signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def settle(<EOL>self,<EOL>transferred_amount: TokenAmount,<EOL>locked_amount: TokenAmount,<EOL>locksroot: Locksroot,<EOL>partner_transferred_amount: TokenAmount,<EOL>partner_locked_amount: TokenAmount,<EOL>partner_locksroot: Locksroot,<EOL>block_identifier: BlockSpecification,<EOL>): | self.token_network.settle(<EOL>channel_identifier=self.channel_identifier,<EOL>transferred_amount=transferred_amount,<EOL>locked_amount=locked_amount,<EOL>locksroot=locksroot,<EOL>partner=self.participant2,<EOL>partner_transferred_amount=partner_transferred_amount,<EOL>partner_locked_amount=partner_locked_amount,<EOL>p... | Settles the channel. | f9351:c0:m14 |
def consume(self, tokens): | wait_time = <NUM_LIT:0.><EOL>self.tokens -= tokens<EOL>if self.tokens < <NUM_LIT:0>:<EOL><INDENT>self._get_tokens()<EOL><DEDENT>if self.tokens < <NUM_LIT:0>:<EOL><INDENT>wait_time = -self.tokens / self.fill_rate<EOL><DEDENT>return wait_time<EOL> | Consume tokens.
Args:
tokens (float): number of transport tokens to consume
Returns:
wait_time (float): waiting time for the consumer | f9352:c1:m1 |
def estimate_blocktime(self, oldest: int = <NUM_LIT>) -> float: | last_block_number = self.block_number()<EOL>if last_block_number < <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:15><EOL><DEDENT>if last_block_number < oldest:<EOL><INDENT>interval = (last_block_number - <NUM_LIT:1>) or <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>interval = last_block_number - oldest<EOL><DEDENT>assert interv... | Calculate a blocktime estimate based on some past blocks.
Args:
oldest: delta in block numbers to go back.
Return:
average block time in seconds | f9353:c0:m6 |
def token(self, token_address: Address) -> Token: | if not is_binary_address(token_address):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>with self._token_creation_lock:<EOL><INDENT>if token_address not in self.address_to_token:<EOL><INDENT>self.address_to_token[token_address] = Token(<EOL>jsonrpc_client=self.client,<EOL>token_address=token_address,<EOL>contrac... | Return a proxy to interact with a token. | f9353:c0:m10 |
def discovery(self, discovery_address: Address) -> Discovery: | if not is_binary_address(discovery_address):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>with self._discovery_creation_lock:<EOL><INDENT>if discovery_address not in self.address_to_discovery:<EOL><INDENT>self.address_to_discovery[discovery_address] = Discovery(<EOL>jsonrpc_client=self.client,<EOL>discovery_ad... | Return a proxy to interact with the discovery. | f9353:c0:m11 |
def get_free_port(<EOL>initial_port: int = <NUM_LIT:0>,<EOL>socket_kind: SocketKind = SocketKind.SOCK_STREAM,<EOL>reliable: bool = True,<EOL>): | def _port_generator():<EOL><INDENT>if initial_port == <NUM_LIT:0>:<EOL><INDENT>next_port = repeat(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>next_port = count(start=initial_port)<EOL><DEDENT>for port_candidate in next_port:<EOL><INDENT>sock = socket.socket(socket.AF_INET, socket_kind)<EOL>with closing(sock):<EOL><INDEN... | Find an unused TCP port.
Unless the `reliable` parameter is set to `True` (the default) this is prone to race
conditions - some other process may grab the port before the caller of this function has
a chance to use it.
When using `reliable` the port is forced into TIME_WAIT mode, ensuring that it will not be
considere... | f9354:m0 |
def get_http_rtt(<EOL>url: str,<EOL>samples: int = <NUM_LIT:3>,<EOL>method: str = '<STR_LIT>',<EOL>timeout: int = <NUM_LIT:1>,<EOL>) -> Optional[float]: | durations = []<EOL>for _ in range(samples):<EOL><INDENT>try:<EOL><INDENT>durations.append(<EOL>requests.request(method, url, timeout=timeout).elapsed.total_seconds(),<EOL>)<EOL><DEDENT>except (RequestException, OSError):<EOL><INDENT>return None<EOL><DEDENT>except Exception as ex:<EOL><INDENT>print(ex)<EOL>return None<E... | Determine the average HTTP RTT to `url` over the number of `samples`.
Returns `None` if the server is unreachable. | f9354:m1 |
def connect(): | upnp = miniupnpc.UPnP()<EOL>upnp.discoverdelay = <NUM_LIT:200><EOL>providers = upnp.discover()<EOL>if providers > <NUM_LIT:1>:<EOL><INDENT>log.debug('<STR_LIT>', num_providers=providers)<EOL><DEDENT>elif providers < <NUM_LIT:1>:<EOL><INDENT>log.error('<STR_LIT>')<EOL>return None<EOL><DEDENT>try:<EOL><INDENT>location = ... | Try to connect to the router.
Returns:
u (miniupnc.UPnP): the connected upnp-instance
router (string): the connection information | f9355:m1 |
def open_port(upnp, internal_port, external_start_port=None): | if external_start_port is None:<EOL><INDENT>external_start_port = internal_port<EOL><DEDENT>if upnp is None:<EOL><INDENT>return False<EOL><DEDENT>def register(internal, external):<EOL><INDENT>mapping = upnp.getspecificportmapping(external, '<STR_LIT>')<EOL>if mapping is not None:<EOL><INDENT>lanaddr, internal_mapped, n... | Open a port for the raiden service (listening at `internal_port`) through
UPnP.
Args:
internal_port (int): the target port of the raiden service
external_start_port (int): query for an external port starting here
(default: internal_port)
Returns:
external_ip_address, ext... | f9355:m2 |
def release_port(upnp, external_port): | mapping = upnp.getspecificportmapping(external_port, '<STR_LIT>')<EOL>if mapping is None:<EOL><INDENT>log.error('<STR_LIT>', external=external_port)<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>log.debug('<STR_LIT>', mapping=mapping)<EOL><DEDENT>if upnp.deleteportmapping(external_port, '<STR_LIT>'):<EOL><INDENT>log.i... | Try to release the port mapping for `external_port`.
Args:
external_port (int): the port that was previously forwarded to.
Returns:
success (boolean): if the release was successful. | f9355:m3 |
def event_first_of(*events: _AbstractLinkable) -> Event: | first_finished = Event()<EOL>if not all(isinstance(e, _AbstractLinkable) for e in events):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for event in events:<EOL><INDENT>event.rawlink(lambda _: first_finished.set())<EOL><DEDENT>return first_finished<EOL> | Waits until one of `events` is set.
The event returned is /not/ cleared with any of the `events`, this value
must not be reused if the clearing behavior is used. | f9356:m0 |
def timeout_exponential_backoff(<EOL>retries: int,<EOL>timeout: int,<EOL>maximum: int,<EOL>) -> Iterator[int]: | yield timeout<EOL>tries = <NUM_LIT:1><EOL>while tries < retries:<EOL><INDENT>tries += <NUM_LIT:1><EOL>yield timeout<EOL><DEDENT>while timeout < maximum:<EOL><INDENT>timeout = min(timeout * <NUM_LIT:2>, maximum)<EOL>yield timeout<EOL><DEDENT>while True:<EOL><INDENT>yield maximum<EOL><DEDENT> | Timeouts generator with an exponential backoff strategy.
Timeouts start spaced by `timeout`, after `retries` exponentially increase
the retry delays until `maximum`, then maximum is returned indefinitely. | f9356:m1 |
def timeout_two_stage(<EOL>retries: int,<EOL>timeout1: int,<EOL>timeout2: int,<EOL>) -> Iterable[int]: | for _ in range(retries):<EOL><INDENT>yield timeout1<EOL><DEDENT>while True:<EOL><INDENT>yield timeout2<EOL><DEDENT> | Timeouts generator with a two stage strategy
Timeouts start spaced by `timeout1`, after `retries` increase
to `timeout2` which is repeated indefinitely. | f9356:m2 |
def retry(<EOL>transport: '<STR_LIT>',<EOL>messagedata: bytes,<EOL>message_id: UDPMessageID,<EOL>recipient: Address,<EOL>stop_event: Event,<EOL>timeout_backoff: Iterable[int],<EOL>) -> bool: | async_result = transport.maybe_sendraw_with_result(<EOL>recipient,<EOL>messagedata,<EOL>message_id,<EOL>)<EOL>event_quit = event_first_of(<EOL>async_result,<EOL>stop_event,<EOL>)<EOL>for timeout in timeout_backoff:<EOL><INDENT>if event_quit.wait(timeout=timeout) is True:<EOL><INDENT>break<EOL><DEDENT>log.debug(<EOL>'<S... | Send messagedata until it's acknowledged.
Exit when:
- The message is delivered.
- Event_stop is set.
- The iterator timeout_backoff runs out.
Returns:
bool: True if the message was acknowledged, False otherwise. | f9356:m3 |
def retry_with_recovery(<EOL>transport: '<STR_LIT>',<EOL>messagedata: bytes,<EOL>message_id: UDPMessageID,<EOL>recipient: Address,<EOL>stop_event: Event,<EOL>event_healthy: Event,<EOL>event_unhealthy: Event,<EOL>backoff: Iterable[int],<EOL>) -> bool: | <EOL>stop_or_unhealthy = event_first_of(<EOL>stop_event,<EOL>event_unhealthy,<EOL>)<EOL>acknowledged = False<EOL>while not stop_event.is_set() and not acknowledged:<EOL><INDENT>if event_unhealthy.is_set():<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(transport.raiden.address),<EOL>recipient=pex(recipient),<EOL>... | Send messagedata while the node is healthy until it's acknowledged.
Note:
backoff must be an infinite iterator, otherwise this task will
become a hot loop. | f9356:m5 |
def single_queue_send(<EOL>transport: '<STR_LIT>',<EOL>recipient: Address,<EOL>queue: Queue_T,<EOL>queue_identifier: QueueIdentifier,<EOL>event_stop: Event,<EOL>event_healthy: Event,<EOL>event_unhealthy: Event,<EOL>message_retries: int,<EOL>message_retry_timeout: int,<EOL>message_retry_max_timeout: int,<EOL>): | <EOL>if not isinstance(queue, NotifyingQueue):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>data_or_stop = event_first_of(<EOL>queue,<EOL>event_stop,<EOL>)<EOL>transport.log.debug(<EOL>'<STR_LIT>',<EOL>queue_identifier=queue_identifier,<EOL>queue_size=len(queue),<EOL>)<EOL>event_first_of(<EOL>event_healthy,<EO... | Handles a single message queue for `recipient`.
Notes:
- This task must be the only consumer of queue.
- This task can be killed at any time, but the intended usage is to stop it
with the event_stop.
- If there are many queues for the same recipient, it is the
caller's responsibility to not... | f9357:m0 |
def _run(self): | try:<EOL><INDENT>self.event_stop.wait()<EOL><DEDENT>except gevent.GreenletExit: <EOL><INDENT>self.event_stop.set()<EOL>gevent.killall(self.greenlets) <EOL>raise <EOL><DEDENT>except Exception:<EOL><INDENT>self.stop() <EOL>raise<EOL><DEDENT> | Runnable main method, perform wait on long-running subtasks | f9357:c0:m2 |
def get_health_events(self, recipient): | if recipient not in self.addresses_events:<EOL><INDENT>self.start_health_check(recipient)<EOL><DEDENT>return self.addresses_events[recipient]<EOL> | Starts a healthcheck task for `recipient` and returns a
HealthEvents with locks to react on its current state. | f9357:c0:m4 |
def whitelist(self, address: Address): | return<EOL> | Whitelist peer address to receive communications from
This may be called before transport is started, to ensure events generated during
start are handled properly.
PS: udp currently doesn't do whitelisting, method defined for compatibility with matrix | f9357:c0:m5 |
def start_health_check(self, recipient): | if recipient not in self.addresses_events:<EOL><INDENT>self.whitelist(recipient) <EOL>ping_nonce = self.nodeaddresses_to_nonces.setdefault(<EOL>recipient,<EOL>{'<STR_LIT>': <NUM_LIT:0>}, <EOL>)<EOL>events = healthcheck.HealthEvents(<EOL>event_healthy=Event(),<EOL>event_unhealthy=Event(),<EOL>)<EOL>self.addresses_even... | Starts a task for healthchecking `recipient` if there is not
one yet.
It also whitelists the address | f9357:c0:m6 |
def init_queue_for(<EOL>self,<EOL>queue_identifier: QueueIdentifier,<EOL>items: List[QueueItem_T],<EOL>) -> NotifyingQueue: | recipient = queue_identifier.recipient<EOL>queue = self.queueids_to_queues.get(queue_identifier)<EOL>assert queue is None<EOL>queue = NotifyingQueue(items=items)<EOL>self.queueids_to_queues[queue_identifier] = queue<EOL>events = self.get_health_events(recipient)<EOL>greenlet_queue = gevent.spawn(<EOL>single_queue_send,... | Create the queue identified by the queue_identifier
and initialize it with `items`. | f9357:c0:m7 |
def get_queue_for(<EOL>self,<EOL>queue_identifier: QueueIdentifier,<EOL>) -> NotifyingQueue: | queue = self.queueids_to_queues.get(queue_identifier)<EOL>if queue is None:<EOL><INDENT>items: List[QueueItem_T] = list()<EOL>queue = self.init_queue_for(queue_identifier, items)<EOL><DEDENT>return queue<EOL> | Return the queue identified by the given queue identifier.
If the queue doesn't exist it will be instantiated. | f9357:c0:m8 |
def send_async(<EOL>self,<EOL>queue_identifier: QueueIdentifier,<EOL>message: Message,<EOL>): | recipient = queue_identifier.recipient<EOL>if not is_binary_address(recipient):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(pex(recipient)))<EOL><DEDENT>if isinstance(message, (Delivered, Ping, Pong)):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(message.__class__.__name__))<EOL><DEDENT>messagedata = message.enc... | Send a new ordered message to recipient.
Messages that use the same `queue_identifier` are ordered. | f9357:c0:m9 |
def send_global( <EOL>self,<EOL>room: str,<EOL>message: Message,<EOL>) -> None: | self.log.warning('<STR_LIT>')<EOL> | This method exists only for interface compatibility with MatrixTransport | f9357:c0:m10 |
def maybe_send(self, recipient: Address, message: Message): | if not is_binary_address(recipient):<EOL><INDENT>raise InvalidAddress('<STR_LIT>'.format(pex(recipient)))<EOL><DEDENT>messagedata = message.encode()<EOL>host_port = self.get_host_port(recipient)<EOL>self.maybe_sendraw(host_port, messagedata)<EOL> | Send message to recipient if the transport is running. | f9357:c0:m11 |
def maybe_sendraw_with_result(<EOL>self,<EOL>recipient: Address,<EOL>messagedata: bytes,<EOL>message_id: UDPMessageID,<EOL>) -> AsyncResult: | async_result = self.messageids_to_asyncresults.get(message_id)<EOL>if async_result is None:<EOL><INDENT>async_result = AsyncResult()<EOL>self.messageids_to_asyncresults[message_id] = async_result<EOL><DEDENT>host_port = self.get_host_port(recipient)<EOL>self.maybe_sendraw(host_port, messagedata)<EOL>return async_result... | Send message to recipient if the transport is running.
Returns:
An AsyncResult that will be set once the message is delivered. As
long as the message has not been acknowledged with a Delivered
message the function will return the same AsyncResult. | f9357:c0:m12 |
def maybe_sendraw(self, host_port: Tuple[int, int], messagedata: bytes): | <EOL>sleep_timeout = self.throttle_policy.consume(<NUM_LIT:1>)<EOL>if sleep_timeout:<EOL><INDENT>gevent.sleep(sleep_timeout)<EOL><DEDENT>if hasattr(self.server, '<STR_LIT>'):<EOL><INDENT>self.server.sendto(<EOL>messagedata,<EOL>host_port,<EOL>)<EOL><DEDENT> | Send message to recipient if the transport is running. | f9357:c0:m13 |
def receive(<EOL>self,<EOL>messagedata: bytes,<EOL>host_port: Tuple[str, int], <EOL>) -> bool: | <EOL>if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE:<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>message=encode_hex(messagedata),<EOL>length=len(messagedata),<EOL>)<EOL>return False<EOL><DEDENT>try:<EOL><INDENT>message = decode(messagedata)<EOL><DEDENT>except InvalidProtocolMessage as e:<EOL><INDENT>self.log.wa... | Handle an UDP packet. | f9357:c0:m14 |
def receive_message(self, message: Message): | self.raiden.on_message(message)<EOL>delivered_message = Delivered(delivered_message_identifier=message.message_identifier)<EOL>self.raiden.sign(delivered_message)<EOL>self.maybe_send(<EOL>message.sender,<EOL>delivered_message,<EOL>)<EOL> | Handle a Raiden protocol message.
The protocol requires durability of the messages. The UDP transport
relies on the node's WAL for durability. The message will be converted
to a state change, saved to the WAL, and *processed* before the
durability is confirmed, which is a stronger prope... | f9357:c0:m15 |
def receive_delivered(self, delivered: Delivered): | self.raiden.on_message(delivered)<EOL>message_id = delivered.delivered_message_identifier<EOL>async_result = self.raiden.transport.messageids_to_asyncresults.get(message_id)<EOL>if async_result is not None:<EOL><INDENT>del self.messageids_to_asyncresults[message_id]<EOL>async_result.set()<EOL><DEDENT>else:<EOL><INDENT>... | Handle a Delivered message.
The Delivered message is how the UDP transport guarantees persistence
by the partner node. The message itself is not part of the raiden
protocol, but it's required by this transport to provide the required
properties. | f9357:c0:m16 |
def receive_ping(self, ping: Ping): | self.log_healthcheck.debug(<EOL>'<STR_LIT>',<EOL>message_id=ping.nonce,<EOL>message=ping,<EOL>sender=pex(ping.sender),<EOL>)<EOL>pong = Pong(nonce=ping.nonce)<EOL>self.raiden.sign(pong)<EOL>try:<EOL><INDENT>self.maybe_send(ping.sender, pong)<EOL><DEDENT>except (InvalidAddress, UnknownAddress) as e:<EOL><INDENT>self.log... | Handle a Ping message by answering with a Pong. | f9357:c0:m17 |
def receive_pong(self, pong: Pong): | message_id = ('<STR_LIT>', pong.nonce, pong.sender)<EOL>async_result = self.messageids_to_asyncresults.get(message_id)<EOL>if async_result is not None:<EOL><INDENT>self.log_healthcheck.debug(<EOL>'<STR_LIT>',<EOL>sender=pex(pong.sender),<EOL>message_id=pong.nonce,<EOL>)<EOL>async_result.set(True)<EOL><DEDENT>else:<EOL>... | Handles a Pong message. | f9357:c0:m18 |
def get_ping(self, nonce: Nonce) -> bytes: | message = Ping(<EOL>nonce=nonce,<EOL>current_protocol_version=constants.PROTOCOL_VERSION,<EOL>)<EOL>self.raiden.sign(message)<EOL>return message.encode()<EOL> | Returns a signed Ping message.
Note: Ping messages don't have an enforced ordering, so a Ping message
with a higher nonce may be acknowledged first. | f9357:c0:m19 |
def healthcheck(<EOL>transport: '<STR_LIT>',<EOL>recipient: Address,<EOL>stop_event: Event,<EOL>event_healthy: Event,<EOL>event_unhealthy: Event,<EOL>nat_keepalive_retries: int,<EOL>nat_keepalive_timeout: int,<EOL>nat_invitation_timeout: int,<EOL>ping_nonce: Dict[str, Nonce],<EOL>): | <EOL>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(transport.address),<EOL>to=pex(recipient),<EOL>)<EOL>last_state = NODE_NETWORK_UNKNOWN<EOL>transport.set_node_network_state(<EOL>recipient,<EOL>last_state,<EOL>)<EOL>try:<EOL><INDENT>transport.get_host_port(recipient)<EOL><DEDENT>except UnknownAddress:<EOL><INDENT>log.debug... | Sends a periodical Ping to `recipient` to check its health. | f9358:m0 |
def get_joined_members(self, force_resync=False) -> List[User]: | if force_resync:<EOL><INDENT>response = self.client.api.get_room_members(self.room_id)<EOL>for event in response['<STR_LIT>']:<EOL><INDENT>if event['<STR_LIT:content>']['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>user_id = event["<STR_LIT>"]<EOL>if user_id not in self._members:<EOL><INDENT>self._mkmembers(<EOL>User(<EOL>s... | Return a list of members of this room. | f9361:c0:m1 |
def update_aliases(self): | changed = False<EOL>try:<EOL><INDENT>response = self.client.api.get_room_state(self.room_id)<EOL><DEDENT>except MatrixRequestError:<EOL><INDENT>return False<EOL><DEDENT>for chunk in response:<EOL><INDENT>content = chunk.get('<STR_LIT:content>')<EOL>if content:<EOL><INDENT>if '<STR_LIT>' in content:<EOL><INDENT>aliases ... | Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not | f9361:c0:m5 |
def listen_forever(<EOL>self,<EOL>timeout_ms: int = <NUM_LIT>,<EOL>exception_handler: Callable[[Exception], None] = None,<EOL>bad_sync_timeout: int = <NUM_LIT:5>,<EOL>): | _bad_sync_timeout = bad_sync_timeout<EOL>self.should_listen = True<EOL>while self.should_listen:<EOL><INDENT>try:<EOL><INDENT>self._sync(timeout_ms)<EOL>_bad_sync_timeout = bad_sync_timeout<EOL><DEDENT>except MatrixRequestError as e:<EOL><INDENT>log.warning('<STR_LIT>')<EOL>if e.code >= <NUM_LIT>:<EOL><INDENT>log.warni... | Keep listening for events forever.
Args:
timeout_ms: How long to poll the Home Server for before retrying.
exception_handler: Optional exception handler function which can
be used to handle exceptions in the caller thread.
bad_sync_timeout: Base time to wait after an error before retrying.
W... | f9361:c2:m1 |
def start_listener_thread(self, timeout_ms: int = <NUM_LIT>, exception_handler: Callable = None): | assert not self.should_listen and self.sync_thread is None, '<STR_LIT>'<EOL>self.should_listen = True<EOL>self.sync_thread = gevent.spawn(self.listen_forever, timeout_ms, exception_handler)<EOL>self.sync_thread.name = f'<STR_LIT>'<EOL> | Start a listener greenlet to listen for events in the background.
Args:
timeout_ms: How long to poll the Home Server for before retrying.
exception_handler: Optional exception handler function which can
be used to handle exceptions in the caller thread. | f9361:c2:m2 |
def stop_listener_thread(self): | <EOL>self.should_listen = False<EOL>if self.sync_thread:<EOL><INDENT>self.sync_thread.kill()<EOL>self.sync_thread.get()<EOL><DEDENT>if self._handle_thread is not None:<EOL><INDENT>self._handle_thread.get()<EOL><DEDENT>self.sync_thread = None<EOL>self._handle_thread = None<EOL> | Kills sync_thread greenlet before joining it | f9361:c2:m3 |
def search_user_directory(self, term: str) -> List[User]: | response = self.api._send(<EOL>'<STR_LIT:POST>',<EOL>'<STR_LIT>',<EOL>{<EOL>'<STR_LIT>': term,<EOL>},<EOL>)<EOL>try:<EOL><INDENT>return [<EOL>User(self.api, _user['<STR_LIT>'], _user['<STR_LIT>'])<EOL>for _user in response['<STR_LIT>']<EOL>]<EOL><DEDENT>except KeyError:<EOL><INDENT>return []<EOL><DEDENT> | Search user directory for a given term, returning a list of users
Args:
term: term to be searched for
Returns:
user_list: list of users returned by server-side search | f9361:c2:m5 |
def typing(self, room: Room, timeout: int = <NUM_LIT>): | path = f'<STR_LIT>'<EOL>return self.api._send('<STR_LIT>', path, {'<STR_LIT>': True, '<STR_LIT>': timeout})<EOL> | Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms | f9361:c2:m10 |
def _mkroom(self, room_id: str) -> Room: | if room_id not in self.rooms:<EOL><INDENT>self.rooms[room_id] = Room(self, room_id)<EOL><DEDENT>room = self.rooms[room_id]<EOL>if not room.canonical_alias:<EOL><INDENT>room.update_aliases()<EOL><DEDENT>return room<EOL> | Uses a geventified Room subclass | f9361:c2:m11 |
def _sync(self, timeout_ms=<NUM_LIT>): | response = self.api.sync(self.sync_token, timeout_ms)<EOL>prev_sync_token = self.sync_token<EOL>self.sync_token = response["<STR_LIT>"]<EOL>if self._handle_thread is not None:<EOL><INDENT>self._handle_thread.get()<EOL><DEDENT>is_first_sync = (prev_sync_token is None)<EOL>self._handle_thread = gevent.Greenlet(self._hand... | Reimplements MatrixClient._sync, add 'account_data' support to /sync | f9361:c2:m14 |
def set_account_data(self, type_: str, content: Dict[str, Any]) -> dict: | self.account_data[type_] = content<EOL>return self.api.set_account_data(quote(self.user_id), quote(type_), content)<EOL> | Use this to set a key: value pair in account_data to keep it synced on server | f9361:c2:m16 |
def set_sync_limit(self, limit: int) -> Optional[int]: | try:<EOL><INDENT>prev_limit = json.loads(self.sync_filter)['<STR_LIT>']['<STR_LIT>']['<STR_LIT>']<EOL><DEDENT>except (json.JSONDecodeError, KeyError):<EOL><INDENT>prev_limit = None<EOL><DEDENT>self.sync_filter = json.dumps({'<STR_LIT>': {'<STR_LIT>': {'<STR_LIT>': limit}}})<EOL>return prev_limit<EOL> | Sets the events limit per room for sync and return previous limit | f9361:c2:m20 |
@staticmethod<EOL><INDENT>def _expiration_generator(<EOL>timeout_generator: Iterable[float],<EOL>now: Callable[[], float] = time.time,<EOL>) -> Iterator[bool]:<DEDENT> | for timeout in timeout_generator:<EOL><INDENT>_next = now() + timeout <EOL>yield True<EOL>while now() < _next: <EOL><INDENT>yield False<EOL><DEDENT><DEDENT> | Stateful generator that yields True if more than timeout has passed since previous True,
False otherwise.
Helper method to tell when a message needs to be retried (more than timeout seconds
passed since last time it was sent).
timeout is iteratively fetched from timeout_generator
... | f9363:c0:m2 |
def enqueue(self, queue_identifier: QueueIdentifier, message: Message): | assert queue_identifier.recipient == self.receiver<EOL>with self._lock:<EOL><INDENT>already_queued = any(<EOL>queue_identifier == data.queue_identifier and message == data.message<EOL>for data in self._message_queue<EOL>)<EOL>if already_queued:<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>receiver=pex(self.receiv... | Enqueue a message to be sent, and notify main loop | f9363:c0:m3 |
def enqueue_global(self, message: Message): | self.enqueue(<EOL>queue_identifier=QueueIdentifier(<EOL>recipient=self.receiver,<EOL>channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,<EOL>),<EOL>message=message,<EOL>)<EOL> | Helper to enqueue a message in the global queue (e.g. Delivered) | f9363:c0:m4 |
def notify(self): | with self._lock:<EOL><INDENT>self._notify_event.set()<EOL><DEDENT> | Notify main loop to check if anything needs to be sent | f9363:c0:m5 |
def _check_and_send(self): | if self.transport._stop_event.ready() or not self.transport.greenlet:<EOL><INDENT>self.log.error("<STR_LIT>")<EOL>return<EOL><DEDENT>if self.transport._prioritize_global_messages:<EOL><INDENT>self.transport._global_send_queue.join()<EOL><DEDENT>self.log.debug('<STR_LIT>', receiver=to_normalized_address(self.receiver))<... | Check and send all pending/queued messages that are not waiting on retry timeout
After composing the to-be-sent message, also message queue from messages that are not
present in the respective SendMessageEvent queue anymore | f9363:c0:m6 |
def _run(self): | <EOL>state_change = ActionUpdateTransportAuthData(<EOL>f'<STR_LIT>',<EOL>)<EOL>self.greenlet.name = f'<STR_LIT>'<EOL>self._raiden_service.handle_and_track_state_change(state_change)<EOL>try:<EOL><INDENT>self._global_send_worker()<EOL><DEDENT>except gevent.GreenletExit: <EOL><INDENT>self._stop_event.set()<EOL>gevent.ki... | Runnable main method, perform wait on long-running subtasks | f9363:c1:m3 |
def stop(self): | if self._stop_event.ready():<EOL><INDENT>return<EOL><DEDENT>self._stop_event.set()<EOL>self._global_send_event.set()<EOL>for retrier in self._address_to_retrier.values():<EOL><INDENT>if retrier:<EOL><INDENT>retrier.notify()<EOL><DEDENT><DEDENT>self._client.set_presence_state(UserPresence.OFFLINE.value)<EOL>self._client... | Try to gracefully stop the greenlet synchronously
Stop isn't expected to re-raise greenlet _run exception
(use self.greenlet.get() for that),
but it should raise any stop-time exception | f9363:c1:m4 |
def _spawn(self, func: Callable, *args, **kwargs) -> gevent.Greenlet: | def on_success(greenlet):<EOL><INDENT>if greenlet in self.greenlets:<EOL><INDENT>self.greenlets.remove(greenlet)<EOL><DEDENT><DEDENT>greenlet = gevent.spawn(func, *args, **kwargs)<EOL>greenlet.link_exception(self.on_error)<EOL>greenlet.link_value(on_success)<EOL>self.greenlets.append(greenlet)<EOL>return greenlet<EOL> | Spawn a sub-task and ensures an error on it crashes self/main greenlet | f9363:c1:m5 |
def whitelist(self, address: Address): | self.log.debug('<STR_LIT>', address=to_normalized_address(address))<EOL>self._address_mgr.add_address(address)<EOL> | Whitelist peer address to receive communications from
This may be called before transport is started, to ensure events generated during
start are handled properly. | f9363:c1:m6 |
def start_health_check(self, node_address): | if self._stop_event.ready():<EOL><INDENT>return<EOL><DEDENT>with self._health_lock:<EOL><INDENT>if self._address_mgr.is_address_known(node_address):<EOL><INDENT>return <EOL><DEDENT>node_address_hex = to_normalized_address(node_address)<EOL>self.log.debug('<STR_LIT>', peer_address=node_address_hex)<EOL>candidates = [<E... | Start healthcheck (status monitoring) for a peer
It also whitelists the address to answer invites and listen for messages | f9363:c1:m7 |
def send_async(<EOL>self,<EOL>queue_identifier: QueueIdentifier,<EOL>message: Message,<EOL>): | <EOL>receiver_address = queue_identifier.recipient<EOL>if not is_binary_address(receiver_address):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(pex(receiver_address)))<EOL><DEDENT>if isinstance(message, (Delivered, Ping, Pong)):<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(message.__class__.__name__),<EOL>)<... | Queue the message for sending to recipient in the queue_identifier
It may be called before transport is started, to initialize message queues
The actual sending is started only when the transport is started | f9363:c1:m8 |
def send_global(self, room: str, message: Message) -> None: | self._global_send_queue.put((room, message))<EOL>self._global_send_event.set()<EOL> | Sends a message to one of the global rooms
These rooms aren't being listened on and therefore no reply could be heard, so these
messages are sent in a send-and-forget async way.
The actual room name is composed from the suffix given as parameter and chain name or id
e.g.: raiden_ropsten... | f9363:c1:m9 |
def _handle_invite(self, room_id: _RoomID, state: dict): | if self._stop_event.ready():<EOL><INDENT>return<EOL><DEDENT>self.log.debug('<STR_LIT>', room_id=room_id)<EOL>invite_events = [<EOL>event<EOL>for event in state['<STR_LIT>']<EOL>if event['<STR_LIT:type>'] == '<STR_LIT>' and<EOL>event['<STR_LIT:content>'].get('<STR_LIT>') == '<STR_LIT>' and<EOL>event['<STR_LIT>'] == self... | Join rooms invited by whitelisted partners | f9363:c1:m16 |
def _handle_message(self, room, event) -> bool: | if (<EOL>event['<STR_LIT:type>'] != '<STR_LIT>' or<EOL>event['<STR_LIT:content>']['<STR_LIT>'] != '<STR_LIT>' or<EOL>self._stop_event.ready()<EOL>):<EOL><INDENT>return False<EOL><DEDENT>sender_id = event['<STR_LIT>']<EOL>if sender_id == self._user_id:<EOL><INDENT>return False<EOL><DEDENT>user = self._get_user(sender_id... | Handle text messages sent to listening rooms | f9363:c1:m17 |
def _get_retrier(self, receiver: Address) -> _RetryQueue: | if receiver not in self._address_to_retrier:<EOL><INDENT>retrier = _RetryQueue(transport=self, receiver=receiver)<EOL>self._address_to_retrier[receiver] = retrier<EOL>retrier.start()<EOL><DEDENT>return self._address_to_retrier[receiver]<EOL> | Construct and return a _RetryQueue for receiver | f9363:c1:m20 |
def _get_private_room(self, invitees: List[User]): | return self._client.create_room(<EOL>None,<EOL>invitees=[user.user_id for user in invitees],<EOL>is_public=False,<EOL>)<EOL> | Create an anonymous, private room and invite peers | f9363:c1:m24 |
def _get_public_room(self, room_name, invitees: List[User]): | room_name_full = f'<STR_LIT>'<EOL>invitees_uids = [user.user_id for user in invitees]<EOL>for _ in range(JOIN_RETRIES):<EOL><INDENT>try:<EOL><INDENT>room = self._client.join_room(room_name_full)<EOL><DEDENT>except MatrixRequestError as error:<EOL><INDENT>if error.code == <NUM_LIT>:<EOL><INDENT>self.log.debug(<EOL>f'<ST... | Obtain a public, canonically named (if possible) room and invite peers | f9363:c1:m25 |
def _sign(self, data: bytes) -> bytes: | assert self._raiden_service is not None<EOL>return self._raiden_service.signer.sign(data=data)<EOL> | Use eth_sign compatible hasher to sign matrix data | f9363:c1:m29 |
def _get_user(self, user: Union[User, str]) -> User: | user_id: str = getattr(user, '<STR_LIT>', user)<EOL>discovery_room = self._global_rooms.get(<EOL>make_room_alias(self.network_id, DISCOVERY_DEFAULT_ROOM),<EOL>)<EOL>if discovery_room and user_id in discovery_room._members:<EOL><INDENT>duser = discovery_room._members[user_id]<EOL>if getattr(user, '<STR_LIT>', None):<EOL... | Creates an User from an user_id, if none, or fetch a cached User
As all users are supposed to be in discovery room, its members dict is used for caching | f9363:c1:m30 |
def _set_room_id_for_address(self, address: Address, room_id: Optional[_RoomID] = None): | assert not room_id or room_id in self._client.rooms, '<STR_LIT>'<EOL>address_hex: AddressHex = to_checksum_address(address)<EOL>room_ids = self._get_room_ids_for_address(address, filter_private=False)<EOL>with self._account_data_lock:<EOL><INDENT>_address_to_room_ids = cast(<EOL>Dict[AddressHex, List[_RoomID]],<EOL>sel... | Uses GMatrixClient.set_account_data to keep updated mapping of addresses->rooms
If room_id is falsy, clean list of rooms. Else, push room_id to front of the list | f9363:c1:m31 |
def _get_room_ids_for_address(<EOL>self,<EOL>address: Address,<EOL>filter_private: bool = None,<EOL>) -> List[_RoomID]: | address_hex: AddressHex = to_checksum_address(address)<EOL>with self._account_data_lock:<EOL><INDENT>room_ids = self._client.account_data.get(<EOL>'<STR_LIT>',<EOL>{},<EOL>).get(address_hex)<EOL>self.log.debug('<STR_LIT>', room_ids=room_ids, for_address=address_hex)<EOL>if not room_ids: <EOL><INDENT>room_ids = list()<... | Uses GMatrixClient.get_account_data to get updated mapping of address->rooms
It'll filter only existing rooms.
If filter_private=True, also filter out public rooms.
If filter_private=None, filter according to self._private_rooms | f9363:c1:m32 |
def _leave_unused_rooms(self, _address_to_room_ids: Dict[AddressHex, List[_RoomID]]): | _msg = '<STR_LIT>'<EOL>assert self._account_data_lock.locked(), _msg<EOL>self._client.set_account_data(<EOL>'<STR_LIT>', <EOL>cast(Dict[str, Any], _address_to_room_ids),<EOL>)<EOL>return<EOL>whitelisted_hex_addresses: Set[AddressHex] = {<EOL>to_checksum_address(address)<EOL>for address in self._address_mgr.known_addre... | Checks for rooms we've joined and which partner isn't health-checked and leave.
**MUST** be called from a context that holds the `_account_data_lock`. | f9363:c1:m33 |
def join_global_room(client: GMatrixClient, name: str, servers: Sequence[str] = ()) -> Room: | our_server_name = urlparse(client.api.base_url).netloc<EOL>assert our_server_name, '<STR_LIT>'<EOL>servers = [our_server_name] + [ <EOL>urlparse(s).netloc<EOL>for s in servers<EOL>if urlparse(s).netloc not in {None, '<STR_LIT>', our_server_name}<EOL>]<EOL>our_server_global_room_alias_full = f'<STR_LIT>'<EOL>for server... | Join or create a global public room with given name
First, try to join room on own server (client-configured one)
If can't, try to join on each one of servers, and if able, alias it in our server
If still can't, create a public room with name in our server
Params:
client: matrix-python-sdk cli... | f9364:m0 |
def login_or_register(<EOL>client: GMatrixClient,<EOL>signer: Signer,<EOL>prev_user_id: str = None,<EOL>prev_access_token: str = None,<EOL>) -> User: | server_url = client.api.base_url<EOL>server_name = urlparse(server_url).netloc<EOL>base_username = to_normalized_address(signer.address)<EOL>_match_user = re.match(<EOL>f'<STR_LIT>',<EOL>prev_user_id or '<STR_LIT>',<EOL>)<EOL>if _match_user: <EOL><INDENT>log.debug('<STR_LIT>', user_id=prev_user_id)<EOL>client.set_acce... | Login to a Raiden matrix server with password and displayname proof-of-keys
- Username is in the format: 0x<eth_address>(.<suffix>)?, where the suffix is not required,
but a deterministic (per-account) random 8-hex string to prevent DoS by other users registering
our address
- Password is the signature... | f9364:m1 |
@cached(cache=LRUCache(<NUM_LIT>), key=attrgetter('<STR_LIT>', '<STR_LIT>'), lock=Semaphore())<EOL>def validate_userid_signature(user: User) -> Optional[Address]: | <EOL>match = USERID_RE.match(user.user_id)<EOL>if not match:<EOL><INDENT>return None<EOL><DEDENT>encoded_address = match.group(<NUM_LIT:1>)<EOL>address: Address = to_canonical_address(encoded_address)<EOL>try:<EOL><INDENT>displayname = user.get_display_name()<EOL>recovered = recover(<EOL>data=user.user_id.encode(),<EOL... | Validate a userId format and signature on displayName, and return its address | f9364:m2 |
def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]: | if not {urlparse(url).scheme for url in servers}.issubset({'<STR_LIT:http>', '<STR_LIT>'}):<EOL><INDENT>raise TransportError('<STR_LIT>')<EOL><DEDENT>get_rtt_jobs = set(<EOL>gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)<EOL>for server_url<EOL>in servers<EOL>)<EOL>gevent.joinall(get_rtt_jobs, raise_erro... | Sorts a list of servers by http round-trip time
Params:
servers: sequence of http server urls
Returns:
sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers
(possibly empty) | f9364:m3 |
def make_client(servers: Sequence[str], *args, **kwargs) -> GMatrixClient: | if len(servers) > <NUM_LIT:1>:<EOL><INDENT>sorted_servers = [<EOL>server_url<EOL>for (server_url, _) in sort_servers_closest(servers)<EOL>]<EOL>log.info(<EOL>'<STR_LIT>',<EOL>sorted_servers=sorted_servers,<EOL>)<EOL><DEDENT>elif len(servers) == <NUM_LIT:1>:<EOL><INDENT>sorted_servers = servers<EOL><DEDENT>else:<EOL><IN... | Given a list of possible servers, chooses the closest available and create a GMatrixClient
Params:
servers: list of servers urls, with scheme (http or https)
Rest of args and kwargs are forwarded to GMatrixClient constructor
Returns:
GMatrixClient instance for one of the available serve... | f9364:m4 |
def make_room_alias(chain_id: ChainID, *suffixes: str) -> str: | network_name = ID_TO_NETWORKNAME.get(chain_id, str(chain_id))<EOL>return ROOM_NAME_SEPARATOR.join([ROOM_NAME_PREFIX, network_name, *suffixes])<EOL> | Given a chain_id and any number of suffixes (global room names, pair of addresses),
compose and return the canonical room name for raiden network
network name from raiden_contracts.constants.ID_TO_NETWORKNAME is used for name, if available,
else numeric id
Params:
chain_id: numeric blockchain i... | f9364:m5 |
@property<EOL><INDENT>def known_addresses(self) -> KeysView[Address]:<DEDENT> | return self._address_to_userids.keys()<EOL> | Return all addresses we keep track of | f9364:c2:m1 |
def is_address_known(self, address: Address) -> bool: | return address in self._address_to_userids<EOL> | Is the given ``address`` reachability being monitored? | f9364:c2:m2 |
def add_address(self, address: Address): | <EOL>_ = self._address_to_userids[address]<EOL> | Add ``address`` to the known addresses that are being observed for reachability. | f9364:c2:m3 |
def add_userid_for_address(self, address: Address, user_id: str): | self._address_to_userids[address].add(user_id)<EOL> | Add a ``user_id`` for the given ``address``.
Implicitly adds the address if it was unknown before. | f9364:c2:m4 |
def add_userids_for_address(self, address: Address, user_ids: Iterable[str]): | self._address_to_userids[address].update(user_ids)<EOL> | Add multiple ``user_ids`` for the given ``address``.
Implicitly adds any addresses if they were unknown before. | f9364:c2:m5 |
def get_userids_for_address(self, address: Address) -> Set[str]: | if not self.is_address_known(address):<EOL><INDENT>return set()<EOL><DEDENT>return self._address_to_userids[address]<EOL> | Return all known user ids for the given ``address``. | f9364:c2:m6 |
def get_userid_presence(self, user_id: str) -> UserPresence: | return self._userid_to_presence.get(user_id, UserPresence.UNKNOWN)<EOL> | Return the current presence state of ``user_id``. | f9364:c2:m7 |
def get_address_reachability(self, address: Address) -> AddressReachability: | return self._address_to_reachability.get(address, AddressReachability.UNKNOWN)<EOL> | Return the current reachability state for ``address``. | f9364:c2:m8 |
def force_user_presence(self, user: User, presence: UserPresence): | self._userid_to_presence[user.user_id] = presence<EOL> | Forcibly set the ``user`` presence to ``presence``.
This method is only provided to cover an edge case in our use of the Matrix protocol and
should **not** generally be used. | f9364:c2:m9 |
def refresh_address_presence(self, address): | composite_presence = {<EOL>self._fetch_user_presence(uid)<EOL>for uid<EOL>in self._address_to_userids[address]<EOL>}<EOL>new_presence = UserPresence.UNKNOWN<EOL>for presence in UserPresence.__members__.values():<EOL><INDENT>if presence in composite_presence:<EOL><INDENT>new_presence = presence<EOL>break<EOL><DEDENT><DE... | Update synthesized address presence state from cached user presence states.
Triggers callback (if any) in case the state has changed.
This method is only provided to cover an edge case in our use of the Matrix protocol and
should **not** generally be used. | f9364:c2:m10 |
def _presence_listener(self, event: Dict[str, Any]): | if self._stop_event.ready():<EOL><INDENT>return<EOL><DEDENT>user_id = event['<STR_LIT>']<EOL>if event['<STR_LIT:type>'] != '<STR_LIT>' or user_id == self._user_id:<EOL><INDENT>return<EOL><DEDENT>user = self._get_user(user_id)<EOL>user.displayname = event['<STR_LIT:content>'].get('<STR_LIT>') or user.displayname<EOL>add... | Update cached user presence state from Matrix presence events.
Due to the possibility of nodes using accounts on multiple homeservers a composite
address state is synthesised from the cached individual user presence states. | f9364:c2:m11 |
def wrap(data): | try:<EOL><INDENT>cmdid = data[<NUM_LIT:0>]<EOL><DEDENT>except IndexError:<EOL><INDENT>log.warning('<STR_LIT>')<EOL>return None<EOL><DEDENT>try:<EOL><INDENT>message_type = CMDID_MESSAGE[cmdid]<EOL><DEDENT>except KeyError:<EOL><INDENT>log.error('<STR_LIT>', cmdid)<EOL>return None<EOL><DEDENT>try:<EOL><INDENT>message = me... | Try to decode data into a message, might return None if the data is invalid. | f9365:m1 |
def buffer_for(klass): | return bytearray(klass.size)<EOL> | Returns a new buffer of the appropriate size for klass. | f9366:m2 |
def namedbuffer(buffer_name, fields_spec): | <EOL>if not len(buffer_name):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not len(fields_spec):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>fields = [<EOL>field<EOL>for field in fields_spec<EOL>if not isinstance(field, Pad)<EOL>]<EOL>if any(field.size_bytes < <NUM_LIT:0> for field in fields):<EOL... | Class factory, returns a class to wrap a buffer instance and expose the
data as fields.
The field spec specifies how many bytes should be used for a field and what
is the encoding / decoding function. | f9366:m4 |
def validate(self, value: int): | if not isinstance(value, int):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if self.minimum > value or self.maximum < value:<EOL><INDENT>msg = (<EOL>'<STR_LIT>'<EOL>).format(value, self.minimum, self.maximum)<EOL>raise ValueError(msg)<EOL><DEDENT> | Validates the integer is in the value range. | f9367:c0:m1 |
def _data_to_sign(self) -> bytes: | packed = self.packed()<EOL>field = type(packed).fields_spec[-<NUM_LIT:1>]<EOL>assert field.name == '<STR_LIT>', '<STR_LIT>'<EOL>return packed.data[:-field.size_bytes]<EOL> | Return the binary data to be/which was signed | f9368:c2:m1 |
def sign(self, signer: Signer): | message_data = self._data_to_sign()<EOL>self.signature = signer.sign(data=message_data)<EOL> | Sign message using signer. | f9368:c2:m2 |
def _sign(self, signer: Signer) -> Signature: | <EOL>data = self._data_to_sign()<EOL>return signer.sign(data)<EOL> | Internal function for the overall `sign` function of `RequestMonitoring`. | f9368:c18:m3 |
def to_dict(self) -> Dict[str, Any]: | return {<EOL>'<STR_LIT:type>': self.__class__.__name__,<EOL>'<STR_LIT>': self.channel_identifier,<EOL>'<STR_LIT>': to_normalized_address(self.token_network_address),<EOL>'<STR_LIT>': encode_hex(self.balance_hash),<EOL>'<STR_LIT>': self.nonce,<EOL>'<STR_LIT>': encode_hex(self.additional_hash),<EOL>'<STR_LIT>': encode_he... | Message format according to monitoring service spec | f9368:c18:m4 |
def to_dict(self) -> Dict: | if not self.non_closing_signature:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not self.reward_proof_signature:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return {<EOL>'<STR_LIT:type>': self.__class__.__name__,<EOL>'<STR_LIT>': self.balance_proof.to_dict(),<EOL>'<STR_LIT>': str(self.reward_amoun... | Message format according to monitoring service spec | f9368:c19:m4 |
def _data_to_sign(self) -> bytes: | packed = pack_reward_proof(<EOL>canonical_identifier=CanonicalIdentifier(<EOL>chain_identifier=self.balance_proof.chain_id,<EOL>token_network_address=self.balance_proof.token_network_address,<EOL>channel_identifier=self.balance_proof.channel_identifier,<EOL>),<EOL>reward_amount=self.reward_amount,<EOL>nonce=self.balanc... | Return the binary data to be/which was signed | f9368:c19:m5 |
def sign(self, signer: Signer): | self.non_closing_signature = self.balance_proof._sign(signer)<EOL>message_data = self._data_to_sign()<EOL>self.signature = signer.sign(data=message_data)<EOL> | This method signs twice:
- the `non_closing_signature` for the balance proof update
- the `reward_proof_signature` for the monitoring request | f9368:c19:m6 |
def verify_request_monitoring(<EOL>self,<EOL>partner_address: Address,<EOL>requesting_address: Address,<EOL>) -> bool: | if not self.non_closing_signature:<EOL><INDENT>return False<EOL><DEDENT>balance_proof_data = pack_balance_proof(<EOL>nonce=self.balance_proof.nonce,<EOL>balance_hash=self.balance_proof.balance_hash,<EOL>additional_hash=self.balance_proof.additional_hash,<EOL>canonical_identifier=CanonicalIdentifier(<EOL>chain_identifie... | One should only use this method to verify integrity and signatures of a
RequestMonitoring message. | f9368:c19:m10 |
def check_keystore_json(jsondata: Dict) -> bool: | if '<STR_LIT>' not in jsondata and '<STR_LIT>' not in jsondata:<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT:version>' not in jsondata:<EOL><INDENT>return False<EOL><DEDENT>if jsondata['<STR_LIT:version>'] != <NUM_LIT:3>:<EOL><INDENT>return False<EOL><DEDENT>crypto = jsondata.get('<STR_LIT>', jsondata.get('<STR_LI... | Check if ``jsondata`` has the structure of a keystore file version 3.
Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters.
Copied from https://github.com/vbuterin/pybitcointools
Args:
jsondata: Dictionary containing the data from the json file
Return... | f9370:m2 |
def get_privkey(self, address: AddressHex, password: str) -> PrivateKey: | address = add_0x_prefix(address).lower()<EOL>if not self.address_in_keystore(address):<EOL><INDENT>raise ValueError('<STR_LIT>' % address)<EOL><DEDENT>with open(self.accounts[address]) as data_file:<EOL><INDENT>data = json.load(data_file)<EOL><DEDENT>acc = Account(data, password, self.accounts[address])<EOL>return acc.... | Find the keystore file for an account, unlock it and get the private key
Args:
address: The Ethereum address for which to find the keyfile in the system
password: Mostly for testing purposes. A password can be provided
as the function argument here. If it's no... | f9370:c1:m2 |
def __init__(self, keystore: Dict, password: str = None, path: str = None): | if path is not None:<EOL><INDENT>path = os.path.abspath(path)<EOL><DEDENT>self.keystore = keystore<EOL>self.locked = True<EOL>self.path = path<EOL>self._privkey = None<EOL>self._address = None<EOL>try:<EOL><INDENT>self._address = decode_hex(self.keystore['<STR_LIT:address>'])<EOL><DEDENT>except KeyError:<EOL><INDENT>pa... | Args:
keystore: the key store as a dictionary (as decoded from json)
password: The password used to unlock the keystore
path: absolute path to the associated keystore file (`None` for in-memory accounts) | f9370:c2:m0 |
@classmethod<EOL><INDENT>def load(cls, path: str, password: str = None) -> '<STR_LIT>':<DEDENT> | with open(path) as f:<EOL><INDENT>keystore = json.load(f)<EOL><DEDENT>if not check_keystore_json(keystore):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return Account(keystore, password, path=path)<EOL> | Load an account from a keystore file.
Args:
path: full path to the keyfile
password: the password to decrypt the key file or `None` to leave it encrypted | f9370:c2:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.