public static AssetCoinholdersViewModel Create(AssetViewModel asset,
                                                       IBalanceSummary balanceSummary,
                                                       int?atBlockHeight,
                                                       IDictionary <string, double> addressChanges,
                                                       IEnumerable <IBalanceBlock> blocksWithChanges,
                                                       IBlockHeader currentBlock,
                                                       IBlockHeader atBlockInfo)
        {
            var total            = balanceSummary.AddressSummaries.Sum(p => p.Balance);
            var addressSummaries = balanceSummary.AddressSummaries
                                   .Select(
                p =>
                BalanceAddressSummary.Create(p, total, asset.Divisibility,
                                             addressChanges.ContainsKey(p.Address) ? addressChanges[p.Address] : 0))
                                   .Where(p => p.Balance != 0 || p.ChangeAtBlock != 0)
                                   .OrderByDescending(p => p.Balance)
                                   .ToList();

            return(new AssetCoinholdersViewModel
            {
                Asset = asset,
                AddressSummaries = addressSummaries,
                Total = BitcoinUtils.CalculateColoredAssetQuantity(total, asset.Divisibility),
                Pagination = BlockPagination.Create(blocksWithChanges.Select(p => p.Height), atBlockHeight ?? currentBlock?.Height, currentBlock),
                CoinholdersCount = addressSummaries.Count,
                AtBlockDateTime = (atBlockInfo ?? currentBlock)?.Time.ToUniversalTime()
            });
        }
Beispiel #2
0
        protected async Task CheckHeaderAppendable(IBlockHeader header)
        {
            var blockHeader = (BlockHeader)header;

            #region genesis
            // TODO: more strict genesis
            if (blockHeader.Index == GlobalConfig.GenesisBlockHeight)
            {
                var curHash = await _chainManager.GetCurrentBlockHashAsync(_chainId);

                if (curHash.IsNull())
                {
                    await _chainManager.AddChainAsync(_chainId, header.GetHash());
                }
                return;
            }

            #endregion genesis
            var prevHeader = await GetHeaderByHashAsync(blockHeader.PreviousBlockHash);

            if (prevHeader == null)
            {
                throw new InvalidOperationException($"Parent is unknown for {blockHeader}.");
            }

            var expected = ((BlockHeader)prevHeader).Index + 1;
            var actual   = blockHeader.Index;

            if (actual != expected)
            {
                throw new InvalidOperationException($"Incorrect index. Expected: {expected}, actual: {actual}");
            }
        }
Beispiel #3
0
 public static Dictionary MarshalBlockHeader(this IBlockHeader header) =>
 MarshalBlockHeader(
     MarshalPreEvaluationBlockHeader(header),
     header.StateRootHash,
     header.Signature,
     header.Hash
     );
Beispiel #4
0
        public Mock <IBlock> MockBlock(IBlockHeader header, IBlockBody body)
        {
            Mock <IBlock> mock = new Mock <IBlock>();

            mock.Setup(b => b.Header).Returns((BlockHeader)header);
            mock.Setup(b => b.Body).Returns((BlockBody)body);
            return(mock);
        }
Beispiel #5
0
        protected async Task AddHeaderAsync(IBlockHeader header)
        {
            await CheckHeaderAppendable(header);

            await _blockManager.AddBlockHeaderAsync((BlockHeader)header);

            await MaybeSwitchBranch(header);

            MessageHub.Instance.Publish((BlockHeader)header);
        }
Beispiel #6
0
        protected async Task MaybeSwitchBranch(IBlockHeader header)
        {
            var blockHeader = (BlockHeader)header;

            if (blockHeader.Index <= GlobalConfig.GenesisBlockHeight)
            {
                var hash = GetHeightHash(blockHeader.Index).OfType(HashType.CanonicalHash);
//                hash.Height = blockHeader.Index;
                await _dataStore.InsertAsync(hash, header.GetHash());

                await _chainManager.UpdateCurrentBlockHashAsync(_chainId, header.GetHash());

                return;
            }

            var currentBlockHash = await GetCurrentBlockHashAsync();

            var currentHeader = await GetHeaderByHashAsync(currentBlockHash);

            if (currentHeader.GetHash().Equals(((BlockHeader)header).PreviousBlockHash) ||
                ((BlockHeader)header).PreviousBlockHash.Equals(Hash.Genesis))
            {
                var hash = GetHeightHash(((BlockHeader)header).Index).OfType(HashType.CanonicalHash);
//                hash.Height = ((BlockHeader) header).Index;
                await _dataStore.InsertAsync(hash, header.GetHash());

                await _chainManager.UpdateCurrentBlockHashAsync(_chainId, header.GetHash());

                return;
            }

            if (((BlockHeader)header).Index > ((BlockHeader)currentHeader).Index)
            {
                await _chainManager.UpdateCurrentBlockHashAsync(_chainId, header.GetHash());

                var branches = await GetComparedBranchesAsync(currentHeader, header);

                if (branches.Item2.Count > 0)
                {
                    foreach (var newBranchHeader in branches.Item2)
                    {
                        if (newBranchHeader == null)
                        {
                            break;
                        }

                        var hash = GetHeightHash(((BlockHeader)newBranchHeader).Index).OfType(HashType.CanonicalHash);
//                        hash.Height = ((BlockHeader) newBranchHeader).Index;
                        await _dataStore.InsertAsync(hash, newBranchHeader.GetHash());
                    }
                }
            }
        }
Beispiel #7
0
 /// <summary>
 /// Creates a <see cref="Block{T}"/> instance by combining a block <paramref name="header"/>
 /// and <paramref name="transactions"/>.
 /// </summary>
 /// <param name="header">The block header.</param>
 /// <param name="transactions">The transactions to include.</param>
 /// <exception cref="InvalidBlockProtocolVersionException">Thrown when
 /// the <paramref name="header"/>'s <see cref="IBlockMetadata.ProtocolVersion"/>
 /// is less than 0, or greater than <see cref="BlockMetadata.CurrentProtocolVersion"/>,
 /// the latest known protocol version.</exception>
 /// <exception cref="InvalidBlockIndexException">Thrown when the <paramref name="header"/>
 /// has a negative <see cref="IBlockMetadata.Index"/>.</exception>
 /// <exception cref="InvalidBlockDifficultyException">Thrown when
 /// the <paramref name="header"/>'s <see cref="IBlockMetadata.Difficulty"/> is negative.
 /// </exception>
 /// <exception cref="InvalidBlockTotalDifficultyException">Thrown when
 /// the <paramref name="header"/>'s <see cref="IBlockMetadata.TotalDifficulty"/> is less
 /// than its <see cref="IBlockMetadata.Difficulty"/>.</exception>
 /// <exception cref="InvalidTxSignatureException">Thrown when any tx signature is invalid or
 /// not signed by its signer.</exception>
 /// <exception cref="InvalidTxPublicKeyException">Thrown when any tx signer is not derived
 /// from its its public key.</exception>
 /// <exception cref="InvalidTxNonceException">Thrown when the same tx nonce is used by
 /// a signer twice or more, or a tx nonce is used without its previous nonce by a signer.
 /// Note that this validates only a block's intrinsic integrity between its transactions,
 /// but does not guarantee integrity between blocks.  Such validation needs to be conducted
 /// by <see cref="Blockchain.BlockChain{T}"/>.</exception>
 /// <exception cref="InvalidTxGenesisHashException">Thrown when transactions to set have
 /// inconsistent genesis hashes.</exception>
 /// <exception cref="InvalidBlockTxHashException">Thrown when the given block
 /// <paramref name="header"/>'s <see cref="IBlockMetadata.TxHash"/> is not consistent with
 /// its <paramref name="transactions"/>.</exception>
 /// <exception cref="InvalidBlockPreEvaluationHashException">Thrown when the given
 /// <paramref name="header"/> has an invalid
 /// <see cref="IPreEvaluationBlockHeader.PreEvaluationHash"/>.</exception>
 /// <exception cref="InvalidBlockNonceException">Thrown when the given
 /// <paramref name="header"/>'s <see cref="IPreEvaluationBlockHeader.Nonce"/> does not
 /// satisfy the required <see cref="PreEvaluationBlockHeader.Difficulty"/>.</exception>
 public Block(IBlockHeader header, IEnumerable <Transaction <T> > transactions)
     : this(
         new PreEvaluationBlock <T>(
             new BlockContent <T>(header, transactions),
             header.HashAlgorithm,
             header.Nonce,
             header.PreEvaluationHash
             ),
         header.StateRootHash,
         header.Signature
         )
 {
 }
Beispiel #8
0
        public static BlockHeaderViewModel Create(IBlockHeader header)
        {
            if (header != null)
            {
                return(new BlockHeaderViewModel
                {
                    BlockId = header.Hash,
                    Height = header.Height
                });
            }

            return(null);
        }
Beispiel #9
0
        protected async Task <Tuple <List <IBlockHeader>, List <IBlockHeader> > > GetComparedBranchesAsync(
            IBlockHeader oldHead,
            IBlockHeader newHead)
        {
            var tempOldHead = (BlockHeader)oldHead;
            var tempNewHead = (BlockHeader)newHead;
            var oldBranch   = new List <IBlockHeader>();
            var newBranch   = new List <IBlockHeader>();

            while (((BlockHeader)oldHead).Index > ((BlockHeader)newHead).Index)
            {
                oldBranch.Add(tempOldHead);
                tempOldHead = (BlockHeader) await GetHeaderByHashAsync(tempOldHead.PreviousBlockHash);
            }

            while (((BlockHeader)newHead).Index > ((BlockHeader)oldHead).Index)
            {
                newBranch.Add(tempNewHead);
                if (tempNewHead == null)
                {
                    break;
                }
                tempNewHead = (BlockHeader) await GetHeaderByHashAsync(tempNewHead.PreviousBlockHash);
            }

            while (tempNewHead != null && tempOldHead.PreviousBlockHash != tempNewHead.PreviousBlockHash)
            {
                oldBranch.Add(tempOldHead);
                newBranch.Add(tempNewHead);
                tempOldHead = (BlockHeader) await GetHeaderByHashAsync(tempOldHead.PreviousBlockHash);

                tempNewHead = (BlockHeader) await GetHeaderByHashAsync(tempNewHead.PreviousBlockHash);
            }

            if (tempOldHead != null && tempNewHead != null)
            {
                oldBranch.Add(tempOldHead);
                newBranch.Add(tempNewHead);
            }

            return(Tuple.Create(oldBranch, newBranch));
        }
 public static BlockViewModel Create(IBlock ninjaBlock, 
     IBlockHeader lastBlock)
 {
     return new BlockViewModel
     {
         Confirmations = ninjaBlock.Confirmations,
         Difficulty = ninjaBlock.Difficulty,
         Hash = ninjaBlock.Hash,
         Height = ninjaBlock.Height,
         MerkleRoot = ninjaBlock.MerkleRoot,
         Nonce = ninjaBlock.Nonce,
         PreviousBlock = ninjaBlock.PreviousBlock,
         Time = ninjaBlock.Time,
         AllTransactionIdList = new TransactionIdList(ninjaBlock.AllTransactionIds),
         ColoredTransactionIdList = new TransactionIdList(ninjaBlock.ColoredTransactionIds),
         UncoloredTransactionIdList = new TransactionIdList(ninjaBlock.UncoloredTransactionIds),
         TotalTransactions = ninjaBlock.TotalTransactions,
         ShowNextBlock = ninjaBlock.Height < lastBlock?.Height,
         NextBlockHeight = ninjaBlock.Height + 1
     };
 }
        public static AddressBalanceViewModel Create(IAddressBalance balance,
                                                     IReadOnlyDictionary <string, IAssetDefinition> assetDictionary,
                                                     IBlockHeader lastBlock,
                                                     IBlockHeader atBlock,
                                                     IEnumerable <IGroup> offchainGroups,
                                                     bool isHub)
        {
            var onchainColoredBalances =
                (balance.ColoredBalances ?? Enumerable.Empty <IColoredBalance>()).Select(p =>
                                                                                         ColoredBalance.Create(p, assetDictionary)).ToList();

            var existedOnchainAssetsBalances = onchainColoredBalances.Select(p => p.AssetId).ToDictionary(p => p);

            //show balances for offchain assets with 0 onchain balance
            var missedOffchainColoredBalances = offchainGroups.Where(p => p.IsColored && !existedOnchainAssetsBalances.ContainsKey(p.AssetId))
                                                .Select(p => p.AssetId)
                                                .Distinct()
                                                .Select(assetId => ColoredBalance.CreateEmpty(assetId, assetDictionary));

            return(new AddressBalanceViewModel
            {
                AddressId = balance.AddressId,
                TotalConfirmedTransactions = balance.TotalTransactions,
                Balance = balance.BtcBalance,
                Assets = onchainColoredBalances.Union(missedOffchainColoredBalances).ToList(),
                UnconfirmedBalanceDelta = balance.UnconfirmedBalanceDelta,
                AssetDic = AssetDictionary.Create(assetDictionary),
                LastBlockHeight = lastBlock.Height,
                LastBlockDateTime = lastBlock.Time,
                AtBlockHeight = (atBlock ?? lastBlock).Height,
                AtBlockDateTime = (atBlock ?? lastBlock).Time,
                OffchainGroupsByAsset = OffchainGroupsByAsset.Create(offchainGroups, assetDictionary),
                TotalTransactionsCountCalculated = balance.TotalTransactionsCountCalculated,
                TotalSpendedTransactions = balance.TotalSpendedTransactions,
                TotalSpendedTransactionsCountCalculated = balance.TotalSpendedTransactionsCountCalculated,
                TotalReceivedTransactions = balance.TotalReceivedTransactions,
                TotalReceivedTransactionsCountCalculated = balance.TotalReceivedTransactionsCountCalculated,
                IsOffchainHub = isHub
            });
        }
Beispiel #12
0
        public async Task ParseLast()
        {
            IBlockHeader blockPtr = null;

            try
            {
                _console.Write(nameof(ParseBlocksFunctions), nameof(ParseLast), null, "Started");

                blockPtr = await _blockService.GetLastBlockHeaderAsync();

                while (blockPtr != null &&
                       !await _assetDefinitionParsedBlockRepository
                       .IsBlockExistsAsync(AssetDefinitionParsedBlock.Create(blockPtr.Hash)))
                {
                    _console.Write(nameof(ParseBlocksFunctions),
                                   nameof(ParseLast),
                                   new { blockPtr.Hash, blockPtr.Height }.ToJson(),
                                   $"Add parse block command {blockPtr.Height}");

                    await _parseBlockCommandProducer.CreateParseBlockCommand(blockPtr.Hash);

                    blockPtr = await _blockService.GetBlockHeaderAsync((blockPtr.Height - 1).ToString());
                }

                _console.Write(nameof(ParseBlocksFunctions), nameof(ParseLast), null, "Done");
            }
            catch (Exception e)
            {
                await _log.WriteErrorAsync(nameof(ParseBlocksFunctions),
                                           nameof(ParseLast),
                                           new { blockHash = blockPtr?.Hash }.ToJson(),
                                           e);

                throw;
            }
        }
Beispiel #13
0
 public byte[] Mine(IBlockHeader blockheader)
 {
     throw new NotImplementedException();
 }
Beispiel #14
0
 public Block(IBlockHeader blockHeader, IBlockBody blockBody)
 {
     BlockHeader = blockHeader;
     BlockBody   = blockBody;
 }
Beispiel #15
0
 public Block(IBlockHeader header, List <ITransaction> transactions)
 {
     this.BlockHeader  = header;
     this.Transactions = transactions;
 }
Beispiel #16
0
 public GenesisBlock(IBlockHeader blockHeader, IBlockBody blockBody)
 {
     BlockHeader = blockHeader;
     BlockBody   = blockBody;
 }
Beispiel #17
0
 //Constructor
 public Block(List <string> data, IBlockHeader header)
 {
     _tree   = new MerkleTree();
     _header = (Header)header;
 }
Beispiel #18
0
 private void FillHeaderData(IBlockHeader header, Block result)
 {
     result.Confirmations = header.Confirmations;
     result.Height        = header.Height;
 }
Beispiel #19
0
 /// <summary>
 /// Mine the specified blockheader.
 /// </summary>
 /// <returns>does not but serilize the block</returns>
 /// <param name="blockheader">Blockheader.</param>
 public byte[] Mine(IBlockHeader blockheader)
 {
     // TODO: return a serlized block header
     return(null);
 }
            public static BlockPagination Create(IEnumerable <int> changedAtHeights, int?atBlock, IBlockHeader currentBlock)
            {
                var ordered = changedAtHeights.OrderBy(p => p).ToList();
                var at      = atBlock ?? ordered.LastOrDefault();

                if (currentBlock != null)
                {
                    ordered.Add(currentBlock.Height);
                }


                var result = new BlockPagination
                {
                    ChangedAtHeights = ordered.Distinct().ToList(),
                    AtBlock          = at,
                    ShowCurrentBlock = atBlock != null
                };

                return(result);
            }