fix(ledger): reject posting sets that overflow the zero-sum check

An adversarial posting set of two MaxInt64 legs plus one of 2 wraps to
zero in int64 arithmetic, so the balance check passed and the ledger
minted 18 quintillion millisatoshis from nothing. The sum is now
accumulated in big.Int, per-account balance arithmetic is checked for
wraparound, and the audit totals parse through big.Int so a corrupt
ledger reports a clear error rather than failing to scan.

Adds room package tests (0% -> covered) and ledger edge cases.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
drjones
2026-08-05 15:43:21 +00:00
parent 2a2a1db8de
commit f2c02e2bde
4 changed files with 929 additions and 24 deletions

View File

@@ -13,6 +13,7 @@ import (
"context"
"errors"
"fmt"
"math/big"
"sort"
"time"
@@ -57,12 +58,16 @@ func (l *Ledger) Post(ctx context.Context, kind string, roundID *int64, postings
if len(postings) == 0 {
return 0, ErrEmptyTransaction
}
var sum int64
// The zero-sum check must be overflow-safe. Accumulating into an int64
// lets a crafted posting set wrap to zero — two legs of MaxInt64 and one
// of 2 sum to 0 in wrapping arithmetic — which would mint money out of
// nothing. big.Int has no such boundary.
sum := new(big.Int)
for _, p := range postings {
sum += p.AmountMsat
sum.Add(sum, big.NewInt(p.AmountMsat))
}
if sum != 0 {
return 0, fmt.Errorf("%w: sum is %d", ErrUnbalanced, sum)
if sum.Sign() != 0 {
return 0, fmt.Errorf("%w: sum is %s", ErrUnbalanced, sum.String())
}
tx, err := l.pool.Begin(ctx)
@@ -102,7 +107,14 @@ func (l *Ledger) Post(ctx context.Context, kind string, roundID *int64, postings
return 0, fmt.Errorf("reading balance of account %d: %w", p.AccountID, err)
}
// Detect wraparound before trusting the result: a credit that
// overflows would otherwise land as a negative balance, and a debit
// that underflows as a positive one.
after := before + p.AmountMsat
if (p.AmountMsat > 0 && after < before) || (p.AmountMsat < 0 && after > before) {
return 0, fmt.Errorf("ledger: amount %d overflows the balance of account %d (%d)",
p.AmountMsat, p.AccountID, before)
}
if after < 0 && !allowNegative {
return 0, fmt.Errorf("%w: account %d holds %d, needs %d",
ErrInsufficientFunds, p.AccountID, before, -p.AmountMsat)
@@ -227,21 +239,37 @@ func (l *Ledger) AccountByName(ctx context.Context, name string) (int64, error)
// every account except the external Lightning bridge. It changes only when
// funds genuinely enter or leave, never through internal play.
func (l *Ledger) TotalIssued(ctx context.Context) (int64, error) {
var total int64
err := l.pool.QueryRow(ctx,
`SELECT COALESCE(SUM(b.balance_msat), 0)
FROM account_balances b
JOIN accounts a ON a.id = b.account_id
WHERE NOT a.allow_negative`).Scan(&total)
return total, err
return l.sumBalances(ctx, `WHERE NOT a.allow_negative`)
}
// ConservationCheck sums every account including the bridge. Because each
// transaction sums to zero, this must always be exactly zero. A non-zero
// result means the books are corrupt, and is the top-level audit alarm.
func (l *Ledger) ConservationCheck(ctx context.Context) (int64, error) {
var total int64
err := l.pool.QueryRow(ctx,
`SELECT COALESCE(SUM(balance_msat), 0) FROM account_balances`).Scan(&total)
return total, err
return l.sumBalances(ctx, ``)
}
// sumBalances totals account balances.
//
// Postgres SUM() over bigint returns numeric, which can exceed int64 even
// though no single balance can. Scanning it as text and parsing through
// big.Int means a corrupt ledger reports a clear error instead of a scan
// failure — the alarm must survive the very condition it exists to detect.
func (l *Ledger) sumBalances(ctx context.Context, where string) (int64, error) {
var text string
err := l.pool.QueryRow(ctx,
`SELECT COALESCE(SUM(b.balance_msat), 0)::text
FROM account_balances b
JOIN accounts a ON a.id = b.account_id `+where).Scan(&text)
if err != nil {
return 0, err
}
total, ok := new(big.Int).SetString(text, 10)
if !ok {
return 0, fmt.Errorf("ledger: unparseable balance total %q", text)
}
if !total.IsInt64() {
return 0, fmt.Errorf("ledger: balance total %s exceeds int64; the books are corrupt", text)
}
return total.Int64(), nil
}