from binascii import hexlify, unhexlify import struct import io SER_DEFAULT = 0 SER_ID = 0 class CompactSize(int): def serialize(self, _stype=SER_DEFAULT): assert self >= 0 if self < 253: return struct.pack(">= 32 return rs def deser_string(f): """Convert an array of bytes in the bitcoin P2P protocol format into a string >>> import io >>> deser_string(io.BytesIO(ser_string("The grid bug bites! You get zapped!".encode()))).decode() 'The grid bug bites! You get zapped!' """ nit = struct.unpack(">> ser_string("The grid bug bites! You get zapped!".encode()) b'$The grid bug bites! You get zapped!' """ if len(s) < 253: return struct.pack("B", len(s)) + s if len(s) < 0x10000: return struct.pack("QQQQ", s[:32]) for i in t: r = (r << 64) | i return r def uint256_from_compact(c): """Convert compact encoding to uint256 Used for the nBits compact encoding of the target in the block header. """ nbytes = (c >> 24) & 0xFF if nbytes <= 3: v = (c & 0xFFFFFF) >> 8 * (3 - nbytes) else: v = (c & 0xFFFFFF) << (8 * (nbytes - 3)) return v def compact_from_uint256(v): """Convert uint256 to compact encoding""" nbytes = (v.bit_length() + 7) >> 3 compact = 0 if nbytes <= 3: compact = (v & 0xFFFFFF) << 8 * (3 - nbytes) else: compact = v >> 8 * (nbytes - 3) compact = compact & 0xFFFFFF # If the sign bit (0x00800000) is set, divide the mantissa by 256 and # increase the exponent to get an encoding without it set. if compact & 0x00800000: compact >>= 8 nbytes += 1 return compact | nbytes << 24 def deser_double(f): return struct.unpack("> 7) - 1 i += 1 ret.append(0x80) return bytes(reversed(ret)) def deser_string_vector(f): nit = struct.unpack(">= 8 if r[-1] & 0x80: r.append(0x80 if neg else 0) elif neg: r[-1] |= 0x80 return r # Deserialize from a hex string representation (eg from RPC) def from_hex(obj, hex_string): obj.deserialize(io.BytesIO(unhexlify(hex_string.strip().encode("ascii")))) return obj # Convert a binary-serializable object to hex (eg for submission via RPC) def to_hex(obj): if isinstance(obj, bytes): return hexlify(obj) return hexlify(obj.serialize()).decode("ascii")