script.py raw

   1  #!/usr/bin/env python3
   2  # Copyright (c) 2015-present The Bitcoin Core developers
   3  # Distributed under the MIT software license, see the accompanying
   4  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  """Functionality to build scripts, as well as signature hash functions.
   6  
   7  This file is modified from python-bitcoinlib.
   8  """
   9  
  10  from collections import namedtuple
  11  import unittest
  12  
  13  from .key import TaggedHash, tweak_add_pubkey, compute_xonly_pubkey
  14  
  15  from .messages import (
  16      CTransaction,
  17      CTxOut,
  18      hash256,
  19      ser_string,
  20      sha256,
  21  )
  22  
  23  from .crypto.ripemd160 import ripemd160
  24  from .util import assert_equal
  25  
  26  MAX_SCRIPT_ELEMENT_SIZE = 520
  27  MAX_SCRIPT_SIZE = 10000
  28  MAX_PUBKEYS_PER_MULTI_A = 999
  29  LOCKTIME_THRESHOLD = 500000000
  30  ANNEX_TAG = 0x50
  31  
  32  SEQUENCE_LOCKTIME_DISABLE_FLAG = (1<<31)
  33  SEQUENCE_LOCKTIME_TYPE_FLAG = (1<<22) # this means use time (0 means height)
  34  SEQUENCE_LOCKTIME_GRANULARITY = 9 # this is a bit-shift
  35  SEQUENCE_LOCKTIME_MASK = 0x0000ffff
  36  
  37  LEAF_VERSION_TAPSCRIPT = 0xc0
  38  
  39  def hash160(s):
  40      return ripemd160(sha256(s))
  41  
  42  def bn2vch(v):
  43      """Convert number to bitcoin-specific little endian format."""
  44      # We need v.bit_length() bits, plus a sign bit for every nonzero number.
  45      n_bits = v.bit_length() + (v != 0)
  46      # The number of bytes for that is:
  47      n_bytes = (n_bits + 7) // 8
  48      # Convert number to absolute value + sign in top bit.
  49      encoded_v = 0 if v == 0 else abs(v) | ((v < 0) << (n_bytes * 8 - 1))
  50      # Serialize to bytes
  51      return encoded_v.to_bytes(n_bytes, 'little')
  52  
  53  class CScriptOp(int):
  54      """A single script opcode"""
  55      __slots__ = ()
  56  
  57      @staticmethod
  58      def encode_op_pushdata(d):
  59          """Encode a PUSHDATA op, returning bytes"""
  60          if len(d) < 0x4c:
  61              return b'' + bytes([len(d)]) + d  # OP_PUSHDATA
  62          elif len(d) <= 0xff:
  63              return b'\x4c' + bytes([len(d)]) + d  # OP_PUSHDATA1
  64          elif len(d) <= 0xffff:
  65              return b'\x4d' + len(d).to_bytes(2, "little") + d  # OP_PUSHDATA2
  66          elif len(d) <= 0xffffffff:
  67              return b'\x4e' + len(d).to_bytes(4, "little") + d  # OP_PUSHDATA4
  68          else:
  69              raise ValueError("Data too long to encode in a PUSHDATA op")
  70  
  71      @staticmethod
  72      def encode_op_n(n):
  73          """Encode a small integer op, returning an opcode"""
  74          if not (0 <= n <= 16):
  75              raise ValueError('Integer must be in range 0 <= n <= 16, got %d' % n)
  76  
  77          if n == 0:
  78              return OP_0
  79          else:
  80              return CScriptOp(OP_1 + n - 1)
  81  
  82      def decode_op_n(self):
  83          """Decode a small integer opcode, returning an integer"""
  84          if self == OP_0:
  85              return 0
  86  
  87          if not (self == OP_0 or OP_1 <= self <= OP_16):
  88              raise ValueError('op %r is not an OP_N' % self)
  89  
  90          return int(self - OP_1 + 1)
  91  
  92      def is_small_int(self):
  93          """Return true if the op pushes a small integer to the stack"""
  94          if 0x51 <= self <= 0x60 or self == 0:
  95              return True
  96          else:
  97              return False
  98  
  99      def __str__(self):
 100          return repr(self)
 101  
 102      def __repr__(self):
 103          if self in OPCODE_NAMES:
 104              return OPCODE_NAMES[self]
 105          else:
 106              return 'CScriptOp(0x%x)' % self
 107  
 108      def __new__(cls, n):
 109          try:
 110              return _opcode_instances[n]
 111          except IndexError:
 112              assert_equal(len(_opcode_instances), n)
 113              _opcode_instances.append(super().__new__(cls, n))
 114              return _opcode_instances[n]
 115  
 116  OPCODE_NAMES: dict[CScriptOp, str] = {}
 117  _opcode_instances: list[CScriptOp] = []
 118  
 119  # Populate opcode instance table
 120  for n in range(0xff + 1):
 121      CScriptOp(n)
 122  
 123  
 124  # push value
 125  OP_0 = CScriptOp(0x00)
 126  OP_FALSE = OP_0
 127  OP_PUSHDATA1 = CScriptOp(0x4c)
 128  OP_PUSHDATA2 = CScriptOp(0x4d)
 129  OP_PUSHDATA4 = CScriptOp(0x4e)
 130  OP_1NEGATE = CScriptOp(0x4f)
 131  OP_RESERVED = CScriptOp(0x50)
 132  OP_1 = CScriptOp(0x51)
 133  OP_TRUE = OP_1
 134  OP_2 = CScriptOp(0x52)
 135  OP_3 = CScriptOp(0x53)
 136  OP_4 = CScriptOp(0x54)
 137  OP_5 = CScriptOp(0x55)
 138  OP_6 = CScriptOp(0x56)
 139  OP_7 = CScriptOp(0x57)
 140  OP_8 = CScriptOp(0x58)
 141  OP_9 = CScriptOp(0x59)
 142  OP_10 = CScriptOp(0x5a)
 143  OP_11 = CScriptOp(0x5b)
 144  OP_12 = CScriptOp(0x5c)
 145  OP_13 = CScriptOp(0x5d)
 146  OP_14 = CScriptOp(0x5e)
 147  OP_15 = CScriptOp(0x5f)
 148  OP_16 = CScriptOp(0x60)
 149  
 150  # control
 151  OP_NOP = CScriptOp(0x61)
 152  OP_VER = CScriptOp(0x62)
 153  OP_IF = CScriptOp(0x63)
 154  OP_NOTIF = CScriptOp(0x64)
 155  OP_VERIF = CScriptOp(0x65)
 156  OP_VERNOTIF = CScriptOp(0x66)
 157  OP_ELSE = CScriptOp(0x67)
 158  OP_ENDIF = CScriptOp(0x68)
 159  OP_VERIFY = CScriptOp(0x69)
 160  OP_RETURN = CScriptOp(0x6a)
 161  
 162  # stack ops
 163  OP_TOALTSTACK = CScriptOp(0x6b)
 164  OP_FROMALTSTACK = CScriptOp(0x6c)
 165  OP_2DROP = CScriptOp(0x6d)
 166  OP_2DUP = CScriptOp(0x6e)
 167  OP_3DUP = CScriptOp(0x6f)
 168  OP_2OVER = CScriptOp(0x70)
 169  OP_2ROT = CScriptOp(0x71)
 170  OP_2SWAP = CScriptOp(0x72)
 171  OP_IFDUP = CScriptOp(0x73)
 172  OP_DEPTH = CScriptOp(0x74)
 173  OP_DROP = CScriptOp(0x75)
 174  OP_DUP = CScriptOp(0x76)
 175  OP_NIP = CScriptOp(0x77)
 176  OP_OVER = CScriptOp(0x78)
 177  OP_PICK = CScriptOp(0x79)
 178  OP_ROLL = CScriptOp(0x7a)
 179  OP_ROT = CScriptOp(0x7b)
 180  OP_SWAP = CScriptOp(0x7c)
 181  OP_TUCK = CScriptOp(0x7d)
 182  
 183  # splice ops
 184  OP_CAT = CScriptOp(0x7e)
 185  OP_SUBSTR = CScriptOp(0x7f)
 186  OP_LEFT = CScriptOp(0x80)
 187  OP_RIGHT = CScriptOp(0x81)
 188  OP_SIZE = CScriptOp(0x82)
 189  
 190  # bit logic
 191  OP_INVERT = CScriptOp(0x83)
 192  OP_AND = CScriptOp(0x84)
 193  OP_OR = CScriptOp(0x85)
 194  OP_XOR = CScriptOp(0x86)
 195  OP_EQUAL = CScriptOp(0x87)
 196  OP_EQUALVERIFY = CScriptOp(0x88)
 197  OP_RESERVED1 = CScriptOp(0x89)
 198  OP_RESERVED2 = CScriptOp(0x8a)
 199  
 200  # numeric
 201  OP_1ADD = CScriptOp(0x8b)
 202  OP_1SUB = CScriptOp(0x8c)
 203  OP_2MUL = CScriptOp(0x8d)
 204  OP_2DIV = CScriptOp(0x8e)
 205  OP_NEGATE = CScriptOp(0x8f)
 206  OP_ABS = CScriptOp(0x90)
 207  OP_NOT = CScriptOp(0x91)
 208  OP_0NOTEQUAL = CScriptOp(0x92)
 209  
 210  OP_ADD = CScriptOp(0x93)
 211  OP_SUB = CScriptOp(0x94)
 212  OP_MUL = CScriptOp(0x95)
 213  OP_DIV = CScriptOp(0x96)
 214  OP_MOD = CScriptOp(0x97)
 215  OP_LSHIFT = CScriptOp(0x98)
 216  OP_RSHIFT = CScriptOp(0x99)
 217  
 218  OP_BOOLAND = CScriptOp(0x9a)
 219  OP_BOOLOR = CScriptOp(0x9b)
 220  OP_NUMEQUAL = CScriptOp(0x9c)
 221  OP_NUMEQUALVERIFY = CScriptOp(0x9d)
 222  OP_NUMNOTEQUAL = CScriptOp(0x9e)
 223  OP_LESSTHAN = CScriptOp(0x9f)
 224  OP_GREATERTHAN = CScriptOp(0xa0)
 225  OP_LESSTHANOREQUAL = CScriptOp(0xa1)
 226  OP_GREATERTHANOREQUAL = CScriptOp(0xa2)
 227  OP_MIN = CScriptOp(0xa3)
 228  OP_MAX = CScriptOp(0xa4)
 229  
 230  OP_WITHIN = CScriptOp(0xa5)
 231  
 232  # crypto
 233  OP_RIPEMD160 = CScriptOp(0xa6)
 234  OP_SHA1 = CScriptOp(0xa7)
 235  OP_SHA256 = CScriptOp(0xa8)
 236  OP_HASH160 = CScriptOp(0xa9)
 237  OP_HASH256 = CScriptOp(0xaa)
 238  OP_CODESEPARATOR = CScriptOp(0xab)
 239  OP_CHECKSIG = CScriptOp(0xac)
 240  OP_CHECKSIGVERIFY = CScriptOp(0xad)
 241  OP_CHECKMULTISIG = CScriptOp(0xae)
 242  OP_CHECKMULTISIGVERIFY = CScriptOp(0xaf)
 243  
 244  # expansion
 245  OP_NOP1 = CScriptOp(0xb0)
 246  OP_CHECKLOCKTIMEVERIFY = CScriptOp(0xb1)
 247  OP_CHECKSEQUENCEVERIFY = CScriptOp(0xb2)
 248  OP_NOP4 = CScriptOp(0xb3)
 249  OP_NOP5 = CScriptOp(0xb4)
 250  OP_NOP6 = CScriptOp(0xb5)
 251  OP_NOP7 = CScriptOp(0xb6)
 252  OP_NOP8 = CScriptOp(0xb7)
 253  OP_NOP9 = CScriptOp(0xb8)
 254  OP_NOP10 = CScriptOp(0xb9)
 255  
 256  # BIP 342 opcodes (Tapscript)
 257  OP_CHECKSIGADD = CScriptOp(0xba)
 258  
 259  OP_INVALIDOPCODE = CScriptOp(0xff)
 260  
 261  OPCODE_NAMES.update({
 262      OP_0: 'OP_0',
 263      OP_PUSHDATA1: 'OP_PUSHDATA1',
 264      OP_PUSHDATA2: 'OP_PUSHDATA2',
 265      OP_PUSHDATA4: 'OP_PUSHDATA4',
 266      OP_1NEGATE: 'OP_1NEGATE',
 267      OP_RESERVED: 'OP_RESERVED',
 268      OP_1: 'OP_1',
 269      OP_2: 'OP_2',
 270      OP_3: 'OP_3',
 271      OP_4: 'OP_4',
 272      OP_5: 'OP_5',
 273      OP_6: 'OP_6',
 274      OP_7: 'OP_7',
 275      OP_8: 'OP_8',
 276      OP_9: 'OP_9',
 277      OP_10: 'OP_10',
 278      OP_11: 'OP_11',
 279      OP_12: 'OP_12',
 280      OP_13: 'OP_13',
 281      OP_14: 'OP_14',
 282      OP_15: 'OP_15',
 283      OP_16: 'OP_16',
 284      OP_NOP: 'OP_NOP',
 285      OP_VER: 'OP_VER',
 286      OP_IF: 'OP_IF',
 287      OP_NOTIF: 'OP_NOTIF',
 288      OP_VERIF: 'OP_VERIF',
 289      OP_VERNOTIF: 'OP_VERNOTIF',
 290      OP_ELSE: 'OP_ELSE',
 291      OP_ENDIF: 'OP_ENDIF',
 292      OP_VERIFY: 'OP_VERIFY',
 293      OP_RETURN: 'OP_RETURN',
 294      OP_TOALTSTACK: 'OP_TOALTSTACK',
 295      OP_FROMALTSTACK: 'OP_FROMALTSTACK',
 296      OP_2DROP: 'OP_2DROP',
 297      OP_2DUP: 'OP_2DUP',
 298      OP_3DUP: 'OP_3DUP',
 299      OP_2OVER: 'OP_2OVER',
 300      OP_2ROT: 'OP_2ROT',
 301      OP_2SWAP: 'OP_2SWAP',
 302      OP_IFDUP: 'OP_IFDUP',
 303      OP_DEPTH: 'OP_DEPTH',
 304      OP_DROP: 'OP_DROP',
 305      OP_DUP: 'OP_DUP',
 306      OP_NIP: 'OP_NIP',
 307      OP_OVER: 'OP_OVER',
 308      OP_PICK: 'OP_PICK',
 309      OP_ROLL: 'OP_ROLL',
 310      OP_ROT: 'OP_ROT',
 311      OP_SWAP: 'OP_SWAP',
 312      OP_TUCK: 'OP_TUCK',
 313      OP_CAT: 'OP_CAT',
 314      OP_SUBSTR: 'OP_SUBSTR',
 315      OP_LEFT: 'OP_LEFT',
 316      OP_RIGHT: 'OP_RIGHT',
 317      OP_SIZE: 'OP_SIZE',
 318      OP_INVERT: 'OP_INVERT',
 319      OP_AND: 'OP_AND',
 320      OP_OR: 'OP_OR',
 321      OP_XOR: 'OP_XOR',
 322      OP_EQUAL: 'OP_EQUAL',
 323      OP_EQUALVERIFY: 'OP_EQUALVERIFY',
 324      OP_RESERVED1: 'OP_RESERVED1',
 325      OP_RESERVED2: 'OP_RESERVED2',
 326      OP_1ADD: 'OP_1ADD',
 327      OP_1SUB: 'OP_1SUB',
 328      OP_2MUL: 'OP_2MUL',
 329      OP_2DIV: 'OP_2DIV',
 330      OP_NEGATE: 'OP_NEGATE',
 331      OP_ABS: 'OP_ABS',
 332      OP_NOT: 'OP_NOT',
 333      OP_0NOTEQUAL: 'OP_0NOTEQUAL',
 334      OP_ADD: 'OP_ADD',
 335      OP_SUB: 'OP_SUB',
 336      OP_MUL: 'OP_MUL',
 337      OP_DIV: 'OP_DIV',
 338      OP_MOD: 'OP_MOD',
 339      OP_LSHIFT: 'OP_LSHIFT',
 340      OP_RSHIFT: 'OP_RSHIFT',
 341      OP_BOOLAND: 'OP_BOOLAND',
 342      OP_BOOLOR: 'OP_BOOLOR',
 343      OP_NUMEQUAL: 'OP_NUMEQUAL',
 344      OP_NUMEQUALVERIFY: 'OP_NUMEQUALVERIFY',
 345      OP_NUMNOTEQUAL: 'OP_NUMNOTEQUAL',
 346      OP_LESSTHAN: 'OP_LESSTHAN',
 347      OP_GREATERTHAN: 'OP_GREATERTHAN',
 348      OP_LESSTHANOREQUAL: 'OP_LESSTHANOREQUAL',
 349      OP_GREATERTHANOREQUAL: 'OP_GREATERTHANOREQUAL',
 350      OP_MIN: 'OP_MIN',
 351      OP_MAX: 'OP_MAX',
 352      OP_WITHIN: 'OP_WITHIN',
 353      OP_RIPEMD160: 'OP_RIPEMD160',
 354      OP_SHA1: 'OP_SHA1',
 355      OP_SHA256: 'OP_SHA256',
 356      OP_HASH160: 'OP_HASH160',
 357      OP_HASH256: 'OP_HASH256',
 358      OP_CODESEPARATOR: 'OP_CODESEPARATOR',
 359      OP_CHECKSIG: 'OP_CHECKSIG',
 360      OP_CHECKSIGVERIFY: 'OP_CHECKSIGVERIFY',
 361      OP_CHECKMULTISIG: 'OP_CHECKMULTISIG',
 362      OP_CHECKMULTISIGVERIFY: 'OP_CHECKMULTISIGVERIFY',
 363      OP_NOP1: 'OP_NOP1',
 364      OP_CHECKLOCKTIMEVERIFY: 'OP_CHECKLOCKTIMEVERIFY',
 365      OP_CHECKSEQUENCEVERIFY: 'OP_CHECKSEQUENCEVERIFY',
 366      OP_NOP4: 'OP_NOP4',
 367      OP_NOP5: 'OP_NOP5',
 368      OP_NOP6: 'OP_NOP6',
 369      OP_NOP7: 'OP_NOP7',
 370      OP_NOP8: 'OP_NOP8',
 371      OP_NOP9: 'OP_NOP9',
 372      OP_NOP10: 'OP_NOP10',
 373      OP_CHECKSIGADD: 'OP_CHECKSIGADD',
 374      OP_INVALIDOPCODE: 'OP_INVALIDOPCODE',
 375  })
 376  
 377  class CScriptInvalidError(Exception):
 378      """Base class for CScript exceptions"""
 379      pass
 380  
 381  class CScriptTruncatedPushDataError(CScriptInvalidError):
 382      """Invalid pushdata due to truncation"""
 383      def __init__(self, msg, data):
 384          self.data = data
 385          super().__init__(msg)
 386  
 387  
 388  # This is used, eg, for blockchain heights in coinbase scripts (bip34)
 389  class CScriptNum:
 390      __slots__ = ("value",)
 391  
 392      def __init__(self, d=0):
 393          self.value = d
 394  
 395      @staticmethod
 396      def encode(obj):
 397          r = bytearray(0)
 398          if obj.value == 0:
 399              return bytes(r)
 400          neg = obj.value < 0
 401          absvalue = -obj.value if neg else obj.value
 402          while (absvalue):
 403              r.append(absvalue & 0xff)
 404              absvalue >>= 8
 405          if r[-1] & 0x80:
 406              r.append(0x80 if neg else 0)
 407          elif neg:
 408              r[-1] |= 0x80
 409          return bytes([len(r)]) + r
 410  
 411      @staticmethod
 412      def decode(vch):
 413          result = 0
 414          # We assume valid push_size and minimal encoding
 415          value = vch[1:]
 416          if len(value) == 0:
 417              return result
 418          for i, byte in enumerate(value):
 419              result |= int(byte) << 8 * i
 420          if value[-1] >= 0x80:
 421              # Mask for all but the highest result bit
 422              num_mask = (2**(len(value) * 8) - 1) >> 1
 423              result &= num_mask
 424              result *= -1
 425          return result
 426  
 427  
 428  class CScript(bytes):
 429      """Serialized script
 430  
 431      A bytes subclass, so you can use this directly whenever bytes are accepted.
 432      Note that this means that indexing does *not* work - you'll get an index by
 433      byte rather than opcode. This format was chosen for efficiency so that the
 434      general case would not require creating a lot of little CScriptOP objects.
 435  
 436      iter(script) however does iterate by opcode.
 437      """
 438      __slots__ = ()
 439  
 440      @classmethod
 441      def __coerce_instance(cls, other):
 442          # Coerce other into bytes
 443          if isinstance(other, CScriptOp):
 444              other = bytes([other])
 445          elif isinstance(other, CScriptNum):
 446              if (other.value == 0):
 447                  other = bytes([CScriptOp(OP_0)])
 448              else:
 449                  other = CScriptNum.encode(other)
 450          elif isinstance(other, int):
 451              if 0 <= other <= 16:
 452                  other = bytes([CScriptOp.encode_op_n(other)])
 453              elif other == -1:
 454                  other = bytes([OP_1NEGATE])
 455              else:
 456                  other = CScriptOp.encode_op_pushdata(bn2vch(other))
 457          elif isinstance(other, (bytes, bytearray)):
 458              other = CScriptOp.encode_op_pushdata(other)
 459          return other
 460  
 461      def __add__(self, other):
 462          # add makes no sense for a CScript()
 463          raise NotImplementedError
 464  
 465      def join(self, iterable):
 466          # join makes no sense for a CScript()
 467          raise NotImplementedError
 468  
 469      def __new__(cls, value=b''):
 470          if isinstance(value, bytes) or isinstance(value, bytearray):
 471              return super().__new__(cls, value)
 472          else:
 473              def coerce_iterable(iterable):
 474                  for instance in iterable:
 475                      yield cls.__coerce_instance(instance)
 476              # Annoyingly on both python2 and python3 bytes.join() always
 477              # returns a bytes instance even when subclassed.
 478              return super().__new__(cls, b''.join(coerce_iterable(value)))
 479  
 480      def raw_iter(self):
 481          """Raw iteration
 482  
 483          Yields tuples of (opcode, data, sop_idx) so that the different possible
 484          PUSHDATA encodings can be accurately distinguished, as well as
 485          determining the exact opcode byte indexes. (sop_idx)
 486          """
 487          i = 0
 488          while i < len(self):
 489              sop_idx = i
 490              opcode = CScriptOp(self[i])
 491              i += 1
 492  
 493              if opcode > OP_PUSHDATA4:
 494                  yield (opcode, None, sop_idx)
 495              else:
 496                  datasize = None
 497                  pushdata_type = None
 498                  if opcode < OP_PUSHDATA1:
 499                      pushdata_type = 'PUSHDATA(%d)' % opcode
 500                      datasize = opcode
 501  
 502                  elif opcode == OP_PUSHDATA1:
 503                      pushdata_type = 'PUSHDATA1'
 504                      if i >= len(self):
 505                          raise CScriptInvalidError('PUSHDATA1: missing data length')
 506                      datasize = self[i]
 507                      i += 1
 508  
 509                  elif opcode == OP_PUSHDATA2:
 510                      pushdata_type = 'PUSHDATA2'
 511                      if i + 1 >= len(self):
 512                          raise CScriptInvalidError('PUSHDATA2: missing data length')
 513                      datasize = self[i] + (self[i + 1] << 8)
 514                      i += 2
 515  
 516                  elif opcode == OP_PUSHDATA4:
 517                      pushdata_type = 'PUSHDATA4'
 518                      if i + 3 >= len(self):
 519                          raise CScriptInvalidError('PUSHDATA4: missing data length')
 520                      datasize = self[i] + (self[i + 1] << 8) + (self[i + 2] << 16) + (self[i + 3] << 24)
 521                      i += 4
 522  
 523                  else:
 524                      assert False  # shouldn't happen
 525  
 526                  data = bytes(self[i:i + datasize])
 527  
 528                  # Check for truncation
 529                  if len(data) < datasize:
 530                      raise CScriptTruncatedPushDataError('%s: truncated data' % pushdata_type, data)
 531  
 532                  i += datasize
 533  
 534                  yield (opcode, data, sop_idx)
 535  
 536      def __iter__(self):
 537          """'Cooked' iteration
 538  
 539          Returns either a CScriptOP instance, an integer, or bytes, as
 540          appropriate.
 541  
 542          See raw_iter() if you need to distinguish the different possible
 543          PUSHDATA encodings.
 544          """
 545          for (opcode, data, sop_idx) in self.raw_iter():
 546              if data is not None:
 547                  yield data
 548              else:
 549                  opcode = CScriptOp(opcode)
 550  
 551                  if opcode.is_small_int():
 552                      yield opcode.decode_op_n()
 553                  else:
 554                      yield CScriptOp(opcode)
 555  
 556      def __repr__(self):
 557          def _repr(o):
 558              if isinstance(o, bytes):
 559                  return "x('%s')" % o.hex()
 560              else:
 561                  return repr(o)
 562  
 563          ops = []
 564          i = iter(self)
 565          while True:
 566              op = None
 567              try:
 568                  op = _repr(next(i))
 569              except CScriptTruncatedPushDataError as err:
 570                  op = '%s...<ERROR: %s>' % (_repr(err.data), err)
 571                  break
 572              except CScriptInvalidError as err:
 573                  op = '<ERROR: %s>' % err
 574                  break
 575              except StopIteration:
 576                  break
 577              finally:
 578                  if op is not None:
 579                      ops.append(op)
 580  
 581          return "CScript([%s])" % ', '.join(ops)
 582  
 583      def GetSigOpCount(self, fAccurate):
 584          """Get the SigOp count.
 585  
 586          fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details.
 587  
 588          Note that this is consensus-critical.
 589          """
 590          n = 0
 591          lastOpcode = OP_INVALIDOPCODE
 592          for (opcode, data, sop_idx) in self.raw_iter():
 593              if opcode in (OP_CHECKSIG, OP_CHECKSIGVERIFY):
 594                  n += 1
 595              elif opcode in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):
 596                  if fAccurate and (OP_1 <= lastOpcode <= OP_16):
 597                      n += lastOpcode.decode_op_n()
 598                  else:
 599                      n += 20
 600              lastOpcode = opcode
 601          return n
 602  
 603      def IsWitnessProgram(self):
 604          """A witness program is any valid CScript that consists of a 1-byte
 605             push opcode followed by a data push between 2 and 40 bytes."""
 606          return ((4 <= len(self) <= 42) and
 607                  (self[0] == OP_0 or (OP_1 <= self[0] <= OP_16)) and
 608                  (self[1] + 2 == len(self)))
 609  
 610  
 611  SIGHASH_DEFAULT = 0 # Taproot-only default, semantics same as SIGHASH_ALL
 612  SIGHASH_ALL = 1
 613  SIGHASH_NONE = 2
 614  SIGHASH_SINGLE = 3
 615  SIGHASH_ANYONECANPAY = 0x80
 616  
 617  def FindAndDelete(script, sig):
 618      """Consensus critical, see FindAndDelete() in Satoshi codebase"""
 619      r = b''
 620      last_sop_idx = sop_idx = 0
 621      skip = True
 622      for (opcode, data, sop_idx) in script.raw_iter():
 623          if not skip:
 624              r += script[last_sop_idx:sop_idx]
 625          last_sop_idx = sop_idx
 626          if script[sop_idx:sop_idx + len(sig)] == sig:
 627              skip = True
 628          else:
 629              skip = False
 630      if not skip:
 631          r += script[last_sop_idx:]
 632      return CScript(r)
 633  
 634  def LegacySignatureMsg(script, txTo, inIdx, hashtype):
 635      """Preimage of the signature hash, if it exists.
 636  
 637      Returns either (None, err) to indicate error (which translates to sighash 1),
 638      or (msg, None).
 639      """
 640  
 641      if inIdx >= len(txTo.vin):
 642          return (None, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin)))
 643      txtmp = CTransaction(txTo)
 644  
 645      for txin in txtmp.vin:
 646          txin.scriptSig = b''
 647      txtmp.vin[inIdx].scriptSig = FindAndDelete(script, CScript([OP_CODESEPARATOR]))
 648  
 649      if (hashtype & 0x1f) == SIGHASH_NONE:
 650          txtmp.vout = []
 651  
 652          for i in range(len(txtmp.vin)):
 653              if i != inIdx:
 654                  txtmp.vin[i].nSequence = 0
 655  
 656      elif (hashtype & 0x1f) == SIGHASH_SINGLE:
 657          outIdx = inIdx
 658          if outIdx >= len(txtmp.vout):
 659              return (None, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))
 660  
 661          tmp = txtmp.vout[outIdx]
 662          txtmp.vout = []
 663          for _ in range(outIdx):
 664              txtmp.vout.append(CTxOut(-1))
 665          txtmp.vout.append(tmp)
 666  
 667          for i in range(len(txtmp.vin)):
 668              if i != inIdx:
 669                  txtmp.vin[i].nSequence = 0
 670  
 671      if hashtype & SIGHASH_ANYONECANPAY:
 672          tmp = txtmp.vin[inIdx]
 673          txtmp.vin = []
 674          txtmp.vin.append(tmp)
 675  
 676      s = txtmp.serialize_without_witness()
 677      s += hashtype.to_bytes(4, "little")
 678  
 679      return (s, None)
 680  
 681  def LegacySignatureHash(*args, **kwargs):
 682      """Consensus-correct SignatureHash
 683  
 684      Returns (hash, err) to precisely match the consensus-critical behavior of
 685      the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity)
 686      """
 687  
 688      HASH_ONE = b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
 689      msg, err = LegacySignatureMsg(*args, **kwargs)
 690      if msg is None:
 691          return (HASH_ONE, err)
 692      else:
 693          return (hash256(msg), err)
 694  
 695  def sign_input_legacy(tx, input_index, input_scriptpubkey, privkey, sighash_type=SIGHASH_ALL):
 696      """Add legacy ECDSA signature for a given transaction input. Note that the signature
 697         is prepended to the scriptSig field, i.e. additional data pushes necessary for more
 698         complex spends than P2PK (e.g. pubkey for P2PKH) can be already set before."""
 699      (sighash, err) = LegacySignatureHash(input_scriptpubkey, tx, input_index, sighash_type)
 700      assert err is None
 701      der_sig = privkey.sign_ecdsa(sighash)
 702      tx.vin[input_index].scriptSig = bytes(CScript([der_sig + bytes([sighash_type])])) + tx.vin[input_index].scriptSig
 703  
 704  def sign_input_segwitv0(tx, input_index, input_scriptpubkey, input_amount, privkey, sighash_type=SIGHASH_ALL):
 705      """Add segwitv0 ECDSA signature for a given transaction input. Note that the signature
 706         is inserted at the bottom of the witness stack, i.e. additional witness data
 707         needed (e.g. pubkey for P2WPKH) can already be set before."""
 708      sighash = SegwitV0SignatureHash(input_scriptpubkey, tx, input_index, sighash_type, input_amount)
 709      der_sig = privkey.sign_ecdsa(sighash)
 710      tx.wit.vtxinwit[input_index].scriptWitness.stack.insert(0, der_sig + bytes([sighash_type]))
 711  
 712  # TODO: Allow cached hashPrevouts/hashSequence/hashOutputs to be provided.
 713  # Performance optimization probably not necessary for python tests, however.
 714  # Note that this corresponds to sigversion == 1 in EvalScript, which is used
 715  # for version 0 witnesses.
 716  def SegwitV0SignatureMsg(script, txTo, inIdx, hashtype, amount):
 717      ZERO_HASH = bytes([0]*32)
 718  
 719      hashPrevouts = ZERO_HASH
 720      hashSequence = ZERO_HASH
 721      hashOutputs = ZERO_HASH
 722  
 723      if not (hashtype & SIGHASH_ANYONECANPAY):
 724          serialize_prevouts = bytes()
 725          for i in txTo.vin:
 726              serialize_prevouts += i.prevout.serialize()
 727          hashPrevouts = hash256(serialize_prevouts)
 728  
 729      if (not (hashtype & SIGHASH_ANYONECANPAY) and (hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
 730          serialize_sequence = bytes()
 731          for i in txTo.vin:
 732              serialize_sequence += i.nSequence.to_bytes(4, "little")
 733          hashSequence = hash256(serialize_sequence)
 734  
 735      if ((hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
 736          serialize_outputs = bytes()
 737          for o in txTo.vout:
 738              serialize_outputs += o.serialize()
 739          hashOutputs = hash256(serialize_outputs)
 740      elif ((hashtype & 0x1f) == SIGHASH_SINGLE and inIdx < len(txTo.vout)):
 741          serialize_outputs = txTo.vout[inIdx].serialize()
 742          hashOutputs = hash256(serialize_outputs)
 743  
 744      ss = bytes()
 745      ss += txTo.version.to_bytes(4, "little")
 746      ss += hashPrevouts
 747      ss += hashSequence
 748      ss += txTo.vin[inIdx].prevout.serialize()
 749      ss += ser_string(script)
 750      ss += amount.to_bytes(8, "little", signed=True)
 751      ss += txTo.vin[inIdx].nSequence.to_bytes(4, "little")
 752      ss += hashOutputs
 753      ss += txTo.nLockTime.to_bytes(4, "little")
 754      ss += hashtype.to_bytes(4, "little")
 755      return ss
 756  
 757  def SegwitV0SignatureHash(*args, **kwargs):
 758      return hash256(SegwitV0SignatureMsg(*args, **kwargs))
 759  
 760  class TestFrameworkScript(unittest.TestCase):
 761      def test_bn2vch(self):
 762          self.assertEqual(bn2vch(0), bytes([]))
 763          self.assertEqual(bn2vch(1), bytes([0x01]))
 764          self.assertEqual(bn2vch(-1), bytes([0x81]))
 765          self.assertEqual(bn2vch(0x7F), bytes([0x7F]))
 766          self.assertEqual(bn2vch(-0x7F), bytes([0xFF]))
 767          self.assertEqual(bn2vch(0x80), bytes([0x80, 0x00]))
 768          self.assertEqual(bn2vch(-0x80), bytes([0x80, 0x80]))
 769          self.assertEqual(bn2vch(0xFF), bytes([0xFF, 0x00]))
 770          self.assertEqual(bn2vch(-0xFF), bytes([0xFF, 0x80]))
 771          self.assertEqual(bn2vch(0x100), bytes([0x00, 0x01]))
 772          self.assertEqual(bn2vch(-0x100), bytes([0x00, 0x81]))
 773          self.assertEqual(bn2vch(0x7FFF), bytes([0xFF, 0x7F]))
 774          self.assertEqual(bn2vch(-0x8000), bytes([0x00, 0x80, 0x80]))
 775          self.assertEqual(bn2vch(-0x7FFFFF), bytes([0xFF, 0xFF, 0xFF]))
 776          self.assertEqual(bn2vch(0x80000000), bytes([0x00, 0x00, 0x00, 0x80, 0x00]))
 777          self.assertEqual(bn2vch(-0x80000000), bytes([0x00, 0x00, 0x00, 0x80, 0x80]))
 778          self.assertEqual(bn2vch(0xFFFFFFFF), bytes([0xFF, 0xFF, 0xFF, 0xFF, 0x00]))
 779          self.assertEqual(bn2vch(123456789), bytes([0x15, 0xCD, 0x5B, 0x07]))
 780          self.assertEqual(bn2vch(-54321), bytes([0x31, 0xD4, 0x80]))
 781  
 782      def test_cscriptnum_encoding(self):
 783          # round-trip negative and multi-byte CScriptNums
 784          values = [0, 1, -1, -2, 127, 128, -255, 256, (1 << 15) - 1, -(1 << 16), (1 << 24) - 1, (1 << 31), 1 - (1 << 32), 1 << 40, 1500, -1500]
 785          for value in values:
 786              self.assertEqual(CScriptNum.decode(CScriptNum.encode(CScriptNum(value))), value)
 787  
 788      def test_legacy_sigopcount(self):
 789          # test repeated single sig ops
 790          for n_ops in range(1, 100, 10):
 791              for singlesig_op in (OP_CHECKSIG, OP_CHECKSIGVERIFY):
 792                  singlesigs_script = CScript([singlesig_op]*n_ops)
 793                  self.assertEqual(singlesigs_script.GetSigOpCount(fAccurate=False), n_ops)
 794                  self.assertEqual(singlesigs_script.GetSigOpCount(fAccurate=True), n_ops)
 795          # test multisig op (including accurate counting, i.e. BIP16)
 796          for n in range(1, 16+1):
 797              for multisig_op in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):
 798                  multisig_script = CScript([CScriptOp.encode_op_n(n), multisig_op])
 799                  self.assertEqual(multisig_script.GetSigOpCount(fAccurate=False), 20)
 800                  self.assertEqual(multisig_script.GetSigOpCount(fAccurate=True), n)
 801  
 802  def BIP341_sha_prevouts(txTo):
 803      return sha256(b"".join(i.prevout.serialize() for i in txTo.vin))
 804  
 805  def BIP341_sha_amounts(spent_utxos):
 806      return sha256(b"".join(u.nValue.to_bytes(8, "little", signed=True) for u in spent_utxos))
 807  
 808  def BIP341_sha_scriptpubkeys(spent_utxos):
 809      return sha256(b"".join(ser_string(u.scriptPubKey) for u in spent_utxos))
 810  
 811  def BIP341_sha_sequences(txTo):
 812      return sha256(b"".join(i.nSequence.to_bytes(4, "little") for i in txTo.vin))
 813  
 814  def BIP341_sha_outputs(txTo):
 815      return sha256(b"".join(o.serialize() for o in txTo.vout))
 816  
 817  def TaprootSignatureMsg(txTo, spent_utxos, hash_type, input_index=0, *, scriptpath=False, leaf_script=None, codeseparator_pos=-1, annex=None, leaf_ver=LEAF_VERSION_TAPSCRIPT):
 818      assert_equal(len(txTo.vin), len(spent_utxos))
 819      assert input_index < len(txTo.vin)
 820      out_type = SIGHASH_ALL if hash_type == 0 else hash_type & 3
 821      in_type = hash_type & SIGHASH_ANYONECANPAY
 822      spk = spent_utxos[input_index].scriptPubKey
 823      ss = bytes([0, hash_type]) # epoch, hash_type
 824      ss += txTo.version.to_bytes(4, "little")
 825      ss += txTo.nLockTime.to_bytes(4, "little")
 826      if in_type != SIGHASH_ANYONECANPAY:
 827          ss += BIP341_sha_prevouts(txTo)
 828          ss += BIP341_sha_amounts(spent_utxos)
 829          ss += BIP341_sha_scriptpubkeys(spent_utxos)
 830          ss += BIP341_sha_sequences(txTo)
 831      if out_type == SIGHASH_ALL:
 832          ss += BIP341_sha_outputs(txTo)
 833      spend_type = 0
 834      if annex is not None:
 835          spend_type |= 1
 836      if scriptpath:
 837          spend_type |= 2
 838      ss += bytes([spend_type])
 839      if in_type == SIGHASH_ANYONECANPAY:
 840          ss += txTo.vin[input_index].prevout.serialize()
 841          ss += spent_utxos[input_index].nValue.to_bytes(8, "little", signed=True)
 842          ss += ser_string(spk)
 843          ss += txTo.vin[input_index].nSequence.to_bytes(4, "little")
 844      else:
 845          ss += input_index.to_bytes(4, "little")
 846      if (spend_type & 1):
 847          ss += sha256(ser_string(annex))
 848      if out_type == SIGHASH_SINGLE:
 849          if input_index < len(txTo.vout):
 850              ss += sha256(txTo.vout[input_index].serialize())
 851          else:
 852              ss += bytes(0 for _ in range(32))
 853      if scriptpath:
 854          ss += TaggedHash("TapLeaf", bytes([leaf_ver]) + ser_string(leaf_script))
 855          ss += bytes([0])
 856          ss += codeseparator_pos.to_bytes(4, "little", signed=False)
 857      assert_equal(len(ss), 175 - (in_type == SIGHASH_ANYONECANPAY) * 49 - (out_type != SIGHASH_ALL and out_type != SIGHASH_SINGLE) * 32 + (annex is not None) * 32 + scriptpath * 37)
 858      return ss
 859  
 860  def TaprootSignatureHash(*args, **kwargs):
 861      return TaggedHash("TapSighash", TaprootSignatureMsg(*args, **kwargs))
 862  
 863  def taproot_tree_helper(scripts):
 864      if len(scripts) == 0:
 865          return ([], bytes())
 866      if len(scripts) == 1:
 867          # One entry: treat as a leaf
 868          script = scripts[0]
 869          assert not callable(script)
 870          if isinstance(script, list):
 871              return taproot_tree_helper(script)
 872          assert isinstance(script, tuple)
 873          version = LEAF_VERSION_TAPSCRIPT
 874          name = script[0]
 875          code = script[1]
 876          if len(script) == 3:
 877              version = script[2]
 878          assert_equal(version & 1, 0)
 879          assert isinstance(code, bytes)
 880          h = TaggedHash("TapLeaf", bytes([version]) + ser_string(code))
 881          if name is None:
 882              return ([], h)
 883          return ([(name, version, code, bytes(), h)], h)
 884      elif len(scripts) == 2 and callable(scripts[1]):
 885          # Two entries, and the right one is a function
 886          left, left_h = taproot_tree_helper(scripts[0:1])
 887          right_h = scripts[1](left_h)
 888          left = [(name, version, script, control + right_h, leaf) for name, version, script, control, leaf in left]
 889          right = []
 890      else:
 891          # Two or more entries: descend into each side
 892          split_pos = len(scripts) // 2
 893          left, left_h = taproot_tree_helper(scripts[0:split_pos])
 894          right, right_h = taproot_tree_helper(scripts[split_pos:])
 895          left = [(name, version, script, control + right_h, leaf) for name, version, script, control, leaf in left]
 896          right = [(name, version, script, control + left_h, leaf) for name, version, script, control, leaf in right]
 897      if right_h < left_h:
 898          right_h, left_h = left_h, right_h
 899      h = TaggedHash("TapBranch", left_h + right_h)
 900      return (left + right, h)
 901  
 902  # A TaprootInfo object has the following fields:
 903  # - scriptPubKey: the scriptPubKey (witness v1 CScript)
 904  # - internal_pubkey: the internal pubkey (32 bytes)
 905  # - negflag: whether the pubkey in the scriptPubKey was negated from internal_pubkey+tweak*G (bool).
 906  # - tweak: the tweak (32 bytes)
 907  # - leaves: a dict of name -> TaprootLeafInfo objects for all known leaves
 908  # - merkle_root: the script tree's Merkle root, or bytes() if no leaves are present
 909  TaprootInfo = namedtuple("TaprootInfo", "scriptPubKey,internal_pubkey,negflag,tweak,leaves,merkle_root,output_pubkey")
 910  
 911  # A TaprootLeafInfo object has the following fields:
 912  # - script: the leaf script (CScript or bytes)
 913  # - version: the leaf version (0xc0 for BIP342 tapscript)
 914  # - merklebranch: the merkle branch to use for this leaf (32*N bytes)
 915  TaprootLeafInfo = namedtuple("TaprootLeafInfo", "script,version,merklebranch,leaf_hash")
 916  
 917  def taproot_construct(pubkey, scripts=None, treat_internal_as_infinity=False):
 918      """Construct a tree of Taproot spending conditions
 919  
 920      pubkey: a 32-byte xonly pubkey for the internal pubkey (bytes)
 921      scripts: a list of items; each item is either:
 922               - a (name, CScript or bytes, leaf version) tuple
 923               - a (name, CScript or bytes) tuple (defaulting to leaf version 0xc0)
 924               - another list of items (with the same structure)
 925               - a list of two items; the first of which is an item itself, and the
 926                 second is a function. The function takes as input the Merkle root of the
 927                 first item, and produces a (fictitious) partner to hash with.
 928  
 929      Returns: a TaprootInfo object
 930      """
 931      if scripts is None:
 932          scripts = []
 933  
 934      ret, h = taproot_tree_helper(scripts)
 935      tweak = TaggedHash("TapTweak", pubkey + h)
 936      if treat_internal_as_infinity:
 937          tweaked, negated = compute_xonly_pubkey(tweak)
 938      else:
 939          tweaked, negated = tweak_add_pubkey(pubkey, tweak)
 940      leaves = dict((name, TaprootLeafInfo(script, version, merklebranch, leaf)) for name, version, script, merklebranch, leaf in ret)
 941      return TaprootInfo(CScript([OP_1, tweaked]), pubkey, negated + 0, tweak, leaves, h, tweaked)
 942  
 943  def is_op_success(o):
 944      return o == 0x50 or o == 0x62 or o == 0x89 or o == 0x8a or o == 0x8d or o == 0x8e or (o >= 0x7e and o <= 0x81) or (o >= 0x83 and o <= 0x86) or (o >= 0x95 and o <= 0x99) or (o >= 0xbb and o <= 0xfe)
 945