main.go raw

   1  // Command tinywallet-verify decides a swap dossier from the command line.
   2  //
   3  // It is the same code the page runs: a dossier in, a verdict out. It exists so a verdict can be
   4  // reproduced outside a browser, which is what makes it evidence.
   5  package main
   6  
   7  import (
   8  	"context"
   9  	"encoding/hex"
  10  	"encoding/json"
  11  	"flag"
  12  	"fmt"
  13  	"io"
  14  	"net/http"
  15  	"os"
  16  	"time"
  17  
  18  	"git.smesh.lol/tinywallet/pkg/tx"
  19  	"git.smesh.lol/tinywallet/pkg/verify"
  20  )
  21  
  22  func main() {
  23  	path := flag.String("dossier", "-", "dossier JSON file, - for standard input")
  24  	txHex := flag.String("tx", "", "decode one raw transaction and print its facts as JSON")
  25  	presetsFlag := flag.Bool("presets", false, "print the baked indexer presets as JSON")
  26  	probe := flag.Bool("probe", false, "ask every preset for its tip and fee floor, and report agreement")
  27  	fetch := flag.Bool("fetch", false, "fill the dossier's facts from the presets, then decide it")
  28  	need := flag.Int("need", 2, "how many sources must agree")
  29  	flag.Parse()
  30  
  31  	if *presetsFlag {
  32  		body, err := json.MarshalIndent(verify.Presets(), "", "  ")
  33  
  34  		if err != nil {
  35  			fail(err)
  36  		}
  37  
  38  		fmt.Println(string(body))
  39  
  40  		return
  41  	}
  42  
  43  	if *probe {
  44  		probePresets()
  45  
  46  		return
  47  	}
  48  
  49  	if *txHex != "" {
  50  		decode(*txHex)
  51  
  52  		return
  53  	}
  54  
  55  	body, err := read(*path)
  56  
  57  	if err != nil {
  58  		fail(err)
  59  	}
  60  
  61  	if *fetch {
  62  		body, err = fill(body, *need)
  63  
  64  		if err != nil {
  65  			fail(err)
  66  		}
  67  	}
  68  
  69  	out, err := verify.AdjudicateJSON(body)
  70  
  71  	if err != nil {
  72  		fail(err)
  73  	}
  74  
  75  	var report verify.Report
  76  
  77  	if err := json.Unmarshal(out, &report); err != nil {
  78  		fail(err)
  79  	}
  80  
  81  	fmt.Println("verdict:", report.Verdict)
  82  	fmt.Printf("verified by %d of %d independent sources\n", report.Agreement, report.Quorum)
  83  
  84  	failed, unverifiable := report.Unverified()
  85  
  86  	for _, check := range report.Checks {
  87  		mark := "ok"
  88  		if check.Status != verify.Pass {
  89  			mark = string(check.Status)
  90  		}
  91  		fmt.Printf("  [%-6s] %-8s %-32s %s\n", check.Tier, mark, check.Name, check.Detail)
  92  	}
  93  
  94  	fmt.Printf("failed: %d, unverifiable: %d\n", len(failed), len(unverifiable))
  95  
  96  	// Exit non-zero when the gate would refuse, so this can be used in a script.
  97  	if err := report.Gate(); err != nil {
  98  		os.Exit(2)
  99  	}
 100  }
 101  
 102  // decode prints what the verifier's own parser sees in a transaction, in the same vocabulary a
 103  // node's decoderawtransaction uses, so the two can be compared directly.
 104  func decode(text string) {
 105  	raw, err := hex.DecodeString(text)
 106  
 107  	if err != nil {
 108  		fail(err)
 109  	}
 110  
 111  	parsed, err := tx.Decode(raw)
 112  
 113  	if err != nil {
 114  		fail(err)
 115  	}
 116  
 117  	id, err := parsed.TxIDHex()
 118  
 119  	if err != nil {
 120  		fail(err)
 121  	}
 122  
 123  	outputs := make([]map[string]any, 0, len(parsed.Outputs))
 124  
 125  	for _, out := range parsed.Outputs {
 126  		outputs = append(outputs, map[string]any{
 127  			"value": out.Value, "script": hex.EncodeToString(out.Script),
 128  		})
 129  	}
 130  
 131  	sequences := make([]uint32, 0, len(parsed.Inputs))
 132  
 133  	for _, in := range parsed.Inputs {
 134  		sequences = append(sequences, in.Sequence)
 135  	}
 136  
 137  	body, err := json.Marshal(map[string]any{
 138  		"txid": id, "locktime": parsed.LockTime, "sequences": sequences, "outputs": outputs,
 139  	})
 140  
 141  	if err != nil {
 142  		fail(err)
 143  	}
 144  
 145  	fmt.Println(string(body))
 146  }
 147  
 148  // probePresets asks every baked indexer for the two facts that need no transaction, and shows
 149  // whether the Bitcoin sources agree on the head.
 150  func probePresets() {
 151  	client := &http.Client{Timeout: 15 * time.Second}
 152  
 153  	tips := map[string]verify.Tip{}
 154  
 155  	for _, preset := range verify.Presets() {
 156  		adapter, err := verify.AdapterFor(preset, client)
 157  
 158  		if err != nil {
 159  			fmt.Printf("%-16s %-4s error: %v\n", preset.Name, preset.Chain, err)
 160  
 161  			continue
 162  		}
 163  
 164  		ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
 165  		tip, err := adapter.Tip(ctx)
 166  		rate, feeErr := adapter.FeeEstimate(ctx)
 167  		cancel()
 168  
 169  		if err != nil {
 170  			fmt.Printf("%-16s %-4s tip error: %v\n", preset.Name, preset.Chain, err)
 171  
 172  			continue
 173  		}
 174  
 175  		tips[preset.Name] = tip
 176  
 177  		note := ""
 178  
 179  		if feeErr != nil {
 180  			note = " (no fee floor: " + feeErr.Error() + ")"
 181  		}
 182  
 183  		fmt.Printf("%-16s %-4s tip %d %s… fee %d sat/vB%s\n", preset.Name, preset.Chain,
 184  			tip.Height, verify.Hash(tip.Hash)[:16], rate, note)
 185  	}
 186  
 187  	// The Bitcoin sources are compared as one group, because that is the quorum a verdict uses.
 188  	hashes := map[[32]byte]bool{}
 189  
 190  	for name, tip := range tips {
 191  		if len(name) > 0 && (name == "mempool.space" || name == "blockstream.info" ||
 192  			name == "btcscan.org" || name == "mempool.ninja") {
 193  			hashes[tip.Hash] = true
 194  		}
 195  	}
 196  
 197  	// One chain has one tip, so identical hashes are the expected state and not evidence of a
 198  	// shared backend. What the probe reports is simply that the sources agree on the head.
 199  	if len(hashes) == 1 {
 200  		fmt.Println("bitcoin sources agree on the tip (expected on one chain; it is not an independence proof)")
 201  	} else {
 202  		fmt.Printf("bitcoin sources report %d different tip hashes: at least one is behind or on a fork\n", len(hashes))
 203  	}
 204  }
 205  
 206  // fill asks the presets about every transaction the dossier names, and replaces the dossier's
 207  // supplied facts with fetched ones. It is the native path to the same verdict the page renders.
 208  func fill(body []byte, need int) ([]byte, error) {
 209  	var dossier verify.Dossier
 210  
 211  	if err := json.Unmarshal(body, &dossier); err != nil {
 212  		return nil, err
 213  	}
 214  
 215  	client := &http.Client{Timeout: 20 * time.Second}
 216  
 217  	// One adapter per preset, built once.
 218  	type source struct {
 219  		preset  verify.Preset
 220  		adapter verify.Source
 221  	}
 222  
 223  	var sources []source
 224  
 225  	for _, preset := range verify.Presets() {
 226  		adapter, err := verify.AdapterFor(preset, client)
 227  
 228  		if err != nil {
 229  			return nil, err
 230  		}
 231  
 232  		sources = append(sources, source{preset: preset, adapter: adapter})
 233  	}
 234  
 235  	facts := map[string]map[string]verify.FactJSON{}
 236  
 237  	for _, leg := range dossier.Legs {
 238  		for _, text := range []string{leg.Funding, leg.Refund, leg.Claim} {
 239  			raw, err := hex.DecodeString(text)
 240  
 241  			if err != nil {
 242  				return nil, err
 243  			}
 244  
 245  			txid, err := verify.TxidOf(raw)
 246  
 247  			if err != nil {
 248  				return nil, err
 249  			}
 250  
 251  			for _, entry := range sources {
 252  				if entry.preset.Chain != leg.Chain {
 253  					continue
 254  				}
 255  
 256  				ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
 257  				fact, err := entry.adapter.Tx(ctx, txid)
 258  				cancel()
 259  
 260  				if facts[entry.preset.Name] == nil {
 261  					facts[entry.preset.Name] = map[string]verify.FactJSON{}
 262  				}
 263  
 264  				if err != nil {
 265  					// A source that could not answer does not appear for that txid.
 266  					continue
 267  				}
 268  
 269  				facts[entry.preset.Name][verify.Hash(txid)] = verify.FactJSON{
 270  					Found: fact.Found, Hex: hex.EncodeToString(fact.Raw), Height: fact.Height,
 271  				}
 272  			}
 273  		}
 274  	}
 275  
 276  	dossier.Need = need
 277  	dossier.Sources = nil
 278  
 279  	for name, entries := range facts {
 280  		chain := ""
 281  
 282  		for _, preset := range verify.Presets() {
 283  			if preset.Name == name {
 284  				chain = preset.Chain
 285  			}
 286  		}
 287  
 288  		_ = chain
 289  		dossier.Sources = append(dossier.Sources, verify.SourceJSON{Name: name, Facts: entries})
 290  	}
 291  
 292  	return json.Marshal(dossier)
 293  }
 294  
 295  func read(path string) ([]byte, error) {
 296  	if path == "-" {
 297  		return io.ReadAll(os.Stdin)
 298  	}
 299  
 300  	return os.ReadFile(path)
 301  }
 302  
 303  func fail(err error) {
 304  	fmt.Fprintln(os.Stderr, "tinywallet-verify:", err)
 305  	os.Exit(1)
 306  }
 307