Exemplo n.º 1
0
 public PosBlockAssembler(ConsensusLoop consensusLoop, Network network, ConcurrentChain chain,
                          MempoolScheduler mempoolScheduler, TxMempool mempool,
                          IDateTimeProvider dateTimeProvider, StakeChain stakeChain, AssemblerOptions options = null)
     : base(consensusLoop, network, chain, mempoolScheduler, mempool, dateTimeProvider, options)
 {
     this.stakeChain = stakeChain;
 }
        public TxMempoolEntry FromTx(Transaction tx, TxMempool pool = null)
        {
            Money inChainValue = (pool != null && pool.HasNoInputsOf(tx)) ? tx.TotalOut : 0;

            return(new TxMempoolEntry(tx, this.nFee, this.nTime, this.dPriority, this.nHeight,
                                      inChainValue, this.spendsCoinbase, this.sigOpCost, this.lp, new ConsensusOptions(), new ConsensusFactory()));
        }
        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();
            var asyncProvider = new AsyncProvider(nodeSettings.LoggerFactory, new Mock <ISignals>().Object, new NodeLifetime());

            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), asyncProvider).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));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Constructs a memory pool orphan manager object.
        /// </summary>
        /// <param name="mempoolLock">A lock for managing asynchronous access to memory pool.</param>
        /// <param name="memPool">Transaction memory pool for managing transactions in the memory pool.</param>
        /// <param name="chain">Thread safe access to the best chain of block headers (that the node is aware of) from genesis.</param>
        /// <param name="signals">Node notifications available to subscribe to.</param>
        /// <param name="validator">Memory pool validator for validating transactions.</param>
        /// <param name="consensusValidator">Proof of work consensus validator used for validating orphan transactions.</param>
        /// <param name="coinView">Coin view of the memory pool.</param>
        /// <param name="dateTimeProvider">Date and time information provider.</param>
        /// <param name="mempoolSettings">Settings from the memory pool.</param>
        /// <param name="loggerFactory">Factory for creating instance logger for this object.</param>
        public MempoolOrphans(
            MempoolSchedulerLock mempoolLock,
            TxMempool memPool,
            ConcurrentChain chain,
            Signals.Signals signals,
            IMempoolValidator validator,
            PowConsensusValidator consensusValidator,
            CoinView coinView,
            IDateTimeProvider dateTimeProvider,
            MempoolSettings mempoolSettings,
            ILoggerFactory loggerFactory)
        {
            this.MempoolLock        = mempoolLock;
            this.memPool            = memPool;
            this.chain              = chain;
            this.signals            = signals;
            this.consensusValidator = consensusValidator;
            this.coinView           = coinView;
            this.dateTimeProvider   = dateTimeProvider;
            this.mempoolSettings    = mempoolSettings;
            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;
            this.mempoolLogger             = loggerFactory.CreateLogger(this.GetType().FullName);
        }
Exemplo n.º 5
0
        public void MempoolConcurrencyTest()
        {
            NodeSettings settings  = NodeSettings.Default(KnownNetworks.TestNet);
            var          pool      = new TxMempool(DateTimeProvider.Default, new BlockPolicyEstimator(new MempoolSettings(settings), settings.LoggerFactory, settings), settings.LoggerFactory, settings);
            var          scheduler = new SchedulerLock();
            var          rand      = new Random();

            int value = 10000;
            var txs   = new List <Transaction>();

            for (int i = 0; i < 20; i++)
            {
                var tx = new Transaction();
                tx.AddInput(new TxIn(new Script(OpcodeType.OP_11)));
                tx.AddOutput(new TxOut(new Money(value++), new Script(OpcodeType.OP_11, OpcodeType.OP_EQUAL)));
                txs.Add(tx);
            }

            var tasks   = new List <Task>();
            var options = new ParallelOptions {
                MaxDegreeOfParallelism = 10
            };

            Parallel.ForEach(txs, options, transaction =>
            {
                var entry = new TxMempoolEntry(transaction, new Money(rand.Next(100)), 0, 0.0, 1, transaction.TotalOut, false, 4, new LockPoints(), new ConsensusOptions(), new ConsensusFactory());
                tasks.Add(scheduler.WriteAsync(() => pool.AddUnchecked(transaction.GetHash(), entry)));
            });

            Task.WaitAll(tasks.ToArray());
            Assert.Equal(20, scheduler.ReadAsync(() => pool.Size).Result);
        }
        /// <summary>
        /// Create the MempoolManager used for testing whether transactions are accepted to the memory pool.
        /// </summary>
        private void CreateMempoolManager()
        {
            this.mempoolSettings   = new MempoolSettings(this.nodeSettings);
            this.consensusSettings = new ConsensusSettings(this.nodeSettings);
            this.txMemPool         = new TxMempool(this.dateTimeProvider, new BlockPolicyEstimator(
                                                       new MempoolSettings(this.nodeSettings), this.loggerFactory, this.nodeSettings), this.loggerFactory, this.nodeSettings);
            this.concurrentChain = new ConcurrentChain(this.Network);
            this.nodeDeployments = new NodeDeployments(this.Network, this.concurrentChain);

            this.MockCoinView();
            this.MockStakeChain();
            this.MockStakeValidator();

            // Create POS consensus rules engine.
            var checkpoints = new Mock <ICheckpoints>();
            var chainState  = new ChainState();

            new FullNodeBuilderConsensusExtension.PosConsensusRulesRegistration().RegisterRules(this.Network.Consensus);
            ConsensusRuleEngine consensusRuleEngine = new PosConsensusRuleEngine(this.Network, this.loggerFactory, this.dateTimeProvider,
                                                                                 this.concurrentChain, this.nodeDeployments, this.consensusSettings, checkpoints.Object, this.coinView.Object, this.stakeChain.Object,
                                                                                 this.stakeValidator.Object, chainState, new InvalidBlockHashStore(this.dateTimeProvider), new Mock <INodeStats>().Object, new Mock <IRewindDataIndexCache>().Object)
                                                      .Register();

            // Create mempool validator.
            var mempoolLock      = new MempoolSchedulerLock();
            var mempoolValidator = new MempoolValidator(this.txMemPool, mempoolLock, this.dateTimeProvider, this.mempoolSettings, this.concurrentChain,
                                                        this.coinView.Object, this.loggerFactory, this.nodeSettings, consensusRuleEngine);

            // Create mempool manager.
            var mempoolPersistence = new Mock <IMempoolPersistence>();

            this.mempoolManager = new MempoolManager(mempoolLock, this.txMemPool, mempoolValidator, this.dateTimeProvider, this.mempoolSettings,
                                                     mempoolPersistence.Object, this.coinView.Object, this.loggerFactory, this.Network);
        }
Exemplo n.º 7
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();

            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.FullValidationRules)
            {
                consensusRulesContainer.FullValidationRules.Add(Activator.CreateInstance(ruleType) as FullValidationConsensusRule);
            }

            var asyncProvider = new AsyncProvider(nodeSettings.LoggerFactory, new Mock <ISignals>().Object, new NodeLifetime());

            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, loggerFactory), asyncProvider, consensusRulesContainer).SetupRulesEngineParent();

            // 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, txMemPool, mempoolSettings, chain, loggerFactory),
                new CheckCoinViewMempoolRule(network, txMemPool, mempoolSettings, chain, loggerFactory),
                new CreateMempoolEntryMempoolRule(network, txMemPool, mempoolSettings, chain, consensusRules, loggerFactory),
                new CheckSigOpsMempoolRule(network, txMemPool, mempoolSettings, chain, loggerFactory),
                new CheckFeeMempoolRule(network, txMemPool, mempoolSettings, chain, loggerFactory),
                new CheckRateLimitMempoolRule(network, txMemPool, mempoolSettings, chain, loggerFactory),
                new CheckAncestorsMempoolRule(network, txMemPool, mempoolSettings, chain, loggerFactory),
                new CheckReplacementMempoolRule(network, txMemPool, mempoolSettings, chain, loggerFactory),
                new CheckAllInputsMempoolRule(network, txMemPool, mempoolSettings, chain, consensusRules, 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 < this.network.Consensus.MempoolRules.Count; i++)
            {
                if (network.Consensus.MempoolRules[i] != mempoolRules[i].GetType())
                {
                    throw new Exception("Mempool rule type mismatch");
                }
            }

            var mempoolValidator = new MempoolValidator(txMemPool, mempoolLock, dateTimeProvider, mempoolSettings, chain, coins, loggerFactory, settings, consensusRules, mempoolRules, new NodeDeployments(this.network, chain));

            return(new MempoolManager(mempoolLock, txMemPool, mempoolValidator, dateTimeProvider, mempoolSettings, mempoolPersistence, coins, loggerFactory, settings.Network));
        }
Exemplo n.º 8
0
        public override void CheckTransaction(MempoolValidationContext context)
        {
            var mempoolRejectFee = this.mempool.GetMinFee(this.settings.MaxMempool * 1000000).GetFee(context.EntrySize);

            if (mempoolRejectFee > 0 && context.ModifiedFees < mempoolRejectFee)
            {
                this.logger.LogTrace("(-)[FAIL_MIN_FEE_NOT_MET]");
                context.State.Fail(MempoolErrors.MinFeeNotMet, $" {context.Fees} < {mempoolRejectFee}").Throw();
            }
            else if (this.settings.RelayPriority &&
                     context.ModifiedFees < context.MinRelayTxFee.GetFee(context.EntrySize) &&
                     !TxMempool.AllowFree(context.Entry.GetPriority(this.chainIndexer.Height + 1)))
            {
                this.logger.LogTrace("(-)[FAIL_INSUFFICIENT_PRIORITY]");
                // Require that free transactions have sufficient priority to be mined in the next block.
                context.State.Fail(MempoolErrors.InsufficientPriority).Throw();
            }

            if (context.State.AbsurdFee > 0 && context.Fees > context.State.AbsurdFee)
            {
                this.logger.LogTrace("(-)[INVALID_ABSURD_FEE]");
                context.State.Invalid(MempoolErrors.AbsurdlyHighFee, $"{context.Fees} > {context.State.AbsurdFee}")
                .Throw();
            }
        }
Exemplo n.º 9
0
        /// <inheritdoc />
        public MemPoolSaveResult Save(TxMempool memPool, string fileName = null)
        {
            fileName = fileName ?? DefaultFilename;
            IEnumerable <MempoolPersistenceEntry> toSave = memPool.MapTx.Values.ToArray().Select(tx => MempoolPersistenceEntry.FromTxMempoolEntry(tx));

            return(this.Save(toSave, fileName));
        }
Exemplo n.º 10
0
 /// <summary>
 /// Constructs a memory pool coin view.
 /// </summary>
 /// <param name="inner">The backing coin view.</param>
 /// <param name="memPool">Transaction memory pool for managing transactions in the memory pool.</param>
 /// <param name="mempoolLock">A lock for managing asynchronous access to memory pool.</param>
 /// <param name="mempoolValidator">Memory pool validator for validating transactions.</param>
 public MempoolCoinView(CoinView inner, TxMempool memPool, SchedulerLock mempoolLock, IMempoolValidator mempoolValidator)
 {
     this.Inner            = inner;
     this.memPool          = memPool;
     this.mempoolLock      = mempoolLock;
     this.mempoolValidator = mempoolValidator;
     this.Set = new UnspentOutputSet();
 }
 public BlockAssemblerFactory(ConsensusLoop consensusLoop, Network network, ConcurrentChain chain,
                              MempoolScheduler mempoolScheduler, TxMempool mempool,
                              IDateTimeProvider dateTimeProvider)
 {
     this.consensusLoop    = consensusLoop;
     this.network          = network;
     this.chain            = chain;
     this.mempoolScheduler = mempoolScheduler;
     this.mempool          = mempool;
     this.dateTimeProvider = dateTimeProvider;
 }
Exemplo n.º 12
0
        private void CheckSort(TxMempool pool, List <TxMempoolEntry> sortedSource, List <string> sortedOrder)
        {
            Assert.Equal(pool.Size, sortedOrder.Count());
            int count = 0;

            using (var it = sortedSource.GetEnumerator())
                for (; it.MoveNext(); ++count)
                {
                    Assert.Equal(it.Current.TransactionHash.ToString(), sortedOrder[count]);
                }
        }
        /// <summary>
        /// Constructs a wallet fee policy.
        /// </summary>
        /// <param name="blockPolicyEstimator">Block policy estimator.</param>
        /// <param name="mempoolValidator">Memory pool validator.</param>
        /// <param name="mempool">Memory pool.</param>
        /// <param name="network">Network node is running on.</param>
        /// <param name="nodeSettings">Settings for the the node.</param>
        public WalletFeePolicy(BlockPolicyEstimator blockPolicyEstimator, IMempoolValidator mempoolValidator, TxMempool mempool, Network network, NodeSettings nodeSettings)
        {
            this.blockPolicyEstimator = blockPolicyEstimator;
            this.mempoolValidator     = mempoolValidator;
            this.mempool = mempool;

            this.minTxFee      = nodeSettings.MinTxFeeRate;
            this.fallbackFee   = nodeSettings.FallbackTxFeeRate;
            this.payTxFee      = new FeeRate(0);
            this.maxTxFee      = new Money(0.1M, MoneyUnit.BTC);
            this.minRelayTxFee = nodeSettings.MinRelayTxFeeRate;
        }
Exemplo n.º 14
0
        public SignedMultisigTransactionBroadcasterTests()
        {
            this.loggerFactory             = Substitute.For <ILoggerFactory>();
            this.logger                    = Substitute.For <ILogger>();
            this.federationGatewaySettings = Substitute.For <IFederationGatewaySettings>();
            this.loggerFactory.CreateLogger(null).ReturnsForAnyArgs(this.logger);
            this.leaderReceiverSubscription = Substitute.For <IDisposable>();
            this.store = Substitute.For <ICrossChainTransferStore>();
            this.broadcasterManager = Substitute.For <IBroadcasterManager>();
            this.asyncProvider      = Substitute.For <IAsyncProvider>();
            this.nodeLifetime       = Substitute.For <INodeLifetime>();

            this.ibdState = Substitute.For <IInitialBlockDownloadState>();
            this.federationWalletManager = Substitute.For <IFederationWalletManager>();
            this.federationWalletManager.IsFederationWalletActive().Returns(true);

            // Setup MempoolManager.
            this.dateTimeProvider = Substitute.For <IDateTimeProvider>();
            this.nodeSettings     = new NodeSettings(networksSelector: CirrusNetwork.NetworksSelector, protocolVersion: NBitcoin.Protocol.ProtocolVersion.ALT_PROTOCOL_VERSION);

            this.mempoolSettings = new MempoolSettings(this.nodeSettings)
            {
                MempoolExpiry = MempoolValidator.DefaultMempoolExpiry
            };

            this.blockPolicyEstimator = new BlockPolicyEstimator(
                this.mempoolSettings,
                this.loggerFactory,
                this.nodeSettings);

            this.txMempool = new TxMempool(
                this.dateTimeProvider,
                this.blockPolicyEstimator,
                this.loggerFactory,
                this.nodeSettings);

            this.mempoolValidator   = Substitute.For <IMempoolValidator>();
            this.mempoolPersistence = Substitute.For <IMempoolPersistence>();
            this.coinView           = Substitute.For <ICoinView>();

            this.mempoolManager = new MempoolManager(
                new MempoolSchedulerLock(),
                this.txMempool,
                this.mempoolValidator,
                this.dateTimeProvider,
                this.mempoolSettings,
                this.mempoolPersistence,
                this.coinView,
                this.loggerFactory,
                this.nodeSettings.Network);
        }
 public PosBlockAssembler(
     ConsensusLoop consensusLoop,
     Network network,
     ConcurrentChain chain,
     MempoolAsyncLock mempoolLock,
     TxMempool mempool,
     IDateTimeProvider dateTimeProvider,
     StakeChain stakeChain,
     ILogger logger,
     AssemblerOptions options = null)
     : base(consensusLoop, network, chain, mempoolLock, mempool, dateTimeProvider, logger, options)
 {
     this.stakeChain = stakeChain;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Return an estimated smart priority.
        /// </summary>
        /// <param name="confTarget">The desired number of confirmations to be included in a block.</param>
        /// <param name="pool">Memory pool transactions.</param>
        /// <param name="answerFoundAtTarget">Block height where answer was found.</param>
        /// <returns>The smart priority.</returns>
        public double EstimateSmartPriority(int confTarget, TxMempool pool, out int answerFoundAtTarget)
        {
            answerFoundAtTarget = confTarget;

            // If mempool is limiting txs, no priority txs are allowed
            Money minPoolFee = pool.GetMinFee(this.mempoolSettings.MaxMempool * 1000000).FeePerK;

            if (minPoolFee > 0)
            {
                return(InfPriority);
            }

            return(-1);
        }
        public double EstimateSmartPriority(int confTarget, TxMempool pool, out int answerFoundAtTarget)
        {
            answerFoundAtTarget = confTarget;


            // If mempool is limiting txs, no priority txs are allowed
            var minPoolFee = pool.GetMinFee(this.nodeArgs.Mempool.MaxMempool * 1000000).FeePerK;

            if (minPoolFee > 0)
            {
                return(INF_PRIORITY);
            }

            return(-1);
        }
Exemplo n.º 18
0
 public PosBlockAssembler(
     ConsensusLoop consensusLoop,
     Network network,
     MempoolSchedulerLock mempoolLock,
     TxMempool mempool,
     IDateTimeProvider dateTimeProvider,
     StakeChain stakeChain,
     ChainedBlock chainTip,
     ILoggerFactory loggerFactory,
     AssemblerOptions options = null)
     : base(consensusLoop, network, mempoolLock, mempool, dateTimeProvider, chainTip, loggerFactory, options)
 {
     this.logger     = loggerFactory.CreateLogger(this.GetType().FullName);
     this.stakeChain = stakeChain;
 }
Exemplo n.º 19
0
        private static BlockTemplate CreateBlockTemplate(TestChainContext testChainContext, Script scriptPubKey,
                                                         TxMempool mempool, MempoolSchedulerLock mempoolLock)
        {
            PowBlockDefinition blockAssembler = new PowBlockDefinition(testChainContext.Consensus,
                                                                       testChainContext.DateTimeProvider, testChainContext.LoggerFactory as LoggerFactory, mempool, mempoolLock,
                                                                       new MinerSettings(testChainContext.NodeSettings), testChainContext.Network, testChainContext.ConsensusRules);

            BlockTemplate newBlock = blockAssembler.Build(testChainContext.Chain.Tip, scriptPubKey);

            int         nHeight    = testChainContext.Chain.Tip.Height + 1; // Height first in coinbase required for block.version=2
            Transaction txCoinbase = newBlock.Block.Transactions[0];

            txCoinbase.Inputs[0] = TxIn.CreateCoinbase(nHeight);
            return(newBlock);
        }
        public PowBlockAssembler(
            ConsensusLoop consensusLoop,
            Network network,
            MempoolAsyncLock mempoolLock,
            TxMempool mempool,
            IDateTimeProvider dateTimeProvider,
            ChainedBlock chainTip,
            ILoggerFactory loggerFactory,
            AssemblerOptions options = null)
        {
            this.logger = loggerFactory.CreateLogger(this.GetType().FullName);

            options = options ?? new AssemblerOptions();
            this.blockMinFeeRate = options.BlockMinFeeRate;

            // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity.
            this.blockMaxWeight = (uint)Math.Max(4000, Math.Min(PowMining.DefaultBlockMaxWeight - 4000, options.BlockMaxWeight));

            // Limit size to between 1K and MAX_BLOCK_SERIALIZED_SIZE-1K for sanity.
            this.blockMaxSize = (uint)Math.Max(1000, Math.Min(network.Consensus.Option <PowConsensusOptions>().MaxBlockSerializedSize - 1000, options.BlockMaxSize));

            // Whether we need to account for byte usage (in addition to weight usage).
            this.needSizeAccounting = (this.blockMaxSize < network.Consensus.Option <PowConsensusOptions>().MaxBlockSerializedSize - 1000);

            this.consensusLoop    = consensusLoop;
            this.mempoolLock      = mempoolLock;
            this.mempool          = mempool;
            this.dateTimeProvider = dateTimeProvider;
            this.options          = options;
            this.network          = network;

            this.inBlock = new TxMempool.SetEntries();

            // Reserve space for coinbase tx.
            this.blockSize       = 1000;
            this.blockWeight     = 4000;
            this.blockSigOpsCost = 400;
            this.fIncludeWitness = false;

            // These counters do not include coinbase tx.
            this.blockTx = 0;
            this.fees    = 0;

            this.ChainTip       = chainTip;
            this.pblocktemplate = new BlockTemplate {
                Block = new Block(), VTxFees = new List <Money>()
            };
        }
        private static MempoolManager CreateTestMempool(NodeSettings settings, out TxMempool txMemPool)
        {
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

            txMemPool = new TxMempool(new FeeRate(1000), settings);
            var mempoolScheduler   = new MempoolScheduler();
            var coins              = new InMemoryCoinView(settings.Network.GenesisHash);
            var chain              = new ConcurrentChain(Network.Main.GetGenesis().Header);
            var mempoolPersistence = new MempoolPersistence(settings);

            NBitcoin.Network.Main.Consensus.Options = new PosConsensusOptions();
            var consensusValidator = new PowConsensusValidator(NBitcoin.Network.Main);
            var mempoolValidator   = new MempoolValidator(txMemPool, mempoolScheduler, consensusValidator, dateTimeProvider, settings, chain, coins);
            var mempoolOrphans     = new MempoolOrphans(mempoolScheduler, txMemPool, chain, mempoolValidator, consensusValidator, coins, dateTimeProvider, settings);

            return(new MempoolManager(mempoolScheduler, txMemPool, mempoolValidator, mempoolOrphans, dateTimeProvider, settings, mempoolPersistence));
        }
        private static MempoolManager CreateTestMempool(NodeSettings settings, out TxMempool txMemPool)
        {
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;

            txMemPool = new TxMempool(new FeeRate(1000), dateTimeProvider, new BlockPolicyEstimator(new FeeRate(1000), NodeSettings.Default(), new LoggerFactory()), new LoggerFactory());
            var mempoolLock        = new MempoolAsyncLock();
            var coins              = new InMemoryCoinView(settings.Network.GenesisHash);
            var chain              = new ConcurrentChain(Network.Main.GetGenesis().Header);
            var mempoolPersistence = new MempoolPersistence(settings, new LoggerFactory());

            NBitcoin.Network.Main.Consensus.Options = new PosConsensusOptions();
            var consensusValidator = new PowConsensusValidator(NBitcoin.Network.Main);
            var mempoolValidator   = new MempoolValidator(txMemPool, mempoolLock, consensusValidator, dateTimeProvider, settings, chain, coins, new LoggerFactory());
            var mempoolOrphans     = new MempoolOrphans(mempoolLock, txMemPool, chain, new Bitcoin.Signals.Signals(), mempoolValidator, consensusValidator, coins, dateTimeProvider, settings, new LoggerFactory());

            return(new MempoolManager(mempoolLock, txMemPool, mempoolValidator, mempoolOrphans, dateTimeProvider, settings, mempoolPersistence, coins, new LoggerFactory()));
        }
        /// <summary>
        /// Mine new blocks in to the consensus database and the chain.
        /// </summary>
        public static async Task <List <Block> > MineBlocksAsync(TestChainContext testChainContext, int count, Script scriptPubKey)
        {
            BlockPolicyEstimator blockPolicyEstimator = new BlockPolicyEstimator(new MempoolSettings(testChainContext.NodeSettings), testChainContext.LoggerFactory, testChainContext.NodeSettings);
            TxMempool            mempool     = new TxMempool(testChainContext.DateTimeProvider, blockPolicyEstimator, testChainContext.LoggerFactory, testChainContext.NodeSettings);
            MempoolSchedulerLock mempoolLock = new MempoolSchedulerLock();

            // Simple block creation, nothing special yet:

            List <Block> blocks = new List <Block>();

            for (int i = 0; i < count; ++i)
            {
                PowBlockAssembler blockAssembler = CreatePowBlockAssembler(testChainContext.Network, testChainContext.Consensus, testChainContext.Chain, mempoolLock, mempool, testChainContext.DateTimeProvider, testChainContext.LoggerFactory as LoggerFactory);

                BlockTemplate newBlock = blockAssembler.CreateNewBlock(scriptPubKey);

                int         nHeight    = testChainContext.Chain.Tip.Height + 1; // Height first in coinbase required for block.version=2
                Transaction txCoinbase = newBlock.Block.Transactions[0];
                txCoinbase.Inputs[0] = TxIn.CreateCoinbase(nHeight);
                newBlock.Block.UpdateMerkleRoot();

                var maxTries = int.MaxValue;

                while (maxTries > 0 && !newBlock.Block.CheckProofOfWork())
                {
                    ++newBlock.Block.Header.Nonce;
                    --maxTries;
                }

                if (maxTries == 0)
                {
                    throw new XunitException("Test failed no blocks found");
                }

                var context = new BlockValidationContext {
                    Block = newBlock.Block
                };
                await testChainContext.Consensus.AcceptBlockAsync(context);

                Assert.Null(context.Error);

                blocks.Add(newBlock.Block);
            }

            return(blocks);
        }
Exemplo n.º 24
0
 public PosAssemblerFactory(
     ConsensusLoop consensusLoop,
     Network network,
     MempoolAsyncLock mempoolScheduler,
     TxMempool mempool,
     IDateTimeProvider dateTimeProvider,
     ILoggerFactory loggerFactory,
     StakeChain stakeChain = null)
 {
     this.consensusLoop    = consensusLoop;
     this.network          = network;
     this.mempoolScheduler = mempoolScheduler;
     this.mempool          = mempool;
     this.dateTimeProvider = dateTimeProvider;
     this.stakeChain       = stakeChain;
     this.loggerFactory    = loggerFactory;
     this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
 }
Exemplo n.º 25
0
        /// <summary>
        /// Mine new blocks in to the consensus database and the chain.
        /// </summary>
        private static async Task <List <Block> > MineBlocksAsync(TestChainContext testChainContext, int count, Script receiver, bool mutateLastBlock)
        {
            var blockPolicyEstimator = new BlockPolicyEstimator(new MempoolSettings(testChainContext.NodeSettings), testChainContext.LoggerFactory, testChainContext.NodeSettings);
            var mempool     = new TxMempool(testChainContext.DateTimeProvider, blockPolicyEstimator, testChainContext.LoggerFactory, testChainContext.NodeSettings);
            var mempoolLock = new MempoolSchedulerLock();

            // Simple block creation, nothing special yet:
            var blocks = new List <Block>();

            for (int i = 0; i < count; i++)
            {
                BlockTemplate newBlock = await MineBlockAsync(testChainContext, receiver, mempool, mempoolLock, mutateLastBlock&& i == count - 1);

                blocks.Add(newBlock.Block);
            }

            return(blocks);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Create the MempoolManager used for testing whether transactions are accepted to the memory pool.
        /// </summary>
        private void CreateMempoolManager()
        {
            this.mempoolSettings   = new MempoolSettings(this.nodeSettings);
            this.consensusSettings = new ConsensusSettings(this.nodeSettings);
            this.txMemPool         = new TxMempool(this.dateTimeProvider, new BlockPolicyEstimator(
                                                       new MempoolSettings(this.nodeSettings), this.loggerFactory, this.nodeSettings), this.loggerFactory, this.nodeSettings);
            this.chainIndexer    = new ChainIndexer(this.Network);
            this.nodeDeployments = new NodeDeployments(this.Network, this.chainIndexer);

            this.MockCoinView();
            this.MockStakeChain();
            this.MockStakeValidator();

            // Create POS consensus rules engine.
            var checkpoints = new Mock <ICheckpoints>();
            var chainState  = new ChainState();

            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.FullValidationRules)
            {
                consensusRulesContainer.FullValidationRules.Add(Activator.CreateInstance(ruleType) as FullValidationConsensusRule);
            }

            ConsensusRuleEngine consensusRuleEngine = new PosConsensusRuleEngine(this.Network, this.loggerFactory, this.dateTimeProvider,
                                                                                 this.chainIndexer, this.nodeDeployments, this.consensusSettings, checkpoints.Object, this.coinView.Object, this.stakeChain.Object,
                                                                                 this.stakeValidator.Object, chainState, new InvalidBlockHashStore(this.dateTimeProvider), new Mock <INodeStats>().Object, new Mock <IRewindDataIndexCache>().Object, this.asyncProvider, consensusRulesContainer)
                                                      .SetupRulesEngineParent();

            // Create mempool validator.
            var mempoolLock      = new MempoolSchedulerLock();
            var mempoolValidator = new MempoolValidator(this.txMemPool, mempoolLock, this.dateTimeProvider, this.mempoolSettings, this.chainIndexer,
                                                        this.coinView.Object, this.loggerFactory, this.nodeSettings, consensusRuleEngine);

            // Create mempool manager.
            var mempoolPersistence = new Mock <IMempoolPersistence>();

            this.mempoolManager = new MempoolManager(mempoolLock, this.txMemPool, mempoolValidator, this.dateTimeProvider, this.mempoolSettings,
                                                     mempoolPersistence.Object, this.coinView.Object, this.loggerFactory, this.Network);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Estimate feerate needed to be included in a block within
        /// confTarget blocks. If no answer can be given at confTarget, return an
        /// estimate at the lowest target where one can be given.
        /// </summary>
        public FeeRate EstimateSmartFee(int confTarget, TxMempool pool, out int answerFoundAtTarget)
        {
            answerFoundAtTarget = confTarget;

            // Return failure if trying to analyze a target we're not tracking
            if (confTarget <= 0 || confTarget > this.feeStats.GetMaxConfirms())
            {
                return(new FeeRate(0));
            }

            // It's not possible to get reasonable estimates for confTarget of 1
            if (confTarget == 1)
            {
                confTarget = 2;
            }

            double median = -1;

            while (median < 0 && confTarget <= this.feeStats.GetMaxConfirms())
            {
                median = this.feeStats.EstimateMedianVal(confTarget++, SufficientFeeTxs, MinSuccessPct, true,
                                                         this.nBestSeenHeight);
            }

            answerFoundAtTarget = confTarget - 1;

            // If mempool is limiting txs , return at least the min feerate from the mempool
            if (pool != null)
            {
                Money minPoolFee = pool.GetMinFee(this.mempoolSettings.MaxMempool * 1000000).FeePerK;
                if (minPoolFee > 0 && minPoolFee.Satoshi > median)
                {
                    return(new FeeRate(minPoolFee));
                }
            }

            if (median < 0)
            {
                return(new FeeRate(0));
            }

            return(new FeeRate((int)median));
        }
        private static MempoolManager CreateTestMempool(NodeSettings settings, out TxMempool txMemPool)
        {
            var mempoolSettings = new MempoolSettings(settings);
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;
            NodeSettings      nodeSettings     = NodeSettings.Default();
            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 ConcurrentChain(Network.Main.GetGenesis().Header);
            var mempoolPersistence = new MempoolPersistence(settings, loggerFactory);

            Network.Main.Consensus.Options = new PosConsensusOptions();
            ConsensusRules consensusRules   = new PowConsensusRules(Network.Main, loggerFactory, dateTimeProvider, chain, new NodeDeployments(Network.Main, chain), consensusSettings, new Checkpoints(), new InMemoryCoinView(new uint256()), new Mock <ILookaheadBlockPuller>().Object).Register(new FullNodeBuilderConsensusExtension.PowConsensusRulesRegistration());
            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));
        }
        private static MempoolManager CreateTestMempool(NodeSettings settings, out TxMempool txMemPool)
        {
            var mempoolSettings = new MempoolSettings(settings);
            IDateTimeProvider dateTimeProvider = DateTimeProvider.Default;
            NodeSettings      nodeSettings     = NodeSettings.Default();
            var loggerFactory = nodeSettings.LoggerFactory;
            ConsensusSettings consensusSettings = new ConsensusSettings().Load(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 ConcurrentChain(Network.Main.GetGenesis().Header);
            var mempoolPersistence = new MempoolPersistence(settings, loggerFactory);

            Network.Main.Consensus.Options = new PosConsensusOptions();
            var consensusValidator = new PowConsensusValidator(Network.Main, new Checkpoints(Network.Main, consensusSettings), dateTimeProvider, loggerFactory);
            var mempoolValidator   = new MempoolValidator(txMemPool, mempoolLock, consensusValidator, dateTimeProvider, mempoolSettings, chain, coins, loggerFactory, settings);
            var mempoolOrphans     = new MempoolOrphans(mempoolLock, txMemPool, chain, new Signals.Signals(), mempoolValidator, consensusValidator, coins, dateTimeProvider, mempoolSettings, loggerFactory);

            return(new MempoolManager(mempoolLock, txMemPool, mempoolValidator, mempoolOrphans, dateTimeProvider, mempoolSettings, mempoolPersistence, coins, loggerFactory, settings.Network));
        }
Exemplo n.º 30
0
 /// <summary>
 /// Constructs an instance of a memory pool manager object.
 /// </summary>
 /// <param name="mempoolLock">A lock for managing asynchronous access to memory pool.</param>
 /// <param name="memPool">Transaction memory pool for managing transactions in the memory pool.</param>
 /// <param name="validator">Memory pool validator for validating transactions.</param>
 /// <param name="orphans">Memory pool orphans for managing orphan transactions.</param>
 /// <param name="dateTimeProvider">Date and time information provider.</param>
 /// <param name="mempoolSettings">Settings for memory pool.</param>
 /// <param name="mempoolPersistence">Memory pool persistence methods for loading and saving from storage.</param>
 /// <param name="coinView">Coin view of the memory pool.</param>
 /// <param name="loggerFactory">Logger factory for creating instance logger.</param>
 public MempoolManager(
     MempoolSchedulerLock mempoolLock,
     TxMempool memPool,
     IMempoolValidator validator,
     MempoolOrphans orphans,
     IDateTimeProvider dateTimeProvider,
     MempoolSettings mempoolSettings,
     IMempoolPersistence mempoolPersistence,
     CoinView coinView,
     ILoggerFactory loggerFactory)
 {
     this.MempoolLock        = mempoolLock;
     this.memPool            = memPool;
     this.DateTimeProvider   = dateTimeProvider;
     this.mempoolSettings    = mempoolSettings;
     this.Orphans            = orphans;
     this.Validator          = validator;
     this.mempoolPersistence = mempoolPersistence;
     this.coinView           = coinView;
     this.mempoolLogger      = loggerFactory.CreateLogger(this.GetType().FullName);
 }