A single script opcode
| 35 | |
| 36 | _opcode_instances = [] |
| 37 | class CScriptOp(int): |
| 38 | """A single script opcode""" |
| 39 | __slots__ = [] |
| 40 | |
| 41 | @staticmethod |
| 42 | def encode_op_pushdata(d): |
| 43 | """Encode a PUSHDATA op, returning bytes""" |
| 44 | if len(d) < 0x4c: |
| 45 | return b'' + bchr(len(d)) + d # OP_PUSHDATA |
| 46 | elif len(d) <= 0xff: |
| 47 | return b'\x4c' + bchr(len(d)) + d # OP_PUSHDATA1 |
| 48 | elif len(d) <= 0xffff: |
| 49 | return b'\x4d' + struct.pack(b'<H', len(d)) + d # OP_PUSHDATA2 |
| 50 | elif len(d) <= 0xffffffff: |
| 51 | return b'\x4e' + struct.pack(b'<I', len(d)) + d # OP_PUSHDATA4 |
| 52 | else: |
| 53 | raise ValueError("Data too long to encode in a PUSHDATA op") |
| 54 | |
| 55 | @staticmethod |
| 56 | def encode_op_n(n): |
| 57 | """Encode a small integer op, returning an opcode""" |
| 58 | if not (0 <= n <= 16): |
| 59 | raise ValueError('Integer must be in range 0 <= n <= 16, got %d' % n) |
| 60 | |
| 61 | if n == 0: |
| 62 | return OP_0 |
| 63 | else: |
| 64 | return CScriptOp(OP_1 + n-1) |
| 65 | |
| 66 | def decode_op_n(self): |
| 67 | """Decode a small integer opcode, returning an integer""" |
| 68 | if self == OP_0: |
| 69 | return 0 |
| 70 | |
| 71 | if not (self == OP_0 or OP_1 <= self <= OP_16): |
| 72 | raise ValueError('op %r is not an OP_N' % self) |
| 73 | |
| 74 | return int(self - OP_1+1) |
| 75 | |
| 76 | def is_small_int(self): |
| 77 | """Return true if the op pushes a small integer to the stack""" |
| 78 | if 0x51 <= self <= 0x60 or self == 0: |
| 79 | return True |
| 80 | else: |
| 81 | return False |
| 82 | |
| 83 | def __str__(self): |
| 84 | return repr(self) |
| 85 | |
| 86 | def __repr__(self): |
| 87 | if self in OPCODE_NAMES: |
| 88 | return OPCODE_NAMES[self] |
| 89 | else: |
| 90 | return 'CScriptOp(0x%x)' % self |
| 91 | |
| 92 | def __new__(cls, n): |
| 93 | try: |
| 94 | return _opcode_instances[n] |
no outgoing calls
no test coverage detected