Returns the payer channel of a given transfer pair or None if it's not found
503368
def get_payer_channel(
        channelidentifiers_to_channels: ChannelMap,
        transfer_pair: MediationPairState,
) -> Optional[NettingChannelState]:
    
    payer_channel_identifier = transfer_pair.payer_transfer.balance_proof.channel_identifier
    return channelidentifiers_to_channels.get(payer_channel_identifier)
869634
def _channel_exists_and_not_settled(
            self,
            participant1: Address,
            participant2: Address,
            block_identifier: BlockSpecification,
            channel_identifier: ChannelID = None,
    ) -> bool:
        """"""
        try:
            channel_state = self._get_channel_state(
                participant1=participant1,
                participant2=participant2,
                block_identifier=block_identifier,
                channel_identifier=channel_identifier,
            )
        except RaidenRecoverableError:
            return False
        exists_and_not_settled = (
            channel_state > ChannelState.NONEXISTENT and
            channel_state < ChannelState.SETTLED
        )
        return exists_and_not_settled
1211323
def settle(
            self,
            channel_identifier: ChannelID,
            transferred_amount: TokenAmount,
            locked_amount: TokenAmount,
            locksroot: Locksroot,
            partner: Address,
            partner_transferred_amount: TokenAmount,
            partner_locked_amount: TokenAmount,
            partner_locksroot: Locksroot,
            given_block_identifier: BlockSpecification,
    ):
        
        log_details = {
            'channel_identifier': channel_identifier,
            'token_network': pex(self.address),
            'node': pex(self.node_address),
            'partner': pex(partner),
            'transferred_amount': transferred_amount,
            'locked_amount': locked_amount,
            'locksroot': encode_hex(locksroot),
            'partner_transferred_amount': partner_transferred_amount,
            'partner_locked_amount': partner_locked_amount,
            'partner_locksroot': encode_hex(partner_locksroot),
        }
        log.debug('settle called', **log_details)

        checking_block = self.client.get_checking_block()
        # and now find out
        our_maximum = transferred_amount + locked_amount
        partner_maximum = partner_transferred_amount + partner_locked_amount

        # The second participant transferred + locked amount must be higher
        our_bp_is_larger = our_maximum > partner_maximum
        if our_bp_is_larger:
            kwargs = {
                'participant1': partner,
                'participant1_transferred_amount': partner_transferred_amount,
                'participant1_locked_amount': partner_locked_amount,
                'participant1_locksroot': partner_locksroot,
                'participant2': self.node_address,
                'participant2_transferred_amount': transferred_amount,
                'participant2_locked_amount': locked_amount,
                'participant2_locksroot': locksroot,
            }
        else:
            kwargs = {
                'participant1': self.node_address,
                'participant1_transferred_amount': transferred_amount,
                'participant1_locked_amount': locked_amount,
                'participant1_locksroot': locksroot,
                'participant2': partner,
                'participant2_transferred_amount': partner_transferred_amount,
                'participant2_locked_amount': partner_locked_amount,
                'participant2_locksroot': partner_locksroot,
            }
        try:
            self._settle_preconditions(
                channel_identifier=channel_identifier,
                partner=partner,
                block_identifier=given_block_identifier,
            )
        except NoStateForBlockIdentifier:
            # If preconditions end up being on pruned state skip them. Estimate
            # gas will stop us from sending a transaction that will fail
            pass

        with self.channel_operations_lock[partner]:
            error_prefix = 'Call to settle will fail'
            gas_limit = self.proxy.estimate_gas(
                checking_block,
                'settleChannel',
                channel_identifier=channel_identifier,
                **kwargs,
            )

            if gas_limit:
                error_prefix = 'settle call failed'
                gas_limit = safe_gas_limit(gas_limit, GAS_REQUIRED_FOR_SETTLE_CHANNEL)

                transaction_hash = self.proxy.transact(
                    'settleChannel',
                    gas_limit,
                    channel_identifier=channel_identifier,
                    **kwargs,
                )
                self.client.poll(transaction_hash)
                receipt_or_none = check_transaction_threw(self.client, transaction_hash)

        transaction_executed = gas_limit is not None
        if not transaction_executed or receipt_or_none:
            if transaction_executed:
                block = receipt_or_none['blockNumber']
            else:
                block = checking_block

            self.proxy.jsonrpc_client.check_for_insufficient_eth(
                transaction_name='settleChannel',
                transaction_executed=transaction_executed,
                required_gas=GAS_REQUIRED_FOR_SETTLE_CHANNEL,
                block_identifier=block,
            )
            msg = self._check_channel_state_after_settle(
                participant1=self.node_address,
                participant2=partner,
                block_identifier=block,
                channel_identifier=channel_identifier,
            )
            error_msg = f'{error_prefix}. {msg}'
            log.critical(error_msg, **log_details)
            raise RaidenUnrecoverableError(error_msg)

        log.info('settle successful', **log_details)
206705
@Nullable
    public StoredClientChannel getChannel(Sha256Hash id, Sha256Hash contractHash) {
        lock.lock();
        try {
            Set<StoredClientChannel> setChannels = mapChannels.get(id);
            for (StoredClientChannel channel : setChannels) {
                if (channel.contract.getTxId().equals(contractHash))
                    return channel;
            }
            return null;
        } finally {
            lock.unlock();
        }
    }
624106
def wait_for_payment_balance(
        raiden: 'RaidenService',
        payment_network_id: PaymentNetworkID,
        token_address: TokenAddress,
        partner_address: Address,
        target_address: Address,
        target_balance: TokenAmount,
        retry_timeout: float,
) -> None:
    
    def get_balance(end_state):
        if end_state.balance_proof:
            return end_state.balance_proof.transferred_amount
        else:
            return 0

    if target_address == raiden.address:
        balance = lambda channel_state: get_balance(channel_state.partner_state)
    elif target_address == partner_address:
        balance = lambda channel_state: get_balance(channel_state.our_state)
    else:
        raise ValueError('target_address must be one of the channel participants')

    channel_state = views.get_channelstate_for(
        views.state_from_raiden(raiden),
        payment_network_id,
        token_address,
        partner_address,
    )

    while balance(channel_state) < target_balance:
        log.critical('wait', b=balance(channel_state), t=target_balance)
        gevent.sleep(retry_timeout)
        channel_state = views.get_channelstate_for(
            views.state_from_raiden(raiden),
            payment_network_id,
            token_address,
            partner_address,
        )
1097728
def events_for_onchain_secretreveal_if_dangerzone(
        channelmap: ChannelMap,
        secrethash: SecretHash,
        transfers_pair: List[MediationPairState],
        block_number: BlockNumber,
        block_hash: BlockHash,
) -> List[Event]:
    
    events: List[Event] = list()

    all_payer_channels = []
    for pair in transfers_pair:
        channel_state = get_payer_channel(channelmap, pair)
        if channel_state:
            all_payer_channels.append(channel_state)

    transaction_sent = has_secret_registration_started(
        all_payer_channels,
        transfers_pair,
        secrethash,
    )

    # Only consider the transfers which have a pair. This means if we have a
    # waiting transfer and for some reason the node knows the secret, it will
    # not try to register it. Otherwise it would be possible for an attacker to
    # reveal the secret late, just to force the node to send an unecessary
    # transaction.

    for pair in get_pending_transfer_pairs(transfers_pair):
        payer_channel = get_payer_channel(channelmap, pair)
        if not payer_channel:
            continue

        lock = pair.payer_transfer.lock

        safe_to_wait, _ = is_safe_to_wait(
            lock.expiration,
            payer_channel.reveal_timeout,
            block_number,
        )

        secret_known = channel.is_secret_known(
            payer_channel.partner_state,
            pair.payer_transfer.lock.secrethash,
        )

        if not safe_to_wait and secret_known:
            pair.payer_state = 'payer_waiting_secret_reveal'

            if not transaction_sent:
                secret = channel.get_secret(
                    payer_channel.partner_state,
                    lock.secrethash,
                )
                assert secret, 'the secret should be known at this point'

                reveal_events = secret_registry.events_for_onchain_secretreveal(
                    channel_state=payer_channel,
                    secret=secret,
                    expiration=lock.expiration,
                    block_hash=block_hash,
                )
                events.extend(reveal_events)

                transaction_sent = True

    return events
1177725
async function getBCHBalance(addr, verbose) {
  try {
    const result = await Wormhole.Address.details([addr])

    if (verbose) console.log(result)

    const bchBalance = result[0]

    return bchBalance.balance
  } catch (err) {
    console.error(`Error in getBCHBalance: `, err)
    console.log(`addr: ${addr}`)
    throw err
  }
}
1138551
def _get_channel(self):
        
        channel = self._transport.open_session()
        channel.set_combine_stderr(True)
        channel.get_pty()
        return channel
532227
def _find_new_partners(self):
        
        open_channels = views.get_channelstate_open(
            chain_state=views.state_from_raiden(self.raiden),
            payment_network_id=self.registry_address,
            token_address=self.token_address,
        )
        known = set(channel_state.partner_state.address for channel_state in open_channels)
        known.add(self.BOOTSTRAP_ADDR)
        known.add(self.raiden.address)

        participants_addresses = views.get_participants_addresses(
            views.state_from_raiden(self.raiden),
            self.registry_address,
            self.token_address,
        )

        available = participants_addresses - known
        available = list(available)
        shuffle(available)
        new_partners = available

        log.debug(
            'Found partners',
            node=pex(self.raiden.address),
            number_of_partners=len(available),
        )

        return new_partners
150592
def handle_cancelpayment(
        payment_state: InitiatorPaymentState,
        channelidentifiers_to_channels: ChannelMap,
) -> TransitionResult[InitiatorPaymentState]:
    
    # Cannot cancel a transfer after the secret is revealed
    events = list()
    for initiator_state in payment_state.initiator_transfers.values():
        channel_identifier = initiator_state.channel_identifier
        channel_state = channelidentifiers_to_channels.get(channel_identifier)

        if not channel_state:
            continue

        if can_cancel(initiator_state):
            transfer_description = initiator_state.transfer_description
            cancel_events = cancel_current_route(payment_state, initiator_state)

            initiator_state.transfer_state = 'transfer_cancelled'

            cancel = EventPaymentSentFailed(
                payment_network_identifier=channel_state.payment_network_identifier,
                token_network_identifier=TokenNetworkID(channel_state.token_network_identifier),
                identifier=transfer_description.payment_identifier,
                target=transfer_description.target,
                reason='user canceled payment',
            )
            cancel_events.append(cancel)

            events.extend(cancel_events)

    return TransitionResult(payment_state, events)
159835
@Override
    public List<String> getDefaultProviderChain() {
        List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());
        Collections.sort(result);
        return result;
    }
427189
def subdispatch_to_all_initiatortransfer(
        payment_state: InitiatorPaymentState,
        state_change: StateChange,
        channelidentifiers_to_channels: ChannelMap,
        pseudo_random_generator: random.Random,
) -> TransitionResult[InitiatorPaymentState]:
    events = list()
    ''' 
    '''
    for secrethash in list(payment_state.initiator_transfers.keys()):
        initiator_state = payment_state.initiator_transfers[secrethash]
        sub_iteration = subdispatch_to_initiatortransfer(
            payment_state=payment_state,
            initiator_state=initiator_state,
            state_change=state_change,
            channelidentifiers_to_channels=channelidentifiers_to_channels,
            pseudo_random_generator=pseudo_random_generator,
        )
        events.extend(sub_iteration.events)
    return TransitionResult(payment_state, events)
1203872
def transfer(self):
        
        result = self.client.get('/account/transfer')

        if not 'used' in result:
            raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!')

        return MappedObject(**result)
1123670
def handle_offchain_secretreveal(
        mediator_state: MediatorTransferState,
        mediator_state_change: ReceiveSecretReveal,
        channelidentifiers_to_channels: ChannelMap,
        pseudo_random_generator: random.Random,
        block_number: BlockNumber,
        block_hash: BlockHash,
) -> TransitionResult[MediatorTransferState]:
    
    is_valid_reveal = is_valid_secret_reveal(
        state_change=mediator_state_change,
        transfer_secrethash=mediator_state.secrethash,
        secret=mediator_state_change.secret,
    )
    is_secret_unknown = mediator_state.secret is None

    # a SecretReveal should be rejected if the payer transfer
    # has expired. To check for this, we use the last
    # transfer pair.
    transfer_pair = mediator_state.transfers_pair[-1]
    payer_transfer = transfer_pair.payer_transfer
    channel_identifier = payer_transfer.balance_proof.channel_identifier
    payer_channel = channelidentifiers_to_channels.get(channel_identifier)
    if not payer_channel:
        return TransitionResult(mediator_state, list())

    has_payer_transfer_expired = channel.is_transfer_expired(
        transfer=transfer_pair.payer_transfer,
        affected_channel=payer_channel,
        block_number=block_number,
    )

    if is_secret_unknown and is_valid_reveal and not has_payer_transfer_expired:
        iteration = secret_learned(
            state=mediator_state,
            channelidentifiers_to_channels=channelidentifiers_to_channels,
            pseudo_random_generator=pseudo_random_generator,
            block_number=block_number,
            block_hash=block_hash,
            secret=mediator_state_change.secret,
            secrethash=mediator_state_change.secrethash,
            payee_address=mediator_state_change.sender,
        )

    else:
        iteration = TransitionResult(mediator_state, list())

    return iteration
1231988
def channel_open(
            self,
            registry_address: PaymentNetworkID,
            token_address: TokenAddress,
            partner_address: Address,
            settle_timeout: BlockTimeout = None,
            retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT,
    ) -> ChannelID:
        
        if settle_timeout is None:
            settle_timeout = self.raiden.config['settle_timeout']

        if settle_timeout < self.raiden.config['reveal_timeout'] * 2:
            raise InvalidSettleTimeout(
                'settle_timeout can not be smaller than double the reveal_timeout',
            )

        if not is_binary_address(registry_address):
            raise InvalidAddress('Expected binary address format for registry in channel open')

        if not is_binary_address(token_address):
            raise InvalidAddress('Expected binary address format for token in channel open')

        if not is_binary_address(partner_address):
            raise InvalidAddress('Expected binary address format for partner in channel open')

        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state=chain_state,
            payment_network_id=registry_address,
            token_address=token_address,
            partner_address=partner_address,
        )

        if channel_state:
            raise DuplicatedChannelError('Channel with given partner address already exists')

        registry = self.raiden.chain.token_network_registry(registry_address)
        token_network_address = registry.get_token_network(token_address)

        if token_network_address is None:
            raise TokenNotRegistered(
                'Token network for token %s does not exist' % to_checksum_address(token_address),
            )

        token_network = self.raiden.chain.token_network(
            registry.get_token_network(token_address),
        )

        with self.raiden.gas_reserve_lock:
            has_enough_reserve, estimated_required_reserve = has_enough_gas_reserve(
                self.raiden,
                channels_to_open=1,
            )

            if not has_enough_reserve:
                raise InsufficientGasReserve((
                    'The account balance is below the estimated amount necessary to '
                    'finish the lifecycles of all active channels. A balance of at '
                    f'least {estimated_required_reserve} wei is required.'
                ))

            try:
                token_network.new_netting_channel(
                    partner=partner_address,
                    settle_timeout=settle_timeout,
                    given_block_identifier=views.state_from_raiden(self.raiden).block_hash,
                )
            except DuplicatedChannelError:
                log.info('partner opened channel first')

        waiting.wait_for_newchannel(
            raiden=self.raiden,
            payment_network_id=registry_address,
            token_address=token_address,
            partner_address=partner_address,
            retry_timeout=retry_timeout,
        )
        chain_state = views.state_from_raiden(self.raiden)
        channel_state = views.get_channelstate_for(
            chain_state=chain_state,
            payment_network_id=registry_address,
            token_address=token_address,
            partner_address=partner_address,
        )

        assert channel_state, f'channel {channel_state} is gone'

        return channel_state.identifier
584426
def is_send_transfer_almost_equal(
        send_channel: NettingChannelState,
        send: LockedTransferUnsignedState,
        received: LockedTransferSignedState,
) -> bool:
    
    # The only thing that may change is the direction of the transfer
    return (
        isinstance(send, LockedTransferUnsignedState) and
        isinstance(received, LockedTransferSignedState) and
        send.payment_identifier == received.payment_identifier and
        send.token == received.token and
        send.lock.amount == received.lock.amount - send_channel.mediation_fee and
        send.lock.expiration == received.lock.expiration and
        send.lock.secrethash == received.lock.secrethash and
        send.initiator == received.initiator and
        send.target == received.target
    )
906616
def transfer(self, receiver_address, amount, from_account):
        
        tx_hash = self.send_transaction(
            'transfer',
            (receiver_address,
             amount),
            transact={'from': from_account.address,
                      'passphrase': from_account.password}
        )
        return self.get_tx_receipt(tx_hash).status == 1