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