From f971f7d5399e9427d5d632e202dc502d7adbb5ec Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 13:39:20 +0200 Subject: [PATCH 01/25] Add stamp-revision: document lineage tokens New `stamp-revision` command that creates a document lineage token for an initial revision, or appends the next revision to an existing one, as designed in issue #13. - Genesis: a mint of the lineage token type (SHA-256 of "unicity-document-lineage") with a random salt, auxData CBOR[0, H(doc_0)], and a mint reason (CBOR tag 39200) carrying the issuer's signature over the token id, token type and auxData. The recipient is P_sig on the next producer's key. - Revisions: transfers with data CBOR[i, H(doc_i)], signed under the P_sig named by the previous revision. The state mask is derived from the signer's key and the source state, so a crashed run can be replayed and recovers the same transaction. - Verification: SDK token verification with a fail-closed lineage issuance policy, plus chain rules the SDK does not check (indices increase by one, reference times never decrease). The producer key and token validity are checked before contacting the gateway. - Writing: a new lineage is created exclusively; an existing one is replaced via a temporary file and rename. On write failure the full token is printed as hex, which --token-file accepts. Co-Authored-By: Claude Opus 5.5 --- README.md | 21 ++ src/cli.ts | 22 +- src/commands/stampRevision.ts | 151 +++++++++++++ src/commands/tokenInput.ts | 11 +- src/config.ts | 153 +++++++++++++ src/errors.ts | 4 + src/lib/TimestampClient.ts | 51 ++++- src/lib/lineage/LineageClient.ts | 210 ++++++++++++++++++ src/lib/lineage/LineagePayload.ts | 266 +++++++++++++++++++++++ src/lib/lineage/LineageVerification.ts | 285 +++++++++++++++++++++++++ src/output.ts | 90 ++++++++ tests/unit/StampRevisionTest.ts | 241 +++++++++++++++++++++ tests/unit/lib/LineageTest.ts | 260 ++++++++++++++++++++++ 13 files changed, 1753 insertions(+), 12 deletions(-) create mode 100644 src/commands/stampRevision.ts create mode 100644 src/lib/lineage/LineageClient.ts create mode 100644 src/lib/lineage/LineagePayload.ts create mode 100644 src/lib/lineage/LineageVerification.ts create mode 100644 tests/unit/StampRevisionTest.ts create mode 100644 tests/unit/lib/LineageTest.ts diff --git a/README.md b/README.md index 3125b50..5af087c 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,27 @@ Or put `UNICITY_PRIVATE_KEY=<64 hex>` in `.env` and every stamp is signed. Two f The signer's compressed public key is printed on every `stamp` and `verify`, as `Signer`, or `none` for anonymous stamps. Publish your public key wherever people need to recognise it; the key alone does not say who you are. +### Stamp revisions (document lineage) + +`stamp-revision` links successive revisions of a document in one *lineage token* +(design: [#13](https://github.com/unicitynetwork/proof-cli/issues/13#issuecomment-6440959902)). +Each call certifies one revision and names who may produce the next: + +```bash +# Revision 0: creates doc.lineage, signed by alice, and names bob as the next producer. +unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file alice.key --recipient-key +# Revision 1: only bob's key can append; bob names carol (key read from a file holding 66 hex characters). +unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file bob.key --recipient-key-file carol.pub +``` + +- Exactly one of `` and `--file`, and exactly one of `--recipient-key` and `--recipient-key-file`, is required. `--token-file` and `--key-file` are always required; `UNICITY_PRIVATE_KEY` is not consulted. +- If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type and revision, which is what makes the origin "accepted"; the salt is random, so the token id cannot be predicted before the genesis is certified. +- If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. +- The state mask of each step is derived from the producer's key and the spent state, so if the command is interrupted after certification, running the same command again with the same file, key, digest and recipient recovers the same revision. +- Network options behave as for `stamp`. `verify` and `inspect` do not yet understand lineage tokens. + +Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, auxiliary data])`. Verification additionally requires the indices to increase by one and the reference times not to decrease along the chain. + ### Verify ```bash diff --git a/src/cli.ts b/src/cli.ts index 4937011..57da145 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -5,8 +5,9 @@ import { ICommandContext } from './commands/context.js'; import { runInspect } from './commands/inspect.js'; import { IKeygenFlags, runKeygen } from './commands/keygen.js'; import { runStamp } from './commands/stamp.js'; +import { runStampRevision } from './commands/stampRevision.js'; import { IVerifyFlags, runVerify } from './commands/verify.js'; -import { IStampFlags, loadEnvironment } from './config.js'; +import { IStampFlags, IStampRevisionFlags, loadEnvironment } from './config.js'; import { describeError, EXIT_USAGE, toExitCode } from './errors.js'; import { warningLine } from './output.js'; import { VERSION } from './version.js'; @@ -77,6 +78,25 @@ program process.exitCode = await runStamp(digest, flags, context()); }); +program + .command('stamp-revision') + .description('certify a document revision, creating a lineage token or appending to an existing one') + .argument('[sha256-hex]', 'digest of the revision; alternatively use --file') + .option('--file ', 'hash this file locally instead of passing a digest') + .requiredOption('--token-file ', 'lineage token; created for an initial revision, otherwise appended to') + .requiredOption('--key-file ', 'secp256k1 private key (64 hex) that signs this revision') + .option('--recipient-key ', "compressed secp256k1 public key (66 hex) of the next revision's producer") + .option('--recipient-key-file ', "file holding the next producer's public key; alternative to --recipient-key") + .option('--network ', 'mainnet or testnet2; or UNICITY_NETWORK (default mainnet)') + .option('--gateway ', 'override the gateway URL; or UNICITY_GATEWAY_URL') + .option('--api-key ', 'gateway API key; or UNICITY_API_KEY') + .option('--trust-base ', 'override the bundled trust base; or UNICITY_TRUST_BASE') + .option('--timeout ', 'wait for the inclusion proof; or UNICITY_TIMEOUT (default 60)') + .option('--allow-insecure', 'permit the API key over plain HTTP (local development only)') + .action(async (digest: string | undefined, flags: IStampRevisionFlags) => { + process.exitCode = await runStampRevision(digest, flags, context()); + }); + program .command('verify') .description('verify a timestamp token offline and print what it proves') diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts new file mode 100644 index 0000000..00f58be --- /dev/null +++ b/src/commands/stampRevision.ts @@ -0,0 +1,151 @@ +import { randomBytes } from 'node:crypto'; +import { rename, rm, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { AggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/AggregatorClient.js'; +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; +import { CertifiedTransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedTransferTransaction.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; + +import { ICommandContext } from './context.js'; +import { decodeToken, tokenBytesFromInput } from './tokenInput.js'; +import { IStampRevisionConfig, IStampRevisionFlags, resolveStampRevisionConfig } from '../config.js'; +import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; +import { appendRevision, createLineage } from '../lib/lineage/LineageClient.js'; +import { revisionJson, revisionRecoveryLines, revisionText, toJsonLine, warningLine } from '../output.js'; + +/** + * Persist a lineage token whose newest revision has already been certified. + * + * A new lineage is written with an exclusive create, so a file that appeared + * since the checks is never clobbered. An existing lineage is replaced through a + * temporary file and `rename`, so the previous version stays intact until the new + * one is complete: truncating it in place and then failing would lose the whole + * history, not just the new revision. Whatever goes wrong, the full token is + * printed as hex before the error propagates. + * + * @param {string} tokenFile Absolute token file path. + * @param {Uint8Array} bytes Encoded token. + * @param {boolean} created Whether this is a new lineage. + * @param {ICommandContext} context Streams. + */ +export async function writeRevisionToken( + tokenFile: string, + bytes: Uint8Array, + created: boolean, + context: ICommandContext, +): Promise { + const temporary = path.join( + path.dirname(tokenFile), + `.${path.basename(tokenFile)}.${randomBytes(8).toString('hex')}`, + ); + try { + if (created) { + await writeFile(tokenFile, bytes, { flag: 'wx' }); + } else { + await writeFile(temporary, bytes, { flag: 'wx' }); + await rename(temporary, tokenFile); + } + } catch (error) { + // First, before anything awaited, so nothing can get between the error and the recovered bytes. + context.stderr.write(revisionRecoveryLines(bytes)); + if (!created) { + await rm(temporary, { force: true }).catch(() => undefined); + } + throw error; + } +} + +function latestCertified(token: Token): CertifiedMintTransaction | CertifiedTransferTransaction { + return token.transactions.at(-1) ?? token.genesis; +} + +/** + * The part of `stamp-revision` after configuration: certify, write, report. Takes + * the client as a parameter so it can run against an in-memory aggregator. + * + * @param {IStampRevisionConfig} config Resolved configuration. + * @param {StateTransitionClient} client Aggregator client for `config.network`. + * @param {ICommandContext} context Streams and interrupt signal. + * @returns {Promise} Exit code. + */ +export async function stampRevisionWith( + config: IStampRevisionConfig, + client: StateTransitionClient, + context: ICommandContext, +): Promise { + const trustBase = config.network.trustBase; + const options = { + onWarning: (message: string): void => { + context.stderr.write(warningLine(message)); + }, + signal: context.interrupt, + timeoutMs: config.timeoutMs, + }; + + let token: Token; + const created = config.tokenBytes === null; + if (config.tokenBytes === null) { + token = await createLineage(client, trustBase, config.digest, config.privateKey, config.recipientKey, options); + } else { + const decoded = await decodeToken(tokenBytesFromInput(config.tokenBytes)); + if (decoded.token === null) { + throw new CliError(`${config.tokenFile} is ${decoded.error}.`, EXIT_VERIFICATION_FAILED); + } + token = await appendRevision( + client, + trustBase, + decoded.token, + config.digest, + config.privateKey, + config.recipientKey, + options, + ); + } + + const bytes = token.toCBOR(); + await writeRevisionToken(config.tokenFile, bytes, created, context); + + const latest = latestCertified(token); + const certificate = latest.inclusionProof.unicityCertificate; + const summary = { + created, + digest: config.digest, + epoch: certificate.unicitySeal.epoch, + gatewayUrl: config.network.gatewayUrl, + networkId: token.networkId.id, + nextProducer: config.recipientKey, + referenceTime: latest.referenceTime, + revision: BigInt(token.transactions.length), + roundNumber: certificate.inputRecord.roundNumber, + roundTimestamp: certificate.inputRecord.timestamp, + signer: new SigningService(config.privateKey).publicKey, + tokenFile: config.tokenFile, + tokenId: token.id.bytes, + }; + context.stdout.write(context.json ? toJsonLine(revisionJson(summary)) : `${revisionText(summary)}\n`); + return EXIT_OK; +} + +/** + * `stamp-revision`: create a document lineage token for an initial revision, or + * append the next revision to an existing one. + * + * @param {string} [digestArgument] Positional digest. + * @param {IStampRevisionFlags} flags Command flags. + * @param {ICommandContext} context Streams and interrupt signal. + * @returns {Promise} Exit code. + */ +export async function runStampRevision( + digestArgument: string | undefined, + flags: IStampRevisionFlags, + context: ICommandContext, +): Promise { + const config = await resolveStampRevisionConfig(digestArgument, flags); + const client = new StateTransitionClient( + new AggregatorClient(config.network.gatewayUrl, config.apiKey, config.allowInsecure), + ); + return stampRevisionWith(config, client, context); +} diff --git a/src/commands/tokenInput.ts b/src/commands/tokenInput.ts index c70a9c1..0808951 100644 --- a/src/commands/tokenInput.ts +++ b/src/commands/tokenInput.ts @@ -19,7 +19,16 @@ const HEX_TEXT = /^[0-9a-fA-F\s]+$/; * @returns {Promise} Token bytes. */ export async function readTokenInput(file: string, stdin: NodeJS.ReadableStream): Promise { - const bytes = new Uint8Array(file === '-' ? await buffer(stdin) : await readFile(file)); + return tokenBytesFromInput(new Uint8Array(file === '-' ? await buffer(stdin) : await readFile(file))); +} + +/** + * Turn the contents of a token file into token bytes: hex text is decoded, anything else is taken as raw CBOR. + * + * @param {Uint8Array} bytes File contents. + * @returns {Uint8Array} Token bytes. + */ +export function tokenBytesFromInput(bytes: Uint8Array): Uint8Array { const text = new TextDecoder('latin1').decode(bytes); if (text.trim() !== '' && HEX_TEXT.test(text)) { const compact = text.replace(/\s+/g, ''); diff --git a/src/config.ts b/src/config.ts index 28e688b..5272f7d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -440,3 +440,156 @@ export async function resolveStampConfig( return { allowInsecure, apiKey, digest, force, network, out, signer, timeoutMs }; } + +export interface IStampRevisionFlags extends INetworkFlags { + readonly allowInsecure?: boolean; + readonly apiKey?: string; + readonly file?: string; + readonly keyFile?: string; + readonly recipientKey?: string; + readonly recipientKeyFile?: string; + readonly timeout?: string; + readonly tokenFile?: string; +} + +export interface IStampRevisionConfig { + readonly allowInsecure: boolean; + readonly apiKey: string; + readonly digest: Uint8Array; + readonly network: ITimestampNetwork; + /** Signs the new revision: the genesis reason for a new lineage, the transfer otherwise. */ + readonly privateKey: Uint8Array; + /** Compressed public key of whoever produces the following revision. */ + readonly recipientKey: Uint8Array; + readonly timeoutMs: number; + /** Bytes of the existing token file, or null when a new lineage is to be created. */ + readonly tokenBytes: Uint8Array | null; + /** Absolute path of the token file. */ + readonly tokenFile: string; +} + +/** Compressed secp256k1 public key as hex, any case, optional 0x prefix. */ +const COMPRESSED_PUBLIC_KEY_HEX = /^(0x)?(02|03)[0-9a-fA-F]{64}$/; + +/** + * @param {string} input 66 hex characters of a compressed secp256k1 public key; surrounding whitespace allowed. + * @param {string} source How the key was given, for the error message. + * @returns {Uint8Array} 33-byte public key. + * @throws {CliError} If the input is not a valid compressed public key. + */ +export function parsePublicKey(input: string, source = 'Recipient key'): Uint8Array { + const trimmed = input.trim(); + const message = `${source} must be a compressed secp256k1 public key of 66 hex characters.`; + if (!COMPRESSED_PUBLIC_KEY_HEX.test(trimmed)) { + throw usageError(message); + } + const key = HexConverter.decode(trimmed.replace(/^0x/, '')); + if (!SigningService.isPublicKeyValid(key)) { + throw usageError(`${source} is not a point on the secp256k1 curve.`); + } + return key; +} + +async function resolveRecipientKey(flags: IStampRevisionFlags): Promise { + if (flags.recipientKey !== undefined && flags.recipientKeyFile !== undefined) { + throw usageError('Pass either --recipient-key or --recipient-key-file, not both.'); + } + if (flags.recipientKey !== undefined) { + return parsePublicKey(flags.recipientKey, '--recipient-key'); + } + if (flags.recipientKeyFile === undefined) { + throw usageError('Name the producer of the next revision: pass --recipient-key or --recipient-key-file.'); + } + let contents: string; + try { + contents = await readFile(flags.recipientKeyFile, 'utf8'); + } catch (error) { + throw usageError(`Cannot read recipient key file ${flags.recipientKeyFile}.`, { cause: error }); + } + return parsePublicKey(contents, `Recipient key file ${flags.recipientKeyFile}`); +} + +/** + * The token file is replaced through a temporary file in the same directory, and + * a new one is created there, so both cases need a writable directory; an existing + * file must also be readable. Checked before any network contact, for the same + * reason as {@link assertWritable}. + * + * @param {string} tokenFile Absolute path. + * @returns {Promise} Whether the file exists. + */ +async function assertTokenFileUsable(tokenFile: string): Promise { + const exists = await access(tokenFile).then( + () => true, + () => false, + ); + const directory = path.dirname(tokenFile); + try { + await access(directory, constants.W_OK | constants.X_OK); + } catch (error) { + throw usageError(`Cannot write to the token file directory ${directory}.`, { cause: error }); + } + return exists; +} + +/** + * Everything `stamp-revision` needs, validated before any network contact. + * + * @param {string} [digestArgument] Positional digest. + * @param {IStampRevisionFlags} flags Command-line flags. + * @param {NodeJS.ProcessEnv} env Environment, after `.env` was loaded. + * @returns {Promise} Resolved configuration. + * @throws {CliError} On any missing or invalid setting. + */ +export async function resolveStampRevisionConfig( + digestArgument: string | undefined, + flags: IStampRevisionFlags, + env: NodeJS.ProcessEnv = process.env, +): Promise { + if (digestArgument === undefined && flags.file === undefined) { + throw usageError('Pass a SHA-256 digest or --file .'); + } + assertOneDigestSource(digestArgument, flags.file); + if (flags.tokenFile === undefined) { + throw usageError('Pass --token-file : the lineage token to create or append to.'); + } + if (flags.keyFile === undefined) { + throw usageError('Pass --key-file : the private key that signs the new revision.'); + } + + const apiKey = (flags.apiKey ?? env.UNICITY_API_KEY)?.trim(); + if (!apiKey) { + throw usageError('No API key. Set UNICITY_API_KEY in the environment or .env, or pass --api-key.'); + } + + const selection = resolveNetworkSelection(flags, env); + const network = resolveNetwork({ + gatewayUrl: selection.gatewayUrl, + network: selection.network, + trustBase: selection.trustBasePath === undefined ? undefined : await loadTrustBase(selection.trustBasePath), + }); + const allowInsecure = flags.allowInsecure ?? false; + if (new URL(network.gatewayUrl).protocol !== 'https:' && !allowInsecure) { + throw usageError( + 'The API key must not be sent over plain HTTP. Use an https gateway, or pass --allow-insecure for a local aggregator.', + ); + } + + const privateKey = parsePrivateKey(await readKeyFile(flags.keyFile)); + const recipientKey = await resolveRecipientKey(flags); + const timeoutMs = parseTimeoutSeconds(flags.timeout ?? env.UNICITY_TIMEOUT); + + const tokenFile = path.resolve(flags.tokenFile); + const exists = await assertTokenFileUsable(tokenFile); + let tokenBytes: Uint8Array | null = null; + if (exists) { + try { + tokenBytes = new Uint8Array(await readFile(tokenFile)); + } catch (error) { + throw usageError(`Cannot read the token file ${tokenFile}.`, { cause: error }); + } + } + + const digest = (await resolveDigest(digestArgument, flags.file)) as Uint8Array; + return { allowInsecure, apiKey, digest, network, privateKey, recipientKey, timeoutMs, tokenBytes, tokenFile }; +} diff --git a/src/errors.ts b/src/errors.ts index f31e8ec..1023fa6 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -5,6 +5,7 @@ import { SleepError } from '@unicitylabs/state-transition-sdk/lib/util/Inclusion import { VerificationError } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationError.js'; import { errorMessage, StampError } from './lib/errors.js'; +import { LineageError } from './lib/lineage/LineageClient.js'; export const EXIT_OK = 0; /** Verification failed, hash mismatch, or the input is not a token. */ @@ -69,6 +70,9 @@ export function toExitCode(error: unknown, interrupted = false): number { if (error instanceof VerificationError) { return EXIT_VERIFICATION_FAILED; } + if (error instanceof LineageError) { + return error.code === 'INVALID_TOKEN' ? EXIT_VERIFICATION_FAILED : EXIT_USAGE; + } return EXIT_USAGE; } diff --git a/src/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index 1201a35..9083f19 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -2,9 +2,11 @@ import { AggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/Aggr import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; import { CertificationStatus } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; +import { InclusionProof } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProof.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; +import type { ITransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/ITransaction.js'; import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { VerificationContext } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/VerificationContext.js'; @@ -41,25 +43,29 @@ const KNOWN_STATUSES: readonly string[] = Object.values(CertificationStatus); const SUCCESS_STATUS: string = CertificationStatus.SUCCESS; /** - * Submit a mint transaction and wait for its inclusion proof. + * Submit a certification request and wait for its inclusion proof. + * + * An unknown status is a warning rather than a failure: the aggregator answers a + * repeated request with `STATE_ID_EXISTS`, which the SDK does not list, and the + * proof that then arrives is checked against this transaction's hash anyway. * * @param {StateTransitionClient} client Aggregator client. * @param {VerificationContext} context Verification context for the network behind the client. - * @param {MintTransaction} transaction Transaction to certify. + * @param {CertificationData} certificationData Request to submit. + * @param {ITransaction} transaction Transaction the request certifies. * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. - * @returns {Promise} The transaction with its verified inclusion proof. + * @returns {Promise} Verified inclusion proof. * @throws {StampError} If the aggregator returns a known failure status. * @throws {SleepError} If the proof does not arrive before the timeout or abort. */ -export async function certifyMintTransaction( +export async function certifyTransaction( client: StateTransitionClient, context: VerificationContext, - transaction: MintTransaction, + certificationData: CertificationData, + transaction: ITransaction, options: ICertifyOptions = {}, -): Promise { - const response = await client.submitCertificationRequest(await CertificationData.fromMintTransaction(transaction), { - signal: options.signal, - }); +): Promise { + const response = await client.submitCertificationRequest(certificationData, { signal: options.signal }); if (response.status !== SUCCESS_STATUS) { if (KNOWN_STATUSES.includes(response.status)) { throw new StampError(response.status); @@ -73,7 +79,7 @@ export async function certifyMintTransaction( if (options.signal) { signals.push(options.signal); } - const proof = await waitInclusionProof( + return waitInclusionProof( client, context.trustBase, context.predicateVerifier, @@ -82,7 +88,32 @@ export async function certifyMintTransaction( AbortSignal.any(signals), options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, ); +} +/** + * Submit a mint transaction and wait for its inclusion proof. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {VerificationContext} context Verification context for the network behind the client. + * @param {MintTransaction} transaction Transaction to certify. + * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. + * @returns {Promise} The transaction with its verified inclusion proof. + * @throws {StampError} If the aggregator returns a known failure status. + * @throws {SleepError} If the proof does not arrive before the timeout or abort. + */ +export async function certifyMintTransaction( + client: StateTransitionClient, + context: VerificationContext, + transaction: MintTransaction, + options: ICertifyOptions = {}, +): Promise { + const proof = await certifyTransaction( + client, + context, + await CertificationData.fromMintTransaction(transaction), + transaction, + options, + ); return transaction.toCertifiedTransaction( context.trustBase, context.predicateVerifier, diff --git a/src/lib/lineage/LineageClient.ts b/src/lib/lineage/LineageClient.ts new file mode 100644 index 0000000..1465c5b --- /dev/null +++ b/src/lib/lineage/LineageClient.ts @@ -0,0 +1,210 @@ +import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; +import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; +import { DataHasher } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasher.js'; +import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js'; +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { SignaturePredicateUnlockScript } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicateUnlockScript.js'; +import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; +import { StateMask } from '@unicitylabs/state-transition-sdk/lib/transaction/StateMask.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; +import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; +import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; +import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; + +import { LINEAGE_TAG, LINEAGE_TOKEN_TYPE, LineageGenesisReason, LineageRevision } from './LineagePayload.js'; +import { createLineageVerificationContext, verifyLineage } from './LineageVerification.js'; +import { ICertifyOptions, certifyMintTransaction, certifyTransaction } from '../TimestampClient.js'; + +/** Thrown when a revision cannot be appended to the given token with the given key. */ +export class LineageError extends Error { + public constructor( + message: string, + /** `INVALID_TOKEN`: the token does not verify as a lineage; `WRONG_KEY`: the key cannot append to it. */ + public readonly code: 'INVALID_TOKEN' | 'WRONG_KEY', + options?: ErrorOptions, + ) { + super(message, options); + this.name = 'LineageError'; + } +} + +/** + * Public key of the `P_sig` predicate the token's latest state is locked to. + * + * @param {Token} token Lineage token. + * @returns {Uint8Array|null} The key, or null when the state is locked to another kind of predicate. + */ +export function currentProducerKey(token: Token): Uint8Array | null { + try { + return SignaturePredicate.fromPredicate(token.latestTransaction.recipient).publicKey; + } catch { + return null; + } +} + +/** + * State mask of a version step, `x = PRF(k, h)`: derived from the producer's + * private key and the state being spent rather than drawn at random. Re-running + * an interrupted step with the same key, digest and recipient therefore rebuilds + * the identical transaction, so a crash between certification and writing the + * token file can be recovered by simply running the command again: the aggregator + * already holds that exact request and its proof is fetched. + * + * @param {Uint8Array} privateKey Producer's secp256k1 private key. + * @param {Token} token Token whose latest state is spent. + * @returns {Promise} Deterministic state mask. + */ +export async function deriveStateMask(privateKey: Uint8Array, token: Token): Promise { + const sourceStateHash = await token.latestTransaction.calculateStateHash(); + const hash = await new DataHasher(HashAlgorithm.SHA256) + .update( + CborSerializer.encodeArray( + CborSerializer.encodeTextString(`${LINEAGE_TAG}/state-mask`), + CborSerializer.encodeByteString(privateKey), + CborSerializer.encodeByteString(sourceStateHash.imprint), + ), + ) + .digest(); + return StateMask.fromBytes(hash.data); +} + +/** + * Create a lineage: mint revision 0, with the issuer's signature as the mint + * reason and the next producer's `P_sig` as recipient. + * + * The salt is random, so the token id stays unpredictable until the genesis is + * certified and cannot be squatted. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Uint8Array} digest 32-byte SHA-256 digest of the initial revision. + * @param {Uint8Array} issuerPrivateKey Issuer's private key; signs the genesis reason. + * @param {Uint8Array} nextProducer Compressed public key of whoever produces revision 1. + * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. + * @returns {Promise} Verified lineage token with no transfers. + */ +export async function createLineage( + client: StateTransitionClient, + trustBase: RootTrustBase, + digest: Uint8Array, + issuerPrivateKey: Uint8Array, + nextProducer: Uint8Array, + options: ICertifyOptions = {}, +): Promise { + const recipient = SignaturePredicate.create(nextProducer); + const auxData = LineageRevision.create(0n, digest).toCBOR(); + const salt = TokenSalt.generate(); + const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + auxData, + new SigningService(issuerPrivateKey), + ); + const transaction = await MintTransaction.create(trustBase.networkId, recipient, { + data: auxData, + justification: reason.toCBOR(), + salt, + tokenType: LINEAGE_TOKEN_TYPE, + }); + const context = createLineageVerificationContext(trustBase); + return Token.mint(await certifyMintTransaction(client, context, transaction, options), context); +} + +/** + * Check, without network contact, that `producerPrivateKey` can append to `token` + * on the network of `trustBase`: the token is a valid lineage for that network and + * its latest state is locked to that key's `P_sig`. + * + * @param {Token} token Existing lineage token. + * @param {RootTrustBase} trustBase Trust base of the token's network. + * @param {Uint8Array} producerPublicKey Public key of the would-be producer. + * @throws {LineageError} If the token is invalid or the key cannot unlock its latest state. + */ +export async function assertCanAppend( + token: Token, + trustBase: RootTrustBase, + producerPublicKey: Uint8Array, +): Promise { + const result = await verifyLineage(token, trustBase); + if (result.status !== 'OK') { + throw new LineageError( + `The token file is not a valid document lineage token: ${result.reason ?? 'unknown'}`, + 'INVALID_TOKEN', + ); + } + const current = currentProducerKey(token); + if (current === null) { + throw new LineageError( + 'The latest revision is not locked to a signature predicate; no key can append to this token.', + 'WRONG_KEY', + ); + } + if (!areUint8ArraysEqual(current, producerPublicKey)) { + throw new LineageError( + 'The key does not match the producer named by the latest revision; only that key can append the next one.', + 'WRONG_KEY', + ); + } +} + +/** + * Append the next revision: a transfer, signed under the `P_sig` the previous + * revision named, whose auxiliary data is `[i, digest]` and whose recipient is the + * producer of revision `i + 1`. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Token} token Existing lineage token. + * @param {Uint8Array} digest 32-byte SHA-256 digest of the new revision. + * @param {Uint8Array} producerPrivateKey Key named by the latest revision; signs the transfer. + * @param {Uint8Array} nextProducer Compressed public key of whoever produces the following revision. + * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. + * @returns {Promise} The token with the new revision appended. + */ +export async function appendRevision( + client: StateTransitionClient, + trustBase: RootTrustBase, + token: Token, + digest: Uint8Array, + producerPrivateKey: Uint8Array, + nextProducer: Uint8Array, + options: ICertifyOptions = {}, +): Promise { + const signer = new SigningService(producerPrivateKey); + await assertCanAppend(token, trustBase, signer.publicKey); + + const recipient = SignaturePredicate.create(nextProducer); + const index = BigInt(token.transactions.length + 1); + const transaction = await TransferTransaction.create( + token, + recipient, + await deriveStateMask(producerPrivateKey, token), + { data: LineageRevision.create(index, digest).toCBOR() }, + ); + const certificationData = await CertificationData.fromTransaction( + transaction, + await SignaturePredicateUnlockScript.create(transaction, signer), + ); + const context = createLineageVerificationContext(trustBase); + const proof = await certifyTransaction(client, context, certificationData, transaction, options); + const certified = await transaction.toCertifiedTransaction( + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + proof, + ); + const appended = await token.transfer(certified, context); + + // The SDK checks the new transfer on its own; the chain rules relate it to its + // predecessor. It is certified either way, so a violation is reported, not thrown. + const check = await verifyLineage(appended, trustBase); + if (check.status !== 'OK') { + options.onWarning?.(`The appended revision breaks a lineage rule: ${check.reason ?? 'unknown'}`); + } + return appended; +} diff --git a/src/lib/lineage/LineagePayload.ts b/src/lib/lineage/LineagePayload.ts new file mode 100644 index 0000000..7fc4869 --- /dev/null +++ b/src/lib/lineage/LineagePayload.ts @@ -0,0 +1,266 @@ +import { DataHash } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHash.js'; +import { DataHasher } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasher.js'; +import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js'; +import { Signature } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/Signature.js'; +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { CborDeserializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborDeserializer.js'; +import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; +import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; +import { TokenType } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenType.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; + +/** + * The seed string of the document lineage format: the token type is its SHA-256, + * and it is the domain tag of every signature and derivation the format defines. + * Like `unicity-timestamp`, it must never change once tokens exist. + */ +export const LINEAGE_TAG = 'unicity-document-lineage'; + +/** SHA-256 of {@link LINEAGE_TAG}. Pinned here; a unit test asserts the derivation. */ +export const LINEAGE_TOKEN_TYPE_HEX = '962e2defb924f7a9a92fee6a7eabab658933fd3973117fc5ed70587474f37028'; + +/** Token type `DOC_LINEAGE` shared by every document lineage token. */ +export const LINEAGE_TOKEN_TYPE: TokenType = new TokenType(HexConverter.decode(LINEAGE_TOKEN_TYPE_HEX)); + +/** + * CBOR tag of the genesis mint reason. The SDK dispatches mint justifications by + * tag, so the reason must carry one. Chosen outside the 39000–39099 block the SDK + * and the Yellowpaper use for their own structures. + */ +export const LINEAGE_GENESIS_REASON_TAG = 39200n; + +/** First element of the genesis reason array. */ +export const LINEAGE_REASON_VERSION = 1n; + +const DIGEST_LENGTH = 32; +const PUBLIC_KEY_LENGTH = 33; +const SIGNATURE_LENGTH = 65; + +/** Thrown when bytes do not form a valid lineage structure. */ +export class LineageFormatError extends Error { + public constructor(message: string, options?: ErrorOptions) { + super(message, options); + this.name = 'LineageFormatError'; + } +} + +function assertDigest(digest: Uint8Array): void { + if (digest.length !== DIGEST_LENGTH) { + throw new LineageFormatError(`Digest must be ${DIGEST_LENGTH} bytes (SHA-256), got ${digest.length} bytes.`); + } +} + +/** + * Deterministic CBOR only: what was decoded must re-encode to exactly the input, + * which rejects trailing bytes and non-minimal encodings in one comparison. + */ +function assertCanonical(input: Uint8Array, reencoded: Uint8Array, what: string): void { + if (!areUint8ArraysEqual(input, reencoded)) { + throw new LineageFormatError(`${what} is not in canonical CBOR encoding.`); + } +} + +/** + * Auxiliary data of every lineage transaction, `CBOR[i, H(doc_i)]`: the revision + * index (0 at genesis, then one more per transfer) and the SHA-256 digest of that + * revision. The document itself is never stored. No previous digest is needed; + * linkage comes from the state hash chain. + */ +export class LineageRevision { + private constructor( + public readonly index: bigint, + private readonly _digest: Uint8Array, + ) { + this._digest = new Uint8Array(_digest); + } + + /** @returns {Uint8Array} Copy of the 32-byte SHA-256 digest of the revision. */ + public get digest(): Uint8Array { + return new Uint8Array(this._digest); + } + + /** + * @param {bigint} index Revision index. + * @param {Uint8Array} digest 32-byte SHA-256 digest. + * @returns {LineageRevision} Revision payload. + * @throws {LineageFormatError} If the digest is not 32 bytes or the index is negative. + */ + public static create(index: bigint, digest: Uint8Array): LineageRevision { + if (index < 0n) { + throw new LineageFormatError(`Revision index must not be negative, got ${index}.`); + } + assertDigest(digest); + return new LineageRevision(index, digest); + } + + /** + * Strict decoder. + * + * @param {Uint8Array} bytes CBOR bytes. + * @returns {LineageRevision} Decoded payload. + * @throws {LineageFormatError} On any structural problem. + */ + public static fromCBOR(bytes: Uint8Array): LineageRevision { + let index: bigint; + let digest: Uint8Array; + try { + const elements = CborDeserializer.decodeArray(bytes, 2); + index = CborDeserializer.decodeUnsignedInteger(elements[0]); + digest = CborDeserializer.decodeByteString(elements[1]); + } catch (error) { + throw new LineageFormatError('Revision payload is not a CBOR array of [index, digest].', { cause: error }); + } + assertDigest(digest); + const revision = new LineageRevision(index, digest); + assertCanonical(bytes, revision.toCBOR(), 'Revision payload'); + return revision; + } + + /** @returns {Uint8Array} CBOR encoding. */ + public toCBOR(): Uint8Array { + return CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(this.index), + CborSerializer.encodeByteString(this._digest), + ); + } +} + +/** + * Genesis mint reason: the issuer's signature over `(id, ty, auxData)`. + * + * ``` + * tag 39200 [ 1, issuer(33), signature(65) ] + * ``` + * + * The mint key is public, so anyone can mint a token of any type; this signature + * is what makes an origin "accepted". Verifiers pin a lineage by its token id, or + * by the issuer key together with the initial digest. + */ +export class LineageGenesisReason { + private constructor( + private readonly _issuer: Uint8Array, + public readonly signature: Signature, + ) { + this._issuer = new Uint8Array(_issuer); + } + + /** @returns {Uint8Array} Copy of the issuer's compressed public key. */ + public get issuer(): Uint8Array { + return new Uint8Array(this._issuer); + } + + /** + * Strict decoder. + * + * @param {Uint8Array} bytes CBOR bytes. + * @returns {LineageGenesisReason} Decoded reason. + * @throws {LineageFormatError} On any structural problem. + */ + public static fromCBOR(bytes: Uint8Array): LineageGenesisReason { + let version: bigint; + let issuer: Uint8Array; + let signatureBytes: Uint8Array; + try { + const tag = CborDeserializer.decodeTag(bytes); + if (tag.tag !== LINEAGE_GENESIS_REASON_TAG) { + throw new LineageFormatError(`Unexpected CBOR tag ${tag.tag}.`); + } + const elements = CborDeserializer.decodeArray(tag.data, 3); + version = CborDeserializer.decodeUnsignedInteger(elements[0]); + issuer = CborDeserializer.decodeByteString(elements[1]); + signatureBytes = CborDeserializer.decodeByteString(elements[2]); + } catch (error) { + throw new LineageFormatError( + `Genesis reason is not tag ${LINEAGE_GENESIS_REASON_TAG} over [version, issuer, signature].`, + { cause: error }, + ); + } + if (version !== LINEAGE_REASON_VERSION) { + throw new LineageFormatError( + `Unsupported genesis reason version ${version}; expected ${LINEAGE_REASON_VERSION}.`, + ); + } + if (issuer.length !== PUBLIC_KEY_LENGTH || !SigningService.isPublicKeyValid(issuer)) { + throw new LineageFormatError('Issuer is not a valid compressed secp256k1 public key.'); + } + if (signatureBytes.length !== SIGNATURE_LENGTH) { + throw new LineageFormatError(`Signature must be ${SIGNATURE_LENGTH} bytes, got ${signatureBytes.length} bytes.`); + } + let signature: Signature; + try { + signature = Signature.decode(signatureBytes); + } catch (error) { + throw new LineageFormatError('Signature is malformed.', { cause: error }); + } + const reason = new LineageGenesisReason(issuer, signature); + assertCanonical(bytes, reason.toCBOR(), 'Genesis reason'); + return reason; + } + + /** + * @param {TokenId} tokenId Token id of the lineage. + * @param {TokenType} tokenType Token type. + * @param {Uint8Array} auxData Exact auxiliary data bytes of the mint. + * @param {SigningService} issuer Issuer's signing service. + * @returns {Promise} Signed reason. + */ + public static async sign( + tokenId: TokenId, + tokenType: TokenType, + auxData: Uint8Array, + issuer: SigningService, + ): Promise { + const signature = await issuer.sign(await LineageGenesisReason.signedMessage(tokenId, tokenType, auxData)); + return new LineageGenesisReason(issuer.publicKey, signature); + } + + /** + * Message the issuer signs: + * `SHA-256(CBOR["unicity-document-lineage", 1, id, ty, auxData])`. + * + * @param {TokenId} tokenId Token id of the lineage. + * @param {TokenType} tokenType Token type. + * @param {Uint8Array} auxData Exact auxiliary data bytes of the mint. + * @returns {Promise} Message hash. + */ + public static signedMessage(tokenId: TokenId, tokenType: TokenType, auxData: Uint8Array): Promise { + return new DataHasher(HashAlgorithm.SHA256) + .update( + CborSerializer.encodeArray( + CborSerializer.encodeTextString(LINEAGE_TAG), + CborSerializer.encodeUnsignedInteger(LINEAGE_REASON_VERSION), + CborSerializer.encodeByteString(tokenId.bytes), + CborSerializer.encodeByteString(tokenType.bytes), + CborSerializer.encodeByteString(auxData), + ), + ) + .digest(); + } + + /** @returns {Uint8Array} Tagged CBOR encoding. */ + public toCBOR(): Uint8Array { + return CborSerializer.encodeTag( + LINEAGE_GENESIS_REASON_TAG, + CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(LINEAGE_REASON_VERSION), + CborSerializer.encodeByteString(this._issuer), + CborSerializer.encodeByteString(this.signature.encode()), + ), + ); + } + + /** + * @param {TokenId} tokenId Token id of the lineage. + * @param {TokenType} tokenType Token type. + * @param {Uint8Array} auxData Exact auxiliary data bytes of the mint. + * @returns {Promise} True if the signature verifies for the issuer. + */ + public async verify(tokenId: TokenId, tokenType: TokenType, auxData: Uint8Array): Promise { + return SigningService.verifyWithPublicKey( + await LineageGenesisReason.signedMessage(tokenId, tokenType, auxData), + this.signature, + this._issuer, + ); + } +} diff --git a/src/lib/lineage/LineageVerification.ts b/src/lib/lineage/LineageVerification.ts new file mode 100644 index 0000000..faf7310 --- /dev/null +++ b/src/lib/lineage/LineageVerification.ts @@ -0,0 +1,285 @@ +import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; +import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; +import { PredicateVerifierService } from '@unicitylabs/state-transition-sdk/lib/predicate/verification/PredicateVerifierService.js'; +import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TokenType } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenType.js'; +import type { IMintJustificationVerifier } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/IMintJustificationVerifier.js'; +import type { ITokenIssuanceVerifier } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/ITokenIssuanceVerifier.js'; +import { MintJustificationVerifierService } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/MintJustificationVerifierService.js'; +import { TokenIssuanceVerifierService } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/TokenIssuanceVerifierService.js'; +import { VerificationContext } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/VerificationContext.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; +import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; +import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; + +import { + LINEAGE_GENESIS_REASON_TAG, + LINEAGE_TOKEN_TYPE, + LineageGenesisReason, + LineageRevision, +} from './LineagePayload.js'; +import { errorMessage } from '../errors.js'; +import { createUnicityCertificateVerifier } from '../verification.js'; + +type Result = VerificationResult; + +function check(rule: string, ok: boolean, failureMessage: string): Result { + return new VerificationResult(rule, ok ? VerificationStatus.OK : VerificationStatus.FAIL, ok ? '' : failureMessage); +} + +function combine(rule: string, results: Result[]): Result { + const firstFailure = results.find((result) => result.status !== VerificationStatus.OK); + return VerificationResult.fromResults(rule, results, firstFailure?.message ?? ''); +} + +/** + * Issuance policy for `DOC_LINEAGE` tokens: the genesis carries revision 0 as its + * auxiliary data and an issuer reason. The reason's signature is checked by + * {@link LineageGenesisReasonVerifier}, which the SDK dispatches by CBOR tag; this + * verifier only insists the reason is there, because the SDK accepts a mint with + * no justification at all. The recipient may be any predicate. + */ +export class LineageIssuanceVerifier implements ITokenIssuanceVerifier { + public static readonly RULE = 'LineageIssuanceVerification'; + + /** @returns {TokenType} The document lineage token type. */ + public get tokenType(): TokenType { + return LINEAGE_TOKEN_TYPE; + } + + /** @inheritDoc */ + public verify(transaction: CertifiedMintTransaction): Promise { + const results: Result[] = []; + try { + results.push( + check('GenesisReasonPresent', transaction.justification !== null, 'Lineage genesis carries no issuer reason.'), + ); + const data = transaction.data; + if (data === null) { + results.push(check('RevisionPresent', false, 'Lineage genesis carries no revision payload.')); + } else { + const revision = LineageRevision.fromCBOR(data); + results.push(check('RevisionDecodes', true, '')); + results.push( + check('GenesisRevisionIsZero', revision.index === 0n, `Genesis revision index is ${revision.index}, not 0.`), + ); + } + } catch (error) { + results.push(check('RevisionDecodes', false, errorMessage(error))); + } + return Promise.resolve(combine(LineageIssuanceVerifier.RULE, results)); + } +} + +/** Checks the issuer signature in a lineage genesis reason. */ +export class LineageGenesisReasonVerifier implements IMintJustificationVerifier { + public static readonly RULE = 'LineageGenesisReasonVerification'; + + /** @returns {bigint} CBOR tag of the lineage genesis reason. */ + public get tag(): bigint { + return LINEAGE_GENESIS_REASON_TAG; + } + + /** @inheritDoc */ + public async verify(transaction: CertifiedMintTransaction): Promise { + const results: Result[] = []; + try { + if (!areUint8ArraysEqual(transaction.tokenType.bytes, LINEAGE_TOKEN_TYPE.bytes)) { + results.push(check('TokenTypeIsLineage', false, 'A lineage genesis reason on a token of another type.')); + } else { + const reason = LineageGenesisReason.fromCBOR(transaction.justification as Uint8Array); + const data = transaction.data ?? new Uint8Array(); + results.push( + check( + 'IssuerSignatureValid', + await reason.verify(transaction.tokenId, transaction.tokenType, data), + 'Issuer signature in the genesis reason does not verify.', + ), + ); + } + } catch (error) { + results.push(check('GenesisReasonDecodes', false, errorMessage(error))); + } + return combine(LineageGenesisReasonVerifier.RULE, results); + } +} + +/** + * Verification context that accepts document lineage tokens and nothing else. + * + * @param {RootTrustBase} trustBase Trust base of the network the token belongs to. + * @returns {VerificationContext} Context for `token.verify`, `Token.mint` and `token.transfer`. + */ +export function createLineageVerificationContext(trustBase: RootTrustBase): VerificationContext { + return new VerificationContext( + trustBase, + PredicateVerifierService.create(), + createUnicityCertificateVerifier(), + new MintJustificationVerifierService().register(new LineageGenesisReasonVerifier()), + new TokenIssuanceVerifierService(true).register(new LineageIssuanceVerifier()), + ); +} + +/** One revision of a lineage as read off the token. */ +export interface ILineageRevisionDescription { + readonly digest: Uint8Array | null; + readonly error: string | null; + readonly index: bigint | null; + /** Public key of the `P_sig` the revision names as producer of the next one; null for any other predicate. */ + readonly nextProducer: Uint8Array | null; + /** Unix seconds. */ + readonly referenceTime: bigint; +} + +/** What a lineage token claims, without verifying it. */ +export interface ILineageDescription { + readonly issuer: Uint8Array | null; + readonly revisions: readonly ILineageRevisionDescription[]; + readonly token: Token; + readonly tokenTypeIsLineage: boolean; +} + +function signaturePredicateKey(predicate: EncodedPredicate): Uint8Array | null { + try { + return SignaturePredicate.fromPredicate(predicate).publicKey; + } catch { + return null; + } +} + +function describeRevision( + data: Uint8Array | null, + recipient: EncodedPredicate, + referenceTime: bigint, +): ILineageRevisionDescription { + const nextProducer = signaturePredicateKey(recipient); + if (data === null) { + return { digest: null, error: 'no revision payload', index: null, nextProducer, referenceTime }; + } + try { + const revision = LineageRevision.fromCBOR(data); + return { digest: revision.digest, error: null, index: revision.index, nextProducer, referenceTime }; + } catch (error) { + return { digest: null, error: errorMessage(error), index: null, nextProducer, referenceTime }; + } +} + +/** + * Read the lineage fields off a token without verifying anything. + * + * @param {Token} token Any SDK token. + * @returns {ILineageDescription} What the token claims. + */ +export function describeLineage(token: Token): ILineageDescription { + let issuer: Uint8Array | null = null; + if (token.genesis.justification !== null) { + try { + issuer = LineageGenesisReason.fromCBOR(token.genesis.justification).issuer; + } catch { + issuer = null; + } + } + return { + issuer, + revisions: [ + describeRevision(token.genesis.data, token.genesis.recipient, token.genesis.referenceTime), + ...token.transactions.map((transaction) => + describeRevision(transaction.data, transaction.recipient, transaction.referenceTime), + ), + ], + token, + tokenTypeIsLineage: areUint8ArraysEqual(token.type.bytes, LINEAGE_TOKEN_TYPE.bytes), + }; +} + +export interface ILineageVerificationResult { + readonly description: ILineageDescription; + /** SDK result tree, or null when it was not reached. */ + readonly details: Result | null; + readonly reason: string | null; + readonly status: 'FAIL' | 'OK'; +} + +/** + * Rules the SDK does not check, because they relate neighbouring transactions: + * each revision's index is one more than the previous, and reference times never + * decrease along the chain (the protocol does not imply this; states can be + * precomputed and certified out of order). + */ +function chainRules(description: ILineageDescription): Result { + const results: Result[] = []; + description.revisions.forEach((revision, position) => { + if (revision.error !== null) { + results.push(check(`Revision[${position}]Decodes`, false, `Revision ${position}: ${revision.error}`)); + return; + } + results.push( + check( + `Revision[${position}]IndexSequential`, + revision.index === BigInt(position), + `Revision at position ${position} claims index ${revision.index}.`, + ), + ); + const previous = description.revisions[position - 1]; + if (previous !== undefined) { + results.push( + check( + `Revision[${position}]TimeMonotone`, + revision.referenceTime >= previous.referenceTime, + `Revision ${position} is certified at ${revision.referenceTime}, before revision ${position - 1} at ${previous.referenceTime}.`, + ), + ); + } + }); + return combine('LineageChainVerification', results); +} + +function deepestMessage(result: VerificationResult): string { + if (result.status === VerificationStatus.OK) { + return ''; + } + for (const child of result.results) { + const message = deepestMessage(child); + if (message !== '') { + return message; + } + } + return result.message !== '' ? result.message : `Verification rule ${result.rule} failed.`; +} + +/** + * Verify a document lineage token offline: the SDK's full token verification with + * the lineage issuance policy, then the chain rules. + * + * @param {Token} token Token to verify. + * @param {RootTrustBase} trustBase Trust base of the token's network. + * @returns {Promise} Outcome. + */ +export async function verifyLineage(token: Token, trustBase: RootTrustBase): Promise { + const description = describeLineage(token); + if (!description.tokenTypeIsLineage) { + return { + description, + details: null, + reason: `Not a document lineage token: token type ${HexConverter.encode(token.type.bytes)}.`, + status: 'FAIL', + }; + } + if (token.networkId.id !== trustBase.networkId.id) { + return { + description, + details: null, + reason: `The token is for network ${token.networkId.id} and the trust base for network ${trustBase.networkId.id}.`, + status: 'FAIL', + }; + } + const sdk = await token.verify(createLineageVerificationContext(trustBase)); + const details = VerificationResult.fromResults('LineageTokenVerification', [sdk, chainRules(description)]); + if (details.status !== VerificationStatus.OK) { + return { description, details, reason: deepestMessage(details), status: 'FAIL' }; + } + return { description, details, reason: null, status: 'OK' }; +} diff --git a/src/output.ts b/src/output.ts index 15a7e95..b511020 100644 --- a/src/output.ts +++ b/src/output.ts @@ -363,3 +363,93 @@ export function verifyJson(result: ITimestampVerificationResult, source: TrustBa export function inspectJson(description: ITimestampDescription): IInspectJson { return { command: 'inspect', verified: false, ...descriptionJson(description) }; } + +/** What `stamp-revision` reports about the revision it just certified. */ +export interface IRevisionSummary { + readonly created: boolean; + readonly digest: Uint8Array; + readonly epoch: bigint; + readonly gatewayUrl: string; + readonly networkId: number; + readonly nextProducer: Uint8Array; + readonly referenceTime: bigint; + readonly revision: bigint; + readonly roundNumber: bigint; + readonly roundTimestamp: bigint; + readonly signer: Uint8Array; + readonly tokenFile: string; + readonly tokenId: Uint8Array; +} + +export interface IRevisionJson { + readonly command: 'stamp-revision'; + readonly created: boolean; + readonly hash: { readonly algorithm: 'SHA-256'; readonly digest: string }; + readonly network: INetworkJson & { readonly gateway: string }; + readonly nextProducer: string; + readonly referenceTime: string; + readonly referenceTimeIso: string | null; + readonly revision: string; + readonly round: { readonly epoch: string; readonly number: string; readonly timestamp: string }; + readonly signer: string; + readonly tokenFile: string; + readonly tokenId: string; +} + +/** + * @param {IRevisionSummary} summary The certified revision. + * @returns {string} Human summary of a `stamp-revision`. + */ +export function revisionText(summary: IRevisionSummary): string { + return [ + line('Revision', `${summary.revision}${summary.created ? ' (new lineage)' : ''}`), + line('Stamped', `SHA-256 ${HexConverter.encode(summary.digest)}`), + line('Network', `${networkLabel(summary.networkId)} via ${summary.gatewayUrl}`), + line('Signed by', HexConverter.encode(summary.signer)), + line('Next producer', HexConverter.encode(summary.nextProducer)), + line('Certified at', `${formatIso(summary.referenceTime)} (reference time ${summary.referenceTime})`), + line('Round', `${summary.roundNumber} (round timestamp ${summary.roundTimestamp}, epoch ${summary.epoch})`), + line('Token id', HexConverter.encode(summary.tokenId)), + line('Written', summary.tokenFile), + ].join('\n'); +} + +/** + * @param {IRevisionSummary} summary The certified revision. + * @returns {IRevisionJson} JSON-safe summary; big integers as decimal strings. + */ +export function revisionJson(summary: IRevisionSummary): IRevisionJson { + return { + command: 'stamp-revision', + created: summary.created, + hash: { algorithm: 'SHA-256', digest: HexConverter.encode(summary.digest) }, + network: { gateway: summary.gatewayUrl, id: summary.networkId, name: networkName(summary.networkId) }, + nextProducer: HexConverter.encode(summary.nextProducer), + referenceTime: summary.referenceTime.toString(), + referenceTimeIso: toIso(summary.referenceTime), + revision: summary.revision.toString(), + round: { + epoch: summary.epoch.toString(), + number: summary.roundNumber.toString(), + timestamp: summary.roundTimestamp.toString(), + }, + signer: HexConverter.encode(summary.signer), + tokenFile: summary.tokenFile, + tokenId: HexConverter.encode(summary.tokenId), + }; +} + +/** + * Last resort for a revision that was certified but could not be written. + * + * @param {Uint8Array} bytes Encoded token, including the new revision. + * @returns {string} Message and token hex, for stderr. + */ +export function revisionRecoveryLines(bytes: Uint8Array): string { + return [ + 'error: the revision was certified but the token file could not be written.', + 'Save the token below; `stamp-revision --token-file` accepts hex text.', + HexConverter.encode(bytes), + '', + ].join('\n'); +} diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts new file mode 100644 index 0000000..220a257 --- /dev/null +++ b/tests/unit/StampRevisionTest.ts @@ -0,0 +1,241 @@ +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { stampRevisionWith, writeRevisionToken } from '../../src/commands/stampRevision.js'; +import { IStampRevisionConfig, parsePublicKey, resolveStampRevisionConfig } from '../../src/config.js'; +import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; +import { verifyLineage } from '../../src/lib/lineage/LineageVerification.js'; +import { testContext } from '../support/context.js'; +import { + OTHER_DIGEST, + OTHER_DIGEST_HEX, + tempDir, + TEST_DIGEST, + TEST_DIGEST_HEX, + TEST_PRIVATE_KEY, + TEST_PRIVATE_KEY_HEX, + TEST_PUBLIC_KEY_HEX, +} from '../support/fixtures.js'; +import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; + +const ENV = { UNICITY_API_KEY: 'key' }; + +describe('resolveStampRevisionConfig', () => { + let directory: string; + let keyFile: string; + + beforeEach(async () => { + directory = await tempDir('proof-cli-revision-'); + keyFile = path.join(directory, 'producer.key'); + await writeFile(keyFile, `${TEST_PRIVATE_KEY_HEX}\n`); + }); + + const base = (): Record => ({ + keyFile, + recipientKey: TEST_PUBLIC_KEY_HEX, + tokenFile: path.join(directory, 'doc.lineage'), + }); + + it('resolves a new lineage', async () => { + const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), ENV); + expect(config.tokenBytes).toBeNull(); + expect(config.digest).toEqual(TEST_DIGEST); + expect(config.privateKey).toEqual(TEST_PRIVATE_KEY); + expect(HexConverter.encode(config.recipientKey)).toEqual(TEST_PUBLIC_KEY_HEX); + expect(config.network.preset).toEqual('mainnet'); + }); + + it('reads an existing token file and a recipient key file', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + await writeFile(tokenFile, 'abcd'); + const recipientKeyFile = path.join(directory, 'next.pub'); + await writeFile(recipientKeyFile, ` ${TEST_PUBLIC_KEY_HEX.toUpperCase()}\n`); + const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, { keyFile, recipientKeyFile, tokenFile }, ENV); + expect(config.tokenBytes).toEqual(new TextEncoder().encode('abcd')); + expect(HexConverter.encode(config.recipientKey)).toEqual(TEST_PUBLIC_KEY_HEX); + }); + + it.each([ + ['no digest source', undefined, {}, 'Pass a SHA-256 digest or --file .'], + ['both digest sources', TEST_DIGEST_HEX, { file: 'x' }, 'Pass either a digest or --file, not both.'], + ['no token file', TEST_DIGEST_HEX, { tokenFile: undefined }, /--token-file/], + ['no key file', TEST_DIGEST_HEX, { keyFile: undefined }, /--key-file/], + ['no recipient', TEST_DIGEST_HEX, { recipientKey: undefined }, /--recipient-key or --recipient-key-file/], + [ + 'both recipients', + TEST_DIGEST_HEX, + { recipientKeyFile: 'x' }, + 'Pass either --recipient-key or --recipient-key-file, not both.', + ], + ['a malformed recipient', TEST_DIGEST_HEX, { recipientKey: '04abcd' }, /compressed secp256k1 public key/], + [ + 'a missing recipient file', + TEST_DIGEST_HEX, + { recipientKey: undefined, recipientKeyFile: '/no/such' }, + /Cannot read/, + ], + ])('refuses %s', async (_, digest, overrides, message) => { + await expect(resolveStampRevisionConfig(digest, { ...base(), ...overrides }, ENV)).rejects.toMatchObject({ + exitCode: EXIT_USAGE, + }); + await expect(resolveStampRevisionConfig(digest, { ...base(), ...overrides }, ENV)).rejects.toThrow(message); + }); + + it('refuses a token file in a directory that does not exist', async () => { + await expect( + resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), tokenFile: path.join(directory, 'no', 'x') }, ENV), + ).rejects.toThrow(/Cannot write to the token file directory/); + }); + + it('requires an API key', async () => { + await expect(resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), {})).rejects.toThrow(/No API key/); + }); +}); + +describe('parsePublicKey', () => { + it('accepts a compressed key with or without 0x', () => { + expect(HexConverter.encode(parsePublicKey(`0x${TEST_PUBLIC_KEY_HEX}`))).toEqual(TEST_PUBLIC_KEY_HEX); + }); + + it('rejects a point that is not on the curve', () => { + expect(() => parsePublicKey(`02${'ff'.repeat(32)}`)).toThrow(/not a point/); + }); +}); + +describe('stampRevisionWith', () => { + const aggregator = TestAggregatorClient.create(); + const client = new StateTransitionClient(aggregator); + const bob = SigningService.generatePrivateKey(); + const bobPublic = new SigningService(bob).publicKey; + let directory: string; + + beforeEach(async () => { + directory = await tempDir('proof-cli-revision-'); + }); + + function config(overrides: Partial): IStampRevisionConfig { + return { + allowInsecure: false, + apiKey: 'key', + digest: TEST_DIGEST, + network: { gatewayUrl: 'https://gateway.test', preset: 'testnet2', trustBase: aggregator.rootTrustBase }, + privateKey: TEST_PRIVATE_KEY, + recipientKey: bobPublic, + timeoutMs: 2_000, + tokenBytes: null, + tokenFile: path.join(directory, 'doc.lineage'), + ...overrides, + }; + } + + it('creates the token file, then appends to it', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + const first = testContext({ json: true }); + expect(await stampRevisionWith(config({}), client, first.context)).toBe(0); + expect(first.json()).toMatchObject({ + command: 'stamp-revision', + created: true, + hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, + nextProducer: HexConverter.encode(bobPublic), + revision: '0', + signer: TEST_PUBLIC_KEY_HEX, + tokenFile, + }); + + const second = testContext(); + const tokenBytes = new Uint8Array(await readFile(tokenFile)); + expect( + await stampRevisionWith( + config({ + digest: OTHER_DIGEST, + privateKey: bob, + recipientKey: HexConverter.decode(TEST_PUBLIC_KEY_HEX), + tokenBytes, + }), + client, + second.context, + ), + ).toBe(0); + expect(second.stdout()).toContain('Revision 1\n'); + expect(second.stdout()).toContain(`Stamped SHA-256 ${OTHER_DIGEST_HEX}`); + expect(await readdir(directory)).toEqual(['doc.lineage']); + + const token = await Token.fromCBOR(new Uint8Array(await readFile(tokenFile))); + expect(token.transactions).toHaveLength(1); + expect((await verifyLineage(token, aggregator.rootTrustBase)).status).toEqual('OK'); + }); + + it('accepts a token file holding hex text', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + await stampRevisionWith(config({}), client, testContext().context); + const hex = HexConverter.encode(new Uint8Array(await readFile(tokenFile))); + await expect( + stampRevisionWith( + config({ privateKey: bob, tokenBytes: new TextEncoder().encode(`${hex}\n`) }), + client, + testContext().context, + ), + ).resolves.toBe(0); + }); + + it('refuses a key that is not the named producer, leaving the file alone', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + await stampRevisionWith(config({}), client, testContext().context); + const before = await readFile(tokenFile); + const attempt = stampRevisionWith(config({ tokenBytes: new Uint8Array(before) }), client, testContext().context); + await expect(attempt).rejects.toThrow(/does not match the producer/); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await readFile(tokenFile)).toEqual(before); + }); + + it('refuses a file that is not a token', async () => { + const attempt = stampRevisionWith( + config({ tokenBytes: new TextEncoder().encode('hello') }), + client, + testContext().context, + ); + await expect(attempt).rejects.toThrow(/is not a token/); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_VERIFICATION_FAILED); + }); +}); + +describe('writeRevisionToken', () => { + const TOKEN = new Uint8Array([0xd9, 0x01, 0x00, 0x82, 0x01, 0x02]); + + it('replaces an existing file without leaving a temporary behind', async () => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + await writeFile(out, 'old'); + const sink = testContext(); + await writeRevisionToken(out, TOKEN, false, sink.context); + expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(sink.stderr()).toEqual(''); + }); + + it('never clobbers a file that appeared before a new lineage was written, and prints the token', async () => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + await writeFile(out, 'someone else'); + const sink = testContext(); + await expect(writeRevisionToken(out, TOKEN, true, sink.context)).rejects.toThrow(/EEXIST/); + expect(await readFile(out, 'utf8')).toEqual('someone else'); + expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); + }); + + it('prints the token when the directory is gone', async () => { + const directory = await tempDir('proof-cli-revision-'); + await mkdir(path.join(directory, 'sub')); + const sink = testContext(); + await expect( + writeRevisionToken(path.join(directory, 'missing', 'doc.lineage'), TOKEN, false, sink.context), + ).rejects.toThrow(/ENOENT/); + expect(sink.stderr()).toContain('the revision was certified'); + expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); + }); +}); diff --git a/tests/unit/lib/LineageTest.ts b/tests/unit/lib/LineageTest.ts new file mode 100644 index 0000000..a34338b --- /dev/null +++ b/tests/unit/lib/LineageTest.ts @@ -0,0 +1,260 @@ +import { createHash } from 'node:crypto'; + +import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; +import { CertificationResponse } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; +import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/IAggregatorClient.js'; +import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js'; +import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; +import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; +import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { + appendRevision, + createLineage, + currentProducerKey, + LineageError, +} from '../../../src/lib/lineage/LineageClient.js'; +import { + LINEAGE_TAG, + LINEAGE_TOKEN_TYPE, + LINEAGE_TOKEN_TYPE_HEX, + LineageFormatError, + LineageGenesisReason, + LineageRevision, +} from '../../../src/lib/lineage/LineagePayload.js'; +import { describeLineage, verifyLineage } from '../../../src/lib/lineage/LineageVerification.js'; +import { bundledTrustBase } from '../../../src/lib/networks.js'; +import { stampWith } from '../../../src/lib/TimestampClient.js'; +import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; +import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; +import { certifyMint } from '../../support/TimestampFixtures.js'; + +/** Counts certification requests so a test can see whether the network was contacted. */ +class CountingClient implements IAggregatorClient { + public submissions = 0; + + public constructor(private readonly inner: TestAggregatorClient) {} + + public getInclusionProof(stateId: StateId): Promise { + return this.inner.getInclusionProof(stateId); + } + + public submitCertificationRequest(certificationData: CertificationData): Promise { + this.submissions += 1; + return this.inner.submitCertificationRequest(certificationData); + } +} + +describe('document lineage', () => { + const aggregator = TestAggregatorClient.create(); + const counting = new CountingClient(aggregator); + const client = new StateTransitionClient(counting); + const trustBase = aggregator.rootTrustBase; + const fast = { pollIntervalMs: 10, timeoutMs: 2_000 }; + + const alice = SigningService.generatePrivateKey(); + const bob = SigningService.generatePrivateKey(); + const carol = SigningService.generatePrivateKey(); + const publicKey = (key: Uint8Array): Uint8Array => new SigningService(key).publicKey; + const THIRD_DIGEST = new Uint8Array(createHash('sha256').update('v2').digest()); + + it('pins the token type to SHA-256 of the tag', () => { + expect(createHash('sha256').update(LINEAGE_TAG).digest('hex')).toEqual(LINEAGE_TOKEN_TYPE_HEX); + }); + + it('creates a lineage, appends revisions along the chain of custody, and verifies offline', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + expect(genesis.transactions).toHaveLength(0); + expect(HexConverter.encode(genesis.type.bytes)).toEqual(LINEAGE_TOKEN_TYPE_HEX); + expect(currentProducerKey(genesis)).toEqual(publicKey(bob)); + + const second = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + const third = await appendRevision( + client, + trustBase, + await Token.fromCBOR(second.toCBOR()), + THIRD_DIGEST, + carol, + publicKey(alice), + fast, + ); + + const result = await verifyLineage(await Token.fromCBOR(third.toCBOR()), trustBase); + expect(result.reason).toBeNull(); + expect(result.status).toEqual('OK'); + expect(result.description.issuer).toEqual(publicKey(alice)); + expect(result.description.revisions.map((revision) => revision.index)).toEqual([0n, 1n, 2n]); + expect(result.description.revisions.map((revision) => HexConverter.encode(revision.digest!))).toEqual( + [TEST_DIGEST, OTHER_DIGEST, THIRD_DIGEST].map((digest) => HexConverter.encode(digest)), + ); + expect(result.description.revisions.map((revision) => revision.nextProducer)).toEqual([ + publicKey(bob), + publicKey(carol), + publicKey(alice), + ]); + }); + + it('refuses, before contacting the network, a key that is not the named producer', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const before = counting.submissions; + const attempt = appendRevision(client, trustBase, genesis, OTHER_DIGEST, alice, publicKey(carol), fast); + await expect(attempt).rejects.toBeInstanceOf(LineageError); + await expect(attempt).rejects.toMatchObject({ code: 'WRONG_KEY' }); + expect(counting.submissions).toBe(before); + }); + + it('refuses to append to a token of another type', async () => { + const stamp = await stampWith(client, trustBase, TEST_DIGEST, fast); + const attempt = appendRevision(client, trustBase, stamp, OTHER_DIGEST, alice, publicKey(bob), fast); + await expect(attempt).rejects.toMatchObject({ code: 'INVALID_TOKEN' }); + await expect(attempt).rejects.toThrow(/Not a document lineage token/); + }); + + it('refuses to append to a token from another network', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + await expect( + appendRevision(client, bundledTrustBase('mainnet'), genesis, OTHER_DIGEST, bob, publicKey(carol), fast), + ).rejects.toMatchObject({ code: 'INVALID_TOKEN' }); + }); + + it('replays an interrupted step identically, so running it again recovers the revision', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const first = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + // Same inputs against the same starting state: the aggregator already holds this request. + const again = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + expect(HexConverter.encode(again.toCBOR())).toEqual(HexConverter.encode(first.toCBOR())); + }); + + it('cannot fork: a different successor of a spent state is never certified', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + await expect( + appendRevision(client, trustBase, genesis, THIRD_DIGEST, bob, publicKey(carol), { + pollIntervalMs: 10, + timeoutMs: 300, + }), + ).rejects.toThrow(); + }); + + describe('verification', () => { + /** Mint a lineage-typed genesis with arbitrary fields and wrap it as a token, bypassing issuance checks. */ + async function rawLineageToken(options: { + data?: Uint8Array | null; + justification?: Uint8Array | null; + }): Promise { + const salt = TokenSalt.generate(); + const genesis = await certifyMint(aggregator, SignaturePredicate.create(publicKey(bob)), { + salt, + tokenType: LINEAGE_TOKEN_TYPE, + ...options, + }); + return Token.fromCBOR( + CborSerializer.encodeTag( + Token.CBOR_TAG, + CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(2n), + genesis.toCBOR(), + CborSerializer.encodeArray(), + ), + ), + ); + } + + it('rejects a genesis whose issuer signature covers another token', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const otherId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); + const reason = await LineageGenesisReason.sign(otherId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); + const result = await verifyLineage(await rawLineageToken({ data, justification: reason.toCBOR() }), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Issuer signature in the genesis reason does not verify.'); + }); + + it('rejects a genesis without an issuer reason', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const result = await verifyLineage(await rawLineageToken({ data, justification: null }), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Lineage genesis carries no issuer reason.'); + }); + + it('rejects a genesis that does not start at revision 0', async () => { + const salt = TokenSalt.generate(); + const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); + const data = LineageRevision.create(1n, TEST_DIGEST).toCBOR(); + const reason = await LineageGenesisReason.sign(tokenId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); + const genesis = await certifyMint(aggregator, SignaturePredicate.create(publicKey(bob)), { + data, + justification: reason.toCBOR(), + salt, + tokenType: LINEAGE_TOKEN_TYPE, + }); + const token = await Token.fromCBOR( + CborSerializer.encodeTag( + Token.CBOR_TAG, + CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(2n), + genesis.toCBOR(), + CborSerializer.encodeArray(), + ), + ), + ); + const result = await verifyLineage(token, trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Genesis revision index is 1, not 0.'); + }); + + it('describes revisions without verifying', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const description = describeLineage(genesis); + expect(description.tokenTypeIsLineage).toBe(true); + expect(description.revisions).toHaveLength(1); + expect(description.revisions[0].error).toBeNull(); + }); + }); + + describe('payload encoding', () => { + it('round-trips a revision', () => { + const revision = LineageRevision.create(3n, TEST_DIGEST); + const decoded = LineageRevision.fromCBOR(revision.toCBOR()); + expect(decoded.index).toBe(3n); + expect(decoded.digest).toEqual(TEST_DIGEST); + }); + + it('rejects malformed revisions', () => { + expect(() => LineageRevision.create(0n, new Uint8Array(31))).toThrow(LineageFormatError); + expect(() => + LineageRevision.fromCBOR(CborSerializer.encodeArray(CborSerializer.encodeUnsignedInteger(0n))), + ).toThrow(LineageFormatError); + const trailing = new Uint8Array([...LineageRevision.create(0n, TEST_DIGEST).toCBOR(), 0x00]); + expect(() => LineageRevision.fromCBOR(trailing)).toThrow(LineageFormatError); + }); + + it('round-trips a genesis reason and rejects a wrong tag', async () => { + const tokenId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + TEST_DIGEST, + new SigningService(alice), + ); + const decoded = LineageGenesisReason.fromCBOR(reason.toCBOR()); + expect(decoded.issuer).toEqual(publicKey(alice)); + expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, TEST_DIGEST)).toBe(true); + expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, OTHER_DIGEST)).toBe(false); + + const wrongTag = CborSerializer.encodeTag(1n, CborSerializer.encodeArray()); + expect(() => LineageGenesisReason.fromCBOR(wrongTag)).toThrow(LineageFormatError); + }); + + it('builds the recipient as a P_sig predicate', () => { + const predicate = EncodedPredicate.fromPredicate(SignaturePredicate.create(publicKey(bob))); + expect(SignaturePredicate.fromPredicate(predicate).publicKey).toEqual(publicKey(bob)); + }); + }); +}); From d48dd0af2dcf20245e7ce8ae332b2222ad061375 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 13:48:45 +0200 Subject: [PATCH 02/25] Verify and inspect document lineage tokens `verify` and `inspect` now recognise lineage tokens by their token type and show them revision by revision: hash, signer, next producer, certification time and round. Every other token is handled as a timestamp, exactly as before. - verify runs the lineage verification (SDK checks with the lineage issuance policy, plus the chain rules) against the same trust base selection as for timestamps. - With --file or --hash, a lineage passes if any revision carries the digest; the output names the matching revisions and whether a later revision supersedes them. A digest no revision carries is a failure. - The signer of revision 0 is the issuer from the genesis reason; of each later revision, the key the previous revision passed to. - JSON output for a lineage has "tokenType": "lineage", a revisions array and matchingRevisions. Co-Authored-By: Claude Opus 5.5 --- README.md | 32 ++++- skills/unicity-proof/SKILL.md | 5 + src/cli.ts | 6 +- src/commands/inspect.ts | 11 +- src/commands/verify.ts | 37 +++-- src/lib/lineage/LineageVerification.ts | 90 +++++++++--- src/output.ts | 190 +++++++++++++++++++++++++ tests/unit/LineageCommandsTest.ts | 172 ++++++++++++++++++++++ 8 files changed, 509 insertions(+), 34 deletions(-) create mode 100644 tests/unit/LineageCommandsTest.ts diff --git a/README.md b/README.md index 5af087c..7a213bf 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,35 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type and revision, which is what makes the origin "accepted"; the salt is random, so the token id cannot be predicted before the genesis is certified. - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. - The state mask of each step is derived from the producer's key and the spent state, so if the command is interrupted after certification, running the same command again with the same file, key, digest and recipient recovers the same revision. -- Network options behave as for `stamp`. `verify` and `inspect` do not yet understand lineage tokens. +- Network options behave as for `stamp`. + +`verify` and `inspect` recognise lineage tokens by their token type and list every revision with its hash, signer, next producer and certification time: + +```bash +unicity-proof verify doc.lineage # is this a valid lineage? +unicity-proof verify doc.lineage --file doc.pdf # ...and which revision is this file? +``` + +``` +Status OK (inclusion proofs, consensus signatures, issuer signature and revision chain verified against the bundled testnet2 trust base) +Trust base bundled testnet2 pin +Expected hash matches revision 1; superseded by revision 2 +Token type document lineage +Network testnet2 (4) +Token id 5394db437e25b271272701e70e3f211ab4be2449fbe5b5d33664afa630b92357 +Issuer 031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f +Revisions 3 +Next producer 034bf90f6fb27ac089cd5649adf2cf28c8d9711c66e5191cbceef04a2b7c85a368 + +Revision 0 SHA-256 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 + Signed by 031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f + Passes to 034bf90f6fb27ac089cd5649adf2cf28c8d9711c66e5191cbceef04a2b7c85a368 + Certified at 2026-11-05T11:45:48Z (reference time 1793879148) + Round 184233 (round timestamp 1793879149, epoch 1) +… +``` + +With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision. In `--json` output a lineage has `"tokenType": "lineage"`, a `revisions` array and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, auxiliary data])`. Verification additionally requires the indices to increase by one and the reference times not to decrease along the chain. @@ -164,7 +192,7 @@ The `Trust base` line says which root of trust produced that verdict — `bundle unicity-proof inspect document.cbor ``` -Prints the same fields as `verify` without checking anything, under an `UNVERIFIED` banner. Useful for looking at tokens from other networks or other token types. +Prints the same fields as `verify` without checking anything, under an `UNVERIFIED` banner. Useful for looking at tokens from other networks or other token types. A lineage token is shown revision by revision, as by `verify`. ### Scripting diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index 99a4490..fbeab23 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -23,6 +23,11 @@ Then read `Expected hash matches`. Without `--file` or `--hash` that line tells you the proof was never tied to anything — a bare `Status OK` on its own establishes nothing about the file in front of you. +A document lineage token (from `stamp-revision`, `Token type document lineage`) +holds several revisions. With `--file` it passes if **any** revision carries the +file's hash, so read the `Expected hash` line in full: `matches revision 1; +superseded by revision 2` means the file is a genuine but outdated revision. + Also read the `Trust base` line. A verdict is only as good as the root of trust behind it, and `OK` against someone else's trust base means nothing. diff --git a/src/cli.ts b/src/cli.ts index 57da145..ae1bfd3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -99,10 +99,10 @@ program program .command('verify') - .description('verify a timestamp token offline and print what it proves') + .description('verify a timestamp or document lineage token offline and print what it proves') .argument('', 'token file, or "-" for stdin; raw CBOR or hex text') - .option('--hash ', 'assert the token is for this digest') - .option('--file ', 'assert the token is for this file, hashed locally') + .option('--hash ', 'assert the token is for this digest (for a lineage: one of its revisions)') + .option('--file ', 'assert the token is for this file, hashed locally (for a lineage: one of its revisions)') .option('--network ', "use this network's bundled trust base instead of the one matching the token") .option('--trust-base ', 'use this trust base file; or UNICITY_TRUST_BASE') .action(async (file: string, flags: IVerifyFlags) => { diff --git a/src/commands/inspect.ts b/src/commands/inspect.ts index 22c3494..cf3446c 100644 --- a/src/commands/inspect.ts +++ b/src/commands/inspect.ts @@ -1,11 +1,13 @@ import { ICommandContext } from './context.js'; import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; import { EXIT_OK } from '../errors.js'; +import { describeLineage } from '../lib/lineage/LineageVerification.js'; import { describeToken } from '../lib/TimestampVerification.js'; -import { inspectJson, inspectText, toJsonLine } from '../output.js'; +import { inspectJson, inspectText, lineageInspectJson, lineageInspectText, toJsonLine } from '../output.js'; /** - * `inspect`: decode and print a token without verifying anything. + * `inspect`: decode and print a token without verifying anything. Document lineage + * tokens are shown revision by revision; every other type as a timestamp. * * @param {string} file Token path, or `-` for stdin. * @param {ICommandContext} context Streams. @@ -16,6 +18,11 @@ export async function runInspect(file: string, context: ICommandContext): Promis if (decoded.token === null) { return reportNotAToken(context, 'inspect', decoded.error); } + const lineage = describeLineage(decoded.token); + if (lineage.tokenTypeIsLineage) { + context.stdout.write(context.json ? toJsonLine(lineageInspectJson(lineage)) : `${lineageInspectText(lineage)}\n`); + return EXIT_OK; + } const description = describeToken(decoded.token); context.stdout.write(context.json ? toJsonLine(inspectJson(description)) : `${inspectText(description)}\n`); return EXIT_OK; diff --git a/src/commands/verify.ts b/src/commands/verify.ts index e263100..012eac5 100644 --- a/src/commands/verify.ts +++ b/src/commands/verify.ts @@ -2,6 +2,7 @@ import { ICommandContext } from './context.js'; import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; import { assertOneDigestSource, INetworkFlags, resolveDigest, resolveTrustBaseOverride } from '../config.js'; import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; +import { describeLineage, ILineageVerificationResult, verifyLineage } from '../lib/lineage/LineageVerification.js'; import { bundledTrustBase, ITrustBaseChoice, networkNameForId, TrustBaseSource } from '../lib/networks.js'; import { describeToken, @@ -9,7 +10,7 @@ import { verificationFailure, verify, } from '../lib/TimestampVerification.js'; -import { toJsonLine, verifyJson, verifyText } from '../output.js'; +import { lineageVerifyJson, lineageVerifyText, toJsonLine, verifyJson, verifyText } from '../output.js'; export interface IVerifyFlags extends INetworkFlags { readonly file?: string; @@ -25,9 +26,21 @@ function report( return result.status === 'OK' ? EXIT_OK : EXIT_VERIFICATION_FAILED; } +function reportLineage( + context: ICommandContext, + result: ILineageVerificationResult, + source: TrustBaseSource | null, +): number { + context.stdout.write( + context.json ? toJsonLine(lineageVerifyJson(result, source)) : `${lineageVerifyText(result, source)}\n`, + ); + return result.status === 'OK' ? EXIT_OK : EXIT_VERIFICATION_FAILED; +} + /** - * `verify`: check a token offline and report what it proves. Cheap failures - * come first; the document is hashed only once the token and trust base are in hand. + * `verify`: check a token offline and report what it proves. A document lineage + * token is verified as a lineage, and an expected digest is looked for among its + * revisions; any other token is verified as a timestamp. Cheap failures come first; the document is hashed only once the token and trust base are in hand. * * @param {string} file Token path, or `-` for stdin. * @param {IVerifyFlags} flags Command flags. @@ -45,16 +58,21 @@ export async function runVerify(file: string, flags: IVerifyFlags, context: ICom return reportNotAToken(context, 'verify', decoded.error); } const token = decoded.token; + const lineage = describeLineage(token); let choice = await resolveTrustBaseOverride(flags); if (choice === undefined) { const name = networkNameForId(token.networkId.id); if (name === undefined) { - return report( - context, - verificationFailure(describeToken(token), `unknown network id ${token.networkId.id}; pass --trust-base`), - null, - ); + const reason = `unknown network id ${token.networkId.id}; pass --trust-base`; + if (lineage.tokenTypeIsLineage) { + return reportLineage( + context, + { description: lineage, details: null, matchingRevisions: null, reason, status: 'FAIL' }, + null, + ); + } + return report(context, verificationFailure(describeToken(token), reason), null); } choice = { source: { kind: 'bundled', network: name }, @@ -63,5 +81,8 @@ export async function runVerify(file: string, flags: IVerifyFlags, context: ICom } const expectedDigest = await resolveDigest(flags.hash, flags.file, '--hash'); + if (lineage.tokenTypeIsLineage) { + return reportLineage(context, await verifyLineage(token, choice.trustBase, { expectedDigest }), choice.source); + } return report(context, await verify(token, choice.trustBase, { expectedDigest }), choice.source); } diff --git a/src/lib/lineage/LineageVerification.ts b/src/lib/lineage/LineageVerification.ts index faf7310..cfc70df 100644 --- a/src/lib/lineage/LineageVerification.ts +++ b/src/lib/lineage/LineageVerification.ts @@ -3,6 +3,7 @@ import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predic import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import { PredicateVerifierService } from '@unicitylabs/state-transition-sdk/lib/predicate/verification/PredicateVerifierService.js'; import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; +import { CertifiedTransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedTransferTransaction.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { TokenType } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenType.js'; import type { IMintJustificationVerifier } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/IMintJustificationVerifier.js'; @@ -126,12 +127,22 @@ export function createLineageVerificationContext(trustBase: RootTrustBase): Veri /** One revision of a lineage as read off the token. */ export interface ILineageRevisionDescription { readonly digest: Uint8Array | null; + readonly epoch: bigint; readonly error: string | null; readonly index: bigint | null; /** Public key of the `P_sig` the revision names as producer of the next one; null for any other predicate. */ readonly nextProducer: Uint8Array | null; /** Unix seconds. */ readonly referenceTime: bigint; + readonly roundNumber: bigint; + /** Unix seconds; consensus-signed upper bound of the reference time. */ + readonly roundTimestamp: bigint; + /** + * Who signed the revision as claimed by the token: the issuer named in the genesis + * reason for revision 0, otherwise the producer the previous revision named. Null + * when that is not a readable `P_sig` key. + */ + readonly signer: Uint8Array | null; } /** What a lineage token claims, without verifying it. */ @@ -151,19 +162,26 @@ function signaturePredicateKey(predicate: EncodedPredicate): Uint8Array | null { } function describeRevision( - data: Uint8Array | null, - recipient: EncodedPredicate, - referenceTime: bigint, + transaction: CertifiedMintTransaction | CertifiedTransferTransaction, + signer: Uint8Array | null, ): ILineageRevisionDescription { - const nextProducer = signaturePredicateKey(recipient); - if (data === null) { - return { digest: null, error: 'no revision payload', index: null, nextProducer, referenceTime }; + const certificate = transaction.inclusionProof.unicityCertificate; + const common = { + epoch: certificate.unicitySeal.epoch, + nextProducer: signaturePredicateKey(transaction.recipient), + referenceTime: transaction.referenceTime, + roundNumber: certificate.inputRecord.roundNumber, + roundTimestamp: certificate.inputRecord.timestamp, + signer, + }; + if (transaction.data === null) { + return { ...common, digest: null, error: 'no revision payload', index: null }; } try { - const revision = LineageRevision.fromCBOR(data); - return { digest: revision.digest, error: null, index: revision.index, nextProducer, referenceTime }; + const revision = LineageRevision.fromCBOR(transaction.data); + return { ...common, digest: revision.digest, error: null, index: revision.index }; } catch (error) { - return { digest: null, error: errorMessage(error), index: null, nextProducer, referenceTime }; + return { ...common, digest: null, error: errorMessage(error), index: null }; } } @@ -182,23 +200,32 @@ export function describeLineage(token: Token): ILineageDescription { issuer = null; } } + const revisions = [describeRevision(token.genesis, issuer)]; + for (const transaction of token.transactions) { + revisions.push(describeRevision(transaction, revisions[revisions.length - 1].nextProducer)); + } return { issuer, - revisions: [ - describeRevision(token.genesis.data, token.genesis.recipient, token.genesis.referenceTime), - ...token.transactions.map((transaction) => - describeRevision(transaction.data, transaction.recipient, transaction.referenceTime), - ), - ], + revisions, token, tokenTypeIsLineage: areUint8ArraysEqual(token.type.bytes, LINEAGE_TOKEN_TYPE.bytes), }; } +export interface ILineageVerifyOptions { + /** Digest one of the revisions is expected to carry. */ + readonly expectedDigest?: Uint8Array; +} + export interface ILineageVerificationResult { readonly description: ILineageDescription; /** SDK result tree, or null when it was not reached. */ readonly details: Result | null; + /** + * Positions of the revisions that carry the expected digest; null when no digest + * was given or the comparison was not reached. Empty means a mismatch. + */ + readonly matchingRevisions: readonly number[] | null; readonly reason: string | null; readonly status: 'FAIL' | 'OK'; } @@ -252,18 +279,25 @@ function deepestMessage(result: VerificationResult): string { /** * Verify a document lineage token offline: the SDK's full token verification with - * the lineage issuance policy, then the chain rules. + * the lineage issuance policy, then the chain rules, then, if asked, whether any + * revision carries the expected digest. * * @param {Token} token Token to verify. * @param {RootTrustBase} trustBase Trust base of the token's network. + * @param {ILineageVerifyOptions} options Expected digest. * @returns {Promise} Outcome. */ -export async function verifyLineage(token: Token, trustBase: RootTrustBase): Promise { +export async function verifyLineage( + token: Token, + trustBase: RootTrustBase, + options: ILineageVerifyOptions = {}, +): Promise { const description = describeLineage(token); if (!description.tokenTypeIsLineage) { return { description, details: null, + matchingRevisions: null, reason: `Not a document lineage token: token type ${HexConverter.encode(token.type.bytes)}.`, status: 'FAIL', }; @@ -272,6 +306,7 @@ export async function verifyLineage(token: Token, trustBase: RootTrustBase): Pro return { description, details: null, + matchingRevisions: null, reason: `The token is for network ${token.networkId.id} and the trust base for network ${trustBase.networkId.id}.`, status: 'FAIL', }; @@ -279,7 +314,24 @@ export async function verifyLineage(token: Token, trustBase: RootTrustBase): Pro const sdk = await token.verify(createLineageVerificationContext(trustBase)); const details = VerificationResult.fromResults('LineageTokenVerification', [sdk, chainRules(description)]); if (details.status !== VerificationStatus.OK) { - return { description, details, reason: deepestMessage(details), status: 'FAIL' }; + return { description, details, matchingRevisions: null, reason: deepestMessage(details), status: 'FAIL' }; + } + const expected = options.expectedDigest; + if (expected === undefined) { + return { description, details, matchingRevisions: null, reason: null, status: 'OK' }; + } + // Every digest decoded: the chain rules above fail on any revision that does not. + const matchingRevisions = description.revisions.flatMap((revision, position) => + revision.digest !== null && areUint8ArraysEqual(revision.digest, expected) ? [position] : [], + ); + if (matchingRevisions.length === 0) { + return { + description, + details, + matchingRevisions, + reason: 'Hash mismatch: no revision of the lineage certifies this digest.', + status: 'FAIL', + }; } - return { description, details, reason: null, status: 'OK' }; + return { description, details, matchingRevisions, reason: null, status: 'OK' }; } diff --git a/src/output.ts b/src/output.ts index b511020..461c568 100644 --- a/src/output.ts +++ b/src/output.ts @@ -1,6 +1,11 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; +import { + ILineageDescription, + ILineageRevisionDescription, + ILineageVerificationResult, +} from './lib/lineage/LineageVerification.js'; import { networkNameForId, TrustBaseSource } from './lib/networks.js'; import { ITimestampDescription, ITimestampVerificationResult } from './lib/TimestampVerification.js'; @@ -453,3 +458,188 @@ export function revisionRecoveryLines(bytes: Uint8Array): string { '', ].join('\n'); } + +export interface ILineageRevisionJson { + readonly error: string | null; + readonly hash: { readonly algorithm: 'SHA-256'; readonly digest: string } | null; + /** The index the revision claims, as a decimal string; null when it does not decode. */ + readonly index: string | null; + readonly nextProducer: string | null; + readonly referenceTime: string; + readonly referenceTimeIso: string | null; + readonly round: { readonly epoch: string; readonly number: string; readonly timestamp: string }; + readonly signer: string | null; +} + +export interface ILineageDescriptionJson { + readonly issuer: string | null; + readonly network: INetworkJson; + /** Who may sign the next revision: the latest revision's next producer. */ + readonly nextProducer: string | null; + readonly revisions: ILineageRevisionJson[]; + readonly tokenId: string; + readonly tokenType: 'lineage'; +} + +export interface ILineageVerifyJson extends ILineageDescriptionJson { + readonly command: 'verify'; + readonly details: IResultJson | null; + readonly expectedHashMatches: boolean | null; + /** Positions of the revisions carrying the expected hash; null when not checked. */ + readonly matchingRevisions: readonly number[] | null; + readonly reason: string | null; + readonly status: 'FAIL' | 'OK'; + readonly trustBase: ITrustBaseJson | null; +} + +export interface ILineageInspectJson extends ILineageDescriptionJson { + readonly command: 'inspect'; + readonly verified: false; +} + +function keyLabel(key: Uint8Array | null, otherwise: string): string { + return key === null ? otherwise : HexConverter.encode(key); +} + +function latestNextProducer(description: ILineageDescription): Uint8Array | null { + return description.revisions.at(-1)?.nextProducer ?? null; +} + +function lineageRevisionLines(revision: ILineageRevisionDescription, position: number): string[] { + const claimed = + revision.index !== null && revision.index !== BigInt(position) ? ` (claims index ${revision.index})` : ''; + return [ + line( + `Revision ${position}`, + revision.digest === null + ? `unreadable (${revision.error ?? 'no revision payload'})` + : `SHA-256 ${HexConverter.encode(revision.digest)}${claimed}`, + ), + line(' Signed by', keyLabel(revision.signer, 'not a signature predicate key')), + line(' Passes to', keyLabel(revision.nextProducer, 'not a signature predicate')), + line(' Certified at', `${formatIso(revision.referenceTime)} (reference time ${revision.referenceTime})`), + line(' Round', `${revision.roundNumber} (round timestamp ${revision.roundTimestamp}, epoch ${revision.epoch})`), + ]; +} + +function lineageLines(description: ILineageDescription): string[] { + const lines = [ + line('Token type', 'document lineage'), + line('Network', networkLabel(description.token.networkId.id)), + line('Token id', HexConverter.encode(description.token.id.bytes)), + line('Issuer', keyLabel(description.issuer, 'unreadable genesis reason')), + line('Revisions', String(description.revisions.length)), + line('Next producer', keyLabel(latestNextProducer(description), 'not a signature predicate')), + ]; + description.revisions.forEach((revision, position) => { + lines.push('', ...lineageRevisionLines(revision, position)); + }); + return lines; +} + +// As for timestamps, relies on `verifyLineage` failing closed: an OK result with +// no comparison can only mean no digest was given. +function lineageExpectedHashLabel(result: ILineageVerificationResult): string { + const matching = result.matchingRevisions; + if (matching === null) { + return result.status === 'OK' + ? 'not checked; pass --file or --hash to find your document in the lineage' + : 'not checked; verification failed'; + } + const latest = result.description.revisions.length - 1; + const last = matching.at(-1); + if (last === undefined) { + return 'differs from every revision'; + } + const which = `matches revision${matching.length > 1 ? 's' : ''} ${matching.join(', ')}`; + return last === latest ? `${which} (the latest)` : `${which}; superseded by revision ${latest}`; +} + +/** + * @param {ILineageVerificationResult} result Lineage verification outcome. + * @param {TrustBaseSource|null} source Root of trust the verdict was produced against. + * @returns {string} Human summary of a lineage verification, with the SDK result tree on failure. + */ +export function lineageVerifyText(result: ILineageVerificationResult, source: TrustBaseSource | null): string { + const against = source?.kind === 'bundled' ? `the bundled ${source.network} trust base` : `${source?.path}`; + const lines = [ + line( + 'Status', + result.status === 'OK' + ? `OK (inclusion proofs, consensus signatures, issuer signature and revision chain verified against ${against})` + : `FAIL: ${result.reason ?? 'verification failed'}`, + ), + line('Trust base', trustBaseLabel(source)), + line('Expected hash', lineageExpectedHashLabel(result)), + ...lineageLines(result.description), + ]; + if (result.status !== 'OK' && result.details !== null) { + lines.push('', result.details.toString()); + } + return lines.join('\n'); +} + +/** + * @param {ILineageDescription} description Fields read off a lineage token. + * @returns {string} Human dump of a lineage token with no verification performed. + */ +export function lineageInspectText(description: ILineageDescription): string { + return [ + line('UNVERIFIED', 'fields read from the token; nothing below has been checked'), + ...lineageLines(description), + ].join('\n'); +} + +function lineageRevisionJson(revision: ILineageRevisionDescription): ILineageRevisionJson { + return { + error: revision.error, + hash: revision.digest === null ? null : { algorithm: 'SHA-256', digest: HexConverter.encode(revision.digest) }, + index: revision.index === null ? null : revision.index.toString(), + nextProducer: revision.nextProducer === null ? null : HexConverter.encode(revision.nextProducer), + referenceTime: revision.referenceTime.toString(), + referenceTimeIso: toIso(revision.referenceTime), + round: { + epoch: revision.epoch.toString(), + number: revision.roundNumber.toString(), + timestamp: revision.roundTimestamp.toString(), + }, + signer: revision.signer === null ? null : HexConverter.encode(revision.signer), + }; +} + +/** + * @param {ILineageDescription} description Fields read off a lineage token. + * @returns {ILineageDescriptionJson} JSON-safe fields; big integers as decimal strings. + */ +export function lineageDescriptionJson(description: ILineageDescription): ILineageDescriptionJson { + const networkId = description.token.networkId.id; + const nextProducer = latestNextProducer(description); + return { + issuer: description.issuer === null ? null : HexConverter.encode(description.issuer), + network: { id: networkId, name: networkName(networkId) }, + nextProducer: nextProducer === null ? null : HexConverter.encode(nextProducer), + revisions: description.revisions.map((revision) => lineageRevisionJson(revision)), + tokenId: HexConverter.encode(description.token.id.bytes), + tokenType: 'lineage', + }; +} + +export function lineageVerifyJson( + result: ILineageVerificationResult, + source: TrustBaseSource | null, +): ILineageVerifyJson { + return { + command: 'verify', + expectedHashMatches: result.matchingRevisions === null ? null : result.matchingRevisions.length > 0, + matchingRevisions: result.matchingRevisions, + reason: result.reason, + status: result.status, + ...lineageDescriptionJson(result.description), + details: result.details ? resultTreeJson(result.details) : null, + trustBase: trustBaseJson(source), + }; +} + +export function lineageInspectJson(description: ILineageDescription): ILineageInspectJson { + return { command: 'inspect', verified: false, ...lineageDescriptionJson(description) }; +} diff --git a/tests/unit/LineageCommandsTest.ts b/tests/unit/LineageCommandsTest.ts new file mode 100644 index 0000000..a800ca2 --- /dev/null +++ b/tests/unit/LineageCommandsTest.ts @@ -0,0 +1,172 @@ +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { runInspect } from '../../src/commands/inspect.js'; +import { runVerify } from '../../src/commands/verify.js'; +import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; +import { appendRevision, createLineage } from '../../src/lib/lineage/LineageClient.js'; +import { testContext } from '../support/context.js'; +import { + OTHER_DIGEST, + OTHER_DIGEST_HEX, + tempDir, + TEST_DIGEST, + TEST_DIGEST_HEX, + TEST_PRIVATE_KEY, + TEST_PUBLIC_KEY_HEX, +} from '../support/fixtures.js'; +import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; + +const THIRD_DIGEST_HEX = 'ab'.repeat(32); + +describe('verify and inspect on a document lineage', () => { + const aggregator = TestAggregatorClient.create(); + const client = new StateTransitionClient(aggregator); + const fast = { pollIntervalMs: 10, timeoutMs: 2_000 }; + const bob = SigningService.generatePrivateKey(); + const bobPublicHex = HexConverter.encode(new SigningService(bob).publicKey); + let directory: string; + let tokenFile: string; + let trustBaseFile: string; + let token: Token; + + beforeAll(async () => { + directory = await tempDir('proof-cli-lineage-'); + // Revision 0 by the issuer naming bob, then revision 1 by bob naming the issuer, then 2 by the issuer naming bob. + const genesis = await createLineage( + client, + aggregator.rootTrustBase, + TEST_DIGEST, + TEST_PRIVATE_KEY, + new SigningService(bob).publicKey, + fast, + ); + const first = await appendRevision( + client, + aggregator.rootTrustBase, + genesis, + OTHER_DIGEST, + bob, + HexConverter.decode(TEST_PUBLIC_KEY_HEX), + fast, + ); + token = await appendRevision( + client, + aggregator.rootTrustBase, + first, + HexConverter.decode(THIRD_DIGEST_HEX), + TEST_PRIVATE_KEY, + new SigningService(bob).publicKey, + fast, + ); + tokenFile = path.join(directory, 'doc.lineage'); + await writeFile(tokenFile, token.toCBOR()); + trustBaseFile = path.join(directory, 'trust-base.json'); + await writeFile(trustBaseFile, JSON.stringify(aggregator.rootTrustBase.toJSON())); + }); + + it('verifies the lineage and lists every revision', async () => { + const sink = testContext(); + expect(await runVerify(tokenFile, { trustBase: trustBaseFile }, sink.context)).toBe(EXIT_OK); + const out = sink.stdout(); + expect(out).toMatch( + /^Status {9}OK {2}\(inclusion proofs, consensus signatures, issuer signature and revision chain/, + ); + expect(out).toContain('Token type document lineage\n'); + expect(out).toContain(`Issuer ${TEST_PUBLIC_KEY_HEX}\n`); + expect(out).toContain('Revisions 3\n'); + expect(out).toContain(`Next producer ${bobPublicHex}\n`); + expect(out).toContain(`Revision 0 SHA-256 ${TEST_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); + expect(out).toContain(`Revision 1 SHA-256 ${OTHER_DIGEST_HEX}\n Signed by ${bobPublicHex}\n`); + expect(out).toContain(`Revision 2 SHA-256 ${THIRD_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); + expect(out).toContain(` Passes to ${bobPublicHex}\n Certified at`); + expect(out).toContain('Expected hash not checked; pass --file or --hash'); + }); + + it('finds an expected hash among the revisions', async () => { + const latest = testContext(); + await runVerify(tokenFile, { hash: THIRD_DIGEST_HEX, trustBase: trustBaseFile }, latest.context); + expect(latest.stdout()).toContain('Expected hash matches revision 2 (the latest)\n'); + + const older = testContext({ json: true }); + expect(await runVerify(tokenFile, { hash: OTHER_DIGEST_HEX, trustBase: trustBaseFile }, older.context)).toBe( + EXIT_OK, + ); + expect(older.json()).toMatchObject({ + command: 'verify', + expectedHashMatches: true, + matchingRevisions: [1], + status: 'OK', + tokenType: 'lineage', + }); + + const text = testContext(); + await runVerify(tokenFile, { hash: OTHER_DIGEST_HEX, trustBase: trustBaseFile }, text.context); + expect(text.stdout()).toContain('Expected hash matches revision 1; superseded by revision 2\n'); + }); + + it('fails on a hash no revision carries', async () => { + const sink = testContext({ json: true }); + expect(await runVerify(tokenFile, { hash: 'cd'.repeat(32), trustBase: trustBaseFile }, sink.context)).toBe( + EXIT_VERIFICATION_FAILED, + ); + expect(sink.json()).toMatchObject({ + expectedHashMatches: false, + matchingRevisions: [], + reason: 'Hash mismatch: no revision of the lineage certifies this digest.', + status: 'FAIL', + }); + }); + + it('fails against the wrong trust base', async () => { + const sink = testContext({ json: true }); + expect(await runVerify(tokenFile, { network: 'testnet2' }, sink.context)).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.json()).toMatchObject({ + matchingRevisions: null, + reason: 'The token is for network 3 and the trust base for network 4.', + status: 'FAIL', + trustBase: { bundledNetwork: 'testnet2', source: 'bundled' }, + }); + }); + + it('reports a network it cannot place as a lineage failure', async () => { + const sink = testContext({ json: true }); + expect(await runVerify(tokenFile, {}, sink.context)).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.json()).toMatchObject({ + reason: 'unknown network id 3; pass --trust-base', + status: 'FAIL', + tokenType: 'lineage', + trustBase: null, + }); + }); + + it('inspects the lineage without verifying it', async () => { + const text = testContext(); + expect(await runInspect(tokenFile, text.context)).toBe(EXIT_OK); + expect(text.stdout()).toMatch(/^UNVERIFIED {5}/); + expect(text.stdout()).toContain('Revisions 3\n'); + + const json = testContext({ json: true }); + expect(await runInspect(tokenFile, json.context)).toBe(EXIT_OK); + const output = json.json() as { revisions: { index: string; signer: string }[] }; + expect(output).toMatchObject({ + command: 'inspect', + issuer: TEST_PUBLIC_KEY_HEX, + network: { id: 3 }, + nextProducer: bobPublicHex, + tokenId: HexConverter.encode(token.id.bytes), + tokenType: 'lineage', + verified: false, + }); + expect(output.revisions.map((revision) => [revision.index, revision.signer])).toEqual([ + ['0', TEST_PUBLIC_KEY_HEX], + ['1', bobPublicHex], + ['2', TEST_PUBLIC_KEY_HEX], + ]); + }); +}); From b42a6271433130a2f883d5c717eb5352d28697f8 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 15:47:40 +0200 Subject: [PATCH 03/25] Finalize a document lineage with stamp-revision --finalize `stamp-revision --finalize` certifies the final revision of a document as a seal and burns the lineage token, as designed in issue #13: the revision's auxData is b_seal = CBOR["seal", i, H(doc_i)] and its recipient is P_burn(H(b_seal)), so no successor can ever be certified and the burn commits to the final digest. - Exactly one of --recipient-key, --recipient-key-file and --finalize is required; any other combination is a usage error. - Appending to a finalized lineage fails before contacting the gateway. On a new lineage, --finalize mints revision 0 as a seal. - Verification requires a revision to be burned exactly when it is a seal, with the burn reason committing to the seal payload, and a seal to be the last revision. - verify and inspect mark the seal "(final)" and report the lineage as finalized; JSON output gains "finalized" and per-revision "sealed", and stamp-revision reports "finalized" with a null nextProducer. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 +- skills/unicity-proof/SKILL.md | 2 + src/cli.ts | 6 +- src/config.ts | 46 +++++++-- src/lib/lineage/LineageClient.ts | 81 ++++++++++++--- src/lib/lineage/LineagePayload.ts | 66 +++++++++--- src/lib/lineage/LineageVerification.ts | 74 +++++++++++--- src/output.ts | 49 +++++++-- tests/unit/LineageCommandsTest.ts | 38 +++++++ tests/unit/StampRevisionTest.ts | 82 ++++++++++++++- tests/unit/lib/LineageTest.ts | 133 +++++++++++++++++++++++++ 11 files changed, 519 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 7a213bf..a0cdef6 100644 --- a/README.md +++ b/README.md @@ -116,18 +116,21 @@ The signer's compressed public key is printed on every `stamp` and `verify`, as `stamp-revision` links successive revisions of a document in one *lineage token* (design: [#13](https://github.com/unicitynetwork/proof-cli/issues/13#issuecomment-6440959902)). -Each call certifies one revision and names who may produce the next: +Each call certifies one revision and either names who may produce the next, or finalizes the document: ```bash # Revision 0: creates doc.lineage, signed by alice, and names bob as the next producer. unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file alice.key --recipient-key # Revision 1: only bob's key can append; bob names carol (key read from a file holding 66 hex characters). unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file bob.key --recipient-key-file carol.pub +# Revision 2: carol finalizes the document; no revision can follow. +unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file carol.key --finalize ``` -- Exactly one of `` and `--file`, and exactly one of `--recipient-key` and `--recipient-key-file`, is required. `--token-file` and `--key-file` are always required; `UNICITY_PRIVATE_KEY` is not consulted. +- Exactly one of `` and `--file`, and exactly one of `--recipient-key`, `--recipient-key-file` and `--finalize`, is required. `--token-file` and `--key-file` are always required; `UNICITY_PRIVATE_KEY` is not consulted. - If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type and revision, which is what makes the origin "accepted"; the salt is random, so the token id cannot be predicted before the genesis is certified. - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. +- `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - The state mask of each step is derived from the producer's key and the spent state, so if the command is interrupted after certification, running the same command again with the same file, key, digest and recipient recovers the same revision. - Network options behave as for `stamp`. @@ -157,9 +160,9 @@ Revision 0 SHA-256 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730433629 … ``` -With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision. In `--json` output a lineage has `"tokenType": "lineage"`, a `revisions` array and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. +With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision, or `none; the lineage is finalized` after a seal, which is marked `(final)`. In `--json` output a lineage has `"tokenType": "lineage"`, `finalized`, a `revisions` array (each with `sealed`) and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. -Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, auxiliary data])`. Verification additionally requires the indices to increase by one and the reference times not to decrease along the chain. +Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer, or `CBOR["seal", i, SHA-256(doc_i)]` on the final revision, whose recipient is then the burn predicate with reason `SHA-256(auxiliary data)`; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, auxiliary data])`. Verification additionally requires the indices to increase by one, the reference times not to decrease along the chain, and a revision to be burned exactly when it is a seal, with the burn reason as above. ### Verify diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index fbeab23..92c5430 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -27,6 +27,8 @@ A document lineage token (from `stamp-revision`, `Token type document lineage`) holds several revisions. With `--file` it passes if **any** revision carries the file's hash, so read the `Expected hash` line in full: `matches revision 1; superseded by revision 2` means the file is a genuine but outdated revision. +`matches revision 2 (the final)` means the lineage was finalized with that +revision (`--finalize`); no later revision can exist. Also read the `Trust base` line. A verdict is only as good as the root of trust behind it, and `OK` against someone else's trust base means nothing. diff --git a/src/cli.ts b/src/cli.ts index ae1bfd3..e407be7 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -80,13 +80,17 @@ program program .command('stamp-revision') - .description('certify a document revision, creating a lineage token or appending to an existing one') + .description( + 'certify a document revision, creating a lineage token or appending to an existing one; ' + + 'name the next producer, or finalize', + ) .argument('[sha256-hex]', 'digest of the revision; alternatively use --file') .option('--file ', 'hash this file locally instead of passing a digest') .requiredOption('--token-file ', 'lineage token; created for an initial revision, otherwise appended to') .requiredOption('--key-file ', 'secp256k1 private key (64 hex) that signs this revision') .option('--recipient-key ', "compressed secp256k1 public key (66 hex) of the next revision's producer") .option('--recipient-key-file ', "file holding the next producer's public key; alternative to --recipient-key") + .option('--finalize', 'make this the final revision: seal it and burn the token, so no revision can follow') .option('--network ', 'mainnet or testnet2; or UNICITY_NETWORK (default mainnet)') .option('--gateway ', 'override the gateway URL; or UNICITY_GATEWAY_URL') .option('--api-key ', 'gateway API key; or UNICITY_API_KEY') diff --git a/src/config.ts b/src/config.ts index 5272f7d..a0d3c4f 100644 --- a/src/config.ts +++ b/src/config.ts @@ -445,6 +445,7 @@ export interface IStampRevisionFlags extends INetworkFlags { readonly allowInsecure?: boolean; readonly apiKey?: string; readonly file?: string; + readonly finalize?: boolean; readonly keyFile?: string; readonly recipientKey?: string; readonly recipientKeyFile?: string; @@ -459,8 +460,11 @@ export interface IStampRevisionConfig { readonly network: ITimestampNetwork; /** Signs the new revision: the genesis reason for a new lineage, the transfer otherwise. */ readonly privateKey: Uint8Array; - /** Compressed public key of whoever produces the following revision. */ - readonly recipientKey: Uint8Array; + /** + * Compressed public key of whoever produces the following revision; null to + * finalize, sealing this revision as the last one. + */ + readonly recipientKey: Uint8Array | null; readonly timeoutMs: number; /** Bytes of the existing token file, or null when a new lineage is to be created. */ readonly tokenBytes: Uint8Array | null; @@ -490,23 +494,43 @@ export function parsePublicKey(input: string, source = 'Recipient key'): Uint8Ar return key; } -async function resolveRecipientKey(flags: IStampRevisionFlags): Promise { - if (flags.recipientKey !== undefined && flags.recipientKeyFile !== undefined) { - throw usageError('Pass either --recipient-key or --recipient-key-file, not both.'); +/** + * Exactly one of `--recipient-key`, `--recipient-key-file` and `--finalize`. + * + * @param {IStampRevisionFlags} flags Command-line flags. + * @returns {Promise} The next producer's key, or null to finalize. + */ +async function resolveRecipientKey(flags: IStampRevisionFlags): Promise { + const given = [ + flags.recipientKey !== undefined ? '--recipient-key' : null, + flags.recipientKeyFile !== undefined ? '--recipient-key-file' : null, + flags.finalize === true ? '--finalize' : null, + ].filter((option) => option !== null); + if (given.length > 1) { + throw usageError( + `Pass only one of --recipient-key, --recipient-key-file and --finalize; got ${given.join(' and ')}.`, + ); + } + if (given.length === 0) { + throw usageError( + 'Name the producer of the next revision with --recipient-key or --recipient-key-file, ' + + 'or pass --finalize to make this the final revision.', + ); + } + if (flags.finalize === true) { + return null; } if (flags.recipientKey !== undefined) { return parsePublicKey(flags.recipientKey, '--recipient-key'); } - if (flags.recipientKeyFile === undefined) { - throw usageError('Name the producer of the next revision: pass --recipient-key or --recipient-key-file.'); - } + const recipientKeyFile = flags.recipientKeyFile as string; let contents: string; try { - contents = await readFile(flags.recipientKeyFile, 'utf8'); + contents = await readFile(recipientKeyFile, 'utf8'); } catch (error) { - throw usageError(`Cannot read recipient key file ${flags.recipientKeyFile}.`, { cause: error }); + throw usageError(`Cannot read recipient key file ${recipientKeyFile}.`, { cause: error }); } - return parsePublicKey(contents, `Recipient key file ${flags.recipientKeyFile}`); + return parsePublicKey(contents, `Recipient key file ${recipientKeyFile}`); } /** diff --git a/src/lib/lineage/LineageClient.ts b/src/lib/lineage/LineageClient.ts index 1465c5b..e59ed57 100644 --- a/src/lib/lineage/LineageClient.ts +++ b/src/lib/lineage/LineageClient.ts @@ -3,6 +3,7 @@ import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/Cer import { DataHasher } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasher.js'; import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; import { SignaturePredicateUnlockScript } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicateUnlockScript.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; @@ -15,7 +16,13 @@ import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/Tok import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; -import { LINEAGE_TAG, LINEAGE_TOKEN_TYPE, LineageGenesisReason, LineageRevision } from './LineagePayload.js'; +import { + LINEAGE_TAG, + LINEAGE_TOKEN_TYPE, + LineageGenesisReason, + LineageRevision, + sealPredicate, +} from './LineagePayload.js'; import { createLineageVerificationContext, verifyLineage } from './LineageVerification.js'; import { ICertifyOptions, certifyMintTransaction, certifyTransaction } from '../TimestampClient.js'; @@ -23,8 +30,11 @@ import { ICertifyOptions, certifyMintTransaction, certifyTransaction } from '../ export class LineageError extends Error { public constructor( message: string, - /** `INVALID_TOKEN`: the token does not verify as a lineage; `WRONG_KEY`: the key cannot append to it. */ - public readonly code: 'INVALID_TOKEN' | 'WRONG_KEY', + /** + * `INVALID_TOKEN`: the token does not verify as a lineage; `WRONG_KEY`: the key + * cannot append to it; `FINALIZED`: the lineage is sealed and nothing can. + */ + public readonly code: 'FINALIZED' | 'INVALID_TOKEN' | 'WRONG_KEY', options?: ErrorOptions, ) { super(message, options); @@ -46,6 +56,22 @@ export function currentProducerKey(token: Token): Uint8Array | null { } } +/** + * Whether the token's latest state is locked to the burn predicate, which for a + * valid lineage means its latest revision is a seal. + * + * @param {Token} token Lineage token. + * @returns {boolean} True when no revision can follow. + */ +export function isFinalized(token: Token): boolean { + try { + BurnPredicate.fromPredicate(token.latestTransaction.recipient); + return true; + } catch { + return false; + } +} + /** * State mask of a version step, `x = PRF(k, h)`: derived from the producer's * private key and the state being spent rather than drawn at random. Re-running @@ -72,9 +98,35 @@ export async function deriveStateMask(privateKey: Uint8Array, token: Token): Pro return StateMask.fromBytes(hash.data); } +/** + * Payload and recipient of a revision: to the next producer's `P_sig`, or, when + * there is none, sealed and burned, so that no further revision can follow. + * + * @param {bigint} index Revision index. + * @param {Uint8Array} digest 32-byte SHA-256 digest of the revision. + * @param {Uint8Array|null} nextProducer Next producer's public key; null to finalize. + * @returns {Promise<{auxData: Uint8Array, recipient: SignaturePredicate | BurnPredicate}>} Payload bytes and recipient. + */ +async function revisionStep( + index: bigint, + digest: Uint8Array, + nextProducer: Uint8Array | null, +): Promise<{ auxData: Uint8Array; recipient: SignaturePredicate | BurnPredicate }> { + if (nextProducer === null) { + const auxData = LineageRevision.create(index, digest, true).toCBOR(); + return { auxData, recipient: await sealPredicate(auxData) }; + } + return { + auxData: LineageRevision.create(index, digest).toCBOR(), + recipient: SignaturePredicate.create(nextProducer), + }; +} + /** * Create a lineage: mint revision 0, with the issuer's signature as the mint - * reason and the next producer's `P_sig` as recipient. + * reason and the next producer's `P_sig` as recipient. Without a next producer + * the lineage is finalized at once: revision 0 is a seal, minted to the burn + * predicate. * * The salt is random, so the token id stays unpredictable until the genesis is * certified and cannot be squatted. @@ -83,7 +135,7 @@ export async function deriveStateMask(privateKey: Uint8Array, token: Token): Pro * @param {RootTrustBase} trustBase Trust base of the network behind the client. * @param {Uint8Array} digest 32-byte SHA-256 digest of the initial revision. * @param {Uint8Array} issuerPrivateKey Issuer's private key; signs the genesis reason. - * @param {Uint8Array} nextProducer Compressed public key of whoever produces revision 1. + * @param {Uint8Array|null} nextProducer Compressed public key of whoever produces revision 1; null to finalize. * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. * @returns {Promise} Verified lineage token with no transfers. */ @@ -92,11 +144,10 @@ export async function createLineage( trustBase: RootTrustBase, digest: Uint8Array, issuerPrivateKey: Uint8Array, - nextProducer: Uint8Array, + nextProducer: Uint8Array | null, options: ICertifyOptions = {}, ): Promise { - const recipient = SignaturePredicate.create(nextProducer); - const auxData = LineageRevision.create(0n, digest).toCBOR(); + const { auxData, recipient } = await revisionStep(0n, digest, nextProducer); const salt = TokenSalt.generate(); const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); const reason = await LineageGenesisReason.sign( @@ -137,6 +188,9 @@ export async function assertCanAppend( 'INVALID_TOKEN', ); } + if (isFinalized(token)) { + throw new LineageError('The lineage is finalized; no revision can follow its sealed final revision.', 'FINALIZED'); + } const current = currentProducerKey(token); if (current === null) { throw new LineageError( @@ -155,14 +209,15 @@ export async function assertCanAppend( /** * Append the next revision: a transfer, signed under the `P_sig` the previous * revision named, whose auxiliary data is `[i, digest]` and whose recipient is the - * producer of revision `i + 1`. + * producer of revision `i + 1`; or, without a next producer, the seal + * `["seal", i, digest]`, burning the token. * * @param {StateTransitionClient} client Aggregator client. * @param {RootTrustBase} trustBase Trust base of the network behind the client. * @param {Token} token Existing lineage token. * @param {Uint8Array} digest 32-byte SHA-256 digest of the new revision. * @param {Uint8Array} producerPrivateKey Key named by the latest revision; signs the transfer. - * @param {Uint8Array} nextProducer Compressed public key of whoever produces the following revision. + * @param {Uint8Array|null} nextProducer Compressed public key of whoever produces the following revision; null to finalize. * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. * @returns {Promise} The token with the new revision appended. */ @@ -172,19 +227,19 @@ export async function appendRevision( token: Token, digest: Uint8Array, producerPrivateKey: Uint8Array, - nextProducer: Uint8Array, + nextProducer: Uint8Array | null, options: ICertifyOptions = {}, ): Promise { const signer = new SigningService(producerPrivateKey); await assertCanAppend(token, trustBase, signer.publicKey); - const recipient = SignaturePredicate.create(nextProducer); const index = BigInt(token.transactions.length + 1); + const { auxData, recipient } = await revisionStep(index, digest, nextProducer); const transaction = await TransferTransaction.create( token, recipient, await deriveStateMask(producerPrivateKey, token), - { data: LineageRevision.create(index, digest).toCBOR() }, + { data: auxData }, ); const certificationData = await CertificationData.fromTransaction( transaction, diff --git a/src/lib/lineage/LineagePayload.ts b/src/lib/lineage/LineagePayload.ts index 7fc4869..820baf4 100644 --- a/src/lib/lineage/LineagePayload.ts +++ b/src/lib/lineage/LineagePayload.ts @@ -3,6 +3,7 @@ import { DataHasher } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/Da import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js'; import { Signature } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/Signature.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; import { CborDeserializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborDeserializer.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; @@ -61,16 +62,30 @@ function assertCanonical(input: Uint8Array, reencoded: Uint8Array, what: string) } } +/** First element of a seal payload, marking the revision as final. */ +export const LINEAGE_SEAL_MARKER = 'seal'; + /** - * Auxiliary data of every lineage transaction, `CBOR[i, H(doc_i)]`: the revision - * index (0 at genesis, then one more per transfer) and the SHA-256 digest of that - * revision. The document itself is never stored. No previous digest is needed; - * linkage comes from the state hash chain. + * Auxiliary data of every lineage transaction: the revision index (0 at genesis, + * then one more per transfer) and the SHA-256 digest of that revision. The + * document itself is never stored. No previous digest is needed; linkage comes + * from the state hash chain. + * + * ``` + * CBOR[i, H(doc_i)] an ordinary revision + * CBOR["seal", i, H(doc_i)] the final revision (seal) + * ``` + * + * A seal is certified with the burn predicate `P_burn(H(b_seal))` as recipient, + * where `b_seal` is the seal payload itself, so no successor can ever exist and + * the burn commits to the final digest. */ export class LineageRevision { private constructor( public readonly index: bigint, private readonly _digest: Uint8Array, + /** Whether this is the final revision, after which the token is burned. */ + public readonly sealed: boolean, ) { this._digest = new Uint8Array(_digest); } @@ -83,15 +98,16 @@ export class LineageRevision { /** * @param {bigint} index Revision index. * @param {Uint8Array} digest 32-byte SHA-256 digest. + * @param {boolean} sealed Whether this is the final revision. * @returns {LineageRevision} Revision payload. * @throws {LineageFormatError} If the digest is not 32 bytes or the index is negative. */ - public static create(index: bigint, digest: Uint8Array): LineageRevision { + public static create(index: bigint, digest: Uint8Array, sealed = false): LineageRevision { if (index < 0n) { throw new LineageFormatError(`Revision index must not be negative, got ${index}.`); } assertDigest(digest); - return new LineageRevision(index, digest); + return new LineageRevision(index, digest, sealed); } /** @@ -104,28 +120,52 @@ export class LineageRevision { public static fromCBOR(bytes: Uint8Array): LineageRevision { let index: bigint; let digest: Uint8Array; + let sealed: boolean; try { - const elements = CborDeserializer.decodeArray(bytes, 2); + const elements = CborDeserializer.decodeArray(bytes); + if (elements.length === 2) { + sealed = false; + } else if (elements.length === 3 && CborDeserializer.decodeTextString(elements[0]) === LINEAGE_SEAL_MARKER) { + sealed = true; + elements.shift(); + } else { + throw new LineageFormatError('Unexpected revision payload shape.'); + } index = CborDeserializer.decodeUnsignedInteger(elements[0]); digest = CborDeserializer.decodeByteString(elements[1]); } catch (error) { - throw new LineageFormatError('Revision payload is not a CBOR array of [index, digest].', { cause: error }); + throw new LineageFormatError( + `Revision payload is not a CBOR array of [index, digest] or ["${LINEAGE_SEAL_MARKER}", index, digest].`, + { cause: error }, + ); } assertDigest(digest); - const revision = new LineageRevision(index, digest); + const revision = new LineageRevision(index, digest, sealed); assertCanonical(bytes, revision.toCBOR(), 'Revision payload'); return revision; } /** @returns {Uint8Array} CBOR encoding. */ public toCBOR(): Uint8Array { - return CborSerializer.encodeArray( - CborSerializer.encodeUnsignedInteger(this.index), - CborSerializer.encodeByteString(this._digest), - ); + const fields = [CborSerializer.encodeUnsignedInteger(this.index), CborSerializer.encodeByteString(this._digest)]; + return this.sealed + ? CborSerializer.encodeArray(CborSerializer.encodeTextString(LINEAGE_SEAL_MARKER), ...fields) + : CborSerializer.encodeArray(...fields); } } +/** + * The predicate a sealed revision is certified to: `P_burn(H(b_seal))`, with the + * SHA-256 of the exact seal payload bytes as the burn reason. + * + * @param {Uint8Array} sealPayload CBOR of the sealed {@link LineageRevision}. + * @returns {Promise} The burn predicate. + */ +export async function sealPredicate(sealPayload: Uint8Array): Promise { + const hash = await new DataHasher(HashAlgorithm.SHA256).update(sealPayload).digest(); + return BurnPredicate.create(hash.data); +} + /** * Genesis mint reason: the issuer's signature over `(id, ty, auxData)`. * diff --git a/src/lib/lineage/LineageVerification.ts b/src/lib/lineage/LineageVerification.ts index cfc70df..e7d84c5 100644 --- a/src/lib/lineage/LineageVerification.ts +++ b/src/lib/lineage/LineageVerification.ts @@ -1,4 +1,5 @@ import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; +import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import { PredicateVerifierService } from '@unicitylabs/state-transition-sdk/lib/predicate/verification/PredicateVerifierService.js'; @@ -21,6 +22,7 @@ import { LINEAGE_TOKEN_TYPE, LineageGenesisReason, LineageRevision, + sealPredicate, } from './LineagePayload.js'; import { errorMessage } from '../errors.js'; import { createUnicityCertificateVerifier } from '../verification.js'; @@ -41,7 +43,8 @@ function combine(rule: string, results: Result[]): Result { * auxiliary data and an issuer reason. The reason's signature is checked by * {@link LineageGenesisReasonVerifier}, which the SDK dispatches by CBOR tag; this * verifier only insists the reason is there, because the SDK accepts a mint with - * no justification at all. The recipient may be any predicate. + * no justification at all. The recipient may be any predicate; that a seal is + * burned, and only a seal, is checked with the chain rules. */ export class LineageIssuanceVerifier implements ITokenIssuanceVerifier { public static readonly RULE = 'LineageIssuanceVerification'; @@ -126,6 +129,11 @@ export function createLineageVerificationContext(trustBase: RootTrustBase): Veri /** One revision of a lineage as read off the token. */ export interface ILineageRevisionDescription { + /** + * Burn reason when the revision's recipient is the burn predicate, which it must + * be exactly when the revision is a seal; null for any other predicate. + */ + readonly burnReason: Uint8Array | null; readonly digest: Uint8Array | null; readonly epoch: bigint; readonly error: string | null; @@ -137,6 +145,8 @@ export interface ILineageRevisionDescription { readonly roundNumber: bigint; /** Unix seconds; consensus-signed upper bound of the reference time. */ readonly roundTimestamp: bigint; + /** Whether the payload marks this as the final revision; false when it does not decode. */ + readonly sealed: boolean; /** * Who signed the revision as claimed by the token: the issuer named in the genesis * reason for revision 0, otherwise the producer the previous revision named. Null @@ -147,6 +157,8 @@ export interface ILineageRevisionDescription { /** What a lineage token claims, without verifying it. */ export interface ILineageDescription { + /** Whether the latest revision is a seal; the token's validity is not implied. */ + readonly finalized: boolean; readonly issuer: Uint8Array | null; readonly revisions: readonly ILineageRevisionDescription[]; readonly token: Token; @@ -161,12 +173,21 @@ function signaturePredicateKey(predicate: EncodedPredicate): Uint8Array | null { } } +function burnReason(predicate: EncodedPredicate): Uint8Array | null { + try { + return BurnPredicate.fromPredicate(predicate).reason; + } catch { + return null; + } +} + function describeRevision( transaction: CertifiedMintTransaction | CertifiedTransferTransaction, signer: Uint8Array | null, ): ILineageRevisionDescription { const certificate = transaction.inclusionProof.unicityCertificate; const common = { + burnReason: burnReason(transaction.recipient), epoch: certificate.unicitySeal.epoch, nextProducer: signaturePredicateKey(transaction.recipient), referenceTime: transaction.referenceTime, @@ -175,13 +196,13 @@ function describeRevision( signer, }; if (transaction.data === null) { - return { ...common, digest: null, error: 'no revision payload', index: null }; + return { ...common, digest: null, error: 'no revision payload', index: null, sealed: false }; } try { const revision = LineageRevision.fromCBOR(transaction.data); - return { ...common, digest: revision.digest, error: null, index: revision.index }; + return { ...common, digest: revision.digest, error: null, index: revision.index, sealed: revision.sealed }; } catch (error) { - return { ...common, digest: null, error: errorMessage(error), index: null }; + return { ...common, digest: null, error: errorMessage(error), index: null, sealed: false }; } } @@ -205,6 +226,7 @@ export function describeLineage(token: Token): ILineageDescription { revisions.push(describeRevision(transaction, revisions[revisions.length - 1].nextProducer)); } return { + finalized: revisions[revisions.length - 1].sealed, issuer, revisions, token, @@ -231,18 +253,28 @@ export interface ILineageVerificationResult { } /** - * Rules the SDK does not check, because they relate neighbouring transactions: - * each revision's index is one more than the previous, and reference times never - * decrease along the chain (the protocol does not imply this; states can be - * precomputed and certified out of order). + * Rules the SDK does not check, because they relate neighbouring transactions + * or the lineage format: each revision's index is one more than the previous, + * reference times never decrease along the chain (the protocol does not imply + * this; states can be precomputed and certified out of order), and a revision is + * burned exactly when it is a seal, with the burn reason committing to the seal. */ -function chainRules(description: ILineageDescription): Result { +async function chainRules(description: ILineageDescription): Promise { const results: Result[] = []; - description.revisions.forEach((revision, position) => { + const transactions = [description.token.genesis, ...description.token.transactions]; + for (const [position, revision] of description.revisions.entries()) { if (revision.error !== null) { results.push(check(`Revision[${position}]Decodes`, false, `Revision ${position}: ${revision.error}`)); - return; + continue; } + results.push(await sealRule(revision, position, transactions[position].data as Uint8Array)); + results.push( + check( + `Revision[${position}]SealIsLast`, + !revision.sealed || position === description.revisions.length - 1, + `Revision ${position} is a seal, but revisions follow it.`, + ), + ); results.push( check( `Revision[${position}]IndexSequential`, @@ -260,10 +292,26 @@ function chainRules(description: ILineageDescription): Result { ), ); } - }); + } return combine('LineageChainVerification', results); } +async function sealRule(revision: ILineageRevisionDescription, position: number, payload: Uint8Array): Promise { + const rule = `Revision[${position}]SealBurned`; + if (!revision.sealed) { + return check(rule, revision.burnReason === null, `Revision ${position} is burned, but is not a seal.`); + } + if (revision.burnReason === null) { + return check(rule, false, `Revision ${position} is a seal, but is not burned.`); + } + const expected = (await sealPredicate(payload)).reason; + return check( + rule, + areUint8ArraysEqual(revision.burnReason, expected), + `Revision ${position} is a seal, but its burn reason does not commit to it.`, + ); +} + function deepestMessage(result: VerificationResult): string { if (result.status === VerificationStatus.OK) { return ''; @@ -312,7 +360,7 @@ export async function verifyLineage( }; } const sdk = await token.verify(createLineageVerificationContext(trustBase)); - const details = VerificationResult.fromResults('LineageTokenVerification', [sdk, chainRules(description)]); + const details = VerificationResult.fromResults('LineageTokenVerification', [sdk, await chainRules(description)]); if (details.status !== VerificationStatus.OK) { return { description, details, matchingRevisions: null, reason: deepestMessage(details), status: 'FAIL' }; } diff --git a/src/output.ts b/src/output.ts index 461c568..de27f23 100644 --- a/src/output.ts +++ b/src/output.ts @@ -376,7 +376,8 @@ export interface IRevisionSummary { readonly epoch: bigint; readonly gatewayUrl: string; readonly networkId: number; - readonly nextProducer: Uint8Array; + /** Null when the revision finalized the lineage. */ + readonly nextProducer: Uint8Array | null; readonly referenceTime: bigint; readonly revision: bigint; readonly roundNumber: bigint; @@ -389,9 +390,12 @@ export interface IRevisionSummary { export interface IRevisionJson { readonly command: 'stamp-revision'; readonly created: boolean; + /** True when this revision sealed the lineage, so that no revision can follow. */ + readonly finalized: boolean; readonly hash: { readonly algorithm: 'SHA-256'; readonly digest: string }; readonly network: INetworkJson & { readonly gateway: string }; - readonly nextProducer: string; + /** Null when the revision finalized the lineage. */ + readonly nextProducer: string | null; readonly referenceTime: string; readonly referenceTimeIso: string | null; readonly revision: string; @@ -407,11 +411,14 @@ export interface IRevisionJson { */ export function revisionText(summary: IRevisionSummary): string { return [ - line('Revision', `${summary.revision}${summary.created ? ' (new lineage)' : ''}`), + line( + 'Revision', + `${summary.revision}${summary.created ? ' (new lineage)' : ''}${summary.nextProducer === null ? ' (final)' : ''}`, + ), line('Stamped', `SHA-256 ${HexConverter.encode(summary.digest)}`), line('Network', `${networkLabel(summary.networkId)} via ${summary.gatewayUrl}`), line('Signed by', HexConverter.encode(summary.signer)), - line('Next producer', HexConverter.encode(summary.nextProducer)), + line('Next producer', keyLabel(summary.nextProducer, FINALIZED_LABEL)), line('Certified at', `${formatIso(summary.referenceTime)} (reference time ${summary.referenceTime})`), line('Round', `${summary.roundNumber} (round timestamp ${summary.roundTimestamp}, epoch ${summary.epoch})`), line('Token id', HexConverter.encode(summary.tokenId)), @@ -427,9 +434,10 @@ export function revisionJson(summary: IRevisionSummary): IRevisionJson { return { command: 'stamp-revision', created: summary.created, + finalized: summary.nextProducer === null, hash: { algorithm: 'SHA-256', digest: HexConverter.encode(summary.digest) }, network: { gateway: summary.gatewayUrl, id: summary.networkId, name: networkName(summary.networkId) }, - nextProducer: HexConverter.encode(summary.nextProducer), + nextProducer: summary.nextProducer === null ? null : HexConverter.encode(summary.nextProducer), referenceTime: summary.referenceTime.toString(), referenceTimeIso: toIso(summary.referenceTime), revision: summary.revision.toString(), @@ -468,13 +476,17 @@ export interface ILineageRevisionJson { readonly referenceTime: string; readonly referenceTimeIso: string | null; readonly round: { readonly epoch: string; readonly number: string; readonly timestamp: string }; + /** Whether the revision is a seal, the final revision of the lineage. */ + readonly sealed: boolean; readonly signer: string | null; } export interface ILineageDescriptionJson { + /** Whether the latest revision is a seal, so that no revision can follow. */ + readonly finalized: boolean; readonly issuer: string | null; readonly network: INetworkJson; - /** Who may sign the next revision: the latest revision's next producer. */ + /** Who may sign the next revision: the latest revision's next producer; null when finalized. */ readonly nextProducer: string | null; readonly revisions: ILineageRevisionJson[]; readonly tokenId: string; @@ -497,10 +509,19 @@ export interface ILineageInspectJson extends ILineageDescriptionJson { readonly verified: false; } +const FINALIZED_LABEL = 'none; the lineage is finalized (sealed and burned)'; + function keyLabel(key: Uint8Array | null, otherwise: string): string { return key === null ? otherwise : HexConverter.encode(key); } +function passesToLabel(revision: ILineageRevisionDescription): string { + if (revision.burnReason !== null) { + return revision.sealed ? 'nobody; sealed and burned' : 'burn predicate, but the revision is not a seal'; + } + return keyLabel(revision.nextProducer, 'not a signature predicate'); +} + function latestNextProducer(description: ILineageDescription): Uint8Array | null { return description.revisions.at(-1)?.nextProducer ?? null; } @@ -513,10 +534,10 @@ function lineageRevisionLines(revision: ILineageRevisionDescription, position: n `Revision ${position}`, revision.digest === null ? `unreadable (${revision.error ?? 'no revision payload'})` - : `SHA-256 ${HexConverter.encode(revision.digest)}${claimed}`, + : `SHA-256 ${HexConverter.encode(revision.digest)}${claimed}${revision.sealed ? ' (final)' : ''}`, ), line(' Signed by', keyLabel(revision.signer, 'not a signature predicate key')), - line(' Passes to', keyLabel(revision.nextProducer, 'not a signature predicate')), + line(' Passes to', passesToLabel(revision)), line(' Certified at', `${formatIso(revision.referenceTime)} (reference time ${revision.referenceTime})`), line(' Round', `${revision.roundNumber} (round timestamp ${revision.roundTimestamp}, epoch ${revision.epoch})`), ]; @@ -529,7 +550,10 @@ function lineageLines(description: ILineageDescription): string[] { line('Token id', HexConverter.encode(description.token.id.bytes)), line('Issuer', keyLabel(description.issuer, 'unreadable genesis reason')), line('Revisions', String(description.revisions.length)), - line('Next producer', keyLabel(latestNextProducer(description), 'not a signature predicate')), + line( + 'Next producer', + keyLabel(latestNextProducer(description), description.finalized ? FINALIZED_LABEL : 'not a signature predicate'), + ), ]; description.revisions.forEach((revision, position) => { lines.push('', ...lineageRevisionLines(revision, position)); @@ -552,7 +576,10 @@ function lineageExpectedHashLabel(result: ILineageVerificationResult): string { return 'differs from every revision'; } const which = `matches revision${matching.length > 1 ? 's' : ''} ${matching.join(', ')}`; - return last === latest ? `${which} (the latest)` : `${which}; superseded by revision ${latest}`; + if (last !== latest) { + return `${which}; superseded by revision ${latest}`; + } + return `${which} (the ${result.description.finalized ? 'final' : 'latest'})`; } /** @@ -603,6 +630,7 @@ function lineageRevisionJson(revision: ILineageRevisionDescription): ILineageRev number: revision.roundNumber.toString(), timestamp: revision.roundTimestamp.toString(), }, + sealed: revision.sealed, signer: revision.signer === null ? null : HexConverter.encode(revision.signer), }; } @@ -615,6 +643,7 @@ export function lineageDescriptionJson(description: ILineageDescription): ILinea const networkId = description.token.networkId.id; const nextProducer = latestNextProducer(description); return { + finalized: description.finalized, issuer: description.issuer === null ? null : HexConverter.encode(description.issuer), network: { id: networkId, name: networkName(networkId) }, nextProducer: nextProducer === null ? null : HexConverter.encode(nextProducer), diff --git a/tests/unit/LineageCommandsTest.ts b/tests/unit/LineageCommandsTest.ts index a800ca2..7948715 100644 --- a/tests/unit/LineageCommandsTest.ts +++ b/tests/unit/LineageCommandsTest.ts @@ -70,6 +70,44 @@ describe('verify and inspect on a document lineage', () => { await writeFile(trustBaseFile, JSON.stringify(aggregator.rootTrustBase.toJSON())); }); + it('verifies a finalized lineage and says so', async () => { + const sealed = await appendRevision( + client, + aggregator.rootTrustBase, + token, + HexConverter.decode('cd'.repeat(32)), + bob, + null, + fast, + ); + const sealedFile = path.join(directory, 'sealed.lineage'); + await writeFile(sealedFile, sealed.toCBOR()); + + const sink = testContext(); + expect(await runVerify(sealedFile, { hash: 'cd'.repeat(32), trustBase: trustBaseFile }, sink.context)).toBe( + EXIT_OK, + ); + const out = sink.stdout(); + expect(out).toContain('Next producer none; the lineage is finalized (sealed and burned)\n'); + expect(out).toContain(`Revision 3 SHA-256 ${'cd'.repeat(32)} (final)\n Signed by ${bobPublicHex}\n`); + expect(out).toContain(' Passes to nobody; sealed and burned\n'); + expect(out).toContain('Expected hash matches revision 3 (the final)'); + + const json = testContext({ json: true }); + expect(await runVerify(sealedFile, { trustBase: trustBaseFile }, json.context)).toBe(EXIT_OK); + expect(json.json()).toMatchObject({ finalized: true, nextProducer: null, status: 'OK' }); + expect((json.json() as { revisions: { sealed: boolean }[] }).revisions.map((entry) => entry.sealed)).toEqual([ + false, + false, + false, + true, + ]); + + const inspected = testContext({ json: true }); + expect(await runInspect(sealedFile, inspected.context)).toBe(EXIT_OK); + expect(inspected.json()).toMatchObject({ finalized: true, verified: false }); + }); + it('verifies the lineage and lists every revision', async () => { const sink = testContext(); expect(await runVerify(tokenFile, { trustBase: trustBaseFile }, sink.context)).toBe(EXIT_OK); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 220a257..f7e0286 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -46,7 +46,7 @@ describe('resolveStampRevisionConfig', () => { expect(config.tokenBytes).toBeNull(); expect(config.digest).toEqual(TEST_DIGEST); expect(config.privateKey).toEqual(TEST_PRIVATE_KEY); - expect(HexConverter.encode(config.recipientKey)).toEqual(TEST_PUBLIC_KEY_HEX); + expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); expect(config.network.preset).toEqual('mainnet'); }); @@ -57,7 +57,16 @@ describe('resolveStampRevisionConfig', () => { await writeFile(recipientKeyFile, ` ${TEST_PUBLIC_KEY_HEX.toUpperCase()}\n`); const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, { keyFile, recipientKeyFile, tokenFile }, ENV); expect(config.tokenBytes).toEqual(new TextEncoder().encode('abcd')); - expect(HexConverter.encode(config.recipientKey)).toEqual(TEST_PUBLIC_KEY_HEX); + expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); + }); + + it('resolves --finalize to no next producer', async () => { + const config = await resolveStampRevisionConfig( + TEST_DIGEST_HEX, + { ...base(), finalize: true, recipientKey: undefined }, + ENV, + ); + expect(config.recipientKey).toBeNull(); }); it.each([ @@ -65,12 +74,35 @@ describe('resolveStampRevisionConfig', () => { ['both digest sources', TEST_DIGEST_HEX, { file: 'x' }, 'Pass either a digest or --file, not both.'], ['no token file', TEST_DIGEST_HEX, { tokenFile: undefined }, /--token-file/], ['no key file', TEST_DIGEST_HEX, { keyFile: undefined }, /--key-file/], - ['no recipient', TEST_DIGEST_HEX, { recipientKey: undefined }, /--recipient-key or --recipient-key-file/], + [ + 'no recipient', + TEST_DIGEST_HEX, + { recipientKey: undefined }, + /--recipient-key or --recipient-key-file, or pass --finalize/, + ], [ 'both recipients', TEST_DIGEST_HEX, { recipientKeyFile: 'x' }, - 'Pass either --recipient-key or --recipient-key-file, not both.', + 'Pass only one of --recipient-key, --recipient-key-file and --finalize; got --recipient-key and --recipient-key-file.', + ], + [ + 'a recipient and --finalize', + TEST_DIGEST_HEX, + { finalize: true }, + 'Pass only one of --recipient-key, --recipient-key-file and --finalize; got --recipient-key and --finalize.', + ], + [ + 'a recipient file and --finalize', + TEST_DIGEST_HEX, + { finalize: true, recipientKey: undefined, recipientKeyFile: 'x' }, + /got --recipient-key-file and --finalize/, + ], + [ + 'all three', + TEST_DIGEST_HEX, + { finalize: true, recipientKeyFile: 'x' }, + /got --recipient-key and --recipient-key-file and --finalize/, ], ['a malformed recipient', TEST_DIGEST_HEX, { recipientKey: '04abcd' }, /compressed secp256k1 public key/], [ @@ -170,6 +202,48 @@ describe('stampRevisionWith', () => { expect((await verifyLineage(token, aggregator.rootTrustBase)).status).toEqual('OK'); }); + it('finalizes a lineage, after which nothing can be appended', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + await stampRevisionWith(config({}), client, testContext().context); + const tokenBytes = new Uint8Array(await readFile(tokenFile)); + + const sealed = testContext({ json: true }); + expect( + await stampRevisionWith( + config({ digest: OTHER_DIGEST, privateKey: bob, recipientKey: null, tokenBytes }), + client, + sealed.context, + ), + ).toBe(0); + expect(sealed.json()).toMatchObject({ finalized: true, nextProducer: null, revision: '1' }); + + const text = testContext(); + const finalBytes = new Uint8Array(await readFile(tokenFile)); + expect( + await stampRevisionWith( + config({ digest: OTHER_DIGEST, privateKey: bob, recipientKey: null, tokenBytes }), + client, + text.context, + ), + ).toBe(0); + expect(text.stdout()).toContain('Revision 1 (final)\n'); + expect(text.stdout()).toContain('Next producer none; the lineage is finalized'); + + const attempt = stampRevisionWith( + config({ privateKey: bob, tokenBytes: finalBytes }), + client, + testContext().context, + ); + await expect(attempt).rejects.toThrow(/finalized/); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + }); + + it('creates a lineage that is final from the start', async () => { + const sink = testContext({ json: true }); + expect(await stampRevisionWith(config({ recipientKey: null }), client, sink.context)).toBe(0); + expect(sink.json()).toMatchObject({ created: true, finalized: true, nextProducer: null, revision: '0' }); + }); + it('accepts a token file holding hex text', async () => { const tokenFile = path.join(directory, 'doc.lineage'); await stampRevisionWith(config({}), client, testContext().context); diff --git a/tests/unit/lib/LineageTest.ts b/tests/unit/lib/LineageTest.ts index a34338b..fe4060c 100644 --- a/tests/unit/lib/LineageTest.ts +++ b/tests/unit/lib/LineageTest.ts @@ -6,8 +6,10 @@ import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/ap import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js'; import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; +import type { IPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/IPredicate.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; @@ -19,6 +21,7 @@ import { appendRevision, createLineage, currentProducerKey, + isFinalized, LineageError, } from '../../../src/lib/lineage/LineageClient.js'; import { @@ -28,6 +31,7 @@ import { LineageFormatError, LineageGenesisReason, LineageRevision, + sealPredicate, } from '../../../src/lib/lineage/LineagePayload.js'; import { describeLineage, verifyLineage } from '../../../src/lib/lineage/LineageVerification.js'; import { bundledTrustBase } from '../../../src/lib/networks.js'; @@ -143,6 +147,114 @@ describe('document lineage', () => { ).rejects.toThrow(); }); + describe('finalization', () => { + it('seals the final revision and burns the token, so nothing can follow', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const sealed = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, null, fast); + const token = await Token.fromCBOR(sealed.toCBOR()); + expect(isFinalized(token)).toBe(true); + expect(isFinalized(genesis)).toBe(false); + expect(currentProducerKey(token)).toBeNull(); + + const payload = token.transactions[0].data as Uint8Array; + const revision = LineageRevision.fromCBOR(payload); + expect(revision.sealed).toBe(true); + expect(revision.index).toBe(1n); + expect(revision.digest).toEqual(OTHER_DIGEST); + // The burn reason commits to the seal: P_burn(H(b_seal)). + expect(BurnPredicate.fromPredicate(token.transactions[0].recipient).reason).toEqual( + new Uint8Array(createHash('sha256').update(payload).digest()), + ); + + const result = await verifyLineage(token, trustBase, { expectedDigest: OTHER_DIGEST }); + expect(result.reason).toBeNull(); + expect(result.status).toEqual('OK'); + expect(result.description.finalized).toBe(true); + expect(result.description.revisions.map((entry) => entry.sealed)).toEqual([false, true]); + + const before = counting.submissions; + for (const key of [alice, bob, carol]) { + await expect( + appendRevision(client, trustBase, token, THIRD_DIGEST, key, publicKey(carol), fast), + ).rejects.toMatchObject({ code: 'FINALIZED' }); + } + expect(counting.submissions).toBe(before); + }); + + it('finalizes a new lineage at revision 0', async () => { + const token = await createLineage(client, trustBase, TEST_DIGEST, alice, null, fast); + expect(isFinalized(token)).toBe(true); + const result = await verifyLineage(await Token.fromCBOR(token.toCBOR()), trustBase); + expect(result.reason).toBeNull(); + expect(result.description.finalized).toBe(true); + expect(result.description.revisions[0].signer).toEqual(publicKey(alice)); + await expect( + appendRevision(client, trustBase, token, OTHER_DIGEST, alice, publicKey(bob), fast), + ).rejects.toMatchObject({ code: 'FINALIZED' }); + }); + + it('replays an interrupted seal identically', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const first = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, null, fast); + const again = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, null, fast); + expect(HexConverter.encode(again.toCBOR())).toEqual(HexConverter.encode(first.toCBOR())); + }); + + /** A genesis with a valid issuer signature over `data`, minted to `recipient`. */ + async function signedGenesis(data: Uint8Array, recipient: IPredicate): Promise { + const salt = TokenSalt.generate(); + const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); + const reason = await LineageGenesisReason.sign(tokenId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); + const genesis = await certifyMint(aggregator, recipient, { + data, + justification: reason.toCBOR(), + salt, + tokenType: LINEAGE_TOKEN_TYPE, + }); + return Token.fromCBOR( + CborSerializer.encodeTag( + Token.CBOR_TAG, + CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(2n), + genesis.toCBOR(), + CborSerializer.encodeArray(), + ), + ), + ); + } + + it('accepts a correctly formed seal at genesis', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const result = await verifyLineage(await signedGenesis(data, await sealPredicate(data)), trustBase); + expect(result.reason).toBeNull(); + }); + + it('rejects a seal that is not burned', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const result = await verifyLineage( + await signedGenesis(data, SignaturePredicate.create(publicKey(bob))), + trustBase, + ); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision 0 is a seal, but is not burned.'); + }); + + it('rejects a burn that is not a seal', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const result = await verifyLineage(await signedGenesis(data, await sealPredicate(data)), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision 0 is burned, but is not a seal.'); + }); + + it('rejects a seal whose burn reason commits to something else', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const other = LineageRevision.create(0n, OTHER_DIGEST, true).toCBOR(); + const result = await verifyLineage(await signedGenesis(data, await sealPredicate(other)), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision 0 is a seal, but its burn reason does not commit to it.'); + }); + }); + describe('verification', () => { /** Mint a lineage-typed genesis with arbitrary fields and wrap it as a token, bypassing issuance checks. */ async function rawLineageToken(options: { @@ -235,6 +347,27 @@ describe('document lineage', () => { expect(() => LineageRevision.fromCBOR(trailing)).toThrow(LineageFormatError); }); + it('round-trips a seal and keeps it distinct from an ordinary revision', () => { + const seal = LineageRevision.create(3n, TEST_DIGEST, true); + const decoded = LineageRevision.fromCBOR(seal.toCBOR()); + expect(decoded.sealed).toBe(true); + expect(decoded.index).toBe(3n); + expect(decoded.digest).toEqual(TEST_DIGEST); + expect(LineageRevision.fromCBOR(LineageRevision.create(3n, TEST_DIGEST).toCBOR()).sealed).toBe(false); + expect(HexConverter.encode(seal.toCBOR())).toEqual( + `8364${HexConverter.encode(new TextEncoder().encode('seal'))}035820${HexConverter.encode(TEST_DIGEST)}`, + ); + }); + + it('rejects a three-element revision without the seal marker', () => { + const bogus = CborSerializer.encodeArray( + CborSerializer.encodeTextString('stop'), + CborSerializer.encodeUnsignedInteger(0n), + CborSerializer.encodeByteString(TEST_DIGEST), + ); + expect(() => LineageRevision.fromCBOR(bogus)).toThrow(LineageFormatError); + }); + it('round-trips a genesis reason and rejects a wrong tag', async () => { const tokenId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); const reason = await LineageGenesisReason.sign( From c53152fef8c2867e91f569aa63415838cfa4076e Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:18:53 +0200 Subject: [PATCH 04/25] Move the lineage modules next to the timestamp ones src/lib/lineage/* moves to src/lib/, so the library code behind `stamp` (Timestamp*.ts) and `stamp-revision` (Lineage*.ts) sits side by side. Imports updated; no behaviour change. Co-Authored-By: Claude Opus 5.5 --- src/commands/inspect.ts | 2 +- src/commands/stampRevision.ts | 2 +- src/commands/verify.ts | 2 +- src/errors.ts | 2 +- src/lib/{lineage => }/LineageClient.ts | 2 +- src/lib/{lineage => }/LineagePayload.ts | 0 src/lib/{lineage => }/LineageVerification.ts | 4 ++-- src/output.ts | 2 +- tests/unit/LineageCommandsTest.ts | 2 +- tests/unit/StampRevisionTest.ts | 2 +- tests/unit/lib/LineageTest.ts | 6 +++--- 11 files changed, 13 insertions(+), 13 deletions(-) rename src/lib/{lineage => }/LineageClient.ts (99%) rename src/lib/{lineage => }/LineagePayload.ts (100%) rename src/lib/{lineage => }/LineageVerification.ts (99%) diff --git a/src/commands/inspect.ts b/src/commands/inspect.ts index cf3446c..0a137dd 100644 --- a/src/commands/inspect.ts +++ b/src/commands/inspect.ts @@ -1,7 +1,7 @@ import { ICommandContext } from './context.js'; import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; import { EXIT_OK } from '../errors.js'; -import { describeLineage } from '../lib/lineage/LineageVerification.js'; +import { describeLineage } from '../lib/LineageVerification.js'; import { describeToken } from '../lib/TimestampVerification.js'; import { inspectJson, inspectText, lineageInspectJson, lineageInspectText, toJsonLine } from '../output.js'; diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 00f58be..61e3e67 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -13,7 +13,7 @@ import { ICommandContext } from './context.js'; import { decodeToken, tokenBytesFromInput } from './tokenInput.js'; import { IStampRevisionConfig, IStampRevisionFlags, resolveStampRevisionConfig } from '../config.js'; import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; -import { appendRevision, createLineage } from '../lib/lineage/LineageClient.js'; +import { appendRevision, createLineage } from '../lib/LineageClient.js'; import { revisionJson, revisionRecoveryLines, revisionText, toJsonLine, warningLine } from '../output.js'; /** diff --git a/src/commands/verify.ts b/src/commands/verify.ts index 012eac5..3648430 100644 --- a/src/commands/verify.ts +++ b/src/commands/verify.ts @@ -2,7 +2,7 @@ import { ICommandContext } from './context.js'; import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; import { assertOneDigestSource, INetworkFlags, resolveDigest, resolveTrustBaseOverride } from '../config.js'; import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; -import { describeLineage, ILineageVerificationResult, verifyLineage } from '../lib/lineage/LineageVerification.js'; +import { describeLineage, ILineageVerificationResult, verifyLineage } from '../lib/LineageVerification.js'; import { bundledTrustBase, ITrustBaseChoice, networkNameForId, TrustBaseSource } from '../lib/networks.js'; import { describeToken, diff --git a/src/errors.ts b/src/errors.ts index 1023fa6..2620f40 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -5,7 +5,7 @@ import { SleepError } from '@unicitylabs/state-transition-sdk/lib/util/Inclusion import { VerificationError } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationError.js'; import { errorMessage, StampError } from './lib/errors.js'; -import { LineageError } from './lib/lineage/LineageClient.js'; +import { LineageError } from './lib/LineageClient.js'; export const EXIT_OK = 0; /** Verification failed, hash mismatch, or the input is not a token. */ diff --git a/src/lib/lineage/LineageClient.ts b/src/lib/LineageClient.ts similarity index 99% rename from src/lib/lineage/LineageClient.ts rename to src/lib/LineageClient.ts index e59ed57..979944b 100644 --- a/src/lib/lineage/LineageClient.ts +++ b/src/lib/LineageClient.ts @@ -24,7 +24,7 @@ import { sealPredicate, } from './LineagePayload.js'; import { createLineageVerificationContext, verifyLineage } from './LineageVerification.js'; -import { ICertifyOptions, certifyMintTransaction, certifyTransaction } from '../TimestampClient.js'; +import { ICertifyOptions, certifyMintTransaction, certifyTransaction } from './TimestampClient.js'; /** Thrown when a revision cannot be appended to the given token with the given key. */ export class LineageError extends Error { diff --git a/src/lib/lineage/LineagePayload.ts b/src/lib/LineagePayload.ts similarity index 100% rename from src/lib/lineage/LineagePayload.ts rename to src/lib/LineagePayload.ts diff --git a/src/lib/lineage/LineageVerification.ts b/src/lib/LineageVerification.ts similarity index 99% rename from src/lib/lineage/LineageVerification.ts rename to src/lib/LineageVerification.ts index e7d84c5..f3cbf05 100644 --- a/src/lib/lineage/LineageVerification.ts +++ b/src/lib/LineageVerification.ts @@ -17,6 +17,7 @@ import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/ import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; +import { errorMessage } from './errors.js'; import { LINEAGE_GENESIS_REASON_TAG, LINEAGE_TOKEN_TYPE, @@ -24,8 +25,7 @@ import { LineageRevision, sealPredicate, } from './LineagePayload.js'; -import { errorMessage } from '../errors.js'; -import { createUnicityCertificateVerifier } from '../verification.js'; +import { createUnicityCertificateVerifier } from './verification.js'; type Result = VerificationResult; diff --git a/src/output.ts b/src/output.ts index de27f23..36bce55 100644 --- a/src/output.ts +++ b/src/output.ts @@ -5,7 +5,7 @@ import { ILineageDescription, ILineageRevisionDescription, ILineageVerificationResult, -} from './lib/lineage/LineageVerification.js'; +} from './lib/LineageVerification.js'; import { networkNameForId, TrustBaseSource } from './lib/networks.js'; import { ITimestampDescription, ITimestampVerificationResult } from './lib/TimestampVerification.js'; diff --git a/tests/unit/LineageCommandsTest.ts b/tests/unit/LineageCommandsTest.ts index 7948715..aad66a6 100644 --- a/tests/unit/LineageCommandsTest.ts +++ b/tests/unit/LineageCommandsTest.ts @@ -9,7 +9,7 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { runInspect } from '../../src/commands/inspect.js'; import { runVerify } from '../../src/commands/verify.js'; import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; -import { appendRevision, createLineage } from '../../src/lib/lineage/LineageClient.js'; +import { appendRevision, createLineage } from '../../src/lib/LineageClient.js'; import { testContext } from '../support/context.js'; import { OTHER_DIGEST, diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index f7e0286..bbb36d8 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -9,7 +9,7 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { stampRevisionWith, writeRevisionToken } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig, parsePublicKey, resolveStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; -import { verifyLineage } from '../../src/lib/lineage/LineageVerification.js'; +import { verifyLineage } from '../../src/lib/LineageVerification.js'; import { testContext } from '../support/context.js'; import { OTHER_DIGEST, diff --git a/tests/unit/lib/LineageTest.ts b/tests/unit/lib/LineageTest.ts index fe4060c..bd81add 100644 --- a/tests/unit/lib/LineageTest.ts +++ b/tests/unit/lib/LineageTest.ts @@ -23,7 +23,7 @@ import { currentProducerKey, isFinalized, LineageError, -} from '../../../src/lib/lineage/LineageClient.js'; +} from '../../../src/lib/LineageClient.js'; import { LINEAGE_TAG, LINEAGE_TOKEN_TYPE, @@ -32,8 +32,8 @@ import { LineageGenesisReason, LineageRevision, sealPredicate, -} from '../../../src/lib/lineage/LineagePayload.js'; -import { describeLineage, verifyLineage } from '../../../src/lib/lineage/LineageVerification.js'; +} from '../../../src/lib/LineagePayload.js'; +import { describeLineage, verifyLineage } from '../../../src/lib/LineageVerification.js'; import { bundledTrustBase } from '../../../src/lib/networks.js'; import { stampWith } from '../../../src/lib/TimestampClient.js'; import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; From 28040c4788b9e0946c002a3521b7fa8e20aa158f Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:24:29 +0200 Subject: [PATCH 05/25] Rename LineageTest to LineageClientTest Matches the timestamp tests, which are named after the module they test (TimestampClientTest for TimestampClient); the top-level describe follows. Co-Authored-By: Claude Opus 5.5 --- tests/unit/lib/{LineageTest.ts => LineageClientTest.ts} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename tests/unit/lib/{LineageTest.ts => LineageClientTest.ts} (99%) diff --git a/tests/unit/lib/LineageTest.ts b/tests/unit/lib/LineageClientTest.ts similarity index 99% rename from tests/unit/lib/LineageTest.ts rename to tests/unit/lib/LineageClientTest.ts index bd81add..d2162a9 100644 --- a/tests/unit/lib/LineageTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -56,7 +56,7 @@ class CountingClient implements IAggregatorClient { } } -describe('document lineage', () => { +describe('LineageClient', () => { const aggregator = TestAggregatorClient.create(); const counting = new CountingClient(aggregator); const client = new StateTransitionClient(counting); From 1518223a54a968cee7282be404ed8df2bc3553a7 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:28:59 +0200 Subject: [PATCH 06/25] Split the lineage tests by module, as for timestamps LineageClientTest keeps creating, appending and finalizing. LineagePayloadTest takes the CBOR encodings, the token type pin and the genesis reason, plus a new check of sealPredicate. LineageVerificationTest takes the hand-built genesis and seal tokens that verification must reject, now sharing one minting helper, and describeLineage. Co-Authored-By: Claude Opus 5.5 --- tests/unit/lib/LineageClientTest.ts | 213 +--------------------- tests/unit/lib/LineagePayloadTest.ts | 104 +++++++++++ tests/unit/lib/LineageVerificationTest.ts | 140 ++++++++++++++ 3 files changed, 246 insertions(+), 211 deletions(-) create mode 100644 tests/unit/lib/LineagePayloadTest.ts create mode 100644 tests/unit/lib/LineageVerificationTest.ts diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts index d2162a9..8fecf7c 100644 --- a/tests/unit/lib/LineageClientTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -7,14 +7,8 @@ import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/ap import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; -import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; -import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; -import type { IPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/IPredicate.js'; -import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; -import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; -import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { @@ -24,21 +18,12 @@ import { isFinalized, LineageError, } from '../../../src/lib/LineageClient.js'; -import { - LINEAGE_TAG, - LINEAGE_TOKEN_TYPE, - LINEAGE_TOKEN_TYPE_HEX, - LineageFormatError, - LineageGenesisReason, - LineageRevision, - sealPredicate, -} from '../../../src/lib/LineagePayload.js'; -import { describeLineage, verifyLineage } from '../../../src/lib/LineageVerification.js'; +import { LINEAGE_TOKEN_TYPE_HEX, LineageRevision } from '../../../src/lib/LineagePayload.js'; +import { verifyLineage } from '../../../src/lib/LineageVerification.js'; import { bundledTrustBase } from '../../../src/lib/networks.js'; import { stampWith } from '../../../src/lib/TimestampClient.js'; import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; -import { certifyMint } from '../../support/TimestampFixtures.js'; /** Counts certification requests so a test can see whether the network was contacted. */ class CountingClient implements IAggregatorClient { @@ -69,10 +54,6 @@ describe('LineageClient', () => { const publicKey = (key: Uint8Array): Uint8Array => new SigningService(key).publicKey; const THIRD_DIGEST = new Uint8Array(createHash('sha256').update('v2').digest()); - it('pins the token type to SHA-256 of the tag', () => { - expect(createHash('sha256').update(LINEAGE_TAG).digest('hex')).toEqual(LINEAGE_TOKEN_TYPE_HEX); - }); - it('creates a lineage, appends revisions along the chain of custody, and verifies offline', async () => { const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); expect(genesis.transactions).toHaveLength(0); @@ -199,195 +180,5 @@ describe('LineageClient', () => { const again = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, null, fast); expect(HexConverter.encode(again.toCBOR())).toEqual(HexConverter.encode(first.toCBOR())); }); - - /** A genesis with a valid issuer signature over `data`, minted to `recipient`. */ - async function signedGenesis(data: Uint8Array, recipient: IPredicate): Promise { - const salt = TokenSalt.generate(); - const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); - const reason = await LineageGenesisReason.sign(tokenId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); - const genesis = await certifyMint(aggregator, recipient, { - data, - justification: reason.toCBOR(), - salt, - tokenType: LINEAGE_TOKEN_TYPE, - }); - return Token.fromCBOR( - CborSerializer.encodeTag( - Token.CBOR_TAG, - CborSerializer.encodeArray( - CborSerializer.encodeUnsignedInteger(2n), - genesis.toCBOR(), - CborSerializer.encodeArray(), - ), - ), - ); - } - - it('accepts a correctly formed seal at genesis', async () => { - const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); - const result = await verifyLineage(await signedGenesis(data, await sealPredicate(data)), trustBase); - expect(result.reason).toBeNull(); - }); - - it('rejects a seal that is not burned', async () => { - const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); - const result = await verifyLineage( - await signedGenesis(data, SignaturePredicate.create(publicKey(bob))), - trustBase, - ); - expect(result.status).toEqual('FAIL'); - expect(result.reason).toEqual('Revision 0 is a seal, but is not burned.'); - }); - - it('rejects a burn that is not a seal', async () => { - const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); - const result = await verifyLineage(await signedGenesis(data, await sealPredicate(data)), trustBase); - expect(result.status).toEqual('FAIL'); - expect(result.reason).toEqual('Revision 0 is burned, but is not a seal.'); - }); - - it('rejects a seal whose burn reason commits to something else', async () => { - const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); - const other = LineageRevision.create(0n, OTHER_DIGEST, true).toCBOR(); - const result = await verifyLineage(await signedGenesis(data, await sealPredicate(other)), trustBase); - expect(result.status).toEqual('FAIL'); - expect(result.reason).toEqual('Revision 0 is a seal, but its burn reason does not commit to it.'); - }); - }); - - describe('verification', () => { - /** Mint a lineage-typed genesis with arbitrary fields and wrap it as a token, bypassing issuance checks. */ - async function rawLineageToken(options: { - data?: Uint8Array | null; - justification?: Uint8Array | null; - }): Promise { - const salt = TokenSalt.generate(); - const genesis = await certifyMint(aggregator, SignaturePredicate.create(publicKey(bob)), { - salt, - tokenType: LINEAGE_TOKEN_TYPE, - ...options, - }); - return Token.fromCBOR( - CborSerializer.encodeTag( - Token.CBOR_TAG, - CborSerializer.encodeArray( - CborSerializer.encodeUnsignedInteger(2n), - genesis.toCBOR(), - CborSerializer.encodeArray(), - ), - ), - ); - } - - it('rejects a genesis whose issuer signature covers another token', async () => { - const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); - const otherId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); - const reason = await LineageGenesisReason.sign(otherId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); - const result = await verifyLineage(await rawLineageToken({ data, justification: reason.toCBOR() }), trustBase); - expect(result.status).toEqual('FAIL'); - expect(result.reason).toEqual('Issuer signature in the genesis reason does not verify.'); - }); - - it('rejects a genesis without an issuer reason', async () => { - const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); - const result = await verifyLineage(await rawLineageToken({ data, justification: null }), trustBase); - expect(result.status).toEqual('FAIL'); - expect(result.reason).toEqual('Lineage genesis carries no issuer reason.'); - }); - - it('rejects a genesis that does not start at revision 0', async () => { - const salt = TokenSalt.generate(); - const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); - const data = LineageRevision.create(1n, TEST_DIGEST).toCBOR(); - const reason = await LineageGenesisReason.sign(tokenId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); - const genesis = await certifyMint(aggregator, SignaturePredicate.create(publicKey(bob)), { - data, - justification: reason.toCBOR(), - salt, - tokenType: LINEAGE_TOKEN_TYPE, - }); - const token = await Token.fromCBOR( - CborSerializer.encodeTag( - Token.CBOR_TAG, - CborSerializer.encodeArray( - CborSerializer.encodeUnsignedInteger(2n), - genesis.toCBOR(), - CborSerializer.encodeArray(), - ), - ), - ); - const result = await verifyLineage(token, trustBase); - expect(result.status).toEqual('FAIL'); - expect(result.reason).toEqual('Genesis revision index is 1, not 0.'); - }); - - it('describes revisions without verifying', async () => { - const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); - const description = describeLineage(genesis); - expect(description.tokenTypeIsLineage).toBe(true); - expect(description.revisions).toHaveLength(1); - expect(description.revisions[0].error).toBeNull(); - }); - }); - - describe('payload encoding', () => { - it('round-trips a revision', () => { - const revision = LineageRevision.create(3n, TEST_DIGEST); - const decoded = LineageRevision.fromCBOR(revision.toCBOR()); - expect(decoded.index).toBe(3n); - expect(decoded.digest).toEqual(TEST_DIGEST); - }); - - it('rejects malformed revisions', () => { - expect(() => LineageRevision.create(0n, new Uint8Array(31))).toThrow(LineageFormatError); - expect(() => - LineageRevision.fromCBOR(CborSerializer.encodeArray(CborSerializer.encodeUnsignedInteger(0n))), - ).toThrow(LineageFormatError); - const trailing = new Uint8Array([...LineageRevision.create(0n, TEST_DIGEST).toCBOR(), 0x00]); - expect(() => LineageRevision.fromCBOR(trailing)).toThrow(LineageFormatError); - }); - - it('round-trips a seal and keeps it distinct from an ordinary revision', () => { - const seal = LineageRevision.create(3n, TEST_DIGEST, true); - const decoded = LineageRevision.fromCBOR(seal.toCBOR()); - expect(decoded.sealed).toBe(true); - expect(decoded.index).toBe(3n); - expect(decoded.digest).toEqual(TEST_DIGEST); - expect(LineageRevision.fromCBOR(LineageRevision.create(3n, TEST_DIGEST).toCBOR()).sealed).toBe(false); - expect(HexConverter.encode(seal.toCBOR())).toEqual( - `8364${HexConverter.encode(new TextEncoder().encode('seal'))}035820${HexConverter.encode(TEST_DIGEST)}`, - ); - }); - - it('rejects a three-element revision without the seal marker', () => { - const bogus = CborSerializer.encodeArray( - CborSerializer.encodeTextString('stop'), - CborSerializer.encodeUnsignedInteger(0n), - CborSerializer.encodeByteString(TEST_DIGEST), - ); - expect(() => LineageRevision.fromCBOR(bogus)).toThrow(LineageFormatError); - }); - - it('round-trips a genesis reason and rejects a wrong tag', async () => { - const tokenId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); - const reason = await LineageGenesisReason.sign( - tokenId, - LINEAGE_TOKEN_TYPE, - TEST_DIGEST, - new SigningService(alice), - ); - const decoded = LineageGenesisReason.fromCBOR(reason.toCBOR()); - expect(decoded.issuer).toEqual(publicKey(alice)); - expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, TEST_DIGEST)).toBe(true); - expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, OTHER_DIGEST)).toBe(false); - - const wrongTag = CborSerializer.encodeTag(1n, CborSerializer.encodeArray()); - expect(() => LineageGenesisReason.fromCBOR(wrongTag)).toThrow(LineageFormatError); - }); - - it('builds the recipient as a P_sig predicate', () => { - const predicate = EncodedPredicate.fromPredicate(SignaturePredicate.create(publicKey(bob))); - expect(SignaturePredicate.fromPredicate(predicate).publicKey).toEqual(publicKey(bob)); - }); }); }); diff --git a/tests/unit/lib/LineagePayloadTest.ts b/tests/unit/lib/LineagePayloadTest.ts new file mode 100644 index 0000000..1d6d95e --- /dev/null +++ b/tests/unit/lib/LineagePayloadTest.ts @@ -0,0 +1,104 @@ +import { createHash } from 'node:crypto'; + +import { NetworkId } from '@unicitylabs/state-transition-sdk/lib/api/NetworkId.js'; +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; +import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; +import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; +import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; +import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { + LINEAGE_TAG, + LINEAGE_TOKEN_TYPE, + LINEAGE_TOKEN_TYPE_HEX, + LineageFormatError, + LineageGenesisReason, + LineageRevision, + sealPredicate, +} from '../../../src/lib/LineagePayload.js'; +import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; + +describe('LineagePayload', () => { + const alice = SigningService.generatePrivateKey(); + const publicKey = (key: Uint8Array): Uint8Array => new SigningService(key).publicKey; + + it('pins the token type to SHA-256 of the tag', () => { + expect(createHash('sha256').update(LINEAGE_TAG).digest('hex')).toEqual(LINEAGE_TOKEN_TYPE_HEX); + }); + + describe('LineageRevision', () => { + it('round-trips a revision', () => { + const revision = LineageRevision.create(3n, TEST_DIGEST); + const decoded = LineageRevision.fromCBOR(revision.toCBOR()); + expect(decoded.index).toBe(3n); + expect(decoded.digest).toEqual(TEST_DIGEST); + }); + + it('rejects malformed revisions', () => { + expect(() => LineageRevision.create(0n, new Uint8Array(31))).toThrow(LineageFormatError); + expect(() => + LineageRevision.fromCBOR(CborSerializer.encodeArray(CborSerializer.encodeUnsignedInteger(0n))), + ).toThrow(LineageFormatError); + const trailing = new Uint8Array([...LineageRevision.create(0n, TEST_DIGEST).toCBOR(), 0x00]); + expect(() => LineageRevision.fromCBOR(trailing)).toThrow(LineageFormatError); + }); + + it('round-trips a seal and keeps it distinct from an ordinary revision', () => { + const seal = LineageRevision.create(3n, TEST_DIGEST, true); + const decoded = LineageRevision.fromCBOR(seal.toCBOR()); + expect(decoded.sealed).toBe(true); + expect(decoded.index).toBe(3n); + expect(decoded.digest).toEqual(TEST_DIGEST); + expect(LineageRevision.fromCBOR(LineageRevision.create(3n, TEST_DIGEST).toCBOR()).sealed).toBe(false); + expect(HexConverter.encode(seal.toCBOR())).toEqual( + `8364${HexConverter.encode(new TextEncoder().encode('seal'))}035820${HexConverter.encode(TEST_DIGEST)}`, + ); + }); + + it('rejects a three-element revision without the seal marker', () => { + const bogus = CborSerializer.encodeArray( + CborSerializer.encodeTextString('stop'), + CborSerializer.encodeUnsignedInteger(0n), + CborSerializer.encodeByteString(TEST_DIGEST), + ); + expect(() => LineageRevision.fromCBOR(bogus)).toThrow(LineageFormatError); + }); + }); + + describe('sealPredicate', () => { + it('burns with the SHA-256 of the seal payload as reason', async () => { + const payload = LineageRevision.create(2n, TEST_DIGEST, true).toCBOR(); + const predicate = EncodedPredicate.fromPredicate(await sealPredicate(payload)); + expect(BurnPredicate.fromPredicate(predicate).reason).toEqual( + new Uint8Array(createHash('sha256').update(payload).digest()), + ); + }); + }); + + describe('LineageGenesisReason', () => { + it('round-trips a genesis reason and rejects a wrong tag', async () => { + const tokenId = await TokenId.fromSalt(NetworkId.LOCAL, TokenSalt.generate()); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + TEST_DIGEST, + new SigningService(alice), + ); + const decoded = LineageGenesisReason.fromCBOR(reason.toCBOR()); + expect(decoded.issuer).toEqual(publicKey(alice)); + expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, TEST_DIGEST)).toBe(true); + expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, OTHER_DIGEST)).toBe(false); + + const wrongTag = CborSerializer.encodeTag(1n, CborSerializer.encodeArray()); + expect(() => LineageGenesisReason.fromCBOR(wrongTag)).toThrow(LineageFormatError); + }); + }); + + it('builds the recipient as a P_sig predicate', () => { + const predicate = EncodedPredicate.fromPredicate(SignaturePredicate.create(publicKey(alice))); + expect(SignaturePredicate.fromPredicate(predicate).publicKey).toEqual(publicKey(alice)); + }); +}); diff --git a/tests/unit/lib/LineageVerificationTest.ts b/tests/unit/lib/LineageVerificationTest.ts new file mode 100644 index 0000000..1c6c66f --- /dev/null +++ b/tests/unit/lib/LineageVerificationTest.ts @@ -0,0 +1,140 @@ +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import type { IPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/IPredicate.js'; +import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; +import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; + +import { createLineage } from '../../../src/lib/LineageClient.js'; +import { + LINEAGE_TOKEN_TYPE, + LineageGenesisReason, + LineageRevision, + sealPredicate, +} from '../../../src/lib/LineagePayload.js'; +import { describeLineage, verifyLineage } from '../../../src/lib/LineageVerification.js'; +import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; +import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; +import { certifyMint } from '../../support/TimestampFixtures.js'; + +describe('LineageVerification', () => { + const aggregator = TestAggregatorClient.create(); + const client = new StateTransitionClient(aggregator); + const trustBase = aggregator.rootTrustBase; + const fast = { pollIntervalMs: 10, timeoutMs: 2_000 }; + + const alice = SigningService.generatePrivateKey(); + const bob = SigningService.generatePrivateKey(); + const publicKey = (key: Uint8Array): Uint8Array => new SigningService(key).publicKey; + + /** + * Mint a lineage-typed genesis with arbitrary fields and wrap it as a token, + * bypassing the issuance checks a real mint goes through. + */ + async function rawLineageToken( + recipient: IPredicate, + options: { data?: Uint8Array | null; justification?: Uint8Array | null; salt?: TokenSalt }, + ): Promise { + const genesis = await certifyMint(aggregator, recipient, { + salt: TokenSalt.generate(), + tokenType: LINEAGE_TOKEN_TYPE, + ...options, + }); + return Token.fromCBOR( + CborSerializer.encodeTag( + Token.CBOR_TAG, + CborSerializer.encodeArray( + CborSerializer.encodeUnsignedInteger(2n), + genesis.toCBOR(), + CborSerializer.encodeArray(), + ), + ), + ); + } + + /** A genesis with a valid issuer signature over `data`, minted to `recipient`. */ + async function signedGenesis(data: Uint8Array, recipient: IPredicate): Promise { + const salt = TokenSalt.generate(); + const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); + const reason = await LineageGenesisReason.sign(tokenId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); + return rawLineageToken(recipient, { data, justification: reason.toCBOR(), salt }); + } + + describe('genesis', () => { + it('rejects a genesis whose issuer signature covers another token', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const otherId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); + const reason = await LineageGenesisReason.sign(otherId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); + const token = await rawLineageToken(SignaturePredicate.create(publicKey(bob)), { + data, + justification: reason.toCBOR(), + }); + const result = await verifyLineage(token, trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Issuer signature in the genesis reason does not verify.'); + }); + + it('rejects a genesis without an issuer reason', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const token = await rawLineageToken(SignaturePredicate.create(publicKey(bob)), { data, justification: null }); + const result = await verifyLineage(token, trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Lineage genesis carries no issuer reason.'); + }); + + it('rejects a genesis that does not start at revision 0', async () => { + const data = LineageRevision.create(1n, TEST_DIGEST).toCBOR(); + const result = await verifyLineage( + await signedGenesis(data, SignaturePredicate.create(publicKey(bob))), + trustBase, + ); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Genesis revision index is 1, not 0.'); + }); + }); + + describe('seal', () => { + it('accepts a correctly formed seal at genesis', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const result = await verifyLineage(await signedGenesis(data, await sealPredicate(data)), trustBase); + expect(result.reason).toBeNull(); + expect(result.description.finalized).toBe(true); + }); + + it('rejects a seal that is not burned', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const result = await verifyLineage( + await signedGenesis(data, SignaturePredicate.create(publicKey(bob))), + trustBase, + ); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision 0 is a seal, but is not burned.'); + }); + + it('rejects a burn that is not a seal', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const result = await verifyLineage(await signedGenesis(data, await sealPredicate(data)), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision 0 is burned, but is not a seal.'); + }); + + it('rejects a seal whose burn reason commits to something else', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const other = LineageRevision.create(0n, OTHER_DIGEST, true).toCBOR(); + const result = await verifyLineage(await signedGenesis(data, await sealPredicate(other)), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision 0 is a seal, but its burn reason does not commit to it.'); + }); + }); + + it('describes revisions without verifying', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const description = describeLineage(genesis); + expect(description.tokenTypeIsLineage).toBe(true); + expect(description.finalized).toBe(false); + expect(description.revisions).toHaveLength(1); + expect(description.revisions[0].error).toBeNull(); + }); +}); From 6cb7d6f7fffbcd24beabcdb18903bd01197a1fa9 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:34:47 +0200 Subject: [PATCH 07/25] Split StampRevisionTest along the lines of the stamp tests - resolveStampRevisionConfig and parsePublicKey move to ConfigTest, next to resolveStampConfig and parsePrivateKey. - writeRevisionToken moves to StampRevisionWriteTest, the counterpart of StampWriteTest. - StampRevisionTest keeps stampRevisionWith. Co-Authored-By: Claude Opus 5.5 --- tests/unit/ConfigTest.ts | 128 ++++++++++++++++++++- tests/unit/StampRevisionTest.ts | 159 +-------------------------- tests/unit/StampRevisionWriteTest.ts | 44 ++++++++ 3 files changed, 173 insertions(+), 158 deletions(-) create mode 100644 tests/unit/StampRevisionWriteTest.ts diff --git a/tests/unit/ConfigTest.ts b/tests/unit/ConfigTest.ts index 63595c7..032ce2a 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -10,16 +10,25 @@ import { parseDigest, parseNetworkName, parsePrivateKey, + parsePublicKey, parseTimeoutSeconds, resolveDigest, resolveNetworkSelection, resolveStampConfig, + resolveStampRevisionConfig, resolveTrustBaseOverride, } from '../../src/config.js'; -import { CliError } from '../../src/errors.js'; +import { CliError, EXIT_USAGE } from '../../src/errors.js'; import { NETWORKS } from '../../src/lib/networks.js'; import { DEFAULT_TIMEOUT_MS } from '../../src/lib/TimestampClient.js'; -import { tempDir, TEST_DIGEST_HEX, TEST_PRIVATE_KEY_HEX, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; +import { + tempDir, + TEST_DIGEST, + TEST_DIGEST_HEX, + TEST_PRIVATE_KEY, + TEST_PRIVATE_KEY_HEX, + TEST_PUBLIC_KEY_HEX, +} from '../support/fixtures.js'; describe('parseDigest', () => { it('accepts upper and lower case with or without 0x', () => { @@ -45,6 +54,16 @@ describe('parsePrivateKey', () => { }); }); +describe('parsePublicKey', () => { + it('accepts a compressed key with or without 0x', () => { + expect(HexConverter.encode(parsePublicKey(`0x${TEST_PUBLIC_KEY_HEX}`))).toEqual(TEST_PUBLIC_KEY_HEX); + }); + + it('rejects a point that is not on the curve', () => { + expect(() => parsePublicKey(`02${'ff'.repeat(32)}`)).toThrow(/not a point/); + }); +}); + describe('parseNetworkName', () => { it('narrows known names and rejects the rest', () => { expect(parseNetworkName('mainnet')).toEqual('mainnet'); @@ -344,3 +363,108 @@ describe('resolveStampConfig', () => { expect(toStdout.out).toEqual('-'); }); }); + +describe('resolveStampRevisionConfig', () => { + const env = { UNICITY_API_KEY: 'key' }; + let directory: string; + let keyFile: string; + + beforeEach(async () => { + directory = await tempDir('proof-cli-revision-'); + keyFile = path.join(directory, 'producer.key'); + await writeFile(keyFile, `${TEST_PRIVATE_KEY_HEX}\n`); + }); + + const base = (): Record => ({ + keyFile, + recipientKey: TEST_PUBLIC_KEY_HEX, + tokenFile: path.join(directory, 'doc.lineage'), + }); + + it('resolves a new lineage', async () => { + const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), env); + expect(config.tokenBytes).toBeNull(); + expect(config.digest).toEqual(TEST_DIGEST); + expect(config.privateKey).toEqual(TEST_PRIVATE_KEY); + expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); + expect(config.network.preset).toEqual('mainnet'); + }); + + it('reads an existing token file and a recipient key file', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + await writeFile(tokenFile, 'abcd'); + const recipientKeyFile = path.join(directory, 'next.pub'); + await writeFile(recipientKeyFile, ` ${TEST_PUBLIC_KEY_HEX.toUpperCase()}\n`); + const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, { keyFile, recipientKeyFile, tokenFile }, env); + expect(config.tokenBytes).toEqual(new TextEncoder().encode('abcd')); + expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); + }); + + it('resolves --finalize to no next producer', async () => { + const config = await resolveStampRevisionConfig( + TEST_DIGEST_HEX, + { ...base(), finalize: true, recipientKey: undefined }, + env, + ); + expect(config.recipientKey).toBeNull(); + }); + + it.each([ + ['no digest source', undefined, {}, 'Pass a SHA-256 digest or --file .'], + ['both digest sources', TEST_DIGEST_HEX, { file: 'x' }, 'Pass either a digest or --file, not both.'], + ['no token file', TEST_DIGEST_HEX, { tokenFile: undefined }, /--token-file/], + ['no key file', TEST_DIGEST_HEX, { keyFile: undefined }, /--key-file/], + [ + 'no recipient', + TEST_DIGEST_HEX, + { recipientKey: undefined }, + /--recipient-key or --recipient-key-file, or pass --finalize/, + ], + [ + 'both recipients', + TEST_DIGEST_HEX, + { recipientKeyFile: 'x' }, + 'Pass only one of --recipient-key, --recipient-key-file and --finalize; got --recipient-key and --recipient-key-file.', + ], + [ + 'a recipient and --finalize', + TEST_DIGEST_HEX, + { finalize: true }, + 'Pass only one of --recipient-key, --recipient-key-file and --finalize; got --recipient-key and --finalize.', + ], + [ + 'a recipient file and --finalize', + TEST_DIGEST_HEX, + { finalize: true, recipientKey: undefined, recipientKeyFile: 'x' }, + /got --recipient-key-file and --finalize/, + ], + [ + 'all three', + TEST_DIGEST_HEX, + { finalize: true, recipientKeyFile: 'x' }, + /got --recipient-key and --recipient-key-file and --finalize/, + ], + ['a malformed recipient', TEST_DIGEST_HEX, { recipientKey: '04abcd' }, /compressed secp256k1 public key/], + [ + 'a missing recipient file', + TEST_DIGEST_HEX, + { recipientKey: undefined, recipientKeyFile: '/no/such' }, + /Cannot read/, + ], + ])('refuses %s', async (_, digest, overrides, message) => { + await expect(resolveStampRevisionConfig(digest, { ...base(), ...overrides }, env)).rejects.toMatchObject({ + exitCode: EXIT_USAGE, + }); + await expect(resolveStampRevisionConfig(digest, { ...base(), ...overrides }, env)).rejects.toThrow(message); + }); + + it('refuses a token file in a directory that does not exist', async () => { + await expect( + resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), tokenFile: path.join(directory, 'no', 'x') }, env), + ).rejects.toThrow(/Cannot write to the token file directory/); + }); + + it('requires an API key', async () => { + await expect(resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), {})).rejects.toThrow(/No API key/); + }); +}); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index bbb36d8..12377ed 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -1,4 +1,4 @@ -import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; +import { readdir, readFile } from 'node:fs/promises'; import path from 'node:path'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; @@ -6,8 +6,8 @@ import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/Sta import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; -import { stampRevisionWith, writeRevisionToken } from '../../src/commands/stampRevision.js'; -import { IStampRevisionConfig, parsePublicKey, resolveStampRevisionConfig } from '../../src/config.js'; +import { stampRevisionWith } from '../../src/commands/stampRevision.js'; +import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; import { testContext } from '../support/context.js'; @@ -18,127 +18,10 @@ import { TEST_DIGEST, TEST_DIGEST_HEX, TEST_PRIVATE_KEY, - TEST_PRIVATE_KEY_HEX, TEST_PUBLIC_KEY_HEX, } from '../support/fixtures.js'; import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; -const ENV = { UNICITY_API_KEY: 'key' }; - -describe('resolveStampRevisionConfig', () => { - let directory: string; - let keyFile: string; - - beforeEach(async () => { - directory = await tempDir('proof-cli-revision-'); - keyFile = path.join(directory, 'producer.key'); - await writeFile(keyFile, `${TEST_PRIVATE_KEY_HEX}\n`); - }); - - const base = (): Record => ({ - keyFile, - recipientKey: TEST_PUBLIC_KEY_HEX, - tokenFile: path.join(directory, 'doc.lineage'), - }); - - it('resolves a new lineage', async () => { - const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), ENV); - expect(config.tokenBytes).toBeNull(); - expect(config.digest).toEqual(TEST_DIGEST); - expect(config.privateKey).toEqual(TEST_PRIVATE_KEY); - expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); - expect(config.network.preset).toEqual('mainnet'); - }); - - it('reads an existing token file and a recipient key file', async () => { - const tokenFile = path.join(directory, 'doc.lineage'); - await writeFile(tokenFile, 'abcd'); - const recipientKeyFile = path.join(directory, 'next.pub'); - await writeFile(recipientKeyFile, ` ${TEST_PUBLIC_KEY_HEX.toUpperCase()}\n`); - const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, { keyFile, recipientKeyFile, tokenFile }, ENV); - expect(config.tokenBytes).toEqual(new TextEncoder().encode('abcd')); - expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); - }); - - it('resolves --finalize to no next producer', async () => { - const config = await resolveStampRevisionConfig( - TEST_DIGEST_HEX, - { ...base(), finalize: true, recipientKey: undefined }, - ENV, - ); - expect(config.recipientKey).toBeNull(); - }); - - it.each([ - ['no digest source', undefined, {}, 'Pass a SHA-256 digest or --file .'], - ['both digest sources', TEST_DIGEST_HEX, { file: 'x' }, 'Pass either a digest or --file, not both.'], - ['no token file', TEST_DIGEST_HEX, { tokenFile: undefined }, /--token-file/], - ['no key file', TEST_DIGEST_HEX, { keyFile: undefined }, /--key-file/], - [ - 'no recipient', - TEST_DIGEST_HEX, - { recipientKey: undefined }, - /--recipient-key or --recipient-key-file, or pass --finalize/, - ], - [ - 'both recipients', - TEST_DIGEST_HEX, - { recipientKeyFile: 'x' }, - 'Pass only one of --recipient-key, --recipient-key-file and --finalize; got --recipient-key and --recipient-key-file.', - ], - [ - 'a recipient and --finalize', - TEST_DIGEST_HEX, - { finalize: true }, - 'Pass only one of --recipient-key, --recipient-key-file and --finalize; got --recipient-key and --finalize.', - ], - [ - 'a recipient file and --finalize', - TEST_DIGEST_HEX, - { finalize: true, recipientKey: undefined, recipientKeyFile: 'x' }, - /got --recipient-key-file and --finalize/, - ], - [ - 'all three', - TEST_DIGEST_HEX, - { finalize: true, recipientKeyFile: 'x' }, - /got --recipient-key and --recipient-key-file and --finalize/, - ], - ['a malformed recipient', TEST_DIGEST_HEX, { recipientKey: '04abcd' }, /compressed secp256k1 public key/], - [ - 'a missing recipient file', - TEST_DIGEST_HEX, - { recipientKey: undefined, recipientKeyFile: '/no/such' }, - /Cannot read/, - ], - ])('refuses %s', async (_, digest, overrides, message) => { - await expect(resolveStampRevisionConfig(digest, { ...base(), ...overrides }, ENV)).rejects.toMatchObject({ - exitCode: EXIT_USAGE, - }); - await expect(resolveStampRevisionConfig(digest, { ...base(), ...overrides }, ENV)).rejects.toThrow(message); - }); - - it('refuses a token file in a directory that does not exist', async () => { - await expect( - resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), tokenFile: path.join(directory, 'no', 'x') }, ENV), - ).rejects.toThrow(/Cannot write to the token file directory/); - }); - - it('requires an API key', async () => { - await expect(resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), {})).rejects.toThrow(/No API key/); - }); -}); - -describe('parsePublicKey', () => { - it('accepts a compressed key with or without 0x', () => { - expect(HexConverter.encode(parsePublicKey(`0x${TEST_PUBLIC_KEY_HEX}`))).toEqual(TEST_PUBLIC_KEY_HEX); - }); - - it('rejects a point that is not on the curve', () => { - expect(() => parsePublicKey(`02${'ff'.repeat(32)}`)).toThrow(/not a point/); - }); -}); - describe('stampRevisionWith', () => { const aggregator = TestAggregatorClient.create(); const client = new StateTransitionClient(aggregator); @@ -277,39 +160,3 @@ describe('stampRevisionWith', () => { expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_VERIFICATION_FAILED); }); }); - -describe('writeRevisionToken', () => { - const TOKEN = new Uint8Array([0xd9, 0x01, 0x00, 0x82, 0x01, 0x02]); - - it('replaces an existing file without leaving a temporary behind', async () => { - const directory = await tempDir('proof-cli-revision-'); - const out = path.join(directory, 'doc.lineage'); - await writeFile(out, 'old'); - const sink = testContext(); - await writeRevisionToken(out, TOKEN, false, sink.context); - expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); - expect(await readdir(directory)).toEqual(['doc.lineage']); - expect(sink.stderr()).toEqual(''); - }); - - it('never clobbers a file that appeared before a new lineage was written, and prints the token', async () => { - const directory = await tempDir('proof-cli-revision-'); - const out = path.join(directory, 'doc.lineage'); - await writeFile(out, 'someone else'); - const sink = testContext(); - await expect(writeRevisionToken(out, TOKEN, true, sink.context)).rejects.toThrow(/EEXIST/); - expect(await readFile(out, 'utf8')).toEqual('someone else'); - expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); - }); - - it('prints the token when the directory is gone', async () => { - const directory = await tempDir('proof-cli-revision-'); - await mkdir(path.join(directory, 'sub')); - const sink = testContext(); - await expect( - writeRevisionToken(path.join(directory, 'missing', 'doc.lineage'), TOKEN, false, sink.context), - ).rejects.toThrow(/ENOENT/); - expect(sink.stderr()).toContain('the revision was certified'); - expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); - }); -}); diff --git a/tests/unit/StampRevisionWriteTest.ts b/tests/unit/StampRevisionWriteTest.ts new file mode 100644 index 0000000..116f490 --- /dev/null +++ b/tests/unit/StampRevisionWriteTest.ts @@ -0,0 +1,44 @@ +import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { writeRevisionToken } from '../../src/commands/stampRevision.js'; +import { testContext } from '../support/context.js'; +import { tempDir } from '../support/fixtures.js'; + +describe('writeRevisionToken', () => { + const TOKEN = new Uint8Array([0xd9, 0x01, 0x00, 0x82, 0x01, 0x02]); + + it('replaces an existing file without leaving a temporary behind', async () => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + await writeFile(out, 'old'); + const sink = testContext(); + await writeRevisionToken(out, TOKEN, false, sink.context); + expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(sink.stderr()).toEqual(''); + }); + + it('never clobbers a file that appeared before a new lineage was written, and prints the token', async () => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + await writeFile(out, 'someone else'); + const sink = testContext(); + await expect(writeRevisionToken(out, TOKEN, true, sink.context)).rejects.toThrow(/EEXIST/); + expect(await readFile(out, 'utf8')).toEqual('someone else'); + expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); + }); + + it('prints the token when the directory is gone', async () => { + const directory = await tempDir('proof-cli-revision-'); + await mkdir(path.join(directory, 'sub')); + const sink = testContext(); + await expect( + writeRevisionToken(path.join(directory, 'missing', 'doc.lineage'), TOKEN, false, sink.context), + ).rejects.toThrow(/ENOENT/); + expect(sink.stderr()).toContain('the revision was certified'); + expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); + }); +}); From 4eb276211872ff49975dd9f6577802d1ab454104 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:39:23 +0200 Subject: [PATCH 08/25] Split LineageCommandsTest into VerifyTest and InspectTest The lineage cases of `verify` join VerifyTest and those of `inspect` go to a new InspectTest, so each command's tests live in one file. The finalized lineage case, which checked both commands, becomes one test in each. The shared lineage (three revisions, plus a finalized copy) is built by tests/support/LineageFixtures.ts, next to TimestampFixtures.ts. Co-Authored-By: Claude Opus 5.5 --- tests/support/LineageFixtures.ts | 67 ++++++++++ tests/unit/InspectTest.ts | 47 +++++++ tests/unit/LineageCommandsTest.ts | 210 ------------------------------ tests/unit/VerifyTest.ts | 117 ++++++++++++++++- 4 files changed, 229 insertions(+), 212 deletions(-) create mode 100644 tests/support/LineageFixtures.ts create mode 100644 tests/unit/InspectTest.ts delete mode 100644 tests/unit/LineageCommandsTest.ts diff --git a/tests/support/LineageFixtures.ts b/tests/support/LineageFixtures.ts new file mode 100644 index 0000000..412d566 --- /dev/null +++ b/tests/support/LineageFixtures.ts @@ -0,0 +1,67 @@ +import { writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; +import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { tempDir, OTHER_DIGEST, TEST_DIGEST, TEST_PRIVATE_KEY, TEST_PUBLIC_KEY_HEX } from './fixtures.js'; +import { TestAggregatorClient } from './TestAggregatorClient.js'; +import { appendRevision, createLineage } from '../../src/lib/LineageClient.js'; + +/** Digest of revision 2 of the fixture lineage. */ +export const THIRD_DIGEST_HEX = 'ab'.repeat(32); + +/** Digest of the seal, revision 3, of the finalized fixture lineage. */ +export const SEAL_DIGEST_HEX = 'cd'.repeat(32); + +export interface ILineageFixture { + readonly bobPublicHex: string; + /** The finalized lineage: {@link token} with a seal appended by bob. */ + readonly sealedFile: string; + /** Three revisions: 0 by the issuer naming bob, 1 by bob naming the issuer, 2 by the issuer naming bob. */ + readonly token: Token; + readonly tokenFile: string; + /** Trust base of the in-memory aggregator, whose network id matches no bundled pin. */ + readonly trustBaseFile: string; +} + +/** + * Certify a document lineage on a fresh in-memory aggregator and write it, a + * finalized copy of it, and the aggregator's trust base to a temporary directory. + * + * @returns {Promise} Paths and the open lineage token. + */ +export async function createLineageFixture(): Promise { + const aggregator = TestAggregatorClient.create(); + const client = new StateTransitionClient(aggregator); + const trustBase = aggregator.rootTrustBase; + const fast = { pollIntervalMs: 10, timeoutMs: 2_000 }; + const bob = SigningService.generatePrivateKey(); + const bobPublic = new SigningService(bob).publicKey; + const issuerPublic = HexConverter.decode(TEST_PUBLIC_KEY_HEX); + + const genesis = await createLineage(client, trustBase, TEST_DIGEST, TEST_PRIVATE_KEY, bobPublic, fast); + const first = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, issuerPublic, fast); + const token = await appendRevision( + client, + trustBase, + first, + HexConverter.decode(THIRD_DIGEST_HEX), + TEST_PRIVATE_KEY, + bobPublic, + fast, + ); + const sealed = await appendRevision(client, trustBase, token, HexConverter.decode(SEAL_DIGEST_HEX), bob, null, fast); + + const directory = await tempDir('proof-cli-lineage-'); + const tokenFile = path.join(directory, 'doc.lineage'); + await writeFile(tokenFile, token.toCBOR()); + const sealedFile = path.join(directory, 'sealed.lineage'); + await writeFile(sealedFile, sealed.toCBOR()); + const trustBaseFile = path.join(directory, 'trust-base.json'); + await writeFile(trustBaseFile, JSON.stringify(trustBase.toJSON())); + + return { bobPublicHex: HexConverter.encode(bobPublic), sealedFile, token, tokenFile, trustBaseFile }; +} diff --git a/tests/unit/InspectTest.ts b/tests/unit/InspectTest.ts new file mode 100644 index 0000000..c84b028 --- /dev/null +++ b/tests/unit/InspectTest.ts @@ -0,0 +1,47 @@ +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { runInspect } from '../../src/commands/inspect.js'; +import { EXIT_OK } from '../../src/errors.js'; +import { testContext } from '../support/context.js'; +import { TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; +import { createLineageFixture, ILineageFixture } from '../support/LineageFixtures.js'; + +describe('runInspect on a document lineage', () => { + let fixture: ILineageFixture; + + beforeAll(async () => { + fixture = await createLineageFixture(); + }); + + it('inspects the lineage without verifying it', async () => { + const text = testContext(); + expect(await runInspect(fixture.tokenFile, text.context)).toBe(EXIT_OK); + expect(text.stdout()).toMatch(/^UNVERIFIED {5}/); + expect(text.stdout()).toContain('Revisions 3\n'); + + const json = testContext({ json: true }); + expect(await runInspect(fixture.tokenFile, json.context)).toBe(EXIT_OK); + const output = json.json() as { revisions: { index: string; signer: string }[] }; + expect(output).toMatchObject({ + command: 'inspect', + finalized: false, + issuer: TEST_PUBLIC_KEY_HEX, + network: { id: 3 }, + nextProducer: fixture.bobPublicHex, + tokenId: HexConverter.encode(fixture.token.id.bytes), + tokenType: 'lineage', + verified: false, + }); + expect(output.revisions.map((revision) => [revision.index, revision.signer])).toEqual([ + ['0', TEST_PUBLIC_KEY_HEX], + ['1', fixture.bobPublicHex], + ['2', TEST_PUBLIC_KEY_HEX], + ]); + }); + + it('inspects a finalized lineage and says so', async () => { + const json = testContext({ json: true }); + expect(await runInspect(fixture.sealedFile, json.context)).toBe(EXIT_OK); + expect(json.json()).toMatchObject({ finalized: true, nextProducer: null, verified: false }); + }); +}); diff --git a/tests/unit/LineageCommandsTest.ts b/tests/unit/LineageCommandsTest.ts deleted file mode 100644 index aad66a6..0000000 --- a/tests/unit/LineageCommandsTest.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { writeFile } from 'node:fs/promises'; -import path from 'node:path'; - -import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; -import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; -import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; -import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; - -import { runInspect } from '../../src/commands/inspect.js'; -import { runVerify } from '../../src/commands/verify.js'; -import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; -import { appendRevision, createLineage } from '../../src/lib/LineageClient.js'; -import { testContext } from '../support/context.js'; -import { - OTHER_DIGEST, - OTHER_DIGEST_HEX, - tempDir, - TEST_DIGEST, - TEST_DIGEST_HEX, - TEST_PRIVATE_KEY, - TEST_PUBLIC_KEY_HEX, -} from '../support/fixtures.js'; -import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; - -const THIRD_DIGEST_HEX = 'ab'.repeat(32); - -describe('verify and inspect on a document lineage', () => { - const aggregator = TestAggregatorClient.create(); - const client = new StateTransitionClient(aggregator); - const fast = { pollIntervalMs: 10, timeoutMs: 2_000 }; - const bob = SigningService.generatePrivateKey(); - const bobPublicHex = HexConverter.encode(new SigningService(bob).publicKey); - let directory: string; - let tokenFile: string; - let trustBaseFile: string; - let token: Token; - - beforeAll(async () => { - directory = await tempDir('proof-cli-lineage-'); - // Revision 0 by the issuer naming bob, then revision 1 by bob naming the issuer, then 2 by the issuer naming bob. - const genesis = await createLineage( - client, - aggregator.rootTrustBase, - TEST_DIGEST, - TEST_PRIVATE_KEY, - new SigningService(bob).publicKey, - fast, - ); - const first = await appendRevision( - client, - aggregator.rootTrustBase, - genesis, - OTHER_DIGEST, - bob, - HexConverter.decode(TEST_PUBLIC_KEY_HEX), - fast, - ); - token = await appendRevision( - client, - aggregator.rootTrustBase, - first, - HexConverter.decode(THIRD_DIGEST_HEX), - TEST_PRIVATE_KEY, - new SigningService(bob).publicKey, - fast, - ); - tokenFile = path.join(directory, 'doc.lineage'); - await writeFile(tokenFile, token.toCBOR()); - trustBaseFile = path.join(directory, 'trust-base.json'); - await writeFile(trustBaseFile, JSON.stringify(aggregator.rootTrustBase.toJSON())); - }); - - it('verifies a finalized lineage and says so', async () => { - const sealed = await appendRevision( - client, - aggregator.rootTrustBase, - token, - HexConverter.decode('cd'.repeat(32)), - bob, - null, - fast, - ); - const sealedFile = path.join(directory, 'sealed.lineage'); - await writeFile(sealedFile, sealed.toCBOR()); - - const sink = testContext(); - expect(await runVerify(sealedFile, { hash: 'cd'.repeat(32), trustBase: trustBaseFile }, sink.context)).toBe( - EXIT_OK, - ); - const out = sink.stdout(); - expect(out).toContain('Next producer none; the lineage is finalized (sealed and burned)\n'); - expect(out).toContain(`Revision 3 SHA-256 ${'cd'.repeat(32)} (final)\n Signed by ${bobPublicHex}\n`); - expect(out).toContain(' Passes to nobody; sealed and burned\n'); - expect(out).toContain('Expected hash matches revision 3 (the final)'); - - const json = testContext({ json: true }); - expect(await runVerify(sealedFile, { trustBase: trustBaseFile }, json.context)).toBe(EXIT_OK); - expect(json.json()).toMatchObject({ finalized: true, nextProducer: null, status: 'OK' }); - expect((json.json() as { revisions: { sealed: boolean }[] }).revisions.map((entry) => entry.sealed)).toEqual([ - false, - false, - false, - true, - ]); - - const inspected = testContext({ json: true }); - expect(await runInspect(sealedFile, inspected.context)).toBe(EXIT_OK); - expect(inspected.json()).toMatchObject({ finalized: true, verified: false }); - }); - - it('verifies the lineage and lists every revision', async () => { - const sink = testContext(); - expect(await runVerify(tokenFile, { trustBase: trustBaseFile }, sink.context)).toBe(EXIT_OK); - const out = sink.stdout(); - expect(out).toMatch( - /^Status {9}OK {2}\(inclusion proofs, consensus signatures, issuer signature and revision chain/, - ); - expect(out).toContain('Token type document lineage\n'); - expect(out).toContain(`Issuer ${TEST_PUBLIC_KEY_HEX}\n`); - expect(out).toContain('Revisions 3\n'); - expect(out).toContain(`Next producer ${bobPublicHex}\n`); - expect(out).toContain(`Revision 0 SHA-256 ${TEST_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); - expect(out).toContain(`Revision 1 SHA-256 ${OTHER_DIGEST_HEX}\n Signed by ${bobPublicHex}\n`); - expect(out).toContain(`Revision 2 SHA-256 ${THIRD_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); - expect(out).toContain(` Passes to ${bobPublicHex}\n Certified at`); - expect(out).toContain('Expected hash not checked; pass --file or --hash'); - }); - - it('finds an expected hash among the revisions', async () => { - const latest = testContext(); - await runVerify(tokenFile, { hash: THIRD_DIGEST_HEX, trustBase: trustBaseFile }, latest.context); - expect(latest.stdout()).toContain('Expected hash matches revision 2 (the latest)\n'); - - const older = testContext({ json: true }); - expect(await runVerify(tokenFile, { hash: OTHER_DIGEST_HEX, trustBase: trustBaseFile }, older.context)).toBe( - EXIT_OK, - ); - expect(older.json()).toMatchObject({ - command: 'verify', - expectedHashMatches: true, - matchingRevisions: [1], - status: 'OK', - tokenType: 'lineage', - }); - - const text = testContext(); - await runVerify(tokenFile, { hash: OTHER_DIGEST_HEX, trustBase: trustBaseFile }, text.context); - expect(text.stdout()).toContain('Expected hash matches revision 1; superseded by revision 2\n'); - }); - - it('fails on a hash no revision carries', async () => { - const sink = testContext({ json: true }); - expect(await runVerify(tokenFile, { hash: 'cd'.repeat(32), trustBase: trustBaseFile }, sink.context)).toBe( - EXIT_VERIFICATION_FAILED, - ); - expect(sink.json()).toMatchObject({ - expectedHashMatches: false, - matchingRevisions: [], - reason: 'Hash mismatch: no revision of the lineage certifies this digest.', - status: 'FAIL', - }); - }); - - it('fails against the wrong trust base', async () => { - const sink = testContext({ json: true }); - expect(await runVerify(tokenFile, { network: 'testnet2' }, sink.context)).toBe(EXIT_VERIFICATION_FAILED); - expect(sink.json()).toMatchObject({ - matchingRevisions: null, - reason: 'The token is for network 3 and the trust base for network 4.', - status: 'FAIL', - trustBase: { bundledNetwork: 'testnet2', source: 'bundled' }, - }); - }); - - it('reports a network it cannot place as a lineage failure', async () => { - const sink = testContext({ json: true }); - expect(await runVerify(tokenFile, {}, sink.context)).toBe(EXIT_VERIFICATION_FAILED); - expect(sink.json()).toMatchObject({ - reason: 'unknown network id 3; pass --trust-base', - status: 'FAIL', - tokenType: 'lineage', - trustBase: null, - }); - }); - - it('inspects the lineage without verifying it', async () => { - const text = testContext(); - expect(await runInspect(tokenFile, text.context)).toBe(EXIT_OK); - expect(text.stdout()).toMatch(/^UNVERIFIED {5}/); - expect(text.stdout()).toContain('Revisions 3\n'); - - const json = testContext({ json: true }); - expect(await runInspect(tokenFile, json.context)).toBe(EXIT_OK); - const output = json.json() as { revisions: { index: string; signer: string }[] }; - expect(output).toMatchObject({ - command: 'inspect', - issuer: TEST_PUBLIC_KEY_HEX, - network: { id: 3 }, - nextProducer: bobPublicHex, - tokenId: HexConverter.encode(token.id.bytes), - tokenType: 'lineage', - verified: false, - }); - expect(output.revisions.map((revision) => [revision.index, revision.signer])).toEqual([ - ['0', TEST_PUBLIC_KEY_HEX], - ['1', bobPublicHex], - ['2', TEST_PUBLIC_KEY_HEX], - ]); - }); -}); diff --git a/tests/unit/VerifyTest.ts b/tests/unit/VerifyTest.ts index 937ddea..d5d0da1 100644 --- a/tests/unit/VerifyTest.ts +++ b/tests/unit/VerifyTest.ts @@ -4,10 +4,16 @@ import path from 'node:path'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { runVerify } from '../../src/commands/verify.js'; -import { EXIT_USAGE, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; +import { EXIT_OK, EXIT_USAGE, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; import { stampWith } from '../../src/lib/TimestampClient.js'; import { testContext } from '../support/context.js'; -import { tempDir, TEST_DIGEST, TEST_DIGEST_HEX } from '../support/fixtures.js'; +import { OTHER_DIGEST_HEX, tempDir, TEST_DIGEST, TEST_DIGEST_HEX, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; +import { + createLineageFixture, + ILineageFixture, + SEAL_DIGEST_HEX, + THIRD_DIGEST_HEX, +} from '../support/LineageFixtures.js'; import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; // The in-memory aggregator's network id matches no bundled pin, which is the @@ -42,3 +48,110 @@ describe('runVerify on a token whose network has no bundled pin', () => { ).rejects.toMatchObject({ exitCode: EXIT_USAGE, message: 'Pass either --hash or --file, not both.' }); }); }); + +describe('runVerify on a document lineage', () => { + let fixture: ILineageFixture; + + beforeAll(async () => { + fixture = await createLineageFixture(); + }); + + it('verifies a finalized lineage and says so', async () => { + const sink = testContext(); + expect( + await runVerify(fixture.sealedFile, { hash: SEAL_DIGEST_HEX, trustBase: fixture.trustBaseFile }, sink.context), + ).toBe(EXIT_OK); + const out = sink.stdout(); + expect(out).toContain('Next producer none; the lineage is finalized (sealed and burned)\n'); + expect(out).toContain( + `Revision 3 SHA-256 ${SEAL_DIGEST_HEX} (final)\n Signed by ${fixture.bobPublicHex}\n`, + ); + expect(out).toContain(' Passes to nobody; sealed and burned\n'); + expect(out).toContain('Expected hash matches revision 3 (the final)'); + + const json = testContext({ json: true }); + expect(await runVerify(fixture.sealedFile, { trustBase: fixture.trustBaseFile }, json.context)).toBe(EXIT_OK); + expect(json.json()).toMatchObject({ finalized: true, nextProducer: null, status: 'OK' }); + expect((json.json() as { revisions: { sealed: boolean }[] }).revisions.map((entry) => entry.sealed)).toEqual([ + false, + false, + false, + true, + ]); + }); + + it('verifies the lineage and lists every revision', async () => { + const sink = testContext(); + expect(await runVerify(fixture.tokenFile, { trustBase: fixture.trustBaseFile }, sink.context)).toBe(EXIT_OK); + const out = sink.stdout(); + expect(out).toMatch( + /^Status {9}OK {2}\(inclusion proofs, consensus signatures, issuer signature and revision chain/, + ); + expect(out).toContain('Token type document lineage\n'); + expect(out).toContain(`Issuer ${TEST_PUBLIC_KEY_HEX}\n`); + expect(out).toContain('Revisions 3\n'); + expect(out).toContain(`Next producer ${fixture.bobPublicHex}\n`); + expect(out).toContain(`Revision 0 SHA-256 ${TEST_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); + expect(out).toContain(`Revision 1 SHA-256 ${OTHER_DIGEST_HEX}\n Signed by ${fixture.bobPublicHex}\n`); + expect(out).toContain(`Revision 2 SHA-256 ${THIRD_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); + expect(out).toContain(` Passes to ${fixture.bobPublicHex}\n Certified at`); + expect(out).toContain('Expected hash not checked; pass --file or --hash'); + }); + + it('finds an expected hash among the revisions', async () => { + const latest = testContext(); + await runVerify(fixture.tokenFile, { hash: THIRD_DIGEST_HEX, trustBase: fixture.trustBaseFile }, latest.context); + expect(latest.stdout()).toContain('Expected hash matches revision 2 (the latest)\n'); + + const older = testContext({ json: true }); + expect( + await runVerify(fixture.tokenFile, { hash: OTHER_DIGEST_HEX, trustBase: fixture.trustBaseFile }, older.context), + ).toBe(EXIT_OK); + expect(older.json()).toMatchObject({ + command: 'verify', + expectedHashMatches: true, + matchingRevisions: [1], + status: 'OK', + tokenType: 'lineage', + }); + + const text = testContext(); + await runVerify(fixture.tokenFile, { hash: OTHER_DIGEST_HEX, trustBase: fixture.trustBaseFile }, text.context); + expect(text.stdout()).toContain('Expected hash matches revision 1; superseded by revision 2\n'); + }); + + it('fails on a hash no revision carries', async () => { + const sink = testContext({ json: true }); + expect( + await runVerify(fixture.tokenFile, { hash: 'ef'.repeat(32), trustBase: fixture.trustBaseFile }, sink.context), + ).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.json()).toMatchObject({ + expectedHashMatches: false, + matchingRevisions: [], + reason: 'Hash mismatch: no revision of the lineage certifies this digest.', + status: 'FAIL', + }); + }); + + it('fails against the wrong trust base', async () => { + const sink = testContext({ json: true }); + expect(await runVerify(fixture.tokenFile, { network: 'testnet2' }, sink.context)).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.json()).toMatchObject({ + matchingRevisions: null, + reason: 'The token is for network 3 and the trust base for network 4.', + status: 'FAIL', + trustBase: { bundledNetwork: 'testnet2', source: 'bundled' }, + }); + }); + + it('reports a network it cannot place as a lineage failure', async () => { + const sink = testContext({ json: true }); + expect(await runVerify(fixture.tokenFile, {}, sink.context)).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.json()).toMatchObject({ + reason: 'unknown network id 3; pass --trust-base', + status: 'FAIL', + tokenType: 'lineage', + trustBase: null, + }); + }); +}); From ffee4d9eaf9fe9a9248fc1031e61468e6b7f9de1 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:43:05 +0200 Subject: [PATCH 09/25] Split OutputTest by command OutputTest keeps the shared helpers (time and network labels, line, the not-a-token envelope, warnings, the result tree). Each command's views move to that command's tests: keygen output to KeygenTest, the timestamp verify and inspect views to VerifyTest and InspectTest, and the stamp views to a new StampTest, the counterpart of StampRevisionTest. The stamped token they use comes from createTimestampToken in TimestampFixtures. Co-Authored-By: Claude Opus 5.5 --- tests/support/TimestampFixtures.ts | 14 +++- tests/unit/InspectTest.ts | 23 ++++++- tests/unit/KeygenTest.ts | 14 ++++ tests/unit/OutputTest.ts | 100 ----------------------------- tests/unit/StampTest.ts | 35 ++++++++++ tests/unit/VerifyTest.ts | 45 +++++++++++++ 6 files changed, 129 insertions(+), 102 deletions(-) create mode 100644 tests/unit/StampTest.ts diff --git a/tests/support/TimestampFixtures.ts b/tests/support/TimestampFixtures.ts index e4e1929..7a579b4 100644 --- a/tests/support/TimestampFixtures.ts +++ b/tests/support/TimestampFixtures.ts @@ -4,10 +4,11 @@ import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/Sta import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; import type { IMintOptions } from '@unicitylabs/state-transition-sdk/lib/transaction/IMintOptions.js'; import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { TestAggregatorClient } from './TestAggregatorClient.js'; import { TIMESTAMP_RECIPIENT, TIMESTAMP_TOKEN_TYPE } from '../../src/lib/constants.js'; -import { certifyMintTransaction } from '../../src/lib/TimestampClient.js'; +import { certifyMintTransaction, stampWith } from '../../src/lib/TimestampClient.js'; import { createVerificationContext } from '../../src/lib/verification.js'; /** @@ -31,3 +32,14 @@ export async function certifyMint( { pollIntervalMs: 10 }, ); } + +/** + * Stamp `digest` anonymously through `aggregator`, as `stamp` would, and return + * the verified token. + */ +export function createTimestampToken(aggregator: TestAggregatorClient, digest: Uint8Array): Promise { + return stampWith(new StateTransitionClient(aggregator), aggregator.rootTrustBase, digest, { + pollIntervalMs: 10, + timeoutMs: 2_000, + }); +} diff --git a/tests/unit/InspectTest.ts b/tests/unit/InspectTest.ts index c84b028..59ae83b 100644 --- a/tests/unit/InspectTest.ts +++ b/tests/unit/InspectTest.ts @@ -2,9 +2,13 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { runInspect } from '../../src/commands/inspect.js'; import { EXIT_OK } from '../../src/errors.js'; +import { describeToken } from '../../src/lib/TimestampVerification.js'; +import { descriptionJson, inspectText } from '../../src/output.js'; import { testContext } from '../support/context.js'; -import { TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; +import { TEST_DIGEST, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; import { createLineageFixture, ILineageFixture } from '../support/LineageFixtures.js'; +import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; +import { createTimestampToken } from '../support/TimestampFixtures.js'; describe('runInspect on a document lineage', () => { let fixture: ILineageFixture; @@ -45,3 +49,20 @@ describe('runInspect on a document lineage', () => { expect(json.json()).toMatchObject({ finalized: true, nextProducer: null, verified: false }); }); }); + +describe('inspect output for a timestamp', () => { + it('shows the fields under an UNVERIFIED banner', async () => { + const description = describeToken(await createTimestampToken(TestAggregatorClient.create(), TEST_DIGEST)); + const inspected = inspectText(description); + expect(inspected.startsWith('UNVERIFIED')).toBe(true); + expect(inspected).toContain('Token type timestamp'); + expect(inspected).toContain('Recipient timestamp burn predicate'); + expect(descriptionJson(description).transferCount).toBe(0); + + // `referenceTimeIso` is typed as an ISO string, so the sentinel for a time + // no Date can hold belongs in the text output only. + const hostileTime = { ...description, referenceTime: 10n ** 30n }; + expect(descriptionJson(hostileTime).referenceTimeIso).toBeNull(); + expect(inspectText(hostileTime)).toContain('out of range (1000000000000000000000000000000)'); + }); +}); diff --git a/tests/unit/KeygenTest.ts b/tests/unit/KeygenTest.ts index 39e70f5..775ba5b 100644 --- a/tests/unit/KeygenTest.ts +++ b/tests/unit/KeygenTest.ts @@ -2,6 +2,7 @@ import { chmod, readdir, readFile, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { runKeygen } from '../../src/commands/keygen.js'; +import { keygenJson, keygenText } from '../../src/output.js'; import { testContext } from '../support/context.js'; import { tempDir } from '../support/fixtures.js'; @@ -63,3 +64,16 @@ describe('runKeygen when the staged write cannot complete', () => { expect(await readFile(out, 'utf8')).toEqual('placeholder\n'); }); }); + +describe('keygen output', () => { + it('reports the key file and public key, and the private key only when printed', () => { + expect(keygenText('/k', '02ab')).toEqual('Key written /k (mode 0600)\nPublic key 02ab'); + expect(keygenJson('/k', '02ab')).toEqual({ command: 'keygen', out: '/k', publicKey: '02ab' }); + expect(keygenJson(null, '02ab', 'ff')).toEqual({ + command: 'keygen', + out: null, + privateKey: 'ff', + publicKey: '02ab', + }); + }); +}); diff --git a/tests/unit/OutputTest.ts b/tests/unit/OutputTest.ts index a015160..ad1cb0e 100644 --- a/tests/unit/OutputTest.ts +++ b/tests/unit/OutputTest.ts @@ -1,30 +1,16 @@ -import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; -import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; -import { stampWith } from '../../src/lib/TimestampClient.js'; -import { describeToken, verify } from '../../src/lib/TimestampVerification.js'; import { - descriptionJson, formatIso, - inspectText, - keygenJson, - keygenText, line, networkLabel, notATokenJson, notATokenText, resultTreeJson, - stampJson, - stampText, toIso, - verifyJson, - verifyText, warningLine, } from '../../src/output.js'; -import { TEST_DIGEST, TEST_DIGEST_HEX } from '../support/fixtures.js'; -import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; describe('formatIso', () => { it('reports an unrepresentable time instead of throwing', () => { @@ -57,14 +43,6 @@ describe('output', () => { expect(line('Status', 'OK')).toEqual('Status OK'); expect(notATokenText('not a token (x)')).toEqual('Status FAIL: not a token (x)'); expect(notATokenJson('inspect', 'bad')).toEqual({ command: 'inspect', reason: 'bad', status: 'FAIL' }); - expect(keygenText('/k', '02ab')).toEqual('Key written /k (mode 0600)\nPublic key 02ab'); - expect(keygenJson('/k', '02ab')).toEqual({ command: 'keygen', out: '/k', publicKey: '02ab' }); - expect(keygenJson(null, '02ab', 'ff')).toEqual({ - command: 'keygen', - out: null, - privateKey: 'ff', - publicKey: '02ab', - }); expect(warningLine('careful')).toEqual('warning: careful\n'); }); @@ -79,82 +57,4 @@ describe('output', () => { status: 'FAIL', }); }); - - describe('with a real token', () => { - const aggregator = TestAggregatorClient.create(); - const client = new StateTransitionClient(aggregator); - const trustBase = aggregator.rootTrustBase; - - it('renders stamp, verify and inspect views consistently', async () => { - const token = await stampWith(client, trustBase, TEST_DIGEST, { pollIntervalMs: 10, timeoutMs: 2000 }); - const description = describeToken(token); - const tokenIdHex = HexConverter.encode(token.id.bytes); - - const text = stampText(description, 'http://gateway.local', '/tmp/x.cbor'); - expect(text).toContain(`Stamped SHA-256 ${TEST_DIGEST_HEX}`); - expect(text).toContain('Network unknown network (3) via http://gateway.local'); - expect(text).toContain('Signer none (anonymous stamp)'); - expect(text).toContain(`Token id ${tokenIdHex}`); - expect(text).toContain('Written /tmp/x.cbor'); - expect(stampText(description, 'http://gateway.local', null)).not.toContain('Written'); - - const json = stampJson(description, 'http://gateway.local', '/tmp/x.cbor', token.toCBOR()); - expect(json).toMatchObject({ - command: 'stamp', - hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, - network: { gateway: 'http://gateway.local', id: 3, name: 'unknown' }, - out: '/tmp/x.cbor', - signer: null, - token: HexConverter.encode(token.toCBOR()), - tokenId: tokenIdHex, - }); - expect(typeof json.referenceTime).toBe('string'); - - const bundled = { kind: 'bundled', network: 'testnet2' } as const; - const ok = await verify(token, trustBase, { expectedDigest: TEST_DIGEST }); - expect(verifyText(ok, bundled)).toContain( - 'Status OK (inclusion proof, consensus signatures and payload verified against the bundled testnet2 trust base)', - ); - expect(verifyText(ok, bundled)).toContain('Trust base bundled testnet2 pin'); - expect(verifyText(ok, bundled)).toContain('Expected hash matches'); - const unchecked = await verify(token, trustBase); - expect(verifyText(unchecked, bundled)).toContain('Expected hash not checked; pass --file or --hash'); - expect(verifyJson(ok, bundled)).toMatchObject({ - command: 'verify', - expectedHashMatches: true, - reason: null, - status: 'OK', - trustBase: { bundledNetwork: 'testnet2', path: null, source: 'bundled' }, - }); - expect(verifyJson(ok, bundled).details?.status).toEqual('OK'); - - // No trust base could be selected at all, which is how `verify` reports a - // token whose network id matches no bundled pin. - expect(verifyText(ok, null)).toContain('Trust base none selected'); - expect(verifyJson(ok, null).trustBase).toBeNull(); - - // An override must never be able to present itself as the bundled pin. - const override = { kind: 'file', path: '/tmp/rogue.json' } as const; - expect(verifyText(ok, override)).toContain('Trust base /tmp/rogue.json (override, not the bundled pin)'); - expect(verifyText(ok, override)).toContain('verified against /tmp/rogue.json'); - expect(verifyText(ok, override)).not.toContain('the bundled testnet2 trust base'); - expect(verifyJson(ok, override).trustBase).toEqual({ - bundledNetwork: null, - path: '/tmp/rogue.json', - source: 'file', - }); - - // `referenceTimeIso` is typed as an ISO string, so the sentinel for a time - // no Date can hold belongs in the text output only. - const hostileTime = { ...description, referenceTime: 10n ** 30n }; - expect(descriptionJson(hostileTime).referenceTimeIso).toBeNull(); - expect(inspectText(hostileTime)).toContain('out of range (1000000000000000000000000000000)'); - - const inspected = inspectText(description); - expect(inspected.startsWith('UNVERIFIED')).toBe(true); - expect(inspected).toContain('Token type timestamp'); - expect(inspected).toContain('Recipient timestamp burn predicate'); - expect(descriptionJson(description).transferCount).toBe(0); - }); - }); }); diff --git a/tests/unit/StampTest.ts b/tests/unit/StampTest.ts new file mode 100644 index 0000000..a86dce7 --- /dev/null +++ b/tests/unit/StampTest.ts @@ -0,0 +1,35 @@ +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; + +import { describeToken } from '../../src/lib/TimestampVerification.js'; +import { stampJson, stampText } from '../../src/output.js'; +import { TEST_DIGEST, TEST_DIGEST_HEX } from '../support/fixtures.js'; +import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; +import { createTimestampToken } from '../support/TimestampFixtures.js'; + +describe('stamp output', () => { + it('renders the certified stamp as text and JSON', async () => { + const token = await createTimestampToken(TestAggregatorClient.create(), TEST_DIGEST); + const description = describeToken(token); + const tokenIdHex = HexConverter.encode(token.id.bytes); + + const text = stampText(description, 'http://gateway.local', '/tmp/x.cbor'); + expect(text).toContain(`Stamped SHA-256 ${TEST_DIGEST_HEX}`); + expect(text).toContain('Network unknown network (3) via http://gateway.local'); + expect(text).toContain('Signer none (anonymous stamp)'); + expect(text).toContain(`Token id ${tokenIdHex}`); + expect(text).toContain('Written /tmp/x.cbor'); + expect(stampText(description, 'http://gateway.local', null)).not.toContain('Written'); + + const json = stampJson(description, 'http://gateway.local', '/tmp/x.cbor', token.toCBOR()); + expect(json).toMatchObject({ + command: 'stamp', + hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, + network: { gateway: 'http://gateway.local', id: 3, name: 'unknown' }, + out: '/tmp/x.cbor', + signer: null, + token: HexConverter.encode(token.toCBOR()), + tokenId: tokenIdHex, + }); + expect(typeof json.referenceTime).toBe('string'); + }); +}); diff --git a/tests/unit/VerifyTest.ts b/tests/unit/VerifyTest.ts index d5d0da1..95f8afb 100644 --- a/tests/unit/VerifyTest.ts +++ b/tests/unit/VerifyTest.ts @@ -6,6 +6,8 @@ import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/Sta import { runVerify } from '../../src/commands/verify.js'; import { EXIT_OK, EXIT_USAGE, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; import { stampWith } from '../../src/lib/TimestampClient.js'; +import { verify } from '../../src/lib/TimestampVerification.js'; +import { verifyJson, verifyText } from '../../src/output.js'; import { testContext } from '../support/context.js'; import { OTHER_DIGEST_HEX, tempDir, TEST_DIGEST, TEST_DIGEST_HEX, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; import { @@ -15,6 +17,7 @@ import { THIRD_DIGEST_HEX, } from '../support/LineageFixtures.js'; import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; +import { createTimestampToken } from '../support/TimestampFixtures.js'; // The in-memory aggregator's network id matches no bundled pin, which is the // token `verify` cannot place and has to report before any trust base exists. @@ -155,3 +158,45 @@ describe('runVerify on a document lineage', () => { }); }); }); + +describe('verify output for a timestamp', () => { + const aggregator = TestAggregatorClient.create(); + const trustBase = aggregator.rootTrustBase; + const bundled = { kind: 'bundled', network: 'testnet2' } as const; + + it('reports the verdict, the trust base and the expected hash', async () => { + const token = await createTimestampToken(aggregator, TEST_DIGEST); + const ok = await verify(token, trustBase, { expectedDigest: TEST_DIGEST }); + expect(verifyText(ok, bundled)).toContain( + 'Status OK (inclusion proof, consensus signatures and payload verified against the bundled testnet2 trust base)', + ); + expect(verifyText(ok, bundled)).toContain('Trust base bundled testnet2 pin'); + expect(verifyText(ok, bundled)).toContain('Expected hash matches'); + const unchecked = await verify(token, trustBase); + expect(verifyText(unchecked, bundled)).toContain('Expected hash not checked; pass --file or --hash'); + expect(verifyJson(ok, bundled)).toMatchObject({ + command: 'verify', + expectedHashMatches: true, + reason: null, + status: 'OK', + trustBase: { bundledNetwork: 'testnet2', path: null, source: 'bundled' }, + }); + expect(verifyJson(ok, bundled).details?.status).toEqual('OK'); + + // No trust base could be selected at all, which is how `verify` reports a + // token whose network id matches no bundled pin. + expect(verifyText(ok, null)).toContain('Trust base none selected'); + expect(verifyJson(ok, null).trustBase).toBeNull(); + + // An override must never be able to present itself as the bundled pin. + const override = { kind: 'file', path: '/tmp/rogue.json' } as const; + expect(verifyText(ok, override)).toContain('Trust base /tmp/rogue.json (override, not the bundled pin)'); + expect(verifyText(ok, override)).toContain('verified against /tmp/rogue.json'); + expect(verifyText(ok, override)).not.toContain('the bundled testnet2 trust base'); + expect(verifyJson(ok, override).trustBase).toEqual({ + bundledNetwork: null, + path: '/tmp/rogue.json', + source: 'file', + }); + }); +}); From 6449713cd8b4b1729db7c91c9c06a3f0df476eb6 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Thu, 5 Nov 2026 16:49:48 +0200 Subject: [PATCH 10/25] Test the lineage output functions directly Each command's output tests sit with that command, as for timestamps: - StampRevisionTest: revisionText and revisionJson for an ordinary, a new and a final revision, and revisionRecoveryLines. - VerifyTest: lineageVerifyText and lineageVerifyJson for every expected hash label (none, latest, superseded, several, final, mismatch), the trust base naming, and failures with and without a result tree. - InspectTest: lineageInspectText, lineageInspectJson and lineageDescriptionJson, including unreadable revisions, a wrong claimed index, an unreadable issuer, a recipient that is not P_sig, a burn that is not a seal, and an unrepresentable time. The lineage fixture now also exposes the sealed token. Co-Authored-By: Claude Opus 5.5 --- tests/support/LineageFixtures.ts | 4 +- tests/unit/InspectTest.ts | 155 ++++++++++++++++++++++++++++++- tests/unit/StampRevisionTest.ts | 76 +++++++++++++++ tests/unit/VerifyTest.ts | 123 +++++++++++++++++++++++- 4 files changed, 353 insertions(+), 5 deletions(-) diff --git a/tests/support/LineageFixtures.ts b/tests/support/LineageFixtures.ts index 412d566..0bc1bcd 100644 --- a/tests/support/LineageFixtures.ts +++ b/tests/support/LineageFixtures.ts @@ -19,6 +19,8 @@ export const SEAL_DIGEST_HEX = 'cd'.repeat(32); export interface ILineageFixture { readonly bobPublicHex: string; /** The finalized lineage: {@link token} with a seal appended by bob. */ + readonly sealed: Token; + /** Where {@link sealed} is written. */ readonly sealedFile: string; /** Three revisions: 0 by the issuer naming bob, 1 by bob naming the issuer, 2 by the issuer naming bob. */ readonly token: Token; @@ -63,5 +65,5 @@ export async function createLineageFixture(): Promise { const trustBaseFile = path.join(directory, 'trust-base.json'); await writeFile(trustBaseFile, JSON.stringify(trustBase.toJSON())); - return { bobPublicHex: HexConverter.encode(bobPublic), sealedFile, token, tokenFile, trustBaseFile }; + return { bobPublicHex: HexConverter.encode(bobPublic), sealed, sealedFile, token, tokenFile, trustBaseFile }; } diff --git a/tests/unit/InspectTest.ts b/tests/unit/InspectTest.ts index 59ae83b..1ba41d3 100644 --- a/tests/unit/InspectTest.ts +++ b/tests/unit/InspectTest.ts @@ -2,11 +2,23 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { runInspect } from '../../src/commands/inspect.js'; import { EXIT_OK } from '../../src/errors.js'; +import { + describeLineage, + ILineageDescription, + ILineageRevisionDescription, +} from '../../src/lib/LineageVerification.js'; import { describeToken } from '../../src/lib/TimestampVerification.js'; -import { descriptionJson, inspectText } from '../../src/output.js'; +import { + descriptionJson, + ILineageRevisionJson, + inspectText, + lineageDescriptionJson, + lineageInspectJson, + lineageInspectText, +} from '../../src/output.js'; import { testContext } from '../support/context.js'; -import { TEST_DIGEST, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; -import { createLineageFixture, ILineageFixture } from '../support/LineageFixtures.js'; +import { OTHER_DIGEST_HEX, TEST_DIGEST, TEST_DIGEST_HEX, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; +import { createLineageFixture, ILineageFixture, SEAL_DIGEST_HEX } from '../support/LineageFixtures.js'; import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; import { createTimestampToken } from '../support/TimestampFixtures.js'; @@ -66,3 +78,140 @@ describe('inspect output for a timestamp', () => { expect(inspectText(hostileTime)).toContain('out of range (1000000000000000000000000000000)'); }); }); + +describe('inspect output for a document lineage', () => { + let fixture: ILineageFixture; + let open: ILineageDescription; + let sealed: ILineageDescription; + + beforeAll(async () => { + fixture = await createLineageFixture(); + open = describeLineage(fixture.token); + sealed = describeLineage(fixture.sealed); + }); + + /** `open` with revision `position` replaced by `changes`, and the top-level fields by `top`. */ + function edited( + position: number, + changes: Partial, + top: Partial = {}, + ): ILineageDescription { + const revisions = open.revisions.map((revision, index) => + index === position ? { ...revision, ...changes } : revision, + ); + return { ...open, revisions, ...top }; + } + + it('lists the lineage and every revision under an UNVERIFIED banner', () => { + const text = lineageInspectText(open); + expect(text).toMatch(/^UNVERIFIED {5}fields read from the token; nothing below has been checked\n/); + expect(text).toContain('Token type document lineage\n'); + expect(text).toContain('Network unknown network (3)\n'); + expect(text).toContain(`Token id ${HexConverter.encode(fixture.token.id.bytes)}\n`); + expect(text).toContain(`Issuer ${TEST_PUBLIC_KEY_HEX}\n`); + expect(text).toContain('Revisions 3\n'); + expect(text).toContain(`Next producer ${fixture.bobPublicHex}\n`); + expect(text).toContain( + `Revision 1 SHA-256 ${OTHER_DIGEST_HEX}\n` + + ` Signed by ${fixture.bobPublicHex}\n` + + ` Passes to ${TEST_PUBLIC_KEY_HEX}\n` + + ' Certified at ', + ); + expect(text).toMatch(/ {2}Round {8}\d+ {2}\(round timestamp \d+, epoch \d+\)/); + expect(text).not.toContain('(final)'); + }); + + it('marks the seal and the finalized lineage', () => { + const text = lineageInspectText(sealed); + expect(text).toContain('Next producer none; the lineage is finalized (sealed and burned)\n'); + expect(text).toContain(`Revision 3 SHA-256 ${SEAL_DIGEST_HEX} (final)\n`); + expect(text).toContain(' Passes to nobody; sealed and burned\n'); + }); + + it('says what it cannot read instead of failing', () => { + expect(lineageInspectText(edited(1, { digest: null, error: 'bad payload', index: null }))).toContain( + 'Revision 1 unreadable (bad payload)\n', + ); + expect(lineageInspectText(edited(1, { digest: null, error: null, index: null }))).toContain( + 'Revision 1 unreadable (no revision payload)\n', + ); + expect(lineageInspectText(edited(2, { index: 5n }))).toContain(' (claims index 5)\n'); + expect(lineageInspectText(edited(0, { signer: null }))).toContain(' Signed by not a signature predicate key\n'); + expect(lineageInspectText(edited(0, {}, { issuer: null }))).toContain('Issuer unreadable genesis reason\n'); + }); + + it('names what an unusual recipient is', () => { + const otherPredicate = lineageInspectText(edited(2, { nextProducer: null })); + expect(otherPredicate).toContain(' Passes to not a signature predicate\n'); + expect(otherPredicate).toContain('Next producer not a signature predicate\n'); + expect( + lineageInspectText(edited(2, { burnReason: new Uint8Array(32), nextProducer: null, sealed: false })), + ).toContain(' Passes to burn predicate, but the revision is not a seal\n'); + }); + + it('renders the same fields as JSON', () => { + const json = lineageInspectJson(open); + expect(json).toMatchObject({ + command: 'inspect', + finalized: false, + issuer: TEST_PUBLIC_KEY_HEX, + network: { id: 3, name: 'unknown' }, + nextProducer: fixture.bobPublicHex, + tokenId: HexConverter.encode(fixture.token.id.bytes), + tokenType: 'lineage', + verified: false, + }); + const revision = open.revisions[0]; + expect(json.revisions[0]).toEqual({ + error: null, + hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, + index: '0', + nextProducer: fixture.bobPublicHex, + referenceTime: revision.referenceTime.toString(), + referenceTimeIso: new Date(Number(revision.referenceTime) * 1000).toISOString().replace('.000Z', 'Z'), + round: { + epoch: revision.epoch.toString(), + number: revision.roundNumber.toString(), + timestamp: revision.roundTimestamp.toString(), + }, + sealed: false, + signer: TEST_PUBLIC_KEY_HEX, + }); + }); + + it('renders the seal, unreadable fields and unrepresentable times as JSON nulls', () => { + const final = lineageDescriptionJson(sealed); + expect(final.finalized).toBe(true); + expect(final.nextProducer).toBeNull(); + expect(final.revisions[3]).toMatchObject({ index: '3', nextProducer: null, sealed: true }); + + const broken = lineageDescriptionJson( + edited( + 1, + { + digest: null, + error: 'bad payload', + index: null, + nextProducer: null, + referenceTime: 10n ** 30n, + signer: null, + }, + { issuer: null }, + ), + ); + expect(broken.issuer).toBeNull(); + expect(broken.revisions[1]).toMatchObject({ + error: 'bad payload', + hash: null, + index: null, + nextProducer: null, + referenceTime: (10n ** 30n).toString(), + referenceTimeIso: null, + signer: null, + }); + // The text keeps the raw value next to the sentinel. + expect(lineageInspectText(edited(1, { referenceTime: 10n ** 30n }))).toContain( + 'out of range (1000000000000000000000000000000)', + ); + }); +}); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 12377ed..a91f291 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -10,6 +10,7 @@ import { stampRevisionWith } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; +import { IRevisionSummary, revisionJson, revisionRecoveryLines, revisionText } from '../../src/output.js'; import { testContext } from '../support/context.js'; import { OTHER_DIGEST, @@ -160,3 +161,78 @@ describe('stampRevisionWith', () => { expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_VERIFICATION_FAILED); }); }); + +describe('stamp-revision output', () => { + const producer = HexConverter.decode(TEST_PUBLIC_KEY_HEX); + const next = new SigningService(SigningService.generatePrivateKey()).publicKey; + const summary: IRevisionSummary = { + created: false, + digest: TEST_DIGEST, + epoch: 1n, + gatewayUrl: 'https://gateway.test', + networkId: 4, + nextProducer: next, + referenceTime: 1791200527n, + revision: 2n, + roundNumber: 184233n, + roundTimestamp: 1791200528n, + signer: producer, + tokenFile: '/docs/doc.lineage', + tokenId: new Uint8Array(32).fill(0xaa), + }; + + it('reports the revision, who signed it and who may produce the next', () => { + expect(revisionText(summary)).toEqual( + [ + 'Revision 2', + `Stamped SHA-256 ${TEST_DIGEST_HEX}`, + 'Network testnet2 (4) via https://gateway.test', + `Signed by ${TEST_PUBLIC_KEY_HEX}`, + `Next producer ${HexConverter.encode(next)}`, + 'Certified at 2026-10-05T11:42:07Z (reference time 1791200527)', + 'Round 184233 (round timestamp 1791200528, epoch 1)', + `Token id ${'aa'.repeat(32)}`, + 'Written /docs/doc.lineage', + ].join('\n'), + ); + }); + + it('marks a new lineage and a final revision', () => { + expect(revisionText({ ...summary, created: true, revision: 0n })).toContain('Revision 0 (new lineage)\n'); + const final = revisionText({ ...summary, nextProducer: null }); + expect(final).toContain('Revision 2 (final)\n'); + expect(final).toContain('Next producer none; the lineage is finalized (sealed and burned)\n'); + expect(revisionText({ ...summary, created: true, nextProducer: null, revision: 0n })).toContain( + 'Revision 0 (new lineage) (final)\n', + ); + }); + + it('renders the same fields as JSON, big integers as decimal strings', () => { + expect(revisionJson(summary)).toEqual({ + command: 'stamp-revision', + created: false, + finalized: false, + hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, + network: { gateway: 'https://gateway.test', id: 4, name: 'testnet2' }, + nextProducer: HexConverter.encode(next), + referenceTime: '1791200527', + referenceTimeIso: '2026-10-05T11:42:07Z', + revision: '2', + round: { epoch: '1', number: '184233', timestamp: '1791200528' }, + signer: TEST_PUBLIC_KEY_HEX, + tokenFile: '/docs/doc.lineage', + tokenId: 'aa'.repeat(32), + }); + expect(revisionJson({ ...summary, nextProducer: null })).toMatchObject({ finalized: true, nextProducer: null }); + expect(revisionJson({ ...summary, referenceTime: 10n ** 30n }).referenceTimeIso).toBeNull(); + }); + + it('hands back a token it could not write, in a form --token-file accepts', () => { + const lines = revisionRecoveryLines(new Uint8Array([0xd9, 0x01, 0x00])); + expect(lines).toEqual( + 'error: the revision was certified but the token file could not be written.\n' + + 'Save the token below; `stamp-revision --token-file` accepts hex text.\n' + + 'd90100\n', + ); + }); +}); diff --git a/tests/unit/VerifyTest.ts b/tests/unit/VerifyTest.ts index 95f8afb..bdb7755 100644 --- a/tests/unit/VerifyTest.ts +++ b/tests/unit/VerifyTest.ts @@ -2,12 +2,15 @@ import { writeFile } from 'node:fs/promises'; import path from 'node:path'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; +import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; import { runVerify } from '../../src/commands/verify.js'; import { EXIT_OK, EXIT_USAGE, EXIT_VERIFICATION_FAILED } from '../../src/errors.js'; +import { describeLineage, ILineageVerificationResult } from '../../src/lib/LineageVerification.js'; import { stampWith } from '../../src/lib/TimestampClient.js'; import { verify } from '../../src/lib/TimestampVerification.js'; -import { verifyJson, verifyText } from '../../src/output.js'; +import { lineageVerifyJson, lineageVerifyText, verifyJson, verifyText } from '../../src/output.js'; import { testContext } from '../support/context.js'; import { OTHER_DIGEST_HEX, tempDir, TEST_DIGEST, TEST_DIGEST_HEX, TEST_PUBLIC_KEY_HEX } from '../support/fixtures.js'; import { @@ -200,3 +203,121 @@ describe('verify output for a timestamp', () => { }); }); }); + +describe('verify output for a document lineage', () => { + const bundled = { kind: 'bundled', network: 'testnet2' } as const; + const override = { kind: 'file', path: '/tmp/rogue.json' } as const; + let fixture: ILineageFixture; + + beforeAll(async () => { + fixture = await createLineageFixture(); + }); + + /** A verification outcome for the open lineage, OK unless overridden. */ + function result(changes: Partial = {}): ILineageVerificationResult { + return { + description: describeLineage(fixture.token), + details: null, + matchingRevisions: null, + reason: null, + status: 'OK', + ...changes, + }; + } + + it('names the trust base the verdict was reached against', () => { + const text = lineageVerifyText(result(), bundled); + expect(text).toMatch( + /^Status {9}OK {2}\(inclusion proofs, consensus signatures, issuer signature and revision chain verified against the bundled testnet2 trust base\)\n/, + ); + expect(text).toContain('Trust base bundled testnet2 pin\n'); + expect(text).toContain('Token type document lineage\n'); + expect(text).toContain('Revisions 3\n'); + + // An override must never be able to present itself as the bundled pin. + const overridden = lineageVerifyText(result(), override); + expect(overridden).toContain('verified against /tmp/rogue.json)'); + expect(overridden).toContain('Trust base /tmp/rogue.json (override, not the bundled pin)\n'); + expect(overridden).not.toContain('bundled testnet2 trust base'); + expect(lineageVerifyJson(result(), override).trustBase).toEqual({ + bundledNetwork: null, + path: '/tmp/rogue.json', + source: 'file', + }); + expect(lineageVerifyJson(result(), bundled).trustBase).toEqual({ + bundledNetwork: 'testnet2', + path: null, + source: 'bundled', + }); + }); + + it.each<[string, readonly number[] | null, string]>([ + ['no digest given', null, 'not checked; pass --file or --hash to find your document in the lineage'], + ['the latest revision', [2], 'matches revision 2 (the latest)'], + ['an older revision', [1], 'matches revision 1; superseded by revision 2'], + ['several revisions', [0, 2], 'matches revisions 0, 2 (the latest)'], + ['no revision', [], 'differs from every revision'], + ])('labels the expected hash when it matches %s', (_, matchingRevisions, label) => { + expect(lineageVerifyText(result({ matchingRevisions }), bundled)).toContain(`Expected hash ${label}\n`); + }); + + it('labels a match on the seal as the final revision', () => { + const final = result({ description: describeLineage(fixture.sealed), matchingRevisions: [3] }); + expect(lineageVerifyText(final, bundled)).toContain('Expected hash matches revision 3 (the final)\n'); + expect(lineageVerifyJson(final, bundled)).toMatchObject({ finalized: true, nextProducer: null }); + }); + + it('reports a failure with its reason and the result tree', () => { + const details = new VerificationResult('LineageTokenVerification', VerificationStatus.FAIL, '', [ + new VerificationResult( + 'Revision[1]SealBurned', + VerificationStatus.FAIL, + 'Revision 1 is a seal, but is not burned.', + ), + ]); + const failed = result({ details, reason: 'Revision 1 is a seal, but is not burned.', status: 'FAIL' }); + + const text = lineageVerifyText(failed, bundled); + expect(text).toMatch(/^Status {9}FAIL: Revision 1 is a seal, but is not burned\.\n/); + expect(text).toContain('Expected hash not checked; verification failed\n'); + expect(text).toContain('Revision[1]SealBurned'); + expect(text.endsWith(details.toString())).toBe(true); + + expect(lineageVerifyJson(failed, bundled)).toMatchObject({ + command: 'verify', + details: { + results: [ + { message: 'Revision 1 is a seal, but is not burned.', rule: 'Revision[1]SealBurned', status: 'FAIL' }, + ], + rule: 'LineageTokenVerification', + status: 'FAIL', + }, + expectedHashMatches: null, + matchingRevisions: null, + reason: 'Revision 1 is a seal, but is not burned.', + status: 'FAIL', + tokenType: 'lineage', + }); + }); + + it('reports a failure before any result tree without one', () => { + const failed = result({ reason: null, status: 'FAIL' }); + const text = lineageVerifyText(failed, null); + expect(text).toMatch(/^Status {9}FAIL: verification failed\n/); + expect(text).toContain('Trust base none selected\n'); + // Ends with the last revision, not with an empty result tree. + expect(text).toMatch(/ {2}Round {8}\d+ {2}\(round timestamp \d+, epoch \d+\)$/); + expect(lineageVerifyJson(failed, null)).toMatchObject({ details: null, trustBase: null }); + }); + + it('reports a mismatch as such in JSON', () => { + expect(lineageVerifyJson(result({ matchingRevisions: [] }), bundled)).toMatchObject({ + expectedHashMatches: false, + matchingRevisions: [], + }); + expect(lineageVerifyJson(result({ matchingRevisions: [0, 2] }), bundled)).toMatchObject({ + expectedHashMatches: true, + matchingRevisions: [0, 2], + }); + }); +}); From 556402d2f50e4f745c6618b8e8f7c687fc3f0d75 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 10 Nov 2026 11:38:32 +0200 Subject: [PATCH 11/25] Cover the genesis recipient with the issuer signature Review on issue #13: the issuer signed (id, ty, auxData), so it endorsed the origin document but not who produces revision 1. In a delegated mint the submitter could name any first producer and verification would still report the issuer signature as valid, so the chain of custody started with a link the issuer never named. The signed message is now SHA-256(CBOR["unicity-document-lineage", 1, id, ty, recipient, auxData]), with the recipient in the predicate's own tagged CBOR encoding, byte for byte as the mint carries it. The verifier takes the recipient from the mint transaction, so it is not repeated in the reason, whose format is unchanged. For a lineage finalized at genesis the signed recipient is the burn, so the issuer also endorses that it is final. The format changes in place, keeping version 1: no lineage has been released, and lineage tokens made before this commit no longer verify. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- src/lib/LineageClient.ts | 5 +- src/lib/LineagePayload.ts | 39 ++++++++++--- src/lib/LineageVerification.ts | 4 +- tests/unit/lib/LineagePayloadTest.ts | 45 ++++++++++++++- tests/unit/lib/LineageVerificationTest.ts | 67 +++++++++++++++++++++-- 6 files changed, 144 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index a0cdef6..87be7ef 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file ``` - Exactly one of `` and `--file`, and exactly one of `--recipient-key`, `--recipient-key-file` and `--finalize`, is required. `--token-file` and `--key-file` are always required; `UNICITY_PRIVATE_KEY` is not consulted. -- If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type and revision, which is what makes the origin "accepted"; the salt is random, so the token id cannot be predicted before the genesis is certified. +- If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type, recipient and revision, which is what makes the origin "accepted". Because the recipient is signed, the issuer names the producer of revision 1 (or the burn, with `--finalize`), just as each later revision names its successor: whoever submits the mint cannot substitute another; the salt is random, so the token id cannot be predicted before the genesis is certified. - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - The state mask of each step is derived from the producer's key and the spent state, so if the command is interrupted after certification, running the same command again with the same file, key, digest and recipient recovers the same revision. @@ -162,7 +162,7 @@ Revision 0 SHA-256 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730433629 With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision, or `none; the lineage is finalized` after a seal, which is marked `(final)`. In `--json` output a lineage has `"tokenType": "lineage"`, `finalized`, a `revisions` array (each with `sealed`) and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. -Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer, or `CBOR["seal", i, SHA-256(doc_i)]` on the final revision, whose recipient is then the burn predicate with reason `SHA-256(auxiliary data)`; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, auxiliary data])`. Verification additionally requires the indices to increase by one, the reference times not to decrease along the chain, and a revision to be burned exactly when it is a seal, with the burn reason as above. +Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer, or `CBOR["seal", i, SHA-256(doc_i)]` on the final revision, whose recipient is then the burn predicate with reason `SHA-256(auxiliary data)`; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, recipient, auxiliary data])`, where `recipient` is the mint's recipient predicate in its tagged CBOR encoding (tag 39032). Verification additionally requires the indices to increase by one, the reference times not to decrease along the chain, and a revision to be burned exactly when it is a seal, with the burn reason as above. ### Verify diff --git a/src/lib/LineageClient.ts b/src/lib/LineageClient.ts index 979944b..2451a80 100644 --- a/src/lib/LineageClient.ts +++ b/src/lib/LineageClient.ts @@ -6,6 +6,7 @@ import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/sec import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; import { SignaturePredicateUnlockScript } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicateUnlockScript.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; @@ -124,7 +125,8 @@ async function revisionStep( /** * Create a lineage: mint revision 0, with the issuer's signature as the mint - * reason and the next producer's `P_sig` as recipient. Without a next producer + * reason and the next producer's `P_sig` as recipient. The signature covers the + * recipient, so the issuer names the producer of revision 1. Without a next producer * the lineage is finalized at once: revision 0 is a seal, minted to the burn * predicate. * @@ -153,6 +155,7 @@ export async function createLineage( const reason = await LineageGenesisReason.sign( tokenId, LINEAGE_TOKEN_TYPE, + EncodedPredicate.fromPredicate(recipient), auxData, new SigningService(issuerPrivateKey), ); diff --git a/src/lib/LineagePayload.ts b/src/lib/LineagePayload.ts index 820baf4..34aa19e 100644 --- a/src/lib/LineagePayload.ts +++ b/src/lib/LineagePayload.ts @@ -4,6 +4,7 @@ import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash import { Signature } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/Signature.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import { CborDeserializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborDeserializer.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; @@ -167,15 +168,18 @@ export async function sealPredicate(sealPayload: Uint8Array): Promise} Signed reason. @@ -248,23 +253,34 @@ export class LineageGenesisReason { public static async sign( tokenId: TokenId, tokenType: TokenType, + recipient: EncodedPredicate, auxData: Uint8Array, issuer: SigningService, ): Promise { - const signature = await issuer.sign(await LineageGenesisReason.signedMessage(tokenId, tokenType, auxData)); + const signature = await issuer.sign( + await LineageGenesisReason.signedMessage(tokenId, tokenType, recipient, auxData), + ); return new LineageGenesisReason(issuer.publicKey, signature); } /** * Message the issuer signs: - * `SHA-256(CBOR["unicity-document-lineage", 1, id, ty, auxData])`. + * `SHA-256(CBOR["unicity-document-lineage", 1, id, ty, recipient, auxData])`, + * where `recipient` is the predicate's own tagged CBOR encoding, byte for byte + * as the mint transaction carries it. * * @param {TokenId} tokenId Token id of the lineage. * @param {TokenType} tokenType Token type. + * @param {EncodedPredicate} recipient Recipient predicate of the mint. * @param {Uint8Array} auxData Exact auxiliary data bytes of the mint. * @returns {Promise} Message hash. */ - public static signedMessage(tokenId: TokenId, tokenType: TokenType, auxData: Uint8Array): Promise { + public static signedMessage( + tokenId: TokenId, + tokenType: TokenType, + recipient: EncodedPredicate, + auxData: Uint8Array, + ): Promise { return new DataHasher(HashAlgorithm.SHA256) .update( CborSerializer.encodeArray( @@ -272,6 +288,7 @@ export class LineageGenesisReason { CborSerializer.encodeUnsignedInteger(LINEAGE_REASON_VERSION), CborSerializer.encodeByteString(tokenId.bytes), CborSerializer.encodeByteString(tokenType.bytes), + recipient.toCBOR(), CborSerializer.encodeByteString(auxData), ), ) @@ -293,12 +310,18 @@ export class LineageGenesisReason { /** * @param {TokenId} tokenId Token id of the lineage. * @param {TokenType} tokenType Token type. + * @param {EncodedPredicate} recipient Recipient predicate of the mint. * @param {Uint8Array} auxData Exact auxiliary data bytes of the mint. * @returns {Promise} True if the signature verifies for the issuer. */ - public async verify(tokenId: TokenId, tokenType: TokenType, auxData: Uint8Array): Promise { + public async verify( + tokenId: TokenId, + tokenType: TokenType, + recipient: EncodedPredicate, + auxData: Uint8Array, + ): Promise { return SigningService.verifyWithPublicKey( - await LineageGenesisReason.signedMessage(tokenId, tokenType, auxData), + await LineageGenesisReason.signedMessage(tokenId, tokenType, recipient, auxData), this.signature, this._issuer, ); diff --git a/src/lib/LineageVerification.ts b/src/lib/LineageVerification.ts index f3cbf05..f55d9a5 100644 --- a/src/lib/LineageVerification.ts +++ b/src/lib/LineageVerification.ts @@ -78,7 +78,7 @@ export class LineageIssuanceVerifier implements ITokenIssuanceVerifier { } } -/** Checks the issuer signature in a lineage genesis reason. */ +/** Checks the issuer signature in a lineage genesis reason, over the mint's own id, type, recipient and auxData. */ export class LineageGenesisReasonVerifier implements IMintJustificationVerifier { public static readonly RULE = 'LineageGenesisReasonVerification'; @@ -99,7 +99,7 @@ export class LineageGenesisReasonVerifier implements IMintJustificationVerifier results.push( check( 'IssuerSignatureValid', - await reason.verify(transaction.tokenId, transaction.tokenType, data), + await reason.verify(transaction.tokenId, transaction.tokenType, transaction.recipient, data), 'Issuer signature in the genesis reason does not verify.', ), ); diff --git a/tests/unit/lib/LineagePayloadTest.ts b/tests/unit/lib/LineagePayloadTest.ts index 1d6d95e..630f6e7 100644 --- a/tests/unit/lib/LineagePayloadTest.ts +++ b/tests/unit/lib/LineagePayloadTest.ts @@ -79,22 +79,63 @@ describe('LineagePayload', () => { }); describe('LineageGenesisReason', () => { + const bob = EncodedPredicate.fromPredicate( + SignaturePredicate.create(publicKey(SigningService.generatePrivateKey())), + ); + const carol = EncodedPredicate.fromPredicate( + SignaturePredicate.create(publicKey(SigningService.generatePrivateKey())), + ); + it('round-trips a genesis reason and rejects a wrong tag', async () => { const tokenId = await TokenId.fromSalt(NetworkId.LOCAL, TokenSalt.generate()); const reason = await LineageGenesisReason.sign( tokenId, LINEAGE_TOKEN_TYPE, + bob, TEST_DIGEST, new SigningService(alice), ); const decoded = LineageGenesisReason.fromCBOR(reason.toCBOR()); expect(decoded.issuer).toEqual(publicKey(alice)); - expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, TEST_DIGEST)).toBe(true); - expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, OTHER_DIGEST)).toBe(false); + expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, bob, TEST_DIGEST)).toBe(true); + expect(await decoded.verify(tokenId, LINEAGE_TOKEN_TYPE, bob, OTHER_DIGEST)).toBe(false); const wrongTag = CborSerializer.encodeTag(1n, CborSerializer.encodeArray()); expect(() => LineageGenesisReason.fromCBOR(wrongTag)).toThrow(LineageFormatError); }); + + it('signs the recipient: the signature holds for no other first producer', async () => { + const tokenId = await TokenId.fromSalt(NetworkId.LOCAL, TokenSalt.generate()); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + bob, + TEST_DIGEST, + new SigningService(alice), + ); + expect(await reason.verify(tokenId, LINEAGE_TOKEN_TYPE, bob, TEST_DIGEST)).toBe(true); + expect(await reason.verify(tokenId, LINEAGE_TOKEN_TYPE, carol, TEST_DIGEST)).toBe(false); + const burn = EncodedPredicate.fromPredicate(await sealPredicate(TEST_DIGEST)); + expect(await reason.verify(tokenId, LINEAGE_TOKEN_TYPE, burn, TEST_DIGEST)).toBe(false); + }); + + it('pins the signed message format', async () => { + const tokenId = await TokenId.fromSalt(NetworkId.LOCAL, TokenSalt.generate()); + const message = await LineageGenesisReason.signedMessage(tokenId, LINEAGE_TOKEN_TYPE, bob, TEST_DIGEST); + const expected = createHash('sha256') + .update( + CborSerializer.encodeArray( + CborSerializer.encodeTextString(LINEAGE_TAG), + CborSerializer.encodeUnsignedInteger(1n), + CborSerializer.encodeByteString(tokenId.bytes), + CborSerializer.encodeByteString(LINEAGE_TOKEN_TYPE.bytes), + bob.toCBOR(), + CborSerializer.encodeByteString(TEST_DIGEST), + ), + ) + .digest(); + expect(message.data).toEqual(new Uint8Array(expected)); + }); }); it('builds the recipient as a P_sig predicate', () => { diff --git a/tests/unit/lib/LineageVerificationTest.ts b/tests/unit/lib/LineageVerificationTest.ts index 1c6c66f..7aca6c3 100644 --- a/tests/unit/lib/LineageVerificationTest.ts +++ b/tests/unit/lib/LineageVerificationTest.ts @@ -1,5 +1,6 @@ import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import type { IPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/IPredicate.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; @@ -27,6 +28,7 @@ describe('LineageVerification', () => { const alice = SigningService.generatePrivateKey(); const bob = SigningService.generatePrivateKey(); + const carol = SigningService.generatePrivateKey(); const publicKey = (key: Uint8Array): Uint8Array => new SigningService(key).publicKey; /** @@ -54,11 +56,24 @@ describe('LineageVerification', () => { ); } - /** A genesis with a valid issuer signature over `data`, minted to `recipient`. */ - async function signedGenesis(data: Uint8Array, recipient: IPredicate): Promise { + /** + * A genesis with an issuer signature over `data` and `signedRecipient`, minted + * to `recipient`; the signature is valid when the two are the same predicate. + */ + async function signedGenesis( + data: Uint8Array, + recipient: IPredicate, + signedRecipient: IPredicate = recipient, + ): Promise { const salt = TokenSalt.generate(); const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); - const reason = await LineageGenesisReason.sign(tokenId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + EncodedPredicate.fromPredicate(signedRecipient), + data, + new SigningService(alice), + ); return rawLineageToken(recipient, { data, justification: reason.toCBOR(), salt }); } @@ -66,8 +81,15 @@ describe('LineageVerification', () => { it('rejects a genesis whose issuer signature covers another token', async () => { const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); const otherId = await TokenId.fromSalt(trustBase.networkId, TokenSalt.generate()); - const reason = await LineageGenesisReason.sign(otherId, LINEAGE_TOKEN_TYPE, data, new SigningService(alice)); - const token = await rawLineageToken(SignaturePredicate.create(publicKey(bob)), { + const recipient = SignaturePredicate.create(publicKey(bob)); + const reason = await LineageGenesisReason.sign( + otherId, + LINEAGE_TOKEN_TYPE, + EncodedPredicate.fromPredicate(recipient), + data, + new SigningService(alice), + ); + const token = await rawLineageToken(recipient, { data, justification: reason.toCBOR(), }); @@ -76,6 +98,41 @@ describe('LineageVerification', () => { expect(result.reason).toEqual('Issuer signature in the genesis reason does not verify.'); }); + it('accepts a genesis minted to the recipient the issuer signed for', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const result = await verifyLineage( + await signedGenesis(data, SignaturePredicate.create(publicKey(bob))), + trustBase, + ); + expect(result.reason).toBeNull(); + expect(result.status).toEqual('OK'); + }); + + // A delegated mint: the issuer signs for bob, whoever submits the mint names carol. + it('rejects a genesis minted to another recipient than the issuer signed for', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const result = await verifyLineage( + await signedGenesis( + data, + SignaturePredicate.create(publicKey(carol)), + SignaturePredicate.create(publicKey(bob)), + ), + trustBase, + ); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Issuer signature in the genesis reason does not verify.'); + }); + + it('rejects a genesis burned at once when the issuer signed for a producer', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const result = await verifyLineage( + await signedGenesis(data, await sealPredicate(data), SignaturePredicate.create(publicKey(bob))), + trustBase, + ); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Issuer signature in the genesis reason does not verify.'); + }); + it('rejects a genesis without an issuer reason', async () => { const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); const token = await rawLineageToken(SignaturePredicate.create(publicKey(bob)), { data, justification: null }); From 825e0599d8df472521b2261399ebf02a58bcc81f Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 10 Nov 2026 12:02:43 +0200 Subject: [PATCH 12/25] Identify a lineage by its token id Review on issue #13: pinning a lineage by issuer key and H(doc_0) is not unique. One issuer can start any number of certified lineages from the same document, and verification cannot tell them apart; only the token id identifies one, so verifiers need it through a trusted channel. - verify --token-id asserts which lineage the token is. A different id fails (exit 1) with "Token id mismatch", reported before a hash mismatch. The text output gains a "Lineage id" line that says when the id was not checked, and the JSON gains expectedTokenIdMatches. The option is a usage error for tokens that are not lineages. verifyLineage takes the id as expectedTokenId. - stamp-revision marks the token id of a new lineage as the thing to give to verifiers. - The genesis salt is derived from the issuer's private key, the encoded recipient and revision 0, like the state mask of later steps. Re-running an interrupted genesis recovers the same lineage instead of starting a parallel one, and nobody without the issuer's key can compute the id before the genesis is certified. Tests that shared an aggregator now get one each, since equal inputs now continue the same lineage. - README and the skill say that the token id, and nothing else, identifies a lineage. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 ++-- skills/unicity-proof/SKILL.md | 12 ++- src/cli.ts | 1 + src/commands/verify.ts | 37 +++++++-- src/config.ts | 9 +++ src/lib/LineageClient.ts | 43 ++++++++++- src/lib/LineageVerification.ts | 66 ++++++++++++---- src/output.ts | 33 +++++++- tests/unit/ConfigTest.ts | 15 ++++ tests/unit/StampRevisionTest.ts | 13 +++- tests/unit/VerifyTest.ts | 94 +++++++++++++++++++++++ tests/unit/lib/LineageClientTest.ts | 64 ++++++++++++++- tests/unit/lib/LineageVerificationTest.ts | 40 ++++++++++ 13 files changed, 397 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 87be7ef..acee047 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,9 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file ``` - Exactly one of `` and `--file`, and exactly one of `--recipient-key`, `--recipient-key-file` and `--finalize`, is required. `--token-file` and `--key-file` are always required; `UNICITY_PRIVATE_KEY` is not consulted. -- If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type, recipient and revision, which is what makes the origin "accepted". Because the recipient is signed, the issuer names the producer of revision 1 (or the burn, with `--finalize`), just as each later revision names its successor: whoever submits the mint cannot substitute another; the salt is random, so the token id cannot be predicted before the genesis is certified. +- If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type, recipient and revision, which is what makes the origin "accepted". Because the recipient is signed, the issuer names the producer of revision 1 (or the burn, with `--finalize`), just as each later revision names its successor: whoever submits the mint cannot substitute another. +- **The token id identifies the lineage, and nothing else does.** It is printed when the lineage is created, marked `(identifies this lineage; give it to verifiers)`; pass it on through a channel the verifiers trust, and have them check it with `verify --token-id`. The issuer key and the first revision's hash are not enough: the same issuer can start any number of certified lineages from the same document, each with its own fork-free history, and verification cannot tell them apart. +- The salt, and so the token id, is derived from the issuer's private key, the recipient and revision 0, not drawn at random. Running an interrupted genesis again with the same file, key, digest and recipient therefore recovers the same lineage instead of starting a parallel one. Nobody without the issuer's key can compute the token id before the genesis is certified, so nobody can mint into its slot first. Starting a second, separate lineage from the same document needs a different first producer (or issuer). - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - The state mask of each step is derived from the producer's key and the spent state, so if the command is interrupted after certification, running the same command again with the same file, key, digest and recipient recovers the same revision. @@ -137,14 +139,16 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file `verify` and `inspect` recognise lineage tokens by their token type and list every revision with its hash, signer, next producer and certification time: ```bash -unicity-proof verify doc.lineage # is this a valid lineage? -unicity-proof verify doc.lineage --file doc.pdf # ...and which revision is this file? +unicity-proof verify doc.lineage # is this a valid lineage? +unicity-proof verify doc.lineage --token-id # ...and the one I was given? +unicity-proof verify doc.lineage --token-id --file doc.pdf # ...and which revision is this file? ``` ``` Status OK (inclusion proofs, consensus signatures, issuer signature and revision chain verified against the bundled testnet2 trust base) Trust base bundled testnet2 pin Expected hash matches revision 1; superseded by revision 2 +Lineage id matches Token type document lineage Network testnet2 (4) Token id 5394db437e25b271272701e70e3f211ab4be2449fbe5b5d33664afa630b92357 @@ -160,7 +164,7 @@ Revision 0 SHA-256 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730433629 … ``` -With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision, or `none; the lineage is finalized` after a seal, which is marked `(final)`. In `--json` output a lineage has `"tokenType": "lineage"`, `finalized`, a `revisions` array (each with `sealed`) and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. +With `--token-id`, the lineage passes only if its token id is that one; `Lineage id` says whether it matched, or that it was not checked, in which case nothing has established *which* lineage this is. A different id is a failure, reported before any hash mismatch. `--token-id` is refused for tokens that are not lineages. With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision, or `none; the lineage is finalized` after a seal, which is marked `(final)`. In `--json` output a lineage has `"tokenType": "lineage"`, `finalized`, a `revisions` array (each with `sealed`), `expectedTokenIdMatches` (null when no `--token-id` was given) and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer, or `CBOR["seal", i, SHA-256(doc_i)]` on the final revision, whose recipient is then the burn predicate with reason `SHA-256(auxiliary data)`; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, recipient, auxiliary data])`, where `recipient` is the mint's recipient predicate in its tagged CBOR encoding (tag 39032). Verification additionally requires the indices to increase by one, the reference times not to decrease along the chain, and a revision to be burned exactly when it is a seal, with the burn reason as above. @@ -207,8 +211,8 @@ unicity-proof verify document.cbor --file document.pdf --json | jq -r .reference | Exit code | Meaning | | --- | --- | -| 0 | Success. For `verify`: valid, and the hash matched if one was given. | -| 1 | Verification failed, hash mismatch, or the input is not a token. | +| 0 | Success. For `verify`: valid, and the hash (and, for a lineage, the token id) matched if one was given. | +| 1 | Verification failed, hash or token id mismatch, or the input is not a token. | | 2 | Usage or configuration error. | | 3 | Network error, aggregator rejection, or timeout. | | 130 | Interrupted. | diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index 92c5430..aaf25c6 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -30,6 +30,14 @@ superseded by revision 2` means the file is a genuine but outdated revision. `matches revision 2 (the final)` means the lineage was finalized with that revision (`--finalize`); no later revision can exist. +A matching hash does not say *which* lineage the file is in: one issuer can +start several certified lineages from the same document. Only the token id +identifies a lineage, so verify with `--token-id `, using the id the +issuer gave you through a channel you trust, and read the `Lineage id` line: +`matches` ties the result to that lineage; `not checked` means the `Issuer` +and `Expected hash` lines are not enough on their own; `differs` means this +is another lineage. + Also read the `Trust base` line. A verdict is only as good as the root of trust behind it, and `OK` against someone else's trust base means nothing. @@ -65,8 +73,8 @@ about foresight. | Code | Meaning | | --- | --- | -| `0` | Success. For `verify`: valid, and the hash matched if one was given. | -| `1` | Verification failed, hash mismatch, or the input is not a token. | +| `0` | Success. For `verify`: valid, and the hash (and, for a lineage, the token id) matched if one was given. | +| `1` | Verification failed, hash or token id mismatch, or the input is not a token. | | `2` | Usage or configuration error. | | `3` | Network error, aggregator rejection, or timeout. | | `130` | Interrupted. | diff --git a/src/cli.ts b/src/cli.ts index e407be7..c8dad34 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -107,6 +107,7 @@ program .argument('', 'token file, or "-" for stdin; raw CBOR or hex text') .option('--hash ', 'assert the token is for this digest (for a lineage: one of its revisions)') .option('--file ', 'assert the token is for this file, hashed locally (for a lineage: one of its revisions)') + .option('--token-id ', 'assert the lineage is the one with this token id, as given to you by its issuer') .option('--network ', "use this network's bundled trust base instead of the one matching the token") .option('--trust-base ', 'use this trust base file; or UNICITY_TRUST_BASE') .action(async (file: string, flags: IVerifyFlags) => { diff --git a/src/commands/verify.ts b/src/commands/verify.ts index 3648430..6e7c5dd 100644 --- a/src/commands/verify.ts +++ b/src/commands/verify.ts @@ -1,7 +1,13 @@ import { ICommandContext } from './context.js'; import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js'; -import { assertOneDigestSource, INetworkFlags, resolveDigest, resolveTrustBaseOverride } from '../config.js'; -import { EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; +import { + assertOneDigestSource, + INetworkFlags, + parseTokenId, + resolveDigest, + resolveTrustBaseOverride, +} from '../config.js'; +import { EXIT_OK, EXIT_VERIFICATION_FAILED, usageError } from '../errors.js'; import { describeLineage, ILineageVerificationResult, verifyLineage } from '../lib/LineageVerification.js'; import { bundledTrustBase, ITrustBaseChoice, networkNameForId, TrustBaseSource } from '../lib/networks.js'; import { @@ -15,6 +21,7 @@ import { lineageVerifyJson, lineageVerifyText, toJsonLine, verifyJson, verifyTex export interface IVerifyFlags extends INetworkFlags { readonly file?: string; readonly hash?: string; + readonly tokenId?: string; } function report( @@ -39,8 +46,9 @@ function reportLineage( /** * `verify`: check a token offline and report what it proves. A document lineage - * token is verified as a lineage, and an expected digest is looked for among its - * revisions; any other token is verified as a timestamp. Cheap failures come first; the document is hashed only once the token and trust base are in hand. + * token is verified as a lineage, an expected token id is compared, and an + * expected digest is looked for among its revisions; any other token is verified + * as a timestamp. Cheap failures come first; the document is hashed only once the token and trust base are in hand. * * @param {string} file Token path, or `-` for stdin. * @param {IVerifyFlags} flags Command flags. @@ -52,6 +60,7 @@ export async function runVerify(file: string, flags: IVerifyFlags, context: ICom // a failed verification, which would answer a contradictory command line with // exit 1 and no mention of the contradiction. assertOneDigestSource(flags.hash, flags.file, '--hash'); + const expectedTokenId = flags.tokenId === undefined ? undefined : parseTokenId(flags.tokenId); const decoded = await decodeToken(await readTokenInput(file, context.stdin)); if (decoded.token === null) { @@ -59,6 +68,11 @@ export async function runVerify(file: string, flags: IVerifyFlags, context: ICom } const token = decoded.token; const lineage = describeLineage(token); + if (expectedTokenId !== undefined && !lineage.tokenTypeIsLineage) { + // A timestamp has no successors, so its id distinguishes nothing; quietly + // ignoring the flag would suggest it had been checked. + throw usageError('--token-id applies to document lineage tokens only; this token is not one.'); + } let choice = await resolveTrustBaseOverride(flags); if (choice === undefined) { @@ -68,7 +82,14 @@ export async function runVerify(file: string, flags: IVerifyFlags, context: ICom if (lineage.tokenTypeIsLineage) { return reportLineage( context, - { description: lineage, details: null, matchingRevisions: null, reason, status: 'FAIL' }, + { + description: lineage, + details: null, + matchingRevisions: null, + reason, + status: 'FAIL', + tokenIdMatches: null, + }, null, ); } @@ -82,7 +103,11 @@ export async function runVerify(file: string, flags: IVerifyFlags, context: ICom const expectedDigest = await resolveDigest(flags.hash, flags.file, '--hash'); if (lineage.tokenTypeIsLineage) { - return reportLineage(context, await verifyLineage(token, choice.trustBase, { expectedDigest }), choice.source); + return reportLineage( + context, + await verifyLineage(token, choice.trustBase, { expectedDigest, expectedTokenId }), + choice.source, + ); } return report(context, await verify(token, choice.trustBase, { expectedDigest }), choice.source); } diff --git a/src/config.ts b/src/config.ts index a0d3c4f..e30b2d1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -129,6 +129,15 @@ export function parseDigest(input: string): Uint8Array { return parseHex32(input, `Expected a SHA-256 digest of 64 hex characters, got '${input}'.`); } +/** + * @param {string} input 64 hex characters, any case, optional 0x prefix. + * @returns {Uint8Array} 32-byte token id. + * @throws {CliError} If the input is not a token id. + */ +export function parseTokenId(input: string): Uint8Array { + return parseHex32(input, `--token-id must be a token id of 64 hex characters, got '${input}'.`); +} + /** * @param {string} input 64 hex characters, any case, optional 0x prefix, surrounding whitespace allowed. * @returns {Uint8Array} 32-byte secp256k1 private key. diff --git a/src/lib/LineageClient.ts b/src/lib/LineageClient.ts index 2451a80..aafd1d2 100644 --- a/src/lib/LineageClient.ts +++ b/src/lib/LineageClient.ts @@ -99,6 +99,38 @@ export async function deriveStateMask(privateKey: Uint8Array, token: Token): Pro return StateMask.fromBytes(hash.data); } +/** + * Salt of a genesis, `salt = PRF(k_issuer, recipient, auxData)`: derived from the + * issuer's private key, the encoded recipient and the revision 0 payload rather + * than drawn at random. Re-running an interrupted genesis with the same key, + * digest and recipient therefore rebuilds the identical mint, so the aggregator + * returns the proof it already holds instead of a second, parallel lineage being + * created. The token id `H(salt, network)` still cannot be computed by anyone + * without the issuer's key, so nobody else can mint into its slot first. + * + * @param {Uint8Array} issuerPrivateKey Issuer's secp256k1 private key. + * @param {EncodedPredicate} recipient Recipient predicate of the mint. + * @param {Uint8Array} auxData Exact auxiliary data bytes of the mint. + * @returns {Promise} Deterministic 32-byte salt. + */ +export async function deriveGenesisSalt( + issuerPrivateKey: Uint8Array, + recipient: EncodedPredicate, + auxData: Uint8Array, +): Promise { + const hash = await new DataHasher(HashAlgorithm.SHA256) + .update( + CborSerializer.encodeArray( + CborSerializer.encodeTextString(`${LINEAGE_TAG}/salt`), + CborSerializer.encodeByteString(issuerPrivateKey), + recipient.toCBOR(), + CborSerializer.encodeByteString(auxData), + ), + ) + .digest(); + return TokenSalt.fromBytes(hash.data); +} + /** * Payload and recipient of a revision: to the next producer's `P_sig`, or, when * there is none, sealed and burned, so that no further revision can follow. @@ -130,8 +162,10 @@ async function revisionStep( * the lineage is finalized at once: revision 0 is a seal, minted to the burn * predicate. * - * The salt is random, so the token id stays unpredictable until the genesis is - * certified and cannot be squatted. + * The salt is derived from the issuer's key ({@link deriveGenesisSalt}), so an + * interrupted run recovers the same lineage when repeated, while the token id stays + * unpredictable to everyone else and cannot be squatted. The token id is what + * identifies the lineage; verifiers should receive it through a trusted channel. * * @param {StateTransitionClient} client Aggregator client. * @param {RootTrustBase} trustBase Trust base of the network behind the client. @@ -150,12 +184,13 @@ export async function createLineage( options: ICertifyOptions = {}, ): Promise { const { auxData, recipient } = await revisionStep(0n, digest, nextProducer); - const salt = TokenSalt.generate(); + const encodedRecipient = EncodedPredicate.fromPredicate(recipient); + const salt = await deriveGenesisSalt(issuerPrivateKey, encodedRecipient, auxData); const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); const reason = await LineageGenesisReason.sign( tokenId, LINEAGE_TOKEN_TYPE, - EncodedPredicate.fromPredicate(recipient), + encodedRecipient, auxData, new SigningService(issuerPrivateKey), ); diff --git a/src/lib/LineageVerification.ts b/src/lib/LineageVerification.ts index f55d9a5..ee7d595 100644 --- a/src/lib/LineageVerification.ts +++ b/src/lib/LineageVerification.ts @@ -237,6 +237,13 @@ export function describeLineage(token: Token): ILineageDescription { export interface ILineageVerifyOptions { /** Digest one of the revisions is expected to carry. */ readonly expectedDigest?: Uint8Array; + /** + * Token id the lineage is expected to have. Only the id identifies a lineage: + * one issuer can start any number of certified lineages from the same initial + * revision, and nothing else tells them apart. Verifiers should receive it + * through a trusted channel when the lineage is created. + */ + readonly expectedTokenId?: Uint8Array; } export interface ILineageVerificationResult { @@ -250,6 +257,11 @@ export interface ILineageVerificationResult { readonly matchingRevisions: readonly number[] | null; readonly reason: string | null; readonly status: 'FAIL' | 'OK'; + /** + * Whether the token id is the expected one; null when no id was given or the + * comparison was not reached. + */ + readonly tokenIdMatches: boolean | null; } /** @@ -327,12 +339,14 @@ function deepestMessage(result: VerificationResult): string { /** * Verify a document lineage token offline: the SDK's full token verification with - * the lineage issuance policy, then the chain rules, then, if asked, whether any - * revision carries the expected digest. + * the lineage issuance policy, then the chain rules, then, if asked, whether the + * token id is the expected one and whether any revision carries the expected + * digest. Without an expected token id, an OK result does not say which lineage + * this is: see {@link ILineageVerifyOptions.expectedTokenId}. * * @param {Token} token Token to verify. * @param {RootTrustBase} trustBase Trust base of the token's network. - * @param {ILineageVerifyOptions} options Expected digest. + * @param {ILineageVerifyOptions} options Expected token id and digest. * @returns {Promise} Outcome. */ export async function verifyLineage( @@ -348,6 +362,7 @@ export async function verifyLineage( matchingRevisions: null, reason: `Not a document lineage token: token type ${HexConverter.encode(token.type.bytes)}.`, status: 'FAIL', + tokenIdMatches: null, }; } if (token.networkId.id !== trustBase.networkId.id) { @@ -357,29 +372,46 @@ export async function verifyLineage( matchingRevisions: null, reason: `The token is for network ${token.networkId.id} and the trust base for network ${trustBase.networkId.id}.`, status: 'FAIL', + tokenIdMatches: null, }; } const sdk = await token.verify(createLineageVerificationContext(trustBase)); const details = VerificationResult.fromResults('LineageTokenVerification', [sdk, await chainRules(description)]); if (details.status !== VerificationStatus.OK) { - return { description, details, matchingRevisions: null, reason: deepestMessage(details), status: 'FAIL' }; - } - const expected = options.expectedDigest; - if (expected === undefined) { - return { description, details, matchingRevisions: null, reason: null, status: 'OK' }; - } - // Every digest decoded: the chain rules above fail on any revision that does not. - const matchingRevisions = description.revisions.flatMap((revision, position) => - revision.digest !== null && areUint8ArraysEqual(revision.digest, expected) ? [position] : [], - ); - if (matchingRevisions.length === 0) { return { description, details, - matchingRevisions, - reason: 'Hash mismatch: no revision of the lineage certifies this digest.', + matchingRevisions: null, + reason: deepestMessage(details), status: 'FAIL', + tokenIdMatches: null, }; } - return { description, details, matchingRevisions, reason: null, status: 'OK' }; + + const expectedId = options.expectedTokenId; + const tokenIdMatches = expectedId === undefined ? null : areUint8ArraysEqual(token.id.bytes, expectedId); + const expected = options.expectedDigest; + // Every digest decoded: the chain rules above fail on any revision that does not. + const matchingRevisions = + expected === undefined + ? null + : description.revisions.flatMap((revision, position) => + revision.digest !== null && areUint8ArraysEqual(revision.digest, expected) ? [position] : [], + ); + + // The wrong lineage is reported first: which revision of it matches is beside the point. + let reason: string | null = null; + if (tokenIdMatches === false) { + reason = 'Token id mismatch: this is not the lineage you were given.'; + } else if (matchingRevisions?.length === 0) { + reason = 'Hash mismatch: no revision of the lineage certifies this digest.'; + } + return { + description, + details, + matchingRevisions, + reason, + status: reason === null ? 'OK' : 'FAIL', + tokenIdMatches, + }; } diff --git a/src/output.ts b/src/output.ts index 36bce55..ed645cf 100644 --- a/src/output.ts +++ b/src/output.ts @@ -421,7 +421,10 @@ export function revisionText(summary: IRevisionSummary): string { line('Next producer', keyLabel(summary.nextProducer, FINALIZED_LABEL)), line('Certified at', `${formatIso(summary.referenceTime)} (reference time ${summary.referenceTime})`), line('Round', `${summary.roundNumber} (round timestamp ${summary.roundTimestamp}, epoch ${summary.epoch})`), - line('Token id', HexConverter.encode(summary.tokenId)), + line( + 'Token id', + `${HexConverter.encode(summary.tokenId)}${summary.created ? ' (identifies this lineage; give it to verifiers)' : ''}`, + ), line('Written', summary.tokenFile), ].join('\n'); } @@ -497,6 +500,8 @@ export interface ILineageVerifyJson extends ILineageDescriptionJson { readonly command: 'verify'; readonly details: IResultJson | null; readonly expectedHashMatches: boolean | null; + /** Whether the token id is the one passed with --token-id; null when not checked. */ + readonly expectedTokenIdMatches: boolean | null; /** Positions of the revisions carrying the expected hash; null when not checked. */ readonly matchingRevisions: readonly number[] | null; readonly reason: string | null; @@ -561,12 +566,19 @@ function lineageLines(description: ILineageDescription): string[] { return lines; } -// As for timestamps, relies on `verifyLineage` failing closed: an OK result with -// no comparison can only mean no digest was given. +// Whether verification got as far as the comparisons with what the caller expects: +// it did when it passed, or when either comparison was made. As for timestamps, +// this relies on `verifyLineage` failing closed and making every comparison it was +// asked for once it gets that far, so a comparison missing past that point can +// only mean nothing was given to compare with. +function lineageComparisonsReached(result: ILineageVerificationResult): boolean { + return result.status === 'OK' || result.matchingRevisions !== null || result.tokenIdMatches !== null; +} + function lineageExpectedHashLabel(result: ILineageVerificationResult): string { const matching = result.matchingRevisions; if (matching === null) { - return result.status === 'OK' + return lineageComparisonsReached(result) ? 'not checked; pass --file or --hash to find your document in the lineage' : 'not checked; verification failed'; } @@ -582,6 +594,17 @@ function lineageExpectedHashLabel(result: ILineageVerificationResult): string { return `${which} (the ${result.description.finalized ? 'final' : 'latest'})`; } +// Like the expected hash: without an id there is no telling this lineage from a +// parallel one the same issuer started from the same document, so say so. +function lineageIdLabel(result: ILineageVerificationResult): string { + if (result.tokenIdMatches === null) { + return lineageComparisonsReached(result) + ? 'not checked; pass --token-id to tie this to the lineage you were given' + : 'not checked; verification failed'; + } + return result.tokenIdMatches ? 'matches' : 'differs from the token id you were given'; +} + /** * @param {ILineageVerificationResult} result Lineage verification outcome. * @param {TrustBaseSource|null} source Root of trust the verdict was produced against. @@ -598,6 +621,7 @@ export function lineageVerifyText(result: ILineageVerificationResult, source: Tr ), line('Trust base', trustBaseLabel(source)), line('Expected hash', lineageExpectedHashLabel(result)), + line('Lineage id', lineageIdLabel(result)), ...lineageLines(result.description), ]; if (result.status !== 'OK' && result.details !== null) { @@ -660,6 +684,7 @@ export function lineageVerifyJson( return { command: 'verify', expectedHashMatches: result.matchingRevisions === null ? null : result.matchingRevisions.length > 0, + expectedTokenIdMatches: result.tokenIdMatches, matchingRevisions: result.matchingRevisions, reason: result.reason, status: result.status, diff --git a/tests/unit/ConfigTest.ts b/tests/unit/ConfigTest.ts index 032ce2a..0ee4ba9 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -11,6 +11,7 @@ import { parseNetworkName, parsePrivateKey, parsePublicKey, + parseTokenId, parseTimeoutSeconds, resolveDigest, resolveNetworkSelection, @@ -43,6 +44,20 @@ describe('parseDigest', () => { }); }); +describe('parseTokenId', () => { + it('accepts 64 hex characters, any case, with or without 0x', () => { + expect(HexConverter.encode(parseTokenId('AB'.repeat(32)))).toEqual('ab'.repeat(32)); + expect(HexConverter.encode(parseTokenId(`0x${'cd'.repeat(32)}`))).toEqual('cd'.repeat(32)); + }); + + it('rejects anything else as a usage error', () => { + expect(() => parseTokenId('ab'.repeat(31))).toThrow( + `--token-id must be a token id of 64 hex characters, got '${'ab'.repeat(31)}'.`, + ); + expect(() => parseTokenId('zz'.repeat(32))).toThrow(CliError); + }); +}); + describe('parsePrivateKey', () => { it('accepts 64 hex characters with surrounding whitespace', () => { expect(HexConverter.encode(parsePrivateKey(`${TEST_PRIVATE_KEY_HEX}\n`))).toEqual(TEST_PRIVATE_KEY_HEX); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index a91f291..8ad7e40 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -24,13 +24,17 @@ import { import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; describe('stampRevisionWith', () => { - const aggregator = TestAggregatorClient.create(); - const client = new StateTransitionClient(aggregator); const bob = SigningService.generatePrivateKey(); const bobPublic = new SigningService(bob).publicKey; + // A fresh aggregator per test: a genesis is deterministic in its issuer, digest + // and recipient, so tests sharing one would all continue the same lineage. + let aggregator: TestAggregatorClient; + let client: StateTransitionClient; let directory: string; beforeEach(async () => { + aggregator = TestAggregatorClient.create(); + client = new StateTransitionClient(aggregator); directory = await tempDir('proof-cli-revision-'); }); @@ -198,7 +202,10 @@ describe('stamp-revision output', () => { }); it('marks a new lineage and a final revision', () => { - expect(revisionText({ ...summary, created: true, revision: 0n })).toContain('Revision 0 (new lineage)\n'); + const created = revisionText({ ...summary, created: true, revision: 0n }); + expect(created).toContain('Revision 0 (new lineage)\n'); + expect(created).toContain(`Token id ${'aa'.repeat(32)} (identifies this lineage; give it to verifiers)\n`); + expect(revisionText(summary)).toContain(`Token id ${'aa'.repeat(32)}\n`); const final = revisionText({ ...summary, nextProducer: null }); expect(final).toContain('Revision 2 (final)\n'); expect(final).toContain('Next producer none; the lineage is finalized (sealed and burned)\n'); diff --git a/tests/unit/VerifyTest.ts b/tests/unit/VerifyTest.ts index bdb7755..6030043 100644 --- a/tests/unit/VerifyTest.ts +++ b/tests/unit/VerifyTest.ts @@ -2,6 +2,7 @@ import { writeFile } from 'node:fs/promises'; import path from 'node:path'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; @@ -48,6 +49,15 @@ describe('runVerify on a token whose network has no bundled pin', () => { }); }); + it('refuses --token-id on a token that is not a lineage, as a usage error', async () => { + await expect( + runVerify(file, { tokenId: 'ab'.repeat(32) }, testContext({ json: true }).context), + ).rejects.toMatchObject({ + exitCode: EXIT_USAGE, + message: '--token-id applies to document lineage tokens only; this token is not one.', + }); + }); + it('refuses a contradictory command line first, as a usage error', async () => { await expect( runVerify(file, { file: 'document.pdf', hash: TEST_DIGEST_HEX }, testContext({ json: true }).context), @@ -102,6 +112,57 @@ describe('runVerify on a document lineage', () => { expect(out).toContain(`Revision 2 SHA-256 ${THIRD_DIGEST_HEX}\n Signed by ${TEST_PUBLIC_KEY_HEX}\n`); expect(out).toContain(` Passes to ${fixture.bobPublicHex}\n Certified at`); expect(out).toContain('Expected hash not checked; pass --file or --hash'); + expect(out).toContain('Lineage id not checked; pass --token-id to tie this to the lineage you were given\n'); + }); + + it('checks the lineage against the token id it was given', async () => { + const tokenId = HexConverter.encode(fixture.token.id.bytes); + const text = testContext(); + expect(await runVerify(fixture.tokenFile, { tokenId, trustBase: fixture.trustBaseFile }, text.context)).toBe( + EXIT_OK, + ); + expect(text.stdout()).toContain('Lineage id matches\n'); + + const json = testContext({ json: true }); + expect( + await runVerify( + fixture.tokenFile, + { hash: THIRD_DIGEST_HEX, tokenId: `0x${tokenId.toUpperCase()}`, trustBase: fixture.trustBaseFile }, + json.context, + ), + ).toBe(EXIT_OK); + expect(json.json()).toMatchObject({ expectedHashMatches: true, expectedTokenIdMatches: true, status: 'OK' }); + }); + + it('fails on another lineage than the one it was given', async () => { + // The finalized copy shares the token id; any other lineage does not. + const other = HexConverter.encode(new Uint8Array(32).fill(0x5a)); + const text = testContext(); + expect(await runVerify(fixture.tokenFile, { tokenId: other, trustBase: fixture.trustBaseFile }, text.context)).toBe( + EXIT_VERIFICATION_FAILED, + ); + const out = text.stdout(); + expect(out).toMatch(/^Status {9}FAIL: Token id mismatch: this is not the lineage you were given\.\n/); + expect(out).toContain('Lineage id differs from the token id you were given\n'); + expect(out).toContain('Expected hash not checked; pass --file or --hash'); + + const json = testContext({ json: true }); + expect(await runVerify(fixture.tokenFile, { tokenId: other, trustBase: fixture.trustBaseFile }, json.context)).toBe( + EXIT_VERIFICATION_FAILED, + ); + expect(json.json()).toMatchObject({ + expectedHashMatches: null, + expectedTokenIdMatches: false, + reason: 'Token id mismatch: this is not the lineage you were given.', + status: 'FAIL', + }); + }); + + it('refuses a malformed token id before reading anything, as a usage error', async () => { + await expect(runVerify('/no/such/token', { tokenId: 'abcd' }, testContext().context)).rejects.toMatchObject({ + exitCode: EXIT_USAGE, + message: "--token-id must be a token id of 64 hex characters, got 'abcd'.", + }); }); it('finds an expected hash among the revisions', async () => { @@ -221,6 +282,7 @@ describe('verify output for a document lineage', () => { matchingRevisions: null, reason: null, status: 'OK', + tokenIdMatches: null, ...changes, }; } @@ -310,6 +372,38 @@ describe('verify output for a document lineage', () => { expect(lineageVerifyJson(failed, null)).toMatchObject({ details: null, trustBase: null }); }); + it.each<[string, Partial, string]>([ + ['no id given', {}, 'not checked; pass --token-id to tie this to the lineage you were given'], + ['verification failed first', { reason: 'x', status: 'FAIL' }, 'not checked; verification failed'], + ['the id matches', { tokenIdMatches: true }, 'matches'], + [ + 'the id differs', + { reason: 'x', status: 'FAIL', tokenIdMatches: false }, + 'differs from the token id you were given', + ], + ])('labels the lineage id when %s', (_, changes, label) => { + expect(lineageVerifyText(result(changes), bundled)).toContain(`Lineage id ${label}\n`); + }); + + it('does not blame a wrong lineage id on verification in the hash label, nor the reverse', () => { + const wrongId = result({ reason: 'x', status: 'FAIL', tokenIdMatches: false }); + expect(lineageVerifyText(wrongId, bundled)).toContain( + 'Expected hash not checked; pass --file or --hash to find your document in the lineage\n', + ); + const wrongHash = result({ matchingRevisions: [], reason: 'x', status: 'FAIL' }); + expect(lineageVerifyText(wrongHash, bundled)).toContain( + 'Lineage id not checked; pass --token-id to tie this to the lineage you were given\n', + ); + }); + + it('reports the lineage id comparison in JSON', () => { + expect(lineageVerifyJson(result(), bundled).expectedTokenIdMatches).toBeNull(); + expect(lineageVerifyJson(result({ tokenIdMatches: true }), bundled).expectedTokenIdMatches).toBe(true); + expect(lineageVerifyJson(result({ status: 'FAIL', tokenIdMatches: false }), bundled).expectedTokenIdMatches).toBe( + false, + ); + }); + it('reports a mismatch as such in JSON', () => { expect(lineageVerifyJson(result({ matchingRevisions: [] }), bundled)).toMatchObject({ expectedHashMatches: false, diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts index 8fecf7c..2f02e59 100644 --- a/tests/unit/lib/LineageClientTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; +import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; import { CertificationResponse } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/IAggregatorClient.js'; @@ -7,6 +8,9 @@ import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/ap import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; +import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; +import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; @@ -15,6 +19,7 @@ import { appendRevision, createLineage, currentProducerKey, + deriveGenesisSalt, isFinalized, LineageError, } from '../../../src/lib/LineageClient.js'; @@ -42,10 +47,19 @@ class CountingClient implements IAggregatorClient { } describe('LineageClient', () => { - const aggregator = TestAggregatorClient.create(); - const counting = new CountingClient(aggregator); - const client = new StateTransitionClient(counting); - const trustBase = aggregator.rootTrustBase; + // A fresh aggregator per test: a genesis is deterministic in its issuer, digest + // and recipient, so tests sharing one would all continue the same lineage. + let aggregator: TestAggregatorClient; + let counting: CountingClient; + let client: StateTransitionClient; + let trustBase: RootTrustBase; + + beforeEach(() => { + aggregator = TestAggregatorClient.create(); + counting = new CountingClient(aggregator); + client = new StateTransitionClient(counting); + trustBase = aggregator.rootTrustBase; + }); const fast = { pollIntervalMs: 10, timeoutMs: 2_000 }; const alice = SigningService.generatePrivateKey(); @@ -117,6 +131,48 @@ describe('LineageClient', () => { expect(HexConverter.encode(again.toCBOR())).toEqual(HexConverter.encode(first.toCBOR())); }); + it('replays an interrupted genesis identically, so running it again recovers the lineage', async () => { + const before = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + // Same issuer, digest and recipient: the same salt, so the aggregator already holds this mint. + const again = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + expect(HexConverter.encode(again.toCBOR())).toEqual(HexConverter.encode(before.toCBOR())); + }); + + it('derives a different token id from a different issuer, digest or recipient', async () => { + const id = async (issuer: Uint8Array, digest: Uint8Array, next: Uint8Array | null): Promise => + HexConverter.encode((await createLineage(client, trustBase, digest, issuer, next, fast)).id.bytes); + const base = await id(alice, TEST_DIGEST, publicKey(bob)); + const others = [ + await id(carol, TEST_DIGEST, publicKey(bob)), + await id(alice, OTHER_DIGEST, publicKey(bob)), + await id(alice, TEST_DIGEST, publicKey(carol)), + await id(alice, TEST_DIGEST, null), + ]; + expect(new Set([base, ...others]).size).toBe(5); + }); + + it('keeps the salt secret to the issuer: it depends on the private key', async () => { + const recipient = EncodedPredicate.fromPredicate(SignaturePredicate.create(publicKey(bob))); + const auxData = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const salt = await deriveGenesisSalt(alice, recipient, auxData); + expect(salt.toBytes()).toHaveLength(32); + expect((await deriveGenesisSalt(alice, recipient, auxData)).equals(salt)).toBe(true); + expect((await deriveGenesisSalt(carol, recipient, auxData)).equals(salt)).toBe(false); + // Pinned: the issuer's *private* key goes in, so nobody else can compute the + // token id before the genesis is certified and mint into its slot first. + const expected = createHash('sha256') + .update( + CborSerializer.encodeArray( + CborSerializer.encodeTextString('unicity-document-lineage/salt'), + CborSerializer.encodeByteString(alice), + recipient.toCBOR(), + CborSerializer.encodeByteString(auxData), + ), + ) + .digest(); + expect(salt.toBytes()).toEqual(new Uint8Array(expected)); + }); + it('cannot fork: a different successor of a spent state is never certified', async () => { const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); diff --git a/tests/unit/lib/LineageVerificationTest.ts b/tests/unit/lib/LineageVerificationTest.ts index 7aca6c3..39729f0 100644 --- a/tests/unit/lib/LineageVerificationTest.ts +++ b/tests/unit/lib/LineageVerificationTest.ts @@ -16,6 +16,7 @@ import { sealPredicate, } from '../../../src/lib/LineagePayload.js'; import { describeLineage, verifyLineage } from '../../../src/lib/LineageVerification.js'; +import { bundledTrustBase } from '../../../src/lib/networks.js'; import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; import { certifyMint } from '../../support/TimestampFixtures.js'; @@ -186,6 +187,45 @@ describe('LineageVerification', () => { }); }); + describe('token id', () => { + it('passes when the lineage is the one with the expected token id', async () => { + const token = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const result = await verifyLineage(token, trustBase, { expectedTokenId: token.id.bytes }); + expect(result.reason).toBeNull(); + expect(result.status).toEqual('OK'); + expect(result.tokenIdMatches).toBe(true); + expect((await verifyLineage(token, trustBase)).tokenIdMatches).toBeNull(); + }); + + // The shadow lineage from the review of issue #13: same issuer, same first + // producer, same initial document, but another salt. Both verify on their own, + // and only the token id tells them apart. + it('tells a parallel lineage from the same issuer and document apart', async () => { + const real = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + const shadow = await signedGenesis(data, SignaturePredicate.create(publicKey(bob))); + expect((await verifyLineage(shadow, trustBase)).status).toEqual('OK'); + expect(describeLineage(shadow).issuer).toEqual(describeLineage(real).issuer); + + const result = await verifyLineage(shadow, trustBase, { + expectedDigest: TEST_DIGEST, + expectedTokenId: real.id.bytes, + }); + expect(result.status).toEqual('FAIL'); + expect(result.tokenIdMatches).toBe(false); + expect(result.reason).toEqual('Token id mismatch: this is not the lineage you were given.'); + // The digest is still compared, so the output can show both. + expect(result.matchingRevisions).toEqual([0]); + }); + + it('does not compare the token id of a token that fails verification', async () => { + const token = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const result = await verifyLineage(token, bundledTrustBase('mainnet'), { expectedTokenId: token.id.bytes }); + expect(result.status).toEqual('FAIL'); + expect(result.tokenIdMatches).toBeNull(); + }); + }); + it('describes revisions without verifying', async () => { const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); const description = describeLineage(genesis); From 2365d27137ddfaa6168acda412f37a54b76a51cd Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 10:59:25 +0200 Subject: [PATCH 13/25] Recover interrupted lineage appends from a journal An append certified by the aggregator but never written to the token file could strand the lineage: the aggregator keeps only the transfer's hash, and a re-run with any different input ended in a bare TRANSACTION_HASH_MISMATCH. - stamp-revision records each append in ..pending next to the token file before submitting it (exclusive create, fsync), echoes it to stderr unless --quiet, and removes it once the token file holds the revision. - The next run recovers a journaled revision the aggregator certified, whatever inputs it is given; with other inputs it writes the recovered revision and refuses the request with ALREADY_CERTIFIED (exit 1). - STATE_ID_EXISTS is now a known answer: a replay of the same transaction completes without the "unknown status" warning, and a slot taken by another transaction is reported only once that proof authenticates against the trust base. Without a journal, the taken slot is reported as ALREADY_CERTIFIED and the attempted revision is echoed regardless of --quiet. - The test aggregator answers STATE_ID_EXISTS for a state id it already holds, as aggregator-go does. Co-Authored-By: Claude Opus 5.5 --- README.md | 8 +- skills/unicity-proof/SKILL.md | 10 +- src/cli.ts | 1 + src/commands/revisionJournal.ts | 229 +++++++++++++++++++++++ src/commands/stampRevision.ts | 203 +++++++++++++++++++-- src/config.ts | 6 +- src/errors.ts | 4 +- src/lib/LineageClient.ts | 220 +++++++++++++++++++--- src/lib/TimestampClient.ts | 124 +++++++++++-- src/lib/errors.ts | 16 ++ src/output.ts | 55 ++++++ tests/support/TestAggregatorClient.ts | 16 +- tests/unit/ConfigTest.ts | 2 + tests/unit/ErrorsTest.ts | 5 + tests/unit/StampRevisionTest.ts | 253 +++++++++++++++++++++++++- tests/unit/lib/LineageClientTest.ts | 127 ++++++++++++- 16 files changed, 1201 insertions(+), 78 deletions(-) create mode 100644 src/commands/revisionJournal.ts diff --git a/README.md b/README.md index acee047..161015f 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,11 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - The salt, and so the token id, is derived from the issuer's private key, the recipient and revision 0, not drawn at random. Running an interrupted genesis again with the same file, key, digest and recipient therefore recovers the same lineage instead of starting a parallel one. Nobody without the issuer's key can compute the token id before the genesis is certified, so nobody can mint into its slot first. Starting a second, separate lineage from the same document needs a different first producer (or issuer). - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. -- The state mask of each step is derived from the producer's key and the spent state, so if the command is interrupted after certification, running the same command again with the same file, key, digest and recipient recovers the same revision. +- **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `..pending` (`.doc.lineage.pending` for `doc.lineage`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. The journal is removed once the token file holds the revision. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. + - If the command is interrupted after submitting, running `stamp-revision` again on the same token file recovers the revision from the journal, whatever it is given this time. If the digest and recipient are the same, that completes the command. If not, the recovered revision is still written and echoed to stderr, the requested one is not appended, and the command exits 1. + - Without the journal, the same command with the same file, key, digest and recipient still recovers the revision, because the state mask of each step is derived from the producer's key and the spent state. With any other digest or recipient it exits 1, saying the revision was already certified with different content, and echoes what it tried to stderr even with `--quiet`. Only the interrupted run's digest and recipient can recover it then, which is what the echo is for. + - A journal the command cannot place (for another lineage, for a later revision than the token file holds, or unreadable) stops it with exit 2 and is left alone. + - A new lineage needs no journal: its genesis is derived from its inputs, and running it again with the same file, key, digest and recipient recovers it (see above). - Network options behave as for `stamp`. `verify` and `inspect` recognise lineage tokens by their token type and list every revision with its hash, signer, next producer and certification time: @@ -212,7 +216,7 @@ unicity-proof verify document.cbor --file document.pdf --json | jq -r .reference | Exit code | Meaning | | --- | --- | | 0 | Success. For `verify`: valid, and the hash (and, for a lineage, the token id) matched if one was given. | -| 1 | Verification failed, hash or token id mismatch, or the input is not a token. | +| 1 | Verification failed, hash or token id mismatch, or the input is not a token. For `stamp-revision`: the revision was already certified with different content. | | 2 | Usage or configuration error. | | 3 | Network error, aggregator rejection, or timeout. | | 130 | Interrupted. | diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index aaf25c6..5670ace 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -59,6 +59,14 @@ without it the proof is gone. - **A failed write after certification is recoverable.** The token is printed to stderr as hex, and both `verify` and `inspect` accept hex, so save that text. Do not re-stamp. +- **An interrupted `stamp-revision` append is recoverable; do not improvise.** + Run `stamp-revision` again on the same token file: it recovers the revision + from the `..pending` journal next to the token file. Never delete that + journal by hand; until the token file holds the revision, it is the only + record of what was certified. Exit 1 with `already certified with different + content` means an earlier run certified something else for this revision: + only that run's digest and recipient recover it, and they are on stderr from + when it was submitted. - `--sign` exits 2 unless a key is configured. Use it in any automated path that must never silently produce an anonymous stamp. `--anonymous` forces the opposite. @@ -74,7 +82,7 @@ about foresight. | Code | Meaning | | --- | --- | | `0` | Success. For `verify`: valid, and the hash (and, for a lineage, the token id) matched if one was given. | -| `1` | Verification failed, hash or token id mismatch, or the input is not a token. | +| `1` | Verification failed, hash or token id mismatch, or the input is not a token. For `stamp-revision`: the revision was already certified with different content. | | `2` | Usage or configuration error. | | `3` | Network error, aggregator rejection, or timeout. | | `130` | Interrupted. | diff --git a/src/cli.ts b/src/cli.ts index c8dad34..7938771 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -91,6 +91,7 @@ program .option('--recipient-key ', "compressed secp256k1 public key (66 hex) of the next revision's producer") .option('--recipient-key-file ', "file holding the next producer's public key; alternative to --recipient-key") .option('--finalize', 'make this the final revision: seal it and burn the token, so no revision can follow') + .option('--quiet', 'do not echo the pending revision to stderr once its journal file is written') .option('--network ', 'mainnet or testnet2; or UNICITY_NETWORK (default mainnet)') .option('--gateway ', 'override the gateway URL; or UNICITY_GATEWAY_URL') .option('--api-key ', 'gateway API key; or UNICITY_API_KEY') diff --git a/src/commands/revisionJournal.ts b/src/commands/revisionJournal.ts new file mode 100644 index 0000000..c16fbbb --- /dev/null +++ b/src/commands/revisionJournal.ts @@ -0,0 +1,229 @@ +import { open, readFile, rm } from 'node:fs/promises'; +import path from 'node:path'; + +import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; + +import { usageError } from '../errors.js'; +import { IPreparedRevision, isSameRevision, nextRevisionIndex } from '../lib/LineageClient.js'; + +/** + * A revision submitted to the aggregator but not yet written to the token file. + * The aggregator keeps only the transaction's hash, so until the token file holds + * the revision, this is the only record of what was certified. + */ +export interface IPendingRevision { + readonly digest: Uint8Array; + /** Null when the revision is a seal. */ + readonly nextProducer: Uint8Array | null; + readonly revision: bigint; + readonly tokenId: Uint8Array; + /** The transfer, CBOR-encoded. */ + readonly transaction: Uint8Array; +} + +const JOURNAL_FORMAT = 'unicity-proof/pending-revision'; +const JOURNAL_VERSION = 1; + +interface IJournalJson { + readonly digest: string; + readonly format: typeof JOURNAL_FORMAT; + readonly nextProducer: string | null; + readonly revision: string; + readonly tokenId: string; + readonly transaction: string; + readonly version: typeof JOURNAL_VERSION; +} + +/** + * @param {string} tokenFile Absolute token file path. + * @returns {string} The journal next to it: `..pending` in the same directory. + */ +export function journalPath(tokenFile: string): string { + return path.join(path.dirname(tokenFile), `.${path.basename(tokenFile)}.pending`); +} + +/** + * @param {Token} token The token the revision was prepared for. + * @param {IPreparedRevision} prepared The prepared revision. + * @param {Uint8Array} digest Its digest. + * @param {Uint8Array|null} nextProducer Its next producer; null for a seal. + * @returns {IPendingRevision} What the journal records. + */ +export function pendingRevision( + token: Token, + prepared: IPreparedRevision, + digest: Uint8Array, + nextProducer: Uint8Array | null, +): IPendingRevision { + return { + digest, + nextProducer, + revision: prepared.index, + tokenId: token.id.bytes, + transaction: prepared.transaction.toCBOR(), + }; +} + +function hasErrorCode(error: unknown, code: string): boolean { + // Not `instanceof Error`: errors from Node's fs need not come from this realm's Error. + return typeof error === 'object' && error !== null && (error as NodeJS.ErrnoException).code === code; +} + +/** + * Write the journal durably, before the revision is submitted: an exclusive + * create, then an fsync of the file and, where the platform allows, of its + * directory, so a crash cannot leave the name pointing at nothing. + * + * @param {string} file Journal path. + * @param {IPendingRevision} pending What to record. + * @throws {CliError} If the journal cannot be written; nothing has been submitted then. + */ +export async function writeJournal(file: string, pending: IPendingRevision): Promise { + const json: IJournalJson = { + digest: HexConverter.encode(pending.digest), + format: JOURNAL_FORMAT, + nextProducer: pending.nextProducer === null ? null : HexConverter.encode(pending.nextProducer), + revision: pending.revision.toString(), + tokenId: HexConverter.encode(pending.tokenId), + transaction: HexConverter.encode(pending.transaction), + version: JOURNAL_VERSION, + }; + try { + const handle = await open(file, 'wx'); + try { + await handle.writeFile(`${JSON.stringify(json, null, 2)}\n`); + await handle.sync(); + } finally { + await handle.close(); + } + } catch (error) { + await rm(file, { force: true }).catch(() => undefined); + throw usageError(`Cannot write the journal ${file}; nothing was submitted.`, { cause: error }); + } + try { + const directory = await open(path.dirname(file), 'r'); + try { + await directory.sync(); + } finally { + await directory.close(); + } + } catch { + // Not every platform can open or sync a directory; the file itself is synced. + } +} + +/** + * @param {string} file Journal path. + */ +export async function removeJournal(file: string): Promise { + await rm(file, { force: true }); +} + +function unreadable(file: string, detail: string, cause?: unknown): Error { + return usageError( + `The journal ${file} is not a pending lineage revision (${detail}). Move it away if it is not needed.`, + { cause }, + ); +} + +function hexField(file: string, value: unknown, name: string): Uint8Array { + if (typeof value !== 'string' || !/^([0-9a-f]{2})+$/.test(value)) { + throw unreadable(file, `bad ${name}`); + } + return HexConverter.decode(value); +} + +/** + * Read the journal, if there is one. + * + * @param {string} file Journal path. + * @returns {Promise} The pending revision, or null without a journal. + * @throws {CliError} If the file exists but is not a journal this version wrote. + */ +export async function readJournal(file: string): Promise { + let text: string; + try { + text = await readFile(file, 'utf8'); + } catch (error) { + if (hasErrorCode(error, 'ENOENT')) { + return null; + } + throw usageError(`Cannot read the journal ${file}.`, { cause: error }); + } + let json: Partial>; + try { + json = JSON.parse(text) as typeof json; + } catch (error) { + throw unreadable(file, 'not JSON', error); + } + if (json.format !== JOURNAL_FORMAT || json.version !== JOURNAL_VERSION) { + throw unreadable(file, 'unknown format'); + } + if (typeof json.revision !== 'string' || !/^[1-9][0-9]*$/.test(json.revision)) { + throw unreadable(file, 'bad revision'); + } + return { + digest: hexField(file, json.digest, 'digest'), + nextProducer: json.nextProducer === null ? null : hexField(file, json.nextProducer, 'nextProducer'), + revision: BigInt(json.revision), + tokenId: hexField(file, json.tokenId, 'tokenId'), + transaction: hexField(file, json.transaction, 'transaction'), + }; +} + +/** Where a journal stands against the token file it sits next to. */ +export type JournalStanding = + /** The token file already holds this revision: the journal is left over from a run that finished writing. */ + | { readonly kind: 'written' } + /** The journal is for the token file's next revision; recover it if it was certified. */ + | { readonly kind: 'next'; readonly transaction: TransferTransaction }; + +/** + * Relate a journal to the token file. Only a journal that is provably redundant, + * or provably for the next revision of this very lineage, is acted on; anything + * else stops the command, so that nothing is thrown away unread. + * + * @param {string} file Journal path, for messages. + * @param {IPendingRevision} pending The journal's contents. + * @param {Token} token The token file's lineage. + * @param {string} tokenFile Token file path, for messages. + * @returns {Promise} What to do with the journal. + * @throws {CliError} If the journal belongs to another lineage, to a later revision, or does not hang together. + */ +export async function journalStanding( + file: string, + pending: IPendingRevision, + token: Token, + tokenFile: string, +): Promise { + if (!areUint8ArraysEqual(pending.tokenId, token.id.bytes)) { + throw usageError( + `The journal ${file} is for lineage ${HexConverter.encode(pending.tokenId)}, but ${tokenFile} holds ` + + `lineage ${HexConverter.encode(token.id.bytes)}. Move the journal away if it is not needed.`, + ); + } + const next = nextRevisionIndex(token); + if (pending.revision < next) { + return { kind: 'written' }; + } + if (pending.revision > next) { + throw usageError( + `The journal ${file} is for revision ${pending.revision}, but ${tokenFile} ends at revision ${next - 1n}: ` + + 'the token file is out of date. Get the current one, or move the journal away if it is not needed.', + ); + } + const tip = token.latestTransaction; + let transaction: TransferTransaction; + try { + transaction = TransferTransaction.fromCBOR(pending.transaction, await tip.calculateStateHash(), tip.recipient); + } catch (error) { + throw unreadable(file, 'bad transaction', error); + } + if (!(await isSameRevision(transaction, pending.revision, pending.digest, pending.nextProducer))) { + throw unreadable(file, 'the digest or next producer does not match the transaction'); + } + return { kind: 'next', transaction }; +} diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 61e3e67..78e3e00 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -8,13 +8,44 @@ import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/Sta import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; import { CertifiedTransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedTransferTransaction.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; +import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { ICommandContext } from './context.js'; +import { + IPendingRevision, + journalPath, + journalStanding, + pendingRevision, + readJournal, + removeJournal, + writeJournal, +} from './revisionJournal.js'; import { decodeToken, tokenBytesFromInput } from './tokenInput.js'; import { IStampRevisionConfig, IStampRevisionFlags, resolveStampRevisionConfig } from '../config.js'; import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; -import { appendRevision, createLineage } from '../lib/LineageClient.js'; -import { revisionJson, revisionRecoveryLines, revisionText, toJsonLine, warningLine } from '../output.js'; +import { StampError } from '../lib/errors.js'; +import { + assertValidLineage, + certifyRevision, + createLineage, + currentProducerKey, + isSameRevision, + LineageError, + prepareRevision, + recoverRevision, +} from '../lib/LineageClient.js'; +import { ICertifyOptions } from '../lib/TimestampClient.js'; +import { + PendingRevisionContext, + pendingRevisionLines, + recoveredRevisionLine, + revisionJson, + revisionRecoveryLines, + revisionText, + toJsonLine, + warningLine, +} from '../output.js'; /** * Persist a lineage token whose newest revision has already been certified. @@ -58,6 +89,157 @@ export async function writeRevisionToken( } } +function writePending( + context: ICommandContext, + pending: IPendingRevision, + journalFile: string, + why: PendingRevisionContext, +): void { + context.stderr.write(pendingRevisionLines({ ...pending, journalFile }, why)); +} + +/** + * The lineage passes to someone after a recovered revision; say who. + * + * @param {Token} token Token ending in the recovered revision. + * @returns {string} Where the lineage stands now. + */ +function standingAfter(token: Token): string { + const next = currentProducerKey(token); + return next === null ? 'the lineage is now finalized' : `the lineage now passes to ${HexConverter.encode(next)}`; +} + +/** + * A revision from an earlier run was recovered, but it is not the one asked for: + * the token file now holds it, and the requested revision was not appended. + * + * @param {bigint} revision Index of the recovered revision. + * @param {Token} token Token ending in it. + * @param {string} tokenFile Where it was written. + * @returns {LineageError} The error to throw. + */ +function recoveredOtherRevision(revision: bigint, token: Token, tokenFile: string): LineageError { + return new LineageError( + `Revision ${revision} of this lineage was already certified with different content by an earlier ` + + `interrupted run. It was recovered and written to ${tokenFile}; the requested revision was not appended, ` + + `and ${standingAfter(token)}.`, + 'ALREADY_CERTIFIED', + ); +} + +/** What an append produced. */ +interface IAppendOutcome { + /** Key that signed the appended transfer. */ + readonly signer: Uint8Array; + readonly token: Token; +} + +/** + * Append the requested revision, journaling it first, so that a run interrupted + * after certification can be recovered by the next one. + * + * - A journal left by an earlier run is dealt with first. If its revision was + * certified, it is written to the token file; if it was not, the journal is + * dropped, but kept in memory in case it is certified while this run is going. + * - The requested revision is then journaled, echoed to stderr unless `--quiet`, + * submitted, written to the token file, and the journal removed. + * - If its slot turns out to be taken (`ALREADY_CERTIFIED`), the journal is + * removed, since it was never certified, and the revision is echoed whatever + * `--quiet` says, so the user can see what this run tried. + * + * @param {IStampRevisionConfig} config Resolved configuration. + * @param {StateTransitionClient} client Aggregator client. + * @param {ICommandContext} context Streams. + * @param {ICertifyOptions} options Certification options. + * @param {Token} token The token file's lineage. + * @returns {Promise} The appended token. + */ +async function appendJournaled( + config: IStampRevisionConfig, + client: StateTransitionClient, + context: ICommandContext, + options: ICertifyOptions, + token: Token, +): Promise { + const trustBase = config.network.trustBase; + const journalFile = journalPath(config.tokenFile); + // Before the journal is acted on, in either direction. + await assertValidLineage(token, trustBase); + + // A recovered revision is written and its journal removed, and then either it was + // the revision asked for, or the request cannot go ahead. + const settle = async ( + pending: IPendingRevision, + recovered: Token, + transaction: TransferTransaction, + ): Promise => { + await writeRevisionToken(config.tokenFile, recovered.toCBOR(), false, context); + await removeJournal(journalFile); + if (await isSameRevision(transaction, pending.revision, config.digest, config.recipientKey)) { + context.stderr.write(recoveredRevisionLine(pending.revision, journalFile)); + return { signer: currentProducerKey(token) as Uint8Array, token: recovered }; + } + writePending(context, pending, journalFile, 'recovered'); + throw recoveredOtherRevision(pending.revision, recovered, config.tokenFile); + }; + + let unconfirmed: { pending: IPendingRevision; transaction: TransferTransaction } | null = null; + const earlier = await readJournal(journalFile); + if (earlier !== null) { + const standing = await journalStanding(journalFile, earlier, token, config.tokenFile); + if (standing.kind === 'next') { + let recovered: Token | null = null; + try { + recovered = await recoverRevision(client, trustBase, token, standing.transaction, options); + } catch (error) { + // Its slot holds another transfer: the journaled one was never certified. + if (!(error instanceof LineageError && error.code === 'ALREADY_CERTIFIED')) { + throw error; + } + } + if (recovered !== null) { + return settle(earlier, recovered, standing.transaction); + } + unconfirmed = { pending: earlier, transaction: standing.transaction }; + } + await removeJournal(journalFile); + } + + const prepared = await prepareRevision(token, trustBase, config.digest, config.privateKey, config.recipientKey); + const pending = pendingRevision(token, prepared, config.digest, config.recipientKey); + await writeJournal(journalFile, pending); + if (!config.quiet) { + writePending(context, pending, journalFile, 'submitting'); + } + + let appended: Token; + try { + appended = await certifyRevision(client, trustBase, token, prepared, options); + } catch (error) { + if (error instanceof StampError) { + // Refused outright: nothing was certified. + await removeJournal(journalFile); + } else if (error instanceof LineageError && error.code === 'ALREADY_CERTIFIED') { + await removeJournal(journalFile); + writePending(context, pending, journalFile, 'rejected'); + if (unconfirmed !== null) { + // The earlier run's revision was still waiting for its round when this run looked. + const recovered = await recoverRevision(client, trustBase, token, unconfirmed.transaction, options).catch( + () => null, + ); + if (recovered !== null) { + return settle(unconfirmed.pending, recovered, unconfirmed.transaction); + } + } + } + throw error; + } + + await writeRevisionToken(config.tokenFile, appended.toCBOR(), false, context); + await removeJournal(journalFile); + return { signer: new SigningService(config.privateKey).publicKey, token: appended }; +} + function latestCertified(token: Token): CertifiedMintTransaction | CertifiedTransferTransaction { return token.transactions.at(-1) ?? token.genesis; } @@ -86,28 +268,19 @@ export async function stampRevisionWith( }; let token: Token; + let signer = new SigningService(config.privateKey).publicKey; const created = config.tokenBytes === null; if (config.tokenBytes === null) { token = await createLineage(client, trustBase, config.digest, config.privateKey, config.recipientKey, options); + await writeRevisionToken(config.tokenFile, token.toCBOR(), true, context); } else { const decoded = await decodeToken(tokenBytesFromInput(config.tokenBytes)); if (decoded.token === null) { throw new CliError(`${config.tokenFile} is ${decoded.error}.`, EXIT_VERIFICATION_FAILED); } - token = await appendRevision( - client, - trustBase, - decoded.token, - config.digest, - config.privateKey, - config.recipientKey, - options, - ); + ({ signer, token } = await appendJournaled(config, client, context, options, decoded.token)); } - const bytes = token.toCBOR(); - await writeRevisionToken(config.tokenFile, bytes, created, context); - const latest = latestCertified(token); const certificate = latest.inclusionProof.unicityCertificate; const summary = { @@ -121,7 +294,7 @@ export async function stampRevisionWith( revision: BigInt(token.transactions.length), roundNumber: certificate.inputRecord.roundNumber, roundTimestamp: certificate.inputRecord.timestamp, - signer: new SigningService(config.privateKey).publicKey, + signer, tokenFile: config.tokenFile, tokenId: token.id.bytes, }; diff --git a/src/config.ts b/src/config.ts index e30b2d1..25f7299 100644 --- a/src/config.ts +++ b/src/config.ts @@ -456,6 +456,7 @@ export interface IStampRevisionFlags extends INetworkFlags { readonly file?: string; readonly finalize?: boolean; readonly keyFile?: string; + readonly quiet?: boolean; readonly recipientKey?: string; readonly recipientKeyFile?: string; readonly timeout?: string; @@ -469,6 +470,8 @@ export interface IStampRevisionConfig { readonly network: ITimestampNetwork; /** Signs the new revision: the genesis reason for a new lineage, the transfer otherwise. */ readonly privateKey: Uint8Array; + /** Leave the pending revision off stderr once its journal file is written. */ + readonly quiet: boolean; /** * Compressed public key of whoever produces the following revision; null to * finalize, sealing this revision as the last one. @@ -624,5 +627,6 @@ export async function resolveStampRevisionConfig( } const digest = (await resolveDigest(digestArgument, flags.file)) as Uint8Array; - return { allowInsecure, apiKey, digest, network, privateKey, recipientKey, timeoutMs, tokenBytes, tokenFile }; + const quiet = flags.quiet ?? false; + return { allowInsecure, apiKey, digest, network, privateKey, quiet, recipientKey, timeoutMs, tokenBytes, tokenFile }; } diff --git a/src/errors.ts b/src/errors.ts index 2620f40..ff96ffd 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -8,7 +8,7 @@ import { errorMessage, StampError } from './lib/errors.js'; import { LineageError } from './lib/LineageClient.js'; export const EXIT_OK = 0; -/** Verification failed, hash mismatch, or the input is not a token. */ +/** Verification failed, hash mismatch, the input is not a token, or a lineage revision slot is taken. */ export const EXIT_VERIFICATION_FAILED = 1; /** Usage or configuration error. */ export const EXIT_USAGE = 2; @@ -71,7 +71,7 @@ export function toExitCode(error: unknown, interrupted = false): number { return EXIT_VERIFICATION_FAILED; } if (error instanceof LineageError) { - return error.code === 'INVALID_TOKEN' ? EXIT_VERIFICATION_FAILED : EXIT_USAGE; + return error.code === 'INVALID_TOKEN' || error.code === 'ALREADY_CERTIFIED' ? EXIT_VERIFICATION_FAILED : EXIT_USAGE; } return EXIT_USAGE; } diff --git a/src/lib/LineageClient.ts b/src/lib/LineageClient.ts index aafd1d2..840ad12 100644 --- a/src/lib/LineageClient.ts +++ b/src/lib/LineageClient.ts @@ -1,5 +1,6 @@ import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; +import { InclusionProof } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProof.js'; import { DataHasher } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasher.js'; import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; @@ -17,6 +18,7 @@ import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/Tok import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; +import { StateAlreadyCertifiedError } from './errors.js'; import { LINEAGE_TAG, LINEAGE_TOKEN_TYPE, @@ -25,7 +27,7 @@ import { sealPredicate, } from './LineagePayload.js'; import { createLineageVerificationContext, verifyLineage } from './LineageVerification.js'; -import { ICertifyOptions, certifyMintTransaction, certifyTransaction } from './TimestampClient.js'; +import { ICertifyOptions, certifyMintTransaction, certifyTransaction, findCertifiedProof } from './TimestampClient.js'; /** Thrown when a revision cannot be appended to the given token with the given key. */ export class LineageError extends Error { @@ -33,9 +35,10 @@ export class LineageError extends Error { message: string, /** * `INVALID_TOKEN`: the token does not verify as a lineage; `WRONG_KEY`: the key - * cannot append to it; `FINALIZED`: the lineage is sealed and nothing can. + * cannot append to it; `FINALIZED`: the lineage is sealed and nothing can; + * `ALREADY_CERTIFIED`: this revision slot was already certified with other content. */ - public readonly code: 'FINALIZED' | 'INVALID_TOKEN' | 'WRONG_KEY', + public readonly code: 'ALREADY_CERTIFIED' | 'FINALIZED' | 'INVALID_TOKEN' | 'WRONG_KEY', options?: ErrorOptions, ) { super(message, options); @@ -204,6 +207,23 @@ export async function createLineage( return Token.mint(await certifyMintTransaction(client, context, transaction, options), context); } +/** + * Check, without network contact, that `token` is a valid lineage on the network of `trustBase`. + * + * @param {Token} token Lineage token. + * @param {RootTrustBase} trustBase Trust base of the token's network. + * @throws {LineageError} `INVALID_TOKEN` if it does not verify. + */ +export async function assertValidLineage(token: Token, trustBase: RootTrustBase): Promise { + const result = await verifyLineage(token, trustBase); + if (result.status !== 'OK') { + throw new LineageError( + `The token file is not a valid document lineage token: ${result.reason ?? 'unknown'}`, + 'INVALID_TOKEN', + ); + } +} + /** * Check, without network contact, that `producerPrivateKey` can append to `token` * on the network of `trustBase`: the token is a valid lineage for that network and @@ -219,13 +239,7 @@ export async function assertCanAppend( trustBase: RootTrustBase, producerPublicKey: Uint8Array, ): Promise { - const result = await verifyLineage(token, trustBase); - if (result.status !== 'OK') { - throw new LineageError( - `The token file is not a valid document lineage token: ${result.reason ?? 'unknown'}`, - 'INVALID_TOKEN', - ); - } + await assertValidLineage(token, trustBase); if (isFinalized(token)) { throw new LineageError('The lineage is finalized; no revision can follow its sealed final revision.', 'FINALIZED'); } @@ -244,34 +258,39 @@ export async function assertCanAppend( } } +/** A revision ready to submit: the transfer and the request that certifies it. */ +export interface IPreparedRevision { + readonly certificationData: CertificationData; + readonly index: bigint; + readonly transaction: TransferTransaction; +} + /** - * Append the next revision: a transfer, signed under the `P_sig` the previous - * revision named, whose auxiliary data is `[i, digest]` and whose recipient is the - * producer of revision `i + 1`; or, without a next producer, the seal - * `["seal", i, digest]`, burning the token. + * Build, without network contact, the next revision of `token`: a transfer, signed + * under the `P_sig` the previous revision named, whose auxiliary data is + * `[i, digest]` and whose recipient is the producer of revision `i + 1`; or, + * without a next producer, the seal `["seal", i, digest]`, burning the token. + * The state mask is derived, so the same inputs always give the same transfer. * - * @param {StateTransitionClient} client Aggregator client. - * @param {RootTrustBase} trustBase Trust base of the network behind the client. * @param {Token} token Existing lineage token. + * @param {RootTrustBase} trustBase Trust base of the token's network. * @param {Uint8Array} digest 32-byte SHA-256 digest of the new revision. * @param {Uint8Array} producerPrivateKey Key named by the latest revision; signs the transfer. * @param {Uint8Array|null} nextProducer Compressed public key of whoever produces the following revision; null to finalize. - * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. - * @returns {Promise} The token with the new revision appended. + * @returns {Promise} The transfer, its index and its certification request. + * @throws {LineageError} If the token is invalid or the key cannot append to it. */ -export async function appendRevision( - client: StateTransitionClient, - trustBase: RootTrustBase, +export async function prepareRevision( token: Token, + trustBase: RootTrustBase, digest: Uint8Array, producerPrivateKey: Uint8Array, nextProducer: Uint8Array | null, - options: ICertifyOptions = {}, -): Promise { +): Promise { const signer = new SigningService(producerPrivateKey); await assertCanAppend(token, trustBase, signer.publicKey); - const index = BigInt(token.transactions.length + 1); + const index = nextRevisionIndex(token); const { auxData, recipient } = await revisionStep(index, digest, nextProducer); const transaction = await TransferTransaction.create( token, @@ -283,8 +302,70 @@ export async function appendRevision( transaction, await SignaturePredicateUnlockScript.create(transaction, signer), ); + return { certificationData, index, transaction }; +} + +/** + * @param {Token} token Lineage token. + * @returns {bigint} Index of the revision that would be appended next. + */ +export function nextRevisionIndex(token: Token): bigint { + return BigInt(token.transactions.length + 1); +} + +/** + * Whether `transaction` is the revision that `digest` and `nextProducer` would + * make at its position. Needs no key: it compares what the transfer carries. + * + * @param {TransferTransaction} transaction A lineage transfer. + * @param {bigint} index Its revision index. + * @param {Uint8Array} digest 32-byte SHA-256 digest. + * @param {Uint8Array|null} nextProducer Next producer's public key; null for a seal. + * @returns {Promise} True when payload and recipient both match. + */ +export async function isSameRevision( + transaction: TransferTransaction, + index: bigint, + digest: Uint8Array, + nextProducer: Uint8Array | null, +): Promise { + const { auxData, recipient } = await revisionStep(index, digest, nextProducer); + const data = transaction.data; + return ( + data !== null && + areUint8ArraysEqual(data, auxData) && + areUint8ArraysEqual(transaction.recipient.toCBOR(), EncodedPredicate.fromPredicate(recipient).toCBOR()) + ); +} + +function alreadyCertified(index: bigint, cause: unknown): LineageError { + return new LineageError( + `Revision ${index} of this lineage was already certified with different content, probably by an earlier ` + + "interrupted run whose token file was not written. Run stamp-revision again with that run's digest and " + + 'next producer to recover it.', + 'ALREADY_CERTIFIED', + { cause }, + ); +} + +/** + * Attach a certified transfer to the token and check it against the chain rules. + * + * @param {RootTrustBase} trustBase Trust base of the token's network. + * @param {Token} token Lineage token the transfer continues. + * @param {TransferTransaction} transaction The transfer. + * @param {InclusionProof} proof Its inclusion proof. + * @param {ICertifyOptions} options Warning sink. + * @returns {Promise} The token with the transfer appended. + */ +async function attachRevision( + trustBase: RootTrustBase, + token: Token, + transaction: TransferTransaction, + proof: InclusionProof, + options: ICertifyOptions, +): Promise { const context = createLineageVerificationContext(trustBase); - const proof = await certifyTransaction(client, context, certificationData, transaction, options); const certified = await transaction.toCertifiedTransaction( context.trustBase, context.predicateVerifier, @@ -301,3 +382,92 @@ export async function appendRevision( } return appended; } + +/** + * Submit a prepared revision and append it to the token once certified. A repeat + * of an already certified revision recovers it. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Token} token The token the revision was prepared for. + * @param {IPreparedRevision} prepared From {@link prepareRevision}. + * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. + * @returns {Promise} The token with the new revision appended. + * @throws {LineageError} `ALREADY_CERTIFIED` if this revision slot holds another transfer. + */ +export async function certifyRevision( + client: StateTransitionClient, + trustBase: RootTrustBase, + token: Token, + prepared: IPreparedRevision, + options: ICertifyOptions = {}, +): Promise { + const context = createLineageVerificationContext(trustBase); + let proof: InclusionProof; + try { + proof = await certifyTransaction(client, context, prepared.certificationData, prepared.transaction, options); + } catch (error) { + if (error instanceof StateAlreadyCertifiedError) { + throw alreadyCertified(prepared.index, error); + } + throw error; + } + return attachRevision(trustBase, token, prepared.transaction, proof, options); +} + +/** + * Recover a revision that an earlier run submitted but did not record: if the + * aggregator certified `transaction`, append it to the token. Needs no key, and + * submits nothing. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Token} token The token the transfer continues. + * @param {TransferTransaction} transaction The transfer the earlier run submitted. + * @param {ICertifyOptions} options Abort signal, warning sink. + * @returns {Promise} The token with the revision appended, or null if it is not certified. + * @throws {LineageError} `ALREADY_CERTIFIED` if the slot holds another transfer instead. + */ +export async function recoverRevision( + client: StateTransitionClient, + trustBase: RootTrustBase, + token: Token, + transaction: TransferTransaction, + options: ICertifyOptions = {}, +): Promise { + let proof: InclusionProof | null; + try { + proof = await findCertifiedProof(client, createLineageVerificationContext(trustBase), transaction, options.signal); + } catch (error) { + if (error instanceof StateAlreadyCertifiedError) { + throw alreadyCertified(nextRevisionIndex(token), error); + } + throw error; + } + return proof === null ? null : attachRevision(trustBase, token, transaction, proof, options); +} + +/** + * Append the next revision: {@link prepareRevision}, then {@link certifyRevision}. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Token} token Existing lineage token. + * @param {Uint8Array} digest 32-byte SHA-256 digest of the new revision. + * @param {Uint8Array} producerPrivateKey Key named by the latest revision; signs the transfer. + * @param {Uint8Array|null} nextProducer Compressed public key of whoever produces the following revision; null to finalize. + * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. + * @returns {Promise} The token with the new revision appended. + */ +export async function appendRevision( + client: StateTransitionClient, + trustBase: RootTrustBase, + token: Token, + digest: Uint8Array, + producerPrivateKey: Uint8Array, + nextProducer: Uint8Array | null, + options: ICertifyOptions = {}, +): Promise { + const prepared = await prepareRevision(token, trustBase, digest, producerPrivateKey, nextProducer); + return certifyRevision(client, trustBase, token, prepared, options); +} diff --git a/src/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index 9083f19..46e05b2 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -3,17 +3,24 @@ import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/Roo import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; import { CertificationStatus } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; import { InclusionProof } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProof.js'; +import { JsonRpcNetworkError } from '@unicitylabs/state-transition-sdk/lib/api/json-rpc/JsonRpcNetworkError.js'; +import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; +import { DataHash } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHash.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; import type { ITransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/ITransaction.js'; import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { + InclusionProofVerificationRule, + InclusionProofVerificationStatus, +} from '@unicitylabs/state-transition-sdk/lib/transaction/verification/rule/InclusionProofVerificationRule.js'; import { VerificationContext } from '@unicitylabs/state-transition-sdk/lib/transaction/verification/VerificationContext.js'; -import { waitInclusionProof } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; +import { SleepError, waitInclusionProof } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; import { TIMESTAMP_RECIPIENT, TIMESTAMP_TOKEN_TYPE } from './constants.js'; -import { StampError } from './errors.js'; +import { StampError, StateAlreadyCertifiedError } from './errors.js'; import { ITimestampNetwork } from './networks.js'; import { TimestampPayload } from './TimestampPayload.js'; import { createVerificationContext } from './verification.js'; @@ -41,13 +48,84 @@ export interface IStampOptions extends ICertifyOptions { const KNOWN_STATUSES: readonly string[] = Object.values(CertificationStatus); const SUCCESS_STATUS: string = CertificationStatus.SUCCESS; +/** + * The aggregator's answer when it already holds a request for the state being + * spent. The SDK does not list it; aggregator-go sends it for every repeated + * state id, whether the earlier request was this very transaction or another. + */ +export const STATE_ID_EXISTS_STATUS = 'STATE_ID_EXISTS'; + +/** + * Look up the inclusion proof the aggregator already holds for the state that + * `transaction` spends, and tell whether it certifies this transaction. + * + * A proof for another transaction is reported only once it authenticates against + * the trust base under that other transaction's hash; the hash comparison alone + * comes before any authentication, and a gateway could fake it. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {VerificationContext} context Verification context for the network behind the client. + * @param {ITransaction} transaction Transaction whose state is looked up. + * @param {AbortSignal} [signal] Abort signal for the request. + * @returns {Promise} The verified proof of this transaction, or null when + * the state is not certified yet or the proof does not verify. + * @throws {StateAlreadyCertifiedError} If the state was certified with another transaction. + */ +export async function findCertifiedProof( + client: StateTransitionClient, + context: VerificationContext, + transaction: ITransaction, + signal?: AbortSignal, +): Promise { + const stateId = await StateId.fromTransaction(transaction); + let proof: InclusionProof | null; + try { + proof = (await client.getInclusionProof(stateId, { signal })).inclusionProof; + } catch (error) { + if (error instanceof JsonRpcNetworkError && error.status === 404) { + return null; + } + throw error; + } + if (proof === null) { + return null; + } + const certified = proof; + const verify = async (transactionHash: DataHash): Promise => + ( + await InclusionProofVerificationRule.verify( + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + certified, + transactionHash, + transaction.expiresAt, + transaction.lockScript, + transaction.sourceStateHash, + ) + ).status; + + const status = await verify(await transaction.calculateTransactionHash()); + if (status === InclusionProofVerificationStatus.OK) { + return certified; + } + if ( + status === InclusionProofVerificationStatus.TRANSACTION_HASH_MISMATCH && + (await verify(certified.certificationData.transactionHash)) === InclusionProofVerificationStatus.OK + ) { + throw new StateAlreadyCertifiedError(certified); + } + return null; +} /** * Submit a certification request and wait for its inclusion proof. * - * An unknown status is a warning rather than a failure: the aggregator answers a - * repeated request with `STATE_ID_EXISTS`, which the SDK does not list, and the - * proof that then arrives is checked against this transaction's hash anyway. + * `STATE_ID_EXISTS` means the aggregator already holds a request for this state. + * If it is this transaction, a repeated run, the proof it holds is returned; if + * it is another, {@link StateAlreadyCertifiedError} says so. Any other status the + * SDK does not list is a warning rather than a failure, and the proof that then + * arrives is checked against this transaction's hash anyway. * * @param {StateTransitionClient} client Aggregator client. * @param {VerificationContext} context Verification context for the network behind the client. @@ -56,6 +134,7 @@ const SUCCESS_STATUS: string = CertificationStatus.SUCCESS; * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. * @returns {Promise} Verified inclusion proof. * @throws {StampError} If the aggregator returns a known failure status. + * @throws {StateAlreadyCertifiedError} If the state was certified with another transaction. * @throws {SleepError} If the proof does not arrive before the timeout or abort. */ export async function certifyTransaction( @@ -66,7 +145,13 @@ export async function certifyTransaction( options: ICertifyOptions = {}, ): Promise { const response = await client.submitCertificationRequest(certificationData, { signal: options.signal }); - if (response.status !== SUCCESS_STATUS) { + const exists = response.status === STATE_ID_EXISTS_STATUS; + if (exists) { + const proof = await findCertifiedProof(client, context, transaction, options.signal); + if (proof !== null) { + return proof; + } + } else if (response.status !== SUCCESS_STATUS) { if (KNOWN_STATUSES.includes(response.status)) { throw new StampError(response.status); } @@ -79,15 +164,24 @@ export async function certifyTransaction( if (options.signal) { signals.push(options.signal); } - return waitInclusionProof( - client, - context.trustBase, - context.predicateVerifier, - context.unicityCertificateVerifier, - transaction, - AbortSignal.any(signals), - options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, - ); + try { + return await waitInclusionProof( + client, + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + transaction, + AbortSignal.any(signals), + options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, + ); + } catch (error) { + // The earlier request was still waiting for its round. The SDK reports a proof + // of another transaction only as a plain Error, so look again to say what it is. + if (exists && !(error instanceof SleepError)) { + await findCertifiedProof(client, context, transaction, options.signal); + } + throw error; + } } /** diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 2b44070..a0f2b80 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -1,3 +1,5 @@ +import type { InclusionProof } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProof.js'; + /** The aggregator refused the certification request with a status the SDK knows. */ export class StampError extends Error { public constructor(public readonly status: string) { @@ -6,6 +8,20 @@ export class StampError extends Error { } } +/** + * The state the transaction spends was already certified, with a different + * transaction: the slot is taken, and this transaction can never be certified. + */ +export class StateAlreadyCertifiedError extends Error { + /** + * @param {InclusionProof} proof Authenticated proof of the transaction that was certified instead. + */ + public constructor(public readonly proof: InclusionProof) { + super('The aggregator already certified a different transaction for this state.'); + this.name = 'StateAlreadyCertifiedError'; + } +} + /** * @param {unknown} error Thrown value. * @returns {string} The message of an Error, or the string form of anything else. diff --git a/src/output.ts b/src/output.ts index ed645cf..e394923 100644 --- a/src/output.ts +++ b/src/output.ts @@ -455,6 +455,61 @@ export function revisionJson(summary: IRevisionSummary): IRevisionJson { }; } +/** A revision recorded in a journal file, for the notes `stamp-revision` prints on stderr. */ +export interface IPendingRevisionNote { + readonly digest: Uint8Array; + readonly journalFile: string; + /** Null when the revision is a seal. */ + readonly nextProducer: Uint8Array | null; + readonly revision: bigint; + readonly tokenId: Uint8Array; +} + +/** + * Why a pending revision is being printed: `submitting` before it goes to the + * aggregator; `rejected` when its slot turned out to be taken; `recovered` when it + * was certified by an earlier run and has just been written to the token file. + */ +export type PendingRevisionContext = 'recovered' | 'rejected' | 'submitting'; + +/** + * The contents of a revision journal, for stderr: enough to recover the revision + * by hand if the journal itself is lost. + * + * @param {IPendingRevisionNote} note The revision. + * @param {PendingRevisionContext} context Why it is being printed. + * @returns {string} Lines for stderr, ending in a newline. + */ +export function pendingRevisionLines(note: IPendingRevisionNote, context: PendingRevisionContext): string { + const heading = { + recovered: `Recovered revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}, certified by an interrupted run:`, + rejected: `Revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}, as this run submitted it (not certified):`, + submitting: `Submitting revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}:`, + }[context]; + const lines = [ + heading, + ` ${line('Stamped', `SHA-256 ${HexConverter.encode(note.digest)}`)}`, + ` ${line('Next producer', keyLabel(note.nextProducer, FINALIZED_LABEL))}`, + ]; + if (context === 'submitting') { + lines.push( + ` ${line('Journal', note.journalFile)}`, + 'If this run is interrupted, run stamp-revision on the same token file again to recover the revision;', + 'without the journal, run it with this digest and next producer.', + ); + } + return `${lines.join('\n')}\n`; +} + +/** + * @param {bigint} revision Revision index. + * @param {string} journalFile Journal it came from. + * @returns {string} Note for stderr that a revision was recovered. + */ +export function recoveredRevisionLine(revision: bigint, journalFile: string): string { + return `Recovered revision ${revision} from the journal ${journalFile} of an interrupted run.\n`; +} + /** * Last resort for a revision that was certified but could not be written. * diff --git a/tests/support/TestAggregatorClient.ts b/tests/support/TestAggregatorClient.ts index 1ebb01c..8670c92 100644 --- a/tests/support/TestAggregatorClient.ts +++ b/tests/support/TestAggregatorClient.ts @@ -21,6 +21,7 @@ import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verifi import { createRootTrustBase } from './RootTrustBaseFixture.js'; import { createUnicityCertificate } from './UnicityCertificateFixture.js'; +import { STATE_ID_EXISTS_STATUS } from '../../src/lib/TimestampClient.js'; /** Lifetime granted to a request without its own deadline, matching the aggregator's default. */ const REQUEST_TTL = 3600n; @@ -92,14 +93,17 @@ export class TestAggregatorClient implements IAggregatorClient { return CertificationResponse.create(CertificationStatus.REQUEST_EXPIRED); } + // Like aggregator-go: a state id it already holds is answered with STATE_ID_EXISTS, + // whether the request is the same transaction again or another one. const path = TestAggregatorClient.pathOf(stateId); - if (!this.requests.has(path)) { - const referenceTime = this.referenceTime; - const leafValue = await calculateLeafValue(certificationData.transactionHash, referenceTime); - await this.smt.addLeaf(stateId.data, leafValue.data); - this.requests.set(path, { certificationData, referenceTime }); - this.referenceTime += 1n; + if (this.requests.has(path)) { + return CertificationResponse.create(STATE_ID_EXISTS_STATUS); } + const referenceTime = this.referenceTime; + const leafValue = await calculateLeafValue(certificationData.transactionHash, referenceTime); + await this.smt.addLeaf(stateId.data, leafValue.data); + this.requests.set(path, { certificationData, referenceTime }); + this.referenceTime += 1n; return CertificationResponse.create(CertificationStatus.SUCCESS); } diff --git a/tests/unit/ConfigTest.ts b/tests/unit/ConfigTest.ts index 0ee4ba9..760bd89 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -403,6 +403,8 @@ describe('resolveStampRevisionConfig', () => { expect(config.privateKey).toEqual(TEST_PRIVATE_KEY); expect(HexConverter.encode(config.recipientKey as Uint8Array)).toEqual(TEST_PUBLIC_KEY_HEX); expect(config.network.preset).toEqual('mainnet'); + expect(config.quiet).toBe(false); + expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), quiet: true }, env)).quiet).toBe(true); }); it('reads an existing token file and a recipient key file', async () => { diff --git a/tests/unit/ErrorsTest.ts b/tests/unit/ErrorsTest.ts index ab48184..e6a0937 100644 --- a/tests/unit/ErrorsTest.ts +++ b/tests/unit/ErrorsTest.ts @@ -8,6 +8,7 @@ import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verifi import { CliError, describeError, toExitCode, usageError } from '../../src/errors.js'; import { StampError } from '../../src/lib/errors.js'; +import { LineageError } from '../../src/lib/LineageClient.js'; function errno(code: string, path?: string): NodeJS.ErrnoException { const error: NodeJS.ErrnoException = new Error(`${code}: ${path ?? ''}`); @@ -29,6 +30,10 @@ describe('toExitCode', () => { ['JSON-RPC error object', new JsonRpcDataError({ code: -32000, message: 'denied' }), 3], ['fetch connection failure', new TypeError('fetch failed'), 3], ['token failed SDK verification', new VerificationError('bad token', failed), 1], + ['not a valid lineage token', new LineageError('x', 'INVALID_TOKEN'), 1], + ['lineage revision slot already taken', new LineageError('x', 'ALREADY_CERTIFIED'), 1], + ['wrong key for the lineage', new LineageError('x', 'WRONG_KEY'), 2], + ['finalized lineage', new LineageError('x', 'FINALIZED'), 2], ['file not found', errno('ENOENT', '/x'), 2], ['file exists', errno('EEXIST', '/x'), 2], ['anything else', new Error('?'), 2], diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 8ad7e40..81e4637 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -1,6 +1,11 @@ -import { readdir, readFile } from 'node:fs/promises'; +import { readdir, readFile, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; +import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; +import { CertificationResponse } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; +import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/IAggregatorClient.js'; +import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js'; +import { JsonRpcNetworkError } from '@unicitylabs/state-transition-sdk/lib/api/json-rpc/JsonRpcNetworkError.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; @@ -10,7 +15,14 @@ import { stampRevisionWith } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; -import { IRevisionSummary, revisionJson, revisionRecoveryLines, revisionText } from '../../src/output.js'; +import { + IRevisionSummary, + pendingRevisionLines, + recoveredRevisionLine, + revisionJson, + revisionRecoveryLines, + revisionText, +} from '../../src/output.js'; import { testContext } from '../support/context.js'; import { OTHER_DIGEST, @@ -23,6 +35,19 @@ import { } from '../support/fixtures.js'; import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; +/** Passes the request on, then loses every proof lookup: the run fails after certification. */ +class InterruptingClient implements IAggregatorClient { + public constructor(private readonly inner: TestAggregatorClient) {} + + public getInclusionProof(): Promise { + return Promise.reject(new JsonRpcNetworkError(502, 'bad gateway')); + } + + public submitCertificationRequest(certificationData: CertificationData): Promise { + return this.inner.submitCertificationRequest(certificationData); + } +} + describe('stampRevisionWith', () => { const bob = SigningService.generatePrivateKey(); const bobPublic = new SigningService(bob).publicKey; @@ -45,6 +70,7 @@ describe('stampRevisionWith', () => { digest: TEST_DIGEST, network: { gatewayUrl: 'https://gateway.test', preset: 'testnet2', trustBase: aggregator.rootTrustBase }, privateKey: TEST_PRIVATE_KEY, + quiet: false, recipientKey: bobPublic, timeoutMs: 2_000, tokenBytes: null, @@ -155,6 +181,182 @@ describe('stampRevisionWith', () => { expect(await readFile(tokenFile)).toEqual(before); }); + describe('journal', () => { + let tokenFile: string; + let journal: string; + let genesisBytes: Uint8Array; + + beforeEach(async () => { + tokenFile = path.join(directory, 'doc.lineage'); + journal = path.join(directory, '.doc.lineage.pending'); + await stampRevisionWith(config({}), client, testContext().context); + genesisBytes = new Uint8Array(await readFile(tokenFile)); + }); + + /** Revision 1, by bob, passing to the test key. */ + const append = (overrides: Partial = {}): IStampRevisionConfig => + config({ + digest: OTHER_DIGEST, + privateKey: bob, + recipientKey: HexConverter.decode(TEST_PUBLIC_KEY_HEX), + tokenBytes: genesisBytes, + ...overrides, + }); + + async function interrupted(): Promise { + const interrupting = new StateTransitionClient(new InterruptingClient(aggregator)); + await expect(stampRevisionWith(append(), interrupting, testContext().context)).rejects.toThrow(/bad gateway/); + expect(await readdir(directory)).toEqual(['.doc.lineage.pending', 'doc.lineage']); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + } + + async function revisions(): Promise { + const token = await Token.fromCBOR(new Uint8Array(await readFile(tokenFile))); + return (await verifyLineage(token, aggregator.rootTrustBase)).description.revisions.map((revision) => + HexConverter.encode(revision.digest!), + ); + } + + it('echoes the pending revision to stderr, and removes the journal once the token is written', async () => { + expect(await readdir(directory)).toEqual(['doc.lineage']); + const sink = testContext(); + expect(await stampRevisionWith(append(), client, sink.context)).toBe(0); + expect(sink.stderr()).toContain('Submitting revision 1 of lineage '); + expect(sink.stderr()).toContain(`Stamped SHA-256 ${OTHER_DIGEST_HEX}`); + expect(sink.stderr()).toContain(`Next producer ${TEST_PUBLIC_KEY_HEX}`); + expect(sink.stderr()).toContain(`Journal ${journal}`); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('leaves the pending revision off stderr with --quiet', async () => { + const sink = testContext(); + expect(await stampRevisionWith(append({ quiet: true }), client, sink.context)).toBe(0); + expect(sink.stderr()).toEqual(''); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + it('keeps the journal when interrupted after submitting, and the next run recovers from it', async () => { + await interrupted(); + const recorded = JSON.parse(await readFile(journal, 'utf8')) as Record; + expect(recorded).toMatchObject({ + digest: OTHER_DIGEST_HEX, + format: 'unicity-proof/pending-revision', + nextProducer: TEST_PUBLIC_KEY_HEX, + revision: '1', + version: 1, + }); + + const sink = testContext(); + expect(await stampRevisionWith(append({ quiet: true }), client, sink.context)).toBe(0); + expect(sink.stderr()).toEqual(`Recovered revision 1 from the journal ${journal} of an interrupted run.\n`); + expect(sink.stdout()).toContain('Revision 1\n'); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + it('recovers the journaled revision when re-run with other inputs, and refuses the request', async () => { + await interrupted(); + const sink = testContext(); + const attempt = stampRevisionWith(append({ digest: TEST_DIGEST, quiet: true }), client, sink.context); + await expect(attempt).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); + const error = await attempt.catch((caught: unknown) => caught); + expect((error as Error).message).toMatch( + new RegExp( + `recovered and written to ${tokenFile}; the requested revision was not appended, ` + + `and the lineage now passes to ${TEST_PUBLIC_KEY_HEX}\\.$`, + ), + ); + expect(toExitCode(error)).toBe(EXIT_VERIFICATION_FAILED); + // The notes come out despite --quiet: they say what the token file now holds. + expect(sink.stderr()).toContain('Recovered revision 1 of lineage '); + expect(sink.stderr()).toContain(`SHA-256 ${OTHER_DIGEST_HEX}`); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + it('without the journal, reports the taken slot and echoes what it tried, even with --quiet', async () => { + await interrupted(); + await rm(journal); + const sink = testContext(); + const attempt = stampRevisionWith(append({ digest: TEST_DIGEST, quiet: true }), client, sink.context); + await expect(attempt).rejects.toThrow( + /already certified with different content.*that run's digest and next producer/, + ); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.stderr()).toContain('as this run submitted it (not certified)'); + expect(sink.stderr()).toContain(`SHA-256 ${TEST_DIGEST_HEX}`); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + + // With the inputs the interrupted run used, the revision is recovered after all. + expect(await stampRevisionWith(append(), client, testContext().context)).toBe(0); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + it('drops a journal whose revision the token file already holds', async () => { + await interrupted(); + const leftover = await readFile(journal); + await stampRevisionWith(append(), client, testContext().context); + await writeFile(journal, leftover); + + const sink = testContext(); + const tokenBytes = new Uint8Array(await readFile(tokenFile)); + expect( + await stampRevisionWith( + config({ digest: TEST_DIGEST, quiet: true, recipientKey: null, tokenBytes }), + client, + sink.context, + ), + ).toBe(0); + expect(sink.stderr()).toEqual(''); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX, TEST_DIGEST_HEX]); + }); + + it('refuses a journal it cannot place, and leaves it alone', async () => { + const tokenId = HexConverter.encode((await Token.fromCBOR(genesisBytes)).id.bytes); + const entry = (fields: Record): string => + JSON.stringify({ + digest: OTHER_DIGEST_HEX, + format: 'unicity-proof/pending-revision', + nextProducer: null, + revision: '1', + tokenId, + transaction: '00', + version: 1, + ...fields, + }); + const cases: [string, RegExp][] = [ + [entry({ tokenId: '00'.repeat(32) }), /is for lineage 0{64}, but .* holds lineage /], + [entry({ revision: '5' }), /is for revision 5, but .* ends at revision 0: the token file is out of date/], + [entry({}), /is not a pending lineage revision \(bad transaction\)/], + ['garbage', /is not a pending lineage revision \(not JSON\)/], + [entry({ version: 2 }), /is not a pending lineage revision \(unknown format\)/], + ]; + for (const [contents, message] of cases) { + await writeFile(journal, contents); + const attempt = stampRevisionWith(append(), client, testContext().context); + await expect(attempt).rejects.toThrow(message); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await readFile(journal, 'utf8')).toEqual(contents); + } + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + }); + + it('does not touch a journal next to a token file that is not a valid lineage', async () => { + await interrupted(); + const leftover = await readFile(journal); + const other = TestAggregatorClient.create(); + const attempt = stampRevisionWith( + append({ network: { gatewayUrl: 'https://gateway.test', preset: 'testnet2', trustBase: other.rootTrustBase } }), + new StateTransitionClient(other), + testContext().context, + ); + await expect(attempt).rejects.toMatchObject({ code: 'INVALID_TOKEN' }); + expect(await readFile(journal)).toEqual(leftover); + }); + }); + it('refuses a file that is not a token', async () => { const attempt = stampRevisionWith( config({ tokenBytes: new TextEncoder().encode('hello') }), @@ -242,4 +444,51 @@ describe('stamp-revision output', () => { 'd90100\n', ); }); + + describe('pending revision notes', () => { + const note = { + digest: TEST_DIGEST, + journalFile: '/docs/.doc.lineage.pending', + nextProducer: next, + revision: 3n, + tokenId: new Uint8Array(32).fill(0xaa), + }; + const id = 'aa'.repeat(32); + + it('lists the revision, its journal and how to recover it before it is submitted', () => { + expect(pendingRevisionLines(note, 'submitting')).toEqual( + [ + `Submitting revision 3 of lineage ${id}:`, + ` Stamped SHA-256 ${TEST_DIGEST_HEX}`, + ` Next producer ${HexConverter.encode(next)}`, + ' Journal /docs/.doc.lineage.pending', + 'If this run is interrupted, run stamp-revision on the same token file again to recover the revision;', + 'without the journal, run it with this digest and next producer.', + '', + ].join('\n'), + ); + }); + + it('says what a rejected or recovered revision held, without the recovery advice', () => { + const sealed = { ...note, nextProducer: null }; + expect(pendingRevisionLines(sealed, 'rejected')).toEqual( + [ + `Revision 3 of lineage ${id}, as this run submitted it (not certified):`, + ` Stamped SHA-256 ${TEST_DIGEST_HEX}`, + ' Next producer none; the lineage is finalized (sealed and burned)', + '', + ].join('\n'), + ); + expect(pendingRevisionLines(note, 'recovered')).toMatch( + new RegExp(`^Recovered revision 3 of lineage ${id}, certified by an interrupted run:\n`), + ); + expect(pendingRevisionLines(note, 'recovered')).not.toContain('Journal'); + }); + + it('notes a recovery from the journal', () => { + expect(recoveredRevisionLine(3n, '/docs/.doc.lineage.pending')).toEqual( + 'Recovered revision 3 from the journal /docs/.doc.lineage.pending of an interrupted run.\n', + ); + }); + }); }); diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts index 2f02e59..1bba73d 100644 --- a/tests/unit/lib/LineageClientTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -15,18 +15,23 @@ import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/Sta import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { StateAlreadyCertifiedError } from '../../../src/lib/errors.js'; import { appendRevision, + certifyRevision, createLineage, currentProducerKey, deriveGenesisSalt, isFinalized, + isSameRevision, LineageError, + prepareRevision, + recoverRevision, } from '../../../src/lib/LineageClient.js'; import { LINEAGE_TOKEN_TYPE_HEX, LineageRevision } from '../../../src/lib/LineagePayload.js'; -import { verifyLineage } from '../../../src/lib/LineageVerification.js'; +import { createLineageVerificationContext, verifyLineage } from '../../../src/lib/LineageVerification.js'; import { bundledTrustBase } from '../../../src/lib/networks.js'; -import { stampWith } from '../../../src/lib/TimestampClient.js'; +import { findCertifiedProof, STATE_ID_EXISTS_STATUS, stampWith } from '../../../src/lib/TimestampClient.js'; import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; @@ -46,6 +51,32 @@ class CountingClient implements IAggregatorClient { } } +/** + * An aggregator that already holds an earlier request for the state, not yet in a + * round: it answers STATE_ID_EXISTS, and certifies the earlier request only from + * the second proof lookup on. + */ +class LateRoundClient implements IAggregatorClient { + private lookups = 0; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly earlier: CertificationData, + ) {} + + public async getInclusionProof(stateId: StateId): Promise { + this.lookups += 1; + if (this.lookups === 2) { + await this.inner.submitCertificationRequest(this.earlier); + } + return this.inner.getInclusionProof(stateId); + } + + public submitCertificationRequest(): Promise { + return Promise.resolve(CertificationResponse.create(STATE_ID_EXISTS_STATUS)); + } +} + describe('LineageClient', () => { // A fresh aggregator per test: a genesis is deterministic in its issuer, digest // and recipient, so tests sharing one would all continue the same lineage. @@ -126,9 +157,90 @@ describe('LineageClient', () => { it('replays an interrupted step identically, so running it again recovers the revision', async () => { const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); const first = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); - // Same inputs against the same starting state: the aggregator already holds this request. - const again = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + // Same inputs against the same starting state: the aggregator answers STATE_ID_EXISTS, + // and the proof it holds is this transfer's, so the replay completes without a warning. + const warnings: string[] = []; + const again = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), { + ...fast, + onWarning: (message) => warnings.push(message), + }); expect(HexConverter.encode(again.toCBOR())).toEqual(HexConverter.encode(first.toCBOR())); + expect(warnings).toEqual([]); + }); + + describe('a revision slot that is already certified', () => { + it('says so, with ALREADY_CERTIFIED, when another transfer took the slot', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + const attempt = appendRevision(client, trustBase, genesis, THIRD_DIGEST, bob, publicKey(carol), fast); + await expect(attempt).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); + await expect(attempt).rejects.toThrow( + /^Revision 1 of this lineage was already certified with different content.*that run's digest and next producer/, + ); + }); + + it('recovers a transfer the aggregator certified, without a key or a submission', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const prepared = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + expect(await recoverRevision(client, trustBase, genesis, prepared.transaction, fast)).toBeNull(); + + const certified = await certifyRevision(client, trustBase, genesis, prepared, fast); + const submissions = counting.submissions; + const recovered = await recoverRevision(client, trustBase, genesis, prepared.transaction, fast); + expect(counting.submissions).toBe(submissions); + expect(HexConverter.encode(recovered!.toCBOR())).toEqual(HexConverter.encode(certified.toCBOR())); + + const other = await prepareRevision(genesis, trustBase, THIRD_DIGEST, bob, publicKey(carol)); + await expect(recoverRevision(client, trustBase, genesis, other.transaction, fast)).rejects.toMatchObject({ + code: 'ALREADY_CERTIFIED', + }); + }); + + it('tells whether a transfer is the revision a digest and next producer make', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const { transaction } = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + expect(await isSameRevision(transaction, 1n, OTHER_DIGEST, publicKey(carol))).toBe(true); + expect(await isSameRevision(transaction, 1n, THIRD_DIGEST, publicKey(carol))).toBe(false); + expect(await isSameRevision(transaction, 1n, OTHER_DIGEST, publicKey(alice))).toBe(false); + expect(await isSameRevision(transaction, 1n, OTHER_DIGEST, null)).toBe(false); + expect(await isSameRevision(transaction, 2n, OTHER_DIGEST, publicKey(carol))).toBe(false); + }); + + it('waits for an earlier request still in its round, and recovers it if it is this one', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const prepared = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + const late = new StateTransitionClient(new LateRoundClient(aggregator, prepared.certificationData)); + const token = await certifyRevision(late, trustBase, genesis, prepared, fast); + expect(token.transactions).toHaveLength(1); + }); + + it('waits for an earlier request still in its round, and reports it if it is another', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const other = await prepareRevision(genesis, trustBase, THIRD_DIGEST, bob, publicKey(carol)); + const late = new StateTransitionClient(new LateRoundClient(aggregator, other.certificationData)); + const prepared = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + await expect(certifyRevision(late, trustBase, genesis, prepared, fast)).rejects.toMatchObject({ + code: 'ALREADY_CERTIFIED', + }); + }); + + // A gateway can claim another transaction took the slot; only a proof that + // authenticates under the trust base is believed. + it('does not take an unauthenticated proof of another transfer for a taken slot', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const elsewhere = TestAggregatorClient.create(); + const other = await prepareRevision(genesis, trustBase, THIRD_DIGEST, bob, publicKey(carol)); + await elsewhere.submitCertificationRequest(other.certificationData); + const forging = new StateTransitionClient(elsewhere); + const mine = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + await expect( + findCertifiedProof(forging, createLineageVerificationContext(trustBase), mine.transaction), + ).resolves.toBeNull(); + // The same proof under its own trust base is a genuine taken slot. + await expect( + findCertifiedProof(forging, createLineageVerificationContext(elsewhere.rootTrustBase), mine.transaction), + ).rejects.toBeInstanceOf(StateAlreadyCertifiedError); + }); }); it('replays an interrupted genesis identically, so running it again recovers the lineage', async () => { @@ -177,11 +289,8 @@ describe('LineageClient', () => { const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); await expect( - appendRevision(client, trustBase, genesis, THIRD_DIGEST, bob, publicKey(carol), { - pollIntervalMs: 10, - timeoutMs: 300, - }), - ).rejects.toThrow(); + appendRevision(client, trustBase, genesis, THIRD_DIGEST, bob, publicKey(carol), fast), + ).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); }); describe('finalization', () => { From 16e1458f83c38e8850d37c46e0945208d0d425ca Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 11:33:29 +0200 Subject: [PATCH 14/25] Recover a re-run genesis as the existing lineage, and refuse it once moved on Re-running a genesis whose token file is elsewhere, or meaning to start a second lineage from the same document and first producer, silently produced revision 0 of the existing lineage, presented as a new one even after it had moved on. - createOrRecoverLineage looks for the mint's proof before submitting, and counts STATE_ID_EXISTS for the same mint as a recovery too. - A recovered genesis is marked "(existing lineage, recovered)", with a note on stderr, regardless of --quiet, on how to start a separate lineage. - Before writing it, findSuccessor asks the aggregator whether revision 1 exists. An authenticated proof means the lineage has moved on: nothing is written, and the command exits 1 (SUPERSEDED) with the token id, when revision 1 was certified and by whom. A failed lookup or an unverifiable proof writes the file with a warning. - stamp-revision output gains "recovered", also for appends replayed or recovered from the journal; onAlreadyCertified reports replays. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- skills/unicity-proof/SKILL.md | 7 +- src/commands/stampRevision.ts | 87 ++++++++++++-- src/errors.ts | 4 +- src/lib/LineageClient.ts | 169 +++++++++++++++++++++++++++- src/lib/TimestampClient.ts | 13 ++- src/output.ts | 66 ++++++++++- tests/unit/ErrorsTest.ts | 1 + tests/unit/StampRevisionTest.ts | 152 ++++++++++++++++++++++++- tests/unit/lib/LineageClientTest.ts | 101 +++++++++++++++++ 10 files changed, 585 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 161015f..d1beb93 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,10 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - If `--token-file` does not exist, a new lineage is minted. Its mint reason is the `--key-file` holder's signature over the token id, type, recipient and revision, which is what makes the origin "accepted". Because the recipient is signed, the issuer names the producer of revision 1 (or the burn, with `--finalize`), just as each later revision names its successor: whoever submits the mint cannot substitute another. - **The token id identifies the lineage, and nothing else does.** It is printed when the lineage is created, marked `(identifies this lineage; give it to verifiers)`; pass it on through a channel the verifiers trust, and have them check it with `verify --token-id`. The issuer key and the first revision's hash are not enough: the same issuer can start any number of certified lineages from the same document, each with its own fork-free history, and verification cannot tell them apart. - The salt, and so the token id, is derived from the issuer's private key, the recipient and revision 0, not drawn at random. Running an interrupted genesis again with the same file, key, digest and recipient therefore recovers the same lineage instead of starting a parallel one. Nobody without the issuer's key can compute the token id before the genesis is certified, so nobody can mint into its slot first. Starting a second, separate lineage from the same document needs a different first producer (or issuer). +- **A genesis that was already certified is recovered, never re-created.** Whether the earlier run was interrupted, its token file went elsewhere, or a second lineage was meant, the same inputs give the same lineage: + - The output says `Revision 0 (existing lineage, recovered)`, and a note on stderr, printed even with `--quiet`, says that this is the existing lineage and how to start a separate one. + - Before writing, the command asks the aggregator whether revision 1 exists. If it shows a proof that verifies against the trust base, the lineage has moved on: nothing is written, and the command exits 1, naming the token id, when revision 1 was certified and by whom. Get the current token file from whoever holds the lineage. + - If the aggregator cannot be asked, or shows a proof that does not verify, the file is written with a warning. The check can find later revisions but never rule them out: the aggregator issues no proofs of absence. - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `..pending` (`.doc.lineage.pending` for `doc.lineage`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. The journal is removed once the token file holds the revision. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. @@ -138,6 +142,7 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - Without the journal, the same command with the same file, key, digest and recipient still recovers the revision, because the state mask of each step is derived from the producer's key and the spent state. With any other digest or recipient it exits 1, saying the revision was already certified with different content, and echoes what it tried to stderr even with `--quiet`. Only the interrupted run's digest and recipient can recover it then, which is what the echo is for. - A journal the command cannot place (for another lineage, for a later revision than the token file holds, or unreadable) stops it with exit 2 and is left alone. - A new lineage needs no journal: its genesis is derived from its inputs, and running it again with the same file, key, digest and recipient recovers it (see above). +- In `--json` output, `recovered` is true when an earlier run had already certified the revision and this run only recovered it; the text output marks such a revision `(recovered)`. - Network options behave as for `stamp`. `verify` and `inspect` recognise lineage tokens by their token type and list every revision with its hash, signer, next producer and certification time: @@ -216,7 +221,7 @@ unicity-proof verify document.cbor --file document.pdf --json | jq -r .reference | Exit code | Meaning | | --- | --- | | 0 | Success. For `verify`: valid, and the hash (and, for a lineage, the token id) matched if one was given. | -| 1 | Verification failed, hash or token id mismatch, or the input is not a token. For `stamp-revision`: the revision was already certified with different content. | +| 1 | Verification failed, hash or token id mismatch, or the input is not a token. For `stamp-revision`: the revision was already certified with different content, or a recovered genesis's lineage has moved on. | | 2 | Usage or configuration error. | | 3 | Network error, aggregator rejection, or timeout. | | 130 | Interrupted. | diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index 5670ace..6c890c5 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -67,6 +67,11 @@ without it the proof is gone. content` means an earlier run certified something else for this revision: only that run's digest and recipient recover it, and they are on stderr from when it was submitted. +- **`(existing lineage, recovered)` means no new lineage was created.** The + same issuer key, document and first producer always give the same lineage. + If `stamp-revision` exits 1 saying `the lineage has moved on`, later + revisions exist: get the current token file from whoever holds the lineage + rather than creating it again. - `--sign` exits 2 unless a key is configured. Use it in any automated path that must never silently produce an anonymous stamp. `--anonymous` forces the opposite. @@ -82,7 +87,7 @@ about foresight. | Code | Meaning | | --- | --- | | `0` | Success. For `verify`: valid, and the hash (and, for a lineage, the token id) matched if one was given. | -| `1` | Verification failed, hash or token id mismatch, or the input is not a token. For `stamp-revision`: the revision was already certified with different content. | +| `1` | Verification failed, hash or token id mismatch, or the input is not a token. For `stamp-revision`: the revision was already certified with different content, or a recovered genesis's lineage has moved on. | | `2` | Usage or configuration error. | | `3` | Network error, aggregator rejection, or timeout. | | `130` | Interrupted. | diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 78e3e00..335e88c 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -3,6 +3,7 @@ import { rename, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { AggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/AggregatorClient.js'; +import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js'; @@ -24,25 +25,29 @@ import { import { decodeToken, tokenBytesFromInput } from './tokenInput.js'; import { IStampRevisionConfig, IStampRevisionFlags, resolveStampRevisionConfig } from '../config.js'; import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; -import { StampError } from '../lib/errors.js'; +import { errorMessage, StampError } from '../lib/errors.js'; import { assertValidLineage, certifyRevision, - createLineage, + createOrRecoverLineage, currentProducerKey, + findSuccessor, isSameRevision, LineageError, prepareRevision, recoverRevision, + SuccessorLookup, } from '../lib/LineageClient.js'; import { ICertifyOptions } from '../lib/TimestampClient.js'; import { + existingLineageNote, PendingRevisionContext, pendingRevisionLines, recoveredRevisionLine, revisionJson, revisionRecoveryLines, revisionText, + supersededLineageMessage, toJsonLine, warningLine, } from '../output.js'; @@ -129,6 +134,8 @@ function recoveredOtherRevision(revision: bigint, token: Token, tokenFile: strin /** What an append produced. */ interface IAppendOutcome { + /** True when an earlier run had certified the revision, and this run recovered it. */ + readonly recovered: boolean; /** Key that signed the appended transfer. */ readonly signer: Uint8Array; readonly token: Token; @@ -177,7 +184,7 @@ async function appendJournaled( await removeJournal(journalFile); if (await isSameRevision(transaction, pending.revision, config.digest, config.recipientKey)) { context.stderr.write(recoveredRevisionLine(pending.revision, journalFile)); - return { signer: currentProducerKey(token) as Uint8Array, token: recovered }; + return { recovered: true, signer: currentProducerKey(token) as Uint8Array, token: recovered }; } writePending(context, pending, journalFile, 'recovered'); throw recoveredOtherRevision(pending.revision, recovered, config.tokenFile); @@ -213,8 +220,14 @@ async function appendJournaled( } let appended: Token; + let replayed = false; try { - appended = await certifyRevision(client, trustBase, token, prepared, options); + appended = await certifyRevision(client, trustBase, token, prepared, { + ...options, + onAlreadyCertified: (): void => { + replayed = true; + }, + }); } catch (error) { if (error instanceof StampError) { // Refused outright: nothing was certified. @@ -237,7 +250,51 @@ async function appendJournaled( await writeRevisionToken(config.tokenFile, appended.toCBOR(), false, context); await removeJournal(journalFile); - return { signer: new SigningService(config.privateKey).publicKey, token: appended }; + return { recovered: replayed, signer: new SigningService(config.privateKey).publicKey, token: appended }; +} + +/** + * Refuse to hand out a recovered genesis whose lineage has moved on: a file with + * only revision 0 would be out of date, yet look like a fresh lineage. When the + * aggregator cannot be asked, or shows a proof that does not verify, the genesis + * is written anyway, with a warning: it is certified and correct, and losing a + * good recovery over a secondary check would be worse. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the token's network. + * @param {Token} token The recovered genesis. + * @param {ICommandContext} context Streams and interrupt signal. + * @throws {LineageError} `SUPERSEDED` if the aggregator proves a later revision exists. + */ +async function assertNotSuperseded( + client: StateTransitionClient, + trustBase: RootTrustBase, + token: Token, + context: ICommandContext, +): Promise { + let lookup: SuccessorLookup; + try { + lookup = await findSuccessor(client, trustBase, token, context.interrupt); + } catch (error) { + context.stderr.write( + warningLine(`Could not check whether the lineage has later revisions: ${errorMessage(error)}`), + ); + return; + } + if (lookup.kind === 'spent') { + throw new LineageError( + supersededLineageMessage(token.id.bytes, lookup.proof.referenceTime, currentProducerKey(token)), + 'SUPERSEDED', + ); + } + if (lookup.kind === 'unverified') { + context.stderr.write( + warningLine( + 'The gateway showed a proof of a later revision that does not verify; could not check whether the ' + + 'lineage has moved on.', + ), + ); + } } function latestCertified(token: Token): CertifiedMintTransaction | CertifiedTransferTransaction { @@ -269,16 +326,31 @@ export async function stampRevisionWith( let token: Token; let signer = new SigningService(config.privateKey).publicKey; + let recovered: boolean; const created = config.tokenBytes === null; if (config.tokenBytes === null) { - token = await createLineage(client, trustBase, config.digest, config.privateKey, config.recipientKey, options); + ({ recovered, token } = await createOrRecoverLineage( + client, + trustBase, + config.digest, + config.privateKey, + config.recipientKey, + options, + )); + if (recovered) { + await assertNotSuperseded(client, trustBase, token, context); + } await writeRevisionToken(config.tokenFile, token.toCBOR(), true, context); + if (recovered) { + // Not subject to --quiet: without it, two files can pass for two lineages. + context.stderr.write(existingLineageNote(token.id.bytes)); + } } else { const decoded = await decodeToken(tokenBytesFromInput(config.tokenBytes)); if (decoded.token === null) { throw new CliError(`${config.tokenFile} is ${decoded.error}.`, EXIT_VERIFICATION_FAILED); } - ({ signer, token } = await appendJournaled(config, client, context, options, decoded.token)); + ({ recovered, signer, token } = await appendJournaled(config, client, context, options, decoded.token)); } const latest = latestCertified(token); @@ -290,6 +362,7 @@ export async function stampRevisionWith( gatewayUrl: config.network.gatewayUrl, networkId: token.networkId.id, nextProducer: config.recipientKey, + recovered, referenceTime: latest.referenceTime, revision: BigInt(token.transactions.length), roundNumber: certificate.inputRecord.roundNumber, diff --git a/src/errors.ts b/src/errors.ts index ff96ffd..8dac434 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -71,7 +71,9 @@ export function toExitCode(error: unknown, interrupted = false): number { return EXIT_VERIFICATION_FAILED; } if (error instanceof LineageError) { - return error.code === 'INVALID_TOKEN' || error.code === 'ALREADY_CERTIFIED' ? EXIT_VERIFICATION_FAILED : EXIT_USAGE; + return error.code === 'INVALID_TOKEN' || error.code === 'ALREADY_CERTIFIED' || error.code === 'SUPERSEDED' + ? EXIT_VERIFICATION_FAILED + : EXIT_USAGE; } return EXIT_USAGE; } diff --git a/src/lib/LineageClient.ts b/src/lib/LineageClient.ts index 840ad12..f270908 100644 --- a/src/lib/LineageClient.ts +++ b/src/lib/LineageClient.ts @@ -1,6 +1,8 @@ import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; import { InclusionProof } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProof.js'; +import { JsonRpcNetworkError } from '@unicitylabs/state-transition-sdk/lib/api/json-rpc/JsonRpcNetworkError.js'; +import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; import { DataHasher } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/DataHasher.js'; import { HashAlgorithm } from '@unicitylabs/state-transition-sdk/lib/crypto/hash/HashAlgorithm.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; @@ -16,6 +18,10 @@ import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.j import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; +import { + InclusionProofVerificationRule, + InclusionProofVerificationStatus, +} from '@unicitylabs/state-transition-sdk/lib/transaction/verification/rule/InclusionProofVerificationRule.js'; import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; import { StateAlreadyCertifiedError } from './errors.js'; @@ -27,7 +33,7 @@ import { sealPredicate, } from './LineagePayload.js'; import { createLineageVerificationContext, verifyLineage } from './LineageVerification.js'; -import { ICertifyOptions, certifyMintTransaction, certifyTransaction, findCertifiedProof } from './TimestampClient.js'; +import { ICertifyOptions, certifyTransaction, findCertifiedProof } from './TimestampClient.js'; /** Thrown when a revision cannot be appended to the given token with the given key. */ export class LineageError extends Error { @@ -36,9 +42,10 @@ export class LineageError extends Error { /** * `INVALID_TOKEN`: the token does not verify as a lineage; `WRONG_KEY`: the key * cannot append to it; `FINALIZED`: the lineage is sealed and nothing can; - * `ALREADY_CERTIFIED`: this revision slot was already certified with other content. + * `ALREADY_CERTIFIED`: this revision slot was already certified with other content; + * `SUPERSEDED`: a recovered genesis whose lineage has moved on since. */ - public readonly code: 'ALREADY_CERTIFIED' | 'FINALIZED' | 'INVALID_TOKEN' | 'WRONG_KEY', + public readonly code: 'ALREADY_CERTIFIED' | 'FINALIZED' | 'INVALID_TOKEN' | 'SUPERSEDED' | 'WRONG_KEY', options?: ErrorOptions, ) { super(message, options); @@ -186,6 +193,26 @@ export async function createLineage( nextProducer: Uint8Array | null, options: ICertifyOptions = {}, ): Promise { + return (await createOrRecoverLineage(client, trustBase, digest, issuerPrivateKey, nextProducer, options)).token; +} + +/** + * Build, without network contact, the genesis of a lineage. Deterministic in its + * inputs: the salt is derived ({@link deriveGenesisSalt}) and the issuer's + * signature is deterministic, so the same inputs always give the same mint. + * + * @param {RootTrustBase} trustBase Trust base of the network to mint on. + * @param {Uint8Array} digest 32-byte SHA-256 digest of the initial revision. + * @param {Uint8Array} issuerPrivateKey Issuer's private key; signs the genesis reason. + * @param {Uint8Array|null} nextProducer Compressed public key of whoever produces revision 1; null to finalize. + * @returns {Promise} The mint. + */ +export async function prepareLineage( + trustBase: RootTrustBase, + digest: Uint8Array, + issuerPrivateKey: Uint8Array, + nextProducer: Uint8Array | null, +): Promise { const { auxData, recipient } = await revisionStep(0n, digest, nextProducer); const encodedRecipient = EncodedPredicate.fromPredicate(recipient); const salt = await deriveGenesisSalt(issuerPrivateKey, encodedRecipient, auxData); @@ -197,14 +224,146 @@ export async function createLineage( auxData, new SigningService(issuerPrivateKey), ); - const transaction = await MintTransaction.create(trustBase.networkId, recipient, { + return MintTransaction.create(trustBase.networkId, recipient, { data: auxData, justification: reason.toCBOR(), salt, tokenType: LINEAGE_TOKEN_TYPE, }); +} + +/** A genesis, and whether an earlier run had already certified it. */ +export interface ILineageGenesis { + /** + * True when this genesis was certified before this call: by an interrupted run, + * or by a run whose token file is elsewhere. The token is then revision 0 of an + * existing lineage, which may have moved on since ({@link findSuccessor}). + */ + readonly recovered: boolean; + readonly token: Token; +} + +/** + * Create a lineage, or recover it if this genesis was already certified. + * + * The aggregator is asked first whether it holds this very mint; if so, nothing is + * submitted. Otherwise the mint is submitted, and a `STATE_ID_EXISTS` answer for it + * (an earlier request still waiting for its round when this one looked) counts as a + * recovery too. A gateway that answers a repeat as a fresh success is caught by the + * first check, unless the repeat comes within the earlier request's round. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Uint8Array} digest 32-byte SHA-256 digest of the initial revision. + * @param {Uint8Array} issuerPrivateKey Issuer's private key; signs the genesis reason. + * @param {Uint8Array|null} nextProducer Compressed public key of whoever produces revision 1; null to finalize. + * @param {ICertifyOptions} options Timeout, poll interval, abort signal, warning sink. + * @returns {Promise} Verified lineage token with no transfers, and whether it was recovered. + */ +export async function createOrRecoverLineage( + client: StateTransitionClient, + trustBase: RootTrustBase, + digest: Uint8Array, + issuerPrivateKey: Uint8Array, + nextProducer: Uint8Array | null, + options: ICertifyOptions = {}, +): Promise { + const transaction = await prepareLineage(trustBase, digest, issuerPrivateKey, nextProducer); const context = createLineageVerificationContext(trustBase); - return Token.mint(await certifyMintTransaction(client, context, transaction, options), context); + let recovered = false; + let proof = await findCertifiedProof(client, context, transaction, options.signal); + if (proof !== null) { + recovered = true; + } else { + proof = await certifyTransaction( + client, + context, + await CertificationData.fromMintTransaction(transaction), + transaction, + { + ...options, + onAlreadyCertified: (): void => { + recovered = true; + options.onAlreadyCertified?.(); + }, + }, + ); + } + const certified = await transaction.toCertifiedTransaction( + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + proof, + ); + return { recovered, token: await Token.mint(certified, context) }; +} + +/** + * What the aggregator says about the state a token ends in: `spent`, with an + * authenticated proof of the transfer that spent it; `unverified`, when it showed a + * proof that does not verify; `none`, when it showed nothing. `none` is not proof + * that no later revision exists: the aggregator issues no proofs of absence, and a + * gateway can withhold one. + */ +export type SuccessorLookup = + | { readonly kind: 'none' } + | { readonly kind: 'spent'; readonly proof: InclusionProof } + | { readonly kind: 'unverified' }; + +/** + * Ask the aggregator whether the state the token ends in has been spent, that is, + * whether the lineage has a revision after the token's latest one. Needs no key + * and submits nothing: the next revision's state id depends only on the latest + * state and the predicate locking it, both in the token. Its content cannot be + * learned, since the aggregator holds only the transfer's hash. + * + * A proof is believed only once it verifies against the trust base: its path, the + * consensus signatures over its round, and the signature of the key the latest + * state is locked to, over the transfer it certifies. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {RootTrustBase} trustBase Trust base of the network behind the client. + * @param {Token} token Lineage token. + * @param {AbortSignal} [signal] Abort signal for the request. + * @returns {Promise} What the aggregator showed. + */ +export async function findSuccessor( + client: StateTransitionClient, + trustBase: RootTrustBase, + token: Token, + signal?: AbortSignal, +): Promise { + if (isFinalized(token)) { + // Locked to a burn predicate, which nothing can unlock. + return { kind: 'none' }; + } + // The state id of any transfer out of the latest state; the probe's recipient + // and mask do not enter it. + const probe = await TransferTransaction.create(token, BurnPredicate.create(new Uint8Array(32)), StateMask.generate()); + let proof: InclusionProof | null; + try { + proof = (await client.getInclusionProof(await StateId.fromTransaction(probe), { signal })).inclusionProof; + } catch (error) { + if (error instanceof JsonRpcNetworkError && error.status === 404) { + return { kind: 'none' }; + } + throw error; + } + if (proof === null) { + return { kind: 'none' }; + } + const context = createLineageVerificationContext(trustBase); + const result = await InclusionProofVerificationRule.verify( + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + proof, + proof.certificationData.transactionHash, + proof.certificationData.expiresAt, + probe.lockScript, + probe.sourceStateHash, + ); + return result.status === InclusionProofVerificationStatus.OK ? { kind: 'spent', proof } : { kind: 'unverified' }; } /** diff --git a/src/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index 46e05b2..bd677ab 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -29,6 +29,11 @@ export const DEFAULT_TIMEOUT_MS = 60_000; export const DEFAULT_POLL_INTERVAL_MS = 1_000; export interface ICertifyOptions { + /** + * Called when the aggregator already held this very transaction, submitted by an + * earlier run: the proof returned is that run's, and nothing new was certified. + */ + readonly onAlreadyCertified?: () => void; /** Called for conditions that do not stop the stamp, such as an unknown aggregator status. */ readonly onWarning?: (message: string) => void; /** Delay between inclusion-proof polls. Default {@link DEFAULT_POLL_INTERVAL_MS}. */ @@ -149,6 +154,7 @@ export async function certifyTransaction( if (exists) { const proof = await findCertifiedProof(client, context, transaction, options.signal); if (proof !== null) { + options.onAlreadyCertified?.(); return proof; } } else if (response.status !== SUCCESS_STATUS) { @@ -165,7 +171,7 @@ export async function certifyTransaction( signals.push(options.signal); } try { - return await waitInclusionProof( + const proof = await waitInclusionProof( client, context.trustBase, context.predicateVerifier, @@ -174,6 +180,11 @@ export async function certifyTransaction( AbortSignal.any(signals), options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, ); + if (exists) { + // The earlier request for this state was this transaction, certified in its own round. + options.onAlreadyCertified?.(); + } + return proof; } catch (error) { // The earlier request was still waiting for its round. The SDK reports a proof // of another transaction only as a plain Error, so look again to say what it is. diff --git a/src/output.ts b/src/output.ts index e394923..07a82b5 100644 --- a/src/output.ts +++ b/src/output.ts @@ -378,6 +378,11 @@ export interface IRevisionSummary { readonly networkId: number; /** Null when the revision finalized the lineage. */ readonly nextProducer: Uint8Array | null; + /** + * True when an earlier run had already certified this revision and this run only + * recovered it; for a genesis, the lineage is then an existing one, not a new one. + */ + readonly recovered: boolean; readonly referenceTime: bigint; readonly revision: bigint; readonly roundNumber: bigint; @@ -396,6 +401,8 @@ export interface IRevisionJson { readonly network: INetworkJson & { readonly gateway: string }; /** Null when the revision finalized the lineage. */ readonly nextProducer: string | null; + /** True when an earlier run had already certified this revision; see {@link IRevisionSummary.recovered}. */ + readonly recovered: boolean; readonly referenceTime: string; readonly referenceTimeIso: string | null; readonly revision: string; @@ -405,16 +412,27 @@ export interface IRevisionJson { readonly tokenId: string; } +/** + * @param {IRevisionSummary} summary The certified revision. + * @returns {string} The marks after the revision number: how it came about, and whether it is final. + */ +function revisionMarks(summary: IRevisionSummary): string { + let origin = ''; + if (summary.created) { + origin = summary.recovered ? ' (existing lineage, recovered)' : ' (new lineage)'; + } else if (summary.recovered) { + origin = ' (recovered)'; + } + return `${origin}${summary.nextProducer === null ? ' (final)' : ''}`; +} + /** * @param {IRevisionSummary} summary The certified revision. * @returns {string} Human summary of a `stamp-revision`. */ export function revisionText(summary: IRevisionSummary): string { return [ - line( - 'Revision', - `${summary.revision}${summary.created ? ' (new lineage)' : ''}${summary.nextProducer === null ? ' (final)' : ''}`, - ), + line('Revision', `${summary.revision}${revisionMarks(summary)}`), line('Stamped', `SHA-256 ${HexConverter.encode(summary.digest)}`), line('Network', `${networkLabel(summary.networkId)} via ${summary.gatewayUrl}`), line('Signed by', HexConverter.encode(summary.signer)), @@ -441,6 +459,7 @@ export function revisionJson(summary: IRevisionSummary): IRevisionJson { hash: { algorithm: 'SHA-256', digest: HexConverter.encode(summary.digest) }, network: { gateway: summary.gatewayUrl, id: summary.networkId, name: networkName(summary.networkId) }, nextProducer: summary.nextProducer === null ? null : HexConverter.encode(summary.nextProducer), + recovered: summary.recovered, referenceTime: summary.referenceTime.toString(), referenceTimeIso: toIso(summary.referenceTime), revision: summary.revision.toString(), @@ -510,6 +529,45 @@ export function recoveredRevisionLine(revision: bigint, journalFile: string): st return `Recovered revision ${revision} from the journal ${journalFile} of an interrupted run.\n`; } +const SEPARATE_LINEAGE_HINT = + 'To start a separate lineage from the same document, name a different first producer ' + + '(or sign with a different issuer key).'; + +/** + * Note for stderr after a genesis that an earlier run had already certified. + * + * @param {Uint8Array} tokenId The existing lineage's token id. + * @returns {string} Note, ending in a newline. + */ +export function existingLineageNote(tokenId: Uint8Array): string { + return ( + 'This genesis was already certified: the token file holds revision 0 of the existing lineage ' + + `${HexConverter.encode(tokenId)}, not a new one. ${SEPARATE_LINEAGE_HINT}\n` + ); +} + +/** + * Why a recovered genesis was not written: the lineage has moved on. + * + * @param {Uint8Array} tokenId The lineage's token id. + * @param {bigint} referenceTime When revision 1 was certified. + * @param {Uint8Array|null} producer Who revision 0 passed to, and so who signed revision 1. + * @returns {string} Error message. + */ +export function supersededLineageMessage( + tokenId: Uint8Array, + referenceTime: bigint, + producer: Uint8Array | null, +): string { + const by = producer === null ? '' : ` by the next producer ${HexConverter.encode(producer)}`; + return ( + `Revision 0 of lineage ${HexConverter.encode(tokenId)} was certified by an earlier run, and the lineage has ` + + `moved on: revision 1 was certified at ${formatIso(referenceTime)}${by}. A token file holding only revision 0 ` + + 'would be out of date, so none was written. Get the current token file from whoever holds the lineage; the ' + + `token id above still identifies the lineage. ${SEPARATE_LINEAGE_HINT}` + ); +} + /** * Last resort for a revision that was certified but could not be written. * diff --git a/tests/unit/ErrorsTest.ts b/tests/unit/ErrorsTest.ts index e6a0937..7c97958 100644 --- a/tests/unit/ErrorsTest.ts +++ b/tests/unit/ErrorsTest.ts @@ -32,6 +32,7 @@ describe('toExitCode', () => { ['token failed SDK verification', new VerificationError('bad token', failed), 1], ['not a valid lineage token', new LineageError('x', 'INVALID_TOKEN'), 1], ['lineage revision slot already taken', new LineageError('x', 'ALREADY_CERTIFIED'), 1], + ['recovered genesis whose lineage moved on', new LineageError('x', 'SUPERSEDED'), 1], ['wrong key for the lineage', new LineageError('x', 'WRONG_KEY'), 2], ['finalized lineage', new LineageError('x', 'FINALIZED'), 2], ['file not found', errno('ENOENT', '/x'), 2], diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 81e4637..e419be4 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -6,6 +6,7 @@ import { CertificationResponse } from '@unicitylabs/state-transition-sdk/lib/api import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/IAggregatorClient.js'; import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js'; import { JsonRpcNetworkError } from '@unicitylabs/state-transition-sdk/lib/api/json-rpc/JsonRpcNetworkError.js'; +import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; @@ -14,14 +15,17 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { stampRevisionWith } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; +import { appendRevision, prepareRevision } from '../../src/lib/LineageClient.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; import { + existingLineageNote, IRevisionSummary, pendingRevisionLines, recoveredRevisionLine, revisionJson, revisionRecoveryLines, revisionText, + supersededLineageMessage, } from '../../src/output.js'; import { testContext } from '../support/context.js'; import { @@ -48,6 +52,28 @@ class InterruptingClient implements IAggregatorClient { } } +type Lookup = (stateId: StateId) => Promise; + +/** Answers the n-th proof lookup with the n-th scripted answer, and the rest from the aggregator. */ +class ScriptedLookupClient implements IAggregatorClient { + private lookups = 0; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly script: (Lookup | null)[], + ) {} + + public getInclusionProof(stateId: StateId): Promise { + const scripted = this.script[this.lookups]; + this.lookups += 1; + return scripted ? scripted(stateId) : this.inner.getInclusionProof(stateId); + } + + public submitCertificationRequest(certificationData: CertificationData): Promise { + return this.inner.submitCertificationRequest(certificationData); + } +} + describe('stampRevisionWith', () => { const bob = SigningService.generatePrivateKey(); const bobPublic = new SigningService(bob).publicKey; @@ -88,10 +114,12 @@ describe('stampRevisionWith', () => { created: true, hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, nextProducer: HexConverter.encode(bobPublic), + recovered: false, revision: '0', signer: TEST_PUBLIC_KEY_HEX, tokenFile, }); + expect(first.stderr()).toEqual(''); const second = testContext(); const tokenBytes = new Uint8Array(await readFile(tokenFile)); @@ -140,7 +168,8 @@ describe('stampRevisionWith', () => { text.context, ), ).toBe(0); - expect(text.stdout()).toContain('Revision 1 (final)\n'); + // The same seal again: the aggregator already holds it, so this run only recovers it. + expect(text.stdout()).toContain('Revision 1 (recovered) (final)\n'); expect(text.stdout()).toContain('Next producer none; the lineage is finalized'); const attempt = stampRevisionWith( @@ -181,6 +210,88 @@ describe('stampRevisionWith', () => { expect(await readFile(tokenFile)).toEqual(before); }); + describe('a genesis that was already certified', () => { + let tokenFile: string; + let genesisBytes: Uint8Array; + let tokenIdHex: string; + + beforeEach(async () => { + tokenFile = path.join(directory, 'doc.lineage'); + await stampRevisionWith(config({}), client, testContext().context); + genesisBytes = new Uint8Array(await readFile(tokenFile)); + tokenIdHex = HexConverter.encode((await Token.fromCBOR(genesisBytes)).id.bytes); + await rm(tokenFile); + }); + + async function bobAppends(): Promise { + const genesis = await Token.fromCBOR(genesisBytes); + await appendRevision(client, aggregator.rootTrustBase, genesis, OTHER_DIGEST, bob, bobPublic, { + pollIntervalMs: 10, + }); + } + + it('is recovered and written, marked as the existing lineage, with a note even under --quiet', async () => { + const sink = testContext({ json: true }); + expect(await stampRevisionWith(config({ quiet: true }), client, sink.context)).toBe(0); + expect(sink.json()).toMatchObject({ created: true, recovered: true, revision: '0', tokenId: tokenIdHex }); + expect(sink.stderr()).toEqual(existingLineageNote(HexConverter.decode(tokenIdHex))); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + + await rm(tokenFile); + const text = testContext(); + await stampRevisionWith(config({}), client, text.context); + expect(text.stdout()).toContain('Revision 0 (existing lineage, recovered)\n'); + }); + + it('is not written once the lineage has moved on, and the error says so', async () => { + await bobAppends(); + const attempt = stampRevisionWith(config({ quiet: true }), client, testContext().context); + await expect(attempt).rejects.toMatchObject({ code: 'SUPERSEDED' }); + const error = (await attempt.catch((caught: unknown) => caught)) as Error; + expect(toExitCode(error)).toBe(EXIT_VERIFICATION_FAILED); + expect(error.message).toContain(`Revision 0 of lineage ${tokenIdHex} was certified by an earlier run`); + expect(error.message).toContain(`by the next producer ${HexConverter.encode(bobPublic)}`); + expect(error.message).toContain('name a different first producer'); + expect(await readdir(directory)).toEqual([]); + }); + + it('is written with a warning when the check for later revisions fails', async () => { + await bobAppends(); + const failing = new StateTransitionClient( + new ScriptedLookupClient(aggregator, [ + null, + (): Promise => Promise.reject(new JsonRpcNetworkError(502, 'bad gateway')), + ]), + ); + const sink = testContext(); + expect(await stampRevisionWith(config({}), failing, sink.context)).toBe(0); + expect(sink.stderr()).toContain('warning: Could not check whether the lineage has later revisions: '); + expect(sink.stderr()).toContain('not a new one.'); + // Revision 0 of the same lineage; its proof is now served under a later root. + const written = await Token.fromCBOR(new Uint8Array(await readFile(tokenFile))); + expect(HexConverter.encode(written.id.bytes)).toEqual(tokenIdHex); + expect(written.transactions).toHaveLength(0); + }); + + it('is written with a warning when the proof of a later revision does not verify', async () => { + // Revision 1 certified by an aggregator outside the trust base. + const elsewhere = TestAggregatorClient.create(); + const genesis = await Token.fromCBOR(genesisBytes); + const forged = await prepareRevision(genesis, aggregator.rootTrustBase, OTHER_DIGEST, bob, bobPublic); + await elsewhere.submitCertificationRequest(forged.certificationData); + const forging = new StateTransitionClient( + new ScriptedLookupClient(aggregator, [ + null, + (stateId): Promise => elsewhere.getInclusionProof(stateId), + ]), + ); + const sink = testContext(); + expect(await stampRevisionWith(config({}), forging, sink.context)).toBe(0); + expect(sink.stderr()).toContain('warning: The gateway showed a proof of a later revision that does not verify'); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + }); + }); + describe('journal', () => { let tokenFile: string; let journal: string; @@ -249,7 +360,7 @@ describe('stampRevisionWith', () => { const sink = testContext(); expect(await stampRevisionWith(append({ quiet: true }), client, sink.context)).toBe(0); expect(sink.stderr()).toEqual(`Recovered revision 1 from the journal ${journal} of an interrupted run.\n`); - expect(sink.stdout()).toContain('Revision 1\n'); + expect(sink.stdout()).toContain('Revision 1 (recovered)\n'); expect(await readdir(directory)).toEqual(['doc.lineage']); expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); }); @@ -378,6 +489,7 @@ describe('stamp-revision output', () => { gatewayUrl: 'https://gateway.test', networkId: 4, nextProducer: next, + recovered: false, referenceTime: 1791200527n, revision: 2n, roundNumber: 184233n, @@ -424,6 +536,7 @@ describe('stamp-revision output', () => { hash: { algorithm: 'SHA-256', digest: TEST_DIGEST_HEX }, network: { gateway: 'https://gateway.test', id: 4, name: 'testnet2' }, nextProducer: HexConverter.encode(next), + recovered: false, referenceTime: '1791200527', referenceTimeIso: '2026-10-05T11:42:07Z', revision: '2', @@ -445,6 +558,41 @@ describe('stamp-revision output', () => { ); }); + it('marks a recovered revision, and a recovered genesis as an existing lineage', () => { + expect(revisionText({ ...summary, recovered: true })).toContain('Revision 2 (recovered)\n'); + expect(revisionText({ ...summary, nextProducer: null, recovered: true })).toContain( + 'Revision 2 (recovered) (final)\n', + ); + expect(revisionText({ ...summary, created: true, recovered: true, revision: 0n })).toContain( + 'Revision 0 (existing lineage, recovered)\n', + ); + expect(revisionText({ ...summary, created: true, revision: 0n })).toContain('Revision 0 (new lineage)\n'); + expect(revisionJson({ ...summary, recovered: true }).recovered).toBe(true); + }); + + it('says a recovered genesis is an existing lineage, and how to start a separate one', () => { + expect(existingLineageNote(new Uint8Array(32).fill(0xaa))).toEqual( + `This genesis was already certified: the token file holds revision 0 of the existing lineage ${'aa'.repeat(32)}, ` + + 'not a new one. To start a separate lineage from the same document, name a different first producer ' + + '(or sign with a different issuer key).\n', + ); + }); + + it('explains a superseded genesis: when the lineage moved on, to whom, and what still holds', () => { + const message = supersededLineageMessage(new Uint8Array(32).fill(0xaa), 1791200527n, producer); + expect(message).toEqual( + `Revision 0 of lineage ${'aa'.repeat(32)} was certified by an earlier run, and the lineage has moved on: ` + + `revision 1 was certified at 2026-10-05T11:42:07Z by the next producer ${TEST_PUBLIC_KEY_HEX}. ` + + 'A token file holding only revision 0 would be out of date, so none was written. Get the current token ' + + 'file from whoever holds the lineage; the token id above still identifies the lineage. To start a ' + + 'separate lineage from the same document, name a different first producer (or sign with a different ' + + 'issuer key).', + ); + expect(supersededLineageMessage(new Uint8Array(32), 1791200527n, null)).toContain( + 'revision 1 was certified at 2026-10-05T11:42:07Z. A token file', + ); + }); + describe('pending revision notes', () => { const note = { digest: TEST_DIGEST, diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts index 1bba73d..7fb029c 100644 --- a/tests/unit/lib/LineageClientTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -20,8 +20,10 @@ import { appendRevision, certifyRevision, createLineage, + createOrRecoverLineage, currentProducerKey, deriveGenesisSalt, + findSuccessor, isFinalized, isSameRevision, LineageError, @@ -77,6 +79,39 @@ class LateRoundClient implements IAggregatorClient { } } +/** Shows nothing on the first `misses` proof lookups, as if the earlier request were still in its round. */ +class MissingLookupsClient implements IAggregatorClient { + private lookups = 0; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly misses: number, + ) {} + + public async getInclusionProof(stateId: StateId): Promise { + this.lookups += 1; + const response = await this.inner.getInclusionProof(stateId); + return this.lookups <= this.misses + ? InclusionProofResponse.notCertified(1n, response.unicityCertificate) + : response; + } + + public submitCertificationRequest(certificationData: CertificationData): Promise { + return this.inner.submitCertificationRequest(certificationData); + } +} + +/** Fails every proof lookup, so a test can see that none was made. */ +class NoLookupClient implements IAggregatorClient { + public getInclusionProof(): Promise { + return Promise.reject(new Error('no lookup expected')); + } + + public submitCertificationRequest(): Promise { + return Promise.reject(new Error('no submission expected')); + } +} + describe('LineageClient', () => { // A fresh aggregator per test: a genesis is deterministic in its issuer, digest // and recipient, so tests sharing one would all continue the same lineage. @@ -293,6 +328,72 @@ describe('LineageClient', () => { ).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); }); + describe('recovering a genesis', () => { + it('tells a fresh genesis from one an earlier run certified, which it recovers without submitting', async () => { + const fresh = await createOrRecoverLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + expect(fresh.recovered).toBe(false); + const submissions = counting.submissions; + const again = await createOrRecoverLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + expect(again.recovered).toBe(true); + expect(counting.submissions).toBe(submissions); + expect(HexConverter.encode(again.token.id.bytes)).toEqual(HexConverter.encode(fresh.token.id.bytes)); + }); + + // One miss: the lookup before submitting. Two: the one after STATE_ID_EXISTS too, + // so the proof only arrives while waiting for it. + it.each([1, 2])('counts STATE_ID_EXISTS for this very mint as a recovery (%i missed lookups)', async (misses) => { + await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const missing = new StateTransitionClient(new MissingLookupsClient(aggregator, misses)); + const replays: string[] = []; + const again = await createOrRecoverLineage(missing, trustBase, TEST_DIGEST, alice, publicKey(bob), { + ...fast, + onAlreadyCertified: () => replays.push('genesis'), + }); + expect(again.recovered).toBe(true); + expect(replays).toEqual(['genesis']); + }); + + it('reports a replayed append through onAlreadyCertified, and a fresh one not', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const replays: number[] = []; + const options = { ...fast, onAlreadyCertified: (): number => replays.push(1) }; + await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), options); + expect(replays).toEqual([]); + await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), options); + expect(replays).toEqual([1]); + }); + }); + + describe('findSuccessor', () => { + it('finds no successor until the next revision is certified, then proves it', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + expect(await findSuccessor(client, trustBase, genesis)).toEqual({ kind: 'none' }); + + const next = await appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast); + const lookup = await findSuccessor(client, trustBase, genesis); + expect(lookup.kind).toEqual('spent'); + expect(lookup.kind === 'spent' && lookup.proof.referenceTime).toBe(next.transactions[0].referenceTime); + // The lookup follows the token's own tip. + expect(await findSuccessor(client, trustBase, next)).toEqual({ kind: 'none' }); + }); + + it('does not look up a finalized lineage, which nothing can follow', async () => { + const sealed = await createLineage(client, trustBase, TEST_DIGEST, alice, null, fast); + const nobody = new StateTransitionClient(new NoLookupClient()); + expect(await findSuccessor(nobody, trustBase, sealed)).toEqual({ kind: 'none' }); + }); + + it('does not believe a proof that does not verify against the trust base', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const elsewhere = TestAggregatorClient.create(); + const forged = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + await elsewhere.submitCertificationRequest(forged.certificationData); + const forging = new StateTransitionClient(elsewhere); + expect(await findSuccessor(forging, trustBase, genesis)).toEqual({ kind: 'unverified' }); + expect((await findSuccessor(forging, elsewhere.rootTrustBase, genesis)).kind).toEqual('spent'); + }); + }); + describe('finalization', () => { it('seals the final revision and burns the token, so nothing can follow', async () => { const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); From 5dbea615c0a88a605341d5b24b086cee74a3203f Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 11:47:56 +0200 Subject: [PATCH 15/25] Say "the latest in this file" instead of "the latest" for an unsealed match `verify` labelled a match on the last revision of an unsealed lineage "(the latest)", a claim offline verification cannot back: every earlier state of a lineage is itself a valid token, so an old copy, or one with trailing revisions dropped, still verifies. The label is now "(the latest in this file)"; "(the final)" after a seal is unchanged. The README and the agent skill say that only --finalize proves no later revision exists. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- skills/unicity-proof/SKILL.md | 6 +++++- src/output.ts | 5 ++++- tests/unit/VerifyTest.ts | 6 +++--- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d1beb93..d4710de 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ Revision 0 SHA-256 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730433629 … ``` -With `--token-id`, the lineage passes only if its token id is that one; `Lineage id` says whether it matched, or that it was not checked, in which case nothing has established *which* lineage this is. A different id is a failure, reported before any hash mismatch. `--token-id` is refused for tokens that are not lineages. With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision, or `none; the lineage is finalized` after a seal, which is marked `(final)`. In `--json` output a lineage has `"tokenType": "lineage"`, `finalized`, a `revisions` array (each with `sealed`), `expectedTokenIdMatches` (null when no `--token-id` was given) and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. +With `--token-id`, the lineage passes only if its token id is that one; `Lineage id` says whether it matched, or that it was not checked, in which case nothing has established *which* lineage this is. A different id is a failure, reported before any hash mismatch. `--token-id` is refused for tokens that are not lineages. With `--file` or `--hash`, the lineage passes if any revision carries that digest; `Expected hash` says which one, and whether a later revision supersedes it. A match on the last revision is marked `(the final)` when that revision is a seal, and `(the latest in this file)` otherwise. Only a seal (`--finalize`) proves that no later revision exists: every earlier state of a lineage is itself a valid token, so an unsealed file can be missing revisions certified since, whether through an old copy or trailing revisions dropped, and verification, being offline, cannot tell. A digest no revision carries is a failure. `Signed by` on revision 0 is the issuer from the genesis reason; on later revisions it is the key the previous revision passed to, which the transfer's signature was checked against. `Next producer` is who may append the next revision, or `none; the lineage is finalized` after a seal, which is marked `(final)`. In `--json` output a lineage has `"tokenType": "lineage"`, `finalized`, a `revisions` array (each with `sealed`), `expectedTokenIdMatches` (null when no `--token-id` was given) and `matchingRevisions` (positions of the matching revisions, or null when no hash was given) in place of the timestamp fields. Format: token type `SHA-256("unicity-document-lineage")`; auxiliary data `CBOR[i, SHA-256(doc_i)]` on the genesis (`i = 0`) and on each transfer, or `CBOR["seal", i, SHA-256(doc_i)]` on the final revision, whose recipient is then the burn predicate with reason `SHA-256(auxiliary data)`; genesis reason CBOR tag 39200 over `[1, issuer public key, signature]`, the signature covering `SHA-256(CBOR["unicity-document-lineage", 1, token id, token type, recipient, auxiliary data])`, where `recipient` is the mint's recipient predicate in its tagged CBOR encoding (tag 39032). Verification additionally requires the indices to increase by one, the reference times not to decrease along the chain, and a revision to be burned exactly when it is a seal, with the burn reason as above. diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index 6c890c5..2761a27 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -28,7 +28,11 @@ holds several revisions. With `--file` it passes if **any** revision carries the file's hash, so read the `Expected hash` line in full: `matches revision 1; superseded by revision 2` means the file is a genuine but outdated revision. `matches revision 2 (the final)` means the lineage was finalized with that -revision (`--finalize`); no later revision can exist. +revision (`--finalize`); no later revision can exist. `matches revision 2 (the +latest in this file)` does **not** mean the file is current: any older copy of +an unsealed lineage still verifies, and verification is offline, so later +revisions may have been certified since. Only `(the final)` rules them out; if +being current matters, ask whoever holds the lineage for the current file. A matching hash does not say *which* lineage the file is in: one issuer can start several certified lineages from the same document. Only the token id diff --git a/src/output.ts b/src/output.ts index 07a82b5..2f97449 100644 --- a/src/output.ts +++ b/src/output.ts @@ -704,7 +704,10 @@ function lineageExpectedHashLabel(result: ILineageVerificationResult): string { if (last !== latest) { return `${which}; superseded by revision ${latest}`; } - return `${which} (the ${result.description.finalized ? 'final' : 'latest'})`; + // A seal is a burn, so nothing can follow it. Without one, every earlier state of + // the lineage is itself a valid token, and offline verification cannot tell + // whether later revisions were certified after this file was made. + return `${which} (${result.description.finalized ? 'the final' : 'the latest in this file'})`; } // Like the expected hash: without an id there is no telling this lineage from a diff --git a/tests/unit/VerifyTest.ts b/tests/unit/VerifyTest.ts index 6030043..90877c1 100644 --- a/tests/unit/VerifyTest.ts +++ b/tests/unit/VerifyTest.ts @@ -168,7 +168,7 @@ describe('runVerify on a document lineage', () => { it('finds an expected hash among the revisions', async () => { const latest = testContext(); await runVerify(fixture.tokenFile, { hash: THIRD_DIGEST_HEX, trustBase: fixture.trustBaseFile }, latest.context); - expect(latest.stdout()).toContain('Expected hash matches revision 2 (the latest)\n'); + expect(latest.stdout()).toContain('Expected hash matches revision 2 (the latest in this file)\n'); const older = testContext({ json: true }); expect( @@ -315,9 +315,9 @@ describe('verify output for a document lineage', () => { it.each<[string, readonly number[] | null, string]>([ ['no digest given', null, 'not checked; pass --file or --hash to find your document in the lineage'], - ['the latest revision', [2], 'matches revision 2 (the latest)'], + ['the last revision in the file', [2], 'matches revision 2 (the latest in this file)'], ['an older revision', [1], 'matches revision 1; superseded by revision 2'], - ['several revisions', [0, 2], 'matches revisions 0, 2 (the latest)'], + ['several revisions', [0, 2], 'matches revisions 0, 2 (the latest in this file)'], ['no revision', [], 'differs from every revision'], ])('labels the expected hash when it matches %s', (_, matchingRevisions, label) => { expect(lineageVerifyText(result({ matchingRevisions }), bundled)).toContain(`Expected hash ${label}\n`); From 8fe985e05f51466e8c5531f292c04d23b37197bc Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 11:54:20 +0200 Subject: [PATCH 16/25] Test the index, time and seal-is-last chain rules The rules the protocol does not provide had no tests past genesis: replacing the time check with `true`, or checking the index at position 0 only, left the suite passing. New tests build transfers by hand, past the checks appendRevision makes: - a transfer claiming index 5 at position 1, and one repeating index 1 at position 2; - a revision certified before the one it follows, and before the genesis, by certifying precomputed states out of order; - a seal followed by a revision, which SealIsLast rejects alongside SealBurned; - an in-order chain built the same way, as the control. Co-Authored-By: Claude Opus 5.5 --- tests/unit/lib/LineageVerificationTest.ts | 175 +++++++++++++++++++++- 1 file changed, 174 insertions(+), 1 deletion(-) diff --git a/tests/unit/lib/LineageVerificationTest.ts b/tests/unit/lib/LineageVerificationTest.ts index 39729f0..6e9ef6b 100644 --- a/tests/unit/lib/LineageVerificationTest.ts +++ b/tests/unit/lib/LineageVerificationTest.ts @@ -1,12 +1,22 @@ +import { createHash } from 'node:crypto'; + +import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { SignaturePredicateUnlockScript } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicateUnlockScript.js'; import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import type { IPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/IPredicate.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { CertifiedTransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedTransferTransaction.js'; +import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js'; +import { StateMask } from '@unicitylabs/state-transition-sdk/lib/transaction/StateMask.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.js'; import { TokenSalt } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenSalt.js'; +import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; +import { VerificationResult } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationResult.js'; +import { VerificationStatus } from '@unicitylabs/state-transition-sdk/lib/verification/VerificationStatus.js'; import { createLineage } from '../../../src/lib/LineageClient.js'; import { @@ -15,8 +25,13 @@ import { LineageRevision, sealPredicate, } from '../../../src/lib/LineagePayload.js'; -import { describeLineage, verifyLineage } from '../../../src/lib/LineageVerification.js'; +import { + createLineageVerificationContext, + describeLineage, + verifyLineage, +} from '../../../src/lib/LineageVerification.js'; import { bundledTrustBase } from '../../../src/lib/networks.js'; +import { certifyMintTransaction, certifyTransaction } from '../../../src/lib/TimestampClient.js'; import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; import { certifyMint } from '../../support/TimestampFixtures.js'; @@ -187,6 +202,164 @@ describe('LineageVerification', () => { }); }); + describe('chain rules', () => { + interface IRawTransfer { + readonly certificationData: CertificationData; + readonly transaction: TransferTransaction; + } + + /** + * A transfer out of the latest state of `source`, with any payload and + * recipient, signed by `producer`, bypassing the checks appendRevision makes. + * `source` need only offer its latest transaction, so a transfer can be built + * on one that is not certified yet. + */ + async function rawTransfer( + source: Pick, + producer: Uint8Array, + data: Uint8Array, + recipient: IPredicate, + ): Promise { + const transaction = await TransferTransaction.create(source as Token, recipient, StateMask.generate(), { data }); + const certificationData = await CertificationData.fromTransaction( + transaction, + await SignaturePredicateUnlockScript.create(transaction, new SigningService(producer)), + ); + return { certificationData, transaction }; + } + + async function certify(raw: IRawTransfer): Promise { + const context = createLineageVerificationContext(trustBase); + const proof = await certifyTransaction(client, context, raw.certificationData, raw.transaction, fast); + return raw.transaction.toCertifiedTransaction( + trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + proof, + ); + } + + async function attach(token: Token, ...transfers: CertifiedTransferTransaction[]): Promise { + let result = token; + for (const transfer of transfers) { + result = await result.transfer(transfer, createLineageVerificationContext(trustBase)); + } + return result; + } + + /** Names of the failing rules anywhere in the result tree. */ + function failedRules(result: VerificationResult | null): string[] { + if (result === null) { + return []; + } + const own = result.status === VerificationStatus.OK ? [] : [result.rule]; + return [...own, ...result.results.flatMap(failedRules)]; + } + + // The aggregator is shared and a genesis is deterministic in its inputs, so each + // test starts its own lineage from a digest of its own. + let lineages = 0; + function freshGenesis(): Promise { + lineages += 1; + const digest = new Uint8Array(createHash('sha256').update(`chain rules ${lineages}`).digest()); + return createLineage(client, trustBase, digest, alice, publicKey(bob), fast); + } + + const revision = (index: bigint, digest = OTHER_DIGEST): Uint8Array => + LineageRevision.create(index, digest).toCBOR(); + const pSig = (key: Uint8Array): IPredicate => SignaturePredicate.create(publicKey(key)); + + it('accepts revisions appended in order, the control for the cases below', async () => { + const genesis = await freshGenesis(); + const first = await rawTransfer(genesis, bob, revision(1n), pSig(carol)); + const second = await rawTransfer({ latestTransaction: first.transaction }, carol, revision(2n), pSig(alice)); + const token = await attach(genesis, await certify(first), await certify(second)); + const result = await verifyLineage(token, trustBase); + expect(result.reason).toBeNull(); + expect(result.status).toEqual('OK'); + }); + + it('rejects a transfer claiming another index than its position', async () => { + const genesis = await freshGenesis(); + // A producer controls the payload of their own transfer, so a wrong index is a realistic input. + const skipped = await rawTransfer(genesis, bob, revision(5n), pSig(carol)); + const result = await verifyLineage(await attach(genesis, await certify(skipped)), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision at position 1 claims index 5.'); + expect(failedRules(result.details)).toContain('Revision[1]IndexSequential'); + }); + + it('rejects a transfer repeating the previous index, further down the chain', async () => { + const genesis = await freshGenesis(); + const first = await rawTransfer(genesis, bob, revision(1n), pSig(carol)); + const repeat = await rawTransfer({ latestTransaction: first.transaction }, carol, revision(1n), pSig(alice)); + const token = await attach(genesis, await certify(first), await certify(repeat)); + const result = await verifyLineage(token, trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual('Revision at position 2 claims index 1.'); + }); + + // States can be precomputed and certified out of order: the protocol links each + // transfer to the state before it, not to the time it was certified. + it('rejects a revision certified before the one it follows', async () => { + const genesis = await freshGenesis(); + const first = await rawTransfer(genesis, bob, revision(1n), pSig(carol)); + const second = await rawTransfer({ latestTransaction: first.transaction }, carol, revision(2n), pSig(alice)); + const certifiedSecond = await certify(second); + const certifiedFirst = await certify(first); + expect(certifiedSecond.referenceTime).toBeLessThan(certifiedFirst.referenceTime); + + const result = await verifyLineage(await attach(genesis, certifiedFirst, certifiedSecond), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toEqual( + `Revision 2 is certified at ${certifiedSecond.referenceTime}, before revision 1 at ${certifiedFirst.referenceTime}.`, + ); + expect(failedRules(result.details)).toContain('Revision[2]TimeMonotone'); + }); + + it('rejects a transfer certified before the genesis it follows', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST).toCBOR(); + // Build the genesis, and the transfer out of it, before certifying either. + const salt = TokenSalt.generate(); + const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + EncodedPredicate.fromPredicate(pSig(bob)), + data, + new SigningService(alice), + ); + const mint = await MintTransaction.create(trustBase.networkId, pSig(bob), { + data, + justification: reason.toCBOR(), + salt, + tokenType: LINEAGE_TOKEN_TYPE, + }); + const first = await rawTransfer({ latestTransaction: mint }, bob, revision(1n), pSig(carol)); + const certifiedFirst = await certify(first); + const context = createLineageVerificationContext(trustBase); + const genesis = await Token.mint(await certifyMintTransaction(client, context, mint, fast), context); + + const result = await verifyLineage(await attach(genesis, certifiedFirst), trustBase); + expect(result.status).toEqual('FAIL'); + expect(result.reason).toMatch(/^Revision 1 is certified at \d+, before revision 0 at \d+\.$/); + }); + + // Defence in depth: a seal is burned and nothing can spend a burn, so a token with + // a revision after a seal fails other rules first. Here the seal is minted to a key + // instead, which SealBurned rejects, and SealIsLast must reject it as well. + it('rejects a seal that revisions follow', async () => { + const data = LineageRevision.create(0n, TEST_DIGEST, true).toCBOR(); + const genesis = await signedGenesis(data, pSig(bob)); + const next = await rawTransfer(genesis, bob, revision(1n), pSig(carol)); + const result = await verifyLineage(await attach(genesis, await certify(next)), trustBase); + expect(result.status).toEqual('FAIL'); + expect(failedRules(result.details)).toEqual( + expect.arrayContaining(['Revision[0]SealBurned', 'Revision[0]SealIsLast']), + ); + }); + }); + describe('token id', () => { it('passes when the lineage is the one with the expected token id', async () => { const token = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); From a6413b27953e80b29f0ccfef99ea3aa9f7299258 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 13:20:02 +0200 Subject: [PATCH 17/25] Refuse, with exit 2, an append to a token from another network The configured network was used to verify the token, so a valid testnet2 lineage appended without --network testnet2 failed as an invalid token (exit 1). The network is still not taken from the token, since it also picks the gateway the API key goes to; instead the mismatch is caught before the journal is read or anything is submitted, as a usage error that names both networks and the setting to change: --network, or --trust-base when the token's network has no bundled trust base or a trust base file is configured. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +-- skills/unicity-proof/SKILL.md | 4 +++ src/commands/stampRevision.ts | 59 +++++++++++++++++++++++++++++- src/config.ts | 20 ++++++++++- tests/unit/ConfigTest.ts | 10 ++++++ tests/unit/StampRevisionTest.ts | 63 ++++++++++++++++++++++++++++++++- 6 files changed, 155 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d4710de..d31b5ea 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Arguments are loaded, in order of precedence, from: flags > variables in shell m | Variable | Flag | Meaning | Default | | --- | --- | --- | --- | | `UNICITY_API_KEY` | `--api-key` | Gateway API key. Needed by `stamp` only. | none | -| `UNICITY_NETWORK` | `--network` | `mainnet` or `testnet2`. Selects the gateway and the bundled trust base for `stamp`. `verify` reads the network from the token; only its `--network` flag overrides that. | `mainnet` | +| `UNICITY_NETWORK` | `--network` | `mainnet` or `testnet2`. Selects the gateway and the bundled trust base for `stamp` and `stamp-revision`; an append must name the network its token is from. `verify` reads the network from the token; only its `--network` flag overrides that. | `mainnet` | | `UNICITY_PRIVATE_KEY` | `--key-file` | secp256k1 private key, 64 hex characters. When set, stamps are signed. | none, stamps are anonymous | | `UNICITY_GATEWAY_URL` | `--gateway` | Override the gateway URL only. | preset gateway | | `UNICITY_TRUST_BASE` | `--trust-base` | Override the bundled trust base file. **Not** read from an automatically discovered `./.env` — see below. | bundled file | @@ -143,7 +143,7 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - A journal the command cannot place (for another lineage, for a later revision than the token file holds, or unreadable) stops it with exit 2 and is left alone. - A new lineage needs no journal: its genesis is derived from its inputs, and running it again with the same file, key, digest and recipient recovers it (see above). - In `--json` output, `recovered` is true when an earlier run had already certified the revision and this run only recovered it; the text output marks such a revision `(recovered)`. -- Network options behave as for `stamp`. +- Network options behave as for `stamp`, so a testnet2 lineage needs `--network testnet2` (or `UNICITY_NETWORK=testnet2`) on every append, not just at creation. The network is not taken from the token, because it also decides which gateway the API key is sent to. An append whose token file is from another network than the one configured stops with exit 2 before anything is submitted, and the message says what to change. `verify` and `inspect` recognise lineage tokens by their token type and list every revision with its hash, signer, next producer and certification time: diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index 2761a27..bab69ce 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -76,6 +76,10 @@ without it the proof is gone. If `stamp-revision` exits 1 saying `the lineage has moved on`, later revisions exist: get the current token file from whoever holds the lineage rather than creating it again. +- **Every `stamp-revision` append needs the lineage's network.** The network is + not read from the token file, so a testnet2 lineage needs `--network testnet2` + each time. Exit 2 naming two networks means the configuration, not the token, + is wrong: change the setting it names. Do not re-create the lineage. - `--sign` exits 2 unless a key is configured. Use it in any automated path that must never silently produce an anonymous stamp. `--anonymous` forces the opposite. diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 335e88c..419ea35 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -24,7 +24,7 @@ import { } from './revisionJournal.js'; import { decodeToken, tokenBytesFromInput } from './tokenInput.js'; import { IStampRevisionConfig, IStampRevisionFlags, resolveStampRevisionConfig } from '../config.js'; -import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED } from '../errors.js'; +import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED, usageError } from '../errors.js'; import { errorMessage, StampError } from '../lib/errors.js'; import { assertValidLineage, @@ -38,9 +38,11 @@ import { recoverRevision, SuccessorLookup, } from '../lib/LineageClient.js'; +import { networkNameForId } from '../lib/networks.js'; import { ICertifyOptions } from '../lib/TimestampClient.js'; import { existingLineageNote, + networkLabel, PendingRevisionContext, pendingRevisionLines, recoveredRevisionLine, @@ -301,6 +303,51 @@ function latestCertified(token: Token): CertifiedMintTransaction | CertifiedTran return token.transactions.at(-1) ?? token.genesis; } +/** + * Say what to change when the token file is from another network than the one + * this run is set to. Not inferred from the token: the network also picks the + * gateway the API key is sent to, so the user chooses it, as for a genesis. + * + * @param {string} tokenFile Token file path, for the message. + * @param {number} tokenNetworkId Network id the token carries. + * @param {number} configuredNetworkId Network id of the configured trust base. + * @param {string|null} trustBasePath The configured trust base file, or null for a bundled one. + * @returns {Error|null} A usage error, or null when the networks agree. + */ +export function networkMismatch( + tokenFile: string, + tokenNetworkId: number, + configuredNetworkId: number, + trustBasePath: string | null, +): Error | null { + if (tokenNetworkId === configuredNetworkId) { + return null; + } + const bundled = networkNameForId(tokenNetworkId); + const lineage = + bundled === undefined + ? `${tokenFile} is a lineage on network ${tokenNetworkId}, which has no bundled trust base` + : `${tokenFile} is a ${networkLabel(tokenNetworkId)} lineage`; + const configured = + trustBasePath === null + ? `this run is set to ${networkLabel(configuredNetworkId)}` + : `the trust base ${trustBasePath} is for ${networkLabel(configuredNetworkId)}`; + let advice: string; + if (bundled === undefined) { + advice = + trustBasePath === null + ? "Pass --trust-base with that network's trust base, and --gateway with its gateway." + : "Pass --trust-base with that network's trust base instead."; + } else { + advice = + trustBasePath === null + ? `Pass --network ${bundled}, or set UNICITY_NETWORK=${bundled}.` + : `Pass a trust base for ${bundled}, or drop the trust base (--trust-base or UNICITY_TRUST_BASE) ` + + `and pass --network ${bundled}.`; + } + return usageError(`${lineage}, but ${configured}. ${advice} Nothing was submitted.`); +} + /** * The part of `stamp-revision` after configuration: certify, write, report. Takes * the client as a parameter so it can run against an in-memory aggregator. @@ -350,6 +397,16 @@ export async function stampRevisionWith( if (decoded.token === null) { throw new CliError(`${config.tokenFile} is ${decoded.error}.`, EXIT_VERIFICATION_FAILED); } + // Before the journal is read: a journal is only acted on against the right network. + const mismatch = networkMismatch( + config.tokenFile, + decoded.token.networkId.id, + trustBase.networkId.id, + config.trustBasePath, + ); + if (mismatch !== null) { + throw mismatch; + } ({ recovered, signer, token } = await appendJournaled(config, client, context, options, decoded.token)); } diff --git a/src/config.ts b/src/config.ts index 25f7299..73a2a42 100644 --- a/src/config.ts +++ b/src/config.ts @@ -482,6 +482,11 @@ export interface IStampRevisionConfig { readonly tokenBytes: Uint8Array | null; /** Absolute path of the token file. */ readonly tokenFile: string; + /** + * Absolute path of the trust base file that replaced the bundled one, or null. + * Only for messages: an append whose token is from another network says what to change. + */ + readonly trustBasePath: string | null; } /** Compressed secp256k1 public key as hex, any case, optional 0x prefix. */ @@ -628,5 +633,18 @@ export async function resolveStampRevisionConfig( const digest = (await resolveDigest(digestArgument, flags.file)) as Uint8Array; const quiet = flags.quiet ?? false; - return { allowInsecure, apiKey, digest, network, privateKey, quiet, recipientKey, timeoutMs, tokenBytes, tokenFile }; + const trustBasePath = selection.trustBasePath === undefined ? null : path.resolve(selection.trustBasePath); + return { + allowInsecure, + apiKey, + digest, + network, + privateKey, + quiet, + recipientKey, + timeoutMs, + tokenBytes, + tokenFile, + trustBasePath, + }; } diff --git a/tests/unit/ConfigTest.ts b/tests/unit/ConfigTest.ts index 760bd89..1de245b 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -407,6 +407,16 @@ describe('resolveStampRevisionConfig', () => { expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), quiet: true }, env)).quiet).toBe(true); }); + it('records the trust base file, as an absolute path, for messages', async () => { + expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), env)).trustBasePath).toBeNull(); + const trustBaseFile = path.join(directory, 'testnet2.json'); + await writeFile(trustBaseFile, JSON.stringify(NETWORKS.testnet2.trustBaseJson)); + const relative = path.relative(process.cwd(), trustBaseFile); + const config = await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), { ...env, UNICITY_TRUST_BASE: relative }); + expect(config.trustBasePath).toEqual(trustBaseFile); + expect(config.network.trustBase.networkId.id).toBe(4); + }); + it('reads an existing token file and a recipient key file', async () => { const tokenFile = path.join(directory, 'doc.lineage'); await writeFile(tokenFile, 'abcd'); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index e419be4..c7722d6 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -12,11 +12,12 @@ import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/Sta import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; -import { stampRevisionWith } from '../../src/commands/stampRevision.js'; +import { networkMismatch, stampRevisionWith } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; import { appendRevision, prepareRevision } from '../../src/lib/LineageClient.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; +import { bundledTrustBase } from '../../src/lib/networks.js'; import { existingLineageNote, IRevisionSummary, @@ -101,6 +102,7 @@ describe('stampRevisionWith', () => { timeoutMs: 2_000, tokenBytes: null, tokenFile: path.join(directory, 'doc.lineage'), + trustBasePath: null, ...overrides, }; } @@ -466,6 +468,65 @@ describe('stampRevisionWith', () => { await expect(attempt).rejects.toMatchObject({ code: 'INVALID_TOKEN' }); expect(await readFile(journal)).toEqual(leftover); }); + + it.each([ + [ + null, + /, but this run is set to mainnet \(1\)\. Pass --trust-base with that network's trust base, and --gateway/, + ], + [ + '/keys/mainnet.json', + /, but the trust base \/keys\/mainnet\.json is for mainnet \(1\)\. Pass --trust-base .* instead\./, + ], + ])( + 'refuses, with exit 2, a token from another network than the configured one (trust base file %s)', + async (trustBasePath, advice) => { + await interrupted(); + const leftover = await readFile(journal); + const mainnet = { + network: { + gatewayUrl: 'https://gateway.test', + preset: 'mainnet' as const, + trustBase: bundledTrustBase('mainnet'), + }, + trustBasePath, + }; + const sink = testContext(); + const attempt = stampRevisionWith(append(mainnet), client, sink.context); + await expect(attempt).rejects.toThrow( + new RegExp(`^${tokenFile} is a lineage on network 3, which has no bundled trust base`), + ); + await expect(attempt).rejects.toThrow(advice); + await expect(attempt).rejects.toThrow(/ Nothing was submitted\.$/); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(sink.stderr()).toEqual(''); + expect(await readFile(journal)).toEqual(leftover); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + }, + ); + }); + + describe('networkMismatch', () => { + it('accepts a token from the configured network', () => { + expect(networkMismatch('/d/doc.lineage', 4, 4, null)).toBeNull(); + expect(networkMismatch('/d/doc.lineage', 3, 3, '/keys/local.json')).toBeNull(); + }); + + it('names both networks and the setting to change', () => { + expect(networkMismatch('/d/doc.lineage', 4, 1, null)?.message).toEqual( + '/d/doc.lineage is a testnet2 (4) lineage, but this run is set to mainnet (1). ' + + 'Pass --network testnet2, or set UNICITY_NETWORK=testnet2. Nothing was submitted.', + ); + expect(networkMismatch('/d/doc.lineage', 1, 3, '/keys/local.json')?.message).toEqual( + '/d/doc.lineage is a mainnet (1) lineage, but the trust base /keys/local.json is for unknown network (3). ' + + 'Pass a trust base for mainnet, or drop the trust base (--trust-base or UNICITY_TRUST_BASE) ' + + 'and pass --network mainnet. Nothing was submitted.', + ); + }); + + it('is a usage error', () => { + expect(toExitCode(networkMismatch('/d/doc.lineage', 4, 1, null))).toBe(EXIT_USAGE); + }); }); it('refuses a file that is not a token', async () => { From 691531170d09f39c3309d55537fec6d36d6f071e Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 13:33:31 +0200 Subject: [PATCH 18/25] Add --force to stamp-revision, and give its EEXIST advice that applies When the exclusive create of a new lineage's token file failed with EEXIST (a file appeared during the proof wait, or --token-file was a dangling symlink), the advice was "pass --force or another --out", and stamp-revision had neither option. The error now says which case it is, that the genesis is certified, and that running the same command again recovers it: with another --token-file, or, for a dangling symlink, with --force, which creates the file the symlink points to. --force makes the new-lineage write non-exclusive. It never applies to an existing token file, which is appended to, not replaced; combining the two is a usage error. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + skills/unicity-proof/SKILL.md | 5 +++ src/cli.ts | 4 ++ src/commands/revisionJournal.ts | 7 +++- src/commands/stampRevision.ts | 55 ++++++++++++++++++++---- src/config.ts | 15 +++++++ tests/unit/ConfigTest.ts | 11 +++++ tests/unit/StampRevisionTest.ts | 63 +++++++++++++++++++++++++++- tests/unit/StampRevisionWriteTest.ts | 14 ++++++- 9 files changed, 163 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d31b5ea..9c3a147 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - The output says `Revision 0 (existing lineage, recovered)`, and a note on stderr, printed even with `--quiet`, says that this is the existing lineage and how to start a separate one. - Before writing, the command asks the aggregator whether revision 1 exists. If it shows a proof that verifies against the trust base, the lineage has moved on: nothing is written, and the command exits 1, naming the token id, when revision 1 was certified and by whom. Get the current token file from whoever holds the lineage. - If the aggregator cannot be asked, or shows a proof that does not verify, the file is written with a warning. The check can find later revisions but never rule them out: the aggregator issues no proofs of absence. +- A new lineage's token file is created exclusively. If a file appears at `--token-file` while the genesis is being certified, it is left alone and the command exits 2; the genesis is printed as hex, and running the same command with another `--token-file` recovers it there. A `--token-file` that is a symlink to a missing file is refused the same way. `--force` overwrites a file that appeared, or creates the file a symlink points to. It only applies to a new lineage: with an existing token file, `--force` is a usage error, because the file would be appended to and never replaced. - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `..pending` (`.doc.lineage.pending` for `doc.lineage`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. The journal is removed once the token file holds the revision. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index bab69ce..8100666 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -76,6 +76,11 @@ without it the proof is gone. If `stamp-revision` exits 1 saying `the lineage has moved on`, later revisions exist: get the current token file from whoever holds the lineage rather than creating it again. +- **A new lineage blocked by a file at `--token-file` is not lost.** Exit 2 + saying the file appeared during certification, or is a dangling symlink, means + the genesis is certified: run the same command with another `--token-file` to + recover it. `--force` only overwrites for a new lineage; never use it to + "replace" an existing token file (it refuses). - **Every `stamp-revision` append needs the lineage's network.** The network is not read from the token file, so a testnet2 lineage needs `--network testnet2` each time. Exit 2 naming two networks means the configuration, not the token, diff --git a/src/cli.ts b/src/cli.ts index 7938771..a3a6213 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -92,6 +92,10 @@ program .option('--recipient-key-file ', "file holding the next producer's public key; alternative to --recipient-key") .option('--finalize', 'make this the final revision: seal it and burn the token, so no revision can follow') .option('--quiet', 'do not echo the pending revision to stderr once its journal file is written') + .option( + '--force', + 'for a new lineage, overwrite a file that appears at --token-file meanwhile, or write through a dangling symlink', + ) .option('--network ', 'mainnet or testnet2; or UNICITY_NETWORK (default mainnet)') .option('--gateway ', 'override the gateway URL; or UNICITY_GATEWAY_URL') .option('--api-key ', 'gateway API key; or UNICITY_API_KEY') diff --git a/src/commands/revisionJournal.ts b/src/commands/revisionJournal.ts index c16fbbb..3d89ca6 100644 --- a/src/commands/revisionJournal.ts +++ b/src/commands/revisionJournal.ts @@ -67,7 +67,12 @@ export function pendingRevision( }; } -function hasErrorCode(error: unknown, code: string): boolean { +/** + * @param {unknown} error Thrown value. + * @param {string} code Node error code, such as `ENOENT`. + * @returns {boolean} Whether the error carries that code. + */ +export function hasErrorCode(error: unknown, code: string): boolean { // Not `instanceof Error`: errors from Node's fs need not come from this realm's Error. return typeof error === 'object' && error !== null && (error as NodeJS.ErrnoException).code === code; } diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 419ea35..e924f25 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -1,5 +1,5 @@ import { randomBytes } from 'node:crypto'; -import { rename, rm, writeFile } from 'node:fs/promises'; +import { lstat, rename, rm, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { AggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/AggregatorClient.js'; @@ -14,6 +14,7 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { ICommandContext } from './context.js'; import { + hasErrorCode, IPendingRevision, journalPath, journalStanding, @@ -54,26 +55,59 @@ import { warningLine, } from '../output.js'; +/** + * Explain an exclusive create of a new lineage's token file that found something + * in the way: a file that appeared since the checks, or a symlink to a missing + * file (which looked absent to them). The genesis is certified either way, and the + * same command recovers it, so say where it can be run again. + * + * @param {string} tokenFile Absolute token file path. + * @param {unknown} cause The EEXIST. + * @returns {Promise} A usage error. + */ +async function tokenFileInTheWay(tokenFile: string, cause: unknown): Promise { + const dangling = + (await lstat(tokenFile).then( + (stats) => stats.isSymbolicLink(), + () => false, + )) && + (await stat(tokenFile).then( + () => false, + () => true, + )); + const certified = 'The new lineage is certified; running the same command again recovers it'; + return usageError( + dangling + ? `${tokenFile} is a symlink to a missing file, so the new lineage was not written. ${certified}: ` + + 'pass --force to create the file the symlink points to, or use another --token-file.' + : `${tokenFile} appeared while the new lineage was being certified, and was not overwritten. ${certified} ` + + 'with another --token-file.', + { cause }, + ); +} + /** * Persist a lineage token whose newest revision has already been certified. * - * A new lineage is written with an exclusive create, so a file that appeared - * since the checks is never clobbered. An existing lineage is replaced through a - * temporary file and `rename`, so the previous version stays intact until the new - * one is complete: truncating it in place and then failing would lose the whole - * history, not just the new revision. Whatever goes wrong, the full token is - * printed as hex before the error propagates. + * A new lineage is written with an exclusive create, unless `--force`, so a file + * that appeared since the checks is never clobbered. An existing lineage is + * replaced through a temporary file and `rename`, so the previous version stays + * intact until the new one is complete: truncating it in place and then failing + * would lose the whole history, not just the new revision. Whatever goes wrong, + * the full token is printed as hex before the error propagates. * * @param {string} tokenFile Absolute token file path. * @param {Uint8Array} bytes Encoded token. * @param {boolean} created Whether this is a new lineage. * @param {ICommandContext} context Streams. + * @param {boolean} [force] For a new lineage, overwrite whatever is at the path, or write through a symlink. */ export async function writeRevisionToken( tokenFile: string, bytes: Uint8Array, created: boolean, context: ICommandContext, + force = false, ): Promise { const temporary = path.join( path.dirname(tokenFile), @@ -81,7 +115,7 @@ export async function writeRevisionToken( ); try { if (created) { - await writeFile(tokenFile, bytes, { flag: 'wx' }); + await writeFile(tokenFile, bytes, { flag: force ? 'w' : 'wx' }); } else { await writeFile(temporary, bytes, { flag: 'wx' }); await rename(temporary, tokenFile); @@ -92,6 +126,9 @@ export async function writeRevisionToken( if (!created) { await rm(temporary, { force: true }).catch(() => undefined); } + if (created && hasErrorCode(error, 'EEXIST')) { + throw await tokenFileInTheWay(tokenFile, error); + } throw error; } } @@ -387,7 +424,7 @@ export async function stampRevisionWith( if (recovered) { await assertNotSuperseded(client, trustBase, token, context); } - await writeRevisionToken(config.tokenFile, token.toCBOR(), true, context); + await writeRevisionToken(config.tokenFile, token.toCBOR(), true, context, config.force); if (recovered) { // Not subject to --quiet: without it, two files can pass for two lineages. context.stderr.write(existingLineageNote(token.id.bytes)); diff --git a/src/config.ts b/src/config.ts index 73a2a42..404e8fc 100644 --- a/src/config.ts +++ b/src/config.ts @@ -455,6 +455,7 @@ export interface IStampRevisionFlags extends INetworkFlags { readonly apiKey?: string; readonly file?: string; readonly finalize?: boolean; + readonly force?: boolean; readonly keyFile?: string; readonly quiet?: boolean; readonly recipientKey?: string; @@ -467,6 +468,12 @@ export interface IStampRevisionConfig { readonly allowInsecure: boolean; readonly apiKey: string; readonly digest: Uint8Array; + /** + * When creating a new lineage, overwrite a file that appeared at the token file + * path meanwhile, or write through a symlink to a missing file. Never set with + * an existing token file. + */ + readonly force: boolean; readonly network: ITimestampNetwork; /** Signs the new revision: the genesis reason for a new lineage, the transfer otherwise. */ readonly privateKey: Uint8Array; @@ -622,6 +629,13 @@ export async function resolveStampRevisionConfig( const tokenFile = path.resolve(flags.tokenFile); const exists = await assertTokenFileUsable(tokenFile); + const force = flags.force ?? false; + if (exists && force) { + throw usageError( + `${tokenFile} exists, so this run would append to it. --force only applies when creating a new lineage, ` + + 'and never replaces an existing token file.', + ); + } let tokenBytes: Uint8Array | null = null; if (exists) { try { @@ -638,6 +652,7 @@ export async function resolveStampRevisionConfig( allowInsecure, apiKey, digest, + force, network, privateKey, quiet, diff --git a/tests/unit/ConfigTest.ts b/tests/unit/ConfigTest.ts index 1de245b..cf98b83 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -407,6 +407,17 @@ describe('resolveStampRevisionConfig', () => { expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), quiet: true }, env)).quiet).toBe(true); }); + it('accepts --force for a new lineage, and refuses it for an existing token file', async () => { + expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), env)).force).toBe(false); + expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), force: true }, env)).force).toBe(true); + const tokenFile = path.join(directory, 'doc.lineage'); + await writeFile(tokenFile, 'abcd'); + await expect(resolveStampRevisionConfig(TEST_DIGEST_HEX, { ...base(), force: true }, env)).rejects.toThrow( + `${tokenFile} exists, so this run would append to it. --force only applies when creating a new lineage, ` + + 'and never replaces an existing token file.', + ); + }); + it('records the trust base file, as an absolute path, for messages', async () => { expect((await resolveStampRevisionConfig(TEST_DIGEST_HEX, base(), env)).trustBasePath).toBeNull(); const trustBaseFile = path.join(directory, 'testnet2.json'); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index c7722d6..d7c1a8f 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -1,4 +1,4 @@ -import { readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { lstat, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; @@ -95,6 +95,7 @@ describe('stampRevisionWith', () => { allowInsecure: false, apiKey: 'key', digest: TEST_DIGEST, + force: false, network: { gatewayUrl: 'https://gateway.test', preset: 'testnet2', trustBase: aggregator.rootTrustBase }, privateKey: TEST_PRIVATE_KEY, quiet: false, @@ -506,6 +507,66 @@ describe('stampRevisionWith', () => { ); }); + describe('a token file in the way of a new lineage', () => { + /** Runs `blocker` on the token file path while the genesis is being certified. */ + function blockingClient(blocker: (tokenFile: string) => Promise): StateTransitionClient { + const tokenFile = path.join(directory, 'doc.lineage'); + return new StateTransitionClient({ + getInclusionProof: async (stateId: StateId): Promise => { + await blocker(tokenFile); + return aggregator.getInclusionProof(stateId); + }, + submitCertificationRequest: (data: CertificationData): Promise => + aggregator.submitCertificationRequest(data), + }); + } + + const appear = async (tokenFile: string): Promise => { + await writeFile(tokenFile, 'someone else'); + }; + + it('leaves a file that appeared alone, and says to run again with another --token-file', async () => { + const sink = testContext(); + const attempt = stampRevisionWith(config({}), blockingClient(appear), sink.context); + await expect(attempt).rejects.toThrow( + /doc\.lineage appeared while the new lineage was being certified, and was not overwritten\. .* with another --token-file\.$/, + ); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await readFile(path.join(directory, 'doc.lineage'), 'utf8')).toEqual('someone else'); + expect(sink.stderr()).toContain('the revision was certified'); + + const elsewhere = path.join(directory, 'other.lineage'); + const again = testContext({ json: true }); + expect(await stampRevisionWith(config({ tokenFile: elsewhere }), client, again.context)).toBe(0); + expect(again.json()).toMatchObject({ created: true, recovered: true, revision: '0' }); + }); + + it('overwrites a file that appeared with --force', async () => { + const sink = testContext({ json: true }); + expect(await stampRevisionWith(config({ force: true }), blockingClient(appear), sink.context)).toBe(0); + const token = await Token.fromCBOR(new Uint8Array(await readFile(path.join(directory, 'doc.lineage')))); + expect((await verifyLineage(token, aggregator.rootTrustBase)).status).toEqual('OK'); + }); + + it('says --force writes through a dangling symlink, and it does', async () => { + const tokenFile = path.join(directory, 'doc.lineage'); + const target = path.join(directory, 'target.lineage'); + await symlink(target, tokenFile); + const attempt = stampRevisionWith(config({}), client, testContext().context); + await expect(attempt).rejects.toThrow( + /doc\.lineage is a symlink to a missing file, so the new lineage was not written\. .*: pass --force to create the file the symlink points to, or use another --token-file\.$/, + ); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + + const sink = testContext({ json: true }); + expect(await stampRevisionWith(config({ force: true }), client, sink.context)).toBe(0); + expect(sink.json()).toMatchObject({ created: true, recovered: true }); + expect((await lstat(tokenFile)).isSymbolicLink()).toBe(true); + const token = await Token.fromCBOR(new Uint8Array(await readFile(target))); + expect((await verifyLineage(token, aggregator.rootTrustBase)).status).toEqual('OK'); + }); + }); + describe('networkMismatch', () => { it('accepts a token from the configured network', () => { expect(networkMismatch('/d/doc.lineage', 4, 4, null)).toBeNull(); diff --git a/tests/unit/StampRevisionWriteTest.ts b/tests/unit/StampRevisionWriteTest.ts index 116f490..b74e20e 100644 --- a/tests/unit/StampRevisionWriteTest.ts +++ b/tests/unit/StampRevisionWriteTest.ts @@ -26,11 +26,23 @@ describe('writeRevisionToken', () => { const out = path.join(directory, 'doc.lineage'); await writeFile(out, 'someone else'); const sink = testContext(); - await expect(writeRevisionToken(out, TOKEN, true, sink.context)).rejects.toThrow(/EEXIST/); + await expect(writeRevisionToken(out, TOKEN, true, sink.context)).rejects.toThrow( + /appeared while the new lineage was being certified/, + ); expect(await readFile(out, 'utf8')).toEqual('someone else'); expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); }); + it('overwrites a file in the way of a new lineage with force', async () => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + await writeFile(out, 'someone else'); + const sink = testContext(); + await writeRevisionToken(out, TOKEN, true, sink.context, true); + expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); + expect(sink.stderr()).toEqual(''); + }); + it('prints the token when the directory is gone', async () => { const directory = await tempDir('proof-cli-revision-'); await mkdir(path.join(directory, 'sub')); From 05cc9ef33b5be8c6f8321ed9acc03040d985a18d Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Mon, 16 Nov 2026 14:45:13 +0200 Subject: [PATCH 19/25] Write token and key files durably, never leaving a partial file A new lineage's token file was created in place, so a write that failed partway (ENOSPC, EIO, a kill) left a truncated file; the next run took the append path and failed with "is not a token". An append, and keygen --force, renamed a temporary into place without fsyncing it or the directory, so a power loss could leave an empty file, and the rename replaced a symlink with a regular file and reset the file mode. writeFileDurably writes to a sibling temporary at 0600 when its final mode is to be set, fsyncs it, publishes it, and fsyncs the directory: `create` links it into place, atomic and as exclusive as O_EXCL, with EEXIST naming the target; `replace` renames it over the old file and keeps that file's mode unless one is given. Where hard links are unsupported, `create` falls back to an exclusive create of the name and removes it if the write fails. Symlinks can be followed, so the file at the end of the chain is written and the links kept. stamp-revision uses it for every token write. An append, and --force for a new lineage, write through a symlink at --token-file; a plain new lineage still refuses one. keygen uses it with mode 0600, and never writes through a symlink. An undecodable token file now says to move it away and run the same command again, which recovers the lineage. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- skills/unicity-proof/SKILL.md | 3 + src/commands/durableFile.ts | 195 +++++++++++++++++++++++++++ src/commands/keygen.ts | 76 ++++------- src/commands/stampRevision.ts | 52 +++---- tests/unit/DurableFileTest.ts | 182 +++++++++++++++++++++++++ tests/unit/KeygenTest.ts | 18 ++- tests/unit/StampRevisionTest.ts | 4 +- tests/unit/StampRevisionWriteTest.ts | 39 +++++- 9 files changed, 494 insertions(+), 80 deletions(-) create mode 100644 src/commands/durableFile.ts create mode 100644 tests/unit/DurableFileTest.ts diff --git a/README.md b/README.md index 9c3a147..1c3ddee 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,8 @@ a bare hex line or, with `--json`, as the object's `privateKey`. That field is present on this path only: a key written to a file stays in the file, and the JSON reports its path and public key alone. +`keygen` writes the key to a new file that is 0600 from creation and puts it in place only when complete, so the key is never visible through a wider file. It never writes through a symlink: without `--force` a symlink at `--out` is refused like any existing file, and with `--force` the link itself is replaced. + Or put `UNICITY_PRIVATE_KEY=<64 hex>` in `.env` and every stamp is signed. Two flags control this explicitly: - `--sign` fails with exit code 2 unless a key is configured. Use it in scripts that must never produce an anonymous stamp. @@ -136,7 +138,8 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - Before writing, the command asks the aggregator whether revision 1 exists. If it shows a proof that verifies against the trust base, the lineage has moved on: nothing is written, and the command exits 1, naming the token id, when revision 1 was certified and by whom. Get the current token file from whoever holds the lineage. - If the aggregator cannot be asked, or shows a proof that does not verify, the file is written with a warning. The check can find later revisions but never rule them out: the aggregator issues no proofs of absence. - A new lineage's token file is created exclusively. If a file appears at `--token-file` while the genesis is being certified, it is left alone and the command exits 2; the genesis is printed as hex, and running the same command with another `--token-file` recovers it there. A `--token-file` that is a symlink to a missing file is refused the same way. `--force` overwrites a file that appeared, or creates the file a symlink points to. It only applies to a new lineage: with an existing token file, `--force` is a usage error, because the file would be appended to and never replaced. -- If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. The file is replaced atomically, and on any write failure the full token is printed as hex. +- If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. On any write failure the full token is printed as hex. +- **The token file never holds a partial token.** It is written to a temporary file next to it, fsynced, and only then put in place (linked for a new lineage, renamed over the old file for an append), and the directory is fsynced after that. A failed or interrupted write leaves the previous file, or for a new lineage no file at all. An append keeps the file's mode, and if `--token-file` is a symlink, for example into a shared or synced folder, the file it points to is updated and the link is kept. On a filesystem without hard links, a new lineage is created in place instead and removed again if the write fails; only a crash during that write can leave a partial file. If a token file is not a token, the error says how to recover: move it away and run the same command again. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `..pending` (`.doc.lineage.pending` for `doc.lineage`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. The journal is removed once the token file holds the revision. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. - If the command is interrupted after submitting, running `stamp-revision` again on the same token file recovers the revision from the journal, whatever it is given this time. If the digest and recipient are the same, that completes the command. If not, the recovered revision is still written and echoed to stderr, the requested one is not appended, and the command exits 1. diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index 8100666..fed3a9a 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -81,6 +81,9 @@ without it the proof is gone. the genesis is certified: run the same command with another `--token-file` to recover it. `--force` only overwrites for a new lineage; never use it to "replace" an existing token file (it refuses). +- **Exit 1 saying the token file `is not a token`, with no lineage yet:** an + earlier run may have failed writing it. Move the file away (don't delete it) + and run the same command again; the lineage is recovered. - **Every `stamp-revision` append needs the lineage's network.** The network is not read from the token file, so a testnet2 lineage needs `--network testnet2` each time. Exit 2 naming two networks means the configuration, not the token, diff --git a/src/commands/durableFile.ts b/src/commands/durableFile.ts new file mode 100644 index 0000000..d9b9149 --- /dev/null +++ b/src/commands/durableFile.ts @@ -0,0 +1,195 @@ +import { randomBytes } from 'node:crypto'; +import { chmod, link, lstat, open, readlink, rename, rm, stat } from 'node:fs/promises'; +import path from 'node:path'; + +/** + * The file operations {@link writeFileDurably} needs, so tests can make one fail + * partway. Each is the plain `node:fs/promises` call, except `writeNew`. + */ +export interface IDurableFileSystem { + chmod(file: string, mode: number): Promise; + link(existing: string, file: string): Promise; + lstat(file: string): Promise<{ isSymbolicLink(): boolean }>; + readlink(file: string): Promise; + rename(from: string, to: string): Promise; + rm(file: string, options: { force: boolean }): Promise; + stat(file: string): Promise<{ mode: number }>; + /** Flush a directory's entries; may fail where directories cannot be opened. */ + syncDirectory(directory: string): Promise; + /** Create `file` exclusively with `mode` (subject to the umask), write `data`, fsync, close. */ + writeNew(file: string, data: Uint8Array, mode: number): Promise; +} + +export const NODE_FILE_SYSTEM: IDurableFileSystem = { + chmod, + link, + lstat, + readlink, + rename, + rm, + stat, + syncDirectory: async (directory) => { + const handle = await open(directory, 'r'); + try { + await handle.sync(); + } finally { + await handle.close(); + } + }, + writeNew: async (file, data, mode) => { + const handle = await open(file, 'wx', mode); + try { + await handle.writeFile(data); + await handle.sync(); + } finally { + await handle.close(); + } + }, +}; + +export interface IDurableWriteOptions { + /** + * Set the file to exactly this mode. Without it, a replaced file keeps its + * mode, and a created one gets the default `0666` less the umask. + */ + readonly fileMode?: number; + /** + * Write to the file at the end of a symlink chain at `file`, rather than + * replacing or refusing the symlink itself. The symlink stays. + */ + readonly followSymlinks: boolean; + /** + * `create`: refuse with EEXIST if anything is at the path, even a symlink to a + * missing file, unless `followSymlinks`. `replace`: replace whatever is there. + */ + readonly publish: 'create' | 'replace'; +} + +/** Codes from `link` on a filesystem without hard links. */ +const NO_HARD_LINKS = new Set(['ENOSYS', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM']); + +const MAX_SYMLINK_HOPS = 40; + +function errorCode(error: unknown): unknown { + // Not `instanceof Error`: errors from Node's fs need not come from this realm's Error. + return typeof error === 'object' && error !== null ? (error as NodeJS.ErrnoException).code : undefined; +} + +function fsError(code: string, message: string, file: string, cause?: unknown): NodeJS.ErrnoException { + return Object.assign(new Error(`${code}: ${message}, '${file}'`, { cause }), { code, path: file }); +} + +/** + * @param {IDurableFileSystem} fs File operations. + * @param {string} file Starting path. + * @returns {Promise} The path at the end of the symlink chain at `file`; it need not exist. + */ +async function resolveSymlinks(fs: IDurableFileSystem, file: string): Promise { + let current = file; + for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop += 1) { + const isLink = await fs.lstat(current).then( + (stats) => stats.isSymbolicLink(), + (error: unknown) => { + if (errorCode(error) === 'ENOENT') { + return false; + } + throw error; + }, + ); + if (!isLink) { + return current; + } + current = path.resolve(path.dirname(current), await fs.readlink(current)); + } + throw fsError('ELOOP', 'too many symbolic links encountered', file); +} + +/** + * Write a file so that its name never refers to a partial file, even if the + * process dies midway, and so that the result survives a power loss once this + * returns. + * + * The data goes to a fresh sibling `..`, created at 0600 when + * its final mode is to be set, so it is never readable more widely on the way. + * It is written and fsynced, then published: `create` links it in place, which + * is atomic and refuses an existing name as an exclusive create does; `replace` + * renames it over the old file. Then the directory is fsynced, where the + * platform allows. The temporary is removed whatever happens. + * + * Where the filesystem has no hard links, `create` falls back to an exclusive + * create of the name itself, and removes it again if the write fails. Only a + * crash during that write can then leave a partial file. + * + * @param {string} file Absolute path. + * @param {Uint8Array} data Contents. + * @param {IDurableWriteOptions} options How to publish. + * @param {IDurableFileSystem} [fs] File operations. + * @throws {NodeJS.ErrnoException} EEXIST, carrying `file` as its path, when `create` finds the name taken. + */ +export async function writeFileDurably( + file: string, + data: Uint8Array, + options: IDurableWriteOptions, + fs: IDurableFileSystem = NODE_FILE_SYSTEM, +): Promise { + const target = options.followSymlinks ? await resolveSymlinks(fs, file) : file; + const directory = path.dirname(target); + let mode = options.fileMode; + if (mode === undefined && options.publish === 'replace') { + mode = await fs.stat(target).then( + (stats) => stats.mode & 0o7777, + () => undefined, + ); + } + const temporary = path.join(directory, `.${path.basename(target)}.${randomBytes(8).toString('hex')}`); + try { + await fs.writeNew(temporary, data, mode === undefined ? 0o666 : 0o600); + if (mode !== undefined) { + await fs.chmod(temporary, mode); + } + if (options.publish === 'replace') { + await fs.rename(temporary, target); + } else { + await publishNew(fs, temporary, target, data, mode); + } + } finally { + // Best effort, and never allowed to replace the error that actually matters. + await fs.rm(temporary, { force: true }).catch(() => undefined); + } + await fs.syncDirectory(directory).catch(() => undefined); +} + +async function publishNew( + fs: IDurableFileSystem, + temporary: string, + target: string, + data: Uint8Array, + mode: number | undefined, +): Promise { + try { + await fs.link(temporary, target); + return; + } catch (error) { + if (errorCode(error) === 'EEXIST') { + // `link` reports the temporary as the path; the name that was taken is the target. + throw fsError('EEXIST', 'file already exists', target, error); + } + if (!NO_HARD_LINKS.has(errorCode(error) as string)) { + throw error; + } + } + try { + await fs.writeNew(target, data, mode === undefined ? 0o666 : 0o600); + if (mode !== undefined) { + await fs.chmod(target, mode); + } + } catch (error) { + if (errorCode(error) === 'EEXIST') { + throw fsError('EEXIST', 'file already exists', target, error); + } + // Any other failure came after the exclusive create, or found nothing to remove: + // the name is this run's, and must not be left holding a partial file. + await fs.rm(target, { force: true }).catch(() => undefined); + throw error; + } +} diff --git a/src/commands/keygen.ts b/src/commands/keygen.ts index 1008027..7a96c70 100644 --- a/src/commands/keygen.ts +++ b/src/commands/keygen.ts @@ -1,11 +1,10 @@ -import { randomBytes } from 'node:crypto'; -import { chmod, rename, rm, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { ICommandContext } from './context.js'; +import { writeFileDurably } from './durableFile.js'; import { EXIT_OK } from '../errors.js'; import { keygenJson, keygenText, toJsonLine } from '../output.js'; @@ -17,58 +16,39 @@ export interface IKeygenFlags { const DEFAULT_KEY_FILE = 'unicity-proof.key'; /** - * Write a private key to a path that already holds a file. + * Write a private key file at exactly mode 0600, with {@link writeFileDurably}. * - * Overwriting in place would truncate and fill the existing inode, which keeps - * whatever permissions it already had for the duration of the write: narrowing it - * afterwards is too late, because a reader that opened the file beforehand keeps - * its descriptor across the change, and a failed `chmod` would leave the finished - * key exposed. The key therefore goes to a fresh inode that is 0600 from creation - * and is moved into place with `rename`, which is atomic and never publishes the - * secret through the old inode. + * The key goes to a fresh inode that is 0600 from creation and is moved into + * place, never written into an existing file: overwriting in place would fill an + * inode that keeps whatever permissions it already had for the duration of the + * write, and narrowing it afterwards is too late, because a reader that opened it + * beforehand keeps its descriptor. The explicit mode is also what corrects a + * umask that covers owner bits, which would otherwise leave 0200 or 0000 while + * the summary reports 0600; it cannot widen the file on the way, since a umask + * only removes bits. A symlink at the path is replaced or refused, never written + * through: a key is not written to wherever a link happens to point. * - * This is the opposite choice from `writeCertifiedToken`, deliberately: there, - * staging bought nothing and added ways to fail after a stamp had been billed, - * whereas here it is the only way to never expose the key, and a failed `keygen` - * costs nothing to repeat. `rename` also works on filesystems without hard links. + * Staging is the opposite choice from `writeCertifiedToken`, deliberately: there, + * it bought nothing and added ways to fail after a stamp had been billed, whereas + * here it is the only way to never expose the key, and a failed `keygen` costs + * nothing to repeat. * * @param {string} out Absolute destination path. * @param {string} contents Key file contents. + * @param {boolean} replace Whether an existing file may be replaced; otherwise EEXIST. */ -async function replaceKeyFile(out: string, contents: string): Promise { - const temporary = path.join(path.dirname(out), `.${path.basename(out)}.${randomBytes(8).toString('hex')}`); - try { - await writeKeyFile(temporary, contents); - await rename(temporary, out); - } catch (error) { - // Best effort, and never allowed to replace the error that actually matters. - await rm(temporary, { force: true }).catch(() => undefined); - throw error; - } -} - -/** - * Create a new file holding a private key, at exactly mode 0600. - * - * `writeFile`'s `mode` is masked by the process umask, so a umask that happens to - * cover owner bits yields 0200 or 0000 and leaves a key nothing can read, while - * the summary still reports 0600. The explicit `chmod` corrects that. It cannot - * widen the file past 0600 on the way, because a umask only ever removes bits — - * which is what makes it safe here, unlike narrowing an inode that was already - * public. - * - * @param {string} file Path to create; must not exist. - * @param {string} contents Key file contents. - */ -async function writeKeyFile(file: string, contents: string): Promise { - await writeFile(file, contents, { flag: 'wx', mode: 0o600 }); - await chmod(file, 0o600); +async function writeKeyFile(out: string, contents: string, replace: boolean): Promise { + await writeFileDurably(out, new TextEncoder().encode(contents), { + fileMode: 0o600, + followSymlinks: false, + publish: replace ? 'replace' : 'create', + }); } /** * `keygen`: write a fresh secp256k1 private key as 64 hex characters, mode 0600. - * An existing file is left alone unless `--force`; the EEXIST from `wx` is - * rendered by the shared error mapping. + * An existing file is left alone unless `--force`; the EEXIST is rendered by + * the shared error mapping. * * @param {IKeygenFlags} flags Command flags. * @param {ICommandContext} context Streams. @@ -88,13 +68,7 @@ export async function runKeygen(flags: IKeygenFlags, context: ICommandContext): } const out = path.resolve(flags.out ?? DEFAULT_KEY_FILE); - if (flags.force) { - await replaceKeyFile(out, `${hex}\n`); - } else { - // A fresh file is never wider than 0600, and `wx` is what refuses an existing - // one, so this path needs no staging. - await writeKeyFile(out, `${hex}\n`); - } + await writeKeyFile(out, `${hex}\n`, flags.force ?? false); context.stdout.write(context.json ? toJsonLine(keygenJson(out, publicKey)) : `${keygenText(out, publicKey)}\n`); return EXIT_OK; diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index e924f25..24b02b6 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -1,6 +1,4 @@ -import { randomBytes } from 'node:crypto'; -import { lstat, rename, rm, stat, writeFile } from 'node:fs/promises'; -import path from 'node:path'; +import { lstat, stat } from 'node:fs/promises'; import { AggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/AggregatorClient.js'; import { RootTrustBase } from '@unicitylabs/state-transition-sdk/lib/api/bft/RootTrustBase.js'; @@ -13,6 +11,7 @@ import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/trans import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { ICommandContext } from './context.js'; +import { IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from './durableFile.js'; import { hasErrorCode, IPendingRevision, @@ -87,20 +86,24 @@ async function tokenFileInTheWay(tokenFile: string, cause: unknown): Promise { - const temporary = path.join( - path.dirname(tokenFile), - `.${path.basename(tokenFile)}.${randomBytes(8).toString('hex')}`, - ); + const exclusive = created && !force; try { - if (created) { - await writeFile(tokenFile, bytes, { flag: force ? 'w' : 'wx' }); - } else { - await writeFile(temporary, bytes, { flag: 'wx' }); - await rename(temporary, tokenFile); - } + await writeFileDurably( + tokenFile, + bytes, + { followSymlinks: !exclusive, publish: exclusive ? 'create' : 'replace' }, + fs, + ); } catch (error) { // First, before anything awaited, so nothing can get between the error and the recovered bytes. context.stderr.write(revisionRecoveryLines(bytes)); - if (!created) { - await rm(temporary, { force: true }).catch(() => undefined); - } - if (created && hasErrorCode(error, 'EEXIST')) { + if (exclusive && hasErrorCode(error, 'EEXIST')) { throw await tokenFileInTheWay(tokenFile, error); } throw error; @@ -432,7 +430,11 @@ export async function stampRevisionWith( } else { const decoded = await decodeToken(tokenBytesFromInput(config.tokenBytes)); if (decoded.token === null) { - throw new CliError(`${config.tokenFile} is ${decoded.error}.`, EXIT_VERIFICATION_FAILED); + throw new CliError( + `${config.tokenFile} is ${decoded.error}. If an earlier stamp-revision run failed while creating a new ` + + 'lineage, move this file away and run the same command again: the lineage is recovered.', + EXIT_VERIFICATION_FAILED, + ); } // Before the journal is read: a journal is only acted on against the right network. const mismatch = networkMismatch( diff --git a/tests/unit/DurableFileTest.ts b/tests/unit/DurableFileTest.ts new file mode 100644 index 0000000..88c890d --- /dev/null +++ b/tests/unit/DurableFileTest.ts @@ -0,0 +1,182 @@ +import { chmod, lstat, readdir, readFile, readlink, stat, symlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from '../../src/commands/durableFile.js'; +import { tempDir } from '../support/fixtures.js'; + +const DATA = new TextEncoder().encode('new contents\n'); + +function errno(code: string): NodeJS.ErrnoException { + return Object.assign(new Error(code), { code }); +} + +/** The real file system, with `writeNew` writing only the first three bytes of `fail` before failing. */ +function failingWrite(fail: (file: string) => boolean): IDurableFileSystem { + return { + ...NODE_FILE_SYSTEM, + writeNew: async (file, data, mode): Promise => { + if (!fail(file)) { + return NODE_FILE_SYSTEM.writeNew(file, data, mode); + } + await NODE_FILE_SYSTEM.writeNew(file, data.subarray(0, 3), mode); + throw errno('ENOSPC'); + }, + }; +} + +const noLink = (): Promise => Promise.reject(errno('EPERM')); + +/** The real file system on a filesystem without hard links. */ +const NO_LINKS: IDurableFileSystem = { ...NODE_FILE_SYSTEM, link: noLink }; + +describe('writeFileDurably', () => { + let directory: string; + let file: string; + + beforeEach(async () => { + directory = await tempDir('proof-cli-durable-'); + file = path.join(directory, 'doc.lineage'); + }); + + describe('create', () => { + const create = { followSymlinks: false, publish: 'create' } as const; + + it('writes the file and leaves no temporary behind', async () => { + await writeFileDurably(file, DATA, create); + expect(new Uint8Array(await readFile(file))).toEqual(DATA); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('refuses an existing file with EEXIST naming it, not the temporary', async () => { + await writeFile(file, 'someone else'); + await expect(writeFileDurably(file, DATA, create)).rejects.toMatchObject({ code: 'EEXIST', path: file }); + expect(await readFile(file, 'utf8')).toEqual('someone else'); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('refuses a symlink to a missing file', async () => { + await symlink(path.join(directory, 'target'), file); + await expect(writeFileDurably(file, DATA, create)).rejects.toMatchObject({ code: 'EEXIST', path: file }); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('creates the file a symlink chain points to when following symlinks, and keeps the links', async () => { + const target = path.join(directory, 'sub-target'); + await symlink('middle', file); + await symlink(target, path.join(directory, 'middle')); + await writeFileDurably(file, DATA, { ...create, followSymlinks: true }); + expect(new Uint8Array(await readFile(target))).toEqual(DATA); + expect(await readlink(file)).toEqual('middle'); + }); + + it('never leaves a partial file at the name when the write fails', async () => { + await expect( + writeFileDurably( + file, + DATA, + create, + failingWrite(() => true), + ), + ).rejects.toMatchObject({ + code: 'ENOSPC', + }); + expect(await readdir(directory)).toEqual([]); + }); + + it('creates the file itself without hard links', async () => { + await writeFileDurably(file, DATA, { ...create, fileMode: 0o600 }, NO_LINKS); + expect(new Uint8Array(await readFile(file))).toEqual(DATA); + expect((await stat(file)).mode & 0o777).toBe(0o600); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('without hard links, still refuses an existing file and removes a partial one', async () => { + await writeFile(file, 'someone else'); + await expect(writeFileDurably(file, DATA, create, NO_LINKS)).rejects.toMatchObject({ + code: 'EEXIST', + path: file, + }); + expect(await readFile(file, 'utf8')).toEqual('someone else'); + + const other = path.join(directory, 'other.lineage'); + const failing = { ...failingWrite((name) => name === other), link: noLink }; + await expect(writeFileDurably(other, DATA, create, failing)).rejects.toMatchObject({ code: 'ENOSPC' }); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + }); + + describe('replace', () => { + const replace = { followSymlinks: true, publish: 'replace' } as const; + + it('keeps the old file intact when the write fails', async () => { + await writeFile(file, 'old'); + await expect( + writeFileDurably( + file, + DATA, + replace, + failingWrite(() => true), + ), + ).rejects.toMatchObject({ + code: 'ENOSPC', + }); + expect(await readFile(file, 'utf8')).toEqual('old'); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it("keeps the file's mode", async () => { + await writeFile(file, 'old'); + await chmod(file, 0o640); + await writeFileDurably(file, DATA, replace); + expect(new Uint8Array(await readFile(file))).toEqual(DATA); + expect((await stat(file)).mode & 0o777).toBe(0o640); + }); + + it('sets an explicit mode instead, whatever the old one was', async () => { + await writeFile(file, 'old', { mode: 0o644 }); + await writeFileDurably(file, DATA, { ...replace, fileMode: 0o600 }); + expect((await stat(file)).mode & 0o777).toBe(0o600); + }); + + it('writes through a symlink, which keeps pointing at the file', async () => { + const shared = await tempDir('proof-cli-durable-shared-'); + const target = path.join(shared, 'doc.lineage'); + await writeFile(target, 'old'); + await chmod(target, 0o640); + await symlink(target, file); + await writeFileDurably(file, DATA, replace); + expect((await lstat(file)).isSymbolicLink()).toBe(true); + expect(new Uint8Array(await readFile(target))).toEqual(DATA); + expect((await stat(target)).mode & 0o777).toBe(0o640); + expect(await readdir(shared)).toEqual(['doc.lineage']); + }); + + it('replaces the symlink itself when not following symlinks', async () => { + const target = path.join(directory, 'target'); + await writeFile(target, 'old'); + await symlink(target, file); + await writeFileDurably(file, DATA, { ...replace, followSymlinks: false }); + expect((await lstat(file)).isSymbolicLink()).toBe(false); + expect(await readFile(target, 'utf8')).toEqual('old'); + }); + + it('fails on a symlink loop', async () => { + await symlink('doc.lineage', file); + await expect(writeFileDurably(file, DATA, replace)).rejects.toMatchObject({ code: 'ELOOP', path: file }); + }); + }); + + it('syncs the directory the file ends up in, and gets by where it cannot', async () => { + const synced: string[] = []; + const recording: IDurableFileSystem = { + ...NODE_FILE_SYSTEM, + syncDirectory: (dir) => { + synced.push(dir); + return Promise.reject(errno('EISDIR')); + }, + }; + await writeFileDurably(file, DATA, { followSymlinks: false, publish: 'create' }, recording); + expect(synced).toEqual([directory]); + expect(new Uint8Array(await readFile(file))).toEqual(DATA); + }); +}); diff --git a/tests/unit/KeygenTest.ts b/tests/unit/KeygenTest.ts index 775ba5b..e463bf2 100644 --- a/tests/unit/KeygenTest.ts +++ b/tests/unit/KeygenTest.ts @@ -1,4 +1,4 @@ -import { chmod, readdir, readFile, stat, writeFile } from 'node:fs/promises'; +import { chmod, lstat, readdir, readFile, stat, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { runKeygen } from '../../src/commands/keygen.js'; @@ -38,6 +38,22 @@ describe('runKeygen under a umask that masks owner bits', () => { }); }); +describe('runKeygen and symlinks', () => { + it('refuses a symlink without --force, and replaces the link, not its target, with it', async () => { + const directory = await tempDir('proof-cli-keygen-link-'); + const target = path.join(directory, 'target'); + await writeFile(target, 'placeholder\n'); + const out = path.join(directory, 'link.key'); + await symlink(target, out); + await expect(runKeygen({ out }, testContext().context)).rejects.toMatchObject({ code: 'EEXIST', path: out }); + await runKeygen({ force: true, out }, testContext().context); + expect((await lstat(out)).isSymbolicLink()).toBe(false); + expect((await stat(out)).mode & 0o777).toBe(0o600); + expect(await readFile(target, 'utf8')).toEqual('placeholder\n'); + expect((await readdir(directory)).sort()).toEqual(['link.key', 'target']); + }); +}); + describe('runKeygen when the staged write cannot complete', () => { let directory: string; diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index d7c1a8f..b83a4c0 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -596,7 +596,9 @@ describe('stampRevisionWith', () => { client, testContext().context, ); - await expect(attempt).rejects.toThrow(/is not a token/); + await expect(attempt).rejects.toThrow( + /is not a token.*\. If an earlier stamp-revision run failed while creating a new lineage, move this file away and run the same command again: the lineage is recovered\.$/, + ); expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_VERIFICATION_FAILED); }); }); diff --git a/tests/unit/StampRevisionWriteTest.ts b/tests/unit/StampRevisionWriteTest.ts index b74e20e..74bda43 100644 --- a/tests/unit/StampRevisionWriteTest.ts +++ b/tests/unit/StampRevisionWriteTest.ts @@ -1,8 +1,9 @@ -import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'; +import { chmod, lstat, mkdir, readdir, readFile, stat, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { NODE_FILE_SYSTEM } from '../../src/commands/durableFile.js'; import { writeRevisionToken } from '../../src/commands/stampRevision.js'; import { testContext } from '../support/context.js'; import { tempDir } from '../support/fixtures.js'; @@ -43,6 +44,42 @@ describe('writeRevisionToken', () => { expect(sink.stderr()).toEqual(''); }); + it('appends through a symlink, keeping the link and the mode', async () => { + const directory = await tempDir('proof-cli-revision-'); + const shared = await tempDir('proof-cli-revision-shared-'); + const target = path.join(shared, 'doc.lineage'); + await writeFile(target, 'old'); + await chmod(target, 0o640); + const out = path.join(directory, 'doc.lineage'); + await symlink(target, out); + await writeRevisionToken(out, TOKEN, false, testContext().context); + expect((await lstat(out)).isSymbolicLink()).toBe(true); + expect(new Uint8Array(await readFile(target))).toEqual(TOKEN); + expect((await stat(target)).mode & 0o777).toBe(0o640); + }); + + it.each([ + ['a new lineage', true, []], + ['an append', false, ['doc.lineage']], + ])('leaves no partial token when writing %s fails, and prints the token', async (_, created, left) => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + if (!created) { + await writeFile(out, 'old'); + } + const failing = { + ...NODE_FILE_SYSTEM, + writeNew: async (file: string, data: Uint8Array, mode: number): Promise => { + await NODE_FILE_SYSTEM.writeNew(file, data.subarray(0, 2), mode); + throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + }, + }; + const sink = testContext(); + await expect(writeRevisionToken(out, TOKEN, created, sink.context, false, failing)).rejects.toThrow(/ENOSPC/); + expect(await readdir(directory)).toEqual(left); + expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); + }); + it('prints the token when the directory is gone', async () => { const directory = await tempDir('proof-cli-revision-'); await mkdir(path.join(directory, 'sub')); From d54593cc61a285cb4f9bfb989b137d85dcc243bf Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 17 Nov 2026 00:31:19 +0200 Subject: [PATCH 20/25] Keep a journal until its outcome is known, and catch conflicts after SUCCESS Review on PR #16: - aggregator-go answers SUCCESS to a repeat for a state whose first request is still waiting for its round, then certifies the first and drops the repeat. certifyTransaction looked up a conflict only after STATE_ID_EXISTS, so the repeat failed with the SDK's plain TRANSACTION_HASH_MISMATCH. It now looks after any failure but a timeout, so the result is ALREADY_CERTIFIED. - A re-run deleted an earlier run's journal as soon as its revision was not certified yet, although its request could still be. Journals are now one per transfer, `...pending`, and one is removed only once its outcome is known: the token file holds its revision, or a verified proof shows its slot holds another transfer. Open ones are listed on stderr even with --quiet, and recovered when their revision turns out to be certified. - writeJournal removed the file on any failure, including the EEXIST of a journal another run had created. It now removes only what it created, and accepts an existing journal for the same transfer. - The conflict check verified the other transaction against this one's expiresAt; it now uses the deadline recorded in the proof. - keygen staged even a fresh key in a temporary file, which a crash could leave as a hidden second copy. A fresh key is again written in place, now through writeFileDurably's createInPlace, with an fsync. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- skills/unicity-proof/SKILL.md | 4 +- src/commands/durableFile.ts | 34 ++++- src/commands/keygen.ts | 30 ++--- src/commands/revisionJournal.ts | 83 +++++++++++-- src/commands/stampRevision.ts | 145 +++++++++++++++------- src/lib/TimestampClient.ts | 26 ++-- src/output.ts | 12 +- tests/unit/DurableFileTest.ts | 43 +++++++ tests/unit/RevisionJournalTest.ts | 66 ++++++++++ tests/unit/StampRevisionTest.ts | 186 +++++++++++++++++++++++++++- tests/unit/lib/LineageClientTest.ts | 26 ++++ 12 files changed, 574 insertions(+), 85 deletions(-) create mode 100644 tests/unit/RevisionJournalTest.ts diff --git a/README.md b/README.md index 1c3ddee..9d94ae8 100644 --- a/README.md +++ b/README.md @@ -141,9 +141,11 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. On any write failure the full token is printed as hex. - **The token file never holds a partial token.** It is written to a temporary file next to it, fsynced, and only then put in place (linked for a new lineage, renamed over the old file for an append), and the directory is fsynced after that. A failed or interrupted write leaves the previous file, or for a new lineage no file at all. An append keeps the file's mode, and if `--token-file` is a symlink, for example into a shared or synced folder, the file it points to is updated and the link is kept. On a filesystem without hard links, a new lineage is created in place instead and removed again if the write fails; only a crash during that write can leave a partial file. If a token file is not a token, the error says how to recover: move it away and run the same command again. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. -- **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `..pending` (`.doc.lineage.pending` for `doc.lineage`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. The journal is removed once the token file holds the revision. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. +- **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `...pending`, where the tag is the first 16 hex digits of the transfer's SHA-256 (for example `.doc.lineage.3f2a9c0e1b7d4a65.pending`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. A journal is removed only once its outcome is known: when the token file holds its revision, or when a proof that verifies shows its revision's slot holds another transfer. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. - If the command is interrupted after submitting, running `stamp-revision` again on the same token file recovers the revision from the journal, whatever it is given this time. If the digest and recipient are the same, that completes the command. If not, the recovered revision is still written and echoed to stderr, the requested one is not appended, and the command exits 1. - Without the journal, the same command with the same file, key, digest and recipient still recovers the revision, because the state mask of each step is derived from the producer's key and the spent state. With any other digest or recipient it exits 1, saying the revision was already certified with different content, and echoes what it tried to stderr even with `--quiet`. Only the interrupted run's digest and recipient can recover it then, which is what the echo is for. + - A revision that an earlier run submitted but that is not certified yet may still be: the aggregator can certify a request that was waiting for its round. Its journal is kept, and listed on stderr even with `--quiet`, and this run's revision is journaled beside it. Whichever is certified is written to the token file, and the other journals for that revision are then removed. A run that is interrupted again leaves every journal in place for the next one. + - Two runs that journal the same transfer share its journal. A journal with the same name and other content stops the command with exit 2, and nothing is removed that the command did not create. - A journal the command cannot place (for another lineage, for a later revision than the token file holds, or unreadable) stops it with exit 2 and is left alone. - A new lineage needs no journal: its genesis is derived from its inputs, and running it again with the same file, key, digest and recipient recovers it (see above). - In `--json` output, `recovered` is true when an earlier run had already certified the revision and this run only recovered it; the text output marks such a revision `(recovered)`. diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index fed3a9a..c6ca76f 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -65,7 +65,9 @@ without it the proof is gone. Do not re-stamp. - **An interrupted `stamp-revision` append is recoverable; do not improvise.** Run `stamp-revision` again on the same token file: it recovers the revision - from the `..pending` journal next to the token file. Never delete that + from the `...pending` journals next to the token file. There can be + more than one: a revision an earlier run submitted keeps its journal until its + outcome is known, and stderr lists it as `not certified yet`. Never delete a journal by hand; until the token file holds the revision, it is the only record of what was certified. Exit 1 with `already certified with different content` means an earlier run certified something else for this revision: diff --git a/src/commands/durableFile.ts b/src/commands/durableFile.ts index d9b9149..bca29ea 100644 --- a/src/commands/durableFile.ts +++ b/src/commands/durableFile.ts @@ -60,9 +60,12 @@ export interface IDurableWriteOptions { readonly followSymlinks: boolean; /** * `create`: refuse with EEXIST if anything is at the path, even a symlink to a - * missing file, unless `followSymlinks`. `replace`: replace whatever is there. + * missing file, unless `followSymlinks`. `createInPlace`: the same, but written + * directly under its name with no temporary: a crash during the write can leave + * a partial file there, but never a second copy anywhere else. `replace`: + * replace whatever is there. */ - readonly publish: 'create' | 'replace'; + readonly publish: 'create' | 'createInPlace' | 'replace'; } /** Codes from `link` on a filesystem without hard links. */ @@ -118,7 +121,9 @@ async function resolveSymlinks(fs: IDurableFileSystem, file: string): Promise { const target = options.followSymlinks ? await resolveSymlinks(fs, file) : file; const directory = path.dirname(target); + if (options.publish === 'createInPlace') { + await createInPlace(fs, target, data, options.fileMode); + await fs.syncDirectory(directory).catch(() => undefined); + return; + } let mode = options.fileMode; if (mode === undefined && options.publish === 'replace') { mode = await fs.stat(target).then( @@ -178,6 +188,24 @@ async function publishNew( throw error; } } + await createInPlace(fs, target, data, mode); +} + +/** + * An exclusive create of the name itself, written, fsynced and set to `mode`; + * removed again if anything after the create fails. + * + * @param {IDurableFileSystem} fs File operations. + * @param {string} target Path to create. + * @param {Uint8Array} data Contents. + * @param {number|undefined} mode Exact mode, or undefined for the default less the umask. + */ +async function createInPlace( + fs: IDurableFileSystem, + target: string, + data: Uint8Array, + mode: number | undefined, +): Promise { try { await fs.writeNew(target, data, mode === undefined ? 0o666 : 0o600); if (mode !== undefined) { diff --git a/src/commands/keygen.ts b/src/commands/keygen.ts index 7a96c70..198fa37 100644 --- a/src/commands/keygen.ts +++ b/src/commands/keygen.ts @@ -18,20 +18,22 @@ const DEFAULT_KEY_FILE = 'unicity-proof.key'; /** * Write a private key file at exactly mode 0600, with {@link writeFileDurably}. * - * The key goes to a fresh inode that is 0600 from creation and is moved into - * place, never written into an existing file: overwriting in place would fill an - * inode that keeps whatever permissions it already had for the duration of the - * write, and narrowing it afterwards is too late, because a reader that opened it - * beforehand keeps its descriptor. The explicit mode is also what corrects a - * umask that covers owner bits, which would otherwise leave 0200 or 0000 while - * the summary reports 0600; it cannot widen the file on the way, since a umask - * only removes bits. A symlink at the path is replaced or refused, never written - * through: a key is not written to wherever a link happens to point. + * A fresh file is created directly under its name, at 0600 from creation, and + * fsynced. Staging it in a temporary file would let a crash leave a hidden second + * copy of the key next to `--out`, easy to miss when the key is later moved or + * deleted; a partial key at `--out` instead fails loudly when it is used. * - * Staging is the opposite choice from `writeCertifiedToken`, deliberately: there, - * it bought nothing and added ways to fail after a stamp had been billed, whereas - * here it is the only way to never expose the key, and a failed `keygen` costs - * nothing to repeat. + * Replacing an existing file is staged: the key goes to a fresh 0600 inode that is + * moved into place, never written into the old one, which keeps whatever + * permissions it already had for the duration of the write; narrowing it + * afterwards is too late, because a reader that opened it beforehand keeps its + * descriptor. + * + * Either way the explicit mode also corrects a umask that covers owner bits, which + * would otherwise leave 0200 or 0000 while the summary reports 0600; it cannot + * widen the file on the way, since a umask only removes bits. A symlink at the + * path is replaced or refused, never written through: a key is not written to + * wherever a link happens to point. * * @param {string} out Absolute destination path. * @param {string} contents Key file contents. @@ -41,7 +43,7 @@ async function writeKeyFile(out: string, contents: string, replace: boolean): Pr await writeFileDurably(out, new TextEncoder().encode(contents), { fileMode: 0o600, followSymlinks: false, - publish: replace ? 'replace' : 'create', + publish: replace ? 'replace' : 'createInPlace', }); } diff --git a/src/commands/revisionJournal.ts b/src/commands/revisionJournal.ts index 3d89ca6..a20a174 100644 --- a/src/commands/revisionJournal.ts +++ b/src/commands/revisionJournal.ts @@ -1,4 +1,5 @@ -import { open, readFile, rm } from 'node:fs/promises'; +import { createHash } from 'node:crypto'; +import { open, readdir, readFile, rm } from 'node:fs/promises'; import path from 'node:path'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; @@ -37,12 +38,45 @@ interface IJournalJson { readonly version: typeof JOURNAL_VERSION; } +const JOURNAL_SUFFIX = '.pending'; + /** + * One journal per transaction, so that two candidates for the same revision, from + * runs with different inputs, can be kept side by side until one is certified. + * * @param {string} tokenFile Absolute token file path. - * @returns {string} The journal next to it: `..pending` in the same directory. + * @param {Uint8Array} transaction The journaled transfer, CBOR-encoded. + * @returns {string} Its journal next to the token file: `...pending`. */ -export function journalPath(tokenFile: string): string { - return path.join(path.dirname(tokenFile), `.${path.basename(tokenFile)}.pending`); +export function journalPath(tokenFile: string, transaction: Uint8Array): string { + const tag = createHash('sha256').update(transaction).digest('hex').slice(0, 16); + return path.join(path.dirname(tokenFile), `.${path.basename(tokenFile)}.${tag}${JOURNAL_SUFFIX}`); +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Every journal next to the token file, in name order. + * + * @param {string} tokenFile Absolute token file path. + * @returns {Promise} Journal paths. + * @throws {CliError} If the directory cannot be listed. + */ +export async function findJournals(tokenFile: string): Promise { + const directory = path.dirname(tokenFile); + const pattern = new RegExp(`^\\.${escapeRegExp(path.basename(tokenFile))}\\.[0-9a-f]{16}\\.pending$`); + let names: string[]; + try { + names = await readdir(directory); + } catch (error) { + throw usageError(`Cannot list ${directory} to look for journals of ${tokenFile}.`, { cause: error }); + } + return names + .filter((name) => pattern.test(name)) + .sort() + .map((name) => path.join(directory, name)); } /** @@ -77,16 +111,33 @@ export function hasErrorCode(error: unknown, code: string): boolean { return typeof error === 'object' && error !== null && (error as NodeJS.ErrnoException).code === code; } +function samePending(a: IPendingRevision, b: IPendingRevision): boolean { + return ( + a.revision === b.revision && + areUint8ArraysEqual(a.digest, b.digest) && + areUint8ArraysEqual(a.tokenId, b.tokenId) && + areUint8ArraysEqual(a.transaction, b.transaction) && + (a.nextProducer === null + ? b.nextProducer === null + : b.nextProducer !== null && areUint8ArraysEqual(a.nextProducer, b.nextProducer)) + ); +} + /** * Write the journal durably, before the revision is submitted: an exclusive * create, then an fsync of the file and, where the platform allows, of its * directory, so a crash cannot leave the name pointing at nothing. * + * A journal that is already there, for the same transfer, is another run's record + * of the very request this run is about to make, and is used as it is. Anything + * this call did not create is never removed. + * * @param {string} file Journal path. * @param {IPendingRevision} pending What to record. - * @throws {CliError} If the journal cannot be written; nothing has been submitted then. + * @returns {Promise} True if this call created the journal; false if it was already there. + * @throws {CliError} If the journal cannot be written, or holds something else; nothing has been submitted then. */ -export async function writeJournal(file: string, pending: IPendingRevision): Promise { +export async function writeJournal(file: string, pending: IPendingRevision): Promise { const json: IJournalJson = { digest: HexConverter.encode(pending.digest), format: JOURNAL_FORMAT, @@ -96,8 +147,24 @@ export async function writeJournal(file: string, pending: IPendingRevision): Pro transaction: HexConverter.encode(pending.transaction), version: JOURNAL_VERSION, }; + let handle; + try { + handle = await open(file, 'wx'); + } catch (error) { + if (hasErrorCode(error, 'EEXIST')) { + const existing = await readJournal(file); + if (existing !== null && samePending(existing, pending)) { + return false; + } + throw usageError( + `The journal ${file} already exists with other content; nothing was submitted. ` + + 'Move it away if it is not needed.', + { cause: error }, + ); + } + throw usageError(`Cannot write the journal ${file}; nothing was submitted.`, { cause: error }); + } try { - const handle = await open(file, 'wx'); try { await handle.writeFile(`${JSON.stringify(json, null, 2)}\n`); await handle.sync(); @@ -105,6 +172,7 @@ export async function writeJournal(file: string, pending: IPendingRevision): Pro await handle.close(); } } catch (error) { + // This call created the file, so it is this call's to remove. await rm(file, { force: true }).catch(() => undefined); throw usageError(`Cannot write the journal ${file}; nothing was submitted.`, { cause: error }); } @@ -118,6 +186,7 @@ export async function writeJournal(file: string, pending: IPendingRevision): Pro } catch { // Not every platform can open or sync a directory; the file itself is synced. } + return true; } /** diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 24b02b6..e133b6d 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -13,6 +13,7 @@ import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConv import { ICommandContext } from './context.js'; import { IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from './durableFile.js'; import { + findJournals, hasErrorCode, IPendingRevision, journalPath, @@ -178,18 +179,36 @@ interface IAppendOutcome { readonly token: Token; } +/** A journal for the token file's next revision, read and decoded. */ +interface IJournalEntry { + readonly file: string; + readonly pending: IPendingRevision; + readonly transaction: TransferTransaction; +} + /** * Append the requested revision, journaling it first, so that a run interrupted * after certification can be recovered by the next one. * - * - A journal left by an earlier run is dealt with first. If its revision was - * certified, it is written to the token file; if it was not, the journal is - * dropped, but kept in memory in case it is certified while this run is going. + * Journals are per transfer, and one is removed only once its outcome is known: + * when the token file holds its revision, or when the slot it would fill is shown, + * by a proof that verifies, to hold another transfer. "Not certified yet" is not an + * outcome: aggregator-go can still certify a request that was waiting for its round. + * + * - Journals left by earlier runs are dealt with first. Those whose revision the + * token file holds are removed. Each one for the next revision is looked up; one + * that was certified is written to the token file, and every other journal for + * that revision removed. Those whose slot holds another transfer are removed. + * The rest are kept and listed on stderr whatever `--quiet` says. * - The requested revision is then journaled, echoed to stderr unless `--quiet`, - * submitted, written to the token file, and the journal removed. - * - If its slot turns out to be taken (`ALREADY_CERTIFIED`), the journal is - * removed, since it was never certified, and the revision is echoed whatever - * `--quiet` says, so the user can see what this run tried. + * and submitted. Once it is certified, the token file is written and every + * journal for the revision removed: none of the others can be certified now. + * - If its slot turns out to be taken (`ALREADY_CERTIFIED`), its journal is + * removed and the revision echoed whatever `--quiet` says, so the user can see + * what this run tried; then the kept journals are looked up again, since one of + * them may be what took the slot. + * - On a refusal, only a journal this run created is removed; on a timeout or any + * other failure, every journal stays. * * @param {IStampRevisionConfig} config Resolved configuration. * @param {StateTransitionClient} client Aggregator client. @@ -206,52 +225,88 @@ async function appendJournaled( token: Token, ): Promise { const trustBase = config.network.trustBase; - const journalFile = journalPath(config.tokenFile); - // Before the journal is acted on, in either direction. + // Before any journal is acted on, in either direction. await assertValidLineage(token, trustBase); - // A recovered revision is written and its journal removed, and then either it was - // the revision asked for, or the request cannot go ahead. - const settle = async ( - pending: IPendingRevision, - recovered: Token, - transaction: TransferTransaction, - ): Promise => { + // Every journal still kept for the next revision, this run's own included once written. + const kept = new Map(); + const removeKept = async (): Promise => { + for (const file of kept.keys()) { + await removeJournal(file); + } + kept.clear(); + }; + + // A recovered revision fills the slot, so it is written and every journal for its + // revision removed; then either it was the revision asked for, or the request + // cannot go ahead. + const settle = async (entry: IJournalEntry, recovered: Token): Promise => { await writeRevisionToken(config.tokenFile, recovered.toCBOR(), false, context); - await removeJournal(journalFile); - if (await isSameRevision(transaction, pending.revision, config.digest, config.recipientKey)) { - context.stderr.write(recoveredRevisionLine(pending.revision, journalFile)); + await removeJournal(entry.file); + await removeKept(); + if (await isSameRevision(entry.transaction, entry.pending.revision, config.digest, config.recipientKey)) { + context.stderr.write(recoveredRevisionLine(entry.pending.revision, entry.file)); return { recovered: true, signer: currentProducerKey(token) as Uint8Array, token: recovered }; } - writePending(context, pending, journalFile, 'recovered'); - throw recoveredOtherRevision(pending.revision, recovered, config.tokenFile); + writePending(context, entry.pending, entry.file, 'recovered'); + throw recoveredOtherRevision(entry.pending.revision, recovered, config.tokenFile); }; - let unconfirmed: { pending: IPendingRevision; transaction: TransferTransaction } | null = null; - const earlier = await readJournal(journalFile); - if (earlier !== null) { - const standing = await journalStanding(journalFile, earlier, token, config.tokenFile); - if (standing.kind === 'next') { - let recovered: Token | null = null; + // Look up each kept journal: settle the one that was certified, and drop those + // whose slot is shown to hold another transfer. With `tolerant`, a failed lookup + // keeps the journal instead of failing the run. + const recoverKept = async (tolerant: boolean): Promise => { + for (const entry of [...kept.values()]) { + let recovered: Token | null; try { - recovered = await recoverRevision(client, trustBase, token, standing.transaction, options); + recovered = await recoverRevision(client, trustBase, token, entry.transaction, options); } catch (error) { - // Its slot holds another transfer: the journaled one was never certified. - if (!(error instanceof LineageError && error.code === 'ALREADY_CERTIFIED')) { - throw error; + if (error instanceof LineageError && error.code === 'ALREADY_CERTIFIED') { + // Its slot holds another transfer, shown by a proof that verifies: it never will be certified. + kept.delete(entry.file); + await removeJournal(entry.file); + continue; + } + if (tolerant) { + continue; } + throw error; } if (recovered !== null) { - return settle(earlier, recovered, standing.transaction); + kept.delete(entry.file); + return settle(entry, recovered); } - unconfirmed = { pending: earlier, transaction: standing.transaction }; } - await removeJournal(journalFile); + return null; + }; + + for (const file of await findJournals(config.tokenFile)) { + const pending = await readJournal(file); + if (pending === null) { + continue; + } + const standing = await journalStanding(file, pending, token, config.tokenFile); + if (standing.kind === 'written') { + await removeJournal(file); + } else { + kept.set(file, { file, pending, transaction: standing.transaction }); + } + } + const earlier = await recoverKept(false); + if (earlier !== null) { + return earlier; } const prepared = await prepareRevision(token, trustBase, config.digest, config.privateKey, config.recipientKey); const pending = pendingRevision(token, prepared, config.digest, config.recipientKey); - await writeJournal(journalFile, pending); + const journalFile = journalPath(config.tokenFile, pending.transaction); + // An earlier run's journal for this very transfer is this run's journal too. + kept.delete(journalFile); + for (const entry of kept.values()) { + // Not subject to --quiet: this is the only notice that an earlier run's revision is still open. + writePending(context, entry.pending, entry.file, 'unresolved'); + } + const created = await writeJournal(journalFile, pending); if (!config.quiet) { writePending(context, pending, journalFile, 'submitting'); } @@ -267,19 +322,18 @@ async function appendJournaled( }); } catch (error) { if (error instanceof StampError) { - // Refused outright: nothing was certified. - await removeJournal(journalFile); + // Refused outright: this request certified nothing. A journal an earlier run + // wrote for the same transfer stays, since that run's request was a separate one. + if (created) { + await removeJournal(journalFile); + } } else if (error instanceof LineageError && error.code === 'ALREADY_CERTIFIED') { await removeJournal(journalFile); writePending(context, pending, journalFile, 'rejected'); - if (unconfirmed !== null) { - // The earlier run's revision was still waiting for its round when this run looked. - const recovered = await recoverRevision(client, trustBase, token, unconfirmed.transaction, options).catch( - () => null, - ); - if (recovered !== null) { - return settle(unconfirmed.pending, recovered, unconfirmed.transaction); - } + // Another transfer holds the slot; it may be one an earlier run journaled. + const recovered = await recoverKept(true); + if (recovered !== null) { + return recovered; } } throw error; @@ -287,6 +341,7 @@ async function appendJournaled( await writeRevisionToken(config.tokenFile, appended.toCBOR(), false, context); await removeJournal(journalFile); + await removeKept(); return { recovered: replayed, signer: new SigningService(config.privateKey).publicKey, token: appended }; } diff --git a/src/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index bd677ab..07705d4 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -96,7 +96,10 @@ export async function findCertifiedProof( return null; } const certified = proof; - const verify = async (transactionHash: DataHash): Promise => + const verify = async ( + transactionHash: DataHash, + expiresAt: bigint | null, + ): Promise => ( await InclusionProofVerificationRule.verify( context.trustBase, @@ -104,19 +107,22 @@ export async function findCertifiedProof( context.unicityCertificateVerifier, certified, transactionHash, - transaction.expiresAt, + expiresAt, transaction.lockScript, transaction.sourceStateHash, ) ).status; - const status = await verify(await transaction.calculateTransactionHash()); + const status = await verify(await transaction.calculateTransactionHash(), transaction.expiresAt); if (status === InclusionProofVerificationStatus.OK) { return certified; } + // The other transaction is checked against its own hash and its own deadline: the + // same source state and lock script, but not necessarily the same expiry. if ( status === InclusionProofVerificationStatus.TRANSACTION_HASH_MISMATCH && - (await verify(certified.certificationData.transactionHash)) === InclusionProofVerificationStatus.OK + (await verify(certified.certificationData.transactionHash, certified.certificationData.expiresAt)) === + InclusionProofVerificationStatus.OK ) { throw new StateAlreadyCertifiedError(certified); } @@ -128,7 +134,9 @@ export async function findCertifiedProof( * * `STATE_ID_EXISTS` means the aggregator already holds a request for this state. * If it is this transaction, a repeated run, the proof it holds is returned; if - * it is another, {@link StateAlreadyCertifiedError} says so. Any other status the + * it is another, {@link StateAlreadyCertifiedError} says so. The same error comes + * from a proof of another transaction that arrives after `SUCCESS`, which is how + * aggregator-go answers a repeat while the first request is still in its round. Any other status the * SDK does not list is a warning rather than a failure, and the proof that then * arrives is checked against this transaction's hash anyway. * @@ -186,9 +194,11 @@ export async function certifyTransaction( } return proof; } catch (error) { - // The earlier request was still waiting for its round. The SDK reports a proof - // of another transaction only as a plain Error, so look again to say what it is. - if (exists && !(error instanceof SleepError)) { + // The SDK reports a proof of another transaction only as a plain Error, so look + // again to say what it is. Not only after STATE_ID_EXISTS: aggregator-go answers + // SUCCESS to a repeat while the first request for the state waits for its round, + // then certifies the first and drops the repeat. A timeout found no proof at all. + if (!(error instanceof SleepError)) { await findCertifiedProof(client, context, transaction, options.signal); } throw error; diff --git a/src/output.ts b/src/output.ts index 2f97449..20c6324 100644 --- a/src/output.ts +++ b/src/output.ts @@ -487,9 +487,11 @@ export interface IPendingRevisionNote { /** * Why a pending revision is being printed: `submitting` before it goes to the * aggregator; `rejected` when its slot turned out to be taken; `recovered` when it - * was certified by an earlier run and has just been written to the token file. + * was certified by an earlier run and has just been written to the token file; + * `unresolved` when an earlier run submitted it and it is not certified yet, but + * may still be. */ -export type PendingRevisionContext = 'recovered' | 'rejected' | 'submitting'; +export type PendingRevisionContext = 'recovered' | 'rejected' | 'submitting' | 'unresolved'; /** * The contents of a revision journal, for stderr: enough to recover the revision @@ -504,6 +506,7 @@ export function pendingRevisionLines(note: IPendingRevisionNote, context: Pendin recovered: `Recovered revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}, certified by an interrupted run:`, rejected: `Revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}, as this run submitted it (not certified):`, submitting: `Submitting revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}:`, + unresolved: `Revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}, submitted by an earlier run and not certified yet:`, }[context]; const lines = [ heading, @@ -516,6 +519,11 @@ export function pendingRevisionLines(note: IPendingRevisionNote, context: Pendin 'If this run is interrupted, run stamp-revision on the same token file again to recover the revision;', 'without the journal, run it with this digest and next producer.', ); + } else if (context === 'unresolved') { + lines.push( + ` ${line('Journal', note.journalFile)}`, + 'It may still be certified, so its journal is kept until a revision in its place is; do not delete it.', + ); } return `${lines.join('\n')}\n`; } diff --git a/tests/unit/DurableFileTest.ts b/tests/unit/DurableFileTest.ts index 88c890d..8620652 100644 --- a/tests/unit/DurableFileTest.ts +++ b/tests/unit/DurableFileTest.ts @@ -105,6 +105,49 @@ describe('writeFileDurably', () => { }); }); + describe('createInPlace', () => { + const inPlace = { fileMode: 0o600, followSymlinks: false, publish: 'createInPlace' } as const; + + it('writes under the name itself, with no temporary that a crash could leave behind', async () => { + const created: string[] = []; + const recording: IDurableFileSystem = { + ...NODE_FILE_SYSTEM, + link: noLink, + writeNew: (name, data, mode) => { + created.push(name); + return NODE_FILE_SYSTEM.writeNew(name, data, mode); + }, + }; + await writeFileDurably(file, DATA, inPlace, recording); + expect(created).toEqual([file]); + expect(new Uint8Array(await readFile(file))).toEqual(DATA); + expect((await stat(file)).mode & 0o777).toBe(0o600); + }); + + it('refuses an existing file or symlink, and removes a partial file it created', async () => { + await writeFile(file, 'someone else'); + await expect(writeFileDurably(file, DATA, inPlace)).rejects.toMatchObject({ code: 'EEXIST', path: file }); + expect(await readFile(file, 'utf8')).toEqual('someone else'); + + const link = path.join(directory, 'link'); + await symlink(path.join(directory, 'missing'), link); + await expect(writeFileDurably(link, DATA, inPlace)).rejects.toMatchObject({ code: 'EEXIST', path: link }); + + const other = path.join(directory, 'other.key'); + await expect( + writeFileDurably( + other, + DATA, + inPlace, + failingWrite(() => true), + ), + ).rejects.toMatchObject({ + code: 'ENOSPC', + }); + expect((await readdir(directory)).sort()).toEqual(['doc.lineage', 'link']); + }); + }); + describe('replace', () => { const replace = { followSymlinks: true, publish: 'replace' } as const; diff --git a/tests/unit/RevisionJournalTest.ts b/tests/unit/RevisionJournalTest.ts new file mode 100644 index 0000000..dd0f8f7 --- /dev/null +++ b/tests/unit/RevisionJournalTest.ts @@ -0,0 +1,66 @@ +import { readdir, readFile, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { + findJournals, + IPendingRevision, + journalPath, + readJournal, + writeJournal, +} from '../../src/commands/revisionJournal.js'; +import { EXIT_USAGE, toExitCode } from '../../src/errors.js'; +import { OTHER_DIGEST, tempDir, TEST_DIGEST } from '../support/fixtures.js'; + +describe('revision journals', () => { + const pending: IPendingRevision = { + digest: TEST_DIGEST, + nextProducer: null, + revision: 1n, + tokenId: new Uint8Array(32).fill(0xaa), + transaction: new Uint8Array([1, 2, 3]), + }; + let directory: string; + let tokenFile: string; + + beforeEach(async () => { + directory = await tempDir('proof-cli-journal-'); + tokenFile = path.join(directory, 'doc.lineage'); + }); + + it('names a journal after its transfer, so candidates for one revision sit side by side', async () => { + const first = journalPath(tokenFile, pending.transaction); + const second = journalPath(tokenFile, new Uint8Array([4, 5, 6])); + expect(path.basename(first)).toMatch(/^\.doc\.lineage\.[0-9a-f]{16}\.pending$/); + expect(second).not.toEqual(first); + expect(await writeJournal(first, pending)).toBe(true); + expect(await writeJournal(second, { ...pending, transaction: new Uint8Array([4, 5, 6]) })).toBe(true); + await writeFile(path.join(directory, '.other.lineage.0000000000000000.pending'), 'not ours'); + await writeFile(path.join(directory, '.doc.lineage.pending'), 'not a journal name'); + expect(await findJournals(tokenFile)).toEqual([first, second].sort()); + expect(await readJournal(first)).toEqual(pending); + }); + + it('accepts a journal another run already wrote for the same transfer, and leaves it as it is', async () => { + const file = journalPath(tokenFile, pending.transaction); + await writeJournal(file, pending); + const written = await readFile(file, 'utf8'); + expect(await writeJournal(file, pending)).toBe(false); + expect(await readFile(file, 'utf8')).toEqual(written); + }); + + // MastaP on PR #16: the loser of a race to create the journal deleted the winner's. + it('never removes a journal it did not create, even one with other content', async () => { + const file = journalPath(tokenFile, pending.transaction); + await writeJournal(file, { ...pending, digest: OTHER_DIGEST }); + const written = await readFile(file, 'utf8'); + const attempt = writeJournal(file, pending); + await expect(attempt).rejects.toThrow(/already exists with other content; nothing was submitted/); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await readFile(file, 'utf8')).toEqual(written); + + await writeFile(file, 'garbage'); + await expect(writeJournal(file, pending)).rejects.toThrow(/is not a pending lineage revision/); + expect(await readFile(file, 'utf8')).toEqual('garbage'); + expect(await readdir(directory)).toEqual([path.basename(file)]); + }); +}); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index b83a4c0..8efd928 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -2,7 +2,10 @@ import { lstat, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promis import path from 'node:path'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; -import { CertificationResponse } from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; +import { + CertificationResponse, + CertificationStatus, +} from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/IAggregatorClient.js'; import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js'; import { JsonRpcNetworkError } from '@unicitylabs/state-transition-sdk/lib/api/json-rpc/JsonRpcNetworkError.js'; @@ -11,6 +14,7 @@ import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/sec import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { SleepError } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; import { networkMismatch, stampRevisionWith } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig } from '../../src/config.js'; @@ -53,6 +57,71 @@ class InterruptingClient implements IAggregatorClient { } } +/** Loses every request before the aggregator sees it, but answers lookups. */ +class LostSubmitClient implements IAggregatorClient { + public constructor(private readonly inner: TestAggregatorClient) {} + + public getInclusionProof(stateId: StateId): Promise { + return this.inner.getInclusionProof(stateId); + } + + public submitCertificationRequest(): Promise { + return Promise.reject(new JsonRpcNetworkError(502, 'bad gateway')); + } +} + +/** + * Queues requests the way aggregator-go does. A state already certified is + * answered with STATE_ID_EXISTS; any other request, even a repeat for a state + * whose first request is still waiting for its round, gets SUCCESS. The round then + * certifies the first request for each state and silently drops the rest. With + * `roundOnRepeat`, the round runs at the first lookup after a repeat was admitted. + */ +class QueueingClient implements IAggregatorClient { + private readonly queue: { data: CertificationData; key: string }[] = []; + private roundDue = false; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly roundOnRepeat: boolean, + ) {} + + private static async keyOf(data: CertificationData): Promise { + return HexConverter.encode((await StateId.fromCertificationData(data)).data); + } + + public async getInclusionProof(stateId: StateId): Promise { + if (this.roundDue) { + await this.runRound(); + } + return this.inner.getInclusionProof(stateId); + } + + public async runRound(): Promise { + this.roundDue = false; + const certified = new Set(); + for (const { data, key } of this.queue.splice(0)) { + if (!certified.has(key)) { + certified.add(key); + await this.inner.submitCertificationRequest(data); + } + } + } + + public async submitCertificationRequest(data: CertificationData): Promise { + const stateId = await StateId.fromCertificationData(data); + if ((await this.inner.getInclusionProof(stateId)).inclusionProof !== null) { + return this.inner.submitCertificationRequest(data); + } + const key = await QueueingClient.keyOf(data); + if (this.roundOnRepeat && this.queue.some((queued) => queued.key === key)) { + this.roundDue = true; + } + this.queue.push({ data, key }); + return CertificationResponse.create(CertificationStatus.SUCCESS); + } +} + type Lookup = (stateId: StateId) => Promise; /** Answers the n-th proof lookup with the n-th scripted answer, and the rest from the aggregator. */ @@ -302,7 +371,8 @@ describe('stampRevisionWith', () => { beforeEach(async () => { tokenFile = path.join(directory, 'doc.lineage'); - journal = path.join(directory, '.doc.lineage.pending'); + // Where a test writes a journal by hand; a run names its own after its transfer. + journal = path.join(directory, '.doc.lineage.0000000000000000.pending'); await stampRevisionWith(config({}), client, testContext().context); genesisBytes = new Uint8Array(await readFile(tokenFile)); }); @@ -320,10 +390,19 @@ describe('stampRevisionWith', () => { async function interrupted(): Promise { const interrupting = new StateTransitionClient(new InterruptingClient(aggregator)); await expect(stampRevisionWith(append(), interrupting, testContext().context)).rejects.toThrow(/bad gateway/); - expect(await readdir(directory)).toEqual(['.doc.lineage.pending', 'doc.lineage']); + const journals = await journalFiles(); + expect(journals).toHaveLength(1); + journal = journals[0]; + expect(await readdir(directory)).toEqual([path.basename(journal), 'doc.lineage']); expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); } + async function journalFiles(): Promise { + return (await readdir(directory)) + .filter((name) => /^\.doc\.lineage\.[0-9a-f]{16}\.pending$/.test(name)) + .map((name) => path.join(directory, name)); + } + async function revisions(): Promise { const token = await Token.fromCBOR(new Uint8Array(await readFile(tokenFile))); return (await verifyLineage(token, aggregator.rootTrustBase)).description.revisions.map((revision) => @@ -338,7 +417,7 @@ describe('stampRevisionWith', () => { expect(sink.stderr()).toContain('Submitting revision 1 of lineage '); expect(sink.stderr()).toContain(`Stamped SHA-256 ${OTHER_DIGEST_HEX}`); expect(sink.stderr()).toContain(`Next producer ${TEST_PUBLIC_KEY_HEX}`); - expect(sink.stderr()).toContain(`Journal ${journal}`); + expect(sink.stderr()).toMatch(/Journal {8}\S+\/\.doc\.lineage\.[0-9a-f]{16}\.pending\n/); expect(await readdir(directory)).toEqual(['doc.lineage']); }); @@ -407,6 +486,105 @@ describe('stampRevisionWith', () => { expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); }); + describe('an earlier run whose outcome is not known yet', () => { + const UNRESOLVED = 'submitted by an earlier run and not certified yet:'; + + /** Run 1: bob's revision 1 (OTHER_DIGEST) is submitted, and the run times out while it is queued. */ + async function timedOut(queueing: QueueingClient): Promise { + const attempt = stampRevisionWith( + append({ quiet: true, timeoutMs: 300 }), + new StateTransitionClient(queueing), + testContext().context, + ); + await expect(attempt).rejects.toBeInstanceOf(SleepError); + expect(await journalFiles()).toHaveLength(1); + } + + // MastaP's reproduction on PR #16: run 2, with other inputs, used to delete run 1's + // journal, then lose its own request to run 1's and fail with a plain hash mismatch. + it("keeps its journal, and recovers its revision when the round certifies it instead of this run's", async () => { + const queueing = new QueueingClient(aggregator, true); + await timedOut(queueing); + + const sink = testContext(); + const attempt = stampRevisionWith( + append({ digest: TEST_DIGEST, quiet: true }), + new StateTransitionClient(queueing), + sink.context, + ); + await expect(attempt).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); + expect(((await attempt.catch((error: unknown) => error)) as Error).message).toContain( + `recovered and written to ${tokenFile}; the requested revision was not appended`, + ); + // Despite --quiet: the earlier run's revision while open, then this run's as rejected. + expect(sink.stderr()).toContain(UNRESOLVED); + expect(sink.stderr()).toContain('as this run submitted it (not certified)'); + expect(sink.stderr()).toContain('Recovered revision 1 of lineage '); + expect(await journalFiles()).toEqual([]); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + it('keeps both journals when the second run times out too, and the next run recovers the certified one', async () => { + const queueing = new QueueingClient(aggregator, false); + await timedOut(queueing); + const sink = testContext(); + await expect( + stampRevisionWith( + append({ digest: TEST_DIGEST, quiet: true, timeoutMs: 300 }), + new StateTransitionClient(queueing), + sink.context, + ), + ).rejects.toBeInstanceOf(SleepError); + expect(sink.stderr()).toContain(UNRESOLVED); + expect(sink.stderr()).toContain(`SHA-256 ${OTHER_DIGEST_HEX}`); + expect(await journalFiles()).toHaveLength(2); + + await queueing.runRound(); + const attempt = stampRevisionWith(append({ digest: TEST_DIGEST, quiet: true }), client, testContext().context); + await expect(attempt).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); + expect(await journalFiles()).toEqual([]); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + it("removes its journal once this run's revision is certified in its place", async () => { + await expect( + stampRevisionWith( + append({ quiet: true }), + new StateTransitionClient(new LostSubmitClient(aggregator)), + testContext().context, + ), + ).rejects.toThrow(/bad gateway/); + expect(await journalFiles()).toHaveLength(1); + + const sink = testContext(); + expect(await stampRevisionWith(append({ digest: TEST_DIGEST, quiet: true }), client, sink.context)).toBe(0); + expect(sink.stderr()).toContain(UNRESOLVED); + expect(await journalFiles()).toEqual([]); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, TEST_DIGEST_HEX]); + }); + + it('removes its journal once a proof shows its slot holds another transfer', async () => { + await expect( + stampRevisionWith( + append({ quiet: true }), + new StateTransitionClient(new LostSubmitClient(aggregator)), + testContext().context, + ), + ).rejects.toThrow(/bad gateway/); + const genesis = await Token.fromCBOR(genesisBytes); + await appendRevision(client, aggregator.rootTrustBase, genesis, TEST_DIGEST, bob, null, { + timeoutMs: 2_000, + }); + + const sink = testContext(); + const attempt = stampRevisionWith(append({ digest: TEST_DIGEST, quiet: true }), client, sink.context); + await expect(attempt).rejects.toThrow(/that run's digest and next producer/); + expect(sink.stderr()).not.toContain(UNRESOLVED); + expect(await journalFiles()).toEqual([]); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + }); + }); + it('drops a journal whose revision the token file already holds', async () => { await interrupted(); const leftover = await readFile(journal); diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts index 7fb029c..de6808d 100644 --- a/tests/unit/lib/LineageClientTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -9,10 +9,13 @@ import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js'; import { BurnPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/BurnPredicate.js'; import { SignaturePredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicate.js'; +import { SignaturePredicateUnlockScript } from '@unicitylabs/state-transition-sdk/lib/predicate/builtin/SignaturePredicateUnlockScript.js'; import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js'; import { CborSerializer } from '@unicitylabs/state-transition-sdk/lib/serialization/cbor/CborSerializer.js'; import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js'; +import { StateMask } from '@unicitylabs/state-transition-sdk/lib/transaction/StateMask.js'; import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; +import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { StateAlreadyCertifiedError } from '../../../src/lib/errors.js'; @@ -328,6 +331,29 @@ describe('LineageClient', () => { ).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); }); + // Another client with the producer's key can set its own deadline. The conflict + // must be checked against that deadline, not this transfer's, or it looks + // uncertified and the run ends in the SDK's plain hash-mismatch error. + it('recognises a conflicting transfer that carries its own deadline', async () => { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const expiresAt = BigInt(Math.floor(Date.now() / 1000)) + 600n; + const conflicting = await TransferTransaction.create( + genesis, + BurnPredicate.create(new Uint8Array(32)), + StateMask.generate(), + { data: new Uint8Array([1]), expiresAt }, + ); + const certificationData = await CertificationData.fromTransaction( + conflicting, + await SignaturePredicateUnlockScript.create(conflicting, new SigningService(bob)), + ); + expect(certificationData.expiresAt).toBe(expiresAt); + expect((await aggregator.submitCertificationRequest(certificationData)).status).toEqual('SUCCESS'); + await expect( + appendRevision(client, trustBase, genesis, OTHER_DIGEST, bob, publicKey(carol), fast), + ).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); + }); + describe('recovering a genesis', () => { it('tells a fresh genesis from one an earlier run certified, which it recovers without submitting', async () => { const fresh = await createOrRecoverLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); From 0ce949ba279395a1c2ddf409e2b52eed92ceabeb Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 24 Nov 2026 14:09:19 +0200 Subject: [PATCH 21/25] Remove a file only once its exclusive create is known to have succeeded Review on PR #16: createInPlace removed the target after any failure from writeNew other than EEXIST, taking it to have come after the create. But the open itself can fail with EMFILE, ENFILE or ENOMEM even when the file exists, since Linux allocates the descriptor before it looks up the path, so `keygen --out existing.key` could delete an existing private key, and the token file's no-hard-link fallback could delete the file in its way. The injected file system now offers a plain exclusive openNew, and the create-write-clean-up sequence lives in durableFile.ts as writeExclusive: a failed open removes nothing, whatever the error; a failed write, fsync or close after it removes the file this call created. createInPlace removes the file only after a failed chmod. Tests cover EMFILE, ENFILE and ENOMEM on an existing file for both paths, and each step failing after the open. Co-Authored-By: Claude Opus 5.5 --- src/commands/durableFile.ts | 92 ++++++++++++++++------- tests/unit/DurableFileTest.ts | 107 ++++++++++++++++++++++++--- tests/unit/StampRevisionWriteTest.ts | 17 +++-- 3 files changed, 177 insertions(+), 39 deletions(-) diff --git a/src/commands/durableFile.ts b/src/commands/durableFile.ts index bca29ea..d3d4b94 100644 --- a/src/commands/durableFile.ts +++ b/src/commands/durableFile.ts @@ -2,28 +2,37 @@ import { randomBytes } from 'node:crypto'; import { chmod, link, lstat, open, readlink, rename, rm, stat } from 'node:fs/promises'; import path from 'node:path'; +/** A file just created by {@link IDurableFileSystem.openNew}. */ +export interface IWritableFile { + close(): Promise; + sync(): Promise; + writeFile(data: Uint8Array): Promise; +} + /** * The file operations {@link writeFileDurably} needs, so tests can make one fail - * partway. Each is the plain `node:fs/promises` call, except `writeNew`. + * partway. Each is the plain `node:fs/promises` call. Deciding what a failure + * leaves behind is not their job: that stays in this module, where it is tested. */ export interface IDurableFileSystem { chmod(file: string, mode: number): Promise; link(existing: string, file: string): Promise; lstat(file: string): Promise<{ isSymbolicLink(): boolean }>; + /** Create `file` exclusively (`wx`) with `mode`, subject to the umask, and open it for writing. */ + openNew(file: string, mode: number): Promise; readlink(file: string): Promise; rename(from: string, to: string): Promise; rm(file: string, options: { force: boolean }): Promise; stat(file: string): Promise<{ mode: number }>; /** Flush a directory's entries; may fail where directories cannot be opened. */ syncDirectory(directory: string): Promise; - /** Create `file` exclusively with `mode` (subject to the umask), write `data`, fsync, close. */ - writeNew(file: string, data: Uint8Array, mode: number): Promise; } export const NODE_FILE_SYSTEM: IDurableFileSystem = { chmod, link, lstat, + openNew: (file, mode) => open(file, 'wx', mode), readlink, rename, rm, @@ -36,15 +45,6 @@ export const NODE_FILE_SYSTEM: IDurableFileSystem = { await handle.close(); } }, - writeNew: async (file, data, mode) => { - const handle = await open(file, 'wx', mode); - try { - await handle.writeFile(data); - await handle.sync(); - } finally { - await handle.close(); - } - }, }; export interface IDurableWriteOptions { @@ -120,7 +120,8 @@ async function resolveSymlinks(fs: IDurableFileSystem, file: string): Promise { + let handle: IWritableFile; + try { + handle = await fs.openNew(file, mode); + } catch (error) { + if (errorCode(error) === 'EEXIST') { + throw fsError('EEXIST', 'file already exists', file, error); + } + throw error; + } + let failure: { error: unknown } | null = null; + try { + await handle.writeFile(data); + await handle.sync(); + } catch (error) { + failure = { error }; + } + try { + await handle.close(); + } catch (error) { + failure ??= { error }; + } + if (failure !== null) { + // Best effort, and never allowed to replace the error that actually matters. + await fs.rm(file, { force: true }).catch(() => undefined); + throw failure.error; + } +} + +/** + * An exclusive create of the name itself, written, fsynced and set to `mode`. A + * file this call created is removed again if a later step fails; nothing else is + * ever removed. * * @param {IDurableFileSystem} fs File operations. * @param {string} target Path to create. @@ -206,17 +251,14 @@ async function createInPlace( data: Uint8Array, mode: number | undefined, ): Promise { + await writeExclusive(fs, target, data, mode === undefined ? 0o666 : 0o600); + if (mode === undefined) { + return; + } try { - await fs.writeNew(target, data, mode === undefined ? 0o666 : 0o600); - if (mode !== undefined) { - await fs.chmod(target, mode); - } + await fs.chmod(target, mode); } catch (error) { - if (errorCode(error) === 'EEXIST') { - throw fsError('EEXIST', 'file already exists', target, error); - } - // Any other failure came after the exclusive create, or found nothing to remove: - // the name is this run's, and must not be left holding a partial file. + // The create succeeded, so the file is this call's. await fs.rm(target, { force: true }).catch(() => undefined); throw error; } diff --git a/tests/unit/DurableFileTest.ts b/tests/unit/DurableFileTest.ts index 8620652..db7cb68 100644 --- a/tests/unit/DurableFileTest.ts +++ b/tests/unit/DurableFileTest.ts @@ -1,7 +1,12 @@ import { chmod, lstat, readdir, readFile, readlink, stat, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; -import { IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from '../../src/commands/durableFile.js'; +import { + IDurableFileSystem, + IWritableFile, + NODE_FILE_SYSTEM, + writeFileDurably, +} from '../../src/commands/durableFile.js'; import { tempDir } from '../support/fixtures.js'; const DATA = new TextEncoder().encode('new contents\n'); @@ -10,20 +15,55 @@ function errno(code: string): NodeJS.ErrnoException { return Object.assign(new Error(code), { code }); } -/** The real file system, with `writeNew` writing only the first three bytes of `fail` before failing. */ -function failingWrite(fail: (file: string) => boolean): IDurableFileSystem { +type Step = 'close' | 'sync' | 'writeFile'; + +/** + * The real file system, with the file `fail` picks failing at `step` after it + * was created: `writeFile` writes only the first three bytes before failing. + */ +function failingWrite(fail: (file: string) => boolean, step: Step = 'writeFile'): IDurableFileSystem { return { ...NODE_FILE_SYSTEM, - writeNew: async (file, data, mode): Promise => { + openNew: async (file, mode): Promise => { + const handle = await NODE_FILE_SYSTEM.openNew(file, mode); if (!fail(file)) { - return NODE_FILE_SYSTEM.writeNew(file, data, mode); + return handle; + } + const failure = errno(step === 'writeFile' ? 'ENOSPC' : 'EIO'); + async function close(): Promise { + await handle.close(); + if (step === 'close') { + throw failure; + } + } + async function sync(): Promise { + if (step === 'sync') { + throw failure; + } + await handle.sync(); } - await NODE_FILE_SYSTEM.writeNew(file, data.subarray(0, 3), mode); - throw errno('ENOSPC'); + async function write(data: Uint8Array): Promise { + if (step !== 'writeFile') { + await handle.writeFile(data); + return; + } + await handle.writeFile(data.subarray(0, 3)); + throw failure; + } + return { close, sync, writeFile: write }; }, }; } +/** The real file system, with creating the file `fail` picks failing at the open itself, with `code`. */ +function failingOpen(fail: (file: string) => boolean, code: string): IDurableFileSystem { + return { + ...NODE_FILE_SYSTEM, + openNew: (file, mode): Promise => + fail(file) ? Promise.reject(errno(code)) : NODE_FILE_SYSTEM.openNew(file, mode), + }; +} + const noLink = (): Promise => Promise.reject(errno('EPERM')); /** The real file system on a filesystem without hard links. */ @@ -113,9 +153,9 @@ describe('writeFileDurably', () => { const recording: IDurableFileSystem = { ...NODE_FILE_SYSTEM, link: noLink, - writeNew: (name, data, mode) => { + openNew: (name, mode) => { created.push(name); - return NODE_FILE_SYSTEM.writeNew(name, data, mode); + return NODE_FILE_SYSTEM.openNew(name, mode); }, }; await writeFileDurably(file, DATA, inPlace, recording); @@ -148,6 +188,55 @@ describe('writeFileDurably', () => { }); }); + // MastaP on PR #16: a failed open is not proof the name was free. Linux allocates the + // descriptor before it looks up the path, so EMFILE comes back even when the file exists. + describe('a create that fails at the open', () => { + it.each(['EMFILE', 'ENFILE', 'ENOMEM'])('never removes an existing file, written in place (%s)', async (code) => { + await writeFile(file, 'existing key\n', { mode: 0o600 }); + await expect( + writeFileDurably( + file, + DATA, + { fileMode: 0o600, followSymlinks: false, publish: 'createInPlace' }, + failingOpen(() => true, code), + ), + ).rejects.toMatchObject({ code }); + expect(await readFile(file, 'utf8')).toEqual('existing key\n'); + }); + + it('never removes an existing file on the no-hard-link fallback either', async () => { + await writeFile(file, 'existing token'); + const fs = { ...failingOpen((name) => name === file, 'EMFILE'), link: noLink }; + await expect( + writeFileDurably(file, DATA, { followSymlinks: false, publish: 'create' }, fs), + ).rejects.toMatchObject({ code: 'EMFILE' }); + expect(await readFile(file, 'utf8')).toEqual('existing token'); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + }); + + describe('a create that fails after the open', () => { + const inPlace = { fileMode: 0o600, followSymlinks: false, publish: 'createInPlace' } as const; + + it.each(['writeFile', 'sync', 'close'])('removes the file it created (%s fails)', async (step) => { + await expect( + writeFileDurably( + file, + DATA, + inPlace, + failingWrite(() => true, step), + ), + ).rejects.toHaveProperty('code'); + expect(await readdir(directory)).toEqual([]); + }); + + it('removes the file it created when setting its mode fails', async () => { + const fs = { ...NODE_FILE_SYSTEM, chmod: (): Promise => Promise.reject(errno('EPERM')) }; + await expect(writeFileDurably(file, DATA, inPlace, fs)).rejects.toMatchObject({ code: 'EPERM' }); + expect(await readdir(directory)).toEqual([]); + }); + }); + describe('replace', () => { const replace = { followSymlinks: true, publish: 'replace' } as const; diff --git a/tests/unit/StampRevisionWriteTest.ts b/tests/unit/StampRevisionWriteTest.ts index 74bda43..272f9b0 100644 --- a/tests/unit/StampRevisionWriteTest.ts +++ b/tests/unit/StampRevisionWriteTest.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; -import { NODE_FILE_SYSTEM } from '../../src/commands/durableFile.js'; +import { IDurableFileSystem, IWritableFile, NODE_FILE_SYSTEM } from '../../src/commands/durableFile.js'; import { writeRevisionToken } from '../../src/commands/stampRevision.js'; import { testContext } from '../support/context.js'; import { tempDir } from '../support/fixtures.js'; @@ -67,11 +67,18 @@ describe('writeRevisionToken', () => { if (!created) { await writeFile(out, 'old'); } - const failing = { + const failing: IDurableFileSystem = { ...NODE_FILE_SYSTEM, - writeNew: async (file: string, data: Uint8Array, mode: number): Promise => { - await NODE_FILE_SYSTEM.writeNew(file, data.subarray(0, 2), mode); - throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + openNew: async (file, mode): Promise => { + const handle = await NODE_FILE_SYSTEM.openNew(file, mode); + return { + close: (): Promise => handle.close(), + sync: (): Promise => handle.sync(), + writeFile: async (data): Promise => { + await handle.writeFile(data.subarray(0, 2)); + throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + }, + }; }, }; const sink = testContext(); From 2654c603d7b102d34f53444ed8cb0973b02447b9 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 24 Nov 2026 14:17:35 +0200 Subject: [PATCH 22/25] Keep the conflict lookups inside --timeout Review on PR #16: the lookup after a failed wait got only the caller's abort signal, not the deadline handed to waitInclusionProof, so after a prompt failure a stalled gateway could keep the command running past --timeout until fetch gave up. certifyTransaction now builds one deadline right after submission and uses it for the lookup after STATE_ID_EXISTS, the wait, and the conflict lookup after a failed wait. A lookup cut off by the deadline ends with the SleepError a timed-out wait gives (exit 3), so stamp-revision keeps every journal, as for a timeout. A test client whose lookups stall until their signal aborts covers both lookups, and a stamp-revision run. Co-Authored-By: Claude Opus 5.5 --- src/lib/TimestampClient.ts | 53 ++++++++++++++++++++++++----- tests/support/StallingClient.ts | 45 ++++++++++++++++++++++++ tests/unit/StampRevisionTest.ts | 16 +++++++++ tests/unit/lib/LineageClientTest.ts | 29 ++++++++++++++++ 4 files changed, 135 insertions(+), 8 deletions(-) create mode 100644 tests/support/StallingClient.ts diff --git a/src/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index 07705d4..76d396f 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -129,6 +129,27 @@ export async function findCertifiedProof( return null; } +/** + * @param {AbortSignal} signal The deadline that fired. + * @param {unknown} cause What the cut-off lookup threw. + * @returns {SleepError} The error {@link waitInclusionProof} gives for the same abort. + */ +function abortedWait(signal: AbortSignal, cause: unknown): SleepError { + let message = 'Wait was aborted'; + try { + const reason: unknown = signal.reason; + if (reason instanceof Error || (typeof reason === 'object' && reason !== null && 'message' in reason)) { + // The SDK prints the reason's own description, e.g. "TimeoutError: The operation was aborted due to timeout". + message = `${(reason as Error).name}: ${(reason as Error).message}`; + } else if (typeof reason === 'string') { + message = reason; + } + } catch { + // A reason that cannot be described still ends the wait. + } + return new SleepError(message, { cause }); +} + /** * Submit a certification request and wait for its inclusion proof. * @@ -148,7 +169,8 @@ export async function findCertifiedProof( * @returns {Promise} Verified inclusion proof. * @throws {StampError} If the aggregator returns a known failure status. * @throws {StateAlreadyCertifiedError} If the state was certified with another transaction. - * @throws {SleepError} If the proof does not arrive before the timeout or abort. + * @throws {SleepError} If the proof does not arrive before the timeout or abort, + * including while a lookup is in flight. */ export async function certifyTransaction( client: StateTransitionClient, @@ -158,9 +180,28 @@ export async function certifyTransaction( options: ICertifyOptions = {}, ): Promise { const response = await client.submitCertificationRequest(certificationData, { signal: options.signal }); + // One deadline from here on, for every lookup as well as the wait: all of them are + // getting the proof, which is what the timeout bounds. + const signals = [AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)]; + if (options.signal) { + signals.push(options.signal); + } + const deadline = AbortSignal.any(signals); + const lookUp = async (): Promise => { + try { + return await findCertifiedProof(client, context, transaction, deadline); + } catch (error) { + if (!(error instanceof StateAlreadyCertifiedError) && deadline.aborted) { + // Cut off by the deadline: the same outcome, and the same error, as a wait that times out. + throw abortedWait(deadline, error); + } + throw error; + } + }; + const exists = response.status === STATE_ID_EXISTS_STATUS; if (exists) { - const proof = await findCertifiedProof(client, context, transaction, options.signal); + const proof = await lookUp(); if (proof !== null) { options.onAlreadyCertified?.(); return proof; @@ -174,10 +215,6 @@ export async function certifyTransaction( ); } - const signals = [AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)]; - if (options.signal) { - signals.push(options.signal); - } try { const proof = await waitInclusionProof( client, @@ -185,7 +222,7 @@ export async function certifyTransaction( context.predicateVerifier, context.unicityCertificateVerifier, transaction, - AbortSignal.any(signals), + deadline, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, ); if (exists) { @@ -199,7 +236,7 @@ export async function certifyTransaction( // SUCCESS to a repeat while the first request for the state waits for its round, // then certifies the first and drops the repeat. A timeout found no proof at all. if (!(error instanceof SleepError)) { - await findCertifiedProof(client, context, transaction, options.signal); + await lookUp(); } throw error; } diff --git a/tests/support/StallingClient.ts b/tests/support/StallingClient.ts new file mode 100644 index 0000000..a7b157f --- /dev/null +++ b/tests/support/StallingClient.ts @@ -0,0 +1,45 @@ +import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; +import { + CertificationResponse, + CertificationStatus, +} from '@unicitylabs/state-transition-sdk/lib/api/CertificationResponse.js'; +import type { IAggregatorClient } from '@unicitylabs/state-transition-sdk/lib/api/IAggregatorClient.js'; +import { InclusionProofResponse } from '@unicitylabs/state-transition-sdk/lib/api/InclusionProofResponse.js'; +import type { IRequestOptions } from '@unicitylabs/state-transition-sdk/lib/api/IRequestOptions.js'; +import { StateId } from '@unicitylabs/state-transition-sdk/lib/api/StateId.js'; + +import { TestAggregatorClient } from './TestAggregatorClient.js'; + +/** + * A gateway that stalls: from the `stallFrom`-th proof lookup on (counting from + * 0), a lookup never answers, and ends only when its signal aborts. With + * `dropRequests`, a request is answered SUCCESS without reaching the aggregator, + * as aggregator-go answers a repeat it will drop; otherwise it is passed on. + */ +export class StallingClient implements IAggregatorClient { + private lookups = 0; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly stallFrom: number, + private readonly dropRequests: boolean, + ) {} + + public getInclusionProof(stateId: StateId, options?: IRequestOptions): Promise { + const lookup = this.lookups; + this.lookups += 1; + if (lookup < this.stallFrom) { + return this.inner.getInclusionProof(stateId); + } + return new Promise((_, reject) => { + const signal = options?.signal; + signal?.addEventListener('abort', () => reject(signal.reason as Error), { once: true }); + }); + } + + public submitCertificationRequest(certificationData: CertificationData): Promise { + return this.dropRequests + ? Promise.resolve(CertificationResponse.create(CertificationStatus.SUCCESS)) + : this.inner.submitCertificationRequest(certificationData); + } +} diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 8efd928..0e75cce 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -42,6 +42,7 @@ import { TEST_PRIVATE_KEY, TEST_PUBLIC_KEY_HEX, } from '../support/fixtures.js'; +import { StallingClient } from '../support/StallingClient.js'; import { TestAggregatorClient } from '../support/TestAggregatorClient.js'; /** Passes the request on, then loses every proof lookup: the run fails after certification. */ @@ -585,6 +586,21 @@ describe('stampRevisionWith', () => { }); }); + it('keeps its journal and exits 3 when the conflict lookup stalls past the timeout', async () => { + const genesis = await Token.fromCBOR(genesisBytes); + const other = await prepareRevision(genesis, aggregator.rootTrustBase, TEST_DIGEST, bob, null); + await aggregator.submitCertificationRequest(other.certificationData); + const attempt = stampRevisionWith( + append({ quiet: true, timeoutMs: 200 }), + new StateTransitionClient(new StallingClient(aggregator, 1, true)), + testContext().context, + ); + await expect(attempt).rejects.toBeInstanceOf(SleepError); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(3); + expect(await journalFiles()).toHaveLength(1); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); + }); + it('drops a journal whose revision the token file already holds', async () => { await interrupted(); const leftover = await readFile(journal); diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts index de6808d..02c8b0e 100644 --- a/tests/unit/lib/LineageClientTest.ts +++ b/tests/unit/lib/LineageClientTest.ts @@ -17,6 +17,7 @@ import { StateMask } from '@unicitylabs/state-transition-sdk/lib/transaction/Sta import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { SleepError } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; import { StateAlreadyCertifiedError } from '../../../src/lib/errors.js'; import { @@ -38,6 +39,7 @@ import { createLineageVerificationContext, verifyLineage } from '../../../src/li import { bundledTrustBase } from '../../../src/lib/networks.js'; import { findCertifiedProof, STATE_ID_EXISTS_STATUS, stampWith } from '../../../src/lib/TimestampClient.js'; import { OTHER_DIGEST, TEST_DIGEST } from '../../support/fixtures.js'; +import { StallingClient } from '../../support/StallingClient.js'; import { TestAggregatorClient } from '../../support/TestAggregatorClient.js'; /** Counts certification requests so a test can see whether the network was contacted. */ @@ -354,6 +356,33 @@ describe('LineageClient', () => { ).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); }); + // MastaP on PR #16: the conflict lookups must stay inside --timeout. A stalled + // lookup ends as a timeout would, with the SDK's SleepError (exit 3). + describe('a stalled conflict lookup', () => { + async function takenSlot(): Promise { + const genesis = await createLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); + const other = await prepareRevision(genesis, trustBase, OTHER_DIGEST, bob, publicKey(carol)); + await aggregator.submitCertificationRequest(other.certificationData); + return genesis; + } + + it.each([ + ['after SUCCESS and a proof of another transfer', 1, true], + ['after STATE_ID_EXISTS', 0, false], + ])('ends within the timeout, as a timeout (%s)', async (_, stallFrom, dropRequests) => { + const genesis = await takenSlot(); + const stalling = new StateTransitionClient(new StallingClient(aggregator, stallFrom, dropRequests)); + const started = Date.now(); + const attempt = appendRevision(stalling, trustBase, genesis, THIRD_DIGEST, bob, publicKey(carol), { + pollIntervalMs: 10, + timeoutMs: 200, + }); + await expect(attempt).rejects.toBeInstanceOf(SleepError); + await expect(attempt).rejects.toThrow(/TimeoutError/); + expect(Date.now() - started).toBeLessThan(1_500); + }); + }); + describe('recovering a genesis', () => { it('tells a fresh genesis from one an earlier run certified, which it recovers without submitting', async () => { const fresh = await createOrRecoverLineage(client, trustBase, TEST_DIGEST, alice, publicKey(bob), fast); From a44e025aa4db7e1eb80b7df53c8ffd35a14932e2 Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 24 Nov 2026 14:34:09 +0200 Subject: [PATCH 23/25] Lock appends, and never roll the token file back Review on PR #16: an append replaced the token file with the token it read at start plus its revision, without checking that the file had not moved on, so a slower concurrent run could write over a revision another run had certified and written, whose journal was already gone. The write in settle had the same exposure. - An append takes a lock file, `..lock` next to the token file after symlinks are resolved, before it reads any journal, and releases it when it ends. A second append meanwhile exits 2 before submitting, naming the holder. Release removes only this run's lock. Under the lock the token file is re-read; if it changed since configuration, the run exits 2 before submitting. - writeFileDurably's replace takes `ifUnchanged`, and fails with ECHANGED instead of renaming over a file that no longer holds those bytes. Both append writes pass the bytes the run started from. When the file changed but already holds this run's revision (same lineage, verified, same transfer by hash), the run notes it and completes; otherwise it prints its token as hex, keeps its journal, and exits 2. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + skills/unicity-proof/SKILL.md | 4 + src/commands/durableFile.ts | 31 +++++- src/commands/stampRevision.ts | 116 +++++++++++++++++--- src/commands/tokenLock.ts | 91 ++++++++++++++++ src/output.ts | 12 +++ tests/unit/DurableFileTest.ts | 16 +++ tests/unit/StampRevisionTest.ts | 152 +++++++++++++++++++++++++++ tests/unit/StampRevisionWriteTest.ts | 35 ++++-- tests/unit/TokenLockTest.ts | 60 +++++++++++ 10 files changed, 496 insertions(+), 23 deletions(-) create mode 100644 src/commands/tokenLock.ts create mode 100644 tests/unit/TokenLockTest.ts diff --git a/README.md b/README.md index 9d94ae8..9050d28 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,8 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - If it exists, it must be a valid lineage token for the selected network whose latest revision names the `--key-file` key; otherwise the command fails before contacting the gateway (exit 1 for an invalid token, 2 for the wrong key). The revision is a transfer signed with that key under its `P_sig` predicate; its recipient is `P_sig` of the next producer. On any write failure the full token is printed as hex. - **The token file never holds a partial token.** It is written to a temporary file next to it, fsynced, and only then put in place (linked for a new lineage, renamed over the old file for an append), and the directory is fsynced after that. A failed or interrupted write leaves the previous file, or for a new lineage no file at all. An append keeps the file's mode, and if `--token-file` is a symlink, for example into a shared or synced folder, the file it points to is updated and the link is kept. On a filesystem without hard links, a new lineage is created in place instead and removed again if the write fails; only a crash during that write can leave a partial file. If a token file is not a token, the error says how to recover: move it away and run the same command again. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. +- **One append at a time.** An append holds a lock file next to the token file, `..lock` (after symlinks are resolved), from before it reads any journal until it has written the token file. A second append to the same file meanwhile exits 2 before submitting anything, naming the process that holds the lock. The lock is removed when the run ends, also after an error, a timeout or Ctrl-C; only a run that is killed outright, or a power loss, leaves it behind. It holds no data, so when no run is active it is always safe to delete. An append also exits 2, before submitting, if the token file changed between being read and being locked: run it again on the current file. +- **The token file is never rolled back.** An append replaces the token file only if it still holds what the run started from. If it changed meanwhile, for example because a program that ignores the lock wrote it, the file is left as it is. When it already holds this run's revision (the same lineage, verified, and the same transfer), nothing is lost: the run says so on stderr and completes. Otherwise the run prints its token as hex, keeps its journal, and exits 2. - **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `...pending`, where the tag is the first 16 hex digits of the transfer's SHA-256 (for example `.doc.lineage.3f2a9c0e1b7d4a65.pending`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. A journal is removed only once its outcome is known: when the token file holds its revision, or when a proof that verifies shows its revision's slot holds another transfer. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. - If the command is interrupted after submitting, running `stamp-revision` again on the same token file recovers the revision from the journal, whatever it is given this time. If the digest and recipient are the same, that completes the command. If not, the recovered revision is still written and echoed to stderr, the requested one is not appended, and the command exits 1. - Without the journal, the same command with the same file, key, digest and recipient still recovers the revision, because the state mask of each step is derived from the producer's key and the spent state. With any other digest or recipient it exits 1, saying the revision was already certified with different content, and echoes what it tried to stderr even with `--quiet`. Only the interrupted run's digest and recipient can recover it then, which is what the echo is for. diff --git a/skills/unicity-proof/SKILL.md b/skills/unicity-proof/SKILL.md index c6ca76f..3c0f1bc 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -73,6 +73,10 @@ without it the proof is gone. content` means an earlier run certified something else for this revision: only that run's digest and recipient recover it, and they are on stderr from when it was submitted. +- **Run one `stamp-revision` append per token file at a time.** Exit 2 saying + `Another stamp-revision run is appending` means wait for it. Delete the + `..lock` file only if no run is active (it holds no data); never delete + a journal. - **`(existing lineage, recovered)` means no new lineage was created.** The same issuer key, document and first producer always give the same lineage. If `stamp-revision` exits 1 saying `the lineage has moved on`, later diff --git a/src/commands/durableFile.ts b/src/commands/durableFile.ts index d3d4b94..0e118d8 100644 --- a/src/commands/durableFile.ts +++ b/src/commands/durableFile.ts @@ -1,5 +1,5 @@ import { randomBytes } from 'node:crypto'; -import { chmod, link, lstat, open, readlink, rename, rm, stat } from 'node:fs/promises'; +import { chmod, link, lstat, open, readFile, readlink, rename, rm, stat } from 'node:fs/promises'; import path from 'node:path'; /** A file just created by {@link IDurableFileSystem.openNew}. */ @@ -20,6 +20,7 @@ export interface IDurableFileSystem { lstat(file: string): Promise<{ isSymbolicLink(): boolean }>; /** Create `file` exclusively (`wx`) with `mode`, subject to the umask, and open it for writing. */ openNew(file: string, mode: number): Promise; + readFile(file: string): Promise; readlink(file: string): Promise; rename(from: string, to: string): Promise; rm(file: string, options: { force: boolean }): Promise; @@ -33,6 +34,7 @@ export const NODE_FILE_SYSTEM: IDurableFileSystem = { link, lstat, openNew: (file, mode) => open(file, 'wx', mode), + readFile: async (file) => new Uint8Array(await readFile(file)), readlink, rename, rm, @@ -58,6 +60,12 @@ export interface IDurableWriteOptions { * replacing or refusing the symlink itself. The symlink stays. */ readonly followSymlinks: boolean; + /** + * For `replace`: the bytes the file must still hold just before it is replaced. + * If it holds anything else, or is gone, nothing is replaced, and the write + * fails with the code {@link CHANGED}. + */ + readonly ifUnchanged?: Uint8Array; /** * `create`: refuse with EEXIST if anything is at the path, even a symlink to a * missing file, unless `followSymlinks`. `createInPlace`: the same, but written @@ -68,6 +76,9 @@ export interface IDurableWriteOptions { readonly publish: 'create' | 'createInPlace' | 'replace'; } +/** The error code of a `replace` whose target no longer holds `ifUnchanged`. */ +export const CHANGED = 'ECHANGED'; + /** Codes from `link` on a filesystem without hard links. */ const NO_HARD_LINKS = new Set(['ENOSYS', 'ENOTSUP', 'EOPNOTSUPP', 'EPERM']); @@ -116,8 +127,9 @@ async function resolveSymlinks(fs: IDurableFileSystem, file: string): Promise undefined); } +async function holds(fs: IDurableFileSystem, file: string, expected: Uint8Array): Promise { + const actual = await fs.readFile(file).catch((error: unknown) => { + if (errorCode(error) === 'ENOENT') { + return null; + } + throw error; + }); + return actual !== null && actual.length === expected.length && actual.every((byte, i) => byte === expected[i]); +} + async function publishNew( fs: IDurableFileSystem, temporary: string, diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index e133b6d..6a0a9b7 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -9,9 +9,10 @@ import { CertifiedTransferTransaction } from '@unicitylabs/state-transition-sdk/ import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js'; import { TransferTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/TransferTransaction.js'; import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; +import { areUint8ArraysEqual } from '@unicitylabs/state-transition-sdk/lib/util/TypedArrayUtils.js'; import { ICommandContext } from './context.js'; -import { IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from './durableFile.js'; +import { CHANGED, IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from './durableFile.js'; import { findJournals, hasErrorCode, @@ -24,6 +25,7 @@ import { writeJournal, } from './revisionJournal.js'; import { decodeToken, tokenBytesFromInput } from './tokenInput.js'; +import { acquireAppendLock } from './tokenLock.js'; import { IStampRevisionConfig, IStampRevisionFlags, resolveStampRevisionConfig } from '../config.js'; import { CliError, EXIT_OK, EXIT_VERIFICATION_FAILED, usageError } from '../errors.js'; import { errorMessage, StampError } from '../lib/errors.js'; @@ -39,9 +41,11 @@ import { recoverRevision, SuccessorLookup, } from '../lib/LineageClient.js'; +import { verifyLineage } from '../lib/LineageVerification.js'; import { networkNameForId } from '../lib/networks.js'; import { ICertifyOptions } from '../lib/TimestampClient.js'; import { + alreadyHeldNote, existingLineageNote, networkLabel, PendingRevisionContext, @@ -86,6 +90,12 @@ async function tokenFileInTheWay(tokenFile: string, cause: unknown): Promise} `changed` when an append found the file no longer holding `base`. */ export async function writeRevisionToken( tokenFile: string, bytes: Uint8Array, - created: boolean, + target: RevisionTarget, context: ICommandContext, - force = false, fs: IDurableFileSystem = NODE_FILE_SYSTEM, -): Promise { - const exclusive = created && !force; +): Promise<'changed' | 'written'> { + const exclusive = target.kind === 'new' && !target.force; try { await writeFileDurably( tokenFile, bytes, - { followSymlinks: !exclusive, publish: exclusive ? 'create' : 'replace' }, + { + followSymlinks: !exclusive, + ifUnchanged: target.kind === 'append' ? target.base : undefined, + publish: exclusive ? 'create' : 'replace', + }, fs, ); + return 'written'; } catch (error) { + if (target.kind === 'append' && hasErrorCode(error, CHANGED)) { + return 'changed'; + } // First, before anything awaited, so nothing can get between the error and the recovered bytes. context.stderr.write(revisionRecoveryLines(bytes)); if (exclusive && hasErrorCode(error, 'EEXIST')) { @@ -132,6 +151,41 @@ export async function writeRevisionToken( } } +/** + * Whether the token file, as it is now, already holds the last revision of + * `token`: the same lineage, verified, with the same transfer at that index (by + * its hash, since the two copies may carry proofs under different roots). Each + * state has only one certified successor, so a valid file that has moved past + * this revision holds it. + * + * @param {string} tokenFile Token file path. + * @param {Token} token This run's token. + * @param {RootTrustBase} trustBase Trust base of the token's network. + * @returns {Promise} True if nothing would be lost by leaving the file as it is. + */ +async function fileHoldsRevision(tokenFile: string, token: Token, trustBase: RootTrustBase): Promise { + try { + const decoded = await decodeToken(tokenBytesFromInput(await NODE_FILE_SYSTEM.readFile(tokenFile))); + const current = decoded.token; + const index = token.transactions.length - 1; + if ( + current === null || + index < 0 || + !areUint8ArraysEqual(current.id.bytes, token.id.bytes) || + current.transactions.length <= index || + // The same transfer: its proof may differ, served under a later root, but not what it certifies. + !(await current.transactions[index].calculateTransactionHash()).equals( + await token.transactions[index].calculateTransactionHash(), + ) + ) { + return false; + } + return (await verifyLineage(current, trustBase)).status === 'OK'; + } catch { + return false; + } +} + function writePending( context: ICommandContext, pending: IPendingRevision, @@ -228,6 +282,28 @@ async function appendJournaled( // Before any journal is acted on, in either direction. await assertValidLineage(token, trustBase); + // Write the token over the file this run started from. If the file changed meanwhile, + // leave it: when it already holds this run's revision, nothing is lost, and the run + // goes on as if it had written it; otherwise this run's token goes to stderr as hex, + // its journals stay, and it stops. + const base = config.tokenBytes as Uint8Array; + const persist = async (result: Token): Promise => { + const bytes = result.toCBOR(); + if ((await writeRevisionToken(config.tokenFile, bytes, { base, kind: 'append' }, context)) === 'written') { + return; + } + if (await fileHoldsRevision(config.tokenFile, result, trustBase)) { + context.stderr.write(alreadyHeldNote(config.tokenFile, BigInt(result.transactions.length))); + return; + } + context.stderr.write(revisionRecoveryLines(bytes)); + throw usageError( + `${config.tokenFile} changed while this run was working, so it was not replaced. This run's token is ` + + 'printed above as hex, and its journal is kept, so running stamp-revision again on the current token ' + + 'file can recover the revision if it belongs there.', + ); + }; + // Every journal still kept for the next revision, this run's own included once written. const kept = new Map(); const removeKept = async (): Promise => { @@ -241,7 +317,7 @@ async function appendJournaled( // revision removed; then either it was the revision asked for, or the request // cannot go ahead. const settle = async (entry: IJournalEntry, recovered: Token): Promise => { - await writeRevisionToken(config.tokenFile, recovered.toCBOR(), false, context); + await persist(recovered); await removeJournal(entry.file); await removeKept(); if (await isSameRevision(entry.transaction, entry.pending.revision, config.digest, config.recipientKey)) { @@ -339,7 +415,7 @@ async function appendJournaled( throw error; } - await writeRevisionToken(config.tokenFile, appended.toCBOR(), false, context); + await persist(appended); await removeJournal(journalFile); await removeKept(); return { recovered: replayed, signer: new SigningService(config.privateKey).publicKey, token: appended }; @@ -477,7 +553,7 @@ export async function stampRevisionWith( if (recovered) { await assertNotSuperseded(client, trustBase, token, context); } - await writeRevisionToken(config.tokenFile, token.toCBOR(), true, context, config.force); + await writeRevisionToken(config.tokenFile, token.toCBOR(), { force: config.force, kind: 'new' }, context); if (recovered) { // Not subject to --quiet: without it, two files can pass for two lineages. context.stderr.write(existingLineageNote(token.id.bytes)); @@ -501,7 +577,19 @@ export async function stampRevisionWith( if (mismatch !== null) { throw mismatch; } - ({ recovered, signer, token } = await appendJournaled(config, client, context, options, decoded.token)); + const release = await acquireAppendLock(config.tokenFile); + try { + // Under the lock: a run that finished between this run's read and its lock moved the file on. + const current = await NODE_FILE_SYSTEM.readFile(config.tokenFile).catch(() => null); + if (current === null || !areUint8ArraysEqual(current, config.tokenBytes)) { + throw usageError( + `${config.tokenFile} changed since this run read it, so nothing was submitted. Run the command again.`, + ); + } + ({ recovered, signer, token } = await appendJournaled(config, client, context, options, decoded.token)); + } finally { + await release(); + } } const latest = latestCertified(token); diff --git a/src/commands/tokenLock.ts b/src/commands/tokenLock.ts new file mode 100644 index 0000000..b53eed3 --- /dev/null +++ b/src/commands/tokenLock.ts @@ -0,0 +1,91 @@ +import { open, readFile, realpath, rm } from 'node:fs/promises'; +import { hostname } from 'node:os'; +import path from 'node:path'; + +import { usageError } from '../errors.js'; +import { hasErrorCode } from './revisionJournal.js'; + +const LOCK_FORMAT = 'unicity-proof/append-lock'; + +interface ILockJson { + readonly format: typeof LOCK_FORMAT; + readonly host: string; + readonly pid: number; + readonly started: string; +} + +/** + * @param {string} realTokenFile The token file, with symlinks resolved. + * @returns {string} Its lock: `..lock` next to it. + */ +export function lockPath(realTokenFile: string): string { + return path.join(path.dirname(realTokenFile), `.${path.basename(realTokenFile)}.lock`); +} + +function describeHolder(text: string): string { + try { + const json = JSON.parse(text) as Partial; + if (json.format === LOCK_FORMAT) { + return ` (pid ${json.pid} on ${json.host}, since ${json.started})`; + } + } catch { + // Described without the details, then. + } + return ''; +} + +/** + * Take the append lock of a token file, so that two `stamp-revision` runs cannot + * append to it at once: a slower one would write its token over the faster one's, + * and a revision certified and written in between would vanish from the file. + * + * The lock is a file created exclusively next to the token file, after symlinks + * are resolved, so every path to the same file shares one lock. It holds no data: + * it only says who holds it, and deleting it when no run is active is always safe. + * + * @param {string} tokenFile Absolute token file path; it must exist. + * @returns {Promise<() => Promise>} Releases the lock; never fails. + * @throws {CliError} If another run holds the lock, or it cannot be taken; nothing has been submitted then. + */ +export async function acquireAppendLock(tokenFile: string): Promise<() => Promise> { + let file: string; + try { + file = lockPath(await realpath(tokenFile)); + } catch (error) { + throw usageError(`Cannot read the token file ${tokenFile}.`, { cause: error }); + } + const json: ILockJson = { + format: LOCK_FORMAT, + host: hostname(), + pid: process.pid, + started: new Date().toISOString(), + }; + const contents = `${JSON.stringify(json, null, 2)}\n`; + let handle; + try { + handle = await open(file, 'wx', 0o644); + } catch (error) { + if (hasErrorCode(error, 'EEXIST')) { + const holder = describeHolder(await readFile(file, 'utf8').catch(() => '')); + throw usageError( + `Another stamp-revision run is appending to ${tokenFile}${holder}; nothing was submitted. ` + + `Wait for it to finish. If no run is active, delete the lock file ${file}: it holds no data.`, + { cause: error }, + ); + } + throw usageError(`Cannot create the lock file ${file}; nothing was submitted.`, { cause: error }); + } + try { + await handle.writeFile(contents); + } finally { + await handle.close(); + } + return async (): Promise => { + // Only this run's lock: if someone deleted it as stale while this run was going, + // and another run took it since, that one is not this run's to remove. + const now = await readFile(file, 'utf8').catch(() => null); + if (now === contents) { + await rm(file, { force: true }).catch(() => undefined); + } + }; +} diff --git a/src/output.ts b/src/output.ts index 20c6324..db236b1 100644 --- a/src/output.ts +++ b/src/output.ts @@ -537,6 +537,18 @@ export function recoveredRevisionLine(revision: bigint, journalFile: string): st return `Recovered revision ${revision} from the journal ${journalFile} of an interrupted run.\n`; } +/** + * @param {string} tokenFile The token file. + * @param {bigint} revisions How many revisions this run's token has. + * @returns {string} Note for stderr that another run wrote this run's revision, and more. + */ +export function alreadyHeldNote(tokenFile: string, revisions: bigint): string { + return ( + `${tokenFile} changed while this run was working, and already holds revision ${revisions}: ` + + 'another run wrote it. The file was left as it is.\n' + ); +} + const SEPARATE_LINEAGE_HINT = 'To start a separate lineage from the same document, name a different first producer ' + '(or sign with a different issuer key).'; diff --git a/tests/unit/DurableFileTest.ts b/tests/unit/DurableFileTest.ts index db7cb68..4a433ec 100644 --- a/tests/unit/DurableFileTest.ts +++ b/tests/unit/DurableFileTest.ts @@ -256,6 +256,22 @@ describe('writeFileDurably', () => { expect(await readdir(directory)).toEqual(['doc.lineage']); }); + it('replaces the file only while it still holds what the caller started from', async () => { + await writeFile(file, 'old'); + const old = new TextEncoder().encode('old'); + await writeFile(file, 'newer, by someone else'); + await expect(writeFileDurably(file, DATA, { ...replace, ifUnchanged: old })).rejects.toMatchObject({ + code: 'ECHANGED', + path: file, + }); + expect(await readFile(file, 'utf8')).toEqual('newer, by someone else'); + expect(await readdir(directory)).toEqual(['doc.lineage']); + + await writeFile(file, 'old'); + await writeFileDurably(file, DATA, { ...replace, ifUnchanged: old }); + expect(new Uint8Array(await readFile(file))).toEqual(DATA); + }); + it("keeps the file's mode", async () => { await writeFile(file, 'old'); await chmod(file, 0o640); diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 0e75cce..5f2f95a 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -123,6 +123,48 @@ class QueueingClient implements IAggregatorClient { } } +/** + * Holds a run at its first submission or its first proof lookup until released, + * so another run, or a test, can act on the token file meanwhile. + */ +class GatedClient implements IAggregatorClient { + public readonly reached: Promise; + private arrive!: () => void; + private readonly gate: Promise; + private held = false; + private open!: () => void; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly at: 'lookup' | 'submit', + ) { + this.reached = new Promise((resolve) => (this.arrive = resolve)); + this.gate = new Promise((resolve) => (this.open = resolve)); + } + + public async getInclusionProof(stateId: StateId): Promise { + await this.hold('lookup'); + return this.inner.getInclusionProof(stateId); + } + + public release(): void { + this.open(); + } + + public async submitCertificationRequest(certificationData: CertificationData): Promise { + await this.hold('submit'); + return this.inner.submitCertificationRequest(certificationData); + } + + private async hold(step: 'lookup' | 'submit'): Promise { + if (step === this.at && !this.held) { + this.held = true; + this.arrive(); + await this.gate; + } + } +} + type Lookup = (stateId: StateId) => Promise; /** Answers the n-th proof lookup with the n-th scripted answer, and the rest from the aggregator. */ @@ -234,6 +276,8 @@ describe('stampRevisionWith', () => { const text = testContext(); const finalBytes = new Uint8Array(await readFile(tokenFile)); + // Back to the copy from before the seal, as if the sealed file had never been written. + await writeFile(tokenFile, tokenBytes); expect( await stampRevisionWith( config({ digest: OTHER_DIGEST, privateKey: bob, recipientKey: null, tokenBytes }), @@ -245,6 +289,7 @@ describe('stampRevisionWith', () => { expect(text.stdout()).toContain('Revision 1 (recovered) (final)\n'); expect(text.stdout()).toContain('Next producer none; the lineage is finalized'); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(finalBytes); const attempt = stampRevisionWith( config({ privateKey: bob, tokenBytes: finalBytes }), client, @@ -264,6 +309,7 @@ describe('stampRevisionWith', () => { const tokenFile = path.join(directory, 'doc.lineage'); await stampRevisionWith(config({}), client, testContext().context); const hex = HexConverter.encode(new Uint8Array(await readFile(tokenFile))); + await writeFile(tokenFile, `${hex}\n`); await expect( stampRevisionWith( config({ privateKey: bob, tokenBytes: new TextEncoder().encode(`${hex}\n`) }), @@ -601,6 +647,112 @@ describe('stampRevisionWith', () => { expect(new Uint8Array(await readFile(tokenFile))).toEqual(genesisBytes); }); + // MastaP on PR #16: a slower run wrote its token over a file another run had moved + // on, and a revision certified and written in between vanished from it. + describe('concurrent runs', () => { + const lockFile = (): string => path.join(directory, '.doc.lineage.lock'); + + it('refuses a second append while one holds the lock, and the first completes', async () => { + const gated = new GatedClient(aggregator, 'submit'); + const slow = stampRevisionWith( + append({ quiet: true }), + new StateTransitionClient(gated), + testContext().context, + ); + await gated.reached; + expect(JSON.parse(await readFile(lockFile(), 'utf8'))).toMatchObject({ + format: 'unicity-proof/append-lock', + pid: process.pid, + }); + + const second = stampRevisionWith(append({ quiet: true }), client, testContext().context); + await expect(second).rejects.toThrow( + new RegExp( + `^Another stamp-revision run is appending to ${tokenFile} \\(pid ${process.pid} on .*\\); ` + + 'nothing was submitted\\. .*delete the lock file .*\\.doc\\.lineage\\.lock: it holds no data\\.$', + ), + ); + expect(toExitCode(await second.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await journalFiles()).toHaveLength(1); + + gated.release(); + expect(await slow).toBe(0); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('refuses, before submitting, a token file that changed since the run read it', async () => { + await stampRevisionWith(append({ quiet: true }), client, testContext().context); + const attempt = stampRevisionWith(append({ quiet: true }), client, testContext().context); + await expect(attempt).rejects.toThrow(`${tokenFile} changed since this run read it, so nothing was submitted.`); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + /** Revisions 0–2, written by a writer that ignores the lock: bob's revision 1 as `append()` makes it, then 2. */ + async function movedOn(): Promise { + const genesis = await Token.fromCBOR(genesisBytes); + const fast = { timeoutMs: 2_000 }; + const first = await appendRevision(client, aggregator.rootTrustBase, genesis, OTHER_DIGEST, bob, testKey, fast); + const second = await appendRevision( + client, + aggregator.rootTrustBase, + first, + TEST_DIGEST, + TEST_PRIVATE_KEY, + bobPublic, + fast, + ); + return second.toCBOR(); + } + const testKey = HexConverter.decode(TEST_PUBLIC_KEY_HEX); + + it("leaves a file that moved on alone when it already holds this run's revision", async () => { + const gated = new GatedClient(aggregator, 'submit'); + const sink = testContext(); + const slow = stampRevisionWith(append({ quiet: true }), new StateTransitionClient(gated), sink.context); + await gated.reached; + const newer = await movedOn(); + await writeFile(tokenFile, newer); + + gated.release(); + expect(await slow).toBe(0); + expect(sink.stderr()).toEqual( + `${tokenFile} changed while this run was working, and already holds revision 1: another run wrote it. ` + + 'The file was left as it is.\n', + ); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(newer); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it.each([ + ['its own append', 'submit'], + ['a revision recovered from a journal', 'lookup'], + ] as const)( + 'never replaces a file that changed into something else, writing %s; prints the token and keeps the journal', + async (_, at) => { + if (at === 'lookup') { + await interrupted(); + } + const gated = new GatedClient(aggregator, at); + const sink = testContext(); + const slow = stampRevisionWith(append({ quiet: true }), new StateTransitionClient(gated), sink.context); + await gated.reached; + await writeFile(tokenFile, 'replaced by hand'); + + gated.release(); + await expect(slow).rejects.toThrow( + `${tokenFile} changed while this run was working, so it was not replaced.`, + ); + expect(toExitCode(await slow.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(sink.stderr()).toContain('the revision was certified'); + expect(await readFile(tokenFile, 'utf8')).toEqual('replaced by hand'); + expect(await journalFiles()).toHaveLength(1); + expect(await readdir(directory)).not.toContain('.doc.lineage.lock'); + }, + ); + }); + it('drops a journal whose revision the token file already holds', async () => { await interrupted(); const leftover = await readFile(journal); diff --git a/tests/unit/StampRevisionWriteTest.ts b/tests/unit/StampRevisionWriteTest.ts index 272f9b0..198823b 100644 --- a/tests/unit/StampRevisionWriteTest.ts +++ b/tests/unit/StampRevisionWriteTest.ts @@ -10,13 +10,16 @@ import { tempDir } from '../support/fixtures.js'; describe('writeRevisionToken', () => { const TOKEN = new Uint8Array([0xd9, 0x01, 0x00, 0x82, 0x01, 0x02]); + const OLD = new TextEncoder().encode('old'); + const appendOverOld = { base: OLD, kind: 'append' } as const; + const newLineage = { force: false, kind: 'new' } as const; it('replaces an existing file without leaving a temporary behind', async () => { const directory = await tempDir('proof-cli-revision-'); const out = path.join(directory, 'doc.lineage'); await writeFile(out, 'old'); const sink = testContext(); - await writeRevisionToken(out, TOKEN, false, sink.context); + await writeRevisionToken(out, TOKEN, appendOverOld, sink.context); expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); expect(await readdir(directory)).toEqual(['doc.lineage']); expect(sink.stderr()).toEqual(''); @@ -27,7 +30,7 @@ describe('writeRevisionToken', () => { const out = path.join(directory, 'doc.lineage'); await writeFile(out, 'someone else'); const sink = testContext(); - await expect(writeRevisionToken(out, TOKEN, true, sink.context)).rejects.toThrow( + await expect(writeRevisionToken(out, TOKEN, newLineage, sink.context)).rejects.toThrow( /appeared while the new lineage was being certified/, ); expect(await readFile(out, 'utf8')).toEqual('someone else'); @@ -39,7 +42,7 @@ describe('writeRevisionToken', () => { const out = path.join(directory, 'doc.lineage'); await writeFile(out, 'someone else'); const sink = testContext(); - await writeRevisionToken(out, TOKEN, true, sink.context, true); + await writeRevisionToken(out, TOKEN, { force: true, kind: 'new' }, sink.context); expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); expect(sink.stderr()).toEqual(''); }); @@ -52,7 +55,7 @@ describe('writeRevisionToken', () => { await chmod(target, 0o640); const out = path.join(directory, 'doc.lineage'); await symlink(target, out); - await writeRevisionToken(out, TOKEN, false, testContext().context); + await writeRevisionToken(out, TOKEN, appendOverOld, testContext().context); expect((await lstat(out)).isSymbolicLink()).toBe(true); expect(new Uint8Array(await readFile(target))).toEqual(TOKEN); expect((await stat(target)).mode & 0o777).toBe(0o640); @@ -82,17 +85,37 @@ describe('writeRevisionToken', () => { }, }; const sink = testContext(); - await expect(writeRevisionToken(out, TOKEN, created, sink.context, false, failing)).rejects.toThrow(/ENOSPC/); + await expect( + writeRevisionToken(out, TOKEN, created ? newLineage : appendOverOld, sink.context, failing), + ).rejects.toThrow(/ENOSPC/); expect(await readdir(directory)).toEqual(left); expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); }); + it.each([ + ['holds something else', 'newer'], + ['is gone', null], + ])('leaves an append unwritten when the file %s, and says so without printing', async (_, now) => { + const directory = await tempDir('proof-cli-revision-'); + const out = path.join(directory, 'doc.lineage'); + if (now !== null) { + await writeFile(out, now); + } + const sink = testContext(); + expect(await writeRevisionToken(out, TOKEN, appendOverOld, sink.context)).toEqual('changed'); + expect(await readdir(directory)).toEqual(now === null ? [] : ['doc.lineage']); + if (now !== null) { + expect(await readFile(out, 'utf8')).toEqual(now); + } + expect(sink.stderr()).toEqual(''); + }); + it('prints the token when the directory is gone', async () => { const directory = await tempDir('proof-cli-revision-'); await mkdir(path.join(directory, 'sub')); const sink = testContext(); await expect( - writeRevisionToken(path.join(directory, 'missing', 'doc.lineage'), TOKEN, false, sink.context), + writeRevisionToken(path.join(directory, 'missing', 'doc.lineage'), TOKEN, appendOverOld, sink.context), ).rejects.toThrow(/ENOENT/); expect(sink.stderr()).toContain('the revision was certified'); expect(sink.stderr()).toContain(HexConverter.encode(TOKEN)); diff --git a/tests/unit/TokenLockTest.ts b/tests/unit/TokenLockTest.ts new file mode 100644 index 0000000..bff0818 --- /dev/null +++ b/tests/unit/TokenLockTest.ts @@ -0,0 +1,60 @@ +import { readdir, readFile, symlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +import { acquireAppendLock } from '../../src/commands/tokenLock.js'; +import { EXIT_USAGE, toExitCode } from '../../src/errors.js'; +import { tempDir } from '../support/fixtures.js'; + +describe('acquireAppendLock', () => { + let directory: string; + let tokenFile: string; + + beforeEach(async () => { + directory = await tempDir('proof-cli-lock-'); + tokenFile = path.join(directory, 'doc.lineage'); + await writeFile(tokenFile, 'token'); + }); + + it('creates a lock naming its holder next to the token file, and removes it on release', async () => { + const release = await acquireAppendLock(tokenFile); + expect(JSON.parse(await readFile(path.join(directory, '.doc.lineage.lock'), 'utf8'))).toMatchObject({ + format: 'unicity-proof/append-lock', + pid: process.pid, + }); + await release(); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + it('refuses while the lock is held, also through another path to the same file', async () => { + const release = await acquireAppendLock(tokenFile); + const other = await tempDir('proof-cli-lock-link-'); + const link = path.join(other, 'linked.lineage'); + await symlink(tokenFile, link); + for (const file of [tokenFile, link]) { + const attempt = acquireAppendLock(file); + await expect(attempt).rejects.toThrow( + new RegExp(`^Another stamp-revision run is appending to ${file} \\(pid ${process.pid} on .+, since .+\\)`), + ); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + } + expect(await readdir(other)).toEqual(['linked.lineage']); + await release(); + const again = await acquireAppendLock(link); + await again(); + }); + + it('describes a lock it cannot read without the details, and still refuses', async () => { + await writeFile(path.join(directory, '.doc.lineage.lock'), 'garbage'); + await expect(acquireAppendLock(tokenFile)).rejects.toThrow( + `Another stamp-revision run is appending to ${tokenFile}; nothing was submitted.`, + ); + }); + + it('never removes a lock that is no longer its own', async () => { + const release = await acquireAppendLock(tokenFile); + const lock = path.join(directory, '.doc.lineage.lock'); + await writeFile(lock, 'another run, after this one was deleted as stale'); + await release(); + expect(await readFile(lock, 'utf8')).toEqual('another run, after this one was deleted as stale'); + }); +}); From 8036630559139f314bcae0661711973d4b82eccb Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Tue, 24 Nov 2026 14:41:57 +0200 Subject: [PATCH 24/25] Test the refusal guard, settle's cleanup and the tolerant lookup Review on PR #16: three lines could be removed with the suite still green. - The `created` guard before removing the journal on a StampError: a re-run with the same inputs reuses an earlier run's journal, and its own refused request must not remove it. Plus the other side: a run refused after creating its journal removes it. - removeKept() in settle: journals are tried in name order, so an uncertified one could be removed by the ALREADY_CERTIFIED branch before settle ran. The test names the journals so the uncertified one sorts last, leaving settle to remove it. - The tolerant branch of recoverKept: a client certifies a rival transfer on the run's submission and then fails every lookup, so the kept journal's lookup after ALREADY_CERTIFIED fails; the run keeps the journal and still exits 1 with ALREADY_CERTIFIED. Removing each line now fails exactly its test. findJournals says that a journal's name is matched by pattern only. Co-Authored-By: Claude Opus 5.5 --- src/commands/revisionJournal.ts | 4 +- tests/unit/StampRevisionTest.ts | 123 +++++++++++++++++++++++++++++++- 2 files changed, 125 insertions(+), 2 deletions(-) diff --git a/src/commands/revisionJournal.ts b/src/commands/revisionJournal.ts index a20a174..d979092 100644 --- a/src/commands/revisionJournal.ts +++ b/src/commands/revisionJournal.ts @@ -58,7 +58,9 @@ function escapeRegExp(text: string): string { } /** - * Every journal next to the token file, in name order. + * Every journal next to the token file, in name order. A journal is matched by + * its name's pattern only; its tag is not checked against its contents, which + * are checked against the token file when it is acted on. * * @param {string} tokenFile Absolute token file path. * @returns {Promise} Journal paths. diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index 5f2f95a..ead8de1 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -1,4 +1,4 @@ -import { lstat, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'; +import { lstat, readdir, readFile, rename, rm, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { CertificationData } from '@unicitylabs/state-transition-sdk/lib/api/CertificationData.js'; @@ -16,9 +16,11 @@ import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.j import { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js'; import { SleepError } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; +import { pendingRevision, writeJournal } from '../../src/commands/revisionJournal.js'; import { networkMismatch, stampRevisionWith } from '../../src/commands/stampRevision.js'; import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; +import { StampError } from '../../src/lib/errors.js'; import { appendRevision, prepareRevision } from '../../src/lib/LineageClient.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; import { bundledTrustBase } from '../../src/lib/networks.js'; @@ -165,6 +167,47 @@ class GatedClient implements IAggregatorClient { } } +/** Refuses every request outright with a status the SDK knows, so the run gets a StampError. */ +class RefusingClient implements IAggregatorClient { + public constructor(private readonly inner: TestAggregatorClient) {} + + public getInclusionProof(stateId: StateId): Promise { + return this.inner.getInclusionProof(stateId); + } + + public submitCertificationRequest(): Promise { + return Promise.resolve(CertificationResponse.create(CertificationStatus.REQUEST_EXPIRED)); + } +} + +/** + * Lets another transfer take the slot first: on the run's submission it certifies + * `rival` directly, then passes the run's request on, which the aggregator answers + * with STATE_ID_EXISTS. Lookups pass through until `goodLookups` have been answered; + * every one after that fails, as a gateway dropping requests would. + */ +class RacingClient implements IAggregatorClient { + private lookups = 0; + + public constructor( + private readonly inner: TestAggregatorClient, + private readonly rival: CertificationData, + private readonly goodLookups: number, + ) {} + + public getInclusionProof(stateId: StateId): Promise { + this.lookups += 1; + return this.lookups > this.goodLookups + ? Promise.reject(new JsonRpcNetworkError(502, 'bad gateway')) + : this.inner.getInclusionProof(stateId); + } + + public async submitCertificationRequest(certificationData: CertificationData): Promise { + await this.inner.submitCertificationRequest(this.rival); + return this.inner.submitCertificationRequest(certificationData); + } +} + type Lookup = (stateId: StateId) => Promise; /** Answers the n-th proof lookup with the n-th scripted answer, and the rest from the aggregator. */ @@ -536,6 +579,84 @@ describe('stampRevisionWith', () => { describe('an earlier run whose outcome is not known yet', () => { const UNRESOLVED = 'submitted by an earlier run and not certified yet:'; + /** Run 1: bob's revision 1 (OTHER_DIGEST) is journaled, but its request never reaches the aggregator. */ + async function lost(): Promise { + await expect( + stampRevisionWith( + append({ quiet: true }), + new StateTransitionClient(new LostSubmitClient(aggregator)), + testContext().context, + ), + ).rejects.toThrow(/bad gateway/); + expect(await journalFiles()).toHaveLength(1); + } + + // MastaP on PR #16: nothing pinned the `created` guard before the removal on a refusal. + it("keeps an earlier run's journal for the same transfer when this run's own request is refused", async () => { + await lost(); + const [earlier] = await journalFiles(); + const attempt = stampRevisionWith( + append({ quiet: true }), + new StateTransitionClient(new RefusingClient(aggregator)), + testContext().context, + ); + await expect(attempt).rejects.toBeInstanceOf(StampError); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(3); + // The earlier request was a separate one, and may still be certified. + expect(await journalFiles()).toEqual([earlier]); + }); + + it('removes its own journal when its request is refused, having created it', async () => { + const attempt = stampRevisionWith( + append({ quiet: true }), + new StateTransitionClient(new RefusingClient(aggregator)), + testContext().context, + ); + await expect(attempt).rejects.toBeInstanceOf(StampError); + expect(await readdir(directory)).toEqual(['doc.lineage']); + }); + + // MastaP on PR #16: nothing pinned removeKept() in settle. Journals are tried in + // name order, and an uncertified one tried before the certified one is removed by + // the ALREADY_CERTIFIED branch first; here it sorts last, so only settle can remove + // it. findJournals matches names by pattern only, so a test can choose the order. + it('removes every other journal for the revision once one is recovered', async () => { + await interrupted(); + const certified = path.join(directory, '.doc.lineage.0000000000000000.pending'); + await rename(journal, certified); + const genesis = await Token.fromCBOR(genesisBytes); + const never = await prepareRevision(genesis, aggregator.rootTrustBase, TEST_DIGEST, bob, null); + await writeJournal( + path.join(directory, '.doc.lineage.ffffffffffffffff.pending'), + pendingRevision(genesis, never, TEST_DIGEST, null), + ); + expect(await journalFiles()).toHaveLength(2); + + expect(await stampRevisionWith(append({ quiet: true }), client, testContext().context)).toBe(0); + expect(await readdir(directory)).toEqual(['doc.lineage']); + expect(await revisions()).toEqual([TEST_DIGEST_HEX, OTHER_DIGEST_HEX]); + }); + + // MastaP on PR #16: nothing pinned the tolerant branch of recoverKept. After + // ALREADY_CERTIFIED, a failed lookup of a kept journal keeps that journal, and the + // run still ends with the outcome it knows, not the network error. + it('keeps a journal whose lookup fails after ALREADY_CERTIFIED, and still reports ALREADY_CERTIFIED', async () => { + await lost(); + const [earlier] = await journalFiles(); + const genesis = await Token.fromCBOR(genesisBytes); + const rival = await prepareRevision(genesis, aggregator.rootTrustBase, TEST_DIGEST, bob, null); + // Good lookups: run 1's journal at start, then the conflict lookup after STATE_ID_EXISTS. + const racing = new StateTransitionClient(new RacingClient(aggregator, rival.certificationData, 2)); + + const sink = testContext(); + const attempt = stampRevisionWith(append({ digest: TEST_DIGEST, quiet: true }), racing, sink.context); + await expect(attempt).rejects.toMatchObject({ code: 'ALREADY_CERTIFIED' }); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_VERIFICATION_FAILED); + expect(sink.stderr()).toContain(UNRESOLVED); + expect(sink.stderr()).toContain('as this run submitted it (not certified)'); + expect(await journalFiles()).toEqual([earlier]); + }); + /** Run 1: bob's revision 1 (OTHER_DIGEST) is submitted, and the run times out while it is queued. */ async function timedOut(queueing: QueueingClient): Promise { const attempt = stampRevisionWith( From 38915f91babeba7a50237e4d8ae6a79a36773c5b Mon Sep 17 00:00:00 2001 From: Ahto Truu Date: Wed, 25 Nov 2026 11:43:43 +0200 Subject: [PATCH 25/25] Clean up a failed lock, test fileHoldsRevision's verification, temper the README Review nits on PR #16: - The lock is now created with writeExclusive, so a lock whose contents cannot be written, or whose close fails, is removed again instead of refusing every later append. - A same-lineage file with the same transfers, certified on another aggregator, must not count as holding this run's revision: the run prints its token as hex, keeps its journal and exits 2. Replacing the verification with `true` fails it. The transfer-hash comparison is commented as a cheap pre-check, redundant once the file verifies. - README: the lock is what keeps other stamp-revision runs from rolling the token file back; the compare-before-replace catches a program that ignores the lock too, unless it writes between the check and the replace, since there is no atomic compare-and-replace. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/commands/durableFile.ts | 7 ++++++- src/commands/stampRevision.ts | 6 +++++- src/commands/tokenLock.ts | 23 ++++++++++++--------- tests/unit/StampRevisionTest.ts | 34 ++++++++++++++++++++++++++++++- tests/unit/TokenLockTest.ts | 36 +++++++++++++++++++++++++++++++++ 6 files changed, 94 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 9050d28..0521331 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ unicity-proof stamp-revision --file doc.pdf --token-file doc.lineage --key-file - **The token file never holds a partial token.** It is written to a temporary file next to it, fsynced, and only then put in place (linked for a new lineage, renamed over the old file for an append), and the directory is fsynced after that. A failed or interrupted write leaves the previous file, or for a new lineage no file at all. An append keeps the file's mode, and if `--token-file` is a symlink, for example into a shared or synced folder, the file it points to is updated and the link is kept. On a filesystem without hard links, a new lineage is created in place instead and removed again if the write fails; only a crash during that write can leave a partial file. If a token file is not a token, the error says how to recover: move it away and run the same command again. - `--finalize` makes this revision the final one, a *seal*: its auxiliary data is `CBOR["seal", i, SHA-256(doc_i)]` and its recipient is the burn predicate `P_burn(SHA-256(auxiliary data))`, which no key can unlock. Appending to a finalized lineage fails before contacting the gateway (exit 2). On a new lineage, `--finalize` mints revision 0 as a seal: a single-revision document that is final from the start. - **One append at a time.** An append holds a lock file next to the token file, `..lock` (after symlinks are resolved), from before it reads any journal until it has written the token file. A second append to the same file meanwhile exits 2 before submitting anything, naming the process that holds the lock. The lock is removed when the run ends, also after an error, a timeout or Ctrl-C; only a run that is killed outright, or a power loss, leaves it behind. It holds no data, so when no run is active it is always safe to delete. An append also exits 2, before submitting, if the token file changed between being read and being locked: run it again on the current file. -- **The token file is never rolled back.** An append replaces the token file only if it still holds what the run started from. If it changed meanwhile, for example because a program that ignores the lock wrote it, the file is left as it is. When it already holds this run's revision (the same lineage, verified, and the same transfer), nothing is lost: the run says so on stderr and completes. Otherwise the run prints its token as hex, keeps its journal, and exits 2. +- **Another `stamp-revision` run never rolls the token file back.** The lock makes sure of that between runs. On top of it, an append replaces the token file only if it still holds what the run started from, so a program that ignores the lock is caught too, unless it writes in the instant between that check and the replace: there is no atomic compare-and-replace. If the file changed, it is left as it is. When it already holds this run's revision (the same lineage, verified, and the same transfer), nothing is lost: the run says so on stderr and completes. Otherwise the run prints its token as hex, keeps its journal, and exits 2. - **Interrupted appends are recovered from a journal.** Before an append is submitted, the revision is recorded in a journal next to the token file, `...pending`, where the tag is the first 16 hex digits of the transfer's SHA-256 (for example `.doc.lineage.3f2a9c0e1b7d4a65.pending`), and echoed to stderr; `--quiet` leaves the echo out once the journal is written. A journal is removed only once its outcome is known: when the token file holds its revision, or when a proof that verifies shows its revision's slot holds another transfer. The aggregator keeps only a hash of each transfer, so until then the journal is the only record of what was certified; do not delete it by hand. - If the command is interrupted after submitting, running `stamp-revision` again on the same token file recovers the revision from the journal, whatever it is given this time. If the digest and recipient are the same, that completes the command. If not, the recovered revision is still written and echoed to stderr, the requested one is not appended, and the command exits 1. - Without the journal, the same command with the same file, key, digest and recipient still recovers the revision, because the state mask of each step is derived from the producer's key and the spent state. With any other digest or recipient it exits 1, saying the revision was already certified with different content, and echoes what it tried to stderr even with `--quiet`. Only the interrupted run's digest and recipient can recover it then, which is what the echo is for. diff --git a/src/commands/durableFile.ts b/src/commands/durableFile.ts index 0e118d8..b6fb325 100644 --- a/src/commands/durableFile.ts +++ b/src/commands/durableFile.ts @@ -231,7 +231,12 @@ async function publishNew( * @param {number} mode Mode to create it with, subject to the umask. * @throws {NodeJS.ErrnoException} EEXIST, carrying `file` as its path, when the name is taken. */ -async function writeExclusive(fs: IDurableFileSystem, file: string, data: Uint8Array, mode: number): Promise { +export async function writeExclusive( + fs: IDurableFileSystem, + file: string, + data: Uint8Array, + mode: number, +): Promise { let handle: IWritableFile; try { handle = await fs.openNew(file, mode); diff --git a/src/commands/stampRevision.ts b/src/commands/stampRevision.ts index 6a0a9b7..1fbee26 100644 --- a/src/commands/stampRevision.ts +++ b/src/commands/stampRevision.ts @@ -173,13 +173,17 @@ async function fileHoldsRevision(tokenFile: string, token: Token, trustBase: Roo index < 0 || !areUint8ArraysEqual(current.id.bytes, token.id.bytes) || current.transactions.length <= index || - // The same transfer: its proof may differ, served under a later root, but not what it certifies. + // A cheap pre-check: once the file verifies, it can only hold this transfer here, + // since a valid lineage has one transfer per slot. Compared by hash, because the + // copies' proofs may be served under different roots. !(await current.transactions[index].calculateTransactionHash()).equals( await token.transactions[index].calculateTransactionHash(), ) ) { return false; } + // The check that matters: a corrupted copy of the same lineage does not hold anything, + // and leaving it in place would drop this run's valid token without a trace. return (await verifyLineage(current, trustBase)).status === 'OK'; } catch { return false; diff --git a/src/commands/tokenLock.ts b/src/commands/tokenLock.ts index b53eed3..d5e631f 100644 --- a/src/commands/tokenLock.ts +++ b/src/commands/tokenLock.ts @@ -1,9 +1,10 @@ -import { open, readFile, realpath, rm } from 'node:fs/promises'; +import { readFile, realpath, rm } from 'node:fs/promises'; import { hostname } from 'node:os'; import path from 'node:path'; -import { usageError } from '../errors.js'; +import { IDurableFileSystem, NODE_FILE_SYSTEM, writeExclusive } from './durableFile.js'; import { hasErrorCode } from './revisionJournal.js'; +import { usageError } from '../errors.js'; const LOCK_FORMAT = 'unicity-proof/append-lock'; @@ -43,11 +44,19 @@ function describeHolder(text: string): string { * are resolved, so every path to the same file shares one lock. It holds no data: * it only says who holds it, and deleting it when no run is active is always safe. * + * The lock is created with {@link writeExclusive}, so a lock whose contents + * cannot be written is removed again: it is this run's, and left behind it would + * refuse every later append until someone deleted it. + * * @param {string} tokenFile Absolute token file path; it must exist. + * @param {IDurableFileSystem} [fs] File operations, for tests. * @returns {Promise<() => Promise>} Releases the lock; never fails. * @throws {CliError} If another run holds the lock, or it cannot be taken; nothing has been submitted then. */ -export async function acquireAppendLock(tokenFile: string): Promise<() => Promise> { +export async function acquireAppendLock( + tokenFile: string, + fs: IDurableFileSystem = NODE_FILE_SYSTEM, +): Promise<() => Promise> { let file: string; try { file = lockPath(await realpath(tokenFile)); @@ -61,9 +70,8 @@ export async function acquireAppendLock(tokenFile: string): Promise<() => Promis started: new Date().toISOString(), }; const contents = `${JSON.stringify(json, null, 2)}\n`; - let handle; try { - handle = await open(file, 'wx', 0o644); + await writeExclusive(fs, file, new TextEncoder().encode(contents), 0o644); } catch (error) { if (hasErrorCode(error, 'EEXIST')) { const holder = describeHolder(await readFile(file, 'utf8').catch(() => '')); @@ -75,11 +83,6 @@ export async function acquireAppendLock(tokenFile: string): Promise<() => Promis } throw usageError(`Cannot create the lock file ${file}; nothing was submitted.`, { cause: error }); } - try { - await handle.writeFile(contents); - } finally { - await handle.close(); - } return async (): Promise => { // Only this run's lock: if someone deleted it as stale while this run was going, // and another run took it since, that one is not this run's to remove. diff --git a/tests/unit/StampRevisionTest.ts b/tests/unit/StampRevisionTest.ts index ead8de1..3cfc547 100644 --- a/tests/unit/StampRevisionTest.ts +++ b/tests/unit/StampRevisionTest.ts @@ -21,7 +21,7 @@ import { networkMismatch, stampRevisionWith } from '../../src/commands/stampRevi import { IStampRevisionConfig } from '../../src/config.js'; import { EXIT_USAGE, EXIT_VERIFICATION_FAILED, toExitCode } from '../../src/errors.js'; import { StampError } from '../../src/lib/errors.js'; -import { appendRevision, prepareRevision } from '../../src/lib/LineageClient.js'; +import { appendRevision, createLineage, prepareRevision } from '../../src/lib/LineageClient.js'; import { verifyLineage } from '../../src/lib/LineageVerification.js'; import { bundledTrustBase } from '../../src/lib/networks.js'; import { @@ -828,6 +828,38 @@ describe('stampRevisionWith', () => { } const testKey = HexConverter.decode(TEST_PUBLIC_KEY_HEX); + // MastaP on PR #16: nothing pinned the verification in fileHoldsRevision. A copy of + // the same lineage, with the same transfers, whose proofs do not verify against this + // run's trust base, must not count as holding the revision. + it("does not count a same-lineage file whose proofs don't verify as holding this run's revision", async () => { + const forger = TestAggregatorClient.create(); + const forging = new StateTransitionClient(forger); + const fast = { timeoutMs: 2_000 }; + // The same genesis and revision 1 as this test's, certified elsewhere: the same token id and transfers. + const genesis = await createLineage( + forging, + forger.rootTrustBase, + TEST_DIGEST, + TEST_PRIVATE_KEY, + bobPublic, + fast, + ); + expect(genesis.id.bytes).toEqual((await Token.fromCBOR(genesisBytes)).id.bytes); + const forged = await appendRevision(forging, forger.rootTrustBase, genesis, OTHER_DIGEST, bob, testKey, fast); + + const gated = new GatedClient(aggregator, 'submit'); + const sink = testContext(); + const slow = stampRevisionWith(append({ quiet: true }), new StateTransitionClient(gated), sink.context); + await gated.reached; + await writeFile(tokenFile, forged.toCBOR()); + + gated.release(); + await expect(slow).rejects.toThrow(`${tokenFile} changed while this run was working, so it was not replaced.`); + expect(sink.stderr()).toContain('the revision was certified'); + expect(new Uint8Array(await readFile(tokenFile))).toEqual(forged.toCBOR()); + expect(await journalFiles()).toHaveLength(1); + }); + it("leaves a file that moved on alone when it already holds this run's revision", async () => { const gated = new GatedClient(aggregator, 'submit'); const sink = testContext(); diff --git a/tests/unit/TokenLockTest.ts b/tests/unit/TokenLockTest.ts index bff0818..9361f04 100644 --- a/tests/unit/TokenLockTest.ts +++ b/tests/unit/TokenLockTest.ts @@ -1,6 +1,7 @@ import { readdir, readFile, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; +import { IDurableFileSystem, IWritableFile, NODE_FILE_SYSTEM } from '../../src/commands/durableFile.js'; import { acquireAppendLock } from '../../src/commands/tokenLock.js'; import { EXIT_USAGE, toExitCode } from '../../src/errors.js'; import { tempDir } from '../support/fixtures.js'; @@ -57,4 +58,39 @@ describe('acquireAppendLock', () => { await release(); expect(await readFile(lock, 'utf8')).toEqual('another run, after this one was deleted as stale'); }); + + // MastaP on PR #16: a lock whose setup failed stayed behind and refused every later append. + it.each(['writeFile', 'close'] as const)( + 'removes the lock it created when %s fails, and says nothing was submitted', + async (step) => { + const failing: IDurableFileSystem = { + ...NODE_FILE_SYSTEM, + openNew: async (file, mode): Promise => { + const handle = await NODE_FILE_SYSTEM.openNew(file, mode); + const full = Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }); + async function writeFile(data: Uint8Array): Promise { + if (step === 'writeFile') { + throw full; + } + await handle.writeFile(data); + } + async function close(): Promise { + await handle.close(); + if (step === 'close') { + throw full; + } + } + return { close, sync: (): Promise => handle.sync(), writeFile }; + }, + }; + const attempt = acquireAppendLock(tokenFile, failing); + await expect(attempt).rejects.toThrow( + /^Cannot create the lock file .*\.doc\.lineage\.lock; nothing was submitted\.$/, + ); + expect(toExitCode(await attempt.catch((error: unknown) => error))).toBe(EXIT_USAGE); + expect(await readdir(directory)).toEqual(['doc.lineage']); + const release = await acquireAppendLock(tokenFile); + await release(); + }, + ); });