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;
56 /// Sanity threshold for amount of sigops.
58 public const uint nMaxSigOps = 20000;
63 public CBlockHeader header;
66 /// Transactions array.
68 public CTransaction[] vtx;
71 /// Block header signature.
73 public byte[] signature = new byte[0];
78 /// <param name="b">CBlock instance.</param>
79 public CBlock(CBlock b)
81 header = new CBlockHeader(b.header);
82 vtx = new CTransaction[b.vtx.Length];
84 for (int i = 0; i < b.vtx.Length; i++)
86 vtx[i] = new CTransaction(b.vtx[i]);
89 signature = new byte[b.signature.Length];
90 b.signature.CopyTo(signature, 0);
94 /// Parse byte sequence and initialize new block instance
96 /// <param name="blockBytes">Bytes sequence.</param>
97 public CBlock (byte[] blockBytes)
101 var stream = new MemoryStream(blockBytes);
102 var reader = new BinaryReader(stream);
104 // Fill the block header fields
105 header = new CBlockHeader(ref reader);
107 // Parse transactions list
108 vtx = CTransaction.ReadTransactionsList(ref reader);
110 // Read block signature
111 signature = reader.ReadBytes((int)VarInt.ReadVarInt(ref reader));
117 throw new BlockException("Deserialization failed", e);
123 // Initialize empty array of transactions. Please note that such
124 // configuration is not valid real block since it has to provide
125 // at least one transaction.
126 vtx = new CTransaction[0];
129 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
131 var uniqueTX = new List<Hash256>(); // tx hashes
132 uint nSigOps = 0; // total sigops
134 // Basic sanity checkings
135 if (vtx.Length == 0 || Size > nMaxBlockSize)
140 bool fProofOfStake = IsProofOfStake;
142 // First transaction must be coinbase, the rest must not be
143 if (!vtx[0].IsCoinBase)
148 if (!vtx[0].CheckTransaction())
153 uniqueTX.Add(vtx[0].Hash);
154 nSigOps += vtx[0].LegacySigOpCount;
158 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
159 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
161 // nNonce must be zero for proof-of-stake blocks
162 if (header.nNonce != 0)
167 // Coinbase output should be empty if proof-of-stake block
168 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
173 // Check coinstake timestamp
174 if (header.nTime != vtx[1].nTime)
179 // Check proof-of-stake block signature
180 if (fCheckSig && !SignatureOK)
185 if (!vtx[1].CheckTransaction())
190 uniqueTX.Add(vtx[1].Hash);
191 nSigOps += vtx[1].LegacySigOpCount;
195 // Check proof of work matches claimed amount
196 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
202 if (header.nTime > NetUtils.FutureDrift(NetUtils.GetAdjustedTime()))
207 // Check coinbase timestamp
208 if (header.nTime < NetUtils.PastDrift(vtx[0].nTime))
214 // Iterate all transactions starting from second for proof-of-stake block
215 // or first for proof-of-work block
216 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
220 // Reject coinbase transactions at non-zero index
226 // Reject coinstake transactions at index != 1
232 // Check transaction timestamp
233 if (header.nTime < tx.nTime)
238 // Check transaction consistency
239 if (!tx.CheckTransaction())
244 // Add transaction hash into list of unique transaction IDs
245 uniqueTX.Add(tx.Hash);
247 // Calculate sigops count
248 nSigOps += tx.LegacySigOpCount;
251 // Check for duplicate txids.
252 if (uniqueTX.Count != vtx.Length)
257 // Reject block if validation would consume too much resources.
258 if (nSigOps > nMaxSigOps)
264 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
272 private bool CheckProofOfWork(ScryptHash256 hash, uint nBits)
280 /// Is this a Proof-of-Stake block?
282 public bool IsProofOfStake
286 return (vtx.Length > 1 && vtx[1].IsCoinStake);
291 /// Was this signed correctly?
293 public bool SignatureOK
299 if (signature.Length == 0)
301 return false; // No signature
304 txnouttype whichType;
305 IList<byte[]> solutions;
307 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
309 return false; // No solutions found
312 if (whichType == txnouttype.TX_PUBKEY)
318 pubkey = new CPubKey(solutions[0]);
322 return false; // Error while loading public key
325 return pubkey.VerifySignature(header.Hash, signature);
330 // Proof-of-Work blocks have no signature
340 /// Get instance as sequence of bytes
342 /// <returns>Byte sequence</returns>
343 public static implicit operator byte[] (CBlock b)
345 var stream = new MemoryStream();
346 var writer = new BinaryWriter(stream);
348 writer.Write(b.header);
349 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
351 foreach (var tx in b.vtx)
356 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
357 writer.Write(b.signature);
359 var resultBytes = stream.ToArray();
373 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
375 foreach (var tx in vtx)
380 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
387 /// Get transaction offset inside block.
389 /// <param name="nTx">Transaction index.</param>
390 /// <returns>Offset in bytes from the beginning of block header.</returns>
391 public int GetTxOffset(int nTx)
393 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
395 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
397 for (int i = 0; i < nTx; i++)
399 nOffset += vtx[i].Size;
408 public Hash256 hashMerkleRoot
412 var merkleTree = new List<byte>();
414 foreach (var tx in vtx)
416 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
420 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
422 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
424 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
426 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
427 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
429 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
431 levelOffset += nLevelSize;
434 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
438 public override string ToString()
440 var sb = new StringBuilder();
442 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
444 foreach(var tx in vtx)
446 sb.AppendFormat("{0}", tx.ToString());
451 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
456 return sb.ToString();