Esempio n. 1
0
 def deposit(from_offset, to_offset):
     return get_pessimistic_udc_balance(
         udc=user_deposit_contract,
         address=address,
         from_block=deposit_block + from_offset,
         to_block=deposit_block + to_offset,
     )
Esempio n. 2
0
def action_monitoring_triggered_event_handler(event: Event,
                                              context: Context) -> None:
    assert isinstance(event, ActionMonitoringTriggeredEvent)
    log.info("Triggering channel monitoring")

    monitor_request = context.database.get_monitor_request(
        token_network_address=event.token_network_address,
        channel_id=event.channel_identifier,
        non_closing_signer=event.non_closing_participant,
    )
    if monitor_request is None:
        log.error(
            "MonitorRequest cannot be found",
            token_network_address=event.token_network_address,
            channel_id=event.channel_identifier,
        )
        metrics.get_metrics_for_label(metrics.ERRORS_LOGGED,
                                      metrics.ErrorCategory.STATE).inc()
        return

    channel = context.database.get_channel(
        token_network_address=monitor_request.token_network_address,
        channel_id=monitor_request.channel_identifier,
    )
    if channel is None:
        log.error("Channel cannot be found", monitor_request=monitor_request)
        metrics.get_metrics_for_label(metrics.ERRORS_LOGGED,
                                      metrics.ErrorCategory.STATE).inc()
        return

    if not _is_mr_valid(monitor_request, channel):
        log.error(
            "MonitorRequest lost its validity",
            monitor_request=monitor_request,
            channel=channel,
        )
        metrics.get_metrics_for_label(metrics.ERRORS_LOGGED,
                                      metrics.ErrorCategory.PROTOCOL).inc()
        return

    last_onchain_nonce = 0
    if channel.update_status:
        last_onchain_nonce = channel.update_status.nonce

    if monitor_request.nonce <= last_onchain_nonce:
        log.info(
            "Another MS submitted the last known channel state",
            monitor_request=monitor_request,
        )
        return

    latest_block = context.web3.eth.blockNumber
    last_confirmed_block = context.latest_confirmed_block
    user_address = monitor_request.non_closing_signer
    user_deposit = get_pessimistic_udc_balance(
        udc=context.user_deposit_contract,
        address=user_address,
        from_block=last_confirmed_block,
        to_block=latest_block,
    )
    if monitor_request.reward_amount < context.min_reward:
        log.info(
            "Monitor request not executed due to insufficient reward amount",
            monitor_request=monitor_request,
            min_reward=context.min_reward,
        )
        return

    if user_deposit < monitor_request.reward_amount * UDC_SECURITY_MARGIN_FACTOR_MS:
        log.debug(
            "User deposit is insufficient -> try monitoring again later",
            monitor_request=monitor_request,
            min_reward=context.min_reward,
        )
        context.database.upsert_scheduled_event(
            ScheduledEvent(
                trigger_block_number=BlockNumber(last_confirmed_block + 1),
                event=event))
        return

    assert (channel.monitor_tx_hash is None
            ), "This MS already monitored this channel. Should be impossible."

    try:
        # Attackers might be able to construct MRs that make this fail.
        # Since we execute a gas estimation before doing the `transact`,
        # the gas estimation will fail before any gas is used.
        # If we stop doing a gas estimation, a `call` has to be done before
        # the `transact` to prevent attackers from wasting the MS's gas.
        tx_hash = TransactionHash(
            bytes(
                context.monitoring_service_contract.functions.monitor(
                    monitor_request.signer,
                    monitor_request.non_closing_signer,
                    monitor_request.balance_hash,
                    monitor_request.nonce,
                    monitor_request.additional_hash,
                    monitor_request.closing_signature,
                    monitor_request.non_closing_signature,
                    monitor_request.reward_amount,
                    monitor_request.token_network_address,
                    monitor_request.reward_proof_signature,
                ).transact({"from": context.ms_state.address})))
    except Exception as exc:  # pylint: disable=broad-except
        first_allowed = BlockNumber(
            _first_allowed_block_to_monitor(event.token_network_address,
                                            channel, context))
        failed_at = context.web3.eth.blockNumber
        log.error(
            "Sending tx failed",
            exc_info=True,
            err=exc,
            first_allowed=first_allowed,
            failed_at=failed_at,
        )
        metrics.get_metrics_for_label(metrics.ERRORS_LOGGED,
                                      metrics.ErrorCategory.BLOCKCHAIN).inc()
        return

    log.info(
        "Sent transaction calling `monitor` for channel",
        token_network_address=channel.token_network_address,
        channel_identifier=channel.identifier,
        transaction_hash=encode_hex(tx_hash),
    )
    assert tx_hash is not None

    with context.database.conn:
        # Add tx hash to list of waiting transactions
        context.database.add_waiting_transaction(tx_hash)

        channel.monitor_tx_hash = tx_hash
        context.database.upsert_channel(channel)
Esempio n. 3
0
def process_payment(  # pylint: disable=too-many-branches
    iou: Optional[IOU],
    pathfinding_service: PathfindingService,
    service_fee: TokenAmount,
    one_to_n_address: Address,
) -> None:
    if service_fee == 0:
        return
    if iou is None:
        raise exceptions.MissingIOU

    # Basic IOU validity checks
    if not is_same_address(iou.receiver, pathfinding_service.address):
        raise exceptions.WrongIOURecipient(
            expected=pathfinding_service.address)
    if iou.chain_id != pathfinding_service.chain_id:
        raise exceptions.UnsupportedChainID(
            expected=pathfinding_service.chain_id)
    if iou.one_to_n_address != one_to_n_address:
        raise exceptions.WrongOneToNAddress(expected=one_to_n_address,
                                            got=iou.one_to_n_address)
    if not iou.is_signature_valid():
        raise exceptions.InvalidSignature

    # Compare with known IOU
    active_iou = pathfinding_service.database.get_iou(sender=iou.sender,
                                                      claimed=False)
    if active_iou:
        if active_iou.expiration_block != iou.expiration_block:
            raise exceptions.UseThisIOU(iou=active_iou)

        expected_amount = active_iou.amount + service_fee
    else:
        claimed_iou = pathfinding_service.database.get_iou(
            sender=iou.sender,
            expiration_block=iou.expiration_block,
            claimed=True)
        if claimed_iou:
            raise exceptions.IOUAlreadyClaimed

        min_expiry = pathfinding_service.web3.eth.blockNumber + MIN_IOU_EXPIRY
        if iou.expiration_block < min_expiry:
            raise exceptions.IOUExpiredTooEarly(min_expiry=min_expiry)
        expected_amount = service_fee
    if iou.amount < expected_amount:
        raise exceptions.InsufficientServicePayment(
            expected_amount=expected_amount)

    # Check client's deposit in UserDeposit contract
    udc = pathfinding_service.user_deposit_contract
    latest_block = pathfinding_service.web3.eth.blockNumber
    udc_balance = get_pessimistic_udc_balance(
        udc=udc,
        address=iou.sender,
        from_block=latest_block - pathfinding_service.required_confirmations,
        to_block=latest_block,
    )
    required_deposit = round(expected_amount * UDC_SECURITY_MARGIN_FACTOR_PFS)
    if udc_balance < required_deposit:
        raise exceptions.DepositTooLow(required_deposit=required_deposit)

    log.info(
        "Received service fee",
        sender=iou.sender,
        expected_amount=expected_amount,
        total_amount=iou.amount,
        added_amount=expected_amount - service_fee,
    )

    # Save latest IOU
    iou.claimed = False
    pathfinding_service.database.upsert_iou(iou)
Esempio n. 4
0
def process_payment(  # pylint: disable=too-many-branches
    iou: Optional[IOU],
    pathfinding_service: PathfindingService,
    service_fee: TokenAmount,
    one_to_n_address: Address,
) -> None:
    if service_fee == 0:
        if iou is not None:
            log.debug(
                "Discarding IOU, service fee is 0",
                sender=to_checksum_address(iou.sender),
                total_amount=iou.amount,
                claimable_until=iou.claimable_until,
            )
        else:
            log.debug("No IOU and service fee is 0")
        return

    if iou is None:
        raise exceptions.MissingIOU

    log.debug(
        "Checking IOU",
        sender=to_checksum_address(iou.sender),
        total_amount=iou.amount,
        claimable_until=iou.claimable_until,
    )

    # Basic IOU validity checks
    if not is_same_address(iou.receiver, pathfinding_service.address):
        raise exceptions.WrongIOURecipient(expected=pathfinding_service.address)
    if iou.chain_id != pathfinding_service.chain_id:
        raise exceptions.UnsupportedChainID(expected=pathfinding_service.chain_id)
    if iou.one_to_n_address != one_to_n_address:
        raise exceptions.WrongOneToNAddress(expected=one_to_n_address, got=iou.one_to_n_address)
    if not iou.is_signature_valid():
        raise exceptions.InvalidSignature

    # Compare with known IOU
    latest_block = pathfinding_service.blockchain_state.latest_committed_block
    active_iou = pathfinding_service.database.get_iou(sender=iou.sender, claimed=False)

    if active_iou:
        if active_iou.claimable_until != iou.claimable_until:
            raise exceptions.UseThisIOU(iou=active_iou.Schema().dump(active_iou))

        expected_amount = active_iou.amount + service_fee
    else:
        claimed_iou = pathfinding_service.database.get_iou(
            sender=iou.sender, claimable_until=iou.claimable_until, claimed=True
        )
        if claimed_iou:
            raise exceptions.IOUAlreadyClaimed

        min_expiry = get_posix_utc_time_now() + MIN_IOU_EXPIRY
        if iou.claimable_until < min_expiry:
            raise exceptions.IOUExpiredTooEarly(
                min_expiry=min_expiry, claimable_until_received=iou.claimable_until
            )
        expected_amount = service_fee
    if iou.amount < expected_amount:
        raise exceptions.InsufficientServicePayment(
            expected_amount=expected_amount, actual_amount=iou.amount
        )

    # Check client's deposit in UserDeposit contract
    udc = pathfinding_service.user_deposit_contract
    udc_balance = get_pessimistic_udc_balance(
        udc=udc,
        address=iou.sender,
        from_block=BlockNumber(latest_block - pathfinding_service.required_confirmations),
        to_block=latest_block,
    )
    required_deposit = round(expected_amount * UDC_SECURITY_MARGIN_FACTOR_PFS)
    if udc_balance < required_deposit:
        raise exceptions.DepositTooLow(
            required_deposit=required_deposit, seen_deposit=udc_balance, block_number=latest_block
        )

    log.info(
        "Received service fee",
        sender=iou.sender,
        expected_amount=expected_amount,
        total_amount=iou.amount,
        added_amount=expected_amount - service_fee,
    )

    # Save latest IOU
    iou.claimed = False
    pathfinding_service.database.upsert_iou(iou)