Add license header.
[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.Security.Cryptography;
21 using System.Collections.Generic;
22 using System.Linq;
23
24 namespace Novacoin
25 {
26     public abstract class Hash
27     {
28         /// <summary>
29         /// Computes the SHA256 hash for the input data using the managed library.
30         /// </summary>
31         protected static SHA256Managed _hasher256 = new SHA256Managed();
32         
33         /// <summary>
34         /// Array of digest bytes.
35         /// </summary>
36         protected byte[] _hashBytes = null;
37
38         /// <summary>
39         /// Hash size, must be overriden
40         /// </summary>
41         public abstract int hashSize 
42         {
43             get; 
44         }
45
46         public byte[] hashBytes
47         {
48             get { return _hashBytes; }
49         }
50
51         /// <summary>
52         /// Initializes an empty instance of the Hash class.
53         /// </summary>
54         public Hash()
55         {
56             _hashBytes = Enumerable.Repeat<byte>(0, hashSize).ToArray();
57         }
58
59         /// <summary>
60         /// Initializes a new instance of Hash class with first 20 bytes from supplied list
61         /// </summary>
62         /// <param name="bytesList">List of bytes</param>
63         public Hash(IEnumerable<byte> bytes, int skip = 0)
64         {
65             _hashBytes = bytes.Skip(skip).Take(hashSize).ToArray();
66         }
67
68         public Hash(byte[] bytes, int offset = 0)
69         {
70             _hashBytes = new byte[hashSize];
71             Array.Copy(bytes, offset, _hashBytes, 0, hashSize);
72         }
73
74         public Hash(Hash h)
75         {
76             _hashBytes = new byte[h.hashSize];
77             h._hashBytes.CopyTo(_hashBytes, 0);
78         }
79
80         public bool IsZero
81         {
82             get { return !_hashBytes.Any(b => b != 0); }
83         }
84
85         public override string ToString()
86         {
87             return Interop.ToHex(Interop.ReverseBytes(_hashBytes));
88         }
89     }
90 }