Simplification of syntax
[NovacoinLibrary.git] / Novacoin / Hash.cs
1 \feffusing System;
2 using System.Security.Cryptography;
3 using System.Collections.Generic;
4 using System.Linq;
5
6 namespace Novacoin
7 {
8     public abstract class Hash
9     {
10         /// <summary>
11         /// Computes the SHA256 hash for the input data using the managed library.
12         /// </summary>
13         protected static SHA256Managed _hasher256 = new SHA256Managed();
14         
15         /// <summary>
16         /// Array of digest bytes.
17         /// </summary>
18         protected byte[] _hashBytes = null;
19
20         /// <summary>
21         /// Hash size, must be overriden
22         /// </summary>
23         public abstract int hashSize 
24         {
25             get; 
26         }
27
28         public byte[] hashBytes
29         {
30             get { return _hashBytes; }
31         }
32
33         /// <summary>
34         /// Initializes an empty instance of the Hash class.
35         /// </summary>
36         public Hash()
37         {
38             _hashBytes = Enumerable.Repeat<byte>(0, hashSize).ToArray();
39         }
40
41         /// <summary>
42         /// Initializes a new instance of Hash class with first 20 bytes from supplied list
43         /// </summary>
44         /// <param name="bytesList">List of bytes</param>
45         public Hash(IEnumerable<byte> bytes, int skip = 0)
46         {
47             _hashBytes = bytes.Skip(skip).Take(hashSize).ToArray();
48         }
49
50         public Hash(byte[] bytes, int offset = 0)
51         {
52             _hashBytes = new byte[hashSize];
53             Array.Copy(bytes, offset, _hashBytes, 0, hashSize);
54         }
55
56         public Hash(Hash h)
57         {
58             _hashBytes = new byte[h.hashSize];
59             h._hashBytes.CopyTo(_hashBytes, 0);
60         }
61
62         public bool IsZero
63         {
64             get { return !_hashBytes.Any(b => b != 0); }
65         }
66
67         public override string ToString()
68         {
69             return Interop.ToHex(Interop.ReverseBytes(_hashBytes));
70         }
71     }
72 }