@motebit/crypto 0.8.0 → 1.1.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/LICENSE +198 -18
- package/NOTICE +19 -0
- package/README.md +11 -3
- package/dist/artifacts.d.ts +431 -32
- package/dist/artifacts.d.ts.map +1 -1
- package/dist/credential-anchor.d.ts +76 -2
- package/dist/credential-anchor.d.ts.map +1 -1
- package/dist/credentials.d.ts +26 -1
- package/dist/credentials.d.ts.map +1 -1
- package/dist/hardware-attestation.d.ts +268 -0
- package/dist/hardware-attestation.d.ts.map +1 -0
- package/dist/index.d.ts +56 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3597 -153
- package/dist/signing.d.ts +52 -17
- package/dist/signing.d.ts.map +1 -1
- package/dist/suite-dispatch.d.ts +103 -0
- package/dist/suite-dispatch.d.ts.map +1 -0
- package/dist/suite-dispatch.js +3233 -0
- package/package.json +20 -5
- package/dist/artifacts.js +0 -506
- package/dist/artifacts.js.map +0 -1
- package/dist/credential-anchor.js +0 -159
- package/dist/credential-anchor.js.map +0 -1
- package/dist/credentials.js +0 -209
- package/dist/credentials.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/signing.js +0 -282
- package/dist/signing.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,2440 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res) => function __init() {
|
|
4
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
5
|
+
};
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/_assert.js
|
|
12
|
+
function anumber(n) {
|
|
13
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
14
|
+
throw new Error("positive integer expected, got " + n);
|
|
15
|
+
}
|
|
16
|
+
function isBytes3(a) {
|
|
17
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
18
|
+
}
|
|
19
|
+
function abytes3(b, ...lengths) {
|
|
20
|
+
if (!isBytes3(b))
|
|
21
|
+
throw new Error("Uint8Array expected");
|
|
22
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
23
|
+
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
|
|
24
|
+
}
|
|
25
|
+
function ahash(h2) {
|
|
26
|
+
if (typeof h2 !== "function" || typeof h2.create !== "function")
|
|
27
|
+
throw new Error("Hash should be wrapped by utils.wrapConstructor");
|
|
28
|
+
anumber(h2.outputLen);
|
|
29
|
+
anumber(h2.blockLen);
|
|
30
|
+
}
|
|
31
|
+
function aexists2(instance, checkFinished = true) {
|
|
32
|
+
if (instance.destroyed)
|
|
33
|
+
throw new Error("Hash instance has been destroyed");
|
|
34
|
+
if (checkFinished && instance.finished)
|
|
35
|
+
throw new Error("Hash#digest() has already been called");
|
|
36
|
+
}
|
|
37
|
+
function aoutput2(out, instance) {
|
|
38
|
+
abytes3(out);
|
|
39
|
+
const min = instance.outputLen;
|
|
40
|
+
if (out.length < min) {
|
|
41
|
+
throw new Error("digestInto() expects output buffer of length at least " + min);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
var init_assert = __esm({
|
|
45
|
+
"../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/_assert.js"() {
|
|
46
|
+
"use strict";
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/cryptoNode.js
|
|
51
|
+
import * as nc from "crypto";
|
|
52
|
+
var crypto2;
|
|
53
|
+
var init_cryptoNode = __esm({
|
|
54
|
+
"../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/cryptoNode.js"() {
|
|
55
|
+
"use strict";
|
|
56
|
+
crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/utils.js
|
|
61
|
+
function utf8ToBytes2(str) {
|
|
62
|
+
if (typeof str !== "string")
|
|
63
|
+
throw new Error("utf8ToBytes expected string, got " + typeof str);
|
|
64
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
65
|
+
}
|
|
66
|
+
function toBytes2(data) {
|
|
67
|
+
if (typeof data === "string")
|
|
68
|
+
data = utf8ToBytes2(data);
|
|
69
|
+
abytes3(data);
|
|
70
|
+
return data;
|
|
71
|
+
}
|
|
72
|
+
function concatBytes2(...arrays) {
|
|
73
|
+
let sum = 0;
|
|
74
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
75
|
+
const a = arrays[i];
|
|
76
|
+
abytes3(a);
|
|
77
|
+
sum += a.length;
|
|
78
|
+
}
|
|
79
|
+
const res = new Uint8Array(sum);
|
|
80
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
81
|
+
const a = arrays[i];
|
|
82
|
+
res.set(a, pad);
|
|
83
|
+
pad += a.length;
|
|
84
|
+
}
|
|
85
|
+
return res;
|
|
86
|
+
}
|
|
87
|
+
function wrapConstructor2(hashCons) {
|
|
88
|
+
const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
|
|
89
|
+
const tmp = hashCons();
|
|
90
|
+
hashC.outputLen = tmp.outputLen;
|
|
91
|
+
hashC.blockLen = tmp.blockLen;
|
|
92
|
+
hashC.create = () => hashCons();
|
|
93
|
+
return hashC;
|
|
94
|
+
}
|
|
95
|
+
function randomBytes2(bytesLength = 32) {
|
|
96
|
+
if (crypto2 && typeof crypto2.getRandomValues === "function") {
|
|
97
|
+
return crypto2.getRandomValues(new Uint8Array(bytesLength));
|
|
98
|
+
}
|
|
99
|
+
if (crypto2 && typeof crypto2.randomBytes === "function") {
|
|
100
|
+
return crypto2.randomBytes(bytesLength);
|
|
101
|
+
}
|
|
102
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
103
|
+
}
|
|
104
|
+
var createView2, rotr2, Hash2;
|
|
105
|
+
var init_utils = __esm({
|
|
106
|
+
"../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/utils.js"() {
|
|
107
|
+
"use strict";
|
|
108
|
+
init_cryptoNode();
|
|
109
|
+
init_assert();
|
|
110
|
+
createView2 = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
111
|
+
rotr2 = (word, shift) => word << 32 - shift | word >>> shift;
|
|
112
|
+
Hash2 = class {
|
|
113
|
+
// Safe version that clones internal state
|
|
114
|
+
clone() {
|
|
115
|
+
return this._cloneInto();
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/_md.js
|
|
122
|
+
function setBigUint642(view, byteOffset, value, isLE) {
|
|
123
|
+
if (typeof view.setBigUint64 === "function")
|
|
124
|
+
return view.setBigUint64(byteOffset, value, isLE);
|
|
125
|
+
const _32n2 = BigInt(32);
|
|
126
|
+
const _u32_max = BigInt(4294967295);
|
|
127
|
+
const wh = Number(value >> _32n2 & _u32_max);
|
|
128
|
+
const wl = Number(value & _u32_max);
|
|
129
|
+
const h2 = isLE ? 4 : 0;
|
|
130
|
+
const l = isLE ? 0 : 4;
|
|
131
|
+
view.setUint32(byteOffset + h2, wh, isLE);
|
|
132
|
+
view.setUint32(byteOffset + l, wl, isLE);
|
|
133
|
+
}
|
|
134
|
+
var Chi2, Maj2, HashMD2;
|
|
135
|
+
var init_md = __esm({
|
|
136
|
+
"../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/_md.js"() {
|
|
137
|
+
"use strict";
|
|
138
|
+
init_assert();
|
|
139
|
+
init_utils();
|
|
140
|
+
Chi2 = (a, b, c) => a & b ^ ~a & c;
|
|
141
|
+
Maj2 = (a, b, c) => a & b ^ a & c ^ b & c;
|
|
142
|
+
HashMD2 = class extends Hash2 {
|
|
143
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
144
|
+
super();
|
|
145
|
+
this.blockLen = blockLen;
|
|
146
|
+
this.outputLen = outputLen;
|
|
147
|
+
this.padOffset = padOffset;
|
|
148
|
+
this.isLE = isLE;
|
|
149
|
+
this.finished = false;
|
|
150
|
+
this.length = 0;
|
|
151
|
+
this.pos = 0;
|
|
152
|
+
this.destroyed = false;
|
|
153
|
+
this.buffer = new Uint8Array(blockLen);
|
|
154
|
+
this.view = createView2(this.buffer);
|
|
155
|
+
}
|
|
156
|
+
update(data) {
|
|
157
|
+
aexists2(this);
|
|
158
|
+
const { view, buffer, blockLen } = this;
|
|
159
|
+
data = toBytes2(data);
|
|
160
|
+
const len = data.length;
|
|
161
|
+
for (let pos = 0; pos < len; ) {
|
|
162
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
163
|
+
if (take === blockLen) {
|
|
164
|
+
const dataView = createView2(data);
|
|
165
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
166
|
+
this.process(dataView, pos);
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
170
|
+
this.pos += take;
|
|
171
|
+
pos += take;
|
|
172
|
+
if (this.pos === blockLen) {
|
|
173
|
+
this.process(view, 0);
|
|
174
|
+
this.pos = 0;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
this.length += data.length;
|
|
178
|
+
this.roundClean();
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
digestInto(out) {
|
|
182
|
+
aexists2(this);
|
|
183
|
+
aoutput2(out, this);
|
|
184
|
+
this.finished = true;
|
|
185
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
186
|
+
let { pos } = this;
|
|
187
|
+
buffer[pos++] = 128;
|
|
188
|
+
this.buffer.subarray(pos).fill(0);
|
|
189
|
+
if (this.padOffset > blockLen - pos) {
|
|
190
|
+
this.process(view, 0);
|
|
191
|
+
pos = 0;
|
|
192
|
+
}
|
|
193
|
+
for (let i = pos; i < blockLen; i++)
|
|
194
|
+
buffer[i] = 0;
|
|
195
|
+
setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE);
|
|
196
|
+
this.process(view, 0);
|
|
197
|
+
const oview = createView2(out);
|
|
198
|
+
const len = this.outputLen;
|
|
199
|
+
if (len % 4)
|
|
200
|
+
throw new Error("_sha2: outputLen should be aligned to 32bit");
|
|
201
|
+
const outLen = len / 4;
|
|
202
|
+
const state = this.get();
|
|
203
|
+
if (outLen > state.length)
|
|
204
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
205
|
+
for (let i = 0; i < outLen; i++)
|
|
206
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
207
|
+
}
|
|
208
|
+
digest() {
|
|
209
|
+
const { buffer, outputLen } = this;
|
|
210
|
+
this.digestInto(buffer);
|
|
211
|
+
const res = buffer.slice(0, outputLen);
|
|
212
|
+
this.destroy();
|
|
213
|
+
return res;
|
|
214
|
+
}
|
|
215
|
+
_cloneInto(to) {
|
|
216
|
+
to || (to = new this.constructor());
|
|
217
|
+
to.set(...this.get());
|
|
218
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
219
|
+
to.length = length;
|
|
220
|
+
to.pos = pos;
|
|
221
|
+
to.finished = finished;
|
|
222
|
+
to.destroyed = destroyed;
|
|
223
|
+
if (length % blockLen)
|
|
224
|
+
to.buffer.set(buffer);
|
|
225
|
+
return to;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/sha256.js
|
|
232
|
+
var SHA256_K2, SHA256_IV2, SHA256_W2, SHA2562, sha2562;
|
|
233
|
+
var init_sha256 = __esm({
|
|
234
|
+
"../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/sha256.js"() {
|
|
235
|
+
"use strict";
|
|
236
|
+
init_md();
|
|
237
|
+
init_utils();
|
|
238
|
+
SHA256_K2 = /* @__PURE__ */ new Uint32Array([
|
|
239
|
+
1116352408,
|
|
240
|
+
1899447441,
|
|
241
|
+
3049323471,
|
|
242
|
+
3921009573,
|
|
243
|
+
961987163,
|
|
244
|
+
1508970993,
|
|
245
|
+
2453635748,
|
|
246
|
+
2870763221,
|
|
247
|
+
3624381080,
|
|
248
|
+
310598401,
|
|
249
|
+
607225278,
|
|
250
|
+
1426881987,
|
|
251
|
+
1925078388,
|
|
252
|
+
2162078206,
|
|
253
|
+
2614888103,
|
|
254
|
+
3248222580,
|
|
255
|
+
3835390401,
|
|
256
|
+
4022224774,
|
|
257
|
+
264347078,
|
|
258
|
+
604807628,
|
|
259
|
+
770255983,
|
|
260
|
+
1249150122,
|
|
261
|
+
1555081692,
|
|
262
|
+
1996064986,
|
|
263
|
+
2554220882,
|
|
264
|
+
2821834349,
|
|
265
|
+
2952996808,
|
|
266
|
+
3210313671,
|
|
267
|
+
3336571891,
|
|
268
|
+
3584528711,
|
|
269
|
+
113926993,
|
|
270
|
+
338241895,
|
|
271
|
+
666307205,
|
|
272
|
+
773529912,
|
|
273
|
+
1294757372,
|
|
274
|
+
1396182291,
|
|
275
|
+
1695183700,
|
|
276
|
+
1986661051,
|
|
277
|
+
2177026350,
|
|
278
|
+
2456956037,
|
|
279
|
+
2730485921,
|
|
280
|
+
2820302411,
|
|
281
|
+
3259730800,
|
|
282
|
+
3345764771,
|
|
283
|
+
3516065817,
|
|
284
|
+
3600352804,
|
|
285
|
+
4094571909,
|
|
286
|
+
275423344,
|
|
287
|
+
430227734,
|
|
288
|
+
506948616,
|
|
289
|
+
659060556,
|
|
290
|
+
883997877,
|
|
291
|
+
958139571,
|
|
292
|
+
1322822218,
|
|
293
|
+
1537002063,
|
|
294
|
+
1747873779,
|
|
295
|
+
1955562222,
|
|
296
|
+
2024104815,
|
|
297
|
+
2227730452,
|
|
298
|
+
2361852424,
|
|
299
|
+
2428436474,
|
|
300
|
+
2756734187,
|
|
301
|
+
3204031479,
|
|
302
|
+
3329325298
|
|
303
|
+
]);
|
|
304
|
+
SHA256_IV2 = /* @__PURE__ */ new Uint32Array([
|
|
305
|
+
1779033703,
|
|
306
|
+
3144134277,
|
|
307
|
+
1013904242,
|
|
308
|
+
2773480762,
|
|
309
|
+
1359893119,
|
|
310
|
+
2600822924,
|
|
311
|
+
528734635,
|
|
312
|
+
1541459225
|
|
313
|
+
]);
|
|
314
|
+
SHA256_W2 = /* @__PURE__ */ new Uint32Array(64);
|
|
315
|
+
SHA2562 = class extends HashMD2 {
|
|
316
|
+
constructor() {
|
|
317
|
+
super(64, 32, 8, false);
|
|
318
|
+
this.A = SHA256_IV2[0] | 0;
|
|
319
|
+
this.B = SHA256_IV2[1] | 0;
|
|
320
|
+
this.C = SHA256_IV2[2] | 0;
|
|
321
|
+
this.D = SHA256_IV2[3] | 0;
|
|
322
|
+
this.E = SHA256_IV2[4] | 0;
|
|
323
|
+
this.F = SHA256_IV2[5] | 0;
|
|
324
|
+
this.G = SHA256_IV2[6] | 0;
|
|
325
|
+
this.H = SHA256_IV2[7] | 0;
|
|
326
|
+
}
|
|
327
|
+
get() {
|
|
328
|
+
const { A, B, C: C2, D, E, F, G: G2, H } = this;
|
|
329
|
+
return [A, B, C2, D, E, F, G2, H];
|
|
330
|
+
}
|
|
331
|
+
// prettier-ignore
|
|
332
|
+
set(A, B, C2, D, E, F, G2, H) {
|
|
333
|
+
this.A = A | 0;
|
|
334
|
+
this.B = B | 0;
|
|
335
|
+
this.C = C2 | 0;
|
|
336
|
+
this.D = D | 0;
|
|
337
|
+
this.E = E | 0;
|
|
338
|
+
this.F = F | 0;
|
|
339
|
+
this.G = G2 | 0;
|
|
340
|
+
this.H = H | 0;
|
|
341
|
+
}
|
|
342
|
+
process(view, offset) {
|
|
343
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
344
|
+
SHA256_W2[i] = view.getUint32(offset, false);
|
|
345
|
+
for (let i = 16; i < 64; i++) {
|
|
346
|
+
const W15 = SHA256_W2[i - 15];
|
|
347
|
+
const W2 = SHA256_W2[i - 2];
|
|
348
|
+
const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3;
|
|
349
|
+
const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10;
|
|
350
|
+
SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0;
|
|
351
|
+
}
|
|
352
|
+
let { A, B, C: C2, D, E, F, G: G2, H } = this;
|
|
353
|
+
for (let i = 0; i < 64; i++) {
|
|
354
|
+
const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25);
|
|
355
|
+
const T1 = H + sigma1 + Chi2(E, F, G2) + SHA256_K2[i] + SHA256_W2[i] | 0;
|
|
356
|
+
const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22);
|
|
357
|
+
const T2 = sigma0 + Maj2(A, B, C2) | 0;
|
|
358
|
+
H = G2;
|
|
359
|
+
G2 = F;
|
|
360
|
+
F = E;
|
|
361
|
+
E = D + T1 | 0;
|
|
362
|
+
D = C2;
|
|
363
|
+
C2 = B;
|
|
364
|
+
B = A;
|
|
365
|
+
A = T1 + T2 | 0;
|
|
366
|
+
}
|
|
367
|
+
A = A + this.A | 0;
|
|
368
|
+
B = B + this.B | 0;
|
|
369
|
+
C2 = C2 + this.C | 0;
|
|
370
|
+
D = D + this.D | 0;
|
|
371
|
+
E = E + this.E | 0;
|
|
372
|
+
F = F + this.F | 0;
|
|
373
|
+
G2 = G2 + this.G | 0;
|
|
374
|
+
H = H + this.H | 0;
|
|
375
|
+
this.set(A, B, C2, D, E, F, G2, H);
|
|
376
|
+
}
|
|
377
|
+
roundClean() {
|
|
378
|
+
SHA256_W2.fill(0);
|
|
379
|
+
}
|
|
380
|
+
destroy() {
|
|
381
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
382
|
+
this.buffer.fill(0);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
sha2562 = /* @__PURE__ */ wrapConstructor2(() => new SHA2562());
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/hmac.js
|
|
390
|
+
var HMAC, hmac;
|
|
391
|
+
var init_hmac = __esm({
|
|
392
|
+
"../../node_modules/.pnpm/@noble+hashes@1.6.0/node_modules/@noble/hashes/esm/hmac.js"() {
|
|
393
|
+
"use strict";
|
|
394
|
+
init_assert();
|
|
395
|
+
init_utils();
|
|
396
|
+
HMAC = class extends Hash2 {
|
|
397
|
+
constructor(hash2, _key) {
|
|
398
|
+
super();
|
|
399
|
+
this.finished = false;
|
|
400
|
+
this.destroyed = false;
|
|
401
|
+
ahash(hash2);
|
|
402
|
+
const key = toBytes2(_key);
|
|
403
|
+
this.iHash = hash2.create();
|
|
404
|
+
if (typeof this.iHash.update !== "function")
|
|
405
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
406
|
+
this.blockLen = this.iHash.blockLen;
|
|
407
|
+
this.outputLen = this.iHash.outputLen;
|
|
408
|
+
const blockLen = this.blockLen;
|
|
409
|
+
const pad = new Uint8Array(blockLen);
|
|
410
|
+
pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key);
|
|
411
|
+
for (let i = 0; i < pad.length; i++)
|
|
412
|
+
pad[i] ^= 54;
|
|
413
|
+
this.iHash.update(pad);
|
|
414
|
+
this.oHash = hash2.create();
|
|
415
|
+
for (let i = 0; i < pad.length; i++)
|
|
416
|
+
pad[i] ^= 54 ^ 92;
|
|
417
|
+
this.oHash.update(pad);
|
|
418
|
+
pad.fill(0);
|
|
419
|
+
}
|
|
420
|
+
update(buf) {
|
|
421
|
+
aexists2(this);
|
|
422
|
+
this.iHash.update(buf);
|
|
423
|
+
return this;
|
|
424
|
+
}
|
|
425
|
+
digestInto(out) {
|
|
426
|
+
aexists2(this);
|
|
427
|
+
abytes3(out, this.outputLen);
|
|
428
|
+
this.finished = true;
|
|
429
|
+
this.iHash.digestInto(out);
|
|
430
|
+
this.oHash.update(out);
|
|
431
|
+
this.oHash.digestInto(out);
|
|
432
|
+
this.destroy();
|
|
433
|
+
}
|
|
434
|
+
digest() {
|
|
435
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
436
|
+
this.digestInto(out);
|
|
437
|
+
return out;
|
|
438
|
+
}
|
|
439
|
+
_cloneInto(to) {
|
|
440
|
+
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
|
441
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
442
|
+
to = to;
|
|
443
|
+
to.finished = finished;
|
|
444
|
+
to.destroyed = destroyed;
|
|
445
|
+
to.blockLen = blockLen;
|
|
446
|
+
to.outputLen = outputLen;
|
|
447
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
448
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
449
|
+
return to;
|
|
450
|
+
}
|
|
451
|
+
destroy() {
|
|
452
|
+
this.destroyed = true;
|
|
453
|
+
this.oHash.destroy();
|
|
454
|
+
this.iHash.destroy();
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest();
|
|
458
|
+
hmac.create = (hash2, key) => new HMAC(hash2, key);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/utils.js
|
|
463
|
+
var utils_exports = {};
|
|
464
|
+
__export(utils_exports, {
|
|
465
|
+
aInRange: () => aInRange,
|
|
466
|
+
abool: () => abool,
|
|
467
|
+
abytes: () => abytes4,
|
|
468
|
+
bitGet: () => bitGet,
|
|
469
|
+
bitLen: () => bitLen,
|
|
470
|
+
bitMask: () => bitMask,
|
|
471
|
+
bitSet: () => bitSet,
|
|
472
|
+
bytesToHex: () => bytesToHex2,
|
|
473
|
+
bytesToNumberBE: () => bytesToNumberBE,
|
|
474
|
+
bytesToNumberLE: () => bytesToNumberLE2,
|
|
475
|
+
concatBytes: () => concatBytes3,
|
|
476
|
+
createHmacDrbg: () => createHmacDrbg,
|
|
477
|
+
ensureBytes: () => ensureBytes,
|
|
478
|
+
equalBytes: () => equalBytes,
|
|
479
|
+
hexToBytes: () => hexToBytes2,
|
|
480
|
+
hexToNumber: () => hexToNumber,
|
|
481
|
+
inRange: () => inRange,
|
|
482
|
+
isBytes: () => isBytes4,
|
|
483
|
+
memoized: () => memoized,
|
|
484
|
+
notImplemented: () => notImplemented,
|
|
485
|
+
numberToBytesBE: () => numberToBytesBE,
|
|
486
|
+
numberToBytesLE: () => numberToBytesLE,
|
|
487
|
+
numberToHexUnpadded: () => numberToHexUnpadded,
|
|
488
|
+
numberToVarBytesBE: () => numberToVarBytesBE,
|
|
489
|
+
utf8ToBytes: () => utf8ToBytes3,
|
|
490
|
+
validateObject: () => validateObject
|
|
491
|
+
});
|
|
492
|
+
function isBytes4(a) {
|
|
493
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
494
|
+
}
|
|
495
|
+
function abytes4(item) {
|
|
496
|
+
if (!isBytes4(item))
|
|
497
|
+
throw new Error("Uint8Array expected");
|
|
498
|
+
}
|
|
499
|
+
function abool(title, value) {
|
|
500
|
+
if (typeof value !== "boolean")
|
|
501
|
+
throw new Error(title + " boolean expected, got " + value);
|
|
502
|
+
}
|
|
503
|
+
function bytesToHex2(bytes) {
|
|
504
|
+
abytes4(bytes);
|
|
505
|
+
let hex = "";
|
|
506
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
507
|
+
hex += hexes[bytes[i]];
|
|
508
|
+
}
|
|
509
|
+
return hex;
|
|
510
|
+
}
|
|
511
|
+
function numberToHexUnpadded(num) {
|
|
512
|
+
const hex = num.toString(16);
|
|
513
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
514
|
+
}
|
|
515
|
+
function hexToNumber(hex) {
|
|
516
|
+
if (typeof hex !== "string")
|
|
517
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
518
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
519
|
+
}
|
|
520
|
+
function asciiToBase16(ch) {
|
|
521
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
522
|
+
return ch - asciis._0;
|
|
523
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
524
|
+
return ch - (asciis.A - 10);
|
|
525
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
526
|
+
return ch - (asciis.a - 10);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
function hexToBytes2(hex) {
|
|
530
|
+
if (typeof hex !== "string")
|
|
531
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
532
|
+
const hl = hex.length;
|
|
533
|
+
const al = hl / 2;
|
|
534
|
+
if (hl % 2)
|
|
535
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
536
|
+
const array = new Uint8Array(al);
|
|
537
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
538
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
539
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
540
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
541
|
+
const char = hex[hi] + hex[hi + 1];
|
|
542
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
543
|
+
}
|
|
544
|
+
array[ai] = n1 * 16 + n2;
|
|
545
|
+
}
|
|
546
|
+
return array;
|
|
547
|
+
}
|
|
548
|
+
function bytesToNumberBE(bytes) {
|
|
549
|
+
return hexToNumber(bytesToHex2(bytes));
|
|
550
|
+
}
|
|
551
|
+
function bytesToNumberLE2(bytes) {
|
|
552
|
+
abytes4(bytes);
|
|
553
|
+
return hexToNumber(bytesToHex2(Uint8Array.from(bytes).reverse()));
|
|
554
|
+
}
|
|
555
|
+
function numberToBytesBE(n, len) {
|
|
556
|
+
return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
557
|
+
}
|
|
558
|
+
function numberToBytesLE(n, len) {
|
|
559
|
+
return numberToBytesBE(n, len).reverse();
|
|
560
|
+
}
|
|
561
|
+
function numberToVarBytesBE(n) {
|
|
562
|
+
return hexToBytes2(numberToHexUnpadded(n));
|
|
563
|
+
}
|
|
564
|
+
function ensureBytes(title, hex, expectedLength) {
|
|
565
|
+
let res;
|
|
566
|
+
if (typeof hex === "string") {
|
|
567
|
+
try {
|
|
568
|
+
res = hexToBytes2(hex);
|
|
569
|
+
} catch (e) {
|
|
570
|
+
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
|
|
571
|
+
}
|
|
572
|
+
} else if (isBytes4(hex)) {
|
|
573
|
+
res = Uint8Array.from(hex);
|
|
574
|
+
} else {
|
|
575
|
+
throw new Error(title + " must be hex string or Uint8Array");
|
|
576
|
+
}
|
|
577
|
+
const len = res.length;
|
|
578
|
+
if (typeof expectedLength === "number" && len !== expectedLength)
|
|
579
|
+
throw new Error(title + " of length " + expectedLength + " expected, got " + len);
|
|
580
|
+
return res;
|
|
581
|
+
}
|
|
582
|
+
function concatBytes3(...arrays) {
|
|
583
|
+
let sum = 0;
|
|
584
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
585
|
+
const a = arrays[i];
|
|
586
|
+
abytes4(a);
|
|
587
|
+
sum += a.length;
|
|
588
|
+
}
|
|
589
|
+
const res = new Uint8Array(sum);
|
|
590
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
591
|
+
const a = arrays[i];
|
|
592
|
+
res.set(a, pad);
|
|
593
|
+
pad += a.length;
|
|
594
|
+
}
|
|
595
|
+
return res;
|
|
596
|
+
}
|
|
597
|
+
function equalBytes(a, b) {
|
|
598
|
+
if (a.length !== b.length)
|
|
599
|
+
return false;
|
|
600
|
+
let diff = 0;
|
|
601
|
+
for (let i = 0; i < a.length; i++)
|
|
602
|
+
diff |= a[i] ^ b[i];
|
|
603
|
+
return diff === 0;
|
|
604
|
+
}
|
|
605
|
+
function utf8ToBytes3(str) {
|
|
606
|
+
if (typeof str !== "string")
|
|
607
|
+
throw new Error("string expected");
|
|
608
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
609
|
+
}
|
|
610
|
+
function inRange(n, min, max) {
|
|
611
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
612
|
+
}
|
|
613
|
+
function aInRange(title, n, min, max) {
|
|
614
|
+
if (!inRange(n, min, max))
|
|
615
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
616
|
+
}
|
|
617
|
+
function bitLen(n) {
|
|
618
|
+
let len;
|
|
619
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
620
|
+
;
|
|
621
|
+
return len;
|
|
622
|
+
}
|
|
623
|
+
function bitGet(n, pos) {
|
|
624
|
+
return n >> BigInt(pos) & _1n;
|
|
625
|
+
}
|
|
626
|
+
function bitSet(n, pos, value) {
|
|
627
|
+
return n | (value ? _1n : _0n) << BigInt(pos);
|
|
628
|
+
}
|
|
629
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
630
|
+
if (typeof hashLen !== "number" || hashLen < 2)
|
|
631
|
+
throw new Error("hashLen must be a number");
|
|
632
|
+
if (typeof qByteLen !== "number" || qByteLen < 2)
|
|
633
|
+
throw new Error("qByteLen must be a number");
|
|
634
|
+
if (typeof hmacFn !== "function")
|
|
635
|
+
throw new Error("hmacFn must be a function");
|
|
636
|
+
let v = u8n2(hashLen);
|
|
637
|
+
let k = u8n2(hashLen);
|
|
638
|
+
let i = 0;
|
|
639
|
+
const reset = () => {
|
|
640
|
+
v.fill(1);
|
|
641
|
+
k.fill(0);
|
|
642
|
+
i = 0;
|
|
643
|
+
};
|
|
644
|
+
const h2 = (...b) => hmacFn(k, v, ...b);
|
|
645
|
+
const reseed = (seed = u8n2()) => {
|
|
646
|
+
k = h2(u8fr2([0]), seed);
|
|
647
|
+
v = h2();
|
|
648
|
+
if (seed.length === 0)
|
|
649
|
+
return;
|
|
650
|
+
k = h2(u8fr2([1]), seed);
|
|
651
|
+
v = h2();
|
|
652
|
+
};
|
|
653
|
+
const gen = () => {
|
|
654
|
+
if (i++ >= 1e3)
|
|
655
|
+
throw new Error("drbg: tried 1000 values");
|
|
656
|
+
let len = 0;
|
|
657
|
+
const out = [];
|
|
658
|
+
while (len < qByteLen) {
|
|
659
|
+
v = h2();
|
|
660
|
+
const sl = v.slice();
|
|
661
|
+
out.push(sl);
|
|
662
|
+
len += v.length;
|
|
663
|
+
}
|
|
664
|
+
return concatBytes3(...out);
|
|
665
|
+
};
|
|
666
|
+
const genUntil = (seed, pred) => {
|
|
667
|
+
reset();
|
|
668
|
+
reseed(seed);
|
|
669
|
+
let res = void 0;
|
|
670
|
+
while (!(res = pred(gen())))
|
|
671
|
+
reseed();
|
|
672
|
+
reset();
|
|
673
|
+
return res;
|
|
674
|
+
};
|
|
675
|
+
return genUntil;
|
|
676
|
+
}
|
|
677
|
+
function validateObject(object, validators, optValidators = {}) {
|
|
678
|
+
const checkField = (fieldName, type, isOptional) => {
|
|
679
|
+
const checkVal = validatorFns[type];
|
|
680
|
+
if (typeof checkVal !== "function")
|
|
681
|
+
throw new Error("invalid validator function");
|
|
682
|
+
const val = object[fieldName];
|
|
683
|
+
if (isOptional && val === void 0)
|
|
684
|
+
return;
|
|
685
|
+
if (!checkVal(val, object)) {
|
|
686
|
+
throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
for (const [fieldName, type] of Object.entries(validators))
|
|
690
|
+
checkField(fieldName, type, false);
|
|
691
|
+
for (const [fieldName, type] of Object.entries(optValidators))
|
|
692
|
+
checkField(fieldName, type, true);
|
|
693
|
+
return object;
|
|
694
|
+
}
|
|
695
|
+
function memoized(fn) {
|
|
696
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
697
|
+
return (arg, ...args) => {
|
|
698
|
+
const val = map.get(arg);
|
|
699
|
+
if (val !== void 0)
|
|
700
|
+
return val;
|
|
701
|
+
const computed = fn(arg, ...args);
|
|
702
|
+
map.set(arg, computed);
|
|
703
|
+
return computed;
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
var _0n, _1n, _2n, hexes, asciis, isPosBig, bitMask, u8n2, u8fr2, validatorFns, notImplemented;
|
|
707
|
+
var init_utils2 = __esm({
|
|
708
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/utils.js"() {
|
|
709
|
+
"use strict";
|
|
710
|
+
_0n = /* @__PURE__ */ BigInt(0);
|
|
711
|
+
_1n = /* @__PURE__ */ BigInt(1);
|
|
712
|
+
_2n = /* @__PURE__ */ BigInt(2);
|
|
713
|
+
hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
714
|
+
asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
715
|
+
isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
716
|
+
bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;
|
|
717
|
+
u8n2 = (data) => new Uint8Array(data);
|
|
718
|
+
u8fr2 = (arr) => Uint8Array.from(arr);
|
|
719
|
+
validatorFns = {
|
|
720
|
+
bigint: (val) => typeof val === "bigint",
|
|
721
|
+
function: (val) => typeof val === "function",
|
|
722
|
+
boolean: (val) => typeof val === "boolean",
|
|
723
|
+
string: (val) => typeof val === "string",
|
|
724
|
+
stringOrUint8Array: (val) => typeof val === "string" || isBytes4(val),
|
|
725
|
+
isSafeInteger: (val) => Number.isSafeInteger(val),
|
|
726
|
+
array: (val) => Array.isArray(val),
|
|
727
|
+
field: (val, object) => object.Fp.isValid(val),
|
|
728
|
+
hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
|
|
729
|
+
};
|
|
730
|
+
notImplemented = () => {
|
|
731
|
+
throw new Error("not implemented");
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/modular.js
|
|
737
|
+
function mod(a, b) {
|
|
738
|
+
const result = a % b;
|
|
739
|
+
return result >= _0n2 ? result : b + result;
|
|
740
|
+
}
|
|
741
|
+
function pow(num, power, modulo) {
|
|
742
|
+
if (power < _0n2)
|
|
743
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
744
|
+
if (modulo <= _0n2)
|
|
745
|
+
throw new Error("invalid modulus");
|
|
746
|
+
if (modulo === _1n2)
|
|
747
|
+
return _0n2;
|
|
748
|
+
let res = _1n2;
|
|
749
|
+
while (power > _0n2) {
|
|
750
|
+
if (power & _1n2)
|
|
751
|
+
res = res * num % modulo;
|
|
752
|
+
num = num * num % modulo;
|
|
753
|
+
power >>= _1n2;
|
|
754
|
+
}
|
|
755
|
+
return res;
|
|
756
|
+
}
|
|
757
|
+
function invert2(number, modulo) {
|
|
758
|
+
if (number === _0n2)
|
|
759
|
+
throw new Error("invert: expected non-zero number");
|
|
760
|
+
if (modulo <= _0n2)
|
|
761
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
762
|
+
let a = mod(number, modulo);
|
|
763
|
+
let b = modulo;
|
|
764
|
+
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
765
|
+
while (a !== _0n2) {
|
|
766
|
+
const q = b / a;
|
|
767
|
+
const r = b % a;
|
|
768
|
+
const m = x - u * q;
|
|
769
|
+
const n = y - v * q;
|
|
770
|
+
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
771
|
+
}
|
|
772
|
+
const gcd = b;
|
|
773
|
+
if (gcd !== _1n2)
|
|
774
|
+
throw new Error("invert: does not exist");
|
|
775
|
+
return mod(x, modulo);
|
|
776
|
+
}
|
|
777
|
+
function tonelliShanks(P2) {
|
|
778
|
+
const legendreC = (P2 - _1n2) / _2n2;
|
|
779
|
+
let Q, S, Z;
|
|
780
|
+
for (Q = P2 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++)
|
|
781
|
+
;
|
|
782
|
+
for (Z = _2n2; Z < P2 && pow(Z, legendreC, P2) !== P2 - _1n2; Z++) {
|
|
783
|
+
if (Z > 1e3)
|
|
784
|
+
throw new Error("Cannot find square root: likely non-prime P");
|
|
785
|
+
}
|
|
786
|
+
if (S === 1) {
|
|
787
|
+
const p1div4 = (P2 + _1n2) / _4n;
|
|
788
|
+
return function tonelliFast(Fp, n) {
|
|
789
|
+
const root = Fp.pow(n, p1div4);
|
|
790
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
791
|
+
throw new Error("Cannot find square root");
|
|
792
|
+
return root;
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
const Q1div2 = (Q + _1n2) / _2n2;
|
|
796
|
+
return function tonelliSlow(Fp, n) {
|
|
797
|
+
if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
|
|
798
|
+
throw new Error("Cannot find square root");
|
|
799
|
+
let r = S;
|
|
800
|
+
let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q);
|
|
801
|
+
let x = Fp.pow(n, Q1div2);
|
|
802
|
+
let b = Fp.pow(n, Q);
|
|
803
|
+
while (!Fp.eql(b, Fp.ONE)) {
|
|
804
|
+
if (Fp.eql(b, Fp.ZERO))
|
|
805
|
+
return Fp.ZERO;
|
|
806
|
+
let m = 1;
|
|
807
|
+
for (let t2 = Fp.sqr(b); m < r; m++) {
|
|
808
|
+
if (Fp.eql(t2, Fp.ONE))
|
|
809
|
+
break;
|
|
810
|
+
t2 = Fp.sqr(t2);
|
|
811
|
+
}
|
|
812
|
+
const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1));
|
|
813
|
+
g = Fp.sqr(ge);
|
|
814
|
+
x = Fp.mul(x, ge);
|
|
815
|
+
b = Fp.mul(b, g);
|
|
816
|
+
r = m;
|
|
817
|
+
}
|
|
818
|
+
return x;
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
function FpSqrt(P2) {
|
|
822
|
+
if (P2 % _4n === _3n) {
|
|
823
|
+
const p1div4 = (P2 + _1n2) / _4n;
|
|
824
|
+
return function sqrt3mod4(Fp, n) {
|
|
825
|
+
const root = Fp.pow(n, p1div4);
|
|
826
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
827
|
+
throw new Error("Cannot find square root");
|
|
828
|
+
return root;
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
if (P2 % _8n === _5n) {
|
|
832
|
+
const c1 = (P2 - _5n) / _8n;
|
|
833
|
+
return function sqrt5mod8(Fp, n) {
|
|
834
|
+
const n2 = Fp.mul(n, _2n2);
|
|
835
|
+
const v = Fp.pow(n2, c1);
|
|
836
|
+
const nv = Fp.mul(n, v);
|
|
837
|
+
const i = Fp.mul(Fp.mul(nv, _2n2), v);
|
|
838
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
839
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
840
|
+
throw new Error("Cannot find square root");
|
|
841
|
+
return root;
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
if (P2 % _16n === _9n) {
|
|
845
|
+
}
|
|
846
|
+
return tonelliShanks(P2);
|
|
847
|
+
}
|
|
848
|
+
function validateField(field) {
|
|
849
|
+
const initial = {
|
|
850
|
+
ORDER: "bigint",
|
|
851
|
+
MASK: "bigint",
|
|
852
|
+
BYTES: "isSafeInteger",
|
|
853
|
+
BITS: "isSafeInteger"
|
|
854
|
+
};
|
|
855
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
856
|
+
map[val] = "function";
|
|
857
|
+
return map;
|
|
858
|
+
}, initial);
|
|
859
|
+
return validateObject(field, opts);
|
|
860
|
+
}
|
|
861
|
+
function FpPow(f, num, power) {
|
|
862
|
+
if (power < _0n2)
|
|
863
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
864
|
+
if (power === _0n2)
|
|
865
|
+
return f.ONE;
|
|
866
|
+
if (power === _1n2)
|
|
867
|
+
return num;
|
|
868
|
+
let p = f.ONE;
|
|
869
|
+
let d = num;
|
|
870
|
+
while (power > _0n2) {
|
|
871
|
+
if (power & _1n2)
|
|
872
|
+
p = f.mul(p, d);
|
|
873
|
+
d = f.sqr(d);
|
|
874
|
+
power >>= _1n2;
|
|
875
|
+
}
|
|
876
|
+
return p;
|
|
877
|
+
}
|
|
878
|
+
function FpInvertBatch(f, nums) {
|
|
879
|
+
const tmp = new Array(nums.length);
|
|
880
|
+
const lastMultiplied = nums.reduce((acc, num, i) => {
|
|
881
|
+
if (f.is0(num))
|
|
882
|
+
return acc;
|
|
883
|
+
tmp[i] = acc;
|
|
884
|
+
return f.mul(acc, num);
|
|
885
|
+
}, f.ONE);
|
|
886
|
+
const inverted = f.inv(lastMultiplied);
|
|
887
|
+
nums.reduceRight((acc, num, i) => {
|
|
888
|
+
if (f.is0(num))
|
|
889
|
+
return acc;
|
|
890
|
+
tmp[i] = f.mul(acc, tmp[i]);
|
|
891
|
+
return f.mul(acc, num);
|
|
892
|
+
}, inverted);
|
|
893
|
+
return tmp;
|
|
894
|
+
}
|
|
895
|
+
function nLength(n, nBitLength) {
|
|
896
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
897
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
898
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
899
|
+
}
|
|
900
|
+
function Field(ORDER, bitLen2, isLE = false, redef = {}) {
|
|
901
|
+
if (ORDER <= _0n2)
|
|
902
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
903
|
+
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
|
|
904
|
+
if (BYTES > 2048)
|
|
905
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
906
|
+
let sqrtP;
|
|
907
|
+
const f = Object.freeze({
|
|
908
|
+
ORDER,
|
|
909
|
+
BITS,
|
|
910
|
+
BYTES,
|
|
911
|
+
MASK: bitMask(BITS),
|
|
912
|
+
ZERO: _0n2,
|
|
913
|
+
ONE: _1n2,
|
|
914
|
+
create: (num) => mod(num, ORDER),
|
|
915
|
+
isValid: (num) => {
|
|
916
|
+
if (typeof num !== "bigint")
|
|
917
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
918
|
+
return _0n2 <= num && num < ORDER;
|
|
919
|
+
},
|
|
920
|
+
is0: (num) => num === _0n2,
|
|
921
|
+
isOdd: (num) => (num & _1n2) === _1n2,
|
|
922
|
+
neg: (num) => mod(-num, ORDER),
|
|
923
|
+
eql: (lhs, rhs) => lhs === rhs,
|
|
924
|
+
sqr: (num) => mod(num * num, ORDER),
|
|
925
|
+
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
|
926
|
+
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
|
927
|
+
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
|
928
|
+
pow: (num, power) => FpPow(f, num, power),
|
|
929
|
+
div: (lhs, rhs) => mod(lhs * invert2(rhs, ORDER), ORDER),
|
|
930
|
+
// Same as above, but doesn't normalize
|
|
931
|
+
sqrN: (num) => num * num,
|
|
932
|
+
addN: (lhs, rhs) => lhs + rhs,
|
|
933
|
+
subN: (lhs, rhs) => lhs - rhs,
|
|
934
|
+
mulN: (lhs, rhs) => lhs * rhs,
|
|
935
|
+
inv: (num) => invert2(num, ORDER),
|
|
936
|
+
sqrt: redef.sqrt || ((n) => {
|
|
937
|
+
if (!sqrtP)
|
|
938
|
+
sqrtP = FpSqrt(ORDER);
|
|
939
|
+
return sqrtP(f, n);
|
|
940
|
+
}),
|
|
941
|
+
invertBatch: (lst) => FpInvertBatch(f, lst),
|
|
942
|
+
// TODO: do we really need constant cmov?
|
|
943
|
+
// We don't have const-time bigints anyway, so probably will be not very useful
|
|
944
|
+
cmov: (a, b, c) => c ? b : a,
|
|
945
|
+
toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
|
|
946
|
+
fromBytes: (bytes) => {
|
|
947
|
+
if (bytes.length !== BYTES)
|
|
948
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
949
|
+
return isLE ? bytesToNumberLE2(bytes) : bytesToNumberBE(bytes);
|
|
950
|
+
}
|
|
951
|
+
});
|
|
952
|
+
return Object.freeze(f);
|
|
953
|
+
}
|
|
954
|
+
function getFieldBytesLength(fieldOrder) {
|
|
955
|
+
if (typeof fieldOrder !== "bigint")
|
|
956
|
+
throw new Error("field order must be bigint");
|
|
957
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
958
|
+
return Math.ceil(bitLength / 8);
|
|
959
|
+
}
|
|
960
|
+
function getMinHashLength(fieldOrder) {
|
|
961
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
962
|
+
return length + Math.ceil(length / 2);
|
|
963
|
+
}
|
|
964
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
965
|
+
const len = key.length;
|
|
966
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
967
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
968
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
969
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
970
|
+
const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE2(key);
|
|
971
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
972
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
973
|
+
}
|
|
974
|
+
var _0n2, _1n2, _2n2, _3n, _4n, _5n, _8n, _9n, _16n, FIELD_FIELDS;
|
|
975
|
+
var init_modular = __esm({
|
|
976
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/modular.js"() {
|
|
977
|
+
"use strict";
|
|
978
|
+
init_utils2();
|
|
979
|
+
_0n2 = BigInt(0);
|
|
980
|
+
_1n2 = BigInt(1);
|
|
981
|
+
_2n2 = /* @__PURE__ */ BigInt(2);
|
|
982
|
+
_3n = /* @__PURE__ */ BigInt(3);
|
|
983
|
+
_4n = /* @__PURE__ */ BigInt(4);
|
|
984
|
+
_5n = /* @__PURE__ */ BigInt(5);
|
|
985
|
+
_8n = /* @__PURE__ */ BigInt(8);
|
|
986
|
+
_9n = /* @__PURE__ */ BigInt(9);
|
|
987
|
+
_16n = /* @__PURE__ */ BigInt(16);
|
|
988
|
+
FIELD_FIELDS = [
|
|
989
|
+
"create",
|
|
990
|
+
"isValid",
|
|
991
|
+
"is0",
|
|
992
|
+
"neg",
|
|
993
|
+
"inv",
|
|
994
|
+
"sqrt",
|
|
995
|
+
"sqr",
|
|
996
|
+
"eql",
|
|
997
|
+
"add",
|
|
998
|
+
"sub",
|
|
999
|
+
"mul",
|
|
1000
|
+
"pow",
|
|
1001
|
+
"div",
|
|
1002
|
+
"addN",
|
|
1003
|
+
"subN",
|
|
1004
|
+
"mulN",
|
|
1005
|
+
"sqrN"
|
|
1006
|
+
];
|
|
1007
|
+
}
|
|
1008
|
+
});
|
|
1009
|
+
|
|
1010
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/curve.js
|
|
1011
|
+
function constTimeNegate(condition, item) {
|
|
1012
|
+
const neg = item.negate();
|
|
1013
|
+
return condition ? neg : item;
|
|
1014
|
+
}
|
|
1015
|
+
function validateW(W2, bits) {
|
|
1016
|
+
if (!Number.isSafeInteger(W2) || W2 <= 0 || W2 > bits)
|
|
1017
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W2);
|
|
1018
|
+
}
|
|
1019
|
+
function calcWOpts(W2, bits) {
|
|
1020
|
+
validateW(W2, bits);
|
|
1021
|
+
const windows = Math.ceil(bits / W2) + 1;
|
|
1022
|
+
const windowSize = 2 ** (W2 - 1);
|
|
1023
|
+
return { windows, windowSize };
|
|
1024
|
+
}
|
|
1025
|
+
function validateMSMPoints(points, c) {
|
|
1026
|
+
if (!Array.isArray(points))
|
|
1027
|
+
throw new Error("array expected");
|
|
1028
|
+
points.forEach((p, i) => {
|
|
1029
|
+
if (!(p instanceof c))
|
|
1030
|
+
throw new Error("invalid point at index " + i);
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
function validateMSMScalars(scalars, field) {
|
|
1034
|
+
if (!Array.isArray(scalars))
|
|
1035
|
+
throw new Error("array of scalars expected");
|
|
1036
|
+
scalars.forEach((s, i) => {
|
|
1037
|
+
if (!field.isValid(s))
|
|
1038
|
+
throw new Error("invalid scalar at index " + i);
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
function getW(P2) {
|
|
1042
|
+
return pointWindowSizes.get(P2) || 1;
|
|
1043
|
+
}
|
|
1044
|
+
function wNAF2(c, bits) {
|
|
1045
|
+
return {
|
|
1046
|
+
constTimeNegate,
|
|
1047
|
+
hasPrecomputes(elm) {
|
|
1048
|
+
return getW(elm) !== 1;
|
|
1049
|
+
},
|
|
1050
|
+
// non-const time multiplication ladder
|
|
1051
|
+
unsafeLadder(elm, n, p = c.ZERO) {
|
|
1052
|
+
let d = elm;
|
|
1053
|
+
while (n > _0n3) {
|
|
1054
|
+
if (n & _1n3)
|
|
1055
|
+
p = p.add(d);
|
|
1056
|
+
d = d.double();
|
|
1057
|
+
n >>= _1n3;
|
|
1058
|
+
}
|
|
1059
|
+
return p;
|
|
1060
|
+
},
|
|
1061
|
+
/**
|
|
1062
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
1063
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
1064
|
+
* Number of precomputed points depends on the curve size:
|
|
1065
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
1066
|
+
* - 𝑊 is the window size
|
|
1067
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
1068
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
1069
|
+
* @param elm Point instance
|
|
1070
|
+
* @param W window size
|
|
1071
|
+
* @returns precomputed point tables flattened to a single array
|
|
1072
|
+
*/
|
|
1073
|
+
precomputeWindow(elm, W2) {
|
|
1074
|
+
const { windows, windowSize } = calcWOpts(W2, bits);
|
|
1075
|
+
const points = [];
|
|
1076
|
+
let p = elm;
|
|
1077
|
+
let base = p;
|
|
1078
|
+
for (let window = 0; window < windows; window++) {
|
|
1079
|
+
base = p;
|
|
1080
|
+
points.push(base);
|
|
1081
|
+
for (let i = 1; i < windowSize; i++) {
|
|
1082
|
+
base = base.add(p);
|
|
1083
|
+
points.push(base);
|
|
1084
|
+
}
|
|
1085
|
+
p = base.double();
|
|
1086
|
+
}
|
|
1087
|
+
return points;
|
|
1088
|
+
},
|
|
1089
|
+
/**
|
|
1090
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
1091
|
+
* @param W window size
|
|
1092
|
+
* @param precomputes precomputed tables
|
|
1093
|
+
* @param n scalar (we don't check here, but should be less than curve order)
|
|
1094
|
+
* @returns real and fake (for const-time) points
|
|
1095
|
+
*/
|
|
1096
|
+
wNAF(W2, precomputes, n) {
|
|
1097
|
+
const { windows, windowSize } = calcWOpts(W2, bits);
|
|
1098
|
+
let p = c.ZERO;
|
|
1099
|
+
let f = c.BASE;
|
|
1100
|
+
const mask = BigInt(2 ** W2 - 1);
|
|
1101
|
+
const maxNumber = 2 ** W2;
|
|
1102
|
+
const shiftBy = BigInt(W2);
|
|
1103
|
+
for (let window = 0; window < windows; window++) {
|
|
1104
|
+
const offset = window * windowSize;
|
|
1105
|
+
let wbits = Number(n & mask);
|
|
1106
|
+
n >>= shiftBy;
|
|
1107
|
+
if (wbits > windowSize) {
|
|
1108
|
+
wbits -= maxNumber;
|
|
1109
|
+
n += _1n3;
|
|
1110
|
+
}
|
|
1111
|
+
const offset1 = offset;
|
|
1112
|
+
const offset2 = offset + Math.abs(wbits) - 1;
|
|
1113
|
+
const cond1 = window % 2 !== 0;
|
|
1114
|
+
const cond2 = wbits < 0;
|
|
1115
|
+
if (wbits === 0) {
|
|
1116
|
+
f = f.add(constTimeNegate(cond1, precomputes[offset1]));
|
|
1117
|
+
} else {
|
|
1118
|
+
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
return { p, f };
|
|
1122
|
+
},
|
|
1123
|
+
/**
|
|
1124
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
1125
|
+
* @param W window size
|
|
1126
|
+
* @param precomputes precomputed tables
|
|
1127
|
+
* @param n scalar (we don't check here, but should be less than curve order)
|
|
1128
|
+
* @param acc accumulator point to add result of multiplication
|
|
1129
|
+
* @returns point
|
|
1130
|
+
*/
|
|
1131
|
+
wNAFUnsafe(W2, precomputes, n, acc = c.ZERO) {
|
|
1132
|
+
const { windows, windowSize } = calcWOpts(W2, bits);
|
|
1133
|
+
const mask = BigInt(2 ** W2 - 1);
|
|
1134
|
+
const maxNumber = 2 ** W2;
|
|
1135
|
+
const shiftBy = BigInt(W2);
|
|
1136
|
+
for (let window = 0; window < windows; window++) {
|
|
1137
|
+
const offset = window * windowSize;
|
|
1138
|
+
if (n === _0n3)
|
|
1139
|
+
break;
|
|
1140
|
+
let wbits = Number(n & mask);
|
|
1141
|
+
n >>= shiftBy;
|
|
1142
|
+
if (wbits > windowSize) {
|
|
1143
|
+
wbits -= maxNumber;
|
|
1144
|
+
n += _1n3;
|
|
1145
|
+
}
|
|
1146
|
+
if (wbits === 0)
|
|
1147
|
+
continue;
|
|
1148
|
+
let curr = precomputes[offset + Math.abs(wbits) - 1];
|
|
1149
|
+
if (wbits < 0)
|
|
1150
|
+
curr = curr.negate();
|
|
1151
|
+
acc = acc.add(curr);
|
|
1152
|
+
}
|
|
1153
|
+
return acc;
|
|
1154
|
+
},
|
|
1155
|
+
getPrecomputes(W2, P2, transform) {
|
|
1156
|
+
let comp = pointPrecomputes.get(P2);
|
|
1157
|
+
if (!comp) {
|
|
1158
|
+
comp = this.precomputeWindow(P2, W2);
|
|
1159
|
+
if (W2 !== 1)
|
|
1160
|
+
pointPrecomputes.set(P2, transform(comp));
|
|
1161
|
+
}
|
|
1162
|
+
return comp;
|
|
1163
|
+
},
|
|
1164
|
+
wNAFCached(P2, n, transform) {
|
|
1165
|
+
const W2 = getW(P2);
|
|
1166
|
+
return this.wNAF(W2, this.getPrecomputes(W2, P2, transform), n);
|
|
1167
|
+
},
|
|
1168
|
+
wNAFCachedUnsafe(P2, n, transform, prev) {
|
|
1169
|
+
const W2 = getW(P2);
|
|
1170
|
+
if (W2 === 1)
|
|
1171
|
+
return this.unsafeLadder(P2, n, prev);
|
|
1172
|
+
return this.wNAFUnsafe(W2, this.getPrecomputes(W2, P2, transform), n, prev);
|
|
1173
|
+
},
|
|
1174
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
1175
|
+
// using windowed method. This specifies window size and
|
|
1176
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
1177
|
+
setWindowSize(P2, W2) {
|
|
1178
|
+
validateW(W2, bits);
|
|
1179
|
+
pointWindowSizes.set(P2, W2);
|
|
1180
|
+
pointPrecomputes.delete(P2);
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
function pippenger(c, fieldN, points, scalars) {
|
|
1185
|
+
validateMSMPoints(points, c);
|
|
1186
|
+
validateMSMScalars(scalars, fieldN);
|
|
1187
|
+
if (points.length !== scalars.length)
|
|
1188
|
+
throw new Error("arrays of points and scalars must have equal length");
|
|
1189
|
+
const zero = c.ZERO;
|
|
1190
|
+
const wbits = bitLen(BigInt(points.length));
|
|
1191
|
+
const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1;
|
|
1192
|
+
const MASK = (1 << windowSize) - 1;
|
|
1193
|
+
const buckets = new Array(MASK + 1).fill(zero);
|
|
1194
|
+
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
|
1195
|
+
let sum = zero;
|
|
1196
|
+
for (let i = lastBits; i >= 0; i -= windowSize) {
|
|
1197
|
+
buckets.fill(zero);
|
|
1198
|
+
for (let j = 0; j < scalars.length; j++) {
|
|
1199
|
+
const scalar = scalars[j];
|
|
1200
|
+
const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK));
|
|
1201
|
+
buckets[wbits2] = buckets[wbits2].add(points[j]);
|
|
1202
|
+
}
|
|
1203
|
+
let resI = zero;
|
|
1204
|
+
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
|
1205
|
+
sumI = sumI.add(buckets[j]);
|
|
1206
|
+
resI = resI.add(sumI);
|
|
1207
|
+
}
|
|
1208
|
+
sum = sum.add(resI);
|
|
1209
|
+
if (i !== 0)
|
|
1210
|
+
for (let j = 0; j < windowSize; j++)
|
|
1211
|
+
sum = sum.double();
|
|
1212
|
+
}
|
|
1213
|
+
return sum;
|
|
1214
|
+
}
|
|
1215
|
+
function validateBasic(curve) {
|
|
1216
|
+
validateField(curve.Fp);
|
|
1217
|
+
validateObject(curve, {
|
|
1218
|
+
n: "bigint",
|
|
1219
|
+
h: "bigint",
|
|
1220
|
+
Gx: "field",
|
|
1221
|
+
Gy: "field"
|
|
1222
|
+
}, {
|
|
1223
|
+
nBitLength: "isSafeInteger",
|
|
1224
|
+
nByteLength: "isSafeInteger"
|
|
1225
|
+
});
|
|
1226
|
+
return Object.freeze({
|
|
1227
|
+
...nLength(curve.n, curve.nBitLength),
|
|
1228
|
+
...curve,
|
|
1229
|
+
...{ p: curve.Fp.ORDER }
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
var _0n3, _1n3, pointPrecomputes, pointWindowSizes;
|
|
1233
|
+
var init_curve = __esm({
|
|
1234
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/curve.js"() {
|
|
1235
|
+
"use strict";
|
|
1236
|
+
init_modular();
|
|
1237
|
+
init_utils2();
|
|
1238
|
+
_0n3 = BigInt(0);
|
|
1239
|
+
_1n3 = BigInt(1);
|
|
1240
|
+
pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
1241
|
+
pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
1242
|
+
}
|
|
1243
|
+
});
|
|
1244
|
+
|
|
1245
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/weierstrass.js
|
|
1246
|
+
function validateSigVerOpts(opts) {
|
|
1247
|
+
if (opts.lowS !== void 0)
|
|
1248
|
+
abool("lowS", opts.lowS);
|
|
1249
|
+
if (opts.prehash !== void 0)
|
|
1250
|
+
abool("prehash", opts.prehash);
|
|
1251
|
+
}
|
|
1252
|
+
function validatePointOpts(curve) {
|
|
1253
|
+
const opts = validateBasic(curve);
|
|
1254
|
+
validateObject(opts, {
|
|
1255
|
+
a: "field",
|
|
1256
|
+
b: "field"
|
|
1257
|
+
}, {
|
|
1258
|
+
allowedPrivateKeyLengths: "array",
|
|
1259
|
+
wrapPrivateKey: "boolean",
|
|
1260
|
+
isTorsionFree: "function",
|
|
1261
|
+
clearCofactor: "function",
|
|
1262
|
+
allowInfinityPoint: "boolean",
|
|
1263
|
+
fromBytes: "function",
|
|
1264
|
+
toBytes: "function"
|
|
1265
|
+
});
|
|
1266
|
+
const { endo, Fp, a } = opts;
|
|
1267
|
+
if (endo) {
|
|
1268
|
+
if (!Fp.eql(a, Fp.ZERO)) {
|
|
1269
|
+
throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");
|
|
1270
|
+
}
|
|
1271
|
+
if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
|
|
1272
|
+
throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function");
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
return Object.freeze({ ...opts });
|
|
1276
|
+
}
|
|
1277
|
+
function weierstrassPoints(opts) {
|
|
1278
|
+
const CURVE = validatePointOpts(opts);
|
|
1279
|
+
const { Fp } = CURVE;
|
|
1280
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
|
1281
|
+
const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => {
|
|
1282
|
+
const a = point.toAffine();
|
|
1283
|
+
return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
|
|
1284
|
+
});
|
|
1285
|
+
const fromBytes = CURVE.fromBytes || ((bytes) => {
|
|
1286
|
+
const tail = bytes.subarray(1);
|
|
1287
|
+
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
|
|
1288
|
+
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
|
|
1289
|
+
return { x, y };
|
|
1290
|
+
});
|
|
1291
|
+
function weierstrassEquation(x) {
|
|
1292
|
+
const { a, b } = CURVE;
|
|
1293
|
+
const x2 = Fp.sqr(x);
|
|
1294
|
+
const x3 = Fp.mul(x2, x);
|
|
1295
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
|
|
1296
|
+
}
|
|
1297
|
+
if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))
|
|
1298
|
+
throw new Error("bad generator point: equation left != right");
|
|
1299
|
+
function isWithinCurveOrder(num) {
|
|
1300
|
+
return inRange(num, _1n4, CURVE.n);
|
|
1301
|
+
}
|
|
1302
|
+
function normPrivateKeyToScalar(key) {
|
|
1303
|
+
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N2 } = CURVE;
|
|
1304
|
+
if (lengths && typeof key !== "bigint") {
|
|
1305
|
+
if (isBytes4(key))
|
|
1306
|
+
key = bytesToHex2(key);
|
|
1307
|
+
if (typeof key !== "string" || !lengths.includes(key.length))
|
|
1308
|
+
throw new Error("invalid private key");
|
|
1309
|
+
key = key.padStart(nByteLength * 2, "0");
|
|
1310
|
+
}
|
|
1311
|
+
let num;
|
|
1312
|
+
try {
|
|
1313
|
+
num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
|
|
1316
|
+
}
|
|
1317
|
+
if (wrapPrivateKey)
|
|
1318
|
+
num = mod(num, N2);
|
|
1319
|
+
aInRange("private key", num, _1n4, N2);
|
|
1320
|
+
return num;
|
|
1321
|
+
}
|
|
1322
|
+
function assertPrjPoint(other) {
|
|
1323
|
+
if (!(other instanceof Point2))
|
|
1324
|
+
throw new Error("ProjectivePoint expected");
|
|
1325
|
+
}
|
|
1326
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
1327
|
+
const { px: x, py: y, pz: z } = p;
|
|
1328
|
+
if (Fp.eql(z, Fp.ONE))
|
|
1329
|
+
return { x, y };
|
|
1330
|
+
const is0 = p.is0();
|
|
1331
|
+
if (iz == null)
|
|
1332
|
+
iz = is0 ? Fp.ONE : Fp.inv(z);
|
|
1333
|
+
const ax = Fp.mul(x, iz);
|
|
1334
|
+
const ay = Fp.mul(y, iz);
|
|
1335
|
+
const zz = Fp.mul(z, iz);
|
|
1336
|
+
if (is0)
|
|
1337
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
1338
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
1339
|
+
throw new Error("invZ was invalid");
|
|
1340
|
+
return { x: ax, y: ay };
|
|
1341
|
+
});
|
|
1342
|
+
const assertValidMemo = memoized((p) => {
|
|
1343
|
+
if (p.is0()) {
|
|
1344
|
+
if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
|
|
1345
|
+
return;
|
|
1346
|
+
throw new Error("bad point: ZERO");
|
|
1347
|
+
}
|
|
1348
|
+
const { x, y } = p.toAffine();
|
|
1349
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
1350
|
+
throw new Error("bad point: x or y not FE");
|
|
1351
|
+
const left = Fp.sqr(y);
|
|
1352
|
+
const right = weierstrassEquation(x);
|
|
1353
|
+
if (!Fp.eql(left, right))
|
|
1354
|
+
throw new Error("bad point: equation left != right");
|
|
1355
|
+
if (!p.isTorsionFree())
|
|
1356
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
1357
|
+
return true;
|
|
1358
|
+
});
|
|
1359
|
+
class Point2 {
|
|
1360
|
+
constructor(px, py, pz) {
|
|
1361
|
+
this.px = px;
|
|
1362
|
+
this.py = py;
|
|
1363
|
+
this.pz = pz;
|
|
1364
|
+
if (px == null || !Fp.isValid(px))
|
|
1365
|
+
throw new Error("x required");
|
|
1366
|
+
if (py == null || !Fp.isValid(py))
|
|
1367
|
+
throw new Error("y required");
|
|
1368
|
+
if (pz == null || !Fp.isValid(pz))
|
|
1369
|
+
throw new Error("z required");
|
|
1370
|
+
Object.freeze(this);
|
|
1371
|
+
}
|
|
1372
|
+
// Does not validate if the point is on-curve.
|
|
1373
|
+
// Use fromHex instead, or call assertValidity() later.
|
|
1374
|
+
static fromAffine(p) {
|
|
1375
|
+
const { x, y } = p || {};
|
|
1376
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
1377
|
+
throw new Error("invalid affine point");
|
|
1378
|
+
if (p instanceof Point2)
|
|
1379
|
+
throw new Error("projective point not allowed");
|
|
1380
|
+
const is0 = (i) => Fp.eql(i, Fp.ZERO);
|
|
1381
|
+
if (is0(x) && is0(y))
|
|
1382
|
+
return Point2.ZERO;
|
|
1383
|
+
return new Point2(x, y, Fp.ONE);
|
|
1384
|
+
}
|
|
1385
|
+
get x() {
|
|
1386
|
+
return this.toAffine().x;
|
|
1387
|
+
}
|
|
1388
|
+
get y() {
|
|
1389
|
+
return this.toAffine().y;
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Takes a bunch of Projective Points but executes only one
|
|
1393
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
1394
|
+
* so this improves performance massively.
|
|
1395
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
1396
|
+
*/
|
|
1397
|
+
static normalizeZ(points) {
|
|
1398
|
+
const toInv = Fp.invertBatch(points.map((p) => p.pz));
|
|
1399
|
+
return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine);
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Converts hash string or Uint8Array to Point.
|
|
1403
|
+
* @param hex short/long ECDSA hex
|
|
1404
|
+
*/
|
|
1405
|
+
static fromHex(hex) {
|
|
1406
|
+
const P2 = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
|
|
1407
|
+
P2.assertValidity();
|
|
1408
|
+
return P2;
|
|
1409
|
+
}
|
|
1410
|
+
// Multiplies generator point by privateKey.
|
|
1411
|
+
static fromPrivateKey(privateKey) {
|
|
1412
|
+
return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey));
|
|
1413
|
+
}
|
|
1414
|
+
// Multiscalar Multiplication
|
|
1415
|
+
static msm(points, scalars) {
|
|
1416
|
+
return pippenger(Point2, Fn, points, scalars);
|
|
1417
|
+
}
|
|
1418
|
+
// "Private method", don't use it directly
|
|
1419
|
+
_setWindowSize(windowSize) {
|
|
1420
|
+
wnaf.setWindowSize(this, windowSize);
|
|
1421
|
+
}
|
|
1422
|
+
// A point on curve is valid if it conforms to equation.
|
|
1423
|
+
assertValidity() {
|
|
1424
|
+
assertValidMemo(this);
|
|
1425
|
+
}
|
|
1426
|
+
hasEvenY() {
|
|
1427
|
+
const { y } = this.toAffine();
|
|
1428
|
+
if (Fp.isOdd)
|
|
1429
|
+
return !Fp.isOdd(y);
|
|
1430
|
+
throw new Error("Field doesn't support isOdd");
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Compare one point to another.
|
|
1434
|
+
*/
|
|
1435
|
+
equals(other) {
|
|
1436
|
+
assertPrjPoint(other);
|
|
1437
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
1438
|
+
const { px: X2, py: Y2, pz: Z2 } = other;
|
|
1439
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
1440
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
1441
|
+
return U1 && U2;
|
|
1442
|
+
}
|
|
1443
|
+
/**
|
|
1444
|
+
* Flips point to one corresponding to (x, -y) in Affine coordinates.
|
|
1445
|
+
*/
|
|
1446
|
+
negate() {
|
|
1447
|
+
return new Point2(this.px, Fp.neg(this.py), this.pz);
|
|
1448
|
+
}
|
|
1449
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
1450
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
1451
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
1452
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
1453
|
+
double() {
|
|
1454
|
+
const { a, b } = CURVE;
|
|
1455
|
+
const b3 = Fp.mul(b, _3n2);
|
|
1456
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
1457
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
1458
|
+
let t0 = Fp.mul(X1, X1);
|
|
1459
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
1460
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
1461
|
+
let t3 = Fp.mul(X1, Y1);
|
|
1462
|
+
t3 = Fp.add(t3, t3);
|
|
1463
|
+
Z3 = Fp.mul(X1, Z1);
|
|
1464
|
+
Z3 = Fp.add(Z3, Z3);
|
|
1465
|
+
X3 = Fp.mul(a, Z3);
|
|
1466
|
+
Y3 = Fp.mul(b3, t2);
|
|
1467
|
+
Y3 = Fp.add(X3, Y3);
|
|
1468
|
+
X3 = Fp.sub(t1, Y3);
|
|
1469
|
+
Y3 = Fp.add(t1, Y3);
|
|
1470
|
+
Y3 = Fp.mul(X3, Y3);
|
|
1471
|
+
X3 = Fp.mul(t3, X3);
|
|
1472
|
+
Z3 = Fp.mul(b3, Z3);
|
|
1473
|
+
t2 = Fp.mul(a, t2);
|
|
1474
|
+
t3 = Fp.sub(t0, t2);
|
|
1475
|
+
t3 = Fp.mul(a, t3);
|
|
1476
|
+
t3 = Fp.add(t3, Z3);
|
|
1477
|
+
Z3 = Fp.add(t0, t0);
|
|
1478
|
+
t0 = Fp.add(Z3, t0);
|
|
1479
|
+
t0 = Fp.add(t0, t2);
|
|
1480
|
+
t0 = Fp.mul(t0, t3);
|
|
1481
|
+
Y3 = Fp.add(Y3, t0);
|
|
1482
|
+
t2 = Fp.mul(Y1, Z1);
|
|
1483
|
+
t2 = Fp.add(t2, t2);
|
|
1484
|
+
t0 = Fp.mul(t2, t3);
|
|
1485
|
+
X3 = Fp.sub(X3, t0);
|
|
1486
|
+
Z3 = Fp.mul(t2, t1);
|
|
1487
|
+
Z3 = Fp.add(Z3, Z3);
|
|
1488
|
+
Z3 = Fp.add(Z3, Z3);
|
|
1489
|
+
return new Point2(X3, Y3, Z3);
|
|
1490
|
+
}
|
|
1491
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
1492
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
1493
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
1494
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
1495
|
+
add(other) {
|
|
1496
|
+
assertPrjPoint(other);
|
|
1497
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
1498
|
+
const { px: X2, py: Y2, pz: Z2 } = other;
|
|
1499
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
1500
|
+
const a = CURVE.a;
|
|
1501
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
1502
|
+
let t0 = Fp.mul(X1, X2);
|
|
1503
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
1504
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
1505
|
+
let t3 = Fp.add(X1, Y1);
|
|
1506
|
+
let t4 = Fp.add(X2, Y2);
|
|
1507
|
+
t3 = Fp.mul(t3, t4);
|
|
1508
|
+
t4 = Fp.add(t0, t1);
|
|
1509
|
+
t3 = Fp.sub(t3, t4);
|
|
1510
|
+
t4 = Fp.add(X1, Z1);
|
|
1511
|
+
let t5 = Fp.add(X2, Z2);
|
|
1512
|
+
t4 = Fp.mul(t4, t5);
|
|
1513
|
+
t5 = Fp.add(t0, t2);
|
|
1514
|
+
t4 = Fp.sub(t4, t5);
|
|
1515
|
+
t5 = Fp.add(Y1, Z1);
|
|
1516
|
+
X3 = Fp.add(Y2, Z2);
|
|
1517
|
+
t5 = Fp.mul(t5, X3);
|
|
1518
|
+
X3 = Fp.add(t1, t2);
|
|
1519
|
+
t5 = Fp.sub(t5, X3);
|
|
1520
|
+
Z3 = Fp.mul(a, t4);
|
|
1521
|
+
X3 = Fp.mul(b3, t2);
|
|
1522
|
+
Z3 = Fp.add(X3, Z3);
|
|
1523
|
+
X3 = Fp.sub(t1, Z3);
|
|
1524
|
+
Z3 = Fp.add(t1, Z3);
|
|
1525
|
+
Y3 = Fp.mul(X3, Z3);
|
|
1526
|
+
t1 = Fp.add(t0, t0);
|
|
1527
|
+
t1 = Fp.add(t1, t0);
|
|
1528
|
+
t2 = Fp.mul(a, t2);
|
|
1529
|
+
t4 = Fp.mul(b3, t4);
|
|
1530
|
+
t1 = Fp.add(t1, t2);
|
|
1531
|
+
t2 = Fp.sub(t0, t2);
|
|
1532
|
+
t2 = Fp.mul(a, t2);
|
|
1533
|
+
t4 = Fp.add(t4, t2);
|
|
1534
|
+
t0 = Fp.mul(t1, t4);
|
|
1535
|
+
Y3 = Fp.add(Y3, t0);
|
|
1536
|
+
t0 = Fp.mul(t5, t4);
|
|
1537
|
+
X3 = Fp.mul(t3, X3);
|
|
1538
|
+
X3 = Fp.sub(X3, t0);
|
|
1539
|
+
t0 = Fp.mul(t3, t1);
|
|
1540
|
+
Z3 = Fp.mul(t5, Z3);
|
|
1541
|
+
Z3 = Fp.add(Z3, t0);
|
|
1542
|
+
return new Point2(X3, Y3, Z3);
|
|
1543
|
+
}
|
|
1544
|
+
subtract(other) {
|
|
1545
|
+
return this.add(other.negate());
|
|
1546
|
+
}
|
|
1547
|
+
is0() {
|
|
1548
|
+
return this.equals(Point2.ZERO);
|
|
1549
|
+
}
|
|
1550
|
+
wNAF(n) {
|
|
1551
|
+
return wnaf.wNAFCached(this, n, Point2.normalizeZ);
|
|
1552
|
+
}
|
|
1553
|
+
/**
|
|
1554
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
1555
|
+
* It's faster, but should only be used when you don't care about
|
|
1556
|
+
* an exposed private key e.g. sig verification, which works over *public* keys.
|
|
1557
|
+
*/
|
|
1558
|
+
multiplyUnsafe(sc) {
|
|
1559
|
+
const { endo, n: N2 } = CURVE;
|
|
1560
|
+
aInRange("scalar", sc, _0n4, N2);
|
|
1561
|
+
const I2 = Point2.ZERO;
|
|
1562
|
+
if (sc === _0n4)
|
|
1563
|
+
return I2;
|
|
1564
|
+
if (this.is0() || sc === _1n4)
|
|
1565
|
+
return this;
|
|
1566
|
+
if (!endo || wnaf.hasPrecomputes(this))
|
|
1567
|
+
return wnaf.wNAFCachedUnsafe(this, sc, Point2.normalizeZ);
|
|
1568
|
+
let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);
|
|
1569
|
+
let k1p = I2;
|
|
1570
|
+
let k2p = I2;
|
|
1571
|
+
let d = this;
|
|
1572
|
+
while (k1 > _0n4 || k2 > _0n4) {
|
|
1573
|
+
if (k1 & _1n4)
|
|
1574
|
+
k1p = k1p.add(d);
|
|
1575
|
+
if (k2 & _1n4)
|
|
1576
|
+
k2p = k2p.add(d);
|
|
1577
|
+
d = d.double();
|
|
1578
|
+
k1 >>= _1n4;
|
|
1579
|
+
k2 >>= _1n4;
|
|
1580
|
+
}
|
|
1581
|
+
if (k1neg)
|
|
1582
|
+
k1p = k1p.negate();
|
|
1583
|
+
if (k2neg)
|
|
1584
|
+
k2p = k2p.negate();
|
|
1585
|
+
k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
|
|
1586
|
+
return k1p.add(k2p);
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Constant time multiplication.
|
|
1590
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
1591
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
1592
|
+
* Uses precomputes when available.
|
|
1593
|
+
* Uses endomorphism for Koblitz curves.
|
|
1594
|
+
* @param scalar by which the point would be multiplied
|
|
1595
|
+
* @returns New point
|
|
1596
|
+
*/
|
|
1597
|
+
multiply(scalar) {
|
|
1598
|
+
const { endo, n: N2 } = CURVE;
|
|
1599
|
+
aInRange("scalar", scalar, _1n4, N2);
|
|
1600
|
+
let point, fake;
|
|
1601
|
+
if (endo) {
|
|
1602
|
+
const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);
|
|
1603
|
+
let { p: k1p, f: f1p } = this.wNAF(k1);
|
|
1604
|
+
let { p: k2p, f: f2p } = this.wNAF(k2);
|
|
1605
|
+
k1p = wnaf.constTimeNegate(k1neg, k1p);
|
|
1606
|
+
k2p = wnaf.constTimeNegate(k2neg, k2p);
|
|
1607
|
+
k2p = new Point2(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
|
|
1608
|
+
point = k1p.add(k2p);
|
|
1609
|
+
fake = f1p.add(f2p);
|
|
1610
|
+
} else {
|
|
1611
|
+
const { p, f } = this.wNAF(scalar);
|
|
1612
|
+
point = p;
|
|
1613
|
+
fake = f;
|
|
1614
|
+
}
|
|
1615
|
+
return Point2.normalizeZ([point, fake])[0];
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
|
|
1619
|
+
* Not using Strauss-Shamir trick: precomputation tables are faster.
|
|
1620
|
+
* The trick could be useful if both P and Q are not G (not in our case).
|
|
1621
|
+
* @returns non-zero affine point
|
|
1622
|
+
*/
|
|
1623
|
+
multiplyAndAddUnsafe(Q, a, b) {
|
|
1624
|
+
const G2 = Point2.BASE;
|
|
1625
|
+
const mul = (P2, a2) => a2 === _0n4 || a2 === _1n4 || !P2.equals(G2) ? P2.multiplyUnsafe(a2) : P2.multiply(a2);
|
|
1626
|
+
const sum = mul(this, a).add(mul(Q, b));
|
|
1627
|
+
return sum.is0() ? void 0 : sum;
|
|
1628
|
+
}
|
|
1629
|
+
// Converts Projective point to affine (x, y) coordinates.
|
|
1630
|
+
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
|
1631
|
+
// (x, y, z) ∋ (x=x/z, y=y/z)
|
|
1632
|
+
toAffine(iz) {
|
|
1633
|
+
return toAffineMemo(this, iz);
|
|
1634
|
+
}
|
|
1635
|
+
isTorsionFree() {
|
|
1636
|
+
const { h: cofactor, isTorsionFree } = CURVE;
|
|
1637
|
+
if (cofactor === _1n4)
|
|
1638
|
+
return true;
|
|
1639
|
+
if (isTorsionFree)
|
|
1640
|
+
return isTorsionFree(Point2, this);
|
|
1641
|
+
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
|
|
1642
|
+
}
|
|
1643
|
+
clearCofactor() {
|
|
1644
|
+
const { h: cofactor, clearCofactor } = CURVE;
|
|
1645
|
+
if (cofactor === _1n4)
|
|
1646
|
+
return this;
|
|
1647
|
+
if (clearCofactor)
|
|
1648
|
+
return clearCofactor(Point2, this);
|
|
1649
|
+
return this.multiplyUnsafe(CURVE.h);
|
|
1650
|
+
}
|
|
1651
|
+
toRawBytes(isCompressed = true) {
|
|
1652
|
+
abool("isCompressed", isCompressed);
|
|
1653
|
+
this.assertValidity();
|
|
1654
|
+
return toBytes3(Point2, this, isCompressed);
|
|
1655
|
+
}
|
|
1656
|
+
toHex(isCompressed = true) {
|
|
1657
|
+
abool("isCompressed", isCompressed);
|
|
1658
|
+
return bytesToHex2(this.toRawBytes(isCompressed));
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
1662
|
+
Point2.ZERO = new Point2(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
1663
|
+
const _bits = CURVE.nBitLength;
|
|
1664
|
+
const wnaf = wNAF2(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
|
|
1665
|
+
return {
|
|
1666
|
+
CURVE,
|
|
1667
|
+
ProjectivePoint: Point2,
|
|
1668
|
+
normPrivateKeyToScalar,
|
|
1669
|
+
weierstrassEquation,
|
|
1670
|
+
isWithinCurveOrder
|
|
1671
|
+
};
|
|
1672
|
+
}
|
|
1673
|
+
function validateOpts(curve) {
|
|
1674
|
+
const opts = validateBasic(curve);
|
|
1675
|
+
validateObject(opts, {
|
|
1676
|
+
hash: "hash",
|
|
1677
|
+
hmac: "function",
|
|
1678
|
+
randomBytes: "function"
|
|
1679
|
+
}, {
|
|
1680
|
+
bits2int: "function",
|
|
1681
|
+
bits2int_modN: "function",
|
|
1682
|
+
lowS: "boolean"
|
|
1683
|
+
});
|
|
1684
|
+
return Object.freeze({ lowS: true, ...opts });
|
|
1685
|
+
}
|
|
1686
|
+
function weierstrass(curveDef) {
|
|
1687
|
+
const CURVE = validateOpts(curveDef);
|
|
1688
|
+
const { Fp, n: CURVE_ORDER } = CURVE;
|
|
1689
|
+
const compressedLen = Fp.BYTES + 1;
|
|
1690
|
+
const uncompressedLen = 2 * Fp.BYTES + 1;
|
|
1691
|
+
function modN2(a) {
|
|
1692
|
+
return mod(a, CURVE_ORDER);
|
|
1693
|
+
}
|
|
1694
|
+
function invN(a) {
|
|
1695
|
+
return invert2(a, CURVE_ORDER);
|
|
1696
|
+
}
|
|
1697
|
+
const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
|
|
1698
|
+
...CURVE,
|
|
1699
|
+
toBytes(_c, point, isCompressed) {
|
|
1700
|
+
const a = point.toAffine();
|
|
1701
|
+
const x = Fp.toBytes(a.x);
|
|
1702
|
+
const cat = concatBytes3;
|
|
1703
|
+
abool("isCompressed", isCompressed);
|
|
1704
|
+
if (isCompressed) {
|
|
1705
|
+
return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
|
|
1706
|
+
} else {
|
|
1707
|
+
return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
|
|
1708
|
+
}
|
|
1709
|
+
},
|
|
1710
|
+
fromBytes(bytes) {
|
|
1711
|
+
const len = bytes.length;
|
|
1712
|
+
const head = bytes[0];
|
|
1713
|
+
const tail = bytes.subarray(1);
|
|
1714
|
+
if (len === compressedLen && (head === 2 || head === 3)) {
|
|
1715
|
+
const x = bytesToNumberBE(tail);
|
|
1716
|
+
if (!inRange(x, _1n4, Fp.ORDER))
|
|
1717
|
+
throw new Error("Point is not on curve");
|
|
1718
|
+
const y2 = weierstrassEquation(x);
|
|
1719
|
+
let y;
|
|
1720
|
+
try {
|
|
1721
|
+
y = Fp.sqrt(y2);
|
|
1722
|
+
} catch (sqrtError) {
|
|
1723
|
+
const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
1724
|
+
throw new Error("Point is not on curve" + suffix);
|
|
1725
|
+
}
|
|
1726
|
+
const isYOdd = (y & _1n4) === _1n4;
|
|
1727
|
+
const isHeadOdd = (head & 1) === 1;
|
|
1728
|
+
if (isHeadOdd !== isYOdd)
|
|
1729
|
+
y = Fp.neg(y);
|
|
1730
|
+
return { x, y };
|
|
1731
|
+
} else if (len === uncompressedLen && head === 4) {
|
|
1732
|
+
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
|
|
1733
|
+
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
|
|
1734
|
+
return { x, y };
|
|
1735
|
+
} else {
|
|
1736
|
+
const cl = compressedLen;
|
|
1737
|
+
const ul = uncompressedLen;
|
|
1738
|
+
throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
});
|
|
1742
|
+
const numToNByteStr = (num) => bytesToHex2(numberToBytesBE(num, CURVE.nByteLength));
|
|
1743
|
+
function isBiggerThanHalfOrder(number) {
|
|
1744
|
+
const HALF = CURVE_ORDER >> _1n4;
|
|
1745
|
+
return number > HALF;
|
|
1746
|
+
}
|
|
1747
|
+
function normalizeS(s) {
|
|
1748
|
+
return isBiggerThanHalfOrder(s) ? modN2(-s) : s;
|
|
1749
|
+
}
|
|
1750
|
+
const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
|
|
1751
|
+
class Signature {
|
|
1752
|
+
constructor(r, s, recovery) {
|
|
1753
|
+
this.r = r;
|
|
1754
|
+
this.s = s;
|
|
1755
|
+
this.recovery = recovery;
|
|
1756
|
+
this.assertValidity();
|
|
1757
|
+
}
|
|
1758
|
+
// pair (bytes of r, bytes of s)
|
|
1759
|
+
static fromCompact(hex) {
|
|
1760
|
+
const l = CURVE.nByteLength;
|
|
1761
|
+
hex = ensureBytes("compactSignature", hex, l * 2);
|
|
1762
|
+
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
|
|
1763
|
+
}
|
|
1764
|
+
// DER encoded ECDSA signature
|
|
1765
|
+
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
|
|
1766
|
+
static fromDER(hex) {
|
|
1767
|
+
const { r, s } = DER.toSig(ensureBytes("DER", hex));
|
|
1768
|
+
return new Signature(r, s);
|
|
1769
|
+
}
|
|
1770
|
+
assertValidity() {
|
|
1771
|
+
aInRange("r", this.r, _1n4, CURVE_ORDER);
|
|
1772
|
+
aInRange("s", this.s, _1n4, CURVE_ORDER);
|
|
1773
|
+
}
|
|
1774
|
+
addRecoveryBit(recovery) {
|
|
1775
|
+
return new Signature(this.r, this.s, recovery);
|
|
1776
|
+
}
|
|
1777
|
+
recoverPublicKey(msgHash) {
|
|
1778
|
+
const { r, s, recovery: rec } = this;
|
|
1779
|
+
const h2 = bits2int_modN(ensureBytes("msgHash", msgHash));
|
|
1780
|
+
if (rec == null || ![0, 1, 2, 3].includes(rec))
|
|
1781
|
+
throw new Error("recovery id invalid");
|
|
1782
|
+
const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
|
|
1783
|
+
if (radj >= Fp.ORDER)
|
|
1784
|
+
throw new Error("recovery id 2 or 3 invalid");
|
|
1785
|
+
const prefix = (rec & 1) === 0 ? "02" : "03";
|
|
1786
|
+
const R = Point2.fromHex(prefix + numToNByteStr(radj));
|
|
1787
|
+
const ir = invN(radj);
|
|
1788
|
+
const u1 = modN2(-h2 * ir);
|
|
1789
|
+
const u2 = modN2(s * ir);
|
|
1790
|
+
const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2);
|
|
1791
|
+
if (!Q)
|
|
1792
|
+
throw new Error("point at infinify");
|
|
1793
|
+
Q.assertValidity();
|
|
1794
|
+
return Q;
|
|
1795
|
+
}
|
|
1796
|
+
// Signatures should be low-s, to prevent malleability.
|
|
1797
|
+
hasHighS() {
|
|
1798
|
+
return isBiggerThanHalfOrder(this.s);
|
|
1799
|
+
}
|
|
1800
|
+
normalizeS() {
|
|
1801
|
+
return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this;
|
|
1802
|
+
}
|
|
1803
|
+
// DER-encoded
|
|
1804
|
+
toDERRawBytes() {
|
|
1805
|
+
return hexToBytes2(this.toDERHex());
|
|
1806
|
+
}
|
|
1807
|
+
toDERHex() {
|
|
1808
|
+
return DER.hexFromSig({ r: this.r, s: this.s });
|
|
1809
|
+
}
|
|
1810
|
+
// padded bytes of r, then padded bytes of s
|
|
1811
|
+
toCompactRawBytes() {
|
|
1812
|
+
return hexToBytes2(this.toCompactHex());
|
|
1813
|
+
}
|
|
1814
|
+
toCompactHex() {
|
|
1815
|
+
return numToNByteStr(this.r) + numToNByteStr(this.s);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
const utils = {
|
|
1819
|
+
isValidPrivateKey(privateKey) {
|
|
1820
|
+
try {
|
|
1821
|
+
normPrivateKeyToScalar(privateKey);
|
|
1822
|
+
return true;
|
|
1823
|
+
} catch (error) {
|
|
1824
|
+
return false;
|
|
1825
|
+
}
|
|
1826
|
+
},
|
|
1827
|
+
normPrivateKeyToScalar,
|
|
1828
|
+
/**
|
|
1829
|
+
* Produces cryptographically secure private key from random of size
|
|
1830
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
1831
|
+
*/
|
|
1832
|
+
randomPrivateKey: () => {
|
|
1833
|
+
const length = getMinHashLength(CURVE.n);
|
|
1834
|
+
return mapHashToField(CURVE.randomBytes(length), CURVE.n);
|
|
1835
|
+
},
|
|
1836
|
+
/**
|
|
1837
|
+
* Creates precompute table for an arbitrary EC point. Makes point "cached".
|
|
1838
|
+
* Allows to massively speed-up `point.multiply(scalar)`.
|
|
1839
|
+
* @returns cached point
|
|
1840
|
+
* @example
|
|
1841
|
+
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
|
|
1842
|
+
* fast.multiply(privKey); // much faster ECDH now
|
|
1843
|
+
*/
|
|
1844
|
+
precompute(windowSize = 8, point = Point2.BASE) {
|
|
1845
|
+
point._setWindowSize(windowSize);
|
|
1846
|
+
point.multiply(BigInt(3));
|
|
1847
|
+
return point;
|
|
1848
|
+
}
|
|
1849
|
+
};
|
|
1850
|
+
function getPublicKey(privateKey, isCompressed = true) {
|
|
1851
|
+
return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed);
|
|
1852
|
+
}
|
|
1853
|
+
function isProbPub(item) {
|
|
1854
|
+
const arr = isBytes4(item);
|
|
1855
|
+
const str = typeof item === "string";
|
|
1856
|
+
const len = (arr || str) && item.length;
|
|
1857
|
+
if (arr)
|
|
1858
|
+
return len === compressedLen || len === uncompressedLen;
|
|
1859
|
+
if (str)
|
|
1860
|
+
return len === 2 * compressedLen || len === 2 * uncompressedLen;
|
|
1861
|
+
if (item instanceof Point2)
|
|
1862
|
+
return true;
|
|
1863
|
+
return false;
|
|
1864
|
+
}
|
|
1865
|
+
function getSharedSecret(privateA, publicB, isCompressed = true) {
|
|
1866
|
+
if (isProbPub(privateA))
|
|
1867
|
+
throw new Error("first arg must be private key");
|
|
1868
|
+
if (!isProbPub(publicB))
|
|
1869
|
+
throw new Error("second arg must be public key");
|
|
1870
|
+
const b = Point2.fromHex(publicB);
|
|
1871
|
+
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
|
|
1872
|
+
}
|
|
1873
|
+
const bits2int = CURVE.bits2int || function(bytes) {
|
|
1874
|
+
if (bytes.length > 8192)
|
|
1875
|
+
throw new Error("input is too large");
|
|
1876
|
+
const num = bytesToNumberBE(bytes);
|
|
1877
|
+
const delta = bytes.length * 8 - CURVE.nBitLength;
|
|
1878
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
1879
|
+
};
|
|
1880
|
+
const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
|
|
1881
|
+
return modN2(bits2int(bytes));
|
|
1882
|
+
};
|
|
1883
|
+
const ORDER_MASK = bitMask(CURVE.nBitLength);
|
|
1884
|
+
function int2octets(num) {
|
|
1885
|
+
aInRange("num < 2^" + CURVE.nBitLength, num, _0n4, ORDER_MASK);
|
|
1886
|
+
return numberToBytesBE(num, CURVE.nByteLength);
|
|
1887
|
+
}
|
|
1888
|
+
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
|
|
1889
|
+
if (["recovered", "canonical"].some((k) => k in opts))
|
|
1890
|
+
throw new Error("sign() legacy options not supported");
|
|
1891
|
+
const { hash: hash2, randomBytes: randomBytes3 } = CURVE;
|
|
1892
|
+
let { lowS, prehash, extraEntropy: ent } = opts;
|
|
1893
|
+
if (lowS == null)
|
|
1894
|
+
lowS = true;
|
|
1895
|
+
msgHash = ensureBytes("msgHash", msgHash);
|
|
1896
|
+
validateSigVerOpts(opts);
|
|
1897
|
+
if (prehash)
|
|
1898
|
+
msgHash = ensureBytes("prehashed msgHash", hash2(msgHash));
|
|
1899
|
+
const h1int = bits2int_modN(msgHash);
|
|
1900
|
+
const d = normPrivateKeyToScalar(privateKey);
|
|
1901
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
1902
|
+
if (ent != null && ent !== false) {
|
|
1903
|
+
const e = ent === true ? randomBytes3(Fp.BYTES) : ent;
|
|
1904
|
+
seedArgs.push(ensureBytes("extraEntropy", e));
|
|
1905
|
+
}
|
|
1906
|
+
const seed = concatBytes3(...seedArgs);
|
|
1907
|
+
const m = h1int;
|
|
1908
|
+
function k2sig(kBytes) {
|
|
1909
|
+
const k = bits2int(kBytes);
|
|
1910
|
+
if (!isWithinCurveOrder(k))
|
|
1911
|
+
return;
|
|
1912
|
+
const ik = invN(k);
|
|
1913
|
+
const q = Point2.BASE.multiply(k).toAffine();
|
|
1914
|
+
const r = modN2(q.x);
|
|
1915
|
+
if (r === _0n4)
|
|
1916
|
+
return;
|
|
1917
|
+
const s = modN2(ik * modN2(m + r * d));
|
|
1918
|
+
if (s === _0n4)
|
|
1919
|
+
return;
|
|
1920
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
1921
|
+
let normS = s;
|
|
1922
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
1923
|
+
normS = normalizeS(s);
|
|
1924
|
+
recovery ^= 1;
|
|
1925
|
+
}
|
|
1926
|
+
return new Signature(r, normS, recovery);
|
|
1927
|
+
}
|
|
1928
|
+
return { seed, k2sig };
|
|
1929
|
+
}
|
|
1930
|
+
const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
|
|
1931
|
+
const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
|
|
1932
|
+
function sign(msgHash, privKey, opts = defaultSigOpts) {
|
|
1933
|
+
const { seed, k2sig } = prepSig(msgHash, privKey, opts);
|
|
1934
|
+
const C2 = CURVE;
|
|
1935
|
+
const drbg = createHmacDrbg(C2.hash.outputLen, C2.nByteLength, C2.hmac);
|
|
1936
|
+
return drbg(seed, k2sig);
|
|
1937
|
+
}
|
|
1938
|
+
Point2.BASE._setWindowSize(8);
|
|
1939
|
+
function verify2(signature, msgHash, publicKey, opts = defaultVerOpts) {
|
|
1940
|
+
const sg = signature;
|
|
1941
|
+
msgHash = ensureBytes("msgHash", msgHash);
|
|
1942
|
+
publicKey = ensureBytes("publicKey", publicKey);
|
|
1943
|
+
const { lowS, prehash, format } = opts;
|
|
1944
|
+
validateSigVerOpts(opts);
|
|
1945
|
+
if ("strict" in opts)
|
|
1946
|
+
throw new Error("options.strict was renamed to lowS");
|
|
1947
|
+
if (format !== void 0 && format !== "compact" && format !== "der")
|
|
1948
|
+
throw new Error("format must be compact or der");
|
|
1949
|
+
const isHex = typeof sg === "string" || isBytes4(sg);
|
|
1950
|
+
const isObj = !isHex && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
|
|
1951
|
+
if (!isHex && !isObj)
|
|
1952
|
+
throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
|
|
1953
|
+
let _sig = void 0;
|
|
1954
|
+
let P2;
|
|
1955
|
+
try {
|
|
1956
|
+
if (isObj)
|
|
1957
|
+
_sig = new Signature(sg.r, sg.s);
|
|
1958
|
+
if (isHex) {
|
|
1959
|
+
try {
|
|
1960
|
+
if (format !== "compact")
|
|
1961
|
+
_sig = Signature.fromDER(sg);
|
|
1962
|
+
} catch (derError) {
|
|
1963
|
+
if (!(derError instanceof DER.Err))
|
|
1964
|
+
throw derError;
|
|
1965
|
+
}
|
|
1966
|
+
if (!_sig && format !== "der")
|
|
1967
|
+
_sig = Signature.fromCompact(sg);
|
|
1968
|
+
}
|
|
1969
|
+
P2 = Point2.fromHex(publicKey);
|
|
1970
|
+
} catch (error) {
|
|
1971
|
+
return false;
|
|
1972
|
+
}
|
|
1973
|
+
if (!_sig)
|
|
1974
|
+
return false;
|
|
1975
|
+
if (lowS && _sig.hasHighS())
|
|
1976
|
+
return false;
|
|
1977
|
+
if (prehash)
|
|
1978
|
+
msgHash = CURVE.hash(msgHash);
|
|
1979
|
+
const { r, s } = _sig;
|
|
1980
|
+
const h2 = bits2int_modN(msgHash);
|
|
1981
|
+
const is = invN(s);
|
|
1982
|
+
const u1 = modN2(h2 * is);
|
|
1983
|
+
const u2 = modN2(r * is);
|
|
1984
|
+
const R = Point2.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine();
|
|
1985
|
+
if (!R)
|
|
1986
|
+
return false;
|
|
1987
|
+
const v = modN2(R.x);
|
|
1988
|
+
return v === r;
|
|
1989
|
+
}
|
|
1990
|
+
return {
|
|
1991
|
+
CURVE,
|
|
1992
|
+
getPublicKey,
|
|
1993
|
+
getSharedSecret,
|
|
1994
|
+
sign,
|
|
1995
|
+
verify: verify2,
|
|
1996
|
+
ProjectivePoint: Point2,
|
|
1997
|
+
Signature,
|
|
1998
|
+
utils
|
|
1999
|
+
};
|
|
2000
|
+
}
|
|
2001
|
+
function SWUFpSqrtRatio(Fp, Z) {
|
|
2002
|
+
const q = Fp.ORDER;
|
|
2003
|
+
let l = _0n4;
|
|
2004
|
+
for (let o = q - _1n4; o % _2n3 === _0n4; o /= _2n3)
|
|
2005
|
+
l += _1n4;
|
|
2006
|
+
const c1 = l;
|
|
2007
|
+
const _2n_pow_c1_1 = _2n3 << c1 - _1n4 - _1n4;
|
|
2008
|
+
const _2n_pow_c1 = _2n_pow_c1_1 * _2n3;
|
|
2009
|
+
const c2 = (q - _1n4) / _2n_pow_c1;
|
|
2010
|
+
const c3 = (c2 - _1n4) / _2n3;
|
|
2011
|
+
const c4 = _2n_pow_c1 - _1n4;
|
|
2012
|
+
const c5 = _2n_pow_c1_1;
|
|
2013
|
+
const c6 = Fp.pow(Z, c2);
|
|
2014
|
+
const c7 = Fp.pow(Z, (c2 + _1n4) / _2n3);
|
|
2015
|
+
let sqrtRatio = (u, v) => {
|
|
2016
|
+
let tv1 = c6;
|
|
2017
|
+
let tv2 = Fp.pow(v, c4);
|
|
2018
|
+
let tv3 = Fp.sqr(tv2);
|
|
2019
|
+
tv3 = Fp.mul(tv3, v);
|
|
2020
|
+
let tv5 = Fp.mul(u, tv3);
|
|
2021
|
+
tv5 = Fp.pow(tv5, c3);
|
|
2022
|
+
tv5 = Fp.mul(tv5, tv2);
|
|
2023
|
+
tv2 = Fp.mul(tv5, v);
|
|
2024
|
+
tv3 = Fp.mul(tv5, u);
|
|
2025
|
+
let tv4 = Fp.mul(tv3, tv2);
|
|
2026
|
+
tv5 = Fp.pow(tv4, c5);
|
|
2027
|
+
let isQR = Fp.eql(tv5, Fp.ONE);
|
|
2028
|
+
tv2 = Fp.mul(tv3, c7);
|
|
2029
|
+
tv5 = Fp.mul(tv4, tv1);
|
|
2030
|
+
tv3 = Fp.cmov(tv2, tv3, isQR);
|
|
2031
|
+
tv4 = Fp.cmov(tv5, tv4, isQR);
|
|
2032
|
+
for (let i = c1; i > _1n4; i--) {
|
|
2033
|
+
let tv52 = i - _2n3;
|
|
2034
|
+
tv52 = _2n3 << tv52 - _1n4;
|
|
2035
|
+
let tvv5 = Fp.pow(tv4, tv52);
|
|
2036
|
+
const e1 = Fp.eql(tvv5, Fp.ONE);
|
|
2037
|
+
tv2 = Fp.mul(tv3, tv1);
|
|
2038
|
+
tv1 = Fp.mul(tv1, tv1);
|
|
2039
|
+
tvv5 = Fp.mul(tv4, tv1);
|
|
2040
|
+
tv3 = Fp.cmov(tv2, tv3, e1);
|
|
2041
|
+
tv4 = Fp.cmov(tvv5, tv4, e1);
|
|
2042
|
+
}
|
|
2043
|
+
return { isValid: isQR, value: tv3 };
|
|
2044
|
+
};
|
|
2045
|
+
if (Fp.ORDER % _4n2 === _3n2) {
|
|
2046
|
+
const c12 = (Fp.ORDER - _3n2) / _4n2;
|
|
2047
|
+
const c22 = Fp.sqrt(Fp.neg(Z));
|
|
2048
|
+
sqrtRatio = (u, v) => {
|
|
2049
|
+
let tv1 = Fp.sqr(v);
|
|
2050
|
+
const tv2 = Fp.mul(u, v);
|
|
2051
|
+
tv1 = Fp.mul(tv1, tv2);
|
|
2052
|
+
let y1 = Fp.pow(tv1, c12);
|
|
2053
|
+
y1 = Fp.mul(y1, tv2);
|
|
2054
|
+
const y2 = Fp.mul(y1, c22);
|
|
2055
|
+
const tv3 = Fp.mul(Fp.sqr(y1), v);
|
|
2056
|
+
const isQR = Fp.eql(tv3, u);
|
|
2057
|
+
let y = Fp.cmov(y2, y1, isQR);
|
|
2058
|
+
return { isValid: isQR, value: y };
|
|
2059
|
+
};
|
|
2060
|
+
}
|
|
2061
|
+
return sqrtRatio;
|
|
2062
|
+
}
|
|
2063
|
+
function mapToCurveSimpleSWU(Fp, opts) {
|
|
2064
|
+
validateField(Fp);
|
|
2065
|
+
if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
|
|
2066
|
+
throw new Error("mapToCurveSimpleSWU: invalid opts");
|
|
2067
|
+
const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
|
|
2068
|
+
if (!Fp.isOdd)
|
|
2069
|
+
throw new Error("Fp.isOdd is not implemented!");
|
|
2070
|
+
return (u) => {
|
|
2071
|
+
let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
|
|
2072
|
+
tv1 = Fp.sqr(u);
|
|
2073
|
+
tv1 = Fp.mul(tv1, opts.Z);
|
|
2074
|
+
tv2 = Fp.sqr(tv1);
|
|
2075
|
+
tv2 = Fp.add(tv2, tv1);
|
|
2076
|
+
tv3 = Fp.add(tv2, Fp.ONE);
|
|
2077
|
+
tv3 = Fp.mul(tv3, opts.B);
|
|
2078
|
+
tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
|
|
2079
|
+
tv4 = Fp.mul(tv4, opts.A);
|
|
2080
|
+
tv2 = Fp.sqr(tv3);
|
|
2081
|
+
tv6 = Fp.sqr(tv4);
|
|
2082
|
+
tv5 = Fp.mul(tv6, opts.A);
|
|
2083
|
+
tv2 = Fp.add(tv2, tv5);
|
|
2084
|
+
tv2 = Fp.mul(tv2, tv3);
|
|
2085
|
+
tv6 = Fp.mul(tv6, tv4);
|
|
2086
|
+
tv5 = Fp.mul(tv6, opts.B);
|
|
2087
|
+
tv2 = Fp.add(tv2, tv5);
|
|
2088
|
+
x = Fp.mul(tv1, tv3);
|
|
2089
|
+
const { isValid, value } = sqrtRatio(tv2, tv6);
|
|
2090
|
+
y = Fp.mul(tv1, u);
|
|
2091
|
+
y = Fp.mul(y, value);
|
|
2092
|
+
x = Fp.cmov(x, tv3, isValid);
|
|
2093
|
+
y = Fp.cmov(y, value, isValid);
|
|
2094
|
+
const e1 = Fp.isOdd(u) === Fp.isOdd(y);
|
|
2095
|
+
y = Fp.cmov(Fp.neg(y), y, e1);
|
|
2096
|
+
x = Fp.div(x, tv4);
|
|
2097
|
+
return { x, y };
|
|
2098
|
+
};
|
|
2099
|
+
}
|
|
2100
|
+
var b2n, h2b, DER, _0n4, _1n4, _2n3, _3n2, _4n2;
|
|
2101
|
+
var init_weierstrass = __esm({
|
|
2102
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/weierstrass.js"() {
|
|
2103
|
+
"use strict";
|
|
2104
|
+
init_curve();
|
|
2105
|
+
init_modular();
|
|
2106
|
+
init_utils2();
|
|
2107
|
+
init_utils2();
|
|
2108
|
+
({ bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports);
|
|
2109
|
+
DER = {
|
|
2110
|
+
// asn.1 DER encoding utils
|
|
2111
|
+
Err: class DERErr extends Error {
|
|
2112
|
+
constructor(m = "") {
|
|
2113
|
+
super(m);
|
|
2114
|
+
}
|
|
2115
|
+
},
|
|
2116
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
2117
|
+
_tlv: {
|
|
2118
|
+
encode: (tag, data) => {
|
|
2119
|
+
const { Err: E } = DER;
|
|
2120
|
+
if (tag < 0 || tag > 256)
|
|
2121
|
+
throw new E("tlv.encode: wrong tag");
|
|
2122
|
+
if (data.length & 1)
|
|
2123
|
+
throw new E("tlv.encode: unpadded data");
|
|
2124
|
+
const dataLen = data.length / 2;
|
|
2125
|
+
const len = numberToHexUnpadded(dataLen);
|
|
2126
|
+
if (len.length / 2 & 128)
|
|
2127
|
+
throw new E("tlv.encode: long form length too big");
|
|
2128
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
2129
|
+
const t = numberToHexUnpadded(tag);
|
|
2130
|
+
return t + lenLen + len + data;
|
|
2131
|
+
},
|
|
2132
|
+
// v - value, l - left bytes (unparsed)
|
|
2133
|
+
decode(tag, data) {
|
|
2134
|
+
const { Err: E } = DER;
|
|
2135
|
+
let pos = 0;
|
|
2136
|
+
if (tag < 0 || tag > 256)
|
|
2137
|
+
throw new E("tlv.encode: wrong tag");
|
|
2138
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
2139
|
+
throw new E("tlv.decode: wrong tlv");
|
|
2140
|
+
const first = data[pos++];
|
|
2141
|
+
const isLong = !!(first & 128);
|
|
2142
|
+
let length = 0;
|
|
2143
|
+
if (!isLong)
|
|
2144
|
+
length = first;
|
|
2145
|
+
else {
|
|
2146
|
+
const lenLen = first & 127;
|
|
2147
|
+
if (!lenLen)
|
|
2148
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
2149
|
+
if (lenLen > 4)
|
|
2150
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
2151
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
2152
|
+
if (lengthBytes.length !== lenLen)
|
|
2153
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
2154
|
+
if (lengthBytes[0] === 0)
|
|
2155
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
2156
|
+
for (const b of lengthBytes)
|
|
2157
|
+
length = length << 8 | b;
|
|
2158
|
+
pos += lenLen;
|
|
2159
|
+
if (length < 128)
|
|
2160
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
2161
|
+
}
|
|
2162
|
+
const v = data.subarray(pos, pos + length);
|
|
2163
|
+
if (v.length !== length)
|
|
2164
|
+
throw new E("tlv.decode: wrong value length");
|
|
2165
|
+
return { v, l: data.subarray(pos + length) };
|
|
2166
|
+
}
|
|
2167
|
+
},
|
|
2168
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
2169
|
+
// since we always use positive integers here. It must always be empty:
|
|
2170
|
+
// - add zero byte if exists
|
|
2171
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
2172
|
+
_int: {
|
|
2173
|
+
encode(num) {
|
|
2174
|
+
const { Err: E } = DER;
|
|
2175
|
+
if (num < _0n4)
|
|
2176
|
+
throw new E("integer: negative integers are not allowed");
|
|
2177
|
+
let hex = numberToHexUnpadded(num);
|
|
2178
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
2179
|
+
hex = "00" + hex;
|
|
2180
|
+
if (hex.length & 1)
|
|
2181
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
2182
|
+
return hex;
|
|
2183
|
+
},
|
|
2184
|
+
decode(data) {
|
|
2185
|
+
const { Err: E } = DER;
|
|
2186
|
+
if (data[0] & 128)
|
|
2187
|
+
throw new E("invalid signature integer: negative");
|
|
2188
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
2189
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
2190
|
+
return b2n(data);
|
|
2191
|
+
}
|
|
2192
|
+
},
|
|
2193
|
+
toSig(hex) {
|
|
2194
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
2195
|
+
const data = typeof hex === "string" ? h2b(hex) : hex;
|
|
2196
|
+
abytes4(data);
|
|
2197
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
2198
|
+
if (seqLeftBytes.length)
|
|
2199
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
2200
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
2201
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
2202
|
+
if (sLeftBytes.length)
|
|
2203
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
2204
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
2205
|
+
},
|
|
2206
|
+
hexFromSig(sig) {
|
|
2207
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
2208
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
2209
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
2210
|
+
const seq = rs + ss;
|
|
2211
|
+
return tlv.encode(48, seq);
|
|
2212
|
+
}
|
|
2213
|
+
};
|
|
2214
|
+
_0n4 = BigInt(0);
|
|
2215
|
+
_1n4 = BigInt(1);
|
|
2216
|
+
_2n3 = BigInt(2);
|
|
2217
|
+
_3n2 = BigInt(3);
|
|
2218
|
+
_4n2 = BigInt(4);
|
|
2219
|
+
}
|
|
2220
|
+
});
|
|
2221
|
+
|
|
2222
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/_shortw_utils.js
|
|
2223
|
+
function getHash(hash2) {
|
|
2224
|
+
return {
|
|
2225
|
+
hash: hash2,
|
|
2226
|
+
hmac: (key, ...msgs) => hmac(hash2, key, concatBytes2(...msgs)),
|
|
2227
|
+
randomBytes: randomBytes2
|
|
2228
|
+
};
|
|
2229
|
+
}
|
|
2230
|
+
function createCurve(curveDef, defHash) {
|
|
2231
|
+
const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) });
|
|
2232
|
+
return Object.freeze({ ...create(defHash), create });
|
|
2233
|
+
}
|
|
2234
|
+
var init_shortw_utils = __esm({
|
|
2235
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/_shortw_utils.js"() {
|
|
2236
|
+
"use strict";
|
|
2237
|
+
init_hmac();
|
|
2238
|
+
init_utils();
|
|
2239
|
+
init_weierstrass();
|
|
2240
|
+
}
|
|
2241
|
+
});
|
|
2242
|
+
|
|
2243
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/hash-to-curve.js
|
|
2244
|
+
function i2osp(value, length) {
|
|
2245
|
+
anum(value);
|
|
2246
|
+
anum(length);
|
|
2247
|
+
if (value < 0 || value >= 1 << 8 * length)
|
|
2248
|
+
throw new Error("invalid I2OSP input: " + value);
|
|
2249
|
+
const res = Array.from({ length }).fill(0);
|
|
2250
|
+
for (let i = length - 1; i >= 0; i--) {
|
|
2251
|
+
res[i] = value & 255;
|
|
2252
|
+
value >>>= 8;
|
|
2253
|
+
}
|
|
2254
|
+
return new Uint8Array(res);
|
|
2255
|
+
}
|
|
2256
|
+
function strxor(a, b) {
|
|
2257
|
+
const arr = new Uint8Array(a.length);
|
|
2258
|
+
for (let i = 0; i < a.length; i++) {
|
|
2259
|
+
arr[i] = a[i] ^ b[i];
|
|
2260
|
+
}
|
|
2261
|
+
return arr;
|
|
2262
|
+
}
|
|
2263
|
+
function anum(item) {
|
|
2264
|
+
if (!Number.isSafeInteger(item))
|
|
2265
|
+
throw new Error("number expected");
|
|
2266
|
+
}
|
|
2267
|
+
function expand_message_xmd(msg, DST, lenInBytes, H) {
|
|
2268
|
+
abytes4(msg);
|
|
2269
|
+
abytes4(DST);
|
|
2270
|
+
anum(lenInBytes);
|
|
2271
|
+
if (DST.length > 255)
|
|
2272
|
+
DST = H(concatBytes3(utf8ToBytes3("H2C-OVERSIZE-DST-"), DST));
|
|
2273
|
+
const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
|
|
2274
|
+
const ell = Math.ceil(lenInBytes / b_in_bytes);
|
|
2275
|
+
if (lenInBytes > 65535 || ell > 255)
|
|
2276
|
+
throw new Error("expand_message_xmd: invalid lenInBytes");
|
|
2277
|
+
const DST_prime = concatBytes3(DST, i2osp(DST.length, 1));
|
|
2278
|
+
const Z_pad = i2osp(0, r_in_bytes);
|
|
2279
|
+
const l_i_b_str = i2osp(lenInBytes, 2);
|
|
2280
|
+
const b = new Array(ell);
|
|
2281
|
+
const b_0 = H(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
|
|
2282
|
+
b[0] = H(concatBytes3(b_0, i2osp(1, 1), DST_prime));
|
|
2283
|
+
for (let i = 1; i <= ell; i++) {
|
|
2284
|
+
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
|
|
2285
|
+
b[i] = H(concatBytes3(...args));
|
|
2286
|
+
}
|
|
2287
|
+
const pseudo_random_bytes = concatBytes3(...b);
|
|
2288
|
+
return pseudo_random_bytes.slice(0, lenInBytes);
|
|
2289
|
+
}
|
|
2290
|
+
function expand_message_xof(msg, DST, lenInBytes, k, H) {
|
|
2291
|
+
abytes4(msg);
|
|
2292
|
+
abytes4(DST);
|
|
2293
|
+
anum(lenInBytes);
|
|
2294
|
+
if (DST.length > 255) {
|
|
2295
|
+
const dkLen = Math.ceil(2 * k / 8);
|
|
2296
|
+
DST = H.create({ dkLen }).update(utf8ToBytes3("H2C-OVERSIZE-DST-")).update(DST).digest();
|
|
2297
|
+
}
|
|
2298
|
+
if (lenInBytes > 65535 || DST.length > 255)
|
|
2299
|
+
throw new Error("expand_message_xof: invalid lenInBytes");
|
|
2300
|
+
return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
|
|
2301
|
+
}
|
|
2302
|
+
function hash_to_field(msg, count, options) {
|
|
2303
|
+
validateObject(options, {
|
|
2304
|
+
DST: "stringOrUint8Array",
|
|
2305
|
+
p: "bigint",
|
|
2306
|
+
m: "isSafeInteger",
|
|
2307
|
+
k: "isSafeInteger",
|
|
2308
|
+
hash: "hash"
|
|
2309
|
+
});
|
|
2310
|
+
const { p, k, m, hash: hash2, expand, DST: _DST } = options;
|
|
2311
|
+
abytes4(msg);
|
|
2312
|
+
anum(count);
|
|
2313
|
+
const DST = typeof _DST === "string" ? utf8ToBytes3(_DST) : _DST;
|
|
2314
|
+
const log2p = p.toString(2).length;
|
|
2315
|
+
const L2 = Math.ceil((log2p + k) / 8);
|
|
2316
|
+
const len_in_bytes = count * m * L2;
|
|
2317
|
+
let prb;
|
|
2318
|
+
if (expand === "xmd") {
|
|
2319
|
+
prb = expand_message_xmd(msg, DST, len_in_bytes, hash2);
|
|
2320
|
+
} else if (expand === "xof") {
|
|
2321
|
+
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2);
|
|
2322
|
+
} else if (expand === "_internal_pass") {
|
|
2323
|
+
prb = msg;
|
|
2324
|
+
} else {
|
|
2325
|
+
throw new Error('expand must be "xmd" or "xof"');
|
|
2326
|
+
}
|
|
2327
|
+
const u = new Array(count);
|
|
2328
|
+
for (let i = 0; i < count; i++) {
|
|
2329
|
+
const e = new Array(m);
|
|
2330
|
+
for (let j = 0; j < m; j++) {
|
|
2331
|
+
const elm_offset = L2 * (j + i * m);
|
|
2332
|
+
const tv = prb.subarray(elm_offset, elm_offset + L2);
|
|
2333
|
+
e[j] = mod(os2ip(tv), p);
|
|
2334
|
+
}
|
|
2335
|
+
u[i] = e;
|
|
2336
|
+
}
|
|
2337
|
+
return u;
|
|
2338
|
+
}
|
|
2339
|
+
function createHasher(Point2, mapToCurve, def) {
|
|
2340
|
+
if (typeof mapToCurve !== "function")
|
|
2341
|
+
throw new Error("mapToCurve() must be defined");
|
|
2342
|
+
return {
|
|
2343
|
+
// Encodes byte string to elliptic curve.
|
|
2344
|
+
// hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
|
|
2345
|
+
hashToCurve(msg, options) {
|
|
2346
|
+
const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });
|
|
2347
|
+
const u0 = Point2.fromAffine(mapToCurve(u[0]));
|
|
2348
|
+
const u1 = Point2.fromAffine(mapToCurve(u[1]));
|
|
2349
|
+
const P2 = u0.add(u1).clearCofactor();
|
|
2350
|
+
P2.assertValidity();
|
|
2351
|
+
return P2;
|
|
2352
|
+
},
|
|
2353
|
+
// Encodes byte string to elliptic curve.
|
|
2354
|
+
// encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
|
|
2355
|
+
encodeToCurve(msg, options) {
|
|
2356
|
+
const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });
|
|
2357
|
+
const P2 = Point2.fromAffine(mapToCurve(u[0])).clearCofactor();
|
|
2358
|
+
P2.assertValidity();
|
|
2359
|
+
return P2;
|
|
2360
|
+
},
|
|
2361
|
+
// Same as encodeToCurve, but without hash
|
|
2362
|
+
mapToCurve(scalars) {
|
|
2363
|
+
if (!Array.isArray(scalars))
|
|
2364
|
+
throw new Error("mapToCurve: expected array of bigints");
|
|
2365
|
+
for (const i of scalars)
|
|
2366
|
+
if (typeof i !== "bigint")
|
|
2367
|
+
throw new Error("mapToCurve: expected array of bigints");
|
|
2368
|
+
const P2 = Point2.fromAffine(mapToCurve(scalars)).clearCofactor();
|
|
2369
|
+
P2.assertValidity();
|
|
2370
|
+
return P2;
|
|
2371
|
+
}
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
var os2ip;
|
|
2375
|
+
var init_hash_to_curve = __esm({
|
|
2376
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() {
|
|
2377
|
+
"use strict";
|
|
2378
|
+
init_modular();
|
|
2379
|
+
init_utils2();
|
|
2380
|
+
os2ip = bytesToNumberBE;
|
|
2381
|
+
}
|
|
2382
|
+
});
|
|
2383
|
+
|
|
2384
|
+
// ../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/p256.js
|
|
2385
|
+
var p256_exports = {};
|
|
2386
|
+
__export(p256_exports, {
|
|
2387
|
+
encodeToCurve: () => encodeToCurve,
|
|
2388
|
+
hashToCurve: () => hashToCurve,
|
|
2389
|
+
p256: () => p256,
|
|
2390
|
+
secp256r1: () => secp256r1
|
|
2391
|
+
});
|
|
2392
|
+
var Fp256, CURVE_A, CURVE_B, p256, secp256r1, mapSWU, htf, hashToCurve, encodeToCurve;
|
|
2393
|
+
var init_p256 = __esm({
|
|
2394
|
+
"../../node_modules/.pnpm/@noble+curves@1.7.0/node_modules/@noble/curves/esm/p256.js"() {
|
|
2395
|
+
"use strict";
|
|
2396
|
+
init_sha256();
|
|
2397
|
+
init_shortw_utils();
|
|
2398
|
+
init_hash_to_curve();
|
|
2399
|
+
init_modular();
|
|
2400
|
+
init_weierstrass();
|
|
2401
|
+
Fp256 = Field(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"));
|
|
2402
|
+
CURVE_A = Fp256.create(BigInt("-3"));
|
|
2403
|
+
CURVE_B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");
|
|
2404
|
+
p256 = createCurve({
|
|
2405
|
+
a: CURVE_A,
|
|
2406
|
+
// Equation params: a, b
|
|
2407
|
+
b: CURVE_B,
|
|
2408
|
+
Fp: Fp256,
|
|
2409
|
+
// Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n
|
|
2410
|
+
// Curve order, total count of valid points in the field
|
|
2411
|
+
n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
|
|
2412
|
+
// Base (generator) point (x, y)
|
|
2413
|
+
Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
|
|
2414
|
+
Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),
|
|
2415
|
+
h: BigInt(1),
|
|
2416
|
+
lowS: false
|
|
2417
|
+
}, sha2562);
|
|
2418
|
+
secp256r1 = p256;
|
|
2419
|
+
mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp256, {
|
|
2420
|
+
A: CURVE_A,
|
|
2421
|
+
B: CURVE_B,
|
|
2422
|
+
Z: Fp256.create(BigInt("-10"))
|
|
2423
|
+
}))();
|
|
2424
|
+
htf = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => mapSWU(scalars[0]), {
|
|
2425
|
+
DST: "P256_XMD:SHA-256_SSWU_RO_",
|
|
2426
|
+
encodeDST: "P256_XMD:SHA-256_SSWU_NU_",
|
|
2427
|
+
p: Fp256.ORDER,
|
|
2428
|
+
m: 1,
|
|
2429
|
+
k: 128,
|
|
2430
|
+
expand: "xmd",
|
|
2431
|
+
hash: sha2562
|
|
2432
|
+
}))();
|
|
2433
|
+
hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();
|
|
2434
|
+
encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();
|
|
2435
|
+
}
|
|
2436
|
+
});
|
|
2437
|
+
|
|
1
2438
|
// ../../node_modules/.pnpm/@noble+ed25519@3.0.1/node_modules/@noble/ed25519/index.js
|
|
2
2439
|
var ed25519_CURVE = {
|
|
3
2440
|
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
|
|
@@ -339,8 +2776,8 @@ var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
|
|
|
339
2776
|
var uvRatio = (u, v) => {
|
|
340
2777
|
const v3 = modP(v * modP(v * v));
|
|
341
2778
|
const v7 = modP(modP(v3 * v3) * v);
|
|
342
|
-
const
|
|
343
|
-
let x = modP(u * modP(v3 *
|
|
2779
|
+
const pow3 = pow_2_252_3(modP(u * v7)).pow_p_5_8;
|
|
2780
|
+
let x = modP(u * modP(v3 * pow3));
|
|
344
2781
|
const vx2 = modP(v * modP(x * x));
|
|
345
2782
|
const root1 = x;
|
|
346
2783
|
const root2 = modP(x * RM1);
|
|
@@ -514,6 +2951,7 @@ function aoutput(out, instance) {
|
|
|
514
2951
|
|
|
515
2952
|
// ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/utils.js
|
|
516
2953
|
var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
2954
|
+
var rotr = (word, shift) => word << 32 - shift | word >>> shift;
|
|
517
2955
|
function utf8ToBytes(str) {
|
|
518
2956
|
if (typeof str !== "string")
|
|
519
2957
|
throw new Error("utf8ToBytes expected string, got " + typeof str);
|
|
@@ -553,6 +2991,8 @@ function setBigUint64(view, byteOffset, value, isLE) {
|
|
|
553
2991
|
view.setUint32(byteOffset + h2, wh, isLE);
|
|
554
2992
|
view.setUint32(byteOffset + l, wl, isLE);
|
|
555
2993
|
}
|
|
2994
|
+
var Chi = (a, b, c) => a & b ^ ~a & c;
|
|
2995
|
+
var Maj = (a, b, c) => a & b ^ a & c ^ b & c;
|
|
556
2996
|
var HashMD = class extends Hash {
|
|
557
2997
|
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
558
2998
|
super();
|
|
@@ -905,10 +3345,235 @@ var SHA512 = class extends HashMD {
|
|
|
905
3345
|
};
|
|
906
3346
|
var sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());
|
|
907
3347
|
|
|
3348
|
+
// ../../node_modules/.pnpm/@noble+hashes@1.6.1/node_modules/@noble/hashes/esm/sha256.js
|
|
3349
|
+
var SHA256_K = /* @__PURE__ */ new Uint32Array([
|
|
3350
|
+
1116352408,
|
|
3351
|
+
1899447441,
|
|
3352
|
+
3049323471,
|
|
3353
|
+
3921009573,
|
|
3354
|
+
961987163,
|
|
3355
|
+
1508970993,
|
|
3356
|
+
2453635748,
|
|
3357
|
+
2870763221,
|
|
3358
|
+
3624381080,
|
|
3359
|
+
310598401,
|
|
3360
|
+
607225278,
|
|
3361
|
+
1426881987,
|
|
3362
|
+
1925078388,
|
|
3363
|
+
2162078206,
|
|
3364
|
+
2614888103,
|
|
3365
|
+
3248222580,
|
|
3366
|
+
3835390401,
|
|
3367
|
+
4022224774,
|
|
3368
|
+
264347078,
|
|
3369
|
+
604807628,
|
|
3370
|
+
770255983,
|
|
3371
|
+
1249150122,
|
|
3372
|
+
1555081692,
|
|
3373
|
+
1996064986,
|
|
3374
|
+
2554220882,
|
|
3375
|
+
2821834349,
|
|
3376
|
+
2952996808,
|
|
3377
|
+
3210313671,
|
|
3378
|
+
3336571891,
|
|
3379
|
+
3584528711,
|
|
3380
|
+
113926993,
|
|
3381
|
+
338241895,
|
|
3382
|
+
666307205,
|
|
3383
|
+
773529912,
|
|
3384
|
+
1294757372,
|
|
3385
|
+
1396182291,
|
|
3386
|
+
1695183700,
|
|
3387
|
+
1986661051,
|
|
3388
|
+
2177026350,
|
|
3389
|
+
2456956037,
|
|
3390
|
+
2730485921,
|
|
3391
|
+
2820302411,
|
|
3392
|
+
3259730800,
|
|
3393
|
+
3345764771,
|
|
3394
|
+
3516065817,
|
|
3395
|
+
3600352804,
|
|
3396
|
+
4094571909,
|
|
3397
|
+
275423344,
|
|
3398
|
+
430227734,
|
|
3399
|
+
506948616,
|
|
3400
|
+
659060556,
|
|
3401
|
+
883997877,
|
|
3402
|
+
958139571,
|
|
3403
|
+
1322822218,
|
|
3404
|
+
1537002063,
|
|
3405
|
+
1747873779,
|
|
3406
|
+
1955562222,
|
|
3407
|
+
2024104815,
|
|
3408
|
+
2227730452,
|
|
3409
|
+
2361852424,
|
|
3410
|
+
2428436474,
|
|
3411
|
+
2756734187,
|
|
3412
|
+
3204031479,
|
|
3413
|
+
3329325298
|
|
3414
|
+
]);
|
|
3415
|
+
var SHA256_IV = /* @__PURE__ */ new Uint32Array([
|
|
3416
|
+
1779033703,
|
|
3417
|
+
3144134277,
|
|
3418
|
+
1013904242,
|
|
3419
|
+
2773480762,
|
|
3420
|
+
1359893119,
|
|
3421
|
+
2600822924,
|
|
3422
|
+
528734635,
|
|
3423
|
+
1541459225
|
|
3424
|
+
]);
|
|
3425
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
3426
|
+
var SHA256 = class extends HashMD {
|
|
3427
|
+
constructor() {
|
|
3428
|
+
super(64, 32, 8, false);
|
|
3429
|
+
this.A = SHA256_IV[0] | 0;
|
|
3430
|
+
this.B = SHA256_IV[1] | 0;
|
|
3431
|
+
this.C = SHA256_IV[2] | 0;
|
|
3432
|
+
this.D = SHA256_IV[3] | 0;
|
|
3433
|
+
this.E = SHA256_IV[4] | 0;
|
|
3434
|
+
this.F = SHA256_IV[5] | 0;
|
|
3435
|
+
this.G = SHA256_IV[6] | 0;
|
|
3436
|
+
this.H = SHA256_IV[7] | 0;
|
|
3437
|
+
}
|
|
3438
|
+
get() {
|
|
3439
|
+
const { A, B, C: C2, D, E, F, G: G2, H } = this;
|
|
3440
|
+
return [A, B, C2, D, E, F, G2, H];
|
|
3441
|
+
}
|
|
3442
|
+
// prettier-ignore
|
|
3443
|
+
set(A, B, C2, D, E, F, G2, H) {
|
|
3444
|
+
this.A = A | 0;
|
|
3445
|
+
this.B = B | 0;
|
|
3446
|
+
this.C = C2 | 0;
|
|
3447
|
+
this.D = D | 0;
|
|
3448
|
+
this.E = E | 0;
|
|
3449
|
+
this.F = F | 0;
|
|
3450
|
+
this.G = G2 | 0;
|
|
3451
|
+
this.H = H | 0;
|
|
3452
|
+
}
|
|
3453
|
+
process(view, offset) {
|
|
3454
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
3455
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
3456
|
+
for (let i = 16; i < 64; i++) {
|
|
3457
|
+
const W15 = SHA256_W[i - 15];
|
|
3458
|
+
const W2 = SHA256_W[i - 2];
|
|
3459
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
3460
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
3461
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
3462
|
+
}
|
|
3463
|
+
let { A, B, C: C2, D, E, F, G: G2, H } = this;
|
|
3464
|
+
for (let i = 0; i < 64; i++) {
|
|
3465
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
3466
|
+
const T1 = H + sigma1 + Chi(E, F, G2) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
3467
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
3468
|
+
const T2 = sigma0 + Maj(A, B, C2) | 0;
|
|
3469
|
+
H = G2;
|
|
3470
|
+
G2 = F;
|
|
3471
|
+
F = E;
|
|
3472
|
+
E = D + T1 | 0;
|
|
3473
|
+
D = C2;
|
|
3474
|
+
C2 = B;
|
|
3475
|
+
B = A;
|
|
3476
|
+
A = T1 + T2 | 0;
|
|
3477
|
+
}
|
|
3478
|
+
A = A + this.A | 0;
|
|
3479
|
+
B = B + this.B | 0;
|
|
3480
|
+
C2 = C2 + this.C | 0;
|
|
3481
|
+
D = D + this.D | 0;
|
|
3482
|
+
E = E + this.E | 0;
|
|
3483
|
+
F = F + this.F | 0;
|
|
3484
|
+
G2 = G2 + this.G | 0;
|
|
3485
|
+
H = H + this.H | 0;
|
|
3486
|
+
this.set(A, B, C2, D, E, F, G2, H);
|
|
3487
|
+
}
|
|
3488
|
+
roundClean() {
|
|
3489
|
+
SHA256_W.fill(0);
|
|
3490
|
+
}
|
|
3491
|
+
destroy() {
|
|
3492
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
3493
|
+
this.buffer.fill(0);
|
|
3494
|
+
}
|
|
3495
|
+
};
|
|
3496
|
+
var sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());
|
|
3497
|
+
|
|
3498
|
+
// src/suite-dispatch.ts
|
|
3499
|
+
init_p256();
|
|
3500
|
+
if (!hashes.sha512) {
|
|
3501
|
+
hashes.sha512 = (msg) => sha512(msg);
|
|
3502
|
+
}
|
|
3503
|
+
async function verifyBySuite(suite, canonicalBytes, signatureBytes, publicKeyBytes) {
|
|
3504
|
+
switch (suite) {
|
|
3505
|
+
case "motebit-jcs-ed25519-b64-v1":
|
|
3506
|
+
case "motebit-jcs-ed25519-hex-v1":
|
|
3507
|
+
case "motebit-jwt-ed25519-v1":
|
|
3508
|
+
case "motebit-concat-ed25519-hex-v1":
|
|
3509
|
+
case "eddsa-jcs-2022":
|
|
3510
|
+
try {
|
|
3511
|
+
return await verifyAsync(signatureBytes, canonicalBytes, publicKeyBytes);
|
|
3512
|
+
} catch {
|
|
3513
|
+
return false;
|
|
3514
|
+
}
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
async function signBySuite(suite, canonicalBytes, privateKeyBytes) {
|
|
3518
|
+
switch (suite) {
|
|
3519
|
+
case "motebit-jcs-ed25519-b64-v1":
|
|
3520
|
+
case "motebit-jcs-ed25519-hex-v1":
|
|
3521
|
+
case "motebit-jwt-ed25519-v1":
|
|
3522
|
+
case "motebit-concat-ed25519-hex-v1":
|
|
3523
|
+
case "eddsa-jcs-2022":
|
|
3524
|
+
return signAsync(canonicalBytes, privateKeyBytes);
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
async function ed25519Sign(message, privateKey) {
|
|
3528
|
+
return signAsync(message, privateKey);
|
|
3529
|
+
}
|
|
3530
|
+
async function ed25519Verify(signature, message, publicKey) {
|
|
3531
|
+
try {
|
|
3532
|
+
return await verifyAsync(signature, message, publicKey);
|
|
3533
|
+
} catch {
|
|
3534
|
+
return false;
|
|
3535
|
+
}
|
|
3536
|
+
}
|
|
3537
|
+
async function generateEd25519Keypair() {
|
|
3538
|
+
const { secretKey, publicKey } = await keygenAsync();
|
|
3539
|
+
return { publicKey, privateKey: secretKey };
|
|
3540
|
+
}
|
|
3541
|
+
async function getPublicKeyBySuite(privateKey, suite) {
|
|
3542
|
+
switch (suite) {
|
|
3543
|
+
case "motebit-jcs-ed25519-b64-v1":
|
|
3544
|
+
case "motebit-jcs-ed25519-hex-v1":
|
|
3545
|
+
case "motebit-jwt-ed25519-v1":
|
|
3546
|
+
case "motebit-concat-ed25519-hex-v1":
|
|
3547
|
+
case "eddsa-jcs-2022":
|
|
3548
|
+
return getPublicKeyAsync(privateKey);
|
|
3549
|
+
}
|
|
3550
|
+
}
|
|
3551
|
+
function verifyP256EcdsaSha256(publicKeyCompressedHex, messageBytes, signatureDerBytes) {
|
|
3552
|
+
try {
|
|
3553
|
+
const digest = sha256(messageBytes);
|
|
3554
|
+
const pubKeyBytes = hexToBytes3(publicKeyCompressedHex);
|
|
3555
|
+
return p256.verify(signatureDerBytes, digest, pubKeyBytes, { prehash: false });
|
|
3556
|
+
} catch {
|
|
3557
|
+
return false;
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
function hexToBytes3(hex) {
|
|
3561
|
+
const clean = hex.startsWith("0x") || hex.startsWith("0X") ? hex.slice(2) : hex;
|
|
3562
|
+
if (clean.length % 2 !== 0) throw new Error("hex length must be even");
|
|
3563
|
+
const out = new Uint8Array(clean.length / 2);
|
|
3564
|
+
for (let i = 0; i < out.length; i++) {
|
|
3565
|
+
const byte = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
|
3566
|
+
if (Number.isNaN(byte)) throw new Error(`invalid hex at position ${i * 2}`);
|
|
3567
|
+
out[i] = byte;
|
|
3568
|
+
}
|
|
3569
|
+
return out;
|
|
3570
|
+
}
|
|
3571
|
+
|
|
908
3572
|
// src/signing.ts
|
|
909
3573
|
if (!hashes.sha512) {
|
|
910
3574
|
hashes.sha512 = (msg) => sha512(msg);
|
|
911
3575
|
}
|
|
3576
|
+
var SIGNED_TOKEN_SUITE = "motebit-jwt-ed25519-v1";
|
|
912
3577
|
function canonicalJson(obj) {
|
|
913
3578
|
if (obj === null || obj === void 0) return JSON.stringify(obj);
|
|
914
3579
|
if (typeof obj !== "object") return JSON.stringify(obj);
|
|
@@ -924,10 +3589,10 @@ function canonicalJson(obj) {
|
|
|
924
3589
|
}
|
|
925
3590
|
return "{" + entries.join(",") + "}";
|
|
926
3591
|
}
|
|
927
|
-
function
|
|
3592
|
+
function bytesToHex3(bytes) {
|
|
928
3593
|
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
929
3594
|
}
|
|
930
|
-
function
|
|
3595
|
+
function hexToBytes4(hex) {
|
|
931
3596
|
const bytes = new Uint8Array(hex.length / 2);
|
|
932
3597
|
for (let i = 0; i < hex.length; i += 2) {
|
|
933
3598
|
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
|
@@ -1013,35 +3678,28 @@ function publicKeyToDidKey(publicKey) {
|
|
|
1013
3678
|
return `did:key:z${base58btcEncode(prefixed)}`;
|
|
1014
3679
|
}
|
|
1015
3680
|
function hexPublicKeyToDidKey(hexPublicKey) {
|
|
1016
|
-
return publicKeyToDidKey(
|
|
3681
|
+
return publicKeyToDidKey(hexToBytes4(hexPublicKey));
|
|
1017
3682
|
}
|
|
1018
3683
|
async function hash(data) {
|
|
1019
3684
|
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
1020
3685
|
const hashArray = new Uint8Array(hashBuffer);
|
|
1021
3686
|
return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1022
3687
|
}
|
|
1023
|
-
async function
|
|
3688
|
+
async function canonicalSha256(obj) {
|
|
3689
|
+
return hash(new TextEncoder().encode(canonicalJson(obj)));
|
|
3690
|
+
}
|
|
3691
|
+
async function sha2563(data) {
|
|
1024
3692
|
const buf = await crypto.subtle.digest("SHA-256", data);
|
|
1025
3693
|
return new Uint8Array(buf);
|
|
1026
3694
|
}
|
|
1027
3695
|
async function generateKeypair() {
|
|
1028
|
-
|
|
1029
|
-
return { publicKey, privateKey: secretKey };
|
|
1030
|
-
}
|
|
1031
|
-
async function ed25519Sign(message, privateKey) {
|
|
1032
|
-
return signAsync(message, privateKey);
|
|
1033
|
-
}
|
|
1034
|
-
async function ed25519Verify(signature, message, publicKey) {
|
|
1035
|
-
try {
|
|
1036
|
-
return await verifyAsync(signature, message, publicKey);
|
|
1037
|
-
} catch {
|
|
1038
|
-
return false;
|
|
1039
|
-
}
|
|
3696
|
+
return generateEd25519Keypair();
|
|
1040
3697
|
}
|
|
1041
3698
|
async function createSignedToken(payload, privateKey) {
|
|
1042
|
-
const
|
|
3699
|
+
const withSuite = { ...payload, suite: SIGNED_TOKEN_SUITE };
|
|
3700
|
+
const payloadBytes = new TextEncoder().encode(JSON.stringify(withSuite));
|
|
1043
3701
|
const payloadB64 = toBase64Url(payloadBytes);
|
|
1044
|
-
const signature = await
|
|
3702
|
+
const signature = await signBySuite(SIGNED_TOKEN_SUITE, payloadBytes, privateKey);
|
|
1045
3703
|
const sigB64 = toBase64Url(signature);
|
|
1046
3704
|
return `${payloadB64}.${sigB64}`;
|
|
1047
3705
|
}
|
|
@@ -1058,14 +3716,15 @@ async function verifySignedToken(token, publicKey) {
|
|
|
1058
3716
|
} catch {
|
|
1059
3717
|
return null;
|
|
1060
3718
|
}
|
|
1061
|
-
const valid = await ed25519Verify(signature, payloadBytes, publicKey);
|
|
1062
|
-
if (!valid) return null;
|
|
1063
3719
|
let payload;
|
|
1064
3720
|
try {
|
|
1065
3721
|
payload = JSON.parse(new TextDecoder().decode(payloadBytes));
|
|
1066
3722
|
} catch {
|
|
1067
3723
|
return null;
|
|
1068
3724
|
}
|
|
3725
|
+
if (payload.suite !== SIGNED_TOKEN_SUITE) return null;
|
|
3726
|
+
const valid = await verifyBySuite(payload.suite, payloadBytes, signature, publicKey);
|
|
3727
|
+
if (!valid) return null;
|
|
1069
3728
|
if (payload.exp <= Date.now()) return null;
|
|
1070
3729
|
if (!payload.jti) return null;
|
|
1071
3730
|
if (!payload.aud) return null;
|
|
@@ -1088,24 +3747,390 @@ function isScopeNarrowed(parentScope, childScope) {
|
|
|
1088
3747
|
return true;
|
|
1089
3748
|
}
|
|
1090
3749
|
|
|
3750
|
+
// src/hardware-attestation.ts
|
|
3751
|
+
function verifyHardwareAttestationClaim(claim, expectedIdentityPublicKeyHex, verifiers, deviceCheckContext) {
|
|
3752
|
+
const platform = claim.platform;
|
|
3753
|
+
const errors = [];
|
|
3754
|
+
switch (platform) {
|
|
3755
|
+
case "secure_enclave":
|
|
3756
|
+
return verifySecureEnclaveClaim(claim, expectedIdentityPublicKeyHex);
|
|
3757
|
+
case "software":
|
|
3758
|
+
errors.push({
|
|
3759
|
+
message: "platform `software` is a no-hardware sentinel; no verification channel"
|
|
3760
|
+
});
|
|
3761
|
+
return { valid: false, platform: "software", errors };
|
|
3762
|
+
case "device_check":
|
|
3763
|
+
if (verifiers?.deviceCheck) {
|
|
3764
|
+
return dispatchInjected(
|
|
3765
|
+
platform,
|
|
3766
|
+
verifiers.deviceCheck(claim, expectedIdentityPublicKeyHex, deviceCheckContext)
|
|
3767
|
+
);
|
|
3768
|
+
}
|
|
3769
|
+
errors.push({
|
|
3770
|
+
message: `platform \`${platform}\` verifier not wired \u2014 pass { deviceCheck: deviceCheckVerifier(...) } from @motebit/crypto-appattest to enable`
|
|
3771
|
+
});
|
|
3772
|
+
return { valid: false, platform, errors };
|
|
3773
|
+
case "tpm":
|
|
3774
|
+
if (verifiers?.tpm) {
|
|
3775
|
+
return dispatchInjected(
|
|
3776
|
+
platform,
|
|
3777
|
+
verifiers.tpm(claim, expectedIdentityPublicKeyHex, deviceCheckContext)
|
|
3778
|
+
);
|
|
3779
|
+
}
|
|
3780
|
+
errors.push({
|
|
3781
|
+
message: `platform \`${platform}\` verifier not wired \u2014 pass { tpm: ... } via the verifiers parameter to enable`
|
|
3782
|
+
});
|
|
3783
|
+
return { valid: false, platform, errors };
|
|
3784
|
+
case "play_integrity":
|
|
3785
|
+
if (verifiers?.playIntegrity) {
|
|
3786
|
+
return dispatchInjected(
|
|
3787
|
+
platform,
|
|
3788
|
+
verifiers.playIntegrity(claim, expectedIdentityPublicKeyHex, deviceCheckContext)
|
|
3789
|
+
);
|
|
3790
|
+
}
|
|
3791
|
+
errors.push({
|
|
3792
|
+
message: `platform \`${platform}\` verifier not wired \u2014 pass { playIntegrity: ... } via the verifiers parameter to enable`
|
|
3793
|
+
});
|
|
3794
|
+
return { valid: false, platform, errors };
|
|
3795
|
+
case "webauthn":
|
|
3796
|
+
if (verifiers?.webauthn) {
|
|
3797
|
+
return dispatchInjected(
|
|
3798
|
+
platform,
|
|
3799
|
+
verifiers.webauthn(claim, expectedIdentityPublicKeyHex, deviceCheckContext)
|
|
3800
|
+
);
|
|
3801
|
+
}
|
|
3802
|
+
errors.push({
|
|
3803
|
+
message: `platform \`${platform}\` verifier not wired \u2014 pass { webauthn: webauthnVerifier(...) } from @motebit/crypto-webauthn to enable`
|
|
3804
|
+
});
|
|
3805
|
+
return { valid: false, platform, errors };
|
|
3806
|
+
case "android_keystore":
|
|
3807
|
+
if (verifiers?.androidKeystore) {
|
|
3808
|
+
return dispatchInjected(
|
|
3809
|
+
platform,
|
|
3810
|
+
verifiers.androidKeystore(claim, expectedIdentityPublicKeyHex, deviceCheckContext)
|
|
3811
|
+
);
|
|
3812
|
+
}
|
|
3813
|
+
errors.push({
|
|
3814
|
+
message: `platform \`${platform}\` verifier not wired \u2014 pass { androidKeystore: androidKeystoreVerifier(...) } from @motebit/crypto-android-keystore to enable`
|
|
3815
|
+
});
|
|
3816
|
+
return { valid: false, platform, errors };
|
|
3817
|
+
default:
|
|
3818
|
+
errors.push({
|
|
3819
|
+
message: `unknown platform \`${claim.platform}\` \u2014 not in the declared enum`
|
|
3820
|
+
});
|
|
3821
|
+
return { valid: false, platform: null, errors };
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
3824
|
+
async function dispatchInjected(platform, result) {
|
|
3825
|
+
const awaited = await Promise.resolve(result);
|
|
3826
|
+
return {
|
|
3827
|
+
valid: awaited.valid,
|
|
3828
|
+
platform,
|
|
3829
|
+
errors: awaited.errors ?? []
|
|
3830
|
+
};
|
|
3831
|
+
}
|
|
3832
|
+
function verifySecureEnclaveClaim(claim, expectedIdentityPublicKeyHex) {
|
|
3833
|
+
const errors = [];
|
|
3834
|
+
const platform = "secure_enclave";
|
|
3835
|
+
if (claim.key_exported === true) {
|
|
3836
|
+
}
|
|
3837
|
+
if (!claim.attestation_receipt) {
|
|
3838
|
+
errors.push({
|
|
3839
|
+
message: "secure_enclave claim missing `attestation_receipt`"
|
|
3840
|
+
});
|
|
3841
|
+
return { valid: false, platform, errors };
|
|
3842
|
+
}
|
|
3843
|
+
const parts = claim.attestation_receipt.split(".");
|
|
3844
|
+
if (parts.length !== 2) {
|
|
3845
|
+
errors.push({
|
|
3846
|
+
message: `attestation_receipt must be 2 base64url parts separated by '.'; got ${parts.length}`
|
|
3847
|
+
});
|
|
3848
|
+
return { valid: false, platform, errors };
|
|
3849
|
+
}
|
|
3850
|
+
const [bodyB64, sigB64] = parts;
|
|
3851
|
+
let bodyBytes;
|
|
3852
|
+
let sigBytes;
|
|
3853
|
+
try {
|
|
3854
|
+
bodyBytes = fromBase64Url(bodyB64);
|
|
3855
|
+
sigBytes = fromBase64Url(sigB64);
|
|
3856
|
+
} catch (err2) {
|
|
3857
|
+
errors.push({
|
|
3858
|
+
message: `base64url decode failed: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
3859
|
+
});
|
|
3860
|
+
return { valid: false, platform, errors };
|
|
3861
|
+
}
|
|
3862
|
+
let bodyJson;
|
|
3863
|
+
try {
|
|
3864
|
+
bodyJson = JSON.parse(new TextDecoder().decode(bodyBytes));
|
|
3865
|
+
} catch (err2) {
|
|
3866
|
+
errors.push({
|
|
3867
|
+
message: `body JSON parse failed: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
3868
|
+
});
|
|
3869
|
+
return { valid: false, platform, errors };
|
|
3870
|
+
}
|
|
3871
|
+
const bodyCheck = parseSecureEnclaveBody(bodyJson);
|
|
3872
|
+
if (bodyCheck.kind === "error") {
|
|
3873
|
+
errors.push({ message: bodyCheck.reason });
|
|
3874
|
+
return { valid: false, platform, errors };
|
|
3875
|
+
}
|
|
3876
|
+
const body = bodyCheck.body;
|
|
3877
|
+
if (body.version !== "1") {
|
|
3878
|
+
errors.push({
|
|
3879
|
+
message: `unsupported body version '${body.version}' (expected '1')`
|
|
3880
|
+
});
|
|
3881
|
+
return { valid: false, platform, errors };
|
|
3882
|
+
}
|
|
3883
|
+
if (body.algorithm !== "ecdsa-p256-sha256") {
|
|
3884
|
+
errors.push({
|
|
3885
|
+
message: `unsupported body algorithm '${body.algorithm}' (expected 'ecdsa-p256-sha256')`
|
|
3886
|
+
});
|
|
3887
|
+
return { valid: false, platform, errors };
|
|
3888
|
+
}
|
|
3889
|
+
let sigValid;
|
|
3890
|
+
try {
|
|
3891
|
+
sigValid = verifyP256EcdsaSha256(body.se_public_key, bodyBytes, sigBytes);
|
|
3892
|
+
} catch (err2) {
|
|
3893
|
+
errors.push({
|
|
3894
|
+
message: `p-256 verification crashed: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
3895
|
+
});
|
|
3896
|
+
return { valid: false, platform, errors };
|
|
3897
|
+
}
|
|
3898
|
+
if (!sigValid) {
|
|
3899
|
+
errors.push({
|
|
3900
|
+
message: "p-256 signature does not verify against body + se_public_key"
|
|
3901
|
+
});
|
|
3902
|
+
return { valid: false, platform, errors };
|
|
3903
|
+
}
|
|
3904
|
+
if (body.identity_public_key.toLowerCase() !== expectedIdentityPublicKeyHex.toLowerCase()) {
|
|
3905
|
+
errors.push({
|
|
3906
|
+
message: `identity_public_key mismatch: body names ${body.identity_public_key.slice(0, 16)}\u2026, expected ${expectedIdentityPublicKeyHex.slice(0, 16)}\u2026`
|
|
3907
|
+
});
|
|
3908
|
+
return { valid: false, platform, errors };
|
|
3909
|
+
}
|
|
3910
|
+
return {
|
|
3911
|
+
valid: true,
|
|
3912
|
+
platform,
|
|
3913
|
+
se_public_key: body.se_public_key,
|
|
3914
|
+
attested_at: body.attested_at,
|
|
3915
|
+
errors: []
|
|
3916
|
+
};
|
|
3917
|
+
}
|
|
3918
|
+
function parseSecureEnclaveBody(raw) {
|
|
3919
|
+
if (raw === null || typeof raw !== "object") {
|
|
3920
|
+
return { kind: "error", reason: "body is not a JSON object" };
|
|
3921
|
+
}
|
|
3922
|
+
const r = raw;
|
|
3923
|
+
const fields = [
|
|
3924
|
+
"version",
|
|
3925
|
+
"algorithm",
|
|
3926
|
+
"motebit_id",
|
|
3927
|
+
"device_id",
|
|
3928
|
+
"identity_public_key",
|
|
3929
|
+
"se_public_key",
|
|
3930
|
+
"attested_at"
|
|
3931
|
+
];
|
|
3932
|
+
for (const f of fields) {
|
|
3933
|
+
if (!(f in r)) {
|
|
3934
|
+
return { kind: "error", reason: `body missing required field '${f}'` };
|
|
3935
|
+
}
|
|
3936
|
+
}
|
|
3937
|
+
if (typeof r.version !== "string" || typeof r.algorithm !== "string" || typeof r.motebit_id !== "string" || typeof r.device_id !== "string" || typeof r.identity_public_key !== "string" || typeof r.se_public_key !== "string" || typeof r.attested_at !== "number") {
|
|
3938
|
+
return { kind: "error", reason: "body field types invalid" };
|
|
3939
|
+
}
|
|
3940
|
+
return {
|
|
3941
|
+
kind: "ok",
|
|
3942
|
+
body: {
|
|
3943
|
+
version: r.version,
|
|
3944
|
+
algorithm: r.algorithm,
|
|
3945
|
+
motebit_id: r.motebit_id,
|
|
3946
|
+
device_id: r.device_id,
|
|
3947
|
+
identity_public_key: r.identity_public_key,
|
|
3948
|
+
se_public_key: r.se_public_key,
|
|
3949
|
+
attested_at: r.attested_at
|
|
3950
|
+
}
|
|
3951
|
+
};
|
|
3952
|
+
}
|
|
3953
|
+
function encodeSecureEnclaveReceiptForTest(bodyBytes, sigBytes) {
|
|
3954
|
+
return `${toBase64Url2(bodyBytes)}.${toBase64Url2(sigBytes)}`;
|
|
3955
|
+
}
|
|
3956
|
+
function canonicalSecureEnclaveBodyForTest(body) {
|
|
3957
|
+
const full = {
|
|
3958
|
+
version: "1",
|
|
3959
|
+
algorithm: "ecdsa-p256-sha256",
|
|
3960
|
+
...body
|
|
3961
|
+
};
|
|
3962
|
+
return new TextEncoder().encode(canonicalJson(full));
|
|
3963
|
+
}
|
|
3964
|
+
async function mintSecureEnclaveReceiptForTest(input) {
|
|
3965
|
+
const { p256: p2562 } = await Promise.resolve().then(() => (init_p256(), p256_exports));
|
|
3966
|
+
const privateKey = p2562.utils.randomPrivateKey();
|
|
3967
|
+
const sePublicKey = p2562.getPublicKey(privateKey, true);
|
|
3968
|
+
const sePublicKeyHex = bytesToHexLocal(sePublicKey);
|
|
3969
|
+
const bodyBytes = canonicalSecureEnclaveBodyForTest({
|
|
3970
|
+
motebit_id: input.motebit_id,
|
|
3971
|
+
device_id: input.device_id,
|
|
3972
|
+
identity_public_key: input.identity_public_key,
|
|
3973
|
+
se_public_key: sePublicKeyHex,
|
|
3974
|
+
attested_at: input.attested_at
|
|
3975
|
+
});
|
|
3976
|
+
const digest = await sha256Local(bodyBytes);
|
|
3977
|
+
const sigBytes = p2562.sign(digest, privateKey, { prehash: false }).toDERRawBytes();
|
|
3978
|
+
const receipt = encodeSecureEnclaveReceiptForTest(bodyBytes, sigBytes);
|
|
3979
|
+
return {
|
|
3980
|
+
claim: {
|
|
3981
|
+
platform: "secure_enclave",
|
|
3982
|
+
key_exported: false,
|
|
3983
|
+
attestation_receipt: receipt
|
|
3984
|
+
},
|
|
3985
|
+
sePublicKeyHex
|
|
3986
|
+
};
|
|
3987
|
+
}
|
|
3988
|
+
function bytesToHexLocal(bytes) {
|
|
3989
|
+
let hex = "";
|
|
3990
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
3991
|
+
hex += bytes[i].toString(16).padStart(2, "0");
|
|
3992
|
+
}
|
|
3993
|
+
return hex;
|
|
3994
|
+
}
|
|
3995
|
+
async function sha256Local(bytes) {
|
|
3996
|
+
const buf = await crypto.subtle.digest("SHA-256", bytes);
|
|
3997
|
+
return new Uint8Array(buf);
|
|
3998
|
+
}
|
|
3999
|
+
function toBase64Url2(bytes) {
|
|
4000
|
+
let binary = "";
|
|
4001
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
4002
|
+
binary += String.fromCharCode(bytes[i]);
|
|
4003
|
+
}
|
|
4004
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
4005
|
+
}
|
|
4006
|
+
|
|
1091
4007
|
// src/artifacts.ts
|
|
4008
|
+
function isReceiptDebugEnabled() {
|
|
4009
|
+
const g = globalThis;
|
|
4010
|
+
if (g.__motebit_debug_receipt_bytes === true) return true;
|
|
4011
|
+
const flag = g.process?.env?.DEBUG_RECEIPT_BYTES;
|
|
4012
|
+
return flag === "1" || flag === "true";
|
|
4013
|
+
}
|
|
4014
|
+
var EXECUTION_RECEIPT_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
1092
4015
|
async function signExecutionReceipt(receipt, privateKey, publicKey) {
|
|
1093
|
-
const
|
|
4016
|
+
const withKey = publicKey ? { ...receipt, public_key: bytesToHex3(publicKey) } : receipt;
|
|
4017
|
+
const body = { ...withKey, suite: EXECUTION_RECEIPT_SUITE };
|
|
1094
4018
|
const canonical = canonicalJson(body);
|
|
1095
4019
|
const message = new TextEncoder().encode(canonical);
|
|
1096
|
-
const sig = await
|
|
1097
|
-
|
|
4020
|
+
const sig = await signBySuite(EXECUTION_RECEIPT_SUITE, message, privateKey);
|
|
4021
|
+
const signed = { ...body, signature: toBase64Url(sig) };
|
|
4022
|
+
if (isReceiptDebugEnabled()) {
|
|
4023
|
+
const sha = await canonicalSha256(body);
|
|
4024
|
+
console.debug(
|
|
4025
|
+
`[motebit/crypto] signExecutionReceipt canonical_sha256=${sha} chain=${Array.isArray(body.delegation_receipts) ? body.delegation_receipts.length : 0} bytes=${canonical.length}`
|
|
4026
|
+
);
|
|
4027
|
+
}
|
|
4028
|
+
return Object.freeze(signed);
|
|
1098
4029
|
}
|
|
1099
4030
|
async function verifyExecutionReceipt(receipt, publicKey) {
|
|
4031
|
+
if (receipt.suite !== EXECUTION_RECEIPT_SUITE) {
|
|
4032
|
+
if (isReceiptDebugEnabled()) {
|
|
4033
|
+
console.debug(
|
|
4034
|
+
`[motebit/crypto] verifyExecutionReceipt EARLY_RETURN suite_mismatch actual=${JSON.stringify(receipt.suite)} expected=${JSON.stringify(EXECUTION_RECEIPT_SUITE)}`
|
|
4035
|
+
);
|
|
4036
|
+
}
|
|
4037
|
+
return false;
|
|
4038
|
+
}
|
|
1100
4039
|
const { signature, ...body } = receipt;
|
|
1101
4040
|
const canonical = canonicalJson(body);
|
|
1102
4041
|
const message = new TextEncoder().encode(canonical);
|
|
4042
|
+
let valid = false;
|
|
1103
4043
|
try {
|
|
1104
4044
|
const sig = fromBase64Url(signature);
|
|
1105
|
-
|
|
4045
|
+
valid = await verifyBySuite(receipt.suite, message, sig, publicKey);
|
|
4046
|
+
} catch {
|
|
4047
|
+
valid = false;
|
|
4048
|
+
}
|
|
4049
|
+
if (isReceiptDebugEnabled()) {
|
|
4050
|
+
const sha = await canonicalSha256(body);
|
|
4051
|
+
console.debug(
|
|
4052
|
+
`[motebit/crypto] verifyExecutionReceipt canonical_sha256=${sha} valid=${valid} bytes=${canonical.length}`
|
|
4053
|
+
);
|
|
4054
|
+
}
|
|
4055
|
+
return valid;
|
|
4056
|
+
}
|
|
4057
|
+
async function verifyExecutionReceiptDetailed(receipt, publicKey) {
|
|
4058
|
+
if (receipt.suite !== EXECUTION_RECEIPT_SUITE) {
|
|
4059
|
+
const { signature: _drop, ...bodyForHash } = receipt;
|
|
4060
|
+
return {
|
|
4061
|
+
valid: false,
|
|
4062
|
+
canonical_sha256: await canonicalSha256(bodyForHash),
|
|
4063
|
+
canonical_preview: canonicalJson(bodyForHash).slice(0, 256),
|
|
4064
|
+
reason: "wrong_suite"
|
|
4065
|
+
};
|
|
4066
|
+
}
|
|
4067
|
+
const { signature, ...body } = receipt;
|
|
4068
|
+
const canonical = canonicalJson(body);
|
|
4069
|
+
const message = new TextEncoder().encode(canonical);
|
|
4070
|
+
let sigBytes;
|
|
4071
|
+
try {
|
|
4072
|
+
sigBytes = fromBase64Url(signature);
|
|
1106
4073
|
} catch {
|
|
4074
|
+
return {
|
|
4075
|
+
valid: false,
|
|
4076
|
+
canonical_sha256: await hash(message),
|
|
4077
|
+
canonical_preview: canonical.slice(0, 256),
|
|
4078
|
+
reason: "bad_base64"
|
|
4079
|
+
};
|
|
4080
|
+
}
|
|
4081
|
+
const valid = await verifyBySuite(receipt.suite, message, sigBytes, publicKey);
|
|
4082
|
+
return {
|
|
4083
|
+
valid,
|
|
4084
|
+
canonical_sha256: await hash(message),
|
|
4085
|
+
canonical_preview: canonical.slice(0, 256),
|
|
4086
|
+
reason: valid ? "ok" : "ed25519_mismatch"
|
|
4087
|
+
};
|
|
4088
|
+
}
|
|
4089
|
+
var TOOL_INVOCATION_RECEIPT_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4090
|
+
async function hashToolPayload(value) {
|
|
4091
|
+
return canonicalSha256(value);
|
|
4092
|
+
}
|
|
4093
|
+
async function signToolInvocationReceipt(receipt, privateKey, publicKey) {
|
|
4094
|
+
const withKey = publicKey ? { ...receipt, public_key: bytesToHex3(publicKey) } : receipt;
|
|
4095
|
+
const body = { ...withKey, suite: TOOL_INVOCATION_RECEIPT_SUITE };
|
|
4096
|
+
const canonical = canonicalJson(body);
|
|
4097
|
+
const message = new TextEncoder().encode(canonical);
|
|
4098
|
+
const sig = await signBySuite(TOOL_INVOCATION_RECEIPT_SUITE, message, privateKey);
|
|
4099
|
+
const signed = { ...body, signature: toBase64Url(sig) };
|
|
4100
|
+
if (isReceiptDebugEnabled()) {
|
|
4101
|
+
const sha = await canonicalSha256(body);
|
|
4102
|
+
console.debug(
|
|
4103
|
+
`[motebit/crypto] signToolInvocationReceipt canonical_sha256=${sha} tool=${body.tool_name} bytes=${canonical.length}`
|
|
4104
|
+
);
|
|
4105
|
+
}
|
|
4106
|
+
return Object.freeze(signed);
|
|
4107
|
+
}
|
|
4108
|
+
async function verifyToolInvocationReceipt(receipt, publicKey) {
|
|
4109
|
+
if (receipt.suite !== TOOL_INVOCATION_RECEIPT_SUITE) {
|
|
4110
|
+
if (isReceiptDebugEnabled()) {
|
|
4111
|
+
console.debug(
|
|
4112
|
+
`[motebit/crypto] verifyToolInvocationReceipt EARLY_RETURN suite_mismatch actual=${JSON.stringify(receipt.suite)} expected=${JSON.stringify(TOOL_INVOCATION_RECEIPT_SUITE)}`
|
|
4113
|
+
);
|
|
4114
|
+
}
|
|
1107
4115
|
return false;
|
|
1108
4116
|
}
|
|
4117
|
+
const { signature, ...body } = receipt;
|
|
4118
|
+
const canonical = canonicalJson(body);
|
|
4119
|
+
const message = new TextEncoder().encode(canonical);
|
|
4120
|
+
let valid = false;
|
|
4121
|
+
try {
|
|
4122
|
+
const sig = fromBase64Url(signature);
|
|
4123
|
+
valid = await verifyBySuite(receipt.suite, message, sig, publicKey);
|
|
4124
|
+
} catch {
|
|
4125
|
+
valid = false;
|
|
4126
|
+
}
|
|
4127
|
+
if (isReceiptDebugEnabled()) {
|
|
4128
|
+
const sha = await canonicalSha256(body);
|
|
4129
|
+
console.debug(
|
|
4130
|
+
`[motebit/crypto] verifyToolInvocationReceipt canonical_sha256=${sha} valid=${valid} bytes=${canonical.length}`
|
|
4131
|
+
);
|
|
4132
|
+
}
|
|
4133
|
+
return valid;
|
|
1109
4134
|
}
|
|
1110
4135
|
async function signSovereignPaymentReceipt(input, privateKey, publicKey) {
|
|
1111
4136
|
const receipt = {
|
|
@@ -1121,6 +4146,7 @@ async function signSovereignPaymentReceipt(input, privateKey, publicKey) {
|
|
|
1121
4146
|
prompt_hash: input.prompt_hash,
|
|
1122
4147
|
result_hash: input.result_hash
|
|
1123
4148
|
// relay_task_id intentionally omitted — sovereign rail, no relay binding
|
|
4149
|
+
// suite is stamped by signExecutionReceipt
|
|
1124
4150
|
};
|
|
1125
4151
|
return signExecutionReceipt(receipt, privateKey, publicKey);
|
|
1126
4152
|
}
|
|
@@ -1128,7 +4154,7 @@ async function verifyReceiptChain(receipt, knownKeys) {
|
|
|
1128
4154
|
const { task_id, motebit_id } = receipt;
|
|
1129
4155
|
let publicKey = knownKeys.get(motebit_id);
|
|
1130
4156
|
if (!publicKey && receipt.public_key) {
|
|
1131
|
-
publicKey =
|
|
4157
|
+
publicKey = hexToBytes4(receipt.public_key);
|
|
1132
4158
|
}
|
|
1133
4159
|
if (!publicKey) {
|
|
1134
4160
|
const delegations2 = await verifyDelegations(receipt, knownKeys);
|
|
@@ -1177,13 +4203,16 @@ async function verifyReceiptSequence(chain) {
|
|
|
1177
4203
|
}
|
|
1178
4204
|
return { valid: true };
|
|
1179
4205
|
}
|
|
4206
|
+
var DELEGATION_TOKEN_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
1180
4207
|
async function signDelegation(delegation, delegatorPrivateKey) {
|
|
1181
|
-
const
|
|
4208
|
+
const body = { ...delegation, suite: DELEGATION_TOKEN_SUITE };
|
|
4209
|
+
const canonical = canonicalJson(body);
|
|
1182
4210
|
const message = new TextEncoder().encode(canonical);
|
|
1183
|
-
const sig = await
|
|
1184
|
-
return { ...
|
|
4211
|
+
const sig = await signBySuite(DELEGATION_TOKEN_SUITE, message, delegatorPrivateKey);
|
|
4212
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
1185
4213
|
}
|
|
1186
4214
|
async function verifyDelegation(delegation, options) {
|
|
4215
|
+
if (delegation.suite !== DELEGATION_TOKEN_SUITE) return false;
|
|
1187
4216
|
const checkExpiry = options?.checkExpiry ?? true;
|
|
1188
4217
|
if (checkExpiry) {
|
|
1189
4218
|
const now = options?.now ?? Date.now();
|
|
@@ -1193,9 +4222,9 @@ async function verifyDelegation(delegation, options) {
|
|
|
1193
4222
|
const canonical = canonicalJson(body);
|
|
1194
4223
|
const message = new TextEncoder().encode(canonical);
|
|
1195
4224
|
try {
|
|
1196
|
-
const pubKey =
|
|
4225
|
+
const pubKey = hexToBytes4(delegation.delegator_public_key);
|
|
1197
4226
|
const sig = fromBase64Url(signature);
|
|
1198
|
-
return await
|
|
4227
|
+
return await verifyBySuite(delegation.suite, message, sig, pubKey);
|
|
1199
4228
|
} catch {
|
|
1200
4229
|
return false;
|
|
1201
4230
|
}
|
|
@@ -1232,11 +4261,186 @@ async function verifyDelegationChain(chain) {
|
|
|
1232
4261
|
}
|
|
1233
4262
|
return { valid: true };
|
|
1234
4263
|
}
|
|
4264
|
+
var ADJUDICATOR_VOTE_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4265
|
+
var DISPUTE_RESOLUTION_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4266
|
+
var DISPUTE_REQUEST_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4267
|
+
var DISPUTE_EVIDENCE_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4268
|
+
var DISPUTE_APPEAL_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4269
|
+
async function signAdjudicatorVote(vote, peerPrivateKey) {
|
|
4270
|
+
const body = { ...vote, suite: ADJUDICATOR_VOTE_SUITE };
|
|
4271
|
+
const canonical = canonicalJson(body);
|
|
4272
|
+
const message = new TextEncoder().encode(canonical);
|
|
4273
|
+
const sig = await signBySuite(ADJUDICATOR_VOTE_SUITE, message, peerPrivateKey);
|
|
4274
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4275
|
+
}
|
|
4276
|
+
async function verifyAdjudicatorVote(vote, peerPublicKey) {
|
|
4277
|
+
if (vote.suite !== ADJUDICATOR_VOTE_SUITE) return false;
|
|
4278
|
+
const { signature, ...body } = vote;
|
|
4279
|
+
const canonical = canonicalJson(body);
|
|
4280
|
+
const message = new TextEncoder().encode(canonical);
|
|
4281
|
+
try {
|
|
4282
|
+
const sig = fromBase64Url(signature);
|
|
4283
|
+
return await verifyBySuite(vote.suite, message, sig, peerPublicKey);
|
|
4284
|
+
} catch {
|
|
4285
|
+
return false;
|
|
4286
|
+
}
|
|
4287
|
+
}
|
|
4288
|
+
async function signDisputeResolution(resolution, adjudicatorPrivateKey) {
|
|
4289
|
+
const body = { ...resolution, suite: DISPUTE_RESOLUTION_SUITE };
|
|
4290
|
+
const canonical = canonicalJson(body);
|
|
4291
|
+
const message = new TextEncoder().encode(canonical);
|
|
4292
|
+
const sig = await signBySuite(DISPUTE_RESOLUTION_SUITE, message, adjudicatorPrivateKey);
|
|
4293
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4294
|
+
}
|
|
4295
|
+
async function verifyDisputeResolution(resolution, adjudicatorPublicKey, peerKeys) {
|
|
4296
|
+
if (resolution.suite !== DISPUTE_RESOLUTION_SUITE) return false;
|
|
4297
|
+
const { signature, ...body } = resolution;
|
|
4298
|
+
const canonical = canonicalJson(body);
|
|
4299
|
+
const message = new TextEncoder().encode(canonical);
|
|
4300
|
+
try {
|
|
4301
|
+
const sig = fromBase64Url(signature);
|
|
4302
|
+
const outerValid = await verifyBySuite(resolution.suite, message, sig, adjudicatorPublicKey);
|
|
4303
|
+
if (!outerValid) return false;
|
|
4304
|
+
} catch {
|
|
4305
|
+
return false;
|
|
4306
|
+
}
|
|
4307
|
+
if (resolution.adjudicator_votes.length > 0) {
|
|
4308
|
+
if (!peerKeys) return false;
|
|
4309
|
+
for (const vote of resolution.adjudicator_votes) {
|
|
4310
|
+
if (vote.dispute_id !== resolution.dispute_id) return false;
|
|
4311
|
+
const peerKey = peerKeys.get(vote.peer_id);
|
|
4312
|
+
if (!peerKey) return false;
|
|
4313
|
+
const voteValid = await verifyAdjudicatorVote(vote, peerKey);
|
|
4314
|
+
if (!voteValid) return false;
|
|
4315
|
+
}
|
|
4316
|
+
}
|
|
4317
|
+
return true;
|
|
4318
|
+
}
|
|
4319
|
+
async function signDisputeRequest(request, filerPrivateKey) {
|
|
4320
|
+
const body = { ...request, suite: DISPUTE_REQUEST_SUITE };
|
|
4321
|
+
const canonical = canonicalJson(body);
|
|
4322
|
+
const message = new TextEncoder().encode(canonical);
|
|
4323
|
+
const sig = await signBySuite(DISPUTE_REQUEST_SUITE, message, filerPrivateKey);
|
|
4324
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4325
|
+
}
|
|
4326
|
+
async function verifyDisputeRequest(request, filerPublicKey) {
|
|
4327
|
+
if (request.suite !== DISPUTE_REQUEST_SUITE) return false;
|
|
4328
|
+
const { signature, ...body } = request;
|
|
4329
|
+
const canonical = canonicalJson(body);
|
|
4330
|
+
const message = new TextEncoder().encode(canonical);
|
|
4331
|
+
try {
|
|
4332
|
+
const sig = fromBase64Url(signature);
|
|
4333
|
+
return await verifyBySuite(request.suite, message, sig, filerPublicKey);
|
|
4334
|
+
} catch {
|
|
4335
|
+
return false;
|
|
4336
|
+
}
|
|
4337
|
+
}
|
|
4338
|
+
async function signDisputeEvidence(evidence, submitterPrivateKey) {
|
|
4339
|
+
const body = { ...evidence, suite: DISPUTE_EVIDENCE_SUITE };
|
|
4340
|
+
const canonical = canonicalJson(body);
|
|
4341
|
+
const message = new TextEncoder().encode(canonical);
|
|
4342
|
+
const sig = await signBySuite(DISPUTE_EVIDENCE_SUITE, message, submitterPrivateKey);
|
|
4343
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4344
|
+
}
|
|
4345
|
+
async function verifyDisputeEvidence(evidence, submitterPublicKey) {
|
|
4346
|
+
if (evidence.suite !== DISPUTE_EVIDENCE_SUITE) return false;
|
|
4347
|
+
const { signature, ...body } = evidence;
|
|
4348
|
+
const canonical = canonicalJson(body);
|
|
4349
|
+
const message = new TextEncoder().encode(canonical);
|
|
4350
|
+
try {
|
|
4351
|
+
const sig = fromBase64Url(signature);
|
|
4352
|
+
return await verifyBySuite(evidence.suite, message, sig, submitterPublicKey);
|
|
4353
|
+
} catch {
|
|
4354
|
+
return false;
|
|
4355
|
+
}
|
|
4356
|
+
}
|
|
4357
|
+
async function signDisputeAppeal(appeal, appealerPrivateKey) {
|
|
4358
|
+
const body = { ...appeal, suite: DISPUTE_APPEAL_SUITE };
|
|
4359
|
+
const canonical = canonicalJson(body);
|
|
4360
|
+
const message = new TextEncoder().encode(canonical);
|
|
4361
|
+
const sig = await signBySuite(DISPUTE_APPEAL_SUITE, message, appealerPrivateKey);
|
|
4362
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4363
|
+
}
|
|
4364
|
+
async function verifyDisputeAppeal(appeal, appealerPublicKey) {
|
|
4365
|
+
if (appeal.suite !== DISPUTE_APPEAL_SUITE) return false;
|
|
4366
|
+
const { signature, ...body } = appeal;
|
|
4367
|
+
const canonical = canonicalJson(body);
|
|
4368
|
+
const message = new TextEncoder().encode(canonical);
|
|
4369
|
+
try {
|
|
4370
|
+
const sig = fromBase64Url(signature);
|
|
4371
|
+
return await verifyBySuite(appeal.suite, message, sig, appealerPublicKey);
|
|
4372
|
+
} catch {
|
|
4373
|
+
return false;
|
|
4374
|
+
}
|
|
4375
|
+
}
|
|
4376
|
+
var CONSOLIDATION_RECEIPT_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4377
|
+
async function signConsolidationReceipt(receipt, privateKey, publicKey) {
|
|
4378
|
+
const withKey = publicKey ? { ...receipt, public_key: bytesToHex3(publicKey) } : receipt;
|
|
4379
|
+
const body = { ...withKey, suite: CONSOLIDATION_RECEIPT_SUITE };
|
|
4380
|
+
const canonical = canonicalJson(body);
|
|
4381
|
+
const message = new TextEncoder().encode(canonical);
|
|
4382
|
+
const sig = await signBySuite(CONSOLIDATION_RECEIPT_SUITE, message, privateKey);
|
|
4383
|
+
return Object.freeze({ ...body, signature: toBase64Url(sig) });
|
|
4384
|
+
}
|
|
4385
|
+
async function verifyConsolidationReceipt(receipt, publicKey) {
|
|
4386
|
+
if (receipt.suite !== CONSOLIDATION_RECEIPT_SUITE) return false;
|
|
4387
|
+
const { signature, ...body } = receipt;
|
|
4388
|
+
const canonical = canonicalJson(body);
|
|
4389
|
+
const message = new TextEncoder().encode(canonical);
|
|
4390
|
+
try {
|
|
4391
|
+
const sig = fromBase64Url(signature);
|
|
4392
|
+
return await verifyBySuite(receipt.suite, message, sig, publicKey);
|
|
4393
|
+
} catch {
|
|
4394
|
+
return false;
|
|
4395
|
+
}
|
|
4396
|
+
}
|
|
4397
|
+
var BALANCE_WAIVER_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4398
|
+
async function signBalanceWaiver(waiver, agentPrivateKey) {
|
|
4399
|
+
const body = { ...waiver, suite: BALANCE_WAIVER_SUITE };
|
|
4400
|
+
const canonical = canonicalJson(body);
|
|
4401
|
+
const message = new TextEncoder().encode(canonical);
|
|
4402
|
+
const sig = await signBySuite(BALANCE_WAIVER_SUITE, message, agentPrivateKey);
|
|
4403
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4404
|
+
}
|
|
4405
|
+
async function verifyBalanceWaiver(waiver, agentPublicKey) {
|
|
4406
|
+
if (waiver.suite !== BALANCE_WAIVER_SUITE) return false;
|
|
4407
|
+
const { signature, ...body } = waiver;
|
|
4408
|
+
const canonical = canonicalJson(body);
|
|
4409
|
+
const message = new TextEncoder().encode(canonical);
|
|
4410
|
+
try {
|
|
4411
|
+
const sig = fromBase64Url(signature);
|
|
4412
|
+
return await verifyBySuite(waiver.suite, message, sig, agentPublicKey);
|
|
4413
|
+
} catch {
|
|
4414
|
+
return false;
|
|
4415
|
+
}
|
|
4416
|
+
}
|
|
4417
|
+
var SETTLEMENT_RECORD_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4418
|
+
async function signSettlement(settlement, issuerPrivateKey) {
|
|
4419
|
+
const body = { ...settlement, suite: SETTLEMENT_RECORD_SUITE };
|
|
4420
|
+
const canonical = canonicalJson(body);
|
|
4421
|
+
const message = new TextEncoder().encode(canonical);
|
|
4422
|
+
const sig = await signBySuite(SETTLEMENT_RECORD_SUITE, message, issuerPrivateKey);
|
|
4423
|
+
return { ...body, signature: toBase64Url(sig) };
|
|
4424
|
+
}
|
|
4425
|
+
async function verifySettlement(settlement, issuerPublicKey) {
|
|
4426
|
+
if (settlement.suite !== SETTLEMENT_RECORD_SUITE) return false;
|
|
4427
|
+
const { signature, ...body } = settlement;
|
|
4428
|
+
const canonical = canonicalJson(body);
|
|
4429
|
+
const message = new TextEncoder().encode(canonical);
|
|
4430
|
+
try {
|
|
4431
|
+
const sig = fromBase64Url(signature);
|
|
4432
|
+
return await verifyBySuite(settlement.suite, message, sig, issuerPublicKey);
|
|
4433
|
+
} catch {
|
|
4434
|
+
return false;
|
|
4435
|
+
}
|
|
4436
|
+
}
|
|
4437
|
+
var KEY_SUCCESSION_SUITE = "motebit-jcs-ed25519-hex-v1";
|
|
1235
4438
|
function keySuccessionPayload(oldPublicKeyHex, newPublicKeyHex, timestamp, reason, recovery) {
|
|
1236
4439
|
const obj = {
|
|
1237
4440
|
old_public_key: oldPublicKeyHex,
|
|
1238
4441
|
new_public_key: newPublicKeyHex,
|
|
1239
|
-
timestamp
|
|
4442
|
+
timestamp,
|
|
4443
|
+
suite: KEY_SUCCESSION_SUITE
|
|
1240
4444
|
};
|
|
1241
4445
|
if (reason !== void 0) {
|
|
1242
4446
|
obj.reason = reason;
|
|
@@ -1248,25 +4452,26 @@ function keySuccessionPayload(oldPublicKeyHex, newPublicKeyHex, timestamp, reaso
|
|
|
1248
4452
|
}
|
|
1249
4453
|
async function signKeySuccession(oldPrivateKey, newPrivateKey, newPublicKey, oldPublicKey, reason) {
|
|
1250
4454
|
const timestamp = Date.now();
|
|
1251
|
-
const oldPublicKeyHex =
|
|
1252
|
-
const newPublicKeyHex =
|
|
4455
|
+
const oldPublicKeyHex = bytesToHex3(oldPublicKey);
|
|
4456
|
+
const newPublicKeyHex = bytesToHex3(newPublicKey);
|
|
1253
4457
|
const payload = keySuccessionPayload(oldPublicKeyHex, newPublicKeyHex, timestamp, reason);
|
|
1254
4458
|
const message = new TextEncoder().encode(payload);
|
|
1255
|
-
const oldSig = await
|
|
1256
|
-
const newSig = await
|
|
4459
|
+
const oldSig = await signBySuite(KEY_SUCCESSION_SUITE, message, oldPrivateKey);
|
|
4460
|
+
const newSig = await signBySuite(KEY_SUCCESSION_SUITE, message, newPrivateKey);
|
|
1257
4461
|
return {
|
|
1258
4462
|
old_public_key: oldPublicKeyHex,
|
|
1259
4463
|
new_public_key: newPublicKeyHex,
|
|
1260
4464
|
timestamp,
|
|
1261
4465
|
...reason !== void 0 ? { reason } : {},
|
|
1262
|
-
|
|
1263
|
-
|
|
4466
|
+
suite: KEY_SUCCESSION_SUITE,
|
|
4467
|
+
old_key_signature: bytesToHex3(oldSig),
|
|
4468
|
+
new_key_signature: bytesToHex3(newSig)
|
|
1264
4469
|
};
|
|
1265
4470
|
}
|
|
1266
4471
|
async function signGuardianRecoverySuccession(guardianPrivateKey, newPrivateKey, oldPublicKey, newPublicKey, reason) {
|
|
1267
4472
|
const timestamp = Date.now();
|
|
1268
|
-
const oldPublicKeyHex =
|
|
1269
|
-
const newPublicKeyHex =
|
|
4473
|
+
const oldPublicKeyHex = bytesToHex3(oldPublicKey);
|
|
4474
|
+
const newPublicKeyHex = bytesToHex3(newPublicKey);
|
|
1270
4475
|
const effectiveReason = reason ?? "guardian_recovery";
|
|
1271
4476
|
const payload = keySuccessionPayload(
|
|
1272
4477
|
oldPublicKeyHex,
|
|
@@ -1276,19 +4481,21 @@ async function signGuardianRecoverySuccession(guardianPrivateKey, newPrivateKey,
|
|
|
1276
4481
|
true
|
|
1277
4482
|
);
|
|
1278
4483
|
const message = new TextEncoder().encode(payload);
|
|
1279
|
-
const guardianSig = await
|
|
1280
|
-
const newSig = await
|
|
4484
|
+
const guardianSig = await signBySuite(KEY_SUCCESSION_SUITE, message, guardianPrivateKey);
|
|
4485
|
+
const newSig = await signBySuite(KEY_SUCCESSION_SUITE, message, newPrivateKey);
|
|
1281
4486
|
return {
|
|
1282
4487
|
old_public_key: oldPublicKeyHex,
|
|
1283
4488
|
new_public_key: newPublicKeyHex,
|
|
1284
4489
|
timestamp,
|
|
1285
4490
|
reason: effectiveReason,
|
|
1286
|
-
|
|
4491
|
+
suite: KEY_SUCCESSION_SUITE,
|
|
4492
|
+
new_key_signature: bytesToHex3(newSig),
|
|
1287
4493
|
recovery: true,
|
|
1288
|
-
guardian_signature:
|
|
4494
|
+
guardian_signature: bytesToHex3(guardianSig)
|
|
1289
4495
|
};
|
|
1290
4496
|
}
|
|
1291
4497
|
async function verifyKeySuccession(record, guardianPublicKeyHex) {
|
|
4498
|
+
if (record.suite !== KEY_SUCCESSION_SUITE) return false;
|
|
1292
4499
|
const payload = keySuccessionPayload(
|
|
1293
4500
|
record.old_public_key,
|
|
1294
4501
|
record.new_public_key,
|
|
@@ -1298,20 +4505,20 @@ async function verifyKeySuccession(record, guardianPublicKeyHex) {
|
|
|
1298
4505
|
);
|
|
1299
4506
|
const message = new TextEncoder().encode(payload);
|
|
1300
4507
|
try {
|
|
1301
|
-
const newPubKey =
|
|
1302
|
-
const newSig =
|
|
1303
|
-
const newValid = await
|
|
4508
|
+
const newPubKey = hexToBytes4(record.new_public_key);
|
|
4509
|
+
const newSig = hexToBytes4(record.new_key_signature);
|
|
4510
|
+
const newValid = await verifyBySuite(record.suite, message, newSig, newPubKey);
|
|
1304
4511
|
if (!newValid) return false;
|
|
1305
4512
|
if (record.recovery) {
|
|
1306
4513
|
if (!record.guardian_signature || !guardianPublicKeyHex) return false;
|
|
1307
|
-
const guardianPubKey =
|
|
1308
|
-
const guardianSig =
|
|
1309
|
-
return await
|
|
4514
|
+
const guardianPubKey = hexToBytes4(guardianPublicKeyHex);
|
|
4515
|
+
const guardianSig = hexToBytes4(record.guardian_signature);
|
|
4516
|
+
return await verifyBySuite(record.suite, message, guardianSig, guardianPubKey);
|
|
1310
4517
|
} else {
|
|
1311
4518
|
if (!record.old_key_signature) return false;
|
|
1312
|
-
const oldPubKey =
|
|
1313
|
-
const oldSig =
|
|
1314
|
-
return await
|
|
4519
|
+
const oldPubKey = hexToBytes4(record.old_public_key);
|
|
4520
|
+
const oldSig = hexToBytes4(record.old_key_signature);
|
|
4521
|
+
return await verifyBySuite(record.suite, message, oldSig, oldPubKey);
|
|
1315
4522
|
}
|
|
1316
4523
|
} catch {
|
|
1317
4524
|
return false;
|
|
@@ -1391,34 +4598,54 @@ async function verifySuccessionChain(chain, guardianPublicKeyHex) {
|
|
|
1391
4598
|
length: chain.length
|
|
1392
4599
|
};
|
|
1393
4600
|
}
|
|
4601
|
+
var GUARDIAN_REVOCATION_SUITE = "motebit-jcs-ed25519-hex-v1";
|
|
1394
4602
|
async function signGuardianRevocation(identityPrivateKey, guardianPrivateKey, timestamp) {
|
|
1395
4603
|
const ts = timestamp ?? Date.now();
|
|
1396
|
-
const payload = canonicalJson({
|
|
4604
|
+
const payload = canonicalJson({
|
|
4605
|
+
action: "guardian_revoked",
|
|
4606
|
+
timestamp: ts,
|
|
4607
|
+
suite: GUARDIAN_REVOCATION_SUITE
|
|
4608
|
+
});
|
|
1397
4609
|
const message = new TextEncoder().encode(payload);
|
|
1398
|
-
const identitySig = await
|
|
1399
|
-
const guardianSig = await
|
|
4610
|
+
const identitySig = await signBySuite(GUARDIAN_REVOCATION_SUITE, message, identityPrivateKey);
|
|
4611
|
+
const guardianSig = await signBySuite(GUARDIAN_REVOCATION_SUITE, message, guardianPrivateKey);
|
|
1400
4612
|
return {
|
|
1401
4613
|
payload,
|
|
1402
|
-
identity_signature:
|
|
1403
|
-
guardian_signature:
|
|
4614
|
+
identity_signature: bytesToHex3(identitySig),
|
|
4615
|
+
guardian_signature: bytesToHex3(guardianSig),
|
|
1404
4616
|
timestamp: ts
|
|
1405
4617
|
};
|
|
1406
4618
|
}
|
|
1407
4619
|
async function verifyGuardianRevocation(revocation, identityPublicKeyHex, guardianPublicKeyHex) {
|
|
1408
|
-
const payload = canonicalJson({
|
|
4620
|
+
const payload = canonicalJson({
|
|
4621
|
+
action: "guardian_revoked",
|
|
4622
|
+
timestamp: revocation.timestamp,
|
|
4623
|
+
suite: GUARDIAN_REVOCATION_SUITE
|
|
4624
|
+
});
|
|
1409
4625
|
const message = new TextEncoder().encode(payload);
|
|
1410
4626
|
try {
|
|
1411
|
-
const identityPub =
|
|
1412
|
-
const guardianPub =
|
|
1413
|
-
const identitySig =
|
|
1414
|
-
const guardianSig =
|
|
1415
|
-
const identityValid = await
|
|
1416
|
-
|
|
4627
|
+
const identityPub = hexToBytes4(identityPublicKeyHex);
|
|
4628
|
+
const guardianPub = hexToBytes4(guardianPublicKeyHex);
|
|
4629
|
+
const identitySig = hexToBytes4(revocation.identity_signature);
|
|
4630
|
+
const guardianSig = hexToBytes4(revocation.guardian_signature);
|
|
4631
|
+
const identityValid = await verifyBySuite(
|
|
4632
|
+
GUARDIAN_REVOCATION_SUITE,
|
|
4633
|
+
message,
|
|
4634
|
+
identitySig,
|
|
4635
|
+
identityPub
|
|
4636
|
+
);
|
|
4637
|
+
const guardianValid = await verifyBySuite(
|
|
4638
|
+
GUARDIAN_REVOCATION_SUITE,
|
|
4639
|
+
message,
|
|
4640
|
+
guardianSig,
|
|
4641
|
+
guardianPub
|
|
4642
|
+
);
|
|
1417
4643
|
return identityValid && guardianValid;
|
|
1418
4644
|
} catch {
|
|
1419
4645
|
return false;
|
|
1420
4646
|
}
|
|
1421
4647
|
}
|
|
4648
|
+
var COLLABORATIVE_RECEIPT_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
1422
4649
|
async function signCollaborativeReceipt(receipt, initiatorPrivateKey) {
|
|
1423
4650
|
const receiptsCanonical = canonicalJson(receipt.participant_receipts);
|
|
1424
4651
|
const receiptsBytes = new TextEncoder().encode(receiptsCanonical);
|
|
@@ -1426,17 +4653,22 @@ async function signCollaborativeReceipt(receipt, initiatorPrivateKey) {
|
|
|
1426
4653
|
const sigPayload = canonicalJson({
|
|
1427
4654
|
proposal_id: receipt.proposal_id,
|
|
1428
4655
|
plan_id: receipt.plan_id,
|
|
1429
|
-
content_hash: contentHash
|
|
4656
|
+
content_hash: contentHash,
|
|
4657
|
+
suite: COLLABORATIVE_RECEIPT_SUITE
|
|
1430
4658
|
});
|
|
1431
4659
|
const sigMessage = new TextEncoder().encode(sigPayload);
|
|
1432
|
-
const sig = await
|
|
4660
|
+
const sig = await signBySuite(COLLABORATIVE_RECEIPT_SUITE, sigMessage, initiatorPrivateKey);
|
|
1433
4661
|
return {
|
|
1434
4662
|
...receipt,
|
|
1435
4663
|
content_hash: contentHash,
|
|
4664
|
+
suite: COLLABORATIVE_RECEIPT_SUITE,
|
|
1436
4665
|
initiator_signature: toBase64Url(sig)
|
|
1437
4666
|
};
|
|
1438
4667
|
}
|
|
1439
4668
|
async function verifyCollaborativeReceipt(receipt, initiatorPublicKey, participantKeys) {
|
|
4669
|
+
if (receipt.suite !== COLLABORATIVE_RECEIPT_SUITE) {
|
|
4670
|
+
return { valid: false, error: "Unknown or missing cryptosuite" };
|
|
4671
|
+
}
|
|
1440
4672
|
const receiptsCanonical = canonicalJson(receipt.participant_receipts);
|
|
1441
4673
|
const receiptsBytes = new TextEncoder().encode(receiptsCanonical);
|
|
1442
4674
|
const expectedHash = await hash(receiptsBytes);
|
|
@@ -1446,12 +4678,13 @@ async function verifyCollaborativeReceipt(receipt, initiatorPublicKey, participa
|
|
|
1446
4678
|
const sigPayload = canonicalJson({
|
|
1447
4679
|
proposal_id: receipt.proposal_id,
|
|
1448
4680
|
plan_id: receipt.plan_id,
|
|
1449
|
-
content_hash: receipt.content_hash
|
|
4681
|
+
content_hash: receipt.content_hash,
|
|
4682
|
+
suite: receipt.suite
|
|
1450
4683
|
});
|
|
1451
4684
|
const sigMessage = new TextEncoder().encode(sigPayload);
|
|
1452
4685
|
try {
|
|
1453
4686
|
const sig = fromBase64Url(receipt.initiator_signature);
|
|
1454
|
-
const sigValid = await
|
|
4687
|
+
const sigValid = await verifyBySuite(receipt.suite, sigMessage, sig, initiatorPublicKey);
|
|
1455
4688
|
if (!sigValid) {
|
|
1456
4689
|
return { valid: false, error: "Initiator signature invalid" };
|
|
1457
4690
|
}
|
|
@@ -1479,6 +4712,39 @@ async function verifyCollaborativeReceipt(receipt, initiatorPublicKey, participa
|
|
|
1479
4712
|
}
|
|
1480
4713
|
return { valid: true };
|
|
1481
4714
|
}
|
|
4715
|
+
var DEVICE_REGISTRATION_SUITE = "motebit-jcs-ed25519-b64-v1";
|
|
4716
|
+
async function signDeviceRegistration(body, privateKey) {
|
|
4717
|
+
const withSuite = { ...body, suite: DEVICE_REGISTRATION_SUITE };
|
|
4718
|
+
const canonical = canonicalJson(withSuite);
|
|
4719
|
+
const message = new TextEncoder().encode(canonical);
|
|
4720
|
+
const sig = await signBySuite(DEVICE_REGISTRATION_SUITE, message, privateKey);
|
|
4721
|
+
return { ...withSuite, signature: toBase64Url(sig) };
|
|
4722
|
+
}
|
|
4723
|
+
var DEVICE_REGISTRATION_MAX_AGE_MS = 5 * 60 * 1e3;
|
|
4724
|
+
async function verifyDeviceRegistration(body, now = Date.now()) {
|
|
4725
|
+
if (typeof body.motebit_id !== "string" || typeof body.device_id !== "string" || typeof body.public_key !== "string" || !/^[0-9a-f]{64}$/i.test(body.public_key) || typeof body.timestamp !== "number" || typeof body.suite !== "string" || typeof body.signature !== "string") {
|
|
4726
|
+
return { valid: false, reason: "malformed" };
|
|
4727
|
+
}
|
|
4728
|
+
if (Math.abs(now - body.timestamp) > DEVICE_REGISTRATION_MAX_AGE_MS) {
|
|
4729
|
+
return { valid: false, reason: "stale" };
|
|
4730
|
+
}
|
|
4731
|
+
if (body.suite !== DEVICE_REGISTRATION_SUITE) {
|
|
4732
|
+
return { valid: false, reason: "unsupported_suite" };
|
|
4733
|
+
}
|
|
4734
|
+
const { signature, ...bodyForSig } = body;
|
|
4735
|
+
const canonical = canonicalJson(bodyForSig);
|
|
4736
|
+
const message = new TextEncoder().encode(canonical);
|
|
4737
|
+
let sigBytes;
|
|
4738
|
+
let pkBytes;
|
|
4739
|
+
try {
|
|
4740
|
+
sigBytes = fromBase64Url(signature);
|
|
4741
|
+
pkBytes = hexToBytes4(body.public_key);
|
|
4742
|
+
} catch {
|
|
4743
|
+
return { valid: false, reason: "malformed" };
|
|
4744
|
+
}
|
|
4745
|
+
const ok = await verifyBySuite(body.suite, message, sigBytes, pkBytes);
|
|
4746
|
+
return ok ? { valid: true } : { valid: false, reason: "bad_signature" };
|
|
4747
|
+
}
|
|
1482
4748
|
|
|
1483
4749
|
// src/credentials.ts
|
|
1484
4750
|
function buildVerificationMethod(publicKey) {
|
|
@@ -1497,9 +4763,9 @@ async function signDataIntegrity(document, privateKey, publicKey, proofPurpose)
|
|
|
1497
4763
|
proofPurpose
|
|
1498
4764
|
};
|
|
1499
4765
|
const encoder = new TextEncoder();
|
|
1500
|
-
const proofHash = await
|
|
4766
|
+
const proofHash = await sha2563(encoder.encode(canonicalJson(proofOptions)));
|
|
1501
4767
|
const { proof: _proof, ...docWithoutProof } = document;
|
|
1502
|
-
const docHash = await
|
|
4768
|
+
const docHash = await sha2563(encoder.encode(canonicalJson(docWithoutProof)));
|
|
1503
4769
|
const combined = new Uint8Array(proofHash.length + docHash.length);
|
|
1504
4770
|
combined.set(proofHash);
|
|
1505
4771
|
combined.set(docHash, proofHash.length);
|
|
@@ -1520,9 +4786,9 @@ async function verifyDataIntegritySigning(document, proof) {
|
|
|
1520
4786
|
}
|
|
1521
4787
|
const { proofValue, ...proofOptions } = proof;
|
|
1522
4788
|
const encoder = new TextEncoder();
|
|
1523
|
-
const proofHash = await
|
|
4789
|
+
const proofHash = await sha2563(encoder.encode(canonicalJson(proofOptions)));
|
|
1524
4790
|
const { proof: _proof, ...docWithoutProof } = document;
|
|
1525
|
-
const docHash = await
|
|
4791
|
+
const docHash = await sha2563(encoder.encode(canonicalJson(docWithoutProof)));
|
|
1526
4792
|
const combined = new Uint8Array(proofHash.length + docHash.length);
|
|
1527
4793
|
combined.set(proofHash);
|
|
1528
4794
|
combined.set(docHash, proofHash.length);
|
|
@@ -1642,7 +4908,8 @@ async function issueTrustCredential(trustRecord, privateKey, publicKey, subjectD
|
|
|
1642
4908
|
successful_tasks: trustRecord.successful_tasks ?? 0,
|
|
1643
4909
|
failed_tasks: trustRecord.failed_tasks ?? 0,
|
|
1644
4910
|
first_seen_at: trustRecord.first_seen_at,
|
|
1645
|
-
last_seen_at: trustRecord.last_seen_at
|
|
4911
|
+
last_seen_at: trustRecord.last_seen_at,
|
|
4912
|
+
...trustRecord.hardware_attestation != null ? { hardware_attestation: trustRecord.hardware_attestation } : {}
|
|
1646
4913
|
};
|
|
1647
4914
|
const now = /* @__PURE__ */ new Date();
|
|
1648
4915
|
const unsignedVC = {
|
|
@@ -1668,6 +4935,7 @@ async function createPresentation(credentials, privateKey, publicKey) {
|
|
|
1668
4935
|
}
|
|
1669
4936
|
|
|
1670
4937
|
// src/credential-anchor.ts
|
|
4938
|
+
var CREDENTIAL_ANCHOR_SUITE = "motebit-jcs-ed25519-hex-v1";
|
|
1671
4939
|
function toHex(bytes) {
|
|
1672
4940
|
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1673
4941
|
}
|
|
@@ -1686,7 +4954,7 @@ function concat(a, b) {
|
|
|
1686
4954
|
}
|
|
1687
4955
|
async function computeCredentialLeaf(credential) {
|
|
1688
4956
|
const canonical = canonicalJson(credential);
|
|
1689
|
-
const hash2 = await
|
|
4957
|
+
const hash2 = await sha2563(new TextEncoder().encode(canonical));
|
|
1690
4958
|
return toHex(hash2);
|
|
1691
4959
|
}
|
|
1692
4960
|
async function verifyMerkleInclusion(leaf, index, siblings, layerSizes, expectedRoot) {
|
|
@@ -1700,7 +4968,7 @@ async function verifyMerkleInclusion(leaf, index, siblings, layerSizes, expected
|
|
|
1700
4968
|
if (sibIdx >= siblings.length) return false;
|
|
1701
4969
|
const siblingBytes = fromHex(siblings[sibIdx]);
|
|
1702
4970
|
const combined = idx % 2 === 0 ? concat(current, siblingBytes) : concat(siblingBytes, current);
|
|
1703
|
-
current = await
|
|
4971
|
+
current = await sha2563(combined);
|
|
1704
4972
|
sibIdx++;
|
|
1705
4973
|
}
|
|
1706
4974
|
idx = Math.floor(idx / 2);
|
|
@@ -1726,25 +4994,36 @@ async function verifyCredentialAnchor(credential, anchorProof, chainVerifier) {
|
|
|
1726
4994
|
if (!merkleValid) {
|
|
1727
4995
|
errors.push("Merkle proof does not reconstruct to the claimed root");
|
|
1728
4996
|
}
|
|
1729
|
-
const
|
|
1730
|
-
batch_id: anchorProof.batch_id,
|
|
1731
|
-
merkle_root: anchorProof.merkle_root,
|
|
1732
|
-
leaf_count: anchorProof.leaf_count,
|
|
1733
|
-
first_issued_at: anchorProof.first_issued_at,
|
|
1734
|
-
last_issued_at: anchorProof.last_issued_at,
|
|
1735
|
-
relay_id: anchorProof.relay_id
|
|
1736
|
-
});
|
|
1737
|
-
const payloadBytes = new TextEncoder().encode(batchPayload);
|
|
1738
|
-
const signatureBytes = hexToBytes2(anchorProof.batch_signature);
|
|
1739
|
-
const publicKeyBytes = hexToBytes2(anchorProof.relay_public_key);
|
|
4997
|
+
const suite = anchorProof.suite;
|
|
1740
4998
|
let relaySignatureValid = false;
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
}
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
4999
|
+
if (suite !== CREDENTIAL_ANCHOR_SUITE) {
|
|
5000
|
+
errors.push(`Relay batch signature: missing or unsupported suite "${String(suite)}"`);
|
|
5001
|
+
} else {
|
|
5002
|
+
const batchPayload = canonicalJson({
|
|
5003
|
+
batch_id: anchorProof.batch_id,
|
|
5004
|
+
merkle_root: anchorProof.merkle_root,
|
|
5005
|
+
leaf_count: anchorProof.leaf_count,
|
|
5006
|
+
first_issued_at: anchorProof.first_issued_at,
|
|
5007
|
+
last_issued_at: anchorProof.last_issued_at,
|
|
5008
|
+
relay_id: anchorProof.relay_id,
|
|
5009
|
+
suite
|
|
5010
|
+
});
|
|
5011
|
+
const payloadBytes = new TextEncoder().encode(batchPayload);
|
|
5012
|
+
const signatureBytes = hexToBytes4(anchorProof.batch_signature);
|
|
5013
|
+
const publicKeyBytes = hexToBytes4(anchorProof.relay_public_key);
|
|
5014
|
+
try {
|
|
5015
|
+
relaySignatureValid = await verifyBySuite(
|
|
5016
|
+
suite,
|
|
5017
|
+
payloadBytes,
|
|
5018
|
+
signatureBytes,
|
|
5019
|
+
publicKeyBytes
|
|
5020
|
+
);
|
|
5021
|
+
} catch {
|
|
5022
|
+
relaySignatureValid = false;
|
|
5023
|
+
}
|
|
5024
|
+
if (!relaySignatureValid) {
|
|
5025
|
+
errors.push("Relay batch signature verification failed");
|
|
5026
|
+
}
|
|
1748
5027
|
}
|
|
1749
5028
|
let chainVerified = null;
|
|
1750
5029
|
if (anchorProof.anchor && chainVerifier) {
|
|
@@ -1775,11 +5054,69 @@ async function verifyCredentialAnchor(credential, anchorProof, chainVerifier) {
|
|
|
1775
5054
|
errors
|
|
1776
5055
|
};
|
|
1777
5056
|
}
|
|
5057
|
+
var REVOCATION_ANCHOR_SUITE = "motebit-concat-ed25519-hex-v1";
|
|
5058
|
+
async function verifyRevocationAnchor(proof, revocationPayload, chainVerifier) {
|
|
5059
|
+
const errors = [];
|
|
5060
|
+
const expectedMemo = `motebit:revocation:v1:${proof.revoked_public_key}:${proof.timestamp}`;
|
|
5061
|
+
const memoValid = proof.revoked_public_key.length === 64 && proof.timestamp > 0;
|
|
5062
|
+
if (!memoValid) {
|
|
5063
|
+
errors.push(
|
|
5064
|
+
`Invalid revocation proof: public key length ${proof.revoked_public_key.length} (expected 64), timestamp ${proof.timestamp}`
|
|
5065
|
+
);
|
|
5066
|
+
}
|
|
5067
|
+
let relaySignatureValid = false;
|
|
5068
|
+
if (proof.suite !== REVOCATION_ANCHOR_SUITE) {
|
|
5069
|
+
errors.push(
|
|
5070
|
+
`Relay revocation signature: missing or unsupported suite "${String(proof.suite)}"`
|
|
5071
|
+
);
|
|
5072
|
+
} else {
|
|
5073
|
+
const payloadBytes = new TextEncoder().encode(revocationPayload);
|
|
5074
|
+
const signatureBytes = hexToBytes4(proof.signature);
|
|
5075
|
+
const publicKeyBytes = hexToBytes4(proof.relay_public_key);
|
|
5076
|
+
try {
|
|
5077
|
+
relaySignatureValid = await verifyBySuite(
|
|
5078
|
+
proof.suite,
|
|
5079
|
+
payloadBytes,
|
|
5080
|
+
signatureBytes,
|
|
5081
|
+
publicKeyBytes
|
|
5082
|
+
);
|
|
5083
|
+
} catch {
|
|
5084
|
+
relaySignatureValid = false;
|
|
5085
|
+
}
|
|
5086
|
+
if (!relaySignatureValid) {
|
|
5087
|
+
errors.push("Relay revocation signature verification failed");
|
|
5088
|
+
}
|
|
5089
|
+
}
|
|
5090
|
+
let chainVerified = null;
|
|
5091
|
+
if (proof.anchor && chainVerifier) {
|
|
5092
|
+
try {
|
|
5093
|
+
chainVerified = await chainVerifier({
|
|
5094
|
+
...proof.anchor,
|
|
5095
|
+
expected_memo: expectedMemo
|
|
5096
|
+
});
|
|
5097
|
+
if (!chainVerified) {
|
|
5098
|
+
errors.push("Onchain revocation anchor verification failed");
|
|
5099
|
+
}
|
|
5100
|
+
} catch (err2) {
|
|
5101
|
+
chainVerified = false;
|
|
5102
|
+
errors.push(
|
|
5103
|
+
`Onchain revocation verification error: ${err2 instanceof Error ? err2.message : String(err2)}`
|
|
5104
|
+
);
|
|
5105
|
+
}
|
|
5106
|
+
}
|
|
5107
|
+
const valid = memoValid && relaySignatureValid && (chainVerified === null || chainVerified);
|
|
5108
|
+
return {
|
|
5109
|
+
valid,
|
|
5110
|
+
steps: {
|
|
5111
|
+
memo_valid: memoValid,
|
|
5112
|
+
relay_signature_valid: relaySignatureValid,
|
|
5113
|
+
chain_verified: chainVerified
|
|
5114
|
+
},
|
|
5115
|
+
errors
|
|
5116
|
+
};
|
|
5117
|
+
}
|
|
1778
5118
|
|
|
1779
5119
|
// src/index.ts
|
|
1780
|
-
if (!hashes.sha512) {
|
|
1781
|
-
hashes.sha512 = (msg) => sha512(msg);
|
|
1782
|
-
}
|
|
1783
5120
|
function parseYamlValue(raw) {
|
|
1784
5121
|
const trimmed = raw.trim();
|
|
1785
5122
|
if (trimmed === "null") return null;
|
|
@@ -1880,7 +5217,7 @@ function parseYaml(text) {
|
|
|
1880
5217
|
}
|
|
1881
5218
|
return root;
|
|
1882
5219
|
}
|
|
1883
|
-
function
|
|
5220
|
+
function hexToBytes5(hex) {
|
|
1884
5221
|
const bytes = new Uint8Array(hex.length / 2);
|
|
1885
5222
|
for (let i = 0; i < hex.length; i += 2) {
|
|
1886
5223
|
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
|
@@ -1973,11 +5310,12 @@ function didKeyToPublicKey2(did) {
|
|
|
1973
5310
|
}
|
|
1974
5311
|
return decoded.slice(2);
|
|
1975
5312
|
}
|
|
1976
|
-
async function
|
|
5313
|
+
async function sha2564(data) {
|
|
1977
5314
|
const buf = await crypto.subtle.digest("SHA-256", data);
|
|
1978
5315
|
return new Uint8Array(buf);
|
|
1979
5316
|
}
|
|
1980
|
-
var
|
|
5317
|
+
var IDENTITY_FILE_SUITE = "motebit-jcs-ed25519-hex-v1";
|
|
5318
|
+
var SIG_PREFIX = `<!-- motebit:sig:${IDENTITY_FILE_SUITE}:`;
|
|
1981
5319
|
var SIG_SUFFIX = " -->";
|
|
1982
5320
|
function detectArtifactType(artifact) {
|
|
1983
5321
|
if (typeof artifact === "string") {
|
|
@@ -2013,7 +5351,16 @@ function parse(content) {
|
|
|
2013
5351
|
const rawFrontmatter = content.slice(bodyStart, secondDash);
|
|
2014
5352
|
const frontmatter = parseYaml(rawFrontmatter);
|
|
2015
5353
|
const sigStart = content.indexOf(SIG_PREFIX);
|
|
2016
|
-
if (sigStart === -1)
|
|
5354
|
+
if (sigStart === -1) {
|
|
5355
|
+
if (content.includes("<!-- motebit:sig:Ed25519:")) {
|
|
5356
|
+
throw new Error(
|
|
5357
|
+
`Legacy identity-file signature format detected (motebit:sig:Ed25519:). Re-sign under ${IDENTITY_FILE_SUITE} \u2014 no legacy fallback.`
|
|
5358
|
+
);
|
|
5359
|
+
}
|
|
5360
|
+
throw new Error(
|
|
5361
|
+
`Missing signature comment (expected <!-- motebit:sig:${IDENTITY_FILE_SUITE}:\u2026 -->)`
|
|
5362
|
+
);
|
|
5363
|
+
}
|
|
2017
5364
|
const sigValueStart = sigStart + SIG_PREFIX.length;
|
|
2018
5365
|
const sigEnd = content.indexOf(SIG_SUFFIX, sigValueStart);
|
|
2019
5366
|
if (sigEnd === -1) throw new Error("Malformed signature");
|
|
@@ -2037,7 +5384,7 @@ async function verifyIdentity(content) {
|
|
|
2037
5384
|
}
|
|
2038
5385
|
let pubKey;
|
|
2039
5386
|
try {
|
|
2040
|
-
pubKey =
|
|
5387
|
+
pubKey = hexToBytes5(pubKeyHex);
|
|
2041
5388
|
} catch {
|
|
2042
5389
|
return identityError("Invalid public key hex");
|
|
2043
5390
|
}
|
|
@@ -2046,7 +5393,7 @@ async function verifyIdentity(content) {
|
|
|
2046
5393
|
}
|
|
2047
5394
|
let sigBytes;
|
|
2048
5395
|
try {
|
|
2049
|
-
sigBytes =
|
|
5396
|
+
sigBytes = hexToBytes5(parsed.signature);
|
|
2050
5397
|
} catch {
|
|
2051
5398
|
return identityError("Invalid signature encoding");
|
|
2052
5399
|
}
|
|
@@ -2054,12 +5401,12 @@ async function verifyIdentity(content) {
|
|
|
2054
5401
|
return identityError("Signature must be 64 bytes");
|
|
2055
5402
|
}
|
|
2056
5403
|
const frontmatterBytes = new TextEncoder().encode(parsed.rawFrontmatter);
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
5404
|
+
const valid = await verifyBySuite(
|
|
5405
|
+
"motebit-jcs-ed25519-hex-v1",
|
|
5406
|
+
frontmatterBytes,
|
|
5407
|
+
sigBytes,
|
|
5408
|
+
pubKey
|
|
5409
|
+
);
|
|
2063
5410
|
if (!valid) {
|
|
2064
5411
|
return identityError("Signature verification failed");
|
|
2065
5412
|
}
|
|
@@ -2074,7 +5421,7 @@ async function verifyIdentity(content) {
|
|
|
2074
5421
|
const attestMessage = new TextEncoder().encode(attestPayload);
|
|
2075
5422
|
let guardianPubKey;
|
|
2076
5423
|
try {
|
|
2077
|
-
guardianPubKey =
|
|
5424
|
+
guardianPubKey = hexToBytes5(guardian.public_key);
|
|
2078
5425
|
} catch {
|
|
2079
5426
|
return identityError("Invalid guardian public key hex");
|
|
2080
5427
|
}
|
|
@@ -2083,16 +5430,16 @@ async function verifyIdentity(content) {
|
|
|
2083
5430
|
}
|
|
2084
5431
|
let attestSig;
|
|
2085
5432
|
try {
|
|
2086
|
-
attestSig =
|
|
5433
|
+
attestSig = hexToBytes5(guardian.attestation);
|
|
2087
5434
|
} catch {
|
|
2088
5435
|
return identityError("Invalid guardian attestation encoding");
|
|
2089
5436
|
}
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
5437
|
+
const attestValid = await verifyBySuite(
|
|
5438
|
+
"motebit-jcs-ed25519-hex-v1",
|
|
5439
|
+
attestMessage,
|
|
5440
|
+
attestSig,
|
|
5441
|
+
guardianPubKey
|
|
5442
|
+
);
|
|
2096
5443
|
if (!attestValid) {
|
|
2097
5444
|
return identityError("Guardian attestation signature verification failed");
|
|
2098
5445
|
}
|
|
@@ -2115,10 +5462,18 @@ async function verifySuccessionChain2(chain, currentPublicKeyHex, guardianPublic
|
|
|
2115
5462
|
try {
|
|
2116
5463
|
for (let i = 0; i < chain.length; i++) {
|
|
2117
5464
|
const record = chain[i];
|
|
5465
|
+
if (record.suite !== "motebit-jcs-ed25519-hex-v1") {
|
|
5466
|
+
return {
|
|
5467
|
+
valid: false,
|
|
5468
|
+
rotations: chain.length,
|
|
5469
|
+
error: `Succession record ${i}: missing or invalid suite (expected motebit-jcs-ed25519-hex-v1)`
|
|
5470
|
+
};
|
|
5471
|
+
}
|
|
2118
5472
|
const payloadObj = {
|
|
2119
5473
|
old_public_key: record.old_public_key,
|
|
2120
5474
|
new_public_key: record.new_public_key,
|
|
2121
|
-
timestamp: record.timestamp
|
|
5475
|
+
timestamp: record.timestamp,
|
|
5476
|
+
suite: "motebit-jcs-ed25519-hex-v1"
|
|
2122
5477
|
};
|
|
2123
5478
|
if (record.reason !== void 0) {
|
|
2124
5479
|
payloadObj.reason = record.reason;
|
|
@@ -2128,9 +5483,14 @@ async function verifySuccessionChain2(chain, currentPublicKeyHex, guardianPublic
|
|
|
2128
5483
|
}
|
|
2129
5484
|
const payload = canonicalJson2(payloadObj);
|
|
2130
5485
|
const message = new TextEncoder().encode(payload);
|
|
2131
|
-
const newPubKey =
|
|
2132
|
-
const newSig =
|
|
2133
|
-
const newValid = await
|
|
5486
|
+
const newPubKey = hexToBytes5(record.new_public_key);
|
|
5487
|
+
const newSig = hexToBytes5(record.new_key_signature);
|
|
5488
|
+
const newValid = await verifyBySuite(
|
|
5489
|
+
"motebit-jcs-ed25519-hex-v1",
|
|
5490
|
+
message,
|
|
5491
|
+
newSig,
|
|
5492
|
+
newPubKey
|
|
5493
|
+
);
|
|
2134
5494
|
if (!newValid) {
|
|
2135
5495
|
return {
|
|
2136
5496
|
valid: false,
|
|
@@ -2153,9 +5513,14 @@ async function verifySuccessionChain2(chain, currentPublicKeyHex, guardianPublic
|
|
|
2153
5513
|
error: `Succession record ${i}: guardian recovery but no guardian_signature`
|
|
2154
5514
|
};
|
|
2155
5515
|
}
|
|
2156
|
-
const guardianPubKey =
|
|
2157
|
-
const guardianSig =
|
|
2158
|
-
const guardianValid = await
|
|
5516
|
+
const guardianPubKey = hexToBytes5(guardianPublicKeyHex);
|
|
5517
|
+
const guardianSig = hexToBytes5(record.guardian_signature);
|
|
5518
|
+
const guardianValid = await verifyBySuite(
|
|
5519
|
+
"motebit-jcs-ed25519-hex-v1",
|
|
5520
|
+
message,
|
|
5521
|
+
guardianSig,
|
|
5522
|
+
guardianPubKey
|
|
5523
|
+
);
|
|
2159
5524
|
if (!guardianValid) {
|
|
2160
5525
|
return {
|
|
2161
5526
|
valid: false,
|
|
@@ -2171,9 +5536,14 @@ async function verifySuccessionChain2(chain, currentPublicKeyHex, guardianPublic
|
|
|
2171
5536
|
error: `Succession record ${i}: normal rotation but no old_key_signature`
|
|
2172
5537
|
};
|
|
2173
5538
|
}
|
|
2174
|
-
const oldPubKey =
|
|
2175
|
-
const oldSig =
|
|
2176
|
-
const oldValid = await
|
|
5539
|
+
const oldPubKey = hexToBytes5(record.old_public_key);
|
|
5540
|
+
const oldSig = hexToBytes5(record.old_key_signature);
|
|
5541
|
+
const oldValid = await verifyBySuite(
|
|
5542
|
+
"motebit-jcs-ed25519-hex-v1",
|
|
5543
|
+
message,
|
|
5544
|
+
oldSig,
|
|
5545
|
+
oldPubKey
|
|
5546
|
+
);
|
|
2177
5547
|
if (!oldValid) {
|
|
2178
5548
|
return {
|
|
2179
5549
|
valid: false,
|
|
@@ -2241,19 +5611,15 @@ async function verifyReceiptSignature(receipt, publicKey) {
|
|
|
2241
5611
|
}
|
|
2242
5612
|
const canonical = canonicalJson2(body);
|
|
2243
5613
|
const message = new TextEncoder().encode(canonical);
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
return { valid };
|
|
2247
|
-
} catch {
|
|
2248
|
-
return { valid: false, error: "Ed25519 verification threw" };
|
|
2249
|
-
}
|
|
5614
|
+
const valid = await verifyBySuite("motebit-jcs-ed25519-b64-v1", message, sig, publicKey);
|
|
5615
|
+
return { valid };
|
|
2250
5616
|
}
|
|
2251
5617
|
async function verifyReceipt(receipt) {
|
|
2252
5618
|
let publicKey = null;
|
|
2253
5619
|
let signerDid;
|
|
2254
5620
|
if (receipt.public_key) {
|
|
2255
5621
|
try {
|
|
2256
|
-
publicKey =
|
|
5622
|
+
publicKey = hexToBytes5(receipt.public_key);
|
|
2257
5623
|
if (publicKey.length === 32) {
|
|
2258
5624
|
signerDid = publicKeyToDidKey2(publicKey);
|
|
2259
5625
|
} else {
|
|
@@ -2314,9 +5680,9 @@ async function verifyDataIntegrity(document, proof) {
|
|
|
2314
5680
|
}
|
|
2315
5681
|
const { proofValue, ...proofOptions } = proof;
|
|
2316
5682
|
const encoder = new TextEncoder();
|
|
2317
|
-
const proofHash = await
|
|
5683
|
+
const proofHash = await sha2564(encoder.encode(canonicalJson2(proofOptions)));
|
|
2318
5684
|
const { proof: _proof, ...docWithoutProof } = document;
|
|
2319
|
-
const docHash = await
|
|
5685
|
+
const docHash = await sha2564(encoder.encode(canonicalJson2(docWithoutProof)));
|
|
2320
5686
|
const combined = new Uint8Array(proofHash.length + docHash.length);
|
|
2321
5687
|
combined.set(proofHash);
|
|
2322
5688
|
combined.set(docHash, proofHash.length);
|
|
@@ -2327,14 +5693,10 @@ async function verifyDataIntegrity(document, proof) {
|
|
|
2327
5693
|
} catch {
|
|
2328
5694
|
return false;
|
|
2329
5695
|
}
|
|
2330
|
-
|
|
2331
|
-
return await verifyAsync(signature, combined, publicKey);
|
|
2332
|
-
} catch {
|
|
2333
|
-
return false;
|
|
2334
|
-
}
|
|
5696
|
+
return verifyBySuite("eddsa-jcs-2022", combined, signature, publicKey);
|
|
2335
5697
|
}
|
|
2336
5698
|
var DEFAULT_CLOCK_SKEW_SECONDS = 60;
|
|
2337
|
-
async function verifyCredential(vc, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS) {
|
|
5699
|
+
async function verifyCredential(vc, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS, hardwareAttestationVerifiers) {
|
|
2338
5700
|
const errors = [];
|
|
2339
5701
|
let expired = false;
|
|
2340
5702
|
if (vc.validUntil) {
|
|
@@ -2351,6 +5713,21 @@ async function verifyCredential(vc, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECOND
|
|
|
2351
5713
|
}
|
|
2352
5714
|
const issuerDid = typeof vc.issuer === "string" ? vc.issuer : void 0;
|
|
2353
5715
|
const subjectId = vc.credentialSubject?.id;
|
|
5716
|
+
const subject = vc.credentialSubject;
|
|
5717
|
+
let hardwareAttestation;
|
|
5718
|
+
if (subject !== void 0 && subject.hardware_attestation !== void 0 && subject.hardware_attestation !== null && typeof subject.hardware_attestation === "object" && typeof subject.identity_public_key === "string") {
|
|
5719
|
+
const deviceCheckContext = {
|
|
5720
|
+
...typeof subject.motebit_id === "string" ? { expectedMotebitId: subject.motebit_id } : {},
|
|
5721
|
+
...typeof subject.device_id === "string" ? { expectedDeviceId: subject.device_id } : {},
|
|
5722
|
+
...typeof subject.attested_at === "number" ? { expectedAttestedAt: subject.attested_at } : {}
|
|
5723
|
+
};
|
|
5724
|
+
hardwareAttestation = await verifyHardwareAttestationClaim(
|
|
5725
|
+
subject.hardware_attestation,
|
|
5726
|
+
subject.identity_public_key,
|
|
5727
|
+
hardwareAttestationVerifiers,
|
|
5728
|
+
deviceCheckContext
|
|
5729
|
+
);
|
|
5730
|
+
}
|
|
2354
5731
|
return {
|
|
2355
5732
|
type: "credential",
|
|
2356
5733
|
valid: proofValid && !expired,
|
|
@@ -2358,10 +5735,11 @@ async function verifyCredential(vc, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECOND
|
|
|
2358
5735
|
issuer: issuerDid,
|
|
2359
5736
|
subject: subjectId,
|
|
2360
5737
|
expired,
|
|
5738
|
+
...hardwareAttestation && { hardware_attestation: hardwareAttestation },
|
|
2361
5739
|
...errors.length > 0 ? { errors } : {}
|
|
2362
5740
|
};
|
|
2363
5741
|
}
|
|
2364
|
-
async function verifyPresentation(vp, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS) {
|
|
5742
|
+
async function verifyPresentation(vp, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS, hardwareAttestationVerifiers) {
|
|
2365
5743
|
const errors = [];
|
|
2366
5744
|
const envelopeValid = await verifyDataIntegrity(
|
|
2367
5745
|
vp,
|
|
@@ -2373,7 +5751,7 @@ async function verifyPresentation(vp, clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECO
|
|
|
2373
5751
|
const credentialResults = [];
|
|
2374
5752
|
for (let i = 0; i < vp.verifiableCredential.length; i++) {
|
|
2375
5753
|
const vc = vp.verifiableCredential[i];
|
|
2376
|
-
const vcResult = await verifyCredential(vc, clockSkewSeconds);
|
|
5754
|
+
const vcResult = await verifyCredential(vc, clockSkewSeconds, hardwareAttestationVerifiers);
|
|
2377
5755
|
credentialResults.push(vcResult);
|
|
2378
5756
|
if (!vcResult.valid) {
|
|
2379
5757
|
errors.push({
|
|
@@ -2438,9 +5816,17 @@ async function verify(artifact, options) {
|
|
|
2438
5816
|
case "receipt":
|
|
2439
5817
|
return verifyReceipt(resolved);
|
|
2440
5818
|
case "credential":
|
|
2441
|
-
return verifyCredential(
|
|
5819
|
+
return verifyCredential(
|
|
5820
|
+
resolved,
|
|
5821
|
+
options?.clockSkewSeconds,
|
|
5822
|
+
options?.hardwareAttestation
|
|
5823
|
+
);
|
|
2442
5824
|
case "presentation":
|
|
2443
|
-
return verifyPresentation(
|
|
5825
|
+
return verifyPresentation(
|
|
5826
|
+
resolved,
|
|
5827
|
+
options?.clockSkewSeconds,
|
|
5828
|
+
options?.hardwareAttestation
|
|
5829
|
+
);
|
|
2444
5830
|
}
|
|
2445
5831
|
}
|
|
2446
5832
|
async function verifyIdentityFile(content) {
|
|
@@ -2454,60 +5840,118 @@ async function verifyIdentityFile(content) {
|
|
|
2454
5840
|
};
|
|
2455
5841
|
}
|
|
2456
5842
|
export {
|
|
5843
|
+
ADJUDICATOR_VOTE_SUITE,
|
|
5844
|
+
BALANCE_WAIVER_SUITE,
|
|
5845
|
+
COLLABORATIVE_RECEIPT_SUITE,
|
|
5846
|
+
CONSOLIDATION_RECEIPT_SUITE,
|
|
5847
|
+
DELEGATION_TOKEN_SUITE,
|
|
5848
|
+
DEVICE_REGISTRATION_MAX_AGE_MS,
|
|
5849
|
+
DEVICE_REGISTRATION_SUITE,
|
|
5850
|
+
DISPUTE_APPEAL_SUITE,
|
|
5851
|
+
DISPUTE_EVIDENCE_SUITE,
|
|
5852
|
+
DISPUTE_REQUEST_SUITE,
|
|
5853
|
+
DISPUTE_RESOLUTION_SUITE,
|
|
5854
|
+
EXECUTION_RECEIPT_SUITE,
|
|
5855
|
+
GUARDIAN_REVOCATION_SUITE,
|
|
5856
|
+
KEY_SUCCESSION_SUITE,
|
|
5857
|
+
SETTLEMENT_RECORD_SUITE,
|
|
5858
|
+
SIGNED_TOKEN_SUITE,
|
|
5859
|
+
TOOL_INVOCATION_RECEIPT_SUITE,
|
|
2457
5860
|
base58btcDecode,
|
|
2458
5861
|
base58btcEncode,
|
|
2459
|
-
|
|
5862
|
+
bytesToHex3 as bytesToHex,
|
|
2460
5863
|
canonicalJson,
|
|
5864
|
+
canonicalSecureEnclaveBodyForTest,
|
|
5865
|
+
canonicalSha256,
|
|
2461
5866
|
computeCredentialLeaf,
|
|
2462
5867
|
createPresentation,
|
|
2463
5868
|
createSignedToken,
|
|
2464
5869
|
didKeyToPublicKey,
|
|
2465
5870
|
ed25519Sign,
|
|
2466
5871
|
ed25519Verify,
|
|
5872
|
+
encodeSecureEnclaveReceiptForTest,
|
|
2467
5873
|
fromBase64Url,
|
|
5874
|
+
generateEd25519Keypair,
|
|
2468
5875
|
generateKeypair,
|
|
5876
|
+
getPublicKeyBySuite,
|
|
2469
5877
|
hash,
|
|
5878
|
+
hashToolPayload,
|
|
2470
5879
|
hexPublicKeyToDidKey,
|
|
2471
|
-
|
|
5880
|
+
hexToBytes4 as hexToBytes,
|
|
2472
5881
|
isScopeNarrowed,
|
|
2473
5882
|
issueGradientCredential,
|
|
2474
5883
|
issueReputationCredential,
|
|
2475
5884
|
issueTrustCredential,
|
|
5885
|
+
mintSecureEnclaveReceiptForTest,
|
|
2476
5886
|
parse,
|
|
2477
5887
|
parseScopeSet,
|
|
2478
5888
|
publicKeyToDidKey,
|
|
2479
|
-
sha256,
|
|
5889
|
+
sha2563 as sha256,
|
|
5890
|
+
signAdjudicatorVote,
|
|
5891
|
+
signBalanceWaiver,
|
|
5892
|
+
signBySuite,
|
|
2480
5893
|
signCollaborativeReceipt,
|
|
5894
|
+
signConsolidationReceipt,
|
|
2481
5895
|
signDelegation,
|
|
5896
|
+
signDeviceRegistration,
|
|
5897
|
+
signDisputeAppeal,
|
|
5898
|
+
signDisputeEvidence,
|
|
5899
|
+
signDisputeRequest,
|
|
5900
|
+
signDisputeResolution,
|
|
2482
5901
|
signExecutionReceipt,
|
|
2483
5902
|
signGuardianRecoverySuccession,
|
|
2484
5903
|
signGuardianRevocation,
|
|
2485
5904
|
signKeySuccession,
|
|
5905
|
+
signSettlement,
|
|
2486
5906
|
signSovereignPaymentReceipt,
|
|
5907
|
+
signToolInvocationReceipt,
|
|
2487
5908
|
signVerifiableCredential,
|
|
2488
5909
|
signVerifiablePresentation,
|
|
2489
5910
|
toBase64Url,
|
|
2490
5911
|
verify,
|
|
5912
|
+
verifyAdjudicatorVote,
|
|
5913
|
+
verifyBalanceWaiver,
|
|
5914
|
+
verifyBySuite,
|
|
2491
5915
|
verifyCollaborativeReceipt,
|
|
5916
|
+
verifyConsolidationReceipt,
|
|
2492
5917
|
verifyCredentialAnchor,
|
|
2493
5918
|
verifyDelegation,
|
|
2494
5919
|
verifyDelegationChain,
|
|
5920
|
+
verifyDeviceRegistration,
|
|
5921
|
+
verifyDisputeAppeal,
|
|
5922
|
+
verifyDisputeEvidence,
|
|
5923
|
+
verifyDisputeRequest,
|
|
5924
|
+
verifyDisputeResolution,
|
|
2495
5925
|
verifyExecutionReceipt,
|
|
5926
|
+
verifyExecutionReceiptDetailed,
|
|
2496
5927
|
verifyGuardianRevocation,
|
|
5928
|
+
verifyHardwareAttestationClaim,
|
|
2497
5929
|
verifyIdentityFile,
|
|
2498
5930
|
verifyKeySuccession,
|
|
2499
5931
|
verifyReceiptChain,
|
|
2500
5932
|
verifyReceiptSequence,
|
|
5933
|
+
verifyRevocationAnchor,
|
|
5934
|
+
verifySettlement,
|
|
2501
5935
|
verifySignedToken,
|
|
2502
5936
|
verifySuccessionChain,
|
|
5937
|
+
verifyToolInvocationReceipt,
|
|
2503
5938
|
verifyVerifiableCredential,
|
|
2504
5939
|
verifyVerifiablePresentation
|
|
2505
5940
|
};
|
|
2506
5941
|
/*! Bundled license information:
|
|
2507
5942
|
|
|
2508
|
-
@noble/
|
|
2509
|
-
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
2510
|
-
|
|
5943
|
+
@noble/hashes/esm/utils.js:
|
|
2511
5944
|
@noble/hashes/esm/utils.js:
|
|
2512
5945
|
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
5946
|
+
|
|
5947
|
+
@noble/curves/esm/abstract/utils.js:
|
|
5948
|
+
@noble/curves/esm/abstract/modular.js:
|
|
5949
|
+
@noble/curves/esm/abstract/curve.js:
|
|
5950
|
+
@noble/curves/esm/abstract/weierstrass.js:
|
|
5951
|
+
@noble/curves/esm/_shortw_utils.js:
|
|
5952
|
+
@noble/curves/esm/p256.js:
|
|
5953
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
5954
|
+
|
|
5955
|
+
@noble/ed25519/index.js:
|
|
5956
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
2513
5957
|
*/
|