/** * Novacoin classes library * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com) * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ using System; using System.Text; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace Novacoin { /// /// Block header /// public class CBlockHeader { /// /// Version of block schema. /// public uint nVersion = 6; /// /// Previous block hash. /// public ScryptHash256 prevHash = new ScryptHash256(); /// /// Merkle root hash. /// public Hash256 merkleRoot = new Hash256(); /// /// Block timestamp. /// public uint nTime = 0; /// /// Compressed difficulty representation. /// public uint nBits = 0; /// /// Nonce counter. /// public uint nNonce = 0; /// /// Initialize an empty instance /// public CBlockHeader () { } public CBlockHeader(CBlockHeader h) { nVersion = h.nVersion; prevHash = new ScryptHash256(h.prevHash); merkleRoot = new Hash256(h.merkleRoot); nTime = h.nTime; nBits = h.nBits; nNonce = h.nNonce; } public CBlockHeader(byte[] bytes) { Contract.Requires(bytes.Length == 80, "Any valid block header is exactly 80 bytes long."); nVersion = BitConverter.ToUInt32(bytes, 0); prevHash = new ScryptHash256(bytes, 4); merkleRoot = new Hash256(bytes, 36); nTime = BitConverter.ToUInt32(bytes, 68); nBits = BitConverter.ToUInt32(bytes, 72); nNonce = BitConverter.ToUInt32(bytes, 76); } /// /// Convert current block header instance into sequence of bytes /// /// Byte sequence public static implicit operator byte[] (CBlockHeader h) { var r = new List(); r.AddRange(BitConverter.GetBytes(h.nVersion)); r.AddRange((byte[])h.prevHash); r.AddRange((byte[])h.merkleRoot); r.AddRange(BitConverter.GetBytes(h.nTime)); r.AddRange(BitConverter.GetBytes(h.nBits)); r.AddRange(BitConverter.GetBytes(h.nNonce)); return r.ToArray(); } public ScryptHash256 Hash { get { return ScryptHash256.Compute256(this); } } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat("CBlockHeader(nVersion={0}, prevHash={1}, merkleRoot={2}, nTime={3}, nBits={4}, nNonce={5})", nVersion, prevHash.ToString(), merkleRoot.ToString(), nTime, nBits, nNonce); return sb.ToString(); } } }