@vordium/sdk 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import { type PolicyV1 } from './agents.js';
3
3
  import { type DomainClass, type TypedDomain } from './domains.js';
4
4
  import { type Transport } from './http.js';
5
5
  import { type Network, type NetworkPreset } from './network.js';
6
- import { type NonceSource } from './nonce.js';
6
+ import { type NonceSource, type NonceStore } from './nonce.js';
7
7
  import { ChainClock } from './resend.js';
8
8
  import { type BatchAction, type OrderInput, type Submitted } from './orders.js';
9
9
  import { type AgentRefusal, type Equity, type OpenOrder, type Position } from './reads.js';
@@ -37,6 +37,12 @@ export interface ConnectOptions {
37
37
  * default with the built-in transport; with a transport of your own, off unless set. Off: against this computer's clock.
38
38
  */
39
39
  chainClock?: boolean;
40
+ /** Tests only: armoured OpenPGP public keys that replace the shipped release key (see `releaseRecord.ts`). */
41
+ releaseKeys?: readonly string[];
42
+ /** Where the highest release-record sequence seen is kept (default: the nonce store, files 0600 under Node.js). */
43
+ releaseRecordStore?: NonceStore;
44
+ /** Tests only: this computer's clock in milliseconds, for the release record's expiry. */
45
+ releaseRecordNow?: () => number;
40
46
  }
41
47
  /** A connection to one Vordium network: reads, and the signing domains of its node. */
42
48
  export declare class Vordium {
@@ -53,8 +59,8 @@ export declare class Vordium {
53
59
  /** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
54
60
  static connect(opts?: ConnectOptions): Promise<Vordium>;
55
61
  /**
56
- * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
57
- * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
62
+ * The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
63
+ * else its pin in `PINS`) after the network's reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
58
64
  * chain is refused, never followed.
59
65
  */
60
66
  domain(cls: DomainClass): Promise<TypedDomain>;
@@ -4,7 +4,7 @@ import { LOWERCASE_ADDRESS_OPS, loosens, policyFromRead, policyProblems, policyV
4
4
  import { domain } from './domains.js';
5
5
  import { InvalidRequest, NetworkMismatch, VordiumError } from './errors.js';
6
6
  import { fetchTransport } from './http.js';
7
- import { connectNetwork, nodeIdentity, signingPin } from './network.js';
7
+ import { connectNetwork, nodeIdentity, refreshRecord, signingPin } from './network.js';
8
8
  import { PinMismatch, pinDifferences, pinRefusal } from './pins.js';
9
9
  import { NonceAllocator, nonceAllocator } from './nonce.js';
10
10
  import { ChainClock, DeliveryUnknown, sendSame } from './resend.js';
@@ -70,15 +70,19 @@ export class Vordium {
70
70
  static async connect(opts = {}) {
71
71
  const transport = opts.transport ?? fetchTransport;
72
72
  const timeoutMs = opts.timeoutMs ?? 15000;
73
- const net = await connectNetwork(opts.network ?? 'testnet', { transport, timeoutMs, onPinProblem: opts.onPinProblem });
73
+ const net = await connectNetwork(opts.network ?? 'testnet', {
74
+ transport, timeoutMs, onPinProblem: opts.onPinProblem,
75
+ releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow,
76
+ });
74
77
  return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
75
78
  }
76
79
  /**
77
- * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
78
- * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
80
+ * The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
81
+ * else its pin in `PINS`) after the network's reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
79
82
  * chain is refused, never followed.
80
83
  */
81
84
  async domain(cls) {
85
+ await refreshRecord(this.network);
82
86
  const pin = signingPin(this.network);
83
87
  if (Date.now() - this.checkedAt >= this.ttlMs) {
84
88
  const id = await nodeIdentity(this.network.api, this.transport, this.timeoutMs);
@@ -10,6 +10,12 @@ export interface Transport {
10
10
  body: unknown;
11
11
  retryAfter: string | null;
12
12
  }>;
13
+ /** The exact bytes served at `url` (the signed release record is verified over them), read no further than `limit` + 1
14
+ * bytes. A transport without it reads no release record. */
15
+ getBytes?(url: string, timeoutMs: number, limit?: number): Promise<{
16
+ status: number;
17
+ bytes: Uint8Array;
18
+ }>;
13
19
  }
14
20
  /** What a redirect answer reads as: never the redirect's own body. */
15
21
  export declare const REDIRECT_REFUSAL: Readonly<{
package/dist/esm/http.js CHANGED
@@ -26,6 +26,32 @@ async function readBody(r) {
26
26
  }
27
27
  }
28
28
  const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
29
+ /** The body of `r`, read no further than `limit` + 1 bytes (the rest is not downloaded). */
30
+ async function readCapped(r, limit) {
31
+ if (!r.body)
32
+ return new Uint8Array(0);
33
+ const reader = r.body.getReader();
34
+ const parts = [];
35
+ let n = 0;
36
+ for (;;) {
37
+ const { done, value } = await reader.read();
38
+ if (done)
39
+ break;
40
+ parts.push(value);
41
+ n += value.length;
42
+ if (n > limit) {
43
+ await reader.cancel().catch(() => undefined);
44
+ break;
45
+ }
46
+ }
47
+ const out = new Uint8Array(n);
48
+ let i = 0;
49
+ for (const p of parts) {
50
+ out.set(p, i);
51
+ i += p.length;
52
+ }
53
+ return out;
54
+ }
29
55
  const isRedirect = (status) => status >= 300 && status < 400;
30
56
  /** What a redirect answer reads as: never the redirect's own body. */
31
57
  export const REDIRECT_REFUSAL = Object.freeze({ code: 'redirect_refused', error: 'The node answered with a redirect, which is not followed: use the https address of the node.' });
@@ -55,6 +81,26 @@ export const fetchTransport = {
55
81
  }
56
82
  throw new VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
57
83
  },
84
+ async getBytes(url, timeoutMs, limit = Infinity) {
85
+ let last = null;
86
+ for (let attempt = 0; attempt < 3; attempt++) {
87
+ try {
88
+ const r = await fetchWithTimeout(url, {}, timeoutMs);
89
+ if (RETRY_STATUS.has(r.status) && attempt < 2) {
90
+ await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
91
+ continue;
92
+ }
93
+ // a redirect is not followed and its body is not read
94
+ return { status: r.status, bytes: isRedirect(r.status) ? new Uint8Array(0) : await readCapped(r, limit) };
95
+ }
96
+ catch (e) {
97
+ last = e;
98
+ if (attempt < 2)
99
+ await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
100
+ }
101
+ }
102
+ throw new VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
103
+ },
58
104
  async post(url, body, timeoutMs) {
59
105
  const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
60
106
  // a redirect is not an answer about the write: no body is read from it
@@ -5,6 +5,7 @@ export * from './types.js';
5
5
  export * from './sign.js';
6
6
  export * from './network.js';
7
7
  export * from './pins.js';
8
+ export * from './releaseRecord.js';
8
9
  export * from './nonce.js';
9
10
  export * from './resend.js';
10
11
  export * from './units.js';
package/dist/esm/index.js CHANGED
@@ -5,6 +5,7 @@ export * from './types.js';
5
5
  export * from './sign.js';
6
6
  export * from './network.js';
7
7
  export * from './pins.js';
8
+ export * from './releaseRecord.js';
8
9
  export * from './nonce.js';
9
10
  export * from './resend.js';
10
11
  export * from './units.js';
@@ -1,10 +1,13 @@
1
1
  import { type Transport } from './http.js';
2
2
  import { type Pin } from './pins.js';
3
+ import { type PublicKey, type ReadRecordOptions, type VerifiedRecord } from './releaseRecord.js';
4
+ import type { NonceStore } from './nonce.js';
3
5
  /**
4
- * Where the SDK asks, and the pin the network is held to. The named networks carry their pins (`PINS`); a preset of
5
- * your own (another address) names the network it serves (`name: 'mainnet' | 'testnet'`) or carries an explicit `pin`.
6
- * Before anything is signed, the network spec, the node's `/status` and the JSON-RPC `eth_chainId` must agree with
7
- * each other and with the pin.
6
+ * Where the SDK asks, and the identity the network is held to. A named network's identity comes from the signed release
7
+ * record when one is served (`releaseRecord.ts`: its genesis for the network's chain id), else from the SDK's pins
8
+ * (`PINS`). A preset of your own (another address) names the network it serves (`name: 'mainnet' | 'testnet'`), or
9
+ * carries an explicit `pin`, or names the `chainId` of a network the signed record lists. Before anything is signed,
10
+ * the network spec, the node's `/status` and the JSON-RPC `eth_chainId` must agree with each other and with it.
8
11
  */
9
12
  export interface NetworkPreset {
10
13
  /** 'mainnet' or 'testnet' holds the preset to that network's pin; any other name needs `pin`. */
@@ -19,6 +22,10 @@ export interface NetworkPreset {
19
22
  feeds?: string;
20
23
  /** An explicit pin, for a network that is not a named one (or the named network's own pin). */
21
24
  pin?: Pin;
25
+ /** A network that only the signed release record names: its chain id (nothing is signed without a record listing it). */
26
+ recordChainId?: number;
27
+ /** Tests only: where the signed release record is read (the named networks read `RELEASE_RECORD_URLS`). */
28
+ releaseRecord?: string;
22
29
  }
23
30
  export declare const NETWORKS: Record<'mainnet' | 'testnet', NetworkPreset>;
24
31
  /** A network the SDK has read and checked. `chainId` and `genesis` are what the network reports. */
@@ -30,7 +37,39 @@ export interface Network extends NetworkPreset {
30
37
  specRead: Record<string, unknown>;
31
38
  /** Why nothing may be signed for this network (its reports differ from its pin, or it has no pin); null when none. */
32
39
  pinProblem: string | null;
40
+ /** The signed release record the network was checked against (its genesis is the pin, its bridge the bridge); null
41
+ * when none is served (the SDK's pin applies). */
42
+ record: VerifiedRecord | null;
43
+ /** Why the served release record cannot be used; nothing is signed while it is set. */
44
+ recordProblem: string | null;
45
+ /** Where the record is read again, and the record as last read: signing uses the record as it is now (see
46
+ * {@link refreshRecord}). Absent for a network with a pin of its own. */
47
+ recordLive?: RecordLive;
33
48
  }
49
+ /** How a connected network's release record is read again, and what was last read. */
50
+ export interface RecordLive {
51
+ chainId: number;
52
+ urls: readonly string[];
53
+ keys: readonly PublicKey[];
54
+ byChain: boolean;
55
+ read: ReadRecordOptions;
56
+ record: VerifiedRecord | null;
57
+ problem: string | null;
58
+ /** Date.now() when it was read. */
59
+ at: number;
60
+ }
61
+ /** How long a network's release record is used before it is read again (ms), and how soon a refused one is retried. */
62
+ export declare const RECORD_TTL_MS = 300000;
63
+ export declare const RECORD_RETRY_MS = 30000;
64
+ /**
65
+ * Read the network's release record again when it has expired, when it is older than {@link RECORD_TTL_MS}, or when it
66
+ * was refused more than {@link RECORD_RETRY_MS} ago. A client calls it before every signature; {@link signingPin} then
67
+ * judges the record as it is now.
68
+ */
69
+ export declare function refreshRecord(net: Network, opts?: {
70
+ ttlMs?: number;
71
+ retryMs?: number;
72
+ }): Promise<void>;
34
73
  /** The pin a preset is held to: its own `pin`, else the pin of the named network it names; null when it has none. */
35
74
  export declare function presetPin(p: NetworkPreset): Pin | null;
36
75
  /**
@@ -47,17 +86,26 @@ export declare function readIdentity(status: unknown): NodeIdentity;
47
86
  /** Where a node's `/status` is read: under the API's own path first, then at the host root. */
48
87
  export declare function statusUrls(api: string): string[];
49
88
  export declare function nodeIdentity(api: string, transport?: Transport, timeoutMs?: number): Promise<NodeIdentity>;
89
+ /** Options of {@link connectNetwork}. `releaseKeys`, `releaseRecordStore` and `releaseRecordNow` are for tests only. */
90
+ export interface ConnectNetworkOptions {
91
+ transport?: Transport;
92
+ timeoutMs?: number;
93
+ onPinProblem?: (message: string) => void;
94
+ /** Tests only: armoured OpenPGP public keys that replace the shipped release key. */
95
+ releaseKeys?: readonly string[];
96
+ /** Where the highest record sequence seen is kept (default: the nonce store). */
97
+ releaseRecordStore?: NonceStore;
98
+ /** Tests only: this computer's clock in milliseconds. */
99
+ releaseRecordNow?: () => number;
100
+ }
50
101
  /**
51
102
  * Read and check a network. Refuses (NetworkMismatch, nothing signed) unless the spec, the node's `/status` and
52
103
  * `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
53
104
  * the preset (a test network never stands in for the main network, nor the reverse).
54
105
  *
55
- * The reports are then held to the network's pin. When they differ (or the network has no pin) the connection still
56
- * reads, `pinProblem` says why, `onPinProblem` (when given) is called with it, and every signature is refused
57
- * (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
106
+ * The network's identity comes from the signed release record when one is served (its genesis for the network's chain
107
+ * id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
108
+ * record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
109
+ * it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
58
110
  */
59
- export declare function connectNetwork(network?: 'mainnet' | 'testnet' | NetworkPreset, opts?: {
60
- transport?: Transport;
61
- timeoutMs?: number;
62
- onPinProblem?: (message: string) => void;
63
- }): Promise<Network>;
111
+ export declare function connectNetwork(network?: 'mainnet' | 'testnet' | NetworkPreset, opts?: ConnectNetworkOptions): Promise<Network>;
@@ -2,6 +2,7 @@ import { NetworkMismatch, VordiumError } from './errors.js';
2
2
  import { fetchTransport } from './http.js';
3
3
  import { genesisHex } from './domains.js';
4
4
  import { PINS, PinMismatch, UnpinnedNetwork, checkPin, pinDifferences, pinRefusal } from './pins.js';
5
+ import { RELEASE_RECORD_URLS, RecordRefused, pinnedKeys, readRecord } from './releaseRecord.js';
5
6
  export const NETWORKS = {
6
7
  mainnet: {
7
8
  name: 'mainnet',
@@ -20,6 +21,81 @@ export const NETWORKS = {
20
21
  feeds: 'wss://testnet.vordex.xyz/chain/feeds',
21
22
  },
22
23
  };
24
+ /** How long a network's release record is used before it is read again (ms), and how soon a refused one is retried. */
25
+ export const RECORD_TTL_MS = 300_000;
26
+ export const RECORD_RETRY_MS = 30_000;
27
+ /**
28
+ * Read the network's release record again when it has expired, when it is older than {@link RECORD_TTL_MS}, or when it
29
+ * was refused more than {@link RECORD_RETRY_MS} ago. A client calls it before every signature; {@link signingPin} then
30
+ * judges the record as it is now.
31
+ */
32
+ export async function refreshRecord(net, opts = {}) {
33
+ const l = net.recordLive;
34
+ if (!l)
35
+ return;
36
+ const now = l.read.now ?? Date.now;
37
+ const age = Date.now() - l.at;
38
+ const due = (l.record && (now() / 1000 > l.record.record.validUntil || age >= (opts.ttlMs ?? RECORD_TTL_MS)))
39
+ || (l.problem !== null && age >= (opts.retryMs ?? RECORD_RETRY_MS));
40
+ if (!due)
41
+ return;
42
+ try {
43
+ l.record = await readRecord(l.chainId, l.urls, l.keys, l.read);
44
+ l.problem = null;
45
+ }
46
+ catch (e) {
47
+ if (!(e instanceof RecordRefused))
48
+ throw e;
49
+ l.record = null;
50
+ l.problem = `${e.message} Nothing was signed.`;
51
+ }
52
+ if (!l.record && !l.problem && l.byChain)
53
+ l.problem = noRecordText(l.chainId);
54
+ l.at = Date.now();
55
+ }
56
+ const noRecordText = (chainId) => `Refusing to sign: no signed release record lists chain ${chainId}, and a network named only by its chain id needs one. Nothing was signed.`;
57
+ /** The pin from the network's release record as last read (throws when it cannot be used), or null when no record is
58
+ * served and none was used for the network (then its pin applies). */
59
+ function recordSigningPin(net, l) {
60
+ const now = l.read.now ?? Date.now;
61
+ let problem = l.problem;
62
+ if (!problem && l.record && now() / 1000 > l.record.record.validUntil)
63
+ problem = `The signed release record expired; it is read again before the next signature. Nothing was signed.`;
64
+ if (!problem && !l.record && net.record)
65
+ problem = 'Refusing to sign: the signed release record this network was checked against is not served now. Nothing was signed.';
66
+ if (problem)
67
+ throw l.byChain ? new UnpinnedNetwork(problem) : new PinMismatch(problem);
68
+ let pin;
69
+ if (!l.record) {
70
+ if (!net.recordProblem)
71
+ return null;
72
+ const named = presetPinOrNull({ ...net, pin: undefined });
73
+ if (!named)
74
+ throw new UnpinnedNetwork(net.recordProblem);
75
+ pin = named;
76
+ }
77
+ else {
78
+ pin = Object.freeze({ ...(net.name ? { name: net.name } : {}), chainId: l.record.entry.chainId, genesis: l.record.entry.genesis });
79
+ }
80
+ const same = !!(net.record && l.record && net.record.entry.genesis === l.record.entry.genesis);
81
+ if (same && net.pinProblem)
82
+ throw new PinMismatch(net.pinProblem);
83
+ const d = pinDifferences(pin, { 'the network': net.chainId }, { 'the network': net.genesis });
84
+ if (l.record && l.record.entry.retiredGenesis.includes(net.genesis)) {
85
+ d.unshift(`the node serves genesis ${net.genesis}, which the signed release record lists in retired_genesis for chain ${l.record.entry.chainId}`);
86
+ }
87
+ if (d.length)
88
+ throw new PinMismatch(pinRefusal(pin, d));
89
+ return pin;
90
+ }
91
+ function presetPinOrNull(p) {
92
+ try {
93
+ return presetPin(p);
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
23
99
  /** The pin a preset is held to: its own `pin`, else the pin of the named network it names; null when it has none. */
24
100
  export function presetPin(p) {
25
101
  const named = Object.prototype.hasOwnProperty.call(PINS, p.name) ? PINS[p.name] : undefined;
@@ -37,7 +113,14 @@ export function presetPin(p) {
37
113
  * `PinMismatch` when what it reported differs from the pin; nothing may be signed then.
38
114
  */
39
115
  export function signingPin(net) {
40
- const pin = presetPin(net);
116
+ if (net.recordLive) {
117
+ const live = recordSigningPin(net, net.recordLive);
118
+ if (live)
119
+ return live;
120
+ }
121
+ if (net.recordProblem)
122
+ throw net.record || presetPinOrNull(net) ? new PinMismatch(net.recordProblem) : new UnpinnedNetwork(net.recordProblem);
123
+ const pin = net.record && net.pin ? net.pin : presetPin(net);
41
124
  if (net.pinProblem)
42
125
  throw pin ? new PinMismatch(net.pinProblem) : new UnpinnedNetwork(net.pinProblem);
43
126
  if (!pin)
@@ -105,17 +188,48 @@ async function rpcChainId(rpc, transport, timeoutMs) {
105
188
  * `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
106
189
  * the preset (a test network never stands in for the main network, nor the reverse).
107
190
  *
108
- * The reports are then held to the network's pin. When they differ (or the network has no pin) the connection still
109
- * reads, `pinProblem` says why, `onPinProblem` (when given) is called with it, and every signature is refused
110
- * (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
191
+ * The network's identity comes from the signed release record when one is served (its genesis for the network's chain
192
+ * id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
193
+ * record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
194
+ * it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
111
195
  */
112
196
  export async function connectNetwork(network = 'testnet', opts = {}) {
113
197
  const p = typeof network === 'string' ? NETWORKS[network] : network;
114
198
  if (!p)
115
199
  throw new VordiumError('unknown_network', `Unknown network ${String(network)}; known: mainnet, testnet.`);
116
- const pin = presetPin(p);
200
+ const named = Object.prototype.hasOwnProperty.call(PINS, p.name) ? PINS[p.name] : undefined;
201
+ if (p.recordChainId !== undefined && (!Number.isSafeInteger(p.recordChainId) || p.recordChainId <= 0 || p.pin || named)) {
202
+ throw new VordiumError('unknown_network', 'recordChainId names a network only the signed release record lists: give a positive chain id, with no pin and a name that is not mainnet or testnet.');
203
+ }
204
+ const hardPin = presetPin(p);
117
205
  const t = opts.transport ?? fetchTransport;
118
206
  const ms = opts.timeoutMs ?? 10000;
207
+ // The identity: the signed record's for a named network or a record-only chain id; an explicit pin of your own skips it.
208
+ const recordChain = p.recordChainId ?? (named ? named.chainId : null);
209
+ let record = null;
210
+ let recordProblem = null;
211
+ let recordLive;
212
+ if (recordChain !== null) {
213
+ const urls = p.releaseRecord ? [p.releaseRecord]
214
+ : p.recordChainId !== undefined ? Object.values(RELEASE_RECORD_URLS).flat() // a chain only the record names: every address
215
+ : RELEASE_RECORD_URLS[p.name] ?? [];
216
+ const read = { transport: t, timeoutMs: ms, store: opts.releaseRecordStore, now: opts.releaseRecordNow };
217
+ try {
218
+ const keys = pinnedKeys(opts.releaseKeys);
219
+ recordLive = { chainId: recordChain, urls, keys, byChain: p.recordChainId !== undefined, read, record: null, problem: null, at: Date.now() };
220
+ record = await readRecord(recordChain, urls, keys, read);
221
+ }
222
+ catch (e) {
223
+ if (!(e instanceof RecordRefused))
224
+ throw e;
225
+ recordProblem = `${e.message} Nothing was signed.`;
226
+ }
227
+ if (!record && !recordProblem && p.recordChainId !== undefined)
228
+ recordProblem = noRecordText(p.recordChainId);
229
+ if (recordLive)
230
+ Object.assign(recordLive, { record, problem: recordProblem, at: Date.now() });
231
+ }
232
+ const pin = record ? Object.freeze({ ...(p.name ? { name: p.name } : {}), chainId: recordChain, genesis: record.entry.genesis }) : hardPin;
119
233
  const sr = await t.get(p.spec, ms);
120
234
  if (sr.status !== 200 || !sr.body || typeof sr.body !== 'object')
121
235
  throw new VordiumError('no_spec', `The network spec at ${p.spec} could not be read.`);
@@ -142,16 +256,19 @@ export async function connectNetwork(network = 'testnet', opts = {}) {
142
256
  if (specGenesis !== null && specGenesis !== ident.genesis) {
143
257
  throw new NetworkMismatch(`The spec names genesis ${specGenesis.slice(0, 8)}…, the node ${ident.genesis.slice(0, 8)}…; refusing to sign.`);
144
258
  }
145
- let pinProblem = null;
146
- if (!pin) {
259
+ let pinProblem = recordProblem;
260
+ if (!pinProblem && !pin) {
147
261
  pinProblem = unpinnedText(p);
148
262
  }
149
- else {
263
+ else if (!pinProblem && pin) {
150
264
  const d = pinDifferences(pin, { 'the network spec': specChain, "the node's /status": ident.chainId, eth_chainId: rpcChain }, { 'the network spec': specGenesis, "the node's /status": ident.genesis });
265
+ if (record && record.entry.retiredGenesis.includes(ident.genesis)) {
266
+ d.unshift(`the node serves genesis ${ident.genesis}, which the signed release record lists in retired_genesis for chain ${record.entry.chainId}`);
267
+ }
151
268
  if (d.length)
152
269
  pinProblem = pinRefusal(pin, d);
153
270
  }
154
271
  if (pinProblem && opts.onPinProblem)
155
272
  opts.onPinProblem(pinProblem);
156
- return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem };
273
+ return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem, record, recordProblem, ...(recordLive ? { recordLive } : {}) };
157
274
  }
@@ -47,9 +47,11 @@ export interface NonceStore {
47
47
  /** Writes what `fn` returns when it differs from the mark (the allocator keeps it rising). `fn` may be called more
48
48
  * than once in one update (a value already taken, a lock lost); the value kept is its last call's, and `taken` is
49
49
  * the value its previous call returned when that one was already taken. `unique` (default true): every value
50
- * written is one no other caller received; false for a record that is not a nonce. */
50
+ * written is one no other caller received; false for a record that is not a nonce. `strict`: a mark that cannot be
51
+ * read throws (`state_unreadable`) instead of reading as 0. */
51
52
  update(key: string, fn: (last: number, taken?: number) => number, opts?: {
52
53
  unique?: boolean;
54
+ strict?: boolean;
53
55
  }): Promise<number>;
54
56
  /** Where the mark of `key` lives, for a message (a file path), or null. */
55
57
  where?(key: string): string | null;
package/dist/esm/nonce.js CHANGED
@@ -268,12 +268,16 @@ export function fileNonceStore(dir, opts = {}) {
268
268
  let done = null;
269
269
  try {
270
270
  let last = 0;
271
+ let text = null;
271
272
  try {
272
- const t = (await fs.readFile(file, 'utf8')).trim();
273
- if (/^\d+$/.test(t))
274
- last = Number(t);
273
+ text = (await fs.readFile(file, 'utf8')).trim();
275
274
  }
276
275
  catch { /* no mark yet */ }
276
+ if (text !== null && /^\d+$/.test(text))
277
+ last = Number(text);
278
+ else if (text !== null && opts?.strict) {
279
+ throw new VordiumError('state_unreadable', `The mark in ${file} cannot be read. Check the file, or remove it to start again.`);
280
+ }
277
281
  let n = last, claimed = false, seen = [];
278
282
  if (!unique)
279
283
  n = fn(last); // a record, not a nonce
@@ -3,7 +3,9 @@ import { NetworkMismatch } from './errors.js';
3
3
  * The identity each named network is pinned to: its chain id and its genesis sha256. These values are part of the SDK.
4
4
  * Before anything is signed, the SDK compares the pin with what the network reports (the network spec, the node's
5
5
  * `/status` and the JSON-RPC `eth_chainId`); when any of them differs, nothing is signed. The EIP-712 domains are built
6
- * from the pin. A new genesis for a named network needs a new SDK release that carries the new pin.
6
+ * from the pin. When the signed release record is served (`releaseRecord.ts`: `releases.json` with its detached signature
7
+ * by the release key), a named network's genesis comes from it instead, so a new genesis listed there needs no new SDK
8
+ * release. These pins apply while no record is served.
7
9
  */
8
10
  export interface Pin {
9
11
  /** "mainnet" or "testnet" for a named network; absent for a pin you give. */
@@ -0,0 +1,141 @@
1
+ import { VordiumError } from './errors.js';
2
+ import type { Transport } from './http.js';
3
+ import { type NonceStore } from './nonce.js';
4
+ /**
5
+ * The signed release record: the genesis, chain id and deposit bridge of each network, signed by the release key.
6
+ *
7
+ * A network's identity is taken from `releases.json`, and only after its detached OpenPGP signature
8
+ * (`releases.json.asc`) verifies under the release key that ships in this package ({@link RELEASE_KEY}, fingerprint
9
+ * {@link RELEASE_KEY_FINGERPRINT}). The signature covers the exact bytes as served; the record is read from those same
10
+ * bytes only after the signature holds.
11
+ *
12
+ * The key is pinned by its fingerprint. Its expiry is read from its newest self-signature. When that expiry is near
13
+ * ({@link KEY_REFRESH_BEFORE_S}) or past, the key is read again from where it is served ({@link KEY_URLS}). A served copy
14
+ * is used only when it is the same key (same fingerprint and point) and its self-signature verifies under that key: its
15
+ * newest self-signature then gives the expiry. A revocation that verifies under the key refuses every record. Nothing
16
+ * else is taken from a served copy, and when none can be read the shipped key is used as it is.
17
+ *
18
+ * Everything else is checked here, with no other program: the ASCII armour (and its CRC-24), the version 4 signature packet (EdDSA over Ed25519, SHA-256 or SHA-512),
19
+ * its hashed subpackets, the issuer fingerprint, the signature hash over the data and the hashed trailer, and the
20
+ * Ed25519 signature itself (RFC 8032).
21
+ */
22
+ /** The release key: every network record must be signed by it. */
23
+ export declare const RELEASE_KEY_FINGERPRINT = "C5EB4728F660369CE519D834B48FB4B71EFD48AE";
24
+ export declare const RELEASE_KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmDMEaqXHBhYJKwYBBAHaRw8BAQdA8NRFgXw3NaEYFesojdDl1TlSlk9O5bXhsM4i\no7k3e+q0J1ZvcmRpdW0gUmVsZWFzZXMgPHJlbGVhc2VzQHZvcmRpdW0uY29tPoi1\nBBMWCgBdFiEExetHKPZgNpzlGdg0tI+0tx79SK4FAmqlxwYbFIAAAAAABAAObWFu\ndTIsMi41KzEuMTIsMCwzAhsDBQkDwmcABQsJCAcCAiICBhUKCQgLAgQWAgMBAh4H\nAheAAAoJELSPtLce/UiuMUgA/2VojVnml+DJHQ6xbxhnbrNeD5p8H4lXsVASdpvs\nRsCIAQCkMr8M76++QNGj08s+apf7CDgEVwbBFo4shxsYAU+gDw==\n=20lT\n-----END PGP PUBLIC KEY BLOCK-----\n";
25
+ /** Where each named network's record is read, in order. The signature is read at the same address + ".asc". */
26
+ export declare const RELEASE_RECORD_URLS: Readonly<Record<'mainnet' | 'testnet', readonly string[]>>;
27
+ /** The record format this SDK reads. */
28
+ export declare const RELEASE_RECORD_SCHEMA = "vordium.release-record/3";
29
+ /** Where the release key is served. Read only when the key's expiry is near or past (see {@link refreshKey}). */
30
+ export declare const KEY_URLS: readonly string[];
31
+ /** The key is read again from {@link KEY_URLS} from this long (seconds) before its expiry. */
32
+ export declare const KEY_REFRESH_BEFORE_S: number;
33
+ /** A key read from {@link KEY_URLS} is used for this long (seconds) before it is read again. */
34
+ export declare const KEY_REFRESH_TTL_S: number;
35
+ /** A read that left an expired key as it was is tried again after this long (seconds). */
36
+ export declare const KEY_RETRY_S = 30;
37
+ /** The release record cannot be used. `code` names the reason; the message is a plain sentence. */
38
+ export declare class RecordRefused extends VordiumError {
39
+ constructor(code: string, message: string);
40
+ }
41
+ export declare function crc24(data: Uint8Array): number;
42
+ /** The bytes inside one ASCII-armoured block of `kind` ("PGP SIGNATURE", "PGP PUBLIC KEY BLOCK"). The CRC-24 line, when
43
+ * present, must match. Throws {@link RecordRefused}. */
44
+ export declare function dearmor(text: string | Uint8Array, kind: string): Uint8Array;
45
+ /** An Ed25519 OpenPGP public key: its v4 fingerprint (40 upper-case hex), its 32-byte point, and when it expires
46
+ * (seconds; null = never), read from its newest self-signature that verifies. */
47
+ export interface PublicKey {
48
+ fingerprint: string;
49
+ point: Uint8Array;
50
+ expires: number | null;
51
+ /** The time of the self-signature the expiry was read from. */
52
+ signedAt: number;
53
+ /** A key revocation signature by this key verifies. */
54
+ revoked: boolean;
55
+ }
56
+ /** The primary key of an armoured public key block. The fingerprint is computed from the key packet (SHA-1 over
57
+ * 0x99 || length || packet). Only a version 4 EdDSA key on Ed25519 is accepted, with at least one user ID whose
58
+ * self-signature verifies; the newest such self-signature gives the key's expiry. */
59
+ export declare function parsePublicKey(armoured: string | Uint8Array): PublicKey;
60
+ /** A checked detached signature: who made it (issuer fingerprint) and when (seconds). */
61
+ export interface SignatureInfo {
62
+ fingerprint: string;
63
+ created: number;
64
+ }
65
+ /**
66
+ * Verify an armoured detached signature over the exact bytes `data` under one of `keys` (the pinned keys). Returns the
67
+ * signature's issuer and time; throws {@link RecordRefused} with a plain sentence otherwise.
68
+ */
69
+ export declare function verifyDetached(data: Uint8Array, armouredSig: string | Uint8Array, keys: readonly PublicKey[], nowSec?: number): SignatureInfo;
70
+ /** The deposit bridge as the signed record names it (addresses lower-case). */
71
+ export interface RecordBridge {
72
+ chainId: number;
73
+ vault: string;
74
+ handler: string;
75
+ usdc: string;
76
+ }
77
+ /** One network of a signed record. */
78
+ export interface RecordNetwork {
79
+ chainId: number;
80
+ genesis: string;
81
+ bridge: RecordBridge;
82
+ retiredGenesis: readonly string[];
83
+ name: string | null;
84
+ }
85
+ /** A signed record, read from the verified bytes. Times are in seconds. */
86
+ export interface ReleaseRecord {
87
+ sequence: number;
88
+ issuedAt: number;
89
+ validUntil: number;
90
+ networks: ReadonlyMap<number, RecordNetwork>;
91
+ signedBy: string;
92
+ }
93
+ /** JSON.parse that refuses a key given twice in one object (two readers could otherwise take different values). */
94
+ export declare function parseStrictJson(text: string): unknown;
95
+ /** Whether bytes that could not be verified claim to be a network record (a JSON object with `networks`). Used only to
96
+ * tell an unsigned record (refused) from another file (ignored); no value of it is ever used. */
97
+ export declare function isNetworkRecord(data: Uint8Array): boolean;
98
+ /** The record in the VERIFIED bytes `data`. Null when the file is not a network record (it has no `networks`: the
99
+ * release list of an earlier format). Throws {@link RecordRefused} for a record that is not well formed. */
100
+ export declare function parseRecord(data: Uint8Array, signedBy?: string): ReleaseRecord | null;
101
+ /** A verified record and the entry of the network it was read for. */
102
+ export interface VerifiedRecord {
103
+ record: ReleaseRecord;
104
+ entry: RecordNetwork;
105
+ url: string;
106
+ }
107
+ export interface RefreshKeyOptions {
108
+ transport: Transport;
109
+ urls?: readonly string[];
110
+ timeoutMs?: number;
111
+ }
112
+ /**
113
+ * `key` as its newest served copy states it. A copy at `urls` (default {@link KEY_URLS}, through `transport.getBytes`) is
114
+ * used only when it parses as the same key (same fingerprint and point, a self-signature that verifies under that key)
115
+ * and its newest self-signature is newer than the one `key` was read from; a copy carrying a revocation that verifies
116
+ * under the key gives the key as revoked. A copy that cannot be read, is another key or is older is skipped; with none
117
+ * usable, `key` is returned as it is.
118
+ */
119
+ export declare function refreshKey(key: PublicKey, opts: RefreshKeyOptions): Promise<PublicKey>;
120
+ /** The keys a record must be signed by: the shipped release key, or (tests only) the armoured keys given. The shipped
121
+ * key's expiry is refreshed by {@link readRecord} from its served copy when near or past (see {@link refreshKey}). */
122
+ export declare function pinnedKeys(releaseKeys?: readonly string[]): PublicKey[];
123
+ export interface ReadRecordOptions {
124
+ transport: Transport;
125
+ timeoutMs?: number;
126
+ /** Where the highest sequence seen is kept (default: the nonce store, files 0600 under Node.js). */
127
+ store?: NonceStore;
128
+ /** This computer's clock in milliseconds (tests replace it). */
129
+ now?: () => number;
130
+ }
131
+ /**
132
+ * Read the signed record for `chainId` from the first of `urls` that serves one (through `transport.getBytes`; a
133
+ * transport without it reads no record).
134
+ *
135
+ * Resolves null when no address serves a network record (nothing, or a signed release list of an earlier format) and no
136
+ * record for this network was seen on this computer before. Throws {@link RecordRefused} (with a plain sentence) for an
137
+ * unsigned record, a bad signature, another key, a record of an unknown format, an expired record, a sequence lower than
138
+ * one seen before, a record that does not list `chainId`, or, when a record for this network was seen before, for no
139
+ * record served now.
140
+ */
141
+ export declare function readRecord(chainId: number, urls: readonly string[], keys: readonly PublicKey[], opts: ReadRecordOptions): Promise<VerifiedRecord | null>;