private BlockVm GenerateBlock(object @object) { try { BlockVm block = (BlockVm)@object; Task <byte[]> hashGenerationProcess = new Task <byte[]>((obj) => BlockHashing.ComputeBlockHashPoW((BlockVm)obj), block); hashGenerationProcess.Start(); while (!hashGenerationProcess.IsCompleted) { blockGenerationCancellToken.ThrowIfCancellationRequested(); Task.Delay(250).Wait(); } block.Header.Hash = hashGenerationProcess.Result; block.Header.Sign = Encryptor.GetSign(BlockHashing.GetBlockBytes(block), NodeData.Instance.NodeKeys.SignPrivateKey, NodeData.Instance.NodeKeys.Password); block.Header.SignKeyId = NodeData.Instance.NodeKeys.KeyId; using (BlockchainDbContext context = new BlockchainDbContext()) { var resultBlock = context.Add(BlockBuilder.GetBlock(block)); context.SaveChanges(); return(BlockBuilder.GetBlockVm(resultBlock.Entity)); } } catch (Exception ex) { throw new BlockGenerationException("An error occurred while generating the block.", ex); } }
private async Task SaveAndRemoveOldBlocksAsync(long blockId) { using (BlockchainDbContext context = new BlockchainDbContext()) { long maxId = await context.Blocks.MaxAsync(opt => opt.Id).ConfigureAwait(false); byte limit = 100; if (maxId < blockId) { return; } for (long i = blockId; i < maxId; i += limit) { var blocks = await context.Blocks .Include(opt => opt.BlockSegments) .ThenInclude(opt => opt.SegmentHeader) .Include(opt => opt.Header) .Where(opt => opt.Id > i) .Take(limit) .ToListAsync().ConfigureAwait(false); var obsoleteBlocks = blocks.Select(opt => new ObsoleteBlock { Id = opt.Id, Data = ObjectSerializer.ObjectToByteArray(BlockBuilder.GetBlockVm(opt)) }); await context.ObsoleteBlocks.AddRangeAsync(obsoleteBlocks).ConfigureAwait(false); await context.SaveChangesAsync().ConfigureAwait(false); } NpgsqlParameter blockIdParam = new NpgsqlParameter("blockId", blockId); RawSqlString sqlString = new RawSqlString(@"DELETE FROM ""Blocks"" WHERE ""Id"" > @blockId"); await context.Database.ExecuteSqlCommandAsync(sqlString, blockIdParam).ConfigureAwait(false); } }