How to use the raiden.utils.formatting.to_checksum_address function in raiden

To help you get started, we’ve selected a few raiden examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github raiden-network / raiden / raiden / network / proxies / token.py View on Github external
"allowance": allowance,
            }

            with log_transaction(log, "approve", log_details):
                checking_block = self.client.get_checking_block()
                error_prefix = "Call to approve will fail"
                gas_limit = self.proxy.estimate_gas(
                    checking_block, "approve", to_checksum_address(allowed_address), allowance
                )

                if gas_limit:
                    error_prefix = "Call to approve failed"
                    gas_limit = safe_gas_limit(gas_limit)
                    log_details["gas_limit"] = gas_limit
                    transaction_hash = self.proxy.transact(
                        "approve", gas_limit, to_checksum_address(allowed_address), allowance
                    )

                    receipt = self.client.poll(transaction_hash)
                    failed_receipt = check_transaction_threw(receipt=receipt)

                    if failed_receipt:
                        failed_at_blockhash = encode_hex(failed_receipt["blockHash"])

                        if failed_receipt["cumulativeGasUsed"] == gas_limit:
                            msg = (
                                f"approve failed and all gas was used ({gas_limit}). "
                                f"Estimate gas may have underestimated approve, or "
                                f"succeeded even though an assert is triggered, or "
                                f"the smart contract code has a conditional assert."
                            )
                            raise RaidenRecoverableError(msg)
github raiden-network / raiden / raiden / network / proxies / user_deposit.py View on Github external
def deposit(
        self,
        beneficiary: Address,
        total_deposit: TokenAmount,
        given_block_identifier: BlockSpecification,
    ) -> None:
        """ Deposit provided amount into the user-deposit contract
        to the beneficiary's account. """

        token_address = self.token_address(given_block_identifier)
        token = self.proxy_manager.token(token_address=token_address)

        log_details = {
            "beneficiary": to_checksum_address(beneficiary),
            "contract": to_checksum_address(self.address),
            "node": to_checksum_address(self.node_address),
            "total_deposit": total_deposit,
        }

        # To prevent concurrent transactions for token transfers where it is unknown if
        # we have enough capacity for both, we acquire the lock
        # for the token proxy. Example: A user deposit and a channel deposit
        # for the same token.
        with self.deposit_lock, token.token_lock:
            # check preconditions
            try:
                previous_total_deposit = self.get_total_deposit(
                    address=beneficiary, block_identifier=given_block_identifier
                )
                current_balance = token.balance_of(
                    address=self.node_address, block_identifier=given_block_identifier
                )
github raiden-network / raiden / raiden / network / transport / matrix / transport.py View on Github external
def _set_room_id_for_address(
        self, address: Address, room_id: Optional[_RoomID] = None
    ) -> 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)
        room_ids = self._get_room_ids_for_address(address)

        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
github raiden-network / raiden / raiden / network / transport / matrix / transport.py View on Github external
f"node: {self._user_id}, "
            f"peer: {to_checksum_address(address)}"
        )
        assert address and self._address_mgr.is_address_known(address), msg

        room_candidates = []
        room_ids = self._get_room_ids_for_address(address)
        if room_ids:
            while room_ids:
                room_id = room_ids.pop(0)
                room = self._client.rooms[room_id]
                if self._is_broadcast_room(room):
                    self.log.warning(
                        "Ignoring broadcast room for peer",
                        room=room,
                        peer=to_checksum_address(address),
                    )
                    continue
                room_candidates.append(room)

        if room_candidates:
            if not require_online_peer:
                # Return the first existing room
                room = room_candidates[0]
                self.log.debug(
                    "Existing room",
                    room=room,
                    members=room.get_joined_members(),
                    require_online_peer=require_online_peer,
                )
                return room
            else:
github raiden-network / raiden / raiden / network / proxies / token.py View on Github external
def allowance(
        self, owner: Address, spender: Address, block_identifier: BlockSpecification
    ) -> TokenAmount:
        return TokenAmount(
            self.proxy.contract.functions.allowance(
                to_checksum_address(owner), to_checksum_address(spender)
            ).call(block_identifier=block_identifier)
        )
github raiden-network / raiden / raiden / api / rest.py View on Github external
def get_channel_list(
        self,
        registry_address: TokenNetworkRegistryAddress,
        token_address: TokenAddress = None,
        partner_address: Address = None,
    ) -> Response:
        log.debug(
            "Getting channel list",
            node=to_checksum_address(self.raiden_api.address),
            registry_address=to_checksum_address(registry_address),
            token_address=optional_address_to_string(token_address),
            partner_address=optional_address_to_string(partner_address),
        )
        raiden_service_result = self.raiden_api.get_channel_list(
            registry_address, token_address, partner_address
        )
        assert isinstance(raiden_service_result, list)
        result = [
            self.channel_schema.dump(channel_schema) for channel_schema in raiden_service_result
        ]
        return api_response(result=result)
github raiden-network / raiden / raiden / waiting.py View on Github external
channel_state = views.get_channelstate_for(
        views.state_from_raiden(raiden),
        token_network_registry_address,
        token_address,
        partner_address,
    )
    if not channel_state:
        raise ValueError("no channel could be found between provided partner and target addresses")

    current_balance = balance(channel_state)

    log_details = {
        "node": to_checksum_address(raiden.address),
        "token_network_registry_address": to_checksum_address(token_network_registry_address),
        "token_address": to_checksum_address(token_address),
        "partner_address": to_checksum_address(partner_address),
        "target_address": to_checksum_address(target_address),
        "target_balance": target_balance,
    }
    while current_balance < target_balance:
        assert raiden, ALARM_TASK_ERROR_MSG
        assert raiden.alarm, ALARM_TASK_ERROR_MSG

        log.debug("wait_for_participant_deposit", current_balance=current_balance, **log_details)
        gevent.sleep(retry_timeout)
        channel_state = views.get_channelstate_for(
            views.state_from_raiden(raiden),
            token_network_registry_address,
            token_address,
            partner_address,
        )
        current_balance = balance(channel_state)
github raiden-network / raiden / raiden / raiden_service.py View on Github external
secrethash: SecretHash = None,
        lock_timeout: BlockTimeout = None,
    ) -> PaymentStatus:

        if secrethash is None:
            secrethash = sha256_secrethash(secret)
        elif secret != ABSENT_SECRET:
            if secrethash != sha256_secrethash(secret):
                raise InvalidSecretHash("provided secret and secret_hash do not match.")
            if len(secret) != SECRET_LENGTH:
                raise InvalidSecret("secret of invalid length.")

        log.debug(
            "Mediated transfer",
            node=to_checksum_address(self.address),
            target=to_checksum_address(target),
            amount=amount,
            identifier=identifier,
            token_network_address=to_checksum_address(token_network_address),
        )

        # We must check if the secret was registered against the latest block,
        # even if the block is forked away and the transaction that registers
        # the secret is removed from the blockchain. The rationale here is that
        # someone else does know the secret, regardless of the chain state, so
        # the node must not use it to start a payment.
        #
        # For this particular case, it's preferable to use `latest` instead of
        # having a specific block_hash, because it's preferable to know if the secret
        # was ever known, rather than having a consistent view of the blockchain.
        secret_registered = self.default_secret_registry.is_secret_registered(
            secrethash=secrethash, block_identifier="latest"
github raiden-network / raiden / raiden / raiden_service.py View on Github external
if secrethash is None:
            secrethash = sha256_secrethash(secret)
        elif secret != ABSENT_SECRET:
            if secrethash != sha256_secrethash(secret):
                raise InvalidSecretHash("provided secret and secret_hash do not match.")
            if len(secret) != SECRET_LENGTH:
                raise InvalidSecret("secret of invalid length.")

        log.debug(
            "Mediated transfer",
            node=to_checksum_address(self.address),
            target=to_checksum_address(target),
            amount=amount,
            identifier=identifier,
            token_network_address=to_checksum_address(token_network_address),
        )

        # We must check if the secret was registered against the latest block,
        # even if the block is forked away and the transaction that registers
        # the secret is removed from the blockchain. The rationale here is that
        # someone else does know the secret, regardless of the chain state, so
        # the node must not use it to start a payment.
        #
        # For this particular case, it's preferable to use `latest` instead of
        # having a specific block_hash, because it's preferable to know if the secret
        # was ever known, rather than having a consistent view of the blockchain.
        secret_registered = self.default_secret_registry.is_secret_registered(
            secrethash=secrethash, block_identifier="latest"
        )
        if secret_registered:
            raise RaidenUnrecoverableError(
github raiden-network / raiden / raiden / api / rest.py View on Github external
def unhandled_exception(self, exception: Exception) -> Response:
        """ Flask.errorhandler when an exception wasn't correctly handled """
        log.critical(
            "Unhandled exception when processing endpoint request",
            exc_info=True,
            node=to_checksum_address(self.rest_api.raiden_api.address),
        )
        self.greenlet.kill(exception)
        return api_error([str(exception)], HTTPStatus.INTERNAL_SERVER_ERROR)