@@ -873,6 +873,58 @@ static struct amount_msat remove_excess(struct flow **flows,
873873 return all_deliver ;
874874}
875875
876+ /* It increases the flows to meet the deliver target. It does not increase any
877+ * flow beyond the tolerance fraction. It doesn't increase any flow above its
878+ * max_deliverable value.
879+ * Returns the total delivery amount. */
880+ static struct amount_msat increase_flows (struct flow * * flows ,
881+ size_t * * flows_index ,
882+ struct amount_msat deliver ,
883+ double tolerance ,
884+ struct amount_msat * max_deliverable )
885+ {
886+ if (tal_count (flows ) == 0 )
887+ return AMOUNT_MSAT (0 );
888+
889+ struct amount_msat all_deliver , defect ;
890+ all_deliver = sum_all_deliver (flows , * flows_index );
891+
892+ /* early exit: target is already met */
893+ if (!amount_msat_sub (& defect , deliver , all_deliver ) ||
894+ amount_msat_is_zero (defect ))
895+ return all_deliver ;
896+
897+ asort (* flows_index , tal_count (* flows_index ), revcmp_flows , flows );
898+
899+ all_deliver = AMOUNT_MSAT (0 );
900+ for (size_t i = 0 ;
901+ i < tal_count (* flows_index ) && !amount_msat_is_zero (defect ); i ++ ) {
902+ const size_t index = (* flows_index )[i ];
903+ struct flow * flow = flows [index ];
904+ struct amount_msat can_add = defect , amt ;
905+
906+ /* no more than tolerance */
907+ if (!amount_msat_scale (& amt , flow -> delivers , tolerance ))
908+ continue ;
909+ else
910+ can_add = amount_msat_min (can_add , amt );
911+
912+ /* no more than max_deliverable */
913+ if (!amount_msat_sub (& amt , max_deliverable [index ],
914+ flow -> delivers ))
915+ continue ;
916+ else
917+ can_add = amount_msat_min (can_add , amt );
918+
919+ if (!amount_msat_add (& flow -> delivers , flow -> delivers ,
920+ can_add ) ||
921+ !amount_msat_sub (& defect , defect , can_add ) ||
922+ !amount_msat_accumulate (& all_deliver , flow -> delivers ))
923+ abort ();
924+ }
925+ return all_deliver ;
926+ }
927+
876928static void write_selected_flows (const tal_t * ctx , size_t * flows_index ,
877929 struct flow * * * flows )
878930{
@@ -931,6 +983,10 @@ const char *refine_flows(const tal_t *ctx, struct route_query *rq,
931983 /* remove excess from MCF granularity if any */
932984 remove_excess (* flows , & flows_index , deliver );
933985
986+ /* increase flows if necessary to meet the target */
987+ increase_flows (* flows , & flows_index , deliver , /* tolerance = */ 0.02 ,
988+ max_deliverable );
989+
934990 /* detect htlc_min violations */
935991 for (size_t i = 0 ; i < tal_count (flows_index );) {
936992 size_t k = flows_index [i ];
0 commit comments