# formancehq/ledger — Kavach Visual Invariant Atlas

> Programmable Numscript multi-asset ledger engine with atomic settlement proposals, chart validation, and v2 mirror translation.

- **Repository:** https://github.com/formancehq/ledger
- **Commit:** `c3dc255` (branch `main`)
- **Proof Tier:** `gold_showcase`
- **Stateful Backend Supported:** `true`
- **Scan:** 1399 ms · 412 files · $0.00 LLM tokens

## Detected Stateful Drivers & Gateways

| Driver | Language | Category | Kavach Adapter |
| :--- | :--- | :--- | :--- |
| `github.com/kavachlabs/kavach-go` | go | database | `kavach-go` |

## Extracted System Invariants (5)

| Invariant | Proof State | Category | Rule Kind | Evidence |
| :--- | :--- | :--- | :--- | :--- |
| `conservation` | `verified` | conservation | `conservation` | `harness/cmd/formance-host/scope.go:446-452` |
| `non_negativity` | `verified` | schema | `non_negative` | `harness/cmd/formance-host/scope.go:435-443` |
| `monotonicity` | `verified` | transport | `at_most_once_emit` | `harness/cmd/formance-host/scope.go:425-433` |
| `transient_zero_clearing` | `verified` | schema | `non_negative` | `harness/cmd/formance-host/scope.go:376-398` |
| `timestamp_bounds` | `verified` | transport | `at_most_once_emit` | `harness/cmd/formance-host/scope.go:454-459` |

### `conservation`
- **Summary:** sum(Input) == sum(Output) across all accounts for every (ledger, asset, color).
- **Proof State:** `verified`
- **Code:** `harness/cmd/formance-host/scope.go:446-452`

### `non_negativity`
- **Summary:** Input >= Output for every non-world, non-forced account on normal ledgers.
- **Proof State:** `verified`
- **Code:** `harness/cmd/formance-host/scope.go:435-443`

### `monotonicity`
- **Summary:** Cumulative Input and Output volumes never decrease compared to preBatch.
- **Proof State:** `verified`
- **Code:** `harness/cmd/formance-host/scope.go:425-433`

### `transient_zero_clearing`
- **Summary:** ACCOUNT_TYPE_TRANSIENT accounts must clear to zero balance at batch commit.
- **Proof State:** `verified`
- **Code:** `harness/cmd/formance-host/scope.go:376-398`

### `timestamp_bounds`
- **Summary:** Persisted effective timestamps never wrap uint64 past math.MaxInt64.
- **Proof State:** `verified`
- **Code:** `harness/cmd/formance-host/scope.go:454-459`

## Guided Causal Flows

### F1: Skipped duplicate tx metadata budget leak
A skippable duplicate CreateTransaction is rolled back with 0 persisted bytes, yet its metadata budget stays charged and rejects the following Numscript fee sweep.

1. **`in_create_tx`**: Seq 11 submits a 3-order SEPA atomic retry batch: primary tx #4, duplicate skippable tx, and Numscript fee sweep.
2. **`fn_process_orders`**: processOrders sums OrderMetadataSize across all 3 orders into ctx.metadataBudget.bytes (processor.go:259-262).
3. **`bug_f1`**: Order 2 hits TRANSACTION_REFERENCE_CONFLICT and matchOrderSkip drops its overlay (0 bytes persisted), but processor.go:357 never subtracts OrderMetadataSize(order).
4. **`fn_proc_tx`**: Order 3 (Numscript fee sweep) hits ValidateCommandBytes(656 > 512) -> METADATA_LIMIT_EXCEEDED and rolls back tx #4.

### F1 (revert): Skipped duplicate RevertTransaction leak
A skippable duplicate RevertTransaction leaks its metadata budget and rejects the paired Numscript dispute-reserve tx.

1. **`in_create_tx`**: Seq 11 retries a card-acquiring chargeback batch with a skippable duplicate revert_tx and a Numscript dispute reserve tx.
2. **`fn_process_orders`**: Order 2 triggers TRANSACTION_ALREADY_REVERTED and matchOrderSkip emits OrderSkippedLog without releasing metadataBudget.
3. **`bug_f1`**: Order 3 fails METADATA_LIMIT_EXCEEDED(actual=640,limit=512).

### F2: CreateLedger chart-of-accounts validation bypass
processCreateLedger omits PatternsConflict and ValidateSegmentTypes, letting NORMAL patterns shadow ACCOUNT_TYPE_TRANSIENT.

1. **`fn_proc_ledger`**: CreateLedger (processor_ledger.go:53-70) validates individual patterns with ValidatePattern, unlike processAddAccountType (processor_account_type.go:31-67).
2. **`bug_f2`**: Conflicting clearing:{ref} (NORMAL) shadows clearing:{id} (TRANSIENT) and invalid SegmentTypes leave strict chart enforcement empty.
3. **`inv_transient`**: ValidateTransientVolumes never triggers on shadowed clearing accounts (verified in harness/cmd/formance-host/repro_test.go:95 + fix.patch).

### F3: v2->v3 mirror pre-1970 timestamp uint64 underflow
Mirror translator swallows time.Parse errors and casts negative UnixMicro() to uint64, wrapping pre-1970 dates to year +586,524 AD.

1. **`fn_v2_translator`**: translateNewTransaction (translator.go:208-213) and translateRevertedTransaction (:305-310) bypass translateV2LogDate (:113-132).
2. **`bug_f3`**: 1969-12-31T23:59:59Z has UnixMicro() = -1000000; uint64(-1000000) underflows to 18446744073708550616.
3. **`inv_ts_bounds`**: Exceeds math.MaxInt64 in timestamp_bounds (verified in harness/cmd/formance-host/repro_test.go:142 + fix.patch).

## Replay-Verified Proofs (79/79 variants, 80/80 regressions)

- **F1: Skipped Duplicate Order Leaks Metadata Budget** (`internal/domain/processing/processor.go:324-358`) — Retrying an atomic settlement batch charges discarded duplicate metadata against METADATA_LIMIT_EXCEEDED. [40/40 variants · verdict `fixed`]
- **F2: CreateLedger Chart-of-Accounts Validation Bypass** (`internal/domain/processing/processor_ledger.go:53-70`) — Omits ValidateSegmentTypes & PatternsConflict, silently shadowing ACCOUNT_TYPE_TRANSIENT. [39/39 variants · verdict `fixed`]
- **F3: v2-to-v3 Mirror Pre-Epoch Timestamp uint64 Underflow** (`internal/adapter/v2/translator.go:208-213`) — Unchecked uint64(ts.UnixMicro()) wraps pre-1970 backdated timestamps to +586,524 AD. [79/79 variants · verdict `fixed`]

## Starter `.kavach/invariants.yaml`

```yaml
service: formance-ledger
invariants:
  - name: conservation
    kind: conservation
    sink: ledger:postings
    field: $.deltas[*]
  - name: non_negativity
    kind: non_negative
    sink: ledger:accounts
    field: $.balance
  - name: transient_zero_clearing
    kind: non_negative
    sink: ledger:transient
    field: $.net_remaining
```

## Driver Wrap Snippet

```text
import "github.com/kavachlabs/kavach-go/kavach"

kavach.RunHost(func(env *kavach.Env, step kavach.Step) error {
  return processor.ProcessProposal(env.Context(), step.Payload)
})
```

## Run Locally (Zero Upload)

```bash
brew install kavachlabs/tap/kavach && kavach map --auto --open
```
