D30-F05-A08 / Released engineering topic

End-to-End Ledger Integrity: Preserve Every Failure, Missing Proof and Trust Boundary

Compose real ledger, hash, Merkle, signer and anchor checks into an eleven-layer report without turning incomplete evidence into a green badge.

End-to-End Ledger Integrity: Preserve Every Failure, Missing Proof and Trust BoundaryD30 / D30-F05

An integrity report should tell an operator why a ledger cannot pass. A single green badge cannot explain whether the source is incomplete, a balance was replayed incorrectly, retained bytes changed, a key was revoked or external evidence is unavailable.

This capstone composes the actual earlier kernels into eleven visible checks. You will follow the original Cedar correction, inspect a valid signature over invalid accounting and keep a model anchor separate from live provider assurance. Known failures remain visible even when another layer is missing.

The teaching data and trust receipts are synthetic. A separate integration archive contains real local PostgreSQL execution and replay of its retained export. That archive does not authenticate a real bank or become a fresh live database query after the disposable cluster is removed.

Begin with an honest policy result

The same clean source can produce different conclusions under two explicitly different policies. If external anchoring is required, a consistent synthetic anchor model leaves live external assurance indeterminate. The overall report cannot pass. If the request explicitly excludes that layer, both anchor checks are marked not applicable, and the remaining bounded internal policy may pass.

Eleven layers distinguish a bounded internal policy pass from required external assurance that remains indeterminate

Open the full-size layered-assurance figure.

Exclusion is visible in the request and report. The excluded policy rejects supplied anchor evidence rather than silently ignoring an adverse receipt. Neither conclusion means that business intent, financial recognition, production key custody or legal compliance has been established.

Reuse the correction instead of inventing a new ledger

The original Cedar branch begins with 100000 USD minor units of funding to Ada. A wrong transfer sends 2500 to Ben. One atomic correction group reverses that original exactly and replaces it with a transfer of 2400 to Cora.

Point in the accepted journeyAda normal liability balanceBen normal balanceCora normal balance
Funding10000000
Wrong transfer9750025000
Whole correction visible9760002400

Ada's final raw debit-minus-credit liability balance is −97600; her normal-side balance is +97600. The inverse and replacement remain one committed group. There are three groups but four journals, so journal sequence 4 is not Merkle leaf 4.

The original three-group correction and the exact inventory of controls executed by the capstone

Open the full-size journey and control-coverage figure.

The independent shared commitment has chain head 8af37be6b7835169129ae57b561d98c0fe36e231921c76029f5aff8c9540beea and Merkle root 34ad17bffd657e7227adb7083eb1be5d0a7f9bcd5ba6b404313dce2242393192. Its signed checkpoint C is 300 bytes; complete envelope E is 524 bytes. The envelope content digest is 8c3d6bb3a098a957a5b555064cda453528aff09995a63a944fd902076f523972.

Those are independently prescribed fixture values, not values invented from the verifier's own desired output. The separately archived actual-close branch has its own identities, amounts and clocks; it does not replace this original correction chronology.

State exactly which earlier controls run

The function directly invokes five earlier algorithms:

Executed controlWhat its result contributes
Event-Sourced Balance FoldFull historical validation and the requested E/K account projection
Hash-Chained JournalWhole-group bytes, scoped chain and independently retained correspondence
Merkle-Batched Journal CommitmentActual full-prefix root and exact requested inclusion paths
Signed Ledger CheckpointSignature mathematics, current key authority and retained full-payload comparison
External WORM/Blockchain AnchorSelected fixed-retention model, with live external evidence still unknown

The historical validator also checks balanced/schema journal invariants and exact inverse/correction links. It does not execute the posting or correction write APIs. Twenty earlier controls—including durable storage, products, reconciliation acceptance and close transitions—remain explicitly not evaluated by this function.

Every one of the 27 earlier topic IDs appears exactly once in the inventory: five direct, two historical-invariant-only and twenty not evaluated. When external anchoring is explicitly not required, that one control moves to not applicable: four direct, two historical, twenty not evaluated and one excluded. The separate domain integration can execute additional controls without pretending they are direct calls inside this verifier.

Keep source knowledge and verification time separate

The request uses economic cutoff E, knowledge cutoff K and verification time V, with E ≤ K ≤ V. The historical reader validates complete supplied history through an independently trusted source head before selecting journal visibility at K. Whole correction groups become visible together; recording timestamps are preserved rather than turned into invented physical commit clocks.

V answers another question: was an independently published replay or retained commitment available for this verification? In the canonical fixture, E and K are 24 October at 12:00 UTC, while V is 12:01. A retained checkpoint received at 12:00:10 and a reported projection published at 12:00:30 can both be used by V to describe that earlier K. Their later publication does not lend later journals to the K projection.

The source observation must cover V, and all supplied group receipts must be available by V. A historical prefix needs its own independently declared head; silently truncating a current export does not establish historical completeness. Current checkpoint creation is a signed assertion, so age is a consistency/policy measure, not an independent signing timestamp.

The canonical checkpoint claims creation at 12:00. At V its age is 60000 milliseconds, below the requested maximum of 300 seconds. The selected age bound is authored policy, not a regulatory retention period.

Read eleven checks instead of one badge

The API takes three strict data objects:

Python
report = verify_ledger_integrity(request, bundle, context)
TypeScript
const report = await verifyLedgerIntegrity(request, bundle, context);

The bundle contains complete groups/accounts, submitted envelope, requested proofs and any selected anchor model inputs. The independent context contains the source head, retained checkpoint receipt, current key registry, expected replay and anchor commitment. IDs and receipt labels cannot authenticate themselves; the host must obtain those facts through trusted channels.

Every accepted report preserves these eleven layer names:

LayerWhat must be established
accounting_historyComplete historical journal and correction invariants
replayActual raw and normal projection matches an independent report
chain_commitmentActual chain corresponds to independently retained commitment
checkpoint_sourceSubmitted checkpoint agrees with actual full-prefix source commitments
merkle_inclusionEvery requested exact group path and actual group bytes agree
signatureStrict actual Ed25519 mathematics on C
key_authorityIndependently supplied current scoped validity/revocation policy
retained_checkpointFull submitted checkpoint matches independent retained payload
freshnessCovered source, creation chronology and requested age policy
anchor_modelSelected version/body/retention model checks
external_anchorIndependently obtained live external evidence, unavailable in this model

Each result has pass, fail, indeterminate or not applicable plus a specific code. A definite failure dominates uncertainty. Missing evidence does not become false financial evidence, and no unavailable computation is relabeled pass. Root structural errors return no partial report; child-specific failures remain in their layer.

Summary balances and hashes come from actual calculations. If a calculation cannot execute, its value remains null. An expected balance or digest never substitutes for the missing calculated result. The full data contract defines schemas, exact receipt availability, mismatch fields and proof-selection precedence.

Check proofs even when another layer fails

The selected full-prefix Merkle root is recalculated from the actual validated whole-group G bytes. For each requested group position, the verifier also runs the real inclusion checker against the structurally valid submitted checkpoint root. A passing mathematical path must then identify the exact corresponding source G bytes.

A bad proof can therefore remain a definite failure even if accounting source validation failed. A mathematically good path with unavailable source correspondence remains indeterminate. Short paths, surplus nodes, missing requested proofs, duplicate deliveries and unrequested extras cannot silently disappear.

RFC 9162 supplies the selected Merkle construction and proof context. This authored ledger wire does not claim Certificate Transparency protocol conformance, consistency proofs, non-equivocation or financial completeness from inclusion alone. RFC 9162, section 2.1.

A valid signature can accompany bad accounting

Consider an independently framed and genuinely signed checkpoint over unbalanced source journals. The signature equation can be valid under an authorized key. Accounting still fails. The signature does not repair the financial instruction, and the report must preserve both conclusions.

Likewise, a financially balanced rewrite may pass local accounting but disagree with a retained original chain, Merkle root or projection. Re-signing a changed checkpoint can repair its signature mathematics while retained payload comparison still fails. These cases expose why independently retained evidence matters when a signer or administrator can rewrite and re-sign.

The actual signature profile uses patched PyNaCl and noble canonical nonidentity main-subgroup A/R checks, strict Ed25519 and real WebCrypto. Public RFC seeds are demonstration fixtures. A missing native digest sets its computed value null and preserves other independent checks; a verifiable invalid signature still fails. This is a bounded authored profile using vetted primitives, not a custom curve implementation or a security certification. RFC 8032, PyNaCl release, noble-curves release.

Treat the external model as a model

The anchor child compares SHA256 of the complete signed envelope E with the exact fetched-version body, independent expected digest and supplied fixed-retention facts. It checks explicit owner/bucket/key/version identity, observation time, COMPLIANCE mode, minimum deadline and unexpired protection.

Those modeled checks can pass while live external assurance remains indeterminate. AWS describes retention for particular object versions; later versions and delete markers do not substitute for the selected version. That product behavior does not authenticate our local receipt, provide a live cloud observation or establish legal sufficiency. AWS Object Lock documentation.

No AWS resources, irreversible retention or blockchain transactions are created. An external-required policy cannot become all green just because a synthetic JSON receipt says the model is consistent.

Reproduce the whole report

Before orchestrator code, an independent reviewer prescribed 61 complete reports without importing End production code. They cover internal-policy pass, required model-anchor uncertainty, balanced rewriting, valid signatures with invalid accounting, known proof failures with unavailable source, missing tails, wrong replay signs/cutoffs/currency, missing/future retained evidence, key rotation/revocation, freshness boundaries and unavailable native cryptography.

The final validation record records actual Python/TypeScript, browser, dependency and integration runs. The guided lab calls the actual bundled orchestrator and retains all eleven checks, full source groups and explicit control inventory. Focus changes what you inspect, not which layers are evaluated.

Open the integrated ledger-integrity lab.

The separately archived actual-close journey preserves original SQL observer clocks, exact retained-export hash, independent local reobservation, actual kernel outputs and source pins. Its external model remains indeterminate. Neither a successful archived replay nor this teaching package asserts a fresh current production head.

Use the report to locate the next action

Investigate the specific failed or missing layer before making a stronger assurance claim. A source gap needs coverage evidence; a wrong replay needs account/clock comparison; a denied key needs trusted authority review; an unavailable provider needs independent external observation. A new signature is not a universal repair.

The primary-source register and shared framing contract keep evidence roles explicit. This capstone connects the 28-topic domain while retaining each algorithm's own limits. Script and asset readiness does not mean a video has been encoded, a real bank certified or the website remotely deployed.

ReferencesPrimary sources and evidence notes

Expand the source trail, evidence role, and limitations behind the engineering choices.

Accessed: 25 October 2026. Supports: the selected hash/Merkle/signature/provider primitives below, with their documented limits. Limitations: the D30 framing, eleven-layer policy, control inventory, resource limits, chronology and diagnostics are authored choices; neither these sources nor a local test certify a bank, provider, source ledger or this tutorial.

Primary sourceDirectly read version / roleBoundary
NIST FIPS180-4 publication statusAugust2015 final, March2023 revision-planning note; SHA-256 contextRevision planning is not a withdrawal claim; using SHA-256 is not FIPS/CAVP certification
RFC9162 §2.1December2021 Experimental; selected empty/leaf/internal hashes, split and exact inclusion proofCT protocol context; this is authored ledger framing, not CT protocol conformance, consistency proof or financial completeness
RFC8032January2017 Informational; pure Ed25519 and §7.1 test vectorsSignature authenticates bytes under a key, not key authority, business intent or source truth
W3C Web Cryptography Level222April2025 First Public Working Draft §25 Ed25519 plus noted point-validation differencesDraft status and runtime support retained; actual native operations are tested, no weaker green fallback
PyNaCl1.6.2 official release and libsodium maintainer fixPatched libsodium1.0.20-stable2025-12-31 valid-point mixed-order fixPinned actual Python profile, not vulnerable unpatched1.0.20; no custom curve arithmetic
noble-curves2.4.0 release and versioned API documentationStrict point parsing/subgroup/small-order and zip215:false verification, combined with actual WebCryptoUpstream audit is not an audit of our orchestrator; declared dependency/provenance must accompany downloads
AWS S3 Object LockCurrent version-specific retention/mode/legal-hold behavior, directly read25October2026The selected adapter is a synthetic fixed-COMPLIANCE model; no live observation, cloud request, retention setup or legal-sufficiency claim
Python3.11 hashlibNative SHA-256 interface used by pinned child kernelsPrimitive availability differs from trusted expectation/source authenticity; unavailable native operation must not imply pass

Financial/accounting invariants are the exact previously frozen historical D30 contract, rather than a new recognition rule. The function directly executes Event-Sourced Balance Fold, Hash-Chained Journal, Merkle-Batched Journal Commitment, Signed Ledger Checkpoint and selected External WORM/Blockchain Anchor. It rechecks historical balanced-journal and exact-correction invariants through that validator. The other20 earlier algorithms are not executed in this function. Separate local SQL/reconciliation/close integration is separately evidenced; its archived observation is not a fresh database query or cloud-provider receipt.

Historical example: not useful without complete reusable journals, account and projection histories, authentic independent retained commitments, key-policy history and provider evidence. The public RFC vectors and both Cedar branches are explicitly synthetic/authored fixtures. No invented named-bank incident or full copyrighted specification is reproduced.

algorithm.ts
/** Bounded layered verification through actual locally pinned kernels. */
import {foldBalance,validateHead} from './history-validation.js';
import {verifyHashChain} from './hash-chain.js';
import {buildMerkleCommitment,verifyMerkleInclusion} from './merkle-commitment.js';
import {encodeCheckpoint,encodeEnvelope,verifySignedCheckpoint} from './signed-checkpoint.js';
import {verifyExternalAnchor} from './anchor.js';
type Json=any;
const REQUEST='schema_version stream_id ledger_id entity_id verification_at knowledge_cutoff effective_cutoff account_id currency max_checkpoint_age_seconds proof_group_indices external_anchor_policy'.split(' ');
const BUNDLE='groups accounts envelope proofs anchor_configuration anchor_receipt'.split(' ');
const CONTEXT='head retained_checkpoint trust_registry expected_replay expected_anchor_commitment'.split(' ');
const REPLAY='schema_version stream_id ledger_id entity_id account_id currency effective_cutoff knowledge_cutoff through_sequence raw_balance_minor normal_balance_minor available_at receipt_ref'.split(' ');
const SCOPE=['stream_id','ledger_id','entity_id'];
const NAMES='accounting_history replay chain_commitment checkpoint_source merkle_inclusion signature key_authority retained_checkpoint freshness anchor_model external_anchor'.split(' ');
const UNKNOWN=new Set(['INCOMPLETE_EXPORT','KNOWLEDGE_BEYOND_EXPORT','KNOWLEDGE_BEYOND_SOURCE','HISTORY_NOT_AVAILABLE']);
class Invalid extends Error{}
function need(ok:unknown,code:string):asserts ok{if(!ok)throw new Invalid(code);}
function exact(value:Json,keys:string[]):boolean{return value!==null&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(k=>Object.hasOwn(value,k));}
function full(pattern:RegExp,value:string):boolean{return pattern.exec(value)?.[0]===value;}
function identifier(value:Json):boolean{return typeof value==='string'&&full(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/,value);}
function count(value:Json,limit:number,minimum=0):boolean{return typeof value==='string'&&full(/^(0|[1-9][0-9]{0,29})$/,value)&&BigInt(value)>=BigInt(minimum)&&BigInt(value)<=BigInt(limit);}
function timestamp(value:Json):boolean{if(typeof value!=='string'||!full(/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3}Z$/,value)||value.startsWith('0000'))return false;const time=Date.parse(value);return Number.isFinite(time)&&new Date(time).toISOString()===value;}
function copy<T>(value:T):T{return JSON.parse(JSON.stringify(value));}
function pick(value:Json,keys:string[]):Json{return Object.fromEntries(keys.map(k=>[k,value[k]]));}
function check(status:string,code:string):Json{return{status,code};}
function checkpointOkay(value:Json):boolean{try{encodeCheckpoint(value);return true;}catch(error){if(error instanceof Error&&error.message==='INVALID_CHECKPOINT')return false;throw error;}}
async function sha256(raw:Uint8Array):Promise<string|null>{if(!globalThis.crypto?.subtle?.digest)return null;try{return Array.from(new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256',raw as BufferSource)),v=>v.toString(16).padStart(2,'0')).join('');}catch(error){if(error instanceof Error&&['NotSupportedError','OperationError','SecurityError'].includes(error.name))return null;throw error;}}
function rejected(code:string):Json{return{status:'rejected',code,scope:null,layers:[],summary:null,mismatches:null,proof_results:[],control_coverage:null};}
function validateRoot(q:Json,b:Json,c:Json):void{
 need(exact(q,REQUEST),'INVALID_REQUEST');need(q.schema_version==='d30-ledger-integrity-verification-v1'&&[...SCOPE,'account_id'].every(k=>identifier(q[k])),'INVALID_REQUEST');
 need(['verification_at','knowledge_cutoff','effective_cutoff'].every(k=>timestamp(q[k]))&&q.effective_cutoff<=q.knowledge_cutoff&&q.knowledge_cutoff<=q.verification_at,'INVALID_REQUEST');
 need(['USD','EUR'].includes(q.currency)&&['required','not-required'].includes(q.external_anchor_policy)&&count(q.max_checkpoint_age_seconds,86400),'INVALID_REQUEST');
 const indices=q.proof_group_indices;need(Array.isArray(indices)&&indices.length<=16&&indices.every(i=>count(i,4096,1))&&new Set(indices).size===indices.length,'INVALID_REQUEST');
 need(exact(b,BUNDLE)&&Array.isArray(b.proofs)&&b.proofs.length<=16,'INVALID_BUNDLE');need(exact(c,CONTEXT),'INVALID_CONTEXT');
 try{validateHead(c.head);}catch(error){if(error instanceof Error)throw new Invalid('INVALID_CONTEXT');throw error;}need(count(c.head.head_sequence,8192),'INVALID_CONTEXT');
 const retained=c.retained_checkpoint;
 if(retained!==null){need(exact(retained,['checkpoint','available_at','receipt_ref'])&&checkpointOkay(retained.checkpoint)&&timestamp(retained.available_at)&&identifier(retained.receipt_ref),'INVALID_RETAINED_CHECKPOINT');need(retained.checkpoint.created_at<=retained.available_at,'RETAINED_RECEIPT_CLOCK_VIOLATION');}
 const replay=c.expected_replay;
 if(replay!==null){need(exact(replay,REPLAY),'INVALID_REPLAY_EXPECTATION');need(replay.schema_version==='d30-expected-replay-v1'&&[...SCOPE,'account_id','receipt_ref'].every(k=>identifier(replay[k]))&&['USD','EUR'].includes(replay.currency),'INVALID_REPLAY_EXPECTATION');need(['effective_cutoff','knowledge_cutoff','available_at'].every(k=>timestamp(replay[k]))&&count(replay.through_sequence,8192),'INVALID_REPLAY_EXPECTATION');need(['raw_balance_minor','normal_balance_minor'].every(k=>typeof replay[k]==='string'&&full(/^(0|-?[1-9][0-9]{0,119})$/,replay[k])),'INVALID_REPLAY_EXPECTATION');need(replay.available_at>=replay.knowledge_cutoff,'REPLAY_RECEIPT_CLOCK_VIOLATION');}
 if(q.external_anchor_policy==='not-required')need(b.anchor_configuration===null&&b.anchor_receipt===null&&c.expected_anchor_commitment===null,'INVALID_ANCHOR_POLICY_INPUT');
}
function inventory(required:boolean):Json{
 const all:string[]=[];for(const[f,size]of [[1,5],[2,5],[3,5],[4,5],[5,7]])for(let a=1;a<=size;a++)all.push(`D30-F${String(f).padStart(2,'0')}-A${String(a).padStart(2,'0')}`);
 const direct=['D30-F01-A03','D30-F05-A04','D30-F05-A05','D30-F05-A06',...(required?['D30-F05-A07']:[])],historical=['D30-F01-A01','D30-F05-A02'],na=required?[]:['D30-F05-A07'];
 return{direct:direct.sort(),historical_invariants_only:historical,not_evaluated:all.filter(id=>!direct.includes(id)&&!historical.includes(id)&&!na.includes(id)).sort(),not_applicable:na};
}
function proofMapping(proofs:Json[],indices:string[]):{chosen:Map<string,Json>;extras:Json[]}{const chosen=new Map<string,Json>(),extras:Json[]=[];for(const proof of proofs){const group=proof!==null&&typeof proof==='object'&&!Array.isArray(proof)&&count(proof.leaf_index,4095)?String(Number(proof.leaf_index)+1):null;if(group===null)extras.push({group_index:null,...check('fail','INVALID_INCLUSION_SELECTION')});else if(!indices.includes(group))extras.push({group_index:null,...check('fail','EXTRA_INCLUSION_PROOF')});else if(chosen.has(group))extras.push({group_index:null,...check('fail','DUPLICATE_INCLUSION_PROOF')});else chosen.set(group,proof);}return{chosen,extras};}
export async function verifyLedgerIntegrity(request:Json,bundle:Json,context:Json):Promise<Json>{
 try{validateRoot(request,bundle,context);}catch(error){if(error instanceof Invalid)return rejected(error.message);throw error;}
 const q=request,b=bundle,c=context,v=q.verification_at,indices=[...q.proof_group_indices].sort((a,b)=>Number(a)-Number(b)),layers:Json={},mismatches:Json={replay_fields:[],checkpoint_source_fields:[]};
 const retained=c.retained_checkpoint,visible=retained!==null&&retained.available_at<=v?retained:null,retainedScope=visible!==null&&SCOPE.every(k=>visible.checkpoint[k]===q[k]);
 const folded=foldBalance({schema_version:'d30-balance-fold-v1',...pick(q,['ledger_id','entity_id','account_id','currency','effective_cutoff','knowledge_cutoff']),checkpoint:null},b.groups,b.accounts,{head:c.head,checkpoint_registry:[]}),foldOk=folded.status==='ok';
 layers.accounting_history=foldOk?check('pass','HISTORICAL_ACCOUNTING_VALIDATED'):check(UNKNOWN.has(folded.code)?'indeterminate':'fail',folded.code);
 const replay=c.expected_replay;
 if(replay===null)layers.replay=check('indeterminate','REPLAY_EXPECTATION_MISSING');else if(replay.available_at>v)layers.replay=check('indeterminate','REPLAY_EXPECTATION_UNAVAILABLE');else if(!foldOk)layers.replay=check('indeterminate','REPLAY_SOURCE_UNAVAILABLE');else{const facts={...pick(q,[...SCOPE,'account_id','currency','effective_cutoff','knowledge_cutoff']),through_sequence:folded.coverage.visible_through_sequence,...pick(folded.balance,['raw_balance_minor','normal_balance_minor'])};mismatches.replay_fields=Object.keys(facts).filter(k=>replay[k]!==facts[k]).sort();layers.replay=mismatches.replay_fields.length?check('fail','REPLAY_EXPECTATION_MISMATCH'):check('pass','REPLAY_EXPECTATION_MATCH');}
 let expectedChain:Json=null;
 if(visible!==null){const cp=visible.checkpoint;expectedChain={schema_version:'d30-expected-chain-v1',...pick(cp,SCOPE),head_sequence:cp.through_sequence,group_count:cp.group_count,chain_head:cp.chain_head,available_at:visible.available_at,receipt_ref:visible.receipt_ref};}
 const chained=await verifyHashChain({schema_version:'d30-hash-chain-verification-v1',...pick(q,[...SCOPE,'verification_at'])},b.groups,b.accounts,{head:c.head,expected_commitment:expectedChain}),commitment=chained.commitment,entries=chained.entries;
 if(commitment!==null)layers.chain_commitment=check(chained.status,chained.code);else if(!foldOk)layers.chain_commitment=check('indeterminate','SOURCE_COMMITMENT_UNAVAILABLE');else layers.chain_commitment=check(chained.status==='rejected'?'fail':'indeterminate',chained.code);
 const env=b.envelope;let encoded:Uint8Array|null=null,checkpoint:Json=null;
 if(env!==null){try{encoded=encodeEnvelope(env);checkpoint=env.checkpoint;}catch(error){if(!(error instanceof Error)||!['INVALID_ENVELOPE','INVALID_CHECKPOINT'].includes(error.message))throw error;}}
 const envelopeDigest=encoded!==null?await sha256(encoded):null,batch=checkpoint!==null?checkpoint.checkpoint_id:visible!==null?visible.checkpoint.checkpoint_id:'LOCAL-UNBOUND';
 const built=commitment!==null?await buildMerkleCommitment({schema_version:'d30-merkle-build-v1',batch_id:batch,...pick(q,SCOPE),start_group_index:'1',entries_hex:entries.map((entry:Json)=>entry.bytes_hex),proof_leaf_index:null}):null,root=built?.commitment??null;
 if(checkpoint===null)layers.checkpoint_source=check('indeterminate','CHECKPOINT_MISSING');else if(commitment===null||root===null)layers.checkpoint_source=check('indeterminate','SOURCE_COMMITMENT_UNAVAILABLE');else{const facts={...pick(q,SCOPE),through_sequence:commitment.head_sequence,group_count:commitment.group_count,chain_head:commitment.chain_head,merkle_root:root.root_hex,merkle_size:root.tree_size};mismatches.checkpoint_source_fields=Object.keys(facts).filter(k=>checkpoint[k]!==facts[k]).sort();layers.checkpoint_source=mismatches.checkpoint_source_fields.length?check('fail','CHECKPOINT_SOURCE_MISMATCH'):check('pass','CHECKPOINT_MATCHES_SOURCE');}
 const trust=checkpoint===null?null:{schema_version:'d30-merkle-root-v1',batch_id:checkpoint.checkpoint_id,...pick(q,SCOPE),start_group_index:'1',tree_size:checkpoint.merkle_size,root_hex:checkpoint.merkle_root},{chosen,extras}=proofMapping(b.proofs,indices),proofResults:Json[]=[];
 for(const group of indices){const proof=chosen.get(group);let result:Json;if(proof===undefined)result=check('fail','MISSING_INCLUSION_PROOF');else{const verified=await verifyMerkleInclusion(proof,trust);if(['fail','rejected'].includes(verified.status))result=check('fail',verified.code);else if(verified.code==='CRYPTO_UNAVAILABLE')result=check('indeterminate','CRYPTO_UNAVAILABLE');else if(checkpoint===null)result=check('indeterminate','CHECKPOINT_MISSING');else if(commitment===null)result=check('indeterminate','SOURCE_ENTRY_UNAVAILABLE');else if(Number(group)>entries.length)result=check('fail','PROOF_GROUP_OUT_OF_RANGE');else if(proof.entry_hex!==entries[Number(group)-1].bytes_hex)result=check('fail','PROOF_ENTRY_MISMATCH');else result=check(verified.status,verified.code);}proofResults.push({group_index:group,...result});}
 proofResults.push(...extras);layers.merkle_inclusion=proofResults.length?pick(proofResults.find(r=>r.status==='fail')??proofResults.find(r=>r.status==='indeterminate')??check('pass','ALL_REQUESTED_INCLUSIONS_VERIFIED'),['status','code']):check('not_applicable','NO_INCLUSION_REQUESTED');
 if(env===null){for(const name of ['signature','key_authority','retained_checkpoint'])layers[name]=check('indeterminate','CHECKPOINT_MISSING');}else{
  const signature=await verifySignedCheckpoint({schema_version:'d30-signed-checkpoint-verification-v1',...pick(q,[...SCOPE,'verification_at']),policy:'current-trust-at-verification-v1',expected_checkpoint:retainedScope?visible.checkpoint:null},env,c.trust_registry);
  if(signature.framing===null){layers.signature=check('fail',signature.code);layers.key_authority=check('indeterminate','CHECKPOINT_PREREQUISITE_UNAVAILABLE');layers.retained_checkpoint=check('indeterminate','CHECKPOINT_PREREQUISITE_UNAVAILABLE');}else{layers.signature=copy(signature.checks.signature);layers.key_authority=copy(signature.checks.authority);const binding=signature.checks.binding;if(binding.status==='fail')layers.retained_checkpoint=copy(binding);else if(retained===null)layers.retained_checkpoint=check('indeterminate','MISSING_RETAINED_CHECKPOINT');else if(visible===null)layers.retained_checkpoint=check('indeterminate','RETAINED_CHECKPOINT_UNAVAILABLE');else if(!retainedScope)layers.retained_checkpoint=check('fail','RETAINED_SCOPE_MISMATCH');else layers.retained_checkpoint=copy(binding);}
 }
 const checkpointAge=checkpoint!==null?String(Date.parse(v)-Date.parse(checkpoint.created_at)):null,currentSource=foldOk&&c.head.observed_at>=v&&b.groups.every((g:Json)=>g.available_at<=v),lastReceipt=currentSource&&b.groups.length?b.groups.at(-1).available_at:null;
 if(checkpoint===null)layers.freshness=check('indeterminate','CHECKPOINT_MISSING');else if(checkpoint.created_at>v)layers.freshness=check('fail','CHECKPOINT_FROM_FUTURE');else if(lastReceipt!==null&&checkpoint.created_at<lastReceipt)layers.freshness=check('fail','CHECKPOINT_PREDATES_SOURCE');else if(Number(checkpointAge)>Number(q.max_checkpoint_age_seconds)*1000)layers.freshness=check('indeterminate','CHECKPOINT_STALE');else if(!currentSource)layers.freshness=check('indeterminate','SOURCE_COVERAGE_UNAVAILABLE');else layers.freshness=check('pass','CHECKPOINT_CURRENT');
 const required=q.external_anchor_policy==='required';
 if(!required){for(const name of ['anchor_model','external_anchor'])layers[name]=check('not_applicable','EXCLUDED_BY_DECLARED_POLICY');}else{layers.external_anchor=check('indeterminate','MODEL_RECEIPT_NOT_INDEPENDENT_PROVIDER_EVIDENCE');if(checkpoint===null)layers.anchor_model=check('indeterminate','CHECKPOINT_MISSING');else if(b.anchor_configuration===null)layers.anchor_model=check('indeterminate','ANCHOR_CONFIGURATION_MISSING');else if(b.anchor_receipt===null)layers.anchor_model=check('indeterminate','ANCHOR_RECEIPT_MISSING');else{const anchored=await verifyExternalAnchor({schema_version:'d30-external-anchor-v1',...pick(q,SCOPE),checkpoint_id:checkpoint.checkpoint_id,as_of:v,policy:b.anchor_configuration},env,b.anchor_receipt,{expected_commitment:c.expected_anchor_commitment});layers.anchor_model=anchored.model!==null?copy(anchored.model):check(['rejected','fail'].includes(anchored.status)?'fail':'indeterminate',anchored.code);}}
 const ordered=NAMES.map(name=>({name,...layers[name]})),status=ordered.some(x=>x.status==='fail')?'fail':ordered.some(x=>x.status==='indeterminate')?'indeterminate':'pass';
 const summary={source_head_sequence:c.head.head_sequence,visible_through_sequence:foldOk?folded.coverage.visible_through_sequence:null,group_count:commitment?.group_count??null,raw_balance_minor:foldOk?folded.balance.raw_balance_minor:null,normal_balance_minor:foldOk?folded.balance.normal_balance_minor:null,chain_head:commitment?.chain_head??null,merkle_root:root?.root_hex??null,envelope_sha256:envelopeDigest,checkpoint_age_ms:checkpointAge},scope=pick(q,Object.keys(q).filter(k=>k!=='schema_version'));scope.proof_group_indices=indices;
 return copy({status,code:{fail:'POLICY_VERIFICATION_FAILED',indeterminate:'POLICY_VERIFICATION_INDETERMINATE',pass:'DECLARED_POLICY_VERIFIED'}[status],scope,layers:ordered,summary,mismatches,proof_results:proofResults,control_coverage:inventory(required)});
}
Full-height labintegrity labOpen full screen
Written by

Fintech engineer building market-data and financial systems, and the author of every article, glossary record, and reference implementation on The Fintech Builder.