1#!/usr/bin/env python3
2# Copyright (c) 2015-2018 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 SignatureHash().
6
7This file is modified from python-bitcoinlib.
8"""
9
10from .messages import CTransaction, CTxOut, sha256, hash256, uint256_from_str, ser_uint256, ser_string
11
12from binascii import hexlify
13import hashlib
14import struct
15
16from .bignum import bn2vch
17
18MAX_SCRIPT_ELEMENT_SIZE = 520
19
20OPCODE_NAMES = {}
21
22def hash160(s):
23    return hashlib.new('ripemd160', sha256(s)).digest()
24
25
26_opcode_instances = []
27class CScriptOp(int):
28    """A single script opcode"""
29    __slots__ = ()
30
31    @staticmethod
32    def encode_op_pushdata(d):
33        """Encode a PUSHDATA op, returning bytes"""
34        if len(d) < 0x4c:
35            return b'' + bytes([len(d)]) + d # OP_PUSHDATA
36        elif len(d) <= 0xff:
37            return b'\x4c' + bytes([len(d)]) + d # OP_PUSHDATA1
38        elif len(d) <= 0xffff:
39            return b'\x4d' + struct.pack(b'<H', len(d)) + d # OP_PUSHDATA2
40        elif len(d) <= 0xffffffff:
41            return b'\x4e' + struct.pack(b'<I', len(d)) + d # OP_PUSHDATA4
42        else:
43            raise ValueError("Data too long to encode in a PUSHDATA op")
44
45    @staticmethod
46    def encode_op_n(n):
47        """Encode a small integer op, returning an opcode"""
48        if not (0 <= n <= 16):
49            raise ValueError('Integer must be in range 0 <= n <= 16, got %d' % n)
50
51        if n == 0:
52            return OP_0
53        else:
54            return CScriptOp(OP_1 + n-1)
55
56    def decode_op_n(self):
57        """Decode a small integer opcode, returning an integer"""
58        if self == OP_0:
59            return 0
60
61        if not (self == OP_0 or OP_1 <= self <= OP_16):
62            raise ValueError('op %r is not an OP_N' % self)
63
64        return int(self - OP_1+1)
65
66    def is_small_int(self):
67        """Return true if the op pushes a small integer to the stack"""
68        if 0x51 <= self <= 0x60 or self == 0:
69            return True
70        else:
71            return False
72
73    def __str__(self):
74        return repr(self)
75
76    def __repr__(self):
77        if self in OPCODE_NAMES:
78            return OPCODE_NAMES[self]
79        else:
80            return 'CScriptOp(0x%x)' % self
81
82    def __new__(cls, n):
83        try:
84            return _opcode_instances[n]
85        except IndexError:
86            assert len(_opcode_instances) == n
87            _opcode_instances.append(super(CScriptOp, cls).__new__(cls, n))
88            return _opcode_instances[n]
89
90# Populate opcode instance table
91for n in range(0xff+1):
92    CScriptOp(n)
93
94
95# push value
96OP_0 = CScriptOp(0x00)
97OP_FALSE = OP_0
98OP_PUSHDATA1 = CScriptOp(0x4c)
99OP_PUSHDATA2 = CScriptOp(0x4d)
100OP_PUSHDATA4 = CScriptOp(0x4e)
101OP_1NEGATE = CScriptOp(0x4f)
102OP_RESERVED = CScriptOp(0x50)
103OP_1 = CScriptOp(0x51)
104OP_TRUE=OP_1
105OP_2 = CScriptOp(0x52)
106OP_3 = CScriptOp(0x53)
107OP_4 = CScriptOp(0x54)
108OP_5 = CScriptOp(0x55)
109OP_6 = CScriptOp(0x56)
110OP_7 = CScriptOp(0x57)
111OP_8 = CScriptOp(0x58)
112OP_9 = CScriptOp(0x59)
113OP_10 = CScriptOp(0x5a)
114OP_11 = CScriptOp(0x5b)
115OP_12 = CScriptOp(0x5c)
116OP_13 = CScriptOp(0x5d)
117OP_14 = CScriptOp(0x5e)
118OP_15 = CScriptOp(0x5f)
119OP_16 = CScriptOp(0x60)
120
121# control
122OP_NOP = CScriptOp(0x61)
123OP_VER = CScriptOp(0x62)
124OP_IF = CScriptOp(0x63)
125OP_NOTIF = CScriptOp(0x64)
126OP_VERIF = CScriptOp(0x65)
127OP_VERNOTIF = CScriptOp(0x66)
128OP_ELSE = CScriptOp(0x67)
129OP_ENDIF = CScriptOp(0x68)
130OP_VERIFY = CScriptOp(0x69)
131OP_RETURN = CScriptOp(0x6a)
132
133# stack ops
134OP_TOALTSTACK = CScriptOp(0x6b)
135OP_FROMALTSTACK = CScriptOp(0x6c)
136OP_2DROP = CScriptOp(0x6d)
137OP_2DUP = CScriptOp(0x6e)
138OP_3DUP = CScriptOp(0x6f)
139OP_2OVER = CScriptOp(0x70)
140OP_2ROT = CScriptOp(0x71)
141OP_2SWAP = CScriptOp(0x72)
142OP_IFDUP = CScriptOp(0x73)
143OP_DEPTH = CScriptOp(0x74)
144OP_DROP = CScriptOp(0x75)
145OP_DUP = CScriptOp(0x76)
146OP_NIP = CScriptOp(0x77)
147OP_OVER = CScriptOp(0x78)
148OP_PICK = CScriptOp(0x79)
149OP_ROLL = CScriptOp(0x7a)
150OP_ROT = CScriptOp(0x7b)
151OP_SWAP = CScriptOp(0x7c)
152OP_TUCK = CScriptOp(0x7d)
153
154# splice ops
155OP_CAT = CScriptOp(0x7e)
156OP_SUBSTR = CScriptOp(0x7f)
157OP_LEFT = CScriptOp(0x80)
158OP_RIGHT = CScriptOp(0x81)
159OP_SIZE = CScriptOp(0x82)
160
161# bit logic
162OP_INVERT = CScriptOp(0x83)
163OP_AND = CScriptOp(0x84)
164OP_OR = CScriptOp(0x85)
165OP_XOR = CScriptOp(0x86)
166OP_EQUAL = CScriptOp(0x87)
167OP_EQUALVERIFY = CScriptOp(0x88)
168OP_RESERVED1 = CScriptOp(0x89)
169OP_RESERVED2 = CScriptOp(0x8a)
170
171# numeric
172OP_1ADD = CScriptOp(0x8b)
173OP_1SUB = CScriptOp(0x8c)
174OP_2MUL = CScriptOp(0x8d)
175OP_2DIV = CScriptOp(0x8e)
176OP_NEGATE = CScriptOp(0x8f)
177OP_ABS = CScriptOp(0x90)
178OP_NOT = CScriptOp(0x91)
179OP_0NOTEQUAL = CScriptOp(0x92)
180
181OP_ADD = CScriptOp(0x93)
182OP_SUB = CScriptOp(0x94)
183OP_MUL = CScriptOp(0x95)
184OP_DIV = CScriptOp(0x96)
185OP_MOD = CScriptOp(0x97)
186OP_LSHIFT = CScriptOp(0x98)
187OP_RSHIFT = CScriptOp(0x99)
188
189OP_BOOLAND = CScriptOp(0x9a)
190OP_BOOLOR = CScriptOp(0x9b)
191OP_NUMEQUAL = CScriptOp(0x9c)
192OP_NUMEQUALVERIFY = CScriptOp(0x9d)
193OP_NUMNOTEQUAL = CScriptOp(0x9e)
194OP_LESSTHAN = CScriptOp(0x9f)
195OP_GREATERTHAN = CScriptOp(0xa0)
196OP_LESSTHANOREQUAL = CScriptOp(0xa1)
197OP_GREATERTHANOREQUAL = CScriptOp(0xa2)
198OP_MIN = CScriptOp(0xa3)
199OP_MAX = CScriptOp(0xa4)
200
201OP_WITHIN = CScriptOp(0xa5)
202
203# crypto
204OP_RIPEMD160 = CScriptOp(0xa6)
205OP_SHA1 = CScriptOp(0xa7)
206OP_SHA256 = CScriptOp(0xa8)
207OP_HASH160 = CScriptOp(0xa9)
208OP_HASH256 = CScriptOp(0xaa)
209OP_CODESEPARATOR = CScriptOp(0xab)
210OP_CHECKSIG = CScriptOp(0xac)
211OP_CHECKSIGVERIFY = CScriptOp(0xad)
212OP_CHECKMULTISIG = CScriptOp(0xae)
213OP_CHECKMULTISIGVERIFY = CScriptOp(0xaf)
214
215# expansion
216OP_NOP1 = CScriptOp(0xb0)
217OP_CHECKLOCKTIMEVERIFY = CScriptOp(0xb1)
218OP_CHECKSEQUENCEVERIFY = CScriptOp(0xb2)
219OP_NOP4 = CScriptOp(0xb3)
220OP_NOP5 = CScriptOp(0xb4)
221OP_NOP6 = CScriptOp(0xb5)
222OP_NOP7 = CScriptOp(0xb6)
223OP_NOP8 = CScriptOp(0xb7)
224OP_NOP9 = CScriptOp(0xb8)
225OP_NOP10 = CScriptOp(0xb9)
226
227# template matching params
228OP_SMALLINTEGER = CScriptOp(0xfa)
229OP_PUBKEYS = CScriptOp(0xfb)
230OP_PUBKEYHASH = CScriptOp(0xfd)
231OP_PUBKEY = CScriptOp(0xfe)
232
233OP_INVALIDOPCODE = CScriptOp(0xff)
234
235OPCODE_NAMES.update({
236    OP_0 : 'OP_0',
237    OP_PUSHDATA1 : 'OP_PUSHDATA1',
238    OP_PUSHDATA2 : 'OP_PUSHDATA2',
239    OP_PUSHDATA4 : 'OP_PUSHDATA4',
240    OP_1NEGATE : 'OP_1NEGATE',
241    OP_RESERVED : 'OP_RESERVED',
242    OP_1 : 'OP_1',
243    OP_2 : 'OP_2',
244    OP_3 : 'OP_3',
245    OP_4 : 'OP_4',
246    OP_5 : 'OP_5',
247    OP_6 : 'OP_6',
248    OP_7 : 'OP_7',
249    OP_8 : 'OP_8',
250    OP_9 : 'OP_9',
251    OP_10 : 'OP_10',
252    OP_11 : 'OP_11',
253    OP_12 : 'OP_12',
254    OP_13 : 'OP_13',
255    OP_14 : 'OP_14',
256    OP_15 : 'OP_15',
257    OP_16 : 'OP_16',
258    OP_NOP : 'OP_NOP',
259    OP_VER : 'OP_VER',
260    OP_IF : 'OP_IF',
261    OP_NOTIF : 'OP_NOTIF',
262    OP_VERIF : 'OP_VERIF',
263    OP_VERNOTIF : 'OP_VERNOTIF',
264    OP_ELSE : 'OP_ELSE',
265    OP_ENDIF : 'OP_ENDIF',
266    OP_VERIFY : 'OP_VERIFY',
267    OP_RETURN : 'OP_RETURN',
268    OP_TOALTSTACK : 'OP_TOALTSTACK',
269    OP_FROMALTSTACK : 'OP_FROMALTSTACK',
270    OP_2DROP : 'OP_2DROP',
271    OP_2DUP : 'OP_2DUP',
272    OP_3DUP : 'OP_3DUP',
273    OP_2OVER : 'OP_2OVER',
274    OP_2ROT : 'OP_2ROT',
275    OP_2SWAP : 'OP_2SWAP',
276    OP_IFDUP : 'OP_IFDUP',
277    OP_DEPTH : 'OP_DEPTH',
278    OP_DROP : 'OP_DROP',
279    OP_DUP : 'OP_DUP',
280    OP_NIP : 'OP_NIP',
281    OP_OVER : 'OP_OVER',
282    OP_PICK : 'OP_PICK',
283    OP_ROLL : 'OP_ROLL',
284    OP_ROT : 'OP_ROT',
285    OP_SWAP : 'OP_SWAP',
286    OP_TUCK : 'OP_TUCK',
287    OP_CAT : 'OP_CAT',
288    OP_SUBSTR : 'OP_SUBSTR',
289    OP_LEFT : 'OP_LEFT',
290    OP_RIGHT : 'OP_RIGHT',
291    OP_SIZE : 'OP_SIZE',
292    OP_INVERT : 'OP_INVERT',
293    OP_AND : 'OP_AND',
294    OP_OR : 'OP_OR',
295    OP_XOR : 'OP_XOR',
296    OP_EQUAL : 'OP_EQUAL',
297    OP_EQUALVERIFY : 'OP_EQUALVERIFY',
298    OP_RESERVED1 : 'OP_RESERVED1',
299    OP_RESERVED2 : 'OP_RESERVED2',
300    OP_1ADD : 'OP_1ADD',
301    OP_1SUB : 'OP_1SUB',
302    OP_2MUL : 'OP_2MUL',
303    OP_2DIV : 'OP_2DIV',
304    OP_NEGATE : 'OP_NEGATE',
305    OP_ABS : 'OP_ABS',
306    OP_NOT : 'OP_NOT',
307    OP_0NOTEQUAL : 'OP_0NOTEQUAL',
308    OP_ADD : 'OP_ADD',
309    OP_SUB : 'OP_SUB',
310    OP_MUL : 'OP_MUL',
311    OP_DIV : 'OP_DIV',
312    OP_MOD : 'OP_MOD',
313    OP_LSHIFT : 'OP_LSHIFT',
314    OP_RSHIFT : 'OP_RSHIFT',
315    OP_BOOLAND : 'OP_BOOLAND',
316    OP_BOOLOR : 'OP_BOOLOR',
317    OP_NUMEQUAL : 'OP_NUMEQUAL',
318    OP_NUMEQUALVERIFY : 'OP_NUMEQUALVERIFY',
319    OP_NUMNOTEQUAL : 'OP_NUMNOTEQUAL',
320    OP_LESSTHAN : 'OP_LESSTHAN',
321    OP_GREATERTHAN : 'OP_GREATERTHAN',
322    OP_LESSTHANOREQUAL : 'OP_LESSTHANOREQUAL',
323    OP_GREATERTHANOREQUAL : 'OP_GREATERTHANOREQUAL',
324    OP_MIN : 'OP_MIN',
325    OP_MAX : 'OP_MAX',
326    OP_WITHIN : 'OP_WITHIN',
327    OP_RIPEMD160 : 'OP_RIPEMD160',
328    OP_SHA1 : 'OP_SHA1',
329    OP_SHA256 : 'OP_SHA256',
330    OP_HASH160 : 'OP_HASH160',
331    OP_HASH256 : 'OP_HASH256',
332    OP_CODESEPARATOR : 'OP_CODESEPARATOR',
333    OP_CHECKSIG : 'OP_CHECKSIG',
334    OP_CHECKSIGVERIFY : 'OP_CHECKSIGVERIFY',
335    OP_CHECKMULTISIG : 'OP_CHECKMULTISIG',
336    OP_CHECKMULTISIGVERIFY : 'OP_CHECKMULTISIGVERIFY',
337    OP_NOP1 : 'OP_NOP1',
338    OP_CHECKLOCKTIMEVERIFY : 'OP_CHECKLOCKTIMEVERIFY',
339    OP_CHECKSEQUENCEVERIFY : 'OP_CHECKSEQUENCEVERIFY',
340    OP_NOP4 : 'OP_NOP4',
341    OP_NOP5 : 'OP_NOP5',
342    OP_NOP6 : 'OP_NOP6',
343    OP_NOP7 : 'OP_NOP7',
344    OP_NOP8 : 'OP_NOP8',
345    OP_NOP9 : 'OP_NOP9',
346    OP_NOP10 : 'OP_NOP10',
347    OP_SMALLINTEGER : 'OP_SMALLINTEGER',
348    OP_PUBKEYS : 'OP_PUBKEYS',
349    OP_PUBKEYHASH : 'OP_PUBKEYHASH',
350    OP_PUBKEY : 'OP_PUBKEY',
351    OP_INVALIDOPCODE : 'OP_INVALIDOPCODE',
352})
353
354class CScriptInvalidError(Exception):
355    """Base class for CScript exceptions"""
356    pass
357
358class CScriptTruncatedPushDataError(CScriptInvalidError):
359    """Invalid pushdata due to truncation"""
360    def __init__(self, msg, data):
361        self.data = data
362        super(CScriptTruncatedPushDataError, self).__init__(msg)
363
364
365# This is used, eg, for blockchain heights in coinbase scripts (bip34)
366class CScriptNum:
367    __slots__ = ("value",)
368
369    def __init__(self, d=0):
370        self.value = d
371
372    @staticmethod
373    def encode(obj):
374        r = bytearray(0)
375        if obj.value == 0:
376            return bytes(r)
377        neg = obj.value < 0
378        absvalue = -obj.value if neg else obj.value
379        while (absvalue):
380            r.append(absvalue & 0xff)
381            absvalue >>= 8
382        if r[-1] & 0x80:
383            r.append(0x80 if neg else 0)
384        elif neg:
385            r[-1] |= 0x80
386        return bytes([len(r)]) + r
387
388    @staticmethod
389    def decode(vch):
390        result = 0
391        # We assume valid push_size and minimal encoding
392        value = vch[1:]
393        if len(value) == 0:
394            return result
395        for i, byte in enumerate(value):
396            result |= int(byte) << 8*i
397        if value[-1] >= 0x80:
398            # Mask for all but the highest result bit
399            num_mask = (2**(len(value)*8) - 1) >> 1
400            result &= num_mask
401            result *= -1
402        return result
403
404
405class CScript(bytes):
406    """Serialized script
407
408    A bytes subclass, so you can use this directly whenever bytes are accepted.
409    Note that this means that indexing does *not* work - you'll get an index by
410    byte rather than opcode. This format was chosen for efficiency so that the
411    general case would not require creating a lot of little CScriptOP objects.
412
413    iter(script) however does iterate by opcode.
414    """
415    __slots__ = ()
416
417    @classmethod
418    def __coerce_instance(cls, other):
419        # Coerce other into bytes
420        if isinstance(other, CScriptOp):
421            other = bytes([other])
422        elif isinstance(other, CScriptNum):
423            if (other.value == 0):
424                other = bytes([CScriptOp(OP_0)])
425            else:
426                other = CScriptNum.encode(other)
427        elif isinstance(other, int):
428            if 0 <= other <= 16:
429                other = bytes([CScriptOp.encode_op_n(other)])
430            elif other == -1:
431                other = bytes([OP_1NEGATE])
432            else:
433                other = CScriptOp.encode_op_pushdata(bn2vch(other))
434        elif isinstance(other, (bytes, bytearray)):
435            other = CScriptOp.encode_op_pushdata(other)
436        return other
437
438    def __add__(self, other):
439        # Do the coercion outside of the try block so that errors in it are
440        # noticed.
441        other = self.__coerce_instance(other)
442
443        try:
444            # bytes.__add__ always returns bytes instances unfortunately
445            return CScript(super(CScript, self).__add__(other))
446        except TypeError:
447            raise TypeError('Can not add a %r instance to a CScript' % other.__class__)
448
449    def join(self, iterable):
450        # join makes no sense for a CScript()
451        raise NotImplementedError
452
453    # Python 3.4 compatibility
454    def hex(self):
455        return hexlify(self).decode('ascii')
456
457    def __new__(cls, value=b''):
458        if isinstance(value, bytes) or isinstance(value, bytearray):
459            return super(CScript, cls).__new__(cls, value)
460        else:
461            def coerce_iterable(iterable):
462                for instance in iterable:
463                    yield cls.__coerce_instance(instance)
464            # Annoyingly on both python2 and python3 bytes.join() always
465            # returns a bytes instance even when subclassed.
466            return super(CScript, cls).__new__(cls, b''.join(coerce_iterable(value)))
467
468    def raw_iter(self):
469        """Raw iteration
470
471        Yields tuples of (opcode, data, sop_idx) so that the different possible
472        PUSHDATA encodings can be accurately distinguished, as well as
473        determining the exact opcode byte indexes. (sop_idx)
474        """
475        i = 0
476        while i < len(self):
477            sop_idx = i
478            opcode = self[i]
479            i += 1
480
481            if opcode > OP_PUSHDATA4:
482                yield (opcode, None, sop_idx)
483            else:
484                datasize = None
485                pushdata_type = None
486                if opcode < OP_PUSHDATA1:
487                    pushdata_type = 'PUSHDATA(%d)' % opcode
488                    datasize = opcode
489
490                elif opcode == OP_PUSHDATA1:
491                    pushdata_type = 'PUSHDATA1'
492                    if i >= len(self):
493                        raise CScriptInvalidError('PUSHDATA1: missing data length')
494                    datasize = self[i]
495                    i += 1
496
497                elif opcode == OP_PUSHDATA2:
498                    pushdata_type = 'PUSHDATA2'
499                    if i + 1 >= len(self):
500                        raise CScriptInvalidError('PUSHDATA2: missing data length')
501                    datasize = self[i] + (self[i+1] << 8)
502                    i += 2
503
504                elif opcode == OP_PUSHDATA4:
505                    pushdata_type = 'PUSHDATA4'
506                    if i + 3 >= len(self):
507                        raise CScriptInvalidError('PUSHDATA4: missing data length')
508                    datasize = self[i] + (self[i+1] << 8) + (self[i+2] << 16) + (self[i+3] << 24)
509                    i += 4
510
511                else:
512                    assert False # shouldn't happen
513
514
515                data = bytes(self[i:i+datasize])
516
517                # Check for truncation
518                if len(data) < datasize:
519                    raise CScriptTruncatedPushDataError('%s: truncated data' % pushdata_type, data)
520
521                i += datasize
522
523                yield (opcode, data, sop_idx)
524
525    def __iter__(self):
526        """'Cooked' iteration
527
528        Returns either a CScriptOP instance, an integer, or bytes, as
529        appropriate.
530
531        See raw_iter() if you need to distinguish the different possible
532        PUSHDATA encodings.
533        """
534        for (opcode, data, sop_idx) in self.raw_iter():
535            if data is not None:
536                yield data
537            else:
538                opcode = CScriptOp(opcode)
539
540                if opcode.is_small_int():
541                    yield opcode.decode_op_n()
542                else:
543                    yield CScriptOp(opcode)
544
545    def __repr__(self):
546        def _repr(o):
547            if isinstance(o, bytes):
548                return "x('%s')" % hexlify(o).decode('ascii')
549            else:
550                return repr(o)
551
552        ops = []
553        i = iter(self)
554        while True:
555            op = None
556            try:
557                op = _repr(next(i))
558            except CScriptTruncatedPushDataError as err:
559                op = '%s...<ERROR: %s>' % (_repr(err.data), err)
560                break
561            except CScriptInvalidError as err:
562                op = '<ERROR: %s>' % err
563                break
564            except StopIteration:
565                break
566            finally:
567                if op is not None:
568                    ops.append(op)
569
570        return "CScript([%s])" % ', '.join(ops)
571
572    def GetSigOpCount(self, fAccurate):
573        """Get the SigOp count.
574
575        fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details.
576
577        Note that this is consensus-critical.
578        """
579        n = 0
580        lastOpcode = OP_INVALIDOPCODE
581        for (opcode, data, sop_idx) in self.raw_iter():
582            if opcode in (OP_CHECKSIG, OP_CHECKSIGVERIFY):
583                n += 1
584            elif opcode in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):
585                if fAccurate and (OP_1 <= lastOpcode <= OP_16):
586                    n += opcode.decode_op_n()
587                else:
588                    n += 20
589            lastOpcode = opcode
590        return n
591
592
593SIGHASH_ALL = 1
594SIGHASH_NONE = 2
595SIGHASH_SINGLE = 3
596SIGHASH_ANYONECANPAY = 0x80
597
598def FindAndDelete(script, sig):
599    """Consensus critical, see FindAndDelete() in Satoshi codebase"""
600    r = b''
601    last_sop_idx = sop_idx = 0
602    skip = True
603    for (opcode, data, sop_idx) in script.raw_iter():
604        if not skip:
605            r += script[last_sop_idx:sop_idx]
606        last_sop_idx = sop_idx
607        if script[sop_idx:sop_idx + len(sig)] == sig:
608            skip = True
609        else:
610            skip = False
611    if not skip:
612        r += script[last_sop_idx:]
613    return CScript(r)
614
615
616def SignatureHash(script, txTo, inIdx, hashtype):
617    """Consensus-correct SignatureHash
618
619    Returns (hash, err) to precisely match the consensus-critical behavior of
620    the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity)
621    """
622    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'
623
624    if inIdx >= len(txTo.vin):
625        return (HASH_ONE, "inIdx %d out of range (%d)" % (inIdx, len(txTo.vin)))
626    txtmp = CTransaction(txTo)
627
628    for txin in txtmp.vin:
629        txin.scriptSig = b''
630    txtmp.vin[inIdx].scriptSig = FindAndDelete(script, CScript([OP_CODESEPARATOR]))
631
632    if (hashtype & 0x1f) == SIGHASH_NONE:
633        txtmp.vout = []
634
635        for i in range(len(txtmp.vin)):
636            if i != inIdx:
637                txtmp.vin[i].nSequence = 0
638
639    elif (hashtype & 0x1f) == SIGHASH_SINGLE:
640        outIdx = inIdx
641        if outIdx >= len(txtmp.vout):
642            return (HASH_ONE, "outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))
643
644        tmp = txtmp.vout[outIdx]
645        txtmp.vout = []
646        for i in range(outIdx):
647            txtmp.vout.append(CTxOut(-1))
648        txtmp.vout.append(tmp)
649
650        for i in range(len(txtmp.vin)):
651            if i != inIdx:
652                txtmp.vin[i].nSequence = 0
653
654    if hashtype & SIGHASH_ANYONECANPAY:
655        tmp = txtmp.vin[inIdx]
656        txtmp.vin = []
657        txtmp.vin.append(tmp)
658
659    s = txtmp.serialize_without_witness()
660    s += struct.pack(b"<I", hashtype)
661
662    hash = hash256(s)
663
664    return (hash, None)
665
666# TODO: Allow cached hashPrevouts/hashSequence/hashOutputs to be provided.
667# Performance optimization probably not necessary for python tests, however.
668# Note that this corresponds to sigversion == 1 in EvalScript, which is used
669# for version 0 witnesses.
670def SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, amount):
671
672    hashPrevouts = 0
673    hashSequence = 0
674    hashOutputs = 0
675
676    if not (hashtype & SIGHASH_ANYONECANPAY):
677        serialize_prevouts = bytes()
678        for i in txTo.vin:
679            serialize_prevouts += i.prevout.serialize()
680        hashPrevouts = uint256_from_str(hash256(serialize_prevouts))
681
682    if (not (hashtype & SIGHASH_ANYONECANPAY) and (hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
683        serialize_sequence = bytes()
684        for i in txTo.vin:
685            serialize_sequence += struct.pack("<I", i.nSequence)
686        hashSequence = uint256_from_str(hash256(serialize_sequence))
687
688    if ((hashtype & 0x1f) != SIGHASH_SINGLE and (hashtype & 0x1f) != SIGHASH_NONE):
689        serialize_outputs = bytes()
690        for o in txTo.vout:
691            serialize_outputs += o.serialize()
692        hashOutputs = uint256_from_str(hash256(serialize_outputs))
693    elif ((hashtype & 0x1f) == SIGHASH_SINGLE and inIdx < len(txTo.vout)):
694        serialize_outputs = txTo.vout[inIdx].serialize()
695        hashOutputs = uint256_from_str(hash256(serialize_outputs))
696
697    ss = bytes()
698    ss += struct.pack("<i", txTo.nVersion)
699    ss += ser_uint256(hashPrevouts)
700    ss += ser_uint256(hashSequence)
701    ss += txTo.vin[inIdx].prevout.serialize()
702    ss += ser_string(script)
703    ss += struct.pack("<q", amount)
704    ss += struct.pack("<I", txTo.vin[inIdx].nSequence)
705    ss += ser_uint256(hashOutputs)
706    ss += struct.pack("<i", txTo.nLockTime)
707    ss += struct.pack("<I", hashtype)
708
709    return hash256(ss)
710