2019-01-15 12:42:25 +03:00
|
|
|
package lntypes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
// PreimageSize of array used to store preimagees.
|
|
|
|
const PreimageSize = 32
|
|
|
|
|
2019-02-20 04:05:45 +03:00
|
|
|
// Preimage is used in several of the lightning messages and common structures.
|
|
|
|
// It represents a payment preimage.
|
2019-01-15 12:42:25 +03:00
|
|
|
type Preimage [PreimageSize]byte
|
|
|
|
|
|
|
|
// String returns the Preimage as a hexadecimal string.
|
|
|
|
func (p Preimage) String() string {
|
|
|
|
return hex.EncodeToString(p[:])
|
|
|
|
}
|
|
|
|
|
2019-02-20 04:05:45 +03:00
|
|
|
// MakePreimage returns a new Preimage from a bytes slice. An error is returned
|
|
|
|
// if the number of bytes passed in is not PreimageSize.
|
|
|
|
func MakePreimage(newPreimage []byte) (Preimage, error) {
|
2019-01-15 12:42:25 +03:00
|
|
|
nhlen := len(newPreimage)
|
|
|
|
if nhlen != PreimageSize {
|
2019-02-20 04:05:45 +03:00
|
|
|
return Preimage{}, fmt.Errorf("invalid preimage length of %v, "+
|
|
|
|
"want %v", nhlen, PreimageSize)
|
2019-01-15 12:42:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
var preimage Preimage
|
|
|
|
copy(preimage[:], newPreimage)
|
|
|
|
|
2019-02-20 04:05:45 +03:00
|
|
|
return preimage, nil
|
2019-01-15 12:42:25 +03:00
|
|
|
}
|
|
|
|
|
2019-02-20 04:05:45 +03:00
|
|
|
// MakePreimageFromStr creates a Preimage from a hex preimage string.
|
|
|
|
func MakePreimageFromStr(newPreimage string) (Preimage, error) {
|
2019-01-15 12:42:25 +03:00
|
|
|
// Return error if preimage string is of incorrect length.
|
|
|
|
if len(newPreimage) != PreimageSize*2 {
|
2019-02-20 04:05:45 +03:00
|
|
|
return Preimage{}, fmt.Errorf("invalid preimage string length "+
|
|
|
|
"of %v, want %v", len(newPreimage), PreimageSize*2)
|
2019-01-15 12:42:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
preimage, err := hex.DecodeString(newPreimage)
|
|
|
|
if err != nil {
|
2019-02-20 04:05:45 +03:00
|
|
|
return Preimage{}, err
|
2019-01-15 12:42:25 +03:00
|
|
|
}
|
|
|
|
|
2019-02-20 04:05:45 +03:00
|
|
|
return MakePreimage(preimage)
|
2019-01-15 12:42:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Hash returns the sha256 hash of the preimage.
|
|
|
|
func (p *Preimage) Hash() Hash {
|
|
|
|
return Hash(sha256.Sum256(p[:]))
|
|
|
|
}
|
2019-02-10 22:38:36 +03:00
|
|
|
|
|
|
|
// Matches returns whether this preimage is the preimage of the given hash.
|
|
|
|
func (p *Preimage) Matches(h Hash) bool {
|
|
|
|
return h == p.Hash()
|
|
|
|
}
|