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 var stream = new MemoryStream(blockBytes);
92 var reader = new BinaryReader(stream);
94 // Fill the block header fields
95 header = new CBlockHeader(ref reader);
97 // Parse transactions list
98 vtx = CTransaction.ReadTransactionsList(ref reader);
100 // Read block signature
101 signature = reader.ReadBytes((int)VarInt.ReadVarInt(ref reader));
107 throw new BlockException("Deserialization failed", e);
113 // Initialize empty array of transactions. Please note that such
114 // configuration is not valid real block since it has to provide
115 // at least one transaction.
116 vtx = new CTransaction[0];
119 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
121 var uniqueTX = new List<Hash256>(); // tx hashes
122 uint nSigOps = 0; // total sigops
124 // Basic sanity checkings
125 if (vtx.Length == 0 || Size > 1000000)
130 bool fProofOfStake = IsProofOfStake;
132 // First transaction must be coinbase, the rest must not be
133 if (!vtx[0].IsCoinBase)
138 if (!vtx[0].CheckTransaction())
143 uniqueTX.Add(vtx[0].Hash);
144 nSigOps += vtx[0].LegacySigOpCount;
148 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
149 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
151 // nNonce must be zero for proof-of-stake blocks
152 if (header.nNonce != 0)
157 // Coinbase output should be empty if proof-of-stake block
158 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
163 // Check coinstake timestamp
164 if (header.nTime != vtx[1].nTime)
169 // Check proof-of-stake block signature
170 if (fCheckSig && !SignatureOK)
175 if (!vtx[1].CheckTransaction())
180 uniqueTX.Add(vtx[1].Hash);
181 nSigOps += vtx[1].LegacySigOpCount;
185 // Check proof of work matches claimed amount
186 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
192 if (header.nTime > NetUtils.FutureDrift(NetUtils.GetAdjustedTime()))
197 // Check coinbase timestamp
198 if (header.nTime < NetUtils.PastDrift(vtx[0].nTime))
204 // Iterate all transactions starting from second for proof-of-stake block
205 // or first for proof-of-work block
206 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
210 // Reject coinbase transactions at non-zero index
216 // Reject coinstake transactions at index != 1
222 // Check transaction timestamp
223 if (header.nTime < tx.nTime)
228 // Check transaction consistency
229 if (!tx.CheckTransaction())
234 // Add transaction hash into list of unique transaction IDs
235 uniqueTX.Add(tx.Hash);
237 // Calculate sigops count
238 nSigOps += tx.LegacySigOpCount;
241 // Check for duplicate txids.
242 if (uniqueTX.Count != vtx.Length)
247 // Reject block if validation would consume too much resources.
254 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
262 private bool CheckProofOfWork(ScryptHash256 hash, uint nBits)
270 /// Is this a Proof-of-Stake block?
272 public bool IsProofOfStake
276 return (vtx.Length > 1 && vtx[1].IsCoinStake);
281 /// Was this signed correctly?
283 public bool SignatureOK
289 if (signature.Length == 0)
291 return false; // No signature
294 txnouttype whichType;
295 IList<byte[]> solutions;
297 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
299 return false; // No solutions found
302 if (whichType == txnouttype.TX_PUBKEY)
308 pubkey = new CPubKey(solutions[0]);
312 return false; // Error while loading public key
315 return pubkey.VerifySignature(header.Hash, signature);
320 // Proof-of-Work blocks have no signature
330 /// Get instance as sequence of bytes
332 /// <returns>Byte sequence</returns>
333 public static implicit operator byte[] (CBlock b)
335 var stream = new MemoryStream();
336 var writer = new BinaryWriter(stream);
338 writer.Write(b.header);
339 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
341 foreach (var tx in b.vtx)
346 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
347 writer.Write(b.signature);
349 var resultBytes = stream.ToArray();
363 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
365 foreach (var tx in vtx)
370 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
377 /// Get transaction offset inside block.
379 /// <param name="nTx">Transaction index.</param>
380 /// <returns>Offset in bytes from the beginning of block header.</returns>
381 public int GetTxOffset(int nTx)
383 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
385 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
387 for (int i = 0; i < nTx; i++)
389 nOffset += vtx[i].Size;
398 public Hash256 hashMerkleRoot
402 var merkleTree = new List<byte>();
404 foreach (var tx in vtx)
406 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
410 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
412 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
414 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
416 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
417 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
419 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
421 levelOffset += nLevelSize;
424 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
428 public override string ToString()
430 var sb = new StringBuilder();
432 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
434 foreach(var tx in vtx)
436 sb.AppendFormat("{0}", tx.ToString());
441 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
446 return sb.ToString();