diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index bd6c8db..e5a85c8 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -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:` 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:` 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. diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 7d813e0..5866509 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -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; diff --git a/packages/sdk/src/pq-registry.ts b/packages/sdk/src/pq-registry.ts new file mode 100644 index 0000000..c465561 --- /dev/null +++ b/packages/sdk/src/pq-registry.ts @@ -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 { + 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`); +} diff --git a/packages/sdk/src/pq-slh.ts b/packages/sdk/src/pq-slh.ts new file mode 100644 index 0000000..c9d26a7 --- /dev/null +++ b/packages/sdk/src/pq-slh.ts @@ -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:`. +// - 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:`, 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:` 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): 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; + 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 { + 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 { + 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'); +} diff --git a/packages/sdk/src/pq.ts b/packages/sdk/src/pq.ts index 4cade5f..7671f94 100644 --- a/packages/sdk/src/pq.ts +++ b/packages/sdk/src/pq.ts @@ -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. */ @@ -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 @@ -183,32 +182,8 @@ type HorizonOpts = { horizonUrl?: string; maxPages?: number; fetchImpl?: typeof * cannot tell. */ export async function findFirstPqKeyRegistration(account: string, opts: HorizonOpts = {}): Promise { - 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. */ diff --git a/packages/sdk/test/pq-slh.test.ts b/packages/sdk/test/pq-slh.test.ts new file mode 100644 index 0000000..aa1abce --- /dev/null +++ b/packages/sdk/test/pq-slh.test.ts @@ -0,0 +1,148 @@ +/** + * Second post-quantum receipt signature (SLH-DSA-SHA2-128s, FIPS 205), offline. + * Runs the built package (run `npm run build` first), like pq-sign.test.ts. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); +const sdk = require('../dist/index.js'); +const { slhKeygen, attestSlh, verifySlh, slhKeyId, slhKeyRegistrationOperation, checkSlhKeyRegistration, + findFirstSlhKeyRegistration, SLH_REGISTRATION_KEY, pqKeygen, attestPq, verifyPq, auditContentSha256, + findFirstPqKeyRegistration } = sdk; +const { Keypair, Operation } = require('@stellar/stellar-sdk'); + +const RECORD = { order: 'A-12', amount: '0.05', asset: 'USDC', approvedBy: 'policy-v1' }; +const SHA = auditContentSha256({ record: RECORD }); +const SEED = new Uint8Array(48).fill(7); +// Signing takes about a second, so sign once and reuse. +const KEYS = slhKeygen(SEED); +const SLH = attestSlh(SHA, KEYS); + +test('same seed gives the same key pair; sizes are FIPS 205 SLH-DSA-SHA2-128s', () => { + const b = slhKeygen(SEED); + assert.deepEqual(Buffer.from(KEYS.publicKey), Buffer.from(b.publicKey)); + assert.equal(KEYS.publicKey.length, 32); + assert.equal(KEYS.secretKey.length, 64); + assert.throws(() => slhKeygen(new Uint8Array(32)), /48 bytes/); +}); + +test('attestSlh signs the same statement as agent and pq, and both verify on one receipt', () => { + assert.equal(SLH.alg, 'slh-dsa-sha2-128s'); + assert.equal(Buffer.from(SLH.signature, 'base64').length, 7856); + assert.deepEqual(verifySlh(SLH, SHA), { ok: true }); + assert.deepEqual(verifySlh(SLH, SHA.toUpperCase()), { ok: true }); + const pq = attestPq(SHA, pqKeygen(new Uint8Array(32).fill(7))); + assert.deepEqual(verifyPq(pq, SHA), { ok: true }); +}); + +test('a changed record fails', () => { + const other = auditContentSha256({ record: { ...RECORD, amount: '5.00' } }); + const r = verifySlh(SLH, other); + assert.equal(r.ok, false); + assert.match(r.error, /does not verify/); +}); + +test('one flipped bit in the signature fails', () => { + const sig = Buffer.from(SLH.signature, 'base64'); + for (const i of [0, 100, 7855]) { + const bad = Buffer.from(sig); + bad[i] ^= 1; + assert.equal(verifySlh({ ...SLH, signature: bad.toString('base64') }, SHA).ok, false, `bit at byte ${i}`); + } +}); + +test('another key fails', () => { + const otherKey = Buffer.from(slhKeygen(new Uint8Array(48).fill(8)).publicKey).toString('base64'); + assert.equal(verifySlh({ ...SLH, key: otherKey }, SHA).ok, false); +}); + +test('an ML-DSA block in the slh field fails, and an slh block in the pq field fails', () => { + const pq = attestPq(SHA, pqKeygen(new Uint8Array(32).fill(7))); + assert.match(verifySlh(pq, SHA).error, /slh.alg/); + assert.equal(verifyPq(SLH, SHA).ok, false); +}); + +test('malformed blocks fail with a reason, never throw', () => { + const cases: Array<[unknown, RegExp]> = [ + [null, /must be an object/], + [[], /must be an object/], + [{ ...SLH, alg: 'ml-dsa-65' }, /slh.alg/], + [{ ...SLH, key: 'not base64!' }, /slh.key/], + [{ ...SLH, key: '' }, /slh.key/], + [{ ...SLH, signature: undefined }, /slh.signature/], + [{ ...SLH, signature: Buffer.from(SLH.signature, 'base64').subarray(0, 7000).toString('base64') }, /7856 bytes/], + [{ ...SLH, key: Buffer.alloc(48).toString('base64') }, /32 bytes/], + ]; + for (const [input, re] of cases) { + const r = verifySlh(input, SHA); + assert.equal(r.ok, false); + assert.match(r.error, re); + } + assert.match(verifySlh(SLH, 'abc').error, /64 hex/); +}); + +test('registration operation stores the raw 32-byte public key under nirium-slh-v1', () => { + const id = slhKeyId(KEYS.publicKey); + assert.equal(id, Buffer.from(KEYS.publicKey).toString('hex')); + assert.equal(slhKeyId(Buffer.from(KEYS.publicKey).toString('base64')), id); + assert.throws(() => slhKeyId(new Uint8Array(31)), /32 bytes/); + const parsed = Operation.fromXDRObject(slhKeyRegistrationOperation(KEYS.publicKey)); + assert.equal(parsed.type, 'manageData'); + assert.equal(parsed.name, SLH_REGISTRATION_KEY); + assert.equal(Buffer.from(parsed.value).toString('hex'), id); +}); + +function horizonStub(pages: any[][]) { + const urls: string[] = []; + const fetchImpl = (async (url: string) => { + urls.push(url); + const i = urls.length - 1; + return new Response(JSON.stringify({ _embedded: { records: pages[i] ?? [] }, _links: { next: { href: `https://h.invalid/next/${i + 1}` } } }), + { status: 200, headers: { 'content-type': 'application/json' } }); + }) as typeof fetch; + return { fetchImpl, urls }; +} + +const OTHER_VALUE = Buffer.alloc(32, 9).toString('base64'); +const op = (account: string, o: object) => ({ type: 'manage_data', name: SLH_REGISTRATION_KEY, + value: Buffer.from(KEYS.publicKey).toString('base64'), transaction_successful: true, source_account: account, ...o }); + +test('only the first own, successful registration counts; a later key does not', async () => { + const account = Keypair.random().publicKey(); + const first = await checkSlhKeyRegistration(account, KEYS.publicKey, { fetchImpl: horizonStub([[ + op(account, { value: OTHER_VALUE, transaction_successful: false, transaction_hash: 'failed' }), + op(account, { value: OTHER_VALUE, source_account: Keypair.random().publicKey(), transaction_hash: 'foreign' }), + op(account, { value: '', transaction_hash: 'deletion' }), + op(account, { transaction_hash: 'good', created_at: '2026-12-05T18:00:00Z' }), + op(account, { value: OTHER_VALUE, transaction_hash: 'later', created_at: '2026-12-06T18:00:00Z' }), + ]]).fetchImpl }); + assert.equal(first.status, 'first'); + assert.deepEqual(first.first, { account, keyId: slhKeyId(KEYS.publicKey), txHash: 'good', registeredAt: '2026-12-05T18:00:00Z' }); + // Another key was registered first: this one does not count, even if it was registered before the receipt. + const notFirst = await checkSlhKeyRegistration(account, KEYS.publicKey, { fetchImpl: horizonStub([[ + op(account, { value: OTHER_VALUE, transaction_hash: 'other-first', created_at: '2026-12-01T00:00:00Z' }), + op(account, { transaction_hash: 'this-second', created_at: '2026-12-05T18:00:00Z' }), + ]]).fetchImpl }); + assert.equal(notFirst.status, 'not-first'); + assert.equal(notFirst.first?.txHash, 'other-first'); +}); + +test('the slh and pq registrations are separate entries', async () => { + const account = Keypair.random().publicKey(); + const { fetchImpl } = horizonStub([[op(account, { transaction_hash: 'slh-only', created_at: 't' })], [op(account, { transaction_hash: 'slh-only', created_at: 't' })]]); + assert.equal((await findFirstSlhKeyRegistration(account, { fetchImpl }))?.txHash, 'slh-only'); + assert.equal(await findFirstPqKeyRegistration(account, { fetchImpl }), null); +}); + +test('not-registered, unknown account, bad address and a too-long history', async () => { + const account = Keypair.random().publicKey(); + assert.deepEqual(await checkSlhKeyRegistration(account, KEYS.publicKey, { fetchImpl: horizonStub([[{ type: 'payment' }]]).fetchImpl }), + { status: 'not-registered', first: null }); + const notFound = (async () => new Response('{}', { status: 404 })) as typeof fetch; + assert.equal(await findFirstSlhKeyRegistration(account, { fetchImpl: notFound }), null); + await assert.rejects(() => checkSlhKeyRegistration('GBAD', KEYS.publicKey, {}), /G\.\.\. address/); + const filler = Array.from({ length: 200 }, () => ({ type: 'payment' })); + await assert.rejects(() => findFirstSlhKeyRegistration(account, { fetchImpl: horizonStub([filler, filler]).fetchImpl, maxPages: 2 }), /longer than 2 pages/); +});