unified_test.go raw

   1  package tx
   2  
   3  import (
   4  	"bytes"
   5  	"encoding/hex"
   6  	"encoding/json"
   7  	"os"
   8  	"testing"
   9  
  10  	"github.com/btcsuite/btcd/btcec/v2"
  11  	btcecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
  12  )
  13  
  14  // The node's own vectors live in the Knots checkout. The test skips when the
  15  // checkout is absent; when it is there, the digest must match byte for byte.
  16  const vectorPath = "/home/mleku/s/bitcoinknots/bitcoin/src/test/data/unified_sighash.json"
  17  
  18  type vector struct {
  19  	ScriptCode   string   `json:"scriptCode"`
  20  	RawTx        string   `json:"rawTx"`
  21  	InIdx        int      `json:"inIdx"`
  22  	HashType     uint32   `json:"hashType"`
  23  	ScriptType   uint32   `json:"scriptType"`
  24  	SpentOutputs [][2]any `json:"spentOutputs"`
  25  	Sighash      string   `json:"sighash"`
  26  }
  27  
  28  func TestSighashUnifiedMatchesNodeVector(t *testing.T) {
  29  	raw, err := os.ReadFile(vectorPath)
  30  	if err != nil {
  31  		t.Skipf("node vectors not present: %v", err)
  32  	}
  33  
  34  	var vectors []json.RawMessage
  35  	if err := json.Unmarshal(raw, &vectors); err != nil {
  36  		t.Fatal(err)
  37  	}
  38  
  39  	var checked int
  40  
  41  	for i, item := range vectors {
  42  		var row []any
  43  		if err := json.Unmarshal(item, &row); err != nil || len(row) != 7 {
  44  			continue
  45  		}
  46  
  47  		hashType, ok := row[3].(float64)
  48  		if !ok || uint32(hashType) != 33 && uint32(hashType) != 161 {
  49  			continue
  50  		}
  51  
  52  		scriptType, ok := row[4].(float64)
  53  		if !ok || uint32(scriptType) != 1 {
  54  			continue
  55  		}
  56  
  57  		scriptCode, err := hex.DecodeString(row[0].(string))
  58  		if err != nil {
  59  			t.Fatalf("vector %d scriptCode: %v", i, err)
  60  		}
  61  
  62  		rawTx, err := hex.DecodeString(row[1].(string))
  63  		if err != nil {
  64  			t.Fatalf("vector %d rawTx: %v", i, err)
  65  		}
  66  
  67  		transaction, err := Decode(rawTx)
  68  		if err != nil {
  69  			t.Fatalf("vector %d decode: %v", i, err)
  70  		}
  71  
  72  		spentRaw := row[5].([]any)
  73  		spent := make([]SpentOutput, 0, len(spentRaw))
  74  
  75  		for _, entry := range spentRaw {
  76  			pair := entry.([]any)
  77  			value := uint64(pair[0].(float64))
  78  			script, err := hex.DecodeString(pair[1].(string))
  79  			if err != nil {
  80  				t.Fatalf("vector %d spent script: %v", i, err)
  81  			}
  82  			spent = append(spent, SpentOutput{Value: value, Script: script})
  83  		}
  84  
  85  		digest, err := transaction.SighashUnifiedV0(
  86  			int(row[2].(float64)), scriptCode, spent, uint32(hashType),
  87  		)
  88  		if err != nil {
  89  			t.Fatalf("vector %d: %v", i, err)
  90  		}
  91  
  92  		want, _ := hex.DecodeString(row[6].(string))
  93  
  94  		if hex.EncodeToString(digest[:]) != hex.EncodeToString(want) {
  95  			t.Fatalf("vector %d: got %x want %x", i, digest, want)
  96  		}
  97  
  98  		checked++
  99  	}
 100  
 101  	if checked == 0 {
 102  		t.Skip("no segwit v0 ALL|UNIFIED vectors found")
 103  	}
 104  }
 105  
 106  func TestSighashUnifiedCommitsToEverySpentOutput(t *testing.T) {
 107  	transaction := New()
 108  	transaction.AddInput(Outpoint{Hash: [32]byte{1}, Index: 0}, SequenceFinal)
 109  	transaction.AddInput(Outpoint{Hash: [32]byte{2}, Index: 1}, SequenceFinal)
 110  	transaction.AddOutput(1000, []byte{0x51})
 111  
 112  	spent := []SpentOutput{
 113  		{Value: 2000, Script: []byte{0x51}},
 114  		{Value: 3000, Script: []byte{0x52}},
 115  	}
 116  
 117  	first, err := transaction.SighashUnifiedV0(0, []byte{0x51}, spent, SighashAllUnified)
 118  	if err != nil {
 119  		t.Fatal(err)
 120  	}
 121  
 122  	changed := []SpentOutput{
 123  		{Value: 2000, Script: []byte{0x51}},
 124  		{Value: 3001, Script: []byte{0x52}},
 125  	}
 126  
 127  	second, err := transaction.SighashUnifiedV0(0, []byte{0x51}, changed, SighashAllUnified)
 128  	if err != nil {
 129  		t.Fatal(err)
 130  	}
 131  
 132  	if first == second {
 133  		t.Fatal("the digest did not commit to the other input's value")
 134  	}
 135  
 136  	if _, err := transaction.SighashUnifiedV0(0, []byte{0x51}, spent[:1], SighashAllUnified); err == nil {
 137  		t.Fatal("a digest accepted a missing spent output")
 138  	}
 139  }
 140  
 141  func TestSignP2WPKHUnifiedUsesTheUnifiedDigest(t *testing.T) {
 142  	secret := bytes.Repeat([]byte{0x11}, 32)
 143  	program := [20]byte{1, 2, 3}
 144  	script := append([]byte{0x00, 0x14}, program[:]...)
 145  
 146  	transaction := New()
 147  	transaction.AddInput(Outpoint{Hash: [32]byte{1}, Index: 0}, SequenceFinal)
 148  	transaction.AddInput(Outpoint{Hash: [32]byte{2}, Index: 1}, SequenceFinal)
 149  	transaction.AddOutput(40_000, []byte{0x51})
 150  
 151  	spent := []SpentOutput{
 152  		{Value: 50_000, Script: script},
 153  		{Value: 60_000, Script: []byte{0x51}},
 154  	}
 155  
 156  	if err := SignP2WPKHUnified(transaction, 0, secret, program, spent); err != nil {
 157  		t.Fatal(err)
 158  	}
 159  
 160  	witness := transaction.Inputs[0].Witness
 161  	if len(witness) != 2 {
 162  		t.Fatalf("witness has %d items", len(witness))
 163  	}
 164  
 165  	der, hashType := witness[0][:len(witness[0])-1], witness[0][len(witness[0])-1]
 166  	if hashType != byte(SighashAllUnified) {
 167  		t.Fatalf("hash type %#x, want %#x", hashType, byte(SighashAllUnified))
 168  	}
 169  
 170  	digest, err := transaction.SighashUnifiedV0(0, P2WPKHScriptCode(program), spent, SighashAllUnified)
 171  	if err != nil {
 172  		t.Fatal(err)
 173  	}
 174  
 175  	signature, err := btcecdsa.ParseDERSignature(der)
 176  	if err != nil {
 177  		t.Fatal(err)
 178  	}
 179  
 180  	pubkey, err := btcec.ParsePubKey(witness[1])
 181  	if err != nil {
 182  		t.Fatal(err)
 183  	}
 184  
 185  	if !signature.Verify(digest[:], pubkey) {
 186  		t.Fatal("the unified signature does not verify over the unified digest")
 187  	}
 188  
 189  	// A BIP143 digest over the same input must not verify: the two messages are
 190  	// different, and that is the replay separation.
 191  	legacy, err := transaction.SighashV0(0, P2WPKHScriptCode(program), spent[0].Value, SighashAll)
 192  	if err != nil {
 193  		t.Fatal(err)
 194  	}
 195  
 196  	if signature.Verify(legacy[:], pubkey) {
 197  		t.Fatal("the unified signature verified over the legacy digest")
 198  	}
 199  }
 200  
 201  func TestSignHTLCRefundUnified(t *testing.T) {
 202  	secret := bytes.Repeat([]byte{0x22}, 32)
 203  	witnessScript := []byte{0x51, 0x52}
 204  
 205  	transaction := New()
 206  	transaction.AddInput(Outpoint{Hash: [32]byte{3}, Index: 0}, 0xfffffffe)
 207  	transaction.AddOutput(40_000, []byte{0x51})
 208  
 209  	spent := []SpentOutput{{Value: 50_000, Script: append([]byte{0x00, 0x20}, bytes.Repeat([]byte{0x33}, 32)...)}}
 210  
 211  	if err := SignHTLCRefundUnified(transaction, 0, secret, witnessScript, spent); err != nil {
 212  		t.Fatal(err)
 213  	}
 214  
 215  	witness := transaction.Inputs[0].Witness
 216  	if len(witness) != 3 || len(witness[0]) == 0 || witness[0][len(witness[0])-1] != byte(SighashAllUnified) {
 217  		t.Fatalf("unified refund witness = %d items, type %#x", len(witness), witness[0][len(witness[0])-1])
 218  	}
 219  }
 220  
 221  func TestSignHTLCClaimUnified(t *testing.T) {
 222  	secret := bytes.Repeat([]byte{0x33}, 32)
 223  	witnessScript := []byte{0x51, 0x52}
 224  	preimage := bytes.Repeat([]byte{0x44}, 32)
 225  
 226  	transaction := New()
 227  	transaction.AddInput(Outpoint{Hash: [32]byte{6}, Index: 0}, 0xfffffffe)
 228  	transaction.AddOutput(40_000, []byte{0x51})
 229  
 230  	spent := []SpentOutput{{Value: 50_000, Script: append([]byte{0x00, 0x20}, bytes.Repeat([]byte{0x55}, 32)...)}}
 231  
 232  	if err := SignHTLCClaimUnified(transaction, 0, secret, witnessScript, preimage, spent); err != nil {
 233  		t.Fatal(err)
 234  	}
 235  
 236  	witness := transaction.Inputs[0].Witness
 237  	if len(witness) != 4 || !bytes.Equal(witness[0], preimage) || witness[1][len(witness[1])-1] != byte(SighashAllUnified) {
 238  		t.Fatalf("unified claim witness = %d items", len(witness))
 239  	}
 240  }
 241