id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
235,600 | raiden-network/raiden | raiden/transfer/architecture.py | StateManager.dispatch | def dispatch(self, state_change: StateChange) -> List[Event]:
""" Apply the `state_change` in the current machine and return the
resulting events.
Args:
state_change: An object representation of a state
change.
Return:
A list of events produced by the state transition.
It's the upper layer's responsibility to decided how to handle
these events.
"""
assert isinstance(state_change, StateChange)
# the state objects must be treated as immutable, so make a copy of the
# current state and pass the copy to the state machine to be modified.
next_state = deepcopy(self.current_state)
# update the current state by applying the change
iteration = self.state_transition(
next_state,
state_change,
)
assert isinstance(iteration, TransitionResult)
self.current_state = iteration.new_state
events = iteration.events
assert isinstance(self.current_state, (State, type(None)))
assert all(isinstance(e, Event) for e in events)
return events | python | def dispatch(self, state_change: StateChange) -> List[Event]:
assert isinstance(state_change, StateChange)
# the state objects must be treated as immutable, so make a copy of the
# current state and pass the copy to the state machine to be modified.
next_state = deepcopy(self.current_state)
# update the current state by applying the change
iteration = self.state_transition(
next_state,
state_change,
)
assert isinstance(iteration, TransitionResult)
self.current_state = iteration.new_state
events = iteration.events
assert isinstance(self.current_state, (State, type(None)))
assert all(isinstance(e, Event) for e in events)
return events | [
"def",
"dispatch",
"(",
"self",
",",
"state_change",
":",
"StateChange",
")",
"->",
"List",
"[",
"Event",
"]",
":",
"assert",
"isinstance",
"(",
"state_change",
",",
"StateChange",
")",
"# the state objects must be treated as immutable, so make a copy of the",
"# curren... | Apply the `state_change` in the current machine and return the
resulting events.
Args:
state_change: An object representation of a state
change.
Return:
A list of events produced by the state transition.
It's the upper layer's responsibility to decided how to handle
these events. | [
"Apply",
"the",
"state_change",
"in",
"the",
"current",
"machine",
"and",
"return",
"the",
"resulting",
"events",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/architecture.py#L275-L308 |
235,601 | raiden-network/raiden | raiden/waiting.py | wait_for_newchannel | def wait_for_newchannel(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
retry_timeout: float,
) -> None:
"""Wait until the channel with partner_address is registered.
Note:
This does not time out, use gevent.Timeout.
"""
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
)
while channel_state is None:
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
) | python | def wait_for_newchannel(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
retry_timeout: float,
) -> None:
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
)
while channel_state is None:
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
) | [
"def",
"wait_for_newchannel",
"(",
"raiden",
":",
"'RaidenService'",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"partner_address",
":",
"Address",
",",
"retry_timeout",
":",
"float",
",",
")",
"->",
"None",
... | Wait until the channel with partner_address is registered.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"the",
"channel",
"with",
"partner_address",
"is",
"registered",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L41-L67 |
235,602 | raiden-network/raiden | raiden/waiting.py | wait_for_participant_newbalance | def wait_for_participant_newbalance(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None:
"""Wait until a given channels balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout.
"""
if target_address == raiden.address:
balance = lambda channel_state: channel_state.our_state.contract_balance
elif target_address == partner_address:
balance = lambda channel_state: channel_state.partner_state.contract_balance
else:
raise ValueError('target_address must be one of the channel participants')
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
)
while balance(channel_state) < target_balance:
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
) | python | def wait_for_participant_newbalance(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None:
if target_address == raiden.address:
balance = lambda channel_state: channel_state.our_state.contract_balance
elif target_address == partner_address:
balance = lambda channel_state: channel_state.partner_state.contract_balance
else:
raise ValueError('target_address must be one of the channel participants')
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
)
while balance(channel_state) < target_balance:
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
) | [
"def",
"wait_for_participant_newbalance",
"(",
"raiden",
":",
"'RaidenService'",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"partner_address",
":",
"Address",
",",
"target_address",
":",
"Address",
",",
"target_ba... | Wait until a given channels balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"a",
"given",
"channels",
"balance",
"exceeds",
"the",
"target",
"balance",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L70-L105 |
235,603 | raiden-network/raiden | raiden/waiting.py | wait_for_payment_balance | def wait_for_payment_balance(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None:
"""Wait until a given channel's balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout.
"""
def get_balance(end_state):
if end_state.balance_proof:
return end_state.balance_proof.transferred_amount
else:
return 0
if target_address == raiden.address:
balance = lambda channel_state: get_balance(channel_state.partner_state)
elif target_address == partner_address:
balance = lambda channel_state: get_balance(channel_state.our_state)
else:
raise ValueError('target_address must be one of the channel participants')
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
)
while balance(channel_state) < target_balance:
log.critical('wait', b=balance(channel_state), t=target_balance)
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
) | python | def wait_for_payment_balance(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
partner_address: Address,
target_address: Address,
target_balance: TokenAmount,
retry_timeout: float,
) -> None:
def get_balance(end_state):
if end_state.balance_proof:
return end_state.balance_proof.transferred_amount
else:
return 0
if target_address == raiden.address:
balance = lambda channel_state: get_balance(channel_state.partner_state)
elif target_address == partner_address:
balance = lambda channel_state: get_balance(channel_state.our_state)
else:
raise ValueError('target_address must be one of the channel participants')
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
)
while balance(channel_state) < target_balance:
log.critical('wait', b=balance(channel_state), t=target_balance)
gevent.sleep(retry_timeout)
channel_state = views.get_channelstate_for(
views.state_from_raiden(raiden),
payment_network_id,
token_address,
partner_address,
) | [
"def",
"wait_for_payment_balance",
"(",
"raiden",
":",
"'RaidenService'",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"partner_address",
":",
"Address",
",",
"target_address",
":",
"Address",
",",
"target_balance",... | Wait until a given channel's balance exceeds the target balance.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"a",
"given",
"channel",
"s",
"balance",
"exceeds",
"the",
"target",
"balance",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L108-L150 |
235,604 | raiden-network/raiden | raiden/waiting.py | wait_for_channel_in_states | def wait_for_channel_in_states(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
target_states: Sequence[str],
) -> None:
"""Wait until all channels are in `target_states`.
Raises:
ValueError: If the token_address is not registered in the
payment_network.
Note:
This does not time out, use gevent.Timeout.
"""
chain_state = views.state_from_raiden(raiden)
token_network = views.get_token_network_by_token_address(
chain_state=chain_state,
payment_network_id=payment_network_id,
token_address=token_address,
)
if token_network is None:
raise ValueError(
f'The token {token_address} is not registered on the network {payment_network_id}.',
)
token_network_address = token_network.address
list_cannonical_ids = [
CanonicalIdentifier(
chain_identifier=chain_state.chain_id,
token_network_address=token_network_address,
channel_identifier=channel_identifier,
)
for channel_identifier in channel_ids
]
while list_cannonical_ids:
canonical_id = list_cannonical_ids[-1]
chain_state = views.state_from_raiden(raiden)
channel_state = views.get_channelstate_by_canonical_identifier(
chain_state=chain_state,
canonical_identifier=canonical_id,
)
channel_is_settled = (
channel_state is None or
channel.get_status(channel_state) in target_states
)
if channel_is_settled:
list_cannonical_ids.pop()
else:
gevent.sleep(retry_timeout) | python | def wait_for_channel_in_states(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
target_states: Sequence[str],
) -> None:
chain_state = views.state_from_raiden(raiden)
token_network = views.get_token_network_by_token_address(
chain_state=chain_state,
payment_network_id=payment_network_id,
token_address=token_address,
)
if token_network is None:
raise ValueError(
f'The token {token_address} is not registered on the network {payment_network_id}.',
)
token_network_address = token_network.address
list_cannonical_ids = [
CanonicalIdentifier(
chain_identifier=chain_state.chain_id,
token_network_address=token_network_address,
channel_identifier=channel_identifier,
)
for channel_identifier in channel_ids
]
while list_cannonical_ids:
canonical_id = list_cannonical_ids[-1]
chain_state = views.state_from_raiden(raiden)
channel_state = views.get_channelstate_by_canonical_identifier(
chain_state=chain_state,
canonical_identifier=canonical_id,
)
channel_is_settled = (
channel_state is None or
channel.get_status(channel_state) in target_states
)
if channel_is_settled:
list_cannonical_ids.pop()
else:
gevent.sleep(retry_timeout) | [
"def",
"wait_for_channel_in_states",
"(",
"raiden",
":",
"'RaidenService'",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"channel_ids",
":",
"List",
"[",
"ChannelID",
"]",
",",
"retry_timeout",
":",
"float",
","... | Wait until all channels are in `target_states`.
Raises:
ValueError: If the token_address is not registered in the
payment_network.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"all",
"channels",
"are",
"in",
"target_states",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L153-L210 |
235,605 | raiden-network/raiden | raiden/waiting.py | wait_for_close | def wait_for_close(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
) -> None:
"""Wait until all channels are closed.
Note:
This does not time out, use gevent.Timeout.
"""
return wait_for_channel_in_states(
raiden=raiden,
payment_network_id=payment_network_id,
token_address=token_address,
channel_ids=channel_ids,
retry_timeout=retry_timeout,
target_states=CHANNEL_AFTER_CLOSE_STATES,
) | python | def wait_for_close(
raiden: 'RaidenService',
payment_network_id: PaymentNetworkID,
token_address: TokenAddress,
channel_ids: List[ChannelID],
retry_timeout: float,
) -> None:
return wait_for_channel_in_states(
raiden=raiden,
payment_network_id=payment_network_id,
token_address=token_address,
channel_ids=channel_ids,
retry_timeout=retry_timeout,
target_states=CHANNEL_AFTER_CLOSE_STATES,
) | [
"def",
"wait_for_close",
"(",
"raiden",
":",
"'RaidenService'",
",",
"payment_network_id",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"channel_ids",
":",
"List",
"[",
"ChannelID",
"]",
",",
"retry_timeout",
":",
"float",
",",
")",
"... | Wait until all channels are closed.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"all",
"channels",
"are",
"closed",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L213-L232 |
235,606 | raiden-network/raiden | raiden/waiting.py | wait_for_healthy | def wait_for_healthy(
raiden: 'RaidenService',
node_address: Address,
retry_timeout: float,
) -> None:
"""Wait until `node_address` becomes healthy.
Note:
This does not time out, use gevent.Timeout.
"""
network_statuses = views.get_networkstatuses(
views.state_from_raiden(raiden),
)
while network_statuses.get(node_address) != NODE_NETWORK_REACHABLE:
gevent.sleep(retry_timeout)
network_statuses = views.get_networkstatuses(
views.state_from_raiden(raiden),
) | python | def wait_for_healthy(
raiden: 'RaidenService',
node_address: Address,
retry_timeout: float,
) -> None:
network_statuses = views.get_networkstatuses(
views.state_from_raiden(raiden),
)
while network_statuses.get(node_address) != NODE_NETWORK_REACHABLE:
gevent.sleep(retry_timeout)
network_statuses = views.get_networkstatuses(
views.state_from_raiden(raiden),
) | [
"def",
"wait_for_healthy",
"(",
"raiden",
":",
"'RaidenService'",
",",
"node_address",
":",
"Address",
",",
"retry_timeout",
":",
"float",
",",
")",
"->",
"None",
":",
"network_statuses",
"=",
"views",
".",
"get_networkstatuses",
"(",
"views",
".",
"state_from_r... | Wait until `node_address` becomes healthy.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"node_address",
"becomes",
"healthy",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L306-L324 |
235,607 | raiden-network/raiden | raiden/waiting.py | wait_for_transfer_success | def wait_for_transfer_success(
raiden: 'RaidenService',
payment_identifier: PaymentID,
amount: PaymentAmount,
retry_timeout: float,
) -> None:
"""Wait until a transfer with a specific identifier and amount
is seen in the WAL.
Note:
This does not time out, use gevent.Timeout.
"""
found = False
while not found:
state_events = raiden.wal.storage.get_events()
for event in state_events:
found = (
isinstance(event, EventPaymentReceivedSuccess) and
event.identifier == payment_identifier and
event.amount == amount
)
if found:
break
gevent.sleep(retry_timeout) | python | def wait_for_transfer_success(
raiden: 'RaidenService',
payment_identifier: PaymentID,
amount: PaymentAmount,
retry_timeout: float,
) -> None:
found = False
while not found:
state_events = raiden.wal.storage.get_events()
for event in state_events:
found = (
isinstance(event, EventPaymentReceivedSuccess) and
event.identifier == payment_identifier and
event.amount == amount
)
if found:
break
gevent.sleep(retry_timeout) | [
"def",
"wait_for_transfer_success",
"(",
"raiden",
":",
"'RaidenService'",
",",
"payment_identifier",
":",
"PaymentID",
",",
"amount",
":",
"PaymentAmount",
",",
"retry_timeout",
":",
"float",
",",
")",
"->",
"None",
":",
"found",
"=",
"False",
"while",
"not",
... | Wait until a transfer with a specific identifier and amount
is seen in the WAL.
Note:
This does not time out, use gevent.Timeout. | [
"Wait",
"until",
"a",
"transfer",
"with",
"a",
"specific",
"identifier",
"and",
"amount",
"is",
"seen",
"in",
"the",
"WAL",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/waiting.py#L327-L351 |
235,608 | raiden-network/raiden | raiden/utils/echo_node.py | EchoNode.poll_all_received_events | def poll_all_received_events(self):
""" This will be triggered once for each `echo_node_alarm_callback`.
It polls all channels for `EventPaymentReceivedSuccess` events,
adds all new events to the `self.received_transfers` queue and
respawns `self.echo_node_worker`, if it died. """
locked = False
try:
with Timeout(10):
locked = self.lock.acquire(blocking=False)
if not locked:
return
else:
received_transfers = self.api.get_raiden_events_payment_history(
token_address=self.token_address,
offset=self.last_poll_offset,
)
# received transfer is a tuple of (block_number, event)
received_transfers = [
event
for event in received_transfers
if type(event) == EventPaymentReceivedSuccess
]
for event in received_transfers:
transfer = copy.deepcopy(event)
self.received_transfers.put(transfer)
# set last_poll_block after events are enqueued (timeout safe)
if received_transfers:
self.last_poll_offset += len(received_transfers)
if not self.echo_worker_greenlet.started:
log.debug(
'restarting echo_worker_greenlet',
dead=self.echo_worker_greenlet.dead,
successful=self.echo_worker_greenlet.successful(),
exception=self.echo_worker_greenlet.exception,
)
self.echo_worker_greenlet = gevent.spawn(self.echo_worker)
except Timeout:
log.info('timeout while polling for events')
finally:
if locked:
self.lock.release() | python | def poll_all_received_events(self):
locked = False
try:
with Timeout(10):
locked = self.lock.acquire(blocking=False)
if not locked:
return
else:
received_transfers = self.api.get_raiden_events_payment_history(
token_address=self.token_address,
offset=self.last_poll_offset,
)
# received transfer is a tuple of (block_number, event)
received_transfers = [
event
for event in received_transfers
if type(event) == EventPaymentReceivedSuccess
]
for event in received_transfers:
transfer = copy.deepcopy(event)
self.received_transfers.put(transfer)
# set last_poll_block after events are enqueued (timeout safe)
if received_transfers:
self.last_poll_offset += len(received_transfers)
if not self.echo_worker_greenlet.started:
log.debug(
'restarting echo_worker_greenlet',
dead=self.echo_worker_greenlet.dead,
successful=self.echo_worker_greenlet.successful(),
exception=self.echo_worker_greenlet.exception,
)
self.echo_worker_greenlet = gevent.spawn(self.echo_worker)
except Timeout:
log.info('timeout while polling for events')
finally:
if locked:
self.lock.release() | [
"def",
"poll_all_received_events",
"(",
"self",
")",
":",
"locked",
"=",
"False",
"try",
":",
"with",
"Timeout",
"(",
"10",
")",
":",
"locked",
"=",
"self",
".",
"lock",
".",
"acquire",
"(",
"blocking",
"=",
"False",
")",
"if",
"not",
"locked",
":",
... | This will be triggered once for each `echo_node_alarm_callback`.
It polls all channels for `EventPaymentReceivedSuccess` events,
adds all new events to the `self.received_transfers` queue and
respawns `self.echo_node_worker`, if it died. | [
"This",
"will",
"be",
"triggered",
"once",
"for",
"each",
"echo_node_alarm_callback",
".",
"It",
"polls",
"all",
"channels",
"for",
"EventPaymentReceivedSuccess",
"events",
"adds",
"all",
"new",
"events",
"to",
"the",
"self",
".",
"received_transfers",
"queue",
"a... | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/echo_node.py#L87-L132 |
235,609 | raiden-network/raiden | raiden/utils/echo_node.py | EchoNode.echo_worker | def echo_worker(self):
""" The `echo_worker` works through the `self.received_transfers` queue and spawns
`self.on_transfer` greenlets for all not-yet-seen transfers. """
log.debug('echo worker', qsize=self.received_transfers.qsize())
while self.stop_signal is None:
if self.received_transfers.qsize() > 0:
transfer = self.received_transfers.get()
if transfer in self.seen_transfers:
log.debug(
'duplicate transfer ignored',
initiator=pex(transfer.initiator),
amount=transfer.amount,
identifier=transfer.identifier,
)
else:
self.seen_transfers.append(transfer)
self.greenlets.add(gevent.spawn(self.on_transfer, transfer))
else:
gevent.sleep(.5) | python | def echo_worker(self):
log.debug('echo worker', qsize=self.received_transfers.qsize())
while self.stop_signal is None:
if self.received_transfers.qsize() > 0:
transfer = self.received_transfers.get()
if transfer in self.seen_transfers:
log.debug(
'duplicate transfer ignored',
initiator=pex(transfer.initiator),
amount=transfer.amount,
identifier=transfer.identifier,
)
else:
self.seen_transfers.append(transfer)
self.greenlets.add(gevent.spawn(self.on_transfer, transfer))
else:
gevent.sleep(.5) | [
"def",
"echo_worker",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'echo worker'",
",",
"qsize",
"=",
"self",
".",
"received_transfers",
".",
"qsize",
"(",
")",
")",
"while",
"self",
".",
"stop_signal",
"is",
"None",
":",
"if",
"self",
".",
"recei... | The `echo_worker` works through the `self.received_transfers` queue and spawns
`self.on_transfer` greenlets for all not-yet-seen transfers. | [
"The",
"echo_worker",
"works",
"through",
"the",
"self",
".",
"received_transfers",
"queue",
"and",
"spawns",
"self",
".",
"on_transfer",
"greenlets",
"for",
"all",
"not",
"-",
"yet",
"-",
"seen",
"transfers",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/echo_node.py#L134-L152 |
235,610 | raiden-network/raiden | raiden/utils/runnable.py | Runnable.start | def start(self):
""" Synchronously start task
Reimplements in children an call super().start() at end to start _run()
Start-time exceptions may be raised
"""
if self.greenlet:
raise RuntimeError(f'Greenlet {self.greenlet!r} already started')
pristine = (
not self.greenlet.dead and
tuple(self.greenlet.args) == tuple(self.args) and
self.greenlet.kwargs == self.kwargs
)
if not pristine:
self.greenlet = Greenlet(self._run, *self.args, **self.kwargs)
self.greenlet.name = f'{self.__class__.__name__}|{self.greenlet.name}'
self.greenlet.start() | python | def start(self):
if self.greenlet:
raise RuntimeError(f'Greenlet {self.greenlet!r} already started')
pristine = (
not self.greenlet.dead and
tuple(self.greenlet.args) == tuple(self.args) and
self.greenlet.kwargs == self.kwargs
)
if not pristine:
self.greenlet = Greenlet(self._run, *self.args, **self.kwargs)
self.greenlet.name = f'{self.__class__.__name__}|{self.greenlet.name}'
self.greenlet.start() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"greenlet",
":",
"raise",
"RuntimeError",
"(",
"f'Greenlet {self.greenlet!r} already started'",
")",
"pristine",
"=",
"(",
"not",
"self",
".",
"greenlet",
".",
"dead",
"and",
"tuple",
"(",
"self",
"."... | Synchronously start task
Reimplements in children an call super().start() at end to start _run()
Start-time exceptions may be raised | [
"Synchronously",
"start",
"task"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/runnable.py#L26-L42 |
235,611 | raiden-network/raiden | raiden/utils/runnable.py | Runnable.on_error | def on_error(self, subtask: Greenlet):
""" Default callback for substasks link_exception
Default callback re-raises the exception inside _run() """
log.error(
'Runnable subtask died!',
this=self,
running=bool(self),
subtask=subtask,
exc=subtask.exception,
)
if not self.greenlet:
return
self.greenlet.kill(subtask.exception) | python | def on_error(self, subtask: Greenlet):
log.error(
'Runnable subtask died!',
this=self,
running=bool(self),
subtask=subtask,
exc=subtask.exception,
)
if not self.greenlet:
return
self.greenlet.kill(subtask.exception) | [
"def",
"on_error",
"(",
"self",
",",
"subtask",
":",
"Greenlet",
")",
":",
"log",
".",
"error",
"(",
"'Runnable subtask died!'",
",",
"this",
"=",
"self",
",",
"running",
"=",
"bool",
"(",
"self",
")",
",",
"subtask",
"=",
"subtask",
",",
"exc",
"=",
... | Default callback for substasks link_exception
Default callback re-raises the exception inside _run() | [
"Default",
"callback",
"for",
"substasks",
"link_exception"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/runnable.py#L59-L72 |
235,612 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | join_global_room | def join_global_room(client: GMatrixClient, name: str, servers: Sequence[str] = ()) -> Room:
"""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
"""
our_server_name = urlparse(client.api.base_url).netloc
assert our_server_name, 'Invalid client\'s homeserver url'
servers = [our_server_name] + [ # client's own server first
urlparse(s).netloc
for s in servers
if urlparse(s).netloc not in {None, '', our_server_name}
]
our_server_global_room_alias_full = f'#{name}:{servers[0]}'
# try joining a global room on any of the available servers, starting with ours
for server in servers:
global_room_alias_full = f'#{name}:{server}'
try:
global_room = client.join_room(global_room_alias_full)
except MatrixRequestError as ex:
if ex.code not in (403, 404, 500):
raise
log.debug(
'Could not join global room',
room_alias_full=global_room_alias_full,
_exception=ex,
)
else:
if our_server_global_room_alias_full not in global_room.aliases:
# we managed to join a global room, but it's not aliased in our server
global_room.add_room_alias(our_server_global_room_alias_full)
global_room.aliases.append(our_server_global_room_alias_full)
break
else:
log.debug('Could not join any global room, trying to create one')
for _ in range(JOIN_RETRIES):
try:
global_room = client.create_room(name, is_public=True)
except MatrixRequestError as ex:
if ex.code not in (400, 409):
raise
try:
global_room = client.join_room(
our_server_global_room_alias_full,
)
except MatrixRequestError as ex:
if ex.code not in (404, 403):
raise
else:
break
else:
break
else:
raise TransportError('Could neither join nor create a global room')
return global_room | python | def join_global_room(client: GMatrixClient, name: str, servers: Sequence[str] = ()) -> Room:
our_server_name = urlparse(client.api.base_url).netloc
assert our_server_name, 'Invalid client\'s homeserver url'
servers = [our_server_name] + [ # client's own server first
urlparse(s).netloc
for s in servers
if urlparse(s).netloc not in {None, '', our_server_name}
]
our_server_global_room_alias_full = f'#{name}:{servers[0]}'
# try joining a global room on any of the available servers, starting with ours
for server in servers:
global_room_alias_full = f'#{name}:{server}'
try:
global_room = client.join_room(global_room_alias_full)
except MatrixRequestError as ex:
if ex.code not in (403, 404, 500):
raise
log.debug(
'Could not join global room',
room_alias_full=global_room_alias_full,
_exception=ex,
)
else:
if our_server_global_room_alias_full not in global_room.aliases:
# we managed to join a global room, but it's not aliased in our server
global_room.add_room_alias(our_server_global_room_alias_full)
global_room.aliases.append(our_server_global_room_alias_full)
break
else:
log.debug('Could not join any global room, trying to create one')
for _ in range(JOIN_RETRIES):
try:
global_room = client.create_room(name, is_public=True)
except MatrixRequestError as ex:
if ex.code not in (400, 409):
raise
try:
global_room = client.join_room(
our_server_global_room_alias_full,
)
except MatrixRequestError as ex:
if ex.code not in (404, 403):
raise
else:
break
else:
break
else:
raise TransportError('Could neither join nor create a global room')
return global_room | [
"def",
"join_global_room",
"(",
"client",
":",
"GMatrixClient",
",",
"name",
":",
"str",
",",
"servers",
":",
"Sequence",
"[",
"str",
"]",
"=",
"(",
")",
")",
"->",
"Room",
":",
"our_server_name",
"=",
"urlparse",
"(",
"client",
".",
"api",
".",
"base_... | 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 | [
"Join",
"or",
"create",
"a",
"global",
"public",
"room",
"with",
"given",
"name"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L254-L319 |
235,613 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | login_or_register | def login_or_register(
client: GMatrixClient,
signer: Signer,
prev_user_id: str = None,
prev_access_token: str = None,
) -> User:
"""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
"""
server_url = client.api.base_url
server_name = urlparse(server_url).netloc
base_username = to_normalized_address(signer.address)
_match_user = re.match(
f'^@{re.escape(base_username)}.*:{re.escape(server_name)}$',
prev_user_id or '',
)
if _match_user: # same user as before
log.debug('Trying previous user login', user_id=prev_user_id)
client.set_access_token(user_id=prev_user_id, token=prev_access_token)
try:
client.api.get_devices()
except MatrixRequestError as ex:
log.debug(
'Couldn\'t use previous login credentials, discarding',
prev_user_id=prev_user_id,
_exception=ex,
)
else:
prev_sync_limit = client.set_sync_limit(0)
client._sync() # initial_sync
client.set_sync_limit(prev_sync_limit)
log.debug('Success. Valid previous credentials', user_id=prev_user_id)
return client.get_user(client.user_id)
elif prev_user_id:
log.debug(
'Different server or account, discarding',
prev_user_id=prev_user_id,
current_address=base_username,
current_server=server_name,
)
# password is signed server address
password = encode_hex(signer.sign(server_name.encode()))
rand = None
# try login and register on first 5 possible accounts
for i in range(JOIN_RETRIES):
username = base_username
if i:
if not rand:
rand = Random() # deterministic, random secret for username suffixes
# initialize rand for seed (which requires a signature) only if/when needed
rand.seed(int.from_bytes(signer.sign(b'seed')[-32:], 'big'))
username = f'{username}.{rand.randint(0, 0xffffffff):08x}'
try:
client.login(username, password, sync=False)
prev_sync_limit = client.set_sync_limit(0)
client._sync() # when logging, do initial_sync with limit=0
client.set_sync_limit(prev_sync_limit)
log.debug(
'Login',
homeserver=server_name,
server_url=server_url,
username=username,
)
break
except MatrixRequestError as ex:
if ex.code != 403:
raise
log.debug(
'Could not login. Trying register',
homeserver=server_name,
server_url=server_url,
username=username,
)
try:
client.register_with_password(username, password)
log.debug(
'Register',
homeserver=server_name,
server_url=server_url,
username=username,
)
break
except MatrixRequestError as ex:
if ex.code != 400:
raise
log.debug('Username taken. Continuing')
continue
else:
raise ValueError('Could not register or login!')
name = encode_hex(signer.sign(client.user_id.encode()))
user = client.get_user(client.user_id)
user.set_display_name(name)
return user | python | def login_or_register(
client: GMatrixClient,
signer: Signer,
prev_user_id: str = None,
prev_access_token: str = None,
) -> User:
server_url = client.api.base_url
server_name = urlparse(server_url).netloc
base_username = to_normalized_address(signer.address)
_match_user = re.match(
f'^@{re.escape(base_username)}.*:{re.escape(server_name)}$',
prev_user_id or '',
)
if _match_user: # same user as before
log.debug('Trying previous user login', user_id=prev_user_id)
client.set_access_token(user_id=prev_user_id, token=prev_access_token)
try:
client.api.get_devices()
except MatrixRequestError as ex:
log.debug(
'Couldn\'t use previous login credentials, discarding',
prev_user_id=prev_user_id,
_exception=ex,
)
else:
prev_sync_limit = client.set_sync_limit(0)
client._sync() # initial_sync
client.set_sync_limit(prev_sync_limit)
log.debug('Success. Valid previous credentials', user_id=prev_user_id)
return client.get_user(client.user_id)
elif prev_user_id:
log.debug(
'Different server or account, discarding',
prev_user_id=prev_user_id,
current_address=base_username,
current_server=server_name,
)
# password is signed server address
password = encode_hex(signer.sign(server_name.encode()))
rand = None
# try login and register on first 5 possible accounts
for i in range(JOIN_RETRIES):
username = base_username
if i:
if not rand:
rand = Random() # deterministic, random secret for username suffixes
# initialize rand for seed (which requires a signature) only if/when needed
rand.seed(int.from_bytes(signer.sign(b'seed')[-32:], 'big'))
username = f'{username}.{rand.randint(0, 0xffffffff):08x}'
try:
client.login(username, password, sync=False)
prev_sync_limit = client.set_sync_limit(0)
client._sync() # when logging, do initial_sync with limit=0
client.set_sync_limit(prev_sync_limit)
log.debug(
'Login',
homeserver=server_name,
server_url=server_url,
username=username,
)
break
except MatrixRequestError as ex:
if ex.code != 403:
raise
log.debug(
'Could not login. Trying register',
homeserver=server_name,
server_url=server_url,
username=username,
)
try:
client.register_with_password(username, password)
log.debug(
'Register',
homeserver=server_name,
server_url=server_url,
username=username,
)
break
except MatrixRequestError as ex:
if ex.code != 400:
raise
log.debug('Username taken. Continuing')
continue
else:
raise ValueError('Could not register or login!')
name = encode_hex(signer.sign(client.user_id.encode()))
user = client.get_user(client.user_id)
user.set_display_name(name)
return user | [
"def",
"login_or_register",
"(",
"client",
":",
"GMatrixClient",
",",
"signer",
":",
"Signer",
",",
"prev_user_id",
":",
"str",
"=",
"None",
",",
"prev_access_token",
":",
"str",
"=",
"None",
",",
")",
"->",
"User",
":",
"server_url",
"=",
"client",
".",
... | 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 | [
"Login",
"to",
"a",
"Raiden",
"matrix",
"server",
"with",
"password",
"and",
"displayname",
"proof",
"-",
"of",
"-",
"keys"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L322-L434 |
235,614 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | validate_userid_signature | def validate_userid_signature(user: User) -> Optional[Address]:
""" Validate a userId format and signature on displayName, and return its address"""
# display_name should be an address in the USERID_RE format
match = USERID_RE.match(user.user_id)
if not match:
return None
encoded_address = match.group(1)
address: Address = to_canonical_address(encoded_address)
try:
displayname = user.get_display_name()
recovered = recover(
data=user.user_id.encode(),
signature=decode_hex(displayname),
)
if not (address and recovered and recovered == address):
return None
except (
DecodeError,
TypeError,
InvalidSignature,
MatrixRequestError,
json.decoder.JSONDecodeError,
):
return None
return address | python | def validate_userid_signature(user: User) -> Optional[Address]:
# display_name should be an address in the USERID_RE format
match = USERID_RE.match(user.user_id)
if not match:
return None
encoded_address = match.group(1)
address: Address = to_canonical_address(encoded_address)
try:
displayname = user.get_display_name()
recovered = recover(
data=user.user_id.encode(),
signature=decode_hex(displayname),
)
if not (address and recovered and recovered == address):
return None
except (
DecodeError,
TypeError,
InvalidSignature,
MatrixRequestError,
json.decoder.JSONDecodeError,
):
return None
return address | [
"def",
"validate_userid_signature",
"(",
"user",
":",
"User",
")",
"->",
"Optional",
"[",
"Address",
"]",
":",
"# display_name should be an address in the USERID_RE format",
"match",
"=",
"USERID_RE",
".",
"match",
"(",
"user",
".",
"user_id",
")",
"if",
"not",
"m... | Validate a userId format and signature on displayName, and return its address | [
"Validate",
"a",
"userId",
"format",
"and",
"signature",
"on",
"displayName",
"and",
"return",
"its",
"address"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L438-L464 |
235,615 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | sort_servers_closest | def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]:
"""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)
"""
if not {urlparse(url).scheme for url in servers}.issubset({'http', 'https'}):
raise TransportError('Invalid server urls')
get_rtt_jobs = set(
gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)
for server_url
in servers
)
# these tasks should never raise, returns None on errors
gevent.joinall(get_rtt_jobs, raise_error=False) # block and wait tasks
sorted_servers: List[Tuple[str, float]] = sorted(
(job.value for job in get_rtt_jobs if job.value[1] is not None),
key=itemgetter(1),
)
log.debug('Matrix homeserver RTT times', rtt_times=sorted_servers)
return sorted_servers | python | def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]:
if not {urlparse(url).scheme for url in servers}.issubset({'http', 'https'}):
raise TransportError('Invalid server urls')
get_rtt_jobs = set(
gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)
for server_url
in servers
)
# these tasks should never raise, returns None on errors
gevent.joinall(get_rtt_jobs, raise_error=False) # block and wait tasks
sorted_servers: List[Tuple[str, float]] = sorted(
(job.value for job in get_rtt_jobs if job.value[1] is not None),
key=itemgetter(1),
)
log.debug('Matrix homeserver RTT times', rtt_times=sorted_servers)
return sorted_servers | [
"def",
"sort_servers_closest",
"(",
"servers",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"Sequence",
"[",
"Tuple",
"[",
"str",
",",
"float",
"]",
"]",
":",
"if",
"not",
"{",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"for",
"url",
"in",
"servers"... | 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) | [
"Sorts",
"a",
"list",
"of",
"servers",
"by",
"http",
"round",
"-",
"trip",
"time"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L467-L491 |
235,616 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | make_client | def make_client(servers: Sequence[str], *args, **kwargs) -> GMatrixClient:
"""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
"""
if len(servers) > 1:
sorted_servers = [
server_url
for (server_url, _) in sort_servers_closest(servers)
]
log.info(
'Automatically selecting matrix homeserver based on RTT',
sorted_servers=sorted_servers,
)
elif len(servers) == 1:
sorted_servers = servers
else:
raise TransportError('No valid servers list given')
last_ex = None
for server_url in sorted_servers:
server_url: str = server_url
client = GMatrixClient(server_url, *args, **kwargs)
try:
client.api._send('GET', '/versions', api_path='/_matrix/client')
except MatrixError as ex:
log.warning('Selected server not usable', server_url=server_url, _exception=ex)
last_ex = ex
else:
break
else:
raise TransportError(
'Unable to find a reachable Matrix server. Please check your network connectivity.',
) from last_ex
return client | python | def make_client(servers: Sequence[str], *args, **kwargs) -> GMatrixClient:
if len(servers) > 1:
sorted_servers = [
server_url
for (server_url, _) in sort_servers_closest(servers)
]
log.info(
'Automatically selecting matrix homeserver based on RTT',
sorted_servers=sorted_servers,
)
elif len(servers) == 1:
sorted_servers = servers
else:
raise TransportError('No valid servers list given')
last_ex = None
for server_url in sorted_servers:
server_url: str = server_url
client = GMatrixClient(server_url, *args, **kwargs)
try:
client.api._send('GET', '/versions', api_path='/_matrix/client')
except MatrixError as ex:
log.warning('Selected server not usable', server_url=server_url, _exception=ex)
last_ex = ex
else:
break
else:
raise TransportError(
'Unable to find a reachable Matrix server. Please check your network connectivity.',
) from last_ex
return client | [
"def",
"make_client",
"(",
"servers",
":",
"Sequence",
"[",
"str",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"GMatrixClient",
":",
"if",
"len",
"(",
"servers",
")",
">",
"1",
":",
"sorted_servers",
"=",
"[",
"server_url",
"for",
"(",... | 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 | [
"Given",
"a",
"list",
"of",
"possible",
"servers",
"chooses",
"the",
"closest",
"available",
"and",
"create",
"a",
"GMatrixClient"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L494-L532 |
235,617 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.add_userid_for_address | def add_userid_for_address(self, address: Address, user_id: str):
""" Add a ``user_id`` for the given ``address``.
Implicitly adds the address if it was unknown before.
"""
self._address_to_userids[address].add(user_id) | python | def add_userid_for_address(self, address: Address, user_id: str):
self._address_to_userids[address].add(user_id) | [
"def",
"add_userid_for_address",
"(",
"self",
",",
"address",
":",
"Address",
",",
"user_id",
":",
"str",
")",
":",
"self",
".",
"_address_to_userids",
"[",
"address",
"]",
".",
"add",
"(",
"user_id",
")"
] | Add a ``user_id`` for the given ``address``.
Implicitly adds the address if it was unknown before. | [
"Add",
"a",
"user_id",
"for",
"the",
"given",
"address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L122-L127 |
235,618 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.add_userids_for_address | def add_userids_for_address(self, address: Address, user_ids: Iterable[str]):
""" Add multiple ``user_ids`` for the given ``address``.
Implicitly adds any addresses if they were unknown before.
"""
self._address_to_userids[address].update(user_ids) | python | def add_userids_for_address(self, address: Address, user_ids: Iterable[str]):
self._address_to_userids[address].update(user_ids) | [
"def",
"add_userids_for_address",
"(",
"self",
",",
"address",
":",
"Address",
",",
"user_ids",
":",
"Iterable",
"[",
"str",
"]",
")",
":",
"self",
".",
"_address_to_userids",
"[",
"address",
"]",
".",
"update",
"(",
"user_ids",
")"
] | Add multiple ``user_ids`` for the given ``address``.
Implicitly adds any addresses if they were unknown before. | [
"Add",
"multiple",
"user_ids",
"for",
"the",
"given",
"address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L129-L134 |
235,619 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.get_userids_for_address | def get_userids_for_address(self, address: Address) -> Set[str]:
""" Return all known user ids for the given ``address``. """
if not self.is_address_known(address):
return set()
return self._address_to_userids[address] | python | def get_userids_for_address(self, address: Address) -> Set[str]:
if not self.is_address_known(address):
return set()
return self._address_to_userids[address] | [
"def",
"get_userids_for_address",
"(",
"self",
",",
"address",
":",
"Address",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"if",
"not",
"self",
".",
"is_address_known",
"(",
"address",
")",
":",
"return",
"set",
"(",
")",
"return",
"self",
".",
"_address_to_... | Return all known user ids for the given ``address``. | [
"Return",
"all",
"known",
"user",
"ids",
"for",
"the",
"given",
"address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L136-L140 |
235,620 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.get_userid_presence | def get_userid_presence(self, user_id: str) -> UserPresence:
""" Return the current presence state of ``user_id``. """
return self._userid_to_presence.get(user_id, UserPresence.UNKNOWN) | python | def get_userid_presence(self, user_id: str) -> UserPresence:
return self._userid_to_presence.get(user_id, UserPresence.UNKNOWN) | [
"def",
"get_userid_presence",
"(",
"self",
",",
"user_id",
":",
"str",
")",
"->",
"UserPresence",
":",
"return",
"self",
".",
"_userid_to_presence",
".",
"get",
"(",
"user_id",
",",
"UserPresence",
".",
"UNKNOWN",
")"
] | Return the current presence state of ``user_id``. | [
"Return",
"the",
"current",
"presence",
"state",
"of",
"user_id",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L142-L144 |
235,621 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.get_address_reachability | def get_address_reachability(self, address: Address) -> AddressReachability:
""" Return the current reachability state for ``address``. """
return self._address_to_reachability.get(address, AddressReachability.UNKNOWN) | python | def get_address_reachability(self, address: Address) -> AddressReachability:
return self._address_to_reachability.get(address, AddressReachability.UNKNOWN) | [
"def",
"get_address_reachability",
"(",
"self",
",",
"address",
":",
"Address",
")",
"->",
"AddressReachability",
":",
"return",
"self",
".",
"_address_to_reachability",
".",
"get",
"(",
"address",
",",
"AddressReachability",
".",
"UNKNOWN",
")"
] | Return the current reachability state for ``address``. | [
"Return",
"the",
"current",
"reachability",
"state",
"for",
"address",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L146-L148 |
235,622 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.force_user_presence | def force_user_presence(self, user: User, presence: UserPresence):
""" 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.
"""
self._userid_to_presence[user.user_id] = presence | python | def force_user_presence(self, user: User, presence: UserPresence):
self._userid_to_presence[user.user_id] = presence | [
"def",
"force_user_presence",
"(",
"self",
",",
"user",
":",
"User",
",",
"presence",
":",
"UserPresence",
")",
":",
"self",
".",
"_userid_to_presence",
"[",
"user",
".",
"user_id",
"]",
"=",
"presence"
] | 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. | [
"Forcibly",
"set",
"the",
"user",
"presence",
"to",
"presence",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L150-L156 |
235,623 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager.refresh_address_presence | def refresh_address_presence(self, address):
"""
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.
"""
composite_presence = {
self._fetch_user_presence(uid)
for uid
in self._address_to_userids[address]
}
# Iterate over UserPresence in definition order (most to least online) and pick
# first matching state
new_presence = UserPresence.UNKNOWN
for presence in UserPresence.__members__.values():
if presence in composite_presence:
new_presence = presence
break
new_address_reachability = USER_PRESENCE_TO_ADDRESS_REACHABILITY[new_presence]
if new_address_reachability == self._address_to_reachability.get(address):
# Cached address reachability matches new state, do nothing
return
log.debug(
'Changing address presence state',
current_user=self._user_id,
address=to_normalized_address(address),
prev_state=self._address_to_reachability.get(address),
state=new_address_reachability,
)
self._address_to_reachability[address] = new_address_reachability
self._address_reachability_changed_callback(address, new_address_reachability) | python | def refresh_address_presence(self, address):
composite_presence = {
self._fetch_user_presence(uid)
for uid
in self._address_to_userids[address]
}
# Iterate over UserPresence in definition order (most to least online) and pick
# first matching state
new_presence = UserPresence.UNKNOWN
for presence in UserPresence.__members__.values():
if presence in composite_presence:
new_presence = presence
break
new_address_reachability = USER_PRESENCE_TO_ADDRESS_REACHABILITY[new_presence]
if new_address_reachability == self._address_to_reachability.get(address):
# Cached address reachability matches new state, do nothing
return
log.debug(
'Changing address presence state',
current_user=self._user_id,
address=to_normalized_address(address),
prev_state=self._address_to_reachability.get(address),
state=new_address_reachability,
)
self._address_to_reachability[address] = new_address_reachability
self._address_reachability_changed_callback(address, new_address_reachability) | [
"def",
"refresh_address_presence",
"(",
"self",
",",
"address",
")",
":",
"composite_presence",
"=",
"{",
"self",
".",
"_fetch_user_presence",
"(",
"uid",
")",
"for",
"uid",
"in",
"self",
".",
"_address_to_userids",
"[",
"address",
"]",
"}",
"# Iterate over User... | 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. | [
"Update",
"synthesized",
"address",
"presence",
"state",
"from",
"cached",
"user",
"presence",
"states",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L158-L194 |
235,624 | raiden-network/raiden | raiden/network/transport/matrix/utils.py | UserAddressManager._presence_listener | def _presence_listener(self, event: Dict[str, Any]):
"""
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.
"""
if self._stop_event.ready():
return
user_id = event['sender']
if event['type'] != 'm.presence' or user_id == self._user_id:
return
user = self._get_user(user_id)
user.displayname = event['content'].get('displayname') or user.displayname
address = self._validate_userid_signature(user)
if not address:
# Malformed address - skip
return
# not a user we've whitelisted, skip
if not self.is_address_known(address):
return
self.add_userid_for_address(address, user_id)
new_state = UserPresence(event['content']['presence'])
if new_state == self._userid_to_presence.get(user_id):
# Cached presence state matches, no action required
return
self._userid_to_presence[user_id] = new_state
self.refresh_address_presence(address)
if self._user_presence_changed_callback:
self._user_presence_changed_callback(user, new_state) | python | def _presence_listener(self, event: Dict[str, Any]):
if self._stop_event.ready():
return
user_id = event['sender']
if event['type'] != 'm.presence' or user_id == self._user_id:
return
user = self._get_user(user_id)
user.displayname = event['content'].get('displayname') or user.displayname
address = self._validate_userid_signature(user)
if not address:
# Malformed address - skip
return
# not a user we've whitelisted, skip
if not self.is_address_known(address):
return
self.add_userid_for_address(address, user_id)
new_state = UserPresence(event['content']['presence'])
if new_state == self._userid_to_presence.get(user_id):
# Cached presence state matches, no action required
return
self._userid_to_presence[user_id] = new_state
self.refresh_address_presence(address)
if self._user_presence_changed_callback:
self._user_presence_changed_callback(user, new_state) | [
"def",
"_presence_listener",
"(",
"self",
",",
"event",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"if",
"self",
".",
"_stop_event",
".",
"ready",
"(",
")",
":",
"return",
"user_id",
"=",
"event",
"[",
"'sender'",
"]",
"if",
"event",
"[",
... | 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. | [
"Update",
"cached",
"user",
"presence",
"state",
"from",
"Matrix",
"presence",
"events",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/utils.py#L196-L230 |
235,625 | raiden-network/raiden | raiden/tasks.py | check_version | def check_version(current_version: str):
""" Check periodically for a new release """
app_version = parse_version(current_version)
while True:
try:
_do_check_version(app_version)
except requests.exceptions.HTTPError as herr:
click.secho('Error while checking for version', fg='red')
print(herr)
except ValueError as verr:
click.secho('Error while checking the version', fg='red')
print(verr)
finally:
# repeat the process once every 3h
gevent.sleep(CHECK_VERSION_INTERVAL) | python | def check_version(current_version: str):
app_version = parse_version(current_version)
while True:
try:
_do_check_version(app_version)
except requests.exceptions.HTTPError as herr:
click.secho('Error while checking for version', fg='red')
print(herr)
except ValueError as verr:
click.secho('Error while checking the version', fg='red')
print(verr)
finally:
# repeat the process once every 3h
gevent.sleep(CHECK_VERSION_INTERVAL) | [
"def",
"check_version",
"(",
"current_version",
":",
"str",
")",
":",
"app_version",
"=",
"parse_version",
"(",
"current_version",
")",
"while",
"True",
":",
"try",
":",
"_do_check_version",
"(",
"app_version",
")",
"except",
"requests",
".",
"exceptions",
".",
... | Check periodically for a new release | [
"Check",
"periodically",
"for",
"a",
"new",
"release"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L59-L73 |
235,626 | raiden-network/raiden | raiden/tasks.py | check_gas_reserve | def check_gas_reserve(raiden):
""" Check periodically for gas reserve in the account """
while True:
has_enough_balance, estimated_required_balance = gas_reserve.has_enough_gas_reserve(
raiden,
channels_to_open=1,
)
estimated_required_balance_eth = Web3.fromWei(estimated_required_balance, 'ether')
if not has_enough_balance:
log.info('Missing gas reserve', required_wei=estimated_required_balance)
click.secho(
(
'WARNING\n'
"Your account's balance is below the estimated gas reserve of "
f'{estimated_required_balance_eth} eth. This may lead to a loss of '
'of funds because your account will be unable to perform on-chain '
'transactions. Please add funds to your account as soon as possible.'
),
fg='red',
)
gevent.sleep(CHECK_GAS_RESERVE_INTERVAL) | python | def check_gas_reserve(raiden):
while True:
has_enough_balance, estimated_required_balance = gas_reserve.has_enough_gas_reserve(
raiden,
channels_to_open=1,
)
estimated_required_balance_eth = Web3.fromWei(estimated_required_balance, 'ether')
if not has_enough_balance:
log.info('Missing gas reserve', required_wei=estimated_required_balance)
click.secho(
(
'WARNING\n'
"Your account's balance is below the estimated gas reserve of "
f'{estimated_required_balance_eth} eth. This may lead to a loss of '
'of funds because your account will be unable to perform on-chain '
'transactions. Please add funds to your account as soon as possible.'
),
fg='red',
)
gevent.sleep(CHECK_GAS_RESERVE_INTERVAL) | [
"def",
"check_gas_reserve",
"(",
"raiden",
")",
":",
"while",
"True",
":",
"has_enough_balance",
",",
"estimated_required_balance",
"=",
"gas_reserve",
".",
"has_enough_gas_reserve",
"(",
"raiden",
",",
"channels_to_open",
"=",
"1",
",",
")",
"estimated_required_balan... | Check periodically for gas reserve in the account | [
"Check",
"periodically",
"for",
"gas",
"reserve",
"in",
"the",
"account"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L76-L98 |
235,627 | raiden-network/raiden | raiden/tasks.py | check_rdn_deposits | def check_rdn_deposits(raiden, user_deposit_proxy: UserDeposit):
""" Check periodically for RDN deposits in the user-deposits contract """
while True:
rei_balance = user_deposit_proxy.effective_balance(raiden.address, "latest")
rdn_balance = to_rdn(rei_balance)
if rei_balance < MIN_REI_THRESHOLD:
click.secho(
(
f'WARNING\n'
f'Your account\'s RDN balance of {rdn_balance} is below the '
f'minimum threshold. Provided that you have either a monitoring '
f'service or a path finding service activated, your node is not going '
f'to be able to pay those services which may lead to denial of service or '
f'loss of funds.'
),
fg='red',
)
gevent.sleep(CHECK_RDN_MIN_DEPOSIT_INTERVAL) | python | def check_rdn_deposits(raiden, user_deposit_proxy: UserDeposit):
while True:
rei_balance = user_deposit_proxy.effective_balance(raiden.address, "latest")
rdn_balance = to_rdn(rei_balance)
if rei_balance < MIN_REI_THRESHOLD:
click.secho(
(
f'WARNING\n'
f'Your account\'s RDN balance of {rdn_balance} is below the '
f'minimum threshold. Provided that you have either a monitoring '
f'service or a path finding service activated, your node is not going '
f'to be able to pay those services which may lead to denial of service or '
f'loss of funds.'
),
fg='red',
)
gevent.sleep(CHECK_RDN_MIN_DEPOSIT_INTERVAL) | [
"def",
"check_rdn_deposits",
"(",
"raiden",
",",
"user_deposit_proxy",
":",
"UserDeposit",
")",
":",
"while",
"True",
":",
"rei_balance",
"=",
"user_deposit_proxy",
".",
"effective_balance",
"(",
"raiden",
".",
"address",
",",
"\"latest\"",
")",
"rdn_balance",
"="... | Check periodically for RDN deposits in the user-deposits contract | [
"Check",
"periodically",
"for",
"RDN",
"deposits",
"in",
"the",
"user",
"-",
"deposits",
"contract"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L101-L119 |
235,628 | raiden-network/raiden | raiden/tasks.py | check_network_id | def check_network_id(network_id, web3: Web3):
""" Check periodically if the underlying ethereum client's network id has changed"""
while True:
current_id = int(web3.version.network)
if network_id != current_id:
raise RuntimeError(
f'Raiden was running on network with id {network_id} and it detected '
f'that the underlying ethereum client network id changed to {current_id}.'
f' Changing the underlying blockchain while the Raiden node is running '
f'is not supported.',
)
gevent.sleep(CHECK_NETWORK_ID_INTERVAL) | python | def check_network_id(network_id, web3: Web3):
while True:
current_id = int(web3.version.network)
if network_id != current_id:
raise RuntimeError(
f'Raiden was running on network with id {network_id} and it detected '
f'that the underlying ethereum client network id changed to {current_id}.'
f' Changing the underlying blockchain while the Raiden node is running '
f'is not supported.',
)
gevent.sleep(CHECK_NETWORK_ID_INTERVAL) | [
"def",
"check_network_id",
"(",
"network_id",
",",
"web3",
":",
"Web3",
")",
":",
"while",
"True",
":",
"current_id",
"=",
"int",
"(",
"web3",
".",
"version",
".",
"network",
")",
"if",
"network_id",
"!=",
"current_id",
":",
"raise",
"RuntimeError",
"(",
... | Check periodically if the underlying ethereum client's network id has changed | [
"Check",
"periodically",
"if",
"the",
"underlying",
"ethereum",
"client",
"s",
"network",
"id",
"has",
"changed"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L122-L133 |
235,629 | raiden-network/raiden | raiden/tasks.py | AlarmTask.register_callback | def register_callback(self, callback):
""" Register a new callback.
Note:
The callback will be executed in the AlarmTask context and for
this reason it should not block, otherwise we can miss block
changes.
"""
if not callable(callback):
raise ValueError('callback is not a callable')
self.callbacks.append(callback) | python | def register_callback(self, callback):
if not callable(callback):
raise ValueError('callback is not a callable')
self.callbacks.append(callback) | [
"def",
"register_callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"not",
"callable",
"(",
"callback",
")",
":",
"raise",
"ValueError",
"(",
"'callback is not a callable'",
")",
"self",
".",
"callbacks",
".",
"append",
"(",
"callback",
")"
] | Register a new callback.
Note:
The callback will be executed in the AlarmTask context and for
this reason it should not block, otherwise we can miss block
changes. | [
"Register",
"a",
"new",
"callback",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L171-L182 |
235,630 | raiden-network/raiden | raiden/tasks.py | AlarmTask.remove_callback | def remove_callback(self, callback):
"""Remove callback from the list of callbacks if it exists"""
if callback in self.callbacks:
self.callbacks.remove(callback) | python | def remove_callback(self, callback):
if callback in self.callbacks:
self.callbacks.remove(callback) | [
"def",
"remove_callback",
"(",
"self",
",",
"callback",
")",
":",
"if",
"callback",
"in",
"self",
".",
"callbacks",
":",
"self",
".",
"callbacks",
".",
"remove",
"(",
"callback",
")"
] | Remove callback from the list of callbacks if it exists | [
"Remove",
"callback",
"from",
"the",
"list",
"of",
"callbacks",
"if",
"it",
"exists"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L184-L187 |
235,631 | raiden-network/raiden | raiden/tasks.py | AlarmTask.first_run | def first_run(self, known_block_number):
""" Blocking call to update the local state, if necessary. """
assert self.callbacks, 'callbacks not set'
latest_block = self.chain.get_block(block_identifier='latest')
log.debug(
'Alarm task first run',
known_block_number=known_block_number,
latest_block_number=latest_block['number'],
latest_gas_limit=latest_block['gasLimit'],
latest_block_hash=to_hex(latest_block['hash']),
)
self.known_block_number = known_block_number
self.chain_id = self.chain.network_id
self._maybe_run_callbacks(latest_block) | python | def first_run(self, known_block_number):
assert self.callbacks, 'callbacks not set'
latest_block = self.chain.get_block(block_identifier='latest')
log.debug(
'Alarm task first run',
known_block_number=known_block_number,
latest_block_number=latest_block['number'],
latest_gas_limit=latest_block['gasLimit'],
latest_block_hash=to_hex(latest_block['hash']),
)
self.known_block_number = known_block_number
self.chain_id = self.chain.network_id
self._maybe_run_callbacks(latest_block) | [
"def",
"first_run",
"(",
"self",
",",
"known_block_number",
")",
":",
"assert",
"self",
".",
"callbacks",
",",
"'callbacks not set'",
"latest_block",
"=",
"self",
".",
"chain",
".",
"get_block",
"(",
"block_identifier",
"=",
"'latest'",
")",
"log",
".",
"debug... | Blocking call to update the local state, if necessary. | [
"Blocking",
"call",
"to",
"update",
"the",
"local",
"state",
"if",
"necessary",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L207-L222 |
235,632 | raiden-network/raiden | raiden/tasks.py | AlarmTask._maybe_run_callbacks | def _maybe_run_callbacks(self, latest_block):
""" Run the callbacks if there is at least one new block.
The callbacks are executed only if there is a new block, otherwise the
filters may try to poll for an inexisting block number and the Ethereum
client can return an JSON-RPC error.
"""
assert self.known_block_number is not None, 'known_block_number not set'
latest_block_number = latest_block['number']
missed_blocks = latest_block_number - self.known_block_number
if missed_blocks < 0:
log.critical(
'Block number decreased',
chain_id=self.chain_id,
known_block_number=self.known_block_number,
old_block_number=latest_block['number'],
old_gas_limit=latest_block['gasLimit'],
old_block_hash=to_hex(latest_block['hash']),
)
elif missed_blocks > 0:
log_details = dict(
known_block_number=self.known_block_number,
latest_block_number=latest_block_number,
latest_block_hash=to_hex(latest_block['hash']),
latest_block_gas_limit=latest_block['gasLimit'],
)
if missed_blocks > 1:
log_details['num_missed_blocks'] = missed_blocks - 1
log.debug(
'Received new block',
**log_details,
)
remove = list()
for callback in self.callbacks:
result = callback(latest_block)
if result is REMOVE_CALLBACK:
remove.append(callback)
for callback in remove:
self.callbacks.remove(callback)
self.known_block_number = latest_block_number | python | def _maybe_run_callbacks(self, latest_block):
assert self.known_block_number is not None, 'known_block_number not set'
latest_block_number = latest_block['number']
missed_blocks = latest_block_number - self.known_block_number
if missed_blocks < 0:
log.critical(
'Block number decreased',
chain_id=self.chain_id,
known_block_number=self.known_block_number,
old_block_number=latest_block['number'],
old_gas_limit=latest_block['gasLimit'],
old_block_hash=to_hex(latest_block['hash']),
)
elif missed_blocks > 0:
log_details = dict(
known_block_number=self.known_block_number,
latest_block_number=latest_block_number,
latest_block_hash=to_hex(latest_block['hash']),
latest_block_gas_limit=latest_block['gasLimit'],
)
if missed_blocks > 1:
log_details['num_missed_blocks'] = missed_blocks - 1
log.debug(
'Received new block',
**log_details,
)
remove = list()
for callback in self.callbacks:
result = callback(latest_block)
if result is REMOVE_CALLBACK:
remove.append(callback)
for callback in remove:
self.callbacks.remove(callback)
self.known_block_number = latest_block_number | [
"def",
"_maybe_run_callbacks",
"(",
"self",
",",
"latest_block",
")",
":",
"assert",
"self",
".",
"known_block_number",
"is",
"not",
"None",
",",
"'known_block_number not set'",
"latest_block_number",
"=",
"latest_block",
"[",
"'number'",
"]",
"missed_blocks",
"=",
... | Run the callbacks if there is at least one new block.
The callbacks are executed only if there is a new block, otherwise the
filters may try to poll for an inexisting block number and the Ethereum
client can return an JSON-RPC error. | [
"Run",
"the",
"callbacks",
"if",
"there",
"is",
"at",
"least",
"one",
"new",
"block",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/tasks.py#L224-L269 |
235,633 | raiden-network/raiden | raiden/storage/restore.py | channel_state_until_state_change | def channel_state_until_state_change(
raiden,
canonical_identifier: CanonicalIdentifier,
state_change_identifier: int,
) -> typing.Optional[NettingChannelState]:
""" Go through WAL state changes until a certain balance hash is found. """
wal = restore_to_state_change(
transition_function=node.state_transition,
storage=raiden.wal.storage,
state_change_identifier=state_change_identifier,
)
msg = 'There is a state change, therefore the state must not be None'
assert wal.state_manager.current_state is not None, msg
chain_state = wal.state_manager.current_state
channel_state = views.get_channelstate_by_canonical_identifier(
chain_state=chain_state,
canonical_identifier=canonical_identifier,
)
if not channel_state:
raise RaidenUnrecoverableError(
f"Channel was not found before state_change {state_change_identifier}",
)
return channel_state | python | def channel_state_until_state_change(
raiden,
canonical_identifier: CanonicalIdentifier,
state_change_identifier: int,
) -> typing.Optional[NettingChannelState]:
wal = restore_to_state_change(
transition_function=node.state_transition,
storage=raiden.wal.storage,
state_change_identifier=state_change_identifier,
)
msg = 'There is a state change, therefore the state must not be None'
assert wal.state_manager.current_state is not None, msg
chain_state = wal.state_manager.current_state
channel_state = views.get_channelstate_by_canonical_identifier(
chain_state=chain_state,
canonical_identifier=canonical_identifier,
)
if not channel_state:
raise RaidenUnrecoverableError(
f"Channel was not found before state_change {state_change_identifier}",
)
return channel_state | [
"def",
"channel_state_until_state_change",
"(",
"raiden",
",",
"canonical_identifier",
":",
"CanonicalIdentifier",
",",
"state_change_identifier",
":",
"int",
",",
")",
"->",
"typing",
".",
"Optional",
"[",
"NettingChannelState",
"]",
":",
"wal",
"=",
"restore_to_stat... | Go through WAL state changes until a certain balance hash is found. | [
"Go",
"through",
"WAL",
"state",
"changes",
"until",
"a",
"certain",
"balance",
"hash",
"is",
"found",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/storage/restore.py#L10-L36 |
235,634 | raiden-network/raiden | raiden/utils/signing.py | pack_data | def pack_data(abi_types, values) -> bytes:
"""Normalize data and pack them into a byte array"""
if len(abi_types) != len(values):
raise ValueError(
"Length mismatch between provided abi types and values. Got "
"{0} types and {1} values.".format(len(abi_types), len(values)),
)
normalized_values = map_abi_data([abi_address_to_hex], abi_types, values)
return decode_hex(''.join(
remove_0x_prefix(hex_encode_abi_type(abi_type, value))
for abi_type, value
in zip(abi_types, normalized_values)
)) | python | def pack_data(abi_types, values) -> bytes:
if len(abi_types) != len(values):
raise ValueError(
"Length mismatch between provided abi types and values. Got "
"{0} types and {1} values.".format(len(abi_types), len(values)),
)
normalized_values = map_abi_data([abi_address_to_hex], abi_types, values)
return decode_hex(''.join(
remove_0x_prefix(hex_encode_abi_type(abi_type, value))
for abi_type, value
in zip(abi_types, normalized_values)
)) | [
"def",
"pack_data",
"(",
"abi_types",
",",
"values",
")",
"->",
"bytes",
":",
"if",
"len",
"(",
"abi_types",
")",
"!=",
"len",
"(",
"values",
")",
":",
"raise",
"ValueError",
"(",
"\"Length mismatch between provided abi types and values. Got \"",
"\"{0} types and {... | Normalize data and pack them into a byte array | [
"Normalize",
"data",
"and",
"pack",
"them",
"into",
"a",
"byte",
"array"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/signing.py#L9-L23 |
235,635 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | _RetryQueue._expiration_generator | def _expiration_generator(
timeout_generator: Iterable[float],
now: Callable[[], float] = time.time,
) -> Iterator[bool]:
"""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
"""
for timeout in timeout_generator:
_next = now() + timeout # next value is now + next generated timeout
yield True
while now() < _next: # yield False while next is still in the future
yield False | python | def _expiration_generator(
timeout_generator: Iterable[float],
now: Callable[[], float] = time.time,
) -> Iterator[bool]:
for timeout in timeout_generator:
_next = now() + timeout # next value is now + next generated timeout
yield True
while now() < _next: # yield False while next is still in the future
yield False | [
"def",
"_expiration_generator",
"(",
"timeout_generator",
":",
"Iterable",
"[",
"float",
"]",
",",
"now",
":",
"Callable",
"[",
"[",
"]",
",",
"float",
"]",
"=",
"time",
".",
"time",
",",
")",
"->",
"Iterator",
"[",
"bool",
"]",
":",
"for",
"timeout",
... | 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 | [
"Stateful",
"generator",
"that",
"yields",
"True",
"if",
"more",
"than",
"timeout",
"has",
"passed",
"since",
"previous",
"True",
"False",
"otherwise",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L117-L133 |
235,636 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | _RetryQueue.enqueue | def enqueue(self, queue_identifier: QueueIdentifier, message: Message):
""" Enqueue a message to be sent, and notify main loop """
assert queue_identifier.recipient == self.receiver
with self._lock:
already_queued = any(
queue_identifier == data.queue_identifier and message == data.message
for data in self._message_queue
)
if already_queued:
self.log.warning(
'Message already in queue - ignoring',
receiver=pex(self.receiver),
queue=queue_identifier,
message=message,
)
return
timeout_generator = udp_utils.timeout_exponential_backoff(
self.transport._config['retries_before_backoff'],
self.transport._config['retry_interval'],
self.transport._config['retry_interval'] * 10,
)
expiration_generator = self._expiration_generator(timeout_generator)
self._message_queue.append(_RetryQueue._MessageData(
queue_identifier=queue_identifier,
message=message,
text=json.dumps(message.to_dict()),
expiration_generator=expiration_generator,
))
self.notify() | python | def enqueue(self, queue_identifier: QueueIdentifier, message: Message):
assert queue_identifier.recipient == self.receiver
with self._lock:
already_queued = any(
queue_identifier == data.queue_identifier and message == data.message
for data in self._message_queue
)
if already_queued:
self.log.warning(
'Message already in queue - ignoring',
receiver=pex(self.receiver),
queue=queue_identifier,
message=message,
)
return
timeout_generator = udp_utils.timeout_exponential_backoff(
self.transport._config['retries_before_backoff'],
self.transport._config['retry_interval'],
self.transport._config['retry_interval'] * 10,
)
expiration_generator = self._expiration_generator(timeout_generator)
self._message_queue.append(_RetryQueue._MessageData(
queue_identifier=queue_identifier,
message=message,
text=json.dumps(message.to_dict()),
expiration_generator=expiration_generator,
))
self.notify() | [
"def",
"enqueue",
"(",
"self",
",",
"queue_identifier",
":",
"QueueIdentifier",
",",
"message",
":",
"Message",
")",
":",
"assert",
"queue_identifier",
".",
"recipient",
"==",
"self",
".",
"receiver",
"with",
"self",
".",
"_lock",
":",
"already_queued",
"=",
... | Enqueue a message to be sent, and notify main loop | [
"Enqueue",
"a",
"message",
"to",
"be",
"sent",
"and",
"notify",
"main",
"loop"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L135-L163 |
235,637 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport.stop | def stop(self):
""" 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 """
if self._stop_event.ready():
return
self._stop_event.set()
self._global_send_event.set()
for retrier in self._address_to_retrier.values():
if retrier:
retrier.notify()
self._client.set_presence_state(UserPresence.OFFLINE.value)
self._client.stop_listener_thread() # stop sync_thread, wait client's greenlets
# wait own greenlets, no need to get on them, exceptions should be raised in _run()
gevent.wait(self.greenlets + [r.greenlet for r in self._address_to_retrier.values()])
# Ensure keep-alive http connections are closed
self._client.api.session.close()
self.log.debug('Matrix stopped', config=self._config)
del self.log | python | def stop(self):
if self._stop_event.ready():
return
self._stop_event.set()
self._global_send_event.set()
for retrier in self._address_to_retrier.values():
if retrier:
retrier.notify()
self._client.set_presence_state(UserPresence.OFFLINE.value)
self._client.stop_listener_thread() # stop sync_thread, wait client's greenlets
# wait own greenlets, no need to get on them, exceptions should be raised in _run()
gevent.wait(self.greenlets + [r.greenlet for r in self._address_to_retrier.values()])
# Ensure keep-alive http connections are closed
self._client.api.session.close()
self.log.debug('Matrix stopped', config=self._config)
del self.log | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_stop_event",
".",
"ready",
"(",
")",
":",
"return",
"self",
".",
"_stop_event",
".",
"set",
"(",
")",
"self",
".",
"_global_send_event",
".",
"set",
"(",
")",
"for",
"retrier",
"in",
"self",
... | 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 | [
"Try",
"to",
"gracefully",
"stop",
"the",
"greenlet",
"synchronously"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L434-L459 |
235,638 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport.whitelist | def whitelist(self, address: Address):
"""Whitelist peer address to receive communications from
This may be called before transport is started, to ensure events generated during
start are handled properly.
"""
self.log.debug('Whitelist', address=to_normalized_address(address))
self._address_mgr.add_address(address) | python | def whitelist(self, address: Address):
self.log.debug('Whitelist', address=to_normalized_address(address))
self._address_mgr.add_address(address) | [
"def",
"whitelist",
"(",
"self",
",",
"address",
":",
"Address",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Whitelist'",
",",
"address",
"=",
"to_normalized_address",
"(",
"address",
")",
")",
"self",
".",
"_address_mgr",
".",
"add_address",
"(",
... | Whitelist peer address to receive communications from
This may be called before transport is started, to ensure events generated during
start are handled properly. | [
"Whitelist",
"peer",
"address",
"to",
"receive",
"communications",
"from"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L476-L483 |
235,639 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport.send_async | def send_async(
self,
queue_identifier: QueueIdentifier,
message: Message,
):
"""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
"""
# even if transport is not started, can run to enqueue messages to send when it starts
receiver_address = queue_identifier.recipient
if not is_binary_address(receiver_address):
raise ValueError('Invalid address {}'.format(pex(receiver_address)))
# These are not protocol messages, but transport specific messages
if isinstance(message, (Delivered, Ping, Pong)):
raise ValueError(
'Do not use send_async for {} messages'.format(message.__class__.__name__),
)
self.log.debug(
'Send async',
receiver_address=pex(receiver_address),
message=message,
queue_identifier=queue_identifier,
)
self._send_with_retry(queue_identifier, message) | python | def send_async(
self,
queue_identifier: QueueIdentifier,
message: Message,
):
# even if transport is not started, can run to enqueue messages to send when it starts
receiver_address = queue_identifier.recipient
if not is_binary_address(receiver_address):
raise ValueError('Invalid address {}'.format(pex(receiver_address)))
# These are not protocol messages, but transport specific messages
if isinstance(message, (Delivered, Ping, Pong)):
raise ValueError(
'Do not use send_async for {} messages'.format(message.__class__.__name__),
)
self.log.debug(
'Send async',
receiver_address=pex(receiver_address),
message=message,
queue_identifier=queue_identifier,
)
self._send_with_retry(queue_identifier, message) | [
"def",
"send_async",
"(",
"self",
",",
"queue_identifier",
":",
"QueueIdentifier",
",",
"message",
":",
"Message",
",",
")",
":",
"# even if transport is not started, can run to enqueue messages to send when it starts",
"receiver_address",
"=",
"queue_identifier",
".",
"recip... | 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 | [
"Queue",
"the",
"message",
"for",
"sending",
"to",
"recipient",
"in",
"the",
"queue_identifier"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L516-L545 |
235,640 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport.send_global | def send_global(self, room: str, message: Message) -> None:
"""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
"""
self._global_send_queue.put((room, message))
self._global_send_event.set() | python | def send_global(self, room: str, message: Message) -> None:
self._global_send_queue.put((room, message))
self._global_send_event.set() | [
"def",
"send_global",
"(",
"self",
",",
"room",
":",
"str",
",",
"message",
":",
"Message",
")",
"->",
"None",
":",
"self",
".",
"_global_send_queue",
".",
"put",
"(",
"(",
"room",
",",
"message",
")",
")",
"self",
".",
"_global_send_event",
".",
"set"... | 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 | [
"Sends",
"a",
"message",
"to",
"one",
"of",
"the",
"global",
"rooms"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L547-L559 |
235,641 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._handle_invite | def _handle_invite(self, room_id: _RoomID, state: dict):
""" Join rooms invited by whitelisted partners """
if self._stop_event.ready():
return
self.log.debug('Got invite', room_id=room_id)
invite_events = [
event
for event in state['events']
if event['type'] == 'm.room.member' and
event['content'].get('membership') == 'invite' and
event['state_key'] == self._user_id
]
if not invite_events:
self.log.debug('Invite: no invite event found', room_id=room_id)
return # there should always be one and only one invite membership event for us
invite_event = invite_events[0]
sender = invite_event['sender']
sender_join_events = [
event
for event in state['events']
if event['type'] == 'm.room.member' and
event['content'].get('membership') == 'join' and
event['state_key'] == sender
]
if not sender_join_events:
self.log.debug('Invite: no sender join event', room_id=room_id)
return # there should always be one and only one join membership event for the sender
sender_join_event = sender_join_events[0]
user = self._get_user(sender)
user.displayname = sender_join_event['content'].get('displayname') or user.displayname
peer_address = validate_userid_signature(user)
if not peer_address:
self.log.debug(
'Got invited to a room by invalid signed user - ignoring',
room_id=room_id,
user=user,
)
return
if not self._address_mgr.is_address_known(peer_address):
self.log.debug(
'Got invited by a non-whitelisted user - ignoring',
room_id=room_id,
user=user,
)
return
join_rules_events = [
event
for event in state['events']
if event['type'] == 'm.room.join_rules'
]
# room privacy as seen from the event
private_room: bool = False
if join_rules_events:
join_rules_event = join_rules_events[0]
private_room = join_rules_event['content'].get('join_rule') == 'invite'
# we join room and _set_room_id_for_address despite room privacy and requirements,
# _get_room_ids_for_address will take care of returning only matching rooms and
# _leave_unused_rooms will clear it in the future, if and when needed
room: Room = None
last_ex: Optional[Exception] = None
retry_interval = 0.1
for _ in range(JOIN_RETRIES):
try:
room = self._client.join_room(room_id)
except MatrixRequestError as e:
last_ex = e
if self._stop_event.wait(retry_interval):
break
retry_interval = retry_interval * 2
else:
break
else:
assert last_ex is not None
raise last_ex # re-raise if couldn't succeed in retries
if not room.listeners:
room.add_listener(self._handle_message, 'm.room.message')
# room state may not populated yet, so we populate 'invite_only' from event
room.invite_only = private_room
self._set_room_id_for_address(address=peer_address, room_id=room_id)
self.log.debug(
'Joined from invite',
room_id=room_id,
aliases=room.aliases,
peer=to_checksum_address(peer_address),
) | python | def _handle_invite(self, room_id: _RoomID, state: dict):
if self._stop_event.ready():
return
self.log.debug('Got invite', room_id=room_id)
invite_events = [
event
for event in state['events']
if event['type'] == 'm.room.member' and
event['content'].get('membership') == 'invite' and
event['state_key'] == self._user_id
]
if not invite_events:
self.log.debug('Invite: no invite event found', room_id=room_id)
return # there should always be one and only one invite membership event for us
invite_event = invite_events[0]
sender = invite_event['sender']
sender_join_events = [
event
for event in state['events']
if event['type'] == 'm.room.member' and
event['content'].get('membership') == 'join' and
event['state_key'] == sender
]
if not sender_join_events:
self.log.debug('Invite: no sender join event', room_id=room_id)
return # there should always be one and only one join membership event for the sender
sender_join_event = sender_join_events[0]
user = self._get_user(sender)
user.displayname = sender_join_event['content'].get('displayname') or user.displayname
peer_address = validate_userid_signature(user)
if not peer_address:
self.log.debug(
'Got invited to a room by invalid signed user - ignoring',
room_id=room_id,
user=user,
)
return
if not self._address_mgr.is_address_known(peer_address):
self.log.debug(
'Got invited by a non-whitelisted user - ignoring',
room_id=room_id,
user=user,
)
return
join_rules_events = [
event
for event in state['events']
if event['type'] == 'm.room.join_rules'
]
# room privacy as seen from the event
private_room: bool = False
if join_rules_events:
join_rules_event = join_rules_events[0]
private_room = join_rules_event['content'].get('join_rule') == 'invite'
# we join room and _set_room_id_for_address despite room privacy and requirements,
# _get_room_ids_for_address will take care of returning only matching rooms and
# _leave_unused_rooms will clear it in the future, if and when needed
room: Room = None
last_ex: Optional[Exception] = None
retry_interval = 0.1
for _ in range(JOIN_RETRIES):
try:
room = self._client.join_room(room_id)
except MatrixRequestError as e:
last_ex = e
if self._stop_event.wait(retry_interval):
break
retry_interval = retry_interval * 2
else:
break
else:
assert last_ex is not None
raise last_ex # re-raise if couldn't succeed in retries
if not room.listeners:
room.add_listener(self._handle_message, 'm.room.message')
# room state may not populated yet, so we populate 'invite_only' from event
room.invite_only = private_room
self._set_room_id_for_address(address=peer_address, room_id=room_id)
self.log.debug(
'Joined from invite',
room_id=room_id,
aliases=room.aliases,
peer=to_checksum_address(peer_address),
) | [
"def",
"_handle_invite",
"(",
"self",
",",
"room_id",
":",
"_RoomID",
",",
"state",
":",
"dict",
")",
":",
"if",
"self",
".",
"_stop_event",
".",
"ready",
"(",
")",
":",
"return",
"self",
".",
"log",
".",
"debug",
"(",
"'Got invite'",
",",
"room_id",
... | Join rooms invited by whitelisted partners | [
"Join",
"rooms",
"invited",
"by",
"whitelisted",
"partners"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L644-L739 |
235,642 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._get_retrier | def _get_retrier(self, receiver: Address) -> _RetryQueue:
""" Construct and return a _RetryQueue for receiver """
if receiver not in self._address_to_retrier:
retrier = _RetryQueue(transport=self, receiver=receiver)
self._address_to_retrier[receiver] = retrier
# Always start the _RetryQueue, otherwise `stop` will block forever
# waiting for the corresponding gevent.Greenlet to complete. This
# has no negative side-effects if the transport has stopped because
# the retrier itself checks the transport running state.
retrier.start()
return self._address_to_retrier[receiver] | python | def _get_retrier(self, receiver: Address) -> _RetryQueue:
if receiver not in self._address_to_retrier:
retrier = _RetryQueue(transport=self, receiver=receiver)
self._address_to_retrier[receiver] = retrier
# Always start the _RetryQueue, otherwise `stop` will block forever
# waiting for the corresponding gevent.Greenlet to complete. This
# has no negative side-effects if the transport has stopped because
# the retrier itself checks the transport running state.
retrier.start()
return self._address_to_retrier[receiver] | [
"def",
"_get_retrier",
"(",
"self",
",",
"receiver",
":",
"Address",
")",
"->",
"_RetryQueue",
":",
"if",
"receiver",
"not",
"in",
"self",
".",
"_address_to_retrier",
":",
"retrier",
"=",
"_RetryQueue",
"(",
"transport",
"=",
"self",
",",
"receiver",
"=",
... | Construct and return a _RetryQueue for receiver | [
"Construct",
"and",
"return",
"a",
"_RetryQueue",
"for",
"receiver"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L951-L961 |
235,643 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._get_private_room | def _get_private_room(self, invitees: List[User]):
""" Create an anonymous, private room and invite peers """
return self._client.create_room(
None,
invitees=[user.user_id for user in invitees],
is_public=False,
) | python | def _get_private_room(self, invitees: List[User]):
return self._client.create_room(
None,
invitees=[user.user_id for user in invitees],
is_public=False,
) | [
"def",
"_get_private_room",
"(",
"self",
",",
"invitees",
":",
"List",
"[",
"User",
"]",
")",
":",
"return",
"self",
".",
"_client",
".",
"create_room",
"(",
"None",
",",
"invitees",
"=",
"[",
"user",
".",
"user_id",
"for",
"user",
"in",
"invitees",
"]... | Create an anonymous, private room and invite peers | [
"Create",
"an",
"anonymous",
"private",
"room",
"and",
"invite",
"peers"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L1078-L1084 |
235,644 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._sign | def _sign(self, data: bytes) -> bytes:
""" Use eth_sign compatible hasher to sign matrix data """
assert self._raiden_service is not None
return self._raiden_service.signer.sign(data=data) | python | def _sign(self, data: bytes) -> bytes:
assert self._raiden_service is not None
return self._raiden_service.signer.sign(data=data) | [
"def",
"_sign",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"bytes",
":",
"assert",
"self",
".",
"_raiden_service",
"is",
"not",
"None",
"return",
"self",
".",
"_raiden_service",
".",
"signer",
".",
"sign",
"(",
"data",
"=",
"data",
")"
] | Use eth_sign compatible hasher to sign matrix data | [
"Use",
"eth_sign",
"compatible",
"hasher",
"to",
"sign",
"matrix",
"data"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L1207-L1210 |
235,645 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._get_user | def _get_user(self, user: Union[User, str]) -> User:
"""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"""
user_id: str = getattr(user, 'user_id', user)
discovery_room = self._global_rooms.get(
make_room_alias(self.network_id, DISCOVERY_DEFAULT_ROOM),
)
if discovery_room and user_id in discovery_room._members:
duser = discovery_room._members[user_id]
# if handed a User instance with displayname set, update the discovery room cache
if getattr(user, 'displayname', None):
assert isinstance(user, User)
duser.displayname = user.displayname
user = duser
elif not isinstance(user, User):
user = self._client.get_user(user_id)
return user | python | def _get_user(self, user: Union[User, str]) -> User:
user_id: str = getattr(user, 'user_id', user)
discovery_room = self._global_rooms.get(
make_room_alias(self.network_id, DISCOVERY_DEFAULT_ROOM),
)
if discovery_room and user_id in discovery_room._members:
duser = discovery_room._members[user_id]
# if handed a User instance with displayname set, update the discovery room cache
if getattr(user, 'displayname', None):
assert isinstance(user, User)
duser.displayname = user.displayname
user = duser
elif not isinstance(user, User):
user = self._client.get_user(user_id)
return user | [
"def",
"_get_user",
"(",
"self",
",",
"user",
":",
"Union",
"[",
"User",
",",
"str",
"]",
")",
"->",
"User",
":",
"user_id",
":",
"str",
"=",
"getattr",
"(",
"user",
",",
"'user_id'",
",",
"user",
")",
"discovery_room",
"=",
"self",
".",
"_global_roo... | 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 | [
"Creates",
"an",
"User",
"from",
"an",
"user_id",
"if",
"none",
"or",
"fetch",
"a",
"cached",
"User"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L1212-L1229 |
235,646 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._set_room_id_for_address | def _set_room_id_for_address(self, address: Address, room_id: Optional[_RoomID] = None):
""" 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 """
assert not room_id or room_id in self._client.rooms, 'Invalid room_id'
address_hex: AddressHex = to_checksum_address(address)
# filter_private=False to preserve public rooms on the list, even if we require privacy
room_ids = self._get_room_ids_for_address(address, filter_private=False)
with self._account_data_lock:
# no need to deepcopy, we don't modify lists in-place
# cast generic Dict[str, Any] to types we expect, to satisfy mypy, runtime no-op
_address_to_room_ids = cast(
Dict[AddressHex, List[_RoomID]],
self._client.account_data.get('network.raiden.rooms', {}).copy(),
)
changed = False
if not room_id: # falsy room_id => clear list
changed = address_hex in _address_to_room_ids
_address_to_room_ids.pop(address_hex, None)
else:
# push to front
room_ids = [room_id] + [r for r in room_ids if r != room_id]
if room_ids != _address_to_room_ids.get(address_hex):
_address_to_room_ids[address_hex] = room_ids
changed = True
if changed:
# dict will be set at the end of _clean_unused_rooms
self._leave_unused_rooms(_address_to_room_ids) | python | 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, 'Invalid room_id'
address_hex: AddressHex = to_checksum_address(address)
# filter_private=False to preserve public rooms on the list, even if we require privacy
room_ids = self._get_room_ids_for_address(address, filter_private=False)
with self._account_data_lock:
# no need to deepcopy, we don't modify lists in-place
# cast generic Dict[str, Any] to types we expect, to satisfy mypy, runtime no-op
_address_to_room_ids = cast(
Dict[AddressHex, List[_RoomID]],
self._client.account_data.get('network.raiden.rooms', {}).copy(),
)
changed = False
if not room_id: # falsy room_id => clear list
changed = address_hex in _address_to_room_ids
_address_to_room_ids.pop(address_hex, None)
else:
# push to front
room_ids = [room_id] + [r for r in room_ids if r != room_id]
if room_ids != _address_to_room_ids.get(address_hex):
_address_to_room_ids[address_hex] = room_ids
changed = True
if changed:
# dict will be set at the end of _clean_unused_rooms
self._leave_unused_rooms(_address_to_room_ids) | [
"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",
",",
"'I... | 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 | [
"Uses",
"GMatrixClient",
".",
"set_account_data",
"to",
"keep",
"updated",
"mapping",
"of",
"addresses",
"-",
">",
"rooms"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L1231-L1262 |
235,647 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._get_room_ids_for_address | def _get_room_ids_for_address(
self,
address: Address,
filter_private: bool = None,
) -> List[_RoomID]:
""" 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
"""
address_hex: AddressHex = to_checksum_address(address)
with self._account_data_lock:
room_ids = self._client.account_data.get(
'network.raiden.rooms',
{},
).get(address_hex)
self.log.debug('matrix get account data', room_ids=room_ids, for_address=address_hex)
if not room_ids: # None or empty
room_ids = list()
if not isinstance(room_ids, list): # old version, single room
room_ids = [room_ids]
if filter_private is None:
filter_private = self._private_rooms
if not filter_private:
# existing rooms
room_ids = [
room_id
for room_id in room_ids
if room_id in self._client.rooms
]
else:
# existing and private rooms
room_ids = [
room_id
for room_id in room_ids
if room_id in self._client.rooms and self._client.rooms[room_id].invite_only
]
return room_ids | python | def _get_room_ids_for_address(
self,
address: Address,
filter_private: bool = None,
) -> List[_RoomID]:
address_hex: AddressHex = to_checksum_address(address)
with self._account_data_lock:
room_ids = self._client.account_data.get(
'network.raiden.rooms',
{},
).get(address_hex)
self.log.debug('matrix get account data', room_ids=room_ids, for_address=address_hex)
if not room_ids: # None or empty
room_ids = list()
if not isinstance(room_ids, list): # old version, single room
room_ids = [room_ids]
if filter_private is None:
filter_private = self._private_rooms
if not filter_private:
# existing rooms
room_ids = [
room_id
for room_id in room_ids
if room_id in self._client.rooms
]
else:
# existing and private rooms
room_ids = [
room_id
for room_id in room_ids
if room_id in self._client.rooms and self._client.rooms[room_id].invite_only
]
return room_ids | [
"def",
"_get_room_ids_for_address",
"(",
"self",
",",
"address",
":",
"Address",
",",
"filter_private",
":",
"bool",
"=",
"None",
",",
")",
"->",
"List",
"[",
"_RoomID",
"]",
":",
"address_hex",
":",
"AddressHex",
"=",
"to_checksum_address",
"(",
"address",
... | 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 | [
"Uses",
"GMatrixClient",
".",
"get_account_data",
"to",
"get",
"updated",
"mapping",
"of",
"address",
"-",
">",
"rooms"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L1264-L1304 |
235,648 | raiden-network/raiden | raiden/network/transport/matrix/transport.py | MatrixTransport._leave_unused_rooms | def _leave_unused_rooms(self, _address_to_room_ids: Dict[AddressHex, List[_RoomID]]):
"""
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`.
"""
_msg = '_leave_unused_rooms called without account data lock'
assert self._account_data_lock.locked(), _msg
# TODO: Remove the next five lines and check if transfers start hanging again
self._client.set_account_data(
'network.raiden.rooms', # back from cast in _set_room_id_for_address
cast(Dict[str, Any], _address_to_room_ids),
)
return
# cache in a set all whitelisted addresses
whitelisted_hex_addresses: Set[AddressHex] = {
to_checksum_address(address)
for address in self._address_mgr.known_addresses
}
keep_rooms: Set[_RoomID] = set()
for address_hex, room_ids in list(_address_to_room_ids.items()):
if not room_ids: # None or empty
room_ids = list()
if not isinstance(room_ids, list): # old version, single room
room_ids = [room_ids]
if address_hex not in whitelisted_hex_addresses:
_address_to_room_ids.pop(address_hex)
continue
counters = [0, 0] # public, private
new_room_ids: List[_RoomID] = list()
# limit to at most 2 public and 2 private rooms, preserving order
for room_id in room_ids:
if room_id not in self._client.rooms:
continue
elif self._client.rooms[room_id].invite_only is None:
new_room_ids.append(room_id) # not known, postpone cleaning
elif counters[self._client.rooms[room_id].invite_only] < 2:
counters[self._client.rooms[room_id].invite_only] += 1
new_room_ids.append(room_id) # not enough rooms of this type yet
else:
continue # enough rooms, leave and clean
keep_rooms |= set(new_room_ids)
if room_ids != new_room_ids:
_address_to_room_ids[address_hex] = new_room_ids
rooms: List[Tuple[_RoomID, Room]] = list(self._client.rooms.items())
self.log.debug(
'Updated address room mapping',
address_to_room_ids=_address_to_room_ids,
)
self._client.set_account_data('network.raiden.rooms', _address_to_room_ids)
def leave(room: Room):
"""A race between /leave and /sync may remove the room before
del on _client.rooms key. Suppress it, as the end result is the same: no more room"""
try:
self.log.debug('Leaving unused room', room=room)
return room.leave()
except KeyError:
return True
for room_id, room in rooms:
if room_id in {groom.room_id for groom in self._global_rooms.values() if groom}:
# don't leave global room
continue
if room_id not in keep_rooms:
greenlet = self._spawn(leave, room)
greenlet.name = (
f'MatrixTransport.leave '
f'node:{pex(self._raiden_service.address)} '
f'user_id:{self._user_id}'
) | python | def _leave_unused_rooms(self, _address_to_room_ids: Dict[AddressHex, List[_RoomID]]):
_msg = '_leave_unused_rooms called without account data lock'
assert self._account_data_lock.locked(), _msg
# TODO: Remove the next five lines and check if transfers start hanging again
self._client.set_account_data(
'network.raiden.rooms', # back from cast in _set_room_id_for_address
cast(Dict[str, Any], _address_to_room_ids),
)
return
# cache in a set all whitelisted addresses
whitelisted_hex_addresses: Set[AddressHex] = {
to_checksum_address(address)
for address in self._address_mgr.known_addresses
}
keep_rooms: Set[_RoomID] = set()
for address_hex, room_ids in list(_address_to_room_ids.items()):
if not room_ids: # None or empty
room_ids = list()
if not isinstance(room_ids, list): # old version, single room
room_ids = [room_ids]
if address_hex not in whitelisted_hex_addresses:
_address_to_room_ids.pop(address_hex)
continue
counters = [0, 0] # public, private
new_room_ids: List[_RoomID] = list()
# limit to at most 2 public and 2 private rooms, preserving order
for room_id in room_ids:
if room_id not in self._client.rooms:
continue
elif self._client.rooms[room_id].invite_only is None:
new_room_ids.append(room_id) # not known, postpone cleaning
elif counters[self._client.rooms[room_id].invite_only] < 2:
counters[self._client.rooms[room_id].invite_only] += 1
new_room_ids.append(room_id) # not enough rooms of this type yet
else:
continue # enough rooms, leave and clean
keep_rooms |= set(new_room_ids)
if room_ids != new_room_ids:
_address_to_room_ids[address_hex] = new_room_ids
rooms: List[Tuple[_RoomID, Room]] = list(self._client.rooms.items())
self.log.debug(
'Updated address room mapping',
address_to_room_ids=_address_to_room_ids,
)
self._client.set_account_data('network.raiden.rooms', _address_to_room_ids)
def leave(room: Room):
"""A race between /leave and /sync may remove the room before
del on _client.rooms key. Suppress it, as the end result is the same: no more room"""
try:
self.log.debug('Leaving unused room', room=room)
return room.leave()
except KeyError:
return True
for room_id, room in rooms:
if room_id in {groom.room_id for groom in self._global_rooms.values() if groom}:
# don't leave global room
continue
if room_id not in keep_rooms:
greenlet = self._spawn(leave, room)
greenlet.name = (
f'MatrixTransport.leave '
f'node:{pex(self._raiden_service.address)} '
f'user_id:{self._user_id}'
) | [
"def",
"_leave_unused_rooms",
"(",
"self",
",",
"_address_to_room_ids",
":",
"Dict",
"[",
"AddressHex",
",",
"List",
"[",
"_RoomID",
"]",
"]",
")",
":",
"_msg",
"=",
"'_leave_unused_rooms called without account data lock'",
"assert",
"self",
".",
"_account_data_lock",... | 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`. | [
"Checks",
"for",
"rooms",
"we",
"ve",
"joined",
"and",
"which",
"partner",
"isn",
"t",
"health",
"-",
"checked",
"and",
"leave",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/transport.py#L1306-L1386 |
235,649 | raiden-network/raiden | tools/scenario-player/scenario_player/scenario.py | NodesConfig.nodes | def nodes(self) -> List[str]:
"""Return the list of nodes configured in the scenario's yaml.
Should the scenario use version 1, we check if there is a 'setting'.
If so, we derive the list of nodes from this dictionary, using its
'first', 'last' and 'template' keys. Should any of these keys be
missing, we throw an appropriate exception.
If the scenario version is not 1, or no 'range' setting exists, we use
the 'list' settings key and return the value. Again, should the key be
absent, we throw an appropriate error.
:raises MissingNodesConfiguration:
if the scenario version is 1 and a 'range' key was detected, but any
one of the keys 'first', 'last', 'template' are missing; *or* the
scenario version is not 1 or the 'range' key and the 'list' are absent.
"""
if self._scenario_version == 1 and 'range' in self._config:
range_config = self._config['range']
try:
start, stop = range_config['first'], range_config['last'] + 1
except KeyError:
raise MissingNodesConfiguration(
'Setting "range" must be a dict containing keys "first" and "last",'
' whose values are integers!',
)
try:
template = range_config['template']
except KeyError:
raise MissingNodesConfiguration(
'Must specify "template" setting when giving "range" setting.',
)
return [template.format(i) for i in range(start, stop)]
try:
return self._config['list']
except KeyError:
raise MissingNodesConfiguration('Must specify nodes under "list" setting!') | python | def nodes(self) -> List[str]:
if self._scenario_version == 1 and 'range' in self._config:
range_config = self._config['range']
try:
start, stop = range_config['first'], range_config['last'] + 1
except KeyError:
raise MissingNodesConfiguration(
'Setting "range" must be a dict containing keys "first" and "last",'
' whose values are integers!',
)
try:
template = range_config['template']
except KeyError:
raise MissingNodesConfiguration(
'Must specify "template" setting when giving "range" setting.',
)
return [template.format(i) for i in range(start, stop)]
try:
return self._config['list']
except KeyError:
raise MissingNodesConfiguration('Must specify nodes under "list" setting!') | [
"def",
"nodes",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"self",
".",
"_scenario_version",
"==",
"1",
"and",
"'range'",
"in",
"self",
".",
"_config",
":",
"range_config",
"=",
"self",
".",
"_config",
"[",
"'range'",
"]",
"try",
":"... | Return the list of nodes configured in the scenario's yaml.
Should the scenario use version 1, we check if there is a 'setting'.
If so, we derive the list of nodes from this dictionary, using its
'first', 'last' and 'template' keys. Should any of these keys be
missing, we throw an appropriate exception.
If the scenario version is not 1, or no 'range' setting exists, we use
the 'list' settings key and return the value. Again, should the key be
absent, we throw an appropriate error.
:raises MissingNodesConfiguration:
if the scenario version is 1 and a 'range' key was detected, but any
one of the keys 'first', 'last', 'template' are missing; *or* the
scenario version is not 1 or the 'range' key and the 'list' are absent. | [
"Return",
"the",
"list",
"of",
"nodes",
"configured",
"in",
"the",
"scenario",
"s",
"yaml",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/scenario.py#L82-L121 |
235,650 | raiden-network/raiden | tools/scenario-player/scenario_player/scenario.py | Scenario.version | def version(self) -> int:
"""Return the scenario's version.
If this is not present, we default to version 1.
:raises InvalidScenarioVersion:
if the supplied version is not present in :var:`SUPPORTED_SCENARIO_VERSIONS`.
"""
version = self._config.get('version', 1)
if version not in SUPPORTED_SCENARIO_VERSIONS:
raise InvalidScenarioVersion(f'Unexpected scenario version {version}')
return version | python | def version(self) -> int:
version = self._config.get('version', 1)
if version not in SUPPORTED_SCENARIO_VERSIONS:
raise InvalidScenarioVersion(f'Unexpected scenario version {version}')
return version | [
"def",
"version",
"(",
"self",
")",
"->",
"int",
":",
"version",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'version'",
",",
"1",
")",
"if",
"version",
"not",
"in",
"SUPPORTED_SCENARIO_VERSIONS",
":",
"raise",
"InvalidScenarioVersion",
"(",
"f'Unexpected... | Return the scenario's version.
If this is not present, we default to version 1.
:raises InvalidScenarioVersion:
if the supplied version is not present in :var:`SUPPORTED_SCENARIO_VERSIONS`. | [
"Return",
"the",
"scenario",
"s",
"version",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/scenario.py#L155-L167 |
235,651 | raiden-network/raiden | tools/scenario-player/scenario_player/scenario.py | Scenario.protocol | def protocol(self) -> str:
"""Return the designated protocol of the scenario.
If the node's mode is :attr:`NodeMode.MANAGED`, we always choose `http` and
display a warning if there was a 'protocol' set explicitly in the
scenario's yaml.
Otherwise we simply access the 'protocol' key of the yaml, defaulting to
'http' if it does not exist.
"""
if self.nodes.mode is NodeMode.MANAGED:
if 'protocol' in self._config:
log.warning('The "protocol" setting is not supported in "managed" node mode.')
return 'http'
return self._config.get('protocol', 'http') | python | def protocol(self) -> str:
if self.nodes.mode is NodeMode.MANAGED:
if 'protocol' in self._config:
log.warning('The "protocol" setting is not supported in "managed" node mode.')
return 'http'
return self._config.get('protocol', 'http') | [
"def",
"protocol",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"nodes",
".",
"mode",
"is",
"NodeMode",
".",
"MANAGED",
":",
"if",
"'protocol'",
"in",
"self",
".",
"_config",
":",
"log",
".",
"warning",
"(",
"'The \"protocol\" setting is not supp... | Return the designated protocol of the scenario.
If the node's mode is :attr:`NodeMode.MANAGED`, we always choose `http` and
display a warning if there was a 'protocol' set explicitly in the
scenario's yaml.
Otherwise we simply access the 'protocol' key of the yaml, defaulting to
'http' if it does not exist. | [
"Return",
"the",
"designated",
"protocol",
"of",
"the",
"scenario",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/scenario.py#L180-L194 |
235,652 | raiden-network/raiden | tools/scenario-player/scenario_player/scenario.py | Scenario.task | def task(self) -> Tuple[str, Any]:
"""Return the scenario's task configuration as a tuple.
:raises MultipleTaskDefinitions:
if there is more than one task config under the 'scenario' key.
"""
try:
items, = self.configuration.items()
except ValueError:
raise MultipleTaskDefinitions(
'Multiple tasks defined in scenario configuration!',
)
return items | python | def task(self) -> Tuple[str, Any]:
try:
items, = self.configuration.items()
except ValueError:
raise MultipleTaskDefinitions(
'Multiple tasks defined in scenario configuration!',
)
return items | [
"def",
"task",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"Any",
"]",
":",
"try",
":",
"items",
",",
"=",
"self",
".",
"configuration",
".",
"items",
"(",
")",
"except",
"ValueError",
":",
"raise",
"MultipleTaskDefinitions",
"(",
"'Multiple tasks ... | Return the scenario's task configuration as a tuple.
:raises MultipleTaskDefinitions:
if there is more than one task config under the 'scenario' key. | [
"Return",
"the",
"scenario",
"s",
"task",
"configuration",
"as",
"a",
"tuple",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/scenario.py#L250-L262 |
235,653 | raiden-network/raiden | tools/scenario-player/scenario_player/scenario.py | Scenario.task_class | def task_class(self):
"""Return the Task class type configured for the scenario."""
from scenario_player.tasks.base import get_task_class_for_type
root_task_type, _ = self.task
task_class = get_task_class_for_type(root_task_type)
return task_class | python | def task_class(self):
from scenario_player.tasks.base import get_task_class_for_type
root_task_type, _ = self.task
task_class = get_task_class_for_type(root_task_type)
return task_class | [
"def",
"task_class",
"(",
"self",
")",
":",
"from",
"scenario_player",
".",
"tasks",
".",
"base",
"import",
"get_task_class_for_type",
"root_task_type",
",",
"_",
"=",
"self",
".",
"task",
"task_class",
"=",
"get_task_class_for_type",
"(",
"root_task_type",
")",
... | Return the Task class type configured for the scenario. | [
"Return",
"the",
"Task",
"class",
"type",
"configured",
"for",
"the",
"scenario",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/scenario-player/scenario_player/scenario.py#L271-L278 |
235,654 | raiden-network/raiden | tools/check_circleci_config.py | _check_workflows_align | def _check_workflows_align(config):
"""
Ensure that the common shared jobs in the `raiden-default` and `nightly` workflows are
identical.
"""
jobs_default = config['workflows']['raiden-default']['jobs']
jobs_nightly = config['workflows']['nightly']['jobs']
if jobs_default == jobs_nightly[:len(jobs_default)]:
return True, []
job_diff = unified_diff(
[f"{line}\n" for line in jobs_default],
[f"{line}\n" for line in jobs_nightly[:len(jobs_default)]],
'raiden-default',
'nightly',
)
message = [
_yellow(
"Mismatch in common items of workflow definitions 'raiden-default' and "
"'nightly':\n",
),
]
for line in job_diff:
if line.startswith('-'):
message.append(_red(line))
elif line.startswith('+'):
message.append(_green(line))
else:
message.append(line)
return False, ''.join(message) | python | def _check_workflows_align(config):
jobs_default = config['workflows']['raiden-default']['jobs']
jobs_nightly = config['workflows']['nightly']['jobs']
if jobs_default == jobs_nightly[:len(jobs_default)]:
return True, []
job_diff = unified_diff(
[f"{line}\n" for line in jobs_default],
[f"{line}\n" for line in jobs_nightly[:len(jobs_default)]],
'raiden-default',
'nightly',
)
message = [
_yellow(
"Mismatch in common items of workflow definitions 'raiden-default' and "
"'nightly':\n",
),
]
for line in job_diff:
if line.startswith('-'):
message.append(_red(line))
elif line.startswith('+'):
message.append(_green(line))
else:
message.append(line)
return False, ''.join(message) | [
"def",
"_check_workflows_align",
"(",
"config",
")",
":",
"jobs_default",
"=",
"config",
"[",
"'workflows'",
"]",
"[",
"'raiden-default'",
"]",
"[",
"'jobs'",
"]",
"jobs_nightly",
"=",
"config",
"[",
"'workflows'",
"]",
"[",
"'nightly'",
"]",
"[",
"'jobs'",
... | Ensure that the common shared jobs in the `raiden-default` and `nightly` workflows are
identical. | [
"Ensure",
"that",
"the",
"common",
"shared",
"jobs",
"in",
"the",
"raiden",
"-",
"default",
"and",
"nightly",
"workflows",
"are",
"identical",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/tools/check_circleci_config.py#L26-L58 |
235,655 | raiden-network/raiden | raiden/network/rpc/smartcontract_proxy.py | ContractProxy.get_transaction_data | def get_transaction_data(
abi: Dict,
function_name: str,
args: Any = None,
kwargs: Any = None,
):
"""Get encoded transaction data"""
args = args or list()
fn_abi = find_matching_fn_abi(
abi,
function_name,
args=args,
kwargs=kwargs,
)
return encode_transaction_data(
None,
function_name,
contract_abi=abi,
fn_abi=fn_abi,
args=args,
kwargs=kwargs,
) | python | def get_transaction_data(
abi: Dict,
function_name: str,
args: Any = None,
kwargs: Any = None,
):
args = args or list()
fn_abi = find_matching_fn_abi(
abi,
function_name,
args=args,
kwargs=kwargs,
)
return encode_transaction_data(
None,
function_name,
contract_abi=abi,
fn_abi=fn_abi,
args=args,
kwargs=kwargs,
) | [
"def",
"get_transaction_data",
"(",
"abi",
":",
"Dict",
",",
"function_name",
":",
"str",
",",
"args",
":",
"Any",
"=",
"None",
",",
"kwargs",
":",
"Any",
"=",
"None",
",",
")",
":",
"args",
"=",
"args",
"or",
"list",
"(",
")",
"fn_abi",
"=",
"find... | Get encoded transaction data | [
"Get",
"encoded",
"transaction",
"data"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/smartcontract_proxy.py#L140-L161 |
235,656 | raiden-network/raiden | raiden/network/rpc/smartcontract_proxy.py | ContractProxy.decode_transaction_input | def decode_transaction_input(self, transaction_hash: bytes) -> Dict:
"""Return inputs of a method call"""
transaction = self.contract.web3.eth.getTransaction(
transaction_hash,
)
return self.contract.decode_function_input(
transaction['input'],
) | python | def decode_transaction_input(self, transaction_hash: bytes) -> Dict:
transaction = self.contract.web3.eth.getTransaction(
transaction_hash,
)
return self.contract.decode_function_input(
transaction['input'],
) | [
"def",
"decode_transaction_input",
"(",
"self",
",",
"transaction_hash",
":",
"bytes",
")",
"->",
"Dict",
":",
"transaction",
"=",
"self",
".",
"contract",
".",
"web3",
".",
"eth",
".",
"getTransaction",
"(",
"transaction_hash",
",",
")",
"return",
"self",
"... | Return inputs of a method call | [
"Return",
"inputs",
"of",
"a",
"method",
"call"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/smartcontract_proxy.py#L163-L171 |
235,657 | raiden-network/raiden | raiden/network/rpc/smartcontract_proxy.py | ContractProxy.estimate_gas | def estimate_gas(
self,
block_identifier,
function: str,
*args,
**kwargs,
) -> typing.Optional[int]:
"""Returns a gas estimate for the function with the given arguments or
None if the function call will fail due to Insufficient funds or
the logic in the called function."""
fn = getattr(self.contract.functions, function)
address = to_checksum_address(self.jsonrpc_client.address)
if self.jsonrpc_client.eth_node is constants.EthClient.GETH:
# Unfortunately geth does not follow the ethereum JSON-RPC spec and
# does not accept a block identifier argument for eth_estimateGas
# parity and py-evm (trinity) do.
#
# Geth only runs estimateGas on the pending block and that's why we
# should also enforce parity, py-evm and others to do the same since
# we can't customize geth.
#
# Spec: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas
# Geth Issue: https://github.com/ethereum/go-ethereum/issues/2586
# Relevant web3 PR: https://github.com/ethereum/web3.py/pull/1046
block_identifier = None
try:
return fn(*args, **kwargs).estimateGas(
transaction={'from': address},
block_identifier=block_identifier,
)
except ValueError as err:
action = inspect_client_error(err, self.jsonrpc_client.eth_node)
will_fail = action in (
ClientErrorInspectResult.INSUFFICIENT_FUNDS,
ClientErrorInspectResult.ALWAYS_FAIL,
)
if will_fail:
return None
raise err | python | def estimate_gas(
self,
block_identifier,
function: str,
*args,
**kwargs,
) -> typing.Optional[int]:
fn = getattr(self.contract.functions, function)
address = to_checksum_address(self.jsonrpc_client.address)
if self.jsonrpc_client.eth_node is constants.EthClient.GETH:
# Unfortunately geth does not follow the ethereum JSON-RPC spec and
# does not accept a block identifier argument for eth_estimateGas
# parity and py-evm (trinity) do.
#
# Geth only runs estimateGas on the pending block and that's why we
# should also enforce parity, py-evm and others to do the same since
# we can't customize geth.
#
# Spec: https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_estimategas
# Geth Issue: https://github.com/ethereum/go-ethereum/issues/2586
# Relevant web3 PR: https://github.com/ethereum/web3.py/pull/1046
block_identifier = None
try:
return fn(*args, **kwargs).estimateGas(
transaction={'from': address},
block_identifier=block_identifier,
)
except ValueError as err:
action = inspect_client_error(err, self.jsonrpc_client.eth_node)
will_fail = action in (
ClientErrorInspectResult.INSUFFICIENT_FUNDS,
ClientErrorInspectResult.ALWAYS_FAIL,
)
if will_fail:
return None
raise err | [
"def",
"estimate_gas",
"(",
"self",
",",
"block_identifier",
",",
"function",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
",",
")",
"->",
"typing",
".",
"Optional",
"[",
"int",
"]",
":",
"fn",
"=",
"getattr",
"(",
"self",
".",
"contract",
... | Returns a gas estimate for the function with the given arguments or
None if the function call will fail due to Insufficient funds or
the logic in the called function. | [
"Returns",
"a",
"gas",
"estimate",
"for",
"the",
"function",
"with",
"the",
"given",
"arguments",
"or",
"None",
"if",
"the",
"function",
"call",
"will",
"fail",
"due",
"to",
"Insufficient",
"funds",
"or",
"the",
"logic",
"in",
"the",
"called",
"function",
... | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/rpc/smartcontract_proxy.py#L179-L218 |
235,658 | raiden-network/raiden | raiden/messages.py | SignedMessage.sign | def sign(self, signer: Signer):
""" Sign message using signer. """
message_data = self._data_to_sign()
self.signature = signer.sign(data=message_data) | python | def sign(self, signer: Signer):
message_data = self._data_to_sign()
self.signature = signer.sign(data=message_data) | [
"def",
"sign",
"(",
"self",
",",
"signer",
":",
"Signer",
")",
":",
"message_data",
"=",
"self",
".",
"_data_to_sign",
"(",
")",
"self",
".",
"signature",
"=",
"signer",
".",
"sign",
"(",
"data",
"=",
"message_data",
")"
] | Sign message using signer. | [
"Sign",
"message",
"using",
"signer",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/messages.py#L282-L285 |
235,659 | raiden-network/raiden | raiden/messages.py | SignedBlindedBalanceProof._sign | def _sign(self, signer: Signer) -> Signature:
"""Internal function for the overall `sign` function of `RequestMonitoring`.
"""
# Important: we don't write the signature to `.signature`
data = self._data_to_sign()
return signer.sign(data) | python | def _sign(self, signer: Signer) -> Signature:
# Important: we don't write the signature to `.signature`
data = self._data_to_sign()
return signer.sign(data) | [
"def",
"_sign",
"(",
"self",
",",
"signer",
":",
"Signer",
")",
"->",
"Signature",
":",
"# Important: we don't write the signature to `.signature`",
"data",
"=",
"self",
".",
"_data_to_sign",
"(",
")",
"return",
"signer",
".",
"sign",
"(",
"data",
")"
] | Internal function for the overall `sign` function of `RequestMonitoring`. | [
"Internal",
"function",
"for",
"the",
"overall",
"sign",
"function",
"of",
"RequestMonitoring",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/messages.py#L1590-L1595 |
235,660 | raiden-network/raiden | raiden/messages.py | RequestMonitoring.verify_request_monitoring | def verify_request_monitoring(
self,
partner_address: Address,
requesting_address: Address,
) -> bool:
""" One should only use this method to verify integrity and signatures of a
RequestMonitoring message. """
if not self.non_closing_signature:
return False
balance_proof_data = pack_balance_proof(
nonce=self.balance_proof.nonce,
balance_hash=self.balance_proof.balance_hash,
additional_hash=self.balance_proof.additional_hash,
canonical_identifier=CanonicalIdentifier(
chain_identifier=self.balance_proof.chain_id,
token_network_address=self.balance_proof.token_network_address,
channel_identifier=self.balance_proof.channel_identifier,
),
)
blinded_data = pack_balance_proof_update(
nonce=self.balance_proof.nonce,
balance_hash=self.balance_proof.balance_hash,
additional_hash=self.balance_proof.additional_hash,
canonical_identifier=CanonicalIdentifier(
chain_identifier=self.balance_proof.chain_id,
token_network_address=self.balance_proof.token_network_address,
channel_identifier=self.balance_proof.channel_identifier,
),
partner_signature=self.balance_proof.signature,
)
reward_proof_data = pack_reward_proof(
canonical_identifier=CanonicalIdentifier(
chain_identifier=self.balance_proof.chain_id,
token_network_address=self.balance_proof.token_network_address,
channel_identifier=self.balance_proof.channel_identifier,
),
reward_amount=self.reward_amount,
nonce=self.balance_proof.nonce,
)
return (
recover(balance_proof_data, self.balance_proof.signature) == partner_address and
recover(blinded_data, self.non_closing_signature) == requesting_address and
recover(reward_proof_data, self.reward_proof_signature) == requesting_address
) | python | def verify_request_monitoring(
self,
partner_address: Address,
requesting_address: Address,
) -> bool:
if not self.non_closing_signature:
return False
balance_proof_data = pack_balance_proof(
nonce=self.balance_proof.nonce,
balance_hash=self.balance_proof.balance_hash,
additional_hash=self.balance_proof.additional_hash,
canonical_identifier=CanonicalIdentifier(
chain_identifier=self.balance_proof.chain_id,
token_network_address=self.balance_proof.token_network_address,
channel_identifier=self.balance_proof.channel_identifier,
),
)
blinded_data = pack_balance_proof_update(
nonce=self.balance_proof.nonce,
balance_hash=self.balance_proof.balance_hash,
additional_hash=self.balance_proof.additional_hash,
canonical_identifier=CanonicalIdentifier(
chain_identifier=self.balance_proof.chain_id,
token_network_address=self.balance_proof.token_network_address,
channel_identifier=self.balance_proof.channel_identifier,
),
partner_signature=self.balance_proof.signature,
)
reward_proof_data = pack_reward_proof(
canonical_identifier=CanonicalIdentifier(
chain_identifier=self.balance_proof.chain_id,
token_network_address=self.balance_proof.token_network_address,
channel_identifier=self.balance_proof.channel_identifier,
),
reward_amount=self.reward_amount,
nonce=self.balance_proof.nonce,
)
return (
recover(balance_proof_data, self.balance_proof.signature) == partner_address and
recover(blinded_data, self.non_closing_signature) == requesting_address and
recover(reward_proof_data, self.reward_proof_signature) == requesting_address
) | [
"def",
"verify_request_monitoring",
"(",
"self",
",",
"partner_address",
":",
"Address",
",",
"requesting_address",
":",
"Address",
",",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"non_closing_signature",
":",
"return",
"False",
"balance_proof_data",
"=",
... | One should only use this method to verify integrity and signatures of a
RequestMonitoring message. | [
"One",
"should",
"only",
"use",
"this",
"method",
"to",
"verify",
"integrity",
"and",
"signatures",
"of",
"a",
"RequestMonitoring",
"message",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/messages.py#L1780-L1824 |
235,661 | raiden-network/raiden | raiden/utils/filters.py | get_filter_args_for_specific_event_from_channel | def get_filter_args_for_specific_event_from_channel(
token_network_address: TokenNetworkAddress,
channel_identifier: ChannelID,
event_name: str,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
):
""" Return the filter params for a specific event of a given channel. """
if not event_name:
raise ValueError('Event name must be given')
event_abi = contract_manager.get_event_abi(CONTRACT_TOKEN_NETWORK, event_name)
# Here the topics for a specific event are created
# The first entry of the topics list is the event name, then the first parameter is encoded,
# in the case of a token network, the first parameter is always the channel identifier
_, event_filter_params = construct_event_filter_params(
event_abi=event_abi,
contract_address=to_checksum_address(token_network_address),
argument_filters={
'channel_identifier': channel_identifier,
},
fromBlock=from_block,
toBlock=to_block,
)
return event_filter_params | python | def get_filter_args_for_specific_event_from_channel(
token_network_address: TokenNetworkAddress,
channel_identifier: ChannelID,
event_name: str,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
):
if not event_name:
raise ValueError('Event name must be given')
event_abi = contract_manager.get_event_abi(CONTRACT_TOKEN_NETWORK, event_name)
# Here the topics for a specific event are created
# The first entry of the topics list is the event name, then the first parameter is encoded,
# in the case of a token network, the first parameter is always the channel identifier
_, event_filter_params = construct_event_filter_params(
event_abi=event_abi,
contract_address=to_checksum_address(token_network_address),
argument_filters={
'channel_identifier': channel_identifier,
},
fromBlock=from_block,
toBlock=to_block,
)
return event_filter_params | [
"def",
"get_filter_args_for_specific_event_from_channel",
"(",
"token_network_address",
":",
"TokenNetworkAddress",
",",
"channel_identifier",
":",
"ChannelID",
",",
"event_name",
":",
"str",
",",
"contract_manager",
":",
"ContractManager",
",",
"from_block",
":",
"BlockSpe... | Return the filter params for a specific event of a given channel. | [
"Return",
"the",
"filter",
"params",
"for",
"a",
"specific",
"event",
"of",
"a",
"given",
"channel",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/filters.py#L32-L59 |
235,662 | raiden-network/raiden | raiden/utils/filters.py | get_filter_args_for_all_events_from_channel | def get_filter_args_for_all_events_from_channel(
token_network_address: TokenNetworkAddress,
channel_identifier: ChannelID,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> Dict:
""" Return the filter params for all events of a given channel. """
event_filter_params = get_filter_args_for_specific_event_from_channel(
token_network_address=token_network_address,
channel_identifier=channel_identifier,
event_name=ChannelEvent.OPENED,
contract_manager=contract_manager,
from_block=from_block,
to_block=to_block,
)
# As we want to get all events for a certain channel we remove the event specific code here
# and filter just for the channel identifier
# We also have to remove the trailing topics to get all filters
event_filter_params['topics'] = [None, event_filter_params['topics'][1]]
return event_filter_params | python | def get_filter_args_for_all_events_from_channel(
token_network_address: TokenNetworkAddress,
channel_identifier: ChannelID,
contract_manager: ContractManager,
from_block: BlockSpecification = GENESIS_BLOCK_NUMBER,
to_block: BlockSpecification = 'latest',
) -> Dict:
event_filter_params = get_filter_args_for_specific_event_from_channel(
token_network_address=token_network_address,
channel_identifier=channel_identifier,
event_name=ChannelEvent.OPENED,
contract_manager=contract_manager,
from_block=from_block,
to_block=to_block,
)
# As we want to get all events for a certain channel we remove the event specific code here
# and filter just for the channel identifier
# We also have to remove the trailing topics to get all filters
event_filter_params['topics'] = [None, event_filter_params['topics'][1]]
return event_filter_params | [
"def",
"get_filter_args_for_all_events_from_channel",
"(",
"token_network_address",
":",
"TokenNetworkAddress",
",",
"channel_identifier",
":",
"ChannelID",
",",
"contract_manager",
":",
"ContractManager",
",",
"from_block",
":",
"BlockSpecification",
"=",
"GENESIS_BLOCK_NUMBER... | Return the filter params for all events of a given channel. | [
"Return",
"the",
"filter",
"params",
"for",
"all",
"events",
"of",
"a",
"given",
"channel",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/filters.py#L62-L85 |
235,663 | pytorch/tnt | torchnet/meter/confusionmeter.py | ConfusionMeter.add | def add(self, predicted, target):
"""Computes the confusion matrix of K x K size where K is no of classes
Args:
predicted (tensor): Can be an N x K tensor of predicted scores obtained from
the model for N examples and K classes or an N-tensor of
integer values between 0 and K-1.
target (tensor): Can be a N-tensor of integer values assumed to be integer
values between 0 and K-1 or N x K tensor, where targets are
assumed to be provided as one-hot vectors
"""
predicted = predicted.cpu().numpy()
target = target.cpu().numpy()
assert predicted.shape[0] == target.shape[0], \
'number of targets and predicted outputs do not match'
if np.ndim(predicted) != 1:
assert predicted.shape[1] == self.k, \
'number of predictions does not match size of confusion matrix'
predicted = np.argmax(predicted, 1)
else:
assert (predicted.max() < self.k) and (predicted.min() >= 0), \
'predicted values are not between 1 and k'
onehot_target = np.ndim(target) != 1
if onehot_target:
assert target.shape[1] == self.k, \
'Onehot target does not match size of confusion matrix'
assert (target >= 0).all() and (target <= 1).all(), \
'in one-hot encoding, target values should be 0 or 1'
assert (target.sum(1) == 1).all(), \
'multi-label setting is not supported'
target = np.argmax(target, 1)
else:
assert (predicted.max() < self.k) and (predicted.min() >= 0), \
'predicted values are not between 0 and k-1'
# hack for bincounting 2 arrays together
x = predicted + self.k * target
bincount_2d = np.bincount(x.astype(np.int32),
minlength=self.k ** 2)
assert bincount_2d.size == self.k ** 2
conf = bincount_2d.reshape((self.k, self.k))
self.conf += conf | python | def add(self, predicted, target):
predicted = predicted.cpu().numpy()
target = target.cpu().numpy()
assert predicted.shape[0] == target.shape[0], \
'number of targets and predicted outputs do not match'
if np.ndim(predicted) != 1:
assert predicted.shape[1] == self.k, \
'number of predictions does not match size of confusion matrix'
predicted = np.argmax(predicted, 1)
else:
assert (predicted.max() < self.k) and (predicted.min() >= 0), \
'predicted values are not between 1 and k'
onehot_target = np.ndim(target) != 1
if onehot_target:
assert target.shape[1] == self.k, \
'Onehot target does not match size of confusion matrix'
assert (target >= 0).all() and (target <= 1).all(), \
'in one-hot encoding, target values should be 0 or 1'
assert (target.sum(1) == 1).all(), \
'multi-label setting is not supported'
target = np.argmax(target, 1)
else:
assert (predicted.max() < self.k) and (predicted.min() >= 0), \
'predicted values are not between 0 and k-1'
# hack for bincounting 2 arrays together
x = predicted + self.k * target
bincount_2d = np.bincount(x.astype(np.int32),
minlength=self.k ** 2)
assert bincount_2d.size == self.k ** 2
conf = bincount_2d.reshape((self.k, self.k))
self.conf += conf | [
"def",
"add",
"(",
"self",
",",
"predicted",
",",
"target",
")",
":",
"predicted",
"=",
"predicted",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"target",
"=",
"target",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"assert",
"predicted",
".",
... | Computes the confusion matrix of K x K size where K is no of classes
Args:
predicted (tensor): Can be an N x K tensor of predicted scores obtained from
the model for N examples and K classes or an N-tensor of
integer values between 0 and K-1.
target (tensor): Can be a N-tensor of integer values assumed to be integer
values between 0 and K-1 or N x K tensor, where targets are
assumed to be provided as one-hot vectors | [
"Computes",
"the",
"confusion",
"matrix",
"of",
"K",
"x",
"K",
"size",
"where",
"K",
"is",
"no",
"of",
"classes"
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/meter/confusionmeter.py#L29-L75 |
235,664 | pytorch/tnt | torchnet/dataset/shuffledataset.py | ShuffleDataset.resample | def resample(self, seed=None):
"""Resample the dataset.
Args:
seed (int, optional): Seed for resampling. By default no seed is
used.
"""
if seed is not None:
gen = torch.manual_seed(seed)
else:
gen = torch.default_generator
if self.replacement:
self.perm = torch.LongTensor(len(self)).random_(
len(self.dataset), generator=gen)
else:
self.perm = torch.randperm(
len(self.dataset), generator=gen).narrow(0, 0, len(self)) | python | def resample(self, seed=None):
if seed is not None:
gen = torch.manual_seed(seed)
else:
gen = torch.default_generator
if self.replacement:
self.perm = torch.LongTensor(len(self)).random_(
len(self.dataset), generator=gen)
else:
self.perm = torch.randperm(
len(self.dataset), generator=gen).narrow(0, 0, len(self)) | [
"def",
"resample",
"(",
"self",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"gen",
"=",
"torch",
".",
"manual_seed",
"(",
"seed",
")",
"else",
":",
"gen",
"=",
"torch",
".",
"default_generator",
"if",
"self",
".",
"r... | Resample the dataset.
Args:
seed (int, optional): Seed for resampling. By default no seed is
used. | [
"Resample",
"the",
"dataset",
"."
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/dataset/shuffledataset.py#L44-L61 |
235,665 | pytorch/tnt | torchnet/meter/apmeter.py | APMeter.reset | def reset(self):
"""Resets the meter with empty member variables"""
self.scores = torch.FloatTensor(torch.FloatStorage())
self.targets = torch.LongTensor(torch.LongStorage())
self.weights = torch.FloatTensor(torch.FloatStorage()) | python | def reset(self):
self.scores = torch.FloatTensor(torch.FloatStorage())
self.targets = torch.LongTensor(torch.LongStorage())
self.weights = torch.FloatTensor(torch.FloatStorage()) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"scores",
"=",
"torch",
".",
"FloatTensor",
"(",
"torch",
".",
"FloatStorage",
"(",
")",
")",
"self",
".",
"targets",
"=",
"torch",
".",
"LongTensor",
"(",
"torch",
".",
"LongStorage",
"(",
")",
")"... | Resets the meter with empty member variables | [
"Resets",
"the",
"meter",
"with",
"empty",
"member",
"variables"
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/meter/apmeter.py#L26-L30 |
235,666 | pytorch/tnt | torchnet/meter/apmeter.py | APMeter.value | def value(self):
"""Returns the model's average precision for each class
Return:
ap (FloatTensor): 1xK tensor, with avg precision for each class k
"""
if self.scores.numel() == 0:
return 0
ap = torch.zeros(self.scores.size(1))
if hasattr(torch, "arange"):
rg = torch.arange(1, self.scores.size(0) + 1).float()
else:
rg = torch.range(1, self.scores.size(0)).float()
if self.weights.numel() > 0:
weight = self.weights.new(self.weights.size())
weighted_truth = self.weights.new(self.weights.size())
# compute average precision for each class
for k in range(self.scores.size(1)):
# sort scores
scores = self.scores[:, k]
targets = self.targets[:, k]
_, sortind = torch.sort(scores, 0, True)
truth = targets[sortind]
if self.weights.numel() > 0:
weight = self.weights[sortind]
weighted_truth = truth.float() * weight
rg = weight.cumsum(0)
# compute true positive sums
if self.weights.numel() > 0:
tp = weighted_truth.cumsum(0)
else:
tp = truth.float().cumsum(0)
# compute precision curve
precision = tp.div(rg)
# compute average precision
ap[k] = precision[truth.byte()].sum() / max(float(truth.sum()), 1)
return ap | python | def value(self):
if self.scores.numel() == 0:
return 0
ap = torch.zeros(self.scores.size(1))
if hasattr(torch, "arange"):
rg = torch.arange(1, self.scores.size(0) + 1).float()
else:
rg = torch.range(1, self.scores.size(0)).float()
if self.weights.numel() > 0:
weight = self.weights.new(self.weights.size())
weighted_truth = self.weights.new(self.weights.size())
# compute average precision for each class
for k in range(self.scores.size(1)):
# sort scores
scores = self.scores[:, k]
targets = self.targets[:, k]
_, sortind = torch.sort(scores, 0, True)
truth = targets[sortind]
if self.weights.numel() > 0:
weight = self.weights[sortind]
weighted_truth = truth.float() * weight
rg = weight.cumsum(0)
# compute true positive sums
if self.weights.numel() > 0:
tp = weighted_truth.cumsum(0)
else:
tp = truth.float().cumsum(0)
# compute precision curve
precision = tp.div(rg)
# compute average precision
ap[k] = precision[truth.byte()].sum() / max(float(truth.sum()), 1)
return ap | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"scores",
".",
"numel",
"(",
")",
"==",
"0",
":",
"return",
"0",
"ap",
"=",
"torch",
".",
"zeros",
"(",
"self",
".",
"scores",
".",
"size",
"(",
"1",
")",
")",
"if",
"hasattr",
"(",
"t... | Returns the model's average precision for each class
Return:
ap (FloatTensor): 1xK tensor, with avg precision for each class k | [
"Returns",
"the",
"model",
"s",
"average",
"precision",
"for",
"each",
"class"
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/meter/apmeter.py#L100-L142 |
235,667 | pytorch/tnt | torchnet/engine/engine.py | Engine.hook | def hook(self, name, state):
r"""Registers a backward hook.
The hook will be called every time a gradient with respect to the
Tensor is computed. The hook should have the following signature::
hook (grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return
a new gradient which will be used in place of :attr:`grad`.
This function returns a handle with a method ``handle.remove()``
that removes the hook from the module.
Example:
>>> v = torch.tensor([0., 0., 0.], requires_grad=True)
>>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
>>> v.backward(torch.tensor([1., 2., 3.]))
>>> v.grad
2
4
6
[torch.FloatTensor of size (3,)]
>>> h.remove() # removes the hook
"""
if name in self.hooks:
self.hooks[name](state) | python | def hook(self, name, state):
r"""Registers a backward hook.
The hook will be called every time a gradient with respect to the
Tensor is computed. The hook should have the following signature::
hook (grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return
a new gradient which will be used in place of :attr:`grad`.
This function returns a handle with a method ``handle.remove()``
that removes the hook from the module.
Example:
>>> v = torch.tensor([0., 0., 0.], requires_grad=True)
>>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
>>> v.backward(torch.tensor([1., 2., 3.]))
>>> v.grad
2
4
6
[torch.FloatTensor of size (3,)]
>>> h.remove() # removes the hook
"""
if name in self.hooks:
self.hooks[name](state) | [
"def",
"hook",
"(",
"self",
",",
"name",
",",
"state",
")",
":",
"if",
"name",
"in",
"self",
".",
"hooks",
":",
"self",
".",
"hooks",
"[",
"name",
"]",
"(",
"state",
")"
] | r"""Registers a backward hook.
The hook will be called every time a gradient with respect to the
Tensor is computed. The hook should have the following signature::
hook (grad) -> Tensor or None
The hook should not modify its argument, but it can optionally return
a new gradient which will be used in place of :attr:`grad`.
This function returns a handle with a method ``handle.remove()``
that removes the hook from the module.
Example:
>>> v = torch.tensor([0., 0., 0.], requires_grad=True)
>>> h = v.register_hook(lambda grad: grad * 2) # double the gradient
>>> v.backward(torch.tensor([1., 2., 3.]))
>>> v.grad
2
4
6
[torch.FloatTensor of size (3,)]
>>> h.remove() # removes the hook | [
"r",
"Registers",
"a",
"backward",
"hook",
"."
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/engine/engine.py#L5-L31 |
235,668 | pytorch/tnt | torchnet/logger/visdomlogger.py | BaseVisdomLogger._viz_prototype | def _viz_prototype(self, vis_fn):
''' Outputs a function which will log the arguments to Visdom in an appropriate way.
Args:
vis_fn: A function, such as self.vis.image
'''
def _viz_logger(*args, **kwargs):
self.win = vis_fn(*args,
win=self.win,
env=self.env,
opts=self.opts,
**kwargs)
return _viz_logger | python | def _viz_prototype(self, vis_fn):
''' Outputs a function which will log the arguments to Visdom in an appropriate way.
Args:
vis_fn: A function, such as self.vis.image
'''
def _viz_logger(*args, **kwargs):
self.win = vis_fn(*args,
win=self.win,
env=self.env,
opts=self.opts,
**kwargs)
return _viz_logger | [
"def",
"_viz_prototype",
"(",
"self",
",",
"vis_fn",
")",
":",
"def",
"_viz_logger",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"win",
"=",
"vis_fn",
"(",
"*",
"args",
",",
"win",
"=",
"self",
".",
"win",
",",
"env",
"=",
... | Outputs a function which will log the arguments to Visdom in an appropriate way.
Args:
vis_fn: A function, such as self.vis.image | [
"Outputs",
"a",
"function",
"which",
"will",
"log",
"the",
"arguments",
"to",
"Visdom",
"in",
"an",
"appropriate",
"way",
"."
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/logger/visdomlogger.py#L36-L48 |
235,669 | pytorch/tnt | torchnet/logger/visdomlogger.py | BaseVisdomLogger.log_state | def log_state(self, state):
""" Gathers the stats from self.trainer.stats and passes them into
self.log, as a list """
results = []
for field_idx, field in enumerate(self.fields):
parent, stat = None, state
for f in field:
parent, stat = stat, stat[f]
results.append(stat)
self.log(*results) | python | def log_state(self, state):
results = []
for field_idx, field in enumerate(self.fields):
parent, stat = None, state
for f in field:
parent, stat = stat, stat[f]
results.append(stat)
self.log(*results) | [
"def",
"log_state",
"(",
"self",
",",
"state",
")",
":",
"results",
"=",
"[",
"]",
"for",
"field_idx",
",",
"field",
"in",
"enumerate",
"(",
"self",
".",
"fields",
")",
":",
"parent",
",",
"stat",
"=",
"None",
",",
"state",
"for",
"f",
"in",
"field... | Gathers the stats from self.trainer.stats and passes them into
self.log, as a list | [
"Gathers",
"the",
"stats",
"from",
"self",
".",
"trainer",
".",
"stats",
"and",
"passes",
"them",
"into",
"self",
".",
"log",
"as",
"a",
"list"
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/logger/visdomlogger.py#L50-L59 |
235,670 | pytorch/tnt | torchnet/logger/meterlogger.py | MeterLogger.peek_meter | def peek_meter(self):
'''Returns a dict of all meters and their values.'''
result = {}
for key in self.meter.keys():
val = self.meter[key].value()
val = val[0] if isinstance(val, (list, tuple)) else val
result[key] = val
return result | python | def peek_meter(self):
'''Returns a dict of all meters and their values.'''
result = {}
for key in self.meter.keys():
val = self.meter[key].value()
val = val[0] if isinstance(val, (list, tuple)) else val
result[key] = val
return result | [
"def",
"peek_meter",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"meter",
".",
"keys",
"(",
")",
":",
"val",
"=",
"self",
".",
"meter",
"[",
"key",
"]",
".",
"value",
"(",
")",
"val",
"=",
"val",
"[",
"0",... | Returns a dict of all meters and their values. | [
"Returns",
"a",
"dict",
"of",
"all",
"meters",
"and",
"their",
"values",
"."
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/logger/meterlogger.py#L103-L110 |
235,671 | pytorch/tnt | torchnet/utils/resultswriter.py | ResultsWriter.update | def update(self, task_name, result):
''' Update the results file with new information.
Args:
task_name (str): Name of the currently running task. A previously unseen
``task_name`` will create a new entry in both :attr:`tasks`
and :attr:`results`.
result: This will be appended to the list in :attr:`results` which
corresponds to the ``task_name`` in ``task_name``:attr:`tasks`.
'''
with open(self.filepath, 'rb') as f:
existing_results = pickle.load(f)
if task_name not in self.tasks:
self._add_task(task_name)
existing_results['tasks'].append(task_name)
existing_results['results'].append([])
task_name_idx = existing_results['tasks'].index(task_name)
results = existing_results['results'][task_name_idx]
results.append(result)
with open(self.filepath, 'wb') as f:
pickle.dump(existing_results, f) | python | def update(self, task_name, result):
''' Update the results file with new information.
Args:
task_name (str): Name of the currently running task. A previously unseen
``task_name`` will create a new entry in both :attr:`tasks`
and :attr:`results`.
result: This will be appended to the list in :attr:`results` which
corresponds to the ``task_name`` in ``task_name``:attr:`tasks`.
'''
with open(self.filepath, 'rb') as f:
existing_results = pickle.load(f)
if task_name not in self.tasks:
self._add_task(task_name)
existing_results['tasks'].append(task_name)
existing_results['results'].append([])
task_name_idx = existing_results['tasks'].index(task_name)
results = existing_results['results'][task_name_idx]
results.append(result)
with open(self.filepath, 'wb') as f:
pickle.dump(existing_results, f) | [
"def",
"update",
"(",
"self",
",",
"task_name",
",",
"result",
")",
":",
"with",
"open",
"(",
"self",
".",
"filepath",
",",
"'rb'",
")",
"as",
"f",
":",
"existing_results",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"if",
"task_name",
"not",
"in",
... | Update the results file with new information.
Args:
task_name (str): Name of the currently running task. A previously unseen
``task_name`` will create a new entry in both :attr:`tasks`
and :attr:`results`.
result: This will be appended to the list in :attr:`results` which
corresponds to the ``task_name`` in ``task_name``:attr:`tasks`. | [
"Update",
"the",
"results",
"file",
"with",
"new",
"information",
"."
] | 3ed904b2cbed16d3bab368bb9ca5adc876d3ce69 | https://github.com/pytorch/tnt/blob/3ed904b2cbed16d3bab368bb9ca5adc876d3ce69/torchnet/utils/resultswriter.py#L49-L70 |
235,672 | onelogin/python3-saml | src/onelogin/saml2/xml_utils.py | OneLogin_Saml2_XML.query | def query(dom, query, context=None, tagid=None):
"""
Extracts nodes that match the query from the Element
:param dom: The root of the lxml objet
:type: Element
:param query: Xpath Expresion
:type: string
:param context: Context Node
:type: DOMElement
:param tagid: Tag ID
:type query: String
:returns: The queried nodes
:rtype: list
"""
if context is None:
source = dom
else:
source = context
if tagid is None:
return source.xpath(query, namespaces=OneLogin_Saml2_Constants.NSMAP)
else:
return source.xpath(query, tagid=tagid, namespaces=OneLogin_Saml2_Constants.NSMAP) | python | def query(dom, query, context=None, tagid=None):
if context is None:
source = dom
else:
source = context
if tagid is None:
return source.xpath(query, namespaces=OneLogin_Saml2_Constants.NSMAP)
else:
return source.xpath(query, tagid=tagid, namespaces=OneLogin_Saml2_Constants.NSMAP) | [
"def",
"query",
"(",
"dom",
",",
"query",
",",
"context",
"=",
"None",
",",
"tagid",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"source",
"=",
"dom",
"else",
":",
"source",
"=",
"context",
"if",
"tagid",
"is",
"None",
":",
"return",... | Extracts nodes that match the query from the Element
:param dom: The root of the lxml objet
:type: Element
:param query: Xpath Expresion
:type: string
:param context: Context Node
:type: DOMElement
:param tagid: Tag ID
:type query: String
:returns: The queried nodes
:rtype: list | [
"Extracts",
"nodes",
"that",
"match",
"the",
"query",
"from",
"the",
"Element"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/xml_utils.py#L107-L134 |
235,673 | onelogin/python3-saml | src/onelogin/saml2/idp_metadata_parser.py | dict_deep_merge | def dict_deep_merge(a, b, path=None):
"""Deep-merge dictionary `b` into dictionary `a`.
Kudos to http://stackoverflow.com/a/7205107/145400
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
dict_deep_merge(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
# Key conflict, but equal value.
pass
else:
# Key/value conflict. Prioritize b over a.
a[key] = b[key]
else:
a[key] = b[key]
return a | python | def dict_deep_merge(a, b, path=None):
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
dict_deep_merge(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
# Key conflict, but equal value.
pass
else:
# Key/value conflict. Prioritize b over a.
a[key] = b[key]
else:
a[key] = b[key]
return a | [
"def",
"dict_deep_merge",
"(",
"a",
",",
"b",
",",
"path",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"[",
"]",
"for",
"key",
"in",
"b",
":",
"if",
"key",
"in",
"a",
":",
"if",
"isinstance",
"(",
"a",
"[",
"key",
"]"... | Deep-merge dictionary `b` into dictionary `a`.
Kudos to http://stackoverflow.com/a/7205107/145400 | [
"Deep",
"-",
"merge",
"dictionary",
"b",
"into",
"dictionary",
"a",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/idp_metadata_parser.py#L248-L267 |
235,674 | onelogin/python3-saml | src/onelogin/saml2/settings.py | OneLogin_Saml2_Settings.__load_paths | def __load_paths(self, base_path=None):
"""
Set the paths of the different folders
"""
if base_path is None:
base_path = dirname(dirname(dirname(__file__)))
if not base_path.endswith(sep):
base_path += sep
self.__paths = {
'base': base_path,
'cert': base_path + 'certs' + sep,
'lib': base_path + 'lib' + sep,
'extlib': base_path + 'extlib' + sep,
} | python | def __load_paths(self, base_path=None):
if base_path is None:
base_path = dirname(dirname(dirname(__file__)))
if not base_path.endswith(sep):
base_path += sep
self.__paths = {
'base': base_path,
'cert': base_path + 'certs' + sep,
'lib': base_path + 'lib' + sep,
'extlib': base_path + 'extlib' + sep,
} | [
"def",
"__load_paths",
"(",
"self",
",",
"base_path",
"=",
"None",
")",
":",
"if",
"base_path",
"is",
"None",
":",
"base_path",
"=",
"dirname",
"(",
"dirname",
"(",
"dirname",
"(",
"__file__",
")",
")",
")",
"if",
"not",
"base_path",
".",
"endswith",
"... | Set the paths of the different folders | [
"Set",
"the",
"paths",
"of",
"the",
"different",
"folders"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L130-L143 |
235,675 | onelogin/python3-saml | src/onelogin/saml2/settings.py | OneLogin_Saml2_Settings.__update_paths | def __update_paths(self, settings):
"""
Set custom paths if necessary
"""
if not isinstance(settings, dict):
return
if 'custom_base_path' in settings:
base_path = settings['custom_base_path']
base_path = join(dirname(__file__), base_path)
self.__load_paths(base_path) | python | def __update_paths(self, settings):
if not isinstance(settings, dict):
return
if 'custom_base_path' in settings:
base_path = settings['custom_base_path']
base_path = join(dirname(__file__), base_path)
self.__load_paths(base_path) | [
"def",
"__update_paths",
"(",
"self",
",",
"settings",
")",
":",
"if",
"not",
"isinstance",
"(",
"settings",
",",
"dict",
")",
":",
"return",
"if",
"'custom_base_path'",
"in",
"settings",
":",
"base_path",
"=",
"settings",
"[",
"'custom_base_path'",
"]",
"ba... | Set custom paths if necessary | [
"Set",
"custom",
"paths",
"if",
"necessary"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L145-L155 |
235,676 | onelogin/python3-saml | src/onelogin/saml2/settings.py | OneLogin_Saml2_Settings.__load_settings_from_dict | def __load_settings_from_dict(self, settings):
"""
Loads settings info from a settings Dict
:param settings: SAML Toolkit Settings
:type settings: dict
:returns: True if the settings info is valid
:rtype: boolean
"""
errors = self.check_settings(settings)
if len(errors) == 0:
self.__errors = []
self.__sp = settings['sp']
self.__idp = settings.get('idp', {})
self.__strict = settings.get('strict', False)
self.__debug = settings.get('debug', False)
self.__security = settings.get('security', {})
self.__contacts = settings.get('contactPerson', {})
self.__organization = settings.get('organization', {})
self.__add_default_values()
return True
self.__errors = errors
return False | python | def __load_settings_from_dict(self, settings):
errors = self.check_settings(settings)
if len(errors) == 0:
self.__errors = []
self.__sp = settings['sp']
self.__idp = settings.get('idp', {})
self.__strict = settings.get('strict', False)
self.__debug = settings.get('debug', False)
self.__security = settings.get('security', {})
self.__contacts = settings.get('contactPerson', {})
self.__organization = settings.get('organization', {})
self.__add_default_values()
return True
self.__errors = errors
return False | [
"def",
"__load_settings_from_dict",
"(",
"self",
",",
"settings",
")",
":",
"errors",
"=",
"self",
".",
"check_settings",
"(",
"settings",
")",
"if",
"len",
"(",
"errors",
")",
"==",
"0",
":",
"self",
".",
"__errors",
"=",
"[",
"]",
"self",
".",
"__sp"... | Loads settings info from a settings Dict
:param settings: SAML Toolkit Settings
:type settings: dict
:returns: True if the settings info is valid
:rtype: boolean | [
"Loads",
"settings",
"info",
"from",
"a",
"settings",
"Dict"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L202-L227 |
235,677 | onelogin/python3-saml | src/onelogin/saml2/settings.py | OneLogin_Saml2_Settings.check_settings | def check_settings(self, settings):
"""
Checks the settings info.
:param settings: Dict with settings data
:type settings: dict
:returns: Errors found on the settings data
:rtype: list
"""
assert isinstance(settings, dict)
errors = []
if not isinstance(settings, dict) or len(settings) == 0:
errors.append('invalid_syntax')
else:
if not self.__sp_validation_only:
errors += self.check_idp_settings(settings)
sp_errors = self.check_sp_settings(settings)
errors += sp_errors
return errors | python | def check_settings(self, settings):
assert isinstance(settings, dict)
errors = []
if not isinstance(settings, dict) or len(settings) == 0:
errors.append('invalid_syntax')
else:
if not self.__sp_validation_only:
errors += self.check_idp_settings(settings)
sp_errors = self.check_sp_settings(settings)
errors += sp_errors
return errors | [
"def",
"check_settings",
"(",
"self",
",",
"settings",
")",
":",
"assert",
"isinstance",
"(",
"settings",
",",
"dict",
")",
"errors",
"=",
"[",
"]",
"if",
"not",
"isinstance",
"(",
"settings",
",",
"dict",
")",
"or",
"len",
"(",
"settings",
")",
"==",
... | Checks the settings info.
:param settings: Dict with settings data
:type settings: dict
:returns: Errors found on the settings data
:rtype: list | [
"Checks",
"the",
"settings",
"info",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L315-L336 |
235,678 | onelogin/python3-saml | src/onelogin/saml2/settings.py | OneLogin_Saml2_Settings.format_idp_cert_multi | def format_idp_cert_multi(self):
"""
Formats the Multple IdP certs.
"""
if 'x509certMulti' in self.__idp:
if 'signing' in self.__idp['x509certMulti']:
for idx in range(len(self.__idp['x509certMulti']['signing'])):
self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx])
if 'encryption' in self.__idp['x509certMulti']:
for idx in range(len(self.__idp['x509certMulti']['encryption'])):
self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx]) | python | def format_idp_cert_multi(self):
if 'x509certMulti' in self.__idp:
if 'signing' in self.__idp['x509certMulti']:
for idx in range(len(self.__idp['x509certMulti']['signing'])):
self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['signing'][idx])
if 'encryption' in self.__idp['x509certMulti']:
for idx in range(len(self.__idp['x509certMulti']['encryption'])):
self.__idp['x509certMulti']['encryption'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp['x509certMulti']['encryption'][idx]) | [
"def",
"format_idp_cert_multi",
"(",
"self",
")",
":",
"if",
"'x509certMulti'",
"in",
"self",
".",
"__idp",
":",
"if",
"'signing'",
"in",
"self",
".",
"__idp",
"[",
"'x509certMulti'",
"]",
":",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"self",
".",
... | Formats the Multple IdP certs. | [
"Formats",
"the",
"Multple",
"IdP",
"certs",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/settings.py#L730-L741 |
235,679 | onelogin/python3-saml | src/onelogin/saml2/utils.py | return_false_on_exception | def return_false_on_exception(func):
"""
Decorator. When applied to a function, it will, by default, suppress any exceptions
raised by that function and return False. It may be overridden by passing a
"raise_exceptions" keyword argument when calling the wrapped function.
"""
@wraps(func)
def exceptfalse(*args, **kwargs):
if not kwargs.pop('raise_exceptions', False):
try:
return func(*args, **kwargs)
except Exception:
return False
else:
return func(*args, **kwargs)
return exceptfalse | python | def return_false_on_exception(func):
@wraps(func)
def exceptfalse(*args, **kwargs):
if not kwargs.pop('raise_exceptions', False):
try:
return func(*args, **kwargs)
except Exception:
return False
else:
return func(*args, **kwargs)
return exceptfalse | [
"def",
"return_false_on_exception",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"exceptfalse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"pop",
"(",
"'raise_exceptions'",
",",
"False",
")",
":",
... | Decorator. When applied to a function, it will, by default, suppress any exceptions
raised by that function and return False. It may be overridden by passing a
"raise_exceptions" keyword argument when calling the wrapped function. | [
"Decorator",
".",
"When",
"applied",
"to",
"a",
"function",
"it",
"will",
"by",
"default",
"suppress",
"any",
"exceptions",
"raised",
"by",
"that",
"function",
"and",
"return",
"False",
".",
"It",
"may",
"be",
"overridden",
"by",
"passing",
"a",
"raise_excep... | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L39-L54 |
235,680 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.is_https | def is_https(request_data):
"""
Checks if https or http.
:param request_data: The request as a dict
:type: dict
:return: False if https is not active
:rtype: boolean
"""
is_https = 'https' in request_data and request_data['https'] != 'off'
is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443')
return is_https | python | def is_https(request_data):
is_https = 'https' in request_data and request_data['https'] != 'off'
is_https = is_https or ('server_port' in request_data and str(request_data['server_port']) == '443')
return is_https | [
"def",
"is_https",
"(",
"request_data",
")",
":",
"is_https",
"=",
"'https'",
"in",
"request_data",
"and",
"request_data",
"[",
"'https'",
"]",
"!=",
"'off'",
"is_https",
"=",
"is_https",
"or",
"(",
"'server_port'",
"in",
"request_data",
"and",
"str",
"(",
"... | Checks if https or http.
:param request_data: The request as a dict
:type: dict
:return: False if https is not active
:rtype: boolean | [
"Checks",
"if",
"https",
"or",
"http",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L300-L312 |
235,681 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.get_self_url_no_query | def get_self_url_no_query(request_data):
"""
Returns the URL of the current host + current view.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view
:rtype: string
"""
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
script_name = request_data['script_name']
if script_name:
if script_name[0] != '/':
script_name = '/' + script_name
else:
script_name = ''
self_url_no_query = self_url_host + script_name
if 'path_info' in request_data:
self_url_no_query += request_data['path_info']
return self_url_no_query | python | def get_self_url_no_query(request_data):
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
script_name = request_data['script_name']
if script_name:
if script_name[0] != '/':
script_name = '/' + script_name
else:
script_name = ''
self_url_no_query = self_url_host + script_name
if 'path_info' in request_data:
self_url_no_query += request_data['path_info']
return self_url_no_query | [
"def",
"get_self_url_no_query",
"(",
"request_data",
")",
":",
"self_url_host",
"=",
"OneLogin_Saml2_Utils",
".",
"get_self_url_host",
"(",
"request_data",
")",
"script_name",
"=",
"request_data",
"[",
"'script_name'",
"]",
"if",
"script_name",
":",
"if",
"script_name... | Returns the URL of the current host + current view.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view
:rtype: string | [
"Returns",
"the",
"URL",
"of",
"the",
"current",
"host",
"+",
"current",
"view",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L315-L336 |
235,682 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.get_self_routed_url_no_query | def get_self_routed_url_no_query(request_data):
"""
Returns the routed URL of the current host + current view.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view
:rtype: string
"""
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
route = ''
if 'request_uri' in request_data and request_data['request_uri']:
route = request_data['request_uri']
if 'query_string' in request_data and request_data['query_string']:
route = route.replace(request_data['query_string'], '')
return self_url_host + route | python | def get_self_routed_url_no_query(request_data):
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
route = ''
if 'request_uri' in request_data and request_data['request_uri']:
route = request_data['request_uri']
if 'query_string' in request_data and request_data['query_string']:
route = route.replace(request_data['query_string'], '')
return self_url_host + route | [
"def",
"get_self_routed_url_no_query",
"(",
"request_data",
")",
":",
"self_url_host",
"=",
"OneLogin_Saml2_Utils",
".",
"get_self_url_host",
"(",
"request_data",
")",
"route",
"=",
"''",
"if",
"'request_uri'",
"in",
"request_data",
"and",
"request_data",
"[",
"'reque... | Returns the routed URL of the current host + current view.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view
:rtype: string | [
"Returns",
"the",
"routed",
"URL",
"of",
"the",
"current",
"host",
"+",
"current",
"view",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L339-L356 |
235,683 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.get_self_url | def get_self_url(request_data):
"""
Returns the URL of the current host + current view + query.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view + query
:rtype: string
"""
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
request_uri = ''
if 'request_uri' in request_data:
request_uri = request_data['request_uri']
if not request_uri.startswith('/'):
match = re.search('^https?://[^/]*(/.*)', request_uri)
if match is not None:
request_uri = match.groups()[0]
return self_url_host + request_uri | python | def get_self_url(request_data):
self_url_host = OneLogin_Saml2_Utils.get_self_url_host(request_data)
request_uri = ''
if 'request_uri' in request_data:
request_uri = request_data['request_uri']
if not request_uri.startswith('/'):
match = re.search('^https?://[^/]*(/.*)', request_uri)
if match is not None:
request_uri = match.groups()[0]
return self_url_host + request_uri | [
"def",
"get_self_url",
"(",
"request_data",
")",
":",
"self_url_host",
"=",
"OneLogin_Saml2_Utils",
".",
"get_self_url_host",
"(",
"request_data",
")",
"request_uri",
"=",
"''",
"if",
"'request_uri'",
"in",
"request_data",
":",
"request_uri",
"=",
"request_data",
"[... | Returns the URL of the current host + current view + query.
:param request_data: The request as a dict
:type: dict
:return: The url of current host + current view + query
:rtype: string | [
"Returns",
"the",
"URL",
"of",
"the",
"current",
"host",
"+",
"current",
"view",
"+",
"query",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L359-L379 |
235,684 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.get_expire_time | def get_expire_time(cache_duration=None, valid_until=None):
"""
Compares 2 dates and returns the earliest.
:param cache_duration: The duration, as a string.
:type: string
:param valid_until: The valid until date, as a string or as a timestamp
:type: string
:return: The expiration time.
:rtype: int
"""
expire_time = None
if cache_duration is not None:
expire_time = OneLogin_Saml2_Utils.parse_duration(cache_duration)
if valid_until is not None:
if isinstance(valid_until, int):
valid_until_time = valid_until
else:
valid_until_time = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
if expire_time is None or expire_time > valid_until_time:
expire_time = valid_until_time
if expire_time is not None:
return '%d' % expire_time
return None | python | def get_expire_time(cache_duration=None, valid_until=None):
expire_time = None
if cache_duration is not None:
expire_time = OneLogin_Saml2_Utils.parse_duration(cache_duration)
if valid_until is not None:
if isinstance(valid_until, int):
valid_until_time = valid_until
else:
valid_until_time = OneLogin_Saml2_Utils.parse_SAML_to_time(valid_until)
if expire_time is None or expire_time > valid_until_time:
expire_time = valid_until_time
if expire_time is not None:
return '%d' % expire_time
return None | [
"def",
"get_expire_time",
"(",
"cache_duration",
"=",
"None",
",",
"valid_until",
"=",
"None",
")",
":",
"expire_time",
"=",
"None",
"if",
"cache_duration",
"is",
"not",
"None",
":",
"expire_time",
"=",
"OneLogin_Saml2_Utils",
".",
"parse_duration",
"(",
"cache_... | Compares 2 dates and returns the earliest.
:param cache_duration: The duration, as a string.
:type: string
:param valid_until: The valid until date, as a string or as a timestamp
:type: string
:return: The expiration time.
:rtype: int | [
"Compares",
"2",
"dates",
"and",
"returns",
"the",
"earliest",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L458-L486 |
235,685 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.calculate_x509_fingerprint | def calculate_x509_fingerprint(x509_cert, alg='sha1'):
"""
Calculates the fingerprint of a formatted x509cert.
:param x509_cert: x509 cert formatted
:type: string
:param alg: The algorithm to build the fingerprint
:type: string
:returns: fingerprint
:rtype: string
"""
assert isinstance(x509_cert, compat.str_type)
lines = x509_cert.split('\n')
data = ''
inData = False
for line in lines:
# Remove '\r' from end of line if present.
line = line.rstrip()
if not inData:
if line == '-----BEGIN CERTIFICATE-----':
inData = True
elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----':
# This isn't an X509 certificate.
return None
else:
if line == '-----END CERTIFICATE-----':
break
# Append the current line to the certificate data.
data += line
if not data:
return None
decoded_data = base64.b64decode(compat.to_bytes(data))
if alg == 'sha512':
fingerprint = sha512(decoded_data)
elif alg == 'sha384':
fingerprint = sha384(decoded_data)
elif alg == 'sha256':
fingerprint = sha256(decoded_data)
else:
fingerprint = sha1(decoded_data)
return fingerprint.hexdigest().lower() | python | def calculate_x509_fingerprint(x509_cert, alg='sha1'):
assert isinstance(x509_cert, compat.str_type)
lines = x509_cert.split('\n')
data = ''
inData = False
for line in lines:
# Remove '\r' from end of line if present.
line = line.rstrip()
if not inData:
if line == '-----BEGIN CERTIFICATE-----':
inData = True
elif line == '-----BEGIN PUBLIC KEY-----' or line == '-----BEGIN RSA PRIVATE KEY-----':
# This isn't an X509 certificate.
return None
else:
if line == '-----END CERTIFICATE-----':
break
# Append the current line to the certificate data.
data += line
if not data:
return None
decoded_data = base64.b64decode(compat.to_bytes(data))
if alg == 'sha512':
fingerprint = sha512(decoded_data)
elif alg == 'sha384':
fingerprint = sha384(decoded_data)
elif alg == 'sha256':
fingerprint = sha256(decoded_data)
else:
fingerprint = sha1(decoded_data)
return fingerprint.hexdigest().lower() | [
"def",
"calculate_x509_fingerprint",
"(",
"x509_cert",
",",
"alg",
"=",
"'sha1'",
")",
":",
"assert",
"isinstance",
"(",
"x509_cert",
",",
"compat",
".",
"str_type",
")",
"lines",
"=",
"x509_cert",
".",
"split",
"(",
"'\\n'",
")",
"data",
"=",
"''",
"inDat... | Calculates the fingerprint of a formatted x509cert.
:param x509_cert: x509 cert formatted
:type: string
:param alg: The algorithm to build the fingerprint
:type: string
:returns: fingerprint
:rtype: string | [
"Calculates",
"the",
"fingerprint",
"of",
"a",
"formatted",
"x509cert",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L498-L547 |
235,686 | onelogin/python3-saml | src/onelogin/saml2/utils.py | OneLogin_Saml2_Utils.sign_binary | def sign_binary(msg, key, algorithm=xmlsec.Transform.RSA_SHA1, debug=False):
"""
Sign binary message
:param msg: The element we should validate
:type: bytes
:param key: The private key
:type: string
:param debug: Activate the xmlsec debug
:type: bool
:return signed message
:rtype str
"""
if isinstance(msg, str):
msg = msg.encode('utf8')
xmlsec.enable_debug_trace(debug)
dsig_ctx = xmlsec.SignatureContext()
dsig_ctx.key = xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None)
return dsig_ctx.sign_binary(compat.to_bytes(msg), algorithm) | python | def sign_binary(msg, key, algorithm=xmlsec.Transform.RSA_SHA1, debug=False):
if isinstance(msg, str):
msg = msg.encode('utf8')
xmlsec.enable_debug_trace(debug)
dsig_ctx = xmlsec.SignatureContext()
dsig_ctx.key = xmlsec.Key.from_memory(key, xmlsec.KeyFormat.PEM, None)
return dsig_ctx.sign_binary(compat.to_bytes(msg), algorithm) | [
"def",
"sign_binary",
"(",
"msg",
",",
"key",
",",
"algorithm",
"=",
"xmlsec",
".",
"Transform",
".",
"RSA_SHA1",
",",
"debug",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"str",
")",
":",
"msg",
"=",
"msg",
".",
"encode",
"(",
"'u... | Sign binary message
:param msg: The element we should validate
:type: bytes
:param key: The private key
:type: string
:param debug: Activate the xmlsec debug
:type: bool
:return signed message
:rtype str | [
"Sign",
"binary",
"message"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/utils.py#L986-L1009 |
235,687 | onelogin/python3-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.process_response | def process_response(self, request_id=None):
"""
Process the SAML Response sent by the IdP.
:param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP.
:type request_id: string
:raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found
"""
self.__errors = []
self.__error_reason = None
if 'post_data' in self.__request_data and 'SAMLResponse' in self.__request_data['post_data']:
# AuthnResponse -- HTTP_POST Binding
response = OneLogin_Saml2_Response(self.__settings, self.__request_data['post_data']['SAMLResponse'])
self.__last_response = response.get_xml_document()
if response.is_valid(self.__request_data, request_id):
self.__attributes = response.get_attributes()
self.__nameid = response.get_nameid()
self.__nameid_format = response.get_nameid_format()
self.__session_index = response.get_session_index()
self.__session_expiration = response.get_session_not_on_or_after()
self.__last_message_id = response.get_id()
self.__last_assertion_id = response.get_assertion_id()
self.__last_authn_contexts = response.get_authn_contexts()
self.__authenticated = True
self.__last_assertion_not_on_or_after = response.get_assertion_not_on_or_after()
else:
self.__errors.append('invalid_response')
self.__error_reason = response.get_error()
else:
self.__errors.append('invalid_binding')
raise OneLogin_Saml2_Error(
'SAML Response not found, Only supported HTTP_POST Binding',
OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND
) | python | def process_response(self, request_id=None):
self.__errors = []
self.__error_reason = None
if 'post_data' in self.__request_data and 'SAMLResponse' in self.__request_data['post_data']:
# AuthnResponse -- HTTP_POST Binding
response = OneLogin_Saml2_Response(self.__settings, self.__request_data['post_data']['SAMLResponse'])
self.__last_response = response.get_xml_document()
if response.is_valid(self.__request_data, request_id):
self.__attributes = response.get_attributes()
self.__nameid = response.get_nameid()
self.__nameid_format = response.get_nameid_format()
self.__session_index = response.get_session_index()
self.__session_expiration = response.get_session_not_on_or_after()
self.__last_message_id = response.get_id()
self.__last_assertion_id = response.get_assertion_id()
self.__last_authn_contexts = response.get_authn_contexts()
self.__authenticated = True
self.__last_assertion_not_on_or_after = response.get_assertion_not_on_or_after()
else:
self.__errors.append('invalid_response')
self.__error_reason = response.get_error()
else:
self.__errors.append('invalid_binding')
raise OneLogin_Saml2_Error(
'SAML Response not found, Only supported HTTP_POST Binding',
OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND
) | [
"def",
"process_response",
"(",
"self",
",",
"request_id",
"=",
"None",
")",
":",
"self",
".",
"__errors",
"=",
"[",
"]",
"self",
".",
"__error_reason",
"=",
"None",
"if",
"'post_data'",
"in",
"self",
".",
"__request_data",
"and",
"'SAMLResponse'",
"in",
"... | Process the SAML Response sent by the IdP.
:param request_id: Is an optional argument. Is the ID of the AuthNRequest sent by this SP to the IdP.
:type request_id: string
:raises: OneLogin_Saml2_Error.SAML_RESPONSE_NOT_FOUND, when a POST with a SAMLResponse is not found | [
"Process",
"the",
"SAML",
"Response",
"sent",
"by",
"the",
"IdP",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L89-L127 |
235,688 | onelogin/python3-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.redirect_to | def redirect_to(self, url=None, parameters={}):
"""
Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request.
:param url: The target URL to redirect the user
:type url: string
:param parameters: Extra parameters to be passed as part of the URL
:type parameters: dict
:returns: Redirection URL
"""
if url is None and 'RelayState' in self.__request_data['get_data']:
url = self.__request_data['get_data']['RelayState']
return OneLogin_Saml2_Utils.redirect(url, parameters, request_data=self.__request_data) | python | def redirect_to(self, url=None, parameters={}):
if url is None and 'RelayState' in self.__request_data['get_data']:
url = self.__request_data['get_data']['RelayState']
return OneLogin_Saml2_Utils.redirect(url, parameters, request_data=self.__request_data) | [
"def",
"redirect_to",
"(",
"self",
",",
"url",
"=",
"None",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"if",
"url",
"is",
"None",
"and",
"'RelayState'",
"in",
"self",
".",
"__request_data",
"[",
"'get_data'",
"]",
":",
"url",
"=",
"self",
".",
"__re... | Redirects the user to the URL passed by parameter or to the URL that we defined in our SSO Request.
:param url: The target URL to redirect the user
:type url: string
:param parameters: Extra parameters to be passed as part of the URL
:type parameters: dict
:returns: Redirection URL | [
"Redirects",
"the",
"user",
"to",
"the",
"URL",
"passed",
"by",
"parameter",
"or",
"to",
"the",
"URL",
"that",
"we",
"defined",
"in",
"our",
"SSO",
"Request",
"."
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L197-L210 |
235,689 | onelogin/python3-saml | src/onelogin/saml2/auth.py | OneLogin_Saml2_Auth.__build_sign_query | def __build_sign_query(saml_data, relay_state, algorithm, saml_type, lowercase_urlencoding=False):
"""
Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Signature Algorithm
:type algorithm: str
:param saml_type: The target URL the user should be redirected to
:type saml_type: string SAMLRequest | SAMLResponse
:param lowercase_urlencoding: lowercase or no
:type lowercase_urlencoding: boolean
"""
sign_data = ['%s=%s' % (saml_type, OneLogin_Saml2_Utils.escape_url(saml_data, lowercase_urlencoding))]
if relay_state is not None:
sign_data.append('RelayState=%s' % OneLogin_Saml2_Utils.escape_url(relay_state, lowercase_urlencoding))
sign_data.append('SigAlg=%s' % OneLogin_Saml2_Utils.escape_url(algorithm, lowercase_urlencoding))
return '&'.join(sign_data) | python | def __build_sign_query(saml_data, relay_state, algorithm, saml_type, lowercase_urlencoding=False):
sign_data = ['%s=%s' % (saml_type, OneLogin_Saml2_Utils.escape_url(saml_data, lowercase_urlencoding))]
if relay_state is not None:
sign_data.append('RelayState=%s' % OneLogin_Saml2_Utils.escape_url(relay_state, lowercase_urlencoding))
sign_data.append('SigAlg=%s' % OneLogin_Saml2_Utils.escape_url(algorithm, lowercase_urlencoding))
return '&'.join(sign_data) | [
"def",
"__build_sign_query",
"(",
"saml_data",
",",
"relay_state",
",",
"algorithm",
",",
"saml_type",
",",
"lowercase_urlencoding",
"=",
"False",
")",
":",
"sign_data",
"=",
"[",
"'%s=%s'",
"%",
"(",
"saml_type",
",",
"OneLogin_Saml2_Utils",
".",
"escape_url",
... | Build sign query
:param saml_data: The Request data
:type saml_data: str
:param relay_state: The Relay State
:type relay_state: str
:param algorithm: The Signature Algorithm
:type algorithm: str
:param saml_type: The target URL the user should be redirected to
:type saml_type: string SAMLRequest | SAMLResponse
:param lowercase_urlencoding: lowercase or no
:type lowercase_urlencoding: boolean | [
"Build",
"sign",
"query"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/auth.py#L469-L492 |
235,690 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.check_status | def check_status(self):
"""
Check if the status of the response is success or not
:raises: Exception. If the status is not success
"""
status = OneLogin_Saml2_Utils.get_status(self.document)
code = status.get('code', None)
if code and code != OneLogin_Saml2_Constants.STATUS_SUCCESS:
splited_code = code.split(':')
printable_code = splited_code.pop()
status_exception_msg = 'The status code of the Response was not Success, was %s' % printable_code
status_msg = status.get('msg', None)
if status_msg:
status_exception_msg += ' -> ' + status_msg
raise OneLogin_Saml2_ValidationError(
status_exception_msg,
OneLogin_Saml2_ValidationError.STATUS_CODE_IS_NOT_SUCCESS
) | python | def check_status(self):
status = OneLogin_Saml2_Utils.get_status(self.document)
code = status.get('code', None)
if code and code != OneLogin_Saml2_Constants.STATUS_SUCCESS:
splited_code = code.split(':')
printable_code = splited_code.pop()
status_exception_msg = 'The status code of the Response was not Success, was %s' % printable_code
status_msg = status.get('msg', None)
if status_msg:
status_exception_msg += ' -> ' + status_msg
raise OneLogin_Saml2_ValidationError(
status_exception_msg,
OneLogin_Saml2_ValidationError.STATUS_CODE_IS_NOT_SUCCESS
) | [
"def",
"check_status",
"(",
"self",
")",
":",
"status",
"=",
"OneLogin_Saml2_Utils",
".",
"get_status",
"(",
"self",
".",
"document",
")",
"code",
"=",
"status",
".",
"get",
"(",
"'code'",
",",
"None",
")",
"if",
"code",
"and",
"code",
"!=",
"OneLogin_Sa... | Check if the status of the response is success or not
:raises: Exception. If the status is not success | [
"Check",
"if",
"the",
"status",
"of",
"the",
"response",
"is",
"success",
"or",
"not"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L330-L348 |
235,691 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_authn_contexts | def get_authn_contexts(self):
"""
Gets the authentication contexts
:returns: The authentication classes for the SAML Response
:rtype: list
"""
authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef')
return [OneLogin_Saml2_XML.element_text(node) for node in authn_context_nodes] | python | def get_authn_contexts(self):
authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef')
return [OneLogin_Saml2_XML.element_text(node) for node in authn_context_nodes] | [
"def",
"get_authn_contexts",
"(",
"self",
")",
":",
"authn_context_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef'",
")",
"return",
"[",
"OneLogin_Saml2_XML",
".",
"element_text",
"(",
"node",
")",
"f... | Gets the authentication contexts
:returns: The authentication classes for the SAML Response
:rtype: list | [
"Gets",
"the",
"authentication",
"contexts"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L380-L388 |
235,692 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_nameid | def get_nameid(self):
"""
Gets the NameID provided by the SAML Response from the IdP
:returns: NameID (value)
:rtype: string|None
"""
nameid_value = None
nameid_data = self.get_nameid_data()
if nameid_data and 'Value' in nameid_data.keys():
nameid_value = nameid_data['Value']
return nameid_value | python | def get_nameid(self):
nameid_value = None
nameid_data = self.get_nameid_data()
if nameid_data and 'Value' in nameid_data.keys():
nameid_value = nameid_data['Value']
return nameid_value | [
"def",
"get_nameid",
"(",
"self",
")",
":",
"nameid_value",
"=",
"None",
"nameid_data",
"=",
"self",
".",
"get_nameid_data",
"(",
")",
"if",
"nameid_data",
"and",
"'Value'",
"in",
"nameid_data",
".",
"keys",
"(",
")",
":",
"nameid_value",
"=",
"nameid_data",... | Gets the NameID provided by the SAML Response from the IdP
:returns: NameID (value)
:rtype: string|None | [
"Gets",
"the",
"NameID",
"provided",
"by",
"the",
"SAML",
"Response",
"from",
"the",
"IdP"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L475-L486 |
235,693 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_nameid_format | def get_nameid_format(self):
"""
Gets the NameID Format provided by the SAML Response from the IdP
:returns: NameID Format
:rtype: string|None
"""
nameid_format = None
nameid_data = self.get_nameid_data()
if nameid_data and 'Format' in nameid_data.keys():
nameid_format = nameid_data['Format']
return nameid_format | python | def get_nameid_format(self):
nameid_format = None
nameid_data = self.get_nameid_data()
if nameid_data and 'Format' in nameid_data.keys():
nameid_format = nameid_data['Format']
return nameid_format | [
"def",
"get_nameid_format",
"(",
"self",
")",
":",
"nameid_format",
"=",
"None",
"nameid_data",
"=",
"self",
".",
"get_nameid_data",
"(",
")",
"if",
"nameid_data",
"and",
"'Format'",
"in",
"nameid_data",
".",
"keys",
"(",
")",
":",
"nameid_format",
"=",
"nam... | Gets the NameID Format provided by the SAML Response from the IdP
:returns: NameID Format
:rtype: string|None | [
"Gets",
"the",
"NameID",
"Format",
"provided",
"by",
"the",
"SAML",
"Response",
"from",
"the",
"IdP"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L488-L499 |
235,694 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_session_not_on_or_after | def get_session_not_on_or_after(self):
"""
Gets the SessionNotOnOrAfter from the AuthnStatement
Could be used to set the local session expiration
:returns: The SessionNotOnOrAfter value
:rtype: time|None
"""
not_on_or_after = None
authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionNotOnOrAfter]')
if authn_statement_nodes:
not_on_or_after = OneLogin_Saml2_Utils.parse_SAML_to_time(authn_statement_nodes[0].get('SessionNotOnOrAfter'))
return not_on_or_after | python | def get_session_not_on_or_after(self):
not_on_or_after = None
authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionNotOnOrAfter]')
if authn_statement_nodes:
not_on_or_after = OneLogin_Saml2_Utils.parse_SAML_to_time(authn_statement_nodes[0].get('SessionNotOnOrAfter'))
return not_on_or_after | [
"def",
"get_session_not_on_or_after",
"(",
"self",
")",
":",
"not_on_or_after",
"=",
"None",
"authn_statement_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:AuthnStatement[@SessionNotOnOrAfter]'",
")",
"if",
"authn_statement_nodes",
":",
"not_on_or_after",
"=",... | Gets the SessionNotOnOrAfter from the AuthnStatement
Could be used to set the local session expiration
:returns: The SessionNotOnOrAfter value
:rtype: time|None | [
"Gets",
"the",
"SessionNotOnOrAfter",
"from",
"the",
"AuthnStatement",
"Could",
"be",
"used",
"to",
"set",
"the",
"local",
"session",
"expiration"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L501-L513 |
235,695 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_session_index | def get_session_index(self):
"""
Gets the SessionIndex from the AuthnStatement
Could be used to be stored in the local session in order
to be used in a future Logout Request that the SP could
send to the SP, to set what specific session must be deleted
:returns: The SessionIndex value
:rtype: string|None
"""
session_index = None
authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionIndex]')
if authn_statement_nodes:
session_index = authn_statement_nodes[0].get('SessionIndex')
return session_index | python | def get_session_index(self):
session_index = None
authn_statement_nodes = self.__query_assertion('/saml:AuthnStatement[@SessionIndex]')
if authn_statement_nodes:
session_index = authn_statement_nodes[0].get('SessionIndex')
return session_index | [
"def",
"get_session_index",
"(",
"self",
")",
":",
"session_index",
"=",
"None",
"authn_statement_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:AuthnStatement[@SessionIndex]'",
")",
"if",
"authn_statement_nodes",
":",
"session_index",
"=",
"authn_statement_n... | Gets the SessionIndex from the AuthnStatement
Could be used to be stored in the local session in order
to be used in a future Logout Request that the SP could
send to the SP, to set what specific session must be deleted
:returns: The SessionIndex value
:rtype: string|None | [
"Gets",
"the",
"SessionIndex",
"from",
"the",
"AuthnStatement",
"Could",
"be",
"used",
"to",
"be",
"stored",
"in",
"the",
"local",
"session",
"in",
"order",
"to",
"be",
"used",
"in",
"a",
"future",
"Logout",
"Request",
"that",
"the",
"SP",
"could",
"send",... | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L521-L535 |
235,696 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.get_attributes | def get_attributes(self):
"""
Gets the Attributes from the AttributeStatement element.
EncryptedAttributes are not supported
"""
attributes = {}
attribute_nodes = self.__query_assertion('/saml:AttributeStatement/saml:Attribute')
for attribute_node in attribute_nodes:
attr_name = attribute_node.get('Name')
if attr_name in attributes.keys():
raise OneLogin_Saml2_ValidationError(
'Found an Attribute element with duplicated Name',
OneLogin_Saml2_ValidationError.DUPLICATED_ATTRIBUTE_NAME_FOUND
)
values = []
for attr in attribute_node.iterchildren('{%s}AttributeValue' % OneLogin_Saml2_Constants.NSMAP['saml']):
attr_text = OneLogin_Saml2_XML.element_text(attr)
if attr_text:
attr_text = attr_text.strip()
if attr_text:
values.append(attr_text)
# Parse any nested NameID children
for nameid in attr.iterchildren('{%s}NameID' % OneLogin_Saml2_Constants.NSMAP['saml']):
values.append({
'NameID': {
'Format': nameid.get('Format'),
'NameQualifier': nameid.get('NameQualifier'),
'value': nameid.text
}
})
attributes[attr_name] = values
return attributes | python | def get_attributes(self):
attributes = {}
attribute_nodes = self.__query_assertion('/saml:AttributeStatement/saml:Attribute')
for attribute_node in attribute_nodes:
attr_name = attribute_node.get('Name')
if attr_name in attributes.keys():
raise OneLogin_Saml2_ValidationError(
'Found an Attribute element with duplicated Name',
OneLogin_Saml2_ValidationError.DUPLICATED_ATTRIBUTE_NAME_FOUND
)
values = []
for attr in attribute_node.iterchildren('{%s}AttributeValue' % OneLogin_Saml2_Constants.NSMAP['saml']):
attr_text = OneLogin_Saml2_XML.element_text(attr)
if attr_text:
attr_text = attr_text.strip()
if attr_text:
values.append(attr_text)
# Parse any nested NameID children
for nameid in attr.iterchildren('{%s}NameID' % OneLogin_Saml2_Constants.NSMAP['saml']):
values.append({
'NameID': {
'Format': nameid.get('Format'),
'NameQualifier': nameid.get('NameQualifier'),
'value': nameid.text
}
})
attributes[attr_name] = values
return attributes | [
"def",
"get_attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"{",
"}",
"attribute_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:AttributeStatement/saml:Attribute'",
")",
"for",
"attribute_node",
"in",
"attribute_nodes",
":",
"attr_name",
"=",
"at... | Gets the Attributes from the AttributeStatement element.
EncryptedAttributes are not supported | [
"Gets",
"the",
"Attributes",
"from",
"the",
"AttributeStatement",
"element",
".",
"EncryptedAttributes",
"are",
"not",
"supported"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L537-L570 |
235,697 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.validate_timestamps | def validate_timestamps(self):
"""
Verifies that the document is valid according to Conditions Element
:returns: True if the condition is valid, False otherwise
:rtype: bool
"""
conditions_nodes = self.__query_assertion('/saml:Conditions')
for conditions_node in conditions_nodes:
nb_attr = conditions_node.get('NotBefore')
nooa_attr = conditions_node.get('NotOnOrAfter')
if nb_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nb_attr) > OneLogin_Saml2_Utils.now() + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT:
raise OneLogin_Saml2_ValidationError(
'Could not validate timestamp: not yet valid. Check system clock.',
OneLogin_Saml2_ValidationError.ASSERTION_TOO_EARLY
)
if nooa_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nooa_attr) + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT <= OneLogin_Saml2_Utils.now():
raise OneLogin_Saml2_ValidationError(
'Could not validate timestamp: expired. Check system clock.',
OneLogin_Saml2_ValidationError.ASSERTION_EXPIRED
)
return True | python | def validate_timestamps(self):
conditions_nodes = self.__query_assertion('/saml:Conditions')
for conditions_node in conditions_nodes:
nb_attr = conditions_node.get('NotBefore')
nooa_attr = conditions_node.get('NotOnOrAfter')
if nb_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nb_attr) > OneLogin_Saml2_Utils.now() + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT:
raise OneLogin_Saml2_ValidationError(
'Could not validate timestamp: not yet valid. Check system clock.',
OneLogin_Saml2_ValidationError.ASSERTION_TOO_EARLY
)
if nooa_attr and OneLogin_Saml2_Utils.parse_SAML_to_time(nooa_attr) + OneLogin_Saml2_Constants.ALLOWED_CLOCK_DRIFT <= OneLogin_Saml2_Utils.now():
raise OneLogin_Saml2_ValidationError(
'Could not validate timestamp: expired. Check system clock.',
OneLogin_Saml2_ValidationError.ASSERTION_EXPIRED
)
return True | [
"def",
"validate_timestamps",
"(",
"self",
")",
":",
"conditions_nodes",
"=",
"self",
".",
"__query_assertion",
"(",
"'/saml:Conditions'",
")",
"for",
"conditions_node",
"in",
"conditions_nodes",
":",
"nb_attr",
"=",
"conditions_node",
".",
"get",
"(",
"'NotBefore'"... | Verifies that the document is valid according to Conditions Element
:returns: True if the condition is valid, False otherwise
:rtype: bool | [
"Verifies",
"that",
"the",
"document",
"is",
"valid",
"according",
"to",
"Conditions",
"Element"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L701-L723 |
235,698 | onelogin/python3-saml | src/onelogin/saml2/response.py | OneLogin_Saml2_Response.__query_assertion | def __query_assertion(self, xpath_expr):
"""
Extracts nodes that match the query from the Assertion
:param xpath_expr: Xpath Expresion
:type xpath_expr: String
:returns: The queried nodes
:rtype: list
"""
assertion_expr = '/saml:Assertion'
signature_expr = '/ds:Signature/ds:SignedInfo/ds:Reference'
signed_assertion_query = '/samlp:Response' + assertion_expr + signature_expr
assertion_reference_nodes = self.__query(signed_assertion_query)
tagid = None
if not assertion_reference_nodes:
# Check if the message is signed
signed_message_query = '/samlp:Response' + signature_expr
message_reference_nodes = self.__query(signed_message_query)
if message_reference_nodes:
message_id = message_reference_nodes[0].get('URI')
final_query = "/samlp:Response[@ID=$tagid]/"
tagid = message_id[1:]
else:
final_query = "/samlp:Response"
final_query += assertion_expr
else:
assertion_id = assertion_reference_nodes[0].get('URI')
final_query = '/samlp:Response' + assertion_expr + "[@ID=$tagid]"
tagid = assertion_id[1:]
final_query += xpath_expr
return self.__query(final_query, tagid) | python | def __query_assertion(self, xpath_expr):
assertion_expr = '/saml:Assertion'
signature_expr = '/ds:Signature/ds:SignedInfo/ds:Reference'
signed_assertion_query = '/samlp:Response' + assertion_expr + signature_expr
assertion_reference_nodes = self.__query(signed_assertion_query)
tagid = None
if not assertion_reference_nodes:
# Check if the message is signed
signed_message_query = '/samlp:Response' + signature_expr
message_reference_nodes = self.__query(signed_message_query)
if message_reference_nodes:
message_id = message_reference_nodes[0].get('URI')
final_query = "/samlp:Response[@ID=$tagid]/"
tagid = message_id[1:]
else:
final_query = "/samlp:Response"
final_query += assertion_expr
else:
assertion_id = assertion_reference_nodes[0].get('URI')
final_query = '/samlp:Response' + assertion_expr + "[@ID=$tagid]"
tagid = assertion_id[1:]
final_query += xpath_expr
return self.__query(final_query, tagid) | [
"def",
"__query_assertion",
"(",
"self",
",",
"xpath_expr",
")",
":",
"assertion_expr",
"=",
"'/saml:Assertion'",
"signature_expr",
"=",
"'/ds:Signature/ds:SignedInfo/ds:Reference'",
"signed_assertion_query",
"=",
"'/samlp:Response'",
"+",
"assertion_expr",
"+",
"signature_ex... | Extracts nodes that match the query from the Assertion
:param xpath_expr: Xpath Expresion
:type xpath_expr: String
:returns: The queried nodes
:rtype: list | [
"Extracts",
"nodes",
"that",
"match",
"the",
"query",
"from",
"the",
"Assertion"
] | 064b7275fba1e5f39a9116ba1cdcc5d01fc34daa | https://github.com/onelogin/python3-saml/blob/064b7275fba1e5f39a9116ba1cdcc5d01fc34daa/src/onelogin/saml2/response.py#L725-L758 |
235,699 | automl/HpBandSter | hpbandster/optimizers/kde/mvkde.py | MultivariateKDE.pdf | def pdf(self, x_test):
"""
Computes the probability density function at all x_test
"""
N,D = self.data.shape
x_test = np.asfortranarray(x_test)
x_test = x_test.reshape([-1, D])
pdfs = self._individual_pdfs(x_test)
#import pdb; pdb.set_trace()
# combine values based on fully_dimensional!
if self.fully_dimensional:
# first the product of the individual pdfs for each point in the data across dimensions and then the average (factorized kernel)
pdfs = np.sum(np.prod(pdfs, axis=-1)*self.weights[None, :], axis=-1)
else:
# first the average over the 1d pdfs and the the product over dimensions (TPE like factorization of the pdf)
pdfs = np.prod(np.sum(pdfs*self.weights[None,:,None], axis=-2), axis=-1)
return(pdfs) | python | def pdf(self, x_test):
N,D = self.data.shape
x_test = np.asfortranarray(x_test)
x_test = x_test.reshape([-1, D])
pdfs = self._individual_pdfs(x_test)
#import pdb; pdb.set_trace()
# combine values based on fully_dimensional!
if self.fully_dimensional:
# first the product of the individual pdfs for each point in the data across dimensions and then the average (factorized kernel)
pdfs = np.sum(np.prod(pdfs, axis=-1)*self.weights[None, :], axis=-1)
else:
# first the average over the 1d pdfs and the the product over dimensions (TPE like factorization of the pdf)
pdfs = np.prod(np.sum(pdfs*self.weights[None,:,None], axis=-2), axis=-1)
return(pdfs) | [
"def",
"pdf",
"(",
"self",
",",
"x_test",
")",
":",
"N",
",",
"D",
"=",
"self",
".",
"data",
".",
"shape",
"x_test",
"=",
"np",
".",
"asfortranarray",
"(",
"x_test",
")",
"x_test",
"=",
"x_test",
".",
"reshape",
"(",
"[",
"-",
"1",
",",
"D",
"]... | Computes the probability density function at all x_test | [
"Computes",
"the",
"probability",
"density",
"function",
"at",
"all",
"x_test"
] | 841db4b827f342e5eb7f725723ea6461ac52d45a | https://github.com/automl/HpBandSter/blob/841db4b827f342e5eb7f725723ea6461ac52d45a/hpbandster/optimizers/kde/mvkde.py#L172-L189 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.