Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to run Discovery V4 and V5 on the same port #7213

Merged
merged 115 commits into from
Aug 12, 2024
Merged
Show file tree
Hide file tree
Changes from 101 commits
Commits
Show all changes
115 commits
Select commit Hold shift + click to select a range
c886f9d
Override RLP decoders with ones from plugins (tx receipt only for now…
flcl42 May 2, 2024
9e18fe7
Init decoder in a method; default impl
flcl42 May 2, 2024
d21cae5
fix
deffrian May 2, 2024
28f10e5
Pass the fork timestamp
flcl42 May 3, 2024
0cfb439
Fix params extraction
flcl42 May 3, 2024
df0c9dc
Merge branch 'master' into receipt-decoder-di
flcl42 May 6, 2024
9aa23e4
Fix test
flcl42 May 6, 2024
30fe6dd
Fix typo
flcl42 May 6, 2024
e72a784
Change DI for receipt decoders
flcl42 May 8, 2024
e07a890
Merge master into receipt-decoder-di
flcl42 May 8, 2024
19f6fe8
Fix whitespace
flcl42 May 8, 2024
c458e58
Fix decoders discovery
flcl42 May 8, 2024
4e16b1c
Fix ctor
flcl42 May 8, 2024
ea51ea9
Improve a trace
flcl42 May 8, 2024
74b9c45
x16
flcl42 May 10, 2024
d92ec7a
Merge branch 'master' into fix/ecotone-fee
deffrian May 13, 2024
5c666cb
Improve decoders instantiation
flcl42 May 13, 2024
7862a9d
Improve RegisterDecoder
flcl42 May 13, 2024
06b0007
Refactor rpc modules initialization
deffrian May 13, 2024
8966716
Fix AA
flcl42 May 13, 2024
9482a82
Clean up
flcl42 May 13, 2024
fee4d1e
Merge branch 'receipt-decoder-di' into op-2
flcl42 May 13, 2024
398a037
Merge remote-tracking branch 'origin/fix/ecotone-fee' into op-2
flcl42 May 13, 2024
c88c88d
sendRawTransaction
deffrian May 13, 2024
cac3915
Add discv5
flcl42 May 13, 2024
52bff34
Logs
flcl42 May 14, 2024
8e37997
Hide debug logs
flcl42 May 14, 2024
c861a42
Merge remote-tracking branch 'origin/fix/optimism-send-tx' into op-2
flcl42 May 14, 2024
ba34eab
Fix configs
flcl42 May 15, 2024
1b10a36
Revert "Hide debug logs"
flcl42 May 15, 2024
c5036fb
Enable v4; add more distances
flcl42 May 15, 2024
71acc59
Custom random walk
flcl42 May 15, 2024
849ecda
Fixes
flcl42 May 21, 2024
e3271de
Custom random walk
flcl42 May 22, 2024
682ba62
Merge master into op-2
flcl42 May 22, 2024
6c3f4fe
Fixes
flcl42 May 22, 2024
402a1ad
Refactor interface
deffrian May 23, 2024
bd6a882
Compute fields; fix spec
flcl42 May 28, 2024
183daf2
Deduplicate via generics and inheritence
flcl42 May 29, 2024
8155b96
Merge fix/op-receipts-rpc into discv5
flcl42 May 29, 2024
f89e700
Use custom distances during discovery
flcl42 May 29, 2024
64ae02d
Refactor DiscoveryReport a bit
flcl42 Jun 6, 2024
fd765d4
Merge master into discv5
flcl42 Jun 10, 2024
d01b8ca
Fix merge; remove redundant project fixes; update discv5
flcl42 Jun 12, 2024
f70bbb0
Merge remote-tracking branch 'origin/master' into discv5
flcl42 Jun 12, 2024
c0db854
Temporary fix bouncy castle dep hell
flcl42 Jun 12, 2024
4a32ff2
Fix discv5
flcl42 Jun 12, 2024
d94e7f5
Improve logging
flcl42 Jun 13, 2024
230eba5
Remove redundant pieces
flcl42 Jun 14, 2024
a722376
Merge master into discv5
flcl42 Jun 14, 2024
6a15d4a
Fix build
alexb5dh Jun 19, 2024
d469569
[WIP] Try to delegate messages from Discv5 implementation to `NettyDi…
alexb5dh Jun 19, 2024
d1873e4
[WIP] Use single DotNetty channel for both v4 and v5
alexb5dh Jun 20, 2024
e2e7bdc
Fix discv5
flcl42 Jun 20, 2024
280638e
Compilation fix
flcl42 Jun 20, 2024
5af29a7
Merge remote-tracking branch 'origin/discv5' into discv5-v4-same-port
alexb5dh Jun 20, 2024
cb3ec2e
[WIP] Added multi-version handler
alexb5dh Jun 21, 2024
2a02a22
[WIP] Switch to implementation via Netty handlers
alexb5dh Jun 23, 2024
88f8f87
[WIP] Remove unused classes
alexb5dh Jun 23, 2024
650d494
Formatting fix
alexb5dh Jun 23, 2024
aadfefd
Remove broken `NoVersionMatchDiscoveryHandler`
alexb5dh Jun 24, 2024
239d162
Fix v5 handler dependencies
alexb5dh Jun 24, 2024
88cdb8f
Fix Discovery initialization
alexb5dh Jun 24, 2024
6adc025
Fix v5 configuration
alexb5dh Jun 24, 2024
8eda321
Fixed v5 port reuse
alexb5dh Jun 24, 2024
803cd33
Fix handlers flow
alexb5dh Jun 24, 2024
bc22b5f
Code cleanup
alexb5dh Jun 24, 2024
006bc48
Remove submodule
flcl42 Jun 24, 2024
22a6c20
Fixed packet release
alexb5dh Jun 24, 2024
61c0fa7
Use prod nuget
flcl42 Jun 25, 2024
bea21fa
Merge master into discv5
flcl42 Jun 25, 2024
47a1577
Fix a whitespace
flcl42 Jun 25, 2024
48741b7
Temporary add alias
flcl42 Jun 25, 2024
ca53b05
Remove submodule traces
flcl42 Jun 25, 2024
9e42610
Roll back log change
flcl42 Jun 25, 2024
9b835cf
Merge master into discv5
flcl42 Jun 25, 2024
e3ebf35
Updated services registration
alexb5dh Jun 27, 2024
58695bd
Fixed packet sending
alexb5dh Jun 27, 2024
c7fd532
Fixed Discovery protocol starting
alexb5dh Jun 27, 2024
d3f798c
Fixed empty packet forwarded to V5
alexb5dh Jun 27, 2024
04e1d86
Merge remote-tracking branch 'origin/discv5' into discv5-v4-same-port
alexb5dh Jun 27, 2024
e0b5a27
Update PierTwo.Lantern.Discv5.WireProtocol to preview 4
alexb5dh Jun 27, 2024
6cfa9ed
Configuration update
alexb5dh Jun 28, 2024
7dbc402
Code cleanup
alexb5dh Jun 28, 2024
2425bac
Basic tests
alexb5dh Jul 8, 2024
e318a4d
Remove irrelevant packet-size validation
alexb5dh Jul 8, 2024
6575a65
Simplify `NettyDiscoveryV5Handler` packet-building
alexb5dh Jul 8, 2024
b503432
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 8, 2024
93ccc60
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 11, 2024
e05d8d6
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 15, 2024
43cc437
Refactor discovery initialization code to a separate class
alexb5dh Jul 17, 2024
9ee6e8f
Invoke `NodeAdded`/`NodeRemoved` for v5 also
alexb5dh Jul 18, 2024
ac84438
Enable only v4 by default
alexb5dh Jul 18, 2024
aeb5c7f
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 18, 2024
a068329
Code cleanup
alexb5dh Jul 18, 2024
2ab9329
Do not include externally-added nodes to v5
alexb5dh Jul 18, 2024
d153140
Code cleanup
alexb5dh Jul 18, 2024
f83e0b9
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 25, 2024
a0861aa
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 27, 2024
56102ee
Allow to add nodes to Discovery V5 from external sources
alexb5dh Jul 28, 2024
c95158e
Simplify getting ENR from a node
alexb5dh Jul 28, 2024
3b32c79
Test fix
alexb5dh Jul 31, 2024
51678ed
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Jul 31, 2024
8a53957
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Aug 4, 2024
d8049ff
Use interfaces to simplify testing
alexb5dh Aug 5, 2024
1adf764
Adjust `ActivePeers` check
alexb5dh Aug 5, 2024
ae96529
Added `NettyDiscoveryBaseHandler` and packet size validation
alexb5dh Aug 5, 2024
9366326
v5 tests for messages of invalid size
alexb5dh Aug 6, 2024
700e3c4
Code cleanup
alexb5dh Aug 6, 2024
1107984
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Aug 8, 2024
b29df82
Simplify `IFullDb` dependency
alexb5dh Aug 8, 2024
82bc93e
Limit `NettyDiscoveryV5Handler` inbound buffer
alexb5dh Aug 8, 2024
5de9c47
Replace `IApiWithNetwork` with direct dependencies
alexb5dh Aug 8, 2024
9c971c1
Merge remote-tracking branch 'origin/master' into discv5-v4-same-port
alexb5dh Aug 12, 2024
25d2e11
Code cleanup
alexb5dh Aug 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Nethermind/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
<PackageVersion Include="NUnit.Analyzers" Version="3.9.0" />
<PackageVersion Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageVersion Include="Open.NAT.Core" Version="2.1.0.5" />
<PackageVersion Include="PierTwo.Lantern.Discv5.WireProtocol" Version="1.0.0-preview.3" />
<PackageVersion Include="PierTwo.Lantern.Discv5.WireProtocol" Version="1.0.0-preview.4" />
<PackageVersion Include="Polly" Version="8.4.1" />
<PackageVersion Include="prometheus-net.AspNetCore" Version="8.2.1" />
<PackageVersion Include="Pyroscope" Version="0.8.14" />
Expand Down
3 changes: 0 additions & 3 deletions src/Nethermind/Nethermind.Api/IApiWithNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
using Nethermind.Synchronization;
using Nethermind.Synchronization.Peers;
using Nethermind.Sockets;
using Nethermind.Synchronization.Blocks;
using Nethermind.Synchronization.SnapSync;

namespace Nethermind.Api
{
Expand All @@ -27,7 +25,6 @@ public interface IApiWithNetwork : IApiWithBlockchain

IDisconnectsAnalyzer? DisconnectsAnalyzer { get; set; }
IDiscoveryApp? DiscoveryApp { get; set; }
IDiscoveryApp? DiscoveryV5App { get; set; }
IGrpcServer? GrpcServer { get; set; }
IIPResolver? IpResolver { get; set; }
IMessageSerializationService MessageSerializationService { get; }
Expand Down
1 change: 0 additions & 1 deletion src/Nethermind/Nethermind.Api/NethermindApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,6 @@ public IBlockchainBridge CreateBlockchainBridge()
public IDbFactory? DbFactory { get; set; }
public IDisconnectsAnalyzer? DisconnectsAnalyzer { get; set; }
public IDiscoveryApp? DiscoveryApp { get; set; }
public IDiscoveryApp? DiscoveryV5App { get; set; }
public ISigner? EngineSigner { get; set; }
public ISignerStore? EngineSignerStore { get; set; }
public IEnode? Enode { get; set; }
Expand Down
108 changes: 4 additions & 104 deletions src/Nethermind/Nethermind.Init/Steps/InitializeNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@
using Nethermind.Network.Config;
using Nethermind.Network.Contract.P2P;
using Nethermind.Network.Discovery;
using Nethermind.Network.Discovery.Lifecycle;
using Nethermind.Network.Discovery.Messages;
using Nethermind.Network.Discovery.RoutingTable;
using Nethermind.Network.Discovery.Serializers;
using Nethermind.Network.Dns;
using Nethermind.Network.Enr;
using Nethermind.Network.P2P.Analyzers;
Expand Down Expand Up @@ -64,7 +60,6 @@ public static long Estimate(uint arenaCount, int arenaOrder)
typeof(InitializeBlockchain))]
public class InitializeNetwork : IStep
{
private const string DiscoveryNodesDbPath = "discoveryNodes";
private const string PeersDbPath = "peers";

protected readonly IApiWithNetwork _api;
Expand Down Expand Up @@ -266,8 +261,7 @@ private Task StartDiscovery()
}

if (_logger.IsDebug) _logger.Debug("Starting discovery process.");
_api.DiscoveryApp.Start();
_api.DiscoveryV5App?.Start();
_ = _api.DiscoveryApp.StartAsync();
if (_logger.IsDebug) _logger.Debug("Discovery process started.");
return Task.CompletedTask;
}
Expand Down Expand Up @@ -304,104 +298,12 @@ private void InitDiscovery()
return;
}

IDiscoveryConfig discoveryConfig = _api.Config<IDiscoveryConfig>();

SameKeyGenerator privateKeyProvider = new(_api.NodeKey.Unprotect());
NodeIdResolver nodeIdResolver = new(_api.EthereumEcdsa);

if (discoveryConfig.Discv5Enabled)
{
SimpleFilePublicKeyDb discv5DiscoveryDb = new(
"EnrDiscoveryDB",
DiscoveryNodesDbPath.GetApplicationResourcePath(_api.Config<IInitConfig>().BaseDbPath),
_api.LogManager);

_api.DiscoveryApp = new DiscoveryV5App(privateKeyProvider, _api, _networkConfig, discoveryConfig, discv5DiscoveryDb, _api.LogManager);
_api.DiscoveryApp.Initialize(_api.NodeKey.PublicKey);
return;
}

NodeRecord selfNodeRecord = PrepareNodeRecord(privateKeyProvider);
IDiscoveryMsgSerializersProvider msgSerializersProvider = new DiscoveryMsgSerializersProvider(
_api.MessageSerializationService,
_api.EthereumEcdsa,
privateKeyProvider,
nodeIdResolver);

msgSerializersProvider.RegisterDiscoverySerializers();

NodeDistanceCalculator nodeDistanceCalculator = new(discoveryConfig);

NodeTable nodeTable = new(nodeDistanceCalculator, discoveryConfig, _networkConfig, _api.LogManager);
EvictionManager evictionManager = new(nodeTable, _api.LogManager);

NodeLifecycleManagerFactory nodeLifeCycleFactory = new(
nodeTable,
evictionManager,
_api.NodeStatsManager,
selfNodeRecord,
discoveryConfig,
_api.Timestamper,
_api.LogManager);

// ToDo: DiscoveryDB is registered outside dbProvider - bad
SimpleFilePublicKeyDb discoveryDb = new(
"DiscoveryDB",
DiscoveryNodesDbPath.GetApplicationResourcePath(_api.Config<IInitConfig>().BaseDbPath),
_api.LogManager);

NetworkStorage discoveryStorage = new(
discoveryDb,
_api.LogManager);

DiscoveryManager discoveryManager = new(
nodeLifeCycleFactory,
nodeTable,
discoveryStorage,
discoveryConfig,
_api.LogManager
);

NodesLocator nodesLocator = new(
nodeTable,
discoveryManager,
discoveryConfig,
_api.LogManager);

_api.DiscoveryApp = new DiscoveryApp(
nodesLocator,
discoveryManager,
nodeTable,
_api.MessageSerializationService,
_api.CryptoRandom,
discoveryStorage,
_networkConfig,
discoveryConfig,
_api.Timestamper,
_api.LogManager);

_api.DiscoveryApp = new CompositeDiscoveryApp(_api, _logger, privateKeyProvider);
_api.DiscoveryApp.Initialize(_api.NodeKey.PublicKey);
}

private NodeRecord PrepareNodeRecord(SameKeyGenerator privateKeyProvider)
{
NodeRecord selfNodeRecord = new();
selfNodeRecord.SetEntry(IdEntry.Instance);
selfNodeRecord.SetEntry(new IpEntry(_api.IpResolver!.ExternalIp));
selfNodeRecord.SetEntry(new TcpEntry(_networkConfig.P2PPort));
selfNodeRecord.SetEntry(new UdpEntry(_networkConfig.DiscoveryPort));
selfNodeRecord.SetEntry(new Secp256K1Entry(_api.NodeKey!.CompressedPublicKey));
selfNodeRecord.EnrSequence = 1;
NodeRecordSigner enrSigner = new(_api.EthereumEcdsa, privateKeyProvider.Generate());
enrSigner.Sign(selfNodeRecord);
if (!enrSigner.Verify(selfNodeRecord))
{
throw new NetworkingException("Self ENR initialization failed", NetworkExceptionType.Discovery);
}

return selfNodeRecord;
}

private Task StartSync()
{
if (_api.SyncPeerPool is null) throw new StepDependencyException(nameof(_api.SyncPeerPool));
Expand Down Expand Up @@ -522,7 +424,7 @@ private async Task InitPeer()
_api.BackgroundTaskScheduler,
_api.TxPool,
pooledTxsRequestor,
_api.DiscoveryApp!,
_api.DiscoveryApp,
_api.MessageSerializationService,
_api.RlpxPeer,
_api.NodeStatsManager,
Expand Down Expand Up @@ -555,9 +457,7 @@ private async Task InitPeer()
_api.DisposeStack.Push(new NodeSourceToDiscV4Feeder(enrDiscovery, _api.DiscoveryApp, 50));
}

CompositeNodeSource nodeSources = _api.DiscoveryV5App is null
? new(_api.StaticNodesManager, nodesLoader, enrDiscovery, _api.DiscoveryApp)
: new(_api.StaticNodesManager, nodesLoader, enrDiscovery, _api.DiscoveryApp, _api.DiscoveryV5App);
CompositeNodeSource nodeSources = new(_api.StaticNodesManager, nodesLoader, enrDiscovery, _api.DiscoveryApp);
_api.PeerPool = new PeerPool(nodeSources, _api.NodeStatsManager, peerStorage, _networkConfig, _api.LogManager);
_api.PeerManager = new PeerManager(
_api.RlpxPeer,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
// SPDX-License-Identifier: LGPL-3.0-only

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Handlers.Logging;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
Expand All @@ -16,6 +18,7 @@
using Nethermind.Logging;
using Nethermind.Network.Discovery.Messages;
using Nethermind.Network.Test.Builders;
using Nethermind.Serialization.Rlp;
using Nethermind.Stats.Model;
using NSubstitute;
using NUnit.Framework;
Expand Down Expand Up @@ -171,6 +174,33 @@ public async Task NeighborsSentReceivedTest()
AssertMetrics(210);
}

[Test]
[TestCase("010203")]
alexb5dh marked this conversation as resolved.
Show resolved Hide resolved
public async Task ForwardsUnrecognizedMessageToNextHandler(string msgHex)
{
ResetMetrics();

NeighborsMsg msg = new(_privateKey2.PublicKey, Timestamper.Default.UnixTime.SecondsLong + 1200, new List<Node>().ToArray())
{
FarAddress = _address2
};

await _discoveryHandlers[0].SendMsg(msg);
await SleepWhileWaiting();
_discoveryManagersMocks[1].Received(1).OnIncomingMsg(Arg.Is<DiscoveryMsg>(x => x.MsgType == MsgType.Neighbors));

NeighborsMsg msg2 = new(_privateKey.PublicKey, Timestamper.Default.UnixTime.SecondsLong + 1200, new List<Node>().ToArray())
{
FarAddress = _address,
};

await _discoveryHandlers[1].SendMsg(msg2);
await SleepWhileWaiting();
_discoveryManagersMocks[0].Received(1).OnIncomingMsg(Arg.Is<DiscoveryMsg>(x => x.MsgType == MsgType.Neighbors));

AssertMetrics(210);
}

private static void ResetMetrics()
{
Metrics.DiscoveryBytesSent = Metrics.DiscoveryBytesReceived = 0;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only

using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Embedded;
using DotNetty.Transport.Channels.Sockets;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Nethermind.Serialization.Rlp;
using NSubstitute;
using NUnit.Framework;

namespace Nethermind.Network.Discovery.Test
{
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class NettyDiscoveryV5HandlerTests
{
private EmbeddedChannel _channel;
private NettyDiscoveryV5Handler _handler;

[SetUp]
public void Initialize()
{
_channel = new();
_handler = new(new LoggerFactory());
_handler.InitializeChannel(_channel);
}

[TearDown]
public async Task CleanUp()
{
await _channel.CloseAsync();
}

[Test]
public async Task ForwardsSentMessageToChannel()
{
byte[] data = [1, 2, 3];
var to = IPEndPoint.Parse("127.0.0.1:10001");

await _handler.SendAsync(data, to);

DatagramPacket packet = _channel.ReadOutbound<DatagramPacket>();
packet.Should().NotBeNull();
packet.Content.ReadAllBytesAsArray().Should().BeEquivalentTo(data);
packet.Recipient.Should().Be(to);
}

[Test]
public async Task ForwardsReceivedMessageToReader()
{
byte[] data = [1, 2, 3];
var from = IPEndPoint.Parse("127.0.0.1:10000");
var to = IPEndPoint.Parse("127.0.0.1:10001");

IAsyncEnumerator<UdpReceiveResult> enumerator = _handler.ReadMessagesAsync().GetAsyncEnumerator();

var ctx = Substitute.For<IChannelHandlerContext>();
var packet = new DatagramPacket(Unpooled.WrappedBuffer(data), from, to);

_handler.ChannelRead(ctx, packet);

using var cancellationSource = new CancellationTokenSource(10_000);
(await enumerator.MoveNextAsync(cancellationSource.Token)).Should().BeTrue();
UdpReceiveResult forwardedPacket = enumerator.Current;

forwardedPacket.Should().NotBeNull();
forwardedPacket.Buffer.Should().BeEquivalentTo(data);
forwardedPacket.RemoteEndPoint.Should().Be(from);
}
}
}
Loading