| 654 | } |
| 655 | |
| 656 | struct amount_msat amount_msat_sub_fee(struct amount_msat in, |
| 657 | u32 fee_base_msat, |
| 658 | u32 fee_proportional_millionths) |
| 659 | { |
| 660 | struct amount_msat out, out_plus_one; |
| 661 | |
| 662 | /* out = in - base - (out * prop / 1000000) |
| 663 | * Thus: out * (1 + prop / 1000000) = in - base |
| 664 | * out = (in - base) / (1 + prop / 1000000) |
| 665 | * out = 1000000 * (in - base) / (1000000 + prop) |
| 666 | * |
| 667 | * Since we round the fee down, out can be a bit bigger than |
| 668 | * expected, so we iterate upwards. |
| 669 | */ |
| 670 | if (!amount_msat_sub(&out, in, amount_msat(fee_base_msat))) |
| 671 | return AMOUNT_MSAT(0); |
| 672 | if (!amount_msat_mul_div(&out, out, 1000000, |
| 673 | 1000000 + fee_proportional_millionths)) |
| 674 | return AMOUNT_MSAT(0); |
| 675 | |
| 676 | /* If we calc reverse, it must work! */ |
| 677 | assert(within_fee(in, out, fee_base_msat, fee_proportional_millionths)); |
| 678 | |
| 679 | /* We can be out-by-one */ |
| 680 | if (amount_msat_add(&out_plus_one, out, AMOUNT_MSAT(1)) |
| 681 | && within_fee(in, out_plus_one, fee_base_msat, fee_proportional_millionths)) |
| 682 | return out_plus_one; |
| 683 | return out; |
| 684 | } |
| 685 | |
| 686 | bool amount_msat_add_fee(struct amount_msat *amt, |
| 687 | u32 fee_base_msat, |