|
| 1 | +package bitcoin |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/hex" |
| 5 | + "fmt" |
| 6 | +) |
| 7 | + |
| 8 | +// HashByteLength is the byte length of the Hash type. |
| 9 | +const HashByteLength = 32 |
| 10 | + |
| 11 | +// Hash represents the double SHA-256 of some arbitrary data using the |
| 12 | +// InternalByteOrder. |
| 13 | +type Hash [HashByteLength]byte |
| 14 | + |
| 15 | +// NewHashFromString creates a new Hash instance using the given string. |
| 16 | +// The string is interpreted according to the given ByteOrder. That is, the |
| 17 | +// string is taken as is if the ByteOrder is InternalByteOrder and reversed if |
| 18 | +// the ByteOrder is ReversedByteOrder. The string's length must be equal |
| 19 | +// to 2*HashByteLength. |
| 20 | +func NewHashFromString(hash string, byteOrder ByteOrder) (Hash, error) { |
| 21 | + if len(hash) != 2*HashByteLength { |
| 22 | + return Hash{}, fmt.Errorf("wrong hash string size") |
| 23 | + } |
| 24 | + |
| 25 | + hashBytes, err := hex.DecodeString(hash) |
| 26 | + if err != nil { |
| 27 | + return Hash{}, fmt.Errorf( |
| 28 | + "cannot decode hash string: [%w]", |
| 29 | + err, |
| 30 | + ) |
| 31 | + } |
| 32 | + |
| 33 | + return NewHash(hashBytes, byteOrder) |
| 34 | +} |
| 35 | + |
| 36 | +// NewHash creates a new Hash instance using the given byte slice. |
| 37 | +// The byte slice is interpreted according to the given ByteOrder. That is, the |
| 38 | +// byte slice is taken as is if the ByteOrder is InternalByteOrder and reversed |
| 39 | +// if the ByteOrder is ReversedByteOrder. The byte slice's length must be equal |
| 40 | +// to HashByteLength. |
| 41 | +func NewHash(hash []byte, byteOrder ByteOrder) (Hash, error) { |
| 42 | + if len(hash) != HashByteLength { |
| 43 | + return Hash{}, fmt.Errorf("wrong hash size") |
| 44 | + } |
| 45 | + |
| 46 | + var result Hash |
| 47 | + |
| 48 | + switch byteOrder { |
| 49 | + case InternalByteOrder: |
| 50 | + copy(result[:], hash[:]) |
| 51 | + case ReversedByteOrder: |
| 52 | + for i := 0; i < HashByteLength/2; i++ { |
| 53 | + hash[i], hash[HashByteLength-1-i] = hash[HashByteLength-1-i], hash[i] |
| 54 | + } |
| 55 | + copy(result[:], hash[:]) |
| 56 | + default: |
| 57 | + panic("unknown byte order") |
| 58 | + } |
| 59 | + |
| 60 | + return result, nil |
| 61 | +} |
| 62 | + |
| 63 | +// String returns the unprefixed hexadecimal string representation of the Hash |
| 64 | +// in the given ByteOrder. |
| 65 | +func (h Hash) String(byteOrder ByteOrder) string { |
| 66 | + switch byteOrder { |
| 67 | + case InternalByteOrder: |
| 68 | + return hex.EncodeToString(h[:]) |
| 69 | + case ReversedByteOrder: |
| 70 | + for i := 0; i < HashByteLength/2; i++ { |
| 71 | + h[i], h[HashByteLength-1-i] = h[HashByteLength-1-i], h[i] |
| 72 | + } |
| 73 | + return hex.EncodeToString(h[:]) |
| 74 | + default: |
| 75 | + panic("unknown byte order") |
| 76 | + } |
| 77 | +} |
0 commit comments