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/>.
22 using System.Collections.Generic;
23 using System.Security.Cryptography;
24 using System.Diagnostics.Contracts;
29 /// Represents the block. Block consists of header, transaction array and header signature.
36 public CBlockHeader header;
39 /// Transactions array.
41 public CTransaction[] vtx;
44 /// Block header signature.
46 public byte[] signature = new byte[0];
48 public CBlock(CBlock b)
50 header = new CBlockHeader(b.header);
51 vtx = new CTransaction[b.vtx.Length];
53 for (int i = 0; i < b.vtx.Length; i++)
55 vtx[i] = new CTransaction(b.vtx[i]);
58 b.signature.CopyTo(signature, 0);
62 /// Parse byte sequence and initialize new block instance
64 /// <param name="blockBytes"></param>
65 public CBlock (byte[] blockBytes)
67 ByteQueue wBytes = new ByteQueue(blockBytes);
69 // Fill the block header fields
70 header = new CBlockHeader(wBytes.Get(80));
72 // Parse transactions list
73 vtx = CTransaction.ReadTransactionsList(ref wBytes);
75 // Read block signature
76 signature = wBytes.Get((int)wBytes.GetVarInt());
81 // Initialize empty array of transactions. Please note that such
82 // configuration is not valid real block since it has to provide
83 // at least one transaction.
84 vtx = new CTransaction[0];
88 /// Is this a Proof-of-Stake block?
90 public bool IsProofOfStake
94 return (vtx.Length > 1 && vtx[1].IsCoinStake);
99 /// Was this signed correctly?
101 public bool SignatureOK
107 if (signature.Length == 0)
109 return false; // No signature
112 txnouttype whichType;
113 IList<byte[]> solutions;
115 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
117 return false; // No solutions found
120 if (whichType == txnouttype.TX_PUBKEY)
126 pubkey = new CPubKey(solutions[0]);
130 return false; // Error while loading public key
133 return pubkey.VerifySignature(header.Hash, signature);
138 // Proof-of-Work blocks have no signature
148 /// Get instance as sequence of bytes
150 /// <returns>Byte sequence</returns>
151 public static implicit operator byte[] (CBlock b)
153 var r = new List<byte>();
155 r.AddRange((byte[])b.header);
156 r.AddRange(VarInt.EncodeVarInt(b.vtx.LongLength)); // transactions count
158 foreach (var tx in b.vtx)
160 r.AddRange((byte[])tx);
163 r.AddRange(VarInt.EncodeVarInt(b.signature.LongLength));
164 r.AddRange(b.signature);
176 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
178 foreach (var tx in vtx)
183 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
190 /// Get transaction offset inside block.
192 /// <param name="nTx">Transaction index.</param>
193 /// <returns>Offset in bytes from the beginning of block header.</returns>
194 public int GetTxOffset(int nTx)
196 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
198 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
200 for (int i = 0; i < nTx; i++)
202 nOffset += vtx[i].Size;
211 public Hash256 hashMerkleRoot
215 var merkleTree = new List<byte>();
217 foreach (var tx in vtx)
219 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
223 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
225 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
227 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
229 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
230 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
232 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
234 levelOffset += nLevelSize;
237 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
241 public override string ToString()
243 var sb = new StringBuilder();
245 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
247 foreach(var tx in vtx)
249 sb.AppendFormat("{0}", tx.ToString());
254 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
259 return sb.ToString();