예제 #1
0
        public void AddTest1()
        {
            //----------------------------------------------------------------------------------------------------
            //---only init the domain records which will force a cleaning of the address records
            InitDomainRecords();
            AddressManager mgr = CreateManager();

            //----------------------------------------------------------------------------------------------------
            //---make sure there are no mx records that exist
            Assert.Equal(0, mgr.Count());

            const long domainId    = 1;
            string     email       = BuildEmailAddress(1, 1);
            string     displayName = BuildEmailAddressDisplayName(1, 1);
            Address    addr        = new Address(domainId, email, displayName);

            using (CreateConfigDatabase())
            {
                mgr.Add(addr);
            }
            Assert.Equal(1, mgr.Count());
            addr = mgr.Get(email);
            Assert.Equal(domainId, addr.DomainID);
            Assert.Equal(email, addr.EmailAddress);
            Assert.Equal(displayName, addr.DisplayName);
            Assert.Equal(EntityStatus.New, addr.Status);
        }
예제 #2
0
        public async Task Connect()
        {
            await Task.Factory.StartNew(async() =>
            {
                EndpointInstance = await BusManager.StartServiceBus(Network.Name);
                _nodeGroup       = new NodesGroup(Network, GetNodeConnectionParameters())
                {
                    AllowSameGroup = true,
                };
                _nodeGroup.Requirements.SupportSPV = true;

                foreach (NetworkAddress networkAddress in BootstrapNodes)
                {
                    AddressManager.Add(networkAddress);
                }

                _nodeGroup.Connect();
                _nodeGroup.ConnectedNodes.Added += (s, e) =>
                {
                    var node              = e.Node;
                    node.MessageReceived += RebroadcastEvent;

                    node.MessageReceived += (node1, message) =>
                    {
                        Console.WriteLine("Message Received");
                        SaveChainData();
                    };

                    node.Disconnected += n =>
                    {
                        Console.WriteLine("Disconnected!");
                    };
                };
            });
        }
        public void AddNodeAddress(IPEndPoint endpoint)
        {
            AddressManager addrman = AddressManagerBehavior.GetAddrman(this.AddNodeNodeGroup.NodeConnectionParameters);

            addrman.Add(new NetworkAddress(endpoint));
            this.AddNodeNodeGroup.MaximumNodeConnection++;
        }
예제 #4
0
        NodesGroup CreateNodeGroup(ConcurrentChain chain, int startHeight)
        {
            AddressManager manager = new AddressManager();

            manager.Add(new NetworkAddress(NodeEndpoint), IPAddress.Loopback);
            NodesGroup group = new NodesGroup(Network, new NodeConnectionParameters()
            {
                Services          = NodeServices.Nothing,
                IsRelay           = true,
                TemplateBehaviors =
                {
                    new AddressManagerBehavior(manager)
                    {
                        PeersToDiscover = 1,
                        Mode            = AddressManagerBehaviorMode.None
                    },
                    new ExplorerBehavior(this, chain)
                    {
                        StartHeight = startHeight
                    },
                    new ChainBehavior(chain)
                    {
                        CanRespondToGetHeaders = false
                    }
                }
            });

            group.AllowSameGroup        = true;
            group.MaximumNodeConnection = 1;
            group.Connect();
            return(group);
        }
예제 #5
0
        public void CanUseAddrManager()
        {
            AddressManager addrman = new AddressManager();

            addrman.DebugMode = true;
            var localhost = new NetworkAddress(IPAddress.Parse("127.0.0.1"), 8333);

            addrman.Add(localhost, IPAddress.Loopback);
            Assert.NotNull(addrman.nKey);
            Assert.True(addrman.nKey != new uint256(0));
            Assert.True(addrman.nNew == 1);
            addrman.Good(localhost);
            Assert.True(addrman.nNew == 0);
            Assert.True(addrman.nTried == 1);
            addrman.Attempt(localhost);

            var addr = addrman.Select();

            Assert.False(addr.Ago < TimeSpan.FromSeconds(10.0));

            addrman.Connected(localhost);

            addr = addrman.Select();
            Assert.True(addr.Ago < TimeSpan.FromSeconds(1.0));
        }
예제 #6
0
        public override void Save()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.COUNTRIES);

            query.Add(Database.Tables.Countries.Name, Name);
            DoSave(query);
            AddressManager.Add(this);
        }
예제 #7
0
        public override void Save()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.CITIES);

            query.Add(Database.Tables.Cities.Name, Name);
            query.Add(Database.Tables.Cities.StateId, State);
            DoSave(query);
            AddressManager.Add(this);
        }
예제 #8
0
        public override void Save()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.POSTAL_CODES);

            query.Add(Database.Tables.PostalCodes.Code, Postcode);
            query.Add(Database.Tables.PostalCodes.CityId, City);
            DoSave(query);
            AddressManager.Add(this);
        }
예제 #9
0
        public override void Save()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.STATES);

            query.Add(Database.Tables.States.Name, Name);
            query.Add(Database.Tables.States.CountryId, Country);
            DoSave(query);
            AddressManager.Add(this);
        }
예제 #10
0
        //[Login]
        public ActionResult Addaddress(string add)
        {
            int userid = Convert.ToInt32(Session["User_id"]);

            //int userid = 1;
            add = Request["dizhi"].ToString();

            addressmanager.Add(userid, add);
            return(Content("<script>alert('添加成功');window.location.href='../Mall/Order';<script>"));
        }
예제 #11
0
        public void AddNodeAddress(IPEndPoint endpoint)
        {
            this.logger.LogTrace("({0}:'{1}')", nameof(endpoint), endpoint);

            AddressManager addrman = AddressManagerBehavior.GetAddrman(this.AddNodeNodeGroup.NodeConnectionParameters);

            addrman.Add(new NetworkAddress(endpoint));
            this.AddNodeNodeGroup.MaximumNodeConnection++;

            this.logger.LogTrace("(-)");
        }
예제 #12
0
        private async Task LoadGroup()
        {
            AddressManager manager = new AddressManager();

            manager.Add(new NetworkAddress(_ChainConfiguration.NodeEndpoint), IPAddress.Loopback);
            NodesGroup group = new NodesGroup(_Network.NBitcoinNetwork, new NodeConnectionParameters()
            {
                Services          = NodeServices.Nothing,
                IsRelay           = true,
                TemplateBehaviors =
                {
                    new AddressManagerBehavior(manager)
                    {
                        PeersToDiscover = 1,
                        Mode            = AddressManagerBehaviorMode.None
                    },
                    new ExplorerBehavior(_Repository, _Chain, _AddressPoolService, _EventAggregator)
                    {
                        StartHeight = _ChainConfiguration.StartHeight
                    },
                    new SlimChainBehavior(_Chain),
                    new PingPongBehavior()
                }
            });

            group.AllowSameGroup        = true;
            group.MaximumNodeConnection = 1;

            var task = WaitConnected(group);

            group.Connect();

            try
            {
                await task;
            }
            catch (Exception ex)
            {
                Logs.Configuration.LogError(ex, $"{_Network.CryptoCode}: Failure to connect to the bitcoin node (P2P)");
                throw;
            }
            _Group = group;

            group.ConnectedNodes.Added   += ConnectedNodes_Changed;
            group.ConnectedNodes.Removed += ConnectedNodes_Changed;

            // !Hack. ExplorerBehavior.AttachCore is async and calling the repository.
            // Because the repository is single thread, calling a ping make sure that AttachCore
            // has fully ran.
            // Without this hack, NBXplorer takes sometimes 1 min to go from Synching to Ready state
            await _Repository.Ping();
        }
예제 #13
0
        private async Task LoadGroup()
        {
            AddressManager manager = new AddressManager();

            manager.Add(new NetworkAddress(GetEndpoint()), IPAddress.Loopback);
            NodesGroup group = new NodesGroup(_Network.NBitcoinNetwork, new NodeConnectionParameters()
            {
                Services          = NodeServices.Nothing,
                IsRelay           = true,
                TemplateBehaviors =
                {
                    new AddressManagerBehavior(manager)
                    {
                        PeersToDiscover = 1,
                        Mode            = AddressManagerBehaviorMode.None
                    },
                    new ExplorerBehavior(_Repository, _Chain, _EventAggregator)
                    {
                        StartHeight = _Configuration.ChainConfigurations.First(c => c.CryptoCode == _Network.CryptoCode).StartHeight
                    },
                    new ChainBehavior(_Chain)
                    {
                        CanRespondToGetHeaders = false,
                        SkipPoWCheck           = true,
                        StripHeader            = true
                    },
                    new PingPongBehavior()
                }
            });

            group.AllowSameGroup        = true;
            group.MaximumNodeConnection = 1;

            var task = WaitConnected(group);

            group.Connect();

            try
            {
                await task;
            }
            catch (Exception ex)
            {
                Logs.Configuration.LogError(ex, $"{_Network.CryptoCode}: Failure to connect to the bitcoin node (P2P)");
                throw;
            }
            _Group = group;

            group.ConnectedNodes.Added   += ConnectedNodes_Changed;
            group.ConnectedNodes.Removed += ConnectedNodes_Changed;
        }
예제 #14
0
 public IActionResult Post([FromBody] Address address)
 {
     if (address == null)
     {
         return(BadRequest("Address is null"));
     }
     if (addressManager.Add(address) == 1)
     {
         return(Ok(address.Id));
     }
     else
     {
         return(BadRequest(false));
     }
 }
예제 #15
0
        public override void Load()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.COUNTRIES);

            query.Add(Database.Tables.Countries.Name);

            MySqlDataReader reader = DoLoad(query);

            if (Loaded)
            {
                Name = reader.GetString(0);
                AddressManager.Add(this);
            }

            reader.Close();
        }
예제 #16
0
        public void AddTest()
        {
            InitDomainRecords();
            AddressManager mgr       = CreateManager();
            List <Address> addresses = new List <Address>();

            for (int i = 1; i <= MAXADDRESSCOUNT; i++)
            {
                addresses.Add(new Address(STARTID, BuildEmailAddress(STARTID, i)));
            }
            Assert.Equal(0, mgr.Count());
            mgr.Add(addresses);
            Assert.Equal(MAXADDRESSCOUNT, mgr.Count());
            Address[] aa = mgr.Get(string.Empty, MAXADDRESSCOUNT + 1).ToArray();
            Assert.Equal(MAXADDRESSCOUNT, aa.Length);
        }
예제 #17
0
        public void CanSerializeDeserializePeerTableAfterBIP155()
        {
            AddressManager addrman = new AddressManager();
            var            netaddr = new NetworkAddress(new DnsEndPoint("wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion", 8333));

            addrman.Add(netaddr);
            addrman.SavePeerFile("serializerPeerBIP155.dat", Network.Main);
            var loaddedAddrMgr = AddressManager.LoadPeerFile("serializerPeerBIP155.dat", Network.Main);

            var addr = addrman.Select();

            Assert.True(addr.Endpoint is DnsEndPoint);
            var dns = addr.Endpoint as DnsEndPoint;

            Assert.Equal("wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion", dns.Host);
            Assert.Equal(8333, dns.Port);
        }
예제 #18
0
        public override void Load()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.POSTAL_CODES);

            query.Add(Database.Tables.PostalCodes.Code);
            query.Add(Database.Tables.PostalCodes.CityId);

            MySqlDataReader reader = DoLoad(query);

            if (Loaded)
            {
                Postcode = reader.GetString(0);
                City     = AddressManager.GetCity(reader.GetInt32(1));
                AddressManager.Add(this);
            }

            reader.Close();
        }
예제 #19
0
        public void Add_AddAddress_ReturnTrueResult()
        {
            IAddressService service = new AddressManager(_mockAddressDal.Object);
            Address         address = new Address
            {
                Id            = 2,
                CityId        = It.IsAny <int>(),
                UserId        = It.IsAny <int>(),
                AddressDetail = It.IsAny <string>(),
                PostalCode    = It.IsAny <string>(),
                CreateDate    = DateTime.Now,
                Active        = true
            };

            var result = service.Add(address);

            Assert.IsTrue(result.Success);
        }
예제 #20
0
        public override void Load()
        {
            DatabaseQuery query = new DatabaseQuery(Database.Tables.STATES);

            query.Add(Database.Tables.States.Name);
            query.Add(Database.Tables.States.CountryId);

            MySqlDataReader reader = DoLoad(query);

            if (Loaded)
            {
                Name    = reader.GetString(0);
                Country = AddressManager.GetCountry(reader.GetInt32(1));
                AddressManager.Add(this);
            }

            reader.Close();
            AddressManager.Add(this);
        }
예제 #21
0
        public Server(IPAddress externalAddress, NetworkInfo network, NodeConnectionParameters nodeConnectionParameters)
        {
            _Server = new NodeServer(network, internalPort: network.DefaultPort);
            OwnResource(_Server);

            if (externalAddress != null)
            {
                var            externalEndpoint = new IPEndPoint(externalAddress, network.DefaultPort);
                AddressManager addressManager   = AddressManagerBehavior.GetAddrman(nodeConnectionParameters);
                addressManager.Add(new NetworkAddress(externalEndpoint));
                addressManager.Connected(new NetworkAddress(externalEndpoint));
                _Server.ExternalEndpoint = externalEndpoint;
            }

            _Server.InboundNodeConnectionParameters = nodeConnectionParameters;
            _Server.AllowLocalPeers = false;             //TODO

            NodeServerTrace.Information($"Server setup at {externalAddress}");
        }
예제 #22
0
        /// <summary>
        /// This method will clean, load and verify address records in the DB for testing purposes
        /// </summary>
        /// <param name="mgr">AddressManager instance used for controlling the Address records</param>
        /// <param name="db">ConfigDatabase instance used as the target storage mechanism for the records</param>
        /// <remarks>
        /// this approach goes out to db each time it is called, however it ensures that clean records
        /// are present for every test that is execute, if it is taking too long, simply cut down on the
        /// number of items using the consts above
        /// </remarks>
        protected void InitAddressRecords(AddressManager mgr
                                          , ConfigDatabase db)
        {
            //----------------------------------------------------------------------------------------------------
            //---init domain records as well we want them fresh too
            InitDomainRecords(new DomainManager(CreateConfigStore()), db);
            foreach (KeyValuePair <long, KeyValuePair <int, string> > kp in TestAddressNames)
            {
                //----------------------------------------------------------------------------------------------------
                //---create new address entry with the domain id (kp.key) and the address
                mgr.Add(db, new Address(kp.Key, kp.Value.Value, BuildEmailAddressDisplayName(kp.Key, kp.Value.Key))
                {
                    Type = "SMTP"
                });
            }

            //----------------------------------------------------------------------------------------------------
            //---submit changes to db and verify existence of records
            db.SubmitChanges();
            foreach (KeyValuePair <long, KeyValuePair <int, string> > kp in TestAddressNames)
            {
                Assert.NotNull(mgr.Get(kp.Value.Value));
            }
        }
예제 #23
0
        public void CanHandshakeWithSeveralTemplateBehaviors()
        {
            using (var builder = NodeBuilderEx.Create())
            {
                var node = builder.CreateNode(true);
                node.Generate(101);
                AddressManager manager = new AddressManager();
                manager.Add(new NetworkAddress(node.NodeEndpoint), IPAddress.Loopback);

                var        chain = new SlimChain(builder.Network.GenesisHash);
                NodesGroup group = new NodesGroup(builder.Network, new NodeConnectionParameters()
                {
                    Services          = NodeServices.Nothing,
                    IsRelay           = true,
                    TemplateBehaviors =
                    {
                        new AddressManagerBehavior(manager)
                        {
                            PeersToDiscover = 1,
                            Mode            = AddressManagerBehaviorMode.None
                        },
                        new SlimChainBehavior(chain),
                        new PingPongBehavior()
                    }
                });
                group.AllowSameGroup        = true;
                group.MaximumNodeConnection = 1;
                var connecting = WaitConnected(group);
                try
                {
                    group.Connect();
                    connecting.GetAwaiter().GetResult();
                    Eventually(() =>
                    {
                        Assert.Equal(101, chain.Height);
                    });
                    var ms = new MemoryStream();
                    chain.Save(ms);

                    var chain2 = new SlimChain(chain.Genesis);
                    ms.Position = 0;
                    chain2.Load(ms);
                    Assert.Equal(chain.Tip, chain2.Tip);

                    using (var fs = new FileStream("test.slim.dat", FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024))
                    {
                        chain.Save(fs);
                        fs.Flush();
                    }

                    chain.ResetToGenesis();
                    using (var fs = new FileStream("test.slim.dat", FileMode.Open, FileAccess.Read, FileShare.None, 1024 * 1024))
                    {
                        chain.Load(fs);
                    }
                    Assert.Equal(101, chain2.Height);
                    chain.ResetToGenesis();
                }
                finally
                {
                    group.Disconnect();
                }
            }
        }
        public void Start()
        {
            this.parameters.UserAgent = "StratisBitcoin:" + GetVersion();
            this.parameters.Version   = this.NodeSettings.ProtocolVersion;
            if (this.connectionManagerSettings.Connect.Count == 0)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this));
                this.DiscoveredNodeGroup = CreateNodeGroup(cloneParameters, this.discoveredNodeRequiredService);
                this.DiscoveredNodeGroup.CustomGroupSelector = WellKnownGroupSelectors.ByNetwork;                 //is the default, but I want to use it
                this.DiscoveredNodeGroup.Connect();
            }
            else
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();
                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.Connect.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);
                var addrmanBehavior = new AddressManagerBehavior(addrman);
                addrmanBehavior.Mode = AddressManagerBehaviorMode.None;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.ConnectNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.ConnectNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.Connect.Count;
                this.ConnectNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
                this.ConnectNodeGroup.Connect();
            }

            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();
                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.AddNode.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);
                var addrmanBehavior = new AddressManagerBehavior(addrman);
                addrmanBehavior.Mode = AddressManagerBehaviorMode.AdvertizeDiscover;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.AddNodeNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.AddNodeNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.AddNode.Count;
                this.AddNodeNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
                this.AddNodeNodeGroup.Connect();
            }

            StringBuilder logs = new StringBuilder();

            logs.AppendLine("Node listening on:");
            foreach (NodeServerEndpoint listen in this.connectionManagerSettings.Listen)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                var server = new NodeServer(this.Network);

                server.LocalEndpoint    = listen.Endpoint;
                server.ExternalEndpoint = this.connectionManagerSettings.ExternalEndpoint;
                this.Servers.Add(server);
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(true, this)
                {
                    Whitelisted = listen.Whitelisted
                });
                server.InboundNodeConnectionParameters = cloneParameters;
                server.Listen();
                logs.Append(listen.Endpoint.Address + ":" + listen.Endpoint.Port);
                if (listen.Whitelisted)
                {
                    logs.Append(" (whitelisted)");
                }
                logs.AppendLine();
            }
            Logs.ConnectionManager.LogInformation(logs.ToString());
        }
예제 #25
0
        public void CanStressAddrManager()
        {
            Exception exception   = null;
            var       addrmanager = new AddressManager();
            Random    randl       = new Random();

            for (int i = 0; i < 30; i++)
            {
                NetworkAddress address       = RandomNetworkAddress(randl);
                IPAddress      addressSource = RandomAddress(randl);
                address.Ago = TimeSpan.FromMinutes(5.0);
                addrmanager.Add(address, addressSource);
            }

            addrmanager.DebugMode = true;
            var threads =
                Enumerable
                .Range(0, 20)
                .Select(t => new Thread(() =>
            {
                try
                {
                    Random rand = new Random(t);
                    for (int i = 0; i < 50; i++)
                    {
                        NetworkAddress address  = RandomNetworkAddress(rand);
                        IPAddress addressSource = RandomAddress(rand);
                        var operation           = rand.Next(0, 7);
                        switch (operation)
                        {
                        case 0:
                            addrmanager.Attempt(address);
                            break;

                        case 1:
                            addrmanager.Add(address, addressSource);
                            break;

                        case 2:
                            addrmanager.Select();
                            break;

                        case 3:
                            addrmanager.GetAddr();
                            break;

                        case 4:
                            {
                                var several = addrmanager.GetAddr();
                                addrmanager.Good(several.Length == 0 ? address : several[0]);
                            }
                            break;

                        case 5:
                            addrmanager.Connected(address);
                            break;

                        case 6:
                            addrmanager.ToBytes();
                            break;

                        default:
                            throw new NotSupportedException();
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                    throw;
                }
            })).ToArray();

            foreach (var t in threads)
            {
                t.Start();
            }
            foreach (var t in threads)
            {
                t.Join();
            }

            Assert.True(addrmanager.nNew != 0);
            Assert.True(addrmanager.nTried != 0);
            Assert.True(addrmanager.GetAddr().Length != 0);
            Assert.Null(exception);
        }
 public bool AddAddress(Address address)
 {
     return(_addressManager.Add(address));
 }
        public void Get_RoutedAddress()
        {
            InitAddressRecords();
            DomainManager dMgr = new DomainManager(CreateConfigStore());
            Domain domain = new Domain("address1.domain1.com");
            domain.Status = EntityStatus.Enabled;
            dMgr.Add(domain);

            string addressType = "Undeliverable";
            AddressManager aMgr = new AddressManager(CreateConfigStore());
            MailAddress address = new MailAddress("*****@*****.**");
            aMgr.Add(address, EntityStatus.Enabled, addressType);
            //
            // [email protected] aready exists
            //

            AddressManager mgr = CreateManager();

            string[] emailAddresses = new[] { "*****@*****.**" };

            IEnumerable<Address> actual = mgr.Get(emailAddresses, true, EntityStatus.Enabled);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }





            actual = mgr.Get(emailAddresses, EntityStatus.Enabled);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }




            actual = mgr.Get(emailAddresses, true);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }




            actual = mgr.Get(emailAddresses);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }



        }
예제 #28
0
        public void Listen(ConcurrentChain chain = null)
        {
            ListenerTrace.Info($"Connecting to node {_Configuration.Indexer.Node}");
            var ip = Utils.ParseIpEndpoint(_Configuration.Indexer.Node, Configuration.Indexer.Network.DefaultPort);

            ListenerTrace.Info($"Connecting to node ip {ip.ToString()}");
            var node = Node.Connect(Configuration.Indexer.Network, ip);

            ListenerTrace.Info($"Connected, trying handshake...");
            node.VersionHandshake();
            ListenerTrace.Info($"Hanshaked");
            node.Disconnect();

            _Chain   = new ConcurrentChain(_Configuration.Indexer.Network);
            _Indexer = Configuration.Indexer.CreateIndexer();
            if (chain == null)
            {
                chain = new ConcurrentChain(_Configuration.Indexer.Network);
            }
            _Chain = chain;
            ListenerTrace.Info("Fetching headers from " + _Chain.Tip.Height + " (from azure)");
            var client = Configuration.Indexer.CreateIndexerClient();

            client.SynchronizeChain(chain);
            ListenerTrace.Info("Headers fetched tip " + _Chain.Tip.Height);

            _Disposables.Add(_IndexerScheduler = new CustomThreadPoolTaskScheduler(50, 100, "Indexing Threads"));
            _Indexer.TaskScheduler             = _IndexerScheduler;

            _Group = new NodesGroup(Configuration.Indexer.Network);
            _Disposables.Add(_Group);
            _Group.AllowSameGroup        = true;
            _Group.MaximumNodeConnection = 2;
            AddressManager addrman = new AddressManager();

            addrman.Add(new NetworkAddress(ip), IPAddress.Parse("127.0.0.1"));

            _Group.NodeConnectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addrman)
            {
                Mode = AddressManagerBehaviorMode.None
            });
            _Group.NodeConnectionParameters.TemplateBehaviors.Add(new ChainBehavior(_Chain)
            {
                SkipPoWCheck = true
            });
            _Group.NodeConnectionParameters.TemplateBehaviors.Add(new Behavior(this));



            ListenerTrace.Info("Fetching wallet rules...");
            _Wallets = _Configuration.Indexer.CreateIndexerClient().GetAllWalletRules();
            ListenerTrace.Info("Wallet rules fetched");

            ListenerTrace.Info("Fetching wallet subscriptions...");
            _Subscriptions = new SubscriptionCollection(_Configuration.GetSubscriptionsTable().Read());
            ListenerTrace.Info("Subscriptions fetched");
            _Group.Connect();

            ListenerTrace.Info("Fetching transactions to broadcast...");

            _Disposables.Add(
                Configuration
                .Topics
                .BroadcastedTransactions
                .CreateConsumer("listener", true)
                .EnsureSubscriptionExists()
                .OnMessage((tx, ctl) =>
            {
                uint256 hash = null;
                var repo     = Configuration.Indexer.CreateIndexerClient();
                var rejects  = Configuration.GetRejectTable();
                try
                {
                    hash          = tx.Transaction.GetHash();
                    var indexedTx = repo.GetTransaction(hash);
                    ListenerTrace.Info("Broadcasting " + hash);
                    var reject = rejects.ReadOne(hash.ToString());
                    if (reject != null)
                    {
                        ListenerTrace.Info("Abort broadcasting of rejected");
                        return;
                    }

                    if (_Broadcasting.Count > 1000)
                    {
                        _Broadcasting.Clear();
                    }

                    _Broadcasting.TryAdd(hash, tx.Transaction);
                    if (indexedTx == null || !indexedTx.BlockIds.Any(id => Chain.Contains(id)))
                    {
                        var unused = SendMessageAsync(tx.Transaction);
                    }
                    var reschedule = new[]
                    {
                        TimeSpan.FromMinutes(5),
                        TimeSpan.FromMinutes(10),
                        TimeSpan.FromHours(1),
                        TimeSpan.FromHours(6),
                        TimeSpan.FromHours(24),
                    };
                    if (tx.Tried <= reschedule.Length - 1)
                    {
                        ctl.RescheduleIn(reschedule[tx.Tried]);
                        tx.Tried++;
                    }
                }
                catch (Exception ex)
                {
                    if (!_Disposed)
                    {
                        LastException = ex;
                        ListenerTrace.Error("Error for new broadcasted transaction " + hash, ex);
                        throw;
                    }
                }
            }));
            ListenerTrace.Info("Transactions to broadcast fetched");

            _Disposables.Add(_Configuration
                             .Topics
                             .SubscriptionChanges
                             .EnsureSubscriptionExists()
                             .AddUnhandledExceptionHandler(ExceptionOnMessagePump)
                             .OnMessage(c =>
            {
                using (_SubscriptionSlimLock.LockWrite())
                {
                    if (c.Added)
                    {
                        _Subscriptions.Add(c.Subscription);
                    }
                    else
                    {
                        _Subscriptions.Remove(c.Subscription.Id);
                    }
                }
            }));

            _Disposables.Add(_Configuration
                             .Topics
                             .SendNotifications
                             .AddUnhandledExceptionHandler(ExceptionOnMessagePump)
                             .OnMessageAsync((n, act) =>
            {
                return(SendAsync(n, act).ContinueWith(t =>
                {
                    if (!_Disposed)
                    {
                        if (t.Exception != null)
                        {
                            LastException = t.Exception;
                        }
                    }
                }));
            }, new OnMessageOptions()
            {
                MaxConcurrentCalls = 1000,
                AutoComplete       = true,
                AutoRenewTimeout   = TimeSpan.Zero
            }));

            _Disposables.Add(Configuration
                             .Topics
                             .AddedAddresses
                             .CreateConsumer("updater", true)
                             .EnsureSubscriptionExists()
                             .AddUnhandledExceptionHandler(ExceptionOnMessagePump)
                             .OnMessage(evt =>
            {
                if (evt == null)
                {
                    return;
                }
                ListenerTrace.Info("New wallet rule");
                using (_WalletsSlimLock.LockWrite())
                {
                    foreach (var address in evt)
                    {
                        _Wallets.Add(address.CreateWalletRuleEntry());
                    }
                }
            }));
        }
예제 #29
0
        private void BroadcastTransaction(Action <BroadcastHub> actionSender, Action actionReceiver)
        {
            WithServerSet(2, servers =>
            {
                WithBlockChains(2, null, blockChains =>
                {
                    AutoResetEvent waitForConnection = new AutoResetEvent(false);
                    bool connected = false;

                    servers.SeedServerIndex = 0;

                    AddressManager serverAddressManager = new AddressManager();
                    serverAddressManager.Add(
                        new NetworkAddress(servers[0].ExternalEndpoint),
                        servers[0].ExternalEndpoint.Address
                        );
                    serverAddressManager.Connected(new NetworkAddress(servers[0].ExternalEndpoint));

                    NodeConnectionParameters serverParameters = new NodeConnectionParameters();
                    serverParameters.TemplateBehaviors.Add(new AddressManagerBehavior(serverAddressManager));
                    serverParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                    serverParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[0], BroadcastHub.GetBroadcastHub(serverParameters.TemplateBehaviors)));

                    blockChains[0].OnAddedToMempool += transaction => {
                        Trace.Information("-- Transaction Received (node server)");
                        actionReceiver();
                    };

                    servers[0].InboundNodeConnectionParameters = serverParameters;

                    #region NodeGroup

                    AddressManager addressManager = new AddressManager();
                    addressManager.PeersToFind    = 1;
                    NodeConnectionParameters nodesGroupParameters = new NodeConnectionParameters();
                    nodesGroupParameters.AddressFrom = servers[1].ExternalEndpoint;
                    nodesGroupParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
                    nodesGroupParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                    nodesGroupParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[1], BroadcastHub.GetBroadcastHub(nodesGroupParameters.TemplateBehaviors)));

                    blockChains[1].OnAddedToMempool += transaction =>
                    {
                        Trace.Information("-- Transaction Received (node group)");
                    };

                    NodesGroup nodesGroup            = new NodesGroup(servers.Network, nodesGroupParameters);
                    nodesGroup.AllowSameGroup        = true;
                    nodesGroup.MaximumNodeConnection = 1;
                    nodesGroup.ConnectedNodes.Added += (object sender, NodeEventArgs e) =>
                    {
                        Trace.Information("-- Node added to node group");
                        connected = true;
                        waitForConnection.Set();
                    };
                    nodesGroup.Connect();

                    #endregion

                    Assert.True(waitForConnection.WaitOne(10000));                     //TODO: use reset events instead of sleep
                    Assert.True(connected);

                    actionSender(BroadcastHub.GetBroadcastHub(nodesGroup.NodeConnectionParameters));

                    Trace.Information("-- Done");
                });
            });
        }
예제 #30
0
        public void ShouldSyncBlockChain()
        {
            WithServerSet(2, servers =>
            {
                var p = new TestTransactionPool();

                p.Add("t1", 1);
                p.Add("t2", 0);
                p.Spend("t2", "t1", 0);

                p.Render();

                var genesisBlock = new TestBlock(p.TakeOut("t1").Value);
                var block1       = new TestBlock(p.TakeOut("t2").Value);
                block1.Parent    = genesisBlock;

                genesisBlock.Render();
                block1.Render();

                WithBlockChains(2, genesisBlock.Value.Key, blockChains =>
                {
                    blockChains[0].HandleNewBlock(genesisBlock.Value.Value);
                    blockChains[0].HandleNewBlock(block1.Value.Value);


                    AutoResetEvent waitForConnection = new AutoResetEvent(false);
                    bool connected = false;

                    servers.SeedServerIndex = 0;

                    AddressManager serverAddressManager = new AddressManager();
                    serverAddressManager.Add(
                        new NetworkAddress(servers[0].ExternalEndpoint),
                        servers[0].ExternalEndpoint.Address
                        );
                    serverAddressManager.Connected(new NetworkAddress(servers[0].ExternalEndpoint));

                    NodeConnectionParameters serverParameters = new NodeConnectionParameters();
                    serverParameters.TemplateBehaviors.Add(new AddressManagerBehavior(serverAddressManager));
                    serverParameters.TemplateBehaviors.Add(new ChainBehavior(blockChains[0]));
                    serverParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                    serverParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[0], BroadcastHub.GetBroadcastHub(serverParameters.TemplateBehaviors)));

                    blockChains[0].OnAddedToStore += transaction =>
                    {
                        Trace.Information("-- Transaction Received (node server)");
                        //	actionReceiver();
                    };

                    servers[0].InboundNodeConnectionParameters = serverParameters;

                    #region NodeGroup

                    AddressManager addressManager = new AddressManager();
                    addressManager.PeersToFind    = 1;
                    NodeConnectionParameters nodesGroupParameters = new NodeConnectionParameters();
                    nodesGroupParameters.AddressFrom = servers[1].ExternalEndpoint;
                    nodesGroupParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
                    nodesGroupParameters.TemplateBehaviors.Add(new ChainBehavior(blockChains[1]));
                    nodesGroupParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                    nodesGroupParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[1], BroadcastHub.GetBroadcastHub(nodesGroupParameters.TemplateBehaviors)));

                    blockChains[1].OnAddedToStore += transaction =>
                    {
                        Trace.Information("-- Transaction Received (node group)");
                    };

                    NodesGroup nodesGroup            = new NodesGroup(servers.Network, nodesGroupParameters);
                    nodesGroup.AllowSameGroup        = true;
                    nodesGroup.MaximumNodeConnection = 1;
                    nodesGroup.ConnectedNodes.Added += (object sender, NodeEventArgs e) =>
                    {
                        Trace.Information("-- Node added to node group");
                        connected = true;
                        waitForConnection.Set();
                    };
                    nodesGroup.Connect();

                    #endregion

                    Assert.True(waitForConnection.WaitOne(10000));                     //TODO: use reset events instead of sleep
                    Assert.True(connected);



                    //TODO
                    Thread.Sleep(30000);



//					actionSender(BroadcastHub.GetBroadcastHub(nodesGroup.NodeConnectionParameters));

                    Trace.Information("-- Done");
                });
            });
        }
예제 #31
0
        public void Start()
        {
            this.logger.LogTrace("()");

            this.parameters.UserAgent = $"{this.NodeSettings.Agent}:{this.GetVersion()}";
            this.parameters.Version   = this.NodeSettings.ProtocolVersion;

            if (this.connectionManagerSettings.Connect.Count == 0)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this, this.loggerFactory));
                this.DiscoveredNodeGroup = CreateNodeGroup(cloneParameters, this.discoveredNodeRequiredService);
                this.DiscoveredNodeGroup.CustomGroupSelector = WellKnownGroupSelectors.ByNetwork; // It is the default, but I want to use it.
            }
            else
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this, this.loggerFactory));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();

                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.Connect.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);

                var addrmanBehavior = new AddressManagerBehavior(addrman)
                {
                    PeersToDiscover = 10
                };
                addrmanBehavior.Mode = AddressManagerBehaviorMode.None;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.ConnectNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.ConnectNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.Connect.Count;
                this.ConnectNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
            }

            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this, this.loggerFactory));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();
                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.AddNode.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);
                var addrmanBehavior = new AddressManagerBehavior(addrman)
                {
                    PeersToDiscover = 10
                };
                addrmanBehavior.Mode = AddressManagerBehaviorMode.AdvertizeDiscover;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.AddNodeNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.AddNodeNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.AddNode.Count;
                this.AddNodeNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
            }

            // Related the groups to each other to prevent duplicate connections.
            RelatedNodesGroups relGroups = new RelatedNodesGroups();

            relGroups.Register("Discovered", this.DiscoveredNodeGroup);
            relGroups.Register("Connect", this.ConnectNodeGroup);
            relGroups.Register("AddNode", this.AddNodeNodeGroup);
            this.DiscoveredNodeGroup?.Connect();
            this.ConnectNodeGroup?.Connect();
            this.AddNodeNodeGroup?.Connect();

            StringBuilder logs = new StringBuilder();

            logs.AppendLine("Node listening on:");
            foreach (NodeServerEndpoint listen in this.connectionManagerSettings.Listen)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                var server = new NodeServer(this.Network)
                {
                    LocalEndpoint    = listen.Endpoint,
                    ExternalEndpoint = this.connectionManagerSettings.ExternalEndpoint
                };

                this.Servers.Add(server);
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(true, this, this.loggerFactory)
                {
                    Whitelisted = listen.Whitelisted
                });

                server.InboundNodeConnectionParameters = cloneParameters;
                server.Listen();

                logs.Append(listen.Endpoint.Address + ":" + listen.Endpoint.Port);
                if (listen.Whitelisted)
                {
                    logs.Append(" (whitelisted)");
                }
                logs.AppendLine();
            }
            this.logger.LogInformation(logs.ToString());

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