Skip to content

3.x.x: verify legacy audit bodies whose digests use Python's escaped JSON or 2.x's parts order, without sidecars (#709, #731) - #809

Merged
kiwidream merged 3 commits into
3.x.xfrom
orca/709-731-legacy-digests
Oct 28, 2026
Merged

kiwidream merged 3 commits into
3.x.xfrom
orca/709-731-legacy-digests

Conversation

@kiwidream

@kiwidream kiwidream commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #709 and #731. Legacy (1.x and 2.x) audit bodies whose digests were computed the way the Python writers computed them failed verification in 3.x unless a sidecar was supplied:

What changes (crates/qbit-prism/src/audit_body_ref.rs)

Tests

  • qbit-prism lib 169, audit_cli 19, audit_parts 8 (1 ignored).
  • Both Python modules pass 41/41 against the real canonicalizer, with their refusal assertions flipped.
  • tests.test_docs_lab_prism_references 147. fmt, clippy and the guards pass.
  • Mutation checks show the new tests fail without each fix.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

kiwidream and others added 2 commits October 28, 2026 14:31
…x/2.x bodies with non-ASCII worker names verify without sidecars (#709)

1.x and 2.x hashed each segment_range and segment_prefix part over Python's
json.dumps, whose default ensure_ascii writes non-ASCII text as \uXXXX.
3.x recomputed the digest over serde_json's raw UTF-8 only, so a part whose
shares carry a non-ASCII worker name failed with "audit body ref hash
mismatch" unless a canonical sidecar was supplied.

- The range and prefix checks accept the digest of either form: serde_json's
  bytes, or the same serialization with Python's escaping
  (PythonJsonFormatter, which reuses window.rs's ensure_ascii escaper,
  surrogate pairs above the BMP included). Both encode the same shares; a
  digest of neither form is still a hash mismatch, reported against the
  serde_json form.
- audit_cli: a body-ref whose prefix and range parts each carry a non-ASCII
  worker (Latin-1 and above the BMP) verifies and canonicalizes; a flipped
  prefix or range digest, or a changed share in the slot, is refused.
- A unit test pins the formatter to CPython's bytes for quotes, backslashes,
  control characters, DEL, BMP and non-BMP text.
- tests/test_prism_legacy_range_sidecars.py: the real canonicalizer now
  accepts the escaped body, which the sidecar tool reports as ok-in-3x with
  no sidecar; a range digest of neither form is refused and the tool still
  proves that body by its rewrite. The sidecar tooling is otherwise
  unchanged, for releases without this fix.
- docs/prism-rust-migration.md and the tool's docstring say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… insertion order with Python's escaping, so 2.x v2 bodies verify without sidecars (#731)

3.x recomputed share_parts_digest_hex through serde_json::json!, and the
workspace builds serde_json without preserve_order, so every part's keys came
out sorted. 2.x hashed json.dumps({"share_parts": parts}) over the parts in
insertion order, kind first, with non-ASCII text escaped. Every 2.x v2 body
failed with "window proof share_parts_digest_hex mismatch" unless a canonical
sidecar was supplied.

- share_parts_digest_hex serializes the parsed parts directly: the tag, then
  each variant's fields in declaration order, which is 2.x's order, and an
  inline share in AcceptedShare's order. It goes through #709's
  PythonJsonFormatter, so inline shares with non-ASCII text hash as 2.x
  wrote them. 3.x has no v2 writer, so no digest 3.x produced changes; the
  sorted-key form matches no writer and is now refused, as is any digest of
  another form.
- tests/fixtures/prism-legacy-v2-inline-audit-body: a v2 body with one inline
  part whose workers are non-ASCII (Latin-1 and above the BMP), encoded by
  2.x.x's AuditArtifactStore at 50e208c. The README records how; 2.x's v2
  writer never emitted inline parts, so its body-ref part iterator supplied
  the part.
- Unit tests: the parts digest reproduces both 2.x fixtures' stored digests;
  the inline fixture canonicalizes to its audit_bundle_sha256; a changed range
  digest, slot, bounds, dropped segment bounds, part order, the sorted-key
  digest or a changed inline share is refused.
- tests/test_prism_legacy_parts_digest_check.py: the real canonicalizer now
  accepts 2.x's digest and refuses the sorted-key one. The checker and the
  sidecar tooling are unchanged and keep modelling a release without the
  fix; their docstrings, the fixture READMEs and
  docs/prism-rust-migration.md say what changes with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T19:23:59.183779Z 55cbd7c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@qbit-reviewer qbit-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

@qbit-reviewer qbit-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

@kiwidream
kiwidream merged commit dc6389d into 3.x.x Oct 28, 2026
41 checks passed
kiwidream added a commit that referenced this pull request Oct 28, 2026
VERSION, the workspace version and both lockfiles' workspace members move
to 3.1.1, the same lines #782 bumped. doc/release-notes-3.1.1.md covers
every change on 3.x.x since v3.1.0 (#786 to #808); the operator-facing
changes: migration 032, the payout-revision listener's connection, the
alert rule UIDs and gating; the upgrade from 3.1.0 (migrate while 3.1.0
serves, then replace the binaries one at a time), from 3.0.0 and earlier;
the rollback to 3.1.0; and the known issues. The README banner, the
development-line note and docs/releasing.md's current-release line name
3.1.1 and the v3.1.1 tag.

The migration guide no longer says a 2.x audit-bundle.v2 body answers 500
until 3.x can verify it: since #809 the public route verifies it with the
parser and canonical-digest check import-audits uses, and serves it.

Co-authored-by: Claude Opus 5.5 <[email protected]>
kiwidream added a commit that referenced this pull request Nov 12, 2026
… and compares every column it carries (#739)

## Problem

`backfill-ctv` refuses every CTV set a 2.x ledger stored: `Error: existing CTV manifest set conflicts with verified audit`.

`persist_fanouts` checks an existing set with `manifest_set=$2 AND manifest_set_sha256=$3`:
- `$2` is jsonb, so the comparison is semantic and it passes.
- `$3` is the sha256 of 3.x's struct-order bytes (`canonical_ctv_fanout_manifest_set_bytes`).
- 2.x stored the sha256 of CPython's `json.dumps(set, sort_keys=True, separators=(",",":"))` (`streamed_sha256_json_hex` in `_persist_ctv_and_credit`, and `canonical_json_text` for `manifest_set_json`, at v2.0.0).

The artifact check fails the same way: every 2.x artifact names the set's sorted-key digest. The issue has the byte evidence: block `…bbce2` at height 17, `c63450ca…` stored against `99995ed8…` recomputed, a pure reorder.

An independent verify of the first version of this PR found that letting 2.x rows through also exposes how little 3.x compared:
- **F1.** An existing set was compared only on its jsonb and digest, and an artifact only on its jsonb, block and set digest. 2.x's own persist compared every column (v2.0.0 `share_ledger.py`, `matching_existing_set` and `artifact_extra`). With `manifest_set_json`, `parent_coinbase_tx_hex`, the amounts, an artifact's `manifest_json`, `manifest_sha256` or `fanout_tx_hex` tampered, backfill-ctv returned `Ok(0)`. `/artifact/<digest>` then answers 500, the sponsor check reads the set's `parent_coinbase_tx_hex`, and the public fanout status serves the artifact columns. Funds can't be redirected: the broadcaster uses the verified jsonb, and CTV fixes the outputs.
- **F2.** A chunk restored under a 2.x set was written as raw UTF-8 serde_json, while 2.x escaped non-ASCII. With a non-ASCII `recipient_id`, its text and address differed from its 2.x siblings'.

## Change

- **`qbit_prism::legacy_ctv_json_text`** (`crates/qbit-prism/src/ctv.rs`) writes a CTV document in 2.x's form: keys sorted, compact, CPython's `ensure_ascii` escapes (surrogate pairs included), using #809's `PythonJsonFormatter`, whose visibility goes from private to `pub(crate)`. `legacy_ctv_fanout_manifest_set_json` and `legacy_ctv_fanout_manifest_set_sha256_hex` give a verified set's 2.x text and digest.
- **`persist_fanouts`** (`ledger/blocks.rs`) compares every column a verified set determines, as 2.x did:
  - The set's and each artifact's `INSERT … ON CONFLICT DO NOTHING` and their comparison share one column list and one bound row, compared with `IS NOT DISTINCT FROM` (`anchor_vout` may be NULL). Set: text, jsonb, digest, settlement mode, parent coinbase txid and transaction, fanout count, output sum, covenant value. Artifact: every column peer sync carries except `origin_node`.
  - Not compared: columns that move as a fanout settles (settlement status, claims, schedules, confirmations, `updated_at`), and `created_at`/`origin_node`, which say when and where a row was written.
  - A held set is the verified set in one of two text forms, text and digest together: 3.x's (struct order) or 2.x's (sorted keys, escaped). So its stored text always hashes to the digest it is served under. The 2.x form is computed only when the 3.x one does not match.
  - Every artifact is in its set's form, under the set's stored digest. A chunk restored under a 2.x set is written as 2.x wrote it, so its text and address match its siblings' (F2). 3.x manifest text is sorted explicitly, as every 3.x release wrote it, whatever serde_json's `preserve_order` feature says.
  - Also refused, as 2.x did: an artifact row holding a verified chunk under another txid, and an artifact under the block that the audit lacks.
  - A refusal names the block, the fanout, and the columns that differ (from the form the row is nearer; on a tie, the form whose digest it holds). It is an error, so the block's transaction rolls back everything it wrote.
  - A row the same statement just inserted is not compared again, and a fresh set skips the extra-artifact count, so a landing does less work than before.
- **3.x rows are held to the same rule.** Only `persist_fanouts` writes these columns (landing and backfill), peer sync copies a peer's rows verbatim, and every 3.x release (v3.0.0-rc.1 to v3.1.1) wrote the same forms. So no 3.x writer leaves a column different.
- **Stored rows are read as written, never re-canonicalised or repaired.** A mismatch is refused; nothing is rewritten.

A deliberate refusal to note: 2.x's `backfill_ctv_fanouts.py` accepted an operator-supplied `--path-manifest-set-sha256` (or a payload digest) without checking that it was the sha256 of the text it stored. A row written that way, with a digest that is not its text's hash, is now refused naming `manifest_set_json`/`manifest_set_sha256`. Its `/artifact/<digest>` already answers 500. That includes sorted-key text stored under the 3.x struct-order digest: it differs from the 3.x form in `manifest_set_json` and from the 2.x form in `manifest_set_sha256`. 2.x's landing path always stored the text's own digest.

Unchanged, and worth knowing: a refused block still stops `backfill-ctv` there, so later blocks are not repaired until the refused rows are dealt with. The error now names the block, so the operator knows where to look. Follow-ups not taken here:
- `FANOUT_ARTIFACT_COLUMNS` repeats peer sync's carried list for `qbit_ctv_fanout_artifacts`, less `origin_node`. One constant could feed both; `ledger/peer_sync.rs` is outside this change.
- `PythonJsonFormatter`'s doc in `audit_body_ref.rs` names `legacy_ctv_fanout_manifest_set_sha256_hex` as its CTV user. It now also writes restored 2.x artifacts' text, through `legacy_ctv_json_text`.

## Tests run (minidev, private PostgreSQL 16 cluster, fsync on)

- `cargo test --locked -p qbit-prism --lib -- ctv:: audit_body_ref::`: 36 passed.
  - `ctv::tests::legacy_ctv_fanout_manifest_set_digest_is_2x_sorted_key_json` pins CPython's digests: the ASCII sample set, one with a non-ASCII recipient id (é, and 😀 as a surrogate pair), and now that set's first manifest in 2.x's form (`f24f32c4…`, from CPython's `json.dumps(json.loads(text), sort_keys=True, separators=(",", ":"))`). It also checks that the manifest's two forms differ only in those escapes.
- `PRISM_TEST_REQUIRE_INTEGRATION=1 … cargo test --locked -p qbit-prism-server --test ledger_postgres --test ledger_deadline_atomicity -- --test-threads=4 backfill_ctv_refuses_any_tampered_column a_2x_ctv_set_under_its_sorted_key_digest_backfills_as_written imported_ctv_audit_backfills_and_links_without_the_legacy_file ctv_artifacts_wait_for_maturity_and_claims_are_fenced backfill_item_failure_is_atomic landing_rows_roll_back_on_late_failure`: 7 passed.
  - New: `two_x::backfill_ctv_refuses_any_tampered_column_of_3x_ctv_rows` and `…_of_2x_ctv_rows` land a two-fanout CTV block whose second recipient's id is not ASCII. The 2.x variant rewrites the rows as 2.x wrote them, by escaping the stored jsonb's sorted text itself rather than with the helper under test. Each test then checks:
    - every determined column equals values taken field by field from the verified set;
    - untouched rows back-fill as a no-op, and a restored chunk is in its set's form;
    - 29 tampers (each set column, each artifact column, the text in the other form with and without its digest, a foreign txid at a chunk, an extra artifact), plus a row moved to another chunk, are each refused with a message naming exactly that column, and leave every row as it was. A chunk the backfill writes before the refusing check is rolled back;
    - changed settlement status, `updated_at` and `created_at` are not compared.
  - Against #846's `blocks.rs` without this follow-up, both new tests fail: the 3.x one with `set text was accepted`, the 2.x one on the restored chunk's text.
- `… --test ledger_postgres -- --test-threads=4 ctv fanout audit_acquire`: 16 passed.
- The gate manifest from these runs lists both new ids, which are added to `test/prism-gated-tests.txt`.
- `cargo fmt --all -- --check`: clean.
- `cargo clippy --locked -p qbit-prism --all-targets -- -D warnings` and `-p qbit-prism-server --all-targets`: clean, apart from the three known vendored sqlx-core warnings.
- `python3 scripts/check_prism_pool_acquires.py`: pass. The new queries run on the caller's transaction.

## What CI must cover

- The full qbit-prism and qbit-prism-server lib suites.
- `ledger_postgres` in full.
- The gated-test proof job for the three new ids.
- The landing binaries: `persist_fanouts` is also the landing path's CTV write. A landing's rows are fresh, so it now skips the comparisons.

Refs #739

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Squashed commits:
4c2a891 3.x.x: backfill-ctv accepts a legacy CTV set under 2.x's sorted-key digest (#739)
6f6b143 3.x.x: sort the legacy CTV set digest's keys whatever serde_json's features (#739)
34217c2 Merge remote-tracking branch 'origin/3.x.x' into orca/739-backfill-ctv-legacy-digest
c054920 3.x.x: backfill-ctv compares every column a held CTV set and its artifacts carry (#739)
7491fc9 3.x.x: a refused CTV row names its block, fanout and differing columns (#739)
0261133 3.x.x: the 2.x set text skips a second verification, and the not-compared check covers origin_node (#739)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant