Exemple #1
0
        private bool OnBroadcastCommand(string[] args)
        {
            string        command = args[1].ToLower();
            ISerializable payload = null;

            switch (command)
            {
            case "addr":
                payload = AddrPayload.Create(NetworkAddressWithTime.Create(new IPEndPoint(IPAddress.Parse(args[2]), ushort.Parse(args[3])), NetworkAddressWithTime.NODE_NETWORK, DateTime.UtcNow.ToTimestamp()));
                break;

            case "block":
                if (args[2].Length == 64 || args[2].Length == 66)
                {
                    payload = Blockchain.Default.GetBlock(UInt256.Parse(args[2]));
                }
                else
                {
                    payload = Blockchain.Default.GetBlock(uint.Parse(args[2]));
                }
                break;

            case "getblocks":
            case "getheaders":
                payload = GetBlocksPayload.Create(UInt256.Parse(args[2]));
                break;

            case "getdata":
            case "inv":
                payload = InvPayload.Create(Enum.Parse <InventoryType>(args[2], true), args.Skip(3).Select(p => UInt256.Parse(p)).ToArray());
                break;

            case "tx":
                payload = LocalNode.GetTransaction(UInt256.Parse(args[2]));
                if (payload == null)
                {
                    payload = Blockchain.Default.GetTransaction(UInt256.Parse(args[2]));
                }
                break;

            case "alert":
            case "consensus":
            case "filteradd":
            case "filterload":
            case "headers":
            case "merkleblock":
            case "ping":
            case "pong":
            case "reject":
            case "verack":
            case "version":
                Console.WriteLine($"Command \"{command}\" is not supported.");
                return(true);
            }
            foreach (RemoteNode node in LocalNode.GetRemoteNodes())
            {
                node.EnqueueMessage(command, payload);
            }
            return(true);
        }
Exemple #2
0
        public void GetHashCodeTest()
        {
            var addr1 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 111, 456);
            var addr2 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 111, 456);
            var addr3 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 111, 4567);
            var addr4 = new NetworkAddressWithTime(NodeServiceFlags.NodeNetwork, IPAddress.Parse("1.2.3.4"), 111, 456);
            var addr5 = new NetworkAddressWithTime(NodeServiceFlags.All, IPAddress.Parse("1.2.3.4"), 111, 4567);
            var addr6 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.5"), 111, 456);
            var addr7 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 112, 456);

            int h1 = addr1.GetHashCode();
            int h2 = addr2.GetHashCode();
            int h3 = addr3.GetHashCode();
            int h4 = addr4.GetHashCode();
            int h5 = addr5.GetHashCode();
            int h6 = addr6.GetHashCode();
            int h7 = addr7.GetHashCode();

            Assert.Equal(h1, h2);
            Assert.Equal(h1, h3);
            Assert.Equal(h1, h4);
            Assert.Equal(h1, h5);
            Assert.NotEqual(h1, h6);
            Assert.NotEqual(h1, h7);
            Assert.NotEqual(h6, h7);
        }
Exemple #3
0
 public static byte[] EncodeNetworkAddressWithTime(NetworkAddressWithTime networkAddressWithTime)
 {
     using (var stream = new MemoryStream())
     {
         EncodeNetworkAddressWithTime(stream, networkAddressWithTime);
         return(stream.ToArray());
     }
 }
Exemple #4
0
 public static void EncodeNetworkAddressWithTime(Stream stream, NetworkAddressWithTime networkAddressWithTime)
 {
     using (var writer = new BinaryWriter(stream, Encoding.ASCII, leaveOpen: true))
     {
         writer.WriteUInt32(networkAddressWithTime.Time);
         EncodeNetworkAddress(stream, networkAddressWithTime.NetworkAddress);
     }
 }
Exemple #5
0
        private async Task ConnectAndHandshake(Peer peer, bool isIncoming)
        {
            // connect
            await peer.ConnectAsync();

            if (!peer.IsConnected)
            {
                throw new Exception();
            }

            // setup task to wait for verack
            var verAckTask = peer.Receiver.WaitForMessage(x => x.Command == "verack", HANDSHAKE_TIMEOUT_MS);

            // setup task to wait for version
            var versionTask = peer.Receiver.WaitForMessage(x => x.Command == "version", HANDSHAKE_TIMEOUT_MS);

            // start listening for messages after tasks have been setup
            peer.Receiver.Listen();

            // send our local version
            var nodeId = random.NextUInt64(); //TODO should be generated and verified on version message

            var currentHeight = this.coreDaemon.CurrentChain.Height;
            await peer.Sender.SendVersion(Messaging.GetExternalIPEndPoint(), peer.RemoteEndPoint, nodeId, (UInt32)currentHeight);

            // wait for our local version to be acknowledged by the remote peer
            // wait for remote peer to send their version
            await Task.WhenAll(verAckTask, versionTask);

            //TODO shouldn't have to decode again
            var versionMessage = versionTask.Result;
            var versionPayload = NodeEncoder.DecodeVersionPayload(versionMessage.Payload.ToArray(), versionMessage.Payload.Length);

            var remoteAddressWithTime = new NetworkAddressWithTime
                                        (
                Time: DateTime.UtcNow.ToUnixTime(),
                NetworkAddress: new NetworkAddress
                (
                    Services: versionPayload.LocalAddress.Services,
                    IPv6Address: versionPayload.LocalAddress.IPv6Address,
                    Port: versionPayload.LocalAddress.Port
                )
                                        );

            // acknowledge their version
            await peer.Sender.SendVersionAcknowledge();

            if (isIncoming)
            {
                Interlocked.Increment(ref this.incomingCount);
            }

            this.pendingPeers.TryRemove(peer);
            this.connectedPeers.TryAdd(peer);

            peer.OnDisconnect += DisconnectPeer;
            RaisePeerConnected(peer);
        }
Exemple #6
0
        public void TryDeserialize_FailTest(FastStreamReader stream, string expErr)
        {
            var addr = new NetworkAddressWithTime();

            bool b = addr.TryDeserialize(stream, out string error);

            Assert.False(b);
            Assert.Equal(expErr, error);
        }
Exemple #7
0
        private void HandlePeerConnected(Peer peer)
        {
            var remoteAddressWithTime = new NetworkAddressWithTime(DateTime.UtcNow.ToUnixTime(), peer.RemoteEndPoint.ToNetworkAddress(/*TODO*/ services: 0));

            this.networkPeerCache[remoteAddressWithTime.NetworkAddress.GetKey()] = remoteAddressWithTime;

            WirePeerEvents(peer);

            this.statsWorker.NotifyWork();
            this.headersRequestWorker.NotifyWork();
            this.blockRequestWorker.NotifyWork();
        }
Exemple #8
0
        public void SerializeTest()
        {
            var        addr   = new NetworkAddressWithTime(NodeServiceFlags.NodeNetwork, IPAddress.Parse("192.0.2.51"), 8333, 1414012889);
            FastStream stream = new FastStream(26);

            addr.Serialize(stream);

            byte[] actual   = stream.ToByteArray();
            byte[] expected = Helper.HexToBytes("d91f4854010000000000000000000000000000000000ffffc0000233208d");

            Assert.Equal(expected, actual);
        }
Exemple #9
0
        public void SetTimeToNowTest()
        {
            var addr = new NetworkAddressWithTime();

            Assert.Equal(0U, addr.Time);

            addr.SetTimeToNow();
            uint actual = (uint)UnixTimeStamp.GetEpochUtcNow();
            bool b      = (actual == addr.Time) || (actual - addr.Time < 2);

            Assert.True(b);
        }
Exemple #10
0
        public void GetDateTimeTest()
        {
            var addr = new NetworkAddressWithTime()
            {
                Time = 1414012889U
            };

            DateTime actual = addr.GetDateTime();
            // Converted using https://www.epochconverter.com/
            DateTime expected = new DateTime(2014, 10, 22, 21, 21, 29);

            Assert.Equal(expected, actual);
        }
Exemple #11
0
        public void TryDeserializeTest()
        {
            var  addr   = new NetworkAddressWithTime();
            var  stream = new FastStreamReader(Helper.HexToBytes("d91f4854010000000000000000000000000000000000ffffc0000233208d"));
            bool b      = addr.TryDeserialize(stream, out string error);

            Assert.True(b, error);
            Assert.Null(error);
            Assert.Equal(1414012889U, addr.Time);
            Assert.Equal(NodeServiceFlags.NodeNetwork, addr.NodeServices);
            Assert.Equal(IPAddress.Parse("192.0.2.51"), addr.NodeIP);
            Assert.Equal((ushort)8333, addr.NodePort);
        }
Exemple #12
0
        public void EqualsTest(NetworkAddressWithTime addr1, NetworkAddressWithTime addr2, bool expected)
        {
            Assert.Equal(expected, addr1.Equals(addr2));
            Assert.Equal(expected, addr1.Equals((object)addr2));

            Assert.Equal(expected, addr2.Equals(addr1));
            Assert.Equal(expected, addr2.Equals((object)addr1));

            Assert.True(addr1.Equals(addr1));
            Assert.True(addr1.Equals((object)addr1));

            Assert.True(addr2.Equals(addr2));
            Assert.True(addr2.Equals((object)addr2));
        }
 public bool TryGetValue(NetworkAddressKey networkAddressKey, out NetworkAddressWithTime networkAddressWithTime)
 {
     byte[] networkAddressWithTimeBytes;
     if (this.dict.TryGetValue(EncodeKey(networkAddressKey), out networkAddressWithTimeBytes))
     {
         networkAddressWithTime = DecodeValue(networkAddressWithTimeBytes);
         return(true);
     }
     else
     {
         networkAddressWithTime = default(NetworkAddressWithTime);
         return(false);
     }
 }
        public void SerializeDeserialize_NetworkAddressWithTime()
        {
            var original = new NetworkAddressWithTime
            {
                EndPoint  = new IPEndPoint(IPAddress.Broadcast.MapToIPv6(), 0),
                Services  = ulong.MaxValue,
                Timestamp = uint.MaxValue
            };

            var copy = _serializer.Deserialize <NetworkAddressWithTime>(_serializer.Serialize(original));

            Assert.AreEqual(original.Timestamp, copy.Timestamp);
            Assert.AreEqual(original.Services, copy.Services);
            Assert.AreEqual(original.EndPoint.ToString(), copy.EndPoint.ToString());
        }
Exemple #15
0
        private void OnGetAddrMessageReceived()
        {
            Random rand = new Random();
            IEnumerable <RemoteNode> peers = LocalNode.Singleton.RemoteNodes.Values
                                             .Where(p => p.ListenerPort > 0)
                                             .GroupBy(p => p.Remote.Address, (k, g) => g.First())
                                             .OrderBy(p => rand.Next())
                                             .Take(AddrPayload.MaxCountToSend);

            NetworkAddressWithTime[] networkAddresses = peers.Select(p => NetworkAddressWithTime.Create(p.Listener, p.Version.Services, p.Version.Timestamp)).ToArray();
            if (networkAddresses.Length == 0)
            {
                return;
            }
            Context.Parent.Tell(Message.Create("addr", AddrPayload.Create(networkAddresses)));
        }
Exemple #16
0
        private void OnBroadcastAddressCommand(IPAddress payload, ushort port)
        {
            if (payload == null)
            {
                Console.WriteLine("You must input the payload to relay.");
                return;
            }

            OnBroadcastCommand(MessageCommand.Addr,
                               AddrPayload.Create(
                                   NetworkAddressWithTime.Create(
                                       payload, DateTime.UtcNow.ToTimestamp(),
                                       new FullNodeCapability(),
                                       new ServerCapability(NodeCapabilityType.TcpServer, port))
                                   ));
        }
Exemple #17
0
        public void SizeAndEndPoint_Get()
        {
            var test = new NetworkAddressWithTime()
            {
                Capabilities = new NodeCapability[0], Address = IPAddress.Any, Timestamp = 1
            };

            test.Size.Should().Be(21);

            Assert.AreEqual(test.EndPoint.Port, 0);

            test = NetworkAddressWithTime.Create(IPAddress.Any, 1, new NodeCapability[] { new ServerCapability(NodeCapabilityType.TcpServer, 22) });
            test.Size.Should().Be(24);

            Assert.AreEqual(test.EndPoint.Port, 22);
        }
Exemple #18
0
        public void DeserializeAndSerialize()
        {
            var test  = NetworkAddressWithTime.Create(IPAddress.Any, 1, new NodeCapability[] { new ServerCapability(NodeCapabilityType.TcpServer, 22) });
            var clone = test.ToArray().AsSerializable <NetworkAddressWithTime>();

            CollectionAssert.AreEqual(test.Capabilities.ToByteArray(), clone.Capabilities.ToByteArray());
            Assert.AreEqual(test.EndPoint.ToString(), clone.EndPoint.ToString());
            Assert.AreEqual(test.Timestamp, clone.Timestamp);
            Assert.AreEqual(test.Address, clone.Address);

            Assert.ThrowsException <FormatException>(() => NetworkAddressWithTime.Create(IPAddress.Any, 1,
                                                                                         new NodeCapability[] {
                new ServerCapability(NodeCapabilityType.TcpServer, 22),
                new ServerCapability(NodeCapabilityType.TcpServer, 22)
            }).ToArray().AsSerializable <NetworkAddressWithTime>());
        }
Exemple #19
0
        private bool OnBroadcastCommand(string[] args)
        {
            if (!Enum.TryParse(args[1], true, out MessageCommand command))
            {
                Console.WriteLine($"Command \"{args[1]}\" is not supported.");
                return(true);
            }
            ISerializable payload = null;

            switch (command)
            {
            case MessageCommand.Addr:
                payload = AddrPayload.Create(NetworkAddressWithTime.Create(IPAddress.Parse(args[2]), DateTime.UtcNow.ToTimestamp(), new FullNodeCapability(), new ServerCapability(NodeCapabilityType.TcpServer, ushort.Parse(args[3]))));
                break;

            case MessageCommand.Block:
                if (args[2].Length == 64 || args[2].Length == 66)
                {
                    payload = Blockchain.Singleton.GetBlock(UInt256.Parse(args[2]));
                }
                else
                {
                    payload = Blockchain.Singleton.Store.GetBlock(uint.Parse(args[2]));
                }
                break;

            case MessageCommand.GetBlocks:
            case MessageCommand.GetHeaders:
                payload = GetBlocksPayload.Create(UInt256.Parse(args[2]));
                break;

            case MessageCommand.GetData:
            case MessageCommand.Inv:
                payload = InvPayload.Create(Enum.Parse <InventoryType>(args[2], true), args.Skip(3).Select(UInt256.Parse).ToArray());
                break;

            case MessageCommand.Transaction:
                payload = Blockchain.Singleton.GetTransaction(UInt256.Parse(args[2]));
                break;

            default:
                Console.WriteLine($"Command \"{command}\" is not supported.");
                return(true);
            }
            system.LocalNode.Tell(Message.Create(command, payload));
            return(true);
        }
 public bool TryAdd(NetworkAddressKey networkAddressKey, NetworkAddressWithTime networkAddressWithTime)
 {
     if (!this.ContainsKey(networkAddressKey))
     {
         try
         {
             this.dict.Add(EncodeKey(networkAddressKey), EncodeValue(networkAddressWithTime));
             return(true);
         }
         catch (ArgumentException)
         { return(false); }
     }
     else
     {
         return(false);
     }
 }
Exemple #21
0
        private bool OnBroadcastCommand(string[] args)
        {
            string        command = args[1].ToLower();
            ISerializable payload = null;

            switch (command)
            {
            case "addr":
                payload = AddrPayload.Create(NetworkAddressWithTime.Create(new IPEndPoint(IPAddress.Parse(args[2]), ushort.Parse(args[3])), NetworkAddressWithTime.NODE_NETWORK, DateTime.UtcNow.ToTimestamp()));
                break;

            case "block":
                if (args[2].Length == 64 || args[2].Length == 66)
                {
                    payload = Blockchain.Singleton.GetBlock(UInt256.Parse(args[2]));
                }
                else
                {
                    payload = Blockchain.Singleton.Store.GetBlock(uint.Parse(args[2]));
                }
                break;

            case "getblocks":
            case "getheaders":
                payload = GetBlocksPayload.Create(UInt256.Parse(args[2]));
                break;

            case "getdata":
            case "inv":
                payload = InvPayload.Create(Enum.Parse <InventoryType>(args[2], true), args.Skip(3).Select(UInt256.Parse).ToArray());
                break;

            case "tx":
                payload = Blockchain.Singleton.GetTransaction(UInt256.Parse(args[2]));
                break;

            default:
                Console.WriteLine($"Command \"{command}\" is not supported.");
                return(true);
            }
            system.LocalNode.Tell(Message.Create(command, payload));
            return(true);
        }
Exemple #22
0
        public static IEnumerable <object[]> GetEqulsCases()
        {
            var addr1 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 111, 456);
            var addr2 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 111, 456);
            var addr3 = new NetworkAddressWithTime(NodeServiceFlags.NodeNetwork, IPAddress.Parse("1.2.3.4"), 111, 456);
            var addr4 = new NetworkAddressWithTime(NodeServiceFlags.NodeNetwork, IPAddress.Parse("1.2.3.4"), 111, 45678);
            var addr5 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.5"), 111, 456);
            var addr6 = new NetworkAddressWithTime(NodeServiceFlags.NodeNone, IPAddress.Parse("1.2.3.4"), 112, 456);

            yield return(new object[] { addr1, addr1, true });

            yield return(new object[] { addr1, addr2, true });

            yield return(new object[] { addr1, addr3, true });

            yield return(new object[] { addr1, addr4, true });

            yield return(new object[] { addr1, addr5, false });

            yield return(new object[] { addr1, addr6, false });
        }
Exemple #23
0
        private void OnGetAddrMessageReceived()
        {
            if (!localNode.ServiceEnabled)
            {
                return;
            }
            AddrPayload payload;

            lock (localNode.connectedPeers)
            {
                const int MaxCountToSend       = 200;
                IEnumerable <RemoteNode> peers = localNode.connectedPeers.Where(p => p.ListenerEndpoint != null && p.Version != null);
                if (localNode.connectedPeers.Count > MaxCountToSend)
                {
                    Random rand = new Random();
                    peers = peers.OrderBy(p => rand.Next());
                }
                peers   = peers.Take(MaxCountToSend);
                payload = AddrPayload.Create(peers.Select(p => NetworkAddressWithTime.Create(p.ListenerEndpoint, p.Version.Services, p.Version.Timestamp)).ToArray());
            }
            EnqueueMessage("addr", payload, true);
        }
        private void OnGetAddrMessageReceived()
        {
            if (!localNode.ServiceEnabled)
            {
                return;
            }
            AddrPayload payload;

            lock (localNode.connectedPeers)
            {
                const int MaxCountToSend       = 200;
                IEnumerable <RemoteNode> peers = localNode.connectedPeers.Where(p => p.ListenerEndpoint != null && p.Version != null);
                if (localNode.connectedPeers.Count > MaxCountToSend)
                {
                    var rnd = new byte[4];
                    using (var rng = new RNGCryptoServiceProvider())
                        rng.GetBytes(rnd);
                    peers = peers.OrderBy(p => BitConverter.ToInt32(rnd, 0));
                }
                peers   = peers.Take(MaxCountToSend);
                payload = AddrPayload.Create(peers.Select(p => NetworkAddressWithTime.Create(p.ListenerEndpoint, p.Version.Services, p.Version.Timestamp)).ToArray());
            }
            EnqueueMessage("addr", payload, true);
        }
Exemple #25
0
        private void OnGetAddrMessageReceived()
        {
            if (!localNode.ServiceEnabled)
            {
                return;
            }
            AddrPayload payload;

            lock (localNode.connectedPeers)
            {
                payload = AddrPayload.Create(localNode.connectedPeers.Where(p => p.ListenerEndpoint != null && p.Version != null).Take(100).Select(p => NetworkAddressWithTime.Create(p.ListenerEndpoint, p.Version.Services, p.Version.Timestamp)).ToArray());
            }
            EnqueueMessage("addr", payload, true);
        }
Exemple #26
0
        public static IEnumerable <object[]> GetReplyCases()
        {
            var cs = new MockClientSettings()
            {
                _netType = NetworkType.MainNet
            };
            var bc        = new MockBlockchain();
            var mockAddr0 = new NetworkAddressWithTime(NodeServiceFlags.All, IPAddress.Loopback, 1010, 5678);
            var mockAddr1 = new NetworkAddressWithTime(NodeServiceFlags.All, IPAddress.Parse("200.2.3.4"), 23, 98);
            var mockAddr2 = new NetworkAddressWithTime(NodeServiceFlags.All, IPAddress.Parse("1.2.3.4"), 8080, 665412);
            var mockAddr3 = new NetworkAddressWithTime(NodeServiceFlags.All, IPAddress.Parse("99.77.88.66"), 444, 120000);

            var mockAddrs = new NetworkAddressWithTime[] { mockAddr1, mockAddr2, mockAddr3 };

            var mockAddrs1000 = Enumerable.Repeat(mockAddr0, 997).ToList();

            mockAddrs1000.AddRange(mockAddrs); // last 3 items are distict

            var mockAddrs1002 = Enumerable.Repeat(mockAddr0, 999).ToList();

            mockAddrs1002.AddRange(mockAddrs); // last 3 items are distict

            var expAddr1002_1 = Enumerable.Repeat(mockAddr0, 999).ToList();

            expAddr1002_1.Add(mockAddr1);
            var expAddr1002_2 = new NetworkAddressWithTime[2] {
                mockAddr2, mockAddr3
            };

            var mockBlock = new MockSerializableBlock(Helper.HexToBytes("01000000161126f0d39ec082e51bbd29a1dfb40b416b445ac8e493f88ce993860000000030e2a3e32abf1663a854efbef1b233c67c8cdcef5656fe3b4f28e52112469e9bae306849ffff001d16d1b42d0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0116ffffffff0100f2052a01000000434104f5efde0c2d30ab28e3dbe804c1a4aaf13066f9b198a4159c76f8f79b3b20caf99f7c979ed6c71481061277a6fc8666977c249da99960c97c8d8714fda9f0e883ac00000000"));

            yield return(new object[]
            {
                // Addr
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                    addrsToReceive = mockAddrs
                },
                bc,
                new Message(new AddrPayload(mockAddrs), NetworkType.MainNet),
                null
            });

            yield return(new object[]
            {
                // Block
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                },
                new MockBlockchain()
                {
                    expProcessBlk = "00000000841cb802ca97cf20fb9470480cae9e5daa5d06b4a18ae2d5dd7f186f",
                    blkProcessSuccess = true
                },
                new Message(new BlockPayload(mockBlock), NetworkType.MainNet),
                null
            });

            yield return(new object[]
            {
                // Block
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true, mediumViolation = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                },
                new MockBlockchain()
                {
                    expProcessBlk = "00000000841cb802ca97cf20fb9470480cae9e5daa5d06b4a18ae2d5dd7f186f",
                    blkProcessSuccess = false
                },
                new Message(new BlockPayload(mockBlock), NetworkType.MainNet),
                null
            });

            yield return(new object[]
            {
                // GetAddr with smaller than max items
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                    addrsToReturn = mockAddrs
                },
                bc,
                new Message(new GetAddrPayload(), NetworkType.MainNet),
                new Message[1] {
                    new Message(new AddrPayload(mockAddrs), NetworkType.MainNet)
                }
            });

            yield return(new object[]
            {
                // GetAddr with max items
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                    addrsToReturn = mockAddrs1000.ToArray()
                },
                bc,
                new Message(new GetAddrPayload(), NetworkType.MainNet),
                new Message[1] {
                    new Message(new AddrPayload(mockAddrs1000.ToArray()), NetworkType.MainNet)
                }
            });

            yield return(new object[]
            {
                // GetAddr with more than max items (needs 2 messages)
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                    addrsToReturn = mockAddrs1002.ToArray()
                },
                bc,
                new Message(new GetAddrPayload(), NetworkType.MainNet),
                new Message[2]
                {
                    new Message(new AddrPayload(expAddr1002_1.ToArray()), NetworkType.MainNet),
                    new Message(new AddrPayload(expAddr1002_2), NetworkType.MainNet)
                }
            });

            yield return(new object[]
            {
                // GetAddr with 0 items (no reply message)
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                new MockClientSettings()
                {
                    _netType = NetworkType.MainNet,
                    addrsToReturn = new NetworkAddressWithTime[0]
                },
                bc,
                new Message(new GetAddrPayload(), NetworkType.MainNet),
                null
            });

            yield return(new object[]
            {
                // Ping
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                cs, bc,
                new Message(new PingPayload(98765), NetworkType.MainNet),
                new Message[1] {
                    new Message(new PongPayload(98765), NetworkType.MainNet)
                }
            });

            yield return(new object[]
            {
                // Pong
                new MockNodeStatus()
                {
                    _handShakeToReturn = HandShakeState.Finished, updateTime = true
                },
                cs, bc,
                new Message(new PongPayload(98765), NetworkType.MainNet),
                null
            });
        }
Exemple #27
0
 public static CandidatePeer ToCandidatePeer(this NetworkAddressWithTime address)
 {
     return(new CandidatePeer(address.NetworkAddress.ToIPEndPoint(), address.Time, isSeed: false));
 }
Exemple #28
0
 public static NetworkAddressKey GetKey(this NetworkAddressWithTime knownAddress)
 {
     return(new NetworkAddressKey(knownAddress.NetworkAddress.IPv6Address, knownAddress.NetworkAddress.Port));
 }
Exemple #29
0
 public static byte[] EncodeNetworkAddressWithTime(NetworkAddressWithTime networkAddressWithTime)
 {
     using (var stream = new MemoryStream())
     using (var writer = new BinaryWriter(stream))
     {
         EncodeNetworkAddressWithTime(writer, networkAddressWithTime);
         return stream.ToArray();
     }
 }
Exemple #30
0
 public static void EncodeNetworkAddressWithTime(BinaryWriter writer, NetworkAddressWithTime networkAddressWithTime)
 {
     writer.WriteUInt32((uint)networkAddressWithTime.Time.ToUnixTimeSeconds()); //TODO is time LE or BE on network messages?
     EncodeNetworkAddress(writer, networkAddressWithTime.NetworkAddress);
 }
Exemple #31
0
        private async Task OnGetAddrMessageReceivedAsync()
        {
            if (!localNode.ServiceEnabled)
            {
                return;
            }
            AddrPayload payload;

            lock (localNode.connectedPeers)
            {
                payload = AddrPayload.Create(localNode.connectedPeers.Take(10).Select(p => NetworkAddressWithTime.Create(p.Value.RemoteEndpoint, p.Value.Version.Services, p.Value.Version.Timestamp)).ToArray());
            }
            await SendMessageAsync("addr", payload);
        }
 private static byte[] EncodeValue(NetworkAddressWithTime networkAddressWithTime)
 {
     return(NodeEncoder.EncodeNetworkAddressWithTime(networkAddressWithTime));
 }