diff --git a/README.md b/README.md index 3125b50..0521331 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 | @@ -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. @@ -112,6 +114,77 @@ 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 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`, `--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 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. +- 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. 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. +- **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. + - 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)`. +- 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: + +```bash +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 +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 `--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. + ### Verify ```bash @@ -143,7 +216,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 @@ -155,8 +228,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. 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 99a4490..3c0f1bc 100644 --- a/skills/unicity-proof/SKILL.md +++ b/skills/unicity-proof/SKILL.md @@ -23,6 +23,25 @@ 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. +`matches revision 2 (the final)` means the lineage was finalized with that +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 +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. @@ -44,6 +63,37 @@ 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` 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: + 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 + 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). +- **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, + 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. @@ -58,8 +108,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. 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/cli.ts b/src/cli.ts index 4937011..a3a6213 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,12 +78,41 @@ 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; ' + + '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('--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') + .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') + .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('--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/durableFile.ts b/src/commands/durableFile.ts new file mode 100644 index 0000000..b6fb325 --- /dev/null +++ b/src/commands/durableFile.ts @@ -0,0 +1,295 @@ +import { randomBytes } from 'node:crypto'; +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}. */ +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. 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; + readFile(file: string): 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; +} + +export const NODE_FILE_SYSTEM: IDurableFileSystem = { + chmod, + link, + lstat, + openNew: (file, mode) => open(file, 'wx', mode), + readFile: async (file) => new Uint8Array(await readFile(file)), + readlink, + rename, + rm, + stat, + syncDirectory: async (directory) => { + const handle = await open(directory, 'r'); + try { + 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; + /** + * 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 + * 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' | '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']); + +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, after checking, with `ifUnchanged`, that the old + * file is still the one the caller started from. 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 a step after the create + * fails; a failed create removes nothing. Only a + * crash during that write can then leave a partial file. `createInPlace` always + * works that way, for data of which a stray second copy would be worse than 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); + 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( + (stats) => stats.mode & 0o7777, + () => undefined, + ); + } + const temporary = path.join(directory, `.${path.basename(target)}.${randomBytes(8).toString('hex')}`); + try { + await writeExclusive(fs, temporary, data, mode === undefined ? 0o666 : 0o600); + if (mode !== undefined) { + await fs.chmod(temporary, mode); + } + if (options.publish === 'replace') { + if (options.ifUnchanged !== undefined && !(await holds(fs, target, options.ifUnchanged))) { + throw fsError(CHANGED, 'file changed since it was read', target); + } + 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 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, + 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; + } + } + await createInPlace(fs, target, data, mode); +} + +/** + * Create `file` exclusively, write `data`, fsync and close it. If anything after + * the create fails, the file is removed again: this call made it. If the create + * itself fails, nothing is removed, whatever the error. A failed open does not + * mean the name was free: Linux allocates the descriptor before it looks up the + * path, so EMFILE, ENFILE or ENOMEM come back even when the file exists, and it + * may be someone's private key. + * + * @param {IDurableFileSystem} fs File operations. + * @param {string} file Path to create. + * @param {Uint8Array} data Contents. + * @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. + */ +export async function writeExclusive( + fs: IDurableFileSystem, + file: string, + data: Uint8Array, + mode: number, +): 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. + * @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 { + await writeExclusive(fs, target, data, mode === undefined ? 0o666 : 0o600); + if (mode === undefined) { + return; + } + try { + await fs.chmod(target, mode); + } catch (error) { + // The create succeeded, so the file is this call's. + await fs.rm(target, { force: true }).catch(() => undefined); + throw error; + } +} diff --git a/src/commands/inspect.ts b/src/commands/inspect.ts index 22c3494..0a137dd 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/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/keygen.ts b/src/commands/keygen.ts index 1008027..198fa37 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,41 @@ 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. + * 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. * - * 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. + * 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. * - * @param {string} out Absolute destination path. - * @param {string} contents Key file contents. - */ -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. + * 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} file Path to create; must not exist. + * @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 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' : 'createInPlace', + }); } /** * `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 +70,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/revisionJournal.ts b/src/commands/revisionJournal.ts new file mode 100644 index 0000000..d979092 --- /dev/null +++ b/src/commands/revisionJournal.ts @@ -0,0 +1,305 @@ +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'; +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; +} + +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. + * @param {Uint8Array} transaction The journaled transfer, CBOR-encoded. + * @returns {string} Its journal next to the token file: `...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. 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. + * @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)); +} + +/** + * @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(), + }; +} + +/** + * @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; +} + +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. + * @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 { + 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, + }; + 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 { + try { + await handle.writeFile(`${JSON.stringify(json, null, 2)}\n`); + await handle.sync(); + } finally { + 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 }); + } + 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. + } + return true; +} + +/** + * @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 new file mode 100644 index 0000000..1fbee26 --- /dev/null +++ b/src/commands/stampRevision.ts @@ -0,0 +1,640 @@ +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'; +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 { 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 { CHANGED, IDurableFileSystem, NODE_FILE_SYSTEM, writeFileDurably } from './durableFile.js'; +import { + findJournals, + hasErrorCode, + IPendingRevision, + journalPath, + journalStanding, + pendingRevision, + readJournal, + removeJournal, + 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'; +import { + assertValidLineage, + certifyRevision, + createOrRecoverLineage, + currentProducerKey, + findSuccessor, + isSameRevision, + LineageError, + prepareRevision, + 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, + pendingRevisionLines, + recoveredRevisionLine, + revisionJson, + revisionRecoveryLines, + revisionText, + supersededLineageMessage, + toJsonLine, + 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 }, + ); +} + +/** Where a token goes: a new lineage's file, or over the token file this run started from. */ +export type RevisionTarget = + | { readonly force: boolean; readonly kind: 'new' } + /** `base`: the token file's bytes as this run read them. */ + | { readonly base: Uint8Array; readonly kind: 'append' }; + +/** + * Persist a lineage token whose newest revision has already been certified, with + * {@link writeFileDurably}: the token file never holds a partial token, a + * replaced one keeps its mode, and once this returns the write survives a power + * loss. The file is the only copy of every revision's transaction, so an append + * writes through a symlink at the path rather than replacing the symlink: a link + * into a shared folder keeps working. + * + * A new lineage is linked into place, so a file that appeared since the checks is + * never clobbered, nor a symlink to a missing file written through, unless + * `--force`, which replaces the one and writes through the other. An append + * replaces the file only if it still holds `base`; otherwise it is left alone, and + * the caller decides what that means. Whatever else 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 {RevisionTarget} target A new lineage, or an append and the file it started from. + * @param {ICommandContext} context Streams. + * @param {IDurableFileSystem} [fs] File operations, for tests. + * @returns {Promise<'changed'|'written'>} `changed` when an append found the file no longer holding `base`. + */ +export async function writeRevisionToken( + tokenFile: string, + bytes: Uint8Array, + target: RevisionTarget, + context: ICommandContext, + fs: IDurableFileSystem = NODE_FILE_SYSTEM, +): Promise<'changed' | 'written'> { + const exclusive = target.kind === 'new' && !target.force; + try { + await writeFileDurably( + tokenFile, + bytes, + { + 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')) { + throw await tokenFileInTheWay(tokenFile, error); + } + throw error; + } +} + +/** + * 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 || + // 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; + } +} + +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 { + /** 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; +} + +/** 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. + * + * 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`, + * 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. + * @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; + // 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 => { + 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 persist(recovered); + 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, entry.pending, entry.file, 'recovered'); + throw recoveredOtherRevision(entry.pending.revision, recovered, config.tokenFile); + }; + + // 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, entry.transaction, options); + } catch (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) { + kept.delete(entry.file); + return settle(entry, recovered); + } + } + 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); + 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'); + } + + let appended: Token; + let replayed = false; + try { + appended = await certifyRevision(client, trustBase, token, prepared, { + ...options, + onAlreadyCertified: (): void => { + replayed = true; + }, + }); + } catch (error) { + if (error instanceof StampError) { + // 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'); + // 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; + } + + await persist(appended); + await removeJournal(journalFile); + await removeKept(); + 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 { + 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. + * + * @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; + let signer = new SigningService(config.privateKey).publicKey; + let recovered: boolean; + const created = config.tokenBytes === null; + if (config.tokenBytes === null) { + ({ 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(), { 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)); + } + } else { + const decoded = await decodeToken(tokenBytesFromInput(config.tokenBytes)); + if (decoded.token === null) { + 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( + config.tokenFile, + decoded.token.networkId.id, + trustBase.networkId.id, + config.trustBasePath, + ); + if (mismatch !== null) { + throw mismatch; + } + 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); + 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, + recovered, + referenceTime: latest.referenceTime, + revision: BigInt(token.transactions.length), + roundNumber: certificate.inputRecord.roundNumber, + roundTimestamp: certificate.inputRecord.timestamp, + signer, + 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/commands/tokenLock.ts b/src/commands/tokenLock.ts new file mode 100644 index 0000000..d5e631f --- /dev/null +++ b/src/commands/tokenLock.ts @@ -0,0 +1,94 @@ +import { readFile, realpath, rm } from 'node:fs/promises'; +import { hostname } from 'node:os'; +import path from 'node:path'; + +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'; + +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. + * + * 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, + fs: IDurableFileSystem = NODE_FILE_SYSTEM, +): 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`; + try { + await writeExclusive(fs, file, new TextEncoder().encode(contents), 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 }); + } + 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/commands/verify.ts b/src/commands/verify.ts index e263100..6e7c5dd 100644 --- a/src/commands/verify.ts +++ b/src/commands/verify.ts @@ -1,7 +1,14 @@ 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 { describeToken, @@ -9,11 +16,12 @@ 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; readonly hash?: string; + readonly tokenId?: string; } function report( @@ -25,9 +33,22 @@ 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, 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. @@ -39,22 +60,40 @@ 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) { return reportNotAToken(context, 'verify', decoded.error); } 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) { 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', + tokenIdMatches: null, + }, + null, + ); + } + return report(context, verificationFailure(describeToken(token), reason), null); } choice = { source: { kind: 'bundled', network: name }, @@ -63,5 +102,12 @@ 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, 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 28e688b..404e8fc 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. @@ -440,3 +449,217 @@ 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 finalize?: boolean; + readonly force?: boolean; + readonly keyFile?: string; + readonly quiet?: boolean; + readonly recipientKey?: string; + readonly recipientKeyFile?: string; + readonly timeout?: string; + readonly tokenFile?: string; +} + +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; + /** 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. + */ + 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; + /** 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. */ +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; +} + +/** + * 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'); + } + const recipientKeyFile = flags.recipientKeyFile as string; + let contents: string; + try { + contents = await readFile(recipientKeyFile, 'utf8'); + } catch (error) { + throw usageError(`Cannot read recipient key file ${recipientKeyFile}.`, { cause: error }); + } + return parsePublicKey(contents, `Recipient key file ${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); + 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 { + 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; + const quiet = flags.quiet ?? false; + const trustBasePath = selection.trustBasePath === undefined ? null : path.resolve(selection.trustBasePath); + return { + allowInsecure, + apiKey, + digest, + force, + network, + privateKey, + quiet, + recipientKey, + timeoutMs, + tokenBytes, + tokenFile, + trustBasePath, + }; +} diff --git a/src/errors.ts b/src/errors.ts index f31e8ec..8dac434 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -5,9 +5,10 @@ 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/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; @@ -69,6 +70,11 @@ 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' || 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 new file mode 100644 index 0000000..f270908 --- /dev/null +++ b/src/lib/LineageClient.ts @@ -0,0 +1,632 @@ +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'; +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'; +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 { + 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'; +import { + LINEAGE_TAG, + LINEAGE_TOKEN_TYPE, + LineageGenesisReason, + LineageRevision, + sealPredicate, +} from './LineagePayload.js'; +import { createLineageVerificationContext, verifyLineage } from './LineageVerification.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 { + public constructor( + 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; + * `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' | 'SUPERSEDED' | '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; + } +} + +/** + * 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 + * 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); +} + +/** + * 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. + * + * @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. 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. + * + * 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. + * @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. + */ +export async function createLineage( + client: StateTransitionClient, + trustBase: RootTrustBase, + digest: Uint8Array, + issuerPrivateKey: Uint8Array, + 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); + const tokenId = await TokenId.fromSalt(trustBase.networkId, salt); + const reason = await LineageGenesisReason.sign( + tokenId, + LINEAGE_TOKEN_TYPE, + encodedRecipient, + auxData, + new SigningService(issuerPrivateKey), + ); + 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); + 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' }; +} + +/** + * 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 + * 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 { + await assertValidLineage(token, trustBase); + 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( + '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', + ); + } +} + +/** 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; +} + +/** + * 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 {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. + * @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 prepareRevision( + token: Token, + trustBase: RootTrustBase, + digest: Uint8Array, + producerPrivateKey: Uint8Array, + nextProducer: Uint8Array | null, +): Promise { + const signer = new SigningService(producerPrivateKey); + await assertCanAppend(token, trustBase, signer.publicKey); + + const index = nextRevisionIndex(token); + const { auxData, recipient } = await revisionStep(index, digest, nextProducer); + const transaction = await TransferTransaction.create( + token, + recipient, + await deriveStateMask(producerPrivateKey, token), + { data: auxData }, + ); + const certificationData = await CertificationData.fromTransaction( + 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 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; +} + +/** + * 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/LineagePayload.ts b/src/lib/LineagePayload.ts new file mode 100644 index 0000000..34aa19e --- /dev/null +++ b/src/lib/LineagePayload.ts @@ -0,0 +1,329 @@ +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 { 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'; +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.`); + } +} + +/** First element of a seal payload, marking the revision as final. */ +export const LINEAGE_SEAL_MARKER = 'seal'; + +/** + * 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); + } + + /** @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. + * @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, sealed = false): LineageRevision { + if (index < 0n) { + throw new LineageFormatError(`Revision index must not be negative, got ${index}.`); + } + assertDigest(digest); + return new LineageRevision(index, digest, sealed); + } + + /** + * 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; + let sealed: boolean; + try { + 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] or ["${LINEAGE_SEAL_MARKER}", index, digest].`, + { cause: error }, + ); + } + assertDigest(digest); + const revision = new LineageRevision(index, digest, sealed); + assertCanonical(bytes, revision.toCBOR(), 'Revision payload'); + return revision; + } + + /** @returns {Uint8Array} CBOR encoding. */ + public toCBOR(): Uint8Array { + 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, recipient, 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". It covers the genesis recipient, so the + * producer of revision 1 (or, for a lineage finalized at genesis, the burn) is + * named with the issuer's authority, like every later successor is named by its + * predecessor: whoever submits the mint cannot substitute another. The recipient + * is not repeated in the reason; it is read from the mint transaction. + */ +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 {EncodedPredicate} recipient Recipient predicate of the mint. + * @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, + recipient: EncodedPredicate, + auxData: Uint8Array, + issuer: SigningService, + ): Promise { + 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, 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, + recipient: EncodedPredicate, + 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), + recipient.toCBOR(), + 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 {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, + recipient: EncodedPredicate, + auxData: Uint8Array, + ): Promise { + return SigningService.verifyWithPublicKey( + await LineageGenesisReason.signedMessage(tokenId, tokenType, recipient, auxData), + this.signature, + this._issuer, + ); + } +} diff --git a/src/lib/LineageVerification.ts b/src/lib/LineageVerification.ts new file mode 100644 index 0000000..ee7d595 --- /dev/null +++ b/src/lib/LineageVerification.ts @@ -0,0 +1,417 @@ +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'; +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'; +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 { errorMessage } from './errors.js'; +import { + LINEAGE_GENESIS_REASON_TAG, + LINEAGE_TOKEN_TYPE, + LineageGenesisReason, + LineageRevision, + sealPredicate, +} from './LineagePayload.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; 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'; + + /** @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, over the mint's own id, type, recipient and auxData. */ +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, transaction.recipient, 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 { + /** + * 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; + 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; + /** 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 + * when that is not a readable `P_sig` key. + */ + readonly signer: Uint8Array | null; +} + +/** 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; + readonly tokenTypeIsLineage: boolean; +} + +function signaturePredicateKey(predicate: EncodedPredicate): Uint8Array | null { + try { + return SignaturePredicate.fromPredicate(predicate).publicKey; + } catch { + return 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, + roundNumber: certificate.inputRecord.roundNumber, + roundTimestamp: certificate.inputRecord.timestamp, + signer, + }; + if (transaction.data === 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, sealed: revision.sealed }; + } catch (error) { + return { ...common, digest: null, error: errorMessage(error), index: null, sealed: false }; + } +} + +/** + * 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; + } + } + const revisions = [describeRevision(token.genesis, issuer)]; + for (const transaction of token.transactions) { + revisions.push(describeRevision(transaction, revisions[revisions.length - 1].nextProducer)); + } + return { + finalized: revisions[revisions.length - 1].sealed, + issuer, + 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; + /** + * 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 { + 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'; + /** + * Whether the token id is the expected one; null when no id was given or the + * comparison was not reached. + */ + readonly tokenIdMatches: boolean | null; +} + +/** + * 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. + */ +async function chainRules(description: ILineageDescription): Promise { + const results: Result[] = []; + 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}`)); + 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`, + 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); +} + +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 ''; + } + 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, 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 token id and digest. + * @returns {Promise} Outcome. + */ +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', + tokenIdMatches: null, + }; + } + if (token.networkId.id !== trustBase.networkId.id) { + 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', + 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', + tokenIdMatches: null, + }; + } + + 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/lib/TimestampClient.ts b/src/lib/TimestampClient.ts index 1201a35..76d396f 100644 --- a/src/lib/TimestampClient.ts +++ b/src/lib/TimestampClient.ts @@ -2,16 +2,25 @@ 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 { 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'; @@ -20,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}. */ @@ -39,28 +53,160 @@ 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'; /** - * Submit a mint transaction and wait for its inclusion proof. + * 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 {MintTransaction} transaction Transaction to certify. + * @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, + expiresAt: bigint | null, + ): Promise => + ( + await InclusionProofVerificationRule.verify( + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + certified, + transactionHash, + expiresAt, + transaction.lockScript, + transaction.sourceStateHash, + ) + ).status; + + 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, certified.certificationData.expiresAt)) === + InclusionProofVerificationStatus.OK + ) { + throw new StateAlreadyCertifiedError(certified); + } + 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. + * + * `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. 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. + * + * @param {StateTransitionClient} client Aggregator client. + * @param {VerificationContext} context Verification context for the network behind the client. + * @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. + * @throws {StateAlreadyCertifiedError} If the state was certified with another transaction. + * @throws {SleepError} If the proof does not arrive before the timeout or abort, + * including while a lookup is in flight. */ -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, - }); - if (response.status !== SUCCESS_STATUS) { +): 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 lookUp(); + if (proof !== null) { + options.onAlreadyCertified?.(); + return proof; + } + } else if (response.status !== SUCCESS_STATUS) { if (KNOWN_STATUSES.includes(response.status)) { throw new StampError(response.status); } @@ -69,20 +215,57 @@ export async function certifyMintTransaction( ); } - const signals = [AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)]; - if (options.signal) { - signals.push(options.signal); + try { + const proof = await waitInclusionProof( + client, + context.trustBase, + context.predicateVerifier, + context.unicityCertificateVerifier, + transaction, + deadline, + 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 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 lookUp(); + } + throw error; } - const proof = await waitInclusionProof( +} + +/** + * 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.trustBase, - context.predicateVerifier, - context.unicityCertificateVerifier, + context, + await CertificationData.fromMintTransaction(transaction), transaction, - AbortSignal.any(signals), - options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS, + options, ); - return transaction.toCertifiedTransaction( context.trustBase, context.predicateVerifier, 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 15a7e95..db236b1 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/LineageVerification.js'; import { networkNameForId, TrustBaseSource } from './lib/networks.js'; import { ITimestampDescription, ITimestampVerificationResult } from './lib/TimestampVerification.js'; @@ -363,3 +368,468 @@ 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; + /** 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; + readonly roundTimestamp: bigint; + readonly signer: Uint8Array; + readonly tokenFile: string; + readonly tokenId: Uint8Array; +} + +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 }; + /** 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; + 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} 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}${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)), + 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)}${summary.created ? ' (identifies this lineage; give it to verifiers)' : ''}`, + ), + 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, + 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: summary.nextProducer === null ? null : HexConverter.encode(summary.nextProducer), + recovered: summary.recovered, + 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), + }; +} + +/** 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; + * `unresolved` when an earlier run submitted it and it is not certified yet, but + * may still be. + */ +export type PendingRevisionContext = 'recovered' | 'rejected' | 'submitting' | 'unresolved'; + +/** + * 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)}:`, + unresolved: `Revision ${note.revision} of lineage ${HexConverter.encode(note.tokenId)}, submitted by an earlier run and not certified yet:`, + }[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.', + ); + } 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`; +} + +/** + * @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`; +} + +/** + * @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).'; + +/** + * 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. + * + * @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'); +} + +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 }; + /** 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; null when finalized. */ + 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; + /** 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; + readonly status: 'FAIL' | 'OK'; + readonly trustBase: ITrustBaseJson | null; +} + +export interface ILineageInspectJson extends ILineageDescriptionJson { + readonly command: 'inspect'; + 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; +} + +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}${revision.sealed ? ' (final)' : ''}`, + ), + line(' Signed by', keyLabel(revision.signer, 'not a signature predicate key')), + 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})`), + ]; +} + +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), description.finalized ? FINALIZED_LABEL : 'not a signature predicate'), + ), + ]; + description.revisions.forEach((revision, position) => { + lines.push('', ...lineageRevisionLines(revision, position)); + }); + return lines; +} + +// 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 lineageComparisonsReached(result) + ? '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(', ')}`; + if (last !== latest) { + return `${which}; superseded by revision ${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 +// 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. + * @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)), + line('Lineage id', lineageIdLabel(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(), + }, + sealed: revision.sealed, + 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 { + 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), + 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, + expectedTokenIdMatches: result.tokenIdMatches, + 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/support/LineageFixtures.ts b/tests/support/LineageFixtures.ts new file mode 100644 index 0000000..0bc1bcd --- /dev/null +++ b/tests/support/LineageFixtures.ts @@ -0,0 +1,69 @@ +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 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; + 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), sealed, sealedFile, token, tokenFile, trustBaseFile }; +} 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/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/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/ConfigTest.ts b/tests/unit/ConfigTest.ts index 63595c7..cf98b83 100644 --- a/tests/unit/ConfigTest.ts +++ b/tests/unit/ConfigTest.ts @@ -10,16 +10,26 @@ import { parseDigest, parseNetworkName, parsePrivateKey, + parsePublicKey, + parseTokenId, 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', () => { @@ -34,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); @@ -45,6 +69,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 +378,131 @@ 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'); + expect(config.quiet).toBe(false); + 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'); + 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'); + 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/DurableFileTest.ts b/tests/unit/DurableFileTest.ts new file mode 100644 index 0000000..4a433ec --- /dev/null +++ b/tests/unit/DurableFileTest.ts @@ -0,0 +1,330 @@ +import { chmod, lstat, readdir, readFile, readlink, stat, symlink, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +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'); + +function errno(code: string): NodeJS.ErrnoException { + return Object.assign(new Error(code), { code }); +} + +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, + openNew: async (file, mode): Promise => { + const handle = await NODE_FILE_SYSTEM.openNew(file, mode); + if (!fail(file)) { + 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(); + } + 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. */ +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('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, + openNew: (name, mode) => { + created.push(name); + return NODE_FILE_SYSTEM.openNew(name, 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']); + }); + }); + + // 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; + + 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('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); + 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/ErrorsTest.ts b/tests/unit/ErrorsTest.ts index ab48184..7c97958 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,11 @@ 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], + ['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], ['file exists', errno('EEXIST', '/x'), 2], ['anything else', new Error('?'), 2], diff --git a/tests/unit/InspectTest.ts b/tests/unit/InspectTest.ts new file mode 100644 index 0000000..1ba41d3 --- /dev/null +++ b/tests/unit/InspectTest.ts @@ -0,0 +1,217 @@ +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 { + describeLineage, + ILineageDescription, + ILineageRevisionDescription, +} from '../../src/lib/LineageVerification.js'; +import { describeToken } from '../../src/lib/TimestampVerification.js'; +import { + descriptionJson, + ILineageRevisionJson, + inspectText, + lineageDescriptionJson, + lineageInspectJson, + lineageInspectText, +} from '../../src/output.js'; +import { testContext } from '../support/context.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'; + +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 }); + }); +}); + +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)'); + }); +}); + +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/KeygenTest.ts b/tests/unit/KeygenTest.ts index 39e70f5..e463bf2 100644 --- a/tests/unit/KeygenTest.ts +++ b/tests/unit/KeygenTest.ts @@ -1,7 +1,8 @@ -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'; +import { keygenJson, keygenText } from '../../src/output.js'; import { testContext } from '../support/context.js'; import { tempDir } from '../support/fixtures.js'; @@ -37,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; @@ -63,3 +80,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/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 new file mode 100644 index 0000000..3cfc547 --- /dev/null +++ b/tests/unit/StampRevisionTest.ts @@ -0,0 +1,1265 @@ +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'; +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'; +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'; +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, createLineage, prepareRevision } from '../../src/lib/LineageClient.js'; +import { verifyLineage } from '../../src/lib/LineageVerification.js'; +import { bundledTrustBase } from '../../src/lib/networks.js'; +import { + existingLineageNote, + IRevisionSummary, + pendingRevisionLines, + recoveredRevisionLine, + revisionJson, + revisionRecoveryLines, + revisionText, + supersededLineageMessage, +} from '../../src/output.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 { 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. */ +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); + } +} + +/** 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); + } +} + +/** + * 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; + } + } +} + +/** 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. */ +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; + // 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-'); + }); + + function config(overrides: Partial): IStampRevisionConfig { + return { + 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, + recipientKey: bobPublic, + timeoutMs: 2_000, + tokenBytes: null, + tokenFile: path.join(directory, 'doc.lineage'), + trustBasePath: null, + ...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), + recovered: false, + revision: '0', + signer: TEST_PUBLIC_KEY_HEX, + tokenFile, + }); + expect(first.stderr()).toEqual(''); + + 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('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)); + // 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 }), + client, + text.context, + ), + ).toBe(0); + // 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'); + + expect(new Uint8Array(await readFile(tokenFile))).toEqual(finalBytes); + 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); + 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`) }), + 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); + }); + + 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; + let genesisBytes: Uint8Array; + + beforeEach(async () => { + tokenFile = path.join(directory, 'doc.lineage'); + // 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)); + }); + + /** 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/); + 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) => + 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()).toMatch(/Journal {8}\S+\/\.doc\.lineage\.[0-9a-f]{16}\.pending\n/); + 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 (recovered)\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]); + }); + + 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( + 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('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); + }); + + // 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); + + // 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(); + 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); + 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.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('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(); + 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 () => { + const attempt = stampRevisionWith( + config({ tokenBytes: new TextEncoder().encode('hello') }), + client, + testContext().context, + ); + 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); + }); +}); + +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, + recovered: false, + 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', () => { + 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'); + 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), + recovered: false, + 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', + ); + }); + + 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, + 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/StampRevisionWriteTest.ts b/tests/unit/StampRevisionWriteTest.ts new file mode 100644 index 0000000..198823b --- /dev/null +++ b/tests/unit/StampRevisionWriteTest.ts @@ -0,0 +1,123 @@ +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 { 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'; + +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, appendOverOld, 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, newLineage, 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, { force: true, kind: 'new' }, sink.context); + expect(new Uint8Array(await readFile(out))).toEqual(TOKEN); + 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, 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); + }); + + 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: IDurableFileSystem = { + ...NODE_FILE_SYSTEM, + 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(); + 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, 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/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/TokenLockTest.ts b/tests/unit/TokenLockTest.ts new file mode 100644 index 0000000..9361f04 --- /dev/null +++ b/tests/unit/TokenLockTest.ts @@ -0,0 +1,96 @@ +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'; + +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'); + }); + + // 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(); + }, + ); +}); diff --git a/tests/unit/VerifyTest.ts b/tests/unit/VerifyTest.ts index 937ddea..90877c1 100644 --- a/tests/unit/VerifyTest.ts +++ b/tests/unit/VerifyTest.ts @@ -2,13 +2,26 @@ 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'; 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 { describeLineage, ILineageVerificationResult } from '../../src/lib/LineageVerification.js'; import { stampWith } from '../../src/lib/TimestampClient.js'; +import { verify } from '../../src/lib/TimestampVerification.js'; +import { lineageVerifyJson, lineageVerifyText, verifyJson, verifyText } from '../../src/output.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'; +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. @@ -36,9 +49,369 @@ 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), ).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'); + 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 () => { + 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 in this file)\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, + }); + }); +}); + +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', + }); + }); +}); + +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', + tokenIdMatches: null, + ...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 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 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`); + }); + + 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.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, + matchingRevisions: [], + }); + expect(lineageVerifyJson(result({ matchingRevisions: [0, 2] }), bundled)).toMatchObject({ + expectedHashMatches: true, + matchingRevisions: [0, 2], + }); + }); +}); diff --git a/tests/unit/lib/LineageClientTest.ts b/tests/unit/lib/LineageClientTest.ts new file mode 100644 index 0000000..02c8b0e --- /dev/null +++ b/tests/unit/lib/LineageClientTest.ts @@ -0,0 +1,505 @@ +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'; +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 { 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 { SleepError } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.js'; + +import { StateAlreadyCertifiedError } from '../../../src/lib/errors.js'; +import { + appendRevision, + certifyRevision, + createLineage, + createOrRecoverLineage, + currentProducerKey, + deriveGenesisSalt, + findSuccessor, + isFinalized, + isSameRevision, + LineageError, + prepareRevision, + recoverRevision, +} from '../../../src/lib/LineageClient.js'; +import { LINEAGE_TOKEN_TYPE_HEX, LineageRevision } from '../../../src/lib/LineagePayload.js'; +import { createLineageVerificationContext, verifyLineage } from '../../../src/lib/LineageVerification.js'; +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. */ +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); + } +} + +/** + * 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)); + } +} + +/** 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. + 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(); + 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('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 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 () => { + 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); + await expect( + appendRevision(client, trustBase, genesis, THIRD_DIGEST, bob, publicKey(carol), fast), + ).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' }); + }); + + // 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); + 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); + 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())); + }); + }); +}); diff --git a/tests/unit/lib/LineagePayloadTest.ts b/tests/unit/lib/LineagePayloadTest.ts new file mode 100644 index 0000000..630f6e7 --- /dev/null +++ b/tests/unit/lib/LineagePayloadTest.ts @@ -0,0 +1,145 @@ +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', () => { + 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, 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', () => { + 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..6e9ef6b --- /dev/null +++ b/tests/unit/lib/LineageVerificationTest.ts @@ -0,0 +1,410 @@ +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 { + LINEAGE_TOKEN_TYPE, + LineageGenesisReason, + LineageRevision, + sealPredicate, +} from '../../../src/lib/LineagePayload.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'; + +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 carol = 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 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, + EncodedPredicate.fromPredicate(signedRecipient), + 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 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(), + }); + 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('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 }); + 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.'); + }); + }); + + 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); + 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); + expect(description.tokenTypeIsLineage).toBe(true); + expect(description.finalized).toBe(false); + expect(description.revisions).toHaveLength(1); + expect(description.revisions[0].error).toBeNull(); + }); +});