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;
27 public class BlockException : Exception
29 public BlockException()
33 public BlockException(string message)
38 public BlockException(string message, Exception inner)
39 : base(message, inner)
45 /// Represents the block. Block consists of header, transaction array and header signature.
52 public CBlockHeader header;
55 /// Transactions array.
57 public CTransaction[] vtx;
60 /// Block header signature.
62 public byte[] signature = new byte[0];
67 /// <param name="b">CBlock instance.</param>
68 public CBlock(CBlock b)
70 header = new CBlockHeader(b.header);
71 vtx = new CTransaction[b.vtx.Length];
73 for (int i = 0; i < b.vtx.Length; i++)
75 vtx[i] = new CTransaction(b.vtx[i]);
78 signature = new byte[b.signature.Length];
79 b.signature.CopyTo(signature, 0);
83 /// Parse byte sequence and initialize new block instance
85 /// <param name="blockBytes">Bytes sequence.</param>
86 public CBlock (byte[] blockBytes)
90 ByteQueue wBytes = new ByteQueue(ref blockBytes);
92 // Fill the block header fields
93 header = new CBlockHeader(wBytes.Get(80));
95 // Parse transactions list
96 vtx = CTransaction.ReadTransactionsList(ref wBytes);
98 // Read block signature
99 signature = wBytes.Get((int)wBytes.GetVarInt());
103 throw new BlockException("Deserialization failed", e);
109 // Initialize empty array of transactions. Please note that such
110 // configuration is not valid real block since it has to provide
111 // at least one transaction.
112 vtx = new CTransaction[0];
115 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
117 var uniqueTX = new List<Hash256>(); // tx hashes
118 uint nSigOps = 0; // total sigops
120 // Basic sanity checkings
121 if (vtx.Length == 0 || Size > 1000000)
126 bool fProofOfStake = IsProofOfStake;
128 // First transaction must be coinbase, the rest must not be
129 if (!vtx[0].IsCoinBase)
134 if (!vtx[0].CheckTransaction())
139 uniqueTX.Add(vtx[0].Hash);
140 nSigOps += vtx[0].LegacySigOpCount;
144 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
145 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
147 // nNonce must be zero for proof-of-stake blocks
148 if (header.nNonce != 0)
153 // Coinbase output should be empty if proof-of-stake block
154 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
159 // Check coinstake timestamp
160 if (header.nTime != vtx[1].nTime)
165 // Check proof-of-stake block signature
166 if (fCheckSig && !SignatureOK)
171 if (!vtx[1].CheckTransaction())
176 uniqueTX.Add(vtx[1].Hash);
177 nSigOps += vtx[1].LegacySigOpCount;
181 // Check proof of work matches claimed amount
182 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
188 if (header.nTime > NetUtils.FutureDrift(NetUtils.GetAdjustedTime()))
193 // Check coinbase timestamp
194 if (header.nTime < NetUtils.PastDrift(vtx[0].nTime))
200 // Iterate all transactions starting from second for proof-of-stake block
201 // or first for proof-of-work block
202 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
206 // Reject coinbase transactions at non-zero index
212 // Reject coinstake transactions at index != 1
218 // Check transaction timestamp
219 if (header.nTime < tx.nTime)
224 // Check transaction consistency
225 if (!tx.CheckTransaction())
230 // Add transaction hash into list of unique transaction IDs
231 uniqueTX.Add(tx.Hash);
233 // Calculate sigops count
234 nSigOps += tx.LegacySigOpCount;
237 // Check for duplicate txids.
238 if (uniqueTX.Count != vtx.Length)
243 // Reject block if validation would consume too much resources.
250 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
258 private bool CheckProofOfWork(ScryptHash256 hash, uint nBits)
266 /// Is this a Proof-of-Stake block?
268 public bool IsProofOfStake
272 return (vtx.Length > 1 && vtx[1].IsCoinStake);
277 /// Was this signed correctly?
279 public bool SignatureOK
285 if (signature.Length == 0)
287 return false; // No signature
290 txnouttype whichType;
291 IList<byte[]> solutions;
293 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
295 return false; // No solutions found
298 if (whichType == txnouttype.TX_PUBKEY)
304 pubkey = new CPubKey(solutions[0]);
308 return false; // Error while loading public key
311 return pubkey.VerifySignature(header.Hash, signature);
316 // Proof-of-Work blocks have no signature
326 /// Get instance as sequence of bytes
328 /// <returns>Byte sequence</returns>
329 public static implicit operator byte[] (CBlock b)
331 var r = new List<byte>();
333 r.AddRange((byte[])b.header);
334 r.AddRange(VarInt.EncodeVarInt(b.vtx.LongLength)); // transactions count
336 foreach (var tx in b.vtx)
338 r.AddRange((byte[])tx);
341 r.AddRange(VarInt.EncodeVarInt(b.signature.LongLength));
342 r.AddRange(b.signature);
354 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
356 foreach (var tx in vtx)
361 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
368 /// Get transaction offset inside block.
370 /// <param name="nTx">Transaction index.</param>
371 /// <returns>Offset in bytes from the beginning of block header.</returns>
372 public int GetTxOffset(int nTx)
374 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
376 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
378 for (int i = 0; i < nTx; i++)
380 nOffset += vtx[i].Size;
389 public Hash256 hashMerkleRoot
393 var merkleTree = new List<byte>();
395 foreach (var tx in vtx)
397 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
401 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
403 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
405 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
407 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
408 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
410 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
412 levelOffset += nLevelSize;
415 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
419 public override string ToString()
421 var sb = new StringBuilder();
423 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
425 foreach(var tx in vtx)
427 sb.AppendFormat("{0}", tx.ToString());
432 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
437 return sb.ToString();