package domain import ( "crypto/sha256" "encoding/hex" "testing" ) // The same vector pkg/script pins to the node: the witness script and the address a regtest // node compiled for these terms. The domain must produce them without a node in the loop. const ( deriveClaimer = "03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd" deriveRefunder = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" deriveHash = "0000000000000000000000000000000000000000000000000000000000000001" deriveLocktime = 500 deriveScript = "632103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdad82012088a820" + "0000000000000000000000000000000000000000000000000000000000000001876702f401b169210279be66" + "7ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac68" deriveAddress = "bcrt1qvsxuue8tp8gnfw02ynzxv5ns4ecpp8k4kjrx7eav02qv3jgad7tqzur2fy" ) // TestDeriveHTLCMatchesTheNode: the wallet derives the contract the node compiled, from the // terms alone, with no descriptor compiler and no node. func TestDeriveHTLCMatchesTheNode(t *testing.T) { dom, _ := signDomain(t) claimer, err := hex.DecodeString(deriveClaimer) if err != nil { t.Fatal(err) } refunder, err := hex.DecodeString(deriveRefunder) if err != nil { t.Fatal(err) } raw, err := hex.DecodeString(deriveHash) if err != nil { t.Fatal(err) } var secretHash [32]byte copy(secretHash[:], raw) address, witness, program, err := dom.DeriveHTLC("btc", claimer, refunder, secretHash, deriveLocktime) if err != nil { t.Fatalf("DeriveHTLC: %v", err) } if got := hex.EncodeToString(witness); got != deriveScript { t.Fatalf("the script is\n%s\nwant\n%s", got, deriveScript) } if address != deriveAddress { t.Fatalf("the address is %s, want %s", address, deriveAddress) } if hex.EncodeToString(program[:]) == "" || program == ([32]byte{}) { t.Fatal("the program is empty") } // The program is the SHA-256 of the script, which is what the address encodes. if want := sha256Of(witness); program != want { t.Fatalf("the program is %x, want %x", program, want) } } // TestDeriveHTLCRefusesNonsense: the terms are a contract, not a suggestion. func TestDeriveHTLCRefusesNonsense(t *testing.T) { dom, _ := signDomain(t) claimer, _ := hex.DecodeString(deriveClaimer) refunder, _ := hex.DecodeString(deriveRefunder) var secretHash [32]byte if _, _, _, err := dom.DeriveHTLC("btc", claimer[:32], refunder, secretHash, 500); err == nil { t.Fatal("a 32-byte claimer key was accepted") } if _, _, _, err := dom.DeriveHTLC("btc", claimer, refunder, secretHash, 0); err == nil { t.Fatal("a zero locktime was accepted") } if _, _, _, err := dom.DeriveHTLC("blake", claimer, refunder, secretHash, 500); err == nil { t.Fatal("a chain the wallet does not drive was accepted") } } // sha256Of is the hash the P2WSH program is built from. func sha256Of(raw []byte) [32]byte { sum := sha256.Sum256(raw) return sum }