github.com/decred/dcrlnd@v0.7.6/lntypes/preimage.go (about)

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