From 5bc61e77cbe31385f1b34c7a06ba9d2d1ac47cca Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Thu, 3 Dec 2020 11:52:01 +1030 Subject: [PATCH] onchaind: speed up HTLC matching by skipping identical CLTVs. We try signatures to see which HTLC (we can have many) is the right one; we can trivially match htlcs against commitment tx outputs, but the CTLV can vary, and that's inside the htlc tx itself. By sorting them, it's easy to skip comparing duplicates: Time before: 2m32.547s Time after: 1m6.984s Signed-off-by: Rusty Russell --- onchaind/onchaind.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/onchaind/onchaind.c b/onchaind/onchaind.c index 731d662ce..fe88ffb10 100644 --- a/onchaind/onchaind.c +++ b/onchaind/onchaind.c @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -2263,6 +2264,12 @@ static size_t resolve_our_htlc_ourcommit(struct tracked_output *out, /* These htlcs are all possibilities, but signature will only match * one with the correct cltv: check which that is. */ for (i = 0; i < tal_count(matches); i++) { + /* Skip over duplicate HTLCs, since we only need one. */ + if (i > 0 + && (htlcs[matches[i]].cltv_expiry + == htlcs[matches[i-1]].cltv_expiry)) + continue; + /* BOLT #5: * * ## HTLC Output Handling: Local Commitment, Local Offers @@ -3640,6 +3647,16 @@ search_done: wait_for_resolved(outs); } +static int cmp_htlc_cltv(const struct htlc_stub *a, + const struct htlc_stub *b, void *unused) +{ + if (a->cltv_expiry < b->cltv_expiry) + return -1; + else if (a->cltv_expiry > b->cltv_expiry) + return 1; + return 0; +} + int main(int argc, char *argv[]) { setup_locale(); @@ -3731,6 +3748,9 @@ int main(int argc, char *argv[]) master_badmsg(WIRE_ONCHAIND_HTLC, msg); } + /* Sort by CLTV, so matches are in CLTV order (and easy to skip dups) */ + asort(htlcs, tal_count(htlcs), cmp_htlc_cltv, NULL); + outs = tal_arr(ctx, struct tracked_output *, 0); wally_tx_input_get_txid(tx->inputs[0], &tmptxid); new_tracked_output(&outs, &tmptxid,