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.
53 public CBlockHeader header;
56 /// Transactions array.
58 public CTransaction[] vtx;
61 /// Block header signature.
63 public byte[] signature = new byte[0];
68 /// <param name="b">CBlock instance.</param>
69 public CBlock(CBlock b)
71 header = new CBlockHeader(b.header);
72 vtx = new CTransaction[b.vtx.Length];
74 for (int i = 0; i < b.vtx.Length; i++)
76 vtx[i] = new CTransaction(b.vtx[i]);
79 signature = new byte[b.signature.Length];
80 b.signature.CopyTo(signature, 0);
84 /// Parse byte sequence and initialize new block instance
86 /// <param name="blockBytes">Bytes sequence.</param>
87 public CBlock (byte[] blockBytes)
91 ByteQueue wBytes = new ByteQueue(ref blockBytes);
93 // Fill the block header fields
94 header = new CBlockHeader(wBytes.Get(80));
96 // Parse transactions list
97 vtx = CTransaction.ReadTransactionsList(ref wBytes);
99 // Read block signature
100 signature = wBytes.Get((int)wBytes.GetVarInt());
104 throw new BlockException("Deserialization failed", e);
110 // Initialize empty array of transactions. Please note that such
111 // configuration is not valid real block since it has to provide
112 // at least one transaction.
113 vtx = new CTransaction[0];
116 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
118 var uniqueTX = new List<Hash256>(); // tx hashes
119 uint nSigOps = 0; // total sigops
121 // Basic sanity checkings
122 if (vtx.Length == 0 || Size > 1000000)
127 bool fProofOfStake = IsProofOfStake;
129 // First transaction must be coinbase, the rest must not be
130 if (!vtx[0].IsCoinBase)
135 if (!vtx[0].CheckTransaction())
140 uniqueTX.Add(vtx[0].Hash);
141 nSigOps += vtx[0].LegacySigOpCount;
145 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
146 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
148 // nNonce must be zero for proof-of-stake blocks
149 if (header.nNonce != 0)
154 // Coinbase output should be empty if proof-of-stake block
155 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
160 // Check coinstake timestamp
161 if (header.nTime != vtx[1].nTime)
166 // Check proof-of-stake block signature
167 if (fCheckSig && !SignatureOK)
172 if (!vtx[1].CheckTransaction())
177 uniqueTX.Add(vtx[1].Hash);
178 nSigOps += vtx[1].LegacySigOpCount;
182 // Check proof of work matches claimed amount
183 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
189 if (header.nTime > NetUtils.FutureDrift(NetUtils.GetAdjustedTime()))
194 // Check coinbase timestamp
195 if (header.nTime < NetUtils.PastDrift(vtx[0].nTime))
201 // Iterate all transactions starting from second for proof-of-stake block
202 // or first for proof-of-work block
203 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
207 // Reject coinbase transactions at non-zero index
213 // Reject coinstake transactions at index != 1
219 // Check transaction timestamp
220 if (header.nTime < tx.nTime)
225 // Check transaction consistency
226 if (!tx.CheckTransaction())
231 // Add transaction hash into list of unique transaction IDs
232 uniqueTX.Add(tx.Hash);
234 // Calculate sigops count
235 nSigOps += tx.LegacySigOpCount;
238 // Check for duplicate txids.
239 if (uniqueTX.Count != vtx.Length)
244 // Reject block if validation would consume too much resources.
251 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
259 private bool CheckProofOfWork(ScryptHash256 hash, uint nBits)
267 /// Is this a Proof-of-Stake block?
269 public bool IsProofOfStake
273 return (vtx.Length > 1 && vtx[1].IsCoinStake);
278 /// Was this signed correctly?
280 public bool SignatureOK
286 if (signature.Length == 0)
288 return false; // No signature
291 txnouttype whichType;
292 IList<byte[]> solutions;
294 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
296 return false; // No solutions found
299 if (whichType == txnouttype.TX_PUBKEY)
305 pubkey = new CPubKey(solutions[0]);
309 return false; // Error while loading public key
312 return pubkey.VerifySignature(header.Hash, signature);
317 // Proof-of-Work blocks have no signature
327 /// Get instance as sequence of bytes
329 /// <returns>Byte sequence</returns>
330 public static implicit operator byte[] (CBlock b)
332 var stream = new MemoryStream();
333 var writer = new BinaryWriter(stream);
335 writer.Write(b.header);
336 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
338 foreach (var tx in b.vtx)
343 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
344 writer.Write(b.signature);
346 var resultBytes = stream.ToArray();
360 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
362 foreach (var tx in vtx)
367 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
374 /// Get transaction offset inside block.
376 /// <param name="nTx">Transaction index.</param>
377 /// <returns>Offset in bytes from the beginning of block header.</returns>
378 public int GetTxOffset(int nTx)
380 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
382 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
384 for (int i = 0; i < nTx; i++)
386 nOffset += vtx[i].Size;
395 public Hash256 hashMerkleRoot
399 var merkleTree = new List<byte>();
401 foreach (var tx in vtx)
403 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
407 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
409 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
411 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
413 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
414 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
416 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
418 levelOffset += nLevelSize;
421 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
425 public override string ToString()
427 var sb = new StringBuilder();
429 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
431 foreach(var tx in vtx)
433 sb.AppendFormat("{0}", tx.ToString());
438 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
443 return sb.ToString();