Skip to content

Commit 26a5cef

Browse files
feat: update the on chain blueprint serialization methods for the new way
1 parent 9b5544c commit 26a5cef

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

hathorlib/nanocontracts/on_chain_blueprint.py

+15-17
Original file line numberDiff line numberDiff line change
@@ -42,32 +42,33 @@ class Code(NamedTuple):
4242
# determines how the content will be interpreted
4343
kind: CodeKind
4444

45-
# the actual content, usually the uncompressed code in utf-8 bytes
46-
content: bytes
45+
# the encoded content, usually encoded implies compressed
46+
data: bytes
4747

4848
def __bytes__(self) -> bytes:
49-
# Code serialization format: [kind:variable bytes][null byte][content:variable bytes]
49+
# Code serialization format: [kind:variable bytes][null byte][data:variable bytes]
5050
if self.kind is not CodeKind.PYTHON_GZIP:
5151
raise ValueError('Invalid code kind value')
52-
# XXX: zlib is gzip compatible and compresses slightly better
53-
zcode = zlib.compress(self.content)
5452
buf = bytearray()
5553
buf.extend(bytes(self.kind))
5654
buf.append(0)
57-
buf.extend(zcode)
55+
buf.extend(self.data)
5856
return bytes(buf)
5957

6058
@classmethod
61-
def from_bytes(cls, data: bytes, max_length: int) -> 'Code':
62-
""" Parses a Code instance from a byte sequence, the length of the data is encoded outside of this class."""
59+
def from_bytes(cls, data: bytes) -> 'Code':
60+
""" Parses a Code instance from a byte sequence, the length of the data is encoded outside of this class.
61+
62+
NOTE: This will not validate whether the encoded has a valid compression format. A Validator must be used to
63+
check that.
64+
"""
6365
data = bytearray(data)
6466
cut_at = data.index(0)
6567
kind = CodeKind(data[0:cut_at].decode())
66-
dcobj = zlib.decompressobj()
67-
content = dcobj.decompress(data[cut_at + 1:], max_length=max_length)
68-
if not dcobj.eof:
69-
raise ValueError('Decompressed code is too long.')
70-
return cls(kind, content)
68+
if kind is not CodeKind.PYTHON_GZIP:
69+
raise ValueError('Code kind not supported')
70+
compressed_code = data[cut_at + 1:]
71+
return cls(kind, compressed_code)
7172

7273

7374
class OnChainBlueprint(Transaction):
@@ -105,10 +106,7 @@ def deserialize_code(_cls, buf: bytes) -> tuple[Code, bytes]:
105106
if serialized_code_len > max_serialized_code_len:
106107
raise ValueError(f'compressed code data is too large: {serialized_code_len} > {max_serialized_code_len}')
107108
serialized_code, buf = unpack_len(serialized_code_len, buf)
108-
code = Code.from_bytes(
109-
serialized_code,
110-
max_length=settings.NC_ON_CHAIN_BLUEPRINT_CODE_MAX_SIZE_UNCOMPRESSED,
111-
)
109+
code = Code.from_bytes(serialized_code)
112110
return code, buf
113111

114112
def _serialize_ocb(self, *, skip_signature: bool = False) -> bytes:

0 commit comments

Comments
 (0)