Initial implementation of CBlockStore.
[NovacoinLibrary.git] / Novacoin / Hash.cs
1 \feff/**
2  *  Novacoin classes library
3  *  Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
4
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.
9
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.
14
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/>.
17  */
18
19 using System;
20 using System.Linq;
21
22 namespace Novacoin
23 {
24     public abstract class Hash
25     {
26         /// <summary>
27         /// Array of digest bytes.
28         /// </summary>
29         protected byte[] _hashBytes = null;
30
31         /// <summary>
32         /// Hash size, must be overriden
33         /// </summary>
34         public abstract int hashSize 
35         {
36             get; 
37         }
38
39         /// <summary>
40         /// Initializes an empty instance of the Hash class.
41         /// </summary>
42         public Hash()
43         {
44             _hashBytes = new byte[hashSize];
45         }
46
47         /// <summary>
48         /// Initializes a new instance of Hash class
49         /// </summary>
50         /// <param name="bytesList">Array of bytes</param>
51         public Hash(byte[] bytes, int offset = 0)
52         {
53             if (bytes.Length - offset < hashSize)
54             {
55                 throw new ArgumentException("You need to provide a sufficient amount of data to initialize new instance of hash object.");
56             }
57
58             _hashBytes = new byte[hashSize];
59             Array.Copy(bytes, offset, _hashBytes, 0, hashSize);
60         }
61
62         /// <summary>
63         /// Initializes a new instance of Hash class as a copy of another one
64         /// </summary>
65         /// <param name="bytesList">Instance of hash class</param>
66         public Hash(Hash h)
67         {
68             _hashBytes = new byte[h.hashSize];
69             h._hashBytes.CopyTo(_hashBytes, 0);
70         }
71
72         public bool IsZero
73         {
74             get { return !_hashBytes.Any(b => b != 0); }
75         }
76
77         public static implicit operator byte[](Hash h)
78         {
79             return h._hashBytes;
80         }
81
82         public override string ToString()
83         {
84             return Interop.ToHex(Interop.ReverseBytes(_hashBytes));
85         }
86     }
87 }