public void TotalDifficulty() { BlockMetadata a = BlockMetadata1.Copy(); a.TotalDifficulty = BlockMetadata1.TotalDifficulty + 10; Assert.Equal(BlockMetadata1.TotalDifficulty + 10, a.TotalDifficulty); Assert.Equal(BlockMetadata1.Difficulty, a.Difficulty); BlockMetadata b = Block1.Copy(); InvalidBlockTotalDifficultyException e = Assert.Throws <InvalidBlockTotalDifficultyException>(() => b.TotalDifficulty = -1); Assert.Equal(BlockMetadata1.TotalDifficulty, b.TotalDifficulty); Assert.Equal(BlockMetadata1.Difficulty, b.Difficulty); Assert.Equal(b.Difficulty, e.Difficulty); Assert.Equal(-1, e.TotalDifficulty); e = Assert.Throws <InvalidBlockTotalDifficultyException>( () => b.TotalDifficulty = b.Difficulty - 1L ); Assert.Equal(BlockMetadata1.TotalDifficulty, b.TotalDifficulty); Assert.Equal(BlockMetadata1.Difficulty, b.Difficulty); Assert.Equal(b.Difficulty, e.Difficulty); Assert.Equal(b.Difficulty - 1L, e.TotalDifficulty); }
public MethodMetadata(string methodName) : base(methodName) { this.parameters = new Dictionary<string, ParameterExp>(); this.parameterPosition = -1; this.returnType = typeof(void); this.block = null; }
public Block ReadBlock(BlockMetadata metadata) { try { byte[] data = new byte[metadata.Size]; int bytesRead; while (numberBlockReader != metadata.Number) { // Начинаем читать только в упорядоченном направлении. // Долгим тестированием выяснено, что засыпание (Thread.Sleep() не ускоряет процесс поиска, // так как операции чтения-записи на установленных нами размерах (1 МБайт) блоков // работы 2х-8 потоков выполняются достаточно быстро и цикл работает не столь долго } lock (lockReader) { bytesRead = reader.Read(data, 0, metadata.Size); numberBlockReader++; } /// Делается один раз с самым последним блоком. И то при сжатии, потому что он может не содержать столько байт сколько мы указываем if (bytesRead < metadata.Size) { metadata.Size = bytesRead; byte[] shortArray = data.Take(bytesRead).ToArray(); data = null; return(new Block(metadata.Number, shortArray)); } /// return(new Block(metadata.Number, data)); } catch (IOException e) { throw new IOException("Не удалось прочитать блок данных с номером {0} из файла", metadata.Number); } }
/// <summary> /// Gathers <see cref="Transaction{T}"/>s for mining a next block /// from the current set of staged <see cref="Transaction{T}"/>s. /// </summary> /// <param name="metadata">The metadata of the block to be mined.</param> /// <param name="maxTransactions">The maximum number of <see cref="Transaction{T}"/>s /// allowed.</param> /// <param name="maxTransactionsPerSigner">The maximum number of /// <see cref="Transaction{T}"/>s with the same signer allowed.</param> /// <param name="txPriority">An optional comparer for give certain transactions to /// priority to belong to the block. No certain priority by default.</param> /// <returns>An <see cref="ImmutableList"/> of <see cref="Transaction{T}"/>s with its /// count not exceeding <paramref name="maxTransactions"/> and the number of /// <see cref="Transaction{T}"/>s in the list for each signer not exceeding /// <paramref name="maxTransactionsPerSigner"/>.</returns> internal ImmutableList <Transaction <T> > GatherTransactionsToMine( BlockMetadata metadata, int maxTransactions, int maxTransactionsPerSigner, IComparer <Transaction <T> > txPriority = null ) { long index = Count; ImmutableList <Transaction <T> > stagedTransactions = ListStagedTransactions(txPriority); _logger.Information( "Gathering transactions to mine for block #{Index} from {TransactionsCount} " + "staged transactions...", index, stagedTransactions.Count); var transactionsToMine = new List <Transaction <T> >(); // FIXME: The tx collection timeout should be configurable. DateTimeOffset timeout = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(4); HashAlgorithmType hashAlgorithm = Policy.GetHashAlgorithm(index); // Makes an empty block payload to estimate the length of bytes without transactions. // FIXME: We'd better to estimate only transactions rather than the whole block. var dumbSig = metadata.PublicKey is null ? (ImmutableArray <byte>?)null : ImmutableArray.Create(new byte[71]); Bencodex.Types.Dictionary marshaledEmptyBlock = MarshalBlock( marshaledBlockHeader: MarshalBlockHeader( marshaledPreEvaluatedBlockHeader: MarshalPreEvaluationBlockHeader( marshaledMetadata: MarshalBlockMetadata(metadata), nonce: default,
public void MetadataSerializationTest() { var props = new [] { new DocumentMetadata(new DocumentId(1000), "Title 1"), new DocumentMetadata(new DocumentId(1001), "Title 2"), new DocumentMetadata(new DocumentId(1002), "Title 3"), }; var metadata = new BlockMetadata(100, props); var stream = new MemoryStream(); metadata.Serialize(stream); stream.Seek(0, SeekOrigin.Begin); var deserializedMetadata = BlockMetadata.Deserialize(stream); Assert.Equal(metadata.Id, deserializedMetadata.Id); foreach (var kv in props) { Assert.Equal(kv.Id.Id, deserializedMetadata[kv.Id].Id.Id); Assert.Equal(kv.Title, deserializedMetadata[kv.Id].Title); } }
public void CopyConstructor() { var g = new BlockMetadata(Genesis); AssertBlockMetadataEqual(Genesis, g); var b1 = new BlockMetadata(Block1); AssertBlockMetadataEqual(Block1, b1); }
public BlockDigest(BlockHeader header, ImmutableArray <ImmutableArray <byte> > txIds) { _metadata = header.Copy(); _nonce = header.Nonce; _preEvaluationHash = header.PreEvaluationHash; StateRootHash = header.StateRootHash; Signature = header.Signature; Hash = header.Hash; TxIds = txIds; }
private void WriteMetadataBlock(long originalPosition, long compressedPosition, int size) { var blockMetadata = new BlockMetadata { OriginalPosition = originalPosition, CompressedPosition = compressedPosition, SizeInBytes = size }; _fileMetadata.Add(blockMetadata); }
public void Difficulty() { BlockMetadata a = BlockMetadata1.Copy(); a.Difficulty = BlockMetadata1.Difficulty + 10L; Assert.Equal(BlockMetadata1.Difficulty + 10L, a.Difficulty); Assert.Equal(BlockMetadata1.TotalDifficulty + 10, a.TotalDifficulty); BlockMetadata b = BlockMetadata1.Copy(); Assert.Throws <InvalidBlockDifficultyException>(() => b.Difficulty = -1); Assert.Equal(BlockMetadata1.Difficulty, b.Difficulty); }
public static byte[] DecompressBlock(Stream compressedFileStream, BlockMetadata block) { var compressedBuffer = new byte[block.SizeInBytes]; compressedFileStream.Read(compressedBuffer, 0, compressedBuffer.Length); var compressedStream = new MemoryStream(compressedBuffer); using var decompressedMemoryStream = new MemoryStream(); using var decompressionStream = new GZipStream(compressedStream, CompressionMode.Decompress); decompressionStream.CopyTo(decompressedMemoryStream); return(decompressedMemoryStream.ToArray()); }
public void Processing(UserThreadPool pool, FileReaderWriter readerWriter) { int blockCount = readerWriter.GetNumberOfBlocks(BLOCK_SIZE); for (int i = 0; i < blockCount; i++) { BlockMetadata metadata = new BlockMetadata(BLOCK_SIZE); Task task = new Task(metadata, (blockData) => Compress(blockData), readerWriter); pool.Execute(task); } }
public void Processing(UserThreadPool pool, FileReaderWriter readerWriter) { readerWriter.ReadInfoBlocksAtTheEndFile(); ///Составление задач foreach (var block in readerWriter.SizeCompressedBlockList) { BlockMetadata metadata = new BlockMetadata(block); Task task = new Task(metadata, (blockData) => Decompress(blockData), readerWriter); pool.Execute(task); } }
public void ValidateTimestamp() { DateTimeOffset now = DateTimeOffset.UtcNow; DateTimeOffset future = now + TimeSpan.FromSeconds(17); IBlockMetadata metadata = new BlockMetadata { Timestamp = future, }; Assert.Throws <InvalidBlockTimestampException>(() => metadata.ValidateTimestamp(now)); // It's okay because 3 seconds later. metadata.ValidateTimestamp(now + TimeSpan.FromSeconds(3)); }
private static BlockInformation[] GetBlocksInternal() { var blocks = UnicodeInfo.GetBlocks(); var blockViewModel = new BlockInformation[blocks.Length]; for (int i = 0; i < blocks.Length; i++) { var block = blocks[i]; blockViewModel[i] = new BlockInformation(block.Name, BlockMetadata.GetDescription(block.Name), new CodePointRange(block.CodePointRange.FirstCodePoint, block.CodePointRange.LastCodePoint)); } return(blockViewModel); }
public void Constructor() { DateTimeOffset before = DateTimeOffset.UtcNow; var m = new BlockMetadata(); DateTimeOffset after = DateTimeOffset.UtcNow; Assert.Equal(BlockMetadata.CurrentProtocolVersion, m.ProtocolVersion); Assert.Equal(0, m.Index); Assert.InRange(m.Timestamp, before, after); AssertBytesEqual(default(Address), m.Miner); Assert.Equal(0, m.Difficulty); Assert.Equal(0, m.TotalDifficulty); AssertBytesEqual(null, m.PreviousHash); AssertBytesEqual(null, m.TxHash); }
public BlockDigest(Bencodex.Types.Dictionary dict) { var headerDict = dict.GetValue <Bencodex.Types.Dictionary>(HeaderKey); var tuple = BlockMarshaler.UnmarshalPreEvaluationBlockHeader(headerDict); _metadata = tuple.Metadata; _nonce = tuple.Nonce; _preEvaluationHash = tuple.PreEvaluationHash; StateRootHash = BlockMarshaler.UnmarshalBlockHeaderStateRootHash(headerDict); Signature = BlockMarshaler.UnmarshalBlockHeaderSignature(headerDict); Hash = BlockMarshaler.UnmarshalBlockHeaderHash(headerDict); TxIds = dict.ContainsKey((IKey)(Binary)TransactionIdsKey) ? dict.GetValue <Bencodex.Types.List>(TransactionIdsKey) .Select(txId => ((Binary)txId).ToImmutableArray()).ToImmutableArray() : ImmutableArray <ImmutableArray <byte> > .Empty; }
public static BlockMetadata ToMetadata(this IBlock block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } var blockMetadata = new BlockMetadata() { Id = block.Id, Data = block.GetData(), Elements = block.Elements.ToMetadata(), Parameters = block.Parameters.ToMetadata() }; return(blockMetadata); }
private static void FixBlock(BlockMetadata blockMetadata) { if (blockMetadata == null) { throw new ArgumentNullException(nameof(blockMetadata)); } if (blockMetadata.Next != null) { //Convert to a list blockMetadata.Elements = EnumerateElementsWhileFixingBlocks(blockMetadata.Next) .ToArray(); //Ditch the next pointer blockMetadata.Next = null; } }
public void TestMerkleRoot() { SHA256 hasher = SHA256.Create(); BlockMetadata meta = new BlockMetadata() { CurrentTransactions = new List <Transaction>(InitTransactions()), Instance = 1, TransactionCount = 2 }; var root = MerkleTree.GetMerkleRoot(meta, meta.TransactionCount); Assert.IsNotNull(root); }
public BlockInfo?Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { if (decoderContext.IsNextItemNull()) { decoderContext.ReadByte(); return(null); } int lastCheck = decoderContext.ReadSequenceLength() + decoderContext.Position; Keccak? blockHash = decoderContext.DecodeKeccak(); bool wasProcessed = decoderContext.DecodeBool(); UInt256 totalDifficulty = decoderContext.DecodeUInt256(); BlockMetadata metadata = BlockMetadata.None; // if we hadn't reached the end of the stream, assume we have metadata to decode if (decoderContext.Position != lastCheck) { metadata = (BlockMetadata)decoderContext.DecodeInt(); } if ((rlpBehaviors & RlpBehaviors.AllowExtraData) != RlpBehaviors.AllowExtraData) { decoderContext.Check(lastCheck); } if (blockHash is null) { return(null); } BlockInfo blockInfo = new(blockHash, totalDifficulty) { WasProcessed = wasProcessed, Metadata = metadata }; return(blockInfo); } }
private void Decompress(CancellationToken cancellationToken) { using var compressedFileStream = new FileStream(_compressedFilename, FileMode.Open, FileAccess.Read, FileShare.Read); using var decompressedFileStream = new FileStream(_decompressedFileName, FileMode.Create, FileAccess.Write, FileShare.Write); BlockMetadata block = null; while (_blockGenerator.TryGetNext(out block)) { if (cancellationToken.IsCancellationRequested) { break; } compressedFileStream.Seek(block.CompressedPosition, SeekOrigin.Begin); var decompressedData = Utils.DecompressBlock(compressedFileStream, block); decompressedFileStream.Seek(block.OriginalPosition, SeekOrigin.Begin); decompressedFileStream.Write(decompressedData, 0, decompressedData.Length); } }
public void Removing_beacon_metadata() { BlockMetadata metadata = BlockMetadata.BeaconBody | BlockMetadata.BeaconHeader; metadata = metadata & ~(BlockMetadata.BeaconBody | BlockMetadata.BeaconHeader); Assert.AreEqual(BlockMetadata.None, metadata); BlockMetadata metadata2 = BlockMetadata.BeaconBody | BlockMetadata.BeaconHeader | BlockMetadata.Finalized | BlockMetadata.Invalid; metadata2 = metadata2 & ~(BlockMetadata.BeaconBody | BlockMetadata.BeaconHeader); Assert.AreEqual(BlockMetadata.Finalized | BlockMetadata.Invalid, metadata2); BlockMetadata metadata3 = BlockMetadata.None; metadata3 &= ~(BlockMetadata.BeaconBody | BlockMetadata.BeaconHeader); Assert.AreEqual(BlockMetadata.None, metadata3); BlockMetadata metadata4 = BlockMetadata.BeaconHeader; metadata4 |= BlockMetadata.BeaconMainChain; Assert.AreEqual(BlockMetadata.BeaconHeader | BlockMetadata.BeaconMainChain, metadata4); }
public static HexString GetMerkleRoot(BlockMetadata data, int countTransactions) { var tempCount = countTransactions; for (int i = 0; i <= tempCount; i += 2) { level++; if (i + 1 < tempCount) { if (level == 1) { merkleList.Add(new HexString(ComputeHashData(data.CurrentTransactions[i].Hash, data.CurrentTransactions[i + 1].Hash))); level = 0; } else { merkleList.Add(new HexString(ComputeHashData(merkleList[i], merkleList[i + 1]))); } } } if (tempCount % 2 == 1) { merkleList.Insert(merkleList.Count, new HexString(ComputeHashData(data.CurrentTransactions[countTransactions - 1].Hash, data.CurrentTransactions[countTransactions - 1].Hash))); tempCount += 1; } if ((tempCount / 2) != 1) { GetMerkleRoot(data, tempCount / 2); } var root = merkleList[merkleList.Count - 1]; return(root); }
public BlockContentFixture() { TimeSpan kst = TimeSpan.FromHours(9); GenesisKey = new PrivateKey(new byte[] { 0x9b, 0xf4, 0x66, 0x4b, 0xa0, 0x9a, 0x89, 0xfa, 0xeb, 0x68, 0x4b, 0x94, 0xe6, 0x9f, 0xfd, 0xe0, 0x1d, 0x26, 0xae, 0x14, 0xb5, 0x56, 0x20, 0x4d, 0x3f, 0x6a, 0xb5, 0x8f, 0x61, 0xf7, 0x84, 0x18, }); GenesisMetadata = new BlockMetadata { Index = 0, Timestamp = new DateTimeOffset(2021, 9, 6, 13, 46, 39, 123, kst), PublicKey = GenesisKey.PublicKey, Difficulty = 0, PreviousHash = null, TxHash = null, }; Genesis = new BlockContent <Arithmetic>(GenesisMetadata); GenesisHash = BlockHash.FromString( "341e8f360597d5bc45ab96aabc5f1b0608063f30af7bd4153556c9536a07693a" ); Block1Key = new PrivateKey(new byte[] { 0xfc, 0xf3, 0x0b, 0x33, 0x3d, 0x04, 0xcc, 0xfe, 0xb5, 0x62, 0xf0, 0x00, 0xa3, 0x2d, 0xf4, 0x88, 0xe7, 0x15, 0x49, 0x49, 0xd3, 0x1d, 0xdc, 0xac, 0x3c, 0xf9, 0x27, 0x8a, 0xcb, 0x57, 0x86, 0xc7, }); BlockMetadata1 = new BlockMetadata { Index = 1, Timestamp = new DateTimeOffset(2021, 9, 6, 17, 1, 9, 45, kst), PublicKey = Block1Key.PublicKey, Difficulty = 123, PreviousHash = GenesisHash, TxHash = HashDigest <SHA256> .FromString( "654698d34b6d9a55b0c93e4ffb2639278324868c91965bc5f96cb3071d6903a0" ), }; var block1Tx0Key = PrivateKey.FromString( "2d5c20079bc4b2e6eab9ecbb405da8ba6590c436edfb07b7d4466563d7dac096" ); Tx0InBlock1 = new Transaction <Arithmetic>( nonce: 0L, signer: block1Tx0Key.ToAddress(), publicKey: block1Tx0Key.PublicKey, genesisHash: GenesisHash, updatedAddresses: ImmutableHashSet <Address> .Empty.Add(block1Tx0Key.ToAddress()), timestamp: new DateTimeOffset(2021, 9, 6, 17, 0, 1, 1, kst), actions: new[] { Arithmetic.Add(10), Arithmetic.Add(50), Arithmetic.Sub(25), }, signature: ByteUtil.ParseHex( "30440220422c85ea44845a56253654d95595ad06d6f09f862ca71b97e986ecbb453eac" + "ae0220606e76276e40fa8f0795b880f712531fd6bd9db253bd8ab9c86aa4ab7d791d37" ) ); Tx0InBlock1.Validate(block1Tx0Key); var block1Tx1Key = PrivateKey.FromString( "105341c78dfb0dd313b961081630444c2586a1f01fb0c625368ffdc9136cfa30" ); Tx1InBlock1 = new Transaction <Arithmetic>( nonce: 1L, signer: block1Tx1Key.ToAddress(), publicKey: block1Tx1Key.PublicKey, genesisHash: GenesisHash, updatedAddresses: ImmutableHashSet <Address> .Empty.Add(block1Tx1Key.ToAddress()), timestamp: new DateTimeOffset(2021, 9, 6, 17, 0, 1, 1, kst), actions: new[] { Arithmetic.Add(30) }, signature: ByteUtil.ParseHex( "3045022100abe3caabf2a46a297f2e4496f2c46d7e2f723e75fc42025d19f3ed7fce382" + "d4e02200ffd36f7bef759b6c7ab43bc0f8959a0c463f88fd0f1faeaa209a8661506c4f0" ) ); Tx1InBlock1.Validate(block1Tx1Key); Block1 = new BlockContent <Arithmetic>( BlockMetadata1, new[] { Tx0InBlock1, Tx1InBlock1, } ); BlockMetadataPv0 = new BlockMetadata { ProtocolVersion = 0, Index = 0, Timestamp = new DateTimeOffset(2021, 9, 6, 13, 46, 39, 123, kst), Miner = GenesisKey.ToAddress(), Difficulty = 0, PreviousHash = null, TxHash = null, }; BlockPv0 = new BlockContent <Arithmetic>(BlockMetadataPv0); BlockPv1 = new BlockContent <Arithmetic>(Block1) { ProtocolVersion = 1, PublicKey = null, }; BlockMetadataPv1 = new BlockMetadata(BlockPv1); }
public static void SetUpBeforeClass(TestContext context) { eventHub = new EventHub("test", "grpc://lh:99", null); // build a block with 3 transactions, set transaction 1,3 as valid, transaction 2 as invalid BlockData blockDataBuilder = new BlockData(); Payload payloadBuilder = new Payload(); ChannelHeader channelHeaderBuilder = new ChannelHeader(); channelHeaderBuilder.Type = (int)HeaderType.EndorserTransaction; Header headerBuilder = new Header(); Envelope envelopeBuilder = new Envelope(); channelHeaderBuilder.ChannelId = "TESTCHANNEL"; // transaction 1 channelHeaderBuilder.TxId = "TRANSACTION1"; headerBuilder.ChannelHeader = channelHeaderBuilder.ToByteString(); payloadBuilder.Header = new Header(headerBuilder); payloadBuilder.Data = ByteString.CopyFrom("test data".ToBytes()); envelopeBuilder.Payload = payloadBuilder.ToByteString(); blockDataBuilder.Data.Add(envelopeBuilder.ToByteString()); // transaction 2 channelHeaderBuilder.TxId = "TRANSACTION2"; headerBuilder.ChannelHeader = channelHeaderBuilder.ToByteString(); payloadBuilder.Header = new Header(headerBuilder); payloadBuilder.Data = ByteString.CopyFrom("test data".ToBytes()); envelopeBuilder.Payload = payloadBuilder.ToByteString(); blockDataBuilder.Data.Add(envelopeBuilder.ToByteString()); // transaction 3 channelHeaderBuilder.TxId = "TRANSACTION3"; headerBuilder.ChannelHeader = channelHeaderBuilder.ToByteString(); payloadBuilder.Header = new Header(headerBuilder); payloadBuilder.Data = ByteString.CopyFrom("test data".ToBytes()); envelopeBuilder.Payload = payloadBuilder.ToByteString(); blockDataBuilder.Data.Add(envelopeBuilder.ToByteString()); // blockData with 3 envelopes blockData = new BlockData(blockDataBuilder); // block header BlockHeader blockHeaderBuilder = new BlockHeader(); blockHeaderBuilder.Number = 1; blockHeaderBuilder.PreviousHash = ByteString.CopyFrom("previous_hash".ToBytes()); blockHeaderBuilder.DataHash = ByteString.CopyFrom("data_hash".ToBytes()); blockHeader = new BlockHeader(blockHeaderBuilder); // block metadata BlockMetadata blockMetadataBuilder = new BlockMetadata(); blockMetadataBuilder.Metadata.Add(ByteString.CopyFrom("signatures".ToBytes())); //BlockMetadataIndex.SIGNATURES_VALUE blockMetadataBuilder.Metadata.Add(ByteString.CopyFrom("last_config".ToBytes())); //BlockMetadataIndex.LAST_CONFIG_VALUE, // mark 2nd transaction in block as invalid byte[] txResultsMap = new byte[] { (byte)TxValidationCode.Valid, (byte)TxValidationCode.InvalidOtherReason, (byte)TxValidationCode.Valid }; blockMetadataBuilder.Metadata.Add(ByteString.CopyFrom(txResultsMap)); //BlockMetadataIndex.TRANSACTIONS_FILTER_VALUE blockMetadataBuilder.Metadata.Add(ByteString.CopyFrom("orderer".ToBytes())); //BlockMetadataIndex.ORDERER_VALUE blockMetadata = new BlockMetadata(blockMetadataBuilder); Block blockBuilder = new Block(); blockBuilder.Data = new BlockData(blockData); blockBuilder.Header = new BlockHeader(blockHeader); blockBuilder.Metadata = new BlockMetadata(blockMetadata); block = new Block(blockBuilder); goodEventBlock = new Event { Block = new Block(blockBuilder) }; // block with bad header headerBuilder.ChannelHeader = ByteString.CopyFrom("bad channel header".ToBytes()); payloadBuilder.Header = new Header(headerBuilder); payloadBuilder.Data = ByteString.CopyFrom("test data".ToBytes()); envelopeBuilder.Payload = payloadBuilder.ToByteString(); blockDataBuilder.Data.Clear(); blockDataBuilder.Data.Add(envelopeBuilder.ToByteString()); blockBuilder.Data = new BlockData(blockDataBuilder); badBlock = new Block(blockBuilder); badEventBlock = new Event { Block = new Block(badBlock) }; }
public async Task <Block <T> > MineBlock( PrivateKey miner, DateTimeOffset timestamp, bool append, long maxBlockBytes, int maxTransactions, int maxTransactionsPerSigner, IComparer <Transaction <T> > txPriority = null, CancellationToken cancellationToken = default(CancellationToken)) { using var cts = new CancellationTokenSource(); using CancellationTokenSource cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token); void WatchTip(object target, (Block <T> OldTip, Block <T> NewTip) tip) { try { cts.Cancel(); } catch (ObjectDisposedException) { // Ignore if mining was already finished. } } long index = Count; long difficulty = Policy.GetNextBlockDifficulty(this); BlockHash?prevHash = index > 0 ? Store.IndexBlockHash(Id, index - 1) : null; int sessionId = new System.Random().Next(); int processId = Process.GetCurrentProcess().Id; _logger.Debug( "{SessionId}/{ProcessId}: Starting to mine block #{Index} with " + "difficulty {Difficulty} and previous hash {PreviousHash}...", sessionId, processId, index, difficulty, prevHash); HashAlgorithmType hashAlgorithm = Policy.GetHashAlgorithm(index); var metadata = new BlockMetadata { Index = index, Difficulty = difficulty, TotalDifficulty = Tip.TotalDifficulty + difficulty, PublicKey = miner.PublicKey, PreviousHash = prevHash, Timestamp = timestamp, }; var transactionsToMine = GatherTransactionsToMine( metadata, maxBlockBytes: maxBlockBytes, maxTransactions: maxTransactions, maxTransactionsPerSigner: maxTransactionsPerSigner, txPriority: txPriority ); if (transactionsToMine.Count < Policy.GetMinTransactionsPerBlock(index)) { cts.Cancel(); throw new OperationCanceledException( $"Mining canceled due to insufficient number of gathered transactions " + $"to mine for the requirement of {Policy.GetMinTransactionsPerBlock(index)} " + $"given by the policy: {transactionsToMine.Count}"); } _logger.Verbose( "{SessionId}/{ProcessId}: Mined block #{Index} will include " + "{TxCount} transactions.", sessionId, processId, index, transactionsToMine.Count); var blockContent = new BlockContent <T>(metadata) { Transactions = transactionsToMine }; PreEvaluationBlock <T> preEval; TipChanged += WatchTip; try { preEval = await Task.Run( () => blockContent.Mine(hashAlgorithm, cancellationTokenSource.Token), cancellationTokenSource.Token ); } catch (OperationCanceledException) { if (cts.IsCancellationRequested) { throw new OperationCanceledException( "Mining canceled due to change of tip index."); } throw new OperationCanceledException(cancellationToken); } finally { TipChanged -= WatchTip; } (Block <T> block, IReadOnlyList <ActionEvaluation> actionEvaluations) = preEval.EvaluateActions(miner, this); IEnumerable <TxExecution> txExecutions = MakeTxExecutions(block, actionEvaluations); UpdateTxExecutions(txExecutions); _logger.Debug( "{SessionId}/{ProcessId}: Mined block #{Index} {Hash} " + "with difficulty {Difficulty} and previous hash {PreviousHash}.", sessionId, processId, block.Index, block.Hash, block.Difficulty, block.PreviousHash); if (append) { Append( block, evaluateActions: true, renderBlocks: true, renderActions: true, actionEvaluations: actionEvaluations); } return(block); }
public MethodMetadata Body(Action<BlockMetadata> fn) { this.block = new BlockMetadata(this.returnType, this.parameters); fn(this.block); return this; }
internal static void BlockAddedToWallet(int height, BlockMetadata blockMetadata) { Logger.LogInformation( $"Block {height} added {blockMetadata.Transactions.Count} {blockMetadata.Transactions.Sum(x => x.ValueAdded) / C.SatoshisPerCoin} {C.Network.CoinTicker} to the wallet."); }
public Task(BlockMetadata metadata, Func <Block, Block> applyInstructions, FileReaderWriter readerWriter) { this.metadata = metadata; this.applyInstructions = applyInstructions; this.readerWriter = readerWriter; }