| 1681 | } |
| 1682 | |
| 1683 | void maybe_record_rebalance(struct db *db, |
| 1684 | struct channel_event *out) |
| 1685 | { |
| 1686 | /* If there's a matching credit event, this is |
| 1687 | * a rebalance. Mark everything with the payment_id |
| 1688 | * and amt as such. If you repeat a payment_id |
| 1689 | * with the same amt, they'll be marked as rebalances |
| 1690 | * also */ |
| 1691 | struct db_stmt *stmt; |
| 1692 | struct amount_msat credit; |
| 1693 | bool ok; |
| 1694 | |
| 1695 | /* The amount of we were credited is debit - fees */ |
| 1696 | ok = amount_msat_sub(&credit, out->debit, out->fees); |
| 1697 | assert(ok); |
| 1698 | |
| 1699 | stmt = db_prepare_v2(db, SQL("SELECT " |
| 1700 | " e.id" |
| 1701 | " FROM channel_events e" |
| 1702 | " WHERE e.payment_id = ?" |
| 1703 | " AND e.credit = ?" |
| 1704 | " AND e.rebalance_id IS NULL")); |
| 1705 | |
| 1706 | db_bind_sha256(stmt, 0, out->payment_id); |
| 1707 | db_bind_amount_msat(stmt, 1, &credit); |
| 1708 | db_query_prepared(stmt); |
| 1709 | |
| 1710 | if (!db_step(stmt)) { |
| 1711 | /* No matching invoice found */ |
| 1712 | tal_free(stmt); |
| 1713 | return; |
| 1714 | } |
| 1715 | |
| 1716 | /* We just take the first one */ |
| 1717 | out->rebalance_id = tal(out, u64); |
| 1718 | *out->rebalance_id = db_col_u64(stmt, "e.id"); |
| 1719 | tal_free(stmt); |
| 1720 | |
| 1721 | /* Set rebalance flag on both records */ |
| 1722 | stmt = db_prepare_v2(db, SQL("UPDATE channel_events SET" |
| 1723 | " rebalance_id = ?" |
| 1724 | " WHERE" |
| 1725 | " id = ?")); |
| 1726 | db_bind_u64(stmt, 0, *out->rebalance_id); |
| 1727 | db_bind_u64(stmt, 1, out->db_id); |
| 1728 | db_exec_prepared_v2(take(stmt)); |
| 1729 | |
| 1730 | stmt = db_prepare_v2(db, SQL("UPDATE channel_events SET" |
| 1731 | " rebalance_id = ?" |
| 1732 | " WHERE" |
| 1733 | " id = ?")); |
| 1734 | db_bind_u64(stmt, 0, out->db_id); |
| 1735 | db_bind_u64(stmt, 1, *out->rebalance_id); |
| 1736 | db_exec_prepared_v2(take(stmt)); |
| 1737 | } |
| 1738 | |
| 1739 | struct rebalance **list_rebalances(const tal_t *ctx, struct db *db) |
| 1740 | { |