| 1539 | } |
| 1540 | |
| 1541 | char *update_channel_onchain_fees(const tal_t *ctx, |
| 1542 | struct db *db, |
| 1543 | struct account *acct) |
| 1544 | { |
| 1545 | struct chain_event *close_ev, **events; |
| 1546 | struct amount_msat onchain_amt; |
| 1547 | |
| 1548 | assert(acct->onchain_resolved_block); |
| 1549 | close_ev = find_chain_event_by_id(ctx, db, |
| 1550 | *acct->closed_event_db_id); |
| 1551 | events = find_chain_events_bytxid(ctx, db, |
| 1552 | close_ev->spending_txid); |
| 1553 | |
| 1554 | /* Starting balance is close-ev's debit amount */ |
| 1555 | onchain_amt = AMOUNT_MSAT(0); |
| 1556 | for (size_t i = 0; i < tal_count(events); i++) { |
| 1557 | struct chain_event *ev = events[i]; |
| 1558 | |
| 1559 | /* Ignore: |
| 1560 | - htlc_fufill (to me) |
| 1561 | - anchors (already exlc from output) |
| 1562 | - to_external (if !htlc_fulfill) |
| 1563 | */ |
| 1564 | if (is_channel_acct(ev) |
| 1565 | && streq("htlc_fulfill", ev->tag)) |
| 1566 | continue; |
| 1567 | |
| 1568 | if (streq("anchor", ev->tag)) |
| 1569 | continue; |
| 1570 | |
| 1571 | /* Ignore stuff it's paid to |
| 1572 | * the peer's account (external), |
| 1573 | * except for fulfilled htlcs (which originated |
| 1574 | * in our balance) */ |
| 1575 | if (streq(ev->acct_name, EXTERNAL_ACCT) |
| 1576 | && !streq("htlc_fulfill", ev->tag)) |
| 1577 | continue; |
| 1578 | |
| 1579 | /* anything else we count? */ |
| 1580 | if (!amount_msat_add(&onchain_amt, onchain_amt, |
| 1581 | ev->credit)) |
| 1582 | return tal_fmt(ctx, "Unable to add" |
| 1583 | "onchain + %s's credit", |
| 1584 | ev->tag); |
| 1585 | } |
| 1586 | |
| 1587 | /* Was this an 'old state' tx, where we ended up |
| 1588 | * with more sats than we had on record? */ |
| 1589 | if (amount_msat_greater(onchain_amt, close_ev->debit)) { |
| 1590 | struct channel_event *ev; |
| 1591 | struct amount_msat diff; |
| 1592 | |
| 1593 | if (!amount_msat_sub(&diff, onchain_amt, |
| 1594 | close_ev->debit)) |
| 1595 | return tal_fmt(ctx, "Unable to sub" |
| 1596 | "close debit from onchain_amt"); |
| 1597 | /* Add in/out journal entries for it */ |
| 1598 | ev = new_channel_event(ctx, |