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