public NodeController(
            ChainIndexer chainIndexer,
            IChainState chainState,
            IConnectionManager connectionManager,
            IDateTimeProvider dateTimeProvider,
            IFullNode fullNode,
            ILoggerFactory loggerFactory,
            NodeSettings nodeSettings,
            Network network,
            IBlockStore blockStore = null,
            IGetUnspentTransaction getUnspentTransaction             = null,
            INetworkDifficulty networkDifficulty                     = null,
            IPooledGetUnspentTransaction pooledGetUnspentTransaction = null,
            IPooledTransaction pooledTransaction                     = null)
        {
            Guard.NotNull(fullNode, nameof(fullNode));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(nodeSettings, nameof(nodeSettings));
            Guard.NotNull(chainState, nameof(chainState));
            Guard.NotNull(connectionManager, nameof(connectionManager));
            Guard.NotNull(dateTimeProvider, nameof(dateTimeProvider));

            this.chainIndexer      = chainIndexer;
            this.chainState        = chainState;
            this.connectionManager = connectionManager;
            this.dateTimeProvider  = dateTimeProvider;
            this.fullNode          = fullNode;
            this.logger            = loggerFactory.CreateLogger(this.GetType().FullName);
            this.network           = network;
            this.nodeSettings      = nodeSettings;

            this.blockStore                  = blockStore;
            this.getUnspentTransaction       = getUnspentTransaction;
            this.networkDifficulty           = networkDifficulty;
            this.pooledGetUnspentTransaction = pooledGetUnspentTransaction;
            this.pooledTransaction           = pooledTransaction;
        }
예제 #2
0
        public void CanSaveChainIncrementally()
        {
            var chain = new ChainIndexer(this.regTest);
            var data  = new DataFolder(TestBase.CreateTestDir(this));

            using (var repo = new ChainRepository(this.loggerFactory, new LeveldbHeaderStore(this.network, data, chain), this.network))
            {
                chain.SetTip(repo.LoadAsync(chain.Genesis).GetAwaiter().GetResult());
                Assert.True(chain.Tip == chain.Genesis);
                chain = new ChainIndexer(this.regTest);
                ChainedHeader tip = this.AppendBlock(chain);
                repo.SaveAsync(chain).GetAwaiter().GetResult();
                var newChain = new ChainIndexer(this.regTest);
                newChain.SetTip(repo.LoadAsync(chain.Genesis).GetAwaiter().GetResult());
                Assert.Equal(tip, newChain.Tip);
                tip = this.AppendBlock(chain);
                repo.SaveAsync(chain).GetAwaiter().GetResult();
                newChain = new ChainIndexer(this.regTest);
                newChain.SetTip(repo.LoadAsync(chain.Genesis).GetAwaiter().GetResult());
                Assert.Equal(tip, newChain.Tip);
            }
        }
예제 #3
0
        public void GetBlockCount_ReturnsHeightFromChainState()
        {
            var logger         = new Mock <ILoggerFactory>();
            var store          = new Mock <IBlockStore>();
            var chainState     = new Mock <IChainState>();
            var addressIndexer = new Mock <IAddressIndexer>();
            var utxoIndexer    = new Mock <IUtxoIndexer>();

            ChainIndexer chainIndexer = WalletTestsHelpers.GenerateChainWithHeight(3, KnownNetworks.StratisTest);

            logger.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(Mock.Of <ILogger>);

            chainState.Setup(c => c.ConsensusTip)
            .Returns(chainIndexer.GetHeader(2));

            var controller = new BlockStoreController(KnownNetworks.StratisTest, logger.Object, store.Object, chainState.Object, chainIndexer, addressIndexer.Object, utxoIndexer.Object);

            var json   = (JsonResult)controller.GetBlockCount();
            int result = int.Parse(json.Value.ToString());

            Assert.Equal(2, result);
        }
예제 #4
0
 public StraxMinting(
     IBlockProvider blockProvider,
     IConsensusManager consensusManager,
     ChainIndexer chainIndexer,
     Network network,
     IDateTimeProvider dateTimeProvider,
     IInitialBlockDownloadState initialBlockDownloadState,
     INodeLifetime nodeLifetime,
     ICoinView coinView,
     IStakeChain stakeChain,
     IStakeValidator stakeValidator,
     MempoolSchedulerLock mempoolLock,
     ITxMempool mempool,
     IWalletManager walletManager,
     IAsyncProvider asyncProvider,
     ITimeSyncBehaviorState timeSyncBehaviorState,
     ILoggerFactory loggerFactory,
     MinerSettings minerSettings) : base(blockProvider, consensusManager, chainIndexer, network, dateTimeProvider,
                                         initialBlockDownloadState, nodeLifetime, coinView, stakeChain, stakeValidator, mempoolLock, mempool,
                                         walletManager, asyncProvider, timeSyncBehaviorState, loggerFactory, minerSettings)
 {
 }
예제 #5
0
        public void ProcessBlock_NewBlock_PreviousHashSameAsWalletTip_PassesBlockToManagerWithoutReorg()
        {
            (ChainIndexer Chain, List <Block> Blocks)result = WalletTestsHelpers.GenerateChainAndBlocksWithHeight(5, KnownNetworks.StratisMain);
            this.chainIndexer = result.Chain;
            List <Block> blocks            = result.Blocks;
            var          walletSyncManager = new WalletSyncManagerOverride(this.LoggerFactory.Object, this.walletManager.Object, this.chainIndexer, KnownNetworks.StratisMain,
                                                                           this.blockStore.Object, this.storeSettings, this.signals, this.asyncProvider);

            walletSyncManager.SetWalletTip(this.chainIndexer.GetHeader(3));

            Block blockToProcess = blocks[3];

            blockToProcess.SetPrivatePropertyValue("BlockSize", 1L);

            walletSyncManager.ProcessBlock(blockToProcess); //4th block in the list has same prevhash as which is loaded

            uint256 expectedBlockHash = this.AssertTipBlockHash(walletSyncManager, 4);

            this.AssertTipBlockHash(walletSyncManager, 4);

            this.walletManager.Verify(w => w.ProcessBlock(It.Is <Block>(b => b.GetHash() == blockToProcess.GetHash()), It.Is <ChainedHeader>(c => c.Header.GetHash() == expectedBlockHash)));
        }
예제 #6
0
        public BlockNotification(
            ILoggerFactory loggerFactory,
            ChainIndexer chainIndexer,
            IConsensusManager consensusManager,
            ISignals signals,
            IAsyncLoopFactory asyncLoopFactory,
            INodeLifetime nodeLifetime)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(consensusManager, nameof(consensusManager));
            Guard.NotNull(signals, nameof(signals));
            Guard.NotNull(asyncLoopFactory, nameof(asyncLoopFactory));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));

            this.ChainIndexer     = chainIndexer;
            this.consensusManager = consensusManager;
            this.signals          = signals;
            this.asyncLoopFactory = asyncLoopFactory;
            this.nodeLifetime     = nodeLifetime;
            this.logger           = loggerFactory.CreateLogger("Impleum.Bitcoin.FullNode");
        }
예제 #7
0
        public PoAFeature(IFederationManager federationManager, PayloadProvider payloadProvider, IConnectionManager connectionManager, ChainIndexer chainIndexer,
                          IInitialBlockDownloadState initialBlockDownloadState, IConsensusManager consensusManager, IPeerBanning peerBanning, ILoggerFactory loggerFactory,
                          IPoAMiner miner, VotingManager votingManager, Network network, IWhitelistedHashesRepository whitelistedHashesRepository,
                          IdleFederationMembersKicker idleFederationMembersKicker, IChainState chainState, IBlockStoreQueue blockStoreQueue)
        {
            this.federationManager         = federationManager;
            this.connectionManager         = connectionManager;
            this.chainIndexer              = chainIndexer;
            this.initialBlockDownloadState = initialBlockDownloadState;
            this.consensusManager          = consensusManager;
            this.peerBanning   = peerBanning;
            this.loggerFactory = loggerFactory;
            this.miner         = miner;
            this.votingManager = votingManager;
            this.whitelistedHashesRepository = whitelistedHashesRepository;
            this.network = network;
            this.idleFederationMembersKicker = idleFederationMembersKicker;
            this.chainState      = chainState;
            this.blockStoreQueue = blockStoreQueue;

            payloadProvider.DiscoverPayloads(this.GetType().Assembly);
        }
예제 #8
0
        public RewardClaimer(
            IBroadcasterManager broadcasterManager,
            ChainIndexer chainIndexer,
            IConsensusManager consensusManager,
            IInitialBlockDownloadState initialBlockDownloadState,
            IKeyValueRepository keyValueRepository,
            Network network,
            ISignals signals)
        {
            this.broadcasterManager        = broadcasterManager;
            this.chainIndexer              = chainIndexer;
            this.consensusManager          = consensusManager;
            this.initialBlockDownloadState = initialBlockDownloadState;
            this.keyValueRepository        = keyValueRepository;
            this.logger  = LogManager.GetCurrentClassLogger();
            this.network = network;
            this.signals = signals;

            this.blockConnectedSubscription = this.signals.Subscribe <BlockConnected>(this.OnBlockConnected);

            LoadLastDistributionHeight();
        }
        public void LoadChainFromDisk()
        {
            string        dir   = CreateTestDir(this);
            var           chain = new ChainIndexer(this.Network);
            ChainedHeader tip   = this.AppendBlock(chain);

            using (var engine = RocksDb.Open(new DbOptions().SetCreateIfMissing(), new DataFolder(dir).ChainPath))
            {
                using (var batch = new WriteBatch())
                {
                    ChainedHeader toSave = tip;
                    var           blocks = new List <ChainedHeader>();
                    while (toSave != null)
                    {
                        blocks.Insert(0, toSave);
                        toSave = toSave.Previous;
                    }

                    foreach (ChainedHeader block in blocks)
                    {
                        batch.Put(1, BitConverter.GetBytes(block.Height),
                                  new ChainRepository.ChainRepositoryData()
                        {
                            Hash = block.HashBlock, Work = block.ChainWorkBytes
                        }
                                  .ToBytes(this.Network.Consensus.ConsensusFactory));
                    }

                    engine.Write(batch);
                }
            }

            using (var repo = new ChainRepository(new RocksDbChainStore(chain.Network, new DataFolder(dir), chain)))
            {
                var testChain = new ChainIndexer(this.Network);
                testChain.SetTip(repo.LoadAsync(testChain.Genesis).GetAwaiter().GetResult());
                Assert.Equal(tip, testChain.Tip);
            }
        }
예제 #10
0
        public BlockStoreQueue(
            ChainIndexer chainIndexer,
            IChainState chainState,
            IBlockStoreQueueFlushCondition blockStoreQueueFlushCondition,
            StoreSettings storeSettings,
            IBlockRepository blockRepository,
            ILoggerFactory loggerFactory,
            INodeStats nodeStats,
            IAsyncProvider asyncProvider,
            IInitialBlockDownloadState initialBlockDownloadState)
        {
            Guard.NotNull(blockStoreQueueFlushCondition, nameof(blockStoreQueueFlushCondition));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(chainState, nameof(chainState));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(blockRepository, nameof(blockRepository));
            Guard.NotNull(nodeStats, nameof(nodeStats));

            this.initialBlockDownloadState     = initialBlockDownloadState;
            this.blockStoreQueueFlushCondition = blockStoreQueueFlushCondition;
            this.chainIndexer           = chainIndexer;
            this.chainState             = chainState;
            this.storeSettings          = storeSettings;
            this.blockRepository        = blockRepository;
            this.asyncProvider          = asyncProvider;
            this.batch                  = new List <ChainedHeaderBlock>();
            this.blocksCacheLock        = new object();
            this.blocksQueue            = asyncProvider.CreateAsyncQueue <ChainedHeaderBlock>();
            this.pendingBlocksCache     = new Dictionary <uint256, ChainedHeaderBlock>();
            this.logger                 = loggerFactory.CreateLogger(this.GetType().FullName);
            this.cancellation           = new CancellationTokenSource();
            this.saveAsyncLoopException = null;

            this.BatchThresholdSizeBytes = storeSettings.MaxCacheSize * 1024 * 1024;

            nodeStats.RegisterStats(this.AddComponentStats, StatsType.Component, this.GetType().Name);
        }
예제 #11
0
        public void ComputeBlockVersion_UsingChainTipAndConsensus_Bip9DeploymentActive_UpdatesHeightAndVersion()
        {
            ConsensusOptions options          = this.stratisTest.Consensus.Options;
            int minerConfirmationWindow       = this.stratisTest.Consensus.MinerConfirmationWindow;
            int ruleChangeActivationThreshold = this.stratisTest.Consensus.RuleChangeActivationThreshold;

            try
            {
                var newOptions = new PosConsensusOptions();
                this.stratisTest.Consensus.Options            = newOptions;
                this.stratisTest.Consensus.BIP9Deployments[0] = new BIP9DeploymentsParameters(19,
                                                                                              new DateTimeOffset(new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
                                                                                              new DateTimeOffset(new DateTime(2018, 1, 1, 0, 0, 0, DateTimeKind.Utc)));

                this.stratisTest.Consensus.MinerConfirmationWindow       = 2;
                this.stratisTest.Consensus.RuleChangeActivationThreshold = 2;

                ChainIndexer chainIndexer = GenerateChainWithHeightAndActivatedBip9(5, this.stratisTest, new Key(), this.stratisTest.Consensus.BIP9Deployments[0]);
                this.SetupRulesEngine(chainIndexer);

                var posBlockAssembler = new PosTestBlockAssembler(this.consensusManager.Object, this.stratisTest, new MempoolSchedulerLock(), this.mempool.Object, this.minerSettings, this.dateTimeProvider.Object, this.stakeChain.Object, this.stakeValidator.Object, this.LoggerFactory.Object);

                (int Height, int Version)result = posBlockAssembler.ComputeBlockVersion(chainIndexer.GetHeader(4));

                Assert.Equal(5, result.Height);
                int expectedVersion = (int)(ThresholdConditionCache.VersionbitsTopBits | (((uint)1) << 19));
                Assert.Equal(expectedVersion, result.Version);
                Assert.NotEqual((int)ThresholdConditionCache.VersionbitsTopBits, result.Version);
            }
            finally
            {
                // This is a static in the global context so be careful updating it. I'm resetting it after being done testing so I don't influence other tests.
                this.stratisTest.Consensus.Options                       = options;
                this.stratisTest.Consensus.BIP9Deployments[0]            = null;
                this.stratisTest.Consensus.MinerConfirmationWindow       = minerConfirmationWindow;
                this.stratisTest.Consensus.RuleChangeActivationThreshold = ruleChangeActivationThreshold;
            }
        }
예제 #12
0
        public NodeControllerTest()
        {
            this.network = KnownNetworks.TestNet;

            this.chainIndexer      = WalletTestsHelpers.GenerateChainWithHeight(3, this.network);
            this.chainState        = new Mock <IChainState>();
            this.connectionManager = new Mock <IConnectionManager>();
            this.connectionManager.Setup(c => c.Network).Returns(this.network);
            this.dateTimeProvider = new Mock <IDateTimeProvider>();
            this.fullNode         = new Mock <IFullNode>();
            this.nodeSettings     = new NodeSettings(networksSelector: Networks.Bitcoin.Networks.Bitcoin);
            this.peerBanning      = new Mock <IPeerBanning>();

            this.blockStore                  = new Mock <IBlockStore>();
            this.getUnspentTransaction       = new Mock <IGetUnspentTransaction>();
            this.networkDifficulty           = new Mock <INetworkDifficulty>();
            this.pooledGetUnspentTransaction = new Mock <IPooledGetUnspentTransaction>();
            this.pooledTransaction           = new Mock <IPooledTransaction>();
            this.asyncProvider               = new Mock <IAsyncProvider>();
            this.selfEndpointTracker         = new Mock <ISelfEndpointTracker>();

            this.controller = new NodeController(
                this.chainIndexer,
                this.chainState.Object,
                this.connectionManager.Object,
                this.dateTimeProvider.Object,
                this.fullNode.Object,
                this.LoggerFactory.Object,
                this.nodeSettings,
                this.network,
                this.asyncProvider.Object,
                this.selfEndpointTracker.Object,
                this.blockStore.Object,
                this.getUnspentTransaction.Object,
                this.networkDifficulty.Object,
                this.pooledGetUnspentTransaction.Object,
                this.pooledTransaction.Object);
        }
        public static ChainIndexer Load(this ChainIndexer chainIndexer, byte[] chain)
        {
            using (var ms = new MemoryStream(chain))
            {
                var bitcoinStream = new BitcoinStream(ms, false, chainIndexer.Network.Consensus.ConsensusFactory);

                try
                {
                    int height = 0;
                    while (true)
                    {
                        uint256.MutableUint256 id = null;
                        bitcoinStream.ReadWrite <uint256.MutableUint256>(ref id);
                        BlockHeader header = null;
                        bitcoinStream.ReadWrite(ref header);
                        if (height == 0)
                        {
                            Assert.True(header.GetHash() == chainIndexer.Tip.HashBlock);
                        }
                        else if (chainIndexer.Tip.HashBlock == header.HashPrevBlock && !(header.IsNull && header.Nonce == 0))
                        {
                            chainIndexer.Add(new ChainedHeader(header, id.Value, chainIndexer.Tip));
                        }
                        else
                        {
                            break;
                        }

                        height++;
                    }
                }
                catch (EndOfStreamException)
                {
                }

                return(chainIndexer);
            }
        }
예제 #14
0
        public void ChainedHeaderVerifySkipListForGetAncestor()
        {
            int skipListLength = 300000;

            // Want a chain of exact length so subtract the genesis block.
            ChainIndexer chainIndexer = this.CreateChain(skipListLength - 1);

            // Also want a copy in array form so can quickly verify indexing.
            var chainArray = new ChainedHeader[skipListLength];

            // Check skip height and build out array copy.
            foreach (ChainedHeader block in chainIndexer.EnumerateToTip(chainIndexer.Genesis))
            {
                if (block.Height > 0)
                {
                    Assert.True(block.Skip.Height < block.Height);
                }
                else
                {
                    Assert.Null(block.Skip);
                }
                chainArray[block.Height] = block;
            }

            // Do some random verification of GetAncestor().
            var random         = new Random();
            int randCheckCount = 1000;

            for (int i = 0; i < randCheckCount; i++)
            {
                int from = random.Next(chainIndexer.Tip.Height - 1);
                int to   = random.Next(from + 1);

                Assert.Equal(chainArray[chainIndexer.Tip.Height - 1].GetAncestor(from), chainArray[from]);
                Assert.Equal(chainArray[from].GetAncestor(to), chainArray[to]);
                Assert.Equal(chainArray[from].GetAncestor(0), chainArray[0]);
            }
        }
        public void SaveChainToDisk()
        {
            string dir   = CreateTestDir(this);
            var    chain = new ChainIndexer(this.Network);

            this.AppendBlock(chain);

            using (var repo = new ChainRepository(new RocksDbChainStore(chain.Network, new DataFolder(dir), chain)))
            {
                repo.SaveAsync(chain).GetAwaiter().GetResult();
            }

            using (var engine = RocksDb.Open(new DbOptions().SetCreateIfMissing(), new DataFolder(dir).ChainPath))
            {
                ChainedHeader tip = null;
                var           itr = engine.NewIterator();
                itr.SeekToFirst();
                while (itr.Valid())
                {
                    if (itr.Key()[0] == 1)
                    {
                        var data = new ChainRepository.ChainRepositoryData();
                        data.FromBytes(itr.Value().ToArray(), this.Network.Consensus.ConsensusFactory);

                        tip = new ChainedHeader(data.Hash, data.Work, tip);

                        if (tip.Height == 0)
                        {
                            tip.SetChainStore(new ChainStore());
                        }
                    }

                    itr.Next();
                }

                Assert.Equal(tip, chain.Tip);
            }
        }
        public FederationWalletManager(
            ILoggerFactory loggerFactory,
            Network network,
            ChainIndexer chainIndexer,
            DataFolder dataFolder,
            IWalletFeePolicy walletFeePolicy,
            IAsyncProvider asyncProvider,
            INodeLifetime nodeLifetime,
            IDateTimeProvider dateTimeProvider,
            IFederationGatewaySettings federationGatewaySettings,
            IWithdrawalExtractor withdrawalExtractor)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(dataFolder, nameof(dataFolder));
            Guard.NotNull(walletFeePolicy, nameof(walletFeePolicy));
            Guard.NotNull(asyncProvider, nameof(asyncProvider));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
            Guard.NotNull(federationGatewaySettings, nameof(federationGatewaySettings));
            Guard.NotNull(withdrawalExtractor, nameof(withdrawalExtractor));

            this.lockObject = new object();

            this.logger = loggerFactory.CreateLogger(this.GetType().FullName);

            this.network                   = network;
            this.coinType                  = (CoinType)network.Consensus.CoinType;
            this.chainIndexer              = chainIndexer;
            this.asyncProvider             = asyncProvider;
            this.nodeLifetime              = nodeLifetime;
            this.fileStorage               = new FileStorage <FederationWallet>(dataFolder.WalletPath);
            this.dateTimeProvider          = dateTimeProvider;
            this.federationGatewaySettings = federationGatewaySettings;
            this.withdrawalExtractor       = withdrawalExtractor;
            this.outpointLookup            = new Dictionary <OutPoint, TransactionData>();
            this.isFederationActive        = false;
        }
예제 #17
0
        private void SetupRulesEngine(ChainIndexer chainIndexer)
        {
            var dateTimeProvider        = new DateTimeProvider();
            var consensusRulesContainer = new ConsensusRulesContainer();

            foreach (var ruleType in this.Network.Consensus.ConsensusRules.HeaderValidationRules)
            {
                consensusRulesContainer.HeaderValidationRules.Add(Activator.CreateInstance(ruleType) as HeaderValidationConsensusRule);
            }
            foreach (var ruleType in this.Network.Consensus.ConsensusRules.PartialValidationRules)
            {
                consensusRulesContainer.PartialValidationRules.Add(Activator.CreateInstance(ruleType) as PartialValidationConsensusRule);
            }
            foreach (var ruleType in this.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 asyncProvider = new AsyncProvider(this.LoggerFactory.Object, new Mock <ISignals>().Object, new NodeLifetime());

            var powConsensusRules = new PowConsensusRuleEngine(this.testNet,
                                                               this.LoggerFactory.Object, this.dateTimeProvider.Object, chainIndexer,
                                                               new NodeDeployments(this.testNet, chainIndexer), new ConsensusSettings(new NodeSettings(this.testNet)), new Checkpoints(),
                                                               new Mock <ICoinView>().Object, new Mock <IChainState>().Object, new InvalidBlockHashStore(dateTimeProvider), new NodeStats(dateTimeProvider, LoggerFactory.Object), asyncProvider, consensusRulesContainer);

            powConsensusRules.SetupRulesEngineParent();
            this.consensusManager.SetupGet(x => x.ConsensusRules).Returns(powConsensusRules);
        }
예제 #18
0
        private MempoolManager CreateTestMempool(NodeSettings settings, out TxMempool txMemPool)
        {
            var mempoolSettings = new MempoolSettings(settings);
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;
            NodeSettings      nodeSettings     = NodeSettings.Default(settings.Network);
            ILoggerFactory    loggerFactory    = nodeSettings.LoggerFactory;
            var consensusSettings = new ConsensusSettings(nodeSettings);

            txMemPool = new TxMempool(dateTimeProvider, new BlockPolicyEstimator(new MempoolSettings(nodeSettings), loggerFactory, nodeSettings), loggerFactory, nodeSettings);
            var mempoolLock        = new MempoolSchedulerLock();
            var coins              = new InMemoryCoinView(settings.Network.GenesisHash);
            var chain              = new ChainIndexer(settings.Network);
            var chainState         = new ChainState();
            var mempoolPersistence = new MempoolPersistence(settings, loggerFactory);

            this.network.Consensus.Options = new PosConsensusOptions();
            new FullNodeBuilderConsensusExtension.PowConsensusRulesRegistration().RegisterRules(this.network.Consensus);
            ConsensusRuleEngine consensusRules = new PowConsensusRuleEngine(this.network, loggerFactory, dateTimeProvider, chain, new NodeDeployments(this.network, chain),
                                                                            consensusSettings, new Checkpoints(), coins, chainState, new InvalidBlockHashStore(dateTimeProvider), new NodeStats(dateTimeProvider)).Register();
            var mempoolValidator = new MempoolValidator(txMemPool, mempoolLock, dateTimeProvider, mempoolSettings, chain, coins, loggerFactory, settings, consensusRules);

            return(new MempoolManager(mempoolLock, txMemPool, mempoolValidator, dateTimeProvider, mempoolSettings, mempoolPersistence, coins, loggerFactory, settings.Network));
        }
        protected void AddBlocksToChain(ChainIndexer chainIndexer, int blockAmount)
        {
            uint    nonce         = RandomUtils.GetUInt32();
            uint256 prevBlockHash = chainIndexer.Tip.HashBlock;

            (this.ruleContext as UtxoRuleContext).UnspentOutputSet = new UnspentOutputSet();
            (this.ruleContext as UtxoRuleContext).UnspentOutputSet.SetCoins(new UnspentOutput[0]);

            for (int i = 0; i < blockAmount; i++)
            {
                Block       block       = chainIndexer.Network.Consensus.ConsensusFactory.CreateBlock();
                Transaction transaction = chainIndexer.Network.CreateTransaction();
                block.AddTransaction(transaction);
                block.UpdateMerkleRoot();
                block.Header.BlockTime     = new DateTimeOffset(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(i));
                block.Header.HashPrevBlock = prevBlockHash;
                block.Header.Nonce         = nonce;
                chainIndexer.SetTip(block.Header);
                prevBlockHash = block.GetHash();
                (this.ruleContext as UtxoRuleContext).UnspentOutputSet.Update(this.network, transaction, i);
                this.lastAddedTransaction = transaction;
            }
        }
예제 #20
0
        public PowConsensusFeature(
            Network network,
            IChainState chainState,
            IConnectionManager connectionManager,
            IConsensusManager consensusManager,
            NodeDeployments nodeDeployments,
            ChainIndexer chainIndexer,
            IInitialBlockDownloadState initialBlockDownloadState,
            IPeerBanning peerBanning,
            ISignals signals,
            ILoggerFactory loggerFactory) : base(network, chainState, connectionManager, signals, consensusManager, nodeDeployments)
        {
            this.chainState                = chainState;
            this.connectionManager         = connectionManager;
            this.consensusManager          = consensusManager;
            this.nodeDeployments           = nodeDeployments;
            this.chainIndexer              = chainIndexer;
            this.initialBlockDownloadState = initialBlockDownloadState;
            this.peerBanning               = peerBanning;
            this.loggerFactory             = loggerFactory;

            this.chainState.MaxReorgLength = network.Consensus.MaxReorgLength;
        }
예제 #21
0
 /// <summary>
 /// Constructs an instance of a MempoolSignaled object.
 /// Starts the block notification loop to memory pool behaviors for connected nodes.
 /// </summary>
 /// <param name="manager">Memory pool manager injected dependency.</param>
 /// <param name="chainIndexer">Concurrent chain injected dependency.</param>
 /// <param name="connection">Connection manager injected dependency.</param>
 /// <param name="nodeLifetime">Node lifetime injected dependency.</param>
 /// <param name="asyncProvider">Asynchronous loop factory injected dependency.</param>
 /// <param name="mempoolLock">The mempool lock.</param>
 /// <param name="memPool">the mempool.</param>
 /// <param name="validator">The mempool validator.</param>
 /// <param name="mempoolOrphans">The mempool orphan list.</param>
 public MempoolSignaled(
     MempoolManager manager,
     ChainIndexer chainIndexer,
     IConnectionManager connection,
     INodeLifetime nodeLifetime,
     IAsyncProvider asyncProvider,
     MempoolSchedulerLock mempoolLock,
     ITxMempool memPool,
     IMempoolValidator validator,
     MempoolOrphans mempoolOrphans,
     ISignals signals)
 {
     this.manager        = manager;
     this.chainIndexer   = chainIndexer;
     this.connection     = connection;
     this.nodeLifetime   = nodeLifetime;
     this.asyncProvider  = asyncProvider;
     this.mempoolLock    = mempoolLock;
     this.memPool        = memPool;
     this.validator      = validator;
     this.mempoolOrphans = mempoolOrphans;
     this.signals        = signals;
 }
예제 #22
0
        public void AddTransactions_WithoutTransactionsInMempool_DoesNotAddEntriesToBlock()
        {
            var newOptions = new ConsensusOptions();

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ChainIndexer chainIndexer = GenerateChainWithHeight(5, this.testNet, new Key());
                this.consensusManager.Setup(c => c.Tip)
                .Returns(chainIndexer.GetHeader(5));
                var indexedTransactionSet = new TxMempool.IndexedTransactionSet();
                this.txMempool.Setup(t => t.MapTx)
                .Returns(indexedTransactionSet);

                var blockDefinition = new PowTestBlockDefinition(this.consensusManager.Object, this.dateTimeProvider.Object, this.LoggerFactory.Object, this.txMempool.Object,
                                                                 new MempoolSchedulerLock(), this.minerSettings, this.testNet, this.consensusRules.Object, new NodeDeployments(this.testNet, chainIndexer));

                (Block Block, int Selected, int Updated)result = blockDefinition.AddTransactions();

                Assert.Empty(result.Block.Transactions);
                Assert.Equal(0, result.Selected);
                Assert.Equal(0, result.Updated);
            });
        }
예제 #23
0
        public void AddTransactions_TransactionAlreadyInInblock_DoesNotAddTransactionToBlock()
        {
            var newOptions = new ConsensusOptions();

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ChainIndexer chainIndexer = GenerateChainWithHeight(5, this.testNet, this.key);
                this.consensusManager.Setup(c => c.Tip)
                .Returns(chainIndexer.GetHeader(5));
                Transaction transaction = CreateTransaction(this.testNet, this.key, 5, new Money(400 * 1000 * 1000), new Key(), new uint256(124124));
                var txFee = new Money(1000);
                TxMempoolEntry[] entries = SetupTxMempool(chainIndexer, newOptions, txFee, transaction);

                var blockDefinition = new PowTestBlockDefinition(this.consensusManager.Object, this.dateTimeProvider.Object, this.LoggerFactory.Object, this.txMempool.Object, new MempoolSchedulerLock(), this.minerSettings, this.testNet, this.consensusRules.Object, new NodeDeployments(this.testNet, chainIndexer));
                blockDefinition.AddInBlockTxEntries(entries);

                (Block Block, int Selected, int Updated)result = blockDefinition.AddTransactions();

                Assert.Empty(result.Block.Transactions);
                Assert.Equal(0, result.Selected);
                Assert.Equal(0, result.Updated);
            });
        }
예제 #24
0
        public Unity3dController(ILoggerFactory loggerFactory, IAddressIndexer addressIndexer,
                                 IBlockStore blockStore, IChainState chainState, Network network, ICoinView coinView, WalletController walletController, ChainIndexer chainIndexer, IStakeChain stakeChain = null,
                                 IContractPrimitiveSerializer primitiveSerializer = null, IStateRepositoryRoot stateRoot = null, IContractAssemblyCache contractAssemblyCache                   = null,
                                 IReceiptRepository receiptRepository             = null, ISmartContractTransactionService smartContractTransactionService = null, ILocalExecutor localExecutor = null)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
            this.addressIndexer   = Guard.NotNull(addressIndexer, nameof(addressIndexer));
            this.blockStore       = Guard.NotNull(blockStore, nameof(blockStore));
            this.chainState       = Guard.NotNull(chainState, nameof(chainState));
            this.network          = Guard.NotNull(network, nameof(network));
            this.coinView         = Guard.NotNull(coinView, nameof(coinView));
            this.walletController = Guard.NotNull(walletController, nameof(walletController));
            this.chainIndexer     = Guard.NotNull(chainIndexer, nameof(chainIndexer));
            this.stakeChain       = stakeChain;

            this.primitiveSerializer             = primitiveSerializer;
            this.stateRoot                       = stateRoot;
            this.contractAssemblyCache           = contractAssemblyCache;
            this.receiptRepository               = receiptRepository;
            this.smartContractTransactionService = smartContractTransactionService;
            this.localExecutor                   = localExecutor;
        }
        public static ChainIndexer GenerateChainWithBlockTimeAndHeight(int blockAmount, Network network, int incrementSeconds, uint nbits)
        {
            var      chain         = new ChainIndexer(network);
            uint     nonce         = RandomUtils.GetUInt32();
            uint256  prevBlockHash = chain.Genesis.HashBlock;
            DateTime blockTime     = Utils.UnixTimeToDateTime(chain.Genesis.Header.Time).UtcDateTime;

            for (int i = 0; i < blockAmount; i++)
            {
                Block block = network.Consensus.ConsensusFactory.CreateBlock();
                block.AddTransaction(new Transaction());
                block.UpdateMerkleRoot();
                block.Header.BlockTime = new DateTimeOffset(blockTime);
                blockTime = blockTime.AddSeconds(incrementSeconds);
                block.Header.HashPrevBlock = prevBlockHash;
                block.Header.Nonce         = nonce;
                block.Header.Bits          = new Target(nbits);
                chain.SetTip(block.Header);
                prevBlockHash = block.GetHash();
            }

            return(chain);
        }
예제 #26
0
 public WalletRPCController(
     IBlockStore blockStore,
     IBroadcasterManager broadcasterManager,
     ChainIndexer chainIndexer,
     IConsensusManager consensusManager,
     IFullNode fullNode,
     ILoggerFactory loggerFactory,
     Network network,
     IScriptAddressReader scriptAddressReader,
     StoreSettings storeSettings,
     IWalletManager walletManager,
     WalletSettings walletSettings,
     IWalletTransactionHandler walletTransactionHandler) : base(fullNode: fullNode, consensusManager: consensusManager, chainIndexer: chainIndexer, network: network)
 {
     this.blockStore               = blockStore;
     this.broadcasterManager       = broadcasterManager;
     this.logger                   = loggerFactory.CreateLogger(this.GetType().FullName);
     this.scriptAddressReader      = scriptAddressReader;
     this.storeSettings            = storeSettings;
     this.walletManager            = walletManager;
     this.walletSettings           = walletSettings;
     this.walletTransactionHandler = walletTransactionHandler;
 }
예제 #27
0
        public WalletSyncManager(ILoggerFactory loggerFactory, IWalletManager walletManager, ChainIndexer chainIndexer,
                                 Network network, IBlockStore blockStore, StoreSettings storeSettings, ISignals signals, IAsyncProvider asyncProvider)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(walletManager, nameof(walletManager));
            Guard.NotNull(chainIndexer, nameof(chainIndexer));
            Guard.NotNull(network, nameof(network));
            Guard.NotNull(blockStore, nameof(blockStore));
            Guard.NotNull(storeSettings, nameof(storeSettings));
            Guard.NotNull(signals, nameof(signals));
            Guard.NotNull(asyncProvider, nameof(asyncProvider));

            this.walletManager = walletManager;
            this.chainIndexer  = chainIndexer;
            this.blockStore    = blockStore;
            this.storeSettings = storeSettings;
            this.signals       = signals;
            this.asyncProvider = asyncProvider;
            this.logger        = loggerFactory.CreateLogger(this.GetType().FullName);
            this.blocksQueue   = this.asyncProvider.CreateAndRunAsyncDelegateDequeuer <Block>($"{nameof(WalletSyncManager)}-{nameof(this.blocksQueue)}", this.OnProcessBlockAsync);

            this.blocksQueueSize = 0;
        }
예제 #28
0
        public void UpdateHeaders_UsingChainAndNetwork_PreparesStakeBlockHeaders()
        {
            this.ExecuteWithConsensusOptions(new PosConsensusOptions(), () =>
            {
                this.dateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 1, 7, 0, 0, 0, DateTimeKind.Utc)));

                ChainIndexer chainIndexer = GenerateChainWithHeight(5, this.stratisTest, new Key());

                this.stakeValidator.Setup(s => s.GetNextTargetRequired(this.stakeChain.Object, chainIndexer.Tip, this.stratisTest.Consensus, true))
                .Returns(new Target(new uint256(1123123123)))
                .Verifiable();

                var posBlockAssembler = new PosTestBlockAssembler(this.consensusManager.Object, this.stratisTest, new MempoolSchedulerLock(), this.mempool.Object, this.minerSettings, this.dateTimeProvider.Object, this.stakeChain.Object, this.stakeValidator.Object, this.LoggerFactory.Object, new NodeDeployments(this.Network, chainIndexer));

                Block block = posBlockAssembler.UpdateHeaders(chainIndexer.Tip);

                Assert.Equal(chainIndexer.Tip.HashBlock, block.Header.HashPrevBlock);
                Assert.Equal((uint)1483747200, block.Header.Time);
                Assert.Equal(2.400408204198463E+58, block.Header.Bits.Difficulty);
                Assert.Equal((uint)0, block.Header.Nonce);
                this.stakeValidator.Verify();
            });
        }
예제 #29
0
        private static ChainIndexer GenerateChainWithHeight(int blockAmount, Network network, Key key)
        {
            var     chain         = new ChainIndexer(network);
            uint    nonce         = RandomUtils.GetUInt32();
            uint256 prevBlockHash = chain.Genesis.HashBlock;

            for (int i = 0; i < blockAmount; i++)
            {
                Block       block     = network.Consensus.ConsensusFactory.CreateBlock();
                Transaction coinStake = CreateCoinStakeTransaction(network, key, chain.Height + 1, new uint256((ulong)12312312 + (ulong)i));

                block.AddTransaction(coinStake);
                block.UpdateMerkleRoot();
                block.Header.BlockTime     = new DateTimeOffset(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddDays(i));
                block.Header.HashPrevBlock = prevBlockHash;
                block.Header.Nonce         = nonce;

                chain.SetTip(block.Header);
                prevBlockHash = block.GetHash();
            }

            return(chain);
        }
        public void AddTransactions_WithoutTransactionsInMempool_DoesNotAddEntriesToBlock()
        {
            var newOptions = new PosConsensusOptions();

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ChainIndexer chainIndexer = GenerateChainWithHeight(5, this.stratisTest, new Key());
                this.consensusManager.Setup(c => c.Tip)
                .Returns(chainIndexer.GetHeader(5));
                var indexedTransactionSet = new TxMempool.IndexedTransactionSet();
                this.mempool.Setup(t => t.MapTx)
                .Returns(indexedTransactionSet);

                var posBlockAssembler = new PosTestBlockAssembler(this.consensusManager.Object, this.stratisTest, new MempoolSchedulerLock(), this.mempool.Object, this.minerSettings,
                                                                  this.dateTimeProvider.Object, this.stakeChain.Object, this.stakeValidator.Object, this.LoggerFactory.Object);

                (Block Block, int Selected, int Updated)result = posBlockAssembler.AddTransactions();

                Assert.Empty(result.Block.Transactions);
                Assert.Equal(0, result.Selected);
                Assert.Equal(0, result.Updated);
            });
        }