public async Task ParallelExecuteAsync_Test()
        {
            var chain = await BlockchainService.GetChainAsync();

            (PrepareTransactions, KeyPairs) = await OsTestHelper.PrepareTokenForParallel(10);

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

            await BlockchainService.AddBlockAsync(Block);

            await BlockAttachService.AttachBlockAsync(Block);

            SystemTransactions = await OsTestHelper.GenerateTransferTransactions(1);

            CancellableTransactions = OsTestHelper.GenerateTransactionsWithoutConflict(KeyPairs);
            Block = OsTestHelper.GenerateBlock(Block.GetHash(), Block.Height,
                                               SystemTransactions.Concat(CancellableTransactions));

            await OsTestHelper.BroadcastTransactions(SystemTransactions.Concat(CancellableTransactions));

            var block = await BlockExecutingService.ExecuteBlockAsync(Block.Header,
                                                                      SystemTransactions, CancellableTransactions, CancellationToken.None);

            block.TransactionIds.Count().ShouldBeGreaterThan(10);
        }
        public async Task TransactionReadOnlyExecutionServiceExtensions_Test()
        {
            var chain = await BlockchainService.GetChainAsync();

            var context = new ChainContext
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            var transaction = OsTestHelper.GenerateTransaction(SampleAddress.AddressList[0],
                                                               SmartContractAddressService.GetAddressByContractName(TokenSmartContractAddressNameProvider.Name),
                                                               "GetBalance", new GetBalanceInput
            {
                Owner  = SampleAddress.AddressList[0],
                Symbol = "ELF"
            });

            var result = await TransactionReadOnlyExecutionService.ExecuteAsync <GetBalanceOutput>(context, transaction,
                                                                                                   TimestampHelper.GetUtcNow(),
                                                                                                   true);

            result.Balance.ShouldBe(0);
            result.Symbol.ShouldBe("ELF");

            //without such method and call
            transaction.MethodName = "NotExist";
            await Should.ThrowAsync <SmartContractExecutingException>(async() =>
            {
                await TransactionReadOnlyExecutionService.ExecuteAsync <GetBalanceOutput>(context, transaction,
                                                                                          TimestampHelper.GetUtcNow(),
                                                                                          true);
            });
        }
Exemple #3
0
        public async Task <JObject> GetChainStatus()
        {
            var chain = await BlockchainService.GetChainAsync();

            var branches = (JObject)JsonConvert.DeserializeObject(chain.Branches.ToString());
            var formattedNotLinkedBlocks = new JArray();

            foreach (var notLinkedBlock in chain.NotLinkedBlocks)
            {
                var block = await this.GetBlock(Hash.LoadBase64(notLinkedBlock.Value));

                formattedNotLinkedBlocks.Add(new JObject
                {
                    ["BlockHash"]         = block.GetHash().ToHex(),
                    ["Height"]            = block.Height,
                    ["PreviousBlockHash"] = block.Header.PreviousBlockHash.ToHex()
                }
                                             );
            }

            return(new JObject
            {
                ["Branches"] = branches,
                ["NotLinkedBlocks"] = formattedNotLinkedBlocks,
                ["LongestChainHeight"] = chain.LongestChainHeight,
                ["LongestChainHash"] = chain.LongestChainHash?.ToHex(),
                ["GenesisBlockHash"] = chain.GenesisBlockHash.ToHex(),
                ["LastIrreversibleBlockHash"] = chain.LastIrreversibleBlockHash?.ToHex(),
                ["LastIrreversibleBlockHeight"] = chain.LastIrreversibleBlockHeight,
                ["BestChainHash"] = chain.BestChainHash?.ToHex(),
                ["BestChainHeight"] = chain.BestChainHeight
            });
        }
        public async Task IsViewTransactionAsync_Test()
        {
            var chain = await BlockchainService.GetChainAsync();

            var context = new ChainContext
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            var transaction = OsTestHelper.GenerateTransaction(SampleAddress.AddressList[0],
                                                               await SmartContractAddressService.GetAddressByContractNameAsync(context, TokenSmartContractAddressNameProvider.StringName),
                                                               "GetBalance", new GetBalanceInput
            {
                Owner  = SampleAddress.AddressList[0],
                Symbol = "ELF"
            });

            var result = await TransactionReadOnlyExecutionService.IsViewTransactionAsync(context, transaction);

            result.ShouldBeTrue();

            transaction = OsTestHelper.GenerateTransaction(SampleAddress.AddressList[0],
                                                           await SmartContractAddressService.GetAddressByContractNameAsync(context,
                                                                                                                           TokenSmartContractAddressNameProvider.StringName),
                                                           "Transfer", new TransferInput
            {
                To     = SampleAddress.AddressList[1],
                Symbol = "ELF",
                Amount = 10
            });
            result = await TransactionReadOnlyExecutionService.IsViewTransactionAsync(context, transaction);

            result.ShouldBeFalse();
        }
        public async Task ExecuteAsync_Test()
        {
            var chain = await BlockchainService.GetChainAsync();

            (PrepareTransactions, KeyPairs) = await OsTestHelper.PrepareTokenForParallel(10);

            Block = OsTestHelper.GenerateBlock(chain.BestChainHash, chain.BestChainHeight, PrepareTransactions);
            PrepareTransactions[0].To = SampleAccount.Accounts[0].Address;
            await OsTestHelper.BroadcastTransactions(PrepareTransactions);

            var executionReturnSets = await _transactionExecutingService.ExecuteAsync(new TransactionExecutingDto
            {
                Transactions = PrepareTransactions,
                BlockHeader  = Block.Header
            }, CancellationToken.None);

            executionReturnSets.Count.ShouldBe(PrepareTransactions.Count);
            executionReturnSets.Count(set => set.TransactionResult.Status == TransactionResultStatus.Failed)
            .ShouldBe(1);
            executionReturnSets.First(set => set.TransactionResult.Status == TransactionResultStatus.Failed).TransactionResult.Error.ShouldBe("Invalid contract address.");
            executionReturnSets.Count(set => set.TransactionResult.Status == TransactionResultStatus.Mined).ShouldBe(9);

            (PrepareTransactions, KeyPairs) = await OsTestHelper.PrepareTokenForParallel(10);

            Block = OsTestHelper.GenerateBlock(Block.GetHash(), Block.Height, PrepareTransactions);
            await OsTestHelper.BroadcastTransactions(PrepareTransactions);

            var cancelTokenSource = new CancellationTokenSource();

            cancelTokenSource.Cancel();
            executionReturnSets = await _transactionExecutingService.ExecuteAsync(new TransactionExecutingDto
            {
                Transactions = PrepareTransactions,
                BlockHeader  = Block.Header
            }, cancelTokenSource.Token);

            executionReturnSets.Count.ShouldBe(0);

            (PrepareTransactions, KeyPairs) = await OsTestHelper.PrepareTokenForParallel(10);

            Block = OsTestHelper.GenerateBlock(Block.GetHash(), Block.Height, PrepareTransactions);
            _systemTransactionExtraDataProvider.SetSystemTransactionCount(1, Block.Header);
            executionReturnSets = await _transactionExecutingService.ExecuteAsync(new TransactionExecutingDto
            {
                Transactions = PrepareTransactions,
                BlockHeader  = Block.Header
            }, CancellationToken.None);

            executionReturnSets.Count.ShouldBe(PrepareTransactions.Count);
            executionReturnSets.ShouldAllBe(set => set.TransactionResult.Status == TransactionResultStatus.Mined);
        }
        public async Task GetFileDescriptorsAsync_Test()
        {
            var chain = await BlockchainService.GetChainAsync();

            var context = new ChainContext
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            var tokenAddress =
                SmartContractAddressService.GetAddressByContractName(TokenSmartContractAddressNameProvider.Name);
            var fileDescriptor =
                (await TransactionReadOnlyExecutionService.GetFileDescriptorsAsync(context, tokenAddress)).ToList();

            fileDescriptor.Count.ShouldBeGreaterThan(0);
            fileDescriptor.ShouldAllBe(o => o.Name.Contains("proto"));
        }
        public async Task GetTransactionParametersAsync_Test()
        {
            var chain = await BlockchainService.GetChainAsync();

            var context = new ChainContext
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            var transaction = await OsTestHelper.GenerateTransferTransaction();

            var jsonResult =
                await TransactionReadOnlyExecutionService.GetTransactionParametersAsync(context, transaction);

            jsonResult.ShouldNotBeEmpty();
            jsonResult.ShouldContain("to");
            jsonResult.ShouldContain("symbol");
            jsonResult.ShouldContain("amount");
        }
Exemple #8
0
        internal async Task <Hash> AEDPoSContract_GetRandomNumber_Test()
        {
            var order = await AEDPoSContract_RequestRandomNumber_Test();

            var currentRound = await AEDPoSContractStub.GetCurrentRoundInformation.CallAsync(new Empty());

            var randomHashes = Enumerable.Range(0, EconomicContractsTestConstants.InitialCoreDataCenterCount)
                               .Select(i => Hash.FromString($"random{i}")).ToList();
            var triggers = Enumerable.Range(0, EconomicContractsTestConstants.InitialCoreDataCenterCount).Select(i =>
                                                                                                                 new AElfConsensusTriggerInformation
            {
                Pubkey     = ByteString.CopyFrom(InitialCoreDataCenterKeyPairs[i].PublicKey),
                RandomHash = randomHashes[i]
            }).ToDictionary(t => t.Pubkey.ToHex(), t => t);

            // Exactly one round except extra block time slot.
            foreach (var minerInRound in currentRound.RealTimeMinersInformation.Values.OrderBy(m => m.Order))
            {
                var currentKeyPair =
                    InitialCoreDataCenterKeyPairs.First(p => p.PublicKey.ToHex() == minerInRound.Pubkey);

                KeyPairProvider.SetKeyPair(currentKeyPair);

                BlockTimeProvider.SetBlockTime(minerInRound.ExpectedMiningTime);

                var stub = GetAEDPoSContractStub(currentKeyPair);
                var headerInformation =
                    (await stub.GetConsensusExtraData.CallAsync(triggers[minerInRound.Pubkey]
                                                                .ToBytesValue())).ToConsensusHeaderInformation();

                // Update consensus information.
                var toUpdate = headerInformation.Round.ExtractInformationToUpdateConsensus(minerInRound.Pubkey);
                await stub.UpdateValue.SendAsync(toUpdate);

                {
                    var chain = await BlockchainService.GetChainAsync();

                    if (chain.BestChainHeight < order.BlockHeight)
                    {
                        // Not enough.
                        var transactionResult = (await AEDPoSContractStub.GetRandomNumber.SendAsync(order.TokenHash))
                                                .TransactionResult;
                        transactionResult.Error.ShouldContain("Still preparing random number.");
                    }
                }

                for (var i = 0; i < 7; i++)
                {
                    await stub.UpdateTinyBlockInformation.SendAsync(new TinyBlockInput
                    {
                        ActualMiningTime = TimestampHelper.GetUtcNow(),
                        RoundId          = currentRound.RoundId
                    });
                }
            }

            // Now it's enough.
            {
                var randomNumber = (await AEDPoSContractStub.GetRandomNumber.SendAsync(order.TokenHash)).Output;
                randomNumber.Value.ShouldNotBeEmpty();
            }

            return(order.TokenHash);
        }
        public async Task GlobalSetup()
        {
            await InitializeChainAsync();

            _chain = await BlockchainService.GetChainAsync();
        }