Serialized script A bytes subclass, so you can use this directly whenever bytes are accepted. Note that this means that indexing does *not* work - you'll get an index by byte rather than opcode. This format was chosen for efficiency so that the general case would not require creatin
| 501 | super(CScriptTruncatedPushDataError, self).__init__(msg) |
| 502 | |
| 503 | class CScript(bytes): |
| 504 | """Serialized script |
| 505 | |
| 506 | A bytes subclass, so you can use this directly whenever bytes are accepted. |
| 507 | Note that this means that indexing does *not* work - you'll get an index by |
| 508 | byte rather than opcode. This format was chosen for efficiency so that the |
| 509 | general case would not require creating a lot of little CScriptOP objects. |
| 510 | |
| 511 | iter(script) however does iterate by opcode. |
| 512 | """ |
| 513 | @classmethod |
| 514 | def __coerce_instance(cls, other): |
| 515 | # Coerce other into bytes |
| 516 | if isinstance(other, CScriptOp): |
| 517 | other = bytes([other]) |
| 518 | elif isinstance(other, int): |
| 519 | if 0 <= other <= 16: |
| 520 | other = bytes([CScriptOp.encode_op_n(other)]) |
| 521 | elif other == -1: |
| 522 | other = bytes([OP_1NEGATE]) |
| 523 | else: |
| 524 | other = CScriptOp.encode_op_pushdata(bitcoin.core._bignum.bn2vch(other)) |
| 525 | elif isinstance(other, (bytes, bytearray)): |
| 526 | other = CScriptOp.encode_op_pushdata(other) |
| 527 | return other |
| 528 | |
| 529 | def __add__(self, other): |
| 530 | # Do the coercion outside of the try block so that errors in it are |
| 531 | # noticed. |
| 532 | other = self.__coerce_instance(other) |
| 533 | |
| 534 | try: |
| 535 | # bytes.__add__ always returns bytes instances unfortunately |
| 536 | return CScript(super(CScript, self).__add__(other)) |
| 537 | except TypeError: |
| 538 | raise TypeError('Can not add a %r instance to a CScript' % other.__class__) |
| 539 | |
| 540 | def join(self, iterable): |
| 541 | # join makes no sense for a CScript() |
| 542 | raise NotImplementedError |
| 543 | |
| 544 | def __new__(cls, value=b''): |
| 545 | if isinstance(value, bytes) or isinstance(value, bytearray): |
| 546 | return super(CScript, cls).__new__(cls, value) |
| 547 | else: |
| 548 | def coerce_iterable(iterable): |
| 549 | for instance in iterable: |
| 550 | yield cls.__coerce_instance(instance) |
| 551 | # Annoyingly on both python2 and python3 bytes.join() always |
| 552 | # returns a bytes instance even when subclassed. |
| 553 | return super(CScript, cls).__new__(cls, b''.join(coerce_iterable(value))) |
| 554 | |
| 555 | def raw_iter(self): |
| 556 | """Raw iteration |
| 557 | |
| 558 | Yields tuples of (opcode, data, sop_idx) so that the different possible |
| 559 | PUSHDATA encodings can be accurately distinguished, as well as |
| 560 | determining the exact opcode byte indexes. (sop_idx) |
no outgoing calls