Files
lnd.xprv/lntypes/hash.go
T

52 lines
1.2 KiB
Go
Raw Normal View History

2019-01-15 10:42:25 +01:00
package lntypes
import (
"encoding/hex"
"fmt"
)
// HashSize of array used to store hashes.
const HashSize = 32
2019-05-28 15:27:04 +02:00
// ZeroHash is a predefined hash containing all zeroes.
var ZeroHash Hash
2019-01-15 10:42:25 +01:00
// Hash is used in several of the lightning messages and common structures. It
// typically represents a payment hash.
type Hash [HashSize]byte
// String returns the Hash as a hexadecimal string.
func (hash Hash) String() string {
return hex.EncodeToString(hash[:])
}
2019-02-09 20:39:43 +01:00
// MakeHash returns a new Hash from a byte slice. An error is returned if
2019-01-15 10:42:25 +01:00
// the number of bytes passed in is not HashSize.
2019-02-09 20:39:43 +01:00
func MakeHash(newHash []byte) (Hash, error) {
2019-01-15 10:42:25 +01:00
nhlen := len(newHash)
if nhlen != HashSize {
2019-02-09 20:39:43 +01:00
return Hash{}, fmt.Errorf("invalid hash length of %v, want %v",
2019-01-15 10:42:25 +01:00
nhlen, HashSize)
}
var hash Hash
copy(hash[:], newHash)
2019-02-09 20:39:43 +01:00
return hash, nil
2019-01-15 10:42:25 +01:00
}
2019-02-09 20:39:43 +01:00
// MakeHashFromStr creates a Hash from a hex hash string.
func MakeHashFromStr(newHash string) (Hash, error) {
2019-01-15 10:42:25 +01:00
// Return error if hash string is of incorrect length.
if len(newHash) != HashSize*2 {
2019-02-09 20:39:43 +01:00
return Hash{}, fmt.Errorf("invalid hash string length of %v, "+
2019-01-15 10:42:25 +01:00
"want %v", len(newHash), HashSize*2)
}
hash, err := hex.DecodeString(newHash)
if err != nil {
2019-02-09 20:39:43 +01:00
return Hash{}, err
2019-01-15 10:42:25 +01:00
}
2019-02-09 20:39:43 +01:00
return MakeHash(hash)
2019-01-15 10:42:25 +01:00
}