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 uint256 prevHash;
45 public uint256 merkleRoot;
53 /// Compressed difficulty representation.
63 /// Initialize an empty instance
65 public CBlockHeader ()
68 prevHash = new uint256();
69 merkleRoot = new uint256();
70 nTime = Interop.GetTime();
75 public CBlockHeader(CBlockHeader header)
77 nVersion = header.nVersion;
78 prevHash = header.prevHash;
79 merkleRoot = header.merkleRoot;
82 nNonce = header.nNonce;
85 internal CBlockHeader(ref BinaryReader reader)
87 nVersion = reader.ReadUInt32();
88 prevHash = reader.ReadBytes(32);
89 merkleRoot = reader.ReadBytes(32);
90 nTime = reader.ReadUInt32();
91 nBits = reader.ReadUInt32();
92 nNonce = reader.ReadUInt32();
96 /// Init block header with bytes.
98 /// <param name="bytes">Byte array.</param>
99 public CBlockHeader(byte[] bytes)
101 Contract.Requires<ArgumentException>(bytes.Length == 80, "Any valid block header is exactly 80 bytes long.");
103 var stream = new MemoryStream(bytes);
104 var reader = new BinaryReader(stream);
106 nVersion = reader.ReadUInt32();
107 prevHash = reader.ReadBytes(32);
108 merkleRoot = reader.ReadBytes(32);
109 nTime = reader.ReadUInt32();
110 nBits = reader.ReadUInt32();
111 nNonce = reader.ReadUInt32();
117 /// Convert current block header instance into sequence of bytes
119 /// <returns>Byte sequence</returns>
120 public static implicit operator byte[] (CBlockHeader header)
122 var stream = new MemoryStream();
123 var writer = new BinaryWriter(stream);
125 writer.Write(header.nVersion);
126 writer.Write(header.prevHash);
127 writer.Write(header.merkleRoot);
128 writer.Write(header.nTime);
129 writer.Write(header.nBits);
130 writer.Write(header.nNonce);
132 var resultBytes = stream.ToArray();
142 return CryptoUtils.ComputeScryptHash256(this);
146 public override string ToString()
148 var sb = new StringBuilder();
149 sb.AppendFormat("CBlockHeader(nVersion={0}, prevHash={1}, merkleRoot={2}, nTime={3}, nBits={4}, nNonce={5})", nVersion, prevHash, merkleRoot, nTime, nBits, nNonce);
150 return sb.ToString();