Use implicit type casting operator for serialization.
[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             _hashBytes = new byte[hashSize];
54             Array.Copy(bytes, offset, _hashBytes, 0, hashSize);
55         }
56
57         /// <summary>
58         /// Initializes a new instance of Hash class as a copy of another one
59         /// </summary>
60         /// <param name="bytesList">Instance of hash class</param>
61         public Hash(Hash h)
62         {
63             _hashBytes = new byte[h.hashSize];
64             h._hashBytes.CopyTo(_hashBytes, 0);
65         }
66
67         public bool IsZero
68         {
69             get { return !_hashBytes.Any(b => b != 0); }
70         }
71
72         public static implicit operator byte[](Hash h)
73         {
74             return h._hashBytes;
75         }
76
77         public override string ToString()
78         {
79             return Interop.ToHex(Interop.ReverseBytes(_hashBytes));
80         }
81     }
82 }