Esempio n. 1
0
 /// <summary>Parameterless constructor for dependency injection.</summary>
 protected PeerConnector(
     IAsyncLoopFactory asyncLoopFactory,
     ILoggerFactory loggerFactory,
     Network network,
     INetworkPeerFactory networkPeerFactory,
     INodeLifetime nodeLifetime,
     NodeSettings nodeSettings,
     IPeerAddressManager peerAddressManager)
 {
     this.asyncLoopFactory   = asyncLoopFactory;
     this.ConnectedPeers     = new NetworkPeerCollection();
     this.loggerFactory      = loggerFactory;
     this.network            = network;
     this.networkPeerFactory = networkPeerFactory;
     this.nodeLifetime       = nodeLifetime;
     this.NodeSettings       = nodeSettings;
     this.peerAddressManager = peerAddressManager;
 }
        public PeerDiscoveryLoop(
            IAsyncLoopFactory asyncLoopFactory,
            Network network,
            NetworkPeerConnectionParameters connectionParameters,
            INodeLifetime nodeLifetime,
            IPeerAddressManager peerAddressManager,
            INetworkPeerFactory networkPeerFactory)
        {
            Guard.NotNull(asyncLoopFactory, nameof(asyncLoopFactory));

            this.asyncLoopFactory   = asyncLoopFactory;
            this.parameters         = connectionParameters;
            this.peerAddressManager = peerAddressManager;
            this.peersToFind        = this.parameters.PeerAddressManagerBehaviour().PeersToDiscover;
            this.network            = network;
            this.nodeLifetime       = nodeLifetime;
            this.networkPeerFactory = networkPeerFactory;
        }
        public PeerAddressManagerBehaviourTests()
        {
            this.extendedLoggerFactory = new ExtendedLoggerFactory();
            this.extendedLoggerFactory.AddConsoleWithFilters();
            this.connectionManagerSettings = new ConnectionManagerSettings(NodeSettings.Default(this.Network));
            this.signals       = new Bitcoin.Signals.Signals(this.extendedLoggerFactory, null);
            this.asyncProvider = new AsyncProvider(this.extendedLoggerFactory, this.signals, new NodeLifetime());

            this.networkPeerFactory = new NetworkPeerFactory(this.Network,
                                                             DateTimeProvider.Default,
                                                             this.extendedLoggerFactory,
                                                             new PayloadProvider().DiscoverPayloads(),
                                                             new SelfEndpointTracker(this.extendedLoggerFactory, this.connectionManagerSettings),
                                                             new Mock <IInitialBlockDownloadState>().Object,
                                                             this.connectionManagerSettings,
                                                             this.asyncProvider,
                                                             new Mock <IPeerAddressManager>().Object);
        }
 public PeerDiscovery(
     IAsyncLoopFactory asyncLoopFactory,
     ILoggerFactory loggerFactory,
     Network network,
     INetworkPeerFactory networkPeerFactory,
     INodeLifetime nodeLifetime,
     NodeSettings nodeSettings,
     IPeerAddressManager peerAddressManager)
 {
     this.asyncLoopFactory   = asyncLoopFactory;
     this.loggerFactory      = loggerFactory;
     this.logger             = this.loggerFactory.CreateLogger(this.GetType().FullName);
     this.peerAddressManager = peerAddressManager;
     this.network            = network;
     this.networkPeerFactory = networkPeerFactory;
     this.nodeLifetime       = nodeLifetime;
     this.nodeSettings       = nodeSettings;
 }
Esempio n. 5
0
        public PeerConnectorAddNode(
            IAsyncProvider asyncProvider,
            IDateTimeProvider dateTimeProvider,
            ILoggerFactory loggerFactory,
            Network network,
            INetworkPeerFactory networkPeerFactory,
            INodeLifetime nodeLifetime,
            NodeSettings nodeSettings,
            ConnectionManagerSettings connectionSettings,
            IPeerAddressManager peerAddressManager,
            ISelfEndpointTracker selfEndpointTracker) :
            base(asyncProvider, dateTimeProvider, loggerFactory, network, networkPeerFactory, nodeLifetime,
                 nodeSettings, connectionSettings, peerAddressManager, selfEndpointTracker)
        {
            this.logger = loggerFactory.CreateLogger(GetType().FullName);

            this.Requirements.RequiredServices = NetworkPeerServices.Nothing;
        }
        public ConnectionManager(IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 INetworkPeerFactory networkPeerFactory,
                                 NodeSettings nodeSettings,
                                 INodeLifetime nodeLifetime,
                                 NetworkPeerConnectionParameters parameters,
                                 IPeerAddressManager peerAddressManager,
                                 IEnumerable <IPeerConnector> peerConnectors,
                                 IPeerDiscovery peerDiscovery,
                                 ISelfEndpointTracker selfEndpointTracker,
                                 ConnectionManagerSettings connectionSettings,
                                 IVersionProvider versionProvider,
                                 INodeStats nodeStats)
        {
            this.connectedPeers      = new NetworkPeerCollection();
            this.dateTimeProvider    = dateTimeProvider;
            this.loggerFactory       = loggerFactory;
            this.logger              = loggerFactory.CreateLogger(this.GetType().FullName);
            this.Network             = network;
            this.NetworkPeerFactory  = networkPeerFactory;
            this.NodeSettings        = nodeSettings;
            this.nodeLifetime        = nodeLifetime;
            this.peerAddressManager  = peerAddressManager;
            this.PeerConnectors      = peerConnectors;
            this.peerDiscovery       = peerDiscovery;
            this.ConnectionSettings  = connectionSettings;
            this.networkPeerDisposer = new NetworkPeerDisposer(this.loggerFactory);
            this.Servers             = new List <NetworkPeerServer>();

            this.Parameters = parameters;
            this.Parameters.ConnectCancellation = this.nodeLifetime.ApplicationStopping;
            this.selfEndpointTracker            = selfEndpointTracker;
            this.versionProvider         = versionProvider;
            this.connectedPeersQueue     = new AsyncQueue <INetworkPeer>(this.OnPeerAdded);
            this.disconnectedPerfCounter = new PerformanceCounter();

            this.Parameters.UserAgent = $"{this.ConnectionSettings.Agent}:{versionProvider.GetVersion()} ({(int)this.NodeSettings.ProtocolVersion})";

            this.Parameters.Version = this.NodeSettings.ProtocolVersion;

            nodeStats.RegisterStats(this.AddComponentStats, StatsType.Component, 1100);
        }
Esempio n. 7
0
        /// <summary>Peer connector initialization as called by the <see cref="Connection.ConnectionManager"/>.</summary>
        public void Initialize(
            IAsyncLoopFactory asyncLoopFactory,
            ILogger logger,
            Network network,
            INetworkPeerFactory networkPeerFactory,
            INodeLifetime nodeLifeTime,
            NodeSettings nodeSettings,
            IPeerAddressManager peerAddressManager)
        {
            this.asyncLoopFactory   = asyncLoopFactory;
            this.ConnectedPeers     = new NetworkPeerCollection();
            this.network            = network;
            this.networkPeerFactory = networkPeerFactory;
            this.nodeLifetime       = nodeLifeTime;
            this.NodeSettings       = nodeSettings;
            this.peerAddressManager = peerAddressManager;

            OnInitialize();
        }
        public CoreNode(NodeRunner runner, NodeBuilder builder, Network network, string configfile)
        {
            this.runner = runner;

            this.State = CoreNodeState.Stopped;
            var pass = Encoders.Hex.EncodeData(RandomUtils.GetBytes(20));

            this.creds  = new NetworkCredential(pass, pass);
            this.Config = Path.Combine(this.runner.DataFolder, configfile);
            this.ConfigParameters.Import(builder.ConfigParameters);
            this.ports = new int[2];
            this.FindPorts(this.ports);

            var loggerFactory = new ExtendedLoggerFactory();

            loggerFactory.AddConsoleWithFilters();

            this.networkPeerFactory = new NetworkPeerFactory(network, DateTimeProvider.Default, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker());
        }
Esempio n. 9
0
 /// <summary>Constructor used by <see cref="Connection.ConnectionManager"/>.</summary>
 public PeerConnectorDiscovery(
     IAsyncLoopFactory asyncLoopFactory,
     ILogger logger,
     Network network,
     INetworkPeerFactory networkPeerFactory,
     INodeLifetime nodeLifeTime,
     NodeSettings nodeSettings,
     NetworkPeerConnectionParameters parameters,
     IPeerAddressManager peerAddressManager)
     :
     base(asyncLoopFactory, logger, network, networkPeerFactory, nodeLifeTime, nodeSettings, parameters, peerAddressManager)
 {
     this.GroupSelector          = WellKnownPeerConnectorSelectors.ByNetwork;
     this.MaximumNodeConnections = 8;
     this.Requirements           = new NetworkPeerRequirement
     {
         MinVersion       = nodeSettings.ProtocolVersion,
         RequiredServices = NetworkPeerServices.Network
     };
 }
Esempio n. 10
0
        /// <summary>
        /// Initializes an instance of the object for outbound network peers.
        /// </summary>
        /// <param name="peerEndPoint">IP address and port on the side of the peer.</param>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        /// <param name="selfEndpointTracker">Tracker for endpoints known to be self.</param>
        /// <param name="onDisconnected">Callback that is invoked when peer has finished disconnecting, or <c>null</c> when no notification after the disconnection is required.</param>
        public NetworkPeer(IPEndPoint peerEndPoint,
                           Network network,
                           NetworkPeerConnectionParameters parameters,
                           INetworkPeerFactory networkPeerFactory,
                           IDateTimeProvider dateTimeProvider,
                           ILoggerFactory loggerFactory,
                           ISelfEndpointTracker selfEndpointTracker,
                           Action <INetworkPeer> onDisconnected = null)
            : this(false, peerEndPoint, network, parameters, dateTimeProvider, loggerFactory, selfEndpointTracker, onDisconnected)
        {
            var client = new TcpClient(AddressFamily.InterNetworkV6);

            client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            client.Client.ReceiveBufferSize = parameters.ReceiveBufferSize;
            client.Client.SendBufferSize    = parameters.SendBufferSize;

            this.Connection = networkPeerFactory.CreateNetworkPeerConnection(this, client, this.ProcessMessageAsync);

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{this.Connection.Id}-{peerEndPoint}] ");
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes an instance of the object for inbound network peers with already established connection.
        /// </summary>
        /// <param name="peerEndPoint">IP address and port on the side of the peer.</param>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
        /// <param name="client">Already connected network client.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        /// <param name="selfEndpointTracker">Tracker for endpoints known to be self.</param>
        /// <param name="onDisconnected">Callback that is invoked when peer has finished disconnecting, or <c>null</c> when no notification after the disconnection is required.</param>
        public NetworkPeer(IPEndPoint peerEndPoint,
                           Network network,
                           NetworkPeerConnectionParameters parameters,
                           TcpClient client,
                           IDateTimeProvider dateTimeProvider,
                           INetworkPeerFactory networkPeerFactory,
                           ILoggerFactory loggerFactory,
                           ISelfEndpointTracker selfEndpointTracker,
                           Action <INetworkPeer> onDisconnected = null)
            : this(true, peerEndPoint, network, parameters, dateTimeProvider, loggerFactory, selfEndpointTracker, onDisconnected)
        {
            this.Connection = networkPeerFactory.CreateNetworkPeerConnection(this, client, this.ProcessMessageAsync);

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{this.Connection.Id}-{peerEndPoint}] ");

            this.logger.LogTrace("Connected to peer '{0}'.", this.PeerEndPoint);

            this.InitDefaultBehaviors(this.ConnectionParameters);
            this.Connection.StartReceiveMessages();
        }
Esempio n. 12
0
 /// <summary>Parameterless constructor for dependency injection.</summary>
 protected PeerConnector(
     IAsyncLoopFactory asyncLoopFactory,
     IDateTimeProvider dateTimeProvider,
     ILoggerFactory loggerFactory,
     Network network,
     INetworkPeerFactory networkPeerFactory,
     INodeLifetime nodeLifetime,
     NodeSettings nodeSettings,
     IPeerAddressManager peerAddressManager)
 {
     this.asyncLoopFactory   = asyncLoopFactory;
     this.ConnectedPeers     = new NetworkPeerCollection();
     this.dateTimeProvider   = dateTimeProvider;
     this.loggerFactory      = loggerFactory;
     this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network            = network;
     this.networkPeerFactory = networkPeerFactory;
     this.nodeLifetime       = nodeLifetime;
     this.NodeSettings       = nodeSettings;
     this.peerAddressManager = peerAddressManager;
 }
        /// <summary>
        /// Initializes instance of a network peer server.
        /// </summary>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="localEndPoint">IP address and port to listen on.</param>
        /// <param name="externalEndPoint">IP address and port that the server is reachable from the Internet on.</param>
        /// <param name="version">Version of the network protocol that the server should run.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="initialBlockDownloadState">Provider of IBD state.</param>
        /// <param name="connectionManagerSettings">Configuration related to incoming and outgoing connections.</param>
        public NetworkPeerServer(Network network,
                                 IPEndPoint localEndPoint,
                                 IPEndPoint externalEndPoint,
                                 ProtocolVersion version,
                                 ILoggerFactory loggerFactory,
                                 INetworkPeerFactory networkPeerFactory,
                                 IInitialBlockDownloadState initialBlockDownloadState,
                                 ConnectionManagerSettings connectionManagerSettings,
                                 IAsyncProvider asyncProvider,
                                 IPeerAddressManager peerAddressManager,
                                 IDateTimeProvider dateTimeProvider)
        {
            this.logger                    = loggerFactory.CreateLogger(this.GetType().FullName, $"[{localEndPoint}] ");
            this.signals                   = asyncProvider.Signals;
            this.networkPeerFactory        = networkPeerFactory;
            this.networkPeerDisposer       = new NetworkPeerDisposer(loggerFactory, asyncProvider);
            this.initialBlockDownloadState = initialBlockDownloadState;
            this.connectionManagerSettings = connectionManagerSettings;
            this.peerAddressManager        = peerAddressManager;
            this.dateTimeProvider          = dateTimeProvider;

            this.InboundNetworkPeerConnectionParameters = new NetworkPeerConnectionParameters();

            this.LocalEndpoint    = Utils.EnsureIPv6(localEndPoint);
            this.ExternalEndpoint = Utils.EnsureIPv6(externalEndPoint);

            this.Network = network;
            this.Version = version;

            this.serverCancel = new CancellationTokenSource();

            this.tcpListener = new TcpListener(this.LocalEndpoint);
            this.tcpListener.Server.LingerState = new LingerOption(true, 0);
            this.tcpListener.Server.NoDelay     = true;
            this.tcpListener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

            this.acceptTask = Task.CompletedTask;

            this.logger.LogDebug("Network peer server ready to listen on '{0}'.", this.LocalEndpoint);
        }
        public ConnectionManager(IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 INetworkPeerFactory networkPeerFactory,
                                 NodeSettings nodeSettings,
                                 INodeLifetime nodeLifetime,
                                 NetworkPeerConnectionParameters parameters,
                                 IPeerAddressManager peerAddressManager,
                                 IEnumerable <IPeerConnector> peerConnectors,
                                 IPeerDiscovery peerDiscovery,
                                 ISelfEndpointTracker selfEndpointTracker,
                                 ConnectionManagerSettings connectionSettings,
                                 IVersionProvider versionProvider)
        {
            this.connectedPeers      = new NetworkPeerCollection();
            this.dateTimeProvider    = dateTimeProvider;
            this.loggerFactory       = loggerFactory;
            this.logger              = loggerFactory.CreateLogger(this.GetType().FullName);
            this.Network             = network;
            this.NetworkPeerFactory  = networkPeerFactory;
            this.NodeSettings        = nodeSettings;
            this.nodeLifetime        = nodeLifetime;
            this.peerAddressManager  = peerAddressManager;
            this.PeerConnectors      = peerConnectors;
            this.peerDiscovery       = peerDiscovery;
            this.ConnectionSettings  = connectionSettings;
            this.networkPeerDisposer = new NetworkPeerDisposer(this.loggerFactory);
            this.Servers             = new List <NetworkPeerServer>();

            this.Parameters = parameters;
            this.Parameters.ConnectCancellation = this.nodeLifetime.ApplicationStopping;
            this.selfEndpointTracker            = selfEndpointTracker;
            this.versionProvider = versionProvider;

            this.Parameters.UserAgent = $"{this.NodeSettings.Agent}:{versionProvider.GetVersion()}";

            this.Parameters.Version = this.NodeSettings.ProtocolVersion;

            this.downloads = new Dictionary <INetworkPeer, PerformanceSnapshot>();
        }
Esempio n. 15
0
        /// <summary>
        /// Initializes instance of a network peer server.
        /// </summary>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="ipAddress">Address of the local interface to listen on, or <c>null</c> to listen on all available interfaces.</param>
        /// <param name="internalPort">Port on which the server will listen, or -1 to use the default port for the selected network.</param>
        /// <param name="version">Version of the network protocol that the server should run.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        public NetworkPeerServer(Network network, IPEndPoint localEndpoint, IPEndPoint externalEndpoint, ProtocolVersion version, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory, INetworkPeerFactory networkPeerFactory)
        {
            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{localEndpoint}] ");
            this.logger.LogTrace("({0}:{1},{2}:{3},{4}:{5})", nameof(network), network, nameof(localEndpoint), localEndpoint, nameof(externalEndpoint), externalEndpoint, nameof(version), version);

            this.dateTimeProvider   = dateTimeProvider;
            this.networkPeerFactory = networkPeerFactory;

            this.AllowLocalPeers = true;
            this.InboundNetworkPeerConnectionParameters = new NetworkPeerConnectionParameters();

            this.LocalEndpoint    = Utils.EnsureIPv6(localEndpoint);
            this.ExternalEndpoint = Utils.EnsureIPv6(externalEndpoint);

            this.MaxConnections = 125;
            this.Network        = network;
            this.Version        = version;

            this.listener        = new EventLoopMessageListener <IncomingMessage>(this.ProcessMessageAsync);
            this.messageProducer = new MessageProducer <IncomingMessage>();
            this.messageProducer.AddMessageListener(this.listener);

            this.ConnectedNetworkPeers = new NetworkPeerCollection();
            this.ConnectedNetworkPeers.MessageProducer.AddMessageListener(this.listener);

            this.serverCancel = new CancellationTokenSource();

            this.tcpListener = new TcpListener(this.LocalEndpoint);
            this.tcpListener.Server.LingerState = new LingerOption(true, 0);
            this.tcpListener.Server.NoDelay     = true;
            this.tcpListener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

            this.clientsById = new ConcurrentDictionary <int, NetworkPeerClient>();
            this.acceptTask  = Task.CompletedTask;

            this.logger.LogTrace("Network peer server ready to listen on '{0}'.", this.LocalEndpoint);

            this.logger.LogTrace("(-)");
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes instance of a network peer server.
        /// </summary>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="localEndPoint">IP address and port to listen on.</param>
        /// <param name="externalEndPoint">IP address and port that the server is reachable from the Internet on.</param>
        /// <param name="version">Version of the network protocol that the server should run.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="initialBlockDownloadState">Provider of IBD state.</param>
        /// <param name="connectionManagerSettings">Configuration related to incoming and outgoing connections.</param>
        public NetworkPeerServer(Network network,
                                 IPEndPoint localEndPoint,
                                 IPEndPoint externalEndPoint,
                                 ProtocolVersion version,
                                 ILoggerFactory loggerFactory,
                                 INetworkPeerFactory networkPeerFactory,
                                 IInitialBlockDownloadState initialBlockDownloadState,
                                 ConnectionManagerSettings connectionManagerSettings)
        {
            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{localEndPoint}] ");
            this.logger.LogTrace("({0}:{1},{2}:{3},{4}:{5})", nameof(network), network, nameof(localEndPoint), localEndPoint, nameof(externalEndPoint), externalEndPoint, nameof(version), version);

            this.networkPeerFactory        = networkPeerFactory;
            this.networkPeerDisposer       = new NetworkPeerDisposer(loggerFactory);
            this.initialBlockDownloadState = initialBlockDownloadState;
            this.connectionManagerSettings = connectionManagerSettings;

            this.InboundNetworkPeerConnectionParameters = new NetworkPeerConnectionParameters();

            this.LocalEndpoint    = Utils.EnsureIPv6(localEndPoint);
            this.ExternalEndpoint = Utils.EnsureIPv6(externalEndPoint);

            this.Network = network;
            this.Version = version;

            this.serverCancel = new CancellationTokenSource();

            this.tcpListener = new TcpListener(this.LocalEndpoint);
            this.tcpListener.Server.LingerState = new LingerOption(true, 0);
            this.tcpListener.Server.NoDelay     = true;
            this.tcpListener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

            this.acceptTask = Task.CompletedTask;

            this.logger.LogTrace("Network peer server ready to listen on '{0}'.", this.LocalEndpoint);

            this.logger.LogTrace("(-)");
        }
Esempio n. 17
0
        /// <summary>Constructor used by <see cref="Connection.ConnectionManager"/>.</summary>
        protected PeerConnector(
            IAsyncLoopFactory asyncLoopFactory,
            ILogger logger,
            Network network,
            INetworkPeerFactory networkPeerFactory,
            INodeLifetime nodeLifeTime,
            NodeSettings nodeSettings,
            NetworkPeerConnectionParameters parameters,
            IPeerAddressManager peerAddressManager)
        {
            this.asyncLoopFactory   = asyncLoopFactory;
            this.ConnectedPeers     = new NetworkPeerCollection();
            this.network            = network;
            this.networkPeerFactory = networkPeerFactory;
            this.nodeLifetime       = nodeLifeTime;
            this.NodeSettings       = nodeSettings;
            this.parentParameters   = parameters;
            this.peerAddressManager = peerAddressManager;

            this.CurrentParameters = this.parentParameters.Clone();
            this.CurrentParameters.TemplateBehaviors.Add(new PeerConnectorBehaviour(this));
            this.CurrentParameters.ConnectCancellation = this.nodeLifetime.ApplicationStopping;
        }
        /// <summary>
        /// Initializes instance of a network peer server.
        /// </summary>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="version">Version of the network protocol that the server should run.</param>
        /// <param name="internalPort">Port on which the server will listen, or -1 to use the default port for the selected network.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        public NetworkPeerServer(Network network, ProtocolVersion version, int internalPort, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory, INetworkPeerFactory networkPeerFactory)
        {
            internalPort = internalPort == -1 ? network.DefaultPort : internalPort;

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{internalPort}] ");
            this.logger.LogTrace("({0}:{1},{2}:{3},{4}:{5})", nameof(network), network, nameof(version), version, nameof(internalPort), internalPort);

            this.dateTimeProvider   = dateTimeProvider;
            this.networkPeerFactory = networkPeerFactory;

            this.AllowLocalPeers = true;
            this.InboundNetworkPeerConnectionParameters = new NetworkPeerConnectionParameters();

            this.localEndpoint = new IPEndPoint(IPAddress.Parse("0.0.0.0").MapToIPv6Ex(), internalPort);

            this.MaxConnections   = 125;
            this.Network          = network;
            this.externalEndpoint = new IPEndPoint(this.localEndpoint.Address, this.Network.DefaultPort);
            this.Version          = version;

            var listener = new EventLoopMessageListener <IncomingMessage>(ProcessMessage);

            this.messageProducer.AddMessageListener(listener);
            this.OwnResource(listener);

            this.ConnectedNetworkPeers          = new NetworkPeerCollection();
            this.ConnectedNetworkPeers.Added   += Peers_PeerAdded;
            this.ConnectedNetworkPeers.Removed += Peers_PeerRemoved;
            this.ConnectedNetworkPeers.MessageProducer.AddMessageListener(listener);

            this.AllMessages = new MessageProducer <IncomingMessage>();

            this.logger.LogTrace("Network peer server ready to listen on '{0}'.", this.LocalEndpoint);

            this.logger.LogTrace("(-)");
        }
Esempio n. 19
0
        /// <summary>
        /// Initializes an instance of the object for outbound network peers.
        /// </summary>
        /// <param name="peerAddress">Information about the peer including its network address, protocol version, time of last contact.</param>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        public NetworkPeer(NetworkAddress peerAddress, Network network, NetworkPeerConnectionParameters parameters, INetworkPeerFactory networkPeerFactory, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory)
            : this(false, peerAddress, network, parameters, dateTimeProvider, loggerFactory)
        {
            NetworkPeerClient client = networkPeerFactory.CreateNetworkPeerClient(parameters);

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{client.Id}-{peerAddress.Endpoint}] ");
            this.logger.LogTrace("()");

            this.Connection = new NetworkPeerConnection(this, client, this.dateTimeProvider, this.loggerFactory);

            this.logger.LogTrace("(-)");
        }
Esempio n. 20
0
        /// <summary>
        /// Initializes an instance of the object for inbound network peers with already established connection.
        /// </summary>
        /// <param name="peerEndPoint">IP address and port on the side of the peer.</param>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
        /// <param name="client">Already connected network client.</param>
        /// <param name="peerVersion">Version message payload received from the peer.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        public NetworkPeer(IPEndPoint peerEndPoint, Network network, NetworkPeerConnectionParameters parameters, TcpClient client, IDateTimeProvider dateTimeProvider, INetworkPeerFactory networkPeerFactory, ILoggerFactory loggerFactory)
            : this(true, peerEndPoint, network, parameters, dateTimeProvider, loggerFactory)
        {
            this.Connection = networkPeerFactory.CreateNetworkPeerConnection(this, client, this.ProcessMessageAsync);

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{this.Connection.Id}-{peerEndPoint}] ");
            this.logger.LogTrace("()");

            this.RemoteSocketEndpoint = this.PeerEndPoint;
            this.RemoteSocketAddress  = this.RemoteSocketEndpoint.Address;
            this.RemoteSocketPort     = this.RemoteSocketEndpoint.Port;

            this.ConnectedAt = this.dateTimeProvider.GetUtcNow();

            this.logger.LogTrace("Connected to peer '{0}'.", this.PeerEndPoint);
            this.State = NetworkPeerState.Connected;

            this.InitDefaultBehaviors(this.Parameters);
            this.Connection.StartReceiveMessages();

            this.logger.LogTrace("(-)");
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes an instance of the object for outbound network peers.
        /// </summary>
        /// <param name="peerAddress">Information about the peer including its network address, protocol version, time of last contact.</param>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        public NetworkPeer(NetworkAddress peerAddress, Network network, NetworkPeerConnectionParameters parameters, INetworkPeerFactory networkPeerFactory, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory)
            : this(false, peerAddress, network, parameters, dateTimeProvider, loggerFactory)
        {
            TcpClient client = new TcpClient(AddressFamily.InterNetworkV6);

            client.Client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            client.Client.ReceiveBufferSize = parameters.ReceiveBufferSize;
            client.Client.SendBufferSize    = parameters.SendBufferSize;

            this.Connection = networkPeerFactory.CreateNetworkPeerConnection(this, client, this.ProcessMessageAsync);

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName, $"[{this.Connection.Id}-{peerAddress.Endpoint}] ");
            this.logger.LogTrace("()");

            this.logger.LogTrace("(-)");
        }
Esempio n. 22
0
        public TestContext()
        {
            this.Network = KnownNetworks.RegTest;

            this.chainIndexer     = new ChainIndexer(this.Network);
            this.dateTimeProvider = new DateTimeProvider();
            this.hashStore        = new InvalidBlockHashStore(this.dateTimeProvider);

            this.coinView        = new TestInMemoryCoinView(this.chainIndexer.Tip.HashBlock);
            this.HeaderValidator = new Mock <IHeaderValidator>();
            this.HeaderValidator.Setup(hv => hv.ValidateHeader(It.IsAny <ChainedHeader>())).Returns(new ValidationContext());

            this.nodeLifetime = new NodeLifetime();
            this.ibd          = new Mock <IInitialBlockDownloadState>();
            this.BlockPuller  = new Mock <IBlockPuller>();

            this.BlockPuller.Setup(b => b.Initialize(It.IsAny <BlockPuller.OnBlockDownloadedCallback>()))
            .Callback <BlockPuller.OnBlockDownloadedCallback>((d) => { this.blockPullerBlockDownloadCallback = d; });
            this.BlockStore  = new Mock <IBlockStore>();
            this.checkpoints = new Mock <ICheckpoints>();
            this.ChainState  = new Mock <IChainState>();

            string[] param = new string[] { };
            this.nodeSettings      = new NodeSettings(this.Network, args: param);
            this.ConsensusSettings = new ConsensusSettings(this.nodeSettings);

            this.loggerFactory = this.nodeSettings.LoggerFactory;

            this.nodeStats = new NodeStats(this.dateTimeProvider, this.loggerFactory);

            var connectionSettings = new ConnectionManagerSettings(this.nodeSettings);

            this.selfEndpointTracker       = new SelfEndpointTracker(this.loggerFactory, connectionSettings);
            this.Network.Consensus.Options = new ConsensusOptions();

            this.signals       = new Bitcoin.Signals.Signals(this.loggerFactory, null);
            this.asyncProvider = new AsyncProvider(this.loggerFactory, this.signals, this.nodeLifetime);

            // Dont check PoW of a header in this test.
            this.Network.Consensus.ConsensusRules.HeaderValidationRules.RemoveAll(x => x.GetType() == typeof(CheckDifficultyPowRule));

            this.ChainedHeaderTree = new ChainedHeaderTree(
                this.Network,
                this.loggerFactory,
                this.HeaderValidator.Object,
                this.checkpoints.Object,
                this.ChainState.Object,
                this.FinalizedBlockMock.Object,
                this.ConsensusSettings,
                this.hashStore);

            this.peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, this.nodeSettings.DataFolder, this.loggerFactory, this.selfEndpointTracker);

            this.networkPeerFactory = new NetworkPeerFactory(this.Network,
                                                             this.dateTimeProvider,
                                                             this.loggerFactory, new PayloadProvider().DiscoverPayloads(),
                                                             this.selfEndpointTracker,
                                                             this.ibd.Object,
                                                             new ConnectionManagerSettings(this.nodeSettings),
                                                             this.asyncProvider,
                                                             this.peerAddressManager);

            var peerDiscovery = new PeerDiscovery(this.asyncProvider, this.loggerFactory, this.Network, this.networkPeerFactory, this.nodeLifetime, this.nodeSettings, this.peerAddressManager);

            this.connectionManager = new ConnectionManager(this.dateTimeProvider, this.loggerFactory, this.Network, this.networkPeerFactory, this.nodeSettings,
                                                           this.nodeLifetime, new NetworkPeerConnectionParameters(), this.peerAddressManager, new IPeerConnector[] { },
                                                           peerDiscovery, this.selfEndpointTracker, connectionSettings, new VersionProvider(), this.nodeStats, this.asyncProvider);

            this.deployments = new NodeDeployments(this.Network, this.chainIndexer);

            this.consensusRules = new PowConsensusRuleEngine(this.Network, this.loggerFactory, this.dateTimeProvider, this.chainIndexer, this.deployments, this.ConsensusSettings,
                                                             this.checkpoints.Object, this.coinView, this.ChainState.Object, this.hashStore, this.nodeStats, this.asyncProvider, new ConsensusRulesContainer());

            this.consensusRules.SetupRulesEngineParent();

            var tree = new ChainedHeaderTree(this.Network, this.loggerFactory, this.HeaderValidator.Object, this.checkpoints.Object,
                                             this.ChainState.Object, this.FinalizedBlockMock.Object, this.ConsensusSettings, this.hashStore);

            this.PartialValidator = new Mock <IPartialValidator>();
            this.FullValidator    = new Mock <IFullValidator>();

            this.peerBanning = new PeerBanning(this.connectionManager, this.loggerFactory, this.dateTimeProvider, this.peerAddressManager);

            this.IntegrityValidator.Setup(i => i.VerifyBlockIntegrity(It.IsAny <ChainedHeader>(), It.IsAny <Block>()))
            .Returns(new ValidationContext());

            ConsensusManager consensusManager = new ConsensusManager(tree, this.Network, this.loggerFactory, this.ChainState.Object, this.IntegrityValidator.Object,
                                                                     this.PartialValidator.Object, this.FullValidator.Object, this.consensusRules,
                                                                     this.FinalizedBlockMock.Object, this.signals, this.peerBanning, this.ibd.Object, this.chainIndexer,
                                                                     this.BlockPuller.Object, this.BlockStore.Object, this.connectionManager, this.nodeStats, this.nodeLifetime, this.ConsensusSettings, this.dateTimeProvider);

            this.TestConsensusManager = new TestConsensusManager(consensusManager);
        }
Esempio n. 23
0
        /// <summary>
        /// Initializes an instance of the object for outbound network peers.
        /// </summary>
        /// <param name="peerAddress">Information about the peer including its network address, protocol version, time of last contact.</param>
        /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
        /// <param name="parameters">Various settings and requirements related to how the connections with peers are going to be established, or <c>null</c> to use default parameters.</param>
        /// <param name="networkPeerFactory">Factory for creating P2P network peers.</param>
        /// <param name="dateTimeProvider">Provider of time functions.</param>
        /// <param name="loggerFactory">Factory for creating loggers.</param>
        public NetworkPeer(NetworkAddress peerAddress, Network network, NetworkPeerConnectionParameters parameters, INetworkPeerFactory networkPeerFactory, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory)
            : this(false, peerAddress, network, parameters, dateTimeProvider, loggerFactory)
        {
            this.logger.LogTrace("()");

            NetworkPeerClient client = networkPeerFactory.CreateNetworkPeerClient(parameters);

            this.Connection = new NetworkPeerConnection(this, client, this.dateTimeProvider, this.loggerFactory);
            this.ConnectAsync(parameters.ConnectCancellation).GetAwaiter().GetResult();

            this.InitDefaultBehaviors(parameters);
            this.Connection.StartReceiveMessages();

            this.logger.LogTrace("(-)");
        }