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 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
raiden-network/raiden | raiden/transfer/mediated_transfer/initiator.py | next_channel_from_routes | def next_channel_from_routes(
available_routes: List[RouteState],
channelidentifiers_to_channels: ChannelMap,
transfer_amount: PaymentAmount,
) -> Optional[NettingChannelState]:
""" Returns the first channel that can be used to start the transfer.
The routing service can race with local changes, so the recommended routes
must be validated.
"""
for route in available_routes:
channel_identifier = route.channel_identifier
channel_state = channelidentifiers_to_channels.get(channel_identifier)
if not channel_state:
continue
if channel.get_status(channel_state) != CHANNEL_STATE_OPENED:
continue
pending_transfers = channel.get_number_of_pending_transfers(channel_state.our_state)
if pending_transfers >= MAXIMUM_PENDING_TRANSFERS:
continue
distributable = channel.get_distributable(
channel_state.our_state,
channel_state.partner_state,
)
if transfer_amount > distributable:
continue
if channel.is_valid_amount(channel_state.our_state, transfer_amount):
return channel_state
return None | python | def next_channel_from_routes(
available_routes: List[RouteState],
channelidentifiers_to_channels: ChannelMap,
transfer_amount: PaymentAmount,
) -> Optional[NettingChannelState]:
""" Returns the first channel that can be used to start the transfer.
The routing service can race with local changes, so the recommended routes
must be validated.
"""
for route in available_routes:
channel_identifier = route.channel_identifier
channel_state = channelidentifiers_to_channels.get(channel_identifier)
if not channel_state:
continue
if channel.get_status(channel_state) != CHANNEL_STATE_OPENED:
continue
pending_transfers = channel.get_number_of_pending_transfers(channel_state.our_state)
if pending_transfers >= MAXIMUM_PENDING_TRANSFERS:
continue
distributable = channel.get_distributable(
channel_state.our_state,
channel_state.partner_state,
)
if transfer_amount > distributable:
continue
if channel.is_valid_amount(channel_state.our_state, transfer_amount):
return channel_state
return None | [
"def",
"next_channel_from_routes",
"(",
"available_routes",
":",
"List",
"[",
"RouteState",
"]",
",",
"channelidentifiers_to_channels",
":",
"ChannelMap",
",",
"transfer_amount",
":",
"PaymentAmount",
",",
")",
"->",
"Optional",
"[",
"NettingChannelState",
"]",
":",
... | Returns the first channel that can be used to start the transfer.
The routing service can race with local changes, so the recommended routes
must be validated. | [
"Returns",
"the",
"first",
"channel",
"that",
"can",
"be",
"used",
"to",
"start",
"the",
"transfer",
".",
"The",
"routing",
"service",
"can",
"race",
"with",
"local",
"changes",
"so",
"the",
"recommended",
"routes",
"must",
"be",
"validated",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L178-L211 | train | 216,600 |
raiden-network/raiden | raiden/transfer/mediated_transfer/initiator.py | send_lockedtransfer | def send_lockedtransfer(
transfer_description: TransferDescriptionWithSecretState,
channel_state: NettingChannelState,
message_identifier: MessageID,
block_number: BlockNumber,
) -> SendLockedTransfer:
""" Create a mediated transfer using channel. """
assert channel_state.token_network_identifier == transfer_description.token_network_identifier
lock_expiration = get_initial_lock_expiration(
block_number,
channel_state.reveal_timeout,
)
# The payment amount and the fee amount must be included in the locked
# amount, as a guarantee to the mediator that the fee will be claimable
# on-chain.
total_amount = PaymentWithFeeAmount(
transfer_description.amount + transfer_description.allocated_fee,
)
lockedtransfer_event = channel.send_lockedtransfer(
channel_state=channel_state,
initiator=transfer_description.initiator,
target=transfer_description.target,
amount=total_amount,
message_identifier=message_identifier,
payment_identifier=transfer_description.payment_identifier,
expiration=lock_expiration,
secrethash=transfer_description.secrethash,
)
return lockedtransfer_event | python | def send_lockedtransfer(
transfer_description: TransferDescriptionWithSecretState,
channel_state: NettingChannelState,
message_identifier: MessageID,
block_number: BlockNumber,
) -> SendLockedTransfer:
""" Create a mediated transfer using channel. """
assert channel_state.token_network_identifier == transfer_description.token_network_identifier
lock_expiration = get_initial_lock_expiration(
block_number,
channel_state.reveal_timeout,
)
# The payment amount and the fee amount must be included in the locked
# amount, as a guarantee to the mediator that the fee will be claimable
# on-chain.
total_amount = PaymentWithFeeAmount(
transfer_description.amount + transfer_description.allocated_fee,
)
lockedtransfer_event = channel.send_lockedtransfer(
channel_state=channel_state,
initiator=transfer_description.initiator,
target=transfer_description.target,
amount=total_amount,
message_identifier=message_identifier,
payment_identifier=transfer_description.payment_identifier,
expiration=lock_expiration,
secrethash=transfer_description.secrethash,
)
return lockedtransfer_event | [
"def",
"send_lockedtransfer",
"(",
"transfer_description",
":",
"TransferDescriptionWithSecretState",
",",
"channel_state",
":",
"NettingChannelState",
",",
"message_identifier",
":",
"MessageID",
",",
"block_number",
":",
"BlockNumber",
",",
")",
"->",
"SendLockedTransfer"... | Create a mediated transfer using channel. | [
"Create",
"a",
"mediated",
"transfer",
"using",
"channel",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L267-L298 | train | 216,601 |
raiden-network/raiden | raiden/transfer/mediated_transfer/initiator.py | handle_offchain_secretreveal | def handle_offchain_secretreveal(
initiator_state: InitiatorTransferState,
state_change: ReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorTransferState]:
""" Once the next hop proves it knows the secret, the initiator can unlock
the mediated transfer.
This will validate the secret, and if valid a new balance proof is sent to
the next hop with the current lock removed from the merkle tree and the
transferred amount updated.
"""
iteration: TransitionResult[InitiatorTransferState]
valid_reveal = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=initiator_state.transfer_description.secrethash,
secret=state_change.secret,
)
sent_by_partner = state_change.sender == channel_state.partner_state.address
is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED
if valid_reveal and is_channel_open and sent_by_partner:
events = events_for_unlock_lock(
initiator_state=initiator_state,
channel_state=channel_state,
secret=state_change.secret,
secrethash=state_change.secrethash,
pseudo_random_generator=pseudo_random_generator,
)
iteration = TransitionResult(None, events)
else:
events = list()
iteration = TransitionResult(initiator_state, events)
return iteration | python | def handle_offchain_secretreveal(
initiator_state: InitiatorTransferState,
state_change: ReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorTransferState]:
""" Once the next hop proves it knows the secret, the initiator can unlock
the mediated transfer.
This will validate the secret, and if valid a new balance proof is sent to
the next hop with the current lock removed from the merkle tree and the
transferred amount updated.
"""
iteration: TransitionResult[InitiatorTransferState]
valid_reveal = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=initiator_state.transfer_description.secrethash,
secret=state_change.secret,
)
sent_by_partner = state_change.sender == channel_state.partner_state.address
is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED
if valid_reveal and is_channel_open and sent_by_partner:
events = events_for_unlock_lock(
initiator_state=initiator_state,
channel_state=channel_state,
secret=state_change.secret,
secrethash=state_change.secrethash,
pseudo_random_generator=pseudo_random_generator,
)
iteration = TransitionResult(None, events)
else:
events = list()
iteration = TransitionResult(initiator_state, events)
return iteration | [
"def",
"handle_offchain_secretreveal",
"(",
"initiator_state",
":",
"InitiatorTransferState",
",",
"state_change",
":",
"ReceiveSecretReveal",
",",
"channel_state",
":",
"NettingChannelState",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
",",
")",
"->",
... | Once the next hop proves it knows the secret, the initiator can unlock
the mediated transfer.
This will validate the secret, and if valid a new balance proof is sent to
the next hop with the current lock removed from the merkle tree and the
transferred amount updated. | [
"Once",
"the",
"next",
"hop",
"proves",
"it",
"knows",
"the",
"secret",
"the",
"initiator",
"can",
"unlock",
"the",
"mediated",
"transfer",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L371-L406 | train | 216,602 |
raiden-network/raiden | raiden/transfer/mediated_transfer/initiator.py | handle_onchain_secretreveal | def handle_onchain_secretreveal(
initiator_state: InitiatorTransferState,
state_change: ContractReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorTransferState]:
""" When a secret is revealed on-chain all nodes learn the secret.
This check the on-chain secret corresponds to the one used by the
initiator, and if valid a new balance proof is sent to the next hop with
the current lock removed from the merkle tree and the transferred amount
updated.
"""
iteration: TransitionResult[InitiatorTransferState]
secret = state_change.secret
secrethash = initiator_state.transfer_description.secrethash
is_valid_secret = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=secrethash,
secret=secret,
)
is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED
is_lock_expired = state_change.block_number > initiator_state.transfer.lock.expiration
is_lock_unlocked = (
is_valid_secret and
not is_lock_expired
)
if is_lock_unlocked:
channel.register_onchain_secret(
channel_state=channel_state,
secret=secret,
secrethash=secrethash,
secret_reveal_block_number=state_change.block_number,
)
if is_lock_unlocked and is_channel_open:
events = events_for_unlock_lock(
initiator_state,
channel_state,
state_change.secret,
state_change.secrethash,
pseudo_random_generator,
)
iteration = TransitionResult(None, events)
else:
events = list()
iteration = TransitionResult(initiator_state, events)
return iteration | python | def handle_onchain_secretreveal(
initiator_state: InitiatorTransferState,
state_change: ContractReceiveSecretReveal,
channel_state: NettingChannelState,
pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorTransferState]:
""" When a secret is revealed on-chain all nodes learn the secret.
This check the on-chain secret corresponds to the one used by the
initiator, and if valid a new balance proof is sent to the next hop with
the current lock removed from the merkle tree and the transferred amount
updated.
"""
iteration: TransitionResult[InitiatorTransferState]
secret = state_change.secret
secrethash = initiator_state.transfer_description.secrethash
is_valid_secret = is_valid_secret_reveal(
state_change=state_change,
transfer_secrethash=secrethash,
secret=secret,
)
is_channel_open = channel.get_status(channel_state) == CHANNEL_STATE_OPENED
is_lock_expired = state_change.block_number > initiator_state.transfer.lock.expiration
is_lock_unlocked = (
is_valid_secret and
not is_lock_expired
)
if is_lock_unlocked:
channel.register_onchain_secret(
channel_state=channel_state,
secret=secret,
secrethash=secrethash,
secret_reveal_block_number=state_change.block_number,
)
if is_lock_unlocked and is_channel_open:
events = events_for_unlock_lock(
initiator_state,
channel_state,
state_change.secret,
state_change.secrethash,
pseudo_random_generator,
)
iteration = TransitionResult(None, events)
else:
events = list()
iteration = TransitionResult(initiator_state, events)
return iteration | [
"def",
"handle_onchain_secretreveal",
"(",
"initiator_state",
":",
"InitiatorTransferState",
",",
"state_change",
":",
"ContractReceiveSecretReveal",
",",
"channel_state",
":",
"NettingChannelState",
",",
"pseudo_random_generator",
":",
"random",
".",
"Random",
",",
")",
... | When a secret is revealed on-chain all nodes learn the secret.
This check the on-chain secret corresponds to the one used by the
initiator, and if valid a new balance proof is sent to the next hop with
the current lock removed from the merkle tree and the transferred amount
updated. | [
"When",
"a",
"secret",
"is",
"revealed",
"on",
"-",
"chain",
"all",
"nodes",
"learn",
"the",
"secret",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/mediated_transfer/initiator.py#L409-L459 | train | 216,603 |
raiden-network/raiden | raiden/transfer/channel.py | is_lock_pending | def is_lock_pending(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> bool:
"""True if the `secrethash` corresponds to a lock that is pending to be claimed
and didn't expire.
"""
return (
secrethash in end_state.secrethashes_to_lockedlocks or
secrethash in end_state.secrethashes_to_unlockedlocks or
secrethash in end_state.secrethashes_to_onchain_unlockedlocks
) | python | def is_lock_pending(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> bool:
"""True if the `secrethash` corresponds to a lock that is pending to be claimed
and didn't expire.
"""
return (
secrethash in end_state.secrethashes_to_lockedlocks or
secrethash in end_state.secrethashes_to_unlockedlocks or
secrethash in end_state.secrethashes_to_onchain_unlockedlocks
) | [
"def",
"is_lock_pending",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
"secrethash",
":",
"SecretHash",
",",
")",
"->",
"bool",
":",
"return",
"(",
"secrethash",
"in",
"end_state",
".",
"secrethashes_to_lockedlocks",
"or",
"secrethash",
"in",
"end_state",
... | True if the `secrethash` corresponds to a lock that is pending to be claimed
and didn't expire. | [
"True",
"if",
"the",
"secrethash",
"corresponds",
"to",
"a",
"lock",
"that",
"is",
"pending",
"to",
"be",
"claimed",
"and",
"didn",
"t",
"expire",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L156-L167 | train | 216,604 |
raiden-network/raiden | raiden/transfer/channel.py | is_deposit_confirmed | def is_deposit_confirmed(
channel_state: NettingChannelState,
block_number: BlockNumber,
) -> bool:
"""True if the block which mined the deposit transaction has been
confirmed.
"""
if not channel_state.deposit_transaction_queue:
return False
return is_transaction_confirmed(
channel_state.deposit_transaction_queue[0].block_number,
block_number,
) | python | def is_deposit_confirmed(
channel_state: NettingChannelState,
block_number: BlockNumber,
) -> bool:
"""True if the block which mined the deposit transaction has been
confirmed.
"""
if not channel_state.deposit_transaction_queue:
return False
return is_transaction_confirmed(
channel_state.deposit_transaction_queue[0].block_number,
block_number,
) | [
"def",
"is_deposit_confirmed",
"(",
"channel_state",
":",
"NettingChannelState",
",",
"block_number",
":",
"BlockNumber",
",",
")",
"->",
"bool",
":",
"if",
"not",
"channel_state",
".",
"deposit_transaction_queue",
":",
"return",
"False",
"return",
"is_transaction_con... | True if the block which mined the deposit transaction has been
confirmed. | [
"True",
"if",
"the",
"block",
"which",
"mined",
"the",
"deposit",
"transaction",
"has",
"been",
"confirmed",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L170-L183 | train | 216,605 |
raiden-network/raiden | raiden/transfer/channel.py | is_lock_expired | def is_lock_expired(
end_state: NettingChannelEndState,
lock: LockType,
block_number: BlockNumber,
lock_expiration_threshold: BlockNumber,
) -> SuccessOrError:
""" Determine whether a lock has expired.
The lock has expired if both:
- The secret was not registered on-chain in time.
- The current block exceeds lock's expiration + confirmation blocks.
"""
secret_registered_on_chain = lock.secrethash in end_state.secrethashes_to_onchain_unlockedlocks
if secret_registered_on_chain:
return (False, 'lock has been unlocked on-chain')
if block_number < lock_expiration_threshold:
msg = (
f'current block number ({block_number}) is not larger than '
f'lock.expiration + confirmation blocks ({lock_expiration_threshold})'
)
return (False, msg)
return (True, None) | python | def is_lock_expired(
end_state: NettingChannelEndState,
lock: LockType,
block_number: BlockNumber,
lock_expiration_threshold: BlockNumber,
) -> SuccessOrError:
""" Determine whether a lock has expired.
The lock has expired if both:
- The secret was not registered on-chain in time.
- The current block exceeds lock's expiration + confirmation blocks.
"""
secret_registered_on_chain = lock.secrethash in end_state.secrethashes_to_onchain_unlockedlocks
if secret_registered_on_chain:
return (False, 'lock has been unlocked on-chain')
if block_number < lock_expiration_threshold:
msg = (
f'current block number ({block_number}) is not larger than '
f'lock.expiration + confirmation blocks ({lock_expiration_threshold})'
)
return (False, msg)
return (True, None) | [
"def",
"is_lock_expired",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
"lock",
":",
"LockType",
",",
"block_number",
":",
"BlockNumber",
",",
"lock_expiration_threshold",
":",
"BlockNumber",
",",
")",
"->",
"SuccessOrError",
":",
"secret_registered_on_chain",
... | Determine whether a lock has expired.
The lock has expired if both:
- The secret was not registered on-chain in time.
- The current block exceeds lock's expiration + confirmation blocks. | [
"Determine",
"whether",
"a",
"lock",
"has",
"expired",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L194-L219 | train | 216,606 |
raiden-network/raiden | raiden/transfer/channel.py | is_secret_known | def is_secret_known(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> bool:
"""True if the `secrethash` is for a lock with a known secret."""
return (
secrethash in end_state.secrethashes_to_unlockedlocks or
secrethash in end_state.secrethashes_to_onchain_unlockedlocks
) | python | def is_secret_known(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> bool:
"""True if the `secrethash` is for a lock with a known secret."""
return (
secrethash in end_state.secrethashes_to_unlockedlocks or
secrethash in end_state.secrethashes_to_onchain_unlockedlocks
) | [
"def",
"is_secret_known",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
"secrethash",
":",
"SecretHash",
",",
")",
"->",
"bool",
":",
"return",
"(",
"secrethash",
"in",
"end_state",
".",
"secrethashes_to_unlockedlocks",
"or",
"secrethash",
"in",
"end_state",... | True if the `secrethash` is for a lock with a known secret. | [
"True",
"if",
"the",
"secrethash",
"is",
"for",
"a",
"lock",
"with",
"a",
"known",
"secret",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L237-L245 | train | 216,607 |
raiden-network/raiden | raiden/transfer/channel.py | get_secret | def get_secret(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[Secret]:
"""Returns `secret` if the `secrethash` is for a lock with a known secret."""
partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if partial_unlock_proof is None:
partial_unlock_proof = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash)
if partial_unlock_proof is not None:
return partial_unlock_proof.secret
return None | python | def get_secret(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[Secret]:
"""Returns `secret` if the `secrethash` is for a lock with a known secret."""
partial_unlock_proof = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if partial_unlock_proof is None:
partial_unlock_proof = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash)
if partial_unlock_proof is not None:
return partial_unlock_proof.secret
return None | [
"def",
"get_secret",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
"secrethash",
":",
"SecretHash",
",",
")",
"->",
"Optional",
"[",
"Secret",
"]",
":",
"partial_unlock_proof",
"=",
"end_state",
".",
"secrethashes_to_unlockedlocks",
".",
"get",
"(",
"secre... | Returns `secret` if the `secrethash` is for a lock with a known secret. | [
"Returns",
"secret",
"if",
"the",
"secrethash",
"is",
"for",
"a",
"lock",
"with",
"a",
"known",
"secret",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L264-L277 | train | 216,608 |
raiden-network/raiden | raiden/transfer/channel.py | is_balance_proof_safe_for_onchain_operations | def is_balance_proof_safe_for_onchain_operations(
balance_proof: BalanceProofSignedState,
) -> bool:
""" Check if the balance proof would overflow onchain. """
total_amount = balance_proof.transferred_amount + balance_proof.locked_amount
return total_amount <= UINT256_MAX | python | def is_balance_proof_safe_for_onchain_operations(
balance_proof: BalanceProofSignedState,
) -> bool:
""" Check if the balance proof would overflow onchain. """
total_amount = balance_proof.transferred_amount + balance_proof.locked_amount
return total_amount <= UINT256_MAX | [
"def",
"is_balance_proof_safe_for_onchain_operations",
"(",
"balance_proof",
":",
"BalanceProofSignedState",
",",
")",
"->",
"bool",
":",
"total_amount",
"=",
"balance_proof",
".",
"transferred_amount",
"+",
"balance_proof",
".",
"locked_amount",
"return",
"total_amount",
... | Check if the balance proof would overflow onchain. | [
"Check",
"if",
"the",
"balance",
"proof",
"would",
"overflow",
"onchain",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L288-L293 | train | 216,609 |
raiden-network/raiden | raiden/transfer/channel.py | is_balance_proof_usable_onchain | def is_balance_proof_usable_onchain(
received_balance_proof: BalanceProofSignedState,
channel_state: NettingChannelState,
sender_state: NettingChannelEndState,
) -> SuccessOrError:
""" Checks the balance proof can be used on-chain.
For a balance proof to be valid it must be newer than the previous one,
i.e. the nonce must increase, the signature must tie the balance proof to
the correct channel, and the values must not result in an under/overflow
onchain.
Important: This predicate does not validate all the message fields. The
fields locksroot, transferred_amount, and locked_amount **MUST** be
validated elsewhere based on the message type.
"""
expected_nonce = get_next_nonce(sender_state)
is_valid_signature_, signature_msg = is_valid_signature(
received_balance_proof,
sender_state.address,
)
result: SuccessOrError
# TODO: Accept unlock messages if the node has not yet sent a transaction
# with the balance proof to the blockchain, this will save one call to
# unlock on-chain for the non-closing party.
if get_status(channel_state) != CHANNEL_STATE_OPENED:
# The channel must be opened, otherwise if receiver is the closer, the
# balance proof cannot be used onchain.
msg = f'The channel is already closed.'
result = (False, msg)
elif received_balance_proof.channel_identifier != channel_state.identifier:
# Informational message, the channel_identifier **validated by the
# signature** must match for the balance_proof to be valid.
msg = (
f"channel_identifier does not match. "
f"expected: {channel_state.identifier} "
f"got: {received_balance_proof.channel_identifier}."
)
result = (False, msg)
elif received_balance_proof.token_network_identifier != channel_state.token_network_identifier:
# Informational message, the token_network_identifier **validated by
# the signature** must match for the balance_proof to be valid.
msg = (
f"token_network_identifier does not match. "
f"expected: {channel_state.token_network_identifier} "
f"got: {received_balance_proof.token_network_identifier}."
)
result = (False, msg)
elif received_balance_proof.chain_id != channel_state.chain_id:
# Informational message, the chain_id **validated by the signature**
# must match for the balance_proof to be valid.
msg = (
f"chain_id does not match channel's "
f"chain_id. expected: {channel_state.chain_id} "
f"got: {received_balance_proof.chain_id}."
)
result = (False, msg)
elif not is_balance_proof_safe_for_onchain_operations(received_balance_proof):
transferred_amount_after_unlock = (
received_balance_proof.transferred_amount +
received_balance_proof.locked_amount
)
msg = (
f"Balance proof total transferred amount would overflow onchain. "
f"max: {UINT256_MAX} result would be: {transferred_amount_after_unlock}"
)
result = (False, msg)
elif received_balance_proof.nonce != expected_nonce:
# The nonces must increase sequentially, otherwise there is a
# synchronization problem.
msg = (
f'Nonce did not change sequentially, expected: {expected_nonce} '
f'got: {received_balance_proof.nonce}.'
)
result = (False, msg)
elif not is_valid_signature_:
# The signature must be valid, otherwise the balance proof cannot be
# used onchain.
result = (False, signature_msg)
else:
result = (True, None)
return result | python | def is_balance_proof_usable_onchain(
received_balance_proof: BalanceProofSignedState,
channel_state: NettingChannelState,
sender_state: NettingChannelEndState,
) -> SuccessOrError:
""" Checks the balance proof can be used on-chain.
For a balance proof to be valid it must be newer than the previous one,
i.e. the nonce must increase, the signature must tie the balance proof to
the correct channel, and the values must not result in an under/overflow
onchain.
Important: This predicate does not validate all the message fields. The
fields locksroot, transferred_amount, and locked_amount **MUST** be
validated elsewhere based on the message type.
"""
expected_nonce = get_next_nonce(sender_state)
is_valid_signature_, signature_msg = is_valid_signature(
received_balance_proof,
sender_state.address,
)
result: SuccessOrError
# TODO: Accept unlock messages if the node has not yet sent a transaction
# with the balance proof to the blockchain, this will save one call to
# unlock on-chain for the non-closing party.
if get_status(channel_state) != CHANNEL_STATE_OPENED:
# The channel must be opened, otherwise if receiver is the closer, the
# balance proof cannot be used onchain.
msg = f'The channel is already closed.'
result = (False, msg)
elif received_balance_proof.channel_identifier != channel_state.identifier:
# Informational message, the channel_identifier **validated by the
# signature** must match for the balance_proof to be valid.
msg = (
f"channel_identifier does not match. "
f"expected: {channel_state.identifier} "
f"got: {received_balance_proof.channel_identifier}."
)
result = (False, msg)
elif received_balance_proof.token_network_identifier != channel_state.token_network_identifier:
# Informational message, the token_network_identifier **validated by
# the signature** must match for the balance_proof to be valid.
msg = (
f"token_network_identifier does not match. "
f"expected: {channel_state.token_network_identifier} "
f"got: {received_balance_proof.token_network_identifier}."
)
result = (False, msg)
elif received_balance_proof.chain_id != channel_state.chain_id:
# Informational message, the chain_id **validated by the signature**
# must match for the balance_proof to be valid.
msg = (
f"chain_id does not match channel's "
f"chain_id. expected: {channel_state.chain_id} "
f"got: {received_balance_proof.chain_id}."
)
result = (False, msg)
elif not is_balance_proof_safe_for_onchain_operations(received_balance_proof):
transferred_amount_after_unlock = (
received_balance_proof.transferred_amount +
received_balance_proof.locked_amount
)
msg = (
f"Balance proof total transferred amount would overflow onchain. "
f"max: {UINT256_MAX} result would be: {transferred_amount_after_unlock}"
)
result = (False, msg)
elif received_balance_proof.nonce != expected_nonce:
# The nonces must increase sequentially, otherwise there is a
# synchronization problem.
msg = (
f'Nonce did not change sequentially, expected: {expected_nonce} '
f'got: {received_balance_proof.nonce}.'
)
result = (False, msg)
elif not is_valid_signature_:
# The signature must be valid, otherwise the balance proof cannot be
# used onchain.
result = (False, signature_msg)
else:
result = (True, None)
return result | [
"def",
"is_balance_proof_usable_onchain",
"(",
"received_balance_proof",
":",
"BalanceProofSignedState",
",",
"channel_state",
":",
"NettingChannelState",
",",
"sender_state",
":",
"NettingChannelEndState",
",",
")",
"->",
"SuccessOrError",
":",
"expected_nonce",
"=",
"get_... | Checks the balance proof can be used on-chain.
For a balance proof to be valid it must be newer than the previous one,
i.e. the nonce must increase, the signature must tie the balance proof to
the correct channel, and the values must not result in an under/overflow
onchain.
Important: This predicate does not validate all the message fields. The
fields locksroot, transferred_amount, and locked_amount **MUST** be
validated elsewhere based on the message type. | [
"Checks",
"the",
"balance",
"proof",
"can",
"be",
"used",
"on",
"-",
"chain",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L368-L462 | train | 216,610 |
raiden-network/raiden | raiden/transfer/channel.py | get_distributable | def get_distributable(
sender: NettingChannelEndState,
receiver: NettingChannelEndState,
) -> TokenAmount:
"""Return the amount of tokens that can be used by the `sender`.
The returned value is limited to a UINT256, since that is the representation
used in the smart contracts and we cannot use a larger value. The limit is
enforced on transferred_amount + locked_amount to avoid overflows. This is
an additional security check.
"""
_, _, transferred_amount, locked_amount = get_current_balanceproof(sender)
distributable = get_balance(sender, receiver) - get_amount_locked(sender)
overflow_limit = max(
UINT256_MAX - transferred_amount - locked_amount,
0,
)
return TokenAmount(min(overflow_limit, distributable)) | python | def get_distributable(
sender: NettingChannelEndState,
receiver: NettingChannelEndState,
) -> TokenAmount:
"""Return the amount of tokens that can be used by the `sender`.
The returned value is limited to a UINT256, since that is the representation
used in the smart contracts and we cannot use a larger value. The limit is
enforced on transferred_amount + locked_amount to avoid overflows. This is
an additional security check.
"""
_, _, transferred_amount, locked_amount = get_current_balanceproof(sender)
distributable = get_balance(sender, receiver) - get_amount_locked(sender)
overflow_limit = max(
UINT256_MAX - transferred_amount - locked_amount,
0,
)
return TokenAmount(min(overflow_limit, distributable)) | [
"def",
"get_distributable",
"(",
"sender",
":",
"NettingChannelEndState",
",",
"receiver",
":",
"NettingChannelEndState",
",",
")",
"->",
"TokenAmount",
":",
"_",
",",
"_",
",",
"transferred_amount",
",",
"locked_amount",
"=",
"get_current_balanceproof",
"(",
"sende... | Return the amount of tokens that can be used by the `sender`.
The returned value is limited to a UINT256, since that is the representation
used in the smart contracts and we cannot use a larger value. The limit is
enforced on transferred_amount + locked_amount to avoid overflows. This is
an additional security check. | [
"Return",
"the",
"amount",
"of",
"tokens",
"that",
"can",
"be",
"used",
"by",
"the",
"sender",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L950-L970 | train | 216,611 |
raiden-network/raiden | raiden/transfer/channel.py | get_batch_unlock | def get_batch_unlock(
end_state: NettingChannelEndState,
) -> Optional[MerkleTreeLeaves]:
""" Unlock proof for an entire merkle tree of pending locks
The unlock proof contains all the merkle tree data, tightly packed, needed by the token
network contract to verify the secret expiry and calculate the token amounts to transfer.
"""
if len(end_state.merkletree.layers[LEAVES]) == 0: # pylint: disable=len-as-condition
return None
lockhashes_to_locks = dict()
lockhashes_to_locks.update({
lock.lockhash: lock
for secrethash, lock in end_state.secrethashes_to_lockedlocks.items()
})
lockhashes_to_locks.update({
proof.lock.lockhash: proof.lock
for secrethash, proof in end_state.secrethashes_to_unlockedlocks.items()
})
lockhashes_to_locks.update({
proof.lock.lockhash: proof.lock
for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items()
})
ordered_locks = [
lockhashes_to_locks[LockHash(lockhash)]
for lockhash in end_state.merkletree.layers[LEAVES]
]
# Not sure why the cast is needed here. The error was:
# Incompatible return value type
# (got "List[HashTimeLockState]", expected "Optional[MerkleTreeLeaves]")
return cast(MerkleTreeLeaves, ordered_locks) | python | def get_batch_unlock(
end_state: NettingChannelEndState,
) -> Optional[MerkleTreeLeaves]:
""" Unlock proof for an entire merkle tree of pending locks
The unlock proof contains all the merkle tree data, tightly packed, needed by the token
network contract to verify the secret expiry and calculate the token amounts to transfer.
"""
if len(end_state.merkletree.layers[LEAVES]) == 0: # pylint: disable=len-as-condition
return None
lockhashes_to_locks = dict()
lockhashes_to_locks.update({
lock.lockhash: lock
for secrethash, lock in end_state.secrethashes_to_lockedlocks.items()
})
lockhashes_to_locks.update({
proof.lock.lockhash: proof.lock
for secrethash, proof in end_state.secrethashes_to_unlockedlocks.items()
})
lockhashes_to_locks.update({
proof.lock.lockhash: proof.lock
for secrethash, proof in end_state.secrethashes_to_onchain_unlockedlocks.items()
})
ordered_locks = [
lockhashes_to_locks[LockHash(lockhash)]
for lockhash in end_state.merkletree.layers[LEAVES]
]
# Not sure why the cast is needed here. The error was:
# Incompatible return value type
# (got "List[HashTimeLockState]", expected "Optional[MerkleTreeLeaves]")
return cast(MerkleTreeLeaves, ordered_locks) | [
"def",
"get_batch_unlock",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
")",
"->",
"Optional",
"[",
"MerkleTreeLeaves",
"]",
":",
"if",
"len",
"(",
"end_state",
".",
"merkletree",
".",
"layers",
"[",
"LEAVES",
"]",
")",
"==",
"0",
":",
"# pylint: di... | Unlock proof for an entire merkle tree of pending locks
The unlock proof contains all the merkle tree data, tightly packed, needed by the token
network contract to verify the secret expiry and calculate the token amounts to transfer. | [
"Unlock",
"proof",
"for",
"an",
"entire",
"merkle",
"tree",
"of",
"pending",
"locks"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L973-L1007 | train | 216,612 |
raiden-network/raiden | raiden/transfer/channel.py | get_lock | def get_lock(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[HashTimeLockState]:
"""Return the lock correspoding to `secrethash` or None if the lock is
unknown.
"""
lock = end_state.secrethashes_to_lockedlocks.get(secrethash)
if not lock:
partial_unlock = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if not partial_unlock:
partial_unlock = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash)
if partial_unlock:
lock = partial_unlock.lock
assert isinstance(lock, HashTimeLockState) or lock is None
return lock | python | def get_lock(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> Optional[HashTimeLockState]:
"""Return the lock correspoding to `secrethash` or None if the lock is
unknown.
"""
lock = end_state.secrethashes_to_lockedlocks.get(secrethash)
if not lock:
partial_unlock = end_state.secrethashes_to_unlockedlocks.get(secrethash)
if not partial_unlock:
partial_unlock = end_state.secrethashes_to_onchain_unlockedlocks.get(secrethash)
if partial_unlock:
lock = partial_unlock.lock
assert isinstance(lock, HashTimeLockState) or lock is None
return lock | [
"def",
"get_lock",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
"secrethash",
":",
"SecretHash",
",",
")",
"->",
"Optional",
"[",
"HashTimeLockState",
"]",
":",
"lock",
"=",
"end_state",
".",
"secrethashes_to_lockedlocks",
".",
"get",
"(",
"secrethash",
... | Return the lock correspoding to `secrethash` or None if the lock is
unknown. | [
"Return",
"the",
"lock",
"correspoding",
"to",
"secrethash",
"or",
"None",
"if",
"the",
"lock",
"is",
"unknown",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1010-L1029 | train | 216,613 |
raiden-network/raiden | raiden/transfer/channel.py | lock_exists_in_either_channel_side | def lock_exists_in_either_channel_side(
channel_state: NettingChannelState,
secrethash: SecretHash,
) -> bool:
"""Check if the lock with `secrethash` exists in either our state or the partner's state"""
lock = get_lock(channel_state.our_state, secrethash)
if not lock:
lock = get_lock(channel_state.partner_state, secrethash)
return lock is not None | python | def lock_exists_in_either_channel_side(
channel_state: NettingChannelState,
secrethash: SecretHash,
) -> bool:
"""Check if the lock with `secrethash` exists in either our state or the partner's state"""
lock = get_lock(channel_state.our_state, secrethash)
if not lock:
lock = get_lock(channel_state.partner_state, secrethash)
return lock is not None | [
"def",
"lock_exists_in_either_channel_side",
"(",
"channel_state",
":",
"NettingChannelState",
",",
"secrethash",
":",
"SecretHash",
",",
")",
"->",
"bool",
":",
"lock",
"=",
"get_lock",
"(",
"channel_state",
".",
"our_state",
",",
"secrethash",
")",
"if",
"not",
... | Check if the lock with `secrethash` exists in either our state or the partner's state | [
"Check",
"if",
"the",
"lock",
"with",
"secrethash",
"exists",
"in",
"either",
"our",
"state",
"or",
"the",
"partner",
"s",
"state"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1032-L1040 | train | 216,614 |
raiden-network/raiden | raiden/transfer/channel.py | _del_lock | def _del_lock(end_state: NettingChannelEndState, secrethash: SecretHash) -> None:
"""Removes the lock from the indexing structures.
Note:
This won't change the merkletree!
"""
assert is_lock_pending(end_state, secrethash)
_del_unclaimed_lock(end_state, secrethash)
if secrethash in end_state.secrethashes_to_onchain_unlockedlocks:
del end_state.secrethashes_to_onchain_unlockedlocks[secrethash] | python | def _del_lock(end_state: NettingChannelEndState, secrethash: SecretHash) -> None:
"""Removes the lock from the indexing structures.
Note:
This won't change the merkletree!
"""
assert is_lock_pending(end_state, secrethash)
_del_unclaimed_lock(end_state, secrethash)
if secrethash in end_state.secrethashes_to_onchain_unlockedlocks:
del end_state.secrethashes_to_onchain_unlockedlocks[secrethash] | [
"def",
"_del_lock",
"(",
"end_state",
":",
"NettingChannelEndState",
",",
"secrethash",
":",
"SecretHash",
")",
"->",
"None",
":",
"assert",
"is_lock_pending",
"(",
"end_state",
",",
"secrethash",
")",
"_del_unclaimed_lock",
"(",
"end_state",
",",
"secrethash",
")... | Removes the lock from the indexing structures.
Note:
This won't change the merkletree! | [
"Removes",
"the",
"lock",
"from",
"the",
"indexing",
"structures",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1103-L1114 | train | 216,615 |
raiden-network/raiden | raiden/transfer/channel.py | compute_merkletree_with | def compute_merkletree_with(
merkletree: MerkleTreeState,
lockhash: LockHash,
) -> Optional[MerkleTreeState]:
"""Register the given lockhash with the existing merkle tree."""
# Use None to inform the caller the lockshash is already known
result = None
leaves = merkletree.layers[LEAVES]
if lockhash not in leaves:
leaves = list(leaves)
leaves.append(Keccak256(lockhash))
result = MerkleTreeState(compute_layers(leaves))
return result | python | def compute_merkletree_with(
merkletree: MerkleTreeState,
lockhash: LockHash,
) -> Optional[MerkleTreeState]:
"""Register the given lockhash with the existing merkle tree."""
# Use None to inform the caller the lockshash is already known
result = None
leaves = merkletree.layers[LEAVES]
if lockhash not in leaves:
leaves = list(leaves)
leaves.append(Keccak256(lockhash))
result = MerkleTreeState(compute_layers(leaves))
return result | [
"def",
"compute_merkletree_with",
"(",
"merkletree",
":",
"MerkleTreeState",
",",
"lockhash",
":",
"LockHash",
",",
")",
"->",
"Optional",
"[",
"MerkleTreeState",
"]",
":",
"# Use None to inform the caller the lockshash is already known",
"result",
"=",
"None",
"leaves",
... | Register the given lockhash with the existing merkle tree. | [
"Register",
"the",
"given",
"lockhash",
"with",
"the",
"existing",
"merkle",
"tree",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1172-L1186 | train | 216,616 |
raiden-network/raiden | raiden/transfer/channel.py | register_offchain_secret | def register_offchain_secret(
channel_state: NettingChannelState,
secret: Secret,
secrethash: SecretHash,
) -> None:
"""This will register the secret and set the lock to the unlocked stated.
Even though the lock is unlock it is *not* claimed. The capacity will
increase once the next balance proof is received.
"""
our_state = channel_state.our_state
partner_state = channel_state.partner_state
register_secret_endstate(our_state, secret, secrethash)
register_secret_endstate(partner_state, secret, secrethash) | python | def register_offchain_secret(
channel_state: NettingChannelState,
secret: Secret,
secrethash: SecretHash,
) -> None:
"""This will register the secret and set the lock to the unlocked stated.
Even though the lock is unlock it is *not* claimed. The capacity will
increase once the next balance proof is received.
"""
our_state = channel_state.our_state
partner_state = channel_state.partner_state
register_secret_endstate(our_state, secret, secrethash)
register_secret_endstate(partner_state, secret, secrethash) | [
"def",
"register_offchain_secret",
"(",
"channel_state",
":",
"NettingChannelState",
",",
"secret",
":",
"Secret",
",",
"secrethash",
":",
"SecretHash",
",",
")",
"->",
"None",
":",
"our_state",
"=",
"channel_state",
".",
"our_state",
"partner_state",
"=",
"channe... | This will register the secret and set the lock to the unlocked stated.
Even though the lock is unlock it is *not* claimed. The capacity will
increase once the next balance proof is received. | [
"This",
"will",
"register",
"the",
"secret",
"and",
"set",
"the",
"lock",
"to",
"the",
"unlocked",
"stated",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1590-L1604 | train | 216,617 |
raiden-network/raiden | raiden/transfer/channel.py | register_onchain_secret | def register_onchain_secret(
channel_state: NettingChannelState,
secret: Secret,
secrethash: SecretHash,
secret_reveal_block_number: BlockNumber,
delete_lock: bool = True,
) -> None:
"""This will register the onchain secret and set the lock to the unlocked stated.
Even though the lock is unlocked it is *not* claimed. The capacity will
increase once the next balance proof is received.
"""
our_state = channel_state.our_state
partner_state = channel_state.partner_state
register_onchain_secret_endstate(
our_state,
secret,
secrethash,
secret_reveal_block_number,
delete_lock,
)
register_onchain_secret_endstate(
partner_state,
secret,
secrethash,
secret_reveal_block_number,
delete_lock,
) | python | def register_onchain_secret(
channel_state: NettingChannelState,
secret: Secret,
secrethash: SecretHash,
secret_reveal_block_number: BlockNumber,
delete_lock: bool = True,
) -> None:
"""This will register the onchain secret and set the lock to the unlocked stated.
Even though the lock is unlocked it is *not* claimed. The capacity will
increase once the next balance proof is received.
"""
our_state = channel_state.our_state
partner_state = channel_state.partner_state
register_onchain_secret_endstate(
our_state,
secret,
secrethash,
secret_reveal_block_number,
delete_lock,
)
register_onchain_secret_endstate(
partner_state,
secret,
secrethash,
secret_reveal_block_number,
delete_lock,
) | [
"def",
"register_onchain_secret",
"(",
"channel_state",
":",
"NettingChannelState",
",",
"secret",
":",
"Secret",
",",
"secrethash",
":",
"SecretHash",
",",
"secret_reveal_block_number",
":",
"BlockNumber",
",",
"delete_lock",
":",
"bool",
"=",
"True",
",",
")",
"... | This will register the onchain secret and set the lock to the unlocked stated.
Even though the lock is unlocked it is *not* claimed. The capacity will
increase once the next balance proof is received. | [
"This",
"will",
"register",
"the",
"onchain",
"secret",
"and",
"set",
"the",
"lock",
"to",
"the",
"unlocked",
"stated",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1607-L1635 | train | 216,618 |
raiden-network/raiden | raiden/transfer/channel.py | handle_receive_lockedtransfer | def handle_receive_lockedtransfer(
channel_state: NettingChannelState,
mediated_transfer: LockedTransferSignedState,
) -> EventsOrError:
"""Register the latest known transfer.
The receiver needs to use this method to update the container with a
_valid_ transfer, otherwise the locksroot will not contain the pending
transfer. The receiver needs to ensure that the merkle root has the
secrethash included, otherwise it won't be able to claim it.
"""
events: List[Event]
is_valid, msg, merkletree = is_valid_lockedtransfer(
mediated_transfer,
channel_state,
channel_state.partner_state,
channel_state.our_state,
)
if is_valid:
assert merkletree, 'is_valid_lock_expired should return merkletree if valid'
channel_state.partner_state.balance_proof = mediated_transfer.balance_proof
channel_state.partner_state.merkletree = merkletree
lock = mediated_transfer.lock
channel_state.partner_state.secrethashes_to_lockedlocks[lock.secrethash] = lock
send_processed = SendProcessed(
recipient=mediated_transfer.balance_proof.sender,
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=mediated_transfer.message_identifier,
)
events = [send_processed]
else:
assert msg, 'is_valid_lock_expired should return error msg if not valid'
invalid_locked = EventInvalidReceivedLockedTransfer(
payment_identifier=mediated_transfer.payment_identifier,
reason=msg,
)
events = [invalid_locked]
return is_valid, events, msg | python | def handle_receive_lockedtransfer(
channel_state: NettingChannelState,
mediated_transfer: LockedTransferSignedState,
) -> EventsOrError:
"""Register the latest known transfer.
The receiver needs to use this method to update the container with a
_valid_ transfer, otherwise the locksroot will not contain the pending
transfer. The receiver needs to ensure that the merkle root has the
secrethash included, otherwise it won't be able to claim it.
"""
events: List[Event]
is_valid, msg, merkletree = is_valid_lockedtransfer(
mediated_transfer,
channel_state,
channel_state.partner_state,
channel_state.our_state,
)
if is_valid:
assert merkletree, 'is_valid_lock_expired should return merkletree if valid'
channel_state.partner_state.balance_proof = mediated_transfer.balance_proof
channel_state.partner_state.merkletree = merkletree
lock = mediated_transfer.lock
channel_state.partner_state.secrethashes_to_lockedlocks[lock.secrethash] = lock
send_processed = SendProcessed(
recipient=mediated_transfer.balance_proof.sender,
channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE,
message_identifier=mediated_transfer.message_identifier,
)
events = [send_processed]
else:
assert msg, 'is_valid_lock_expired should return error msg if not valid'
invalid_locked = EventInvalidReceivedLockedTransfer(
payment_identifier=mediated_transfer.payment_identifier,
reason=msg,
)
events = [invalid_locked]
return is_valid, events, msg | [
"def",
"handle_receive_lockedtransfer",
"(",
"channel_state",
":",
"NettingChannelState",
",",
"mediated_transfer",
":",
"LockedTransferSignedState",
",",
")",
"->",
"EventsOrError",
":",
"events",
":",
"List",
"[",
"Event",
"]",
"is_valid",
",",
"msg",
",",
"merkle... | Register the latest known transfer.
The receiver needs to use this method to update the container with a
_valid_ transfer, otherwise the locksroot will not contain the pending
transfer. The receiver needs to ensure that the merkle root has the
secrethash included, otherwise it won't be able to claim it. | [
"Register",
"the",
"latest",
"known",
"transfer",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/channel.py#L1742-L1783 | train | 216,619 |
raiden-network/raiden | raiden/utils/notifying_queue.py | NotifyingQueue.get | def get(self, block=True, timeout=None):
""" Removes and returns an item from the queue. """
value = self._queue.get(block, timeout)
if self._queue.empty():
self.clear()
return value | python | def get(self, block=True, timeout=None):
""" Removes and returns an item from the queue. """
value = self._queue.get(block, timeout)
if self._queue.empty():
self.clear()
return value | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"value",
"=",
"self",
".",
"_queue",
".",
"get",
"(",
"block",
",",
"timeout",
")",
"if",
"self",
".",
"_queue",
".",
"empty",
"(",
")",
":",
"self",
"... | Removes and returns an item from the queue. | [
"Removes",
"and",
"returns",
"an",
"item",
"from",
"the",
"queue",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/notifying_queue.py#L18-L23 | train | 216,620 |
raiden-network/raiden | raiden/utils/notifying_queue.py | NotifyingQueue.copy | def copy(self):
""" Copies the current queue items. """
copy = self._queue.copy()
result = list()
while not copy.empty():
result.append(copy.get_nowait())
return result | python | def copy(self):
""" Copies the current queue items. """
copy = self._queue.copy()
result = list()
while not copy.empty():
result.append(copy.get_nowait())
return result | [
"def",
"copy",
"(",
"self",
")",
":",
"copy",
"=",
"self",
".",
"_queue",
".",
"copy",
"(",
")",
"result",
"=",
"list",
"(",
")",
"while",
"not",
"copy",
".",
"empty",
"(",
")",
":",
"result",
".",
"append",
"(",
"copy",
".",
"get_nowait",
"(",
... | Copies the current queue items. | [
"Copies",
"the",
"current",
"queue",
"items",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/utils/notifying_queue.py#L31-L38 | train | 216,621 |
raiden-network/raiden | raiden/routing.py | get_best_routes_internal | def get_best_routes_internal(
chain_state: ChainState,
token_network_id: TokenNetworkID,
from_address: InitiatorAddress,
to_address: TargetAddress,
amount: int,
previous_address: Optional[Address],
) -> List[RouteState]:
""" Returns a list of channels that can be used to make a transfer.
This will filter out channels that are not open and don't have enough
capacity.
"""
# TODO: Route ranking.
# Rate each route to optimize the fee price/quality of each route and add a
# rate from in the range [0.0,1.0].
available_routes = list()
token_network = views.get_token_network_by_identifier(
chain_state,
token_network_id,
)
if not token_network:
return list()
neighbors_heap: List[Neighbour] = list()
try:
all_neighbors = networkx.all_neighbors(token_network.network_graph.network, from_address)
except networkx.NetworkXError:
# If `our_address` is not in the graph, no channels opened with the
# address
return list()
for partner_address in all_neighbors:
# don't send the message backwards
if partner_address == previous_address:
continue
channel_state = views.get_channelstate_by_token_network_and_partner(
chain_state,
token_network_id,
partner_address,
)
if not channel_state:
continue
if channel.get_status(channel_state) != CHANNEL_STATE_OPENED:
log.info(
'Channel is not opened, ignoring',
from_address=pex(from_address),
partner_address=pex(partner_address),
routing_source='Internal Routing',
)
continue
nonrefundable = amount > channel.get_distributable(
channel_state.partner_state,
channel_state.our_state,
)
try:
length = networkx.shortest_path_length(
token_network.network_graph.network,
partner_address,
to_address,
)
neighbour = Neighbour(
length=length,
nonrefundable=nonrefundable,
partner_address=partner_address,
channelid=channel_state.identifier,
)
heappush(neighbors_heap, neighbour)
except (networkx.NetworkXNoPath, networkx.NodeNotFound):
pass
if not neighbors_heap:
log.warning(
'No routes available',
from_address=pex(from_address),
to_address=pex(to_address),
)
return list()
while neighbors_heap:
neighbour = heappop(neighbors_heap)
route_state = RouteState(
node_address=neighbour.partner_address,
channel_identifier=neighbour.channelid,
)
available_routes.append(route_state)
return available_routes | python | def get_best_routes_internal(
chain_state: ChainState,
token_network_id: TokenNetworkID,
from_address: InitiatorAddress,
to_address: TargetAddress,
amount: int,
previous_address: Optional[Address],
) -> List[RouteState]:
""" Returns a list of channels that can be used to make a transfer.
This will filter out channels that are not open and don't have enough
capacity.
"""
# TODO: Route ranking.
# Rate each route to optimize the fee price/quality of each route and add a
# rate from in the range [0.0,1.0].
available_routes = list()
token_network = views.get_token_network_by_identifier(
chain_state,
token_network_id,
)
if not token_network:
return list()
neighbors_heap: List[Neighbour] = list()
try:
all_neighbors = networkx.all_neighbors(token_network.network_graph.network, from_address)
except networkx.NetworkXError:
# If `our_address` is not in the graph, no channels opened with the
# address
return list()
for partner_address in all_neighbors:
# don't send the message backwards
if partner_address == previous_address:
continue
channel_state = views.get_channelstate_by_token_network_and_partner(
chain_state,
token_network_id,
partner_address,
)
if not channel_state:
continue
if channel.get_status(channel_state) != CHANNEL_STATE_OPENED:
log.info(
'Channel is not opened, ignoring',
from_address=pex(from_address),
partner_address=pex(partner_address),
routing_source='Internal Routing',
)
continue
nonrefundable = amount > channel.get_distributable(
channel_state.partner_state,
channel_state.our_state,
)
try:
length = networkx.shortest_path_length(
token_network.network_graph.network,
partner_address,
to_address,
)
neighbour = Neighbour(
length=length,
nonrefundable=nonrefundable,
partner_address=partner_address,
channelid=channel_state.identifier,
)
heappush(neighbors_heap, neighbour)
except (networkx.NetworkXNoPath, networkx.NodeNotFound):
pass
if not neighbors_heap:
log.warning(
'No routes available',
from_address=pex(from_address),
to_address=pex(to_address),
)
return list()
while neighbors_heap:
neighbour = heappop(neighbors_heap)
route_state = RouteState(
node_address=neighbour.partner_address,
channel_identifier=neighbour.channelid,
)
available_routes.append(route_state)
return available_routes | [
"def",
"get_best_routes_internal",
"(",
"chain_state",
":",
"ChainState",
",",
"token_network_id",
":",
"TokenNetworkID",
",",
"from_address",
":",
"InitiatorAddress",
",",
"to_address",
":",
"TargetAddress",
",",
"amount",
":",
"int",
",",
"previous_address",
":",
... | Returns a list of channels that can be used to make a transfer.
This will filter out channels that are not open and don't have enough
capacity. | [
"Returns",
"a",
"list",
"of",
"channels",
"that",
"can",
"be",
"used",
"to",
"make",
"a",
"transfer",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/routing.py#L80-L174 | train | 216,622 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | Room.get_joined_members | def get_joined_members(self, force_resync=False) -> List[User]:
""" Return a list of members of this room. """
if force_resync:
response = self.client.api.get_room_members(self.room_id)
for event in response['chunk']:
if event['content']['membership'] == 'join':
user_id = event["state_key"]
if user_id not in self._members:
self._mkmembers(
User(
self.client.api,
user_id,
event['content'].get('displayname'),
),
)
return list(self._members.values()) | python | def get_joined_members(self, force_resync=False) -> List[User]:
""" Return a list of members of this room. """
if force_resync:
response = self.client.api.get_room_members(self.room_id)
for event in response['chunk']:
if event['content']['membership'] == 'join':
user_id = event["state_key"]
if user_id not in self._members:
self._mkmembers(
User(
self.client.api,
user_id,
event['content'].get('displayname'),
),
)
return list(self._members.values()) | [
"def",
"get_joined_members",
"(",
"self",
",",
"force_resync",
"=",
"False",
")",
"->",
"List",
"[",
"User",
"]",
":",
"if",
"force_resync",
":",
"response",
"=",
"self",
".",
"client",
".",
"api",
".",
"get_room_members",
"(",
"self",
".",
"room_id",
")... | Return a list of members of this room. | [
"Return",
"a",
"list",
"of",
"members",
"of",
"this",
"room",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L31-L46 | train | 216,623 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | Room.update_aliases | def update_aliases(self):
""" Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not
"""
changed = False
try:
response = self.client.api.get_room_state(self.room_id)
except MatrixRequestError:
return False
for chunk in response:
content = chunk.get('content')
if content:
if 'aliases' in content:
aliases = content['aliases']
if aliases != self.aliases:
self.aliases = aliases
changed = True
if chunk.get('type') == 'm.room.canonical_alias':
canonical_alias = content['alias']
if self.canonical_alias != canonical_alias:
self.canonical_alias = canonical_alias
changed = True
if changed and self.aliases and not self.canonical_alias:
self.canonical_alias = self.aliases[0]
return changed | python | def update_aliases(self):
""" Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not
"""
changed = False
try:
response = self.client.api.get_room_state(self.room_id)
except MatrixRequestError:
return False
for chunk in response:
content = chunk.get('content')
if content:
if 'aliases' in content:
aliases = content['aliases']
if aliases != self.aliases:
self.aliases = aliases
changed = True
if chunk.get('type') == 'm.room.canonical_alias':
canonical_alias = content['alias']
if self.canonical_alias != canonical_alias:
self.canonical_alias = canonical_alias
changed = True
if changed and self.aliases and not self.canonical_alias:
self.canonical_alias = self.aliases[0]
return changed | [
"def",
"update_aliases",
"(",
"self",
")",
":",
"changed",
"=",
"False",
"try",
":",
"response",
"=",
"self",
".",
"client",
".",
"api",
".",
"get_room_state",
"(",
"self",
".",
"room_id",
")",
"except",
"MatrixRequestError",
":",
"return",
"False",
"for",... | Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not | [
"Get",
"aliases",
"information",
"from",
"room",
"state"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L60-L86 | train | 216,624 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | GMatrixClient.stop_listener_thread | def stop_listener_thread(self):
""" Kills sync_thread greenlet before joining it """
# when stopping, `kill` will cause the `self.api.sync` call in _sync
# to raise a connection error. This flag will ensure it exits gracefully then
self.should_listen = False
if self.sync_thread:
self.sync_thread.kill()
self.sync_thread.get()
if self._handle_thread is not None:
self._handle_thread.get()
self.sync_thread = None
self._handle_thread = None | python | def stop_listener_thread(self):
""" Kills sync_thread greenlet before joining it """
# when stopping, `kill` will cause the `self.api.sync` call in _sync
# to raise a connection error. This flag will ensure it exits gracefully then
self.should_listen = False
if self.sync_thread:
self.sync_thread.kill()
self.sync_thread.get()
if self._handle_thread is not None:
self._handle_thread.get()
self.sync_thread = None
self._handle_thread = None | [
"def",
"stop_listener_thread",
"(",
"self",
")",
":",
"# when stopping, `kill` will cause the `self.api.sync` call in _sync",
"# to raise a connection error. This flag will ensure it exits gracefully then",
"self",
".",
"should_listen",
"=",
"False",
"if",
"self",
".",
"sync_thread",... | Kills sync_thread greenlet before joining it | [
"Kills",
"sync_thread",
"greenlet",
"before",
"joining",
"it"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L267-L278 | train | 216,625 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | GMatrixClient.typing | def typing(self, room: Room, timeout: int = 5000):
"""
Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms
"""
path = f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}'
return self.api._send('PUT', path, {'typing': True, 'timeout': timeout}) | python | def typing(self, room: Room, timeout: int = 5000):
"""
Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms
"""
path = f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}'
return self.api._send('PUT', path, {'typing': True, 'timeout': timeout}) | [
"def",
"typing",
"(",
"self",
",",
"room",
":",
"Room",
",",
"timeout",
":",
"int",
"=",
"5000",
")",
":",
"path",
"=",
"f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}'",
"return",
"self",
".",
"api",
".",
"_send",
"(",
"'PUT'",
",",
"path",
","... | Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms | [
"Send",
"typing",
"event",
"directly",
"to",
"api"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L362-L371 | train | 216,626 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | GMatrixClient._mkroom | def _mkroom(self, room_id: str) -> Room:
""" Uses a geventified Room subclass """
if room_id not in self.rooms:
self.rooms[room_id] = Room(self, room_id)
room = self.rooms[room_id]
if not room.canonical_alias:
room.update_aliases()
return room | python | def _mkroom(self, room_id: str) -> Room:
""" Uses a geventified Room subclass """
if room_id not in self.rooms:
self.rooms[room_id] = Room(self, room_id)
room = self.rooms[room_id]
if not room.canonical_alias:
room.update_aliases()
return room | [
"def",
"_mkroom",
"(",
"self",
",",
"room_id",
":",
"str",
")",
"->",
"Room",
":",
"if",
"room_id",
"not",
"in",
"self",
".",
"rooms",
":",
"self",
".",
"rooms",
"[",
"room_id",
"]",
"=",
"Room",
"(",
"self",
",",
"room_id",
")",
"room",
"=",
"se... | Uses a geventified Room subclass | [
"Uses",
"a",
"geventified",
"Room",
"subclass"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L373-L380 | train | 216,627 |
raiden-network/raiden | raiden/network/transport/matrix/client.py | GMatrixClient.set_sync_limit | def set_sync_limit(self, limit: int) -> Optional[int]:
""" Sets the events limit per room for sync and return previous limit """
try:
prev_limit = json.loads(self.sync_filter)['room']['timeline']['limit']
except (json.JSONDecodeError, KeyError):
prev_limit = None
self.sync_filter = json.dumps({'room': {'timeline': {'limit': limit}}})
return prev_limit | python | def set_sync_limit(self, limit: int) -> Optional[int]:
""" Sets the events limit per room for sync and return previous limit """
try:
prev_limit = json.loads(self.sync_filter)['room']['timeline']['limit']
except (json.JSONDecodeError, KeyError):
prev_limit = None
self.sync_filter = json.dumps({'room': {'timeline': {'limit': limit}}})
return prev_limit | [
"def",
"set_sync_limit",
"(",
"self",
",",
"limit",
":",
"int",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"try",
":",
"prev_limit",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"sync_filter",
")",
"[",
"'room'",
"]",
"[",
"'timeline'",
"]",
"[",
... | Sets the events limit per room for sync and return previous limit | [
"Sets",
"the",
"events",
"limit",
"per",
"room",
"for",
"sync",
"and",
"return",
"previous",
"limit"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/network/transport/matrix/client.py#L491-L498 | train | 216,628 |
raiden-network/raiden | raiden/api/rest.py | handle_request_parsing_error | def handle_request_parsing_error(
err,
_req,
_schema,
_err_status_code,
_err_headers,
):
""" This handles request parsing errors generated for example by schema
field validation failing."""
abort(HTTPStatus.BAD_REQUEST, errors=err.messages) | python | def handle_request_parsing_error(
err,
_req,
_schema,
_err_status_code,
_err_headers,
):
""" This handles request parsing errors generated for example by schema
field validation failing."""
abort(HTTPStatus.BAD_REQUEST, errors=err.messages) | [
"def",
"handle_request_parsing_error",
"(",
"err",
",",
"_req",
",",
"_schema",
",",
"_err_status_code",
",",
"_err_headers",
",",
")",
":",
"abort",
"(",
"HTTPStatus",
".",
"BAD_REQUEST",
",",
"errors",
"=",
"err",
".",
"messages",
")"
] | This handles request parsing errors generated for example by schema
field validation failing. | [
"This",
"handles",
"request",
"parsing",
"errors",
"generated",
"for",
"example",
"by",
"schema",
"field",
"validation",
"failing",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L230-L239 | train | 216,629 |
raiden-network/raiden | raiden/api/rest.py | hexbytes_to_str | def hexbytes_to_str(map_: Dict):
""" Converts values that are of type `HexBytes` to strings. """
for k, v in map_.items():
if isinstance(v, HexBytes):
map_[k] = encode_hex(v) | python | def hexbytes_to_str(map_: Dict):
""" Converts values that are of type `HexBytes` to strings. """
for k, v in map_.items():
if isinstance(v, HexBytes):
map_[k] = encode_hex(v) | [
"def",
"hexbytes_to_str",
"(",
"map_",
":",
"Dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"map_",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"HexBytes",
")",
":",
"map_",
"[",
"k",
"]",
"=",
"encode_hex",
"(",
"v",
")"
] | Converts values that are of type `HexBytes` to strings. | [
"Converts",
"values",
"that",
"are",
"of",
"type",
"HexBytes",
"to",
"strings",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L249-L253 | train | 216,630 |
raiden-network/raiden | raiden/api/rest.py | encode_byte_values | def encode_byte_values(map_: Dict):
""" Converts values that are of type `bytes` to strings. """
for k, v in map_.items():
if isinstance(v, bytes):
map_[k] = encode_hex(v) | python | def encode_byte_values(map_: Dict):
""" Converts values that are of type `bytes` to strings. """
for k, v in map_.items():
if isinstance(v, bytes):
map_[k] = encode_hex(v) | [
"def",
"encode_byte_values",
"(",
"map_",
":",
"Dict",
")",
":",
"for",
"k",
",",
"v",
"in",
"map_",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"bytes",
")",
":",
"map_",
"[",
"k",
"]",
"=",
"encode_hex",
"(",
"v",
")"
] | Converts values that are of type `bytes` to strings. | [
"Converts",
"values",
"that",
"are",
"of",
"type",
"bytes",
"to",
"strings",
"."
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L256-L260 | train | 216,631 |
raiden-network/raiden | raiden/api/rest.py | normalize_events_list | def normalize_events_list(old_list):
"""Internally the `event_type` key is prefixed with underscore but the API
returns an object without that prefix"""
new_list = []
for _event in old_list:
new_event = dict(_event)
if new_event.get('args'):
new_event['args'] = dict(new_event['args'])
encode_byte_values(new_event['args'])
# remove the queue identifier
if new_event.get('queue_identifier'):
del new_event['queue_identifier']
# the events contain HexBytes values, convert those to strings
hexbytes_to_str(new_event)
# Some of the raiden events contain accounts and as such need to
# be exported in hex to the outside world
name = new_event['event']
if name == 'EventPaymentReceivedSuccess':
new_event['initiator'] = to_checksum_address(new_event['initiator'])
if name in ('EventPaymentSentSuccess', 'EventPaymentSentFailed'):
new_event['target'] = to_checksum_address(new_event['target'])
encode_byte_values(new_event)
# encode unserializable objects
encode_object_to_str(new_event)
new_list.append(new_event)
return new_list | python | def normalize_events_list(old_list):
"""Internally the `event_type` key is prefixed with underscore but the API
returns an object without that prefix"""
new_list = []
for _event in old_list:
new_event = dict(_event)
if new_event.get('args'):
new_event['args'] = dict(new_event['args'])
encode_byte_values(new_event['args'])
# remove the queue identifier
if new_event.get('queue_identifier'):
del new_event['queue_identifier']
# the events contain HexBytes values, convert those to strings
hexbytes_to_str(new_event)
# Some of the raiden events contain accounts and as such need to
# be exported in hex to the outside world
name = new_event['event']
if name == 'EventPaymentReceivedSuccess':
new_event['initiator'] = to_checksum_address(new_event['initiator'])
if name in ('EventPaymentSentSuccess', 'EventPaymentSentFailed'):
new_event['target'] = to_checksum_address(new_event['target'])
encode_byte_values(new_event)
# encode unserializable objects
encode_object_to_str(new_event)
new_list.append(new_event)
return new_list | [
"def",
"normalize_events_list",
"(",
"old_list",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"_event",
"in",
"old_list",
":",
"new_event",
"=",
"dict",
"(",
"_event",
")",
"if",
"new_event",
".",
"get",
"(",
"'args'",
")",
":",
"new_event",
"[",
"'args'"... | Internally the `event_type` key is prefixed with underscore but the API
returns an object without that prefix | [
"Internally",
"the",
"event_type",
"key",
"is",
"prefixed",
"with",
"underscore",
"but",
"the",
"API",
"returns",
"an",
"object",
"without",
"that",
"prefix"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L271-L296 | train | 216,632 |
raiden-network/raiden | raiden/api/rest.py | APIServer.unhandled_exception | def unhandled_exception(self, exception: Exception):
""" Flask.errorhandler when an exception wasn't correctly handled """
log.critical(
'Unhandled exception when processing endpoint request',
exc_info=True,
node=pex(self.rest_api.raiden_api.address),
)
self.greenlet.kill(exception)
return api_error([str(exception)], HTTPStatus.INTERNAL_SERVER_ERROR) | python | def unhandled_exception(self, exception: Exception):
""" Flask.errorhandler when an exception wasn't correctly handled """
log.critical(
'Unhandled exception when processing endpoint request',
exc_info=True,
node=pex(self.rest_api.raiden_api.address),
)
self.greenlet.kill(exception)
return api_error([str(exception)], HTTPStatus.INTERNAL_SERVER_ERROR) | [
"def",
"unhandled_exception",
"(",
"self",
",",
"exception",
":",
"Exception",
")",
":",
"log",
".",
"critical",
"(",
"'Unhandled exception when processing endpoint request'",
",",
"exc_info",
"=",
"True",
",",
"node",
"=",
"pex",
"(",
"self",
".",
"rest_api",
"... | Flask.errorhandler when an exception wasn't correctly handled | [
"Flask",
".",
"errorhandler",
"when",
"an",
"exception",
"wasn",
"t",
"correctly",
"handled"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L540-L548 | train | 216,633 |
raiden-network/raiden | raiden/api/rest.py | RestAPI.get_connection_managers_info | def get_connection_managers_info(self, registry_address: typing.PaymentNetworkID):
"""Get a dict whose keys are token addresses and whose values are
open channels, funds of last request, sum of deposits and number of channels"""
log.debug(
'Getting connection managers info',
node=pex(self.raiden_api.address),
registry_address=to_checksum_address(registry_address),
)
connection_managers = dict()
for token in self.raiden_api.get_tokens_list(registry_address):
token_network_identifier = views.get_token_network_identifier_by_token_address(
views.state_from_raiden(self.raiden_api.raiden),
payment_network_id=registry_address,
token_address=token,
)
try:
connection_manager = self.raiden_api.raiden.connection_manager_for_token_network(
token_network_identifier,
)
except InvalidAddress:
connection_manager = None
open_channels = views.get_channelstate_open(
chain_state=views.state_from_raiden(self.raiden_api.raiden),
payment_network_id=registry_address,
token_address=token,
)
if connection_manager is not None and open_channels:
connection_managers[to_checksum_address(connection_manager.token_address)] = {
'funds': connection_manager.funds,
'sum_deposits': views.get_our_capacity_for_token_network(
views.state_from_raiden(self.raiden_api.raiden),
registry_address,
token,
),
'channels': len(open_channels),
}
return connection_managers | python | def get_connection_managers_info(self, registry_address: typing.PaymentNetworkID):
"""Get a dict whose keys are token addresses and whose values are
open channels, funds of last request, sum of deposits and number of channels"""
log.debug(
'Getting connection managers info',
node=pex(self.raiden_api.address),
registry_address=to_checksum_address(registry_address),
)
connection_managers = dict()
for token in self.raiden_api.get_tokens_list(registry_address):
token_network_identifier = views.get_token_network_identifier_by_token_address(
views.state_from_raiden(self.raiden_api.raiden),
payment_network_id=registry_address,
token_address=token,
)
try:
connection_manager = self.raiden_api.raiden.connection_manager_for_token_network(
token_network_identifier,
)
except InvalidAddress:
connection_manager = None
open_channels = views.get_channelstate_open(
chain_state=views.state_from_raiden(self.raiden_api.raiden),
payment_network_id=registry_address,
token_address=token,
)
if connection_manager is not None and open_channels:
connection_managers[to_checksum_address(connection_manager.token_address)] = {
'funds': connection_manager.funds,
'sum_deposits': views.get_our_capacity_for_token_network(
views.state_from_raiden(self.raiden_api.raiden),
registry_address,
token,
),
'channels': len(open_channels),
}
return connection_managers | [
"def",
"get_connection_managers_info",
"(",
"self",
",",
"registry_address",
":",
"typing",
".",
"PaymentNetworkID",
")",
":",
"log",
".",
"debug",
"(",
"'Getting connection managers info'",
",",
"node",
"=",
"pex",
"(",
"self",
".",
"raiden_api",
".",
"address",
... | Get a dict whose keys are token addresses and whose values are
open channels, funds of last request, sum of deposits and number of channels | [
"Get",
"a",
"dict",
"whose",
"keys",
"are",
"token",
"addresses",
"and",
"whose",
"values",
"are",
"open",
"channels",
"funds",
"of",
"last",
"request",
"sum",
"of",
"deposits",
"and",
"number",
"of",
"channels"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/api/rest.py#L788-L828 | train | 216,634 |
raiden-network/raiden | raiden/ui/startup.py | setup_network_id_or_exit | def setup_network_id_or_exit(
config: Dict[str, Any],
given_network_id: int,
web3: Web3,
) -> Tuple[int, bool]:
"""
Takes the given network id and checks it against the connected network
If they don't match, exits the program with an error. If they do adds it
to the configuration and then returns it and whether it is a known network
"""
node_network_id = int(web3.version.network) # pylint: disable=no-member
known_given_network_id = given_network_id in ID_TO_NETWORKNAME
known_node_network_id = node_network_id in ID_TO_NETWORKNAME
if node_network_id != given_network_id:
if known_given_network_id and known_node_network_id:
click.secho(
f"The chosen ethereum network '{ID_TO_NETWORKNAME[given_network_id]}' "
f"differs from the ethereum client '{ID_TO_NETWORKNAME[node_network_id]}'. "
"Please update your settings.",
fg='red',
)
else:
click.secho(
f"The chosen ethereum network id '{given_network_id}' differs "
f"from the ethereum client '{node_network_id}'. "
"Please update your settings.",
fg='red',
)
sys.exit(1)
config['chain_id'] = given_network_id
return given_network_id, known_node_network_id | python | def setup_network_id_or_exit(
config: Dict[str, Any],
given_network_id: int,
web3: Web3,
) -> Tuple[int, bool]:
"""
Takes the given network id and checks it against the connected network
If they don't match, exits the program with an error. If they do adds it
to the configuration and then returns it and whether it is a known network
"""
node_network_id = int(web3.version.network) # pylint: disable=no-member
known_given_network_id = given_network_id in ID_TO_NETWORKNAME
known_node_network_id = node_network_id in ID_TO_NETWORKNAME
if node_network_id != given_network_id:
if known_given_network_id and known_node_network_id:
click.secho(
f"The chosen ethereum network '{ID_TO_NETWORKNAME[given_network_id]}' "
f"differs from the ethereum client '{ID_TO_NETWORKNAME[node_network_id]}'. "
"Please update your settings.",
fg='red',
)
else:
click.secho(
f"The chosen ethereum network id '{given_network_id}' differs "
f"from the ethereum client '{node_network_id}'. "
"Please update your settings.",
fg='red',
)
sys.exit(1)
config['chain_id'] = given_network_id
return given_network_id, known_node_network_id | [
"def",
"setup_network_id_or_exit",
"(",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"given_network_id",
":",
"int",
",",
"web3",
":",
"Web3",
",",
")",
"->",
"Tuple",
"[",
"int",
",",
"bool",
"]",
":",
"node_network_id",
"=",
"int",
"(",
... | Takes the given network id and checks it against the connected network
If they don't match, exits the program with an error. If they do adds it
to the configuration and then returns it and whether it is a known network | [
"Takes",
"the",
"given",
"network",
"id",
"and",
"checks",
"it",
"against",
"the",
"connected",
"network"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/startup.py#L46-L79 | train | 216,635 |
raiden-network/raiden | raiden/ui/startup.py | setup_environment | def setup_environment(config: Dict[str, Any], environment_type: Environment) -> None:
"""Sets the config depending on the environment type"""
# interpret the provided string argument
if environment_type == Environment.PRODUCTION:
# Safe configuration: restrictions for mainnet apply and matrix rooms have to be private
config['transport']['matrix']['private_rooms'] = True
config['environment_type'] = environment_type
print(f'Raiden is running in {environment_type.value.lower()} mode') | python | def setup_environment(config: Dict[str, Any], environment_type: Environment) -> None:
"""Sets the config depending on the environment type"""
# interpret the provided string argument
if environment_type == Environment.PRODUCTION:
# Safe configuration: restrictions for mainnet apply and matrix rooms have to be private
config['transport']['matrix']['private_rooms'] = True
config['environment_type'] = environment_type
print(f'Raiden is running in {environment_type.value.lower()} mode') | [
"def",
"setup_environment",
"(",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"environment_type",
":",
"Environment",
")",
"->",
"None",
":",
"# interpret the provided string argument",
"if",
"environment_type",
"==",
"Environment",
".",
"PRODUCTION",
... | Sets the config depending on the environment type | [
"Sets",
"the",
"config",
"depending",
"on",
"the",
"environment",
"type"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/startup.py#L82-L91 | train | 216,636 |
raiden-network/raiden | raiden/ui/startup.py | setup_contracts_or_exit | def setup_contracts_or_exit(
config: Dict[str, Any],
network_id: int,
) -> Dict[str, Any]:
"""Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error
"""
environment_type = config['environment_type']
not_allowed = ( # for now we only disallow mainnet with test configuration
network_id == 1 and
environment_type == Environment.DEVELOPMENT
)
if not_allowed:
click.secho(
f'The chosen network ({ID_TO_NETWORKNAME[network_id]}) is not a testnet, '
f'but the "development" environment was selected.\n'
f'This is not allowed. Please start again with a safe environment setting '
f'(--environment production).',
fg='red',
)
sys.exit(1)
contracts = dict()
contracts_version = environment_type_to_contracts_version(environment_type)
config['contracts_path'] = contracts_precompiled_path(contracts_version)
if network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[network_id] != 'smoketest':
try:
deployment_data = get_contracts_deployment_info(
chain_id=network_id,
version=contracts_version,
)
except ValueError:
return contracts, False
contracts = deployment_data['contracts']
return contracts | python | def setup_contracts_or_exit(
config: Dict[str, Any],
network_id: int,
) -> Dict[str, Any]:
"""Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error
"""
environment_type = config['environment_type']
not_allowed = ( # for now we only disallow mainnet with test configuration
network_id == 1 and
environment_type == Environment.DEVELOPMENT
)
if not_allowed:
click.secho(
f'The chosen network ({ID_TO_NETWORKNAME[network_id]}) is not a testnet, '
f'but the "development" environment was selected.\n'
f'This is not allowed. Please start again with a safe environment setting '
f'(--environment production).',
fg='red',
)
sys.exit(1)
contracts = dict()
contracts_version = environment_type_to_contracts_version(environment_type)
config['contracts_path'] = contracts_precompiled_path(contracts_version)
if network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[network_id] != 'smoketest':
try:
deployment_data = get_contracts_deployment_info(
chain_id=network_id,
version=contracts_version,
)
except ValueError:
return contracts, False
contracts = deployment_data['contracts']
return contracts | [
"def",
"setup_contracts_or_exit",
"(",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"network_id",
":",
"int",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"environment_type",
"=",
"config",
"[",
"'environment_type'",
"]",
"not_al... | Sets the contract deployment data depending on the network id and environment type
If an invalid combination of network id and environment type is provided, exits
the program with an error | [
"Sets",
"the",
"contract",
"deployment",
"data",
"depending",
"on",
"the",
"network",
"id",
"and",
"environment",
"type"
] | 407ba15c72074e9de88771d6b9661ff4dc36bef5 | https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/ui/startup.py#L94-L135 | train | 216,637 |
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]:
""" 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 | [
"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 | train | 216,638 |
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:
"""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,
) | [
"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 | train | 216,639 |
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:
"""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,
) | [
"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 | train | 216,640 |
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:
"""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,
) | [
"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 | train | 216,641 |
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:
"""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) | [
"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 | train | 216,642 |
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:
"""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,
) | [
"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 | train | 216,643 |
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:
"""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),
) | [
"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 | train | 216,644 |
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:
"""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) | [
"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 | train | 216,645 |
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):
""" 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() | [
"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 | train | 216,646 |
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):
""" 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) | [
"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 | train | 216,647 |
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):
""" 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() | [
"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 | train | 216,648 |
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):
""" 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) | [
"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 | train | 216,649 |
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:
"""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 | [
"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 | train | 216,650 |
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:
"""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 | [
"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 | train | 216,651 |
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]:
""" 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 | [
"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 | train | 216,652 |
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]]:
"""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 | [
"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 | train | 216,653 |
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:
"""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 | [
"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 | train | 216,654 |
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):
""" 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) | [
"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 | train | 216,655 |
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]):
""" 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) | [
"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 | train | 216,656 |
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]:
""" Return all known user ids for the given ``address``. """
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 | train | 216,657 |
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 the current presence state of ``user_id``. """
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 | train | 216,658 |
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 the current reachability state for ``address``. """
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 | train | 216,659 |
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):
""" 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 | [
"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 | train | 216,660 |
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):
"""
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) | [
"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 | train | 216,661 |
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]):
"""
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) | [
"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 | train | 216,662 |
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):
""" 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) | [
"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 | train | 216,663 |
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):
""" 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) | [
"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 | train | 216,664 |
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):
""" 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) | [
"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 | train | 216,665 |
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):
""" 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) | [
"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 | train | 216,666 |
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):
""" 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) | [
"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 | train | 216,667 |
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):
"""Remove callback from the list of callbacks if it exists"""
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 | train | 216,668 |
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):
""" 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) | [
"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 | train | 216,669 |
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):
""" 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 | [
"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 | train | 216,670 |
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]:
""" 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 | [
"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 | train | 216,671 |
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:
"""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)
)) | [
"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 | train | 216,672 |
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]:
"""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 | [
"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 | train | 216,673 |
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):
""" 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() | [
"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 | train | 216,674 |
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):
""" 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 | [
"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 | train | 216,675 |
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):
"""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) | [
"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 | train | 216,676 |
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,
):
"""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) | [
"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 | train | 216,677 |
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:
"""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() | [
"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 | train | 216,678 |
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):
""" 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),
) | [
"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 | train | 216,679 |
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:
""" 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] | [
"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 | train | 216,680 |
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]):
""" 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,
) | [
"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 | train | 216,681 |
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:
""" Use eth_sign compatible hasher to sign matrix data """
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 | train | 216,682 |
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:
"""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 | [
"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 | train | 216,683 |
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):
""" 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) | [
"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 | train | 216,684 |
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]:
""" 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 | [
"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 | train | 216,685 |
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]]):
"""
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}'
) | [
"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 | train | 216,686 |
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]:
"""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!') | [
"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 | train | 216,687 |
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:
"""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 | [
"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 | train | 216,688 |
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:
"""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') | [
"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 | train | 216,689 |
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]:
"""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 | [
"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 | train | 216,690 |
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):
"""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 | [
"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 | train | 216,691 |
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):
"""
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) | [
"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 | train | 216,692 |
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,
):
"""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,
) | [
"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 | train | 216,693 |
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:
"""Return inputs of a method call"""
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 | train | 216,694 |
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]:
"""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 | [
"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 | train | 216,695 |
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):
""" Sign message using 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 | train | 216,696 |
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:
"""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) | [
"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 | train | 216,697 |
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:
""" 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
) | [
"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 | train | 216,698 |
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',
):
""" 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 | [
"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 | train | 216,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.