feature_taproot.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2019-2022 The Limenka developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  # Test Taproot softfork (BIPs 340-342)
   6  
   7  from test_framework.blocktools import (
   8      COINBASE_MATURITY,
   9      create_coinbase,
  10      create_block,
  11      add_witness_commitment,
  12      MAX_BLOCK_SIGOPS_WEIGHT,
  13  )
  14  from test_framework.messages import (
  15      COutPoint,
  16      CTransaction,
  17      CTxIn,
  18      CTxInWitness,
  19      CTxOut,
  20      SEQUENCE_FINAL,
  21      tx_from_hex,
  22      WITNESS_SCALE_FACTOR,
  23  )
  24  from test_framework.script import (
  25      ANNEX_TAG,
  26      BIP341_sha_amounts,
  27      BIP341_sha_outputs,
  28      BIP341_sha_prevouts,
  29      BIP341_sha_scriptpubkeys,
  30      BIP341_sha_sequences,
  31      CScript,
  32      CScriptNum,
  33      CScriptOp,
  34      hash256,
  35      LEAF_VERSION_TAPSCRIPT,
  36      LegacySignatureMsg,
  37      LOCKTIME_THRESHOLD,
  38      MAX_SCRIPT_ELEMENT_SIZE,
  39      OP_0,
  40      OP_1,
  41      OP_2,
  42      OP_3,
  43      OP_4,
  44      OP_5,
  45      OP_6,
  46      OP_7,
  47      OP_8,
  48      OP_9,
  49      OP_10,
  50      OP_11,
  51      OP_12,
  52      OP_16,
  53      OP_2DROP,
  54      OP_2DUP,
  55      OP_CHECKMULTISIG,
  56      OP_CHECKMULTISIGVERIFY,
  57      OP_CHECKSIG,
  58      OP_CHECKSIGADD,
  59      OP_CHECKSIGVERIFY,
  60      OP_CODESEPARATOR,
  61      OP_DROP,
  62      OP_DUP,
  63      OP_ELSE,
  64      OP_ENDIF,
  65      OP_EQUAL,
  66      OP_EQUALVERIFY,
  67      OP_IF,
  68      OP_NOP,
  69      OP_NOT,
  70      OP_NOTIF,
  71      OP_PUSHDATA1,
  72      OP_RETURN,
  73      OP_SWAP,
  74      OP_TUCK,
  75      OP_VERIFY,
  76      SIGHASH_DEFAULT,
  77      SIGHASH_ALL,
  78      SIGHASH_NONE,
  79      SIGHASH_SINGLE,
  80      SIGHASH_ANYONECANPAY,
  81      SegwitV0SignatureMsg,
  82      TaggedHash,
  83      TAPROOT_CONTROL_MAX_NODE_COUNT_REDUCED,
  84      TaprootSignatureMsg,
  85      is_op_success,
  86      taproot_construct,
  87  )
  88  from test_framework.script_util import (
  89      key_to_p2pk_script,
  90      key_to_p2pkh_script,
  91      key_to_p2wpkh_script,
  92      keyhash_to_p2pkh_script,
  93      script_to_p2sh_script,
  94      script_to_p2wsh_script,
  95  )
  96  from test_framework.test_framework import LimenkaTestFramework
  97  from test_framework.util import (
  98      assert_raises_rpc_error,
  99      assert_equal,
 100  )
 101  from test_framework.wallet_util import generate_keypair
 102  from test_framework.key import (
 103      generate_privkey,
 104      compute_xonly_pubkey,
 105      sign_schnorr,
 106      tweak_add_privkey,
 107      ECKey,
 108  )
 109  from test_framework.crypto import secp256k1
 110  from test_framework.address import (
 111      hash160,
 112      program_to_witness,
 113  )
 114  from collections import OrderedDict, namedtuple
 115  import json
 116  import hashlib
 117  import os
 118  import random
 119  
 120  # Whether or not to output generated test vectors, in JSON format.
 121  GEN_TEST_VECTORS = False
 122  
 123  # === Framework for building spending transactions. ===
 124  #
 125  # The computation is represented as a "context" dict, whose entries store potentially-unevaluated expressions that
 126  # refer to lower-level ones. By overwriting these expression, many aspects - both high and low level - of the signing
 127  # process can be overridden.
 128  #
 129  # Specifically, a context object is a dict that maps names to compositions of:
 130  # - values
 131  # - lists of values
 132  # - callables which, when fed the context object as argument, produce any of these
 133  #
 134  # The DEFAULT_CONTEXT object specifies a standard signing process, with many overridable knobs.
 135  #
 136  # The get(ctx, name) function can evaluate a name, and cache its result in the context.
 137  # getter(name) can be used to construct a callable that evaluates name. For example:
 138  #
 139  #   ctx1 = {**DEFAULT_CONTEXT, inputs=[getter("sign"), b'\x01']}
 140  #
 141  # creates a context where the script inputs are a signature plus the bytes 0x01.
 142  #
 143  # override(expr, name1=expr1, name2=expr2, ...) can be used to cause an expression to be evaluated in a selectively
 144  # modified context. For example:
 145  #
 146  #   ctx2 = {**DEFAULT_CONTEXT, sighash=override(default_sighash, hashtype=SIGHASH_DEFAULT)}
 147  #
 148  # creates a context ctx2 where the sighash is modified to use hashtype=SIGHASH_DEFAULT. This differs from
 149  #
 150  #   ctx3 = {**DEFAULT_CONTEXT, hashtype=SIGHASH_DEFAULT}
 151  #
 152  # in that ctx3 will globally use hashtype=SIGHASH_DEFAULT (including in the hashtype byte appended to the signature)
 153  # while ctx2 only uses the modified hashtype inside the sighash calculation.
 154  
 155  def deep_eval(ctx, expr):
 156      """Recursively replace any callables c in expr (including inside lists) with c(ctx)."""
 157      while callable(expr):
 158          expr = expr(ctx)
 159      if isinstance(expr, list):
 160          expr = [deep_eval(ctx, x) for x in expr]
 161      return expr
 162  
 163  # Data type to represent fully-evaluated expressions in a context dict (so we can avoid reevaluating them).
 164  Final = namedtuple("Final", "value")
 165  
 166  def get(ctx, name):
 167      """Evaluate name in context ctx."""
 168      assert name in ctx, "Missing '%s' in context" % name
 169      expr = ctx[name]
 170      if not isinstance(expr, Final):
 171          # Evaluate and cache the result.
 172          expr = Final(deep_eval(ctx, expr))
 173          ctx[name] = expr
 174      return expr.value
 175  
 176  def getter(name, **kwargs):
 177      """Return a callable that evaluates name in its passed context."""
 178      return lambda ctx: get({**ctx, **kwargs}, name)
 179  
 180  def override(expr, **kwargs):
 181      """Return a callable that evaluates expr in a modified context."""
 182      return lambda ctx: deep_eval({**ctx, **kwargs}, expr)
 183  
 184  # === Implementations for the various default expressions in DEFAULT_CONTEXT ===
 185  
 186  def default_hashtype(ctx):
 187      """Default expression for "hashtype": SIGHASH_DEFAULT for taproot, SIGHASH_ALL otherwise."""
 188      mode = get(ctx, "mode")
 189      if mode == "taproot":
 190          return SIGHASH_DEFAULT
 191      else:
 192          return SIGHASH_ALL
 193  
 194  def default_tapleaf(ctx):
 195      """Default expression for "tapleaf": looking up leaf in tap[2]."""
 196      return get(ctx, "tap").leaves[get(ctx, "leaf")]
 197  
 198  def default_script_taproot(ctx):
 199      """Default expression for "script_taproot": tapleaf.script."""
 200      return get(ctx, "tapleaf").script
 201  
 202  def default_leafversion(ctx):
 203      """Default expression for "leafversion": tapleaf.version"""
 204      return get(ctx, "tapleaf").version
 205  
 206  def default_negflag(ctx):
 207      """Default expression for "negflag": tap.negflag."""
 208      return get(ctx, "tap").negflag
 209  
 210  def default_pubkey_internal(ctx):
 211      """Default expression for "pubkey_internal": tap.internal_pubkey."""
 212      return get(ctx, "tap").internal_pubkey
 213  
 214  def default_merklebranch(ctx):
 215      """Default expression for "merklebranch": tapleaf.merklebranch."""
 216      return get(ctx, "tapleaf").merklebranch
 217  
 218  def default_controlblock(ctx):
 219      """Default expression for "controlblock": combine leafversion, negflag, pubkey_internal, merklebranch."""
 220      return bytes([get(ctx, "leafversion") + get(ctx, "negflag")]) + get(ctx, "pubkey_internal") + get(ctx, "merklebranch")
 221  
 222  def default_scriptcode_suffix(ctx):
 223      """Default expression for "scriptcode_suffix", the actually used portion of the scriptcode."""
 224      scriptcode = get(ctx, "scriptcode")
 225      codesepnum = get(ctx, "codesepnum")
 226      if codesepnum == -1:
 227          return scriptcode
 228      codeseps = 0
 229      for (opcode, data, sop_idx) in scriptcode.raw_iter():
 230          if opcode == OP_CODESEPARATOR:
 231              if codeseps == codesepnum:
 232                  return CScript(scriptcode[sop_idx+1:])
 233              codeseps += 1
 234      assert False
 235  
 236  def default_sigmsg(ctx):
 237      """Default expression for "sigmsg": depending on mode, compute BIP341, BIP143, or legacy sigmsg."""
 238      tx = get(ctx, "tx")
 239      idx = get(ctx, "idx")
 240      hashtype = get(ctx, "hashtype_actual")
 241      mode = get(ctx, "mode")
 242      if mode == "taproot":
 243          # BIP341 signature hash
 244          utxos = get(ctx, "utxos")
 245          annex = get(ctx, "annex")
 246          if get(ctx, "leaf") is not None:
 247              codeseppos = get(ctx, "codeseppos")
 248              leaf_ver = get(ctx, "leafversion")
 249              script = get(ctx, "script_taproot")
 250              return TaprootSignatureMsg(tx, utxos, hashtype, idx, scriptpath=True, leaf_script=script, leaf_ver=leaf_ver, codeseparator_pos=codeseppos, annex=annex)
 251          else:
 252              return TaprootSignatureMsg(tx, utxos, hashtype, idx, scriptpath=False, annex=annex)
 253      elif mode == "witv0":
 254          # BIP143 signature hash
 255          scriptcode = get(ctx, "scriptcode_suffix")
 256          utxos = get(ctx, "utxos")
 257          return SegwitV0SignatureMsg(scriptcode, tx, idx, hashtype, utxos[idx].nValue)
 258      else:
 259          # Pre-segwit signature hash
 260          scriptcode = get(ctx, "scriptcode_suffix")
 261          return LegacySignatureMsg(scriptcode, tx, idx, hashtype)[0]
 262  
 263  def default_sighash(ctx):
 264      """Default expression for "sighash": depending on mode, compute tagged hash or dsha256 of sigmsg."""
 265      msg = get(ctx, "sigmsg")
 266      mode = get(ctx, "mode")
 267      if mode == "taproot":
 268          return TaggedHash("TapSighash", msg)
 269      else:
 270          if msg is None:
 271              return (1).to_bytes(32, 'little')
 272          else:
 273              return hash256(msg)
 274  
 275  def default_tweak(ctx):
 276      """Default expression for "tweak": None if a leaf is specified, tap[0] otherwise."""
 277      if get(ctx, "leaf") is None:
 278          return get(ctx, "tap").tweak
 279      return None
 280  
 281  def default_key_tweaked(ctx):
 282      """Default expression for "key_tweaked": key if tweak is None, tweaked with it otherwise."""
 283      key = get(ctx, "key")
 284      tweak = get(ctx, "tweak")
 285      if tweak is None:
 286          return key
 287      else:
 288          return tweak_add_privkey(key, tweak)
 289  
 290  def default_signature(ctx):
 291      """Default expression for "signature": BIP340 signature or ECDSA signature depending on mode."""
 292      sighash = get(ctx, "sighash")
 293      deterministic = get(ctx, "deterministic")
 294      if get(ctx, "mode") == "taproot":
 295          key = get(ctx, "key_tweaked")
 296          flip_r = get(ctx, "flag_flip_r")
 297          flip_p = get(ctx, "flag_flip_p")
 298          aux = bytes([0] * 32)
 299          if not deterministic:
 300              aux = random.getrandbits(256).to_bytes(32, 'big')
 301          return sign_schnorr(key, sighash, flip_r=flip_r, flip_p=flip_p, aux=aux)
 302      else:
 303          key = get(ctx, "key")
 304          return key.sign_ecdsa(sighash, rfc6979=deterministic)
 305  
 306  def default_hashtype_actual(ctx):
 307      """Default expression for "hashtype_actual": hashtype, unless mismatching SIGHASH_SINGLE in taproot."""
 308      hashtype = get(ctx, "hashtype")
 309      mode = get(ctx, "mode")
 310      if mode != "taproot":
 311          return hashtype
 312      idx = get(ctx, "idx")
 313      tx = get(ctx, "tx")
 314      if hashtype & 3 == SIGHASH_SINGLE and idx >= len(tx.vout):
 315          return (hashtype & ~3) | SIGHASH_NONE
 316      return hashtype
 317  
 318  def default_bytes_hashtype(ctx):
 319      """Default expression for "bytes_hashtype": bytes([hashtype_actual]) if not 0, b"" otherwise."""
 320      mode = get(ctx, "mode")
 321      hashtype_actual = get(ctx, "hashtype_actual")
 322      if mode != "taproot" or hashtype_actual != 0:
 323          return bytes([hashtype_actual])
 324      else:
 325          return bytes()
 326  
 327  def default_sign(ctx):
 328      """Default expression for "sign": concatenation of signature and bytes_hashtype."""
 329      return get(ctx, "signature") + get(ctx, "bytes_hashtype")
 330  
 331  def default_inputs_keypath(ctx):
 332      """Default expression for "inputs_keypath": a signature."""
 333      return [get(ctx, "sign")]
 334  
 335  def default_witness_taproot(ctx):
 336      """Default expression for "witness_taproot", consisting of inputs, script, control block, and annex as needed."""
 337      annex = get(ctx, "annex")
 338      suffix_annex = []
 339      if annex is not None:
 340          suffix_annex = [annex]
 341      if get(ctx, "leaf") is None:
 342          return get(ctx, "inputs_keypath") + suffix_annex
 343      else:
 344          return get(ctx, "inputs") + [bytes(get(ctx, "script_taproot")), get(ctx, "controlblock")] + suffix_annex
 345  
 346  def default_witness_witv0(ctx):
 347      """Default expression for "witness_witv0", consisting of inputs and witness script, as needed."""
 348      script = get(ctx, "script_witv0")
 349      inputs = get(ctx, "inputs")
 350      if script is None:
 351          return inputs
 352      else:
 353          return inputs + [script]
 354  
 355  def default_witness(ctx):
 356      """Default expression for "witness", delegating to "witness_taproot" or "witness_witv0" as needed."""
 357      mode = get(ctx, "mode")
 358      if mode == "taproot":
 359          return get(ctx, "witness_taproot")
 360      elif mode == "witv0":
 361          return get(ctx, "witness_witv0")
 362      else:
 363          return []
 364  
 365  def default_scriptsig(ctx):
 366      """Default expression for "scriptsig", consisting of inputs and redeemscript, as needed."""
 367      scriptsig = []
 368      mode = get(ctx, "mode")
 369      if mode == "legacy":
 370          scriptsig = get(ctx, "inputs")
 371      redeemscript = get(ctx, "script_p2sh")
 372      if redeemscript is not None:
 373          scriptsig += [bytes(redeemscript)]
 374      return scriptsig
 375  
 376  # The default context object.
 377  DEFAULT_CONTEXT = {
 378      # == The main expressions to evaluate. Only override these for unusual or invalid spends. ==
 379      # The overall witness stack, as a list of bytes objects.
 380      "witness": default_witness,
 381      # The overall scriptsig, as a list of CScript objects (to be concatenated) and bytes objects (to be pushed)
 382      "scriptsig": default_scriptsig,
 383  
 384      # == Expressions you'll generally only override for intentionally invalid spends. ==
 385      # The witness stack for spending a taproot output.
 386      "witness_taproot": default_witness_taproot,
 387      # The witness stack for spending a P2WPKH/P2WSH output.
 388      "witness_witv0": default_witness_witv0,
 389      # The script inputs for a taproot key path spend.
 390      "inputs_keypath": default_inputs_keypath,
 391      # The actual hashtype to use (usually equal to hashtype, but in taproot SIGHASH_SINGLE is not always allowed).
 392      "hashtype_actual": default_hashtype_actual,
 393      # The bytes object for a full signature (including hashtype byte, if needed).
 394      "bytes_hashtype": default_bytes_hashtype,
 395      # A full script signature (bytes including hashtype, if needed)
 396      "sign": default_sign,
 397      # An ECDSA or Schnorr signature (excluding hashtype byte).
 398      "signature": default_signature,
 399      # The 32-byte tweaked key (equal to key for script path spends, or key+tweak for key path spends).
 400      "key_tweaked": default_key_tweaked,
 401      # The tweak to use (None for script path spends, the actual tweak for key path spends).
 402      "tweak": default_tweak,
 403      # The part of the scriptcode after the last executed OP_CODESEPARATOR.
 404      "scriptcode_suffix": default_scriptcode_suffix,
 405      # The sigmsg value (preimage of sighash)
 406      "sigmsg": default_sigmsg,
 407      # The sighash value (32 bytes)
 408      "sighash": default_sighash,
 409      # The information about the chosen script path spend (TaprootLeafInfo object).
 410      "tapleaf": default_tapleaf,
 411      # The script to push, and include in the sighash, for a taproot script path spend.
 412      "script_taproot": default_script_taproot,
 413      # The internal pubkey for a taproot script path spend (32 bytes).
 414      "pubkey_internal": default_pubkey_internal,
 415      # The negation flag of the internal pubkey for a taproot script path spend.
 416      "negflag": default_negflag,
 417      # The leaf version to include in the sighash (this does not affect the one in the control block).
 418      "leafversion": default_leafversion,
 419      # The Merkle path to include in the control block for a script path spend.
 420      "merklebranch": default_merklebranch,
 421      # The control block to push for a taproot script path spend.
 422      "controlblock": default_controlblock,
 423      # Whether to produce signatures with invalid P sign (Schnorr signatures only).
 424      "flag_flip_p": False,
 425      # Whether to produce signatures with invalid R sign (Schnorr signatures only).
 426      "flag_flip_r": False,
 427  
 428      # == Parameters that can be changed without invalidating, but do have a default: ==
 429      # The hashtype (as an integer).
 430      "hashtype": default_hashtype,
 431      # The annex (only when mode=="taproot").
 432      "annex": None,
 433      # The codeseparator position (only when mode=="taproot").
 434      "codeseppos": -1,
 435      # Which OP_CODESEPARATOR is the last executed one in the script (in legacy/P2SH/P2WSH).
 436      "codesepnum": -1,
 437      # The redeemscript to add to the scriptSig (if P2SH; None implies not P2SH).
 438      "script_p2sh": None,
 439      # The script to add to the witness in (if P2WSH; None implies P2WPKH)
 440      "script_witv0": None,
 441      # The leaf to use in taproot spends (if script path spend; None implies key path spend).
 442      "leaf": None,
 443      # The input arguments to provide to the executed script
 444      "inputs": [],
 445      # Use deterministic signing nonces
 446      "deterministic": False,
 447  
 448      # == Parameters to be set before evaluation: ==
 449      # - mode: what spending style to use ("taproot", "witv0", or "legacy").
 450      # - key: the (untweaked) private key to sign with (ECKey object for ECDSA, 32 bytes for Schnorr).
 451      # - tap: the TaprootInfo object (see taproot_construct; needed in mode=="taproot").
 452      # - tx: the transaction to sign.
 453      # - utxos: the UTXOs being spent (needed in mode=="witv0" and mode=="taproot").
 454      # - idx: the input position being signed.
 455      # - scriptcode: the scriptcode to include in legacy and witv0 sighashes.
 456  }
 457  
 458  def flatten(lst):
 459      ret = []
 460      for elem in lst:
 461          if isinstance(elem, list):
 462              ret += flatten(elem)
 463          else:
 464              ret.append(elem)
 465      return ret
 466  
 467  
 468  def spend(tx, idx, utxos, **kwargs):
 469      """Sign transaction input idx of tx, provided utxos is the list of outputs being spent.
 470  
 471      Additional arguments may be provided that override any aspect of the signing process.
 472      See DEFAULT_CONTEXT above for what can be overridden, and what must be provided.
 473      """
 474  
 475      ctx = {**DEFAULT_CONTEXT, "tx":tx, "idx":idx, "utxos":utxos, **kwargs}
 476  
 477      def to_script(elem):
 478          """If fed a CScript, return it; if fed bytes, return a CScript that pushes it."""
 479          if isinstance(elem, CScript):
 480              return elem
 481          else:
 482              return CScript([elem])
 483  
 484      scriptsig_list = flatten(get(ctx, "scriptsig"))
 485      scriptsig = CScript(b"".join(bytes(to_script(elem)) for elem in scriptsig_list))
 486      witness_stack = flatten(get(ctx, "witness"))
 487      return (scriptsig, witness_stack)
 488  
 489  
 490  # === Spender objects ===
 491  #
 492  # Each spender is a tuple of:
 493  # - A scriptPubKey which is to be spent from (CScript)
 494  # - A comment describing the test (string)
 495  # - Whether the spending (on itself) is expected to be standard (bool)
 496  # - A tx-signing lambda returning (scriptsig, witness_stack), taking as inputs:
 497  #   - A transaction to sign (CTransaction)
 498  #   - An input position (int)
 499  #   - The spent UTXOs by this transaction (list of CTxOut)
 500  #   - Whether to produce a valid spend (bool)
 501  # - A string with an expected error message for failure case if known
 502  # - The (pre-taproot) sigops weight consumed by a successful spend
 503  # - Whether this spend cannot fail
 504  # - Whether this test demands being placed in a txin with no corresponding txout (for testing SIGHASH_SINGLE behavior)
 505  
 506  Spender = namedtuple("Spender", "script,comment,is_standard,sat_function,err_msg,sigops_weight,no_fail,need_vin_vout_mismatch")
 507  
 508  
 509  def make_spender(comment, *, tap=None, witv0=False, script=None, pkh=None, p2sh=False, spk_mutate_pre_p2sh=None, failure=None, standard=True, err_msg=None, sigops_weight=0, need_vin_vout_mismatch=False, **kwargs):
 510      """Helper for constructing Spender objects using the context signing framework.
 511  
 512      * tap: a TaprootInfo object (see taproot_construct), for Taproot spends (cannot be combined with pkh, witv0, or script)
 513      * witv0: boolean indicating the use of witness v0 spending (needs one of script or pkh)
 514      * script: the actual script executed (for bare/P2WSH/P2SH spending)
 515      * pkh: the public key for P2PKH or P2WPKH spending
 516      * p2sh: whether the output is P2SH wrapper (this is supported even for Taproot, where it makes the output unencumbered)
 517      * spk_mutate_pre_psh: a callable to be applied to the script (before potentially P2SH-wrapping it)
 518      * failure: a dict of entries to override in the context when intentionally failing to spend (if None, no_fail will be set)
 519      * standard: whether the (valid version of) spending is expected to be standard
 520      * err_msg: a string with an expected error message for failure (or None, if not cared about)
 521      * sigops_weight: the pre-taproot sigops weight consumed by a successful spend
 522      * need_vin_vout_mismatch: whether this test requires being tested in a transaction input that has no corresponding
 523                                transaction output.
 524      """
 525  
 526      conf = dict()
 527  
 528      # Compute scriptPubKey and set useful defaults based on the inputs.
 529      if witv0:
 530          assert tap is None
 531          conf["mode"] = "witv0"
 532          if pkh is not None:
 533              # P2WPKH
 534              assert script is None
 535              pubkeyhash = hash160(pkh)
 536              spk = key_to_p2wpkh_script(pkh)
 537              conf["scriptcode"] = keyhash_to_p2pkh_script(pubkeyhash)
 538              conf["script_witv0"] = None
 539              conf["inputs"] = [getter("sign"), pkh]
 540          elif script is not None:
 541              # P2WSH
 542              spk = script_to_p2wsh_script(script)
 543              conf["scriptcode"] = script
 544              conf["script_witv0"] = script
 545          else:
 546              assert False
 547      elif tap is None:
 548          conf["mode"] = "legacy"
 549          if pkh is not None:
 550              # P2PKH
 551              assert script is None
 552              pubkeyhash = hash160(pkh)
 553              spk = keyhash_to_p2pkh_script(pubkeyhash)
 554              conf["scriptcode"] = spk
 555              conf["inputs"] = [getter("sign"), pkh]
 556          elif script is not None:
 557              # bare
 558              spk = script
 559              conf["scriptcode"] = script
 560          else:
 561              assert False
 562      else:
 563          assert script is None
 564          conf["mode"] = "taproot"
 565          conf["tap"] = tap
 566          spk = tap.scriptPubKey
 567  
 568      if spk_mutate_pre_p2sh is not None:
 569          spk = spk_mutate_pre_p2sh(spk)
 570  
 571      if p2sh:
 572          # P2SH wrapper can be combined with anything else
 573          conf["script_p2sh"] = spk
 574          spk = script_to_p2sh_script(spk)
 575  
 576      conf = {**conf, **kwargs}
 577  
 578      def sat_fn(tx, idx, utxos, valid):
 579          if valid:
 580              return spend(tx, idx, utxos, **conf)
 581          else:
 582              assert failure is not None
 583              return spend(tx, idx, utxos, **{**conf, **failure})
 584  
 585      return Spender(script=spk, comment=comment, is_standard=standard, sat_function=sat_fn, err_msg=err_msg, sigops_weight=sigops_weight, no_fail=failure is None, need_vin_vout_mismatch=need_vin_vout_mismatch)
 586  
 587  def add_spender(spenders, *args, **kwargs):
 588      """Make a spender using make_spender, and add it to spenders."""
 589      spenders.append(make_spender(*args, **kwargs))
 590  
 591  # === Helpers for the test ===
 592  
 593  def random_checksig_style(pubkey):
 594      """Creates a random CHECKSIG* tapscript that would succeed with only the valid signature on witness stack."""
 595      opcode = random.choice([OP_CHECKSIG, OP_CHECKSIGVERIFY, OP_CHECKSIGADD])
 596      if opcode == OP_CHECKSIGVERIFY:
 597          ret = CScript([pubkey, opcode, OP_1])
 598      elif opcode == OP_CHECKSIGADD:
 599          num = random.choice([0, 0x7fffffff, -0x7fffffff])
 600          ret = CScript([num, pubkey, opcode, num + 1, OP_EQUAL])
 601      else:
 602          ret = CScript([pubkey, opcode])
 603      return bytes(ret)
 604  
 605  def bitflipper(expr):
 606      """Return a callable that evaluates expr and returns it with a random bitflip."""
 607      def fn(ctx):
 608          sub = deep_eval(ctx, expr)
 609          assert isinstance(sub, bytes)
 610          return (int.from_bytes(sub, 'little') ^ (1 << random.randrange(len(sub) * 8))).to_bytes(len(sub), 'little')
 611      return fn
 612  
 613  def zero_appender(expr):
 614      """Return a callable that evaluates expr and returns it with a zero added."""
 615      return lambda ctx: deep_eval(ctx, expr) + b"\x00"
 616  
 617  def byte_popper(expr):
 618      """Return a callable that evaluates expr and returns it with its last byte removed."""
 619      return lambda ctx: deep_eval(ctx, expr)[:-1]
 620  
 621  # Expected error strings
 622  
 623  ERR_SIG_SIZE = {"err_msg": "Invalid Schnorr signature size"}
 624  ERR_SIG_HASHTYPE = {"err_msg": "Invalid Schnorr signature hash type"}
 625  ERR_SIG_SCHNORR = {"err_msg": "Invalid Schnorr signature"}
 626  ERR_OP_RETURN = {"err_msg": "OP_RETURN was encountered"}
 627  ERR_CONTROLBLOCK_SIZE = {"err_msg": "Invalid Taproot control block size"}
 628  ERR_WITNESS_PROGRAM_MISMATCH = {"err_msg": "Witness program hash mismatch"}
 629  ERR_PUSH_LIMIT = {"err_msg": "Push value size limit exceeded"}
 630  ERR_DISABLED_OPCODE = {"err_msg": "Attempted to use a disabled opcode"}
 631  ERR_TAPSCRIPT_CHECKMULTISIG = {"err_msg": "OP_CHECKMULTISIG(VERIFY) is not available in tapscript"}
 632  ERR_MINIMALIF = {"err_msg": "OP_IF/NOTIF argument must be minimal in tapscript"}
 633  ERR_UNKNOWN_PUBKEY = {"err_msg": "Public key is neither compressed or uncompressed"}
 634  ERR_STACK_SIZE = {"err_msg": "Stack size limit exceeded"}
 635  ERR_CLEANSTACK = {"err_msg": "Stack size must be exactly one after execution"}
 636  ERR_STACK_EMPTY = {"err_msg": "Operation not valid with the current stack size"}
 637  ERR_SIGOPS_RATIO = {"err_msg": "Too much signature validation relative to witness weight"}
 638  ERR_UNDECODABLE = {"err_msg": "Opcode missing or not understood"}
 639  ERR_NO_SUCCESS = {"err_msg": "Script evaluated without error but finished with a false/empty top stack element"}
 640  ERR_EMPTY_WITNESS = {"err_msg": "Witness program was passed an empty witness"}
 641  ERR_CHECKSIGVERIFY = {"err_msg": "Script failed an OP_CHECKSIGVERIFY operation"}
 642  
 643  VALID_SIGHASHES_ECDSA = [
 644      SIGHASH_ALL,
 645      SIGHASH_NONE,
 646      SIGHASH_SINGLE,
 647      SIGHASH_ANYONECANPAY + SIGHASH_ALL,
 648      SIGHASH_ANYONECANPAY + SIGHASH_NONE,
 649      SIGHASH_ANYONECANPAY + SIGHASH_SINGLE
 650  ]
 651  
 652  VALID_SIGHASHES_TAPROOT = [SIGHASH_DEFAULT] + VALID_SIGHASHES_ECDSA
 653  
 654  VALID_SIGHASHES_TAPROOT_SINGLE = [
 655      SIGHASH_SINGLE,
 656      SIGHASH_ANYONECANPAY + SIGHASH_SINGLE
 657  ]
 658  
 659  VALID_SIGHASHES_TAPROOT_NO_SINGLE = [h for h in VALID_SIGHASHES_TAPROOT if h not in VALID_SIGHASHES_TAPROOT_SINGLE]
 660  
 661  SIGHASH_BITFLIP = {"failure": {"sighash": bitflipper(default_sighash)}}
 662  SIG_POP_BYTE = {"failure": {"sign": byte_popper(default_sign)}}
 663  SINGLE_SIG = {"inputs": [getter("sign")]}
 664  SIG_ADD_ZERO = {"failure": {"sign": zero_appender(default_sign)}}
 665  
 666  DUST_LIMIT = 600
 667  MIN_FEE = 50000
 668  
 669  TX_MAX_STANDARD_VERSION = 3
 670  TX_STANDARD_VERSIONS = [1, 2, TX_MAX_STANDARD_VERSION]
 671  TRUC_MAX_VSIZE = 10000 # test doesn't cover in-mempool spends, so only this limit is hit
 672  
 673  # === Actual test cases ===
 674  
 675  
 676  def spenders_taproot_active():
 677      """Return a list of Spenders for testing post-Taproot activation behavior."""
 678  
 679      secs = [generate_privkey() for _ in range(8)]
 680      pubs = [compute_xonly_pubkey(sec)[0] for sec in secs]
 681  
 682      spenders = []
 683  
 684      # == Tests for BIP340 signature validation. ==
 685      # These are primarily tested through the test vectors implemented in libsecp256k1, and in src/tests/key_tests.cpp.
 686      # Some things are tested programmatically as well here.
 687  
 688      tap = taproot_construct(pubs[0])
 689      # Test with key with bit flipped.
 690      add_spender(spenders, "sig/key", tap=tap, key=secs[0], failure={"key_tweaked": bitflipper(default_key_tweaked)}, **ERR_SIG_SCHNORR)
 691      # Test with sighash with bit flipped.
 692      add_spender(spenders, "sig/sighash", tap=tap, key=secs[0], failure={"sighash": bitflipper(default_sighash)}, **ERR_SIG_SCHNORR)
 693      # Test with invalid R sign.
 694      add_spender(spenders, "sig/flip_r", tap=tap, key=secs[0], failure={"flag_flip_r": True}, **ERR_SIG_SCHNORR)
 695      # Test with invalid P sign.
 696      add_spender(spenders, "sig/flip_p", tap=tap, key=secs[0], failure={"flag_flip_p": True}, **ERR_SIG_SCHNORR)
 697      # Test with signature with bit flipped.
 698      add_spender(spenders, "sig/bitflip", tap=tap, key=secs[0], failure={"signature": bitflipper(default_signature)}, **ERR_SIG_SCHNORR)
 699  
 700      # == Test involving an internal public key not on the curve ==
 701  
 702      # X-only public keys are 32 bytes, but not every 32-byte array is a valid public key; only
 703      # around 50% of them are. This does not affect users using correct software; these "keys" have
 704      # no corresponding private key, and thus will never appear as output of key
 705      # generation/derivation/tweaking.
 706      #
 707      # Using an invalid public key as P2TR output key makes the UTXO unspendable. Revealing an
 708      # invalid public key as internal key in a P2TR script path spend also makes the spend invalid.
 709      # These conditions are explicitly spelled out in BIP341.
 710      #
 711      # It is however hard to create test vectors for this, because it involves "guessing" how a
 712      # hypothetical incorrect implementation deals with an obviously-invalid condition, and making
 713      # sure that guessed behavior (accepting it in certain condition) doesn't occur.
 714      #
 715      # The test case added here tries to detect a very specific bug a verifier could have: if they
 716      # don't verify whether or not a revealed internal public key in a script path spend is valid,
 717      # and (correctly) implement output_key == tweak(internal_key, tweakval) but (incorrectly) treat
 718      # tweak(invalid_key, tweakval) as equal the public key corresponding to private key tweakval.
 719      # This may seem like a far-fetched edge condition to test for, but in fact, the BIP341 wallet
 720      # pseudocode did exactly that (but obviously only triggerable by someone invoking the tweaking
 721      # function with an invalid public key, which shouldn't happen).
 722  
 723      # Generate an invalid public key
 724      while True:
 725          invalid_pub = random.randbytes(32)
 726          if not secp256k1.GE.is_valid_x(int.from_bytes(invalid_pub, 'big')):
 727              break
 728  
 729      # Implement a test case that detects validation logic which maps invalid public keys to the
 730      # point at infinity in the tweaking logic.
 731      tap = taproot_construct(invalid_pub, [("true", CScript([OP_1]))], treat_internal_as_infinity=True)
 732      add_spender(spenders, "output/invalid_x", tap=tap, key_tweaked=tap.tweak, failure={"leaf": "true", "inputs": []}, **ERR_WITNESS_PROGRAM_MISMATCH)
 733  
 734      # Do the same thing without invalid point, to make sure there is no mistake in the test logic.
 735      tap = taproot_construct(pubs[0], [("true", CScript([OP_1]))])
 736      add_spender(spenders, "output/invalid_x_mock", tap=tap, key=secs[0], leaf="true", inputs=[])
 737  
 738      # == Tests for signature hashing ==
 739  
 740      # Run all tests once with no annex, and once with a valid random annex.
 741      for annex in [None, lambda _: bytes([ANNEX_TAG]) + random.randbytes(random.randrange(0, 250))]:
 742          # Non-empty annex is non-standard
 743          no_annex = annex is None
 744  
 745          # Sighash mutation tests (test all sighash combinations)
 746          for hashtype in VALID_SIGHASHES_TAPROOT:
 747              common = {"annex": annex, "hashtype": hashtype, "standard": no_annex}
 748  
 749              # Pure pubkey
 750              tap = taproot_construct(pubs[0])
 751              add_spender(spenders, "sighash/purepk", tap=tap, key=secs[0], **common, **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 752  
 753              # Pubkey/P2PK script combination
 754              scripts = [("s0", CScript(random_checksig_style(pubs[1])))]
 755              tap = taproot_construct(pubs[0], scripts)
 756              add_spender(spenders, "sighash/keypath_hashtype_%x" % hashtype, tap=tap, key=secs[0], **common, **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 757              add_spender(spenders, "sighash/scriptpath_hashtype_%x" % hashtype, tap=tap, leaf="s0", key=secs[1], **common, **SINGLE_SIG, **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 758  
 759              # Test SIGHASH_SINGLE behavior in combination with mismatching outputs
 760              if hashtype in VALID_SIGHASHES_TAPROOT_SINGLE:
 761                  add_spender(spenders, "sighash/keypath_hashtype_mis_%x" % hashtype, tap=tap, key=secs[0], annex=annex, standard=no_annex, hashtype_actual=random.choice(VALID_SIGHASHES_TAPROOT_NO_SINGLE), failure={"hashtype_actual": hashtype}, **ERR_SIG_HASHTYPE, need_vin_vout_mismatch=True)
 762                  add_spender(spenders, "sighash/scriptpath_hashtype_mis_%x" % hashtype, tap=tap, leaf="s0", key=secs[1], annex=annex, standard=no_annex, hashtype_actual=random.choice(VALID_SIGHASHES_TAPROOT_NO_SINGLE), **SINGLE_SIG, failure={"hashtype_actual": hashtype}, **ERR_SIG_HASHTYPE, need_vin_vout_mismatch=True)
 763  
 764          # Test OP_CODESEPARATOR impact on sighashing.
 765          hashtype = lambda _: random.choice(VALID_SIGHASHES_TAPROOT)
 766          common = {"annex": annex, "hashtype": hashtype, "standard": no_annex}
 767          scripts = [
 768              ("pk_codesep", CScript(random_checksig_style(pubs[1]) + bytes([OP_CODESEPARATOR]))),  # codesep after checksig
 769              ("codesep_pk", CScript(bytes([OP_CODESEPARATOR]) + random_checksig_style(pubs[1]))),  # codesep before checksig
 770              ("branched_codesep", CScript([random.randbytes(random.randrange(2, 75)), OP_DROP, OP_IF, OP_CODESEPARATOR, pubs[0], OP_ELSE, OP_CODESEPARATOR, pubs[1], OP_ENDIF, OP_CHECKSIG])),  # branch dependent codesep
 771              # Note that the first data push in the "branched_codesep" script has the purpose of
 772              # randomizing the sighash, both by varying script size and content. In order to
 773              # avoid MINIMALDATA script verification errors caused by not-minimal-encoded data
 774              # pushes (e.g. `OP_PUSH1 1` instead of `OP_1`), we set a minimum data size of 2 bytes.
 775          ]
 776          random.shuffle(scripts)
 777          tap = taproot_construct(pubs[0], scripts)
 778          add_spender(spenders, "sighash/pk_codesep", tap=tap, leaf="pk_codesep", key=secs[1], **common, **SINGLE_SIG, **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 779          add_spender(spenders, "sighash/codesep_pk", tap=tap, leaf="codesep_pk", key=secs[1], codeseppos=0, **common, **SINGLE_SIG, **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 780          common['standard'] = False
 781          add_spender(spenders, "sighash/branched_codesep/left", tap=tap, leaf="branched_codesep", key=secs[0], codeseppos=3, **common, inputs=[getter("sign"), b'\x01'], **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 782          add_spender(spenders, "sighash/branched_codesep/right", tap=tap, leaf="branched_codesep", key=secs[1], codeseppos=6, **common, inputs=[getter("sign"), b''], **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 783  
 784      # Reusing the scripts above, test that various features affect the sighash.
 785      add_spender(spenders, "sighash/annex", tap=tap, leaf="pk_codesep", key=secs[1], hashtype=hashtype, standard=False, **SINGLE_SIG, annex=bytes([ANNEX_TAG]), failure={"sighash": override(default_sighash, annex=None)}, **ERR_SIG_SCHNORR)
 786      add_spender(spenders, "sighash/script", tap=tap, leaf="pk_codesep", key=secs[1], **common, **SINGLE_SIG, failure={"sighash": override(default_sighash, script_taproot=tap.leaves["codesep_pk"].script)}, **ERR_SIG_SCHNORR)
 787      add_spender(spenders, "sighash/leafver", tap=tap, leaf="pk_codesep", key=secs[1], **common, **SINGLE_SIG, failure={"sighash": override(default_sighash, leafversion=random.choice([x & 0xFE for x in range(0x100) if x & 0xFE != LEAF_VERSION_TAPSCRIPT]))}, **ERR_SIG_SCHNORR)
 788      add_spender(spenders, "sighash/scriptpath", tap=tap, leaf="pk_codesep", key=secs[1], **common, **SINGLE_SIG, failure={"sighash": override(default_sighash, leaf=None)}, **ERR_SIG_SCHNORR)
 789      add_spender(spenders, "sighash/keypath", tap=tap, key=secs[0], **common, failure={"sighash": override(default_sighash, leaf="pk_codesep")}, **ERR_SIG_SCHNORR)
 790  
 791      # Test that invalid hashtypes don't work, both in key path and script path spends
 792      hashtype = lambda _: random.choice(VALID_SIGHASHES_TAPROOT)
 793      for invalid_hashtype in [x for x in range(0x100) if x not in VALID_SIGHASHES_TAPROOT]:
 794          add_spender(spenders, "sighash/keypath_unk_hashtype_%x" % invalid_hashtype, tap=tap, key=secs[0], hashtype=hashtype, failure={"hashtype": invalid_hashtype}, **ERR_SIG_HASHTYPE)
 795          add_spender(spenders, "sighash/scriptpath_unk_hashtype_%x" % invalid_hashtype, tap=tap, leaf="pk_codesep", key=secs[1], **SINGLE_SIG, hashtype=hashtype, failure={"hashtype": invalid_hashtype}, **ERR_SIG_HASHTYPE)
 796  
 797      # Test that hashtype 0 cannot have a hashtype byte, and 1 must have one.
 798      add_spender(spenders, "sighash/hashtype0_byte_keypath", tap=tap, key=secs[0], hashtype=SIGHASH_DEFAULT, failure={"bytes_hashtype": bytes([SIGHASH_DEFAULT])}, **ERR_SIG_HASHTYPE)
 799      add_spender(spenders, "sighash/hashtype0_byte_scriptpath", tap=tap, leaf="pk_codesep", key=secs[1], **SINGLE_SIG, hashtype=SIGHASH_DEFAULT, failure={"bytes_hashtype": bytes([SIGHASH_DEFAULT])}, **ERR_SIG_HASHTYPE)
 800      add_spender(spenders, "sighash/hashtype1_byte_keypath", tap=tap, key=secs[0], hashtype=SIGHASH_ALL, failure={"bytes_hashtype": b''}, **ERR_SIG_SCHNORR)
 801      add_spender(spenders, "sighash/hashtype1_byte_scriptpath", tap=tap, leaf="pk_codesep", key=secs[1], **SINGLE_SIG, hashtype=SIGHASH_ALL, failure={"bytes_hashtype": b''}, **ERR_SIG_SCHNORR)
 802      # Test that hashtype 0 and hashtype 1 cannot be transmuted into each other.
 803      add_spender(spenders, "sighash/hashtype0to1_keypath", tap=tap, key=secs[0], hashtype=SIGHASH_DEFAULT, failure={"bytes_hashtype": bytes([SIGHASH_ALL])}, **ERR_SIG_SCHNORR)
 804      add_spender(spenders, "sighash/hashtype0to1_scriptpath", tap=tap, leaf="pk_codesep", key=secs[1], **SINGLE_SIG, hashtype=SIGHASH_DEFAULT, failure={"bytes_hashtype": bytes([SIGHASH_ALL])}, **ERR_SIG_SCHNORR)
 805      add_spender(spenders, "sighash/hashtype1to0_keypath", tap=tap, key=secs[0], hashtype=SIGHASH_ALL, failure={"bytes_hashtype": b''}, **ERR_SIG_SCHNORR)
 806      add_spender(spenders, "sighash/hashtype1to0_scriptpath", tap=tap, leaf="pk_codesep", key=secs[1], **SINGLE_SIG, hashtype=SIGHASH_ALL, failure={"bytes_hashtype": b''}, **ERR_SIG_SCHNORR)
 807  
 808      # Test aspects of signatures with unusual lengths
 809      for hashtype in [SIGHASH_DEFAULT, random.choice(VALID_SIGHASHES_TAPROOT)]:
 810          scripts = [
 811              ("csv", CScript([pubs[2], OP_CHECKSIGVERIFY, OP_1])),
 812              ("cs_pos", CScript([pubs[2], OP_CHECKSIG])),
 813              ("csa_pos", CScript([OP_0, pubs[2], OP_CHECKSIGADD, OP_1, OP_EQUAL])),
 814              ("cs_neg", CScript([pubs[2], OP_CHECKSIG, OP_NOT])),
 815              ("csa_neg", CScript([OP_2, pubs[2], OP_CHECKSIGADD, OP_2, OP_EQUAL]))
 816          ]
 817          random.shuffle(scripts)
 818          tap = taproot_construct(pubs[3], scripts)
 819          # Empty signatures
 820          add_spender(spenders, "siglen/empty_keypath", tap=tap, key=secs[3], hashtype=hashtype, failure={"sign": b""}, **ERR_SIG_SIZE)
 821          add_spender(spenders, "siglen/empty_csv", tap=tap, key=secs[2], leaf="csv", hashtype=hashtype, **SINGLE_SIG, failure={"sign": b""}, **ERR_CHECKSIGVERIFY)
 822          add_spender(spenders, "siglen/empty_cs", tap=tap, key=secs[2], leaf="cs_pos", hashtype=hashtype, **SINGLE_SIG, failure={"sign": b""}, **ERR_NO_SUCCESS)
 823          add_spender(spenders, "siglen/empty_csa", tap=tap, key=secs[2], leaf="csa_pos", hashtype=hashtype, **SINGLE_SIG, failure={"sign": b""}, **ERR_NO_SUCCESS)
 824          add_spender(spenders, "siglen/empty_cs_neg", tap=tap, key=secs[2], leaf="cs_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", failure={"sign": lambda _: random.randbytes(random.randrange(1, 63))}, **ERR_SIG_SIZE)
 825          add_spender(spenders, "siglen/empty_csa_neg", tap=tap, key=secs[2], leaf="csa_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", failure={"sign": lambda _: random.randbytes(random.randrange(66, 100))}, **ERR_SIG_SIZE)
 826          # Appending a zero byte to signatures invalidates them
 827          add_spender(spenders, "siglen/padzero_keypath", tap=tap, key=secs[3], hashtype=hashtype, **SIG_ADD_ZERO, **(ERR_SIG_HASHTYPE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SIZE))
 828          add_spender(spenders, "siglen/padzero_csv", tap=tap, key=secs[2], leaf="csv", hashtype=hashtype, **SINGLE_SIG, **SIG_ADD_ZERO, **(ERR_SIG_HASHTYPE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SIZE))
 829          add_spender(spenders, "siglen/padzero_cs", tap=tap, key=secs[2], leaf="cs_pos", hashtype=hashtype, **SINGLE_SIG, **SIG_ADD_ZERO, **(ERR_SIG_HASHTYPE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SIZE))
 830          add_spender(spenders, "siglen/padzero_csa", tap=tap, key=secs[2], leaf="csa_pos", hashtype=hashtype, **SINGLE_SIG, **SIG_ADD_ZERO, **(ERR_SIG_HASHTYPE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SIZE))
 831          add_spender(spenders, "siglen/padzero_cs_neg", tap=tap, key=secs[2], leaf="cs_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", **SIG_ADD_ZERO, **(ERR_SIG_HASHTYPE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SIZE))
 832          add_spender(spenders, "siglen/padzero_csa_neg", tap=tap, key=secs[2], leaf="csa_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", **SIG_ADD_ZERO, **(ERR_SIG_HASHTYPE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SIZE))
 833          # Removing the last byte from signatures invalidates them
 834          add_spender(spenders, "siglen/popbyte_keypath", tap=tap, key=secs[3], hashtype=hashtype, **SIG_POP_BYTE, **(ERR_SIG_SIZE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SCHNORR))
 835          add_spender(spenders, "siglen/popbyte_csv", tap=tap, key=secs[2], leaf="csv", hashtype=hashtype, **SINGLE_SIG, **SIG_POP_BYTE, **(ERR_SIG_SIZE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SCHNORR))
 836          add_spender(spenders, "siglen/popbyte_cs", tap=tap, key=secs[2], leaf="cs_pos", hashtype=hashtype, **SINGLE_SIG, **SIG_POP_BYTE, **(ERR_SIG_SIZE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SCHNORR))
 837          add_spender(spenders, "siglen/popbyte_csa", tap=tap, key=secs[2], leaf="csa_pos", hashtype=hashtype, **SINGLE_SIG, **SIG_POP_BYTE, **(ERR_SIG_SIZE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SCHNORR))
 838          add_spender(spenders, "siglen/popbyte_cs_neg", tap=tap, key=secs[2], leaf="cs_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", **SIG_POP_BYTE, **(ERR_SIG_SIZE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SCHNORR))
 839          add_spender(spenders, "siglen/popbyte_csa_neg", tap=tap, key=secs[2], leaf="csa_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", **SIG_POP_BYTE, **(ERR_SIG_SIZE if hashtype == SIGHASH_DEFAULT else ERR_SIG_SCHNORR))
 840          # Verify that an invalid signature is not allowed, not even when the CHECKSIG* is expected to fail.
 841          add_spender(spenders, "siglen/invalid_cs_neg", tap=tap, key=secs[2], leaf="cs_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", failure={"sign": default_sign, "sighash": bitflipper(default_sighash)}, **ERR_SIG_SCHNORR)
 842          add_spender(spenders, "siglen/invalid_csa_neg", tap=tap, key=secs[2], leaf="csa_neg", hashtype=hashtype, **SINGLE_SIG, sign=b"", failure={"sign": default_sign, "sighash": bitflipper(default_sighash)}, **ERR_SIG_SCHNORR)
 843  
 844      # == Test that BIP341 spending only applies to witness version 1, program length 32, no P2SH ==
 845  
 846      for p2sh in [False, True]:
 847          for witver in range(1, 17):
 848              for witlen in [20, 31, 32, 33]:
 849                  def mutate(spk):
 850                      prog = spk[2:]
 851                      assert len(prog) == 32
 852                      if witlen < 32:
 853                          prog = prog[0:witlen]
 854                      elif witlen > 32:
 855                          prog += bytes([0 for _ in range(witlen - 32)])
 856                      return CScript([CScriptOp.encode_op_n(witver), prog])
 857                  scripts = [("s0", CScript([pubs[0], OP_CHECKSIG])), ("dummy", CScript([OP_RETURN]))]
 858                  tap = taproot_construct(pubs[1], scripts)
 859                  if not p2sh and witver == 1 and witlen == 32:
 860                      add_spender(spenders, "applic/keypath", p2sh=p2sh, spk_mutate_pre_p2sh=mutate, tap=tap, key=secs[1], **SIGHASH_BITFLIP, **ERR_SIG_SCHNORR)
 861                      add_spender(spenders, "applic/scriptpath", p2sh=p2sh, leaf="s0", spk_mutate_pre_p2sh=mutate, tap=tap, key=secs[0], **SINGLE_SIG, failure={"leaf": "dummy"}, **ERR_OP_RETURN)
 862                  else:
 863                      add_spender(spenders, "applic/keypath", p2sh=p2sh, spk_mutate_pre_p2sh=mutate, tap=tap, key=secs[1], standard=False)
 864                      add_spender(spenders, "applic/scriptpath", p2sh=p2sh, leaf="s0", spk_mutate_pre_p2sh=mutate, tap=tap, key=secs[0], **SINGLE_SIG, standard=False)
 865  
 866      # == Test various aspects of BIP341 spending paths ==
 867  
 868      # A set of functions that compute the hashing partner in a Merkle tree, designed to exercise
 869      # edge cases. This relies on the taproot_construct feature that a lambda can be passed in
 870      # instead of a subtree, to compute the partner to be hashed with.
 871      PARTNER_MERKLE_FN = [
 872          # Combine with itself
 873          lambda h: h,
 874          # Combine with hash 0
 875          lambda h: bytes([0 for _ in range(32)]),
 876          # Combine with hash 2^256-1
 877          lambda h: bytes([0xff for _ in range(32)]),
 878          # Combine with itself-1 (BE)
 879          lambda h: (int.from_bytes(h, 'big') - 1).to_bytes(32, 'big'),
 880          # Combine with itself+1 (BE)
 881          lambda h: (int.from_bytes(h, 'big') + 1).to_bytes(32, 'big'),
 882          # Combine with itself-1 (LE)
 883          lambda h: (int.from_bytes(h, 'little') - 1).to_bytes(32, 'big'),
 884          # Combine with itself+1 (LE)
 885          lambda h: (int.from_bytes(h, 'little') + 1).to_bytes(32, 'little'),
 886          # Combine with random bitflipped version of self.
 887          lambda h: (int.from_bytes(h, 'little') ^ (1 << random.randrange(256))).to_bytes(32, 'little')
 888      ]
 889      # Start with a tree of that has depth 1 for "128deep" and depth 2 for "129deep".
 890      scripts = [("128deep", CScript([pubs[0], OP_CHECKSIG])), [("129deep", CScript([pubs[0], OP_CHECKSIG])), random.choice(PARTNER_MERKLE_FN)]]
 891      # Add 127 nodes on top of that tree, so that "128deep" and "129deep" end up at their designated depths.
 892      for _ in range(127):
 893          scripts = [scripts, random.choice(PARTNER_MERKLE_FN)]
 894      tap = taproot_construct(pubs[0], scripts)
 895      # Test that spends with a depth of 128 work, but 129 doesn't (even with a tree with weird Merkle branches in it).
 896      assert 'standard' not in SINGLE_SIG
 897      SINGLE_SIG['standard'] = False
 898      add_spender(spenders, "spendpath/merklelimit", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"leaf": "129deep"}, **ERR_CONTROLBLOCK_SIZE)
 899      # Test that flipping the negation bit invalidates spends.
 900      add_spender(spenders, "spendpath/negflag", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"negflag": lambda ctx: 1 - default_negflag(ctx)}, **ERR_WITNESS_PROGRAM_MISMATCH)
 901      # Test that bitflips in the Merkle branch invalidate it.
 902      add_spender(spenders, "spendpath/bitflipmerkle", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"merklebranch": bitflipper(default_merklebranch)}, **ERR_WITNESS_PROGRAM_MISMATCH)
 903      # Test that bitflips in the internal pubkey invalidate it.
 904      add_spender(spenders, "spendpath/bitflippubkey", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"pubkey_internal": bitflipper(default_pubkey_internal)}, **ERR_WITNESS_PROGRAM_MISMATCH)
 905      # Test that empty witnesses are invalid.
 906      add_spender(spenders, "spendpath/emptywit", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"witness": []}, **ERR_EMPTY_WITNESS)
 907      # Test that adding garbage to the control block invalidates it.
 908      add_spender(spenders, "spendpath/padlongcontrol", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"controlblock": lambda ctx: default_controlblock(ctx) + random.randbytes(random.randrange(1, 32))}, **ERR_CONTROLBLOCK_SIZE)
 909      # Test that truncating the control block invalidates it.
 910      add_spender(spenders, "spendpath/trunclongcontrol", tap=tap, leaf="128deep", **SINGLE_SIG, key=secs[0], failure={"controlblock": lambda ctx: default_merklebranch(ctx)[0:random.randrange(1, 32)]}, **ERR_CONTROLBLOCK_SIZE)
 911      del SINGLE_SIG['standard']
 912  
 913      scripts = [("s", CScript([pubs[0], OP_CHECKSIG]))]
 914      tap = taproot_construct(pubs[1], scripts)
 915      # Test that adding garbage to the control block invalidates it.
 916      add_spender(spenders, "spendpath/padshortcontrol", tap=tap, leaf="s", **SINGLE_SIG, key=secs[0], failure={"controlblock": lambda ctx: default_controlblock(ctx) + random.randbytes(random.randrange(1, 32))}, **ERR_CONTROLBLOCK_SIZE)
 917      # Test that truncating the control block invalidates it.
 918      add_spender(spenders, "spendpath/truncshortcontrol", tap=tap, leaf="s", **SINGLE_SIG, key=secs[0], failure={"controlblock": lambda ctx: default_merklebranch(ctx)[0:random.randrange(1, 32)]}, **ERR_CONTROLBLOCK_SIZE)
 919      # Test that truncating the control block to 1 byte ("-1 Merkle length") invalidates it
 920      add_spender(spenders, "spendpath/trunc1shortcontrol", tap=tap, leaf="s", **SINGLE_SIG, key=secs[0], failure={"controlblock": lambda ctx: default_merklebranch(ctx)[0:1]}, **ERR_CONTROLBLOCK_SIZE)
 921  
 922      # == Test BIP342 edge cases ==
 923  
 924      csa_low_val = random.randrange(0, 17) # Within range for OP_n
 925      csa_low_result = csa_low_val + 1
 926  
 927      csa_high_val = random.randrange(17, 100) if random.getrandbits(1) else random.randrange(-100, -1) # Outside OP_n range
 928      csa_high_result = csa_high_val + 1
 929  
 930      OVERSIZE_NUMBER = 2**31
 931      assert_equal(len(CScriptNum.encode(CScriptNum(OVERSIZE_NUMBER))), 6)
 932      assert_equal(len(CScriptNum.encode(CScriptNum(OVERSIZE_NUMBER-1))), 5)
 933  
 934      big_choices = []
 935      big_scriptops = []
 936      for i in range(1000):
 937          r = random.randrange(len(pubs))
 938          big_choices.append(r)
 939          big_scriptops += [pubs[r], OP_CHECKSIGVERIFY]
 940  
 941  
 942      def big_spend_inputs(ctx):
 943          """Helper function to construct the script input for t33/t34 below."""
 944          # Instead of signing 999 times, precompute signatures for every (key, hashtype) combination
 945          sigs = {}
 946          for ht in VALID_SIGHASHES_TAPROOT:
 947              for k in range(len(pubs)):
 948                  sigs[(k, ht)] = override(default_sign, hashtype=ht, key=secs[k])(ctx)
 949          num = get(ctx, "num")
 950          return [sigs[(big_choices[i], random.choice(VALID_SIGHASHES_TAPROOT))] for i in range(num - 1, -1, -1)]
 951  
 952      # Various BIP342 features
 953      scripts = [
 954          # 0) drop stack element and OP_CHECKSIG
 955          ("t0", CScript([OP_DROP, pubs[1], OP_CHECKSIG])),
 956          # 1) normal OP_CHECKSIG
 957          ("t1", CScript([pubs[1], OP_CHECKSIG])),
 958          # 2) normal OP_CHECKSIGVERIFY
 959          ("t2", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_1])),
 960          # 3) Hypothetical OP_CHECKMULTISIG script that takes a single sig as input
 961          ("t3", CScript([OP_0, OP_SWAP, OP_1, pubs[1], OP_1, OP_CHECKMULTISIG])),
 962          # 4) Hypothetical OP_CHECKMULTISIGVERIFY script that takes a single sig as input
 963          ("t4", CScript([OP_0, OP_SWAP, OP_1, pubs[1], OP_1, OP_CHECKMULTISIGVERIFY, OP_1])),
 964          # 5) OP_IF script that needs a true input
 965          ("t5", CScript([OP_IF, pubs[1], OP_CHECKSIG, OP_ELSE, OP_RETURN, OP_ENDIF])),
 966          # 6) OP_NOTIF script that needs a true input
 967          ("t6", CScript([OP_NOTIF, OP_RETURN, OP_ELSE, pubs[1], OP_CHECKSIG, OP_ENDIF])),
 968          # 7) OP_CHECKSIG with an empty key
 969          ("t7", CScript([OP_0, OP_CHECKSIG])),
 970          # 8) OP_CHECKSIGVERIFY with an empty key
 971          ("t8", CScript([OP_0, OP_CHECKSIGVERIFY, OP_1])),
 972          # 9) normal OP_CHECKSIGADD that also ensures return value is correct
 973          ("t9", CScript([csa_low_val, pubs[1], OP_CHECKSIGADD, csa_low_result, OP_EQUAL])),
 974          # 10) OP_CHECKSIGADD with empty key
 975          ("t10", CScript([csa_low_val, OP_0, OP_CHECKSIGADD, csa_low_result, OP_EQUAL])),
 976          # 11) OP_CHECKSIGADD with missing counter stack element
 977          ("t11", CScript([pubs[1], OP_CHECKSIGADD, OP_1, OP_EQUAL])),
 978          # 12) OP_CHECKSIG that needs invalid signature
 979          ("t12", CScript([pubs[1], OP_CHECKSIGVERIFY, pubs[0], OP_CHECKSIG, OP_NOT])),
 980          # 13) OP_CHECKSIG with empty key that needs invalid signature
 981          ("t13", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_0, OP_CHECKSIG, OP_NOT])),
 982          # 14) OP_CHECKSIGADD that needs invalid signature
 983          ("t14", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_0, pubs[0], OP_CHECKSIGADD, OP_NOT])),
 984          # 15) OP_CHECKSIGADD with empty key that needs invalid signature
 985          ("t15", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_0, OP_0, OP_CHECKSIGADD, OP_NOT])),
 986          # 16) OP_CHECKSIG with unknown pubkey type
 987          ("t16", CScript([OP_1, OP_CHECKSIG])),
 988          # 17) OP_CHECKSIGADD with unknown pubkey type
 989          ("t17", CScript([OP_0, OP_1, OP_CHECKSIGADD])),
 990          # 18) OP_CHECKSIGVERIFY with unknown pubkey type
 991          ("t18", CScript([OP_1, OP_CHECKSIGVERIFY, OP_1])),
 992          # 19) script longer than 10000 bytes and over 201 non-push opcodes
 993          ("t19", CScript([OP_0, OP_0, OP_2DROP] * 10001 + [pubs[1], OP_CHECKSIG])),
 994          # 20) OP_CHECKSIGVERIFY with empty key
 995          ("t20", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_0, OP_0, OP_CHECKSIGVERIFY, OP_1])),
 996          # 21) Script that grows the stack to 1000 elements
 997          ("t21", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_1] + [OP_DUP] * 999 + [OP_DROP] * 999)),
 998          # 22) Script that grows the stack to 1001 elements
 999          ("t22", CScript([pubs[1], OP_CHECKSIGVERIFY, OP_1] + [OP_DUP] * 1000 + [OP_DROP] * 1000)),
1000          # 23) Script that expects an input stack of 1000 elements
1001          ("t23", CScript([OP_DROP] * 999 + [pubs[1], OP_CHECKSIG])),
1002          # 24) Script that expects an input stack of 1001 elements
1003          ("t24", CScript([OP_DROP] * 1000 + [pubs[1], OP_CHECKSIG])),
1004          # 25) Script that pushes a MAX_SCRIPT_ELEMENT_SIZE-bytes element
1005          ("t25", CScript([random.randbytes(MAX_SCRIPT_ELEMENT_SIZE), OP_DROP, pubs[1], OP_CHECKSIG])),
1006          # 26) Script that pushes a (MAX_SCRIPT_ELEMENT_SIZE+1)-bytes element
1007          ("t26", CScript([random.randbytes(MAX_SCRIPT_ELEMENT_SIZE+1), OP_DROP, pubs[1], OP_CHECKSIG])),
1008          # 27) CHECKSIGADD that must fail because numeric argument number is >4 bytes
1009          ("t27", CScript([CScriptNum(OVERSIZE_NUMBER), pubs[1], OP_CHECKSIGADD])),
1010          # 28) Pushes random CScriptNum value, checks OP_CHECKSIGADD result
1011          ("t28", CScript([csa_high_val, pubs[1], OP_CHECKSIGADD, csa_high_result, OP_EQUAL])),
1012          # 29) CHECKSIGADD that succeeds with proper sig because numeric argument number is <=4 bytes
1013          ("t29", CScript([CScriptNum(OVERSIZE_NUMBER-1), pubs[1], OP_CHECKSIGADD])),
1014          # 30) Variant of t1 with "normal" 33-byte pubkey
1015          ("t30", CScript([b'\x03' + pubs[1], OP_CHECKSIG])),
1016          # 31) Variant of t2 with "normal" 33-byte pubkey
1017          ("t31", CScript([b'\x02' + pubs[1], OP_CHECKSIGVERIFY, OP_1])),
1018          # 32) Variant of t28 with "normal" 33-byte pubkey
1019          ("t32", CScript([csa_high_val, b'\x03' + pubs[1], OP_CHECKSIGADD, csa_high_result, OP_EQUAL])),
1020          # 33) 999-of-999 multisig
1021          ("t33", CScript(big_scriptops[:1998] + [OP_1])),
1022          # 34) 1000-of-1000 multisig
1023          ("t34", CScript(big_scriptops[:2000] + [OP_1])),
1024          # 35) Variant of t9 that uses a non-minimally encoded input arg
1025          ("t35", CScript([bytes([csa_low_val]), pubs[1], OP_CHECKSIGADD, csa_low_result, OP_EQUAL])),
1026          # 36) Empty script
1027          ("t36", CScript([])),
1028      ]
1029      # Add many dummies to test huge trees
1030      for j in range(min(100000, 2**TAPROOT_CONTROL_MAX_NODE_COUNT_REDUCED - len(scripts))):
1031          scripts.append((None, CScript([OP_RETURN, random.randrange(100000)])))
1032      random.shuffle(scripts)
1033      tap = taproot_construct(pubs[0], scripts)
1034      common = {
1035          "hashtype": hashtype,
1036          "key": secs[1],
1037          "tap": tap,
1038      }
1039      # Test that MAX_SCRIPT_ELEMENT_SIZE byte stack element inputs are valid, but not one more (and 80 bytes is standard but 81 is not).
1040      add_spender(spenders, "tapscript/inputmaxlimit", leaf="t0", **common, standard=False, inputs=[getter("sign"), random.randbytes(MAX_SCRIPT_ELEMENT_SIZE)], failure={"inputs": [getter("sign"), random.randbytes(MAX_SCRIPT_ELEMENT_SIZE+1)]}, **ERR_PUSH_LIMIT)
1041      add_spender(spenders, "tapscript/input80limit", leaf="t0", **common, inputs=[getter("sign"), random.randbytes(80)])
1042      add_spender(spenders, "tapscript/input81limit", leaf="t0", **common, standard=False, inputs=[getter("sign"), random.randbytes(81)])
1043      # Test that OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY cause failure, but OP_CHECKSIG and OP_CHECKSIGVERIFY work.
1044      add_spender(spenders, "tapscript/disabled_checkmultisig", leaf="t1", **common, **SINGLE_SIG, failure={"leaf": "t3"}, **ERR_TAPSCRIPT_CHECKMULTISIG)
1045      add_spender(spenders, "tapscript/disabled_checkmultisigverify", leaf="t2", **common, **SINGLE_SIG, failure={"leaf": "t4"}, **ERR_TAPSCRIPT_CHECKMULTISIG)
1046      # Test that OP_IF and OP_NOTIF do not accept non-0x01 as truth value (the MINIMALIF rule is consensus in Tapscript)
1047      assert 'standard' not in common
1048      common['standard'] = False
1049      add_spender(spenders, "tapscript/minimalif", leaf="t5", **common, inputs=[getter("sign"), b'\x01'], failure={"inputs": [getter("sign"), b'\x02']}, **ERR_MINIMALIF)
1050      add_spender(spenders, "tapscript/minimalnotif", leaf="t6", **common, inputs=[getter("sign"), b'\x01'], failure={"inputs": [getter("sign"), b'\x03']}, **ERR_MINIMALIF)
1051      add_spender(spenders, "tapscript/minimalif", leaf="t5", **common, inputs=[getter("sign"), b'\x01'], failure={"inputs": [getter("sign"), b'\x0001']}, **ERR_MINIMALIF)
1052      add_spender(spenders, "tapscript/minimalnotif", leaf="t6", **common, inputs=[getter("sign"), b'\x01'], failure={"inputs": [getter("sign"), b'\x0100']}, **ERR_MINIMALIF)
1053      del common['standard']
1054      # Test that 1-byte public keys (which are unknown) are acceptable but nonstandard with unrelated signatures, but 0-byte public keys are not valid.
1055      add_spender(spenders, "tapscript/unkpk/checksig", leaf="t16", standard=False, **common, **SINGLE_SIG, failure={"leaf": "t7"}, **ERR_UNKNOWN_PUBKEY)
1056      add_spender(spenders, "tapscript/unkpk/checksigadd", leaf="t17", standard=False, **common, **SINGLE_SIG, failure={"leaf": "t10"}, **ERR_UNKNOWN_PUBKEY)
1057      add_spender(spenders, "tapscript/unkpk/checksigverify", leaf="t18", standard=False, **common, **SINGLE_SIG, failure={"leaf": "t8"}, **ERR_UNKNOWN_PUBKEY)
1058      # Test that 33-byte public keys (which are unknown) are acceptable but nonstandard with valid signatures, but normal pubkeys are not valid in that case.
1059      add_spender(spenders, "tapscript/oldpk/checksig", leaf="t30", standard=False, **common, **SINGLE_SIG, sighash=bitflipper(default_sighash), failure={"leaf": "t1"}, **ERR_SIG_SCHNORR)
1060      add_spender(spenders, "tapscript/oldpk/checksigadd", leaf="t31", standard=False, **common, **SINGLE_SIG, sighash=bitflipper(default_sighash), failure={"leaf": "t2"}, **ERR_SIG_SCHNORR)
1061      add_spender(spenders, "tapscript/oldpk/checksigverify", leaf="t32", standard=False, **common, **SINGLE_SIG, sighash=bitflipper(default_sighash), failure={"leaf": "t28"}, **ERR_SIG_SCHNORR)
1062      # Test that 0-byte public keys are not acceptable.
1063      add_spender(spenders, "tapscript/emptypk/checksig", leaf="t1", **SINGLE_SIG, **common, failure={"leaf": "t7"}, **ERR_UNKNOWN_PUBKEY)
1064      add_spender(spenders, "tapscript/emptypk/checksigverify", leaf="t2", **SINGLE_SIG, **common, failure={"leaf": "t8"}, **ERR_UNKNOWN_PUBKEY)
1065      add_spender(spenders, "tapscript/emptypk/checksigadd", leaf="t9", **SINGLE_SIG, **common, failure={"leaf": "t10"}, **ERR_UNKNOWN_PUBKEY)
1066      add_spender(spenders, "tapscript/emptypk/checksigadd", leaf="t35", standard=False, **SINGLE_SIG, **common, failure={"leaf": "t10"}, **ERR_UNKNOWN_PUBKEY)
1067      # Test that OP_CHECKSIGADD results are as expected
1068      add_spender(spenders, "tapscript/checksigaddresults", leaf="t28", **SINGLE_SIG, **common, failure={"leaf": "t27"}, err_msg="unknown error")
1069      add_spender(spenders, "tapscript/checksigaddoversize", leaf="t29", **SINGLE_SIG, **common, failure={"leaf": "t27"}, err_msg="unknown error")
1070      # Test that OP_CHECKSIGADD requires 3 stack elements.
1071      add_spender(spenders, "tapscript/checksigadd3args", leaf="t9", **SINGLE_SIG, **common, failure={"leaf": "t11"}, **ERR_STACK_EMPTY)
1072      # Test that empty signatures do not cause script failure in OP_CHECKSIG and OP_CHECKSIGADD (but do fail with empty pubkey, and do fail OP_CHECKSIGVERIFY)
1073      add_spender(spenders, "tapscript/emptysigs/checksig", leaf="t12", **common, inputs=[b'', getter("sign")], failure={"leaf": "t13"}, **ERR_UNKNOWN_PUBKEY)
1074      add_spender(spenders, "tapscript/emptysigs/nochecksigverify", leaf="t12", **common, inputs=[b'', getter("sign")], failure={"leaf": "t20"}, **ERR_UNKNOWN_PUBKEY)
1075      add_spender(spenders, "tapscript/emptysigs/checksigadd", leaf="t14", **common, inputs=[b'', getter("sign")], failure={"leaf": "t15"}, **ERR_UNKNOWN_PUBKEY)
1076      # Test that scripts over 10000 bytes (and over 201 non-push ops) are acceptable.
1077      add_spender(spenders, "tapscript/no10000limit", leaf="t19", **SINGLE_SIG, **common)
1078      # Test that a stack size of 1000 elements is permitted, but 1001 isn't.
1079      add_spender(spenders, "tapscript/1000stack", leaf="t21", **SINGLE_SIG, **common, failure={"leaf": "t22"}, **ERR_STACK_SIZE)
1080      # Test that an input stack size of 1000 elements is permitted, but 1001 isn't.
1081      add_spender(spenders, "tapscript/1000inputs", leaf="t23", **common, inputs=[getter("sign")] + [b'' for _ in range(999)], failure={"leaf": "t24", "inputs": [getter("sign")] + [b'' for _ in range(1000)]}, **ERR_STACK_SIZE)
1082      # Test that pushing a MAX_SCRIPT_ELEMENT_SIZE byte stack element is valid, but one longer is not.
1083      add_spender(spenders, "tapscript/pushmaxlimit", standard=False, leaf="t25", **common, **SINGLE_SIG, failure={"leaf": "t26"}, **ERR_PUSH_LIMIT)
1084      # Test that 999-of-999 multisig works (but 1000-of-1000 triggers stack size limits)
1085      add_spender(spenders, "tapscript/bigmulti", leaf="t33", **common, inputs=big_spend_inputs, num=999, failure={"leaf": "t34", "num": 1000}, **ERR_STACK_SIZE)
1086      # Test that the CLEANSTACK rule is consensus critical in tapscript
1087      add_spender(spenders, "tapscript/cleanstack", leaf="t36", tap=tap, inputs=[b'\x01'], failure={"inputs": [b'\x01', b'\x01']}, **ERR_CLEANSTACK)
1088  
1089      # == Test for sigops ratio limit ==
1090  
1091      # Given a number n, and a public key pk, functions that produce a (CScript, sigops). Each script takes as
1092      # input a valid signature with the passed pk followed by a dummy push of bytes that are to be dropped, and
1093      # will execute sigops signature checks.
1094      SIGOPS_RATIO_SCRIPTS = [
1095          # n OP_CHECKSIGVERIFYs and 1 OP_CHECKSIG.
1096          lambda n, pk: (CScript([OP_DROP, pk] + [OP_2DUP, OP_CHECKSIGVERIFY] * n + [OP_CHECKSIG]), n + 1),
1097          # n OP_CHECKSIGVERIFYs and 1 OP_CHECKSIGADD, but also one unexecuted OP_CHECKSIGVERIFY.
1098          lambda n, pk: (CScript([OP_DROP, pk, OP_0, OP_IF, OP_2DUP, OP_CHECKSIGVERIFY, OP_ENDIF] + [OP_2DUP, OP_CHECKSIGVERIFY] * n + [OP_2, OP_SWAP, OP_CHECKSIGADD, OP_3, OP_EQUAL]), n + 1),
1099          # n OP_CHECKSIGVERIFYs and 1 OP_CHECKSIGADD, but also one unexecuted OP_CHECKSIG.
1100          lambda n, pk: (CScript([random.randbytes(220), OP_2DROP, pk, OP_1, OP_NOTIF, OP_2DUP, OP_CHECKSIG, OP_VERIFY, OP_ENDIF] + [OP_2DUP, OP_CHECKSIGVERIFY] * n + [OP_4, OP_SWAP, OP_CHECKSIGADD, OP_5, OP_EQUAL]), n + 1),
1101          # n OP_CHECKSIGVERIFYs and 1 OP_CHECKSIGADD, but also one unexecuted OP_CHECKSIGADD.
1102          lambda n, pk: (CScript([OP_DROP, pk, OP_1, OP_IF, OP_ELSE, OP_2DUP, OP_6, OP_SWAP, OP_CHECKSIGADD, OP_7, OP_EQUALVERIFY, OP_ENDIF] + [OP_2DUP, OP_CHECKSIGVERIFY] * n + [OP_8, OP_SWAP, OP_CHECKSIGADD, OP_9, OP_EQUAL]), n + 1),
1103          # n+1 OP_CHECKSIGs, but also one OP_CHECKSIG with an empty signature.
1104          lambda n, pk: (CScript([OP_DROP, OP_0, pk, OP_CHECKSIG, OP_NOT, OP_VERIFY, pk] + [OP_2DUP, OP_CHECKSIG, OP_VERIFY] * n + [OP_CHECKSIG]), n + 1),
1105          # n OP_CHECKSIGADDs and 1 OP_CHECKSIG, but also an OP_CHECKSIGADD with an empty signature.
1106          lambda n, pk: (CScript([OP_DROP, OP_0, OP_10, pk, OP_CHECKSIGADD, OP_10, OP_EQUALVERIFY, pk] + [OP_2DUP, OP_16, OP_SWAP, OP_CHECKSIGADD, b'\x11', OP_EQUALVERIFY] * n + [OP_CHECKSIG]), n + 1),
1107      ]
1108      for annex in [None, bytes([ANNEX_TAG]) + random.randbytes(random.randrange(1000))]:
1109          for hashtype in [SIGHASH_DEFAULT, SIGHASH_ALL]:
1110              for pubkey in [pubs[1], random.randbytes(random.choice([x for x in range(2, 81) if x != 32]))]:
1111                  for fn_num, fn in enumerate(SIGOPS_RATIO_SCRIPTS):
1112                      merkledepth = random.randrange(129)
1113  
1114  
1115                      def predict_sigops_ratio(n, dummy_size):
1116                          """Predict whether spending fn(n, pubkey) with dummy_size will pass the ratio test."""
1117                          script, sigops = fn(n, pubkey)
1118                          # Predict the size of the witness for a given choice of n
1119                          stacklen_size = 1
1120                          sig_size = 64 + (hashtype != SIGHASH_DEFAULT)
1121                          siglen_size = 1
1122                          dummylen_size = 1 + 2 * (dummy_size >= 253)
1123                          script_size = len(script)
1124                          scriptlen_size = 1 + 2 * (script_size >= 253)
1125                          control_size = 33 + 32 * merkledepth
1126                          controllen_size = 1 + 2 * (control_size >= 253)
1127                          annex_size = 0 if annex is None else len(annex)
1128                          annexlen_size = 0 if annex is None else 1 + 2 * (annex_size >= 253)
1129                          witsize = stacklen_size + sig_size + siglen_size + dummy_size + dummylen_size + script_size + scriptlen_size + control_size + controllen_size + annex_size + annexlen_size
1130                          # sigops ratio test
1131                          return witsize + 50 >= 50 * sigops
1132                      # Make sure n is high enough that with empty dummy, the script is not valid
1133                      n = 0
1134                      while predict_sigops_ratio(n, 0):
1135                          n += 1
1136                      # But allow picking a bit higher still
1137                      n += random.randrange(5)
1138                      # Now pick dummy size *just* large enough that the overall construction passes
1139                      dummylen = 0
1140                      while not predict_sigops_ratio(n, dummylen):
1141                          dummylen += 1
1142                      script = fn(n, pubkey)[0]
1143                      scripts = [("s", script)]
1144                      for _ in range(merkledepth):
1145                          scripts = [scripts, random.choice(PARTNER_MERKLE_FN)]
1146                      tap = taproot_construct(pubs[0], scripts)
1147                      has_conditional = any(op in (OP_IF, OP_NOTIF) for op, _, _ in script.raw_iter())
1148                      standard = annex is None and dummylen <= 80 and len(pubkey) == 32 and not has_conditional and merkledepth <= TAPROOT_CONTROL_MAX_NODE_COUNT_REDUCED
1149                      add_spender(spenders, "tapscript/sigopsratio_%i" % fn_num, tap=tap, leaf="s", annex=annex, hashtype=hashtype, key=secs[1], inputs=[getter("sign"), random.randbytes(dummylen)], standard=standard, failure={"inputs": [getter("sign"), random.randbytes(dummylen - 1)]}, **ERR_SIGOPS_RATIO)
1150  
1151      # Future leaf versions
1152      for leafver in range(0, 0x100, 2):
1153          if leafver == LEAF_VERSION_TAPSCRIPT or leafver == ANNEX_TAG:
1154              # Skip the defined LEAF_VERSION_TAPSCRIPT, and the ANNEX_TAG which is not usable as leaf version
1155              continue
1156          scripts = [
1157              ("bare_c0", CScript([OP_NOP])),
1158              ("bare_unkver", CScript([OP_NOP]), leafver),
1159              ("return_c0", CScript([OP_RETURN])),
1160              ("return_unkver", CScript([OP_RETURN]), leafver),
1161              ("undecodable_c0", CScript([OP_PUSHDATA1])),
1162              ("undecodable_unkver", CScript([OP_PUSHDATA1]), leafver),
1163              ("bigpush_c0", CScript([random.randbytes(MAX_SCRIPT_ELEMENT_SIZE+1), OP_DROP])),
1164              ("bigpush_unkver", CScript([random.randbytes(MAX_SCRIPT_ELEMENT_SIZE+1), OP_DROP]), leafver),
1165              ("1001push_c0", CScript([OP_0] * 1001)),
1166              ("1001push_unkver", CScript([OP_0] * 1001), leafver),
1167          ]
1168          random.shuffle(scripts)
1169          tap = taproot_construct(pubs[0], scripts)
1170          add_spender(spenders, "unkver/bare", standard=False, tap=tap, leaf="bare_unkver", failure={"leaf": "bare_c0"}, **ERR_CLEANSTACK)
1171          add_spender(spenders, "unkver/return", standard=False, tap=tap, leaf="return_unkver", failure={"leaf": "return_c0"}, **ERR_OP_RETURN)
1172          add_spender(spenders, "unkver/undecodable", standard=False, tap=tap, leaf="undecodable_unkver", failure={"leaf": "undecodable_c0"}, **ERR_UNDECODABLE)
1173          add_spender(spenders, "unkver/bigpush", standard=False, tap=tap, leaf="bigpush_unkver", failure={"leaf": "bigpush_c0"}, **ERR_PUSH_LIMIT)
1174          add_spender(spenders, "unkver/1001push", standard=False, tap=tap, leaf="1001push_unkver", failure={"leaf": "1001push_c0"}, **ERR_STACK_SIZE)
1175          add_spender(spenders, "unkver/1001inputs", standard=False, tap=tap, leaf="bare_unkver", inputs=[b'']*1001, failure={"leaf": "bare_c0"}, **ERR_STACK_SIZE)
1176  
1177      # OP_SUCCESSx tests.
1178      hashtype = lambda _: random.choice(VALID_SIGHASHES_TAPROOT)
1179      for opval in range(76, 0x100):
1180          opcode = CScriptOp(opval)
1181          if not is_op_success(opcode):
1182              continue
1183          scripts = [
1184              ("bare_success", CScript([opcode])),
1185              ("bare_nop", CScript([OP_NOP])),
1186              ("unexecif_success", CScript([OP_0, OP_IF, opcode, OP_ENDIF])),
1187              ("unexecif_nop", CScript([OP_0, OP_IF, OP_NOP, OP_ENDIF])),
1188              ("return_success", CScript([OP_RETURN, opcode])),
1189              ("return_nop", CScript([OP_RETURN, OP_NOP])),
1190              ("undecodable_success", CScript([opcode, OP_PUSHDATA1])),
1191              ("undecodable_nop", CScript([OP_NOP, OP_PUSHDATA1])),
1192              ("undecodable_bypassed_success", CScript([OP_PUSHDATA1, OP_2, opcode])),
1193              ("bigpush_success", CScript([random.randbytes(MAX_SCRIPT_ELEMENT_SIZE+1), OP_DROP, opcode])),
1194              ("bigpush_nop", CScript([random.randbytes(MAX_SCRIPT_ELEMENT_SIZE+1), OP_DROP, OP_NOP])),
1195              ("1001push_success", CScript([OP_0] * 1001 + [opcode])),
1196              ("1001push_nop", CScript([OP_0] * 1001 + [OP_NOP])),
1197          ]
1198          random.shuffle(scripts)
1199          tap = taproot_construct(pubs[0], scripts)
1200          add_spender(spenders, "opsuccess/bare", standard=False, tap=tap, leaf="bare_success", failure={"leaf": "bare_nop"}, **ERR_CLEANSTACK)
1201          add_spender(spenders, "opsuccess/unexecif", standard=False, tap=tap, leaf="unexecif_success", failure={"leaf": "unexecif_nop"}, **ERR_CLEANSTACK)
1202          add_spender(spenders, "opsuccess/return", standard=False, tap=tap, leaf="return_success", failure={"leaf": "return_nop"}, **ERR_OP_RETURN)
1203          add_spender(spenders, "opsuccess/undecodable", standard=False, tap=tap, leaf="undecodable_success", failure={"leaf": "undecodable_nop"}, **ERR_UNDECODABLE)
1204          add_spender(spenders, "opsuccess/undecodable_bypass", standard=False, tap=tap, leaf="undecodable_success", failure={"leaf": "undecodable_bypassed_success"}, **ERR_UNDECODABLE)
1205          add_spender(spenders, "opsuccess/bigpush", standard=False, tap=tap, leaf="bigpush_success", failure={"leaf": "bigpush_nop"}, **ERR_PUSH_LIMIT)
1206          add_spender(spenders, "opsuccess/1001push", standard=False, tap=tap, leaf="1001push_success", failure={"leaf": "1001push_nop"}, **ERR_STACK_SIZE)
1207          add_spender(spenders, "opsuccess/1001inputs", standard=False, tap=tap, leaf="bare_success", inputs=[b'']*1001, failure={"leaf": "bare_nop"}, **ERR_STACK_SIZE)
1208  
1209      # Non-OP_SUCCESSx (verify that those aren't accidentally treated as OP_SUCCESSx)
1210      for opval in range(0, 0x100):
1211          opcode = CScriptOp(opval)
1212          if is_op_success(opcode):
1213              continue
1214          scripts = [
1215              ("normal", CScript([OP_RETURN, opcode] + [OP_NOP] * 75)),
1216              ("op_success", CScript([OP_RETURN, CScriptOp(0x50)]))
1217          ]
1218          tap = taproot_construct(pubs[0], scripts)
1219          add_spender(spenders, "alwaysvalid/notsuccessx", tap=tap, leaf="op_success", inputs=[], standard=False, failure={"leaf": "normal"}) # err_msg differs based on opcode
1220  
1221      # == Test case for https://github.com/limenka/limenka/issues/24765 ==
1222  
1223      zero_fn = lambda h: bytes([0 for _ in range(32)])
1224      tap = taproot_construct(pubs[0], [("leaf", CScript([pubs[1], OP_CHECKSIG, pubs[1], OP_CHECKSIGADD, OP_2, OP_EQUAL])), zero_fn])
1225      add_spender(spenders, "case24765", tap=tap, leaf="leaf", inputs=[getter("sign"), getter("sign")], key=secs[1], no_fail=True)
1226  
1227      # == Legacy tests ==
1228  
1229      # Also add a few legacy spends into the mix, so that transactions which combine taproot and pre-taproot spends get tested too.
1230      for compressed in [False, True]:
1231          eckey1, pubkey1 = generate_keypair(compressed=compressed)
1232          eckey2, _ = generate_keypair(compressed=compressed)
1233          for p2sh in [False, True]:
1234              for witv0 in [False, True]:
1235                  for hashtype in VALID_SIGHASHES_ECDSA + [random.randrange(0x04, 0x80), random.randrange(0x84, 0x100)]:
1236                      standard = (hashtype in VALID_SIGHASHES_ECDSA) and (compressed or not witv0)
1237                      add_spender(spenders, "legacy/pk-wrongkey", hashtype=hashtype, p2sh=p2sh, witv0=witv0, standard=standard, script=key_to_p2pk_script(pubkey1), **SINGLE_SIG, key=eckey1, failure={"key": eckey2}, sigops_weight=4-3*witv0, **ERR_NO_SUCCESS)
1238                      add_spender(spenders, "legacy/pkh-sighashflip", hashtype=hashtype, p2sh=p2sh, witv0=witv0, standard=standard, pkh=pubkey1, key=eckey1, **SIGHASH_BITFLIP, sigops_weight=4-3*witv0, **ERR_NO_SUCCESS)
1239  
1240      # Verify that OP_CHECKSIGADD wasn't accidentally added to pre-taproot validation logic.
1241      for p2sh in [False, True]:
1242          for witv0 in [False, True]:
1243              for hashtype in VALID_SIGHASHES_ECDSA + [random.randrange(0x04, 0x80), random.randrange(0x84, 0x100)]:
1244                  standard = hashtype in VALID_SIGHASHES_ECDSA and (p2sh or witv0)
1245                  add_spender(spenders, "compat/nocsa", hashtype=hashtype, p2sh=p2sh, witv0=witv0, standard=standard, script=CScript([OP_IF, OP_11, pubkey1, OP_CHECKSIGADD, OP_12, OP_EQUAL, OP_ELSE, pubkey1, OP_CHECKSIG, OP_ENDIF]), key=eckey1, sigops_weight=4-3*witv0, inputs=[getter("sign"), b''], failure={"inputs": [getter("sign"), b'\x01']}, **ERR_UNDECODABLE)
1246  
1247      # == sighash caching tests ==
1248  
1249      # Sighash caching in legacy.
1250      for p2sh in [False, True]:
1251          for witv0 in [False, True]:
1252              eckey1, pubkey1 = generate_keypair(compressed=compressed)
1253              for _ in range(10):
1254                  # Construct a script with 20 checksig operations (10 sighash types, each 2 times),
1255                  # randomly ordered and interleaved with 4 OP_CODESEPARATORS.
1256                  ops = [1, 2, 3, 0x21, 0x42, 0x63, 0x81, 0x83, 0xe1, 0xc2, -1, -1] * 2
1257                  # Make sure no OP_CODESEPARATOR appears last.
1258                  while True:
1259                      random.shuffle(ops)
1260                      if ops[-1] != -1:
1261                          break
1262                  script = [pubkey1]
1263                  inputs = []
1264                  codeseps = -1
1265                  for pos, op in enumerate(ops):
1266                      if op == -1:
1267                          codeseps += 1
1268                          script.append(OP_CODESEPARATOR)
1269                      elif pos + 1 != len(ops):
1270                          script += [OP_TUCK, OP_CHECKSIGVERIFY]
1271                          inputs.append(getter("sign", codesepnum=codeseps, hashtype=op))
1272                      else:
1273                          script += [OP_CHECKSIG]
1274                          inputs.append(getter("sign", codesepnum=codeseps, hashtype=op))
1275                  inputs.reverse()
1276                  script = CScript(script)
1277                  add_spender(spenders, "sighashcache/legacy", p2sh=p2sh, witv0=witv0, standard=False, script=script, inputs=inputs, key=eckey1, sigops_weight=12*8*(4-3*witv0), no_fail=True)
1278  
1279      # Sighash caching in tapscript.
1280      for _ in range(10):
1281          # Construct a script with 700 checksig operations (7 sighash types, each 100 times),
1282          # randomly ordered and interleaved with 100 OP_CODESEPARATORS.
1283          ops = [0, 1, 2, 3, 0x81, 0x82, 0x83, -1] * 100
1284          # Make sure no OP_CODESEPARATOR appears last.
1285          while True:
1286              random.shuffle(ops)
1287              if ops[-1] != -1:
1288                   break
1289          script = [pubs[1]]
1290          inputs = []
1291          opcount = 1
1292          codeseppos = -1
1293          for pos, op in enumerate(ops):
1294              if op == -1:
1295                  codeseppos = opcount
1296                  opcount += 1
1297                  script.append(OP_CODESEPARATOR)
1298              elif pos + 1 != len(ops):
1299                  opcount += 2
1300                  script += [OP_TUCK, OP_CHECKSIGVERIFY]
1301                  inputs.append(getter("sign", codeseppos=codeseppos, hashtype=op))
1302              else:
1303                  opcount += 1
1304                  script += [OP_CHECKSIG]
1305                  inputs.append(getter("sign", codeseppos=codeseppos, hashtype=op))
1306          inputs.reverse()
1307          script = CScript(script)
1308          tap = taproot_construct(pubs[0], [("leaf", script)])
1309          add_spender(spenders, "sighashcache/taproot", tap=tap, leaf="leaf", inputs=inputs, standard=True, key=secs[1], no_fail=True)
1310  
1311      return spenders
1312  
1313  
1314  def spenders_taproot_nonstandard():
1315      """Spenders for testing that post-activation Taproot rules may be nonstandard."""
1316  
1317      spenders = []
1318  
1319      sec = generate_privkey()
1320      pub, _ = compute_xonly_pubkey(sec)
1321      scripts = [
1322          ("future_leaf", CScript([pub, OP_CHECKSIG]), 0xc2),
1323          ("op_success", CScript([pub, OP_CHECKSIG, OP_0, OP_IF, CScriptOp(0x50), OP_ENDIF])),
1324      ]
1325      tap = taproot_construct(pub, scripts)
1326  
1327      # Test that features like annex, leaf versions, or OP_SUCCESS are valid but non-standard
1328      add_spender(spenders, "inactive/scriptpath_valid_unkleaf", key=sec, tap=tap, leaf="future_leaf", standard=False, inputs=[getter("sign")])
1329      add_spender(spenders, "inactive/scriptpath_invalid_unkleaf", key=sec, tap=tap, leaf="future_leaf", standard=False, inputs=[getter("sign")], sighash=bitflipper(default_sighash))
1330      add_spender(spenders, "inactive/scriptpath_valid_opsuccess", key=sec, tap=tap, leaf="op_success", standard=False, inputs=[getter("sign")])
1331      add_spender(spenders, "inactive/scriptpath_valid_opsuccess", key=sec, tap=tap, leaf="op_success", standard=False, inputs=[getter("sign")], sighash=bitflipper(default_sighash))
1332  
1333      return spenders
1334  
1335  # Consensus validation flags to use in dumps for tests with "legacy/" or "inactive/" prefix.
1336  LEGACY_FLAGS = "P2SH,DERSIG,CHECKLOCKTIMEVERIFY,CHECKSEQUENCEVERIFY,WITNESS,NULLDUMMY"
1337  # Consensus validation flags to use in dumps for all other tests.
1338  TAPROOT_FLAGS = "P2SH,DERSIG,CHECKLOCKTIMEVERIFY,CHECKSEQUENCEVERIFY,WITNESS,NULLDUMMY,TAPROOT"
1339  
1340  def dump_json_test(tx, input_utxos, idx, success, failure):
1341      spender = input_utxos[idx].spender
1342      # Determine flags to dump
1343      flags = LEGACY_FLAGS if spender.comment.startswith("legacy/") or spender.comment.startswith("inactive/") else TAPROOT_FLAGS
1344  
1345      fields = [
1346          ("tx", tx.serialize().hex()),
1347          ("prevouts", [x.output.serialize().hex() for x in input_utxos]),
1348          ("index", idx),
1349          ("flags", flags),
1350          ("comment", spender.comment)
1351      ]
1352  
1353      # The "final" field indicates that a spend should be always valid, even with more validation flags enabled
1354      # than the listed ones. Use standardness as a proxy for this (which gives a conservative underestimate).
1355      if spender.is_standard:
1356          fields.append(("final", True))
1357  
1358      def dump_witness(wit):
1359          return OrderedDict([("scriptSig", wit[0].hex()), ("witness", [x.hex() for x in wit[1]])])
1360      if success is not None:
1361          fields.append(("success", dump_witness(success)))
1362      if failure is not None:
1363          fields.append(("failure", dump_witness(failure)))
1364  
1365      # Write the dump to $TEST_DUMP_DIR/x/xyz... where x,y,z,... are the SHA1 sum of the dump (which makes the
1366      # file naming scheme compatible with fuzzing infrastructure).
1367      dump = json.dumps(OrderedDict(fields)) + ",\n"
1368      sha1 = hashlib.sha1(dump.encode("utf-8")).hexdigest()
1369      dirname = os.environ.get("TEST_DUMP_DIR", ".") + ("/%s" % sha1[0])
1370      os.makedirs(dirname, exist_ok=True)
1371      with open(dirname + ("/%s" % sha1), 'w', encoding="utf8") as f:
1372          f.write(dump)
1373  
1374  # Data type to keep track of UTXOs, where they were created, and how to spend them.
1375  UTXOData = namedtuple('UTXOData', 'outpoint,output,spender')
1376  
1377  
1378  class TaprootTest(LimenkaTestFramework):
1379      def add_options(self, parser):
1380          self.add_wallet_options(parser)
1381          parser.add_argument("--dumptests", dest="dump_tests", default=False, action="store_true",
1382                              help="Dump generated test cases to directory set by TEST_DUMP_DIR environment variable")
1383  
1384      def skip_test_if_missing_module(self):
1385          self.skip_if_no_wallet()
1386  
1387      def set_test_params(self):
1388          self.num_nodes = 1
1389          self.setup_clean_chain = True
1390          self.extra_args = [["-datacarrierfullcount"]]
1391  
1392      def block_submit(self, node, txs, msg, err_msg, cb_pubkey=None, fees=0, sigops_weight=0, witness=False, accept=False):
1393  
1394          # Deplete block of any non-tapscript sigops using a single additional 0-value coinbase output.
1395          # It is not impossible to fit enough tapscript sigops to hit the old 80k limit without
1396          # busting txin-level limits. We simply have to account for the p2pk outputs in all
1397          # transactions.
1398          extra_output_script = CScript(bytes([OP_CHECKSIG]*((MAX_BLOCK_SIGOPS_WEIGHT - sigops_weight) // WITNESS_SCALE_FACTOR)))
1399  
1400          coinbase_tx = create_coinbase(self.lastblockheight + 1, pubkey=cb_pubkey, extra_output_script=extra_output_script, fees=fees)
1401          block = create_block(self.tip, coinbase_tx, self.lastblocktime + 1, txlist=txs)
1402          witness and add_witness_commitment(block)
1403          block.solve()
1404          block_response = node.submitblock(block.serialize().hex())
1405          if err_msg is not None:
1406              assert block_response is not None and err_msg in block_response, "Missing error message '%s' from block response '%s': %s" % (err_msg, "(None)" if block_response is None else block_response, msg)
1407          if accept:
1408              assert node.getbestblockhash() == block.hash, "Failed to accept: %s (response: %s)" % (msg, block_response)
1409              self.tip = block.sha256
1410              self.lastblockhash = block.hash
1411              self.lastblocktime += 1
1412              self.lastblockheight += 1
1413          else:
1414              assert node.getbestblockhash() == self.lastblockhash, "Failed to reject: " + msg
1415  
1416      def init_blockinfo(self, node):
1417          # Initialize variables used by block_submit().
1418          self.lastblockhash = node.getbestblockhash()
1419          self.tip = int(self.lastblockhash, 16)
1420          block = node.getblock(self.lastblockhash)
1421          self.lastblockheight = block['height']
1422          self.lastblocktime = block['time']
1423  
1424      def test_spenders(self, node, spenders, input_counts):
1425          """Run randomized tests with a number of "spenders".
1426  
1427          Steps:
1428              1) Generate an appropriate UTXO for each spender to test spend conditions
1429              2) Generate 100 random addresses of all wallet types: pkh/sh_wpkh/wpkh
1430              3) Select random number of inputs from (1)
1431              4) Select random number of addresses from (2) as outputs
1432  
1433          Each spender embodies a test; in a large randomized test, it is verified
1434          that toggling the valid argument to each lambda toggles the validity of
1435          the transaction. This is accomplished by constructing transactions consisting
1436          of all valid inputs, except one invalid one.
1437          """
1438  
1439          # Construct a bunch of sPKs that send coins back to the host wallet
1440          self.log.info("- Constructing addresses for returning coins")
1441          host_spks = []
1442          host_pubkeys = []
1443          for i in range(16):
1444              addr = node.getnewaddress(address_type=random.choice(["legacy", "p2sh-segwit", "bech32"]))
1445              info = node.getaddressinfo(addr)
1446              spk = bytes.fromhex(info['scriptPubKey'])
1447              host_spks.append(spk)
1448              host_pubkeys.append(bytes.fromhex(info['pubkey']))
1449  
1450          self.init_blockinfo(node)
1451  
1452          # Create transactions spending up to 50 of the wallet's inputs, with one output for each spender, and
1453          # one change output at the end. The transaction is constructed on the Python side to enable
1454          # having multiple outputs to the same address and outputs with no assigned address. The wallet
1455          # is then asked to sign it through signrawtransactionwithwallet, and then added to a block on the
1456          # Python side (to bypass standardness rules).
1457          self.log.info("- Creating test UTXOs...")
1458          random.shuffle(spenders)
1459          normal_utxos = []
1460          mismatching_utxos = [] # UTXOs with input that requires mismatching output position
1461          done = 0
1462          while done < len(spenders):
1463              # Compute how many UTXOs to create with this transaction
1464              count_this_tx = min(len(spenders) - done, (len(spenders) + 4) // 5, 10000)
1465  
1466              fund_tx = CTransaction()
1467              # Add the 50 highest-value inputs
1468              unspents = node.listunspent()
1469              random.shuffle(unspents)
1470              unspents.sort(key=lambda x: int(x["amount"] * 100000000), reverse=True)
1471              if len(unspents) > 50:
1472                  unspents = unspents[:50]
1473              random.shuffle(unspents)
1474              balance = 0
1475              for unspent in unspents:
1476                  balance += int(unspent["amount"] * 100000000)
1477                  txid = int(unspent["txid"], 16)
1478                  fund_tx.vin.append(CTxIn(COutPoint(txid, int(unspent["vout"])), CScript()))
1479              # Add outputs
1480              cur_progress = done / len(spenders)
1481              next_progress = (done + count_this_tx) / len(spenders)
1482              change_goal = (1.0 - 0.6 * next_progress) / (1.0 - 0.6 * cur_progress) * balance
1483              self.log.debug("Create %i UTXOs in a transaction spending %i inputs worth %.8f (sending ~%.8f to change)" % (count_this_tx, len(unspents), balance * 0.00000001, change_goal * 0.00000001))
1484              for i in range(count_this_tx):
1485                  avg = (balance - change_goal) / (count_this_tx - i)
1486                  amount = int(random.randrange(int(avg*0.85 + 0.5), int(avg*1.15 + 0.5)) + 0.5)
1487                  balance -= amount
1488                  fund_tx.vout.append(CTxOut(amount, spenders[done + i].script))
1489              # Add change
1490              fund_tx.vout.append(CTxOut(balance - 10000, random.choice(host_spks)))
1491              # Ask the wallet to sign
1492              fund_tx = tx_from_hex(node.signrawtransactionwithwallet(fund_tx.serialize().hex())["hex"])
1493              # Construct UTXOData entries
1494              fund_tx.rehash()
1495              for i in range(count_this_tx):
1496                  utxodata = UTXOData(outpoint=COutPoint(fund_tx.sha256, i), output=fund_tx.vout[i], spender=spenders[done])
1497                  if utxodata.spender.need_vin_vout_mismatch:
1498                      mismatching_utxos.append(utxodata)
1499                  else:
1500                      normal_utxos.append(utxodata)
1501                  done += 1
1502              # Mine into a block
1503              self.block_submit(node, [fund_tx], "Funding tx", None, random.choice(host_pubkeys), 10000, MAX_BLOCK_SIGOPS_WEIGHT, True, True)
1504  
1505          # Consume groups of choice(input_coins) from utxos in a tx, testing the spenders.
1506          self.log.info("- Running %i spending tests" % done)
1507          random.shuffle(normal_utxos)
1508          random.shuffle(mismatching_utxos)
1509          assert done == len(normal_utxos) + len(mismatching_utxos)
1510  
1511          left = done
1512          while left:
1513              # Construct CTransaction with random version, nLocktime
1514              tx = CTransaction()
1515              tx.version = random.choice(TX_STANDARD_VERSIONS + [0, TX_MAX_STANDARD_VERSION + 1, random.getrandbits(32)])
1516              min_sequence = (tx.version != 1 and tx.version != 0) * 0x80000000  # The minimum sequence number to disable relative locktime
1517              if random.choice([True, False]):
1518                  tx.nLockTime = random.randrange(LOCKTIME_THRESHOLD, self.lastblocktime - 7200)  # all absolute locktimes in the past
1519              else:
1520                  tx.nLockTime = random.randrange(self.lastblockheight + 1)  # all block heights in the past
1521  
1522              # Decide how many UTXOs to test with.
1523              acceptable = [n for n in input_counts if n <= left and (left - n > max(input_counts) or (left - n) in [0] + input_counts)]
1524              num_inputs = random.choice(acceptable)
1525  
1526              # If we have UTXOs that require mismatching inputs/outputs left, include exactly one of those
1527              # unless there is only one normal UTXO left (as tests with mismatching UTXOs require at least one
1528              # normal UTXO to go in the first position), and we don't want to run out of normal UTXOs.
1529              input_utxos = []
1530              while len(mismatching_utxos) and (len(input_utxos) == 0 or len(normal_utxos) == 1):
1531                  input_utxos.append(mismatching_utxos.pop())
1532                  left -= 1
1533  
1534              # Top up until we hit num_inputs (but include at least one normal UTXO always).
1535              for _ in range(max(1, num_inputs - len(input_utxos))):
1536                  input_utxos.append(normal_utxos.pop())
1537                  left -= 1
1538  
1539              # The first input cannot require a mismatching output (as there is at least one output).
1540              while True:
1541                  random.shuffle(input_utxos)
1542                  if not input_utxos[0].spender.need_vin_vout_mismatch:
1543                      break
1544              first_mismatch_input = None
1545              for i in range(len(input_utxos)):
1546                  if input_utxos[i].spender.need_vin_vout_mismatch:
1547                      first_mismatch_input = i
1548              assert first_mismatch_input is None or first_mismatch_input > 0
1549  
1550              # Decide fee, and add CTxIns to tx.
1551              amount = sum(utxo.output.nValue for utxo in input_utxos)
1552              fee = min(random.randrange(MIN_FEE * 2, MIN_FEE * 4), amount - DUST_LIMIT)  # 10000-20000 sat fee
1553              in_value = amount - fee
1554              tx.vin = [CTxIn(outpoint=utxo.outpoint, nSequence=random.randint(min_sequence, 0xffffffff)) for utxo in input_utxos]
1555              tx.wit.vtxinwit = [CTxInWitness() for _ in range(len(input_utxos))]
1556              sigops_weight = sum(utxo.spender.sigops_weight for utxo in input_utxos)
1557              self.log.debug("Test: %s" % (", ".join(utxo.spender.comment for utxo in input_utxos)))
1558  
1559              # Add 1 to 4 random outputs (but constrained by inputs that require mismatching outputs)
1560              num_outputs = random.choice(range(1, 1 + min(4, 4 if first_mismatch_input is None else first_mismatch_input)))
1561              assert in_value >= 0 and fee - num_outputs * DUST_LIMIT >= MIN_FEE
1562              for i in range(num_outputs):
1563                  tx.vout.append(CTxOut())
1564                  if in_value <= DUST_LIMIT:
1565                      tx.vout[-1].nValue = DUST_LIMIT
1566                  elif i < num_outputs - 1:
1567                      tx.vout[-1].nValue = in_value
1568                  else:
1569                      tx.vout[-1].nValue = random.randint(DUST_LIMIT, in_value)
1570                  in_value -= tx.vout[-1].nValue
1571                  tx.vout[-1].scriptPubKey = random.choice(host_spks)
1572                  sigops_weight += CScript(tx.vout[-1].scriptPubKey).GetSigOpCount(False) * WITNESS_SCALE_FACTOR
1573              fee += in_value
1574              assert fee >= 0
1575  
1576              # Select coinbase pubkey
1577              cb_pubkey = random.choice(host_pubkeys)
1578              sigops_weight += 1 * WITNESS_SCALE_FACTOR
1579  
1580              # Precompute one satisfying and one failing scriptSig/witness for each input.
1581              input_data = []
1582              for i in range(len(input_utxos)):
1583                  fn = input_utxos[i].spender.sat_function
1584                  fail = None
1585                  success = fn(tx, i, [utxo.output for utxo in input_utxos], True)
1586                  if not input_utxos[i].spender.no_fail:
1587                      fail = fn(tx, i, [utxo.output for utxo in input_utxos], False)
1588                  input_data.append((fail, success))
1589                  if self.options.dump_tests:
1590                      dump_json_test(tx, input_utxos, i, success, fail)
1591  
1592              # Sign each input incorrectly once on each complete signing pass, except the very last.
1593              for fail_input in list(range(len(input_utxos))) + [None]:
1594                  # Skip trying to fail at spending something that can't be made to fail.
1595                  if fail_input is not None and input_utxos[fail_input].spender.no_fail:
1596                      continue
1597                  # Expected message with each input failure, may be None(which is ignored)
1598                  expected_fail_msg = None if fail_input is None else input_utxos[fail_input].spender.err_msg
1599                  # Fill inputs/witnesses
1600                  for i in range(len(input_utxos)):
1601                      tx.vin[i].scriptSig = input_data[i][i != fail_input][0]
1602                      tx.wit.vtxinwit[i].scriptWitness.stack = input_data[i][i != fail_input][1]
1603                  # Submit to mempool to check standardness
1604                  is_standard_tx = (
1605                      fail_input is None  # Must be valid to be standard
1606                      and (all(utxo.spender.is_standard for utxo in input_utxos))  # All inputs must be standard
1607                      and tx.version in TX_STANDARD_VERSIONS # The tx version must be standard
1608                      and not (tx.version == 3 and tx.get_vsize() > TRUC_MAX_VSIZE)  # Topological standardness rules must be followed
1609                  )
1610                  tx.rehash()
1611                  msg = ','.join(utxo.spender.comment + ("*" if n == fail_input else "") for n, utxo in enumerate(input_utxos))
1612                  if is_standard_tx:
1613                      node.sendrawtransaction(tx.serialize().hex(), 0)
1614                      assert node.getmempoolentry(tx.hash) is not None, "Failed to accept into mempool: " + msg
1615                  else:
1616                      assert_raises_rpc_error(-26, None, node.sendrawtransaction, tx.serialize().hex(), 0)
1617                  # Submit in a block
1618                  self.block_submit(node, [tx], msg, witness=True, accept=fail_input is None, cb_pubkey=cb_pubkey, fees=fee, sigops_weight=sigops_weight, err_msg=expected_fail_msg)
1619  
1620              if (len(spenders) - left) // 200 > (len(spenders) - left - len(input_utxos)) // 200:
1621                  self.log.info("  - %i tests done" % (len(spenders) - left))
1622  
1623          assert left == 0
1624          assert len(normal_utxos) == 0
1625          assert len(mismatching_utxos) == 0
1626          self.log.info("  - Done")
1627  
1628      def gen_test_vectors(self):
1629          """Run a scenario that corresponds (and optionally produces) to BIP341 test vectors."""
1630  
1631          self.log.info("Unit test scenario...")
1632  
1633          # Deterministically mine coins to OP_TRUE in block 1
1634          assert_equal(self.nodes[0].getblockcount(), 0)
1635          coinbase = CTransaction()
1636          coinbase.version = 1
1637          coinbase.vin = [CTxIn(COutPoint(0, 0xffffffff), CScript([OP_1, OP_1]), SEQUENCE_FINAL)]
1638          coinbase.vout = [CTxOut(5000000000, CScript([OP_1]))]
1639          coinbase.nLockTime = 0
1640          coinbase.rehash()
1641          assert coinbase.hash == "f60c73405d499a956d3162e3483c395526ef78286458a4cb17b125aa92e49b20"
1642          # Mine it
1643          block = create_block(hashprev=int(self.nodes[0].getbestblockhash(), 16), coinbase=coinbase)
1644          block.rehash()
1645          block.solve()
1646          self.nodes[0].submitblock(block.serialize().hex())
1647          assert_equal(self.nodes[0].getblockcount(), 1)
1648          self.generate(self.nodes[0], COINBASE_MATURITY)
1649  
1650          SEED = 317
1651          VALID_LEAF_VERS = list(range(0xc0, 0x100, 2)) + [0x66, 0x7e, 0x80, 0x84, 0x96, 0x98, 0xba, 0xbc, 0xbe]
1652          # Generate private keys
1653          prvs = [hashlib.sha256(SEED.to_bytes(2, 'big') + bytes([i])).digest() for i in range(100)]
1654          # Generate corresponding public x-only pubkeys
1655          pubs = [compute_xonly_pubkey(prv)[0] for prv in prvs]
1656          # Generate taproot objects
1657          inner_keys = [pubs[i] for i in range(7)]
1658  
1659          script_lists = [
1660              None,
1661              [("0", CScript([pubs[50], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT)],
1662              [("0", CScript([pubs[51], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT)],
1663              [("0", CScript([pubs[52], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT), ("1", CScript([b"BIP341"]), VALID_LEAF_VERS[pubs[99][0] % 41])],
1664              [("0", CScript([pubs[53], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT), ("1", CScript([b"Taproot"]), VALID_LEAF_VERS[pubs[99][1] % 41])],
1665              [("0", CScript([pubs[54], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT),
1666                  [("1", CScript([pubs[55], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT), ("2", CScript([pubs[56], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT)]
1667              ],
1668              [("0", CScript([pubs[57], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT),
1669                  [("1", CScript([pubs[58], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT), ("2", CScript([pubs[59], OP_CHECKSIG]), LEAF_VERSION_TAPSCRIPT)]
1670              ],
1671          ]
1672          taps = [taproot_construct(inner_keys[i], script_lists[i]) for i in range(len(inner_keys))]
1673  
1674          # Require negated taps[0]
1675          assert taps[0].negflag
1676          # Require one negated and one non-negated in taps 1 and 2.
1677          assert taps[1].negflag != taps[2].negflag
1678          # Require one negated and one non-negated in taps 3 and 4.
1679          assert taps[3].negflag != taps[4].negflag
1680          # Require one negated and one non-negated in taps 5 and 6.
1681          assert taps[5].negflag != taps[6].negflag
1682  
1683          cblks = [{leaf: get({**DEFAULT_CONTEXT, 'tap': taps[i], 'leaf': leaf}, 'controlblock') for leaf in taps[i].leaves} for i in range(7)]
1684          # Require one swapped and one unswapped in taps 3 and 4.
1685          assert (cblks[3]['0'][33:65] < cblks[3]['1'][33:65]) != (cblks[4]['0'][33:65] < cblks[4]['1'][33:65])
1686          # Require one swapped and one unswapped in taps 5 and 6, both at the top and child level.
1687          assert (cblks[5]['0'][33:65] < cblks[5]['1'][65:]) != (cblks[6]['0'][33:65] < cblks[6]['1'][65:])
1688          assert (cblks[5]['1'][33:65] < cblks[5]['2'][33:65]) != (cblks[6]['1'][33:65] < cblks[6]['2'][33:65])
1689          # Require within taps 5 (and thus also 6) that one level is swapped and the other is not.
1690          assert (cblks[5]['0'][33:65] < cblks[5]['1'][65:]) != (cblks[5]['1'][33:65] < cblks[5]['2'][33:65])
1691  
1692          # Compute a deterministic set of scriptPubKeys
1693          tap_spks = []
1694          old_spks = []
1695          spend_info = {}
1696          # First, taproot scriptPubKeys, for the tap objects constructed above
1697          for i, tap in enumerate(taps):
1698              tap_spks.append(tap.scriptPubKey)
1699              d = {'key': prvs[i], 'tap': tap, 'mode': 'taproot'}
1700              spend_info[tap.scriptPubKey] = d
1701          # Then, a number of deterministically generated (keys 0x1,0x2,0x3) with 2x P2PKH, 1x P2WPKH spks.
1702          for i in range(1, 4):
1703              prv = ECKey()
1704              prv.set(i.to_bytes(32, 'big'), True)
1705              pub = prv.get_pubkey().get_bytes()
1706              d = {"key": prv}
1707              d["scriptcode"] = key_to_p2pkh_script(pub)
1708              d["inputs"] = [getter("sign"), pub]
1709              if i < 3:
1710                  # P2PKH
1711                  d['spk'] = key_to_p2pkh_script(pub)
1712                  d['mode'] = 'legacy'
1713              else:
1714                  # P2WPKH
1715                  d['spk'] = key_to_p2wpkh_script(pub)
1716                  d['mode'] = 'witv0'
1717              old_spks.append(d['spk'])
1718              spend_info[d['spk']] = d
1719  
1720          # Construct a deterministic chain of transactions creating UTXOs to the test's spk's (so that they
1721          # come from distinct txids).
1722          txn = []
1723          lasttxid = coinbase.sha256
1724          amount = 5000000000
1725          for i, spk in enumerate(old_spks + tap_spks):
1726              val = 42000000 * (i + 7)
1727              tx = CTransaction()
1728              tx.version = 1
1729              tx.vin = [CTxIn(COutPoint(lasttxid, i & 1), CScript([]), SEQUENCE_FINAL)]
1730              tx.vout = [CTxOut(val, spk), CTxOut(amount - val, CScript([OP_1]))]
1731              if i & 1:
1732                  tx.vout = list(reversed(tx.vout))
1733              tx.nLockTime = 0
1734              tx.rehash()
1735              amount -= val
1736              lasttxid = tx.sha256
1737              txn.append(tx)
1738              spend_info[spk]['prevout'] = COutPoint(tx.sha256, i & 1)
1739              spend_info[spk]['utxo'] = CTxOut(val, spk)
1740          # Mine those transactions
1741          self.init_blockinfo(self.nodes[0])
1742          self.block_submit(self.nodes[0], txn, "Crediting txn", None, sigops_weight=10, accept=True)
1743  
1744          # scriptPubKey computation
1745          tests = {"version": 1}
1746          spk_tests = tests.setdefault("scriptPubKey", [])
1747          for i, tap in enumerate(taps):
1748              test_case = {}
1749              given = test_case.setdefault("given", {})
1750              given['internalPubkey'] = tap.internal_pubkey.hex()
1751  
1752              def pr(node):
1753                  if node is None:
1754                      return None
1755                  elif isinstance(node, tuple):
1756                      return {"id": int(node[0]), "script": node[1].hex(), "leafVersion": node[2]}
1757                  elif len(node) == 1:
1758                      return pr(node[0])
1759                  elif len(node) == 2:
1760                      return [pr(node[0]), pr(node[1])]
1761                  else:
1762                      assert False
1763  
1764              given['scriptTree'] = pr(script_lists[i])
1765              intermediary = test_case.setdefault("intermediary", {})
1766              if len(tap.leaves):
1767                  leafhashes = intermediary.setdefault('leafHashes', [None] * len(tap.leaves))
1768                  for leaf in tap.leaves:
1769                      leafhashes[int(leaf)] = tap.leaves[leaf].leaf_hash.hex()
1770              intermediary['merkleRoot'] = tap.merkle_root.hex() if tap.merkle_root else None
1771              intermediary['tweak'] = tap.tweak.hex()
1772              intermediary['tweakedPubkey'] = tap.output_pubkey.hex()
1773              expected = test_case.setdefault("expected", {})
1774              expected['scriptPubKey'] = tap.scriptPubKey.hex()
1775              expected['bip350Address'] = program_to_witness(1, bytes(tap.output_pubkey), True)
1776              if len(tap.leaves):
1777                  control_blocks = expected.setdefault("scriptPathControlBlocks", [None] * len(tap.leaves))
1778                  for leaf in tap.leaves:
1779                      ctx = {**DEFAULT_CONTEXT, 'tap': tap, 'leaf': leaf}
1780                      control_blocks[int(leaf)] = get(ctx, "controlblock").hex()
1781              spk_tests.append(test_case)
1782  
1783          # Construct a deterministic transaction spending all outputs created above.
1784          tx = CTransaction()
1785          tx.version = 2
1786          tx.vin = []
1787          inputs = []
1788          input_spks = [tap_spks[0], tap_spks[1], old_spks[0], tap_spks[2], tap_spks[5], old_spks[2], tap_spks[6], tap_spks[3], tap_spks[4]]
1789          sequences = [0, SEQUENCE_FINAL, SEQUENCE_FINAL, 0xfffffffe, 0xfffffffe, 0, 0, SEQUENCE_FINAL, SEQUENCE_FINAL]
1790          hashtypes = [SIGHASH_SINGLE, SIGHASH_SINGLE|SIGHASH_ANYONECANPAY, SIGHASH_ALL, SIGHASH_ALL, SIGHASH_DEFAULT, SIGHASH_ALL, SIGHASH_NONE, SIGHASH_NONE|SIGHASH_ANYONECANPAY, SIGHASH_ALL|SIGHASH_ANYONECANPAY]
1791          for i, spk in enumerate(input_spks):
1792              tx.vin.append(CTxIn(spend_info[spk]['prevout'], CScript(), sequences[i]))
1793              inputs.append(spend_info[spk]['utxo'])
1794          tx.vout.append(CTxOut(1000000000, old_spks[1]))
1795          tx.vout.append(CTxOut(3410000000, pubs[98]))
1796          tx.nLockTime = 500000000
1797          precomputed = {
1798              "hashAmounts": BIP341_sha_amounts(inputs),
1799              "hashPrevouts": BIP341_sha_prevouts(tx),
1800              "hashScriptPubkeys": BIP341_sha_scriptpubkeys(inputs),
1801              "hashSequences": BIP341_sha_sequences(tx),
1802              "hashOutputs": BIP341_sha_outputs(tx)
1803          }
1804          keypath_tests = tests.setdefault("keyPathSpending", [])
1805          tx_test = {}
1806          global_given = tx_test.setdefault("given", {})
1807          global_given['rawUnsignedTx'] = tx.serialize().hex()
1808          utxos_spent = global_given.setdefault("utxosSpent", [])
1809          for i in range(len(input_spks)):
1810              utxos_spent.append({"scriptPubKey": inputs[i].scriptPubKey.hex(), "amountSats": inputs[i].nValue})
1811          global_intermediary = tx_test.setdefault("intermediary", {})
1812          for key in sorted(precomputed.keys()):
1813              global_intermediary[key] = precomputed[key].hex()
1814          test_list = tx_test.setdefault('inputSpending', [])
1815          for i in range(len(input_spks)):
1816              ctx = {
1817                  **DEFAULT_CONTEXT,
1818                  **spend_info[input_spks[i]],
1819                  'tx': tx,
1820                  'utxos': inputs,
1821                  'idx': i,
1822                  'hashtype': hashtypes[i],
1823                  'deterministic': True
1824              }
1825              if ctx['mode'] == 'taproot':
1826                  test_case = {}
1827                  given = test_case.setdefault("given", {})
1828                  given['txinIndex'] = i
1829                  given['internalPrivkey'] = get(ctx, 'key').hex()
1830                  if get(ctx, "tap").merkle_root != bytes():
1831                      given['merkleRoot'] = get(ctx, "tap").merkle_root.hex()
1832                  else:
1833                      given['merkleRoot'] = None
1834                  given['hashType'] = get(ctx, "hashtype")
1835                  intermediary = test_case.setdefault("intermediary", {})
1836                  intermediary['internalPubkey'] = get(ctx, "tap").internal_pubkey.hex()
1837                  intermediary['tweak'] = get(ctx, "tap").tweak.hex()
1838                  intermediary['tweakedPrivkey'] = get(ctx, "key_tweaked").hex()
1839                  sigmsg = get(ctx, "sigmsg")
1840                  intermediary['sigMsg'] = sigmsg.hex()
1841                  intermediary['precomputedUsed'] = [key for key in sorted(precomputed.keys()) if sigmsg.count(precomputed[key])]
1842                  intermediary['sigHash'] = get(ctx, "sighash").hex()
1843                  expected = test_case.setdefault("expected", {})
1844                  expected['witness'] = [get(ctx, "sign").hex()]
1845                  test_list.append(test_case)
1846              tx.wit.vtxinwit.append(CTxInWitness())
1847              tx.vin[i].scriptSig = CScript(flatten(get(ctx, "scriptsig")))
1848              tx.wit.vtxinwit[i].scriptWitness.stack = flatten(get(ctx, "witness"))
1849          aux = tx_test.setdefault("auxiliary", {})
1850          aux['fullySignedTx'] = tx.serialize().hex()
1851          keypath_tests.append(tx_test)
1852          assert_equal(hashlib.sha256(tx.serialize()).hexdigest(), "24bab662cb55a7f3bae29b559f651674c62bcc1cd442d44715c0133939107b38")
1853          # Mine the spending transaction
1854          self.block_submit(self.nodes[0], [tx], "Spending txn", None, sigops_weight=10000, accept=True, witness=True)
1855  
1856          if GEN_TEST_VECTORS:
1857              print(json.dumps(tests, indent=4, sort_keys=False))
1858  
1859      def run_test(self):
1860          self.gen_test_vectors()
1861  
1862          self.log.info("Post-activation tests...")
1863          self.test_spenders(self.nodes[0], spenders_taproot_active(), input_counts=[1, 2, 2, 2, 2, 3])
1864          # Run each test twice; once in isolation, and once combined with others. Testing in isolation
1865          # means that the standardness is verified in every test (as combined transactions are only standard
1866          # when all their inputs are standard).
1867          self.test_spenders(self.nodes[0], spenders_taproot_nonstandard(), input_counts=[1])
1868          self.test_spenders(self.nodes[0], spenders_taproot_nonstandard(), input_counts=[2, 3])
1869  
1870  
1871  if __name__ == '__main__':
1872      TaprootTest(__file__).main()
1873