# Verifying integrity

Source: https://docs.formance.com/v3.2/modules/ledger/advanced/verifying-integrity

Stack: v3.2

With `HASH_LOGS` enabled, the Ledger is tamper-evident: it maintains a hash chain over its history that a change made outside the Ledger will break. Nothing checks that chain on its own, so detection is a job you run. This page covers how to run it in each `HASH_LOGS` mode, and why a chain check alone does not prove that history is unchanged.

How you run it depends on which `HASH_LOGS` mode the ledger uses — `SYNC` and `ASYNC` build **different structures**, so they give you different things to verify against.

Everything here requires `HASH_LOGS` set to `SYNC` or `ASYNC`. A ledger created with `HASH_LOGS: DISABLED` has no hash chain, so there is nothing to recompute and no way to detect tampering from the ledger's own data — [reconciliation](https://docs.formance.com/v3.2/modules/reconciliation) against outside records is the only check available to it. Features are immutable after creation, so this cannot be retrofitted.

Note that importing a hash-less export into a `SYNC` ledger is **not** a way around it. The target compares the hash it computes against the hash carried in the export; with nothing there to compare, every log fails with `ErrInvalidHash` even though nothing was tampered with. The same is true of an export taken from an `ASYNC` ledger.

## What each mode gives you to verify

`SYNC` and `ASYNC` are not two speeds of the same mechanism.

|                            | `SYNC`                                        | `ASYNC`                          |
| -------------------------- | --------------------------------------------- | -------------------------------- |
| Where the hash lives       | `hash` column on every log                    | separate `logs_blocks` table     |
| What is chained            | each log to the previous log                  | each block to the previous block |
| Granularity of a mismatch  | the exact log                                 | the block's log range            |
| Built by                   | a trigger, at insert time                     | the ledger worker, on a schedule |
| Write cost                 | a per-ledger advisory lock serializes inserts | none on the write path           |
| Verifiable through the API | yes, via import                               | no, requires database access     |

With `SYNC`, a trigger computes each log's SHA-256 over the previous log's hash plus the current payload, so every entry is chained to the one before it. The insert takes a per-ledger advisory lock — that lock, not the hashing, is what limits write throughput.

With `ASYNC`, logs are inserted **without a hash**. A background worker later groups them into blocks and writes one hash per block into `logs_blocks`, covering a range of log IDs and chaining to the previous block's hash. Nothing is on the write path, so throughput is much higher, and mismatches localize to a block rather than to a single log.

Because `ASYNC` never populates the per-log `hash` column, the export-and-import check below **does not work on an `ASYNC` ledger**. Choose the mode with the verification workflow you want in mind — `HASH_LOGS` cannot be changed after the ledger is created. See [Data isolation with buckets](https://docs.formance.com/v3.2/modules/ledger/working-with/data-isolation-buckets#hash_logs) for how to set it, and [the self-hosted deployment guide](https://docs.formance.com/v3.2/deploy/self-hosted/modules/ledger#async-block-hasher) for the worker configuration `ASYNC` requires.

## What the chain proves, and what it doesn't

The chain only covers changes made to the database outside the Ledger. There are two ways that happens, and they need different checks.

**Someone edits a row and leaves the hashes after it alone.** Recomputing the chain catches this, and tells you which log broke. This is the accident and the careless insider — an `UPDATE` run against the database, and every hash after it stops matching. The checks below cover it.

**Someone edits a row and recomputes every hash or block after it.** Recomputing the chain does not catch this. The chain is internally consistent, and every value you compare it against came out of the same database. A check sourced entirely from the database it is checking proves consistency, not authenticity.

To cover the second case, keep an anchor outside an attacker's reach.

**Anchor hashes outside the database.** On a schedule, copy the newest hash — the last log's `hash` under `SYNC`, the newest block's `(to_id, hash)` under `ASYNC` — somewhere the database operator cannot rewrite: a write-once bucket, an append-only store, or a signed copy sent to an auditor. A recomputed chain is then checked against a value that did not come from the database. Do this in both modes.

An anchor also saves work later. You can trust history up to that point without rechecking everything before it.

## Detecting tampering is a job you schedule

Here is how to run the recomputation in each mode. Neither belongs on the write path.

### For `SYNC` ledgers: export and re-import

The Ledger's import path already recomputes and verifies a per-log chain, so you do not have to implement the check yourself. It runs entirely through the API.

Export the full log stream

Export every log from the ledger you want to verify. The ledger name comes from the `--ledger` flag, and the stream goes to stdout unless you pass `--file`.

```bash
fctl ledger export --ledger=my-ledger > my-ledger.export
```

The equivalent API call is `POST /v2/{ledger}/logs/export`, which returns the logs as an `application/octet-stream`.

Create a fresh verification ledger with HASH\_LOGS: SYNC

The verification happens on the **target** side, and only when the target has `HASH_LOGS` set to `SYNC`. An `ASYNC` or `DISABLED` target skips the hash comparison entirely and the import will succeed without telling you anything.

```bash
fctl ledger create my-ledger-verify --features HASH_LOGS=SYNC
```

Unspecified features keep their defaults, so this only pins `HASH_LOGS`.

Import the stream

Import takes the ledger name and the file path as positional arguments.

```bash
fctl ledger import my-ledger-verify my-ledger.export
```

The equivalent API call is `POST /v2/{ledger}/logs/import`. If a large import is interrupted, `fctl ledger import --resume-from-last-log` picks up from the last log the target accepted rather than starting over.

Read the result

For each log, the target recomputes the hash from its own chain and compares it against the hash carried in the export. On a mismatch the import stops with an `ErrInvalidHash` naming the expected hash, the hash it got, and the log ID — which is the exact point where the history diverges.

A clean import means the chain is internally consistent. To make it mean _unchanged_, compare the last log's hash against your external anchor as a final step; the export carries the source's own hashes, so on its own this check cannot detect a chain that was rewritten wholesale.

Two import constraints affect how you run this:

- **Log IDs must be strictly monotonically increasing.** Import rejects any log whose ID is less than or equal to the highest ID already in the target, with `log <id> already exists`. Import into a ledger created for the check, not one already holding data.
- **A concurrent write aborts the import.** Each log is imported in its own transaction, and a serialization conflict fails the import with `concurrent transaction occurred, cannot import the ledger` rather than producing a half-verified result. Nothing else should be writing to the target while the check runs.

The cost of this check scales with the size of the export, so on a large ledger, run full passes on a schedule rather than continuously.

### For `ASYNC` ledgers: verify the block chain

An `ASYNC` ledger has no per-log hashes to compare, so there is nothing for import to check. What it has instead is `logs_blocks`, where each row covers a log range and chains to the row before it. Verifying means recomputing a block's hash from the logs in its range and confirming it reproduces the stored value, then confirming each block's `previous` reference lines up with the block before it.

`logs_blocks` is not exposed through the Ledger API today. Verifying an `ASYNC` ledger's chain means querying the bucket schema directly, which makes it an operator task rather than something an application can do for itself. If API-level verification matters to you, that is an argument for `SYNC`.

Because blocks are already checkpoints, you do not have to re-verify all of history on every pass. Verify only the blocks added since your last run, and re-verify older ranges on a rolling schedule. A mismatch narrows the tampering to that block's log range, so the block size you configure on the worker trades checkpoint density against how precisely you can localize a problem.

The same limit applies as with `SYNC`: recomputing blocks from the same database proves the block chain is self-consistent, and only a block hash you anchored externally tells you it has not been rebuilt.

### Reconcile against source-of-truth systems

Hash verification is a check on the shape of the history, not on its contents — it does not tell you the numbers are correct. Comparing ledger balances against outside records — bank statements, PSP reports — is what surfaces real errors and fraud. [Reconciliation](https://docs.formance.com/v3.2/modules/reconciliation) covers that check.

It also covers the case the hash chain structurally cannot: a rewritten-but-consistent history still has to reconcile against records held in someone else's system. Along with external anchoring, this is the reason reconciliation is not optional.

## Recovering from a detected problem

When you find tampering, do not edit the history to repair it. Rewriting past entries destroys the property that let you detect the problem in the first place. The check tells you where the chain diverges — the exact log under `SYNC`, the block's range under `ASYNC` — so you know how far back you have to go.

You have two ways to rebuild a clean ledger:

- **Restore the database.** Restore Postgres to a point before the divergence, then replay the legitimate activity that occurred after it.
- **Rebuild from a clean export.** Import the clean prefix of an export, up to but not including the divergence, into a fresh ledger, then re-post the legitimate transactions that came after.

Once the chain is continuous again, correct any resulting balances by appending compensating transactions, which is the Ledger's built-in way to reverse and adjust while keeping a complete record of what happened.

## Where to start

Pick the mode for the verification you actually intend to run, since you cannot change it later:

- **`SYNC`** when you want verification you can drive entirely through the API, and per-log precision when something is wrong. Accept the per-ledger insert lock.
- **`ASYNC`** when write throughput rules the decision. Budget for an operator-side job against `logs_blocks`, and for localizing a mismatch to a block rather than a log.

Then run all three checks, because each one covers what the others cannot: recompute the chain on a schedule to catch an edit that left the hashes after it alone, anchor hashes outside the database to catch one that recomputed them, and reconcile against source-of-truth systems to catch numbers that are wrong regardless of what the chain says.
