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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,47 @@ unicity-proof stamp --file document.pdf --gateway http://localhost:3000 --allow-

The testnet2 key above is the shared public demo key published in the [sphere-sdk README](https://github.com/unicity-sphere/sphere-sdk/blob/main/README.md#api-key), where it is documented as public rather than secret; capacity is shared, so get your own key for sustained use. Trust bases for mainnet and testnet2 ship inside the package. The CLI never downloads a trust base at run time.

### Library

The package is importable as well as runnable. Verification has its own entry
point that cannot reach a gateway: no aggregator client, no JSON-RPC transport,
and no `node:` import anywhere in its module graph — 80 modules against the 137
behind the package root, and nothing that can open a socket or read a file, which
is what a browser bundle needs.

```js
import { readFile } from 'node:fs/promises';

import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js';
import { bundledTrustBase, networkNameForId, verify } from '@unicitylabs/proof-cli/verify';

const token = await Token.fromCBOR(new Uint8Array(await readFile('document.cbor')));
const network = networkNameForId(token.networkId.id);
if (network === undefined) {
throw new Error(`No bundled trust base for network ${token.networkId.id}.`);
}

// digest is the document's own SHA-256. Without it the result says only that
// some hash was certified, not that it was yours.
const result = await verify(token, bundledTrustBase(network), { expectedDigest: digest });
console.log(result.status, result.reason, result.referenceTime);
```

Stamping needs a gateway and an API key, so it lives at the package root, which
re-exports everything above:

```js
import { resolveNetwork, stamp } from '@unicitylabs/proof-cli';

const token = await stamp(digest, resolveNetwork({ network: 'testnet2' }), process.env.UNICITY_API_KEY);
```

Those two entry points are the whole public API; Node refuses deep imports into
the implementation. Anything they do not export is internal and may change in any
release. `tests/unit/PublicApiTest.ts` pins both export lists, and fails if a
module in this package starts importing from `node:` or if the verification entry
point gains a path to the aggregator.

## What a stamp proves

A verified token shows that a transaction containing your hash was certified by the Unicity Network in a specific round, and records the round's reference time, which is at or before the consensus-signed round timestamp. If the stamp is signed, it also shows that the holder of the printed key signed the hash, and that this signature existed no later than the certified time.
Expand Down
10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
},
"exports": {
".": {
"types": "./lib/lib/index.d.ts",
"default": "./lib/lib/index.js"
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"./verify": {
"types": "./lib/verify.d.ts",
"default": "./lib/verify.js"
}
},
"files": [
Expand All @@ -19,7 +23,7 @@
"README.md"
],
"scripts": {
"build": "tsc --project tsconfig.build.json",
"build": "node -e \"require('node:fs').rmSync('lib', { force: true, recursive: true })\" && tsc --project tsconfig.build.json",
"build:check": "tsc --noEmit",
"lint": "eslint \"src/**/*\" \"tests/**/*\"",
"lint:fix": "eslint \"src/**/*\" \"tests/**/*\" --fix",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/inspect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ICommandContext } from './context.js';
import { decodeToken, readTokenInput, reportNotAToken } from './tokenInput.js';
import { EXIT_OK } from '../errors.js';
import { describeToken } from '../lib/TimestampClient.js';
import { describeToken } from '../lib/TimestampVerification.js';
import { inspectJson, inspectText, toJsonLine } from '../output.js';

/**
Expand Down
3 changes: 2 additions & 1 deletion src/commands/stamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import path from 'node:path';
import { ICommandContext } from './context.js';
import { IStampFlags, resolveStampConfig } from '../config.js';
import { EXIT_OK } from '../errors.js';
import { describeToken, stamp } from '../lib/TimestampClient.js';
import { stamp } from '../lib/TimestampClient.js';
import { describeToken } from '../lib/TimestampVerification.js';
import { recoveryLines, stampJson, stampText, toJsonLine, warningLine } from '../output.js';

/**
Expand Down
7 changes: 6 additions & 1 deletion src/commands/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ 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 { bundledTrustBase, ITrustBaseChoice, networkNameForId, TrustBaseSource } from '../lib/networks.js';
import { describeToken, ITimestampVerificationResult, verificationFailure, verify } from '../lib/TimestampClient.js';
import {
describeToken,
ITimestampVerificationResult,
verificationFailure,
verify,
} from '../lib/TimestampVerification.js';
import { toJsonLine, verifyJson, verifyText } from '../output.js';

export interface IVerifyFlags extends INetworkFlags {
Expand Down
39 changes: 36 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,16 @@ import { access, readFile } from 'node:fs/promises';
import path from 'node:path';
import { pipeline } from 'node:stream/promises';

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 { HexConverter } from '@unicitylabs/state-transition-sdk/lib/util/HexConverter.js';

import { usageError } from './errors.js';
import {
bundledTrustBase,
INetworkSelection,
isNetworkName,
ITimestampNetwork,
ITrustBaseChoice,
loadTrustBase,
NETWORK_NAMES,
NetworkName,
resolveNetwork,
Expand All @@ -34,6 +33,20 @@ export interface INetworkFlags {
readonly trustBase?: string;
}

/**
* A network choice as the command line expresses it, with the trust base still a
* path. The library takes a parsed trust base instead, so {@link loadTrustBase}
* sits between this and {@link resolveNetwork}.
*/
export interface INetworkSelection {
/** Overrides the preset gateway. */
readonly gatewayUrl?: string;
/** Defaults to mainnet. */
readonly network?: NetworkName;
/** Path to a trust base JSON file that replaces the bundled one. */
readonly trustBasePath?: string;
}

export interface IStampFlags extends INetworkFlags {
readonly allowInsecure?: boolean;
readonly anonymous?: boolean;
Expand Down Expand Up @@ -189,6 +202,21 @@ export async function resolveDigest(
return file === undefined ? undefined : await hashFile(file);
}

/**
* Read and parse a trust base file.
*
* The library reads no files, so this lives here: a `--trust-base` path is a
* command-line concept, and keeping the read in the CLI leaves the verification
* path able to run where there is no filesystem.
*
* @param {string} file Path to a trust base JSON file.
* @returns {Promise<RootTrustBase>} Parsed trust base.
* @throws {Error} If the file cannot be read or is not a trust base.
*/
export async function loadTrustBase(file: string): Promise<RootTrustBase> {
return RootTrustBase.fromJSON(JSON.parse(await readFile(file, 'utf8')));
}

/**
* Network selection for stamping: flags, then environment, then the mainnet default.
*
Expand Down Expand Up @@ -384,7 +412,12 @@ export async function resolveStampConfig(
throw usageError('No API key. Set UNICITY_API_KEY in the environment or .env, or pass --api-key.');
}

const network = await resolveNetwork(resolveNetworkSelection(flags, env));
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(
Expand Down
20 changes: 20 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* The library: offline verification, plus stamping through a gateway.
*
* Verification on its own is available from `@unicitylabs/proof-cli/verify`, whose
* module graph cannot reach the aggregator client. Prefer that entry point in code
* that only checks proofs — importing this one pulls in the gateway stack a
* verifier never calls.
*
* Every name here is listed deliberately. A symbol added to a module under
* `src/lib/` is internal until it appears in this file or in `src/verify.ts`.
*/

export * from './verify.js';

export { TIMESTAMP_RECIPIENT } from './lib/constants.js';
export { StampError } from './lib/errors.js';
export { resolveNetwork } from './lib/networks.js';
export type { INetworkOverrides, ITimestampNetwork } from './lib/networks.js';
export { DEFAULT_TIMEOUT_MS, stamp, stampWith } from './lib/TimestampClient.js';
export type { ICertifyOptions, IStampOptions } from './lib/TimestampClient.js';
161 changes: 2 additions & 159 deletions src/lib/TimestampClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,18 @@ 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 { NetworkId } from '@unicitylabs/state-transition-sdk/lib/api/NetworkId.js';
import { SigningService } from '@unicitylabs/state-transition-sdk/lib/crypto/secp256k1/SigningService.js';
import { EncodedPredicate } from '@unicitylabs/state-transition-sdk/lib/predicate/EncodedPredicate.js';
import { StateTransitionClient } from '@unicitylabs/state-transition-sdk/lib/StateTransitionClient.js';
import { CertifiedMintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/CertifiedMintTransaction.js';
import { MintTransaction } from '@unicitylabs/state-transition-sdk/lib/transaction/MintTransaction.js';
import { Token } from '@unicitylabs/state-transition-sdk/lib/transaction/Token.js';
import { TokenId } from '@unicitylabs/state-transition-sdk/lib/transaction/TokenId.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 { waitInclusionProof } from '@unicitylabs/state-transition-sdk/lib/util/InclusionProofUtils.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 { TIMESTAMP_RECIPIENT, TIMESTAMP_RECIPIENT_ENCODED, TIMESTAMP_TOKEN_TYPE } from './constants.js';
import { TIMESTAMP_RECIPIENT, TIMESTAMP_TOKEN_TYPE } from './constants.js';
import { StampError } from './errors.js';
import { ITimestampNetwork } from './networks.js';
import { decodePayload, TimestampPayload } from './TimestampPayload.js';
import { TimestampPayload } from './TimestampPayload.js';
import { createVerificationContext } from './verification.js';

export const DEFAULT_TIMEOUT_MS = 60_000;
Expand All @@ -44,37 +37,6 @@ export interface IStampOptions extends ICertifyOptions {
readonly signer?: SigningService;
}

export interface ITimestampVerifyOptions {
/** Digest the token is expected to carry. */
readonly expectedDigest?: Uint8Array;
}

/** Everything that can be read off a token without verifying it. */
export interface ITimestampDescription {
readonly epoch: bigint;
readonly networkId: NetworkId;
readonly payload: TimestampPayload | null;
readonly payloadError: string | null;
readonly recipientIsTimestampBurn: boolean;
/** Unix seconds; the certified time of the stamp. */
readonly referenceTime: bigint;
readonly roundNumber: bigint;
/** Unix seconds; consensus-signed upper bound of the reference time. */
readonly roundTimestamp: bigint;
readonly tokenId: TokenId;
readonly tokenTypeIsTimestamp: boolean;
readonly transferCount: number;
}

export interface ITimestampVerificationResult extends ITimestampDescription {
/** SDK result tree, or null when verification was not reached. */
readonly details: VerificationResult<VerificationStatus> | null;
/** Null when no expected digest was given or the comparison was not reached. */
readonly expectedDigestMatches: boolean | null;
readonly reason: string | null;
readonly status: 'FAIL' | 'OK';
}

const KNOWN_STATUSES: readonly string[] = Object.values(CertificationStatus);
const SUCCESS_STATUS: string = CertificationStatus.SUCCESS;

Expand Down Expand Up @@ -176,122 +138,3 @@ export async function stampWith(
const context = createVerificationContext(trustBase);
return Token.mint(await certifyMintTransaction(client, context, transaction, options), context);
}

/**
* Read the timestamp fields off a token without verifying anything.
*
* @param {Token} token Any SDK token.
* @returns {ITimestampDescription} What the token claims.
*/
export function describeToken(token: Token): ITimestampDescription {
const genesis = token.genesis;
const certificate = genesis.inclusionProof.unicityCertificate;
const { error: payloadError, payload } = decodePayload(genesis.data);

return {
epoch: certificate.unicitySeal.epoch,
networkId: token.networkId,
payload,
payloadError,
recipientIsTimestampBurn: EncodedPredicate.equals(genesis.recipient, TIMESTAMP_RECIPIENT_ENCODED),
referenceTime: genesis.referenceTime,
roundNumber: certificate.inputRecord.roundNumber,
roundTimestamp: certificate.inputRecord.timestamp,
tokenId: token.id,
tokenTypeIsTimestamp: areUint8ArraysEqual(token.type.bytes, TIMESTAMP_TOKEN_TYPE.bytes),
transferCount: token.transactions.length,
};
}

/**
* Build a failed verification result around a token description.
*
* @param {ITimestampDescription} description Fields read off the token.
* @param {string} reason Why verification failed.
* @param {VerificationResult<VerificationStatus>|null} details SDK result tree, if verification ran.
* @param {boolean|null} expectedDigestMatches Digest comparison outcome, if one was requested.
* @returns {ITimestampVerificationResult} Failed result.
*/
export function verificationFailure(
description: ITimestampDescription,
reason: string,
details: VerificationResult<VerificationStatus> | null = null,
expectedDigestMatches: boolean | null = null,
): ITimestampVerificationResult {
return { ...description, details, expectedDigestMatches, reason, status: 'FAIL' };
}

/**
* Verify a timestamp token offline against a trust base.
*
* @param {Token} token Token to verify.
* @param {RootTrustBase} trustBase Trust base of the network the token claims.
* @param {ITimestampVerifyOptions} options Expected digest.
* @returns {Promise<ITimestampVerificationResult>} Outcome with the SDK result tree.
*/
export async function verify(
token: Token,
trustBase: RootTrustBase,
options: ITimestampVerifyOptions = {},
): Promise<ITimestampVerificationResult> {
const description = describeToken(token);
if (description.transferCount > 0) {
return verificationFailure(
description,
`Timestamp tokens carry no transfers; this one has ${description.transferCount}.`,
);
}
if (!description.tokenTypeIsTimestamp) {
return verificationFailure(
description,
`Not a timestamp token: token type ${HexConverter.encode(token.type.bytes)}.`,
);
}

const details = await token.verify(createVerificationContext(trustBase));
if (details.status !== VerificationStatus.OK) {
return verificationFailure(description, explainFailure(details, description, trustBase), details);
}
if (options.expectedDigest === undefined) {
return { ...description, details, expectedDigestMatches: null, reason: null, status: 'OK' };
}
// Not dead code, and not a pass: reachable only if `describeToken` and the
// issuance verifier disagree about the payload, which is exactly the case that
// must not report OK with the caller's comparison quietly skipped.
if (description.payload === null) {
return verificationFailure(
description,
`Cannot check the expected hash: the payload could not be read (${description.payloadError ?? 'no payload'}).`,
details,
);
}
if (!areUint8ArraysEqual(description.payload.digest, options.expectedDigest)) {
return verificationFailure(description, 'Hash mismatch: the token certifies a different digest.', details, false);
}
return { ...description, details, expectedDigestMatches: true, reason: null, status: 'OK' };
}

/**
* Pick the message a user needs out of a failed verification: the deepest failing
* rule that carries one, followed by the trust-base network when it is not the token's.
*/
function explainFailure(
details: VerificationResult<VerificationStatus>,
description: ITimestampDescription,
trustBase: RootTrustBase,
): string {
const failures = collectFailures(details);
const explained = failures.filter((result) => result.message !== '').at(-1) ?? failures.at(-1) ?? details;
const reason = explained.message !== '' ? explained.message : `Verification rule ${explained.rule} failed.`;
if (description.networkId.id !== trustBase.networkId.id) {
return `${reason} The token is for network ${description.networkId.id} and the trust base for network ${trustBase.networkId.id}; select the matching network or trust base.`;
}
return reason;
}

function collectFailures(result: VerificationResult<unknown>): VerificationResult<unknown>[] {
if (result.status === VerificationStatus.OK) {
return [];
}
return [result, ...result.results.flatMap((child) => collectFailures(child))];
}
Loading
Loading