package verify import ( "bytes" "crypto/sha256" "errors" "fmt" "git.smesh.lol/tinywallet/pkg/script" "git.smesh.lol/tinywallet/pkg/tx" ) // Terms is what the two sides signed. Every check here compares a transaction with this, not with // validity in the abstract: a transaction can be perfectly valid and still not be the swap that // was agreed. type Terms struct { // HashLock is the secret hash both legs must use. It is one value, not one per leg: a swap // with two hashlocks is two swaps. HashLock [32]byte // Timeouts are the absolute locktimes of the refund paths, one per chain. TimeoutBTC uint32 TimeoutXBT uint32 // Amounts are what each side locks, in satoshis. AmountBTC uint64 AmountXBT uint64 // Fees are what each side pays out of its locked amount. FeeBTC uint64 FeeXBT uint64 // The four pubkeys the HTLC scripts commit to. ClaimerBTC []byte RefunderBTC []byte ClaimerXBT []byte RefunderXBT []byte // MinTimeoutGap is the smallest difference the parties accept between the two refund // deadlines. Too small a gap lets the party who can claim do so after the other side's // refund already landed. MinTimeoutGap uint32 } // Leg is one chain's half of the swap, as the counterparty supplied it. type Leg struct { // Chain is "btc" or "xbt". Chain string // Funding creates the HTLC output; Refund and Claim spend it. Funding []byte Refund []byte Claim []byte // Timeout, Amount and Fee as supplied with the leg; they must match the signed terms. Timeout uint32 Amount uint64 Fee uint64 // HashLock as supplied; it must equal the terms'. HashLock [32]byte // Claimer and Refunder as supplied; they must equal the terms'. Claimer []byte Refunder []byte // ChangeScripts are the scripts the funding side may pay change to. Anything else is a // hidden output. ChangeScripts [][]byte } // HTLCScript rebuilds the script the terms require. func (t Terms) HTLCScript(chain string) ([]byte, error) { switch chain { case "btc": return script.HTLC(t.ClaimerBTC, t.RefunderBTC, t.HashLock, t.TimeoutBTC) case "xbt": return script.HTLC(t.ClaimerXBT, t.RefunderXBT, t.HashLock, t.TimeoutXBT) } return nil, fmt.Errorf("verify: unknown chain %q", chain) } func (t Terms) timeoutFor(chain string) uint32 { if chain == "xbt" { return t.TimeoutXBT } return t.TimeoutBTC } func (t Terms) amountFor(chain string) uint64 { if chain == "xbt" { return t.AmountXBT } return t.AmountBTC } func (t Terms) feeFor(chain string) uint64 { if chain == "xbt" { return t.FeeXBT } return t.FeeBTC } // Verify runs every commitment check and records each one, pass or fail, on the report. func (t Terms) Verify(r *Report, legs []Leg) { r.Local("hashlock_is_one_value", "both legs commit to the same secret hash", t.checkHashLock(legs)) r.Local("timeout_asymmetry", "the refund deadlines differ by at least the agreed gap", t.checkAsymmetry()) for _, leg := range legs { t.verifyLeg(r, leg) } } func (t Terms) checkHashLock(legs []Leg) error { for _, leg := range legs { if leg.HashLock != t.HashLock { return fmt.Errorf("leg %s commits to %s, terms say %s", leg.Chain, Hash(leg.HashLock), Hash(t.HashLock)) } } return nil } func (t Terms) checkAsymmetry() error { var a, b uint32 for _, timeout := range []uint32{t.TimeoutBTC, t.TimeoutXBT} { if timeout == 0 { return errors.New("a timeout is zero") } if a == 0 { a = timeout continue } b = timeout } if a == 0 || b == 0 { return errors.New("one timeout is missing") } gap := a - b if b > a { gap = b - a } if gap < t.MinTimeoutGap { return fmt.Errorf("the refund deadlines differ by %d blocks, less than %d", gap, t.MinTimeoutGap) } return nil } func (t Terms) verifyLeg(r *Report, leg Leg) { prefix := leg.Chain + "_" want, err := t.HTLCScript(leg.Chain) r.Local(prefix+"htlc_script", "the HTLC script is rebuilt from the terms, not trusted", err) if err != nil { return } // The leg's own numbers must be the terms' numbers before anything is decoded. r.Local(prefix+"timeout_matches_terms", "the leg's locktime equals the signed timeout", diff("timeout", leg.Timeout, t.timeoutFor(leg.Chain))) r.Local(prefix+"amount_matches_terms", "the locked amount equals the signed amount", diff64("amount", leg.Amount, t.amountFor(leg.Chain))) r.Local(prefix+"fee_matches_terms", "the fee equals the signed fee", diff64("fee", leg.Fee, t.feeFor(leg.Chain))) r.Local(prefix+"keys_match_terms", "the leg's keys are the signed keys", keysMatch(t, leg)) funding, err := tx.Decode(leg.Funding) r.Local(prefix+"funding_decodes", "the funding transaction decodes", err) if err != nil { return } t.checkFunding(r, leg, want, funding) refund, err := tx.Decode(leg.Refund) r.Local(prefix+"refund_decodes", "the refund transaction decodes", err) if err == nil { t.checkRefund(r, leg, refund) } claim, err := tx.Decode(leg.Claim) r.Local(prefix+"claim_decodes", "the claim transaction decodes", err) if err == nil { t.checkClaim(r, leg, claim) } } func (t Terms) checkFunding(r *Report, leg Leg, want []byte, funding *tx.Tx) { prefix := leg.Chain + "_" var htlc *tx.Output hidden := 0 for i := range funding.Outputs { out := &funding.Outputs[i] switch { case bytes.Equal(out.Script, want): htlc = out case isChange(out.Script, leg.ChangeScripts): default: hidden++ } } status := "the funding transaction has one HTLC output" if htlc == nil { r.LocalFail(prefix+"funding_htlc_output", status+": it has none") } else { r.Local(prefix+"funding_htlc_output", status, nil) } if hidden > 0 { r.LocalFail(prefix+"no_hidden_outputs", fmt.Sprintf( "the funding transaction has %d output(s) that are neither the HTLC nor declared change", hidden)) } else { r.Local(prefix+"no_hidden_outputs", "every output is the HTLC or declared change", nil) } if htlc != nil && htlc.Value < leg.Amount { r.LocalFail(prefix+"funding_amount", fmt.Sprintf( "the HTLC output holds %d sat, less than the agreed %d", htlc.Value, leg.Amount)) } else if htlc != nil { r.Local(prefix+"funding_amount", "the HTLC output holds at least the agreed amount", nil) } } func (t Terms) checkRefund(r *Report, leg Leg, refund *tx.Tx) { prefix := leg.Chain + "_" // A refund that cannot use its locktime is not a refund path at all. if refund.LockTime != leg.Timeout { r.LocalFail(prefix+"refund_locktime", fmt.Sprintf( "the refund's locktime is %d, the agreed timeout is %d", refund.LockTime, leg.Timeout)) } else { r.Local(prefix+"refund_locktime", "the refund's locktime is the agreed timeout", nil) } enabled := false for _, in := range refund.Inputs { if in.Sequence != tx.SequenceFinal { enabled = true } } if !enabled { r.LocalFail(prefix+"refund_locktime_enabled", "every refund input is final, so the locktime cannot take effect") } else { r.Local(prefix+"refund_locktime_enabled", "the refund's sequence enables its locktime", nil) } if len(refund.Outputs) == 0 { r.LocalFail(prefix+"refund_output", "the refund pays nothing") return } wantValue := leg.Amount - leg.Fee if refund.Outputs[0].Value > wantValue { r.LocalFail(prefix+"refund_value", fmt.Sprintf( "the refund pays %d sat, more than the agreed %d", refund.Outputs[0].Value, wantValue)) } else { r.Local(prefix+"refund_value", "the refund pays no more than the agreed amount minus fee", nil) } } func (t Terms) checkClaim(r *Report, leg Leg, claim *tx.Tx) { prefix := leg.Chain + "_" // The claim must reveal the preimage of the agreed hashlock; that reveal is what gives the // other side its money back, so a claim that does not match is not this swap's claim. matched := false for _, in := range claim.Inputs { for _, item := range in.Witness { sum := sha256.Sum256(item) if sum == t.HashLock { matched = true } } } if !matched { r.LocalFail(prefix+"claim_preimage", "no witness item hashes to the agreed hashlock") } else { r.Local(prefix+"claim_preimage", "the claim reveals the preimage of the agreed hashlock", nil) } if len(claim.Outputs) == 0 { r.LocalFail(prefix+"claim_output", "the claim pays nothing") } } func keysMatch(t Terms, leg Leg) error { var claimer, refunder []byte if leg.Chain == "xbt" { claimer, refunder = t.ClaimerXBT, t.RefunderXBT } else { claimer, refunder = t.ClaimerBTC, t.RefunderBTC } if !bytes.Equal(claimer, leg.Claimer) { return errors.New("the claim key is not the signed key") } if !bytes.Equal(refunder, leg.Refunder) { return errors.New("the refund key is not the signed key") } return nil } func isChange(scriptBytes []byte, allowed [][]byte) bool { for _, candidate := range allowed { if bytes.Equal(candidate, scriptBytes) { return true } } return false } func diff(name string, got, want uint32) error { if got != want { return fmt.Errorf("%s is %d, terms say %d", name, got, want) } return nil } func diff64(name string, got, want uint64) error { if got != want { return fmt.Errorf("%s is %d, terms say %d", name, got, want) } return nil }