@cardanowall/sdk-ts 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/client/index.cjs +2566 -1706
  2. package/dist/client/index.cjs.map +1 -1
  3. package/dist/client/index.d.cts +42 -5
  4. package/dist/client/index.d.ts +42 -5
  5. package/dist/client/index.js +2564 -1708
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/conformance/cli.cjs +5978 -3438
  8. package/dist/conformance/cli.cjs.map +1 -1
  9. package/dist/conformance/cli.js +5978 -3438
  10. package/dist/conformance/cli.js.map +1 -1
  11. package/dist/fetch/index.cjs +33 -14
  12. package/dist/fetch/index.cjs.map +1 -1
  13. package/dist/fetch/index.d.cts +2 -2
  14. package/dist/fetch/index.d.ts +2 -2
  15. package/dist/fetch/index.js +32 -15
  16. package/dist/fetch/index.js.map +1 -1
  17. package/dist/{fetch-outbound-BT5-NiYN.d.cts → fetch-outbound-dOK3ZxYa.d.cts} +7 -3
  18. package/dist/{fetch-outbound-BT5-NiYN.d.ts → fetch-outbound-dOK3ZxYa.d.ts} +7 -3
  19. package/dist/hash/index.cjs +1 -1
  20. package/dist/hash/index.cjs.map +1 -1
  21. package/dist/hash/index.js +1 -1
  22. package/dist/hash/index.js.map +1 -1
  23. package/dist/identity/index.cjs +460 -219
  24. package/dist/identity/index.cjs.map +1 -1
  25. package/dist/identity/index.d.cts +3 -2
  26. package/dist/identity/index.d.ts +3 -2
  27. package/dist/identity/index.js +460 -219
  28. package/dist/identity/index.js.map +1 -1
  29. package/dist/index.cjs +6912 -3678
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +7 -7
  32. package/dist/index.d.ts +7 -7
  33. package/dist/index.js +6890 -3672
  34. package/dist/index.js.map +1 -1
  35. package/dist/merkle/index.cjs +1 -1
  36. package/dist/merkle/index.js +1 -1
  37. package/dist/types-Cexm4VH9.d.cts +119 -0
  38. package/dist/types-CgoBub9J.d.ts +119 -0
  39. package/dist/{types-DGsZTMuZ.d.cts → types-Dp4wUSFI.d.cts} +220 -1
  40. package/dist/{types-DGsZTMuZ.d.ts → types-Dp4wUSFI.d.ts} +220 -1
  41. package/dist/verifier/index.cjs +5738 -3205
  42. package/dist/verifier/index.cjs.map +1 -1
  43. package/dist/verifier/index.d.cts +159 -111
  44. package/dist/verifier/index.d.ts +159 -111
  45. package/dist/verifier/index.js +5726 -3201
  46. package/dist/verifier/index.js.map +1 -1
  47. package/package.json +3 -3
  48. package/dist/types-B8Q3gW54.d.ts +0 -123
  49. package/dist/types-CLXdbjqr.d.cts +0 -123
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/verifier/types.ts","../../../poe-standard/src/schema.ts","../../../crypto-core/src/cbor/errors.ts","../../../crypto-core/src/cbor/canonical.ts","../../../crypto-core/src/cbor/permissive.ts","../../../poe-standard/src/encoder.ts","../../../crypto-core/src/hash/blake2b-256.ts","../../../crypto-core/src/sig/ed25519.ts","../../../crypto-core/src/util/compare-ct.ts","../../../crypto-core/src/cose/errors.ts","../../../crypto-core/src/cose/sign1.ts","../../../crypto-core/src/cose/cose-key.ts","../../../poe-standard/src/chunked.ts","../../../poe-standard/src/error-codes.ts","../../../poe-standard/src/validator.ts","../../../crypto-core/src/kdf/argon2id.ts","../../../crypto-core/src/aead/errors.ts","../../../crypto-core/src/aead/xchacha20-poly1305.ts","../../../crypto-core/src/hash/sha-256.ts","../../../crypto-core/src/hash/merkle-sha2-256.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/utils.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/_crystals.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/ml-kem.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/hybrid.ts","../../../crypto-core/src/aead/chacha20-poly1305.ts","../../../crypto-core/src/kdf/hkdf.ts","../../../crypto-core/src/kem/mlkem768x25519.ts","../../../crypto-core/src/kem/x25519.ts","../../../crypto-core/src/sealed-poe/errors.ts","../../../crypto-core/src/sealed-poe/slots-codec.ts","../../../crypto-core/src/sealed-poe/wrap.ts","../../../crypto-core/src/sealed-poe/unwrap.ts","../../../crypto-core/src/sealed-poe/envelope-from-parsed.ts","../../src/fetch/fetch-outbound.ts","../../src/verifier/fetch.ts","../../src/verifier/decrypt.ts","../../../crypto-core/src/merkle/leaves-list.ts","../../src/verifier/merkle.ts","../../src/verifier/profile.ts","../../src/verifier/cbor-walker.ts","../../src/verifier/resolve.ts","../../src/hex.ts","../../src/verifier/signatures.ts","../../src/verifier/tx-witnesses.ts","../../src/verifier/verify.ts","../../src/conformance/cli.ts"],"names":["z","encode","sortCoreDeterministic","decode","cdeDecodeOptions","hashes","CanonicalCborError","encodeCanonicalCbor","decodeCanonicalCbor","mapDecodeError","blake2b","ed","sha512","opts","UTF8_ENCODER","issue","j","argon2id","xchacha20poly1305","sha256","nobleSha256","blake2b224","abytes","randb","abytes_","N","Q","F","ROOT_OF_UNITY","reverseBits","FFTCore","shake128","u32","swap32IfBE","shake256","sha3_256","sha3_512","bytesToNumberLE","bytesToNumberBE","anumber","x25519","concatBytes","asciiToBytes","AeadVerificationError","chacha20poly1305","xchacha20Poly1305Decrypt","hkdf","compareCt","ZERO_NONCE_12","EMPTY_SALT","X25519_SECRET_KEY_LENGTH","X25519_PUBLIC_KEY_LENGTH","NONCE_LENGTH","WRAP_LENGTH","SLOTS_MAC_LENGTH","concat","hmac","LEAF_PREFIX","NODE_PREFIX","DIGEST_LENGTH","validateLeaves","merkleSha2256Root","mthRecursive","largestPow2Lt","hashLeaf","hashNode","ED25519_PUBLIC_KEY_LENGTH","ed2","L","leBytesToBigInt","verifyEd25519","asMap"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CO,IAAM,YAAA,GAAk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AAA,CAAM,CAAC,CAAA,EAAG;AAAA,IAC9B,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IAC3C,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI;AAAA,GAC5C,EAAE,IAAA,CAAK,CAAC,SAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA;AACtC","file":"cli.cjs","sourcesContent":["// Public types for the Label 309 standalone verifier.\n//\n// The verifier is service-independent: it depends only on the operator-supplied\n// Cardano / Arweave / IPFS gateway chains and a `denyHosts` policy. Every\n// outbound network call routes through `fetchOutbound` (single egress point)\n// and lands in `VerifyReport.httpCalls` for audit.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { FetchOutbound, HttpCallRecord } from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verdict / exit-code\n// -----------------------------------------------------------------------------\n//\n// `'valid'` → exit 0 — every check returned ok.\n// `'pending'` → exit 3 — INSUFFICIENT_CONFIRMATIONS (record well-formed but\n// below the verifier's reorg-safety threshold).\n// `'failed'` → exit 1 — integrity / structural / signature class.\n// → exit 2 — network class (CONTENT_UNAVAILABLE, PROVIDER_UNAVAILABLE).\n\nexport type Verdict = 'valid' | 'pending' | 'failed';\nexport type ExitCode = 0 | 1 | 2 | 3;\n\n// -----------------------------------------------------------------------------\n// Conformance profile\n// -----------------------------------------------------------------------------\n//\n// Strict-superset order: each higher profile reads everything below it plus\n// one additional surface. A verifier of a LOWER profile that sees a field\n// belonging to a HIGHER profile MUST emit `OUT_OF_PROFILE_SKIPPED`\n// (info-severity) and continue — it MUST NOT report the record as invalid.\n\nexport type Profile = 'core' | 'signed' | 'sealed' | 'recipient-sealed';\n\n// -----------------------------------------------------------------------------\n// Network identifier — mainnet-only policy.\n// -----------------------------------------------------------------------------\n//\n// Cardano mainnet only; testnet is explicitly out-of-scope by project\n// policy. The literal `'cardano:mainnet'` is the wire-canonical\n// identifier surfaced in every VerifyReport so a downstream consumer never has\n// to infer which network the record was anchored on.\n\nexport type Network = 'cardano:mainnet';\n\nexport const PROFILE_RANK: Readonly<Record<Profile, number>> = Object.freeze({\n core: 0,\n signed: 1,\n sealed: 2,\n 'recipient-sealed': 3,\n});\n\n// -----------------------------------------------------------------------------\n// FetchOutbound (the verifier's only network egress point)\n// -----------------------------------------------------------------------------\n\nexport type {\n FetchOutbound,\n FetchOutboundOptions,\n FetchOutboundResult,\n HttpCallRecord,\n} from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verifier issue surface — re-exports the validator's `ValidationIssue` so\n// downstream consumers can dispatch on a single union (`ErrorCode` covers\n// both Part A and Part B per `@cardanowall/poe-standard`).\n// -----------------------------------------------------------------------------\n\nexport type { ValidationIssue } from '@cardanowall/poe-standard';\n\n// -----------------------------------------------------------------------------\n// VerifyTx input — discriminated decryption union.\n// -----------------------------------------------------------------------------\n\nexport interface VerifyTxInput {\n readonly txHash: string; // lowercase hex, no 0x prefix\n readonly profile?: Profile; // default 'recipient-sealed' (full pipeline)\n readonly cardanoGatewayChain?: ReadonlyArray<string>; // Koios-compatible URLs, in order\n readonly blockfrostProjectId?: string; // enables Blockfrost fallback\n readonly arweaveGatewayChain?: ReadonlyArray<string>;\n readonly ipfsGatewayChain?: ReadonlyArray<string>;\n readonly confirmationDepthThreshold?: number; // default 15; verifier-policy floor\n readonly denyHosts?: ReadonlyArray<string>; // service-independence guard\n // Master offline switch for the verifier's outbound URI fetches. When\n // `false`, the verifier neither fetches a sealed item's `uris[]` ciphertext\n // (decryption falls back to caller-supplied `ciphertextBytes` only) nor the\n // Merkle list-commitment leaves-list — so a Merkle-bearing or sealed record\n // verifies with ZERO egress beyond the chain/indexer resolve step. The\n // on-record `record.merkle[]` / `items[].uris[]` data round-trips through\n // `record` unchanged; only the verifier's defence-in-depth recompute and the\n // ciphertext download are suppressed. Defaults to `true` (full pipeline).\n // Server-rendered pages flip this to `false` so hash-only / merkle-only /\n // sealed records render from indexed CBOR alone, with the leaves-list and\n // ciphertext fetches deferred to a user-initiated client-side action.\n readonly verifyMerkle?: boolean;\n // Out-of-band sealed-PoE decryption attempts. The verifier dispatches by\n // inspecting `items[i].enc.slots` vs `items[i].enc.passphrase` presence; a\n // mismatched entry surfaces as WRONG_DECRYPTION_INPUT_SHAPE.\n readonly decryption?: ReadonlyArray<\n | { readonly itemIndex: number; readonly recipientSecretKey: Uint8Array }\n | { readonly itemIndex: number; readonly passphrase: string }\n >;\n // Out-of-band ciphertext bytes (keyed by item index). When supplied, takes\n // precedence over `items[i].uris[]` (no network fetch is issued).\n readonly ciphertextBytes?: Readonly<Record<number, Uint8Array>>;\n // Out-of-band Merkle leaves-list bytes (keyed by `record.merkle[i]` index).\n // CBOR is the normative wire form.\n readonly merkleLeaves?: Readonly<Record<number, Uint8Array>>;\n // For stake-address binding (path-2 wallet signatures). The\n // verifier recomputes `network_header || Blake2b-224(pubkey)` and compares\n // to the protected-header `address` field; mismatch emits\n // WALLET_ADDRESS_MISMATCH. Defaults to 'mainnet' when omitted; 'preprod' is\n // supplied only by callers running against the Cardano preprod testnet\n // (worker dev mode, future receiver-side scanner on preprod). The\n // wire-canonical `VerifyReport.network` field stays pinned to\n // 'cardano:mainnet' — this input only governs the stake-byte used for\n // path-2 address derivation.\n readonly cardanoNetwork?: 'mainnet' | 'preprod';\n // Injected for tests; defaults to fetchOutbound (the single egress point).\n readonly fetchOutbound?: FetchOutbound;\n}\n\n// -----------------------------------------------------------------------------\n// VerifyReport shape.\n// -----------------------------------------------------------------------------\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unsupported' | 'unresolved';\nexport type SignatureFailureReason =\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'SIGNATURE_UNSUPPORTED'\n | 'SIGNER_KEY_UNRESOLVED'\n | 'SIGNATURE_INVALID'\n | 'WALLET_ADDRESS_MISMATCH';\n\nexport type SignerType = 'in-signature-kid' | 'wallet-inline-key';\n\nexport interface VerifyRecordSignature {\n readonly index: number;\n readonly verdict: SignatureVerdict;\n readonly signer_pub?: string; // lowercase hex of 32-byte Ed25519 pubkey when resolved\n readonly signer_type?: SignerType;\n readonly reason?: SignatureFailureReason;\n}\n\nexport type DecryptionVerdict =\n | 'decrypted'\n | 'wrong-key'\n | 'tampered-header'\n | 'tampered-ciphertext'\n | 'wrong-input-shape'\n | 'no-enc-envelope'\n | 'ciphertext-unavailable'\n | 'content-unavailable'\n | 'skipped'\n | 'kdf-failed';\n\nexport interface VerifyItemDecryption {\n readonly item_index: number;\n readonly verdict: DecryptionVerdict;\n // True iff every content-hash entry in `items[i].hashes` recomputes to the\n // recovered plaintext. Always a concrete boolean on `verdict === 'decrypted'`.\n readonly plaintext_hash_ok?: boolean;\n readonly reason?: string;\n}\n\nexport type ItemHashCheck = {\n readonly item_index: number;\n readonly alg: string;\n readonly ok: boolean;\n};\n\nexport type MerkleVerdict =\n | 'valid'\n | 'mismatch'\n | 'unavailable'\n | 'format-unsupported'\n | 'unsupported';\n\nexport interface VerifyMerkleCheck {\n readonly merkle_index: number;\n readonly alg: string;\n readonly verdict: MerkleVerdict;\n readonly root_recomputed?: Uint8Array;\n readonly reason?: string;\n}\n\nexport interface VerifyUriCheck {\n readonly item_index: number;\n readonly uri: string;\n readonly ok: boolean;\n readonly reason?: string;\n}\n\n// -----------------------------------------------------------------------------\n// Transaction-level description — DISTINCT from record-level authorship.\n// -----------------------------------------------------------------------------\n//\n// These surfaces describe the Cardano transaction that carried the PoE: which\n// wallet vkey(s) authorised/paid for it, the fee, and the outputs. This is the\n// \"who submitted and paid for this anchoring\" view — orthogonal to\n// `record_signatures`, which is the optional Label 309 record-level authorship\n// claim. A failed `signature_valid` here is INFORMATIONAL: it never changes the\n// verifier's verdict (the content claim does not depend on who paid the fee).\n\nexport interface VerifyTxWitness {\n readonly type: 'vkey';\n readonly vkey: string; // hex 32B Ed25519 pubkey\n readonly key_hash: string; // hex 28B Blake2b-224(vkey)\n readonly signature_valid: boolean; // Ed25519.verify(sig, blake2b256(tx_body), vkey)\n}\n\nexport interface VerifyTxOutput {\n readonly address: string; // bech32\n readonly lovelace: string; // decimal string\n}\n\nexport interface VerifyTxSummary {\n readonly fee_lovelace: string; // decimal string\n readonly input_count: number;\n readonly output_count: number;\n readonly outputs: ReadonlyArray<VerifyTxOutput>;\n readonly total_output_lovelace: string; // decimal string\n readonly script_witness_count: number;\n readonly invalid_before?: number;\n readonly invalid_hereafter?: number;\n readonly required_signer_key_hashes?: ReadonlyArray<string>;\n readonly network_id?: number;\n}\n\n// VerifyReport is snake_case end-to-end: the wire shape, the SDK's in-memory\n// representation, and every consumer-facing field share the same identifier\n// grammar. No transformer layer between the verifier and the API response —\n// `VerifyReport` IS the wire body for `POST /api/v1/records/{tx_hash}/verify`.\nexport interface VerifyReport {\n readonly tx_hash: string;\n readonly network: Network;\n readonly verdict: Verdict;\n readonly exit_code: ExitCode;\n readonly profile: Profile;\n readonly num_confirmations: number;\n readonly confirmation_depth_threshold: number;\n readonly block_time?: number;\n readonly block_slot?: number;\n readonly metadata_present: boolean;\n readonly validation: {\n readonly valid: boolean;\n readonly issues?: ReadonlyArray<ValidationIssue>;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n };\n readonly record?: PoeRecord;\n readonly record_signatures?: ReadonlyArray<VerifyRecordSignature>;\n // Transaction-level description (present only when raw tx CBOR is available\n // to the pipeline — the live `verifyTx` path always has it; the DB-first\n // `verifyResolved` path has it only when the caller passes `txCbor`).\n readonly tx_witnesses?: ReadonlyArray<VerifyTxWitness>;\n readonly tx_summary?: VerifyTxSummary;\n readonly metadata_labels?: ReadonlyArray<number>; // sorted ascending; all aux metadata label keys\n readonly item_hash_checks?: ReadonlyArray<ItemHashCheck>;\n readonly item_decryptions?: ReadonlyArray<VerifyItemDecryption>;\n readonly merkle_checks?: ReadonlyArray<VerifyMerkleCheck>;\n readonly uri_checks?: ReadonlyArray<VerifyUriCheck>;\n readonly supersedes_resolved?: { readonly tx: string; readonly exists: boolean };\n readonly http_calls: ReadonlyArray<HttpCallRecord>;\n}\n","// Label 309 v1 PoE record Zod schemas.\n//\n// Scope: structural shape gate. The schema enforces per-field types, length\n// bounds (chunk size, digest length, supersedes length, nonce length,\n// passphrase salt length), closed-map invariants (`sigs[i]`, `slot`,\n// `passphrase`, `merkle[i]`), and the `v == 1` literal. Cross-field rules\n// (item.hashes content-hash binding when `enc` present, slots/passphrase\n// exclusivity, `crit[]` shape, registry membership of algorithm\n// identifiers, COSE_Sign1 structural decode, URI per-scheme shape rules)\n// fire in `validator.ts` so the validator can emit the precise structural\n// codes (`UNSUPPORTED_*_ALG`, `ENC_*`, `SIG_*`, `INVALID_URI`,\n// `CRIT_SHAPE_INVALID`, …) rather than a generic schema-mismatch.\n//\n// Refinements that DO live in the schema (because the validator's domain\n// pass lifts these as `SCHEMA_*` / `*_LENGTH_MISMATCH` codes directly):\n// - chunk size `[1, 64]` → `CHUNK_TOO_LARGE`\n// - 32-byte digest / 32-byte root / 32-byte supersedes → `HASH_DIGEST_LENGTH_MISMATCH`\n// / `SUPERSEDES_TX_INVALID_LENGTH`\n// - 24-byte nonce / 32-byte slots_mac →\n// `NONCE_LENGTH_MISMATCH` / `ENC_SLOTS_MAC_INVALID_LENGTH`\n// - passphrase salt 16..64 bytes → `ENC_PASSPHRASE_SALT_TOO_SHORT` /\n// `ENC_PASSPHRASE_SALT_TOO_LONG`\n//\n// Per-slot recipient lengths (`epk`, `kem_ct`, `wrap`) are NOT enforced here:\n// the required slot shape depends on the envelope-level `kem`, which a slot\n// cannot see in isolation. The KEM-driven slot descriptor in `validator.ts`\n// emits the precise `KEM_EPK_LENGTH_MISMATCH` / `KEM_CT_LENGTH_MISMATCH` /\n// `WRAP_LENGTH_MISMATCH` / `ENC_SLOT_INVALID_SHAPE` codes instead.\n\nimport { z } from 'zod';\n\n// =============================================================================\n// Chunked-bytes / chunked-text arrays\n// =============================================================================\n\n// `[1* bstr .size (1..64)]`. A zero-length chunk (0 < 1) is rejected with the\n// SAME `CHUNK_TOO_LARGE` code as oversized chunks (any length outside\n// `[1, 64]`).\nexport const ChunkedBytesArraySchema = z\n .array(\n z.instanceof(Uint8Array).refine((b) => b.length >= 1 && b.length <= 64, {\n params: { code: 'CHUNK_TOO_LARGE' },\n }),\n )\n .min(1);\nexport type ChunkedBytesArray = z.infer<typeof ChunkedBytesArraySchema>;\n\n// `[1* tstr .size (1..64)]` — chunk byte length is the UTF-8-encoded length\n// (each `tstr` is wire-encoded as UTF-8). The `tstr .size (1..64)` pin is a\n// byte-count constraint, not a code-unit constraint.\nconst UTF8_ENCODER = new TextEncoder();\nexport const UriChunkArraySchema = z\n .array(\n z.string().refine(\n (s) => {\n const n = UTF8_ENCODER.encode(s).length;\n return n >= 1 && n <= 64;\n },\n { params: { code: 'CHUNK_TOO_LARGE' } },\n ),\n )\n .min(1);\nexport type UriChunkArray = z.infer<typeof UriChunkArraySchema>;\n\n// =============================================================================\n// Hashes map\n// =============================================================================\n//\n// `hashes` is a non-empty CBOR map keyed by content-hash algorithm identifier\n// (a CBOR text string from the content-hash registry) with the 32-byte digest\n// as value. cbor2 surfaces a text-keyed CBOR map as a plain JS object — z.record\n// admits any string key here. Both the registry-membership check\n// (`UNSUPPORTED_HASH_ALG`) and the per-algorithm digest-length check\n// (`HASH_DIGEST_LENGTH_MISMATCH`) live in the validator's domain pass so\n// each violation emits its precise code; the schema only enforces the\n// value is a CBOR byte string.\n\nexport const HashDigestSchema = z.instanceof(Uint8Array);\n\nexport const HashesMapSchema = z.record(z.string(), HashDigestSchema);\nexport type HashesMap = z.infer<typeof HashesMapSchema>;\n\n// =============================================================================\n// Top-level `merkle[]`\n// =============================================================================\n//\n// Each commit is a closed map `{alg, root, leaf_count, ? uris}`. `alg` is open\n// (registry membership is enforced in the validator's domain pass — unknown\n// identifiers emit `UNSUPPORTED_MERKLE_COMMIT_ALG`).\n\nexport const MerkleCommitSchema = z\n .object({\n alg: z.string(),\n root: z.instanceof(Uint8Array),\n leaf_count: z.number().int().min(1),\n uris: z.array(UriChunkArraySchema).min(1).optional(),\n })\n .strict();\nexport type MerkleCommit = z.infer<typeof MerkleCommitSchema>;\n\n// =============================================================================\n// Encryption envelope\n// =============================================================================\n\n// Per-slot recipient entry. The slot shape is KEM-driven:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — `epk` is the\n// ephemeral X25519 public key, `wrap` is the 32-byte CEK + 16-byte\n// ChaCha20-Poly1305 tag.\n// - mlkem768x25519: `{ kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }` —\n// `kem_ct` is the 1120-byte X-Wing `enc` carried as a chunked byte-string\n// array (the same `bytes-chunk-array` shape `sigs[i].cose_sign1` uses);\n// there is NO per-slot `epk` on the hybrid path.\n//\n// The `kem` identifier is hoisted to envelope scope (a per-slot `kem` would\n// be wire-bloat). The schema is deliberately PERMISSIVE:\n// `epk`, `kem_ct`, and `wrap` are all optional and `.strict()` is NOT applied.\n// Both the per-field length checks (`KEM_EPK_LENGTH_MISMATCH`,\n// `KEM_CT_LENGTH_MISMATCH`, `WRAP_LENGTH_MISMATCH`) and the KEM-driven\n// shape gate (which field MUST/MUST NOT be present for the declared `kem`,\n// emitting `ENC_SLOT_INVALID_SHAPE`) live in the validator's domain pass —\n// the structural schema cannot know the envelope `kem` from a slot in\n// isolation, and we want the precise KEM-aware code rather than a generic\n// schema mismatch. Because `.strict()` is dropped, the domain pass MUST\n// explicitly reject cross-KEM contamination (an x25519 slot carrying\n// `kem_ct`, or a hybrid slot carrying `epk`).\nexport const SlotSchema = z.object({\n epk: z.instanceof(Uint8Array).optional(),\n kem_ct: ChunkedBytesArraySchema.optional(),\n wrap: z.instanceof(Uint8Array).optional(),\n});\nexport type Slot = z.infer<typeof SlotSchema>;\n\n// Argon2id params `{m, t, p}` are a closed map. Each value MUST be a CBOR\n// unsigned integer; the FLOOR check (`m ≥ 65536`,\n// `t ≥ 3`, `p ≥ 1`) emits `ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW` in the\n// validator's domain pass — keeping it out of the schema lets us emit the\n// distinct salt-length code when salt itself is malformed too.\nexport const Argon2idParamsSchema = z\n .object({\n m: z.number().int(),\n t: z.number().int(),\n p: z.number().int(),\n })\n .strict();\nexport type Argon2idParams = z.infer<typeof Argon2idParamsSchema>;\n\n// Passphrase block. `alg` is open (registry membership checked in the\n// validator's domain pass → `ENC_PASSPHRASE_ALG_UNSUPPORTED`);\n// `params` is open here (validator narrows on the registered `alg` value and\n// emits `SCHEMA_UNKNOWN_FIELD` for extra keys, `ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW`\n// for sub-floor values). `salt` length floor/ceiling are schema-layer\n// refinements with the dedicated `ENC_PASSPHRASE_SALT_TOO_SHORT/TOO_LONG`\n// codes — they belong at the schema layer because a slot cannot otherwise\n// see the salt length.\nexport const PassphraseBlockSchema = z\n .object({\n alg: z.string(),\n salt: z.instanceof(Uint8Array).superRefine((bytes, ctx) => {\n if (bytes.length < 16) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} < 16`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_SHORT' },\n });\n } else if (bytes.length > 64) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} > 64`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_LONG' },\n });\n }\n }),\n params: z.record(z.string(), z.unknown()),\n })\n .strict();\nexport type PassphraseBlock = z.infer<typeof PassphraseBlockSchema>;\n\n// Sealed-PoE envelope. The wire format admits any combination of\n// `kem` / `slots` / `slots_mac` / `passphrase` keys (permissive superset);\n// cross-field invariants (slots ⊕ passphrase, slots ↔ slots_mac, slots\n// requires kem, content-hash binding, slots non-empty) are enforced in the\n// validator's domain pass so each violation emits its typed code rather\n// than a generic shape mismatch.\nexport const EncryptionEnvelopeSchema = z\n .object({\n scheme: z.unknown(),\n aead: z.string(),\n kem: z.string().optional(),\n nonce: z.instanceof(Uint8Array),\n slots: z.array(SlotSchema).optional(),\n slots_mac: z\n .instanceof(Uint8Array)\n .refine((b) => b.length === 32, {\n params: { code: 'ENC_SLOTS_MAC_INVALID_LENGTH' },\n })\n .optional(),\n passphrase: PassphraseBlockSchema.optional(),\n })\n .strict();\nexport type EncryptionEnvelope = z.infer<typeof EncryptionEnvelopeSchema>;\n\n// =============================================================================\n// Item entry\n// =============================================================================\n\nexport const ItemEntrySchema = z\n .object({\n hashes: HashesMapSchema,\n uris: z.array(UriChunkArraySchema).min(1).optional(),\n // Captured as `unknown` so the validator can run the\n // `ENC_REQUIRES_CONTENT_HASH` pre-check ahead of any inner-shape errors\n // and surface the most informative code first.\n enc: z.unknown().optional(),\n })\n .strict();\nexport type ItemEntry = z.infer<typeof ItemEntrySchema>;\n\n// =============================================================================\n// Sig entry\n// =============================================================================\n//\n// Closed CBOR map `{cose_sign1, ? cose_key}`. Canonical CBOR map-key sort\n// (RFC 8949 §4.2.1, bytewise lex on encoded keys) places `cose_key`\n// (length-8 tstr, `0x68`) BEFORE `cose_sign1` (length-10 tstr, `0x6a`); the\n// schema property-order is irrelevant — the canonical encoder handles it.\nexport const SigEntrySchema = z\n .object({\n cose_key: ChunkedBytesArraySchema.optional(),\n cose_sign1: ChunkedBytesArraySchema,\n })\n .strict();\nexport type SigEntry = z.infer<typeof SigEntrySchema>;\n\n// =============================================================================\n// Supersedence\n// =============================================================================\n\nexport const SupersedesSchema = z.instanceof(Uint8Array).refine((b) => b.length === 32, {\n params: { code: 'SUPERSEDES_TX_INVALID_LENGTH' },\n});\nexport type Supersedes = z.infer<typeof SupersedesSchema>;\n\n// =============================================================================\n// Top-level record\n// =============================================================================\n//\n// `v == 1` is a literal — a future major (`v: 2`) MUST be rejected with\n// `SCHEMA_INVALID_LITERAL`. `z.literal(1)` preserves the narrow `1` type for\n// the inferred `PoeRecord[\"v\"]` (so consumers can dispatch on it) and emits\n// Zod's `invalid_value` code which the validator's mapper lifts to\n// `SCHEMA_INVALID_LITERAL`.\n//\n// `looseObject` admits extension keys (matching `^x-.+` or `^[a-z]+-.+`); the\n// validator's domain pass rejects unknown keys that match neither pattern with\n// `SCHEMA_UNKNOWN_FIELD`.\nexport const VersionLiteralSchema = z.literal(1);\n\nexport const PoeRecordSchema = z.looseObject({\n v: VersionLiteralSchema,\n items: z.array(ItemEntrySchema).optional(),\n merkle: z.array(MerkleCommitSchema).optional(),\n supersedes: SupersedesSchema.optional(),\n sigs: z.array(SigEntrySchema).optional(),\n crit: z.array(z.string()).optional(),\n});\nexport type PoeRecord = z.infer<typeof PoeRecordSchema>;\n\n// =============================================================================\n// Closed top-level base-key registry\n// =============================================================================\n//\n// Used by the validator's domain pass to distinguish unknown-typo keys from\n// well-formed extension keys (`^x-.+` / `^[a-z]+-.+`).\nexport const TOP_LEVEL_BASE_KEYS: ReadonlySet<string> = new Set([\n 'v',\n 'items',\n 'merkle',\n 'supersedes',\n 'sigs',\n 'crit',\n]);\n\n// Extension-key namespaces. Anchored at both ends so an\n// embedded newline cannot smuggle a multi-segment key past the check: `.`\n// excludes `\\n` in JS, and the `\\n?$` tail tolerates exactly ONE trailing\n// newline (matching the Python validator's `re.fullmatch(r'^(x-.+|[a-z]+-.+)$')`\n// semantics, where `$` likewise admits a single trailing `\\n`). So `x-note\\n`\n// is an extension key, but `x-a\\nb`, `x-note\\n\\n`, and `x-\\n` are not.\nexport const EXTENSION_KEY_VENDOR_RE = /^x-.+\\n?$/;\nexport const EXTENSION_KEY_COMPANION_RE = /^[a-z]+-.+\\n?$/;\n\nexport function isExtensionKey(k: string): boolean {\n return EXTENSION_KEY_VENDOR_RE.test(k) || EXTENSION_KEY_COMPANION_RE.test(k);\n}\n","// Every canonical-CBOR decode violation collapses to the single public Label 309\n// taxonomy code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate\n// keys, unsorted keys, non-minimal integer encodings, and invalid UTF-8 in text\n// strings. The taxonomy intentionally has one code for all of these; the\n// specific cause survives in the human-readable error message, not as a\n// separate code.\nexport type CanonicalCborErrorCode = 'MALFORMED_CBOR';\n\nexport class CanonicalCborError extends Error {\n readonly code: CanonicalCborErrorCode;\n\n constructor(code: CanonicalCborErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CanonicalCborError';\n this.code = code;\n }\n}\n","import { cdeDecodeOptions, decode, encode } from 'cbor2';\nimport { sortCoreDeterministic } from 'cbor2/sorts';\n\nimport { CanonicalCborError } from './errors';\n\nexport type CanonicalCborValue =\n | null\n | boolean\n | number\n | bigint\n | string\n | Uint8Array\n | readonly CanonicalCborValue[]\n | { readonly [key: string]: CanonicalCborValue }\n | ReadonlyMap<string | number, CanonicalCborValue>;\n\nexport function encodeCanonicalCbor(value: CanonicalCborValue): Uint8Array {\n return encode(value, {\n cde: true,\n collapseBigInts: true,\n rejectDuplicateKeys: true,\n sortKeys: sortCoreDeterministic,\n });\n}\n\nexport function decodeCanonicalCbor(bytes: Uint8Array): unknown {\n try {\n return decode(bytes, {\n ...cdeDecodeOptions,\n rejectStreaming: true,\n rejectDuplicateKeys: true,\n // A Label 309 record carries integers, byte/text strings, arrays, maps and\n // `null` — and nothing else. Without these rejections the major-type-7\n // surface leaks into the decoder: a float16/32/64 that happens to hold an\n // integral value (e.g. 1.0) silently decodes to the integer 1 and passes\n // a `z.literal(1)` / Number.isInteger schema check, so two byte strings\n // that are NOT byte-identical canonicalise to the same record. That\n // breaks the cross-implementation parity invariant (the Python twin\n // already rejects non-integer `v` / `enc.scheme` outright). Reject the\n // whole non-record surface — floats, negative zero, undefined, and\n // non-{true,false,null} simple values — so any such input surfaces as\n // MALFORMED_CBOR via mapDecodeError rather than decoding to a look-alike.\n rejectFloats: true,\n rejectNegativeZero: true,\n rejectUndefined: true,\n rejectSimple: true,\n });\n } catch (cause) {\n throw mapDecodeError(cause);\n }\n}\n\nfunction mapDecodeError(cause: unknown): CanonicalCborError {\n const message = cause instanceof Error ? cause.message : String(cause);\n const lower = message.toLowerCase();\n // Every canonical-decode violation collapses to the single public taxonomy\n // code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate keys,\n // non-canonical (unsorted) key ordering, non-minimal integer encodings, and\n // invalid UTF-8 in text strings. cbor2 raises the SAME \"Duplicate or out of\n // order key\" message for both true duplicates AND distinct-but-unsorted keys,\n // so the two are indistinguishable by message — and per the Label 309 taxonomy\n // both belong under MALFORMED_CBOR anyway. The specific cause survives in the\n // human-readable message below; for indefinite-length we state it explicitly\n // so the diagnostic is not lost when the code is collapsed.\n const isIndefinite = lower.includes('streaming') || lower.includes('indefinite');\n const detail = isIndefinite\n ? `indefinite-length items are not permitted in canonical CBOR: ${message}`\n : message;\n return new CanonicalCborError('MALFORMED_CBOR', `cbor decode failed: ${detail}`, { cause });\n}\n","// Permissive (non-canonical) CBOR decoder for outer wire decode (e.g. Cardano tx CBOR),\n// where the input is not constrained to be canonical RFC 8949 §4.2.1 form.\n//\n// Label 309 records themselves MUST be canonical and MUST go through\n// `decodeCanonicalCbor`. This decoder\n// exists to peel the outer Cardano tx structure ([body, witness_set, is_valid,\n// auxiliary_data]) so the label-309 byte string can be re-encoded canonically\n// for validator + signature verification.\n\nimport { decode } from 'cbor2';\n\nexport function decodeCbor(bytes: Uint8Array): unknown {\n return decode(bytes);\n}\n","// Label 309 v1 record encoder.\n//\n// Produces canonical CBOR bytes per RFC 8949 §4.2.1 deterministic encoding —\n// definite-length, sorted bytewise lex map keys, no duplicates, preferred\n// integer/float form. The canonical layer (`@cardanowall/crypto-core/cbor`)\n// configures `cbor2` with `cde: true, rejectDuplicateKeys: true`, so the\n// encoder's only job is to translate the validator-typed record shape into\n// the `CanonicalCborValue` algebra.\n//\n// Wire-shape contract:\n// - `items[i].hashes` is a CBOR MAP (text-keyed) — not an array of `{alg,h}`.\n// - `merkle[]` is a top-level array, peer to `items` and `sigs`.\n// - Each `sigs[i]` is a CBOR MAP `{cose_sign1, ? cose_key}` (canonical\n// sort places the optional `cose_key` BEFORE `cose_sign1`).\n// - The encryption envelope uses `scheme` (NOT `v`), `aead` (NOT `alg`),\n// `nonce` (NOT `iv`), `slots` (NOT `recipients`), `slots_mac` (NOT\n// `hdr_mac`); the KEM identifier is hoisted to envelope scope as `kem`.\n// - The passphrase block uses key name `passphrase` and `alg = \"argon2id\"`.\n//\n// Round-trip property: for every record `R` that the validator accepts,\n// validate(encode(R)).ok === true\n// && validate(encode(R)).record ≡ R (modulo CBOR-canonical key sort)\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '@cardanowall/crypto-core/cbor';\n\nimport type {\n EncryptionEnvelope,\n ItemEntry,\n MerkleCommit,\n PassphraseBlock,\n PoeRecord,\n SigEntry,\n Slot,\n} from './schema';\n\ntype CborMap = { [key: string]: CanonicalCborValue };\n\nexport function encodePoeRecord(record: PoeRecord): Uint8Array {\n return encodeCanonicalCbor(recordToCbor(record));\n}\n\n// Helper: build the canonical-CBOR `record_body` (the bytes that record-level\n// `sigs[i]` signs over). The body is the full record map MINUS the `sigs`\n// field; producers prepend the 25-byte UTF-8 domain prefix\n// `cardano-poe-record-sig-v1` before invoking Ed25519 (the crypto-core\n// helper `buildLabel309SigStructure` handles the prefix and `Sig_structure`\n// wrapping).\nexport function encodeRecordBodyForSigning(record: PoeRecord): Uint8Array {\n const body: CborMap = recordToCborInternal(record, /* includeSigs */ false);\n return encodeCanonicalCbor(body);\n}\n\nfunction recordToCbor(record: PoeRecord): CanonicalCborValue {\n return recordToCborInternal(record, /* includeSigs */ true);\n}\n\nfunction recordToCborInternal(record: PoeRecord, includeSigs: boolean): CborMap {\n const out: CborMap = { v: record.v };\n if (record.items !== undefined) out['items'] = record.items.map(itemToCbor);\n if (record.merkle !== undefined) out['merkle'] = record.merkle.map(merkleToCbor);\n if (record.supersedes !== undefined) out['supersedes'] = record.supersedes;\n if (includeSigs && record.sigs !== undefined) out['sigs'] = record.sigs.map(sigEntryToCbor);\n if (record.crit !== undefined) out['crit'] = record.crit.slice();\n // Preserve extension keys verbatim — they are part of the signed\n // `record_body` and MUST round-trip byte-identical.\n for (const [k, v] of Object.entries(record)) {\n if (\n k === 'v' ||\n k === 'items' ||\n k === 'merkle' ||\n k === 'supersedes' ||\n k === 'sigs' ||\n k === 'crit'\n ) {\n continue;\n }\n out[k] = v as CanonicalCborValue;\n }\n return out;\n}\n\nfunction itemToCbor(item: ItemEntry): CanonicalCborValue {\n const out: CborMap = { hashes: hashesToCbor(item.hashes) };\n if (item.uris !== undefined) {\n out['uris'] = item.uris.map((chunks) => chunks.slice());\n }\n if (item.enc !== undefined) {\n out['enc'] = envelopeToCbor(item.enc as EncryptionEnvelope);\n }\n return out;\n}\n\nfunction hashesToCbor(hashes: Readonly<Record<string, Uint8Array>>): CanonicalCborValue {\n // text-keyed CBOR map — canonical sort orders by encoded-key bytewise lex\n // automatically (`sha2-256` `0x68` precedes `blake2b-256` `0x6b`).\n const out: CborMap = {};\n for (const [alg, digest] of Object.entries(hashes)) {\n out[alg] = digest;\n }\n return out;\n}\n\nfunction merkleToCbor(commit: MerkleCommit): CanonicalCborValue {\n const out: CborMap = {\n alg: commit.alg,\n root: commit.root,\n leaf_count: commit.leaf_count,\n };\n if (commit.uris !== undefined) {\n out['uris'] = commit.uris.map((chunks) => chunks.slice());\n }\n return out;\n}\n\nfunction envelopeToCbor(enc: EncryptionEnvelope): CanonicalCborValue {\n const out: CborMap = {\n scheme: enc.scheme as CanonicalCborValue,\n aead: enc.aead,\n nonce: enc.nonce,\n };\n if (enc.kem !== undefined) out['kem'] = enc.kem;\n if (enc.slots !== undefined) out['slots'] = enc.slots.map(slotToCbor);\n if (enc.slots_mac !== undefined) out['slots_mac'] = enc.slots_mac;\n if (enc.passphrase !== undefined) out['passphrase'] = passphraseToCbor(enc.passphrase);\n return out;\n}\n\nfunction slotToCbor(slot: Slot): CanonicalCborValue {\n // KEM-driven slot serialization. The canonical encoder sorts map keys by\n // length-then-bytewise (RFC 8949 §4.2.1), so it emits `wrap` (4-byte key)\n // before `kem_ct` (6-byte key) and `epk` (3-byte key) before `wrap`\n // automatically — insertion order here is irrelevant to the wire bytes.\n //\n // - x25519: `{ epk: bstr(32), wrap: bstr(48) }`\n // - mlkem768x25519: `{ kem_ct: [ bstr, ... ], wrap: bstr(48) }` — `kem_ct`\n // is the already-chunked array (NOT re-chunked here), so the bytes match\n // what crypto-core committed to `slots_mac` byte-for-byte.\n if (slot.kem_ct !== undefined) {\n return { kem_ct: slot.kem_ct.map((c) => c), wrap: slot.wrap! };\n }\n return { epk: slot.epk!, wrap: slot.wrap! };\n}\n\nfunction passphraseToCbor(pp: PassphraseBlock): CanonicalCborValue {\n return {\n alg: pp.alg,\n salt: pp.salt,\n params: pp.params as { readonly [key: string]: CanonicalCborValue },\n };\n}\n\nfunction sigEntryToCbor(entry: SigEntry): CanonicalCborValue {\n const out: CborMap = { cose_sign1: entry.cose_sign1.map((b) => b) };\n if (entry.cose_key !== undefined) {\n out['cose_key'] = entry.cose_key.map((b) => b);\n }\n return out;\n}\n","import { blake2b } from '@noble/hashes/blake2.js';\n\nexport function blake2b256(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 32 });\n}\n\n// CIP-19 stake-address derivation, used for the wallet path-2 signer binding,\n// requires the 28-byte BLAKE2b digest of the signer's Ed25519 public key.\n// The Cardano ledger encodes stake addresses as\n// `network_header_byte || Blake2b-224(stake_vk)`\n// per CIP-19, so this output length is fixed by spec.\nexport function blake2b224(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 28 });\n}\n","import * as ed from '@noble/ed25519';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ned.hashes.sha512 = sha512;\n\n// Ed25519 group order L (= 2^252 + 27742317777372353535851937790883648493).\nconst L = ed.Point.CURVE().n;\n\nexport interface SignEd25519Opts {\n readonly seed: Uint8Array;\n readonly message: Uint8Array;\n}\n\nexport interface VerifyEd25519Opts {\n readonly publicKey: Uint8Array;\n readonly message: Uint8Array;\n readonly signature: Uint8Array;\n}\n\nexport interface GetPublicKeyEd25519Opts {\n readonly seed: Uint8Array;\n}\n\nexport function signEd25519(opts: SignEd25519Opts): Uint8Array {\n return ed.sign(opts.message, opts.seed);\n}\n\n// Little-endian 32-byte scalar → bigint.\nfunction leBytesToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]!);\n }\n return value;\n}\n\n// Strict (non-cofactored) Ed25519 verification per RFC 8032 §5.1.7, matching\n// libsodium/PyNaCl `crypto_sign_verify_detached` and ed25519-dalek\n// `verify_strict`. The cofactor-less check rejects every small-order /\n// torsion-component edge case in the C2SP/CCTV corpus, which noble's\n// `{ zip215: false }` mode does NOT (it remains cofactored: it checks\n// `[8]([S]B - [k]A - R) == 0`, accepting torsion components).\n//\n// The verification equation is the unscaled `[S]B == R + [k]A`, rewritten as\n// `[S]B - [k]A - R == identity`. We reject S >= L (non-canonical scalar) and\n// any small-order A or R up front, so a torsion component can never be smuggled\n// through the cofactor multiplication the cofactored variant performs.\nexport function verifyEd25519(opts: VerifyEd25519Opts): boolean {\n const { signature, message, publicKey } = opts;\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n\n // S = LE(sig[32..64]); reject if not a canonical scalar (S >= L).\n const S = leBytesToBigInt(signature.subarray(32, 64));\n if (S >= L) return false;\n\n // Decode A (public key) and R (sig[0..32]) with the canonical (non-zip215)\n // point encoding; a non-canonical encoding throws and rejects.\n let A: ed.Point;\n let R: ed.Point;\n try {\n A = ed.Point.fromBytes(publicKey);\n R = ed.Point.fromBytes(signature.subarray(0, 32));\n } catch {\n return false;\n }\n\n // Reject small-order (cofactor-torsion) A or R: this is exactly the strictness\n // that distinguishes verify_strict from the cofactored check.\n if (A.isSmallOrder() || R.isSmallOrder()) return false;\n\n // k = SHA-512(R || A || M) reduced mod L.\n const k =\n leBytesToBigInt(ed.hash(concatBytes(signature.subarray(0, 32), publicKey, message))) % L;\n\n // Accept iff [S]B - [k]A - R == identity. `multiplyUnsafe` returns the\n // identity for a 0 scalar, but guard explicitly to avoid relying on that.\n const sB = S === 0n ? ed.Point.ZERO : ed.Point.BASE.multiplyUnsafe(S);\n const kA = k === 0n ? ed.Point.ZERO : A.multiplyUnsafe(k);\n return sB.subtract(kA).subtract(R).is0();\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function getPublicKeyEd25519(opts: GetPublicKeyEd25519Opts): Uint8Array {\n return ed.getPublicKey(opts.seed);\n}\n","// Isomorphic constant-time byte-equality. crypto-core is browser-safe by\n// design, so we cannot import `node:crypto.timingSafeEqual` — webpack rejects\n// the `node:` scheme in the browser bundle. A pure-JS XOR loop is constant-time\n// for equal-length inputs; length mismatch is a deliberate early-return (the\n// API surface itself leaks length, same as node's timingSafeEqual which throws).\nexport function compareCt(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n // Lengths are equal and `i` stays in-bounds, so both indexes are always\n // defined — no nullish guard is needed (and one would read as a guard for\n // an impossible case).\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n","export type CoseVerifyErrorCode =\n | 'MALFORMED_SIG_COSE'\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'UNSUPPORTED_SIG_ALG'\n | 'KID_UNRESOLVED'\n | 'SIGNATURE_INVALID';\n\nexport class CoseVerifyError extends Error {\n readonly code: CoseVerifyErrorCode;\n\n constructor(code: CoseVerifyErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CoseVerifyError';\n this.code = code;\n }\n}\n\nexport type CoseVerifyResult =\n | { ok: true; signerKey: Uint8Array; alg: number }\n | { ok: false; error: { code: CoseVerifyErrorCode; message: string } };\n","import {\n decodeCanonicalCbor,\n encodeCanonicalCbor,\n type CanonicalCborValue,\n} from '../cbor/canonical';\nimport { CanonicalCborError } from '../cbor/errors';\nimport { blake2b224 } from '../hash/blake2b-256';\nimport { signEd25519, verifyEd25519 } from '../sig/ed25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { CoseVerifyError, type CoseVerifyResult } from './errors';\n\nexport type CoseHeader = Map<number | string, unknown>;\n\n// Label 309 v1 domain separator embedded as a prefix on `Sig_structure[3]`\n// (`to_sign`). The separator is\n// NOT placed in `Sig_structure[2]` (`external_aad`) because CIP-30 `signData`\n// — the only realistic wallet-signing path on Cardano — explicitly forbids a\n// non-empty `external_aad`. Pinning the prefix into the payload preserves the\n// anti-replay property while keeping wallet-produced signatures byte-identical\n// to verifier-side recomputation.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX = 'cardano-poe-record-sig-v1' as const;\n// Composer path-2 wallet flow consumes the prefix bytes directly\n// to assemble `toSign = prefix || canonical_cbor(record_body)` BEFORE calling\n// `walletSignData` (the wallet's `signData()` receives this concatenation as\n// its `payload` argument verbatim per CIP-30). The bytes constant is exported\n// so a composer can build the input without re-encoding the prefix at every\n// call site.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES = new TextEncoder().encode(\n CARDANO_POE_SIG_DOMAIN_PREFIX,\n);\n\n// Fail-fast: the prefix length is byte-pinned at 25 UTF-8 bytes. A different\n// runtime encoding would silently break round-tripping\n// against the reference vectors.\nif (CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length !== 25) {\n throw new Error(\n `cardano-poe-record-sig-v1 prefix must encode to exactly 25 UTF-8 bytes, got ${CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length}`,\n );\n}\n\nconst EMPTY_BYTES = new Uint8Array(0);\n\nexport interface CoseSign1Decoded {\n readonly protectedHeader: CoseHeader;\n // preserved for Sig_structure reconstruction — never re-encode the decoded header map (RFC 9052 §4.4)\n readonly protectedBytes: Uint8Array;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport interface BuildSigStructureArgs {\n readonly context: 'Signature1';\n readonly bodyProtectedBytes: Uint8Array;\n readonly externalAad: Uint8Array;\n readonly payload: Uint8Array;\n}\n\n// Raw RFC 9052 §4.4 Sig_structure builder. General-purpose: callers control\n// `external_aad` and `payload` exactly. For Label 309 record signing use\n// `buildLabel309SigStructure` instead — it enforces the Label 309 record-signature invariants.\nexport function buildSigStructure(args: BuildSigStructureArgs): Uint8Array {\n return encodeCanonicalCbor([\n args.context,\n args.bodyProtectedBytes,\n args.externalAad,\n args.payload,\n ] as readonly CanonicalCborValue[]);\n}\n\nexport interface BuildLabel309SigStructureArgs {\n readonly bodyProtectedBytes: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed.\n readonly recordBodyCbor: Uint8Array;\n}\n\n// Label 309 v1 specialisation of `Sig_structure` (RFC 9052 §4.4 base structure):\n// to_sign = utf8(\"cardano-poe-record-sig-v1\") || canonical_cbor(record_body_minus_sigs)\n// Sig_structure = [ \"Signature1\", body_protected, h'' (empty), to_sign ]\n// Always forces `external_aad = h''` (empty bstr) — the CIP-30 wallet path\n// cannot carry a non-empty `external_aad`, so the domain separator lives in\n// `Sig_structure[3]` rather than `Sig_structure[2]`.\nexport function buildLabel309SigStructure(args: BuildLabel309SigStructureArgs): Uint8Array {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.recordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.recordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n return buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: args.bodyProtectedBytes,\n externalAad: EMPTY_BYTES,\n payload: toSign,\n });\n}\n\nexport interface EncodeCoseSign1Args {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport function encodeCoseSign1(args: EncodeCoseSign1Args): Uint8Array {\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n return encodeCanonicalCbor([\n protectedBytes,\n args.unprotectedHeader as CanonicalCborValue,\n args.payload,\n args.signature,\n ] as readonly CanonicalCborValue[]);\n}\n\n// cbor2's decoder returns Map for integer-keyed maps but plain Object for empty\n// or string-keyed maps; normalise both representations to Map.\nfunction asCoseHeader(value: unknown): CoseHeader | null {\n if (value instanceof Map) return value as CoseHeader;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function decodeCoseSign1(bytes: Uint8Array): CoseSign1Decoded {\n let arr: unknown;\n try {\n arr = decodeCanonicalCbor(bytes);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'cose decode failed', { cause });\n }\n if (!Array.isArray(arr) || arr.length !== 4) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'expected 4-element array');\n }\n const [protectedBytesRaw, unprotectedRaw, payloadRaw, signatureRaw] = arr;\n if (!(protectedBytesRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected_bytes must be bytes');\n }\n const unprotectedHeader = asCoseHeader(unprotectedRaw);\n if (unprotectedHeader === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'unprotected header must be map');\n }\n if (payloadRaw !== null && !(payloadRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'payload must be bytes or null');\n }\n if (!(signatureRaw instanceof Uint8Array) || signatureRaw.length !== 64) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'signature must be 64 bytes');\n }\n let protectedHeader: CoseHeader;\n if (protectedBytesRaw.length === 0) {\n protectedHeader = new Map();\n } else {\n let decodedProtected: unknown;\n try {\n decodedProtected = decodeCanonicalCbor(protectedBytesRaw);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header decode failed', { cause });\n }\n const ph = asCoseHeader(decodedProtected);\n if (ph === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header must decode to map');\n }\n // Empty protected header MUST encode as the single byte 0x40 (zero-length bstr),\n // not 0x41 0xA0 (a 1-byte bstr containing an empty CBOR map). RFC 9052 §3 +\n // Label 309 canonical-CBOR mandate.\n if (ph.size === 0) {\n throw new CoseVerifyError(\n 'MALFORMED_SIG_COSE',\n 'empty protected header must encode as 0x40 (zero-length bstr), not as an empty map',\n );\n }\n protectedHeader = ph;\n }\n return {\n protectedHeader,\n protectedBytes: protectedBytesRaw,\n unprotectedHeader,\n payload: payloadRaw,\n signature: signatureRaw,\n };\n}\n\nexport type CoseSign1BuildErrorCode = 'SIGNER_NOT_PROVIDED' | 'SIGNER_AND_SEED_BOTH_PROVIDED';\n\nexport class CoseSign1BuildError extends Error {\n readonly code: CoseSign1BuildErrorCode;\n\n constructor(code: CoseSign1BuildErrorCode, message: string) {\n super(message);\n this.name = 'CoseSign1BuildError';\n this.code = code;\n }\n}\n\nexport interface CoseSign1Label309BuildArgs {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n // Canonical CBOR of the record body with `sigs` removed. The\n // builder prepends the 25-byte UTF-8 domain prefix `cardano-poe-record-sig-v1`\n // internally — callers MUST NOT pre-concatenate it.\n readonly recordBodyCbor: Uint8Array;\n // EITHER the raw 32-byte Ed25519 seed (used by KAT tests, Python parity, and\n // the off-host signing helper) OR an injected signer closure that signs the\n // assembled Sig_structure bytes (composer-side use — keeps the private key\n // inside the unlock-store closure so it never escapes scope).\n // Exactly one of the two MUST be provided; mutual exclusion enforced at\n // runtime via CoseSign1BuildError.\n readonly signerSecretKey?: Uint8Array;\n readonly signer?: (sigStructureBytes: Uint8Array) => Uint8Array;\n}\n\n// Label 309 v1 record-signature builder:\n// 1. compute `to_sign = utf8(\"cardano-poe-record-sig-v1\") || recordBodyCbor`\n// 2. Sig_structure = [ \"Signature1\", bodyProtected, h'', to_sign ]\n// 3. Ed25519-sign Sig_structure (via seed OR injected closure)\n// 4. emit COSE_Sign1 with payload = CBOR null (detached signature, mandatory)\nexport function coseSign1Label309Build(args: CoseSign1Label309BuildArgs): Uint8Array {\n if (args.signerSecretKey === undefined && args.signer === undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n 'coseSign1Label309Build requires either signerSecretKey or signer',\n );\n }\n if (args.signerSecretKey !== undefined && args.signer !== undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_AND_SEED_BOTH_PROVIDED',\n 'coseSign1Label309Build accepts signerSecretKey XOR signer (not both)',\n );\n }\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n const sigStructureBytes = buildLabel309SigStructure({\n bodyProtectedBytes: protectedBytes,\n recordBodyCbor: args.recordBodyCbor,\n });\n let signature: Uint8Array;\n if (args.signer !== undefined) {\n signature = args.signer(sigStructureBytes);\n if (!(signature instanceof Uint8Array) || signature.length !== 64) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n `injected signer must return a 64-byte Uint8Array; got ${signature instanceof Uint8Array ? `${signature.length}-byte Uint8Array` : typeof signature}`,\n );\n }\n } else {\n signature = signEd25519({ seed: args.signerSecretKey!, message: sigStructureBytes });\n }\n return encodeCoseSign1({\n protectedHeader: args.protectedHeader,\n unprotectedHeader: args.unprotectedHeader,\n payload: null,\n signature,\n });\n}\n\nexport interface CoseSign1Label309VerifyArgs {\n readonly message: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed (verifier-recomputed;\n // the 25-byte UTF-8 prefix is prepended internally — callers\n // MUST NOT pre-concatenate it).\n readonly detachedRecordBodyCbor: Uint8Array;\n // Optional out-of-band signer key (path-2 wallet path resolves the key from\n // `sigs[i].cose_key`). Path-1 records carry the 32-byte raw Ed25519 pubkey\n // in the protected header at label 4 (`kid`) and need no out-of-band hint.\n readonly expectedSignerKey?: Uint8Array;\n}\n\n// Label 309 v1 record-signature verifier:\n// - Decode COSE_Sign1\n// - Reject COSE_Sign1[2] != CBOR null (attached payload — including h'') as\n// MALFORMED_SIG_COSE_SIGN1\n// - Recompute to_sign = utf8(\"cardano-poe-record-sig-v1\") || detachedRecordBodyCbor\n// - Sig_structure = [ \"Signature1\", protectedBytes, h'', to_sign ]\n// - Strict Ed25519 verify (RFC 8032 §5.1.7 — `zip215: false` per ed25519.ts)\n//\n// The verifier does NOT accept an `externalAad` argument: Label 309 v1 pins\n// `external_aad = h''` and any deviation would either silently weaken the\n// domain separator or quietly accept malformed records. If a future CIP\n// revision re-enables external_aad, this helper takes a v-bump.\nexport function coseSign1Label309Verify(args: CoseSign1Label309VerifyArgs): CoseVerifyResult {\n let decoded: CoseSign1Decoded;\n try {\n decoded = decodeCoseSign1(args.message);\n } catch (e) {\n if (e instanceof CoseVerifyError) {\n return { ok: false, error: { code: e.code, message: 'errors.cose.malformed' } };\n }\n if (e instanceof CanonicalCborError) {\n return {\n ok: false,\n error: { code: 'MALFORMED_SIG_COSE', message: 'errors.cose.malformed_cbor' },\n };\n }\n throw e;\n }\n // Label 309 v1 mandate: COSE_Sign1[2] (payload field) MUST be CBOR `null` (0xF6).\n // Any non-null payload — including a zero-length byte string `h''` — MUST\n // be rejected as MALFORMED_SIG_COSE_SIGN1.\n if (decoded.payload !== null) {\n return {\n ok: false,\n error: {\n code: 'MALFORMED_SIG_COSE_SIGN1',\n message: 'errors.cose.attached_payload_forbidden',\n },\n };\n }\n const alg = decoded.protectedHeader.get(1);\n if (typeof alg !== 'number' || alg !== -8) {\n return {\n ok: false,\n error: { code: 'UNSUPPORTED_SIG_ALG', message: 'errors.cose.unsupported_alg' },\n };\n }\n const kidRaw = decoded.protectedHeader.get(4);\n let signerKey: Uint8Array | undefined;\n if (kidRaw instanceof Uint8Array && kidRaw.length === 32) {\n signerKey = kidRaw;\n } else if (args.expectedSignerKey instanceof Uint8Array && args.expectedSignerKey.length === 32) {\n signerKey = args.expectedSignerKey;\n }\n if (signerKey === undefined) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_unresolved' },\n };\n }\n // When both a protected-header kid AND an expectedSignerKey are provided,\n // require they agree (constant-time). A protected kid that disagrees with\n // the caller's out-of-band binding is a misuse, not a transient mismatch.\n if (\n kidRaw instanceof Uint8Array &&\n kidRaw.length === 32 &&\n args.expectedSignerKey instanceof Uint8Array &&\n args.expectedSignerKey.length === 32 &&\n !compareCt(kidRaw, args.expectedSignerKey)\n ) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_mismatch' },\n };\n }\n // CIP-8 `hashed = true` mode (the wallet-signed path-2 variant). The unprotected\n // header carries the literal text key `\"hashed\"` with boolean value `true`\n // (text-keyed CBOR maps decode to `Map<string, unknown>` via cbor2). When\n // set, both producer and verifier build `Sig_structure[3] = Blake2b-224(to_sign)`\n // (28-byte digest of the FULL `to_sign` payload including the 25-byte\n // domain prefix). When absent or false, the standard non-hashed path\n // applies unchanged.\n const hashedFlag = decoded.unprotectedHeader.get('hashed');\n let sigStructureBytes: Uint8Array;\n if (hashedFlag === true) {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.detachedRecordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.detachedRecordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n const hashedPayload = blake2b224(toSign);\n sigStructureBytes = buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: decoded.protectedBytes,\n externalAad: EMPTY_BYTES,\n payload: hashedPayload,\n });\n } else {\n sigStructureBytes = buildLabel309SigStructure({\n bodyProtectedBytes: decoded.protectedBytes,\n recordBodyCbor: args.detachedRecordBodyCbor,\n });\n }\n const valid = verifyEd25519({\n publicKey: signerKey,\n message: sigStructureBytes,\n signature: decoded.signature,\n });\n if (!valid) {\n return {\n ok: false,\n error: { code: 'SIGNATURE_INVALID', message: 'errors.cose.signature_invalid' },\n };\n }\n return { ok: true, signerKey, alg };\n}\n","// CIP-30 / RFC 9052 §7 COSE_Key extraction for the Ed25519 sig path.\n//\n// CIP-30 wallets that don't put a 32-byte raw Ed25519 pubkey in the COSE_Sign1\n// protected header instead deliver the signer key as a separate `cbor<COSE_Key>`\n// blob, surfaced in the Label 309 record under the top-level `signer_keys` field.\n// This helper decodes one such blob and returns the underlying 32-byte Ed25519\n// pubkey, or `null` when the blob is malformed, uses an unexpected key type /\n// curve, or has the wrong `x` length.\n//\n// The expected COSE_Key shape (RFC 9053 §7.2 + RFC 8152 §13):\n// {\n// 1 (kty): 1 // OKP\n// 3 (alg): -8 // EdDSA — OPTIONAL but if present MUST be -8\n// -1 (crv): 6 // Ed25519\n// -2 (x): <32 byte raw public key>\n// }\n\nimport { decodeCanonicalCbor } from '../cbor/canonical';\n\nconst COSE_KEY_LABEL_KTY = 1;\nconst COSE_KEY_LABEL_ALG = 3;\nconst COSE_KEY_LABEL_CRV = -1;\nconst COSE_KEY_LABEL_X = -2;\n\nconst KTY_OKP = 1;\nconst ALG_EDDSA = -8;\nconst CRV_ED25519 = 6;\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\n\nfunction asMap(value: unknown): Map<unknown, unknown> | null {\n if (value instanceof Map) return value as Map<unknown, unknown>;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function parseCoseKeyEd25519(blob: Uint8Array): Uint8Array | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(blob);\n } catch {\n return null;\n }\n const map = asMap(decoded);\n if (map === null) return null;\n\n const kty = map.get(COSE_KEY_LABEL_KTY);\n if (typeof kty !== 'number' || kty !== KTY_OKP) return null;\n\n const crv = map.get(COSE_KEY_LABEL_CRV);\n if (typeof crv !== 'number' || crv !== CRV_ED25519) return null;\n\n if (map.has(COSE_KEY_LABEL_ALG)) {\n const alg = map.get(COSE_KEY_LABEL_ALG);\n if (typeof alg !== 'number' || alg !== ALG_EDDSA) return null;\n }\n\n const x = map.get(COSE_KEY_LABEL_X);\n if (!(x instanceof Uint8Array) || x.length !== ED25519_PUBLIC_KEY_LENGTH) return null;\n\n return x;\n}\n","// Label 309 v1 chunked-bytes and chunked-text helpers.\n//\n// The Cardano ledger CDDL constrains every `transaction_metadatum` byte string\n// (`bstr`) and text string (`tstr`) to ≤ 64 bytes. Label 309 therefore carries\n// any logical value larger than 64 bytes as an ARRAY of ≤ 64-byte chunks. Two\n// chunked shapes exist:\n//\n// * `bytes-chunk-array` — `[ 1* bstr .size (1..64) ]` — used for chunked\n// `COSE_Sign1` bytes (`sigs[i].cose_sign1`) and the chunked\n// `cbor<COSE_Key>` blob (`sigs[i].cose_key`).\n// * `uri-chunk-array` — `[ 1* tstr .size (1..64) ]` — used as the inner\n// element of `items[i].uris` and `merkle[i].uris`.\n//\n// Two reconstruction invariants are normative:\n//\n// 1. **Per-chunk size.** `[1, 64]` bytes (zero-length chunks rejected\n// identically to oversized chunks). The validator's schema layer enforces\n// this; the helpers here assume the schema gate has fired.\n// 2. **UTF-8 codepoint integrity (text only).** The reconstructed\n// concatenation MUST be valid UTF-8. The canonical-CBOR decoder already\n// rejects any `tstr` that is not valid UTF-8 (→ `MALFORMED_CBOR`) before\n// these helpers run, so each chunk arrives as a well-formed string; the\n// `TextDecoder({ fatal: true })` pass below is the residual structural\n// guard.\n\nconst CHUNK_MAX_BYTES = 64;\n\nconst UTF8_ENCODER = new TextEncoder();\n\n/**\n * Split a logical byte string into ≤ 64-byte CBOR-bytes chunks\n * (`bytes-chunk-array`). Always returns a non-empty array.\n *\n * For empty inputs, returns `[<empty>]` so the caller's schema gate fails\n * later via `CHUNK_TOO_LARGE` (zero-length chunks are rejected). Real callers\n * feed COSE_Sign1 / cbor<COSE_Key> byte strings, which are never empty.\n */\nexport function chunkBytes(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) return [new Uint8Array(0)];\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n/**\n * Reverse of {@link chunkBytes}: concatenate chunked bytes (`sigs[i].cose_sign1`,\n * `sigs[i].cose_key`) into a single buffer for downstream CBOR/COSE decode.\n * The validator-layer schema enforces the per-chunk size + non-empty-array\n * invariants before this helper runs, so it makes no length checks.\n */\nexport function bytesChunkArrayConcat(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\nexport type ReconstructUriResult =\n | { ok: true; uri: string }\n | { ok: false; code: 'INVALID_URI'; reason: string };\n\n/**\n * Reconstruct a chunked URI (`uri-chunk-array`) into its logical string.\n *\n * The chunks arrive as JS strings produced by the canonical-CBOR decoder,\n * which already rejects any non-UTF-8 `tstr` (surfacing it upstream as\n * `MALFORMED_CBOR`) — so by the time this helper runs the only structural\n * task left is to byte-concatenate and decode. We re-encode each chunk to its\n * UTF-8 bytes, concatenate, and decode the whole with `{ fatal: true }`. A\n * conformant producer never splits a multi-byte codepoint across chunks (the\n * Cardano 64-byte cap is applied on codepoint boundaries), so this decode\n * succeeds for every well-formed record; the `INVALID_URI` branch is the\n * residual guard for a byte sequence that does not reconstruct to valid UTF-8.\n *\n * Per-scheme shape validation (the IPFS CID profile) and absolute-URI /\n * fragment-identifier / scheme-set checks fire in `validator.ts`, NOT here —\n * this helper is structural-only.\n */\nexport function reconstructChunkedUri(chunks: ReadonlyArray<string>): ReconstructUriResult {\n const merged = bytesChunkArrayConcat(chunks.map((c) => UTF8_ENCODER.encode(c)));\n try {\n const uri = new TextDecoder('utf-8', { fatal: true }).decode(merged);\n return { ok: true, uri };\n } catch (cause) {\n return {\n ok: false,\n code: 'INVALID_URI',\n reason: cause instanceof Error ? cause.message : String(cause),\n };\n }\n}\n\n/**\n * Chunk a URI string into `[ tstr .size (1..64) ]`, splitting on UTF-8 byte\n * boundaries so no multi-byte codepoint straddles a chunk.\n *\n * For pure-ASCII URIs (the common `ar://`, `ipfs://` cases) this collapses\n * to plain 64-byte byte-slice chunks. For URIs with non-ASCII path components\n * (rare but possible — RFC 3986 §2.5 IRIs / percent-encoded UTF-8) the\n * algorithm rewinds to the nearest codepoint boundary at each chunk break.\n */\nexport function chunkUri(uri: string): string[] {\n const bytes = UTF8_ENCODER.encode(uri);\n if (bytes.length === 0) return [''];\n if (bytes.length <= CHUNK_MAX_BYTES) return [uri];\n const decoder = new TextDecoder('utf-8', { fatal: true });\n const chunks: string[] = [];\n let cursor = 0;\n while (cursor < bytes.length) {\n let end = Math.min(cursor + CHUNK_MAX_BYTES, bytes.length);\n // Rewind to the start of the previous UTF-8 codepoint if we landed in\n // the middle of a multibyte sequence. UTF-8 continuation bytes match\n // 0b10xx_xxxx; rewind while the byte at `end` is a continuation.\n while (end < bytes.length && (bytes[end]! & 0xc0) === 0x80) end--;\n chunks.push(decoder.decode(bytes.subarray(cursor, end)));\n cursor = end;\n }\n return chunks;\n}\n","// Label 309 v1 error-code catalogue — single source of truth for the\n// structural-validator codes (Part A) and the verifier-layer codes (Part B)\n// that downstream verifiers re-export from this package.\n//\n// The structural validator emits ONLY Part A codes. Part B codes are\n// re-exported so consumers can `import { ErrorCode } from '@cardanowall/poe-standard'`\n// and dispatch on a single union type without round-tripping through the\n// verifier package.\n//\n// Codes are SCREAMING_SNAKE_CASE and MUST match the canonical taxonomy\n// byte-exact across the TS/PY/RS implementations — no lowercase synonyms,\n// no `schema_*`-prefixed parser-internal codes.\n\n// =============================================================================\n// Part A — structural validator codes\n// =============================================================================\nexport const STRUCTURAL_ERROR_CODES = [\n // CBOR decode layer. A single code covers every canonical-decode failure —\n // malformed/truncated bytes, indefinite-length encodings, non-canonical\n // (unsorted) map-key ordering, duplicate map keys, non-minimal integers, and\n // invalid UTF-8 — by design (no separate duplicate-key code).\n 'MALFORMED_CBOR',\n // Generic schema-layer\n 'SCHEMA_TYPE_MISMATCH',\n 'SCHEMA_MISSING_REQUIRED',\n 'SCHEMA_UNKNOWN_FIELD',\n 'SCHEMA_INVALID_LITERAL',\n 'SCHEMA_EMPTY_RECORD',\n // Hash-map\n 'HASH_DIGEST_LENGTH_MISMATCH',\n 'UNSUPPORTED_HASH_ALG',\n // Top-level `merkle[]`\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n // URI / chunking. A chunk whose bytes do not reconstruct to valid UTF-8\n // surfaces as MALFORMED_CBOR at decode (cbor2 rejects invalid-UTF-8 tstr)\n // or, in the residual reconstruct guard, as INVALID_URI — there is no\n // separate codepoint-split code.\n 'INVALID_URI',\n 'CHUNK_TOO_LARGE',\n // Encryption envelope\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n 'UNSUPPORTED_AEAD_ALG',\n 'NONCE_LENGTH_MISMATCH',\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n 'ENC_SLOTS_EMPTY',\n 'ENC_SLOT_INVALID_SHAPE',\n 'UNSUPPORTED_KEM_ALG',\n 'ENC_KEM_REQUIRED',\n 'KEM_EPK_LENGTH_MISMATCH',\n 'KEM_CT_LENGTH_MISMATCH',\n 'WRAP_LENGTH_MISMATCH',\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n 'ENC_SLOTS_MAC_REQUIRED',\n 'ENC_SLOTS_REQUIRED',\n 'ENC_EXCLUSIVITY_VIOLATION',\n 'ENC_NO_KEY_PATH',\n 'ENC_REQUIRES_CONTENT_HASH',\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n 'ENC_PASSPHRASE_SALT_TOO_SHORT',\n 'ENC_PASSPHRASE_SALT_TOO_LONG',\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n 'ENC_PASSPHRASE_PARAMS_EXCEED_POLICY',\n // Signatures\n 'MALFORMED_SIG_COSE_SIGN1',\n 'SIGNATURE_UNSUPPORTED',\n 'SIG_ENTRY_INVALID_SHAPE',\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n 'SIG_PRIVATE_KEY_LEAKED',\n // Supersedence\n 'SUPERSEDES_TX_INVALID_LENGTH',\n // Forward-compat critical extensions\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n 'CRIT_SHAPE_INVALID',\n] as const;\n\n// =============================================================================\n// Part B — verifier-layer codes\n// Re-exported so downstream verifiers can dispatch on a single union.\n// The structural validator NEVER emits these.\n// =============================================================================\nexport const VERIFIER_ERROR_CODES = [\n 'METADATA_NOT_FOUND',\n 'INSUFFICIENT_CONFIRMATIONS',\n 'SIGNATURE_INVALID',\n 'SIGNER_KEY_UNRESOLVED',\n 'WALLET_ADDRESS_MISMATCH',\n 'URI_TARGET_FORBIDDEN',\n 'URI_INTEGRITY_MISMATCH',\n 'URI_FETCH_FAILED',\n 'CONTENT_UNAVAILABLE',\n 'CIPHERTEXT_UNAVAILABLE',\n 'PROVIDER_UNAVAILABLE',\n 'SERVICE_INDEPENDENCE_VIOLATION',\n 'WRONG_DECRYPTION_INPUT_SHAPE',\n 'WRONG_RECIPIENT_KEY',\n 'TAMPERED_HEADER',\n 'TAMPERED_CIPHERTEXT',\n 'KDF_DERIVATION_FAILED',\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'MERKLE_ROOT_MISMATCH',\n 'MERKLE_LEAVES_UNAVAILABLE',\n 'MERKLE_LEAVES_INFORMATIVE_FORM',\n 'MERKLE_UNSUPPORTED',\n 'OUT_OF_PROFILE_SKIPPED',\n] as const;\n\nexport const ERROR_CODES = [...STRUCTURAL_ERROR_CODES, ...VERIFIER_ERROR_CODES] as const;\n\nexport type StructuralErrorCode = (typeof STRUCTURAL_ERROR_CODES)[number];\nexport type VerifierErrorCode = (typeof VERIFIER_ERROR_CODES)[number];\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n// Severity classification. Codes not listed are `error` by default.\n//\n// `info` — a deliberate non-check (algorithm out of profile, unrecognised\n// signature algorithm at the opt-in informational tier).\n//\n// `warning` — a non-fatal anomaly that occurred at runtime but did not\n// invalidate the record (e.g. a transient gateway failure, partial leaves\n// availability).\n//\n// `MERKLE_UNSUPPORTED` / `OUT_OF_PROFILE_SKIPPED` carry dual severity\n// (`info` when another commitment was validated; `error` for the\n// merkle-only / strict-mode case). The verifier emits the resolved severity\n// per-issue; this map records the default `info` reading.\nexport type Severity = 'error' | 'warning' | 'info';\n\nexport const SEVERITY: Readonly<Record<ErrorCode, Severity>> = Object.freeze({\n // --- Part A ---\n MALFORMED_CBOR: 'error',\n SCHEMA_TYPE_MISMATCH: 'error',\n SCHEMA_MISSING_REQUIRED: 'error',\n SCHEMA_UNKNOWN_FIELD: 'error',\n SCHEMA_INVALID_LITERAL: 'error',\n SCHEMA_EMPTY_RECORD: 'error',\n HASH_DIGEST_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_HASH_ALG: 'error',\n UNSUPPORTED_MERKLE_COMMIT_ALG: 'error',\n INVALID_URI: 'error',\n CHUNK_TOO_LARGE: 'error',\n UNAUTHENTICATED_CIPHER_FORBIDDEN: 'error',\n UNSUPPORTED_AEAD_ALG: 'error',\n NONCE_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_ENVELOPE_SCHEME: 'error',\n ENC_SLOTS_EMPTY: 'error',\n ENC_SLOT_INVALID_SHAPE: 'error',\n UNSUPPORTED_KEM_ALG: 'error',\n ENC_KEM_REQUIRED: 'error',\n KEM_EPK_LENGTH_MISMATCH: 'error',\n KEM_CT_LENGTH_MISMATCH: 'error',\n WRAP_LENGTH_MISMATCH: 'error',\n ENC_SLOTS_MAC_INVALID_LENGTH: 'error',\n ENC_SLOTS_MAC_REQUIRED: 'error',\n ENC_SLOTS_REQUIRED: 'error',\n ENC_EXCLUSIVITY_VIOLATION: 'error',\n ENC_NO_KEY_PATH: 'error',\n ENC_REQUIRES_CONTENT_HASH: 'error',\n ENC_PASSPHRASE_ALG_UNSUPPORTED: 'error',\n ENC_PASSPHRASE_SALT_TOO_SHORT: 'error',\n ENC_PASSPHRASE_SALT_TOO_LONG: 'error',\n ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW: 'error',\n ENC_PASSPHRASE_PARAMS_EXCEED_POLICY: 'error',\n MALFORMED_SIG_COSE_SIGN1: 'error',\n SIGNATURE_UNSUPPORTED: 'info',\n SIG_ENTRY_INVALID_SHAPE: 'error',\n SIG_ENTRY_KID_COSE_KEY_CONFLICT: 'error',\n SIG_PRIVATE_KEY_LEAKED: 'error',\n SUPERSEDES_TX_INVALID_LENGTH: 'error',\n EXTENSION_UNSUPPORTED_CRITICAL: 'error',\n CRIT_SHAPE_INVALID: 'error',\n // --- Part B ---\n METADATA_NOT_FOUND: 'error',\n INSUFFICIENT_CONFIRMATIONS: 'info',\n SIGNATURE_INVALID: 'error',\n SIGNER_KEY_UNRESOLVED: 'error',\n WALLET_ADDRESS_MISMATCH: 'error',\n URI_TARGET_FORBIDDEN: 'error',\n URI_INTEGRITY_MISMATCH: 'error',\n URI_FETCH_FAILED: 'warning',\n CONTENT_UNAVAILABLE: 'error',\n CIPHERTEXT_UNAVAILABLE: 'error',\n PROVIDER_UNAVAILABLE: 'error',\n SERVICE_INDEPENDENCE_VIOLATION: 'error',\n WRONG_DECRYPTION_INPUT_SHAPE: 'error',\n WRONG_RECIPIENT_KEY: 'error',\n TAMPERED_HEADER: 'error',\n TAMPERED_CIPHERTEXT: 'error',\n KDF_DERIVATION_FAILED: 'error',\n SCHEMA_MERKLE_LEAF_COUNT_MISMATCH: 'error',\n SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED: 'error',\n SCHEMA_MERKLE_LEAVES_MALFORMED: 'error',\n MERKLE_ROOT_MISMATCH: 'error',\n MERKLE_LEAVES_UNAVAILABLE: 'warning',\n MERKLE_LEAVES_INFORMATIVE_FORM: 'info',\n // Dual-severity — default reading is `info`; the verifier promotes to\n // `error` for merkle-only records (no `items[]` content claim was\n // validated in the same record).\n MERKLE_UNSUPPORTED: 'info',\n // Dual-severity — default reading is `info` (render mode); strict\n // end-to-end verifiers promote to `error`.\n OUT_OF_PROFILE_SKIPPED: 'info',\n});\n\nexport function severityOf(code: ErrorCode): Severity {\n return SEVERITY[code];\n}\n","// Label 309 v1 structural validator (the Part A structural-validation role).\n//\n// Pure function over CBOR bytes — performs no I/O, opens no socket, decodes\n// no ciphertext. Cryptographic signature verification, chain resolution, URI\n// fetching, decryption, and confirmation-depth checks are the verifier's\n// concern (the Part B verifier role) and live in `@cardanowall/sdk-ts`.\n//\n// Pipeline:\n// Step 1 Resource boundary — n/a here (validator has no fixed cap;\n// transactions are bounded by maxTxSize\n// enforced at submission)\n// Step 2 Canonical CBOR decode — `decodeCanonicalCbor` from crypto-core\n// surfaces malformed / non-canonical /\n// duplicate-key inputs as typed errors.\n// Step 3 Schema parse — Zod schema in `./schema.ts`; the mapper\n// below lifts each Zod issue to a\n// SCREAMING_SNAKE structural code.\n// Step 4 Domain checks — cross-field rules, registry membership,\n// URI reconstruction + per-scheme shape\n// (the IPFS CID profile), `enc`\n// cross-field invariants, `sigs[i]`\n// closed-map check + COSE_Sign1 structural\n// decode (path-1/path-2 mutual exclusion,\n// `SIG_PRIVATE_KEY_LEAKED` guard).\n// Step 5 Result emission — `{ ok: true, record, info?, warnings? }`\n// or `{ ok: false, issues }`.\n//\n// The validator NEVER throws — failure paths route through the discriminated\n// `ValidateResult` union so callers handle errors as data.\n\nimport { z } from 'zod';\n\nimport { decodeCanonicalCbor } from '@cardanowall/crypto-core/cbor';\nimport { CoseVerifyError, decodeCoseSign1 } from '@cardanowall/crypto-core/cose';\n\nimport { bytesChunkArrayConcat, reconstructChunkedUri } from './chunked';\nimport { SEVERITY, type ErrorCode, type Severity } from './error-codes';\nimport {\n EncryptionEnvelopeSchema,\n isExtensionKey,\n PoeRecordSchema,\n TOP_LEVEL_BASE_KEYS,\n type ItemEntry,\n type MerkleCommit,\n type PoeRecord,\n type SigEntry,\n type Slot,\n} from './schema';\n\n// =============================================================================\n// Registries\n// =============================================================================\n\n// Content-hash algorithm registry. Map value = digest length.\nconst HASH_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'sha2-256': 32,\n 'blake2b-256': 32,\n};\n\n// Merkle list-commitment algorithm registry.\nconst MERKLE_COMMIT_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'rfc9162-sha256': 32,\n};\n\n// Content AEAD registry. Value = nonce length.\nconst AEAD_NONCE_LENGTHS: Readonly<Record<string, number>> = {\n 'xchacha20-poly1305': 24,\n};\n\n// Unauthenticated-cipher family. An `enc.aead` naming any of these is rejected\n// with `UNAUTHENTICATED_CIPHER_FORBIDDEN` (not the generic `UNSUPPORTED_AEAD_ALG`)\n// so the failure names the integrity hazard. Two arms:\n// - block-cipher modes with no integrity (`cbc`, `ctr`, `ecb`, `cfb`, `ofb`)\n// appearing as a delimited token, which matches every key-size spelling\n// (`aes-cbc`, `aes-256-cbc`, `aes-128-cbc`, `des-ede3-cbc`, …);\n// - legacy stream/block ciphers as a leading token (`rc4`, `des`, `3des`).\n// The token delimiters keep the authenticated AEADs (`aes-256-gcm`,\n// `chacha20-poly1305`, `xchacha20-poly1305`) from matching. The trailing\n// boundary tolerates a single trailing `\\n` (`\\n?$`) so a forbidden cipher\n// cannot evade the denylist by appending one newline (`aes-256-cbc\\n` /\n// `rc4\\n`), matching the Python/Rust validators.\nconst UNAUTHENTICATED_CIPHER_RE =\n /(?:^|[-_])(?:cbc|ctr|ecb|cfb|ofb)(?:[-_]|\\n?$)|^(?:rc4|des|3des)(?:[-_]|\\n?$)/i;\n\n// KEM registry, expressed as a per-KEM slot DESCRIPTOR.\n//\n// Each registered KEM pins the exact recipient-slot shape:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — classical\n// ephemeral-static X25519. The per-slot `epk` is the 32-byte ephemeral\n// public key.\n// - mlkem768x25519: `{ kem_ct: <1120-byte X-Wing enc>, wrap: bstr(48) }` —\n// the X-Wing hybrid (ML-KEM-768 + X25519). The ciphertext is carried as a\n// chunked byte-string array (`kem_ct`) that MUST reassemble to exactly\n// 1120 bytes; there is NO per-slot `epk` on the hybrid path.\n//\n// A descriptor declares the slot's *ciphertext-bearing* field (`epk` for a\n// classical KEM, `kem_ct` for a hybrid) and its expected reassembled byte\n// length. `wrap` is 48 bytes for every KEM (32-byte CEK + 16-byte AEAD tag).\n// The validator branches on the descriptor's `field` to know which field MUST\n// be present and which MUST be absent, so adding a future KEM is a one-line\n// registry edit, not a new code path.\ntype KemSlotField = 'epk' | 'kem_ct';\ninterface KemSlotDescriptor {\n /** The ciphertext-bearing slot field this KEM uses. */\n readonly field: KemSlotField;\n /** Expected length of that field (reassembled length for a chunked field). */\n readonly fieldLength: number;\n /** `wrap` length — 32-byte CEK + 16-byte AEAD tag. */\n readonly wrapLength: number;\n}\nconst KEM_SLOT_DESCRIPTORS: Readonly<Record<string, KemSlotDescriptor>> = {\n x25519: { field: 'epk', fieldLength: 32, wrapLength: 48 },\n mlkem768x25519: { field: 'kem_ct', fieldLength: 1120, wrapLength: 48 },\n};\n\n// The length-mismatch code emitted when a slot's ciphertext-bearing field has\n// the wrong (reassembled) length, keyed by the descriptor's `field`.\nconst KEM_FIELD_LENGTH_CODE: Readonly<Record<KemSlotField, ErrorCode>> = {\n epk: 'KEM_EPK_LENGTH_MISMATCH',\n kem_ct: 'KEM_CT_LENGTH_MISMATCH',\n};\n\n// Passphrase KDF registry.\nconst PASSPHRASE_KDF_ALGS: ReadonlySet<string> = new Set(['argon2id']);\n\n// Signature-algorithm baseline. `-8` (EdDSA, curve-agnostic — pinned to\n// Ed25519) is the mandatory baseline; `-19` (Ed25519 fully-specified) is\n// optional and verified identically under the Ed25519 primitive when\n// accepted. The reference validator accepts both; anything else surfaces as\n// `SIGNATURE_UNSUPPORTED` (info-severity).\nconst KNOWN_SIG_ALG_IDS: ReadonlySet<number> = new Set([-8, -19]);\n\n// =============================================================================\n// Result types\n// =============================================================================\n\nexport interface ValidationIssue {\n readonly code: ErrorCode;\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n readonly severity: Severity;\n}\n\nexport type ValidateResult =\n | {\n readonly ok: true;\n readonly record: PoeRecord;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n }\n | { readonly ok: false; readonly issues: ReadonlyArray<ValidationIssue> };\n\n// =============================================================================\n// Public entry point\n// =============================================================================\n\nexport function validatePoeRecord(bytes: Uint8Array): ValidateResult {\n // Step 2 — canonical CBOR decode. Every decode failure surfaces as the single\n // MALFORMED_CBOR code: malformed/truncated bytes, indefinite-length\n // (streaming) encodings, non-canonical map-key ordering, duplicate map keys,\n // non-minimal integers, and invalid UTF-8. The taxonomy has no finer-grained\n // CBOR-decode codes — the validator catches all of these at decode and\n // reports one error.\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytes);\n } catch (cause) {\n return {\n ok: false,\n issues: [\n {\n code: 'MALFORMED_CBOR',\n path: [],\n message: cause instanceof Error ? cause.message : String(cause),\n severity: 'error',\n },\n ],\n };\n }\n\n // Step 3 — schema parse\n const parse = PoeRecordSchema.safeParse(decoded);\n if (!parse.success) {\n const issues = parse.error.issues\n .map((issue) => mapZodIssue(issue, decoded))\n .sort(compareIssuePath);\n return { ok: false, issues };\n }\n\n // Step 4 — domain checks\n const record = parse.data;\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n const info: ValidationIssue[] = [];\n\n // 4a — content-commitment rule (`SCHEMA_EMPTY_RECORD`).\n const itemsLen = Array.isArray(record.items) ? record.items.length : 0;\n const merkleLen = Array.isArray(record.merkle) ? record.merkle.length : 0;\n if (itemsLen === 0 && merkleLen === 0) {\n errors.push(\n issue(\n 'SCHEMA_EMPTY_RECORD',\n [],\n 'record must carry at least one of items[] or merkle[] non-empty',\n ),\n );\n }\n\n // `crit[]` shape rules. Runs BEFORE the per-entry\n // `EXTENSION_UNSUPPORTED_CRITICAL` check.\n const decodedTopKeys = topLevelKeysOf(decoded);\n const critShapeInvalidIndices = checkCritShape(record, decodedTopKeys, errors);\n\n // Unknown top-level fields (typos like `supersedess`, `Sigs` that fall\n // outside both the base set and the extension-key namespaces).\n for (const k of decodedTopKeys) {\n if (TOP_LEVEL_BASE_KEYS.has(k)) continue;\n if (isExtensionKey(k)) continue;\n errors.push(issue('SCHEMA_UNKNOWN_FIELD', [k], `unknown top-level field: ${k}`));\n }\n\n // `EXTENSION_UNSUPPORTED_CRITICAL`: v1 reference validator implements no\n // extension keys, so every shape-valid `crit` entry is unsupported.\n if (Array.isArray(record.crit)) {\n for (let i = 0; i < record.crit.length; i++) {\n if (critShapeInvalidIndices.has(i)) continue;\n const critName = record.crit[i]!;\n errors.push(\n issue(\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n ['crit', i],\n `crit lists extension '${critName}' that this validator does not implement`,\n ),\n );\n }\n }\n\n // 4b – 4e — per-item walk.\n for (let i = 0; i < (record.items ?? []).length; i++) {\n const item = record.items![i]!;\n checkItemHashes(item, i, errors);\n if (item.uris) checkItemUris(item.uris, ['items', i, 'uris'], errors);\n if (item.enc !== undefined) checkItemEnc(item, i, errors);\n }\n\n // 4i — top-level `merkle[]` walk.\n for (let i = 0; i < (record.merkle ?? []).length; i++) {\n const commit = record.merkle![i]!;\n checkMerkleCommit(commit, i, errors);\n }\n\n // 4h — supersedes length is enforced by the schema-layer refinement; this\n // step adds no further check.\n\n // 4f + 4g — `sigs[i]` closed map shape + COSE_Sign1 structural decode.\n if (record.sigs) {\n for (let i = 0; i < record.sigs.length; i++) {\n checkSigEntry(record.sigs[i]!, i, errors, info);\n }\n }\n\n // Step 5 — result emission. `info`-severity entries do NOT fail the record;\n // `warning`-severity entries (none among the structural codes) also remain\n // non-fatal.\n if (errors.length > 0) {\n return { ok: false, issues: errors.sort(compareIssuePath) };\n }\n const result: {\n ok: true;\n record: PoeRecord;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = {\n ok: true,\n record,\n };\n if (warnings.length > 0) result.warnings = warnings.sort(compareIssuePath);\n if (info.length > 0) result.info = info.sort(compareIssuePath);\n return result;\n}\n\n// =============================================================================\n// Step 3 helpers — Zod issue → structural-code mapping\n// =============================================================================\n\nfunction mapZodIssue(zissue: z.core.$ZodIssue, decoded?: unknown): ValidationIssue {\n const path = zissue.path as ReadonlyArray<string | number>;\n // Refinements with an explicit `params.code` win unconditionally — they\n // are the canonical taxonomy code attached at schema-definition time.\n const explicit = (zissue as { params?: { code?: string } }).params?.code as ErrorCode | undefined;\n if (explicit !== undefined) {\n return issue(explicit, path, zissue.message);\n }\n\n // Path-based dispatch:\n // `sigs[i].*` → `SIG_ENTRY_INVALID_SHAPE` (the sig-entry closed-map rule)\n // `items[i].enc.slots[j].(epk|wrap)` → `ENC_SLOT_INVALID_SHAPE`\n // (structurally malformed slots)\n // `v` literal mismatch / missing → `SCHEMA_INVALID_LITERAL` vs\n // `SCHEMA_MISSING_REQUIRED`.\n const inSigsEntry = path.length >= 2 && path[0] === 'sigs' && typeof path[1] === 'number';\n\n // Match either the absolute path (`items[i].enc.slots[j]…`) or the\n // relative-to-`enc` path (`slots[j]…`) — the latter is what\n // `EncryptionEnvelopeSchema.safeParse(item.enc)` emits before\n // `checkItemEnc` prefixes the `items[i].enc.` segment.\n //\n // The match includes the whole slot ELEMENT (path ending at `slots[j]`, no\n // trailing field) as well as a field WITHIN a slot (`slots[j].epk`). A\n // wrong-typed slot (`slots: [[1, 2]]` → array instead of `{epk, wrap}`) and\n // a slot carrying an extra key both classify as `ENC_SLOT_INVALID_SHAPE`,\n // matching the spec's \"a slot is not a 2-key map {epk, wrap}\".\n const isInSlotEntry = (() => {\n if (\n path.length >= 5 &&\n path[0] === 'items' &&\n typeof path[1] === 'number' &&\n path[2] === 'enc' &&\n path[3] === 'slots' &&\n typeof path[4] === 'number'\n ) {\n return true;\n }\n if (path.length >= 2 && path[0] === 'slots' && typeof path[1] === 'number') {\n return true;\n }\n return false;\n })();\n\n const valueAtIssue = valueAtPath(decoded, path);\n const isMissing = valueAtIssue === undefined;\n\n switch (zissue.code) {\n case 'invalid_type':\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (isMissing) {\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_MISSING_REQUIRED', path, zissue.message);\n }\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_value':\n // Zod 4's `z.literal(1)` emits `invalid_value` for both a missing field\n // AND a present-but-wrong value. Disambiguate via the runtime value:\n // missing → `SCHEMA_MISSING_REQUIRED`; present-but-wrong → `SCHEMA_INVALID_LITERAL`.\n if (path.length === 1 && path[0] === 'v') {\n return issue(\n isMissing ? 'SCHEMA_MISSING_REQUIRED' : 'SCHEMA_INVALID_LITERAL',\n path,\n zissue.message,\n );\n }\n return issue('SCHEMA_INVALID_LITERAL', path, zissue.message);\n case 'unrecognized_keys':\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_UNKNOWN_FIELD', path, zissue.message);\n case 'invalid_format':\n case 'too_big':\n case 'too_small':\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_union':\n case 'invalid_key':\n case 'invalid_element':\n case 'custom':\n default:\n if (isInSlotEntry) return issue('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issue('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issue('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n }\n}\n\n// =============================================================================\n// Step 4 helpers — domain checks\n// =============================================================================\n\n// 4b — hash-map registry membership + digest length per algorithm.\nfunction checkItemHashes(item: ItemEntry, idx: number, errors: ValidationIssue[]): void {\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) {\n errors.push(\n issue(\n 'SCHEMA_TYPE_MISMATCH',\n ['items', idx, 'hashes'],\n 'hashes must be a non-empty CBOR map of <alg-id> -> <digest>',\n ),\n );\n return;\n }\n for (const [alg, digest] of entries) {\n if (!(alg in HASH_ALG_LENGTHS)) {\n errors.push(\n issue('UNSUPPORTED_HASH_ALG', ['items', idx, 'hashes', alg], `unknown hash alg: ${alg}`),\n );\n continue;\n }\n const expected = HASH_ALG_LENGTHS[alg]!;\n if (digest.length !== expected) {\n errors.push(\n issue(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n ['items', idx, 'hashes', alg],\n `hashes['${alg}'] digest length ${digest.length} != ${expected}`,\n ),\n );\n }\n }\n}\n\n// 4c — URI chunk reconstruction + per-scheme shape.\nfunction checkItemUris(\n uris: ReadonlyArray<ReadonlyArray<string>>,\n basePath: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n uris.forEach((chunks, ui) => validateOneUri(chunks, [...basePath, ui], errors));\n}\n\nfunction validateOneUri(\n chunks: ReadonlyArray<string>,\n path: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n const reconstructed = reconstructChunkedUri(chunks);\n if (!reconstructed.ok) {\n errors.push(issue(reconstructed.code, path, reconstructed.reason));\n return;\n }\n const uri = reconstructed.uri;\n\n // Absolute URI, no fragment, scheme in `{ar://, ipfs://}`.\n if (uri.includes('#')) {\n errors.push(\n issue('INVALID_URI', path, \"URI contains a fragment identifier ('#'), which is forbidden\"),\n );\n return;\n }\n const sepIdx = uri.indexOf('://');\n if (sepIdx <= 0 || !/^[a-z][a-z0-9+.-]*$/i.test(uri.slice(0, sepIdx))) {\n errors.push(\n issue('INVALID_URI', path, 'URI is not absolute (missing scheme://hierarchical-part)'),\n );\n return;\n }\n // RFC 3986 §3.1: the scheme is case-insensitive, so case-fold the SCHEME ONLY,\n // then ALWAYS validate the body. The host / CID / txid is NOT case-folded — a\n // base64url Arweave txid and a base58btc CID are case-significant. An\n // uppercase scheme (`AR://`, `IPFS://`) is accepted iff its body passes the\n // same per-scheme shape check a lowercase scheme would.\n const scheme = uri.slice(0, sepIdx).toLowerCase();\n const rest = uri.slice(sepIdx + '://'.length);\n if (scheme === 'ar') {\n if (!/^ar:\\/\\/[A-Za-z0-9_-]{43}$/.test('ar://' + rest)) {\n errors.push(\n issue(\n 'INVALID_URI',\n path,\n 'ar:// URI does not match `^ar://[A-Za-z0-9_-]{43}$` (43-char base64url txid, no path/query/fragment)',\n ),\n );\n }\n return;\n }\n if (scheme === 'ipfs') {\n // The structural validator does a full CID parse (not just a prefix check).\n const slashIdx = rest.indexOf('/');\n const cid = slashIdx === -1 ? rest : rest.slice(0, slashIdx);\n if (!validateCidProfile(cid)) {\n errors.push(\n issue('INVALID_URI', path, 'ipfs:// URI is not a valid CID under the Label 309 profile'),\n );\n }\n return;\n }\n // Scheme not in `{ar://, ipfs://}`.\n errors.push(\n issue('INVALID_URI', path, 'unsupported URI scheme; v1 PoE URI set is {ar://, ipfs://}'),\n );\n}\n\n// 4d — encryption envelope.\nfunction checkItemEnc(item: ItemEntry, idx: number, errors: ValidationIssue[]): void {\n // Pre-check: an `enc`-bearing item MUST commit to a content hash. The claim\n // is the *plaintext* digest, so the hashes map MUST carry at least one\n // registered content-hash entry (sha2-256 / blake2b-256). This is a PRESENCE\n // check, not merely a non-empty check: a `hashes` map that exists but carries\n // only a non-content algorithm (e.g. `{md5}`) still fails — there is no\n // content digest to bind the ciphertext to. The empty-map case is also caught\n // here (and additionally fails the CDDL `1*` cardinality in checkItemHashes).\n const hasContentHash = Object.keys(item.hashes).some((alg) => alg in HASH_ALG_LENGTHS);\n if (!hasContentHash) {\n errors.push(\n issue(\n 'ENC_REQUIRES_CONTENT_HASH',\n ['items', idx, 'enc'],\n 'item carries `enc` but `hashes` has no content-hash entry (sha2-256 or blake2b-256)',\n ),\n );\n return;\n }\n\n // Schema-parse the envelope independently so we can lift its issues with\n // the correct path prefix.\n const encParse = EncryptionEnvelopeSchema.safeParse(item.enc);\n if (!encParse.success) {\n for (const zissue of encParse.error.issues) {\n const mapped = mapZodIssue(zissue, item.enc);\n errors.push({\n ...mapped,\n path: ['items', idx, 'enc', ...mapped.path],\n });\n }\n return;\n }\n const enc = encParse.data;\n const basePath: ReadonlyArray<string | number> = ['items', idx, 'enc'];\n\n // `enc.scheme` MUST be the unsigned integer 1.\n if (typeof enc.scheme !== 'number' || !Number.isInteger(enc.scheme) || enc.scheme !== 1) {\n errors.push(\n issue(\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n [...basePath, 'scheme'],\n `enc.scheme must be the unsigned integer 1; got ${String(enc.scheme)}`,\n ),\n );\n // Continue — other checks remain informative.\n }\n\n // AEAD checks (forbidden cipher first, then registry). The forbidden set is\n // the unauthenticated-cipher family — block-cipher modes that provide no\n // integrity (CBC, CTR, ECB, CFB, OFB) in any key-size spelling\n // (`aes-256-cbc`, `aes-128-cbc`, OpenSSL/JCA form) plus the legacy stream\n // ciphers (RC4, DES/3DES). Matching this family — rather than a generic\n // \"unknown alg\" fall-through to `UNSUPPORTED_AEAD_ALG` — names the security\n // hazard precisely: the record selected an authenticated-encryption-absent\n // cipher, not merely an unregistered one.\n if (UNAUTHENTICATED_CIPHER_RE.test(enc.aead)) {\n errors.push(\n issue(\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n [...basePath, 'aead'],\n `'${enc.aead}' is an unauthenticated cipher; Label 309 mandates an authenticated (AEAD) cipher`,\n ),\n );\n return; // unrecoverable — nonce / kem / slot checks become noise\n }\n if (!(enc.aead in AEAD_NONCE_LENGTHS)) {\n errors.push(\n issue('UNSUPPORTED_AEAD_ALG', [...basePath, 'aead'], `unknown aead alg: ${enc.aead}`),\n );\n return;\n }\n const expectedNonceLen = AEAD_NONCE_LENGTHS[enc.aead]!;\n if (enc.nonce.length !== expectedNonceLen) {\n errors.push(\n issue(\n 'NONCE_LENGTH_MISMATCH',\n [...basePath, 'nonce'],\n `nonce length ${enc.nonce.length} != ${expectedNonceLen} for ${enc.aead}`,\n ),\n );\n }\n\n // Envelope-level KEM check (when present).\n if (enc.kem !== undefined && !(enc.kem in KEM_SLOT_DESCRIPTORS)) {\n errors.push(issue('UNSUPPORTED_KEM_ALG', [...basePath, 'kem'], `unknown kem alg: ${enc.kem}`));\n }\n\n // Key-path branching.\n const hasSlots = enc.slots !== undefined;\n const hasSlotsMac = enc.slots_mac !== undefined;\n const hasPassphrase = enc.passphrase !== undefined;\n\n if (hasSlots && hasPassphrase) {\n errors.push(\n issue('ENC_EXCLUSIVITY_VIOLATION', basePath, 'enc combines slots with passphrase; pick one'),\n );\n }\n if (hasSlots && !hasSlotsMac) {\n errors.push(\n issue('ENC_SLOTS_MAC_REQUIRED', basePath, 'enc.slots present but enc.slots_mac absent'),\n );\n }\n if (hasSlotsMac && !hasSlots) {\n errors.push(\n issue('ENC_SLOTS_REQUIRED', basePath, 'enc.slots_mac present but enc.slots absent'),\n );\n }\n if (hasSlots && enc.kem === undefined) {\n errors.push(issue('ENC_KEM_REQUIRED', basePath, 'enc.slots present but enc.kem absent'));\n }\n if (!hasSlots && !hasPassphrase) {\n errors.push(\n issue(\n 'ENC_NO_KEY_PATH',\n basePath,\n 'enc requires either slots or passphrase — no on-chain key path otherwise',\n ),\n );\n }\n\n // Slots shape checks. The slot shape is KEM-driven: the descriptor for the\n // declared `kem` pins which ciphertext-bearing field (`epk` for x25519,\n // `kem_ct` for mlkem768x25519) MUST be present and at what length, and\n // forbids the other KEM's field. Because the schema is permissive (no\n // `.strict()`), this domain pass is the ONLY thing rejecting cross-KEM\n // contamination — an x25519 slot carrying a stray `kem_ct`, or a hybrid slot\n // carrying a stray `epk`, surfaces as `ENC_SLOT_INVALID_SHAPE`.\n if (hasSlots) {\n if (enc.slots!.length < 1) {\n errors.push(\n issue('ENC_SLOTS_EMPTY', [...basePath, 'slots'], `slots length ${enc.slots!.length} < 1`),\n );\n }\n // Only validate slot shape when the KEM is known; an unknown / absent KEM\n // already emits its own code above, and we cannot pick a descriptor.\n const descriptor = enc.kem !== undefined ? KEM_SLOT_DESCRIPTORS[enc.kem] : undefined;\n if (descriptor !== undefined) {\n // The permissive `SlotSchema` strips unknown keys before they reach the\n // parsed slot, so the closed-map invariant (\"a slot is exactly {<ct\n // field>, wrap}\") is enforced against the RAW decoded slot key set here.\n const rawSlotKeys = rawSlotKeySets(item.enc);\n enc.slots!.forEach((slot, si) => {\n checkSlotShape(\n slot,\n rawSlotKeys[si] ?? new Set<string>(),\n descriptor,\n enc.kem!,\n [...basePath, 'slots', si],\n errors,\n );\n });\n }\n }\n\n // Passphrase block checks (registry membership + Argon2id closed-params + floor).\n if (hasPassphrase) {\n const pp = enc.passphrase!;\n const ppPath: ReadonlyArray<string | number> = [...basePath, 'passphrase'];\n if (!PASSPHRASE_KDF_ALGS.has(pp.alg)) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n [...ppPath, 'alg'],\n `unknown passphrase kdf alg: ${pp.alg}`,\n ),\n );\n return; // can't apply alg-specific params check\n }\n if (pp.alg === 'argon2id') {\n const allowed = new Set(['m', 't', 'p']);\n for (const k of Object.keys(pp.params)) {\n if (!allowed.has(k)) {\n errors.push(\n issue(\n 'SCHEMA_UNKNOWN_FIELD',\n [...ppPath, 'params', k],\n `unknown argon2id params field: ${k}`,\n ),\n );\n }\n }\n const p = pp.params as { m?: unknown; t?: unknown; p?: unknown };\n const argonInt = (val: unknown, name: 'm' | 't' | 'p'): number | null => {\n if (typeof val !== 'number' || !Number.isInteger(val)) {\n errors.push(\n issue(\n 'SCHEMA_TYPE_MISMATCH',\n [...ppPath, 'params', name],\n `argon2id params.${name} must be a CBOR unsigned integer`,\n ),\n );\n return null;\n }\n return val;\n };\n const mVal = argonInt(p.m, 'm');\n const tVal = argonInt(p.t, 't');\n const pVal = argonInt(p.p, 'p');\n if (mVal !== null && mVal < 65_536) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 'm'],\n 'argon2id requires m >= 65536 KiB',\n ),\n );\n }\n if (tVal !== null && tVal < 3) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 't'],\n 'argon2id requires t >= 3',\n ),\n );\n }\n if (pVal !== null && pVal < 1) {\n errors.push(\n issue(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...ppPath, 'params', 'p'],\n 'argon2id requires p >= 1',\n ),\n );\n }\n }\n }\n}\n\n// KEM-driven per-slot shape gate (pure). Branches on the descriptor for the\n// declared envelope `kem`:\n//\n// - The descriptor's ciphertext-bearing field (`epk` for x25519, `kem_ct`\n// for mlkem768x25519) MUST be present at the expected (reassembled) length.\n// - The OTHER KEM's ciphertext field MUST be absent — its presence is\n// cross-KEM contamination and surfaces as `ENC_SLOT_INVALID_SHAPE` (the\n// hole that dropping `.strict()` on `SlotSchema` would otherwise open).\n// - `wrap` MUST be present at 48 bytes.\n//\n// This stays a pure function over already-decoded values: `kem_ct` reassembly\n// uses `bytesChunkArrayConcat` (byte concatenation only) — no crypto, no I/O.\n//\n// `rawKeys` is the slot's key set as it appeared on the wire (before the\n// permissive schema stripped unknowns); any key outside {<ct field>, wrap}\n// for this KEM is a closed-map violation.\nconst SLOT_KEY_UNIVERSE: ReadonlySet<string> = new Set(['epk', 'kem_ct', 'wrap']);\n\nfunction checkSlotShape(\n slot: Slot,\n rawKeys: ReadonlySet<string>,\n descriptor: KemSlotDescriptor,\n kem: string,\n slotPath: ReadonlyArray<string | number>,\n errors: ValidationIssue[],\n): void {\n // The ciphertext field that does NOT belong to this KEM. Its presence is a\n // shape violation regardless of length. Drive this off the RAW key set so a\n // future schema change cannot silently drop the foreign field before we see\n // it.\n const foreignField: KemSlotField = descriptor.field === 'epk' ? 'kem_ct' : 'epk';\n if (rawKeys.has(foreignField)) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, foreignField],\n `slot carries '${foreignField}' but kem='${kem}' expects '${descriptor.field}'`,\n ),\n );\n }\n\n // Any key outside the slot universe is a closed-map violation (the schema is\n // permissive and would otherwise strip it silently).\n for (const k of rawKeys) {\n if (!SLOT_KEY_UNIVERSE.has(k)) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, k],\n `slot carries unexpected key '${k}'; a slot is a 2-key map {${descriptor.field}, wrap}`,\n ),\n );\n }\n }\n\n // The required ciphertext-bearing field MUST be present at the expected\n // (reassembled) length.\n if (descriptor.field === 'epk') {\n if (slot.epk === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'epk'],\n `slot for kem='${kem}' is missing required 'epk'`,\n ),\n );\n } else if (slot.epk.length !== descriptor.fieldLength) {\n errors.push(\n issue(\n KEM_FIELD_LENGTH_CODE.epk,\n [...slotPath, 'epk'],\n `slot.epk length ${slot.epk.length} != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n } else {\n if (slot.kem_ct === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'kem_ct'],\n `slot for kem='${kem}' is missing required 'kem_ct'`,\n ),\n );\n } else {\n const reassembled = bytesChunkArrayConcat(slot.kem_ct).length;\n if (reassembled !== descriptor.fieldLength) {\n errors.push(\n issue(\n KEM_FIELD_LENGTH_CODE.kem_ct,\n [...slotPath, 'kem_ct'],\n `slot.kem_ct reassembles to ${reassembled} bytes != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n }\n }\n\n // `wrap` is 48 bytes for every KEM.\n if (slot.wrap === undefined) {\n errors.push(\n issue(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'wrap'],\n `slot for kem='${kem}' is missing required 'wrap'`,\n ),\n );\n } else if (slot.wrap.length !== descriptor.wrapLength) {\n errors.push(\n issue(\n 'WRAP_LENGTH_MISMATCH',\n [...slotPath, 'wrap'],\n `slot.wrap length ${slot.wrap.length} != ${descriptor.wrapLength}`,\n ),\n );\n }\n}\n\n// Extract the per-slot RAW key sets from a decoded `enc` value, BEFORE the\n// permissive schema strips unknown slot keys. cbor2 surfaces a CBOR map either\n// as a `Map` (int/heterogeneous keys) or a plain object (text keys); slot maps\n// are text-keyed, so this reads string keys from whichever form. A slot that\n// is not a map at all yields an empty set — the slot's own type errors are\n// already emitted by the schema parse, so the shape gate simply finds no keys.\nfunction rawSlotKeySets(rawEnc: unknown): ReadonlyArray<ReadonlySet<string>> {\n const slots = mapLikeGet(rawEnc, 'slots');\n if (!Array.isArray(slots)) return [];\n return slots.map((slot) => {\n const keys = new Set<string>();\n if (slot instanceof Map) {\n for (const k of slot.keys()) if (typeof k === 'string') keys.add(k);\n } else if (typeof slot === 'object' && slot !== null) {\n for (const k of Object.keys(slot as Record<string, unknown>)) keys.add(k);\n }\n return keys;\n });\n}\n\nfunction mapLikeGet(value: unknown, key: string): unknown {\n if (value instanceof Map) return value.get(key);\n if (typeof value === 'object' && value !== null) {\n return (value as Record<string, unknown>)[key];\n }\n return undefined;\n}\n\n// 4i — `merkle[i]` walk.\nfunction checkMerkleCommit(commit: MerkleCommit, idx: number, errors: ValidationIssue[]): void {\n const basePath: ReadonlyArray<string | number> = ['merkle', idx];\n if (!(commit.alg in MERKLE_COMMIT_ALG_LENGTHS)) {\n errors.push(\n issue(\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n [...basePath, 'alg'],\n `unknown merkle commitment alg: ${commit.alg}`,\n ),\n );\n return;\n }\n const expected = MERKLE_COMMIT_ALG_LENGTHS[commit.alg]!;\n if (commit.root.length !== expected) {\n errors.push(\n issue(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n [...basePath, 'root'],\n `merkle entry root length ${commit.root.length} != ${expected} for ${commit.alg}`,\n ),\n );\n }\n if (commit.uris) {\n checkItemUris(commit.uris, [...basePath, 'uris'], errors);\n }\n}\n\n// 4f + 4g — record-level signature entries.\nfunction checkSigEntry(\n entry: SigEntry,\n idx: number,\n errors: ValidationIssue[],\n info: ValidationIssue[],\n): void {\n // Path-2 `cose_key` private-material guard runs FIRST.\n if (entry.cose_key !== undefined) {\n const keyIssue = inspectCoseKey(entry.cose_key, idx);\n if (keyIssue !== null) {\n errors.push(keyIssue);\n return;\n }\n }\n\n // 4g — COSE_Sign1 structural decode.\n const merged = bytesChunkArrayConcat(entry.cose_sign1);\n let cose: ReturnType<typeof decodeCoseSign1>;\n try {\n cose = decodeCoseSign1(merged);\n } catch (cause) {\n errors.push(\n issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n cause instanceof CoseVerifyError || cause instanceof Error ? cause.message : String(cause),\n ),\n );\n return;\n }\n\n // Detached-only payload — the COSE_Sign1 payload MUST be null.\n if (cose.payload !== null) {\n errors.push(\n issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n 'COSE_Sign1 payload must be null (detached); attached form forbidden',\n ),\n );\n return;\n }\n\n // Signature-algorithm registry check (info-severity — an unrecognised alg\n // does not fail the record).\n const alg = cose.protectedHeader.get(1);\n if (typeof alg !== 'number' || !KNOWN_SIG_ALG_IDS.has(alg)) {\n info.push(\n issue(\n 'SIGNATURE_UNSUPPORTED',\n ['sigs', idx],\n `COSE_Sign1 protected alg ${String(alg)} not in {-8, -19}`,\n ),\n );\n }\n\n // Path-1 (32-byte protected-header `kid`) and path-2 (`cose_key` sidecar)\n // are mutually exclusive — a sig entry must not carry both.\n const protectedKid = cose.protectedHeader.get(4);\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === 32 &&\n entry.cose_key !== undefined\n ) {\n errors.push(\n issue(\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n ['sigs', idx],\n 'sigs[i] carries both a 32-byte protected `kid` (path 1) and an inline `cose_key` (path 2); paths are mutually exclusive',\n ),\n );\n }\n}\n\n// =============================================================================\n// COSE_Key inspector (path-2 `sigs[i].cose_key` blob)\n// =============================================================================\n//\n// Two structural checks:\n// 5a — Private-material guard (FIRST). COSE_Key label `-4` (the private\n// scalar `d` for OKP / EC2 per RFC 9052 §7.1) → `SIG_PRIVATE_KEY_LEAKED`.\n// This check is load-bearing producer-side preflight: publishing a\n// private key on the permanent ledger is catastrophic and irreversible.\n// 5b — Positive-shape guard. The decoded `cbor<COSE_Key>` map MUST carry\n// `kty=1` (OKP), `crv=6` (Ed25519), and a 32-byte `-2` (x). Any\n// failure → `MALFORMED_SIG_COSE_SIGN1`.\n\nfunction inspectCoseKey(keyChunks: ReadonlyArray<Uint8Array>, i: number): ValidationIssue | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytesChunkArrayConcat(keyChunks));\n } catch (cause) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key failed to decode as cbor<COSE_Key>: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n\n // cbor2 surfaces int-keyed COSE_Key maps as `Map`; string-keyed maps as\n // plain JS objects (a malformed COSE_Key would carry string keys).\n const getLabel = (label: number): unknown => {\n if (decoded instanceof Map) return decoded.get(label);\n if (typeof decoded === 'object' && decoded !== null) {\n return (decoded as Record<string, unknown>)[String(label)];\n }\n return undefined;\n };\n const hasLabel = (label: number): boolean => {\n if (decoded instanceof Map) return decoded.has(label);\n if (typeof decoded === 'object' && decoded !== null) {\n return Object.prototype.hasOwnProperty.call(decoded, String(label));\n }\n return false;\n };\n\n // 5a — Private-material guard.\n if (hasLabel(-4)) {\n return issue(\n 'SIG_PRIVATE_KEY_LEAKED',\n ['sigs', i, 'cose_key'],\n 'cose_key carries COSE_Key private-key material (label -4, the OKP/EC2 private scalar d); publishing a private key on the permanent ledger is forbidden',\n );\n }\n\n // 5b — Positive-shape guard.\n const kty = getLabel(1);\n if (kty !== 1) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key kty (label 1) must be 1 (OKP); got ${String(kty)}`,\n );\n }\n const crv = getLabel(-1);\n if (crv !== 6) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key crv (label -1) must be 6 (Ed25519); got ${String(crv)}`,\n );\n }\n if (!hasLabel(-2)) {\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key missing label -2 (Ed25519 public-key bytes)`,\n );\n }\n const x = getLabel(-2);\n if (!(x instanceof Uint8Array) || x.length !== 32) {\n const got = x instanceof Uint8Array ? `${x.length}-byte bstr` : typeof x;\n return issue(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key label -2 must be a 32-byte byte string (Ed25519 public key); got ${got}`,\n );\n }\n return null;\n}\n\n// =============================================================================\n// Label 309 CID profile\n// =============================================================================\n//\n// Accept CIDv0 (`Qm` prefix, 46-char base58btc, sha2-256 multihash) and\n// CIDv1 (multibase prefix + version 0x01 + codec + multihash) per the\n// closed profile:\n// - Multibase: b, B, f, F, z\n// - Multicodec: 0x55 (raw), 0x70 (dag-pb), 0x71 (dag-cbor)\n// - Multihash: 0x12 (sha2-256, 32 B), 0xb220 (blake2b-256, 32 B)\n//\n// Returns true iff the CID conforms to the Label 309 profile.\n\nconst ACCEPTED_CIDV1_MULTIBASE: ReadonlySet<string> = new Set(['b', 'B', 'f', 'F', 'z']);\n\nconst ACCEPTED_MULTICODECS: ReadonlySet<number> = new Set([0x55, 0x70, 0x71]);\n\n// Multihash table: code → digest length (bytes).\n// `0x12` = sha2-256; `0xb220` = blake2b-256.\nconst ACCEPTED_MULTIHASHES: ReadonlyMap<number, number> = new Map([\n [0x12, 32],\n [0xb220, 32],\n]);\n\nexport function validateCidProfile(cid: string): boolean {\n if (cid.length === 0) return false;\n // CIDv0: a base58btc-encoded sha2-256 multihash. Decode the WHOLE string and\n // verify the multihash prefix (0x12 = sha2-256, 0x20 = 32-byte digest length)\n // and total length (34 bytes = 2-byte prefix + 32-byte digest). A `Qm`\n // prefix alone is not sufficient — a malformed body must be rejected.\n if (cid.startsWith('Qm')) {\n let decoded: Uint8Array;\n try {\n decoded = decodeBase58btc(cid);\n } catch {\n return false;\n }\n return decoded.length === 34 && decoded[0] === 0x12 && decoded[1] === 0x20;\n }\n // CIDv1: multibase + binary CID body.\n const mbPrefix = cid[0]!;\n if (!ACCEPTED_CIDV1_MULTIBASE.has(mbPrefix)) return false;\n let bytes: Uint8Array;\n try {\n bytes = decodeMultibase(mbPrefix, cid.slice(1));\n } catch {\n return false;\n }\n if (bytes.length < 4) return false;\n // CIDv1 layout: <version varint> <multicodec varint> <multihash>\n const versionParse = readVarint(bytes, 0);\n if (versionParse === null || versionParse.value !== 1) return false;\n const codecParse = readVarint(bytes, versionParse.next);\n if (codecParse === null) return false;\n if (!ACCEPTED_MULTICODECS.has(codecParse.value)) return false;\n const mhParse = readVarint(bytes, codecParse.next);\n if (mhParse === null) return false;\n const lenParse = readVarint(bytes, mhParse.next);\n if (lenParse === null) return false;\n const digestLen = lenParse.value;\n const expectedLen = ACCEPTED_MULTIHASHES.get(mhParse.value);\n if (expectedLen === undefined || digestLen !== expectedLen) return false;\n if (lenParse.next + digestLen !== bytes.length) return false;\n return true;\n}\n\nfunction readVarint(bytes: Uint8Array, start: number): { value: number; next: number } | null {\n let value = 0;\n let shift = 0;\n let i = start;\n while (i < bytes.length) {\n const b = bytes[i]!;\n value |= (b & 0x7f) << shift;\n i++;\n if ((b & 0x80) === 0) return { value, next: i };\n shift += 7;\n if (shift > 28) return null; // overflow guard; Label 309 profile uses ≤ 16-bit codes\n }\n return null;\n}\n\n// Multibase decoders for the closed set the CID profile admits.\nfunction decodeMultibase(prefix: string, body: string): Uint8Array {\n switch (prefix) {\n case 'b':\n return decodeBase32(body.toLowerCase(), 'rfc4648-lower');\n case 'B':\n return decodeBase32(body.toUpperCase(), 'rfc4648-upper');\n case 'f':\n return decodeBase16(body.toLowerCase());\n case 'F':\n return decodeBase16(body.toUpperCase());\n case 'z':\n return decodeBase58btc(body);\n default:\n throw new Error(`unsupported multibase prefix ${prefix}`);\n }\n}\n\nconst BASE16_LOWER = '0123456789abcdef';\nconst BASE16_UPPER = '0123456789ABCDEF';\n\nfunction decodeBase16(s: string): Uint8Array {\n if (s.length % 2 !== 0) throw new Error('base16: odd-length');\n const out = new Uint8Array(s.length / 2);\n const alphabet = s === s.toLowerCase() ? BASE16_LOWER : BASE16_UPPER;\n for (let i = 0; i < out.length; i++) {\n const hi = alphabet.indexOf(s[i * 2]!);\n const lo = alphabet.indexOf(s[i * 2 + 1]!);\n if (hi < 0 || lo < 0) throw new Error(`base16: non-hex char at ${i * 2}`);\n out[i] = (hi << 4) | lo;\n }\n return out;\n}\n\nconst BASE32_RFC4648_LOWER = 'abcdefghijklmnopqrstuvwxyz234567';\nconst BASE32_RFC4648_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\nfunction decodeBase32(s: string, variant: 'rfc4648-lower' | 'rfc4648-upper'): Uint8Array {\n const alphabet = variant === 'rfc4648-lower' ? BASE32_RFC4648_LOWER : BASE32_RFC4648_UPPER;\n // Multibase strips padding per spec; we accept either form for robustness.\n const trimmed = s.replace(/=+$/, '');\n const out: number[] = [];\n let buf = 0;\n let bits = 0;\n for (const ch of trimmed) {\n const idx = alphabet.indexOf(ch);\n if (idx < 0) throw new Error(`base32: invalid char '${ch}'`);\n buf = (buf << 5) | idx;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((buf >> bits) & 0xff);\n }\n }\n return Uint8Array.from(out);\n}\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\nfunction decodeBase58btc(s: string): Uint8Array {\n if (s.length === 0) return new Uint8Array(0);\n let zeros = 0;\n while (zeros < s.length && s[zeros] === '1') zeros++;\n const size = Math.floor(((s.length - zeros) * 733) / 1000) + 1;\n const b256 = new Uint8Array(size);\n let length = 0;\n for (let i = zeros; i < s.length; i++) {\n const ch = s[i]!;\n const carryIdx = BASE58_ALPHABET.indexOf(ch);\n if (carryIdx < 0) throw new Error(`base58: invalid char '${ch}'`);\n let carry = carryIdx;\n let k = 0;\n for (let j = size - 1; (carry !== 0 || k < length) && j >= 0; j--, k++) {\n carry += 58 * b256[j]!;\n b256[j] = carry % 256;\n carry = Math.floor(carry / 256);\n }\n length = k;\n }\n let it = size - length;\n while (it < size && b256[it] === 0) it++;\n const out = new Uint8Array(zeros + (size - it));\n let j = zeros;\n while (it < size) {\n out[j++] = b256[it++]!;\n }\n return out;\n}\n\n// =============================================================================\n// `crit[]` shape rule helper\n// =============================================================================\n\nfunction checkCritShape(\n record: PoeRecord,\n decodedTopKeys: ReadonlySet<string>,\n errors: ValidationIssue[],\n): Set<number> {\n const invalid = new Set<number>();\n if (!Array.isArray(record.crit)) return invalid;\n // `crit` has `1*` cardinality: when present it MUST carry at least one\n // entry. An empty array is a malformed shape — reject it here in the\n // domain pass (rather than via a schema `.min(1)`) so the emitted message\n // string is identical across the TS/PY/RS validators.\n if (record.crit.length === 0) {\n errors.push(\n issue('SCHEMA_TYPE_MISMATCH', ['crit'], 'crit[] must carry at least one entry when present'),\n );\n return invalid;\n }\n const seen = new Set<string>();\n for (let i = 0; i < record.crit.length; i++) {\n const critName = record.crit[i]!;\n let reason: string | null = null;\n if (TOP_LEVEL_BASE_KEYS.has(critName)) {\n reason = `'${critName}' is a base key and MUST NOT appear in crit[]`;\n } else if (!isExtensionKey(critName)) {\n reason = `'${critName}' does not match the extension-key regex (^x-.+ or ^[a-z]+-.+)`;\n } else if (!decodedTopKeys.has(critName)) {\n reason = `'${critName}' is named in crit but absent from the record map`;\n } else if (seen.has(critName)) {\n reason = `'${critName}' appears more than once in crit[]`;\n }\n seen.add(critName);\n if (reason !== null) {\n invalid.add(i);\n errors.push(issue('CRIT_SHAPE_INVALID', ['crit', i], reason));\n }\n }\n return invalid;\n}\n\nfunction topLevelKeysOf(decoded: unknown): Set<string> {\n if (decoded === null || typeof decoded !== 'object') return new Set();\n if (decoded instanceof Map) {\n const out = new Set<string>();\n for (const k of decoded.keys()) {\n if (typeof k === 'string') out.add(k);\n }\n return out;\n }\n return new Set(Object.keys(decoded as Record<string, unknown>));\n}\n\n// =============================================================================\n// Path / issue helpers\n// =============================================================================\n\nfunction issue(\n code: ErrorCode,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nfunction compareIssuePath(a: ValidationIssue, b: ValidationIssue): number {\n return a.path.join('.').localeCompare(b.path.join('.'));\n}\n\nfunction valueAtPath(root: unknown, path: ReadonlyArray<string | number>): unknown {\n let cur: unknown = root;\n for (const seg of path) {\n if (cur === null || cur === undefined) return undefined;\n if (cur instanceof Map) {\n cur = cur.get(seg);\n continue;\n }\n if (typeof cur !== 'object') return undefined;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n return cur;\n}\n","import { argon2id } from 'hash-wasm';\n\nexport interface Argon2idParams {\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport interface Argon2idV13Opts {\n readonly password: Uint8Array;\n readonly salt: Uint8Array;\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport async function argon2idV13(opts: Argon2idV13Opts): Promise<Uint8Array> {\n return (await argon2id({\n password: opts.password,\n salt: opts.salt,\n parallelism: opts.parallelism,\n iterations: opts.iterations,\n memorySize: opts.memSizeKB,\n hashLength: opts.outBytes,\n outputType: 'binary',\n })) as Uint8Array;\n}\n","export class AeadVerificationError extends Error {\n readonly code: string = 'aead_verification_failed';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'AeadVerificationError';\n }\n}\n","import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface XChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface XChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function xchacha20Poly1305Encrypt(opts: XChaCha20Poly1305EncryptOpts): Uint8Array {\n return xchacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function xchacha20Poly1305Decrypt(opts: XChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return xchacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('xchacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\n\nexport function sha256(input: Uint8Array): Uint8Array {\n return nobleSha256(input);\n}\n","// RFC 9162 §2.1.1 binary Merkle tree under SHA-256.\n// This implements the algorithm tier identified on the wire as the\n// `rfc9162-sha256` OPT-INFO; the record's `merkle[]` field carries the proof.\n//\n// Construction (RFC 9162 §2.1.1):\n// - Single leaf: MTH({d_0}) = SHA-256(0x00 || d_0)\n// - Internal node: MTH(L) = SHA-256(0x01 || MTH(L[0:k]) || MTH(L[k:n]))\n// where k = largest power of 2 strictly less than n.\n// - Empty trees (n == 0) are FORBIDDEN.\n// - The 0x00 leaf / 0x01 internal prefixes prevent the CVE-2012-2459\n// leaf-vs-internal collision family.\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { compareCt } from '../util/compare-ct';\n\nexport const MERKLE_ALG_ID = 'rfc9162-sha256' as const;\n\nconst LEAF_PREFIX = 0x00;\nconst NODE_PREFIX = 0x01;\nconst DIGEST_LENGTH = 32;\n\nfunction validateLeaves(leaves: ReadonlyArray<Uint8Array>, fnName: string): void {\n if (leaves.length === 0) {\n throw new Error(`${fnName}: empty leaf list (n == 0 is forbidden by RFC 9162 §2.1.1)`);\n }\n for (let i = 0; i < leaves.length; i++) {\n const leaf = leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new Error(\n `${fnName}: leaf[${i}] must be a Uint8Array(${DIGEST_LENGTH}); got length ${\n leaf instanceof Uint8Array ? leaf.length : 'non-Uint8Array'\n }`,\n );\n }\n }\n}\n\nexport function merkleSha2256Root(leaves: ReadonlyArray<Uint8Array>): Uint8Array {\n validateLeaves(leaves, 'merkleSha2256Root');\n return mthRecursive(leaves, 0, leaves.length);\n}\n\nexport function merkleSha2256InclusionProof(\n leaves: ReadonlyArray<Uint8Array>,\n index: number,\n): Uint8Array[] {\n validateLeaves(leaves, 'merkleSha2256InclusionProof');\n if (!Number.isInteger(index) || index < 0 || index >= leaves.length) {\n throw new Error(\n `merkleSha2256InclusionProof: index ${index} out of range [0, ${leaves.length})`,\n );\n }\n return auditPath(leaves, index, 0, leaves.length);\n}\n\n/**\n * Verify an inclusion proof per RFC 9162 §2.1.3.2 (iterative form).\n *\n * `proof` is ordered leaf-to-root: `proof[0]` is the sibling at the leaf\n * level, `proof[m-1]` is the top-level sibling. The fold uses the\n * `sn`/`fn` tracking from RFC 9162: `sn` is the leaf index within the\n * current subtree, `fn` is (subtree_size - 1). At each step, `sn` odd\n * OR `sn == fn` means the current node is a right child (sibling on\n * the left); otherwise it is a left child (sibling on the right).\n * Both shift right by one each iteration. This handles non-power-of-2\n * sizes including the \"promote a lone right subtree\" cases.\n */\nexport function merkleSha2256VerifyInclusion(\n leaf: Uint8Array,\n index: number,\n treeSize: number,\n proof: ReadonlyArray<Uint8Array>,\n root: Uint8Array,\n): boolean {\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) return false;\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) return false;\n if (\n !Number.isInteger(index) ||\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index < 0 ||\n index >= treeSize\n ) {\n return false;\n }\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (!(sibling instanceof Uint8Array) || sibling.length !== DIGEST_LENGTH) {\n return false;\n }\n }\n\n if (treeSize === 1) {\n if (proof.length !== 0 || index !== 0) return false;\n return compareCt(hashLeaf(leaf), root);\n }\n\n let h = hashLeaf(leaf);\n let sn = index;\n let fn = treeSize - 1;\n for (let i = 0; i < proof.length; i++) {\n if (fn === 0) return false;\n const sibling = proof[i] as Uint8Array;\n if ((sn & 1) === 1 || sn === fn) {\n h = hashNode(sibling, h);\n while ((sn & 1) === 0 && sn !== 0) {\n sn >>>= 1;\n fn >>>= 1;\n }\n } else {\n h = hashNode(h, sibling);\n }\n sn >>>= 1;\n fn >>>= 1;\n }\n if (fn !== 0) return false;\n return compareCt(h, root);\n}\n\nfunction largestPow2Lt(n: number): number {\n let k = 1;\n while (k * 2 < n) k *= 2;\n return k;\n}\n\nfunction hashLeaf(d: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + d.length);\n buf[0] = LEAF_PREFIX;\n buf.set(d, 1);\n return sha256(buf);\n}\n\nfunction hashNode(left: Uint8Array, right: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + left.length + right.length);\n buf[0] = NODE_PREFIX;\n buf.set(left, 1);\n buf.set(right, 1 + left.length);\n return sha256(buf);\n}\n\nfunction mthRecursive(leaves: ReadonlyArray<Uint8Array>, start: number, end: number): Uint8Array {\n const n = end - start;\n if (n === 1) {\n return hashLeaf(leaves[start] as Uint8Array);\n }\n const k = largestPow2Lt(n);\n const left = mthRecursive(leaves, start, start + k);\n const right = mthRecursive(leaves, start + k, end);\n return hashNode(left, right);\n}\n\nfunction auditPath(\n leaves: ReadonlyArray<Uint8Array>,\n i: number,\n start: number,\n end: number,\n): Uint8Array[] {\n const n = end - start;\n if (n === 1) return [];\n const k = largestPow2Lt(n);\n if (i < k) {\n const subPath = auditPath(leaves, i, start, start + k);\n subPath.push(mthRecursive(leaves, start + k, end));\n return subPath;\n }\n const subPath = auditPath(leaves, i - k, start + k, end);\n subPath.push(mthRecursive(leaves, start, start + k));\n return subPath;\n}\n","/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64<T extends ArrayBufferView>(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: <T extends ArrayBufferView>(arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg<VerOpts>): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg<SigOpts>): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<SigOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<VerOpts>\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg<Uint8Array>,\n msg?: TArg<Uint8Array>\n ) => {\n cipherText: TRet<Uint8Array>;\n sharedSecret: TRet<Uint8Array>;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder<F, T> {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder<T> extends Coder<T, Uint8Array> {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen<T> = BytesCoder<T> & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder<T> = T extends BytesCoder<infer U> ? U : never;\ntype SplitOut<T extends (number | BytesCoderLen<any>)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder<T[K]>;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder<T extends (number | BytesCoderLen<any>)[]>(\n label: string,\n ...lengths: T\n): TRet<BytesCoder<SplitOut<T>> & { bytesLen: number }> {\n const getLength = (c: TArg<number | BytesCoderLen<any>>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen<any>).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg<Uint8Array>) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut<T>;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder<T>(c: TArg<BytesCoderLen<T>>, vecLen: number): TRet<BytesCoderLen<T[]>> {\n const coder = c as BytesCoderLen<T>;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg<T[]>): TRet<Uint8Array> => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet<Uint8Array>;\n },\n decode: (a: TArg<Uint8Array>): TRet<T[]> => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet<T[]>;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet<Uint8Array> = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg<Uint8Array>, ctx: TArg<Uint8Array> = EMPTY): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg<Uint8Array>,\n ctx: TArg<Uint8Array> = EMPTY\n): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n","/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts<T extends TypedArray> = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons<T>;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons<T extends TypedArray> = (n: number) => T;\n\ntype Crystals<T extends TypedArray> = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder<number, number>) => BytesCoderLen<T>;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = <T extends TypedArray>(opts: CrystalOpts<T>): TRet<Crystals<T>> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder<number, number>): TRet<BytesCoderLen<T>> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg<T>): TRet<Uint8Array> => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet<Uint8Array>;\n },\n decode: (bytes: TArg<Uint8Array>): TRet<T> => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet<T>;\n },\n } as TRet<BytesCoderLen<T>>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet<T>,\n NTT: {\n encode: (r: TArg<T>): TRet<T> => NTT.encode(r as T) as TRet<T>,\n decode: (r: TArg<T>): TRet<T> => NTT.decode(r as T) as TRet<T>,\n },\n bitsCoder: bitsCoder as TRet<Crystals<T>>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet<XOF> =>\n (seed: TArg<Uint8Array>, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet<Uint8Array>;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet<XOF> = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet<XOF> = /* @__PURE__ */ createXofShake(shake256);\n","/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet<Uint16Array> => new Uint16Array(n) as TRet<Uint16Array>,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record<string, KEMParam> = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder<number, number> => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg<Poly>, g_: TArg<Poly>): TRet<Poly> {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet<Poly>;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType<ReturnType<XOF>['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash<any, { dkLen?: number }>;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg<XofGet>): TRet<Poly> {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet<Poly>;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg<Uint8Array>, eta: number): TRet<Poly> => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet<Poly>;\n};\n\nfunction sampleCBD(\n PRF_: TArg<PRF>,\n seed: TArg<Uint8Array>,\n nonce: number,\n eta: number\n): TRet<Poly> {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg<KyberOpts>) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg<Uint8Array>) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t ← A ◦ s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n seed: TArg<Uint8Array>\n ): TRet<Uint8Array> => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet<Uint8Array>;\n },\n decrypt: (cipherText: TArg<Uint8Array>, privateKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet<Uint8Array>;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg<KyberOpts>): TRet<KEM> {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg<Uint8Array> = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet<Uint8Array>,\n secretKey: secretKey as TRet<Uint8Array>,\n };\n },\n getPublicKey: (secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet<Uint8Array>;\n },\n encapsulate: (publicKey: TArg<Uint8Array>, msg: TArg<Uint8Array> = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)).\n // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet<Uint8Array>,\n sharedSecret: kr.subarray(0, 32) as TRet<Uint8Array>,\n };\n },\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, “implicitly reject”\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet<Uint8Array>;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg<Uint8Array>, nonce: number): TRet<Uint8Array> {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet<Uint8Array>;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg<Uint16Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet<Uint16Array>);\n },\n ByteDecode_d: (B: TArg<Uint8Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg<Uint16Array>) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg<Uint16Array>) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg<Uint16Array>, gHat: TArg<Uint16Array>) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg<Uint8Array>, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg<Uint8Array>) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n","/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * • Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * • getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * • Expanding a small seed into multiple keys reduces entropy.\n * • API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * • Some omit the compression byte (parity) for WebCrypto compatibility.\n * • Better: hash the raw secret; coordinate output is already non-uniform.\n * • Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * • Different domain separations and encodings across libraries.\n * • Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * • Concatenate keys.\n * • Combiner: SHA-512.\n *\n * - GPG:\n * • Concatenate keys.\n * • Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * • Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * • draft-irtf-cfrg-hybrid-kems\n * • draft-connolly-cfrg-xwing-kem\n * • draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * • superdilithium (cyph/pqcrypto.js) – low adoption.\n * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { type EdDSA } from '@noble/curves/abstract/edwards.js';\nimport { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js';\nimport { type ECDSA } from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport {\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\n} from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from './ml-kem.ts';\nimport {\n cleanBytes,\n copyBytes,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n type CryptoKeys,\n type KEM,\n type Signer,\n type TArg,\n type TRet,\n} from './utils.ts';\n\ntype CurveAll = ECDSA | EdDSA | MontgomeryECDH;\ntype CurveECDH = ECDSA | MontgomeryECDH;\ntype CurveSign = ECDSA | EdDSA;\n\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) {\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve as ECDSA;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed: TArg<Uint8Array> = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed!, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey as TRet<Uint8Array>,\n publicKey: curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed?: TArg<Uint8Array>) =>\n keygen(seed) as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>,\n getPublicKey: (secretKey: TArg<Uint8Array>) =>\n curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n}\n\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet<KEM> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(\n publicKey: TArg<Uint8Array>,\n rand: TArg<Uint8Array> = randomBytes(curve.lengths.seed)\n ) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = this.keygen(seed).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet<Signer> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'ecSigner does not support extraEntropy; use the underlying curve directly'\n );\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey) as TRet<Uint8Array>;\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\n\nfunction splitLengths<K extends string, T extends { lengths: Partial<Record<K, number>> }>(\n lst: T[],\n name: K\n) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n return splitCoder(\n name,\n ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name);\n return i.lengths[name];\n })\n );\n}\n\n/** Seed-expansion callback used by the hybrid combiners. */\nexport type ExpandSeed = (seed: TArg<Uint8Array>, len: number) => TRet<Uint8Array>;\ntype XOF = CHashXOF<any, { dkLen: number }>;\n\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof: TArg<XOF>): TRet<ExpandSeed> {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed: TArg<Uint8Array>, seedLen: number): TRet<Uint8Array> =>\n (xof as XOF)(seed, { dkLen: seedLen }) as TRet<Uint8Array>) as TRet<ExpandSeed>;\n}\n\n/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */\nexport type Combiner = (\n publicKeys: TArg<Uint8Array[]>,\n cipherTexts: TArg<Uint8Array[]>,\n sharedSecrets: TArg<Uint8Array[]>\n) => TRet<Uint8Array>;\n\nfunction combineKeys(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n expandSeed_: TArg<ExpandSeed>,\n ...ck_: TArg<CryptoKeys[]>\n) {\n const expandSeed = expandSeed_ as ExpandSeed;\n const ck = ck_ as CryptoKeys[];\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen;\n anumber(realSeedLen);\n function expandDecapsulationKey(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }> {\n abytes(seed, realSeedLen!);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded: Uint8Array[] = [];\n const keySecret: Uint8Array[] = [];\n const secretKey: Uint8Array[] = [];\n const publicKey: Uint8Array[] = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }>;\n } finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok) cleanBytes(secretKey);\n }\n }\n return {\n info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n return this.keygen(secretKey).publicKey as TRet<Uint8Array>;\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(realSeedLen)) {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);\n try {\n const publicKey = pkCoder.encode(pk) as TRet<Uint8Array>;\n return { secretKey: seed as TRet<Uint8Array>, publicKey };\n } finally {\n cleanBytes(pk);\n // The exported secretKey is the caller/root seed itself; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(secretKey);\n }\n },\n expandDecapsulationKey,\n realSeedLen,\n };\n}\n\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param realMsgLen - Shared-secret length returned by `combiner`.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - KEM implementations to combine.\n * @returns Composite KEM.\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n realMsgLen: number | undefined, // how much bytes combiner returns\n expandSeed: TArg<ExpandSeed>,\n combiner: TArg<Combiner>,\n ...kems: TArg<KEM[]>\n): TRet<KEM> {\n const rawCombiner = combiner as Combiner;\n const rawKems = kems as KEM[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen;\n anumber(realMsgLen);\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: realMsgLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(\n pk: TArg<Uint8Array>,\n randomness: TArg<Uint8Array> = randomBytes(msgCoder.bytesLen)\n ) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret: Uint8Array[] = [];\n const cipherText: Uint8Array[] = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),\n cipherText: ctCoder.encode(cipherText) as TRet<Uint8Array>,\n };\n } finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct: TArg<Uint8Array>, seed: TArg<Uint8Array>) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));\n try {\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return copyBytes(rawCombiner(publicKey, cts, sharedSecret));\n } finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - Signers to combine.\n * @returns Composite signer.\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineSigners(\n realSeedLen: number | undefined,\n expandSeed: TArg<ExpandSeed>,\n ...signers: TArg<Signer[]>\n): TRet<Signer> {\n const rawSigners = signers as Signer[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'combineSigners does not support extraEntropy; use the underlying signer directly'\n );\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs) as TRet<Uint8Array>;\n } finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify\n * check fails. Throws on unsupported generic opts or malformed aggregate encodings.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const pks = pkCoder.decode(publicKey);\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false;\n }\n return true;\n },\n };\n}\n\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n kdf: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(kdf);\n return combineKEMS(\n 32,\n kdf.outputLen,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n pqc,\n curveKEM\n );\n}\n\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem768,\n ecdhKem(p256, true),\n shake256,\n sha3_256\n ))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem1024,\n ecdhKem(p384, true),\n shake256,\n sha3_256\n ))();\n\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n hash: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(hash);\n return combineKEMS(\n 32,\n 32,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(\n numberToBytesBE(len, 2),\n asciiToBytes('shared_secret'),\n asciiToBytes('')\n );\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n },\n pqc,\n curveKEM\n );\n}\n\n// Internal alias only: this stays exactly `ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n createKitchenSink(\n 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)',\n ml_kem768,\n x25519kem,\n shake256,\n sha256\n ))();\n\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n combineKEMS(\n 32,\n 32,\n expandSeedXof(shake256),\n // Awesome label, so much escaping hell in a single line.\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))),\n ml_kem768,\n x25519kem\n ))();\n\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet<KEM> {\n const Fn = curve.Point.Fn;\n if (!Fn) throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }> {\n let sk: bigint;\n for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) {\n if (end > seed.length) throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk)) break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>;\n }\n\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n return curve.getPublicKey(secretKey, false) as TRet<Uint8Array>;\n },\n encapsulate(publicKey: TArg<Uint8Array>, rand: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(\n label: string,\n mlkem: TArg<KEM>,\n curve: ECDSA,\n nseed: number\n): TRet<KEM> {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen) throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n\n return combineKEMS(\n 32,\n 32,\n (seed: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(seed, 32);\n const expanded = shake256(seed, { dkLen: totalSeedLen });\n const mlkemSeed = expanded.subarray(0, mlkemSeedLen);\n const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen);\n return concatBytes(mlkemSeed, curveSeed) as TRet<Uint8Array>;\n },\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n mlkem,\n curveKem\n );\n}\n\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n\n// Legacy aliases\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const XWing: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const MLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_p256`. */\nexport const MLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_p256)();\n/** Legacy alias for `ml_kem1024_p384`. */\nexport const MLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => ml_kem1024_p384)();\n/** Legacy alias for `QSF_ml_kem768_p256`. */\nexport const QSFMLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();\n/** Legacy alias for `QSF_ml_kem1024_p384`. */\nexport const QSFMLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();\n/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */\nexport const KitchenSinkMLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() =>\n KitchenSink_ml_kem768_x25519)();\n","import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface ChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface ChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function chacha20Poly1305Encrypt(opts: ChaCha20Poly1305EncryptOpts): Uint8Array {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function chacha20Poly1305Decrypt(opts: ChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('chacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nexport interface HkdfSha256Opts {\n readonly ikm: Uint8Array;\n readonly salt: Uint8Array;\n readonly info: Uint8Array;\n readonly length: number;\n}\n\nexport function hkdfSha256(opts: HkdfSha256Opts): Uint8Array {\n return hkdf(sha256, opts.ikm, opts.salt, opts.info, opts.length);\n}\n","import { XWing } from '@noble/post-quantum/hybrid.js';\n\n// X-Wing (ML-KEM-768 + X25519) hybrid KEM per draft-connolly-cfrg-xwing-kem-06.\n// `XWing` is @noble/post-quantum's alias for `ml_kem768_x25519`. We expose it\n// through opts-object wrappers that pin the wire lengths and map noble's field\n// names onto the project's vocabulary.\n//\n// Unlike the bare X25519 KEM, there is no contributory-behaviour rejection to\n// translate: X-Wing combines the ML-KEM and X25519 shared secrets through a\n// SHA3-256 combiner that also binds the X25519 ephemeral and recipient public\n// keys, and ML-KEM's implicit rejection already yields a constant-work\n// pseudorandom secret on a malformed ciphertext. Decapsulation therefore never\n// throws on attacker-supplied wire data — a wrong shared secret is the correct,\n// indistinguishable failure mode, and callers MUST treat it as a non-match\n// rather than expecting an exception.\n\nexport const MLKEM768X25519_PUBLIC_KEY_LENGTH = 1216 as const;\nexport const MLKEM768X25519_ENC_LENGTH = 1120 as const;\nexport const MLKEM768X25519_SHARED_SECRET_LENGTH = 32 as const;\nexport const MLKEM768X25519_SEED_LENGTH = 32 as const;\nexport const MLKEM768X25519_ESEED_LENGTH = 64 as const;\n\nexport interface Mlkem768X25519KeyPair {\n // The 32-byte root seed IS the secret key in draft-06: the ML-KEM coins and\n // the X25519 scalar are re-expanded from it via SHAKE-256 at decapsulation.\n readonly secretSeed: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface Mlkem768X25519EncapsulateOpts {\n readonly publicKey: Uint8Array;\n // Optional 64-byte encapsulation randomness (msgRand). When supplied the\n // ciphertext and shared secret are fully deterministic; a 32-byte value is\n // rejected by noble, so we pin the length here too.\n readonly eseed?: Uint8Array;\n}\n\nexport interface Mlkem768X25519Encapsulation {\n readonly enc: Uint8Array;\n readonly ss: Uint8Array;\n}\n\nexport interface Mlkem768X25519DecapsulateOpts {\n readonly secretSeed: Uint8Array;\n readonly enc: Uint8Array;\n}\n\nexport function mlkem768x25519Keygen(seed: Uint8Array): Mlkem768X25519KeyPair {\n if (seed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${seed.length}`,\n );\n }\n const { secretKey, publicKey } = XWing.keygen(seed);\n return { secretSeed: secretKey, publicKey };\n}\n\nexport function mlkem768x25519Encapsulate(\n opts: Mlkem768X25519EncapsulateOpts,\n): Mlkem768X25519Encapsulation {\n if (opts.publicKey.length !== MLKEM768X25519_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `mlkem768x25519 public key must be ${MLKEM768X25519_PUBLIC_KEY_LENGTH} bytes, got ${opts.publicKey.length}`,\n );\n }\n if (opts.eseed !== undefined && opts.eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 eseed must be ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${opts.eseed.length}`,\n );\n }\n const { cipherText, sharedSecret } = XWing.encapsulate(opts.publicKey, opts.eseed);\n return { enc: cipherText, ss: sharedSecret };\n}\n\nexport function mlkem768x25519Decapsulate(opts: Mlkem768X25519DecapsulateOpts): Uint8Array {\n // Pre-check both lengths before calling noble: decapsulation must perform a\n // constant amount of work for any caller-supplied ciphertext (implicit\n // rejection), which requires the inputs to be the exact expected sizes.\n if (opts.secretSeed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 secret seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${opts.secretSeed.length}`,\n );\n }\n if (opts.enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(\n `mlkem768x25519 enc must be ${MLKEM768X25519_ENC_LENGTH} bytes, got ${opts.enc.length}`,\n );\n }\n // noble's signature is decapsulate(cipherText, secretKey) — ciphertext first.\n return XWing.decapsulate(opts.enc, opts.secretSeed);\n}\n","import { x25519 } from '@noble/curves/ed25519.js';\n\n// RFC 7748 §6.1 contributory-behaviour rejection: a small-order (low-order)\n// Montgomery `u` coordinate makes the X25519 shared secret all-zero, which\n// @noble/curves refuses with `Error: invalid private or public key received`.\n// We rethrow that as a *typed* error so callers can distinguish a structurally\n// valid-but-malicious peer public key (a property of attacker-supplied wire\n// data — trial-decrypt MUST treat the slot as a non-match, not crash) from\n// genuine caller misuse such as a wrong-length key (which @noble raises as a\n// RangeError and which we deliberately let propagate untouched).\nexport class X25519LowOrderPointError extends Error {\n readonly code = 'X25519_LOW_ORDER_POINT' as const;\n constructor(options?: { cause?: unknown }) {\n super('x25519 ECDH rejected: peer public key is a small-order point', options);\n this.name = 'X25519LowOrderPointError';\n }\n}\n\n// @noble/curves v2 signals a small-order/all-zero shared secret with this exact\n// message. Matching on it (rather than the broad Error class) keeps unrelated\n// failures — e.g. a future internal assertion — surfacing as themselves.\nconst NOBLE_LOW_ORDER_MESSAGE = 'invalid private or public key received';\n\nexport interface X25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface X25519PublicKeyOpts {\n readonly secretKey: Uint8Array;\n}\n\nexport interface X25519EcdhOpts {\n readonly secretKey: Uint8Array;\n readonly theirPublicKey: Uint8Array;\n}\n\nexport function x25519Keygen(): X25519KeyPair {\n return x25519.keygen();\n}\n\nexport function x25519PublicKey(opts: X25519PublicKeyOpts): Uint8Array {\n return x25519.getPublicKey(opts.secretKey);\n}\n\nexport function x25519Ecdh(opts: X25519EcdhOpts): Uint8Array {\n try {\n return x25519.getSharedSecret(opts.secretKey, opts.theirPublicKey);\n } catch (e) {\n // Translate ONLY the contributory-check rejection into our typed error.\n // A wrong-length key throws a RangeError from @noble's length assertion;\n // that is caller misuse, not malicious wire data, so it must propagate.\n if (e instanceof Error && e.message === NOBLE_LOW_ORDER_MESSAGE) {\n throw new X25519LowOrderPointError({ cause: e });\n }\n throw e;\n }\n}\n","// Sealed-PoE error taxonomy (wire-shape + partitioning-oracle pre-checks).\n\nexport type EciesSealedPoeErrorCode =\n | 'ENC_SLOTS_EMPTY'\n | 'ENC_SLOTS_REQUIRED'\n | 'ENC_SLOTS_MAC_REQUIRED'\n | 'ENC_SLOTS_MAC_INVALID_LENGTH'\n | 'KEM_EPK_LENGTH_MISMATCH'\n | 'KEM_CT_LENGTH_MISMATCH'\n | 'INVALID_CEK_LENGTH'\n | 'NONCE_LENGTH_MISMATCH'\n | 'INVALID_EPHEMERAL_SECRET_LENGTH'\n | 'EPHEMERAL_SECRETS_COUNT_MISMATCH'\n | 'UNSUPPORTED_ENC_VERSION'\n | 'UNSUPPORTED_AEAD_ALG'\n | 'UNSUPPORTED_KEM_ALG'\n | 'INVALID_ENVELOPE_SHAPE'\n | 'INVALID_RECIPIENT_KEY'\n | 'WRAP_LENGTH_MISMATCH';\n\nexport class EciesSealedPoeError extends Error {\n readonly code: EciesSealedPoeErrorCode;\n\n constructor(code: EciesSealedPoeErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'EciesSealedPoeError';\n this.code = code;\n }\n}\n","// Single source of truth for two seams that wrap, unwrap, and the wire encoder\n// MUST agree on byte-for-byte:\n//\n// 1. How the 1120-byte X-Wing `enc` is split into the ≤ 64-byte byte-string\n// chunks the Cardano ledger requires (`kem_ct`), and the inverse join.\n// 2. The canonical-CBOR serialization of the slot array that feeds slots_mac.\n//\n// Keeping both here means the producer (wrap) and the verifier (unwrap), as well\n// as the downstream record encoder, cannot diverge on the bytes the MAC commits\n// to — the single highest correctness risk for the hybrid branch, since a\n// divergence would leave the ML-KEM ciphertext unauthenticated.\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '../cbor/canonical';\n\nimport type { Mlkem768X25519Slot, X25519Slot } from './wrap';\n\n// The envelope-level KEM discriminator.\nexport type SealedKem = 'x25519' | 'mlkem768x25519';\n\n// Cardano ledger CDDL caps every `transaction_metadatum` byte string at 64\n// bytes, so any value larger than 64 bytes is carried as an array of ≤ 64-byte\n// chunks (the `bytes-chunk-array` wire form). This is the identical split rule\n// the record encoder applies to chunked COSE bytes.\nconst CHUNK_MAX_BYTES = 64;\n\n// Split a logical byte string into ≤ 64-byte chunks. Used for the X-Wing\n// `enc` → `kem_ct` wire form. Subarrays are views over the input, never copies.\nexport function chunkKemCt(value: Uint8Array): Uint8Array[] {\n if (value.length === 0) {\n throw new Error('chunkKemCt: refusing to chunk an empty byte string');\n }\n const chunks: Uint8Array[] = [];\n for (let i = 0; i < value.length; i += CHUNK_MAX_BYTES) {\n chunks.push(value.subarray(i, Math.min(i + CHUNK_MAX_BYTES, value.length)));\n }\n return chunks;\n}\n\n// Inverse of chunkKemCt: concatenate the chunked `kem_ct` back into the flat\n// X-Wing `enc`. Performs NO length validation — the caller (unwrap) gates the\n// reassembled length against MLKEM768X25519_ENC_LENGTH before any decapsulation.\nexport function joinKemCt(chunks: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = 0;\n for (const c of chunks) total += c.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const c of chunks) {\n out.set(c, offset);\n offset += c.length;\n }\n return out;\n}\n\n// KEM-driven slot serialization for the slots_mac input.\n//\n// • x25519: each slot → { epk: bstr, wrap: bstr }\n// • mlkem768x25519: each slot → { kem_ct: [ bstr, ... ], wrap: bstr }\n//\n// The hybrid form uses the SAME chunked-array shape as the wire encoder, so the\n// MAC commits to the ciphertext exactly as it appears on-chain. Returns the\n// canonical-CBOR bytes ready for HMAC.\nexport function slotsToMacCbor(\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n let value: CanonicalCborValue;\n if (kem === 'x25519') {\n value = (slots as ReadonlyArray<X25519Slot>).map((s) => ({ epk: s.epk, wrap: s.wrap }));\n } else {\n value = (slots as ReadonlyArray<Mlkem768X25519Slot>).map((s) => ({\n // Canonicalize the chunk boundaries before the MAC commits to them:\n // reassemble the logical ciphertext and re-split into canonical ≤ 64-byte\n // chunks. The on-wire `kem_ct` array is a transport detail (the Cardano\n // ledger's 64-byte metadatum cap), and a hostile or non-canonical chunking\n // ([1, 63, …] instead of [64, …]) reassembles to the SAME bytes — so the\n // MAC must be invariant to it. Committing to the verbatim wire chunks would\n // let an attacker re-chunk an honest envelope and break the slots_mac match\n // for an honest recipient. Honest (already-64B-chunked) records are\n // unchanged; a real byte flip still changes the reassembled bytes and is\n // still rejected.\n kem_ct: chunkKemCt(joinKemCt(s.kem_ct)),\n wrap: s.wrap,\n }));\n }\n return encodeCanonicalCbor(value);\n}\n","// Multi-recipient sealed-PoE wrap (age-style ECIES + AEAD-bound slots).\n// Wire-field names are fixed by the standard: scheme, aead, kem, nonce, slots, slots_mac.\n//\n// Two KEM branches share one envelope shape, discriminated on the envelope-level\n// `kem` field:\n//\n// • kem: 'x25519' — classical age-style ECIES. Per-slot epk(32) + wrap(48).\n// • kem: 'mlkem768x25519' — X-Wing hybrid (ML-KEM-768 + X25519). Per-slot the\n// 1120-byte X-Wing enc carried as a chunked byte-string\n// array (`kem_ct`) + wrap(48). No per-slot epk.\n//\n// The slot type is a discriminated union so every consumer is forced — at compile\n// time — to branch on the KEM before touching kem-specific fields.\n\nimport { randomBytes } from '@noble/ciphers/utils.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Encrypt } from '../aead/chacha20-poly1305';\nimport { xchacha20Poly1305Encrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport {\n mlkem768x25519Encapsulate,\n MLKEM768X25519_ENC_LENGTH,\n MLKEM768X25519_ESEED_LENGTH,\n MLKEM768X25519_PUBLIC_KEY_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, x25519PublicKey } from '../kem/x25519';\n\nimport { EciesSealedPoeError } from './errors';\nimport { chunkKemCt, slotsToMacCbor, type SealedKem } from './slots-codec';\n\n// HKDF info strings — fixed protocol labels for KEK derivation and the slot MAC.\n// Byte-length invariants enforce that the SCREAMING_SNAKE constants stay in sync\n// with the on-wire ASCII literals every conformant verifier hashes against.\nexport const CARDANO_POE_HKDF_INFO_KEK: Uint8Array = new TextEncoder().encode('cardano-poe-kek-v1');\n// Hybrid (X-Wing) per-slot KEK label. Distinct from the classical label so a\n// KEK derived under one KEM can never collide with the other. Reused verbatim as\n// the per-slot wrap AEAD AAD, exactly as the classical path reuses its own label.\nexport const CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-kek-mlkem768x25519-v1',\n);\nexport const CARDANO_POE_HKDF_INFO_SLOTS_MAC: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-mac-v1',\n);\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst CEK_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nif (CARDANO_POE_HKDF_INFO_KEK.length !== 18) {\n throw new Error('CARDANO_POE_HKDF_INFO_KEK byte-length invariant violated (expected 18)');\n}\nif (CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519 byte-length invariant violated (expected 33)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_SLOTS_MAC.length !== 24) {\n throw new Error('CARDANO_POE_HKDF_INFO_SLOTS_MAC byte-length invariant violated (expected 24)');\n}\nif (ZERO_NONCE_12.length !== 12) {\n throw new Error('ZERO_NONCE_12 byte-length invariant violated (expected 12)');\n}\n\n// Classical per-slot wire shape: { epk: bstr(32), wrap: bstr(48) }.\nexport interface X25519Slot {\n readonly epk: Uint8Array;\n readonly wrap: Uint8Array;\n}\n\n// Hybrid per-slot wire shape: { kem_ct: [ bstr .size (1..64) ], wrap: bstr(48) }.\n// `kem_ct` is the 1120-byte X-Wing enc carried as a chunked byte-string array\n// (the Cardano ledger caps any single metadatum bstr at 64 bytes). There is NO\n// per-slot epk and NO per-slot kem field — the KEM identifier is hoisted to\n// envelope scope (every slot shares it).\nexport interface Mlkem768X25519Slot {\n readonly kem_ct: ReadonlyArray<Uint8Array>;\n readonly wrap: Uint8Array;\n}\n\n// Back-compat alias retired: callers branch on the envelope `kem` and use the\n// concrete slot type. The discriminated `SealedEnvelope` below is the only\n// shape consumers should depend on.\n\n// Sealed envelope wire shape (discriminated on `kem`).\nexport type SealedEnvelope =\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<X25519Slot>;\n readonly slots_mac: Uint8Array;\n }\n | {\n readonly scheme: 1;\n readonly aead: 'xchacha20-poly1305';\n readonly kem: 'mlkem768x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<Mlkem768X25519Slot>;\n readonly slots_mac: Uint8Array;\n };\n\nexport interface SealedPoeOutput {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\nexport interface WrapArgs {\n readonly plaintext: Uint8Array;\n readonly recipientPublicKeys: ReadonlyArray<Uint8Array>;\n // KEM branch selector. Defaults to 'x25519' for the classical path. The\n // recipient public-key length is validated against the chosen KEM.\n readonly kem?: SealedKem;\n readonly cek?: Uint8Array;\n readonly nonce?: Uint8Array;\n // Deterministic X25519 ephemeral scalars — x25519 branch only.\n readonly ephemeralSecrets?: ReadonlyArray<Uint8Array>;\n // Deterministic X-Wing encapsulation randomness (64 bytes each) — hybrid\n // branch only. One per recipient, parallel to recipientPublicKeys.\n readonly eseeds?: ReadonlyArray<Uint8Array>;\n readonly skipShuffle?: boolean;\n}\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Anonymity invariant: wire ordering MUST NOT encode \"primary\n// recipient first\". A CSPRNG-keyed Fisher-Yates shuffle uniformly permutes the\n// slot array so trial-decrypt order leaks no recipient identity. The\n// slot-set HMAC is computed AFTER this shuffle, binding the on-wire order.\n//\n// Draw an unbiased index in [0, m) from a CSPRNG uint32 via rejection sampling.\n// A plain `u32 % m` skews toward the low residues whenever `m` does not divide\n// 2^32 evenly: the values [0, 2^32 mod m) each occur one extra time. This\n// function exists purely to produce a UNIFORM permutation, so the bias — though\n// cryptographically negligible — is exactly the property we cannot tolerate.\n// We reject any draw landing in the final partial block [limit, 2^32) and\n// redraw, leaving only the residues that map uniformly onto [0, m).\n// Exported so the rejection-bound arithmetic can be asserted directly in tests\n// without relying on a flaky statistical-distribution check.\nexport function uniformIndexBelow(m: number): number {\n // 2^32 mod m, computed without overflowing the 32-bit space.\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % m);\n const buf = new Uint32Array(1);\n let x: number;\n do {\n crypto.getRandomValues(buf);\n x = buf[0] as number;\n } while (x >= limit);\n return x % m;\n}\n\nfunction csprngShuffle<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = uniformIndexBelow(i + 1);\n const tmp = arr[i] as T;\n arr[i] = arr[j] as T;\n arr[j] = tmp;\n }\n}\n\n// Wrap the CEK for one classical recipient: age-style ECIES stanza.\nfunction wrapSlotX25519(args: {\n pubR: Uint8Array;\n privEph: Uint8Array | undefined;\n cek: Uint8Array;\n slotIdx: number;\n}): X25519Slot {\n const privEph = args.privEph ?? randomBytes(X25519_SECRET_KEY_LENGTH);\n if (privEph.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `ephemeralSecrets[${args.slotIdx}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${privEph.length}`,\n );\n }\n const epk = x25519PublicKey({ secretKey: privEph });\n const shared = x25519Ecdh({ secretKey: privEph, theirPublicKey: args.pubR });\n // age v1 stanza salt is `epk || pub_R`.\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(epk, args.pubR),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n // Per-slot wrap AAD MUST be the 18-byte ASCII literal of the KEK info\n // string (never empty AAD).\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { epk, wrap };\n}\n\n// Wrap the CEK for one hybrid recipient: X-Wing encapsulation → HKDF → AEAD.\n// The KEK info label doubles as the wrap AEAD AAD, mirroring the classical path.\nfunction wrapSlotMlkem768X25519(args: {\n pubR: Uint8Array;\n eseed: Uint8Array | undefined;\n cek: Uint8Array;\n}): Mlkem768X25519Slot {\n const { enc, ss } = mlkem768x25519Encapsulate({\n publicKey: args.pubR,\n ...(args.eseed !== undefined ? { eseed: args.eseed } : {}),\n });\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(`internal: enc.length=${enc.length}, expected ${MLKEM768X25519_ENC_LENGTH}`);\n }\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { kem_ct: chunkKemCt(enc), wrap };\n}\n\nexport function eciesSealedPoeWrap(args: WrapArgs): SealedPoeOutput {\n const { plaintext, recipientPublicKeys } = args;\n const kem: SealedKem = args.kem ?? 'x25519';\n const n = recipientPublicKeys.length;\n\n // There is no fixed upper bound on slot count; the producer SDK polices the\n // per-record byte budget. Only the lower bound is enforced here.\n if (n < 1) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_EMPTY',\n `recipientPublicKeys.length=${n} must be >= 1`,\n );\n }\n\n const expectedPubLen =\n kem === 'x25519' ? X25519_PUBLIC_KEY_LENGTH : MLKEM768X25519_PUBLIC_KEY_LENGTH;\n for (let i = 0; i < n; i++) {\n const pub = recipientPublicKeys[i];\n if (pub === undefined || pub.length !== expectedPubLen) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `recipientPublicKeys[${i}] MUST be exactly ${expectedPubLen} bytes for kem='${kem}'`,\n );\n }\n }\n\n if (kem === 'x25519') {\n if (args.eseeds !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"eseeds is an X-Wing (mlkem768x25519) override and MUST NOT be supplied for kem='x25519'\",\n );\n }\n if (args.ephemeralSecrets !== undefined && args.ephemeralSecrets.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `ephemeralSecrets.length=${args.ephemeralSecrets.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n } else {\n if (args.ephemeralSecrets !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"ephemeralSecrets is an X25519 override and MUST NOT be supplied for kem='mlkem768x25519'\",\n );\n }\n if (args.eseeds !== undefined) {\n if (args.eseeds.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `eseeds.length=${args.eseeds.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n for (let i = 0; i < n; i++) {\n const eseed = args.eseeds[i]!;\n if (eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `eseeds[${i}] MUST be exactly ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${eseed.length}`,\n );\n }\n }\n }\n }\n\n const cek = args.cek ?? randomBytes(CEK_LENGTH);\n const nonce = args.nonce ?? randomBytes(NONCE_LENGTH);\n if (cek.length !== CEK_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_CEK_LENGTH',\n `cek MUST be exactly ${CEK_LENGTH} bytes, got ${cek.length}`,\n );\n }\n if (nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${nonce.length}`,\n );\n }\n\n let envelope: SealedEnvelope;\n if (kem === 'x25519') {\n const slots: X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotX25519({\n pubR: recipientPublicKeys[i]!,\n privEph: args.ephemeralSecrets ? (args.ephemeralSecrets[i] as Uint8Array) : undefined,\n cek,\n slotIdx: i,\n }),\n );\n }\n // Anonymity invariant (see csprngShuffle comment).\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n } else {\n const slots: Mlkem768X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotMlkem768X25519({\n pubR: recipientPublicKeys[i]!,\n eseed: args.eseeds ? (args.eseeds[i] as Uint8Array) : undefined,\n cek,\n }),\n );\n }\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsMac = computeSlotsMac(cek, slots, 'mlkem768x25519');\n envelope = {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce,\n slots,\n slots_mac: slotsMac,\n };\n }\n\n // Content AEAD AAD is `nonce || slots_mac` (24 + 32 = 56 B).\n const adContent = concat(nonce, envelope.slots_mac);\n const ciphertext = xchacha20Poly1305Encrypt({\n key: cek,\n nonce,\n aad: adContent,\n plaintext,\n });\n\n return { envelope, ciphertext };\n}\n\n// Slot-set MAC binds canonical-CBOR(slots) to the CEK.\n// The slot→CBOR serialization is KEM-driven (`slotsToMacCbor`) so the hybrid\n// kem_ct is authenticated by slots_mac exactly as the classical epk is.\nfunction computeSlotsMac(\n cek: Uint8Array,\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n kem: SealedKem,\n): Uint8Array {\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsCbor = slotsToMacCbor(slots, kem);\n const slotsMac = hmac(sha256, hmacKey, slotsCbor);\n if (slotsMac.length !== SLOTS_MAC_LENGTH) {\n throw new Error(`internal: slots_mac.length=${slotsMac.length}, expected ${SLOTS_MAC_LENGTH}`);\n }\n return slotsMac;\n}\n","// Multi-recipient sealed-PoE unwrap (age-style trial-decrypt\n// + constant-time slots_mac binding + partitioning-oracle length pre-checks).\n//\n// Two forms (mutually exclusive — exactly one MUST be supplied):\n//\n// • Single-priv form: `recipientSecretKey: Uint8Array` — the standalone-verifier\n// path. Runs the trial-decrypt loop over `envelope.slots` once.\n//\n// • Multi-priv form: `recipientSecretKeys: ReadonlyArray<Uint8Array>` — for the\n// trial-decrypt scan of a rotated identity holding `[currentPriv, ...archivedPrivs]`.\n// Caller supplies the order; the iterator runs outer-loop = privkey ×\n// inner-loop = slot, short-circuiting on the first cross-priv match that\n// passes slots_mac verification. The recommended caller order\n// is `[currentPriv, ...previousPrivsReversed]` (newest archive first).\n//\n// Constant-time-N (default `true`) applies PER PRIV (the inner loop): all slots\n// are entered regardless of match position. The outer loop short-circuits on\n// first cross-priv match — the cross-priv channel is intrinsic to trial-decrypt\n//\n// Both KEM branches share this control flow. The per-slot recovery body differs:\n// • x25519: X25519 ECDH → HKDF → AEAD-unwrap; may throw on a low-order\n// epk (RFC 7748 §6.1 contributory-check rejection), handled\n// as a non-match.\n// • mlkem768x25519: X-Wing decapsulate → HKDF → AEAD-unwrap; NEVER throws on\n// attacker wire data (ML-KEM implicit rejection yields a\n// pseudorandom shared secret), so no try/catch around it.\n\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { chacha20Poly1305Decrypt } from '../aead/chacha20-poly1305';\nimport { AeadVerificationError } from '../aead/errors';\nimport { xchacha20Poly1305Decrypt } from '../aead/xchacha20-poly1305';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport { mlkem768x25519Decapsulate, MLKEM768X25519_ENC_LENGTH } from '../kem/mlkem768x25519';\nimport { x25519Ecdh, X25519LowOrderPointError, x25519PublicKey } from '../kem/x25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport { joinKemCt, slotsToMacCbor } from './slots-codec';\nimport {\n CARDANO_POE_HKDF_INFO_KEK,\n CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n type Mlkem768X25519Slot,\n type SealedEnvelope,\n type X25519Slot,\n} from './wrap';\n\nexport type UnwrapFailureReason = 'WRONG_RECIPIENT_KEY' | 'TAMPERED_HEADER' | 'TAMPERED_CIPHERTEXT';\n\nexport type UnwrapResult =\n | { readonly matched: true; readonly plaintext: Uint8Array }\n | { readonly matched: false; readonly reason: UnwrapFailureReason };\n\n// Unified recipient key bundle. Callers hold BOTH the X25519\n// private-key chain (current + archived, for classical and rotation history)\n// AND the X-Wing secret seed(s) (for the hybrid KEM), without knowing which a\n// given record was sealed under. They pass the whole bundle; the unwrap /\n// trial-decrypt dispatch selects the correct secret list from `envelope.kem`:\n//\n// • kem === 'x25519' → bundle.x25519PrivateKeys\n// • kem === 'mlkem768x25519' → bundle.mlkem768x25519SecretSeeds\n//\n// Both lists are ordered newest-first (caller's responsibility — the outer\n// trial-decrypt loop scans them in order). A list MAY be empty when the\n// recipient holds no key for that KEM (e.g. archived-only X25519 identities\n// predate the hybrid KEM, so their hybrid seed list is empty); a bundle whose\n// selected list is empty unwraps to a clean WRONG_RECIPIENT_KEY / no_aead_pass\n// without touching any KEM primitive.\nexport interface RecipientKeyBundle {\n readonly x25519PrivateKeys: ReadonlyArray<Uint8Array>;\n readonly mlkem768x25519SecretSeeds: ReadonlyArray<Uint8Array>;\n}\n\n// Select the secret-key list a bundle contributes for the given envelope KEM.\n// The single dispatch seam — wrap and trial-decrypt both route through here so\n// the per-KEM selection lives in exactly one place.\nfunction selectBundleSecrets(\n envelope: SealedEnvelope,\n bundle: RecipientKeyBundle,\n): ReadonlyArray<Uint8Array> {\n return envelope.kem === 'x25519' ? bundle.x25519PrivateKeys : bundle.mlkem768x25519SecretSeeds;\n}\n\ninterface UnwrapArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n readonly constantTimeN?: boolean;\n // Test-only instrumentation for constant-time-N verification.\n // The unwrap fn bumps `count` once per inner-loop iteration entered. In the\n // multi-priv path, `count` is reset at the start of each outer iteration and\n // — when `perPrivCounts` is provided — the final per-priv inner count is\n // appended after that priv's inner loop completes. Production callers never\n // pass this.\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n // Test-only multi-priv outer-loop iteration counter. Bumped to `k + 1` at\n // the start of each outer-loop iteration. Production callers never pass this.\n readonly _privsAttemptedOut?: { count: number };\n}\n\nexport interface UnwrapArgsSinglePriv extends UnwrapArgsCommon {\n readonly recipientSecretKey: Uint8Array;\n}\n\nexport interface UnwrapArgsMultiPriv extends UnwrapArgsCommon {\n readonly recipientSecretKeys: ReadonlyArray<Uint8Array>;\n}\n\n// Bundle form of the multi-priv path: the caller passes both KEMs' secret\n// lists and the dispatch picks the right one from `envelope.kem`. This is the\n// surface every read-path consumer (inbox decrypt, CLI decrypt, standalone\n// recipient verifier) should use — they hold the whole identity key bundle and\n// must NOT pre-select a list or rebuild slots themselves.\nexport interface UnwrapArgsBundle extends UnwrapArgsCommon {\n readonly recipientKeyBundle: RecipientKeyBundle;\n}\n\nexport type UnwrapArgs = UnwrapArgsSinglePriv | UnwrapArgsMultiPriv | UnwrapArgsBundle;\n\n// Trial-decrypt-only sibling of eciesSealedPoeUnwrap. Runs the\n// per-slot AEAD + slots_mac check but NEVER calls the content AEAD (which\n// requires the off-chain `ciphertext` blob, not available at trial-decrypt\n// time). Used by an inbox-scan agent to discover readable records before\n// fetching their ciphertext.\ninterface TrialDecryptOnlyArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly constantTimeN?: boolean;\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n readonly _privsAttemptedOut?: { count: number };\n}\n\n// Exactly one of `recipientSecretKeys` (flat, KEM-pre-selected) or\n// `recipientKeyBundle` (whole bundle, KEM dispatched from `envelope.kem`).\n// Inbox-scan consumers pass the bundle; the low-level / parity tests pass the\n// flat list directly.\nexport type TrialDecryptOnlyArgs = TrialDecryptOnlyArgsCommon &\n (\n | { readonly recipientSecretKeys: ReadonlyArray<Uint8Array> }\n | { readonly recipientKeyBundle: RecipientKeyBundle }\n );\n\nexport type TrialDecryptOnlyResult =\n | { readonly kind: 'match'; readonly slotIdx: number; readonly cek: Uint8Array }\n | { readonly kind: 'no_aead_pass' }\n | { readonly kind: 'aead_pass_no_mac_match' };\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nfunction concat(a: Uint8Array, b: Uint8Array): Uint8Array {\n const out = new Uint8Array(a.length + b.length);\n out.set(a, 0);\n out.set(b, a.length);\n return out;\n}\n\n// Partitioning-oracle defence: every wire\n// length MUST be validated before any KEM/AEAD primitive is invoked, so malformed\n// records cannot probe per-slot failure ordering. Shared between\n// `eciesSealedPoeUnwrap` (single- and multi-priv) and `eciesSealedPoeTrialDecrypt`\n// to guarantee byte-identical pre-trial behaviour and to keep the dispatch\n// invariant in one place. For the hybrid branch this includes reassembling each\n// slot's `kem_ct` and asserting the flat enc length BEFORE any decapsulation.\nfunction assertEnvelopeStructure(\n envelope: SealedEnvelope,\n multiPrivKeys?: ReadonlyArray<Uint8Array>,\n singlePrivKey?: Uint8Array,\n): void {\n if (envelope.scheme !== 1) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_ENC_VERSION',\n `envelope.scheme=${String(envelope.scheme)} unsupported (expected 1)`,\n );\n }\n if (envelope.aead !== 'xchacha20-poly1305') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_AEAD_ALG',\n `envelope.aead=${String(envelope.aead)} unsupported (expected 'xchacha20-poly1305')`,\n );\n }\n if (envelope.kem !== 'x25519' && envelope.kem !== 'mlkem768x25519') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_KEM_ALG',\n `envelope.kem=${String((envelope as { kem: string }).kem)} unsupported (expected 'x25519' or 'mlkem768x25519')`,\n );\n }\n\n // Envelope-level length pre-checks in this exact order.\n const n = envelope.slots.length;\n if (n < 1) {\n throw new EciesSealedPoeError('ENC_SLOTS_EMPTY', `envelope.slots.length=${n} must be >= 1`);\n }\n if (envelope.nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `envelope.nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${envelope.nonce.length}`,\n );\n }\n if (envelope.slots_mac.length !== SLOTS_MAC_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n `envelope.slots_mac MUST be exactly ${SLOTS_MAC_LENGTH} bytes, got ${envelope.slots_mac.length}`,\n );\n }\n\n // Per-slot length pre-checks — KEM-driven. ALL slots are validated here,\n // before any decapsulation, so the trial-decrypt loop never observes a\n // malformed slot (partitioning-oracle-safe ordering).\n if (envelope.kem === 'x25519') {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n if (slot.epk.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `envelope.slots[${i}].epk MUST be exactly ${X25519_PUBLIC_KEY_LENGTH} bytes, got ${slot.epk.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n } else {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n const enc = joinKemCt(slot.kem_ct);\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_CT_LENGTH_MISMATCH',\n `envelope.slots[${i}].kem_ct MUST reassemble to exactly ${MLKEM768X25519_ENC_LENGTH} bytes, got ${enc.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n }\n }\n\n if (multiPrivKeys !== undefined) {\n for (let i = 0; i < multiPrivKeys.length; i++) {\n if (multiPrivKeys[i]!.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKeys[${i}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${multiPrivKeys[i]!.length}`,\n );\n }\n }\n } else if (singlePrivKey !== undefined) {\n if (singlePrivKey.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKey MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${singlePrivKey.length}`,\n );\n }\n }\n}\n\n// Classical (x25519) per-slot recovery body. Returns the CEK on the first\n// AEAD-tag success; null otherwise. `liveSlot` distinguishes the real-work path\n// (attempt the AEAD unwrap) from the constant-time-N dummy path (do the ECDH +\n// HKDF but skip the AEAD, since a CEK is already in hand).\nfunction tryX25519Slot(args: {\n slot: X25519Slot;\n recipientSecretKey: Uint8Array;\n pubRLocal: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // A slot's `epk` is attacker-influenceable wire data. A small-order\n // Montgomery point makes the X25519 shared secret all-zero, which the KEM\n // rejects per RFC 7748 §6.1. Such a slot can never have been produced by a\n // conformant wrap for THIS recipient, so it is a non-match — handled here\n // identically to an AEAD-tag failure (skip the slot, keep iterating so the\n // constant-time-N loop shape is preserved). Only the contributory-check\n // rejection is swallowed; any other error propagates.\n if (args.liveSlot) {\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n const kek = hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError) && !(e instanceof X25519LowOrderPointError)) {\n throw e;\n }\n return null;\n }\n }\n // Constant-time-N dummy path: mirror the real-work ECDH + HKDF, still\n // tolerating a low-order epk in a later slot so it cannot turn a successful\n // unwrap into a throw.\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n hkdfSha256({\n ikm: shared,\n salt: concat(args.slot.epk, args.pubRLocal),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n } catch (e) {\n if (!(e instanceof X25519LowOrderPointError)) throw e;\n }\n return null;\n}\n\n// Hybrid (mlkem768x25519) per-slot recovery body. X-Wing decapsulate NEVER\n// throws on attacker wire data (ML-KEM implicit rejection), so there is no\n// try/catch: a wrong shared secret simply yields a KEK that fails the AEAD tag.\n// The dummy (constant-time-N) path runs a FULL decapsulate + HKDF so matching\n// and non-matching slots cost the same X-Wing work.\nfunction tryMlkem768X25519Slot(args: {\n slot: Mlkem768X25519Slot;\n recipientSecretKey: Uint8Array;\n liveSlot: boolean;\n}): Uint8Array | null {\n // kem_ct length was validated to reassemble to MLKEM768X25519_ENC_LENGTH in\n // assertEnvelopeStructure, so this join + decapsulate is constant-work.\n const enc = joinKemCt(args.slot.kem_ct);\n const ss = mlkem768x25519Decapsulate({ secretSeed: args.recipientSecretKey, enc });\n const kek = hkdfSha256({\n ikm: ss,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n if (!args.liveSlot) {\n // Dummy path: full decapsulate + HKDF already done above; skip only the\n // AEAD attempt (a CEK is already in hand).\n return null;\n }\n try {\n return chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n ciphertext: args.slot.wrap,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return null;\n }\n}\n\n// Per-priv inner trial-decrypt loop with slot-index reporting, KEM-driven.\n// Enters every slot when constantTimeN; the dummy path keeps per-iteration cost\n// uniform regardless of which slot matched.\nfunction tryRecipientUnwrapWithIdx(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): { cek: Uint8Array; slotIdx: number } | null {\n const n = envelope.slots.length;\n let cek: Uint8Array | null = null;\n let matchedSlotIdx = -1;\n\n if (envelope.kem === 'x25519') {\n const pubRLocal = x25519PublicKey({ secretKey: recipientSecretKey });\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryX25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n pubRLocal,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n } else {\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n const candidate = tryMlkem768X25519Slot({\n slot: envelope.slots[i]!,\n recipientSecretKey,\n liveSlot: cek === null,\n });\n if (cek === null && candidate !== null) {\n cek = candidate;\n matchedSlotIdx = i;\n }\n if (cek !== null && !constantTimeN) break;\n }\n }\n return cek === null ? null : { cek, slotIdx: matchedSlotIdx };\n}\n\n// Back-compat wrapper preserved for callers that only care about the CEK\n// (single-priv path inside `eciesSealedPoeUnwrap`).\nfunction tryRecipientUnwrap(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n constantTimeN: boolean,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): Uint8Array | null {\n return (\n tryRecipientUnwrapWithIdx(envelope, recipientSecretKey, constantTimeN, slotsAttemptedOut)\n ?.cek ?? null\n );\n}\n\n// Slot-set MAC bytes, KEM-driven so the hybrid kem_ct is\n// committed exactly as it appears on-wire. Constant across the multi-priv outer\n// loop (depends only on envelope.slots), so callers compute it once.\nfunction slotsMacCborBytes(envelope: SealedEnvelope): Uint8Array {\n return slotsToMacCbor(\n envelope.slots as ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n envelope.kem,\n );\n}\n\nexport function eciesSealedPoeUnwrap(args: UnwrapArgs): UnwrapResult {\n const { envelope, ciphertext } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Exactly-one-of validation across the three UnwrapArgs forms (single-priv,\n // flat multi-priv, bundle). Runs before any AEAD / wire-shape work so a\n // malformed call cannot probe per-slot AEAD timing. The bundle form resolves\n // to a flat multi-priv list here by dispatching on `envelope.kem` — from this\n // point the loop is identical regardless of how the caller supplied keys.\n const hasSingle = 'recipientSecretKey' in args;\n const hasBundle = 'recipientKeyBundle' in args;\n const multiPrivKeys: ReadonlyArray<Uint8Array> | undefined = hasBundle\n ? selectBundleSecrets(envelope, (args as UnwrapArgsBundle).recipientKeyBundle)\n : 'recipientSecretKeys' in args\n ? (args as UnwrapArgsMultiPriv).recipientSecretKeys\n : undefined;\n const hasMulti = multiPrivKeys !== undefined;\n if (hasSingle === hasMulti) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'exactly one of recipientSecretKey / recipientSecretKeys / recipientKeyBundle MUST be supplied',\n );\n }\n // A bundle selecting an empty list for this KEM means the recipient holds no\n // key of the matching kind (e.g. an archived-only identity facing a hybrid\n // record). That is a legitimate non-match, NOT a malformed call — return a\n // clean WRONG_RECIPIENT_KEY without invoking any KEM primitive. The flat\n // multi-priv form keeps the original \"empty array is a programmer error\"\n // contract its callers (and step-3 tests) rely on.\n if (hasMulti && multiPrivKeys!.length === 0) {\n if (hasBundle) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n\n // Partitioning-oracle pre-checks; per-priv length validation happens\n // inside `assertEnvelopeStructure`.\n if (hasMulti) {\n assertEnvelopeStructure(envelope, multiPrivKeys, undefined);\n } else {\n assertEnvelopeStructure(envelope, undefined, (args as UnwrapArgsSinglePriv).recipientSecretKey);\n }\n\n // Trial-decrypt loop. With constantTimeN=true the loop\n // entries are uniform regardless of match position; the per-iteration body\n // does the same KEM + HKDF work in both branches.\n\n let matchedCek: Uint8Array | null = null;\n let anyCandidateRecovered = false;\n\n if (hasSingle) {\n const recipientSecretKey = (args as UnwrapArgsSinglePriv).recipientSecretKey;\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKey,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (cek === null) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n // Slot-set MAC verification. Use compareCt to\n // avoid leaking byte-position via early-exit on first mismatching byte.\n const slotsCbor = slotsMacCborBytes(envelope);\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (!compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n matchedCek = cek;\n } else {\n // The slots-CBOR is constant across the outer loop (depends only on\n // envelope.slots) — compute once before the loop to keep per-priv cost\n // identical to the single-priv path.\n const slotsCbor = slotsMacCborBytes(envelope);\n const recipientSecretKeys = multiPrivKeys!;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const cek = tryRecipientUnwrap(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (cek === null) continue;\n // Slot-set MAC verification per priv that recovered a candidate CEK.\n const hmacKey = hkdfSha256({\n ikm: cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n // The outer cross-priv loop short-circuits on the first priv whose\n // recovered CEK also passes slots_mac. This intentionally leaks \"which\n // priv matched\" → \"how many key rotations the recipient has performed\".\n // We accept it: trial-decrypt runs client-side, so this timing is only\n // locally observable, and the leak is a weak ordering signal, not a\n // key/plaintext oracle. Making the outer loop constant-work would cost a\n // FULL KEM decapsulation (an X25519 ECDH, or — for the hybrid branch — a\n // full X-Wing ML-KEM-768 + X25519 decapsulation) for EVERY archived priv\n // on EVERY record, which for the hybrid case is the dominant cost; the\n // benefit (hiding a count the user already knows) does not justify it.\n // The inner per-slot loop IS held constant-work (constant-time-N).\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n matchedCek = cek;\n break;\n }\n anyCandidateRecovered = true;\n }\n if (matchedCek === null) {\n return {\n matched: false,\n reason: anyCandidateRecovered ? 'TAMPERED_HEADER' : 'WRONG_RECIPIENT_KEY',\n };\n }\n }\n\n // Content AEAD AAD is `nonce || slots_mac`.\n const adContent = concat(envelope.nonce, envelope.slots_mac);\n try {\n const plaintext = xchacha20Poly1305Decrypt({\n key: matchedCek,\n nonce: envelope.nonce,\n aad: adContent,\n ciphertext,\n });\n return { matched: true, plaintext };\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n}\n\n// Trial-decrypt half of the sealed-PoE unwrap algorithm:\n// recovers the CEK + slot index without touching the content AEAD. Used by an\n// inbox-scan agent where the on-chain `metadata_cbor` envelope is available but\n// the off-chain ciphertext blob is fetched lazily only when the user invokes\n// Decrypt.\n//\n// Mirrors the multi-priv branch of `eciesSealedPoeUnwrap`: same\n// partitioning-oracle pre-checks, same per-priv inner loop, same\n// constant-time-N invariant (default `true` — MANDATORY for untrusted scan\n// agents), same `compareCt` slots_mac check. Differs only\n// in the return shape: `{kind: 'match', slotIdx, cek}` instead of plaintext;\n// `{kind: 'aead_pass_no_mac_match'}`\n// instead of `TAMPERED_HEADER`; `{kind: 'no_aead_pass'}` instead of\n// `WRONG_RECIPIENT_KEY`. Cross-priv variable-time short-circuit is preserved\n// (leaks \"which priv matched\" → \"how many rotations\",\n// a documented weak ordering signal).\nexport function eciesSealedPoeTrialDecrypt(args: TrialDecryptOnlyArgs): TrialDecryptOnlyResult {\n const { envelope } = args;\n const constantTimeN = args.constantTimeN ?? true;\n\n // Bundle form selects the per-KEM list from `envelope.kem`; flat form is\n // already KEM-pre-selected. An empty bundle list for this KEM is a clean\n // no_aead_pass (the recipient holds no key of the matching kind), whereas an\n // empty flat list stays a programmer error (its callers / step-3 tests rely\n // on the throw).\n const hasBundle = 'recipientKeyBundle' in args;\n const recipientSecretKeys: ReadonlyArray<Uint8Array> = hasBundle\n ? selectBundleSecrets(envelope, args.recipientKeyBundle)\n : args.recipientSecretKeys;\n\n if (recipientSecretKeys.length === 0) {\n if (hasBundle) {\n return { kind: 'no_aead_pass' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n assertEnvelopeStructure(envelope, recipientSecretKeys, undefined);\n\n const slotsCbor = slotsMacCborBytes(envelope);\n\n let anyCandidateRecovered = false;\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const candidate = tryRecipientUnwrapWithIdx(\n envelope,\n recipientSecretKeys[k]!,\n constantTimeN,\n args._slotsAttemptedOut,\n );\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (candidate === null) continue;\n const hmacKey = hkdfSha256({\n ikm: candidate.cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n const slotsMacCalc = hmac(sha256, hmacKey, slotsCbor);\n if (compareCt(slotsMacCalc, envelope.slots_mac)) {\n return { kind: 'match', slotIdx: candidate.slotIdx, cek: candidate.cek };\n }\n anyCandidateRecovered = true;\n }\n return anyCandidateRecovered ? { kind: 'aead_pass_no_mac_match' } : { kind: 'no_aead_pass' };\n}\n","// The single seam that turns a structurally-validated but permissive on-wire\n// `enc` block into the discriminated `SealedEnvelope` the unwrap / trial-decrypt\n// path consumes.\n//\n// Every read-path consumer (inbox trial-decrypt, inbox CEK recovery, the CLI\n// `inbox sync` / `inbox decrypt` orchestrators, the standalone recipient\n// verifier) used to do this inline with a HARDCODED `kem: 'x25519'` and an\n// unconditional `slots.map(s => ({ epk: s.epk, wrap: s.wrap }))`. With the\n// discriminated-union slot shape (classical `{epk, wrap}` vs hybrid\n// `{kem_ct, wrap}`) that inline build is both wrong (drops `kem_ct`) and\n// uncompilable (reads optional `epk` as required). This helper is the ONE place\n// the conversion lives: it dispatches on `enc.kem`, picks the matching per-slot\n// fields, and returns `null` for anything that is not a recognised sealed\n// envelope (passphrase-only blocks, missing slots, unknown KEM). Callers then\n// pass the whole returned envelope plus their `RecipientKeyBundle` straight to\n// `eciesSealedPoeUnwrap` / `eciesSealedPoeTrialDecrypt` — they never rebuild\n// slots or reassemble `kem_ct` themselves.\n//\n// crypto-core is a leaf package and must not depend on poe-standard's Zod\n// schema, so the input is a structural shape mirroring the fields the parsed\n// `EncryptionEnvelope` exposes. Anything narrower (per-slot length checks) is\n// re-asserted by `assertEnvelopeStructure` inside the unwrap path; this helper\n// is purely the KEM-driven shape projection.\n\nimport type { Mlkem768X25519Slot, SealedEnvelope, X25519Slot } from './wrap';\n\n// Structural mirror of the parsed-but-permissive on-wire slot. Each field is\n// `T | undefined` (not just optional) so the parsed `EncryptionEnvelope` from a\n// consumer compiled with `exactOptionalPropertyTypes` is assignable without a\n// cast: the schema layer cannot know the envelope `kem` from a slot in\n// isolation, so it leaves all three fields optional (see poe-standard\n// SlotSchema).\nexport interface ParsedSlotShape {\n readonly epk?: Uint8Array | undefined;\n readonly kem_ct?: ReadonlyArray<Uint8Array> | undefined;\n readonly wrap?: Uint8Array | undefined;\n}\n\n// Structural mirror of the parsed-but-permissive `enc` block.\nexport interface ParsedEnvelopeShape {\n readonly scheme?: unknown;\n readonly aead?: string | undefined;\n readonly kem?: string | undefined;\n readonly nonce?: Uint8Array | undefined;\n readonly slots?: ReadonlyArray<ParsedSlotShape> | undefined;\n readonly slots_mac?: Uint8Array | undefined;\n}\n\n// Build the discriminated `SealedEnvelope` from a parsed `enc` block, or return\n// `null` when the block is not a sealed-recipient envelope we can trial-decrypt\n// (passphrase-only, missing slots/nonce/slots_mac, unrecognised KEM, or a slot\n// missing the KEM's required field). Returning `null` keeps every consumer's\n// \"this item is not for the recipient path → no match, no crypto\" branch.\nexport function sealedEnvelopeFromParsed(enc: ParsedEnvelopeShape): SealedEnvelope | null {\n if (enc.scheme !== 1 || enc.aead !== 'xchacha20-poly1305') return null;\n if (enc.nonce === undefined || enc.slots_mac === undefined) return null;\n const slots = enc.slots;\n if (slots === undefined || slots.length < 1) return null;\n\n if (enc.kem === 'x25519') {\n const x25519Slots: X25519Slot[] = [];\n for (const s of slots) {\n if (s.epk === undefined || s.wrap === undefined) return null;\n x25519Slots.push({ epk: s.epk, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'x25519',\n nonce: enc.nonce,\n slots: x25519Slots,\n slots_mac: enc.slots_mac,\n };\n }\n\n if (enc.kem === 'mlkem768x25519') {\n const hybridSlots: Mlkem768X25519Slot[] = [];\n for (const s of slots) {\n if (s.kem_ct === undefined || s.wrap === undefined) return null;\n hybridSlots.push({ kem_ct: s.kem_ct, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: 'xchacha20-poly1305',\n kem: 'mlkem768x25519',\n nonce: enc.nonce,\n slots: hybridSlots,\n slots_mac: enc.slots_mac,\n };\n }\n\n return null;\n}\n","// Canonical outbound HTTP wrapper: deny-list short-circuit, protocol/method\n// allowlist, bounded timeout, exp-backoff retry with jitter, audit trail.\n\n// Universal loopback deny-host list a service-independent verifier MUST reject\n// so a record can never be made to \"verify\" only because it reached a loopback\n// address. This default carries no operator-specific entries: a deployment that\n// wants to forbid its own gateway/viewer hosts appends those at construction\n// time. Producers SHOULD pass this through `denyHosts` on every verifier\n// invocation; the wrapper accepts arbitrary lists but exports the canonical\n// loopback set so callers don't duplicate it inline. (RFC-1918 / link-local IP\n// ranges are blocked separately by the SSRF guard, not by this name list.)\nexport const DENY_HOSTS_DEFAULT: ReadonlyArray<string> = ['localhost', '127.0.0.1'];\n\n// Every outbound call carries a purpose tag from the closed set\n// `{cardano, arweave, ipfs}` (the three v1 gateway-chain purposes).\n// `https` is a transitional legacy tag for non-storage HTTPS\n// auxiliaries; new code SHOULD pick one of the three normative purposes.\n// `webhook` is the user-supplied-URL purpose: it triggers the SSRF guard\n// (DNS resolution + IP range check + connection pinning + redirect-chain\n// re-checking + body-size cap), and MUST be used for any fetch where the\n// target URL came from end-user input.\nexport type HttpPurpose = 'cardano' | 'arweave' | 'ipfs' | 'https' | 'webhook';\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface FetchOutboundOptions {\n readonly method: HttpMethod;\n readonly purpose: HttpPurpose;\n readonly headers?: Readonly<Record<string, string>>;\n readonly body?: string;\n // Hard cap on the response body the primitive will buffer. Gateway content\n // (ar:// / ipfs:// / https) is producer-chosen and therefore UNTRUSTED — the\n // verifier never trusts the producer — so a malicious gateway could otherwise\n // stream unbounded bytes into memory. Omit to use DEFAULT_OUTBOUND_MAX_BYTES.\n readonly maxBytes?: number;\n}\n\nexport interface FetchOutboundResult {\n readonly status: number;\n readonly bytes: Uint8Array;\n readonly durationMs: number;\n}\n\nexport type FetchOutbound = (\n url: string,\n opts: FetchOutboundOptions,\n) => Promise<FetchOutboundResult>;\n\n// Audit-log entry for one outbound HTTP fetch. Field names are snake_case so\n// the record can land directly on `VerifyReport.http_calls[]` (which IS the\n// wire shape) without a key-renaming pass.\nexport interface HttpCallRecord {\n readonly url: string;\n readonly method: HttpMethod;\n readonly status: number;\n readonly bytes: number;\n readonly duration_ms: number;\n readonly purpose: HttpPurpose;\n}\n\nexport interface RetryConfig {\n readonly timeoutMs?: number;\n readonly retries?: number;\n readonly retryableStatuses?: ReadonlyArray<number>;\n}\n\nexport interface WrapFetchOutboundConfig extends RetryConfig {\n readonly denyHosts?: ReadonlyArray<string>;\n}\n\nexport class DenyHostError extends Error {\n readonly code = 'SERVICE_INDEPENDENCE_VIOLATION';\n readonly host: string;\n readonly url: string;\n constructor(host: string, url: string) {\n super(`SERVICE_INDEPENDENCE_VIOLATION: host \"${host}\" is in denyHosts (url=${url})`);\n this.name = 'DenyHostError';\n this.host = host;\n this.url = url;\n }\n}\n\nexport class UnsupportedProtocolError extends Error {\n readonly code = 'UNSUPPORTED_PROTOCOL';\n readonly protocol: string;\n readonly url: string;\n constructor(protocol: string, url: string) {\n super(`UNSUPPORTED_PROTOCOL: \"${protocol}\" not in {http:, https:} (url=${url})`);\n this.name = 'UnsupportedProtocolError';\n this.protocol = protocol;\n this.url = url;\n }\n}\n\nexport class UnsupportedMethodError extends Error {\n readonly code = 'UNSUPPORTED_METHOD';\n readonly method: string;\n readonly url: string;\n constructor(method: string, url: string) {\n super(`UNSUPPORTED_METHOD: \"${method}\" not in {GET, POST} (url=${url})`);\n this.name = 'UnsupportedMethodError';\n this.method = method;\n this.url = url;\n }\n}\n\nexport class BodyTooLargeError extends Error {\n readonly code = 'OUTBOUND_BODY_TOO_LARGE';\n readonly url: string;\n readonly limitBytes: number;\n constructor(url: string, limitBytes: number) {\n super(`OUTBOUND_BODY_TOO_LARGE: response exceeded ${limitBytes} bytes (url=${url})`);\n this.name = 'BodyTooLargeError';\n this.url = url;\n this.limitBytes = limitBytes;\n }\n}\n\nexport class OutboundExhaustedError extends Error {\n readonly code = 'OUTBOUND_EXHAUSTED';\n readonly url: string;\n readonly attempts: number;\n readonly lastStatus: number | undefined;\n readonly lastError: Error | undefined;\n constructor(args: {\n url: string;\n attempts: number;\n lastStatus?: number | undefined;\n lastError?: Error | undefined;\n }) {\n super(\n `OUTBOUND_EXHAUSTED: ${args.attempts} attempts exhausted (url=${args.url}, lastStatus=${args.lastStatus ?? '-'})`,\n );\n this.name = 'OutboundExhaustedError';\n this.url = args.url;\n this.attempts = args.attempts;\n this.lastStatus = args.lastStatus;\n this.lastError = args.lastError;\n }\n}\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n// Default response-body cap for the verifier's gateway fetches. 64 MiB sits\n// well above any single sealed-PoE ciphertext or merkle-leaf payload a verifier\n// would realistically recompute a hash over, while bounding the memory a hostile\n// gateway can force the verifier to allocate for one request. Callers that\n// legitimately handle larger content raise it per-call via `opts.maxBytes`.\nexport const DEFAULT_OUTBOUND_MAX_BYTES = 64 * 1024 * 1024;\nexport const DEFAULT_RETRYABLE_STATUSES: ReadonlyArray<number> = [502, 503, 504];\nconst BACKOFF_BASE_MS: ReadonlyArray<number> = [1000, 2000, 4000];\nconst JITTER_RATIO = 0.25;\n\nfunction canonicaliseHost(host: string): string {\n return host.replace(/^\\[/, '').replace(/\\]$/, '').replace(/\\.$/, '').toLowerCase();\n}\n\nexport function matchesDenyList(host: string, denyHosts: ReadonlyArray<string>): boolean {\n const h = canonicaliseHost(host);\n for (const raw of denyHosts) {\n const pattern = raw.replace(/\\.$/, '').toLowerCase();\n if (pattern.startsWith('*.')) {\n const suffix = pattern.slice(2);\n if (h.endsWith('.' + suffix)) return true;\n continue;\n }\n if (h === pattern) return true;\n if (pattern === 'localhost') {\n if (h === '::1' || h === '0.0.0.0' || h === '169.254.169.254') return true;\n }\n if (pattern === '127.0.0.1') {\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n }\n }\n return false;\n}\n\nfunction parseProtocol(url: string): string | null {\n try {\n return new URL(url).protocol;\n } catch {\n return null;\n }\n}\n\nfunction isAllowedMethod(method: string): method is HttpMethod {\n return method === 'GET' || method === 'POST';\n}\n\nfunction backoffJitteredMs(attemptIndex: number): number {\n const idx = Math.min(attemptIndex, BACKOFF_BASE_MS.length - 1);\n const base = BACKOFF_BASE_MS[idx] ?? BACKOFF_BASE_MS[BACKOFF_BASE_MS.length - 1]!;\n const jitter = 1 + (Math.random() - 0.5) * 2 * JITTER_RATIO;\n return base * jitter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport const defaultFetchOutbound: FetchOutbound = async (url, opts) => {\n const t0 = Date.now();\n const maxBytes = opts.maxBytes ?? DEFAULT_OUTBOUND_MAX_BYTES;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);\n const init: RequestInit = {\n method: opts.method,\n signal: controller.signal,\n };\n if (opts.headers) init.headers = { ...opts.headers };\n if (opts.body !== undefined) init.body = opts.body;\n try {\n // allow-raw-fetch: canonical defaultFetchOutbound — single egress point\n const res = await fetch(url, init);\n\n // Fast path: a truthful Content-Length over the cap lets us bail before\n // reading a single body byte. A lying/absent header is still caught by the\n // streaming counter below — the header is an optimisation, not the guard.\n const declared = res.headers.get('content-length');\n if (declared !== null) {\n const declaredLen = Number(declared);\n if (Number.isFinite(declaredLen) && declaredLen > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n }\n\n const bytes = await readBodyCapped(res, url, maxBytes, controller);\n return { status: res.status, bytes, durationMs: Date.now() - t0 };\n } finally {\n clearTimeout(timeout);\n }\n};\n\n// Stream the response body, aborting the underlying request the instant the\n// running byte count exceeds `maxBytes`. This is the actual OOM guard: a\n// gateway that withholds or lies about Content-Length still cannot make us\n// buffer more than the cap, because we stop reading and tear the socket down.\nasync function readBodyCapped(\n res: Response,\n url: string,\n maxBytes: number,\n controller: AbortController,\n): Promise<Uint8Array> {\n const body = res.body;\n if (body === null) {\n // No stream (e.g. a 204, or a fetch polyfill that buffered eagerly). Fall\n // back to arrayBuffer but still enforce the cap on the materialised length.\n const buf = await res.arrayBuffer();\n if (buf.byteLength > maxBytes) {\n throw new BodyTooLargeError(url, maxBytes);\n }\n return new Uint8Array(buf);\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value === undefined) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nexport function wrapFetchOutbound(\n inner: FetchOutbound,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig | ReadonlyArray<string> | undefined = undefined,\n): FetchOutbound {\n // Accept either a denyHosts array (positional) or the full config object.\n const normConfig: WrapFetchOutboundConfig =\n config === undefined\n ? {}\n : Array.isArray(config)\n ? { denyHosts: config as ReadonlyArray<string> }\n : (config as WrapFetchOutboundConfig);\n\n const denyHosts = normConfig.denyHosts ?? [];\n // Default retries=0 (single attempt). Callers opt in via explicit `retries`;\n // the top-level `fetchOutbound` entrypoint forwards caller config.\n const retries = normConfig.retries ?? 0;\n const retryableStatuses = normConfig.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES;\n\n return async (url, opts) => {\n // The `webhook` purpose has bespoke requirements (DNS pinning,\n // per-hop redirect re-checking, body-size cap) that the generic\n // wrapper cannot satisfy. Force callers to use `fetchWebhook`\n // instead of silently accepting the call here.\n if (opts.purpose === 'webhook') {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new Error(\n `webhook purpose must be sent via fetchWebhook, not fetchOutbound (url=${url})`,\n );\n }\n\n // Protocol allowlist.\n const protocol = parseProtocol(url);\n if (protocol !== 'http:' && protocol !== 'https:') {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedProtocolError(protocol ?? '', url);\n }\n\n // Method allowlist.\n if (!isAllowedMethod(opts.method)) {\n audit.push({\n url,\n method: 'GET',\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedMethodError(opts.method, url);\n }\n\n // Deny-list short-circuit.\n if (denyHosts.length > 0) {\n const host = new URL(url).hostname;\n if (matchesDenyList(host, denyHosts)) {\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: 0,\n purpose: opts.purpose,\n });\n throw new DenyHostError(canonicaliseHost(host), url);\n }\n }\n\n // Retry loop. retries=0 → single attempt, return-or-rethrow original.\n let lastStatus: number | undefined;\n let lastError: Error | undefined;\n const totalAttempts = retries + 1;\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n const t0 = Date.now();\n try {\n const result = await inner(url, opts);\n audit.push({\n url,\n method: opts.method,\n status: result.status,\n bytes: result.bytes.byteLength,\n duration_ms: result.durationMs,\n purpose: opts.purpose,\n });\n if (retryableStatuses.includes(result.status) && retries > 0) {\n lastStatus = result.status;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n return result;\n } catch (e) {\n const durationMs = Date.now() - t0;\n if (\n e instanceof DenyHostError ||\n e instanceof UnsupportedProtocolError ||\n e instanceof UnsupportedMethodError\n ) {\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: durationMs,\n purpose: opts.purpose,\n });\n throw e;\n }\n audit.push({\n url,\n method: opts.method,\n status: 0,\n bytes: 0,\n duration_ms: durationMs,\n purpose: opts.purpose,\n });\n lastError = e as Error;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n }\n // Single-attempt mode re-throws the original verbatim so callers can match\n // by identity; retry mode wraps the terminal failure in OutboundExhaustedError.\n if (retries === 0 && lastError !== undefined) {\n throw lastError;\n }\n throw new OutboundExhaustedError({ url, attempts: totalAttempts, lastStatus, lastError });\n };\n}\n\nexport async function fetchOutbound(\n url: string,\n opts: FetchOutboundOptions,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig = {},\n): Promise<FetchOutboundResult> {\n const wrapped = wrapFetchOutbound(defaultFetchOutbound, audit, config);\n return wrapped(url, opts);\n}\n","// Verifier-side URI fetching plus the canonical `fetchOutbound` re-exports.\n// Two concerns colocated:\n//\n// * `fetchItemCiphertext` — given a chunked `uris[]` from a record item or\n// merkle entry, reconstruct the URI, dispatch to the appropriate gateway\n// chain (ar:// → Arweave HTTPS rotation; ipfs:// → caller-supplied IPFS\n// rotation), and return the raw bytes. Per-attempt diagnostics surface\n// as `URI_FETCH_FAILED` warnings in the caller's sink; the chain-exhausted\n// terminal state throws `CONTENT_UNAVAILABLE` so the caller emits the\n// terminal verdict.\n//\n// * Canonical re-exports of `defaultFetchOutbound`, `wrapFetchOutbound`, et\n// al. from `../fetch/fetch-outbound.js`.\n\nimport type { FetchOutbound, VerifyUriCheck } from './types';\n\nexport {\n BodyTooLargeError,\n DEFAULT_OUTBOUND_MAX_BYTES,\n defaultFetchOutbound,\n DENY_HOSTS_DEFAULT,\n DenyHostError,\n fetchOutbound,\n OutboundExhaustedError,\n UnsupportedMethodError,\n UnsupportedProtocolError,\n wrapFetchOutbound,\n} from '../fetch/fetch-outbound';\nexport type { RetryConfig, WrapFetchOutboundConfig } from '../fetch/fetch-outbound';\n\n// Default Arweave gateway rotation.\nconst ARWEAVE_DEFAULTS: ReadonlyArray<string> = [\n 'https://arweave.net',\n 'https://ar-io.net',\n 'https://g8way.io',\n];\n\nconst ARWEAVE_TXID_RE = /^[A-Za-z0-9_-]{43}$/;\n\nexport interface FetchItemCiphertextArgs {\n // Reconstructed-from-chunks URI list (each entry is itself a chunk array).\n readonly uris: ReadonlyArray<ReadonlyArray<string>>;\n readonly arweaveGateways?: ReadonlyArray<string> | undefined;\n readonly ipfsGateways?: ReadonlyArray<string> | undefined;\n readonly fetchFn: FetchOutbound;\n // Caller-supplied sink for per-attempt URI diagnostics. Each gateway failure\n // appends a `{ok: false, reason}` entry; the successful gateway appends\n // `{ok: true}`.\n readonly uriChecksOut: VerifyUriCheck[];\n // Caller path: `items[i]` → `itemIndex`; `merkle[i]` → reuse the field for\n // mapping (the report's `uriChecks[]` is item-indexed for v1).\n readonly itemIndex: number;\n}\n\n// Returns the first gateway response whose status is 200. Individual gateway\n// failures are warnings; only chain-exhaustion raises the terminal\n// `CONTENT_UNAVAILABLE`. The closed v1 scheme set is `{ar://, ipfs://}`; any\n// other scheme has already been rejected by the structural validator as\n// `INVALID_URI` and is rejected here too as defence in depth\n// (`URI_TARGET_FORBIDDEN`).\nexport async function fetchItemCiphertext(args: FetchItemCiphertextArgs): Promise<Uint8Array> {\n const reconstructed = args.uris.map((chunks) => chunks.join(''));\n const candidate = reconstructed.find((u) => /^(ar|ipfs):\\/\\//.test(u));\n if (candidate === undefined) {\n // No in-set URI present — defence-in-depth rejection.\n for (const u of reconstructed) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: u,\n ok: false,\n reason: 'URI_TARGET_FORBIDDEN',\n });\n }\n throw new Error('URI_TARGET_FORBIDDEN');\n }\n\n if (candidate.startsWith('ar://')) {\n const txid = candidate.slice(5);\n if (!ARWEAVE_TXID_RE.test(txid)) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: 'INVALID_URI',\n });\n throw new Error('CONTENT_UNAVAILABLE');\n }\n const gateways =\n args.arweaveGateways && args.arweaveGateways.length > 0\n ? args.arweaveGateways\n : ARWEAVE_DEFAULTS;\n for (const gw of gateways) {\n try {\n const res = await args.fetchFn(`${gw}/${txid}`, { method: 'GET', purpose: 'arweave' });\n if (res.status === 200) {\n args.uriChecksOut.push({ item_index: args.itemIndex, uri: candidate, ok: true });\n return res.bytes;\n }\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${res.status}`,\n });\n } catch (e) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n throw new Error('CONTENT_UNAVAILABLE');\n }\n\n // ipfs:// — caller MUST configure an IPFS gateway chain. No baked-in\n // defaults: IPFS gateways are not the producer's storage provider, and a\n // silent fallback would couple the verifier to an off-record gateway.\n const cidPart = candidate.slice('ipfs://'.length);\n const ipfsCid = cidPart.split('/')[0] ?? cidPart;\n const ipfsGateways = args.ipfsGateways;\n if (ipfsGateways === undefined || ipfsGateways.length === 0) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: 'CONTENT_UNAVAILABLE:no_ipfs_gateway',\n });\n throw new Error('CONTENT_UNAVAILABLE');\n }\n for (const gw of ipfsGateways) {\n try {\n const sep = gw.endsWith('/') ? '' : '/';\n const url = `${gw}${sep}ipfs/${ipfsCid}`;\n const res = await args.fetchFn(url, { method: 'GET', purpose: 'ipfs' });\n if (res.status === 200) {\n args.uriChecksOut.push({ item_index: args.itemIndex, uri: candidate, ok: true });\n return res.bytes;\n }\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${res.status}`,\n });\n } catch (e) {\n args.uriChecksOut.push({\n item_index: args.itemIndex,\n uri: candidate,\n ok: false,\n reason: `URI_FETCH_FAILED:${gw}:${e instanceof Error ? e.message : String(e)}`,\n });\n }\n }\n throw new Error('CONTENT_UNAVAILABLE');\n}\n","// Sealed-PoE decryption.\n//\n// Two mutually-exclusive on-wire paths:\n// * `enc.slots[]` (sealed-recipient, X25519 ECIES) — invokes\n// `eciesSealedPoeUnwrap` from `@cardanowall/crypto-core/sealed-poe`.\n// * `enc.passphrase` (Argon2id-derived CEK) — derives the CEK and runs\n// the AEAD primitive directly (empty AAD on the passphrase path).\n//\n// After successful unwrap (either path), the verifier recomputes every\n// content-hash entry in `item.hashes` and compares to the recovered plaintext.\n// Mismatch surfaces as `URI_INTEGRITY_MISMATCH`.\n\nimport { argon2idV13 } from '@cardanowall/crypto-core/kdf';\nimport { xchacha20Poly1305Decrypt, AeadVerificationError } from '@cardanowall/crypto-core/aead';\nimport { blake2b256, sha256 } from '@cardanowall/crypto-core/hash';\nimport {\n eciesSealedPoeUnwrap,\n sealedEnvelopeFromParsed,\n} from '@cardanowall/crypto-core/sealed-poe';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { ItemEntry, PoeRecord } from '@cardanowall/poe-standard';\n\nimport { fetchItemCiphertext } from './fetch';\nimport type {\n DecryptionVerdict,\n FetchOutbound,\n HttpCallRecord,\n VerifyItemDecryption,\n VerifyTxInput,\n VerifyUriCheck,\n} from './types';\n\n// The v1 passphrase KDF registry has a single member.\nconst PASSPHRASE_KDF_ARGON2ID = 'argon2id' as const;\n\n// Content-AEAD AAD is an empty bstr on the passphrase path.\nconst EMPTY_AAD = new Uint8Array(0);\n\nexport interface TryDecryptionsArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n readonly httpCalls: HttpCallRecord[];\n readonly uriChecksOut: VerifyUriCheck[];\n // When `false`, the verifier is running offline: it MUST NOT fetch a sealed\n // item's on-record `uris[]` ciphertext. Decryption then succeeds only for\n // items whose ciphertext the caller supplied out-of-band (`ciphertextBytes`);\n // others surface as `ciphertext-unavailable` with no outbound egress.\n readonly allowUriFetch: boolean;\n}\n\nexport interface TryDecryptionsResult {\n readonly results: VerifyItemDecryption[];\n}\n\nexport async function tryDecryptions(args: TryDecryptionsArgs): Promise<TryDecryptionsResult> {\n const { record, input } = args;\n const items = (record.items ?? []) as ItemEntry[];\n const out: VerifyItemDecryption[] = [];\n const reqs = input.decryption ?? [];\n\n for (const req of reqs) {\n const idx = req.itemIndex;\n if (!Number.isInteger(idx) || idx < 0 || idx >= items.length) {\n out.push({\n item_index: idx,\n verdict: 'no-enc-envelope',\n reason: 'itemIndex out of range',\n });\n continue;\n }\n const item = items[idx]!;\n const enc = item.enc as unknown;\n if (enc === undefined || enc === null || typeof enc !== 'object') {\n out.push({ item_index: idx, verdict: 'no-enc-envelope' });\n continue;\n }\n const encShape = enc as {\n readonly slots?: unknown;\n readonly passphrase?: unknown;\n };\n const hasSlots = Array.isArray(encShape.slots);\n const hasPassphrase = encShape.passphrase !== undefined && encShape.passphrase !== null;\n const reqHasSecret = 'recipientSecretKey' in req;\n const reqHasPassphrase = 'passphrase' in req;\n if (hasSlots && !reqHasSecret) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n if (hasPassphrase && !reqHasPassphrase) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n\n // Ciphertext acquisition: out-of-band bytes first, then (when fetching is\n // allowed) on-record `item.uris[]`, then `CIPHERTEXT_UNAVAILABLE`. Offline\n // mode (`allowUriFetch === false`) never reaches the network branch.\n const oobBytes = input.ciphertextBytes?.[idx];\n let ciphertext: Uint8Array | null;\n if (oobBytes !== undefined) {\n ciphertext = oobBytes;\n } else if (args.allowUriFetch && Array.isArray(item.uris) && item.uris.length > 0) {\n try {\n ciphertext = await fetchItemCiphertext({\n uris: item.uris as ReadonlyArray<ReadonlyArray<string>>,\n arweaveGateways: input.arweaveGatewayChain,\n ipfsGateways: input.ipfsGatewayChain,\n fetchFn: args.fetchFn,\n uriChecksOut: args.uriChecksOut,\n itemIndex: idx,\n });\n } catch (e) {\n const code = e instanceof Error ? e.message : 'CONTENT_UNAVAILABLE';\n const verdict: DecryptionVerdict =\n code === 'URI_TARGET_FORBIDDEN' ? 'ciphertext-unavailable' : 'content-unavailable';\n out.push({ item_index: idx, verdict, reason: code });\n continue;\n }\n } else {\n out.push({\n item_index: idx,\n verdict: 'ciphertext-unavailable',\n reason: 'CIPHERTEXT_UNAVAILABLE',\n });\n continue;\n }\n if (ciphertext === null) {\n out.push({\n item_index: idx,\n verdict: 'ciphertext-unavailable',\n reason: 'CIPHERTEXT_UNAVAILABLE',\n });\n continue;\n }\n\n let plaintext: Uint8Array | null = null;\n let failure: { verdict: DecryptionVerdict; reason: string } | null = null;\n if (reqHasSecret) {\n // Build the discriminated SealedEnvelope from the on-wire `enc` block,\n // dispatching on `enc.kem` (classical `{epk, wrap}` vs hybrid\n // `{kem_ct, wrap}`). A null result means the envelope isn't a sealed\n // recipient envelope we can unwrap — surface it as wrong-input-shape.\n const envelope = sealedEnvelopeFromParsed(\n enc as Parameters<typeof sealedEnvelopeFromParsed>[0],\n );\n if (envelope === null) {\n out.push({\n item_index: idx,\n verdict: 'wrong-input-shape',\n reason: 'WRONG_DECRYPTION_INPUT_SHAPE',\n });\n continue;\n }\n // ECIES sealed-PoE unwrap. The single-priv standalone-verifier form takes\n // the one secret matching the envelope's KEM (X25519 priv for classical,\n // X-Wing secret seed for hybrid); the per-slot loop inside dispatches on\n // `envelope.kem`. The helper returns a discriminated result — never throws\n // on auth failure.\n const unwrap = eciesSealedPoeUnwrap({\n envelope,\n ciphertext,\n recipientSecretKey: (req as { recipientSecretKey: Uint8Array }).recipientSecretKey,\n });\n if (unwrap.matched) {\n plaintext = unwrap.plaintext;\n } else {\n const map: Record<string, { verdict: DecryptionVerdict; reason: string }> = {\n WRONG_RECIPIENT_KEY: { verdict: 'wrong-key', reason: 'WRONG_RECIPIENT_KEY' },\n TAMPERED_HEADER: { verdict: 'tampered-header', reason: 'TAMPERED_HEADER' },\n TAMPERED_CIPHERTEXT: { verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' },\n };\n failure = map[unwrap.reason] ?? {\n verdict: 'tampered-ciphertext',\n reason: 'TAMPERED_CIPHERTEXT',\n };\n }\n } else {\n try {\n plaintext = await decryptPassphrase({\n enc: enc as PassphraseEncEnvelope,\n ciphertext,\n passphrase: (req as { passphrase: string }).passphrase,\n });\n } catch (e) {\n if (e instanceof AeadVerificationError) {\n failure = { verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' };\n } else if (e instanceof Error && e.message.startsWith('KDF_')) {\n failure = { verdict: 'kdf-failed', reason: e.message };\n } else {\n failure = {\n verdict: 'tampered-ciphertext',\n reason: e instanceof Error ? e.message : 'TAMPERED_CIPHERTEXT',\n };\n }\n }\n }\n\n if (failure !== null) {\n out.push({ item_index: idx, verdict: failure.verdict, reason: failure.reason });\n continue;\n }\n if (plaintext === null) {\n // Defensive — failure path should already have returned above.\n out.push({ item_index: idx, verdict: 'tampered-ciphertext', reason: 'TAMPERED_CIPHERTEXT' });\n continue;\n }\n\n // Post-unwrap plaintext-hash recompute: re-hash the recovered plaintext\n // under every content-hash entry the item carries and compare. Every\n // `enc`-bearing item carries at least one content-hash entry (the\n // structural validator enforces ENC_REQUIRES_CONTENT_HASH), so this is a\n // concrete boolean on successful decryption.\n const plaintextHashOk = recomputeHashes(item, plaintext);\n out.push({ item_index: idx, verdict: 'decrypted', plaintext_hash_ok: plaintextHashOk });\n }\n\n return { results: out };\n}\n\ninterface PassphraseEncEnvelope {\n readonly scheme: number;\n readonly aead: string;\n readonly nonce: Uint8Array;\n readonly passphrase: {\n readonly alg: string;\n readonly salt: Uint8Array;\n readonly params: { readonly m: number; readonly t: number; readonly p: number };\n };\n}\n\nasync function decryptPassphrase(args: {\n enc: PassphraseEncEnvelope;\n ciphertext: Uint8Array;\n passphrase: string;\n}): Promise<Uint8Array> {\n const { enc, ciphertext, passphrase } = args;\n if (enc.passphrase.alg !== PASSPHRASE_KDF_ARGON2ID) {\n throw new Error(`KDF_DERIVATION_FAILED: unsupported passphrase alg ${enc.passphrase.alg}`);\n }\n // Passphrase normalisation: NFKC → collapse whitespace → trim → UTF-8. Must\n // match the producer's normalisation exactly or the derived CEK won't match.\n const normalised = passphrase.normalize('NFKC').replace(/\\s+/g, ' ').trim();\n const password = new TextEncoder().encode(normalised);\n let cek: Uint8Array;\n try {\n cek = await argon2idV13({\n password,\n salt: enc.passphrase.salt,\n memSizeKB: enc.passphrase.params.m,\n iterations: enc.passphrase.params.t,\n parallelism: enc.passphrase.params.p,\n outBytes: 32,\n });\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n throw new Error(`KDF_DERIVATION_FAILED: ${reason}`, { cause });\n }\n if (enc.aead !== 'xchacha20-poly1305') {\n throw new Error(`KDF_DERIVATION_FAILED: unsupported aead ${enc.aead}`);\n }\n return xchacha20Poly1305Decrypt({\n key: cek,\n nonce: enc.nonce,\n aad: EMPTY_AAD,\n ciphertext,\n });\n}\n\nfunction recomputeHashes(item: ItemEntry, plaintext: Uint8Array): boolean {\n // `item.hashes` is a text-keyed map of algorithm id → expected digest;\n // cbor2 surfaces it as a plain JS object. The recovered plaintext is\n // \"hash-ok\" only when there is at least one entry AND every entry names a\n // hash we can recompute AND its digest matches. An empty map, or any entry\n // whose alg we don't recognise, is NOT silently treated as a pass: returning\n // `true` there would vacuously certify ciphertext whose integrity we never\n // actually checked. (Mirrors the CLI's `recomputeItemHashes`, which returns\n // `UNSUPPORTED_HASH_ALG` on an unknown alg.)\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) return false;\n for (const [alg, digest] of entries) {\n if (alg === 'sha2-256') {\n if (!compareCt(sha256(plaintext), digest)) return false;\n } else if (alg === 'blake2b-256') {\n if (!compareCt(blake2b256(plaintext), digest)) return false;\n } else {\n // Unknown/unsupported hash alg — cannot certify integrity.\n return false;\n }\n }\n return true;\n}\n","// Canonical-CBOR codec for the off-chain Merkle leaves-list artefact.\n// The on-chain `merkle[]` field binds to this file via `uris[]` / `leaf_count`;\n// the file itself carries the full leaf set. Canonical CBOR is RFC 8949 §4.2.1.\n//\n// CDDL:\n//\n// leaves-list = {\n// \"format\": \"cardano-poe-merkle-leaves-v1\",\n// \"tree_alg\": \"rfc9162-sha256\",\n// \"root\": bytes .size 32,\n// \"leaves\": [ + bytes .size 32 ],\n// \"leaf_count\": uint,\n// ? \"leaf_alg\": tstr,\n// }\n//\n// Canonical ordering is bytewise-lexicographic on encoded map keys (RFC 8949\n// §4.2.1) so the wire-key order is fixed by `cde:true` regardless of insertion\n// order: root (4B) < format (6B) < leaves (6B) < leaf_alg (8B) < tree_alg (8B)\n// < leaf_count (10B).\n\nimport { decodeCanonicalCbor, encodeCanonicalCbor } from '../cbor/canonical';\nimport { compareCt } from '../util/compare-ct';\nimport { merkleSha2256Root } from '../hash/merkle-sha2-256';\n\nexport const LEAVES_LIST_FORMAT_V1 = 'cardano-poe-merkle-leaves-v1' as const;\nconst TREE_ALG_RFC9162 = 'rfc9162-sha256' as const;\nconst DIGEST_LENGTH = 32;\nconst REGISTERED_FORMATS = new Set<string>([LEAVES_LIST_FORMAT_V1]);\n\nexport type MerkleLeavesListErrorCode =\n | 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED'\n | 'SCHEMA_MERKLE_LEAVES_MALFORMED'\n | 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH'\n | 'MERKLE_ROOT_MISMATCH';\n\nexport class MerkleLeavesListError extends Error {\n readonly code: MerkleLeavesListErrorCode;\n constructor(code: MerkleLeavesListErrorCode, message?: string) {\n super(message ? `${code}: ${message}` : code);\n this.code = code;\n this.name = 'MerkleLeavesListError';\n }\n}\n\nexport interface EncodeLeavesListArgs {\n readonly leaves: ReadonlyArray<Uint8Array>;\n readonly root: Uint8Array;\n readonly leafAlg?: string;\n}\n\nexport interface DecodedLeavesList {\n readonly format: typeof LEAVES_LIST_FORMAT_V1;\n readonly treeAlg: typeof TREE_ALG_RFC9162;\n readonly root: Uint8Array;\n readonly leaves: Uint8Array[];\n readonly leafCount: number;\n readonly leafAlg?: string;\n}\n\nexport function encodeLeavesList(args: EncodeLeavesListArgs): Uint8Array {\n if (!(args.root instanceof Uint8Array) || args.root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n if (args.leaves.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves array must be non-empty',\n );\n }\n const leavesCopy: Uint8Array[] = [];\n for (let i = 0; i < args.leaves.length; i++) {\n const leaf = args.leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n leavesCopy.push(leaf);\n }\n if (args.leafAlg !== undefined && typeof args.leafAlg !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a string when present',\n );\n }\n const map: Record<string, unknown> = {\n format: LEAVES_LIST_FORMAT_V1,\n tree_alg: TREE_ALG_RFC9162,\n root: args.root,\n leaves: leavesCopy,\n leaf_count: leavesCopy.length,\n };\n if (args.leafAlg !== undefined) {\n map['leaf_alg'] = args.leafAlg;\n }\n return encodeCanonicalCbor(map as never);\n}\n\nexport function decodeLeavesList(bytes: Uint8Array): DecodedLeavesList {\n const decoded = decodeCanonicalCbor(bytes);\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves-list MUST be a CBOR map',\n );\n }\n const m = decoded as Record<string, unknown>;\n\n const format = m['format'];\n if (typeof format !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'format must be a text string',\n );\n }\n if (!REGISTERED_FORMATS.has(format)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n `format '${format}' is not in the registered set`,\n );\n }\n\n const treeAlg = m['tree_alg'];\n if (treeAlg !== TREE_ALG_RFC9162) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `tree_alg '${String(treeAlg)}' is not '${TREE_ALG_RFC9162}'`,\n );\n }\n\n const root = m['root'];\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n\n const leavesRaw = m['leaves'];\n if (!Array.isArray(leavesRaw) || leavesRaw.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves must be a non-empty array',\n );\n }\n const leaves: Uint8Array[] = [];\n for (let i = 0; i < leavesRaw.length; i++) {\n const leaf = leavesRaw[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n leaves.push(leaf);\n }\n\n const leafCountRaw = m['leaf_count'];\n let leafCount: number;\n if (typeof leafCountRaw === 'number' && Number.isInteger(leafCountRaw) && leafCountRaw >= 0) {\n leafCount = leafCountRaw;\n } else if (typeof leafCountRaw === 'bigint' && leafCountRaw >= 0n) {\n if (leafCountRaw > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count exceeds Number.MAX_SAFE_INTEGER',\n );\n }\n leafCount = Number(leafCountRaw);\n } else {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count must be a non-negative CBOR uint',\n );\n }\n if (leaves.length !== leafCount) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n `leaves.length (${leaves.length}) != leaf_count (${leafCount})`,\n );\n }\n\n let leafAlg: string | undefined;\n if (m['leaf_alg'] !== undefined) {\n if (typeof m['leaf_alg'] !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a text string when present',\n );\n }\n leafAlg = m['leaf_alg'];\n }\n\n const recomputed = merkleSha2256Root(leaves);\n if (!compareCt(recomputed, root)) {\n throw new MerkleLeavesListError(\n 'MERKLE_ROOT_MISMATCH',\n 'leaves recompute does not match declared root',\n );\n }\n\n const out: DecodedLeavesList = {\n format: LEAVES_LIST_FORMAT_V1,\n treeAlg: TREE_ALG_RFC9162,\n root,\n leaves,\n leafCount,\n ...(leafAlg !== undefined ? { leafAlg } : {}),\n };\n return out;\n}\n","// Merkle list-commitment verification.\n//\n// For each `record.merkle[i]` the verifier:\n// 1. Acquires the leaves-list document (caller-supplied or fetched via the\n// first ar://-or-ipfs:// URI in `merkle[i].uris[]`).\n// 2. Decodes the normative CBOR leaves-list wire form via crypto-core's\n// `decodeLeavesList` (which also recomputes the canonical RFC 9162 root\n// defence-in-depth and surfaces `MERKLE_ROOT_MISMATCH` /\n// `SCHEMA_MERKLE_LEAF_COUNT_MISMATCH`).\n// 3. Compares the on-record `merkle[i].root` byte-exact to the recomputed\n// root via `compareCt`.\n//\n// Per-attempt URI failures are warnings (`URI_FETCH_FAILED`); the per-commit\n// verdict on chain-exhaustion is `MERKLE_LEAVES_UNAVAILABLE` — a warning, NOT\n// escalated to `'failed'`, because the on-chain root alone is structurally\n// valid.\n\nimport { merkleSha2256Root } from '@cardanowall/crypto-core/hash';\nimport { decodeLeavesList, MerkleLeavesListError } from '@cardanowall/crypto-core/merkle';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { MerkleCommit, PoeRecord } from '@cardanowall/poe-standard';\n\nimport { fetchItemCiphertext } from './fetch';\nimport type { FetchOutbound, VerifyMerkleCheck, VerifyTxInput, VerifyUriCheck } from './types';\n\nexport interface VerifyMerkleArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n readonly uriChecksOut: VerifyUriCheck[];\n}\n\nexport interface VerifyMerkleResult {\n readonly checks: VerifyMerkleCheck[];\n}\n\nexport async function verifyMerkleCommitments(args: VerifyMerkleArgs): Promise<VerifyMerkleResult> {\n const merkleArr = (args.record.merkle ?? []) as MerkleCommit[];\n const out: VerifyMerkleCheck[] = [];\n for (let i = 0; i < merkleArr.length; i++) {\n out.push(await verifyOneCommit(i, merkleArr[i]!, args));\n }\n return { checks: out };\n}\n\nasync function verifyOneCommit(\n index: number,\n commit: MerkleCommit,\n args: VerifyMerkleArgs,\n): Promise<VerifyMerkleCheck> {\n // v1 registers exactly one Merkle commitment algorithm. The structural\n // validator already rejects unknown algs; this is defence-in-depth.\n if (commit.alg !== 'rfc9162-sha256') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unsupported',\n reason: 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n };\n }\n\n // Leaves-list acquisition: caller-supplied bytes first, then the first\n // ar://-or-ipfs:// URI in `merkle[i].uris[]`.\n let leavesBytes: Uint8Array | null = args.input.merkleLeaves?.[index] ?? null;\n if (leavesBytes === null) {\n const uris = commit.uris;\n if (uris === undefined || uris.length === 0) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: 'MERKLE_LEAVES_UNAVAILABLE',\n };\n }\n try {\n leavesBytes = await fetchItemCiphertext({\n uris,\n arweaveGateways: args.input.arweaveGatewayChain,\n ipfsGateways: args.input.ipfsGatewayChain,\n fetchFn: args.fetchFn,\n uriChecksOut: args.uriChecksOut,\n // Merkle commits are not item-indexed; reuse a sentinel index so\n // downstream UIs can distinguish them from item URIs.\n itemIndex: -1 - index,\n });\n } catch {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: 'MERKLE_LEAVES_UNAVAILABLE',\n };\n }\n }\n\n // Decode the leaves-list document. `decodeLeavesList` enforces format,\n // tree_alg, leaf-count match, and recomputes the root for defence-in-depth;\n // any failure surfaces as a typed error code.\n try {\n const decoded = decodeLeavesList(leavesBytes);\n // Compare the on-record root to the recomputed root byte-exact.\n const recomputed = merkleSha2256Root(decoded.leaves);\n if (!compareCt(recomputed, commit.root)) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'MERKLE_ROOT_MISMATCH',\n root_recomputed: recomputed,\n };\n }\n if (decoded.leafCount !== commit.leaf_count) {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'valid',\n root_recomputed: recomputed,\n };\n } catch (e) {\n if (e instanceof MerkleLeavesListError) {\n if (e.code === 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'format-unsupported',\n reason: 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n };\n }\n if (e.code === 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n };\n }\n if (e.code === 'MERKLE_ROOT_MISMATCH') {\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'mismatch',\n reason: 'MERKLE_ROOT_MISMATCH',\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: e.code,\n };\n }\n return {\n merkle_index: index,\n alg: commit.alg,\n verdict: 'unavailable',\n reason: e instanceof Error ? e.message : String(e),\n };\n }\n}\n","// Conformance-profile helpers.\n//\n// A `core`-profile verifier reading a record that carries `sigs`, `enc`, or\n// `merkle` MUST emit `OUT_OF_PROFILE_SKIPPED` (info severity) per affected\n// field — NOT `SCHEMA_UNKNOWN_FIELD` (which applies only to fields outside\n// the v1 CDDL). This rule lets a block explorer shipping only the `core`\n// surface still surface every conformant v1 record regardless of which\n// extensions it carries.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { Profile } from './types';\nimport { PROFILE_RANK } from './types';\n\nexport const DEFAULT_PROFILE: Profile = 'recipient-sealed';\n\nexport function profileImplements(actual: Profile, required: Profile): boolean {\n return PROFILE_RANK[actual] >= PROFILE_RANK[required];\n}\n\nexport interface ProfileSkipsResult {\n // info-severity entries emitted when a field belongs to a higher profile\n // than the active one. Surfaces in `validation.info`.\n readonly skips: ValidationIssue[];\n // Convenience flags for the verifier pipeline (whether to enter each\n // sub-pipeline at all).\n readonly verifySignatures: boolean;\n readonly verifyDecrypt: boolean;\n}\n\n/**\n * Emit the minimum conformance profile a verifier MUST implement\n * to read this record end-to-end. The profiles form a strict superset chain\n * `core ⊂ signed ⊂ sealed ⊂ recipient-sealed`.\n *\n * The function classifies based on RECORD CONTENT only:\n * - `'core'` — no signatures, no sealed items.\n * - `'signed'` — `record.sigs[]` is present, no sealed items.\n * - `'sealed'` — any `record.items[i].enc` is present (with or without sigs).\n *\n * The function does NOT return `'recipient-sealed'`: that profile is about\n * VERIFIER CAPABILITY (whether the verifier decrypts with a recipient X25519\n * key), not about record content. A separate helper is required if a caller\n * needs to test whether a particular recipient key can unwrap any slot — see\n * `@cardanowall/crypto-core/sealed-poe` for that pathway.\n */\nexport function detectConformanceProfile(record: PoeRecord): 'core' | 'signed' | 'sealed' {\n const hasSealedItem =\n Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined);\n if (hasSealedItem) return 'sealed';\n const hasSigs = Array.isArray(record.sigs) && record.sigs.length > 0;\n if (hasSigs) return 'signed';\n return 'core';\n}\n\nexport function planProfileSkips(profile: Profile, record: PoeRecord): ProfileSkipsResult {\n const skips: ValidationIssue[] = [];\n const has = (k: string): boolean => Object.prototype.hasOwnProperty.call(record, k);\n const verifySignatures = PROFILE_RANK[profile] >= PROFILE_RANK['signed'];\n // The `sealed` rank gates whether the verifier reads the enc envelope at all.\n // There is no separate `sealed`-only sub-pipeline distinct from decryption,\n // so this drives only the skip-emission below rather than a returned flag.\n const readsEnc = PROFILE_RANK[profile] >= PROFILE_RANK['sealed'];\n const verifyDecrypt = PROFILE_RANK[profile] >= PROFILE_RANK['recipient-sealed'];\n\n if (!verifySignatures && has('sigs')) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['sigs'],\n message: `sigs[] requires profile >= 'signed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n if (!readsEnc && Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined)) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['items', 'enc'],\n message: `items[].enc requires profile >= 'sealed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n return { skips, verifySignatures, verifyDecrypt };\n}\n","// Position-aware CBOR walker for byte-faithful label-309 metadata extraction.\n//\n// The verifier MUST fetch raw transaction CBOR and extract the label-309\n// value VERBATIM (not via decode-then-re-encode). A\n// re-encode pass would silently launder a non-conformant on-chain record into\n// a conformant one because cbor2's decoder normalises non-canonical input\n// (sorts map keys, collapses indefinite-length encodings, etc.); the\n// structural validator's canonical-CBOR check (`decodeCanonicalCbor` +\n// cbor2 CDE options) only catches the violation if it sees the producer's\n// original bytes.\n//\n// Pure stdlib walker (no `cbor2` dependency for the slicing path). Rejects\n// indefinite-length encodings, which canonical CBOR forbids; the structural\n// validator downstream performs the rest of the deterministic-encoding checks.\n\ninterface CborHead {\n readonly mt: number;\n readonly ai: number;\n readonly payloadStart: number;\n readonly valueU64: number;\n}\n\nfunction readHead(bytes: Uint8Array, pos: number): CborHead {\n if (pos >= bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated input (no head byte)');\n }\n const head = bytes[pos]!;\n const mt = head >> 5;\n const ai = head & 0x1f;\n let p = pos + 1;\n let valueU64: number;\n\n if (ai < 24) {\n valueU64 = ai;\n } else if (ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 1-byte argument');\n }\n valueU64 = bytes[p]!;\n p += 1;\n } else if (ai === 25) {\n if (p + 2 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 2-byte argument');\n }\n valueU64 = (bytes[p]! << 8) | bytes[p + 1]!;\n p += 2;\n } else if (ai === 26) {\n if (p + 4 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 4-byte argument');\n }\n valueU64 =\n bytes[p]! * 0x1000000 + ((bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!);\n p += 4;\n } else if (ai === 27) {\n if (p + 8 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 8-byte argument');\n }\n let n = 0;\n for (let k = 0; k < 8; k++) n = n * 256 + bytes[p + k]!;\n if (n > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('MALFORMED_CBOR: 8-byte argument exceeds JavaScript safe integer range');\n }\n valueU64 = n;\n p += 8;\n } else if (ai === 31) {\n throw new RangeError(\n 'MALFORMED_CBOR: indefinite-length encoding (ai=31) not allowed under canonical CBOR',\n );\n } else {\n throw new RangeError(`MALFORMED_CBOR: reserved additional info ai=${ai}`);\n }\n\n return { mt, ai, payloadStart: p, valueU64 };\n}\n\nfunction skipCborItem(bytes: Uint8Array, pos: number): number {\n const h = readHead(bytes, pos);\n let p = h.payloadStart;\n switch (h.mt) {\n case 0:\n case 1:\n return p;\n case 2:\n case 3:\n if (p + h.valueU64 > bytes.length) {\n throw new RangeError(\n `MALFORMED_CBOR: truncated ${h.mt === 2 ? 'byte' : 'text'} string payload`,\n );\n }\n return p + h.valueU64;\n case 4:\n for (let i = 0; i < h.valueU64; i++) p = skipCborItem(bytes, p);\n return p;\n case 5:\n for (let i = 0; i < h.valueU64 * 2; i++) p = skipCborItem(bytes, p);\n return p;\n case 6:\n return skipCborItem(bytes, p);\n case 7: {\n if (h.ai < 24) return p;\n if (h.ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated simple value');\n }\n return p + 1;\n }\n if (h.ai === 25 || h.ai === 26 || h.ai === 27) return p;\n throw new RangeError(`MALFORMED_CBOR: unsupported major-7 ai=${h.ai}`);\n }\n default:\n throw new RangeError(`MALFORMED_CBOR: unknown major type ${h.mt}`);\n }\n}\n\n// CBOR tag 259 wraps post-Alonzo auxiliary_data (CIP-29).\nconst CARDANO_AUX_DATA_TAG = 259;\nconst POE_LABEL = 309;\n\n/**\n * Byte-faithful components of a Cardano transaction, located by walking the\n * tx CBOR without a decode-then-re-encode pass.\n *\n * `txBody` and `witnessSet` are EXACT on-chain byte slices: `blake2b256(txBody)`\n * equals the transaction hash, and the witness set decodes to the vkey\n * witnesses that authorised the transaction. The slices are produced by the\n * same position-aware walk that finds label 309, so they never round-trip\n * through a CBOR re-encoder.\n *\n * `label309` is the reassembled label-309 value (chunked-bytes concatenated;\n * see `reassembleLabel309Value`), `null` when auxiliary_data is null/undefined\n * or label 309 is absent. `auxMetadataLabels` is the ascending-sorted list of\n * every integer key in the auxiliary metadata map (`[]` when aux is null).\n */\nexport interface TxComponents {\n readonly label309: Uint8Array | null;\n readonly txBody: Uint8Array;\n readonly witnessSet: Uint8Array;\n readonly auxMetadataLabels: number[];\n}\n\n/**\n * Walk the transaction CBOR once and return its byte-faithful components.\n *\n * Throws `RangeError(\"MALFORMED_CBOR: …\")` on structural violations. The body\n * and witness-set slices are the producer's ORIGINAL bytes; `label309` carries\n * the same byte-faithful guarantee `sliceLabel309Value` documents (no\n * decode-then-re-encode, so non-canonical encodings reach the structural\n * validator unchanged).\n */\nexport function sliceTxComponents(txCbor: Uint8Array): TxComponents {\n const txHead = readHead(txCbor, 0);\n if (txHead.mt !== 4) {\n throw new RangeError(`MALFORMED_CBOR: tx CBOR is not a CBOR array (major type ${txHead.mt})`);\n }\n if (txHead.valueU64 < 4) {\n throw new RangeError(\n `MALFORMED_CBOR: tx CBOR array has ${txHead.valueU64} elements; expected >= 4 (post-Conway: [body, witness_set, is_valid, auxiliary_data])`,\n );\n }\n\n const bodyStart = txHead.payloadStart;\n const bodyEnd = skipCborItem(txCbor, bodyStart);\n const witnessSetStart = bodyEnd;\n const witnessSetEnd = skipCborItem(txCbor, witnessSetStart);\n const pos = skipCborItem(txCbor, witnessSetEnd); // skip is_valid\n\n const txBody = txCbor.slice(bodyStart, bodyEnd);\n const witnessSet = txCbor.slice(witnessSetStart, witnessSetEnd);\n\n if (pos >= txCbor.length) {\n throw new RangeError('MALFORMED_CBOR: truncated tx (auxiliary_data missing)');\n }\n const auxFirstByte = txCbor[pos]!;\n if (auxFirstByte === 0xf6 || auxFirstByte === 0xf7) {\n return { label309: null, txBody, witnessSet, auxMetadataLabels: [] };\n }\n\n let auxMapPos = pos;\n const auxHead = readHead(txCbor, pos);\n if (auxHead.mt === 6) {\n if (auxHead.valueU64 !== CARDANO_AUX_DATA_TAG) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data carries unexpected CBOR tag ${auxHead.valueU64}; expected ${CARDANO_AUX_DATA_TAG} or bare map`,\n );\n }\n auxMapPos = auxHead.payloadStart;\n }\n\n const mapHead = readHead(txCbor, auxMapPos);\n if (mapHead.mt !== 5) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data is not a CBOR map (major type ${mapHead.mt})`,\n );\n }\n\n // Disambiguate the tagged (post-Alonzo, `{0 → metadata, 1 → ...}`) and bare\n // (pre-Alonzo, the map IS the metadata map directly) auxiliary_data shapes\n // by walking the map keys: if any int key in `{0,1,2,3}` is present, treat\n // it as the post-Alonzo shape and find key 0; else treat the whole map as\n // metadata directly. Modern Cardano txs (Conway+) are always tag-259\n // wrapped, but synthetic test fixtures often emit the post-Alonzo shape\n // bare and we want to handle both without forcing producers to add the tag.\n let metadataMapPos: number | null;\n {\n let entryPos = mapHead.payloadStart;\n let sawAuxKey = false;\n let foundMetadataAt: number | null = null;\n for (let i = 0; i < mapHead.valueU64; i++) {\n const keyHead = readHead(txCbor, entryPos);\n if (keyHead.mt === 0 && keyHead.valueU64 <= 3) {\n sawAuxKey = true;\n if (keyHead.valueU64 === 0) {\n foundMetadataAt = keyHead.payloadStart;\n }\n }\n entryPos = skipCborItem(txCbor, entryPos); // skip key\n entryPos = skipCborItem(txCbor, entryPos); // skip value\n }\n if (sawAuxKey || auxHead.mt === 6) {\n metadataMapPos = foundMetadataAt;\n } else {\n // Bare pre-Alonzo metadata map.\n metadataMapPos = auxMapPos;\n }\n }\n\n if (metadataMapPos === null) {\n return { label309: null, txBody, witnessSet, auxMetadataLabels: [] };\n }\n\n const metaHead = readHead(txCbor, metadataMapPos);\n if (metaHead.mt !== 5) {\n throw new RangeError(`MALFORMED_CBOR: metadata is not a CBOR map (major type ${metaHead.mt})`);\n }\n const labels: number[] = [];\n let label309: Uint8Array | null = null;\n let pairPos = metaHead.payloadStart;\n for (let i = 0; i < metaHead.valueU64; i++) {\n const keyHead = readHead(txCbor, pairPos);\n const keyVal = decodeIntKey(keyHead);\n labels.push(keyVal);\n const valueStart = skipCborItem(txCbor, pairPos);\n const valueEnd = skipCborItem(txCbor, valueStart);\n if (keyVal === POE_LABEL) {\n label309 = reassembleLabel309Value(txCbor, valueStart, valueEnd);\n }\n pairPos = valueEnd;\n }\n labels.sort((a, b) => a - b);\n return { label309, txBody, witnessSet, auxMetadataLabels: labels };\n}\n\n/**\n * Extract the byte slice corresponding to the value under metadata label 309.\n * Returns `null` when auxiliary_data is null/undefined or when label 309 is\n * absent. Throws `RangeError(\"MALFORMED_CBOR: …\")` on structural violations.\n *\n * Returns the producer's ORIGINAL on-chain bytes — no decode-then-re-encode\n * pass. The structural validator MUST receive these bytes verbatim so\n * non-canonical encodings surface as `MALFORMED_CBOR` rather than being\n * silently laundered.\n */\nexport function sliceLabel309Value(txCbor: Uint8Array): Uint8Array | null {\n return sliceTxComponents(txCbor).label309;\n}\n\n/**\n * Cardano caps individual metadata `bstr` / `tstr` values at 64 bytes\n * (Cardano metadata spec). A Label 309 PoE record's\n * canonical CBOR is typically several hundred bytes, so the producer emits\n * it as a `bytes-chunk-array` — `[ bstr .size (1..64), … ]` — at the\n * label-309 value position. The verifier MUST byte-concatenate the chunks\n * IN ORDER before passing the result to `validatePoeRecord`, otherwise\n * the canonical-CBOR decoder sees an outer CBOR array of byte strings\n * instead of the inner CBOR map and the record fails with\n * `SCHEMA_TYPE_MISMATCH` / `MALFORMED_CBOR`.\n *\n * Small records (≤ 64 bytes) MAY be emitted as a single `bstr` directly.\n * For backwards-compat we also accept a bare CBOR map value — older\n * producers and small synthetic fixtures use that shape.\n *\n * Returns the canonical-CBOR PoE record body (a `bstr`-free, map-rooted\n * byte sequence) ready for validation.\n */\nfunction reassembleLabel309Value(\n txCbor: Uint8Array,\n valueStart: number,\n valueEnd: number,\n): Uint8Array {\n const head = readHead(txCbor, valueStart);\n // Major type 4 = array → assume bytes-chunk-array; concatenate inner bstr items.\n if (head.mt === 4) {\n const out: Uint8Array[] = [];\n let totalLen = 0;\n let chunkPos = head.payloadStart;\n for (let i = 0; i < head.valueU64; i++) {\n const chunkHead = readHead(txCbor, chunkPos);\n if (chunkHead.mt !== 2) {\n throw new RangeError(\n `MALFORMED_CBOR: label-309 value is a CBOR array but element ${i} has major type ${chunkHead.mt}; expected byte string (chunked-bytes shape)`,\n );\n }\n const chunkValueStart = chunkHead.payloadStart;\n const chunkValueEnd = chunkValueStart + chunkHead.valueU64;\n out.push(txCbor.slice(chunkValueStart, chunkValueEnd));\n totalLen += chunkHead.valueU64;\n chunkPos = chunkValueEnd;\n }\n const concat = new Uint8Array(totalLen);\n let offset = 0;\n for (const c of out) {\n concat.set(c, offset);\n offset += c.length;\n }\n return concat;\n }\n // Major type 2 = single bstr value. The bstr CONTENTS are the canonical\n // CBOR record body — strip the bstr head so decodeCanonicalCbor sees the\n // map directly.\n if (head.mt === 2) {\n return txCbor.slice(head.payloadStart, head.payloadStart + head.valueU64);\n }\n // Major type 5 = map directly (bare-canonical shape; some synthetic\n // fixtures emit this when the record fits in one chunk and the producer\n // chose not to box it in a bstr). Pass through unchanged.\n if (head.mt === 5) {\n return txCbor.slice(valueStart, valueEnd);\n }\n throw new RangeError(\n `MALFORMED_CBOR: label-309 value has major type ${head.mt}; expected array (chunked), byte string, or map`,\n );\n}\n\nfunction decodeIntKey(h: CborHead): number {\n if (h.mt === 0) return h.valueU64;\n if (h.mt === 1) return -1 - h.valueU64;\n throw new RangeError(\n `MALFORMED_CBOR: metadata map key has major type ${h.mt}; expected unsigned integer`,\n );\n}\n","// Cardano gateway resolver — Koios first, then Blockfrost fallback if a\n// project ID is supplied. Returns the RAW on-chain transaction CBOR (NOT\n// the gateway's lossy JSON metadata projection — the verifier needs the\n// producer's original bytes to detect non-canonical encodings).\n\nimport { sliceLabel309Value } from './cbor-walker';\nimport type { FetchOutbound, VerifyTxInput } from './types';\n\nexport interface ResolvedTx {\n readonly txCbor: Uint8Array;\n readonly numConfirmations: number;\n readonly blockTime: number;\n readonly blockSlot: number;\n readonly provider: 'koios' | 'blockfrost';\n readonly providerUrl: string;\n}\n\nexport const KOIOS_MAINNET_URL = 'https://api.koios.rest/api/v1';\nexport const BLOCKFROST_MAINNET_HOST = 'https://cardano-mainnet.blockfrost.io/api/v0';\n\n// Distinct error class so the verifier can short-circuit the gateway-fallback\n// loop on a definitive \"this tx is not on chain / has no PoE metadata\"\n// response: a definitive negative from one gateway is authoritative, so there\n// is no point rotating to the next gateway.\nexport class NotALabel309RecordError extends Error {\n readonly code = 'METADATA_NOT_FOUND' as const;\n constructor(message: string) {\n super(message);\n this.name = 'NotALabel309RecordError';\n }\n}\n\nexport async function resolveCardanoTx(args: {\n readonly input: VerifyTxInput;\n readonly fetchFn: FetchOutbound;\n}): Promise<ResolvedTx> {\n const { input, fetchFn } = args;\n const koiosChain = input.cardanoGatewayChain ?? [KOIOS_MAINNET_URL];\n\n let lastErr: unknown;\n for (const koiosUrl of koiosChain) {\n try {\n return await resolveViaKoios(input.txHash, koiosUrl, fetchFn);\n } catch (e) {\n if (e instanceof NotALabel309RecordError) throw e;\n lastErr = e;\n }\n }\n\n if (input.blockfrostProjectId !== undefined) {\n try {\n return await resolveViaBlockfrost(input.txHash, input.blockfrostProjectId, fetchFn);\n } catch (e) {\n if (e instanceof NotALabel309RecordError) throw e;\n lastErr = e;\n }\n }\n\n throw new Error(`all_providers_failed: ${(lastErr as Error | undefined)?.message ?? 'unknown'}`);\n}\n\nasync function resolveViaKoios(\n txHash: string,\n koiosUrl: string,\n fetchFn: FetchOutbound,\n): Promise<ResolvedTx> {\n const cborRes = await fetchFn(`${koiosUrl}/tx_cbor`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n throw new Error(`koios_tx_cbor_${cborRes.status}`);\n }\n const cborJson = parseJson(cborRes.bytes);\n if (!Array.isArray(cborJson) || cborJson.length === 0) {\n throw new NotALabel309RecordError('koios returned empty array for tx_cbor; tx may not exist');\n }\n const cborEntry = cborJson[0] as { tx_hash?: unknown; cbor?: unknown };\n if (typeof cborEntry.cbor !== 'string') {\n throw new Error('koios_tx_cbor_missing_cbor_field');\n }\n if (\n typeof cborEntry.tx_hash === 'string' &&\n cborEntry.tx_hash.toLowerCase() !== txHash.toLowerCase()\n ) {\n throw new Error(`koios_tx_cbor_hash_mismatch: requested ${txHash} got ${cborEntry.tx_hash}`);\n }\n const txCbor = hexToBytes(cborEntry.cbor);\n\n const infoRes = await fetchFn(`${koiosUrl}/tx_info`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (infoRes.status !== 200) {\n throw new Error(`koios_tx_info_${infoRes.status}`);\n }\n const infoJson = parseJson(infoRes.bytes);\n if (!Array.isArray(infoJson) || infoJson.length === 0) {\n throw new NotALabel309RecordError('koios returned empty array for tx_info');\n }\n const infoEntry = infoJson[0] as {\n tx_hash?: unknown;\n num_confirmations?: unknown;\n block_height?: unknown;\n tx_timestamp?: unknown;\n absolute_slot?: unknown;\n };\n if (\n typeof infoEntry.tx_hash === 'string' &&\n infoEntry.tx_hash.toLowerCase() !== txHash.toLowerCase()\n ) {\n throw new Error(`koios_tx_info_hash_mismatch: requested ${txHash} got ${infoEntry.tx_hash}`);\n }\n\n // Koios v1 `/tx_info` no longer returns `num_confirmations` — only\n // `block_height` (verified live against `preprod.koios.rest/api/v1/tx_info`\n // and `api.koios.rest/api/v1/tx_info` on 2026-05-20: response keys do not\n // include num_confirmations). Compute manually as `tip - txBlockHeight + 1`,\n // mirroring the Blockfrost path. Fall back to a deprecated direct read of\n // `num_confirmations` for forward-compat against older Koios deployments.\n let numConfirmations: number;\n if (typeof infoEntry.num_confirmations === 'number') {\n numConfirmations = requireNonNegativeInt(infoEntry.num_confirmations, 'num_confirmations');\n } else {\n const txBlockHeight = requireNonNegativeInt(infoEntry.block_height, 'block_height');\n const tipRes = await fetchFn(`${koiosUrl}/tip`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n throw new Error(`koios_tip_${tipRes.status}`);\n }\n const tipJson = parseJson(tipRes.bytes);\n if (!Array.isArray(tipJson) || tipJson.length === 0) {\n throw new Error('koios_tip_empty');\n }\n const tipEntry = tipJson[0] as { block_height?: unknown };\n const tipHeight = requireNonNegativeInt(tipEntry.block_height, 'tip.block_height');\n numConfirmations = Math.max(0, tipHeight - txBlockHeight + 1);\n }\n\n return {\n txCbor,\n numConfirmations,\n blockTime: requireNonNegativeInt(infoEntry.tx_timestamp, 'tx_timestamp'),\n blockSlot: requireNonNegativeInt(infoEntry.absolute_slot, 'absolute_slot'),\n provider: 'koios',\n providerUrl: koiosUrl,\n };\n}\n\nasync function resolveViaBlockfrost(\n txHash: string,\n projectId: string,\n fetchFn: FetchOutbound,\n): Promise<ResolvedTx> {\n const base = BLOCKFROST_MAINNET_HOST;\n const headers = { project_id: projectId, accept: 'application/json' };\n\n const cborRes = await fetchFn(`${base}/txs/${txHash}/cbor`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n throw new Error(`blockfrost_tx_cbor_${cborRes.status}`);\n }\n const cborJson = parseJson(cborRes.bytes) as { cbor?: unknown };\n if (typeof cborJson.cbor !== 'string') {\n throw new Error('blockfrost_tx_cbor_missing_cbor_field');\n }\n const txCbor = hexToBytes(cborJson.cbor);\n\n const txRes = await fetchFn(`${base}/txs/${txHash}`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (txRes.status !== 200) {\n throw new Error(`blockfrost_tx_${txRes.status}`);\n }\n const txJson = parseJson(txRes.bytes) as {\n block_time?: unknown;\n slot?: unknown;\n block_height?: unknown;\n };\n const blockTime = requireNonNegativeInt(txJson.block_time, 'block_time');\n const txSlot = requireNonNegativeInt(txJson.slot, 'slot');\n // Confirmations are counted in BLOCKS, not slots. Cardano's active-slot\n // coefficient f=0.05 means only ~1 slot in 20 produces a block, so a\n // slot-difference count would inflate confirmations by ~20×. Blockfrost\n // returns `block_height` on `tx_content` and `height` on `/blocks/latest` —\n // both are the block-number field — so confirmations are\n // `tipHeight - blockHeight + 1`.\n const txBlockHeight = requireNonNegativeInt(txJson.block_height, 'block_height');\n\n const tipRes = await fetchFn(`${base}/blocks/latest`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n throw new Error(`blockfrost_blocks_latest_${tipRes.status}`);\n }\n const tipJson = parseJson(tipRes.bytes) as { slot?: unknown; height?: unknown };\n const tipHeight = requireNonNegativeInt(tipJson.height, 'tip_height');\n const numConfirmations = Math.max(0, tipHeight - txBlockHeight + 1);\n\n return {\n txCbor,\n numConfirmations,\n blockTime,\n blockSlot: txSlot,\n provider: 'blockfrost',\n providerUrl: base,\n };\n}\n\n// Byte-faithful label-309 extraction (delegates to the position-aware\n// `cbor-walker`, which never decode-then-re-encodes).\nexport function extractLabel309Metadata(txCbor: Uint8Array): Uint8Array | null {\n return sliceLabel309Value(txCbor);\n}\n\nfunction parseJson(bytes: Uint8Array): unknown {\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nfunction requireNonNegativeInt(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new Error(`gateway_field_invalid: ${field} (got ${typeof value}=${String(value)})`);\n }\n return value;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new Error(`hex string has odd length (${clean.length})`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n","// Lowercase, no-`0x`-prefix hex encoder shared across the SDK. Single\n// implementation so the verifier, the wire serialiser, and the publish client\n// all emit byte-identical hex (the Python parity twin and the cross-language\n// fixtures depend on this exact form).\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n","// Label 309 record-level signature verifier.\n//\n// One verification per `record.sigs[i]`. v1 has NO per-item signature slot —\n// the only signature surface is the record-level array. Two on-wire signer-key\n// paths (mutually exclusive on the wire, enforced by the structural\n// validator as `SIG_ENTRY_KID_COSE_KEY_CONFLICT`):\n//\n// Path 1 — protected-header `kid` is exactly 32 bytes (raw Ed25519 pubkey).\n// Path 2 — `sigs[i].cose_key` is a chunked `cbor<COSE_Key>` blob carrying\n// the wallet's public key. The protected header carries a 29-byte\n// CIP-19 stake address at label `\"address\"`; the verifier\n// recomputes `address_derived = network_header || Blake2b-224(pub)`\n// and rejects on mismatch (`WALLET_ADDRESS_MISMATCH`).\n//\n// The signed-payload construction (`Sig_structure[3] = \"cardano-poe-record-sig-v1\" ||\n// canonicalCbor(record_body)`, `Sig_structure[2] = h''`) is enforced by the\n// `coseSign1Label309Verify` helper in `@cardanowall/crypto-core/cose` — this\n// verifier never sees the prefix directly.\n\nimport {\n bytesChunkArrayConcat,\n encodeRecordBodyForSigning,\n type PoeRecord,\n type SigEntry,\n} from '@cardanowall/poe-standard';\nimport {\n coseSign1Label309Verify,\n decodeCoseSign1,\n parseCoseKeyEd25519,\n type CoseSign1Decoded,\n} from '@cardanowall/crypto-core/cose';\nimport { blake2b224 } from '@cardanowall/crypto-core/hash';\nimport { compareCt } from '@cardanowall/crypto-core/util';\n\nimport { bytesToHex } from '../hex';\nimport type { SignatureFailureReason, VerifyRecordSignature, VerifyTxInput } from './types';\n\n// v1 wallet-path constraint: stake (reward) addresses only. The 29-byte CIP-19\n// layout is `network_header_byte || Blake2b-224(stake_vk)`. CIP-19\n// stake-address network bytes: mainnet = 0xe1, testnet = 0xe0 (preprod and\n// preview share the testnet header). Product policy is mainnet-only; the\n// preprod branch exists only so dev environments can replay records anchored\n// on preprod against the same standalone verifier.\nconst CARDANO_MAINNET_STAKE_NETWORK_BYTE = 0xe1;\nconst CARDANO_PREPROD_STAKE_NETWORK_BYTE = 0xe0;\nconst CARDANO_STAKE_ADDRESS_LENGTH = 29;\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst BLAKE2B_224_LENGTH = 28;\n\nexport interface VerifyRecordSignaturesArgs {\n readonly record: PoeRecord;\n readonly input: VerifyTxInput;\n}\n\nexport async function verifyRecordSignatures(\n args: VerifyRecordSignaturesArgs,\n): Promise<VerifyRecordSignature[]> {\n const { record, input } = args;\n // The signed payload is canonical-CBOR(record_body), where record_body =\n // record minus `sigs`. We use the encoder helper to keep the wire shape and\n // key sort in lockstep with producer-side signing.\n const recordBodyCbor = encodeRecordBodyForSigning(record);\n const list = record.sigs ?? [];\n const out: VerifyRecordSignature[] = [];\n for (let i = 0; i < list.length; i++) {\n out.push(await verifyOneSig(i, list[i]!, recordBodyCbor, input));\n }\n return out;\n}\n\nasync function verifyOneSig(\n index: number,\n entry: SigEntry,\n recordBodyCbor: Uint8Array,\n input: VerifyTxInput,\n): Promise<VerifyRecordSignature> {\n const coseBytes = bytesChunkArrayConcat(entry.cose_sign1);\n let cose: CoseSign1Decoded;\n try {\n cose = decodeCoseSign1(coseBytes);\n } catch {\n return { index, verdict: 'invalid', reason: 'MALFORMED_SIG_COSE_SIGN1' };\n }\n\n // Resolve the signer's 32-byte Ed25519 pubkey (path 1 vs path 2).\n const resolved = resolveSignerKey(cose, entry);\n if (resolved.kind === 'unresolved') {\n return { index, verdict: 'unresolved', reason: 'SIGNER_KEY_UNRESOLVED' };\n }\n const { pub, signerType } = resolved;\n\n // Strict Ed25519 verify via the Label 309-pinned helper.\n const verifyResult = coseSign1Label309Verify({\n message: coseBytes,\n detachedRecordBodyCbor: recordBodyCbor,\n expectedSignerKey: pub,\n });\n\n if (!verifyResult.ok) {\n const reason = mapVerifyError(verifyResult.error.code);\n if (reason === 'SIGNATURE_UNSUPPORTED') {\n return {\n index,\n verdict: 'unsupported',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason,\n };\n }\n return {\n index,\n verdict: 'invalid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason,\n };\n }\n\n // Path-2 wallet `address` ↔ `cose_key` binding. Path-1 entries skip this\n // check entirely.\n if (signerType === 'wallet-inline-key') {\n const addressOk = checkWalletAddressBinding(cose, pub, input);\n if (!addressOk) {\n return {\n index,\n verdict: 'invalid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n reason: 'WALLET_ADDRESS_MISMATCH',\n };\n }\n }\n\n return {\n index,\n verdict: 'valid',\n signer_type: signerType,\n signer_pub: bytesToHex(pub),\n };\n}\n\ninterface ResolvedPathOne {\n readonly kind: 'in-signature-kid';\n readonly pub: Uint8Array;\n readonly signerType: 'in-signature-kid';\n}\ninterface ResolvedPathTwo {\n readonly kind: 'wallet-inline-key';\n readonly pub: Uint8Array;\n readonly signerType: 'wallet-inline-key';\n}\ntype ResolvedKey = ResolvedPathOne | ResolvedPathTwo | { readonly kind: 'unresolved' };\n\nfunction resolveSignerKey(cose: CoseSign1Decoded, entry: SigEntry): ResolvedKey {\n // Path 1 — protected-header label 4 (`kid`) as the 32-byte raw Ed25519\n // pubkey. Unprotected-header `kid` values are NEVER consulted: they sit\n // outside the COSE integrity envelope and an attacker could rewrite them.\n const protectedKid = cose.protectedHeader.get(4) as unknown;\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === ED25519_PUBLIC_KEY_LENGTH &&\n entry.cose_key === undefined\n ) {\n return {\n kind: 'in-signature-kid',\n pub: protectedKid,\n signerType: 'in-signature-kid',\n };\n }\n // Path 2 — chunked `cbor<COSE_Key>` carrying the wallet pubkey.\n if (entry.cose_key !== undefined) {\n const blob = bytesChunkArrayConcat(entry.cose_key);\n const pub = parseCoseKeyEd25519(blob);\n if (pub !== null && pub.length === ED25519_PUBLIC_KEY_LENGTH) {\n return { kind: 'wallet-inline-key', pub, signerType: 'wallet-inline-key' };\n }\n }\n return { kind: 'unresolved' };\n}\n\nfunction mapVerifyError(code: string): SignatureFailureReason {\n switch (code) {\n case 'MALFORMED_SIG_COSE':\n case 'MALFORMED_SIG_COSE_SIGN1':\n return 'MALFORMED_SIG_COSE_SIGN1';\n case 'UNSUPPORTED_SIG_ALG':\n return 'SIGNATURE_UNSUPPORTED';\n case 'KID_UNRESOLVED':\n return 'SIGNER_KEY_UNRESOLVED';\n case 'SIGNATURE_INVALID':\n return 'SIGNATURE_INVALID';\n default:\n return 'SIGNATURE_INVALID';\n }\n}\n\n// Recompute the 29-byte stake address from the resolved Ed25519 pubkey and\n// compare it byte-exact (constant-time) to the path-2 protected-header\n// `address` field. The wallet path binds to stake (reward) addresses only in\n// v1 — base/enterprise/pointer/payment addresses are rejected (the recomputed\n// 29-byte stake address fails the equality check against any other\n// format/length).\nfunction checkWalletAddressBinding(\n cose: CoseSign1Decoded,\n pub: Uint8Array,\n input: VerifyTxInput,\n): boolean {\n const networkByte =\n (input.cardanoNetwork ?? 'mainnet') === 'preprod'\n ? CARDANO_PREPROD_STAKE_NETWORK_BYTE\n : CARDANO_MAINNET_STAKE_NETWORK_BYTE;\n const rawAddress = cose.protectedHeader.get('address') as unknown;\n if (!(rawAddress instanceof Uint8Array)) {\n // Address-less path-2 records are non-conformant with CIP-30 signData\n // (a wallet signature without an address claim cannot be safely surfaced\n // as wallet-bound). Treat as WALLET_ADDRESS_MISMATCH.\n return false;\n }\n if (rawAddress.length !== CARDANO_STAKE_ADDRESS_LENGTH) return false;\n if (rawAddress[0] !== networkByte) return false;\n const stakeKeyHash = blake2b224(pub);\n if (stakeKeyHash.length !== BLAKE2B_224_LENGTH) {\n // Defensive guard — `blake2b224` is byte-pinned to 28 bytes.\n return false;\n }\n const derived = new Uint8Array(CARDANO_STAKE_ADDRESS_LENGTH);\n derived[0] = networkByte;\n derived.set(stakeKeyHash, 1);\n return compareCt(derived, rawAddress);\n}\n","// Transaction-level decode for the Label 309 verifier.\n//\n// This module surfaces the Cardano TRANSACTION that carried a PoE record: which\n// wallet vkey(s) signed it, the fee, the outputs, and the co-published metadata\n// labels. It answers \"who authorised and paid for this anchoring\" — distinct\n// from the record-level COSE authorship signatures handled in `signatures.ts`.\n//\n// Unlike label-309 extraction, this decode is purely INFORMATIONAL: it is not\n// fed back into the structural validator, so it is not subject to the\n// canonical-CBOR byte-faithfulness concern that forces `cbor-walker` to slice\n// rather than decode. We therefore decode the body + witness-set slices with\n// the permissive CBOR decoder. The slices themselves are still byte-faithful —\n// `decodeTxWitnesses` verifies each signature against `blake2b256(txBody)`,\n// which only equals the on-chain transaction hash when the body bytes are\n// exactly as produced.\n\nimport { decodeCbor } from '@cardanowall/crypto-core/cbor';\nimport { blake2b224, blake2b256 } from '@cardanowall/crypto-core/hash';\nimport { verifyEd25519 } from '@cardanowall/crypto-core/sig';\n\nimport { bytesToHex } from '../hex';\nimport type { VerifyTxOutput, VerifyTxSummary, VerifyTxWitness } from './types';\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst ED25519_SIGNATURE_LENGTH = 64;\n\n// Conway-era transaction body map keys (RFC-style integer keys).\nconst BODY_KEY_INPUTS = 0;\nconst BODY_KEY_OUTPUTS = 1;\nconst BODY_KEY_FEE = 2;\nconst BODY_KEY_INVALID_HEREAFTER = 3; // ttl\nconst BODY_KEY_INVALID_BEFORE = 8; // validity_interval_start\nconst BODY_KEY_REQUIRED_SIGNERS = 14;\nconst BODY_KEY_NETWORK_ID = 15;\n\n// Witness-set map keys. Key 0 is the vkey witness set; every other key\n// (native scripts, bootstrap witnesses, Plutus v1/v2/v3) is counted as a\n// \"script/other\" witness without being deep-decoded.\nconst WITNESS_KEY_VKEY = 0;\n\n// inputs, vkey_witnesses, and required_signers are CBOR sets (tag 258). The\n// permissive decoder may surface a set as a JS `Set` or an `Array` depending\n// on how the producer encoded it; normalise both to an array.\nfunction asArray(v: unknown): unknown[] {\n if (v instanceof Set) return [...v];\n if (Array.isArray(v)) return v;\n return [];\n}\n\nfunction asMap(v: unknown): Map<unknown, unknown> | null {\n return v instanceof Map ? v : null;\n}\n\n/**\n * Decode the vkey witnesses of a transaction and verify each signature against\n * the transaction body.\n *\n * Each Cardano vkey witness is `[vkey(32B), signature(64B)]`; the signed\n * message is `blake2b256(txBody)` (the transaction hash). A witness whose vkey\n * or signature is malformed, or whose signature does not verify, is reported\n * with `signature_valid: false` rather than dropped — the caller surfaces it\n * informationally and never fails the record on it.\n */\nexport function decodeTxWitnesses(\n witnessSetBytes: Uint8Array,\n txBodyBytes: Uint8Array,\n): VerifyTxWitness[] {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return [];\n const vkeyWitnesses = asArray(witnessSet.get(WITNESS_KEY_VKEY));\n const txHash = blake2b256(txBodyBytes);\n\n const out: VerifyTxWitness[] = [];\n for (const entry of vkeyWitnesses) {\n const pair = asArray(entry);\n const vkey = pair[0];\n const signature = pair[1];\n if (\n !(vkey instanceof Uint8Array) ||\n vkey.length !== ED25519_PUBLIC_KEY_LENGTH ||\n !(signature instanceof Uint8Array) ||\n signature.length !== ED25519_SIGNATURE_LENGTH\n ) {\n // A structurally malformed witness still describes an attempted\n // authorisation; surface what we can (when the vkey is a valid pubkey)\n // and mark the signature invalid.\n if (vkey instanceof Uint8Array && vkey.length === ED25519_PUBLIC_KEY_LENGTH) {\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: false,\n });\n }\n continue;\n }\n let signatureValid: boolean;\n try {\n signatureValid = verifyEd25519({ publicKey: vkey, message: txHash, signature });\n } catch {\n signatureValid = false;\n }\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: signatureValid,\n });\n }\n return out;\n}\n\n/**\n * Count the witness-set entries that are NOT vkey witnesses (native scripts,\n * bootstrap witnesses, Plutus v1/v2/v3). These are summed as a single\n * \"script/other\" count without deep-decoding their contents.\n */\nfunction countScriptWitnesses(witnessSetBytes: Uint8Array): number {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return 0;\n let count = 0;\n for (const [key, value] of witnessSet) {\n if (key === WITNESS_KEY_VKEY) continue;\n count += asArray(value).length;\n }\n return count;\n}\n\n/**\n * Decode a transaction body into a JSON-safe summary: fee, input/output counts,\n * the output addresses + lovelace amounts, validity interval, required signer\n * key hashes, and network id.\n *\n * All lovelace amounts are serialised as DECIMAL STRINGS so they survive JSON\n * round-trips exactly (Cardano coin values can exceed `Number.MAX_SAFE_INTEGER`\n * and BigInt is not JSON-native). Coin math is performed with BigInt internally.\n */\nexport function decodeTxSummary(\n txBodyBytes: Uint8Array,\n witnessSetBytes: Uint8Array,\n network: 'mainnet' | 'preprod',\n): VerifyTxSummary {\n const body = asMap(decodeCbor(txBodyBytes));\n if (body === null) {\n throw new RangeError('MALFORMED_CBOR: tx body is not a CBOR map');\n }\n\n const inputs = asArray(body.get(BODY_KEY_INPUTS));\n const outputsRaw = asArray(body.get(BODY_KEY_OUTPUTS));\n\n const outputs: VerifyTxOutput[] = [];\n let totalOutput = 0n;\n for (const o of outputsRaw) {\n const { addressBytes, lovelace } = readOutput(o);\n totalOutput += lovelace;\n outputs.push({\n address: encodeCardanoAddress(addressBytes, network),\n lovelace: lovelace.toString(),\n });\n }\n\n const requiredSigners = asArray(body.get(BODY_KEY_REQUIRED_SIGNERS))\n .filter((s): s is Uint8Array => s instanceof Uint8Array)\n .map((s) => bytesToHex(s));\n\n const summary: {\n -readonly [K in keyof VerifyTxSummary]: VerifyTxSummary[K];\n } = {\n fee_lovelace: coinToString(body.get(BODY_KEY_FEE)),\n input_count: inputs.length,\n output_count: outputs.length,\n outputs,\n total_output_lovelace: totalOutput.toString(),\n script_witness_count: countScriptWitnesses(witnessSetBytes),\n };\n\n const invalidBefore = body.get(BODY_KEY_INVALID_BEFORE);\n if (typeof invalidBefore === 'number') summary.invalid_before = invalidBefore;\n else if (typeof invalidBefore === 'bigint') summary.invalid_before = Number(invalidBefore);\n\n const invalidHereafter = body.get(BODY_KEY_INVALID_HEREAFTER);\n if (typeof invalidHereafter === 'number') summary.invalid_hereafter = invalidHereafter;\n else if (typeof invalidHereafter === 'bigint')\n summary.invalid_hereafter = Number(invalidHereafter);\n\n if (requiredSigners.length > 0) summary.required_signer_key_hashes = requiredSigners;\n\n const networkId = body.get(BODY_KEY_NETWORK_ID);\n if (typeof networkId === 'number') summary.network_id = networkId;\n else if (typeof networkId === 'bigint') summary.network_id = Number(networkId);\n\n return summary;\n}\n\n// A transaction output is EITHER a legacy array `[address, amount]` OR a map\n// `{0: address, 1: amount}` (post-Babbage). `amount` is either a bare coin\n// (uint) or a `[coin, multiasset]` pair — only the coin (lovelace) component is\n// summarised here.\nfunction readOutput(output: unknown): { addressBytes: Uint8Array; lovelace: bigint } {\n let address: unknown;\n let amount: unknown;\n if (Array.isArray(output)) {\n address = output[0];\n amount = output[1];\n } else if (output instanceof Map) {\n address = output.get(0);\n amount = output.get(1);\n } else {\n throw new RangeError('MALFORMED_CBOR: tx output is neither a CBOR array nor a CBOR map');\n }\n if (!(address instanceof Uint8Array)) {\n throw new RangeError('MALFORMED_CBOR: tx output address is not a byte string');\n }\n const lovelace = Array.isArray(amount) ? toBigInt(amount[0]) : toBigInt(amount);\n return { addressBytes: address, lovelace };\n}\n\nfunction coinToString(v: unknown): string {\n return toBigInt(v).toString();\n}\n\nfunction toBigInt(v: unknown): bigint {\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isInteger(v)) return BigInt(v);\n throw new RangeError(`MALFORMED_CBOR: expected an integer coin value, got ${typeof v}`);\n}\n\n// -----------------------------------------------------------------------------\n// Cardano address bech32 encoding (BIP-173, the CIP-19 bech32 form).\n// -----------------------------------------------------------------------------\n//\n// Implemented inline so the published SDK keeps a minimal, auditable dependency\n// surface (the verifier's only third-party deps are the cryptographic core).\n// The header byte's high nibble is the address type and its low nibble is the\n// network id (0 = testnet, 1 = mainnet). Payment-address types 0–7 use the\n// `addr` HRP; stake/reward types 14–15 use the `stake` HRP. The header's\n// network nibble is authoritative for the `_test` suffix; the caller's\n// `network` argument is the fallback when a header is ambiguous.\n\nconst BECH32_CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\n\nfunction encodeCardanoAddress(addressBytes: Uint8Array, network: 'mainnet' | 'preprod'): string {\n if (addressBytes.length === 0) {\n throw new RangeError('MALFORMED_CBOR: empty address byte string');\n }\n const header = addressBytes[0]!;\n const addressType = header >> 4;\n const networkNibble = header & 0x0f;\n const isStake = addressType === 14 || addressType === 15;\n // The header's network nibble is authoritative. Fall back to the caller's\n // network only when the nibble is not the canonical 0 (testnet) / 1 (mainnet).\n const isTestnet =\n networkNibble === 0 ? true : networkNibble === 1 ? false : network === 'preprod';\n const base = isStake ? 'stake' : 'addr';\n const hrp = isTestnet ? `${base}_test` : base;\n return bech32Encode(hrp, addressBytes);\n}\n\nfunction bech32Polymod(values: number[]): number {\n const generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n let chk = 1;\n for (const value of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) {\n if ((top >> i) & 1) chk ^= generators[i]!;\n }\n }\n return chk;\n}\n\nfunction bech32HrpExpand(hrp: string): number[] {\n const out: number[] = [];\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) >> 5);\n out.push(0);\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) & 31);\n return out;\n}\n\n// 8-bit → 5-bit regrouping with zero-padding of the final group (the encode\n// direction always pads).\nfunction bech32ToWords(data: Uint8Array): number[] {\n let acc = 0;\n let bits = 0;\n const out: number[] = [];\n const maxv = (1 << 5) - 1;\n for (const value of data) {\n acc = (acc << 8) | value;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out.push((acc >> bits) & maxv);\n }\n }\n if (bits > 0) out.push((acc << (5 - bits)) & maxv);\n return out;\n}\n\nfunction bech32Encode(hrp: string, data: Uint8Array): string {\n const words = bech32ToWords(data);\n const polymodInput = bech32HrpExpand(hrp).concat(words, [0, 0, 0, 0, 0, 0]);\n const polymod = bech32Polymod(polymodInput) ^ 1;\n const checksum: number[] = [];\n for (let i = 0; i < 6; i++) checksum.push((polymod >> (5 * (5 - i))) & 31);\n let result = `${hrp}1`;\n for (const w of words.concat(checksum)) result += BECH32_CHARSET.charAt(w);\n return result;\n}\n","// Label 309 standalone verifier entry point.\n//\n// Pipeline (steps run sequentially; the verdict is the worst outcome across them):\n// 1. Resolve Cardano gateway + raw tx CBOR + confirmation depth.\n// 2. Byte-faithful extract of label-309 metadata.\n// 3. Structural validator (Part A; never throws).\n// 4. Confirmation-depth check → INSUFFICIENT_CONFIRMATIONS / verdict 'pending'.\n// 5. Profile-gated work (signed: signatures; sealed: enc structure;\n// recipient-sealed: decrypt). Out-of-profile fields emit\n// OUT_OF_PROFILE_SKIPPED (info) — not SCHEMA_UNKNOWN_FIELD.\n// 6. Merkle list-commitment verification (awaited after step 5).\n// 7. Three-state verdict emission with exit-code mapping.\n\nimport { SEVERITY, validatePoeRecord, type ValidationIssue } from '@cardanowall/poe-standard';\n\nimport { tryDecryptions } from './decrypt';\nimport { defaultFetchOutbound, wrapFetchOutbound } from './fetch';\nimport { verifyMerkleCommitments } from './merkle';\nimport { DEFAULT_PROFILE, planProfileSkips } from './profile';\nimport { extractLabel309Metadata, NotALabel309RecordError, resolveCardanoTx } from './resolve';\nimport { verifyRecordSignatures } from './signatures';\nimport { sliceTxComponents } from './cbor-walker';\nimport { decodeTxSummary, decodeTxWitnesses } from './tx-witnesses';\nimport type {\n ExitCode,\n FetchOutbound,\n HttpCallRecord,\n Profile,\n VerifyItemDecryption,\n VerifyMerkleCheck,\n VerifyRecordSignature,\n VerifyReport,\n VerifyTxInput,\n VerifyUriCheck,\n Verdict,\n} from './types';\n\nexport const CONFIRMATION_DEPTH_THRESHOLD_DEFAULT = 15;\n\ntype MutableReport = { -readonly [K in keyof VerifyReport]: VerifyReport[K] };\n\nexport async function verifyTx(input: VerifyTxInput): Promise<VerifyReport> {\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n const httpCalls: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n httpCalls,\n input.denyHosts,\n );\n\n const base = (\n over: Partial<VerifyReport> & Pick<VerifyReport, 'verdict' | 'exit_code'>,\n ): VerifyReport => ({\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: 0,\n confirmation_depth_threshold: threshold,\n metadata_present: false,\n validation: { valid: false },\n http_calls: httpCalls,\n ...over,\n });\n\n // 1. Resolve Cardano gateway + raw tx CBOR.\n let resolved;\n try {\n resolved = await resolveCardanoTx({ input, fetchFn });\n } catch (e) {\n if (e instanceof NotALabel309RecordError) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n validation: {\n valid: false,\n issues: [issueOf('METADATA_NOT_FOUND', [], e.message)],\n },\n });\n }\n return base({\n verdict: 'failed',\n exit_code: 2,\n validation: {\n valid: false,\n issues: [issueOf('PROVIDER_UNAVAILABLE', [], (e as Error).message)],\n },\n });\n }\n\n // 2. Byte-faithful label-309 extraction.\n let metadataBytes: Uint8Array | null;\n try {\n metadataBytes = extractLabel309Metadata(resolved.txCbor);\n } catch (e) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: resolved.numConfirmations,\n block_time: resolved.blockTime,\n block_slot: resolved.blockSlot,\n validation: {\n valid: false,\n issues: [issueOf('MALFORMED_CBOR', [], (e as Error).message)],\n },\n });\n }\n if (metadataBytes === null) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: resolved.numConfirmations,\n block_time: resolved.blockTime,\n block_slot: resolved.blockSlot,\n metadata_present: false,\n validation: {\n valid: false,\n issues: [issueOf('METADATA_NOT_FOUND', [], 'no label-309 metadata on this tx')],\n },\n });\n }\n\n return verifyResolvedRecord({\n input,\n metadataBytes,\n txCbor: resolved.txCbor,\n numConfirmations: resolved.numConfirmations,\n blockTime: resolved.blockTime,\n blockSlot: resolved.blockSlot,\n httpCalls,\n fetchFn,\n });\n}\n\n/**\n * `verifyResolved` — same pipeline as `verifyTx` starting from step 3\n * (structural validator). The caller has already resolved the label-309\n * metadata bytes + block-info tuple from somewhere other than a live chain\n * fetch (typically an indexer database mirror).\n *\n * Use this when you trust an upstream indexer for the (metadataCbor,\n * blockTime, blockSlot, numConfirmations) tuple and want to skip the\n * /tx_cbor + /tx_info round-trip. The caller is responsible for the\n * confidence that the supplied bytes actually came from the label-309\n * metadata field of a confirmed Cardano transaction.\n */\nexport async function verifyResolved(input: {\n txHash: string;\n metadataCbor: Uint8Array;\n // Raw on-chain transaction CBOR. When supplied, the report also carries the\n // transaction-level description (tx_witnesses, tx_summary, metadata_labels);\n // when absent, those three fields are left undefined. The label-309 record\n // is always taken from `metadataCbor`, never re-derived from `txCbor`.\n txCbor?: Uint8Array;\n numConfirmations: number;\n blockTime?: number;\n blockSlot?: number;\n network?: VerifyReport['network'];\n cardanoNetwork?: VerifyTxInput['cardanoNetwork'];\n profile?: Profile;\n confirmationDepthThreshold?: number;\n fetchOutbound?: FetchOutbound;\n denyHosts?: ReadonlyArray<string>;\n decryption?: VerifyTxInput['decryption'];\n // Mirrors `VerifyTxInput.verifyMerkle`. SSR callers pass `false` so the\n // viewer renders from indexed CBOR alone with no Arweave/IPFS leaves-list\n // fetch (deferred to a user-initiated client-side action instead).\n verifyMerkle?: boolean;\n}): Promise<VerifyReport> {\n const httpCalls: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n httpCalls,\n input.denyHosts,\n );\n // Reuse the post-resolve pipeline by adapting the caller's args back into\n // the VerifyTxInput shape that signature/decryption/merkle helpers expect.\n const verifyTxInput: VerifyTxInput = {\n txHash: input.txHash,\n ...(input.profile !== undefined ? { profile: input.profile } : {}),\n ...(input.cardanoNetwork !== undefined ? { cardanoNetwork: input.cardanoNetwork } : {}),\n ...(input.confirmationDepthThreshold !== undefined\n ? { confirmationDepthThreshold: input.confirmationDepthThreshold }\n : {}),\n ...(input.fetchOutbound !== undefined ? { fetchOutbound: input.fetchOutbound } : {}),\n ...(input.denyHosts !== undefined ? { denyHosts: input.denyHosts } : {}),\n ...(input.decryption !== undefined ? { decryption: input.decryption } : {}),\n ...(input.verifyMerkle !== undefined ? { verifyMerkle: input.verifyMerkle } : {}),\n };\n const report = await verifyResolvedRecord({\n input: verifyTxInput,\n metadataBytes: input.metadataCbor,\n ...(input.txCbor !== undefined ? { txCbor: input.txCbor } : {}),\n numConfirmations: input.numConfirmations,\n ...(input.blockTime !== undefined ? { blockTime: input.blockTime } : {}),\n ...(input.blockSlot !== undefined ? { blockSlot: input.blockSlot } : {}),\n httpCalls,\n fetchFn,\n });\n if (input.network !== undefined) {\n return { ...report, network: input.network };\n }\n return report;\n}\n\nasync function verifyResolvedRecord(args: {\n input: VerifyTxInput;\n metadataBytes: Uint8Array;\n txCbor?: Uint8Array;\n numConfirmations: number;\n blockTime?: number;\n blockSlot?: number;\n httpCalls: HttpCallRecord[];\n fetchFn: ReturnType<typeof wrapFetchOutbound>;\n}): Promise<VerifyReport> {\n const {\n input,\n metadataBytes,\n txCbor,\n numConfirmations,\n blockTime,\n blockSlot,\n httpCalls,\n fetchFn,\n } = args;\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n\n // Transaction-level description — who authorised/paid for the anchoring,\n // distinct from record-level authorship. Decoded once when the raw tx CBOR\n // is available, then merged into every report shape below. This is pure\n // description: it never gates on profile and never changes the verdict.\n const txDescription = txCbor !== undefined ? decodeTxDescription(txCbor, input) : {};\n\n const base = (\n over: Partial<VerifyReport> & Pick<VerifyReport, 'verdict' | 'exit_code'>,\n ): VerifyReport => ({\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: 0,\n confirmation_depth_threshold: threshold,\n metadata_present: false,\n validation: { valid: false },\n http_calls: httpCalls,\n ...txDescription,\n ...over,\n });\n\n // 3. Structural validator (Part A).\n const validation = validatePoeRecord(metadataBytes);\n if (!validation.ok) {\n return base({\n verdict: 'failed',\n exit_code: 1,\n num_confirmations: numConfirmations,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n validation: { valid: false, issues: validation.issues },\n });\n }\n const record = validation.record;\n\n // 4. Confirmation-depth — a record below the reorg-safety threshold is\n // well-formed but not yet final, so INSUFFICIENT_CONFIRMATIONS short-circuits\n // to verdict `'pending'` (exit 3), NOT `'failed'`.\n if (numConfirmations < threshold) {\n return base({\n verdict: 'pending',\n exit_code: 3,\n num_confirmations: numConfirmations,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n record,\n validation: {\n valid: false,\n issues: [\n issueOf('INSUFFICIENT_CONFIRMATIONS', [], `${numConfirmations} < threshold ${threshold}`),\n ],\n },\n });\n }\n\n // 5. Build optimistic report; mutate verdict on per-check failure.\n const initialWarnings = (validation.warnings ?? []).slice();\n const initialInfo = (validation.info ?? []).slice();\n const plan = planProfileSkips(profile, record);\n initialInfo.push(...plan.skips);\n\n // (Note: a `MERKLE_UNSUPPORTED` escalation — a verifier reading a\n // merkle-only record without implementing Merkle — never fires here because\n // this reference verifier always runs the Merkle subsystem at every profile.\n // A future `core - merkle` opt-out would emit MERKLE_UNSUPPORTED at info\n // severity when items[] also commits content, error severity otherwise.)\n\n const reportShape: VerifyReport = {\n tx_hash: input.txHash,\n network: 'cardano:mainnet',\n profile,\n num_confirmations: numConfirmations,\n confirmation_depth_threshold: threshold,\n ...(blockTime !== undefined ? { block_time: blockTime } : {}),\n ...(blockSlot !== undefined ? { block_slot: blockSlot } : {}),\n metadata_present: true,\n validation: composeValidation(true, undefined, initialWarnings, initialInfo),\n record,\n ...txDescription,\n http_calls: httpCalls,\n verdict: 'valid',\n exit_code: 0,\n };\n const report: MutableReport = { ...reportShape };\n const uriChecks: VerifyUriCheck[] = [];\n\n // `verifyMerkle === false` is the offline switch: it suppresses EVERY\n // outbound URI fetch the verifier would otherwise issue past the\n // chain/indexer resolve step — both the sealed-item ciphertext download in\n // decryption (5b) and the Merkle leaves-list fetch (6). Offline callers\n // (server-rendered viewers, CLI `--no-fetch`) get a report built from\n // indexed CBOR plus any caller-supplied out-of-band bytes alone.\n const allowUriFetch = input.verifyMerkle ?? true;\n\n // 5a. Record-level signatures (profile >= 'signed').\n if (plan.verifySignatures && record.sigs && record.sigs.length > 0) {\n const sigOut: VerifyRecordSignature[] = await verifyRecordSignatures({ record, input });\n report.record_signatures = sigOut;\n if (recordSignaturesShouldFail(sigOut)) {\n report.verdict = 'failed';\n report.exit_code = 1;\n }\n }\n\n // 5b. Decryption (profile >= 'recipient-sealed' AND caller supplied keys).\n if (plan.verifyDecrypt && input.decryption && input.decryption.length > 0) {\n const dec = await tryDecryptions({\n record,\n input,\n fetchFn,\n httpCalls,\n uriChecksOut: uriChecks,\n allowUriFetch,\n });\n report.item_decryptions = dec.results;\n const decFailure = decryptionsShouldFail(dec.results);\n if (decFailure !== null) {\n report.verdict = 'failed';\n report.exit_code = decFailure === 'network' ? 2 : 1;\n }\n }\n\n // 6. Merkle commitments (always in `core` and above; only escalates verdict\n // to `'failed'` on `MERKLE_ROOT_MISMATCH` / leaf-count mismatch — leaves\n // unavailability stays at warning).\n //\n // Suppressed entirely when the offline switch is set (see `allowUriFetch`)\n // so a server-rendered viewer produces a VerifyReport from indexed CBOR\n // alone, with zero outbound fetches to Arweave/IPFS gateways. The on-record\n // `merkle[]` data (alg, root, leaf_count, uris) survives unchanged on\n // `report.record`; only the defence-in-depth re-root + leaf-count check is\n // suppressed. A user-initiated client-side flow performs the same\n // verification at click time.\n if (allowUriFetch && Array.isArray(record.merkle) && record.merkle.length > 0) {\n const merkle = await verifyMerkleCommitments({\n record,\n input,\n fetchFn,\n uriChecksOut: uriChecks,\n });\n report.merkle_checks = merkle.checks;\n const merkleFailure = merkleChecksShouldFail(merkle.checks);\n if (merkleFailure && report.verdict === 'valid') {\n report.verdict = 'failed';\n report.exit_code = 1;\n }\n }\n\n if (uriChecks.length > 0) {\n report.uri_checks = uriChecks;\n }\n\n return report;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\n// Decode the transaction-level description (witnesses, summary, co-published\n// metadata labels) from raw tx CBOR. This is purely informational, so a decode\n// failure must NOT propagate into the verdict — it degrades to omitting the\n// affected fields. The label-309 record is validated separately from\n// `metadataBytes`; this view only describes the carrying transaction.\ntype TxDescriptionFields = Pick<VerifyReport, 'tx_witnesses' | 'tx_summary' | 'metadata_labels'>;\nfunction decodeTxDescription(txCbor: Uint8Array, input: VerifyTxInput): TxDescriptionFields {\n const network = input.cardanoNetwork ?? 'mainnet';\n const out: { -readonly [K in keyof TxDescriptionFields]: TxDescriptionFields[K] } = {};\n let components;\n try {\n components = sliceTxComponents(txCbor);\n } catch {\n return out;\n }\n out.metadata_labels = components.auxMetadataLabels;\n try {\n out.tx_witnesses = decodeTxWitnesses(components.witnessSet, components.txBody);\n } catch {\n // leave tx_witnesses undefined\n }\n try {\n out.tx_summary = decodeTxSummary(components.txBody, components.witnessSet, network);\n } catch {\n // leave tx_summary undefined\n }\n return out;\n}\n\n// A public hash-only PoE stays valid even when every signature entry is\n// SIGNATURE_UNSUPPORTED — the content claim does not depend on signer identity,\n// so an unverifiable algorithm is informational, not fatal. Any OTHER failure\n// (MALFORMED_SIG_COSE_SIGN1, SIGNER_KEY_UNRESOLVED, SIGNATURE_INVALID,\n// WALLET_ADDRESS_MISMATCH) fails the record.\nfunction recordSignaturesShouldFail(sigs: ReadonlyArray<VerifyRecordSignature>): boolean {\n return sigs.some((s) => s.verdict === 'invalid' || s.verdict === 'unresolved');\n}\n\n// Returns null on success, 'network' for CONTENT_UNAVAILABLE / IPFS-no-gateway\n// (exit 2), or 'integrity' for any other failure (exit 1).\nfunction decryptionsShouldFail(\n results: ReadonlyArray<VerifyItemDecryption>,\n): 'network' | 'integrity' | null {\n let saw: 'network' | 'integrity' | null = null;\n for (const d of results) {\n if (d.verdict === 'decrypted' && d.plaintext_hash_ok !== false) continue;\n if (d.verdict === 'content-unavailable' || d.verdict === 'ciphertext-unavailable') {\n saw = saw === 'integrity' ? 'integrity' : 'network';\n continue;\n }\n saw = 'integrity';\n }\n return saw;\n}\n\nfunction merkleChecksShouldFail(checks: ReadonlyArray<VerifyMerkleCheck>): boolean {\n for (const c of checks) {\n if (c.verdict === 'mismatch') return true;\n // `unavailable`, `format-unsupported`, and `unsupported` are warning/\n // info-severity — the on-chain root is structurally valid on its own, so\n // they do NOT escalate to verdict 'failed'.\n }\n return false;\n}\n\nfunction issueOf(\n code: keyof typeof SEVERITY,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nfunction composeValidation(\n valid: boolean,\n issues: ReadonlyArray<ValidationIssue> | undefined,\n warnings: ReadonlyArray<ValidationIssue>,\n info: ReadonlyArray<ValidationIssue>,\n): VerifyReport['validation'] {\n const out: {\n valid: boolean;\n issues?: ReadonlyArray<ValidationIssue>;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = { valid };\n if (issues !== undefined && issues.length > 0) out.issues = issues;\n if (warnings.length > 0) out.warnings = warnings;\n if (info.length > 0) out.info = info;\n return out;\n}\n\n// Convenience re-export so callers can map verdicts to exit codes without\n// importing the union shape.\nexport function exitCodeForVerdict(report: VerifyReport): ExitCode {\n return report.exit_code;\n}\n\nexport type { Verdict, ExitCode };\n","#!/usr/bin/env node\n// Conformance CLI: single-tx verification against the Label 309 standalone\n// verifier.\n//\n// Exit codes (extended with 4 for CLI input errors):\n// 0 = valid, 1 = failed (integrity), 2 = failed (network),\n// 3 = pending, 4 = CLI input error\n\nimport { KOIOS_MAINNET_URL, exitCodeForVerdict, verifyTx } from '../verifier/index';\n\nconst VERSION = '0.1.0';\n\ninterface ParsedArgs {\n readonly txHash: string | undefined;\n readonly gateways: ReadonlyArray<string>;\n readonly threshold: number | undefined;\n readonly json: boolean;\n readonly showHelp: boolean;\n readonly showVersion: boolean;\n readonly error: string | undefined;\n}\n\nexport function parseArgs(args: ReadonlyArray<string>): ParsedArgs {\n let txHash: string | undefined;\n const gateways: string[] = [];\n let threshold: number | undefined;\n let json = true;\n let showHelp = false;\n let showVersion = false;\n let error: string | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!;\n if (arg === '--help' || arg === '-h') {\n showHelp = true;\n } else if (arg === '--version' || arg === '-V') {\n showVersion = true;\n } else if (arg === '--json') {\n json = true;\n } else if (arg === '--gateway') {\n const v = args[++i];\n if (v === undefined) {\n error = '--gateway requires a value';\n break;\n }\n gateways.push(v);\n } else if (arg === '--threshold') {\n const v = args[++i];\n const n = Number(v);\n if (v === undefined || !Number.isFinite(n) || !Number.isInteger(n) || n < 0) {\n error = '--threshold requires a non-negative integer';\n break;\n }\n threshold = n;\n } else if (arg.startsWith('-')) {\n error = `unknown flag: ${arg}`;\n break;\n } else if (txHash === undefined) {\n txHash = arg;\n } else {\n error = `unexpected positional argument: ${arg}`;\n break;\n }\n }\n\n return { txHash, gateways, threshold, json, showHelp, showVersion, error };\n}\n\nconst USAGE = `Usage: cardanowall-sdk-conformance <tx-hash> [--gateway <url>] [--threshold <n>] [--json]\n cardanowall-sdk-conformance --version\n cardanowall-sdk-conformance --help\n\nRuns the @cardanowall/sdk-ts standalone Label 309 verifier against a single\nCardano transaction. Exit codes:\n 0 = valid, 1 = failed (integrity), 2 = failed (network), 3 = pending,\n 4 = CLI input error.`;\n\nexport interface RunIO {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function run(args: ReadonlyArray<string>, io: RunIO): Promise<number> {\n const parsed = parseArgs(args);\n if (parsed.showHelp) {\n io.stdout(USAGE + '\\n');\n return 0;\n }\n if (parsed.showVersion) {\n io.stdout(`cardanowall-sdk-conformance ${VERSION}\\n`);\n return 0;\n }\n if (parsed.error !== undefined) {\n io.stderr(`cardanowall-sdk-conformance: ${parsed.error}\\n`);\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (parsed.txHash === undefined) {\n io.stderr('cardanowall-sdk-conformance: <tx-hash> is required\\n');\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (!/^[0-9a-f]{64}$/i.test(parsed.txHash)) {\n io.stderr(\n `cardanowall-sdk-conformance: invalid tx-hash (expected 64 hex chars): ${parsed.txHash}\\n`,\n );\n return 4;\n }\n\n const gateways = parsed.gateways.length > 0 ? parsed.gateways : [KOIOS_MAINNET_URL];\n\n try {\n const report = await verifyTx({\n txHash: parsed.txHash.toLowerCase(),\n cardanoGatewayChain: gateways,\n ...(parsed.threshold !== undefined ? { confirmationDepthThreshold: parsed.threshold } : {}),\n });\n io.stdout(JSON.stringify(report, null, 2) + '\\n');\n return exitCodeForVerdict(report);\n } catch (err) {\n io.stderr(\n `cardanowall-sdk-conformance: verifier error: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 2;\n }\n}\n\n// Only run as a script when invoked directly (not when imported by tests).\nif (/cli\\.(c?js|ts)$/.test(process.argv[1] ?? '')) {\n void run(process.argv.slice(2), {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n }).then((code) => process.exit(code));\n}\n"]}
1
+ {"version":3,"sources":["../../src/verifier/types.ts","../../../poe-standard/src/schema.ts","../../../crypto-core/src/cbor/errors.ts","../../../crypto-core/src/cbor/canonical.ts","../../../crypto-core/src/cbor/permissive.ts","../../../poe-standard/src/encoder.ts","../../../poe-standard/src/error-codes.ts","../../../poe-standard/src/carriage.ts","../../../crypto-core/src/hash/blake2b-256.ts","../../../crypto-core/src/sig/ed25519.ts","../../../crypto-core/src/util/compare-ct.ts","../../../crypto-core/src/cose/errors.ts","../../../crypto-core/src/cose/sign1.ts","../../../crypto-core/src/cose/cose-key.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/utils.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/_crystals.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/ml-kem.ts","../../../../node_modules/.pnpm/@noble+post-quantum@0.6.1/node_modules/@noble/post-quantum/src/hybrid.ts","../../../crypto-core/src/aead/errors.ts","../../../crypto-core/src/aead/chacha20-poly1305.ts","../../../crypto-core/src/kem/mlkem768x25519.ts","../../../crypto-core/src/kem/x25519.ts","../../../crypto-core/src/kdf/hkdf.ts","../../../crypto-core/src/sealed-poe/errors.ts","../../../crypto-core/src/sealed-poe/stream.ts","../../../crypto-core/src/sealed-poe/transcript.ts","../../../crypto-core/src/sealed-poe/wrap.ts","../../../crypto-core/src/sealed-poe/slot-acceptance.ts","../../../crypto-core/src/sealed-poe/unwrap.ts","../../../crypto-core/src/kdf/argon2id.ts","../../../crypto-core/src/unicode/nfkc16-data.ts","../../../crypto-core/src/unicode/nfkc16.ts","../../../crypto-core/src/sealed-poe/passphrase-normalize.ts","../../../crypto-core/src/sealed-poe/passphrase.ts","../../../crypto-core/src/sealed-poe/envelope-from-parsed.ts","../../../poe-standard/src/validator.ts","../../src/fetch/fetch-outbound.ts","../../../crypto-core/src/hash/sha-256.ts","../../../crypto-core/src/hash/merkle-sha2-256.ts","../../src/verifier/cid.ts","../../src/verifier/content.ts","../../src/verifier/cbor-walker.ts","../../src/verifier/items.ts","../../src/verifier/decrypt.ts","../../src/verifier/issues.ts","../../../crypto-core/src/merkle/leaves-list.ts","../../src/verifier/merkle.ts","../../src/verifier/profile.ts","../../src/verifier/tx-binding.ts","../../src/verifier/resolve.ts","../../src/hex.ts","../../src/verifier/signatures.ts","../../src/verifier/tx-witnesses.ts","../../src/verifier/verify.ts","../../src/verifier/serialize.ts","../../src/conformance/cli.ts"],"names":["z","encode","sortCoreDeterministic","decode","cdeDecodeOptions","out","CanonicalCborError","encodeCanonicalCbor","decodeCanonicalCbor","mapDecodeError","blake2b","ed","sha512","opts","abytes","randb","abytes_","N","Q","F","ROOT_OF_UNITY","reverseBits","FFTCore","shake128","u32","swap32IfBE","shake256","sha3_256","sha3_512","bytesToNumberLE","bytesToNumberBE","anumber","x25519","concatBytes","asciiToBytes","chacha20poly1305","hkdf","sha256","hashes","hmac","compareCt","CEK_LENGTH","ZERO_NONCE_12","X25519_SECRET_KEY_LENGTH","X25519_PUBLIC_KEY_LENGTH","NONCE_LENGTH","WRAP_LENGTH","SLOTS_MAC_LENGTH","argon2id","j","nobleSha256","blake2b224","BASE58_ALPHABET","readVarint","decoded","UTF8","issueOf","sortIssues","LEAF_PREFIX","NODE_PREFIX","DIGEST_LENGTH","validateLeaves","merkleSha2256Root","mthRecursive","largestPow2Lt","hashLeaf","hashNode","checkMerkleCommit","bytesToHex","ED25519_PUBLIC_KEY_LENGTH","ed2","L","leBytesToBigInt","verifyEd25519","asMap"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCO,IAAM,qBAAA,GAA6D,OAAO,MAAA,CAAO;AAAA,EACtF,KAAA,EAAO,CAAA;AAAA,EACP,MAAA,EAAQ,CAAA;AAAA,EACR,YAAA,EAAc,CAAA;AAAA,EACd,OAAA,EAAS;AACX,CAAC,CAAA;AAaM,IAAM,YAAA,GAAkD,OAAO,MAAA,CAAO;AAAA,EAC3E,IAAA,EAAM,CAAA;AAAA,EACN,MAAA,EAAQ,CAAA;AAAA,EACR,MAAA,EAAQ,CAAA;AAAA,EACR,kBAAA,EAAoB;AACtB,CAAC,CAAA;ACvBD,SAAS,aAAkC,KAAA,EAAU;AACnD,EAAA,OAAOA,MACJ,MAAA,CAAgB,CAAC,KAAA,KAAU,EAAE,iBAAiB,UAAA,CAAA,EAAa;AAAA,IAC1D,OAAA,EAAS;AAAA,GACV,CAAA,CACA,IAAA,CAAK,KAAK,CAAA;AACf;AAcO,IAAM,gBAAA,GAAmBA,KAAA,CAAE,UAAA,CAAW,UAAU,CAAA;AAEhD,IAAM,kBAAkBA,KAAA,CAAE,MAAA,CAAOA,KAAA,CAAE,MAAA,IAAU,gBAAgB,CAAA;AAU7D,IAAM,SAAA,GAAYA,MAAE,MAAA,EAAO;AAe3B,IAAM,kBAAA,GAAqB,YAAA;AAAA,EAChCA,MACG,MAAA,CAAO;AAAA,IACN,GAAA,EAAKA,MAAE,MAAA,EAAO;AAAA,IACd,IAAA,EAAMA,KAAA,CAAE,UAAA,CAAW,UAAU,CAAA;AAAA,IAC7B,UAAA,EAAYA,KAAA,CAAE,KAAA,CAAM,CAACA,KAAA,CA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CAAO,GAAG,CAAC;AAAA;AAAA,KAClG;AACA,IAAA,OAAO,CAAA;AAAA,EACT;AACF;AAGA,IAAI,kBAAkB,IAAA,CAAK,OAAA,CAAQ,KAAK,CAAC,CAAA,IAAK,EAAE,CAAA,EAAG;AACjD,EAAA,KAAK,GAAA,CAAI,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA,EAAG;AAAA,IAC9B,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,IAC3C,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI;AAAA,GAC5C,EAAE,IAAA,CAAK,CAAC,SAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA;AACtC","file":"cli.cjs","sourcesContent":["// Public types for the Label 309 standalone verifier.\n//\n// The verifier is service-independent: it depends only on the caller-supplied\n// Cardano / Arweave / IPFS gateway chains and a `denyHosts` policy. Every\n// outbound network call routes through `fetchOutbound` (the single recording\n// egress point) and lands in `VerifyReport.auditTrail` for audit.\n//\n// `VerifyReport` implements the normative report contract: the required key\n// set, the verdict / exit-code enums, the per-claim `contentCheck` states,\n// and the audit-trail entry shape are all pinned by the published\n// verify-report JSON Schema. The schema is a minimum — this implementation\n// adds informational fields (`record`, `signatures`, transaction\n// description) on top of it.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { FetchOutbound, HttpCallRecord } from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verdict / exit code\n// -----------------------------------------------------------------------------\n//\n// `failed` is reserved for record-attributable outcomes — integrity,\n// structural, signature, Merkle-mismatch, and service-independence-violation\n// classes, including METADATA_NOT_FOUND (the absence is proven by the\n// integrity-bound transaction itself). Provider misbehaviour can never\n// manufacture it. `unverifiable` means no record-attributable error is\n// present but a required check could not run — or could not be attributed —\n// for network, policy, or provider-integrity reasons. `pending` is the\n// below-confirmation-threshold outcome; no result from a pending record may\n// be presented as final.\n\nexport type Verdict = 'valid' | 'pending' | 'unverifiable' | 'failed';\n\n// valid → 0, failed → 1, unverifiable → 2, pending → 3. Exit codes 4+ denote\n// verifier-host runtime failures and never correspond to a verdict.\nexport type ExitCode = 0 | 1 | 2 | 3;\n\nexport const EXIT_CODE_FOR_VERDICT: Readonly<Record<Verdict, ExitCode>> = Object.freeze({\n valid: 0,\n failed: 1,\n unverifiable: 2,\n pending: 3,\n});\n\n// -----------------------------------------------------------------------------\n// Conformance profile\n// -----------------------------------------------------------------------------\n//\n// Strict-superset order: each higher profile reads everything below it plus\n// one additional surface. A verifier of a LOWER profile that sees a field\n// belonging to a HIGHER profile MUST emit `OUT_OF_PROFILE_SKIPPED`\n// (info severity) and continue — it MUST NOT report the record as invalid.\n\nexport type Profile = 'core' | 'signed' | 'sealed' | 'recipient-sealed';\n\nexport const PROFILE_RANK: Readonly<Record<Profile, number>> = Object.freeze({\n core: 0,\n signed: 1,\n sealed: 2,\n 'recipient-sealed': 3,\n});\n\n// -----------------------------------------------------------------------------\n// FetchOutbound (the verifier's only network egress point)\n// -----------------------------------------------------------------------------\n\nexport type {\n FetchOutbound,\n FetchOutboundOptions,\n FetchOutboundResult,\n HttpCallRecord,\n} from '../fetch/fetch-outbound';\n\n// -----------------------------------------------------------------------------\n// Verifier issue surface — re-exports the validator's `ValidationIssue` so\n// downstream consumers dispatch on a single union (`ErrorCode` covers both\n// Part A and Part B per `@cardanowall/poe-standard`).\n// -----------------------------------------------------------------------------\n\nexport type { ValidationIssue } from '@cardanowall/poe-standard';\n\n// -----------------------------------------------------------------------------\n// Decryption keyring\n// -----------------------------------------------------------------------------\n//\n// The verification run's keyring: a set of decryption credentials GLOBAL to\n// the run, not positionally paired with encrypted items. For each\n// `enc`-bearing item the verifier attempts every applicable credential\n// independently — `recipientSecretKey` entries against the `enc.slots` path\n// (a 32-byte X25519 scalar or a 32-byte X-Wing decapsulation seed; the KEM is\n// dispatched from the envelope), `passphrase` entries against the\n// `enc.passphrase` path. One credential may open several items; different\n// credentials may succeed on different items. An `enc`-bearing item for which\n// the keyring holds no credential of the applicable shape is reported with\n// WRONG_DECRYPTION_INPUT_SHAPE.\n\nexport type DecryptionCredential =\n | { readonly recipientSecretKey: Uint8Array }\n | { readonly passphrase: string };\n\n// -----------------------------------------------------------------------------\n// VerifyTx input\n// -----------------------------------------------------------------------------\n\nexport interface VerifyTxInput {\n readonly txHash: string; // lowercase hex, no 0x prefix\n readonly profile?: Profile; // default 'recipient-sealed' (full pipeline)\n readonly cardanoGatewayChain?: ReadonlyArray<string>; // Koios-compatible URLs, in order\n readonly blockfrostProjectId?: string; // enables Blockfrost fallback\n readonly arweaveGatewayChain?: ReadonlyArray<string>;\n readonly ipfsGatewayChain?: ReadonlyArray<string>;\n readonly confirmationDepthThreshold?: number; // default 15; deployment policy\n readonly denyHosts?: ReadonlyArray<string>; // service-independence guard\n // Master content-fetch switch (default true). When `false`, every outbound\n // content fetch — item URIs, Merkle leaves-lists, and ciphertext alike — is\n // suppressed, so a record renders offline from the chain-resolved CBOR\n // alone with the affected content claims reported `not_checked`.\n // Caller-supplied out-of-band bytes (`ciphertextBytes`, `merkleLeaves`) are\n // still verified: they require no egress and are attributable by\n // definition.\n readonly fetchContent?: boolean;\n // Per-URI fetch ceiling in bytes, enforced incrementally during streaming.\n // Deployment policy, not a wire rule: a fetch that reaches the ceiling is\n // aborted and surfaced as CONTENT_FETCH_LIMIT_EXCEEDED (network/policy\n // class — a statement about the verifier, never about the record).\n readonly maxFetchBytes?: number;\n // The decryption keyring (see DecryptionCredential). Non-empty ⇒ the run is\n // a RECIPIENT verifier: the structural validator runs in the\n // 'recipient_or_strict' role and sealed decryption is attempted.\n readonly decryption?: ReadonlyArray<DecryptionCredential>;\n // Out-of-band ciphertext bytes for `enc`-bearing items, keyed by item\n // index. Takes precedence over `items[i].uris[]` (no fetch is issued) and\n // counts as attributable for the integrity/attribution split.\n readonly ciphertextBytes?: Readonly<Record<number, Uint8Array>>;\n // Out-of-band Merkle leaves-list bytes keyed by `record.merkle[i]` index.\n // CBOR is the normative wire form. Attributable by definition.\n readonly merkleLeaves?: Readonly<Record<number, Uint8Array>>;\n // The network the configured explorer chain serves. Drives the report's\n // `network` identifier and the expected network-header byte recomputed for\n // wallet-path signature addresses — never echoed from the record body,\n // which carries no network value. Defaults to 'mainnet'.\n readonly cardanoNetwork?: 'mainnet' | 'preprod';\n // Injected for tests; defaults to the canonical egress primitive.\n readonly fetchOutbound?: FetchOutbound;\n}\n\n// -----------------------------------------------------------------------------\n// Sibling entry point: caller-supplied record bytes + block-info tuple\n// -----------------------------------------------------------------------------\n//\n// Runs the same pipeline from the structural-validator step onward — the path\n// a server-rendered viewer uses to display on-chain data without a\n// render-time chain fetch. The caller vouches that `metadataCbor` is the\n// reassembled label-309 record body of a real transaction and supplies the\n// explorer-asserted block-info tuple the chain fetch would have produced.\n\nexport interface VerifyResolvedInput {\n readonly txHash: string;\n // The reassembled canonical record-body bytes (the chunk-array transport\n // already concatenated). NOT re-derived from `txCbor`.\n readonly metadataCbor: Uint8Array;\n // Explorer-asserted confirmation depth in blocks (tip − block + 1; a tx in\n // the tip block has depth exactly 1). Must be an integer >= 1 — a smaller\n // value is impossible for a transaction in a block and is rejected as a\n // caller-input error (RangeError), never folded into a report outcome.\n readonly confirmationDepth: number;\n // POSIX seconds UTC of the slot of the including block.\n readonly blockTime: number;\n readonly blockSlot?: number;\n // Raw on-chain transaction CBOR. When supplied, the report also carries the\n // transaction-level description (txWitnesses, txSummary, metadataLabels);\n // the label-309 record is always taken from `metadataCbor`.\n readonly txCbor?: Uint8Array;\n readonly network?: string;\n readonly cardanoNetwork?: 'mainnet' | 'preprod';\n readonly profile?: Profile;\n readonly confirmationDepthThreshold?: number;\n readonly arweaveGatewayChain?: ReadonlyArray<string>;\n readonly ipfsGatewayChain?: ReadonlyArray<string>;\n readonly fetchOutbound?: FetchOutbound;\n readonly denyHosts?: ReadonlyArray<string>;\n readonly fetchContent?: boolean;\n readonly maxFetchBytes?: number;\n readonly decryption?: ReadonlyArray<DecryptionCredential>;\n readonly ciphertextBytes?: Readonly<Record<number, Uint8Array>>;\n readonly merkleLeaves?: Readonly<Record<number, Uint8Array>>;\n}\n\n// -----------------------------------------------------------------------------\n// Per-claim report entries\n// -----------------------------------------------------------------------------\n\n// Three-state per-claim status, so an unchecked claim can never masquerade as\n// a verified one. `checked` — bytes were obtained and every committed digest\n// matched; `mismatched` — attributable fetched (or decrypted) bytes failed a\n// commitment (record-attributable); `not_checked` — the claim was not checked\n// (`fetchContent` off, availability failure, unattributable fetched bytes, or\n// the per-URI fetch ceiling).\nexport type ContentCheck = 'checked' | 'mismatched' | 'not_checked';\n\n// The recipient-verifier outcome for one `enc`-bearing item after every\n// applicable keyring credential was attempted independently.\nexport interface DecryptionOutcome {\n readonly decrypted: boolean;\n // The post-decryption recheck: every digest in the item's `hashes` map\n // recomputed over the recovered plaintext. A concrete boolean whenever\n // decryption ran to completion; `false` raises URI_INTEGRITY_MISMATCH and\n // forces the record's verdict to `failed`.\n readonly plaintextHashOk?: boolean;\n // The typed code describing why decryption did not succeed; the same code\n // also appears in the issue list when it affects the verdict.\n readonly code?: string;\n}\n\nexport interface ItemReportEntry {\n readonly contentCheck: ContentCheck;\n readonly decryption?: DecryptionOutcome;\n}\n\nexport interface MerkleReportEntry {\n readonly contentCheck: ContentCheck;\n}\n\n// -----------------------------------------------------------------------------\n// Record-signature results (informational extra; failures also raise issues)\n// -----------------------------------------------------------------------------\n\nexport type SignatureVerdict = 'valid' | 'invalid' | 'unsupported' | 'unresolved';\nexport type SignatureFailureReason =\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'SIGNATURE_UNSUPPORTED'\n | 'SIGNER_KEY_UNRESOLVED'\n | 'SIGNATURE_INVALID'\n | 'WALLET_ADDRESS_MISMATCH';\n\nexport type SignerType = 'in-signature-kid' | 'wallet-inline-key';\n\nexport interface VerifyRecordSignature {\n readonly index: number;\n readonly verdict: SignatureVerdict;\n readonly signerPub?: string; // lowercase hex of the resolved 32-byte Ed25519 pubkey\n readonly signerType?: SignerType;\n readonly reason?: SignatureFailureReason;\n}\n\n// -----------------------------------------------------------------------------\n// Transaction-level description — DISTINCT from record-level authorship.\n// -----------------------------------------------------------------------------\n//\n// These surfaces describe the Cardano transaction that carried the PoE: which\n// wallet vkey(s) authorised/paid for it, the fee, and the outputs. This is\n// the \"who submitted and paid for this anchoring\" view — orthogonal to\n// `signatures`, the optional record-level authorship claim. A failed\n// `signature_valid` here is INFORMATIONAL: it never changes the verdict (the\n// content claim does not depend on who paid the fee).\n\nexport interface VerifyTxWitness {\n readonly type: 'vkey';\n readonly vkey: string; // hex 32B Ed25519 pubkey\n readonly key_hash: string; // hex 28B Blake2b-224(vkey)\n readonly signature_valid: boolean; // Ed25519.verify(sig, blake2b256(tx_body), vkey)\n}\n\nexport interface VerifyTxOutput {\n readonly address: string; // bech32\n readonly lovelace: string; // decimal string\n}\n\nexport interface VerifyTxSummary {\n readonly fee_lovelace: string; // decimal string\n readonly input_count: number;\n readonly output_count: number;\n readonly outputs: ReadonlyArray<VerifyTxOutput>;\n readonly total_output_lovelace: string; // decimal string\n readonly script_witness_count: number;\n readonly invalid_before?: number;\n readonly invalid_hereafter?: number;\n readonly required_signer_key_hashes?: ReadonlyArray<string>;\n readonly network_id?: number;\n}\n\n// -----------------------------------------------------------------------------\n// VerifyReport\n// -----------------------------------------------------------------------------\n\nexport interface VerifyReport {\n // ── Normative minimum (the published report schema) ──────────────────────\n readonly verdict: Verdict;\n readonly exitCode: ExitCode;\n // The structural-validation issue list plus every verifier-layer code\n // raised by the run, sorted segment-wise by path (integer segments\n // numerically, text segments by bytewise UTF-8 order, integer before text\n // where kinds differ, prefix before extension); identical paths tie-break\n // by error-code-registry order. Run-level codes carry an empty path.\n readonly issues: ReadonlyArray<ValidationIssue>;\n // One entry per record `items[]` element, positionally aligned. Empty\n // exactly when the record carries no `items` array (including every\n // outcome where no record was parsed).\n readonly items: ReadonlyArray<ItemReportEntry>;\n // One entry per record `merkle[]` element, positionally aligned.\n readonly merkle: ReadonlyArray<MerkleReportEntry>;\n // Every outbound network call of the run — success, failure, retry —\n // captured by the single recording egress wrapper.\n readonly auditTrail: ReadonlyArray<HttpCallRecord>;\n // Network of the resolved transaction (e.g. `cardano:mainnet`), as\n // established by the explorer chain the verifier is configured against.\n readonly network: string;\n // Explorer-asserted depth in blocks; present whenever the transaction\n // resolved (always, for valid/pending).\n readonly confirmationDepth?: number;\n readonly confirmationThreshold?: number;\n // POSIX seconds UTC of the slot of the including block — the time T in\n // \"this content existed on or before T\".\n readonly block_time?: number;\n readonly block_slot?: number;\n\n // ── Implementation extras (the schema is an open map) ────────────────────\n readonly txHash: string;\n readonly profile: Profile;\n readonly record?: PoeRecord;\n readonly signatures?: ReadonlyArray<VerifyRecordSignature>;\n // Present only when raw tx CBOR is available to the pipeline (the live\n // `verifyTx` path always has it; `verifyResolved` only when `txCbor` is\n // passed).\n readonly txWitnesses?: ReadonlyArray<VerifyTxWitness>;\n readonly txSummary?: VerifyTxSummary;\n readonly metadataLabels?: ReadonlyArray<number>; // ascending; all aux metadata labels\n}\n","// Label 309 v1 PoE record Zod schemas.\n//\n// Scope: structural shape gate over the DECODED record body. The schema\n// enforces per-field CBOR types (every map position rejects a CBOR byte\n// string — see the text-keyed-map gate below), the fixed byte lengths a field\n// can assert in isolation (32-byte `supersedes`, 32-byte `slots_mac`, the\n// 16..64-byte passphrase salt), closed-map invariants (`items[i]`,\n// `merkle[i]`, `sigs[i]`, `passphrase`), and the `v == 1` literal.\n// Cross-field rules (content-hash binding under `enc`, slots/passphrase\n// exclusivity, `crit[]` shape, registry membership of algorithm identifiers,\n// COSE_Sign1 structural decode, URI shape, non-empty-array rules, integer\n// ranges) fire in `validator.ts` so each violation emits its precise\n// canonical code rather than a generic schema mismatch.\n//\n// Every logical byte string is a SINGLE CBOR byte string and every URI is a\n// SINGLE text string: record-body fields carry no 64-byte cap and no chunk\n// wrappers. The ledger's 64-byte metadata-string cap is satisfied by the\n// whole-body transport chunk array alone (see `carriage.ts`), which is\n// reassembled before the validator ever sees the body.\n\nimport { z } from 'zod';\n\n// =============================================================================\n// Text-keyed-map gate\n// =============================================================================\n//\n// Every map position in the record grammar is a CBOR text-keyed map. The\n// canonical decoder surfaces such a map as a plain object — but a CBOR byte\n// string surfaces as a Uint8Array, which is ALSO an object to Zod, so an\n// ungated object schema would walk its byte indices as if they were map keys\n// and mis-report one unknown-key issue per byte plus a missing-required issue\n// per absent field. The gate runs ahead of the map schema and fails a byte\n// string with a SINGLE issue at the position itself — the same one-issue\n// rejection every other non-map CBOR shape already receives from the object\n// parser; the validator's issue mapper then lifts it to the position's\n// canonical code by path. (`z.record` positions need no gate: Zod's record\n// parser rejects a Uint8Array outright. A map carrying non-text keys decodes\n// to a `Map` and is handled by the validator's pre-guard, not here.)\nfunction textKeyedMap<S extends z.ZodType>(inner: S) {\n return z\n .custom<unknown>((value) => !(value instanceof Uint8Array), {\n message: 'CBOR byte string present where a text-keyed map is required',\n })\n .pipe(inner);\n}\n\n// =============================================================================\n// Hashes map\n// =============================================================================\n//\n// `hashes` is a non-empty CBOR map keyed by content-hash algorithm identifier\n// (a text string from the content-hash registry) with the 32-byte digest as\n// value. The canonical decoder surfaces a text-keyed CBOR map as a plain JS\n// object — `z.record` admits any string key here. Registry membership\n// (`UNSUPPORTED_HASH_ALG`), per-algorithm digest length\n// (`HASH_DIGEST_LENGTH_MISMATCH`), and the non-empty rule live in the\n// validator's domain pass.\n\nexport const HashDigestSchema = z.instanceof(Uint8Array);\n\nexport const HashesMapSchema = z.record(z.string(), HashDigestSchema);\nexport type HashesMap = z.infer<typeof HashesMapSchema>;\n\n// =============================================================================\n// URIs\n// =============================================================================\n//\n// One absolute URI in a single text string. Absolute-URI / fragment / scheme\n// / per-scheme body rules (`INVALID_URI`) are domain checks.\n\nexport const UriSchema = z.string();\nexport type Uri = z.infer<typeof UriSchema>;\n\n// =============================================================================\n// Top-level `merkle[]`\n// =============================================================================\n//\n// Each commit is a closed map `{alg, root, leaf_count, ? uris}`. `alg` is open\n// (registry membership → `UNSUPPORTED_MERKLE_COMMIT_ALG` in the domain pass).\n// `leaf_count` is a CBOR unsigned integer pinned to `1 .. 2^32 − 1`, handled\n// as an EXACT integer: the canonical decoder surfaces values above 2^53 − 1 as\n// `bigint`, so the schema admits both representations and the domain pass\n// enforces the range (`SCHEMA_MERKLE_LEAF_COUNT_INVALID`) without ever\n// rounding through a float.\n\nexport const MerkleCommitSchema = textKeyedMap(\n z\n .object({\n alg: z.string(),\n root: z.instanceof(Uint8Array),\n leaf_count: z.union([z.number().int(), z.bigint()]),\n uris: z.array(UriSchema).optional(),\n })\n .strict(),\n);\nexport type MerkleCommit = z.infer<typeof MerkleCommitSchema>;\n\n// =============================================================================\n// Encryption envelope\n// =============================================================================\n//\n// The wire `enc` value is a CHOICE between two readings, mirroring the\n// grammar's `enc = enc-scheme-1 / enc-opaque`:\n//\n// - the scheme-1 shape — the closed map this revision defines, applied by\n// the validator only when `scheme`, `kem`, and `aead` are ALL supported\n// identifiers;\n// - the opaque reading — `scheme` (any CBOR unsigned integer) plus\n// arbitrary text-keyed bounded metadata, the degrade-to-opaque escape\n// hatch for envelopes under identifiers this implementation does not\n// support (`ENC_UNSUPPORTED`).\n//\n// The choice is not a discriminator: a `scheme: 1` envelope that fails the\n// scheme-1 shape is rejected with its typed code, never reclassified as\n// opaque. The validator therefore keeps `enc` as `unknown` at the item layer\n// and dispatches on raw `scheme` / `kem` / `aead` support before applying\n// `EncScheme1Schema`.\n\n// Per-slot recipient entry. The slot shape is KEM-driven:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — `epk` is the\n// ephemeral X25519 public key.\n// - mlkem768x25519: `{ kem_ct: bstr(1120), wrap: bstr(48) }` — `kem_ct` is\n// the single 1120-byte X-Wing encapsulation; there is NO per-slot `epk`\n// on the hybrid path (the X25519 ephemeral is the trailing 32 bytes of\n// `kem_ct`).\n//\n// The schema is deliberately PERMISSIVE: all three fields are optional and\n// `.strict()` is not applied, because the required shape depends on the\n// envelope-level `kem`, which a slot cannot see in isolation. The KEM-driven\n// gate in the validator emits the precise codes (`KEM_EPK_LENGTH_MISMATCH`,\n// `KEM_CT_LENGTH_MISMATCH`, `WRAP_LENGTH_MISMATCH`, `ENC_SLOT_INVALID_SHAPE`)\n// against the RAW decoded slot key set, so cross-KEM contamination and stray\n// keys are rejected even though the schema strips nothing here.\nexport const SlotSchema = textKeyedMap(\n z.object({\n epk: z.instanceof(Uint8Array).optional(),\n kem_ct: z.instanceof(Uint8Array).optional(),\n wrap: z.instanceof(Uint8Array).optional(),\n }),\n);\nexport type Slot = z.infer<typeof SlotSchema>;\n\n// Argon2id params `{m, t, p}` — a closed map of CBOR unsigned integers in the\n// pinned `0 .. 2^32 − 1` exact-integer range. The closed-map rule, the range,\n// and the floor checks all emit their codes in the validator's domain pass;\n// this schema is the public convenience type for producers.\nexport const Argon2idParamsSchema = textKeyedMap(\n z\n .object({\n m: z.union([z.number().int(), z.bigint()]),\n t: z.union([z.number().int(), z.bigint()]),\n p: z.union([z.number().int(), z.bigint()]),\n })\n .strict(),\n);\nexport type Argon2idParams = z.infer<typeof Argon2idParamsSchema>;\n\n// Passphrase block. `alg` is open (registry membership →\n// `ENC_PASSPHRASE_ALG_UNSUPPORTED` in the domain pass); `params` is open here\n// (the domain pass narrows on the registered `alg` and emits\n// `SCHEMA_UNKNOWN_FIELD` / `SCHEMA_MISSING_REQUIRED` / `SCHEMA_TYPE_MISMATCH`\n// / the floor and ceiling codes per sub-field). Salt length bounds are\n// schema-layer refinements carrying their dedicated codes.\nexport const PassphraseBlockSchema = textKeyedMap(\n z\n .object({\n alg: z.string(),\n salt: z.instanceof(Uint8Array).superRefine((bytes, ctx) => {\n if (bytes.length < 16) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} < 16`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_SHORT' },\n });\n } else if (bytes.length > 64) {\n ctx.addIssue({\n code: 'custom',\n path: [],\n message: `passphrase.salt length ${bytes.length} > 64`,\n params: { code: 'ENC_PASSPHRASE_SALT_TOO_LONG' },\n });\n }\n }),\n params: z.record(z.string(), z.unknown()),\n })\n .strict(),\n);\nexport type PassphraseBlock = z.infer<typeof PassphraseBlockSchema>;\n\n// The typed scheme-1 envelope arm. Applied by the validator only when\n// `scheme` / `kem` / `aead` are all supported identifiers; under an\n// unsupported identifier the envelope takes the opaque reading instead and\n// this schema never runs. The map is CLOSED (`.strict()`): an unknown key in\n// a supported envelope is `SCHEMA_UNKNOWN_FIELD`, never a reason to fall back\n// to the opaque reading. Cross-field key-path invariants (exclusivity,\n// `slots` ↔ `slots_mac` ↔ `kem`, non-empty `slots`) are domain checks.\nexport const EncScheme1Schema = textKeyedMap(\n z\n .object({\n scheme: z.literal(1),\n aead: z.string(),\n kem: z.string().optional(),\n nonce: z.instanceof(Uint8Array),\n slots: z.array(SlotSchema).optional(),\n slots_mac: z\n .instanceof(Uint8Array)\n .refine((b) => b.length === 32, {\n params: { code: 'ENC_SLOTS_MAC_INVALID_LENGTH' },\n })\n .optional(),\n passphrase: PassphraseBlockSchema.optional(),\n })\n .strict(),\n);\nexport type EncScheme1 = z.infer<typeof EncScheme1Schema>;\n\n// The opaque reading: `scheme` is the only structurally required key (any\n// CBOR unsigned integer — `bigint` admits values above 2^53), and every other\n// text-keyed entry is unconstrained bounded metadata. A verifier escape\n// hatch, never a producer surface.\nexport const EncOpaqueSchema = textKeyedMap(\n z.looseObject({\n scheme: z.union([z.number().int().nonnegative(), z.bigint().nonnegative()]),\n }),\n);\nexport type EncOpaque = z.infer<typeof EncOpaqueSchema>;\n\nexport const EncryptionEnvelopeSchema = z.union([EncScheme1Schema, EncOpaqueSchema]);\nexport type EncryptionEnvelope = z.infer<typeof EncryptionEnvelopeSchema>;\n\n// =============================================================================\n// Item entry\n// =============================================================================\n\nexport const ItemEntrySchema = textKeyedMap(\n z\n .object({\n hashes: HashesMapSchema,\n uris: z.array(UriSchema).optional(),\n // Captured as `unknown`: the envelope is a union whose disposition\n // (typed scheme-1 vs opaque) depends on identifier support, so the\n // validator's domain pass — not this schema — narrows it.\n enc: z.unknown().optional(),\n })\n .strict(),\n);\nexport type ItemEntry = z.infer<typeof ItemEntrySchema>;\n\n// =============================================================================\n// Sig entry\n// =============================================================================\n//\n// Closed CBOR map `{cose_sign1, ? cose_key}`. Each value is a SINGLE byte\n// string carrying the CBOR-encoded COSE_Sign1 / COSE_Key. Canonical CBOR\n// map-key sort (RFC 8949 §4.2.1, bytewise lex on encoded keys) places\n// `cose_key` before `cose_sign1`; schema property order is irrelevant.\nexport const SigEntrySchema = textKeyedMap(\n z\n .object({\n cose_key: z.instanceof(Uint8Array).optional(),\n cose_sign1: z.instanceof(Uint8Array),\n })\n .strict(),\n);\nexport type SigEntry = z.infer<typeof SigEntrySchema>;\n\n// =============================================================================\n// Supersedence\n// =============================================================================\n\nexport const SupersedesSchema = z.instanceof(Uint8Array).refine((b) => b.length === 32, {\n params: { code: 'SUPERSEDES_TX_INVALID_LENGTH' },\n});\nexport type Supersedes = z.infer<typeof SupersedesSchema>;\n\n// =============================================================================\n// Top-level record\n// =============================================================================\n//\n// `v == 1` is a literal — a future major (`v: 2`) MUST be rejected with\n// `SCHEMA_INVALID_LITERAL`. `z.literal(1)` preserves the narrow `1` type for\n// the inferred `PoeRecord[\"v\"]` and emits Zod's `invalid_value` code, which\n// the validator's mapper lifts to `SCHEMA_INVALID_LITERAL`.\n//\n// `looseObject` admits extension keys; the validator's domain pass rejects\n// unknown keys that match neither extension namespace with\n// `SCHEMA_UNKNOWN_FIELD`.\nexport const VersionLiteralSchema = z.literal(1);\n\nexport const PoeRecordSchema = textKeyedMap(\n z.looseObject({\n v: VersionLiteralSchema,\n items: z.array(ItemEntrySchema).optional(),\n merkle: z.array(MerkleCommitSchema).optional(),\n supersedes: SupersedesSchema.optional(),\n sigs: z.array(SigEntrySchema).optional(),\n crit: z.array(z.string()).optional(),\n }),\n);\nexport type PoeRecord = z.infer<typeof PoeRecordSchema>;\n\n// =============================================================================\n// Closed top-level base-key registry\n// =============================================================================\n//\n// Used by the validator's domain pass to distinguish unknown-typo keys from\n// well-formed extension keys.\nexport const TOP_LEVEL_BASE_KEYS: ReadonlySet<string> = new Set([\n 'v',\n 'items',\n 'merkle',\n 'supersedes',\n 'sigs',\n 'crit',\n]);\n\n// Extension-key namespaces: `^x-.+` (vendor / experimental) and `^[a-z]+-.+`\n// (companion namespace), with control characters (U+0000–U+001F,\n// U+007F–U+009F) rejected ANYWHERE in the key — including a trailing newline,\n// so `x-note\\n` and `x-a\\nb` are both outside the namespace. The suffix\n// character class spells the exclusion out rather than relying on `.`\n// semantics, the literal `x-` / `[a-z]+-` prefixes admit no control\n// characters by construction, and `$` in JavaScript matches only at the true\n// end of the string, so a trailing newline cannot hide behind the anchor.\n// eslint-disable-next-line no-control-regex -- the control-character exclusion IS the admissibility rule\nexport const EXTENSION_KEY_VENDOR_RE = /^x-[^\\u0000-\\u001f\\u007f-\\u009f]+$/;\n// eslint-disable-next-line no-control-regex -- the control-character exclusion IS the admissibility rule\nexport const EXTENSION_KEY_COMPANION_RE = /^[a-z]+-[^\\u0000-\\u001f\\u007f-\\u009f]+$/;\n\nexport function isExtensionKey(k: string): boolean {\n return EXTENSION_KEY_VENDOR_RE.test(k) || EXTENSION_KEY_COMPANION_RE.test(k);\n}\n","// Every canonical-CBOR decode violation collapses to the single public Label 309\n// taxonomy code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate\n// keys, unsorted keys, non-minimal integer encodings, and invalid UTF-8 in text\n// strings. The taxonomy intentionally has one code for all of these; the\n// specific cause survives in the human-readable error message, not as a\n// separate code.\nexport type CanonicalCborErrorCode = 'MALFORMED_CBOR';\n\nexport class CanonicalCborError extends Error {\n readonly code: CanonicalCborErrorCode;\n\n constructor(code: CanonicalCborErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CanonicalCborError';\n this.code = code;\n }\n}\n","import { cdeDecodeOptions, decode, encode } from 'cbor2';\nimport { sortCoreDeterministic } from 'cbor2/sorts';\n\nimport { CanonicalCborError } from './errors';\n\nexport type CanonicalCborValue =\n | null\n | boolean\n | number\n | bigint\n | string\n | Uint8Array\n | readonly CanonicalCborValue[]\n | { readonly [key: string]: CanonicalCborValue }\n | ReadonlyMap<string | number, CanonicalCborValue>;\n\nexport function encodeCanonicalCbor(value: CanonicalCborValue): Uint8Array {\n return encode(value, {\n cde: true,\n collapseBigInts: true,\n rejectDuplicateKeys: true,\n sortKeys: sortCoreDeterministic,\n });\n}\n\nexport function decodeCanonicalCbor(bytes: Uint8Array): unknown {\n try {\n return decode(bytes, {\n ...cdeDecodeOptions,\n rejectStreaming: true,\n rejectDuplicateKeys: true,\n // A Label 309 record carries integers, byte/text strings, arrays, maps and\n // `null` — and nothing else. Without these rejections the major-type-7\n // surface leaks into the decoder: a float16/32/64 that happens to hold an\n // integral value (e.g. 1.0) silently decodes to the integer 1 and passes\n // a `z.literal(1)` / Number.isInteger schema check, so two byte strings\n // that are NOT byte-identical canonicalise to the same record. That\n // breaks the cross-implementation parity invariant (the Python twin\n // already rejects non-integer `v` / `enc.scheme` outright). Reject the\n // whole non-record surface — floats, negative zero, undefined, and\n // non-{true,false,null} simple values — so any such input surfaces as\n // MALFORMED_CBOR via mapDecodeError rather than decoding to a look-alike.\n rejectFloats: true,\n rejectNegativeZero: true,\n rejectUndefined: true,\n rejectSimple: true,\n });\n } catch (cause) {\n throw mapDecodeError(cause);\n }\n}\n\nfunction mapDecodeError(cause: unknown): CanonicalCborError {\n const message = cause instanceof Error ? cause.message : String(cause);\n const lower = message.toLowerCase();\n // Every canonical-decode violation collapses to the single public taxonomy\n // code MALFORMED_CBOR: indefinite-length (streaming) items, duplicate keys,\n // non-canonical (unsorted) key ordering, non-minimal integer encodings, and\n // invalid UTF-8 in text strings. cbor2 raises the SAME \"Duplicate or out of\n // order key\" message for both true duplicates AND distinct-but-unsorted keys,\n // so the two are indistinguishable by message — and per the Label 309 taxonomy\n // both belong under MALFORMED_CBOR anyway. The specific cause survives in the\n // human-readable message below; for indefinite-length we state it explicitly\n // so the diagnostic is not lost when the code is collapsed.\n const isIndefinite = lower.includes('streaming') || lower.includes('indefinite');\n const detail = isIndefinite\n ? `indefinite-length items are not permitted in canonical CBOR: ${message}`\n : message;\n return new CanonicalCborError('MALFORMED_CBOR', `cbor decode failed: ${detail}`, { cause });\n}\n","// Permissive (non-canonical) CBOR decoder for outer wire decode (e.g. Cardano tx CBOR),\n// where the input is not constrained to be canonical RFC 8949 §4.2.1 form.\n//\n// Label 309 records themselves MUST be canonical and MUST go through\n// `decodeCanonicalCbor`. This decoder\n// exists to peel the outer Cardano tx structure ([body, witness_set, is_valid,\n// auxiliary_data]) so the label-309 byte string can be re-encoded canonically\n// for validator + signature verification.\n\nimport { decode } from 'cbor2';\n\nexport function decodeCbor(bytes: Uint8Array): unknown {\n return decode(bytes);\n}\n","// Label 309 v1 record encoder.\n//\n// Produces canonical CBOR bytes per RFC 8949 §4.2.1 deterministic encoding —\n// definite lengths, bytewise-lexicographically sorted map keys, no duplicate\n// keys, shortest-form integers. The canonical layer\n// (`@cardanowall/crypto-core/cbor`) owns those rules, so this module's job is\n// only to project the typed record onto the CBOR value algebra.\n//\n// That projection is the identity: under the Label 309 wire shapes every\n// record field already IS its CBOR value — `hashes` is a text-keyed map of\n// byte-string digests, each URI is a single text string, `kem_ct` /\n// `cose_sign1` / `cose_key` are single byte strings, and the canonical\n// encoder derives map-key order itself. The only transformation performed\n// here is dropping `undefined` optionals (a JS-only artefact with no CBOR\n// counterpart — left in place it would encode as the `undefined` simple\n// value, which the canonical profile forbids) and, for the signing body,\n// removing `sigs`.\n//\n// Round-trip property: for every record `R` the validator accepts,\n// validatePoeRecord(encodePoeRecord(R)).valid === true\n// and the decoded record is `R` (modulo CBOR-canonical key order).\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '@cardanowall/crypto-core/cbor';\n\nimport type { PoeRecord } from './schema';\n\n/** Canonical CBOR bytes of the full record body — the bytes the chunk-array\n * transport carries on chain (see `carriage.ts`). */\nexport function encodePoeRecord(record: PoeRecord): Uint8Array {\n return encodeCanonicalCbor(toCborValue(record, /* includeSigs */ true));\n}\n\n/**\n * Canonical CBOR bytes of the record body **with `sigs` removed** — the body\n * a record-level signature covers. Producers prepend the 25-byte UTF-8 domain\n * prefix `cardano-poe-record-sig-v1` before invoking Ed25519 (the crypto-core\n * helper `buildLabel309SigStructure` handles the prefix and the\n * `Sig_structure` wrapping). Extension keys are part of the signed body and\n * pass through verbatim.\n */\nexport function encodeRecordBodyForSigning(record: PoeRecord): Uint8Array {\n return encodeCanonicalCbor(toCborValue(record, /* includeSigs */ false));\n}\n\nfunction toCborValue(record: PoeRecord, includeSigs: boolean): CanonicalCborValue {\n const out: { [key: string]: CanonicalCborValue } = {};\n for (const [key, value] of Object.entries(record)) {\n if (value === undefined) continue;\n if (!includeSigs && key === 'sigs') continue;\n out[key] = stripUndefined(value as CanonicalCborValue);\n }\n return out;\n}\n\n// Drop `undefined`-valued properties recursively. A typed record reaches the\n// encoder with its optional fields either absent or explicitly `undefined`;\n// CBOR has no counterpart for the latter (cbor2 would emit the major-type-7\n// `undefined` simple value, which the canonical profile rejects on decode),\n// so both spell \"absent\" on the wire.\nfunction stripUndefined(value: CanonicalCborValue): CanonicalCborValue {\n if (value === null || typeof value !== 'object' || value instanceof Uint8Array) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((element) => stripUndefined(element));\n }\n if (value instanceof Map) {\n const out = new Map<string | number, CanonicalCborValue>();\n for (const [k, v] of value) {\n if (v === undefined) continue;\n out.set(k, stripUndefined(v));\n }\n return out;\n }\n const out: { [key: string]: CanonicalCborValue } = {};\n for (const [k, v] of Object.entries(value)) {\n if (v === undefined) continue;\n out[k] = stripUndefined(v as CanonicalCborValue);\n }\n return out;\n}\n","// Label 309 v1 error-code catalogue — the TypeScript projection of the\n// machine-readable registry (`error-codes.json` in the Label 309 distribution).\n//\n// Three layers emit these codes:\n// - Part A — the structural validator (`validatePoeRecord`): a pure\n// function over the reassembled CBOR record body.\n// - carriage — the pre-validator transport step that reassembles the\n// label-309 chunk array (`reassembleLabel309Value`).\n// - Part B — the public / recipient verifier (chain resolution,\n// signature verification, content fetch, decryption).\n// Re-exported here so downstream verifiers dispatch on a\n// single `ErrorCode` union.\n//\n// Codes are SCREAMING_SNAKE_CASE and MUST match the canonical catalogue\n// byte-exact across the TS/PY/RS implementations — no lowercase synonyms,\n// no parser-internal codes, no free-form reason strings.\n//\n// `ERROR_CODES` preserves the registry's entry order. That order is\n// load-bearing: issues sharing an identical path tie-break by the order in\n// which their codes appear in the registry, so the list below doubles as the\n// cross-implementation sort key (`errorCodeRegistryIndex`).\n\nexport const ERROR_CODES = [\n 'MALFORMED_CBOR',\n 'SCHEMA_TYPE_MISMATCH',\n 'SCHEMA_MISSING_REQUIRED',\n 'SCHEMA_UNKNOWN_FIELD',\n 'SCHEMA_INVALID_LITERAL',\n 'SCHEMA_EMPTY_RECORD',\n 'HASH_DIGEST_LENGTH_MISMATCH',\n 'UNSUPPORTED_HASH_ALG',\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n 'SCHEMA_MERKLE_LEAF_COUNT_INVALID',\n 'INVALID_URI',\n 'CHUNK_TOO_LARGE',\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n 'UNSUPPORTED_AEAD_ALG',\n 'NONCE_LENGTH_MISMATCH',\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n 'ENC_UNSUPPORTED',\n 'ENC_SLOTS_EMPTY',\n 'ENC_SLOT_INVALID_SHAPE',\n 'UNSUPPORTED_KEM_ALG',\n 'ENC_KEM_REQUIRED',\n 'KEM_EPK_LENGTH_MISMATCH',\n 'KEM_CT_LENGTH_MISMATCH',\n 'WRAP_LENGTH_MISMATCH',\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n 'ENC_SLOTS_MAC_REQUIRED',\n 'ENC_SLOTS_REQUIRED',\n 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL',\n 'ENC_SLOTS_TOO_MANY',\n 'ENC_ENVELOPE_TOO_LARGE',\n 'ENC_EXCLUSIVITY_VIOLATION',\n 'ENC_NO_KEY_PATH',\n 'ENC_REQUIRES_CONTENT_HASH',\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n 'ENC_PASSPHRASE_SALT_TOO_SHORT',\n 'ENC_PASSPHRASE_SALT_TOO_LONG',\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n 'ENC_PASSPHRASE_PARAMS_EXCEED_POLICY',\n 'MALFORMED_SIG_COSE_SIGN1',\n 'SIGNATURE_UNSUPPORTED',\n 'SIG_ENTRY_INVALID_SHAPE',\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n 'SIG_PRIVATE_KEY_LEAKED',\n 'SUPERSEDES_TX_INVALID_LENGTH',\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n 'CRIT_SHAPE_INVALID',\n 'TX_NOT_FOUND',\n 'PROVIDER_UNAVAILABLE',\n 'TX_INTEGRITY_MISMATCH',\n 'METADATA_NOT_FOUND',\n 'INSUFFICIENT_CONFIRMATIONS',\n 'SIGNATURE_INVALID',\n 'SIGNER_KEY_UNRESOLVED',\n 'WALLET_ADDRESS_MISMATCH',\n 'URI_TARGET_FORBIDDEN',\n 'URI_INTEGRITY_MISMATCH',\n 'URI_PROVIDER_INTEGRITY_MISMATCH',\n 'URI_FETCH_FAILED',\n 'CONTENT_UNAVAILABLE',\n 'CONTENT_FETCH_LIMIT_EXCEEDED',\n 'CIPHERTEXT_UNAVAILABLE',\n 'SERVICE_INDEPENDENCE_VIOLATION',\n 'WRONG_DECRYPTION_INPUT_SHAPE',\n 'WRONG_RECIPIENT_KEY',\n 'TAMPERED_HEADER',\n 'TAMPERED_CIPHERTEXT',\n 'KDF_DERIVATION_FAILED',\n 'ENC_PASSPHRASE_UNNORMALIZABLE',\n 'ENC_PASSPHRASE_EMPTY',\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'MERKLE_ROOT_MISMATCH',\n 'MERKLE_LEAVES_UNAVAILABLE',\n 'MERKLE_UNSUPPORTED',\n 'OUT_OF_PROFILE_SKIPPED',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n// =============================================================================\n// Emitting layer (`part` in the registry)\n// =============================================================================\n\nexport type ErrorCodePart = 'A' | 'B' | 'carriage';\n\nexport const ERROR_CODE_PART: Readonly<Record<ErrorCode, ErrorCodePart>> = Object.freeze({\n MALFORMED_CBOR: 'A',\n SCHEMA_TYPE_MISMATCH: 'A',\n SCHEMA_MISSING_REQUIRED: 'A',\n SCHEMA_UNKNOWN_FIELD: 'A',\n SCHEMA_INVALID_LITERAL: 'A',\n SCHEMA_EMPTY_RECORD: 'A',\n HASH_DIGEST_LENGTH_MISMATCH: 'A',\n UNSUPPORTED_HASH_ALG: 'A',\n UNSUPPORTED_MERKLE_COMMIT_ALG: 'A',\n SCHEMA_MERKLE_LEAF_COUNT_INVALID: 'A',\n INVALID_URI: 'A',\n CHUNK_TOO_LARGE: 'carriage',\n UNAUTHENTICATED_CIPHER_FORBIDDEN: 'A',\n UNSUPPORTED_AEAD_ALG: 'A',\n NONCE_LENGTH_MISMATCH: 'A',\n UNSUPPORTED_ENVELOPE_SCHEME: 'A',\n ENC_UNSUPPORTED: 'A',\n ENC_SLOTS_EMPTY: 'A',\n ENC_SLOT_INVALID_SHAPE: 'A',\n UNSUPPORTED_KEM_ALG: 'A',\n ENC_KEM_REQUIRED: 'A',\n KEM_EPK_LENGTH_MISMATCH: 'A',\n KEM_CT_LENGTH_MISMATCH: 'A',\n WRAP_LENGTH_MISMATCH: 'A',\n ENC_SLOTS_MAC_INVALID_LENGTH: 'A',\n ENC_SLOTS_MAC_REQUIRED: 'A',\n ENC_SLOTS_REQUIRED: 'A',\n ENC_SLOTS_DUPLICATE_KEM_MATERIAL: 'A',\n ENC_SLOTS_TOO_MANY: 'A',\n ENC_ENVELOPE_TOO_LARGE: 'A',\n ENC_EXCLUSIVITY_VIOLATION: 'A',\n ENC_NO_KEY_PATH: 'A',\n ENC_REQUIRES_CONTENT_HASH: 'A',\n ENC_PASSPHRASE_ALG_UNSUPPORTED: 'A',\n ENC_PASSPHRASE_SALT_TOO_SHORT: 'A',\n ENC_PASSPHRASE_SALT_TOO_LONG: 'A',\n ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW: 'A',\n ENC_PASSPHRASE_PARAMS_EXCEED_POLICY: 'A',\n MALFORMED_SIG_COSE_SIGN1: 'A',\n SIGNATURE_UNSUPPORTED: 'A',\n SIG_ENTRY_INVALID_SHAPE: 'A',\n SIG_ENTRY_KID_COSE_KEY_CONFLICT: 'A',\n SIG_PRIVATE_KEY_LEAKED: 'A',\n SUPERSEDES_TX_INVALID_LENGTH: 'A',\n EXTENSION_UNSUPPORTED_CRITICAL: 'A',\n CRIT_SHAPE_INVALID: 'A',\n TX_NOT_FOUND: 'B',\n PROVIDER_UNAVAILABLE: 'B',\n TX_INTEGRITY_MISMATCH: 'B',\n METADATA_NOT_FOUND: 'B',\n INSUFFICIENT_CONFIRMATIONS: 'B',\n SIGNATURE_INVALID: 'B',\n SIGNER_KEY_UNRESOLVED: 'B',\n WALLET_ADDRESS_MISMATCH: 'B',\n URI_TARGET_FORBIDDEN: 'B',\n URI_INTEGRITY_MISMATCH: 'B',\n URI_PROVIDER_INTEGRITY_MISMATCH: 'B',\n URI_FETCH_FAILED: 'B',\n CONTENT_UNAVAILABLE: 'B',\n CONTENT_FETCH_LIMIT_EXCEEDED: 'B',\n CIPHERTEXT_UNAVAILABLE: 'B',\n SERVICE_INDEPENDENCE_VIOLATION: 'B',\n WRONG_DECRYPTION_INPUT_SHAPE: 'B',\n WRONG_RECIPIENT_KEY: 'B',\n TAMPERED_HEADER: 'B',\n TAMPERED_CIPHERTEXT: 'B',\n KDF_DERIVATION_FAILED: 'B',\n ENC_PASSPHRASE_UNNORMALIZABLE: 'B',\n ENC_PASSPHRASE_EMPTY: 'B',\n SCHEMA_MERKLE_LEAF_COUNT_MISMATCH: 'B',\n SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED: 'B',\n SCHEMA_MERKLE_LEAVES_MALFORMED: 'B',\n MERKLE_ROOT_MISMATCH: 'B',\n MERKLE_LEAVES_UNAVAILABLE: 'B',\n MERKLE_UNSUPPORTED: 'B',\n OUT_OF_PROFILE_SKIPPED: 'B',\n});\n\n// Layer-filtered views, in registry order. The structural validator emits only\n// Part A codes; the carriage (transport) step emits only the carriage code;\n// the verifier layer emits Part B codes (and re-runs the first two layers).\nexport const STRUCTURAL_ERROR_CODES: ReadonlyArray<ErrorCode> = Object.freeze(\n ERROR_CODES.filter((code) => ERROR_CODE_PART[code] === 'A'),\n);\nexport const CARRIAGE_ERROR_CODES: ReadonlyArray<ErrorCode> = Object.freeze(\n ERROR_CODES.filter((code) => ERROR_CODE_PART[code] === 'carriage'),\n);\nexport const VERIFIER_ERROR_CODES: ReadonlyArray<ErrorCode> = Object.freeze(\n ERROR_CODES.filter((code) => ERROR_CODE_PART[code] === 'B'),\n);\n\nexport type StructuralErrorCode = ErrorCode;\nexport type VerifierErrorCode = ErrorCode;\n\n// =============================================================================\n// Severity\n// =============================================================================\n//\n// `error` fails the record; `warning` is a non-fatal runtime anomaly; `info`\n// is a deliberate non-failing disposition. Four codes carry DUAL severity —\n// the map records their DEFAULT reading, and a strict context promotes them\n// to `error`:\n// - ENC_UNSUPPORTED — info by default; error for the recipient\n// role / strict sealed-crypto mode.\n// - MERKLE_LEAVES_UNAVAILABLE — warning beside a verified content\n// commitment; error when its absence leaves\n// the record with no verified commitment.\n// - MERKLE_UNSUPPORTED — info beside a validated items[] claim;\n// error on a merkle-only record.\n// - OUT_OF_PROFILE_SKIPPED — info in render mode; error in strict\n// end-to-end mode.\n// No layer may soften an `error` into a `warning` to make a record pass.\n\nexport type Severity = 'error' | 'warning' | 'info';\n\nexport const SEVERITY: Readonly<Record<ErrorCode, Severity>> = Object.freeze({\n MALFORMED_CBOR: 'error',\n SCHEMA_TYPE_MISMATCH: 'error',\n SCHEMA_MISSING_REQUIRED: 'error',\n SCHEMA_UNKNOWN_FIELD: 'error',\n SCHEMA_INVALID_LITERAL: 'error',\n SCHEMA_EMPTY_RECORD: 'error',\n HASH_DIGEST_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_HASH_ALG: 'error',\n UNSUPPORTED_MERKLE_COMMIT_ALG: 'error',\n SCHEMA_MERKLE_LEAF_COUNT_INVALID: 'error',\n INVALID_URI: 'error',\n CHUNK_TOO_LARGE: 'error',\n UNAUTHENTICATED_CIPHER_FORBIDDEN: 'error',\n UNSUPPORTED_AEAD_ALG: 'error',\n NONCE_LENGTH_MISMATCH: 'error',\n UNSUPPORTED_ENVELOPE_SCHEME: 'error',\n ENC_UNSUPPORTED: 'info',\n ENC_SLOTS_EMPTY: 'error',\n ENC_SLOT_INVALID_SHAPE: 'error',\n UNSUPPORTED_KEM_ALG: 'error',\n ENC_KEM_REQUIRED: 'error',\n KEM_EPK_LENGTH_MISMATCH: 'error',\n KEM_CT_LENGTH_MISMATCH: 'error',\n WRAP_LENGTH_MISMATCH: 'error',\n ENC_SLOTS_MAC_INVALID_LENGTH: 'error',\n ENC_SLOTS_MAC_REQUIRED: 'error',\n ENC_SLOTS_REQUIRED: 'error',\n ENC_SLOTS_DUPLICATE_KEM_MATERIAL: 'error',\n ENC_SLOTS_TOO_MANY: 'error',\n ENC_ENVELOPE_TOO_LARGE: 'error',\n ENC_EXCLUSIVITY_VIOLATION: 'error',\n ENC_NO_KEY_PATH: 'error',\n ENC_REQUIRES_CONTENT_HASH: 'error',\n ENC_PASSPHRASE_ALG_UNSUPPORTED: 'error',\n ENC_PASSPHRASE_SALT_TOO_SHORT: 'error',\n ENC_PASSPHRASE_SALT_TOO_LONG: 'error',\n ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW: 'error',\n ENC_PASSPHRASE_PARAMS_EXCEED_POLICY: 'error',\n MALFORMED_SIG_COSE_SIGN1: 'error',\n SIGNATURE_UNSUPPORTED: 'info',\n SIG_ENTRY_INVALID_SHAPE: 'error',\n SIG_ENTRY_KID_COSE_KEY_CONFLICT: 'error',\n SIG_PRIVATE_KEY_LEAKED: 'error',\n SUPERSEDES_TX_INVALID_LENGTH: 'error',\n EXTENSION_UNSUPPORTED_CRITICAL: 'error',\n CRIT_SHAPE_INVALID: 'error',\n TX_NOT_FOUND: 'error',\n PROVIDER_UNAVAILABLE: 'error',\n TX_INTEGRITY_MISMATCH: 'error',\n METADATA_NOT_FOUND: 'error',\n INSUFFICIENT_CONFIRMATIONS: 'info',\n SIGNATURE_INVALID: 'error',\n SIGNER_KEY_UNRESOLVED: 'error',\n WALLET_ADDRESS_MISMATCH: 'error',\n URI_TARGET_FORBIDDEN: 'error',\n URI_INTEGRITY_MISMATCH: 'error',\n URI_PROVIDER_INTEGRITY_MISMATCH: 'warning',\n URI_FETCH_FAILED: 'warning',\n CONTENT_UNAVAILABLE: 'error',\n CONTENT_FETCH_LIMIT_EXCEEDED: 'error',\n CIPHERTEXT_UNAVAILABLE: 'error',\n SERVICE_INDEPENDENCE_VIOLATION: 'error',\n WRONG_DECRYPTION_INPUT_SHAPE: 'error',\n WRONG_RECIPIENT_KEY: 'error',\n TAMPERED_HEADER: 'error',\n TAMPERED_CIPHERTEXT: 'error',\n KDF_DERIVATION_FAILED: 'error',\n ENC_PASSPHRASE_UNNORMALIZABLE: 'error',\n ENC_PASSPHRASE_EMPTY: 'error',\n SCHEMA_MERKLE_LEAF_COUNT_MISMATCH: 'error',\n SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED: 'error',\n SCHEMA_MERKLE_LEAVES_MALFORMED: 'error',\n MERKLE_ROOT_MISMATCH: 'error',\n MERKLE_LEAVES_UNAVAILABLE: 'warning',\n MERKLE_UNSUPPORTED: 'info',\n OUT_OF_PROFILE_SKIPPED: 'info',\n});\n\n// Codes whose severity is context-dependent. `SEVERITY` records the default\n// reading; the promoting context escalates to `error`.\nexport const DUAL_SEVERITY_CODES: ReadonlySet<ErrorCode> = new Set<ErrorCode>([\n 'ENC_UNSUPPORTED',\n 'MERKLE_LEAVES_UNAVAILABLE',\n 'MERKLE_UNSUPPORTED',\n 'OUT_OF_PROFILE_SKIPPED',\n]);\n\nexport function severityOf(code: ErrorCode): Severity {\n return SEVERITY[code];\n}\n\n// Position of a code in the canonical registry. Issues that carry an\n// identical path are ordered by this index, so every implementation sorts an\n// issue list identically.\nconst REGISTRY_INDEX: ReadonlyMap<ErrorCode, number> = new Map(\n ERROR_CODES.map((code, index) => [code, index]),\n);\n\nexport function errorCodeRegistryIndex(code: ErrorCode): number {\n return REGISTRY_INDEX.get(code) as number;\n}\n","// Label 309 metadata-label-309 carriage: the whole-body chunk-array transport.\n//\n// The Cardano ledger caps every metadata byte string and text string at 64\n// bytes, so a serialised record body crosses the ledger as an opaque\n// whole-body chunk array: a definite-length CBOR array of definite-length\n// byte strings of at most 64 bytes each, whose in-order concatenation is the\n// canonical record-body bytes. This transport split is the ONLY chunking the\n// format performs — fields inside the reassembled body are ordinary CBOR\n// values with no per-field chunk wrappers and no 64-byte cap of their own.\n//\n// This module owns both directions of that transport:\n//\n// - `chunkRecordBody` — producer: canonical body bytes → the chunk\n// array stored as the label-309 value.\n// - `reassembleLabel309Value`— consumer: raw label-309 value bytes → the\n// record body, enforcing the carriage-error\n// taxonomy (`MALFORMED_CBOR` for every\n// non-chunk-array shape, `CHUNK_TOO_LARGE` for\n// an oversized element, zero-length elements\n// tolerated).\n//\n// Reassembly happens BEFORE structural validation: `validatePoeRecord`\n// receives the concatenated body and never sees the transport wrapper.\n\nimport { decodeCanonicalCbor, encodeCanonicalCbor } from '@cardanowall/crypto-core/cbor';\n\nimport { SEVERITY, type ErrorCode } from './error-codes';\nimport type { ValidationIssue } from './validator';\n\n/** The ledger's per-metadatum string cap: the maximum transport chunk size. */\nexport const TRANSPORT_CHUNK_MAX_BYTES = 64;\n\n/**\n * Split a serialised record body into the whole-body transport chunk array —\n * the value a producer stores under metadata label 309.\n *\n * Uses the minimal split: every chunk except the last is exactly 64 bytes.\n * The chunk-array form is required regardless of body length, so a body of\n * 64 bytes or fewer still yields a one-element array. Chunks are copies — a\n * caller mutating the input body afterwards cannot corrupt them.\n *\n * A canonical CBOR record body is never empty, so zero-length input is a\n * caller bug and throws `RangeError` (the `1* bstr` transport grammar cannot\n * represent an empty body).\n */\nexport function chunkRecordBody(body: Uint8Array): Uint8Array[] {\n if (body.length === 0) {\n throw new RangeError('record body must be non-empty; a CBOR value is at least one byte');\n }\n const chunks: Uint8Array[] = [];\n for (let offset = 0; offset < body.length; offset += TRANSPORT_CHUNK_MAX_BYTES) {\n chunks.push(body.slice(offset, Math.min(offset + TRANSPORT_CHUNK_MAX_BYTES, body.length)));\n }\n return chunks;\n}\n\n/**\n * Serialise the transport chunk array to the CBOR bytes of the label-309\n * value (the byte form of `chunkRecordBody`'s output). Convenience for\n * producers and test harnesses that embed the value at the byte level.\n */\nexport function encodeLabel309Value(body: Uint8Array): Uint8Array {\n return encodeCanonicalCbor(chunkRecordBody(body));\n}\n\nexport type Label309ReassemblyResult =\n | { readonly ok: true; readonly body: Uint8Array }\n | { readonly ok: false; readonly issue: ValidationIssue };\n\n/**\n * Reassemble a label-309 value into the record body, enforcing the\n * carriage-error taxonomy:\n *\n * - a definite-length array of definite-length byte strings each ≤ 64\n * bytes is accepted; the body is the in-order concatenation;\n * - zero-length elements are tolerated (chunk boundaries are\n * semantics-free, including degenerate ones) — an array whose\n * concatenation is empty reassembles to zero bytes, and the failure then\n * surfaces from the canonical decode of the empty body, not from this\n * layer;\n * - an element longer than 64 bytes is `CHUNK_TOO_LARGE`;\n * - every other shape — a non-array value, a non-byte-string element, an\n * indefinite-length array or element — is `MALFORMED_CBOR`.\n *\n * The input is the raw CBOR bytes of the label-309 value exactly as carried\n * in the transaction's auxiliary data.\n */\nexport function reassembleLabel309Value(valueBytes: Uint8Array): Label309ReassemblyResult {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(valueBytes);\n } catch (cause) {\n return failure(\n 'MALFORMED_CBOR',\n `label-309 value failed to decode: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n if (!Array.isArray(decoded)) {\n return failure(\n 'MALFORMED_CBOR',\n 'label-309 value must be the whole-body chunk array (a CBOR array of byte strings), regardless of body length',\n );\n }\n let total = 0;\n for (let i = 0; i < decoded.length; i++) {\n const element: unknown = decoded[i];\n if (!(element instanceof Uint8Array)) {\n return failure('MALFORMED_CBOR', `chunk array element ${i} is not a byte string`);\n }\n if (element.length > TRANSPORT_CHUNK_MAX_BYTES) {\n return failure(\n 'CHUNK_TOO_LARGE',\n `chunk array element ${i} is ${element.length} bytes; the ledger caps metadata byte strings at ${TRANSPORT_CHUNK_MAX_BYTES}`,\n );\n }\n total += element.length;\n }\n const body = new Uint8Array(total);\n let offset = 0;\n for (const element of decoded as ReadonlyArray<Uint8Array>) {\n body.set(element, offset);\n offset += element.length;\n }\n return { ok: true, body };\n}\n\nfunction failure(code: ErrorCode, message: string): Label309ReassemblyResult {\n return { ok: false, issue: { code, path: [], message, severity: SEVERITY[code] } };\n}\n","import { blake2b } from '@noble/hashes/blake2.js';\n\nexport function blake2b256(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 32 });\n}\n\n// CIP-19 stake-address derivation, used for the wallet path-2 signer binding,\n// requires the 28-byte BLAKE2b digest of the signer's Ed25519 public key.\n// The Cardano ledger encodes stake addresses as\n// `network_header_byte || Blake2b-224(stake_vk)`\n// per CIP-19, so this output length is fixed by spec.\nexport function blake2b224(input: Uint8Array): Uint8Array {\n return blake2b(input, { dkLen: 28 });\n}\n","import * as ed from '@noble/ed25519';\nimport { sha512 } from '@noble/hashes/sha2.js';\n\ned.hashes.sha512 = sha512;\n\n// Ed25519 group order L (= 2^252 + 27742317777372353535851937790883648493).\nconst L = ed.Point.CURVE().n;\n\nexport interface SignEd25519Opts {\n readonly seed: Uint8Array;\n readonly message: Uint8Array;\n}\n\nexport interface VerifyEd25519Opts {\n readonly publicKey: Uint8Array;\n readonly message: Uint8Array;\n readonly signature: Uint8Array;\n}\n\nexport interface GetPublicKeyEd25519Opts {\n readonly seed: Uint8Array;\n}\n\nexport function signEd25519(opts: SignEd25519Opts): Uint8Array {\n return ed.sign(opts.message, opts.seed);\n}\n\n// Little-endian 32-byte scalar → bigint.\nfunction leBytesToBigInt(bytes: Uint8Array): bigint {\n let value = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n value = (value << 8n) | BigInt(bytes[i]!);\n }\n return value;\n}\n\n// Strict (non-cofactored) Ed25519 verification per RFC 8032 §5.1.7, matching\n// libsodium/PyNaCl `crypto_sign_verify_detached` and ed25519-dalek\n// `verify_strict`. The cofactor-less check rejects every small-order /\n// torsion-component edge case in the C2SP/CCTV corpus, which noble's\n// `{ zip215: false }` mode does NOT (it remains cofactored: it checks\n// `[8]([S]B - [k]A - R) == 0`, accepting torsion components).\n//\n// The verification equation is the unscaled `[S]B == R + [k]A`, rewritten as\n// `[S]B - [k]A - R == identity`. We reject S >= L (non-canonical scalar) and\n// any small-order A or R up front, so a torsion component can never be smuggled\n// through the cofactor multiplication the cofactored variant performs.\nexport function verifyEd25519(opts: VerifyEd25519Opts): boolean {\n const { signature, message, publicKey } = opts;\n if (signature.length !== 64 || publicKey.length !== 32) return false;\n\n // S = LE(sig[32..64]); reject if not a canonical scalar (S >= L).\n const S = leBytesToBigInt(signature.subarray(32, 64));\n if (S >= L) return false;\n\n // Decode A (public key) and R (sig[0..32]) with the canonical (non-zip215)\n // point encoding; a non-canonical encoding throws and rejects.\n let A: ed.Point;\n let R: ed.Point;\n try {\n A = ed.Point.fromBytes(publicKey);\n R = ed.Point.fromBytes(signature.subarray(0, 32));\n } catch {\n return false;\n }\n\n // Reject small-order (cofactor-torsion) A or R: this is exactly the strictness\n // that distinguishes verify_strict from the cofactored check.\n if (A.isSmallOrder() || R.isSmallOrder()) return false;\n\n // k = SHA-512(R || A || M) reduced mod L.\n const k =\n leBytesToBigInt(ed.hash(concatBytes(signature.subarray(0, 32), publicKey, message))) % L;\n\n // Accept iff [S]B - [k]A - R == identity. `multiplyUnsafe` returns the\n // identity for a 0 scalar, but guard explicitly to avoid relying on that.\n const sB = S === 0n ? ed.Point.ZERO : ed.Point.BASE.multiplyUnsafe(S);\n const kA = k === 0n ? ed.Point.ZERO : A.multiplyUnsafe(k);\n return sB.subtract(kA).subtract(R).is0();\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n let total = 0;\n for (const p of parts) total += p.length;\n const out = new Uint8Array(total);\n let offset = 0;\n for (const p of parts) {\n out.set(p, offset);\n offset += p.length;\n }\n return out;\n}\n\nexport function getPublicKeyEd25519(opts: GetPublicKeyEd25519Opts): Uint8Array {\n return ed.getPublicKey(opts.seed);\n}\n","// Isomorphic constant-time byte-equality. crypto-core is browser-safe by\n// design, so we cannot import `node:crypto.timingSafeEqual` — webpack rejects\n// the `node:` scheme in the browser bundle. A pure-JS XOR loop is constant-time\n// for equal-length inputs; length mismatch is a deliberate early-return (the\n// API surface itself leaks length, same as node's timingSafeEqual which throws).\nexport function compareCt(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n // Lengths are equal and `i` stays in-bounds, so both indexes are always\n // defined — no nullish guard is needed (and one would read as a guard for\n // an impossible case).\n for (let i = 0; i < a.length; i++) diff |= (a[i] as number) ^ (b[i] as number);\n return diff === 0;\n}\n","export type CoseVerifyErrorCode =\n | 'MALFORMED_SIG_COSE'\n | 'MALFORMED_SIG_COSE_SIGN1'\n | 'UNSUPPORTED_SIG_ALG'\n | 'KID_UNRESOLVED'\n | 'SIGNATURE_INVALID';\n\nexport class CoseVerifyError extends Error {\n readonly code: CoseVerifyErrorCode;\n\n constructor(code: CoseVerifyErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'CoseVerifyError';\n this.code = code;\n }\n}\n\nexport type CoseVerifyResult =\n | { ok: true; signerKey: Uint8Array; alg: number }\n | { ok: false; error: { code: CoseVerifyErrorCode; message: string } };\n","import {\n decodeCanonicalCbor,\n encodeCanonicalCbor,\n type CanonicalCborValue,\n} from '../cbor/canonical';\nimport { CanonicalCborError } from '../cbor/errors';\nimport { blake2b224 } from '../hash/blake2b-256';\nimport { signEd25519, verifyEd25519 } from '../sig/ed25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { CoseVerifyError, type CoseVerifyResult } from './errors';\n\nexport type CoseHeader = Map<number | string, unknown>;\n\n// Label 309 v1 domain separator embedded as a prefix on `Sig_structure[3]`\n// (`to_sign`). The separator is\n// NOT placed in `Sig_structure[2]` (`external_aad`) because CIP-30 `signData`\n// — the only realistic wallet-signing path on Cardano — explicitly forbids a\n// non-empty `external_aad`. Pinning the prefix into the payload preserves the\n// anti-replay property while keeping wallet-produced signatures byte-identical\n// to verifier-side recomputation.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX = 'cardano-poe-record-sig-v1' as const;\n// Composer path-2 wallet flow consumes the prefix bytes directly\n// to assemble `toSign = prefix || canonical_cbor(record_body)` BEFORE calling\n// `walletSignData` (the wallet's `signData()` receives this concatenation as\n// its `payload` argument verbatim per CIP-30). The bytes constant is exported\n// so a composer can build the input without re-encoding the prefix at every\n// call site.\nexport const CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES = new TextEncoder().encode(\n CARDANO_POE_SIG_DOMAIN_PREFIX,\n);\n\n// Fail-fast: the prefix length is byte-pinned at 25 UTF-8 bytes. A different\n// runtime encoding would silently break round-tripping\n// against the reference vectors.\nif (CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length !== 25) {\n throw new Error(\n `cardano-poe-record-sig-v1 prefix must encode to exactly 25 UTF-8 bytes, got ${CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length}`,\n );\n}\n\nconst EMPTY_BYTES = new Uint8Array(0);\n\nexport interface CoseSign1Decoded {\n readonly protectedHeader: CoseHeader;\n // preserved for Sig_structure reconstruction — never re-encode the decoded header map (RFC 9052 §4.4)\n readonly protectedBytes: Uint8Array;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport interface BuildSigStructureArgs {\n readonly context: 'Signature1';\n readonly bodyProtectedBytes: Uint8Array;\n readonly externalAad: Uint8Array;\n readonly payload: Uint8Array;\n}\n\n// Raw RFC 9052 §4.4 Sig_structure builder. General-purpose: callers control\n// `external_aad` and `payload` exactly. For Label 309 record signing use\n// `buildLabel309SigStructure` instead — it enforces the Label 309 record-signature invariants.\nexport function buildSigStructure(args: BuildSigStructureArgs): Uint8Array {\n return encodeCanonicalCbor([\n args.context,\n args.bodyProtectedBytes,\n args.externalAad,\n args.payload,\n ] as readonly CanonicalCborValue[]);\n}\n\nexport interface BuildLabel309SigStructureArgs {\n readonly bodyProtectedBytes: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed.\n readonly recordBodyCbor: Uint8Array;\n}\n\n// Label 309 v1 specialisation of `Sig_structure` (RFC 9052 §4.4 base structure):\n// to_sign = utf8(\"cardano-poe-record-sig-v1\") || canonical_cbor(record_body_minus_sigs)\n// Sig_structure = [ \"Signature1\", body_protected, h'' (empty), to_sign ]\n// Always forces `external_aad = h''` (empty bstr) — the CIP-30 wallet path\n// cannot carry a non-empty `external_aad`, so the domain separator lives in\n// `Sig_structure[3]` rather than `Sig_structure[2]`.\nexport function buildLabel309SigStructure(args: BuildLabel309SigStructureArgs): Uint8Array {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.recordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.recordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n return buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: args.bodyProtectedBytes,\n externalAad: EMPTY_BYTES,\n payload: toSign,\n });\n}\n\nexport interface EncodeCoseSign1Args {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n readonly payload: Uint8Array | null;\n readonly signature: Uint8Array;\n}\n\nexport function encodeCoseSign1(args: EncodeCoseSign1Args): Uint8Array {\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n return encodeCanonicalCbor([\n protectedBytes,\n args.unprotectedHeader as CanonicalCborValue,\n args.payload,\n args.signature,\n ] as readonly CanonicalCborValue[]);\n}\n\n// cbor2's decoder returns Map for integer-keyed maps but plain Object for empty\n// or string-keyed maps; normalise both representations to Map.\nfunction asCoseHeader(value: unknown): CoseHeader | null {\n if (value instanceof Map) return value as CoseHeader;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function decodeCoseSign1(bytes: Uint8Array): CoseSign1Decoded {\n let arr: unknown;\n try {\n arr = decodeCanonicalCbor(bytes);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'cose decode failed', { cause });\n }\n if (!Array.isArray(arr) || arr.length !== 4) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'expected 4-element array');\n }\n const [protectedBytesRaw, unprotectedRaw, payloadRaw, signatureRaw] = arr;\n if (!(protectedBytesRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected_bytes must be bytes');\n }\n const unprotectedHeader = asCoseHeader(unprotectedRaw);\n if (unprotectedHeader === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'unprotected header must be map');\n }\n if (payloadRaw !== null && !(payloadRaw instanceof Uint8Array)) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'payload must be bytes or null');\n }\n if (!(signatureRaw instanceof Uint8Array) || signatureRaw.length !== 64) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'signature must be 64 bytes');\n }\n let protectedHeader: CoseHeader;\n if (protectedBytesRaw.length === 0) {\n protectedHeader = new Map();\n } else {\n let decodedProtected: unknown;\n try {\n decodedProtected = decodeCanonicalCbor(protectedBytesRaw);\n } catch (cause) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header decode failed', { cause });\n }\n const ph = asCoseHeader(decodedProtected);\n if (ph === null) {\n throw new CoseVerifyError('MALFORMED_SIG_COSE', 'protected header must decode to map');\n }\n // Empty protected header MUST encode as the single byte 0x40 (zero-length bstr),\n // not 0x41 0xA0 (a 1-byte bstr containing an empty CBOR map). RFC 9052 §3 +\n // Label 309 canonical-CBOR mandate.\n if (ph.size === 0) {\n throw new CoseVerifyError(\n 'MALFORMED_SIG_COSE',\n 'empty protected header must encode as 0x40 (zero-length bstr), not as an empty map',\n );\n }\n protectedHeader = ph;\n }\n return {\n protectedHeader,\n protectedBytes: protectedBytesRaw,\n unprotectedHeader,\n payload: payloadRaw,\n signature: signatureRaw,\n };\n}\n\nexport type CoseSign1BuildErrorCode = 'SIGNER_NOT_PROVIDED' | 'SIGNER_AND_SEED_BOTH_PROVIDED';\n\nexport class CoseSign1BuildError extends Error {\n readonly code: CoseSign1BuildErrorCode;\n\n constructor(code: CoseSign1BuildErrorCode, message: string) {\n super(message);\n this.name = 'CoseSign1BuildError';\n this.code = code;\n }\n}\n\nexport interface CoseSign1Label309BuildArgs {\n readonly protectedHeader: CoseHeader;\n readonly unprotectedHeader: CoseHeader;\n // Canonical CBOR of the record body with `sigs` removed. The\n // builder prepends the 25-byte UTF-8 domain prefix `cardano-poe-record-sig-v1`\n // internally — callers MUST NOT pre-concatenate it.\n readonly recordBodyCbor: Uint8Array;\n // EITHER the raw 32-byte Ed25519 seed (used by KAT tests, Python parity, and\n // the off-host signing helper) OR an injected signer closure that signs the\n // assembled Sig_structure bytes (composer-side use — keeps the private key\n // inside the unlock-store closure so it never escapes scope).\n // Exactly one of the two MUST be provided; mutual exclusion enforced at\n // runtime via CoseSign1BuildError.\n readonly signerSecretKey?: Uint8Array;\n readonly signer?: (sigStructureBytes: Uint8Array) => Uint8Array;\n}\n\n// Label 309 v1 record-signature builder:\n// 1. compute `to_sign = utf8(\"cardano-poe-record-sig-v1\") || recordBodyCbor`\n// 2. Sig_structure = [ \"Signature1\", bodyProtected, h'', to_sign ]\n// 3. Ed25519-sign Sig_structure (via seed OR injected closure)\n// 4. emit COSE_Sign1 with payload = CBOR null (detached signature, mandatory)\nexport function coseSign1Label309Build(args: CoseSign1Label309BuildArgs): Uint8Array {\n if (args.signerSecretKey === undefined && args.signer === undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n 'coseSign1Label309Build requires either signerSecretKey or signer',\n );\n }\n if (args.signerSecretKey !== undefined && args.signer !== undefined) {\n throw new CoseSign1BuildError(\n 'SIGNER_AND_SEED_BOTH_PROVIDED',\n 'coseSign1Label309Build accepts signerSecretKey XOR signer (not both)',\n );\n }\n const protectedBytes =\n args.protectedHeader.size === 0\n ? EMPTY_BYTES\n : encodeCanonicalCbor(args.protectedHeader as CanonicalCborValue);\n const sigStructureBytes = buildLabel309SigStructure({\n bodyProtectedBytes: protectedBytes,\n recordBodyCbor: args.recordBodyCbor,\n });\n let signature: Uint8Array;\n if (args.signer !== undefined) {\n signature = args.signer(sigStructureBytes);\n if (!(signature instanceof Uint8Array) || signature.length !== 64) {\n throw new CoseSign1BuildError(\n 'SIGNER_NOT_PROVIDED',\n `injected signer must return a 64-byte Uint8Array; got ${signature instanceof Uint8Array ? `${signature.length}-byte Uint8Array` : typeof signature}`,\n );\n }\n } else {\n signature = signEd25519({ seed: args.signerSecretKey!, message: sigStructureBytes });\n }\n return encodeCoseSign1({\n protectedHeader: args.protectedHeader,\n unprotectedHeader: args.unprotectedHeader,\n payload: null,\n signature,\n });\n}\n\nexport interface CoseSign1Label309VerifyArgs {\n readonly message: Uint8Array;\n // Canonical CBOR of the record body with `sigs` removed (verifier-recomputed;\n // the 25-byte UTF-8 prefix is prepended internally — callers\n // MUST NOT pre-concatenate it).\n readonly detachedRecordBodyCbor: Uint8Array;\n // Optional out-of-band signer key (path-2 wallet path resolves the key from\n // `sigs[i].cose_key`). Path-1 records carry the 32-byte raw Ed25519 pubkey\n // in the protected header at label 4 (`kid`) and need no out-of-band hint.\n readonly expectedSignerKey?: Uint8Array;\n}\n\n// Label 309 v1 record-signature verifier:\n// - Decode COSE_Sign1\n// - Reject COSE_Sign1[2] != CBOR null (attached payload — including h'') as\n// MALFORMED_SIG_COSE_SIGN1\n// - Recompute to_sign = utf8(\"cardano-poe-record-sig-v1\") || detachedRecordBodyCbor\n// - Sig_structure = [ \"Signature1\", protectedBytes, h'', to_sign ]\n// - Strict Ed25519 verify (RFC 8032 §5.1.7 — `zip215: false` per ed25519.ts)\n//\n// The verifier does NOT accept an `externalAad` argument: Label 309 v1 pins\n// `external_aad = h''` and any deviation would either silently weaken the\n// domain separator or quietly accept malformed records. If a future CIP\n// revision re-enables external_aad, this helper takes a v-bump.\nexport function coseSign1Label309Verify(args: CoseSign1Label309VerifyArgs): CoseVerifyResult {\n let decoded: CoseSign1Decoded;\n try {\n decoded = decodeCoseSign1(args.message);\n } catch (e) {\n if (e instanceof CoseVerifyError) {\n return { ok: false, error: { code: e.code, message: 'errors.cose.malformed' } };\n }\n if (e instanceof CanonicalCborError) {\n return {\n ok: false,\n error: { code: 'MALFORMED_SIG_COSE', message: 'errors.cose.malformed_cbor' },\n };\n }\n throw e;\n }\n // Label 309 v1 mandate: COSE_Sign1[2] (payload field) MUST be CBOR `null` (0xF6).\n // Any non-null payload — including a zero-length byte string `h''` — MUST\n // be rejected as MALFORMED_SIG_COSE_SIGN1.\n if (decoded.payload !== null) {\n return {\n ok: false,\n error: {\n code: 'MALFORMED_SIG_COSE_SIGN1',\n message: 'errors.cose.attached_payload_forbidden',\n },\n };\n }\n const alg = decoded.protectedHeader.get(1);\n if (typeof alg !== 'number' || alg !== -8) {\n return {\n ok: false,\n error: { code: 'UNSUPPORTED_SIG_ALG', message: 'errors.cose.unsupported_alg' },\n };\n }\n const kidRaw = decoded.protectedHeader.get(4);\n let signerKey: Uint8Array | undefined;\n if (kidRaw instanceof Uint8Array && kidRaw.length === 32) {\n signerKey = kidRaw;\n } else if (args.expectedSignerKey instanceof Uint8Array && args.expectedSignerKey.length === 32) {\n signerKey = args.expectedSignerKey;\n }\n if (signerKey === undefined) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_unresolved' },\n };\n }\n // When both a protected-header kid AND an expectedSignerKey are provided,\n // require they agree (constant-time). A protected kid that disagrees with\n // the caller's out-of-band binding is a misuse, not a transient mismatch.\n if (\n kidRaw instanceof Uint8Array &&\n kidRaw.length === 32 &&\n args.expectedSignerKey instanceof Uint8Array &&\n args.expectedSignerKey.length === 32 &&\n !compareCt(kidRaw, args.expectedSignerKey)\n ) {\n return {\n ok: false,\n error: { code: 'KID_UNRESOLVED', message: 'errors.cose.kid_mismatch' },\n };\n }\n // CIP-8 `hashed = true` mode (the wallet-signed path-2 variant). The unprotected\n // header carries the literal text key `\"hashed\"` with boolean value `true`\n // (text-keyed CBOR maps decode to `Map<string, unknown>` via cbor2). When\n // set, both producer and verifier build `Sig_structure[3] = Blake2b-224(to_sign)`\n // (28-byte digest of the FULL `to_sign` payload including the 25-byte\n // domain prefix). When absent or false, the standard non-hashed path\n // applies unchanged.\n const hashedFlag = decoded.unprotectedHeader.get('hashed');\n let sigStructureBytes: Uint8Array;\n if (hashedFlag === true) {\n const toSign = new Uint8Array(\n CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length + args.detachedRecordBodyCbor.length,\n );\n toSign.set(CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES, 0);\n toSign.set(args.detachedRecordBodyCbor, CARDANO_POE_SIG_DOMAIN_PREFIX_BYTES.length);\n const hashedPayload = blake2b224(toSign);\n sigStructureBytes = buildSigStructure({\n context: 'Signature1',\n bodyProtectedBytes: decoded.protectedBytes,\n externalAad: EMPTY_BYTES,\n payload: hashedPayload,\n });\n } else {\n sigStructureBytes = buildLabel309SigStructure({\n bodyProtectedBytes: decoded.protectedBytes,\n recordBodyCbor: args.detachedRecordBodyCbor,\n });\n }\n const valid = verifyEd25519({\n publicKey: signerKey,\n message: sigStructureBytes,\n signature: decoded.signature,\n });\n if (!valid) {\n return {\n ok: false,\n error: { code: 'SIGNATURE_INVALID', message: 'errors.cose.signature_invalid' },\n };\n }\n return { ok: true, signerKey, alg };\n}\n","// CIP-30 / RFC 9052 §7 COSE_Key extraction for the Ed25519 sig path.\n//\n// CIP-30 wallets that don't put a 32-byte raw Ed25519 pubkey in the COSE_Sign1\n// protected header instead deliver the signer key as a separate `cbor<COSE_Key>`\n// blob, surfaced in the Label 309 record under the top-level `signer_keys` field.\n// This helper decodes one such blob and returns the underlying 32-byte Ed25519\n// pubkey, or `null` when the blob is malformed, uses an unexpected key type /\n// curve, or has the wrong `x` length.\n//\n// The expected COSE_Key shape (RFC 9053 §7.2 + RFC 8152 §13):\n// {\n// 1 (kty): 1 // OKP\n// 3 (alg): -8 // EdDSA — OPTIONAL but if present MUST be -8\n// -1 (crv): 6 // Ed25519\n// -2 (x): <32 byte raw public key>\n// }\n\nimport { decodeCanonicalCbor } from '../cbor/canonical';\n\nconst COSE_KEY_LABEL_KTY = 1;\nconst COSE_KEY_LABEL_ALG = 3;\nconst COSE_KEY_LABEL_CRV = -1;\nconst COSE_KEY_LABEL_X = -2;\n\nconst KTY_OKP = 1;\nconst ALG_EDDSA = -8;\nconst CRV_ED25519 = 6;\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\n\nfunction asMap(value: unknown): Map<unknown, unknown> | null {\n if (value instanceof Map) return value as Map<unknown, unknown>;\n if (value !== null && typeof value === 'object' && (value as object).constructor === Object) {\n return new Map(Object.entries(value as Record<string, unknown>));\n }\n return null;\n}\n\nexport function parseCoseKeyEd25519(blob: Uint8Array): Uint8Array | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(blob);\n } catch {\n return null;\n }\n const map = asMap(decoded);\n if (map === null) return null;\n\n const kty = map.get(COSE_KEY_LABEL_KTY);\n if (typeof kty !== 'number' || kty !== KTY_OKP) return null;\n\n const crv = map.get(COSE_KEY_LABEL_CRV);\n if (typeof crv !== 'number' || crv !== CRV_ED25519) return null;\n\n if (map.has(COSE_KEY_LABEL_ALG)) {\n const alg = map.get(COSE_KEY_LABEL_ALG);\n if (typeof alg !== 'number' || alg !== ALG_EDDSA) return null;\n }\n\n const x = map.get(COSE_KEY_LABEL_X);\n if (!(x instanceof Uint8Array) || x.length !== ED25519_PUBLIC_KEY_LENGTH) return null;\n\n return x;\n}\n","/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64<T extends ArrayBufferView>(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: <T extends ArrayBufferView>(arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg<VerOpts>): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg<SigOpts>): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<SigOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<VerOpts>\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg<Uint8Array>,\n msg?: TArg<Uint8Array>\n ) => {\n cipherText: TRet<Uint8Array>;\n sharedSecret: TRet<Uint8Array>;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder<F, T> {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder<T> extends Coder<T, Uint8Array> {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen<T> = BytesCoder<T> & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder<T> = T extends BytesCoder<infer U> ? U : never;\ntype SplitOut<T extends (number | BytesCoderLen<any>)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder<T[K]>;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder<T extends (number | BytesCoderLen<any>)[]>(\n label: string,\n ...lengths: T\n): TRet<BytesCoder<SplitOut<T>> & { bytesLen: number }> {\n const getLength = (c: TArg<number | BytesCoderLen<any>>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen<any>).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg<Uint8Array>) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut<T>;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder<T>(c: TArg<BytesCoderLen<T>>, vecLen: number): TRet<BytesCoderLen<T[]>> {\n const coder = c as BytesCoderLen<T>;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg<T[]>): TRet<Uint8Array> => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet<Uint8Array>;\n },\n decode: (a: TArg<Uint8Array>): TRet<T[]> => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet<T[]>;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet<Uint8Array> = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg<Uint8Array>, ctx: TArg<Uint8Array> = EMPTY): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg<Uint8Array>,\n ctx: TArg<Uint8Array> = EMPTY\n): TRet<Uint8Array> {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n","/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts<T extends TypedArray> = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons<T>;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons<T extends TypedArray> = (n: number) => T;\n\ntype Crystals<T extends TypedArray> = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder<number, number>) => BytesCoderLen<T>;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = <T extends TypedArray>(opts: CrystalOpts<T>): TRet<Crystals<T>> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder<number, number>): TRet<BytesCoderLen<T>> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg<T>): TRet<Uint8Array> => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet<Uint8Array>;\n },\n decode: (bytes: TArg<Uint8Array>): TRet<T> => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet<T>;\n },\n } as TRet<BytesCoderLen<T>>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet<T>,\n NTT: {\n encode: (r: TArg<T>): TRet<T> => NTT.encode(r as T) as TRet<T>,\n decode: (r: TArg<T>): TRet<T> => NTT.decode(r as T) as TRet<T>,\n },\n bitsCoder: bitsCoder as TRet<Crystals<T>>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet<XOF> =>\n (seed: TArg<Uint8Array>, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet<Uint8Array>;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet<XOF> = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet<XOF> = /* @__PURE__ */ createXofShake(shake256);\n","/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet<Uint16Array> => new Uint16Array(n) as TRet<Uint16Array>,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record<string, KEMParam> = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder<number, number> => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg<Poly>, b_: TArg<Poly>) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg<Poly>, g_: TArg<Poly>): TRet<Poly> {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet<Poly>;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType<ReturnType<XOF>['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash<any, { dkLen?: number }>;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg<XofGet>): TRet<Poly> {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet<Poly>;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg<Uint8Array>, eta: number): TRet<Poly> => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet<Poly>;\n};\n\nfunction sampleCBD(\n PRF_: TArg<PRF>,\n seed: TArg<Uint8Array>,\n nonce: number,\n eta: number\n): TRet<Poly> {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg<KyberOpts>) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg<Uint8Array>) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t ← A ◦ s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n seed: TArg<Uint8Array>\n ): TRet<Uint8Array> => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet<Uint8Array>;\n },\n decrypt: (cipherText: TArg<Uint8Array>, privateKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet<Uint8Array>;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg<KyberOpts>): TRet<KEM> {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg<Uint8Array> = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet<Uint8Array>,\n secretKey: secretKey as TRet<Uint8Array>,\n };\n },\n getPublicKey: (secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet<Uint8Array>;\n },\n encapsulate: (publicKey: TArg<Uint8Array>, msg: TArg<Uint8Array> = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)).\n // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet<Uint8Array>,\n sharedSecret: kr.subarray(0, 32) as TRet<Uint8Array>,\n };\n },\n decapsulate: (cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, “implicitly reject”\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet<Uint8Array>;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg<Uint8Array>, nonce: number): TRet<Uint8Array> {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet<Uint8Array>;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet<KEM> = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg<Uint16Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet<Uint16Array>);\n },\n ByteDecode_d: (B: TArg<Uint8Array>, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg<Uint16Array>) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg<Uint16Array>) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg<Uint16Array>, gHat: TArg<Uint16Array>) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg<Uint8Array>, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg<Uint8Array>) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n","/**\n * Post-Quantum Hybrid Cryptography\n *\n * The current implementation is flawed and likely redundant. We should offer\n * a small, generic API to compose hybrid schemes instead of reimplementing\n * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings.\n *\n * 1. Core Issues\n * - sign/verify: implemented as two separate operations with different keys.\n * - EC getSharedSecret: could be refactored into a proper KEM.\n * - Multiple calls: keys, signatures, and shared secrets could be\n * concatenated to reduce the number of API invocations.\n * - Reinvention: most libraries add strange domain separations and\n * encodings instead of simple byte concatenation.\n *\n * 2. API Goals\n * - Provide primitives to build hybrids generically.\n * - Avoid embedding SSH- or GPG-specific formats in the core API.\n *\n * 3. Edge Cases\n * • Variable-length signatures:\n * - DER-encoded (Weierstrass curves).\n * - Falcon (unpadded).\n * - Concatenation works only if length is fixed; otherwise a length\n * prefix is required (but that breaks compatibility).\n *\n * • getSharedSecret:\n * - Default: non-KEM (authenticated ECDH).\n * - KEM conversion: generate a random SK to remove implicit auth.\n *\n * 4. Common Pitfalls\n * - Seed expansion:\n * • Expanding a small seed into multiple keys reduces entropy.\n * • API should allow identity mapping (no expansion).\n *\n * - Skipping full point encoding:\n * • Some omit the compression byte (parity) for WebCrypto compatibility.\n * • Better: hash the raw secret; coordinate output is already non-uniform.\n * • Some curves (e.g., X448) produce secrets that must be re-hashed to match\n * symmetric-key lengths.\n *\n * - Combiner inconsistencies:\n * • Different domain separations and encodings across libraries.\n * • Should live at the application layer, since key lengths vary.\n *\n * 5. Protocol Examples\n * - SSH:\n * • Concatenate keys.\n * • Combiner: SHA-512.\n *\n * - GPG:\n * • Concatenate keys.\n * • Combiner:\n * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))\n *\n * - TLS:\n * • Transcript-based derivation (HKDF).\n *\n * 6. Relevant Specs & Implementations\n * - IETF Hybrid KEM drafts:\n * • draft-irtf-cfrg-hybrid-kems\n * • draft-connolly-cfrg-xwing-kem\n * • draft-westerbaan-tls-xyber768d00\n *\n * - PQC Libraries:\n * • superdilithium (cyph/pqcrypto.js) – low adoption.\n * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings.\n *\n * 7. Signatures\n * - Ed25519: fixed-size, easy to support.\n * - Variable-size: introduces custom format requirements; best left to\n * higher-level code.\n *\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { type EdDSA } from '@noble/curves/abstract/edwards.js';\nimport { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js';\nimport { type ECDSA } from '@noble/curves/abstract/weierstrass.js';\nimport { x25519 } from '@noble/curves/ed25519.js';\nimport { p256, p384 } from '@noble/curves/nist.js';\nimport {\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\n} from '@noble/curves/utils.js';\nimport { expand, extract } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { sha3_256, shake256 } from '@noble/hashes/sha3.js';\nimport { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js';\nimport { ml_kem1024, ml_kem768 } from './ml-kem.ts';\nimport {\n cleanBytes,\n copyBytes,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n type CryptoKeys,\n type KEM,\n type Signer,\n type TArg,\n type TRet,\n} from './utils.ts';\n\ntype CurveAll = ECDSA | EdDSA | MontgomeryECDH;\ntype CurveECDH = ECDSA | MontgomeryECDH;\ntype CurveSign = ECDSA | EdDSA;\n\n// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly\nfunction ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) {\n const lengths = curve.lengths;\n let keygen = curve.keygen;\n if (allowZeroKey) {\n // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are\n // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on\n // those curves would change key construction instead of just relaxing scalar range handling.\n if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))\n throw new Error('allowZeroKey requires a Weierstrass curve');\n // This legacy flag is really \"skip the +1 shift\" for vector matching, not \"accept scalar 0\".\n // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into\n // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.\n // This is ugly, but we need to return exact results here.\n const wCurve = curve as ECDSA;\n const Fn = wCurve.Point.Fn;\n // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.\n // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to\n // scalar 0 here and getPublicKey(secretKey) throws instead of \"allowing zero\".\n keygen = (seed: TArg<Uint8Array> = randomBytes(lengths.seed)) => {\n abytes(seed, lengths.seed!, 'seed');\n const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);\n // Reduce directly into [0, ORDER); scalar 0 still stays invalid.\n const secretKey = Fn.toBytes(Fn.create(seedScalar));\n return {\n secretKey: secretKey as TRet<Uint8Array>,\n publicKey: curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n };\n }\n return {\n lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },\n keygen: (seed?: TArg<Uint8Array>) =>\n keygen(seed) as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>,\n getPublicKey: (secretKey: TArg<Uint8Array>) =>\n curve.getPublicKey(secretKey) as TRet<Uint8Array>,\n };\n}\n\n/**\n * Wraps an ECDH-capable curve as a KEM.\n * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.\n * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the\n * 1-byte `0x02` / `0x03` prefix.\n * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.\n * @param curve - Curve with `getSharedSecret`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns KEM wrapper over the curve.\n * @throws If the curve does not expose `getSharedSecret`. {@link Error}\n * @example\n * Wrap an ECDH-capable curve as a generic KEM.\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * import { ecdhKem } from '@noble/post-quantum/hybrid.js';\n * const kem = ecdhKem(x25519);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet<KEM> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n encapsulate(\n publicKey: TArg<Uint8Array>,\n rand: TArg<Uint8Array> = randomBytes(curve.lengths.seed)\n ) {\n // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller\n // randomness first so cleanBytes() only wipes wrapper-owned material.\n const seed = copyBytes(rand);\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = this.keygen(seed).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and\n // derived ephemeral secret key even when encapsulation aborts before returning.\n cleanBytes(seed);\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const res = curve.getSharedSecret(secretKey, cipherText);\n return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Wraps a curve signer as a generic `Signer`.\n * Signatures stay in the wrapped curve's native byte encoding.\n * This wrapper does not normalize or document which per-curve signing options are meaningful.\n * @param curve - Curve with `sign` and `verify`.\n * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.\n * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar\n * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero\n * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.\n * Only supported on Weierstrass/ECDSA curves.\n * @returns Signer wrapper over the curve.\n * @throws If the curve does not expose `sign` and `verify`. {@link Error}\n * @example\n * Wrap a curve signer as a generic signer.\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { ecSigner } from '@noble/post-quantum/hybrid.js';\n * const signer = ecSigner(ed25519);\n * const sigLen = signer.lengths.signature;\n * ```\n */\nexport function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet<Signer> {\n const kg = ecKeygen(curve, allowZeroKey);\n if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one!\n return {\n lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },\n keygen: kg.keygen,\n getPublicKey: kg.getPublicKey,\n sign: (message, secretKey, opts = {}) => {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the Signer contract to message + key only.\n // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded\n // uniformly through combineSigners(), so callers that need them must use the curve directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'ecSigner does not support extraEntropy; use the underlying curve directly'\n );\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.sign(message, secretKey) as TRet<Uint8Array>;\n },\n /** Verify one wrapped curve signature.\n * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported\n * generic opts and lets wrapped-curve malformed-input errors escape unchanged.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error('ecSigner does not support context; use the underlying curve directly');\n return curve.verify(signature, message, publicKey);\n },\n };\n}\n\nfunction splitLengths<K extends string, T extends { lengths: Partial<Record<K, number>> }>(\n lst: T[],\n name: K\n) {\n // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.\n return splitCoder(\n name,\n ...lst.map((i) => {\n if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name);\n return i.lengths[name];\n })\n );\n}\n\n/** Seed-expansion callback used by the hybrid combiners. */\nexport type ExpandSeed = (seed: TArg<Uint8Array>, len: number) => TRet<Uint8Array>;\ntype XOF = CHashXOF<any, { dkLen: number }>;\n\n// It is XOF for most cases, but can be more complex!\n/**\n * Adapts an XOF into an `ExpandSeed` callback.\n * The returned callback interprets its second argument as an output byte length passed as `dkLen`.\n * @param xof - Extendable-output hash function.\n * @returns Seed expander using `dkLen`.\n * @example\n * Adapt an XOF into a seed expander.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * const expandSeed = expandSeedXof(shake256);\n * const seed = expandSeed(new Uint8Array([1]), 4);\n * ```\n */\nexport function expandSeedXof(xof: TArg<XOF>): TRet<ExpandSeed> {\n // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this\n // adapter only translates the requested byte length into the hash API's `dkLen` option.\n return ((seed: TArg<Uint8Array>, seedLen: number): TRet<Uint8Array> =>\n (xof as XOF)(seed, { dkLen: seedLen }) as TRet<Uint8Array>) as TRet<ExpandSeed>;\n}\n\n/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */\nexport type Combiner = (\n publicKeys: TArg<Uint8Array[]>,\n cipherTexts: TArg<Uint8Array[]>,\n sharedSecrets: TArg<Uint8Array[]>\n) => TRet<Uint8Array>;\n\nfunction combineKeys(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n expandSeed_: TArg<ExpandSeed>,\n ...ck_: TArg<CryptoKeys[]>\n) {\n const expandSeed = expandSeed_ as ExpandSeed;\n const ck = ck_ as CryptoKeys[];\n const seedCoder = splitLengths(ck, 'seed');\n const pkCoder = splitLengths(ck, 'publicKey');\n // Allows to use identity functions for combiner/expandSeed\n if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen;\n anumber(realSeedLen);\n function expandDecapsulationKey(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }> {\n abytes(seed, realSeedLen!);\n const expandedRaw = expandSeed(seed, seedCoder.bytesLen);\n // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so\n // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.\n const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;\n const expanded: Uint8Array[] = [];\n const keySecret: Uint8Array[] = [];\n const secretKey: Uint8Array[] = [];\n const publicKey: Uint8Array[] = [];\n let ok = false;\n try {\n // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child\n // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any\n // later cleanup wipes the shared backing bytes.\n for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part));\n for (let i = 0; i < ck.length; i++) {\n const keys = ck[i].keygen(expanded[i]);\n keySecret.push(keys.secretKey);\n secretKey.push(copyBytes(keys.secretKey));\n publicKey.push(keys.publicKey);\n }\n ok = true;\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array[];\n publicKey: Uint8Array[];\n }>;\n } finally {\n // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep\n // the exported copies on success, but wipe all temporary and partially built secret material\n // on either path so failures do not strand derived child seeds in memory.\n cleanBytes(expandedSeed, expanded, keySecret);\n if (!ok) cleanBytes(secretKey);\n }\n }\n return {\n info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n // Composite secret keys are root seeds, so public-key derivation reruns key expansion from\n // that seed instead of decoding a packed child-secret-key structure.\n return this.keygen(secretKey).publicKey as TRet<Uint8Array>;\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(realSeedLen)) {\n const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);\n try {\n const publicKey = pkCoder.encode(pk) as TRet<Uint8Array>;\n return { secretKey: seed as TRet<Uint8Array>, publicKey };\n } finally {\n cleanBytes(pk);\n // The exported secretKey is the caller/root seed itself; child secret keys are internal\n // expansion outputs that are cleaned whether encoding succeeds or throws.\n cleanBytes(secretKey);\n }\n },\n expandDecapsulationKey,\n realSeedLen,\n };\n}\n\n// This generic function that combines multiple KEMs into single one\n/**\n * Combines multiple KEMs into one composite KEM.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param realMsgLen - Shared-secret length returned by `combiner`.\n * @param expandSeed - Seed expander used to derive per-KEM seeds.\n * @param combiner - Combines the per-KEM outputs into one shared secret.\n * @param kems - KEM implementations to combine.\n * @returns Composite KEM.\n * @example\n * Combine multiple KEMs into one composite KEM.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const hybrid = combineKEMS(\n * 32,\n * 32,\n * expandSeedXof(shake256),\n * (_pk, _ct, sharedSecrets) => sharedSecrets[0],\n * ml_kem768,\n * ml_kem768\n * );\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineKEMS(\n realSeedLen: number | undefined, // how much bytes expandSeed expects\n realMsgLen: number | undefined, // how much bytes combiner returns\n expandSeed: TArg<ExpandSeed>,\n combiner: TArg<Combiner>,\n ...kems: TArg<KEM[]>\n): TRet<KEM> {\n const rawCombiner = combiner as Combiner;\n const rawKems = kems as KEM[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);\n const ctCoder = splitLengths(rawKems, 'cipherText');\n const pkCoder = splitLengths(rawKems, 'publicKey');\n const msgCoder = splitLengths(rawKems, 'msg');\n if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen;\n anumber(realMsgLen);\n const lengths = Object.freeze({\n ...keys.info.lengths,\n msg: realMsgLen,\n msgRand: msgCoder.bytesLen,\n cipherText: ctCoder.bytesLen,\n });\n return Object.freeze({\n lengths,\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n encapsulate(\n pk: TArg<Uint8Array>,\n randomness: TArg<Uint8Array> = randomBytes(msgCoder.bytesLen)\n ) {\n const pks = pkCoder.decode(pk);\n const rand = msgCoder.decode(randomness);\n const sharedSecret: Uint8Array[] = [];\n const cipherText: Uint8Array[] = [];\n try {\n for (let i = 0; i < rawKems.length; i++) {\n const enc = rawKems[i].encapsulate(pks[i], rand[i]);\n sharedSecret.push(enc.sharedSecret);\n cipherText.push(enc.cipherText);\n }\n return {\n // Detach the combiner result before cleanup: a caller-provided combiner may alias one of\n // the child sharedSecret buffers, and those child buffers are zeroized immediately below.\n sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),\n cipherText: ctCoder.encode(cipherText) as TRet<Uint8Array>,\n };\n } finally {\n // Child encapsulation or combiner failures can happen after some components already\n // returned secret material; zeroize whatever was produced before propagating the error.\n cleanBytes(sharedSecret, cipherText);\n }\n },\n decapsulate(ct: TArg<Uint8Array>, seed: TArg<Uint8Array>) {\n const cts = ctCoder.decode(ct);\n const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);\n const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));\n try {\n // Detach the decapsulation result before cleanup: the combiner may hand back one of the\n // child shared-secret buffers, and those temporary buffers are zeroized below.\n return copyBytes(rawCombiner(publicKey, cts, sharedSecret));\n } finally {\n // Decapsulation only needs the expanded child secret keys and child shared secrets for this\n // call; keep the caller/root seed intact, but wipe all derived material even on errors.\n cleanBytes(secretKey, sharedSecret);\n }\n },\n });\n}\n// There is no specs for this, but can be useful\n// realSeedLen: how much bytes expandSeed expects.\n/**\n * Combines multiple signers into one composite signer.\n * @param realSeedLen - Input seed length expected by `expandSeed`.\n * @param expandSeed - Seed expander used to derive per-signer seeds.\n * @param signers - Signers to combine.\n * @returns Composite signer.\n * @example\n * Combine multiple signers into one composite signer.\n * ```ts\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);\n * const { publicKey } = hybrid.keygen();\n * ```\n */\nexport function combineSigners(\n realSeedLen: number | undefined,\n expandSeed: TArg<ExpandSeed>,\n ...signers: TArg<Signer[]>\n): TRet<Signer> {\n const rawSigners = signers as Signer[];\n const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);\n const sigCoder = splitLengths(rawSigners, 'signature');\n const pkCoder = splitLengths(rawSigners, 'publicKey');\n return {\n lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },\n getPublicKey: keys.getPublicKey,\n keygen: keys.keygen,\n sign(message, seed, opts = {}) {\n validateSigOpts(opts);\n // This generic wrapper intentionally keeps the composite signer contract to message + root\n // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly\n // across mixed backends, so callers that need them must use the underlying signer directly.\n if (opts.extraEntropy !== undefined)\n throw new Error(\n 'combineSigners does not support extraEntropy; use the underlying signer directly'\n );\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const { secretKey } = keys.expandDecapsulationKey(seed);\n try {\n const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));\n return sigCoder.encode(sigs) as TRet<Uint8Array>;\n } finally {\n // Composite secret keys are root seeds; the per-signer child secret keys are temporary\n // expansion outputs and must not stay live after the combined signature is produced.\n cleanBytes(secretKey);\n }\n },\n /** Verify one combined signature.\n * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify\n * check fails. Throws on unsupported generic opts or malformed aggregate encodings.\n */\n verify: (signature, message, publicKey, opts = {}) => {\n validateVerOpts(opts);\n if (opts.context !== undefined)\n throw new Error(\n 'combineSigners does not support context; use the underlying signer directly'\n );\n const pks = pkCoder.decode(publicKey);\n const sigs = sigCoder.decode(signature);\n for (let i = 0; i < rawSigners.length; i++) {\n if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false;\n }\n return true;\n },\n };\n}\n\n/**\n * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte\n * SHA3-256 output, while custom `kdf` choices inherit their own digest size.\n * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full\n * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param kdf - Hash used for the final combiner.\n * @returns Hybrid KEM.\n * @example\n * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.\n * ```ts\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';\n * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function QSF(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n kdf: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(kdf);\n return combineKEMS(\n 32,\n kdf.outputLen,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n pqc,\n curveKEM\n );\n}\n\n/** QSF preset combining ML-KEM-768 with P-256. */\nexport const QSF_ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem768,\n ecdhKem(p256, true),\n shake256,\n sha3_256\n ))();\n/** QSF preset combining ML-KEM-1024 with P-384. */\nexport const QSF_ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n QSF(\n 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)',\n ml_kem1024,\n ecdhKem(p384, true),\n shake256,\n sha3_256\n ))();\n\n/**\n * Builds the \"KitchenSink\" hybrid KEM combiner.\n * The current builder always derives a fixed 32-byte output,\n * regardless of the hash's native output size.\n * Its HKDF extract step uses implicit zero salt with IKM\n * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.\n * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.\n * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.\n * @param label - Domain-separation label.\n * @param pqc - Post-quantum KEM.\n * @param curveKEM - Classical curve KEM.\n * @param xof - XOF used for seed expansion.\n * @param hash - Hash used for HKDF extraction and expansion.\n * @returns Hybrid KEM.\n * @example\n * Build the \"KitchenSink\" hybrid KEM combiner.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';\n * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);\n * const publicKeyLen = kem.lengths.publicKey;\n * ```\n */\nexport function createKitchenSink(\n label: string,\n pqc: TArg<KEM>,\n curveKEM: TArg<KEM>,\n xof: TArg<XOF>,\n hash: CHash\n): TRet<KEM> {\n ahash(xof);\n ahash(hash);\n return combineKEMS(\n 32,\n 32,\n expandSeedXof(xof),\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) => {\n const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label));\n const len = 32;\n const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage);\n const prk = extract(hash, ikm);\n const info = concatBytes(\n numberToBytesBE(len, 2),\n asciiToBytes('shared_secret'),\n asciiToBytes('')\n );\n const res = expand(hash, prk, info, len);\n cleanBytes(prk, info, ikm, preimage);\n return res;\n },\n pqc,\n curveKEM\n );\n}\n\n// Internal alias only: this stays exactly `ecdhKem(x25519)`\n// and inherits that wrapper's mutation/oracle behavior.\nconst x25519kem = /* @__PURE__ */ ecdhKem(x25519);\n/** KitchenSink preset combining ML-KEM-768 with X25519.\n * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.\n */\nexport const KitchenSink_ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n createKitchenSink(\n 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)',\n ml_kem768,\n x25519kem,\n shake256,\n sha256\n ))();\n\n// Always X25519 and ML-KEM - 768, no point to export\n/** X25519 + ML-KEM-768 hybrid preset.\n * Uses the hard-coded domain-separation label `\\\\.//^\\\\` and hashes only `ct1 || pk1`\n * from the X25519 side in addition to the two component shared secrets.\n */\nexport const ml_kem768_x25519: TRet<KEM> = /* @__PURE__ */ (() =>\n combineKEMS(\n 32,\n 32,\n expandSeedXof(shake256),\n // Awesome label, so much escaping hell in a single line.\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\\\.//^\\\\'))),\n ml_kem768,\n x25519kem\n ))();\n\n/**\n * Internal SEC 1-style KEM wrapper for NIST curves.\n * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:\n * current presets use `128` bytes for P-256 and `48` bytes for P-384.\n * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`\n * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash\n * both coordinates.\n */\nfunction nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet<KEM> {\n const Fn = curve.Point.Fn;\n if (!Fn) throw new Error('no Point.Fn');\n // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every\n // window is zero or out of range, fail instead of silently reducing modulo `n`.\n function rejectionSampling(seed: TArg<Uint8Array>): TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }> {\n let sk: bigint;\n for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) {\n if (end > seed.length) throw new Error('rejection sampling failed');\n sk = Fn.fromBytes(seed.subarray(start, end), true);\n if (Fn.isValidNot0(sk)) break;\n }\n const secretKey = Fn.toBytes(Fn.create(sk));\n const publicKey = curve.getPublicKey(secretKey, false);\n return { secretKey, publicKey } as TRet<{\n secretKey: Uint8Array;\n publicKey: Uint8Array;\n }>;\n }\n\n return {\n lengths: {\n secretKey: scalarLen,\n publicKey: elemLen,\n seed: nseed,\n msg: nseed,\n cipherText: elemLen,\n },\n keygen(seed: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(seed, nseed, 'seed');\n return rejectionSampling(seed);\n },\n getPublicKey(secretKey: TArg<Uint8Array>) {\n return curve.getPublicKey(secretKey, false) as TRet<Uint8Array>;\n },\n encapsulate(publicKey: TArg<Uint8Array>, rand: TArg<Uint8Array> = randomBytes(nseed)) {\n abytes(rand, nseed, 'rand');\n let ek: Uint8Array | undefined = undefined;\n try {\n ek = rejectionSampling(rand).secretKey;\n const sharedSecret = this.decapsulate(publicKey, ek);\n const cipherText = curve.getPublicKey(ek, false) as TRet<Uint8Array>;\n return { sharedSecret, cipherText };\n } finally {\n // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and\n // must be wiped even if peer-key validation or shared-secret derivation throws.\n if (ek) cleanBytes(ek);\n }\n },\n decapsulate(cipherText: TArg<Uint8Array>, secretKey: TArg<Uint8Array>) {\n const full = curve.getSharedSecret(secretKey, cipherText);\n return full.subarray(1) as TRet<Uint8Array>;\n },\n };\n}\n\n/**\n * Internal ML-KEM + NIST-curve combiner.\n * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the\n * 32-byte root seed and is not itself part of the exported secret-key length.\n * The domain-separation `label` is used only in the final `sha3_256` combiner, not in\n * `shake256(seed, { dkLen: 64 + nseed })`,\n * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.\n */\nfunction concreteHybridKem(\n label: string,\n mlkem: TArg<KEM>,\n curve: ECDSA,\n nseed: number\n): TRet<KEM> {\n const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;\n if (!scalarLen || !elemLen) throw new Error('wrong curve');\n const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed);\n const mlkemSeedLen = 64;\n const totalSeedLen = mlkemSeedLen + nseed;\n\n return combineKEMS(\n 32,\n 32,\n (seed: TArg<Uint8Array>): TRet<Uint8Array> => {\n abytes(seed, 32);\n const expanded = shake256(seed, { dkLen: totalSeedLen });\n const mlkemSeed = expanded.subarray(0, mlkemSeedLen);\n const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen);\n return concatBytes(mlkemSeed, curveSeed) as TRet<Uint8Array>;\n },\n (pk: TArg<Uint8Array[]>, ct: TArg<Uint8Array[]>, ss: TArg<Uint8Array[]>) =>\n sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))),\n mlkem,\n curveKem\n );\n}\n\n/** P-256 + ML-KEM-768 hybrid preset. */\nexport const ml_kem768_p256: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();\n\n/** P-384 + ML-KEM-1024 hybrid preset. */\nexport const ml_kem1024_p384: TRet<KEM> = /* @__PURE__ */ (() =>\n concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();\n\n// Legacy aliases\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const XWing: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_x25519`. */\nexport const MLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_x25519)();\n/** Legacy alias for `ml_kem768_p256`. */\nexport const MLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => ml_kem768_p256)();\n/** Legacy alias for `ml_kem1024_p384`. */\nexport const MLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => ml_kem1024_p384)();\n/** Legacy alias for `QSF_ml_kem768_p256`. */\nexport const QSFMLKEM768P256: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();\n/** Legacy alias for `QSF_ml_kem1024_p384`. */\nexport const QSFMLKEM1024P384: TRet<KEM> = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();\n/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */\nexport const KitchenSinkMLKEM768X25519: TRet<KEM> = /* @__PURE__ */ (() =>\n KitchenSink_ml_kem768_x25519)();\n","export class AeadVerificationError extends Error {\n readonly code: string = 'aead_verification_failed';\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'AeadVerificationError';\n }\n}\n","import { chacha20poly1305 } from '@noble/ciphers/chacha.js';\n\nimport { AeadVerificationError } from './errors';\n\nexport interface ChaCha20Poly1305EncryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly plaintext: Uint8Array;\n}\n\nexport interface ChaCha20Poly1305DecryptOpts {\n readonly key: Uint8Array;\n readonly nonce: Uint8Array;\n readonly aad: Uint8Array;\n readonly ciphertext: Uint8Array;\n}\n\nexport function chacha20Poly1305Encrypt(opts: ChaCha20Poly1305EncryptOpts): Uint8Array {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).encrypt(opts.plaintext);\n}\n\nexport function chacha20Poly1305Decrypt(opts: ChaCha20Poly1305DecryptOpts): Uint8Array {\n try {\n return chacha20poly1305(opts.key, opts.nonce, opts.aad).decrypt(opts.ciphertext);\n } catch (cause) {\n throw new AeadVerificationError('chacha20-poly1305 decrypt failed', { cause });\n }\n}\n","import { XWing } from '@noble/post-quantum/hybrid.js';\n\n// X-Wing (ML-KEM-768 + X25519) hybrid KEM per draft-connolly-cfrg-xwing-kem-10.\n// `XWing` is @noble/post-quantum's alias for `ml_kem768_x25519`. We expose it\n// through opts-object wrappers that pin the wire lengths and map noble's field\n// names onto the project's vocabulary.\n//\n// Unlike the bare X25519 KEM, there is no contributory-behaviour rejection to\n// translate: X-Wing combines the ML-KEM and X25519 shared secrets through a\n// SHA3-256 combiner that also binds the X25519 ephemeral and recipient public\n// keys, and ML-KEM's implicit rejection already yields a constant-work\n// pseudorandom secret on a malformed ciphertext. Decapsulation therefore never\n// throws on attacker-supplied wire data — a wrong shared secret is the correct,\n// indistinguishable failure mode, and callers MUST treat it as a non-match\n// rather than expecting an exception.\n\nexport const MLKEM768X25519_PUBLIC_KEY_LENGTH = 1216 as const;\nexport const MLKEM768X25519_ENC_LENGTH = 1120 as const;\nexport const MLKEM768X25519_SHARED_SECRET_LENGTH = 32 as const;\nexport const MLKEM768X25519_SEED_LENGTH = 32 as const;\nexport const MLKEM768X25519_ESEED_LENGTH = 64 as const;\n\nexport interface Mlkem768X25519KeyPair {\n // The 32-byte root seed IS the secret key: the ML-KEM coins and the X25519\n // scalar are re-expanded from it via SHAKE-256 at decapsulation. (Later X-Wing\n // drafts also define an optional expanded decapsulation-key form; we keep the\n // seed-only key, which the draft-10 Appendix C vectors still pin.)\n readonly secretSeed: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface Mlkem768X25519EncapsulateOpts {\n readonly publicKey: Uint8Array;\n // Optional 64-byte encapsulation randomness (msgRand). When supplied the\n // ciphertext and shared secret are fully deterministic; a 32-byte value is\n // rejected by noble, so we pin the length here too.\n readonly eseed?: Uint8Array;\n}\n\nexport interface Mlkem768X25519Encapsulation {\n readonly enc: Uint8Array;\n readonly ss: Uint8Array;\n}\n\nexport interface Mlkem768X25519DecapsulateOpts {\n readonly secretSeed: Uint8Array;\n readonly enc: Uint8Array;\n}\n\nexport function mlkem768x25519Keygen(seed: Uint8Array): Mlkem768X25519KeyPair {\n if (seed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${seed.length}`,\n );\n }\n const { secretKey, publicKey } = XWing.keygen(seed);\n return { secretSeed: secretKey, publicKey };\n}\n\nexport function mlkem768x25519Encapsulate(\n opts: Mlkem768X25519EncapsulateOpts,\n): Mlkem768X25519Encapsulation {\n if (opts.publicKey.length !== MLKEM768X25519_PUBLIC_KEY_LENGTH) {\n throw new Error(\n `mlkem768x25519 public key must be ${MLKEM768X25519_PUBLIC_KEY_LENGTH} bytes, got ${opts.publicKey.length}`,\n );\n }\n if (opts.eseed !== undefined && opts.eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 eseed must be ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${opts.eseed.length}`,\n );\n }\n const { cipherText, sharedSecret } = XWing.encapsulate(opts.publicKey, opts.eseed);\n return { enc: cipherText, ss: sharedSecret };\n}\n\nexport function mlkem768x25519Decapsulate(opts: Mlkem768X25519DecapsulateOpts): Uint8Array {\n // Pre-check both lengths before calling noble: decapsulation must perform a\n // constant amount of work for any caller-supplied ciphertext (implicit\n // rejection), which requires the inputs to be the exact expected sizes.\n if (opts.secretSeed.length !== MLKEM768X25519_SEED_LENGTH) {\n throw new Error(\n `mlkem768x25519 secret seed must be ${MLKEM768X25519_SEED_LENGTH} bytes, got ${opts.secretSeed.length}`,\n );\n }\n if (opts.enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(\n `mlkem768x25519 enc must be ${MLKEM768X25519_ENC_LENGTH} bytes, got ${opts.enc.length}`,\n );\n }\n // noble's signature is decapsulate(cipherText, secretKey) — ciphertext first.\n return XWing.decapsulate(opts.enc, opts.secretSeed);\n}\n","import { x25519 } from '@noble/curves/ed25519.js';\n\n// RFC 7748 §6.1 contributory-behaviour rejection: a small-order (low-order)\n// Montgomery `u` coordinate makes the X25519 shared secret all-zero, which\n// @noble/curves refuses with `Error: invalid private or public key received`.\n// We rethrow that as a *typed* error so callers can distinguish a structurally\n// valid-but-malicious peer public key (a property of attacker-supplied wire\n// data — trial-decrypt MUST treat the slot as a non-match, not crash) from\n// genuine caller misuse such as a wrong-length key (which @noble raises as a\n// RangeError and which we deliberately let propagate untouched).\nexport class X25519LowOrderPointError extends Error {\n readonly code = 'X25519_LOW_ORDER_POINT' as const;\n constructor(options?: { cause?: unknown }) {\n super('x25519 ECDH rejected: peer public key is a small-order point', options);\n this.name = 'X25519LowOrderPointError';\n }\n}\n\n// @noble/curves v2 signals a small-order/all-zero shared secret with this exact\n// message. Matching on it (rather than the broad Error class) keeps unrelated\n// failures — e.g. a future internal assertion — surfacing as themselves.\nconst NOBLE_LOW_ORDER_MESSAGE = 'invalid private or public key received';\n\nexport interface X25519KeyPair {\n readonly secretKey: Uint8Array;\n readonly publicKey: Uint8Array;\n}\n\nexport interface X25519PublicKeyOpts {\n readonly secretKey: Uint8Array;\n}\n\nexport interface X25519EcdhOpts {\n readonly secretKey: Uint8Array;\n readonly theirPublicKey: Uint8Array;\n}\n\nexport function x25519Keygen(): X25519KeyPair {\n return x25519.keygen();\n}\n\nexport function x25519PublicKey(opts: X25519PublicKeyOpts): Uint8Array {\n return x25519.getPublicKey(opts.secretKey);\n}\n\nexport function x25519Ecdh(opts: X25519EcdhOpts): Uint8Array {\n try {\n return x25519.getSharedSecret(opts.secretKey, opts.theirPublicKey);\n } catch (e) {\n // Translate ONLY the contributory-check rejection into our typed error.\n // A wrong-length key throws a RangeError from @noble's length assertion;\n // that is caller misuse, not malicious wire data, so it must propagate.\n if (e instanceof Error && e.message === NOBLE_LOW_ORDER_MESSAGE) {\n throw new X25519LowOrderPointError({ cause: e });\n }\n throw e;\n }\n}\n","import { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nexport interface HkdfSha256Opts {\n readonly ikm: Uint8Array;\n readonly salt: Uint8Array;\n readonly info: Uint8Array;\n readonly length: number;\n}\n\nexport function hkdfSha256(opts: HkdfSha256Opts): Uint8Array {\n return hkdf(sha256, opts.ikm, opts.salt, opts.info, opts.length);\n}\n","// Sealed-PoE construction error taxonomy (wire-shape + partitioning-oracle\n// pre-checks + caller-input validation).\n//\n// Codes whose concept exists in the wire error-code registry reuse the registry\n// string verbatim (UNSUPPORTED_ENVELOPE_SCHEME, UNSUPPORTED_AEAD_ALG,\n// ENC_PASSPHRASE_EMPTY, ...), so a consumer correlating construction failures\n// with validator/verifier reports sees one vocabulary. Conditions that exist\n// only at the construction API boundary (raw caller-input lengths, deterministic\n// test-override mismatches) carry construction-local names with no wire\n// counterpart.\n\nexport type EciesSealedPoeErrorCode =\n // Wire-registry codes (same concept, same string).\n | 'ENC_SLOTS_EMPTY'\n | 'ENC_SLOTS_MAC_INVALID_LENGTH'\n | 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL'\n | 'ENC_SLOTS_TOO_MANY'\n | 'ENC_ENVELOPE_TOO_LARGE'\n | 'ENC_REQUIRES_CONTENT_HASH'\n | 'ENC_PASSPHRASE_EMPTY'\n | 'ENC_PASSPHRASE_UNNORMALIZABLE'\n | 'ENC_PASSPHRASE_ALG_UNSUPPORTED'\n | 'ENC_PASSPHRASE_SALT_TOO_SHORT'\n | 'ENC_PASSPHRASE_SALT_TOO_LONG'\n | 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW'\n | 'KEM_EPK_LENGTH_MISMATCH'\n | 'KEM_CT_LENGTH_MISMATCH'\n | 'NONCE_LENGTH_MISMATCH'\n | 'WRAP_LENGTH_MISMATCH'\n | 'UNSUPPORTED_ENVELOPE_SCHEME'\n | 'UNSUPPORTED_AEAD_ALG'\n | 'UNSUPPORTED_KEM_ALG'\n | 'KDF_DERIVATION_FAILED'\n // Construction-local codes (no wire counterpart).\n | 'INVALID_CEK_LENGTH'\n | 'INVALID_EPHEMERAL_SECRET_LENGTH'\n | 'EPHEMERAL_SECRETS_COUNT_MISMATCH'\n | 'INVALID_RECIPIENT_KEY'\n | 'INVALID_PASSPHRASE_PARAMS'\n | 'PASSPHRASE_INPUT_TOO_LONG';\n\nexport class EciesSealedPoeError extends Error {\n readonly code: EciesSealedPoeErrorCode;\n\n constructor(code: EciesSealedPoeErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'EciesSealedPoeError';\n this.code = code;\n }\n}\n","// chacha20-poly1305-stream64k: the segmented STREAM content format for sealed\n// PoE (the age v1 STREAM layout).\n//\n// cipher : ChaCha20-Poly1305 (RFC 8439; 12-byte nonce, 16-byte tag)\n// chunk size : 65536 plaintext bytes per non-final chunk\n// chunk nonce : uint88_be(counter) || final_flag — counter starts at 0,\n// +1 per chunk; final_flag is 0x01 on the final chunk,\n// 0x00 otherwise\n// per-chunk AAD : empty (all context binds transitively through the\n// payload_key, whose CEK is committed by slots_mac or the\n// passphrase commitment header)\n// final chunk : 0..65536 plaintext bytes; zero-length only when the whole\n// plaintext is empty (an empty plaintext is exactly one\n// zero-length final chunk — a lone 16-byte tag)\n//\n// The counter nonces are safe because the payload_key is single-use (a fresh\n// CEK salted by the envelope-unique enc.nonce), so no two streams ever share a\n// (key, nonce) pair. The final flag domain-separates the last chunk, which is\n// what makes truncation detectable.\n//\n// Layout violations — a tag failure, a truncated stream, data after the final\n// chunk, a non-final chunk shorter than CHUNK_SIZE, a zero-length final chunk\n// on a non-empty stream — all surface as StreamTamperedError; the caller maps\n// it to the single generic decryption failure. Each chunk's tag is verified\n// before that chunk's plaintext is released, but the whole-plaintext hash\n// recheck is post-hoc: incremental consumers MUST treat released bytes as\n// tentative until it passes.\n\nimport { chacha20Poly1305Decrypt, chacha20Poly1305Encrypt } from '../aead/chacha20-poly1305';\nimport { AeadVerificationError } from '../aead/errors';\n\n// Pinned format constants. The 88-bit counter admits at most 2^88 chunks, far\n// above any realisable payload, so the format imposes no cryptographic payload\n// ceiling — the practical maximum is a deployment denial-of-service policy, not\n// a wire constant.\nexport const CHUNK_SIZE = 65536;\nexport const TAG_SIZE = 16;\n\nconst NONCE_LENGTH = 12;\nconst COUNTER_LENGTH = 11;\nconst SEALED_CHUNK_SIZE = CHUNK_SIZE + TAG_SIZE;\nconst PAYLOAD_KEY_LENGTH = 32;\nconst EMPTY_AAD: Uint8Array = new Uint8Array(0);\n\n// Authenticated-decryption failure of the stream: a chunk tag did not verify or\n// the chunk layout violates the format rules. Callers surface it as the single\n// generic decryption failure (the TAMPERED_CIPHERTEXT outcome).\nexport class StreamTamperedError extends Error {\n readonly code = 'TAMPERED_CIPHERTEXT' as const;\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'StreamTamperedError';\n }\n}\n\n// Shared chunk-nonce state machine: an 11-byte big-endian counter followed by\n// the final-flag byte. The counter increments once per chunk; using a chunk\n// machine after its final chunk is a caller error, never silently accepted.\nclass ChunkNonce {\n private readonly nonce = new Uint8Array(NONCE_LENGTH);\n private finished = false;\n\n next(final: boolean): Uint8Array {\n if (this.finished) {\n throw new Error('STREAM: no chunks may follow the final chunk');\n }\n if (final) {\n this.finished = true;\n this.nonce[COUNTER_LENGTH] = 0x01;\n }\n const out = this.nonce.slice();\n this.increment();\n return out;\n }\n\n get done(): boolean {\n return this.finished;\n }\n\n private increment(): void {\n for (let i = COUNTER_LENGTH - 1; i >= 0; i--) {\n const v = ((this.nonce[i] as number) + 1) & 0xff;\n this.nonce[i] = v;\n if (v !== 0) return;\n }\n // 2^88 chunks exhausted — unreachable for any realisable payload.\n throw new Error('STREAM: chunk counter overflow');\n }\n}\n\nfunction assertPayloadKey(payloadKey: Uint8Array): void {\n if (payloadKey.length !== PAYLOAD_KEY_LENGTH) {\n throw new Error(\n `STREAM: payloadKey MUST be exactly ${PAYLOAD_KEY_LENGTH} bytes, got ${payloadKey.length}`,\n );\n }\n}\n\n// Incremental sealer. Feed plaintext chunk by chunk: every non-final chunk MUST\n// be exactly CHUNK_SIZE bytes; the final chunk carries 0..CHUNK_SIZE bytes, and\n// a zero-length final chunk is admissible only as the sole chunk of an empty\n// plaintext.\nexport class StreamSealer {\n private readonly payloadKey: Uint8Array;\n private readonly nonce = new ChunkNonce();\n private chunkIndex = 0;\n\n constructor(payloadKey: Uint8Array) {\n assertPayloadKey(payloadKey);\n this.payloadKey = payloadKey;\n }\n\n sealChunk(plaintext: Uint8Array, final: boolean): Uint8Array {\n if (!final && plaintext.length !== CHUNK_SIZE) {\n throw new Error(\n `STREAM: non-final chunk MUST carry exactly ${CHUNK_SIZE} plaintext bytes, got ${plaintext.length}`,\n );\n }\n if (final && plaintext.length > CHUNK_SIZE) {\n throw new Error(\n `STREAM: final chunk MUST carry at most ${CHUNK_SIZE} plaintext bytes, got ${plaintext.length}`,\n );\n }\n if (final && plaintext.length === 0 && this.chunkIndex > 0) {\n throw new Error(\n 'STREAM: a zero-length final chunk is admissible only for an empty plaintext',\n );\n }\n const sealed = chacha20Poly1305Encrypt({\n key: this.payloadKey,\n nonce: this.nonce.next(final),\n aad: EMPTY_AAD,\n plaintext,\n });\n this.chunkIndex += 1;\n return sealed;\n }\n}\n\n// Incremental opener. Feed sealed chunks in order with the expected final flag;\n// each chunk's plaintext is released only after its tag verifies (and is still\n// tentative until the caller's whole-plaintext hash recheck passes). Chunk\n// boundaries are the caller's responsibility in incremental use; `streamOpen`\n// derives them from the blob length.\nexport class StreamOpener {\n private readonly payloadKey: Uint8Array;\n private readonly nonce = new ChunkNonce();\n private chunkIndex = 0;\n\n constructor(payloadKey: Uint8Array) {\n assertPayloadKey(payloadKey);\n this.payloadKey = payloadKey;\n }\n\n openChunk(sealedChunk: Uint8Array, final: boolean): Uint8Array {\n if (sealedChunk.length < TAG_SIZE) {\n throw new StreamTamperedError(\n `STREAM: sealed chunk shorter than the ${TAG_SIZE}-byte tag floor`,\n );\n }\n if (!final && sealedChunk.length !== SEALED_CHUNK_SIZE) {\n throw new StreamTamperedError(\n `STREAM: non-final sealed chunk MUST be exactly ${SEALED_CHUNK_SIZE} bytes, got ${sealedChunk.length}`,\n );\n }\n if (final && sealedChunk.length > SEALED_CHUNK_SIZE) {\n throw new StreamTamperedError(\n `STREAM: final sealed chunk MUST be at most ${SEALED_CHUNK_SIZE} bytes, got ${sealedChunk.length}`,\n );\n }\n if (final && sealedChunk.length === TAG_SIZE && this.chunkIndex > 0) {\n throw new StreamTamperedError('STREAM: zero-length final chunk on a non-empty stream');\n }\n let plaintext: Uint8Array;\n try {\n plaintext = chacha20Poly1305Decrypt({\n key: this.payloadKey,\n nonce: this.nonce.next(final),\n aad: EMPTY_AAD,\n ciphertext: sealedChunk,\n });\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n throw new StreamTamperedError(`STREAM: chunk ${this.chunkIndex} tag verification failed`, {\n cause: e,\n });\n }\n this.chunkIndex += 1;\n return plaintext;\n }\n}\n\n// Whole-buffer seal: split the plaintext into CHUNK_SIZE chunks (an empty\n// plaintext is exactly one zero-length final chunk) and concatenate the sealed\n// chunks.\nexport function streamSeal(args: { payloadKey: Uint8Array; plaintext: Uint8Array }): Uint8Array {\n const { plaintext } = args;\n const sealer = new StreamSealer(args.payloadKey);\n const chunkCount = Math.max(1, Math.ceil(plaintext.length / CHUNK_SIZE));\n const out = new Uint8Array(plaintext.length + chunkCount * TAG_SIZE);\n let offset = 0;\n for (let i = 0; i < chunkCount; i++) {\n const final = i === chunkCount - 1;\n const chunk = plaintext.subarray(\n i * CHUNK_SIZE,\n Math.min((i + 1) * CHUNK_SIZE, plaintext.length),\n );\n const sealed = sealer.sealChunk(chunk, final);\n out.set(sealed, offset);\n offset += sealed.length;\n }\n return out;\n}\n\n// Whole-buffer open. The chunk boundaries are fully determined by the blob\n// length: every non-final sealed chunk is exactly SEALED_CHUNK_SIZE bytes and\n// the final sealed chunk is whatever remains (TAG_SIZE..SEALED_CHUNK_SIZE). A\n// blob below the 16-byte floor, a tail that cannot form a well-formed final\n// chunk, or a zero-length final chunk on a non-empty stream is malformed before\n// any tag is checked. Truncation that removes the final chunk leaves a stream\n// whose last chunk was sealed with the 0x00 flag but is opened with the 0x01\n// flag nonce, so its tag fails — the final-flag byte is the truncation\n// detector.\nexport function streamOpen(args: { payloadKey: Uint8Array; ciphertext: Uint8Array }): Uint8Array {\n const { ciphertext } = args;\n const total = ciphertext.length;\n if (total < TAG_SIZE) {\n throw new StreamTamperedError(\n `STREAM: ciphertext shorter than the ${TAG_SIZE}-byte single-tag floor`,\n );\n }\n const rem = total % SEALED_CHUNK_SIZE;\n let nonFinalCount: number;\n let finalSealedLength: number;\n if (rem === 0) {\n nonFinalCount = total / SEALED_CHUNK_SIZE - 1;\n finalSealedLength = SEALED_CHUNK_SIZE;\n } else if (rem >= TAG_SIZE) {\n nonFinalCount = (total - rem) / SEALED_CHUNK_SIZE;\n finalSealedLength = rem;\n } else {\n throw new StreamTamperedError('STREAM: trailing bytes cannot form a well-formed final chunk');\n }\n if (nonFinalCount > 0 && finalSealedLength === TAG_SIZE) {\n throw new StreamTamperedError('STREAM: zero-length final chunk on a non-empty stream');\n }\n\n const opener = new StreamOpener(args.payloadKey);\n const out = new Uint8Array(nonFinalCount * CHUNK_SIZE + finalSealedLength - TAG_SIZE);\n let readOffset = 0;\n let writeOffset = 0;\n for (let i = 0; i < nonFinalCount; i++) {\n const plaintext = opener.openChunk(\n ciphertext.subarray(readOffset, readOffset + SEALED_CHUNK_SIZE),\n false,\n );\n out.set(plaintext, writeOffset);\n readOffset += SEALED_CHUNK_SIZE;\n writeOffset += CHUNK_SIZE;\n }\n const finalPlaintext = opener.openChunk(ciphertext.subarray(readOffset), true);\n out.set(finalPlaintext, writeOffset);\n return out;\n}\n","// Shared, byte-critical pieces of the sealed-PoE construction that the producer\n// (wrap / passphrase seal) and every verifier (unwrap, trial-decrypt,\n// passphrase open) MUST compute byte-for-byte identically:\n//\n// 1. The item-hashes digest `hashes_hash`.\n// 2. The slots transcript, its SHA-256 `slots_hash`, and the CEK-keyed\n// `slots_mac`.\n// 3. The passphrase transcript, its SHA-256 `pw_hash`, and the CEK-keyed\n// in-ciphertext `commitment`.\n// 4. The content `payload_key` derivations (both key paths).\n// 5. Both per-slot KEK HKDF salts (classical and hybrid).\n//\n// Keeping these in one module is the interop guarantee: a single divergence in\n// the canonical encoding silently yields a `slots_mac`, a commitment, or an\n// AEAD tag that another implementation cannot reproduce, with no typed error to\n// localise the fault. There is exactly one shared implementation, imported by\n// both sides.\n\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { encodeCanonicalCbor, type CanonicalCborValue } from '../cbor/canonical';\nimport { hkdfSha256 } from '../kdf/hkdf';\n\nimport { EciesSealedPoeError } from './errors';\nimport type { Mlkem768X25519Slot, SealedKem, X25519Slot } from './wrap';\n\n// Internal domain-separation labels. Each is exact ASCII with no terminator and\n// no length prefix; each is a fixed constant of the scheme, never serialised on\n// the wire and never registry-selectable. The byte-length invariants below keep\n// the SCREAMING_SNAKE constants in sync with the ASCII literals every conformant\n// verifier hashes against.\n\n// SHA-256 prefix for the item-hashes digest `hashes_hash`.\nexport const CARDANO_POE_ITEM_HASHES_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-item-hashes-v1',\n);\n// SHA-256 prefix for the slots-transcript hash `slots_hash`.\nexport const CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-transcript-v1',\n);\n// SHA-256 prefix for the passphrase-transcript hash `pw_hash`.\nexport const CARDANO_POE_PASSPHRASE_TRANSCRIPT_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-passphrase-transcript-v1',\n);\n// HKDF info for the slot-set MAC key.\nexport const CARDANO_POE_HKDF_INFO_SLOTS_MAC: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-slots-mac-v1',\n);\n// HKDF info for the passphrase commitment MAC key.\nexport const CARDANO_POE_HKDF_INFO_PASSPHRASE_MAC: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-passphrase-mac-v1',\n);\n// HKDF info for the slots-path content `payload_key`.\nexport const CARDANO_POE_HKDF_INFO_PAYLOAD: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-payload-v1',\n);\n// HKDF info for the passphrase-path content `payload_key`.\nexport const CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-payload-passphrase-v1',\n);\n// SHA-256 prefix for the classical (x25519) per-slot KEK HKDF salt.\nexport const CARDANO_POE_X25519_KEK_SALT_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-x25519-kek-salt-v1',\n);\n// SHA-256 prefix for the hybrid (X-Wing) per-slot KEK HKDF salt.\nexport const CARDANO_POE_XWING_KEK_SALT_PREFIX: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-xwing-kek-salt-v1',\n);\n\nif (CARDANO_POE_ITEM_HASHES_PREFIX.length !== 26) {\n throw new Error('CARDANO_POE_ITEM_HASHES_PREFIX byte-length invariant violated (expected 26)');\n}\nif (CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX.length !== 31) {\n throw new Error(\n 'CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX byte-length invariant violated (expected 31)',\n );\n}\nif (CARDANO_POE_PASSPHRASE_TRANSCRIPT_PREFIX.length !== 36) {\n throw new Error(\n 'CARDANO_POE_PASSPHRASE_TRANSCRIPT_PREFIX byte-length invariant violated (expected 36)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_SLOTS_MAC.length !== 24) {\n throw new Error('CARDANO_POE_HKDF_INFO_SLOTS_MAC byte-length invariant violated (expected 24)');\n}\nif (CARDANO_POE_HKDF_INFO_PASSPHRASE_MAC.length !== 29) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_PASSPHRASE_MAC byte-length invariant violated (expected 29)',\n );\n}\nif (CARDANO_POE_HKDF_INFO_PAYLOAD.length !== 22) {\n throw new Error('CARDANO_POE_HKDF_INFO_PAYLOAD byte-length invariant violated (expected 22)');\n}\nif (CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE byte-length invariant violated (expected 33)',\n );\n}\nif (CARDANO_POE_X25519_KEK_SALT_PREFIX.length !== 30) {\n throw new Error(\n 'CARDANO_POE_X25519_KEK_SALT_PREFIX byte-length invariant violated (expected 30)',\n );\n}\nif (CARDANO_POE_XWING_KEK_SALT_PREFIX.length !== 29) {\n throw new Error('CARDANO_POE_XWING_KEK_SALT_PREFIX byte-length invariant violated (expected 29)');\n}\n\n// Scheme-fixed constant pinning the passphrase normalization profile the CEK was\n// derived under. Fed into the passphrase transcript; never serialised on the\n// wire.\nexport const CARDANO_POE_PW_NORM_PROFILE = 'cardano-poe-pw-norm-v1' as const;\n\n// Verifier-side resource bounds a public parser MUST enforce BEFORE invoking any\n// KEM/AEAD primitive, so a malformed envelope cannot drive unbounded work. Both\n// are deployment-pinned reference constants (not wire fields); deployments MAY\n// tighten them. They sit far above the ~16 KiB Cardano transaction-metadata\n// ceiling that bounds honest records, so a conformant record never trips them.\n//\n// • MAX_SLOTS — the maximum slot count; an envelope with more slots is\n// rejected outright.\n// • MAX_DECODED_ENVELOPE_BYTES — a backstop on the decoded envelope's\n// aggregate byte size (nonce + slots_mac + every per-slot wire field),\n// bounding the work even before the slot-count cap would.\nexport const MAX_SLOTS = 1024;\nexport const MAX_DECODED_ENVELOPE_BYTES = 65536;\n\nconst EMPTY_SALT: Uint8Array = new Uint8Array(0);\n\n// The item's plaintext-hash claim: registered algorithm identifier → digest\n// bytes, exactly as carried in the record body. Both key paths bind this map\n// (via `hashes_hash`) into their commitment, so an envelope spliced onto an\n// item with a different hash claim is rejected before any ciphertext work.\nexport type ItemHashes = Readonly<Record<string, Uint8Array>>;\n\nfunction labelledSha256(prefix: Uint8Array, ...parts: ReadonlyArray<Uint8Array>): Uint8Array {\n let total = prefix.length;\n for (const p of parts) total += p.length;\n const message = new Uint8Array(total);\n message.set(prefix, 0);\n let offset = prefix.length;\n for (const p of parts) {\n message.set(p, offset);\n offset += p.length;\n }\n return sha256(message);\n}\n\n// SHA-256(\"cardano-poe-item-hashes-v1\" || canonicalEncode(item.hashes)).\n// The hashes map is encoded exactly as it appears in the record body\n// (registry-identifier keys → digest byte strings, canonical key order). An\n// `enc`-bearing item MUST declare at least one content hash — the ciphertext is\n// bound to the plaintext only through that digest — so an empty map is rejected\n// here, on both the producer and the verifier side.\nexport function itemHashesHash(hashes: ItemHashes): Uint8Array {\n if (Object.keys(hashes).length === 0) {\n throw new EciesSealedPoeError(\n 'ENC_REQUIRES_CONTENT_HASH',\n 'hashes MUST carry at least one content-hash entry',\n );\n }\n return labelledSha256(CARDANO_POE_ITEM_HASHES_PREFIX, encodeCanonicalCbor(hashes));\n}\n\n// SHA-256(\"cardano-poe-slots-transcript-v1\" || canonicalEncode(SLOTS_TRANSCRIPT)).\n// SLOTS_TRANSCRIPT is the closed seven-key map binding the cross-KEM header\n// fields (scheme, path, aead, kem, nonce) and the item's hash claim\n// (hashes_hash) to the on-wire slot set, so a relay that flips any header field\n// — or splices the envelope onto a different item — yields a different\n// `slots_hash` and the MAC fails. Computed ONCE per envelope and held constant\n// across the recipient trial-decrypt loop. The map keys are a SET — their wire\n// order is fixed by the canonical-encode sort, never hand-arranged here.\nexport function computeSlotsHash(args: {\n aead: string;\n kem: SealedKem;\n nonce: Uint8Array;\n slots: ReadonlyArray<X25519Slot | Mlkem768X25519Slot>;\n hashesHash: Uint8Array;\n}): Uint8Array {\n // The slot array is re-stated as explicit closed two-key maps (never the raw\n // caller objects), so an extra property on a caller's slot value can never\n // leak into the committed bytes.\n const slots: CanonicalCborValue =\n args.kem === 'x25519'\n ? (args.slots as ReadonlyArray<X25519Slot>).map((s) => ({ epk: s.epk, wrap: s.wrap }))\n : (args.slots as ReadonlyArray<Mlkem768X25519Slot>).map((s) => ({\n kem_ct: s.kem_ct,\n wrap: s.wrap,\n }));\n const transcript: CanonicalCborValue = {\n scheme: 1,\n path: 'slots',\n aead: args.aead,\n kem: args.kem,\n nonce: args.nonce,\n slots,\n hashes_hash: args.hashesHash,\n };\n return labelledSha256(CARDANO_POE_SLOTS_TRANSCRIPT_PREFIX, encodeCanonicalCbor(transcript));\n}\n\n// SHA-256(\"cardano-poe-passphrase-transcript-v1\" || canonicalEncode(PASSPHRASE_TRANSCRIPT)).\n// PASSPHRASE_TRANSCRIPT is the closed six-key map (with `passphrase` itself a\n// closed sub-map) binding the header fields, the Argon2id parameters, the\n// normalization profile, and the item's hash claim into the in-ciphertext\n// commitment. There is NO `kem` key on this path. The `normalization` value is\n// the scheme-fixed profile constant, pinned into the transcript and never\n// serialised on the wire.\nexport function computePassphraseHash(args: {\n aead: string;\n nonce: Uint8Array;\n hashesHash: Uint8Array;\n salt: Uint8Array;\n params: { m: number; t: number; p: number };\n}): Uint8Array {\n const transcript: CanonicalCborValue = {\n scheme: 1,\n path: 'passphrase',\n aead: args.aead,\n nonce: args.nonce,\n hashes_hash: args.hashesHash,\n passphrase: {\n alg: 'argon2id',\n salt: args.salt,\n params: { m: args.params.m, t: args.params.t, p: args.params.p },\n normalization: CARDANO_POE_PW_NORM_PROFILE,\n },\n };\n return labelledSha256(CARDANO_POE_PASSPHRASE_TRANSCRIPT_PREFIX, encodeCanonicalCbor(transcript));\n}\n\n// Slot-set MAC: HMAC-SHA-256 keyed by an HKDF leaf of the CEK over the 32-byte\n// `slots_hash`. Pre-hashing the transcript only changes the HMAC message from\n// the full transcript to its SHA-256, leaving the CEK-keyed commitment intact.\n// The fixed 32-byte HKDF key structurally excludes the HMAC over-block-length\n// key ambiguity.\nexport function computeSlotsMac(args: { cek: Uint8Array; slotsHash: Uint8Array }): Uint8Array {\n const macKey = hkdfSha256({\n ikm: args.cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_SLOTS_MAC,\n length: 32,\n });\n return hmac(sha256, macKey, args.slotsHash);\n}\n\n// Passphrase-path key commitment: HMAC-SHA-256 keyed by an HKDF leaf of the CEK\n// over the 32-byte `pw_hash`. Prepended inside the ciphertext blob (never an\n// on-chain field), so testing a passphrase guess requires possession of the\n// blob itself.\nexport function computePassphraseCommitment(args: {\n cek: Uint8Array;\n pwHash: Uint8Array;\n}): Uint8Array {\n const macKey = hkdfSha256({\n ikm: args.cek,\n salt: EMPTY_SALT,\n info: CARDANO_POE_HKDF_INFO_PASSPHRASE_MAC,\n length: 32,\n });\n return hmac(sha256, macKey, args.pwHash);\n}\n\n// Slots-path content key: HKDF-SHA-256(ikm=CEK, salt=enc.nonce, info=payload-v1).\n// The content is encrypted under this leaf of the CEK, never under the CEK\n// directly, so the wrap layer and the content layer never key the same primitive\n// on the same bytes. The envelope-unique nonce salt makes the key single-use,\n// which is what keeps the STREAM counter nonces collision-free.\nexport function slotsPayloadKey(args: { cek: Uint8Array; nonce: Uint8Array }): Uint8Array {\n return hkdfSha256({\n ikm: args.cek,\n salt: args.nonce,\n info: CARDANO_POE_HKDF_INFO_PAYLOAD,\n length: 32,\n });\n}\n\n// Passphrase-path content key: HKDF-SHA-256(ikm=CEK, salt=enc.nonce,\n// info=payload-passphrase-v1).\nexport function passphrasePayloadKey(args: { cek: Uint8Array; nonce: Uint8Array }): Uint8Array {\n return hkdfSha256({\n ikm: args.cek,\n salt: args.nonce,\n info: CARDANO_POE_HKDF_INFO_PAYLOAD_PASSPHRASE,\n length: 32,\n });\n}\n\n// Classical (x25519) per-slot KEK salt:\n// SHA-256(\"cardano-poe-x25519-kek-salt-v1\" || enc.nonce || epk || pub_R).\n// The slot's own ephemeral anchors the KEK to a slot-unique value, `pub_R`\n// binds it to the specific recipient (defeating confused-deputy relay of the\n// ephemeral against a different recipient), and the envelope-unique `enc.nonce`\n// anchors it to one envelope — a CSPRNG failure that repeats KEM randomness\n// across records degrades to mere linkability instead of reproducing a\n// (KEK, zero-nonce) wrap pair.\nexport function x25519KekSalt(args: {\n nonce: Uint8Array;\n epk: Uint8Array;\n pubR: Uint8Array;\n}): Uint8Array {\n return labelledSha256(CARDANO_POE_X25519_KEK_SALT_PREFIX, args.nonce, args.epk, args.pubR);\n}\n\n// Hybrid (mlkem768x25519) per-slot KEK salt:\n// SHA-256(\"cardano-poe-xwing-kek-salt-v1\" || enc.nonce || kem_ct || pub_R).\n// `kem_ct` is the slot's 1120-byte X-Wing ciphertext exactly as carried on the\n// wire and `pub_R` the 1216-byte X-Wing recipient public key — the same three\n// bindings as the classical salt, computed outside the KEM over the slot's own\n// wire bytes so it holds X-Wing as a black box.\nexport function xwingKekSalt(args: {\n nonce: Uint8Array;\n kemCt: Uint8Array;\n pubR: Uint8Array;\n}): Uint8Array {\n return labelledSha256(CARDANO_POE_XWING_KEK_SALT_PREFIX, args.nonce, args.kemCt, args.pubR);\n}\n","// Multi-recipient sealed-PoE wrap (age-style KEM-then-wrap slots + segmented\n// STREAM content). Wire-field names are fixed by the standard: scheme, aead,\n// kem, nonce, slots, slots_mac.\n//\n// Two KEM branches share one envelope shape, discriminated on the envelope-level\n// `kem` field:\n//\n// • kem: 'x25519' — classical age-style ECIES. Per-slot epk(32) + wrap(48).\n// • kem: 'mlkem768x25519' — X-Wing hybrid (ML-KEM-768 + X25519). Per-slot the\n// 1120-byte X-Wing ciphertext as a single byte\n// string (`kem_ct`) + wrap(48). No per-slot epk.\n//\n// The slot type is a discriminated union so every consumer is forced — at compile\n// time — to branch on the KEM before touching kem-specific fields.\n\nimport { randomBytes } from '@noble/ciphers/utils.js';\n\nimport { chacha20Poly1305Encrypt } from '../aead/chacha20-poly1305';\nimport {\n mlkem768x25519Encapsulate,\n MLKEM768X25519_ENC_LENGTH,\n MLKEM768X25519_ESEED_LENGTH,\n MLKEM768X25519_PUBLIC_KEY_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, x25519PublicKey } from '../kem/x25519';\nimport { hkdfSha256 } from '../kdf/hkdf';\n\nimport { EciesSealedPoeError } from './errors';\nimport { streamSeal } from './stream';\nimport {\n computeSlotsHash,\n computeSlotsMac,\n itemHashesHash,\n slotsPayloadKey,\n x25519KekSalt,\n xwingKekSalt,\n type ItemHashes,\n} from './transcript';\n\n// The envelope-level KEM discriminator.\nexport type SealedKem = 'x25519' | 'mlkem768x25519';\n\n// The sole registered content format under enc.scheme 1: ChaCha20-Poly1305 in\n// the 64 KiB segmented STREAM layout. Producers MUST emit this identifier\n// byte-exact.\nexport const SEALED_POE_AEAD = 'chacha20-poly1305-stream64k' as const;\n\n// HKDF info strings — fixed protocol labels for KEK derivation. Each doubles as\n// the per-slot wrap AEAD AAD (never empty AAD). Byte-length invariants enforce\n// that the SCREAMING_SNAKE constants stay in sync with the ASCII literals every\n// conformant verifier hashes against.\nexport const CARDANO_POE_HKDF_INFO_KEK: Uint8Array = new TextEncoder().encode('cardano-poe-kek-v1');\n// Hybrid (X-Wing) per-slot KEK label. Distinct from the classical label so a\n// KEK derived under one KEM can never collide with the other.\nexport const CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519: Uint8Array = new TextEncoder().encode(\n 'cardano-poe-kek-mlkem768x25519-v1',\n);\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst CEK_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\nif (CARDANO_POE_HKDF_INFO_KEK.length !== 18) {\n throw new Error('CARDANO_POE_HKDF_INFO_KEK byte-length invariant violated (expected 18)');\n}\nif (CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519.length !== 33) {\n throw new Error(\n 'CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519 byte-length invariant violated (expected 33)',\n );\n}\nif (ZERO_NONCE_12.length !== 12) {\n throw new Error('ZERO_NONCE_12 byte-length invariant violated (expected 12)');\n}\n\n// Classical per-slot wire shape: { epk: bstr(32), wrap: bstr(48) }.\nexport interface X25519Slot {\n readonly epk: Uint8Array;\n readonly wrap: Uint8Array;\n}\n\n// Hybrid per-slot wire shape: { kem_ct: bstr(1120), wrap: bstr(48) }. `kem_ct`\n// is the X-Wing ciphertext as a single byte string. There is NO per-slot epk\n// (the X25519 ephemeral is the trailing 32 bytes of kem_ct) and NO per-slot kem\n// field — the KEM identifier is hoisted to envelope scope (every slot shares it).\nexport interface Mlkem768X25519Slot {\n readonly kem_ct: Uint8Array;\n readonly wrap: Uint8Array;\n}\n\n// Sealed envelope wire shape (discriminated on `kem`).\nexport type SealedEnvelope =\n | {\n readonly scheme: 1;\n readonly aead: typeof SEALED_POE_AEAD;\n readonly kem: 'x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<X25519Slot>;\n readonly slots_mac: Uint8Array;\n }\n | {\n readonly scheme: 1;\n readonly aead: typeof SEALED_POE_AEAD;\n readonly kem: 'mlkem768x25519';\n readonly nonce: Uint8Array;\n readonly slots: ReadonlyArray<Mlkem768X25519Slot>;\n readonly slots_mac: Uint8Array;\n };\n\nexport interface SealedPoeOutput {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n}\n\nexport interface WrapArgs {\n readonly plaintext: Uint8Array;\n // The item's plaintext-hash claim (registered algorithm id → digest bytes).\n // Its labelled digest is bound into the slots transcript, so the on-chain\n // slots_mac match also confirms the envelope belongs to this hash claim.\n readonly hashes: ItemHashes;\n readonly recipientPublicKeys: ReadonlyArray<Uint8Array>;\n // KEM branch selector. Defaults to 'x25519' for the classical path. The\n // recipient public-key length is validated against the chosen KEM.\n readonly kem?: SealedKem;\n readonly cek?: Uint8Array;\n readonly nonce?: Uint8Array;\n // Deterministic X25519 ephemeral scalars — x25519 branch only.\n readonly ephemeralSecrets?: ReadonlyArray<Uint8Array>;\n // Deterministic X-Wing encapsulation randomness (64 bytes each) — hybrid\n // branch only. One per recipient, parallel to recipientPublicKeys.\n readonly eseeds?: ReadonlyArray<Uint8Array>;\n readonly skipShuffle?: boolean;\n}\n\n// Anonymity invariant: wire ordering MUST NOT encode \"primary\n// recipient first\". A CSPRNG-keyed Fisher-Yates shuffle uniformly permutes the\n// slot array so trial-decrypt order leaks no recipient identity. The\n// slot-set HMAC is computed AFTER this shuffle, binding the on-wire order.\n//\n// Draw an unbiased index in [0, m) from a CSPRNG uint32 via rejection sampling.\n// A plain `u32 % m` skews toward the low residues whenever `m` does not divide\n// 2^32 evenly: the values [0, 2^32 mod m) each occur one extra time. This\n// function exists purely to produce a UNIFORM permutation, so the bias — though\n// cryptographically negligible — is exactly the property we cannot tolerate.\n// We reject any draw landing in the final partial block [limit, 2^32) and\n// redraw, leaving only the residues that map uniformly onto [0, m).\n// Exported so the rejection-bound arithmetic can be asserted directly in tests\n// without relying on a flaky statistical-distribution check.\nexport function uniformIndexBelow(m: number): number {\n // 2^32 mod m, computed without overflowing the 32-bit space.\n const limit = 0x1_0000_0000 - (0x1_0000_0000 % m);\n const buf = new Uint32Array(1);\n let x: number;\n do {\n crypto.getRandomValues(buf);\n x = buf[0] as number;\n } while (x >= limit);\n return x % m;\n}\n\nfunction csprngShuffle<T>(arr: T[]): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = uniformIndexBelow(i + 1);\n const tmp = arr[i] as T;\n arr[i] = arr[j] as T;\n arr[j] = tmp;\n }\n}\n\n// Wrap the CEK for one classical recipient: age-style ECIES stanza with the\n// labelled-hash KEK salt binding nonce, epk, and pub_R.\nfunction wrapSlotX25519(args: {\n pubR: Uint8Array;\n privEph: Uint8Array | undefined;\n cek: Uint8Array;\n nonce: Uint8Array;\n slotIdx: number;\n}): X25519Slot {\n const privEph = args.privEph ?? randomBytes(X25519_SECRET_KEY_LENGTH);\n if (privEph.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `ephemeralSecrets[${args.slotIdx}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${privEph.length}`,\n );\n }\n const epk = x25519PublicKey({ secretKey: privEph });\n const shared = x25519Ecdh({ secretKey: privEph, theirPublicKey: args.pubR });\n const kek = hkdfSha256({\n ikm: shared,\n salt: x25519KekSalt({ nonce: args.nonce, epk, pubR: args.pubR }),\n info: CARDANO_POE_HKDF_INFO_KEK,\n length: 32,\n });\n // Per-slot wrap AAD MUST be the 18-byte ASCII literal of the KEK info\n // string (never empty AAD).\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { epk, wrap };\n}\n\n// Wrap the CEK for one hybrid recipient: X-Wing encapsulation → HKDF → AEAD.\n// The KEK info label doubles as the wrap AEAD AAD, mirroring the classical path.\nfunction wrapSlotMlkem768X25519(args: {\n pubR: Uint8Array;\n eseed: Uint8Array | undefined;\n cek: Uint8Array;\n nonce: Uint8Array;\n}): Mlkem768X25519Slot {\n const { enc, ss } = mlkem768x25519Encapsulate({\n publicKey: args.pubR,\n ...(args.eseed !== undefined ? { eseed: args.eseed } : {}),\n });\n if (enc.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new Error(`internal: enc.length=${enc.length}, expected ${MLKEM768X25519_ENC_LENGTH}`);\n }\n // The hybrid KEK salt binds the envelope nonce, the slot's own X-Wing\n // ciphertext, and the recipient public key, mirroring the classical salt: the\n // ciphertext anchors the KEK to a slot-unique value and `pub_R` binds it to\n // the specific recipient. It is computed outside the KEM, over the slot's wire\n // bytes, so it holds X-Wing as a black-box KEM.\n const kek = hkdfSha256({\n ikm: ss,\n salt: xwingKekSalt({ nonce: args.nonce, kemCt: enc, pubR: args.pubR }),\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n const wrap = chacha20Poly1305Encrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n plaintext: args.cek,\n });\n if (wrap.length !== WRAP_LENGTH) {\n throw new Error(`internal: wrap.length=${wrap.length}, expected ${WRAP_LENGTH}`);\n }\n return { kem_ct: enc, wrap };\n}\n\nexport function eciesSealedPoeWrap(args: WrapArgs): SealedPoeOutput {\n const { plaintext, recipientPublicKeys } = args;\n const kem: SealedKem = args.kem ?? 'x25519';\n const n = recipientPublicKeys.length;\n\n // The hash-claim digest is computed before any KEM/AEAD work: an item without\n // a content hash cannot be sealed (the ciphertext is bound to the plaintext\n // only through that digest).\n const hashesHash = itemHashesHash(args.hashes);\n\n // There is no fixed upper bound on slot count; the producer SDK polices the\n // per-record byte budget. Only the lower bound is enforced here.\n if (n < 1) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_EMPTY',\n `recipientPublicKeys.length=${n} must be >= 1`,\n );\n }\n\n const expectedPubLen =\n kem === 'x25519' ? X25519_PUBLIC_KEY_LENGTH : MLKEM768X25519_PUBLIC_KEY_LENGTH;\n for (let i = 0; i < n; i++) {\n const pub = recipientPublicKeys[i];\n if (pub === undefined || pub.length !== expectedPubLen) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `recipientPublicKeys[${i}] MUST be exactly ${expectedPubLen} bytes for kem='${kem}'`,\n );\n }\n }\n\n if (kem === 'x25519') {\n if (args.eseeds !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"eseeds is an X-Wing (mlkem768x25519) override and MUST NOT be supplied for kem='x25519'\",\n );\n }\n if (args.ephemeralSecrets !== undefined && args.ephemeralSecrets.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `ephemeralSecrets.length=${args.ephemeralSecrets.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n } else {\n if (args.ephemeralSecrets !== undefined) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n \"ephemeralSecrets is an X25519 override and MUST NOT be supplied for kem='mlkem768x25519'\",\n );\n }\n if (args.eseeds !== undefined) {\n if (args.eseeds.length !== n) {\n throw new EciesSealedPoeError(\n 'EPHEMERAL_SECRETS_COUNT_MISMATCH',\n `eseeds.length=${args.eseeds.length} must match recipientPublicKeys.length=${n}`,\n );\n }\n for (let i = 0; i < n; i++) {\n const eseed = args.eseeds[i]!;\n if (eseed.length !== MLKEM768X25519_ESEED_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_EPHEMERAL_SECRET_LENGTH',\n `eseeds[${i}] MUST be exactly ${MLKEM768X25519_ESEED_LENGTH} bytes, got ${eseed.length}`,\n );\n }\n }\n }\n }\n\n const cek = args.cek ?? randomBytes(CEK_LENGTH);\n const nonce = args.nonce ?? randomBytes(NONCE_LENGTH);\n if (cek.length !== CEK_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_CEK_LENGTH',\n `cek MUST be exactly ${CEK_LENGTH} bytes, got ${cek.length}`,\n );\n }\n if (nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${nonce.length}`,\n );\n }\n\n let envelope: SealedEnvelope;\n if (kem === 'x25519') {\n const slots: X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotX25519({\n pubR: recipientPublicKeys[i]!,\n privEph: args.ephemeralSecrets ? (args.ephemeralSecrets[i] as Uint8Array) : undefined,\n cek,\n nonce,\n slotIdx: i,\n }),\n );\n }\n // Anonymity invariant (see csprngShuffle comment). The transcript is built\n // AFTER the shuffle so the MAC binds the on-wire slot order.\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsHash = computeSlotsHash({\n aead: SEALED_POE_AEAD,\n kem: 'x25519',\n nonce,\n slots,\n hashesHash,\n });\n envelope = {\n scheme: 1,\n aead: SEALED_POE_AEAD,\n kem: 'x25519',\n nonce,\n slots,\n slots_mac: sizedSlotsMac(cek, slotsHash),\n };\n } else {\n const slots: Mlkem768X25519Slot[] = [];\n for (let i = 0; i < n; i++) {\n slots.push(\n wrapSlotMlkem768X25519({\n pubR: recipientPublicKeys[i]!,\n eseed: args.eseeds ? (args.eseeds[i] as Uint8Array) : undefined,\n cek,\n nonce,\n }),\n );\n }\n if (args.skipShuffle !== true) {\n csprngShuffle(slots);\n }\n const slotsHash = computeSlotsHash({\n aead: SEALED_POE_AEAD,\n kem: 'mlkem768x25519',\n nonce,\n slots,\n hashesHash,\n });\n envelope = {\n scheme: 1,\n aead: SEALED_POE_AEAD,\n kem: 'mlkem768x25519',\n nonce,\n slots,\n slots_mac: sizedSlotsMac(cek, slotsHash),\n };\n }\n\n // Content is encrypted under a derived `payload_key` (a separate HKDF leaf of\n // the CEK salted by the envelope-unique nonce), never under the CEK directly,\n // in the segmented STREAM format. There is no content AAD: the content binds\n // to the header transitively — payload_key derives from the CEK, and the CEK\n // is committed to the full header (including hashes_hash) by slots_mac.\n const ciphertext = streamSeal({\n payloadKey: slotsPayloadKey({ cek, nonce }),\n plaintext,\n });\n\n return { envelope, ciphertext };\n}\n\nfunction sizedSlotsMac(cek: Uint8Array, slotsHash: Uint8Array): Uint8Array {\n const slotsMac = computeSlotsMac({ cek, slotsHash });\n if (slotsMac.length !== SLOTS_MAC_LENGTH) {\n throw new Error(`internal: slots_mac.length=${slotsMac.length}, expected ${SLOTS_MAC_LENGTH}`);\n }\n return slotsMac;\n}\n","// Per-slot acceptance accumulator for the trial-decrypt loop.\n//\n// A slot is \"mine\" only when its KEM validity bit, its wrap-open, AND its\n// slot-set MAC check all hold (the folded per-slot `ok` bit). The accumulator\n// selects the FIRST accepted slot's CEK, keeps scanning every remaining slot\n// (the loop never breaks early within one private key's pass), and raises the\n// conflict bit when a later accepted slot recovers a CEK that differs from the\n// selected one — the multi-key commitment collision the construction fails\n// closed on. Slots that wrap-open under an attacker-chosen CEK but fail the\n// MAC are simply not accepted: they neither select a CEK nor raise a conflict,\n// so an honest slot later in the array still wins.\n//\n// The fold is branchless mask-based selection — no control flow keyed on which\n// slot matched:\n//\n// first = ok AND NOT found\n// cek_conflict = cek_conflict OR (ok AND found AND NOT ctEq(cand, selected))\n// selected_CEK = select(first, cand, selected) (byte masks 0x00/0xFF)\n// selected_idx = select(first, idx, selected_idx) (word masks 0/-1)\n// found = found OR ok\n//\n// Every update runs on every slot with the same operations; the state is a\n// fixed-size buffer plus 0|1 bits, never a data-dependent assignment guarded\n// by `if`. JavaScript offers no hardware constant-time guarantee — a JIT may\n// reintroduce data-dependent paths — so this is the best-effort discipline,\n// not a timing proof.\n//\n// Two accepted slots recovering DIFFERENT CEKs requires a collision in the\n// CEK-keyed commitment, so the conflict bit is not reachable through any\n// envelope the public API can build; it is exercised directly on this\n// accumulator. This module is internal to the trial-decrypt implementation and\n// is not part of the package surface.\n\nconst CEK_LENGTH = 32;\n\n// Mutable accumulator state. `foundBit` / `conflictBit` are 0|1 integers;\n// `selectedCek` is a fixed 32-byte buffer (all-zero until a slot is accepted);\n// `selectedSlotIdx` keeps the -1 sentinel until the first acceptance.\nexport interface SlotAcceptanceState {\n foundBit: number;\n conflictBit: number;\n readonly selectedCek: Uint8Array;\n selectedSlotIdx: number;\n}\n\nexport function newSlotAcceptanceState(): SlotAcceptanceState {\n return {\n foundBit: 0,\n conflictBit: 0,\n selectedCek: new Uint8Array(CEK_LENGTH),\n selectedSlotIdx: -1,\n };\n}\n\n// Fold one slot's outcome into the state. `ok` MUST be the slot's\n// `kem_ok AND open_ok AND mac_ok` acceptance as a 0|1 integer; `candidateCek`\n// MUST be exactly 32 bytes (the recovered CEK, or the caller's fixed dummy\n// when the wrap-open failed, so every slot folds the same-shaped input).\nexport function foldSlotAcceptance(\n state: SlotAcceptanceState,\n ok: number,\n candidateCek: Uint8Array,\n slotIdx: number,\n): void {\n if (candidateCek.length !== CEK_LENGTH) {\n // Structural programmer-error guard on a public quantity (the wrap length\n // is wire-validated upstream); never reachable from envelope data.\n throw new Error(\n `candidate CEK MUST be exactly ${CEK_LENGTH} bytes, got ${candidateCek.length}`,\n );\n }\n const okBit = ok & 1;\n const firstBit = okBit & (state.foundBit ^ 1);\n const firstByteMask = -firstBit & 0xff; // 0x00 or 0xFF\n const firstWordMask = -firstBit | 0; // 0 or -1 (all-ones int32)\n\n // Constant-time inequality of candidate vs selected as a 0|1 bit. Computed\n // unconditionally on every slot; its conflict contribution is masked off\n // unless this slot AND an earlier slot were both accepted.\n let diff = 0;\n for (let i = 0; i < CEK_LENGTH; i++) {\n diff |= (candidateCek[i] as number) ^ (state.selectedCek[i] as number);\n }\n const neqBit = ((diff | -diff) >>> 31) & 1;\n\n state.conflictBit |= okBit & state.foundBit & neqBit;\n for (let i = 0; i < CEK_LENGTH; i++) {\n state.selectedCek[i] =\n ((candidateCek[i] as number) & firstByteMask) |\n ((state.selectedCek[i] as number) & ~firstByteMask & 0xff);\n }\n state.selectedSlotIdx = (slotIdx & firstWordMask) | (state.selectedSlotIdx & ~firstWordMask);\n state.foundBit |= okBit;\n}\n\n// The pass outcome in consumer shape, read once after the whole slot loop.\nexport interface SlotAcceptanceOutcome {\n readonly found: boolean;\n readonly cekConflict: boolean;\n // The first accepted slot's CEK (null when nothing was accepted).\n readonly selectedCek: Uint8Array | null;\n // The first accepted slot's index (-1 when nothing was accepted).\n readonly selectedSlotIdx: number;\n}\n\nexport function finishSlotAcceptance(state: SlotAcceptanceState): SlotAcceptanceOutcome {\n const found = state.foundBit === 1;\n return {\n found,\n cekConflict: state.conflictBit === 1,\n selectedCek: found ? state.selectedCek : null,\n selectedSlotIdx: state.selectedSlotIdx,\n };\n}\n","// Multi-recipient sealed-PoE unwrap (age-style trial-decrypt with the slot-set\n// MAC folded into per-slot acceptance + partitioning-oracle length pre-checks).\n//\n// Three key forms (mutually exclusive — exactly one MUST be supplied):\n//\n// • Single-priv form: `recipientSecretKey: Uint8Array` — the standalone-verifier\n// path. Runs the trial-decrypt loop over `envelope.slots` once.\n//\n// • Multi-priv form: `recipientSecretKeys: ReadonlyArray<Uint8Array>` — for the\n// trial-decrypt scan of a rotated identity holding `[currentPriv, ...archivedPrivs]`.\n// Caller supplies the order; the iterator runs outer-loop = privkey ×\n// inner-loop = slot, short-circuiting on the first priv that accepts a\n// slot. The recommended caller order is `[currentPriv,\n// ...previousPrivsReversed]` (newest archive first).\n//\n// • Bundle form: `recipientKeyBundle` — both KEMs' secret lists; the dispatch\n// picks the right one from `envelope.kem`.\n//\n// The inner per-slot loop is constant-time across slots: every slot of a key's\n// pass is entered regardless of match position, and every slot pays the same\n// KEM + HKDF + wrap-open + MAC work, so an observer cannot infer which slot\n// index matched. The outer loop short-circuits on the first cross-priv match —\n// that channel leaks only the weak \"which key matched\" ordering signal,\n// intrinsic to multi-key trial-decrypt.\n//\n// Per-slot acceptance folds three bits: `ok = kem_ok AND open_ok AND mac_ok`.\n// The MAC fold is load-bearing: a malicious sender can craft a slot that\n// wrap-opens under a recipient's key with an attacker-chosen CEK, but that CEK\n// does not reproduce `slots_mac`, so the forged slot is skipped exactly like a\n// non-matching one and an honest slot later in the array still wins.\n//\n// The per-slot recovery body differs by KEM, but both take the same work\n// shape — KEK derivation, then a wrap-open attempt on EVERY slot:\n// • x25519: X25519 ECDH → HKDF → AEAD-unwrap; a low-order epk\n// (RFC 7748 §6.1 contributory-check rejection) sets\n// kem_ok=false, derives a dummy KEK instead, and STILL\n// attempts the wrap-open under it, so an invalid-ECDH slot\n// pays the identical per-slot cost and can never be\n// accepted (the kem bit is folded into acceptance).\n// • mlkem768x25519: X-Wing decapsulate → HKDF → AEAD-unwrap; NEVER throws on\n// attacker wire data (ML-KEM implicit rejection yields a\n// pseudorandom shared secret), so no try/catch around it.\n\nimport { chacha20Poly1305Decrypt } from '../aead/chacha20-poly1305';\nimport { AeadVerificationError } from '../aead/errors';\nimport { hkdfSha256 } from '../kdf/hkdf';\nimport {\n mlkem768x25519Decapsulate,\n mlkem768x25519Keygen,\n MLKEM768X25519_ENC_LENGTH,\n} from '../kem/mlkem768x25519';\nimport { x25519Ecdh, X25519LowOrderPointError, x25519PublicKey } from '../kem/x25519';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport {\n finishSlotAcceptance,\n foldSlotAcceptance,\n newSlotAcceptanceState,\n} from './slot-acceptance';\nimport { streamOpen, StreamTamperedError } from './stream';\nimport {\n computeSlotsHash,\n computeSlotsMac,\n itemHashesHash,\n MAX_DECODED_ENVELOPE_BYTES,\n MAX_SLOTS,\n slotsPayloadKey,\n x25519KekSalt,\n xwingKekSalt,\n type ItemHashes,\n} from './transcript';\nimport {\n CARDANO_POE_HKDF_INFO_KEK,\n CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n SEALED_POE_AEAD,\n type Mlkem768X25519Slot,\n type SealedEnvelope,\n type X25519Slot,\n} from './wrap';\n\n// Typed decryption outcomes — internal diagnostics for a trusted local caller.\n// An untrusted external caller MUST receive one indistinguishable generic\n// failure regardless of which of these fired.\nexport type UnwrapFailureReason = 'WRONG_RECIPIENT_KEY' | 'TAMPERED_HEADER' | 'TAMPERED_CIPHERTEXT';\n\nexport type UnwrapResult =\n | { readonly matched: true; readonly plaintext: Uint8Array }\n | { readonly matched: false; readonly reason: UnwrapFailureReason };\n\n// Unified recipient key bundle. Callers hold BOTH the X25519\n// private-key chain (current + archived, for classical and rotation history)\n// AND the X-Wing secret seed(s) (for the hybrid KEM), without knowing which a\n// given record was sealed under. They pass the whole bundle; the unwrap /\n// trial-decrypt dispatch selects the correct secret list from `envelope.kem`:\n//\n// • kem === 'x25519' → bundle.x25519PrivateKeys\n// • kem === 'mlkem768x25519' → bundle.mlkem768x25519SecretSeeds\n//\n// Both lists are ordered newest-first (caller's responsibility — the outer\n// trial-decrypt loop scans them in order). A list MAY be empty when the\n// recipient holds no key for that KEM (e.g. archived-only X25519 identities\n// predate the hybrid KEM, so their hybrid seed list is empty); a bundle whose\n// selected list is empty unwraps to a clean no-match without touching any KEM\n// primitive.\nexport interface RecipientKeyBundle {\n readonly x25519PrivateKeys: ReadonlyArray<Uint8Array>;\n readonly mlkem768x25519SecretSeeds: ReadonlyArray<Uint8Array>;\n}\n\n// Select the secret-key list a bundle contributes for the given envelope KEM.\n// The single dispatch seam — unwrap and trial-decrypt both route through here so\n// the per-KEM selection lives in exactly one place.\nfunction selectBundleSecrets(\n envelope: SealedEnvelope,\n bundle: RecipientKeyBundle,\n): ReadonlyArray<Uint8Array> {\n return envelope.kem === 'x25519' ? bundle.x25519PrivateKeys : bundle.mlkem768x25519SecretSeeds;\n}\n\ninterface UnwrapArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly ciphertext: Uint8Array;\n // The item's plaintext-hash claim, as carried in the record body. Bound into\n // the slots transcript: an envelope spliced onto an item with a different\n // hashes map fails the per-slot MAC, before any content work.\n readonly hashes: ItemHashes;\n // Test-only instrumentation for the constant-time-across-slots invariant.\n // The unwrap fn bumps `count` once per inner-loop iteration entered. In the\n // multi-priv path, `count` is reset at the start of each outer iteration and\n // — when `perPrivCounts` is provided — the final per-priv inner count is\n // appended after that priv's inner loop completes. Production callers never\n // pass this.\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n // Test-only multi-priv outer-loop iteration counter. Bumped to `k + 1` at\n // the start of each outer-loop iteration. Production callers never pass this.\n readonly _privsAttemptedOut?: { count: number };\n}\n\nexport interface UnwrapArgsSinglePriv extends UnwrapArgsCommon {\n readonly recipientSecretKey: Uint8Array;\n}\n\nexport interface UnwrapArgsMultiPriv extends UnwrapArgsCommon {\n readonly recipientSecretKeys: ReadonlyArray<Uint8Array>;\n}\n\n// Bundle form of the multi-priv path: the caller passes both KEMs' secret\n// lists and the dispatch picks the right one from `envelope.kem`. This is the\n// surface every read-path consumer (inbox decrypt, CLI decrypt, standalone\n// recipient verifier) should use — they hold the whole identity key bundle and\n// must NOT pre-select a list or rebuild slots themselves.\nexport interface UnwrapArgsBundle extends UnwrapArgsCommon {\n readonly recipientKeyBundle: RecipientKeyBundle;\n}\n\nexport type UnwrapArgs = UnwrapArgsSinglePriv | UnwrapArgsMultiPriv | UnwrapArgsBundle;\n\n// Trial-decrypt-only sibling of eciesSealedPoeUnwrap. Runs the per-slot\n// acceptance (KEM + wrap-open + slots_mac) but NEVER opens the content stream\n// (which requires the off-chain ciphertext blob, not available at trial-decrypt\n// time). Used by an inbox-scan agent to discover readable records before\n// fetching their ciphertext.\ninterface TrialDecryptOnlyArgsCommon {\n readonly envelope: SealedEnvelope;\n readonly hashes: ItemHashes;\n readonly _slotsAttemptedOut?: { count: number; perPrivCounts?: number[] };\n readonly _privsAttemptedOut?: { count: number };\n}\n\n// Exactly one of `recipientSecretKeys` (flat, KEM-pre-selected) or\n// `recipientKeyBundle` (whole bundle, KEM dispatched from `envelope.kem`).\n// Inbox-scan consumers pass the bundle; the low-level / parity tests pass the\n// flat list directly.\nexport type TrialDecryptOnlyArgs = TrialDecryptOnlyArgsCommon &\n (\n | { readonly recipientSecretKeys: ReadonlyArray<Uint8Array> }\n | { readonly recipientKeyBundle: RecipientKeyBundle }\n );\n\n// Binary by design: with the MAC folded into per-slot acceptance there is no\n// observable middle state — a slot either fully matches (KEM + wrap + MAC) or\n// it does not. A CEK conflict among accepted slots fails closed to no_match.\nexport type TrialDecryptOnlyResult =\n | { readonly kind: 'match'; readonly slotIdx: number; readonly cek: Uint8Array }\n | { readonly kind: 'no_match' };\n\nconst ZERO_NONCE_12: Uint8Array = new Uint8Array(12);\nconst CEK_LENGTH = 32 as const;\nconst X25519_SECRET_KEY_LENGTH = 32 as const;\nconst X25519_PUBLIC_KEY_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst WRAP_LENGTH = 48 as const;\nconst SLOTS_MAC_LENGTH = 32 as const;\n\n// Stable string key for a byte string, used only for the per-slot KEM-material\n// duplicate check (a structural pre-trial gate, not a constant-time comparison).\nfunction bytesKey(bytes: Uint8Array): string {\n let s = '';\n for (let i = 0; i < bytes.length; i++) {\n s += String.fromCharCode(bytes[i]!);\n }\n return s;\n}\n\n// Partitioning-oracle defence: every wire\n// length MUST be validated before any KEM/AEAD primitive is invoked, so malformed\n// records cannot probe per-slot failure ordering. Shared between\n// `eciesSealedPoeUnwrap` (single- and multi-priv) and `eciesSealedPoeTrialDecrypt`\n// to guarantee byte-identical pre-trial behaviour and to keep the dispatch\n// invariant in one place.\nfunction assertEnvelopeStructure(\n envelope: SealedEnvelope,\n multiPrivKeys?: ReadonlyArray<Uint8Array>,\n singlePrivKey?: Uint8Array,\n): void {\n if (envelope.scheme !== 1) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n `envelope.scheme=${String(envelope.scheme)} unsupported (expected 1)`,\n );\n }\n if (envelope.aead !== SEALED_POE_AEAD) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_AEAD_ALG',\n `envelope.aead=${String(envelope.aead)} unsupported (expected '${SEALED_POE_AEAD}')`,\n );\n }\n if (envelope.kem !== 'x25519' && envelope.kem !== 'mlkem768x25519') {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_KEM_ALG',\n `envelope.kem=${String((envelope as { kem: string }).kem)} unsupported (expected 'x25519' or 'mlkem768x25519')`,\n );\n }\n\n // Envelope-level length pre-checks in this exact order.\n const n = envelope.slots.length;\n if (n < 1) {\n throw new EciesSealedPoeError('ENC_SLOTS_EMPTY', `envelope.slots.length=${n} must be >= 1`);\n }\n // Resource bound: reject an envelope with more than MAX_SLOTS slots before any\n // KEM/AEAD primitive runs, so a malformed record cannot drive unbounded\n // per-slot work. Checked before the per-slot length loop below.\n if (n > MAX_SLOTS) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_TOO_MANY',\n `envelope.slots.length=${n} exceeds MAX_SLOTS=${MAX_SLOTS}`,\n );\n }\n if (envelope.nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `envelope.nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${envelope.nonce.length}`,\n );\n }\n if (envelope.slots_mac.length !== SLOTS_MAC_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_MAC_INVALID_LENGTH',\n `envelope.slots_mac MUST be exactly ${SLOTS_MAC_LENGTH} bytes, got ${envelope.slots_mac.length}`,\n );\n }\n\n // Per-slot length pre-checks — KEM-driven. ALL slots are validated here,\n // before any decapsulation, so the trial-decrypt loop never observes a\n // malformed slot (partitioning-oracle-safe ordering).\n //\n // Per-slot KEK uniqueness is also enforced here. The zero-nonce per-slot wrap\n // is safe only because each slot draws fresh KEM randomness, so its KEK is\n // unique; two slots sharing the same KEM material derive the same KEK and\n // repeat a (KEK, zero-nonce) pair. The KEM material that fixes the KEK is the\n // `epk` (x25519) or the `kem_ct` (hybrid) — both bound into the KEK salt — so\n // a repeat of either across slots is rejected outright.\n const seenKemMaterial = new Set<string>();\n if (envelope.kem === 'x25519') {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n if (slot.epk.length !== X25519_PUBLIC_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_EPK_LENGTH_MISMATCH',\n `envelope.slots[${i}].epk MUST be exactly ${X25519_PUBLIC_KEY_LENGTH} bytes, got ${slot.epk.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n const key = bytesKey(slot.epk);\n if (seenKemMaterial.has(key)) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL',\n `envelope.slots[${i}].epk duplicates an earlier slot — per-slot KEK uniqueness is violated`,\n );\n }\n seenKemMaterial.add(key);\n }\n } else {\n for (let i = 0; i < n; i++) {\n const slot = envelope.slots[i]!;\n if (slot.kem_ct.length !== MLKEM768X25519_ENC_LENGTH) {\n throw new EciesSealedPoeError(\n 'KEM_CT_LENGTH_MISMATCH',\n `envelope.slots[${i}].kem_ct MUST be exactly ${MLKEM768X25519_ENC_LENGTH} bytes, got ${slot.kem_ct.length}`,\n );\n }\n if (slot.wrap.length !== WRAP_LENGTH) {\n throw new EciesSealedPoeError(\n 'WRAP_LENGTH_MISMATCH',\n `envelope.slots[${i}].wrap MUST be exactly ${WRAP_LENGTH} bytes, got ${slot.wrap.length}`,\n );\n }\n const key = bytesKey(slot.kem_ct);\n if (seenKemMaterial.has(key)) {\n throw new EciesSealedPoeError(\n 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL',\n `envelope.slots[${i}].kem_ct duplicates an earlier slot — per-slot KEK uniqueness is violated`,\n );\n }\n seenKemMaterial.add(key);\n }\n }\n\n // Decoded-envelope byte backstop. Every per-slot field above is validated to a\n // fixed length, so the decoded envelope's aggregate size is determined here:\n // nonce + slots_mac + per-slot (epk|kem_ct + wrap). Reject before any KEM/AEAD\n // primitive when it exceeds the bound — a tighter resource cap than MAX_SLOTS\n // for honest records, and the bound a parser that can see the decoded size\n // enforces. (The slot-count cap above already bounds work; this is the byte\n // backstop the verifier also pins.)\n const perSlotBytes =\n envelope.kem === 'x25519'\n ? X25519_PUBLIC_KEY_LENGTH + WRAP_LENGTH\n : MLKEM768X25519_ENC_LENGTH + WRAP_LENGTH;\n const decodedEnvelopeBytes = NONCE_LENGTH + SLOTS_MAC_LENGTH + n * perSlotBytes;\n if (decodedEnvelopeBytes > MAX_DECODED_ENVELOPE_BYTES) {\n throw new EciesSealedPoeError(\n 'ENC_ENVELOPE_TOO_LARGE',\n `decoded envelope size ${decodedEnvelopeBytes} exceeds MAX_DECODED_ENVELOPE_BYTES=${MAX_DECODED_ENVELOPE_BYTES}`,\n );\n }\n\n if (multiPrivKeys !== undefined) {\n for (let i = 0; i < multiPrivKeys.length; i++) {\n if (multiPrivKeys[i]!.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKeys[${i}] MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${multiPrivKeys[i]!.length}`,\n );\n }\n }\n } else if (singlePrivKey !== undefined) {\n if (singlePrivKey.length !== X25519_SECRET_KEY_LENGTH) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n `recipientSecretKey MUST be exactly ${X25519_SECRET_KEY_LENGTH} bytes, got ${singlePrivKey.length}`,\n );\n }\n }\n}\n\n// All-zero IKM for the dummy KEK an invalid-ECDH slot derives so it pays the\n// same HKDF work as a live slot (see `tryX25519Slot`).\nconst ZERO_IKM_32: Uint8Array = new Uint8Array(32);\n// Fixed dummy candidate CEK for a slot whose wrap-open failed, so the per-slot\n// MAC step runs uniformly on every slot. The dummy is independent of the failed\n// ciphertext, and its MAC outcome can never accept a slot — acceptance also\n// requires the slot's `ok` bit.\nconst DUMMY_CEK_32: Uint8Array = new Uint8Array(32);\n\n// One slot's recovery outcome: the folded `kem_ok AND open_ok` acceptance\n// contribution as a 0|1 integer, plus the candidate CEK — the recovered\n// 32-byte wrap plaintext, or the fixed dummy when the bit is 0 — so the\n// caller's MAC step folds the same-shaped input for every slot.\ninterface SlotCandidate {\n readonly ok: number;\n readonly candidate: Uint8Array;\n}\n\n// Attempt the per-slot wrap AEAD, or yield the dummy candidate. Atomic: on a\n// tag failure no plaintext escapes and the candidate is the fixed all-zero\n// dummy, independent of the failed ciphertext.\nfunction wrapOpenOrDummy(kek: Uint8Array, aad: Uint8Array, wrap: Uint8Array): SlotCandidate {\n try {\n const plaintext = chacha20Poly1305Decrypt({\n key: kek,\n nonce: ZERO_NONCE_12,\n aad,\n ciphertext: wrap,\n });\n // The wrap is pre-validated to 48 bytes, so the recovered CEK is exactly\n // 32; anything else is treated as a failed open.\n if (plaintext.length === CEK_LENGTH) {\n return { ok: 1, candidate: plaintext };\n }\n return { ok: 0, candidate: DUMMY_CEK_32 };\n } catch (e) {\n if (!(e instanceof AeadVerificationError)) throw e;\n return { ok: 0, candidate: DUMMY_CEK_32 };\n }\n}\n\n// Classical (x25519) per-slot recovery body. The wrap AEAD is attempted on\n// EVERY slot (no match-position-dependent skip), so a per-priv scan recovers a\n// candidate CEK from each slot the recipient is addressed in — which is what\n// the CEK-conflict detection needs — and every slot pays the identical\n// ECDH + HKDF + AEAD-open cost regardless of where the match lands.\n//\n// `kem_ok` is the X25519 validity bit: a small-order `epk` drives the shared\n// secret to all-zero, which RFC 7748 §6.1 rejects. @noble/curves signals this\n// by THROWING from `getSharedSecret`, so a fully branchless ct-select over the\n// shared secret is not expressible against this library API. The next-best,\n// equivalent form is taken instead: on the all-zero rejection the slot derives\n// a DUMMY KEK from `ikm=0^32` (same salt/info — same HKDF work) and STILL\n// attempts the wrap-open under it, so the invalid-ECDH slot takes the same\n// per-slot work shape as a live one, while `kem_ok=0` folded into the returned\n// bit means it can never be accepted regardless of the AEAD outcome.\nfunction tryX25519Slot(args: {\n slot: X25519Slot;\n nonce: Uint8Array;\n recipientSecretKey: Uint8Array;\n pubRLocal: Uint8Array;\n}): SlotCandidate {\n const salt = x25519KekSalt({ nonce: args.nonce, epk: args.slot.epk, pubR: args.pubRLocal });\n let kemOk = 1;\n let kek: Uint8Array;\n try {\n const shared = x25519Ecdh({\n secretKey: args.recipientSecretKey,\n theirPublicKey: args.slot.epk,\n });\n kek = hkdfSha256({ ikm: shared, salt, info: CARDANO_POE_HKDF_INFO_KEK, length: 32 });\n } catch (e) {\n if (!(e instanceof X25519LowOrderPointError)) throw e;\n kemOk = 0;\n kek = hkdfSha256({ ikm: ZERO_IKM_32, salt, info: CARDANO_POE_HKDF_INFO_KEK, length: 32 });\n }\n const opened = wrapOpenOrDummy(kek, CARDANO_POE_HKDF_INFO_KEK, args.slot.wrap);\n return { ok: kemOk & opened.ok, candidate: opened.candidate };\n}\n\n// Hybrid (mlkem768x25519) per-slot recovery body. X-Wing decapsulate NEVER\n// throws on attacker wire data (ML-KEM implicit rejection), so there is no\n// try/catch and the KEM validity bit is constant 1: a wrong shared secret\n// simply yields a KEK that fails the AEAD tag. As in the classical body, the\n// AEAD is attempted on EVERY slot (full decapsulate + HKDF + AEAD-open) so\n// matching and non-matching slots cost the same X-Wing work.\nfunction tryMlkem768X25519Slot(args: {\n slot: Mlkem768X25519Slot;\n nonce: Uint8Array;\n recipientSecretKey: Uint8Array;\n pubR: Uint8Array;\n}): SlotCandidate {\n // kem_ct length was validated against MLKEM768X25519_ENC_LENGTH in\n // assertEnvelopeStructure, so this decapsulate is constant-work.\n const ss = mlkem768x25519Decapsulate({\n secretSeed: args.recipientSecretKey,\n enc: args.slot.kem_ct,\n });\n // The KEK salt binds the envelope nonce, the slot's own ciphertext, and the\n // recipient's own X-Wing public key (recomputed from the held seed), exactly\n // as the producer bound them — see the wrap path.\n const kek = hkdfSha256({\n ikm: ss,\n salt: xwingKekSalt({ nonce: args.nonce, kemCt: args.slot.kem_ct, pubR: args.pubR }),\n info: CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519,\n length: 32,\n });\n return wrapOpenOrDummy(kek, CARDANO_POE_HKDF_INFO_KEK_MLKEM768X25519, args.slot.wrap);\n}\n\n// Outcome of one private key's full pass over the slot array.\n//\n// • found — some slot fully matched (kem_ok AND open_ok AND mac_ok).\n// • selectedCek — the FIRST matching slot's CEK (null when !found).\n// • cekConflict — two matching slots recovered different CEKs (the\n// commitment collision the construction fails closed on).\n// • anyOpened — some slot wrap-opened under a valid KEM (`kem_ok AND\n// open_ok`), regardless of its MAC outcome. Distinguishes\n// the tampered-header diagnostic from a plain non-recipient.\ninterface PrivPassResult {\n readonly found: boolean;\n readonly selectedCek: Uint8Array | null;\n readonly selectedSlotIdx: number;\n readonly cekConflict: boolean;\n readonly anyOpened: boolean;\n}\n\n// Per-priv inner trial-decrypt loop, KEM-driven, with the slot-set MAC folded\n// into per-slot acceptance. Every slot is entered and every slot pays the same\n// work: KEM recovery, wrap-open, then the MAC check over the loop-constant\n// `slots_hash` — keyed from the recovered candidate CEK, or from a fixed dummy\n// when the wrap-open failed, so the MAC step is uniform too. This follows the\n// spec loop shape:\n//\n// ok = kem_ok AND open_ok AND mac_ok\n// first = ok AND NOT found\n// cek_conflict = cek_conflict OR (ok AND found AND NOT ctEq(cand, selected))\n// selected_CEK = select(first, cand, selected)\n// found = found OR ok\n//\n// No early break is taken, the bits combine with integer `&`/`|` (never a\n// short-circuit), and the running selection state is folded with mask-based\n// updates, so the scan takes the same source-level path across the whole slot\n// set regardless of where (or whether) a match lands.\nfunction runPrivPass(\n envelope: SealedEnvelope,\n recipientSecretKey: Uint8Array,\n slotsHash: Uint8Array,\n slotsAttemptedOut: { count: number; perPrivCounts?: number[] } | undefined,\n): PrivPassResult {\n const n = envelope.slots.length;\n const state = newSlotAcceptanceState();\n let anyOpenedBit = 0;\n\n const acceptSlot = (slot: SlotCandidate, i: number): void => {\n anyOpenedBit |= slot.ok;\n const macOk =\n Number(compareCt(computeSlotsMac({ cek: slot.candidate, slotsHash }), envelope.slots_mac)) &\n 1;\n foldSlotAcceptance(state, slot.ok & macOk, slot.candidate, i);\n };\n\n if (envelope.kem === 'x25519') {\n const pubRLocal = x25519PublicKey({ secretKey: recipientSecretKey });\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n acceptSlot(\n tryX25519Slot({\n slot: envelope.slots[i]!,\n nonce: envelope.nonce,\n recipientSecretKey,\n pubRLocal,\n }),\n i,\n );\n }\n } else {\n // Recompute the recipient's own X-Wing public key from the held seed: the\n // hybrid KEK salt binds `pub_R`, so each private key in a multi-key scan\n // MUST re-derive it (a single shared pub_R would compute the wrong KEK for\n // every key but one).\n const pubR = mlkem768x25519Keygen(recipientSecretKey).publicKey;\n for (let i = 0; i < n; i++) {\n if (slotsAttemptedOut !== undefined) {\n slotsAttemptedOut.count = i + 1;\n }\n acceptSlot(\n tryMlkem768X25519Slot({\n slot: envelope.slots[i]!,\n nonce: envelope.nonce,\n recipientSecretKey,\n pubR,\n }),\n i,\n );\n }\n }\n const outcome = finishSlotAcceptance(state);\n return {\n found: outcome.found,\n selectedCek: outcome.selectedCek,\n selectedSlotIdx: outcome.selectedSlotIdx,\n cekConflict: outcome.cekConflict,\n anyOpened: anyOpenedBit === 1,\n };\n}\n\n// 32-byte slots-transcript hash. It depends only on the header, the slots, and\n// the item's hash claim, so it is constant across the multi-priv outer loop and\n// the per-slot trial-decrypt loop — callers compute it ONCE and re-key the HMAC\n// from each candidate CEK over this same 32-byte message.\nfunction slotsHashBytes(envelope: SealedEnvelope, hashes: ItemHashes): Uint8Array {\n return computeSlotsHash({\n aead: envelope.aead,\n kem: envelope.kem,\n nonce: envelope.nonce,\n slots: envelope.slots as ReadonlyArray<X25519Slot | Mlkem768X25519Slot>,\n hashesHash: itemHashesHash(hashes),\n });\n}\n\nexport function eciesSealedPoeUnwrap(args: UnwrapArgs): UnwrapResult {\n const { envelope, ciphertext } = args;\n\n // Exactly-one-of validation across the three UnwrapArgs forms (single-priv,\n // flat multi-priv, bundle). Runs before any AEAD / wire-shape work so a\n // malformed call cannot probe per-slot AEAD timing. The bundle form resolves\n // to a flat multi-priv list here by dispatching on `envelope.kem` — from this\n // point the loop is identical regardless of how the caller supplied keys.\n const hasSingle = 'recipientSecretKey' in args;\n const hasBundle = 'recipientKeyBundle' in args;\n const multiPrivKeys: ReadonlyArray<Uint8Array> | undefined = hasBundle\n ? selectBundleSecrets(envelope, (args as UnwrapArgsBundle).recipientKeyBundle)\n : 'recipientSecretKeys' in args\n ? (args as UnwrapArgsMultiPriv).recipientSecretKeys\n : undefined;\n const hasMulti = multiPrivKeys !== undefined;\n if (hasSingle === hasMulti) {\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'exactly one of recipientSecretKey / recipientSecretKeys / recipientKeyBundle MUST be supplied',\n );\n }\n // A bundle selecting an empty list for this KEM means the recipient holds no\n // key of the matching kind (e.g. an archived-only identity facing a hybrid\n // record). That is a legitimate non-match, NOT a malformed call — return a\n // clean WRONG_RECIPIENT_KEY without invoking any KEM primitive. The flat\n // multi-priv form keeps the \"empty array is a programmer error\" contract.\n if (hasMulti && multiPrivKeys!.length === 0) {\n if (hasBundle) {\n return { matched: false, reason: 'WRONG_RECIPIENT_KEY' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n\n // Partitioning-oracle pre-checks; per-priv length validation happens\n // inside `assertEnvelopeStructure`.\n if (hasMulti) {\n assertEnvelopeStructure(envelope, multiPrivKeys, undefined);\n } else {\n assertEnvelopeStructure(envelope, undefined, (args as UnwrapArgsSinglePriv).recipientSecretKey);\n }\n\n // The slots-transcript hash (which also digests the item's hash claim) is\n // constant across the whole scan — compute it ONCE, then re-key the HMAC from\n // each candidate CEK over this same 32-byte message.\n const slotsHash = slotsHashBytes(envelope, args.hashes);\n\n let matchedCek: Uint8Array | null = null;\n let anyOpenedAcrossPrivs = false;\n\n const privKeys: ReadonlyArray<Uint8Array> = hasMulti\n ? multiPrivKeys!\n : [(args as UnwrapArgsSinglePriv).recipientSecretKey];\n\n for (let k = 0; k < privKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const pass = runPrivPass(envelope, privKeys[k]!, slotsHash, args._slotsAttemptedOut);\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n anyOpenedAcrossPrivs = anyOpenedAcrossPrivs || pass.anyOpened;\n if (!pass.found) continue;\n // Two accepted slots recovering different CEKs is the commitment collision\n // the construction fails closed on — an anomalous slot set, surfaced as the\n // generic tampered-header diagnostic.\n if (pass.cekConflict) {\n return { matched: false, reason: 'TAMPERED_HEADER' };\n }\n matchedCek = pass.selectedCek;\n // The outer cross-priv loop short-circuits on the first priv that accepted\n // a slot. This intentionally leaks \"which priv matched\" → \"how many key\n // rotations the recipient has performed\". We accept it: trial-decrypt runs\n // client-side, so this timing is only locally observable, and the leak is a\n // weak ordering signal, not a key/plaintext oracle. Making the outer loop\n // constant-work would cost a FULL KEM pass (for the hybrid branch a full\n // X-Wing decapsulation per slot) for EVERY archived priv on EVERY record;\n // the benefit (hiding a count the user already knows) does not justify it.\n // The inner per-slot loop IS constant across slots.\n break;\n }\n\n if (matchedCek === null) {\n // A slot wrap-opened somewhere but nothing passed the folded acceptance:\n // some slot, header field, the hashes claim, or slots_mac itself was\n // tampered. No wrap-open at all is a plain non-recipient.\n return {\n matched: false,\n reason: anyOpenedAcrossPrivs ? 'TAMPERED_HEADER' : 'WRONG_RECIPIENT_KEY',\n };\n }\n\n // Content opens under the derived `payload_key` in the segmented STREAM\n // format; each chunk's tag is verified before its plaintext is released.\n try {\n const plaintext = streamOpen({\n payloadKey: slotsPayloadKey({ cek: matchedCek, nonce: envelope.nonce }),\n ciphertext,\n });\n return { matched: true, plaintext };\n } catch (e) {\n if (!(e instanceof StreamTamperedError)) throw e;\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n}\n\n// Trial-decrypt half of the sealed-PoE unwrap algorithm:\n// recovers the CEK + slot index without touching the content stream. Used by an\n// inbox-scan agent where the on-chain envelope is available but the off-chain\n// ciphertext blob is fetched lazily only when the user invokes Decrypt.\n//\n// Mirrors the multi-priv branch of `eciesSealedPoeUnwrap`: same\n// partitioning-oracle pre-checks, same per-priv inner loop with the MAC folded\n// into per-slot acceptance, same constant-across-slots invariant. Differs only\n// in the return shape: `{kind: 'match', slotIdx, cek}` instead of plaintext;\n// `{kind: 'no_match'}` for everything else (per-slot acceptance is binary, so\n// there is no distinguishable middle outcome). Cross-priv variable-time\n// short-circuit is preserved (leaks \"which priv matched\" → \"how many\n// rotations\", a documented weak ordering signal).\nexport function eciesSealedPoeTrialDecrypt(args: TrialDecryptOnlyArgs): TrialDecryptOnlyResult {\n const { envelope } = args;\n\n // Bundle form selects the per-KEM list from `envelope.kem`; flat form is\n // already KEM-pre-selected. An empty bundle list for this KEM is a clean\n // no_match (the recipient holds no key of the matching kind), whereas an\n // empty flat list stays a programmer error.\n const hasBundle = 'recipientKeyBundle' in args;\n const recipientSecretKeys: ReadonlyArray<Uint8Array> = hasBundle\n ? selectBundleSecrets(envelope, args.recipientKeyBundle)\n : args.recipientSecretKeys;\n\n if (recipientSecretKeys.length === 0) {\n if (hasBundle) {\n return { kind: 'no_match' };\n }\n throw new EciesSealedPoeError(\n 'INVALID_RECIPIENT_KEY',\n 'recipientSecretKeys MUST be a non-empty array, got length=0',\n );\n }\n assertEnvelopeStructure(envelope, recipientSecretKeys, undefined);\n\n const slotsHash = slotsHashBytes(envelope, args.hashes);\n\n for (let k = 0; k < recipientSecretKeys.length; k++) {\n if (args._privsAttemptedOut !== undefined) {\n args._privsAttemptedOut.count = k + 1;\n }\n if (args._slotsAttemptedOut !== undefined) {\n args._slotsAttemptedOut.count = 0;\n }\n const pass = runPrivPass(envelope, recipientSecretKeys[k]!, slotsHash, args._slotsAttemptedOut);\n if (args._slotsAttemptedOut?.perPrivCounts !== undefined) {\n args._slotsAttemptedOut.perPrivCounts.push(args._slotsAttemptedOut.count);\n }\n if (!pass.found) continue;\n // A CEK conflict is never a clean match — fail closed.\n if (pass.cekConflict) {\n return { kind: 'no_match' };\n }\n return {\n kind: 'match',\n slotIdx: pass.selectedSlotIdx,\n cek: pass.selectedCek as Uint8Array,\n };\n }\n return { kind: 'no_match' };\n}\n","import { argon2id } from 'hash-wasm';\n\nexport interface Argon2idParams {\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport interface Argon2idV13Opts {\n readonly password: Uint8Array;\n readonly salt: Uint8Array;\n readonly memSizeKB: number;\n readonly iterations: number;\n readonly parallelism: number;\n readonly outBytes: number;\n}\n\nexport async function argon2idV13(opts: Argon2idV13Opts): Promise<Uint8Array> {\n return (await argon2id({\n password: opts.password,\n salt: opts.salt,\n parallelism: opts.parallelism,\n iterations: opts.iterations,\n memorySize: opts.memSizeKB,\n hashLength: opts.outBytes,\n outputType: 'binary',\n })) as Uint8Array;\n}\n","// Generated by generate-unicode-nfkc-16.py from the Unicode Character Database 16.0.0.\n// Do not edit by hand.\n//\n// Derived from Unicode data files, copyright (c) 2024 Unicode, Inc., used\n// under the UNICODE LICENSE V3 (https://www.unicode.org/license.txt).\n\n// Fully expanded compatibility (NFKD) decompositions, Hangul excluded.\n// Entry: <cp>=<cp> <cp>...; all numbers uppercase hex; entries sorted, ';'-joined.\nexport const NFKC16_DECOMPOSITION_PACKED: string = [\n 'A0=20;A8=20 308;AA=61;AF=20 304;B2=32;B3=33;B4=20 301;B5=3BC;B8=20 327;B9=31;BA=6F;BC=31',\n ' 2044 34;BD=31 2044 32;BE=33 2044 34;C0=41 300;C1=41 301;C2=41 302;C3=41 303;C4=41 308;C',\n '5=41 30A;C7=43 327;C8=45 300;C9=45 301;CA=45 302;CB=45 308;CC=49 300;CD=49 301;CE=49 302',\n ';CF=49 308;D1=4E 303;D2=4F 300;D3=4F 301;D4=4F 302;D5=4F 303;D6=4F 308;D9=55 300;DA=55 3',\n '01;DB=55 302;DC=55 308;DD=59 301;E0=61 300;E1=61 301;E2=61 302;E3=61 303;E4=61 308;E5=61',\n ' 30A;E7=63 327;E8=65 300;E9=65 301;EA=65 302;EB=65 308;EC=69 300;ED=69 301;EE=69 302;EF=',\n '69 308;F1=6E 303;F2=6F 300;F3=6F 301;F4=6F 302;F5=6F 303;F6=6F 308;F9=75 300;FA=75 301;F',\n 'B=75 302;FC=75 308;FD=79 301;FF=79 308;100=41 304;101=61 304;102=41 306;103=61 306;104=4',\n '1 328;105=61 328;106=43 301;107=63 301;108=43 302;109=63 302;10A=43 307;10B=63 307;10C=4',\n '3 30C;10D=63 30C;10E=44 30C;10F=64 30C;112=45 304;113=65 304;114=45 306;115=65 306;116=4',\n '5 307;117=65 307;118=45 328;119=65 328;11A=45 30C;11B=65 30C;11C=47 302;11D=67 302;11E=4',\n '7 306;11F=67 306;120=47 307;121=67 307;122=47 327;123=67 327;124=48 302;125=68 302;128=4',\n '9 303;129=69 303;12A=49 304;12B=69 304;12C=49 306;12D=69 306;12E=49 328;12F=69 328;130=4',\n '9 307;132=49 4A;133=69 6A;134=4A 302;135=6A 302;136=4B 327;137=6B 327;139=4C 301;13A=6C ',\n '301;13B=4C 327;13C=6C 327;13D=4C 30C;13E=6C 30C;13F=4C B7;140=6C B7;143=4E 301;144=6E 30',\n '1;145=4E 327;146=6E 327;147=4E 30C;148=6E 30C;149=2BC 6E;14C=4F 304;14D=6F 304;14E=4F 30',\n '6;14F=6F 306;150=4F 30B;151=6F 30B;154=52 301;155=72 301;156=52 327;157=72 327;158=52 30',\n 'C;159=72 30C;15A=53 301;15B=73 301;15C=53 302;15D=73 302;15E=53 327;15F=73 327;160=53 30',\n 'C;161=73 30C;162=54 327;163=74 327;164=54 30C;165=74 30C;168=55 303;169=75 303;16A=55 30',\n '4;16B=75 304;16C=55 306;16D=75 306;16E=55 30A;16F=75 30A;170=55 30B;171=75 30B;172=55 32',\n '8;173=75 328;174=57 302;175=77 302;176=59 302;177=79 302;178=59 308;179=5A 301;17A=7A 30',\n '1;17B=5A 307;17C=7A 307;17D=5A 30C;17E=7A 30C;17F=73;1A0=4F 31B;1A1=6F 31B;1AF=55 31B;1B',\n '0=75 31B;1C4=44 5A 30C;1C5=44 7A 30C;1C6=64 7A 30C;1C7=4C 4A;1C8=4C 6A;1C9=6C 6A;1CA=4E ',\n '4A;1CB=4E 6A;1CC=6E 6A;1CD=41 30C;1CE=61 30C;1CF=49 30C;1D0=69 30C;1D1=4F 30C;1D2=6F 30C',\n ';1D3=55 30C;1D4=75 30C;1D5=55 308 304;1D6=75 308 304;1D7=55 308 301;1D8=75 308 301;1D9=5',\n '5 308 30C;1DA=75 308 30C;1DB=55 308 300;1DC=75 308 300;1DE=41 308 304;1DF=61 308 304;1E0',\n '=41 307 304;1E1=61 307 304;1E2=C6 304;1E3=E6 304;1E6=47 30C;1E7=67 30C;1E8=4B 30C;1E9=6B',\n ' 30C;1EA=4F 328;1EB=6F 328;1EC=4F 328 304;1ED=6F 328 304;1EE=1B7 30C;1EF=292 30C;1F0=6A ',\n '30C;1F1=44 5A;1F2=44 7A;1F3=64 7A;1F4=47 301;1F5=67 301;1F8=4E 300;1F9=6E 300;1FA=41 30A',\n ' 301;1FB=61 30A 301;1FC=C6 301;1FD=E6 301;1FE=D8 301;1FF=F8 301;200=41 30F;201=61 30F;20',\n '2=41 311;203=61 311;204=45 30F;205=65 30F;206=45 311;207=65 311;208=49 30F;209=69 30F;20',\n 'A=49 311;20B=69 311;20C=4F 30F;20D=6F 30F;20E=4F 311;20F=6F 311;210=52 30F;211=72 30F;21',\n '2=52 311;213=72 311;214=55 30F;215=75 30F;216=55 311;217=75 311;218=53 326;219=73 326;21',\n 'A=54 326;21B=74 326;21E=48 30C;21F=68 30C;226=41 307;227=61 307;228=45 327;229=65 327;22',\n 'A=4F 308 304;22B=6F 308 304;22C=4F 303 304;22D=6F 303 304;22E=4F 307;22F=6F 307;230=4F 3',\n '07 304;231=6F 307 304;232=59 304;233=79 304;2B0=68;2B1=266;2B2=6A;2B3=72;2B4=279;2B5=27B',\n ';2B6=281;2B7=77;2B8=79;2D8=20 306;2D9=20 307;2DA=20 30A;2DB=20 328;2DC=20 303;2DD=20 30B',\n ';2E0=263;2E1=6C;2E2=73;2E3=78;2E4=295;340=300;341=301;343=313;344=308 301;374=2B9;37A=20',\n ' 345;37E=3B;384=20 301;385=20 308 301;386=391 301;387=B7;388=395 301;389=397 301;38A=399',\n ' 301;38C=39F 301;38E=3A5 301;38F=3A9 301;390=3B9 308 301;3AA=399 308;3AB=3A5 308;3AC=3B1',\n ' 301;3AD=3B5 301;3AE=3B7 301;3AF=3B9 301;3B0=3C5 308 301;3CA=3B9 308;3CB=3C5 308;3CC=3BF',\n ' 301;3CD=3C5 301;3CE=3C9 301;3D0=3B2;3D1=3B8;3D2=3A5;3D3=3A5 301;3D4=3A5 308;3D5=3C6;3D6',\n '=3C0;3F0=3BA;3F1=3C1;3F2=3C2;3F4=398;3F5=3B5;3F9=3A3;400=415 300;401=415 308;403=413 301',\n ';407=406 308;40C=41A 301;40D=418 300;40E=423 306;419=418 306;439=438 306;450=435 300;451',\n '=435 308;453=433 301;457=456 308;45C=43A 301;45D=438 300;45E=443 306;476=474 30F;477=475',\n ' 30F;4C1=416 306;4C2=436 306;4D0=410 306;4D1=430 306;4D2=410 308;4D3=430 308;4D6=415 306',\n ';4D7=435 306;4DA=4D8 308;4DB=4D9 308;4DC=416 308;4DD=436 308;4DE=417 308;4DF=437 308;4E2',\n '=418 304;4E3=438 304;4E4=418 308;4E5=438 308;4E6=41E 308;4E7=43E 308;4EA=4E8 308;4EB=4E9',\n ' 308;4EC=42D 308;4ED=44D 308;4EE=423 304;4EF=443 304;4F0=423 308;4F1=443 308;4F2=423 30B',\n ';4F3=443 30B;4F4=427 308;4F5=447 308;4F8=42B 308;4F9=44B 308;587=565 582;622=627 653;623',\n '=627 654;624=648 654;625=627 655;626=64A 654;675=627 674;676=648 674;677=6C7 674;678=64A',\n ' 674;6C0=6D5 654;6C2=6C1 654;6D3=6D2 654;929=928 93C;931=930 93C;934=933 93C;958=915 93C',\n ';959=916 93C;95A=917 93C;95B=91C 93C;95C=921 93C;95D=922 93C;95E=92B 93C;95F=92F 93C;9CB',\n '=9C7 9BE;9CC=9C7 9D7;9DC=9A1 9BC;9DD=9A2 9BC;9DF=9AF 9BC;A33=A32 A3C;A36=A38 A3C;A59=A16',\n ' A3C;A5A=A17 A3C;A5B=A1C A3C;A5E=A2B A3C;B48=B47 B56;B4B=B47 B3E;B4C=B47 B57;B5C=B21 B3C',\n ';B5D=B22 B3C;B94=B92 BD7;BCA=BC6 BBE;BCB=BC7 BBE;BCC=BC6 BD7;C48=C46 C56;CC0=CBF CD5;CC7',\n '=CC6 CD5;CC8=CC6 CD6;CCA=CC6 CC2;CCB=CC6 CC2 CD5;D4A=D46 D3E;D4B=D47 D3E;D4C=D46 D57;DDA',\n '=DD9 DCA;DDC=DD9 DCF;DDD=DD9 DCF DCA;DDE=DD9 DDF;E33=E4D E32;EB3=ECD EB2;EDC=EAB E99;EDD',\n '=EAB EA1;F0C=F0B;F43=F42 FB7;F4D=F4C FB7;F52=F51 FB7;F57=F56 FB7;F5C=F5B FB7;F69=F40 FB5',\n ';F73=F71 F72;F75=F71 F74;F76=FB2 F80;F77=FB2 F71 F80;F78=FB3 F80;F79=FB3 F71 F80;F81=F71',\n ' F80;F93=F92 FB7;F9D=F9C FB7;FA2=FA1 FB7;FA7=FA6 FB7;FAC=FAB FB7;FB9=F90 FB5;1026=1025 1',\n '02E;10FC=10DC;1B06=1B05 1B35;1B08=1B07 1B35;1B0A=1B09 1B35;1B0C=1B0B 1B35;1B0E=1B0D 1B35',\n ';1B12=1B11 1B35;1B3B=1B3A 1B35;1B3D=1B3C 1B35;1B40=1B3E 1B35;1B41=1B3F 1B35;1B43=1B42 1B',\n '35;1D2C=41;1D2D=C6;1D2E=42;1D30=44;1D31=45;1D32=18E;1D33=47;1D34=48;1D35=49;1D36=4A;1D37',\n '=4B;1D38=4C;1D39=4D;1D3A=4E;1D3C=4F;1D3D=222;1D3E=50;1D3F=52;1D40=54;1D41=55;1D42=57;1D4',\n '3=61;1D44=250;1D45=251;1D46=1D02;1D47=62;1D48=64;1D49=65;1D4A=259;1D4B=25B;1D4C=25C;1D4D',\n '=67;1D4F=6B;1D50=6D;1D51=14B;1D52=6F;1D53=254;1D54=1D16;1D55=1D17;1D56=70;1D57=74;1D58=7',\n '5;1D59=1D1D;1D5A=26F;1D5B=76;1D5C=1D25;1D5D=3B2;1D5E=3B3;1D5F=3B4;1D60=3C6;1D61=3C7;1D62',\n '=69;1D63=72;1D64=75;1D65=76;1D66=3B2;1D67=3B3;1D68=3C1;1D69=3C6;1D6A=3C7;1D78=43D;1D9B=2',\n '52;1D9C=63;1D9D=255;1D9E=F0;1D9F=25C;1DA0=66;1DA1=25F;1DA2=261;1DA3=265;1DA4=268;1DA5=26',\n '9;1DA6=26A;1DA7=1D7B;1DA8=29D;1DA9=26D;1DAA=1D85;1DAB=29F;1DAC=271;1DAD=270;1DAE=272;1DA',\n 'F=273;1DB0=274;1DB1=275;1DB2=278;1DB3=282;1DB4=283;1DB5=1AB;1DB6=289;1DB7=28A;1DB8=1D1C;',\n '1DB9=28B;1DBA=28C;1DBB=7A;1DBC=290;1DBD=291;1DBE=292;1DBF=3B8;1E00=41 325;1E01=61 325;1E',\n '02=42 307;1E03=62 307;1E04=42 323;1E05=62 323;1E06=42 331;1E07=62 331;1E08=43 327 301;1E',\n '09=63 327 301;1E0A=44 307;1E0B=64 307;1E0C=44 323;1E0D=64 323;1E0E=44 331;1E0F=64 331;1E',\n '10=44 327;1E11=64 327;1E12=44 32D;1E13=64 32D;1E14=45 304 300;1E15=65 304 300;1E16=45 30',\n '4 301;1E17=65 304 301;1E18=45 32D;1E19=65 32D;1E1A=45 330;1E1B=65 330;1E1C=45 327 306;1E',\n '1D=65 327 306;1E1E=46 307;1E1F=66 307;1E20=47 304;1E21=67 304;1E22=48 307;1E23=68 307;1E',\n '24=48 323;1E25=68 323;1E26=48 308;1E27=68 308;1E28=48 327;1E29=68 327;1E2A=48 32E;1E2B=6',\n '8 32E;1E2C=49 330;1E2D=69 330;1E2E=49 308 301;1E2F=69 308 301;1E30=4B 301;1E31=6B 301;1E',\n '32=4B 323;1E33=6B 323;1E34=4B 331;1E35=6B 331;1E36=4C 323;1E37=6C 323;1E38=4C 323 304;1E',\n '39=6C 323 304;1E3A=4C 331;1E3B=6C 331;1E3C=4C 32D;1E3D=6C 32D;1E3E=4D 301;1E3F=6D 301;1E',\n '40=4D 307;1E41=6D 307;1E42=4D 323;1E43=6D 323;1E44=4E 307;1E45=6E 307;1E46=4E 323;1E47=6',\n 'E 323;1E48=4E 331;1E49=6E 331;1E4A=4E 32D;1E4B=6E 32D;1E4C=4F 303 301;1E4D=6F 303 301;1E',\n '4E=4F 303 308;1E4F=6F 303 308;1E50=4F 304 300;1E51=6F 304 300;1E52=4F 304 301;1E53=6F 30',\n '4 301;1E54=50 301;1E55=70 301;1E56=50 307;1E57=70 307;1E58=52 307;1E59=72 307;1E5A=52 32',\n '3;1E5B=72 323;1E5C=52 323 304;1E5D=72 323 304;1E5E=52 331;1E5F=72 331;1E60=53 307;1E61=7',\n '3 307;1E62=53 323;1E63=73 323;1E64=53 301 307;1E65=73 301 307;1E66=53 30C 307;1E67=73 30',\n 'C 307;1E68=53 323 307;1E69=73 323 307;1E6A=54 307;1E6B=74 307;1E6C=54 323;1E6D=74 323;1E',\n '6E=54 331;1E6F=74 331;1E70=54 32D;1E71=74 32D;1E72=55 324;1E73=75 324;1E74=55 330;1E75=7',\n '5 330;1E76=55 32D;1E77=75 32D;1E78=55 303 301;1E79=75 303 301;1E7A=55 304 308;1E7B=75 30',\n '4 308;1E7C=56 303;1E7D=76 303;1E7E=56 323;1E7F=76 323;1E80=57 300;1E81=77 300;1E82=57 30',\n '1;1E83=77 301;1E84=57 308;1E85=77 308;1E86=57 307;1E87=77 307;1E88=57 323;1E89=77 323;1E',\n '8A=58 307;1E8B=78 307;1E8C=58 308;1E8D=78 308;1E8E=59 307;1E8F=79 307;1E90=5A 302;1E91=7',\n 'A 302;1E92=5A 323;1E93=7A 323;1E94=5A 331;1E95=7A 331;1E96=68 331;1E97=74 308;1E98=77 30',\n 'A;1E99=79 30A;1E9A=61 2BE;1E9B=73 307;1EA0=41 323;1EA1=61 323;1EA2=41 309;1EA3=61 309;1E',\n 'A4=41 302 301;1EA5=61 302 301;1EA6=41 302 300;1EA7=61 302 300;1EA8=41 302 309;1EA9=61 30',\n '2 309;1EAA=41 302 303;1EAB=61 302 303;1EAC=41 323 302;1EAD=61 323 302;1EAE=41 306 301;1E',\n 'AF=61 306 301;1EB0=41 306 300;1EB1=61 306 300;1EB2=41 306 309;1EB3=61 306 309;1EB4=41 30',\n '6 303;1EB5=61 306 303;1EB6=41 323 306;1EB7=61 323 306;1EB8=45 323;1EB9=65 323;1EBA=45 30',\n '9;1EBB=65 309;1EBC=45 303;1EBD=65 303;1EBE=45 302 301;1EBF=65 302 301;1EC0=45 302 300;1E',\n 'C1=65 302 300;1EC2=45 302 309;1EC3=65 302 309;1EC4=45 302 303;1EC5=65 302 303;1EC6=45 32',\n '3 302;1EC7=65 323 302;1EC8=49 309;1EC9=69 309;1ECA=49 323;1ECB=69 323;1ECC=4F 323;1ECD=6',\n 'F 323;1ECE=4F 309;1ECF=6F 309;1ED0=4F 302 301;1ED1=6F 302 301;1ED2=4F 302 300;1ED3=6F 30',\n '2 300;1ED4=4F 302 309;1ED5=6F 302 309;1ED6=4F 302 303;1ED7=6F 302 303;1ED8=4F 323 302;1E',\n 'D9=6F 323 302;1EDA=4F 31B 301;1EDB=6F 31B 301;1EDC=4F 31B 300;1EDD=6F 31B 300;1EDE=4F 31',\n 'B 309;1EDF=6F 31B 309;1EE0=4F 31B 303;1EE1=6F 31B 303;1EE2=4F 31B 323;1EE3=6F 31B 323;1E',\n 'E4=55 323;1EE5=75 323;1EE6=55 309;1EE7=75 309;1EE8=55 31B 301;1EE9=75 31B 301;1EEA=55 31',\n 'B 300;1EEB=75 31B 300;1EEC=55 31B 309;1EED=75 31B 309;1EEE=55 31B 303;1EEF=75 31B 303;1E',\n 'F0=55 31B 323;1EF1=75 31B 323;1EF2=59 300;1EF3=79 300;1EF4=59 323;1EF5=79 323;1EF6=59 30',\n '9;1EF7=79 309;1EF8=59 303;1EF9=79 303;1F00=3B1 313;1F01=3B1 314;1F02=3B1 313 300;1F03=3B',\n '1 314 300;1F04=3B1 313 301;1F05=3B1 314 301;1F06=3B1 313 342;1F07=3B1 314 342;1F08=391 3',\n '13;1F09=391 314;1F0A=391 313 300;1F0B=391 314 300;1F0C=391 313 301;1F0D=391 314 301;1F0E',\n '=391 313 342;1F0F=391 314 342;1F10=3B5 313;1F11=3B5 314;1F12=3B5 313 300;1F13=3B5 314 30',\n '0;1F14=3B5 313 301;1F15=3B5 314 301;1F18=395 313;1F19=395 314;1F1A=395 313 300;1F1B=395 ',\n '314 300;1F1C=395 313 301;1F1D=395 314 301;1F20=3B7 313;1F21=3B7 314;1F22=3B7 313 300;1F2',\n '3=3B7 314 300;1F24=3B7 313 301;1F25=3B7 314 301;1F26=3B7 313 342;1F27=3B7 314 342;1F28=3',\n '97 313;1F29=397 314;1F2A=397 313 300;1F2B=397 314 300;1F2C=397 313 301;1F2D=397 314 301;',\n '1F2E=397 313 342;1F2F=397 314 342;1F30=3B9 313;1F31=3B9 314;1F32=3B9 313 300;1F33=3B9 31',\n '4 300;1F34=3B9 313 301;1F35=3B9 314 301;1F36=3B9 313 342;1F37=3B9 314 342;1F38=399 313;1',\n 'F39=399 314;1F3A=399 313 300;1F3B=399 314 300;1F3C=399 313 301;1F3D=399 314 301;1F3E=399',\n ' 313 342;1F3F=399 314 342;1F40=3BF 313;1F41=3BF 314;1F42=3BF 313 300;1F43=3BF 314 300;1F',\n '44=3BF 313 301;1F45=3BF 314 301;1F48=39F 313;1F49=39F 314;1F4A=39F 313 300;1F4B=39F 314 ',\n '300;1F4C=39F 313 301;1F4D=39F 314 301;1F50=3C5 313;1F51=3C5 314;1F52=3C5 313 300;1F53=3C',\n '5 314 300;1F54=3C5 313 301;1F55=3C5 314 301;1F56=3C5 313 342;1F57=3C5 314 342;1F59=3A5 3',\n '14;1F5B=3A5 314 300;1F5D=3A5 314 301;1F5F=3A5 314 342;1F60=3C9 313;1F61=3C9 314;1F62=3C9',\n ' 313 300;1F63=3C9 314 300;1F64=3C9 313 301;1F65=3C9 314 301;1F66=3C9 313 342;1F67=3C9 31',\n '4 342;1F68=3A9 313;1F69=3A9 314;1F6A=3A9 313 300;1F6B=3A9 314 300;1F6C=3A9 313 301;1F6D=',\n '3A9 314 301;1F6E=3A9 313 342;1F6F=3A9 314 342;1F70=3B1 300;1F71=3B1 301;1F72=3B5 300;1F7',\n '3=3B5 301;1F74=3B7 300;1F75=3B7 301;1F76=3B9 300;1F77=3B9 301;1F78=3BF 300;1F79=3BF 301;',\n '1F7A=3C5 300;1F7B=3C5 301;1F7C=3C9 300;1F7D=3C9 301;1F80=3B1 313 345;1F81=3B1 314 345;1F',\n '82=3B1 313 300 345;1F83=3B1 314 300 345;1F84=3B1 313 301 345;1F85=3B1 314 301 345;1F86=3',\n 'B1 313 342 345;1F87=3B1 314 342 345;1F88=391 313 345;1F89=391 314 345;1F8A=391 313 300 3',\n '45;1F8B=391 314 300 345;1F8C=391 313 301 345;1F8D=391 314 301 345;1F8E=391 313 342 345;1',\n 'F8F=391 314 342 345;1F90=3B7 313 345;1F91=3B7 314 345;1F92=3B7 313 300 345;1F93=3B7 314 ',\n '300 345;1F94=3B7 313 301 345;1F95=3B7 314 301 345;1F96=3B7 313 342 345;1F97=3B7 314 342 ',\n '345;1F98=397 313 345;1F99=397 314 345;1F9A=397 313 300 345;1F9B=397 314 300 345;1F9C=397',\n ' 313 301 345;1F9D=397 314 301 345;1F9E=397 313 342 345;1F9F=397 314 342 345;1FA0=3C9 313',\n ' 345;1FA1=3C9 314 345;1FA2=3C9 313 300 345;1FA3=3C9 314 300 345;1FA4=3C9 313 301 345;1FA',\n '5=3C9 314 301 345;1FA6=3C9 313 342 345;1FA7=3C9 314 342 345;1FA8=3A9 313 345;1FA9=3A9 31',\n '4 345;1FAA=3A9 313 300 345;1FAB=3A9 314 300 345;1FAC=3A9 313 301 345;1FAD=3A9 314 301 34',\n '5;1FAE=3A9 313 342 345;1FAF=3A9 314 342 345;1FB0=3B1 306;1FB1=3B1 304;1FB2=3B1 300 345;1',\n 'FB3=3B1 345;1FB4=3B1 301 345;1FB6=3B1 342;1FB7=3B1 342 345;1FB8=391 306;1FB9=391 304;1FB',\n 'A=391 300;1FBB=391 301;1FBC=391 345;1FBD=20 313;1FBE=3B9;1FBF=20 313;1FC0=20 342;1FC1=20',\n ' 308 342;1FC2=3B7 300 345;1FC3=3B7 345;1FC4=3B7 301 345;1FC6=3B7 342;1FC7=3B7 342 345;1F',\n 'C8=395 300;1FC9=395 301;1FCA=397 300;1FCB=397 301;1FCC=397 345;1FCD=20 313 300;1FCE=20 3',\n '13 301;1FCF=20 313 342;1FD0=3B9 306;1FD1=3B9 304;1FD2=3B9 308 300;1FD3=3B9 308 301;1FD6=',\n '3B9 342;1FD7=3B9 308 342;1FD8=399 306;1FD9=399 304;1FDA=399 300;1FDB=399 301;1FDD=20 314',\n ' 300;1FDE=20 314 301;1FDF=20 314 342;1FE0=3C5 306;1FE1=3C5 304;1FE2=3C5 308 300;1FE3=3C5',\n ' 308 301;1FE4=3C1 313;1FE5=3C1 314;1FE6=3C5 342;1FE7=3C5 308 342;1FE8=3A5 306;1FE9=3A5 3',\n '04;1FEA=3A5 300;1FEB=3A5 301;1FEC=3A1 314;1FED=20 308 300;1FEE=20 308 301;1FEF=60;1FF2=3',\n 'C9 300 345;1FF3=3C9 345;1FF4=3C9 301 345;1FF6=3C9 342;1FF7=3C9 342 345;1FF8=39F 300;1FF9',\n '=39F 301;1FFA=3A9 300;1FFB=3A9 301;1FFC=3A9 345;1FFD=20 301;1FFE=20 314;2000=20;2001=20;',\n '2002=20;2003=20;2004=20;2005=20;2006=20;2007=20;2008=20;2009=20;200A=20;2011=2010;2017=2',\n '0 333;2024=2E;2025=2E 2E;2026=2E 2E 2E;202F=20;2033=2032 2032;2034=2032 2032 2032;2036=2',\n '035 2035;2037=2035 2035 2035;203C=21 21;203E=20 305;2047=3F 3F;2048=3F 21;2049=21 3F;205',\n '7=2032 2032 2032 2032;205F=20;2070=30;2071=69;2074=34;2075=35;2076=36;2077=37;2078=38;20',\n '79=39;207A=2B;207B=2212;207C=3D;207D=28;207E=29;207F=6E;2080=30;2081=31;2082=32;2083=33;',\n '2084=34;2085=35;2086=36;2087=37;2088=38;2089=39;208A=2B;208B=2212;208C=3D;208D=28;208E=2',\n '9;2090=61;2091=65;2092=6F;2093=78;2094=259;2095=68;2096=6B;2097=6C;2098=6D;2099=6E;209A=',\n '70;209B=73;209C=74;20A8=52 73;2100=61 2F 63;2101=61 2F 73;2102=43;2103=B0 43;2105=63 2F ',\n '6F;2106=63 2F 75;2107=190;2109=B0 46;210A=67;210B=48;210C=48;210D=48;210E=68;210F=127;21',\n '10=49;2111=49;2112=4C;2113=6C;2115=4E;2116=4E 6F;2119=50;211A=51;211B=52;211C=52;211D=52',\n ';2120=53 4D;2121=54 45 4C;2122=54 4D;2124=5A;2126=3A9;2128=5A;212A=4B;212B=41 30A;212C=4',\n '2;212D=43;212F=65;2130=45;2131=46;2133=4D;2134=6F;2135=5D0;2136=5D1;2137=5D2;2138=5D3;21',\n '39=69;213B=46 41 58;213C=3C0;213D=3B3;213E=393;213F=3A0;2140=2211;2145=44;2146=64;2147=6',\n '5;2148=69;2149=6A;2150=31 2044 37;2151=31 2044 39;2152=31 2044 31 30;2153=31 2044 33;215',\n '4=32 2044 33;2155=31 2044 35;2156=32 2044 35;2157=33 2044 35;2158=34 2044 35;2159=31 204',\n '4 36;215A=35 2044 36;215B=31 2044 38;215C=33 2044 38;215D=35 2044 38;215E=37 2044 38;215',\n 'F=31 2044;2160=49;2161=49 49;2162=49 49 49;2163=49 56;2164=56;2165=56 49;2166=56 49 49;2',\n '167=56 49 49 49;2168=49 58;2169=58;216A=58 49;216B=58 49 49;216C=4C;216D=43;216E=44;216F',\n '=4D;2170=69;2171=69 69;2172=69 69 69;2173=69 76;2174=76;2175=76 69;2176=76 69 69;2177=76',\n ' 69 69 69;2178=69 78;2179=78;217A=78 69;217B=78 69 69;217C=6C;217D=63;217E=64;217F=6D;21',\n '89=30 2044 33;219A=2190 338;219B=2192 338;21AE=2194 338;21CD=21D0 338;21CE=21D4 338;21CF',\n '=21D2 338;2204=2203 338;2209=2208 338;220C=220B 338;2224=2223 338;2226=2225 338;222C=222',\n 'B 222B;222D=222B 222B 222B;222F=222E 222E;2230=222E 222E 222E;2241=223C 338;2244=2243 33',\n '8;2247=2245 338;2249=2248 338;2260=3D 338;2262=2261 338;226D=224D 338;226E=3C 338;226F=3',\n 'E 338;2270=2264 338;2271=2265 338;2274=2272 338;2275=2273 338;2278=2276 338;2279=2277 33',\n '8;2280=227A 338;2281=227B 338;2284=2282 338;2285=2283 338;2288=2286 338;2289=2287 338;22',\n 'AC=22A2 338;22AD=22A8 338;22AE=22A9 338;22AF=22AB 338;22E0=227C 338;22E1=227D 338;22E2=2',\n '291 338;22E3=2292 338;22EA=22B2 338;22EB=22B3 338;22EC=22B4 338;22ED=22B5 338;2329=3008;',\n '232A=3009;2460=31;2461=32;2462=33;2463=34;2464=35;2465=36;2466=37;2467=38;2468=39;2469=3',\n '1 30;246A=31 31;246B=31 32;246C=31 33;246D=31 34;246E=31 35;246F=31 36;2470=31 37;2471=3',\n '1 38;2472=31 39;2473=32 30;2474=28 31 29;2475=28 32 29;2476=28 33 29;2477=28 34 29;2478=',\n '28 35 29;2479=28 36 29;247A=28 37 29;247B=28 38 29;247C=28 39 29;247D=28 31 30 29;247E=2',\n '8 31 31 29;247F=28 31 32 29;2480=28 31 33 29;2481=28 31 34 29;2482=28 31 35 29;2483=28 3',\n '1 36 29;2484=28 31 37 29;2485=28 31 38 29;2486=28 31 39 29;2487=28 32 30 29;2488=31 2E;2',\n '489=32 2E;248A=33 2E;248B=34 2E;248C=35 2E;248D=36 2E;248E=37 2E;248F=38 2E;2490=39 2E;2',\n '491=31 30 2E;2492=31 31 2E;2493=31 32 2E;2494=31 33 2E;2495=31 34 2E;2496=31 35 2E;2497=',\n '31 36 2E;2498=31 37 2E;2499=31 38 2E;249A=31 39 2E;249B=32 30 2E;249C=28 61 29;249D=28 6',\n '2 29;249E=28 63 29;249F=28 64 29;24A0=28 65 29;24A1=28 66 29;24A2=28 67 29;24A3=28 68 29',\n ';24A4=28 69 29;24A5=28 6A 29;24A6=28 6B 29;24A7=28 6C 29;24A8=28 6D 29;24A9=28 6E 29;24A',\n 'A=28 6F 29;24AB=28 70 29;24AC=28 71 29;24AD=28 72 29;24AE=28 73 29;24AF=28 74 29;24B0=28',\n ' 75 29;24B1=28 76 29;24B2=28 77 29;24B3=28 78 29;24B4=28 79 29;24B5=28 7A 29;24B6=41;24B',\n '7=42;24B8=43;24B9=44;24BA=45;24BB=46;24BC=47;24BD=48;24BE=49;24BF=4A;24C0=4B;24C1=4C;24C',\n '2=4D;24C3=4E;24C4=4F;24C5=50;24C6=51;24C7=52;24C8=53;24C9=54;24CA=55;24CB=56;24CC=57;24C',\n 'D=58;24CE=59;24CF=5A;24D0=61;24D1=62;24D2=63;24D3=64;24D4=65;24D5=66;24D6=67;24D7=68;24D',\n '8=69;24D9=6A;24DA=6B;24DB=6C;24DC=6D;24DD=6E;24DE=6F;24DF=70;24E0=71;24E1=72;24E2=73;24E',\n '3=74;24E4=75;24E5=76;24E6=77;24E7=78;24E8=79;24E9=7A;24EA=30;2A0C=222B 222B 222B 222B;2A',\n '74=3A 3A 3D;2A75=3D 3D;2A76=3D 3D 3D;2ADC=2ADD 338;2C7C=6A;2C7D=56;2D6F=2D61;2E9F=6BCD;2',\n 'EF3=9F9F;2F00=4E00;2F01=4E28;2F02=4E36;2F03=4E3F;2F04=4E59;2F05=4E85;2F06=4E8C;2F07=4EA0',\n ';2F08=4EBA;2F09=513F;2F0A=5165;2F0B=516B;2F0C=5182;2F0D=5196;2F0E=51AB;2F0F=51E0;2F10=51',\n 'F5;2F11=5200;2F12=529B;2F13=52F9;2F14=5315;2F15=531A;2F16=5338;2F17=5341;2F18=535C;2F19=',\n '5369;2F1A=5382;2F1B=53B6;2F1C=53C8;2F1D=53E3;2F1E=56D7;2F1F=571F;2F20=58EB;2F21=5902;2F2',\n '2=590A;2F23=5915;2F24=5927;2F25=5973;2F26=5B50;2F27=5B80;2F28=5BF8;2F29=5C0F;2F2A=5C22;2',\n 'F2B=5C38;2F2C=5C6E;2F2D=5C71;2F2E=5DDB;2F2F=5DE5;2F30=5DF1;2F31=5DFE;2F32=5E72;2F33=5E7A',\n ';2F34=5E7F;2F35=5EF4;2F36=5EFE;2F37=5F0B;2F38=5F13;2F39=5F50;2F3A=5F61;2F3B=5F73;2F3C=5F',\n 'C3;2F3D=6208;2F3E=6236;2F3F=624B;2F40=652F;2F41=6534;2F42=6587;2F43=6597;2F44=65A4;2F45=',\n '65B9;2F46=65E0;2F47=65E5;2F48=66F0;2F49=6708;2F4A=6728;2F4B=6B20;2F4C=6B62;2F4D=6B79;2F4',\n 'E=6BB3;2F4F=6BCB;2F50=6BD4;2F51=6BDB;2F52=6C0F;2F53=6C14;2F54=6C34;2F55=706B;2F56=722A;2',\n 'F57=7236;2F58=723B;2F59=723F;2F5A=7247;2F5B=7259;2F5C=725B;2F5D=72AC;2F5E=7384;2F5F=7389',\n ';2F60=74DC;2F61=74E6;2F62=7518;2F63=751F;2F64=7528;2F65=7530;2F66=758B;2F67=7592;2F68=76',\n '76;2F69=767D;2F6A=76AE;2F6B=76BF;2F6C=76EE;2F6D=77DB;2F6E=77E2;2F6F=77F3;2F70=793A;2F71=',\n '79B8;2F72=79BE;2F73=7A74;2F74=7ACB;2F75=7AF9;2F76=7C73;2F77=7CF8;2F78=7F36;2F79=7F51;2F7',\n 'A=7F8A;2F7B=7FBD;2F7C=8001;2F7D=800C;2F7E=8012;2F7F=8033;2F80=807F;2F81=8089;2F82=81E3;2',\n 'F83=81EA;2F84=81F3;2F85=81FC;2F86=820C;2F87=821B;2F88=821F;2F89=826E;2F8A=8272;2F8B=8278',\n ';2F8C=864D;2F8D=866B;2F8E=8840;2F8F=884C;2F90=8863;2F91=897E;2F92=898B;2F93=89D2;2F94=8A',\n '00;2F95=8C37;2F96=8C46;2F97=8C55;2F98=8C78;2F99=8C9D;2F9A=8D64;2F9B=8D70;2F9C=8DB3;2F9D=',\n '8EAB;2F9E=8ECA;2F9F=8F9B;2FA0=8FB0;2FA1=8FB5;2FA2=9091;2FA3=9149;2FA4=91C6;2FA5=91CC;2FA',\n '6=91D1;2FA7=9577;2FA8=9580;2FA9=961C;2FAA=96B6;2FAB=96B9;2FAC=96E8;2FAD=9751;2FAE=975E;2',\n 'FAF=9762;2FB0=9769;2FB1=97CB;2FB2=97ED;2FB3=97F3;2FB4=9801;2FB5=98A8;2FB6=98DB;2FB7=98DF',\n ';2FB8=9996;2FB9=9999;2FBA=99AC;2FBB=9AA8;2FBC=9AD8;2FBD=9ADF;2FBE=9B25;2FBF=9B2F;2FC0=9B',\n '32;2FC1=9B3C;2FC2=9B5A;2FC3=9CE5;2FC4=9E75;2FC5=9E7F;2FC6=9EA5;2FC7=9EBB;2FC8=9EC3;2FC9=',\n '9ECD;2FCA=9ED1;2FCB=9EF9;2FCC=9EFD;2FCD=9F0E;2FCE=9F13;2FCF=9F20;2FD0=9F3B;2FD1=9F4A;2FD',\n '2=9F52;2FD3=9F8D;2FD4=9F9C;2FD5=9FA0;3000=20;3036=3012;3038=5341;3039=5344;303A=5345;304',\n 'C=304B 3099;304E=304D 3099;3050=304F 3099;3052=3051 3099;3054=3053 3099;3056=3055 3099;3',\n '058=3057 3099;305A=3059 3099;305C=305B 3099;305E=305D 3099;3060=305F 3099;3062=3061 3099',\n ';3065=3064 3099;3067=3066 3099;3069=3068 3099;3070=306F 3099;3071=306F 309A;3073=3072 30',\n '99;3074=3072 309A;3076=3075 3099;3077=3075 309A;3079=3078 3099;307A=3078 309A;307C=307B ',\n '3099;307D=307B 309A;3094=3046 3099;309B=20 3099;309C=20 309A;309E=309D 3099;309F=3088 30',\n '8A;30AC=30AB 3099;30AE=30AD 3099;30B0=30AF 3099;30B2=30B1 3099;30B4=30B3 3099;30B6=30B5 ',\n '3099;30B8=30B7 3099;30BA=30B9 3099;30BC=30BB 3099;30BE=30BD 3099;30C0=30BF 3099;30C2=30C',\n '1 3099;30C5=30C4 3099;30C7=30C6 3099;30C9=30C8 3099;30D0=30CF 3099;30D1=30CF 309A;30D3=3',\n '0D2 3099;30D4=30D2 309A;30D6=30D5 3099;30D7=30D5 309A;30D9=30D8 3099;30DA=30D8 309A;30DC',\n '=30DB 3099;30DD=30DB 309A;30F4=30A6 3099;30F7=30EF 3099;30F8=30F0 3099;30F9=30F1 3099;30',\n 'FA=30F2 3099;30FE=30FD 3099;30FF=30B3 30C8;3131=1100;3132=1101;3133=11AA;3134=1102;3135=',\n '11AC;3136=11AD;3137=1103;3138=1104;3139=1105;313A=11B0;313B=11B1;313C=11B2;313D=11B3;313',\n 'E=11B4;313F=11B5;3140=111A;3141=1106;3142=1107;3143=1108;3144=1121;3145=1109;3146=110A;3',\n '147=110B;3148=110C;3149=110D;314A=110E;314B=110F;314C=1110;314D=1111;314E=1112;314F=1161',\n ';3150=1162;3151=1163;3152=1164;3153=1165;3154=1166;3155=1167;3156=1168;3157=1169;3158=11',\n '6A;3159=116B;315A=116C;315B=116D;315C=116E;315D=116F;315E=1170;315F=1171;3160=1172;3161=',\n '1173;3162=1174;3163=1175;3164=1160;3165=1114;3166=1115;3167=11C7;3168=11C8;3169=11CC;316',\n 'A=11CE;316B=11D3;316C=11D7;316D=11D9;316E=111C;316F=11DD;3170=11DF;3171=111D;3172=111E;3',\n '173=1120;3174=1122;3175=1123;3176=1127;3177=1129;3178=112B;3179=112C;317A=112D;317B=112E',\n ';317C=112F;317D=1132;317E=1136;317F=1140;3180=1147;3181=114C;3182=11F1;3183=11F2;3184=11',\n '57;3185=1158;3186=1159;3187=1184;3188=1185;3189=1188;318A=1191;318B=1192;318C=1194;318D=',\n '119E;318E=11A1;3192=4E00;3193=4E8C;3194=4E09;3195=56DB;3196=4E0A;3197=4E2D;3198=4E0B;319',\n '9=7532;319A=4E59;319B=4E19;319C=4E01;319D=5929;319E=5730;319F=4EBA;3200=28 1100 29;3201=',\n '28 1102 29;3202=28 1103 29;3203=28 1105 29;3204=28 1106 29;3205=28 1107 29;3206=28 1109 ',\n '29;3207=28 110B 29;3208=28 110C 29;3209=28 110E 29;320A=28 110F 29;320B=28 1110 29;320C=',\n '28 1111 29;320D=28 1112 29;320E=28 1100 1161 29;320F=28 1102 1161 29;3210=28 1103 1161 2',\n '9;3211=28 1105 1161 29;3212=28 1106 1161 29;3213=28 1107 1161 29;3214=28 1109 1161 29;32',\n '15=28 110B 1161 29;3216=28 110C 1161 29;3217=28 110E 1161 29;3218=28 110F 1161 29;3219=2',\n '8 1110 1161 29;321A=28 1111 1161 29;321B=28 1112 1161 29;321C=28 110C 116E 29;321D=28 11',\n '0B 1169 110C 1165 11AB 29;321E=28 110B 1169 1112 116E 29;3220=28 4E00 29;3221=28 4E8C 29',\n ';3222=28 4E09 29;3223=28 56DB 29;3224=28 4E94 29;3225=28 516D 29;3226=28 4E03 29;3227=28',\n ' 516B 29;3228=28 4E5D 29;3229=28 5341 29;322A=28 6708 29;322B=28 706B 29;322C=28 6C34 29',\n ';322D=28 6728 29;322E=28 91D1 29;322F=28 571F 29;3230=28 65E5 29;3231=28 682A 29;3232=28',\n ' 6709 29;3233=28 793E 29;3234=28 540D 29;3235=28 7279 29;3236=28 8CA1 29;3237=28 795D 29',\n ';3238=28 52B4 29;3239=28 4EE3 29;323A=28 547C 29;323B=28 5B66 29;323C=28 76E3 29;323D=28',\n ' 4F01 29;323E=28 8CC7 29;323F=28 5354 29;3240=28 796D 29;3241=28 4F11 29;3242=28 81EA 29',\n ';3243=28 81F3 29;3244=554F;3245=5E7C;3246=6587;3247=7B8F;3250=50 54 45;3251=32 31;3252=3',\n '2 32;3253=32 33;3254=32 34;3255=32 35;3256=32 36;3257=32 37;3258=32 38;3259=32 39;325A=3',\n '3 30;325B=33 31;325C=33 32;325D=33 33;325E=33 34;325F=33 35;3260=1100;3261=1102;3262=110',\n '3;3263=1105;3264=1106;3265=1107;3266=1109;3267=110B;3268=110C;3269=110E;326A=110F;326B=1',\n '110;326C=1111;326D=1112;326E=1100 1161;326F=1102 1161;3270=1103 1161;3271=1105 1161;3272',\n '=1106 1161;3273=1107 1161;3274=1109 1161;3275=110B 1161;3276=110C 1161;3277=110E 1161;32',\n '78=110F 1161;3279=1110 1161;327A=1111 1161;327B=1112 1161;327C=110E 1161 11B7 1100 1169;',\n '327D=110C 116E 110B 1174;327E=110B 116E;3280=4E00;3281=4E8C;3282=4E09;3283=56DB;3284=4E9',\n '4;3285=516D;3286=4E03;3287=516B;3288=4E5D;3289=5341;328A=6708;328B=706B;328C=6C34;328D=6',\n '728;328E=91D1;328F=571F;3290=65E5;3291=682A;3292=6709;3293=793E;3294=540D;3295=7279;3296',\n '=8CA1;3297=795D;3298=52B4;3299=79D8;329A=7537;329B=5973;329C=9069;329D=512A;329E=5370;32',\n '9F=6CE8;32A0=9805;32A1=4F11;32A2=5199;32A3=6B63;32A4=4E0A;32A5=4E2D;32A6=4E0B;32A7=5DE6;',\n '32A8=53F3;32A9=533B;32AA=5B97;32AB=5B66;32AC=76E3;32AD=4F01;32AE=8CC7;32AF=5354;32B0=591',\n 'C;32B1=33 36;32B2=33 37;32B3=33 38;32B4=33 39;32B5=34 30;32B6=34 31;32B7=34 32;32B8=34 3',\n '3;32B9=34 34;32BA=34 35;32BB=34 36;32BC=34 37;32BD=34 38;32BE=34 39;32BF=35 30;32C0=31 6',\n '708;32C1=32 6708;32C2=33 6708;32C3=34 6708;32C4=35 6708;32C5=36 6708;32C6=37 6708;32C7=3',\n '8 6708;32C8=39 6708;32C9=31 30 6708;32CA=31 31 6708;32CB=31 32 6708;32CC=48 67;32CD=65 7',\n '2 67;32CE=65 56;32CF=4C 54 44;32D0=30A2;32D1=30A4;32D2=30A6;32D3=30A8;32D4=30AA;32D5=30A',\n 'B;32D6=30AD;32D7=30AF;32D8=30B1;32D9=30B3;32DA=30B5;32DB=30B7;32DC=30B9;32DD=30BB;32DE=3',\n '0BD;32DF=30BF;32E0=30C1;32E1=30C4;32E2=30C6;32E3=30C8;32E4=30CA;32E5=30CB;32E6=30CC;32E7',\n '=30CD;32E8=30CE;32E9=30CF;32EA=30D2;32EB=30D5;32EC=30D8;32ED=30DB;32EE=30DE;32EF=30DF;32',\n 'F0=30E0;32F1=30E1;32F2=30E2;32F3=30E4;32F4=30E6;32F5=30E8;32F6=30E9;32F7=30EA;32F8=30EB;',\n '32F9=30EC;32FA=30ED;32FB=30EF;32FC=30F0;32FD=30F1;32FE=30F2;32FF=4EE4 548C;3300=30A2 30C',\n 'F 309A 30FC 30C8;3301=30A2 30EB 30D5 30A1;3302=30A2 30F3 30D8 309A 30A2;3303=30A2 30FC 3',\n '0EB;3304=30A4 30CB 30F3 30AF 3099;3305=30A4 30F3 30C1;3306=30A6 30A9 30F3;3307=30A8 30B9',\n ' 30AF 30FC 30C8 3099;3308=30A8 30FC 30AB 30FC;3309=30AA 30F3 30B9;330A=30AA 30FC 30E0;33',\n '0B=30AB 30A4 30EA;330C=30AB 30E9 30C3 30C8;330D=30AB 30ED 30EA 30FC;330E=30AB 3099 30ED ',\n '30F3;330F=30AB 3099 30F3 30DE;3310=30AD 3099 30AB 3099;3311=30AD 3099 30CB 30FC;3312=30A',\n 'D 30E5 30EA 30FC;3313=30AD 3099 30EB 30BF 3099 30FC;3314=30AD 30ED;3315=30AD 30ED 30AF 3',\n '099 30E9 30E0;3316=30AD 30ED 30E1 30FC 30C8 30EB;3317=30AD 30ED 30EF 30C3 30C8;3318=30AF',\n ' 3099 30E9 30E0;3319=30AF 3099 30E9 30E0 30C8 30F3;331A=30AF 30EB 30BB 3099 30A4 30ED;33',\n '1B=30AF 30ED 30FC 30CD;331C=30B1 30FC 30B9;331D=30B3 30EB 30CA;331E=30B3 30FC 30DB 309A;',\n '331F=30B5 30A4 30AF 30EB;3320=30B5 30F3 30C1 30FC 30E0;3321=30B7 30EA 30F3 30AF 3099;332',\n '2=30BB 30F3 30C1;3323=30BB 30F3 30C8;3324=30BF 3099 30FC 30B9;3325=30C6 3099 30B7;3326=3',\n '0C8 3099 30EB;3327=30C8 30F3;3328=30CA 30CE;3329=30CE 30C3 30C8;332A=30CF 30A4 30C4;332B',\n '=30CF 309A 30FC 30BB 30F3 30C8;332C=30CF 309A 30FC 30C4;332D=30CF 3099 30FC 30EC 30EB;33',\n '2E=30D2 309A 30A2 30B9 30C8 30EB;332F=30D2 309A 30AF 30EB;3330=30D2 309A 30B3;3331=30D2 ',\n '3099 30EB;3332=30D5 30A1 30E9 30C3 30C8 3099;3333=30D5 30A3 30FC 30C8;3334=30D5 3099 30C',\n '3 30B7 30A7 30EB;3335=30D5 30E9 30F3;3336=30D8 30AF 30BF 30FC 30EB;3337=30D8 309A 30BD;3',\n '338=30D8 309A 30CB 30D2;3339=30D8 30EB 30C4;333A=30D8 309A 30F3 30B9;333B=30D8 309A 30FC',\n ' 30B7 3099;333C=30D8 3099 30FC 30BF;333D=30DB 309A 30A4 30F3 30C8;333E=30DB 3099 30EB 30',\n 'C8;333F=30DB 30F3;3340=30DB 309A 30F3 30C8 3099;3341=30DB 30FC 30EB;3342=30DB 30FC 30F3;',\n '3343=30DE 30A4 30AF 30ED;3344=30DE 30A4 30EB;3345=30DE 30C3 30CF;3346=30DE 30EB 30AF;334',\n '7=30DE 30F3 30B7 30E7 30F3;3348=30DF 30AF 30ED 30F3;3349=30DF 30EA;334A=30DF 30EA 30CF 3',\n '099 30FC 30EB;334B=30E1 30AB 3099;334C=30E1 30AB 3099 30C8 30F3;334D=30E1 30FC 30C8 30EB',\n ';334E=30E4 30FC 30C8 3099;334F=30E4 30FC 30EB;3350=30E6 30A2 30F3;3351=30EA 30C3 30C8 30',\n 'EB;3352=30EA 30E9;3353=30EB 30D2 309A 30FC;3354=30EB 30FC 30D5 3099 30EB;3355=30EC 30E0;',\n '3356=30EC 30F3 30C8 30B1 3099 30F3;3357=30EF 30C3 30C8;3358=30 70B9;3359=31 70B9;335A=32',\n ' 70B9;335B=33 70B9;335C=34 70B9;335D=35 70B9;335E=36 70B9;335F=37 70B9;3360=38 70B9;3361',\n '=39 70B9;3362=31 30 70B9;3363=31 31 70B9;3364=31 32 70B9;3365=31 33 70B9;3366=31 34 70B9',\n ';3367=31 35 70B9;3368=31 36 70B9;3369=31 37 70B9;336A=31 38 70B9;336B=31 39 70B9;336C=32',\n ' 30 70B9;336D=32 31 70B9;336E=32 32 70B9;336F=32 33 70B9;3370=32 34 70B9;3371=68 50 61;3',\n '372=64 61;3373=41 55;3374=62 61 72;3375=6F 56;3376=70 63;3377=64 6D;3378=64 6D 32;3379=6',\n '4 6D 33;337A=49 55;337B=5E73 6210;337C=662D 548C;337D=5927 6B63;337E=660E 6CBB;337F=682A',\n ' 5F0F 4F1A 793E;3380=70 41;3381=6E 41;3382=3BC 41;3383=6D 41;3384=6B 41;3385=4B 42;3386=',\n '4D 42;3387=47 42;3388=63 61 6C;3389=6B 63 61 6C;338A=70 46;338B=6E 46;338C=3BC 46;338D=3',\n 'BC 67;338E=6D 67;338F=6B 67;3390=48 7A;3391=6B 48 7A;3392=4D 48 7A;3393=47 48 7A;3394=54',\n ' 48 7A;3395=3BC 6C;3396=6D 6C;3397=64 6C;3398=6B 6C;3399=66 6D;339A=6E 6D;339B=3BC 6D;33',\n '9C=6D 6D;339D=63 6D;339E=6B 6D;339F=6D 6D 32;33A0=63 6D 32;33A1=6D 32;33A2=6B 6D 32;33A3',\n '=6D 6D 33;33A4=63 6D 33;33A5=6D 33;33A6=6B 6D 33;33A7=6D 2215 73;33A8=6D 2215 73 32;33A9',\n '=50 61;33AA=6B 50 61;33AB=4D 50 61;33AC=47 50 61;33AD=72 61 64;33AE=72 61 64 2215 73;33A',\n 'F=72 61 64 2215 73 32;33B0=70 73;33B1=6E 73;33B2=3BC 73;33B3=6D 73;33B4=70 56;33B5=6E 56',\n ';33B6=3BC 56;33B7=6D 56;33B8=6B 56;33B9=4D 56;33BA=70 57;33BB=6E 57;33BC=3BC 57;33BD=6D ',\n '57;33BE=6B 57;33BF=4D 57;33C0=6B 3A9;33C1=4D 3A9;33C2=61 2E 6D 2E;33C3=42 71;33C4=63 63;',\n '33C5=63 64;33C6=43 2215 6B 67;33C7=43 6F 2E;33C8=64 42;33C9=47 79;33CA=68 61;33CB=48 50;',\n '33CC=69 6E;33CD=4B 4B;33CE=4B 4D;33CF=6B 74;33D0=6C 6D;33D1=6C 6E;33D2=6C 6F 67;33D3=6C ',\n '78;33D4=6D 62;33D5=6D 69 6C;33D6=6D 6F 6C;33D7=50 48;33D8=70 2E 6D 2E;33D9=50 50 4D;33DA',\n '=50 52;33DB=73 72;33DC=53 76;33DD=57 62;33DE=56 2215 6D;33DF=41 2215 6D;33E0=31 65E5;33E',\n '1=32 65E5;33E2=33 65E5;33E3=34 65E5;33E4=35 65E5;33E5=36 65E5;33E6=37 65E5;33E7=38 65E5;',\n '33E8=39 65E5;33E9=31 30 65E5;33EA=31 31 65E5;33EB=31 32 65E5;33EC=31 33 65E5;33ED=31 34 ',\n '65E5;33EE=31 35 65E5;33EF=31 36 65E5;33F0=31 37 65E5;33F1=31 38 65E5;33F2=31 39 65E5;33F',\n '3=32 30 65E5;33F4=32 31 65E5;33F5=32 32 65E5;33F6=32 33 65E5;33F7=32 34 65E5;33F8=32 35 ',\n '65E5;33F9=32 36 65E5;33FA=32 37 65E5;33FB=32 38 65E5;33FC=32 39 65E5;33FD=33 30 65E5;33F',\n 'E=33 31 65E5;33FF=67 61 6C;A69C=44A;A69D=44C;A770=A76F;A7F2=43;A7F3=46;A7F4=51;A7F8=126;',\n 'A7F9=153;AB5C=A727;AB5D=AB37;AB5E=26B;AB5F=AB52;AB69=28D;F900=8C48;F901=66F4;F902=8ECA;F',\n '903=8CC8;F904=6ED1;F905=4E32;F906=53E5;F907=9F9C;F908=9F9C;F909=5951;F90A=91D1;F90B=5587',\n ';F90C=5948;F90D=61F6;F90E=7669;F90F=7F85;F910=863F;F911=87BA;F912=88F8;F913=908F;F914=6A',\n '02;F915=6D1B;F916=70D9;F917=73DE;F918=843D;F919=916A;F91A=99F1;F91B=4E82;F91C=5375;F91D=',\n '6B04;F91E=721B;F91F=862D;F920=9E1E;F921=5D50;F922=6FEB;F923=85CD;F924=8964;F925=62C9;F92',\n '6=81D8;F927=881F;F928=5ECA;F929=6717;F92A=6D6A;F92B=72FC;F92C=90CE;F92D=4F86;F92E=51B7;F',\n '92F=52DE;F930=64C4;F931=6AD3;F932=7210;F933=76E7;F934=8001;F935=8606;F936=865C;F937=8DEF',\n ';F938=9732;F939=9B6F;F93A=9DFA;F93B=788C;F93C=797F;F93D=7DA0;F93E=83C9;F93F=9304;F940=9E',\n '7F;F941=8AD6;F942=58DF;F943=5F04;F944=7C60;F945=807E;F946=7262;F947=78CA;F948=8CC2;F949=',\n '96F7;F94A=58D8;F94B=5C62;F94C=6A13;F94D=6DDA;F94E=6F0F;F94F=7D2F;F950=7E37;F951=964B;F95',\n '2=52D2;F953=808B;F954=51DC;F955=51CC;F956=7A1C;F957=7DBE;F958=83F1;F959=9675;F95A=8B80;F',\n '95B=62CF;F95C=6A02;F95D=8AFE;F95E=4E39;F95F=5BE7;F960=6012;F961=7387;F962=7570;F963=5317',\n ';F964=78FB;F965=4FBF;F966=5FA9;F967=4E0D;F968=6CCC;F969=6578;F96A=7D22;F96B=53C3;F96C=58',\n '5E;F96D=7701;F96E=8449;F96F=8AAA;F970=6BBA;F971=8FB0;F972=6C88;F973=62FE;F974=82E5;F975=',\n '63A0;F976=7565;F977=4EAE;F978=5169;F979=51C9;F97A=6881;F97B=7CE7;F97C=826F;F97D=8AD2;F97',\n 'E=91CF;F97F=52F5;F980=5442;F981=5973;F982=5EEC;F983=65C5;F984=6FFE;F985=792A;F986=95AD;F',\n '987=9A6A;F988=9E97;F989=9ECE;F98A=529B;F98B=66C6;F98C=6B77;F98D=8F62;F98E=5E74;F98F=6190',\n ';F990=6200;F991=649A;F992=6F23;F993=7149;F994=7489;F995=79CA;F996=7DF4;F997=806F;F998=8F',\n '26;F999=84EE;F99A=9023;F99B=934A;F99C=5217;F99D=52A3;F99E=54BD;F99F=70C8;F9A0=88C2;F9A1=',\n '8AAA;F9A2=5EC9;F9A3=5FF5;F9A4=637B;F9A5=6BAE;F9A6=7C3E;F9A7=7375;F9A8=4EE4;F9A9=56F9;F9A',\n 'A=5BE7;F9AB=5DBA;F9AC=601C;F9AD=73B2;F9AE=7469;F9AF=7F9A;F9B0=8046;F9B1=9234;F9B2=96F6;F',\n '9B3=9748;F9B4=9818;F9B5=4F8B;F9B6=79AE;F9B7=91B4;F9B8=96B8;F9B9=60E1;F9BA=4E86;F9BB=50DA',\n ';F9BC=5BEE;F9BD=5C3F;F9BE=6599;F9BF=6A02;F9C0=71CE;F9C1=7642;F9C2=84FC;F9C3=907C;F9C4=9F',\n '8D;F9C5=6688;F9C6=962E;F9C7=5289;F9C8=677B;F9C9=67F3;F9CA=6D41;F9CB=6E9C;F9CC=7409;F9CD=',\n '7559;F9CE=786B;F9CF=7D10;F9D0=985E;F9D1=516D;F9D2=622E;F9D3=9678;F9D4=502B;F9D5=5D19;F9D',\n '6=6DEA;F9D7=8F2A;F9D8=5F8B;F9D9=6144;F9DA=6817;F9DB=7387;F9DC=9686;F9DD=5229;F9DE=540F;F',\n '9DF=5C65;F9E0=6613;F9E1=674E;F9E2=68A8;F9E3=6CE5;F9E4=7406;F9E5=75E2;F9E6=7F79;F9E7=88CF',\n ';F9E8=88E1;F9E9=91CC;F9EA=96E2;F9EB=533F;F9EC=6EBA;F9ED=541D;F9EE=71D0;F9EF=7498;F9F0=85',\n 'FA;F9F1=96A3;F9F2=9C57;F9F3=9E9F;F9F4=6797;F9F5=6DCB;F9F6=81E8;F9F7=7ACB;F9F8=7B20;F9F9=',\n '7C92;F9FA=72C0;F9FB=7099;F9FC=8B58;F9FD=4EC0;F9FE=8336;F9FF=523A;FA00=5207;FA01=5EA6;FA0',\n '2=62D3;FA03=7CD6;FA04=5B85;FA05=6D1E;FA06=66B4;FA07=8F3B;FA08=884C;FA09=964D;FA0A=898B;F',\n 'A0B=5ED3;FA0C=5140;FA0D=55C0;FA10=585A;FA12=6674;FA15=51DE;FA16=732A;FA17=76CA;FA18=793C',\n ';FA19=795E;FA1A=7965;FA1B=798F;FA1C=9756;FA1D=7CBE;FA1E=7FBD;FA20=8612;FA22=8AF8;FA25=90',\n '38;FA26=90FD;FA2A=98EF;FA2B=98FC;FA2C=9928;FA2D=9DB4;FA2E=90DE;FA2F=96B7;FA30=4FAE;FA31=',\n '50E7;FA32=514D;FA33=52C9;FA34=52E4;FA35=5351;FA36=559D;FA37=5606;FA38=5668;FA39=5840;FA3',\n 'A=58A8;FA3B=5C64;FA3C=5C6E;FA3D=6094;FA3E=6168;FA3F=618E;FA40=61F2;FA41=654F;FA42=65E2;F',\n 'A43=6691;FA44=6885;FA45=6D77;FA46=6E1A;FA47=6F22;FA48=716E;FA49=722B;FA4A=7422;FA4B=7891',\n ';FA4C=793E;FA4D=7949;FA4E=7948;FA4F=7950;FA50=7956;FA51=795D;FA52=798D;FA53=798E;FA54=7A',\n '40;FA55=7A81;FA56=7BC0;FA57=7DF4;FA58=7E09;FA59=7E41;FA5A=7F72;FA5B=8005;FA5C=81ED;FA5D=',\n '8279;FA5E=8279;FA5F=8457;FA60=8910;FA61=8996;FA62=8B01;FA63=8B39;FA64=8CD3;FA65=8D08;FA6',\n '6=8FB6;FA67=9038;FA68=96E3;FA69=97FF;FA6A=983B;FA6B=6075;FA6C=242EE;FA6D=8218;FA70=4E26;',\n 'FA71=51B5;FA72=5168;FA73=4F80;FA74=5145;FA75=5180;FA76=52C7;FA77=52FA;FA78=559D;FA79=555',\n '5;FA7A=5599;FA7B=55E2;FA7C=585A;FA7D=58B3;FA7E=5944;FA7F=5954;FA80=5A62;FA81=5B28;FA82=5',\n 'ED2;FA83=5ED9;FA84=5F69;FA85=5FAD;FA86=60D8;FA87=614E;FA88=6108;FA89=618E;FA8A=6160;FA8B',\n '=61F2;FA8C=6234;FA8D=63C4;FA8E=641C;FA8F=6452;FA90=6556;FA91=6674;FA92=6717;FA93=671B;FA',\n '94=6756;FA95=6B79;FA96=6BBA;FA97=6D41;FA98=6EDB;FA99=6ECB;FA9A=6F22;FA9B=701E;FA9C=716E;',\n 'FA9D=77A7;FA9E=7235;FA9F=72AF;FAA0=732A;FAA1=7471;FAA2=7506;FAA3=753B;FAA4=761D;FAA5=761',\n 'F;FAA6=76CA;FAA7=76DB;FAA8=76F4;FAA9=774A;FAAA=7740;FAAB=78CC;FAAC=7AB1;FAAD=7BC0;FAAE=7',\n 'C7B;FAAF=7D5B;FAB0=7DF4;FAB1=7F3E;FAB2=8005;FAB3=8352;FAB4=83EF;FAB5=8779;FAB6=8941;FAB7',\n '=8986;FAB8=8996;FAB9=8ABF;FABA=8AF8;FABB=8ACB;FABC=8B01;FABD=8AFE;FABE=8AED;FABF=8B39;FA',\n 'C0=8B8A;FAC1=8D08;FAC2=8F38;FAC3=9072;FAC4=9199;FAC5=9276;FAC6=967C;FAC7=96E3;FAC8=9756;',\n 'FAC9=97DB;FACA=97FF;FACB=980B;FACC=983B;FACD=9B12;FACE=9F9C;FACF=2284A;FAD0=22844;FAD1=2',\n '33D5;FAD2=3B9D;FAD3=4018;FAD4=4039;FAD5=25249;FAD6=25CD0;FAD7=27ED3;FAD8=9F43;FAD9=9F8E;',\n 'FB00=66 66;FB01=66 69;FB02=66 6C;FB03=66 66 69;FB04=66 66 6C;FB05=73 74;FB06=73 74;FB13=',\n '574 576;FB14=574 565;FB15=574 56B;FB16=57E 576;FB17=574 56D;FB1D=5D9 5B4;FB1F=5F2 5B7;FB',\n '20=5E2;FB21=5D0;FB22=5D3;FB23=5D4;FB24=5DB;FB25=5DC;FB26=5DD;FB27=5E8;FB28=5EA;FB29=2B;F',\n 'B2A=5E9 5C1;FB2B=5E9 5C2;FB2C=5E9 5BC 5C1;FB2D=5E9 5BC 5C2;FB2E=5D0 5B7;FB2F=5D0 5B8;FB3',\n '0=5D0 5BC;FB31=5D1 5BC;FB32=5D2 5BC;FB33=5D3 5BC;FB34=5D4 5BC;FB35=5D5 5BC;FB36=5D6 5BC;',\n 'FB38=5D8 5BC;FB39=5D9 5BC;FB3A=5DA 5BC;FB3B=5DB 5BC;FB3C=5DC 5BC;FB3E=5DE 5BC;FB40=5E0 5',\n 'BC;FB41=5E1 5BC;FB43=5E3 5BC;FB44=5E4 5BC;FB46=5E6 5BC;FB47=5E7 5BC;FB48=5E8 5BC;FB49=5E',\n '9 5BC;FB4A=5EA 5BC;FB4B=5D5 5B9;FB4C=5D1 5BF;FB4D=5DB 5BF;FB4E=5E4 5BF;FB4F=5D0 5DC;FB50',\n '=671;FB51=671;FB52=67B;FB53=67B;FB54=67B;FB55=67B;FB56=67E;FB57=67E;FB58=67E;FB59=67E;FB',\n '5A=680;FB5B=680;FB5C=680;FB5D=680;FB5E=67A;FB5F=67A;FB60=67A;FB61=67A;FB62=67F;FB63=67F;',\n 'FB64=67F;FB65=67F;FB66=679;FB67=679;FB68=679;FB69=679;FB6A=6A4;FB6B=6A4;FB6C=6A4;FB6D=6A',\n '4;FB6E=6A6;FB6F=6A6;FB70=6A6;FB71=6A6;FB72=684;FB73=684;FB74=684;FB75=684;FB76=683;FB77=',\n '683;FB78=683;FB79=683;FB7A=686;FB7B=686;FB7C=686;FB7D=686;FB7E=687;FB7F=687;FB80=687;FB8',\n '1=687;FB82=68D;FB83=68D;FB84=68C;FB85=68C;FB86=68E;FB87=68E;FB88=688;FB89=688;FB8A=698;F',\n 'B8B=698;FB8C=691;FB8D=691;FB8E=6A9;FB8F=6A9;FB90=6A9;FB91=6A9;FB92=6AF;FB93=6AF;FB94=6AF',\n ';FB95=6AF;FB96=6B3;FB97=6B3;FB98=6B3;FB99=6B3;FB9A=6B1;FB9B=6B1;FB9C=6B1;FB9D=6B1;FB9E=6',\n 'BA;FB9F=6BA;FBA0=6BB;FBA1=6BB;FBA2=6BB;FBA3=6BB;FBA4=6D5 654;FBA5=6D5 654;FBA6=6C1;FBA7=',\n '6C1;FBA8=6C1;FBA9=6C1;FBAA=6BE;FBAB=6BE;FBAC=6BE;FBAD=6BE;FBAE=6D2;FBAF=6D2;FBB0=6D2 654',\n ';FBB1=6D2 654;FBD3=6AD;FBD4=6AD;FBD5=6AD;FBD6=6AD;FBD7=6C7;FBD8=6C7;FBD9=6C6;FBDA=6C6;FB',\n 'DB=6C8;FBDC=6C8;FBDD=6C7 674;FBDE=6CB;FBDF=6CB;FBE0=6C5;FBE1=6C5;FBE2=6C9;FBE3=6C9;FBE4=',\n '6D0;FBE5=6D0;FBE6=6D0;FBE7=6D0;FBE8=649;FBE9=649;FBEA=64A 654 627;FBEB=64A 654 627;FBEC=',\n '64A 654 6D5;FBED=64A 654 6D5;FBEE=64A 654 648;FBEF=64A 654 648;FBF0=64A 654 6C7;FBF1=64A',\n ' 654 6C7;FBF2=64A 654 6C6;FBF3=64A 654 6C6;FBF4=64A 654 6C8;FBF5=64A 654 6C8;FBF6=64A 65',\n '4 6D0;FBF7=64A 654 6D0;FBF8=64A 654 6D0;FBF9=64A 654 649;FBFA=64A 654 649;FBFB=64A 654 6',\n '49;FBFC=6CC;FBFD=6CC;FBFE=6CC;FBFF=6CC;FC00=64A 654 62C;FC01=64A 654 62D;FC02=64A 654 64',\n '5;FC03=64A 654 649;FC04=64A 654 64A;FC05=628 62C;FC06=628 62D;FC07=628 62E;FC08=628 645;',\n 'FC09=628 649;FC0A=628 64A;FC0B=62A 62C;FC0C=62A 62D;FC0D=62A 62E;FC0E=62A 645;FC0F=62A 6',\n '49;FC10=62A 64A;FC11=62B 62C;FC12=62B 645;FC13=62B 649;FC14=62B 64A;FC15=62C 62D;FC16=62',\n 'C 645;FC17=62D 62C;FC18=62D 645;FC19=62E 62C;FC1A=62E 62D;FC1B=62E 645;FC1C=633 62C;FC1D',\n '=633 62D;FC1E=633 62E;FC1F=633 645;FC20=635 62D;FC21=635 645;FC22=636 62C;FC23=636 62D;F',\n 'C24=636 62E;FC25=636 645;FC26=637 62D;FC27=637 645;FC28=638 645;FC29=639 62C;FC2A=639 64',\n '5;FC2B=63A 62C;FC2C=63A 645;FC2D=641 62C;FC2E=641 62D;FC2F=641 62E;FC30=641 645;FC31=641',\n ' 649;FC32=641 64A;FC33=642 62D;FC34=642 645;FC35=642 649;FC36=642 64A;FC37=643 627;FC38=',\n '643 62C;FC39=643 62D;FC3A=643 62E;FC3B=643 644;FC3C=643 645;FC3D=643 649;FC3E=643 64A;FC',\n '3F=644 62C;FC40=644 62D;FC41=644 62E;FC42=644 645;FC43=644 649;FC44=644 64A;FC45=645 62C',\n ';FC46=645 62D;FC47=645 62E;FC48=645 645;FC49=645 649;FC4A=645 64A;FC4B=646 62C;FC4C=646 ',\n '62D;FC4D=646 62E;FC4E=646 645;FC4F=646 649;FC50=646 64A;FC51=647 62C;FC52=647 645;FC53=6',\n '47 649;FC54=647 64A;FC55=64A 62C;FC56=64A 62D;FC57=64A 62E;FC58=64A 645;FC59=64A 649;FC5',\n 'A=64A 64A;FC5B=630 670;FC5C=631 670;FC5D=649 670;FC5E=20 64C 651;FC5F=20 64D 651;FC60=20',\n ' 64E 651;FC61=20 64F 651;FC62=20 650 651;FC63=20 651 670;FC64=64A 654 631;FC65=64A 654 6',\n '32;FC66=64A 654 645;FC67=64A 654 646;FC68=64A 654 649;FC69=64A 654 64A;FC6A=628 631;FC6B',\n '=628 632;FC6C=628 645;FC6D=628 646;FC6E=628 649;FC6F=628 64A;FC70=62A 631;FC71=62A 632;F',\n 'C72=62A 645;FC73=62A 646;FC74=62A 649;FC75=62A 64A;FC76=62B 631;FC77=62B 632;FC78=62B 64',\n '5;FC79=62B 646;FC7A=62B 649;FC7B=62B 64A;FC7C=641 649;FC7D=641 64A;FC7E=642 649;FC7F=642',\n ' 64A;FC80=643 627;FC81=643 644;FC82=643 645;FC83=643 649;FC84=643 64A;FC85=644 645;FC86=',\n '644 649;FC87=644 64A;FC88=645 627;FC89=645 645;FC8A=646 631;FC8B=646 632;FC8C=646 645;FC',\n '8D=646 646;FC8E=646 649;FC8F=646 64A;FC90=649 670;FC91=64A 631;FC92=64A 632;FC93=64A 645',\n ';FC94=64A 646;FC95=64A 649;FC96=64A 64A;FC97=64A 654 62C;FC98=64A 654 62D;FC99=64A 654 6',\n '2E;FC9A=64A 654 645;FC9B=64A 654 647;FC9C=628 62C;FC9D=628 62D;FC9E=628 62E;FC9F=628 645',\n ';FCA0=628 647;FCA1=62A 62C;FCA2=62A 62D;FCA3=62A 62E;FCA4=62A 645;FCA5=62A 647;FCA6=62B ',\n '645;FCA7=62C 62D;FCA8=62C 645;FCA9=62D 62C;FCAA=62D 645;FCAB=62E 62C;FCAC=62E 645;FCAD=6',\n '33 62C;FCAE=633 62D;FCAF=633 62E;FCB0=633 645;FCB1=635 62D;FCB2=635 62E;FCB3=635 645;FCB',\n '4=636 62C;FCB5=636 62D;FCB6=636 62E;FCB7=636 645;FCB8=637 62D;FCB9=638 645;FCBA=639 62C;',\n 'FCBB=639 645;FCBC=63A 62C;FCBD=63A 645;FCBE=641 62C;FCBF=641 62D;FCC0=641 62E;FCC1=641 6',\n '45;FCC2=642 62D;FCC3=642 645;FCC4=643 62C;FCC5=643 62D;FCC6=643 62E;FCC7=643 644;FCC8=64',\n '3 645;FCC9=644 62C;FCCA=644 62D;FCCB=644 62E;FCCC=644 645;FCCD=644 647;FCCE=645 62C;FCCF',\n '=645 62D;FCD0=645 62E;FCD1=645 645;FCD2=646 62C;FCD3=646 62D;FCD4=646 62E;FCD5=646 645;F',\n 'CD6=646 647;FCD7=647 62C;FCD8=647 645;FCD9=647 670;FCDA=64A 62C;FCDB=64A 62D;FCDC=64A 62',\n 'E;FCDD=64A 645;FCDE=64A 647;FCDF=64A 654 645;FCE0=64A 654 647;FCE1=628 645;FCE2=628 647;',\n 'FCE3=62A 645;FCE4=62A 647;FCE5=62B 645;FCE6=62B 647;FCE7=633 645;FCE8=633 647;FCE9=634 6',\n '45;FCEA=634 647;FCEB=643 644;FCEC=643 645;FCED=644 645;FCEE=646 645;FCEF=646 647;FCF0=64',\n 'A 645;FCF1=64A 647;FCF2=640 64E 651;FCF3=640 64F 651;FCF4=640 650 651;FCF5=637 649;FCF6=',\n '637 64A;FCF7=639 649;FCF8=639 64A;FCF9=63A 649;FCFA=63A 64A;FCFB=633 649;FCFC=633 64A;FC',\n 'FD=634 649;FCFE=634 64A;FCFF=62D 649;FD00=62D 64A;FD01=62C 649;FD02=62C 64A;FD03=62E 649',\n ';FD04=62E 64A;FD05=635 649;FD06=635 64A;FD07=636 649;FD08=636 64A;FD09=634 62C;FD0A=634 ',\n '62D;FD0B=634 62E;FD0C=634 645;FD0D=634 631;FD0E=633 631;FD0F=635 631;FD10=636 631;FD11=6',\n '37 649;FD12=637 64A;FD13=639 649;FD14=639 64A;FD15=63A 649;FD16=63A 64A;FD17=633 649;FD1',\n '8=633 64A;FD19=634 649;FD1A=634 64A;FD1B=62D 649;FD1C=62D 64A;FD1D=62C 649;FD1E=62C 64A;',\n 'FD1F=62E 649;FD20=62E 64A;FD21=635 649;FD22=635 64A;FD23=636 649;FD24=636 64A;FD25=634 6',\n '2C;FD26=634 62D;FD27=634 62E;FD28=634 645;FD29=634 631;FD2A=633 631;FD2B=635 631;FD2C=63',\n '6 631;FD2D=634 62C;FD2E=634 62D;FD2F=634 62E;FD30=634 645;FD31=633 647;FD32=634 647;FD33',\n '=637 645;FD34=633 62C;FD35=633 62D;FD36=633 62E;FD37=634 62C;FD38=634 62D;FD39=634 62E;F',\n 'D3A=637 645;FD3B=638 645;FD3C=627 64B;FD3D=627 64B;FD50=62A 62C 645;FD51=62A 62D 62C;FD5',\n '2=62A 62D 62C;FD53=62A 62D 645;FD54=62A 62E 645;FD55=62A 645 62C;FD56=62A 645 62D;FD57=6',\n '2A 645 62E;FD58=62C 645 62D;FD59=62C 645 62D;FD5A=62D 645 64A;FD5B=62D 645 649;FD5C=633 ',\n '62D 62C;FD5D=633 62C 62D;FD5E=633 62C 649;FD5F=633 645 62D;FD60=633 645 62D;FD61=633 645',\n ' 62C;FD62=633 645 645;FD63=633 645 645;FD64=635 62D 62D;FD65=635 62D 62D;FD66=635 645 64',\n '5;FD67=634 62D 645;FD68=634 62D 645;FD69=634 62C 64A;FD6A=634 645 62E;FD6B=634 645 62E;F',\n 'D6C=634 645 645;FD6D=634 645 645;FD6E=636 62D 649;FD6F=636 62E 645;FD70=636 62E 645;FD71',\n '=637 645 62D;FD72=637 645 62D;FD73=637 645 645;FD74=637 645 64A;FD75=639 62C 645;FD76=63',\n '9 645 645;FD77=639 645 645;FD78=639 645 649;FD79=63A 645 645;FD7A=63A 645 64A;FD7B=63A 6',\n '45 649;FD7C=641 62E 645;FD7D=641 62E 645;FD7E=642 645 62D;FD7F=642 645 645;FD80=644 62D ',\n '645;FD81=644 62D 64A;FD82=644 62D 649;FD83=644 62C 62C;FD84=644 62C 62C;FD85=644 62E 645',\n ';FD86=644 62E 645;FD87=644 645 62D;FD88=644 645 62D;FD89=645 62D 62C;FD8A=645 62D 645;FD',\n '8B=645 62D 64A;FD8C=645 62C 62D;FD8D=645 62C 645;FD8E=645 62E 62C;FD8F=645 62E 645;FD92=',\n '645 62C 62E;FD93=647 645 62C;FD94=647 645 645;FD95=646 62D 645;FD96=646 62D 649;FD97=646',\n ' 62C 645;FD98=646 62C 645;FD99=646 62C 649;FD9A=646 645 64A;FD9B=646 645 649;FD9C=64A 64',\n '5 645;FD9D=64A 645 645;FD9E=628 62E 64A;FD9F=62A 62C 64A;FDA0=62A 62C 649;FDA1=62A 62E 6',\n '4A;FDA2=62A 62E 649;FDA3=62A 645 64A;FDA4=62A 645 649;FDA5=62C 645 64A;FDA6=62C 62D 649;',\n 'FDA7=62C 645 649;FDA8=633 62E 649;FDA9=635 62D 64A;FDAA=634 62D 64A;FDAB=636 62D 64A;FDA',\n 'C=644 62C 64A;FDAD=644 645 64A;FDAE=64A 62D 64A;FDAF=64A 62C 64A;FDB0=64A 645 64A;FDB1=6',\n '45 645 64A;FDB2=642 645 64A;FDB3=646 62D 64A;FDB4=642 645 62D;FDB5=644 62D 645;FDB6=639 ',\n '645 64A;FDB7=643 645 64A;FDB8=646 62C 62D;FDB9=645 62E 64A;FDBA=644 62C 645;FDBB=643 645',\n ' 645;FDBC=644 62C 645;FDBD=646 62C 62D;FDBE=62C 62D 64A;FDBF=62D 62C 64A;FDC0=645 62C 64',\n 'A;FDC1=641 645 64A;FDC2=628 62D 64A;FDC3=643 645 645;FDC4=639 62C 645;FDC5=635 645 645;F',\n 'DC6=633 62E 64A;FDC7=646 62C 64A;FDF0=635 644 6D2;FDF1=642 644 6D2;FDF2=627 644 644 647;',\n 'FDF3=627 643 628 631;FDF4=645 62D 645 62F;FDF5=635 644 639 645;FDF6=631 633 648 644;FDF7',\n '=639 644 64A 647;FDF8=648 633 644 645;FDF9=635 644 649;FDFA=635 644 649 20 627 644 644 6',\n '47 20 639 644 64A 647 20 648 633 644 645;FDFB=62C 644 20 62C 644 627 644 647;FDFC=631 6C',\n 'C 627 644;FE10=2C;FE11=3001;FE12=3002;FE13=3A;FE14=3B;FE15=21;FE16=3F;FE17=3016;FE18=301',\n '7;FE19=2E 2E 2E;FE30=2E 2E;FE31=2014;FE32=2013;FE33=5F;FE34=5F;FE35=28;FE36=29;FE37=7B;F',\n 'E38=7D;FE39=3014;FE3A=3015;FE3B=3010;FE3C=3011;FE3D=300A;FE3E=300B;FE3F=3008;FE40=3009;F',\n 'E41=300C;FE42=300D;FE43=300E;FE44=300F;FE47=5B;FE48=5D;FE49=20 305;FE4A=20 305;FE4B=20 3',\n '05;FE4C=20 305;FE4D=5F;FE4E=5F;FE4F=5F;FE50=2C;FE51=3001;FE52=2E;FE54=3B;FE55=3A;FE56=3F',\n ';FE57=21;FE58=2014;FE59=28;FE5A=29;FE5B=7B;FE5C=7D;FE5D=3014;FE5E=3015;FE5F=23;FE60=26;F',\n 'E61=2A;FE62=2B;FE63=2D;FE64=3C;FE65=3E;FE66=3D;FE68=5C;FE69=24;FE6A=25;FE6B=40;FE70=20 6',\n '4B;FE71=640 64B;FE72=20 64C;FE74=20 64D;FE76=20 64E;FE77=640 64E;FE78=20 64F;FE79=640 64',\n 'F;FE7A=20 650;FE7B=640 650;FE7C=20 651;FE7D=640 651;FE7E=20 652;FE7F=640 652;FE80=621;FE',\n '81=627 653;FE82=627 653;FE83=627 654;FE84=627 654;FE85=648 654;FE86=648 654;FE87=627 655',\n ';FE88=627 655;FE89=64A 654;FE8A=64A 654;FE8B=64A 654;FE8C=64A 654;FE8D=627;FE8E=627;FE8F',\n '=628;FE90=628;FE91=628;FE92=628;FE93=629;FE94=629;FE95=62A;FE96=62A;FE97=62A;FE98=62A;FE',\n '99=62B;FE9A=62B;FE9B=62B;FE9C=62B;FE9D=62C;FE9E=62C;FE9F=62C;FEA0=62C;FEA1=62D;FEA2=62D;',\n 'FEA3=62D;FEA4=62D;FEA5=62E;FEA6=62E;FEA7=62E;FEA8=62E;FEA9=62F;FEAA=62F;FEAB=630;FEAC=63',\n '0;FEAD=631;FEAE=631;FEAF=632;FEB0=632;FEB1=633;FEB2=633;FEB3=633;FEB4=633;FEB5=634;FEB6=',\n '634;FEB7=634;FEB8=634;FEB9=635;FEBA=635;FEBB=635;FEBC=635;FEBD=636;FEBE=636;FEBF=636;FEC',\n '0=636;FEC1=637;FEC2=637;FEC3=637;FEC4=637;FEC5=638;FEC6=638;FEC7=638;FEC8=638;FEC9=639;F',\n 'ECA=639;FECB=639;FECC=639;FECD=63A;FECE=63A;FECF=63A;FED0=63A;FED1=641;FED2=641;FED3=641',\n ';FED4=641;FED5=642;FED6=642;FED7=642;FED8=642;FED9=643;FEDA=643;FEDB=643;FEDC=643;FEDD=6',\n '44;FEDE=644;FEDF=644;FEE0=644;FEE1=645;FEE2=645;FEE3=645;FEE4=645;FEE5=646;FEE6=646;FEE7',\n '=646;FEE8=646;FEE9=647;FEEA=647;FEEB=647;FEEC=647;FEED=648;FEEE=648;FEEF=649;FEF0=649;FE',\n 'F1=64A;FEF2=64A;FEF3=64A;FEF4=64A;FEF5=644 627 653;FEF6=644 627 653;FEF7=644 627 654;FEF',\n '8=644 627 654;FEF9=644 627 655;FEFA=644 627 655;FEFB=644 627;FEFC=644 627;FF01=21;FF02=2',\n '2;FF03=23;FF04=24;FF05=25;FF06=26;FF07=27;FF08=28;FF09=29;FF0A=2A;FF0B=2B;FF0C=2C;FF0D=2',\n 'D;FF0E=2E;FF0F=2F;FF10=30;FF11=31;FF12=32;FF13=33;FF14=34;FF15=35;FF16=36;FF17=37;FF18=3',\n '8;FF19=39;FF1A=3A;FF1B=3B;FF1C=3C;FF1D=3D;FF1E=3E;FF1F=3F;FF20=40;FF21=41;FF22=42;FF23=4',\n '3;FF24=44;FF25=45;FF26=46;FF27=47;FF28=48;FF29=49;FF2A=4A;FF2B=4B;FF2C=4C;FF2D=4D;FF2E=4',\n 'E;FF2F=4F;FF30=50;FF31=51;FF32=52;FF33=53;FF34=54;FF35=55;FF36=56;FF37=57;FF38=58;FF39=5',\n '9;FF3A=5A;FF3B=5B;FF3C=5C;FF3D=5D;FF3E=5E;FF3F=5F;FF40=60;FF41=61;FF42=62;FF43=63;FF44=6',\n '4;FF45=65;FF46=66;FF47=67;FF48=68;FF49=69;FF4A=6A;FF4B=6B;FF4C=6C;FF4D=6D;FF4E=6E;FF4F=6',\n 'F;FF50=70;FF51=71;FF52=72;FF53=73;FF54=74;FF55=75;FF56=76;FF57=77;FF58=78;FF59=79;FF5A=7',\n 'A;FF5B=7B;FF5C=7C;FF5D=7D;FF5E=7E;FF5F=2985;FF60=2986;FF61=3002;FF62=300C;FF63=300D;FF64',\n '=3001;FF65=30FB;FF66=30F2;FF67=30A1;FF68=30A3;FF69=30A5;FF6A=30A7;FF6B=30A9;FF6C=30E3;FF',\n '6D=30E5;FF6E=30E7;FF6F=30C3;FF70=30FC;FF71=30A2;FF72=30A4;FF73=30A6;FF74=30A8;FF75=30AA;',\n 'FF76=30AB;FF77=30AD;FF78=30AF;FF79=30B1;FF7A=30B3;FF7B=30B5;FF7C=30B7;FF7D=30B9;FF7E=30B',\n 'B;FF7F=30BD;FF80=30BF;FF81=30C1;FF82=30C4;FF83=30C6;FF84=30C8;FF85=30CA;FF86=30CB;FF87=3',\n '0CC;FF88=30CD;FF89=30CE;FF8A=30CF;FF8B=30D2;FF8C=30D5;FF8D=30D8;FF8E=30DB;FF8F=30DE;FF90',\n '=30DF;FF91=30E0;FF92=30E1;FF93=30E2;FF94=30E4;FF95=30E6;FF96=30E8;FF97=30E9;FF98=30EA;FF',\n '99=30EB;FF9A=30EC;FF9B=30ED;FF9C=30EF;FF9D=30F3;FF9E=3099;FF9F=309A;FFA0=1160;FFA1=1100;',\n 'FFA2=1101;FFA3=11AA;FFA4=1102;FFA5=11AC;FFA6=11AD;FFA7=1103;FFA8=1104;FFA9=1105;FFAA=11B',\n '0;FFAB=11B1;FFAC=11B2;FFAD=11B3;FFAE=11B4;FFAF=11B5;FFB0=111A;FFB1=1106;FFB2=1107;FFB3=1',\n '108;FFB4=1121;FFB5=1109;FFB6=110A;FFB7=110B;FFB8=110C;FFB9=110D;FFBA=110E;FFBB=110F;FFBC',\n '=1110;FFBD=1111;FFBE=1112;FFC2=1161;FFC3=1162;FFC4=1163;FFC5=1164;FFC6=1165;FFC7=1166;FF',\n 'CA=1167;FFCB=1168;FFCC=1169;FFCD=116A;FFCE=116B;FFCF=116C;FFD2=116D;FFD3=116E;FFD4=116F;',\n 'FFD5=1170;FFD6=1171;FFD7=1172;FFDA=1173;FFDB=1174;FFDC=1175;FFE0=A2;FFE1=A3;FFE2=AC;FFE3',\n '=20 304;FFE4=A6;FFE5=A5;FFE6=20A9;FFE8=2502;FFE9=2190;FFEA=2191;FFEB=2192;FFEC=2193;FFED',\n '=25A0;FFEE=25CB;105C9=105D2 307;105E4=105DA 307;10781=2D0;10782=2D1;10783=E6;10784=299;1',\n '0785=253;10787=2A3;10788=AB66;10789=2A5;1078A=2A4;1078B=256;1078C=257;1078D=1D91;1078E=2',\n '58;1078F=25E;10790=2A9;10791=264;10792=262;10793=260;10794=29B;10795=127;10796=29C;10797',\n '=267;10798=284;10799=2AA;1079A=2AB;1079B=26C;1079C=1DF04;1079D=A78E;1079E=26E;1079F=1DF0',\n '5;107A0=28E;107A1=1DF06;107A2=F8;107A3=276;107A4=277;107A5=71;107A6=27A;107A7=1DF08;107A',\n '8=27D;107A9=27E;107AA=280;107AB=2A8;107AC=2A6;107AD=AB67;107AE=2A7;107AF=288;107B0=2C71;',\n '107B2=28F;107B3=2A1;107B4=2A2;107B5=298;107B6=1C0;107B7=1C1;107B8=1C2;107B9=1DF0A;107BA=',\n '1DF1E;1109A=11099 110BA;1109C=1109B 110BA;110AB=110A5 110BA;1112E=11131 11127;1112F=1113',\n '2 11127;1134B=11347 1133E;1134C=11347 11357;11383=11382 113C9;11385=11384 113BB;1138E=11',\n '38B 113C2;11391=11390 113C9;113C5=113C2 113C2;113C7=113C2 113B8;113C8=113C2 113C9;114BB=',\n '114B9 114BA;114BC=114B9 114B0;114BE=114B9 114BD;115BA=115B8 115AF;115BB=115B9 115AF;1193',\n '8=11935 11930;16121=1611E 1611E;16122=1611E 16129;16123=1611E 1611F;16124=16129 1611F;16',\n '125=1611E 16120;16126=1611E 1611E 1611F;16127=1611E 16129 1611F;16128=1611E 1611E 16120;',\n '16D68=16D67 16D67;16D69=16D63 16D67;16D6A=16D63 16D67 16D67;1CCD6=41;1CCD7=42;1CCD8=43;1',\n 'CCD9=44;1CCDA=45;1CCDB=46;1CCDC=47;1CCDD=48;1CCDE=49;1CCDF=4A;1CCE0=4B;1CCE1=4C;1CCE2=4D',\n ';1CCE3=4E;1CCE4=4F;1CCE5=50;1CCE6=51;1CCE7=52;1CCE8=53;1CCE9=54;1CCEA=55;1CCEB=56;1CCEC=',\n '57;1CCED=58;1CCEE=59;1CCEF=5A;1CCF0=30;1CCF1=31;1CCF2=32;1CCF3=33;1CCF4=34;1CCF5=35;1CCF',\n '6=36;1CCF7=37;1CCF8=38;1CCF9=39;1D15E=1D157 1D165;1D15F=1D158 1D165;1D160=1D158 1D165 1D',\n '16E;1D161=1D158 1D165 1D16F;1D162=1D158 1D165 1D170;1D163=1D158 1D165 1D171;1D164=1D158 ',\n '1D165 1D172;1D1BB=1D1B9 1D165;1D1BC=1D1BA 1D165;1D1BD=1D1B9 1D165 1D16E;1D1BE=1D1BA 1D16',\n '5 1D16E;1D1BF=1D1B9 1D165 1D16F;1D1C0=1D1BA 1D165 1D16F;1D400=41;1D401=42;1D402=43;1D403',\n '=44;1D404=45;1D405=46;1D406=47;1D407=48;1D408=49;1D409=4A;1D40A=4B;1D40B=4C;1D40C=4D;1D4',\n '0D=4E;1D40E=4F;1D40F=50;1D410=51;1D411=52;1D412=53;1D413=54;1D414=55;1D415=56;1D416=57;1',\n 'D417=58;1D418=59;1D419=5A;1D41A=61;1D41B=62;1D41C=63;1D41D=64;1D41E=65;1D41F=66;1D420=67',\n ';1D421=68;1D422=69;1D423=6A;1D424=6B;1D425=6C;1D426=6D;1D427=6E;1D428=6F;1D429=70;1D42A=',\n '71;1D42B=72;1D42C=73;1D42D=74;1D42E=75;1D42F=76;1D430=77;1D431=78;1D432=79;1D433=7A;1D43',\n '4=41;1D435=42;1D436=43;1D437=44;1D438=45;1D439=46;1D43A=47;1D43B=48;1D43C=49;1D43D=4A;1D',\n '43E=4B;1D43F=4C;1D440=4D;1D441=4E;1D442=4F;1D443=50;1D444=51;1D445=52;1D446=53;1D447=54;',\n '1D448=55;1D449=56;1D44A=57;1D44B=58;1D44C=59;1D44D=5A;1D44E=61;1D44F=62;1D450=63;1D451=6',\n '4;1D452=65;1D453=66;1D454=67;1D456=69;1D457=6A;1D458=6B;1D459=6C;1D45A=6D;1D45B=6E;1D45C',\n '=6F;1D45D=70;1D45E=71;1D45F=72;1D460=73;1D461=74;1D462=75;1D463=76;1D464=77;1D465=78;1D4',\n '66=79;1D467=7A;1D468=41;1D469=42;1D46A=43;1D46B=44;1D46C=45;1D46D=46;1D46E=47;1D46F=48;1',\n 'D470=49;1D471=4A;1D472=4B;1D473=4C;1D474=4D;1D475=4E;1D476=4F;1D477=50;1D478=51;1D479=52',\n ';1D47A=53;1D47B=54;1D47C=55;1D47D=56;1D47E=57;1D47F=58;1D480=59;1D481=5A;1D482=61;1D483=',\n '62;1D484=63;1D485=64;1D486=65;1D487=66;1D488=67;1D489=68;1D48A=69;1D48B=6A;1D48C=6B;1D48',\n 'D=6C;1D48E=6D;1D48F=6E;1D490=6F;1D491=70;1D492=71;1D493=72;1D494=73;1D495=74;1D496=75;1D',\n '497=76;1D498=77;1D499=78;1D49A=79;1D49B=7A;1D49C=41;1D49E=43;1D49F=44;1D4A2=47;1D4A5=4A;',\n '1D4A6=4B;1D4A9=4E;1D4AA=4F;1D4AB=50;1D4AC=51;1D4AE=53;1D4AF=54;1D4B0=55;1D4B1=56;1D4B2=5',\n '7;1D4B3=58;1D4B4=59;1D4B5=5A;1D4B6=61;1D4B7=62;1D4B8=63;1D4B9=64;1D4BB=66;1D4BD=68;1D4BE',\n '=69;1D4BF=6A;1D4C0=6B;1D4C1=6C;1D4C2=6D;1D4C3=6E;1D4C5=70;1D4C6=71;1D4C7=72;1D4C8=73;1D4',\n 'C9=74;1D4CA=75;1D4CB=76;1D4CC=77;1D4CD=78;1D4CE=79;1D4CF=7A;1D4D0=41;1D4D1=42;1D4D2=43;1',\n 'D4D3=44;1D4D4=45;1D4D5=46;1D4D6=47;1D4D7=48;1D4D8=49;1D4D9=4A;1D4DA=4B;1D4DB=4C;1D4DC=4D',\n ';1D4DD=4E;1D4DE=4F;1D4DF=50;1D4E0=51;1D4E1=52;1D4E2=53;1D4E3=54;1D4E4=55;1D4E5=56;1D4E6=',\n '57;1D4E7=58;1D4E8=59;1D4E9=5A;1D4EA=61;1D4EB=62;1D4EC=63;1D4ED=64;1D4EE=65;1D4EF=66;1D4F',\n '0=67;1D4F1=68;1D4F2=69;1D4F3=6A;1D4F4=6B;1D4F5=6C;1D4F6=6D;1D4F7=6E;1D4F8=6F;1D4F9=70;1D',\n '4FA=71;1D4FB=72;1D4FC=73;1D4FD=74;1D4FE=75;1D4FF=76;1D500=77;1D501=78;1D502=79;1D503=7A;',\n '1D504=41;1D505=42;1D507=44;1D508=45;1D509=46;1D50A=47;1D50D=4A;1D50E=4B;1D50F=4C;1D510=4',\n 'D;1D511=4E;1D512=4F;1D513=50;1D514=51;1D516=53;1D517=54;1D518=55;1D519=56;1D51A=57;1D51B',\n '=58;1D51C=59;1D51E=61;1D51F=62;1D520=63;1D521=64;1D522=65;1D523=66;1D524=67;1D525=68;1D5',\n '26=69;1D527=6A;1D528=6B;1D529=6C;1D52A=6D;1D52B=6E;1D52C=6F;1D52D=70;1D52E=71;1D52F=72;1',\n 'D530=73;1D531=74;1D532=75;1D533=76;1D534=77;1D535=78;1D536=79;1D537=7A;1D538=41;1D539=42',\n ';1D53B=44;1D53C=45;1D53D=46;1D53E=47;1D540=49;1D541=4A;1D542=4B;1D543=4C;1D544=4D;1D546=',\n '4F;1D54A=53;1D54B=54;1D54C=55;1D54D=56;1D54E=57;1D54F=58;1D550=59;1D552=61;1D553=62;1D55',\n '4=63;1D555=64;1D556=65;1D557=66;1D558=67;1D559=68;1D55A=69;1D55B=6A;1D55C=6B;1D55D=6C;1D',\n '55E=6D;1D55F=6E;1D560=6F;1D561=70;1D562=71;1D563=72;1D564=73;1D565=74;1D566=75;1D567=76;',\n '1D568=77;1D569=78;1D56A=79;1D56B=7A;1D56C=41;1D56D=42;1D56E=43;1D56F=44;1D570=45;1D571=4',\n '6;1D572=47;1D573=48;1D574=49;1D575=4A;1D576=4B;1D577=4C;1D578=4D;1D579=4E;1D57A=4F;1D57B',\n '=50;1D57C=51;1D57D=52;1D57E=53;1D57F=54;1D580=55;1D581=56;1D582=57;1D583=58;1D584=59;1D5',\n '85=5A;1D586=61;1D587=62;1D588=63;1D589=64;1D58A=65;1D58B=66;1D58C=67;1D58D=68;1D58E=69;1',\n 'D58F=6A;1D590=6B;1D591=6C;1D592=6D;1D593=6E;1D594=6F;1D595=70;1D596=71;1D597=72;1D598=73',\n ';1D599=74;1D59A=75;1D59B=76;1D59C=77;1D59D=78;1D59E=79;1D59F=7A;1D5A0=41;1D5A1=42;1D5A2=',\n '43;1D5A3=44;1D5A4=45;1D5A5=46;1D5A6=47;1D5A7=48;1D5A8=49;1D5A9=4A;1D5AA=4B;1D5AB=4C;1D5A',\n 'C=4D;1D5AD=4E;1D5AE=4F;1D5AF=50;1D5B0=51;1D5B1=52;1D5B2=53;1D5B3=54;1D5B4=55;1D5B5=56;1D',\n '5B6=57;1D5B7=58;1D5B8=59;1D5B9=5A;1D5BA=61;1D5BB=62;1D5BC=63;1D5BD=64;1D5BE=65;1D5BF=66;',\n '1D5C0=67;1D5C1=68;1D5C2=69;1D5C3=6A;1D5C4=6B;1D5C5=6C;1D5C6=6D;1D5C7=6E;1D5C8=6F;1D5C9=7',\n '0;1D5CA=71;1D5CB=72;1D5CC=73;1D5CD=74;1D5CE=75;1D5CF=76;1D5D0=77;1D5D1=78;1D5D2=79;1D5D3',\n '=7A;1D5D4=41;1D5D5=42;1D5D6=43;1D5D7=44;1D5D8=45;1D5D9=46;1D5DA=47;1D5DB=48;1D5DC=49;1D5',\n 'DD=4A;1D5DE=4B;1D5DF=4C;1D5E0=4D;1D5E1=4E;1D5E2=4F;1D5E3=50;1D5E4=51;1D5E5=52;1D5E6=53;1',\n 'D5E7=54;1D5E8=55;1D5E9=56;1D5EA=57;1D5EB=58;1D5EC=59;1D5ED=5A;1D5EE=61;1D5EF=62;1D5F0=63',\n ';1D5F1=64;1D5F2=65;1D5F3=66;1D5F4=67;1D5F5=68;1D5F6=69;1D5F7=6A;1D5F8=6B;1D5F9=6C;1D5FA=',\n '6D;1D5FB=6E;1D5FC=6F;1D5FD=70;1D5FE=71;1D5FF=72;1D600=73;1D601=74;1D602=75;1D603=76;1D60',\n '4=77;1D605=78;1D606=79;1D607=7A;1D608=41;1D609=42;1D60A=43;1D60B=44;1D60C=45;1D60D=46;1D',\n '60E=47;1D60F=48;1D610=49;1D611=4A;1D612=4B;1D613=4C;1D614=4D;1D615=4E;1D616=4F;1D617=50;',\n '1D618=51;1D619=52;1D61A=53;1D61B=54;1D61C=55;1D61D=56;1D61E=57;1D61F=58;1D620=59;1D621=5',\n 'A;1D622=61;1D623=62;1D624=63;1D625=64;1D626=65;1D627=66;1D628=67;1D629=68;1D62A=69;1D62B',\n '=6A;1D62C=6B;1D62D=6C;1D62E=6D;1D62F=6E;1D630=6F;1D631=70;1D632=71;1D633=72;1D634=73;1D6',\n '35=74;1D636=75;1D637=76;1D638=77;1D639=78;1D63A=79;1D63B=7A;1D63C=41;1D63D=42;1D63E=43;1',\n 'D63F=44;1D640=45;1D641=46;1D642=47;1D643=48;1D644=49;1D645=4A;1D646=4B;1D647=4C;1D648=4D',\n ';1D649=4E;1D64A=4F;1D64B=50;1D64C=51;1D64D=52;1D64E=53;1D64F=54;1D650=55;1D651=56;1D652=',\n '57;1D653=58;1D654=59;1D655=5A;1D656=61;1D657=62;1D658=63;1D659=64;1D65A=65;1D65B=66;1D65',\n 'C=67;1D65D=68;1D65E=69;1D65F=6A;1D660=6B;1D661=6C;1D662=6D;1D663=6E;1D664=6F;1D665=70;1D',\n '666=71;1D667=72;1D668=73;1D669=74;1D66A=75;1D66B=76;1D66C=77;1D66D=78;1D66E=79;1D66F=7A;',\n '1D670=41;1D671=42;1D672=43;1D673=44;1D674=45;1D675=46;1D676=47;1D677=48;1D678=49;1D679=4',\n 'A;1D67A=4B;1D67B=4C;1D67C=4D;1D67D=4E;1D67E=4F;1D67F=50;1D680=51;1D681=52;1D682=53;1D683',\n '=54;1D684=55;1D685=56;1D686=57;1D687=58;1D688=59;1D689=5A;1D68A=61;1D68B=62;1D68C=63;1D6',\n '8D=64;1D68E=65;1D68F=66;1D690=67;1D691=68;1D692=69;1D693=6A;1D694=6B;1D695=6C;1D696=6D;1',\n 'D697=6E;1D698=6F;1D699=70;1D69A=71;1D69B=72;1D69C=73;1D69D=74;1D69E=75;1D69F=76;1D6A0=77',\n ';1D6A1=78;1D6A2=79;1D6A3=7A;1D6A4=131;1D6A5=237;1D6A8=391;1D6A9=392;1D6AA=393;1D6AB=394;',\n '1D6AC=395;1D6AD=396;1D6AE=397;1D6AF=398;1D6B0=399;1D6B1=39A;1D6B2=39B;1D6B3=39C;1D6B4=39',\n 'D;1D6B5=39E;1D6B6=39F;1D6B7=3A0;1D6B8=3A1;1D6B9=398;1D6BA=3A3;1D6BB=3A4;1D6BC=3A5;1D6BD=',\n '3A6;1D6BE=3A7;1D6BF=3A8;1D6C0=3A9;1D6C1=2207;1D6C2=3B1;1D6C3=3B2;1D6C4=3B3;1D6C5=3B4;1D6',\n 'C6=3B5;1D6C7=3B6;1D6C8=3B7;1D6C9=3B8;1D6CA=3B9;1D6CB=3BA;1D6CC=3BB;1D6CD=3BC;1D6CE=3BD;1',\n 'D6CF=3BE;1D6D0=3BF;1D6D1=3C0;1D6D2=3C1;1D6D3=3C2;1D6D4=3C3;1D6D5=3C4;1D6D6=3C5;1D6D7=3C6',\n ';1D6D8=3C7;1D6D9=3C8;1D6DA=3C9;1D6DB=2202;1D6DC=3B5;1D6DD=3B8;1D6DE=3BA;1D6DF=3C6;1D6E0=',\n '3C1;1D6E1=3C0;1D6E2=391;1D6E3=392;1D6E4=393;1D6E5=394;1D6E6=395;1D6E7=396;1D6E8=397;1D6E',\n '9=398;1D6EA=399;1D6EB=39A;1D6EC=39B;1D6ED=39C;1D6EE=39D;1D6EF=39E;1D6F0=39F;1D6F1=3A0;1D',\n '6F2=3A1;1D6F3=398;1D6F4=3A3;1D6F5=3A4;1D6F6=3A5;1D6F7=3A6;1D6F8=3A7;1D6F9=3A8;1D6FA=3A9;',\n '1D6FB=2207;1D6FC=3B1;1D6FD=3B2;1D6FE=3B3;1D6FF=3B4;1D700=3B5;1D701=3B6;1D702=3B7;1D703=3',\n 'B8;1D704=3B9;1D705=3BA;1D706=3BB;1D707=3BC;1D708=3BD;1D709=3BE;1D70A=3BF;1D70B=3C0;1D70C',\n '=3C1;1D70D=3C2;1D70E=3C3;1D70F=3C4;1D710=3C5;1D711=3C6;1D712=3C7;1D713=3C8;1D714=3C9;1D7',\n '15=2202;1D716=3B5;1D717=3B8;1D718=3BA;1D719=3C6;1D71A=3C1;1D71B=3C0;1D71C=391;1D71D=392;',\n '1D71E=393;1D71F=394;1D720=395;1D721=396;1D722=397;1D723=398;1D724=399;1D725=39A;1D726=39',\n 'B;1D727=39C;1D728=39D;1D729=39E;1D72A=39F;1D72B=3A0;1D72C=3A1;1D72D=398;1D72E=3A3;1D72F=',\n '3A4;1D730=3A5;1D731=3A6;1D732=3A7;1D733=3A8;1D734=3A9;1D735=2207;1D736=3B1;1D737=3B2;1D7',\n '38=3B3;1D739=3B4;1D73A=3B5;1D73B=3B6;1D73C=3B7;1D73D=3B8;1D73E=3B9;1D73F=3BA;1D740=3BB;1',\n 'D741=3BC;1D742=3BD;1D743=3BE;1D744=3BF;1D745=3C0;1D746=3C1;1D747=3C2;1D748=3C3;1D749=3C4',\n ';1D74A=3C5;1D74B=3C6;1D74C=3C7;1D74D=3C8;1D74E=3C9;1D74F=2202;1D750=3B5;1D751=3B8;1D752=',\n '3BA;1D753=3C6;1D754=3C1;1D755=3C0;1D756=391;1D757=392;1D758=393;1D759=394;1D75A=395;1D75',\n 'B=396;1D75C=397;1D75D=398;1D75E=399;1D75F=39A;1D760=39B;1D761=39C;1D762=39D;1D763=39E;1D',\n '764=39F;1D765=3A0;1D766=3A1;1D767=398;1D768=3A3;1D769=3A4;1D76A=3A5;1D76B=3A6;1D76C=3A7;',\n '1D76D=3A8;1D76E=3A9;1D76F=2207;1D770=3B1;1D771=3B2;1D772=3B3;1D773=3B4;1D774=3B5;1D775=3',\n 'B6;1D776=3B7;1D777=3B8;1D778=3B9;1D779=3BA;1D77A=3BB;1D77B=3BC;1D77C=3BD;1D77D=3BE;1D77E',\n '=3BF;1D77F=3C0;1D780=3C1;1D781=3C2;1D782=3C3;1D783=3C4;1D784=3C5;1D785=3C6;1D786=3C7;1D7',\n '87=3C8;1D788=3C9;1D789=2202;1D78A=3B5;1D78B=3B8;1D78C=3BA;1D78D=3C6;1D78E=3C1;1D78F=3C0;',\n '1D790=391;1D791=392;1D792=393;1D793=394;1D794=395;1D795=396;1D796=397;1D797=398;1D798=39',\n '9;1D799=39A;1D79A=39B;1D79B=39C;1D79C=39D;1D79D=39E;1D79E=39F;1D79F=3A0;1D7A0=3A1;1D7A1=',\n '398;1D7A2=3A3;1D7A3=3A4;1D7A4=3A5;1D7A5=3A6;1D7A6=3A7;1D7A7=3A8;1D7A8=3A9;1D7A9=2207;1D7',\n 'AA=3B1;1D7AB=3B2;1D7AC=3B3;1D7AD=3B4;1D7AE=3B5;1D7AF=3B6;1D7B0=3B7;1D7B1=3B8;1D7B2=3B9;1',\n 'D7B3=3BA;1D7B4=3BB;1D7B5=3BC;1D7B6=3BD;1D7B7=3BE;1D7B8=3BF;1D7B9=3C0;1D7BA=3C1;1D7BB=3C2',\n ';1D7BC=3C3;1D7BD=3C4;1D7BE=3C5;1D7BF=3C6;1D7C0=3C7;1D7C1=3C8;1D7C2=3C9;1D7C3=2202;1D7C4=',\n '3B5;1D7C5=3B8;1D7C6=3BA;1D7C7=3C6;1D7C8=3C1;1D7C9=3C0;1D7CA=3DC;1D7CB=3DD;1D7CE=30;1D7CF',\n '=31;1D7D0=32;1D7D1=33;1D7D2=34;1D7D3=35;1D7D4=36;1D7D5=37;1D7D6=38;1D7D7=39;1D7D8=30;1D7',\n 'D9=31;1D7DA=32;1D7DB=33;1D7DC=34;1D7DD=35;1D7DE=36;1D7DF=37;1D7E0=38;1D7E1=39;1D7E2=30;1',\n 'D7E3=31;1D7E4=32;1D7E5=33;1D7E6=34;1D7E7=35;1D7E8=36;1D7E9=37;1D7EA=38;1D7EB=39;1D7EC=30',\n ';1D7ED=31;1D7EE=32;1D7EF=33;1D7F0=34;1D7F1=35;1D7F2=36;1D7F3=37;1D7F4=38;1D7F5=39;1D7F6=',\n '30;1D7F7=31;1D7F8=32;1D7F9=33;1D7FA=34;1D7FB=35;1D7FC=36;1D7FD=37;1D7FE=38;1D7FF=39;1E03',\n '0=430;1E031=431;1E032=432;1E033=433;1E034=434;1E035=435;1E036=436;1E037=437;1E038=438;1E',\n '039=43A;1E03A=43B;1E03B=43C;1E03C=43E;1E03D=43F;1E03E=440;1E03F=441;1E040=442;1E041=443;',\n '1E042=444;1E043=445;1E044=446;1E045=447;1E046=448;1E047=44B;1E048=44D;1E049=44E;1E04A=A6',\n '89;1E04B=4D9;1E04C=456;1E04D=458;1E04E=4E9;1E04F=4AF;1E050=4CF;1E051=430;1E052=431;1E053',\n '=432;1E054=433;1E055=434;1E056=435;1E057=436;1E058=437;1E059=438;1E05A=43A;1E05B=43B;1E0',\n '5C=43E;1E05D=43F;1E05E=441;1E05F=443;1E060=444;1E061=445;1E062=446;1E063=447;1E064=448;1',\n 'E065=44A;1E066=44B;1E067=491;1E068=456;1E069=455;1E06A=45F;1E06B=4AB;1E06C=A651;1E06D=4B',\n '1;1EE00=627;1EE01=628;1EE02=62C;1EE03=62F;1EE05=648;1EE06=632;1EE07=62D;1EE08=637;1EE09=',\n '64A;1EE0A=643;1EE0B=644;1EE0C=645;1EE0D=646;1EE0E=633;1EE0F=639;1EE10=641;1EE11=635;1EE1',\n '2=642;1EE13=631;1EE14=634;1EE15=62A;1EE16=62B;1EE17=62E;1EE18=630;1EE19=636;1EE1A=638;1E',\n 'E1B=63A;1EE1C=66E;1EE1D=6BA;1EE1E=6A1;1EE1F=66F;1EE21=628;1EE22=62C;1EE24=647;1EE27=62D;',\n '1EE29=64A;1EE2A=643;1EE2B=644;1EE2C=645;1EE2D=646;1EE2E=633;1EE2F=639;1EE30=641;1EE31=63',\n '5;1EE32=642;1EE34=634;1EE35=62A;1EE36=62B;1EE37=62E;1EE39=636;1EE3B=63A;1EE42=62C;1EE47=',\n '62D;1EE49=64A;1EE4B=644;1EE4D=646;1EE4E=633;1EE4F=639;1EE51=635;1EE52=642;1EE54=634;1EE5',\n '7=62E;1EE59=636;1EE5B=63A;1EE5D=6BA;1EE5F=66F;1EE61=628;1EE62=62C;1EE64=647;1EE67=62D;1E',\n 'E68=637;1EE69=64A;1EE6A=643;1EE6C=645;1EE6D=646;1EE6E=633;1EE6F=639;1EE70=641;1EE71=635;',\n '1EE72=642;1EE74=634;1EE75=62A;1EE76=62B;1EE77=62E;1EE79=636;1EE7A=638;1EE7B=63A;1EE7C=66',\n 'E;1EE7E=6A1;1EE80=627;1EE81=628;1EE82=62C;1EE83=62F;1EE84=647;1EE85=648;1EE86=632;1EE87=',\n '62D;1EE88=637;1EE89=64A;1EE8B=644;1EE8C=645;1EE8D=646;1EE8E=633;1EE8F=639;1EE90=641;1EE9',\n '1=635;1EE92=642;1EE93=631;1EE94=634;1EE95=62A;1EE96=62B;1EE97=62E;1EE98=630;1EE99=636;1E',\n 'E9A=638;1EE9B=63A;1EEA1=628;1EEA2=62C;1EEA3=62F;1EEA5=648;1EEA6=632;1EEA7=62D;1EEA8=637;',\n '1EEA9=64A;1EEAB=644;1EEAC=645;1EEAD=646;1EEAE=633;1EEAF=639;1EEB0=641;1EEB1=635;1EEB2=64',\n '2;1EEB3=631;1EEB4=634;1EEB5=62A;1EEB6=62B;1EEB7=62E;1EEB8=630;1EEB9=636;1EEBA=638;1EEBB=',\n '63A;1F100=30 2E;1F101=30 2C;1F102=31 2C;1F103=32 2C;1F104=33 2C;1F105=34 2C;1F106=35 2C;',\n '1F107=36 2C;1F108=37 2C;1F109=38 2C;1F10A=39 2C;1F110=28 41 29;1F111=28 42 29;1F112=28 4',\n '3 29;1F113=28 44 29;1F114=28 45 29;1F115=28 46 29;1F116=28 47 29;1F117=28 48 29;1F118=28',\n ' 49 29;1F119=28 4A 29;1F11A=28 4B 29;1F11B=28 4C 29;1F11C=28 4D 29;1F11D=28 4E 29;1F11E=',\n '28 4F 29;1F11F=28 50 29;1F120=28 51 29;1F121=28 52 29;1F122=28 53 29;1F123=28 54 29;1F12',\n '4=28 55 29;1F125=28 56 29;1F126=28 57 29;1F127=28 58 29;1F128=28 59 29;1F129=28 5A 29;1F',\n '12A=3014 53 3015;1F12B=43;1F12C=52;1F12D=43 44;1F12E=57 5A;1F130=41;1F131=42;1F132=43;1F',\n '133=44;1F134=45;1F135=46;1F136=47;1F137=48;1F138=49;1F139=4A;1F13A=4B;1F13B=4C;1F13C=4D;',\n '1F13D=4E;1F13E=4F;1F13F=50;1F140=51;1F141=52;1F142=53;1F143=54;1F144=55;1F145=56;1F146=5',\n '7;1F147=58;1F148=59;1F149=5A;1F14A=48 56;1F14B=4D 56;1F14C=53 44;1F14D=53 53;1F14E=50 50',\n ' 56;1F14F=57 43;1F16A=4D 43;1F16B=4D 44;1F16C=4D 52;1F190=44 4A;1F200=307B 304B;1F201=30',\n 'B3 30B3;1F202=30B5;1F210=624B;1F211=5B57;1F212=53CC;1F213=30C6 3099;1F214=4E8C;1F215=591',\n 'A;1F216=89E3;1F217=5929;1F218=4EA4;1F219=6620;1F21A=7121;1F21B=6599;1F21C=524D;1F21D=5F8',\n 'C;1F21E=518D;1F21F=65B0;1F220=521D;1F221=7D42;1F222=751F;1F223=8CA9;1F224=58F0;1F225=543',\n '9;1F226=6F14;1F227=6295;1F228=6355;1F229=4E00;1F22A=4E09;1F22B=904A;1F22C=5DE6;1F22D=4E2',\n 'D;1F22E=53F3;1F22F=6307;1F230=8D70;1F231=6253;1F232=7981;1F233=7A7A;1F234=5408;1F235=6E8',\n '0;1F236=6709;1F237=6708;1F238=7533;1F239=5272;1F23A=55B6;1F23B=914D;1F240=3014 672C 3015',\n ';1F241=3014 4E09 3015;1F242=3014 4E8C 3015;1F243=3014 5B89 3015;1F244=3014 70B9 3015;1F2',\n '45=3014 6253 3015;1F246=3014 76D7 3015;1F247=3014 52DD 3015;1F248=3014 6557 3015;1F250=5',\n 'F97;1F251=53EF;1FBF0=30;1FBF1=31;1FBF2=32;1FBF3=33;1FBF4=34;1FBF5=35;1FBF6=36;1FBF7=37;1',\n 'FBF8=38;1FBF9=39;2F800=4E3D;2F801=4E38;2F802=4E41;2F803=20122;2F804=4F60;2F805=4FAE;2F80',\n '6=4FBB;2F807=5002;2F808=507A;2F809=5099;2F80A=50E7;2F80B=50CF;2F80C=349E;2F80D=2063A;2F8',\n '0E=514D;2F80F=5154;2F810=5164;2F811=5177;2F812=2051C;2F813=34B9;2F814=5167;2F815=518D;2F',\n '816=2054B;2F817=5197;2F818=51A4;2F819=4ECC;2F81A=51AC;2F81B=51B5;2F81C=291DF;2F81D=51F5;',\n '2F81E=5203;2F81F=34DF;2F820=523B;2F821=5246;2F822=5272;2F823=5277;2F824=3515;2F825=52C7;',\n '2F826=52C9;2F827=52E4;2F828=52FA;2F829=5305;2F82A=5306;2F82B=5317;2F82C=5349;2F82D=5351;',\n '2F82E=535A;2F82F=5373;2F830=537D;2F831=537F;2F832=537F;2F833=537F;2F834=20A2C;2F835=7070',\n ';2F836=53CA;2F837=53DF;2F838=20B63;2F839=53EB;2F83A=53F1;2F83B=5406;2F83C=549E;2F83D=543',\n '8;2F83E=5448;2F83F=5468;2F840=54A2;2F841=54F6;2F842=5510;2F843=5553;2F844=5563;2F845=558',\n '4;2F846=5584;2F847=5599;2F848=55AB;2F849=55B3;2F84A=55C2;2F84B=5716;2F84C=5606;2F84D=571',\n '7;2F84E=5651;2F84F=5674;2F850=5207;2F851=58EE;2F852=57CE;2F853=57F4;2F854=580D;2F855=578',\n 'B;2F856=5832;2F857=5831;2F858=58AC;2F859=214E4;2F85A=58F2;2F85B=58F7;2F85C=5906;2F85D=59',\n '1A;2F85E=5922;2F85F=5962;2F860=216A8;2F861=216EA;2F862=59EC;2F863=5A1B;2F864=5A27;2F865=',\n '59D8;2F866=5A66;2F867=36EE;2F868=36FC;2F869=5B08;2F86A=5B3E;2F86B=5B3E;2F86C=219C8;2F86D',\n '=5BC3;2F86E=5BD8;2F86F=5BE7;2F870=5BF3;2F871=21B18;2F872=5BFF;2F873=5C06;2F874=5F53;2F87',\n '5=5C22;2F876=3781;2F877=5C60;2F878=5C6E;2F879=5CC0;2F87A=5C8D;2F87B=21DE4;2F87C=5D43;2F8',\n '7D=21DE6;2F87E=5D6E;2F87F=5D6B;2F880=5D7C;2F881=5DE1;2F882=5DE2;2F883=382F;2F884=5DFD;2F',\n '885=5E28;2F886=5E3D;2F887=5E69;2F888=3862;2F889=22183;2F88A=387C;2F88B=5EB0;2F88C=5EB3;2',\n 'F88D=5EB6;2F88E=5ECA;2F88F=2A392;2F890=5EFE;2F891=22331;2F892=22331;2F893=8201;2F894=5F2',\n '2;2F895=5F22;2F896=38C7;2F897=232B8;2F898=261DA;2F899=5F62;2F89A=5F6B;2F89B=38E3;2F89C=5',\n 'F9A;2F89D=5FCD;2F89E=5FD7;2F89F=5FF9;2F8A0=6081;2F8A1=393A;2F8A2=391C;2F8A3=6094;2F8A4=2',\n '26D4;2F8A5=60C7;2F8A6=6148;2F8A7=614C;2F8A8=614E;2F8A9=614C;2F8AA=617A;2F8AB=618E;2F8AC=',\n '61B2;2F8AD=61A4;2F8AE=61AF;2F8AF=61DE;2F8B0=61F2;2F8B1=61F6;2F8B2=6210;2F8B3=621B;2F8B4=',\n '625D;2F8B5=62B1;2F8B6=62D4;2F8B7=6350;2F8B8=22B0C;2F8B9=633D;2F8BA=62FC;2F8BB=6368;2F8BC',\n '=6383;2F8BD=63E4;2F8BE=22BF1;2F8BF=6422;2F8C0=63C5;2F8C1=63A9;2F8C2=3A2E;2F8C3=6469;2F8C',\n '4=647E;2F8C5=649D;2F8C6=6477;2F8C7=3A6C;2F8C8=654F;2F8C9=656C;2F8CA=2300A;2F8CB=65E3;2F8',\n 'CC=66F8;2F8CD=6649;2F8CE=3B19;2F8CF=6691;2F8D0=3B08;2F8D1=3AE4;2F8D2=5192;2F8D3=5195;2F8',\n 'D4=6700;2F8D5=669C;2F8D6=80AD;2F8D7=43D9;2F8D8=6717;2F8D9=671B;2F8DA=6721;2F8DB=675E;2F8',\n 'DC=6753;2F8DD=233C3;2F8DE=3B49;2F8DF=67FA;2F8E0=6785;2F8E1=6852;2F8E2=6885;2F8E3=2346D;2',\n 'F8E4=688E;2F8E5=681F;2F8E6=6914;2F8E7=3B9D;2F8E8=6942;2F8E9=69A3;2F8EA=69EA;2F8EB=6AA8;2',\n 'F8EC=236A3;2F8ED=6ADB;2F8EE=3C18;2F8EF=6B21;2F8F0=238A7;2F8F1=6B54;2F8F2=3C4E;2F8F3=6B72',\n ';2F8F4=6B9F;2F8F5=6BBA;2F8F6=6BBB;2F8F7=23A8D;2F8F8=21D0B;2F8F9=23AFA;2F8FA=6C4E;2F8FB=2',\n '3CBC;2F8FC=6CBF;2F8FD=6CCD;2F8FE=6C67;2F8FF=6D16;2F900=6D3E;2F901=6D77;2F902=6D41;2F903=',\n '6D69;2F904=6D78;2F905=6D85;2F906=23D1E;2F907=6D34;2F908=6E2F;2F909=6E6E;2F90A=3D33;2F90B',\n '=6ECB;2F90C=6EC7;2F90D=23ED1;2F90E=6DF9;2F90F=6F6E;2F910=23F5E;2F911=23F8E;2F912=6FC6;2F',\n '913=7039;2F914=701E;2F915=701B;2F916=3D96;2F917=704A;2F918=707D;2F919=7077;2F91A=70AD;2F',\n '91B=20525;2F91C=7145;2F91D=24263;2F91E=719C;2F91F=243AB;2F920=7228;2F921=7235;2F922=7250',\n ';2F923=24608;2F924=7280;2F925=7295;2F926=24735;2F927=24814;2F928=737A;2F929=738B;2F92A=3',\n 'EAC;2F92B=73A5;2F92C=3EB8;2F92D=3EB8;2F92E=7447;2F92F=745C;2F930=7471;2F931=7485;2F932=7',\n '4CA;2F933=3F1B;2F934=7524;2F935=24C36;2F936=753E;2F937=24C92;2F938=7570;2F939=2219F;2F93',\n 'A=7610;2F93B=24FA1;2F93C=24FB8;2F93D=25044;2F93E=3FFC;2F93F=4008;2F940=76F4;2F941=250F3;',\n '2F942=250F2;2F943=25119;2F944=25133;2F945=771E;2F946=771F;2F947=771F;2F948=774A;2F949=40',\n '39;2F94A=778B;2F94B=4046;2F94C=4096;2F94D=2541D;2F94E=784E;2F94F=788C;2F950=78CC;2F951=4',\n '0E3;2F952=25626;2F953=7956;2F954=2569A;2F955=256C5;2F956=798F;2F957=79EB;2F958=412F;2F95',\n '9=7A40;2F95A=7A4A;2F95B=7A4F;2F95C=2597C;2F95D=25AA7;2F95E=25AA7;2F95F=7AEE;2F960=4202;2',\n 'F961=25BAB;2F962=7BC6;2F963=7BC9;2F964=4227;2F965=25C80;2F966=7CD2;2F967=42A0;2F968=7CE8',\n ';2F969=7CE3;2F96A=7D00;2F96B=25F86;2F96C=7D63;2F96D=4301;2F96E=7DC7;2F96F=7E02;2F970=7E4',\n '5;2F971=4334;2F972=26228;2F973=26247;2F974=4359;2F975=262D9;2F976=7F7A;2F977=2633E;2F978',\n '=7F95;2F979=7FFA;2F97A=8005;2F97B=264DA;2F97C=26523;2F97D=8060;2F97E=265A8;2F97F=8070;2F',\n '980=2335F;2F981=43D5;2F982=80B2;2F983=8103;2F984=440B;2F985=813E;2F986=5AB5;2F987=267A7;',\n '2F988=267B5;2F989=23393;2F98A=2339C;2F98B=8201;2F98C=8204;2F98D=8F9E;2F98E=446B;2F98F=82',\n '91;2F990=828B;2F991=829D;2F992=52B3;2F993=82B1;2F994=82B3;2F995=82BD;2F996=82E6;2F997=26',\n 'B3C;2F998=82E5;2F999=831D;2F99A=8363;2F99B=83AD;2F99C=8323;2F99D=83BD;2F99E=83E7;2F99F=8',\n '457;2F9A0=8353;2F9A1=83CA;2F9A2=83CC;2F9A3=83DC;2F9A4=26C36;2F9A5=26D6B;2F9A6=26CD5;2F9A',\n '7=452B;2F9A8=84F1;2F9A9=84F3;2F9AA=8516;2F9AB=273CA;2F9AC=8564;2F9AD=26F2C;2F9AE=455D;2F',\n '9AF=4561;2F9B0=26FB1;2F9B1=270D2;2F9B2=456B;2F9B3=8650;2F9B4=865C;2F9B5=8667;2F9B6=8669;',\n '2F9B7=86A9;2F9B8=8688;2F9B9=870E;2F9BA=86E2;2F9BB=8779;2F9BC=8728;2F9BD=876B;2F9BE=8786;',\n '2F9BF=45D7;2F9C0=87E1;2F9C1=8801;2F9C2=45F9;2F9C3=8860;2F9C4=8863;2F9C5=27667;2F9C6=88D7',\n ';2F9C7=88DE;2F9C8=4635;2F9C9=88FA;2F9CA=34BB;2F9CB=278AE;2F9CC=27966;2F9CD=46BE;2F9CE=46',\n 'C7;2F9CF=8AA0;2F9D0=8AED;2F9D1=8B8A;2F9D2=8C55;2F9D3=27CA8;2F9D4=8CAB;2F9D5=8CC1;2F9D6=8',\n 'D1B;2F9D7=8D77;2F9D8=27F2F;2F9D9=20804;2F9DA=8DCB;2F9DB=8DBC;2F9DC=8DF0;2F9DD=208DE;2F9D',\n 'E=8ED4;2F9DF=8F38;2F9E0=285D2;2F9E1=285ED;2F9E2=9094;2F9E3=90F1;2F9E4=9111;2F9E5=2872E;2',\n 'F9E6=911B;2F9E7=9238;2F9E8=92D7;2F9E9=92D8;2F9EA=927C;2F9EB=93F9;2F9EC=9415;2F9ED=28BFA;',\n '2F9EE=958B;2F9EF=4995;2F9F0=95B7;2F9F1=28D77;2F9F2=49E6;2F9F3=96C3;2F9F4=5DB2;2F9F5=9723',\n ';2F9F6=29145;2F9F7=2921A;2F9F8=4A6E;2F9F9=4A76;2F9FA=97E0;2F9FB=2940A;2F9FC=4AB2;2F9FD=2',\n '9496;2F9FE=980B;2F9FF=980B;2FA00=9829;2FA01=295B6;2FA02=98E2;2FA03=4B33;2FA04=9929;2FA05',\n '=99A7;2FA06=99C2;2FA07=99FE;2FA08=4BCE;2FA09=29B30;2FA0A=9B12;2FA0B=9C40;2FA0C=9CFD;2FA0',\n 'D=4CCE;2FA0E=4CED;2FA0F=9D67;2FA10=2A0CE;2FA11=4CF8;2FA12=2A105;2FA13=2A20E;2FA14=2A291;',\n '2FA15=9EBB;2FA16=4D56;2FA17=9EF9;2FA18=9EFE;2FA19=9F05;2FA1A=9F0F;2FA1B=9F16;2FA1C=9F3B;',\n '2FA1D=2A600',\n].join('');\n\n// Nonzero canonical combining classes.\n// Entry: <cp>:<ccc> or <first>-<last>:<ccc>; uppercase hex; sorted, ';'-joined.\nexport const NFKC16_CCC_PACKED: string = [\n '300-314:E6;315:E8;316-319:DC;31A:E8;31B:D8;31C-320:DC;321-322:CA;323-326:DC;327-328:CA;3',\n '29-333:DC;334-338:1;339-33C:DC;33D-344:E6;345:F0;346:E6;347-349:DC;34A-34C:E6;34D-34E:DC',\n ';350-352:E6;353-356:DC;357:E6;358:E8;359-35A:DC;35B:E6;35C:E9;35D-35E:EA;35F:E9;360-361:',\n 'EA;362:E9;363-36F:E6;483-487:E6;591:DC;592-595:E6;596:DC;597-599:E6;59A:DE;59B:DC;59C-5A',\n '1:E6;5A2-5A7:DC;5A8-5A9:E6;5AA:DC;5AB-5AC:E6;5AD:DE;5AE:E4;5AF:E6;5B0:A;5B1:B;5B2:C;5B3:',\n 'D;5B4:E;5B5:F;5B6:10;5B7:11;5B8:12;5B9-5BA:13;5BB:14;5BC:15;5BD:16;5BF:17;5C1:18;5C2:19;',\n '5C4:E6;5C5:DC;5C7:12;610-617:E6;618:1E;619:1F;61A:20;64B:1B;64C:1C;64D:1D;64E:1E;64F:1F;',\n '650:20;651:21;652:22;653-654:E6;655-656:DC;657-65B:E6;65C:DC;65D-65E:E6;65F:DC;670:23;6D',\n '6-6DC:E6;6DF-6E2:E6;6E3:DC;6E4:E6;6E7-6E8:E6;6EA:DC;6EB-6EC:E6;6ED:DC;711:24;730:E6;731:',\n 'DC;732-733:E6;734:DC;735-736:E6;737-739:DC;73A:E6;73B-73C:DC;73D:E6;73E:DC;73F-741:E6;74',\n '2:DC;743:E6;744:DC;745:E6;746:DC;747:E6;748:DC;749-74A:E6;7EB-7F1:E6;7F2:DC;7F3:E6;7FD:D',\n 'C;816-819:E6;81B-823:E6;825-827:E6;829-82D:E6;859-85B:DC;897-898:E6;899-89B:DC;89C-89F:E',\n '6;8CA-8CE:E6;8CF-8D3:DC;8D4-8E1:E6;8E3:DC;8E4-8E5:E6;8E6:DC;8E7-8E8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DFE:E6;1DFF:DC;20D0-20D1:E6;20D',\n '2-20D3:1;20D4-20D7:E6;20D8-20DA:1;20DB-20DC:E6;20E1:E6;20E5-20E6:1;20E7:E6;20E8:DC;20E9:',\n 'E6;20EA-20EB:1;20EC-20EF:DC;20F0:E6;2CEF-2CF1:E6;2D7F:9;2DE0-2DFF:E6;302A:DA;302B:E4;302',\n 'C:E8;302D:DE;302E-302F:E0;3099-309A:8;A66F:E6;A674-A67D:E6;A69E-A69F:E6;A6F0-A6F1:E6;A80',\n '6:9;A82C:9;A8C4:9;A8E0-A8F1:E6;A92B-A92D:DC;A953:9;A9B3:7;A9C0:9;AAB0:E6;AAB2-AAB3:E6;AA',\n 'B4:DC;AAB7-AAB8:E6;AABE-AABF:E6;AAC1:E6;AAF6:9;ABED:9;FB1E:1A;FE20-FE26:E6;FE27-FE2D:DC;',\n 'FE2E-FE2F:E6;101FD:DC;102E0:DC;10376-1037A:E6;10A0D:DC;10A0F:E6;10A38:E6;10A39:1;10A3A:D',\n 'C;10A3F:9;10AE5:E6;10AE6:DC;10D24-10D27:E6;10D69-10D6D:E6;10EAB-10EAC:E6;10EFD-10EFF:DC;',\n '10F46-10F47:DC;10F48-10F4A:E6;10F4B:DC;10F4C:E6;10F4D-10F50:DC;10F82:E6;10F83:DC;10F84:E',\n '6;10F85:DC;11046:9;11070:9;1107F:9;110B9:9;110BA:7;11100-11102:E6;11133-11134:9;11173:7;',\n '111C0:9;111CA:7;11235:9;11236:7;112E9:7;112EA:9;1133B-1133C:7;1134D:9;11366-1136C:E6;113',\n '70-11374:E6;113CE-113D0:9;11442:9;11446:7;1145E:E6;114C2:9;114C3:7;115BF:9;115C0:7;1163F',\n ':9;116B6:9;116B7:7;1172B:9;11839:9;1183A:7;1193D-1193E:9;11943:7;119E0:9;11A34:9;11A47:9',\n ';11A99:9;11C3F:9;11D42:7;11D44-11D45:9;11D97:9;11F41-11F42:9;1612F:9;16AF0-16AF4:1;16B30',\n '-16B36:E6;16FF0-16FF1:6;1BC9E:1;1D165-1D166:D8;1D167-1D169:1;1D16D:E2;1D16E-1D172:D8;1D1',\n '7B-1D182:DC;1D185-1D189:E6;1D18A-1D18B:DC;1D1AA-1D1AD:E6;1D242-1D244:E6;1E000-1E006:E6;1',\n 'E008-1E018:E6;1E01B-1E021:E6;1E023-1E024:E6;1E026-1E02A:E6;1E08F:E6;1E130-1E136:E6;1E2AE',\n ':E6;1E2EC-1E2EF:E6;1E4EC-1E4ED:E8;1E4EE:DC;1E4EF:E6;1E5EE:E6;1E5EF:DC;1E8D0-1E8D6:DC;1E9',\n '44-1E949:E6;1E94A:7',\n].join('');\n\n// Primary composite pairs (UAX #15 exclusions applied), Hangul excluded.\n// Entry: <starter> <combining>=<composite>; uppercase hex; sorted, ';'-joined.\nexport const NFKC16_COMPOSITION_PACKED: string = [\n '3C 338=226E;3D 338=2260;3E 338=226F;41 300=C0;41 301=C1;41 302=C2;41 303=C3;41 304=100;4',\n '1 306=102;41 307=226;41 308=C4;41 309=1EA2;41 30A=C5;41 30C=1CD;41 30F=200;41 311=202;41',\n ' 323=1EA0;41 325=1E00;41 328=104;42 307=1E02;42 323=1E04;42 331=1E06;43 301=106;43 302=1',\n '08;43 307=10A;43 30C=10C;43 327=C7;44 307=1E0A;44 30C=10E;44 323=1E0C;44 327=1E10;44 32D',\n '=1E12;44 331=1E0E;45 300=C8;45 301=C9;45 302=CA;45 303=1EBC;45 304=112;45 306=114;45 307',\n '=116;45 308=CB;45 309=1EBA;45 30C=11A;45 30F=204;45 311=206;45 323=1EB8;45 327=228;45 32',\n '8=118;45 32D=1E18;45 330=1E1A;46 307=1E1E;47 301=1F4;47 302=11C;47 304=1E20;47 306=11E;4',\n '7 307=120;47 30C=1E6;47 327=122;48 302=124;48 307=1E22;48 308=1E26;48 30C=21E;48 323=1E2',\n '4;48 327=1E28;48 32E=1E2A;49 300=CC;49 301=CD;49 302=CE;49 303=128;49 304=12A;49 306=12C',\n ';49 307=130;49 308=CF;49 309=1EC8;49 30C=1CF;49 30F=208;49 311=20A;49 323=1ECA;49 328=12',\n 'E;49 330=1E2C;4A 302=134;4B 301=1E30;4B 30C=1E8;4B 323=1E32;4B 327=136;4B 331=1E34;4C 30',\n '1=139;4C 30C=13D;4C 323=1E36;4C 327=13B;4C 32D=1E3C;4C 331=1E3A;4D 301=1E3E;4D 307=1E40;',\n '4D 323=1E42;4E 300=1F8;4E 301=143;4E 303=D1;4E 307=1E44;4E 30C=147;4E 323=1E46;4E 327=14',\n '5;4E 32D=1E4A;4E 331=1E48;4F 300=D2;4F 301=D3;4F 302=D4;4F 303=D5;4F 304=14C;4F 306=14E;',\n '4F 307=22E;4F 308=D6;4F 309=1ECE;4F 30B=150;4F 30C=1D1;4F 30F=20C;4F 311=20E;4F 31B=1A0;',\n '4F 323=1ECC;4F 328=1EA;50 301=1E54;50 307=1E56;52 301=154;52 307=1E58;52 30C=158;52 30F=',\n '210;52 311=212;52 323=1E5A;52 327=156;52 331=1E5E;53 301=15A;53 302=15C;53 307=1E60;53 3',\n '0C=160;53 323=1E62;53 326=218;53 327=15E;54 307=1E6A;54 30C=164;54 323=1E6C;54 326=21A;5',\n '4 327=162;54 32D=1E70;54 331=1E6E;55 300=D9;55 301=DA;55 302=DB;55 303=168;55 304=16A;55',\n ' 306=16C;55 308=DC;55 309=1EE6;55 30A=16E;55 30B=170;55 30C=1D3;55 30F=214;55 311=216;55',\n ' 31B=1AF;55 323=1EE4;55 324=1E72;55 328=172;55 32D=1E76;55 330=1E74;56 303=1E7C;56 323=1',\n 'E7E;57 300=1E80;57 301=1E82;57 302=174;57 307=1E86;57 308=1E84;57 323=1E88;58 307=1E8A;5',\n '8 308=1E8C;59 300=1EF2;59 301=DD;59 302=176;59 303=1EF8;59 304=232;59 307=1E8E;59 308=17',\n '8;59 309=1EF6;59 323=1EF4;5A 301=179;5A 302=1E90;5A 307=17B;5A 30C=17D;5A 323=1E92;5A 33',\n '1=1E94;61 300=E0;61 301=E1;61 302=E2;61 303=E3;61 304=101;61 306=103;61 307=227;61 308=E',\n '4;61 309=1EA3;61 30A=E5;61 30C=1CE;61 30F=201;61 311=203;61 323=1EA1;61 325=1E01;61 328=',\n '105;62 307=1E03;62 323=1E05;62 331=1E07;63 301=107;63 302=109;63 307=10B;63 30C=10D;63 3',\n '27=E7;64 307=1E0B;64 30C=10F;64 323=1E0D;64 327=1E11;64 32D=1E13;64 331=1E0F;65 300=E8;6',\n '5 301=E9;65 302=EA;65 303=1EBD;65 304=113;65 306=115;65 307=117;65 308=EB;65 309=1EBB;65',\n ' 30C=11B;65 30F=205;65 311=207;65 323=1EB9;65 327=229;65 328=119;65 32D=1E19;65 330=1E1B',\n ';66 307=1E1F;67 301=1F5;67 302=11D;67 304=1E21;67 306=11F;67 307=121;67 30C=1E7;67 327=1',\n '23;68 302=125;68 307=1E23;68 308=1E27;68 30C=21F;68 323=1E25;68 327=1E29;68 32E=1E2B;68 ',\n '331=1E96;69 300=EC;69 301=ED;69 302=EE;69 303=129;69 304=12B;69 306=12D;69 308=EF;69 309',\n '=1EC9;69 30C=1D0;69 30F=209;69 311=20B;69 323=1ECB;69 328=12F;69 330=1E2D;6A 302=135;6A ',\n '30C=1F0;6B 301=1E31;6B 30C=1E9;6B 323=1E33;6B 327=137;6B 331=1E35;6C 301=13A;6C 30C=13E;',\n '6C 323=1E37;6C 327=13C;6C 32D=1E3D;6C 331=1E3B;6D 301=1E3F;6D 307=1E41;6D 323=1E43;6E 30',\n '0=1F9;6E 301=144;6E 303=F1;6E 307=1E45;6E 30C=148;6E 323=1E47;6E 327=146;6E 32D=1E4B;6E ',\n '331=1E49;6F 300=F2;6F 301=F3;6F 302=F4;6F 303=F5;6F 304=14D;6F 306=14F;6F 307=22F;6F 308',\n '=F6;6F 309=1ECF;6F 30B=151;6F 30C=1D2;6F 30F=20D;6F 311=20F;6F 31B=1A1;6F 323=1ECD;6F 32',\n '8=1EB;70 301=1E55;70 307=1E57;72 301=155;72 307=1E59;72 30C=159;72 30F=211;72 311=213;72',\n ' 323=1E5B;72 327=157;72 331=1E5F;73 301=15B;73 302=15D;73 307=1E61;73 30C=161;73 323=1E6',\n '3;73 326=219;73 327=15F;74 307=1E6B;74 308=1E97;74 30C=165;74 323=1E6D;74 326=21B;74 327',\n '=163;74 32D=1E71;74 331=1E6F;75 300=F9;75 301=FA;75 302=FB;75 303=169;75 304=16B;75 306=',\n '16D;75 308=FC;75 309=1EE7;75 30A=16F;75 30B=171;75 30C=1D4;75 30F=215;75 311=217;75 31B=',\n '1B0;75 323=1EE5;75 324=1E73;75 328=173;75 32D=1E77;75 330=1E75;76 303=1E7D;76 323=1E7F;7',\n '7 300=1E81;77 301=1E83;77 302=175;77 307=1E87;77 308=1E85;77 30A=1E98;77 323=1E89;78 307',\n '=1E8B;78 308=1E8D;79 300=1EF3;79 301=FD;79 302=177;79 303=1EF9;79 304=233;79 307=1E8F;79',\n ' 308=FF;79 309=1EF7;79 30A=1E99;79 323=1EF5;7A 301=17A;7A 302=1E91;7A 307=17C;7A 30C=17E',\n ';7A 323=1E93;7A 331=1E95;A8 300=1FED;A8 301=385;A8 342=1FC1;C2 300=1EA6;C2 301=1EA4;C2 3',\n '03=1EAA;C2 309=1EA8;C4 304=1DE;C5 301=1FA;C6 301=1FC;C6 304=1E2;C7 301=1E08;CA 300=1EC0;',\n 'CA 301=1EBE;CA 303=1EC4;CA 309=1EC2;CF 301=1E2E;D4 300=1ED2;D4 301=1ED0;D4 303=1ED6;D4 3',\n '09=1ED4;D5 301=1E4C;D5 304=22C;D5 308=1E4E;D6 304=22A;D8 301=1FE;DC 300=1DB;DC 301=1D7;D',\n 'C 304=1D5;DC 30C=1D9;E2 300=1EA7;E2 301=1EA5;E2 303=1EAB;E2 309=1EA9;E4 304=1DF;E5 301=1',\n 'FB;E6 301=1FD;E6 304=1E3;E7 301=1E09;EA 300=1EC1;EA 301=1EBF;EA 303=1EC5;EA 309=1EC3;EF ',\n '301=1E2F;F4 300=1ED3;F4 301=1ED1;F4 303=1ED7;F4 309=1ED5;F5 301=1E4D;F5 304=22D;F5 308=1',\n 'E4F;F6 304=22B;F8 301=1FF;FC 300=1DC;FC 301=1D8;FC 304=1D6;FC 30C=1DA;102 300=1EB0;102 3',\n '01=1EAE;102 303=1EB4;102 309=1EB2;103 300=1EB1;103 301=1EAF;103 303=1EB5;103 309=1EB3;11',\n '2 300=1E14;112 301=1E16;113 300=1E15;113 301=1E17;14C 300=1E50;14C 301=1E52;14D 300=1E51',\n ';14D 301=1E53;15A 307=1E64;15B 307=1E65;160 307=1E66;161 307=1E67;168 301=1E78;169 301=1',\n 'E79;16A 308=1E7A;16B 308=1E7B;17F 307=1E9B;1A0 300=1EDC;1A0 301=1EDA;1A0 303=1EE0;1A0 30',\n '9=1EDE;1A0 323=1EE2;1A1 300=1EDD;1A1 301=1EDB;1A1 303=1EE1;1A1 309=1EDF;1A1 323=1EE3;1AF',\n ' 300=1EEA;1AF 301=1EE8;1AF 303=1EEE;1AF 309=1EEC;1AF 323=1EF0;1B0 300=1EEB;1B0 301=1EE9;',\n '1B0 303=1EEF;1B0 309=1EED;1B0 323=1EF1;1B7 30C=1EE;1EA 304=1EC;1EB 304=1ED;226 304=1E0;2',\n '27 304=1E1;228 306=1E1C;229 306=1E1D;22E 304=230;22F 304=231;292 30C=1EF;391 300=1FBA;39',\n '1 301=386;391 304=1FB9;391 306=1FB8;391 313=1F08;391 314=1F09;391 345=1FBC;395 300=1FC8;',\n '395 301=388;395 313=1F18;395 314=1F19;397 300=1FCA;397 301=389;397 313=1F28;397 314=1F29',\n ';397 345=1FCC;399 300=1FDA;399 301=38A;399 304=1FD9;399 306=1FD8;399 308=3AA;399 313=1F3',\n '8;399 314=1F39;39F 300=1FF8;39F 301=38C;39F 313=1F48;39F 314=1F49;3A1 314=1FEC;3A5 300=1',\n 'FEA;3A5 301=38E;3A5 304=1FE9;3A5 306=1FE8;3A5 308=3AB;3A5 314=1F59;3A9 300=1FFA;3A9 301=',\n '38F;3A9 313=1F68;3A9 314=1F69;3A9 345=1FFC;3AC 345=1FB4;3AE 345=1FC4;3B1 300=1F70;3B1 30',\n '1=3AC;3B1 304=1FB1;3B1 306=1FB0;3B1 313=1F00;3B1 314=1F01;3B1 342=1FB6;3B1 345=1FB3;3B5 ',\n '300=1F72;3B5 301=3AD;3B5 313=1F10;3B5 314=1F11;3B7 300=1F74;3B7 301=3AE;3B7 313=1F20;3B7',\n ' 314=1F21;3B7 342=1FC6;3B7 345=1FC3;3B9 300=1F76;3B9 301=3AF;3B9 304=1FD1;3B9 306=1FD0;3',\n 'B9 308=3CA;3B9 313=1F30;3B9 314=1F31;3B9 342=1FD6;3BF 300=1F78;3BF 301=3CC;3BF 313=1F40;',\n '3BF 314=1F41;3C1 313=1FE4;3C1 314=1FE5;3C5 300=1F7A;3C5 301=3CD;3C5 304=1FE1;3C5 306=1FE',\n '0;3C5 308=3CB;3C5 313=1F50;3C5 314=1F51;3C5 342=1FE6;3C9 300=1F7C;3C9 301=3CE;3C9 313=1F',\n '60;3C9 314=1F61;3C9 342=1FF6;3C9 345=1FF3;3CA 300=1FD2;3CA 301=390;3CA 342=1FD7;3CB 300=',\n '1FE2;3CB 301=3B0;3CB 342=1FE7;3CE 345=1FF4;3D2 301=3D3;3D2 308=3D4;406 308=407;410 306=4',\n 'D0;410 308=4D2;413 301=403;415 300=400;415 306=4D6;415 308=401;416 306=4C1;416 308=4DC;4',\n '17 308=4DE;418 300=40D;418 304=4E2;418 306=419;418 308=4E4;41A 301=40C;41E 308=4E6;423 3',\n '04=4EE;423 306=40E;423 308=4F0;423 30B=4F2;427 308=4F4;42B 308=4F8;42D 308=4EC;430 306=4',\n 'D1;430 308=4D3;433 301=453;435 300=450;435 306=4D7;435 308=451;436 306=4C2;436 308=4DD;4',\n '37 308=4DF;438 300=45D;438 304=4E3;438 306=439;438 308=4E5;43A 301=45C;43E 308=4E7;443 3',\n '04=4EF;443 306=45E;443 308=4F1;443 30B=4F3;447 308=4F5;44B 308=4F9;44D 308=4ED;456 308=4',\n '57;474 30F=476;475 30F=477;4D8 308=4DA;4D9 308=4DB;4E8 308=4EA;4E9 308=4EB;627 653=622;6',\n '27 654=623;627 655=625;648 654=624;64A 654=626;6C1 654=6C2;6D2 654=6D3;6D5 654=6C0;928 9',\n '3C=929;930 93C=931;933 93C=934;9C7 9BE=9CB;9C7 9D7=9CC;B47 B3E=B4B;B47 B56=B48;B47 B57=B',\n '4C;B92 BD7=B94;BC6 BBE=BCA;BC6 BD7=BCC;BC7 BBE=BCB;C46 C56=C48;CBF CD5=CC0;CC6 CC2=CCA;C',\n 'C6 CD5=CC7;CC6 CD6=CC8;CCA CD5=CCB;D46 D3E=D4A;D46 D57=D4C;D47 D3E=D4B;DD9 DCA=DDA;DD9 D',\n 'CF=DDC;DD9 DDF=DDE;DDC DCA=DDD;1025 102E=1026;1B05 1B35=1B06;1B07 1B35=1B08;1B09 1B35=1B',\n '0A;1B0B 1B35=1B0C;1B0D 1B35=1B0E;1B11 1B35=1B12;1B3A 1B35=1B3B;1B3C 1B35=1B3D;1B3E 1B35=',\n '1B40;1B3F 1B35=1B41;1B42 1B35=1B43;1E36 304=1E38;1E37 304=1E39;1E5A 304=1E5C;1E5B 304=1E',\n '5D;1E62 307=1E68;1E63 307=1E69;1EA0 302=1EAC;1EA0 306=1EB6;1EA1 302=1EAD;1EA1 306=1EB7;1',\n 'EB8 302=1EC6;1EB9 302=1EC7;1ECC 302=1ED8;1ECD 302=1ED9;1F00 300=1F02;1F00 301=1F04;1F00 ',\n '342=1F06;1F00 345=1F80;1F01 300=1F03;1F01 301=1F05;1F01 342=1F07;1F01 345=1F81;1F02 345=',\n '1F82;1F03 345=1F83;1F04 345=1F84;1F05 345=1F85;1F06 345=1F86;1F07 345=1F87;1F08 300=1F0A',\n ';1F08 301=1F0C;1F08 342=1F0E;1F08 345=1F88;1F09 300=1F0B;1F09 301=1F0D;1F09 342=1F0F;1F0',\n '9 345=1F89;1F0A 345=1F8A;1F0B 345=1F8B;1F0C 345=1F8C;1F0D 345=1F8D;1F0E 345=1F8E;1F0F 34',\n '5=1F8F;1F10 300=1F12;1F10 301=1F14;1F11 300=1F13;1F11 301=1F15;1F18 300=1F1A;1F18 301=1F',\n '1C;1F19 300=1F1B;1F19 301=1F1D;1F20 300=1F22;1F20 301=1F24;1F20 342=1F26;1F20 345=1F90;1',\n 'F21 300=1F23;1F21 301=1F25;1F21 342=1F27;1F21 345=1F91;1F22 345=1F92;1F23 345=1F93;1F24 ',\n '345=1F94;1F25 345=1F95;1F26 345=1F96;1F27 345=1F97;1F28 300=1F2A;1F28 301=1F2C;1F28 342=',\n '1F2E;1F28 345=1F98;1F29 300=1F2B;1F29 301=1F2D;1F29 342=1F2F;1F29 345=1F99;1F2A 345=1F9A',\n ';1F2B 345=1F9B;1F2C 345=1F9C;1F2D 345=1F9D;1F2E 345=1F9E;1F2F 345=1F9F;1F30 300=1F32;1F3',\n '0 301=1F34;1F30 342=1F36;1F31 300=1F33;1F31 301=1F35;1F31 342=1F37;1F38 300=1F3A;1F38 30',\n '1=1F3C;1F38 342=1F3E;1F39 300=1F3B;1F39 301=1F3D;1F39 342=1F3F;1F40 300=1F42;1F40 301=1F',\n '44;1F41 300=1F43;1F41 301=1F45;1F48 300=1F4A;1F48 301=1F4C;1F49 300=1F4B;1F49 301=1F4D;1',\n 'F50 300=1F52;1F50 301=1F54;1F50 342=1F56;1F51 300=1F53;1F51 301=1F55;1F51 342=1F57;1F59 ',\n '300=1F5B;1F59 301=1F5D;1F59 342=1F5F;1F60 300=1F62;1F60 301=1F64;1F60 342=1F66;1F60 345=',\n '1FA0;1F61 300=1F63;1F61 301=1F65;1F61 342=1F67;1F61 345=1FA1;1F62 345=1FA2;1F63 345=1FA3',\n ';1F64 345=1FA4;1F65 345=1FA5;1F66 345=1FA6;1F67 345=1FA7;1F68 300=1F6A;1F68 301=1F6C;1F6',\n '8 342=1F6E;1F68 345=1FA8;1F69 300=1F6B;1F69 301=1F6D;1F69 342=1F6F;1F69 345=1FA9;1F6A 34',\n '5=1FAA;1F6B 345=1FAB;1F6C 345=1FAC;1F6D 345=1FAD;1F6E 345=1FAE;1F6F 345=1FAF;1F70 345=1F',\n 'B2;1F74 345=1FC2;1F7C 345=1FF2;1FB6 345=1FB7;1FBF 300=1FCD;1FBF 301=1FCE;1FBF 342=1FCF;1',\n 'FC6 345=1FC7;1FF6 345=1FF7;1FFE 300=1FDD;1FFE 301=1FDE;1FFE 342=1FDF;2190 338=219A;2192 ',\n '338=219B;2194 338=21AE;21D0 338=21CD;21D2 338=21CF;21D4 338=21CE;2203 338=2204;2208 338=',\n '2209;220B 338=220C;2223 338=2224;2225 338=2226;223C 338=2241;2243 338=2244;2245 338=2247',\n ';2248 338=2249;224D 338=226D;2261 338=2262;2264 338=2270;2265 338=2271;2272 338=2274;227',\n '3 338=2275;2276 338=2278;2277 338=2279;227A 338=2280;227B 338=2281;227C 338=22E0;227D 33',\n '8=22E1;2282 338=2284;2283 338=2285;2286 338=2288;2287 338=2289;2291 338=22E2;2292 338=22',\n 'E3;22A2 338=22AC;22A8 338=22AD;22A9 338=22AE;22AB 338=22AF;22B2 338=22EA;22B3 338=22EB;2',\n '2B4 338=22EC;22B5 338=22ED;3046 3099=3094;304B 3099=304C;304D 3099=304E;304F 3099=3050;3',\n '051 3099=3052;3053 3099=3054;3055 3099=3056;3057 3099=3058;3059 3099=305A;305B 3099=305C',\n ';305D 3099=305E;305F 3099=3060;3061 3099=3062;3064 3099=3065;3066 3099=3067;3068 3099=30',\n '69;306F 3099=3070;306F 309A=3071;3072 3099=3073;3072 309A=3074;3075 3099=3076;3075 309A=',\n '3077;3078 3099=3079;3078 309A=307A;307B 3099=307C;307B 309A=307D;309D 3099=309E;30A6 309',\n '9=30F4;30AB 3099=30AC;30AD 3099=30AE;30AF 3099=30B0;30B1 3099=30B2;30B3 3099=30B4;30B5 3',\n '099=30B6;30B7 3099=30B8;30B9 3099=30BA;30BB 3099=30BC;30BD 3099=30BE;30BF 3099=30C0;30C1',\n ' 3099=30C2;30C4 3099=30C5;30C6 3099=30C7;30C8 3099=30C9;30CF 3099=30D0;30CF 309A=30D1;30',\n 'D2 3099=30D3;30D2 309A=30D4;30D5 3099=30D6;30D5 309A=30D7;30D8 3099=30D9;30D8 309A=30DA;',\n '30DB 3099=30DC;30DB 309A=30DD;30EF 3099=30F7;30F0 3099=30F8;30F1 3099=30F9;30F2 3099=30F',\n 'A;30FD 3099=30FE;105D2 307=105C9;105DA 307=105E4;11099 110BA=1109A;1109B 110BA=1109C;110',\n 'A5 110BA=110AB;11131 11127=1112E;11132 11127=1112F;11347 1133E=1134B;11347 11357=1134C;1',\n '1382 113C9=11383;11384 113BB=11385;1138B 113C2=1138E;11390 113C9=11391;113C2 113B8=113C7',\n ';113C2 113C2=113C5;113C2 113C9=113C8;114B9 114B0=114BC;114B9 114BA=114BB;114B9 114BD=114',\n 'BE;115B8 115AF=115BA;115B9 115AF=115BB;11935 11930=11938;1611E 1611E=16121;1611E 1611F=1',\n '6123;1611E 16120=16125;1611E 16129=16122;16121 1611F=16126;16121 16120=16128;16122 1611F',\n '=16127;16129 1611F=16124;16D63 16D67=16D69;16D67 16D67=16D68;16D69 16D67=16D6A',\n].join('');\n\n// Code points assigned in Unicode 16.0.0 (General_Category != Cn).\n// Entry: <cp> or <first>-<last>; uppercase hex; sorted, ';'-joined.\nexport const NFKC16_ASSIGNED_RANGES_PACKED: string = [\n '0-377;37A-37F;384-38A;38C;38E-3A1;3A3-52F;531-556;559-58A;58D-58F;591-5C7;5D0-5EA;5EF-5F',\n '4;600-70D;70F-74A;74D-7B1;7C0-7FA;7FD-82D;830-83E;840-85B;85E;860-86A;870-88E;890-891;89',\n '7-983;985-98C;98F-990;993-9A8;9AA-9B0;9B2;9B6-9B9;9BC-9C4;9C7-9C8;9CB-9CE;9D7;9DC-9DD;9D',\n 'F-9E3;9E6-9FE;A01-A03;A05-A0A;A0F-A10;A13-A28;A2A-A30;A32-A33;A35-A36;A38-A39;A3C;A3E-A4',\n '2;A47-A48;A4B-A4D;A51;A59-A5C;A5E;A66-A76;A81-A83;A85-A8D;A8F-A91;A93-AA8;AAA-AB0;AB2-AB',\n '3;AB5-AB9;ABC-AC5;AC7-AC9;ACB-ACD;AD0;AE0-AE3;AE6-AF1;AF9-AFF;B01-B03;B05-B0C;B0F-B10;B1',\n '3-B28;B2A-B30;B32-B33;B35-B39;B3C-B44;B47-B48;B4B-B4D;B55-B57;B5C-B5D;B5F-B63;B66-B77;B8',\n '2-B83;B85-B8A;B8E-B90;B92-B95;B99-B9A;B9C;B9E-B9F;BA3-BA4;BA8-BAA;BAE-BB9;BBE-BC2;BC6-BC',\n '8;BCA-BCD;BD0;BD7;BE6-BFA;C00-C0C;C0E-C10;C12-C28;C2A-C39;C3C-C44;C46-C48;C4A-C4D;C55-C5',\n '6;C58-C5A;C5D;C60-C63;C66-C6F;C77-C8C;C8E-C90;C92-CA8;CAA-CB3;CB5-CB9;CBC-CC4;CC6-CC8;CC',\n 'A-CCD;CD5-CD6;CDD-CDE;CE0-CE3;CE6-CEF;CF1-CF3;D00-D0C;D0E-D10;D12-D44;D46-D48;D4A-D4F;D5',\n '4-D63;D66-D7F;D81-D83;D85-D96;D9A-DB1;DB3-DBB;DBD;DC0-DC6;DCA;DCF-DD4;DD6;DD8-DDF;DE6-DE',\n 'F;DF2-DF4;E01-E3A;E3F-E5B;E81-E82;E84;E86-E8A;E8C-EA3;EA5;EA7-EBD;EC0-EC4;EC6;EC8-ECE;ED',\n '0-ED9;EDC-EDF;F00-F47;F49-F6C;F71-F97;F99-FBC;FBE-FCC;FCE-FDA;1000-10C5;10C7;10CD;10D0-1',\n '248;124A-124D;1250-1256;1258;125A-125D;1260-1288;128A-128D;1290-12B0;12B2-12B5;12B8-12BE',\n ';12C0;12C2-12C5;12C8-12D6;12D8-1310;1312-1315;1318-135A;135D-137C;1380-1399;13A0-13F5;13',\n 'F8-13FD;1400-169C;16A0-16F8;1700-1715;171F-1736;1740-1753;1760-176C;176E-1770;1772-1773;',\n '1780-17DD;17E0-17E9;17F0-17F9;1800-1819;1820-1878;1880-18AA;18B0-18F5;1900-191E;1920-192',\n 'B;1930-193B;1940;1944-196D;1970-1974;1980-19AB;19B0-19C9;19D0-19DA;19DE-1A1B;1A1E-1A5E;1',\n 'A60-1A7C;1A7F-1A89;1A90-1A99;1AA0-1AAD;1AB0-1ACE;1B00-1B4C;1B4E-1BF3;1BFC-1C37;1C3B-1C49',\n ';1C4D-1C8A;1C90-1CBA;1CBD-1CC7;1CD0-1CFA;1D00-1F15;1F18-1F1D;1F20-1F45;1F48-1F4D;1F50-1F',\n '57;1F59;1F5B;1F5D;1F5F-1F7D;1F80-1FB4;1FB6-1FC4;1FC6-1FD3;1FD6-1FDB;1FDD-1FEF;1FF2-1FF4;',\n '1FF6-1FFE;2000-2064;2066-2071;2074-208E;2090-209C;20A0-20C0;20D0-20F0;2100-218B;2190-242',\n '9;2440-244A;2460-2B73;2B76-2B95;2B97-2CF3;2CF9-2D25;2D27;2D2D;2D30-2D67;2D6F-2D70;2D7F-2',\n 'D96;2DA0-2DA6;2DA8-2DAE;2DB0-2DB6;2DB8-2DBE;2DC0-2DC6;2DC8-2DCE;2DD0-2DD6;2DD8-2DDE;2DE0',\n '-2E5D;2E80-2E99;2E9B-2EF3;2F00-2FD5;2FF0-303F;3041-3096;3099-30FF;3105-312F;3131-318E;31',\n '90-31E5;31EF-321E;3220-A48C;A490-A4C6;A4D0-A62B;A640-A6F7;A700-A7CD;A7D0-A7D1;A7D3;A7D5-',\n 'A7DC;A7F2-A82C;A830-A839;A840-A877;A880-A8C5;A8CE-A8D9;A8E0-A953;A95F-A97C;A980-A9CD;A9C',\n 'F-A9D9;A9DE-A9FE;AA00-AA36;AA40-AA4D;AA50-AA59;AA5C-AAC2;AADB-AAF6;AB01-AB06;AB09-AB0E;A',\n 'B11-AB16;AB20-AB26;AB28-AB2E;AB30-AB6B;AB70-ABED;ABF0-ABF9;AC00-D7A3;D7B0-D7C6;D7CB-D7FB',\n ';D800-FA6D;FA70-FAD9;FB00-FB06;FB13-FB17;FB1D-FB36;FB38-FB3C;FB3E;FB40-FB41;FB43-FB44;FB',\n '46-FBC2;FBD3-FD8F;FD92-FDC7;FDCF;FDF0-FE19;FE20-FE52;FE54-FE66;FE68-FE6B;FE70-FE74;FE76-',\n 'FEFC;FEFF;FF01-FFBE;FFC2-FFC7;FFCA-FFCF;FFD2-FFD7;FFDA-FFDC;FFE0-FFE6;FFE8-FFEE;FFF9-FFF',\n 'D;10000-1000B;1000D-10026;10028-1003A;1003C-1003D;1003F-1004D;10050-1005D;10080-100FA;10',\n '100-10102;10107-10133;10137-1018E;10190-1019C;101A0;101D0-101FD;10280-1029C;102A0-102D0;',\n '102E0-102FB;10300-10323;1032D-1034A;10350-1037A;10380-1039D;1039F-103C3;103C8-103D5;1040',\n '0-1049D;104A0-104A9;104B0-104D3;104D8-104FB;10500-10527;10530-10563;1056F-1057A;1057C-10',\n '58A;1058C-10592;10594-10595;10597-105A1;105A3-105B1;105B3-105B9;105BB-105BC;105C0-105F3;',\n '10600-10736;10740-10755;10760-10767;10780-10785;10787-107B0;107B2-107BA;10800-10805;1080',\n '8;1080A-10835;10837-10838;1083C;1083F-10855;10857-1089E;108A7-108AF;108E0-108F2;108F4-10',\n '8F5;108FB-1091B;1091F-10939;1093F;10980-109B7;109BC-109CF;109D2-10A03;10A05-10A06;10A0C-',\n '10A13;10A15-10A17;10A19-10A35;10A38-10A3A;10A3F-10A48;10A50-10A58;10A60-10A9F;10AC0-10AE',\n '6;10AEB-10AF6;10B00-10B35;10B39-10B55;10B58-10B72;10B78-10B91;10B99-10B9C;10BA9-10BAF;10',\n 'C00-10C48;10C80-10CB2;10CC0-10CF2;10CFA-10D27;10D30-10D39;10D40-10D65;10D69-10D85;10D8E-',\n '10D8F;10E60-10E7E;10E80-10EA9;10EAB-10EAD;10EB0-10EB1;10EC2-10EC4;10EFC-10F27;10F30-10F5',\n '9;10F70-10F89;10FB0-10FCB;10FE0-10FF6;11000-1104D;11052-11075;1107F-110C2;110CD;110D0-11',\n '0E8;110F0-110F9;11100-11134;11136-11147;11150-11176;11180-111DF;111E1-111F4;11200-11211;',\n '11213-11241;11280-11286;11288;1128A-1128D;1128F-1129D;1129F-112A9;112B0-112EA;112F0-112F',\n '9;11300-11303;11305-1130C;1130F-11310;11313-11328;1132A-11330;11332-11333;11335-11339;11',\n '33B-11344;11347-11348;1134B-1134D;11350;11357;1135D-11363;11366-1136C;11370-11374;11380-',\n '11389;1138B;1138E;11390-113B5;113B7-113C0;113C2;113C5;113C7-113CA;113CC-113D5;113D7-113D',\n '8;113E1-113E2;11400-1145B;1145D-11461;11480-114C7;114D0-114D9;11580-115B5;115B8-115DD;11',\n '600-11644;11650-11659;11660-1166C;11680-116B9;116C0-116C9;116D0-116E3;11700-1171A;1171D-',\n '1172B;11730-11746;11800-1183B;118A0-118F2;118FF-11906;11909;1190C-11913;11915-11916;1191',\n '8-11935;11937-11938;1193B-11946;11950-11959;119A0-119A7;119AA-119D7;119DA-119E4;11A00-11',\n 'A47;11A50-11AA2;11AB0-11AF8;11B00-11B09;11BC0-11BE1;11BF0-11BF9;11C00-11C08;11C0A-11C36;',\n '11C38-11C45;11C50-11C6C;11C70-11C8F;11C92-11CA7;11CA9-11CB6;11D00-11D06;11D08-11D09;11D0',\n 'B-11D36;11D3A;11D3C-11D3D;11D3F-11D47;11D50-11D59;11D60-11D65;11D67-11D68;11D6A-11D8E;11',\n 'D90-11D91;11D93-11D98;11DA0-11DA9;11EE0-11EF8;11F00-11F10;11F12-11F3A;11F3E-11F5A;11FB0;',\n '11FC0-11FF1;11FFF-12399;12400-1246E;12470-12474;12480-12543;12F90-12FF2;13000-13455;1346',\n '0-143FA;14400-14646;16100-16139;16800-16A38;16A40-16A5E;16A60-16A69;16A6E-16ABE;16AC0-16',\n 'AC9;16AD0-16AED;16AF0-16AF5;16B00-16B45;16B50-16B59;16B5B-16B61;16B63-16B77;16B7D-16B8F;',\n '16D40-16D79;16E40-16E9A;16F00-16F4A;16F4F-16F87;16F8F-16F9F;16FE0-16FE4;16FF0-16FF1;1700',\n '0-187F7;18800-18CD5;18CFF-18D08;1AFF0-1AFF3;1AFF5-1AFFB;1AFFD-1AFFE;1B000-1B122;1B132;1B',\n '150-1B152;1B155;1B164-1B167;1B170-1B2FB;1BC00-1BC6A;1BC70-1BC7C;1BC80-1BC88;1BC90-1BC99;',\n '1BC9C-1BCA3;1CC00-1CCF9;1CD00-1CEB3;1CF00-1CF2D;1CF30-1CF46;1CF50-1CFC3;1D000-1D0F5;1D10',\n '0-1D126;1D129-1D1EA;1D200-1D245;1D2C0-1D2D3;1D2E0-1D2F3;1D300-1D356;1D360-1D378;1D400-1D',\n '454;1D456-1D49C;1D49E-1D49F;1D4A2;1D4A5-1D4A6;1D4A9-1D4AC;1D4AE-1D4B9;1D4BB;1D4BD-1D4C3;',\n '1D4C5-1D505;1D507-1D50A;1D50D-1D514;1D516-1D51C;1D51E-1D539;1D53B-1D53E;1D540-1D544;1D54',\n '6;1D54A-1D550;1D552-1D6A5;1D6A8-1D7CB;1D7CE-1DA8B;1DA9B-1DA9F;1DAA1-1DAAF;1DF00-1DF1E;1D',\n 'F25-1DF2A;1E000-1E006;1E008-1E018;1E01B-1E021;1E023-1E024;1E026-1E02A;1E030-1E06D;1E08F;',\n '1E100-1E12C;1E130-1E13D;1E140-1E149;1E14E-1E14F;1E290-1E2AE;1E2C0-1E2F9;1E2FF;1E4D0-1E4F',\n '9;1E5D0-1E5FA;1E5FF;1E7E0-1E7E6;1E7E8-1E7EB;1E7ED-1E7EE;1E7F0-1E7FE;1E800-1E8C4;1E8C7-1E',\n '8D6;1E900-1E94B;1E950-1E959;1E95E-1E95F;1EC71-1ECB4;1ED01-1ED3D;1EE00-1EE03;1EE05-1EE1F;',\n '1EE21-1EE22;1EE24;1EE27;1EE29-1EE32;1EE34-1EE37;1EE39;1EE3B;1EE42;1EE47;1EE49;1EE4B;1EE4',\n 'D-1EE4F;1EE51-1EE52;1EE54;1EE57;1EE59;1EE5B;1EE5D;1EE5F;1EE61-1EE62;1EE64;1EE67-1EE6A;1E',\n 'E6C-1EE72;1EE74-1EE77;1EE79-1EE7C;1EE7E;1EE80-1EE89;1EE8B-1EE9B;1EEA1-1EEA3;1EEA5-1EEA9;',\n '1EEAB-1EEBB;1EEF0-1EEF1;1F000-1F02B;1F030-1F093;1F0A0-1F0AE;1F0B1-1F0BF;1F0C1-1F0CF;1F0D',\n '1-1F0F5;1F100-1F1AD;1F1E6-1F202;1F210-1F23B;1F240-1F248;1F250-1F251;1F260-1F265;1F300-1F',\n '6D7;1F6DC-1F6EC;1F6F0-1F6FC;1F700-1F776;1F77B-1F7D9;1F7E0-1F7EB;1F7F0;1F800-1F80B;1F810-',\n '1F847;1F850-1F859;1F860-1F887;1F890-1F8AD;1F8B0-1F8BB;1F8C0-1F8C1;1F900-1FA53;1FA60-1FA6',\n 'D;1FA70-1FA7C;1FA80-1FA89;1FA8F-1FAC6;1FACE-1FADC;1FADF-1FAE9;1FAF0-1FAF8;1FB00-1FB92;1F',\n 'B94-1FBF9;20000-2A6DF;2A700-2B739;2B740-2B81D;2B820-2CEA1;2CEB0-2EBE0;2EBF0-2EE5D;2F800-',\n '2FA1D;30000-3134A;31350-323AF;E0001;E0020-E007F;E0100-E01EF;F0000-FFFFD;100000-10FFFD',\n].join('');\n\n// Code points with White_Space=Yes in Unicode 16.0.0.\n// Entry: <cp> or <first>-<last>; uppercase hex; sorted, ';'-joined.\nexport const NFKC16_WHITE_SPACE_RANGES_PACKED: string = [\n '9-D;20;85;A0;1680;2000-200A;2028-2029;202F;205F;3000',\n].join('');\n","// Pinned Unicode 16.0.0 NFKC normalization.\n//\n// Keys derived from passphrases must come out identical in every conformant\n// implementation, today and years from now, so this module never delegates to\n// the host engine's String.prototype.normalize — those tables float with the\n// runtime's Unicode version, and two engines on different versions can derive\n// different keys from the same passphrase. The tables here are generated from\n// the Unicode 16.0.0 UCD and pinned. Code points that Unicode 16.0 leaves\n// unassigned are rejected outright: the Unicode stability policy only\n// guarantees normalization stability for code points that are assigned in the\n// pinned version, so passing unassigned input through would re-open the drift.\n//\n// Algorithm (UAX #15, no quick-check fast path): validate scalar values and\n// the assigned-at-16.0 guard, fully decompose through the flat NFKD table\n// (recursion was resolved at table-generation time; Hangul is algorithmic),\n// canonically reorder by combining class, then canonically compose (pair\n// table with composition exclusions applied, plus algorithmic Hangul).\n\nimport {\n NFKC16_ASSIGNED_RANGES_PACKED,\n NFKC16_CCC_PACKED,\n NFKC16_COMPOSITION_PACKED,\n NFKC16_DECOMPOSITION_PACKED,\n NFKC16_WHITE_SPACE_RANGES_PACKED,\n} from './nfkc16-data';\n\nexport type Nfkc16ErrorCode = 'UNPAIRED_SURROGATE' | 'UNASSIGNED_CODEPOINT';\n\nexport class Nfkc16Error extends Error {\n readonly code: Nfkc16ErrorCode;\n /** The offending code point (for UNPAIRED_SURROGATE, the lone surrogate code unit). */\n readonly codePoint: number;\n\n constructor(code: Nfkc16ErrorCode, message: string, codePoint: number) {\n super(message);\n this.name = 'Nfkc16Error';\n this.code = code;\n this.codePoint = codePoint;\n }\n}\n\n// Hangul decomposition/composition is algorithmic (UAX #15 section 3.12).\nconst HANGUL_S_BASE = 0xac00;\nconst HANGUL_L_BASE = 0x1100;\nconst HANGUL_V_BASE = 0x1161;\nconst HANGUL_T_BASE = 0x11a7;\nconst HANGUL_L_COUNT = 19;\nconst HANGUL_V_COUNT = 21;\nconst HANGUL_T_COUNT = 28;\nconst HANGUL_N_COUNT = HANGUL_V_COUNT * HANGUL_T_COUNT; // 588\nconst HANGUL_S_COUNT = HANGUL_L_COUNT * HANGUL_N_COUNT; // 11172\n\nconst MAX_CODE_POINT = 0x10ffff;\n\n// Composition pairs are keyed as starter * 2^21 + combining; both halves are\n// scalar values (<= 0x10FFFF < 2^21), so the packed key stays an exact integer.\nconst COMPOSITION_KEY_SHIFT = 0x200000;\n\ninterface Nfkc16Tables {\n readonly decomposition: ReadonlyMap<number, readonly number[]>;\n readonly ccc: ReadonlyMap<number, number>;\n readonly composition: ReadonlyMap<number, number>;\n /** Flat sorted [start0, end0, start1, end1, ...] pairs for binary search. */\n readonly assignedRanges: Uint32Array;\n readonly whiteSpaceRanges: Uint32Array;\n}\n\nfunction parseDecomposition(packed: string): Map<number, readonly number[]> {\n const out = new Map<number, readonly number[]>();\n for (const entry of packed.split(';')) {\n const eq = entry.indexOf('=');\n const cp = parseInt(entry.slice(0, eq), 16);\n const targets = entry\n .slice(eq + 1)\n .split(' ')\n .map((token) => parseInt(token, 16));\n out.set(cp, targets);\n }\n return out;\n}\n\nfunction parseCcc(packed: string): Map<number, number> {\n const out = new Map<number, number>();\n for (const entry of packed.split(';')) {\n const colon = entry.indexOf(':');\n const value = parseInt(entry.slice(colon + 1), 16);\n const span = entry.slice(0, colon);\n const dash = span.indexOf('-');\n const first = parseInt(dash < 0 ? span : span.slice(0, dash), 16);\n const last = dash < 0 ? first : parseInt(span.slice(dash + 1), 16);\n for (let cp = first; cp <= last; cp++) out.set(cp, value);\n }\n return out;\n}\n\nfunction parseComposition(packed: string): Map<number, number> {\n const out = new Map<number, number>();\n for (const entry of packed.split(';')) {\n const eq = entry.indexOf('=');\n const space = entry.indexOf(' ');\n const starter = parseInt(entry.slice(0, space), 16);\n const combining = parseInt(entry.slice(space + 1, eq), 16);\n out.set(starter * COMPOSITION_KEY_SHIFT + combining, parseInt(entry.slice(eq + 1), 16));\n }\n return out;\n}\n\nfunction parseRanges(packed: string): Uint32Array {\n const entries = packed.split(';');\n const out = new Uint32Array(entries.length * 2);\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i] ?? '';\n const dash = entry.indexOf('-');\n const first = parseInt(dash < 0 ? entry : entry.slice(0, dash), 16);\n const last = dash < 0 ? first : parseInt(entry.slice(dash + 1), 16);\n out[i * 2] = first;\n out[i * 2 + 1] = last;\n }\n return out;\n}\n\nlet cachedTables: Nfkc16Tables | undefined;\n\nfunction tables(): Nfkc16Tables {\n cachedTables ??= {\n decomposition: parseDecomposition(NFKC16_DECOMPOSITION_PACKED),\n ccc: parseCcc(NFKC16_CCC_PACKED),\n composition: parseComposition(NFKC16_COMPOSITION_PACKED),\n assignedRanges: parseRanges(NFKC16_ASSIGNED_RANGES_PACKED),\n whiteSpaceRanges: parseRanges(NFKC16_WHITE_SPACE_RANGES_PACKED),\n };\n return cachedTables;\n}\n\nfunction inRanges(ranges: Uint32Array, codePoint: number): boolean {\n let lo = 0;\n let hi = ranges.length / 2 - 1;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n // The fallbacks are unreachable (mid is in bounds) and fail closed.\n const start = ranges[mid * 2] ?? Number.MAX_SAFE_INTEGER;\n const end = ranges[mid * 2 + 1] ?? -1;\n if (codePoint < start) hi = mid - 1;\n else if (codePoint > end) lo = mid + 1;\n else return true;\n }\n return false;\n}\n\n/** Whether the code point is assigned (General_Category != Cn) in Unicode 16.0.0. */\nexport function isAssigned16(codePoint: number): boolean {\n if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > MAX_CODE_POINT) return false;\n return inRanges(tables().assignedRanges, codePoint);\n}\n\n/** Whether the code point has White_Space=Yes in Unicode 16.0.0. */\nexport function isWhiteSpace16(codePoint: number): boolean {\n if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > MAX_CODE_POINT) return false;\n return inRanges(tables().whiteSpaceRanges, codePoint);\n}\n\nfunction unpairedSurrogate(unit: number, index: number): Nfkc16Error {\n return new Nfkc16Error(\n 'UNPAIRED_SURROGATE',\n `unpaired surrogate 0x${unit.toString(16).toUpperCase()} at UTF-16 index ${index}`,\n unit,\n );\n}\n\n/**\n * Decode the input into Unicode scalar values, rejecting lone surrogates, and\n * enforce the assigned-at-16.0 guard. Errors are raised in input order.\n */\nfunction validatedScalarValues(input: string, t: Nfkc16Tables): number[] {\n const codePoints: number[] = [];\n for (let i = 0; i < input.length; i++) {\n const unit = input.charCodeAt(i);\n let codePoint = unit;\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;\n if (next < 0xdc00 || next > 0xdfff) throw unpairedSurrogate(unit, i);\n codePoint = 0x10000 + ((unit - 0xd800) << 10) + (next - 0xdc00);\n i++;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n throw unpairedSurrogate(unit, i);\n }\n if (!inRanges(t.assignedRanges, codePoint)) {\n throw new Nfkc16Error(\n 'UNASSIGNED_CODEPOINT',\n `code point U+${codePoint.toString(16).toUpperCase().padStart(4, '0')} is not assigned in Unicode 16.0.0`,\n codePoint,\n );\n }\n codePoints.push(codePoint);\n }\n return codePoints;\n}\n\nfunction cccOf(t: Nfkc16Tables, codePoint: number): number {\n return t.ccc.get(codePoint) ?? 0;\n}\n\nfunction decompose(t: Nfkc16Tables, codePoints: readonly number[]): number[] {\n const out: number[] = [];\n for (const cp of codePoints) {\n if (cp >= HANGUL_S_BASE && cp < HANGUL_S_BASE + HANGUL_S_COUNT) {\n const sIndex = cp - HANGUL_S_BASE;\n out.push(HANGUL_L_BASE + Math.floor(sIndex / HANGUL_N_COUNT));\n out.push(HANGUL_V_BASE + Math.floor((sIndex % HANGUL_N_COUNT) / HANGUL_T_COUNT));\n const trailing = sIndex % HANGUL_T_COUNT;\n if (trailing !== 0) out.push(HANGUL_T_BASE + trailing);\n continue;\n }\n const mapped = t.decomposition.get(cp);\n if (mapped !== undefined) {\n for (const target of mapped) out.push(target);\n } else {\n out.push(cp);\n }\n }\n return out;\n}\n\n/** Canonical Ordering Algorithm: stable insertion sort of nonzero-ccc runs. */\nfunction canonicalReorder(t: Nfkc16Tables, codePoints: number[]): void {\n for (let i = 1; i < codePoints.length; i++) {\n const cp = codePoints[i];\n if (cp === undefined) break; // unreachable: i < length\n const combining = cccOf(t, cp);\n if (combining === 0) continue;\n let j = i;\n while (j > 0) {\n const prev = codePoints[j - 1];\n if (prev === undefined || cccOf(t, prev) <= combining) break;\n codePoints[j] = prev;\n j--;\n }\n codePoints[j] = cp;\n }\n}\n\nfunction composePair(t: Nfkc16Tables, a: number, b: number): number | undefined {\n if (\n a >= HANGUL_L_BASE &&\n a < HANGUL_L_BASE + HANGUL_L_COUNT &&\n b >= HANGUL_V_BASE &&\n b < HANGUL_V_BASE + HANGUL_V_COUNT\n ) {\n return (\n HANGUL_S_BASE + ((a - HANGUL_L_BASE) * HANGUL_V_COUNT + (b - HANGUL_V_BASE)) * HANGUL_T_COUNT\n );\n }\n if (\n a >= HANGUL_S_BASE &&\n a < HANGUL_S_BASE + HANGUL_S_COUNT &&\n (a - HANGUL_S_BASE) % HANGUL_T_COUNT === 0 &&\n b > HANGUL_T_BASE &&\n b < HANGUL_T_BASE + HANGUL_T_COUNT\n ) {\n return a + (b - HANGUL_T_BASE);\n }\n return t.composition.get(a * COMPOSITION_KEY_SHIFT + b);\n}\n\n/**\n * Canonical Composition Algorithm. A combining character composes with the\n * last starter when it is not blocked: either it directly follows the starter,\n * or every character in between has a strictly lower combining class (the\n * sequence is canonically ordered, so checking the immediately preceding\n * class suffices). Primary composites are always starters, so a successful\n * composition never changes the trailing combining class.\n */\nfunction compose(t: Nfkc16Tables, codePoints: readonly number[]): number[] {\n const out: number[] = [];\n let starterIdx = -1;\n let lastCcc = 0;\n for (const cp of codePoints) {\n const combining = cccOf(t, cp);\n if (starterIdx >= 0 && (starterIdx === out.length - 1 || lastCcc < combining)) {\n const starter = out[starterIdx];\n const composed = starter === undefined ? undefined : composePair(t, starter, cp);\n if (composed !== undefined) {\n out[starterIdx] = composed;\n continue;\n }\n }\n out.push(cp);\n lastCcc = combining;\n if (combining === 0) starterIdx = out.length - 1;\n }\n return out;\n}\n\nfunction codePointsToString(codePoints: readonly number[]): string {\n let out = '';\n // Chunked to stay clear of engine argument-count limits on long inputs.\n for (let i = 0; i < codePoints.length; i += 1024) {\n out += String.fromCodePoint(...codePoints.slice(i, i + 1024));\n }\n return out;\n}\n\n/**\n * Normalize to NFKC exactly as Unicode 16.0.0 defines it.\n *\n * Throws {@link Nfkc16Error} with code UNPAIRED_SURROGATE when the input is\n * not a well-formed UTF-16 string, and with code UNASSIGNED_CODEPOINT when it\n * contains a code point that Unicode 16.0.0 leaves unassigned (normalization\n * of such input would not be stable across Unicode versions).\n */\nexport function nfkc16(input: string): string {\n const t = tables();\n const codePoints = validatedScalarValues(input, t);\n const decomposed = decompose(t, codePoints);\n canonicalReorder(t, decomposed);\n return codePointsToString(compose(t, decomposed));\n}\n","// cardano-poe-pw-norm-v1: the normative passphrase normalization profile.\n//\n// Two implementations MUST derive a byte-identical CEK from the same\n// passphrase, so the normalization applied before Argon2id is pinned, in\n// order:\n//\n// 1. Bound the raw input (a pre-KDF denial-of-service backstop).\n// 2. NFKC under the pinned Unicode 16.0.0 tables. Input the pinned tables\n// cannot normalize stably — an unpaired surrogate, or a code point that\n// Unicode 16.0 leaves unassigned (a later Unicode version may give it a\n// decomposition and silently change the derived key) — is rejected.\n// 3. Collapse every maximal run of White_Space characters to one U+0020.\n// 4. Trim leading/trailing U+0020.\n// 5. Reject the empty result — a whitespace-only passphrase normalizes to\n// zero bytes, which Argon2id would silently accept, keying the record to\n// a CEK any party can derive.\n// 6. UTF-8-encode; those bytes are the Argon2id password input.\n//\n// Every Unicode-sensitive step resolves against the pinned Unicode 16.0.0\n// data — the NFKC tables and the White_Space property both — never the host\n// engine, whose tables float with its Unicode version.\n\nimport { Nfkc16Error, isWhiteSpace16, nfkc16 } from '../unicode/nfkc16';\nimport { EciesSealedPoeError } from './errors';\n\n// Reference bound on the RAW UTF-8 byte length of a passphrase, enforced before\n// any normalization or hashing work. A deployment-pinned constant, not a wire\n// field; deployments MAY tighten it.\nexport const MAX_PASSPHRASE_INPUT_BYTES = 4096;\n\nconst UTF8 = new TextEncoder();\n\n// One code-point pass implementing profile steps 3 + 4: each maximal\n// White_Space run becomes a single U+0020, and a leading or trailing run is\n// dropped entirely (never emitted), which is exactly collapse-then-trim.\n// `isWhiteSpace16` is the pinned Unicode 16.0 White_Space property —\n// deliberately NOT JavaScript's `\\s`, which also matches U+FEFF, a character\n// the property (and therefore the profile) does not treat as whitespace.\nfunction collapseAndTrimWhiteSpace(input: string): string {\n let out = '';\n let pendingRun = false;\n for (const ch of input) {\n if (isWhiteSpace16(ch.codePointAt(0) as number)) {\n pendingRun = true;\n continue;\n }\n if (pendingRun && out.length > 0) {\n out += ' ';\n }\n pendingRun = false;\n out += ch;\n }\n return out;\n}\n\n// Apply the cardano-poe-pw-norm-v1 profile and return the exact Argon2id\n// password bytes. Throws PASSPHRASE_INPUT_TOO_LONG when the raw input exceeds\n// the pre-normalization bound, ENC_PASSPHRASE_UNNORMALIZABLE when the input\n// cannot normalize stably under Unicode 16.0 (an unpaired surrogate or an\n// unassigned code point), and ENC_PASSPHRASE_EMPTY when the normalized result\n// is the empty string.\nexport function normalizePassphrase(passphrase: string): Uint8Array {\n const rawBytes = UTF8.encode(passphrase);\n if (rawBytes.length > MAX_PASSPHRASE_INPUT_BYTES) {\n throw new EciesSealedPoeError(\n 'PASSPHRASE_INPUT_TOO_LONG',\n `passphrase raw UTF-8 length ${rawBytes.length} exceeds MAX_PASSPHRASE_INPUT_BYTES=${MAX_PASSPHRASE_INPUT_BYTES}`,\n );\n }\n let folded: string;\n try {\n folded = nfkc16(passphrase);\n } catch (error) {\n if (error instanceof Nfkc16Error) {\n throw new EciesSealedPoeError('ENC_PASSPHRASE_UNNORMALIZABLE', error.message, {\n cause: error,\n });\n }\n throw error;\n }\n const normalized = collapseAndTrimWhiteSpace(folded);\n if (normalized.length === 0) {\n throw new EciesSealedPoeError(\n 'ENC_PASSPHRASE_EMPTY',\n 'passphrase normalizes to the empty string',\n );\n }\n return UTF8.encode(normalized);\n}\n","// Passphrase-path sealed PoE: the CEK is derived directly from a normalised\n// passphrase via Argon2id — no ephemeral keypair, no slots, no trial-decrypt\n// loop, and no on-chain slots_mac. The key commitment that `slots_mac`\n// provides on the slots path lives instead in a 32-byte header prepended\n// INSIDE the ciphertext blob (same object, same URI, same fetch), so a\n// chain-only observer gets no offline passphrase-test oracle: testing a guess\n// requires possession of the blob itself.\n//\n// blob = commitment(32) || STREAM chunks\n//\n// The commitment is an HMAC keyed by an HKDF leaf of the CEK over the\n// passphrase-transcript hash, which binds the header fields, the Argon2id\n// parameters, the normalization profile, and the item's hash claim. Open\n// verifies it in constant time BEFORE any chunk is opened; a wrong passphrase\n// is indistinguishable from a tampered record by design.\n\nimport { randomBytes } from '@noble/ciphers/utils.js';\n\nimport { argon2idV13 } from '../kdf/argon2id';\nimport { compareCt } from '../util/compare-ct';\n\nimport { EciesSealedPoeError } from './errors';\nimport { normalizePassphrase } from './passphrase-normalize';\nimport { streamOpen, streamSeal, StreamTamperedError, TAG_SIZE } from './stream';\nimport {\n computePassphraseCommitment,\n computePassphraseHash,\n itemHashesHash,\n passphrasePayloadKey,\n type ItemHashes,\n} from './transcript';\nimport { SEALED_POE_AEAD } from './wrap';\n\nconst CEK_LENGTH = 32 as const;\nconst NONCE_LENGTH = 24 as const;\nconst COMMITMENT_LENGTH = 32 as const;\n// Registry-pinned Argon2id constraints: salt 16..64 bytes; m (KiB) ≥ 65536,\n// t ≥ 3, p ≥ 1; each parameter a uint ≤ 2^32 − 1.\nconst SALT_MIN_LENGTH = 16 as const;\nconst SALT_MAX_LENGTH = 64 as const;\nconst ARGON2_M_MIN = 65536 as const;\nconst ARGON2_T_MIN = 3 as const;\nconst ARGON2_P_MIN = 1 as const;\nconst PARAM_VALUE_MAX = 0xffff_ffff;\n\nexport interface PassphraseParams {\n readonly m: number;\n readonly t: number;\n readonly p: number;\n}\n\n// Producer default: the registry floors for memory and iterations plus the\n// RFC 9106 §4 recommended parallelism.\nconst DEFAULT_PARAMS: PassphraseParams = { m: 65536, t: 3, p: 4 };\n\n// The passphrase-path `enc` envelope as carried on chain: no kem, no slots, no\n// slots_mac — the commitment lives in the ciphertext blob.\nexport interface PassphraseSealedEnvelope {\n readonly scheme: 1;\n readonly aead: typeof SEALED_POE_AEAD;\n readonly nonce: Uint8Array;\n readonly passphrase: {\n readonly alg: 'argon2id';\n readonly salt: Uint8Array;\n readonly params: PassphraseParams;\n };\n}\n\nexport interface PassphraseSealArgs {\n readonly plaintext: Uint8Array;\n // The item's plaintext-hash claim; bound into the commitment so a spliced\n // envelope fails the header check before any chunk opens.\n readonly hashes: ItemHashes;\n readonly passphrase: string;\n // Fresh CSPRNG salt per envelope by default; a fixed or derived salt makes\n // equal passphrases yield equal CEKs across records.\n readonly salt?: Uint8Array;\n readonly params?: PassphraseParams;\n readonly nonce?: Uint8Array;\n}\n\nexport interface PassphraseSealedPoeOutput {\n readonly envelope: PassphraseSealedEnvelope;\n // commitment(32) || STREAM chunks — published as one object.\n readonly blob: Uint8Array;\n}\n\nexport interface PassphraseOpenArgs {\n readonly envelope: PassphraseSealedEnvelope;\n readonly blob: Uint8Array;\n readonly passphrase: string;\n readonly hashes: ItemHashes;\n}\n\n// Every decryption-layer failure — wrong passphrase, tampered salt/params/\n// header, tampered commitment, malformed or tampered stream — collapses to the\n// single TAMPERED_CIPHERTEXT outcome: the response gives an untrusted caller\n// nothing to distinguish.\nexport type PassphraseOpenResult =\n | { readonly matched: true; readonly plaintext: Uint8Array }\n | { readonly matched: false; readonly reason: 'TAMPERED_CIPHERTEXT' };\n\nfunction assertUint32(value: number, name: string): void {\n if (!Number.isInteger(value) || value < 0 || value > PARAM_VALUE_MAX) {\n throw new EciesSealedPoeError(\n 'INVALID_PASSPHRASE_PARAMS',\n `passphrase.params.${name} MUST be a uint in 0..2^32-1, got ${String(value)}`,\n );\n }\n}\n\n// Shape checks shared by seal (over caller inputs) and open (over wire data),\n// run before any KDF or AEAD primitive.\nfunction assertPassphraseBlock(args: {\n salt: Uint8Array;\n params: PassphraseParams;\n nonce: Uint8Array;\n}): void {\n if (args.nonce.length !== NONCE_LENGTH) {\n throw new EciesSealedPoeError(\n 'NONCE_LENGTH_MISMATCH',\n `nonce MUST be exactly ${NONCE_LENGTH} bytes, got ${args.nonce.length}`,\n );\n }\n if (args.salt.length < SALT_MIN_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_PASSPHRASE_SALT_TOO_SHORT',\n `passphrase.salt MUST be at least ${SALT_MIN_LENGTH} bytes, got ${args.salt.length}`,\n );\n }\n if (args.salt.length > SALT_MAX_LENGTH) {\n throw new EciesSealedPoeError(\n 'ENC_PASSPHRASE_SALT_TOO_LONG',\n `passphrase.salt MUST be at most ${SALT_MAX_LENGTH} bytes, got ${args.salt.length}`,\n );\n }\n assertUint32(args.params.m, 'm');\n assertUint32(args.params.t, 't');\n assertUint32(args.params.p, 'p');\n if (\n args.params.m < ARGON2_M_MIN ||\n args.params.t < ARGON2_T_MIN ||\n args.params.p < ARGON2_P_MIN\n ) {\n throw new EciesSealedPoeError(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n `passphrase.params MUST satisfy m >= ${ARGON2_M_MIN}, t >= ${ARGON2_T_MIN}, p >= ${ARGON2_P_MIN}; got m=${args.params.m}, t=${args.params.t}, p=${args.params.p}`,\n );\n }\n}\n\n// CEK = argon2id(password, salt, params, 32) with the Argon2 version pinned at\n// 0x13. `password` is the already-normalized passphrase byte string\n// (cardano-poe-pw-norm-v1 via `normalizePassphrase`) — normalization is a\n// separate, earlier step so its typed rejections fire before any\n// blob-dependent work on the open path.\nasync function argon2Cek(\n password: Uint8Array,\n salt: Uint8Array,\n params: PassphraseParams,\n): Promise<Uint8Array> {\n try {\n return await argon2idV13({\n password,\n salt,\n memSizeKB: params.m,\n iterations: params.t,\n parallelism: params.p,\n outBytes: CEK_LENGTH,\n });\n } catch (cause) {\n throw new EciesSealedPoeError('KDF_DERIVATION_FAILED', 'argon2id rejected the derivation', {\n cause,\n });\n }\n}\n\nfunction commitmentFor(\n envelope: PassphraseSealedEnvelope,\n cek: Uint8Array,\n hashesHash: Uint8Array,\n): Uint8Array {\n const pwHash = computePassphraseHash({\n aead: envelope.aead,\n nonce: envelope.nonce,\n hashesHash,\n salt: envelope.passphrase.salt,\n params: envelope.passphrase.params,\n });\n return computePassphraseCommitment({ cek, pwHash });\n}\n\nexport async function passphraseSealedPoeSeal(\n args: PassphraseSealArgs,\n): Promise<PassphraseSealedPoeOutput> {\n const salt = args.salt ?? randomBytes(SALT_MIN_LENGTH);\n const params = args.params ?? DEFAULT_PARAMS;\n const nonce = args.nonce ?? randomBytes(NONCE_LENGTH);\n assertPassphraseBlock({ salt, params, nonce });\n // The hash claim is digested before any KDF work: a sealed item commits to\n // the plaintext only through it, so an item without a content hash cannot be\n // sealed.\n const hashesHash = itemHashesHash(args.hashes);\n\n const envelope: PassphraseSealedEnvelope = {\n scheme: 1,\n aead: SEALED_POE_AEAD,\n nonce,\n passphrase: { alg: 'argon2id', salt, params: { m: params.m, t: params.t, p: params.p } },\n };\n\n const cek = await argon2Cek(normalizePassphrase(args.passphrase), salt, params);\n const commitment = commitmentFor(envelope, cek, hashesHash);\n const stream = streamSeal({\n payloadKey: passphrasePayloadKey({ cek, nonce }),\n plaintext: args.plaintext,\n });\n\n const blob = new Uint8Array(commitment.length + stream.length);\n blob.set(commitment, 0);\n blob.set(stream, commitment.length);\n return { envelope, blob };\n}\n\nexport async function passphraseSealedPoeOpen(\n args: PassphraseOpenArgs,\n): Promise<PassphraseOpenResult> {\n const { envelope, blob } = args;\n\n // Typed caller-input rejections fire in a pinned order — the item's hash\n // claim, then passphrase normalization, then the envelope shape — and every\n // one of them strictly precedes any blob-dependent generic failure, so a\n // malformed call is reported the same way whatever blob accompanies it.\n const hashesHash = itemHashesHash(args.hashes);\n const password = normalizePassphrase(args.passphrase);\n\n if (envelope.scheme !== 1) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_ENVELOPE_SCHEME',\n `envelope.scheme=${String(envelope.scheme)} unsupported (expected 1)`,\n );\n }\n if (envelope.aead !== SEALED_POE_AEAD) {\n throw new EciesSealedPoeError(\n 'UNSUPPORTED_AEAD_ALG',\n `envelope.aead=${String(envelope.aead)} unsupported (expected '${SEALED_POE_AEAD}')`,\n );\n }\n if (envelope.passphrase.alg !== 'argon2id') {\n throw new EciesSealedPoeError(\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n `passphrase.alg=${String(envelope.passphrase.alg)} unsupported (expected 'argon2id')`,\n );\n }\n assertPassphraseBlock({\n salt: envelope.passphrase.salt,\n params: envelope.passphrase.params,\n nonce: envelope.nonce,\n });\n\n // A passphrase-path blob shorter than the 32-byte commitment header plus the\n // 16-byte minimum STREAM (the lone tag of an empty final chunk) cannot be\n // well-formed — rejected before the KDF, so no Argon2 work is spent on it.\n // The blob is public input; the early return reveals nothing.\n if (blob.length < COMMITMENT_LENGTH + TAG_SIZE) {\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n\n const cek = await argon2Cek(password, envelope.passphrase.salt, envelope.passphrase.params);\n\n // Constant-time commitment check BEFORE any chunk is opened: the commitment\n // (not merely a Poly1305 tag deep in the stream) is what a correct passphrase\n // must reproduce, and a mismatch never begins streaming.\n const expected = commitmentFor(envelope, cek, hashesHash);\n if (!compareCt(expected, blob.subarray(0, COMMITMENT_LENGTH))) {\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n\n try {\n const plaintext = streamOpen({\n payloadKey: passphrasePayloadKey({ cek, nonce: envelope.nonce }),\n ciphertext: blob.subarray(COMMITMENT_LENGTH),\n });\n return { matched: true, plaintext };\n } catch (e) {\n if (!(e instanceof StreamTamperedError)) throw e;\n return { matched: false, reason: 'TAMPERED_CIPHERTEXT' };\n }\n}\n","// The single seam that turns a structurally-validated but permissive on-wire\n// `enc` block into the discriminated `SealedEnvelope` the unwrap / trial-decrypt\n// path consumes.\n//\n// Every read-path consumer (inbox trial-decrypt, inbox CEK recovery, CLI\n// decrypt orchestrators, the standalone recipient verifier) passes the whole\n// returned envelope plus their `RecipientKeyBundle` straight to\n// `eciesSealedPoeUnwrap` / `eciesSealedPoeTrialDecrypt` — they never rebuild\n// slots themselves. This helper is the ONE place the conversion lives: it\n// dispatches on `enc.kem`, picks the matching per-slot fields, and returns\n// `null` for anything that is not a recognised sealed-recipient envelope\n// (passphrase-only blocks, missing slots, unknown KEM, unknown scheme/aead),\n// preserving every consumer's \"this item is not for the recipient path → no\n// match, no crypto\" branch.\n//\n// crypto-core is a leaf package and must not depend on poe-standard's schema,\n// so the input is a structural shape mirroring the fields the parsed\n// `EncryptionEnvelope` exposes. Anything narrower (per-slot length checks) is\n// re-asserted by `assertEnvelopeStructure` inside the unwrap path; this helper\n// is purely the KEM-driven shape projection.\n\nimport {\n SEALED_POE_AEAD,\n type Mlkem768X25519Slot,\n type SealedEnvelope,\n type X25519Slot,\n} from './wrap';\n\n// Structural mirror of the parsed-but-permissive on-wire slot. Each field is\n// `T | undefined` (not just optional) so the parsed `EncryptionEnvelope` from a\n// consumer compiled with `exactOptionalPropertyTypes` is assignable without a\n// cast: the schema layer cannot know the envelope `kem` from a slot in\n// isolation, so it leaves all three fields optional.\nexport interface ParsedSlotShape {\n readonly epk?: Uint8Array | undefined;\n readonly kem_ct?: Uint8Array | undefined;\n readonly wrap?: Uint8Array | undefined;\n}\n\n// Structural mirror of the parsed-but-permissive `enc` block.\nexport interface ParsedEnvelopeShape {\n readonly scheme?: unknown;\n readonly aead?: string | undefined;\n readonly kem?: string | undefined;\n readonly nonce?: Uint8Array | undefined;\n readonly slots?: ReadonlyArray<ParsedSlotShape> | undefined;\n readonly slots_mac?: Uint8Array | undefined;\n}\n\n// Build the discriminated `SealedEnvelope` from a parsed `enc` block, or return\n// `null` when the block is not a sealed-recipient envelope we can trial-decrypt\n// (passphrase-only, missing slots/nonce/slots_mac, unrecognised KEM, or a slot\n// missing the KEM's required field).\nexport function sealedEnvelopeFromParsed(enc: ParsedEnvelopeShape): SealedEnvelope | null {\n if (enc.scheme !== 1 || enc.aead !== SEALED_POE_AEAD) return null;\n if (enc.nonce === undefined || enc.slots_mac === undefined) return null;\n const slots = enc.slots;\n if (slots === undefined || slots.length < 1) return null;\n\n if (enc.kem === 'x25519') {\n const x25519Slots: X25519Slot[] = [];\n for (const s of slots) {\n if (s.epk === undefined || s.wrap === undefined) return null;\n x25519Slots.push({ epk: s.epk, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: SEALED_POE_AEAD,\n kem: 'x25519',\n nonce: enc.nonce,\n slots: x25519Slots,\n slots_mac: enc.slots_mac,\n };\n }\n\n if (enc.kem === 'mlkem768x25519') {\n const hybridSlots: Mlkem768X25519Slot[] = [];\n for (const s of slots) {\n if (s.kem_ct === undefined || s.wrap === undefined) return null;\n hybridSlots.push({ kem_ct: s.kem_ct, wrap: s.wrap });\n }\n return {\n scheme: 1,\n aead: SEALED_POE_AEAD,\n kem: 'mlkem768x25519',\n nonce: enc.nonce,\n slots: hybridSlots,\n slots_mac: enc.slots_mac,\n };\n }\n\n return null;\n}\n","// Label 309 v1 structural validator (the Part A structural-validation role).\n//\n// Pure function over the reassembled CBOR record body — performs no I/O,\n// opens no socket, verifies no signature cryptographically, decodes no\n// ciphertext. Chain resolution, URI fetching, decryption, and\n// confirmation-depth checks are the verifier's concern (the Part B role).\n// The transport chunk array is reassembled BEFORE this function runs (see\n// `carriage.ts`); the carriage codes (`CHUNK_TOO_LARGE`, the transport\n// `MALFORMED_CBOR` reuse) are emitted by that step, not here.\n//\n// Pipeline:\n// Step 1 Canonical CBOR decode — `decodeCanonicalCbor` surfaces malformed /\n// non-canonical / duplicate-key / indefinite-length inputs as the\n// single MALFORMED_CBOR code.\n// Step 2 Schema parse — the closed Zod shapes in `./schema.ts`; the mapper\n// below lifts each Zod issue to its canonical structural code.\n// Step 3 Domain checks — cross-field rules, registry membership, URI shape\n// (the offline CID profile), the encryption-envelope union\n// (typed scheme-1 vs the degrade-to-opaque reading), `sigs[i]`\n// COSE_Sign1 structural decode, `crit[]` shape, exact-integer\n// range enforcement.\n// Step 4 Result emission — every collected issue is sorted (path\n// segment-wise, registry-order tie-break) and the record is valid\n// iff no error-severity issue is present.\n//\n// The validator NEVER throws — failure paths route through the discriminated\n// `ValidationResult` union so callers handle errors as data, and its output\n// is deterministic for any given `(bytes, options)` pair.\n\nimport { z } from 'zod';\n\nimport {\n decodeCanonicalCbor,\n encodeCanonicalCbor,\n type CanonicalCborValue,\n} from '@cardanowall/crypto-core/cbor';\nimport { CoseVerifyError, decodeCoseSign1 } from '@cardanowall/crypto-core/cose';\n// The verifier resource bounds the sealed-PoE unwrap layer enforces. Importing\n// the same constants, rather than re-declaring them, makes the structural\n// validator and the unwrap layer default to identical thresholds. Both are\n// deployment-pinned reference values, not wire fields — `ValidatorOptions`\n// overrides them per deployment.\nimport { MAX_DECODED_ENVELOPE_BYTES, MAX_SLOTS } from '@cardanowall/crypto-core/sealed-poe';\n\nimport { SEVERITY, errorCodeRegistryIndex, type ErrorCode, type Severity } from './error-codes';\nimport {\n EncScheme1Schema,\n isExtensionKey,\n PoeRecordSchema,\n TOP_LEVEL_BASE_KEYS,\n type EncScheme1,\n type ItemEntry,\n type MerkleCommit,\n type PassphraseBlock,\n type PoeRecord,\n type SigEntry,\n type Slot,\n} from './schema';\n\n// =============================================================================\n// Registries (closed catalogue of this implementation)\n// =============================================================================\n\n// Content-hash algorithm registry. Map value = digest length.\nconst HASH_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'sha2-256': 32,\n 'blake2b-256': 32,\n};\n\n// Merkle list-commitment algorithm registry. Map value = root length.\nconst MERKLE_COMMIT_ALG_LENGTHS: Readonly<Record<string, number>> = {\n 'rfc9162-sha256': 32,\n};\n\n// Content-format (AEAD) registry. Value = the registered `enc.nonce` length.\nconst AEAD_NONCE_LENGTHS: Readonly<Record<string, number>> = {\n 'chacha20-poly1305-stream64k': 24,\n};\n\n// Unauthenticated-cipher family. An `enc.aead` naming any of these is rejected\n// with `UNAUTHENTICATED_CIPHER_FORBIDDEN` in EVERY role — a forbidden\n// primitive is a recognised hazard, not an unknown identifier, so it never\n// takes the degrade-to-opaque reading. Two arms:\n// - block-cipher modes with no integrity (`cbc`, `ctr`, `ecb`, `cfb`,\n// `ofb`) appearing as a delimited token, matching every key-size spelling\n// (`aes-cbc`, `aes-256-cbc`, `des-ede3-cbc`, …);\n// - legacy stream/block ciphers as a leading token (`rc4`, `des`, `3des`).\n// The token delimiters keep authenticated AEADs (`aes-256-gcm`,\n// `chacha20-poly1305-stream64k`) from matching.\nconst UNAUTHENTICATED_CIPHER_RE =\n /(?:^|[-_])(?:cbc|ctr|ecb|cfb|ofb)(?:[-_]|$)|^(?:rc4|des|3des)(?:[-_]|$)/i;\n\n// KEM registry, expressed as a per-KEM slot DESCRIPTOR. Each registered KEM\n// pins the exact recipient-slot shape:\n//\n// - x25519: `{ epk: bstr(32), wrap: bstr(48) }` — classical\n// ephemeral-static X25519.\n// - mlkem768x25519: `{ kem_ct: bstr(1120), wrap: bstr(48) }` — the X-Wing\n// hybrid; the encapsulation is a SINGLE 1120-byte byte string and there\n// is NO per-slot `epk` (the X25519 ephemeral is the trailing 32 bytes of\n// `kem_ct`).\n//\n// A descriptor declares the slot's ciphertext-bearing field and its exact\n// byte length; `wrap` is 48 bytes for every KEM (32-byte CEK + 16-byte AEAD\n// tag). The validator branches on the descriptor so adding a future KEM is a\n// registry edit, not a new code path.\ntype KemSlotField = 'epk' | 'kem_ct';\ninterface KemSlotDescriptor {\n readonly field: KemSlotField;\n readonly fieldLength: number;\n readonly wrapLength: number;\n}\nconst KEM_SLOT_DESCRIPTORS: Readonly<Record<string, KemSlotDescriptor>> = {\n x25519: { field: 'epk', fieldLength: 32, wrapLength: 48 },\n mlkem768x25519: { field: 'kem_ct', fieldLength: 1120, wrapLength: 48 },\n};\n\nconst KEM_FIELD_LENGTH_CODE: Readonly<Record<KemSlotField, ErrorCode>> = {\n epk: 'KEM_EPK_LENGTH_MISMATCH',\n kem_ct: 'KEM_CT_LENGTH_MISMATCH',\n};\n\n// Passphrase KDF registry.\nconst PASSPHRASE_KDF_ALGS: ReadonlySet<string> = new Set(['argon2id']);\n\n// Signature-algorithm registry: COSE `alg` labels. `-8` (EdDSA, pinned to\n// Ed25519) is the mandatory baseline; `-19` (Ed25519 fully-specified) is\n// verified identically when accepted. Anything else is tagged\n// `SIGNATURE_UNSUPPORTED` (info-severity) — signatures are optional, so an\n// unrecognised algorithm never fails the record by itself.\nconst KNOWN_SIG_ALG_IDS: ReadonlySet<number> = new Set([-8, -19]);\n\n// Every numeric wire field is a CBOR unsigned integer pinned to this range\n// and handled as an EXACT integer (the canonical decoder surfaces values\n// above 2^53 − 1 as `bigint`, so no precision is ever lost before the range\n// check rejects).\nconst UINT32_MAX = 0xffff_ffff;\n\n// =============================================================================\n// Options\n// =============================================================================\n\nexport type ValidatorRole = 'public' | 'recipient_or_strict';\n\nexport interface Argon2ParamsCeiling {\n readonly m: number;\n readonly t: number;\n readonly p: number;\n}\n\n// The reference deployment ceiling on Argon2id work factors — a verifier-side\n// denial-of-service backstop (a 64 GiB `m` must not be able to stall a\n// decrypt-on-paste consumer), enforced by default and distinct from the\n// normative floors. Ceilings are deployment policy, not a wire rule: override\n// per deployment, or pass `passphraseParamsCeiling: null` to disable.\nexport const DEFAULT_PASSPHRASE_PARAMS_CEILING: Argon2ParamsCeiling = Object.freeze({\n m: 2_097_152, // KiB = 2 GiB\n t: 16,\n p: 8,\n});\n\nexport interface ValidatorOptions {\n /**\n * Names of the critical extensions this validator implements. Default: the\n * empty set — a default-configured validator therefore fails every\n * `crit`-bearing record with `EXTENSION_UNSUPPORTED_CRITICAL`, by design.\n */\n readonly supportedCriticalExtensions?: ReadonlySet<string>;\n /**\n * The validation reading for dual-severity envelope dispositions.\n * `public` (default): an envelope under an unsupported `scheme` / `kem` /\n * `aead` degrades to opaque and `ENC_UNSUPPORTED` is informational.\n * `recipient_or_strict` (the recipient verifier and strict sealed-crypto\n * mode): the same condition is a hard reject — `ENC_UNSUPPORTED` escalates\n * to `error` and co-fires with the identifier-specific `UNSUPPORTED_*`\n * code.\n */\n readonly role?: ValidatorRole;\n /** Slot-count resource bound (reference bound 1024; deployments MAY tighten). */\n readonly maxSlots?: number;\n /** Decoded-envelope byte resource bound (reference bound 65536). */\n readonly maxEncEnvelopeBytes?: number;\n /**\n * Upper policy ceiling on Argon2id parameters\n * (`ENC_PASSPHRASE_PARAMS_EXCEED_POLICY`). Defaults to\n * `DEFAULT_PASSPHRASE_PARAMS_CEILING`; `null` disables the ceiling.\n */\n readonly passphraseParamsCeiling?: Argon2ParamsCeiling | null;\n}\n\ninterface ResolvedOptions {\n readonly supportedCriticalExtensions: ReadonlySet<string>;\n readonly role: ValidatorRole;\n readonly maxSlots: number;\n readonly maxEncEnvelopeBytes: number;\n readonly passphraseParamsCeiling: Argon2ParamsCeiling | null;\n}\n\nconst EMPTY_EXTENSION_SET: ReadonlySet<string> = new Set();\n\nfunction resolveOptions(options?: ValidatorOptions): ResolvedOptions {\n return {\n supportedCriticalExtensions: options?.supportedCriticalExtensions ?? EMPTY_EXTENSION_SET,\n role: options?.role ?? 'public',\n maxSlots: options?.maxSlots ?? MAX_SLOTS,\n maxEncEnvelopeBytes: options?.maxEncEnvelopeBytes ?? MAX_DECODED_ENVELOPE_BYTES,\n passphraseParamsCeiling:\n options?.passphraseParamsCeiling === undefined\n ? DEFAULT_PASSPHRASE_PARAMS_CEILING\n : options.passphraseParamsCeiling,\n };\n}\n\n// =============================================================================\n// Result types\n// =============================================================================\n\nexport interface ValidationIssue {\n /**\n * Segments from the record root: text map keys and integer array indices\n * (e.g. `[\"items\", 0, \"hashes\", \"sha2-256\"]`). A dotted string is a display\n * rendering only — the segment list is the API form, so map keys containing\n * `.` need no escaping.\n */\n readonly path: ReadonlyArray<string | number>;\n readonly code: ErrorCode;\n readonly severity: Severity;\n readonly message: string;\n}\n\nexport type ValidationResult =\n | {\n readonly valid: true;\n readonly record: PoeRecord;\n readonly warnings?: ReadonlyArray<ValidationIssue>;\n readonly info?: ReadonlyArray<ValidationIssue>;\n }\n | { readonly valid: false; readonly issues: ReadonlyArray<ValidationIssue> };\n\n// =============================================================================\n// Public entry point\n// =============================================================================\n\nexport function validatePoeRecord(bytes: Uint8Array, options?: ValidatorOptions): ValidationResult {\n const opts = resolveOptions(options);\n\n // Step 1 — canonical CBOR decode. Every decode failure surfaces as the\n // single MALFORMED_CBOR code: malformed/truncated bytes, indefinite-length\n // (streaming) encodings, non-canonical map-key ordering, duplicate map\n // keys, non-minimal integers, and invalid UTF-8. There is no separate\n // duplicate-key code — canonical-decode rejection covers it.\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(bytes);\n } catch (cause) {\n return {\n valid: false,\n issues: [\n {\n code: 'MALFORMED_CBOR',\n path: [],\n message: cause instanceof Error ? cause.message : String(cause),\n severity: 'error',\n },\n ],\n };\n }\n\n // Step 2 pre-guard — non-text map keys. Every map at a typed grammar\n // position is text-keyed; the canonical decoder surfaces a map carrying any\n // non-text key as a `Map` (an all-text-key map decodes to a plain object).\n // A `Map` is still a JS object, so an object schema run over it would read\n // its (absent) named properties and mis-report every required field as\n // missing — the violation is detected here instead and attributed at the\n // containing map as SCHEMA_TYPE_MISMATCH, foreclosing the parse the same\n // way any other unparseable shape does.\n const nonTextKeyIssues = collectNonTextKeyMapIssues(decoded);\n if (nonTextKeyIssues.length > 0) {\n return { valid: false, issues: sortIssues(nonTextKeyIssues) };\n }\n\n // Step 2 — schema parse. A failed parse forecloses the domain pass (there\n // is no typed record to walk); its issues are emitted sorted.\n const parse = PoeRecordSchema.safeParse(decoded);\n if (!parse.success) {\n return { valid: false, issues: sortIssues(mapZodIssues(parse.error.issues, decoded)) };\n }\n\n // Step 3 — domain checks. Issues of every severity are collected together;\n // no error-severity issue stops the walk.\n const record = parse.data;\n const issues: ValidationIssue[] = [];\n\n checkContentCommitmentPresence(record, issues);\n\n // `crit[]` shape rules run before the per-entry support check.\n const decodedTopKeys = topLevelKeysOf(decoded);\n checkCrit(record, decodedTopKeys, opts.supportedCriticalExtensions, issues);\n\n // Unknown top-level fields: keys outside the base set that match neither\n // extension-key namespace (typos, control-character keys).\n for (const key of decodedTopKeys) {\n if (TOP_LEVEL_BASE_KEYS.has(key)) continue;\n if (isExtensionKey(key)) continue;\n issues.push(issueOf('SCHEMA_UNKNOWN_FIELD', [key], `unknown top-level field: ${key}`));\n }\n\n const items = record.items ?? [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i]!;\n checkItemHashes(item, i, issues);\n if (item.uris !== undefined) checkUris(item.uris, ['items', i, 'uris'], issues);\n if (item.enc !== undefined) checkItemEnc(item, i, opts, issues);\n }\n\n const merkle = record.merkle ?? [];\n for (let i = 0; i < merkle.length; i++) {\n checkMerkleCommit(merkle[i]!, i, issues);\n }\n\n if (record.sigs !== undefined) {\n if (record.sigs.length === 0) {\n issues.push(\n issueOf('SCHEMA_TYPE_MISMATCH', ['sigs'], 'sigs[] must be non-empty when present'),\n );\n }\n for (let i = 0; i < record.sigs.length; i++) {\n checkSigEntry(record.sigs[i]!, i, issues);\n }\n }\n\n // Step 4 — result emission. The full issue list is sorted once (path\n // segment-wise, registry-order tie-break); the record is valid iff no\n // error-severity issue is present, and warnings / info never fail it.\n const sorted = sortIssues(issues);\n if (sorted.some((issue) => issue.severity === 'error')) {\n return { valid: false, issues: sorted };\n }\n const warnings = sorted.filter((issue) => issue.severity === 'warning');\n const info = sorted.filter((issue) => issue.severity === 'info');\n const result: {\n valid: true;\n record: PoeRecord;\n warnings?: ReadonlyArray<ValidationIssue>;\n info?: ReadonlyArray<ValidationIssue>;\n } = { valid: true, record };\n if (warnings.length > 0) result.warnings = warnings;\n if (info.length > 0) result.info = info;\n return result;\n}\n\n// =============================================================================\n// Step 2 helpers — Zod issue → structural-code mapping\n// =============================================================================\n\n// Lift a Zod issue list to canonical structural issues. An\n// `unrecognized_keys` issue names every stray key of one closed map in a\n// single Zod issue; it is expanded here into one canonical issue per key,\n// attributed at the key itself — the same per-key attribution the domain\n// pass uses for closed maps it walks by hand.\nfunction mapZodIssues(\n zissues: ReadonlyArray<z.core.$ZodIssue>,\n decodedRoot?: unknown,\n): ValidationIssue[] {\n const out: ValidationIssue[] = [];\n for (const zissue of zissues) {\n if (zissue.code === 'unrecognized_keys') {\n for (const key of zissue.keys) {\n const path = [...(zissue.path as ReadonlyArray<string | number>), key];\n const code = unknownKeyCode(path);\n out.push(issueOf(code, path, `unrecognized key '${key}' in a closed map`));\n }\n continue;\n }\n out.push(mapZodIssue(zissue, decodedRoot));\n }\n return out;\n}\n\n// The canonical code for a stray key, by position: a stray key inside a\n// `sigs[i]` entry violates the sig-entry closed-map rule; everywhere else a\n// stray key in a closed map is the generic SCHEMA_UNKNOWN_FIELD. (Slot maps\n// never reach this dispatch — their schema is permissive and the KEM-driven\n// domain gate emits ENC_SLOT_INVALID_SHAPE for stray slot keys.)\nfunction unknownKeyCode(path: ReadonlyArray<string | number>): ErrorCode {\n if (path.length >= 2 && path[0] === 'sigs' && typeof path[1] === 'number') {\n return 'SIG_ENTRY_INVALID_SHAPE';\n }\n return 'SCHEMA_UNKNOWN_FIELD';\n}\n\n// Non-text-key detection over the typed grammar positions reachable from the\n// record root: the root map, each `items[i]` / `merkle[i]` / `sigs[i]` entry,\n// and the `hashes` / `enc` maps inside an item. Positions inside extension\n// values are deliberately NOT walked — extension values admit any CBOR value\n// the canonical profile allows, integer-keyed maps included. The interior of\n// a supported `enc` envelope is scanned by the envelope dispatch itself (the\n// opaque reading likewise admits arbitrary extension values).\nfunction collectNonTextKeyMapIssues(decoded: unknown): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const flag = (path: ReadonlyArray<string | number>): void => {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n path,\n 'CBOR map carries a non-text key where a text-keyed map is required',\n ),\n );\n };\n if (decoded instanceof Map) {\n flag([]);\n return issues;\n }\n if (decoded === null || typeof decoded !== 'object' || Array.isArray(decoded)) return issues;\n const record = decoded as Record<string, unknown>;\n for (const field of ['items', 'merkle', 'sigs'] as const) {\n const entries = record[field];\n if (!Array.isArray(entries)) continue;\n entries.forEach((entry, i) => {\n if (entry instanceof Map) {\n flag([field, i]);\n return;\n }\n if (field !== 'items' || entry === null || typeof entry !== 'object') return;\n const item = entry as Record<string, unknown>;\n if (item['hashes'] instanceof Map) flag([field, i, 'hashes']);\n if (item['enc'] instanceof Map) flag([field, i, 'enc']);\n });\n }\n return issues;\n}\n\nfunction mapZodIssue(zissue: z.core.$ZodIssue, decodedRoot?: unknown): ValidationIssue {\n const path = zissue.path as ReadonlyArray<string | number>;\n // Refinements with an explicit `params.code` win unconditionally — they are\n // the canonical taxonomy code attached at schema-definition time\n // (SUPERSEDES_TX_INVALID_LENGTH, ENC_SLOTS_MAC_INVALID_LENGTH, the salt\n // bounds).\n const explicit = (zissue as { params?: { code?: string } }).params?.code as ErrorCode | undefined;\n if (explicit !== undefined) {\n return issueOf(explicit, path, zissue.message);\n }\n\n const valueAtIssue = valueAtPath(decodedRoot, path);\n\n // A CBOR map carrying any non-text key decodes to a `Map` (an all-text-key\n // map decodes to a plain object), and every registered map position in the\n // grammar is text-keyed — so a `Map` anywhere a registered map is expected\n // is a non-text-key violation, reported as SCHEMA_TYPE_MISMATCH at the\n // containing map regardless of which position it sits in.\n if (valueAtIssue instanceof Map) {\n return issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n path,\n 'CBOR map carries a non-text key where a text-keyed map is required',\n );\n }\n\n // Path-based dispatch:\n // `sigs[i]…` → SIG_ENTRY_INVALID_SHAPE (the sig-entry closed-map rule)\n // a slot element or a field within a slot → ENC_SLOT_INVALID_SHAPE\n // `v` literal mismatch / missing → SCHEMA_INVALID_LITERAL vs\n // SCHEMA_MISSING_REQUIRED.\n const inSigsEntry = path.length >= 2 && path[0] === 'sigs' && typeof path[1] === 'number';\n\n // The typed envelope parse runs with the `enc` map as its root, so a slot\n // issue arrives with the relative path `slots[j]…`; `checkItemEnc` prefixes\n // the `items[i].enc` segments afterwards. (The top-level record parse never\n // descends into `enc` — the item schema holds it as `unknown` for the\n // typed-vs-opaque dispatch.)\n const isInSlotEntry = path.length >= 2 && path[0] === 'slots' && typeof path[1] === 'number';\n\n const isMissing = valueAtIssue === undefined;\n\n switch (zissue.code) {\n case 'invalid_type':\n if (isInSlotEntry) return issueOf('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (isMissing) {\n if (inSigsEntry) return issueOf('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issueOf('SCHEMA_MISSING_REQUIRED', path, zissue.message);\n }\n if (inSigsEntry) return issueOf('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issueOf('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n case 'invalid_value':\n // `z.literal(1)` emits `invalid_value` for both a missing field AND a\n // present-but-wrong value; disambiguate via the runtime value.\n if (isMissing) return issueOf('SCHEMA_MISSING_REQUIRED', path, zissue.message);\n return issueOf('SCHEMA_INVALID_LITERAL', path, zissue.message);\n case 'invalid_union':\n case 'invalid_format':\n case 'too_big':\n case 'too_small':\n case 'invalid_key':\n case 'invalid_element':\n case 'custom':\n default:\n if (isInSlotEntry) return issueOf('ENC_SLOT_INVALID_SHAPE', path, zissue.message);\n if (inSigsEntry) return issueOf('SIG_ENTRY_INVALID_SHAPE', path, zissue.message);\n return issueOf('SCHEMA_TYPE_MISMATCH', path, zissue.message);\n }\n}\n\n// =============================================================================\n// Step 3 helpers — domain checks\n// =============================================================================\n\n// Content-commitment rule: a record MUST carry at least one of `items[]` or\n// `merkle[]` non-empty (SCHEMA_EMPTY_RECORD when both are empty or absent).\n// When exactly one of them is present-but-empty beside a non-empty sibling,\n// the empty array itself violates its `1*` cardinality.\nfunction checkContentCommitmentPresence(record: PoeRecord, issues: ValidationIssue[]): void {\n const itemsLen = record.items?.length ?? 0;\n const merkleLen = record.merkle?.length ?? 0;\n if (itemsLen === 0 && merkleLen === 0) {\n issues.push(\n issueOf(\n 'SCHEMA_EMPTY_RECORD',\n [],\n 'record must carry at least one of items[] or merkle[] non-empty',\n ),\n );\n return;\n }\n if (record.items !== undefined && itemsLen === 0) {\n issues.push(\n issueOf('SCHEMA_TYPE_MISMATCH', ['items'], 'items[] must be non-empty when present'),\n );\n }\n if (record.merkle !== undefined && merkleLen === 0) {\n issues.push(\n issueOf('SCHEMA_TYPE_MISMATCH', ['merkle'], 'merkle[] must be non-empty when present'),\n );\n }\n}\n\n// Hash-map: non-empty, registry membership, per-algorithm digest length.\nfunction checkItemHashes(item: ItemEntry, idx: number, issues: ValidationIssue[]): void {\n const entries = Object.entries(item.hashes);\n if (entries.length === 0) {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n ['items', idx, 'hashes'],\n 'hashes must be a non-empty CBOR map of <alg-id> -> <digest>',\n ),\n );\n return;\n }\n for (const [alg, digest] of entries) {\n if (!(alg in HASH_ALG_LENGTHS)) {\n issues.push(\n issueOf('UNSUPPORTED_HASH_ALG', ['items', idx, 'hashes', alg], `unknown hash alg: ${alg}`),\n );\n continue;\n }\n const expected = HASH_ALG_LENGTHS[alg]!;\n if (digest.length !== expected) {\n issues.push(\n issueOf(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n ['items', idx, 'hashes', alg],\n `hashes['${alg}'] digest length ${digest.length} != ${expected}`,\n ),\n );\n }\n }\n}\n\n// URI shape: each entry is one absolute URI in a single text string.\nfunction checkUris(\n uris: ReadonlyArray<string>,\n basePath: ReadonlyArray<string | number>,\n issues: ValidationIssue[],\n): void {\n if (uris.length === 0) {\n issues.push(issueOf('SCHEMA_TYPE_MISMATCH', basePath, 'uris[] must be non-empty when present'));\n return;\n }\n uris.forEach((uri, ui) => checkOneUri(uri, [...basePath, ui], issues));\n}\n\nfunction checkOneUri(\n uri: string,\n path: ReadonlyArray<string | number>,\n issues: ValidationIssue[],\n): void {\n // Absolute URI, no fragment, scheme in `{ar://, ipfs://}`.\n if (uri.includes('#')) {\n issues.push(\n issueOf('INVALID_URI', path, \"URI contains a fragment identifier ('#'), which is forbidden\"),\n );\n return;\n }\n const sepIdx = uri.indexOf('://');\n if (sepIdx <= 0 || !/^[a-z][a-z0-9+.-]*$/i.test(uri.slice(0, sepIdx))) {\n issues.push(\n issueOf('INVALID_URI', path, 'URI is not absolute (missing scheme://hierarchical-part)'),\n );\n return;\n }\n // RFC 3986 §3.1: the scheme is case-insensitive, so case-fold the SCHEME\n // ONLY, then ALWAYS validate the body. The body is matched verbatim — a\n // base64url Arweave txid and a base58btc CID are case-significant.\n const scheme = uri.slice(0, sepIdx).toLowerCase();\n const rest = uri.slice(sepIdx + '://'.length);\n if (scheme === 'ar') {\n if (!/^[A-Za-z0-9_-]{43}$/.test(rest)) {\n issues.push(\n issueOf(\n 'INVALID_URI',\n path,\n 'ar:// URI does not match `^ar://[A-Za-z0-9_-]{43}$` (43-char base64url txid, no path/query/fragment)',\n ),\n );\n }\n return;\n }\n if (scheme === 'ipfs') {\n // Full offline CID parse (not a prefix heuristic).\n const slashIdx = rest.indexOf('/');\n const cid = slashIdx === -1 ? rest : rest.slice(0, slashIdx);\n if (!validateCidProfile(cid)) {\n issues.push(\n issueOf('INVALID_URI', path, 'ipfs:// URI is not a valid CID under the Label 309 profile'),\n );\n }\n return;\n }\n issues.push(\n issueOf('INVALID_URI', path, 'unsupported URI scheme; v1 PoE URI set is {ar://, ipfs://}'),\n );\n}\n\n// =============================================================================\n// Encryption envelope — the typed-vs-opaque union\n// =============================================================================\n//\n// `enc = enc-scheme-1 / enc-opaque`. The disposition is decided by identifier\n// support, never by shape success:\n//\n// - When `scheme`, `kem`, and `aead` are ALL supported identifiers, the\n// envelope is held to the full scheme-1 shape and key-path rules; an\n// envelope that fails them is rejected with its typed code, never\n// reclassified as opaque.\n// - When any of the three names an identifier this implementation does not\n// support, the envelope becomes OPAQUE: no shape, length, or key-path\n// rule is applied against an unknown identifier; the item is tagged\n// ENC_UNSUPPORTED (info in the public reading; error co-firing with the\n// identifier-specific UNSUPPORTED_* code in the recipient role / strict\n// sealed-crypto mode).\n// - Carve-out: an `aead` naming a forbidden unauthenticated cipher family\n// is rejected UNAUTHENTICATED_CIPHER_FORBIDDEN in every role — a\n// recognised hazard, not an unknown identifier.\n//\n// The content-hash binding (ENC_REQUIRES_CONTENT_HASH) inspects the item's\n// `hashes` map, not the envelope, so it applies even under an opaque\n// envelope.\n\nfunction checkItemEnc(\n item: ItemEntry,\n idx: number,\n opts: ResolvedOptions,\n issues: ValidationIssue[],\n): void {\n const encPath: ReadonlyArray<string | number> = ['items', idx, 'enc'];\n\n // Content-hash binding: an `enc`-bearing item MUST commit to at least one\n // REGISTERED content hash — the ciphertext is otherwise bound to no\n // plaintext digest. A presence check, not a non-empty check: `{md5: …}`\n // fails it (and MAY co-fire with UNSUPPORTED_HASH_ALG on the same item).\n const hasContentHash = Object.keys(item.hashes).some((alg) => alg in HASH_ALG_LENGTHS);\n if (!hasContentHash) {\n issues.push(\n issueOf(\n 'ENC_REQUIRES_CONTENT_HASH',\n encPath,\n 'item carries `enc` but `hashes` has no registered content-hash entry (sha2-256 or blake2b-256)',\n ),\n );\n }\n\n // The pre-guard has already rejected an `enc` that decoded to a `Map`\n // (non-text keys), so a well-typed envelope arrives here as a plain object.\n const rawEnc = item.enc;\n if (\n rawEnc === null ||\n typeof rawEnc !== 'object' ||\n Array.isArray(rawEnc) ||\n rawEnc instanceof Uint8Array\n ) {\n issues.push(issueOf('SCHEMA_TYPE_MISMATCH', encPath, 'enc must be a CBOR map'));\n return;\n }\n const enc = rawEnc as Record<string, unknown>;\n\n // Decoded-envelope byte resource bound — a generic decode limit that\n // applies in every reading, opaque included. Canonical decode → canonical\n // encode is byte-identical, so re-encoding the decoded envelope measures\n // exactly the wire bytes of the `enc` subtree.\n const envelopeBytes = encodeCanonicalCbor(rawEnc as CanonicalCborValue).length;\n if (envelopeBytes > opts.maxEncEnvelopeBytes) {\n issues.push(\n issueOf(\n 'ENC_ENVELOPE_TOO_LARGE',\n encPath,\n `decoded envelope is ${envelopeBytes} bytes; the resource bound is ${opts.maxEncEnvelopeBytes}`,\n ),\n );\n }\n\n // `scheme` is structurally required in BOTH readings, as a CBOR unsigned\n // integer (the opaque grammar admits any uint; the typed grammar pins 1).\n const scheme = enc['scheme'];\n if (scheme === undefined) {\n issues.push(\n issueOf('SCHEMA_MISSING_REQUIRED', [...encPath, 'scheme'], 'enc.scheme is required'),\n );\n return;\n }\n if (!isUint(scheme)) {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n [...encPath, 'scheme'],\n 'enc.scheme must be a CBOR unsigned integer',\n ),\n );\n return;\n }\n\n // Forbidden-cipher carve-out: rejected in every role, never opaque.\n const aead = enc['aead'];\n if (typeof aead === 'string' && UNAUTHENTICATED_CIPHER_RE.test(aead)) {\n issues.push(\n issueOf(\n 'UNAUTHENTICATED_CIPHER_FORBIDDEN',\n [...encPath, 'aead'],\n `'${aead}' is an unauthenticated cipher; Label 309 mandates an authenticated (AEAD) cipher`,\n ),\n );\n return;\n }\n\n // Unknown-envelope rule: collect every identifier outside the implemented\n // set. A non-text `kem` / `aead` is not an identifier at all — it is a type\n // violation of whichever reading applies, handled by the typed pass below.\n const kem = enc['kem'];\n const unsupported: Array<{ field: 'scheme' | 'kem' | 'aead'; code: ErrorCode; id: string }> = [];\n if (!(typeof scheme === 'number' && scheme === 1)) {\n unsupported.push({ field: 'scheme', code: 'UNSUPPORTED_ENVELOPE_SCHEME', id: String(scheme) });\n }\n if (typeof kem === 'string' && !(kem in KEM_SLOT_DESCRIPTORS)) {\n unsupported.push({ field: 'kem', code: 'UNSUPPORTED_KEM_ALG', id: kem });\n }\n if (typeof aead === 'string' && !(aead in AEAD_NONCE_LENGTHS)) {\n unsupported.push({ field: 'aead', code: 'UNSUPPORTED_AEAD_ALG', id: aead });\n }\n if (unsupported.length > 0) {\n // Degrade to opaque: the envelope is bounded metadata only. No shape,\n // length, nonce, slot, or key-path rule may be applied against an\n // unknown identifier.\n const named = unsupported.map((u) => `${u.field}=${u.id}`).join(', ');\n const message =\n `envelope uses identifiers this implementation does not support (${named}); ` +\n 'the envelope is opaque and only the content-hash claim is validated';\n if (opts.role === 'recipient_or_strict') {\n issues.push({ code: 'ENC_UNSUPPORTED', path: encPath, message, severity: 'error' });\n for (const u of unsupported) {\n issues.push(\n issueOf(u.code, [...encPath, u.field], `enc.${u.field} '${u.id}' is not supported`),\n );\n }\n } else {\n issues.push({ code: 'ENC_UNSUPPORTED', path: encPath, message, severity: 'info' });\n }\n return;\n }\n\n // Fully supported identifiers → the typed scheme-1 pass is mandatory.\n // Non-text-key maps inside the typed envelope (a slot, the passphrase\n // block, its params) are rejected first, at the containing map — the same\n // pre-guard rule the record level applies, scoped here because only the\n // typed reading constrains the envelope interior.\n const internalMapIssues = encInternalNonTextKeyIssues(enc, encPath);\n if (internalMapIssues.length > 0) {\n issues.push(...internalMapIssues);\n return;\n }\n const encParse = EncScheme1Schema.safeParse(rawEnc);\n if (!encParse.success) {\n for (const mapped of mapZodIssues(encParse.error.issues, rawEnc)) {\n issues.push({ ...mapped, path: [...encPath, ...mapped.path] });\n }\n return;\n }\n checkScheme1Envelope(encParse.data, rawEnc, encPath, opts, issues);\n}\n\n// Non-text-key maps at the typed envelope's interior positions: each slot,\n// the passphrase block, and its `params` map.\nfunction encInternalNonTextKeyIssues(\n enc: Record<string, unknown>,\n encPath: ReadonlyArray<string | number>,\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const flag = (path: ReadonlyArray<string | number>): void => {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n path,\n 'CBOR map carries a non-text key where a text-keyed map is required',\n ),\n );\n };\n const slots = enc['slots'];\n if (Array.isArray(slots)) {\n slots.forEach((slot, i) => {\n if (slot instanceof Map) flag([...encPath, 'slots', i]);\n });\n }\n const passphrase = enc['passphrase'];\n if (passphrase instanceof Map) {\n flag([...encPath, 'passphrase']);\n } else if (passphrase !== null && typeof passphrase === 'object' && !Array.isArray(passphrase)) {\n const params = (passphrase as Record<string, unknown>)['params'];\n if (params instanceof Map) flag([...encPath, 'passphrase', 'params']);\n }\n return issues;\n}\n\nfunction checkScheme1Envelope(\n enc: EncScheme1,\n rawEnc: object,\n encPath: ReadonlyArray<string | number>,\n opts: ResolvedOptions,\n issues: ValidationIssue[],\n): void {\n // Nonce length is registered per content format (24 bytes for\n // chacha20-poly1305-stream64k). Checked only under a supported `aead` —\n // which is guaranteed on this path.\n const expectedNonceLen = AEAD_NONCE_LENGTHS[enc.aead]!;\n if (enc.nonce.length !== expectedNonceLen) {\n issues.push(\n issueOf(\n 'NONCE_LENGTH_MISMATCH',\n [...encPath, 'nonce'],\n `nonce length ${enc.nonce.length} != ${expectedNonceLen} for ${enc.aead}`,\n ),\n );\n }\n\n // Key-path cross-field rules. Exactly one of `slots` / `passphrase` is\n // present; `passphrase` forbids `kem`, `slots`, and `slots_mac`; `slots`\n // requires both `kem` and `slots_mac`; `slots_mac` binds nothing without\n // `slots`. Each independent rule emits its own code — they co-fire where\n // several apply.\n const hasSlots = enc.slots !== undefined;\n const hasSlotsMac = enc.slots_mac !== undefined;\n const hasPassphrase = enc.passphrase !== undefined;\n const hasKem = enc.kem !== undefined;\n\n if (hasPassphrase && (hasSlots || hasSlotsMac || hasKem)) {\n issues.push(\n issueOf(\n 'ENC_EXCLUSIVITY_VIOLATION',\n encPath,\n 'enc.passphrase is mutually exclusive with kem / slots / slots_mac; exactly one key path is allowed',\n ),\n );\n }\n if (hasSlots && !hasSlotsMac) {\n issues.push(\n issueOf('ENC_SLOTS_MAC_REQUIRED', encPath, 'enc.slots present but enc.slots_mac absent'),\n );\n }\n if (hasSlotsMac && !hasSlots) {\n issues.push(\n issueOf('ENC_SLOTS_REQUIRED', encPath, 'enc.slots_mac present but enc.slots absent'),\n );\n }\n if (hasSlots && !hasKem) {\n issues.push(issueOf('ENC_KEM_REQUIRED', encPath, 'enc.slots present but enc.kem absent'));\n }\n if (!hasSlots && !hasPassphrase) {\n issues.push(\n issueOf(\n 'ENC_NO_KEY_PATH',\n encPath,\n 'enc requires either slots or passphrase — no on-chain key path otherwise',\n ),\n );\n }\n\n if (hasSlots) {\n const slots = enc.slots!;\n if (slots.length < 1) {\n issues.push(\n issueOf('ENC_SLOTS_EMPTY', [...encPath, 'slots'], 'slots[] must carry at least one slot'),\n );\n } else if (slots.length > opts.maxSlots) {\n // Slot-count resource bound: reject before walking any slot, so a\n // hostile record cannot drive unbounded per-slot work.\n issues.push(\n issueOf(\n 'ENC_SLOTS_TOO_MANY',\n [...encPath, 'slots'],\n `slots length ${slots.length} exceeds the slot-count bound ${opts.maxSlots}`,\n ),\n );\n } else if (hasKem) {\n // The descriptor exists — `kem` is registered on this path.\n const descriptor = KEM_SLOT_DESCRIPTORS[enc.kem!]!;\n const rawSlotKeys = rawSlotKeySets(rawEnc);\n // Per-slot KEK uniqueness: the zero-nonce per-slot wrap is safe only\n // because each slot draws fresh KEM randomness; two slots sharing the\n // same encapsulation material would derive the same KEK. Reject the\n // repeat before any cryptographic layer would.\n const seenKemMaterial = new Set<string>();\n slots.forEach((slot, si) => {\n const slotPath = [...encPath, 'slots', si] as const;\n checkSlotShape(\n slot,\n rawSlotKeys[si] ?? new Set<string>(),\n descriptor,\n enc.kem!,\n slotPath,\n issues,\n );\n const material = descriptor.field === 'epk' ? slot.epk : slot.kem_ct;\n if (material !== undefined) {\n const key = bytesToHex(material);\n if (seenKemMaterial.has(key)) {\n issues.push(\n issueOf(\n 'ENC_SLOTS_DUPLICATE_KEM_MATERIAL',\n [...slotPath, descriptor.field],\n `slot ${si} ${descriptor.field} duplicates an earlier slot — per-slot KEK uniqueness is violated`,\n ),\n );\n } else {\n seenKemMaterial.add(key);\n }\n }\n });\n }\n }\n\n if (hasPassphrase) {\n checkPassphraseBlock(enc.passphrase!, [...encPath, 'passphrase'], opts, issues);\n }\n}\n\n// KEM-driven per-slot shape gate. The descriptor for the declared envelope\n// `kem` pins which ciphertext-bearing field MUST be present at what exact\n// length, and forbids everything else: the other KEM's field, any stray key\n// (a slot is a CLOSED 2-key map), and a missing required field all surface\n// as ENC_SLOT_INVALID_SHAPE. `rawKeys` is the slot's key set exactly as it\n// appeared on the wire, so the permissive slot schema cannot mask a foreign\n// field.\nconst SLOT_KEY_UNIVERSE: ReadonlySet<string> = new Set(['epk', 'kem_ct', 'wrap']);\n\nfunction checkSlotShape(\n slot: Slot,\n rawKeys: ReadonlySet<string>,\n descriptor: KemSlotDescriptor,\n kem: string,\n slotPath: ReadonlyArray<string | number>,\n issues: ValidationIssue[],\n): void {\n const foreignField: KemSlotField = descriptor.field === 'epk' ? 'kem_ct' : 'epk';\n if (rawKeys.has(foreignField)) {\n issues.push(\n issueOf(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, foreignField],\n `slot carries '${foreignField}' but kem='${kem}' expects '${descriptor.field}'`,\n ),\n );\n }\n for (const key of rawKeys) {\n if (!SLOT_KEY_UNIVERSE.has(key)) {\n issues.push(\n issueOf(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, key],\n `slot carries unexpected key '${key}'; a slot is a 2-key map {${descriptor.field}, wrap}`,\n ),\n );\n }\n }\n\n const ctField = descriptor.field === 'epk' ? slot.epk : slot.kem_ct;\n if (ctField === undefined) {\n issues.push(\n issueOf(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, descriptor.field],\n `slot for kem='${kem}' is missing required '${descriptor.field}'`,\n ),\n );\n } else if (ctField.length !== descriptor.fieldLength) {\n issues.push(\n issueOf(\n KEM_FIELD_LENGTH_CODE[descriptor.field],\n [...slotPath, descriptor.field],\n `slot.${descriptor.field} length ${ctField.length} != ${descriptor.fieldLength} for ${kem}`,\n ),\n );\n }\n\n if (slot.wrap === undefined) {\n issues.push(\n issueOf(\n 'ENC_SLOT_INVALID_SHAPE',\n [...slotPath, 'wrap'],\n `slot for kem='${kem}' is missing required 'wrap'`,\n ),\n );\n } else if (slot.wrap.length !== descriptor.wrapLength) {\n issues.push(\n issueOf(\n 'WRAP_LENGTH_MISMATCH',\n [...slotPath, 'wrap'],\n `slot.wrap length ${slot.wrap.length} != ${descriptor.wrapLength}`,\n ),\n );\n }\n}\n\n// Passphrase block: KDF registry membership, then the registered algorithm's\n// CLOSED parameter map with exact-integer range, floors, and the deployment\n// ceiling. Salt bounds are schema refinements and have already fired.\nfunction checkPassphraseBlock(\n pp: PassphraseBlock,\n ppPath: ReadonlyArray<string | number>,\n opts: ResolvedOptions,\n issues: ValidationIssue[],\n): void {\n if (!PASSPHRASE_KDF_ALGS.has(pp.alg)) {\n issues.push(\n issueOf(\n 'ENC_PASSPHRASE_ALG_UNSUPPORTED',\n [...ppPath, 'alg'],\n `unknown passphrase kdf alg: ${pp.alg}`,\n ),\n );\n return; // no algorithm-specific params rule can apply\n }\n\n // argon2id: `params` is the CLOSED map of exactly {m, t, p}.\n const paramsPath = [...ppPath, 'params'] as const;\n const params = pp.params;\n for (const key of Object.keys(params)) {\n if (key !== 'm' && key !== 't' && key !== 'p') {\n issues.push(\n issueOf(\n 'SCHEMA_UNKNOWN_FIELD',\n [...paramsPath, key],\n `unknown argon2id params field: ${key}`,\n ),\n );\n }\n }\n\n const floors = { m: 65_536, t: 3, p: 1 } as const;\n const ceiling = opts.passphraseParamsCeiling;\n for (const name of ['m', 't', 'p'] as const) {\n const value: unknown = params[name];\n if (value === undefined) {\n issues.push(\n issueOf(\n 'SCHEMA_MISSING_REQUIRED',\n [...paramsPath, name],\n `argon2id params.${name} is required`,\n ),\n );\n continue;\n }\n // Exact-integer discipline: values above 2^53 − 1 arrive as `bigint`,\n // so an out-of-range value is rejected without precision loss.\n if (!isUint(value)) {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n [...paramsPath, name],\n `argon2id params.${name} must be a CBOR unsigned integer`,\n ),\n );\n continue;\n }\n if (!uintWithin(value, 0, UINT32_MAX)) {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n [...paramsPath, name],\n `argon2id params.${name} exceeds the pinned wire range 0 .. 2^32 - 1`,\n ),\n );\n continue;\n }\n const num = Number(value);\n if (num < floors[name]) {\n issues.push(\n issueOf(\n 'ENC_PASSPHRASE_ARGON2_PARAMS_TOO_LOW',\n [...paramsPath, name],\n `argon2id requires ${name} >= ${floors[name]}`,\n ),\n );\n continue;\n }\n if (ceiling !== null && num > ceiling[name]) {\n issues.push(\n issueOf(\n 'ENC_PASSPHRASE_PARAMS_EXCEED_POLICY',\n [...paramsPath, name],\n `argon2id params.${name} = ${num} exceeds the deployment ceiling ${ceiling[name]}`,\n ),\n );\n }\n }\n}\n\n// Extract the per-slot RAW key sets from the decoded `enc` value, so the\n// closed-slot rule sees keys the permissive slot schema does not model. The\n// canonical decoder yields a plain object for a text-keyed CBOR map and a\n// `Map` for a map carrying any non-text key.\nfunction rawSlotKeySets(rawEnc: object): ReadonlyArray<ReadonlySet<string>> {\n const slots = (rawEnc as Record<string, unknown>)['slots'];\n if (!Array.isArray(slots)) return [];\n return slots.map((slot) => {\n const keys = new Set<string>();\n if (slot instanceof Map) {\n for (const k of slot.keys()) if (typeof k === 'string') keys.add(k);\n } else if (typeof slot === 'object' && slot !== null) {\n for (const k of Object.keys(slot as Record<string, unknown>)) keys.add(k);\n }\n return keys;\n });\n}\n\n// =============================================================================\n// Merkle commitments\n// =============================================================================\n\nfunction checkMerkleCommit(commit: MerkleCommit, idx: number, issues: ValidationIssue[]): void {\n const basePath: ReadonlyArray<string | number> = ['merkle', idx];\n if (!(commit.alg in MERKLE_COMMIT_ALG_LENGTHS)) {\n issues.push(\n issueOf(\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n [...basePath, 'alg'],\n `unknown merkle commitment alg: ${commit.alg}`,\n ),\n );\n } else {\n const expected = MERKLE_COMMIT_ALG_LENGTHS[commit.alg]!;\n if (commit.root.length !== expected) {\n issues.push(\n issueOf(\n 'HASH_DIGEST_LENGTH_MISMATCH',\n [...basePath, 'root'],\n `merkle entry root length ${commit.root.length} != ${expected} for ${commit.alg}`,\n ),\n );\n }\n }\n\n // `leaf_count` is REQUIRED and pinned to `1 .. 2^32 − 1`, compared as an\n // exact integer: the decoder surfaces values above 2^53 − 1 as `bigint`,\n // so 2^53 + 1 cannot round to a boundary value before rejection. A\n // negative value is a CBOR type violation (nint where uint is required),\n // distinct from an out-of-range unsigned value.\n const leafCount = commit.leaf_count;\n if (!isUint(leafCount)) {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n [...basePath, 'leaf_count'],\n 'leaf_count must be a CBOR unsigned integer',\n ),\n );\n } else if (!uintWithin(leafCount, 1, UINT32_MAX)) {\n issues.push(\n issueOf(\n 'SCHEMA_MERKLE_LEAF_COUNT_INVALID',\n [...basePath, 'leaf_count'],\n `leaf_count ${String(leafCount)} is outside the pinned range 1 .. 2^32 - 1`,\n ),\n );\n }\n\n if (commit.uris !== undefined) {\n checkUris(commit.uris, [...basePath, 'uris'], issues);\n }\n}\n\n// =============================================================================\n// Record-level signature entries\n// =============================================================================\n\nfunction checkSigEntry(entry: SigEntry, idx: number, issues: ValidationIssue[]): void {\n // Path-2 `cose_key` private-material guard runs FIRST: a leaked private\n // scalar must be named even when the COSE_Sign1 is also malformed.\n if (entry.cose_key !== undefined) {\n const keyIssue = inspectCoseKey(entry.cose_key, idx);\n if (keyIssue !== null) {\n issues.push(keyIssue);\n return;\n }\n }\n\n let cose: ReturnType<typeof decodeCoseSign1>;\n try {\n cose = decodeCoseSign1(entry.cose_sign1);\n } catch (cause) {\n issues.push(\n issueOf(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n cause instanceof CoseVerifyError || cause instanceof Error ? cause.message : String(cause),\n ),\n );\n return;\n }\n\n // Detached-only: the COSE_Sign1 payload MUST be CBOR null. An attached\n // payload — even zero-length — is rejected; a producer chaining a CIP-30\n // signData result must null the payload before embedding.\n if (cose.payload !== null) {\n issues.push(\n issueOf(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', idx],\n 'COSE_Sign1 payload must be null (detached); attached form forbidden',\n ),\n );\n return;\n }\n\n // Signature-algorithm registry check (info severity — signatures are\n // optional, so an unrecognised algorithm never fails the record alone).\n const alg = cose.protectedHeader.get(1);\n if (typeof alg !== 'number' || !KNOWN_SIG_ALG_IDS.has(alg)) {\n issues.push(\n issueOf(\n 'SIGNATURE_UNSUPPORTED',\n ['sigs', idx],\n `COSE_Sign1 protected alg ${String(alg)} not in {-8, -19}`,\n ),\n );\n }\n\n // Path-1 (32-byte protected-header `kid`) and path-2 (`cose_key` sidecar)\n // are mutually exclusive.\n const protectedKid = cose.protectedHeader.get(4);\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === 32 &&\n entry.cose_key !== undefined\n ) {\n issues.push(\n issueOf(\n 'SIG_ENTRY_KID_COSE_KEY_CONFLICT',\n ['sigs', idx],\n 'sigs[i] carries both a 32-byte protected `kid` (path 1) and an inline `cose_key` (path 2); paths are mutually exclusive',\n ),\n );\n }\n}\n\n// COSE_Key inspector (path-2 `sigs[i].cose_key` blob). Two structural checks:\n// 1. Private-material guard (FIRST). COSE_Key label `-4` (the private\n// scalar `d` for OKP / EC2 per RFC 9052 §7.1) → SIG_PRIVATE_KEY_LEAKED.\n// Publishing a private key on the permanent ledger is catastrophic and\n// irreversible, so this is a load-bearing producer-side preflight.\n// 2. Positive-shape guard: `kty = 1` (OKP), `crv = 6` (Ed25519), and a\n// 32-byte `-2` (x). Any failure → MALFORMED_SIG_COSE_SIGN1.\nfunction inspectCoseKey(keyBytes: Uint8Array, i: number): ValidationIssue | null {\n let decoded: unknown;\n try {\n decoded = decodeCanonicalCbor(keyBytes);\n } catch (cause) {\n return issueOf(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key failed to decode as cbor<COSE_Key>: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n\n // A COSE_Key map is int-keyed, so the canonical decoder surfaces it as a\n // `Map`; a text-keyed look-alike arrives as a plain object and fails the\n // label lookups below.\n const getLabel = (label: number): unknown => {\n if (decoded instanceof Map) return decoded.get(label);\n return undefined;\n };\n const hasLabel = (label: number): boolean => {\n if (decoded instanceof Map) return decoded.has(label);\n return false;\n };\n\n if (hasLabel(-4)) {\n return issueOf(\n 'SIG_PRIVATE_KEY_LEAKED',\n ['sigs', i, 'cose_key'],\n 'cose_key carries COSE_Key private-key material (label -4, the OKP/EC2 private scalar d); publishing a private key on the permanent ledger is forbidden',\n );\n }\n\n const kty = getLabel(1);\n if (kty !== 1) {\n return issueOf(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key kty (label 1) must be 1 (OKP); got ${String(kty)}`,\n );\n }\n const crv = getLabel(-1);\n if (crv !== 6) {\n return issueOf(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key crv (label -1) must be 6 (Ed25519); got ${String(crv)}`,\n );\n }\n const x = getLabel(-2);\n if (!(x instanceof Uint8Array) || x.length !== 32) {\n const got = x instanceof Uint8Array ? `${x.length}-byte bstr` : typeof x;\n return issueOf(\n 'MALFORMED_SIG_COSE_SIGN1',\n ['sigs', i, 'cose_key'],\n `sigs[${i}].cose_key COSE_Key label -2 must be a 32-byte byte string (Ed25519 public key); got ${got}`,\n );\n }\n return null;\n}\n\n// =============================================================================\n// `crit[]` shape + critical-extension support\n// =============================================================================\n\nfunction checkCrit(\n record: PoeRecord,\n decodedTopKeys: ReadonlySet<string>,\n supportedCriticalExtensions: ReadonlySet<string>,\n issues: ValidationIssue[],\n): void {\n if (!Array.isArray(record.crit)) return;\n // `crit` has `1*` cardinality: an empty array is a malformed shape.\n if (record.crit.length === 0) {\n issues.push(\n issueOf(\n 'SCHEMA_TYPE_MISMATCH',\n ['crit'],\n 'crit[] must carry at least one entry when present',\n ),\n );\n return;\n }\n const seen = new Set<string>();\n for (let i = 0; i < record.crit.length; i++) {\n const critName = record.crit[i]!;\n let reason: string | null = null;\n if (TOP_LEVEL_BASE_KEYS.has(critName)) {\n reason = `'${critName}' is a base key and MUST NOT appear in crit[]`;\n } else if (!isExtensionKey(critName)) {\n reason = `'${critName}' does not match the extension-key form (^x-.+ or ^[a-z]+-.+, no control characters)`;\n } else if (!decodedTopKeys.has(critName)) {\n reason = `'${critName}' is named in crit but absent from the record map`;\n } else if (seen.has(critName)) {\n reason = `'${critName}' appears more than once in crit[]`;\n }\n seen.add(critName);\n if (reason !== null) {\n issues.push(issueOf('CRIT_SHAPE_INVALID', ['crit', i], reason));\n continue;\n }\n // Shape-valid entry: accepted iff this validator implements the named\n // extension. The default supported set is empty, so a default-configured\n // validator fails every `crit`-bearing record — by design.\n if (!supportedCriticalExtensions.has(critName)) {\n issues.push(\n issueOf(\n 'EXTENSION_UNSUPPORTED_CRITICAL',\n ['crit', i],\n `crit lists extension '${critName}' that this validator does not implement`,\n ),\n );\n }\n }\n}\n\nfunction topLevelKeysOf(decoded: unknown): Set<string> {\n if (decoded === null || typeof decoded !== 'object') return new Set();\n if (decoded instanceof Map) {\n const out = new Set<string>();\n for (const k of decoded.keys()) {\n if (typeof k === 'string') out.add(k);\n }\n return out;\n }\n return new Set(Object.keys(decoded as Record<string, unknown>));\n}\n\n// =============================================================================\n// Label 309 CID profile\n// =============================================================================\n//\n// Accept CIDv0 (`Qm` prefix, 46-char base58btc, sha2-256 multihash) and\n// CIDv1 (multibase prefix + version 0x01 + codec + multihash) per the\n// closed profile:\n// - Multibase: b, B, f, F, z\n// - Multicodec: 0x55 (raw), 0x70 (dag-pb), 0x71 (dag-cbor)\n// - Multihash: 0x12 (sha2-256, 32 B), 0xb220 (blake2b-256, 32 B)\n//\n// Returns true iff the CID conforms to the Label 309 profile.\n\nconst ACCEPTED_CIDV1_MULTIBASE: ReadonlySet<string> = new Set(['b', 'B', 'f', 'F', 'z']);\n\nconst ACCEPTED_MULTICODECS: ReadonlySet<number> = new Set([0x55, 0x70, 0x71]);\n\n// Multihash table: code → digest length (bytes).\nconst ACCEPTED_MULTIHASHES: ReadonlyMap<number, number> = new Map([\n [0x12, 32],\n [0xb220, 32],\n]);\n\nexport function validateCidProfile(cid: string): boolean {\n if (cid.length === 0) return false;\n // CIDv0: a base58btc-encoded sha2-256 multihash. Decode the WHOLE string\n // and verify the multihash prefix (0x12 = sha2-256, 0x20 = 32-byte digest)\n // and total length (34 bytes); a `Qm` prefix alone is not sufficient.\n if (cid.startsWith('Qm')) {\n let decoded: Uint8Array;\n try {\n decoded = decodeBase58btc(cid);\n } catch {\n return false;\n }\n return decoded.length === 34 && decoded[0] === 0x12 && decoded[1] === 0x20;\n }\n // CIDv1: multibase + binary CID body.\n const mbPrefix = cid[0]!;\n if (!ACCEPTED_CIDV1_MULTIBASE.has(mbPrefix)) return false;\n let bytes: Uint8Array;\n try {\n bytes = decodeMultibase(mbPrefix, cid.slice(1));\n } catch {\n return false;\n }\n if (bytes.length < 4) return false;\n // CIDv1 layout: <version varint> <multicodec varint> <multihash>\n const versionParse = readVarint(bytes, 0);\n if (versionParse === null || versionParse.value !== 1) return false;\n const codecParse = readVarint(bytes, versionParse.next);\n if (codecParse === null) return false;\n if (!ACCEPTED_MULTICODECS.has(codecParse.value)) return false;\n const mhParse = readVarint(bytes, codecParse.next);\n if (mhParse === null) return false;\n const lenParse = readVarint(bytes, mhParse.next);\n if (lenParse === null) return false;\n const digestLen = lenParse.value;\n const expectedLen = ACCEPTED_MULTIHASHES.get(mhParse.value);\n if (expectedLen === undefined || digestLen !== expectedLen) return false;\n if (lenParse.next + digestLen !== bytes.length) return false;\n return true;\n}\n\nfunction readVarint(bytes: Uint8Array, start: number): { value: number; next: number } | null {\n let value = 0;\n let shift = 0;\n let i = start;\n while (i < bytes.length) {\n const b = bytes[i]!;\n value |= (b & 0x7f) << shift;\n i++;\n if ((b & 0x80) === 0) return { value, next: i };\n shift += 7;\n if (shift > 28) return null; // overflow guard; the profile uses ≤ 16-bit codes\n }\n return null;\n}\n\n// Multibase decoders for the closed set the CID profile admits.\nfunction decodeMultibase(prefix: string, body: string): Uint8Array {\n switch (prefix) {\n case 'b':\n return decodeBase32(body.toLowerCase(), 'rfc4648-lower');\n case 'B':\n return decodeBase32(body.toUpperCase(), 'rfc4648-upper');\n case 'f':\n return decodeBase16(body.toLowerCase());\n case 'F':\n return decodeBase16(body.toUpperCase());\n case 'z':\n return decodeBase58btc(body);\n default:\n throw new Error(`unsupported multibase prefix ${prefix}`);\n }\n}\n\nconst BASE16_LOWER = '0123456789abcdef';\nconst BASE16_UPPER = '0123456789ABCDEF';\n\nfunction decodeBase16(s: string): Uint8Array {\n if (s.length % 2 !== 0) throw new Error('base16: odd-length');\n const out = new Uint8Array(s.length / 2);\n const alphabet = s === s.toLowerCase() ? BASE16_LOWER : BASE16_UPPER;\n for (let i = 0; i < out.length; i++) {\n const hi = alphabet.indexOf(s[i * 2]!);\n const lo = alphabet.indexOf(s[i * 2 + 1]!);\n if (hi < 0 || lo < 0) throw new Error(`base16: non-hex char at ${i * 2}`);\n out[i] = (hi << 4) | lo;\n }\n return out;\n}\n\nconst BASE32_RFC4648_LOWER = 'abcdefghijklmnopqrstuvwxyz234567';\nconst BASE32_RFC4648_UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\nfunction decodeBase32(s: string, variant: 'rfc4648-lower' | 'rfc4648-upper'): Uint8Array {\n const alphabet = variant === 'rfc4648-lower' ? BASE32_RFC4648_LOWER : BASE32_RFC4648_UPPER;\n // Multibase strips padding per spec; accept either form for robustness.\n const trimmed = s.replace(/=+$/, '');\n const out: number[] = [];\n let buf = 0;\n let bits = 0;\n for (const ch of trimmed) {\n const idx = alphabet.indexOf(ch);\n if (idx < 0) throw new Error(`base32: invalid char '${ch}'`);\n buf = (buf << 5) | idx;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((buf >> bits) & 0xff);\n }\n }\n return Uint8Array.from(out);\n}\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\nfunction decodeBase58btc(s: string): Uint8Array {\n if (s.length === 0) return new Uint8Array(0);\n let zeros = 0;\n while (zeros < s.length && s[zeros] === '1') zeros++;\n const size = Math.floor(((s.length - zeros) * 733) / 1000) + 1;\n const b256 = new Uint8Array(size);\n let length = 0;\n for (let i = zeros; i < s.length; i++) {\n const ch = s[i]!;\n const carryIdx = BASE58_ALPHABET.indexOf(ch);\n if (carryIdx < 0) throw new Error(`base58: invalid char '${ch}'`);\n let carry = carryIdx;\n let k = 0;\n for (let j = size - 1; (carry !== 0 || k < length) && j >= 0; j--, k++) {\n carry += 58 * b256[j]!;\n b256[j] = carry % 256;\n carry = Math.floor(carry / 256);\n }\n length = k;\n }\n let it = size - length;\n while (it < size && b256[it] === 0) it++;\n const out = new Uint8Array(zeros + (size - it));\n let j = zeros;\n while (it < size) {\n out[j++] = b256[it++]!;\n }\n return out;\n}\n\n// Hex rendering for byte-equality keys (the duplicate-KEM-material set).\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\n// =============================================================================\n// Exact-integer helpers\n// =============================================================================\n\n// A CBOR unsigned integer as the canonical decoder surfaces it: a\n// non-negative `number` for values up to 2^53 − 1, a non-negative `bigint`\n// above (exact in both representations). A negative value is a different\n// CBOR major type and is never a uint.\nfunction isUint(value: unknown): value is number | bigint {\n if (typeof value === 'number') return Number.isInteger(value) && value >= 0;\n if (typeof value === 'bigint') return value >= 0n;\n return false;\n}\n\nfunction uintWithin(value: number | bigint, min: number, max: number): boolean {\n if (typeof value === 'bigint') return value >= BigInt(min) && value <= BigInt(max);\n return value >= min && value <= max;\n}\n\n// =============================================================================\n// Issue construction and deterministic ordering\n// =============================================================================\n\nfunction issueOf(\n code: ErrorCode,\n path: ReadonlyArray<string | number>,\n message: string,\n): ValidationIssue {\n return { code, path, message, severity: SEVERITY[code] };\n}\n\nconst PATH_UTF8 = new TextEncoder();\n\n// Bytewise comparison of the UTF-8 encodings — the only collation that is\n// byte-stable across runs and across language implementations (no locale\n// tables, no UTF-16 code-unit artefacts for non-BMP keys).\nfunction compareTextSegments(a: string, b: string): number {\n const ab = PATH_UTF8.encode(a);\n const bb = PATH_UTF8.encode(b);\n const n = Math.min(ab.length, bb.length);\n for (let i = 0; i < n; i++) {\n const d = ab[i]! - bb[i]!;\n if (d !== 0) return d;\n }\n return ab.length - bb.length;\n}\n\n// Segment-wise path order: integer segments compare numerically, text\n// segments compare by UTF-8 bytes, an integer segment orders before a text\n// segment where the kinds differ, and a strict prefix orders before its\n// extensions. Issues on an identical path tie-break by the position of their\n// code in the canonical error-code registry.\nfunction compareIssues(a: ValidationIssue, b: ValidationIssue): number {\n const ap = a.path;\n const bp = b.path;\n const n = Math.min(ap.length, bp.length);\n for (let i = 0; i < n; i++) {\n const x = ap[i]!;\n const y = bp[i]!;\n const xIsNum = typeof x === 'number';\n const yIsNum = typeof y === 'number';\n if (xIsNum !== yIsNum) return xIsNum ? -1 : 1;\n if (xIsNum && yIsNum) {\n if (x !== y) return (x as number) < (y as number) ? -1 : 1;\n } else {\n const d = compareTextSegments(x as string, y as string);\n if (d !== 0) return d;\n }\n }\n if (ap.length !== bp.length) return ap.length - bp.length;\n return errorCodeRegistryIndex(a.code) - errorCodeRegistryIndex(b.code);\n}\n\nfunction sortIssues(issues: ReadonlyArray<ValidationIssue>): ValidationIssue[] {\n return [...issues].sort(compareIssues);\n}\n\nfunction valueAtPath(root: unknown, path: ReadonlyArray<string | number>): unknown {\n let cur: unknown = root;\n for (const seg of path) {\n if (cur === null || cur === undefined) return undefined;\n if (cur instanceof Map) {\n cur = cur.get(seg);\n continue;\n }\n if (typeof cur !== 'object') return undefined;\n cur = (cur as Record<string | number, unknown>)[seg];\n }\n return cur;\n}\n","// Canonical outbound HTTP wrapper: deny-list short-circuit, protocol/method\n// allowlist, bounded timeout, exp-backoff retry with jitter, audit trail.\n\n// Universal loopback deny-host list a service-independent verifier MUST reject\n// so a record can never be made to \"verify\" only because it reached a loopback\n// address. This default carries no operator-specific entries: a deployment that\n// wants to forbid its own gateway/viewer hosts appends those at construction\n// time. Producers SHOULD pass this through `denyHosts` on every verifier\n// invocation; the wrapper accepts arbitrary lists but exports the canonical\n// loopback set so callers don't duplicate it inline. (RFC-1918 / link-local IP\n// ranges are blocked separately by the SSRF guard, not by this name list.)\nexport const DENY_HOSTS_DEFAULT: ReadonlyArray<string> = ['localhost', '127.0.0.1'];\n\n// Every outbound call carries a purpose tag from the closed set\n// `{cardano, arweave, ipfs}` (the three v1 gateway-chain purposes).\n// `https` is a transitional legacy tag for non-storage HTTPS\n// auxiliaries; new code SHOULD pick one of the three normative purposes.\n// `webhook` is the user-supplied-URL purpose: it triggers the SSRF guard\n// (DNS resolution + IP range check + connection pinning + redirect-chain\n// re-checking + body-size cap), and MUST be used for any fetch where the\n// target URL came from end-user input.\nexport type HttpPurpose = 'cardano' | 'arweave' | 'ipfs' | 'https' | 'webhook';\nexport type HttpMethod = 'GET' | 'POST';\n\nexport interface FetchOutboundOptions {\n readonly method: HttpMethod;\n readonly purpose: HttpPurpose;\n readonly headers?: Readonly<Record<string, string>>;\n readonly body?: string;\n // Hard cap on the response body the primitive will buffer. Gateway content\n // (ar:// / ipfs:// / https) is producer-chosen and therefore UNTRUSTED — the\n // verifier never trusts the producer — so a malicious gateway could otherwise\n // stream unbounded bytes into memory. Omit to use DEFAULT_OUTBOUND_MAX_BYTES.\n readonly maxBytes?: number;\n}\n\nexport interface FetchOutboundResult {\n readonly status: number;\n readonly bytes: Uint8Array;\n readonly durationMs: number;\n}\n\nexport type FetchOutbound = (\n url: string,\n opts: FetchOutboundOptions,\n) => Promise<FetchOutboundResult>;\n\n// Audit-log entry for one outbound HTTP fetch. The field set and names match\n// the verifier report's audit-trail entry exactly, so the record lands on\n// `VerifyReport.auditTrail[]` without a key-renaming pass. `status` is the\n// HTTP status when a response was received and `null` when none was (refused\n// call, transport failure).\nexport interface HttpCallRecord {\n readonly url: string;\n readonly method: HttpMethod;\n readonly status: number | null;\n readonly bytes: number;\n readonly durationMs: number;\n readonly purpose: HttpPurpose;\n}\n\nexport interface RetryConfig {\n readonly timeoutMs?: number;\n readonly retries?: number;\n readonly retryableStatuses?: ReadonlyArray<number>;\n}\n\nexport interface WrapFetchOutboundConfig extends RetryConfig {\n readonly denyHosts?: ReadonlyArray<string>;\n}\n\nexport class DenyHostError extends Error {\n readonly code = 'SERVICE_INDEPENDENCE_VIOLATION';\n readonly host: string;\n readonly url: string;\n constructor(host: string, url: string) {\n super(`SERVICE_INDEPENDENCE_VIOLATION: host \"${host}\" is in denyHosts (url=${url})`);\n this.name = 'DenyHostError';\n this.host = host;\n this.url = url;\n }\n}\n\n// The typed errors discriminate on their stable `code` property, never on\n// class identity: the package ships several entry points in two module\n// formats, so a consumer's `BodyTooLargeError` (thrown by a custom transport\n// that imported it from another entry) is a different class object than the\n// verifier's. `instanceof` is kept as the fast path for the common\n// same-module case.\n\n/** Whether `e` is a deny-host refusal (`SERVICE_INDEPENDENCE_VIOLATION`). */\nexport function isDenyHostError(e: unknown): e is DenyHostError {\n return (\n e instanceof DenyHostError ||\n (typeof e === 'object' &&\n e !== null &&\n (e as { code?: unknown }).code === 'SERVICE_INDEPENDENCE_VIOLATION')\n );\n}\n\n/** Whether `e` is a body-cap abort (`OUTBOUND_BODY_TOO_LARGE`). */\nexport function isBodyTooLargeError(e: unknown): e is BodyTooLargeError {\n return (\n e instanceof BodyTooLargeError ||\n (typeof e === 'object' &&\n e !== null &&\n (e as { code?: unknown }).code === 'OUTBOUND_BODY_TOO_LARGE')\n );\n}\n\nexport class UnsupportedProtocolError extends Error {\n readonly code = 'UNSUPPORTED_PROTOCOL';\n readonly protocol: string;\n readonly url: string;\n constructor(protocol: string, url: string) {\n super(`UNSUPPORTED_PROTOCOL: \"${protocol}\" not in {http:, https:} (url=${url})`);\n this.name = 'UnsupportedProtocolError';\n this.protocol = protocol;\n this.url = url;\n }\n}\n\nexport class UnsupportedMethodError extends Error {\n readonly code = 'UNSUPPORTED_METHOD';\n readonly method: string;\n readonly url: string;\n constructor(method: string, url: string) {\n super(`UNSUPPORTED_METHOD: \"${method}\" not in {GET, POST} (url=${url})`);\n this.name = 'UnsupportedMethodError';\n this.method = method;\n this.url = url;\n }\n}\n\nexport class BodyTooLargeError extends Error {\n readonly code = 'OUTBOUND_BODY_TOO_LARGE';\n readonly url: string;\n readonly limitBytes: number;\n constructor(url: string, limitBytes: number) {\n super(`OUTBOUND_BODY_TOO_LARGE: response exceeded ${limitBytes} bytes (url=${url})`);\n this.name = 'BodyTooLargeError';\n this.url = url;\n this.limitBytes = limitBytes;\n }\n}\n\nexport class OutboundExhaustedError extends Error {\n readonly code = 'OUTBOUND_EXHAUSTED';\n readonly url: string;\n readonly attempts: number;\n readonly lastStatus: number | undefined;\n readonly lastError: Error | undefined;\n constructor(args: {\n url: string;\n attempts: number;\n lastStatus?: number | undefined;\n lastError?: Error | undefined;\n }) {\n super(\n `OUTBOUND_EXHAUSTED: ${args.attempts} attempts exhausted (url=${args.url}, lastStatus=${args.lastStatus ?? '-'})`,\n );\n this.name = 'OutboundExhaustedError';\n this.url = args.url;\n this.attempts = args.attempts;\n this.lastStatus = args.lastStatus;\n this.lastError = args.lastError;\n }\n}\n\nexport const DEFAULT_TIMEOUT_MS = 10_000;\n// Default response-body cap for the verifier's gateway fetches. 64 MiB sits\n// well above any single sealed-PoE ciphertext or merkle-leaf payload a verifier\n// would realistically recompute a hash over, while bounding the memory a hostile\n// gateway can force the verifier to allocate for one request. Callers that\n// legitimately handle larger content raise it per-call via `opts.maxBytes`.\nexport const DEFAULT_OUTBOUND_MAX_BYTES = 64 * 1024 * 1024;\nexport const DEFAULT_RETRYABLE_STATUSES: ReadonlyArray<number> = [502, 503, 504];\nconst BACKOFF_BASE_MS: ReadonlyArray<number> = [1000, 2000, 4000];\nconst JITTER_RATIO = 0.25;\n\nfunction canonicaliseHost(host: string): string {\n return host.replace(/^\\[/, '').replace(/\\]$/, '').replace(/\\.$/, '').toLowerCase();\n}\n\nexport function matchesDenyList(host: string, denyHosts: ReadonlyArray<string>): boolean {\n const h = canonicaliseHost(host);\n for (const raw of denyHosts) {\n const pattern = raw.replace(/\\.$/, '').toLowerCase();\n if (pattern.startsWith('*.')) {\n const suffix = pattern.slice(2);\n if (h.endsWith('.' + suffix)) return true;\n continue;\n }\n if (h === pattern) return true;\n if (pattern === 'localhost') {\n if (h === '::1' || h === '0.0.0.0' || h === '169.254.169.254') return true;\n }\n if (pattern === '127.0.0.1') {\n if (/^127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/.test(h)) return true;\n }\n }\n return false;\n}\n\nfunction parseProtocol(url: string): string | null {\n try {\n return new URL(url).protocol;\n } catch {\n return null;\n }\n}\n\nfunction isAllowedMethod(method: string): method is HttpMethod {\n return method === 'GET' || method === 'POST';\n}\n\nfunction backoffJitteredMs(attemptIndex: number): number {\n const idx = Math.min(attemptIndex, BACKOFF_BASE_MS.length - 1);\n const base = BACKOFF_BASE_MS[idx] ?? BACKOFF_BASE_MS[BACKOFF_BASE_MS.length - 1]!;\n const jitter = 1 + (Math.random() - 0.5) * 2 * JITTER_RATIO;\n return base * jitter;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\nexport const defaultFetchOutbound: FetchOutbound = async (url, opts) => {\n const t0 = Date.now();\n const maxBytes = opts.maxBytes ?? DEFAULT_OUTBOUND_MAX_BYTES;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);\n const init: RequestInit = {\n method: opts.method,\n signal: controller.signal,\n // Redirects are never followed — deny-host and protocol validation ran\n // against the original URL only, so a 3xx from an allowed host could\n // otherwise pivot the fetch to any target (e.g. `302 Location:\n // http://127.0.0.1/…`) behind the verifier's back. Every target must be\n // validated, so a redirect is a fetch failure; all SDKs behave\n // identically. A readable 3xx flows through as a non-2xx status and the\n // caller's attempt handling marks it failed, like a 5xx.\n redirect: 'manual',\n };\n if (opts.headers) init.headers = { ...opts.headers };\n if (opts.body !== undefined) init.body = opts.body;\n try {\n // allow-raw-fetch: canonical defaultFetchOutbound — single egress point\n const res = await fetch(url, init);\n\n // Browser runtimes surface a refused redirect as an opaque response\n // (type 'opaqueredirect', status 0) with no readable status or body;\n // there is nothing to report from it, so it fails like a transport error.\n if (res.type === 'opaqueredirect') {\n throw new Error(`redirect refused (opaqueredirect): ${url} answered with a redirect`);\n }\n\n // Fast path: a truthful Content-Length over the cap lets us bail before\n // reading a single body byte. A lying/absent header is still caught by the\n // streaming counter below — the header is an optimisation, not the guard.\n const declared = res.headers.get('content-length');\n if (declared !== null) {\n const declaredLen = Number(declared);\n if (Number.isFinite(declaredLen) && declaredLen > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n }\n\n const bytes = await readBodyCapped(res, url, maxBytes, controller);\n return { status: res.status, bytes, durationMs: Date.now() - t0 };\n } finally {\n clearTimeout(timeout);\n }\n};\n\n// Stream the response body, aborting the underlying request the instant the\n// running byte count exceeds `maxBytes`. This is the actual OOM guard: a\n// gateway that withholds or lies about Content-Length still cannot make us\n// buffer more than the cap, because we stop reading and tear the socket down.\nasync function readBodyCapped(\n res: Response,\n url: string,\n maxBytes: number,\n controller: AbortController,\n): Promise<Uint8Array> {\n const body = res.body;\n if (body === null) {\n // No stream (e.g. a 204, or a fetch polyfill that buffered eagerly). Fall\n // back to arrayBuffer but still enforce the cap on the materialised length.\n const buf = await res.arrayBuffer();\n if (buf.byteLength > maxBytes) {\n throw new BodyTooLargeError(url, maxBytes);\n }\n return new Uint8Array(buf);\n }\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value === undefined) continue;\n total += value.byteLength;\n if (total > maxBytes) {\n controller.abort();\n throw new BodyTooLargeError(url, maxBytes);\n }\n chunks.push(value);\n }\n } finally {\n reader.releaseLock();\n }\n\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return out;\n}\n\nexport function wrapFetchOutbound(\n inner: FetchOutbound,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig | ReadonlyArray<string> | undefined = undefined,\n): FetchOutbound {\n // Accept either a denyHosts array (positional) or the full config object.\n const normConfig: WrapFetchOutboundConfig =\n config === undefined\n ? {}\n : Array.isArray(config)\n ? { denyHosts: config as ReadonlyArray<string> }\n : (config as WrapFetchOutboundConfig);\n\n const denyHosts = normConfig.denyHosts ?? [];\n // Default retries=0 (single attempt). Callers opt in via explicit `retries`;\n // the top-level `fetchOutbound` entrypoint forwards caller config.\n const retries = normConfig.retries ?? 0;\n const retryableStatuses = normConfig.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES;\n\n return async (url, opts) => {\n // The `webhook` purpose has bespoke requirements (DNS pinning,\n // per-hop redirect re-checking, body-size cap) that the generic\n // wrapper cannot satisfy. Force callers to use `fetchWebhook`\n // instead of silently accepting the call here.\n if (opts.purpose === 'webhook') {\n audit.push({\n url,\n method: 'GET',\n status: null,\n bytes: 0,\n durationMs: 0,\n purpose: opts.purpose,\n });\n throw new Error(\n `webhook purpose must be sent via fetchWebhook, not fetchOutbound (url=${url})`,\n );\n }\n\n // Protocol allowlist.\n const protocol = parseProtocol(url);\n if (protocol !== 'http:' && protocol !== 'https:') {\n audit.push({\n url,\n method: 'GET',\n status: null,\n bytes: 0,\n durationMs: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedProtocolError(protocol ?? '', url);\n }\n\n // Method allowlist.\n if (!isAllowedMethod(opts.method)) {\n audit.push({\n url,\n method: 'GET',\n status: null,\n bytes: 0,\n durationMs: 0,\n purpose: opts.purpose,\n });\n throw new UnsupportedMethodError(opts.method, url);\n }\n\n // Deny-list short-circuit.\n if (denyHosts.length > 0) {\n const host = new URL(url).hostname;\n if (matchesDenyList(host, denyHosts)) {\n audit.push({\n url,\n method: opts.method,\n status: null,\n bytes: 0,\n durationMs: 0,\n purpose: opts.purpose,\n });\n throw new DenyHostError(canonicaliseHost(host), url);\n }\n }\n\n // Retry loop. retries=0 → single attempt, return-or-rethrow original.\n let lastStatus: number | undefined;\n let lastError: Error | undefined;\n const totalAttempts = retries + 1;\n for (let attempt = 1; attempt <= totalAttempts; attempt++) {\n const t0 = Date.now();\n try {\n const result = await inner(url, opts);\n audit.push({\n url,\n method: opts.method,\n status: result.status,\n bytes: result.bytes.byteLength,\n durationMs: result.durationMs,\n purpose: opts.purpose,\n });\n if (retryableStatuses.includes(result.status) && retries > 0) {\n lastStatus = result.status;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n return result;\n } catch (e) {\n const durationMs = Date.now() - t0;\n if (\n e instanceof DenyHostError ||\n e instanceof UnsupportedProtocolError ||\n e instanceof UnsupportedMethodError\n ) {\n audit.push({\n url,\n method: opts.method,\n status: null,\n bytes: 0,\n durationMs,\n purpose: opts.purpose,\n });\n throw e;\n }\n audit.push({\n url,\n method: opts.method,\n status: null,\n bytes: 0,\n durationMs,\n purpose: opts.purpose,\n });\n lastError = e as Error;\n if (attempt < totalAttempts) {\n await sleep(backoffJitteredMs(attempt - 1));\n continue;\n }\n break;\n }\n }\n // Single-attempt mode re-throws the original verbatim so callers can match\n // by identity; retry mode wraps the terminal failure in OutboundExhaustedError.\n if (retries === 0 && lastError !== undefined) {\n throw lastError;\n }\n throw new OutboundExhaustedError({ url, attempts: totalAttempts, lastStatus, lastError });\n };\n}\n\nexport async function fetchOutbound(\n url: string,\n opts: FetchOutboundOptions,\n audit: HttpCallRecord[],\n config: WrapFetchOutboundConfig = {},\n): Promise<FetchOutboundResult> {\n const wrapped = wrapFetchOutbound(defaultFetchOutbound, audit, config);\n return wrapped(url, opts);\n}\n","import { createSHA256 } from 'hash-wasm';\nimport { sha256 as nobleSha256 } from '@noble/hashes/sha2.js';\n\nexport function sha256(input: Uint8Array): Uint8Array {\n return nobleSha256(input);\n}\n\n/**\n * Stream a source through an incremental SHA-256 and return the 32-byte digest,\n * never holding more than one chunk in memory. Use this when the input is too\n * large to buffer (a multi-gigabyte file read in slices), where `sha256(input)`\n * would force the whole input into a single array first.\n */\nexport async function sha256Stream(source: AsyncIterable<Uint8Array>): Promise<Uint8Array> {\n const hasher = await createSHA256();\n hasher.init();\n for await (const chunk of source) {\n hasher.update(chunk);\n }\n return hasher.digest('binary') as Uint8Array;\n}\n","// RFC 9162 §2.1.1 binary Merkle tree under SHA-256.\n// This implements the algorithm tier identified on the wire as the\n// `rfc9162-sha256` OPT-INFO; the record's `merkle[]` field carries the proof.\n//\n// Construction (RFC 9162 §2.1.1):\n// - Single leaf: MTH({d_0}) = SHA-256(0x00 || d_0)\n// - Internal node: MTH(L) = SHA-256(0x01 || MTH(L[0:k]) || MTH(L[k:n]))\n// where k = largest power of 2 strictly less than n.\n// - Empty trees (n == 0) are FORBIDDEN.\n// - The 0x00 leaf / 0x01 internal prefixes prevent the CVE-2012-2459\n// leaf-vs-internal collision family.\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\nimport { compareCt } from '../util/compare-ct';\n\nexport const MERKLE_ALG_ID = 'rfc9162-sha256' as const;\n\nconst LEAF_PREFIX = 0x00;\nconst NODE_PREFIX = 0x01;\nconst DIGEST_LENGTH = 32;\n\nfunction validateLeaves(leaves: ReadonlyArray<Uint8Array>, fnName: string): void {\n if (leaves.length === 0) {\n throw new Error(`${fnName}: empty leaf list (n == 0 is forbidden by RFC 9162 §2.1.1)`);\n }\n for (let i = 0; i < leaves.length; i++) {\n const leaf = leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new Error(\n `${fnName}: leaf[${i}] must be a Uint8Array(${DIGEST_LENGTH}); got length ${\n leaf instanceof Uint8Array ? leaf.length : 'non-Uint8Array'\n }`,\n );\n }\n }\n}\n\nexport function merkleSha2256Root(leaves: ReadonlyArray<Uint8Array>): Uint8Array {\n validateLeaves(leaves, 'merkleSha2256Root');\n return mthRecursive(leaves, 0, leaves.length);\n}\n\nexport function merkleSha2256InclusionProof(\n leaves: ReadonlyArray<Uint8Array>,\n index: number,\n): Uint8Array[] {\n validateLeaves(leaves, 'merkleSha2256InclusionProof');\n if (!Number.isInteger(index) || index < 0 || index >= leaves.length) {\n throw new Error(\n `merkleSha2256InclusionProof: index ${index} out of range [0, ${leaves.length})`,\n );\n }\n return auditPath(leaves, index, 0, leaves.length);\n}\n\n/**\n * Verify an inclusion proof per RFC 9162 §2.1.3.2 (iterative form).\n *\n * `proof` is ordered leaf-to-root: `proof[0]` is the sibling at the leaf\n * level, `proof[m-1]` is the top-level sibling. The fold uses the\n * `sn`/`fn` tracking from RFC 9162: `sn` is the leaf index within the\n * current subtree, `fn` is (subtree_size - 1). At each step, `sn` odd\n * OR `sn == fn` means the current node is a right child (sibling on\n * the left); otherwise it is a left child (sibling on the right).\n * Both shift right by one each iteration. This handles non-power-of-2\n * sizes including the \"promote a lone right subtree\" cases.\n */\nexport function merkleSha2256VerifyInclusion(\n leaf: Uint8Array,\n index: number,\n treeSize: number,\n proof: ReadonlyArray<Uint8Array>,\n root: Uint8Array,\n): boolean {\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) return false;\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) return false;\n if (\n !Number.isInteger(index) ||\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index < 0 ||\n index >= treeSize\n ) {\n return false;\n }\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (!(sibling instanceof Uint8Array) || sibling.length !== DIGEST_LENGTH) {\n return false;\n }\n }\n\n if (treeSize === 1) {\n if (proof.length !== 0 || index !== 0) return false;\n return compareCt(hashLeaf(leaf), root);\n }\n\n let h = hashLeaf(leaf);\n let sn = index;\n let fn = treeSize - 1;\n for (let i = 0; i < proof.length; i++) {\n if (fn === 0) return false;\n const sibling = proof[i] as Uint8Array;\n if ((sn & 1) === 1 || sn === fn) {\n h = hashNode(sibling, h);\n while ((sn & 1) === 0 && sn !== 0) {\n sn >>>= 1;\n fn >>>= 1;\n }\n } else {\n h = hashNode(h, sibling);\n }\n sn >>>= 1;\n fn >>>= 1;\n }\n if (fn !== 0) return false;\n return compareCt(h, root);\n}\n\nfunction largestPow2Lt(n: number): number {\n let k = 1;\n while (k * 2 < n) k *= 2;\n return k;\n}\n\nfunction hashLeaf(d: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + d.length);\n buf[0] = LEAF_PREFIX;\n buf.set(d, 1);\n return sha256(buf);\n}\n\nfunction hashNode(left: Uint8Array, right: Uint8Array): Uint8Array {\n const buf = new Uint8Array(1 + left.length + right.length);\n buf[0] = NODE_PREFIX;\n buf.set(left, 1);\n buf.set(right, 1 + left.length);\n return sha256(buf);\n}\n\nfunction mthRecursive(leaves: ReadonlyArray<Uint8Array>, start: number, end: number): Uint8Array {\n const n = end - start;\n if (n === 1) {\n return hashLeaf(leaves[start] as Uint8Array);\n }\n const k = largestPow2Lt(n);\n const left = mthRecursive(leaves, start, start + k);\n const right = mthRecursive(leaves, start + k, end);\n return hashNode(left, right);\n}\n\nfunction auditPath(\n leaves: ReadonlyArray<Uint8Array>,\n i: number,\n start: number,\n end: number,\n): Uint8Array[] {\n const n = end - start;\n if (n === 1) return [];\n const k = largestPow2Lt(n);\n if (i < k) {\n const subPath = auditPath(leaves, i, start, start + k);\n subPath.push(mthRecursive(leaves, start + k, end));\n return subPath;\n }\n const subPath = auditPath(leaves, i - k, start + k, end);\n subPath.push(mthRecursive(leaves, start, start + k));\n return subPath;\n}\n","// Offline CID decoding for the content-address binding of fetched bytes.\n//\n// Both fetch schemes are content-addressed, so fetched bytes CAN be verified\n// against the URI itself — independently of whichever gateway served them.\n// The binding check decides ATTRIBUTION, and attribution decides what a\n// mismatch means: attributable bytes failing a record commitment condemn the\n// record (URI_INTEGRITY_MISMATCH); unattributable bytes indict only the\n// serving provider (URI_PROVIDER_INTEGRITY_MISMATCH).\n//\n// This implementation verifies the binding for the raw-codec CIDv1 case: the\n// multihash is computed directly over the content bytes, so a plain hash\n// recompute proves the gateway served exactly what the CID addresses. The\n// other forms need block-level verification this SDK does not implement —\n// DAG CIDs (dag-pb / dag-cbor, including every CIDv0) commit to encoded\n// blocks rather than the file bytes a path gateway returns, and `ar://`\n// needs the Arweave data_root chunk tree or the ANS-104 deep-hash — so\n// fetched bytes under those forms stay UNVERIFIED and their mismatches are\n// routed through the provider code, never URI_INTEGRITY_MISMATCH.\n//\n// The accepted multibase / multicodec / multihash sets mirror the normative\n// CID profile (already enforced by the structural validator); anything\n// outside it simply yields `unsupported` here.\n\nimport { blake2b256, sha256 } from '@cardanowall/crypto-core/hash';\n\nconst CODEC_RAW = 0x55;\nconst MULTIHASH_SHA2_256 = 0x12;\nconst MULTIHASH_BLAKE2B_256 = 0xb220;\n\nexport interface ParsedCid {\n readonly version: 0 | 1;\n readonly codec: number;\n readonly multihashCode: number;\n readonly digest: Uint8Array;\n}\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: ReadonlyMap<string, number> = new Map(\n Array.from(BASE58_ALPHABET, (c, i) => [c, i] as const),\n);\n\nfunction base58Decode(input: string): Uint8Array | null {\n if (input.length === 0) return null;\n const bytes: number[] = [0];\n for (const ch of input) {\n const value = BASE58_INDEX.get(ch);\n if (value === undefined) return null;\n let carry = value;\n for (let i = 0; i < bytes.length; i++) {\n const x = bytes[i]! * 58 + carry;\n bytes[i] = x & 0xff;\n carry = x >> 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n // Leading '1' characters encode leading zero bytes.\n for (const ch of input) {\n if (ch !== '1') break;\n bytes.push(0);\n }\n return new Uint8Array(bytes.reverse());\n}\n\nconst BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';\nconst BASE32_INDEX: ReadonlyMap<string, number> = new Map(\n Array.from(BASE32_ALPHABET, (c, i) => [c, i] as const),\n);\n\nfunction base32Decode(input: string): Uint8Array | null {\n let bits = 0;\n let acc = 0;\n const out: number[] = [];\n for (const ch of input) {\n const value = BASE32_INDEX.get(ch);\n if (value === undefined) return null;\n acc = (acc << 5) | value;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((acc >> bits) & 0xff);\n }\n }\n // Trailing bits must be zero padding only.\n if ((acc & ((1 << bits) - 1)) !== 0) return null;\n return new Uint8Array(out);\n}\n\nfunction base16Decode(input: string): Uint8Array | null {\n if (input.length % 2 !== 0 || !/^[0-9a-f]*$/.test(input)) return null;\n const out = new Uint8Array(input.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(input.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nfunction readVarint(bytes: Uint8Array, pos: number): { value: number; next: number } | null {\n let value = 0;\n let shift = 0;\n let p = pos;\n for (;;) {\n if (p >= bytes.length || shift > 28) return null;\n const b = bytes[p]!;\n value |= (b & 0x7f) << shift;\n p += 1;\n if ((b & 0x80) === 0) return { value: value >>> 0, next: p };\n shift += 7;\n }\n}\n\n/**\n * Decode the authority component of an `ipfs://` URI into its CID fields.\n * Returns `null` for anything outside the profile's multibase set or for\n * undecodable input — callers treat that exactly like an unsupported binding.\n */\nexport function parseCid(cid: string): ParsedCid | null {\n if (cid.length === 0) return null;\n\n // CIDv0: fixed base58btc \"Qm…\" shape, an implied dag-pb + sha2-256 multihash.\n if (cid.startsWith('Qm') && cid.length === 46) {\n const decoded = base58Decode(cid);\n if (decoded === null || decoded.length !== 34) return null;\n if (decoded[0] !== MULTIHASH_SHA2_256 || decoded[1] !== 32) return null;\n return {\n version: 0,\n codec: 0x70,\n multihashCode: MULTIHASH_SHA2_256,\n digest: decoded.slice(2),\n };\n }\n\n const prefix = cid[0]!;\n const body = cid.slice(1);\n let decoded: Uint8Array | null;\n switch (prefix) {\n case 'b':\n decoded = base32Decode(body);\n break;\n case 'B':\n decoded = base32Decode(body.toLowerCase());\n break;\n case 'f':\n decoded = base16Decode(body);\n break;\n case 'F':\n decoded = base16Decode(body.toLowerCase());\n break;\n case 'z':\n decoded = base58Decode(body);\n break;\n default:\n return null;\n }\n if (decoded === null) return null;\n\n const version = readVarint(decoded, 0);\n if (version === null || version.value !== 1) return null;\n const codec = readVarint(decoded, version.next);\n if (codec === null) return null;\n const mhCode = readVarint(decoded, codec.next);\n if (mhCode === null) return null;\n const mhLength = readVarint(decoded, mhCode.next);\n if (mhLength === null) return null;\n const digest = decoded.slice(mhLength.next);\n if (digest.length !== mhLength.value) return null;\n return { version: 1, codec: codec.value, multihashCode: mhCode.value, digest };\n}\n\nexport type CidBindingOutcome = 'verified' | 'failed' | 'unsupported';\n\n/**\n * The minimum binding check: for a raw-codec CIDv1 with no path component,\n * recompute the multihash directly over the fetched bytes and compare it to\n * the CID's digest. Everything else — CIDv0, DAG codecs, a path component\n * (which navigates a DAG the raw recompute cannot reproduce), an\n * out-of-profile multihash — is `unsupported`: the bytes stay unattributed\n * and a mismatch indicts the provider, never the record.\n */\nexport function verifyIpfsCidBinding(args: {\n readonly cid: string;\n readonly path: string; // '' when the URI carries no path component\n readonly bytes: Uint8Array;\n}): CidBindingOutcome {\n if (args.path !== '') return 'unsupported';\n const parsed = parseCid(args.cid);\n if (parsed === null || parsed.version !== 1 || parsed.codec !== CODEC_RAW) {\n return 'unsupported';\n }\n let computed: Uint8Array;\n if (parsed.multihashCode === MULTIHASH_SHA2_256) {\n computed = sha256(args.bytes);\n } else if (parsed.multihashCode === MULTIHASH_BLAKE2B_256) {\n computed = blake2b256(args.bytes);\n } else {\n return 'unsupported';\n }\n if (computed.length !== parsed.digest.length) return 'failed';\n for (let i = 0; i < computed.length; i++) {\n if (computed[i] !== parsed.digest[i]) return 'failed';\n }\n return 'verified';\n}\n","// Content acquisition with attribution — the shared engine behind the three\n// fetching consumers (plain-item digests, Merkle leaves-lists, sealed\n// ciphertext).\n//\n// Multiple URIs are alternative sources for the same bytes, processed\n// first-success-for-availability: sources are yielded in order (caller-\n// supplied out-of-band bytes first, then each URI against its scheme's\n// gateway chain) and the consumer stops at the first source satisfying its\n// claim. Every yielded blob knows its ATTRIBUTION — whether the bytes are\n// bound to the URI's content address (or were supplied out-of-band) — which\n// decides whether a mismatch condemns the record or merely indicts the\n// serving provider:\n//\n// * out-of-band bytes → attributable;\n// * ipfs:// raw-codec CIDv1 → attributable iff the multihash recompute\n// over the fetched bytes verifies;\n// * everything else fetched → unattributable (no binding check\n// implemented for ar:// L1 / ANS-104 or\n// DAG-form CIDs), so mismatches route\n// through URI_PROVIDER_INTEGRITY_MISMATCH.\n//\n// Per-attempt diagnostics land in the issue sink (URI_FETCH_FAILED warnings,\n// URI_TARGET_FORBIDDEN refusals, SERVICE_INDEPENDENCE_VIOLATION on a denied\n// host), each at the claim's `uris[j]` path; the per-claim END-state\n// (CONTENT_UNAVAILABLE vs CONTENT_FETCH_LIMIT_EXCEEDED vs the claim-specific\n// availability code) is the consumer's to emit, with `flags.limitExceeded`\n// recording whether an attempt aborted at the `maxFetchBytes` ceiling. A\n// ceiling abort ENDS the claim: every URI of a claim addresses the same\n// bytes, so any other honest source would abort at the same ceiling.\n\nimport { isBodyTooLargeError, isDenyHostError } from '../fetch/fetch-outbound';\nimport { verifyIpfsCidBinding } from './cid';\nimport type { IssuePath, IssueSink } from './issues';\nimport type { FetchOutbound } from './types';\n\n// Default Arweave gateway rotation. IPFS has NO baked-in default: IPFS\n// gateways are not the producer's storage provider, and a silent fallback\n// would couple the verifier to an off-record gateway — a deployment that\n// fetches ipfs:// must configure its own chain, and one that does not is a\n// deployment that declines IPFS (URI_TARGET_FORBIDDEN at fetch time).\nexport const ARWEAVE_GATEWAY_DEFAULTS: ReadonlyArray<string> = [\n 'https://arweave.net',\n 'https://ar-io.net',\n 'https://g8way.io',\n];\n\nconst ARWEAVE_TXID_RE = /^[A-Za-z0-9_-]{43}$/;\n\nexport interface ContentFetchContext {\n readonly fetchFn: FetchOutbound;\n readonly arweaveGateways: ReadonlyArray<string>;\n readonly ipfsGateways: ReadonlyArray<string>;\n readonly maxFetchBytes?: number | undefined;\n readonly issues: IssueSink;\n}\n\nexport interface AcquiredBlob {\n readonly bytes: Uint8Array;\n readonly source: 'out_of_band' | 'fetched';\n readonly uri?: string;\n // The `uris[]` index of the source URI, absent for out-of-band bytes.\n readonly uriIndex?: number;\n // Lazily computed (and memoized) content-address binding: the digest work\n // only runs when a consumer actually needs attribution, i.e. on the\n // mismatch path. Bytes that satisfy the record's own commitment never need\n // it — the record's commitment is at least as strong as the storage\n // layer's.\n readonly attributable: () => boolean;\n}\n\nexport interface BlobIterationFlags {\n limitExceeded: boolean;\n}\n\ninterface ParsedFetchUri {\n readonly scheme: 'ar' | 'ipfs';\n // ar: the txid. ipfs: the CID (authority).\n readonly address: string;\n // ipfs only: the '/'-prefixed path within the DAG, '' when absent.\n readonly path: string;\n}\n\n// Scheme matching is case-insensitive (the scheme alone is folded); the\n// remainder of the URI is a case-sensitive content address and is used\n// verbatim.\nfunction parseFetchUri(uri: string): ParsedFetchUri | null {\n const m = /^([A-Za-z][A-Za-z0-9+.-]*):\\/\\//.exec(uri);\n if (m === null) return null;\n const scheme = m[1]!.toLowerCase();\n const rest = uri.slice(m[0].length);\n if (scheme === 'ar') {\n if (!ARWEAVE_TXID_RE.test(rest)) return null;\n return { scheme: 'ar', address: rest, path: '' };\n }\n if (scheme === 'ipfs') {\n const slash = rest.indexOf('/');\n if (slash === -1) return { scheme: 'ipfs', address: rest, path: '' };\n return { scheme: 'ipfs', address: rest.slice(0, slash), path: rest.slice(slash) };\n }\n return null;\n}\n\nfunction joinGateway(base: string, suffix: string): string {\n return base.endsWith('/') ? `${base}${suffix}` : `${base}/${suffix}`;\n}\n\n/**\n * Yield candidate blobs for one claim, in source order: caller-supplied\n * out-of-band bytes first, then (when `allowFetch`) each URI in record order\n * against its scheme's gateway chain, first 200 per URI. The consumer breaks\n * out at the first acceptable blob; exhaustion of the generator means the\n * claim is left unchecked and the consumer emits the applicable availability\n * end-state.\n */\nexport async function* iterateBlobSources(args: {\n readonly outOfBand?: Uint8Array | undefined;\n readonly uris: ReadonlyArray<string>;\n readonly allowFetch: boolean;\n readonly basePath: IssuePath;\n readonly ctx: ContentFetchContext;\n readonly flags: BlobIterationFlags;\n}): AsyncGenerator<AcquiredBlob> {\n const { ctx } = args;\n if (args.outOfBand !== undefined) {\n const bytes = args.outOfBand;\n yield { bytes, source: 'out_of_band', attributable: () => true };\n }\n if (!args.allowFetch) return;\n\n for (let uriIndex = 0; uriIndex < args.uris.length; uriIndex++) {\n const uri = args.uris[uriIndex]!;\n const uriPath: IssuePath = [...args.basePath, 'uris', uriIndex];\n const parsed = parseFetchUri(uri);\n if (parsed === null) {\n // Defence-in-depth: a target outside the closed fetch set can only\n // reach here by bypassing structural validation.\n ctx.issues.add(\n 'URI_TARGET_FORBIDDEN',\n uriPath,\n `refusing to fetch \"${uri}\": not a conformant ar:// or ipfs:// content address`,\n );\n continue;\n }\n\n let gateways: ReadonlyArray<string>;\n let urlFor: (gateway: string) => string;\n let purpose: 'arweave' | 'ipfs';\n if (parsed.scheme === 'ar') {\n gateways = ctx.arweaveGateways;\n urlFor = (gw) => joinGateway(gw, parsed.address);\n purpose = 'arweave';\n } else {\n gateways = ctx.ipfsGateways;\n urlFor = (gw) => joinGateway(gw, `ipfs/${parsed.address}${parsed.path}`);\n purpose = 'ipfs';\n if (gateways.length === 0) {\n // This deployment declines every IPFS fetch — a policy statement\n // about the verifier, never about the record.\n ctx.issues.add(\n 'URI_TARGET_FORBIDDEN',\n uriPath,\n `refusing to fetch \"${uri}\": no IPFS gateway chain is configured`,\n );\n continue;\n }\n }\n\n for (const gateway of gateways) {\n const url = urlFor(gateway);\n let bytes: Uint8Array;\n try {\n const res = await ctx.fetchFn(url, {\n method: 'GET',\n purpose,\n ...(ctx.maxFetchBytes !== undefined ? { maxBytes: ctx.maxFetchBytes } : {}),\n });\n if (res.status !== 200) {\n ctx.issues.add(\n 'URI_FETCH_FAILED',\n uriPath,\n `fetch of \"${uri}\" via ${gateway} returned HTTP ${res.status}`,\n );\n continue;\n }\n bytes = res.bytes;\n } catch (e) {\n if (isBodyTooLargeError(e)) {\n // Aborted at the deployment's per-URI fetch ceiling. Every URI of\n // a claim addresses the same bytes, so any other honest source\n // would abort at the same ceiling: end the claim. The consumer's\n // end-state surfaces CONTENT_FETCH_LIMIT_EXCEEDED.\n args.flags.limitExceeded = true;\n return;\n }\n if (isDenyHostError(e)) {\n // The egress hard-failed the call against the deny-host list. A\n // per-attempt error-severity issue (verdict `failed` via severity);\n // the remaining sources are still tried so the report shows every\n // violating target.\n ctx.issues.add(\n 'SERVICE_INDEPENDENCE_VIOLATION',\n uriPath,\n `outbound call to ${url} targets a denyHosts entry`,\n );\n continue;\n }\n ctx.issues.add(\n 'URI_FETCH_FAILED',\n uriPath,\n `fetch of \"${uri}\" via ${gateway} failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n continue;\n }\n\n let binding: 'verified' | 'failed' | 'unsupported' | null = null;\n const attributable = (): boolean => {\n if (binding === null) {\n binding =\n parsed.scheme === 'ipfs'\n ? verifyIpfsCidBinding({ cid: parsed.address, path: parsed.path, bytes })\n : 'unsupported';\n }\n return binding === 'verified';\n };\n yield { bytes, source: 'fetched', uri, uriIndex, attributable };\n // The consumer pulled the next source: this blob did not settle the\n // claim (an unattributable mismatch indicts the gateway, not the\n // address), so the remaining gateways of the same URI are tried next.\n }\n }\n}\n\n/**\n * The issue path for an unattributable provider mismatch: the source URI when\n * the blob was fetched, the claim base path otherwise.\n */\nexport function providerMismatchPath(basePath: IssuePath, blob: AcquiredBlob): IssuePath {\n return blob.uriIndex !== undefined ? [...basePath, 'uris', blob.uriIndex] : basePath;\n}\n","// Position-aware CBOR walker for byte-faithful transaction dissection.\n//\n// The verifier MUST fetch raw transaction CBOR and slice its components\n// VERBATIM (never decode-then-re-encode). A re-encode pass would silently\n// launder a non-conformant on-chain record into a conformant one — a CBOR\n// decoder normalises non-canonical input (sorts map keys, collapses\n// indefinite-length encodings) — and would break both integrity bindings,\n// which are defined over the bytes exactly as fetched:\n//\n// * blake2b-256(transaction-body bytes) == the transaction id;\n// * blake2b-256(auxiliary-data bytes) == the body's auxiliary_data_hash.\n//\n// This module owns three byte-level concerns:\n//\n// * `sliceTxComponents` — split a transaction into the exact body /\n// witness-set / auxiliary-data byte slices.\n// * `unwrapAuxiliaryData` — unwrap auxiliary-data bytes down to the\n// raw label-309 value, accepting all three\n// Conway-era envelope forms and dispatching\n// on the top-level CBOR type and tag ONLY\n// (never on map-key inspection).\n// * `auxiliaryDataHashFromTxBody` — read the body's `auxiliary_data_hash`\n// field (key 7) for the integrity binding.\n//\n// Chunk-array reassembly of the label-309 value is NOT here: it is the\n// shared transport step `reassembleLabel309Value` in\n// `@cardanowall/poe-standard/carriage`.\n\ninterface CborHead {\n readonly mt: number;\n readonly ai: number;\n readonly payloadStart: number;\n readonly valueU64: number;\n}\n\nfunction readHead(bytes: Uint8Array, pos: number): CborHead {\n if (pos >= bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated input (no head byte)');\n }\n const head = bytes[pos]!;\n const mt = head >> 5;\n const ai = head & 0x1f;\n let p = pos + 1;\n let valueU64: number;\n\n if (ai < 24) {\n valueU64 = ai;\n } else if (ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 1-byte argument');\n }\n valueU64 = bytes[p]!;\n p += 1;\n } else if (ai === 25) {\n if (p + 2 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 2-byte argument');\n }\n valueU64 = (bytes[p]! << 8) | bytes[p + 1]!;\n p += 2;\n } else if (ai === 26) {\n if (p + 4 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 4-byte argument');\n }\n valueU64 =\n bytes[p]! * 0x1000000 + ((bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!);\n p += 4;\n } else if (ai === 27) {\n if (p + 8 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated 8-byte argument');\n }\n let n = 0;\n for (let k = 0; k < 8; k++) n = n * 256 + bytes[p + k]!;\n if (n > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('MALFORMED_CBOR: 8-byte argument exceeds JavaScript safe integer range');\n }\n valueU64 = n;\n p += 8;\n } else if (ai === 31) {\n throw new RangeError(\n 'MALFORMED_CBOR: indefinite-length encoding (ai=31) not allowed under canonical CBOR',\n );\n } else {\n throw new RangeError(`MALFORMED_CBOR: reserved additional info ai=${ai}`);\n }\n\n return { mt, ai, payloadStart: p, valueU64 };\n}\n\nfunction skipCborItem(bytes: Uint8Array, pos: number): number {\n const h = readHead(bytes, pos);\n let p = h.payloadStart;\n switch (h.mt) {\n case 0:\n case 1:\n return p;\n case 2:\n case 3:\n if (p + h.valueU64 > bytes.length) {\n throw new RangeError(\n `MALFORMED_CBOR: truncated ${h.mt === 2 ? 'byte' : 'text'} string payload`,\n );\n }\n return p + h.valueU64;\n case 4:\n for (let i = 0; i < h.valueU64; i++) p = skipCborItem(bytes, p);\n return p;\n case 5:\n for (let i = 0; i < h.valueU64 * 2; i++) p = skipCborItem(bytes, p);\n return p;\n case 6:\n return skipCborItem(bytes, p);\n case 7: {\n if (h.ai < 24) return p;\n if (h.ai === 24) {\n if (p + 1 > bytes.length) {\n throw new RangeError('MALFORMED_CBOR: truncated simple value');\n }\n return p + 1;\n }\n if (h.ai === 25 || h.ai === 26 || h.ai === 27) return p;\n throw new RangeError(`MALFORMED_CBOR: unsupported major-7 ai=${h.ai}`);\n }\n default:\n throw new RangeError(`MALFORMED_CBOR: unknown major type ${h.mt}`);\n }\n}\n\n// CBOR tag 259 wraps the keyed-map auxiliary-data form (Conway).\nconst CARDANO_AUX_DATA_TAG = 259;\nconst POE_LABEL = 309;\nconst AUX_DATA_HASH_BODY_KEY = 7;\n\n/**\n * Byte-faithful components of a Cardano transaction, located by walking the\n * tx CBOR without a decode-then-re-encode pass.\n *\n * Every field is an EXACT on-chain byte slice: `blake2b256(txBody)` equals the\n * transaction id, `blake2b256(auxiliaryData)` equals the body's\n * `auxiliary_data_hash`, and the witness set decodes to the vkey witnesses\n * that authorised the transaction. `auxiliaryData` is `null` when the\n * transaction carries none (CBOR null/undefined at the auxiliary-data\n * position).\n */\nexport interface TxComponents {\n readonly txBody: Uint8Array;\n readonly witnessSet: Uint8Array;\n readonly auxiliaryData: Uint8Array | null;\n}\n\n/**\n * Walk the transaction CBOR once and return its byte-faithful components.\n * Accepts the four-element post-Alonzo shape `[body, witness_set, is_valid,\n * auxiliary_data]` and the three-element pre-Alonzo shape\n * `[body, witness_set, auxiliary_data]`. Throws\n * `RangeError(\"MALFORMED_CBOR: …\")` on structural violations.\n */\nexport function sliceTxComponents(txCbor: Uint8Array): TxComponents {\n const txHead = readHead(txCbor, 0);\n if (txHead.mt !== 4) {\n throw new RangeError(`MALFORMED_CBOR: tx CBOR is not a CBOR array (major type ${txHead.mt})`);\n }\n if (txHead.valueU64 !== 3 && txHead.valueU64 !== 4) {\n throw new RangeError(\n `MALFORMED_CBOR: tx CBOR array has ${txHead.valueU64} elements; expected 3 ([body, witness_set, auxiliary_data]) or 4 ([body, witness_set, is_valid, auxiliary_data])`,\n );\n }\n\n const bodyStart = txHead.payloadStart;\n const bodyEnd = skipCborItem(txCbor, bodyStart);\n const witnessSetStart = bodyEnd;\n const witnessSetEnd = skipCborItem(txCbor, witnessSetStart);\n const auxStart = txHead.valueU64 === 4 ? skipCborItem(txCbor, witnessSetEnd) : witnessSetEnd; // skip is_valid in the four-element shape\n\n const txBody = txCbor.slice(bodyStart, bodyEnd);\n const witnessSet = txCbor.slice(witnessSetStart, witnessSetEnd);\n\n if (auxStart >= txCbor.length) {\n throw new RangeError('MALFORMED_CBOR: truncated tx (auxiliary_data missing)');\n }\n const auxFirstByte = txCbor[auxStart]!;\n if (auxFirstByte === 0xf6 || auxFirstByte === 0xf7) {\n return { txBody, witnessSet, auxiliaryData: null };\n }\n const auxEnd = skipCborItem(txCbor, auxStart);\n return { txBody, witnessSet, auxiliaryData: txCbor.slice(auxStart, auxEnd) };\n}\n\n/**\n * The unwrapped view of one auxiliary-data value: the raw label-309 value\n * bytes (the transport chunk array exactly as carried; `null` when the\n * metadata carries no label-309 entry) plus the ascending-sorted list of\n * every metadata label present.\n */\nexport interface UnwrappedAuxiliaryData {\n readonly label309: Uint8Array | null;\n readonly metadataLabels: ReadonlyArray<number>;\n}\n\n/**\n * Unwrap auxiliary-data bytes down to the label-309 value. All three\n * Conway-era envelope forms are accepted, dispatching PURELY on the top-level\n * CBOR type and tag:\n *\n * * tag 259 → keyed map; the metadata map sits under integer key 0;\n * * untagged array → the two-element `[ transaction_metadata,\n * auxiliary_scripts ]` form; the metadata map is\n * element 0;\n * * untagged map → ALWAYS the metadata map itself.\n *\n * Map keys are never inspected to guess the shape — a metadata map is keyed\n * by integer labels, so any key-sniffing heuristic would silently mis-parse\n * legitimate metadata (e.g. a metadata map whose only label is 0). Any other\n * top-level shape, and any tag other than 259, throws\n * `RangeError(\"MALFORMED_CBOR: …\")`.\n *\n * A tag-259 map with no key 0, and a metadata map with no entry under label\n * 309, are well-formed auxiliary data that simply carry no PoE record —\n * `label309` is `null` and the caller emits METADATA_NOT_FOUND.\n */\nexport function unwrapAuxiliaryData(auxBytes: Uint8Array): UnwrappedAuxiliaryData {\n const head = readHead(auxBytes, 0);\n let metadataMapPos: number | null;\n\n if (head.mt === 6) {\n if (head.valueU64 !== CARDANO_AUX_DATA_TAG) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary data carries CBOR tag ${head.valueU64}; only tag ${CARDANO_AUX_DATA_TAG} is an auxiliary-data envelope`,\n );\n }\n const inner = readHead(auxBytes, head.payloadStart);\n if (inner.mt !== 5) {\n throw new RangeError(\n `MALFORMED_CBOR: tag-${CARDANO_AUX_DATA_TAG} auxiliary data must wrap a map (major type ${inner.mt})`,\n );\n }\n // Find integer key 0 (the transaction_metadata entry); other keys carry\n // scripts and are skipped without inspection.\n metadataMapPos = null;\n let entryPos = inner.payloadStart;\n for (let i = 0; i < inner.valueU64; i++) {\n const keyHead = readHead(auxBytes, entryPos);\n const valuePos = skipCborItem(auxBytes, entryPos);\n if (keyHead.mt === 0 && keyHead.valueU64 === 0) {\n metadataMapPos = valuePos;\n }\n entryPos = skipCborItem(auxBytes, valuePos);\n }\n } else if (head.mt === 4) {\n if (head.valueU64 !== 2) {\n throw new RangeError(\n `MALFORMED_CBOR: untagged auxiliary-data array must be the two-element [transaction_metadata, auxiliary_scripts] form (got ${head.valueU64} elements)`,\n );\n }\n metadataMapPos = head.payloadStart;\n } else if (head.mt === 5) {\n // An untagged map is always the metadata map itself.\n metadataMapPos = 0;\n } else {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary data has major type ${head.mt}; expected map, array, or tag ${CARDANO_AUX_DATA_TAG}`,\n );\n }\n\n if (metadataMapPos === null) {\n return { label309: null, metadataLabels: [] };\n }\n\n const metaHead = readHead(auxBytes, metadataMapPos);\n if (metaHead.mt !== 5) {\n throw new RangeError(\n `MALFORMED_CBOR: transaction metadata is not a CBOR map (major type ${metaHead.mt})`,\n );\n }\n const labels: number[] = [];\n let label309: Uint8Array | null = null;\n let pairPos = metaHead.payloadStart;\n for (let i = 0; i < metaHead.valueU64; i++) {\n const keyHead = readHead(auxBytes, pairPos);\n // The ledger pins metadata labels as unsigned integers; any other key\n // type cannot appear in on-chain transaction metadata.\n if (keyHead.mt !== 0) {\n throw new RangeError(\n `MALFORMED_CBOR: metadata map key has major type ${keyHead.mt}; metadata labels are unsigned integers`,\n );\n }\n const keyVal = keyHead.valueU64;\n labels.push(keyVal);\n const valueStart = skipCborItem(auxBytes, pairPos);\n const valueEnd = skipCborItem(auxBytes, valueStart);\n if (keyVal === POE_LABEL) {\n label309 = auxBytes.slice(valueStart, valueEnd);\n }\n pairPos = valueEnd;\n }\n labels.sort((a, b) => a - b);\n return { label309, metadataLabels: labels };\n}\n\n/**\n * Read the transaction body's `auxiliary_data_hash` (body-map key 7) as an\n * exact byte slice; `null` when the body carries no key 7. Throws\n * `RangeError(\"MALFORMED_CBOR: …\")` when the body is not a CBOR map.\n */\nexport function auxiliaryDataHashFromTxBody(txBody: Uint8Array): Uint8Array | null {\n const head = readHead(txBody, 0);\n if (head.mt !== 5) {\n throw new RangeError(\n `MALFORMED_CBOR: transaction body is not a CBOR map (major type ${head.mt})`,\n );\n }\n let pairPos = head.payloadStart;\n for (let i = 0; i < head.valueU64; i++) {\n const keyHead = readHead(txBody, pairPos);\n const valueStart = skipCborItem(txBody, pairPos);\n const valueEnd = skipCborItem(txBody, valueStart);\n if (keyHead.mt === 0 && keyHead.valueU64 === AUX_DATA_HASH_BODY_KEY) {\n const valueHead = readHead(txBody, valueStart);\n if (valueHead.mt !== 2) {\n throw new RangeError(\n `MALFORMED_CBOR: auxiliary_data_hash (body key 7) is not a byte string (major type ${valueHead.mt})`,\n );\n }\n return txBody.slice(valueHead.payloadStart, valueEnd);\n }\n pairPos = valueEnd;\n }\n return null;\n}\n","// Plain-item content verification (non-`enc` items).\n//\n// For each item that proceeds to fetch, the verifier resolves the item's URIs\n// in order against the scheme-appropriate gateway chain and checks every\n// digest in `item.hashes` against the fetched bytes —\n// first-success-for-availability, with the integrity / attribution /\n// availability split:\n//\n// * bytes satisfying every committed digest → contentCheck `checked`\n// (no binding check needed — the record's commitment is at least as\n// strong as the storage layer's);\n// * ATTRIBUTABLE bytes failing a digest → URI_INTEGRITY_MISMATCH\n// (error, record-attributable, verdict `failed`) — one provably\n// mismatching URI condemns the record even if a sibling URI matches,\n// because the producer asserted at publication that every listed URI\n// resolves to committed bytes;\n// * UNATTRIBUTABLE bytes failing a digest → URI_PROVIDER_INTEGRITY_MISMATCH\n// (warning, provider-attributable) and the remaining sources are tried;\n// * sources exhausted with nothing attributable → CONTENT_UNAVAILABLE\n// (or CONTENT_FETCH_LIMIT_EXCEEDED when an attempt aborted at the fetch\n// ceiling) — network class, claim unchecked, verdict `unverifiable`.\n//\n// A hash-only item (no URIs) has nothing to fetch: its claim is reported\n// `not_checked` with no availability issue — nothing failed, nothing was\n// expected to be fetched. Sealed (`enc`-bearing) items never enter this step;\n// their plaintext claim is checked by the decryption step's post-decryption\n// recheck.\n\nimport { blake2b256, sha256 } from '@cardanowall/crypto-core/hash';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { ItemEntry } from '@cardanowall/poe-standard';\n\nimport {\n iterateBlobSources,\n providerMismatchPath,\n type BlobIterationFlags,\n type ContentFetchContext,\n} from './content';\nimport type { ContentCheck } from './types';\n\n// True iff every entry of the item's `hashes` map recomputes over `bytes`.\n// The structural validator guarantees registry membership of every key, so an\n// unknown algorithm reaching here is a defensive no-certify, not a wire case.\nexport function recomputeItemHashes(\n hashes: Readonly<Record<string, Uint8Array>>,\n bytes: Uint8Array,\n): boolean {\n const entries = Object.entries(hashes);\n if (entries.length === 0) return false;\n for (const [alg, digest] of entries) {\n if (alg === 'sha2-256') {\n if (!compareCt(sha256(bytes), digest)) return false;\n } else if (alg === 'blake2b-256') {\n if (!compareCt(blake2b256(bytes), digest)) return false;\n } else {\n return false;\n }\n }\n return true;\n}\n\nexport async function checkItemContent(args: {\n readonly item: ItemEntry;\n readonly itemIndex: number;\n readonly fetchContent: boolean;\n readonly ctx: ContentFetchContext;\n}): Promise<ContentCheck> {\n const { item, itemIndex, ctx } = args;\n if (!args.fetchContent) return 'not_checked';\n\n const uris = item.uris ?? [];\n if (uris.length === 0) return 'not_checked';\n\n const basePath = ['items', itemIndex];\n const flags: BlobIterationFlags = { limitExceeded: false };\n for await (const blob of iterateBlobSources({\n uris,\n allowFetch: true,\n basePath,\n ctx,\n flags,\n })) {\n if (recomputeItemHashes(item.hashes, blob.bytes)) {\n return 'checked';\n }\n if (blob.attributable()) {\n ctx.issues.add(\n 'URI_INTEGRITY_MISMATCH',\n basePath,\n `attributable bytes fetched from \"${blob.uri ?? 'out-of-band input'}\" do not satisfy the item's hashes commitment`,\n );\n return 'mismatched';\n }\n ctx.issues.add(\n 'URI_PROVIDER_INTEGRITY_MISMATCH',\n providerMismatchPath(basePath, blob),\n `bytes fetched from \"${blob.uri ?? 'unknown source'}\" do not satisfy the item's hashes commitment and could not be attributed to the URI's content address; the serving provider is indicted, not the record`,\n );\n }\n\n if (flags.limitExceeded) {\n ctx.issues.add(\n 'CONTENT_FETCH_LIMIT_EXCEEDED',\n basePath,\n `a fetch for this item was aborted at the deployment's maxFetchBytes ceiling${ctx.maxFetchBytes !== undefined ? ` (${ctx.maxFetchBytes} bytes)` : ''}; the claim is unchecked`,\n );\n } else {\n ctx.issues.add(\n 'CONTENT_UNAVAILABLE',\n basePath,\n 'the URI list was exhausted with no attributable bytes satisfying the commitment; the claim is unchecked',\n );\n }\n return 'not_checked';\n}\n","// Sealed-PoE decryption (recipient verifier).\n//\n// For each `enc`-bearing item — when the run's decryption keyring is\n// non-empty — the verifier acquires the ciphertext blob (out-of-band bytes,\n// or fetched from `item.uris[]`), dispatches on the item's on-wire key path,\n// and attempts every applicable keyring credential independently:\n//\n// * `enc.slots` — the sealed-PoE trial-decrypt loop: per-slot\n// acceptance folds the KEM validity bit, the\n// wrap-open, and the slot-set MAC over `slots_hash`\n// into one constant-time decision, then the recovered\n// CEK opens the segmented STREAM chunk by chunk.\n// * `enc.passphrase` — Argon2id over the pinned-normalization passphrase,\n// the leading 32-byte key-commitment header verified\n// in constant time BEFORE any chunk opens, then the\n// same STREAM open.\n//\n// Failure attribution:\n//\n// * WRONG_RECIPIENT_KEY / TAMPERED_HEADER bind to ON-CHAIN data (the slot\n// set and its MAC), so they are terminal for the item no matter which\n// blob was tried.\n// * TAMPERED_CIPHERTEXT is blob-dependent: it holds the blob against the\n// record only when the blob is ATTRIBUTABLE (out-of-band, or fetched\n// with a verified content-address binding). The same failure over an\n// unattributable fetched blob is URI_PROVIDER_INTEGRITY_MISMATCH\n// (warning) and the remaining sources are tried; exhaustion without an\n// attributable blob ends as CIPHERTEXT_UNAVAILABLE (verdict\n// `unverifiable`).\n// * The post-decryption plaintext-hash recheck needs no attribution\n// qualifier: ciphertext that opens under the authenticated envelope is\n// attributed by the AEAD itself, so a recheck mismatch is always\n// URI_INTEGRITY_MISMATCH and the record's verdict is `failed` — no\n// \"decrypted\" surface may outrank it.\n\nimport {\n EciesSealedPoeError,\n eciesSealedPoeUnwrap,\n passphraseSealedPoeOpen,\n sealedEnvelopeFromParsed,\n type PassphraseSealedEnvelope,\n type UnwrapFailureReason,\n} from '@cardanowall/crypto-core/sealed-poe';\nimport type { ErrorCode } from '@cardanowall/poe-standard';\nimport type { ItemEntry } from '@cardanowall/poe-standard';\n\nimport {\n iterateBlobSources,\n providerMismatchPath,\n type BlobIterationFlags,\n type ContentFetchContext,\n} from './content';\nimport { recomputeItemHashes } from './items';\nimport type { IssuePath } from './issues';\nimport type { ContentCheck, DecryptionCredential, DecryptionOutcome } from './types';\n\nexport interface ItemDecryptionResult {\n readonly contentCheck: ContentCheck;\n readonly decryption: DecryptionOutcome;\n}\n\ntype AttemptOutcome =\n | { readonly kind: 'opened'; readonly plaintext: Uint8Array }\n // Bound to on-chain data — retrying with a different blob cannot change it.\n | { readonly kind: 'header_failure'; readonly code: 'WRONG_RECIPIENT_KEY' | 'TAMPERED_HEADER' }\n // Blob-dependent: subject to the attribution split.\n | { readonly kind: 'blob_failure'; readonly code: 'TAMPERED_CIPHERTEXT' }\n // A caller-input / KDF problem independent of the blob — terminal.\n | { readonly kind: 'input_failure'; readonly code: ErrorCode; readonly message: string };\n\n// Map a construction-API rejection to the wire error-code vocabulary. Codes\n// that exist in the wire registry pass through verbatim; the\n// construction-local pre-KDF input bound maps to KDF_DERIVATION_FAILED (the\n// KDF input was rejected before derivation could run).\nfunction inputFailureFrom(e: EciesSealedPoeError): AttemptOutcome {\n const code: ErrorCode =\n e.code === 'ENC_PASSPHRASE_UNNORMALIZABLE' ||\n e.code === 'ENC_PASSPHRASE_EMPTY' ||\n e.code === 'KDF_DERIVATION_FAILED'\n ? e.code\n : 'KDF_DERIVATION_FAILED';\n return { kind: 'input_failure', code, message: e.message };\n}\n\nasync function attemptSlotsPath(args: {\n readonly enc: unknown;\n readonly hashes: Readonly<Record<string, Uint8Array>>;\n readonly ciphertext: Uint8Array;\n readonly secretKeys: ReadonlyArray<Uint8Array>;\n}): Promise<AttemptOutcome> {\n const envelope = sealedEnvelopeFromParsed(\n args.enc as Parameters<typeof sealedEnvelopeFromParsed>[0],\n );\n if (envelope === null) {\n // Unreachable on a structurally validated record (the recipient-role\n // validator hard-rejects every envelope it cannot fully validate);\n // defensively classed as a header failure.\n return { kind: 'header_failure', code: 'TAMPERED_HEADER' };\n }\n let result;\n try {\n result = eciesSealedPoeUnwrap({\n envelope,\n ciphertext: args.ciphertext,\n hashes: args.hashes,\n recipientSecretKeys: args.secretKeys,\n });\n } catch (e) {\n if (e instanceof EciesSealedPoeError) return inputFailureFrom(e);\n throw e;\n }\n if (result.matched) {\n return { kind: 'opened', plaintext: result.plaintext };\n }\n const reason: UnwrapFailureReason = result.reason;\n if (reason === 'TAMPERED_CIPHERTEXT') {\n return { kind: 'blob_failure', code: 'TAMPERED_CIPHERTEXT' };\n }\n return { kind: 'header_failure', code: reason };\n}\n\nasync function attemptPassphrasePath(args: {\n readonly enc: unknown;\n readonly hashes: Readonly<Record<string, Uint8Array>>;\n readonly blob: Uint8Array;\n readonly passphrases: ReadonlyArray<string>;\n}): Promise<AttemptOutcome> {\n let firstFailure: AttemptOutcome | null = null;\n for (const passphrase of args.passphrases) {\n let outcome: AttemptOutcome;\n try {\n const result = await passphraseSealedPoeOpen({\n envelope: args.enc as PassphraseSealedEnvelope,\n blob: args.blob,\n passphrase,\n hashes: args.hashes,\n });\n outcome = result.matched\n ? { kind: 'opened', plaintext: result.plaintext }\n : // Wrong passphrase, tampered salt/params/header fields, a spliced\n // envelope, or a tampered stream — indistinguishable by design.\n { kind: 'blob_failure', code: 'TAMPERED_CIPHERTEXT' };\n } catch (e) {\n if (!(e instanceof EciesSealedPoeError)) throw e;\n outcome = inputFailureFrom(e);\n }\n if (outcome.kind === 'opened') return outcome;\n firstFailure ??= outcome;\n }\n // The keyring is non-empty by construction (the caller filtered applicable\n // credentials before dispatching here).\n return firstFailure!;\n}\n\nexport async function decryptItem(args: {\n readonly item: ItemEntry;\n readonly itemIndex: number;\n readonly credentials: ReadonlyArray<DecryptionCredential>;\n readonly outOfBandCiphertext?: Uint8Array | undefined;\n readonly fetchContent: boolean;\n readonly ctx: ContentFetchContext;\n}): Promise<ItemDecryptionResult> {\n const { item, itemIndex, ctx } = args;\n const basePath: IssuePath = ['items', itemIndex, 'enc'];\n const enc = item.enc as { slots?: unknown; passphrase?: unknown };\n const isSlotsPath = Array.isArray(enc.slots);\n\n // Applicable credentials for the item's on-wire key path. The two paths are\n // mutually exclusive on a validated record (ENC_EXCLUSIVITY_VIOLATION).\n const secretKeys: Uint8Array[] = [];\n const passphrases: string[] = [];\n for (const credential of args.credentials) {\n if ('recipientSecretKey' in credential) secretKeys.push(credential.recipientSecretKey);\n else passphrases.push(credential.passphrase);\n }\n const applicable = isSlotsPath ? secretKeys.length : passphrases.length;\n if (applicable === 0) {\n ctx.issues.add(\n 'WRONG_DECRYPTION_INPUT_SHAPE',\n basePath,\n isSlotsPath\n ? 'the keyring holds no recipient secret key for this slots-path item'\n : 'the keyring holds no passphrase for this passphrase-path item',\n );\n return {\n contentCheck: 'not_checked',\n decryption: { decrypted: false, code: 'WRONG_DECRYPTION_INPUT_SHAPE' },\n };\n }\n\n const flags: BlobIterationFlags = { limitExceeded: false };\n for await (const blob of iterateBlobSources({\n outOfBand: args.outOfBandCiphertext,\n uris: item.uris ?? [],\n allowFetch: args.fetchContent,\n basePath: ['items', itemIndex],\n ctx,\n flags,\n })) {\n const outcome = isSlotsPath\n ? await attemptSlotsPath({\n enc,\n hashes: item.hashes,\n ciphertext: blob.bytes,\n secretKeys,\n })\n : await attemptPassphrasePath({\n enc,\n hashes: item.hashes,\n blob: blob.bytes,\n passphrases,\n });\n\n switch (outcome.kind) {\n case 'opened': {\n const plaintextHashOk = recomputeItemHashes(item.hashes, outcome.plaintext);\n if (!plaintextHashOk) {\n ctx.issues.add(\n 'URI_INTEGRITY_MISMATCH',\n ['items', itemIndex],\n 'decryption succeeded but the post-decryption plaintext-hash recheck failed; decrypted bytes are attributed by the AEAD itself, so the record is condemned',\n );\n return {\n contentCheck: 'mismatched',\n decryption: { decrypted: true, plaintextHashOk: false, code: 'URI_INTEGRITY_MISMATCH' },\n };\n }\n return { contentCheck: 'checked', decryption: { decrypted: true, plaintextHashOk: true } };\n }\n case 'header_failure': {\n ctx.issues.add(\n outcome.code,\n basePath,\n outcome.code === 'WRONG_RECIPIENT_KEY'\n ? 'no slot accepted any supplied recipient key — the key is not a recipient of this sealed PoE'\n : 'a slot wrap-opened but no candidate content-encryption key reproduces slots_mac — the authenticated envelope header fails its integrity check',\n );\n return {\n // `contentCheck` reports the plaintext-vs-hash comparison, which a\n // header failure never reaches — the claim is unchecked either way.\n // TAMPERED_HEADER still condemns the record through its issue.\n contentCheck: 'not_checked',\n decryption: { decrypted: false, code: outcome.code },\n };\n }\n case 'blob_failure': {\n if (blob.attributable()) {\n ctx.issues.add(\n 'TAMPERED_CIPHERTEXT',\n basePath,\n 'the ciphertext blob failed the decryption layer and is attributable (out-of-band, or content-address-bound to its URI); the record is condemned',\n );\n return {\n contentCheck: 'mismatched',\n decryption: { decrypted: false, code: 'TAMPERED_CIPHERTEXT' },\n };\n }\n ctx.issues.add(\n 'URI_PROVIDER_INTEGRITY_MISMATCH',\n providerMismatchPath(['items', itemIndex], blob),\n `ciphertext bytes fetched from \"${blob.uri ?? 'unknown source'}\" fail the decryption layer and could not be attributed to the URI's content address; the serving provider is indicted, not the record`,\n );\n continue;\n }\n case 'input_failure': {\n ctx.issues.add(outcome.code, basePath, outcome.message);\n return {\n contentCheck: 'not_checked',\n decryption: { decrypted: false, code: outcome.code },\n };\n }\n }\n }\n\n const endCode: ErrorCode = flags.limitExceeded\n ? 'CONTENT_FETCH_LIMIT_EXCEEDED'\n : 'CIPHERTEXT_UNAVAILABLE';\n ctx.issues.add(\n endCode,\n ['items', itemIndex],\n flags.limitExceeded\n ? 'a ciphertext fetch for this item was aborted at the maxFetchBytes ceiling; decryption could not proceed'\n : 'no out-of-band ciphertext was supplied and no URI yielded an attributable blob; decryption could not proceed',\n );\n return { contentCheck: 'not_checked', decryption: { decrypted: false, code: endCode } };\n}\n","// Issue construction and the normative issue ordering.\n//\n// The report's issue list merges the structural validator's output with every\n// verifier-layer code the run raises. The combined list is sorted by the same\n// rule the validator uses internally, so two implementations replaying the\n// same run emit byte-identical issue order:\n//\n// * paths compare segment-wise from the record root — two integer segments\n// numerically, two text segments by the bytewise order of their UTF-8\n// encodings, integer before text where the kinds differ, and a path that\n// is a strict prefix of another orders before it;\n// * issues carrying an identical path tie-break by the position of their\n// `code` in the error-code registry.\n//\n// Run-level verifier codes (TX_NOT_FOUND, PROVIDER_UNAVAILABLE, …) carry an\n// empty path and therefore sort ahead of every record-located issue.\n\nimport {\n SEVERITY,\n errorCodeRegistryIndex,\n type ErrorCode,\n type Severity,\n type ValidationIssue,\n} from '@cardanowall/poe-standard';\n\nconst UTF8 = new TextEncoder();\n\nexport type IssuePath = ReadonlyArray<string | number>;\n\n// Build one issue with the registry's default severity for the code; pass\n// `severity` to apply a context-promoted reading (dual-severity codes only —\n// no code may ever be softened below its registry severity).\nexport function issueOf(\n code: ErrorCode,\n path: IssuePath,\n message: string,\n severity?: Severity,\n): ValidationIssue {\n return { code, path, message, severity: severity ?? SEVERITY[code] };\n}\n\nfunction compareSegments(a: string | number, b: string | number): number {\n const aIsNumber = typeof a === 'number';\n const bIsNumber = typeof b === 'number';\n if (aIsNumber && bIsNumber) return (a as number) - (b as number);\n // Integer segments order before text segments where the kinds differ.\n if (aIsNumber !== bIsNumber) return aIsNumber ? -1 : 1;\n const aBytes = UTF8.encode(a as string);\n const bBytes = UTF8.encode(b as string);\n const n = Math.min(aBytes.length, bBytes.length);\n for (let i = 0; i < n; i++) {\n const d = aBytes[i]! - bBytes[i]!;\n if (d !== 0) return d;\n }\n return aBytes.length - bBytes.length;\n}\n\nexport function compareIssuePaths(a: IssuePath, b: IssuePath): number {\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n const d = compareSegments(a[i]!, b[i]!);\n if (d !== 0) return d;\n }\n // A strict prefix orders before its extension.\n return a.length - b.length;\n}\n\nexport function sortIssues(issues: ReadonlyArray<ValidationIssue>): ValidationIssue[] {\n return issues\n .slice()\n .sort(\n (a, b) =>\n compareIssuePaths(a.path, b.path) ||\n errorCodeRegistryIndex(a.code) - errorCodeRegistryIndex(b.code),\n );\n}\n\n// A mutable per-run sink the pipeline steps append to; the report assembly\n// sorts once at emission.\nexport class IssueSink {\n private readonly issues: ValidationIssue[] = [];\n\n push(issue: ValidationIssue): void {\n this.issues.push(issue);\n }\n\n add(code: ErrorCode, path: IssuePath, message: string, severity?: Severity): void {\n this.issues.push(issueOf(code, path, message, severity));\n }\n\n // Idempotent add: a no-op when the sink already holds an issue with the\n // same code, path, and effective severity. Used where two pipeline layers\n // can legitimately conclude the same fact about the same location (e.g.\n // the structural validator and the signature pass both finding a signature\n // entry unsupported) and the report must carry it exactly once.\n addOnce(code: ErrorCode, path: IssuePath, message: string, severity?: Severity): void {\n const issue = issueOf(code, path, message, severity);\n const duplicate = this.issues.some(\n (existing) =>\n existing.code === issue.code &&\n existing.severity === issue.severity &&\n compareIssuePaths(existing.path, issue.path) === 0,\n );\n if (!duplicate) this.issues.push(issue);\n }\n\n pushAll(issues: ReadonlyArray<ValidationIssue>): void {\n this.issues.push(...issues);\n }\n\n has(code: ErrorCode): boolean {\n return this.issues.some((i) => i.code === code);\n }\n\n sorted(): ValidationIssue[] {\n return sortIssues(this.issues);\n }\n}\n","// Canonical-CBOR codec for the off-chain Merkle leaves-list artefact.\n// The on-chain `merkle[]` field binds to this file via `uris[]` / `leaf_count`;\n// the file itself carries the full leaf set. Canonical CBOR is RFC 8949 §4.2.1.\n//\n// CDDL:\n//\n// leaves-list = {\n// \"format\": \"cardano-poe-merkle-leaves-v1\",\n// \"tree_alg\": \"rfc9162-sha256\",\n// \"root\": bytes .size 32,\n// \"leaves\": [ + bytes .size 32 ],\n// \"leaf_count\": uint,\n// ? \"leaf_alg\": tstr,\n// }\n//\n// Canonical ordering is bytewise-lexicographic on encoded map keys (RFC 8949\n// §4.2.1) so the wire-key order is fixed by `cde:true` regardless of insertion\n// order: root (4B) < format (6B) < leaves (6B) < leaf_alg (8B) < tree_alg (8B)\n// < leaf_count (10B).\n\nimport { decodeCanonicalCbor, encodeCanonicalCbor } from '../cbor/canonical';\nimport { compareCt } from '../util/compare-ct';\nimport { merkleSha2256Root } from '../hash/merkle-sha2-256';\n\nexport const LEAVES_LIST_FORMAT_V1 = 'cardano-poe-merkle-leaves-v1' as const;\nconst TREE_ALG_RFC9162 = 'rfc9162-sha256' as const;\nconst DIGEST_LENGTH = 32;\nconst REGISTERED_FORMATS = new Set<string>([LEAVES_LIST_FORMAT_V1]);\n\nexport type MerkleLeavesListErrorCode =\n | 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED'\n | 'SCHEMA_MERKLE_LEAVES_MALFORMED'\n | 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH'\n | 'MERKLE_ROOT_MISMATCH';\n\nexport class MerkleLeavesListError extends Error {\n readonly code: MerkleLeavesListErrorCode;\n constructor(code: MerkleLeavesListErrorCode, message?: string) {\n super(message ? `${code}: ${message}` : code);\n this.code = code;\n this.name = 'MerkleLeavesListError';\n }\n}\n\nexport interface EncodeLeavesListArgs {\n readonly leaves: ReadonlyArray<Uint8Array>;\n readonly root: Uint8Array;\n readonly leafAlg?: string;\n}\n\nexport interface DecodedLeavesList {\n readonly format: typeof LEAVES_LIST_FORMAT_V1;\n readonly treeAlg: typeof TREE_ALG_RFC9162;\n readonly root: Uint8Array;\n readonly leaves: Uint8Array[];\n readonly leafCount: number;\n readonly leafAlg?: string;\n}\n\nexport function encodeLeavesList(args: EncodeLeavesListArgs): Uint8Array {\n if (!(args.root instanceof Uint8Array) || args.root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n if (args.leaves.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves array must be non-empty',\n );\n }\n const leavesCopy: Uint8Array[] = [];\n for (let i = 0; i < args.leaves.length; i++) {\n const leaf = args.leaves[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a Uint8Array(${DIGEST_LENGTH})`,\n );\n }\n leavesCopy.push(leaf);\n }\n if (args.leafAlg !== undefined && typeof args.leafAlg !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a string when present',\n );\n }\n const map: Record<string, unknown> = {\n format: LEAVES_LIST_FORMAT_V1,\n tree_alg: TREE_ALG_RFC9162,\n root: args.root,\n leaves: leavesCopy,\n leaf_count: leavesCopy.length,\n };\n if (args.leafAlg !== undefined) {\n map['leaf_alg'] = args.leafAlg;\n }\n return encodeCanonicalCbor(map as never);\n}\n\nexport function decodeLeavesList(bytes: Uint8Array): DecodedLeavesList {\n const decoded = decodeCanonicalCbor(bytes);\n if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves-list MUST be a CBOR map',\n );\n }\n const m = decoded as Record<string, unknown>;\n\n const format = m['format'];\n if (typeof format !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'format must be a text string',\n );\n }\n if (!REGISTERED_FORMATS.has(format)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED',\n `format '${format}' is not in the registered set`,\n );\n }\n\n const treeAlg = m['tree_alg'];\n if (treeAlg !== TREE_ALG_RFC9162) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `tree_alg '${String(treeAlg)}' is not '${TREE_ALG_RFC9162}'`,\n );\n }\n\n const root = m['root'];\n if (!(root instanceof Uint8Array) || root.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `root must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n\n const leavesRaw = m['leaves'];\n if (!Array.isArray(leavesRaw) || leavesRaw.length < 1) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaves must be a non-empty array',\n );\n }\n const leaves: Uint8Array[] = [];\n for (let i = 0; i < leavesRaw.length; i++) {\n const leaf = leavesRaw[i];\n if (!(leaf instanceof Uint8Array) || leaf.length !== DIGEST_LENGTH) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n `leaves[${i}] must be a ${DIGEST_LENGTH}-byte byte string`,\n );\n }\n leaves.push(leaf);\n }\n\n const leafCountRaw = m['leaf_count'];\n let leafCount: number;\n if (typeof leafCountRaw === 'number' && Number.isInteger(leafCountRaw) && leafCountRaw >= 0) {\n leafCount = leafCountRaw;\n } else if (typeof leafCountRaw === 'bigint' && leafCountRaw >= 0n) {\n if (leafCountRaw > BigInt(Number.MAX_SAFE_INTEGER)) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count exceeds Number.MAX_SAFE_INTEGER',\n );\n }\n leafCount = Number(leafCountRaw);\n } else {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_count must be a non-negative CBOR uint',\n );\n }\n if (leaves.length !== leafCount) {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n `leaves.length (${leaves.length}) != leaf_count (${leafCount})`,\n );\n }\n\n let leafAlg: string | undefined;\n if (m['leaf_alg'] !== undefined) {\n if (typeof m['leaf_alg'] !== 'string') {\n throw new MerkleLeavesListError(\n 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n 'leaf_alg must be a text string when present',\n );\n }\n leafAlg = m['leaf_alg'];\n }\n\n const recomputed = merkleSha2256Root(leaves);\n if (!compareCt(recomputed, root)) {\n throw new MerkleLeavesListError(\n 'MERKLE_ROOT_MISMATCH',\n 'leaves recompute does not match declared root',\n );\n }\n\n const out: DecodedLeavesList = {\n format: LEAVES_LIST_FORMAT_V1,\n treeAlg: TREE_ALG_RFC9162,\n root,\n leaves,\n leafCount,\n ...(leafAlg !== undefined ? { leafAlg } : {}),\n };\n return out;\n}\n","// Merkle list-commitment verification.\n//\n// For each `record.merkle[i]` the verifier obtains the leaves-list document\n// (caller-supplied bytes, or fetched from `merkle[i].uris[]` under the same\n// first-success / attribution / fetch-ceiling semantics as item content),\n// validates it against the normative CBOR leaves-list container — the ONLY\n// accepted wire form — recomputes the RFC 9162 §2.1.1 root, and compares\n// byte-exact against the on-chain commitment.\n//\n// The record-attributable codes (SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED /\n// SCHEMA_MERKLE_LEAVES_MALFORMED / SCHEMA_MERKLE_LEAF_COUNT_MISMATCH /\n// MERKLE_ROOT_MISMATCH) hold the record to account only for an ATTRIBUTABLE\n// leaves-list — supplied out-of-band, or fetched with a verified\n// content-address binding. An unattributable fetched document failing them is\n// URI_PROVIDER_INTEGRITY_MISMATCH (warning) and the remaining sources are\n// tried.\n//\n// A claim left with no attributable leaves-list is MERKLE_LEAVES_UNAVAILABLE,\n// whose severity is context-dependent (the commitment floor): warning when at\n// least one other content commitment of the record was verified, error\n// (network class, verdict `unverifiable`) when the unavailability leaves the\n// record with no verified content commitment. Because the floor needs the\n// whole-record picture, this module returns the unavailability as a PENDING\n// marker and the report assembly emits the issue once every content check has\n// run.\n\nimport { merkleSha2256Root } from '@cardanowall/crypto-core/hash';\nimport { decodeLeavesList, MerkleLeavesListError } from '@cardanowall/crypto-core/merkle';\nimport { compareCt } from '@cardanowall/crypto-core/util';\nimport type { MerkleCommit } from '@cardanowall/poe-standard';\n\nimport {\n iterateBlobSources,\n providerMismatchPath,\n type BlobIterationFlags,\n type ContentFetchContext,\n} from './content';\nimport type { IssuePath } from './issues';\nimport type { ContentCheck } from './types';\n\n// v1 registers exactly one Merkle commitment algorithm; this verifier\n// implements it, so MERKLE_UNSUPPORTED never fires here (an unregistered\n// identifier is already rejected by the structural validator with\n// UNSUPPORTED_MERKLE_COMMIT_ALG).\nconst MERKLE_ALG = 'rfc9162-sha256';\n\nexport interface MerkleCommitOutcome {\n readonly contentCheck: ContentCheck;\n // Set when the claim ended unchecked because no attributable leaves-list\n // could be obtained; the report assembly emits MERKLE_LEAVES_UNAVAILABLE\n // (or CONTENT_FETCH_LIMIT_EXCEEDED) with floor-resolved severity.\n readonly unavailable?: {\n readonly path: IssuePath;\n readonly limitExceeded: boolean;\n };\n}\n\ntype LeavesValidation =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly code:\n | 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED'\n | 'SCHEMA_MERKLE_LEAVES_MALFORMED'\n | 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH'\n | 'MERKLE_ROOT_MISMATCH';\n readonly message: string;\n };\n\n// Validate one acquired leaves-list document against the on-chain commitment:\n// container grammar, document-internal consistency, RFC 9162 root recompute,\n// and the leaf-count binding.\nfunction validateLeavesDocument(bytes: Uint8Array, commit: MerkleCommit): LeavesValidation {\n let decoded;\n try {\n decoded = decodeLeavesList(bytes);\n } catch (e) {\n if (e instanceof MerkleLeavesListError) {\n const code =\n e.code === 'SCHEMA_MERKLE_LEAVES_FORMAT_UNSUPPORTED' ||\n e.code === 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH' ||\n e.code === 'MERKLE_ROOT_MISMATCH'\n ? e.code\n : ('SCHEMA_MERKLE_LEAVES_MALFORMED' as const);\n return { ok: false, code, message: e.message };\n }\n return {\n ok: false,\n code: 'SCHEMA_MERKLE_LEAVES_MALFORMED',\n message: e instanceof Error ? e.message : String(e),\n };\n }\n if (BigInt(decoded.leafCount) !== BigInt(commit.leaf_count)) {\n return {\n ok: false,\n code: 'SCHEMA_MERKLE_LEAF_COUNT_MISMATCH',\n message: `leaves-list carries ${decoded.leafCount} leaves but the on-chain commitment declares ${commit.leaf_count}`,\n };\n }\n const recomputed = merkleSha2256Root(decoded.leaves);\n if (!compareCt(recomputed, commit.root)) {\n return {\n ok: false,\n code: 'MERKLE_ROOT_MISMATCH',\n message: 'the RFC 9162 root recomputed from the leaves-list does not equal the on-chain root',\n };\n }\n return { ok: true };\n}\n\nexport async function checkMerkleCommit(args: {\n readonly commit: MerkleCommit;\n readonly commitIndex: number;\n readonly outOfBand?: Uint8Array | undefined;\n readonly fetchContent: boolean;\n readonly ctx: ContentFetchContext;\n}): Promise<MerkleCommitOutcome> {\n const { commit, commitIndex, ctx } = args;\n const basePath: IssuePath = ['merkle', commitIndex];\n\n if (commit.alg !== MERKLE_ALG) {\n // Defence-in-depth: the structural validator already rejected unknown\n // identifiers, so an unimplemented-but-registered algorithm cannot occur\n // in v1 (the registry has exactly one member).\n ctx.issues.add(\n 'UNSUPPORTED_MERKLE_COMMIT_ALG',\n [...basePath, 'alg'],\n `merkle commitment algorithm \"${commit.alg}\" is not implemented`,\n );\n return { contentCheck: 'not_checked' };\n }\n\n const uris = commit.uris ?? [];\n // Offline with no out-of-band document: the claim is simply not checked —\n // the fetch was suppressed by policy, not unavailable.\n if (!args.fetchContent && args.outOfBand === undefined) {\n return { contentCheck: 'not_checked' };\n }\n\n const flags: BlobIterationFlags = { limitExceeded: false };\n for await (const blob of iterateBlobSources({\n outOfBand: args.outOfBand,\n uris,\n allowFetch: args.fetchContent,\n basePath,\n ctx,\n flags,\n })) {\n const validation = validateLeavesDocument(blob.bytes, commit);\n if (validation.ok) {\n return { contentCheck: 'checked' };\n }\n if (blob.attributable()) {\n ctx.issues.add(validation.code, basePath, validation.message);\n return { contentCheck: 'mismatched' };\n }\n ctx.issues.add(\n 'URI_PROVIDER_INTEGRITY_MISMATCH',\n providerMismatchPath(basePath, blob),\n `leaves-list bytes fetched from \"${blob.uri ?? 'unknown source'}\" fail validation (${validation.code}) and could not be attributed to the URI's content address; the serving provider is indicted, not the record`,\n );\n }\n\n return {\n contentCheck: 'not_checked',\n unavailable: { path: basePath, limitExceeded: flags.limitExceeded },\n };\n}\n","// Conformance-profile helpers.\n//\n// A `core`-profile verifier reading a record that carries `sigs`, `enc`, or\n// `merkle` MUST emit `OUT_OF_PROFILE_SKIPPED` (info severity) per affected\n// field — NOT `SCHEMA_UNKNOWN_FIELD` (which applies only to fields outside\n// the v1 CDDL). This rule lets a block explorer shipping only the `core`\n// surface still surface every conformant v1 record regardless of which\n// extensions it carries.\n\nimport type { PoeRecord, ValidationIssue } from '@cardanowall/poe-standard';\n\nimport type { Profile } from './types';\nimport { PROFILE_RANK } from './types';\n\nexport const DEFAULT_PROFILE: Profile = 'recipient-sealed';\n\nexport function profileImplements(actual: Profile, required: Profile): boolean {\n return PROFILE_RANK[actual] >= PROFILE_RANK[required];\n}\n\nexport interface ProfileSkipsResult {\n // info-severity entries emitted when a field belongs to a higher profile\n // than the active one. Surfaces in `validation.info`.\n readonly skips: ValidationIssue[];\n // Convenience flags for the verifier pipeline (whether to enter each\n // sub-pipeline at all).\n readonly verifySignatures: boolean;\n readonly verifyDecrypt: boolean;\n}\n\n/**\n * Emit the minimum conformance profile a verifier MUST implement\n * to read this record end-to-end. The profiles form a strict superset chain\n * `core ⊂ signed ⊂ sealed ⊂ recipient-sealed`.\n *\n * The function classifies based on RECORD CONTENT only:\n * - `'core'` — no signatures, no sealed items.\n * - `'signed'` — `record.sigs[]` is present, no sealed items.\n * - `'sealed'` — any `record.items[i].enc` is present (with or without sigs).\n *\n * The function does NOT return `'recipient-sealed'`: that profile is about\n * VERIFIER CAPABILITY (whether the verifier decrypts with a recipient X25519\n * key), not about record content. A separate helper is required if a caller\n * needs to test whether a particular recipient key can unwrap any slot — see\n * `@cardanowall/crypto-core/sealed-poe` for that pathway.\n */\nexport function detectConformanceProfile(record: PoeRecord): 'core' | 'signed' | 'sealed' {\n const hasSealedItem =\n Array.isArray(record.items) && record.items.some((it) => it.enc !== undefined);\n if (hasSealedItem) return 'sealed';\n const hasSigs = Array.isArray(record.sigs) && record.sigs.length > 0;\n if (hasSigs) return 'signed';\n return 'core';\n}\n\nexport function planProfileSkips(profile: Profile, record: PoeRecord): ProfileSkipsResult {\n const skips: ValidationIssue[] = [];\n const has = (k: string): boolean => Object.prototype.hasOwnProperty.call(record, k);\n const verifySignatures = PROFILE_RANK[profile] >= PROFILE_RANK['signed'];\n // The `sealed` rank gates whether the verifier reads the enc envelope at all.\n // There is no separate `sealed`-only sub-pipeline distinct from decryption,\n // so this drives only the skip-emission below rather than a returned flag.\n const readsEnc = PROFILE_RANK[profile] >= PROFILE_RANK['sealed'];\n const verifyDecrypt = PROFILE_RANK[profile] >= PROFILE_RANK['recipient-sealed'];\n\n if (!verifySignatures && has('sigs')) {\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['sigs'],\n message: `sigs[] requires profile >= 'signed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n if (!readsEnc && Array.isArray(record.items)) {\n for (let i = 0; i < record.items.length; i++) {\n if (record.items[i]!.enc === undefined) continue;\n skips.push({\n code: 'OUT_OF_PROFILE_SKIPPED',\n path: ['items', i, 'enc'],\n message: `items[${i}].enc requires profile >= 'sealed'; active profile is '${profile}'`,\n severity: 'info',\n });\n }\n }\n return { skips, verifySignatures, verifyDecrypt };\n}\n","// Transaction-reference integrity binding.\n//\n// Before reading anything out of a fetched transaction, the verifier MUST\n// bind the fetched bytes to the caller-supplied transaction reference:\n//\n// 1. blake2b-256 over the transaction-body bytes — by ledger definition,\n// the transaction id — must equal the requested transaction hash;\n// 2. blake2b-256 over the auxiliary-data bytes must equal the\n// `auxiliary_data_hash` field of the now-verified body.\n//\n// Both digests are computed over the bytes EXACTLY as fetched, never over a\n// re-encoding. A response that fails either check carries provably wrong\n// bytes: the caller discards it and tries the next provider; if no provider\n// survives, the run reports TX_INTEGRITY_MISMATCH — provider-attributable,\n// verdict `unverifiable`, because no record bytes were ever obtained and the\n// record cannot be condemned by bytes a provider fabricated.\n//\n// After the binding holds, every byte of the record body and of the\n// surrounding transaction is cryptographically committed to the requested\n// transaction hash; no explorer can substitute, amend, or truncate the record\n// without producing a blake2b-256 second preimage. The chain facts the\n// binding does NOT establish — inclusion, height, depth, slot, time — stay\n// explorer-asserted.\n\nimport { blake2b256 } from '@cardanowall/crypto-core/hash';\nimport { compareCt } from '@cardanowall/crypto-core/util';\n\nimport { auxiliaryDataHashFromTxBody } from './cbor-walker';\n\nexport type TxBindingResult =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly check: 'tx_hash' | 'auxiliary_data_hash';\n readonly message: string;\n };\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let out = '';\n for (const b of bytes) out += b.toString(16).padStart(2, '0');\n return out;\n}\n\nfunction hexToBytesOrNull(hex: string): Uint8Array | null {\n if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/.test(hex)) return null;\n const out = new Uint8Array(hex.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n\nexport function bindTransactionBytes(args: {\n // 32-byte transaction hash, lowercase/uppercase hex accepted.\n readonly requestedTxHashHex: string;\n readonly txBody: Uint8Array;\n readonly auxiliaryData: Uint8Array | null;\n}): TxBindingResult {\n const requested = hexToBytesOrNull(args.requestedTxHashHex.toLowerCase());\n const computedTxHash = blake2b256(args.txBody);\n if (requested === null || !compareCt(computedTxHash, requested)) {\n return {\n ok: false,\n check: 'tx_hash',\n message: `blake2b-256 of the fetched transaction body is ${bytesToHex(computedTxHash)}, not the requested ${args.requestedTxHashHex.toLowerCase()}`,\n };\n }\n\n let committed: Uint8Array | null;\n try {\n committed = auxiliaryDataHashFromTxBody(args.txBody);\n } catch (e) {\n return {\n ok: false,\n check: 'auxiliary_data_hash',\n message: e instanceof Error ? e.message : String(e),\n };\n }\n\n if (args.auxiliaryData === null) {\n if (committed !== null) {\n // The verified body commits to auxiliary data the response does not\n // carry: the provider served a provably incomplete transaction.\n return {\n ok: false,\n check: 'auxiliary_data_hash',\n message:\n 'the verified transaction body carries auxiliary_data_hash but the response carries no auxiliary data',\n };\n }\n return { ok: true };\n }\n\n if (committed === null) {\n // Auxiliary data present but the body never committed to it — such a\n // transaction cannot exist on chain.\n return {\n ok: false,\n check: 'auxiliary_data_hash',\n message:\n 'auxiliary data is present but the verified transaction body carries no auxiliary_data_hash',\n };\n }\n const computedAuxHash = blake2b256(args.auxiliaryData);\n if (!compareCt(computedAuxHash, committed)) {\n return {\n ok: false,\n check: 'auxiliary_data_hash',\n message: `blake2b-256 of the fetched auxiliary data is ${bytesToHex(computedAuxHash)}, not the body-committed ${bytesToHex(committed)}`,\n };\n }\n return { ok: true };\n}\n","// Cardano transaction resolution — an ordered explorer chain (Koios-compatible\n// endpoints, then a Blockfrost fallback when a project ID is supplied), with\n// the transaction-reference integrity binding applied to every response\n// BEFORE anything is read out of it.\n//\n// The verifier fetches the RAW on-chain transaction CBOR, never an explorer's\n// metadata-JSON projection: the projection is lossy (map-key ordering,\n// definite-vs-indefinite lengths, bytes-vs-text discrimination), so a\n// verifier that re-encoded from it could not reproduce the byte-exact signing\n// input.\n//\n// Resolution distinguishes three terminal negatives, in evidence order:\n//\n// * TX_INTEGRITY_MISMATCH — at least one provider actively served bytes\n// that fail the blake2b-256 binding to the requested reference and no\n// provider's response survived it. Provider-attributable; verdict\n// `unverifiable` (no record bytes were ever obtained).\n// * TX_NOT_FOUND — at least one provider answered definitively that it\n// knows no such transaction, and none had it. A single provider's\n// negative is not chain-authoritative, so every remaining provider is\n// consulted first. Network class; verdict `unverifiable`.\n// * PROVIDER_UNAVAILABLE — every provider was unreachable or returned no\n// usable response. Network class; verdict `unverifiable`.\n//\n// Chain facts (tip height, block height, block time, block slot) are\n// explorer-asserted; the binding cannot establish them. Confirmation depth is\n// counted in blocks: depth = tip − block + 1, so a transaction in the tip\n// block has depth exactly 1.\n\nimport { isDenyHostError } from '../fetch/fetch-outbound';\nimport { sliceTxComponents, type TxComponents } from './cbor-walker';\nimport { bindTransactionBytes } from './tx-binding';\nimport type { FetchOutbound } from './types';\n\nexport const KOIOS_MAINNET_URL = 'https://api.koios.rest/api/v1';\nexport const BLOCKFROST_MAINNET_HOST = 'https://cardano-mainnet.blockfrost.io/api/v0';\n\nexport interface ResolvedTx {\n readonly txCbor: Uint8Array;\n readonly components: TxComponents;\n readonly confirmationDepth: number;\n readonly blockTime: number; // POSIX seconds UTC\n readonly blockSlot: number;\n readonly provider: 'koios' | 'blockfrost';\n readonly providerUrl: string;\n}\n\nexport type ResolveFailureCode = 'TX_NOT_FOUND' | 'PROVIDER_UNAVAILABLE' | 'TX_INTEGRITY_MISMATCH';\n\nexport type ResolveOutcome =\n | { readonly ok: true; readonly resolved: ResolvedTx }\n | { readonly ok: false; readonly code: ResolveFailureCode; readonly message: string };\n\ntype ProviderAttempt =\n | { readonly kind: 'served'; readonly resolved: ResolvedTx }\n | { readonly kind: 'not_found'; readonly detail: string }\n | { readonly kind: 'integrity_mismatch'; readonly detail: string }\n | { readonly kind: 'unusable'; readonly detail: string };\n\nexport async function resolveCardanoTx(args: {\n readonly txHash: string;\n readonly cardanoGatewayChain?: ReadonlyArray<string> | undefined;\n readonly blockfrostProjectId?: string | undefined;\n readonly fetchFn: FetchOutbound;\n}): Promise<ResolveOutcome> {\n const koiosChain = args.cardanoGatewayChain ?? [KOIOS_MAINNET_URL];\n\n let sawNotFound: string | null = null;\n let sawIntegrityMismatch: string | null = null;\n let lastUnusable: string | null = null;\n\n const record = (attempt: ProviderAttempt): ResolvedTx | null => {\n switch (attempt.kind) {\n case 'served':\n return attempt.resolved;\n case 'not_found':\n sawNotFound = attempt.detail;\n return null;\n case 'integrity_mismatch':\n sawIntegrityMismatch = attempt.detail;\n return null;\n case 'unusable':\n lastUnusable = attempt.detail;\n return null;\n }\n };\n\n for (const koiosUrl of koiosChain) {\n const resolved = record(await resolveViaKoios(args.txHash, koiosUrl, args.fetchFn));\n if (resolved !== null) return { ok: true, resolved };\n }\n if (args.blockfrostProjectId !== undefined) {\n const resolved = record(\n await resolveViaBlockfrost(args.txHash, args.blockfrostProjectId, args.fetchFn),\n );\n if (resolved !== null) return { ok: true, resolved };\n }\n\n // Evidence precedence: a provider that actively served wrong bytes is the\n // strongest signal, then a definitive negative answer, then plain\n // unreachability.\n if (sawIntegrityMismatch !== null) {\n return {\n ok: false,\n code: 'TX_INTEGRITY_MISMATCH',\n message: `no provider response survived the transaction-reference binding: ${sawIntegrityMismatch as string}`,\n };\n }\n if (sawNotFound !== null) {\n return {\n ok: false,\n code: 'TX_NOT_FOUND',\n message: `no consulted provider knows transaction ${args.txHash}: ${sawNotFound as string}`,\n };\n }\n return {\n ok: false,\n code: 'PROVIDER_UNAVAILABLE',\n message: lastUnusable ?? 'no provider configured',\n };\n}\n\n// Bind a fetched transaction's bytes to the requested reference. Runs the\n// moment the bytes arrive — BEFORE any further chain-fact call against the\n// same provider, so a provider serving wrong bytes is identified without\n// spending more calls on it.\ntype BoundTx =\n | { readonly kind: 'bound'; readonly components: TxComponents }\n | { readonly kind: 'integrity_mismatch'; readonly detail: string }\n | { readonly kind: 'unusable'; readonly detail: string };\n\nfunction bindFetchedTx(args: {\n readonly txHash: string;\n readonly txCbor: Uint8Array;\n readonly providerUrl: string;\n}): BoundTx {\n let components: TxComponents;\n try {\n components = sliceTxComponents(args.txCbor);\n } catch (e) {\n return {\n kind: 'unusable',\n detail: `${args.providerUrl}: response is not parseable transaction CBOR (${e instanceof Error ? e.message : String(e)})`,\n };\n }\n const binding = bindTransactionBytes({\n requestedTxHashHex: args.txHash,\n txBody: components.txBody,\n auxiliaryData: components.auxiliaryData,\n });\n if (!binding.ok) {\n return {\n kind: 'integrity_mismatch',\n detail: `${args.providerUrl}: ${binding.message}`,\n };\n }\n return { kind: 'bound', components };\n}\n\nasync function resolveViaKoios(\n txHash: string,\n koiosUrl: string,\n fetchFn: FetchOutbound,\n): Promise<ProviderAttempt> {\n try {\n const cborRes = await fetchFn(`${koiosUrl}/tx_cbor`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (cborRes.status !== 200) {\n return { kind: 'unusable', detail: `${koiosUrl}: tx_cbor returned HTTP ${cborRes.status}` };\n }\n const cborJson = parseJson(cborRes.bytes);\n if (!Array.isArray(cborJson)) {\n return { kind: 'unusable', detail: `${koiosUrl}: tx_cbor returned a non-array body` };\n }\n if (cborJson.length === 0) {\n // An empty result set is Koios's definitive \"I know no such tx\".\n return { kind: 'not_found', detail: `${koiosUrl} returned an empty tx_cbor result set` };\n }\n const cborEntry = cborJson[0] as { cbor?: unknown };\n if (typeof cborEntry.cbor !== 'string') {\n return { kind: 'unusable', detail: `${koiosUrl}: tx_cbor entry carries no cbor field` };\n }\n const txCbor = hexToBytes(cborEntry.cbor);\n const bound = bindFetchedTx({ txHash, txCbor, providerUrl: koiosUrl });\n if (bound.kind !== 'bound') return bound;\n\n const infoRes = await fetchFn(`${koiosUrl}/tx_info`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ _tx_hashes: [txHash] }),\n purpose: 'cardano',\n });\n if (infoRes.status !== 200) {\n return { kind: 'unusable', detail: `${koiosUrl}: tx_info returned HTTP ${infoRes.status}` };\n }\n const infoJson = parseJson(infoRes.bytes);\n if (!Array.isArray(infoJson) || infoJson.length === 0) {\n return { kind: 'unusable', detail: `${koiosUrl}: tx_info returned no entry` };\n }\n const infoEntry = infoJson[0] as {\n num_confirmations?: unknown;\n block_height?: unknown;\n tx_timestamp?: unknown;\n absolute_slot?: unknown;\n };\n\n // Koios v1 `/tx_info` carries `block_height` but (on current deployments)\n // no `num_confirmations`; depth is computed as tip − block + 1, with a\n // direct read kept for older deployments that still serve the field.\n let confirmationDepth: number;\n if (typeof infoEntry.num_confirmations === 'number') {\n confirmationDepth = requireNonNegativeInt(infoEntry.num_confirmations, 'num_confirmations');\n // A served count of 0 for a transaction the provider itself reports as\n // on-chain is the same self-contradiction as a lagging tip (see\n // depthFromHeights): the snapshot is unusable.\n if (confirmationDepth < 1) {\n throw new Error(\n 'inconsistent provider snapshot: num_confirmations is 0 for an on-chain transaction',\n );\n }\n } else {\n const txBlockHeight = requireNonNegativeInt(infoEntry.block_height, 'block_height');\n const tipRes = await fetchFn(`${koiosUrl}/tip`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n return { kind: 'unusable', detail: `${koiosUrl}: tip returned HTTP ${tipRes.status}` };\n }\n const tipJson = parseJson(tipRes.bytes);\n if (!Array.isArray(tipJson) || tipJson.length === 0) {\n return { kind: 'unusable', detail: `${koiosUrl}: tip returned no entry` };\n }\n const tipEntry = tipJson[0] as { block_height?: unknown };\n const tipHeight = requireNonNegativeInt(tipEntry.block_height, 'tip.block_height');\n confirmationDepth = depthFromHeights(tipHeight, txBlockHeight);\n }\n\n return {\n kind: 'served',\n resolved: {\n txCbor,\n components: bound.components,\n confirmationDepth,\n blockTime: requireNonNegativeInt(infoEntry.tx_timestamp, 'tx_timestamp'),\n blockSlot: requireNonNegativeInt(infoEntry.absolute_slot, 'absolute_slot'),\n provider: 'koios',\n providerUrl: koiosUrl,\n },\n };\n } catch (e) {\n // A denyHosts hit is a run-level service-independence violation, not a\n // provider-availability outcome; the pipeline reports it as such.\n if (isDenyHostError(e)) throw e;\n return {\n kind: 'unusable',\n detail: `${koiosUrl}: ${e instanceof Error ? e.message : String(e)}`,\n };\n }\n}\n\nasync function resolveViaBlockfrost(\n txHash: string,\n projectId: string,\n fetchFn: FetchOutbound,\n): Promise<ProviderAttempt> {\n const base = BLOCKFROST_MAINNET_HOST;\n const headers = { project_id: projectId, accept: 'application/json' };\n try {\n const cborRes = await fetchFn(`${base}/txs/${txHash}/cbor`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (cborRes.status === 404) {\n return { kind: 'not_found', detail: `${base} returned 404 for the transaction` };\n }\n if (cborRes.status !== 200) {\n return { kind: 'unusable', detail: `${base}: tx cbor returned HTTP ${cborRes.status}` };\n }\n const cborJson = parseJson(cborRes.bytes) as { cbor?: unknown };\n if (typeof cborJson.cbor !== 'string') {\n return { kind: 'unusable', detail: `${base}: tx cbor response carries no cbor field` };\n }\n const txCbor = hexToBytes(cborJson.cbor);\n const bound = bindFetchedTx({ txHash, txCbor, providerUrl: base });\n if (bound.kind !== 'bound') return bound;\n\n const txRes = await fetchFn(`${base}/txs/${txHash}`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (txRes.status !== 200) {\n return { kind: 'unusable', detail: `${base}: tx info returned HTTP ${txRes.status}` };\n }\n const txJson = parseJson(txRes.bytes) as {\n block_time?: unknown;\n slot?: unknown;\n block_height?: unknown;\n };\n const blockTime = requireNonNegativeInt(txJson.block_time, 'block_time');\n const blockSlot = requireNonNegativeInt(txJson.slot, 'slot');\n // Confirmations are counted in BLOCKS, not slots: Cardano's active-slot\n // coefficient f=0.05 means only ~1 slot in 20 produces a block, so a\n // slot-difference count would inflate depth by ~20×.\n const txBlockHeight = requireNonNegativeInt(txJson.block_height, 'block_height');\n\n const tipRes = await fetchFn(`${base}/blocks/latest`, {\n method: 'GET',\n headers,\n purpose: 'cardano',\n });\n if (tipRes.status !== 200) {\n return { kind: 'unusable', detail: `${base}: blocks/latest returned HTTP ${tipRes.status}` };\n }\n const tipJson = parseJson(tipRes.bytes) as { height?: unknown };\n const tipHeight = requireNonNegativeInt(tipJson.height, 'tip_height');\n\n return {\n kind: 'served',\n resolved: {\n txCbor,\n components: bound.components,\n confirmationDepth: depthFromHeights(tipHeight, txBlockHeight),\n blockTime,\n blockSlot,\n provider: 'blockfrost',\n providerUrl: base,\n },\n };\n } catch (e) {\n if (isDenyHostError(e)) throw e;\n return { kind: 'unusable', detail: `${base}: ${e instanceof Error ? e.message : String(e)}` };\n }\n}\n\n// depth = tip − block + 1; a transaction in the tip block has depth exactly 1.\n// A provider whose tip height is below the height of the block it itself\n// reports for the transaction contradicts its own snapshot. An internally\n// inconsistent snapshot proves only that the provider's view is unusable, so\n// the provider is discarded through the per-provider failure path (the throw\n// lands in the surrounding catch) and contributes no chain facts — a depth is\n// never fabricated by flooring.\nfunction depthFromHeights(tipHeight: number, blockHeight: number): number {\n const depth = tipHeight - blockHeight + 1;\n if (depth < 1) {\n throw new Error(\n `inconsistent provider snapshot: tip height ${tipHeight} is below the transaction's block height ${blockHeight}`,\n );\n }\n return depth;\n}\n\nfunction parseJson(bytes: Uint8Array): unknown {\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\nfunction requireNonNegativeInt(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new Error(`gateway_field_invalid: ${field} (got ${typeof value}=${String(value)})`);\n }\n return value;\n}\n\nfunction hexToBytes(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;\n if (clean.length % 2 !== 0) {\n throw new Error(`hex string has odd length (${clean.length})`);\n }\n if (!/^[0-9a-fA-F]*$/.test(clean)) {\n throw new Error('hex string contains non-hex characters');\n }\n const out = new Uint8Array(clean.length / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return out;\n}\n","// Lowercase, no-`0x`-prefix hex encoder shared across the SDK. Single\n// implementation so the verifier, the wire serialiser, and the publish client\n// all emit byte-identical hex (the Python parity twin and the cross-language\n// fixtures depend on this exact form).\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n","// Label 309 record-level signature verifier.\n//\n// One verification per `record.sigs[i]`. v1 has NO per-item signature slot —\n// the only signature surface is the record-level array. Two on-wire signer-key\n// paths (mutually exclusive on the wire, enforced by the structural\n// validator as `SIG_ENTRY_KID_COSE_KEY_CONFLICT`):\n//\n// Path 1 — protected-header `kid` is exactly 32 bytes (raw Ed25519 pubkey).\n// Path 2 — `sigs[i].cose_key` is a single `cbor<COSE_Key>` byte string\n// carrying the wallet's public key. The protected header carries a\n// 29-byte CIP-19 stake address at label `\"address\"`; the verifier\n// recomputes `expected_network_header || Blake2b-224(pub)` —\n// deriving the network byte from the CONTAINING TRANSACTION's\n// network, never echoing the byte found in the record — and\n// rejects on any of the 29 bytes (`WALLET_ADDRESS_MISMATCH`).\n//\n// The producer's protected-header bytes are used VERBATIM as\n// `Sig_structure[1]` — never re-encoded or re-canonicalised (RFC 9052 §4.4) —\n// and the signing body is the canonical de-chunked record body with `sigs`\n// removed; both rules are enforced by `coseSign1Label309Verify` in\n// `@cardanowall/crypto-core/cose`. Ed25519 verification is strict per\n// RFC 8032 §5.1.7 (canonical R/S, low-order rejection, no cofactor\n// multiplication).\n//\n// Record signatures are OPTIONAL: a public hash-only PoE remains valid even\n// when every signature entry is unverifiable (SIGNATURE_UNSUPPORTED, info).\n// Every `unsupported` per-signature verdict puts SIGNATURE_UNSUPPORTED (info)\n// at ['sigs', i] EXACTLY ONCE: the structural validator contributes the same\n// issue for UNREGISTERED algorithms, while a registered-but-unimplemented\n// algorithm is only detected here, so this pass emits idempotently against\n// the sink. Error-class failures (SIGNATURE_INVALID, SIGNER_KEY_UNRESOLVED,\n// WALLET_ADDRESS_MISMATCH, MALFORMED_SIG_COSE_SIGN1) raise issues into the\n// run's sink and fail the record.\n\nimport {\n encodeRecordBodyForSigning,\n type PoeRecord,\n type SigEntry,\n} from '@cardanowall/poe-standard';\nimport {\n coseSign1Label309Verify,\n decodeCoseSign1,\n parseCoseKeyEd25519,\n type CoseSign1Decoded,\n} from '@cardanowall/crypto-core/cose';\nimport { blake2b224 } from '@cardanowall/crypto-core/hash';\nimport { compareCt } from '@cardanowall/crypto-core/util';\n\nimport { bytesToHex } from '../hex';\nimport type { IssueSink } from './issues';\nimport type { SignatureFailureReason, VerifyRecordSignature } from './types';\n\n// v1 wallet-path constraint: stake (reward) addresses only. The 29-byte\n// CIP-19 layout is `network_header_byte || Blake2b-224(stake_vk)`; stake\n// network bytes: mainnet = 0xe1, testnet = 0xe0 (preprod and preview share\n// the testnet header).\nconst CARDANO_MAINNET_STAKE_NETWORK_BYTE = 0xe1;\nconst CARDANO_PREPROD_STAKE_NETWORK_BYTE = 0xe0;\nconst CARDANO_STAKE_ADDRESS_LENGTH = 29;\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst BLAKE2B_224_LENGTH = 28;\n\nexport interface VerifyRecordSignaturesArgs {\n readonly record: PoeRecord;\n readonly cardanoNetwork: 'mainnet' | 'preprod';\n readonly issues: IssueSink;\n}\n\nexport function verifyRecordSignatures(args: VerifyRecordSignaturesArgs): VerifyRecordSignature[] {\n const { record } = args;\n // The signed payload is canonical-CBOR(record_body), where record_body =\n // record minus `sigs`. The encoder helper keeps the wire shape and key sort\n // in lockstep with producer-side signing.\n const recordBodyCbor = encodeRecordBodyForSigning(record);\n const list = record.sigs ?? [];\n const out: VerifyRecordSignature[] = [];\n for (let i = 0; i < list.length; i++) {\n const result = verifyOneSig(i, list[i]!, recordBodyCbor, args.cardanoNetwork);\n out.push(result);\n if (result.verdict === 'invalid' || result.verdict === 'unresolved') {\n args.issues.add(\n result.reason ?? 'SIGNATURE_INVALID',\n ['sigs', i],\n signatureFailureMessage(result),\n );\n } else if (result.verdict === 'unsupported') {\n // An unsupported entry MUST surface as exactly one SIGNATURE_UNSUPPORTED\n // (info) at ['sigs', i]. The idempotent add covers both ways an entry\n // gets here: an UNREGISTERED algorithm (the structural validator already\n // contributed the identical issue) and a registered algorithm this\n // verifier does not implement (only this pass detects it).\n args.issues.addOnce(\n 'SIGNATURE_UNSUPPORTED',\n ['sigs', i],\n 'the COSE_Sign1 signature algorithm is not implemented by this verifier; the entry is unsupported, not invalid',\n );\n }\n }\n return out;\n}\n\nfunction signatureFailureMessage(result: VerifyRecordSignature): string {\n switch (result.reason) {\n case 'MALFORMED_SIG_COSE_SIGN1':\n return 'the cose_sign1 blob is not a verifiable detached COSE_Sign1';\n case 'SIGNER_KEY_UNRESOLVED':\n return 'neither key-resolution path yielded a 32-byte Ed25519 public key';\n case 'WALLET_ADDRESS_MISMATCH':\n return 'the wallet-path protected-header address does not equal the recomputed network_header || Blake2b-224(pubkey)';\n default:\n return 'strict Ed25519 verification failed against the resolved public key';\n }\n}\n\nfunction verifyOneSig(\n index: number,\n entry: SigEntry,\n recordBodyCbor: Uint8Array,\n cardanoNetwork: 'mainnet' | 'preprod',\n): VerifyRecordSignature {\n const coseBytes = entry.cose_sign1;\n let cose: CoseSign1Decoded;\n try {\n cose = decodeCoseSign1(coseBytes);\n } catch {\n return { index, verdict: 'invalid', reason: 'MALFORMED_SIG_COSE_SIGN1' };\n }\n\n // Resolve the signer's 32-byte Ed25519 pubkey (path 1 vs path 2).\n const resolved = resolveSignerKey(cose, entry);\n if (resolved.kind === 'unresolved') {\n return { index, verdict: 'unresolved', reason: 'SIGNER_KEY_UNRESOLVED' };\n }\n const { pub, signerType } = resolved;\n\n // Strict Ed25519 verify; Sig_structure[1] is the producer's protected bytes\n // verbatim.\n const verifyResult = coseSign1Label309Verify({\n message: coseBytes,\n detachedRecordBodyCbor: recordBodyCbor,\n expectedSignerKey: pub,\n });\n\n if (!verifyResult.ok) {\n const reason = mapVerifyError(verifyResult.error.code);\n if (reason === 'SIGNATURE_UNSUPPORTED') {\n return {\n index,\n verdict: 'unsupported',\n signerType,\n signerPub: bytesToHex(pub),\n reason,\n };\n }\n return {\n index,\n verdict: 'invalid',\n signerType,\n signerPub: bytesToHex(pub),\n reason,\n };\n }\n\n // Path-2 wallet `address` ↔ `cose_key` binding. Path-1 entries skip this\n // check entirely.\n if (signerType === 'wallet-inline-key') {\n const addressOk = checkWalletAddressBinding(cose, pub, cardanoNetwork);\n if (!addressOk) {\n return {\n index,\n verdict: 'invalid',\n signerType,\n signerPub: bytesToHex(pub),\n reason: 'WALLET_ADDRESS_MISMATCH',\n };\n }\n }\n\n return {\n index,\n verdict: 'valid',\n signerType,\n signerPub: bytesToHex(pub),\n };\n}\n\ninterface ResolvedPathOne {\n readonly kind: 'in-signature-kid';\n readonly pub: Uint8Array;\n readonly signerType: 'in-signature-kid';\n}\ninterface ResolvedPathTwo {\n readonly kind: 'wallet-inline-key';\n readonly pub: Uint8Array;\n readonly signerType: 'wallet-inline-key';\n}\ntype ResolvedKey = ResolvedPathOne | ResolvedPathTwo | { readonly kind: 'unresolved' };\n\nfunction resolveSignerKey(cose: CoseSign1Decoded, entry: SigEntry): ResolvedKey {\n // Path 1 — protected-header label 4 (`kid`) as the 32-byte raw Ed25519\n // pubkey. Unprotected-header `kid` values are NEVER consulted: they sit\n // outside the COSE integrity envelope and an attacker could rewrite them.\n const protectedKid = cose.protectedHeader.get(4) as unknown;\n if (\n protectedKid instanceof Uint8Array &&\n protectedKid.length === ED25519_PUBLIC_KEY_LENGTH &&\n entry.cose_key === undefined\n ) {\n return {\n kind: 'in-signature-kid',\n pub: protectedKid,\n signerType: 'in-signature-kid',\n };\n }\n // Path 2 — a single `cbor<COSE_Key>` byte string carrying the wallet pubkey.\n if (entry.cose_key !== undefined) {\n const pub = parseCoseKeyEd25519(entry.cose_key);\n if (pub !== null && pub.length === ED25519_PUBLIC_KEY_LENGTH) {\n return { kind: 'wallet-inline-key', pub, signerType: 'wallet-inline-key' };\n }\n }\n return { kind: 'unresolved' };\n}\n\nfunction mapVerifyError(code: string): SignatureFailureReason {\n switch (code) {\n case 'MALFORMED_SIG_COSE':\n case 'MALFORMED_SIG_COSE_SIGN1':\n return 'MALFORMED_SIG_COSE_SIGN1';\n case 'UNSUPPORTED_SIG_ALG':\n return 'SIGNATURE_UNSUPPORTED';\n case 'KID_UNRESOLVED':\n return 'SIGNER_KEY_UNRESOLVED';\n case 'SIGNATURE_INVALID':\n return 'SIGNATURE_INVALID';\n default:\n return 'SIGNATURE_INVALID';\n }\n}\n\n// Recompute the 29-byte stake address from the resolved Ed25519 pubkey and\n// compare it byte-exact (constant-time) to the path-2 protected-header\n// `address` field. The wallet path binds to stake (reward) addresses only in\n// v1 — base/enterprise/pointer/payment addresses fail the equality check\n// against the recomputed 29-byte stake address.\nfunction checkWalletAddressBinding(\n cose: CoseSign1Decoded,\n pub: Uint8Array,\n cardanoNetwork: 'mainnet' | 'preprod',\n): boolean {\n const networkByte =\n cardanoNetwork === 'preprod'\n ? CARDANO_PREPROD_STAKE_NETWORK_BYTE\n : CARDANO_MAINNET_STAKE_NETWORK_BYTE;\n const rawAddress = cose.protectedHeader.get('address') as unknown;\n if (!(rawAddress instanceof Uint8Array)) {\n // `address` is REQUIRED on the wallet path: a wallet signature without an\n // address claim cannot be safely surfaced as wallet-bound.\n return false;\n }\n if (rawAddress.length !== CARDANO_STAKE_ADDRESS_LENGTH) return false;\n const stakeKeyHash = blake2b224(pub);\n if (stakeKeyHash.length !== BLAKE2B_224_LENGTH) {\n // Defensive guard — `blake2b224` is byte-pinned to 28 bytes.\n return false;\n }\n const derived = new Uint8Array(CARDANO_STAKE_ADDRESS_LENGTH);\n derived[0] = networkByte;\n derived.set(stakeKeyHash, 1);\n return compareCt(derived, rawAddress);\n}\n","// Transaction-level decode for the Label 309 verifier.\n//\n// This module surfaces the Cardano TRANSACTION that carried a PoE record: which\n// wallet vkey(s) signed it, the fee, the outputs, and the co-published metadata\n// labels. It answers \"who authorised and paid for this anchoring\" — distinct\n// from the record-level COSE authorship signatures handled in `signatures.ts`.\n//\n// Unlike label-309 extraction, this decode is purely INFORMATIONAL: it is not\n// fed back into the structural validator, so it is not subject to the\n// canonical-CBOR byte-faithfulness concern that forces `cbor-walker` to slice\n// rather than decode. We therefore decode the body + witness-set slices with\n// the permissive CBOR decoder. The slices themselves are still byte-faithful —\n// `decodeTxWitnesses` verifies each signature against `blake2b256(txBody)`,\n// which only equals the on-chain transaction hash when the body bytes are\n// exactly as produced.\n\nimport { decodeCbor } from '@cardanowall/crypto-core/cbor';\nimport { blake2b224, blake2b256 } from '@cardanowall/crypto-core/hash';\nimport { verifyEd25519 } from '@cardanowall/crypto-core/sig';\n\nimport { bytesToHex } from '../hex';\nimport type { VerifyTxOutput, VerifyTxSummary, VerifyTxWitness } from './types';\n\nconst ED25519_PUBLIC_KEY_LENGTH = 32;\nconst ED25519_SIGNATURE_LENGTH = 64;\n\n// Conway-era transaction body map keys (RFC-style integer keys).\nconst BODY_KEY_INPUTS = 0;\nconst BODY_KEY_OUTPUTS = 1;\nconst BODY_KEY_FEE = 2;\nconst BODY_KEY_INVALID_HEREAFTER = 3; // ttl\nconst BODY_KEY_INVALID_BEFORE = 8; // validity_interval_start\nconst BODY_KEY_REQUIRED_SIGNERS = 14;\nconst BODY_KEY_NETWORK_ID = 15;\n\n// Witness-set map keys. Key 0 is the vkey witness set; every other key\n// (native scripts, bootstrap witnesses, Plutus v1/v2/v3) is counted as a\n// \"script/other\" witness without being deep-decoded.\nconst WITNESS_KEY_VKEY = 0;\n\n// inputs, vkey_witnesses, and required_signers are CBOR sets (tag 258). The\n// permissive decoder may surface a set as a JS `Set` or an `Array` depending\n// on how the producer encoded it; normalise both to an array.\nfunction asArray(v: unknown): unknown[] {\n if (v instanceof Set) return [...v];\n if (Array.isArray(v)) return v;\n return [];\n}\n\nfunction asMap(v: unknown): Map<unknown, unknown> | null {\n return v instanceof Map ? v : null;\n}\n\n/**\n * Decode the vkey witnesses of a transaction and verify each signature against\n * the transaction body.\n *\n * Each Cardano vkey witness is `[vkey(32B), signature(64B)]`; the signed\n * message is `blake2b256(txBody)` (the transaction hash). A witness whose vkey\n * or signature is malformed, or whose signature does not verify, is reported\n * with `signature_valid: false` rather than dropped — the caller surfaces it\n * informationally and never fails the record on it.\n */\nexport function decodeTxWitnesses(\n witnessSetBytes: Uint8Array,\n txBodyBytes: Uint8Array,\n): VerifyTxWitness[] {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return [];\n const vkeyWitnesses = asArray(witnessSet.get(WITNESS_KEY_VKEY));\n const txHash = blake2b256(txBodyBytes);\n\n const out: VerifyTxWitness[] = [];\n for (const entry of vkeyWitnesses) {\n const pair = asArray(entry);\n const vkey = pair[0];\n const signature = pair[1];\n if (\n !(vkey instanceof Uint8Array) ||\n vkey.length !== ED25519_PUBLIC_KEY_LENGTH ||\n !(signature instanceof Uint8Array) ||\n signature.length !== ED25519_SIGNATURE_LENGTH\n ) {\n // A structurally malformed witness still describes an attempted\n // authorisation; surface what we can (when the vkey is a valid pubkey)\n // and mark the signature invalid.\n if (vkey instanceof Uint8Array && vkey.length === ED25519_PUBLIC_KEY_LENGTH) {\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: false,\n });\n }\n continue;\n }\n let signatureValid: boolean;\n try {\n signatureValid = verifyEd25519({ publicKey: vkey, message: txHash, signature });\n } catch {\n signatureValid = false;\n }\n out.push({\n type: 'vkey',\n vkey: bytesToHex(vkey),\n key_hash: bytesToHex(blake2b224(vkey)),\n signature_valid: signatureValid,\n });\n }\n return out;\n}\n\n/**\n * Count the witness-set entries that are NOT vkey witnesses (native scripts,\n * bootstrap witnesses, Plutus v1/v2/v3). These are summed as a single\n * \"script/other\" count without deep-decoding their contents.\n */\nfunction countScriptWitnesses(witnessSetBytes: Uint8Array): number {\n const witnessSet = asMap(decodeCbor(witnessSetBytes));\n if (witnessSet === null) return 0;\n let count = 0;\n for (const [key, value] of witnessSet) {\n if (key === WITNESS_KEY_VKEY) continue;\n count += asArray(value).length;\n }\n return count;\n}\n\n/**\n * Decode a transaction body into a JSON-safe summary: fee, input/output counts,\n * the output addresses + lovelace amounts, validity interval, required signer\n * key hashes, and network id.\n *\n * All lovelace amounts are serialised as DECIMAL STRINGS so they survive JSON\n * round-trips exactly (Cardano coin values can exceed `Number.MAX_SAFE_INTEGER`\n * and BigInt is not JSON-native). Coin math is performed with BigInt internally.\n */\nexport function decodeTxSummary(\n txBodyBytes: Uint8Array,\n witnessSetBytes: Uint8Array,\n network: 'mainnet' | 'preprod',\n): VerifyTxSummary {\n const body = asMap(decodeCbor(txBodyBytes));\n if (body === null) {\n throw new RangeError('MALFORMED_CBOR: tx body is not a CBOR map');\n }\n\n const inputs = asArray(body.get(BODY_KEY_INPUTS));\n const outputsRaw = asArray(body.get(BODY_KEY_OUTPUTS));\n\n const outputs: VerifyTxOutput[] = [];\n let totalOutput = 0n;\n for (const o of outputsRaw) {\n const { addressBytes, lovelace } = readOutput(o);\n totalOutput += lovelace;\n outputs.push({\n address: encodeCardanoAddress(addressBytes, network),\n lovelace: lovelace.toString(),\n });\n }\n\n const requiredSigners = asArray(body.get(BODY_KEY_REQUIRED_SIGNERS))\n .filter((s): s is Uint8Array => s instanceof Uint8Array)\n .map((s) => bytesToHex(s));\n\n const summary: {\n -readonly [K in keyof VerifyTxSummary]: VerifyTxSummary[K];\n } = {\n fee_lovelace: coinToString(body.get(BODY_KEY_FEE)),\n input_count: inputs.length,\n output_count: outputs.length,\n outputs,\n total_output_lovelace: totalOutput.toString(),\n script_witness_count: countScriptWitnesses(witnessSetBytes),\n };\n\n const invalidBefore = body.get(BODY_KEY_INVALID_BEFORE);\n if (typeof invalidBefore === 'number') summary.invalid_before = invalidBefore;\n else if (typeof invalidBefore === 'bigint') summary.invalid_before = Number(invalidBefore);\n\n const invalidHereafter = body.get(BODY_KEY_INVALID_HEREAFTER);\n if (typeof invalidHereafter === 'number') summary.invalid_hereafter = invalidHereafter;\n else if (typeof invalidHereafter === 'bigint')\n summary.invalid_hereafter = Number(invalidHereafter);\n\n if (requiredSigners.length > 0) summary.required_signer_key_hashes = requiredSigners;\n\n const networkId = body.get(BODY_KEY_NETWORK_ID);\n if (typeof networkId === 'number') summary.network_id = networkId;\n else if (typeof networkId === 'bigint') summary.network_id = Number(networkId);\n\n return summary;\n}\n\n// A transaction output is EITHER a legacy array `[address, amount]` OR a map\n// `{0: address, 1: amount}` (post-Babbage). `amount` is either a bare coin\n// (uint) or a `[coin, multiasset]` pair — only the coin (lovelace) component is\n// summarised here.\nfunction readOutput(output: unknown): { addressBytes: Uint8Array; lovelace: bigint } {\n let address: unknown;\n let amount: unknown;\n if (Array.isArray(output)) {\n address = output[0];\n amount = output[1];\n } else if (output instanceof Map) {\n address = output.get(0);\n amount = output.get(1);\n } else {\n throw new RangeError('MALFORMED_CBOR: tx output is neither a CBOR array nor a CBOR map');\n }\n if (!(address instanceof Uint8Array)) {\n throw new RangeError('MALFORMED_CBOR: tx output address is not a byte string');\n }\n const lovelace = Array.isArray(amount) ? toBigInt(amount[0]) : toBigInt(amount);\n return { addressBytes: address, lovelace };\n}\n\nfunction coinToString(v: unknown): string {\n return toBigInt(v).toString();\n}\n\nfunction toBigInt(v: unknown): bigint {\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isInteger(v)) return BigInt(v);\n throw new RangeError(`MALFORMED_CBOR: expected an integer coin value, got ${typeof v}`);\n}\n\n// -----------------------------------------------------------------------------\n// Cardano address bech32 encoding (BIP-173, the CIP-19 bech32 form).\n// -----------------------------------------------------------------------------\n//\n// Implemented inline so the published SDK keeps a minimal, auditable dependency\n// surface (the verifier's only third-party deps are the cryptographic core).\n// The header byte's high nibble is the address type and its low nibble is the\n// network id (0 = testnet, 1 = mainnet). Payment-address types 0–7 use the\n// `addr` HRP; stake/reward types 14–15 use the `stake` HRP. The header's\n// network nibble is authoritative for the `_test` suffix; the caller's\n// `network` argument is the fallback when a header is ambiguous.\n\nconst BECH32_CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';\n\nfunction encodeCardanoAddress(addressBytes: Uint8Array, network: 'mainnet' | 'preprod'): string {\n if (addressBytes.length === 0) {\n throw new RangeError('MALFORMED_CBOR: empty address byte string');\n }\n const header = addressBytes[0]!;\n const addressType = header >> 4;\n const networkNibble = header & 0x0f;\n const isStake = addressType === 14 || addressType === 15;\n // The header's network nibble is authoritative. Fall back to the caller's\n // network only when the nibble is not the canonical 0 (testnet) / 1 (mainnet).\n const isTestnet =\n networkNibble === 0 ? true : networkNibble === 1 ? false : network === 'preprod';\n const base = isStake ? 'stake' : 'addr';\n const hrp = isTestnet ? `${base}_test` : base;\n return bech32Encode(hrp, addressBytes);\n}\n\nfunction bech32Polymod(values: number[]): number {\n const generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n let chk = 1;\n for (const value of values) {\n const top = chk >> 25;\n chk = ((chk & 0x1ffffff) << 5) ^ value;\n for (let i = 0; i < 5; i++) {\n if ((top >> i) & 1) chk ^= generators[i]!;\n }\n }\n return chk;\n}\n\nfunction bech32HrpExpand(hrp: string): number[] {\n const out: number[] = [];\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) >> 5);\n out.push(0);\n for (let i = 0; i < hrp.length; i++) out.push(hrp.charCodeAt(i) & 31);\n return out;\n}\n\n// 8-bit → 5-bit regrouping with zero-padding of the final group (the encode\n// direction always pads).\nfunction bech32ToWords(data: Uint8Array): number[] {\n let acc = 0;\n let bits = 0;\n const out: number[] = [];\n const maxv = (1 << 5) - 1;\n for (const value of data) {\n acc = (acc << 8) | value;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out.push((acc >> bits) & maxv);\n }\n }\n if (bits > 0) out.push((acc << (5 - bits)) & maxv);\n return out;\n}\n\nfunction bech32Encode(hrp: string, data: Uint8Array): string {\n const words = bech32ToWords(data);\n const polymodInput = bech32HrpExpand(hrp).concat(words, [0, 0, 0, 0, 0, 0]);\n const polymod = bech32Polymod(polymodInput) ^ 1;\n const checksum: number[] = [];\n for (let i = 0; i < 6; i++) checksum.push((polymod >> (5 * (5 - i))) & 31);\n let result = `${hrp}1`;\n for (const w of words.concat(checksum)) result += BECH32_CHARSET.charAt(w);\n return result;\n}\n","// Label 309 standalone verifier — the Part B pipeline.\n//\n// `verifyTx` executes, in order; a step whose outcome forecloses the rest\n// short-circuits the pipeline:\n//\n// 1. Resolve the transaction via the explorer chain (raw tx CBOR, never a\n// JSON projection). Negative outcomes split three ways: TX_NOT_FOUND /\n// PROVIDER_UNAVAILABLE → `unverifiable`.\n// 2. Bind the fetched bytes to the transaction reference — blake2b-256\n// over the body vs the requested hash, blake2b-256 over the auxiliary\n// data vs the body's auxiliary_data_hash; no surviving response →\n// TX_INTEGRITY_MISMATCH, `unverifiable` (provider-provable, never\n// record-attributable).\n// 3. Unwrap the auxiliary data (all three Conway envelope forms, dispatch\n// on type/tag only) and reassemble the label-309 chunk array. No\n// label-309 entry → METADATA_NOT_FOUND, `failed` (the absence is\n// proven by the integrity-bound transaction itself).\n// 4. Structurally validate (`validatePoeRecord`), with the validator role\n// matching the verifier mode: a run that will actually decrypt —\n// decryption credentials held AND the profile admits sealed decryption\n// — is a RECIPIENT verifier ('recipient_or_strict'); otherwise 'public'.\n// 5. Check confirmation depth — below threshold → INSUFFICIENT_CONFIRMATIONS,\n// verdict `pending`, pipeline halts (results computed against a\n// transaction that may yet be orphaned must not be presented as final).\n// 6. Verify record signatures (strict Ed25519, detached payload, verbatim\n// protected bytes, wallet-address network binding).\n// 7. Fetch and hash-check plain-item content and Merkle leaves-lists\n// (first-success-for-availability; integrity vs attribution vs\n// availability split; suppressed by `fetchContent: false`).\n// 8. Decrypt `enc`-bearing items with the keyring (recipient verifier),\n// including the post-decryption plaintext-hash recheck.\n// 9. (`supersedes` is an advisory pointer; this implementation performs\n// no existence hop.)\n// 10. Emit the report: verdict ∈ valid | pending | unverifiable | failed,\n// exit codes 0 | 3 | 2 | 1 respectively, issues sorted by path then\n// registry order, one per-claim entry per item / commitment, and the\n// complete audit trail of every outbound call.\n//\n// `verifyResolved` runs the same pipeline from step 4 onward over\n// caller-supplied record-body bytes plus an explorer-asserted block-info\n// tuple.\n\nimport {\n SEVERITY,\n reassembleLabel309Value,\n validatePoeRecord,\n type ErrorCode,\n type PoeRecord,\n type ValidationIssue,\n} from '@cardanowall/poe-standard';\n\nimport { defaultFetchOutbound, isDenyHostError, wrapFetchOutbound } from '../fetch/fetch-outbound';\nimport { ARWEAVE_GATEWAY_DEFAULTS, type ContentFetchContext } from './content';\nimport { sliceTxComponents, unwrapAuxiliaryData } from './cbor-walker';\nimport { decryptItem } from './decrypt';\nimport { checkItemContent } from './items';\nimport { IssueSink, issueOf, sortIssues } from './issues';\nimport { checkMerkleCommit, type MerkleCommitOutcome } from './merkle';\nimport { DEFAULT_PROFILE, planProfileSkips } from './profile';\nimport { resolveCardanoTx } from './resolve';\nimport { verifyRecordSignatures } from './signatures';\nimport { decodeTxSummary, decodeTxWitnesses } from './tx-witnesses';\nimport type {\n ExitCode,\n HttpCallRecord,\n ItemReportEntry,\n MerkleReportEntry,\n Profile,\n Verdict,\n VerifyReport,\n VerifyResolvedInput,\n VerifyTxInput,\n} from './types';\nimport { EXIT_CODE_FOR_VERDICT, PROFILE_RANK } from './types';\n\nexport const CONFIRMATION_DEPTH_THRESHOLD_DEFAULT = 15;\n\n// Error-severity codes that are NOT record-attributable: network, policy, and\n// provider-integrity outcomes. They block a `valid` verdict but can never\n// condemn the record — the verdict they produce is `unverifiable`. Every\n// other error-severity code is record-attributable and produces `failed`.\nconst NETWORK_CLASS_CODES: ReadonlySet<ErrorCode> = new Set<ErrorCode>([\n 'TX_NOT_FOUND',\n 'PROVIDER_UNAVAILABLE',\n 'TX_INTEGRITY_MISMATCH',\n 'CONTENT_UNAVAILABLE',\n 'CONTENT_FETCH_LIMIT_EXCEEDED',\n 'CIPHERTEXT_UNAVAILABLE',\n 'MERKLE_LEAVES_UNAVAILABLE',\n 'URI_TARGET_FORBIDDEN',\n]);\n\nfunction verdictFromIssues(issues: ReadonlyArray<ValidationIssue>): Verdict {\n let sawNetworkError = false;\n for (const issue of issues) {\n if (issue.severity !== 'error') continue;\n if (!NETWORK_CLASS_CODES.has(issue.code)) return 'failed';\n sawNetworkError = true;\n }\n return sawNetworkError ? 'unverifiable' : 'valid';\n}\n\ninterface ChainFacts {\n readonly confirmationDepth: number;\n readonly blockTime: number;\n readonly blockSlot?: number | undefined;\n}\n\ninterface ReportSkeleton {\n readonly txHash: string;\n readonly network: string;\n readonly profile: Profile;\n readonly threshold: number;\n readonly auditTrail: HttpCallRecord[];\n readonly chainFacts?: ChainFacts | undefined;\n readonly txDescription: TxDescriptionFields;\n}\n\nfunction assembleReport(args: {\n readonly skeleton: ReportSkeleton;\n readonly issues: ReadonlyArray<ValidationIssue>;\n readonly verdict: Verdict;\n readonly items?: ReadonlyArray<ItemReportEntry>;\n readonly merkle?: ReadonlyArray<MerkleReportEntry>;\n readonly record?: PoeRecord | undefined;\n readonly signatures?: VerifyReport['signatures'] | undefined;\n}): VerifyReport {\n const { skeleton } = args;\n const exitCode: ExitCode = EXIT_CODE_FOR_VERDICT[args.verdict];\n const facts = skeleton.chainFacts;\n return {\n verdict: args.verdict,\n exitCode,\n issues: sortIssues(args.issues),\n items: args.items ?? [],\n merkle: args.merkle ?? [],\n auditTrail: skeleton.auditTrail,\n network: skeleton.network,\n txHash: skeleton.txHash,\n profile: skeleton.profile,\n confirmationThreshold: skeleton.threshold,\n ...(facts !== undefined\n ? {\n confirmationDepth: facts.confirmationDepth,\n block_time: facts.blockTime,\n ...(facts.blockSlot !== undefined ? { block_slot: facts.blockSlot } : {}),\n }\n : {}),\n ...(args.record !== undefined ? { record: args.record } : {}),\n ...(args.signatures !== undefined && args.signatures.length > 0\n ? { signatures: args.signatures }\n : {}),\n ...skeleton.txDescription,\n };\n}\n\nexport async function verifyTx(input: VerifyTxInput): Promise<VerifyReport> {\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n const cardanoNetwork = input.cardanoNetwork ?? 'mainnet';\n const auditTrail: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n auditTrail,\n input.denyHosts,\n );\n\n const baseSkeleton: ReportSkeleton = {\n txHash: input.txHash,\n network: `cardano:${cardanoNetwork}`,\n profile,\n threshold,\n auditTrail,\n txDescription: {},\n };\n\n try {\n return await runVerifyTx({ input, profile, threshold, cardanoNetwork, baseSkeleton, fetchFn });\n } catch (e) {\n // A RESOLVE-path call (explorer adapter) targeted a denyHosts entry: the\n // egress hard-failed it and the violation is terminal for the run — no\n // transaction was resolved, so there is nothing to verify. The report\n // carries one SERVICE_INDEPENDENCE_VIOLATION at the empty path, verdict\n // `failed`. Content-path deny-hits never reach here: the content engine\n // records them per attempt at the claim's uris[] path and continues.\n if (isDenyHostError(e)) {\n return assembleReport({\n skeleton: baseSkeleton,\n issues: [issueOf('SERVICE_INDEPENDENCE_VIOLATION', [], e.message)],\n verdict: 'failed',\n });\n }\n throw e;\n }\n}\n\nasync function runVerifyTx(args: {\n readonly input: VerifyTxInput;\n readonly profile: Profile;\n readonly threshold: number;\n readonly cardanoNetwork: 'mainnet' | 'preprod';\n readonly baseSkeleton: ReportSkeleton;\n readonly fetchFn: ReturnType<typeof wrapFetchOutbound>;\n}): Promise<VerifyReport> {\n const { input, profile, threshold, cardanoNetwork, baseSkeleton, fetchFn } = args;\n\n // Steps 1 + 2 — resolve via the explorer chain with the integrity binding\n // applied per response.\n const outcome = await resolveCardanoTx({\n txHash: input.txHash,\n cardanoGatewayChain: input.cardanoGatewayChain,\n blockfrostProjectId: input.blockfrostProjectId,\n fetchFn,\n });\n if (!outcome.ok) {\n const issues = [issueOf(outcome.code, [], outcome.message)];\n return assembleReport({\n skeleton: baseSkeleton,\n issues,\n verdict: verdictFromIssues(issues),\n });\n }\n const { resolved } = outcome;\n const skeleton: ReportSkeleton = {\n ...baseSkeleton,\n chainFacts: {\n confirmationDepth: resolved.confirmationDepth,\n blockTime: resolved.blockTime,\n blockSlot: resolved.blockSlot,\n },\n txDescription: decodeTxDescription(resolved.txCbor, cardanoNetwork),\n };\n\n // Step 3 — unwrap the bound auxiliary data and reassemble the record body.\n let label309: Uint8Array | null;\n try {\n label309 =\n resolved.components.auxiliaryData === null\n ? null\n : unwrapAuxiliaryData(resolved.components.auxiliaryData).label309;\n } catch (e) {\n const issues = [issueOf('MALFORMED_CBOR', [], e instanceof Error ? e.message : String(e))];\n return assembleReport({ skeleton, issues, verdict: 'failed' });\n }\n if (label309 === null) {\n const issues = [\n issueOf(\n 'METADATA_NOT_FOUND',\n [],\n 'the integrity-bound transaction carries no metadata under label 309',\n ),\n ];\n return assembleReport({ skeleton, issues, verdict: 'failed' });\n }\n const reassembly = reassembleLabel309Value(label309);\n if (!reassembly.ok) {\n return assembleReport({ skeleton, issues: [reassembly.issue], verdict: 'failed' });\n }\n\n return verifyRecordBody({\n skeleton,\n recordBody: reassembly.body,\n chainFacts: skeleton.chainFacts!,\n fetchFn,\n input: {\n profile,\n cardanoNetwork,\n threshold,\n fetchContent: input.fetchContent ?? true,\n maxFetchBytes: input.maxFetchBytes,\n decryption: input.decryption ?? [],\n ciphertextBytes: input.ciphertextBytes,\n merkleLeaves: input.merkleLeaves,\n arweaveGateways:\n input.arweaveGatewayChain && input.arweaveGatewayChain.length > 0\n ? input.arweaveGatewayChain\n : ARWEAVE_GATEWAY_DEFAULTS,\n ipfsGateways: input.ipfsGatewayChain ?? [],\n },\n });\n}\n\n/**\n * Sibling entry point: run the pipeline from the structural-validator step\n * onward over caller-supplied label-309 record-body bytes plus an\n * explorer-asserted block-info tuple — the path a server-rendered viewer uses\n * to display on-chain data without a render-time chain fetch. The caller is\n * responsible for the confidence that the bytes came from the label-309\n * metadata of a real Cardano transaction.\n */\nexport async function verifyResolved(input: VerifyResolvedInput): Promise<VerifyReport> {\n // The caller vouches for the block-info tuple, and a transaction in a block\n // has depth = tip − block + 1 ≥ 1 by definition — so a smaller (or\n // non-integer) confirmationDepth is a caller-input error, never a\n // verification outcome.\n if (!Number.isInteger(input.confirmationDepth) || input.confirmationDepth < 1) {\n throw new RangeError(\n `confirmationDepth must be an integer >= 1 (a transaction in the tip block has depth exactly 1); got ${input.confirmationDepth}`,\n );\n }\n const profile = input.profile ?? DEFAULT_PROFILE;\n const threshold = input.confirmationDepthThreshold ?? CONFIRMATION_DEPTH_THRESHOLD_DEFAULT;\n const cardanoNetwork = input.cardanoNetwork ?? 'mainnet';\n const auditTrail: HttpCallRecord[] = [];\n const fetchFn = wrapFetchOutbound(\n input.fetchOutbound ?? defaultFetchOutbound,\n auditTrail,\n input.denyHosts,\n );\n const skeleton: ReportSkeleton = {\n txHash: input.txHash,\n network: input.network ?? `cardano:${cardanoNetwork}`,\n profile,\n threshold,\n auditTrail,\n chainFacts: {\n confirmationDepth: input.confirmationDepth,\n blockTime: input.blockTime,\n blockSlot: input.blockSlot,\n },\n txDescription:\n input.txCbor !== undefined ? decodeTxDescription(input.txCbor, cardanoNetwork) : {},\n };\n // No resolve step runs here, and content-path deny-hits are recorded per\n // attempt inside the content engine, so no DenyHostError can escape.\n return verifyRecordBody({\n skeleton,\n recordBody: input.metadataCbor,\n chainFacts: skeleton.chainFacts!,\n fetchFn,\n input: {\n profile,\n cardanoNetwork,\n threshold,\n fetchContent: input.fetchContent ?? true,\n maxFetchBytes: input.maxFetchBytes,\n decryption: input.decryption ?? [],\n ciphertextBytes: input.ciphertextBytes,\n merkleLeaves: input.merkleLeaves,\n arweaveGateways:\n input.arweaveGatewayChain && input.arweaveGatewayChain.length > 0\n ? input.arweaveGatewayChain\n : ARWEAVE_GATEWAY_DEFAULTS,\n ipfsGateways: input.ipfsGatewayChain ?? [],\n },\n });\n}\n\ninterface PipelineOptions {\n readonly profile: Profile;\n readonly cardanoNetwork: 'mainnet' | 'preprod';\n readonly threshold: number;\n readonly fetchContent: boolean;\n readonly maxFetchBytes: number | undefined;\n readonly decryption: ReadonlyArray<\n { readonly recipientSecretKey: Uint8Array } | { readonly passphrase: string }\n >;\n readonly ciphertextBytes: Readonly<Record<number, Uint8Array>> | undefined;\n readonly merkleLeaves: Readonly<Record<number, Uint8Array>> | undefined;\n readonly arweaveGateways: ReadonlyArray<string>;\n readonly ipfsGateways: ReadonlyArray<string>;\n}\n\nasync function verifyRecordBody(args: {\n readonly skeleton: ReportSkeleton;\n readonly recordBody: Uint8Array;\n readonly chainFacts: ChainFacts;\n readonly fetchFn: ReturnType<typeof wrapFetchOutbound>;\n readonly input: PipelineOptions;\n}): Promise<VerifyReport> {\n const { skeleton, input } = args;\n\n // Step 4 — structural validation, with the role matching the verifier\n // mode: a run that will actually decrypt (credentials held AND the profile\n // implements decryption) is a recipient verifier, whose validator\n // hard-rejects envelopes it cannot fully validate (ENC_UNSUPPORTED\n // escalates to error) — a sealed delivery is never processed under a\n // half-validated envelope. A lower profile never decrypts, so it keeps the\n // public reading even when credentials were supplied.\n const willDecrypt =\n input.decryption.length > 0 && PROFILE_RANK[input.profile] >= PROFILE_RANK['recipient-sealed'];\n const role = willDecrypt ? 'recipient_or_strict' : 'public';\n const validation = validatePoeRecord(args.recordBody, { role });\n if (!validation.valid) {\n return assembleReport({\n skeleton,\n issues: validation.issues,\n verdict: 'failed',\n });\n }\n const record = validation.record;\n const issues = new IssueSink();\n issues.pushAll(validation.warnings ?? []);\n issues.pushAll(validation.info ?? []);\n\n const items = record.items ?? [];\n const merkleCommits = record.merkle ?? [];\n\n // Step 5 — confirmation depth. Below threshold the record is well-formed\n // but not final: verdict `pending`, and the signature / content / decrypt\n // steps are skipped so nothing computed against a possibly-orphaned\n // transaction can be presented as final.\n if (args.chainFacts.confirmationDepth < input.threshold) {\n issues.add(\n 'INSUFFICIENT_CONFIRMATIONS',\n [],\n `confirmation depth ${args.chainFacts.confirmationDepth} is below the threshold ${input.threshold}; signature, content, and decryption steps did not run`,\n );\n return assembleReport({\n skeleton,\n issues: issues.sorted(),\n verdict: 'pending',\n items: items.map(() => ({ contentCheck: 'not_checked' as const })),\n merkle: merkleCommits.map(() => ({ contentCheck: 'not_checked' as const })),\n record,\n });\n }\n\n // Profile gating: fields above the active profile are skipped with\n // OUT_OF_PROFILE_SKIPPED (info) — the record is never invalid solely\n // because this verifier does not implement a profile extension.\n const plan = planProfileSkips(input.profile, record);\n issues.pushAll(plan.skips);\n\n // Step 6 — record-level signatures.\n let signatures: VerifyReport['signatures'];\n if (plan.verifySignatures && (record.sigs?.length ?? 0) > 0) {\n signatures = verifyRecordSignatures({\n record,\n cardanoNetwork: input.cardanoNetwork,\n issues,\n });\n }\n\n // Steps 7 + 8 — content checks and sealed decryption.\n const ctx: ContentFetchContext = {\n fetchFn: args.fetchFn,\n arweaveGateways: input.arweaveGateways,\n ipfsGateways: input.ipfsGateways,\n maxFetchBytes: input.maxFetchBytes,\n issues,\n };\n\n const itemEntries: ItemReportEntry[] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i]!;\n if (item.enc !== undefined && item.enc !== null) {\n if (input.decryption.length > 0 && plan.verifyDecrypt) {\n const result = await decryptItem({\n item,\n itemIndex: i,\n credentials: input.decryption,\n outOfBandCiphertext: input.ciphertextBytes?.[i],\n fetchContent: input.fetchContent,\n ctx,\n });\n itemEntries.push({ contentCheck: result.contentCheck, decryption: result.decryption });\n } else {\n // Public verifier (or a profile below recipient-sealed): a sealed\n // item's plaintext claim cannot be checked without decrypting, and\n // the URIs hold ciphertext, not the committed plaintext.\n itemEntries.push({ contentCheck: 'not_checked' });\n }\n continue;\n }\n const contentCheck = await checkItemContent({\n item,\n itemIndex: i,\n fetchContent: input.fetchContent,\n ctx,\n });\n itemEntries.push({ contentCheck });\n }\n\n const merkleOutcomes: MerkleCommitOutcome[] = [];\n for (let i = 0; i < merkleCommits.length; i++) {\n merkleOutcomes.push(\n await checkMerkleCommit({\n commit: merkleCommits[i]!,\n commitIndex: i,\n outOfBand: input.merkleLeaves?.[i],\n fetchContent: input.fetchContent,\n ctx,\n }),\n );\n }\n\n // The commitment floor resolves the dual severity of\n // MERKLE_LEAVES_UNAVAILABLE: warning when at least one other content\n // commitment of the record was verified in this run, error (network class,\n // verdict `unverifiable`) when the unavailability leaves the record with no\n // verified content commitment.\n const anyCommitmentVerified =\n itemEntries.some((e) => e.contentCheck === 'checked') ||\n merkleOutcomes.some((o) => o.contentCheck === 'checked');\n for (const outcomeEntry of merkleOutcomes) {\n if (outcomeEntry.unavailable === undefined) continue;\n if (outcomeEntry.unavailable.limitExceeded) {\n issues.add(\n 'CONTENT_FETCH_LIMIT_EXCEEDED',\n outcomeEntry.unavailable.path,\n 'a leaves-list fetch was aborted at the maxFetchBytes ceiling; the commitment is unchecked',\n );\n continue;\n }\n issues.add(\n 'MERKLE_LEAVES_UNAVAILABLE',\n outcomeEntry.unavailable.path,\n anyCommitmentVerified\n ? 'no attributable leaves-list could be obtained; another content commitment of the record was verified'\n : 'no attributable leaves-list could be obtained and no content commitment of the record was verified',\n anyCommitmentVerified ? SEVERITY.MERKLE_LEAVES_UNAVAILABLE : 'error',\n );\n }\n\n // Step 10 — verdict + report.\n const sorted = issues.sorted();\n return assembleReport({\n skeleton,\n issues: sorted,\n verdict: verdictFromIssues(sorted),\n items: itemEntries,\n merkle: merkleOutcomes.map((o) => ({ contentCheck: o.contentCheck })),\n record,\n signatures,\n });\n}\n\n// ─── Transaction-level description ───────────────────────────────────────────\n//\n// Decode the witnesses / summary / co-published-labels view from raw tx CBOR.\n// Purely informational: a decode failure degrades to omitting the affected\n// fields and never propagates into the verdict. The label-309 record is\n// validated separately from the record-body bytes; this view only describes\n// the carrying transaction.\n\ntype TxDescriptionFields = Pick<VerifyReport, 'txWitnesses' | 'txSummary' | 'metadataLabels'>;\n\nfunction decodeTxDescription(\n txCbor: Uint8Array,\n network: 'mainnet' | 'preprod',\n): TxDescriptionFields {\n const out: { -readonly [K in keyof TxDescriptionFields]: TxDescriptionFields[K] } = {};\n let components;\n try {\n components = sliceTxComponents(txCbor);\n } catch {\n return out;\n }\n if (components.auxiliaryData !== null) {\n try {\n out.metadataLabels = unwrapAuxiliaryData(components.auxiliaryData).metadataLabels;\n } catch {\n // leave metadataLabels undefined\n }\n } else {\n out.metadataLabels = [];\n }\n try {\n out.txWitnesses = decodeTxWitnesses(components.witnessSet, components.txBody);\n } catch {\n // leave txWitnesses undefined\n }\n try {\n out.txSummary = decodeTxSummary(components.txBody, components.witnessSet, network);\n } catch {\n // leave txSummary undefined\n }\n return out;\n}\n\n// Convenience so callers can map verdicts to exit codes without importing the\n// union shape.\nexport function exitCodeForVerdict(report: VerifyReport): ExitCode {\n return report.exitCode;\n}\n\nexport type { Verdict, ExitCode };\n","// Canonical JSON-form serializer for VerifyReport. The report's property\n// names already follow the published verify-report schema, so this helper\n// exists only to normalise non-JSON-native values:\n// * `Uint8Array` → lowercase hex (no `0x` prefix).\n// * `undefined` / `null` values are OMITTED — except the audit-trail\n// `status`, which the published schema REQUIRES on every entry with null\n// as the no-response reading, so it serialises as JSON null.\n// * `Map` is rejected — the report shape does not allow it and any stray\n// instance points at an internal bug, not a data shape we should silently\n// serialise.\n\nimport { bytesToHex } from '../hex';\nimport type { HttpCallRecord, VerifyReport } from './types';\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (v === null || typeof v !== 'object') return false;\n if (Array.isArray(v) || v instanceof Uint8Array || v instanceof Map || v instanceof Set) {\n return false;\n }\n return true;\n}\n\nfunction walk(value: unknown): unknown {\n if (value === undefined || value === null) return undefined;\n if (value instanceof Uint8Array) return bytesToHex(value);\n if (value instanceof Map) {\n throw new Error('unsupported Map in VerifyReport tree');\n }\n if (Array.isArray(value)) {\n return value.map((v) => walk(v));\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (v === undefined || v === null) continue;\n const walked = walk(v);\n if (walked === undefined) continue;\n out[k] = walked;\n }\n return out;\n }\n return value;\n}\n\n// Audit-trail entries carry a fixed schema-pinned shape; serialised\n// explicitly so the required `status` key survives as JSON null when no HTTP\n// response was received (the generic walk omits nulls).\nfunction auditEntryToDict(call: HttpCallRecord): Record<string, unknown> {\n return {\n url: call.url,\n method: call.method,\n status: call.status,\n bytes: call.bytes,\n durationMs: call.durationMs,\n purpose: call.purpose,\n };\n}\n\nexport function verifyReportToDict(report: VerifyReport): Record<string, unknown> {\n const out = walk(report);\n if (!isPlainObject(out)) {\n throw new Error('verifyReportToDict: walk produced non-object root');\n }\n out['auditTrail'] = report.auditTrail.map((call) => auditEntryToDict(call));\n return out;\n}\n","#!/usr/bin/env node\n// Conformance CLI: single-tx verification against the Label 309 standalone\n// verifier.\n//\n// Exit codes mirror the verifier's four-state mapping; 4 and higher denote\n// verifier-host failures that are not record-attributable:\n// 0 = valid, 1 = failed, 2 = unverifiable, 3 = pending,\n// 4 = CLI input error or verifier-host runtime failure\n\nimport {\n KOIOS_MAINNET_URL,\n exitCodeForVerdict,\n verifyReportToDict,\n verifyTx,\n} from '../verifier/index';\n\nconst VERSION = '0.1.0';\n\ninterface ParsedArgs {\n readonly txHash: string | undefined;\n readonly gateways: ReadonlyArray<string>;\n readonly threshold: number | undefined;\n readonly json: boolean;\n readonly showHelp: boolean;\n readonly showVersion: boolean;\n readonly error: string | undefined;\n}\n\nexport function parseArgs(args: ReadonlyArray<string>): ParsedArgs {\n let txHash: string | undefined;\n const gateways: string[] = [];\n let threshold: number | undefined;\n let json = true;\n let showHelp = false;\n let showVersion = false;\n let error: string | undefined;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!;\n if (arg === '--help' || arg === '-h') {\n showHelp = true;\n } else if (arg === '--version' || arg === '-V') {\n showVersion = true;\n } else if (arg === '--json') {\n json = true;\n } else if (arg === '--gateway') {\n const v = args[++i];\n if (v === undefined) {\n error = '--gateway requires a value';\n break;\n }\n gateways.push(v);\n } else if (arg === '--threshold') {\n const v = args[++i];\n const n = Number(v);\n if (v === undefined || !Number.isFinite(n) || !Number.isInteger(n) || n < 0) {\n error = '--threshold requires a non-negative integer';\n break;\n }\n threshold = n;\n } else if (arg.startsWith('-')) {\n error = `unknown flag: ${arg}`;\n break;\n } else if (txHash === undefined) {\n txHash = arg;\n } else {\n error = `unexpected positional argument: ${arg}`;\n break;\n }\n }\n\n return { txHash, gateways, threshold, json, showHelp, showVersion, error };\n}\n\nconst USAGE = `Usage: cardanowall-sdk-conformance <tx-hash> [--gateway <url>] [--threshold <n>] [--json]\n cardanowall-sdk-conformance --version\n cardanowall-sdk-conformance --help\n\nRuns the @cardanowall/sdk-ts standalone Label 309 verifier against a single\nCardano transaction. Exit codes:\n 0 = valid, 1 = failed, 2 = unverifiable, 3 = pending,\n 4 = CLI input error or verifier-host runtime failure.`;\n\nexport interface RunIO {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function run(args: ReadonlyArray<string>, io: RunIO): Promise<number> {\n const parsed = parseArgs(args);\n if (parsed.showHelp) {\n io.stdout(USAGE + '\\n');\n return 0;\n }\n if (parsed.showVersion) {\n io.stdout(`cardanowall-sdk-conformance ${VERSION}\\n`);\n return 0;\n }\n if (parsed.error !== undefined) {\n io.stderr(`cardanowall-sdk-conformance: ${parsed.error}\\n`);\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (parsed.txHash === undefined) {\n io.stderr('cardanowall-sdk-conformance: <tx-hash> is required\\n');\n io.stderr(USAGE + '\\n');\n return 4;\n }\n if (!/^[0-9a-f]{64}$/i.test(parsed.txHash)) {\n io.stderr(\n `cardanowall-sdk-conformance: invalid tx-hash (expected 64 hex chars): ${parsed.txHash}\\n`,\n );\n return 4;\n }\n\n const gateways = parsed.gateways.length > 0 ? parsed.gateways : [KOIOS_MAINNET_URL];\n\n try {\n const report = await verifyTx({\n txHash: parsed.txHash.toLowerCase(),\n cardanoGatewayChain: gateways,\n ...(parsed.threshold !== undefined ? { confirmationDepthThreshold: parsed.threshold } : {}),\n });\n io.stdout(JSON.stringify(verifyReportToDict(report), null, 2) + '\\n');\n return exitCodeForVerdict(report);\n } catch (err) {\n // A thrown error is a verifier-host runtime failure, not a verdict: it is\n // never record-attributable and never masquerades as one.\n io.stderr(\n `cardanowall-sdk-conformance: verifier error: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n return 4;\n }\n}\n\n// Only run as a script when invoked directly (not when imported by tests).\nif (/cli\\.(c?js|ts)$/.test(process.argv[1] ?? '')) {\n void run(process.argv.slice(2), {\n stdout: (text) => process.stdout.write(text),\n stderr: (text) => process.stderr.write(text),\n }).then((code) => process.exit(code));\n}\n"]}