-
Notifications
You must be signed in to change notification settings - Fork 44
feat(nano): change ctx.address to ctx.caller_id and add support in NC types #1359
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| # Copyright 2025 Hathor Labs | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from types import UnionType | ||
| from typing import _UnionGenericAlias as UnionGenericAlias, assert_never, get_args # type: ignore[attr-defined] | ||
|
|
||
| from typing_extensions import Self, override | ||
|
|
||
| from hathor.crypto.util import decode_address, get_address_b58_from_bytes | ||
| from hathor.nanocontracts.nc_types.nc_type import NCType | ||
| from hathor.nanocontracts.types import Address, CallerId, ContractId | ||
| from hathor.serialization import Deserializer, Serializer | ||
| from hathor.serialization.compound_encoding.caller_id import decode_caller_id, encode_caller_id | ||
| from hathor.transaction.base_transaction import TX_HASH_SIZE | ||
| from hathor.transaction.headers.nano_header import ADDRESS_LEN_BYTES | ||
|
|
||
|
|
||
| class CallerIdNCType(NCType[CallerId]): | ||
| """Represents `CallerID` values, which can be `Address` or `ContractId`.""" | ||
| __slots__ = () | ||
| _is_hashable = True | ||
|
|
||
| @override | ||
| @classmethod | ||
| def _from_type(cls, type_: type[Address] | type[ContractId], /, *, type_map: NCType.TypeMap) -> Self: | ||
| if not isinstance(type_, (UnionType, UnionGenericAlias)): | ||
| raise TypeError('expected type union') | ||
| args = get_args(type_) | ||
| assert args, 'union always has args' | ||
| if len(args) != 2 or Address not in args or ContractId not in args: | ||
| raise TypeError('type must be either `Address | ContractId` or `ContractId | Address`') | ||
| return cls() | ||
|
|
||
| @override | ||
| def _check_value(self, value: CallerId, /, *, deep: bool) -> None: | ||
| match value: | ||
| case Address(): | ||
| if len(value) != ADDRESS_LEN_BYTES: | ||
| raise ValueError(f'an address must always have {ADDRESS_LEN_BYTES} bytes') | ||
| case ContractId(): | ||
| if len(value) != TX_HASH_SIZE: | ||
| raise ValueError(f'an contract id must always have {TX_HASH_SIZE} bytes') | ||
| case _: | ||
| assert_never(value) | ||
|
|
||
| @override | ||
| def _serialize(self, serializer: Serializer, value: CallerId, /) -> None: | ||
| encode_caller_id(serializer, value) | ||
|
|
||
| @override | ||
| def _deserialize(self, deserializer: Deserializer, /) -> CallerId: | ||
| return decode_caller_id(deserializer) | ||
|
|
||
| @override | ||
| def _json_to_value(self, json_value: NCType.Json, /) -> CallerId: | ||
| """ | ||
| >>> nc_type = CallerIdNCType() | ||
| >>> value = nc_type.json_to_value('HH5As5aLtzFkcbmbXZmE65wSd22GqPWq2T') | ||
| >>> isinstance(value, Address) | ||
| True | ||
| >>> value == Address(bytes.fromhex('2873c0a326af979a12be89ee8a00e8871c8e2765022e9b803c')) | ||
| True | ||
| >>> contract_id = ContractId(b'\x11' * 32) | ||
| >>> value = nc_type.json_to_value(contract_id.hex()) | ||
| >>> isinstance(value, ContractId) | ||
| True | ||
| >>> value == contract_id | ||
| True | ||
| >>> nc_type.json_to_value('foo') | ||
| Traceback (most recent call last): | ||
| ... | ||
| ValueError: cannot decode "foo" as CallerId | ||
| """ | ||
| if not isinstance(json_value, str): | ||
| raise ValueError('expected str') | ||
|
|
||
| if len(json_value) == 34: | ||
| return Address(decode_address(json_value)) | ||
|
|
||
| if len(json_value) == TX_HASH_SIZE * 2: | ||
| return ContractId(bytes.fromhex(json_value)) | ||
|
|
||
| raise ValueError(f'cannot decode "{json_value}" as CallerId') | ||
|
|
||
| @override | ||
| def _value_to_json(self, value: CallerId, /) -> NCType.Json: | ||
| """ | ||
| >>> nc_type = CallerIdNCType() | ||
| >>> address = Address(bytes.fromhex('2873c0a326af979a12be89ee8a00e8871c8e2765022e9b803c')) | ||
| >>> nc_type.value_to_json(address) | ||
| 'HH5As5aLtzFkcbmbXZmE65wSd22GqPWq2T' | ||
| >>> contract_id = ContractId(b'\x11' * 32) | ||
| >>> nc_type.value_to_json(contract_id) | ||
| '1111111111111111111111111111111111111111111111111111111111111111' | ||
| """ | ||
| match value: | ||
| case Address(): | ||
| return get_address_b58_from_bytes(value) | ||
| case ContractId(): | ||
| return value.hex() | ||
| case _: | ||
| assert_never(value) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| # Copyright 2025 Hathor Labs | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| r""" | ||
| A caller ID union type is encoded with a single byte identifier followed by the encoded value according to the type. | ||
|
|
||
| Layout: | ||
|
|
||
| [0x00][address] when Address | ||
| [0x01][contract_id] when ContractId | ||
|
|
||
| >>> from hathor.nanocontracts.types import Address, ContractId | ||
| >>> se = Serializer.build_bytes_serializer() | ||
| >>> addr = Address(b'\x11' * 25) | ||
| >>> encode_caller_id(se, addr) | ||
| >>> bytes(se.finalize()).hex() | ||
| '0011111111111111111111111111111111111111111111111111' | ||
|
|
||
| >>> se = Serializer.build_bytes_serializer() | ||
| >>> contract_id = ContractId(b'\x22' * 32) | ||
| >>> encode_caller_id(se, contract_id) | ||
| >>> bytes(se.finalize()).hex() | ||
| '012222222222222222222222222222222222222222222222222222222222222222' | ||
|
|
||
| >>> de = Deserializer.build_bytes_deserializer(bytes.fromhex('0011111111111111111111111111111111111111111111111111')) | ||
| >>> result = decode_caller_id(de) | ||
| >>> isinstance(result, Address) | ||
| True | ||
| >>> de.finalize() | ||
|
|
||
| >>> value = bytes.fromhex('012222222222222222222222222222222222222222222222222222222222222222') | ||
| >>> de = Deserializer.build_bytes_deserializer(value) | ||
| >>> result = decode_caller_id(de) | ||
| >>> isinstance(result, ContractId) | ||
| True | ||
| >>> de.finalize() | ||
| """ | ||
|
|
||
| from typing import assert_never | ||
|
|
||
| from hathor.nanocontracts.types import Address, CallerId, ContractId | ||
| from hathor.serialization import Deserializer, Serializer | ||
| from hathor.serialization.encoding.bool import decode_bool, encode_bool | ||
|
|
||
| from ...transaction.base_transaction import TX_HASH_SIZE | ||
| from ...transaction.headers.nano_header import ADDRESS_LEN_BYTES | ||
|
|
||
|
|
||
| def encode_caller_id(serializer: Serializer, value: CallerId) -> None: | ||
| match value: | ||
| case Address(): | ||
| assert len(value) == ADDRESS_LEN_BYTES | ||
| encode_bool(serializer, False) | ||
| case ContractId(): | ||
| assert len(value) == TX_HASH_SIZE | ||
| encode_bool(serializer, True) | ||
| case _: | ||
| assert_never(value) | ||
| serializer.write_bytes(value) | ||
|
|
||
|
|
||
| def decode_caller_id(deserializer: Deserializer) -> CallerId: | ||
| is_contract = decode_bool(deserializer) | ||
| if is_contract: | ||
| data = bytes(deserializer.read_bytes(TX_HASH_SIZE)) | ||
| return ContractId(data) | ||
| else: | ||
| data = bytes(deserializer.read_bytes(ADDRESS_LEN_BYTES)) | ||
| return Address(data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.