Exemple #1
0
        public async Task BlockExecutedData_Test()
        {
            var genesisBlock = _kernelTestHelper.GenerateBlock(0, Hash.Empty, new List <Transaction>());
            var chain        = await _blockchainService.CreateChainAsync(genesisBlock, new List <Transaction>());

            var blockStateSet = new BlockStateSet
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            var chainKey   = GetBlockExecutedDataKey <Chain>();
            var dictionary = new Dictionary <string, ByteString>
            {
                { chainKey, ByteString.CopyFrom(SerializationHelper.Serialize(chain)) }
            };
            await _blockchainExecutedDataManager.AddBlockExecutedCacheAsync(blockStateSet.BlockHash, dictionary);

            var isInStore = await CheckExecutedDataInStoreAsync(blockStateSet, chainKey, dictionary[chainKey]);

            isInStore.ShouldBeFalse();

            await _blockchainStateService.MergeBlockStateAsync(chain.BestChainHeight, chain.BestChainHash);

            isInStore = await CheckExecutedDataInStoreAsync(blockStateSet, chainKey, dictionary[chainKey]);

            isInStore.ShouldBeTrue();

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            isInStore = await CheckExecutedDataInStoreAsync(blockStateSet, chainKey, dictionary[chainKey]);

            isInStore.ShouldBeTrue();
        }
        public async Task BlockState_MergeBlock_Normal_Test()
        {
            var blockStateSet1 = new BlockStateSet()
            {
                BlockHeight  = 1,
                BlockHash    = Hash.FromString("hash"),
                PreviousHash = Hash.Empty
            };
            var blockStateSet2 = new BlockStateSet()
            {
                BlockHeight  = 2,
                BlockHash    = Hash.FromString("hash2"),
                PreviousHash = blockStateSet1.BlockHash
            };
            var blockStateSet3 = new BlockStateSet()
            {
                BlockHeight  = 3,
                BlockHash    = Hash.FromString("hash3"),
                PreviousHash = blockStateSet2.BlockHash
            };

            //test merge block height 1
            {
                await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet1);

                await _blockchainStateService.MergeBlockStateAsync(blockStateSet1.BlockHeight,
                                                                   blockStateSet1.BlockHash);

                var chainStateInfo = await _blockStateSetManger.GetChainStateInfoAsync();

                chainStateInfo.BlockHeight.ShouldBe(1);
                chainStateInfo.BlockHash.ShouldBe(blockStateSet1.BlockHash);
            }

            //test merge block height 2
            {
                await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet2);

                await _blockchainStateService.MergeBlockStateAsync(blockStateSet2.BlockHeight,
                                                                   blockStateSet2.BlockHash);

                var chainStateInfo = await _blockStateSetManger.GetChainStateInfoAsync();

                chainStateInfo.BlockHeight.ShouldBe(2);
                chainStateInfo.BlockHash.ShouldBe(blockStateSet2.BlockHash);
            }

            //test merge height 3 without block state set before
            {
                await Should.ThrowAsync <InvalidOperationException>(() => _blockchainStateService.MergeBlockStateAsync(blockStateSet3.BlockHeight,
                                                                                                                       blockStateSet3.BlockHash));

                var chainStateInfo = await _blockStateSetManger.GetChainStateInfoAsync();

                chainStateInfo.BlockHeight.ShouldBe(2);
                chainStateInfo.BlockHash.ShouldBe(blockStateSet2.BlockHash);
            }
        }
Exemple #3
0
        private async Task AddBlockStateSetAsync(Block block)
        {
            var blockStateSet = new BlockStateSet()
            {
                BlockHeight  = block.Height,
                BlockHash    = block.GetHash(),
                PreviousHash = block.Header.PreviousBlockHash
            };

            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);
        }
Exemple #4
0
        internal async Task MineBlockAsync(Block block)
        {
            var transactions = block.Body.TransactionIds.Count > 0
                ? await _blockchainService.GetTransactionsAsync(block.TransactionIds)
                : new List <Transaction>();

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

            await _transactionResultManager.AddTransactionResultsAsync(
                executionReturnSets.Select(s => s.TransactionResult).ToList(), block.GetHash());

            var blockStateSet = new BlockStateSet
            {
                BlockHash    = block.GetHash(),
                PreviousHash = block.Header.PreviousBlockHash,
                BlockHeight  = block.Height
            };

            foreach (var stateChange in executionReturnSets.SelectMany(executionReturnSet => executionReturnSet.StateChanges))
            {
                blockStateSet.Changes[stateChange.Key] = stateChange.Value;
            }

            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);
        }
Exemple #5
0
        public async Task SmartContractAddress_Get_WithFork_Test()
        {
            var chain = await _smartContractHelper.CreateChainAsync();

            var block = await _kernelTestHelper.AttachBlockToBestChain();

            await _blockchainService.SetIrreversibleBlockAsync(chain, block.Height,
                                                               block.GetHash());

            block = _kernelTestHelper.GenerateBlock(block.Header.Height - 1, block.Header.PreviousBlockHash);
            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            });

            var chainContext = new ChainContext
            {
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            };
            var contractName = Hash.Empty.ToStorageKey();
            await _smartContractAddressService.SetSmartContractAddressAsync(chainContext, contractName,
                                                                            SampleAddress.AddressList[0]);

            var smartContractAddressDto = await _smartContractAddressService.GetSmartContractAddressAsync(chainContext, contractName);

            smartContractAddressDto.SmartContractAddress.ShouldBe(new SmartContractAddress
            {
                Address     = SampleAddress.AddressList[0],
                BlockHash   = block.GetHash(),
                BlockHeight = block.Height
            });
            smartContractAddressDto.Irreversible.ShouldBeFalse();
        }
Exemple #6
0
        public async Task <Block> AttachBlockToBestChain(List <Transaction> transactions             = null,
                                                         List <TransactionResult> transactionResults = null)
        {
            var chain = await _blockchainService.GetChainAsync();

            var block = await AttachBlock(chain.BestChainHeight, chain.BestChainHash, transactions, transactionResults);

            var blockStateSet = new BlockStateSet
            {
                BlockHash    = block.GetHash(),
                BlockHeight  = block.Height,
                PreviousHash = block.Header.PreviousBlockHash
            };
            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            chain = await _blockchainService.GetChainAsync();

            await _blockchainService.SetBestChainAsync(chain, block.Height, block.GetHash());

            var chainBlockLink = await _chainManager.GetChainBlockLinkAsync(block.GetHash());

            await _chainManager.SetChainBlockLinkExecutionStatusAsync(chainBlockLink,
                                                                      ChainBlockLinkExecutionStatus.ExecutionSuccess);

            return(block);
        }
        public async Task GetStateAsync_Test()
        {
            var chain = await _smartContractHelper.CreateChainAsync();

            await Assert.ThrowsAsync <InvalidOperationException>(() => _smartContractBridgeService.GetStateAsync(
                                                                     SampleAddress.AddressList[0], string.Empty,
                                                                     chain.BestChainHeight,
                                                                     chain.BestChainHash));


            var scopedStatePath = new ScopedStatePath
            {
                Address = SampleAddress.AddressList[0],
                Path    = new StatePath
                {
                    Parts = { "part" }
                }
            };
            var state = await _smartContractBridgeService.GetStateAsync(SampleAddress.AddressList[0], scopedStatePath.ToStateKey(),
                                                                        chain.BestChainHeight, chain.BestChainHash);

            state.ShouldBeNull();

            var blockStateSet = await _blockStateSetManger.GetBlockStateSetAsync(chain.BestChainHash);

            blockStateSet.Changes[scopedStatePath.ToStateKey()] = ByteString.Empty;
            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            state = await _smartContractBridgeService.GetStateAsync(SampleAddress.AddressList[0], scopedStatePath.ToStateKey(),
                                                                    chain.BestChainHeight, chain.BestChainHash);

            state.ShouldBe(ByteString.Empty);
        }
Exemple #8
0
        public async Task GenerateTransactions_Test()
        {
            var sideChainId         = 123;
            var previousBlockHash   = HashHelper.ComputeFrom("PreviousBlockHash");
            var previousBlockHeight = 1;
            var crossChainBlockData = new CrossChainBlockData
            {
            };

            var cachingCount = 5;

            for (int i = 1; i < cachingCount + CrossChainConstants.DefaultBlockCacheEntityCount; i++)
            {
                var sideChainBlockData = new SideChainBlockData()
                {
                    ChainId = sideChainId,
                    Height  = (i + 1),
                    TransactionStatusMerkleTreeRoot = HashHelper.ComputeFrom((sideChainId + 1).ToString())
                };
                if (i <= CrossChainConstants.DefaultBlockCacheEntityCount)
                {
                    crossChainBlockData.SideChainBlockDataList.Add(sideChainBlockData);
                }
            }

            var crossChainTransactionInput = new CrossChainTransactionInput
            {
                Value               = crossChainBlockData.ToByteString(),
                MethodName          = nameof(CrossChainContractImplContainer.CrossChainContractImplStub.ProposeCrossChainIndexing),
                PreviousBlockHeight = previousBlockHeight
            };

            _crossChainTestHelper.AddFakeCrossChainTransactionInput(previousBlockHash, crossChainTransactionInput);
            // AddFakeCacheData(new Dictionary<int, List<ICrossChainBlockEntity>> {{sideChainId, sideChainBlockInfoCache}});

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = previousBlockHash,
                BlockHeight = previousBlockHeight
            });

            var transactions =
                await _crossChainIndexingTransactionGenerator.GenerateTransactionsAsync(SampleAddress.AddressList[0],
                                                                                        previousBlockHeight, previousBlockHash);

            transactions.Count.ShouldBe(1);
            transactions[0].From.ShouldBe(SampleAddress.AddressList[0]);
            transactions[0].To.ShouldBeNull();
            transactions[0].RefBlockNumber.ShouldBe(previousBlockHeight);

            transactions[0].RefBlockPrefix.ShouldBe(BlockHelper.GetRefBlockPrefix(previousBlockHash));
            transactions[0].MethodName
            .ShouldBe(nameof(CrossChainContractImplContainer.CrossChainContractImplStub.ProposeCrossChainIndexing));

            var crossChainBlockDataInParam = CrossChainBlockData.Parser.ParseFrom(transactions[0].Params);

            Assert.Equal(crossChainBlockData, crossChainBlockDataInParam);
        }
        public async Task IterationCleanup()
        {
            await _chainStateInfoCollection.SetAsync(_chain.Id.ToStorageKey(), _chainStateInfo);

            foreach (var blockStateSet in _blockStateSets)
            {
                await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);
            }
        }
Exemple #10
0
        public async Task Mine_Test()
        {
            var chain = await _blockchainService.GetChainAsync();

            var blockStateSet = new BlockStateSet
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight,
            };
            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            var transactions = _kernelTestHelper.GenerateTransactions(5, chain.BestChainHeight, chain.BestChainHash);
            await _transactionPoolService.UpdateTransactionPoolByBestChainAsync(chain.BestChainHash,
                                                                                chain.BestChainHeight);

            await _transactionPoolService.AddTransactionsAsync(transactions);

            await Task.Delay(200);

            await _transactionPoolService.UpdateTransactionPoolByBestChainAsync(chain.BestChainHash,
                                                                                chain.BestChainHeight);

            {
                await _transactionPackingOptionProvider.SetTransactionPackingOptionAsync(new BlockIndex
                {
                    BlockHash   = chain.BestChainHash,
                    BlockHeight = chain.BestChainHeight
                }, false);

                var blockTime = TimestampHelper.GetUtcNow();
                var result    = await _minerService.MineAsync(chain.BestChainHash, chain.BestChainHeight, blockTime,
                                                              TimestampHelper.DurationFromSeconds(4));
                await CheckMiningResultAsync(result, blockTime, 0);
            }

            {
                await _transactionPackingOptionProvider.SetTransactionPackingOptionAsync(new BlockIndex
                {
                    BlockHash   = chain.BestChainHash,
                    BlockHeight = chain.BestChainHeight
                }, true);

                await _blockTransactionLimitProvider.SetLimitAsync(new BlockIndex
                {
                    BlockHash   = chain.BestChainHash,
                    BlockHeight = chain.BestChainHeight
                }, 3);

                var blockTime = TimestampHelper.GetUtcNow();
                var result    = await _minerService.MineAsync(chain.BestChainHash, chain.BestChainHeight, blockTime,
                                                              TimestampHelper.DurationFromSeconds(4));
                await CheckMiningResultAsync(result, blockTime, 2);
            }
        }
        public async Task TransactionLimitSetAndGet_Test()
        {
            var blockIndex = new BlockIndex
            {
                BlockHash   = HashHelper.ComputeFrom("BlockHash"),
                BlockHeight = 1
            };

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            var blockTransactionLimit = 50;

            {
                var limit = await _blockTransactionLimitProvider.GetLimitAsync(
                    new ChainContext
                {
                    BlockHash   = blockIndex.BlockHash,
                    BlockHeight = blockIndex.BlockHeight
                });

                limit.ShouldBe(int.MaxValue);
            }

            {
                await _blockTransactionLimitProvider.SetLimitAsync(blockIndex, blockTransactionLimit);

                var limit = await _blockTransactionLimitProvider.GetLimitAsync(
                    new ChainContext
                {
                    BlockHash   = blockIndex.BlockHash,
                    BlockHeight = blockIndex.BlockHeight
                });

                limit.ShouldBe(blockTransactionLimit);
            }

            var blockTransactionLimitLessThanSystemTransaction =
                GetRequiredService <IEnumerable <ISystemTransactionGenerator> >().Count();
            await _blockTransactionLimitProvider.SetLimitAsync(blockIndex, blockTransactionLimitLessThanSystemTransaction);

            var limit2 = await _blockTransactionLimitProvider.GetLimitAsync(
                new ChainContext
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            limit2.ShouldBe(blockTransactionLimit);
        }
Exemple #12
0
        public async Task ProcessConfiguration_Test()
        {
            var blockTransactionLimit = 50;
            var blockIndex            = new BlockIndex
            {
                BlockHash   = HashHelper.ComputeFrom("BlockHash"),
                BlockHeight = 1
            };

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            var limit = await _blockTransactionLimitProvider.GetLimitAsync(
                new ChainContext
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            limit.ShouldBe(int.MaxValue);

            await _blockTransactionLimitConfigurationProcessor.ProcessConfigurationAsync(new Int32Value
            {
                Value = -1
            }.ToByteString(), blockIndex);

            limit = await _blockTransactionLimitProvider.GetLimitAsync(
                new ChainContext
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            limit.ShouldBe(int.MaxValue);

            await _blockTransactionLimitConfigurationProcessor.ProcessConfigurationAsync(new Int32Value
            {
                Value = blockTransactionLimit
            }.ToByteString(), blockIndex);

            limit = await _blockTransactionLimitProvider.GetLimitAsync(
                new ChainContext
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            limit.ShouldBe(blockTransactionLimit);
        }
Exemple #13
0
        private async Task <CachedStateProvider> GenerateStateProviderAsync()
        {
            var chain = await _smartContractHelper.CreateChainAsync();

            var smartContractBridgeContext = _hostSmartContractBridgeContextService.Create();

            smartContractBridgeContext.TransactionContext = new TransactionContext
            {
                Transaction = new Transaction
                {
                    To = SampleAddress.AddressList[0]
                },
                BlockHeight       = chain.BestChainHeight,
                PreviousBlockHash = chain.BestChainHash
            };
            _innerProvider.ContractAddress = SampleAddress.AddressList[0];
            _innerProvider.HostSmartContractBridgeContext = smartContractBridgeContext;
            var statePath = new ScopedStatePath
            {
                Address = _innerProvider.ContractAddress,
                Path    = new StatePath
                {
                    Parts = { "test2" }
                }
            };
            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight,
                Changes     =
                {
                    {
                        statePath.ToStateKey(), ByteString.CopyFrom(1, 2, 3, 4)
                    }
                }
            });

            var cachedStateProvider = new CachedStateProvider(_innerProvider);
            var cacheProvider       = cachedStateProvider as CachedStateProvider;

            cacheProvider.Cache[new ScopedStatePath
                                {
                                    Address = _innerProvider.ContractAddress,
                                    Path = new StatePath
                                    {
                                        Parts = { "test1" }
                                    }
                                }] = new byte[] { 0, 1, 2, 3 };

            return(cachedStateProvider);
        }
        protected async Task <BlockStateSet> AddBlockStateSetAsync(BlockStateSet previousBlockStateSet)
        {
            var block = await KernelTestHelper.AttachBlockToBestChain();

            var blockStateSet = new BlockStateSet
            {
                BlockHash    = block.GetHash(),
                BlockHeight  = block.Height,
                PreviousHash = previousBlockStateSet.BlockHash
            };
            await BlockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            return(blockStateSet);
        }
Exemple #15
0
        public async Task SmartContractRegistrationSetAndGet_Test()
        {
            var genesisBlock = _kernelTestHelper.GenerateBlock(0, Hash.Empty, new List <Transaction>());
            var chain        = await _blockchainService.CreateChainAsync(genesisBlock, new List <Transaction>());

            var blockStateSet = new BlockStateSet
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            var blockExecutedDataKey = $"BlockExecutedData/SmartContractRegistration/{SampleAddress.AddressList[0]}";

            blockStateSet.BlockExecutedData.ShouldNotContainKey(blockExecutedDataKey);

            var chainContext = new ChainContext
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };

            var smartContractRegistration = new SmartContractRegistration
            {
                CodeHash = Hash.FromString(blockExecutedDataKey),
                Category = KernelConstants.CodeCoverageRunnerCategory,
                Version  = 1
            };
            await _smartContractRegistrationProvider.SetSmartContractRegistrationAsync(chainContext,
                                                                                       SampleAddress.AddressList[0], smartContractRegistration);

            blockStateSet = await _blockStateSetManger.GetBlockStateSetAsync(chain.BestChainHash);

            blockStateSet.BlockExecutedData.ShouldContainKey(blockExecutedDataKey);

            var smartContractRegistrationFromState =
                await _smartContractRegistrationProvider.GetSmartContractRegistrationAsync(chainContext,
                                                                                           SampleAddress.AddressList[0]);

            smartContractRegistrationFromState.ShouldBe(smartContractRegistration);
        }
        public async Task ValidateBlockBeforeExecute_Test()
        {
            var previousBlockHash     = _kernelTestHelper.BestBranchBlockList.Last().GetHash();
            var previousBlockHeight   = _kernelTestHelper.BestBranchBlockList.Last().Height;
            var blockWithTransaction2 = GenerateBlock(previousBlockHeight, previousBlockHash, 2);
            var blockWithTransaction3 = GenerateBlock(previousBlockHeight, previousBlockHash, 3);
            var blockWithTransaction4 = GenerateBlock(previousBlockHeight, previousBlockHash, 4);
            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = previousBlockHash,
                BlockHeight = previousBlockHeight
            });

            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction2)).ShouldBeTrue();
            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction3)).ShouldBeTrue();
            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction4)).ShouldBeTrue();

            await _blockTransactionLimitProvider.SetLimitAsync(new BlockIndex
            {
                BlockHeight = previousBlockHeight,
                BlockHash   = previousBlockHash
            }, 3);

            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction2)).ShouldBeTrue();
            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction3)).ShouldBeTrue();
            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction4)).ShouldBeFalse();

            await _blockTransactionLimitProvider.SetLimitAsync(new BlockIndex
            {
                BlockHeight = previousBlockHeight,
                BlockHash   = previousBlockHash
            }, 4);

            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction2)).ShouldBeTrue();
            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction3)).ShouldBeTrue();
            (await _blockValidationProvider.ValidateBlockBeforeExecuteAsync(blockWithTransaction4)).ShouldBeTrue();
        }
Exemple #17
0
        public async Task ExecutionObserverThresholdProvider_GetAndSet_Test()
        {
            var blockIndex = new BlockIndex
            {
                BlockHash   = HashHelper.ComputeFrom("BlockHash"),
                BlockHeight = 1
            };

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            {
                var executionObserverThreshold =
                    _executionObserverThresholdProvider.GetExecutionObserverThreshold(blockIndex);
                executionObserverThreshold.ExecutionBranchThreshold.ShouldBe(SmartContractConstants
                                                                             .ExecutionBranchThreshold);
                executionObserverThreshold.ExecutionCallThreshold.ShouldBe(
                    SmartContractConstants.ExecutionCallThreshold);
            }

            var newExecutionObserverThreshold = new ExecutionObserverThreshold
            {
                ExecutionBranchThreshold = 1,
                ExecutionCallThreshold   = 1
            };

            {
                await _executionObserverThresholdProvider.SetExecutionObserverThresholdAsync(blockIndex,
                                                                                             newExecutionObserverThreshold);

                var executionObserverThreshold =
                    _executionObserverThresholdProvider.GetExecutionObserverThreshold(blockIndex);
                executionObserverThreshold.ShouldBe(newExecutionObserverThreshold);
            }

            var blockIndex2 = new BlockIndex
            {
                BlockHash   = HashHelper.ComputeFrom("BlockHash1"),
                BlockHeight = blockIndex.BlockHeight + 1
            };

            var blockStateSet2 = new BlockStateSet
            {
                PreviousHash = blockIndex.BlockHash,
                BlockHash    = blockIndex2.BlockHash,
                BlockHeight  = blockIndex2.BlockHeight + 1
            };

            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet2);

            {
                var executionObserverThreshold =
                    _executionObserverThresholdProvider.GetExecutionObserverThreshold(blockIndex2);
                executionObserverThreshold.ShouldBe(newExecutionObserverThreshold);
            }

            {
                var invalidThreshold = new ExecutionObserverThreshold
                {
                    ExecutionBranchThreshold = 1
                };
                await _executionObserverThresholdProvider.SetExecutionObserverThresholdAsync(blockIndex2,
                                                                                             invalidThreshold);

                var executionObserverThreshold =
                    _executionObserverThresholdProvider.GetExecutionObserverThreshold(blockIndex2);
                executionObserverThreshold.ShouldBe(newExecutionObserverThreshold);
            }

            {
                var invalidThreshold = new ExecutionObserverThreshold
                {
                    ExecutionCallThreshold = 1
                };
                await _executionObserverThresholdProvider.SetExecutionObserverThresholdAsync(blockIndex2,
                                                                                             invalidThreshold);

                var executionObserverThreshold =
                    _executionObserverThresholdProvider.GetExecutionObserverThreshold(blockIndex2);
                executionObserverThreshold.ShouldBe(newExecutionObserverThreshold);
            }

            {
                var validThreshold = new ExecutionObserverThreshold
                {
                    ExecutionCallThreshold   = 2,
                    ExecutionBranchThreshold = 2
                };
                await _executionObserverThresholdProvider.SetExecutionObserverThresholdAsync(blockIndex2,
                                                                                             validThreshold);

                var executionObserverThreshold =
                    _executionObserverThresholdProvider.GetExecutionObserverThreshold(blockIndex2);
                executionObserverThreshold.ShouldBe(validThreshold);
            }
        }
        public async Task BlockExecutedData_Test()
        {
            var genesisBlock = _kernelTestHelper.GenerateBlock(0, Hash.Empty, new List <Transaction>());
            var chain        = await _blockchainService.CreateChainAsync(genesisBlock, new List <Transaction>());

            var blockStateSet = new BlockStateSet
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);

            var transactionDic = new Dictionary <string, Transaction>();

            for (var i = 0; i < 5; i++)
            {
                var transaction = new Transaction
                {
                    From           = SampleAddress.AddressList[i],
                    To             = SampleAddress.AddressList[i + 1],
                    RefBlockNumber = chain.BestChainHeight - 1,
                    MethodName     = "Test"
                };
                transactionDic.Add(GetBlockExecutedDataKey <Transaction>(transaction.GetHash()), transaction);
            }

            await _transactionBlockchainExecutedDataService.AddBlockExecutedDataAsync(new BlockIndex
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            }, transactionDic);

            var transactionResult = new TransactionResult
            {
                TransactionId = transactionDic.First().Value.GetHash()
            };
            var transactionResultKey = GetBlockExecutedDataKey <TransactionResult>(transactionResult.TransactionId);
            await _transactionResultBlockchainExecutedDataService.AddBlockExecutedDataAsync(new BlockIndex
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            },
                                                                                            transactionResultKey,
                                                                                            transactionResult);

            var chainKey = GetBlockExecutedDataKey <Chain>();
            await _chainBlockchainExecutedDataService.AddBlockExecutedDataAsync(new BlockIndex
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            },
                                                                                chainKey, chain);

            var newBlockStateSet = await _blockStateSetManger.GetBlockStateSetAsync(chain.BestChainHash);

            newBlockStateSet.BlockHash.ShouldBe(blockStateSet.BlockHash);
            newBlockStateSet.BlockHeight.ShouldBe(blockStateSet.BlockHeight);
            newBlockStateSet.BlockExecutedData.Count.ShouldBe(7);
            newBlockStateSet.BlockExecutedData.Keys.ShouldContain(key => key.Contains(typeof(Transaction).Name));
            newBlockStateSet.BlockExecutedData.Keys.ShouldContain(key => key.Contains(typeof(TransactionResult).Name));
            newBlockStateSet.BlockExecutedData.Keys.ShouldContain(key => key.Contains(typeof(Chain).Name));

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            CheckBlockExecutedData(blockStateSet, chain, transactionResult, transactionDic);
            await _blockchainStateService.MergeBlockStateAsync(chain.BestChainHeight, chain.BestChainHash);

            CheckBlockExecutedData(blockStateSet, chain, transactionResult, transactionDic);

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            CheckBlockExecutedData(blockStateSet, chain, transactionResult, transactionDic);
        }
        public async Task StateSizeLimitStateProvider_GetAndSet_Test()
        {
            var blockIndex = new BlockIndex
            {
                BlockHash   = HashHelper.ComputeFrom("BlockHash"),
                BlockHeight = 1
            };

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet
            {
                BlockHash   = blockIndex.BlockHash,
                BlockHeight = blockIndex.BlockHeight
            });

            {
                var limit = await _stateSizeLimitProvider.GetStateSizeLimitAsync(blockIndex);

                limit.ShouldBe(SmartContractConstants.StateSizeLimit);
            }

            var expectedLimit = 50;

            {
                await _stateSizeLimitProvider.SetStateSizeLimitAsync(blockIndex, expectedLimit);

                var limit = await _stateSizeLimitProvider.GetStateSizeLimitAsync(blockIndex);

                limit.ShouldBe(expectedLimit);

                expectedLimit = 1;
                await _stateSizeLimitProvider.SetStateSizeLimitAsync(blockIndex, expectedLimit);

                limit = await _stateSizeLimitProvider.GetStateSizeLimitAsync(blockIndex);

                limit.ShouldBe(expectedLimit);

                await _stateSizeLimitProvider.SetStateSizeLimitAsync(blockIndex, 0);

                limit = await _stateSizeLimitProvider.GetStateSizeLimitAsync(
                    new ChainContext
                {
                    BlockHash   = blockIndex.BlockHash,
                    BlockHeight = blockIndex.BlockHeight
                });

                limit.ShouldBe(expectedLimit);
            }

            var blockIndex2 = new BlockIndex
            {
                BlockHash   = HashHelper.ComputeFrom("BlockHash1"),
                BlockHeight = blockIndex.BlockHeight + 1
            };

            var blockStateSet2 = new BlockStateSet
            {
                PreviousHash = blockIndex.BlockHash,
                BlockHash    = blockIndex2.BlockHash,
                BlockHeight  = blockIndex2.BlockHeight + 1
            };

            await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet2);

            {
                var stateSizeLimit =
                    await _stateSizeLimitProvider.GetStateSizeLimitAsync(blockIndex2);

                stateSizeLimit.ShouldBe(expectedLimit);
            }
        }
Exemple #20
0
 public async Task SetBlockStateSetAsync(BlockStateSet blockStateSet)
 {
     await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);
 }
        public async Task AddBlockStateSet_Test()
        {
            // one level tests without best chain state
            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet()
            {
                BlockHash    = _tv[1].BlockHash,
                BlockHeight  = _tv[1].BlockHeight,
                PreviousHash = null,
                Changes      =
                {
                    {
                        _tv[1].Key,
                        _tv[1].Value
                    },
                    {
                        _tv[2].Key,
                        _tv[2].Value
                    },
                }
            });


            var check1 = new Func <Task>(async() =>
            {
                (await _blockchainStateManager.GetStateAsync(_tv[1].Key, _tv[1].BlockHeight, _tv[1].BlockHash))
                .ShouldBe(_tv[1].Value);

                (await _blockchainStateManager.GetStateAsync(_tv[2].Key, _tv[1].BlockHeight, _tv[1].BlockHash))
                .ShouldBe(_tv[2].Value);
            });

            await check1();

            //two level tests without best chain state

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet()
            {
                BlockHash    = _tv[2].BlockHash,
                BlockHeight  = _tv[2].BlockHeight,
                PreviousHash = _tv[1].BlockHash,
                Changes      =
                {
                    //override key 1
                    {
                        _tv[1].Key,
                        _tv[2].Value
                    },
                }
            });

            var check2 = new Func <Task>(async() =>
            {
                //key 1 was changed, value was changed to value 2
                (await _blockchainStateManager.GetStateAsync(_tv[1].Key, _tv[2].BlockHeight, _tv[2].BlockHash))
                .ShouldBe(_tv[2].Value);

                (await _blockchainStateManager.GetStateAsync(_tv[2].Key, _tv[2].BlockHeight, _tv[2].BlockHash))
                .ShouldBe(_tv[2].Value);
            });

            await check2();

            //but when we we can get value at the height of block height 1, also block hash 1
            await check1();

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet()
            {
                BlockHash    = _tv[3].BlockHash,
                BlockHeight  = _tv[3].BlockHeight,
                PreviousHash = _tv[2].BlockHash,
                Changes      =
                {
                    //override key 2 at height 3
                    {
                        _tv[2].Key,
                        _tv[4].Value
                    },
                }
            });

            var check3_1 = new Func <Task>(async() =>
            {
                (await _blockchainStateManager.GetStateAsync(_tv[2].Key, _tv[3].BlockHeight, _tv[3].BlockHash))
                .ShouldBe(_tv[4].Value);
            });


            await check1();
            await check2();
            await check3_1();

            await _blockStateSetManger.SetBlockStateSetAsync(new BlockStateSet()
            {
                BlockHash    = _tv[4].BlockHash,
                BlockHeight  = _tv[3].BlockHeight, // it's a branch
                PreviousHash = _tv[2].BlockHash,
                Changes      =
                {
                    //override key 2 at height 3
                    {
                        _tv[2].Key,
                        _tv[5].Value
                    },
                }
            });

            var check3_2 = new Func <Task>(async() =>
            {
                (await _blockchainStateManager.GetStateAsync(_tv[2].Key, _tv[3].BlockHeight, _tv[4].BlockHash))
                .ShouldBe(_tv[5].Value);
            });

            await check1();
            await check2();
            await check3_2();

            var chainStateInfo = await _blockStateSetManger.GetChainStateInfoAsync();

            await _blockStateSetManger.MergeBlockStateAsync(chainStateInfo, _tv[1].BlockHash);

            await check1();
            await check2();
            await check3_1();
            await check3_2();

            await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                 await _blockStateSetManger.MergeBlockStateAsync(chainStateInfo, _tv[3].BlockHash));

            await _blockStateSetManger.MergeBlockStateAsync(chainStateInfo, _tv[2].BlockHash);

            await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                 await check1());

            await check2();

            //test failed merge recover
            chainStateInfo.Status           = ChainStateMergingStatus.Merging;
            chainStateInfo.MergingBlockHash = _tv[4].BlockHash;

            //merge best to second branch
            await _blockStateSetManger.MergeBlockStateAsync(chainStateInfo, _tv[4].BlockHash);

            await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                 await check1());

            await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                 await check2());

            await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                 await check3_1());

            await check3_2();

            //test failed merge recover
            chainStateInfo.Status           = ChainStateMergingStatus.Merged;
            chainStateInfo.MergingBlockHash = _tv[4].BlockHash;
            await _blockStateSetManger.MergeBlockStateAsync(chainStateInfo, _tv[4].BlockHash);
        }