public async Task NewBlockDiscoveredAsync(NewBlockDiscoveredEvent e) { var blockHash = new uint256(e.BlockHash); // If block is already present in DB, there is no need to parse it again var blockInDb = await txRepository.GetBlockAsync(blockHash.ToBytes()); if (blockInDb != null) { return; } logger.LogInformation($"Block parser got a new block {e.BlockHash} inserting into database"); var blockHeader = await rpcMultiClient.GetBlockHeaderAsync(e.BlockHash); var blockCount = (await rpcMultiClient.GetBestBlockchainInfoAsync()).Blocks; // If received block that is too far from the best tip, we don't save the block anymore and // stop verifying block chain if (blockHeader.Height < blockCount - appSettings.MaxBlockChainLengthForFork) { PushBlocksToEventQueue(); return; } var dbBlock = new Block { BlockHash = blockHash.ToBytes(), BlockHeight = blockHeader.Height, BlockTime = HelperTools.GetEpochTime(blockHeader.Time), OnActiveChain = true, PrevBlockHash = blockHeader.Previousblockhash == null?uint256.Zero.ToBytes() : new uint256(blockHeader.Previousblockhash).ToBytes() }; // Insert block in DB and add the event to block stack for later processing var blockId = await txRepository.InsertBlockAsync(dbBlock); if (blockId.HasValue) { dbBlock.BlockInternalId = blockId.Value; } else { return; } newBlockStack.Push(new NewBlockAvailableInDB() { CreationDate = clock.UtcNow(), BlockHash = new uint256(dbBlock.BlockHash).ToString(), BlockDBInternalId = dbBlock.BlockInternalId, }); await VerifyBlockChain(blockHeader.Previousblockhash); }
public async Task InitializeDB() { var dbIsEmpty = await txRepository.GetBestBlockAsync() == null; var bestBlockHash = (await rpcMultiClient.GetBestBlockchainInfoAsync()).BestBlockHash; if (dbIsEmpty) { var blockHeader = await rpcMultiClient.GetBlockHeaderAsync(bestBlockHash); var dbBlock = new Block { BlockHash = new uint256(bestBlockHash).ToBytes(), BlockHeight = blockHeader.Height, BlockTime = HelperTools.GetEpochTime(blockHeader.Time), OnActiveChain = true, PrevBlockHash = blockHeader.Previousblockhash == null?uint256.Zero.ToBytes() : new uint256(blockHeader.Previousblockhash).ToBytes() }; await txRepository.InsertBlockAsync(dbBlock); } }