@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.
package/README.md CHANGED
@@ -19,11 +19,17 @@ const v = await Vordium.connect({ network: 'testnet' }) // or 'mainnet'
19
19
  ```
20
20
 
21
21
  `connect` reads the network spec, the node's `/status` and the JSON-RPC `eth_chainId`, and refuses unless all three name
22
- the same chain and the same genesis. Each named network is pinned in the SDK (`PINS`: mainnet chain 101101, testnet chain
23
- 101102, each with its genesis sha256), and every signature is made under the pin: the EIP-712 domain's chain id and
24
- `salt` come from it. When what the network reports differs from its pin, reads still work, `network.pinProblem` says
25
- why (and `onPinProblem`, when given, is called), and every signature is refused with `PinMismatch`, naming the network,
26
- the expected and the reported values. A new genesis for a named network needs a new SDK release.
22
+ the same chain and the same genesis. A named network's identity comes from the signed release record: `releases.json`
23
+ (at `https://binaries.vordium.com/<network>/releases.json`) names each network's chain id, genesis sha256 and deposit
24
+ bridge, and is used only when its detached OpenPGP signature (`releases.json.asc`) verifies under the release key that
25
+ ships in the SDK (fingerprint `C5EB4728F660369CE519D834B48FB4B71EFD48AE`). The SDK verifies it itself (Ed25519, no
26
+ other program, no key fetched), and refuses a record that is unsigned, signed by another key, changed after signing,
27
+ expired or older than one it has seen, and any genesis other than the one the record names for the network
28
+ (`network.record`, `network.recordProblem`). While no record is served, the pins in the SDK apply (`PINS`: mainnet
29
+ chain 101101, testnet chain 101102, each with its genesis sha256). Every signature is made under that identity: the
30
+ EIP-712 domain's chain id and `salt` come from it. When what the network reports differs, reads still work,
31
+ `network.pinProblem` says why (and `onPinProblem`, when given, is called), and every signature is refused with
32
+ `PinMismatch`, naming the network, the expected and the reported values.
27
33
 
28
34
  An address of your own must say which network it serves, or carry a pin; without one it can be read, but nothing is
29
35
  signed for it (`UnpinnedNetwork`):
@@ -33,6 +39,8 @@ const mine = await Vordium.connect({ network: { ...NETWORKS.mainnet, spec: 'http
33
39
  rpc: 'https://node.example', api: 'https://node.example' } }) // held to the mainnet pin
34
40
  const dev = await Vordium.connect({ network: { name: 'devnet', spec: '…', rpc: '…', api: '…',
35
41
  pin: { chainId: 777001, genesis: '<64 hex>' } } }) // a network of your own
42
+ const listed = await Vordium.connect({ network: { name: 'devnet', spec: '…', rpc: '…', api: '…',
43
+ recordChainId: 777002 } }) // a chain the signed record lists
36
44
  ```
37
45
 
38
46
  ## Trade
@@ -77,15 +77,19 @@ class Vordium {
77
77
  static async connect(opts = {}) {
78
78
  const transport = opts.transport ?? http_js_1.fetchTransport;
79
79
  const timeoutMs = opts.timeoutMs ?? 15000;
80
- const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', { transport, timeoutMs, onPinProblem: opts.onPinProblem });
80
+ const net = await (0, network_js_1.connectNetwork)(opts.network ?? 'testnet', {
81
+ transport, timeoutMs, onPinProblem: opts.onPinProblem,
82
+ releaseKeys: opts.releaseKeys, releaseRecordStore: opts.releaseRecordStore, releaseRecordNow: opts.releaseRecordNow,
83
+ });
81
84
  return new Vordium(net, transport, timeoutMs, opts.identityTtlMs ?? 60000, opts.chainClock ?? opts.transport === undefined);
82
85
  }
83
86
  /**
84
- * The signing domain of the node this client posts to, built from the network's pin (`PINS`) after the network's
85
- * reports were checked against it. The node's identity is read again after the TTL; a node that now serves another
87
+ * The signing domain of the node this client posts to, built from the network's identity (the signed release record's,
88
+ * 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
86
89
  * chain is refused, never followed.
87
90
  */
88
91
  async domain(cls) {
92
+ await (0, network_js_1.refreshRecord)(this.network);
89
93
  const pin = (0, network_js_1.signingPin)(this.network);
90
94
  if (Date.now() - this.checkedAt >= this.ttlMs) {
91
95
  const id = await (0, network_js_1.nodeIdentity)(this.network.api, this.transport, this.timeoutMs);
package/dist/cjs/http.js CHANGED
@@ -30,6 +30,32 @@ async function readBody(r) {
30
30
  }
31
31
  }
32
32
  const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
33
+ /** The body of `r`, read no further than `limit` + 1 bytes (the rest is not downloaded). */
34
+ async function readCapped(r, limit) {
35
+ if (!r.body)
36
+ return new Uint8Array(0);
37
+ const reader = r.body.getReader();
38
+ const parts = [];
39
+ let n = 0;
40
+ for (;;) {
41
+ const { done, value } = await reader.read();
42
+ if (done)
43
+ break;
44
+ parts.push(value);
45
+ n += value.length;
46
+ if (n > limit) {
47
+ await reader.cancel().catch(() => undefined);
48
+ break;
49
+ }
50
+ }
51
+ const out = new Uint8Array(n);
52
+ let i = 0;
53
+ for (const p of parts) {
54
+ out.set(p, i);
55
+ i += p.length;
56
+ }
57
+ return out;
58
+ }
33
59
  const isRedirect = (status) => status >= 300 && status < 400;
34
60
  /** What a redirect answer reads as: never the redirect's own body. */
35
61
  exports.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.' });
@@ -59,6 +85,26 @@ exports.fetchTransport = {
59
85
  }
60
86
  throw new errors_js_1.VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
61
87
  },
88
+ async getBytes(url, timeoutMs, limit = Infinity) {
89
+ let last = null;
90
+ for (let attempt = 0; attempt < 3; attempt++) {
91
+ try {
92
+ const r = await fetchWithTimeout(url, {}, timeoutMs);
93
+ if (RETRY_STATUS.has(r.status) && attempt < 2) {
94
+ await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
95
+ continue;
96
+ }
97
+ // a redirect is not followed and its body is not read
98
+ return { status: r.status, bytes: isRedirect(r.status) ? new Uint8Array(0) : await readCapped(r, limit) };
99
+ }
100
+ catch (e) {
101
+ last = e;
102
+ if (attempt < 2)
103
+ await sleep(250 * 2 ** attempt * (0.5 + Math.random() / 2));
104
+ }
105
+ }
106
+ throw new errors_js_1.VordiumError('unreachable', `The node at ${url} did not answer.`, String(last?.message ?? last));
107
+ },
62
108
  async post(url, body, timeoutMs) {
63
109
  const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
64
110
  // a redirect is not an answer about the write: no body is read from it
package/dist/cjs/index.js CHANGED
@@ -24,6 +24,7 @@ __exportStar(require("./types.js"), exports);
24
24
  __exportStar(require("./sign.js"), exports);
25
25
  __exportStar(require("./network.js"), exports);
26
26
  __exportStar(require("./pins.js"), exports);
27
+ __exportStar(require("./releaseRecord.js"), exports);
27
28
  __exportStar(require("./nonce.js"), exports);
28
29
  __exportStar(require("./resend.js"), exports);
29
30
  __exportStar(require("./units.js"), exports);
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NETWORKS = void 0;
3
+ exports.RECORD_RETRY_MS = exports.RECORD_TTL_MS = exports.NETWORKS = void 0;
4
+ exports.refreshRecord = refreshRecord;
4
5
  exports.presetPin = presetPin;
5
6
  exports.signingPin = signingPin;
6
7
  exports.readIdentity = readIdentity;
@@ -11,6 +12,7 @@ const errors_js_1 = require("./errors.js");
11
12
  const http_js_1 = require("./http.js");
12
13
  const domains_js_1 = require("./domains.js");
13
14
  const pins_js_1 = require("./pins.js");
15
+ const releaseRecord_js_1 = require("./releaseRecord.js");
14
16
  exports.NETWORKS = {
15
17
  mainnet: {
16
18
  name: 'mainnet',
@@ -29,6 +31,81 @@ exports.NETWORKS = {
29
31
  feeds: 'wss://testnet.vordex.xyz/chain/feeds',
30
32
  },
31
33
  };
34
+ /** How long a network's release record is used before it is read again (ms), and how soon a refused one is retried. */
35
+ exports.RECORD_TTL_MS = 300_000;
36
+ exports.RECORD_RETRY_MS = 30_000;
37
+ /**
38
+ * Read the network's release record again when it has expired, when it is older than {@link RECORD_TTL_MS}, or when it
39
+ * was refused more than {@link RECORD_RETRY_MS} ago. A client calls it before every signature; {@link signingPin} then
40
+ * judges the record as it is now.
41
+ */
42
+ async function refreshRecord(net, opts = {}) {
43
+ const l = net.recordLive;
44
+ if (!l)
45
+ return;
46
+ const now = l.read.now ?? Date.now;
47
+ const age = Date.now() - l.at;
48
+ const due = (l.record && (now() / 1000 > l.record.record.validUntil || age >= (opts.ttlMs ?? exports.RECORD_TTL_MS)))
49
+ || (l.problem !== null && age >= (opts.retryMs ?? exports.RECORD_RETRY_MS));
50
+ if (!due)
51
+ return;
52
+ try {
53
+ l.record = await (0, releaseRecord_js_1.readRecord)(l.chainId, l.urls, l.keys, l.read);
54
+ l.problem = null;
55
+ }
56
+ catch (e) {
57
+ if (!(e instanceof releaseRecord_js_1.RecordRefused))
58
+ throw e;
59
+ l.record = null;
60
+ l.problem = `${e.message} Nothing was signed.`;
61
+ }
62
+ if (!l.record && !l.problem && l.byChain)
63
+ l.problem = noRecordText(l.chainId);
64
+ l.at = Date.now();
65
+ }
66
+ 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.`;
67
+ /** The pin from the network's release record as last read (throws when it cannot be used), or null when no record is
68
+ * served and none was used for the network (then its pin applies). */
69
+ function recordSigningPin(net, l) {
70
+ const now = l.read.now ?? Date.now;
71
+ let problem = l.problem;
72
+ if (!problem && l.record && now() / 1000 > l.record.record.validUntil)
73
+ problem = `The signed release record expired; it is read again before the next signature. Nothing was signed.`;
74
+ if (!problem && !l.record && net.record)
75
+ problem = 'Refusing to sign: the signed release record this network was checked against is not served now. Nothing was signed.';
76
+ if (problem)
77
+ throw l.byChain ? new pins_js_1.UnpinnedNetwork(problem) : new pins_js_1.PinMismatch(problem);
78
+ let pin;
79
+ if (!l.record) {
80
+ if (!net.recordProblem)
81
+ return null;
82
+ const named = presetPinOrNull({ ...net, pin: undefined });
83
+ if (!named)
84
+ throw new pins_js_1.UnpinnedNetwork(net.recordProblem);
85
+ pin = named;
86
+ }
87
+ else {
88
+ pin = Object.freeze({ ...(net.name ? { name: net.name } : {}), chainId: l.record.entry.chainId, genesis: l.record.entry.genesis });
89
+ }
90
+ const same = !!(net.record && l.record && net.record.entry.genesis === l.record.entry.genesis);
91
+ if (same && net.pinProblem)
92
+ throw new pins_js_1.PinMismatch(net.pinProblem);
93
+ const d = (0, pins_js_1.pinDifferences)(pin, { 'the network': net.chainId }, { 'the network': net.genesis });
94
+ if (l.record && l.record.entry.retiredGenesis.includes(net.genesis)) {
95
+ d.unshift(`the node serves genesis ${net.genesis}, which the signed release record lists in retired_genesis for chain ${l.record.entry.chainId}`);
96
+ }
97
+ if (d.length)
98
+ throw new pins_js_1.PinMismatch((0, pins_js_1.pinRefusal)(pin, d));
99
+ return pin;
100
+ }
101
+ function presetPinOrNull(p) {
102
+ try {
103
+ return presetPin(p);
104
+ }
105
+ catch {
106
+ return null;
107
+ }
108
+ }
32
109
  /** The pin a preset is held to: its own `pin`, else the pin of the named network it names; null when it has none. */
33
110
  function presetPin(p) {
34
111
  const named = Object.prototype.hasOwnProperty.call(pins_js_1.PINS, p.name) ? pins_js_1.PINS[p.name] : undefined;
@@ -46,7 +123,14 @@ function presetPin(p) {
46
123
  * `PinMismatch` when what it reported differs from the pin; nothing may be signed then.
47
124
  */
48
125
  function signingPin(net) {
49
- const pin = presetPin(net);
126
+ if (net.recordLive) {
127
+ const live = recordSigningPin(net, net.recordLive);
128
+ if (live)
129
+ return live;
130
+ }
131
+ if (net.recordProblem)
132
+ throw net.record || presetPinOrNull(net) ? new pins_js_1.PinMismatch(net.recordProblem) : new pins_js_1.UnpinnedNetwork(net.recordProblem);
133
+ const pin = net.record && net.pin ? net.pin : presetPin(net);
50
134
  if (net.pinProblem)
51
135
  throw pin ? new pins_js_1.PinMismatch(net.pinProblem) : new pins_js_1.UnpinnedNetwork(net.pinProblem);
52
136
  if (!pin)
@@ -114,17 +198,48 @@ async function rpcChainId(rpc, transport, timeoutMs) {
114
198
  * `eth_chainId` name the same chain id, the spec and the node the same genesis, and the spec's `testnet` flag matches
115
199
  * the preset (a test network never stands in for the main network, nor the reverse).
116
200
  *
117
- * The reports are then held to the network's pin. When they differ (or the network has no pin) the connection still
118
- * reads, `pinProblem` says why, `onPinProblem` (when given) is called with it, and every signature is refused
119
- * (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
201
+ * The network's identity comes from the signed release record when one is served (its genesis for the network's chain
202
+ * id; see `readRecord`), else from its pin. When the reports differ (or the network has no identity, or the served
203
+ * record cannot be used) the connection still reads, `pinProblem` says why, `onPinProblem` (when given) is called with
204
+ * it, and every signature is refused (`PinMismatch` / `UnpinnedNetwork`). The SDK prints nothing.
120
205
  */
121
206
  async function connectNetwork(network = 'testnet', opts = {}) {
122
207
  const p = typeof network === 'string' ? exports.NETWORKS[network] : network;
123
208
  if (!p)
124
209
  throw new errors_js_1.VordiumError('unknown_network', `Unknown network ${String(network)}; known: mainnet, testnet.`);
125
- const pin = presetPin(p);
210
+ const named = Object.prototype.hasOwnProperty.call(pins_js_1.PINS, p.name) ? pins_js_1.PINS[p.name] : undefined;
211
+ if (p.recordChainId !== undefined && (!Number.isSafeInteger(p.recordChainId) || p.recordChainId <= 0 || p.pin || named)) {
212
+ throw new errors_js_1.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.');
213
+ }
214
+ const hardPin = presetPin(p);
126
215
  const t = opts.transport ?? http_js_1.fetchTransport;
127
216
  const ms = opts.timeoutMs ?? 10000;
217
+ // The identity: the signed record's for a named network or a record-only chain id; an explicit pin of your own skips it.
218
+ const recordChain = p.recordChainId ?? (named ? named.chainId : null);
219
+ let record = null;
220
+ let recordProblem = null;
221
+ let recordLive;
222
+ if (recordChain !== null) {
223
+ const urls = p.releaseRecord ? [p.releaseRecord]
224
+ : p.recordChainId !== undefined ? Object.values(releaseRecord_js_1.RELEASE_RECORD_URLS).flat() // a chain only the record names: every address
225
+ : releaseRecord_js_1.RELEASE_RECORD_URLS[p.name] ?? [];
226
+ const read = { transport: t, timeoutMs: ms, store: opts.releaseRecordStore, now: opts.releaseRecordNow };
227
+ try {
228
+ const keys = (0, releaseRecord_js_1.pinnedKeys)(opts.releaseKeys);
229
+ recordLive = { chainId: recordChain, urls, keys, byChain: p.recordChainId !== undefined, read, record: null, problem: null, at: Date.now() };
230
+ record = await (0, releaseRecord_js_1.readRecord)(recordChain, urls, keys, read);
231
+ }
232
+ catch (e) {
233
+ if (!(e instanceof releaseRecord_js_1.RecordRefused))
234
+ throw e;
235
+ recordProblem = `${e.message} Nothing was signed.`;
236
+ }
237
+ if (!record && !recordProblem && p.recordChainId !== undefined)
238
+ recordProblem = noRecordText(p.recordChainId);
239
+ if (recordLive)
240
+ Object.assign(recordLive, { record, problem: recordProblem, at: Date.now() });
241
+ }
242
+ const pin = record ? Object.freeze({ ...(p.name ? { name: p.name } : {}), chainId: recordChain, genesis: record.entry.genesis }) : hardPin;
128
243
  const sr = await t.get(p.spec, ms);
129
244
  if (sr.status !== 200 || !sr.body || typeof sr.body !== 'object')
130
245
  throw new errors_js_1.VordiumError('no_spec', `The network spec at ${p.spec} could not be read.`);
@@ -151,16 +266,19 @@ async function connectNetwork(network = 'testnet', opts = {}) {
151
266
  if (specGenesis !== null && specGenesis !== ident.genesis) {
152
267
  throw new errors_js_1.NetworkMismatch(`The spec names genesis ${specGenesis.slice(0, 8)}…, the node ${ident.genesis.slice(0, 8)}…; refusing to sign.`);
153
268
  }
154
- let pinProblem = null;
155
- if (!pin) {
269
+ let pinProblem = recordProblem;
270
+ if (!pinProblem && !pin) {
156
271
  pinProblem = unpinnedText(p);
157
272
  }
158
- else {
273
+ else if (!pinProblem && pin) {
159
274
  const d = (0, pins_js_1.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 });
275
+ if (record && record.entry.retiredGenesis.includes(ident.genesis)) {
276
+ d.unshift(`the node serves genesis ${ident.genesis}, which the signed release record lists in retired_genesis for chain ${record.entry.chainId}`);
277
+ }
160
278
  if (d.length)
161
279
  pinProblem = (0, pins_js_1.pinRefusal)(pin, d);
162
280
  }
163
281
  if (pinProblem && opts.onPinProblem)
164
282
  opts.onPinProblem(pinProblem);
165
- return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem };
283
+ return { ...p, ...(pin ? { pin } : {}), chainId: ident.chainId, genesis: ident.genesis, specRead: spec, pinProblem, record, recordProblem, ...(recordLive ? { recordLive } : {}) };
166
284
  }
package/dist/cjs/nonce.js CHANGED
@@ -280,12 +280,16 @@ function fileNonceStore(dir, opts = {}) {
280
280
  let done = null;
281
281
  try {
282
282
  let last = 0;
283
+ let text = null;
283
284
  try {
284
- const t = (await fs.readFile(file, 'utf8')).trim();
285
- if (/^\d+$/.test(t))
286
- last = Number(t);
285
+ text = (await fs.readFile(file, 'utf8')).trim();
287
286
  }
288
287
  catch { /* no mark yet */ }
288
+ if (text !== null && /^\d+$/.test(text))
289
+ last = Number(text);
290
+ else if (text !== null && opts?.strict) {
291
+ throw new errors_js_1.VordiumError('state_unreadable', `The mark in ${file} cannot be read. Check the file, or remove it to start again.`);
292
+ }
289
293
  let n = last, claimed = false, seen = [];
290
294
  if (!unique)
291
295
  n = fn(last); // a record, not a nonce