12 Functionality to build scripts, as well as SignatureHash(). 15 from __future__
import absolute_import, division, print_function, unicode_literals
17 from .mininode
import CTransaction, CTxOut, hash256
18 from binascii
import hexlify
25 bchr =
lambda x: bytes([x])
30 from .bignum
import bn2vch
32 MAX_SCRIPT_SIZE = 10000
33 MAX_SCRIPT_ELEMENT_SIZE = 520
34 MAX_SCRIPT_OPCODES = 201
38 _opcode_instances = []
40 """A single script opcode""" 45 """Encode a PUSHDATA op, returning bytes""" 47 return b
'' +
bchr(len(d)) + d
49 return b
'\x4c' +
bchr(len(d)) + d
50 elif len(d) <= 0xffff:
51 return b
'\x4d' + struct.pack(b
'<H', len(d)) + d
52 elif len(d) <= 0xffffffff:
53 return b
'\x4e' + struct.pack(b
'<I', len(d)) + d
55 raise ValueError(
"Data too long to encode in a PUSHDATA op")
59 """Encode a small integer op, returning an opcode""" 60 if not (0 <= n <= 16):
61 raise ValueError(
'Integer must be in range 0 <= n <= 16, got %d' % n)
69 """Decode a small integer opcode, returning an integer""" 73 if not (self == OP_0
or OP_1 <= self <= OP_16):
74 raise ValueError(
'op %r is not an OP_N' % self)
76 return int(self - OP_1+1)
79 """Return true if the op pushes a small integer to the stack""" 80 if 0x51 <= self <= 0x60
or self == 0:
89 if self
in OPCODE_NAMES:
90 return OPCODE_NAMES[self]
92 return 'CScriptOp(0x%x)' % self
96 return _opcode_instances[n]
98 assert len(_opcode_instances) == n
99 _opcode_instances.append(super(CScriptOp, cls).
__new__(cls, n))
100 return _opcode_instances[n]
103 for n
in range(0xff+1):
338 OP_GREATERTHANOREQUAL,
353 OP_CHECKMULTISIGVERIFY,
356 OP_CHECKLOCKTIMEVERIFY,
357 OP_CHECKSEQUENCEVERIFY,
372 OPCODE_NAMES.update({
374 OP_PUSHDATA1 :
'OP_PUSHDATA1',
375 OP_PUSHDATA2 :
'OP_PUSHDATA2',
376 OP_PUSHDATA4 :
'OP_PUSHDATA4',
377 OP_1NEGATE :
'OP_1NEGATE',
378 OP_RESERVED :
'OP_RESERVED',
398 OP_NOTIF :
'OP_NOTIF',
399 OP_VERIF :
'OP_VERIF',
400 OP_VERNOTIF :
'OP_VERNOTIF',
402 OP_ENDIF :
'OP_ENDIF',
403 OP_VERIFY :
'OP_VERIFY',
404 OP_RETURN :
'OP_RETURN',
405 OP_TOALTSTACK :
'OP_TOALTSTACK',
406 OP_FROMALTSTACK :
'OP_FROMALTSTACK',
407 OP_2DROP :
'OP_2DROP',
410 OP_2OVER :
'OP_2OVER',
412 OP_2SWAP :
'OP_2SWAP',
413 OP_IFDUP :
'OP_IFDUP',
414 OP_DEPTH :
'OP_DEPTH',
425 OP_SUBSTR :
'OP_SUBSTR',
427 OP_RIGHT :
'OP_RIGHT',
429 OP_INVERT :
'OP_INVERT',
433 OP_EQUAL :
'OP_EQUAL',
434 OP_EQUALVERIFY :
'OP_EQUALVERIFY',
435 OP_RESERVED1 :
'OP_RESERVED1',
436 OP_RESERVED2 :
'OP_RESERVED2',
441 OP_NEGATE :
'OP_NEGATE',
444 OP_0NOTEQUAL :
'OP_0NOTEQUAL',
450 OP_LSHIFT :
'OP_LSHIFT',
451 OP_RSHIFT :
'OP_RSHIFT',
452 OP_BOOLAND :
'OP_BOOLAND',
453 OP_BOOLOR :
'OP_BOOLOR',
454 OP_NUMEQUAL :
'OP_NUMEQUAL',
455 OP_NUMEQUALVERIFY :
'OP_NUMEQUALVERIFY',
456 OP_NUMNOTEQUAL :
'OP_NUMNOTEQUAL',
457 OP_LESSTHAN :
'OP_LESSTHAN',
458 OP_GREATERTHAN :
'OP_GREATERTHAN',
459 OP_LESSTHANOREQUAL :
'OP_LESSTHANOREQUAL',
460 OP_GREATERTHANOREQUAL :
'OP_GREATERTHANOREQUAL',
463 OP_WITHIN :
'OP_WITHIN',
464 OP_RIPEMD160 :
'OP_RIPEMD160',
466 OP_SHA256 :
'OP_SHA256',
467 OP_HASH160 :
'OP_HASH160',
468 OP_HASH256 :
'OP_HASH256',
469 OP_CODESEPARATOR :
'OP_CODESEPARATOR',
470 OP_CHECKSIG :
'OP_CHECKSIG',
471 OP_CHECKSIGVERIFY :
'OP_CHECKSIGVERIFY',
472 OP_CHECKMULTISIG :
'OP_CHECKMULTISIG',
473 OP_CHECKMULTISIGVERIFY :
'OP_CHECKMULTISIGVERIFY',
475 OP_CHECKLOCKTIMEVERIFY :
'OP_CHECKLOCKTIMEVERIFY',
476 OP_CHECKSEQUENCEVERIFY :
'OP_CHECKSEQUENCEVERIFY',
483 OP_NOP10 :
'OP_NOP10',
484 OP_SMALLINTEGER :
'OP_SMALLINTEGER',
485 OP_PUBKEYS :
'OP_PUBKEYS',
486 OP_PUBKEYHASH :
'OP_PUBKEYHASH',
487 OP_PUBKEY :
'OP_PUBKEY',
488 OP_INVALIDOPCODE :
'OP_INVALIDOPCODE',
493 'OP_PUSHDATA1' : OP_PUSHDATA1,
494 'OP_PUSHDATA2' : OP_PUSHDATA2,
495 'OP_PUSHDATA4' : OP_PUSHDATA4,
496 'OP_1NEGATE' : OP_1NEGATE,
497 'OP_RESERVED' : OP_RESERVED,
517 'OP_NOTIF' : OP_NOTIF,
518 'OP_VERIF' : OP_VERIF,
519 'OP_VERNOTIF' : OP_VERNOTIF,
521 'OP_ENDIF' : OP_ENDIF,
522 'OP_VERIFY' : OP_VERIFY,
523 'OP_RETURN' : OP_RETURN,
524 'OP_TOALTSTACK' : OP_TOALTSTACK,
525 'OP_FROMALTSTACK' : OP_FROMALTSTACK,
526 'OP_2DROP' : OP_2DROP,
529 'OP_2OVER' : OP_2OVER,
531 'OP_2SWAP' : OP_2SWAP,
532 'OP_IFDUP' : OP_IFDUP,
533 'OP_DEPTH' : OP_DEPTH,
544 'OP_SUBSTR' : OP_SUBSTR,
546 'OP_RIGHT' : OP_RIGHT,
548 'OP_INVERT' : OP_INVERT,
552 'OP_EQUAL' : OP_EQUAL,
553 'OP_EQUALVERIFY' : OP_EQUALVERIFY,
554 'OP_RESERVED1' : OP_RESERVED1,
555 'OP_RESERVED2' : OP_RESERVED2,
560 'OP_NEGATE' : OP_NEGATE,
563 'OP_0NOTEQUAL' : OP_0NOTEQUAL,
569 'OP_LSHIFT' : OP_LSHIFT,
570 'OP_RSHIFT' : OP_RSHIFT,
571 'OP_BOOLAND' : OP_BOOLAND,
572 'OP_BOOLOR' : OP_BOOLOR,
573 'OP_NUMEQUAL' : OP_NUMEQUAL,
574 'OP_NUMEQUALVERIFY' : OP_NUMEQUALVERIFY,
575 'OP_NUMNOTEQUAL' : OP_NUMNOTEQUAL,
576 'OP_LESSTHAN' : OP_LESSTHAN,
577 'OP_GREATERTHAN' : OP_GREATERTHAN,
578 'OP_LESSTHANOREQUAL' : OP_LESSTHANOREQUAL,
579 'OP_GREATERTHANOREQUAL' : OP_GREATERTHANOREQUAL,
582 'OP_WITHIN' : OP_WITHIN,
583 'OP_RIPEMD160' : OP_RIPEMD160,
585 'OP_SHA256' : OP_SHA256,
586 'OP_HASH160' : OP_HASH160,
587 'OP_HASH256' : OP_HASH256,
588 'OP_CODESEPARATOR' : OP_CODESEPARATOR,
589 'OP_CHECKSIG' : OP_CHECKSIG,
590 'OP_CHECKSIGVERIFY' : OP_CHECKSIGVERIFY,
591 'OP_CHECKMULTISIG' : OP_CHECKMULTISIG,
592 'OP_CHECKMULTISIGVERIFY' : OP_CHECKMULTISIGVERIFY,
594 'OP_CHECKLOCKTIMEVERIFY' : OP_CHECKLOCKTIMEVERIFY,
595 'OP_CHECKSEQUENCEVERIFY' : OP_CHECKSEQUENCEVERIFY,
602 'OP_NOP10' : OP_NOP10,
603 'OP_SMALLINTEGER' : OP_SMALLINTEGER,
604 'OP_PUBKEYS' : OP_PUBKEYS,
605 'OP_PUBKEYHASH' : OP_PUBKEYHASH,
606 'OP_PUBKEY' : OP_PUBKEY,
610 """Base class for CScript exceptions""" 613 class CScriptTruncatedPushDataError(CScriptInvalidError):
614 """Invalid pushdata due to truncation""" 617 super(CScriptTruncatedPushDataError, self).
__init__(msg)
630 absvalue = -obj.value
if neg
else obj.value
632 r.append(absvalue & 0xff)
635 r.append(0x80
if neg
else 0)
638 return bytes(
bchr(len(r)) + r)
644 A bytes subclass, so you can use this directly whenever bytes are accepted. 645 Note that this means that indexing does *not* work - you'll get an index by 646 byte rather than opcode. This format was chosen for efficiency so that the 647 general case would not require creating a lot of little CScriptOP objects. 649 iter(script) however does iterate by opcode. 654 if isinstance(other, CScriptOp):
656 elif isinstance(other, CScriptNum):
657 if (other.value == 0):
660 other = CScriptNum.encode(other)
661 elif isinstance(other, (int, long)):
663 other = bytes(
bchr(CScriptOp.encode_op_n(other)))
665 other = bytes(
bchr(OP_1NEGATE))
667 other = CScriptOp.encode_op_pushdata(
bn2vch(other))
668 elif isinstance(other, (bytes, bytearray)):
669 other = CScriptOp.encode_op_pushdata(other)
681 raise TypeError(
'Can not add a %r instance to a CScript' % other.__class__)
685 raise NotImplementedError
688 if isinstance(value, bytes)
or isinstance(value, bytearray):
689 return super(CScript, cls).
__new__(cls, value)
691 def coerce_iterable(iterable):
692 for instance
in iterable:
696 return super(CScript, cls).
__new__(cls, b
''.
join(coerce_iterable(value)))
701 Yields tuples of (opcode, data, sop_idx) so that the different possible 702 PUSHDATA encodings can be accurately distinguished, as well as 703 determining the exact opcode byte indexes. (sop_idx) 708 opcode =
bord(self[i])
711 if opcode > OP_PUSHDATA4:
712 yield (opcode,
None, sop_idx)
716 if opcode < OP_PUSHDATA1:
717 pushdata_type =
'PUSHDATA(%d)' % opcode
720 elif opcode == OP_PUSHDATA1:
721 pushdata_type =
'PUSHDATA1' 724 datasize =
bord(self[i])
727 elif opcode == OP_PUSHDATA2:
728 pushdata_type =
'PUSHDATA2' 729 if i + 1 >= len(self):
731 datasize =
bord(self[i]) + (
bord(self[i+1]) << 8)
734 elif opcode == OP_PUSHDATA4:
735 pushdata_type =
'PUSHDATA4' 736 if i + 3 >= len(self):
738 datasize =
bord(self[i]) + (
bord(self[i+1]) << 8) + (
bord(self[i+2]) << 16) + (
bord(self[i+3]) << 24)
745 data = bytes(self[i:i+datasize])
748 if len(data) < datasize:
753 yield (opcode, data, sop_idx)
756 """'Cooked' iteration 758 Returns either a CScriptOP instance, an integer, or bytes, as 761 See raw_iter() if you need to distinguish the different possible 764 for (opcode, data, sop_idx)
in self.
raw_iter():
770 if opcode.is_small_int():
771 yield opcode.decode_op_n()
779 if isinstance(o, bytes):
780 return b
"x('%s')" % hexlify(o).decode(
'ascii')
790 except CScriptTruncatedPushDataError
as err:
791 op =
'%s...<ERROR: %s>' % (_repr(err.data), err)
793 except CScriptInvalidError
as err:
794 op =
'<ERROR: %s>' % err
796 except StopIteration:
802 return "CScript([%s])" %
', '.
join(ops)
805 """Get the SigOp count. 807 fAccurate - Accurately count CHECKMULTISIG, see BIP16 for details. 809 Note that this is consensus-critical. 812 lastOpcode = OP_INVALIDOPCODE
813 for (opcode, data, sop_idx)
in self.
raw_iter():
814 if opcode
in (OP_CHECKSIG, OP_CHECKSIGVERIFY):
816 elif opcode
in (OP_CHECKMULTISIG, OP_CHECKMULTISIGVERIFY):
817 if fAccurate
and (OP_1 <= lastOpcode <= OP_16):
818 n += opcode.decode_op_n()
828 SIGHASH_ANYONECANPAY = 0x80
831 """Consensus critical, see FindAndDelete() in Satoshi codebase""" 833 last_sop_idx = sop_idx = 0
835 for (opcode, data, sop_idx)
in script.raw_iter():
837 r += script[last_sop_idx:sop_idx]
838 last_sop_idx = sop_idx
839 if script[sop_idx:sop_idx + len(sig)] == sig:
844 r += script[last_sop_idx:]
849 """Consensus-correct SignatureHash 851 Returns (hash, err) to precisely match the consensus-critical behavior of 852 the SIGHASH_SINGLE bug. (inIdx is *not* checked for validity) 854 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' 856 if inIdx >= len(txTo.vin):
857 return (HASH_ONE,
"inIdx %d out of range (%d)" % (inIdx, len(txTo.vin)))
860 for txin
in txtmp.vin:
864 if (hashtype & 0x1f) == SIGHASH_NONE:
867 for i
in range(len(txtmp.vin)):
869 txtmp.vin[i].nSequence = 0
871 elif (hashtype & 0x1f) == SIGHASH_SINGLE:
873 if outIdx >= len(txtmp.vout):
874 return (HASH_ONE,
"outIdx %d out of range (%d)" % (outIdx, len(txtmp.vout)))
876 tmp = txtmp.vout[outIdx]
878 for i
in range(outIdx):
879 txtmp.vout.append(
CTxOut())
880 txtmp.vout.append(tmp)
882 for i
in range(len(txtmp.vin)):
884 txtmp.vin[i].nSequence = 0
886 if hashtype & SIGHASH_ANYONECANPAY:
887 tmp = txtmp.vin[inIdx]
889 txtmp.vin.append(tmp)
891 s = txtmp.serialize()
892 s += struct.pack(b
"<I", hashtype)
def __coerce_instance(cls, other)
def __init__(self, msg, data)
def SignatureHash(script, txTo, inIdx, hashtype)
def encode_op_pushdata(d)
def FindAndDelete(script, sig)
def __new__(cls, value=b'')
def GetSigOpCount(self, fAccurate)