2 # Copyright (c) 2015-2017 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.
10 from .mininode
import CTransaction
, CTxOut
, sha256
, hash256
, uint256_from_str
, ser_uint256
, ser_string
11 from binascii
import hexlify
19 bchr
= lambda x
: bytes([x
])
24 from .bignum
import bn2vch
26 MAX_SCRIPT_ELEMENT_SIZE
= 520
31 return hashlib
.new('ripemd160', sha256(s
)).digest()
34 _opcode_instances
= []
36 """A single script opcode"""
40 def encode_op_pushdata(d
):
41 """Encode a PUSHDATA op, returning bytes"""
43 return b
'' + bchr(len(d
)) + d
# OP_PUSHDATA
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
51 raise ValueError("Data too long to encode in a PUSHDATA op")
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
)
62 return CScriptOp(OP_1
+ n
-1)
64 def decode_op_n(self
):
65 """Decode a small integer opcode, returning an integer"""
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:
85 if self
in OPCODE_NAMES
:
86 return OPCODE_NAMES
[self
]
88 return 'CScriptOp(0x%x)' % self
92 return _opcode_instances
[n
]
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):
104 OP_0
= CScriptOp(0x00)
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)
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)
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)
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)
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)
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)
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)
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)
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({
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',
269 OP_NOTIF
: 'OP_NOTIF',
270 OP_VERIF
: 'OP_VERIF',
271 OP_VERNOTIF
: 'OP_VERNOTIF',
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',
281 OP_2OVER
: 'OP_2OVER',
283 OP_2SWAP
: 'OP_2SWAP',
284 OP_IFDUP
: 'OP_IFDUP',
285 OP_DEPTH
: 'OP_DEPTH',
296 OP_SUBSTR
: 'OP_SUBSTR',
298 OP_RIGHT
: 'OP_RIGHT',
300 OP_INVERT
: 'OP_INVERT',
304 OP_EQUAL
: 'OP_EQUAL',
305 OP_EQUALVERIFY
: 'OP_EQUALVERIFY',
306 OP_RESERVED1
: 'OP_RESERVED1',
307 OP_RESERVED2
: 'OP_RESERVED2',
312 OP_NEGATE
: 'OP_NEGATE',
315 OP_0NOTEQUAL
: 'OP_0NOTEQUAL',
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',
334 OP_WITHIN
: 'OP_WITHIN',
335 OP_RIPEMD160
: 'OP_RIPEMD160',
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',
346 OP_CHECKLOCKTIMEVERIFY
: 'OP_CHECKLOCKTIMEVERIFY',
347 OP_CHECKSEQUENCEVERIFY
: 'OP_CHECKSEQUENCEVERIFY',
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"""
366 class CScriptTruncatedPushDataError(CScriptInvalidError
):
367 """Invalid pushdata due to truncation"""
368 def __init__(self
, msg
, data
):
370 super(CScriptTruncatedPushDataError
, self
).__init
__(msg
)
372 # This is used, eg, for blockchain heights in coinbase scripts (bip34)
374 def __init__(self
, d
=0):
383 absvalue
= -obj
.value
if neg
else obj
.value
385 r
.append(absvalue
& 0xff)
388 r
.append(0x80 if neg
else 0)
391 return bytes(bchr(len(r
)) + r
)
394 class CScript(bytes
):
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.
405 def __coerce_instance(cls
, other
):
406 # Coerce other into bytes
407 if isinstance(other
, CScriptOp
):
409 elif isinstance(other
, CScriptNum
):
410 if (other
.value
== 0):
411 other
= bchr(CScriptOp(OP_0
))
413 other
= CScriptNum
.encode(other
)
414 elif isinstance(other
, int):
416 other
= bytes(bchr(CScriptOp
.encode_op_n(other
)))
418 other
= bytes(bchr(OP_1NEGATE
))
420 other
= CScriptOp
.encode_op_pushdata(bn2vch(other
))
421 elif isinstance(other
, (bytes
, bytearray
)):
422 other
= CScriptOp
.encode_op_pushdata(other
)
425 def __add__(self
, other
):
426 # Do the coercion outside of the try block so that errors in it are
428 other
= self
.__coerce
_instance
(other
)
431 # bytes.__add__ always returns bytes instances unfortunately
432 return CScript(super(CScript
, self
).__add
__(other
))
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
)
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
)))
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)
461 opcode
= bord(self
[i
])
464 if opcode
> OP_PUSHDATA4
:
465 yield (opcode
, None, sop_idx
)
469 if opcode
< OP_PUSHDATA1
:
470 pushdata_type
= 'PUSHDATA(%d)' % opcode
473 elif opcode
== OP_PUSHDATA1
:
474 pushdata_type
= 'PUSHDATA1'
476 raise CScriptInvalidError('PUSHDATA1: missing data length')
477 datasize
= bord(self
[i
])
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)
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)
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
)
506 yield (opcode
, data
, sop_idx
)
509 """'Cooked' iteration
511 Returns either a CScriptOP instance, an integer, or bytes, as
514 See raw_iter() if you need to distinguish the different possible
517 for (opcode
, data
, sop_idx
) in self
.raw_iter():
521 opcode
= CScriptOp(opcode
)
523 if opcode
.is_small_int():
524 yield opcode
.decode_op_n()
526 yield CScriptOp(opcode
)
529 # For Python3 compatibility add b before strings so testcases don't
532 if isinstance(o
, bytes
):
533 return b
"x('%s')" % hexlify(o
).decode('ascii')
543 except CScriptTruncatedPushDataError
as err
:
544 op
= '%s...<ERROR: %s>' % (_repr(err
.data
), err
)
546 except CScriptInvalidError
as err
:
547 op
= '<ERROR: %s>' % err
549 except StopIteration:
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.
565 lastOpcode
= OP_INVALIDOPCODE
566 for (opcode
, data
, sop_idx
) in self
.raw_iter():
567 if opcode
in (OP_CHECKSIG
, OP_CHECKSIGVERIFY
):
569 elif opcode
in (OP_CHECKMULTISIG
, OP_CHECKMULTISIGVERIFY
):
570 if fAccurate
and (OP_1
<= lastOpcode
<= OP_16
):
571 n
+= opcode
.decode_op_n()
581 SIGHASH_ANYONECANPAY
= 0x80
583 def FindAndDelete(script
, sig
):
584 """Consensus critical, see FindAndDelete() in Satoshi codebase"""
586 last_sop_idx
= sop_idx
= 0
588 for (opcode
, data
, sop_idx
) in script
.raw_iter():
590 r
+= script
[last_sop_idx
:sop_idx
]
591 last_sop_idx
= sop_idx
592 if script
[sop_idx
:sop_idx
+ len(sig
)] == sig
:
597 r
+= script
[last_sop_idx
:]
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
:
615 txtmp
.vin
[inIdx
].scriptSig
= FindAndDelete(script
, CScript([OP_CODESEPARATOR
]))
617 if (hashtype
& 0x1f) == SIGHASH_NONE
:
620 for i
in range(len(txtmp
.vin
)):
622 txtmp
.vin
[i
].nSequence
= 0
624 elif (hashtype
& 0x1f) == SIGHASH_SINGLE
:
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
]
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
)):
637 txtmp
.vin
[i
].nSequence
= 0
639 if hashtype
& SIGHASH_ANYONECANPAY
:
640 tmp
= txtmp
.vin
[inIdx
]
642 txtmp
.vin
.append(tmp
)
644 s
= txtmp
.serialize()
645 s
+= struct
.pack(b
"<I", hashtype
)
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
):
661 if not (hashtype
& SIGHASH_ANYONECANPAY
):
662 serialize_prevouts
= bytes()
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()
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()
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
))
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
)