differential.py raw

   1  #!/usr/bin/env python3
   2  """Differential: our transaction parser against both rig nodes.
   3  
   4  For each chain: take the tip block, pick a spending transaction, ask the node for its raw bytes and
   5  for its own decoding, ask the verifier's parser for the same facts, and compare txid, locktime,
   6  every input sequence and every output value and script.
   7  
   8  usage: differential.py [path-to-tinywallet-verify]
   9  """
  10  
  11  import base64
  12  import json
  13  import subprocess
  14  import sys
  15  import urllib.error
  16  import urllib.request
  17  
  18  VERIFY = sys.argv[1] if len(sys.argv) > 1 else "/tmp/tinywallet-verify"
  19  
  20  CHAINS = [
  21      ("btc", 18443, "/home/mleku/.blake-swap-test/btc/regtest/.cookie"),
  22      ("blake", 19443, "/home/mleku/.blake-swap-test/blake/regtest/.cookie"),
  23  ]
  24  
  25  
  26  def rpc(port, cookie_path, method, *params):
  27      with open(cookie_path) as handle:
  28          cookie = handle.read().strip()
  29  
  30      body = json.dumps({"jsonrpc": "1.0", "id": 1, "method": method, "params": list(params)}).encode()
  31      request = urllib.request.Request(
  32          f"http://127.0.0.1:{port}/", data=body,
  33          headers={"content-type": "application/json",
  34                   "authorization": "Basic " + base64.b64encode(cookie.encode()).decode()})
  35      try:
  36          answer = json.loads(urllib.request.urlopen(request, timeout=20).read())
  37      except urllib.error.HTTPError as err:
  38          raise RuntimeError(f"{method}: {err.read().decode()[:200]}")
  39  
  40      if answer.get("error"):
  41          raise RuntimeError(f"{method}: {answer['error']}")
  42  
  43      return answer["result"]
  44  
  45  
  46  def main():
  47      failures = 0
  48  
  49      for name, port, cookie in CHAINS:
  50          tip = rpc(port, cookie, "getbestblockhash")
  51          block = rpc(port, cookie, "getblock", tip, 2)
  52  
  53          txs = block["tx"] if isinstance(block["tx"], list) else []
  54  
  55          if not txs:
  56              print(name, "tip block has no transactions to compare")
  57              failures += 1
  58              continue
  59  
  60          chosen = next((t for t in txs if not t["vin"][0].get("coinbase")), txs[0])
  61          txid = chosen["txid"]
  62          raw = rpc(port, cookie, "getrawtransaction", txid, 0, tip)
  63          ours = json.loads(subprocess.run([VERIFY, "-tx", raw], capture_output=True,
  64                                           text=True, check=True).stdout)
  65          theirs = rpc(port, cookie, "decoderawtransaction", raw)
  66  
  67          checks = {
  68              "txid": ours["txid"] == theirs["txid"],
  69              "locktime": ours["locktime"] == theirs["locktime"],
  70              "sequences": ours["sequences"] == [v["sequence"] for v in theirs["vin"]],
  71              "values": [o["value"] for o in ours["outputs"]] ==
  72                        [int(round(v["value"] * 1e8)) for v in theirs["vout"]],
  73              "scripts": [o["script"] for o in ours["outputs"]] ==
  74                         [v["scriptPubKey"]["hex"] for v in theirs["vout"]],
  75          }
  76  
  77          bad = [label for label, ok in checks.items() if not ok]
  78          print(f"{name}: block {block['height']} tx {txid[:16]}… outputs={len(ours['outputs'])} "
  79                f"inputs={len(ours['sequences'])} " + ("match" if not bad else "MISMATCH: " + ", ".join(bad)))
  80          failures += len(bad)
  81  
  82      print("failures:", failures)
  83      return 1 if failures else 0
  84  
  85  
  86  sys.exit(main())
  87