preimage.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package lntypes
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. // PreimageSize of array used to store preimagees.
  8. const PreimageSize = 32
  9. // Preimage is used in several of the lightning messages and common structures.
  10. // It represents a payment preimage.
  11. type Preimage [PreimageSize]byte
  12. // String returns the Preimage as a hexadecimal string.
  13. func (p Preimage) String() string {
  14. return hex.EncodeToString(p[:])
  15. }
  16. // MakePreimage returns a new Preimage from a bytes slice. An error is returned
  17. // if the number of bytes passed in is not PreimageSize.
  18. func MakePreimage(newPreimage []byte) (Preimage, error) {
  19. nhlen := len(newPreimage)
  20. if nhlen != PreimageSize {
  21. return Preimage{}, fmt.Errorf("invalid preimage length of %v, "+
  22. "want %v", nhlen, PreimageSize)
  23. }
  24. var preimage Preimage
  25. copy(preimage[:], newPreimage)
  26. return preimage, nil
  27. }
  28. // MakePreimageFromStr creates a Preimage from a hex preimage string.
  29. func MakePreimageFromStr(newPreimage string) (Preimage, error) {
  30. // Return error if preimage string is of incorrect length.
  31. if len(newPreimage) != PreimageSize*2 {
  32. return Preimage{}, fmt.Errorf("invalid preimage string length "+
  33. "of %v, want %v", len(newPreimage), PreimageSize*2)
  34. }
  35. preimage, err := hex.DecodeString(newPreimage)
  36. if err != nil {
  37. return Preimage{}, err
  38. }
  39. return MakePreimage(preimage)
  40. }
  41. // Hash returns the sha256 hash of the preimage.
  42. func (p *Preimage) Hash() Hash {
  43. return Hash(sha256.Sum256(p[:]))
  44. }
  45. // Matches returns whether this preimage is the preimage of the given hash.
  46. func (p *Preimage) Matches(h Hash) bool {
  47. return h == p.Hash()
  48. }