Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_save_and_load_token_networks(pathfinding_service_mock_empty):
pfs = pathfinding_service_mock_empty
token_address = TokenAddress(bytes([1] * 20))
token_network_address = TokenNetworkAddress(bytes([2] * 20))
channel_id = ChannelID(1)
p1 = Address(bytes([3] * 20))
p2 = Address(bytes([4] * 20))
events = [
ReceiveTokenNetworkCreatedEvent(
token_address=token_address,
token_network_address=token_network_address,
block_number=BlockNumber(1),
),
ReceiveChannelOpenedEvent(
token_network_address=token_network_address,
channel_identifier=channel_id,
participant1=p1,
participant2=p2,
settle_timeout=BlockTimeout(2 ** 65), # larger than max_uint64 to check hex storage
block_number=BlockNumber(2),
),
]
# it fails it the no deposit is in the UDC
iou = make_iou(privkey, pfs.address)
with pytest.raises(exceptions.DepositTooLow):
test_payment(iou)
# adding deposit does not help immediately
deposit_to_udc(sender, 10)
with pytest.raises(exceptions.DepositTooLow):
test_payment(iou)
# must succeed after deposit is confirmed
web3.testing.mine(pathfinding_service_web3_mock.required_confirmations)
test_payment(iou)
# wrong recipient
iou = make_iou(privkey, Address(bytes([6] * 20)))
with pytest.raises(exceptions.WrongIOURecipient):
test_payment(iou)
# wrong chain_id
iou = make_iou(privkey, pfs.address, chain_id=2)
with pytest.raises(exceptions.UnsupportedChainID):
test_payment(iou)
# wrong one_to_n_address
iou = make_iou(privkey, pfs.address, one_to_n_address=bytes([1] * 20))
with pytest.raises(exceptions.WrongOneToNAddress):
test_payment(iou)
# payment too low
iou = make_iou(privkey, pfs.address)
with pytest.raises(exceptions.InsufficientServicePayment):
)
receipt = self.client.poll(transaction_hash)
failed_receipt = check_transaction_threw(receipt=receipt)
if failed_receipt:
failed_at_blocknumber = failed_receipt["blockNumber"]
latest_deposit = self.get_total_deposit(
address=self.node_address, block_identifier=failed_at_blocknumber
)
amount_to_deposit = TokenAmount(total_deposit - latest_deposit)
allowance = token.allowance(
owner=self.node_address,
spender=Address(self.address),
block_identifier=failed_at_blocknumber,
)
whole_balance = self.whole_balance(block_identifier=failed_at_blocknumber)
whole_balance_limit = self.whole_balance_limit(
block_identifier=failed_at_blocknumber
)
if latest_deposit >= total_deposit:
msg = "Deposit amount already increased after another transaction"
raise RaidenRecoverableError(msg)
if allowance < amount_to_deposit:
msg = (
"The allowance is insufficient. Check concurrent deposits "
"for the same token network but different proxies."
# the handler handle_receive_lockedtransfer.
target_state = TargetTransferState(route, transfer)
safe_to_wait = is_safe_to_wait(
transfer.lock.expiration, channel_state.reveal_timeout, block_number
)
# If there is not enough time to safely unlock the lock on-chain
# silently let the transfer expire. The target task must be created to
# handle the ReceiveLockExpired state change, which will clear the
# expired lock.
if safe_to_wait:
message_identifier = message_identifier_from_prng(pseudo_random_generator)
recipient = transfer.initiator
secret_request = SendSecretRequest(
recipient=Address(recipient),
message_identifier=message_identifier,
payment_identifier=transfer.payment_identifier,
amount=transfer.lock.amount,
expiration=transfer.lock.expiration,
secrethash=transfer.lock.secrethash,
canonical_identifier=CANONICAL_IDENTIFIER_GLOBAL_QUEUE,
)
channel_events.append(secret_request)
iteration = TransitionResult(target_state, channel_events)
else:
# If the balance proof is not valid, do *not* create a task. Otherwise it's
# possible for an attacker to send multiple invalid transfers, and increase
# the memory usage of this Node.
assert errormsg, "handle_receive_lockedtransfer should return error msg if not valid"
unlock_failed = EventUnlockClaimFailed(
)
events.append(
ReceiveTokenNetworkCreatedEvent(
token_network_address=token_network_address,
token_address=to_canonical_address(event_dict["args"]["token_address"]),
block_number=event_dict["blockNumber"],
)
)
new_chain_state.token_network_addresses.append(token_network_address)
# then check all token networks
for token_network_address in new_chain_state.token_network_addresses:
network_events = query_blockchain_events(
web3=web3,
contract_manager=contract_manager,
contract_address=Address(token_network_address),
contract_name=CONTRACT_TOKEN_NETWORK,
topics=[None],
from_block=from_block,
to_block=to_block,
)
for event_dict in network_events:
event = parse_token_network_event(event_dict)
if event:
events.append(event)
# get events from monitoring service contract, this only queries the chain
# if the monitor contract address is set in chain_state
monitoring_events = get_monitoring_blockchain_events(
web3=web3,
contract_manager=contract_manager,
def get_pfs_info(url: str) -> PFSInfo:
try:
response = requests.get(f"{url}/api/v1/info", timeout=DEFAULT_HTTP_REQUEST_TIMEOUT)
infos = get_response_json(response)
return PFSInfo(
url=url,
price=infos["price_info"],
chain_id=infos["network_info"]["chain_id"],
token_network_registry_address=TokenNetworkRegistryAddress(
to_canonical_address(infos["network_info"]["token_network_registry_address"])
),
user_deposit_address=Address(
to_canonical_address(infos["network_info"]["user_deposit_address"])
),
payment_address=to_canonical_address(infos["payment_address"]),
message=infos["message"],
operator=infos["operator"],
version=infos["version"],
)
except requests.exceptions.RequestException as e:
msg = "Selected Pathfinding Service did not respond"
raise ServiceRequestFailed(msg) from e
except (json.JSONDecodeError, requests.exceptions.RequestException, KeyError) as e:
msg = "Selected Pathfinding Service returned unexpected reply"
raise ServiceRequestFailed(msg) from e
if not is_binary_address(monitoring_service_address):
raise ValueError("Expected binary address for monitoring service")
self.contract_manager = contract_manager
check_address_has_code(
client=jsonrpc_client,
address=Address(monitoring_service_address),
contract_name=CONTRACT_MONITORING_SERVICE,
expected_code=decode_hex(
contract_manager.get_runtime_hexcode(CONTRACT_MONITORING_SERVICE)
),
)
proxy = jsonrpc_client.new_contract_proxy(
abi=self.contract_manager.get_contract_abi(CONTRACT_MONITORING_SERVICE),
contract_address=Address(monitoring_service_address),
)
self.address = monitoring_service_address
self.proxy = proxy
self.client = jsonrpc_client
self.node_address = self.client.address
all_neighbour_nodes = views.all_neighbour_nodes(chain_state)
for neighbour in all_neighbour_nodes:
if neighbour == ConnectionManager.BOOTSTRAP_ADDR:
continue
neighbour_addresses.append(neighbour)
events_queues = views.get_all_messagequeues(chain_state)
for event_queue in events_queues.values():
for event in event_queue:
if isinstance(event, SendLockedTransfer):
transfer = event.transfer
if transfer.initiator == self.address:
neighbour_addresses.append(Address(transfer.target))
return neighbour_addresses
from dataclasses import dataclass
from typing import Optional
from monitoring_service.constants import DEFAULT_FILTER_INTERVAL
from raiden.utils.typing import Address, BlockNumber, BlockTimeout, ChainID
@dataclass
class BlockchainState:
chain_id: ChainID
token_network_registry_address: Address
latest_committed_block: BlockNumber
monitor_contract_address: Optional[Address] = None
current_event_filter_interval: BlockTimeout = DEFAULT_FILTER_INTERVAL
def __init__(
self,
jsonrpc_client: JSONRPCClient,
token_address: TokenAddress,
contract_manager: ContractManager,
) -> None:
contract = jsonrpc_client.new_contract(
contract_manager.get_contract_abi(CONTRACT_CUSTOM_TOKEN), Address(token_address)
)
proxy = ContractProxy(jsonrpc_client, contract)
if not is_binary_address(token_address):
raise ValueError("token_address must be a valid address")
check_address_has_code(jsonrpc_client, Address(token_address), "Token", expected_code=None)
self.address = token_address
self.client = jsonrpc_client
self.node_address = jsonrpc_client.address
self.proxy = proxy
self.token_lock: RLock = RLock()