Exemple #1
0
 public GenericNode(String name, NodeType type)
 {
     // Initialize with default settings
     Settings = new NodeSettings(name, type,
         new BindingList<RecordBase>(),
         new InternalNodeSettings(Properties.Settings.Default.DefaultEnabled,
             (PriorityLevel) Properties.Settings.Default.DefaultPriorityLevel,
             Properties.Settings.Default.DefaultNodeRuns,
             Properties.Settings.Default.DefaultVOffset,
             Properties.Settings.Default.DefaultHOffset,
             (MouseSpeed) Properties.Settings.Default.DefaultMouseSpeed),
         new InternalTimeSettings(
             (EntropyLevel) Properties.Settings.Default.DefaultNodeEntropy,
             Properties.Settings.Default.DefaultForcedPause));
 }
Exemple #2
0
        public void GivenIHaveDeployedInstances(int p0)
        {
            var names = new List<string>(p0);
            for (var i = 0; i < p0; i++)
            {
                names.Add((i + (100 * run)).ToString(CultureInfo.InvariantCulture));
            }

            this.infra.Middleware = new Middleware();
            this.infra.Nodes = new List<Node<string>>(p0);
            var settings = new NodeSettings { Nodes = names.ToArray(), TimeoutInMs = 100 };

            for (var i = 0; i < p0; i++)
            {
                settings.NodeId = names[i];
                var node = new Node<string>(this.infra.Middleware.RootUnitOfExecution.BuildSequencer(), settings, this.infra.Middleware, this.infra.Machine);
                this.infra.Nodes.Add(node);
            }
            run++;
        }
Exemple #3
0
        public static NodeSettings BuildNodeSettings(string nodeId, IEnumerable<string> nodes)
        {
            List<string> workNodes;
            if (nodes != null)
            {
                workNodes = new List<string>(nodes);
                if (workNodes.Contains(nodeId))
                {
                    workNodes.Remove(nodeId);
                }
            }
            else
            {
                workNodes = new List<string>();
            }

            var settings = new NodeSettings
            {
                NodeId = nodeId,
                TimeoutInMs = 10,
                Nodes = workNodes.ToArray()
            };
            return settings;
        }
        public void WhenRefreshWhitelist_AndOwnIPInPeers_AndAreRunningFullNode_ThenWhitelistDoesContainOwnIP()
        {
            // Arrange.
            Mock <IDateTimeProvider> mockDateTimeProvider = new Mock <IDateTimeProvider>();

            Mock <ILogger>        mockLogger        = new Mock <ILogger>();
            Mock <ILoggerFactory> mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 5000;

            IPAddress      activeIpAddressOne      = IPAddress.Parse("::ffff:192.168.0.1");
            NetworkAddress activeNetworkAddressOne = new NetworkAddress(activeIpAddressOne, 80);

            IPAddress      activeIpAddressTwo      = IPAddress.Parse("::ffff:192.168.0.2");
            NetworkAddress activeNetworkAddressTwo = new NetworkAddress(activeIpAddressTwo, 80);

            IPAddress      activeIpAddressThree      = IPAddress.Parse("::ffff:192.168.0.3");
            NetworkAddress activeNetworkAddressThree = new NetworkAddress(activeIpAddressThree, 80);

            IPAddress      externalIPAdress       = IPAddress.Parse("::ffff:192.168.99.99");
            int            externalPort           = 80;
            NetworkAddress externalNetworkAddress = new NetworkAddress(externalIPAdress, externalPort);

            List <Tuple <NetworkAddress, DateTimeOffset> > activeTestDataSet = new List <Tuple <NetworkAddress, DateTimeOffset> >()
            {
                new Tuple <NetworkAddress, DateTimeOffset> (activeNetworkAddressOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <NetworkAddress, DateTimeOffset>(activeNetworkAddressTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <NetworkAddress, DateTimeOffset>(activeNetworkAddressThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <NetworkAddress, DateTimeOffset> (externalNetworkAddress, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40))
            };

            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet);

            string[] args = new string[] {
                $"-dnspeeractivethreshold={inactiveTimePeriod.ToString()}",
                $"-externalip={externalNetworkAddress.Endpoint.Address.ToString()}",
                $"-port={externalPort.ToString()}",
            };

            IMasterFile       spiedMasterFile = null;
            Mock <IDnsServer> mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            Network      network      = Network.StratisTest;
            NodeSettings nodeSettings = new NodeSettings(network).LoadArguments(args);
            DnsSettings  dnsSettings  = new Mock <DnsSettings>().Object;

            dnsSettings.DnsFullNode = true;
            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings();

            connectionSettings.Load(nodeSettings);

            WhitelistManager whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            Question question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.AAAA);
            IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question);

            resourceRecords.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet);

            foreach (Tuple <NetworkAddress, DateTimeOffset> testData in activeTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Endpoint.Address)).Should().NotBeNull();
            }
        }
Exemple #5
0
 public RPCFeature(FullNode fullNode, NodeSettings nodeSettings)
 {
     this.fullNode     = fullNode;
     this.nodeSettings = Guard.NotNull(nodeSettings, nameof(nodeSettings));
 }
Exemple #6
0
 /// <summary>
 /// Constructs an instance of an object for persisting memory pool transactions.
 /// </summary>
 /// <param name="settings">Node settings used for getting the data directory.</param>
 /// <param name="loggerFactory">Logger factory for creating instance logger.</param>
 public MempoolPersistence(NodeSettings settings, ILoggerFactory loggerFactory)
 {
     this.dataDir       = settings?.DataDir;
     this.mempoolLogger = loggerFactory.CreateLogger(this.GetType().FullName);
 }
        /// <summary>
        /// Creates the test chain with some default blocks and txs.
        /// </summary>
        /// <param name="network">Network to create the chain on.</param>
        /// <param name="scriptPubKey">Public key to create blocks/txs with.</param>
        /// <param name="requireStandard">By default testnet and regtest networks do not require transactions to be standard. This changes that default.</param>
        /// <returns>Context object representing the test chain.</returns>
        public static async Task <ITestChainContext> CreateAsync(Network network, Script scriptPubKey, string dataDir, bool requireStandard = true)
        {
            var nodeSettings = new NodeSettings(network, args: new string[] { $"-datadir={dataDir}" });

            ILoggerFactory    loggerFactory    = nodeSettings.LoggerFactory;
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

            network.Consensus.Options = new ConsensusOptions();

            var consensusRulesContainer = new ConsensusRulesContainer();

            foreach (Type ruleType in network.Consensus.ConsensusRules.HeaderValidationRules)
            {
                // Don't check PoW of a header in this test.
                if (ruleType == typeof(CheckDifficultyPowRule))
                {
                    continue;
                }

                consensusRulesContainer.HeaderValidationRules.Add(Activator.CreateInstance(ruleType) as HeaderValidationConsensusRule);
            }
            foreach (Type ruleType in network.Consensus.ConsensusRules.PartialValidationRules)
            {
                consensusRulesContainer.PartialValidationRules.Add(Activator.CreateInstance(ruleType) as PartialValidationConsensusRule);
            }
            foreach (var ruleType in network.Consensus.ConsensusRules.FullValidationRules)
            {
                FullValidationConsensusRule rule = null;
                if (ruleType == typeof(FlushCoinviewRule))
                {
                    rule = new FlushCoinviewRule(new Mock <IInitialBlockDownloadState>().Object);
                }
                else
                {
                    rule = Activator.CreateInstance(ruleType) as FullValidationConsensusRule;
                }

                consensusRulesContainer.FullValidationRules.Add(rule);
            }

            var consensusSettings = new ConsensusSettings(nodeSettings);
            var chain             = new ChainIndexer(network);
            var inMemoryCoinView  = new InMemoryCoinView(new HashHeightPair(chain.Tip));

            var asyncProvider = new AsyncProvider(loggerFactory, new Mock <ISignals>().Object);

            var chainState  = new ChainState();
            var deployments = new NodeDeployments(network, chain);

            ConsensusRuleEngine consensusRules = new PowConsensusRuleEngine(network, loggerFactory, dateTimeProvider, chain, deployments, consensusSettings, new Checkpoints(),
                                                                            inMemoryCoinView, chainState, new InvalidBlockHashStore(dateTimeProvider), new NodeStats(dateTimeProvider, nodeSettings, new Mock <IVersionProvider>().Object), asyncProvider, consensusRulesContainer).SetupRulesEngineParent();

            ConsensusManager consensus = ConsensusManagerHelper.CreateConsensusManager(network, dataDir, chainState, chainIndexer: chain, consensusRules: consensusRules, inMemoryCoinView: inMemoryCoinView);

            var genesis = new ChainedHeader(network.GetGenesis().Header, network.GenesisHash, 0);

            chainState.BlockStoreTip = genesis;
            await consensus.InitializeAsync(genesis).ConfigureAwait(false);

            var blockPolicyEstimator = new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings);
            var mempool     = new TxMempool(dateTimeProvider, blockPolicyEstimator, loggerFactory, nodeSettings);
            var mempoolLock = new MempoolSchedulerLock();

            var minerSettings = new MinerSettings(nodeSettings);

            // Simple block creation, nothing special yet:
            var           blockDefinition = new PowBlockDefinition(consensus, dateTimeProvider, loggerFactory, mempool, mempoolLock, minerSettings, network, consensusRules, deployments);
            BlockTemplate newBlock        = blockDefinition.Build(chain.Tip, scriptPubKey);

            await consensus.BlockMinedAsync(newBlock.Block);

            List <BlockInfo> blockinfo = CreateBlockInfoList();

            // We can't make transactions until we have inputs therefore, load 100 blocks.

            var srcTxs = new List <Transaction>();

            for (int i = 0; i < blockinfo.Count; ++i)
            {
                Block currentBlock = Block.Load(newBlock.Block.ToBytes(network.Consensus.ConsensusFactory), network.Consensus.ConsensusFactory);
                currentBlock.Header.HashPrevBlock = chain.Tip.HashBlock;
                currentBlock.Header.Version       = 1;
                currentBlock.Header.Time          = Utils.DateTimeToUnixTime(chain.Tip.GetMedianTimePast()) + 1;

                Transaction txCoinbase = network.CreateTransaction(currentBlock.Transactions[0].ToBytes());
                txCoinbase.Inputs.Clear();
                txCoinbase.Version = 1;
                txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(blockinfo[i].extraNonce), Op.GetPushOp(chain.Height) })));
                // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
                txCoinbase.AddOutput(new TxOut(Money.Zero, new Script()));
                currentBlock.Transactions[0] = txCoinbase;

                currentBlock.UpdateMerkleRoot();
                currentBlock.Header.Nonce = blockinfo[i].nonce;

                chain.SetTip(currentBlock.Header);
                srcTxs.Add(currentBlock.Transactions[0]);

                inMemoryCoinView.SaveChanges(new List <UnspentOutput>()
                {
                    new UnspentOutput(new OutPoint(currentBlock.Transactions[0], 0), new Coins((uint)(i + 1), currentBlock.Transactions[0].Outputs.First(), currentBlock.Transactions[0].IsCoinBase))
                }, new HashHeightPair(chain.Tip.Previous), new HashHeightPair(chain.Tip));
            }

            // Just to make sure we can still make simple blocks
            blockDefinition = new PowBlockDefinition(consensus, dateTimeProvider, loggerFactory, mempool, mempoolLock, minerSettings, network, consensusRules, deployments);
            blockDefinition.Build(chain.Tip, scriptPubKey);

            var mempoolSettings = new MempoolSettings(nodeSettings)
            {
                RequireStandard = requireStandard
            };

            // The mempool rule constructors aren't parameterless, so we have to manually inject the dependencies for every rule
            var mempoolRules = new List <MempoolRule>
            {
                new CheckConflictsMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckCoinViewMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CreateMempoolEntryMempoolRule(network, mempool, mempoolSettings, chain, consensusRules, loggerFactory),
                new CheckSigOpsMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckFeeMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckRateLimitMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckAncestorsMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckReplacementMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckAllInputsMempoolRule(network, mempool, mempoolSettings, chain, consensusRules, deployments, loggerFactory),
                new CheckTxOutDustRule(network, mempool, mempoolSettings, chain, loggerFactory),
            };

            // We also have to check that the manually instantiated rules match the ones in the network, or the test isn't valid
            for (int i = 0; i < network.Consensus.MempoolRules.Count; i++)
            {
                if (network.Consensus.MempoolRules[i] != mempoolRules[i].GetType())
                {
                    throw new Exception("Mempool rule type mismatch");
                }
            }

            Assert.Equal(network.Consensus.MempoolRules.Count, mempoolRules.Count);

            var nodeDeployments = new NodeDeployments(network, chain);

            var mempoolValidator = new MempoolValidator(mempool, mempoolLock, dateTimeProvider, mempoolSettings, chain, inMemoryCoinView, loggerFactory, nodeSettings, consensusRules, mempoolRules, new Signals.Signals(loggerFactory, null), nodeDeployments);

            return(new TestChainContext {
                MempoolValidator = mempoolValidator, MempoolSettings = mempoolSettings, ChainIndexer = chain, SrcTxs = srcTxs
            });
        }
Exemple #8
0
            public async Task InitializeAsync()
            {
                this.blockinfo = new List <Blockinfo>();
                var lst = blockinfoarr.Cast <long>().ToList();

                for (int i = 0; i < lst.Count; i += 2)
                {
                    this.blockinfo.Add(new Blockinfo {
                        extranonce = (int)lst[i], nonce = (uint)lst[i + 1]
                    });
                }

                // Note that by default, these tests run with size accounting enabled.
                this.network = Network.Main;
                var hex = Encoders.Hex.DecodeData("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");

                this.scriptPubKey = new Script(new[] { Op.GetPushOp(hex), OpcodeType.OP_CHECKSIG });
                this.newBlock     = new BlockTemplate();

                this.entry = new TestMemPoolEntryHelper();
                this.chain = new ConcurrentChain(this.network);
                this.network.Consensus.Options = new PowConsensusOptions();
                IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

                this.cachedCoinView = new CachedCoinView(new InMemoryCoinView(this.chain.Tip.HashBlock), dateTimeProvider, new LoggerFactory());

                var loggerFactory = new ExtendedLoggerFactory();

                loggerFactory.AddConsoleWithFilters();

                var nodeSettings      = NodeSettings.Default();
                var consensusSettings = new ConsensusSettings(nodeSettings, loggerFactory)
                {
                    UseCheckpoints = this.useCheckpoints
                };

                PowConsensusValidator consensusValidator = new PowConsensusValidator(this.network, new Checkpoints(), dateTimeProvider, loggerFactory);
                NetworkPeerFactory    networkPeerFactory = new NetworkPeerFactory(this.network, dateTimeProvider, loggerFactory);

                var peerAddressManager = new PeerAddressManager(nodeSettings.DataFolder, loggerFactory);
                var peerDiscovery      = new PeerDiscovery(new AsyncLoopFactory(loggerFactory), loggerFactory, Network.Main, networkPeerFactory, new NodeLifetime(), nodeSettings, peerAddressManager);
                var connectionManager  = new ConnectionManager(dateTimeProvider, loggerFactory, this.network, networkPeerFactory, nodeSettings, new NodeLifetime(), new NetworkPeerConnectionParameters(), peerAddressManager, new IPeerConnector[] { }, peerDiscovery);

                LookaheadBlockPuller blockPuller    = new LookaheadBlockPuller(this.chain, connectionManager, new LoggerFactory());
                PeerBanning          peerBanning    = new PeerBanning(connectionManager, loggerFactory, dateTimeProvider, nodeSettings);
                NodeDeployments      deployments    = new NodeDeployments(this.network, this.chain);
                ConsensusRules       consensusRules = new ConsensusRules(this.network, loggerFactory, dateTimeProvider, this.chain, deployments, consensusSettings, new Checkpoints()).Register(new FullNodeBuilderConsensusExtension.CoreConsensusRules());

                this.consensus = new ConsensusLoop(new AsyncLoopFactory(loggerFactory), consensusValidator, new NodeLifetime(), this.chain, this.cachedCoinView, blockPuller, new NodeDeployments(this.network, this.chain), loggerFactory, new ChainState(new InvalidBlockHashStore(dateTimeProvider)), connectionManager, dateTimeProvider, new Signals.Signals(), consensusSettings, nodeSettings, peerBanning, consensusRules);
                await this.consensus.StartAsync();

                this.entry.Fee(11);
                this.entry.Height(11);
                var date1 = new MemoryPoolTests.DateTimeProviderSet();

                date1.time       = dateTimeProvider.GetTime();
                date1.timeutc    = dateTimeProvider.GetUtcNow();
                this.date        = date1;
                this.mempool     = new TxMempool(dateTimeProvider, new BlockPolicyEstimator(new MempoolSettings(nodeSettings), new LoggerFactory(), nodeSettings), new LoggerFactory(), nodeSettings);
                this.mempoolLock = new MempoolSchedulerLock();

                // Simple block creation, nothing special yet:
                this.newBlock = AssemblerForTest(this).CreateNewBlock(this.scriptPubKey);
                this.chain.SetTip(this.newBlock.Block.Header);
                await this.consensus.ValidateAndExecuteBlockAsync(new RuleContext(new BlockValidationContext {
                    Block = this.newBlock.Block
                }, this.network.Consensus, this.consensus.Tip) { CheckPow = false, CheckMerkleRoot = false });

                // We can't make transactions until we have inputs
                // Therefore, load 100 blocks :)
                this.baseheight = 0;
                List <Block> blocks = new List <Block>();

                this.txFirst = new List <Transaction>();
                for (int i = 0; i < this.blockinfo.Count; ++i)
                {
                    var pblock = this.newBlock.Block.Clone(); // pointer for convenience
                    pblock.Header.HashPrevBlock = this.chain.Tip.HashBlock;
                    pblock.Header.Version       = 1;
                    pblock.Header.Time          = Utils.DateTimeToUnixTime(this.chain.Tip.GetMedianTimePast()) + 1;
                    Transaction txCoinbase = pblock.Transactions[0].Clone();
                    txCoinbase.Inputs.Clear();
                    txCoinbase.Version = 1;
                    txCoinbase.AddInput(new TxIn(new Script(new[] { Op.GetPushOp(this.blockinfo[i].extranonce), Op.GetPushOp(this.chain.Height) })));
                    // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this)
                    txCoinbase.AddOutput(new TxOut(Money.Zero, new Script()));
                    pblock.Transactions[0] = txCoinbase;

                    if (this.txFirst.Count == 0)
                    {
                        this.baseheight = this.chain.Height;
                    }
                    if (this.txFirst.Count < 4)
                    {
                        this.txFirst.Add(pblock.Transactions[0]);
                    }
                    pblock.UpdateMerkleRoot();

                    pblock.Header.Nonce = this.blockinfo[i].nonce;

                    this.chain.SetTip(pblock.Header);
                    await this.consensus.ValidateAndExecuteBlockAsync(new RuleContext(new BlockValidationContext {
                        Block = pblock
                    }, this.network.Consensus, this.consensus.Tip) { CheckPow = false, CheckMerkleRoot = false });

                    blocks.Add(pblock);
                }

                // Just to make sure we can still make simple blocks
                this.newBlock = AssemblerForTest(this).CreateNewBlock(this.scriptPubKey);
                Assert.NotNull(this.newBlock);
            }
        public void WhenDnsServerInitialized_AndMasterFileOnDisk_ThenDnsServerSuccessfullyInitializes()
        {
            // Arrange.
            Mock <IUdpClient>  udpClient  = new Mock <IUdpClient>();
            Mock <IMasterFile> masterFile = new Mock <IMasterFile>();

            masterFile.Setup(m => m.Get(It.IsAny <Question>())).Returns(new List <IResourceRecord>());

            CancellationTokenSource source       = new CancellationTokenSource(5000);
            Mock <INodeLifetime>    nodeLifetime = new Mock <INodeLifetime>();

            nodeLifetime.Setup(n => n.ApplicationStopping).Returns(source.Token);

            Mock <ILogger>        logger        = new Mock <ILogger>();
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            Mock <IAsyncLoopFactory> asyncLoopFactory = new Mock <IAsyncLoopFactory>();

            asyncLoopFactory.Setup(f => f.Run(It.IsAny <string>(), It.IsAny <Func <CancellationToken, Task> >(), It.IsAny <TimeSpan?>(), It.IsAny <TimeSpan?>())).Returns(new Mock <IAsyncLoop>().Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DnsSettings dnsSettings = new Mock <DnsSettings>().Object;

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolders = new Mock <DataFolder>(nodeSettings).Object;

            string masterFilePath = Path.Combine(dataFolders.DnsMasterFilePath, DnsFeature.DnsMasterFileName);

            // Act.
            try
            {
                // Create masterfile on disk
                using (FileStream stream = File.Create(masterFilePath))
                {
                    stream.Close();
                }

                // Run server
                DnsSeedServer server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncLoopFactory.Object, nodeLifetime.Object, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolders);
                server.Initialize();
                bool waited = source.Token.WaitHandle.WaitOne();

                // Assert.
                server.Should().NotBeNull();
                waited.Should().BeTrue();
                masterFile.Verify(m => m.Load(It.IsAny <Stream>()), Times.Once);
            }
            finally
            {
                // Try and remove created
                if (File.Exists(masterFilePath))
                {
                    File.Delete(masterFilePath);
                }
            }
        }
Exemple #10
0
        public void VerifyCheckpoints_BitcoinTestnet()
        {
            var verifyableCheckpoints = new Dictionary <int, CheckpointInfo>
            {
                { 546, new CheckpointInfo(new uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")) },
                { 1210000, new CheckpointInfo(new uint256("00000000461201277cf8c635fc10d042d6f0a7eaa57f6c9e8c099b9e0dbc46dc")) },
            };

            var checkpoints = new Checkpoints(KnownNetworks.TestNet, new ConsensusSettings(NodeSettings.Default(this.network))
            {
                UseCheckpoints = true
            });

            VerifyCheckpoints(checkpoints, verifyableCheckpoints);
        }
Exemple #11
0
        public void GetCheckPoint_CheckpointExists_PoSChain_ReturnsCheckpoint()
        {
            var checkpoints = new Checkpoints(KnownNetworks.StratisMain, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest))
            {
                UseCheckpoints = true
            });

            CheckpointInfo result = checkpoints.GetCheckpoint(2);

            Assert.Equal(new uint256("0xbca5936f638181e74a5f1e9999c95b0ce77da48c2688399e72bcc53a00c61eff"), result.Hash);
            Assert.Equal(new uint256("0x7d61c139a471821caa6b7635a4636e90afcfe5e195040aecbc1ad7d24924db1e"), result.StakeModifierV2);
        }
Exemple #12
0
 public ExtendedBlockPuller(IChainState chainState, NodeSettings nodeSettings, IDateTimeProvider dateTimeProvider, INodeStats nodeStats, ILoggerFactory loggerFactory)
 {
     this.puller = new BlockPuller(chainState, nodeSettings, dateTimeProvider, nodeStats, loggerFactory);
 }
Exemple #13
0
 public SmartContractMempoolValidator(ITxMempool memPool, MempoolSchedulerLock mempoolLock,
                                      IDateTimeProvider dateTimeProvider, MempoolSettings mempoolSettings, ChainIndexer chainIndexer,
                                      ICoinView coinView, ILoggerFactory loggerFactory, NodeSettings nodeSettings,
                                      IConsensusRuleEngine consensusRules, IEnumerable <IMempoolRule> mempoolRules, NodeDeployments nodeDeployments)
     : base(memPool, mempoolLock, dateTimeProvider, mempoolSettings, chainIndexer, coinView, loggerFactory, nodeSettings, consensusRules, mempoolRules, nodeDeployments)
 {
     // Dirty hack, but due to AllowedScriptTypeRule we don't need to check for standard scripts on any network, even live.
     // TODO: Remove ASAP. Ensure RequireStandard isn't used on SC mainnets, or the StandardScripts check is modular.
     mempoolSettings.RequireStandard = false;
 }
Exemple #14
0
        /// <summary>
        /// Creates a transaction to transfers funds from an old federation to a new federation.
        /// </summary>
        /// <param name="isSideChain">Indicates whether the <paramref name="network"/> is the sidechain.</param>
        /// <param name="network">The network that we are creating the recovery transaction for.</param>
        /// <param name="counterChainNetwork">The counterchain network.</param>
        /// <param name="dataDirPath">The root folder containing the old federation.</param>
        /// <param name="redeemScript">The new redeem script.</param>
        /// <param name="password">The password required to generate transactions using the federation wallet.</param>
        /// <param name="txTime">Any deposits beyond this UTC date will be ignored when selecting coin inputs.</param>
        /// <returns>A funds recovery transaction that moves funds to the new redeem script.</returns>
        public FundsRecoveryTransactionModel CreateFundsRecoveryTransaction(bool isSideChain, Network network, Network counterChainNetwork, string dataDirPath, Script redeemScript, string password, DateTime txTime)
        {
            var model = new FundsRecoveryTransactionModel()
            {
                Network = network, IsSideChain = isSideChain, RedeemScript = redeemScript
            };

            // Get the old redeem script from the wallet file.
            PayToMultiSigTemplateParameters multisigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript);
            string           theChain          = isSideChain ? "sidechain" : "mainchain";
            var              nodeSettings      = new NodeSettings(network, args: new string[] { $"datadir={dataDirPath}", $"redeemscript={redeemScript}", $"-{theChain}" });
            var              walletFileStorage = new FileStorage <FederationWallet>(nodeSettings.DataFolder.WalletPath);
            FederationWallet wallet            = walletFileStorage.LoadByFileName("multisig_wallet.json");
            Script           oldRedeemScript   = wallet.MultiSigAddress.RedeemScript;
            PayToMultiSigTemplateParameters oldMultisigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(oldRedeemScript);

            model.oldMultisigAddress = oldRedeemScript.Hash.GetAddress(network);
            model.newMultisigAddress = redeemScript.Hash.GetAddress(network);

            // Create dummy inputs to avoid errors when constructing FederatedPegSettings.
            var extraArgs = new Dictionary <string, string>();

            extraArgs[FederatedPegSettings.FederationIpsParam] = oldMultisigParams.PubKeys.Select(p => "0.0.0.0".ToIPEndPoint(nodeSettings.Network.DefaultPort)).Join(",");
            var privateKey = Key.Parse(wallet.EncryptedSeed, password, network);

            extraArgs[FederatedPegSettings.PublicKeyParam] = privateKey.PubKey.ToHex(network);
            (new TextFileConfiguration(extraArgs.Select(i => $"{i.Key}={i.Value}").ToArray())).MergeInto(nodeSettings.ConfigReader);

            model.PubKey = privateKey.PubKey;

            var dBreezeSerializer = new DBreezeSerializer(network.Consensus.ConsensusFactory);
            var blockStore        = new BlockRepository(network, nodeSettings.DataFolder, nodeSettings.LoggerFactory, dBreezeSerializer);

            blockStore.Initialize();

            var           chain        = new ChainRepository(nodeSettings.LoggerFactory, new ChainStore(), network);
            Block         genesisBlock = network.GetGenesis();
            ChainedHeader tip          = chain.LoadAsync(new ChainedHeader(genesisBlock.Header, genesisBlock.GetHash(), 0)).GetAwaiter().GetResult();
            var           chainIndexer = new ChainIndexer(network, tip);

            var nodeLifetime = new NodeLifetime();
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;
            var federatedPegSettings           = new FederatedPegSettings(nodeSettings);
            var opReturnDataReader             = new OpReturnDataReader(nodeSettings.LoggerFactory, new CounterChainNetworkWrapper(counterChainNetwork));
            var walletFeePolicy = new WalletFeePolicy(nodeSettings);

            var walletManager = new FederationWalletManager(nodeSettings.LoggerFactory, network, chainIndexer, nodeSettings.DataFolder, walletFeePolicy,
                                                            new AsyncProvider(nodeSettings.LoggerFactory, new Signals(nodeSettings.LoggerFactory, new DefaultSubscriptionErrorHandler(nodeSettings.LoggerFactory)), nodeLifetime), nodeLifetime,
                                                            dateTimeProvider, federatedPegSettings, new WithdrawalExtractor(nodeSettings.LoggerFactory, federatedPegSettings, opReturnDataReader, network), blockStore);

            walletManager.Start();
            walletManager.EnableFederationWallet(password);

            if (!walletManager.IsFederationWalletActive())
            {
                throw new ArgumentException($"Could not activate the federation wallet on {network}.");
            }

            // Retrieves the unspent outputs in deterministic order.
            List <Stratis.Features.FederatedPeg.Wallet.UnspentOutputReference> coinRefs = walletManager.GetSpendableTransactionsInWallet().ToList();

            // Exclude coins (deposits) beyond the transaction (switch-over) time!
            coinRefs = coinRefs.Where(r => r.Transaction.CreationTime < txTime).ToList();
            if (!coinRefs.Any())
            {
                throw new ArgumentException($"There are no coins to recover from the federation wallet on {network}.");
            }

            Money fee = federatedPegSettings.GetWithdrawalTransactionFee(coinRefs.Count());

            var builder = new TransactionBuilder(network);

            builder.AddKeys(privateKey);
            builder.AddCoins(coinRefs.Select(c => ScriptCoin.Create(network, c.Transaction.Id, (uint)c.Transaction.Index, c.Transaction.Amount, c.Transaction.ScriptPubKey, oldRedeemScript)));

            // Split the coins into multiple outputs.
            Money     amount         = coinRefs.Sum(r => r.Transaction.Amount) - fee;
            const int numberOfSplits = 10;
            Money     splitAmount    = new Money((long)amount / numberOfSplits);
            var       recipients     = new List <Stratis.Features.FederatedPeg.Wallet.Recipient>();

            for (int i = 0; i < numberOfSplits; i++)
            {
                Money sendAmount = (i != (numberOfSplits - 1)) ? splitAmount : amount - splitAmount * (numberOfSplits - 1);

                builder.Send(redeemScript.PaymentScript, sendAmount);
            }

            builder.SetTimeStamp((uint)(new DateTimeOffset(txTime)).ToUnixTimeSeconds());
            builder.CoinSelector = new DeterministicCoinSelector();
            builder.SendFees(fee);

            model.tx = builder.BuildTransaction(true);

            File.WriteAllText(Path.Combine(dataDirPath, $"{network.Name}_{model.PubKey.ToHex(network).Substring(0, 8)}.hex"), model.tx.ToHex(network));

            // Merge our transaction with other transactions which have been placed in the data folder.
            Transaction oldTransaction = model.tx;
            string      namePattern    = $"{network.Name}_*.hex";
            int         sigCount       = 1;

            foreach (string fileName in Directory.EnumerateFiles(dataDirPath, namePattern))
            {
                Transaction incomingPartialTransaction = network.CreateTransaction(File.ReadAllText(fileName));

                // Don't merge with self.
                if (incomingPartialTransaction.GetHash() == oldTransaction.GetHash())
                {
                    continue;
                }

                // Transaction times must match.
                //if (incomingPartialTransaction is PosTransaction && incomingPartialTransaction.Time != model.tx.Time)
                //{
                //    Console.WriteLine($"The locally generated transaction is time-stamped differently from the transaction contained in '{fileName}'. The imported signature can't be used.");
                //    continue;
                //}

                // Combine signatures.
                Transaction newTransaction = SigningUtils.CheckTemplateAndCombineSignatures(builder, model.tx, new[] { incomingPartialTransaction });

                if (oldTransaction.GetHash() == newTransaction.GetHash())
                {
                    Console.WriteLine($"The locally generated transaction is not similar to '{fileName}'. The imported signature can't be used.");
                    continue;
                }

                model.tx = newTransaction;
                sigCount++;
            }

            Console.WriteLine($"{sigCount} of {multisigParams.SignatureCount} signatures collected for {network.Name}.");

            if (sigCount >= multisigParams.SignatureCount)
            {
                if (builder.Verify(model.tx))
                {
                    // Write the transaction to file.
                    File.WriteAllText(Path.Combine(dataDirPath, $"{(txTime > DateTime.Now ? "Preliminary " : "")}{network.Name}Recovery.txt"), model.tx.ToHex(network));
                }
                else
                {
                    Console.WriteLine("Could not verify the transaction.");
                }
            }

            // Stop the wallet manager to release the database folder.
            nodeLifetime.StopApplication();
            walletManager.Stop();

            return(model);
        }
Exemple #15
0
 /// <summary>
 /// Initializes an instance of the object from the default configuration.
 /// </summary>
 public StoreSettings() : this(NodeSettings.Default())
 {
 }
Exemple #16
0
 /// <summary>Constructor used for unit testing.</summary>
 public PeerConnectorDiscovery(NodeSettings nodeSettings, IPeerAddressManager peerAddressManager)
     : base(nodeSettings, peerAddressManager)
 {
 }
 public PeerSelectorTests()
 {
     this.extendedLoggerFactory     = ExtendedLoggerFactory.Create();
     this.connectionManagerSettings = new ConnectionManagerSettings(NodeSettings.Default(new StraxRegTest()));
 }
Exemple #18
0
        public void VerifyCheckpoints_StratisMainnet()
        {
            var verifyableCheckpoints = new Dictionary <int, CheckpointInfo>
            {
                { 0, new CheckpointInfo(new uint256("0x0000066e91e46e5a264d42c89e1204963b2ee6be230b443e9159020539d972af"), new uint256("0x0000000000000000000000000000000000000000000000000000000000000000")) },
                { 2, new CheckpointInfo(new uint256("0xbca5936f638181e74a5f1e9999c95b0ce77da48c2688399e72bcc53a00c61eff"), new uint256("0x7d61c139a471821caa6b7635a4636e90afcfe5e195040aecbc1ad7d24924db1e")) }, // Premine
                { 50, new CheckpointInfo(new uint256("0x0353b43f4ce80bf24578e7c0141d90d7962fb3a4b4b4e5a17925ca95e943b816"), new uint256("0x7c2af3b10d13f9d2bc6063baaf7f0860d90d870c994378144f9bf85d0d555061")) },
                { 100, new CheckpointInfo(new uint256("0x688468a8aa48cd1c2197e42e7d8acd42760b7e2ac4bcab9d18ac149a673e16f6"), new uint256("0xcf2b1e9e76aaa3d96f255783eb2d907bf6ccb9c1deeb3617149278f0e4a1ab1b")) },
                { 150, new CheckpointInfo(new uint256("0xe4ae9663519abec15e28f68bdb2cb89a739aee22f53d1573048d69141db6ee5d"), new uint256("0xa6c17173e958dc716cc0892ce33dad8bc327963d78a16c436264ceae43d584ce")) },
                { 127500, new CheckpointInfo(new uint256("0x4773ca7512489df22de03aa03938412fab5b46154b05df004b97bcbeaa184078"), new uint256("0x619743c02ebaff06b90fcc5c60c52dba8aa3fdb6ba3800aae697cbb3c5483f17")) },
                { 128943, new CheckpointInfo(new uint256("0x36bcaa27a53d3adf22b2064150a297adb02ac39c24263a5ceb73856832d49679"), new uint256("0xa3a6fd04e41fcaae411a3990aaabcf5e086d2d06c72c849182b27b4de8c2c42a")) },
                { 136601, new CheckpointInfo(new uint256("0xf5c5210c55ff1ef9c04715420a82728e1647f3473e31dc478b3745a97b4a6d10"), new uint256("0x42058fabe21f7b118a9e358eaf9ef574dadefd024244899e71f2f6d618161e16")) }, // Hardfork to V2 - Drifting Bug Fix
                { 170000, new CheckpointInfo(new uint256("0x22b10952e0cf7e85bfc81c38f1490708f195bff34d2951d193cc20e9ca1fc9d5"), new uint256("0xa4942a6c99cba397cf2b18e4b912930fe1e64a7413c3d97c5a926c2af9073091")) },
                { 200000, new CheckpointInfo(new uint256("0x2391dd493be5d0ff0ef57c3b08c73eefeecc2701b80f983054bb262f7a146989"), new uint256("0x253152d129e82c30c584197deb6833502eff3ec2f30014008f75842d7bb48453")) },
                { 250000, new CheckpointInfo(new uint256("0x681c70fab7c1527246138f0cf937f0eb013838b929fbe9a831af02a60fc4bf55"), new uint256("0x24eed95e00c90618aa9d137d2ee273267285c444c9cde62a25a3e880c98a3685")) },
                { 300000, new CheckpointInfo(new uint256("0xd10ca8c2f065a49ae566c7c9d7a2030f4b8b7f71e4c6fc6b2a02509f94cdcd44"), new uint256("0x39c4dd765b49652935524248b4de4ccb604df086d0723bcd81faf5d1c2489304")) },
                { 350000, new CheckpointInfo(new uint256("0xe2b76d1a068c4342f91db7b89b66e0f2146d3a4706c21f3a262737bb7339253a"), new uint256("0xd1dd94985eaaa028c893687a7ddf89143dcf0176918f958c2d01f33d64910399")) },
                { 390000, new CheckpointInfo(new uint256("0x4682737abc2a3257fdf4c3c119deb09cbac75981969e2ffa998b4f76b7c657bb"), new uint256("0xd84b204ee94499ff65262328a428851fb4f4d2741e928cdd088fdf1deb5413b8")) },
                { 394000, new CheckpointInfo(new uint256("0x42857fa2bc15d45cdcaae83411f755b95985da1cb464ee23f6d40936df523e9f"), new uint256("0x2314b336906a2ed2a39cbdf6fc0622530709c62dbb3a3729de17154fc9d1a7c4")) },
                { 400000, new CheckpointInfo(new uint256("0x4938d5cf450b4e2d9072558971223555055aa3987b634a8bb2e97f95d1a3c501"), new uint256("0x1756c127f0ac7029cf095a6c3ed9b7d206d0e36744d8b3cef306002f9f901a31")) },
                { 450000, new CheckpointInfo(new uint256("0x7699e07ac18c25ac042deb6b985e2decfd6034cb6361de2152a2d704ef785bac"), new uint256("0xa140a86a03c4f852d8a651f6386a02a0262e7bbf841ede8b54541c011c51ba0e")) },
                { 500000, new CheckpointInfo(new uint256("0x558700d99239e64017d10910466719fe1edc6f863bd3de254b89ba828818ea47"), new uint256("0x6a0b7dab4a7aa9ea2477cddffe5a976c9423454835054a39c19d37613002638f")) },
                { 550000, new CheckpointInfo(new uint256("0x83d074957f509772b1fbbfaeb7bdc52932c540d54e205b92a7d4e92f68957eb4"), new uint256("0x012b63ad7d50606f2cafb1a7806ea90f4981c56b5407725aeeff34e3c584433c")) },
                { 600000, new CheckpointInfo(new uint256("0xcd05c75c0c47060d78508095c0766452f80e2defb6a4641ac603742a2ccf2207"), new uint256("0x1f25507e09b199a71d5879811376856e5fb3da1da3d522204c017eec3b6c4dad")) },
                { 650000, new CheckpointInfo(new uint256("0xa2814a439b33662f43bdbc8ab089d368524975bb53a08326395e57456cba8d39"), new uint256("0x192a2ef70e2280cf05aa5655f496a109b2445d0ddda62531e9bce9aaced1fe54")) },
                { 700000, new CheckpointInfo(new uint256("0x782b2506bb67bb448ff56aa946f7aad6b63a6b27d8c5818725a56b568f25b9ce"), new uint256("0xf23dc64b130d80790a83a86913f619afaeef10e1fd24e4b42af9387ec935edd6")) },
                { 750000, new CheckpointInfo(new uint256("0x4db98bd41a2f9ee845cc89ac03109686f615f4d0dcd81e0488005c1616fa692c"), new uint256("0x9f620af75bc27a0e4b503deaf7f052ba112a49bb74fb6446350642bc2ac9d93b")) },
                { 800000, new CheckpointInfo(new uint256("0x161da1d97d35d6897dbdae110617bb839805f8b02d33ac23d227a87cacbfac78"), new uint256("0xe95049a313345f26bfa90094ceb6400f43359fc43fc5f1471918d98bc4ab3bac")) },
                { 850000, new CheckpointInfo(new uint256("0xc3a249b01795b22858aa00fd0973471fcd769a14f4f9cf0abe6651ac3e6ade19"), new uint256("0x5de8766ed4cfcc3ce9d74f38196596c6f91b9ff62cbd20abbfa991dca54d2bd4")) }
            };

            var checkpoints = new Checkpoints(KnownNetworks.StratisMain, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest))
            {
                UseCheckpoints = true
            });

            VerifyCheckpoints(checkpoints, verifyableCheckpoints);
        }
        public async Task WhenDnsServerListening_AndDnsRequestReceivedRepeatedly_ThenResponsesReturnedInRoundRobinOrder_Async()
        {
            // Arrange.
            Queue <CancellationTokenSource> sources = new Queue <CancellationTokenSource>();
            Queue <byte[]>    responses             = new Queue <byte[]>();
            Mock <IUdpClient> udpClient             = new Mock <IUdpClient>();

            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) =>
            {
                // One response at a time.
                responses.Enqueue(p);
                CancellationTokenSource source = sources.Dequeue();
                source.Cancel();
            }).ReturnsAsync(1);

            DnsSeedMasterFile masterFile = new DnsSeedMasterFile();

            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.1")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.2")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.3")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.4")));

            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DnsSettings dnsSettings = new Mock <DnsSettings>().Object;

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolders = new Mock <DataFolder>(nodeSettings).Object;

            Mock <ILogger>        logger        = new Mock <ILogger>();
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act (Part 1).
            DnsSeedServer server = new DnsSeedServer(udpClient.Object, masterFile, asyncLoopFactory, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolders);

            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 1).
            responses.Count.Should().Be(1);
            byte[]    response    = responses.Dequeue();
            IResponse dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 2).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 2).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.2");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 3).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 3).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.3");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 4).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 4).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.4");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 5).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 5).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            // This should start back at the beginning again.
            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }
        }
Exemple #20
0
        public void VerifyCheckpoints_StratisTestnet()
        {
            var verifyableCheckpoints = new Dictionary <int, CheckpointInfo>
            {
                { 0, new CheckpointInfo(new uint256("0x00000e246d7b73b88c9ab55f2e5e94d9e22d471def3df5ea448f5576b1d156b9"), new uint256("0x0000000000000000000000000000000000000000000000000000000000000000")) },
                { 2, new CheckpointInfo(new uint256("0x56959b1c8498631fb0ca5fe7bd83319dccdc6ac003dccb3171f39f553ecfa2f2"), new uint256("0x13f4c27ca813aefe2d9018077f8efeb3766796b9144fcc4cd51803bf4376ab02")) },
                { 50000, new CheckpointInfo(new uint256("0xb42c18eacf8fb5ed94eac31943bd364451d88da0fd44cc49616ffea34d530ad4"), new uint256("0x824934ddc5f935e854ac59ae7f5ed25f2d29a7c3914cac851f3eddb4baf96d78")) },
                { 100000, new CheckpointInfo(new uint256("0xf9e2f7561ee4b92d3bde400d251363a0e8924204c326da7f4ad9ccc8863aad79"), new uint256("0xdef8d92d20becc71f662ee1c32252aca129f1bf4744026b116d45d9bfe67e9fb")) },
                { 150000, new CheckpointInfo(new uint256("0x08b7c20a450252ddf9ce41dbeb92ecf54932beac9090dc8250e933ad3a175381"), new uint256("0xf05dad15f733ae0acbd34adc449be9429099dbee5fa9ecd8e524cf28e9153adb")) },
                { 200000, new CheckpointInfo(new uint256("0x8609cc873222a0573615788dc32e377b88bfd6a0015791f627d969ee3a415115"), new uint256("0xfa28c1f20a8162d133607c6a1c8997833befac3efd9076567258a7683ac181fa")) },
                { 250000, new CheckpointInfo(new uint256("0xdd664e15ac679a6f3b96a7176303956661998174a697ad8231f154f1e32ff4a3"), new uint256("0x19fc0fa29418f8b19cbb6557c1c79dfd0eff6779c0eaaec5d245c5cdf3c96d78")) },
                { 300000, new CheckpointInfo(new uint256("0x2409eb5ae72c80d5b37c77903d75a8e742a33843ab633935ce6e5264db962e23"), new uint256("0xf5ec7af55516b8e264ed280e9a5dba0180a4a9d3713351bfea275b18f3f1514e")) },
                { 350000, new CheckpointInfo(new uint256("0x36811041e9060f4b4c26dc20e0850dca5efaabb60618e3456992e9c0b1b2120e"), new uint256("0xbfda55ef0756bcee8485e15527a2b8ca27ca877aa09c88e363ef8d3253cdfd1c")) },
                { 400000, new CheckpointInfo(new uint256("0xb6abcb933d3e3590345ca5d3abb697461093313f8886568ac8ae740d223e56f6"), new uint256("0xfaf5fcebee3ec0df5155393a99da43de18b12e620fef5edb111a791ecbfaa63a")) }
            };

            var checkpoints = new Checkpoints(KnownNetworks.StratisTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest))
            {
                UseCheckpoints = true
            });

            VerifyCheckpoints(checkpoints, verifyableCheckpoints);
        }
 public SelfEndpointTrackerTests()
 {
     this.extendedLoggerFactory = new ExtendedLoggerFactory();
     this.selfEndpointTracker   = new SelfEndpointTracker(this.extendedLoggerFactory,
                                                          new Configuration.Settings.ConnectionManagerSettings(NodeSettings.Default(new StratisRegTest())));
 }
Exemple #22
0
        public void GetLastCheckPointHeight_BitcoinRegTestNet_DoesNotLoadCheckpoints()
        {
            var checkpoints = new Checkpoints(KnownNetworks.RegTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest))
            {
                UseCheckpoints = true
            });

            int result = checkpoints.GetLastCheckpointHeight();

            Assert.Equal(0, result);
        }
        public static async Task <ITestChainContext> CreatePosAsync(Network network, Script scriptPubKey, string dataDir, bool requireStandard = true)
        {
            var nodeSettings = new NodeSettings(network, args: new string[] { $"-datadir={dataDir}" });

            ILoggerFactory    loggerFactory    = nodeSettings.LoggerFactory;
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

            network.Consensus.Options = new ConsensusOptions();

            var consensusRulesContainer = new ConsensusRulesContainer();

            foreach (var ruleType in network.Consensus.ConsensusRules.HeaderValidationRules)
            {
                // Don't check PoW of a header in this test.
                if (ruleType == typeof(CheckDifficultyPowRule))
                {
                    continue;
                }

                consensusRulesContainer.HeaderValidationRules.Add(Activator.CreateInstance(ruleType) as HeaderValidationConsensusRule);
            }
            foreach (Type ruleType in network.Consensus.ConsensusRules.FullValidationRules)
            {
                consensusRulesContainer.FullValidationRules.Add(Activator.CreateInstance(ruleType) as FullValidationConsensusRule);
            }
            foreach (Type ruleType in network.Consensus.ConsensusRules.PartialValidationRules)
            {
                consensusRulesContainer.PartialValidationRules.Add(Activator.CreateInstance(ruleType) as PartialValidationConsensusRule);
            }

            var consensusSettings = new ConsensusSettings(nodeSettings);
            var chain             = new ChainIndexer(network);
            var inMemoryCoinView  = new InMemoryCoinView(new HashHeightPair(chain.Tip));

            var chainState  = new ChainState();
            var deployments = new NodeDeployments(network, chain);

            var asyncProvider = new AsyncProvider(loggerFactory, new Mock <ISignals>().Object);

            var stakeChain = new StakeChainStore(network, chain, null, loggerFactory);
            ConsensusRuleEngine consensusRules = new PosConsensusRuleEngine(network, loggerFactory, dateTimeProvider, chain, deployments, consensusSettings, new Checkpoints(),
                                                                            inMemoryCoinView, stakeChain, new StakeValidator(network, stakeChain, chain, inMemoryCoinView, loggerFactory), chainState, new InvalidBlockHashStore(dateTimeProvider),
                                                                            new NodeStats(dateTimeProvider, NodeSettings.Default(network), new Mock <IVersionProvider>().Object), new RewindDataIndexCache(dateTimeProvider, network, new FinalizedBlockInfoRepository(new HashHeightPair()), new Checkpoints()), asyncProvider, consensusRulesContainer).SetupRulesEngineParent();

            ConsensusManager consensus = ConsensusManagerHelper.CreateConsensusManager(network, dataDir, chainState, chainIndexer: chain, consensusRules: consensusRules, inMemoryCoinView: inMemoryCoinView);

            var genesis = new ChainedHeader(network.GetGenesis().Header, network.GenesisHash, 0);

            chainState.BlockStoreTip = genesis;
            await consensus.InitializeAsync(genesis).ConfigureAwait(false);

            var mempoolSettings = new MempoolSettings(nodeSettings)
            {
                RequireStandard = requireStandard
            };
            var blockPolicyEstimator = new BlockPolicyEstimator(mempoolSettings, loggerFactory, nodeSettings);
            var mempool     = new TxMempool(dateTimeProvider, blockPolicyEstimator, loggerFactory, nodeSettings);
            var mempoolLock = new MempoolSchedulerLock();

            // The mempool rule constructors aren't parameterless, so we have to manually inject the dependencies for every rule
            var mempoolRules = new List <MempoolRule>
            {
                new CheckConflictsMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new StraxCoinViewMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CreateMempoolEntryMempoolRule(network, mempool, mempoolSettings, chain, consensusRules, loggerFactory),
                new CheckSigOpsMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new StraxTransactionFeeMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckRateLimitMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckAncestorsMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckReplacementMempoolRule(network, mempool, mempoolSettings, chain, loggerFactory),
                new CheckAllInputsMempoolRule(network, mempool, mempoolSettings, chain, consensusRules, deployments, loggerFactory),
                new CheckTxOutDustRule(network, mempool, mempoolSettings, chain, loggerFactory),
            };

            // We also have to check that the manually instantiated rules match the ones in the network, or the test isn't valid
            for (int i = 0; i < network.Consensus.MempoolRules.Count; i++)
            {
                if (network.Consensus.MempoolRules[i] != mempoolRules[i].GetType())
                {
                    throw new Exception("Mempool rule type mismatch");
                }
            }

            var nodeDeployments = new NodeDeployments(network, chain);

            var mempoolValidator = new MempoolValidator(mempool, mempoolLock, dateTimeProvider, mempoolSettings, chain, inMemoryCoinView, loggerFactory, nodeSettings, consensusRules, mempoolRules, new Signals.Signals(loggerFactory, null), nodeDeployments);

            var            blocks = new List <Block>();
            var            srcTxs = new List <Transaction>();
            DateTimeOffset now    = DateTimeOffset.UtcNow;

            for (int i = 0; i < 50; i++)
            {
                uint  nonce = 0;
                Block block = network.CreateBlock();
                block.Header.HashPrevBlock = chain.Tip.HashBlock;
                block.Header.Bits          = block.Header.GetWorkRequired(network, chain.Tip);
                block.Header.UpdateTime(now, network, chain.Tip);

                Transaction coinbase = network.CreateTransaction();
                coinbase.AddInput(TxIn.CreateCoinbase(chain.Height + 1));
                coinbase.AddOutput(new TxOut(network.Consensus.ProofOfWorkReward, scriptPubKey));
                block.AddTransaction(coinbase);
                block.UpdateMerkleRoot();
                while (!block.CheckProofOfWork())
                {
                    block.Header.Nonce = ++nonce;
                }
                block.Header.PrecomputeHash();
                blocks.Add(block);
                chain.SetTip(block.Header);
                srcTxs.Add(block.Transactions[0]);

                inMemoryCoinView.SaveChanges(new List <UnspentOutput>()
                {
                    new UnspentOutput(new OutPoint(block.Transactions[0], 0), new Coins((uint)(i + 1), block.Transactions[0].Outputs.First(), block.Transactions[0].IsCoinBase))
                }, new HashHeightPair(chain.Tip.Previous), new HashHeightPair(chain.Tip));
            }

            return(new TestChainContext {
                MempoolValidator = mempoolValidator, MempoolSettings = mempoolSettings, ChainIndexer = chain, SrcTxs = srcTxs
            });
        }
Exemple #24
0
        public void GetLastCheckPointHeight_StratisTestnet_ReturnsLastCheckPointHeight()
        {
            var checkpoints = new Checkpoints(KnownNetworks.StratisTest, new ConsensusSettings(NodeSettings.Default(KnownNetworks.StratisTest))
            {
                UseCheckpoints = true
            });

            int result = checkpoints.GetLastCheckpointHeight();

            Assert.Equal(1400000, result);
        }
Exemple #25
0
        public MempoolOrphans(MempoolScheduler mempoolScheduler, TxMempool memPool, ConcurrentChain chain,
                              MempoolValidator validator, CoinView coinView, DateTimeProvider dateTimeProvider, NodeSettings nodeArgs)
        {
            this.MempoolScheduler = mempoolScheduler;
            this.memPool          = memPool;
            this.chain            = chain;
            this.coinView         = coinView;
            this.dateTimeProvider = dateTimeProvider;
            this.nodeArgs         = nodeArgs;
            this.Validator        = validator;

            this.mapOrphanTransactions       = new Dictionary <uint256, OrphanTx>();
            this.mapOrphanTransactionsByPrev = new Dictionary <OutPoint, List <OrphanTx> >();          // OutPoint already correctly implements equality compare
            this.recentRejects             = new Dictionary <uint256, uint256>();
            this.hashRecentRejectsChainTip = uint256.Zero;
        }
 public PeerAddressManagerTests()
 {
     this.connectionManagerSettings = new ConnectionManagerSettings(NodeSettings.Default(new StraxRegTest()));
 }
Exemple #27
0
 public IndexStoreFeature(ConcurrentChain chain, IConnectionManager connectionManager, Signals.Signals signals, IndexRepository indexRepository,
                          IndexStoreCache indexStoreCache, IndexBlockPuller blockPuller, IndexStoreLoop indexStoreLoop, IndexStoreManager indexStoreManager,
                          IndexStoreSignaled indexStoreSignaled, INodeLifetime nodeLifetime, NodeSettings nodeSettings, ILoggerFactory loggerFactory) :
     base(chain, connectionManager, signals, indexRepository, indexStoreCache, blockPuller, indexStoreLoop, indexStoreManager,
          indexStoreSignaled, nodeLifetime, nodeSettings, loggerFactory, "IndexStore")
 {
 }
 public ConsensusManager(ICheckpoints checkpoints, ConsensusLoop consensusLoop = null, IDateTimeProvider dateTimeProvider = null, NodeSettings nodeSettings = null, Network network = null,
                         PowConsensusValidator consensusValidator = null, ChainState chainState = null)
 {
     this.ConsensusLoop      = consensusLoop;
     this.DateTimeProvider   = dateTimeProvider;
     this.NodeSettings       = nodeSettings;
     this.Network            = network;
     this.ConsensusValidator = consensusValidator;
     this.ChainState         = chainState;
     this.checkpoints        = checkpoints;
 }
        public void WhenRefreshWhitelist_AndInactivePeersInWhitelist_ThenWhitelistDoesNotContainInactivePeers()
        {
            // Arrange.
            Mock <IDateTimeProvider> mockDateTimeProvider = new Mock <IDateTimeProvider>();

            Mock <ILogger>        mockLogger        = new Mock <ILogger>();
            Mock <ILoggerFactory> mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 3000;

            IPAddress      activeIpAddressOne      = IPAddress.Parse("::ffff:192.168.0.1");
            NetworkAddress activeNetworkAddressOne = new NetworkAddress(activeIpAddressOne, 80);

            IPAddress      activeIpAddressTwo      = IPAddress.Parse("::ffff:192.168.0.2");
            NetworkAddress activeNetworkAddressTwo = new NetworkAddress(activeIpAddressTwo, 80);

            IPAddress      activeIpAddressThree      = IPAddress.Parse("::ffff:192.168.0.3");
            NetworkAddress activeNetworkAddressThree = new NetworkAddress(activeIpAddressThree, 80);

            IPAddress      activeIpAddressFour      = IPAddress.Parse("::ffff:192.168.0.4");
            NetworkAddress activeNetworkAddressFour = new NetworkAddress(activeIpAddressFour, 80);

            List <Tuple <NetworkAddress, DateTimeOffset> > activeTestDataSet = new List <Tuple <NetworkAddress, DateTimeOffset> >()
            {
                new Tuple <NetworkAddress, DateTimeOffset> (activeNetworkAddressOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <NetworkAddress, DateTimeOffset>(activeNetworkAddressTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <NetworkAddress, DateTimeOffset>(activeNetworkAddressThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <NetworkAddress, DateTimeOffset>(activeNetworkAddressFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40))
            };

            IPAddress      inactiveIpAddressOne      = IPAddress.Parse("::ffff:192.168.100.1");
            NetworkAddress inactiveNetworkAddressOne = new NetworkAddress(inactiveIpAddressOne, 80);

            IPAddress      inactiveIpAddressTwo      = IPAddress.Parse("::ffff:192.168.100.2");
            NetworkAddress inactiveNetworkAddressTwo = new NetworkAddress(inactiveIpAddressTwo, 80);

            IPAddress      inactiveIpAddressThree      = IPAddress.Parse("::ffff:192.168.100.3");
            NetworkAddress inactiveNetworkAddressThree = new NetworkAddress(inactiveIpAddressThree, 80);

            List <Tuple <NetworkAddress, DateTimeOffset> > inactiveTestDataSet = new List <Tuple <NetworkAddress, DateTimeOffset> >()
            {
                new Tuple <NetworkAddress, DateTimeOffset> (inactiveNetworkAddressOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-10)),
                new Tuple <NetworkAddress, DateTimeOffset>(inactiveNetworkAddressTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-20)),
                new Tuple <NetworkAddress, DateTimeOffset>(inactiveNetworkAddressThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-30))
            };

            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet.Concat(inactiveTestDataSet).ToList());

            IMasterFile       spiedMasterFile = null;
            Mock <IDnsServer> mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            NodeSettings nodeSettings = NodeSettings.Default();
            DnsSettings  dnsSettings  = new Mock <DnsSettings>().Object;

            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings();

            connectionSettings.Load(nodeSettings);

            WhitelistManager whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            Question question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.AAAA);
            IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question);

            resourceRecords.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet);

            foreach (Tuple <NetworkAddress, DateTimeOffset> testData in activeTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Endpoint.Address)).Should().NotBeNull("the ip address is active and should be in DNS");
            }

            foreach (Tuple <NetworkAddress, DateTimeOffset> testData in inactiveTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Endpoint.Address)).Should().BeNull("the ip address is inactive and should not be returned from DNS");
            }
        }
        public SmartContractMempoolValidator(ITxMempool memPool, MempoolSchedulerLock mempoolLock, IDateTimeProvider dateTimeProvider, MempoolSettings mempoolSettings, ConcurrentChain chain, ICoinView coinView, ILoggerFactory loggerFactory, NodeSettings nodeSettings, IConsensusRuleEngine consensusRules)
            : base(memPool, mempoolLock, dateTimeProvider, mempoolSettings, chain, coinView, loggerFactory, nodeSettings, consensusRules)
        {
            var p2pkhRule = new P2PKHNotContractRule();

            p2pkhRule.Parent = (ConsensusRuleEngine)consensusRules;
            p2pkhRule.Initialize();

            this.preTxRules = new List <ISmartContractMempoolRule>
            {
                new MempoolOpSpendRule(),
                new TxOutSmartContractExecRule(),
                p2pkhRule
            };

            this.feeTxRules = new List <ISmartContractMempoolRule>()
            {
                new SmartContractFormatRule(),
            };
        }
Exemple #31
0
 public TestNode(NodeSettings nodeSettings) : base(nodeSettings)
 {
 }
Exemple #32
0
        /// <summary>
        /// Initializes an instance of the object from the node configuration.
        /// </summary>
        /// <param name="nodeSettings">The node configuration.</param>
        public ConnectionManagerSettings(NodeSettings nodeSettings)
        {
            Guard.NotNull(nodeSettings, nameof(nodeSettings));

            this.logger = nodeSettings.LoggerFactory.CreateLogger(typeof(ConnectionManagerSettings).FullName);

            this.addNodeLock = new object();

            this.Connect = new List <IPEndPoint>();

            lock (this.addNodeLock)
            {
                this.addNode = new List <IPEndPoint>();
            }

            this.Bind      = new List <NodeServerEndpoint>();
            this.Whitelist = new List <IPEndPoint>();

            TextFileConfiguration config = nodeSettings.ConfigReader;

            try
            {
                this.Connect.AddRange(config.GetAll("connect", this.logger).Select(c => c.ToIPEndPoint(nodeSettings.Network.DefaultPort)));
            }
            catch (FormatException)
            {
                throw new ConfigurationException("Invalid 'connect' parameter.");
            }

            try
            {
                foreach (IPEndPoint addNode in config.GetAll("addnode", this.logger).Select(c => c.ToIPEndPoint(nodeSettings.Network.DefaultPort)))
                {
                    this.AddAddNode(addNode);
                }
            }
            catch (FormatException)
            {
                throw new ConfigurationException("Invalid 'addnode' parameter.");
            }

            this.Port = config.GetOrDefault <int>("port", nodeSettings.Network.DefaultPort, this.logger);

            try
            {
                IEnumerable <IPEndPoint> whitebindEndpoints = config.GetAll("whitebind", this.logger).Select(s => s.ToIPEndPoint(this.Port));

                this.Bind = whitebindEndpoints.Where(x => x.Address.AnyIP()).Select(x => new NodeServerEndpoint(x, true)).ToList();

                foreach (IPEndPoint endPoint in whitebindEndpoints.Where(x => !x.Address.AnyIP()))
                {
                    if (this.Bind.Select(x => x.Endpoint).Any(x => x.Contains(endPoint)))
                    {
                        continue;
                    }

                    this.Bind.Add(new NodeServerEndpoint(endPoint, true));
                }
            }
            catch (FormatException)
            {
                throw new ConfigurationException("Invalid 'whitebind' parameter");
            }

            try
            {
                foreach (NodeServerEndpoint endPoint in config.GetAll("bind").Select(c => new NodeServerEndpoint(c.ToIPEndPoint(this.Port), false)))
                {
                    if (this.Bind.Select(x => x.Endpoint).Any(x => x.Contains(endPoint.Endpoint)))
                    {
                        continue;
                    }

                    this.Bind.Add(endPoint);
                }
            }
            catch (FormatException)
            {
                throw new ConfigurationException("Invalid 'bind' parameter");
            }

            if (this.Bind.Count == 0)
            {
                this.Bind.Add(new NodeServerEndpoint(new IPEndPoint(IPAddress.Parse("0.0.0.0"), this.Port), false));
            }

            try
            {
                this.Whitelist.AddRange(config.GetAll("whitelist", this.logger).Select(c => c.ToIPEndPoint(nodeSettings.Network.DefaultPort)));
            }
            catch (FormatException)
            {
                throw new ConfigurationException("Invalid 'whitelist' parameter.");
            }

            string externalIp = config.GetOrDefault <string>("externalip", null, this.logger);

            if (externalIp != null)
            {
                try
                {
                    this.ExternalEndpoint = externalIp.ToIPEndPoint(this.Port);
                }
                catch (FormatException)
                {
                    throw new ConfigurationException("Invalid 'externalip' parameter");
                }
            }

            if (this.ExternalEndpoint == null)
            {
                this.ExternalEndpoint = new IPEndPoint(IPAddress.Loopback, this.Port);
            }

            this.BanTimeSeconds = config.GetOrDefault <int>("bantime", nodeSettings.Network.DefaultBanTimeSeconds, this.logger);

            // Listen option will default to true in case there are no connect option specified.
            // When running the node with connect option listen flag has to be explicitly passed to the node to enable listen flag.
            this.Listen = config.GetOrDefault <bool>("listen", !this.Connect.Any(), this.logger);

            this.MaxOutboundConnections = config.GetOrDefault <int>("maxoutboundconnections", nodeSettings.Network.DefaultMaxOutboundConnections, this.logger);
            if (this.MaxOutboundConnections <= 0)
            {
                throw new ConfigurationException("The 'maxoutboundconnections' must be greater than zero.");
            }

            this.MaxInboundConnections = config.GetOrDefault <int>("maxinboundconnections", nodeSettings.Network.DefaultMaxInboundConnections, this.logger);
            if (this.MaxInboundConnections < 0)
            {
                throw new ConfigurationException("The 'maxinboundconnections' must be greater or equal to zero.");
            }

            this.InitialConnectionTarget = config.GetOrDefault("initialconnectiontarget", 1, this.logger);
            this.SyncTimeEnabled         = config.GetOrDefault <bool>("synctime", true, this.logger);
            this.RelayTxes        = !config.GetOrDefault("blocksonly", DefaultBlocksOnly, this.logger);
            this.IpRangeFiltering = config.GetOrDefault <bool>("IpRangeFiltering", true, this.logger);

            var agentPrefix = config.GetOrDefault("agentprefix", string.Empty, this.logger).Replace("-", string.Empty);

            if (agentPrefix.Length > MaximumAgentPrefixLength)
            {
                agentPrefix = agentPrefix.Substring(0, MaximumAgentPrefixLength);
            }

            this.Agent = string.IsNullOrEmpty(agentPrefix) ? nodeSettings.Agent : $"{agentPrefix}-{nodeSettings.Agent}";
            this.logger.LogDebug("Agent set to '{0}'.", this.Agent);

            this.IsGateway = config.GetOrDefault <bool>("gateway", false, this.logger);
        }
        public async Task WhenDnsServerListening_AndDnsRequestReceived_ThenDnsServerSuccessfullyProcessesRequest_Async()
        {
            // Arrange.
            bool startedListening       = false;
            bool sentResponse           = false;
            Mock <IUdpClient> udpClient = new Mock <IUdpClient>();

            udpClient.Setup(c => c.StartListening(It.IsAny <int>())).Callback(() => startedListening = true);
            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) => sentResponse = true).ReturnsAsync(1);

            Mock <IMasterFile> masterFile = new Mock <IMasterFile>();

            masterFile.Setup(m => m.Get(It.IsAny <Question>())).Returns(new List <IResourceRecord>()
            {
                new IPAddressResourceRecord(Domain.FromString("google.com"), IPAddress.Loopback)
            });

            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            NodeSettings      nodeSettings     = NodeSettings.Default();

            nodeSettings.DataDir = Directory.GetCurrentDirectory();
            DnsSettings dnsSettings = new Mock <DnsSettings>().Object;

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolders = new Mock <DataFolder>(nodeSettings).Object;

            Mock <ILogger> logger          = new Mock <ILogger>();
            bool           receivedRequest = false;

            logger.Setup(l => l.Log(LogLevel.Trace, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())).Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((level, id, state, e, f) =>
            {
                // Don't reset if we found the trace message we were looking for
                if (!receivedRequest)
                {
                    // Not yet set, check trace message
                    receivedRequest = state.ToString().StartsWith("DNS request received");
                }
            });
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act.
            CancellationTokenSource source = new CancellationTokenSource(2000);
            DnsSeedServer           server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncLoopFactory, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolders);

            try
            {
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected
            }

            // Assert.
            server.Should().NotBeNull();
            startedListening.Should().BeTrue();
            receivedRequest.Should().BeTrue();
            sentResponse.Should().BeTrue();
            server.Metrics.DnsRequestCountSinceStart.Should().BeGreaterThan(0);
            server.Metrics.DnsRequestFailureCountSinceStart.Should().Be(0);
            server.Metrics.DnsServerFailureCountSinceStart.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestCountSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.DnsRequestFailureCountSinceLastPeriod.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsServerFailureCountSinceLastPeriod.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestElapsedTicksSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.LastDnsRequestElapsedTicks.Should().BeGreaterThan(0);
        }
 // ReSharper disable once MemberCanBeMadeStatic.Local
 private INode CreateNode(NodeSettings nodeSettings)
 {
     return(new IpNode(nodeSettings, _settings.TimeDelta));
 }