digest.go raw

   1  package tx
   2  
   3  import (
   4  	"github.com/btcsuite/btcd/btcec/v2"
   5  	btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
   6  )
   7  
   8  // SignDigest signs one BIP143 digest and returns the DER signature with its sighash byte and
   9  // the compressed public key that verifies it.
  10  //
  11  // It is the piece SignP2WPKH and a PSBT signer share: a P2WPKH witness and a partial-signature
  12  // record carry the same bytes, and two signers that computed them differently would be two
  13  // answers to one question.
  14  func SignDigest(secret []byte, digest [32]byte) ([]byte, []byte, error) {
  15  	return SignDigestWithType(secret, digest, byte(SighashAll))
  16  }
  17  
  18  // SignDigestWithType signs one digest and appends the signature hash byte the
  19  // verifier reads. The legacy wallet uses SIGHASH_ALL; the XBT wallet uses
  20  // SIGHASH_ALL|SIGHASH_UNIFIED, where the byte is 0x21 and the digest is the
  21  // unified one, not BIP143.
  22  func SignDigestWithType(secret []byte, digest [32]byte, sighashType byte) ([]byte, []byte, error) {
  23  	if len(secret) != 32 {
  24  		return nil, nil, ErrKey
  25  	}
  26  
  27  	key, _ := btcec.PrivKeyFromBytes(secret)
  28  
  29  	if key == nil {
  30  		return nil, nil, ErrKey
  31  	}
  32  
  33  	signature := btcecdsa.Sign(key, digest[:])
  34  
  35  	der := append(signature.Serialize(), sighashType)
  36  
  37  	return der, key.PubKey().SerializeCompressed(), nil
  38  }
  39