Example #1
0
        private async Task <bool> StartConnecting()
        {
            return(await Task <bool> .Factory.StartNew(() =>
            {
                try
                {
                    NodeConnectionParameters parameters = new NodeConnectionParameters();
                    //So we find nodes faster
                    parameters.TemplateBehaviors.Add(new AddressManagerBehavior(GetAddressManager()));
                    //So we don't have to load the chain each time we start
                    parameters.TemplateBehaviors.Add(new ChainBehavior(GetChain()));
                    //Tracker knows which scriptPubKey and outpoints to track
                    parameters.TemplateBehaviors.Add(new TrackerBehavior(GetTracker()));

                    var nodeReq = new NodeRequirement()
                    {
                        RequiredServices = NodeServices.Network
                    };
                    _group = new NodesGroup(_wallet.NetworkChoice, parameters, nodeReq);
                    _group.MaximumNodeConnection = MAX_NUM_CONNECTIONS;
                    _group.Connect();
                    _connectionparameters = parameters;
                    return true;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }));
        }
 public KnoledgeNodesGroup(
     Network network,
     NodeConnectionParameters connectionParameters = null,
     NodeRequirement requirements = null)
     : base(network, connectionParameters, requirements)
 {
 }
Example #3
0
        private async void StartConnecting()
        {
            await Task.Factory.StartNew(() =>
            {
                NodeConnectionParameters parameters = new NodeConnectionParameters();
                //So we find nodes faster
                parameters.TemplateBehaviors.Add(new AddressManagerBehavior(this.GetAddressManager()));
                //So we don't have to load the chain each time we start
                parameters.TemplateBehaviors.Add(new ChainBehavior(this.GetChain()));
                //Tracker knows which scriptPubKey and outpoints to track
                parameters.TemplateBehaviors.Add(new TrackerBehavior(this.GetTracker()));
                var nodeReq = new NodeRequirement()
                {
                    RequiredServices = NodeServices.Network
                };
                _group = new NodesGroup(_wallet.NetworkChoice, parameters, nodeReq);
                _group.MaximumNodeConnection = MAX_NUM_CONNECTIONS;
                _group.Connect();
                _connectionparameters = parameters;
            });

            _wallet.Configure(_group);
            _wallet.Connect();
            _wallet.Connected = true;

            PeriodicKick();
            PeriodicSave();
        }
        protected BlockPuller(ConcurrentChain chain, IReadOnlyNodesCollection nodes, ProtocolVersion protocolVersion)
        {
            this.Chain                   = chain;
            this.Nodes                   = nodes;
            this.DownloadedBlocks        = new ConcurrentDictionary <uint256, DownloadedBlock>();
            this.pendingInventoryVectors = new ConcurrentBag <uint256>();
            this.map = new ConcurrentDictionary <uint256, BlockPullerBehavior>();

            // set the default requirements
            this.requirements = new NodeRequirement
            {
                MinVersion       = protocolVersion,
                RequiredServices = NodeServices.Network
            };
        }
Example #5
0
		public NodesGroup(
			Network network,
			NodeConnectionParameters connectionParameters = null,
			NodeRequirement requirements = null)
		{
			AllowSameGroup = false;
			MaximumNodeConnection = 8;
			_Network = network;
			cs = new object();
			_ConnectedNodes = new NodesCollection();
			_ConnectionParameters = connectionParameters ?? new NodeConnectionParameters();
			_ConnectionParameters = _ConnectionParameters.Clone();
			_Requirements = requirements ?? new NodeRequirement();
			_Disconnect = new CancellationTokenSource();
		}
Example #6
0
 public NodesGroup(
     Network network,
     NodeConnectionParameters connectionParameters = null,
     NodeRequirement requirements = null)
 {
     AllowSameGroup        = false;
     MaximumNodeConnection = 8;
     _network                 = network;
     _cs                      = new object();
     ConnectedNodes           = new NodesCollection();
     NodeConnectionParameters = connectionParameters ?? new NodeConnectionParameters();
     NodeConnectionParameters = NodeConnectionParameters.Clone();
     Requirements             = requirements ?? new NodeRequirement();
     _disconnect              = new CancellationTokenSource();
 }
Example #7
0
        public void VersionHandshake(NodeRequirement requirements, CancellationToken cancellationToken = default(CancellationToken))
        {
            requirements = requirements ?? new NodeRequirement();
            using (var listener = CreateListener()
                                  .Where(p => p.Message.Payload is Version ||
                                         p.Message.Payload is RejectPayload ||
                                         p.Message.Payload is VerAckPayload))
            {
                SendMessageAsync(MyVersion);
                var payload = listener.ReceivePayload <Payload>(cancellationToken);
                if (payload is RejectPayload)
                {
                    throw new ProtocolException("Handshake rejected : " + ((RejectPayload)payload).Reason);
                }
                var version = (VersionPayload)payload;
                _PeerVersion = version;
                SetVersion(Math.Min(MyVersion.Version, version.Version));

                if (!version.AddressReceiver.Address.Equals(MyVersion.AddressFrom.Address))
                {
                    Logs.NodeServer.LogWarning("Different external address detected by the node {addressReceiver} instead of {addressFrom}", version.AddressReceiver.Address, MyVersion.AddressFrom.Address);
                }

                if (ProtocolCapabilities.PeerTooOld)
                {
                    Logs.NodeServer.LogWarning("Outdated version {version} disconnecting", version.Version);
                    Disconnect("Outdated version");
                    return;
                }

                if (!requirements.Check(version, ProtocolCapabilities))
                {
                    Disconnect("The peer does not support the required services requirement");
                    return;
                }

                SendMessageAsync(new VerAckPayload());
                listener.ReceivePayload <VerAckPayload>(cancellationToken);
                State = NodeState.HandShaked;
                if (Advertize && MyVersion.AddressFrom.Address.IsRoutable(true))
                {
                    SendMessageAsync(new AddrPayload(new NetworkAddress(MyVersion.AddressFrom)
                    {
                        Time = DateTimeOffset.UtcNow
                    }));
                }
            }
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the object having a chain of block headers and a list of available nodes.
        /// </summary>
        /// <param name="chain">Chain of block headers.</param>
        /// <param name="nodes">Network peers of the node.</param>
        /// <param name="protocolVersion">Version of the protocol that the node supports.</param>
        /// <param name="loggerFactory">Factory to be used to create logger for the puller.</param>
        protected BlockPuller(ConcurrentChain chain, IReadOnlyNodesCollection nodes, ProtocolVersion protocolVersion, ILoggerFactory loggerFactory)
        {
            this.Chain                   = chain;
            this.Nodes                   = nodes;
            this.logger                  = loggerFactory.CreateLogger(this.GetType().FullName);
            this.downloadedBlocks        = new Dictionary <uint256, DownloadedBlock>();
            this.pendingInventoryVectors = new Queue <uint256>();
            this.assignedBlockTasks      = new Dictionary <uint256, BlockPullerBehavior>();
            this.peerQuality             = new QualityScore(QualityScoreHistoryLength, loggerFactory);

            // Set the default requirements.
            this.requirements = new NodeRequirement
            {
                MinVersion       = protocolVersion,
                RequiredServices = NodeServices.Network
            };
        }
Example #9
0
        private IPeerConnector CreatePeerConnector(
            NodeConnectionParameters parameters,
            NodeServices requiredServices,
            Func <IPEndPoint, byte[]> peerSelector,
            PeerIntroductionType peerIntroductionType,
            int?maximumNodeConnections = 8)
        {
            this.logger.LogTrace("({0}:{1})", nameof(requiredServices), requiredServices);

            var nodeRequirement = new NodeRequirement
            {
                MinVersion       = this.NodeSettings.ProtocolVersion,
                RequiredServices = requiredServices,
            };

            var peerConnector = new PeerConnector(this.Network, this.nodeLifetime, parameters, nodeRequirement, peerSelector, this.asyncLoopFactory, this.peerAddressManager, peerIntroductionType)
            {
                MaximumNodeConnections = maximumNodeConnections.Value
            };

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

            return(peerConnector);
        }
        /// <summary>Constructor used by dependency injection.</summary>
        internal PeerConnector(Network network,
                               INodeLifetime nodeLifeTime,
                               NodeConnectionParameters parameters,
                               NodeRequirement nodeRequirements,
                               Func <IPEndPoint, byte[]> groupSelector,
                               IAsyncLoopFactory asyncLoopFactory,
                               IPeerAddressManager peerAddressManager,
                               PeerIntroductionType peerIntroductionType)
        {
            this.asyncLoopFactory       = asyncLoopFactory;
            this.ConnectedPeers         = new NodesCollection();
            this.groupSelector          = groupSelector;
            this.MaximumNodeConnections = 8;
            this.network              = network;
            this.nodeLifetime         = nodeLifeTime;
            this.parentParameters     = parameters;
            this.peerAddressManager   = peerAddressManager;
            this.peerIntroductionType = peerIntroductionType;
            this.Requirements         = nodeRequirements;

            this.currentParameters = this.parentParameters.Clone();
            this.currentParameters.TemplateBehaviors.Add(new PeerConnectorBehaviour(this));
            this.currentParameters.ConnectCancellation = this.nodeLifetime.ApplicationStopping;
        }
Example #11
0
        public void CanHandshakeRestrictNodes()
        {
            using (var builder = NodeBuilderEx.Create())
            {
                var node    = builder.CreateNode(true);
                var manager = new AddressManager();
                manager.Add(new NetworkAddress(node.NodeEndpoint), IPAddress.Loopback);

                var nodesRequirement = new NodeRequirement()
                {
                    MinStartHeight = 100
                };
                var nodeConnectionParameters = new NodeConnectionParameters()
                {
                    TemplateBehaviors =
                    {
                        new AddressManagerBehavior(manager)
                        {
                            PeersToDiscover = 1,
                            Mode            = AddressManagerBehaviorMode.None
                        }
                    }
                };
                var group = new NodesGroup(builder.Network, nodeConnectionParameters, nodesRequirement);
                group.AllowSameGroup = true;
                var connecting = WaitConnected(group);
                try
                {
                    group.Connect();
                    connecting.GetAwaiter().GetResult();
                }
                catch (TaskCanceledException)
                {
                    // It is expected because no node should connect.
                    Assert.Empty(group.ConnectedNodes);                     // but we chack it anyway.
                }
                finally
                {
                    group.Disconnect();
                }

                node.Generate(101);
                group = new NodesGroup(builder.Network, nodeConnectionParameters, nodesRequirement);
                group.AllowSameGroup = true;
                connecting           = WaitConnected(group);
                try
                {
                    group.Connect();
                    connecting.GetAwaiter().GetResult();
                    Eventually(() =>
                    {
                        Assert.NotEmpty(group.ConnectedNodes);
                        Assert.All(group.ConnectedNodes, connectedNode =>
                                   Assert.True(connectedNode.RemoteSocketEndpoint.IsEqualTo(node.NodeEndpoint)));
                    });
                }
                finally
                {
                    group.Disconnect();
                }
            }
        }