示例#1
0
        /// <inheritdoc />
        /// <exception cref="ConsensusErrors.BadBlockSigOps">The block contains more signature check operations than allowed.</exception>
        public override Task RunAsync(RuleContext context)
        {
            if (context.SkipValidation)
            {
                return(Task.CompletedTask);
            }

            Block            block   = context.ValidationContext.BlockToValidate;
            ConsensusOptions options = this.Parent.Network.Consensus.Options;

            long nSigOps = 0;

            foreach (Transaction tx in block.Transactions)
            {
                nSigOps += this.GetLegacySigOpCount(tx);
            }

            if ((nSigOps * options.WitnessScaleFactor) > options.MaxBlockSigopsCost)
            {
                this.Logger.LogTrace("(-)[BAD_BLOCK_SIGOPS]");
                ConsensusErrors.BadBlockSigOps.Throw();
            }

            return(Task.CompletedTask);
        }
        public PowMiningTest(PowMiningTestFixture fixture)
        {
            this.fixture = fixture;
            this.network = fixture.Network;

            this.initialNetworkOptions = this.network.Consensus.Options;
            if (this.initialNetworkOptions == null)
            {
                this.network.Consensus.Options = new ConsensusOptions();
            }

            this.asyncProvider = new Mock <IAsyncProvider>();

            this.consensusManager = new Mock <IConsensusManager>();
            this.consensusManager.SetupGet(c => c.Tip).Returns(() => this.chainIndexer.Tip);
            this.consensusRules = new Mock <IConsensusRuleEngine>();

            this.mempool = new Mock <ITxMempool>();
            this.mempool.SetupGet(mp => mp.MapTx).Returns(new TxMempool.IndexedTransactionSet());

            this.minerSettings = new MinerSettings(NodeSettings.Default(this.network));

            this.chainIndexer = fixture.ChainIndexer;

            this.nodeLifetime = new Mock <INodeLifetime>();
            this.nodeLifetime.Setup(n => n.ApplicationStopping).Returns(new CancellationToken()).Verifiable();

            this.initialBlockDownloadState = new Mock <IInitialBlockDownloadState>();
            this.initialBlockDownloadState.Setup(s => s.IsInitialBlockDownload()).Returns(false);

            this.mempoolLock = new MempoolSchedulerLock();
        }
示例#3
0
 public GenesisSmartContractDtoProvider(IOptionsSnapshot <ConsensusOptions> consensusOptions,
                                        IOptionsSnapshot <ContractOptions> contractOptions, ISideChainInitializationDataProvider sideChainInitializationDataProvider)
 {
     _sideChainInitializationDataProvider = sideChainInitializationDataProvider;
     _consensusOptions = consensusOptions.Value;
     _contractOptions  = contractOptions.Value;
 }
 public GenesisSmartContractDtoProvider(IOptionsSnapshot <ConsensusOptions> dposOptions,
                                        IOptionsSnapshot <EconomicOptions> economicOptions, IOptionsSnapshot <ContractOptions> contractOptions)
 {
     _consensusOptions = dposOptions.Value;
     _economicOptions  = economicOptions.Value;
     _contractOptions  = contractOptions.Value;
 }
示例#5
0
        public PowMiningTest(PowMiningTestFixture fixture)
        {
            this.fixture = fixture;
            this.network = fixture.Network;

            this.initialNetworkOptions = this.network.Consensus.Options;
            if (this.initialNetworkOptions == null)
            {
                this.network.Consensus.Options = new ConsensusOptions();
            }

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

            this.consensusLoop = new Mock <IConsensusLoop>();
            this.consensusLoop.SetupGet(c => c.Tip).Returns(() => this.chain.Tip);
            this.consensusRules = new Mock <IConsensusRules>();

            this.mempool = new Mock <ITxMempool>();
            this.mempool.SetupGet(mp => mp.MapTx).Returns(new TxMempool.IndexedTransactionSet());

            this.chain = fixture.Chain;

            this.nodeLifetime = new Mock <INodeLifetime>();
            this.nodeLifetime.Setup(n => n.ApplicationStopping).Returns(new CancellationToken()).Verifiable();

            this.mempoolLock = new MempoolSchedulerLock();
        }
        public void AddTransactions_WithoutTransactionsInMempool_DoesNotAddEntriesToBlock()
        {
            var newOptions = new ConsensusOptions()
            {
                MaxBlockWeight = 1500
            };

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ConcurrentChain chain = GenerateChainWithHeight(5, this.network, new Key());
                this.consensusLoop.Setup(c => c.Tip)
                .Returns(chain.GetBlock(5));
                var indexedTransactionSet = new TxMempool.IndexedTransactionSet();
                this.txMempool.Setup(t => t.MapTx)
                .Returns(indexedTransactionSet);

                var blockDefinition = new PowTestBlockDefinition(this.consensusLoop.Object, this.dateTimeProvider.Object, this.LoggerFactory.Object, this.txMempool.Object,
                                                                 new MempoolSchedulerLock(), this.network, this.consensusRules.Object);

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

                Assert.Empty(result.Block.Transactions);
                Assert.Equal(0, result.Selected);
                Assert.Equal(0, result.Updated);
            });
        }
        public void CreateNewBlock_WithScript_ValidatesTemplateUsingRuleContext()
        {
            var newOptions = new ConsensusOptions();

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ConcurrentChain chain = GenerateChainWithHeight(5, this.testNet, this.key);
                this.SetupRulesEngine(chain);

                this.dateTimeProvider.Setup(d => d.GetAdjustedTimeAsUnixTimestamp())
                .Returns(new DateTime(2017, 1, 7, 0, 0, 1, DateTimeKind.Utc).ToUnixTimestamp());
                this.consensusLoop.Setup(c => c.Tip)
                .Returns(chain.GetBlock(5));

                Transaction transaction = CreateTransaction(this.testNet, this.key, 5, new Money(400 * 1000 * 1000), new Key(), new uint256(124124));
                var txFee = new Money(1000);
                SetupTxMempool(chain, this.testNet.Consensus.Options as ConsensusOptions, txFee, transaction);
                ValidationContext validationContext = null;
                var powRuleContext = new PowRuleContext(new ValidationContext(), this.testNet.Consensus, chain.Tip, this.dateTimeProvider.Object.GetTimeOffset());
                this.consensusRules
                .Setup(s => s.CreateRuleContext(It.IsAny <ValidationContext>(), It.IsAny <ChainedHeader>())).Callback <ValidationContext, ChainedHeader>((r, s) => validationContext = r)
                .Returns(powRuleContext);

                var blockDefinition = new PowBlockDefinition(this.consensusLoop.Object, this.dateTimeProvider.Object, this.LoggerFactory.Object, this.txMempool.Object, new MempoolSchedulerLock(), this.minerSettings.Object, this.testNet, this.consensusRules.Object);

                BlockTemplate blockTemplate = blockDefinition.Build(chain.Tip, this.key.ScriptPubKey);
                Assert.NotNull(this.callbackRuleContext);

                Assert.True(this.callbackRuleContext.MinedBlock);
                Assert.Equal(blockTemplate.Block.GetHash(), validationContext.Block.GetHash());
                Assert.Equal(chain.GetBlock(5).HashBlock, powRuleContext.ConsensusTip.HashBlock);
                this.consensusLoop.Verify();
            });
        }
        public void TestBlockValidity_UsesRuleContextToValidateBlock()
        {
            var newOptions = new ConsensusOptions()
            {
                MaxBlockWeight = 1500
            };

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ConcurrentChain chain = GenerateChainWithHeight(5, this.network, new Key());
                this.consensusLoop.Setup(c => c.Tip).Returns(chain.GetBlock(5));

                ValidationContext validationContext = null;
                var powRuleContext = new PowRuleContext(new ValidationContext(), this.network.Consensus, chain.Tip, this.dateTimeProvider.Object.GetTimeOffset());
                this.consensusRules
                .Setup(s => s.CreateRuleContext(It.IsAny <ValidationContext>(), It.IsAny <ChainedHeader>())).Callback <ValidationContext, ChainedHeader>((r, s) => validationContext = r)
                .Returns(powRuleContext);

                var powBlockAssembler = new PowTestBlockDefinition(this.consensusLoop.Object, this.dateTimeProvider.Object, this.LoggerFactory.Object, this.txMempool.Object, new MempoolSchedulerLock(), this.network, this.consensusRules.Object);
                Block block           = powBlockAssembler.TestBlockValidity();

                Assert.NotNull(this.callbackRuleContext);

                Assert.True(this.callbackRuleContext.MinedBlock);
                Assert.Equal(block.GetHash(), validationContext.Block.GetHash());
                Assert.Equal(chain.GetBlock(5).HashBlock, powRuleContext.ConsensusTip.HashBlock);
                Assert.Equal(1500, this.callbackRuleContext.Consensus.Options.MaxBlockWeight);
                this.consensusLoop.Verify();
            });
        }
示例#9
0
        /// <summary>
        /// Constructs a transaction memory pool entry.
        /// </summary>
        /// <param name="transaction">Transaction for the entry.</param>
        /// <param name="nFee">Fee for the transaction in the entry in the memory pool.</param>
        /// <param name="nTime">The local time when entering the memory pool.</param>
        /// <param name="entryPriority">Priority when entering the memory pool.</param>
        /// <param name="entryHeight">The chain height when entering the mempool.</param>
        /// <param name="inChainInputValue">The sum of all txin values that are already in blockchain.</param>
        /// <param name="spendsCoinbase">Whether the transaction spends a coinbase.</param>
        /// <param name="nSigOpsCost">The total signature operations cost.</param>
        /// <param name="lp">Tthe lock points that track the height and time at which tx was final.</param>
        /// <param name="consensusOptions">Proof of work consensus options used to compute transaction weight and modified size.</param>
        public TxMempoolEntry(Transaction transaction, Money nFee,
                              long nTime, double entryPriority, int entryHeight,
                              Money inChainInputValue, bool spendsCoinbase,
                              long nSigOpsCost, LockPoints lp, ConsensusOptions consensusOptions)
        {
            this.Transaction       = transaction;
            this.TransactionHash   = transaction.GetHash();
            this.Fee               = nFee;
            this.Time              = nTime;
            this.entryPriority     = entryPriority;
            this.EntryHeight       = entryHeight;
            this.InChainInputValue = inChainInputValue;
            this.SpendsCoinbase    = spendsCoinbase;
            this.SigOpCost         = nSigOpsCost;
            this.LockPoints        = lp;

            this.TxWeight = MempoolValidator.GetTransactionWeight(transaction, consensusOptions);
            this.nModSize = MempoolValidator.CalculateModifiedSize(this.Transaction.GetSerializedSize(), this.Transaction, consensusOptions);

            this.nUsageSize = transaction.GetSerializedSize(); // RecursiveDynamicUsage(*tx) + memusage::DynamicUsage(Transaction);

            this.CountWithDescendants   = 1;
            this.SizeWithDescendants    = this.GetTxSize();
            this.ModFeesWithDescendants = this.Fee;
            Money nValueIn = transaction.TotalOut + this.Fee;

            Guard.Assert(this.InChainInputValue <= nValueIn);

            this.feeDelta = 0;

            this.CountWithAncestors     = 1;
            this.SizeWithAncestors      = this.GetTxSize();
            this.ModFeesWithAncestors   = this.Fee;
            this.SigOpCostWithAncestors = this.SigOpCost;
        }
        public void AddTransactions_TransactionAlreadyInInblock_DoesNotAddTransactionToBlock()
        {
            var newOptions = new ConsensusOptions()
            {
                MaxBlockWeight = 1500
            };

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ConcurrentChain chain = GenerateChainWithHeight(5, this.network, this.key);
                this.consensusLoop.Setup(c => c.Tip)
                .Returns(chain.GetBlock(5));
                Transaction transaction = CreateTransaction(this.network, this.key, 5, new Money(400 * 1000 * 1000), new Key(), new uint256(124124));
                var txFee = new Money(1000);
                TxMempoolEntry[] entries = SetupTxMempool(chain, newOptions, txFee, transaction);

                var blockDefinition = new PowTestBlockDefinition(this.consensusLoop.Object, this.dateTimeProvider.Object, this.LoggerFactory.Object, this.txMempool.Object, new MempoolSchedulerLock(), this.network, this.consensusRules.Object);
                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);
            });
        }
示例#11
0
        private TxMempoolEntry[] SetupTxMempool(ConcurrentChain chain, ConsensusOptions newOptions, Money txFee, params Transaction[] transactions)
        {
            uint txTime     = Utils.DateTimeToUnixTime(chain.Tip.Header.BlockTime.AddSeconds(25));
            var  lockPoints = new LockPoints()
            {
                Height        = 4,
                MaxInputBlock = chain.GetBlock(4),
                Time          = chain.GetBlock(4).Header.Time
            };

            var resultingTransactionEntries = new List <TxMempoolEntry>();
            var indexedTransactionSet       = new TxMempool.IndexedTransactionSet();

            foreach (Transaction transaction in transactions)
            {
                var txPoolEntry = new TxMempoolEntry(transaction, txFee, txTime, 1, 4, new Money(400000000), false, 2, lockPoints, newOptions);
                indexedTransactionSet.Add(txPoolEntry);
                resultingTransactionEntries.Add(txPoolEntry);
            }


            this.txMempool.Setup(t => t.MapTx)
            .Returns(indexedTransactionSet);

            return(resultingTransactionEntries.ToArray());
        }
示例#12
0
        public PowMiningTest(PowMiningTestFixture fixture)
        {
            this.initialBlockSignature = Block.BlockSignature;
            this.initialTimestamp      = Transaction.TimeStamp;

            Transaction.TimeStamp = true;
            Block.BlockSignature  = true;

            this.fixture = fixture;
            this.network = fixture.Network;
            this.initialNetworkOptions = this.network.Consensus.Options;
            if (this.initialNetworkOptions == null)
            {
                this.network.Consensus.Options = new PowConsensusOptions();
            }

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

            this.consensusLoop = new Mock <IConsensusLoop>();
            this.consensusLoop.SetupGet(c => c.Tip).Returns(() => { return(this.chain.Tip); });
            this.consensusLoop.SetupGet(c => c.Validator).Returns(new PowConsensusValidator(this.network, new Checkpoints(), DateTimeProvider.Default, this.LoggerFactory.Object));

            this.mempool = new Mock <ITxMempool>();
            this.mempool.SetupGet(mp => mp.MapTx).Returns(new TxMempool.IndexedTransactionSet());

            this.chain = fixture.Chain;

            this.nodeLifetime = new Mock <INodeLifetime>();
            this.nodeLifetime.Setup(n => n.ApplicationStopping).Returns(new CancellationToken()).Verifiable();

            var mempoolLock = new MempoolSchedulerLock();

            this.blockAssembler = new Mock <PowBlockAssembler>(this.chain.Tip, this.consensusLoop.Object, DateTimeProvider.Default, this.LoggerFactory.Object, this.mempool.Object, mempoolLock, this.network);
            this.powMining      = new PowMining(this.asyncLoopFactory.Object, this.consensusLoop.Object, this.chain, DateTimeProvider.Default, this.mempool.Object, mempoolLock, this.network, this.nodeLifetime.Object, this.LoggerFactory.Object);
        }
        public GenesisSmartContractDtoProvider(IOptionsSnapshot <ConsensusOptions> dposOptions,
                                               IOptionsSnapshot <TokenInitialOptions> tokenInitialOptions, ContractsDeployer contractsDeployer)
        {
            _consensusOptions    = dposOptions.Value;
            _tokenInitialOptions = tokenInitialOptions.Value;

            _codes = contractsDeployer.GetContractCodes <GenesisSmartContractDtoProvider>();
        }
示例#14
0
 public UnitTestTokenContractInitializationProvider(
     ITokenContractInitializationDataProvider tokenContractInitializationDataProvider,
     IOptionsSnapshot <EconomicOptions> economicOptions, IOptionsSnapshot <ConsensusOptions> consensusOptions) : base(
         tokenContractInitializationDataProvider)
 {
     _economicOptions  = economicOptions.Value;
     _consensusOptions = consensusOptions.Value;
 }
示例#15
0
 /// <summary>
 ///     Computes the transaction size based on <see cref="ConsensusOptions" />.
 ///     Takes into account witness options in the computation.
 /// </summary>
 /// <param name="tx">Transaction.</param>
 /// <param name="consensusOptions">Proof of work consensus options.</param>
 /// <returns>Transaction weight.</returns>
 /// <seealso cref="Transaction.GetSerializedSize" />
 public static int GetTransactionWeight(Transaction tx, ConsensusOptions consensusOptions)
 {
     return(tx.GetSerializedSize(
                (ProtocolVersion)
                ((uint)ProtocolVersion.PROTOCOL_VERSION | ConsensusOptions.SerializeTransactionNoWitness),
                SerializationType.Network) * (consensusOptions.WitnessScaleFactor - 1) +
            tx.GetSerializedSize(ProtocolVersion.PROTOCOL_VERSION, SerializationType.Network));
 }
 public GenesisSmartContractDtoProvider(IOptionsSnapshot <ConsensusOptions> consensusOptions,
                                        IOptionsSnapshot <ContractOptions> contractOptions, ISideChainInitializationDataProvider sideChainInitializationDataProvider)
 {
     _sideChainInitializationDataProvider = sideChainInitializationDataProvider;
     _consensusOptions = consensusOptions.Value;
     _contractOptions  = contractOptions.Value;
     _codes            = ContractsDeployer.GetContractCodes <GenesisSmartContractDtoProvider>(_contractOptions
                                                                                              .GenesisContractDir);
 }
 public GenesisSmartContractDtoProvider(IOptionsSnapshot <ConsensusOptions> dposOptions,
                                        IOptionsSnapshot <EconomicOptions> economicOptions, IOptionsSnapshot <ContractOptions> contractOptions)
 {
     _consensusOptions = dposOptions.Value;
     _economicOptions  = economicOptions.Value;
     _contractOptions  = contractOptions.Value;
     _codes            = ContractsDeployer.GetContractCodes <GenesisSmartContractDtoProvider>(_contractOptions
                                                                                              .GenesisContractDir);
 }
示例#18
0
        public GenesisSmartContractDtoProvider(IOptionsSnapshot <ConsensusOptions> consensusOptions,
                                               IOptionsSnapshot <EconomicOptions> economicOptions, ContractsDeployer contractsDeployer,
                                               IAccountService accountService)
        {
            _accountService   = accountService;
            _consensusOptions = consensusOptions.Value;
            _economicOptions  = economicOptions.Value;

            _codes = contractsDeployer.GetContractCodes <GenesisSmartContractDtoProvider>();
        }
示例#19
0
        public static IApplicationBuilder UseConsensus(this IApplicationBuilder builder, Action <ConsensusOptions> setupAction)
        {
            var options = new ConsensusOptions();

            setupAction?.Invoke(options);

            var consensusContext = builder.ApplicationServices.GetService <IConsensusContext>();
            var stateObservable  = builder.ApplicationServices.GetService <IStateObservable>();
            var logReplicable    = builder.ApplicationServices.GetService <ILogReplicable>();

            consensusContext.Run(options, stateObservable, logReplicable);
            return(builder);
        }
示例#20
0
        private void ExecuteWithConsensusOptions(ConsensusOptions newOptions, Action action)
        {
            ConsensusOptions options = this.testNet.Consensus.Options;

            try
            {
                this.testNet.Consensus.Options = newOptions;

                action();
            }
            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.testNet.Consensus.Options            = options;
                this.testNet.Consensus.BIP9Deployments[0] = null;
            }
        }
示例#21
0
        public void ComputeBlockVersion_UsingChainTipAndConsensus_Bip9DeploymentActive_UpdatesHeightAndVersion()
        {
            ConsensusOptions options          = this.testNet.Consensus.Options;
            int minerConfirmationWindow       = this.testNet.Consensus.MinerConfirmationWindow;
            int ruleChangeActivationThreshold = this.testNet.Consensus.RuleChangeActivationThreshold;

            try
            {
                var newOptions = new ConsensusOptions();
                this.testNet.Consensus.Options            = newOptions;
                this.testNet.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)));

                // As we are effectively using TestNet the other deployments need to be disabled
                this.testNet.Consensus.BIP9Deployments[BitcoinBIP9Deployments.CSV]    = null;
                this.testNet.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit] = null;

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

                ConcurrentChain chain = GenerateChainWithHeightAndActivatedBip9(5, this.testNet, new Key(), this.testNet.Consensus.BIP9Deployments[0]);
                this.SetupRulesEngine(chain);

                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);

                (int Height, int Version)result = blockDefinition.ComputeBlockVersion(chain.GetBlock(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.testNet.Consensus.Options                       = options;
                this.testNet.Consensus.BIP9Deployments[0]            = null;
                this.testNet.Consensus.MinerConfirmationWindow       = minerConfirmationWindow;
                this.testNet.Consensus.RuleChangeActivationThreshold = ruleChangeActivationThreshold;
            }
        }
        GenerateConsensusInitializationCallList(ConsensusOptions consensusOptions)
        {
            var consensusMethodCallList = new List <ContractInitializationMethodCall>();

            consensusMethodCallList.Add(nameof(AEDPoSContractContainer.AEDPoSContractStub.InitialAElfConsensusContract),
                                        new InitialAElfConsensusContractInput
            {
                IsTermStayOne = true
            });
            consensusMethodCallList.Add(nameof(AEDPoSContractContainer.AEDPoSContractStub.FirstRound),
                                        new MinerList
            {
                Pubkeys =
                {
                    consensusOptions.InitialMinerList.Select(ByteStringHelper.FromHexString)
                }
            }.GenerateFirstRoundOfNewTerm(consensusOptions.MiningInterval,
                                          consensusOptions.StartTimestamp));
            return(consensusMethodCallList);
        }
示例#23
0
        GenerateConsensusInitializationCallList(ConsensusOptions consensusOptions)
        {
            var consensusMethodCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();

            consensusMethodCallList.Add(nameof(AEDPoSContractContainer.AEDPoSContractStub.InitialAElfConsensusContract),
                                        new InitialAElfConsensusContractInput
            {
                IsTermStayOne = true
            });
            consensusMethodCallList.Add(nameof(AEDPoSContractContainer.AEDPoSContractStub.FirstRound),
                                        new MinerList
            {
                Pubkeys =
                {
                    consensusOptions.InitialMinerList.Select(k => k.ToByteString())
                }
            }.GenerateFirstRoundOfNewTerm(consensusOptions.MiningInterval,
                                          consensusOptions.StartTimestamp));
            return(consensusMethodCallList);
        }
示例#24
0
        GenerateConsensusInitializationCallList(ConsensusOptions consensusOptions)
        {
            var consensusMethodCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();

            consensusMethodCallList.Add(nameof(AEDPoSContract.InitialAElfConsensusContract),
                                        new InitialAElfConsensusContractInput
            {
                IsTermStayOne = true
            });
            consensusMethodCallList.Add(nameof(AEDPoSContract.FirstRound),
                                        new Miners
            {
                PublicKeys =
                {
                    consensusOptions.InitialMiners.Select(k =>
                                                          ByteString.CopyFrom(ByteArrayHelpers.FromHexString(k)))
                }
            }.GenerateFirstRoundOfNewTerm(consensusOptions.MiningInterval,
                                          consensusOptions.StartTimestamp.ToUniversalTime()));
            return(consensusMethodCallList);
        }
示例#25
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;
            }
        }
示例#26
0
        public void Run(
            ConsensusOptions consensusOptions,
            IStateObservable stateObservable,
            ILogReplicable logReplicable)
        {
            _consensusOptions = consensusOptions;
            _stateObservable  = stateObservable;
            _logReplicable    = logReplicable;

            _nodeStates = new List <NodeState>();
            if (_consensusOptions.NodesAddresses != null)
            {
                foreach (var nodeAddress in _consensusOptions.NodesAddresses)
                {
                    _nodeStates.Add(new NodeState {
                        NodeAddress = nodeAddress, VoteGranted = false
                    });
                }
            }

            RandomElectionTimeout();
            State = new Follower(this, _logger);
        }
示例#27
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);
            });
        }
示例#28
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);
            });
        }
        /// <summary>
        /// Calculates the modified transaction size used for memory pool priority.
        /// Calculated by stripping off the lengths of the inputs signatures.
        /// </summary>
        /// <param name="nTxSize">Current transaction size, set to 0 to compute it.</param>
        /// <param name="trx">The transaction.</param>
        /// <param name="consensusOptions">The consensus option, needed to compute the transaction size.</param>
        /// <returns>The new transaction size.</returns>
        public static int CalculateModifiedSize(int nTxSize, Transaction trx, ConsensusOptions consensusOptions)
        {
            // In order to avoid disincentivizing cleaning up the UTXO set we don't count
            // the constant overhead for each txin and up to 110 bytes of scriptSig (which
            // is enough to cover a compressed pubkey p2sh redemption) for priority.
            // Providing any more cleanup incentive than making additional inputs free would
            // risk encouraging people to create junk outputs to redeem later.
            if (nTxSize == 0)
            {
                nTxSize = (GetTransactionWeight(trx, consensusOptions) + (consensusOptions.WitnessScaleFactor) - 1) / consensusOptions.WitnessScaleFactor;
            }

            foreach (TxIn txInput in trx.Inputs)
            {
                long offset = 41U + Math.Min(110U, txInput.ScriptSig.Length);
                if (nTxSize > offset)
                {
                    nTxSize -= (int)offset;
                }
            }

            return(nTxSize);
        }
示例#30
0
        public void AddTransactions_TransactionNotInblock_AddsTransactionToBlock()
        {
            var newOptions = new ConsensusOptions();

            this.ExecuteWithConsensusOptions(newOptions, () =>
            {
                ConcurrentChain chain = GenerateChainWithHeight(5, this.testNet, this.key);
                this.consensusManager.Setup(c => c.Tip).Returns(chain.GetBlock(5));
                Transaction transaction = CreateTransaction(this.testNet, this.key, 5, new Money(400 * 1000 * 1000), new Key(), new uint256(124124));
                var txFee = new Money(1000);
                SetupTxMempool(chain, 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);

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

                Assert.NotEmpty(result.Block.Transactions);

                Assert.Equal(transaction.ToHex(), result.Block.Transactions[0].ToHex());
                Assert.Equal(1, result.Selected);
                Assert.Equal(0, result.Updated);
            });
        }