private BlockStateSet CreateBlockStateSet(Hash previousBlockHash, long blockHeight,
                                                  ExecutionReturnSetCollection executionReturnSetCollection)
        {
            var blockStateSet = new BlockStateSet
            {
                BlockHeight  = blockHeight,
                PreviousHash = previousBlockHash
            };

            foreach (var returnSet in executionReturnSetCollection.Executed)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                    blockStateSet.Deletes.Remove(change.Key);
                }

                foreach (var delete in returnSet.StateDeletes)
                {
                    blockStateSet.Deletes.AddIfNotContains(delete.Key);
                    blockStateSet.Changes.Remove(delete.Key);
                }
            }

            return(blockStateSet);
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
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();
        }
        private void CheckBlockExecutedData(BlockStateSet blockStateSet, Chain chain,
                                            TransactionResult transactionResult, Dictionary <string, Transaction> transactionDic)
        {
            var chainContext = new ChainContext
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            };
            var chainFromBlockExecutedData =
                _chainBlockchainExecutedDataService.GetBlockExecutedData(chainContext,
                                                                         GetBlockExecutedDataKey <Chain>());

            chainFromBlockExecutedData.ShouldBe(chain);

            var transactionResultFromBlockExecutedData =
                _transactionResultBlockchainExecutedDataService.GetBlockExecutedData(chainContext,
                                                                                     GetBlockExecutedDataKey <TransactionResult>(transactionResult.TransactionId));

            transactionResultFromBlockExecutedData.ShouldBe(transactionResult);
            foreach (var keyPair in transactionDic)
            {
                var transaction =
                    _transactionBlockchainExecutedDataService.GetBlockExecutedData(chainContext, keyPair.Key);
                transaction.ShouldBe(keyPair.Value);
            }
        }
Ejemplo n.º 6
0
        protected virtual async Task <Block> FillBlockAfterExecutionAsync(BlockHeader blockHeader, List <Transaction> transactions,
                                                                          ReturnSetCollection returnSetCollection)
        {
            Logger.LogTrace("Start block field filling after execution.");
            var bloom         = new Bloom();
            var blockStateSet = new BlockStateSet
            {
                BlockHeight  = blockHeader.Height,
                PreviousHash = blockHeader.PreviousBlockHash
            };

            foreach (var returnSet in returnSetCollection.Executed)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                    blockStateSet.Deletes.Remove(change.Key);
                }

                foreach (var delete in returnSet.StateDeletes)
                {
                    blockStateSet.Deletes.AddIfNotContains(delete.Key);
                    blockStateSet.Changes.Remove(delete.Key);
                }

                bloom.Combine(new[] { new Bloom(returnSet.Bloom.ToByteArray()) });
            }

            blockHeader.Bloom = ByteString.CopyFrom(bloom.Data);
            blockHeader.MerkleTreeRootOfWorldState = CalculateWorldStateMerkleTreeRoot(blockStateSet);

            var allExecutedTransactionIds = transactions.Select(x => x.GetHash()).ToList();
            var orderedReturnSets         = returnSetCollection.ToList().AsParallel()
                                            .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId)).ToList();

            blockHeader.MerkleTreeRootOfTransactionStatus =
                CalculateTransactionStatusMerkleTreeRoot(orderedReturnSets);

            blockHeader.MerkleTreeRootOfTransactions = CalculateTransactionMerkleTreeRoot(allExecutedTransactionIds);

            var blockHash = blockHeader.GetHashWithoutCache();
            var blockBody = new BlockBody();

            blockBody.TransactionIds.AddRange(allExecutedTransactionIds);

            var block = new Block
            {
                Header = blockHeader,
                Body   = blockBody
            };

            blockStateSet.BlockHash = blockHash;
            Logger.LogTrace("Set block state set.");

            await _blockchainStateService.SetBlockStateSetAsync(blockStateSet);

            Logger.LogTrace("Finish block field filling after execution.");
            return(block);
        }
        public async Task BlockState_MergeBlock_Normal()
        {
            var blockStateSet1 = new BlockStateSet()
            {
                BlockHeight  = 1,
                BlockHash    = Hash.Generate(),
                PreviousHash = Hash.Empty
            };
            var blockStateSet2 = new BlockStateSet()
            {
                BlockHeight  = 2,
                BlockHash    = Hash.Generate(),
                PreviousHash = blockStateSet1.BlockHash
            };
            var blockStateSet3 = new BlockStateSet()
            {
                BlockHeight  = 3,
                BlockHash    = Hash.Generate(),
                PreviousHash = blockStateSet2.BlockHash
            };

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

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

                var chainStateInfo = await _blockchainStateManager.GetChainStateInfoAsync();

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

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

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

                var chainStateInfo = await _blockchainStateManager.GetChainStateInfoAsync();

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

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

                var chainStateInfo = await _blockchainStateManager.GetChainStateInfoAsync();

                chainStateInfo.BlockHeight.ShouldBe(2);
                chainStateInfo.BlockHash.ShouldBe(blockStateSet2.BlockHash);
            }
        }
Ejemplo n.º 8
0
        private async Task <bool> CheckExecutedDataInStoreAsync(BlockStateSet blockStateSet, string key,
                                                                ByteString blockExecutedData)
        {
            var stateReturn = await _blockchainExecutedDataManager.GetExecutedCacheAsync(key, blockStateSet.BlockHeight,
                                                                                         blockStateSet.BlockHash);

            stateReturn.Value.ShouldBe(blockExecutedData);
            return(stateReturn.IsInStore);
        }
Ejemplo n.º 9
0
        public static TieredStateCache ToTieredStateCache(this BlockStateSet blockStateSet)
        {
            var groupStateCache = blockStateSet == null
                ? new TieredStateCache()
                : new TieredStateCache(
                new StateCacheFromPartialBlockStateSet(blockStateSet));

            return(groupStateCache);
        }
Ejemplo n.º 10
0
        public async Task <Block> FillBlockAfterExecutionAsync(BlockHeader blockHeader, List <Transaction> transactions,
                                                               List <ExecutionReturnSet> blockExecutionReturnSet)
        {
            var bloom         = new Bloom();
            var blockStateSet = new BlockStateSet
            {
                BlockHeight  = blockHeader.Height,
                PreviousHash = blockHeader.PreviousBlockHash
            };

            foreach (var returnSet in blockExecutionReturnSet)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                }

                if (returnSet.Status == TransactionResultStatus.Mined)
                {
                    bloom.Combine(new[] { new Bloom(returnSet.Bloom.ToByteArray()) });
                }
            }

            blockHeader.Bloom = ByteString.CopyFrom(bloom.Data);
            var merkleTreeRootOfWorldState = ComputeHash(GetDeterministicByteArrays(blockStateSet));

            blockHeader.MerkleTreeRootOfWorldState = merkleTreeRootOfWorldState;

            var allExecutedTransactionIds = transactions.Select(x => x.GetHash()).ToList();
            var bmt = new BinaryMerkleTree();

            bmt.AddNodes(allExecutedTransactionIds);
            blockHeader.MerkleTreeRootOfTransactions = bmt.ComputeRootHash();

            _blockExtraDataService.FillMerkleTreeRootExtraDataForTransactionStatus(blockHeader,
                                                                                   blockExecutionReturnSet.Select(executionReturn =>
                                                                                                                  (executionReturn.TransactionId, executionReturn.Status)));

            var blockBody = new BlockBody();

            blockBody.Transactions.AddRange(allExecutedTransactionIds);
            blockBody.TransactionList.AddRange(transactions);

            var block = new Block
            {
                Header = blockHeader,
                Body   = blockBody
            };

            blockBody.BlockHeader   = blockHeader.GetHash();
            blockStateSet.BlockHash = blockHeader.GetHash();

            await _blockchainStateManager.SetBlockStateSetAsync(blockStateSet);

            return(block);
        }
 private async Task AddBlockStateSetAsync(Block block)
 {
     var blockStateSet = new BlockStateSet
     {
         BlockHash    = block.GetHash(),
         BlockHeight  = block.Height,
         PreviousHash = block.Header.PreviousBlockHash
     };
     await _blockStateSetManger.SetBlockStateSetAsync(blockStateSet);
 }
Ejemplo n.º 12
0
        public void TryGetExecutedCache_Test()
        {
            var blockStateSet = new BlockStateSet();

            blockStateSet.TryGetExecutedCache("key1", out var value).ShouldBeFalse();

            blockStateSet.BlockExecutedData.Add("key1", ByteString.CopyFromUtf8("key1"));
            blockStateSet.TryGetExecutedCache("key1", out value).ShouldBeTrue();
            value.ShouldBe(ByteString.CopyFromUtf8("key1"));
        }
Ejemplo n.º 13
0
        private IEnumerable <byte[]> GetDeterministicByteArrays(BlockStateSet blockStateSet)
        {
            var keys = blockStateSet.Changes.Keys;

            foreach (var k in new SortedSet <string>(keys))
            {
                yield return(Encoding.UTF8.GetBytes(k));

                yield return(blockStateSet.Changes[k].ToByteArray());
            }
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
0
        public static bool TryGetExecutedCache(this BlockStateSet blockStateSet, string key, out ByteString value)
        {
            value = null;

            if (blockStateSet.BlockExecutedData.ContainsKey(key))
            {
                value = blockStateSet.BlockExecutedData[key];
                return(true);
            }

            return(false);
        }
Ejemplo n.º 16
0
        public async Task <Block> FillBlockAfterExecutionAsync(BlockHeader blockHeader, List <Transaction> transactions,
                                                               List <ExecutionReturnSet> blockExecutionReturnSet)
        {
            var bloom         = new Bloom();
            var blockStateSet = new BlockStateSet
            {
                BlockHeight  = blockHeader.Height,
                PreviousHash = blockHeader.PreviousBlockHash
            };

            foreach (var returnSet in blockExecutionReturnSet)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                }

                if (returnSet.Status == TransactionResultStatus.Mined)
                {
                    bloom.Combine(new[] { new Bloom(returnSet.Bloom.ToByteArray()) });
                }
            }

            blockHeader.Bloom = ByteString.CopyFrom(bloom.Data);
            blockHeader.MerkleTreeRootOfWorldState        = CalculateWorldStateMerkleTreeRoot(blockStateSet);
            blockHeader.MerkleTreeRootOfTransactionStatus =
                CalculateTransactionStatusMerkleTreeRoot(blockExecutionReturnSet);

            var allExecutedTransactionIds = transactions.Select(x => x.GetHash()).ToList();

            blockHeader.MerkleTreeRootOfTransactions = CalculateTransactionMerkleTreeRoot(allExecutedTransactionIds);

            var blockHash = blockHeader.GetHashWithoutCache();
            var blockBody = new BlockBody
            {
                BlockHeader = blockHash
            };

            blockBody.TransactionIds.AddRange(allExecutedTransactionIds);

            var block = new Block
            {
                Header = blockHeader,
                Body   = blockBody
            };

            blockBody.BlockHeader   = blockHash;
            blockStateSet.BlockHash = blockHash;

            await _blockchainStateManager.SetBlockStateSetAsync(blockStateSet);

            return(block);
        }
        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);
        }
Ejemplo n.º 18
0
        public BlockStateSet ToBlockStateSet()
        {
            var blockStateSet = new BlockStateSet();

            foreach (var returnSet in _executed)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                }
            }

            return(blockStateSet);
        }
Ejemplo n.º 19
0
        public static bool TryGetState(this BlockStateSet blockStateSet, string key, out ByteString value)
        {
            value = null;
            if (blockStateSet.Deletes.Contains(key))
            {
                return(true);
            }

            if (blockStateSet.Changes.ContainsKey(key))
            {
                value = blockStateSet.Changes[key];
                return(true);
            }

            return(false);
        }
Ejemplo n.º 20
0
        private Hash CalculateWorldStateMerkleTreeRoot(BlockStateSet blockStateSet)
        {
            Hash merkleTreeRootOfWorldState;
            var  byteArrays = GetDeterministicByteArrays(blockStateSet);

            using (var hashAlgorithm = SHA256.Create())
            {
                foreach (var bytes in byteArrays)
                {
                    hashAlgorithm.TransformBlock(bytes, 0, bytes.Length, null, 0);
                }

                hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);
                merkleTreeRootOfWorldState = Hash.FromByteArray(hashAlgorithm.Hash);
            }

            return(merkleTreeRootOfWorldState);
        }
Ejemplo n.º 21
0
        public void TryGetState_Test()
        {
            var blockStateSet = new BlockStateSet();

            blockStateSet.TryGetState("key1", out var value).ShouldBeFalse();

            blockStateSet.Deletes.Add("key1");
            blockStateSet.TryGetState("key1", out value).ShouldBeTrue();
            value.ShouldBeNull();

            blockStateSet.Changes.Add("key1", ByteString.CopyFromUtf8("key1"));
            blockStateSet.TryGetState("key1", out value).ShouldBeTrue();
            value.ShouldBeNull();

            blockStateSet.Changes.Add("key2", ByteString.CopyFromUtf8("key2"));
            blockStateSet.TryGetState("key2", out value).ShouldBeTrue();
            value.ShouldBe(ByteString.CopyFromUtf8("key2"));
        }
Ejemplo n.º 22
0
        public async Task CalculateFunctionMap_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 functionMapDict = new Dictionary <string, Dictionary <string, CalculateFunction> >();
            var functionMap     = GenerateFunctionMap();

            functionMapDict.Add(GetBlockExecutedDataKey(), functionMap);

            await _calculateFunctionExecutedDataService.AddBlockExecutedDataAsync(new BlockIndex
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            },
                                                                                  functionMapDict);

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

            newBlockStateSet.BlockHash.ShouldBe(blockStateSet.BlockHash);
            newBlockStateSet.BlockHeight.ShouldBe(blockStateSet.BlockHeight);
            newBlockStateSet.BlockExecutedData.Count.ShouldBe(1);
            newBlockStateSet.BlockExecutedData.Keys.ShouldContain(key =>
                                                                  key.Contains(typeof(AllCalculateFeeCoefficients).Name));

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            CheckBlockExecutedData(blockStateSet, functionMap);
            await BlockchainStateService.MergeBlockStateAsync(chain.BestChainHeight, chain.BestChainHash);

            CheckBlockExecutedData(blockStateSet, functionMap);

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            CheckBlockExecutedData(blockStateSet, functionMap);
        }
Ejemplo n.º 23
0
        public async Task TokenFeeProviderBase_Calculate_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 functionMap = GenerateFunctionMap();
            await _calculateFunctionProvider.AddCalculateFunctions(new BlockIndex
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            },
                                                                   functionMap);

            var transaction = new Transaction
            {
                Params = new SInt64Value
                {
                    Value = 100
                }.ToByteString()
            };
            var transactionContext = new TransactionContext
            {
                Transaction = transaction
            };
            var size         = transaction.Size();
            var chainContext = new ChainContext
            {
                BlockHash   = chain.BestChainHash,
                BlockHeight = chain.BestChainHeight
            };
            var sizeFee = await _primaryTokenFeeProvider.CalculateFeeAsync(transactionContext, chainContext);

            var feeCalculatedByCoefficients = GetFeeForTx(size);

            sizeFee.ShouldBe(feeCalculatedByCoefficients);
        }
Ejemplo n.º 24
0
        private void CheckBlockExecutedData(BlockStateSet blockStateSet,
                                            Dictionary <string, CalculateFunction> functionMap)
        {
            var chainContext = new ChainContext
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            };
            var functionMapFromBlockExecutedData =
                _calculateFunctionProvider.GetCalculateFunctions(chainContext);

            foreach (var key in functionMap.Keys)
            {
                var fromExecutedData = functionMapFromBlockExecutedData.Values.Single(d =>
                                                                                      ((FeeTypeEnum)d.CalculateFeeCoefficients.FeeTokenType).ToString().ToUpper() == key);
                var actual = functionMap.Values.Single(d =>
                                                       ((FeeTypeEnum)d.CalculateFeeCoefficients.FeeTokenType).ToString().ToUpper() == key);
                fromExecutedData.CalculateFeeCoefficients.ShouldBe(actual.CalculateFeeCoefficients);
            }
        }
Ejemplo n.º 25
0
        public async Task CalculateFunctionMap_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/AllCalculateFeeCoefficients";

            blockStateSet.BlockExecutedData.ShouldNotContainKey(blockExecutedDataKey);
            var functionMap = GenerateFunctionMap();
            await _calculateFunctionProvider.AddCalculateFunctions(new BlockIndex
            {
                BlockHash   = blockStateSet.BlockHash,
                BlockHeight = blockStateSet.BlockHeight
            },
                                                                   functionMap);

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

            newBlockStateSet.BlockHash.ShouldBe(blockStateSet.BlockHash);
            newBlockStateSet.BlockHeight.ShouldBe(blockStateSet.BlockHeight);
            newBlockStateSet.BlockExecutedData.Count.ShouldBe(1);
            newBlockStateSet.BlockExecutedData.ShouldContainKey(blockExecutedDataKey);

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            CheckBlockExecutedData(blockStateSet, functionMap);
            await BlockchainStateService.MergeBlockStateAsync(chain.BestChainHeight, chain.BestChainHash);

            CheckBlockExecutedData(blockStateSet, functionMap);

            blockStateSet = await AddBlockStateSetAsync(blockStateSet);

            CheckBlockExecutedData(blockStateSet, functionMap);
        }
Ejemplo n.º 26
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);
        }
Ejemplo n.º 27
0
        public BlockStateSet ToBlockStateSet()
        {
            var blockStateSet = new BlockStateSet();

            foreach (var returnSet in _executed)
            {
                foreach (var change in returnSet.StateChanges)
                {
                    blockStateSet.Changes[change.Key] = change.Value;
                    blockStateSet.Deletes.Remove(change.Key);
                }

                foreach (var delete in returnSet.StateDeletes)
                {
                    blockStateSet.Deletes.AddIfNotContains(delete.Key);
                    blockStateSet.Changes.Remove(delete.Key);
                }
            }

            return(blockStateSet);
        }
Ejemplo n.º 28
0
        public void StateCacheFromPartialBlockStateSet_Test()
        {
            var path            = new StatePath();
            var deleteStatePath = new ScopedStatePath
            {
                Address = SampleAddress.AddressList[0],
                Path    = path
            };
            var changeStatePath = new ScopedStatePath
            {
                Address = SampleAddress.AddressList[1],
                Path    = path
            };
            var blockStateSet = new BlockStateSet
            {
                Deletes = { deleteStatePath.ToStateKey() },
                Changes = { { changeStatePath.ToStateKey(), ByteString.Empty } },
            };
            var stateCacheFromPartialBlockStateSet = new StateCacheFromPartialBlockStateSet(blockStateSet);
            var notExistStatePath = new ScopedStatePath
            {
                Address = SampleAddress.AddressList[2],
                Path    = path
            };

            stateCacheFromPartialBlockStateSet.TryGetValue(deleteStatePath, out var deletedValue).ShouldBeTrue();
            deletedValue.ShouldBeNull();
            stateCacheFromPartialBlockStateSet[deleteStatePath].ShouldBeNull();

            stateCacheFromPartialBlockStateSet.TryGetValue(changeStatePath, out var changeValue).ShouldBeTrue();
            changeValue.ShouldBe(ByteString.Empty);
            stateCacheFromPartialBlockStateSet[changeStatePath].ShouldBe(ByteString.Empty.ToByteArray());

            stateCacheFromPartialBlockStateSet.TryGetValue(notExistStatePath, out var value).ShouldBeFalse();
            value.ShouldBeNull();
            stateCacheFromPartialBlockStateSet[notExistStatePath].ShouldBeNull();

            stateCacheFromPartialBlockStateSet[notExistStatePath] = ByteString.Empty.ToByteArray();
            stateCacheFromPartialBlockStateSet[notExistStatePath].ShouldBeNull();
        }
Ejemplo n.º 29
0
        private async Task <ExecutionReturnSetMergeResult> ExecuteParallelizableTransactionsAsync(
            List <List <Transaction> > groupedTransactions, BlockHeader blockHeader, BlockStateSet blockStateSet,
            CancellationToken cancellationToken)
        {
            var tasks = groupedTransactions.Select(
                txns => ExecuteAndPreprocessResult(new TransactionExecutingDto
            {
                BlockHeader          = blockHeader,
                Transactions         = txns,
                PartialBlockStateSet = blockStateSet
            }, cancellationToken));
            var results = await Task.WhenAll(tasks);

            Logger.LogTrace("Executed parallelizables.");

            var executionReturnSets = MergeResults(results, out var conflictingSets);

            Logger.LogTrace("Merged results from parallelizables.");
            return(new ExecutionReturnSetMergeResult
            {
                ExecutionReturnSets = executionReturnSets,
                ConflictingReturnSets = conflictingSets
            });
        }
Ejemplo n.º 30
0
 private string GetKey(BlockStateSet blockStateSet)
 {
     return(blockStateSet.BlockHash.ToStorageKey());
 }