Exemplo n.º 1
0
        public async Task IterationSetup()
        {
            var chain = await _blockchainService.GetChainAsync();

            var tokenAmount = TransactionCount / GroupCount;

            (_prepareTransactions, _keyPairs) = await _osTestHelper.PrepareTokenForParallel(GroupCount, tokenAmount);

            _block = _osTestHelper.GenerateBlock(chain.BestChainHash, chain.BestChainHeight, _prepareTransactions);
            await _blockExecutingService.ExecuteBlockAsync(_block.Header, _prepareTransactions);

            await _osTestHelper.BroadcastTransactions(_prepareTransactions);

            _block = (await _minerService.MineAsync(chain.BestChainHash, chain.BestChainHeight,
                                                    TimestampHelper.GetUtcNow(), TimestampHelper.DurationFromSeconds(4))).Block;

            _systemTransactions = await _osTestHelper.GenerateTransferTransactions(1);

            _cancellableTransactions = await _osTestHelper.GenerateTransactionsWithoutConflictAsync(_keyPairs, tokenAmount);

            chain = await _blockchainService.GetChainAsync();

            _block = _osTestHelper.GenerateBlock(chain.BestChainHash, chain.BestChainHeight,
                                                 _systemTransactions.Concat(_cancellableTransactions));
        }
Exemplo n.º 2
0
        public async Task ExecuteBlocks_Success()
        {
            var chain = await _smartContractExecutionHelper.CreateChainAsync();

            var block        = _kernelTestHelper.GenerateBlock(chain.BestChainHeight, chain.BestChainHash);
            var transactions = new List <Transaction>
            {
                new Transaction
                {
                    From       = SampleAddress.AddressList[0],
                    To         = _smartContractAddressService.GetZeroSmartContractAddress(),
                    MethodName = nameof(ACS0Container.ACS0Stub.GetContractInfo),
                    Params     = _smartContractAddressService.GetZeroSmartContractAddress().ToByteString()
                }
            };
            var blockExecutedSet = await _blockExecutingService.ExecuteBlockAsync(block.Header, transactions);

            await _blockStateSetManger.RemoveBlockStateSetsAsync(new List <Hash> {
                blockExecutedSet.GetHash()
            });

            await _blockchainService.AddTransactionsAsync(transactions);

            await ExecuteBlocksAsync(new List <Block> {
                blockExecutedSet.Block
            });
        }
        public async Task <Chain> CreateChainAsync()
        {
            _defaultContractZeroCodeProvider.SetDefaultContractZeroRegistrationByType(null);
            var blockHeader = new BlockHeader
            {
                Height            = AElfConstants.GenesisBlockHeight,
                PreviousBlockHash = Hash.Empty,
                Time = new Timestamp {
                    Seconds = 0
                }
            };
            var transactions = new List <Transaction>
            {
                new Transaction
                {
                    From       = _defaultContractZeroCodeProvider.ContractZeroAddress,
                    To         = _defaultContractZeroCodeProvider.ContractZeroAddress,
                    MethodName = nameof(ACS0Container.ACS0Stub.DeploySystemSmartContract),
                    Params     = new SystemContractDeploymentInput
                    {
                        Name     = ZeroSmartContractAddressNameProvider.Name,
                        Category = KernelConstants.DefaultRunnerCategory,
                        Code     = ByteString.CopyFrom(ContractCodes["AElf.Contracts.Genesis"]),
                    }.ToByteString()
                },
                new Transaction
                {
                    From       = _defaultContractZeroCodeProvider.ContractZeroAddress,
                    To         = _defaultContractZeroCodeProvider.ContractZeroAddress,
                    MethodName = nameof(ACS0Container.ACS0Stub.DeploySystemSmartContract),
                    Params     = new SystemContractDeploymentInput
                    {
                        Name     = ConfigurationSmartContractAddressNameProvider.Name,
                        Category = KernelConstants.DefaultRunnerCategory,
                        Code     = ByteString.CopyFrom(ContractCodes["AElf.Contracts.Configuration"])
                    }.ToByteString()
                }
            };

            var block = await _blockExecutingService.ExecuteBlockAsync(blockHeader, transactions);

            var chain = await _blockchainService.CreateChainAsync(block.Block, transactions);

            var blockExecutionResult = await _blockchainExecutingService.ExecuteBlocksAsync(new[] { block.Block });

            await _blockExecutionResultProcessingService.ProcessBlockExecutionResultAsync(chain, blockExecutionResult);

            return(await _blockchainService.GetChainAsync());
        }
        private async Task <BlockExecutedSet> ExecuteBlockAsync(Block block)
        {
            var blockHash = block.GetHash();

            var blockState = await _blockStateSetManger.GetBlockStateSetAsync(blockHash);

            if (blockState != null)
            {
                Logger.LogDebug($"Block already executed. block hash: {blockHash}");
                return(await GetExecuteBlockSetAsync(block, blockHash));
            }

            var transactions = await _blockchainService.GetTransactionsAsync(block.TransactionIds);

            var blockExecutedSet = await _blockExecutingService.ExecuteBlockAsync(block.Header, transactions);

            var executedBlock = blockExecutedSet.Block;

            var blockHashWithoutCache = executedBlock.GetHashWithoutCache();

            if (blockHashWithoutCache == blockHash)
            {
                return(blockExecutedSet);
            }
            Logger.LogDebug(
                $"Block execution failed. Expected: {block}, actual: {executedBlock}");
            return(null);
        }
Exemplo n.º 5
0
        public async Task <Block> MineAsync(Hash previousBlockHash, long previousBlockHeight,
                                            List <Transaction> transactions, DateTime blockTime, TimeSpan timeSpan)
        {
            var block = await GenerateBlock(previousBlockHash, previousBlockHeight, blockTime);

            var systemTransactions = await GenerateSystemTransactions(previousBlockHash, previousBlockHeight);

            var pending = transactions;

            using (var cts = new CancellationTokenSource())
            {
                cts.CancelAfter(timeSpan);
                block = await _blockExecutingService.ExecuteBlockAsync(block.Header,
                                                                       systemTransactions, pending, cts.Token);
            }

            await SignBlockAsync(block);

            // TODO: TxHub needs to be updated when BestChain is found/extended, so maybe the call should be centralized
            //await _txHub.OnNewBlock(block);

            Logger.LogInformation($"Generated block: {block.ToDiagnosticString()}, " +
                                  $"previous: {block.Header.PreviousBlockHash}, " +
                                  $"transactions: {block.Body.TransactionsCount}");

            return(block);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates a new chain with the provided genesis transactions and Smart Contract Zero.
        /// </summary>
        /// <returns>The new chain async.</returns>
        /// <param name="">The new chain id which will be derived from the creator address.</param>
        /// <param name="genesisTransactions">The transactions to be executed in the genesis block.</param>
        public async Task <Chain> CreateNewChainAsync(IEnumerable <Transaction> genesisTransactions)
        {
            try
            {
                var blockHeader = new BlockHeader
                {
                    Height            = AElfConstants.GenesisBlockHeight,
                    PreviousBlockHash = Hash.Empty,
                    Time = new Timestamp {
                        Seconds = 0
                    },
                    ChainId = _blockchainService.GetChainId()
                };

                var transactions = genesisTransactions.ToList();

                var block = await _blockExecutingService.ExecuteBlockAsync(blockHeader, transactions);

                var chain = await _blockchainService.CreateChainAsync(block, transactions);

                await _blockchainExecutingService.ExecuteBlocksAttachedToLongestChain(chain, BlockAttachOperationStatus.LongestChainFound);

                return(await _blockchainService.GetChainAsync());
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Create new chain failed.");
                throw;
            }
        }
        private async Task <bool> TryExecuteBlockAsync(Block block)
        {
            var blockHash = block.GetHash();

            var blockState = await _blockchainStateManager.GetBlockStateSetAsync(blockHash);

            if (blockState != null)
            {
                return(true);
            }

            var transactions = await _blockchainService.GetTransactionsAsync(block.TransactionIds);

            var executedBlock = await _blockExecutingService.ExecuteBlockAsync(block.Header, transactions);

            var blockHashWithoutCache = executedBlock.GetHashWithoutCache();

            if (blockHashWithoutCache != blockHash)
            {
                blockState = await _blockchainStateManager.GetBlockStateSetAsync(blockHashWithoutCache);

                Logger.LogWarning($"Block execution failed. BlockStateSet: {blockState}");
                Logger.LogWarning(
                    $"Block execution failed. Block header: {executedBlock.Header}, Block body: {executedBlock.Body}");

                return(false);
            }

            return(true);
        }
Exemplo n.º 8
0
        public async Task <Block> MineAsync(RequestMiningDto requestMiningDto, List <Transaction> transactions,
                                            Timestamp blockTime)
        {
            using (var cts = new CancellationTokenSource())
            {
                cts.CancelAfter((int)requestMiningDto.BlockExecutionTime.Milliseconds());

                var block = await GenerateBlock(requestMiningDto.PreviousBlockHash,
                                                requestMiningDto.PreviousBlockHeight, blockTime);

                var systemTransactions = await GenerateSystemTransactions(requestMiningDto.PreviousBlockHash,
                                                                          requestMiningDto.PreviousBlockHeight);

                var pending = transactions;

                block = await _blockExecutingService.ExecuteBlockAsync(block.Header,
                                                                       systemTransactions, pending, cts.Token);
                await SignBlockAsync(block);

                Logger.LogInformation($"Generated block: {block.ToDiagnosticString()}, " +
                                      $"previous: {block.Header.PreviousBlockHash}, " +
                                      $"transactions: {block.Body.TransactionsCount}");
                return(block);
            }
        }
        public async Task AttachBlockWithTransactions_Test()
        {
            var chain = await _blockchainService.GetChainAsync();

            var transactions = await _osTestHelper.GenerateTransferTransactions(2);

            var block                 = _osTestHelper.GenerateBlock(chain.BestChainHash, chain.BestChainHeight, transactions);
            var executedBlock         = (await _blockExecutingService.ExecuteBlockAsync(block.Header, transactions)).Block;
            var blockWithTransactions = new BlockWithTransactions
            {
                Header = executedBlock.Header, Transactions = { transactions }
            };

            var attachFinished = false;

            await _blockSyncAttachService.AttachBlockWithTransactionsAsync(blockWithTransactions, "pubkey",
                                                                           () =>
            {
                attachFinished = true;
                return(Task.CompletedTask);
            });

            chain = await _blockchainService.GetChainAsync();

            chain.BestChainHash.ShouldBe(blockWithTransactions.GetHash());
            chain.BestChainHeight.ShouldBe(blockWithTransactions.Height);
            attachFinished.ShouldBeTrue();

            var txs = await _blockchainService.GetTransactionsAsync(transactions.Select(t => t.GetHash()));

            txs.Count.ShouldBe(2);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Creates a new chain with the provided and Smart Contract Zero.
        /// </summary>
        /// <returns>The new chain async.</returns>
        /// <param name="">The new chain id which will be derived from the creator address.</param>
        /// <param name="genesisTransactions">The transactions to be executed in the genesis block.</param>
        public async Task <Chain> CreateNewChainAsync(IEnumerable <Transaction> genesisTransactions)
        {
            try
            {
                var blockHeader = new BlockHeader
                {
                    Height            = KernelConstants.GenesisBlockHeight,
                    PreviousBlockHash = Hash.Empty,
                    Time    = Timestamp.FromDateTime(DateTime.MinValue.ToUniversalTime()),
                    ChainId = _blockchainService.GetChainId()
                };

                var block = await _blockExecutingService.ExecuteBlockAsync(blockHeader, genesisTransactions);

                var chain = await _blockchainService.CreateChainAsync(block);

                await _blockchainExecutingService.ExecuteBlocksAttachedToLongestChain(chain, BlockAttachOperationStatus.LongestChainFound);

                return(await _blockchainService.GetChainAsync());
            }
            catch (Exception e)
            {
                Logger.LogError("CreateNewChainAsync Error: " + e);
                throw;
            }
        }
Exemplo n.º 11
0
        public async Task <BlockExecutedSet> MineAsync(RequestMiningDto requestMiningDto, List <Transaction> transactions,
                                                       Timestamp blockTime)
        {
            try
            {
                using (var cts = new CancellationTokenSource())
                {
                    var expirationTime = blockTime + requestMiningDto.BlockExecutionTime;
                    if (expirationTime < TimestampHelper.GetUtcNow())
                    {
                        cts.Cancel();
                    }
                    else
                    {
                        var ts = (expirationTime - TimestampHelper.GetUtcNow()).ToTimeSpan();
                        if (ts.TotalMilliseconds > int.MaxValue)
                        {
                            ts = TimeSpan.FromMilliseconds(int.MaxValue);
                        }

                        cts.CancelAfter(ts);
                    }

                    var block = await GenerateBlock(requestMiningDto.PreviousBlockHash,
                                                    requestMiningDto.PreviousBlockHeight, blockTime);

                    var systemTransactions = await GenerateSystemTransactions(requestMiningDto.PreviousBlockHash,
                                                                              requestMiningDto.PreviousBlockHeight);

                    _systemTransactionExtraDataProvider.SetSystemTransactionCount(systemTransactions.Count,
                                                                                  block.Header);
                    var txTotalCount = transactions.Count + systemTransactions.Count;

                    var pending = txTotalCount > requestMiningDto.TransactionCountLimit
                        ? transactions
                                  .Take(requestMiningDto.TransactionCountLimit - systemTransactions.Count)
                                  .ToList()
                        : transactions;
                    var blockExecutedSet = await _blockExecutingService.ExecuteBlockAsync(block.Header,
                                                                                          systemTransactions, pending, cts.Token);

                    block = blockExecutedSet.Block;
                    await SignBlockAsync(block);

                    Logger.LogInformation($"Generated block: {block.ToDiagnosticString()}, " +
                                          $"previous: {block.Header.PreviousBlockHash}, " +
                                          $"executed transactions: {block.Body.TransactionsCount}, " +
                                          $"not executed transactions {pending.Count + systemTransactions.Count - block.Body.TransactionsCount} ");
                    return(blockExecutedSet);
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Failed while mining block.");
                throw;
            }
        }
Exemplo n.º 12
0
        public async Task TokenTransferParallelTest()
        {
            var chain = await _blockchainService.GetChainAsync();

            var tokenAmount = _transactionCount / _groupCount;

            var(prepareTransactions, keyPairs) =
                await _parallelTestHelper.PrepareTokenForParallel(_groupCount, tokenAmount);

            await _parallelTestHelper.BroadcastTransactions(prepareTransactions);

            var block = _parallelTestHelper.GenerateBlock(chain.BestChainHash, chain.BestChainHeight,
                                                          prepareTransactions);

            block = await _blockExecutingService.ExecuteBlockAsync(block.Header, prepareTransactions);

            var systemTransactions = await _parallelTestHelper.GenerateTransferTransactions(1);

            var cancellableTransactions =
                await _parallelTestHelper.GenerateTransactionsWithoutConflict(keyPairs, tokenAmount);

            var allTransaction = systemTransactions.Concat(cancellableTransactions).ToList();
            await _parallelTestHelper.BroadcastTransactions(allTransaction);

            var groupedTransactions = await _grouper.GroupAsync(
                new ChainContext { BlockHash = block.GetHash(), BlockHeight = block.Height },
                cancellableTransactions);

            groupedTransactions.Parallelizables.Count.ShouldBe(_groupCount);
            groupedTransactions.NonParallelizables.Count.ShouldBe(0);

            block = _parallelTestHelper.GenerateBlock(block.GetHash(), block.Height, allTransaction);
            block = await _blockExecutingService.ExecuteBlockAsync(block.Header, systemTransactions,
                                                                   cancellableTransactions, CancellationToken.None);

            var codeRemarks =
                await _codeRemarksManager.GetCodeRemarksAsync(Hash.FromRawBytes(_parallelTestHelper.TokenContractCode));

            codeRemarks.ShouldBeNull();

            groupedTransactions = await _grouper.GroupAsync(
                new ChainContext { BlockHash = block.GetHash(), BlockHeight = block.Height },
                cancellableTransactions);

            groupedTransactions.Parallelizables.Count.ShouldBe(_groupCount);
            groupedTransactions.NonParallelizables.Count.ShouldBe(0);

            block.TransactionIds.Count().ShouldBe(allTransaction.Count);
        }
Exemplo n.º 13
0
        private async Task <bool> ExecuteBlock(ChainBlockLink blockLink, Block block)
        {
            var blockState = await _blockchainStateManager.GetBlockStateSetAsync(block.GetHash());

            if (blockState != null)
            {
                return(true);
            }

            var blockHash     = block.GetHash();
            var executedBlock = await _blockExecutingService.ExecuteBlockAsync(block.Header, block.Body.TransactionList);

            return(executedBlock.GetHash().Equals(blockHash));
        }
Exemplo n.º 14
0
        private async Task <bool> TryExecuteBlockAsync(Block block)
        {
            var blockHash = block.GetHash();

            var blockState = await _blockchainStateManager.GetBlockStateSetAsync(blockHash);

            if (blockState != null)
            {
                return(true);
            }

            var transactions = await _blockchainService.GetTransactionsAsync(block.TransactionIds);

            var executedBlock = await _blockExecutingService.ExecuteBlockAsync(block.Header, transactions);

            return(executedBlock.GetHashWithoutCache().Equals(blockHash));
        }
Exemplo n.º 15
0
        public async Task AttachBlockAsync_Test()
        {
            var chain = await _smartContractExecutionHelper.CreateChainAsync();

            await _blockAttachService.AttachBlockAsync(_kernelTestHelper.GenerateBlock(0, Hash.Empty));

            var blockHeader = new BlockHeader
            {
                Height            = chain.BestChainHeight + 1,
                PreviousBlockHash = chain.BestChainHash,
                Time         = TimestampHelper.GetUtcNow(),
                SignerPubkey = ByteString.CopyFrom(CryptoHelper.GenerateKeyPair().PublicKey)
            };

            var transactions = new List <Transaction>
            {
                new Transaction
                {
                    From       = _smartContractAddressService.GetZeroSmartContractAddress(),
                    To         = _smartContractAddressService.GetZeroSmartContractAddress(),
                    MethodName = nameof(ACS0Container.ACS0Stub.DeploySmartContract),
                    Params     = new ContractDeploymentInput
                    {
                        Category = KernelConstants.DefaultRunnerCategory,
                        Code     = ByteString.CopyFrom(
                            _smartContractExecutionHelper.ContractCodes["AElf.Contracts.MultiToken"])
                    }.ToByteString()
                }
            };

            var blockExecutedSet = await _blockExecutingService.ExecuteBlockAsync(blockHeader, transactions);

            await _blockchainService.AddBlockAsync(blockExecutedSet.Block);

            _blockAttachService.AttachBlockAsync(blockExecutedSet.Block).ShouldThrow <Exception>();

            await _blockchainService.AddTransactionsAsync(transactions);

            await _blockAttachService.AttachBlockAsync(blockExecutedSet.Block);

            var newChain = await _blockchainService.GetChainAsync();

            newChain.BestChainHeight.ShouldBe(chain.BestChainHeight + 1);
        }
Exemplo n.º 16
0
        public async Task <Block> MineAsync(RequestMiningDto requestMiningDto, List <Transaction> transactions,
                                            Timestamp blockTime)
        {
            using (var cts = new CancellationTokenSource())
            {
                var expirationTime = blockTime + requestMiningDto.BlockExecutionTime;

                if (expirationTime < TimestampHelper.GetUtcNow())
                {
                    cts.Cancel();
                }
                else
                {
                    var ts = (expirationTime - TimestampHelper.GetUtcNow()).ToTimeSpan();
                    if (ts.TotalMilliseconds > 4000)
                    {
                        ts = TimeSpan.FromMilliseconds(4000);
                    }
                    cts.CancelAfter(ts);
                }

                var block = await GenerateBlock(requestMiningDto.PreviousBlockHash,
                                                requestMiningDto.PreviousBlockHeight, blockTime);

                var systemTransactions = await GenerateSystemTransactions(requestMiningDto.PreviousBlockHash,
                                                                          requestMiningDto.PreviousBlockHeight);

                var pending = transactions;

                block = await _blockExecutingService.ExecuteBlockAsync(block.Header,
                                                                       systemTransactions, pending, cts.Token);
                await SignBlockAsync(block);

                Logger.LogInformation($"Generated block: {block.ToDiagnosticString()}, " +
                                      $"previous: {block.Header.PreviousBlockHash}, " +
                                      $"executed transactions: {block.Body.TransactionsCount}, " +
                                      $"not executed transactions {transactions.Count + systemTransactions.Count - block.Body.TransactionsCount}");
                return(block);
            }
        }
Exemplo n.º 17
0
        public async Task TokenTransferParallelTest()
        {
            var chain = await _blockchainService.GetChainAsync();

            var tokenAmount = _transactionCount / _groupCount;

            var(prepareTransactions, keyPairs) =
                await _parallelTestHelper.PrepareTokenForParallel(_groupCount, 1000000000);

            await _parallelTestHelper.BroadcastTransactions(prepareTransactions);

            var block = _parallelTestHelper.GenerateBlock(chain.BestChainHash, chain.BestChainHeight,
                                                          prepareTransactions);

            block = (await _blockExecutingService.ExecuteBlockAsync(block.Header, prepareTransactions)).Block;

            await _blockchainService.AddBlockAsync(block);

            await _blockAttachService.AttachBlockAsync(block);

            var systemTransactions = await _parallelTestHelper.GenerateTransferTransactions(1);

            var cancellableTransactions =
                await _parallelTestHelper.GenerateTransactionsWithoutConflictAsync(keyPairs, tokenAmount);

            var allTransaction = systemTransactions.Concat(cancellableTransactions).ToList();
            await _parallelTestHelper.BroadcastTransactions(allTransaction);

            var groupedTransactions = await _grouper.GroupAsync(
                new ChainContext { BlockHash = block.GetHash(), BlockHeight = block.Height },
                cancellableTransactions);

            groupedTransactions.Parallelizables.Count.ShouldBe(_groupCount);
            groupedTransactions.NonParallelizables.Count.ShouldBe(0);

            block = _parallelTestHelper.GenerateBlock(block.GetHash(), block.Height, allTransaction);
            block = (await _blockExecutingService.ExecuteBlockAsync(block.Header, systemTransactions,
                                                                    cancellableTransactions, CancellationToken.None)).Block;
            await _blockchainService.AddBlockAsync(block);

            await _blockAttachService.AttachBlockAsync(block);

            var chainContext = new ChainContext
            {
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            };
            var tokenContractAddress =
                await _smartContractAddressService.GetAddressByContractNameAsync(chainContext, TokenSmartContractAddressNameProvider.StringName);

            var nonparallelContractCode =
                await _nonparallelContractCodeProvider.GetNonparallelContractCodeAsync(chainContext,
                                                                                       tokenContractAddress);

            nonparallelContractCode.ShouldBeNull();

            groupedTransactions = await _grouper.GroupAsync(
                new ChainContext { BlockHash = block.GetHash(), BlockHeight = block.Height },
                cancellableTransactions);

            groupedTransactions.Parallelizables.Count.ShouldBe(_groupCount);
            groupedTransactions.NonParallelizables.Count.ShouldBe(0);

            block.TransactionIds.Count().ShouldBe(allTransaction.Count);
        }
Exemplo n.º 18
0
 public async Task ExecuteBlock()
 {
     _block = await _blockExecutingService.ExecuteBlockAsync(_block.Header, _transactions);
 }
Exemplo n.º 19
0
 public void ExecuteBlock()
 {
     AsyncHelper.RunSync(() => _blockExecutingService.ExecuteBlockAsync(_block.Header, _transactions));
     _counter.Increment();
 }