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>partner_locksroot=partner_locksroot,<EOL>given_block_identifier=block_identifier,<EOL>)<EOL>
|
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 interval > <NUM_LIT:0><EOL>last_timestamp = self.get_block_header(last_block_number)['<STR_LIT>']<EOL>first_timestamp = self.get_block_header(last_block_number - interval)['<STR_LIT>']<EOL>delta = last_timestamp - first_timestamp<EOL>return delta / interval<EOL>
|
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>contract_manager=self.contract_manager,<EOL>)<EOL><DEDENT><DEDENT>return self.address_to_token[token_address]<EOL>
|
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_address=discovery_address,<EOL>contract_manager=self.contract_manager,<EOL>)<EOL><DEDENT><DEDENT>return self.address_to_discovery[discovery_address]<EOL>
|
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><INDENT>if reliable:<EOL><INDENT>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, <NUM_LIT:1>)<EOL><DEDENT>try:<EOL><INDENT>sock.bind(('<STR_LIT:127.0.0.1>', port_candidate))<EOL><DEDENT>except OSError as ex:<EOL><INDENT>if ex.errno == errno.EADDRINUSE:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>sock_addr = sock.getsockname()<EOL>port = sock_addr[<NUM_LIT:1>]<EOL>if reliable:<EOL><INDENT>sock.listen(<NUM_LIT:1>)<EOL>sock2 = socket.socket(socket.AF_INET, socket_kind)<EOL>with closing(sock2):<EOL><INDENT>sock2.connect(sock_addr)<EOL>sock.accept()<EOL><DEDENT><DEDENT><DEDENT>yield port<EOL><DEDENT><DEDENT>return _port_generator()<EOL>
|
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
considered 'free' by the OS for the next 60 seconds. This does however require that the
process using the port sets SO_REUSEADDR on it's sockets. Most 'server' applications do.
If `initial_port` is passed the function will try to find a port as close as possible.
Otherwise a random port is chosen by the OS.
Returns an iterator that will return unused port numbers.
|
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<EOL><DEDENT>sleep(<NUM_LIT>)<EOL><DEDENT>return sum(durations) / samples<EOL>
|
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 = upnp.selectigd()<EOL>log.debug('<STR_LIT>', upnp=upnp)<EOL><DEDENT>except Exception as e:<EOL><INDENT>log.error('<STR_LIT>', exception_info=e)<EOL>return None<EOL><DEDENT>if not valid_mappable_ipv4(upnp.lanaddr):<EOL><INDENT>log.error('<STR_LIT>', reported=upnp.lanaddr)<EOL>return None<EOL><DEDENT>try: <EOL><INDENT>if not valid_mappable_ipv4(upnp.externalipaddress()):<EOL><INDENT>log.error('<STR_LIT>', reported=upnp.externalipaddress())<EOL>return None<EOL><DEDENT>return upnp, location<EOL><DEDENT>except Exception:<EOL><INDENT>log.error('<STR_LIT>', location=location)<EOL>return None<EOL><DEDENT>
|
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, name, _, _ = mapping<EOL>is_valid_mapping = (<EOL>lanaddr == upnp.lanaddr and<EOL>name == RAIDEN_IDENTIFICATOR and<EOL>internal_mapped == internal<EOL>)<EOL>is_not_our_mapping = (<EOL>internal_mapped != internal and<EOL>name != RAIDEN_IDENTIFICATOR<EOL>)<EOL>is_previous_mapping = (<EOL>internal_mapped != internal and<EOL>name == RAIDEN_IDENTIFICATOR and<EOL>lanaddr == upnp.lanaddr<EOL>)<EOL>if is_valid_mapping:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>internal=internal,<EOL>external=external,<EOL>lanaddr=lanaddr,<EOL>)<EOL>return True<EOL><DEDENT>elif lanaddr != upnp.lanaddr:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>internal=internal,<EOL>external=external,<EOL>other_ip=lanaddr,<EOL>our_ip=upnp.lanaddr,<EOL>)<EOL>return False<EOL><DEDENT>elif is_not_our_mapping:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>name=name,<EOL>)<EOL>return False<EOL><DEDENT>elif is_previous_mapping:<EOL><INDENT>log.debug('<STR_LIT>')<EOL>upnp.deleteportmapping(external, '<STR_LIT>')<EOL><DEDENT><DEDENT>log.debug('<STR_LIT>', internal=internal, external=external)<EOL>return upnp.addportmapping(<EOL>external,<EOL>'<STR_LIT>',<EOL>upnp.lanaddr,<EOL>internal,<EOL>RAIDEN_IDENTIFICATOR,<EOL>'<STR_LIT>',<EOL>)<EOL><DEDENT>external_port = external_start_port<EOL>success = register(internal_port, external_port)<EOL>while not success and external_port <= MAX_PORT:<EOL><INDENT>external_port += <NUM_LIT:1><EOL>log.debug('<STR_LIT>', external=external_port)<EOL>success = register(internal_port, external_port)<EOL><DEDENT>if success:<EOL><INDENT>return upnp.externalipaddress(), external_port<EOL><DEDENT>else:<EOL><INDENT>log.error(<EOL>'<STR_LIT>',<EOL>location='<STR_LIT>',<EOL>)<EOL>return False<EOL><DEDENT>return False<EOL>
|
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, external_port (tuple(str, int)): if successful or None
|
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.info('<STR_LIT>', external=external_port)<EOL>return True<EOL><DEDENT>log.warning(<EOL>'<STR_LIT>',<EOL>)<EOL>return False<EOL>
|
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>'<STR_LIT>',<EOL>node=pex(transport.raiden.address),<EOL>recipient=pex(recipient),<EOL>msgid=message_id,<EOL>)<EOL>transport.maybe_sendraw_with_result(<EOL>recipient,<EOL>messagedata,<EOL>message_id,<EOL>)<EOL><DEDENT>return async_result.ready()<EOL>
|
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>)<EOL>wait_recovery(<EOL>stop_event,<EOL>event_healthy,<EOL>)<EOL>stop_or_unhealthy.clear()<EOL>if stop_event.is_set():<EOL><INDENT>return acknowledged<EOL><DEDENT><DEDENT>acknowledged = retry(<EOL>transport,<EOL>messagedata,<EOL>message_id,<EOL>recipient,<EOL>stop_or_unhealthy,<EOL>backoff,<EOL>)<EOL><DEDENT>return acknowledged<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,<EOL>event_stop,<EOL>).wait()<EOL>transport.log.debug(<EOL>'<STR_LIT>',<EOL>queue_identifier=queue_identifier,<EOL>queue_size=len(queue),<EOL>)<EOL>while True:<EOL><INDENT>data_or_stop.wait()<EOL>if event_stop.is_set():<EOL><INDENT>transport.log.debug(<EOL>'<STR_LIT>',<EOL>queue_identifier=queue_identifier,<EOL>queue_size=len(queue),<EOL>)<EOL>return<EOL><DEDENT>(messagedata, message_id) = queue.peek(block=False)<EOL>transport.log.debug(<EOL>'<STR_LIT>',<EOL>recipient=pex(recipient),<EOL>msgid=message_id,<EOL>queue_identifier=queue_identifier,<EOL>queue_size=len(queue),<EOL>)<EOL>backoff = timeout_exponential_backoff(<EOL>message_retries,<EOL>message_retry_timeout,<EOL>message_retry_max_timeout,<EOL>)<EOL>acknowledged = retry_with_recovery(<EOL>transport,<EOL>messagedata,<EOL>message_id,<EOL>recipient,<EOL>event_stop,<EOL>event_healthy,<EOL>event_unhealthy,<EOL>backoff,<EOL>)<EOL>if acknowledged:<EOL><INDENT>queue.get()<EOL>if not queue:<EOL><INDENT>data_or_stop.clear()<EOL>if event_stop.is_set():<EOL><INDENT>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
|
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 start them together to avoid congestion.
- This task assumes the endpoint is never cleared after it's first known.
If this assumption changes the code must be updated to handle unknown
addresses.
|
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_events[recipient] = events<EOL>greenlet_healthcheck = gevent.spawn(<EOL>healthcheck.healthcheck,<EOL>self,<EOL>recipient,<EOL>self.event_stop,<EOL>events.event_healthy,<EOL>events.event_unhealthy,<EOL>self.nat_keepalive_retries,<EOL>self.nat_keepalive_timeout,<EOL>self.nat_invitation_timeout,<EOL>ping_nonce,<EOL>)<EOL>greenlet_healthcheck.name = f'<STR_LIT>'<EOL>greenlet_healthcheck.link_exception(self.on_error)<EOL>self.greenlets.append(greenlet_healthcheck)<EOL><DEDENT>
|
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,<EOL>self,<EOL>recipient,<EOL>queue,<EOL>queue_identifier,<EOL>self.event_stop,<EOL>events.event_healthy,<EOL>events.event_unhealthy,<EOL>self.retries_before_backoff,<EOL>self.retry_interval,<EOL>self.retry_interval * <NUM_LIT:10>,<EOL>)<EOL>if queue_identifier.channel_identifier == CHANNEL_IDENTIFIER_GLOBAL_QUEUE:<EOL><INDENT>greenlet_queue.name = f'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>greenlet_queue.name = (<EOL>f'<STR_LIT>'<EOL>)<EOL><DEDENT>greenlet_queue.link_exception(self.on_error)<EOL>self.greenlets.append(greenlet_queue)<EOL>self.log.debug(<EOL>'<STR_LIT>',<EOL>queue_identifier=queue_identifier,<EOL>items_qty=len(items),<EOL>)<EOL>return queue<EOL>
|
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.encode()<EOL>if len(messagedata) > self.UDP_MAX_MESSAGE_SIZE:<EOL><INDENT>raise ValueError(<EOL>'<STR_LIT>'.format(self.UDP_MAX_MESSAGE_SIZE),<EOL>)<EOL><DEDENT>message_id = message.message_identifier<EOL>if message_id not in self.messageids_to_asyncresults:<EOL><INDENT>self.messageids_to_asyncresults[message_id] = AsyncResult()<EOL>queue = self.get_queue_for(queue_identifier)<EOL>queue.put((messagedata, message_id))<EOL>assert queue.is_set()<EOL>self.log.debug(<EOL>'<STR_LIT>',<EOL>queue_identifier=queue_identifier,<EOL>queue_size=len(queue),<EOL>message=message,<EOL>)<EOL><DEDENT>
|
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<EOL>
|
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.warning(<EOL>'<STR_LIT>',<EOL>error=str(e),<EOL>message=encode_hex(messagedata),<EOL>)<EOL>return False<EOL><DEDENT>if type(message) == Pong:<EOL><INDENT>assert isinstance(message, Pong), MYPY_ANNOTATION<EOL>self.receive_pong(message)<EOL><DEDENT>elif type(message) == Ping:<EOL><INDENT>assert isinstance(message, Ping), MYPY_ANNOTATION<EOL>self.receive_ping(message)<EOL><DEDENT>elif type(message) == Delivered:<EOL><INDENT>assert isinstance(message, Delivered), MYPY_ANNOTATION<EOL>self.receive_delivered(message)<EOL><DEDENT>elif message is not None:<EOL><INDENT>self.receive_message(message)<EOL><DEDENT>else:<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>message=encode_hex(messagedata),<EOL>)<EOL>return False<EOL><DEDENT>return True<EOL>
|
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 property than what is
required of any transport.
|
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>self.log.warn(<EOL>'<STR_LIT>',<EOL>message_id=message_id,<EOL>)<EOL><DEDENT>
|
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.debug("<STR_LIT>", e=e)<EOL><DEDENT>
|
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><INDENT>self.log_healthcheck.warn(<EOL>'<STR_LIT>',<EOL>message_id=message_id,<EOL>)<EOL><DEDENT>
|
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(<EOL>'<STR_LIT>',<EOL>node=pex(transport.address),<EOL>to=pex(recipient),<EOL>)<EOL>event_healthy.clear()<EOL>event_unhealthy.set()<EOL>backoff = udp_utils.timeout_exponential_backoff(<EOL>nat_keepalive_retries,<EOL>nat_keepalive_timeout,<EOL>nat_invitation_timeout,<EOL>)<EOL>sleep = next(backoff)<EOL>while not stop_event.wait(sleep):<EOL><INDENT>try:<EOL><INDENT>transport.get_host_port(recipient)<EOL><DEDENT>except UnknownAddress:<EOL><INDENT>sleep = next(backoff)<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>sleep = <NUM_LIT:0><EOL>event_unhealthy.clear()<EOL>event_healthy.set()<EOL>while not stop_event.wait(sleep):<EOL><INDENT>sleep = nat_keepalive_timeout<EOL>ping_nonce['<STR_LIT>'] = Nonce(ping_nonce['<STR_LIT>'] + <NUM_LIT:1>)<EOL>messagedata = transport.get_ping(ping_nonce['<STR_LIT>'])<EOL>message_id = ('<STR_LIT>', ping_nonce['<STR_LIT>'], recipient)<EOL>acknowledged = udp_utils.retry(<EOL>transport,<EOL>messagedata,<EOL>message_id,<EOL>recipient,<EOL>stop_event,<EOL>[nat_keepalive_timeout] * nat_keepalive_retries,<EOL>)<EOL>if stop_event.is_set():<EOL><INDENT>return<EOL><DEDENT>if not acknowledged:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(transport.address),<EOL>to=pex(recipient),<EOL>current_state=last_state,<EOL>new_state=NODE_NETWORK_UNREACHABLE,<EOL>retries=nat_keepalive_retries,<EOL>timeout=nat_keepalive_timeout,<EOL>)<EOL>last_state = NODE_NETWORK_UNREACHABLE<EOL>transport.set_node_network_state(<EOL>recipient,<EOL>last_state,<EOL>)<EOL>event_healthy.clear()<EOL>event_unhealthy.set()<EOL>acknowledged = udp_utils.retry(<EOL>transport,<EOL>messagedata,<EOL>message_id,<EOL>recipient,<EOL>stop_event,<EOL>repeat(nat_invitation_timeout),<EOL>)<EOL><DEDENT>if acknowledged:<EOL><INDENT>current_state = views.get_node_network_status(<EOL>views.state_from_raiden(transport.raiden),<EOL>recipient,<EOL>)<EOL>if last_state != NODE_NETWORK_REACHABLE:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>node=pex(transport.raiden.address),<EOL>to=pex(recipient),<EOL>current_state=current_state,<EOL>new_state=NODE_NETWORK_REACHABLE,<EOL>)<EOL>last_state = NODE_NETWORK_REACHABLE<EOL>transport.set_node_network_state(<EOL>recipient,<EOL>last_state,<EOL>)<EOL>event_unhealthy.clear()<EOL>event_healthy.set()<EOL><DEDENT><DEDENT><DEDENT>
|
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>self.client.api,<EOL>user_id,<EOL>event['<STR_LIT:content>'].get('<STR_LIT>'),<EOL>),<EOL>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return list(self._members.values())<EOL>
|
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 = content['<STR_LIT>']<EOL>if aliases != self.aliases:<EOL><INDENT>self.aliases = aliases<EOL>changed = True<EOL><DEDENT><DEDENT>if chunk.get('<STR_LIT:type>') == '<STR_LIT>':<EOL><INDENT>canonical_alias = content['<STR_LIT>']<EOL>if self.canonical_alias != canonical_alias:<EOL><INDENT>self.canonical_alias = canonical_alias<EOL>changed = True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if changed and self.aliases and not self.canonical_alias:<EOL><INDENT>self.canonical_alias = self.aliases[<NUM_LIT:0>]<EOL><DEDENT>return changed<EOL>
|
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.warning(<EOL>'<STR_LIT>',<EOL>wait_for=_bad_sync_timeout,<EOL>)<EOL>gevent.sleep(_bad_sync_timeout)<EOL>_bad_sync_timeout = min(_bad_sync_timeout * <NUM_LIT:2>, self.bad_sync_timeout_limit)<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT>except MatrixHttpLibError:<EOL><INDENT>log.exception('<STR_LIT>')<EOL>if self.should_listen:<EOL><INDENT>gevent.sleep(_bad_sync_timeout)<EOL>_bad_sync_timeout = min(_bad_sync_timeout * <NUM_LIT:2>, self.bad_sync_timeout_limit)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>log.exception('<STR_LIT>')<EOL>if exception_handler is not None:<EOL><INDENT>exception_handler(e)<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>
|
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.
Will be increased according to exponential backoff.
|
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._handle_response, response, is_first_sync)<EOL>self._handle_thread.name = (<EOL>f'<STR_LIT>'<EOL>)<EOL>self._handle_thread.link_exception(lambda g: self.sync_thread.kill(g.exception))<EOL>self._handle_thread.start()<EOL>if self._post_hook_func is not None:<EOL><INDENT>self._post_hook_func(self.sync_token)<EOL><DEDENT>
|
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
First value is True to always send message at least once
|
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.receiver),<EOL>queue=queue_identifier,<EOL>message=message,<EOL>)<EOL>return<EOL><DEDENT>timeout_generator = udp_utils.timeout_exponential_backoff(<EOL>self.transport._config['<STR_LIT>'],<EOL>self.transport._config['<STR_LIT>'],<EOL>self.transport._config['<STR_LIT>'] * <NUM_LIT:10>,<EOL>)<EOL>expiration_generator = self._expiration_generator(timeout_generator)<EOL>self._message_queue.append(_RetryQueue._MessageData(<EOL>queue_identifier=queue_identifier,<EOL>message=message,<EOL>text=json.dumps(message.to_dict()),<EOL>expiration_generator=expiration_generator,<EOL>))<EOL><DEDENT>self.notify()<EOL>
|
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))<EOL>status = self.transport._address_mgr.get_address_reachability(self.receiver)<EOL>if status is not AddressReachability.REACHABLE:<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>partner=pex(self.receiver),<EOL>status=status,<EOL>)<EOL>return<EOL><DEDENT>ordered_queue = sorted(<EOL>self._message_queue,<EOL>key=lambda d: d.queue_identifier.channel_identifier,<EOL>)<EOL>message_texts = [<EOL>data.text<EOL>for data in ordered_queue<EOL>if next(data.expiration_generator)<EOL>]<EOL>def message_is_in_queue(data: _RetryQueue._MessageData) -> bool:<EOL><INDENT>return any(<EOL>isinstance(data.message, RetrieableMessage) and<EOL>send_event.message_identifier == data.message.message_identifier<EOL>for send_event in self.transport._queueids_to_queues[data.queue_identifier]<EOL>)<EOL><DEDENT>for msg_data in self._message_queue[:]:<EOL><INDENT>remove = False<EOL>if isinstance(msg_data.message, (Delivered, Ping, Pong)):<EOL><INDENT>remove = True<EOL><DEDENT>elif msg_data.queue_identifier not in self.transport._queueids_to_queues:<EOL><INDENT>remove = True<EOL>self.log.debug(<EOL>'<STR_LIT>',<EOL>queue=msg_data.queue_identifier,<EOL>message=msg_data.message,<EOL>reason='<STR_LIT>',<EOL>)<EOL><DEDENT>elif not message_is_in_queue(msg_data):<EOL><INDENT>remove = True<EOL>self.log.debug(<EOL>'<STR_LIT>',<EOL>queue=msg_data.queue_identifier,<EOL>message=msg_data.message,<EOL>reason='<STR_LIT>',<EOL>)<EOL><DEDENT>if remove:<EOL><INDENT>self._message_queue.remove(msg_data)<EOL><DEDENT><DEDENT>if message_texts:<EOL><INDENT>self.log.debug('<STR_LIT>', receiver=pex(self.receiver), messages=message_texts)<EOL>self.transport._send_raw(self.receiver, '<STR_LIT:\n>'.join(message_texts))<EOL><DEDENT>
|
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.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
|
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.stop_listener_thread() <EOL>gevent.wait(self.greenlets + [r.greenlet for r in self._address_to_retrier.values()])<EOL>self._client.api.session.close()<EOL>self.log.debug('<STR_LIT>', config=self._config)<EOL>del self.log<EOL>
|
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 = [<EOL>self._get_user(user)<EOL>for user in self._client.search_user_directory(node_address_hex)<EOL>]<EOL>user_ids = {<EOL>user.user_id<EOL>for user in candidates<EOL>if validate_userid_signature(user) == node_address<EOL>}<EOL>self.whitelist(node_address)<EOL>self._address_mgr.add_userids_for_address(node_address, user_ids)<EOL>self._address_mgr.refresh_address_presence(node_address)<EOL><DEDENT>
|
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>)<EOL><DEDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>receiver_address=pex(receiver_address),<EOL>message=message,<EOL>queue_identifier=queue_identifier,<EOL>)<EOL>self._send_with_retry(queue_identifier, message)<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_discovery
Params:
room: name suffix as passed in config['global_rooms'] list
message: Message instance to be serialized and sent
|
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._user_id<EOL>]<EOL>if not invite_events:<EOL><INDENT>self.log.debug('<STR_LIT>', room_id=room_id)<EOL>return <EOL><DEDENT>invite_event = invite_events[<NUM_LIT:0>]<EOL>sender = invite_event['<STR_LIT>']<EOL>sender_join_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>'] == sender<EOL>]<EOL>if not sender_join_events:<EOL><INDENT>self.log.debug('<STR_LIT>', room_id=room_id)<EOL>return <EOL><DEDENT>sender_join_event = sender_join_events[<NUM_LIT:0>]<EOL>user = self._get_user(sender)<EOL>user.displayname = sender_join_event['<STR_LIT:content>'].get('<STR_LIT>') or user.displayname<EOL>peer_address = validate_userid_signature(user)<EOL>if not peer_address:<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>room_id=room_id,<EOL>user=user,<EOL>)<EOL>return<EOL><DEDENT>if not self._address_mgr.is_address_known(peer_address):<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>room_id=room_id,<EOL>user=user,<EOL>)<EOL>return<EOL><DEDENT>join_rules_events = [<EOL>event<EOL>for event in state['<STR_LIT>']<EOL>if event['<STR_LIT:type>'] == '<STR_LIT>'<EOL>]<EOL>private_room: bool = False<EOL>if join_rules_events:<EOL><INDENT>join_rules_event = join_rules_events[<NUM_LIT:0>]<EOL>private_room = join_rules_event['<STR_LIT:content>'].get('<STR_LIT>') == '<STR_LIT>'<EOL><DEDENT>room: Room = None<EOL>last_ex: Optional[Exception] = None<EOL>retry_interval = <NUM_LIT:0.1><EOL>for _ in range(JOIN_RETRIES):<EOL><INDENT>try:<EOL><INDENT>room = self._client.join_room(room_id)<EOL><DEDENT>except MatrixRequestError as e:<EOL><INDENT>last_ex = e<EOL>if self._stop_event.wait(retry_interval):<EOL><INDENT>break<EOL><DEDENT>retry_interval = retry_interval * <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>assert last_ex is not None<EOL>raise last_ex <EOL><DEDENT>if not room.listeners:<EOL><INDENT>room.add_listener(self._handle_message, '<STR_LIT>')<EOL><DEDENT>room.invite_only = private_room<EOL>self._set_room_id_for_address(address=peer_address, room_id=room_id)<EOL>self.log.debug(<EOL>'<STR_LIT>',<EOL>room_id=room_id,<EOL>aliases=room.aliases,<EOL>peer=to_checksum_address(peer_address),<EOL>)<EOL>
|
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)<EOL>peer_address = validate_userid_signature(user)<EOL>if not peer_address:<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>peer_user=user.user_id,<EOL>room=room,<EOL>)<EOL>return False<EOL><DEDENT>if not self._address_mgr.is_address_known(peer_address):<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>sender=user,<EOL>sender_address=pex(peer_address),<EOL>room=room,<EOL>)<EOL>return False<EOL><DEDENT>room_ids = self._get_room_ids_for_address(peer_address)<EOL>if room.room_id not in room_ids and (self._private_rooms and not room.invite_only):<EOL><INDENT>if self._private_rooms and not room.invite_only:<EOL><INDENT>reason = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>reason = '<STR_LIT>'<EOL><DEDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>peer_user=user.user_id,<EOL>peer_address=pex(peer_address),<EOL>room=room,<EOL>expected_room_ids=room_ids,<EOL>reason=reason,<EOL>)<EOL>return False<EOL><DEDENT>if not room_ids or room.room_id != room_ids[<NUM_LIT:0>]:<EOL><INDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>peer_user=user.user_id,<EOL>peer_address=pex(peer_address),<EOL>known_user_rooms=room_ids,<EOL>room=room,<EOL>)<EOL>self._set_room_id_for_address(peer_address, room.room_id)<EOL><DEDENT>is_peer_reachable = self._address_mgr.get_address_reachability(peer_address) is (<EOL>AddressReachability.REACHABLE<EOL>)<EOL>if not is_peer_reachable:<EOL><INDENT>self.log.debug('<STR_LIT>', peer_address=peer_address, user_id=sender_id)<EOL>self._address_mgr.force_user_presence(user, UserPresence.ONLINE)<EOL>self._address_mgr.refresh_address_presence(peer_address)<EOL><DEDENT>data = event['<STR_LIT:content>']['<STR_LIT:body>']<EOL>if not isinstance(data, str):<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>peer_user=user.user_id,<EOL>peer_address=to_checksum_address(peer_address),<EOL>room=room,<EOL>)<EOL>return False<EOL><DEDENT>messages: List[Message] = list()<EOL>if data.startswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>message = message_from_bytes(decode_hex(data))<EOL>if not message:<EOL><INDENT>raise InvalidProtocolMessage<EOL><DEDENT><DEDENT>except (DecodeError, AssertionError) as ex:<EOL><INDENT>self.log.warning(<EOL>"<STR_LIT>",<EOL>message_data=data,<EOL>peer_address=pex(peer_address),<EOL>_exc=ex,<EOL>)<EOL>return False<EOL><DEDENT>except InvalidProtocolMessage as ex:<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>message_data=data,<EOL>peer_address=pex(peer_address),<EOL>_exc=ex,<EOL>)<EOL>return False<EOL><DEDENT>else:<EOL><INDENT>messages.append(message)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for line in data.splitlines():<EOL><INDENT>line = line.strip()<EOL>if not line:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>message_dict = json.loads(line)<EOL>message = message_from_dict(message_dict)<EOL><DEDENT>except (UnicodeDecodeError, json.JSONDecodeError) as ex:<EOL><INDENT>self.log.warning(<EOL>"<STR_LIT>",<EOL>message_data=line,<EOL>peer_address=pex(peer_address),<EOL>_exc=ex,<EOL>)<EOL>continue<EOL><DEDENT>except InvalidProtocolMessage as ex:<EOL><INDENT>self.log.warning(<EOL>"<STR_LIT>",<EOL>message_data=line,<EOL>peer_address=pex(peer_address),<EOL>_exc=ex,<EOL>)<EOL>continue<EOL><DEDENT>if not isinstance(message, (SignedRetrieableMessage, SignedMessage)):<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>message=message,<EOL>)<EOL>continue<EOL><DEDENT>elif message.sender != peer_address:<EOL><INDENT>self.log.warning(<EOL>'<STR_LIT>',<EOL>message=message,<EOL>signer=message.sender,<EOL>peer_address=peer_address,<EOL>)<EOL>continue<EOL><DEDENT>messages.append(message)<EOL><DEDENT><DEDENT>if not messages:<EOL><INDENT>return False<EOL><DEDENT>self.log.debug(<EOL>'<STR_LIT>',<EOL>messages=messages,<EOL>sender=pex(peer_address),<EOL>sender_user=user,<EOL>room=room,<EOL>)<EOL>for message in messages:<EOL><INDENT>if isinstance(message, Delivered):<EOL><INDENT>self._receive_delivered(message)<EOL><DEDENT>elif isinstance(message, Processed):<EOL><INDENT>self._receive_message(message)<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(message, SignedRetrieableMessage)<EOL>self._receive_message(message)<EOL><DEDENT><DEDENT>return True<EOL>
|
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'<STR_LIT>',<EOL>room_name=room_name_full,<EOL>error=error,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.log.debug(<EOL>f'<STR_LIT>',<EOL>room_name=room_name,<EOL>error=error.content,<EOL>error_code=error.code,<EOL>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>member_ids = {user.user_id for user in room.get_joined_members(force_resync=True)}<EOL>users_to_invite = set(invitees_uids) - member_ids<EOL>self.log.debug('<STR_LIT>', room=room, invitee_ids=users_to_invite)<EOL>for invitee_id in users_to_invite:<EOL><INDENT>room.invite_user(invitee_id)<EOL><DEDENT>self.log.debug('<STR_LIT>', room=room)<EOL>break<EOL><DEDENT>try:<EOL><INDENT>room = self._client.create_room(<EOL>room_name,<EOL>invitees=invitees_uids,<EOL>is_public=True,<EOL>)<EOL><DEDENT>except MatrixRequestError as error:<EOL><INDENT>if error.code == <NUM_LIT>:<EOL><INDENT>msg = (<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>)<EOL><DEDENT>else:<EOL><INDENT>msg = '<STR_LIT>'<EOL><DEDENT>self.log.debug(<EOL>msg,<EOL>room_name=room_name,<EOL>error=error.content,<EOL>error_code=error.code,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.log.debug('<STR_LIT>', room=room, invitees=invitees)<EOL>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>room = self._client.create_room(<EOL>None,<EOL>invitees=invitees_uids,<EOL>is_public=True,<EOL>)<EOL>self.log.warning(<EOL>'<STR_LIT>',<EOL>room=room,<EOL>invitees=invitees,<EOL>)<EOL><DEDENT>return room<EOL>
|
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><INDENT>assert isinstance(user, User)<EOL>duser.displayname = user.displayname<EOL><DEDENT>user = duser<EOL><DEDENT>elif not isinstance(user, User):<EOL><INDENT>user = self._client.get_user(user_id)<EOL><DEDENT>return user<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>self._client.account_data.get('<STR_LIT>', {}).copy(),<EOL>)<EOL>changed = False<EOL>if not room_id: <EOL><INDENT>changed = address_hex in _address_to_room_ids<EOL>_address_to_room_ids.pop(address_hex, None)<EOL><DEDENT>else:<EOL><INDENT>room_ids = [room_id] + [r for r in room_ids if r != room_id]<EOL>if room_ids != _address_to_room_ids.get(address_hex):<EOL><INDENT>_address_to_room_ids[address_hex] = room_ids<EOL>changed = True<EOL><DEDENT><DEDENT>if changed:<EOL><INDENT>self._leave_unused_rooms(_address_to_room_ids)<EOL><DEDENT><DEDENT>
|
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()<EOL><DEDENT>if not isinstance(room_ids, list): <EOL><INDENT>room_ids = [room_ids]<EOL><DEDENT>if filter_private is None:<EOL><INDENT>filter_private = self._private_rooms<EOL><DEDENT>if not filter_private:<EOL><INDENT>room_ids = [<EOL>room_id<EOL>for room_id in room_ids<EOL>if room_id in self._client.rooms<EOL>]<EOL><DEDENT>else:<EOL><INDENT>room_ids = [<EOL>room_id<EOL>for room_id in room_ids<EOL>if room_id in self._client.rooms and self._client.rooms[room_id].invite_only<EOL>]<EOL><DEDENT>return room_ids<EOL><DEDENT>
|
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_addresses<EOL>}<EOL>keep_rooms: Set[_RoomID] = set()<EOL>for address_hex, room_ids in list(_address_to_room_ids.items()):<EOL><INDENT>if not room_ids: <EOL><INDENT>room_ids = list()<EOL><DEDENT>if not isinstance(room_ids, list): <EOL><INDENT>room_ids = [room_ids]<EOL><DEDENT>if address_hex not in whitelisted_hex_addresses:<EOL><INDENT>_address_to_room_ids.pop(address_hex)<EOL>continue<EOL><DEDENT>counters = [<NUM_LIT:0>, <NUM_LIT:0>] <EOL>new_room_ids: List[_RoomID] = list()<EOL>for room_id in room_ids:<EOL><INDENT>if room_id not in self._client.rooms:<EOL><INDENT>continue<EOL><DEDENT>elif self._client.rooms[room_id].invite_only is None:<EOL><INDENT>new_room_ids.append(room_id) <EOL><DEDENT>elif counters[self._client.rooms[room_id].invite_only] < <NUM_LIT:2>:<EOL><INDENT>counters[self._client.rooms[room_id].invite_only] += <NUM_LIT:1><EOL>new_room_ids.append(room_id) <EOL><DEDENT>else:<EOL><INDENT>continue <EOL><DEDENT><DEDENT>keep_rooms |= set(new_room_ids)<EOL>if room_ids != new_room_ids:<EOL><INDENT>_address_to_room_ids[address_hex] = new_room_ids<EOL><DEDENT><DEDENT>rooms: List[Tuple[_RoomID, Room]] = list(self._client.rooms.items())<EOL>self.log.debug(<EOL>'<STR_LIT>',<EOL>address_to_room_ids=_address_to_room_ids,<EOL>)<EOL>self._client.set_account_data('<STR_LIT>', _address_to_room_ids)<EOL>def leave(room: Room):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>self.log.debug('<STR_LIT>', room=room)<EOL>return room.leave()<EOL><DEDENT>except KeyError:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>for room_id, room in rooms:<EOL><INDENT>if room_id in {groom.room_id for groom in self._global_rooms.values() if groom}:<EOL><INDENT>continue<EOL><DEDENT>if room_id not in keep_rooms:<EOL><INDENT>greenlet = self._spawn(leave, room)<EOL>greenlet.name = (<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>f'<STR_LIT>'<EOL>)<EOL><DEDENT><DEDENT>
|
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 in servers:<EOL><INDENT>global_room_alias_full = f'<STR_LIT>'<EOL>try:<EOL><INDENT>global_room = client.join_room(global_room_alias_full)<EOL><DEDENT>except MatrixRequestError as ex:<EOL><INDENT>if ex.code not in (<NUM_LIT>, <NUM_LIT>, <NUM_LIT>):<EOL><INDENT>raise<EOL><DEDENT>log.debug(<EOL>'<STR_LIT>',<EOL>room_alias_full=global_room_alias_full,<EOL>_exception=ex,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>if our_server_global_room_alias_full not in global_room.aliases:<EOL><INDENT>global_room.add_room_alias(our_server_global_room_alias_full)<EOL>global_room.aliases.append(our_server_global_room_alias_full)<EOL><DEDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.debug('<STR_LIT>')<EOL>for _ in range(JOIN_RETRIES):<EOL><INDENT>try:<EOL><INDENT>global_room = client.create_room(name, is_public=True)<EOL><DEDENT>except MatrixRequestError as ex:<EOL><INDENT>if ex.code not in (<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>raise<EOL><DEDENT>try:<EOL><INDENT>global_room = client.join_room(<EOL>our_server_global_room_alias_full,<EOL>)<EOL><DEDENT>except MatrixRequestError as ex:<EOL><INDENT>if ex.code not in (<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>raise<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TransportError('<STR_LIT>')<EOL><DEDENT><DEDENT>return global_room<EOL>
|
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 client instance
name: name or alias of the room (without #-prefix or server name suffix)
servers: optional: sequence of known/available servers to try to find the room in
Returns:
matrix's Room instance linked to client
|
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_access_token(user_id=prev_user_id, token=prev_access_token)<EOL>try:<EOL><INDENT>client.api.get_devices()<EOL><DEDENT>except MatrixRequestError as ex:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>prev_user_id=prev_user_id,<EOL>_exception=ex,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>prev_sync_limit = client.set_sync_limit(<NUM_LIT:0>)<EOL>client._sync() <EOL>client.set_sync_limit(prev_sync_limit)<EOL>log.debug('<STR_LIT>', user_id=prev_user_id)<EOL>return client.get_user(client.user_id)<EOL><DEDENT><DEDENT>elif prev_user_id:<EOL><INDENT>log.debug(<EOL>'<STR_LIT>',<EOL>prev_user_id=prev_user_id,<EOL>current_address=base_username,<EOL>current_server=server_name,<EOL>)<EOL><DEDENT>password = encode_hex(signer.sign(server_name.encode()))<EOL>rand = None<EOL>for i in range(JOIN_RETRIES):<EOL><INDENT>username = base_username<EOL>if i:<EOL><INDENT>if not rand:<EOL><INDENT>rand = Random() <EOL>rand.seed(int.from_bytes(signer.sign(b'<STR_LIT>')[-<NUM_LIT:32>:], '<STR_LIT>'))<EOL><DEDENT>username = f'<STR_LIT>'<EOL><DEDENT>try:<EOL><INDENT>client.login(username, password, sync=False)<EOL>prev_sync_limit = client.set_sync_limit(<NUM_LIT:0>)<EOL>client._sync() <EOL>client.set_sync_limit(prev_sync_limit)<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>homeserver=server_name,<EOL>server_url=server_url,<EOL>username=username,<EOL>)<EOL>break<EOL><DEDENT>except MatrixRequestError as ex:<EOL><INDENT>if ex.code != <NUM_LIT>:<EOL><INDENT>raise<EOL><DEDENT>log.debug(<EOL>'<STR_LIT>',<EOL>homeserver=server_name,<EOL>server_url=server_url,<EOL>username=username,<EOL>)<EOL>try:<EOL><INDENT>client.register_with_password(username, password)<EOL>log.debug(<EOL>'<STR_LIT>',<EOL>homeserver=server_name,<EOL>server_url=server_url,<EOL>username=username,<EOL>)<EOL>break<EOL><DEDENT>except MatrixRequestError as ex:<EOL><INDENT>if ex.code != <NUM_LIT>:<EOL><INDENT>raise<EOL><DEDENT>log.debug('<STR_LIT>')<EOL>continue<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>name = encode_hex(signer.sign(client.user_id.encode()))<EOL>user = client.get_user(client.user_id)<EOL>user.set_display_name(name)<EOL>return user<EOL>
|
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 of the server hostname, verified by the server to prevent account
creation spam
- Displayname currently is the signature of the whole user_id (including homeserver), to be
verified by other peers. May include in the future other metadata such as protocol version
Params:
client: GMatrixClient instance configured with desired homeserver
signer: raiden.utils.signer.Signer instance for signing password and displayname
prev_user_id: (optional) previous persisted client.user_id. Must match signer's account
prev_access_token: (optional) previous persistend client.access_token for prev_user_id
Returns:
Own matrix_client.User
|
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>signature=decode_hex(displayname),<EOL>)<EOL>if not (address and recovered and recovered == address):<EOL><INDENT>return None<EOL><DEDENT><DEDENT>except (<EOL>DecodeError,<EOL>TypeError,<EOL>InvalidSignature,<EOL>MatrixRequestError,<EOL>json.decoder.JSONDecodeError,<EOL>):<EOL><INDENT>return None<EOL><DEDENT>return address<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_error=False) <EOL>sorted_servers: List[Tuple[str, float]] = sorted(<EOL>(job.value for job in get_rtt_jobs if job.value[<NUM_LIT:1>] is not None),<EOL>key=itemgetter(<NUM_LIT:1>),<EOL>)<EOL>log.debug('<STR_LIT>', rtt_times=sorted_servers)<EOL>return sorted_servers<EOL>
|
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><INDENT>raise TransportError('<STR_LIT>')<EOL><DEDENT>last_ex = None<EOL>for server_url in sorted_servers:<EOL><INDENT>server_url: str = server_url<EOL>client = GMatrixClient(server_url, *args, **kwargs)<EOL>try:<EOL><INDENT>client.api._send('<STR_LIT:GET>', '<STR_LIT>', api_path='<STR_LIT>')<EOL><DEDENT>except MatrixError as ex:<EOL><INDENT>log.warning('<STR_LIT>', server_url=server_url, _exception=ex)<EOL>last_ex = ex<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TransportError(<EOL>'<STR_LIT>',<EOL>) from last_ex<EOL><DEDENT>return client<EOL>
|
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 servers
|
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 id for that room, as raiden rooms are per-chain specific
*suffixes: one or more suffixes for the name
Returns:
Qualified full room name. e.g.:
make_room_alias(3, 'discovery') == 'raiden_ropsten_discovery'
|
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><DEDENT>new_address_reachability = USER_PRESENCE_TO_ADDRESS_REACHABILITY[new_presence]<EOL>if new_address_reachability == self._address_to_reachability.get(address):<EOL><INDENT>return<EOL><DEDENT>log.debug(<EOL>'<STR_LIT>',<EOL>current_user=self._user_id,<EOL>address=to_normalized_address(address),<EOL>prev_state=self._address_to_reachability.get(address),<EOL>state=new_address_reachability,<EOL>)<EOL>self._address_to_reachability[address] = new_address_reachability<EOL>self._address_reachability_changed_callback(address, new_address_reachability)<EOL>
|
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>address = self._validate_userid_signature(user)<EOL>if not address:<EOL><INDENT>return<EOL><DEDENT>if not self.is_address_known(address):<EOL><INDENT>return<EOL><DEDENT>self.add_userid_for_address(address, user_id)<EOL>new_state = UserPresence(event['<STR_LIT:content>']['<STR_LIT>'])<EOL>if new_state == self._userid_to_presence.get(user_id):<EOL><INDENT>return<EOL><DEDENT>self._userid_to_presence[user_id] = new_state<EOL>self.refresh_address_presence(address)<EOL>if self._user_presence_changed_callback:<EOL><INDENT>self._user_presence_changed_callback(user, new_state)<EOL><DEDENT>
|
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 = message_type(data)<EOL><DEDENT>except ValueError:<EOL><INDENT>log.error('<STR_LIT>')<EOL>return None<EOL><DEDENT>return message<EOL>
|
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><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if any(len(field.name) < <NUM_LIT:0> for field in fields):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>names_fields = {<EOL>field.name: field<EOL>for field in fields<EOL>}<EOL>if '<STR_LIT:data>' in names_fields:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if any(count > <NUM_LIT:1> for count in Counter(field.name for field in fields).values()):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>fields_format = '<STR_LIT:>>' + '<STR_LIT>'.join(field.format_string for field in fields_spec)<EOL>size = sum(field.size_bytes for field in fields_spec)<EOL>names_slices = compute_slices(fields_spec)<EOL>sorted_names = sorted(names_fields.keys())<EOL>@staticmethod<EOL>def get_bytes_from(buffer_, name):<EOL><INDENT>slice_ = names_slices[name]<EOL>return buffer_[slice_]<EOL><DEDENT>def __init__(self, data):<EOL><INDENT>if len(data) < size:<EOL><INDENT>raise InvalidProtocolMessage(<EOL>'<STR_LIT>'.format(size),<EOL>)<EOL><DEDENT>object.__setattr__(self, '<STR_LIT:data>', data)<EOL><DEDENT>def __getattribute__(self, name):<EOL><INDENT>if name in names_slices:<EOL><INDENT>slice_ = names_slices[name]<EOL>field = names_fields[name]<EOL>data = object.__getattribute__(self, '<STR_LIT:data>')<EOL>value = data[slice_]<EOL>if field.encoder:<EOL><INDENT>value = field.encoder.decode(value)<EOL><DEDENT>return value<EOL><DEDENT>if name == '<STR_LIT:data>':<EOL><INDENT>return object.__getattribute__(self, '<STR_LIT:data>')<EOL><DEDENT>raise AttributeError<EOL><DEDENT>def __setattr__(self, name, value):<EOL><INDENT>if name in names_slices:<EOL><INDENT>slice_ = names_slices[name]<EOL>field = names_fields[name]<EOL>if field.encoder:<EOL><INDENT>field.encoder.validate(value)<EOL>value = field.encoder.encode(value, field.size_bytes)<EOL><DEDENT>length = len(value)<EOL>if length > field.size_bytes:<EOL><INDENT>msg = '<STR_LIT>'.format(<EOL>length=length,<EOL>attr=name,<EOL>)<EOL>raise ValueError(msg)<EOL><DEDENT>elif length < field.size_bytes:<EOL><INDENT>pad_size = field.size_bytes - length<EOL>pad_value = b'<STR_LIT:\x00>' * pad_size<EOL>value = pad_value + value<EOL><DEDENT>data = object.__getattribute__(self, '<STR_LIT:data>')<EOL>if isinstance(value, str):<EOL><INDENT>value = value.encode()<EOL><DEDENT>data[slice_] = value<EOL><DEDENT>else:<EOL><INDENT>super(self.__class__, self).__setattr__(name, value)<EOL><DEDENT><DEDENT>def __repr__(self):<EOL><INDENT>return '<STR_LIT>'.format(buffer_name)<EOL><DEDENT>def __len__(self):<EOL><INDENT>return size<EOL><DEDENT>def __dir__(self):<EOL><INDENT>return sorted_names<EOL><DEDENT>attributes = {<EOL>'<STR_LIT>': __init__,<EOL>'<STR_LIT>': ('<STR_LIT:data>',),<EOL>'<STR_LIT>': __getattribute__,<EOL>'<STR_LIT>': __setattr__,<EOL>'<STR_LIT>': __repr__,<EOL>'<STR_LIT>': __len__,<EOL>'<STR_LIT>': __dir__,<EOL>'<STR_LIT>': fields_spec,<EOL>'<STR_LIT>': fields_format,<EOL>'<STR_LIT:size>': size,<EOL>'<STR_LIT>': get_bytes_from,<EOL>}<EOL>return type(buffer_name, (), attributes)<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_hex(self.signature),<EOL>'<STR_LIT>': self.chain_id,<EOL>}<EOL>
|
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_amount),<EOL>'<STR_LIT>': encode_hex(self.non_closing_signature),<EOL>'<STR_LIT>': encode_hex(self.reward_proof_signature),<EOL>}<EOL>
|
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.balance_proof.nonce,<EOL>)<EOL>return packed<EOL>
|
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_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>)<EOL>blinded_data = pack_balance_proof_update(<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_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>partner_signature=self.balance_proof.signature,<EOL>)<EOL>reward_proof_data = 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.balance_proof.nonce,<EOL>)<EOL>return (<EOL>recover(balance_proof_data, self.balance_proof.signature) == partner_address and<EOL>recover(blinded_data, self.non_closing_signature) == requesting_address and<EOL>recover(reward_proof_data, self.reward_proof_signature) == requesting_address<EOL>)<EOL>
|
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_LIT>'))<EOL>if '<STR_LIT>' not in crypto:<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT>' not in crypto:<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT>' not in crypto:<EOL><INDENT>return False<EOL><DEDENT>if '<STR_LIT>' not in crypto:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
|
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
Returns:
`True` if the data appears to be valid, otherwise `False`
|
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.privkey<EOL>
|
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 not then the
user is interactively queried for one.
Returns
The private key associated with the address
|
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>pass<EOL><DEDENT>if password is not None:<EOL><INDENT>self.unlock(password)<EOL><DEDENT>
|
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.