2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 using System.Collections.Generic;
22 using System.Diagnostics.Contracts;
28 public class BlockException : Exception
30 public BlockException()
34 public BlockException(string message)
39 public BlockException(string message, Exception inner)
40 : base(message, inner)
46 /// Represents the block. Block consists of header, transaction array and header signature.
51 /// Maximum block size is 1Mb.
53 public const uint nMaxBlockSize = 1000000;
58 public CBlockHeader header;
61 /// Transactions array.
63 public CTransaction[] vtx;
66 /// Block header signature.
68 public byte[] signature = new byte[0];
73 /// <param name="b">CBlock instance.</param>
74 public CBlock(CBlock b)
76 header = new CBlockHeader(b.header);
77 vtx = new CTransaction[b.vtx.Length];
79 for (int i = 0; i < b.vtx.Length; i++)
81 vtx[i] = new CTransaction(b.vtx[i]);
84 signature = new byte[b.signature.Length];
85 b.signature.CopyTo(signature, 0);
89 /// Parse byte sequence and initialize new block instance
91 /// <param name="blockBytes">Bytes sequence.</param>
92 public CBlock (byte[] blockBytes)
96 var stream = new MemoryStream(blockBytes);
97 var reader = new BinaryReader(stream);
99 // Fill the block header fields
100 header = new CBlockHeader(ref reader);
102 // Parse transactions list
103 vtx = CTransaction.ReadTransactionsList(ref reader);
105 // Read block signature
106 signature = reader.ReadBytes((int)VarInt.ReadVarInt(ref reader));
112 throw new BlockException("Deserialization failed", e);
118 // Initialize empty array of transactions. Please note that such
119 // configuration is not valid real block since it has to provide
120 // at least one transaction.
121 vtx = new CTransaction[0];
124 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
126 var uniqueTX = new List<Hash256>(); // tx hashes
127 uint nSigOps = 0; // total sigops
129 // Basic sanity checkings
130 if (vtx.Length == 0 || Size > nMaxBlockSize)
135 bool fProofOfStake = IsProofOfStake;
137 // First transaction must be coinbase, the rest must not be
138 if (!vtx[0].IsCoinBase)
143 if (!vtx[0].CheckTransaction())
148 uniqueTX.Add(vtx[0].Hash);
149 nSigOps += vtx[0].LegacySigOpCount;
153 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
154 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
156 // nNonce must be zero for proof-of-stake blocks
157 if (header.nNonce != 0)
162 // Coinbase output should be empty if proof-of-stake block
163 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
168 // Check coinstake timestamp
169 if (header.nTime != vtx[1].nTime)
174 // Check proof-of-stake block signature
175 if (fCheckSig && !SignatureOK)
180 if (!vtx[1].CheckTransaction())
185 uniqueTX.Add(vtx[1].Hash);
186 nSigOps += vtx[1].LegacySigOpCount;
190 // Check proof of work matches claimed amount
191 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
197 if (header.nTime > NetUtils.FutureDrift(NetUtils.GetAdjustedTime()))
202 // Check coinbase timestamp
203 if (header.nTime < NetUtils.PastDrift(vtx[0].nTime))
209 // Iterate all transactions starting from second for proof-of-stake block
210 // or first for proof-of-work block
211 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
215 // Reject coinbase transactions at non-zero index
221 // Reject coinstake transactions at index != 1
227 // Check transaction timestamp
228 if (header.nTime < tx.nTime)
233 // Check transaction consistency
234 if (!tx.CheckTransaction())
239 // Add transaction hash into list of unique transaction IDs
240 uniqueTX.Add(tx.Hash);
242 // Calculate sigops count
243 nSigOps += tx.LegacySigOpCount;
246 // Check for duplicate txids.
247 if (uniqueTX.Count != vtx.Length)
252 // Reject block if validation would consume too much resources.
259 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
267 private bool CheckProofOfWork(ScryptHash256 hash, uint nBits)
275 /// Is this a Proof-of-Stake block?
277 public bool IsProofOfStake
281 return (vtx.Length > 1 && vtx[1].IsCoinStake);
286 /// Was this signed correctly?
288 public bool SignatureOK
294 if (signature.Length == 0)
296 return false; // No signature
299 txnouttype whichType;
300 IList<byte[]> solutions;
302 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
304 return false; // No solutions found
307 if (whichType == txnouttype.TX_PUBKEY)
313 pubkey = new CPubKey(solutions[0]);
317 return false; // Error while loading public key
320 return pubkey.VerifySignature(header.Hash, signature);
325 // Proof-of-Work blocks have no signature
335 /// Get instance as sequence of bytes
337 /// <returns>Byte sequence</returns>
338 public static implicit operator byte[] (CBlock b)
340 var stream = new MemoryStream();
341 var writer = new BinaryWriter(stream);
343 writer.Write(b.header);
344 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
346 foreach (var tx in b.vtx)
351 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
352 writer.Write(b.signature);
354 var resultBytes = stream.ToArray();
368 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
370 foreach (var tx in vtx)
375 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
382 /// Get transaction offset inside block.
384 /// <param name="nTx">Transaction index.</param>
385 /// <returns>Offset in bytes from the beginning of block header.</returns>
386 public int GetTxOffset(int nTx)
388 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
390 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
392 for (int i = 0; i < nTx; i++)
394 nOffset += vtx[i].Size;
403 public Hash256 hashMerkleRoot
407 var merkleTree = new List<byte>();
409 foreach (var tx in vtx)
411 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
415 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
417 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
419 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
421 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
422 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
424 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
426 levelOffset += nLevelSize;
429 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
433 public override string ToString()
435 var sb = new StringBuilder();
437 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
439 foreach(var tx in vtx)
441 sb.AppendFormat("{0}", tx.ToString());
446 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
451 return sb.ToString();