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
| 639 | |
| 640 | |
| 641 | class CScript(bytes): |
| 642 | """Serialized script |
| 643 | |
| 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. |
| 648 | |
| 649 | iter(script) however does iterate by opcode. |
| 650 | """ |
| 651 | @classmethod |
| 652 | def __coerce_instance(cls, other): |
| 653 | # Coerce other into bytes |
| 654 | if isinstance(other, CScriptOp): |
| 655 | other = bchr(other) |
| 656 | elif isinstance(other, CScriptNum): |
| 657 | if (other.value == 0): |
| 658 | other = bchr(CScriptOp(OP_0)) |
| 659 | else: |
| 660 | other = CScriptNum.encode(other) |
| 661 | elif isinstance(other, (int, long)): |
| 662 | if 0 <= other <= 16: |
| 663 | other = bytes(bchr(CScriptOp.encode_op_n(other))) |
| 664 | elif other == -1: |
| 665 | other = bytes(bchr(OP_1NEGATE)) |
| 666 | else: |
| 667 | other = CScriptOp.encode_op_pushdata(bn2vch(other)) |
| 668 | elif isinstance(other, (bytes, bytearray)): |
| 669 | other = CScriptOp.encode_op_pushdata(other) |
| 670 | return other |
| 671 | |
| 672 | def __add__(self, other): |
| 673 | # Do the coercion outside of the try block so that errors in it are |
| 674 | # noticed. |
| 675 | other = self.__coerce_instance(other) |
| 676 | |
| 677 | try: |
| 678 | # bytes.__add__ always returns bytes instances unfortunately |
| 679 | return CScript(super(CScript, self).__add__(other)) |
| 680 | except TypeError: |
| 681 | raise TypeError('Can not add a %r instance to a CScript' % other.__class__) |
| 682 | |
| 683 | def join(self, iterable): |
| 684 | # join makes no sense for a CScript() |
| 685 | raise NotImplementedError |
| 686 | |
| 687 | def __new__(cls, value=b''): |
| 688 | if isinstance(value, bytes) or isinstance(value, bytearray): |
| 689 | return super(CScript, cls).__new__(cls, value) |
| 690 | else: |
| 691 | def coerce_iterable(iterable): |
| 692 | for instance in iterable: |
| 693 | yield cls.__coerce_instance(instance) |
| 694 | # Annoyingly on both python2 and python3 bytes.join() always |
| 695 | # returns a bytes instance even when subclassed. |
| 696 | return super(CScript, cls).__new__(cls, b''.join(coerce_iterable(value))) |
| 697 | |
| 698 | def raw_iter(self): |
no outgoing calls