Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

All notable changes to the `nirium` package are documented here.

## Unreleased

- New, preview: a second post-quantum signature from a different family of math. `slhKeygen()`, `attestSlh()` and `verifySlh()` sign and check `nirium-audit-v1:<content_sha256>` with SLH-DSA-SHA2-128s (NIST FIPS 205), whose security rests only on SHA-256, next to the lattice-based ML-DSA-65 `pq`. `slhKeyRegistrationOperation()` registers the 32-byte public key itself on the payer's own account (`manage_data` `nirium-slh-v1`), and `checkSlhKeyRegistration()` / `findFirstSlhKeyRegistration()` apply the same "only the first key counts" rule as `pq`. Checked off chain only: Protocol 30 (CAP-87) verifies ML-DSA, not SLH-DSA. Signing takes about a second; verifying a few milliseconds. The node and `nirium-cli` do not read `slh` yet.

## 0.23.0 - 2026-12-04

- New, preview: post-quantum signature for audit receipts. `pqKeygen()`, `attestPq()` and `verifyPq()` sign and check `nirium-audit-v1:<content_sha256>` with ML-DSA-65 (NIST FIPS 204), the same statement the ed25519 `agent` signature covers. `pqKeyRegistrationOperation()` and `findPqKeyRegistration()` register the key's sha-256 on the payer's own account (`manage_data` `nirium-pq-v1`) and read its ledger date back from Horizon. Adds `@noble/post-quantum`, loaded only when one of these functions runs. The Nirium node stores `pq` in the anchored receipt (testnet and mainnet since 4 Dec 2026), and `nirium-cli` 4.1.0 checks it.
Expand Down
1 change: 1 addition & 0 deletions packages/sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { captureRequirements, toSpendCapError, type X402OfferedRequirement } fro
import { attestPq, type PqAttestation, type PqKeyPair } from './pq';
export { receiptCid } from './receipt-cid';
export * from './pq';
export * from './pq-slh';

export interface AgentConfig {
apiKey: string;
Expand Down
50 changes: 50 additions & 0 deletions packages/sdk/src/pq-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Shared lookup for post-quantum key registrations on a Stellar account.
// Not exported from the package index: pq.ts (ML-DSA-65, `nirium-pq-v1`) and
// pq-slh.ts (SLH-DSA, `nirium-slh-v1`) wrap it with their own public API.

import { StrKey } from '@stellar/stellar-sdk';

export type HorizonOpts = { horizonUrl?: string; maxPages?: number; fetchImpl?: typeof fetch };

export interface DataEntryRegistration {
account: string;
/** The manage_data value, hex. */
valueHex: string;
txHash: string;
registeredAt: string;
}

/**
* Oldest successful manage_data that set `name` to a non-empty value, done by
* the account itself (failed transactions, other accounts' operations and
* deletions are skipped). Null if none. Throws if Horizon fails or the history
* is longer than `maxPages` pages of 200 operations, because then it cannot tell.
*/
export async function findFirstDataEntry(account: string, name: string, opts: HorizonOpts, label: string): Promise<DataEntryRegistration | null> {
if (!StrKey.isValidEd25519PublicKey(account)) throw new Error(`${label}: account must be a G... address`);
const base = (opts.horizonUrl ?? 'https://horizon.stellar.org').replace(/\/+$/, '');
const doFetch = opts.fetchImpl ?? fetch;
const maxPages = opts.maxPages ?? 25;
let url: string | undefined = `${base}/accounts/${account}/operations?order=asc&limit=200`;
for (let page = 0; url && page < maxPages; page++) {
const res = await doFetch(url);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Horizon ${res.status} for ${url}`);
const body = (await res.json()) as { _embedded?: { records?: any[] }; _links?: { next?: { href?: string } } };
const records = body._embedded?.records ?? [];
for (const op of records) {
if (op.type === 'manage_data' && op.name === name && typeof op.value === 'string' && op.value !== ''
&& op.transaction_successful !== false && op.source_account === account) {
return {
account,
valueHex: Buffer.from(op.value, 'base64').toString('hex'),
txHash: op.transaction_hash,
registeredAt: op.created_at,
};
}
}
if (records.length < 200) return null;
url = body._links?.next?.href;
}
throw new Error(`${label}: history of ${account} is longer than ${maxPages} pages; cannot tell which key was first`);
}
187 changes: 187 additions & 0 deletions packages/sdk/src/pq-slh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// ═══════════════════════════════════════════════════════════════
// Second post-quantum signature for audit receipts: SLH-DSA (NIST FIPS 205)
// ═══════════════════════════════════════════════════════════════
//
// The `pq` block (pq.ts) is ML-DSA-65, a lattice scheme. This module adds an
// optional `slh` block with SLH-DSA-SHA2-128s, a scheme whose security rests
// only on the hash function (SHA-256). The two rest on different math: if a
// weakness is ever found in lattices, the hash-based signature still holds,
// and the other way round.
//
// Same rules as `pq`:
// - It signs the SAME statement as `agent` and `pq`: `nirium-audit-v1:<content_sha256>`.
// - It only protects the receipt, not the payment.
// - The key has to be tied to the payer on the ledger BEFORE the receipt, and
// only the FIRST key the account registered counts (see pq.ts for why).
//
// One difference: an SLH-DSA public key is 32 bytes, so the registration
// (manage_data `nirium-slh-v1`) holds the public key itself, not a hash of it.
//
// Stellar contracts cannot check SLH-DSA today (Protocol 30 / CAP-87 adds
// ML-DSA only), so this signature is checked off chain: in this SDK, the CLI
// or a browser.
//
// The "s" (small signature) parameter set is slow to sign, about one second
// on a laptop. Verifying takes a few milliseconds.
//
// @noble/post-quantum is ESM-only and is loaded on first use, like pq.ts.

import { randomBytes } from 'node:crypto';
import { Operation, StrKey, type xdr } from '@stellar/stellar-sdk';
import { findFirstDataEntry, type HorizonOpts } from './pq-registry';

export const SLH_ALG = 'slh-dsa-sha2-128s' as const;
/** manage_data entry name that holds the raw SLH-DSA public key (32 bytes). */
export const SLH_REGISTRATION_KEY = 'nirium-slh-v1';

const PUBLIC_KEY_BYTES = 32;
const SIGNATURE_BYTES = 7856;
const SEED_BYTES = 48;

type SlhDsa = {
keygen(seed?: Uint8Array): { publicKey: Uint8Array; secretKey: Uint8Array };
sign(msg: Uint8Array, secretKey: Uint8Array): Uint8Array;
verify(sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array): boolean;
};

let slhDsa: SlhDsa | undefined;
function loadSlhDsa(): SlhDsa {
if (!slhDsa) {
// eslint-disable-next-line @typescript-eslint/no-require-imports
slhDsa = (require('@noble/post-quantum/slh-dsa.js') as { slh_dsa_sha2_128s: SlhDsa }).slh_dsa_sha2_128s;
}
return slhDsa;
}

/** The `slh` block that can travel next to `agent` (and `pq`) in a receipt. */
export interface SlhAttestation {
alg: typeof SLH_ALG;
/** SLH-DSA-SHA2-128s public key, base64 (32 bytes). */
key: string;
/** SLH-DSA signature over `nirium-audit-v1:<content_sha256>`, base64 (7,856 bytes). */
signature: string;
}

export interface SlhKeyPair {
/** 48-byte seed. Keep only this: it rebuilds the whole key pair. Never send it anywhere. */
seed: Uint8Array;
publicKey: Uint8Array;
secretKey: Uint8Array;
}

/** New SLH-DSA-SHA2-128s key pair. Pass a 48-byte seed to rebuild one you already have. */
export function slhKeygen(seed?: Uint8Array): SlhKeyPair {
const s = seed ?? new Uint8Array(randomBytes(SEED_BYTES));
if (s.length !== SEED_BYTES) throw new Error(`slhKeygen: seed must be ${SEED_BYTES} bytes`);
const { publicKey, secretKey } = loadSlhDsa().keygen(s);
return { seed: s, publicKey, secretKey };
}

/** Hex of the raw SLH-DSA public key. This is what gets registered on the account. */
export function slhKeyId(publicKey: Uint8Array | string): string {
const pk = toBytes(publicKey, 'publicKey');
if (pk.length !== PUBLIC_KEY_BYTES) throw new Error(`slhKeyId: public key must be ${PUBLIC_KEY_BYTES} bytes, got ${pk.length}`);
return pk.toString('hex');
}

function statementFor(contentSha256: string): string {
if (typeof contentSha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(contentSha256)) {
throw new Error('content_sha256 must be 64 hex chars');
}
return `nirium-audit-v1:${contentSha256.toLowerCase()}`;
}

/**
* Sign `nirium-audit-v1:<content_sha256>` with SLH-DSA-SHA2-128s: the same
* statement the ed25519 `agent` and the ML-DSA `pq` signatures cover.
*/
export function attestSlh(contentSha256: string, keys: Pick<SlhKeyPair, 'publicKey' | 'secretKey'>): SlhAttestation {
const msg = Buffer.from(statementFor(contentSha256), 'utf8');
const signature = loadSlhDsa().sign(msg, keys.secretKey);
return {
alg: SLH_ALG,
key: Buffer.from(keys.publicKey).toString('base64'),
signature: Buffer.from(signature).toString('base64'),
};
}

export type SlhCheck = { ok: true } | { ok: false; error: string };

/**
* Checks the SLH-DSA signature of an `slh` block against `content_sha256`.
* It does not say whose key it is: use checkSlhKeyRegistration() for that.
*/
export function verifySlh(slh: unknown, contentSha256: string): SlhCheck {
if (typeof slh !== 'object' || slh === null || Array.isArray(slh)) {
return { ok: false, error: '`slh` must be an object { alg, key, signature }' };
}
const { alg, key, signature } = slh as Record<string, unknown>;
if (alg !== SLH_ALG) return { ok: false, error: `\`slh.alg\` must be "${SLH_ALG}"` };
let pk: Buffer;
let sig: Buffer;
let statement: string;
try {
pk = toBytes(key, 'slh.key');
sig = toBytes(signature, 'slh.signature');
statement = statementFor(contentSha256);
} catch (e) {
return { ok: false, error: (e as Error).message };
}
if (pk.length !== PUBLIC_KEY_BYTES) return { ok: false, error: `\`slh.key\` must be ${PUBLIC_KEY_BYTES} bytes, got ${pk.length}` };
if (sig.length !== SIGNATURE_BYTES) return { ok: false, error: `\`slh.signature\` must be ${SIGNATURE_BYTES} bytes, got ${sig.length}` };
let good = false;
try {
good = loadSlhDsa().verify(sig, Buffer.from(statement, 'utf8'), pk);
} catch {
good = false;
}
return good ? { ok: true } : { ok: false, error: `\`slh.signature\` does not verify over "${statement}"` };
}

/**
* The manage_data operation that registers the SLH-DSA key on the payer's own
* account (the value is the 32-byte public key). Add it to a transaction the
* payer signs and pays for; it locks one base reserve until removed. Do it
* once: only the first key an account registers counts.
*/
export function slhKeyRegistrationOperation(publicKey: Uint8Array | string): xdr.Operation {
return Operation.manageData({ name: SLH_REGISTRATION_KEY, value: Buffer.from(slhKeyId(publicKey), 'hex') });
}

export interface SlhKeyRegistration {
account: string;
/** Hex of the registered SLH-DSA public key. */
keyId: string;
/** Transaction that set `nirium-slh-v1` to this key. */
txHash: string;
/** Ledger close time of that transaction (ISO 8601). Accept only receipts anchored after it. */
registeredAt: string;
}

export interface SlhKeyCheck {
/** Same meaning as PqKeyCheck.status, for `nirium-slh-v1`. */
status: 'first' | 'not-first' | 'not-registered';
first: SlhKeyRegistration | null;
}

/** The account's first SLH-DSA key registration, whatever key it holds. Null if none. */
export async function findFirstSlhKeyRegistration(account: string, opts: HorizonOpts = {}): Promise<SlhKeyRegistration | null> {
const r = await findFirstDataEntry(account, SLH_REGISTRATION_KEY, opts, 'findFirstSlhKeyRegistration');
return r ? { account: r.account, keyId: r.valueHex, txHash: r.txHash, registeredAt: r.registeredAt } : null;
}

/** Whether `publicKey` is the first SLH-DSA key `account` registered. */
export async function checkSlhKeyRegistration(account: string, publicKey: Uint8Array | string, opts: HorizonOpts = {}): Promise<SlhKeyCheck> {
if (!StrKey.isValidEd25519PublicKey(account)) throw new Error('checkSlhKeyRegistration: account must be a G... address');
const keyId = slhKeyId(publicKey);
const first = await findFirstSlhKeyRegistration(account, opts);
if (!first) return { status: 'not-registered', first: null };
return { status: first.keyId === keyId ? 'first' : 'not-first', first };
}

function toBytes(v: unknown, field: string): Buffer {
if (v instanceof Uint8Array) return Buffer.from(v);
if (typeof v !== 'string' || !v) throw new Error(`\`${field}\` must be base64 or bytes`);
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(v)) throw new Error(`\`${field}\` must be base64`);
return Buffer.from(v, 'base64');
}
31 changes: 3 additions & 28 deletions packages/sdk/src/pq.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

import { createHash, randomBytes } from 'node:crypto';
import { Operation, StrKey, type xdr } from '@stellar/stellar-sdk';
import { findFirstDataEntry, type HorizonOpts } from './pq-registry';

export const PQ_ALG = 'ml-dsa-65' as const;
/** manage_data entry name that holds sha-256 of the ML-DSA-65 public key. */
Expand Down Expand Up @@ -172,8 +173,6 @@ export interface PqKeyCheck {
first: PqKeyRegistration | null;
}

type HorizonOpts = { horizonUrl?: string; maxPages?: number; fetchImpl?: typeof fetch };

/**
* The account's first post-quantum key registration: oldest successful
* manage_data that set `nirium-pq-v1` to a value, done by the account itself
Expand All @@ -183,32 +182,8 @@ type HorizonOpts = { horizonUrl?: string; maxPages?: number; fetchImpl?: typeof
* cannot tell.
*/
export async function findFirstPqKeyRegistration(account: string, opts: HorizonOpts = {}): Promise<PqKeyRegistration | null> {
if (!StrKey.isValidEd25519PublicKey(account)) throw new Error('findFirstPqKeyRegistration: account must be a G... address');
const base = (opts.horizonUrl ?? 'https://horizon.stellar.org').replace(/\/+$/, '');
const doFetch = opts.fetchImpl ?? fetch;
const maxPages = opts.maxPages ?? 25;
let url: string | undefined = `${base}/accounts/${account}/operations?order=asc&limit=200`;
for (let page = 0; url && page < maxPages; page++) {
const res = await doFetch(url);
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Horizon ${res.status} for ${url}`);
const body = (await res.json()) as { _embedded?: { records?: any[] }; _links?: { next?: { href?: string } } };
const records = body._embedded?.records ?? [];
for (const op of records) {
if (op.type === 'manage_data' && op.name === PQ_REGISTRATION_KEY && typeof op.value === 'string' && op.value !== ''
&& op.transaction_successful !== false && op.source_account === account) {
return {
account,
keyId: Buffer.from(op.value, 'base64').toString('hex'),
txHash: op.transaction_hash,
registeredAt: op.created_at,
};
}
}
if (records.length < 200) return null;
url = body._links?.next?.href;
}
throw new Error(`findFirstPqKeyRegistration: history of ${account} is longer than ${maxPages} pages; cannot tell which key was first`);
const r = await findFirstDataEntry(account, PQ_REGISTRATION_KEY, opts, 'findFirstPqKeyRegistration');
return r ? { account: r.account, keyId: r.valueHex, txHash: r.txHash, registeredAt: r.registeredAt } : null;
}

/** Whether `publicKey` is the first post-quantum key `account` registered. */
Expand Down
Loading