* From array of incoming channels [inchan], find suitable ones for * a payment-to-us of [amount_needed], using criteria: * 1. Channel's peer is known, in state CHANNELD_NORMAL and is online. * 2. Channel's peer capacity to pay us is sufficient. * * Then use weighted reservoir sampling, which makes probing channel balances * harder, to choose one channel from the set of suitable channels. It
| 531 | * channels that have less balance on our side as fraction of their capacity. |
| 532 | */ |
| 533 | static struct route_info **select_inchan(const tal_t *ctx, |
| 534 | struct lightningd *ld, |
| 535 | struct amount_msat amount_needed, |
| 536 | const struct routehint_candidate |
| 537 | *candidates) |
| 538 | { |
| 539 | /* BOLT-11 struct wants an array of arrays (can provide multiple routes) */ |
| 540 | struct route_info **r = NULL; |
| 541 | double total_weight = 0.0; |
| 542 | |
| 543 | /* Collect suitable channels and assign each a weight. */ |
| 544 | for (size_t i = 0; i < tal_count(candidates); i++) { |
| 545 | struct amount_msat excess, capacity; |
| 546 | struct amount_sat cumulative_reserve; |
| 547 | double excess_frac; |
| 548 | |
| 549 | /* Does the peer have sufficient balance to pay us, |
| 550 | * even after having taken into account their reserve? */ |
| 551 | if (!amount_msat_sub(&excess, candidates[i].capacity, |
| 552 | amount_needed)) |
| 553 | continue; |
| 554 | |
| 555 | /* Channel balance as seen by our node: |
| 556 | |
| 557 | |<----------------- capacity ----------------->| |
| 558 | . . |
| 559 | . |<------------------ their_msat -------------------->| |
| 560 | . | . | |
| 561 | . |<----- capacity_to_pay_us ----->|<- their_reserve ->| |
| 562 | . | | | |
| 563 | . |<- amount_needed --><- excess ->| | |
| 564 | . | | | |
| 565 | |-------|-------------|--------------------------------|-------------------| |
| 566 | 0 ^ ^ ^ funding |
| 567 | our_reserve our_msat */ |
| 568 | |
| 569 | /* Find capacity and calculate its excess fraction */ |
| 570 | if (!amount_sat_add(&cumulative_reserve, |
| 571 | candidates[i].c->our_config.channel_reserve, |
| 572 | candidates[i].c->channel_info.their_config.channel_reserve) |
| 573 | || !amount_sat_to_msat(&capacity, candidates[i].c->funding_sats) |
| 574 | || !amount_msat_deduct_sat(&capacity, cumulative_reserve)) { |
| 575 | log_broken(ld->log, "Channel %s capacity overflow!", |
| 576 | fmt_short_channel_id(tmpctx, *candidates[i].c->scid)); |
| 577 | continue; |
| 578 | } |
| 579 | |
| 580 | /* We don't want a 0 probability if 0 excess; it might be the |
| 581 | * only one! So bump it by 1 msat */ |
| 582 | if (!amount_msat_accumulate(&excess, AMOUNT_MSAT(1))) { |
| 583 | log_broken(ld->log, "Channel %s excess overflow!", |
| 584 | fmt_short_channel_id(tmpctx, |
| 585 | *candidates[i].c->scid)); |
| 586 | continue; |
| 587 | } |
| 588 | excess_frac = amount_msat_ratio(excess, capacity); |
| 589 | |
| 590 | if (random_select(excess_frac, &total_weight)) { |