-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathencodeToCapData.js
447 lines (428 loc) · 16.1 KB
/
encodeToCapData.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/// <reference types="ses"/>
// This module is based on the `encodePassable.js` in `@agoric/store`,
// which may migrate here. The main external difference is that
// `encodePassable` goes directly to string, whereas `encodeToCapData`
// encodes to CapData, a JSON-representable data structure, and leaves it to
// the caller (`marshal.js`) to stringify it.
import { X, Fail, q } from '@endo/errors';
import { freezeOrSuppressTrapping } from 'ses/nonTrappingShimAdapter.js';
import {
passStyleOf,
isErrorLike,
makeTagged,
isObject,
getTag,
hasOwnPropertyOf,
assertPassableSymbol,
nameForPassableSymbol,
passableSymbolForName,
} from '@endo/pass-style';
/** @import {Passable, RemotableObject} from '@endo/pass-style' */
/** @import {Encoding, EncodingUnion} from './types.js' */
const { ownKeys } = Reflect;
const { isArray } = Array;
const {
getOwnPropertyDescriptors,
defineProperties,
is,
entries,
fromEntries,
} = Object;
/**
* Special property name that indicates an encoding that needs special
* decoding.
*/
const QCLASS = '@qclass';
export { QCLASS };
/**
* @param {Encoding} encoded
* @returns {encoded is EncodingUnion}
*/
const hasQClass = encoded => hasOwnPropertyOf(encoded, QCLASS);
/**
* @param {Encoding} encoded
* @param {string} qclass
* @returns {boolean}
*/
const qclassMatches = (encoded, qclass) =>
isObject(encoded) &&
!isArray(encoded) &&
hasQClass(encoded) &&
encoded[QCLASS] === qclass;
/**
* @typedef {object} EncodeToCapDataOptions
* @property {(
* remotable: RemotableObject,
* encodeRecur: (p: Passable) => Encoding
* ) => Encoding} [encodeRemotableToCapData]
* @property {(
* promise: Promise,
* encodeRecur: (p: Passable) => Encoding
* ) => Encoding} [encodePromiseToCapData]
* @property {(
* error: Error,
* encodeRecur: (p: Passable) => Encoding
* ) => Encoding} [encodeErrorToCapData]
*/
const dontEncodeRemotableToCapData = rem => Fail`remotable unexpected: ${rem}`;
const dontEncodePromiseToCapData = prom => Fail`promise unexpected: ${prom}`;
const dontEncodeErrorToCapData = err => Fail`error object unexpected: ${err}`;
/**
* @param {EncodeToCapDataOptions} [encodeOptions]
* @returns {(passable: Passable) => Encoding}
*/
export const makeEncodeToCapData = (encodeOptions = {}) => {
const {
encodeRemotableToCapData = dontEncodeRemotableToCapData,
encodePromiseToCapData = dontEncodePromiseToCapData,
encodeErrorToCapData = dontEncodeErrorToCapData,
} = encodeOptions;
/**
* Must encode `val` into plain JSON data *canonically*, such that
* `JSON.stringify(encode(v1)) === JSON.stringify(encode(v1))`. For most
* encodings, the order of properties of each node of the output
* structure is determined by the algorithm below without special
* arrangement, usually by being expressed directly as an object literal.
* The exception is copyRecords, whose natural enumeration order
* can differ between copyRecords that our distributed object semantics
* considers to be equivalent.
* Since, for each copyRecord, we only accept string property names,
* not symbols, we can canonically sort the names first.
* JSON.stringify will then visit these in that sorted order.
*
* Encoding with a canonical-JSON encoder would also solve this canonicalness
* problem in a more modular and encapsulated manner. Note that the
* actual order produced here, though it agrees with canonical-JSON on
* copyRecord property ordering, differs from canonical-JSON as a whole
* in that the other record properties are visited in the order in which
* they are literally written below. TODO perhaps we should indeed switch
* to a canonical JSON encoder, and not delicately depend on the order
* in which these object literals are written.
*
* Readers must not care about this order anyway. We impose this requirement
* mainly to reduce non-determinism exposed outside a vat.
*
* @param {any} passable
* @returns {Encoding} except that `encodeToCapData` does not generally
* `harden` this result before returning. Rather, `encodeToCapData` is not
* directly exposed.
* What's exposed instead is a wrapper that freezes the output before
* returning. If this turns out to impede static analysis for `harden` safety,
* we can always put the (now redundant) hardens back in. They don't hurt.
*/
const encodeToCapDataRecur = passable => {
// First we handle all primitives. Some can be represented directly as
// JSON, and some must be encoded as [QCLASS] composites.
const passStyle = passStyleOf(passable);
switch (passStyle) {
case 'null':
case 'boolean':
case 'string': {
// pass through to JSON
return passable;
}
case 'undefined': {
return { [QCLASS]: 'undefined' };
}
case 'number': {
// Special-case numbers with no digit-based representation.
if (Number.isNaN(passable)) {
return { [QCLASS]: 'NaN' };
} else if (passable === Infinity) {
return { [QCLASS]: 'Infinity' };
} else if (passable === -Infinity) {
return { [QCLASS]: '-Infinity' };
}
// Pass through everything else, replacing -0 with 0.
return is(passable, -0) ? 0 : passable;
}
case 'bigint': {
return {
[QCLASS]: 'bigint',
digits: String(passable),
};
}
case 'symbol': {
assertPassableSymbol(passable);
const name = /** @type {string} */ (nameForPassableSymbol(passable));
return {
[QCLASS]: 'symbol',
name,
};
}
case 'copyRecord': {
if (hasOwnPropertyOf(passable, QCLASS)) {
// Hilbert hotel
const { [QCLASS]: qclassValue, ...rest } = passable;
/** @type {Encoding} */
const result = {
[QCLASS]: 'hilbert',
original: encodeToCapDataRecur(qclassValue),
};
if (ownKeys(rest).length >= 1) {
// We harden the entire capData encoding before we return it.
// `encodeToCapData` requires that its input be Passable, and
// therefore hardened.
// The `freezeOrSuppressTrapping` here is needed anyway, because
// the `rest` is
// freshly constructed by the `...` above, and we're using it
// as input in another call to `encodeToCapData`.
result.rest = encodeToCapDataRecur(freezeOrSuppressTrapping(rest));
}
return result;
}
// Currently copyRecord allows only string keys so this will
// work. If we allow sortable symbol keys, this will need to
// become more interesting.
const names = ownKeys(passable).sort();
// TODO The following directive line should either be removed or
// turned back into an at-ts-expect-error. We made it into an
// at-ts-ignore because we were getting inconsistent reports.
// See https://github.com/endojs/endo/pull/2673#issuecomment-2566711810
// @ts-ignore Apparent confusion about `@qclass`
return fromEntries(
names.map(name => [name, encodeToCapDataRecur(passable[name])]),
);
}
case 'copyArray': {
return passable.map(encodeToCapDataRecur);
}
case 'tagged': {
return {
[QCLASS]: 'tagged',
tag: getTag(passable),
payload: encodeToCapDataRecur(passable.payload),
};
}
case 'remotable': {
const encoded = encodeRemotableToCapData(
passable,
encodeToCapDataRecur,
);
if (qclassMatches(encoded, 'slot')) {
return encoded;
}
// `throw` is noop since `Fail` throws. But linter confused
throw Fail`internal: Remotable encoding must be an object with ${q(
QCLASS,
)} ${q('slot')}: ${encoded}`;
}
case 'promise': {
const encoded = encodePromiseToCapData(passable, encodeToCapDataRecur);
if (qclassMatches(encoded, 'slot')) {
return encoded;
}
throw Fail`internal: Promise encoding must be an object with ${q(
QCLASS,
'slot',
)}: ${encoded}`;
}
case 'error': {
const encoded = encodeErrorToCapData(passable, encodeToCapDataRecur);
if (qclassMatches(encoded, 'error')) {
return encoded;
}
throw Fail`internal: Error encoding must be an object with ${q(
QCLASS,
'error',
)}: ${encoded}`;
}
default: {
throw assert.fail(
X`internal: Unrecognized passStyle ${q(passStyle)}`,
TypeError,
);
}
}
};
const encodeToCapData = passable => {
if (isErrorLike(passable)) {
// We pull out this special case to accommodate errors that are not
// valid Passables. For example, because they're not frozen.
// The special case can only ever apply at the root, and therefore
// outside the recursion, since an error could only be deeper in
// a passable structure if it were passable.
//
// We pull out this special case because, for these errors, we're much
// more interested in reporting whatever diagnostic information they
// carry than we are about reporting problems encountered in reporting
// this information.
return harden(encodeErrorToCapData(passable, encodeToCapDataRecur));
}
return harden(encodeToCapDataRecur(passable));
};
return harden(encodeToCapData);
};
harden(makeEncodeToCapData);
/**
* @typedef {object} DecodeOptions
* @property {(
* encodedRemotable: Encoding,
* decodeRecur: (e: Encoding) => Passable
* ) => (Promise|RemotableObject)} [decodeRemotableFromCapData]
* @property {(
* encodedPromise: Encoding,
* decodeRecur: (e: Encoding) => Passable
* ) => (Promise|RemotableObject)} [decodePromiseFromCapData]
* @property {(
* encodedError: Encoding,
* decodeRecur: (e: Encoding) => Passable
* ) => Error} [decodeErrorFromCapData]
*/
const dontDecodeRemotableOrPromiseFromCapData = slotEncoding =>
Fail`remotable or promise unexpected: ${slotEncoding}`;
const dontDecodeErrorFromCapData = errorEncoding =>
Fail`error unexpected: ${errorEncoding}`;
/**
* The current encoding does not give the decoder enough into to distinguish
* whether a slot represents a promise or a remotable. As an implementation
* restriction until this is fixed, if either is provided, both must be
* provided and they must be the same.
*
* This seems like the best starting point to incrementally evolve to an
* API where these can reliably differ.
* See https://github.com/Agoric/agoric-sdk/issues/4334
*
* @param {DecodeOptions} [decodeOptions]
* @returns {(encoded: Encoding) => Passable}
*/
export const makeDecodeFromCapData = (decodeOptions = {}) => {
const {
decodeRemotableFromCapData = dontDecodeRemotableOrPromiseFromCapData,
decodePromiseFromCapData = dontDecodeRemotableOrPromiseFromCapData,
decodeErrorFromCapData = dontDecodeErrorFromCapData,
} = decodeOptions;
decodeRemotableFromCapData === decodePromiseFromCapData ||
Fail`An implementation restriction for now: If either decodeRemotableFromCapData or decodePromiseFromCapData is provided, both must be provided and they must be the same: ${q(
decodeRemotableFromCapData,
)} vs ${q(decodePromiseFromCapData)}`;
/**
* `decodeFromCapData` may rely on `jsonEncoded` being the result of a
* plain call to JSON.parse. However, it *cannot* rely on `jsonEncoded`
* having been produced by JSON.stringify on the output of `encodeToCapData`
* above, i.e., `decodeFromCapData` cannot rely on `jsonEncoded` being a
* valid marshalled representation. Rather, `decodeFromCapData` must
* validate that.
*
* @param {Encoding} jsonEncoded must be hardened
*/
const decodeFromCapData = jsonEncoded => {
if (!isObject(jsonEncoded)) {
// primitives pass through
return jsonEncoded;
}
if (isArray(jsonEncoded)) {
return jsonEncoded.map(encodedVal => decodeFromCapData(encodedVal));
} else if (hasQClass(jsonEncoded)) {
const qclass = jsonEncoded[QCLASS];
typeof qclass === 'string' ||
Fail`invalid ${q(QCLASS)} typeof ${q(typeof qclass)}`;
switch (qclass) {
// Encoding of primitives not handled by JSON
case 'undefined': {
return undefined;
}
case 'NaN': {
return NaN;
}
case 'Infinity': {
return Infinity;
}
case '-Infinity': {
return -Infinity;
}
case 'bigint': {
const { digits } = jsonEncoded;
typeof digits === 'string' ||
Fail`invalid digits typeof ${q(typeof digits)}`;
return BigInt(digits);
}
case '@@asyncIterator': {
// Deprecated qclass. TODO make conditional
// on environment variable. Eventually remove, but after confident
// that there are no more supported senders.
//
return Symbol.asyncIterator;
}
case 'symbol': {
const { name } = jsonEncoded;
return passableSymbolForName(name);
}
case 'tagged': {
const { tag, payload } = jsonEncoded;
return makeTagged(tag, decodeFromCapData(payload));
}
case 'slot': {
// See note above about how the current encoding cannot reliably
// distinguish which we should call, so in the non-default case
// both must be the same and it doesn't matter which we call.
const decoded = decodeRemotableFromCapData(
jsonEncoded,
decodeFromCapData,
);
// BEWARE: capdata does not check that `decoded` is
// a promise or a remotable, since that would break some
// capdata clients. We are deprecating capdata, and these clients
// will need to update before switching to smallcaps.
return decoded;
}
case 'error': {
const decoded = decodeErrorFromCapData(
jsonEncoded,
decodeFromCapData,
);
if (passStyleOf(decoded) === 'error') {
return decoded;
}
throw Fail`internal: decodeErrorFromCapData option must return an error: ${decoded}`;
}
case 'hilbert': {
const { original, rest } = jsonEncoded;
hasOwnPropertyOf(jsonEncoded, 'original') ||
Fail`Invalid Hilbert Hotel encoding ${jsonEncoded}`;
// Don't harden since we're not done mutating it
const result = { [QCLASS]: decodeFromCapData(original) };
if (hasOwnPropertyOf(jsonEncoded, 'rest')) {
const isNonEmptyObject =
typeof rest === 'object' &&
rest !== null &&
ownKeys(rest).length >= 1;
if (!isNonEmptyObject) {
throw Fail`Rest encoding must be a non-empty object: ${rest}`;
}
const restObj = decodeFromCapData(rest);
// TODO really should assert that `passStyleOf(rest)` is
// `'copyRecord'` but we'd have to harden it and it is too
// early to do that.
!hasOwnPropertyOf(restObj, QCLASS) ||
Fail`Rest must not contain its own definition of ${q(QCLASS)}`;
defineProperties(result, getOwnPropertyDescriptors(restObj));
}
return result;
}
// @ts-expect-error This is the error case we're testing for
case 'ibid': {
throw Fail`The capData protocol no longer supports ${q(QCLASS)} ${q(
qclass,
)}`;
}
default: {
throw assert.fail(
X`unrecognized ${q(QCLASS)} ${q(qclass)}`,
TypeError,
);
}
}
} else {
assert(typeof jsonEncoded === 'object' && jsonEncoded !== null);
const decodeEntry = ([name, encodedVal]) => {
typeof name === 'string' ||
Fail`Property ${q(name)} of ${jsonEncoded} must be a string`;
return [name, decodeFromCapData(encodedVal)];
};
const decodedEntries = entries(jsonEncoded).map(decodeEntry);
return fromEntries(decodedEntries);
}
};
return harden(decodeFromCapData);
};