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