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();
96 header.nVersion = reader.ReadUInt32();
97 header.prevHash = new ScryptHash256(reader.ReadBytes(32));
98 header.merkleRoot = new Hash256(reader.ReadBytes(32));
99 header.nTime = reader.ReadUInt32();
100 header.nBits = reader.ReadUInt32();
101 header.nNonce = reader.ReadUInt32();
103 // Parse transactions list
104 vtx = CTransaction.ReadTransactionsList(ref reader);
106 // Read block signature
107 signature = reader.ReadBytes((int)VarInt.ReadVarInt(ref reader));
113 throw new BlockException("Deserialization failed", e);
119 // Initialize empty array of transactions. Please note that such
120 // configuration is not valid real block since it has to provide
121 // at least one transaction.
122 vtx = new CTransaction[0];
125 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
127 var uniqueTX = new List<Hash256>(); // tx hashes
128 uint nSigOps = 0; // total sigops
130 // Basic sanity checkings
131 if (vtx.Length == 0 || Size > 1000000)
136 bool fProofOfStake = IsProofOfStake;
138 // First transaction must be coinbase, the rest must not be
139 if (!vtx[0].IsCoinBase)
144 if (!vtx[0].CheckTransaction())
149 uniqueTX.Add(vtx[0].Hash);
150 nSigOps += vtx[0].LegacySigOpCount;
154 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
155 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
157 // nNonce must be zero for proof-of-stake blocks
158 if (header.nNonce != 0)
163 // Coinbase output should be empty if proof-of-stake block
164 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
169 // Check coinstake timestamp
170 if (header.nTime != vtx[1].nTime)
175 // Check proof-of-stake block signature
176 if (fCheckSig && !SignatureOK)
181 if (!vtx[1].CheckTransaction())
186 uniqueTX.Add(vtx[1].Hash);
187 nSigOps += vtx[1].LegacySigOpCount;
191 // Check proof of work matches claimed amount
192 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
198 if (header.nTime > NetUtils.FutureDrift(NetUtils.GetAdjustedTime()))
203 // Check coinbase timestamp
204 if (header.nTime < NetUtils.PastDrift(vtx[0].nTime))
210 // Iterate all transactions starting from second for proof-of-stake block
211 // or first for proof-of-work block
212 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
216 // Reject coinbase transactions at non-zero index
222 // Reject coinstake transactions at index != 1
228 // Check transaction timestamp
229 if (header.nTime < tx.nTime)
234 // Check transaction consistency
235 if (!tx.CheckTransaction())
240 // Add transaction hash into list of unique transaction IDs
241 uniqueTX.Add(tx.Hash);
243 // Calculate sigops count
244 nSigOps += tx.LegacySigOpCount;
247 // Check for duplicate txids.
248 if (uniqueTX.Count != vtx.Length)
253 // Reject block if validation would consume too much resources.
260 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
268 private bool CheckProofOfWork(ScryptHash256 hash, uint nBits)
276 /// Is this a Proof-of-Stake block?
278 public bool IsProofOfStake
282 return (vtx.Length > 1 && vtx[1].IsCoinStake);
287 /// Was this signed correctly?
289 public bool SignatureOK
295 if (signature.Length == 0)
297 return false; // No signature
300 txnouttype whichType;
301 IList<byte[]> solutions;
303 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
305 return false; // No solutions found
308 if (whichType == txnouttype.TX_PUBKEY)
314 pubkey = new CPubKey(solutions[0]);
318 return false; // Error while loading public key
321 return pubkey.VerifySignature(header.Hash, signature);
326 // Proof-of-Work blocks have no signature
336 /// Get instance as sequence of bytes
338 /// <returns>Byte sequence</returns>
339 public static implicit operator byte[] (CBlock b)
341 var stream = new MemoryStream();
342 var writer = new BinaryWriter(stream);
344 writer.Write(b.header);
345 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
347 foreach (var tx in b.vtx)
352 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
353 writer.Write(b.signature);
355 var resultBytes = stream.ToArray();
369 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
371 foreach (var tx in vtx)
376 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
383 /// Get transaction offset inside block.
385 /// <param name="nTx">Transaction index.</param>
386 /// <returns>Offset in bytes from the beginning of block header.</returns>
387 public int GetTxOffset(int nTx)
389 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
391 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
393 for (int i = 0; i < nTx; i++)
395 nOffset += vtx[i].Size;
404 public Hash256 hashMerkleRoot
408 var merkleTree = new List<byte>();
410 foreach (var tx in vtx)
412 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
416 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
418 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
420 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
422 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
423 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
425 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
427 levelOffset += nLevelSize;
430 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
434 public override string ToString()
436 var sb = new StringBuilder();
438 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
440 foreach(var tx in vtx)
442 sb.AppendFormat("{0}", tx.ToString());
447 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
452 return sb.ToString();