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
| 384 | |
| 385 | |
| 386 | class CScript(bytes): |
| 387 | """Serialized script |
| 388 | |
| 389 | A bytes subclass, so you can use this directly whenever bytes are accepted. |
| 390 | Note that this means that indexing does *not* work - you'll get an index by |
| 391 | byte rather than opcode. This format was chosen for efficiency so that the |
| 392 | general case would not require creating a lot of little CScriptOP objects. |
| 393 | |
| 394 | iter(script) however does iterate by opcode. |
| 395 | """ |
| 396 | @classmethod |
| 397 | def __coerce_instance(cls, other): |
| 398 | # Coerce other into bytes |
| 399 | if isinstance(other, CScriptOp): |
| 400 | other = bytes([other]) |
| 401 | elif isinstance(other, CScriptNum): |
| 402 | if (other.value == 0): |
| 403 | other = bytes([CScriptOp(OP_0)]) |
| 404 | else: |
| 405 | other = CScriptNum.encode(other) |
| 406 | elif isinstance(other, int): |
| 407 | if 0 <= other <= 16: |
| 408 | other = bytes([CScriptOp.encode_op_n(other)]) |
| 409 | elif other == -1: |
| 410 | other = bytes([OP_1NEGATE]) |
| 411 | else: |
| 412 | other = CScriptOp.encode_op_pushdata(bn2vch(other)) |
| 413 | elif isinstance(other, (bytes, bytearray)): |
| 414 | other = CScriptOp.encode_op_pushdata(other) |
| 415 | return other |
| 416 | |
| 417 | def __add__(self, other): |
| 418 | # Do the coercion outside of the try block so that errors in it are |
| 419 | # noticed. |
| 420 | other = self.__coerce_instance(other) |
| 421 | |
| 422 | try: |
| 423 | # bytes.__add__ always returns bytes instances unfortunately |
| 424 | return CScript(super(CScript, self).__add__(other)) |
| 425 | except TypeError: |
| 426 | raise TypeError('Can not add a %r instance to a CScript' % other.__class__) |
| 427 | |
| 428 | def join(self, iterable): |
| 429 | # join makes no sense for a CScript() |
| 430 | raise NotImplementedError |
| 431 | |
| 432 | def __new__(cls, value=b''): |
| 433 | if isinstance(value, bytes) or isinstance(value, bytearray): |
| 434 | return super(CScript, cls).__new__(cls, value) |
| 435 | else: |
| 436 | def coerce_iterable(iterable): |
| 437 | for instance in iterable: |
| 438 | yield cls.__coerce_instance(instance) |
| 439 | # Annoyingly on both python2 and python3 bytes.join() always |
| 440 | # returns a bytes instance even when subclassed. |
| 441 | return super(CScript, cls).__new__(cls, b''.join(coerce_iterable(value))) |
| 442 | |
| 443 | def raw_iter(self): |
no outgoing calls