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