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.
51 /// Maximum block size is 1Mb.
53 public const uint nMaxBlockSize = 1000000;
56 /// Sanity threshold for amount of sigops.
58 public const uint nMaxSigOps = 20000;
63 public CBlockHeader header;
66 /// Transactions array.
68 public CTransaction[] vtx;
71 /// Block header signature.
73 public byte[] signature = new byte[0];
78 /// <param name="b">CBlock instance.</param>
79 public CBlock(CBlock b)
81 header = new CBlockHeader(b.header);
82 vtx = new CTransaction[b.vtx.Length];
84 for (int i = 0; i < b.vtx.Length; i++)
86 vtx[i] = new CTransaction(b.vtx[i]);
89 signature = new byte[b.signature.Length];
90 b.signature.CopyTo(signature, 0);
94 /// Parse byte sequence and initialize new block instance
96 /// <param name="blockBytes">Bytes sequence.</param>
97 public CBlock (byte[] blockBytes)
101 var stream = new MemoryStream(blockBytes);
102 var reader = new BinaryReader(stream);
104 // Fill the block header fields
105 header = new CBlockHeader(ref reader);
107 // Parse transactions list
108 vtx = CTransaction.ReadTransactionsList(ref reader);
110 // Read block signature
111 signature = reader.ReadBytes((int)VarInt.ReadVarInt(ref reader));
117 throw new BlockException("Deserialization failed", e);
123 // Initialize empty array of transactions. Please note that such
124 // configuration is not valid real block since it has to provide
125 // at least one transaction.
126 vtx = new CTransaction[0];
129 public bool CheckBlock(bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true)
131 var uniqueTX = new List<uint256>(); // tx hashes
132 uint nSigOps = 0; // total sigops
134 // Basic sanity checkings
135 if (vtx.Length == 0 || Size > nMaxBlockSize)
140 bool fProofOfStake = IsProofOfStake;
142 // First transaction must be coinbase, the rest must not be
143 if (!vtx[0].IsCoinBase)
148 if (!vtx[0].CheckTransaction())
153 uniqueTX.Add(vtx[0].Hash);
154 nSigOps += vtx[0].LegacySigOpCount;
158 // Proof-of-STake related checkings. Note that we know here that 1st transactions is coinstake. We don't need
159 // check the type of 1st transaction because it's performed earlier by IsProofOfStake()
161 // nNonce must be zero for proof-of-stake blocks
162 if (header.nNonce != 0)
167 // Coinbase output must be empty if proof-of-stake block
168 if (vtx[0].vout.Length != 1 || !vtx[0].vout[0].IsEmpty)
173 // Check coinstake timestamp
174 if (header.nTime != vtx[1].nTime)
179 // Check proof-of-stake block signature
180 if (fCheckSig && !SignatureOK)
182 return false; // Proof-of-Stake signature checking failure.
185 if (!vtx[1].CheckTransaction())
190 uniqueTX.Add(vtx[1].Hash);
191 nSigOps += vtx[1].LegacySigOpCount;
195 // Check proof of work matches claimed amount
196 if (fCheckPOW && !CheckProofOfWork(header.Hash, header.nBits))
202 if (header.nTime > NetInfo.FutureDrift(NetInfo.GetAdjustedTime()))
207 // Check coinbase timestamp
208 if (header.nTime < NetInfo.PastDrift(vtx[0].nTime))
214 // Iterate all transactions starting from second for proof-of-stake block
215 // or first for proof-of-work block
216 for (int i = fProofOfStake ? 2 : 1; i < vtx.Length; i++)
220 // Reject coinbase transactions at non-zero index
226 // Reject coinstake transactions at index != 1
232 // Check transaction timestamp
233 if (header.nTime < tx.nTime)
238 // Check transaction consistency
239 if (!tx.CheckTransaction())
244 // Add transaction hash into list of unique transaction IDs
245 uniqueTX.Add(tx.Hash);
247 // Calculate sigops count
248 nSigOps += tx.LegacySigOpCount;
251 // Check for duplicate txids.
252 if (uniqueTX.Count != vtx.Length)
257 // Reject block if validation would consume too much resources.
258 if (nSigOps > nMaxSigOps)
264 if (fCheckMerkleRoot && hashMerkleRoot != header.merkleRoot)
272 private static bool CheckProofOfWork(uint256 hash, uint nBits)
274 uint256 nTarget = new uint256();
275 nTarget.Compact = nBits;
278 if (nTarget > NetInfo.nProofOfWorkLimit)
280 // nBits below minimum work
284 // Check proof of work matches claimed amount
287 // hash doesn't match nBits
295 /// Is this a Proof-of-Stake block?
297 public bool IsProofOfStake
301 return (vtx.Length > 1 && vtx[1].IsCoinStake);
306 /// Was this signed correctly?
308 public bool SignatureOK
314 if (signature.Length == 0)
316 return false; // No signature
319 txnouttype whichType;
320 IList<byte[]> solutions;
322 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
324 return false; // No solutions found
327 if (whichType == txnouttype.TX_PUBKEY)
333 pubkey = new CPubKey(solutions[0]);
337 return false; // Error while loading public key
340 return pubkey.VerifySignature(header.Hash, signature);
345 // Proof-of-Work blocks have no signature
355 /// Get instance as sequence of bytes
357 /// <returns>Byte sequence</returns>
358 public static implicit operator byte[] (CBlock b)
360 var stream = new MemoryStream();
361 var writer = new BinaryWriter(stream);
363 writer.Write(b.header);
364 writer.Write(VarInt.EncodeVarInt(b.vtx.LongLength));
366 foreach (var tx in b.vtx)
371 writer.Write(VarInt.EncodeVarInt(b.signature.LongLength));
372 writer.Write(b.signature);
374 var resultBytes = stream.ToArray();
388 uint nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
390 foreach (var tx in vtx)
395 nSize += VarInt.GetEncodedSize(signature.Length) + (uint)signature.Length;
402 /// Get transaction offset inside block.
404 /// <param name="nTx">Transaction index.</param>
405 /// <returns>Offset in bytes from the beginning of block header.</returns>
406 public uint GetTxOffset(int nTx)
408 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
410 uint nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
412 for (int i = 0; i < nTx; i++)
414 nOffset += vtx[i].Size;
423 public uint256 hashMerkleRoot
427 var merkleTree = new List<byte>();
429 foreach (var tx in vtx)
431 merkleTree.AddRange(CryptoUtils.ComputeHash256(tx));
435 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
437 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
439 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
441 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
442 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
444 merkleTree.AddRange(CryptoUtils.ComputeHash256(ref left, ref right));
446 levelOffset += nLevelSize;
449 return (merkleTree.Count == 0) ? 0 : (uint256)merkleTree.GetRange(merkleTree.Count-32, 32).ToArray();
453 public override string ToString()
455 var sb = new StringBuilder();
457 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
459 foreach(var tx in vtx)
461 sb.AppendFormat("{0}", tx.ToString());
466 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
471 return sb.ToString();
475 /// Calculate proof-of-work reward.
477 /// <param name="nBits">Packed difficulty representation.</param>
478 /// <param name="nFees">Amount of fees.</param>
479 /// <returns>Reward value.</returns>
480 public static ulong GetProofOfWorkReward(uint nBits, ulong nFees)
482 // NovaCoin: subsidy is cut in half every 64x multiply of PoW difficulty
483 // A reasonably continuous curve is used to avoid shock to market
484 // (nSubsidyLimit / nSubsidy) ** 6 == bnProofOfWorkLimit / bnTarget
486 // Human readable form:
488 // nSubsidy = 100 / (diff ^ 1/6)
490 // Please note that we're using bisection to find an approximate solutuion
494 nTarget.Compact = nBits;
496 BigNum bnTarget = nTarget;
497 BigNum bnTargetLimit = NetInfo.nProofOfWorkLimit;
499 BigNum bnSubsidyLimit = NetInfo.nMaxMintProofOfWork;
500 BigNum bnLowerBound = CTransaction.nCent;
501 BigNum bnUpperBound = bnSubsidyLimit;
503 while (bnLowerBound + CTransaction.nCent <= bnUpperBound)
505 BigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
506 if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnSubsidyLimit * bnTarget)
507 bnUpperBound = bnMidValue;
509 bnLowerBound = bnMidValue;
512 ulong nSubsidy = bnUpperBound;
513 nSubsidy = (nSubsidy / CTransaction.nCent) * CTransaction.nCent;
515 return Math.Min(nSubsidy, NetInfo.nMaxMintProofOfWork) + nFees;
518 public static ulong GetProofOfStakeReward(ulong nCoinAge, uint nBits, uint nTime)
520 ulong nRewardCoinYear, nSubsidy, nSubsidyLimit = 10 * CTransaction.nCoin;
522 if (nTime > NetInfo.nDynamicStakeRewardTime)
524 // Stage 2 of emission process is PoS-based. It will be active on mainNet since 20 Jun 2013.
526 BigNum bnRewardCoinYearLimit = NetInfo.nMaxMintProofOfStake; // Base stake mint rate, 100% year interest
529 nTarget.Compact = nBits;
531 BigNum bnTarget = nTarget;
532 BigNum bnTargetLimit = NetInfo.GetProofOfStakeLimit(0, nTime);
534 // NovaCoin: A reasonably continuous curve is used to avoid shock to market
536 BigNum bnLowerBound = CTransaction.nCent, // Lower interest bound is 1% per year
537 bnUpperBound = bnRewardCoinYearLimit, // Upper interest bound is 100% per year
538 bnMidPart, bnRewardPart;
540 while (bnLowerBound + CTransaction.nCent <= bnUpperBound)
542 BigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
543 if (nTime < NetInfo.nStakeCurveSwitchTime)
546 // Until 20 Oct 2013: reward for coin-year is cut in half every 64x multiply of PoS difficulty
548 // (nRewardCoinYearLimit / nRewardCoinYear) ** 6 == bnProofOfStakeLimit / bnTarget
550 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/6)
553 bnMidPart = bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnMidValue;
554 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
559 // Since 20 Oct 2013: reward for coin-year is cut in half every 8x multiply of PoS difficulty
561 // (nRewardCoinYearLimit / nRewardCoinYear) ** 3 == bnProofOfStakeLimit / bnTarget
563 // Human readable form: nRewardCoinYear = 1 / (posdiff ^ 1/3)
566 bnMidPart = bnMidValue * bnMidValue * bnMidValue;
567 bnRewardPart = bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit;
570 if (bnMidPart * bnTargetLimit > bnRewardPart * bnTarget)
571 bnUpperBound = bnMidValue;
573 bnLowerBound = bnMidValue;
576 nRewardCoinYear = bnUpperBound;
577 nRewardCoinYear = Math.Min((nRewardCoinYear / CTransaction.nCent) * CTransaction.nCent, NetInfo.nMaxMintProofOfStake);
581 // Old creation amount per coin-year, 5% fixed stake mint rate
582 nRewardCoinYear = 5 * CTransaction.nCent;
585 nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
587 // Set reasonable reward limit for large inputs since 20 Oct 2013
589 // This will stimulate large holders to use smaller inputs, that's good for the network protection
590 if (NetInfo.nStakeCurveSwitchTime < nTime)
592 nSubsidy = Math.Min(nSubsidy, nSubsidyLimit);