# Integrity anchors: daily tamper evidence (INTEGRITY-2, #202)

The activity log (`audit_log`) is append-only by trigger, and every lot seal is signed and time-stamped. Someone who
can write to the database directly, CropPath's own operators included, could still change a past row and leave no
trace. Integrity anchors leave one. After each UTC day ends, a job builds a fingerprint of that day's records, links
it to the previous day's fingerprint, and has an external time-stamp authority (TSA) sign the result. If a past row
is changed, removed or added later, it no longer matches the stored fingerprint, and anyone holding the published
anchors can see that.

- Public routes: `GET /v1/public/anchors` and `GET /v1/public/lots/{publicId}/anchor-proof` (OpenAPI:
  `listPublicAnchors`, `getPublicLotAnchorProof`; the document is `/developers/openapi.json`).
- Verifier: `verify_anchors.py`, served at `/developers/downloads/verify_anchors.py`. It needs Python 3.10+ and the
  standard library only.

## What is anchored

Each day covers five kinds of record. A record belongs to day D when its time, in Unix seconds, falls in
[D 00:00, D+1 00:00) UTC.

| Kind | Source | Time | Fields, in this order (type) |
|---|---|---|---|
| `audit` (tag 1) | every `audit_log` row | `at` | `id` (int), `at` (float), `actor`, `tenant`, `action`, `entity`, `entity_id`, `before_hash`, `after`, `request_id`, `ip_hash` (text, or NULL) |
| `evidence` (tag 2) | every `envelopes` row: accepted, quarantined or rejected after review | `received_at` | `id` (text), `received_at` (float), `payload_sha256` (text: lowercase hex SHA-256 of the stored `payload` as UTF-8) |
| `seal` (tag 3) | every `lot_seals` row | `sealed_at` | `manifest_sha256` (text), `sealed_at` (float), `fruit_count` (int), `event_count` (int) |
| `review` (tag 4) | every `reviews` row: a person's decision on a quarantined envelope; and every `envelope_requarantines` row: a pack that sent an accepted envelope back to quarantine, with `decision` `requarantine`, `reviewer` NULL and its reason (`pack_mismatch: seal`) as `note` | `reviewed_at` (a requarantine: `requarantined_at`) | `envelope_id`, `decision`, `reviewer`, `note` (text, or NULL), `reviewed_at` (float) |
| `held` (tag 5) | every `envelopes` row of the day that was not accepted when the day was anchored | `received_at` | `id` (text), `status` (text: `quarantined` or `rejected_after_review`) |

The evidence record names no device and no sequence number: both are in the signed payload, which its SHA-256 commits
to, and no public page lists device ids (the public proofs return this record).

## Canonical encoding (version 1)

Everything below is byte-exact. A verifier on any machine must produce the same bytes from the same values.

**Field.** One type byte, then the value:

| Type | Bytes |
|---|---|
| NULL (any type) | `00` |
| integer | `01`, then the value as 8 bytes, two's complement, big-endian (signed 64-bit) |
| float | `02`, then the value as IEEE 754 binary64, 8 bytes, big-endian. Times are Unix seconds as stored (SQLite REAL and PostgreSQL double precision hold the same binary64 value). An integer read from a float column is encoded as that float |
| text | `03`, then the length of the UTF-8 bytes as 4 bytes unsigned big-endian, then the UTF-8 bytes. The empty text is `03 00000000`, which is not NULL |

**Record.** The kind's tag byte (1 to 5), followed by each field in the order of the table above.

**Order.** Within a kind, the leaves (below) are sorted by their 32 bytes, compared as unsigned bytes from the first
byte on. The order therefore does not depend on database collation, row order or insertion order, and a day is read
keeping 32 bytes per record.

**Trees** (RFC 9162, Certificate Transparency v2, section 2.1.1). Each kind has its own tree:

- leaf = SHA-256(`00` || record)
- node = SHA-256(`01` || left || right)
- With n > 1 leaves, the tree splits at the largest power of two smaller than n.
- The root of an empty tree is SHA-256 of nothing, `e3b0c442…b855`.

**Day root** = SHA-256(`02` || audit root || evidence root || seal root || review root || held root). Each root is 32
bytes.

**Anchor** = SHA-256(previous anchor || day root || the day as 10 ASCII bytes `YYYY-MM-DD` || audit count ||
evidence count || seal count || review count || held count). The previous anchor is 32 bytes and each count is 8 bytes
unsigned big-endian. The
"previous anchor" of the first anchored day (`seq` 0) is 32 zero bytes. Days are consecutive: `seq` goes up by one per
day with no gap.

Hashes are shown as lowercase hex.

**Worked example.** A seal with manifest `abab…ab` (64 characters), sealed at 1791460800.25, with 12 fruits and 40
events:

```text
record     03 0300000040 6162…6162 (64 bytes) 02 41dab1e170100000 01 000000000000000c 01 0000000000000028
leaf       1475dd4c5b0f111030641e631196f194268bc3d5eb5a9e1f42174ea1eee2b66f
day root   901bc7d2a4ba0c8ae5358c53df958ee1a7770e2e9bf56e93c72bd1140ad0b8d1   (this one seal, every other tree empty)
anchor     372540ab8661336688f9e5b8031cb7abe6f92791684f5036cded7bb001725aa0   (as the first day, 2026-10-08, counts 0, 0, 1, 0, 0)
```

## Per-device daily digests (#239)

Beside each day's anchor, the daily per-device digest job gives every device with envelopes that UTC day its own digest:
the RFC 9162 root of that device's `evidence` records of the day (the encoding above: id, `received_at` and payload
SHA-256 of each envelope it sent, whatever its status; leaves ordered by hash), in `device_day_digests`, built once
the day ended an hour ago. The same TSA time-stamps each digest (`device_day_digest_timestamps`, the rules of the
anchor timestamps), so one device's readings of a day can be shown to have existed by the token's genTime without the
rest of the day's evidence. `verify_anchors.py`'s `encode_record`, `leaf_hash` and `merkle_root` (the verifier,
served at `/developers/downloads/verify_anchors.py`) recompute a digest from the device's envelopes. A sandbox
deployment builds none; the rows are deleted with the company's records.

## Verifying, as a buyer or an auditor

The verifier is one file, `verify_anchors.py` (download it from `/developers/downloads/verify_anchors.py`). It uses
only the Python standard library and needs nothing from the platform: download it, read it and run it alone.

```bash
# the whole chain: every anchor recomputed from the one before, days consecutive, each TSA token's imprint = its anchor
# and its genTime after its day ended, at most 48 hours after
python3 verify_anchors.py chain --api https://txng.theio.vn
# ... and the token's signature and certificate chain too (needs the openssl command and the TSA's root certificate)
python3 verify_anchors.py chain --api https://txng.theio.vn --tsa-ca tsa-root.pem
# ... and the copy you saved earlier is still an unchanged prefix of the live chain
python3 verify_anchors.py chain --api https://txng.theio.vn --anchors saved.json

# a public lot's seal, or one of its events (an eventID of its EPCIS document), against the published chain
python3 verify_anchors.py proof --api https://txng.theio.vn --lot <publicId> [--event <id>]

# one day recomputed from an auditor's export
python3 verify_anchors.py day --file day.json --api https://txng.theio.vn
```

`chain` prints how long after its day ended the latest token was made, and fails a token made more than 48 hours
after. It also fails every day without a verified token (still pending, or with no timestamp at all) whose end is more
than 48 hours before the time you run it. `--max-lag-hours` changes both limits. The days the job back-filled when
anchoring started were all stamped on its first day: pass the cutoff the operator publishes with
`--backfill-before YYYY-MM-DD` to accept late or missing tokens for the days before it, and only for those. For a
platform that runs without a TSA, `--allow-unstamped` accepts days with no verified token; a token that is present is
still checked.

What the live chain alone proves, and what it does not. Someone who can write to the database could change a past
row, drop the triggers, rebuild every anchor from that day on, and have the TSA stamp the rebuilt anchors again. The
rebuilt chain is consistent, so `chain --api` alone would pass, except for the time-stamps: a token made for a
rebuilt anchor is later than the 48-hour limit, and a rebuilt anchor left without a verified token (pending, or its
timestamp row deleted) fails the same limit once its day ended more than 48 hours ago. Within those 48 hours, and
with `--allow-unstamped`, the protection is a copy made by someone else.
Save the pages of `GET /v1/public/anchors` (`chain --api ... > /dev/null` is not enough: keep the JSON) and later run
`chain --api ... --anchors saved.json`. It fails when any anchor you saved differs from the live one, when a token you
saved was replaced, or when the live chain is shorter than your copy. A history rewritten after you saved your copy
can no longer produce the anchors you hold. `--anchors FILE` alone checks a saved copy offline.

The proof route answers `included: false` when the record, as stored today, is not among the records anchored for its
day, which means it was changed after that day was anchored.

Not checked by the script without `--tsa-ca`: the token's signature and its certificate chain. With `--tsa-ca` it runs
`openssl ts -verify -digest <anchor> -in token.der -token_in -CAfile <root>`. Revocation is not checked.
