terms.go raw

   1  package verify
   2  
   3  import (
   4  	"bytes"
   5  	"crypto/sha256"
   6  	"errors"
   7  	"fmt"
   8  
   9  	"git.smesh.lol/tinywallet/pkg/script"
  10  	"git.smesh.lol/tinywallet/pkg/tx"
  11  )
  12  
  13  // Terms is what the two sides signed. Every check here compares a transaction with this, not with
  14  // validity in the abstract: a transaction can be perfectly valid and still not be the swap that
  15  // was agreed.
  16  type Terms struct {
  17  	// HashLock is the secret hash both legs must use. It is one value, not one per leg: a swap
  18  	// with two hashlocks is two swaps.
  19  	HashLock [32]byte
  20  	// Timeouts are the absolute locktimes of the refund paths, one per chain.
  21  	TimeoutBTC uint32
  22  	TimeoutXBT uint32
  23  	// Amounts are what each side locks, in satoshis.
  24  	AmountBTC uint64
  25  	AmountXBT uint64
  26  	// Fees are what each side pays out of its locked amount.
  27  	FeeBTC uint64
  28  	FeeXBT uint64
  29  	// The four pubkeys the HTLC scripts commit to.
  30  	ClaimerBTC  []byte
  31  	RefunderBTC []byte
  32  	ClaimerXBT  []byte
  33  	RefunderXBT []byte
  34  	// MinTimeoutGap is the smallest difference the parties accept between the two refund
  35  	// deadlines. Too small a gap lets the party who can claim do so after the other side's
  36  	// refund already landed.
  37  	MinTimeoutGap uint32
  38  }
  39  
  40  // Leg is one chain's half of the swap, as the counterparty supplied it.
  41  type Leg struct {
  42  	// Chain is "btc" or "xbt".
  43  	Chain string
  44  	// Funding creates the HTLC output; Refund and Claim spend it.
  45  	Funding []byte
  46  	Refund  []byte
  47  	Claim   []byte
  48  	// Timeout, Amount and Fee as supplied with the leg; they must match the signed terms.
  49  	Timeout uint32
  50  	Amount  uint64
  51  	Fee     uint64
  52  	// HashLock as supplied; it must equal the terms'.
  53  	HashLock [32]byte
  54  	// Claimer and Refunder as supplied; they must equal the terms'.
  55  	Claimer  []byte
  56  	Refunder []byte
  57  	// ChangeScripts are the scripts the funding side may pay change to. Anything else is a
  58  	// hidden output.
  59  	ChangeScripts [][]byte
  60  }
  61  
  62  // HTLCScript rebuilds the script the terms require.
  63  func (t Terms) HTLCScript(chain string) ([]byte, error) {
  64  	switch chain {
  65  	case "btc":
  66  		return script.HTLC(t.ClaimerBTC, t.RefunderBTC, t.HashLock, t.TimeoutBTC)
  67  	case "xbt":
  68  		return script.HTLC(t.ClaimerXBT, t.RefunderXBT, t.HashLock, t.TimeoutXBT)
  69  	}
  70  
  71  	return nil, fmt.Errorf("verify: unknown chain %q", chain)
  72  }
  73  
  74  func (t Terms) timeoutFor(chain string) uint32 {
  75  	if chain == "xbt" {
  76  		return t.TimeoutXBT
  77  	}
  78  
  79  	return t.TimeoutBTC
  80  }
  81  
  82  func (t Terms) amountFor(chain string) uint64 {
  83  	if chain == "xbt" {
  84  		return t.AmountXBT
  85  	}
  86  
  87  	return t.AmountBTC
  88  }
  89  
  90  func (t Terms) feeFor(chain string) uint64 {
  91  	if chain == "xbt" {
  92  		return t.FeeXBT
  93  	}
  94  
  95  	return t.FeeBTC
  96  }
  97  
  98  // Verify runs every commitment check and records each one, pass or fail, on the report.
  99  func (t Terms) Verify(r *Report, legs []Leg) {
 100  	r.Local("hashlock_is_one_value", "both legs commit to the same secret hash",
 101  		t.checkHashLock(legs))
 102  	r.Local("timeout_asymmetry", "the refund deadlines differ by at least the agreed gap",
 103  		t.checkAsymmetry())
 104  
 105  	for _, leg := range legs {
 106  		t.verifyLeg(r, leg)
 107  	}
 108  }
 109  
 110  func (t Terms) checkHashLock(legs []Leg) error {
 111  	for _, leg := range legs {
 112  		if leg.HashLock != t.HashLock {
 113  			return fmt.Errorf("leg %s commits to %s, terms say %s", leg.Chain,
 114  				Hash(leg.HashLock), Hash(t.HashLock))
 115  		}
 116  	}
 117  
 118  	return nil
 119  }
 120  
 121  func (t Terms) checkAsymmetry() error {
 122  	var a, b uint32
 123  
 124  	for _, timeout := range []uint32{t.TimeoutBTC, t.TimeoutXBT} {
 125  		if timeout == 0 {
 126  			return errors.New("a timeout is zero")
 127  		}
 128  
 129  		if a == 0 {
 130  			a = timeout
 131  			continue
 132  		}
 133  
 134  		b = timeout
 135  	}
 136  
 137  	if a == 0 || b == 0 {
 138  		return errors.New("one timeout is missing")
 139  	}
 140  
 141  	gap := a - b
 142  
 143  	if b > a {
 144  		gap = b - a
 145  	}
 146  
 147  	if gap < t.MinTimeoutGap {
 148  		return fmt.Errorf("the refund deadlines differ by %d blocks, less than %d", gap, t.MinTimeoutGap)
 149  	}
 150  
 151  	return nil
 152  }
 153  
 154  func (t Terms) verifyLeg(r *Report, leg Leg) {
 155  	prefix := leg.Chain + "_"
 156  	want, err := t.HTLCScript(leg.Chain)
 157  	r.Local(prefix+"htlc_script", "the HTLC script is rebuilt from the terms, not trusted", err)
 158  
 159  	if err != nil {
 160  		return
 161  	}
 162  
 163  	// The leg's own numbers must be the terms' numbers before anything is decoded.
 164  	r.Local(prefix+"timeout_matches_terms", "the leg's locktime equals the signed timeout",
 165  		diff("timeout", leg.Timeout, t.timeoutFor(leg.Chain)))
 166  	r.Local(prefix+"amount_matches_terms", "the locked amount equals the signed amount",
 167  		diff64("amount", leg.Amount, t.amountFor(leg.Chain)))
 168  	r.Local(prefix+"fee_matches_terms", "the fee equals the signed fee",
 169  		diff64("fee", leg.Fee, t.feeFor(leg.Chain)))
 170  	r.Local(prefix+"keys_match_terms", "the leg's keys are the signed keys", keysMatch(t, leg))
 171  
 172  	funding, err := tx.Decode(leg.Funding)
 173  	r.Local(prefix+"funding_decodes", "the funding transaction decodes", err)
 174  
 175  	if err != nil {
 176  		return
 177  	}
 178  
 179  	t.checkFunding(r, leg, want, funding)
 180  
 181  	refund, err := tx.Decode(leg.Refund)
 182  	r.Local(prefix+"refund_decodes", "the refund transaction decodes", err)
 183  
 184  	if err == nil {
 185  		t.checkRefund(r, leg, refund)
 186  	}
 187  
 188  	claim, err := tx.Decode(leg.Claim)
 189  	r.Local(prefix+"claim_decodes", "the claim transaction decodes", err)
 190  
 191  	if err == nil {
 192  		t.checkClaim(r, leg, claim)
 193  	}
 194  }
 195  
 196  func (t Terms) checkFunding(r *Report, leg Leg, want []byte, funding *tx.Tx) {
 197  	prefix := leg.Chain + "_"
 198  
 199  	var htlc *tx.Output
 200  	hidden := 0
 201  
 202  	for i := range funding.Outputs {
 203  		out := &funding.Outputs[i]
 204  
 205  		switch {
 206  		case bytes.Equal(out.Script, want):
 207  			htlc = out
 208  		case isChange(out.Script, leg.ChangeScripts):
 209  		default:
 210  			hidden++
 211  		}
 212  	}
 213  
 214  	status := "the funding transaction has one HTLC output"
 215  
 216  	if htlc == nil {
 217  		r.LocalFail(prefix+"funding_htlc_output", status+": it has none")
 218  	} else {
 219  		r.Local(prefix+"funding_htlc_output", status, nil)
 220  	}
 221  
 222  	if hidden > 0 {
 223  		r.LocalFail(prefix+"no_hidden_outputs", fmt.Sprintf(
 224  			"the funding transaction has %d output(s) that are neither the HTLC nor declared change", hidden))
 225  	} else {
 226  		r.Local(prefix+"no_hidden_outputs", "every output is the HTLC or declared change", nil)
 227  	}
 228  
 229  	if htlc != nil && htlc.Value < leg.Amount {
 230  		r.LocalFail(prefix+"funding_amount", fmt.Sprintf(
 231  			"the HTLC output holds %d sat, less than the agreed %d", htlc.Value, leg.Amount))
 232  	} else if htlc != nil {
 233  		r.Local(prefix+"funding_amount", "the HTLC output holds at least the agreed amount", nil)
 234  	}
 235  }
 236  
 237  func (t Terms) checkRefund(r *Report, leg Leg, refund *tx.Tx) {
 238  	prefix := leg.Chain + "_"
 239  
 240  	// A refund that cannot use its locktime is not a refund path at all.
 241  	if refund.LockTime != leg.Timeout {
 242  		r.LocalFail(prefix+"refund_locktime", fmt.Sprintf(
 243  			"the refund's locktime is %d, the agreed timeout is %d", refund.LockTime, leg.Timeout))
 244  	} else {
 245  		r.Local(prefix+"refund_locktime", "the refund's locktime is the agreed timeout", nil)
 246  	}
 247  
 248  	enabled := false
 249  
 250  	for _, in := range refund.Inputs {
 251  		if in.Sequence != tx.SequenceFinal {
 252  			enabled = true
 253  		}
 254  	}
 255  
 256  	if !enabled {
 257  		r.LocalFail(prefix+"refund_locktime_enabled",
 258  			"every refund input is final, so the locktime cannot take effect")
 259  	} else {
 260  		r.Local(prefix+"refund_locktime_enabled", "the refund's sequence enables its locktime", nil)
 261  	}
 262  
 263  	if len(refund.Outputs) == 0 {
 264  		r.LocalFail(prefix+"refund_output", "the refund pays nothing")
 265  
 266  		return
 267  	}
 268  
 269  	wantValue := leg.Amount - leg.Fee
 270  
 271  	if refund.Outputs[0].Value > wantValue {
 272  		r.LocalFail(prefix+"refund_value", fmt.Sprintf(
 273  			"the refund pays %d sat, more than the agreed %d", refund.Outputs[0].Value, wantValue))
 274  	} else {
 275  		r.Local(prefix+"refund_value", "the refund pays no more than the agreed amount minus fee", nil)
 276  	}
 277  }
 278  
 279  func (t Terms) checkClaim(r *Report, leg Leg, claim *tx.Tx) {
 280  	prefix := leg.Chain + "_"
 281  
 282  	// The claim must reveal the preimage of the agreed hashlock; that reveal is what gives the
 283  	// other side its money back, so a claim that does not match is not this swap's claim.
 284  	matched := false
 285  
 286  	for _, in := range claim.Inputs {
 287  		for _, item := range in.Witness {
 288  			sum := sha256.Sum256(item)
 289  
 290  			if sum == t.HashLock {
 291  				matched = true
 292  			}
 293  		}
 294  	}
 295  
 296  	if !matched {
 297  		r.LocalFail(prefix+"claim_preimage", "no witness item hashes to the agreed hashlock")
 298  	} else {
 299  		r.Local(prefix+"claim_preimage", "the claim reveals the preimage of the agreed hashlock", nil)
 300  	}
 301  
 302  	if len(claim.Outputs) == 0 {
 303  		r.LocalFail(prefix+"claim_output", "the claim pays nothing")
 304  	}
 305  }
 306  
 307  func keysMatch(t Terms, leg Leg) error {
 308  	var claimer, refunder []byte
 309  
 310  	if leg.Chain == "xbt" {
 311  		claimer, refunder = t.ClaimerXBT, t.RefunderXBT
 312  	} else {
 313  		claimer, refunder = t.ClaimerBTC, t.RefunderBTC
 314  	}
 315  
 316  	if !bytes.Equal(claimer, leg.Claimer) {
 317  		return errors.New("the claim key is not the signed key")
 318  	}
 319  
 320  	if !bytes.Equal(refunder, leg.Refunder) {
 321  		return errors.New("the refund key is not the signed key")
 322  	}
 323  
 324  	return nil
 325  }
 326  
 327  func isChange(scriptBytes []byte, allowed [][]byte) bool {
 328  	for _, candidate := range allowed {
 329  		if bytes.Equal(candidate, scriptBytes) {
 330  			return true
 331  		}
 332  	}
 333  
 334  	return false
 335  }
 336  
 337  func diff(name string, got, want uint32) error {
 338  	if got != want {
 339  		return fmt.Errorf("%s is %d, terms say %d", name, got, want)
 340  	}
 341  
 342  	return nil
 343  }
 344  
 345  func diff64(name string, got, want uint64) error {
 346  	if got != want {
 347  		return fmt.Errorf("%s is %d, terms say %d", name, got, want)
 348  	}
 349  
 350  	return nil
 351  }
 352