@ocap/client 1.30.26 → 1.31.0
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/dist/base.js +1 -1
- package/dist/browser.d.ts +108 -0
- package/dist/bundle.js +1 -1
- package/dist/extension.js +15 -4
- package/dist/extension.js.map +1 -1
- package/dist/report.html +2 -2
- package/dist/schema/graphql.json +1099 -110
- package/dist/schema/graphql.txt +2 -2
- package/dist/types.js +263 -1
- package/dist/types.js.map +1 -1
- package/dist/verify.js +307 -8
- package/dist/verify.js.map +1 -1
- package/docs/QUERIES.md +175 -5
- package/docs/README.md +515 -111
- package/lib/base.js +1 -1
- package/lib/extension.js +15 -4
- package/lib/extension.js.map +1 -1
- package/lib/node.d.ts +108 -0
- package/lib/schema/graphql.json +1099 -110
- package/lib/schema/graphql.txt +2 -2
- package/lib/types.js +263 -1
- package/lib/types.js.map +1 -1
- package/lib/verify.js +307 -8
- package/lib/verify.js.map +1 -1
- package/package.json +11 -11
package/lib/verify.js
CHANGED
|
@@ -1,11 +1,266 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');
|
|
4
|
+
const { formatMessage, toTypeUrl } = require('@ocap/message');
|
|
5
|
+
const { CANONICAL_SELF_DESCRIBE_PREFIX, decodeTx: decodeCbor, encodeTx: encodeCbor } = require('@ocap/message/cbor');
|
|
6
|
+
const { decodeTx: decodeProto, encodeTx: encodeProto } = require('@ocap/message/protobuf');
|
|
4
7
|
|
|
5
8
|
function normalizeHex(hex) {
|
|
6
9
|
return String(hex || '').replace(/^0x/i, '').toLowerCase();
|
|
7
10
|
}
|
|
8
11
|
|
|
12
|
+
function isPlainObject(value) {
|
|
13
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
const proto = Object.getPrototypeOf(value);
|
|
17
|
+
return proto === Object.prototype || proto === null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function stableStringify(value) {
|
|
21
|
+
if (value === null || typeof value !== 'object') {
|
|
22
|
+
return JSON.stringify(value);
|
|
23
|
+
}
|
|
24
|
+
if (Array.isArray(value)) {
|
|
25
|
+
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
26
|
+
}
|
|
27
|
+
if (!isPlainObject(value)) {
|
|
28
|
+
return JSON.stringify(String(value));
|
|
29
|
+
}
|
|
30
|
+
const keys = Object.keys(value).filter(k => value[k] !== undefined).sort();
|
|
31
|
+
return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function hasCborSelfDescribeTag(buf) {
|
|
35
|
+
return buf.length >= CANONICAL_SELF_DESCRIBE_PREFIX.length && buf[0] === CANONICAL_SELF_DESCRIBE_PREFIX[0] && buf[1] === CANONICAL_SELF_DESCRIBE_PREFIX[1] && buf[2] === CANONICAL_SELF_DESCRIBE_PREFIX[2];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function sameBytes(a, b) {
|
|
39
|
+
if (a.length !== b.length) return false;
|
|
40
|
+
for (let i = 0; i < a.length; i++) {
|
|
41
|
+
if (a[i] !== b[i]) return false;
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function validatePresentEntryPrimitives(entry) {
|
|
47
|
+
const stringFields = ['from', 'pk', 'signature', 'chainId', 'txType'];
|
|
48
|
+
for (let i = 0; i < stringFields.length; i++) {
|
|
49
|
+
const field = stringFields[i];
|
|
50
|
+
const val = entry[field];
|
|
51
|
+
if (val !== undefined && val !== null && typeof val !== 'string') {
|
|
52
|
+
return `Entry ${field} must be a string`;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (entry.nonce !== undefined && entry.nonce !== null) {
|
|
56
|
+
const isNum = typeof entry.nonce === 'number' && Number.isFinite(entry.nonce);
|
|
57
|
+
const isStr = typeof entry.nonce === 'string';
|
|
58
|
+
if (!isNum && !isStr) {
|
|
59
|
+
return 'Entry nonce must be a finite number or string';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function tryDecodeOcapWireTx(txRaw) {
|
|
66
|
+
const trimmed = String(txRaw || '').trim();
|
|
67
|
+
if (!trimmed || trimmed.startsWith('{')) return { kind: 'none' };
|
|
68
|
+
let rawBuf;
|
|
69
|
+
try {
|
|
70
|
+
rawBuf = Buffer.from(trimmed, 'base64');
|
|
71
|
+
} catch (_err) {
|
|
72
|
+
return { kind: 'none' };
|
|
73
|
+
}
|
|
74
|
+
if (rawBuf.length === 0) {
|
|
75
|
+
return { kind: 'none' };
|
|
76
|
+
}
|
|
77
|
+
const isCanonicalBase64 = rawBuf.toString('base64') === trimmed;
|
|
78
|
+
const rawBytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);
|
|
79
|
+
|
|
80
|
+
if (hasCborSelfDescribeTag(rawBytes)) {
|
|
81
|
+
if (!isCanonicalBase64) {
|
|
82
|
+
return { kind: 'invalid', reason: 'Non-canonical base64 encoding in entry txRaw' };
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const decoded = decodeCbor(rawBytes);
|
|
86
|
+
const reencoded = encodeCbor(decoded);
|
|
87
|
+
if (!sameBytes(rawBytes, reencoded)) {
|
|
88
|
+
return { kind: 'invalid', reason: 'Invalid canonical CBOR transaction in entry txRaw' };
|
|
89
|
+
}
|
|
90
|
+
return { kind: 'ocap', formattedTx: formatMessage('Transaction', decoded) };
|
|
91
|
+
} catch (_err) {
|
|
92
|
+
return { kind: 'invalid', reason: 'Failed to decode CBOR transaction in entry txRaw' };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const decoded = decodeProto(rawBytes);
|
|
98
|
+
const hasTxField = Boolean(decoded.from || decoded.pk && decoded.pk.length > 0 || decoded.signature && decoded.signature.length > 0 || decoded.chainId || decoded.itx && typeof decoded.itx === 'object' && decoded.itx.typeUrl);
|
|
99
|
+
if (!hasTxField) return { kind: 'none' };
|
|
100
|
+
|
|
101
|
+
const formattedTx = formatMessage('Transaction', decoded);
|
|
102
|
+
const reencodeInput = Object.assign({}, decoded);
|
|
103
|
+
const rawItx = decoded.itx;
|
|
104
|
+
if (rawItx && typeof rawItx === 'object' && rawItx.typeUrl) {
|
|
105
|
+
if (rawItx.typeUrl === 'json' || rawItx.typeUrl === 'vc') {
|
|
106
|
+
reencodeInput.itx = formattedTx.itx;
|
|
107
|
+
} else if (!rawItx.value) {
|
|
108
|
+
reencodeInput.itx = { typeUrl: rawItx.typeUrl, value: new Uint8Array(0) };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const reencoded = encodeProto(reencodeInput);
|
|
113
|
+
if (!sameBytes(rawBytes, reencoded)) return { kind: 'none' };
|
|
114
|
+
if (!isCanonicalBase64) {
|
|
115
|
+
return { kind: 'invalid', reason: 'Non-canonical base64 encoding in entry txRaw' };
|
|
116
|
+
}
|
|
117
|
+
return { kind: 'ocap', formattedTx };
|
|
118
|
+
} catch (_err) {
|
|
119
|
+
return { kind: 'none' };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function authenticateEntryDecodedFields(entry, strict) {
|
|
124
|
+
const primitiveErr = validatePresentEntryPrimitives(entry);
|
|
125
|
+
if (primitiveErr) {
|
|
126
|
+
return { ok: false, reason: primitiveErr };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const rawStr = String(entry.txRaw !== undefined && entry.txRaw !== null ? entry.txRaw : '').trim();
|
|
130
|
+
|
|
131
|
+
if (rawStr.startsWith('{')) {
|
|
132
|
+
let parsedRaw;
|
|
133
|
+
try {
|
|
134
|
+
const parsed = JSON.parse(rawStr);
|
|
135
|
+
if (!isPlainObject(parsed)) {
|
|
136
|
+
return { ok: false, reason: 'Entry txRaw JSON is not an object' };
|
|
137
|
+
}
|
|
138
|
+
parsedRaw = parsed;
|
|
139
|
+
} catch (_err) {
|
|
140
|
+
return { ok: false, reason: 'Entry txRaw is not valid JSON' };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (entry.tx !== undefined && entry.tx !== null) {
|
|
144
|
+
let entryTxObj = entry.tx;
|
|
145
|
+
if (typeof entryTxObj === 'string') {
|
|
146
|
+
try {
|
|
147
|
+
entryTxObj = JSON.parse(entryTxObj);
|
|
148
|
+
} catch (_err) {
|
|
149
|
+
return { ok: false, reason: 'Entry tx is not valid JSON' };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (!isPlainObject(entryTxObj) || stableStringify(entryTxObj) !== stableStringify(parsedRaw)) {
|
|
153
|
+
return { ok: false, reason: 'Entry tx does not match authenticated txRaw' };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const rawFrom = parsedRaw.from !== undefined && parsedRaw.from !== null ? parsedRaw.from : parsedRaw.spenderDid;
|
|
158
|
+
if (rawFrom !== undefined && rawFrom !== null && entry.from !== undefined && entry.from !== null) {
|
|
159
|
+
if (String(entry.from) !== String(rawFrom)) {
|
|
160
|
+
return { ok: false, reason: `Entry from mismatch: expected ${rawFrom}, got ${entry.from}` };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (parsedRaw.nonce !== undefined && parsedRaw.nonce !== null && entry.nonce !== undefined && entry.nonce !== null) {
|
|
164
|
+
if (String(entry.nonce) !== String(parsedRaw.nonce)) {
|
|
165
|
+
return { ok: false, reason: `Entry nonce mismatch: expected ${parsedRaw.nonce}, got ${entry.nonce}` };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const rawPk = parsedRaw.pk !== undefined && parsedRaw.pk !== null ? parsedRaw.pk : parsedRaw.spenderPublicKey;
|
|
169
|
+
if (rawPk !== undefined && rawPk !== null && entry.pk !== undefined && entry.pk !== null) {
|
|
170
|
+
if (String(entry.pk) !== String(rawPk)) {
|
|
171
|
+
return { ok: false, reason: `Entry pk mismatch: expected ${rawPk}, got ${entry.pk}` };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const rawSig = parsedRaw.signature !== undefined && parsedRaw.signature !== null ? parsedRaw.signature : parsedRaw.spenderSignature;
|
|
175
|
+
if (rawSig !== undefined && rawSig !== null && entry.signature !== undefined && entry.signature !== null) {
|
|
176
|
+
if (String(entry.signature) !== String(rawSig)) {
|
|
177
|
+
return { ok: false, reason: `Entry signature mismatch: expected ${rawSig}, got ${entry.signature}` };
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (parsedRaw.chainId !== undefined && parsedRaw.chainId !== null && entry.chainId !== undefined && entry.chainId !== null) {
|
|
181
|
+
if (String(entry.chainId) !== String(parsedRaw.chainId)) {
|
|
182
|
+
return { ok: false, reason: `Entry chainId mismatch: expected ${parsedRaw.chainId}, got ${entry.chainId}` };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (parsedRaw.txType !== undefined && parsedRaw.txType !== null && entry.txType !== undefined && entry.txType !== null) {
|
|
186
|
+
if (String(entry.txType) !== String(parsedRaw.txType)) {
|
|
187
|
+
return { ok: false, reason: `Entry txType mismatch: expected ${parsedRaw.txType}, got ${entry.txType}` };
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { ok: true, decodedTx: parsedRaw };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const decodedResult = tryDecodeOcapWireTx(rawStr);
|
|
195
|
+
if (decodedResult.kind === 'invalid') {
|
|
196
|
+
return { ok: false, reason: decodedResult.reason };
|
|
197
|
+
}
|
|
198
|
+
if (decodedResult.kind === 'none') {
|
|
199
|
+
if (strict) {
|
|
200
|
+
return { ok: false, reason: 'Failed to decode entry txRaw as canonical transaction' };
|
|
201
|
+
}
|
|
202
|
+
return { ok: true };
|
|
203
|
+
}
|
|
204
|
+
const formattedTx = decodedResult.formattedTx;
|
|
205
|
+
|
|
206
|
+
const expectedFrom = String(formattedTx.from || '');
|
|
207
|
+
if (entry.from !== undefined && entry.from !== null && String(entry.from) !== expectedFrom) {
|
|
208
|
+
return { ok: false, reason: `Entry from mismatch: expected ${expectedFrom}, got ${entry.from}` };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const expectedNonce = String(formattedTx.nonce !== undefined && formattedTx.nonce !== null ? formattedTx.nonce : 0);
|
|
212
|
+
if (entry.nonce !== undefined && entry.nonce !== null && String(entry.nonce) !== expectedNonce) {
|
|
213
|
+
return { ok: false, reason: `Entry nonce mismatch: expected ${expectedNonce}, got ${entry.nonce}` };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const expectedPk = String(formattedTx.pk || '');
|
|
217
|
+
if (entry.pk !== undefined && entry.pk !== null && String(entry.pk) !== expectedPk) {
|
|
218
|
+
return { ok: false, reason: `Entry pk mismatch: expected ${expectedPk}, got ${entry.pk}` };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const expectedSig = String(formattedTx.signature || '');
|
|
222
|
+
if (entry.signature !== undefined && entry.signature !== null && String(entry.signature) !== expectedSig) {
|
|
223
|
+
return { ok: false, reason: `Entry signature mismatch: expected ${expectedSig}, got ${entry.signature}` };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const expectedChainId = String(formattedTx.chainId || '');
|
|
227
|
+
if (entry.chainId !== undefined && entry.chainId !== null && String(entry.chainId) !== expectedChainId) {
|
|
228
|
+
return { ok: false, reason: `Entry chainId mismatch: expected ${expectedChainId}, got ${entry.chainId}` };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const itxObj = formattedTx.itx;
|
|
232
|
+
const rawItxType = itxObj && (itxObj.type || itxObj.typeUrl) || '';
|
|
233
|
+
if (entry.txType !== undefined && entry.txType !== null) {
|
|
234
|
+
if (!rawItxType) {
|
|
235
|
+
if (String(entry.txType) !== '') {
|
|
236
|
+
return { ok: false, reason: `Entry txType mismatch: expected empty, got ${entry.txType}` };
|
|
237
|
+
}
|
|
238
|
+
} else {
|
|
239
|
+
const mappedTypeUrl = rawItxType.includes(':') ? rawItxType : toTypeUrl(rawItxType);
|
|
240
|
+
const expectedTypeUrl = mappedTypeUrl || rawItxType;
|
|
241
|
+
if (String(entry.txType) !== rawItxType && String(entry.txType) !== expectedTypeUrl) {
|
|
242
|
+
return { ok: false, reason: `Entry txType mismatch: expected ${expectedTypeUrl}, got ${entry.txType}` };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (entry.tx !== undefined && entry.tx !== null) {
|
|
248
|
+
let entryTxObj = entry.tx;
|
|
249
|
+
if (typeof entryTxObj === 'string') {
|
|
250
|
+
try {
|
|
251
|
+
entryTxObj = JSON.parse(entryTxObj);
|
|
252
|
+
} catch (_err) {
|
|
253
|
+
return { ok: false, reason: 'Entry tx is not valid JSON' };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (!isPlainObject(entryTxObj) || stableStringify(entryTxObj) !== stableStringify(formattedTx)) {
|
|
257
|
+
return { ok: false, reason: 'Entry tx does not match authenticated txRaw' };
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return { ok: true, decodedTx: formattedTx };
|
|
262
|
+
}
|
|
263
|
+
|
|
9
264
|
function sha256Buf(data) {
|
|
10
265
|
const hex = Hasher.SHA2.hash256(data, 1, 'hex');
|
|
11
266
|
return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');
|
|
@@ -54,8 +309,17 @@ function verifyMerkleProof(leaf, index, proof, root, treeSize) {
|
|
|
54
309
|
return currentHash.equals(root);
|
|
55
310
|
}
|
|
56
311
|
|
|
312
|
+
// Entry hash versions (#1337). v1 = legacy plain concatenation written by nodes <= 1.30.26,
|
|
313
|
+
// v2 = length-prefixed framing (#1325). The version is a function of the sequence on the node side.
|
|
314
|
+
function computeEntryHashV1(sequence, txRaw, stateCommitHash = '') {
|
|
315
|
+
return Hasher.SHA2.hash256(Buffer.concat([Buffer.from(String(sequence), 'utf8'), Buffer.from(String(txRaw == null ? '' : txRaw), 'utf8'), Buffer.from(String(stateCommitHash == null ? '' : stateCommitHash), 'utf8')]), 1, 'hex');
|
|
316
|
+
}
|
|
317
|
+
|
|
57
318
|
function computeEntryHash(sequence, txRaw, stateCommitHash = '') {
|
|
58
|
-
const
|
|
319
|
+
const seqBytes = Buffer.from(String(sequence), 'utf8');
|
|
320
|
+
const txBytes = Buffer.from(String(txRaw == null ? '' : txRaw), 'utf8');
|
|
321
|
+
const stateBytes = Buffer.from(String(stateCommitHash == null ? '' : stateCommitHash), 'utf8');
|
|
322
|
+
const data = Buffer.concat([Buffer.from(`seq:${seqBytes.length}:`, 'utf8'), seqBytes, Buffer.from(`|tx:${txBytes.length}:`, 'utf8'), txBytes, Buffer.from(`|state:${stateBytes.length}:`, 'utf8'), stateBytes]);
|
|
59
323
|
return Hasher.SHA2.hash256(data, 1, 'hex');
|
|
60
324
|
}
|
|
61
325
|
|
|
@@ -140,9 +404,9 @@ function resolveTrustAnchor(params) {
|
|
|
140
404
|
/**
|
|
141
405
|
* Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).
|
|
142
406
|
*
|
|
143
|
-
*
|
|
144
|
-
* `entry.tx`, `from`, `pk`, `nonce
|
|
145
|
-
* fields
|
|
407
|
+
* When `txRaw` is an OCAP wire transaction (CBOR/Protobuf) or canonical JSON payload, `verifyTxInclusion`
|
|
408
|
+
* decodes `txRaw` and authenticates any present `entry.tx`, `from`, `pk`, `nonce`, `signature`, `txType`,
|
|
409
|
+
* and `chainId` fields against the decoded payload (#1139), attaching `decodedTx` on the result.
|
|
146
410
|
*
|
|
147
411
|
* @param {object} params
|
|
148
412
|
* @param {object} params.checkpoint
|
|
@@ -150,13 +414,14 @@ function resolveTrustAnchor(params) {
|
|
|
150
414
|
* @param {object} params.entry
|
|
151
415
|
* @param {string} [params.txHash]
|
|
152
416
|
* @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)
|
|
417
|
+
* @param {boolean} [params.verifyDecodedEntry] - controls decoded entry field verification (#1139)
|
|
153
418
|
* @param {string} [params.expectedProposer]
|
|
154
419
|
* @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is
|
|
155
420
|
* required, otherwise the result is `{ verified: false }` (#1133)
|
|
156
421
|
* @param {Function} [params.verifier]
|
|
157
422
|
* @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor
|
|
158
423
|
* is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.
|
|
159
|
-
* @returns {Promise<{ verified: boolean, reason?: string }>}
|
|
424
|
+
* @returns {Promise<{ verified: boolean, reason?: string, decodedTx?: object }>}
|
|
160
425
|
*/
|
|
161
426
|
async function verifyTxInclusion(params) {
|
|
162
427
|
try {
|
|
@@ -212,8 +477,23 @@ async function verifyTxInclusion(params) {
|
|
|
212
477
|
};
|
|
213
478
|
}
|
|
214
479
|
|
|
215
|
-
|
|
216
|
-
|
|
480
|
+
// v2 (length-prefixed) first, then legacy v1 so proofs from 1.30.26 nodes keep verifying (#1337).
|
|
481
|
+
// With params.entryHashV2From the version is exact: seq >= v2From -> v2, below -> v1.
|
|
482
|
+
// allowLegacyEntryHash:false (without a pin) refuses v1. v1's boundary ambiguity cannot be
|
|
483
|
+
// exploited here because entry.hash == toTxHash(txRaw) (default on) and the Merkle index pin
|
|
484
|
+
// txRaw and sequence; pass entryHashV2From if you also disable verifyTxRawHash.
|
|
485
|
+
const v2Hash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');
|
|
486
|
+
const v1Hash = computeEntryHashV1(seq, entry.txRaw, entry.stateCommitHash || '');
|
|
487
|
+
const pinned = params.entryHashV2From === undefined ? undefined : seq >= Number(params.entryHashV2From) ? 2 : 1;
|
|
488
|
+
const legacyAllowed = pinned === 1 || pinned === undefined && params.allowLegacyEntryHash !== false;
|
|
489
|
+
const givenHash = normalizeHex(entry.entryHash);
|
|
490
|
+
let recomputedEntryHash = v2Hash;
|
|
491
|
+
if (pinned !== 2 && legacyAllowed && givenHash !== normalizeHex(v2Hash) && givenHash === normalizeHex(v1Hash)) {
|
|
492
|
+
recomputedEntryHash = v1Hash;
|
|
493
|
+
} else if (pinned === 1) {
|
|
494
|
+
recomputedEntryHash = v1Hash;
|
|
495
|
+
}
|
|
496
|
+
if (givenHash !== normalizeHex(recomputedEntryHash)) {
|
|
217
497
|
return {
|
|
218
498
|
verified: false,
|
|
219
499
|
reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`
|
|
@@ -262,7 +542,25 @@ async function verifyTxInclusion(params) {
|
|
|
262
542
|
}
|
|
263
543
|
}
|
|
264
544
|
|
|
265
|
-
|
|
545
|
+
let decodedTx;
|
|
546
|
+
if (params.verifyDecodedEntry !== false) {
|
|
547
|
+
const authFields = authenticateEntryDecodedFields(entry, params.verifyDecodedEntry === true);
|
|
548
|
+
if (!authFields.ok) {
|
|
549
|
+
return { verified: false, reason: authFields.reason };
|
|
550
|
+
}
|
|
551
|
+
decodedTx = authFields.decodedTx;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const res = { verified: true };
|
|
555
|
+
if (decodedTx !== undefined) {
|
|
556
|
+
Object.defineProperty(res, 'decodedTx', {
|
|
557
|
+
value: decodedTx,
|
|
558
|
+
enumerable: false,
|
|
559
|
+
configurable: true,
|
|
560
|
+
writable: true
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
return res;
|
|
266
564
|
} catch (err) {
|
|
267
565
|
return {
|
|
268
566
|
verified: false,
|
|
@@ -275,6 +573,7 @@ module.exports = {
|
|
|
275
573
|
verifyTxInclusion,
|
|
276
574
|
verifyCheckpointSignature,
|
|
277
575
|
computeEntryHash,
|
|
576
|
+
computeEntryHashV1,
|
|
278
577
|
computeCheckpointHash
|
|
279
578
|
};
|
|
280
579
|
//# sourceMappingURL=verify.js.map
|
package/lib/verify.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/verify.js"],"names":["Hasher","Signer","toTxHash","require","normalizeHex","hex","String","replace","toLowerCase","sha256Buf","data","SHA2","hash256","Buffer","from","hashPair","left","right","concat","merkleProofLength","treeSize","depth","width","Math","ceil","verifyMerkleProof","leaf","index","proof","root","Number","isInteger","undefined","length","equals","currentHash","currentIndex","i","sibling","floor","computeEntryHash","sequence","txRaw","stateCommitHash","computeCheckpointHash","checkpoint","JSON","stringify","height","prevSequence","txRoot","txCount","stateRoot","timestamp","prevCheckpoint","proposer","verifyCheckpointSignature","publicKeyOrVerifier","expectedProposer","hash","signature","recomputedHash","hashBytes","_err","Ed25519","verify","sha3Digest","SHA3","sha2Digest","NO_TRUST_ANCHOR_REASON","resolveTrustAnchor","params","verifier","pk","proposerPublicKey","bare","trim","test","Uint8Array","verifyTxInclusion","entry","verified","reason","txHash","trustAnchor","allowUnauthenticated","verifyTxRawHash","seq","prevSeq","cpSeq","expectedIndex","recomputedEntryHash","entryHash","expectedLeafHash","leafBuf","proofBufs","map","p","rootBuf","recomputedCpHash","sigValid","err","Error","message","module","exports"],"mappings":";;AAAA,MAAM,EAAEA,MAAF,EAAUC,MAAV,EAAkBC,QAAlB,KAA+BC,QAAQ,eAAR,CAArC;;AAEA,SAASC,YAAT,CAAsBC,GAAtB,EAA2B;AACzB,SAAOC,OAAOD,OAAO,EAAd,EACJE,OADI,CACI,MADJ,EACY,EADZ,EAEJC,WAFI,EAAP;AAGD;;AAED,SAASC,SAAT,CAAmBC,IAAnB,EAAyB;AACvB,QAAML,MAAML,OAAOW,IAAP,CAAYC,OAAZ,CAAoBF,IAApB,EAA0B,CAA1B,EAA6B,KAA7B,CAAZ;AACA,SAAOG,OAAOC,IAAP,CAAYR,OAAOD,GAAP,EAAYE,OAAZ,CAAoB,MAApB,EAA4B,E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asher, Signer, toTxHash } = require('@ocap/mcrypto');\n\nfunction normalizeHex(hex) {\n return String(hex || '')\n .replace(/^0x/i, '')\n .toLowerCase();\n}\n\nfunction sha256Buf(data) {\n const hex = Hasher.SHA2.hash256(data, 1, 'hex');\n return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');\n}\n\nfunction hashPair(left, right) {\n return sha256Buf(Buffer.concat([left, right]));\n}\n\n// Proof length for every leaf of a tree with `treeSize` leaves (odd last node pairs with itself)\nfunction merkleProofLength(treeSize) {\n let depth = 0;\n for (let width = treeSize; width > 1; width = Math.ceil(width / 2)) {\n depth++;\n }\n return depth;\n}\n\nfunction verifyMerkleProof(leaf, index, proof, root, treeSize) {\n if (!Number.isInteger(index) || index < 0) {\n return false;\n }\n // #972: bind the proof to the checkpoint's tree size\n if (treeSize !== undefined) {\n if (\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index >= treeSize ||\n proof.length !== merkleProofLength(treeSize)\n ) {\n return false;\n }\n }\n if (proof.length === 0) {\n return index === 0 && leaf.equals(root);\n }\n let currentHash = leaf;\n let currentIndex = index;\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (currentIndex % 2 === 0) {\n currentHash = hashPair(currentHash, sibling);\n } else {\n currentHash = hashPair(sibling, currentHash);\n }\n currentIndex = Math.floor(currentIndex / 2);\n }\n if (currentIndex !== 0) {\n return false;\n }\n return currentHash.equals(root);\n}\n\nfunction computeEntryHash(sequence, txRaw, stateCommitHash = '') {\n const data = Buffer.concat([Buffer.from(String(sequence)), Buffer.from(txRaw), Buffer.from(stateCommitHash)]);\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nfunction computeCheckpointHash(checkpoint) {\n const data = Buffer.from(\n JSON.stringify({\n height: Number(checkpoint.height),\n sequence: Number(checkpoint.sequence),\n prevSequence: Number(checkpoint.prevSequence),\n txRoot: checkpoint.txRoot,\n txCount: Number(checkpoint.txCount),\n stateRoot: checkpoint.stateRoot || undefined,\n timestamp: Number(checkpoint.timestamp),\n prevCheckpoint: checkpoint.prevCheckpoint || null,\n proposer: checkpoint.proposer,\n })\n );\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nasync function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expectedProposer) {\n if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {\n return false;\n }\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return false;\n }\n const recomputedHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedHash) !== normalizeHex(checkpoint.hash)) {\n return false;\n }\n if (!publicKeyOrVerifier) {\n return false;\n }\n const hashBytes = Buffer.from(normalizeHex(checkpoint.hash), 'hex');\n if (typeof publicKeyOrVerifier === 'function') {\n try {\n // Only a literal `true` authenticates: `{ verified: false }`, 1 or 'false' must not pass as truthy.\n return (await publicKeyOrVerifier(hashBytes, checkpoint.signature, checkpoint.proposer)) === true;\n } catch (_err) {\n return false;\n }\n }\n try {\n if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n return false;\n } catch (_err) {\n return false;\n }\n}\n\nconst NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';\n\n// Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.\n// Empty / whitespace / bare \"0x\" strings and zero-length byte arrays do not count as an anchor (#1133).\n// Hex strings are normalised to bytes whether or not they carry a 0x prefix.\nfunction resolveTrustAnchor(params) {\n if (typeof params.verifier === 'function') return params.verifier;\n const pk = params.proposerPublicKey;\n if (typeof pk === 'string') {\n const bare = pk.trim().replace(/^0x/i, '');\n if (bare.length === 0) return undefined;\n // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both\n // implementations hand the same value to the signature check.\n return /^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim();\n }\n if (pk instanceof Uint8Array) {\n return pk.length > 0 ? pk : undefined;\n }\n return undefined;\n}\n\n/**\n * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).\n *\n * Only `txRaw` is authenticated: `entryHash` covers `sequence`, `txRaw` and `stateCommitHash`, not\n * `entry.tx`, `from`, `pk`, `nonce` or `signature`. A `verified: true` result says nothing about those\n * fields. Decode the verified `txRaw` yourself; never read `entry.tx` directly (#1139).\n *\n * @param {object} params\n * @param {object} params.checkpoint\n * @param {object} params.proof\n * @param {object} params.entry\n * @param {string} [params.txHash]\n * @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)\n * @param {string} [params.expectedProposer]\n * @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is\n * required, otherwise the result is `{ verified: false }` (#1133)\n * @param {Function} [params.verifier]\n * @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor\n * is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.\n * @returns {Promise<{ verified: boolean, reason?: string }>}\n */\nasync function verifyTxInclusion(params) {\n try {\n if (!params || !params.checkpoint || !params.proof || !params.entry) {\n return { verified: false, reason: 'Missing checkpoint, proof, or entry' };\n }\n\n const { checkpoint, proof, entry, txHash, expectedProposer } = params;\n\n // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;\n // only the checkpoint signature against a trust anchor authenticates the bundle.\n const trustAnchor = resolveTrustAnchor(params);\n if (!trustAnchor && params.allowUnauthenticated !== true) {\n return { verified: false, reason: NO_TRUST_ANCHOR_REASON };\n }\n\n // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).\n // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).\n if (\n params.verifyTxRawHash !== false &&\n normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)\n ) {\n return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };\n }\n\n if (txHash && entry.hash !== txHash) {\n return {\n verified: false,\n reason: `Transaction hash mismatch: expected ${txHash}, got ${entry.hash}`,\n };\n }\n\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return {\n verified: false,\n reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`,\n };\n }\n\n const seq = Number(entry.sequence);\n const prevSeq = Number(checkpoint.prevSequence);\n const cpSeq = Number(checkpoint.sequence);\n\n if (seq <= prevSeq || seq > cpSeq) {\n return {\n verified: false,\n reason: `Entry sequence ${seq} is outside checkpoint range (${prevSeq}, ${cpSeq}]`,\n };\n }\n\n const expectedIndex = seq - (prevSeq + 1);\n if (Number(proof.index) !== expectedIndex) {\n return {\n verified: false,\n reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`,\n };\n }\n\n const recomputedEntryHash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');\n if (normalizeHex(entry.entryHash) !== normalizeHex(recomputedEntryHash)) {\n return {\n verified: false,\n reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`,\n };\n }\n\n const expectedLeafHash = Hasher.SHA2.hash256(Buffer.from(recomputedEntryHash), 1, 'hex');\n if (normalizeHex(proof.leaf) !== normalizeHex(expectedLeafHash)) {\n return {\n verified: false,\n reason: `Merkle proof leaf mismatch: expected ${expectedLeafHash}, got ${proof.leaf}`,\n };\n }\n\n if (normalizeHex(proof.root) !== normalizeHex(checkpoint.txRoot)) {\n return {\n verified: false,\n reason: `Merkle proof root mismatch: expected ${checkpoint.txRoot}, got ${proof.root}`,\n };\n }\n\n const leafBuf = Buffer.from(normalizeHex(proof.leaf), 'hex');\n const proofBufs = (proof.proof || []).map((p) => Buffer.from(normalizeHex(p), 'hex'));\n const rootBuf = Buffer.from(normalizeHex(proof.root), 'hex');\n\n if (!verifyMerkleProof(leafBuf, Number(proof.index), proofBufs, rootBuf, Number(checkpoint.txCount))) {\n return { verified: false, reason: 'Invalid Merkle inclusion proof' };\n }\n\n const recomputedCpHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedCpHash) !== normalizeHex(checkpoint.hash)) {\n return {\n verified: false,\n reason: `Checkpoint hash mismatch: expected ${recomputedCpHash}, got ${checkpoint.hash}`,\n };\n }\n\n if (!checkpoint.signature || checkpoint.signature === 'unsigned') {\n return { verified: false, reason: 'Checkpoint is unsigned' };\n }\n\n if (trustAnchor) {\n const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);\n if (!sigValid) {\n return { verified: false, reason: 'Invalid checkpoint signature' };\n }\n }\n\n return { verified: true };\n } catch (err) {\n return {\n verified: false,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nmodule.exports = {\n verifyTxInclusion,\n verifyCheckpointSignature,\n computeEntryHash,\n computeCheckpointHash,\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/verify.js"],"names":["Hasher","Signer","toTxHash","require","formatMessage","toTypeUrl","CANONICAL_SELF_DESCRIBE_PREFIX","decodeTx","decodeCbor","encodeTx","encodeCbor","decodeProto","encodeProto","normalizeHex","hex","String","replace","toLowerCase","isPlainObject","value","Array","isArray","proto","Object","getPrototypeOf","prototype","stableStringify","JSON","stringify","map","item","join","keys","filter","k","undefined","sort","hasCborSelfDescribeTag","buf","length","sameBytes","a","b","i","validatePresentEntryPrimitives","entry","stringFields","field","val","nonce","isNum","Number","isFinite","isStr","tryDecodeOcapWireTx","txRaw","trimmed","trim","startsWith","kind","rawBuf","Buffer","from","_err","isCanonicalBase64","toString","rawBytes","Uint8Array","buffer","byteOffset","byteLength","reason","decoded","reencoded","formattedTx","hasTxField","Boolean","pk","signature","chainId","itx","typeUrl","reencodeInput","assign","rawItx","authenticateEntryDecodedFields","strict","primitiveErr","ok","rawStr","parsedRaw","parsed","parse","tx","entryTxObj","rawFrom","spenderDid","rawPk","spenderPublicKey","rawSig","spenderSignature","txType","decodedTx","decodedResult","expectedFrom","expectedNonce","expectedPk","expectedSig","expectedChainId","itxObj","rawItxType","type","mappedTypeUrl","includes","expectedTypeUrl","sha256Buf","data","SHA2","hash256","hashPair","left","right","concat","merkleProofLength","treeSize","depth","width","Math","ceil","verifyMerkleProof","leaf","index","proof","root","isInteger","equals","currentHash","currentIndex","sibling","floor","computeEntryHashV1","sequence","stateCommitHash","computeEntryHash","seqBytes","txBytes","stateBytes","computeCheckpointHash","checkpoint","height","prevSequence","txRoot","txCount","stateRoot","timestamp","prevCheckpoint","proposer","verifyCheckpointSignature","publicKeyOrVerifier","expectedProposer","hash","recomputedHash","hashBytes","Ed25519","verify","sha3Digest","SHA3","sha2Digest","NO_TRUST_ANCHOR_REASON","resolveTrustAnchor","params","verifier","proposerPublicKey","bare","test","verifyTxInclusion","verified","txHash","trustAnchor","allowUnauthenticated","verifyTxRawHash","seq","prevSeq","cpSeq","expectedIndex","v2Hash","v1Hash","pinned","entryHashV2From","legacyAllowed","allowLegacyEntryHash","givenHash","entryHash","recomputedEntryHash","expectedLeafHash","leafBuf","proofBufs","p","rootBuf","recomputedCpHash","sigValid","verifyDecodedEntry","authFields","res","defineProperty","enumerable","configurable","writable","err","Error","message","module","exports"],"mappings":";;AAAA,MAAM,EAAEA,MAAF,EAAUC,MAAV,EAAkBC,QAAlB,KAA+BC,QAAQ,eAAR,CAArC;AACA,MAAM,EAAEC,aAAF,EAAiBC,SAAjB,KAA+BF,QAAQ,eAAR,CAArC;AACA,MAAM,EAAEG,8BAAF,EAAkCC,UAAUC,UAA5C,EAAwDC,UAAUC,UAAlE,KAAiFP,QAAQ,oBAAR,CAAvF;AACA,MAAM,EAAEI,UAAUI,WAAZ,EAAyBF,UAAUG,WAAnC,KAAmDT,QAAQ,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BzG,QAAQ,wBAA3B,EAAP;AACD;;AAED,QAAI2G,WAAJ,EAAiB;AACf,YAAMsB,WAAW,MAAM3C,0BAA0BT,UAA1B,EAAsC8B,WAAtC,EAAmDnB,gBAAnD,CAAvB;AACA,UAAI,CAACyC,QAAL,EAAe;AACb,eAAO,EAAExB,UAAU,KAAZ,EAAmBzG,QAAQ,8BAA3B,EAAP;AACD;AACF;;AAED,QAAI+B,SAAJ;AACA,QAAIoE,OAAO+B,kBAAP,KAA8B,KAAlC,EAAyC;AACvC,YAAMC,aAAarH,+BAA+BxC,KAA/B,EAAsC6H,OAAO+B,kBAAP,KAA8B,IAApE,CAAnB;AACA,UAAI,CAACC,WAAWlH,EAAhB,EAAoB;AAClB,eAAO,EAAEwF,UAAU,KAAZ,EAAmBzG,QAAQmI,WAAWnI,MAAtC,EAAP;AACD;AACD+B,kBAAYoG,WAAWpG,SAAvB;AACD;;AAED,UAAMqG,MAAM,EAAE3B,UAAU,IAAZ,EAAZ;AACA,QAAI1E,cAAcnE,SAAlB,EAA6B;AAC3BZ,aAAOqL,cAAP,CAAsBD,GAAtB,EAA2B,WAA3B,EAAwC;AACtCxL,eAAOmF,SAD+B;AAEtCuG,oBAAY,KAF0B;AAGtCC,sBAAc,IAHwB;AAItCC,kBAAU;AAJ4B,OAAxC;AAMD;AACD,WAAOJ,GAAP;AACD,GA5ID,CA4IE,OAAOK,GAAP,EAAY;AACZ,WAAO;AACLhC,gBAAU,KADL;AAELzG,cAAQyI,eAAeC,KAAf,GAAuBD,IAAIE,OAA3B,GAAqCnM,OAAOiM,GAAP;AAFxC,KAAP;AAID;AACF;;AAEDG,OAAOC,OAAP,GAAiB;AACfrC,mBADe;AAEflB,2BAFe;AAGfd,kBAHe;AAIfH,oBAJe;AAKfO;AALe,CAAjB","file":"verify.js","sourcesContent":["const { Hasher, Signer, toTxHash } = require('@ocap/mcrypto');\nconst { formatMessage, toTypeUrl } = require('@ocap/message');\nconst { CANONICAL_SELF_DESCRIBE_PREFIX, decodeTx: decodeCbor, encodeTx: encodeCbor } = require('@ocap/message/cbor');\nconst { decodeTx: decodeProto, encodeTx: encodeProto } = require('@ocap/message/protobuf');\n\nfunction normalizeHex(hex) {\n return String(hex || '')\n .replace(/^0x/i, '')\n .toLowerCase();\n}\n\nfunction isPlainObject(value) {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction stableStringify(value) {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(',')}]`;\n }\n if (!isPlainObject(value)) {\n return JSON.stringify(String(value));\n }\n const keys = Object.keys(value)\n .filter((k) => value[k] !== undefined)\n .sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;\n}\n\nfunction hasCborSelfDescribeTag(buf) {\n return (\n buf.length >= CANONICAL_SELF_DESCRIBE_PREFIX.length &&\n buf[0] === CANONICAL_SELF_DESCRIBE_PREFIX[0] &&\n buf[1] === CANONICAL_SELF_DESCRIBE_PREFIX[1] &&\n buf[2] === CANONICAL_SELF_DESCRIBE_PREFIX[2]\n );\n}\n\nfunction sameBytes(a, b) {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction validatePresentEntryPrimitives(entry) {\n const stringFields = ['from', 'pk', 'signature', 'chainId', 'txType'];\n for (let i = 0; i < stringFields.length; i++) {\n const field = stringFields[i];\n const val = entry[field];\n if (val !== undefined && val !== null && typeof val !== 'string') {\n return `Entry ${field} must be a string`;\n }\n }\n if (entry.nonce !== undefined && entry.nonce !== null) {\n const isNum = typeof entry.nonce === 'number' && Number.isFinite(entry.nonce);\n const isStr = typeof entry.nonce === 'string';\n if (!isNum && !isStr) {\n return 'Entry nonce must be a finite number or string';\n }\n }\n return null;\n}\n\nfunction tryDecodeOcapWireTx(txRaw) {\n const trimmed = String(txRaw || '').trim();\n if (!trimmed || trimmed.startsWith('{')) return { kind: 'none' };\n let rawBuf;\n try {\n rawBuf = Buffer.from(trimmed, 'base64');\n } catch (_err) {\n return { kind: 'none' };\n }\n if (rawBuf.length === 0) {\n return { kind: 'none' };\n }\n const isCanonicalBase64 = rawBuf.toString('base64') === trimmed;\n const rawBytes = new Uint8Array(rawBuf.buffer, rawBuf.byteOffset, rawBuf.byteLength);\n\n if (hasCborSelfDescribeTag(rawBytes)) {\n if (!isCanonicalBase64) {\n return { kind: 'invalid', reason: 'Non-canonical base64 encoding in entry txRaw' };\n }\n try {\n const decoded = decodeCbor(rawBytes);\n const reencoded = encodeCbor(decoded);\n if (!sameBytes(rawBytes, reencoded)) {\n return { kind: 'invalid', reason: 'Invalid canonical CBOR transaction in entry txRaw' };\n }\n return { kind: 'ocap', formattedTx: formatMessage('Transaction', decoded) };\n } catch (_err) {\n return { kind: 'invalid', reason: 'Failed to decode CBOR transaction in entry txRaw' };\n }\n }\n\n try {\n const decoded = decodeProto(rawBytes);\n const hasTxField = Boolean(\n decoded.from ||\n (decoded.pk && decoded.pk.length > 0) ||\n (decoded.signature && decoded.signature.length > 0) ||\n decoded.chainId ||\n (decoded.itx && typeof decoded.itx === 'object' && decoded.itx.typeUrl)\n );\n if (!hasTxField) return { kind: 'none' };\n\n const formattedTx = formatMessage('Transaction', decoded);\n const reencodeInput = Object.assign({}, decoded);\n const rawItx = decoded.itx;\n if (rawItx && typeof rawItx === 'object' && rawItx.typeUrl) {\n if (rawItx.typeUrl === 'json' || rawItx.typeUrl === 'vc') {\n reencodeInput.itx = formattedTx.itx;\n } else if (!rawItx.value) {\n reencodeInput.itx = { typeUrl: rawItx.typeUrl, value: new Uint8Array(0) };\n }\n }\n\n const reencoded = encodeProto(reencodeInput);\n if (!sameBytes(rawBytes, reencoded)) return { kind: 'none' };\n if (!isCanonicalBase64) {\n return { kind: 'invalid', reason: 'Non-canonical base64 encoding in entry txRaw' };\n }\n return { kind: 'ocap', formattedTx };\n } catch (_err) {\n return { kind: 'none' };\n }\n}\n\nfunction authenticateEntryDecodedFields(entry, strict) {\n const primitiveErr = validatePresentEntryPrimitives(entry);\n if (primitiveErr) {\n return { ok: false, reason: primitiveErr };\n }\n\n const rawStr = String(entry.txRaw !== undefined && entry.txRaw !== null ? entry.txRaw : '').trim();\n\n if (rawStr.startsWith('{')) {\n let parsedRaw;\n try {\n const parsed = JSON.parse(rawStr);\n if (!isPlainObject(parsed)) {\n return { ok: false, reason: 'Entry txRaw JSON is not an object' };\n }\n parsedRaw = parsed;\n } catch (_err) {\n return { ok: false, reason: 'Entry txRaw is not valid JSON' };\n }\n\n if (entry.tx !== undefined && entry.tx !== null) {\n let entryTxObj = entry.tx;\n if (typeof entryTxObj === 'string') {\n try {\n entryTxObj = JSON.parse(entryTxObj);\n } catch (_err) {\n return { ok: false, reason: 'Entry tx is not valid JSON' };\n }\n }\n if (!isPlainObject(entryTxObj) || stableStringify(entryTxObj) !== stableStringify(parsedRaw)) {\n return { ok: false, reason: 'Entry tx does not match authenticated txRaw' };\n }\n }\n\n const rawFrom = parsedRaw.from !== undefined && parsedRaw.from !== null ? parsedRaw.from : parsedRaw.spenderDid;\n if (rawFrom !== undefined && rawFrom !== null && entry.from !== undefined && entry.from !== null) {\n if (String(entry.from) !== String(rawFrom)) {\n return { ok: false, reason: `Entry from mismatch: expected ${rawFrom}, got ${entry.from}` };\n }\n }\n if (\n parsedRaw.nonce !== undefined &&\n parsedRaw.nonce !== null &&\n entry.nonce !== undefined &&\n entry.nonce !== null\n ) {\n if (String(entry.nonce) !== String(parsedRaw.nonce)) {\n return { ok: false, reason: `Entry nonce mismatch: expected ${parsedRaw.nonce}, got ${entry.nonce}` };\n }\n }\n const rawPk = parsedRaw.pk !== undefined && parsedRaw.pk !== null ? parsedRaw.pk : parsedRaw.spenderPublicKey;\n if (rawPk !== undefined && rawPk !== null && entry.pk !== undefined && entry.pk !== null) {\n if (String(entry.pk) !== String(rawPk)) {\n return { ok: false, reason: `Entry pk mismatch: expected ${rawPk}, got ${entry.pk}` };\n }\n }\n const rawSig =\n parsedRaw.signature !== undefined && parsedRaw.signature !== null\n ? parsedRaw.signature\n : parsedRaw.spenderSignature;\n if (rawSig !== undefined && rawSig !== null && entry.signature !== undefined && entry.signature !== null) {\n if (String(entry.signature) !== String(rawSig)) {\n return { ok: false, reason: `Entry signature mismatch: expected ${rawSig}, got ${entry.signature}` };\n }\n }\n if (\n parsedRaw.chainId !== undefined &&\n parsedRaw.chainId !== null &&\n entry.chainId !== undefined &&\n entry.chainId !== null\n ) {\n if (String(entry.chainId) !== String(parsedRaw.chainId)) {\n return { ok: false, reason: `Entry chainId mismatch: expected ${parsedRaw.chainId}, got ${entry.chainId}` };\n }\n }\n if (\n parsedRaw.txType !== undefined &&\n parsedRaw.txType !== null &&\n entry.txType !== undefined &&\n entry.txType !== null\n ) {\n if (String(entry.txType) !== String(parsedRaw.txType)) {\n return { ok: false, reason: `Entry txType mismatch: expected ${parsedRaw.txType}, got ${entry.txType}` };\n }\n }\n\n return { ok: true, decodedTx: parsedRaw };\n }\n\n const decodedResult = tryDecodeOcapWireTx(rawStr);\n if (decodedResult.kind === 'invalid') {\n return { ok: false, reason: decodedResult.reason };\n }\n if (decodedResult.kind === 'none') {\n if (strict) {\n return { ok: false, reason: 'Failed to decode entry txRaw as canonical transaction' };\n }\n return { ok: true };\n }\n const formattedTx = decodedResult.formattedTx;\n\n const expectedFrom = String(formattedTx.from || '');\n if (entry.from !== undefined && entry.from !== null && String(entry.from) !== expectedFrom) {\n return { ok: false, reason: `Entry from mismatch: expected ${expectedFrom}, got ${entry.from}` };\n }\n\n const expectedNonce = String(formattedTx.nonce !== undefined && formattedTx.nonce !== null ? formattedTx.nonce : 0);\n if (entry.nonce !== undefined && entry.nonce !== null && String(entry.nonce) !== expectedNonce) {\n return { ok: false, reason: `Entry nonce mismatch: expected ${expectedNonce}, got ${entry.nonce}` };\n }\n\n const expectedPk = String(formattedTx.pk || '');\n if (entry.pk !== undefined && entry.pk !== null && String(entry.pk) !== expectedPk) {\n return { ok: false, reason: `Entry pk mismatch: expected ${expectedPk}, got ${entry.pk}` };\n }\n\n const expectedSig = String(formattedTx.signature || '');\n if (entry.signature !== undefined && entry.signature !== null && String(entry.signature) !== expectedSig) {\n return { ok: false, reason: `Entry signature mismatch: expected ${expectedSig}, got ${entry.signature}` };\n }\n\n const expectedChainId = String(formattedTx.chainId || '');\n if (entry.chainId !== undefined && entry.chainId !== null && String(entry.chainId) !== expectedChainId) {\n return { ok: false, reason: `Entry chainId mismatch: expected ${expectedChainId}, got ${entry.chainId}` };\n }\n\n const itxObj = formattedTx.itx;\n const rawItxType = (itxObj && (itxObj.type || itxObj.typeUrl)) || '';\n if (entry.txType !== undefined && entry.txType !== null) {\n if (!rawItxType) {\n if (String(entry.txType) !== '') {\n return { ok: false, reason: `Entry txType mismatch: expected empty, got ${entry.txType}` };\n }\n } else {\n const mappedTypeUrl = rawItxType.includes(':') ? rawItxType : toTypeUrl(rawItxType);\n const expectedTypeUrl = mappedTypeUrl || rawItxType;\n if (String(entry.txType) !== rawItxType && String(entry.txType) !== expectedTypeUrl) {\n return { ok: false, reason: `Entry txType mismatch: expected ${expectedTypeUrl}, got ${entry.txType}` };\n }\n }\n }\n\n if (entry.tx !== undefined && entry.tx !== null) {\n let entryTxObj = entry.tx;\n if (typeof entryTxObj === 'string') {\n try {\n entryTxObj = JSON.parse(entryTxObj);\n } catch (_err) {\n return { ok: false, reason: 'Entry tx is not valid JSON' };\n }\n }\n if (!isPlainObject(entryTxObj) || stableStringify(entryTxObj) !== stableStringify(formattedTx)) {\n return { ok: false, reason: 'Entry tx does not match authenticated txRaw' };\n }\n }\n\n return { ok: true, decodedTx: formattedTx };\n}\n\nfunction sha256Buf(data) {\n const hex = Hasher.SHA2.hash256(data, 1, 'hex');\n return Buffer.from(String(hex).replace(/^0x/i, ''), 'hex');\n}\n\nfunction hashPair(left, right) {\n return sha256Buf(Buffer.concat([left, right]));\n}\n\n// Proof length for every leaf of a tree with `treeSize` leaves (odd last node pairs with itself)\nfunction merkleProofLength(treeSize) {\n let depth = 0;\n for (let width = treeSize; width > 1; width = Math.ceil(width / 2)) {\n depth++;\n }\n return depth;\n}\n\nfunction verifyMerkleProof(leaf, index, proof, root, treeSize) {\n if (!Number.isInteger(index) || index < 0) {\n return false;\n }\n // #972: bind the proof to the checkpoint's tree size\n if (treeSize !== undefined) {\n if (\n !Number.isInteger(treeSize) ||\n treeSize < 1 ||\n index >= treeSize ||\n proof.length !== merkleProofLength(treeSize)\n ) {\n return false;\n }\n }\n if (proof.length === 0) {\n return index === 0 && leaf.equals(root);\n }\n let currentHash = leaf;\n let currentIndex = index;\n for (let i = 0; i < proof.length; i++) {\n const sibling = proof[i];\n if (currentIndex % 2 === 0) {\n currentHash = hashPair(currentHash, sibling);\n } else {\n currentHash = hashPair(sibling, currentHash);\n }\n currentIndex = Math.floor(currentIndex / 2);\n }\n if (currentIndex !== 0) {\n return false;\n }\n return currentHash.equals(root);\n}\n\n// Entry hash versions (#1337). v1 = legacy plain concatenation written by nodes <= 1.30.26,\n// v2 = length-prefixed framing (#1325). The version is a function of the sequence on the node side.\nfunction computeEntryHashV1(sequence, txRaw, stateCommitHash = '') {\n return Hasher.SHA2.hash256(\n Buffer.concat([\n Buffer.from(String(sequence), 'utf8'),\n Buffer.from(String(txRaw == null ? '' : txRaw), 'utf8'),\n Buffer.from(String(stateCommitHash == null ? '' : stateCommitHash), 'utf8'),\n ]),\n 1,\n 'hex'\n );\n}\n\nfunction computeEntryHash(sequence, txRaw, stateCommitHash = '') {\n const seqBytes = Buffer.from(String(sequence), 'utf8');\n const txBytes = Buffer.from(String(txRaw == null ? '' : txRaw), 'utf8');\n const stateBytes = Buffer.from(String(stateCommitHash == null ? '' : stateCommitHash), 'utf8');\n const data = Buffer.concat([\n Buffer.from(`seq:${seqBytes.length}:`, 'utf8'),\n seqBytes,\n Buffer.from(`|tx:${txBytes.length}:`, 'utf8'),\n txBytes,\n Buffer.from(`|state:${stateBytes.length}:`, 'utf8'),\n stateBytes,\n ]);\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nfunction computeCheckpointHash(checkpoint) {\n const data = Buffer.from(\n JSON.stringify({\n height: Number(checkpoint.height),\n sequence: Number(checkpoint.sequence),\n prevSequence: Number(checkpoint.prevSequence),\n txRoot: checkpoint.txRoot,\n txCount: Number(checkpoint.txCount),\n stateRoot: checkpoint.stateRoot || undefined,\n timestamp: Number(checkpoint.timestamp),\n prevCheckpoint: checkpoint.prevCheckpoint || null,\n proposer: checkpoint.proposer,\n })\n );\n return Hasher.SHA2.hash256(data, 1, 'hex');\n}\n\nasync function verifyCheckpointSignature(checkpoint, publicKeyOrVerifier, expectedProposer) {\n if (!checkpoint || !checkpoint.hash || !checkpoint.signature || checkpoint.signature === 'unsigned') {\n return false;\n }\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return false;\n }\n const recomputedHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedHash) !== normalizeHex(checkpoint.hash)) {\n return false;\n }\n if (!publicKeyOrVerifier) {\n return false;\n }\n const hashBytes = Buffer.from(normalizeHex(checkpoint.hash), 'hex');\n if (typeof publicKeyOrVerifier === 'function') {\n try {\n // Only a literal `true` authenticates: `{ verified: false }`, 1 or 'false' must not pass as truthy.\n return (await publicKeyOrVerifier(hashBytes, checkpoint.signature, checkpoint.proposer)) === true;\n } catch (_err) {\n return false;\n }\n }\n try {\n if (Signer.Ed25519.verify(hashBytes, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha3Digest = Hasher.SHA3.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha3Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n const sha2Digest = Hasher.SHA2.hash256(hashBytes, 1);\n if (Signer.Ed25519.verify(sha2Digest, checkpoint.signature, publicKeyOrVerifier)) {\n return true;\n }\n return false;\n } catch (_err) {\n return false;\n }\n}\n\nconst NO_TRUST_ANCHOR_REASON = 'no trust anchor (proposerPublicKey/verifier) supplied';\n\n// Pick the trust anchor that authenticates the checkpoint signature, or undefined when none is usable.\n// Empty / whitespace / bare \"0x\" strings and zero-length byte arrays do not count as an anchor (#1133).\n// Hex strings are normalised to bytes whether or not they carry a 0x prefix.\nfunction resolveTrustAnchor(params) {\n if (typeof params.verifier === 'function') return params.verifier;\n const pk = params.proposerPublicKey;\n if (typeof pk === 'string') {\n const bare = pk.trim().replace(/^0x/i, '');\n if (bare.length === 0) return undefined;\n // Hex keys are accepted with or without 0x and in any case; decode them to bytes so both\n // implementations hand the same value to the signature check.\n return /^[0-9a-fA-F]+$/.test(bare) && bare.length % 2 === 0 ? Buffer.from(bare, 'hex') : pk.trim();\n }\n if (pk instanceof Uint8Array) {\n return pk.length > 0 ? pk : undefined;\n }\n return undefined;\n}\n\n/**\n * Pure client-side verification of transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).\n *\n * When `txRaw` is an OCAP wire transaction (CBOR/Protobuf) or canonical JSON payload, `verifyTxInclusion`\n * decodes `txRaw` and authenticates any present `entry.tx`, `from`, `pk`, `nonce`, `signature`, `txType`,\n * and `chainId` fields against the decoded payload (#1139), attaching `decodedTx` on the result.\n *\n * @param {object} params\n * @param {object} params.checkpoint\n * @param {object} params.proof\n * @param {object} params.entry\n * @param {string} [params.txHash]\n * @param {boolean} [params.verifyTxRawHash=true] - require entry.hash === toTxHash(txRaw) (#976)\n * @param {boolean} [params.verifyDecodedEntry] - controls decoded entry field verification (#1139)\n * @param {string} [params.expectedProposer]\n * @param {string|Buffer} [params.proposerPublicKey] - trust anchor; one of proposerPublicKey / verifier is\n * required, otherwise the result is `{ verified: false }` (#1133)\n * @param {Function} [params.verifier]\n * @param {boolean} [params.allowUnauthenticated=false] - UNSAFE: skip the signature check when no trust anchor\n * is supplied (pre-#1133 behavior). A malicious RPC can then forge inclusion.\n * @returns {Promise<{ verified: boolean, reason?: string, decodedTx?: object }>}\n */\nasync function verifyTxInclusion(params) {\n try {\n if (!params || !params.checkpoint || !params.proof || !params.entry) {\n return { verified: false, reason: 'Missing checkpoint, proof, or entry' };\n }\n\n const { checkpoint, proof, entry, txHash, expectedProposer } = params;\n\n // Fail closed (#1133): every check below is structural and a forging RPC can satisfy them all;\n // only the checkpoint signature against a trust anchor authenticates the bundle.\n const trustAnchor = resolveTrustAnchor(params);\n if (!trustAnchor && params.allowUnauthenticated !== true) {\n return { verified: false, reason: NO_TRUST_ANCHOR_REASON };\n }\n\n // entry.hash is not covered by entryHash or the Merkle leaf, so bind it to txRaw (#976).\n // On by default: this client only talks to OCAP chains, where hash = toTxHash(txRaw).\n if (\n params.verifyTxRawHash !== false &&\n normalizeHex(toTxHash(Buffer.from(String(entry.txRaw || ''), 'base64'))) !== normalizeHex(entry.hash)\n ) {\n return { verified: false, reason: `Transaction hash ${entry.hash} does not match entry txRaw` };\n }\n\n if (txHash && entry.hash !== txHash) {\n return {\n verified: false,\n reason: `Transaction hash mismatch: expected ${txHash}, got ${entry.hash}`,\n };\n }\n\n if (expectedProposer && checkpoint.proposer !== expectedProposer) {\n return {\n verified: false,\n reason: `Checkpoint proposer mismatch: expected ${expectedProposer}, got ${checkpoint.proposer}`,\n };\n }\n\n const seq = Number(entry.sequence);\n const prevSeq = Number(checkpoint.prevSequence);\n const cpSeq = Number(checkpoint.sequence);\n\n if (seq <= prevSeq || seq > cpSeq) {\n return {\n verified: false,\n reason: `Entry sequence ${seq} is outside checkpoint range (${prevSeq}, ${cpSeq}]`,\n };\n }\n\n const expectedIndex = seq - (prevSeq + 1);\n if (Number(proof.index) !== expectedIndex) {\n return {\n verified: false,\n reason: `Merkle proof index mismatch: expected ${expectedIndex}, got ${proof.index}`,\n };\n }\n\n // v2 (length-prefixed) first, then legacy v1 so proofs from 1.30.26 nodes keep verifying (#1337).\n // With params.entryHashV2From the version is exact: seq >= v2From -> v2, below -> v1.\n // allowLegacyEntryHash:false (without a pin) refuses v1. v1's boundary ambiguity cannot be\n // exploited here because entry.hash == toTxHash(txRaw) (default on) and the Merkle index pin\n // txRaw and sequence; pass entryHashV2From if you also disable verifyTxRawHash.\n const v2Hash = computeEntryHash(seq, entry.txRaw, entry.stateCommitHash || '');\n const v1Hash = computeEntryHashV1(seq, entry.txRaw, entry.stateCommitHash || '');\n const pinned = params.entryHashV2From === undefined ? undefined : seq >= Number(params.entryHashV2From) ? 2 : 1;\n const legacyAllowed = pinned === 1 || (pinned === undefined && params.allowLegacyEntryHash !== false);\n const givenHash = normalizeHex(entry.entryHash);\n let recomputedEntryHash = v2Hash;\n if (pinned !== 2 && legacyAllowed && givenHash !== normalizeHex(v2Hash) && givenHash === normalizeHex(v1Hash)) {\n recomputedEntryHash = v1Hash;\n } else if (pinned === 1) {\n recomputedEntryHash = v1Hash;\n }\n if (givenHash !== normalizeHex(recomputedEntryHash)) {\n return {\n verified: false,\n reason: `Entry hash mismatch: expected ${recomputedEntryHash}, got ${entry.entryHash}`,\n };\n }\n\n const expectedLeafHash = Hasher.SHA2.hash256(Buffer.from(recomputedEntryHash), 1, 'hex');\n if (normalizeHex(proof.leaf) !== normalizeHex(expectedLeafHash)) {\n return {\n verified: false,\n reason: `Merkle proof leaf mismatch: expected ${expectedLeafHash}, got ${proof.leaf}`,\n };\n }\n\n if (normalizeHex(proof.root) !== normalizeHex(checkpoint.txRoot)) {\n return {\n verified: false,\n reason: `Merkle proof root mismatch: expected ${checkpoint.txRoot}, got ${proof.root}`,\n };\n }\n\n const leafBuf = Buffer.from(normalizeHex(proof.leaf), 'hex');\n const proofBufs = (proof.proof || []).map((p) => Buffer.from(normalizeHex(p), 'hex'));\n const rootBuf = Buffer.from(normalizeHex(proof.root), 'hex');\n\n if (!verifyMerkleProof(leafBuf, Number(proof.index), proofBufs, rootBuf, Number(checkpoint.txCount))) {\n return { verified: false, reason: 'Invalid Merkle inclusion proof' };\n }\n\n const recomputedCpHash = computeCheckpointHash(checkpoint);\n if (normalizeHex(recomputedCpHash) !== normalizeHex(checkpoint.hash)) {\n return {\n verified: false,\n reason: `Checkpoint hash mismatch: expected ${recomputedCpHash}, got ${checkpoint.hash}`,\n };\n }\n\n if (!checkpoint.signature || checkpoint.signature === 'unsigned') {\n return { verified: false, reason: 'Checkpoint is unsigned' };\n }\n\n if (trustAnchor) {\n const sigValid = await verifyCheckpointSignature(checkpoint, trustAnchor, expectedProposer);\n if (!sigValid) {\n return { verified: false, reason: 'Invalid checkpoint signature' };\n }\n }\n\n let decodedTx;\n if (params.verifyDecodedEntry !== false) {\n const authFields = authenticateEntryDecodedFields(entry, params.verifyDecodedEntry === true);\n if (!authFields.ok) {\n return { verified: false, reason: authFields.reason };\n }\n decodedTx = authFields.decodedTx;\n }\n\n const res = { verified: true };\n if (decodedTx !== undefined) {\n Object.defineProperty(res, 'decodedTx', {\n value: decodedTx,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n }\n return res;\n } catch (err) {\n return {\n verified: false,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nmodule.exports = {\n verifyTxInclusion,\n verifyCheckpointSignature,\n computeEntryHash,\n computeEntryHashV1,\n computeCheckpointHash,\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ocap/client",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.31.0",
|
|
4
4
|
"description": "graphql client to read/write data on arcblock blockchain",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"graphql",
|
|
@@ -52,17 +52,17 @@
|
|
|
52
52
|
"encode.d.ts"
|
|
53
53
|
],
|
|
54
54
|
"dependencies": {
|
|
55
|
-
"@arcblock/did": "1.
|
|
56
|
-
"@arcblock/did-util": "1.
|
|
57
|
-
"@arcblock/jwt": "1.
|
|
55
|
+
"@arcblock/did": "1.31.0",
|
|
56
|
+
"@arcblock/did-util": "1.31.0",
|
|
57
|
+
"@arcblock/jwt": "1.31.0",
|
|
58
58
|
"@arcblock/sdk-util": "^0.36.4",
|
|
59
|
-
"@arcblock/ws": "1.
|
|
60
|
-
"@ocap/asset": "1.
|
|
61
|
-
"@ocap/mcrypto": "1.
|
|
62
|
-
"@ocap/message": "1.
|
|
63
|
-
"@ocap/proto": "1.
|
|
64
|
-
"@ocap/util": "1.
|
|
65
|
-
"@ocap/wallet": "1.
|
|
59
|
+
"@arcblock/ws": "1.31.0",
|
|
60
|
+
"@ocap/asset": "1.31.0",
|
|
61
|
+
"@ocap/mcrypto": "1.31.0",
|
|
62
|
+
"@ocap/message": "1.31.0",
|
|
63
|
+
"@ocap/proto": "1.31.0",
|
|
64
|
+
"@ocap/util": "1.31.0",
|
|
65
|
+
"@ocap/wallet": "1.31.0",
|
|
66
66
|
"blueimp-md5": "^2.19.0",
|
|
67
67
|
"buffer": "6.0.3",
|
|
68
68
|
"debug": "^4.4.3",
|