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;
27 public class BlockConstructorException : Exception
29 public BlockConstructorException()
33 public BlockConstructorException(string message)
38 public BlockConstructorException(string message, Exception inner)
39 : base(message, inner)
45 /// Represents the block. Block consists of header, transaction array and header signature.
52 public CBlockHeader header;
55 /// Transactions array.
57 public CTransaction[] vtx;
60 /// Block header signature.
62 public byte[] signature = new byte[0];
67 /// <param name="b">CBlock instance.</param>
68 public CBlock(CBlock b)
70 header = new CBlockHeader(b.header);
71 vtx = new CTransaction[b.vtx.Length];
73 for (int i = 0; i < b.vtx.Length; i++)
75 vtx[i] = new CTransaction(b.vtx[i]);
78 b.signature.CopyTo(signature, 0);
82 /// Parse byte sequence and initialize new block instance
84 /// <param name="blockBytes">Bytes sequence.</param>
85 public CBlock (byte[] blockBytes)
89 ByteQueue wBytes = new ByteQueue(blockBytes);
91 // Fill the block header fields
92 header = new CBlockHeader(wBytes.Get(80));
94 // Parse transactions list
95 vtx = CTransaction.ReadTransactionsList(ref wBytes);
97 // Read block signature
98 signature = wBytes.Get((int)wBytes.GetVarInt());
102 throw new BlockConstructorException("Deserealization failed", e);
108 // Initialize empty array of transactions. Please note that such
109 // configuration is not valid real block since it has to provide
110 // at least one transaction.
111 vtx = new CTransaction[0];
115 /// Is this a Proof-of-Stake block?
117 public bool IsProofOfStake
121 return (vtx.Length > 1 && vtx[1].IsCoinStake);
126 /// Was this signed correctly?
128 public bool SignatureOK
134 if (signature.Length == 0)
136 return false; // No signature
139 txnouttype whichType;
140 IList<byte[]> solutions;
142 if (!ScriptCode.Solver(vtx[1].vout[1].scriptPubKey, out whichType, out solutions))
144 return false; // No solutions found
147 if (whichType == txnouttype.TX_PUBKEY)
153 pubkey = new CPubKey(solutions[0]);
157 return false; // Error while loading public key
160 return pubkey.VerifySignature(header.Hash, signature);
165 // Proof-of-Work blocks have no signature
175 /// Get instance as sequence of bytes
177 /// <returns>Byte sequence</returns>
178 public static implicit operator byte[] (CBlock b)
180 var r = new List<byte>();
182 r.AddRange((byte[])b.header);
183 r.AddRange(VarInt.EncodeVarInt(b.vtx.LongLength)); // transactions count
185 foreach (var tx in b.vtx)
187 r.AddRange((byte[])tx);
190 r.AddRange(VarInt.EncodeVarInt(b.signature.LongLength));
191 r.AddRange(b.signature);
203 int nSize = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
205 foreach (var tx in vtx)
210 nSize += VarInt.GetEncodedSize(signature.Length) + signature.Length;
217 /// Get transaction offset inside block.
219 /// <param name="nTx">Transaction index.</param>
220 /// <returns>Offset in bytes from the beginning of block header.</returns>
221 public int GetTxOffset(int nTx)
223 Contract.Requires<ArgumentException>(nTx >= 0 && nTx < vtx.Length, "Transaction index you've specified is incorrect.");
225 int nOffset = 80 + VarInt.GetEncodedSize(vtx.Length); // CBlockHeader + NumTx
227 for (int i = 0; i < nTx; i++)
229 nOffset += vtx[i].Size;
238 public Hash256 hashMerkleRoot
242 var merkleTree = new List<byte>();
244 foreach (var tx in vtx)
246 merkleTree.AddRange(Hash256.ComputeRaw256(tx));
250 for (int nLevelSize = vtx.Length; nLevelSize > 1; nLevelSize = (nLevelSize + 1) / 2)
252 for (int nLeft = 0; nLeft < nLevelSize; nLeft += 2)
254 int nRight = Math.Min(nLeft + 1, nLevelSize - 1);
256 var left = merkleTree.GetRange((levelOffset + nLeft) * 32, 32).ToArray();
257 var right = merkleTree.GetRange((levelOffset + nRight) * 32, 32).ToArray();
259 merkleTree.AddRange(Hash256.ComputeRaw256(ref left, ref right));
261 levelOffset += nLevelSize;
264 return (merkleTree.Count == 0) ? new Hash256() : new Hash256(merkleTree.GetRange(merkleTree.Count-32, 32).ToArray());
268 public override string ToString()
270 var sb = new StringBuilder();
272 sb.AppendFormat("CBlock(\n header={0},\n", header.ToString());
274 foreach(var tx in vtx)
276 sb.AppendFormat("{0}", tx.ToString());
281 sb.AppendFormat(", signature={0}, signatureOK={1}\n", Interop.ToHex(signature), SignatureOK);
286 return sb.ToString();