| 1461 | } |
| 1462 | |
| 1463 | static void insert_chain_fees_diff(struct db *db, |
| 1464 | u64 acct_id, |
| 1465 | struct bitcoin_txid *txid, |
| 1466 | struct amount_msat amount, |
| 1467 | const char *currency, |
| 1468 | u64 timestamp) |
| 1469 | { |
| 1470 | struct db_stmt *stmt; |
| 1471 | u32 update_count; |
| 1472 | struct amount_msat current_amt, credit, debit; |
| 1473 | |
| 1474 | /* First, look to see if there's an already existing |
| 1475 | * record to update */ |
| 1476 | stmt = db_prepare_v2(db, SQL("SELECT" |
| 1477 | " update_count" |
| 1478 | ", credit" |
| 1479 | ", debit" |
| 1480 | " FROM onchain_fees" |
| 1481 | " WHERE txid = ?" |
| 1482 | " AND account_id = ?" |
| 1483 | " ORDER BY update_count")); |
| 1484 | |
| 1485 | db_bind_txid(stmt, 0, txid); |
| 1486 | db_bind_u64(stmt, 1, acct_id); |
| 1487 | db_query_prepared(stmt); |
| 1488 | |
| 1489 | /* If there's no current record, add it */ |
| 1490 | current_amt = AMOUNT_MSAT(0); |
| 1491 | update_count = 0; |
| 1492 | while (db_step(stmt)) { |
| 1493 | update_count = db_col_int(stmt, "update_count"); |
| 1494 | db_col_amount_msat(stmt, "credit", &credit); |
| 1495 | db_col_amount_msat(stmt, "debit", &debit); |
| 1496 | |
| 1497 | /* These should apply perfectly, as we sorted them by |
| 1498 | * insert order */ |
| 1499 | if (!amount_msat_add(¤t_amt, current_amt, credit)) |
| 1500 | db_fatal("Overflow when adding onchain fees"); |
| 1501 | |
| 1502 | if (!amount_msat_sub(¤t_amt, current_amt, debit)) |
| 1503 | db_fatal("Underflow when subtracting onchain fees"); |
| 1504 | |
| 1505 | } |
| 1506 | tal_free(stmt); |
| 1507 | |
| 1508 | /* If they're already equal, no need to update */ |
| 1509 | if (amount_msat_eq(current_amt, amount)) |
| 1510 | return; |
| 1511 | |
| 1512 | if (!amount_msat_sub(&credit, amount, current_amt)) { |
| 1513 | credit = AMOUNT_MSAT(0); |
| 1514 | if (!amount_msat_sub(&debit, current_amt, amount)) |
| 1515 | db_fatal("shouldn't happen, unable to subtract"); |
| 1516 | } else |
| 1517 | debit = AMOUNT_MSAT(0); |
| 1518 | |
| 1519 | stmt = db_prepare_v2(db, SQL("INSERT INTO onchain_fees" |
| 1520 | " (" |
no test coverage detected