signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def new_channel(self):
|
partner_privkey, partner_address = factories.make_privkey_address()<EOL>self.address_to_privkey[partner_address] = partner_privkey<EOL>self.address_to_channel[partner_address] = factories.create(<EOL>factories.NettingChannelStateProperties(<EOL>our_state=factories.NettingChannelEndStateProperties(<EOL>balance=<NUM_LIT:1000>,<EOL>address=self.address,<EOL>),<EOL>partner_state=factories.NettingChannelEndStateProperties(<EOL>balance=<NUM_LIT:1000>,<EOL>address=partner_address,<EOL>),<EOL>canonical_identifier=factories.make_canonical_identifier(<EOL>token_network_address=self.token_network_id,<EOL>),<EOL>),<EOL>)<EOL>return partner_address<EOL>
|
Create a new partner address with private key and channel. The
private key and channels are listed in the instance's dictionaries,
the address is returned and should be added to the partners Bundle.
|
f9327:c0:m1
|
def event(self, description):
|
if not self.replay_path:<EOL><INDENT>event(description)<EOL><DEDENT>
|
Wrapper for hypothesis' event function.
hypothesis.event raises an exception when invoked outside of hypothesis
context, so skip it when we are replaying a failed path.
|
f9327:c0:m4
|
@invariant()<EOL><INDENT>def monotonicity(self):<DEDENT>
|
for address, netting_channel in self.address_to_channel.items():<EOL><INDENT>assert netting_channel.our_total_deposit >= self.our_previous_deposit[address]<EOL>assert netting_channel.partner_total_deposit >= self.partner_previous_deposit[address]<EOL>self.our_previous_deposit[address] = netting_channel.our_total_deposit<EOL>self.partner_previous_deposit[address] = netting_channel.partner_total_deposit<EOL>our_transferred = transferred_amount(netting_channel.our_state)<EOL>partner_transferred = transferred_amount(netting_channel.partner_state)<EOL>our_unclaimed = channel.get_amount_unclaimed_onchain(netting_channel.our_state)<EOL>partner_unclaimed = channel.get_amount_unclaimed_onchain(<EOL>netting_channel.partner_state,<EOL>)<EOL>assert our_transferred >= self.our_previous_transferred[address]<EOL>assert partner_transferred >= self.partner_previous_transferred[address]<EOL>assert (<EOL>our_unclaimed + our_transferred >=<EOL>self.our_previous_transferred[address] + self.our_previous_unclaimed[address]<EOL>)<EOL>assert (<EOL>partner_unclaimed + partner_transferred >=<EOL>self.our_previous_transferred[address] + self.our_previous_unclaimed[address]<EOL>)<EOL>self.our_previous_transferred[address] = our_transferred<EOL>self.partner_previous_transferred[address] = partner_transferred<EOL>self.our_previous_unclaimed[address] = our_unclaimed<EOL>self.partner_previous_unclaimed[address] = partner_unclaimed<EOL><DEDENT>
|
Check monotonicity properties as given in Raiden specification
|
f9327:c0:m5
|
@invariant()<EOL><INDENT>def channel_state_invariants(self):<DEDENT>
|
for netting_channel in self.address_to_channel.values():<EOL><INDENT>our_state = netting_channel.our_state<EOL>partner_state = netting_channel.partner_state<EOL>our_transferred_amount = <NUM_LIT:0><EOL>if our_state.balance_proof:<EOL><INDENT>our_transferred_amount = our_state.balance_proof.transferred_amount<EOL>assert our_transferred_amount >= <NUM_LIT:0><EOL><DEDENT>partner_transferred_amount = <NUM_LIT:0><EOL>if partner_state.balance_proof:<EOL><INDENT>partner_transferred_amount = partner_state.balance_proof.transferred_amount<EOL>assert partner_transferred_amount >= <NUM_LIT:0><EOL><DEDENT>assert channel.get_distributable(our_state, partner_state) >= <NUM_LIT:0><EOL>assert channel.get_distributable(partner_state, our_state) >= <NUM_LIT:0><EOL>our_deposit = netting_channel.our_total_deposit<EOL>partner_deposit = netting_channel.partner_total_deposit<EOL>total_deposit = our_deposit + partner_deposit<EOL>our_amount_locked = channel.get_amount_locked(our_state)<EOL>our_balance = channel.get_balance(our_state, partner_state)<EOL>partner_amount_locked = channel.get_amount_locked(partner_state)<EOL>partner_balance = channel.get_balance(partner_state, our_state)<EOL>assert <NUM_LIT:0> <= our_amount_locked <= our_balance<EOL>assert <NUM_LIT:0> <= partner_amount_locked <= partner_balance<EOL>assert our_amount_locked <= total_deposit<EOL>assert partner_amount_locked <= total_deposit<EOL>our_transferred = partner_transferred_amount - our_transferred_amount<EOL>netted_transferred = our_transferred + partner_amount_locked - our_amount_locked<EOL>assert <NUM_LIT:0> <= our_deposit + our_transferred - our_amount_locked <= total_deposit<EOL>assert <NUM_LIT:0> <= partner_deposit - our_transferred - partner_amount_locked <= total_deposit<EOL>assert - our_deposit <= netted_transferred <= partner_deposit<EOL><DEDENT>
|
Check the invariants for the channel state given in the Raiden specification
|
f9327:c0:m6
|
def escape_for_format(string):
|
return string.translate(DUPLICATED_BRACKETS)<EOL>
|
Escape `string` so that it can be used with `.format()`.
>>> escaped = escape_for_format('{}')
>>> escaped + '{}'.format(0)
'{}0'
|
f9329:m0
|
def _chain(first_func, *funcs) -> Callable:
|
@wraps(first_func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>result = first_func(*args, **kwargs)<EOL>for func in funcs:<EOL><INDENT>result = func(result)<EOL><DEDENT>return result<EOL><DEDENT>return wrapper<EOL>
|
Chains a give number of functions.
First function receives all args/kwargs. Its result is passed on as an argument
to the second one and so on and so forth until all function arguments are used.
The last result is then returned.
|
f9331:m0
|
def add_greenlet_name(<EOL>_logger: str,<EOL>_method_name: str,<EOL>event_dict: Dict[str, Any],<EOL>) -> Dict[str, Any]:
|
current_greenlet = gevent.getcurrent()<EOL>greenlet_name = getattr(current_greenlet, '<STR_LIT:name>', None)<EOL>if greenlet_name is not None and not greenlet_name.startswith('<STR_LIT>'):<EOL><INDENT>event_dict['<STR_LIT>'] = greenlet_name<EOL><DEDENT>return event_dict<EOL>
|
Add greenlet_name to the event dict for greenlets that have a non-default name.
|
f9331:m2
|
def redactor(blacklist: Dict[Pattern, str]) -> Callable[[str], str]:
|
def processor_wrapper(msg: str) -> str:<EOL><INDENT>for regex, repl in blacklist.items():<EOL><INDENT>if repl is None:<EOL><INDENT>repl = '<STR_LIT>'<EOL><DEDENT>msg = regex.sub(repl, msg)<EOL><DEDENT>return msg<EOL><DEDENT>return processor_wrapper<EOL>
|
Returns a function which transforms a str, replacing all matches for its replacement
|
f9331:m3
|
def _wrap_tracebackexception_format(redact: Callable[[str], str]):
|
original_format = getattr(TracebackException, '<STR_LIT>', None)<EOL>if original_format is None:<EOL><INDENT>original_format = TracebackException.format<EOL>setattr(TracebackException, '<STR_LIT>', original_format)<EOL><DEDENT>@wraps(original_format)<EOL>def tracebackexception_format(self, *, chain=True):<EOL><INDENT>for line in original_format(self, chain=chain):<EOL><INDENT>yield redact(line)<EOL><DEDENT><DEDENT>setattr(TracebackException, '<STR_LIT>', tracebackexception_format)<EOL>
|
Monkey-patch TracebackException.format to redact printed lines.
Only the last call will be effective. Consecutive calls will overwrite the
previous monkey patches.
|
f9331:m4
|
def __init__(self, config: Dict[str, str], default_level: str):
|
self._should_log: Dict[Tuple[str, str], bool] = {}<EOL>self._default_level = config.get('<STR_LIT>', default_level)<EOL>self._log_rules = [<EOL>(logger.split('<STR_LIT:.>') if logger else list(), level)<EOL>for logger, level in config.items()<EOL>]<EOL>
|
Initializes a new `LogFilter`
Args:
config: Dictionary mapping module names to logging level
default_level: The default logging level
|
f9331:c0:m0
|
def should_log(self, logger_name: str, level: str) -> bool:
|
if (logger_name, level) not in self._should_log:<EOL><INDENT>log_level_per_rule = self._get_log_level(logger_name)<EOL>log_level_per_rule_numeric = getattr(logging, log_level_per_rule.upper(), <NUM_LIT:10>)<EOL>log_level_event_numeric = getattr(logging, level.upper(), <NUM_LIT:10>)<EOL>should_log = log_level_event_numeric >= log_level_per_rule_numeric<EOL>self._should_log[(logger_name, level)] = should_log<EOL><DEDENT>return self._should_log[(logger_name, level)]<EOL>
|
Returns if a message for the logger should be logged.
|
f9331:c0:m2
|
def get_best_routes_internal(<EOL>chain_state: ChainState,<EOL>token_network_id: TokenNetworkID,<EOL>from_address: InitiatorAddress,<EOL>to_address: TargetAddress,<EOL>amount: int,<EOL>previous_address: Optional[Address],<EOL>) -> List[RouteState]:
|
<EOL>available_routes = list()<EOL>token_network = views.get_token_network_by_identifier(<EOL>chain_state,<EOL>token_network_id,<EOL>)<EOL>if not token_network:<EOL><INDENT>return list()<EOL><DEDENT>neighbors_heap: List[Neighbour] = list()<EOL>try:<EOL><INDENT>all_neighbors = networkx.all_neighbors(token_network.network_graph.network, from_address)<EOL><DEDENT>except networkx.NetworkXError:<EOL><INDENT>return list()<EOL><DEDENT>for partner_address in all_neighbors:<EOL><INDENT>if partner_address == previous_address:<EOL><INDENT>continue<EOL><DEDENT>channel_state = views.get_channelstate_by_token_network_and_partner(<EOL>chain_state,<EOL>token_network_id,<EOL>partner_address,<EOL>)<EOL>if not channel_state:<EOL><INDENT>continue<EOL><DEDENT>if channel.get_status(channel_state) != CHANNEL_STATE_OPENED:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>from_address=pex(from_address),<EOL>partner_address=pex(partner_address),<EOL>routing_source='<STR_LIT>',<EOL>)<EOL>continue<EOL><DEDENT>nonrefundable = amount > channel.get_distributable(<EOL>channel_state.partner_state,<EOL>channel_state.our_state,<EOL>)<EOL>try:<EOL><INDENT>length = networkx.shortest_path_length(<EOL>token_network.network_graph.network,<EOL>partner_address,<EOL>to_address,<EOL>)<EOL>neighbour = Neighbour(<EOL>length=length,<EOL>nonrefundable=nonrefundable,<EOL>partner_address=partner_address,<EOL>channelid=channel_state.identifier,<EOL>)<EOL>heappush(neighbors_heap, neighbour)<EOL><DEDENT>except (networkx.NetworkXNoPath, networkx.NodeNotFound):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if not neighbors_heap:<EOL><INDENT>log.warning(<EOL>'<STR_LIT>',<EOL>from_address=pex(from_address),<EOL>to_address=pex(to_address),<EOL>)<EOL>return list()<EOL><DEDENT>while neighbors_heap:<EOL><INDENT>neighbour = heappop(neighbors_heap)<EOL>route_state = RouteState(<EOL>node_address=neighbour.partner_address,<EOL>channel_identifier=neighbour.channelid,<EOL>)<EOL>available_routes.append(route_state)<EOL><DEDENT>return available_routes<EOL>
|
Returns a list of channels that can be used to make a transfer.
This will filter out channels that are not open and don't have enough
capacity.
|
f9332:m1
|
def connect(<EOL>self,<EOL>funds: typing.TokenAmount,<EOL>initial_channel_target: int = <NUM_LIT:3>,<EOL>joinable_funds_target: float = <NUM_LIT>,<EOL>):
|
token = self.raiden.chain.token(self.token_address)<EOL>token_balance = token.balance_of(self.raiden.address)<EOL>if token_balance < funds:<EOL><INDENT>raise InvalidAmount(<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT>if funds <= <NUM_LIT:0>:<EOL><INDENT>raise InvalidAmount(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>if joinable_funds_target < <NUM_LIT:0> or joinable_funds_target > <NUM_LIT:1>:<EOL><INDENT>raise InvalidAmount(<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT>with self.lock:<EOL><INDENT>self.funds = funds<EOL>self.initial_channel_target = initial_channel_target<EOL>self.joinable_funds_target = joinable_funds_target<EOL>log_open_channels(self.raiden, self.registry_address, self.token_address, funds)<EOL>qty_network_channels = views.count_token_network_channels(<EOL>views.state_from_raiden(self.raiden),<EOL>self.registry_address,<EOL>self.token_address,<EOL>)<EOL>if not qty_network_channels:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>network_id=pex(self.registry_address),<EOL>token_id=pex(self.token_address),<EOL>)<EOL>self.api.channel_open(<EOL>self.registry_address,<EOL>self.token_address,<EOL>self.BOOTSTRAP_ADDR,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self._open_channels()<EOL><DEDENT><DEDENT>
|
Connect to the network.
Subsequent calls to `connect` are allowed, but will only affect the spendable
funds and the connection strategy parameters for the future. `connect` will not
close any channels.
Note: the ConnectionManager does not discriminate manually opened channels from
automatically opened ones. If the user manually opened channels, those deposit
amounts will affect the funding per channel and the number of new channels opened.
Args:
funds: Target amount of tokens spendable to join the network.
initial_channel_target: Target number of channels to open.
joinable_funds_target: Amount of funds not initially assigned.
|
f9333:c0:m1
|
def leave(self, registry_address):
|
with self.lock:<EOL><INDENT>self.initial_channel_target = <NUM_LIT:0><EOL>channels_to_close = views.get_channelstate_open(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=registry_address,<EOL>token_address=self.token_address,<EOL>)<EOL>partner_addresses = [<EOL>channel_state.partner_state.address<EOL>for channel_state in channels_to_close<EOL>]<EOL>self.api.channel_batch_close(<EOL>registry_address,<EOL>self.token_address,<EOL>partner_addresses,<EOL>)<EOL>channel_ids = [<EOL>channel_state.identifier<EOL>for channel_state in channels_to_close<EOL>]<EOL>waiting.wait_for_settle(<EOL>self.raiden,<EOL>registry_address,<EOL>self.token_address,<EOL>channel_ids,<EOL>self.raiden.alarm.sleep_time,<EOL>)<EOL><DEDENT>return channels_to_close<EOL>
|
Leave the token network.
This implies closing all channels and waiting for all channels to be
settled.
|
f9333:c0:m2
|
def join_channel(self, partner_address, partner_deposit):
|
<EOL>token_network_proxy = self.raiden.chain.token_network(self.token_network_identifier)<EOL>with self.lock, token_network_proxy.channel_operations_lock[partner_address]:<EOL><INDENT>channel_state = views.get_channelstate_for(<EOL>views.state_from_raiden(self.raiden),<EOL>self.token_network_identifier,<EOL>self.token_address,<EOL>partner_address,<EOL>)<EOL>if not channel_state:<EOL><INDENT>return<EOL><DEDENT>joining_funds = min(<EOL>partner_deposit,<EOL>self._funds_remaining,<EOL>self._initial_funding_per_partner,<EOL>)<EOL>if joining_funds <= <NUM_LIT:0> or self._leaving_state:<EOL><INDENT>return<EOL><DEDENT>if joining_funds <= channel_state.our_state.contract_balance:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>self.api.set_total_channel_deposit(<EOL>self.registry_address,<EOL>self.token_address,<EOL>partner_address,<EOL>joining_funds,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>)<EOL><DEDENT>except InvalidDBData:<EOL><INDENT>raise<EOL><DEDENT>except RaidenUnrecoverableError as e:<EOL><INDENT>should_crash = (<EOL>self.raiden.config['<STR_LIT>'] != Environment.PRODUCTION or<EOL>self.raiden.config['<STR_LIT>']<EOL>)<EOL>if should_crash:<EOL><INDENT>raise<EOL><DEDENT>log.critical(<EOL>str(e),<EOL>node=pex(self.raiden.address),<EOL>)<EOL><DEDENT>else:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>partner=pex(partner_address),<EOL>funds=joining_funds,<EOL>)<EOL><DEDENT><DEDENT>
|
Will be called, when we were selected as channel partner by another
node. It will fund the channel with up to the partners deposit, but
not more than remaining funds or the initial funding per channel.
If the connection manager has no funds, this is a noop.
|
f9333:c0:m3
|
def retry_connect(self):
|
with self.lock:<EOL><INDENT>if self._funds_remaining > <NUM_LIT:0> and not self._leaving_state:<EOL><INDENT>self._open_channels()<EOL><DEDENT><DEDENT>
|
Will be called when new channels in the token network are detected.
If the minimum number of channels was not yet established, it will try
to open new channels.
If the connection manager has no funds, this is a noop.
|
f9333:c0:m4
|
def _find_new_partners(self):
|
open_channels = views.get_channelstate_open(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=self.registry_address,<EOL>token_address=self.token_address,<EOL>)<EOL>known = set(channel_state.partner_state.address for channel_state in open_channels)<EOL>known.add(self.BOOTSTRAP_ADDR)<EOL>known.add(self.raiden.address)<EOL>participants_addresses = views.get_participants_addresses(<EOL>views.state_from_raiden(self.raiden),<EOL>self.registry_address,<EOL>self.token_address,<EOL>)<EOL>available = participants_addresses - known<EOL>available = list(available)<EOL>shuffle(available)<EOL>new_partners = available<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>number_of_partners=len(available),<EOL>)<EOL>return new_partners<EOL>
|
Search the token network for potential channel partners.
|
f9333:c0:m5
|
def _join_partner(self, partner: Address):
|
try:<EOL><INDENT>self.api.channel_open(<EOL>self.registry_address,<EOL>self.token_address,<EOL>partner,<EOL>)<EOL><DEDENT>except DuplicatedChannelError:<EOL><INDENT>pass<EOL><DEDENT>total_deposit = self._initial_funding_per_partner<EOL>if total_deposit == <NUM_LIT:0>:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>self.api.set_total_channel_deposit(<EOL>registry_address=self.registry_address,<EOL>token_address=self.token_address,<EOL>partner_address=partner,<EOL>total_deposit=total_deposit,<EOL>)<EOL><DEDENT>except InvalidDBData:<EOL><INDENT>raise<EOL><DEDENT>except RECOVERABLE_ERRORS:<EOL><INDENT>log.info(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>partner=pex(partner),<EOL>)<EOL><DEDENT>except RaidenUnrecoverableError:<EOL><INDENT>should_crash = (<EOL>self.raiden.config['<STR_LIT>'] != Environment.PRODUCTION or<EOL>self.raiden.config['<STR_LIT>']<EOL>)<EOL>if should_crash:<EOL><INDENT>raise<EOL><DEDENT>log.critical(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>partner=pex(partner),<EOL>)<EOL><DEDENT>
|
Ensure a channel exists with partner and is funded in our side
|
f9333:c0:m6
|
def _open_channels(self) -> bool:
|
open_channels = views.get_channelstate_open(<EOL>chain_state=views.state_from_raiden(self.raiden),<EOL>payment_network_id=self.registry_address,<EOL>token_address=self.token_address,<EOL>)<EOL>open_channels = [<EOL>channel_state<EOL>for channel_state in open_channels<EOL>if channel_state.partner_state.address != self.BOOTSTRAP_ADDR<EOL>]<EOL>funded_channels = [<EOL>channel_state for channel_state in open_channels<EOL>if channel_state.our_state.contract_balance >= self._initial_funding_per_partner<EOL>]<EOL>nonfunded_channels = [<EOL>channel_state for channel_state in open_channels<EOL>if channel_state not in funded_channels<EOL>]<EOL>possible_new_partners = self._find_new_partners()<EOL>if possible_new_partners == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>if len(funded_channels) >= self.initial_channel_target:<EOL><INDENT>return False<EOL><DEDENT>if not nonfunded_channels and possible_new_partners == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>n_to_join = self.initial_channel_target - len(funded_channels)<EOL>nonfunded_partners = [<EOL>channel_state.partner_state.address<EOL>for channel_state in nonfunded_channels<EOL>]<EOL>join_partners = (nonfunded_partners + possible_new_partners)[:n_to_join]<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.raiden.address),<EOL>num_greenlets=len(join_partners),<EOL>)<EOL>greenlets = set(<EOL>gevent.spawn(self._join_partner, partner)<EOL>for partner in join_partners<EOL>)<EOL>gevent.joinall(greenlets, raise_error=True)<EOL>return True<EOL>
|
Open channels until there are `self.initial_channel_target`
channels open. Do nothing if there are enough channels open already.
Note:
- This method must be called with the lock held.
Return:
- False if no channels could be opened
|
f9333:c0:m7
|
@property<EOL><INDENT>def _initial_funding_per_partner(self) -> int:<DEDENT>
|
if self.initial_channel_target:<EOL><INDENT>return int(<EOL>self.funds * (<NUM_LIT:1> - self.joinable_funds_target) /<EOL>self.initial_channel_target,<EOL>)<EOL><DEDENT>return <NUM_LIT:0><EOL>
|
The calculated funding per partner depending on configuration and
overall funding of the ConnectionManager.
Note:
- This attribute must be accessed with the lock held.
|
f9333:c0:m8
|
@property<EOL><INDENT>def _funds_remaining(self) -> int:<DEDENT>
|
if self.funds > <NUM_LIT:0>:<EOL><INDENT>token = self.raiden.chain.token(self.token_address)<EOL>token_balance = token.balance_of(self.raiden.address)<EOL>sum_deposits = views.get_our_capacity_for_token_network(<EOL>views.state_from_raiden(self.raiden),<EOL>self.registry_address,<EOL>self.token_address,<EOL>)<EOL>return min(self.funds - sum_deposits, token_balance)<EOL><DEDENT>return <NUM_LIT:0><EOL>
|
The remaining funds after subtracting the already deposited amounts.
Note:
- This attribute must be accessed with the lock held.
|
f9333:c0:m9
|
@property<EOL><INDENT>def _leaving_state(self) -> bool:<DEDENT>
|
return self.initial_channel_target < <NUM_LIT:1><EOL>
|
True if the node is leaving the token network.
Note:
- This attribute must be accessed with the lock held.
|
f9333:c0:m10
|
def get_random_service(<EOL>service_registry: ServiceRegistry,<EOL>block_identifier: BlockSpecification,<EOL>) -> Tuple[Optional[str], Optional[str]]:
|
count = service_registry.service_count(block_identifier=block_identifier)<EOL>if count == <NUM_LIT:0>:<EOL><INDENT>return None, None<EOL><DEDENT>index = random.SystemRandom().randint(<NUM_LIT:0>, count - <NUM_LIT:1>)<EOL>address = service_registry.get_service_address(<EOL>block_identifier=block_identifier,<EOL>index=index,<EOL>)<EOL>assert address, '<STR_LIT>'<EOL>url = service_registry.get_service_url(<EOL>block_identifier=block_identifier,<EOL>service_hex_address=address,<EOL>)<EOL>return url, address<EOL>
|
Selects a random PFS from service_registry.
Returns a tuple of the chosen services url and eth address.
If there are no PFS in the given registry, it returns (None, None).
|
f9337:m1
|
def configure_pfs_or_exit(<EOL>pfs_address: Optional[str],<EOL>pfs_eth_address: Optional[str],<EOL>routing_mode: RoutingMode,<EOL>service_registry,<EOL>) -> Optional[PFSConfiguration]:
|
if routing_mode == RoutingMode.BASIC:<EOL><INDENT>msg = '<STR_LIT>'<EOL>log.info(msg)<EOL>click.secho(msg)<EOL>return None<EOL><DEDENT>msg = "<STR_LIT>"<EOL>assert pfs_address, msg<EOL>if pfs_address == '<STR_LIT>':<EOL><INDENT>assert service_registry, '<STR_LIT>'<EOL>block_hash = service_registry.client.get_confirmed_blockhash()<EOL>pfs_address, pfs_eth_address = get_random_service(<EOL>service_registry=service_registry,<EOL>block_identifier=block_hash,<EOL>)<EOL>if pfs_address is None:<EOL><INDENT>click.secho(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>assert pfs_eth_address, "<STR_LIT>"<EOL>pathfinding_service_info = get_pfs_info(pfs_address)<EOL>if not pathfinding_service_info:<EOL><INDENT>click.secho(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>',<EOL>)<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>msg = configure_pfs_message(<EOL>info=pathfinding_service_info,<EOL>url=pfs_address,<EOL>eth_address=pfs_eth_address,<EOL>)<EOL>click.secho(msg)<EOL>log.info('<STR_LIT>', pfs_info=pathfinding_service_info)<EOL><DEDENT>return PFSConfiguration(<EOL>url=pfs_address,<EOL>eth_address=pfs_eth_address,<EOL>fee=pathfinding_service_info.get('<STR_LIT>', <NUM_LIT:0>),<EOL>)<EOL>
|
Take in the given pfs_address argument, the service registry and find out a
pfs address to use.
If pfs_address is None then basic routing must have been requested.
If pfs_address is provided we use that.
If pfs_address is 'auto' then we randomly choose a PFS address from the registry
Returns a NamedTuple containing url, eth_address and fee (per paths request) of
the selected PFS, or None if we use basic routing instead of a PFS.
|
f9337:m3
|
def query_paths(<EOL>service_config: Dict[str, Any],<EOL>our_address: Address,<EOL>privkey: bytes,<EOL>current_block_number: BlockNumber,<EOL>token_network_address: Union[TokenNetworkAddress, TokenNetworkID],<EOL>route_from: InitiatorAddress,<EOL>route_to: TargetAddress,<EOL>value: PaymentAmount,<EOL>) -> List[Dict[str, Any]]:
|
max_paths = service_config['<STR_LIT>']<EOL>url = service_config['<STR_LIT>']<EOL>payload = {<EOL>'<STR_LIT>': to_checksum_address(route_from),<EOL>'<STR_LIT:to>': to_checksum_address(route_to),<EOL>'<STR_LIT:value>': value,<EOL>'<STR_LIT>': max_paths,<EOL>}<EOL>offered_fee = service_config.get('<STR_LIT>', service_config['<STR_LIT>'])<EOL>scrap_existing_iou = False<EOL>for retries in reversed(range(MAX_PATHS_QUERY_ATTEMPTS)):<EOL><INDENT>payload['<STR_LIT>'] = create_current_iou(<EOL>config=service_config,<EOL>token_network_address=token_network_address,<EOL>our_address=our_address,<EOL>privkey=privkey,<EOL>block_number=current_block_number,<EOL>offered_fee=offered_fee,<EOL>scrap_existing_iou=scrap_existing_iou,<EOL>)<EOL>try:<EOL><INDENT>return post_pfs_paths(<EOL>url=url,<EOL>token_network_address=token_network_address,<EOL>payload=payload,<EOL>)<EOL><DEDENT>except ServiceRequestIOURejected as error:<EOL><INDENT>code = error.error_code<EOL>if retries == <NUM_LIT:0> or code in (PFSError.WRONG_IOU_RECIPIENT, PFSError.DEPOSIT_TOO_LOW):<EOL><INDENT>raise<EOL><DEDENT>elif code in (PFSError.IOU_ALREADY_CLAIMED, PFSError.IOU_EXPIRED_TOO_EARLY):<EOL><INDENT>scrap_existing_iou = True<EOL><DEDENT>elif code == PFSError.INSUFFICIENT_SERVICE_PAYMENT:<EOL><INDENT>if offered_fee < service_config['<STR_LIT>']:<EOL><INDENT>offered_fee = service_config['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>log.info(f'<STR_LIT>')<EOL><DEDENT><DEDENT>return list()<EOL>
|
Query paths from the PFS.
Send a request to the /paths endpoint of the PFS specified in service_config, and
retry in case of a failed request if it makes sense.
|
f9337:m9
|
def logs_blocks_sanity_check(from_block: BlockSpecification, to_block: BlockSpecification) -> None:
|
is_valid_from = isinstance(from_block, int) or isinstance(from_block, str)<EOL>assert is_valid_from, '<STR_LIT>'<EOL>is_valid_to = isinstance(to_block, int) or isinstance(to_block, str)<EOL>assert is_valid_to, '<STR_LIT>'<EOL>
|
Checks that the from/to blocks passed onto log calls contain only appropriate types
|
f9338:m0
|
def parity_discover_next_available_nonce(<EOL>web3: Web3,<EOL>address: AddressHex,<EOL>) -> Nonce:
|
next_nonce_encoded = web3.manager.request_blocking('<STR_LIT>', [address])<EOL>return Nonce(int(next_nonce_encoded, <NUM_LIT:16>))<EOL>
|
Returns the next available nonce for `address`.
|
f9338:m3
|
def geth_discover_next_available_nonce(<EOL>web3: Web3,<EOL>address: AddressHex,<EOL>) -> Nonce:
|
<EOL>pool = web3.txpool.inspect or {}<EOL>address = to_checksum_address(address)<EOL>queued = pool.get('<STR_LIT>', {}).get(address)<EOL>if queued:<EOL><INDENT>return Nonce(max(int(k) for k in queued.keys()) + <NUM_LIT:1>)<EOL><DEDENT>pending = pool.get('<STR_LIT>', {}).get(address)<EOL>if pending:<EOL><INDENT>return Nonce(max(int(k) for k in pending.keys()) + <NUM_LIT:1>)<EOL><DEDENT>return web3.eth.getTransactionCount(address, '<STR_LIT>')<EOL>
|
Returns the next available nonce for `address`.
|
f9338:m4
|
def check_address_has_code(<EOL>client: '<STR_LIT>',<EOL>address: Address,<EOL>contract_name: str = '<STR_LIT>',<EOL>):
|
result = client.web3.eth.getCode(to_checksum_address(address), '<STR_LIT>')<EOL>if not result:<EOL><INDENT>if contract_name:<EOL><INDENT>formated_contract_name = '<STR_LIT>'.format(contract_name)<EOL><DEDENT>else:<EOL><INDENT>formated_contract_name = '<STR_LIT>'<EOL><DEDENT>raise AddressWithoutCode(<EOL>'<STR_LIT>'.format(<EOL>formated_contract_name,<EOL>to_checksum_address(address),<EOL>),<EOL>)<EOL><DEDENT>
|
Checks that the given address contains code.
|
f9338:m5
|
def dependencies_order_of_build(target_contract, dependencies_map):
|
if not dependencies_map:<EOL><INDENT>return [target_contract]<EOL><DEDENT>if target_contract not in dependencies_map:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(target_contract))<EOL><DEDENT>order = [target_contract]<EOL>todo = list(dependencies_map[target_contract])<EOL>while todo:<EOL><INDENT>target_contract = todo.pop(<NUM_LIT:0>)<EOL>target_pos = len(order)<EOL>for dependency in dependencies_map[target_contract]:<EOL><INDENT>if dependency in order:<EOL><INDENT>target_pos = order.index(dependency)<EOL><DEDENT>else:<EOL><INDENT>todo.append(dependency)<EOL><DEDENT><DEDENT>order.insert(target_pos, target_contract)<EOL><DEDENT>order.reverse()<EOL>return order<EOL>
|
Return an ordered list of contracts that is sufficient to successfully
deploy the target contract.
Note:
This function assumes that the `dependencies_map` is an acyclic graph.
|
f9338:m7
|
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool:
|
try:<EOL><INDENT>error_data = json.loads(str(value_error).replace("<STR_LIT:'>", '<STR_LIT:">'))<EOL><DEDENT>except json.JSONDecodeError:<EOL><INDENT>return False<EOL><DEDENT>if call_type == ParityCallType.ESTIMATE_GAS:<EOL><INDENT>code_checks_out = error_data['<STR_LIT:code>'] == -<NUM_LIT><EOL>message_checks_out = '<STR_LIT>' in error_data['<STR_LIT:message>']<EOL><DEDENT>elif call_type == ParityCallType.CALL:<EOL><INDENT>code_checks_out = error_data['<STR_LIT:code>'] == -<NUM_LIT><EOL>message_checks_out = '<STR_LIT>' in error_data['<STR_LIT:message>']<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if code_checks_out and message_checks_out:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>
|
For parity failing calls and functions do not return None if the transaction
will fail but instead throw a ValueError exception.
This function checks the thrown exception to see if it's the correct one and
if yes returns True, if not returns False
|
f9338:m8
|
def patched_web3_eth_estimate_gas(self, transaction, block_identifier=None):
|
if '<STR_LIT>' not in transaction and is_checksum_address(self.defaultAccount):<EOL><INDENT>transaction = assoc(transaction, '<STR_LIT>', self.defaultAccount)<EOL><DEDENT>if block_identifier is None:<EOL><INDENT>params = [transaction]<EOL><DEDENT>else:<EOL><INDENT>params = [transaction, block_identifier]<EOL><DEDENT>try:<EOL><INDENT>result = self.web3.manager.request_blocking(<EOL>'<STR_LIT>',<EOL>params,<EOL>)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>if check_value_error_for_parity(e, ParityCallType.ESTIMATE_GAS):<EOL><INDENT>result = None<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>return result<EOL>
|
Temporary workaround until next web3.py release (5.X.X)
Current master of web3.py has this implementation already:
https://github.com/ethereum/web3.py/blob/2a67ea9f0ab40bb80af2b803dce742d6cad5943e/web3/eth.py#L311
|
f9338:m9
|
def estimate_gas_for_function(<EOL>address,<EOL>web3,<EOL>fn_identifier=None,<EOL>transaction=None,<EOL>contract_abi=None,<EOL>fn_abi=None,<EOL>block_identifier=None,<EOL>*args,<EOL>**kwargs,<EOL>):
|
estimate_transaction = prepare_transaction(<EOL>address,<EOL>web3,<EOL>fn_identifier=fn_identifier,<EOL>contract_abi=contract_abi,<EOL>fn_abi=fn_abi,<EOL>transaction=transaction,<EOL>fn_args=args,<EOL>fn_kwargs=kwargs,<EOL>)<EOL>try:<EOL><INDENT>gas_estimate = web3.eth.estimateGas(estimate_transaction, block_identifier)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>if check_value_error_for_parity(e, ParityCallType.ESTIMATE_GAS):<EOL><INDENT>gas_estimate = None<EOL><DEDENT>else:<EOL><INDENT>raise e<EOL><DEDENT><DEDENT>return gas_estimate<EOL>
|
Temporary workaround until next web3.py release (5.X.X)
|
f9338:m11
|
def patched_contractfunction_estimateGas(self, transaction=None, block_identifier=None):
|
if transaction is None:<EOL><INDENT>estimate_gas_transaction = {}<EOL><DEDENT>else:<EOL><INDENT>estimate_gas_transaction = dict(**transaction)<EOL><DEDENT>if '<STR_LIT:data>' in estimate_gas_transaction:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if '<STR_LIT:to>' in estimate_gas_transaction:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.address:<EOL><INDENT>estimate_gas_transaction.setdefault('<STR_LIT:to>', self.address)<EOL><DEDENT>if self.web3.eth.defaultAccount is not empty:<EOL><INDENT>estimate_gas_transaction.setdefault('<STR_LIT>', self.web3.eth.defaultAccount)<EOL><DEDENT>if '<STR_LIT:to>' not in estimate_gas_transaction:<EOL><INDENT>if isinstance(self, type):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT><DEDENT>return estimate_gas_for_function(<EOL>self.address,<EOL>self.web3,<EOL>self.function_identifier,<EOL>estimate_gas_transaction,<EOL>self.contract_abi,<EOL>self.abi,<EOL>block_identifier,<EOL>*self.args,<EOL>**self.kwargs,<EOL>)<EOL>
|
Temporary workaround until next web3.py release (5.X.X)
|
f9338:m12
|
def block_number(self):
|
return self.web3.eth.blockNumber<EOL>
|
Return the most recent block.
|
f9338:c1:m2
|
def get_block(self, block_identifier: BlockSpecification) -> Dict:
|
return self.web3.eth.getBlock(block_identifier)<EOL>
|
Given a block number, query the chain to get its corresponding block hash
|
f9338:c1:m3
|
def get_confirmed_blockhash(self):
|
confirmed_block_number = self.web3.eth.blockNumber - self.default_block_num_confirmations<EOL>if confirmed_block_number < <NUM_LIT:0>:<EOL><INDENT>confirmed_block_number = <NUM_LIT:0><EOL><DEDENT>return self.blockhash_from_blocknumber(confirmed_block_number)<EOL>
|
Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash
|
f9338:c1:m4
|
def blockhash_from_blocknumber(self, block_number: BlockSpecification) -> BlockHash:
|
block = self.get_block(block_number)<EOL>return BlockHash(bytes(block['<STR_LIT>']))<EOL>
|
Given a block number, query the chain to get its corresponding block hash
|
f9338:c1:m5
|
def can_query_state_for_block(self, block_identifier: BlockSpecification) -> bool:
|
latest_block_number = self.block_number()<EOL>preconditions_block = self.web3.eth.getBlock(block_identifier)<EOL>preconditions_block_number = int(preconditions_block['<STR_LIT>'])<EOL>difference = latest_block_number - preconditions_block_number<EOL>return difference < constants.NO_STATE_QUERY_AFTER_BLOCKS<EOL>
|
Returns if the provided block identifier is safe enough to query chain
state for. If it's close to the state pruning blocks then state should
not be queried.
More info: https://github.com/raiden-network/raiden/issues/3566.
|
f9338:c1:m6
|
def balance(self, account: Address):
|
return self.web3.eth.getBalance(to_checksum_address(account), '<STR_LIT>')<EOL>
|
Return the balance of the account of the given address.
|
f9338:c1:m7
|
def parity_get_pending_transaction_hash_by_nonce(<EOL>self,<EOL>address: AddressHex,<EOL>nonce: Nonce,<EOL>) -> Optional[TransactionHash]:
|
assert self.eth_node is constants.EthClient.PARITY<EOL>transactions = self.web3.manager.request_blocking('<STR_LIT>', [])<EOL>log.debug('<STR_LIT>', transactions=transactions)<EOL>for tx in transactions:<EOL><INDENT>address_match = to_checksum_address(tx['<STR_LIT>']) == address<EOL>if address_match and int(tx['<STR_LIT>'], <NUM_LIT:16>) == nonce:<EOL><INDENT>return tx['<STR_LIT>']<EOL><DEDENT><DEDENT>return None<EOL>
|
Queries the local parity transaction pool and searches for a transaction.
Checks the local tx pool for a transaction from a particular address and for
a given nonce. If it exists it returns the transaction hash.
|
f9338:c1:m8
|
def new_contract_proxy(self, contract_interface, contract_address: Address):
|
return ContractProxy(<EOL>self,<EOL>contract=self.new_contract(contract_interface, contract_address),<EOL>)<EOL>
|
Return a proxy for interacting with a smart contract.
Args:
contract_interface: The contract interface as defined by the json.
address: The contract's address.
|
f9338:c1:m10
|
def deploy_solidity_contract(<EOL>self, <EOL>contract_name: str,<EOL>all_contracts: Dict[str, ABI],<EOL>libraries: Dict[str, Address] = None,<EOL>constructor_parameters: Tuple[Any] = None,<EOL>contract_path: str = None,<EOL>):
|
if libraries:<EOL><INDENT>libraries = dict(libraries)<EOL><DEDENT>else:<EOL><INDENT>libraries = dict()<EOL><DEDENT>ctor_parameters = constructor_parameters or ()<EOL>all_contracts = copy.deepcopy(all_contracts)<EOL>if contract_name in all_contracts:<EOL><INDENT>contract_key = contract_name<EOL><DEDENT>elif contract_path is not None:<EOL><INDENT>contract_key = os.path.basename(contract_path) + '<STR_LIT::>' + contract_name<EOL>if contract_key not in all_contracts:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(contract_name))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(contract_name),<EOL>)<EOL><DEDENT>contract = all_contracts[contract_key]<EOL>contract_interface = contract['<STR_LIT>']<EOL>symbols = solidity_unresolved_symbols(contract['<STR_LIT>'])<EOL>if symbols:<EOL><INDENT>available_symbols = list(map(solidity_library_symbol, all_contracts.keys()))<EOL>unknown_symbols = set(symbols) - set(available_symbols)<EOL>if unknown_symbols:<EOL><INDENT>msg = '<STR_LIT>'.format(<EOL>available_symbols,<EOL>unknown_symbols,<EOL>)<EOL>raise Exception(msg)<EOL><DEDENT>dependencies = deploy_dependencies_symbols(all_contracts)<EOL>deployment_order = dependencies_order_of_build(contract_key, dependencies)<EOL>deployment_order.pop() <EOL>log.debug(<EOL>'<STR_LIT>'.format(str(deployment_order)),<EOL>node=pex(self.address),<EOL>)<EOL>for deploy_contract in deployment_order:<EOL><INDENT>dependency_contract = all_contracts[deploy_contract]<EOL>hex_bytecode = solidity_resolve_symbols(dependency_contract['<STR_LIT>'], libraries)<EOL>bytecode = decode_hex(hex_bytecode)<EOL>dependency_contract['<STR_LIT>'] = bytecode<EOL>gas_limit = self.web3.eth.getBlock('<STR_LIT>')['<STR_LIT>'] * <NUM_LIT:8> // <NUM_LIT:10><EOL>transaction_hash = self.send_transaction(<EOL>to=Address(b'<STR_LIT>'),<EOL>startgas=gas_limit,<EOL>data=bytecode,<EOL>)<EOL>self.poll(transaction_hash)<EOL>receipt = self.get_transaction_receipt(transaction_hash)<EOL>contract_address = receipt['<STR_LIT>']<EOL>contract_address = remove_0x_prefix(contract_address)<EOL>libraries[deploy_contract] = contract_address<EOL>deployed_code = self.web3.eth.getCode(to_checksum_address(contract_address))<EOL>if not deployed_code:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT><DEDENT>hex_bytecode = solidity_resolve_symbols(contract['<STR_LIT>'], libraries)<EOL>bytecode = decode_hex(hex_bytecode)<EOL>contract['<STR_LIT>'] = bytecode<EOL><DEDENT>if isinstance(contract['<STR_LIT>'], str):<EOL><INDENT>contract['<STR_LIT>'] = decode_hex(contract['<STR_LIT>'])<EOL><DEDENT>contract_object = self.web3.eth.contract(abi=contract['<STR_LIT>'], bytecode=contract['<STR_LIT>'])<EOL>contract_transaction = contract_object.constructor(*ctor_parameters).buildTransaction()<EOL>transaction_hash = self.send_transaction(<EOL>to=Address(b'<STR_LIT>'),<EOL>data=contract_transaction['<STR_LIT:data>'],<EOL>startgas=self._gas_estimate_correction(contract_transaction['<STR_LIT>']),<EOL>)<EOL>self.poll(transaction_hash)<EOL>receipt = self.get_transaction_receipt(transaction_hash)<EOL>contract_address = receipt['<STR_LIT>']<EOL>deployed_code = self.web3.eth.getCode(to_checksum_address(contract_address))<EOL>if not deployed_code:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>'.format(<EOL>contract_name,<EOL>),<EOL>)<EOL><DEDENT>return self.new_contract_proxy(contract_interface, contract_address), receipt<EOL>
|
Deploy a solidity contract.
Args:
contract_name: The name of the contract to compile.
all_contracts: The json dictionary containing the result of compiling a file.
libraries: A list of libraries to use in deployment.
constructor_parameters: A tuple of arguments to pass to the constructor.
contract_path: If we are dealing with solc >= v0.4.9 then the path
to the contract is a required argument to extract
the contract data from the `all_contracts` dict.
|
f9338:c1:m13
|
def send_transaction(<EOL>self,<EOL>to: Address,<EOL>startgas: int,<EOL>value: int = <NUM_LIT:0>,<EOL>data: bytes = b'<STR_LIT>',<EOL>) -> bytes:
|
if to == to_canonical_address(constants.NULL_ADDRESS):<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL><DEDENT>with self._nonce_lock:<EOL><INDENT>nonce = self._available_nonce<EOL>gas_price = self.gas_price()<EOL>transaction = {<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT>': startgas,<EOL>'<STR_LIT>': nonce,<EOL>'<STR_LIT:value>': value,<EOL>'<STR_LIT>': gas_price,<EOL>}<EOL>node_gas_price = self.web3.eth.gasPrice<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(self.address),<EOL>calculated_gas_price=gas_price,<EOL>node_gas_price=node_gas_price,<EOL>)<EOL>if to != b'<STR_LIT>':<EOL><INDENT>transaction['<STR_LIT:to>'] = to_checksum_address(to)<EOL><DEDENT>signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey)<EOL>log_details = {<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': transaction['<STR_LIT>'],<EOL>'<STR_LIT>': transaction['<STR_LIT>'],<EOL>'<STR_LIT>': transaction['<STR_LIT>'],<EOL>}<EOL>log.debug('<STR_LIT>', **log_details)<EOL>tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction)<EOL>self._available_nonce += <NUM_LIT:1><EOL>log.debug('<STR_LIT>', tx_hash=encode_hex(tx_hash), **log_details)<EOL>return tx_hash<EOL><DEDENT>
|
Helper to send signed messages.
This method will use the `privkey` provided in the constructor to
locally sign the transaction. This requires an extended server
implementation that accepts the variables v, r, and s.
|
f9338:c1:m14
|
def poll(<EOL>self,<EOL>transaction_hash: bytes,<EOL>):
|
if len(transaction_hash) != <NUM_LIT:32>:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>transaction_hash = encode_hex(transaction_hash)<EOL>last_result = None<EOL>while True:<EOL><INDENT>transaction = self.web3.eth.getTransaction(transaction_hash)<EOL>if transaction is None and last_result is not None:<EOL><INDENT>raise Exception('<STR_LIT>')<EOL><DEDENT>if transaction and transaction['<STR_LIT>'] is not None:<EOL><INDENT>last_result = transaction<EOL>transaction_block = transaction['<STR_LIT>']<EOL>confirmation_block = transaction_block + self.default_block_num_confirmations<EOL>block_number = self.block_number()<EOL>if block_number >= confirmation_block:<EOL><INDENT>return transaction<EOL><DEDENT><DEDENT>gevent.sleep(<NUM_LIT:1.0>)<EOL><DEDENT>
|
Wait until the `transaction_hash` is applied or rejected.
Args:
transaction_hash: Transaction hash that we are waiting for.
|
f9338:c1:m15
|
def check_for_insufficient_eth(<EOL>self,<EOL>transaction_name: str,<EOL>transaction_executed: bool,<EOL>required_gas: int,<EOL>block_identifier: BlockSpecification,<EOL>):
|
if transaction_executed:<EOL><INDENT>return<EOL><DEDENT>our_address = to_checksum_address(self.address)<EOL>balance = self.web3.eth.getBalance(our_address, block_identifier)<EOL>required_balance = required_gas * self.gas_price()<EOL>if balance < required_balance:<EOL><INDENT>msg = f'<STR_LIT>'<EOL>log.critical(msg, required_wei=required_balance, actual_wei=balance)<EOL>raise InsufficientFunds(msg)<EOL><DEDENT>
|
After estimate gas failure checks if our address has enough balance.
If the account did not have enough ETH balance to execute the,
transaction then it raises an `InsufficientFunds` error
|
f9338:c1:m18
|
def get_checking_block(self):
|
checking_block = '<STR_LIT>'<EOL>if self.eth_node is constants.EthClient.PARITY:<EOL><INDENT>checking_block = '<STR_LIT>'<EOL><DEDENT>return checking_block<EOL>
|
Workaround for parity https://github.com/paritytech/parity-ethereum/issues/9707
In parity doing any call() with the 'pending' block no longer falls back
to the latest if no pending block is found but throws a mistaken error.
Until that bug is fixed we need to enforce special behaviour for parity
and use the latest block for checking.
|
f9338:c1:m19
|
def check_transaction_threw(client, transaction_hash: bytes):
|
receipt = client.get_transaction_receipt(transaction_hash)<EOL>if '<STR_LIT:status>' not in receipt:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>if receipt['<STR_LIT:status>'] == RECEIPT_FAILURE_CODE:<EOL><INDENT>return receipt<EOL><DEDENT>return None<EOL>
|
Check if the transaction threw/reverted or if it executed properly
Returns None in case of success and the transaction receipt if the
transaction's status indicator is 0x0.
|
f9339:m0
|
@staticmethod<EOL><INDENT>def get_transaction_data(<EOL>abi: Dict,<EOL>function_name: str,<EOL>args: Any = None,<EOL>kwargs: Any = None,<EOL>):<DEDENT>
|
args = args or list()<EOL>fn_abi = find_matching_fn_abi(<EOL>abi,<EOL>function_name,<EOL>args=args,<EOL>kwargs=kwargs,<EOL>)<EOL>return encode_transaction_data(<EOL>None,<EOL>function_name,<EOL>contract_abi=abi,<EOL>fn_abi=fn_abi,<EOL>args=args,<EOL>kwargs=kwargs,<EOL>)<EOL>
|
Get encoded transaction data
|
f9340:c1:m2
|
def decode_transaction_input(self, transaction_hash: bytes) -> Dict:
|
transaction = self.contract.web3.eth.getTransaction(<EOL>transaction_hash,<EOL>)<EOL>return self.contract.decode_function_input(<EOL>transaction['<STR_LIT:input>'],<EOL>)<EOL>
|
Return inputs of a method call
|
f9340:c1:m3
|
def estimate_gas(<EOL>self,<EOL>block_identifier,<EOL>function: str,<EOL>*args,<EOL>**kwargs,<EOL>) -> typing.Optional[int]:
|
fn = getattr(self.contract.functions, function)<EOL>address = to_checksum_address(self.jsonrpc_client.address)<EOL>if self.jsonrpc_client.eth_node is constants.EthClient.GETH:<EOL><INDENT>block_identifier = None<EOL><DEDENT>try:<EOL><INDENT>return fn(*args, **kwargs).estimateGas(<EOL>transaction={'<STR_LIT>': address},<EOL>block_identifier=block_identifier,<EOL>)<EOL><DEDENT>except ValueError as err:<EOL><INDENT>action = inspect_client_error(err, self.jsonrpc_client.eth_node)<EOL>will_fail = action in (<EOL>ClientErrorInspectResult.INSUFFICIENT_FUNDS,<EOL>ClientErrorInspectResult.ALWAYS_FAIL,<EOL>)<EOL>if will_fail:<EOL><INDENT>return None<EOL><DEDENT>raise err<EOL><DEDENT>
|
Returns a gas estimate for the function with the given arguments or
None if the function call will fail due to Insufficient funds or
the logic in the called function.
|
f9340:c1:m6
|
def http_retry_with_backoff_middleware(<EOL>make_request,<EOL>web3, <EOL>errors: Tuple = (<EOL>exceptions.ConnectionError,<EOL>exceptions.HTTPError,<EOL>exceptions.Timeout,<EOL>exceptions.TooManyRedirects,<EOL>),<EOL>retries: int = <NUM_LIT:10>,<EOL>first_backoff: float = <NUM_LIT>,<EOL>backoff_factor: float = <NUM_LIT:2>,<EOL>):
|
def middleware(method, params):<EOL><INDENT>backoff = first_backoff<EOL>if check_if_retry_on_failure(method):<EOL><INDENT>for i in range(retries):<EOL><INDENT>try:<EOL><INDENT>return make_request(method, params)<EOL><DEDENT>except errors:<EOL><INDENT>if i < retries - <NUM_LIT:1>:<EOL><INDENT>gevent.sleep(backoff)<EOL>backoff *= backoff_factor<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return make_request(method, params)<EOL><DEDENT><DEDENT>return middleware<EOL>
|
Retry requests with exponential backoff
Creates middleware that retries failed HTTP requests and exponentially
increases the backoff between retries. Meant to replace the default
middleware `http_retry_request_middleware` for HTTPProvider.
|
f9341:m1
|
def __init__(self, source_ip: Host, source_port: Port, strategy='<STR_LIT>', **kwargs):
|
self.source_ip = source_ip<EOL>self.source_port = source_port<EOL>self.method_args = None<EOL>if isinstance(strategy, tuple):<EOL><INDENT>if strategy[<NUM_LIT:1>] is None:<EOL><INDENT>strategy = strategy[<NUM_LIT:0>], source_port<EOL><DEDENT>self.strategy_args = strategy<EOL>strategy = '<STR_LIT>'<EOL><DEDENT>self.strategy = strategy<EOL>self.kwargs = kwargs<EOL>self.method = None<EOL>self.socket = None<EOL>self.storage = {}<EOL>
|
Create a port mapped socket via selectable strategy.
Args:
source_ip (ip string): the network interface/ip to bind
source_port (int): the local port to bind
strategy (str, tuple): Strategy to use to traverse NAT (auto, upnp, stun, none,
(ip, port))
**kwargs: generic kwargs that are passed to the underlying implementations
The traversal methods are implemented in the `map_<method>` and `unmap_<method>` methods.
|
f9342:c1:m0
|
def service_count(self, block_identifier: BlockSpecification) -> int:
|
result = self.proxy.contract.functions.serviceCount().call(<EOL>block_identifier=block_identifier,<EOL>)<EOL>return result<EOL>
|
Get the number of registered services
|
f9344:c0:m1
|
def get_service_address(<EOL>self,<EOL>block_identifier: BlockSpecification,<EOL>index: int,<EOL>) -> Optional[AddressHex]:
|
try:<EOL><INDENT>result = self.proxy.contract.functions.service_addresses(index).call(<EOL>block_identifier=block_identifier,<EOL>)<EOL><DEDENT>except web3.exceptions.BadFunctionCallOutput:<EOL><INDENT>result = None<EOL><DEDENT>return result<EOL>
|
Gets the address of a service by index. If index is out of range return None
|
f9344:c0:m2
|
def get_service_url(<EOL>self,<EOL>block_identifier: BlockSpecification,<EOL>service_hex_address: AddressHex,<EOL>) -> Optional[str]:
|
result = self.proxy.contract.functions.urls(service_hex_address).call(<EOL>block_identifier=block_identifier,<EOL>)<EOL>if result == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>return result<EOL>
|
Gets the URL of a service by address. If does not exist return None
|
f9344:c0:m3
|
def set_url(self, url: str):
|
gas_limit = self.proxy.estimate_gas('<STR_LIT>', '<STR_LIT>', url)<EOL>transaction_hash = self.proxy.transact('<STR_LIT>', gas_limit, url)<EOL>self.client.poll(transaction_hash)<EOL>assert not check_transaction_threw(self.client, transaction_hash)<EOL>
|
Sets the url needed to access the service via HTTP for the caller
|
f9344:c0:m4
|
def register_secret_batch(<EOL>self,<EOL>secrets: List[Secret],<EOL>):
|
secrets_to_register = list()<EOL>secrethashes_to_register = list()<EOL>secrethashes_not_sent = list()<EOL>transaction_result = AsyncResult()<EOL>wait_for = set()<EOL>with self._open_secret_transactions_lock:<EOL><INDENT>verification_block_hash = self.client.get_confirmed_blockhash()<EOL>for secret in secrets:<EOL><INDENT>secrethash = sha3(secret)<EOL>secrethash_hex = encode_hex(secrethash)<EOL>other_result = self.open_secret_transactions.get(secret)<EOL>if other_result is not None:<EOL><INDENT>wait_for.add(other_result)<EOL>secrethashes_not_sent.append(secrethash_hex)<EOL><DEDENT>elif not self.is_secret_registered(secrethash, verification_block_hash):<EOL><INDENT>secrets_to_register.append(secret)<EOL>secrethashes_to_register.append(secrethash_hex)<EOL>self.open_secret_transactions[secret] = transaction_result<EOL><DEDENT><DEDENT><DEDENT>log_details = {<EOL>'<STR_LIT>': pex(self.node_address),<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': secrethashes_to_register,<EOL>'<STR_LIT>': secrethashes_not_sent,<EOL>}<EOL>if not secrets_to_register:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>**log_details,<EOL>)<EOL>gevent.joinall(wait_for, raise_error=True)<EOL>log.info(<EOL>'<STR_LIT>',<EOL>**log_details,<EOL>)<EOL>return<EOL><DEDENT>checking_block = self.client.get_checking_block()<EOL>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>secrets_to_register,<EOL>)<EOL>receipt = None<EOL>transaction_hash = None<EOL>msg = None<EOL>if gas_limit:<EOL><INDENT>gas_limit = safe_gas_limit(<EOL>gas_limit,<EOL>len(secrets_to_register) * GAS_REQUIRED_PER_SECRET_IN_BATCH,<EOL>)<EOL>log.debug('<STR_LIT>', **log_details)<EOL>try:<EOL><INDENT>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>gas_limit,<EOL>secrets_to_register,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt = self.client.get_transaction_receipt(transaction_hash)<EOL><DEDENT>except Exception as e: <EOL><INDENT>msg = f'<STR_LIT>'<EOL><DEDENT><DEDENT>with self._open_secret_transactions_lock:<EOL><INDENT>for secret in secrets_to_register:<EOL><INDENT>self.open_secret_transactions.pop(secret)<EOL><DEDENT><DEDENT>unrecoverable_error = (<EOL>gas_limit is None or<EOL>receipt is None or<EOL>receipt['<STR_LIT:status>'] == RECEIPT_FAILURE_CODE<EOL>)<EOL>exception: Union[RaidenRecoverableError, RaidenUnrecoverableError]<EOL>if unrecoverable_error:<EOL><INDENT>if receipt is not None:<EOL><INDENT>if receipt['<STR_LIT>'] == gas_limit:<EOL><INDENT>error = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>else:<EOL><INDENT>error = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>log.critical(error, **log_details)<EOL>exception = RaidenUnrecoverableError(error)<EOL>transaction_result.set_exception(exception)<EOL>raise exception<EOL><DEDENT>if gas_limit:<EOL><INDENT>assert msg, (<EOL>'<STR_LIT>'<EOL>)<EOL>error = (<EOL>f"<STR_LIT>"<EOL>f"<STR_LIT>"<EOL>f"<STR_LIT>"<EOL>)<EOL>log.critical(error, **log_details)<EOL>exception = RaidenUnrecoverableError(error)<EOL>transaction_result.set_exception(exception)<EOL>raise exception<EOL><DEDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=True,<EOL>required_gas=gas_limit,<EOL>block_identifier=checking_block,<EOL>)<EOL>error = "<STR_LIT>"<EOL>log.critical(error, **log_details)<EOL>exception = RaidenRecoverableError(error)<EOL>transaction_result.set_exception(exception)<EOL>raise exception<EOL><DEDENT>transaction_result.set(transaction_hash)<EOL>if wait_for:<EOL><INDENT>log.info('<STR_LIT>', **log_details)<EOL>gevent.joinall(wait_for, raise_error=True)<EOL><DEDENT>log.info('<STR_LIT>', **log_details)<EOL>
|
Register a batch of secrets. Check if they are already registered at
the given block identifier.
|
f9345:c0:m2
|
def get_secret_registration_block_by_secrethash(<EOL>self,<EOL>secrethash: SecretHash,<EOL>block_identifier: BlockSpecification,<EOL>) -> Optional[BlockNumber]:
|
result = self.proxy.contract.functions.getSecretRevealBlockHeight(<EOL>secrethash,<EOL>).call(block_identifier=block_identifier)<EOL>if result == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return result<EOL>
|
Return the block number at which the secret for `secrethash` was
registered, None if the secret was never registered.
|
f9345:c0:m3
|
def is_secret_registered(<EOL>self,<EOL>secrethash: SecretHash,<EOL>block_identifier: BlockSpecification,<EOL>) -> bool:
|
if not self.client.can_query_state_for_block(block_identifier):<EOL><INDENT>raise NoStateForBlockIdentifier()<EOL><DEDENT>block = self.get_secret_registration_block_by_secrethash(<EOL>secrethash=secrethash,<EOL>block_identifier=block_identifier,<EOL>)<EOL>return block is not None<EOL>
|
True if the secret for `secrethash` is registered at `block_identifier`.
Throws NoStateForBlockIdentifier if the given block_identifier
is older than the pruning limit
|
f9345:c0:m4
|
def add_token_with_limits(<EOL>self,<EOL>token_address: TokenAddress,<EOL>channel_participant_deposit_limit: TokenAmount,<EOL>token_network_deposit_limit: TokenAmount,<EOL>) -> Address:
|
return self._add_token(<EOL>token_address=token_address,<EOL>additional_arguments={<EOL>'<STR_LIT>': channel_participant_deposit_limit,<EOL>'<STR_LIT>': token_network_deposit_limit,<EOL>},<EOL>)<EOL>
|
Register token of `token_address` with the token network.
The limits apply for version 0.13.0 and above of raiden-contracts,
since instantiation also takes the limits as constructor arguments.
|
f9346:c0:m2
|
def add_token_without_limits(<EOL>self,<EOL>token_address: TokenAddress,<EOL>) -> Address:
|
return self._add_token(<EOL>token_address=token_address,<EOL>additional_arguments=dict(),<EOL>)<EOL>
|
Register token of `token_address` with the token network.
This applies for versions prior to 0.13.0 of raiden-contracts,
since limits were hardcoded into the TokenNetwork contract.
|
f9346:c0:m3
|
def settlement_timeout_min(self) -> int:
|
return self.proxy.contract.functions.settlement_timeout_min().call()<EOL>
|
Returns the minimal settlement timeout for the token network registry.
|
f9346:c0:m7
|
def settlement_timeout_max(self) -> int:
|
return self.proxy.contract.functions.settlement_timeout_max().call()<EOL>
|
Returns the maximal settlement timeout for the token network registry.
|
f9346:c0:m8
|
def deposit(<EOL>self,<EOL>beneficiary: Address,<EOL>total_deposit: TokenAmount,<EOL>block_identifier: BlockSpecification,<EOL>) -> None:
|
token_address = self.token_address(block_identifier)<EOL>token = Token(<EOL>jsonrpc_client=self.client,<EOL>token_address=token_address,<EOL>contract_manager=self.contract_manager,<EOL>)<EOL>log_details = {<EOL>'<STR_LIT>': pex(beneficiary),<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': total_deposit,<EOL>}<EOL>checking_block = self.client.get_checking_block()<EOL>error_prefix = '<STR_LIT>'<EOL>with self.deposit_lock:<EOL><INDENT>amount_to_deposit, log_details = self._deposit_preconditions(<EOL>total_deposit=total_deposit,<EOL>beneficiary=beneficiary,<EOL>token=token,<EOL>block_identifier=block_identifier,<EOL>)<EOL>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>to_checksum_address(beneficiary),<EOL>total_deposit,<EOL>)<EOL>if gas_limit:<EOL><INDENT>error_prefix = '<STR_LIT>'<EOL>log.debug('<STR_LIT>', **log_details)<EOL>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>safe_gas_limit(gas_limit),<EOL>to_checksum_address(beneficiary),<EOL>total_deposit,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt_or_none = check_transaction_threw(self.client, transaction_hash)<EOL><DEDENT>transaction_executed = gas_limit is not None<EOL>if not transaction_executed or receipt_or_none:<EOL><INDENT>if transaction_executed:<EOL><INDENT>block = receipt_or_none['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>block = checking_block<EOL><DEDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=transaction_executed,<EOL>required_gas=GAS_REQUIRED_FOR_UDC_DEPOSIT,<EOL>block_identifier=block,<EOL>)<EOL>msg = self._check_why_deposit_failed(<EOL>token=token,<EOL>amount_to_deposit=amount_to_deposit,<EOL>total_deposit=total_deposit,<EOL>block_identifier=block,<EOL>)<EOL>error_msg = f'<STR_LIT>'<EOL>log.critical(error_msg, **log_details)<EOL>raise RaidenUnrecoverableError(error_msg)<EOL><DEDENT><DEDENT>log.info('<STR_LIT>', **log_details)<EOL>
|
Deposit provided amount into the user-deposit contract
to the beneficiary's account.
|
f9347:c0:m3
|
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance:
|
fn = getattr(self.proxy.contract.functions, '<STR_LIT>')<EOL>balance = fn(address).call(block_identifier=block_identifier)<EOL>if balance == b'<STR_LIT>':<EOL><INDENT>raise RuntimeError(f"<STR_LIT>")<EOL><DEDENT>return balance<EOL>
|
The user's balance with planned withdrawals deducted.
|
f9347:c0:m4
|
def token_address(self) -> Address:
|
return to_canonical_address(self.proxy.contract.functions.token().call())<EOL>
|
Return the token of this manager.
|
f9348:c4:m2
|
def new_netting_channel(<EOL>self,<EOL>partner: Address,<EOL>settle_timeout: int,<EOL>given_block_identifier: BlockSpecification,<EOL>) -> ChannelID:
|
checking_block = self.client.get_checking_block()<EOL>self._new_channel_preconditions(<EOL>partner=partner,<EOL>settle_timeout=settle_timeout,<EOL>block_identifier=given_block_identifier,<EOL>)<EOL>log_details = {<EOL>'<STR_LIT>': pex(self.node_address),<EOL>'<STR_LIT>': pex(partner),<EOL>}<EOL>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>participant1=self.node_address,<EOL>participant2=partner,<EOL>settle_timeout=settle_timeout,<EOL>)<EOL>if not gas_limit:<EOL><INDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=False,<EOL>required_gas=GAS_REQUIRED_FOR_OPEN_CHANNEL,<EOL>block_identifier=checking_block,<EOL>)<EOL>self._new_channel_postconditions(<EOL>partner=partner,<EOL>block=checking_block,<EOL>)<EOL>log.critical('<STR_LIT>', **log_details)<EOL>raise RaidenUnrecoverableError('<STR_LIT>')<EOL><DEDENT>log.debug('<STR_LIT>', **log_details)<EOL>if gas_limit and partner not in self.open_channel_transactions:<EOL><INDENT>new_open_channel_transaction = AsyncResult()<EOL>self.open_channel_transactions[partner] = new_open_channel_transaction<EOL>gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_OPEN_CHANNEL)<EOL>try:<EOL><INDENT>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>gas_limit,<EOL>participant1=self.node_address,<EOL>participant2=partner,<EOL>settle_timeout=settle_timeout,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt_or_none = check_transaction_threw(self.client, transaction_hash)<EOL>if receipt_or_none:<EOL><INDENT>self._new_channel_postconditions(<EOL>partner=partner,<EOL>block=receipt_or_none['<STR_LIT>'],<EOL>)<EOL>log.critical('<STR_LIT>', **log_details)<EOL>raise RaidenUnrecoverableError('<STR_LIT>')<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.critical('<STR_LIT>', **log_details)<EOL>new_open_channel_transaction.set_exception(e)<EOL>raise<EOL><DEDENT>else:<EOL><INDENT>new_open_channel_transaction.set(transaction_hash)<EOL><DEDENT>finally:<EOL><INDENT>self.open_channel_transactions.pop(partner, None)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.open_channel_transactions[partner].get()<EOL><DEDENT>channel_identifier: ChannelID = self._detail_channel(<EOL>participant1=self.node_address,<EOL>participant2=partner,<EOL>block_identifier='<STR_LIT>',<EOL>).channel_identifier<EOL>log_details['<STR_LIT>'] = str(channel_identifier)<EOL>log.info('<STR_LIT>', **log_details)<EOL>return channel_identifier<EOL>
|
Creates a new channel in the TokenNetwork contract.
Args:
partner: The peer to open the channel with.
settle_timeout: The settle timeout to use for this channel.
given_block_identifier: The block identifier of the state change that
prompted this proxy action
Returns:
The ChannelID of the new netting channel.
|
f9348:c4:m5
|
def _channel_exists_and_not_settled(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID = None,<EOL>) -> bool:
|
try:<EOL><INDENT>channel_state = self._get_channel_state(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>return False<EOL><DEDENT>exists_and_not_settled = (<EOL>channel_state > ChannelState.NONEXISTENT and<EOL>channel_state < ChannelState.SETTLED<EOL>)<EOL>return exists_and_not_settled<EOL>
|
Returns if the channel exists and is in a non-settled state
|
f9348:c4:m7
|
def _detail_participant(<EOL>self,<EOL>channel_identifier: ChannelID,<EOL>participant: Address,<EOL>partner: Address,<EOL>block_identifier: BlockSpecification,<EOL>) -> ParticipantDetails:
|
data = self._call_and_check_result(<EOL>block_identifier,<EOL>'<STR_LIT>',<EOL>channel_identifier=channel_identifier,<EOL>participant=to_checksum_address(participant),<EOL>partner=to_checksum_address(partner),<EOL>)<EOL>return ParticipantDetails(<EOL>address=participant,<EOL>deposit=data[ParticipantInfoIndex.DEPOSIT],<EOL>withdrawn=data[ParticipantInfoIndex.WITHDRAWN],<EOL>is_closer=data[ParticipantInfoIndex.IS_CLOSER],<EOL>balance_hash=data[ParticipantInfoIndex.BALANCE_HASH],<EOL>nonce=data[ParticipantInfoIndex.NONCE],<EOL>locksroot=data[ParticipantInfoIndex.LOCKSROOT],<EOL>locked_amount=data[ParticipantInfoIndex.LOCKED_AMOUNT],<EOL>)<EOL>
|
Returns a dictionary with the channel participant information.
|
f9348:c4:m8
|
def _detail_channel(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID = None,<EOL>) -> ChannelData:
|
channel_identifier = self._inspect_channel_identifier(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>called_by_fn='<STR_LIT>',<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL>channel_data = self._call_and_check_result(<EOL>block_identifier,<EOL>'<STR_LIT>',<EOL>channel_identifier=channel_identifier,<EOL>participant1=to_checksum_address(participant1),<EOL>participant2=to_checksum_address(participant2),<EOL>)<EOL>return ChannelData(<EOL>channel_identifier=channel_identifier,<EOL>settle_block_number=channel_data[ChannelInfoIndex.SETTLE_BLOCK],<EOL>state=channel_data[ChannelInfoIndex.STATE],<EOL>)<EOL>
|
Returns a ChannelData instance with the channel specific information.
If no specific channel_identifier is given then it tries to see if there
is a currently open channel and uses that identifier.
|
f9348:c4:m9
|
def detail_participants(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID = None,<EOL>) -> ParticipantsDetails:
|
if self.node_address not in (participant1, participant2):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.node_address == participant2:<EOL><INDENT>participant1, participant2 = participant2, participant1<EOL><DEDENT>channel_identifier = self._inspect_channel_identifier(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>called_by_fn='<STR_LIT>',<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL>our_data = self._detail_participant(<EOL>channel_identifier=channel_identifier,<EOL>participant=participant1,<EOL>partner=participant2,<EOL>block_identifier=block_identifier,<EOL>)<EOL>partner_data = self._detail_participant(<EOL>channel_identifier=channel_identifier,<EOL>participant=participant2,<EOL>partner=participant1,<EOL>block_identifier=block_identifier,<EOL>)<EOL>return ParticipantsDetails(our_details=our_data, partner_details=partner_data)<EOL>
|
Returns a ParticipantsDetails instance with the participants'
channel information.
Note:
For now one of the participants has to be the node_address
|
f9348:c4:m10
|
def detail(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID = None,<EOL>) -> ChannelDetails:
|
if self.node_address not in (participant1, participant2):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.node_address == participant2:<EOL><INDENT>participant1, participant2 = participant2, participant1<EOL><DEDENT>channel_data = self._detail_channel(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL>participants_data = self.detail_participants(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_data.channel_identifier,<EOL>)<EOL>chain_id = self.proxy.contract.functions.chain_id().call()<EOL>return ChannelDetails(<EOL>chain_id=chain_id,<EOL>channel_data=channel_data,<EOL>participants_data=participants_data,<EOL>)<EOL>
|
Returns a ChannelDetails instance with all the details of the
channel and the channel participants.
Note:
For now one of the participants has to be the node_address
|
f9348:c4:m11
|
def settlement_timeout_min(self) -> int:
|
return self.proxy.contract.functions.settlement_timeout_min().call()<EOL>
|
Returns the minimal settlement timeout for the token network.
|
f9348:c4:m12
|
def settlement_timeout_max(self) -> int:
|
return self.proxy.contract.functions.settlement_timeout_max().call()<EOL>
|
Returns the maximal settlement timeout for the token network.
|
f9348:c4:m13
|
def channel_is_opened(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID,<EOL>) -> bool:
|
try:<EOL><INDENT>channel_state = self._get_channel_state(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>return False<EOL><DEDENT>return channel_state == ChannelState.OPENED<EOL>
|
Returns true if the channel is in an open state, false otherwise.
|
f9348:c4:m14
|
def channel_is_closed(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID,<EOL>) -> bool:
|
try:<EOL><INDENT>channel_state = self._get_channel_state(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>return False<EOL><DEDENT>return channel_state == ChannelState.CLOSED<EOL>
|
Returns true if the channel is in a closed state, false otherwise.
|
f9348:c4:m15
|
def channel_is_settled(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID,<EOL>) -> bool:
|
try:<EOL><INDENT>channel_state = self._get_channel_state(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>return False<EOL><DEDENT>return channel_state >= ChannelState.SETTLED<EOL>
|
Returns true if the channel is in a settled state, false otherwise.
|
f9348:c4:m16
|
def closing_address(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID = None,<EOL>) -> Optional[Address]:
|
try:<EOL><INDENT>channel_data = self._detail_channel(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>return None<EOL><DEDENT>if channel_data.state >= ChannelState.SETTLED:<EOL><INDENT>return None<EOL><DEDENT>participants_data = self.detail_participants(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_data.channel_identifier,<EOL>)<EOL>if participants_data.our_details.is_closer:<EOL><INDENT>return participants_data.our_details.address<EOL><DEDENT>elif participants_data.partner_details.is_closer:<EOL><INDENT>return participants_data.partner_details.address<EOL><DEDENT>return None<EOL>
|
Returns the address of the closer, if the channel is closed and not settled. None
otherwise.
|
f9348:c4:m17
|
def can_transfer(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID,<EOL>) -> bool:
|
opened = self.channel_is_opened(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL>if opened is False:<EOL><INDENT>return False<EOL><DEDENT>deposit = self._detail_participant(<EOL>channel_identifier=channel_identifier,<EOL>participant=participant1,<EOL>partner=participant2,<EOL>block_identifier=block_identifier,<EOL>).deposit<EOL>return deposit > <NUM_LIT:0><EOL>
|
Returns True if the channel is opened and the node has deposit in
it.
Note: Having a deposit does not imply having a balance for off-chain
transfers.
|
f9348:c4:m18
|
def set_total_deposit(<EOL>self,<EOL>given_block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID,<EOL>total_deposit: TokenAmount,<EOL>partner: Address,<EOL>):
|
if not isinstance(total_deposit, int):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>token_address = self.token_address()<EOL>token = Token(<EOL>jsonrpc_client=self.client,<EOL>token_address=token_address,<EOL>contract_manager=self.contract_manager,<EOL>)<EOL>checking_block = self.client.get_checking_block()<EOL>error_prefix = '<STR_LIT>'<EOL>with self.channel_operations_lock[partner], self.deposit_lock:<EOL><INDENT>previous_total_deposit = self._detail_participant(<EOL>channel_identifier=channel_identifier,<EOL>participant=self.node_address,<EOL>partner=partner,<EOL>block_identifier=given_block_identifier,<EOL>).deposit<EOL>amount_to_deposit = TokenAmount(total_deposit - previous_total_deposit)<EOL>log_details = {<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': channel_identifier,<EOL>'<STR_LIT>': pex(self.node_address),<EOL>'<STR_LIT>': pex(partner),<EOL>'<STR_LIT>': total_deposit,<EOL>'<STR_LIT>': previous_total_deposit,<EOL>}<EOL>try:<EOL><INDENT>self._deposit_preconditions(<EOL>channel_identifier=channel_identifier,<EOL>total_deposit=total_deposit,<EOL>partner=partner,<EOL>token=token,<EOL>previous_total_deposit=previous_total_deposit,<EOL>log_details=log_details,<EOL>block_identifier=given_block_identifier,<EOL>)<EOL><DEDENT>except NoStateForBlockIdentifier:<EOL><INDENT>pass<EOL><DEDENT>token.approve(<EOL>allowed_address=Address(self.address),<EOL>allowance=amount_to_deposit,<EOL>)<EOL>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>channel_identifier=channel_identifier,<EOL>participant=self.node_address,<EOL>total_deposit=total_deposit,<EOL>partner=partner,<EOL>)<EOL>if gas_limit:<EOL><INDENT>gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT)<EOL>error_prefix = '<STR_LIT>'<EOL>log.debug('<STR_LIT>', **log_details)<EOL>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>gas_limit,<EOL>channel_identifier=channel_identifier,<EOL>participant=self.node_address,<EOL>total_deposit=total_deposit,<EOL>partner=partner,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt_or_none = check_transaction_threw(self.client, transaction_hash)<EOL><DEDENT>transaction_executed = gas_limit is not None<EOL>if not transaction_executed or receipt_or_none:<EOL><INDENT>if transaction_executed:<EOL><INDENT>block = receipt_or_none['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>block = checking_block<EOL><DEDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=transaction_executed,<EOL>required_gas=GAS_REQUIRED_FOR_SET_TOTAL_DEPOSIT,<EOL>block_identifier=block,<EOL>)<EOL>error_type, msg = self._check_why_deposit_failed(<EOL>channel_identifier=channel_identifier,<EOL>partner=partner,<EOL>token=token,<EOL>amount_to_deposit=amount_to_deposit,<EOL>total_deposit=total_deposit,<EOL>transaction_executed=transaction_executed,<EOL>block_identifier=block,<EOL>)<EOL>error_msg = f'<STR_LIT>'<EOL>if error_type == RaidenRecoverableError:<EOL><INDENT>log.warning(error_msg, **log_details)<EOL><DEDENT>else:<EOL><INDENT>log.critical(error_msg, **log_details)<EOL><DEDENT>raise error_type(error_msg)<EOL><DEDENT>log.info('<STR_LIT>', **log_details)<EOL><DEDENT>
|
Set channel's total deposit.
`total_deposit` has to be monotonically increasing, this is enforced by
the `TokenNetwork` smart contract. This is done for the same reason why
the balance proofs have a monotonically increasing transferred amount,
it simplifies the analysis of bad behavior and the handling code of
out-dated balance proofs.
Races to `set_total_deposit` are handled by the smart contract, where
largest total deposit wins. The end balance of the funding accounts is
undefined. E.g.
- Acc1 calls set_total_deposit with 10 tokens
- Acc2 calls set_total_deposit with 13 tokens
- If Acc2's transaction is mined first, then Acc1 token supply is left intact.
- If Acc1's transaction is mined first, then Acc2 will only move 3 tokens.
Races for the same account don't have any unexpeted side-effect.
Raises:
DepositMismatch: If the new request total deposit is lower than the
existing total deposit on-chain for the `given_block_identifier`.
RaidenRecoverableError: If the channel was closed meanwhile the
deposit was in transit.
RaidenUnrecoverableError: If the transaction was sucessful and the
deposit_amount is not as large as the requested value.
RuntimeError: If the token address is empty.
ValueError: If an argument is of the invalid type.
|
f9348:c4:m20
|
def close(<EOL>self,<EOL>channel_identifier: ChannelID,<EOL>partner: Address,<EOL>balance_hash: BalanceHash,<EOL>nonce: Nonce,<EOL>additional_hash: AdditionalHash,<EOL>signature: Signature,<EOL>given_block_identifier: BlockSpecification,<EOL>):
|
log_details = {<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': pex(self.node_address),<EOL>'<STR_LIT>': pex(partner),<EOL>'<STR_LIT>': nonce,<EOL>'<STR_LIT>': encode_hex(balance_hash),<EOL>'<STR_LIT>': encode_hex(additional_hash),<EOL>'<STR_LIT>': encode_hex(signature),<EOL>}<EOL>log.debug('<STR_LIT>', **log_details)<EOL>checking_block = self.client.get_checking_block()<EOL>try:<EOL><INDENT>self._close_preconditions(<EOL>channel_identifier,<EOL>partner=partner,<EOL>block_identifier=given_block_identifier,<EOL>)<EOL><DEDENT>except NoStateForBlockIdentifier:<EOL><INDENT>pass<EOL><DEDENT>error_prefix = '<STR_LIT>'<EOL>with self.channel_operations_lock[partner]:<EOL><INDENT>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>channel_identifier=channel_identifier,<EOL>partner=partner,<EOL>balance_hash=balance_hash,<EOL>nonce=nonce,<EOL>additional_hash=additional_hash,<EOL>signature=signature,<EOL>)<EOL>if gas_limit:<EOL><INDENT>error_prefix = '<STR_LIT>'<EOL>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_CLOSE_CHANNEL),<EOL>channel_identifier=channel_identifier,<EOL>partner=partner,<EOL>balance_hash=balance_hash,<EOL>nonce=nonce,<EOL>additional_hash=additional_hash,<EOL>signature=signature,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt_or_none = check_transaction_threw(self.client, transaction_hash)<EOL><DEDENT>transaction_executed = gas_limit is not None<EOL>if not transaction_executed or receipt_or_none:<EOL><INDENT>if transaction_executed:<EOL><INDENT>block = receipt_or_none['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>block = checking_block<EOL><DEDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=transaction_executed,<EOL>required_gas=GAS_REQUIRED_FOR_CLOSE_CHANNEL,<EOL>block_identifier=block,<EOL>)<EOL>error_type, msg = self._check_channel_state_for_close(<EOL>participant1=self.node_address,<EOL>participant2=partner,<EOL>block_identifier=block,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL>if not error_type:<EOL><INDENT>error_type = RaidenUnrecoverableError<EOL><DEDENT>error_msg = f'<STR_LIT>'<EOL>if error_type == RaidenRecoverableError:<EOL><INDENT>log.warning(error_msg, **log_details)<EOL><DEDENT>else:<EOL><INDENT>log.critical(error_msg, **log_details)<EOL><DEDENT>raise error_type(error_msg)<EOL><DEDENT><DEDENT>log.info('<STR_LIT>', **log_details)<EOL>
|
Close the channel using the provided balance proof.
Note:
This method must *not* be called without updating the application
state, otherwise the node may accept new transfers which cannot be
used, because the closer is not allowed to update the balance proof
submitted on chain after closing
Raises:
RaidenRecoverableError: If the channel is already closed.
RaidenUnrecoverableError: If the channel does not exist or is settled.
|
f9348:c4:m23
|
def settle(<EOL>self,<EOL>channel_identifier: ChannelID,<EOL>transferred_amount: TokenAmount,<EOL>locked_amount: TokenAmount,<EOL>locksroot: Locksroot,<EOL>partner: Address,<EOL>partner_transferred_amount: TokenAmount,<EOL>partner_locked_amount: TokenAmount,<EOL>partner_locksroot: Locksroot,<EOL>given_block_identifier: BlockSpecification,<EOL>):
|
log_details = {<EOL>'<STR_LIT>': channel_identifier,<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': pex(self.node_address),<EOL>'<STR_LIT>': pex(partner),<EOL>'<STR_LIT>': transferred_amount,<EOL>'<STR_LIT>': locked_amount,<EOL>'<STR_LIT>': encode_hex(locksroot),<EOL>'<STR_LIT>': partner_transferred_amount,<EOL>'<STR_LIT>': partner_locked_amount,<EOL>'<STR_LIT>': encode_hex(partner_locksroot),<EOL>}<EOL>log.debug('<STR_LIT>', **log_details)<EOL>checking_block = self.client.get_checking_block()<EOL>our_maximum = transferred_amount + locked_amount<EOL>partner_maximum = partner_transferred_amount + partner_locked_amount<EOL>our_bp_is_larger = our_maximum > partner_maximum<EOL>if our_bp_is_larger:<EOL><INDENT>kwargs = {<EOL>'<STR_LIT>': partner,<EOL>'<STR_LIT>': partner_transferred_amount,<EOL>'<STR_LIT>': partner_locked_amount,<EOL>'<STR_LIT>': partner_locksroot,<EOL>'<STR_LIT>': self.node_address,<EOL>'<STR_LIT>': transferred_amount,<EOL>'<STR_LIT>': locked_amount,<EOL>'<STR_LIT>': locksroot,<EOL>}<EOL><DEDENT>else:<EOL><INDENT>kwargs = {<EOL>'<STR_LIT>': self.node_address,<EOL>'<STR_LIT>': transferred_amount,<EOL>'<STR_LIT>': locked_amount,<EOL>'<STR_LIT>': locksroot,<EOL>'<STR_LIT>': partner,<EOL>'<STR_LIT>': partner_transferred_amount,<EOL>'<STR_LIT>': partner_locked_amount,<EOL>'<STR_LIT>': partner_locksroot,<EOL>}<EOL><DEDENT>try:<EOL><INDENT>self._settle_preconditions(<EOL>channel_identifier=channel_identifier,<EOL>partner=partner,<EOL>block_identifier=given_block_identifier,<EOL>)<EOL><DEDENT>except NoStateForBlockIdentifier:<EOL><INDENT>pass<EOL><DEDENT>with self.channel_operations_lock[partner]:<EOL><INDENT>error_prefix = '<STR_LIT>'<EOL>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>channel_identifier=channel_identifier,<EOL>**kwargs,<EOL>)<EOL>if gas_limit:<EOL><INDENT>error_prefix = '<STR_LIT>'<EOL>gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SETTLE_CHANNEL)<EOL>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>gas_limit,<EOL>channel_identifier=channel_identifier,<EOL>**kwargs,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt_or_none = check_transaction_threw(self.client, transaction_hash)<EOL><DEDENT><DEDENT>transaction_executed = gas_limit is not None<EOL>if not transaction_executed or receipt_or_none:<EOL><INDENT>if transaction_executed:<EOL><INDENT>block = receipt_or_none['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>block = checking_block<EOL><DEDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=transaction_executed,<EOL>required_gas=GAS_REQUIRED_FOR_SETTLE_CHANNEL,<EOL>block_identifier=block,<EOL>)<EOL>msg = self._check_channel_state_after_settle(<EOL>participant1=self.node_address,<EOL>participant2=partner,<EOL>block_identifier=block,<EOL>channel_identifier=channel_identifier,<EOL>)<EOL>error_msg = f'<STR_LIT>'<EOL>log.critical(error_msg, **log_details)<EOL>raise RaidenUnrecoverableError(error_msg)<EOL><DEDENT>log.info('<STR_LIT>', **log_details)<EOL>
|
Settle the channel.
|
f9348:c4:m28
|
def events_filter(<EOL>self,<EOL>topics: List[str] = None,<EOL>from_block: BlockSpecification = None,<EOL>to_block: BlockSpecification = None,<EOL>) -> StatelessFilter:
|
return self.client.new_filter(<EOL>self.address,<EOL>topics=topics,<EOL>from_block=from_block,<EOL>to_block=to_block,<EOL>)<EOL>
|
Install a new filter for an array of topics emitted by the contract.
Args:
topics: A list of event ids to filter for. Can also be None,
in which case all events are queried.
from_block: The block number at which to start looking for events.
to_block: The block number at which to stop looking for events.
Return:
Filter: The filter instance.
|
f9348:c4:m29
|
def _check_for_outdated_channel(<EOL>self,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>channel_identifier: ChannelID,<EOL>) -> None:
|
try:<EOL><INDENT>onchain_channel_details = self._detail_channel(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>block_identifier=block_identifier,<EOL>)<EOL><DEDENT>except RaidenRecoverableError:<EOL><INDENT>return<EOL><DEDENT>onchain_channel_identifier = onchain_channel_details.channel_identifier<EOL>if onchain_channel_identifier != channel_identifier:<EOL><INDENT>raise ChannelOutdatedError(<EOL>'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT>
|
Checks whether an operation is being executed on a channel
between two participants using an old channel identifier
|
f9348:c4:m31
|
def _check_channel_state_for_update(<EOL>self,<EOL>channel_identifier: ChannelID,<EOL>closer: Address,<EOL>update_nonce: Nonce,<EOL>block_identifier: BlockSpecification,<EOL>) -> Optional[str]:
|
msg = None<EOL>closer_details = self._detail_participant(<EOL>channel_identifier=channel_identifier,<EOL>participant=closer,<EOL>partner=self.node_address,<EOL>block_identifier=block_identifier,<EOL>)<EOL>if closer_details.nonce == update_nonce:<EOL><INDENT>msg = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>return msg<EOL>
|
Check the channel state on chain to see if it has been updated.
Compare the nonce, we are about to update the contract with, with the
updated nonce in the onchain state and, if it's the same, return a
message with which the caller should raise a RaidenRecoverableError.
If all is okay return None.
|
f9348:c4:m36
|
def approve(<EOL>self,<EOL>allowed_address: Address,<EOL>allowance: TokenAmount,<EOL>):
|
<EOL>log_details = {<EOL>'<STR_LIT>': pex(self.node_address),<EOL>'<STR_LIT>': pex(self.address),<EOL>'<STR_LIT>': pex(allowed_address),<EOL>'<STR_LIT>': allowance,<EOL>}<EOL>checking_block = self.client.get_checking_block()<EOL>error_prefix = '<STR_LIT>'<EOL>gas_limit = self.proxy.estimate_gas(<EOL>checking_block,<EOL>'<STR_LIT>',<EOL>to_checksum_address(allowed_address),<EOL>allowance,<EOL>)<EOL>if gas_limit:<EOL><INDENT>error_prefix = '<STR_LIT>'<EOL>log.debug('<STR_LIT>', **log_details)<EOL>transaction_hash = self.proxy.transact(<EOL>'<STR_LIT>',<EOL>safe_gas_limit(gas_limit),<EOL>to_checksum_address(allowed_address),<EOL>allowance,<EOL>)<EOL>self.client.poll(transaction_hash)<EOL>receipt_or_none = check_transaction_threw(self.client, transaction_hash)<EOL><DEDENT>transaction_executed = gas_limit is not None<EOL>if not transaction_executed or receipt_or_none:<EOL><INDENT>if transaction_executed:<EOL><INDENT>block = receipt_or_none['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>block = checking_block<EOL><DEDENT>self.proxy.jsonrpc_client.check_for_insufficient_eth(<EOL>transaction_name='<STR_LIT>',<EOL>transaction_executed=transaction_executed,<EOL>required_gas=GAS_REQUIRED_FOR_APPROVE,<EOL>block_identifier=block,<EOL>)<EOL>msg = self._check_why_approved_failed(allowance, block)<EOL>error_msg = f'<STR_LIT>'<EOL>log.critical(error_msg, **log_details)<EOL>raise RaidenUnrecoverableError(error_msg)<EOL><DEDENT>log.info('<STR_LIT>', **log_details)<EOL>
|
Aprove `allowed_address` to transfer up to `deposit` amount of token.
Note:
For channel deposit please use the channel proxy, since it does
additional validations.
|
f9349:c0:m2
|
def compare_contract_versions(<EOL>proxy: ContractProxy,<EOL>expected_version: str,<EOL>contract_name: str,<EOL>address: Address,<EOL>) -> None:
|
assert isinstance(expected_version, str)<EOL>try:<EOL><INDENT>deployed_version = proxy.contract.functions.contract_version().call()<EOL><DEDENT>except BadFunctionCallOutput:<EOL><INDENT>raise AddressWrongContract('<STR_LIT>')<EOL><DEDENT>deployed_version = deployed_version.replace('<STR_LIT:_>', '<STR_LIT:0>')<EOL>expected_version = expected_version.replace('<STR_LIT:_>', '<STR_LIT:0>')<EOL>deployed = [int(x) for x in deployed_version.split('<STR_LIT:.>')]<EOL>expected = [int(x) for x in expected_version.split('<STR_LIT:.>')]<EOL>if deployed != expected:<EOL><INDENT>raise ContractVersionMismatch(<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>',<EOL>)<EOL><DEDENT>
|
Compare version strings of a contract.
If not matching raise ContractVersionMismatch. Also may raise AddressWrongContract
if the contract contains no code.
|
f9350:m0
|
def get_onchain_locksroots(<EOL>chain: '<STR_LIT>',<EOL>canonical_identifier: CanonicalIdentifier,<EOL>participant1: Address,<EOL>participant2: Address,<EOL>block_identifier: BlockSpecification,<EOL>) -> Tuple[Locksroot, Locksroot]:
|
payment_channel = chain.payment_channel(canonical_identifier=canonical_identifier)<EOL>token_network = payment_channel.token_network<EOL>participants_details = token_network.detail_participants(<EOL>participant1=participant1,<EOL>participant2=participant2,<EOL>channel_identifier=canonical_identifier.channel_identifier,<EOL>block_identifier=block_identifier,<EOL>)<EOL>our_details = participants_details.our_details<EOL>our_locksroot = our_details.locksroot<EOL>partner_details = participants_details.partner_details<EOL>partner_locksroot = partner_details.locksroot<EOL>return our_locksroot, partner_locksroot<EOL>
|
Return the locksroot for `participant1` and `participant2` at `block_identifier`.
|
f9350:m1
|
def token_address(self) -> Address:
|
return self.token_network.token_address()<EOL>
|
Returns the address of the token for the channel.
|
f9351:c0:m1
|
def detail(self, block_identifier: BlockSpecification) -> ChannelDetails:
|
return self.token_network.detail(<EOL>participant1=self.participant1,<EOL>participant2=self.participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=self.channel_identifier,<EOL>)<EOL>
|
Returns the channel details.
|
f9351:c0:m2
|
def settle_timeout(self) -> int:
|
<EOL>filter_args = get_filter_args_for_specific_event_from_channel(<EOL>token_network_address=self.token_network.address,<EOL>channel_identifier=self.channel_identifier,<EOL>event_name=ChannelEvent.OPENED,<EOL>contract_manager=self.contract_manager,<EOL>)<EOL>events = self.token_network.proxy.contract.web3.eth.getLogs(filter_args)<EOL>assert len(events) > <NUM_LIT:0>, '<STR_LIT>'<EOL>event = decode_event(<EOL>self.contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),<EOL>events[-<NUM_LIT:1>],<EOL>)<EOL>return event['<STR_LIT:args>']['<STR_LIT>']<EOL>
|
Returns the channels settle_timeout.
|
f9351:c0:m3
|
def close_block_number(self) -> Optional[int]:
|
<EOL>filter_args = get_filter_args_for_specific_event_from_channel(<EOL>token_network_address=self.token_network.address,<EOL>channel_identifier=self.channel_identifier,<EOL>event_name=ChannelEvent.CLOSED,<EOL>contract_manager=self.contract_manager,<EOL>)<EOL>events = self.token_network.proxy.contract.web3.eth.getLogs(filter_args)<EOL>if not events:<EOL><INDENT>return None<EOL><DEDENT>assert len(events) == <NUM_LIT:1><EOL>event = decode_event(<EOL>self.contract_manager.get_contract_abi(CONTRACT_TOKEN_NETWORK),<EOL>events[<NUM_LIT:0>],<EOL>)<EOL>return event['<STR_LIT>']<EOL>
|
Returns the channel's closed block number.
|
f9351:c0:m4
|
def opened(self, block_identifier: BlockSpecification) -> bool:
|
return self.token_network.channel_is_opened(<EOL>participant1=self.participant1,<EOL>participant2=self.participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=self.channel_identifier,<EOL>)<EOL>
|
Returns if the channel is opened.
|
f9351:c0:m5
|
def closed(self, block_identifier: BlockSpecification) -> bool:
|
return self.token_network.channel_is_closed(<EOL>participant1=self.participant1,<EOL>participant2=self.participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=self.channel_identifier,<EOL>)<EOL>
|
Returns if the channel is closed.
|
f9351:c0:m6
|
def settled(self, block_identifier: BlockSpecification) -> bool:
|
return self.token_network.channel_is_settled(<EOL>participant1=self.participant1,<EOL>participant2=self.participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=self.channel_identifier,<EOL>)<EOL>
|
Returns if the channel is settled.
|
f9351:c0:m7
|
def closing_address(self, block_identifier: BlockSpecification) -> Optional[Address]:
|
return self.token_network.closing_address(<EOL>participant1=self.participant1,<EOL>participant2=self.participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=self.channel_identifier,<EOL>)<EOL>
|
Returns the address of the closer of the channel.
|
f9351:c0:m8
|
def can_transfer(self, block_identifier: BlockSpecification) -> bool:
|
return self.token_network.can_transfer(<EOL>participant1=self.participant1,<EOL>participant2=self.participant2,<EOL>block_identifier=block_identifier,<EOL>channel_identifier=self.channel_identifier,<EOL>)<EOL>
|
Returns True if the channel is opened and the node has deposit in it.
|
f9351:c0:m9
|
def close(<EOL>self,<EOL>nonce: Nonce,<EOL>balance_hash: BalanceHash,<EOL>additional_hash: AdditionalHash,<EOL>signature: Signature,<EOL>block_identifier: BlockSpecification,<EOL>):
|
self.token_network.close(<EOL>channel_identifier=self.channel_identifier,<EOL>partner=self.participant2,<EOL>balance_hash=balance_hash,<EOL>nonce=nonce,<EOL>additional_hash=additional_hash,<EOL>signature=signature,<EOL>given_block_identifier=block_identifier,<EOL>)<EOL>
|
Closes the channel using the provided balance proof.
|
f9351:c0:m11
|
def update_transfer(<EOL>self,<EOL>nonce: Nonce,<EOL>balance_hash: BalanceHash,<EOL>additional_hash: AdditionalHash,<EOL>partner_signature: Signature,<EOL>signature: Signature,<EOL>block_identifier: BlockSpecification,<EOL>):
|
self.token_network.update_transfer(<EOL>channel_identifier=self.channel_identifier,<EOL>partner=self.participant2,<EOL>balance_hash=balance_hash,<EOL>nonce=nonce,<EOL>additional_hash=additional_hash,<EOL>closing_signature=partner_signature,<EOL>non_closing_signature=signature,<EOL>given_block_identifier=block_identifier,<EOL>)<EOL>
|
Updates the channel using the provided balance proof.
|
f9351:c0:m12
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.