feature_taproot.py raw

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