* 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
| 555 | * channels that have less balance on our side as fraction of their capacity. |
| 556 | */ |
| 557 | static struct route_info **select_inchan(const tal_t *ctx, |
| 558 | struct lightningd *ld, |
| 559 | struct amount_msat amount_needed, |
| 560 | const struct routehint_candidate |
| 561 | *candidates) |
| 562 | { |
| 563 | /* BOLT11 struct wants an array of arrays (can provide multiple routes) */ |
| 564 | struct route_info **r = NULL; |
| 565 | double total_weight = 0.0; |
| 566 | |
| 567 | /* Collect suitable channels and assign each a weight. */ |
| 568 | for (size_t i = 0; i < tal_count(candidates); i++) { |
| 569 | struct amount_msat excess, capacity; |
| 570 | struct amount_sat cumulative_reserve; |
| 571 | double excess_frac; |
| 572 | |
| 573 | /* Does the peer have sufficient balance to pay us, |
| 574 | * even after having taken into account their reserve? */ |
| 575 | if (!amount_msat_sub(&excess, candidates[i].capacity, |
| 576 | amount_needed)) |
| 577 | continue; |
| 578 | |
| 579 | /* Channel balance as seen by our node: |
| 580 | |
| 581 | |<----------------- capacity ----------------->| |
| 582 | . . |
| 583 | . |<------------------ their_msat -------------------->| |
| 584 | . | . | |
| 585 | . |<----- capacity_to_pay_us ----->|<- their_reserve ->| |
| 586 | . | | | |
| 587 | . |<- amount_needed --><- excess ->| | |
| 588 | . | | | |
| 589 | |-------|-------------|--------------------------------|-------------------| |
| 590 | 0 ^ ^ ^ funding |
| 591 | our_reserve our_msat */ |
| 592 | |
| 593 | /* Find capacity and calculate its excess fraction */ |
| 594 | if (!amount_sat_add(&cumulative_reserve, |
| 595 | candidates[i].c->our_config.channel_reserve, |
| 596 | candidates[i].c->channel_info.their_config.channel_reserve) |
| 597 | || !amount_sat_to_msat(&capacity, candidates[i].c->funding_sats) |
| 598 | || !amount_msat_sub_sat(&capacity, capacity, cumulative_reserve)) { |
| 599 | log_broken(ld->log, "Channel %s capacity overflow!", |
| 600 | type_to_string(tmpctx, struct short_channel_id, candidates[i].c->scid)); |
| 601 | continue; |
| 602 | } |
| 603 | |
| 604 | /* We don't want a 0 probability if 0 excess; it might be the |
| 605 | * only one! So bump it by 1 msat */ |
| 606 | if (!amount_msat_add(&excess, excess, AMOUNT_MSAT(1))) { |
| 607 | log_broken(ld->log, "Channel %s excess overflow!", |
| 608 | type_to_string(tmpctx, |
| 609 | struct short_channel_id, |
| 610 | candidates[i].c->scid)); |
| 611 | continue; |
| 612 | } |
| 613 | excess_frac = amount_msat_ratio(excess, capacity); |
| 614 |