Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions hathor/nanocontracts/blueprint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Copyright 2023 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 typing import Any

from hathor.nanocontracts.exception import BlueprintSyntaxError
from hathor.nanocontracts.types import NC_FALLBACK_METHOD, NC_INITIALIZE_METHOD, NC_METHOD_TYPE_ATTR, NCMethodType

FORBIDDEN_NAMES = {
'syscall',
'log',
}

NC_FIELDS_ATTR: str = '__fields'


class _BlueprintBase(type):
"""Metaclass for blueprints.

This metaclass will modify the attributes and set Fields to them according to their types.
"""

def __new__(cls, name, bases, attrs, **kwargs):
from hathor.nanocontracts.fields import make_field_for_type

# Initialize only subclasses of Blueprint.
parents = [b for b in bases if isinstance(b, _BlueprintBase)]
if not parents:
return super().__new__(cls, name, bases, attrs, **kwargs)

cls._validate_initialize_method(attrs)
cls._validate_fallback_method(attrs)
nc_fields = attrs.get('__annotations__', {})

# Check for forbidden names.
for field_name in nc_fields:
if field_name in FORBIDDEN_NAMES:
raise BlueprintSyntaxError(f'field name is forbidden: `{field_name}`')

if field_name.startswith('_'):
raise BlueprintSyntaxError(f'field name cannot start with underscore: `{field_name}`')

# Create the fields attribute with the type for each field.
attrs[NC_FIELDS_ATTR] = nc_fields

# Use an empty __slots__ to prevent storing any attributes directly on instances.
# The declared attributes are stored as fields on the class, so they still work despite the empty slots.
attrs['__slots__'] = tuple()

# Finally, create class!
new_class = super().__new__(cls, name, bases, attrs, **kwargs)

# Create the Field instance according to each type.
for field_name, field_type in attrs[NC_FIELDS_ATTR].items():
value = getattr(new_class, field_name, None)
if value is None:
# This is the case when a type is specified but not a value.
# Example:
# name: str
# age: int
try:
field = make_field_for_type(field_name, field_type)
except TypeError:
raise BlueprintSyntaxError(
f'unsupported field type `{field_type.__name__}` on field `{field_name}`'
)
setattr(new_class, field_name, field)
else:
# This is the case when a value is specified.
# Example:
# name: str = StrField()
#
# This was not implemented yet and will be extended later.
raise BlueprintSyntaxError(f'fields with default values are currently not supported: `{field_name}`')

return new_class

@staticmethod
def _validate_initialize_method(attrs: Any) -> None:
if NC_INITIALIZE_METHOD not in attrs:
raise BlueprintSyntaxError(f'blueprints require a method called `{NC_INITIALIZE_METHOD}`')

method = attrs[NC_INITIALIZE_METHOD]
method_type = getattr(method, NC_METHOD_TYPE_ATTR, None)

if method_type is not NCMethodType.PUBLIC:
raise BlueprintSyntaxError(f'`{NC_INITIALIZE_METHOD}` method must be annotated with @public')

@staticmethod
def _validate_fallback_method(attrs: Any) -> None:
if NC_FALLBACK_METHOD not in attrs:
return

method = attrs[NC_FALLBACK_METHOD]
method_type = getattr(method, NC_METHOD_TYPE_ATTR, None)

if method_type is not NCMethodType.FALLBACK:
raise BlueprintSyntaxError(f'`{NC_FALLBACK_METHOD}` method must be annotated with @fallback')


class Blueprint(metaclass=_BlueprintBase):
"""Base class for all blueprints.

Example:

class MyBlueprint(Blueprint):
name: str
age: int
"""

__slots__ = ('__env',)
61 changes: 61 additions & 0 deletions hathor/nanocontracts/fields/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Copyright 2023 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 collections import deque
from typing import TypeVar

from hathor.nanocontracts.fields.deque_field import DequeField
from hathor.nanocontracts.fields.dict_field import DictField
from hathor.nanocontracts.fields.field import Field
from hathor.nanocontracts.fields.set_field import SetField
from hathor.nanocontracts.fields.utils import TypeToFieldMap
from hathor.nanocontracts.nc_types import DEFAULT_TYPE_ALIAS_MAP, DEFAULT_TYPE_TO_NC_TYPE_MAP
from hathor.nanocontracts.nc_types.utils import TypeAliasMap, TypeToNCTypeMap

__all__ = [
'DEFAULT_TYPE_TO_FIELD_MAP',
'DequeField',
'DictField',
'Field',
'SetField',
'TypeToFieldMap',
'make_field_for_type',
]

T = TypeVar('T')

DEFAULT_TYPE_TO_FIELD_MAP: TypeToFieldMap = {
dict: DictField,
list: DequeField, # XXX: we should really make a ListField, a deque is different from a list
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should do this. At least the "backend" implementation (how it maps the exposed interface to the storage) can be exactly the same, but Deque is not just the implementation it is the exposed interface, which IMO should be different when only a list (and not a deque), is requested.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postponed thread.

set: SetField,
deque: DequeField,
# XXX: other types fallback to DEFAULT_TYPE_TO_NC_TYPE_MAP
}


def make_field_for_type(
name: str,
type_: type[T],
/,
*,
type_field_map: TypeToFieldMap = DEFAULT_TYPE_TO_FIELD_MAP,
type_nc_type_map: TypeToNCTypeMap = DEFAULT_TYPE_TO_NC_TYPE_MAP,
type_alias_map: TypeAliasMap = DEFAULT_TYPE_ALIAS_MAP,
) -> Field[T]:
""" Like Field.from_name_and_type, but with default maps.

Default arguments can't be easily added to NCType.from_type signature because of recursion.
"""
type_map = Field.TypeMap(type_alias_map, type_nc_type_map, type_field_map)
return Field.from_name_and_type(name, type_, type_map=type_map)
117 changes: 117 additions & 0 deletions hathor/nanocontracts/fields/container_field.py
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For all container fields, review which methods we want to provide. See #1280 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postponed thread.

Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# 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 abc import ABC, abstractmethod
from collections.abc import Container
from typing import Generic, TypeVar

from typing_extensions import TYPE_CHECKING, Self, override

from hathor.nanocontracts.fields.field import Field
from hathor.nanocontracts.storage import NCContractStorage
from hathor.util import not_none
from hathor.utils.typing import InnerTypeMixin, get_origin

if TYPE_CHECKING:
from hathor.nanocontracts.blueprint import Blueprint

C = TypeVar('C', bound=Container)

KEY_SEPARATOR: str = ':'


class StorageContainer(Generic[C], ABC):
""" Abstraction over the class that will be returned when accessing a container field.

Every method and property in this class should use either `__dunder` or `__special__` naming pattern, because
otherwise the property/method would be accessible from an OCB. Even if there would be no harm, this is generally
avoided.
"""
__slots__ = ()

@classmethod
@abstractmethod
def __check_name_and_type__(cls, name: str, type_: type[C]) -> None:
"""Should raise a TypeError if the given name or type is incompatible for use with container."""
raise NotImplementedError

@classmethod
@abstractmethod
def __from_name_and_type__(
cls,
storage: NCContractStorage,
name: str,
type_: type[C],
/,
*,
type_map: Field.TypeMap,
) -> Self:
"""Every StorageContainer should be able to be built with this signature.

Expect a type that has been previously checked with `cls.__check_name_and_type__`.
"""
raise NotImplementedError


T = TypeVar('T', bound=StorageContainer)


class ContainerField(InnerTypeMixin[T], Field[T]):
""" This class models a Field with a StorageContainer, it can't be set, only accessed as a container.

This is modeled after a Python descriptor, similar to the built in `property`, see:

- https://docs.python.org/3/reference/datamodel.html#implementing-descriptors

The observed value behaves like a container, the specific behavior depends on the container type.
"""

__slots__ = ('__name', '__type', '__type_map')
__name: str
__type: type[T]
__type_map: Field.TypeMap

# XXX: customize InnerTypeMixin behavior so it stores the origin type, since that's what we want
@classmethod
def __extract_inner_type__(cls, args: tuple[type, ...], /) -> type[T]:
inner_type: type[T] = InnerTypeMixin.__extract_inner_type__(args)
return not_none(get_origin(inner_type))

@override
@classmethod
def _from_name_and_type(cls, name: str, type_: type[T], /, *, type_map: Field.TypeMap) -> Self:
if not issubclass(cls.__inner_type__, StorageContainer):
raise TypeError(f'{cls.__inner_type__} is not a StorageContainer')
cls.__inner_type__.__check_name_and_type__(name, type_)
field = cls()
field.__name = name
field.__type = type_
field.__type_map = type_map
return field

@override
def __set__(self, instance: Blueprint, value: T) -> None:
# XXX: alternatively this could mimick a `my_container.clear(); my_container.update(value)`
raise AttributeError('cannot set a container field')

@override
def __get__(self, instance: Blueprint, owner: object | None = None) -> T:
raise NotImplementedError('temporarily removed during nano merge')

@override
def __delete__(self, instance: Blueprint) -> None:
# XXX: alternatively delete the database
raise AttributeError('cannot delete a container field')
Loading