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;
30 public class CBlockHeader
33 /// Version of block schema.
38 /// Previous block hash.
40 public ScryptHash256 prevHash;
45 public Hash256 merkleRoot;
53 /// Compressed difficulty representation.
63 /// Initialize an empty instance
65 public CBlockHeader ()
68 prevHash = new ScryptHash256();
69 merkleRoot = new Hash256();
70 nTime = Interop.GetTime();
75 public CBlockHeader(CBlockHeader h)
77 nVersion = h.nVersion;
78 prevHash = new ScryptHash256(h.prevHash);
79 merkleRoot = new Hash256(h.merkleRoot);
86 /// Init block header with bytes.
88 /// <param name="bytes">Byte array.</param>
89 public CBlockHeader(byte[] bytes)
91 Contract.Requires<ArgumentException>(bytes.Length == 80, "Any valid block header is exactly 80 bytes long.");
93 var stream = new MemoryStream(bytes);
94 var reader = new BinaryReader(stream);
96 nVersion = reader.ReadUInt32();
97 prevHash = new ScryptHash256(reader.ReadBytes(32));
98 merkleRoot = new Hash256(reader.ReadBytes(32));
99 nTime = reader.ReadUInt32();
100 nBits = reader.ReadUInt32();
101 nNonce = reader.ReadUInt32();
107 /// Convert current block header instance into sequence of bytes
109 /// <returns>Byte sequence</returns>
110 public static implicit operator byte[] (CBlockHeader h)
112 var stream = new MemoryStream();
113 var writer = new BinaryWriter(stream);
115 writer.Write(h.nVersion);
116 writer.Write(h.prevHash);
117 writer.Write(h.merkleRoot);
118 writer.Write(h.nTime);
119 writer.Write(h.nBits);
120 writer.Write(h.nNonce);
122 var resultBytes = stream.ToArray();
129 public ScryptHash256 Hash
132 return ScryptHash256.Compute256(this);
136 public override string ToString()
138 var sb = new StringBuilder();
139 sb.AppendFormat("CBlockHeader(nVersion={0}, prevHash={1}, merkleRoot={2}, nTime={3}, nBits={4}, nNonce={5})", nVersion, prevHash.ToString(), merkleRoot.ToString(), nTime, nBits, nNonce);
140 return sb.ToString();