A single script opcode
| 52 | return encoded_v.to_bytes(n_bytes, 'little') |
| 53 | |
| 54 | class CScriptOp(int): |
| 55 | """A single script opcode""" |
| 56 | __slots__ = () |
| 57 | |
| 58 | @staticmethod |
| 59 | def encode_op_pushdata(d): |
| 60 | """Encode a PUSHDATA op, returning bytes""" |
| 61 | if len(d) < 0x4c: |
| 62 | return b'' + bytes([len(d)]) + d # OP_PUSHDATA |
| 63 | elif len(d) <= 0xff: |
| 64 | return b'\x4c' + bytes([len(d)]) + d # OP_PUSHDATA1 |
| 65 | elif len(d) <= 0xffff: |
| 66 | return b'\x4d' + struct.pack(b'<H', len(d)) + d # OP_PUSHDATA2 |
| 67 | elif len(d) <= 0xffffffff: |
| 68 | return b'\x4e' + struct.pack(b'<I', len(d)) + d # OP_PUSHDATA4 |
| 69 | else: |
| 70 | raise ValueError("Data too long to encode in a PUSHDATA op") |
| 71 | |
| 72 | @staticmethod |
| 73 | def encode_op_n(n): |
| 74 | """Encode a small integer op, returning an opcode""" |
| 75 | if not (0 <= n <= 16): |
| 76 | raise ValueError('Integer must be in range 0 <= n <= 16, got %d' % n) |
| 77 | |
| 78 | if n == 0: |
| 79 | return OP_0 |
| 80 | else: |
| 81 | return CScriptOp(OP_1 + n - 1) |
| 82 | |
| 83 | def decode_op_n(self): |
| 84 | """Decode a small integer opcode, returning an integer""" |
| 85 | if self == OP_0: |
| 86 | return 0 |
| 87 | |
| 88 | if not (self == OP_0 or OP_1 <= self <= OP_16): |
| 89 | raise ValueError('op %r is not an OP_N' % self) |
| 90 | |
| 91 | return int(self - OP_1 + 1) |
| 92 | |
| 93 | def is_small_int(self): |
| 94 | """Return true if the op pushes a small integer to the stack""" |
| 95 | if 0x51 <= self <= 0x60 or self == 0: |
| 96 | return True |
| 97 | else: |
| 98 | return False |
| 99 | |
| 100 | def __str__(self): |
| 101 | return repr(self) |
| 102 | |
| 103 | def __repr__(self): |
| 104 | if self in OPCODE_NAMES: |
| 105 | return OPCODE_NAMES[self] |
| 106 | else: |
| 107 | return 'CScriptOp(0x%x)' % self |
| 108 | |
| 109 | def __new__(cls, n): |
| 110 | try: |
| 111 | return _opcode_instances[n] |
no outgoing calls