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;
24 using System.Numerics;
29 public class BlockException : Exception
31 public BlockException()
35 public BlockException(string message)
40 public BlockException(string message, Exception inner)
41 : base(message, inner)
47 /// Represents the block. Block consists of header, transaction array and header signature.
52 /// Maximum block size is 1Mb.
54 public const uint nMaxBlockSize = 1000000;
57 /// Sanity threshold for amount of sigops.
59 public const uint nMaxSigOps = 20000;
64 public CBlockHeader header;
67 /// Transactions array.
69 public CTransaction[] vtx;
72 /// Block header signature.
74 public byte[] signature = new byte[0];
79 /// <param name="b">CBlock instance.</param>
80 public CBlock(CBlock b)
82 header = new CBlockHeader(b.header);
83 vtx = new CTransaction[b.vtx.Length];
85 for (int i = 0; i < b.vtx.Length; i++)
87 vtx[i] = new CTransaction(b.vtx[i]);
90 signature = new byte[b.signature.Length];
91 b.signature.CopyTo(signature, 0);
95 /// Parse byte sequence and initialize new block instance
97 /// <param name="blockBytes">Bytes sequence.</param>
98 public CBlock (byte[] blockBytes)
102 var stream = new MemoryStream(blockBytes);
103 var reader = new BinaryReader(stream);
105 // Fill the block header fields
106 header = new CBlockHeader(ref reader);
108 // Parse transactions list
109 vtx = CTransaction.ReadTransactionsList(ref reader);
111 // Read block signature
112 signature = reader.ReadBytes((int)VarInt.ReadVarInt(ref reader));
118 throw new BlockException("Deserialization failed", e);
124 // Initialize empty array of transactions. Please note that such
125 // configuration is not valid real block since it has to provide
126 // at least one transaction.
127 vtx = new CTransaction[0];
130 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
132 var uniqueTX = new List<uint256>(); // tx hashes
133 uint nSigOps = 0; // total sigops
135 // Basic sanity checkings
136 if (vtx.Length == 0 || Size > nMaxBlockSize)
141 bool fProofOfStake = IsProofOfStake;
143 // First transaction must be coinbase, the rest must not be
144 if (!vtx[0].IsCoinBase)
149 if (!vtx[0].CheckTransaction())
154 uniqueTX.Add(vtx[0].Hash);
155 nSigOps += vtx[0].LegacySigOpCount;
159 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
160 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
162 // nNonce must be zero for proof-of-stake blocks
163 if (header.nNonce != 0)
168 // Coinbase output should be empty if proof-of-stake block
169 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
174 // Check coinstake timestamp
175 if (header.nTime != vtx[1].nTime)
180 // Check proof-of-stake block signature
181 if (fCheckSig && !SignatureOK)
186 if (!vtx[1].CheckTransaction())
191 uniqueTX.Add(vtx[1].Hash);
192 nSigOps += vtx[1].LegacySigOpCount;
196 // Check proof of work matches claimed amount
197 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
203 if (header.nTime > NetInfo.FutureDrift(NetInfo.GetAdjustedTime()))
208 // Check coinbase timestamp
209 if (header.nTime < NetInfo.PastDrift(vtx[0].nTime))
215 // Iterate all transactions starting from second for proof-of-stake block
216 // or first for proof-of-work block
217 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
221 // Reject coinbase transactions at non-zero index
227 // Reject coinstake transactions at index != 1
233 // Check transaction timestamp
234 if (header.nTime < tx.nTime)
239 // Check transaction consistency
240 if (!tx.CheckTransaction())
245 // Add transaction hash into list of unique transaction IDs
246 uniqueTX.Add(tx.Hash);
248 // Calculate sigops count
249 nSigOps += tx.LegacySigOpCount;
252 // Check for duplicate txids.
253 if (uniqueTX.Count != vtx.Length)
258 // Reject block if validation would consume too much resources.
259 if (nSigOps > nMaxSigOps)
265 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
273 private bool CheckProofOfWork(uint256 hash, uint nBits)
275 uint256 nTarget = new uint256();
276 nTarget.Compact = nBits;
279 if (nTarget > NetInfo.nProofOfWorkLimit)
281 // nBits below minimum work
285 // Check proof of work matches claimed amount
288 // hash doesn't match nBits
296 /// Is this a Proof-of-Stake block?
298 public bool IsProofOfStake
302 return (vtx.Length > 1 && vtx[1].IsCoinStake);
307 /// Was this signed correctly?
309 public bool SignatureOK
315 if (signature.Length == 0)
317 return false; // No signature
320 txnouttype whichType;
321 IList<byte[]> solutions;
323 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
325 return false; // No solutions found
328 if (whichType == txnouttype.TX_PUBKEY)
334 pubkey = new CPubKey(solutions[0]);
338 return false; // Error while loading public key
341 return pubkey.VerifySignature(header.Hash, signature);
346 // Proof-of-Work blocks have no signature
356 /// Get instance as sequence of bytes
358 /// <returns>Byte sequence</returns>
359 public static implicit operator byte[] (CBlock b)
361 var stream = new MemoryStream();
362 var writer = new BinaryWriter(stream);
364 writer.Write(b.header);
365 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
367 foreach (var tx in b.vtx)
372 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
373 writer.Write(b.signature);
375 var resultBytes = stream.ToArray();
389 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
391 foreach (var tx in vtx)
396 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
403 /// Get transaction offset inside block.
405 /// <param name="nTx">Transaction index.</param>
406 /// <returns>Offset in bytes from the beginning of block header.</returns>
407 public int GetTxOffset(int nTx)
409 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
411 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
413 for (int i = 0; i < nTx; i++)
415 nOffset += vtx[i].Size;
424 public uint256 hashMerkleRoot
428 var merkleTree = new List<byte>();
430 foreach (var tx in vtx)
432 merkleTree.AddRange(CryptoUtils.ComputeHash256(tx));
436 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
438 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
440 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
442 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
443 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
445 merkleTree.AddRange(CryptoUtils.ComputeHash256(ref left, ref right));
447 levelOffset += nLevelSize;
450 return (merkleTree.Count == 0) ? 0 : (uint256)merkleTree.GetRange(merkleTree.Count-32, 32).ToArray();
454 public override string ToString()
456 var sb = new StringBuilder();
458 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
460 foreach(var tx in vtx)
462 sb.AppendFormat("{0}", tx.ToString());
467 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
472 return sb.ToString();
476 /// Calculate proof-of-work reward.
478 /// <param name="nBits">Packed difficulty representation.</param>
479 /// <param name="nFees">Amount of fees.</param>
480 /// <returns>Reward value.</returns>
481 public static ulong GetProofOfWorkReward(uint nBits, ulong nFees)
483 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
484 // A reasonably continuous curve is used to avoid shock to market
485 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
487 // Human readable form:
489 // nSubsidy = 100 / (diff ^ 1/6)
491 // Please note that we're using bisection to find an approximate solutuion
493 BigInteger bnSubsidyLimit = NetInfo.nMaxMintProofOfWork;
496 nTarget.Compact = nBits;
498 BigInteger bnTarget = new BigInteger(nTarget);
499 BigInteger bnTargetLimit = new BigInteger(NetInfo.nProofOfWorkLimit);
501 BigInteger bnLowerBound = CTransaction.nCent;
502 BigInteger bnUpperBound = bnSubsidyLimit;
504 while (bnLowerBound + CTransaction.nCent <= bnUpperBound)
506 BigInteger bnMidValue = (bnLowerBound + bnUpperBound) / 2;
507 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
508 bnUpperBound = bnMidValue;
510 bnLowerBound = bnMidValue;
513 ulong nSubsidy = (ulong)bnUpperBound;
514 nSubsidy = (nSubsidy / CTransaction.nCent) * CTransaction.nCent;
517 return Math.Min(nSubsidy, NetInfo.nMaxMintProofOfWork) + nFees;