unified.go raw

   1  package tx
   2  
   3  import (
   4  	"crypto/sha256"
   5  	"encoding/binary"
   6  	"errors"
   7  	"fmt"
   8  )
   9  
  10  // SIGHASH_UNIFIED is the XBT fork's opt-in signature hash bit.
  11  //
  12  // A signature carrying it commits to the unified message rather than BIP143
  13  // or the legacy message. A chain that does not implement the bit computes a
  14  // different message for the same byte, so the signature does not verify there.
  15  const SighashUnified uint32 = 0x20
  16  
  17  // SighashAllUnified is the type the wallet signs on the XBT chain.
  18  const SighashAllUnified uint32 = SighashAll | SighashUnified
  19  
  20  // SpentOutput is one output being spent: its value and its scriptPubKey.
  21  //
  22  // The unified message commits to every input's value and scriptPubKey, not
  23  // just the one being signed. A wallet that only knows the current input cannot
  24  // produce this digest; PSBT already carries the records, and the send path has
  25  // the coins.
  26  type SpentOutput struct {
  27  	Value  uint64
  28  	Script []byte
  29  }
  30  
  31  // SighashUnifiedV0 is the XBT fork's unified digest for input index of a
  32  // segwit v0 spend.
  33  //
  34  // It is not BIP143 with extra fields: it is a tagged hash over the BIP341-shaped
  35  // message in doc/unified-sighash.md. The aggregates are single SHA-256, the
  36  // transaction locktime is committed to as five bytes, and the script type byte
  37  // separates bare/P2SH, segwit v0, taproot and tapscript. This implementation
  38  // covers segwit v0, which is what this wallet signs.
  39  func (t *Tx) SighashUnifiedV0(
  40  	index int, scriptCode []byte, spent []SpentOutput, sighashType uint32,
  41  ) ([32]byte, error) {
  42  	if sighashType&SighashUnified == 0 {
  43  		return [32]byte{}, ErrSighashType
  44  	}
  45  
  46  	outputType := sighashType & 0x1f
  47  	anyoneCanPay := sighashType&0x80 != 0
  48  
  49  	// The wallet signs ALL|UNIFIED. ANYONECANPAY is carried because the node's
  50  	// vectors cover it; NONE and SINGLE are not produced here.
  51  	if outputType != SighashAll {
  52  		return [32]byte{}, fmt.Errorf("%w: output type %d", ErrSighashType, outputType)
  53  	}
  54  
  55  	if sighashType&^(SighashUnified|SighashAll|0x80) != 0 {
  56  		return [32]byte{}, fmt.Errorf("%w: unsupported bits in %#x", ErrSighashType, sighashType)
  57  	}
  58  
  59  	if index < 0 || index >= len(t.Inputs) {
  60  		return [32]byte{}, ErrInputIndex
  61  	}
  62  
  63  	if len(spent) != len(t.Inputs) {
  64  		return [32]byte{}, fmt.Errorf(
  65  			"tx: %d spent outputs for %d inputs; the unified digest commits to every input",
  66  			len(spent), len(t.Inputs),
  67  		)
  68  	}
  69  
  70  	if len(scriptCode) == 0 {
  71  		return [32]byte{}, ErrScriptTooLong
  72  	}
  73  
  74  	var prevouts, amounts, scripts, sequences, outputs [32]byte
  75  
  76  	if !anyoneCanPay {
  77  		prevouts = sha256.Sum256(serializePrevouts(t.Inputs))
  78  		amounts = sha256.Sum256(serializeAmounts(spent))
  79  		scripts = sha256.Sum256(serializeScripts(spent))
  80  		sequences = sha256.Sum256(serializeSequences(t.Inputs))
  81  	}
  82  
  83  	outputs = sha256.Sum256(serializeOutputs(t.Outputs))
  84  
  85  	message := make([]byte, 0, 256+len(scriptCode))
  86  
  87  	// Epoch, then the hash type as one byte. Consensus reads the type from the
  88  	// last byte of the signature, so it is exactly this byte.
  89  	message = append(message, 0)
  90  	message = append(message, byte(sighashType))
  91  
  92  	// Version, then locktime as five bytes: four now and a zero fifth for a
  93  	// future widened field.
  94  	message = binary.LittleEndian.AppendUint32(message, t.Version)
  95  	message = binary.LittleEndian.AppendUint32(message, t.LockTime)
  96  	message = append(message, 0)
  97  
  98  	if !anyoneCanPay {
  99  		message = append(message, prevouts[:]...)
 100  		message = append(message, amounts[:]...)
 101  		message = append(message, scripts[:]...)
 102  		message = append(message, sequences[:]...)
 103  	}
 104  
 105  	message = append(message, outputs[:]...)
 106  
 107  	// Script type 1 is segwit v0.
 108  	message = append(message, 1)
 109  
 110  	if anyoneCanPay {
 111  		input := t.Inputs[index]
 112  		message = append(message, input.Hash[:]...)
 113  		message = binary.LittleEndian.AppendUint32(message, input.Index)
 114  		message = binary.LittleEndian.AppendUint64(message, spent[index].Value)
 115  		message = appendCompactSize(message, len(spent[index].Script))
 116  		message = append(message, spent[index].Script...)
 117  		message = binary.LittleEndian.AppendUint32(message, input.Sequence)
 118  	} else {
 119  		message = binary.LittleEndian.AppendUint32(message, uint32(index))
 120  	}
 121  
 122  	message = appendCompactSize(message, len(scriptCode))
 123  	message = append(message, scriptCode...)
 124  
 125  	return taggedHash("UnifiedSighash", message), nil
 126  }
 127  
 128  func serializePrevouts(inputs []Input) []byte {
 129  	out := make([]byte, 0, 36*len(inputs))
 130  
 131  	for _, input := range inputs {
 132  		out = append(out, input.Hash[:]...)
 133  		out = binary.LittleEndian.AppendUint32(out, input.Index)
 134  	}
 135  
 136  	return out
 137  }
 138  
 139  func serializeAmounts(spent []SpentOutput) []byte {
 140  	out := make([]byte, 0, 8*len(spent))
 141  
 142  	for _, coin := range spent {
 143  		out = binary.LittleEndian.AppendUint64(out, coin.Value)
 144  	}
 145  
 146  	return out
 147  }
 148  
 149  func serializeScripts(spent []SpentOutput) []byte {
 150  	out := make([]byte, 0, 34*len(spent))
 151  
 152  	for _, coin := range spent {
 153  		out = appendCompactSize(out, len(coin.Script))
 154  		out = append(out, coin.Script...)
 155  	}
 156  
 157  	return out
 158  }
 159  
 160  func serializeSequences(inputs []Input) []byte {
 161  	out := make([]byte, 0, 4*len(inputs))
 162  
 163  	for _, input := range inputs {
 164  		out = binary.LittleEndian.AppendUint32(out, input.Sequence)
 165  	}
 166  
 167  	return out
 168  }
 169  
 170  func serializeOutputs(outputs []Output) []byte {
 171  	out := make([]byte, 0, 34*len(outputs))
 172  
 173  	for _, output := range outputs {
 174  		out = binary.LittleEndian.AppendUint64(out, output.Value)
 175  		out = appendCompactSize(out, len(output.Script))
 176  		out = append(out, output.Script...)
 177  	}
 178  
 179  	return out
 180  }
 181  
 182  // taggedHash is BIP340's tagged hash.
 183  func taggedHash(tag string, message []byte) [32]byte {
 184  	tagHash := sha256.Sum256([]byte(tag))
 185  
 186  	h := sha256.New()
 187  	h.Write(tagHash[:])
 188  	h.Write(tagHash[:])
 189  	h.Write(message)
 190  
 191  	var out [32]byte
 192  
 193  	copy(out[:], h.Sum(nil))
 194  
 195  	return out
 196  }
 197  
 198  // ErrUnifiedUnavailable is a chain where the fork is not scheduled, so the node
 199  // would refuse an opted-in signature.
 200  var ErrUnifiedUnavailable = errors.New("tx: the unified signature hash is not active on this chain")
 201