Esempio n. 1
0
    Signature,
    TargetAddress,
    TokenAddress,
    TokenAmount,
    TokenNetworkAddress,
    TokenNetworkID,
    TransactionHash,
    Tuple,
    Type,
    TypeVar,
)

EMPTY = "empty"
GENERATE = "generate"

K = TypeVar("K")
V = TypeVar("V")


def _partial_dict(full_dict: Dict[K, V], *args) -> Dict[K, V]:
    return {key: full_dict[key] for key in args}


class Properties:
    """ Base class for all properties classes. """

    DEFAULTS: ClassVar["Properties"] = None
    TARGET_TYPE: ClassVar[Type] = None

    @property
    def kwargs(self):
Esempio n. 2
0
    Iterator,
    List,
    NamedTuple,
    NewType,
    Optional,
    RaidenDBVersion,
    Tuple,
    Type,
    TypeVar,
    Union,
)

StateChangeID = NewType("StateChangeID", ULID)
SnapshotID = NewType("SnapshotID", ULID)
EventID = NewType("EventID", ULID)
ID = TypeVar("ID", StateChangeID, SnapshotID, EventID)


@dataclass
class Range(Generic[ID]):
    """Inclusive range used to filter database entries."""

    first: ID
    last: ID

    def __post_init__(self) -> None:
        # Because the range is inclusive, the values can be equal
        if self.first > self.last:
            raise ValueError("last must be larger or equal to first")

Esempio n. 3
0
        Range(from_identifier, state_change_identifier))
    if unapplied_state_changes:
        log.debug(
            "Replaying state changes",
            replayed_state_changes=[
                redact_secret(DictSerializer.serialize(state_change))
                for state_change in unapplied_state_changes
            ],
            node=to_checksum_address(node_address),
        )
        wal.state_manager.dispatch(unapplied_state_changes)

    return wal


ST = TypeVar("ST", bound=State)


@dataclass(frozen=True)
class SavedState(Generic[ST]):
    """Saves the state and the id of the state change that produced it.

    This datastructure keeps the state and the state_change_id synchronized.
    Having these values available is useful for debugging.
    """

    state_change_id: StateChangeID
    state: ST


class WriteAheadLog(Generic[ST]):
Esempio n. 4
0
    Set,
    Tuple,
    List,
    Optional,
    Address,
    Callable,
    Mapping,
    TypeVar,
    Union,
    Type,
)
from raiden_libs.network.matrix import GMatrixClient, Room

log = structlog.get_logger(__name__)

_CT = TypeVar('CT')  # class type
_CIT = Union[_CT, Type[_CT]]  # class or instance type
_RT = TypeVar('RT')  # return type
_CacheT = Mapping[Tuple, _RT]  # cache type (mapping)


def _cachegetter(
        attr: str,
        cachefactory: Callable[
            [],
            _CacheT] = WeakKeyDictionary,  # WeakKewDict best for properties
) -> Callable[[_CIT], _CacheT]:
    """Returns a safer attrgetter which constructs the missing object with cachefactory

    May be used for normal methods, classmethods and properties, as default
    factory is a WeakKeyDictionary (good for storing weak-refs for self or cls).
Esempio n. 5
0
    Dict,
    Keccak256,
    List,
    Locksroot,
    Secret,
    SecretHash,
    TransactionHash,
    Tuple,
    TypeVar,
)

# The names `T`, `KT`, `VT` are used the same way as the documentation:
#    https://mypy.readthedocs.io/en/latest/generics.html#defining-sub-classes-of-generic-classes
# R stands for return type

T = TypeVar("T")  # function type
RT = TypeVar("RT")  # function return type
KT = TypeVar("KT")  # dict key type
VT = TypeVar("VT")  # dict value type
KRT = TypeVar("KRT")  # dict key return type
VRT = TypeVar("VRT")  # dict value return type


def identity(val: T) -> T:
    return val


def map_dict(key_func: Callable[[KT], KRT], value_func: Callable[[VT], VRT],
             dict_: Dict[KT, VT]) -> Dict[KRT, VRT]:
    return {key_func(k): value_func(v) for k, v in dict_.items()}
Esempio n. 6
0
        assert all(isinstance(e, Event) for e in events)

        return events

    def __eq__(self, other):
        return (
            isinstance(other, StateManager) and
            self.state_transition == other.state_transition and
            self.current_state == other.current_state
        )

    def __ne__(self, other):
        return not self.__eq__(other)


ST = TypeVar('ST', bound=State)


class TransitionResult(Generic[ST]):  # pylint: disable=unsubscriptable-object
    """ Representes the result of applying a single state change.

    When a task is completed the new_state is set to None, allowing the parent
    task to cleanup after the child.
    """

    __slots__ = (
        'new_state',
        'events',
    )

    def __init__(self, new_state: ST, events: List[Event]):
Esempio n. 7
0
    if unapplied_state_changes:
        log.debug(
            "Replaying state changes",
            replayed_state_changes=[
                redact_secret(DictSerializer.serialize(state_change))
                for state_change in unapplied_state_changes
            ],
            node=to_checksum_address(node_address),
        )
        for state_change in unapplied_state_changes:
            wal.state_manager.dispatch(state_change)

    return state_change_qty, len(unapplied_state_changes), wal


ST = TypeVar("ST", bound=State)
ST2 = TypeVar("ST2", bound=State)


@dataclass(frozen=True)
class SavedState(Generic[ST]):
    """Saves the state and the id of the state change that produced it.

    This datastructure keeps the state and the state_change_id synchronized.
    Having these values available is useful for debugging.
    """

    state_change_id: StateChangeID
    state: ST

Esempio n. 8
0

@dataclass(frozen=True)
class ContractReceiveStateChange(StateChange):
    """ Marker used for state changes which represent on-chain logs. """

    transaction_hash: TransactionHash
    block_number: BlockNumber
    block_hash: BlockHash

    def __post_init__(self) -> None:
        typecheck(self.block_number, T_BlockNumber)
        typecheck(self.block_hash, T_BlockHash)


T = TypeVar("T", covariant=True)
ST = TypeVar("ST", bound=State)


class TransitionResult(Generic[T]):  # pylint: disable=unsubscriptable-object
    """ Representes the result of applying a single state change.

    When a task is completed the new_state is set to None, allowing the parent
    task to cleanup after the child.
    """

    def __init__(self, new_state: T, events: List[Event]) -> None:
        self.new_state = new_state
        self.events = events

    def __eq__(self, other: Any) -> bool:
Esempio n. 9
0
from dataclasses import dataclass

from raiden.utils.typing import (
    ABI,
    Address,
    BlockNumber,
    EVMBytecode,
    GasMeasurements,
    Optional,
    TypeVar,
)

T = TypeVar("T")


@dataclass
class SmartContractMetadata:
    """Basic metadata of a smart contract."""

    # If the user deployed the smart contract, the mined block is unknown.
    deployed_at: Optional[BlockNumber]

    # Value to use as `fromBlock` for filters. If the deployed block number is
    # know it must be used, otherwise a hard fork block number can be used as a
    # lower bound.
    #
    # The deployed_at must be used because querying for logs before the smart
    # contract is deployed has bad performance (see #3958), and values larger
    # than the deployed_at will potentially miss logs.
    filters_start_at: BlockNumber
Esempio n. 10
0
        assert len(self.identifier) == 16, "id_ must be 16 bytes long"

    def __repr__(self) -> str:
        return f"ULID<{self.identifier.hex()}>"

    @property
    def timestamp(self) -> int:
        """Aproximated timestamp of the database entry.

        There is no lower bound for the skew in time.
        """
        timestamp_bytes = self.identifier[:8]
        return int.from_bytes(timestamp_bytes, "big")


ID = TypeVar("ID", bound=ULID)


class ULIDMonotonicFactory(Generic[ID]):
    """Monotonic ULID factory that guarantees new ULIDs will not decrease.

    This factory does not follow the SPEC. The timestamp is not walltime and
    the precision was increased from ms to ns to guarantee total order.

    time.time() can not be used because it is not monotonic.  The clock can be
    reset by the user, a NTPD daemon, adjusted because of TZ changes, adjusted
    because of leap seconds, etc. Therefore a monotonic clock must be used.
    """
    def __init__(self, start: Optional[int]) -> None:
        resolution = clock_getres(CLOCK_MONOTONIC_RAW)
Esempio n. 11
0
from collections.abc import Mapping

import gevent

from raiden.raiden_service import RaidenService
from raiden.storage.sqlite import RANGE_ALL_STATE_CHANGES
from raiden.transfer.architecture import Event, StateChange
from raiden.transfer.mediated_transfer.events import EventUnlockClaimFailed, EventUnlockFailed
from raiden.utils.typing import Any, Iterable, List, Optional, Tuple, Type, TypeVar

NOVALUE = object()
T = TypeVar("T")
SC = TypeVar("SC", bound=StateChange)
TM = TypeVar("TM", bound=Mapping)


def check_dict_nested_attrs(item: Mapping, dict_data: Mapping) -> bool:
    """ Checks the values from `dict_data` are contained in `item`

    >>> d = {'a': 1, 'b': {'c': 2}}
    >>> check_dict_nested_attrs(d, {'a': 1})
    True
    >>> check_dict_nested_attrs(d, {'b': {'c': 2}})
    True
    >>> check_dict_nested_attrs(d, {'d': []})
    False
    """
    for key, value in dict_data.items():
        if key not in item:
            return False
Esempio n. 12
0
    Dict,
    Keccak256,
    List,
    Locksroot,
    Secret,
    SecretHash,
    TransactionHash,
    Tuple,
    TypeVar,
)

# The names `T`, `KT`, `VT` are used the same way as the documentation:
#    https://mypy.readthedocs.io/en/latest/generics.html#defining-sub-classes-of-generic-classes
# R stands for return type

T = TypeVar('T')  # function type
RT = TypeVar('RT')  # function return type
KT = TypeVar('KT')  # dict key type
VT = TypeVar('VT')  # dict value type
KRT = TypeVar('KRT')  # dict key return type
VRT = TypeVar('VRT')  # dict value return type


def identity(val: T) -> T:
    return val


def map_dict(
    key_func: Callable[[KT], KRT],
    value_func: Callable[[VT], VRT],
    dict_: Dict[KT, VT],