@bankofai/wallet-cli-gasfree-plugin 0.0.0-stage → 0.1.0-next.1
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 +21 -0
- package/README.md +53 -2
- package/dist/THIRD_PARTY_LICENSES.txt +73 -0
- package/dist/index.mjs +4582 -0
- package/package.json +58 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,4582 @@
|
|
|
1
|
+
import { createRequire as __pluginRequire } from "node:module"; const require = __pluginRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// packages/gasfree/adapters/outbound/gasfree/client.ts
|
|
4
|
+
import { createHmac } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
// node_modules/lossless-json/lib/esm/utils.js
|
|
7
|
+
function isInteger(value) {
|
|
8
|
+
return INTEGER_REGEX.test(value);
|
|
9
|
+
}
|
|
10
|
+
var INTEGER_REGEX = /^-?[0-9]+$/;
|
|
11
|
+
function isNumber(value) {
|
|
12
|
+
return NUMBER_REGEX.test(value);
|
|
13
|
+
}
|
|
14
|
+
var NUMBER_REGEX = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
15
|
+
function isSafeNumber(value, config2) {
|
|
16
|
+
if (isInteger(value)) {
|
|
17
|
+
return Number.isSafeInteger(Number.parseInt(value, 10));
|
|
18
|
+
}
|
|
19
|
+
const num = Number.parseFloat(value);
|
|
20
|
+
const parsed = String(num);
|
|
21
|
+
if (value === parsed) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
const valueDigits = extractSignificantDigits(value);
|
|
25
|
+
const parsedDigits = extractSignificantDigits(parsed);
|
|
26
|
+
if (valueDigits === parsedDigits) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
if (config2?.approx === true) {
|
|
30
|
+
const requiredDigits = 14;
|
|
31
|
+
if (!isInteger(value) && parsedDigits.length >= requiredDigits && valueDigits.startsWith(parsedDigits.substring(0, requiredDigits))) {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
var UnsafeNumberReason = /* @__PURE__ */ (function(UnsafeNumberReason2) {
|
|
38
|
+
UnsafeNumberReason2["underflow"] = "underflow";
|
|
39
|
+
UnsafeNumberReason2["overflow"] = "overflow";
|
|
40
|
+
UnsafeNumberReason2["truncate_integer"] = "truncate_integer";
|
|
41
|
+
UnsafeNumberReason2["truncate_float"] = "truncate_float";
|
|
42
|
+
return UnsafeNumberReason2;
|
|
43
|
+
})({});
|
|
44
|
+
function getUnsafeNumberReason(value) {
|
|
45
|
+
if (isSafeNumber(value, {
|
|
46
|
+
approx: false
|
|
47
|
+
})) {
|
|
48
|
+
return void 0;
|
|
49
|
+
}
|
|
50
|
+
if (isInteger(value)) {
|
|
51
|
+
return UnsafeNumberReason.truncate_integer;
|
|
52
|
+
}
|
|
53
|
+
const num = Number.parseFloat(value);
|
|
54
|
+
if (!Number.isFinite(num)) {
|
|
55
|
+
return UnsafeNumberReason.overflow;
|
|
56
|
+
}
|
|
57
|
+
if (num === 0) {
|
|
58
|
+
return UnsafeNumberReason.underflow;
|
|
59
|
+
}
|
|
60
|
+
return UnsafeNumberReason.truncate_float;
|
|
61
|
+
}
|
|
62
|
+
function extractSignificantDigits(value) {
|
|
63
|
+
const {
|
|
64
|
+
start,
|
|
65
|
+
end
|
|
66
|
+
} = getSignificantDigitRange(value);
|
|
67
|
+
const digits = value.substring(start, end);
|
|
68
|
+
const dot = digits.indexOf(".");
|
|
69
|
+
if (dot === -1) {
|
|
70
|
+
return digits;
|
|
71
|
+
}
|
|
72
|
+
return digits.substring(0, dot) + digits.substring(dot + 1);
|
|
73
|
+
}
|
|
74
|
+
function getSignificantDigitRange(value) {
|
|
75
|
+
let start = 0;
|
|
76
|
+
if (value[0] === "-") {
|
|
77
|
+
start++;
|
|
78
|
+
}
|
|
79
|
+
while (value[start] === "0" || value[start] === ".") {
|
|
80
|
+
start++;
|
|
81
|
+
}
|
|
82
|
+
let end = value.lastIndexOf("e");
|
|
83
|
+
if (end === -1) {
|
|
84
|
+
end = value.lastIndexOf("E");
|
|
85
|
+
}
|
|
86
|
+
if (end === -1) {
|
|
87
|
+
end = value.length;
|
|
88
|
+
}
|
|
89
|
+
while ((value[end - 1] === "0" || value[end - 1] === ".") && end > start) {
|
|
90
|
+
end--;
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
start,
|
|
94
|
+
end
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// node_modules/lossless-json/lib/esm/LosslessNumber.js
|
|
99
|
+
var LosslessNumber = class {
|
|
100
|
+
// numeric value as string
|
|
101
|
+
// type information
|
|
102
|
+
isLosslessNumber = true;
|
|
103
|
+
constructor(value) {
|
|
104
|
+
if (!isNumber(value)) {
|
|
105
|
+
throw new Error(`Invalid number (value: "${value}")`);
|
|
106
|
+
}
|
|
107
|
+
this.value = value;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get the value of the LosslessNumber as number or bigint.
|
|
111
|
+
*
|
|
112
|
+
* - a number is returned for safe numbers and decimal values that only lose some insignificant digits
|
|
113
|
+
* - a bigint is returned for big integer numbers
|
|
114
|
+
* - an Error is thrown for values that will overflow or underflow
|
|
115
|
+
*
|
|
116
|
+
* Note that you can implement your own strategy for conversion by just getting the value as string
|
|
117
|
+
* via .toString(), and using util functions like isInteger, isSafeNumber, getUnsafeNumberReason,
|
|
118
|
+
* and toSafeNumberOrThrow to convert it to a numeric value.
|
|
119
|
+
*/
|
|
120
|
+
valueOf() {
|
|
121
|
+
const unsafeReason = getUnsafeNumberReason(this.value);
|
|
122
|
+
if (unsafeReason === void 0 || unsafeReason === UnsafeNumberReason.truncate_float) {
|
|
123
|
+
return Number.parseFloat(this.value);
|
|
124
|
+
}
|
|
125
|
+
if (isInteger(this.value)) {
|
|
126
|
+
return BigInt(this.value);
|
|
127
|
+
}
|
|
128
|
+
throw new Error(`Cannot safely convert to number: the value '${this.value}' would ${unsafeReason} and become ${Number.parseFloat(this.value)}`);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Get the value of the LosslessNumber as string.
|
|
132
|
+
*/
|
|
133
|
+
toString() {
|
|
134
|
+
return this.value;
|
|
135
|
+
}
|
|
136
|
+
// Note: we do NOT implement a .toJSON() method, and you should not implement
|
|
137
|
+
// or use that, it cannot safely turn the numeric value in the string into
|
|
138
|
+
// stringified JSON since it has to be parsed into a number first.
|
|
139
|
+
};
|
|
140
|
+
function isLosslessNumber(value) {
|
|
141
|
+
return value && typeof value === "object" && value.isLosslessNumber || false;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// node_modules/lossless-json/lib/esm/numberParsers.js
|
|
145
|
+
function parseLosslessNumber(value) {
|
|
146
|
+
return new LosslessNumber(value);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// node_modules/lossless-json/lib/esm/revive.js
|
|
150
|
+
function revive(json, reviver) {
|
|
151
|
+
return reviveValue({
|
|
152
|
+
"": json
|
|
153
|
+
}, "", json, reviver);
|
|
154
|
+
}
|
|
155
|
+
function reviveValue(context, key, value, reviver) {
|
|
156
|
+
if (Array.isArray(value)) {
|
|
157
|
+
return reviver.call(context, key, reviveArray(value, reviver));
|
|
158
|
+
}
|
|
159
|
+
if (value && typeof value === "object" && !isLosslessNumber(value)) {
|
|
160
|
+
return reviver.call(context, key, reviveObject(value, reviver));
|
|
161
|
+
}
|
|
162
|
+
return reviver.call(context, key, value);
|
|
163
|
+
}
|
|
164
|
+
function reviveObject(object2, reviver) {
|
|
165
|
+
for (const key of Object.keys(object2)) {
|
|
166
|
+
const value = reviveValue(object2, key, object2[key], reviver);
|
|
167
|
+
if (value !== void 0) {
|
|
168
|
+
object2[key] = value;
|
|
169
|
+
} else {
|
|
170
|
+
delete object2[key];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return object2;
|
|
174
|
+
}
|
|
175
|
+
function reviveArray(array2, reviver) {
|
|
176
|
+
for (let i = 0; i < array2.length; i++) {
|
|
177
|
+
array2[i] = reviveValue(array2, String(i), array2[i], reviver);
|
|
178
|
+
}
|
|
179
|
+
return array2;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// node_modules/lossless-json/lib/esm/parse.js
|
|
183
|
+
function parse(text2, reviver, options) {
|
|
184
|
+
const optionsObj = typeof options === "function" ? {
|
|
185
|
+
parseNumber: options
|
|
186
|
+
} : options;
|
|
187
|
+
const parseNumber = optionsObj?.parseNumber ?? parseLosslessNumber;
|
|
188
|
+
const onDuplicateKey = optionsObj?.onDuplicateKey ?? throwDuplicateKey;
|
|
189
|
+
let i = 0;
|
|
190
|
+
const value = parseValue();
|
|
191
|
+
expectValue(value);
|
|
192
|
+
expectEndOfInput();
|
|
193
|
+
return reviver ? revive(value, reviver) : value;
|
|
194
|
+
function parseObject() {
|
|
195
|
+
if (text2.charCodeAt(i) === codeOpeningBrace) {
|
|
196
|
+
i++;
|
|
197
|
+
skipWhitespace();
|
|
198
|
+
const object2 = {};
|
|
199
|
+
let initial = true;
|
|
200
|
+
while (i < text2.length && text2.charCodeAt(i) !== codeClosingBrace) {
|
|
201
|
+
if (!initial) {
|
|
202
|
+
eatComma();
|
|
203
|
+
skipWhitespace();
|
|
204
|
+
} else {
|
|
205
|
+
initial = false;
|
|
206
|
+
}
|
|
207
|
+
const start = i;
|
|
208
|
+
const key = parseString();
|
|
209
|
+
if (key === void 0) {
|
|
210
|
+
throwObjectKeyExpected();
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
skipWhitespace();
|
|
214
|
+
eatColon();
|
|
215
|
+
const value2 = parseValue();
|
|
216
|
+
if (value2 === void 0) {
|
|
217
|
+
throwObjectValueExpected();
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (Object.prototype.hasOwnProperty.call(object2, key) && !isDeepEqual(value2, object2[key])) {
|
|
221
|
+
const returnedValue = onDuplicateKey({
|
|
222
|
+
key,
|
|
223
|
+
position: start + 1,
|
|
224
|
+
oldValue: object2[key],
|
|
225
|
+
newValue: value2
|
|
226
|
+
});
|
|
227
|
+
if (returnedValue !== void 0) {
|
|
228
|
+
object2[key] = returnedValue;
|
|
229
|
+
}
|
|
230
|
+
} else {
|
|
231
|
+
object2[key] = value2;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (text2.charCodeAt(i) !== codeClosingBrace) {
|
|
235
|
+
throwObjectKeyOrEndExpected();
|
|
236
|
+
}
|
|
237
|
+
i++;
|
|
238
|
+
return object2;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function parseArray() {
|
|
242
|
+
if (text2.charCodeAt(i) === codeOpeningBracket) {
|
|
243
|
+
i++;
|
|
244
|
+
skipWhitespace();
|
|
245
|
+
const array2 = [];
|
|
246
|
+
let initial = true;
|
|
247
|
+
while (i < text2.length && text2.charCodeAt(i) !== codeClosingBracket) {
|
|
248
|
+
if (!initial) {
|
|
249
|
+
eatComma();
|
|
250
|
+
} else {
|
|
251
|
+
initial = false;
|
|
252
|
+
}
|
|
253
|
+
const value2 = parseValue();
|
|
254
|
+
expectArrayItem(value2);
|
|
255
|
+
array2.push(value2);
|
|
256
|
+
}
|
|
257
|
+
if (text2.charCodeAt(i) !== codeClosingBracket) {
|
|
258
|
+
throwArrayItemOrEndExpected();
|
|
259
|
+
}
|
|
260
|
+
i++;
|
|
261
|
+
return array2;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function parseValue() {
|
|
265
|
+
skipWhitespace();
|
|
266
|
+
const value2 = parseString() ?? parseNumeric() ?? parseObject() ?? parseArray() ?? parseKeyword("true", true) ?? parseKeyword("false", false) ?? parseKeyword("null", null);
|
|
267
|
+
skipWhitespace();
|
|
268
|
+
return value2;
|
|
269
|
+
}
|
|
270
|
+
function parseKeyword(name, value2) {
|
|
271
|
+
if (text2.slice(i, i + name.length) === name) {
|
|
272
|
+
i += name.length;
|
|
273
|
+
return value2;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function skipWhitespace() {
|
|
277
|
+
while (isWhitespace(text2.charCodeAt(i))) {
|
|
278
|
+
i++;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
function parseString() {
|
|
282
|
+
if (text2.charCodeAt(i) === codeDoubleQuote) {
|
|
283
|
+
i++;
|
|
284
|
+
let result = "";
|
|
285
|
+
while (i < text2.length && text2.charCodeAt(i) !== codeDoubleQuote) {
|
|
286
|
+
if (text2.charCodeAt(i) === codeBackslash) {
|
|
287
|
+
const char = text2[i + 1];
|
|
288
|
+
const escapeChar = escapeCharacters[char];
|
|
289
|
+
if (escapeChar !== void 0) {
|
|
290
|
+
result += escapeChar;
|
|
291
|
+
i++;
|
|
292
|
+
} else if (char === "u") {
|
|
293
|
+
if (isHex(text2.charCodeAt(i + 2)) && isHex(text2.charCodeAt(i + 3)) && isHex(text2.charCodeAt(i + 4)) && isHex(text2.charCodeAt(i + 5))) {
|
|
294
|
+
result += String.fromCharCode(Number.parseInt(text2.slice(i + 2, i + 6), 16));
|
|
295
|
+
i += 5;
|
|
296
|
+
} else {
|
|
297
|
+
throwInvalidUnicodeCharacter(i);
|
|
298
|
+
}
|
|
299
|
+
} else {
|
|
300
|
+
throwInvalidEscapeCharacter(i);
|
|
301
|
+
}
|
|
302
|
+
} else {
|
|
303
|
+
if (isValidStringCharacter(text2.charCodeAt(i))) {
|
|
304
|
+
result += text2[i];
|
|
305
|
+
} else {
|
|
306
|
+
throwInvalidCharacter(text2[i]);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
i++;
|
|
310
|
+
}
|
|
311
|
+
expectEndOfString();
|
|
312
|
+
i++;
|
|
313
|
+
return result;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
function parseNumeric() {
|
|
317
|
+
const start = i;
|
|
318
|
+
if (text2.charCodeAt(i) === codeMinus) {
|
|
319
|
+
i++;
|
|
320
|
+
expectDigit(start);
|
|
321
|
+
}
|
|
322
|
+
if (text2.charCodeAt(i) === codeZero) {
|
|
323
|
+
i++;
|
|
324
|
+
} else if (isNonZeroDigit(text2.charCodeAt(i))) {
|
|
325
|
+
i++;
|
|
326
|
+
while (isDigit(text2.charCodeAt(i))) {
|
|
327
|
+
i++;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (text2.charCodeAt(i) === codeDot) {
|
|
331
|
+
i++;
|
|
332
|
+
expectDigit(start);
|
|
333
|
+
while (isDigit(text2.charCodeAt(i))) {
|
|
334
|
+
i++;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (text2.charCodeAt(i) === codeLowercaseE || text2.charCodeAt(i) === codeUppercaseE) {
|
|
338
|
+
i++;
|
|
339
|
+
if (text2.charCodeAt(i) === codeMinus || text2.charCodeAt(i) === codePlus) {
|
|
340
|
+
i++;
|
|
341
|
+
}
|
|
342
|
+
expectDigit(start);
|
|
343
|
+
while (isDigit(text2.charCodeAt(i))) {
|
|
344
|
+
i++;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (i > start) {
|
|
348
|
+
return parseNumber(text2.slice(start, i));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
function eatComma() {
|
|
352
|
+
if (text2.charCodeAt(i) !== codeComma) {
|
|
353
|
+
throw new SyntaxError(`Comma ',' expected after value ${gotAt()}`);
|
|
354
|
+
}
|
|
355
|
+
i++;
|
|
356
|
+
}
|
|
357
|
+
function eatColon() {
|
|
358
|
+
if (text2.charCodeAt(i) !== codeColon) {
|
|
359
|
+
throw new SyntaxError(`Colon ':' expected after property name ${gotAt()}`);
|
|
360
|
+
}
|
|
361
|
+
i++;
|
|
362
|
+
}
|
|
363
|
+
function expectValue(value2) {
|
|
364
|
+
if (value2 === void 0) {
|
|
365
|
+
throw new SyntaxError(`JSON value expected ${gotAt()}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function expectArrayItem(value2) {
|
|
369
|
+
if (value2 === void 0) {
|
|
370
|
+
throw new SyntaxError(`Array item expected ${gotAt()}`);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
function expectEndOfInput() {
|
|
374
|
+
if (i < text2.length) {
|
|
375
|
+
throw new SyntaxError(`Expected end of input ${gotAt()}`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
function expectDigit(start) {
|
|
379
|
+
if (!isDigit(text2.charCodeAt(i))) {
|
|
380
|
+
const numSoFar = text2.slice(start, i);
|
|
381
|
+
throw new SyntaxError(`Invalid number '${numSoFar}', expecting a digit ${gotAt()}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
function expectEndOfString() {
|
|
385
|
+
if (text2.charCodeAt(i) !== codeDoubleQuote) {
|
|
386
|
+
throw new SyntaxError(`End of string '"' expected ${gotAt()}`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function throwObjectKeyExpected() {
|
|
390
|
+
throw new SyntaxError(`Quoted object key expected ${gotAt()}`);
|
|
391
|
+
}
|
|
392
|
+
function throwDuplicateKey(_ref) {
|
|
393
|
+
let {
|
|
394
|
+
key,
|
|
395
|
+
position
|
|
396
|
+
} = _ref;
|
|
397
|
+
throw new SyntaxError(`Duplicate key '${key}' encountered at position ${position}`);
|
|
398
|
+
}
|
|
399
|
+
function throwObjectKeyOrEndExpected() {
|
|
400
|
+
throw new SyntaxError(`Quoted object key or end of object '}' expected ${gotAt()}`);
|
|
401
|
+
}
|
|
402
|
+
function throwArrayItemOrEndExpected() {
|
|
403
|
+
throw new SyntaxError(`Array item or end of array ']' expected ${gotAt()}`);
|
|
404
|
+
}
|
|
405
|
+
function throwInvalidCharacter(char) {
|
|
406
|
+
throw new SyntaxError(`Invalid character '${char}' ${pos()}`);
|
|
407
|
+
}
|
|
408
|
+
function throwInvalidEscapeCharacter(start) {
|
|
409
|
+
const chars = text2.slice(start, start + 2);
|
|
410
|
+
throw new SyntaxError(`Invalid escape character '${chars}' ${pos()}`);
|
|
411
|
+
}
|
|
412
|
+
function throwObjectValueExpected() {
|
|
413
|
+
throw new SyntaxError(`Object value expected after ':' ${pos()}`);
|
|
414
|
+
}
|
|
415
|
+
function throwInvalidUnicodeCharacter(start) {
|
|
416
|
+
const chars = text2.slice(start, start + 6);
|
|
417
|
+
throw new SyntaxError(`Invalid unicode character '${chars}' ${pos()}`);
|
|
418
|
+
}
|
|
419
|
+
function pos() {
|
|
420
|
+
return `at position ${i}`;
|
|
421
|
+
}
|
|
422
|
+
function got() {
|
|
423
|
+
return i < text2.length ? `but got '${text2[i]}'` : "but reached end of input";
|
|
424
|
+
}
|
|
425
|
+
function gotAt() {
|
|
426
|
+
return `${got()} ${pos()}`;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
function isWhitespace(code) {
|
|
430
|
+
return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;
|
|
431
|
+
}
|
|
432
|
+
function isHex(code) {
|
|
433
|
+
return code >= codeZero && code <= codeNine || code >= codeUppercaseA && code <= codeUppercaseF || code >= codeLowercaseA && code <= codeLowercaseF;
|
|
434
|
+
}
|
|
435
|
+
function isDigit(code) {
|
|
436
|
+
return code >= codeZero && code <= codeNine;
|
|
437
|
+
}
|
|
438
|
+
function isNonZeroDigit(code) {
|
|
439
|
+
return code >= codeOne && code <= codeNine;
|
|
440
|
+
}
|
|
441
|
+
function isValidStringCharacter(code) {
|
|
442
|
+
return code >= 32 && code <= 1114111;
|
|
443
|
+
}
|
|
444
|
+
function isDeepEqual(a, b) {
|
|
445
|
+
if (a === b) {
|
|
446
|
+
return true;
|
|
447
|
+
}
|
|
448
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
449
|
+
return a.length === b.length && a.every((item, index) => isDeepEqual(item, b[index]));
|
|
450
|
+
}
|
|
451
|
+
if (isObject(a) && isObject(b)) {
|
|
452
|
+
const keys = [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])];
|
|
453
|
+
return keys.every((key) => isDeepEqual(a[key], b[key]));
|
|
454
|
+
}
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
function isObject(value) {
|
|
458
|
+
return typeof value === "object" && value !== null;
|
|
459
|
+
}
|
|
460
|
+
var escapeCharacters = {
|
|
461
|
+
'"': '"',
|
|
462
|
+
"\\": "\\",
|
|
463
|
+
"/": "/",
|
|
464
|
+
b: "\b",
|
|
465
|
+
f: "\f",
|
|
466
|
+
n: "\n",
|
|
467
|
+
r: "\r",
|
|
468
|
+
t: " "
|
|
469
|
+
// note that \u is handled separately in parseString()
|
|
470
|
+
};
|
|
471
|
+
var codeBackslash = 92;
|
|
472
|
+
var codeOpeningBrace = 123;
|
|
473
|
+
var codeClosingBrace = 125;
|
|
474
|
+
var codeOpeningBracket = 91;
|
|
475
|
+
var codeClosingBracket = 93;
|
|
476
|
+
var codeSpace = 32;
|
|
477
|
+
var codeNewline = 10;
|
|
478
|
+
var codeTab = 9;
|
|
479
|
+
var codeReturn = 13;
|
|
480
|
+
var codeDoubleQuote = 34;
|
|
481
|
+
var codePlus = 43;
|
|
482
|
+
var codeMinus = 45;
|
|
483
|
+
var codeZero = 48;
|
|
484
|
+
var codeOne = 49;
|
|
485
|
+
var codeNine = 57;
|
|
486
|
+
var codeComma = 44;
|
|
487
|
+
var codeDot = 46;
|
|
488
|
+
var codeColon = 58;
|
|
489
|
+
var codeUppercaseA = 65;
|
|
490
|
+
var codeLowercaseA = 97;
|
|
491
|
+
var codeUppercaseE = 69;
|
|
492
|
+
var codeLowercaseE = 101;
|
|
493
|
+
var codeUppercaseF = 70;
|
|
494
|
+
var codeLowercaseF = 102;
|
|
495
|
+
|
|
496
|
+
// node_modules/lossless-json/lib/esm/stringify.js
|
|
497
|
+
function stringify(value, replacer, space, numberStringifiers) {
|
|
498
|
+
const resolvedSpace = resolveSpace(space);
|
|
499
|
+
const replacedValue = typeof replacer === "function" ? replacer.call({
|
|
500
|
+
"": value
|
|
501
|
+
}, "", value) : value;
|
|
502
|
+
return stringifyValue(replacedValue, "");
|
|
503
|
+
function stringifyValue(value2, indent) {
|
|
504
|
+
if (Array.isArray(numberStringifiers)) {
|
|
505
|
+
const stringifier = numberStringifiers.find((item) => item.test(value2));
|
|
506
|
+
if (stringifier) {
|
|
507
|
+
const str = stringifier.stringify(value2);
|
|
508
|
+
if (typeof str !== "string" || !isNumber(str)) {
|
|
509
|
+
throw new Error(`Invalid JSON number: output of a number stringifier must be a string containing a JSON number (output: ${str})`);
|
|
510
|
+
}
|
|
511
|
+
return str;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
if (typeof value2 === "boolean" || typeof value2 === "number" || typeof value2 === "string" || value2 === null || value2 instanceof Date || value2 instanceof Boolean || value2 instanceof Number || value2 instanceof String) {
|
|
515
|
+
return JSON.stringify(value2);
|
|
516
|
+
}
|
|
517
|
+
if (value2?.isLosslessNumber) {
|
|
518
|
+
return value2.toString();
|
|
519
|
+
}
|
|
520
|
+
if (typeof value2 === "bigint") {
|
|
521
|
+
return value2.toString();
|
|
522
|
+
}
|
|
523
|
+
if (Array.isArray(value2)) {
|
|
524
|
+
return stringifyArray(value2, indent);
|
|
525
|
+
}
|
|
526
|
+
if (value2 && typeof value2 === "object") {
|
|
527
|
+
return stringifyObject(value2, indent);
|
|
528
|
+
}
|
|
529
|
+
return void 0;
|
|
530
|
+
}
|
|
531
|
+
function stringifyArray(array2, indent) {
|
|
532
|
+
if (array2.length === 0) {
|
|
533
|
+
return "[]";
|
|
534
|
+
}
|
|
535
|
+
const childIndent = resolvedSpace ? indent + resolvedSpace : void 0;
|
|
536
|
+
let str = resolvedSpace ? "[\n" : "[";
|
|
537
|
+
for (let i = 0; i < array2.length; i++) {
|
|
538
|
+
const item = typeof replacer === "function" ? replacer.call(array2, String(i), array2[i]) : array2[i];
|
|
539
|
+
if (resolvedSpace) {
|
|
540
|
+
str += childIndent;
|
|
541
|
+
}
|
|
542
|
+
if (typeof item !== "undefined" && typeof item !== "function") {
|
|
543
|
+
str += stringifyValue(item, childIndent);
|
|
544
|
+
} else {
|
|
545
|
+
str += "null";
|
|
546
|
+
}
|
|
547
|
+
if (i < array2.length - 1) {
|
|
548
|
+
str += resolvedSpace ? ",\n" : ",";
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
str += resolvedSpace ? `
|
|
552
|
+
${indent}]` : "]";
|
|
553
|
+
return str;
|
|
554
|
+
}
|
|
555
|
+
function stringifyObject(object2, indent) {
|
|
556
|
+
if (typeof object2.toJSON === "function") {
|
|
557
|
+
return stringify(object2.toJSON(), replacer, space, void 0);
|
|
558
|
+
}
|
|
559
|
+
const keys = Array.isArray(replacer) ? replacer.map(String) : Object.keys(object2);
|
|
560
|
+
if (keys.length === 0) {
|
|
561
|
+
return "{}";
|
|
562
|
+
}
|
|
563
|
+
const childIndent = resolvedSpace ? indent + resolvedSpace : void 0;
|
|
564
|
+
let first = true;
|
|
565
|
+
let str = resolvedSpace ? "{\n" : "{";
|
|
566
|
+
for (const key of keys) {
|
|
567
|
+
const value2 = typeof replacer === "function" ? replacer.call(object2, key, object2[key]) : object2[key];
|
|
568
|
+
if (includeProperty(key, value2)) {
|
|
569
|
+
if (first) {
|
|
570
|
+
first = false;
|
|
571
|
+
} else {
|
|
572
|
+
str += resolvedSpace ? ",\n" : ",";
|
|
573
|
+
}
|
|
574
|
+
const keyStr = JSON.stringify(key);
|
|
575
|
+
str += resolvedSpace ? `${childIndent + keyStr}: ` : `${keyStr}:`;
|
|
576
|
+
str += stringifyValue(value2, childIndent);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
str += resolvedSpace ? `
|
|
580
|
+
${indent}}` : "}";
|
|
581
|
+
return str;
|
|
582
|
+
}
|
|
583
|
+
function includeProperty(_key, value2) {
|
|
584
|
+
return typeof value2 !== "undefined" && typeof value2 !== "function" && typeof value2 !== "symbol";
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
function resolveSpace(space) {
|
|
588
|
+
if (typeof space === "number") {
|
|
589
|
+
return " ".repeat(space);
|
|
590
|
+
}
|
|
591
|
+
if (typeof space === "string" && space !== "") {
|
|
592
|
+
return space;
|
|
593
|
+
}
|
|
594
|
+
return void 0;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// packages/gasfree/adapters/outbound/gasfree/client.ts
|
|
598
|
+
import {
|
|
599
|
+
ChainError,
|
|
600
|
+
networkBlock,
|
|
601
|
+
normalizeTxHash,
|
|
602
|
+
TransportError,
|
|
603
|
+
TronAddress,
|
|
604
|
+
UsageError
|
|
605
|
+
} from "@tron-walletcli/plugin-sdk/domain";
|
|
606
|
+
import { requestJson } from "@tron-walletcli/plugin-sdk/http";
|
|
607
|
+
|
|
608
|
+
// shared/domain/network.ts
|
|
609
|
+
import {
|
|
610
|
+
isTronNetwork
|
|
611
|
+
} from "@tron-walletcli/plugin-sdk/domain";
|
|
612
|
+
var GASFREE_NETWORK_DEFAULTS = {
|
|
613
|
+
"tron:728126428": {
|
|
614
|
+
baseUrl: "https://open.gasfree.io",
|
|
615
|
+
apiPrefix: "/tron",
|
|
616
|
+
controllerChainId: "728126428",
|
|
617
|
+
verifyingContract: "TFFAMQLZybALaLb4uxHA9RBE7pxhUAjF3U"
|
|
618
|
+
},
|
|
619
|
+
"tron:3448148188": {
|
|
620
|
+
baseUrl: "https://open-test.gasfree.io",
|
|
621
|
+
apiPrefix: "/nile",
|
|
622
|
+
controllerChainId: "3448148188",
|
|
623
|
+
verifyingContract: "THQGuFzL87ZqhxkgqYEryRAd7gqFqL5rdc"
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
function gasfreeNetworkConfig(network, block) {
|
|
627
|
+
if (!isTronNetwork(network)) return void 0;
|
|
628
|
+
if (block.present) return block.value;
|
|
629
|
+
return Object.hasOwn(GASFREE_NETWORK_DEFAULTS, network.id) ? GASFREE_NETWORK_DEFAULTS[network.id] : void 0;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// packages/gasfree/adapters/outbound/gasfree/client.ts
|
|
633
|
+
var MAX_BYTES = 1024 * 1024;
|
|
634
|
+
var ADDRESS = new TronAddress();
|
|
635
|
+
var STATES = /* @__PURE__ */ new Set(["WAITING", "INPROGRESS", "CONFIRMING", "SUCCEED", "FAILED"]);
|
|
636
|
+
var SECONDS_TIMESTAMP_LIMIT = 100000000000n;
|
|
637
|
+
var GasFreeClient = class {
|
|
638
|
+
constructor(config2, guard, fetchImpl = globalThis.fetch, clock = () => Date.now()) {
|
|
639
|
+
this.config = config2;
|
|
640
|
+
this.guard = guard;
|
|
641
|
+
this.fetchImpl = fetchImpl;
|
|
642
|
+
this.clock = clock;
|
|
643
|
+
}
|
|
644
|
+
config;
|
|
645
|
+
guard;
|
|
646
|
+
fetchImpl;
|
|
647
|
+
clock;
|
|
648
|
+
async listTokens(network, check) {
|
|
649
|
+
const data = object(
|
|
650
|
+
await this.#request(network, "GET", "/api/v1/config/token/all", check),
|
|
651
|
+
"data"
|
|
652
|
+
);
|
|
653
|
+
return array(data.tokens, "data.tokens").map((entry, index) => {
|
|
654
|
+
const item = object(entry, `data.tokens[${index}]`);
|
|
655
|
+
const symbol = optionalText(item.symbol, 32, `data.tokens[${index}].symbol`);
|
|
656
|
+
return {
|
|
657
|
+
tokenAddress: address(item.tokenAddress, `data.tokens[${index}].tokenAddress`),
|
|
658
|
+
activateFee: uint(item.activateFee, `data.tokens[${index}].activateFee`),
|
|
659
|
+
transferFee: uint(item.transferFee, `data.tokens[${index}].transferFee`),
|
|
660
|
+
...symbol === void 0 ? {} : { symbol },
|
|
661
|
+
...item.decimals === void 0 ? {} : { decimals: smallUInt(item.decimals, `data.tokens[${index}].decimals`, 255) }
|
|
662
|
+
};
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
async listProviders(network, check) {
|
|
666
|
+
const data = object(
|
|
667
|
+
await this.#request(network, "GET", "/api/v1/config/provider/all", check),
|
|
668
|
+
"data"
|
|
669
|
+
);
|
|
670
|
+
return array(data.providers, "data.providers").map((entry, index) => {
|
|
671
|
+
const item = object(entry, `data.providers[${index}]`);
|
|
672
|
+
const providerConfig = object(item.config, `data.providers[${index}].config`);
|
|
673
|
+
return {
|
|
674
|
+
address: address(item.address, `data.providers[${index}].address`),
|
|
675
|
+
defaultDeadlineDuration: uint(
|
|
676
|
+
providerConfig.defaultDeadlineDuration,
|
|
677
|
+
`data.providers[${index}].config.defaultDeadlineDuration`
|
|
678
|
+
),
|
|
679
|
+
...typeof item.default === "boolean" ? { isDefault: item.default } : {}
|
|
680
|
+
};
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
async getAddress(network, ownerAddress, check) {
|
|
684
|
+
if (!ADDRESS.validate(ownerAddress)) {
|
|
685
|
+
throw new UsageError("invalid_value", "ownerAddress must be a valid TRON address");
|
|
686
|
+
}
|
|
687
|
+
const data = object(
|
|
688
|
+
await this.#request(
|
|
689
|
+
network,
|
|
690
|
+
"GET",
|
|
691
|
+
`/api/v1/address/${encodeURIComponent(ownerAddress)}`,
|
|
692
|
+
check
|
|
693
|
+
),
|
|
694
|
+
"data"
|
|
695
|
+
);
|
|
696
|
+
return {
|
|
697
|
+
ownerAddress,
|
|
698
|
+
gasFreeAddress: address(data.gasFreeAddress, "data.gasFreeAddress"),
|
|
699
|
+
active: boolean(data.active, "data.active"),
|
|
700
|
+
nonce: uint(data.nonce, "data.nonce"),
|
|
701
|
+
...typeof data.allowSubmit === "boolean" ? { allowSubmit: data.allowSubmit } : {},
|
|
702
|
+
assets: array(data.assets, "data.assets").map((entry, index) => {
|
|
703
|
+
const item = object(entry, `data.assets[${index}]`);
|
|
704
|
+
return {
|
|
705
|
+
tokenAddress: address(item.tokenAddress, `data.assets[${index}].tokenAddress`),
|
|
706
|
+
activateFee: uint(item.activateFee, `data.assets[${index}].activateFee`),
|
|
707
|
+
transferFee: uint(item.transferFee, `data.assets[${index}].transferFee`)
|
|
708
|
+
};
|
|
709
|
+
})
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
async submitTransfer(network, authorization, check) {
|
|
713
|
+
this.guard.assertAllowed();
|
|
714
|
+
const body = {
|
|
715
|
+
token: authorization.token,
|
|
716
|
+
serviceProvider: authorization.serviceProvider,
|
|
717
|
+
user: authorization.user,
|
|
718
|
+
receiver: authorization.receiver,
|
|
719
|
+
value: new LosslessNumber(authorization.value),
|
|
720
|
+
maxFee: new LosslessNumber(authorization.maxFee),
|
|
721
|
+
deadline: new LosslessNumber(authorization.deadline),
|
|
722
|
+
version: new LosslessNumber(authorization.version),
|
|
723
|
+
nonce: new LosslessNumber(authorization.nonce),
|
|
724
|
+
sig: authorization.sig
|
|
725
|
+
};
|
|
726
|
+
return transferRecord(
|
|
727
|
+
await this.#request(network, "POST", "/api/v1/gasfree/submit", check, body)
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
async trace(network, traceId, check) {
|
|
731
|
+
const normalized = traceIdentifier(traceId);
|
|
732
|
+
return transferRecord(
|
|
733
|
+
await this.#request(
|
|
734
|
+
network,
|
|
735
|
+
"GET",
|
|
736
|
+
`/api/v1/gasfree/${encodeURIComponent(normalized)}`,
|
|
737
|
+
check
|
|
738
|
+
)
|
|
739
|
+
);
|
|
740
|
+
}
|
|
741
|
+
async #request(network, method, suffix, check, body) {
|
|
742
|
+
const metadata = endpoint(
|
|
743
|
+
network,
|
|
744
|
+
gasfreeNetworkConfig(network, networkBlock(network, "gasfree"))
|
|
745
|
+
);
|
|
746
|
+
const credentials = this.#credentials();
|
|
747
|
+
const path = `${metadata.apiPrefix}${suffix}`;
|
|
748
|
+
const timestamp = String(Math.floor(this.clock() / 1e3));
|
|
749
|
+
const signature = createHmac("sha256", credentials.apiSecret).update(`${method}${path}${timestamp}`, "utf8").digest("base64");
|
|
750
|
+
const encoded = body === void 0 ? void 0 : stringify(body);
|
|
751
|
+
if (encoded !== void 0 && Buffer.byteLength(encoded, "utf8") > MAX_BYTES) {
|
|
752
|
+
throw new UsageError("invalid_value", "GasFree request exceeds the 1 MiB limit");
|
|
753
|
+
}
|
|
754
|
+
const { body: decoded } = await requestJson(
|
|
755
|
+
this.fetchImpl,
|
|
756
|
+
`${metadata.baseUrl}${path}`,
|
|
757
|
+
{
|
|
758
|
+
method,
|
|
759
|
+
headers: {
|
|
760
|
+
Timestamp: timestamp,
|
|
761
|
+
Authorization: `ApiKey ${credentials.apiKey}:${signature}`,
|
|
762
|
+
Accept: "application/json",
|
|
763
|
+
...encoded === void 0 ? {} : { "content-type": "application/json" }
|
|
764
|
+
},
|
|
765
|
+
body: encoded,
|
|
766
|
+
referrerPolicy: "no-referrer",
|
|
767
|
+
cache: "no-store"
|
|
768
|
+
},
|
|
769
|
+
{
|
|
770
|
+
service: "GasFree service",
|
|
771
|
+
check,
|
|
772
|
+
maxBytes: MAX_BYTES,
|
|
773
|
+
parse: (text2) => normalizeLossless(parse(text2)),
|
|
774
|
+
refuse: httpError,
|
|
775
|
+
errors: GASFREE_ERRORS
|
|
776
|
+
}
|
|
777
|
+
);
|
|
778
|
+
return unwrap(decoded);
|
|
779
|
+
}
|
|
780
|
+
#credentials() {
|
|
781
|
+
const apiKey = this.config.credential("gasfreeApiKey");
|
|
782
|
+
const apiSecret = this.config.credential("gasfreeApiSecret");
|
|
783
|
+
if (!apiKey || !apiSecret) {
|
|
784
|
+
throw new UsageError(
|
|
785
|
+
"gasfree_credentials_missing",
|
|
786
|
+
"GasFree credentials are incomplete; configure gasfreeApiKey and gasfreeApiSecret"
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
return { apiKey, apiSecret };
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
function endpoint(network, value) {
|
|
793
|
+
if (!value) {
|
|
794
|
+
throw new UsageError("unsupported_network", `network ${network.id} does not support GasFree`);
|
|
795
|
+
}
|
|
796
|
+
let url;
|
|
797
|
+
try {
|
|
798
|
+
url = new URL(value.baseUrl);
|
|
799
|
+
} catch {
|
|
800
|
+
throw new UsageError("invalid_config", "GasFree baseUrl is invalid");
|
|
801
|
+
}
|
|
802
|
+
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
|
803
|
+
throw new UsageError(
|
|
804
|
+
"invalid_config",
|
|
805
|
+
"GasFree baseUrl must be an HTTPS origin without credentials, path, query, or fragment"
|
|
806
|
+
);
|
|
807
|
+
}
|
|
808
|
+
if (!/^\/[a-z0-9-]+$/.test(value.apiPrefix)) {
|
|
809
|
+
throw new UsageError("invalid_config", "GasFree apiPrefix must be one absolute path segment");
|
|
810
|
+
}
|
|
811
|
+
return { baseUrl: url.origin, apiPrefix: value.apiPrefix };
|
|
812
|
+
}
|
|
813
|
+
var GASFREE_ERRORS = {
|
|
814
|
+
timeout: () => new ChainError("timeout", "GasFree request did not finish in time"),
|
|
815
|
+
unreachable: () => new TransportError("provider_error", "GasFree service request failed"),
|
|
816
|
+
tooLarge: () => new ChainError("provider_error", "GasFree response exceeds the 1 MiB limit"),
|
|
817
|
+
malformed: () => new ChainError("provider_error", "GasFree service returned malformed JSON")
|
|
818
|
+
};
|
|
819
|
+
function httpError(response) {
|
|
820
|
+
if (response.status === 401 || response.status === 403) {
|
|
821
|
+
return new ChainError("gasfree_auth_failed", "GasFree credentials were rejected", {
|
|
822
|
+
status: response.status
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
if (response.status === 404) {
|
|
826
|
+
return new ChainError("not_found", "GasFree resource was not found", {
|
|
827
|
+
status: 404
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
if (response.status >= 500) {
|
|
831
|
+
return new TransportError("provider_error", `GasFree service returned HTTP ${response.status}`);
|
|
832
|
+
}
|
|
833
|
+
return new ChainError("gasfree_rejected", `GasFree service returned HTTP ${response.status}`, {
|
|
834
|
+
status: response.status
|
|
835
|
+
});
|
|
836
|
+
}
|
|
837
|
+
function unwrap(value) {
|
|
838
|
+
const root = object(value, "response");
|
|
839
|
+
const code = smallUInt(root.code, "code", 999999);
|
|
840
|
+
if (code !== 200) {
|
|
841
|
+
throw new ChainError("gasfree_rejected", "GasFree service rejected the request", { code });
|
|
842
|
+
}
|
|
843
|
+
if (root.data === null || root.data === void 0) {
|
|
844
|
+
throw new ChainError("not_found", "GasFree resource was not found");
|
|
845
|
+
}
|
|
846
|
+
return root.data;
|
|
847
|
+
}
|
|
848
|
+
function transferRecord(value) {
|
|
849
|
+
const data = object(value, "data");
|
|
850
|
+
const state = text(data.state, "data.state", 32);
|
|
851
|
+
if (!STATES.has(state)) throw invalid("data.state", "a known GasFree state");
|
|
852
|
+
return {
|
|
853
|
+
id: traceIdentifier(text(data.id, "data.id", 128)),
|
|
854
|
+
state,
|
|
855
|
+
tokenAddress: address(data.tokenAddress, "data.tokenAddress"),
|
|
856
|
+
providerAddress: address(data.providerAddress, "data.providerAddress"),
|
|
857
|
+
accountAddress: address(data.accountAddress, "data.accountAddress"),
|
|
858
|
+
gasFreeAddress: address(data.gasFreeAddress, "data.gasFreeAddress"),
|
|
859
|
+
targetAddress: address(data.targetAddress, "data.targetAddress"),
|
|
860
|
+
amount: uint(data.amount, "data.amount"),
|
|
861
|
+
nonce: uint(data.nonce, "data.nonce"),
|
|
862
|
+
...data.expiredAt === void 0 || data.expiredAt === null ? {} : { expiredAt: milliseconds(uint(data.expiredAt, "data.expiredAt")) },
|
|
863
|
+
...optionalUintFields(data, [
|
|
864
|
+
"maxFee",
|
|
865
|
+
"estimatedTransferFee",
|
|
866
|
+
"estimatedActivateFee",
|
|
867
|
+
"estimatedTotalFee",
|
|
868
|
+
"estimatedTotalCost",
|
|
869
|
+
"txnAmount",
|
|
870
|
+
"txnTransferFee",
|
|
871
|
+
"txnActivateFee",
|
|
872
|
+
"txnTotalFee",
|
|
873
|
+
"txnTotalCost",
|
|
874
|
+
"txnBlockNum",
|
|
875
|
+
"txnBlockTimestamp"
|
|
876
|
+
]),
|
|
877
|
+
...data.txnHash === void 0 || data.txnHash === null ? {} : { txnHash: transactionHash(data.txnHash) },
|
|
878
|
+
...data.txnState === void 0 || data.txnState === null ? {} : { txnState: text(data.txnState, "data.txnState", 64) },
|
|
879
|
+
...data.failureReason === void 0 || data.failureReason === null ? {} : {
|
|
880
|
+
failureReason: text(data.failureReason, "data.failureReason", 256)
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
function optionalUintFields(data, fields) {
|
|
885
|
+
return Object.fromEntries(
|
|
886
|
+
fields.filter((field) => data[field] !== void 0 && data[field] !== null).map((field) => [field, uint(data[field], `data.${field}`)])
|
|
887
|
+
);
|
|
888
|
+
}
|
|
889
|
+
function milliseconds(timestamp) {
|
|
890
|
+
const value = BigInt(timestamp);
|
|
891
|
+
return (value < SECONDS_TIMESTAMP_LIMIT ? value * 1000n : value).toString();
|
|
892
|
+
}
|
|
893
|
+
function transactionHash(value) {
|
|
894
|
+
const result = normalizeTxHash("tron", text(value, "data.txnHash", 66));
|
|
895
|
+
if (result === void 0) throw invalid("data.txnHash", "a 32-byte transaction hash");
|
|
896
|
+
return result;
|
|
897
|
+
}
|
|
898
|
+
function traceIdentifier(value) {
|
|
899
|
+
const normalized = value.trim();
|
|
900
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(normalized)) {
|
|
901
|
+
throw new UsageError("invalid_value", "traceId contains unsupported characters");
|
|
902
|
+
}
|
|
903
|
+
return normalized;
|
|
904
|
+
}
|
|
905
|
+
function address(value, field) {
|
|
906
|
+
const result = text(value, field, 64);
|
|
907
|
+
if (!ADDRESS.validate(result)) throw invalid(field, "a valid TRON address");
|
|
908
|
+
return result;
|
|
909
|
+
}
|
|
910
|
+
function boolean(value, field) {
|
|
911
|
+
if (typeof value !== "boolean") throw invalid(field, "a boolean");
|
|
912
|
+
return value;
|
|
913
|
+
}
|
|
914
|
+
function uint(value, field) {
|
|
915
|
+
let result;
|
|
916
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0) {
|
|
917
|
+
result = String(value);
|
|
918
|
+
} else if (typeof value === "string" && /^(0|[1-9]\d*)$/.test(value)) {
|
|
919
|
+
result = value;
|
|
920
|
+
} else {
|
|
921
|
+
throw invalid(field, "an unsigned decimal integer");
|
|
922
|
+
}
|
|
923
|
+
if (result.length > 78 || BigInt(result) >= 1n << 256n) {
|
|
924
|
+
throw invalid(field, "an unsigned uint256 decimal integer");
|
|
925
|
+
}
|
|
926
|
+
return result;
|
|
927
|
+
}
|
|
928
|
+
function smallUInt(value, field, maximum) {
|
|
929
|
+
const parsed = Number(uint(value, field));
|
|
930
|
+
if (!Number.isSafeInteger(parsed) || parsed > maximum) {
|
|
931
|
+
throw invalid(field, `an integer no greater than ${maximum}`);
|
|
932
|
+
}
|
|
933
|
+
return parsed;
|
|
934
|
+
}
|
|
935
|
+
function text(value, field, maximum) {
|
|
936
|
+
if (typeof value !== "string" || value.length === 0 || value.length > maximum || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
937
|
+
throw invalid(field, `non-empty text no longer than ${maximum} characters`);
|
|
938
|
+
}
|
|
939
|
+
return value;
|
|
940
|
+
}
|
|
941
|
+
function optionalText(value, maximum, field) {
|
|
942
|
+
return value === void 0 || value === null ? void 0 : text(value, field, maximum);
|
|
943
|
+
}
|
|
944
|
+
function object(value, field) {
|
|
945
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
946
|
+
throw invalid(field, "an object");
|
|
947
|
+
}
|
|
948
|
+
return value;
|
|
949
|
+
}
|
|
950
|
+
function array(value, field) {
|
|
951
|
+
if (!Array.isArray(value) || value.length > 1e3) {
|
|
952
|
+
throw invalid(field, "an array with at most 1000 entries");
|
|
953
|
+
}
|
|
954
|
+
return value;
|
|
955
|
+
}
|
|
956
|
+
function invalid(field, expected) {
|
|
957
|
+
return new ChainError("provider_error", `GasFree ${field} must be ${expected}`);
|
|
958
|
+
}
|
|
959
|
+
function normalizeLossless(value) {
|
|
960
|
+
if (isLosslessNumber(value)) {
|
|
961
|
+
const exact = value.toString();
|
|
962
|
+
const numeric = Number(exact);
|
|
963
|
+
return Number.isSafeInteger(numeric) ? numeric : exact;
|
|
964
|
+
}
|
|
965
|
+
if (Array.isArray(value)) return value.map(normalizeLossless);
|
|
966
|
+
if (value && typeof value === "object") {
|
|
967
|
+
return Object.fromEntries(
|
|
968
|
+
Object.entries(value).map(([key, item]) => [key, normalizeLossless(item)])
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
return value;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
// node_modules/@noble/hashes/utils.js
|
|
975
|
+
function isBytes(a) {
|
|
976
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
|
|
977
|
+
}
|
|
978
|
+
var atitle = (title) => title ? `"${title}" ` : "";
|
|
979
|
+
function anumber(n, title = "") {
|
|
980
|
+
if (typeof n !== "number")
|
|
981
|
+
throw new TypeError(atitle(title) + "expected number, got " + typeof n);
|
|
982
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
983
|
+
throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
|
|
984
|
+
return n;
|
|
985
|
+
}
|
|
986
|
+
function abool(value, title = "") {
|
|
987
|
+
if (typeof value !== "boolean")
|
|
988
|
+
throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value);
|
|
989
|
+
return value;
|
|
990
|
+
}
|
|
991
|
+
function abytes(value, length, title = "") {
|
|
992
|
+
if (isBytes(value) && (length === void 0 || value.length === length))
|
|
993
|
+
return value;
|
|
994
|
+
if (length !== void 0)
|
|
995
|
+
anumber(length, "length");
|
|
996
|
+
const bytes = isBytes(value);
|
|
997
|
+
const ofLen = length !== void 0 ? ` of length ${length}` : "";
|
|
998
|
+
const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
|
|
999
|
+
const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
|
|
1000
|
+
if (!bytes)
|
|
1001
|
+
throw new TypeError(message);
|
|
1002
|
+
throw new RangeError(message);
|
|
1003
|
+
}
|
|
1004
|
+
function ahash(h) {
|
|
1005
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
1006
|
+
throw new TypeError("expected hash wrapped by utils.createHasher");
|
|
1007
|
+
anumber(h.outputLen);
|
|
1008
|
+
anumber(h.blockLen);
|
|
1009
|
+
if (h.outputLen < 1 || h.blockLen < 1)
|
|
1010
|
+
throw new Error("hash blockLen / outputLen must be >= 1");
|
|
1011
|
+
}
|
|
1012
|
+
var aobject = (value, label) => {
|
|
1013
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
1014
|
+
throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
|
|
1015
|
+
};
|
|
1016
|
+
var aopts = (value, label) => {
|
|
1017
|
+
aobject(value, label);
|
|
1018
|
+
const proto = Object.getPrototypeOf(value);
|
|
1019
|
+
if (proto !== Object.prototype && proto !== null)
|
|
1020
|
+
throw new TypeError(`"${label}" expected plain object`);
|
|
1021
|
+
if (Object.hasOwn(value, "__proto__"))
|
|
1022
|
+
throw new TypeError(`"${label}.__proto__" is not allowed`);
|
|
1023
|
+
};
|
|
1024
|
+
function aexists(instance, checkFinished = true) {
|
|
1025
|
+
if (instance.destroyed)
|
|
1026
|
+
throw new Error("hash was destroyed");
|
|
1027
|
+
if (checkFinished && instance.finished)
|
|
1028
|
+
throw new Error("digest() was already called");
|
|
1029
|
+
}
|
|
1030
|
+
function aoutput(out, instance) {
|
|
1031
|
+
abytes(out, void 0, "output");
|
|
1032
|
+
const min = instance.outputLen;
|
|
1033
|
+
if (!(out.length >= min)) {
|
|
1034
|
+
throw new RangeError('"output" expected length >= ' + min);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
function u32(arr) {
|
|
1038
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
1039
|
+
}
|
|
1040
|
+
function clean(...arrays) {
|
|
1041
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
1042
|
+
arrays[i].fill(0);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
function createView(arr) {
|
|
1046
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
1047
|
+
}
|
|
1048
|
+
function rotr(word, shift) {
|
|
1049
|
+
return word << 32 - shift | word >>> shift;
|
|
1050
|
+
}
|
|
1051
|
+
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
1052
|
+
function byteSwap(word) {
|
|
1053
|
+
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
|
|
1054
|
+
}
|
|
1055
|
+
function byteSwap32(arr) {
|
|
1056
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1057
|
+
arr[i] = byteSwap(arr[i]);
|
|
1058
|
+
}
|
|
1059
|
+
return arr;
|
|
1060
|
+
}
|
|
1061
|
+
var swap32IfBE = isLE ? (u) => u : byteSwap32;
|
|
1062
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
1063
|
+
// @ts-ignore
|
|
1064
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
1065
|
+
))();
|
|
1066
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
1067
|
+
function bytesToHex(bytes) {
|
|
1068
|
+
abytes(bytes);
|
|
1069
|
+
if (hasHexBuiltin)
|
|
1070
|
+
return bytes.toHex();
|
|
1071
|
+
let hex = "";
|
|
1072
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
1073
|
+
hex += hexes[bytes[i]];
|
|
1074
|
+
}
|
|
1075
|
+
return hex;
|
|
1076
|
+
}
|
|
1077
|
+
function asciiToBase16(ch) {
|
|
1078
|
+
return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
|
|
1079
|
+
}
|
|
1080
|
+
function hexToBytes(hex) {
|
|
1081
|
+
if (typeof hex !== "string")
|
|
1082
|
+
throw new TypeError("hex string expected, got " + typeof hex);
|
|
1083
|
+
if (hasHexBuiltin) {
|
|
1084
|
+
try {
|
|
1085
|
+
return Uint8Array.fromHex(hex);
|
|
1086
|
+
} catch (error) {
|
|
1087
|
+
if (error instanceof SyntaxError)
|
|
1088
|
+
throw new RangeError(error.message);
|
|
1089
|
+
throw error;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
const hl = hex.length;
|
|
1093
|
+
const al = hl / 2;
|
|
1094
|
+
if (hl % 2)
|
|
1095
|
+
throw new RangeError("hex string expected, got unpadded hex of length " + hl);
|
|
1096
|
+
const array2 = new Uint8Array(al);
|
|
1097
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
1098
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
1099
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
1100
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
1101
|
+
const char = hex[hi] + hex[hi + 1];
|
|
1102
|
+
throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
1103
|
+
}
|
|
1104
|
+
array2[ai] = n1 * 16 + n2;
|
|
1105
|
+
}
|
|
1106
|
+
return array2;
|
|
1107
|
+
}
|
|
1108
|
+
function concatBytes(...arrays) {
|
|
1109
|
+
let sum = 0;
|
|
1110
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
1111
|
+
const a = arrays[i];
|
|
1112
|
+
abytes(a);
|
|
1113
|
+
sum += a.length;
|
|
1114
|
+
}
|
|
1115
|
+
const res = new Uint8Array(sum);
|
|
1116
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
1117
|
+
const a = arrays[i];
|
|
1118
|
+
res.set(a, pad);
|
|
1119
|
+
pad += a.length;
|
|
1120
|
+
}
|
|
1121
|
+
return res;
|
|
1122
|
+
}
|
|
1123
|
+
function checkOpts(defaults, opts, title = "opts") {
|
|
1124
|
+
aopts(defaults, "defaults");
|
|
1125
|
+
if (opts !== void 0)
|
|
1126
|
+
aopts(opts, title);
|
|
1127
|
+
const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
|
|
1128
|
+
return merged;
|
|
1129
|
+
}
|
|
1130
|
+
function createHasher(hashCons, info = {}) {
|
|
1131
|
+
if (typeof hashCons !== "function")
|
|
1132
|
+
throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
|
|
1133
|
+
info = checkOpts({}, info, "info");
|
|
1134
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
1135
|
+
const tmp = hashCons(void 0);
|
|
1136
|
+
hashC.outputLen = tmp.outputLen;
|
|
1137
|
+
hashC.blockLen = tmp.blockLen;
|
|
1138
|
+
hashC.canXOF = tmp.canXOF;
|
|
1139
|
+
hashC.create = (opts) => hashCons(opts);
|
|
1140
|
+
Object.assign(hashC, info);
|
|
1141
|
+
return Object.freeze(hashC);
|
|
1142
|
+
}
|
|
1143
|
+
function randomBytes(bytesLength = 32) {
|
|
1144
|
+
anumber(bytesLength, "bytesLength");
|
|
1145
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
1146
|
+
if (typeof cr?.getRandomValues !== "function")
|
|
1147
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
1148
|
+
if (bytesLength > 65536)
|
|
1149
|
+
throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
|
|
1150
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
1151
|
+
}
|
|
1152
|
+
var oidNist = (suffix) => ({
|
|
1153
|
+
// Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
|
|
1154
|
+
// Larger suffix values would need base-128 OID encoding and a different length byte.
|
|
1155
|
+
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
// packages/gasfree/application/use-cases/gasfree-service.ts
|
|
1159
|
+
import {
|
|
1160
|
+
assertSubmitAdmitted,
|
|
1161
|
+
DeadlineExpiredError,
|
|
1162
|
+
requestDispatchCheck,
|
|
1163
|
+
sleepWithin,
|
|
1164
|
+
submitDispatchCheck,
|
|
1165
|
+
waitsForConfirmation
|
|
1166
|
+
} from "@tron-walletcli/plugin-sdk/application";
|
|
1167
|
+
import {
|
|
1168
|
+
assertPositiveAmount,
|
|
1169
|
+
ChainError as ChainError2,
|
|
1170
|
+
CliError as CliError2,
|
|
1171
|
+
errorMessage,
|
|
1172
|
+
matchTokenSymbol,
|
|
1173
|
+
networkBlock as networkBlock2,
|
|
1174
|
+
toBaseUnits,
|
|
1175
|
+
TransportError as TransportError2,
|
|
1176
|
+
UsageError as UsageError2
|
|
1177
|
+
} from "@tron-walletcli/plugin-sdk/domain";
|
|
1178
|
+
|
|
1179
|
+
// node_modules/@noble/hashes/_u64.js
|
|
1180
|
+
var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
|
|
1181
|
+
var _32n = /* @__PURE__ */ BigInt(32);
|
|
1182
|
+
function fromBig(n, le = false) {
|
|
1183
|
+
if (le)
|
|
1184
|
+
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
|
|
1185
|
+
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
1186
|
+
}
|
|
1187
|
+
function split(lst, le = false) {
|
|
1188
|
+
const len = lst.length;
|
|
1189
|
+
let Ah = new Uint32Array(len);
|
|
1190
|
+
let Al = new Uint32Array(len);
|
|
1191
|
+
for (let i = 0; i < len; i++) {
|
|
1192
|
+
const { h, l } = fromBig(lst[i], le);
|
|
1193
|
+
[Ah[i], Al[i]] = [h, l];
|
|
1194
|
+
}
|
|
1195
|
+
return [Ah, Al];
|
|
1196
|
+
}
|
|
1197
|
+
var fromNumH = (n) => n / 2 ** 32 | 0;
|
|
1198
|
+
var fromNumL = (n) => n >>> 0;
|
|
1199
|
+
function setU64FromNum(view, byteOffset, n, isLE2) {
|
|
1200
|
+
const h = fromNumH(n);
|
|
1201
|
+
const l = fromNumL(n);
|
|
1202
|
+
view.setUint32(byteOffset, isLE2 ? l : h, isLE2);
|
|
1203
|
+
view.setUint32(byteOffset + 4, isLE2 ? h : l, isLE2);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
// node_modules/@noble/hashes/_md.js
|
|
1207
|
+
function Chi(a, b, c) {
|
|
1208
|
+
return a & b ^ ~a & c;
|
|
1209
|
+
}
|
|
1210
|
+
function Maj(a, b, c) {
|
|
1211
|
+
return a & b ^ a & c ^ b & c;
|
|
1212
|
+
}
|
|
1213
|
+
var HashMD = class {
|
|
1214
|
+
blockLen;
|
|
1215
|
+
outputLen;
|
|
1216
|
+
canXOF = false;
|
|
1217
|
+
padOffset;
|
|
1218
|
+
isLE;
|
|
1219
|
+
// For partial updates less than block size
|
|
1220
|
+
buffer;
|
|
1221
|
+
view;
|
|
1222
|
+
finished = false;
|
|
1223
|
+
length = 0;
|
|
1224
|
+
pos = 0;
|
|
1225
|
+
destroyed = false;
|
|
1226
|
+
constructor(blockLen, outputLen, padOffset, isLE2) {
|
|
1227
|
+
this.blockLen = blockLen;
|
|
1228
|
+
this.outputLen = outputLen;
|
|
1229
|
+
this.padOffset = padOffset;
|
|
1230
|
+
this.isLE = isLE2;
|
|
1231
|
+
this.buffer = new Uint8Array(blockLen);
|
|
1232
|
+
this.view = createView(this.buffer);
|
|
1233
|
+
}
|
|
1234
|
+
update(data) {
|
|
1235
|
+
aexists(this);
|
|
1236
|
+
abytes(data);
|
|
1237
|
+
const { view, buffer, blockLen } = this;
|
|
1238
|
+
const len = data.length;
|
|
1239
|
+
let processed = false;
|
|
1240
|
+
for (let pos = 0; pos < len; ) {
|
|
1241
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
1242
|
+
if (take === blockLen) {
|
|
1243
|
+
const dataView = createView(data);
|
|
1244
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
1245
|
+
this.process(dataView, pos);
|
|
1246
|
+
processed = true;
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
|
|
1250
|
+
this.pos += take;
|
|
1251
|
+
pos += take;
|
|
1252
|
+
if (this.pos === blockLen) {
|
|
1253
|
+
this.process(view, 0);
|
|
1254
|
+
this.pos = 0;
|
|
1255
|
+
processed = true;
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
this.length += data.length;
|
|
1259
|
+
if (processed)
|
|
1260
|
+
this.roundClean();
|
|
1261
|
+
return this;
|
|
1262
|
+
}
|
|
1263
|
+
digestInto(out) {
|
|
1264
|
+
aexists(this);
|
|
1265
|
+
aoutput(out, this);
|
|
1266
|
+
this.finished = true;
|
|
1267
|
+
const { buffer, view, blockLen, isLE: isLE2 } = this;
|
|
1268
|
+
let { pos } = this;
|
|
1269
|
+
buffer[pos++] = 128;
|
|
1270
|
+
buffer.fill(0, pos);
|
|
1271
|
+
if (this.padOffset > blockLen - pos) {
|
|
1272
|
+
this.process(view, 0);
|
|
1273
|
+
buffer.fill(0);
|
|
1274
|
+
}
|
|
1275
|
+
setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
|
|
1276
|
+
this.process(view, 0);
|
|
1277
|
+
this.roundClean();
|
|
1278
|
+
const oview = out === buffer ? view : createView(out);
|
|
1279
|
+
const len = this.outputLen;
|
|
1280
|
+
const outLen = len / 4;
|
|
1281
|
+
const state = this.get();
|
|
1282
|
+
if (len % 4 || outLen > state.length)
|
|
1283
|
+
throw new Error("invalid outputLen");
|
|
1284
|
+
for (let i = 0; i < outLen; i++)
|
|
1285
|
+
oview.setUint32(4 * i, state[i], isLE2);
|
|
1286
|
+
}
|
|
1287
|
+
digest() {
|
|
1288
|
+
const { buffer, outputLen } = this;
|
|
1289
|
+
this.digestInto(buffer);
|
|
1290
|
+
const res = buffer.slice(0, outputLen);
|
|
1291
|
+
this.destroy();
|
|
1292
|
+
return res;
|
|
1293
|
+
}
|
|
1294
|
+
_cloneIntoMeta(to) {
|
|
1295
|
+
const { buffer, length, finished, destroyed, pos } = this;
|
|
1296
|
+
to.destroyed = destroyed;
|
|
1297
|
+
to.finished = finished;
|
|
1298
|
+
to.length = length;
|
|
1299
|
+
to.pos = pos;
|
|
1300
|
+
if (pos)
|
|
1301
|
+
to.buffer.set(buffer);
|
|
1302
|
+
return to;
|
|
1303
|
+
}
|
|
1304
|
+
clone() {
|
|
1305
|
+
return this._cloneInto();
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
1309
|
+
1779033703,
|
|
1310
|
+
3144134277,
|
|
1311
|
+
1013904242,
|
|
1312
|
+
2773480762,
|
|
1313
|
+
1359893119,
|
|
1314
|
+
2600822924,
|
|
1315
|
+
528734635,
|
|
1316
|
+
1541459225
|
|
1317
|
+
]);
|
|
1318
|
+
|
|
1319
|
+
// node_modules/@noble/hashes/sha2.js
|
|
1320
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
1321
|
+
1116352408,
|
|
1322
|
+
1899447441,
|
|
1323
|
+
3049323471,
|
|
1324
|
+
3921009573,
|
|
1325
|
+
961987163,
|
|
1326
|
+
1508970993,
|
|
1327
|
+
2453635748,
|
|
1328
|
+
2870763221,
|
|
1329
|
+
3624381080,
|
|
1330
|
+
310598401,
|
|
1331
|
+
607225278,
|
|
1332
|
+
1426881987,
|
|
1333
|
+
1925078388,
|
|
1334
|
+
2162078206,
|
|
1335
|
+
2614888103,
|
|
1336
|
+
3248222580,
|
|
1337
|
+
3835390401,
|
|
1338
|
+
4022224774,
|
|
1339
|
+
264347078,
|
|
1340
|
+
604807628,
|
|
1341
|
+
770255983,
|
|
1342
|
+
1249150122,
|
|
1343
|
+
1555081692,
|
|
1344
|
+
1996064986,
|
|
1345
|
+
2554220882,
|
|
1346
|
+
2821834349,
|
|
1347
|
+
2952996808,
|
|
1348
|
+
3210313671,
|
|
1349
|
+
3336571891,
|
|
1350
|
+
3584528711,
|
|
1351
|
+
113926993,
|
|
1352
|
+
338241895,
|
|
1353
|
+
666307205,
|
|
1354
|
+
773529912,
|
|
1355
|
+
1294757372,
|
|
1356
|
+
1396182291,
|
|
1357
|
+
1695183700,
|
|
1358
|
+
1986661051,
|
|
1359
|
+
2177026350,
|
|
1360
|
+
2456956037,
|
|
1361
|
+
2730485921,
|
|
1362
|
+
2820302411,
|
|
1363
|
+
3259730800,
|
|
1364
|
+
3345764771,
|
|
1365
|
+
3516065817,
|
|
1366
|
+
3600352804,
|
|
1367
|
+
4094571909,
|
|
1368
|
+
275423344,
|
|
1369
|
+
430227734,
|
|
1370
|
+
506948616,
|
|
1371
|
+
659060556,
|
|
1372
|
+
883997877,
|
|
1373
|
+
958139571,
|
|
1374
|
+
1322822218,
|
|
1375
|
+
1537002063,
|
|
1376
|
+
1747873779,
|
|
1377
|
+
1955562222,
|
|
1378
|
+
2024104815,
|
|
1379
|
+
2227730452,
|
|
1380
|
+
2361852424,
|
|
1381
|
+
2428436474,
|
|
1382
|
+
2756734187,
|
|
1383
|
+
3204031479,
|
|
1384
|
+
3329325298
|
|
1385
|
+
]);
|
|
1386
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
1387
|
+
var SHA2_32B = class extends HashMD {
|
|
1388
|
+
// We cannot use array here since array allows indexing by variable
|
|
1389
|
+
// which means optimizer/compiler cannot use registers.
|
|
1390
|
+
// Numeric initializers matter: starting the fields as `undefined` changes
|
|
1391
|
+
// V8's field representation and makes sha256 3x slower (measured).
|
|
1392
|
+
A = 0;
|
|
1393
|
+
B = 0;
|
|
1394
|
+
C = 0;
|
|
1395
|
+
D = 0;
|
|
1396
|
+
E = 0;
|
|
1397
|
+
F = 0;
|
|
1398
|
+
G = 0;
|
|
1399
|
+
H = 0;
|
|
1400
|
+
constructor(outputLen, IV) {
|
|
1401
|
+
super(64, outputLen, 8, false);
|
|
1402
|
+
this.A = IV[0] | 0;
|
|
1403
|
+
this.B = IV[1] | 0;
|
|
1404
|
+
this.C = IV[2] | 0;
|
|
1405
|
+
this.D = IV[3] | 0;
|
|
1406
|
+
this.E = IV[4] | 0;
|
|
1407
|
+
this.F = IV[5] | 0;
|
|
1408
|
+
this.G = IV[6] | 0;
|
|
1409
|
+
this.H = IV[7] | 0;
|
|
1410
|
+
}
|
|
1411
|
+
get() {
|
|
1412
|
+
const { A, B: B2, C, D, E, F, G, H } = this;
|
|
1413
|
+
return [A, B2, C, D, E, F, G, H];
|
|
1414
|
+
}
|
|
1415
|
+
// prettier-ignore
|
|
1416
|
+
set(A, B2, C, D, E, F, G, H) {
|
|
1417
|
+
this.A = A | 0;
|
|
1418
|
+
this.B = B2 | 0;
|
|
1419
|
+
this.C = C | 0;
|
|
1420
|
+
this.D = D | 0;
|
|
1421
|
+
this.E = E | 0;
|
|
1422
|
+
this.F = F | 0;
|
|
1423
|
+
this.G = G | 0;
|
|
1424
|
+
this.H = H | 0;
|
|
1425
|
+
}
|
|
1426
|
+
_cloneInto(to) {
|
|
1427
|
+
(to ||= new this.constructor()).set(...this.get());
|
|
1428
|
+
return this._cloneIntoMeta(to);
|
|
1429
|
+
}
|
|
1430
|
+
process(view, offset) {
|
|
1431
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
1432
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
1433
|
+
for (let i = 16; i < 64; i++) {
|
|
1434
|
+
const W15 = SHA256_W[i - 15];
|
|
1435
|
+
const W2 = SHA256_W[i - 2];
|
|
1436
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
1437
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
1438
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
1439
|
+
}
|
|
1440
|
+
let { A, B: B2, C, D, E, F, G, H } = this;
|
|
1441
|
+
for (let i = 0; i < 64; i++) {
|
|
1442
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
1443
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
1444
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
1445
|
+
const T2 = sigma0 + Maj(A, B2, C) | 0;
|
|
1446
|
+
H = G;
|
|
1447
|
+
G = F;
|
|
1448
|
+
F = E;
|
|
1449
|
+
E = D + T1 | 0;
|
|
1450
|
+
D = C;
|
|
1451
|
+
C = B2;
|
|
1452
|
+
B2 = A;
|
|
1453
|
+
A = T1 + T2 | 0;
|
|
1454
|
+
}
|
|
1455
|
+
A = A + this.A | 0;
|
|
1456
|
+
B2 = B2 + this.B | 0;
|
|
1457
|
+
C = C + this.C | 0;
|
|
1458
|
+
D = D + this.D | 0;
|
|
1459
|
+
E = E + this.E | 0;
|
|
1460
|
+
F = F + this.F | 0;
|
|
1461
|
+
G = G + this.G | 0;
|
|
1462
|
+
H = H + this.H | 0;
|
|
1463
|
+
this.set(A, B2, C, D, E, F, G, H);
|
|
1464
|
+
}
|
|
1465
|
+
roundClean() {
|
|
1466
|
+
clean(SHA256_W);
|
|
1467
|
+
}
|
|
1468
|
+
destroy() {
|
|
1469
|
+
this.destroyed = true;
|
|
1470
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
1471
|
+
clean(this.buffer);
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
var _SHA256 = class extends SHA2_32B {
|
|
1475
|
+
constructor() {
|
|
1476
|
+
super(32, SHA256_IV);
|
|
1477
|
+
}
|
|
1478
|
+
};
|
|
1479
|
+
var sha256 = /* @__PURE__ */ createHasher(
|
|
1480
|
+
() => new _SHA256(),
|
|
1481
|
+
/* @__PURE__ */ oidNist(1)
|
|
1482
|
+
);
|
|
1483
|
+
|
|
1484
|
+
// node_modules/@noble/curves/utils.js
|
|
1485
|
+
function aarray(item, title, inner = () => {
|
|
1486
|
+
}) {
|
|
1487
|
+
if (!Array.isArray(item))
|
|
1488
|
+
throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
|
1489
|
+
for (let i = 0; i < item.length; i++)
|
|
1490
|
+
inner(item[i], `${title}[${i}]`);
|
|
1491
|
+
return item;
|
|
1492
|
+
}
|
|
1493
|
+
var abytes2 = (value, length, title) => abytes(value, length, title);
|
|
1494
|
+
var anumber2 = anumber;
|
|
1495
|
+
function astring(value, title = "") {
|
|
1496
|
+
if (typeof value !== "string") {
|
|
1497
|
+
const prefix = title && `"${title}" `;
|
|
1498
|
+
throw new TypeError(prefix + "expected string, got type=" + typeof value);
|
|
1499
|
+
}
|
|
1500
|
+
return value;
|
|
1501
|
+
}
|
|
1502
|
+
function aobject2(value, title = "object") {
|
|
1503
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
1504
|
+
throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
|
|
1505
|
+
return value;
|
|
1506
|
+
}
|
|
1507
|
+
function afunction(value, title) {
|
|
1508
|
+
if (typeof value !== "function")
|
|
1509
|
+
throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
|
|
1510
|
+
return value;
|
|
1511
|
+
}
|
|
1512
|
+
var bytesToHex2 = bytesToHex;
|
|
1513
|
+
var concatBytes2 = (...arrays) => concatBytes(...arrays);
|
|
1514
|
+
var hexToBytes2 = (hex) => hexToBytes(hex);
|
|
1515
|
+
var isBytes2 = isBytes;
|
|
1516
|
+
var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
|
|
1517
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
1518
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
1519
|
+
var atitle2 = (title) => title ? `"${title}" ` : "";
|
|
1520
|
+
function abool2(value, title = "") {
|
|
1521
|
+
if (typeof value !== "boolean")
|
|
1522
|
+
throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
|
|
1523
|
+
return value;
|
|
1524
|
+
}
|
|
1525
|
+
function abignumber(n) {
|
|
1526
|
+
if (typeof n === "bigint") {
|
|
1527
|
+
if (!isPosBig(n))
|
|
1528
|
+
throw new RangeError("positive bigint expected, got " + n);
|
|
1529
|
+
} else
|
|
1530
|
+
anumber2(n);
|
|
1531
|
+
return n;
|
|
1532
|
+
}
|
|
1533
|
+
function asafenumber(value, title = "") {
|
|
1534
|
+
if (typeof value !== "number") {
|
|
1535
|
+
const prefix = title && `"${title}" `;
|
|
1536
|
+
throw new TypeError(prefix + "expected number, got type=" + typeof value);
|
|
1537
|
+
}
|
|
1538
|
+
if (!Number.isSafeInteger(value)) {
|
|
1539
|
+
const prefix = title && `"${title}" `;
|
|
1540
|
+
throw new RangeError(prefix + "expected safe integer, got " + value);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
function numberToHexUnpadded(num) {
|
|
1544
|
+
const hex = abignumber(num).toString(16);
|
|
1545
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
1546
|
+
}
|
|
1547
|
+
function hexToNumber(hex) {
|
|
1548
|
+
if (typeof hex !== "string")
|
|
1549
|
+
throw new TypeError("hex string expected, got " + typeof hex);
|
|
1550
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
1551
|
+
}
|
|
1552
|
+
function bytesToNumberBE(bytes) {
|
|
1553
|
+
return hexToNumber(bytesToHex(bytes));
|
|
1554
|
+
}
|
|
1555
|
+
function bytesToNumberLE(bytes) {
|
|
1556
|
+
return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
|
|
1557
|
+
}
|
|
1558
|
+
function numberToBytesBE(n, len) {
|
|
1559
|
+
anumber(len);
|
|
1560
|
+
if (len === 0)
|
|
1561
|
+
throw new Error("zero output length is invalid");
|
|
1562
|
+
n = abignumber(n);
|
|
1563
|
+
const expectedLen = len * 2;
|
|
1564
|
+
const hex = n.toString(16);
|
|
1565
|
+
if (hex.length > expectedLen)
|
|
1566
|
+
throw new RangeError("number is too large");
|
|
1567
|
+
return hexToBytes(hex.padStart(expectedLen, "0"));
|
|
1568
|
+
}
|
|
1569
|
+
function numberToBytesLE(n, len) {
|
|
1570
|
+
return numberToBytesBE(n, len).reverse();
|
|
1571
|
+
}
|
|
1572
|
+
function copyBytes(bytes) {
|
|
1573
|
+
return Uint8Array.from(abytes2(bytes));
|
|
1574
|
+
}
|
|
1575
|
+
function isPosBig(n) {
|
|
1576
|
+
return typeof n === "bigint" && _0n <= n;
|
|
1577
|
+
}
|
|
1578
|
+
function inRange(n, min, max) {
|
|
1579
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
1580
|
+
}
|
|
1581
|
+
function aInRange(title, n, min, max) {
|
|
1582
|
+
if (!inRange(n, min, max))
|
|
1583
|
+
throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
1584
|
+
}
|
|
1585
|
+
function bitLen(n) {
|
|
1586
|
+
if (n < _0n)
|
|
1587
|
+
throw new Error("expected non-negative bigint, got " + n);
|
|
1588
|
+
return n === _0n ? 0 : n.toString(2).length;
|
|
1589
|
+
}
|
|
1590
|
+
var bitMask = (n) => {
|
|
1591
|
+
asafenumber(n, "n");
|
|
1592
|
+
return (_1n << BigInt(n)) - _1n;
|
|
1593
|
+
};
|
|
1594
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
1595
|
+
anumber(hashLen, "hashLen");
|
|
1596
|
+
anumber(qByteLen, "qByteLen");
|
|
1597
|
+
if (typeof hmacFn !== "function")
|
|
1598
|
+
throw new TypeError("hmacFn must be a function");
|
|
1599
|
+
const u8n = (len) => new Uint8Array(len);
|
|
1600
|
+
const NULL = Uint8Array.of();
|
|
1601
|
+
const byte0 = Uint8Array.of(0);
|
|
1602
|
+
const byte1 = Uint8Array.of(1);
|
|
1603
|
+
const _maxDrbgIters = 1e3;
|
|
1604
|
+
let v = u8n(hashLen);
|
|
1605
|
+
let k = u8n(hashLen);
|
|
1606
|
+
let i = 0;
|
|
1607
|
+
const reset = () => {
|
|
1608
|
+
v.fill(1);
|
|
1609
|
+
k.fill(0);
|
|
1610
|
+
i = 0;
|
|
1611
|
+
};
|
|
1612
|
+
const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs));
|
|
1613
|
+
const reseed = (seed = NULL) => {
|
|
1614
|
+
k = h(byte0, seed);
|
|
1615
|
+
v = h();
|
|
1616
|
+
if (seed.length === 0)
|
|
1617
|
+
return;
|
|
1618
|
+
k = h(byte1, seed);
|
|
1619
|
+
v = h();
|
|
1620
|
+
};
|
|
1621
|
+
const gen = () => {
|
|
1622
|
+
if (i++ >= _maxDrbgIters)
|
|
1623
|
+
throw new Error("drbg: tried max amount of iterations");
|
|
1624
|
+
let len = 0;
|
|
1625
|
+
const out = [];
|
|
1626
|
+
while (len < qByteLen) {
|
|
1627
|
+
v = h();
|
|
1628
|
+
const sl = v.slice();
|
|
1629
|
+
out.push(sl);
|
|
1630
|
+
len += v.length;
|
|
1631
|
+
}
|
|
1632
|
+
return concatBytes2(...out);
|
|
1633
|
+
};
|
|
1634
|
+
const genUntil = (seed, pred) => {
|
|
1635
|
+
reset();
|
|
1636
|
+
reseed(seed);
|
|
1637
|
+
let res = void 0;
|
|
1638
|
+
while ((res = pred(gen())) === void 0)
|
|
1639
|
+
reseed();
|
|
1640
|
+
reset();
|
|
1641
|
+
return res;
|
|
1642
|
+
};
|
|
1643
|
+
return genUntil;
|
|
1644
|
+
}
|
|
1645
|
+
function validateObject(object2, fields = {}, optFields = {}, title = "object") {
|
|
1646
|
+
aobject2(object2, title);
|
|
1647
|
+
aobject2(fields, "fields");
|
|
1648
|
+
aobject2(optFields, "optFields");
|
|
1649
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
1650
|
+
const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
|
|
1651
|
+
const val = object2[fieldName];
|
|
1652
|
+
if (!Object.hasOwn(object2, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
|
|
1653
|
+
throw new TypeError(`${label} is invalid: expected own property`);
|
|
1654
|
+
}
|
|
1655
|
+
if (isOpt && val === void 0)
|
|
1656
|
+
return;
|
|
1657
|
+
const current = typeof val;
|
|
1658
|
+
if (current !== expectedType || val === null)
|
|
1659
|
+
throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
|
|
1660
|
+
}
|
|
1661
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
1662
|
+
iter(fields, false);
|
|
1663
|
+
iter(optFields, true);
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
// node_modules/@noble/curves/abstract/modular.js
|
|
1667
|
+
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
1668
|
+
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
1669
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
1670
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
1671
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
1672
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
1673
|
+
var _7n = /* @__PURE__ */ BigInt(7);
|
|
1674
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
1675
|
+
var _9n = /* @__PURE__ */ BigInt(9);
|
|
1676
|
+
var _15n = /* @__PURE__ */ BigInt(15);
|
|
1677
|
+
var _16n = /* @__PURE__ */ BigInt(16);
|
|
1678
|
+
var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
|
|
1679
|
+
function mod(a, b) {
|
|
1680
|
+
if (b <= _0n2)
|
|
1681
|
+
throw new Error("mod: expected positive modulus, got " + b);
|
|
1682
|
+
const result = a % b;
|
|
1683
|
+
return result >= _0n2 ? result : b + result;
|
|
1684
|
+
}
|
|
1685
|
+
function pow(num, power, modulo) {
|
|
1686
|
+
if (modulo <= _1n2)
|
|
1687
|
+
throw new Error("pow: expected modulus > 1, got " + modulo);
|
|
1688
|
+
if (typeof power !== "bigint")
|
|
1689
|
+
throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
|
|
1690
|
+
if (power < _0n2)
|
|
1691
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
1692
|
+
if (power === _0n2)
|
|
1693
|
+
return _1n2;
|
|
1694
|
+
if (power === _1n2)
|
|
1695
|
+
return num;
|
|
1696
|
+
let d = num % modulo;
|
|
1697
|
+
if (d < _0n2)
|
|
1698
|
+
d += modulo;
|
|
1699
|
+
if (power < POW_WINDOWED_MIN) {
|
|
1700
|
+
let p2 = _1n2;
|
|
1701
|
+
while (power > _0n2) {
|
|
1702
|
+
if (power & _1n2)
|
|
1703
|
+
p2 = p2 * d % modulo;
|
|
1704
|
+
d = d * d % modulo;
|
|
1705
|
+
power >>= _1n2;
|
|
1706
|
+
}
|
|
1707
|
+
return p2;
|
|
1708
|
+
}
|
|
1709
|
+
const digits = [];
|
|
1710
|
+
while (power > _0n2) {
|
|
1711
|
+
digits.push(Number(power & _15n));
|
|
1712
|
+
power >>= _4n;
|
|
1713
|
+
}
|
|
1714
|
+
const table2 = new Array(16);
|
|
1715
|
+
table2[0] = _1n2;
|
|
1716
|
+
table2[1] = d;
|
|
1717
|
+
for (let i = 2; i < 16; i++)
|
|
1718
|
+
table2[i] = table2[i - 1] * d % modulo;
|
|
1719
|
+
let p = table2[digits[digits.length - 1]];
|
|
1720
|
+
for (let w = digits.length - 2; w >= 0; w--) {
|
|
1721
|
+
p = p * p % modulo;
|
|
1722
|
+
p = p * p % modulo;
|
|
1723
|
+
p = p * p % modulo;
|
|
1724
|
+
p = p * p % modulo;
|
|
1725
|
+
const digit = digits[w];
|
|
1726
|
+
if (digit !== 0)
|
|
1727
|
+
p = p * table2[digit] % modulo;
|
|
1728
|
+
}
|
|
1729
|
+
return p;
|
|
1730
|
+
}
|
|
1731
|
+
function pow2(x, power, modulo) {
|
|
1732
|
+
if (modulo <= _1n2)
|
|
1733
|
+
throw new Error("pow2: expected modulus > 1, got " + modulo);
|
|
1734
|
+
if (power < _0n2)
|
|
1735
|
+
throw new Error("pow2: expected non-negative exponent, got " + power);
|
|
1736
|
+
let res = x;
|
|
1737
|
+
while (power-- > _0n2) {
|
|
1738
|
+
res *= res;
|
|
1739
|
+
res %= modulo;
|
|
1740
|
+
}
|
|
1741
|
+
return res;
|
|
1742
|
+
}
|
|
1743
|
+
function invert(number, modulo) {
|
|
1744
|
+
if (number === _0n2)
|
|
1745
|
+
throw new Error("invert: expected non-zero number");
|
|
1746
|
+
if (modulo <= _1n2)
|
|
1747
|
+
throw new Error("invert: expected modulus > 1, got " + modulo);
|
|
1748
|
+
let a = mod(number, modulo);
|
|
1749
|
+
let b = modulo;
|
|
1750
|
+
let x = _0n2, u = _1n2;
|
|
1751
|
+
while (a !== _0n2) {
|
|
1752
|
+
const q = b / a;
|
|
1753
|
+
const r = b - a * q;
|
|
1754
|
+
const m = x - u * q;
|
|
1755
|
+
b = a, a = r, x = u, u = m;
|
|
1756
|
+
}
|
|
1757
|
+
const gcd = b;
|
|
1758
|
+
if (gcd !== _1n2)
|
|
1759
|
+
throw new Error("invert: does not exist");
|
|
1760
|
+
return mod(x, modulo);
|
|
1761
|
+
}
|
|
1762
|
+
function invertCt(a, prime) {
|
|
1763
|
+
if (prime <= _1n2)
|
|
1764
|
+
throw new Error("invertCt: expected prime modulus > 1, got " + prime);
|
|
1765
|
+
const an = mod(a, prime);
|
|
1766
|
+
if (an === _0n2)
|
|
1767
|
+
throw new Error("invertCt: expected non-zero number");
|
|
1768
|
+
const inverse = pow(an, prime - _2n, prime);
|
|
1769
|
+
if (mod(an * inverse, prime) !== _1n2)
|
|
1770
|
+
throw new Error("invertCt: does not exist");
|
|
1771
|
+
return inverse;
|
|
1772
|
+
}
|
|
1773
|
+
function assertIsSquare(Fp, root, n) {
|
|
1774
|
+
const F = Fp;
|
|
1775
|
+
if (!F.eql(F.sqr(root), n))
|
|
1776
|
+
throw new Error("Cannot find square root");
|
|
1777
|
+
}
|
|
1778
|
+
function aoddModulus(order, fnName) {
|
|
1779
|
+
if ((order & _1n2) === _0n2)
|
|
1780
|
+
throw new Error(fnName + ": expected odd modulus, got " + order);
|
|
1781
|
+
}
|
|
1782
|
+
function sqrt3mod4(Fp, n) {
|
|
1783
|
+
const F = Fp;
|
|
1784
|
+
const p1div4 = (F.ORDER + _1n2) / _4n;
|
|
1785
|
+
const root = F.pow(n, p1div4);
|
|
1786
|
+
assertIsSquare(F, root, n);
|
|
1787
|
+
return root;
|
|
1788
|
+
}
|
|
1789
|
+
function sqrt5mod8(Fp, n) {
|
|
1790
|
+
const F = Fp;
|
|
1791
|
+
const p5div8 = (F.ORDER - _5n) / _8n;
|
|
1792
|
+
const n2 = F.mul(n, _2n);
|
|
1793
|
+
const v = F.pow(n2, p5div8);
|
|
1794
|
+
const nv = F.mul(n, v);
|
|
1795
|
+
const i = F.mul(F.mul(nv, _2n), v);
|
|
1796
|
+
const root = F.mul(nv, F.sub(i, F.ONE));
|
|
1797
|
+
assertIsSquare(F, root, n);
|
|
1798
|
+
return root;
|
|
1799
|
+
}
|
|
1800
|
+
function sqrt9mod16(P) {
|
|
1801
|
+
const Fp_ = Field(P);
|
|
1802
|
+
const tn = tonelliShanks(P);
|
|
1803
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
1804
|
+
const c2 = tn(Fp_, c1);
|
|
1805
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
1806
|
+
const c4 = (P + _7n) / _16n;
|
|
1807
|
+
return ((Fp, n) => {
|
|
1808
|
+
const F = Fp;
|
|
1809
|
+
let tv1 = F.pow(n, c4);
|
|
1810
|
+
let tv2 = F.mul(tv1, c1);
|
|
1811
|
+
const tv3 = F.mul(tv1, c2);
|
|
1812
|
+
const tv4 = F.mul(tv1, c3);
|
|
1813
|
+
const e1 = F.eql(F.sqr(tv2), n);
|
|
1814
|
+
const e2 = F.eql(F.sqr(tv3), n);
|
|
1815
|
+
tv1 = F.cmov(tv1, tv2, e1);
|
|
1816
|
+
tv2 = F.cmov(tv4, tv3, e2);
|
|
1817
|
+
const e3 = F.eql(F.sqr(tv2), n);
|
|
1818
|
+
const root = F.cmov(tv1, tv2, e3);
|
|
1819
|
+
assertIsSquare(F, root, n);
|
|
1820
|
+
return root;
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
function tonelliShanks(P) {
|
|
1824
|
+
if (P < _3n)
|
|
1825
|
+
throw new Error("sqrt is not defined for small field");
|
|
1826
|
+
aoddModulus(P, "tonelliShanks");
|
|
1827
|
+
let Q = P - _1n2;
|
|
1828
|
+
let S = 0;
|
|
1829
|
+
while (Q % _2n === _0n2) {
|
|
1830
|
+
Q /= _2n;
|
|
1831
|
+
S++;
|
|
1832
|
+
}
|
|
1833
|
+
let Z = _2n;
|
|
1834
|
+
const _Fp = Field(P);
|
|
1835
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
1836
|
+
if (Z++ > 1e3)
|
|
1837
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
1838
|
+
}
|
|
1839
|
+
if (S === 1)
|
|
1840
|
+
return sqrt3mod4;
|
|
1841
|
+
let cc = _Fp.pow(Z, Q);
|
|
1842
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
1843
|
+
return function tonelliSlow(Fp, n) {
|
|
1844
|
+
const F = Fp;
|
|
1845
|
+
if (F.is0(n))
|
|
1846
|
+
return n;
|
|
1847
|
+
if (FpLegendre(F, n) !== 1)
|
|
1848
|
+
throw new Error("Cannot find square root");
|
|
1849
|
+
let M = S;
|
|
1850
|
+
let c = F.mul(F.ONE, cc);
|
|
1851
|
+
let t = F.pow(n, Q);
|
|
1852
|
+
let R = F.pow(n, Q1div2);
|
|
1853
|
+
while (!F.eql(t, F.ONE)) {
|
|
1854
|
+
if (F.is0(t))
|
|
1855
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
1856
|
+
let i = 1;
|
|
1857
|
+
let t_tmp = F.sqr(t);
|
|
1858
|
+
while (!F.eql(t_tmp, F.ONE)) {
|
|
1859
|
+
i++;
|
|
1860
|
+
t_tmp = F.sqr(t_tmp);
|
|
1861
|
+
if (i === M)
|
|
1862
|
+
throw new Error("Cannot find square root");
|
|
1863
|
+
}
|
|
1864
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
1865
|
+
const b = F.pow(c, exponent);
|
|
1866
|
+
M = i;
|
|
1867
|
+
c = F.sqr(b);
|
|
1868
|
+
t = F.mul(t, c);
|
|
1869
|
+
R = F.mul(R, b);
|
|
1870
|
+
}
|
|
1871
|
+
return R;
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
function FpSqrt(P) {
|
|
1875
|
+
aoddModulus(P, "Fp.sqrt");
|
|
1876
|
+
if (P % _4n === _3n)
|
|
1877
|
+
return sqrt3mod4;
|
|
1878
|
+
if (P % _8n === _5n)
|
|
1879
|
+
return sqrt5mod8;
|
|
1880
|
+
if (P % _16n === _9n)
|
|
1881
|
+
return sqrt9mod16(P);
|
|
1882
|
+
return tonelliShanks(P);
|
|
1883
|
+
}
|
|
1884
|
+
var FIELD_FIELDS = [
|
|
1885
|
+
"create",
|
|
1886
|
+
"isValid",
|
|
1887
|
+
"is0",
|
|
1888
|
+
"neg",
|
|
1889
|
+
"inv",
|
|
1890
|
+
"sqrt",
|
|
1891
|
+
"sqr",
|
|
1892
|
+
"eql",
|
|
1893
|
+
"add",
|
|
1894
|
+
"sub",
|
|
1895
|
+
"mul",
|
|
1896
|
+
"pow",
|
|
1897
|
+
"div",
|
|
1898
|
+
"addN",
|
|
1899
|
+
"subN",
|
|
1900
|
+
"mulN",
|
|
1901
|
+
"sqrN"
|
|
1902
|
+
];
|
|
1903
|
+
function validateField(field) {
|
|
1904
|
+
aobject2(field, "field");
|
|
1905
|
+
if (typeof field.ORDER !== "bigint")
|
|
1906
|
+
throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
|
|
1907
|
+
asafenumber(field.BYTES, "BYTES");
|
|
1908
|
+
asafenumber(field.BITS, "BITS");
|
|
1909
|
+
for (const name of FIELD_FIELDS)
|
|
1910
|
+
afunction(field[name], "field." + name);
|
|
1911
|
+
if (field.BYTES < 1 || field.BITS < 1)
|
|
1912
|
+
throw new Error("invalid field: expected BYTES/BITS > 0");
|
|
1913
|
+
if (field.ORDER <= _1n2)
|
|
1914
|
+
throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
|
|
1915
|
+
return field;
|
|
1916
|
+
}
|
|
1917
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
1918
|
+
validateField(Fp);
|
|
1919
|
+
aarray(nums, "nums");
|
|
1920
|
+
abool2(passZero, "passZero");
|
|
1921
|
+
const F = Fp;
|
|
1922
|
+
const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
|
|
1923
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
1924
|
+
if (F.is0(num))
|
|
1925
|
+
return acc;
|
|
1926
|
+
inverted[i] = acc;
|
|
1927
|
+
return F.mul(acc, num);
|
|
1928
|
+
}, F.ONE);
|
|
1929
|
+
const invertedAcc = F.inv(multipliedAcc);
|
|
1930
|
+
nums.reduceRight((acc, num, i) => {
|
|
1931
|
+
if (F.is0(num))
|
|
1932
|
+
return acc;
|
|
1933
|
+
inverted[i] = F.mul(acc, inverted[i]);
|
|
1934
|
+
return F.mul(acc, num);
|
|
1935
|
+
}, invertedAcc);
|
|
1936
|
+
return inverted;
|
|
1937
|
+
}
|
|
1938
|
+
function FpLegendre(Fp, n) {
|
|
1939
|
+
validateField(Fp);
|
|
1940
|
+
const F = Fp;
|
|
1941
|
+
aoddModulus(F.ORDER, "FpLegendre");
|
|
1942
|
+
const p1mod2 = (F.ORDER - _1n2) / _2n;
|
|
1943
|
+
const powered = F.pow(n, p1mod2);
|
|
1944
|
+
const yes = F.eql(powered, F.ONE);
|
|
1945
|
+
const zero = F.eql(powered, F.ZERO);
|
|
1946
|
+
const no = F.eql(powered, F.neg(F.ONE));
|
|
1947
|
+
if (!yes && !zero && !no)
|
|
1948
|
+
throw new Error("invalid Legendre symbol result");
|
|
1949
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
1950
|
+
}
|
|
1951
|
+
function nLength(n, nBitLength) {
|
|
1952
|
+
if (nBitLength !== void 0)
|
|
1953
|
+
anumber2(nBitLength);
|
|
1954
|
+
if (n <= _0n2)
|
|
1955
|
+
throw new Error("invalid n length: expected positive n, got " + n);
|
|
1956
|
+
if (nBitLength !== void 0 && nBitLength < 1)
|
|
1957
|
+
throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
|
|
1958
|
+
const bits = bitLen(n);
|
|
1959
|
+
if (nBitLength !== void 0 && nBitLength < bits)
|
|
1960
|
+
throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
|
|
1961
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
|
|
1962
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
1963
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
1964
|
+
}
|
|
1965
|
+
var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
|
|
1966
|
+
var _Field = class {
|
|
1967
|
+
ORDER;
|
|
1968
|
+
BITS;
|
|
1969
|
+
BYTES;
|
|
1970
|
+
isLE;
|
|
1971
|
+
ZERO = _0n2;
|
|
1972
|
+
ONE = _1n2;
|
|
1973
|
+
_lengths;
|
|
1974
|
+
_mod;
|
|
1975
|
+
constructor(ORDER, opts = {}) {
|
|
1976
|
+
if (ORDER <= _1n2)
|
|
1977
|
+
throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
|
|
1978
|
+
let _nbitLength = void 0;
|
|
1979
|
+
this.isLE = false;
|
|
1980
|
+
if (opts != null && typeof opts === "object") {
|
|
1981
|
+
if (typeof opts.BITS === "number")
|
|
1982
|
+
_nbitLength = opts.BITS;
|
|
1983
|
+
if (typeof opts.sqrt === "function")
|
|
1984
|
+
Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
|
|
1985
|
+
if (typeof opts.isLE === "boolean")
|
|
1986
|
+
this.isLE = opts.isLE;
|
|
1987
|
+
if (opts.allowedLengths)
|
|
1988
|
+
this._lengths = Object.freeze(opts.allowedLengths.slice());
|
|
1989
|
+
if (typeof opts.modFromBytes === "boolean")
|
|
1990
|
+
this._mod = opts.modFromBytes;
|
|
1991
|
+
}
|
|
1992
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
1993
|
+
if (nByteLength > 2048)
|
|
1994
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
1995
|
+
this.ORDER = ORDER;
|
|
1996
|
+
this.BITS = nBitLength;
|
|
1997
|
+
this.BYTES = nByteLength;
|
|
1998
|
+
Object.freeze(this);
|
|
1999
|
+
}
|
|
2000
|
+
create(num) {
|
|
2001
|
+
return mod(num, this.ORDER);
|
|
2002
|
+
}
|
|
2003
|
+
isValid(num) {
|
|
2004
|
+
if (typeof num !== "bigint")
|
|
2005
|
+
throw new TypeError("invalid field element: expected bigint, got " + typeof num);
|
|
2006
|
+
return _0n2 <= num && num < this.ORDER;
|
|
2007
|
+
}
|
|
2008
|
+
is0(num) {
|
|
2009
|
+
return num === _0n2;
|
|
2010
|
+
}
|
|
2011
|
+
// is valid and invertible
|
|
2012
|
+
isValidNot0(num) {
|
|
2013
|
+
return !this.is0(num) && this.isValid(num);
|
|
2014
|
+
}
|
|
2015
|
+
isOdd(num) {
|
|
2016
|
+
return (num & _1n2) === _1n2;
|
|
2017
|
+
}
|
|
2018
|
+
neg(num) {
|
|
2019
|
+
return mod(-num, this.ORDER);
|
|
2020
|
+
}
|
|
2021
|
+
eql(lhs, rhs) {
|
|
2022
|
+
return lhs === rhs;
|
|
2023
|
+
}
|
|
2024
|
+
sqr(num) {
|
|
2025
|
+
return mod(num * num, this.ORDER);
|
|
2026
|
+
}
|
|
2027
|
+
add(lhs, rhs) {
|
|
2028
|
+
return mod(lhs + rhs, this.ORDER);
|
|
2029
|
+
}
|
|
2030
|
+
sub(lhs, rhs) {
|
|
2031
|
+
return mod(lhs - rhs, this.ORDER);
|
|
2032
|
+
}
|
|
2033
|
+
mul(lhs, rhs) {
|
|
2034
|
+
return mod(lhs * rhs, this.ORDER);
|
|
2035
|
+
}
|
|
2036
|
+
pow(num, power) {
|
|
2037
|
+
return pow(num, power, this.ORDER);
|
|
2038
|
+
}
|
|
2039
|
+
div(lhs, rhs) {
|
|
2040
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
2041
|
+
}
|
|
2042
|
+
// Same as above, but doesn't normalize
|
|
2043
|
+
sqrN(num) {
|
|
2044
|
+
return num * num;
|
|
2045
|
+
}
|
|
2046
|
+
addN(lhs, rhs) {
|
|
2047
|
+
return lhs + rhs;
|
|
2048
|
+
}
|
|
2049
|
+
subN(lhs, rhs) {
|
|
2050
|
+
return lhs - rhs;
|
|
2051
|
+
}
|
|
2052
|
+
mulN(lhs, rhs) {
|
|
2053
|
+
return lhs * rhs;
|
|
2054
|
+
}
|
|
2055
|
+
inv(num) {
|
|
2056
|
+
return invert(num, this.ORDER);
|
|
2057
|
+
}
|
|
2058
|
+
sqrt(num) {
|
|
2059
|
+
let sqrt = FIELD_SQRT.get(this);
|
|
2060
|
+
if (!sqrt)
|
|
2061
|
+
FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
|
|
2062
|
+
return sqrt(this, num);
|
|
2063
|
+
}
|
|
2064
|
+
toBytes(num) {
|
|
2065
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
2066
|
+
}
|
|
2067
|
+
fromBytes(bytes, skipValidation = false) {
|
|
2068
|
+
abytes2(bytes);
|
|
2069
|
+
const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
|
|
2070
|
+
if (allowedLengths) {
|
|
2071
|
+
if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
2072
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
2073
|
+
}
|
|
2074
|
+
const padded = new Uint8Array(BYTES);
|
|
2075
|
+
padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
|
|
2076
|
+
bytes = padded;
|
|
2077
|
+
}
|
|
2078
|
+
if (bytes.length !== BYTES)
|
|
2079
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
2080
|
+
let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
2081
|
+
if (modFromBytes)
|
|
2082
|
+
scalar = mod(scalar, ORDER);
|
|
2083
|
+
if (!skipValidation) {
|
|
2084
|
+
if (!this.isValid(scalar))
|
|
2085
|
+
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
2086
|
+
}
|
|
2087
|
+
return scalar;
|
|
2088
|
+
}
|
|
2089
|
+
// TODO: we don't need it here, move out to separate fn
|
|
2090
|
+
invertBatch(lst) {
|
|
2091
|
+
return FpInvertBatch(this, lst, true);
|
|
2092
|
+
}
|
|
2093
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
2094
|
+
// and it's unclear what to return in there.
|
|
2095
|
+
cmov(a, b, condition) {
|
|
2096
|
+
abool2(condition, "condition");
|
|
2097
|
+
return condition ? b : a;
|
|
2098
|
+
}
|
|
2099
|
+
};
|
|
2100
|
+
function Field(ORDER, opts = {}) {
|
|
2101
|
+
Object.freeze(_Field.prototype);
|
|
2102
|
+
return new _Field(ORDER, opts);
|
|
2103
|
+
}
|
|
2104
|
+
function getFieldBytesLength(fieldOrder) {
|
|
2105
|
+
if (typeof fieldOrder !== "bigint")
|
|
2106
|
+
throw new Error("field order must be bigint");
|
|
2107
|
+
if (fieldOrder <= _1n2)
|
|
2108
|
+
throw new Error("field order must be greater than 1");
|
|
2109
|
+
const bitLength = bitLen(fieldOrder - _1n2);
|
|
2110
|
+
return Math.ceil(bitLength / 8);
|
|
2111
|
+
}
|
|
2112
|
+
function getMinHashLength(fieldOrder) {
|
|
2113
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
2114
|
+
return length + Math.ceil(length / 2);
|
|
2115
|
+
}
|
|
2116
|
+
function mapHashToField(key, fieldOrder, isLE2 = false) {
|
|
2117
|
+
abytes2(key);
|
|
2118
|
+
const len = key.length;
|
|
2119
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
2120
|
+
const minLen = Math.max(getMinHashLength(fieldOrder), 16);
|
|
2121
|
+
if (len < minLen || len > 1024)
|
|
2122
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
2123
|
+
const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
2124
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
2125
|
+
return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
// node_modules/@noble/curves/abstract/curve.js
|
|
2129
|
+
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
2130
|
+
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
2131
|
+
var _4n2 = /* @__PURE__ */ BigInt(4);
|
|
2132
|
+
var BLIND_BYTES = 16;
|
|
2133
|
+
var BLIND_BITS = 128;
|
|
2134
|
+
var FW_WINDOW = 5;
|
|
2135
|
+
var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
|
|
2136
|
+
function validatePointCons(Point) {
|
|
2137
|
+
const pc = Point;
|
|
2138
|
+
if (typeof pc !== "function")
|
|
2139
|
+
throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
|
|
2140
|
+
afunction(pc.fromAffine, "Point.fromAffine");
|
|
2141
|
+
afunction(pc.fromBytes, "Point.fromBytes");
|
|
2142
|
+
afunction(pc.fromHex, "Point.fromHex");
|
|
2143
|
+
aobject2(pc.BASE, "Point.BASE");
|
|
2144
|
+
aobject2(pc.ZERO, "Point.ZERO");
|
|
2145
|
+
validateField(pc.Fp);
|
|
2146
|
+
validateField(pc.Fn);
|
|
2147
|
+
}
|
|
2148
|
+
function normalizeZ(c, points) {
|
|
2149
|
+
validatePointCons(c);
|
|
2150
|
+
validateMSMPoints(points, c);
|
|
2151
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
2152
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
2153
|
+
}
|
|
2154
|
+
function validateW(W, bits, min = 1) {
|
|
2155
|
+
if (!Number.isSafeInteger(W) || W < min || W > bits)
|
|
2156
|
+
throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
|
|
2157
|
+
}
|
|
2158
|
+
function validateTableBytes(numPoints, fpBytes) {
|
|
2159
|
+
const bytes = numPoints * (4 * fpBytes + 128);
|
|
2160
|
+
if (bytes > TABLE_BYTES_MAX)
|
|
2161
|
+
throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
|
|
2162
|
+
}
|
|
2163
|
+
function probeRandomBytes(randomBytes3, length) {
|
|
2164
|
+
if (randomBytes3 === void 0)
|
|
2165
|
+
return void 0;
|
|
2166
|
+
afunction(randomBytes3, "randomBytes");
|
|
2167
|
+
try {
|
|
2168
|
+
const probe = randomBytes3(length);
|
|
2169
|
+
if (!isBytes2(probe) || probe.length !== length)
|
|
2170
|
+
return void 0;
|
|
2171
|
+
} catch {
|
|
2172
|
+
return void 0;
|
|
2173
|
+
}
|
|
2174
|
+
return randomBytes3;
|
|
2175
|
+
}
|
|
2176
|
+
function validateMSMPoints(points, c) {
|
|
2177
|
+
aarray(points, "points");
|
|
2178
|
+
points.forEach((p, i) => {
|
|
2179
|
+
if (!(p instanceof c))
|
|
2180
|
+
throw new Error("invalid point at index " + i);
|
|
2181
|
+
});
|
|
2182
|
+
}
|
|
2183
|
+
function validateMSMScalars(scalars, field, maxScalar) {
|
|
2184
|
+
if (!Array.isArray(scalars))
|
|
2185
|
+
throw new Error("array of scalars expected");
|
|
2186
|
+
scalars.forEach((s, i) => {
|
|
2187
|
+
const ok2 = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
|
|
2188
|
+
if (!ok2)
|
|
2189
|
+
throw new Error("invalid scalar at index " + i);
|
|
2190
|
+
});
|
|
2191
|
+
}
|
|
2192
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
2193
|
+
function getWindowSize(P) {
|
|
2194
|
+
return pointWindowSizes.get(P) || 1;
|
|
2195
|
+
}
|
|
2196
|
+
function oddMultiples(p, size) {
|
|
2197
|
+
const dbl = p.double();
|
|
2198
|
+
const t = [p];
|
|
2199
|
+
for (let j = 1; j < size; j++)
|
|
2200
|
+
t.push(t[j - 1].add(dbl));
|
|
2201
|
+
return t;
|
|
2202
|
+
}
|
|
2203
|
+
function wnafDigits(n, W) {
|
|
2204
|
+
const size = 2 ** W;
|
|
2205
|
+
const half = size / 2;
|
|
2206
|
+
const mask = BigInt(size - 1);
|
|
2207
|
+
const d = [];
|
|
2208
|
+
while (n > _0n3) {
|
|
2209
|
+
let w = 0;
|
|
2210
|
+
if (n & _1n3) {
|
|
2211
|
+
w = Number(n & mask);
|
|
2212
|
+
if (w >= half)
|
|
2213
|
+
w -= size;
|
|
2214
|
+
n -= BigInt(w);
|
|
2215
|
+
}
|
|
2216
|
+
d.push(w);
|
|
2217
|
+
n >>= _1n3;
|
|
2218
|
+
}
|
|
2219
|
+
return d;
|
|
2220
|
+
}
|
|
2221
|
+
function signedWindowDigits(n, W, windows) {
|
|
2222
|
+
const size = 2 ** W;
|
|
2223
|
+
const half = size / 2;
|
|
2224
|
+
const mask = BigInt(size - 1);
|
|
2225
|
+
const shiftBy = BigInt(W);
|
|
2226
|
+
const d = [];
|
|
2227
|
+
for (let w = 0; w < windows; w++) {
|
|
2228
|
+
let v = Number(n & mask);
|
|
2229
|
+
n >>= shiftBy;
|
|
2230
|
+
if (v > half) {
|
|
2231
|
+
v -= size;
|
|
2232
|
+
n += _1n3;
|
|
2233
|
+
}
|
|
2234
|
+
d.push(v);
|
|
2235
|
+
}
|
|
2236
|
+
if (n !== _0n3)
|
|
2237
|
+
throw new Error("invalid wnaf");
|
|
2238
|
+
return d;
|
|
2239
|
+
}
|
|
2240
|
+
function wnafWalk(zero, tables, digits) {
|
|
2241
|
+
let max = 0;
|
|
2242
|
+
for (const d of digits)
|
|
2243
|
+
max = Math.max(max, d.length);
|
|
2244
|
+
let acc = zero;
|
|
2245
|
+
for (let bit = max - 1; bit >= 0; bit--) {
|
|
2246
|
+
if (bit !== max - 1)
|
|
2247
|
+
acc = acc.double();
|
|
2248
|
+
for (let i = 0; i < digits.length; i++) {
|
|
2249
|
+
const w = digits[i][bit];
|
|
2250
|
+
if (w) {
|
|
2251
|
+
const item = tables[i][Math.abs(w) - 1 >> 1];
|
|
2252
|
+
acc = acc.add(w < 0 ? item.negate() : item);
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
return acc;
|
|
2257
|
+
}
|
|
2258
|
+
var ScalarMultiplier = class {
|
|
2259
|
+
Point;
|
|
2260
|
+
BASE;
|
|
2261
|
+
ZERO;
|
|
2262
|
+
randomBytes;
|
|
2263
|
+
wnafPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
2264
|
+
baseCanBeBlinded;
|
|
2265
|
+
bits;
|
|
2266
|
+
// Parametrized with a given Point class (not individual point)
|
|
2267
|
+
constructor(Point, randomBytes3) {
|
|
2268
|
+
validatePointCons(Point);
|
|
2269
|
+
this.randomBytes = probeRandomBytes(randomBytes3, BLIND_BYTES);
|
|
2270
|
+
this.Point = Point;
|
|
2271
|
+
this.BASE = Point.BASE;
|
|
2272
|
+
this.ZERO = Point.ZERO;
|
|
2273
|
+
this.bits = Point.Fn.BITS;
|
|
2274
|
+
}
|
|
2275
|
+
/**
|
|
2276
|
+
* Creates a signed fixed-window wNAF precomputation table: for every window w, the
|
|
2277
|
+
* multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
|
|
2278
|
+
* so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
|
|
2279
|
+
* window absorbs the final carry of signed-digit recoding.
|
|
2280
|
+
* For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
|
|
2281
|
+
* @param point - Point instance
|
|
2282
|
+
* @param W - window size
|
|
2283
|
+
* @param bits - scalar bitlength the table must cover
|
|
2284
|
+
*/
|
|
2285
|
+
buildWnafTable(point, W, bits) {
|
|
2286
|
+
const windows = Math.ceil(bits / W) + 1;
|
|
2287
|
+
const half = 2 ** (W - 1);
|
|
2288
|
+
const comp = [];
|
|
2289
|
+
let base = point;
|
|
2290
|
+
for (let w = 0; w < windows; w++) {
|
|
2291
|
+
let acc = base;
|
|
2292
|
+
for (let i = 0; i < half; i++) {
|
|
2293
|
+
comp.push(acc);
|
|
2294
|
+
acc = acc.add(base);
|
|
2295
|
+
}
|
|
2296
|
+
base = comp[comp.length - 1].double();
|
|
2297
|
+
}
|
|
2298
|
+
return { W, bits, windows, comp };
|
|
2299
|
+
}
|
|
2300
|
+
/**
|
|
2301
|
+
* Implements ec multiplication using precomputed signed fixed-window wNAF tables.
|
|
2302
|
+
* Constant-time: fixed window count with one table addition per window — zero digits feed
|
|
2303
|
+
* the fake accumulator — and no doublings; the lookup scans the whole window slice.
|
|
2304
|
+
* Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
|
|
2305
|
+
* {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
|
|
2306
|
+
* signedWindowDigits throws if `n` exceeds the table.
|
|
2307
|
+
* @returns real and fake (for const-time) points
|
|
2308
|
+
*/
|
|
2309
|
+
wnafCachedCT(precomputes, n) {
|
|
2310
|
+
const { W, windows, comp } = precomputes;
|
|
2311
|
+
const half = 2 ** (W - 1);
|
|
2312
|
+
const digits = signedWindowDigits(n, W, windows);
|
|
2313
|
+
let p = this.ZERO;
|
|
2314
|
+
let f = this.BASE;
|
|
2315
|
+
for (let w = 0; w < windows; w++) {
|
|
2316
|
+
const digit = digits[w];
|
|
2317
|
+
const start = w * half;
|
|
2318
|
+
const idx = Math.abs(digit) - 1;
|
|
2319
|
+
let sel = comp[start];
|
|
2320
|
+
for (let i = 1; i < half; i++)
|
|
2321
|
+
sel = i === idx ? comp[start + i] : sel;
|
|
2322
|
+
const neg = sel.negate();
|
|
2323
|
+
if (digit === 0)
|
|
2324
|
+
f = f.add(comp[start]);
|
|
2325
|
+
else
|
|
2326
|
+
p = p.add(digit < 0 ? neg : sel);
|
|
2327
|
+
}
|
|
2328
|
+
return { p, f };
|
|
2329
|
+
}
|
|
2330
|
+
// Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
|
|
2331
|
+
// `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
|
|
2332
|
+
// incompatible `transform(...)` layouts and expect a separate cache entry.
|
|
2333
|
+
getWnafPrecomputes(W, point, bits, transform) {
|
|
2334
|
+
let entries = this.wnafPrecomputes.get(point);
|
|
2335
|
+
let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
|
|
2336
|
+
if (!comp) {
|
|
2337
|
+
comp = this.buildWnafTable(point, W, bits);
|
|
2338
|
+
if (typeof transform === "function")
|
|
2339
|
+
comp = { ...comp, comp: transform(comp.comp) };
|
|
2340
|
+
if (!entries) {
|
|
2341
|
+
entries = [];
|
|
2342
|
+
this.wnafPrecomputes.set(point, entries);
|
|
2343
|
+
}
|
|
2344
|
+
entries.push(comp);
|
|
2345
|
+
}
|
|
2346
|
+
return comp;
|
|
2347
|
+
}
|
|
2348
|
+
assertPoint(point) {
|
|
2349
|
+
if (!(point instanceof this.Point))
|
|
2350
|
+
throw new TypeError('"point" expected Point instance, got type=' + typeof point);
|
|
2351
|
+
}
|
|
2352
|
+
// Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
|
|
2353
|
+
// callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
|
|
2354
|
+
// Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
|
|
2355
|
+
validateMulInput(point, scalar) {
|
|
2356
|
+
this.assertPoint(point);
|
|
2357
|
+
if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
|
|
2358
|
+
throw new Error("invalid scalar");
|
|
2359
|
+
}
|
|
2360
|
+
// Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
|
|
2361
|
+
// ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
|
|
2362
|
+
// multiply. `n` must be < 2^bits.
|
|
2363
|
+
runCT(point, n, bits, transform) {
|
|
2364
|
+
const W = getWindowSize(point);
|
|
2365
|
+
if (W === 1)
|
|
2366
|
+
return this.fixedWindowCT(point, n, bits);
|
|
2367
|
+
return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
|
|
2368
|
+
}
|
|
2369
|
+
mulCT(point, scalar, transform) {
|
|
2370
|
+
this.validateMulInput(point, scalar);
|
|
2371
|
+
return this.runCT(point, scalar, this.bits, transform);
|
|
2372
|
+
}
|
|
2373
|
+
mulCTBlinded(point, scalar, transform) {
|
|
2374
|
+
this.validateMulInput(point, scalar);
|
|
2375
|
+
if (this.randomBytes === void 0)
|
|
2376
|
+
throw new Error("randomBytes is required for scalar blinding");
|
|
2377
|
+
const bits = this.Point.Fn.BITS + BLIND_BITS;
|
|
2378
|
+
const blind = this.randomBytes(BLIND_BYTES);
|
|
2379
|
+
if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
|
|
2380
|
+
throw new Error("randomBytes returned invalid byte array");
|
|
2381
|
+
blind[0] = blind[0] & 63 | 128;
|
|
2382
|
+
const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
|
|
2383
|
+
return this.runCT(point, n, bits, transform);
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
|
|
2387
|
+
* A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
|
|
2388
|
+
* far cheaper to build for a single use. The point-operation sequence is independent of `n`:
|
|
2389
|
+
* build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
|
|
2390
|
+
* every table entry, and one addition (adds the identity when the window digit is 0 — never
|
|
2391
|
+
* skipped).
|
|
2392
|
+
*
|
|
2393
|
+
* `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
|
|
2394
|
+
* add), which holds for the Weierstrass/Edwards point types used here. The table is left in
|
|
2395
|
+
* projective form (no normalizeZ): normalizing this small a table costs more than the
|
|
2396
|
+
* mixed-add savings it would buy for a single multiply.
|
|
2397
|
+
* @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
|
|
2398
|
+
* (this path needs no fake accumulator — its op-count is already scalar-independent).
|
|
2399
|
+
*/
|
|
2400
|
+
fixedWindowCT(point, n, bits) {
|
|
2401
|
+
const W = FW_WINDOW;
|
|
2402
|
+
const size = 1 << W;
|
|
2403
|
+
const mask = bitMask(W);
|
|
2404
|
+
const table2 = new Array(size);
|
|
2405
|
+
table2[0] = this.ZERO;
|
|
2406
|
+
for (let i = 1; i < size; i++)
|
|
2407
|
+
table2[i] = table2[i - 1].add(point);
|
|
2408
|
+
const windows = Math.ceil(bits / W);
|
|
2409
|
+
let acc = this.ZERO;
|
|
2410
|
+
for (let window = windows - 1; window >= 0; window--) {
|
|
2411
|
+
if (window !== windows - 1)
|
|
2412
|
+
for (let d = 0; d < W; d++)
|
|
2413
|
+
acc = acc.double();
|
|
2414
|
+
const digit = Number(n >> BigInt(window * W) & mask);
|
|
2415
|
+
let sel = table2[0];
|
|
2416
|
+
for (let i = 1; i < size; i++)
|
|
2417
|
+
sel = i === digit ? table2[i] : sel;
|
|
2418
|
+
acc = acc.add(sel);
|
|
2419
|
+
}
|
|
2420
|
+
return { p: acc, f: acc };
|
|
2421
|
+
}
|
|
2422
|
+
shouldBlind(point, cofactor) {
|
|
2423
|
+
if (this.randomBytes === void 0)
|
|
2424
|
+
return false;
|
|
2425
|
+
if (cofactor === _1n3)
|
|
2426
|
+
return true;
|
|
2427
|
+
if (point !== this.BASE)
|
|
2428
|
+
return false;
|
|
2429
|
+
if (this.baseCanBeBlinded === void 0)
|
|
2430
|
+
this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
|
|
2431
|
+
return this.baseCanBeBlinded;
|
|
2432
|
+
}
|
|
2433
|
+
mulSecret(point, scalar, cofactor, transform) {
|
|
2434
|
+
return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
|
|
2435
|
+
}
|
|
2436
|
+
mulUnsafe(point, scalar, transform) {
|
|
2437
|
+
this.assertPoint(point);
|
|
2438
|
+
if (!isPosBig(scalar))
|
|
2439
|
+
throw new Error("invalid scalar");
|
|
2440
|
+
const W = getWindowSize(point);
|
|
2441
|
+
if (W === 1 || scalar >= this.Point.Fn.ORDER)
|
|
2442
|
+
return mulAddUnsafe(this.Point, [point], [scalar], true);
|
|
2443
|
+
const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
|
|
2444
|
+
return this.wnafCachedCT(precomputes, scalar).p;
|
|
2445
|
+
}
|
|
2446
|
+
// Remembers the window size used for precomputed wNAF multiplication of the given point
|
|
2447
|
+
// and drops any previously built tables. Usually only the base point is precomputed.
|
|
2448
|
+
// W=1 resets the point to the un-precomputed (table-less) paths.
|
|
2449
|
+
// W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
|
|
2450
|
+
setWindowSize(point, W) {
|
|
2451
|
+
this.assertPoint(point);
|
|
2452
|
+
validateW(W, this.bits);
|
|
2453
|
+
const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
|
|
2454
|
+
validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
|
|
2455
|
+
pointWindowSizes.set(point, W);
|
|
2456
|
+
this.wnafPrecomputes.delete(point);
|
|
2457
|
+
}
|
|
2458
|
+
// True when a window size is set: tables themselves are built lazily on first multiply.
|
|
2459
|
+
hasWindowSize(point) {
|
|
2460
|
+
return getWindowSize(point) !== 1;
|
|
2461
|
+
}
|
|
2462
|
+
};
|
|
2463
|
+
function mulAddUnsafe(c, points, scalars, allowOversized = false) {
|
|
2464
|
+
validatePointCons(c);
|
|
2465
|
+
validateMSMPoints(points, c);
|
|
2466
|
+
abool2(allowOversized, "allowOversized");
|
|
2467
|
+
validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
|
|
2468
|
+
if (points.length !== scalars.length)
|
|
2469
|
+
throw new Error("arrays of points and scalars must have equal length");
|
|
2470
|
+
const tables = points.map((p) => oddMultiples(p, 4));
|
|
2471
|
+
const digits = scalars.map((n) => wnafDigits(n, 4));
|
|
2472
|
+
return wnafWalk(c.ZERO, tables, digits);
|
|
2473
|
+
}
|
|
2474
|
+
function createField(order, field, isLE2) {
|
|
2475
|
+
if (field) {
|
|
2476
|
+
if (field.ORDER !== order)
|
|
2477
|
+
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
2478
|
+
validateField(field);
|
|
2479
|
+
return field;
|
|
2480
|
+
} else {
|
|
2481
|
+
return Field(order, { isLE: isLE2 });
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
2485
|
+
if (type !== "weierstrass" && type !== "edwards")
|
|
2486
|
+
throw new Error('expected curve type "weierstrass" or "edwards"');
|
|
2487
|
+
if (FpFnLE === void 0)
|
|
2488
|
+
FpFnLE = type === "edwards";
|
|
2489
|
+
if (!CURVE || typeof CURVE !== "object")
|
|
2490
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
2491
|
+
validateObject(curveOpts);
|
|
2492
|
+
for (const p of ["p", "n", "h"]) {
|
|
2493
|
+
const val = CURVE[p];
|
|
2494
|
+
if (!(isPosBig(val) && val !== _0n3))
|
|
2495
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
2496
|
+
}
|
|
2497
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
2498
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
2499
|
+
const _b = type === "weierstrass" ? "b" : "d";
|
|
2500
|
+
const params = ["Gx", "Gy", "a", _b];
|
|
2501
|
+
for (const p of params) {
|
|
2502
|
+
if (!Fp.isValid(CURVE[p]))
|
|
2503
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
2504
|
+
}
|
|
2505
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
2506
|
+
return { CURVE, Fp, Fn };
|
|
2507
|
+
}
|
|
2508
|
+
function createKeygen(randomSecretKey, getPublicKey) {
|
|
2509
|
+
return function keygen(seed) {
|
|
2510
|
+
const secretKey = randomSecretKey(seed);
|
|
2511
|
+
return { secretKey, publicKey: getPublicKey(secretKey) };
|
|
2512
|
+
};
|
|
2513
|
+
}
|
|
2514
|
+
|
|
2515
|
+
// node_modules/@noble/hashes/hmac.js
|
|
2516
|
+
var _HMAC = class {
|
|
2517
|
+
oHash;
|
|
2518
|
+
iHash;
|
|
2519
|
+
blockLen;
|
|
2520
|
+
outputLen;
|
|
2521
|
+
canXOF = false;
|
|
2522
|
+
finished = false;
|
|
2523
|
+
destroyed = false;
|
|
2524
|
+
constructor(hash, key) {
|
|
2525
|
+
ahash(hash);
|
|
2526
|
+
abytes(key, void 0, "key");
|
|
2527
|
+
this.iHash = hash.create();
|
|
2528
|
+
if (typeof this.iHash.update !== "function")
|
|
2529
|
+
throw new Error("expected Hash instance");
|
|
2530
|
+
this.blockLen = this.iHash.blockLen;
|
|
2531
|
+
this.outputLen = this.iHash.outputLen;
|
|
2532
|
+
const blockLen = this.blockLen;
|
|
2533
|
+
const pad = new Uint8Array(blockLen);
|
|
2534
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
2535
|
+
for (let i = 0; i < pad.length; i++)
|
|
2536
|
+
pad[i] ^= 54;
|
|
2537
|
+
this.iHash.update(pad);
|
|
2538
|
+
this.oHash = hash.create();
|
|
2539
|
+
for (let i = 0; i < pad.length; i++)
|
|
2540
|
+
pad[i] ^= 54 ^ 92;
|
|
2541
|
+
this.oHash.update(pad);
|
|
2542
|
+
clean(pad);
|
|
2543
|
+
}
|
|
2544
|
+
update(buf) {
|
|
2545
|
+
aexists(this);
|
|
2546
|
+
this.iHash.update(buf);
|
|
2547
|
+
return this;
|
|
2548
|
+
}
|
|
2549
|
+
digestInto(out) {
|
|
2550
|
+
aexists(this);
|
|
2551
|
+
aoutput(out, this);
|
|
2552
|
+
this.finished = true;
|
|
2553
|
+
const buf = out.subarray(0, this.outputLen);
|
|
2554
|
+
this.iHash.digestInto(buf);
|
|
2555
|
+
this.oHash.update(buf);
|
|
2556
|
+
this.oHash.digestInto(buf);
|
|
2557
|
+
this.destroy();
|
|
2558
|
+
}
|
|
2559
|
+
digest() {
|
|
2560
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
2561
|
+
this.digestInto(out);
|
|
2562
|
+
return out;
|
|
2563
|
+
}
|
|
2564
|
+
_cloneInto(to) {
|
|
2565
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
2566
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
|
|
2567
|
+
to = to;
|
|
2568
|
+
to.finished = finished;
|
|
2569
|
+
to.destroyed = destroyed;
|
|
2570
|
+
to.blockLen = blockLen;
|
|
2571
|
+
to.outputLen = outputLen;
|
|
2572
|
+
to.canXOF = canXOF;
|
|
2573
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
2574
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
2575
|
+
return to;
|
|
2576
|
+
}
|
|
2577
|
+
clone() {
|
|
2578
|
+
return this._cloneInto();
|
|
2579
|
+
}
|
|
2580
|
+
destroy() {
|
|
2581
|
+
this.destroyed = true;
|
|
2582
|
+
this.oHash.destroy();
|
|
2583
|
+
this.iHash.destroy();
|
|
2584
|
+
}
|
|
2585
|
+
};
|
|
2586
|
+
var hmac = /* @__PURE__ */ (() => {
|
|
2587
|
+
const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
|
|
2588
|
+
hmac_.create = (hash, key) => new _HMAC(hash, key);
|
|
2589
|
+
return hmac_;
|
|
2590
|
+
})();
|
|
2591
|
+
|
|
2592
|
+
// node_modules/@noble/curves/abstract/der.js
|
|
2593
|
+
var _0n4 = /* @__PURE__ */ BigInt(0);
|
|
2594
|
+
var DERErr = class extends Error {
|
|
2595
|
+
constructor(m = "") {
|
|
2596
|
+
super(m);
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
var _DER = {
|
|
2600
|
+
// asn.1 DER encoding utils
|
|
2601
|
+
Err: DERErr,
|
|
2602
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
2603
|
+
_tlv: {
|
|
2604
|
+
encode: (tag, data) => {
|
|
2605
|
+
const { Err: E } = _DER;
|
|
2606
|
+
asafenumber(tag, "tag");
|
|
2607
|
+
if (tag < 0 || tag > 255)
|
|
2608
|
+
throw new E("tlv.encode: wrong tag");
|
|
2609
|
+
astring(data, "data");
|
|
2610
|
+
if (data.length & 1)
|
|
2611
|
+
throw new E("tlv.encode: unpadded data");
|
|
2612
|
+
const dataLen = data.length / 2;
|
|
2613
|
+
const len = numberToHexUnpadded(dataLen);
|
|
2614
|
+
if (len.length / 2 & 128)
|
|
2615
|
+
throw new E("tlv.encode: long form length too big");
|
|
2616
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
2617
|
+
const t = numberToHexUnpadded(tag);
|
|
2618
|
+
return t + lenLen + len + data;
|
|
2619
|
+
},
|
|
2620
|
+
// v - value, l - left bytes (unparsed)
|
|
2621
|
+
decode(tag, data) {
|
|
2622
|
+
const { Err: E } = _DER;
|
|
2623
|
+
data = abytes2(data, void 0, "DER data");
|
|
2624
|
+
let pos = 0;
|
|
2625
|
+
if (tag < 0 || tag > 255)
|
|
2626
|
+
throw new E("tlv.decode: wrong tag");
|
|
2627
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
2628
|
+
throw new E("tlv.decode: wrong tlv");
|
|
2629
|
+
const first = data[pos++];
|
|
2630
|
+
const isLong = !!(first & 128);
|
|
2631
|
+
let length = 0;
|
|
2632
|
+
if (!isLong)
|
|
2633
|
+
length = first;
|
|
2634
|
+
else {
|
|
2635
|
+
const lenLen = first & 127;
|
|
2636
|
+
if (!lenLen)
|
|
2637
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
2638
|
+
if (lenLen > 4)
|
|
2639
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
2640
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
2641
|
+
if (lengthBytes.length !== lenLen)
|
|
2642
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
2643
|
+
if (lengthBytes[0] === 0)
|
|
2644
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
2645
|
+
for (const b of lengthBytes)
|
|
2646
|
+
length = length << 8 | b;
|
|
2647
|
+
pos += lenLen;
|
|
2648
|
+
if (length < 128)
|
|
2649
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
2650
|
+
}
|
|
2651
|
+
const v = data.subarray(pos, pos + length);
|
|
2652
|
+
if (v.length !== length)
|
|
2653
|
+
throw new E("tlv.decode: wrong value length");
|
|
2654
|
+
return { v, l: data.subarray(pos + length) };
|
|
2655
|
+
}
|
|
2656
|
+
},
|
|
2657
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
2658
|
+
// since we always use positive integers here. It must always be empty:
|
|
2659
|
+
// - add zero byte if exists
|
|
2660
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
2661
|
+
_int: {
|
|
2662
|
+
encode(num) {
|
|
2663
|
+
const { Err: E } = _DER;
|
|
2664
|
+
abignumber(num);
|
|
2665
|
+
if (num < _0n4)
|
|
2666
|
+
throw new E("integer: negative integers are not allowed");
|
|
2667
|
+
let hex = numberToHexUnpadded(num);
|
|
2668
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
2669
|
+
hex = "00" + hex;
|
|
2670
|
+
if (hex.length & 1)
|
|
2671
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
2672
|
+
return hex;
|
|
2673
|
+
},
|
|
2674
|
+
decode(data) {
|
|
2675
|
+
const { Err: E } = _DER;
|
|
2676
|
+
if (data.length < 1)
|
|
2677
|
+
throw new E("invalid signature integer: empty");
|
|
2678
|
+
if (data[0] & 128)
|
|
2679
|
+
throw new E("invalid signature integer: negative");
|
|
2680
|
+
if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
|
|
2681
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
2682
|
+
return bytesToNumberBE(data);
|
|
2683
|
+
}
|
|
2684
|
+
},
|
|
2685
|
+
toSig(bytes, maxScalarBytes) {
|
|
2686
|
+
const { Err: E, _int: int, _tlv: tlv } = _DER;
|
|
2687
|
+
if (maxScalarBytes !== void 0) {
|
|
2688
|
+
asafenumber(maxScalarBytes, "maxScalarBytes");
|
|
2689
|
+
if (maxScalarBytes < 1)
|
|
2690
|
+
throw new E("invalid signature: maxScalarBytes must be positive");
|
|
2691
|
+
}
|
|
2692
|
+
const data = abytes2(bytes, void 0, "signature");
|
|
2693
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
2694
|
+
if (seqLeftBytes.length)
|
|
2695
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
2696
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
2697
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
2698
|
+
if (sLeftBytes.length)
|
|
2699
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
2700
|
+
if (maxScalarBytes !== void 0 && (rBytes.length > maxScalarBytes || sBytes.length > maxScalarBytes))
|
|
2701
|
+
throw new E("invalid signature: integer too large");
|
|
2702
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
2703
|
+
},
|
|
2704
|
+
hexFromSig(sig) {
|
|
2705
|
+
const { _tlv: tlv, _int: int } = _DER;
|
|
2706
|
+
validateObject(sig, { r: "bigint", s: "bigint" }, {}, "sig");
|
|
2707
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
2708
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
2709
|
+
const seq = rs + ss;
|
|
2710
|
+
return tlv.encode(48, seq);
|
|
2711
|
+
}
|
|
2712
|
+
};
|
|
2713
|
+
var DER = /* @__PURE__ */ (() => {
|
|
2714
|
+
Object.freeze(_DER._tlv);
|
|
2715
|
+
Object.freeze(_DER._int);
|
|
2716
|
+
return Object.freeze(_DER);
|
|
2717
|
+
})();
|
|
2718
|
+
|
|
2719
|
+
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
2720
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
2721
|
+
function _splitEndoScalar(k, basis, n) {
|
|
2722
|
+
aInRange("scalar", k, _0n5, n);
|
|
2723
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
2724
|
+
const c1 = divNearest(b2 * k, n);
|
|
2725
|
+
const c2 = divNearest(-b1 * k, n);
|
|
2726
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
2727
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
2728
|
+
const k1neg = k1 < _0n5;
|
|
2729
|
+
const k2neg = k2 < _0n5;
|
|
2730
|
+
if (k1neg)
|
|
2731
|
+
k1 = -k1;
|
|
2732
|
+
if (k2neg)
|
|
2733
|
+
k2 = -k2;
|
|
2734
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
2735
|
+
if (k1 < _0n5 || k1 >= MAX_NUM || k2 < _0n5 || k2 >= MAX_NUM) {
|
|
2736
|
+
throw new Error("splitScalar (endomorphism): failed for k");
|
|
2737
|
+
}
|
|
2738
|
+
return { k1neg, k1, k2neg, k2 };
|
|
2739
|
+
}
|
|
2740
|
+
function validateSigFormat(format) {
|
|
2741
|
+
if (!["compact", "recovered", "der"].includes(format))
|
|
2742
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
2743
|
+
return format;
|
|
2744
|
+
}
|
|
2745
|
+
function validateSigOpts(opts, def) {
|
|
2746
|
+
validateObject(opts);
|
|
2747
|
+
const optsn = {};
|
|
2748
|
+
for (let optName of Object.keys(def)) {
|
|
2749
|
+
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
2750
|
+
}
|
|
2751
|
+
abool2(optsn.lowS, "lowS");
|
|
2752
|
+
abool2(optsn.prehash, "prehash");
|
|
2753
|
+
if (optsn.format !== void 0)
|
|
2754
|
+
validateSigFormat(optsn.format);
|
|
2755
|
+
return optsn;
|
|
2756
|
+
}
|
|
2757
|
+
var _0n5 = /* @__PURE__ */ BigInt(0);
|
|
2758
|
+
var _1n4 = /* @__PURE__ */ BigInt(1);
|
|
2759
|
+
var _2n2 = /* @__PURE__ */ BigInt(2);
|
|
2760
|
+
var _3n2 = /* @__PURE__ */ BigInt(3);
|
|
2761
|
+
var _4n3 = /* @__PURE__ */ BigInt(4);
|
|
2762
|
+
function weierstrass(params, extraOpts = {}) {
|
|
2763
|
+
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
2764
|
+
const Fp = validated.Fp;
|
|
2765
|
+
const Fn = validated.Fn;
|
|
2766
|
+
let CURVE = validated.CURVE;
|
|
2767
|
+
const { h: cofactor, n: CURVE_ORDER } = CURVE;
|
|
2768
|
+
validateObject(extraOpts, {}, {
|
|
2769
|
+
allowInfinityPoint: "boolean",
|
|
2770
|
+
clearCofactor: "function",
|
|
2771
|
+
isTorsionFree: "function",
|
|
2772
|
+
fromBytes: "function",
|
|
2773
|
+
toBytes: "function",
|
|
2774
|
+
endo: "object",
|
|
2775
|
+
randomBytes: "function"
|
|
2776
|
+
});
|
|
2777
|
+
const { endo: endoOpts, allowInfinityPoint, clearCofactor, isTorsionFree, fromBytes, toBytes } = extraOpts;
|
|
2778
|
+
const randomBytes3 = extraOpts.randomBytes === void 0 ? randomBytes2 : extraOpts.randomBytes;
|
|
2779
|
+
if (endoOpts) {
|
|
2780
|
+
if (!Fp.is0(CURVE.a) || typeof endoOpts.beta !== "bigint" || !Array.isArray(endoOpts.basises)) {
|
|
2781
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
const endo = endoOpts ? {
|
|
2785
|
+
beta: endoOpts.beta,
|
|
2786
|
+
basises: endoOpts.basises.map((basis) => [...basis])
|
|
2787
|
+
} : void 0;
|
|
2788
|
+
const lengths = getWLengths(Fp, Fn);
|
|
2789
|
+
function assertCompressionIsSupported() {
|
|
2790
|
+
if (!Fp.isOdd)
|
|
2791
|
+
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
2792
|
+
}
|
|
2793
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
2794
|
+
if (point.is0()) {
|
|
2795
|
+
if (!allowInfinityPoint)
|
|
2796
|
+
throw new Error("bad point: ZERO");
|
|
2797
|
+
return Uint8Array.of(0);
|
|
2798
|
+
}
|
|
2799
|
+
const { x, y } = point.toAffine();
|
|
2800
|
+
const bx = Fp.toBytes(x);
|
|
2801
|
+
abool2(isCompressed, "isCompressed");
|
|
2802
|
+
if (isCompressed) {
|
|
2803
|
+
assertCompressionIsSupported();
|
|
2804
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
2805
|
+
return concatBytes2(pprefix(hasEvenY), bx);
|
|
2806
|
+
} else {
|
|
2807
|
+
return concatBytes2(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
function pointFromBytes(bytes) {
|
|
2811
|
+
abytes2(bytes, void 0, "Point");
|
|
2812
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
2813
|
+
const length = bytes.length;
|
|
2814
|
+
const head = bytes[0];
|
|
2815
|
+
const tail = bytes.subarray(1);
|
|
2816
|
+
if (allowInfinityPoint && length === 1 && head === 0)
|
|
2817
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
2818
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
2819
|
+
const x = Fp.fromBytes(tail);
|
|
2820
|
+
if (!Fp.isValid(x))
|
|
2821
|
+
throw new Error("bad point: is not on curve, wrong x");
|
|
2822
|
+
const y2 = weierstrassEquation(x);
|
|
2823
|
+
let y;
|
|
2824
|
+
try {
|
|
2825
|
+
y = Fp.sqrt(y2);
|
|
2826
|
+
} catch (sqrtError) {
|
|
2827
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
2828
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
2829
|
+
}
|
|
2830
|
+
assertCompressionIsSupported();
|
|
2831
|
+
const evenY = Fp.isOdd(y);
|
|
2832
|
+
const evenH = (head & 1) === 1;
|
|
2833
|
+
if (evenH !== evenY)
|
|
2834
|
+
y = Fp.neg(y);
|
|
2835
|
+
return { x, y };
|
|
2836
|
+
} else if (length === uncomp && head === 4) {
|
|
2837
|
+
const L = Fp.BYTES;
|
|
2838
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
2839
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
2840
|
+
if (!isValidXY(x, y))
|
|
2841
|
+
throw new Error("bad point: is not on curve");
|
|
2842
|
+
return { x, y };
|
|
2843
|
+
} else {
|
|
2844
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
2845
|
+
}
|
|
2846
|
+
}
|
|
2847
|
+
const encodePoint = toBytes === void 0 ? pointToBytes : toBytes;
|
|
2848
|
+
const decodePoint = fromBytes === void 0 ? pointFromBytes : fromBytes;
|
|
2849
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
2850
|
+
const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);
|
|
2851
|
+
function weierstrassEquation(x) {
|
|
2852
|
+
const x2 = Fp.sqr(x);
|
|
2853
|
+
const x3 = Fp.mul(x2, x);
|
|
2854
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
2855
|
+
}
|
|
2856
|
+
function isValidXY(x, y) {
|
|
2857
|
+
const left = Fp.sqr(y);
|
|
2858
|
+
const right = weierstrassEquation(x);
|
|
2859
|
+
return Fp.eql(left, right);
|
|
2860
|
+
}
|
|
2861
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
2862
|
+
throw new Error("bad curve params: generator point");
|
|
2863
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n3);
|
|
2864
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
2865
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
2866
|
+
throw new Error("bad curve params: a or b");
|
|
2867
|
+
function acoord(title, n, banZero = false) {
|
|
2868
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
2869
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
2870
|
+
return typeof n === "object" && n !== null ? Fp.create(n) : n;
|
|
2871
|
+
}
|
|
2872
|
+
function aprjpoint(other) {
|
|
2873
|
+
if (!(other instanceof Point))
|
|
2874
|
+
throw new Error("Weierstrass Point expected");
|
|
2875
|
+
}
|
|
2876
|
+
function splitEndoScalarN(k) {
|
|
2877
|
+
if (!endo || !endo.basises)
|
|
2878
|
+
throw new Error("no endo");
|
|
2879
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
2880
|
+
}
|
|
2881
|
+
function pushWnafPair(points, scalars, p, k) {
|
|
2882
|
+
if (!Fn.isValid(k))
|
|
2883
|
+
throw new RangeError("invalid scalar: out of range");
|
|
2884
|
+
if (endo) {
|
|
2885
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);
|
|
2886
|
+
const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);
|
|
2887
|
+
points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);
|
|
2888
|
+
scalars.push(k1, k2);
|
|
2889
|
+
} else {
|
|
2890
|
+
points.push(p);
|
|
2891
|
+
scalars.push(k);
|
|
2892
|
+
}
|
|
2893
|
+
}
|
|
2894
|
+
const validityCache = /* @__PURE__ */ new WeakSet();
|
|
2895
|
+
class Point {
|
|
2896
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
2897
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
2898
|
+
static Fp = Fp;
|
|
2899
|
+
static Fn = Fn;
|
|
2900
|
+
X;
|
|
2901
|
+
Y;
|
|
2902
|
+
Z;
|
|
2903
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2904
|
+
constructor(X, Y, Z) {
|
|
2905
|
+
this.X = acoord("x", X);
|
|
2906
|
+
this.Y = acoord("y", Y, true);
|
|
2907
|
+
this.Z = acoord("z", Z);
|
|
2908
|
+
Object.freeze(this);
|
|
2909
|
+
}
|
|
2910
|
+
static CURVE() {
|
|
2911
|
+
return CURVE;
|
|
2912
|
+
}
|
|
2913
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
2914
|
+
static fromAffine(p) {
|
|
2915
|
+
const { x, y } = p || {};
|
|
2916
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
2917
|
+
throw new Error("invalid affine point");
|
|
2918
|
+
if (p instanceof Point)
|
|
2919
|
+
throw new Error("projective point not allowed");
|
|
2920
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
2921
|
+
return Point.ZERO;
|
|
2922
|
+
return new Point(x, y, Fp.ONE);
|
|
2923
|
+
}
|
|
2924
|
+
static fromBytes(bytes) {
|
|
2925
|
+
const P = Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point")));
|
|
2926
|
+
P.assertValidity();
|
|
2927
|
+
return P;
|
|
2928
|
+
}
|
|
2929
|
+
static fromHex(hex) {
|
|
2930
|
+
return Point.fromBytes(hexToBytes2(hex));
|
|
2931
|
+
}
|
|
2932
|
+
get x() {
|
|
2933
|
+
return this.toAffine().x;
|
|
2934
|
+
}
|
|
2935
|
+
get y() {
|
|
2936
|
+
return this.toAffine().y;
|
|
2937
|
+
}
|
|
2938
|
+
/**
|
|
2939
|
+
* @param isLazy - true will defer table computation until the first multiplication
|
|
2940
|
+
*/
|
|
2941
|
+
precompute(windowSize = 6, isLazy = true) {
|
|
2942
|
+
wnaf.setWindowSize(this, windowSize);
|
|
2943
|
+
if (!isLazy)
|
|
2944
|
+
this.multiply(_3n2);
|
|
2945
|
+
return this;
|
|
2946
|
+
}
|
|
2947
|
+
// TODO: return `this`
|
|
2948
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
2949
|
+
assertValidity() {
|
|
2950
|
+
const p = this;
|
|
2951
|
+
if (p.is0()) {
|
|
2952
|
+
if (allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
|
|
2953
|
+
return;
|
|
2954
|
+
throw new Error("bad point: ZERO");
|
|
2955
|
+
}
|
|
2956
|
+
if (validityCache.has(p))
|
|
2957
|
+
return;
|
|
2958
|
+
const { x, y } = p.toAffine();
|
|
2959
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
2960
|
+
throw new Error("bad point: x or y not field elements");
|
|
2961
|
+
if (!isValidXY(x, y))
|
|
2962
|
+
throw new Error("bad point: equation left != right");
|
|
2963
|
+
if (!p.isTorsionFree())
|
|
2964
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
2965
|
+
validityCache.add(p);
|
|
2966
|
+
}
|
|
2967
|
+
hasEvenY() {
|
|
2968
|
+
const { y } = this.toAffine();
|
|
2969
|
+
if (!Fp.isOdd)
|
|
2970
|
+
throw new Error("Field doesn't support isOdd");
|
|
2971
|
+
return !Fp.isOdd(y);
|
|
2972
|
+
}
|
|
2973
|
+
/** Compare one point to another. */
|
|
2974
|
+
equals(other) {
|
|
2975
|
+
aprjpoint(other);
|
|
2976
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2977
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
2978
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
2979
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
2980
|
+
return U1 && U2;
|
|
2981
|
+
}
|
|
2982
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
2983
|
+
negate() {
|
|
2984
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
2985
|
+
}
|
|
2986
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
2987
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
2988
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
2989
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
2990
|
+
double() {
|
|
2991
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
2992
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
2993
|
+
let t0 = Fp.mul(X1, X1);
|
|
2994
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
2995
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
2996
|
+
let t3 = Fp.mul(X1, Y1);
|
|
2997
|
+
t3 = Fp.add(t3, t3);
|
|
2998
|
+
Z3 = Fp.mul(X1, Z1);
|
|
2999
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3000
|
+
X3 = mulA(Z3);
|
|
3001
|
+
Y3 = Fp.mul(b3, t2);
|
|
3002
|
+
Y3 = Fp.add(X3, Y3);
|
|
3003
|
+
X3 = Fp.sub(t1, Y3);
|
|
3004
|
+
Y3 = Fp.add(t1, Y3);
|
|
3005
|
+
Y3 = Fp.mul(X3, Y3);
|
|
3006
|
+
X3 = Fp.mul(t3, X3);
|
|
3007
|
+
Z3 = Fp.mul(b3, Z3);
|
|
3008
|
+
t2 = mulA(t2);
|
|
3009
|
+
t3 = Fp.sub(t0, t2);
|
|
3010
|
+
t3 = mulA(t3);
|
|
3011
|
+
t3 = Fp.add(t3, Z3);
|
|
3012
|
+
Z3 = Fp.add(t0, t0);
|
|
3013
|
+
t0 = Fp.add(Z3, t0);
|
|
3014
|
+
t0 = Fp.add(t0, t2);
|
|
3015
|
+
t0 = Fp.mul(t0, t3);
|
|
3016
|
+
Y3 = Fp.add(Y3, t0);
|
|
3017
|
+
t2 = Fp.mul(Y1, Z1);
|
|
3018
|
+
t2 = Fp.add(t2, t2);
|
|
3019
|
+
t0 = Fp.mul(t2, t3);
|
|
3020
|
+
X3 = Fp.sub(X3, t0);
|
|
3021
|
+
Z3 = Fp.mul(t2, t1);
|
|
3022
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3023
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3024
|
+
return new Point(X3, Y3, Z3);
|
|
3025
|
+
}
|
|
3026
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
3027
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
3028
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
3029
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
3030
|
+
add(other) {
|
|
3031
|
+
aprjpoint(other);
|
|
3032
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
3033
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
3034
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
3035
|
+
let t0 = Fp.mul(X1, X2);
|
|
3036
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
3037
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
3038
|
+
let t3 = Fp.add(X1, Y1);
|
|
3039
|
+
let t4 = Fp.add(X2, Y2);
|
|
3040
|
+
t3 = Fp.mul(t3, t4);
|
|
3041
|
+
t4 = Fp.add(t0, t1);
|
|
3042
|
+
t3 = Fp.sub(t3, t4);
|
|
3043
|
+
t4 = Fp.add(X1, Z1);
|
|
3044
|
+
let t5 = Fp.add(X2, Z2);
|
|
3045
|
+
t4 = Fp.mul(t4, t5);
|
|
3046
|
+
t5 = Fp.add(t0, t2);
|
|
3047
|
+
t4 = Fp.sub(t4, t5);
|
|
3048
|
+
t5 = Fp.add(Y1, Z1);
|
|
3049
|
+
X3 = Fp.add(Y2, Z2);
|
|
3050
|
+
t5 = Fp.mul(t5, X3);
|
|
3051
|
+
X3 = Fp.add(t1, t2);
|
|
3052
|
+
t5 = Fp.sub(t5, X3);
|
|
3053
|
+
Z3 = mulA(t4);
|
|
3054
|
+
X3 = Fp.mul(b3, t2);
|
|
3055
|
+
Z3 = Fp.add(X3, Z3);
|
|
3056
|
+
X3 = Fp.sub(t1, Z3);
|
|
3057
|
+
Z3 = Fp.add(t1, Z3);
|
|
3058
|
+
Y3 = Fp.mul(X3, Z3);
|
|
3059
|
+
t1 = Fp.add(t0, t0);
|
|
3060
|
+
t1 = Fp.add(t1, t0);
|
|
3061
|
+
t2 = mulA(t2);
|
|
3062
|
+
t4 = Fp.mul(b3, t4);
|
|
3063
|
+
t1 = Fp.add(t1, t2);
|
|
3064
|
+
t2 = Fp.sub(t0, t2);
|
|
3065
|
+
t2 = mulA(t2);
|
|
3066
|
+
t4 = Fp.add(t4, t2);
|
|
3067
|
+
t0 = Fp.mul(t1, t4);
|
|
3068
|
+
Y3 = Fp.add(Y3, t0);
|
|
3069
|
+
t0 = Fp.mul(t5, t4);
|
|
3070
|
+
X3 = Fp.mul(t3, X3);
|
|
3071
|
+
X3 = Fp.sub(X3, t0);
|
|
3072
|
+
t0 = Fp.mul(t3, t1);
|
|
3073
|
+
Z3 = Fp.mul(t5, Z3);
|
|
3074
|
+
Z3 = Fp.add(Z3, t0);
|
|
3075
|
+
return new Point(X3, Y3, Z3);
|
|
3076
|
+
}
|
|
3077
|
+
subtract(other) {
|
|
3078
|
+
aprjpoint(other);
|
|
3079
|
+
return this.add(other.negate());
|
|
3080
|
+
}
|
|
3081
|
+
is0() {
|
|
3082
|
+
return this.equals(Point.ZERO);
|
|
3083
|
+
}
|
|
3084
|
+
/**
|
|
3085
|
+
* Constant time multiplication.
|
|
3086
|
+
* Uses precomputed tables (signed fixed-window wNAF) when available.
|
|
3087
|
+
* Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.
|
|
3088
|
+
* @param scalar - by which the point would be multiplied
|
|
3089
|
+
* @returns New point
|
|
3090
|
+
*/
|
|
3091
|
+
multiply(scalar) {
|
|
3092
|
+
if (!Fn.isValidNot0(scalar))
|
|
3093
|
+
throw new RangeError("invalid scalar: out of range");
|
|
3094
|
+
const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
|
|
3095
|
+
return normalize([p, f])[0];
|
|
3096
|
+
}
|
|
3097
|
+
/**
|
|
3098
|
+
* Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting
|
|
3099
|
+
* when available (two half-width scalars sharing one halved doubling chain).
|
|
3100
|
+
* It's faster, but should only be used when you don't care about
|
|
3101
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
3102
|
+
*/
|
|
3103
|
+
multiplyUnsafe(scalar) {
|
|
3104
|
+
const p = this;
|
|
3105
|
+
const sc = scalar;
|
|
3106
|
+
if (!Fn.isValid(sc))
|
|
3107
|
+
throw new RangeError("invalid scalar: out of range");
|
|
3108
|
+
if (sc === _0n5 || p.is0())
|
|
3109
|
+
return Point.ZERO;
|
|
3110
|
+
if (sc === _1n4)
|
|
3111
|
+
return p;
|
|
3112
|
+
if (wnaf.hasWindowSize(this))
|
|
3113
|
+
return wnaf.mulUnsafe(p, sc, normalize);
|
|
3114
|
+
const points = [];
|
|
3115
|
+
const scalars = [];
|
|
3116
|
+
pushWnafPair(points, scalars, p, sc);
|
|
3117
|
+
return mulAddUnsafe(Point, points, scalars);
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Non-constant-time double-scalar multiplication `a⋅this + b⋅other` (Strauss–Shamir).
|
|
3121
|
+
* Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism
|
|
3122
|
+
* (when available) halves the chain again by splitting each scalar into two half-width
|
|
3123
|
+
* parts. Used by ECDSA verification and public-key recovery for `R = u1⋅G + u2⋅P`.
|
|
3124
|
+
* Only for public scalars.
|
|
3125
|
+
*/
|
|
3126
|
+
mulAddUnsafe(a, other, b) {
|
|
3127
|
+
aprjpoint(other);
|
|
3128
|
+
const points = [];
|
|
3129
|
+
const scalars = [];
|
|
3130
|
+
pushWnafPair(points, scalars, this, a);
|
|
3131
|
+
pushWnafPair(points, scalars, other, b);
|
|
3132
|
+
return mulAddUnsafe(Point, points, scalars);
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
3136
|
+
* (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
|
|
3137
|
+
* @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
3138
|
+
*/
|
|
3139
|
+
toAffine(invertedZ) {
|
|
3140
|
+
const p = this;
|
|
3141
|
+
let iz = invertedZ;
|
|
3142
|
+
if (iz != null && !Fp.isValid(iz))
|
|
3143
|
+
throw new RangeError('"invertedZ" expected valid field element');
|
|
3144
|
+
const { X, Y, Z } = p;
|
|
3145
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
3146
|
+
return { x: X, y: Y };
|
|
3147
|
+
const is0 = p.is0();
|
|
3148
|
+
if (iz == null)
|
|
3149
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
3150
|
+
const x = Fp.mul(X, iz);
|
|
3151
|
+
const y = Fp.mul(Y, iz);
|
|
3152
|
+
const zz = Fp.mul(Z, iz);
|
|
3153
|
+
if (is0)
|
|
3154
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
3155
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
3156
|
+
throw new Error("invZ was invalid");
|
|
3157
|
+
return { x, y };
|
|
3158
|
+
}
|
|
3159
|
+
/**
|
|
3160
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
3161
|
+
* Always torsion-free for cofactor=1 curves.
|
|
3162
|
+
*/
|
|
3163
|
+
isTorsionFree() {
|
|
3164
|
+
if (cofactor === _1n4)
|
|
3165
|
+
return true;
|
|
3166
|
+
if (isTorsionFree)
|
|
3167
|
+
return isTorsionFree(Point, this);
|
|
3168
|
+
return wnaf.mulUnsafe(this, CURVE_ORDER).is0();
|
|
3169
|
+
}
|
|
3170
|
+
clearCofactor() {
|
|
3171
|
+
if (cofactor === _1n4)
|
|
3172
|
+
return this;
|
|
3173
|
+
if (clearCofactor)
|
|
3174
|
+
return clearCofactor(Point, this);
|
|
3175
|
+
return this.multiplyUnsafe(cofactor);
|
|
3176
|
+
}
|
|
3177
|
+
isSmallOrder() {
|
|
3178
|
+
if (cofactor === _1n4)
|
|
3179
|
+
return this.is0();
|
|
3180
|
+
return this.clearCofactor().is0();
|
|
3181
|
+
}
|
|
3182
|
+
toBytes(isCompressed = true) {
|
|
3183
|
+
abool2(isCompressed, "isCompressed");
|
|
3184
|
+
this.assertValidity();
|
|
3185
|
+
return encodePoint(Point, this, isCompressed);
|
|
3186
|
+
}
|
|
3187
|
+
toHex(isCompressed = true) {
|
|
3188
|
+
return bytesToHex2(this.toBytes(isCompressed));
|
|
3189
|
+
}
|
|
3190
|
+
toString() {
|
|
3191
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
const normalize = (points) => normalizeZ(Point, points);
|
|
3195
|
+
const wnaf = new ScalarMultiplier(Point, randomBytes3);
|
|
3196
|
+
if (wnaf.bits >= 6)
|
|
3197
|
+
Point.BASE.precompute(6);
|
|
3198
|
+
Object.freeze(Point.prototype);
|
|
3199
|
+
Object.freeze(Point);
|
|
3200
|
+
return Point;
|
|
3201
|
+
}
|
|
3202
|
+
function pprefix(hasEvenY) {
|
|
3203
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
3204
|
+
}
|
|
3205
|
+
function getWLengths(Fp, Fn) {
|
|
3206
|
+
return {
|
|
3207
|
+
secretKey: Fn.BYTES,
|
|
3208
|
+
publicKey: 1 + Fp.BYTES,
|
|
3209
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
3210
|
+
publicKeyHasPrefix: true,
|
|
3211
|
+
// Raw compact `(r || s)` signature width; DER and recovered signatures use
|
|
3212
|
+
// different lengths outside this helper.
|
|
3213
|
+
signature: 2 * Fn.BYTES
|
|
3214
|
+
};
|
|
3215
|
+
}
|
|
3216
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
3217
|
+
validatePointCons(Point);
|
|
3218
|
+
const { Fn } = Point;
|
|
3219
|
+
const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes;
|
|
3220
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), {
|
|
3221
|
+
seed: Math.max(getMinHashLength(Fn.ORDER), 16)
|
|
3222
|
+
});
|
|
3223
|
+
function isValidSecretKey(secretKey) {
|
|
3224
|
+
try {
|
|
3225
|
+
const num = Fn.fromBytes(secretKey);
|
|
3226
|
+
return Fn.isValidNot0(num);
|
|
3227
|
+
} catch (error) {
|
|
3228
|
+
return false;
|
|
3229
|
+
}
|
|
3230
|
+
}
|
|
3231
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
3232
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
3233
|
+
try {
|
|
3234
|
+
const l = publicKey.length;
|
|
3235
|
+
if (isCompressed === true && l !== comp)
|
|
3236
|
+
return false;
|
|
3237
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
3238
|
+
return false;
|
|
3239
|
+
return !Point.fromBytes(publicKey).is0();
|
|
3240
|
+
} catch (error) {
|
|
3241
|
+
return false;
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
function randomSecretKey(seed) {
|
|
3245
|
+
seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
|
|
3246
|
+
return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
3247
|
+
}
|
|
3248
|
+
function getPublicKey(secretKey, isCompressed = true) {
|
|
3249
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
3250
|
+
}
|
|
3251
|
+
function isProbPub(item) {
|
|
3252
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
3253
|
+
const allowedLengths = Fn._lengths;
|
|
3254
|
+
if (!isBytes2(item))
|
|
3255
|
+
return void 0;
|
|
3256
|
+
const l = abytes2(item, void 0, "key").length;
|
|
3257
|
+
const isPub = l === publicKey || l === publicKeyUncompressed;
|
|
3258
|
+
const isSec = l === secretKey || !!allowedLengths?.includes(l);
|
|
3259
|
+
if (isPub && isSec)
|
|
3260
|
+
return void 0;
|
|
3261
|
+
return isPub;
|
|
3262
|
+
}
|
|
3263
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
3264
|
+
if (isProbPub(secretKeyA) === true)
|
|
3265
|
+
throw new Error("first arg must be private key");
|
|
3266
|
+
if (isProbPub(publicKeyB) === false)
|
|
3267
|
+
throw new Error("second arg must be public key");
|
|
3268
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
3269
|
+
const b = Point.fromBytes(publicKeyB);
|
|
3270
|
+
if (b.is0())
|
|
3271
|
+
throw new Error("invalid public key: point at infinity");
|
|
3272
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
3273
|
+
}
|
|
3274
|
+
const utils = {
|
|
3275
|
+
isValidSecretKey,
|
|
3276
|
+
isValidPublicKey,
|
|
3277
|
+
randomSecretKey
|
|
3278
|
+
};
|
|
3279
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey);
|
|
3280
|
+
Object.freeze(utils);
|
|
3281
|
+
Object.freeze(lengths);
|
|
3282
|
+
return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });
|
|
3283
|
+
}
|
|
3284
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
3285
|
+
validatePointCons(Point);
|
|
3286
|
+
const hash_ = hash;
|
|
3287
|
+
ahash(hash_);
|
|
3288
|
+
validateObject(ecdsaOpts, {}, {
|
|
3289
|
+
hmac: "function",
|
|
3290
|
+
lowS: "boolean",
|
|
3291
|
+
randomBytes: "function",
|
|
3292
|
+
bits2int: "function",
|
|
3293
|
+
bits2int_modN: "function"
|
|
3294
|
+
});
|
|
3295
|
+
const opts = Object.assign({}, ecdsaOpts);
|
|
3296
|
+
const randomBytes3 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
|
|
3297
|
+
const hmac2 = opts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : opts.hmac;
|
|
3298
|
+
const { Fp, Fn } = Point;
|
|
3299
|
+
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
|
|
3300
|
+
const blindLength = getMinHashLength(CURVE_ORDER);
|
|
3301
|
+
const csprng = probeRandomBytes(randomBytes3, blindLength);
|
|
3302
|
+
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);
|
|
3303
|
+
const defaultSigOpts = {
|
|
3304
|
+
prehash: true,
|
|
3305
|
+
lowS: typeof opts.lowS === "boolean" ? opts.lowS : true,
|
|
3306
|
+
format: "compact",
|
|
3307
|
+
extraEntropy: false
|
|
3308
|
+
};
|
|
3309
|
+
const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp.ORDER;
|
|
3310
|
+
function isBiggerThanHalfOrder(number) {
|
|
3311
|
+
const HALF = CURVE_ORDER >> _1n4;
|
|
3312
|
+
return number > HALF;
|
|
3313
|
+
}
|
|
3314
|
+
function validateRS(title, num) {
|
|
3315
|
+
if (!Fn.isValidNot0(num))
|
|
3316
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
3317
|
+
return num;
|
|
3318
|
+
}
|
|
3319
|
+
function assertFieldSignIsSupported() {
|
|
3320
|
+
if (!Fp.isOdd)
|
|
3321
|
+
throw new Error("Field doesn't support isOdd");
|
|
3322
|
+
}
|
|
3323
|
+
function getRecoveryBit(x, y, r) {
|
|
3324
|
+
assertFieldSignIsSupported();
|
|
3325
|
+
return (x === r ? 0 : 2) | Number(Fp.isOdd(y));
|
|
3326
|
+
}
|
|
3327
|
+
function assertRecoverableCurve() {
|
|
3328
|
+
if (hasLargeRecoveryLifts)
|
|
3329
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
3330
|
+
}
|
|
3331
|
+
function validateSigLength(bytes, format) {
|
|
3332
|
+
validateSigFormat(format);
|
|
3333
|
+
const size = lengths.signature;
|
|
3334
|
+
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
3335
|
+
return abytes2(bytes, sizer);
|
|
3336
|
+
}
|
|
3337
|
+
class Signature {
|
|
3338
|
+
r;
|
|
3339
|
+
s;
|
|
3340
|
+
recovery;
|
|
3341
|
+
constructor(r, s, recovery) {
|
|
3342
|
+
this.r = validateRS("r", r);
|
|
3343
|
+
this.s = validateRS("s", s);
|
|
3344
|
+
if (recovery != null) {
|
|
3345
|
+
assertRecoverableCurve();
|
|
3346
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
3347
|
+
throw new Error("invalid recovery id");
|
|
3348
|
+
this.recovery = recovery;
|
|
3349
|
+
}
|
|
3350
|
+
Object.freeze(this);
|
|
3351
|
+
}
|
|
3352
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
3353
|
+
validateSigLength(bytes, format);
|
|
3354
|
+
let recid;
|
|
3355
|
+
if (format === "der") {
|
|
3356
|
+
if (bytes.length > 2 * Fn.BYTES + 16)
|
|
3357
|
+
throw new DER.Err("invalid signature: DER signature too long");
|
|
3358
|
+
const { r: r2, s: s2 } = DER.toSig(abytes2(bytes), Fn.BYTES + 1);
|
|
3359
|
+
return new Signature(r2, s2);
|
|
3360
|
+
}
|
|
3361
|
+
if (format === "recovered") {
|
|
3362
|
+
recid = bytes[0];
|
|
3363
|
+
format = "compact";
|
|
3364
|
+
bytes = bytes.subarray(1);
|
|
3365
|
+
}
|
|
3366
|
+
const L = lengths.signature / 2;
|
|
3367
|
+
const r = bytes.subarray(0, L);
|
|
3368
|
+
const s = bytes.subarray(L, L * 2);
|
|
3369
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
3370
|
+
}
|
|
3371
|
+
static fromHex(hex, format) {
|
|
3372
|
+
return this.fromBytes(hexToBytes2(hex), format);
|
|
3373
|
+
}
|
|
3374
|
+
assertRecovery() {
|
|
3375
|
+
const { recovery } = this;
|
|
3376
|
+
if (recovery == null)
|
|
3377
|
+
throw new Error("invalid recovery id: must be present");
|
|
3378
|
+
return recovery;
|
|
3379
|
+
}
|
|
3380
|
+
addRecoveryBit(recovery) {
|
|
3381
|
+
return new Signature(this.r, this.s, recovery);
|
|
3382
|
+
}
|
|
3383
|
+
// Unlike the top-level helper below, this method expects a digest that has
|
|
3384
|
+
// already been hashed to the curve's message representative.
|
|
3385
|
+
recoverPublicKey(messageHash) {
|
|
3386
|
+
const { r, s } = this;
|
|
3387
|
+
const recovery = this.assertRecovery();
|
|
3388
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
|
|
3389
|
+
if (!Fp.isValid(radj))
|
|
3390
|
+
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
3391
|
+
const x = Fp.toBytes(radj);
|
|
3392
|
+
const R = Point.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x));
|
|
3393
|
+
const ir = Fn.inv(radj);
|
|
3394
|
+
const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash"));
|
|
3395
|
+
const u1 = Fn.create(-h * ir);
|
|
3396
|
+
const u2 = Fn.create(s * ir);
|
|
3397
|
+
const Q = Point.BASE.mulAddUnsafe(u1, R, u2);
|
|
3398
|
+
if (Q.is0())
|
|
3399
|
+
throw new Error("invalid recovery: point at infinify");
|
|
3400
|
+
Q.assertValidity();
|
|
3401
|
+
return Q;
|
|
3402
|
+
}
|
|
3403
|
+
// Signatures should be low-s, to prevent malleability.
|
|
3404
|
+
hasHighS() {
|
|
3405
|
+
return isBiggerThanHalfOrder(this.s);
|
|
3406
|
+
}
|
|
3407
|
+
toBytes(format = defaultSigOpts.format) {
|
|
3408
|
+
validateSigFormat(format);
|
|
3409
|
+
if (format === "der")
|
|
3410
|
+
return hexToBytes2(DER.hexFromSig(this));
|
|
3411
|
+
const { r, s } = this;
|
|
3412
|
+
const rb = Fn.toBytes(r);
|
|
3413
|
+
const sb = Fn.toBytes(s);
|
|
3414
|
+
if (format === "recovered") {
|
|
3415
|
+
assertRecoverableCurve();
|
|
3416
|
+
return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
3417
|
+
}
|
|
3418
|
+
return concatBytes2(rb, sb);
|
|
3419
|
+
}
|
|
3420
|
+
toHex(format) {
|
|
3421
|
+
return bytesToHex2(this.toBytes(format));
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3424
|
+
Object.freeze(Signature.prototype);
|
|
3425
|
+
Object.freeze(Signature);
|
|
3426
|
+
const bits2int = opts.bits2int === void 0 ? function bits2int_def(bytes) {
|
|
3427
|
+
if (bytes.length > 8192)
|
|
3428
|
+
throw new Error("input is too large");
|
|
3429
|
+
const num = bytesToNumberBE(bytes);
|
|
3430
|
+
const delta = bytes.length * 8 - fnBits;
|
|
3431
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
3432
|
+
} : opts.bits2int;
|
|
3433
|
+
const bits2int_modN = opts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
|
|
3434
|
+
return Fn.create(bits2int(bytes));
|
|
3435
|
+
} : opts.bits2int_modN;
|
|
3436
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
3437
|
+
function int2octets(num) {
|
|
3438
|
+
aInRange("num < 2^" + fnBits, num, _0n5, ORDER_MASK);
|
|
3439
|
+
return Fn.toBytes(num);
|
|
3440
|
+
}
|
|
3441
|
+
function validateMsgAndHash(message, prehash) {
|
|
3442
|
+
abytes2(message, void 0, "message");
|
|
3443
|
+
return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message;
|
|
3444
|
+
}
|
|
3445
|
+
function prepSig(message, secretKey, opts2) {
|
|
3446
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts2, defaultSigOpts);
|
|
3447
|
+
message = validateMsgAndHash(message, prehash);
|
|
3448
|
+
const h1int = bits2int_modN(message);
|
|
3449
|
+
const d = Fn.fromBytes(secretKey);
|
|
3450
|
+
if (!Fn.isValidNot0(d))
|
|
3451
|
+
throw new Error("invalid private key");
|
|
3452
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
3453
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
3454
|
+
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
3455
|
+
seedArgs.push(abytes2(e, void 0, "extraEntropy"));
|
|
3456
|
+
}
|
|
3457
|
+
const seed = concatBytes2(...seedArgs);
|
|
3458
|
+
const m = h1int;
|
|
3459
|
+
function k2sig(kBytes) {
|
|
3460
|
+
const k = bits2int(kBytes);
|
|
3461
|
+
if (!Fn.isValidNot0(k))
|
|
3462
|
+
return;
|
|
3463
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
3464
|
+
const r = Fn.create(q.x);
|
|
3465
|
+
if (r === _0n5)
|
|
3466
|
+
return;
|
|
3467
|
+
let s;
|
|
3468
|
+
if (csprng !== void 0) {
|
|
3469
|
+
const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));
|
|
3470
|
+
const ibk = Fn.inv(Fn.mul(b, k));
|
|
3471
|
+
const bm = Fn.mul(b, m);
|
|
3472
|
+
const bd = Fn.mul(b, d);
|
|
3473
|
+
s = Fn.create(ibk * Fn.create(bm + bd * r));
|
|
3474
|
+
} else {
|
|
3475
|
+
const ik = invertCt(k, CURVE_ORDER);
|
|
3476
|
+
s = Fn.create(ik * Fn.create(m + r * d));
|
|
3477
|
+
}
|
|
3478
|
+
if (s === _0n5)
|
|
3479
|
+
return;
|
|
3480
|
+
let recovery = getRecoveryBit(q.x, q.y, r);
|
|
3481
|
+
let normS = s;
|
|
3482
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
3483
|
+
normS = Fn.neg(s);
|
|
3484
|
+
recovery ^= 1;
|
|
3485
|
+
}
|
|
3486
|
+
return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
|
|
3487
|
+
}
|
|
3488
|
+
return { seed, k2sig };
|
|
3489
|
+
}
|
|
3490
|
+
function sign(message, secretKey, opts2 = {}) {
|
|
3491
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts2);
|
|
3492
|
+
const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac2);
|
|
3493
|
+
const sig = drbg(seed, k2sig);
|
|
3494
|
+
return sig.toBytes(opts2.format);
|
|
3495
|
+
}
|
|
3496
|
+
function verify(signature, message, publicKey, opts2 = {}) {
|
|
3497
|
+
const { lowS, prehash, format } = validateSigOpts(opts2, defaultSigOpts);
|
|
3498
|
+
publicKey = abytes2(publicKey, void 0, "publicKey");
|
|
3499
|
+
message = validateMsgAndHash(message, prehash);
|
|
3500
|
+
if (!isBytes2(signature)) {
|
|
3501
|
+
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
3502
|
+
throw new Error("verify expects Uint8Array signature" + end);
|
|
3503
|
+
}
|
|
3504
|
+
validateSigLength(signature, format);
|
|
3505
|
+
try {
|
|
3506
|
+
const sig = Signature.fromBytes(signature, format);
|
|
3507
|
+
const P = Point.fromBytes(publicKey);
|
|
3508
|
+
if (P.is0())
|
|
3509
|
+
return false;
|
|
3510
|
+
if (lowS && sig.hasHighS())
|
|
3511
|
+
return false;
|
|
3512
|
+
const { r, s } = sig;
|
|
3513
|
+
const h = bits2int_modN(message);
|
|
3514
|
+
const is = Fn.inv(s);
|
|
3515
|
+
const u1 = Fn.create(h * is);
|
|
3516
|
+
const u2 = Fn.create(r * is);
|
|
3517
|
+
const R = Point.BASE.mulAddUnsafe(u1, P, u2);
|
|
3518
|
+
if (R.is0())
|
|
3519
|
+
return false;
|
|
3520
|
+
const q = R.toAffine();
|
|
3521
|
+
const v = Fn.create(q.x);
|
|
3522
|
+
if (v !== r)
|
|
3523
|
+
return false;
|
|
3524
|
+
if (format === "recovered" && sig.recovery !== getRecoveryBit(q.x, q.y, r))
|
|
3525
|
+
return false;
|
|
3526
|
+
return true;
|
|
3527
|
+
} catch (e) {
|
|
3528
|
+
return false;
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
function recoverPublicKey(signature, message, opts2 = {}) {
|
|
3532
|
+
const { prehash } = validateSigOpts(opts2, defaultSigOpts);
|
|
3533
|
+
message = validateMsgAndHash(message, prehash);
|
|
3534
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
3535
|
+
}
|
|
3536
|
+
return Object.freeze({
|
|
3537
|
+
keygen,
|
|
3538
|
+
getPublicKey,
|
|
3539
|
+
getSharedSecret,
|
|
3540
|
+
utils,
|
|
3541
|
+
lengths,
|
|
3542
|
+
Point,
|
|
3543
|
+
sign,
|
|
3544
|
+
verify,
|
|
3545
|
+
recoverPublicKey,
|
|
3546
|
+
Signature,
|
|
3547
|
+
hash: hash_
|
|
3548
|
+
});
|
|
3549
|
+
}
|
|
3550
|
+
|
|
3551
|
+
// node_modules/@noble/curves/secp256k1.js
|
|
3552
|
+
var secp256k1_CURVE = {
|
|
3553
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
3554
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
3555
|
+
h: BigInt(1),
|
|
3556
|
+
a: BigInt(0),
|
|
3557
|
+
b: BigInt(7),
|
|
3558
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
3559
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
3560
|
+
};
|
|
3561
|
+
var secp256k1_ENDO = {
|
|
3562
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
3563
|
+
basises: [
|
|
3564
|
+
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
3565
|
+
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
3566
|
+
]
|
|
3567
|
+
};
|
|
3568
|
+
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
3569
|
+
function sqrtMod(y) {
|
|
3570
|
+
const P = secp256k1_CURVE.p;
|
|
3571
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
3572
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
3573
|
+
const b2 = y * y * y % P;
|
|
3574
|
+
const b3 = b2 * b2 * y % P;
|
|
3575
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
3576
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
3577
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
3578
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
3579
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
3580
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
3581
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
3582
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
3583
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
3584
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
3585
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
3586
|
+
const root = pow2(t2, _2n3, P);
|
|
3587
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
3588
|
+
throw new Error("Cannot find square root");
|
|
3589
|
+
return root;
|
|
3590
|
+
}
|
|
3591
|
+
var Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
3592
|
+
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
3593
|
+
Fp: Fpk1,
|
|
3594
|
+
endo: secp256k1_ENDO
|
|
3595
|
+
});
|
|
3596
|
+
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);
|
|
3597
|
+
|
|
3598
|
+
// node_modules/@noble/hashes/sha3.js
|
|
3599
|
+
var _0n6 = BigInt(0);
|
|
3600
|
+
var _1n5 = BigInt(1);
|
|
3601
|
+
var _2n4 = BigInt(2);
|
|
3602
|
+
var _7n2 = BigInt(7);
|
|
3603
|
+
var _256n = BigInt(256);
|
|
3604
|
+
var _0x71n = BigInt(113);
|
|
3605
|
+
var SHA3_PI = [];
|
|
3606
|
+
var SHA3_ROTL = [];
|
|
3607
|
+
var _SHA3_IOTA = [];
|
|
3608
|
+
for (let round = 0, R = _1n5, x = 1, y = 0; round < 24; round++) {
|
|
3609
|
+
[x, y] = [y, (2 * x + 3 * y) % 5];
|
|
3610
|
+
SHA3_PI.push(2 * (5 * y + x));
|
|
3611
|
+
SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
|
|
3612
|
+
let t = _0n6;
|
|
3613
|
+
for (let j = 0; j < 7; j++) {
|
|
3614
|
+
R = (R << _1n5 ^ (R >> _7n2) * _0x71n) % _256n;
|
|
3615
|
+
if (R & _2n4)
|
|
3616
|
+
t ^= _1n5 << (_1n5 << BigInt(j)) - _1n5;
|
|
3617
|
+
}
|
|
3618
|
+
_SHA3_IOTA.push(t);
|
|
3619
|
+
}
|
|
3620
|
+
var IOTAS = split(_SHA3_IOTA, true);
|
|
3621
|
+
var SHA3_IOTA_H = IOTAS[0];
|
|
3622
|
+
var SHA3_IOTA_L = IOTAS[1];
|
|
3623
|
+
var rotlSH = (h, l, s) => h << s | l >>> 32 - s;
|
|
3624
|
+
var rotlSL = (h, l, s) => l << s | h >>> 32 - s;
|
|
3625
|
+
var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
|
|
3626
|
+
var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
|
|
3627
|
+
var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
|
|
3628
|
+
var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
|
|
3629
|
+
var B = new Uint32Array(5 * 2);
|
|
3630
|
+
function keccakP(s, rounds = 24) {
|
|
3631
|
+
if (!(s instanceof Uint32Array))
|
|
3632
|
+
throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s);
|
|
3633
|
+
if (s.length !== 50)
|
|
3634
|
+
throw new RangeError('"s" expected Uint32Array(50), got length=' + s.length);
|
|
3635
|
+
anumber(rounds, "rounds");
|
|
3636
|
+
if (rounds < 1 || rounds > 24)
|
|
3637
|
+
throw new Error('"rounds" expected integer 1..24');
|
|
3638
|
+
for (let round = 24 - rounds; round < 24; round++) {
|
|
3639
|
+
for (let x = 0; x < 10; x++)
|
|
3640
|
+
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
|
|
3641
|
+
for (let x = 0; x < 10; x += 2) {
|
|
3642
|
+
const idx1 = (x + 8) % 10;
|
|
3643
|
+
const idx0 = (x + 2) % 10;
|
|
3644
|
+
const B0 = B[idx0];
|
|
3645
|
+
const B1 = B[idx0 + 1];
|
|
3646
|
+
const Th = rotlH(B0, B1, 1) ^ B[idx1];
|
|
3647
|
+
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
|
|
3648
|
+
for (let y = 0; y < 50; y += 10) {
|
|
3649
|
+
s[x + y] ^= Th;
|
|
3650
|
+
s[x + y + 1] ^= Tl;
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
let curH = s[2];
|
|
3654
|
+
let curL = s[3];
|
|
3655
|
+
for (let t = 0; t < 24; t++) {
|
|
3656
|
+
const shift = SHA3_ROTL[t];
|
|
3657
|
+
const Th = rotlH(curH, curL, shift);
|
|
3658
|
+
const Tl = rotlL(curH, curL, shift);
|
|
3659
|
+
const PI = SHA3_PI[t];
|
|
3660
|
+
curH = s[PI];
|
|
3661
|
+
curL = s[PI + 1];
|
|
3662
|
+
s[PI] = Th;
|
|
3663
|
+
s[PI + 1] = Tl;
|
|
3664
|
+
}
|
|
3665
|
+
for (let y = 0; y < 50; y += 10) {
|
|
3666
|
+
const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
|
|
3667
|
+
s[y] ^= ~s[y + 2] & s[y + 4];
|
|
3668
|
+
s[y + 1] ^= ~s[y + 3] & s[y + 5];
|
|
3669
|
+
s[y + 2] ^= ~s[y + 4] & s[y + 6];
|
|
3670
|
+
s[y + 3] ^= ~s[y + 5] & s[y + 7];
|
|
3671
|
+
s[y + 4] ^= ~s[y + 6] & s[y + 8];
|
|
3672
|
+
s[y + 5] ^= ~s[y + 7] & s[y + 9];
|
|
3673
|
+
s[y + 6] ^= ~s[y + 8] & b0;
|
|
3674
|
+
s[y + 7] ^= ~s[y + 9] & b1;
|
|
3675
|
+
s[y + 8] ^= ~b0 & b2;
|
|
3676
|
+
s[y + 9] ^= ~b1 & b3;
|
|
3677
|
+
}
|
|
3678
|
+
s[0] ^= SHA3_IOTA_H[round];
|
|
3679
|
+
s[1] ^= SHA3_IOTA_L[round];
|
|
3680
|
+
}
|
|
3681
|
+
clean(B);
|
|
3682
|
+
}
|
|
3683
|
+
var Keccak = class _Keccak {
|
|
3684
|
+
state;
|
|
3685
|
+
pos = 0;
|
|
3686
|
+
posOut = 0;
|
|
3687
|
+
finished = false;
|
|
3688
|
+
state32;
|
|
3689
|
+
destroyed = false;
|
|
3690
|
+
blockLen;
|
|
3691
|
+
suffix;
|
|
3692
|
+
outputLen;
|
|
3693
|
+
canXOF;
|
|
3694
|
+
enableXOF = false;
|
|
3695
|
+
rounds;
|
|
3696
|
+
// NOTE: we accept arguments in bytes instead of bits here.
|
|
3697
|
+
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
|
|
3698
|
+
anumber(blockLen, "blockLen");
|
|
3699
|
+
anumber(suffix, "suffix");
|
|
3700
|
+
anumber(rounds, "rounds");
|
|
3701
|
+
abool(enableXOF, "enableXOF");
|
|
3702
|
+
this.blockLen = blockLen;
|
|
3703
|
+
this.suffix = suffix;
|
|
3704
|
+
this.outputLen = outputLen;
|
|
3705
|
+
this.enableXOF = enableXOF;
|
|
3706
|
+
this.canXOF = enableXOF;
|
|
3707
|
+
this.rounds = rounds;
|
|
3708
|
+
anumber(outputLen, "outputLen");
|
|
3709
|
+
if (!(0 < blockLen && blockLen < 200))
|
|
3710
|
+
throw new Error('"blockLen" must be 1..199');
|
|
3711
|
+
this.state = new Uint8Array(200);
|
|
3712
|
+
this.state32 = u32(this.state);
|
|
3713
|
+
}
|
|
3714
|
+
clone() {
|
|
3715
|
+
return this._cloneInto();
|
|
3716
|
+
}
|
|
3717
|
+
keccak() {
|
|
3718
|
+
swap32IfBE(this.state32);
|
|
3719
|
+
keccakP(this.state32, this.rounds);
|
|
3720
|
+
swap32IfBE(this.state32);
|
|
3721
|
+
this.posOut = 0;
|
|
3722
|
+
this.pos = 0;
|
|
3723
|
+
}
|
|
3724
|
+
update(data) {
|
|
3725
|
+
aexists(this);
|
|
3726
|
+
abytes(data);
|
|
3727
|
+
const { blockLen, state, state32 } = this;
|
|
3728
|
+
const len = data.length;
|
|
3729
|
+
const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
|
|
3730
|
+
const blockLen32 = blockLen / 4;
|
|
3731
|
+
const data32 = canUseU32 && len >= blockLen ? u32(data) : void 0;
|
|
3732
|
+
for (let pos = 0; pos < len; ) {
|
|
3733
|
+
if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
|
|
3734
|
+
for (let i = 0, o = pos / 4; i < blockLen32; i++)
|
|
3735
|
+
state32[i] ^= data32[o + i];
|
|
3736
|
+
pos += blockLen;
|
|
3737
|
+
this.pos = blockLen;
|
|
3738
|
+
this.keccak();
|
|
3739
|
+
continue;
|
|
3740
|
+
}
|
|
3741
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
3742
|
+
for (let i = 0; i < take; i++)
|
|
3743
|
+
state[this.pos++] ^= data[pos++];
|
|
3744
|
+
if (this.pos === blockLen)
|
|
3745
|
+
this.keccak();
|
|
3746
|
+
}
|
|
3747
|
+
return this;
|
|
3748
|
+
}
|
|
3749
|
+
finish() {
|
|
3750
|
+
if (this.finished)
|
|
3751
|
+
return;
|
|
3752
|
+
this.finished = true;
|
|
3753
|
+
const { state, suffix, pos, blockLen } = this;
|
|
3754
|
+
state[pos] ^= suffix;
|
|
3755
|
+
if ((suffix & 128) !== 0 && pos === blockLen - 1)
|
|
3756
|
+
this.keccak();
|
|
3757
|
+
state[blockLen - 1] ^= 128;
|
|
3758
|
+
this.keccak();
|
|
3759
|
+
}
|
|
3760
|
+
writeInto(out) {
|
|
3761
|
+
aexists(this, false);
|
|
3762
|
+
abytes(out);
|
|
3763
|
+
this.finish();
|
|
3764
|
+
const bufferOut = this.state;
|
|
3765
|
+
const { blockLen } = this;
|
|
3766
|
+
for (let pos = 0, len = out.length; pos < len; ) {
|
|
3767
|
+
if (this.posOut >= blockLen)
|
|
3768
|
+
this.keccak();
|
|
3769
|
+
const take = Math.min(blockLen - this.posOut, len - pos);
|
|
3770
|
+
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
|
|
3771
|
+
this.posOut += take;
|
|
3772
|
+
pos += take;
|
|
3773
|
+
}
|
|
3774
|
+
return out;
|
|
3775
|
+
}
|
|
3776
|
+
xofInto(out) {
|
|
3777
|
+
if (!this.enableXOF)
|
|
3778
|
+
throw new Error("XOF is not enabled");
|
|
3779
|
+
return this.writeInto(out);
|
|
3780
|
+
}
|
|
3781
|
+
xof(bytes) {
|
|
3782
|
+
anumber(bytes);
|
|
3783
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
3784
|
+
}
|
|
3785
|
+
digestInto(out) {
|
|
3786
|
+
aoutput(out, this);
|
|
3787
|
+
if (this.finished)
|
|
3788
|
+
throw new Error("digest() was already called");
|
|
3789
|
+
this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
|
|
3790
|
+
this.destroy();
|
|
3791
|
+
}
|
|
3792
|
+
digest() {
|
|
3793
|
+
const out = new Uint8Array(this.outputLen);
|
|
3794
|
+
this.digestInto(out);
|
|
3795
|
+
return out;
|
|
3796
|
+
}
|
|
3797
|
+
destroy() {
|
|
3798
|
+
this.destroyed = true;
|
|
3799
|
+
clean(this.state);
|
|
3800
|
+
}
|
|
3801
|
+
_cloneInto(to) {
|
|
3802
|
+
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
|
|
3803
|
+
to ||= new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
|
|
3804
|
+
to.blockLen = blockLen;
|
|
3805
|
+
to.state32.set(this.state32);
|
|
3806
|
+
to.pos = this.pos;
|
|
3807
|
+
to.posOut = this.posOut;
|
|
3808
|
+
to.finished = this.finished;
|
|
3809
|
+
to.rounds = rounds;
|
|
3810
|
+
to.suffix = suffix;
|
|
3811
|
+
to.outputLen = outputLen;
|
|
3812
|
+
to.enableXOF = enableXOF;
|
|
3813
|
+
to.canXOF = this.canXOF;
|
|
3814
|
+
to.destroyed = this.destroyed;
|
|
3815
|
+
return to;
|
|
3816
|
+
}
|
|
3817
|
+
};
|
|
3818
|
+
var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);
|
|
3819
|
+
var keccak_256 = /* @__PURE__ */ genKeccak(1, 136, 32);
|
|
3820
|
+
|
|
3821
|
+
// packages/gasfree/domain/typed-data.ts
|
|
3822
|
+
import {
|
|
3823
|
+
TronAddress as TronAddress2,
|
|
3824
|
+
tronAddressBytes
|
|
3825
|
+
} from "@tron-walletcli/plugin-sdk/domain";
|
|
3826
|
+
var GASFREE_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)";
|
|
3827
|
+
var GASFREE_PERMIT_TYPE = "PermitTransfer(address token,address serviceProvider,address user,address receiver,uint256 value,uint256 maxFee,uint256 deadline,uint256 version,uint256 nonce)";
|
|
3828
|
+
var GASFREE_DOMAIN_NAME = "GasFreeController";
|
|
3829
|
+
var GASFREE_DOMAIN_VERSION = "V1.0.0";
|
|
3830
|
+
var UTF8 = new TextEncoder();
|
|
3831
|
+
function uint256Word(value, field) {
|
|
3832
|
+
if (!/^(0|[1-9][0-9]*)$/.test(value)) {
|
|
3833
|
+
throw new Error(`${field} must be an unsigned decimal integer`);
|
|
3834
|
+
}
|
|
3835
|
+
const integer = BigInt(value);
|
|
3836
|
+
if (integer >= 1n << 256n) throw new Error(`${field} exceeds uint256`);
|
|
3837
|
+
return hexToBytes(integer.toString(16).padStart(64, "0"));
|
|
3838
|
+
}
|
|
3839
|
+
function addressWord(address2) {
|
|
3840
|
+
const decoded = tronAddressBytes(address2);
|
|
3841
|
+
const result = new Uint8Array(32);
|
|
3842
|
+
result.set(decoded.slice(1), 12);
|
|
3843
|
+
return result;
|
|
3844
|
+
}
|
|
3845
|
+
function gasFreeDomainSeparator(domain) {
|
|
3846
|
+
return keccak_256(
|
|
3847
|
+
concatBytes(
|
|
3848
|
+
keccak_256(UTF8.encode(GASFREE_DOMAIN_TYPE)),
|
|
3849
|
+
keccak_256(UTF8.encode(GASFREE_DOMAIN_NAME)),
|
|
3850
|
+
keccak_256(UTF8.encode(GASFREE_DOMAIN_VERSION)),
|
|
3851
|
+
uint256Word(domain.controllerChainId, "controllerChainId"),
|
|
3852
|
+
addressWord(domain.verifyingContract)
|
|
3853
|
+
)
|
|
3854
|
+
);
|
|
3855
|
+
}
|
|
3856
|
+
function gasFreeMessageHash(authorization) {
|
|
3857
|
+
return keccak_256(
|
|
3858
|
+
concatBytes(
|
|
3859
|
+
keccak_256(UTF8.encode(GASFREE_PERMIT_TYPE)),
|
|
3860
|
+
addressWord(authorization.token),
|
|
3861
|
+
addressWord(authorization.serviceProvider),
|
|
3862
|
+
addressWord(authorization.user),
|
|
3863
|
+
addressWord(authorization.receiver),
|
|
3864
|
+
uint256Word(authorization.value, "value"),
|
|
3865
|
+
uint256Word(authorization.maxFee, "maxFee"),
|
|
3866
|
+
uint256Word(authorization.deadline, "deadline"),
|
|
3867
|
+
uint256Word(authorization.version, "version"),
|
|
3868
|
+
uint256Word(authorization.nonce, "nonce")
|
|
3869
|
+
)
|
|
3870
|
+
);
|
|
3871
|
+
}
|
|
3872
|
+
function gasFreeDigest(domain, authorization) {
|
|
3873
|
+
return keccak_256(
|
|
3874
|
+
concatBytes(
|
|
3875
|
+
Uint8Array.of(25, 1),
|
|
3876
|
+
gasFreeDomainSeparator(domain),
|
|
3877
|
+
gasFreeMessageHash(authorization)
|
|
3878
|
+
)
|
|
3879
|
+
);
|
|
3880
|
+
}
|
|
3881
|
+
function gasFreeTypedData(domain, authorization) {
|
|
3882
|
+
return {
|
|
3883
|
+
domain: {
|
|
3884
|
+
name: GASFREE_DOMAIN_NAME,
|
|
3885
|
+
version: GASFREE_DOMAIN_VERSION,
|
|
3886
|
+
chainId: domain.controllerChainId,
|
|
3887
|
+
verifyingContract: domain.verifyingContract
|
|
3888
|
+
},
|
|
3889
|
+
types: {
|
|
3890
|
+
PermitTransfer: [
|
|
3891
|
+
{ name: "token", type: "address" },
|
|
3892
|
+
{ name: "serviceProvider", type: "address" },
|
|
3893
|
+
{ name: "user", type: "address" },
|
|
3894
|
+
{ name: "receiver", type: "address" },
|
|
3895
|
+
{ name: "value", type: "uint256" },
|
|
3896
|
+
{ name: "maxFee", type: "uint256" },
|
|
3897
|
+
{ name: "deadline", type: "uint256" },
|
|
3898
|
+
{ name: "version", type: "uint256" },
|
|
3899
|
+
{ name: "nonce", type: "uint256" }
|
|
3900
|
+
]
|
|
3901
|
+
},
|
|
3902
|
+
primaryType: "PermitTransfer",
|
|
3903
|
+
message: { ...authorization }
|
|
3904
|
+
};
|
|
3905
|
+
}
|
|
3906
|
+
function normalizeGasFreeSignature(signatureHex) {
|
|
3907
|
+
const normalized = signatureHex.replace(/^0x/i, "").toLowerCase();
|
|
3908
|
+
if (!/^[0-9a-f]{130}$/.test(normalized)) {
|
|
3909
|
+
throw new Error("GasFree signature must be 65-byte hexadecimal r || s || v");
|
|
3910
|
+
}
|
|
3911
|
+
const raw = hexToBytes(normalized);
|
|
3912
|
+
const v = raw[64];
|
|
3913
|
+
const recovery = v >= 27 ? v - 27 : v;
|
|
3914
|
+
if (recovery !== 0 && recovery !== 1) {
|
|
3915
|
+
throw new Error("GasFree signature recovery id must be 0/1 or 27/28");
|
|
3916
|
+
}
|
|
3917
|
+
const signature = secp256k1.Signature.fromBytes(raw.slice(0, 64), "compact");
|
|
3918
|
+
if (signature.hasHighS()) throw new Error("GasFree signature must use low-s form");
|
|
3919
|
+
raw[64] = recovery + 27;
|
|
3920
|
+
return bytesToHex(raw);
|
|
3921
|
+
}
|
|
3922
|
+
function recoverGasFreeSigner(digest, signatureHex) {
|
|
3923
|
+
if (digest.length !== 32) throw new Error("GasFree digest must be 32 bytes");
|
|
3924
|
+
const canonical = hexToBytes(normalizeGasFreeSignature(signatureHex));
|
|
3925
|
+
const recovery = canonical[64] - 27;
|
|
3926
|
+
const recoveredSignature = concatBytes(Uint8Array.of(recovery), canonical.slice(0, 64));
|
|
3927
|
+
const compressed = secp256k1.recoverPublicKey(recoveredSignature, digest, { prehash: false });
|
|
3928
|
+
const uncompressed = secp256k1.Point.fromBytes(compressed).toBytes(false);
|
|
3929
|
+
return new TronAddress2().fromPublicKey(uncompressed);
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
// packages/gasfree/application/use-cases/gasfree-service.ts
|
|
3933
|
+
var MAX_DEADLINE_SECONDS = 86400n;
|
|
3934
|
+
var POLL_MS = 1e3;
|
|
3935
|
+
var GasFreeService = class {
|
|
3936
|
+
constructor(provider, gateways, signing, recipients, clock, sleep = (milliseconds2, deadline) => sleepWithin(deadline, milliseconds2)) {
|
|
3937
|
+
this.provider = provider;
|
|
3938
|
+
this.gateways = gateways;
|
|
3939
|
+
this.signing = signing;
|
|
3940
|
+
this.recipients = recipients;
|
|
3941
|
+
this.clock = clock;
|
|
3942
|
+
this.sleep = sleep;
|
|
3943
|
+
}
|
|
3944
|
+
provider;
|
|
3945
|
+
gateways;
|
|
3946
|
+
signing;
|
|
3947
|
+
recipients;
|
|
3948
|
+
clock;
|
|
3949
|
+
sleep;
|
|
3950
|
+
async info(scope, network) {
|
|
3951
|
+
const owner = scope.resolveAddress("tron");
|
|
3952
|
+
const gateway = this.gateways.get(network, "tron", requestDispatchCheck(scope.deadline));
|
|
3953
|
+
const [addressInfo, tokens] = await Promise.all([
|
|
3954
|
+
this.provider.getAddress(network, owner, requestDispatchCheck(scope.deadline)),
|
|
3955
|
+
this.#tokens(scope.deadline, network)
|
|
3956
|
+
]);
|
|
3957
|
+
if (addressInfo.ownerAddress !== owner) {
|
|
3958
|
+
throw new ChainError2(
|
|
3959
|
+
"gasfree_integrity",
|
|
3960
|
+
"GasFree address response owner does not match the selected account"
|
|
3961
|
+
);
|
|
3962
|
+
}
|
|
3963
|
+
const byAddress = new Map(tokens.map((token) => [token.tokenAddress, token]));
|
|
3964
|
+
const views = await Promise.all(
|
|
3965
|
+
addressInfo.assets.map(async (asset) => {
|
|
3966
|
+
const token = byAddress.get(asset.tokenAddress);
|
|
3967
|
+
if (!token || token.activateFee !== asset.activateFee || token.transferFee !== asset.transferFee) {
|
|
3968
|
+
throw new ChainError2(
|
|
3969
|
+
"gasfree_integrity",
|
|
3970
|
+
"GasFree token and address fee metadata disagree"
|
|
3971
|
+
);
|
|
3972
|
+
}
|
|
3973
|
+
return {
|
|
3974
|
+
symbol: token.symbol,
|
|
3975
|
+
address: token.tokenAddress,
|
|
3976
|
+
decimals: token.decimals,
|
|
3977
|
+
activateFee: token.activateFee,
|
|
3978
|
+
transferFee: token.transferFee,
|
|
3979
|
+
balance: await gateway.getTrc20Balance(token.tokenAddress, addressInfo.gasFreeAddress)
|
|
3980
|
+
};
|
|
3981
|
+
})
|
|
3982
|
+
);
|
|
3983
|
+
return {
|
|
3984
|
+
ownerAddress: owner,
|
|
3985
|
+
gasFreeAddress: addressInfo.gasFreeAddress,
|
|
3986
|
+
active: addressInfo.active,
|
|
3987
|
+
nonce: addressInfo.nonce,
|
|
3988
|
+
tokens: views
|
|
3989
|
+
};
|
|
3990
|
+
}
|
|
3991
|
+
async transfer(scope, network, input) {
|
|
3992
|
+
const wait = waitsForConfirmation(scope.wait, !input.dryRun);
|
|
3993
|
+
if (!input.dryRun) {
|
|
3994
|
+
this.signing.assertCanSign(scope.activeAccount, "tron");
|
|
3995
|
+
}
|
|
3996
|
+
const metadata = gasfreeNetworkConfig(network, networkBlock2(network, "gasfree"));
|
|
3997
|
+
if (!metadata) {
|
|
3998
|
+
throw new UsageError2("unsupported_network", `network ${network.id} does not support GasFree`);
|
|
3999
|
+
}
|
|
4000
|
+
const owner = scope.resolveAddress("tron");
|
|
4001
|
+
const recipient = this.recipients.resolve("tron", input.to);
|
|
4002
|
+
const [addressInfo, tokens, providers] = await Promise.all([
|
|
4003
|
+
this.provider.getAddress(network, owner, requestDispatchCheck(scope.deadline)),
|
|
4004
|
+
this.#tokens(scope.deadline, network),
|
|
4005
|
+
this.provider.listProviders(network, requestDispatchCheck(scope.deadline))
|
|
4006
|
+
]);
|
|
4007
|
+
if (addressInfo.ownerAddress !== owner) {
|
|
4008
|
+
throw new ChainError2(
|
|
4009
|
+
"gasfree_integrity",
|
|
4010
|
+
"GasFree address response owner does not match the selected account"
|
|
4011
|
+
);
|
|
4012
|
+
}
|
|
4013
|
+
const token = selectToken(tokens, input.token);
|
|
4014
|
+
const provider = selectProvider(providers);
|
|
4015
|
+
const duration = BigInt(provider.defaultDeadlineDuration);
|
|
4016
|
+
if (duration <= 0n || duration > MAX_DEADLINE_SECONDS) {
|
|
4017
|
+
throw new ChainError2(
|
|
4018
|
+
"gasfree_integrity",
|
|
4019
|
+
"GasFree provider deadline duration is outside the accepted range"
|
|
4020
|
+
);
|
|
4021
|
+
}
|
|
4022
|
+
const asset = selectAsset(addressInfo, token);
|
|
4023
|
+
const value = toBaseUnits(input.amount, token.decimals, token.symbol);
|
|
4024
|
+
assertPositiveAmount(BigInt(value), "--amount");
|
|
4025
|
+
const activateFee = addressInfo.active ? "0" : asset.activateFee;
|
|
4026
|
+
const authorizedMaxFee = add(asset.activateFee, asset.transferFee);
|
|
4027
|
+
const totalDeducted = add(value, activateFee, asset.transferFee);
|
|
4028
|
+
const gateway = this.gateways.get(network, "tron", requestDispatchCheck(scope.deadline));
|
|
4029
|
+
const balance = await gateway.getTrc20Balance(token.tokenAddress, addressInfo.gasFreeAddress);
|
|
4030
|
+
if (BigInt(balance) < BigInt(totalDeducted)) {
|
|
4031
|
+
throw new ChainError2(
|
|
4032
|
+
"insufficient_token_balance",
|
|
4033
|
+
"GasFree token balance is below transfer amount plus fees",
|
|
4034
|
+
{ balance, required: totalDeducted }
|
|
4035
|
+
);
|
|
4036
|
+
}
|
|
4037
|
+
const authorization = {
|
|
4038
|
+
token: token.tokenAddress,
|
|
4039
|
+
serviceProvider: provider.address,
|
|
4040
|
+
user: owner,
|
|
4041
|
+
receiver: recipient.address,
|
|
4042
|
+
value,
|
|
4043
|
+
maxFee: authorizedMaxFee,
|
|
4044
|
+
deadline: String(BigInt(Math.floor(this.clock() / 1e3)) + duration),
|
|
4045
|
+
version: "1",
|
|
4046
|
+
nonce: addressInfo.nonce
|
|
4047
|
+
};
|
|
4048
|
+
const base = {
|
|
4049
|
+
...transferView("dry-run", authorization, token, addressInfo, activateFee, totalDeducted),
|
|
4050
|
+
...recipient.contactName ? { toContact: recipient.contactName } : {}
|
|
4051
|
+
};
|
|
4052
|
+
if (input.dryRun) return base;
|
|
4053
|
+
if (addressInfo.allowSubmit === false) {
|
|
4054
|
+
throw new ChainError2(
|
|
4055
|
+
"gasfree_rejected",
|
|
4056
|
+
"GasFree address is not currently allowed to submit transfers"
|
|
4057
|
+
);
|
|
4058
|
+
}
|
|
4059
|
+
if (this.signing.signerAddress(scope.activeAccount, "tron") !== owner) {
|
|
4060
|
+
throw new UsageError2(
|
|
4061
|
+
"invalid_account",
|
|
4062
|
+
"resolved signer address changed during GasFree construction"
|
|
4063
|
+
);
|
|
4064
|
+
}
|
|
4065
|
+
const domain = {
|
|
4066
|
+
controllerChainId: metadata.controllerChainId,
|
|
4067
|
+
verifyingContract: metadata.verifyingContract
|
|
4068
|
+
};
|
|
4069
|
+
const expectedDigest = gasFreeDigest(domain, authorization);
|
|
4070
|
+
const signed = await this.signing.sign(scope, {
|
|
4071
|
+
network,
|
|
4072
|
+
family: "tron",
|
|
4073
|
+
payload: { kind: "typed-data", typedData: gasFreeTypedData(domain, authorization) }
|
|
4074
|
+
});
|
|
4075
|
+
const reportedDigest = signed.digest.replace(/^0x/i, "").toLowerCase();
|
|
4076
|
+
if (!/^[0-9a-f]{64}$/.test(reportedDigest) || reportedDigest !== bytesToHex(expectedDigest) || signed.primaryType !== "PermitTransfer") {
|
|
4077
|
+
throw new ChainError2(
|
|
4078
|
+
"signing_rejected",
|
|
4079
|
+
"GasFree signer did not sign the expected PermitTransfer digest"
|
|
4080
|
+
);
|
|
4081
|
+
}
|
|
4082
|
+
let signature;
|
|
4083
|
+
let recovered;
|
|
4084
|
+
try {
|
|
4085
|
+
signature = normalizeGasFreeSignature(signed.signature);
|
|
4086
|
+
recovered = recoverGasFreeSigner(expectedDigest, signature);
|
|
4087
|
+
} catch {
|
|
4088
|
+
throw new ChainError2("signing_rejected", "GasFree signer returned an invalid signature");
|
|
4089
|
+
}
|
|
4090
|
+
if (recovered !== owner) {
|
|
4091
|
+
throw new ChainError2(
|
|
4092
|
+
"signing_rejected",
|
|
4093
|
+
"GasFree signature does not recover to the selected account"
|
|
4094
|
+
);
|
|
4095
|
+
}
|
|
4096
|
+
assertSubmitAdmitted(scope.deadline);
|
|
4097
|
+
let submitted;
|
|
4098
|
+
try {
|
|
4099
|
+
submitted = await this.provider.submitTransfer(
|
|
4100
|
+
network,
|
|
4101
|
+
{ ...authorization, sig: signature },
|
|
4102
|
+
submitDispatchCheck(scope.deadline)
|
|
4103
|
+
);
|
|
4104
|
+
} catch (error) {
|
|
4105
|
+
throw uncertainSubmit(error, network, authorization, token, addressInfo, expectedDigest);
|
|
4106
|
+
}
|
|
4107
|
+
assertAccepted(submitted, authorization, addressInfo.gasFreeAddress, {
|
|
4108
|
+
traceId: submitted.id,
|
|
4109
|
+
outcome: "unknown"
|
|
4110
|
+
});
|
|
4111
|
+
const accepted = {
|
|
4112
|
+
...base,
|
|
4113
|
+
stage: "submitted",
|
|
4114
|
+
traceId: submitted.id,
|
|
4115
|
+
state: submitted.state
|
|
4116
|
+
};
|
|
4117
|
+
if (!wait) return accepted;
|
|
4118
|
+
const terminal = await this.#wait(
|
|
4119
|
+
scope,
|
|
4120
|
+
network,
|
|
4121
|
+
submitted,
|
|
4122
|
+
authorization,
|
|
4123
|
+
addressInfo.gasFreeAddress
|
|
4124
|
+
);
|
|
4125
|
+
if (!terminal) return accepted;
|
|
4126
|
+
const settledAmount = terminal.txnAmount ?? accepted.amount;
|
|
4127
|
+
const settledServiceFee = terminal.txnTransferFee ?? accepted.serviceFee;
|
|
4128
|
+
const settledActivateFee = terminal.txnActivateFee ?? accepted.activateFee;
|
|
4129
|
+
return {
|
|
4130
|
+
...accepted,
|
|
4131
|
+
stage: terminal.state === "SUCCEED" ? "confirmed" : "failed",
|
|
4132
|
+
state: terminal.state,
|
|
4133
|
+
amount: settledAmount,
|
|
4134
|
+
serviceFee: settledServiceFee,
|
|
4135
|
+
activateFee: settledActivateFee,
|
|
4136
|
+
totalDeducted: terminal.txnTotalCost ?? add(settledAmount, settledServiceFee, settledActivateFee),
|
|
4137
|
+
...terminal.txnHash ? { txId: terminal.txnHash } : {},
|
|
4138
|
+
...terminal.failureReason ? { failureReason: terminal.failureReason } : {}
|
|
4139
|
+
};
|
|
4140
|
+
}
|
|
4141
|
+
async trace(deadline, network, traceId) {
|
|
4142
|
+
const record = await this.provider.trace(network, traceId, requestDispatchCheck(deadline));
|
|
4143
|
+
assertFeeIntegrity(record, record.maxFee);
|
|
4144
|
+
const token = (await this.#tokens(deadline, network)).find(
|
|
4145
|
+
(item) => item.tokenAddress === record.tokenAddress
|
|
4146
|
+
);
|
|
4147
|
+
if (!token) {
|
|
4148
|
+
throw new ChainError2(
|
|
4149
|
+
"gasfree_integrity",
|
|
4150
|
+
"trace token is not in the current GasFree token configuration"
|
|
4151
|
+
);
|
|
4152
|
+
}
|
|
4153
|
+
const serviceFee = record.txnTransferFee ?? record.estimatedTransferFee ?? "0";
|
|
4154
|
+
const activateFee = record.txnActivateFee ?? record.estimatedActivateFee ?? "0";
|
|
4155
|
+
return {
|
|
4156
|
+
traceId: record.id,
|
|
4157
|
+
state: record.state,
|
|
4158
|
+
...record.txnHash ? { txId: record.txnHash } : {},
|
|
4159
|
+
token: token.symbol,
|
|
4160
|
+
tokenAddress: token.tokenAddress,
|
|
4161
|
+
decimals: token.decimals,
|
|
4162
|
+
amount: record.txnAmount ?? record.amount,
|
|
4163
|
+
serviceFee,
|
|
4164
|
+
activateFee,
|
|
4165
|
+
totalDeducted: record.txnTotalCost ?? record.estimatedTotalCost ?? add(record.amount, serviceFee, activateFee),
|
|
4166
|
+
from: record.gasFreeAddress,
|
|
4167
|
+
owner: record.accountAddress,
|
|
4168
|
+
to: record.targetAddress,
|
|
4169
|
+
nonce: record.nonce,
|
|
4170
|
+
...record.failureReason ? { failureReason: record.failureReason } : {}
|
|
4171
|
+
};
|
|
4172
|
+
}
|
|
4173
|
+
async #tokens(deadline, network) {
|
|
4174
|
+
const gateway = this.gateways.get(network, "tron", requestDispatchCheck(deadline));
|
|
4175
|
+
const tokens = await this.provider.listTokens(network, requestDispatchCheck(deadline));
|
|
4176
|
+
return Promise.all(
|
|
4177
|
+
tokens.map(async (token) => {
|
|
4178
|
+
const info = await gateway.getTokenInfo(token.tokenAddress);
|
|
4179
|
+
const symbol = typeof info.symbol === "string" ? info.symbol : void 0;
|
|
4180
|
+
const decimals = info.decimals;
|
|
4181
|
+
if (!symbol || decimals === void 0 || !Number.isInteger(decimals) || decimals < 0 || decimals > 255) {
|
|
4182
|
+
throw new ChainError2(
|
|
4183
|
+
"gasfree_integrity",
|
|
4184
|
+
`token metadata is incomplete for ${token.tokenAddress}`
|
|
4185
|
+
);
|
|
4186
|
+
}
|
|
4187
|
+
if (token.symbol !== void 0 && token.symbol !== symbol || token.decimals !== void 0 && token.decimals !== decimals) {
|
|
4188
|
+
throw new ChainError2(
|
|
4189
|
+
"gasfree_integrity",
|
|
4190
|
+
`provider token metadata disagrees with the TRC20 contract for ${token.tokenAddress}`
|
|
4191
|
+
);
|
|
4192
|
+
}
|
|
4193
|
+
return { ...token, symbol, decimals };
|
|
4194
|
+
})
|
|
4195
|
+
);
|
|
4196
|
+
}
|
|
4197
|
+
// Preserve the submitted receipt on polling failure, except for integrity violations.
|
|
4198
|
+
async #wait(scope, network, initial, authorization, gasFreeAddress) {
|
|
4199
|
+
const { deadline } = scope;
|
|
4200
|
+
const traceContext = { traceId: initial.id, outcome: "unknown" };
|
|
4201
|
+
let previous = initial.state;
|
|
4202
|
+
if (previous === "SUCCEED" || previous === "FAILED") return initial;
|
|
4203
|
+
for (; ; ) {
|
|
4204
|
+
const beforeSleep = deadline.remainingMs();
|
|
4205
|
+
if (beforeSleep > 0) await this.sleep(Math.min(POLL_MS, beforeSleep), deadline);
|
|
4206
|
+
if (deadline.expired()) {
|
|
4207
|
+
scope.warn(
|
|
4208
|
+
errorMessage`GasFree transfer ${initial.id} did not finish before the command's time limit; returning submitted`
|
|
4209
|
+
);
|
|
4210
|
+
return void 0;
|
|
4211
|
+
}
|
|
4212
|
+
let current;
|
|
4213
|
+
try {
|
|
4214
|
+
current = await this.provider.trace(network, initial.id, requestDispatchCheck(deadline));
|
|
4215
|
+
} catch (error) {
|
|
4216
|
+
if (isRetryablePoll(error)) continue;
|
|
4217
|
+
if (error instanceof CliError2 && error.code === "gasfree_integrity")
|
|
4218
|
+
throw new ChainError2(error.code, error.userMessage, {
|
|
4219
|
+
...error.details,
|
|
4220
|
+
...traceContext
|
|
4221
|
+
});
|
|
4222
|
+
scope.warn(
|
|
4223
|
+
errorMessage`GasFree trace could not be polled (${error instanceof CliError2 ? error.code : "provider_error"}); returning submitted — reconcile with \`gasfree trace ${initial.id}\``
|
|
4224
|
+
);
|
|
4225
|
+
return void 0;
|
|
4226
|
+
}
|
|
4227
|
+
if (current.id !== initial.id) {
|
|
4228
|
+
throw new ChainError2(
|
|
4229
|
+
"gasfree_integrity",
|
|
4230
|
+
"GasFree trace id changed while polling",
|
|
4231
|
+
traceContext
|
|
4232
|
+
);
|
|
4233
|
+
}
|
|
4234
|
+
assertAccepted(current, authorization, gasFreeAddress, traceContext);
|
|
4235
|
+
if (stateRank(current.state) < stateRank(previous)) {
|
|
4236
|
+
throw new ChainError2(
|
|
4237
|
+
"gasfree_integrity",
|
|
4238
|
+
"GasFree state regressed while polling",
|
|
4239
|
+
traceContext
|
|
4240
|
+
);
|
|
4241
|
+
}
|
|
4242
|
+
previous = current.state;
|
|
4243
|
+
if (current.state === "SUCCEED" || current.state === "FAILED") {
|
|
4244
|
+
return current;
|
|
4245
|
+
}
|
|
4246
|
+
}
|
|
4247
|
+
}
|
|
4248
|
+
};
|
|
4249
|
+
var DEFINITE_SUBMIT_REFUSALS = /* @__PURE__ */ new Set([
|
|
4250
|
+
"gasfree_auth_failed",
|
|
4251
|
+
"gasfree_rejected",
|
|
4252
|
+
"provider_rate_limited"
|
|
4253
|
+
]);
|
|
4254
|
+
function uncertainSubmit(error, network, authorization, token, address2, digest) {
|
|
4255
|
+
if (error instanceof DeadlineExpiredError || error instanceof CliError2 && (error.kind === "usage" || DEFINITE_SUBMIT_REFUSALS.has(error.code))) {
|
|
4256
|
+
return error;
|
|
4257
|
+
}
|
|
4258
|
+
const code = error instanceof CliError2 && error.code === "timeout" ? "timeout" : "provider_error";
|
|
4259
|
+
return new TransportError2(
|
|
4260
|
+
code,
|
|
4261
|
+
"GasFree submit outcome is unknown and no trace id is known; check the GasFree nonce before signing another transfer",
|
|
4262
|
+
{
|
|
4263
|
+
paymentStatus: "unknown",
|
|
4264
|
+
outcome: "unknown",
|
|
4265
|
+
retryPayment: false,
|
|
4266
|
+
network: network.id,
|
|
4267
|
+
serviceProvider: authorization.serviceProvider,
|
|
4268
|
+
owner: authorization.user,
|
|
4269
|
+
from: address2.gasFreeAddress,
|
|
4270
|
+
to: authorization.receiver,
|
|
4271
|
+
token: token.symbol,
|
|
4272
|
+
tokenAddress: authorization.token,
|
|
4273
|
+
amount: authorization.value,
|
|
4274
|
+
authorizedMaxFee: authorization.maxFee,
|
|
4275
|
+
nonce: authorization.nonce,
|
|
4276
|
+
deadline: authorization.deadline,
|
|
4277
|
+
permitDigest: `0x${bytesToHex(digest)}`
|
|
4278
|
+
}
|
|
4279
|
+
);
|
|
4280
|
+
}
|
|
4281
|
+
function isRetryablePoll(error) {
|
|
4282
|
+
return error instanceof TransportError2 || error instanceof CliError2 && error.code === "timeout";
|
|
4283
|
+
}
|
|
4284
|
+
function selectToken(tokens, symbol) {
|
|
4285
|
+
const match = matchTokenSymbol(tokens, symbol);
|
|
4286
|
+
if (match.kind === "none") {
|
|
4287
|
+
throw new UsageError2("unsupported_token", `GasFree provider does not support token: ${symbol}`);
|
|
4288
|
+
}
|
|
4289
|
+
if (match.kind === "ambiguous") {
|
|
4290
|
+
throw new ChainError2("gasfree_integrity", `GasFree token symbol is ambiguous: ${symbol}`);
|
|
4291
|
+
}
|
|
4292
|
+
return match.token;
|
|
4293
|
+
}
|
|
4294
|
+
function selectProvider(providers) {
|
|
4295
|
+
if (providers.length === 0) {
|
|
4296
|
+
throw new ChainError2("gasfree_integrity", "GasFree provider configuration is empty");
|
|
4297
|
+
}
|
|
4298
|
+
return providers[0];
|
|
4299
|
+
}
|
|
4300
|
+
function selectAsset(address2, token) {
|
|
4301
|
+
const matches = address2.assets.filter((asset2) => asset2.tokenAddress === token.tokenAddress);
|
|
4302
|
+
if (matches.length !== 1) {
|
|
4303
|
+
throw new ChainError2(
|
|
4304
|
+
"gasfree_integrity",
|
|
4305
|
+
"GasFree address asset configuration is missing or ambiguous"
|
|
4306
|
+
);
|
|
4307
|
+
}
|
|
4308
|
+
const asset = matches[0];
|
|
4309
|
+
if (asset.activateFee !== token.activateFee || asset.transferFee !== token.transferFee) {
|
|
4310
|
+
throw new ChainError2("gasfree_integrity", "GasFree fee metadata disagrees across endpoints");
|
|
4311
|
+
}
|
|
4312
|
+
return asset;
|
|
4313
|
+
}
|
|
4314
|
+
function transferView(stage, authorization, token, address2, activateFee, totalDeducted) {
|
|
4315
|
+
return {
|
|
4316
|
+
kind: "gasfree-transfer",
|
|
4317
|
+
stage,
|
|
4318
|
+
token: token.symbol,
|
|
4319
|
+
tokenAddress: token.tokenAddress,
|
|
4320
|
+
decimals: token.decimals,
|
|
4321
|
+
amount: authorization.value,
|
|
4322
|
+
serviceFee: token.transferFee,
|
|
4323
|
+
activateFee,
|
|
4324
|
+
authorizedMaxFee: authorization.maxFee,
|
|
4325
|
+
totalDeducted,
|
|
4326
|
+
owner: authorization.user,
|
|
4327
|
+
from: address2.gasFreeAddress,
|
|
4328
|
+
to: authorization.receiver,
|
|
4329
|
+
serviceProvider: authorization.serviceProvider,
|
|
4330
|
+
nonce: authorization.nonce,
|
|
4331
|
+
deadline: authorization.deadline
|
|
4332
|
+
};
|
|
4333
|
+
}
|
|
4334
|
+
function assertAccepted(record, authorization, gasFreeAddress, context) {
|
|
4335
|
+
const deadlineMatches = record.expiredAt === void 0 || BigInt(record.expiredAt) === BigInt(authorization.deadline) * 1000n;
|
|
4336
|
+
if (record.tokenAddress !== authorization.token || record.providerAddress !== authorization.serviceProvider || record.accountAddress !== authorization.user || record.targetAddress !== authorization.receiver || record.gasFreeAddress !== gasFreeAddress || record.amount !== authorization.value || record.nonce !== authorization.nonce || record.maxFee !== void 0 && record.maxFee !== authorization.maxFee || !deadlineMatches || record.txnAmount !== void 0 && record.txnAmount !== authorization.value) {
|
|
4337
|
+
throw new ChainError2(
|
|
4338
|
+
"gasfree_integrity",
|
|
4339
|
+
"GasFree submit receipt does not match the signed authorization",
|
|
4340
|
+
context
|
|
4341
|
+
);
|
|
4342
|
+
}
|
|
4343
|
+
assertFeeIntegrity(record, authorization.maxFee, context);
|
|
4344
|
+
}
|
|
4345
|
+
function assertFeeIntegrity(record, authorizedMaxFee, context) {
|
|
4346
|
+
const feeSets = [
|
|
4347
|
+
[
|
|
4348
|
+
record.estimatedTransferFee,
|
|
4349
|
+
record.estimatedActivateFee,
|
|
4350
|
+
record.estimatedTotalFee,
|
|
4351
|
+
record.estimatedTotalCost
|
|
4352
|
+
],
|
|
4353
|
+
[record.txnTransferFee, record.txnActivateFee, record.txnTotalFee, record.txnTotalCost]
|
|
4354
|
+
];
|
|
4355
|
+
for (const [transfer, activate, totalFee, totalCost] of feeSets) {
|
|
4356
|
+
const componentTotal = transfer !== void 0 && activate !== void 0 ? BigInt(transfer) + BigInt(activate) : void 0;
|
|
4357
|
+
const observedTotal = totalFee === void 0 ? componentTotal : BigInt(totalFee);
|
|
4358
|
+
if (observedTotal !== void 0 && authorizedMaxFee !== void 0 && observedTotal > BigInt(authorizedMaxFee)) {
|
|
4359
|
+
throw new ChainError2(
|
|
4360
|
+
"gasfree_integrity",
|
|
4361
|
+
"GasFree provider fee exceeds the signed maxFee",
|
|
4362
|
+
context
|
|
4363
|
+
);
|
|
4364
|
+
}
|
|
4365
|
+
if (componentTotal !== void 0 && totalFee !== void 0 && componentTotal !== BigInt(totalFee)) {
|
|
4366
|
+
throw new ChainError2(
|
|
4367
|
+
"gasfree_integrity",
|
|
4368
|
+
"GasFree provider fee components do not match the total fee",
|
|
4369
|
+
context
|
|
4370
|
+
);
|
|
4371
|
+
}
|
|
4372
|
+
if (observedTotal !== void 0 && totalCost !== void 0 && BigInt(record.amount) + observedTotal !== BigInt(totalCost)) {
|
|
4373
|
+
throw new ChainError2(
|
|
4374
|
+
"gasfree_integrity",
|
|
4375
|
+
"GasFree provider total cost does not match amount plus fees",
|
|
4376
|
+
context
|
|
4377
|
+
);
|
|
4378
|
+
}
|
|
4379
|
+
}
|
|
4380
|
+
}
|
|
4381
|
+
function add(...values) {
|
|
4382
|
+
return values.reduce((sum, value) => sum + BigInt(value), 0n).toString();
|
|
4383
|
+
}
|
|
4384
|
+
function stateRank(state) {
|
|
4385
|
+
return {
|
|
4386
|
+
WAITING: 0,
|
|
4387
|
+
INPROGRESS: 1,
|
|
4388
|
+
CONFIRMING: 2,
|
|
4389
|
+
SUCCEED: 3,
|
|
4390
|
+
FAILED: 3
|
|
4391
|
+
}[state];
|
|
4392
|
+
}
|
|
4393
|
+
|
|
4394
|
+
// packages/gasfree/application/capabilities.ts
|
|
4395
|
+
import { networkBlock as networkBlock3 } from "@tron-walletcli/plugin-sdk/domain";
|
|
4396
|
+
var gasfree = (network) => gasfreeNetworkConfig(network, networkBlock3(network, "gasfree")) !== void 0 ? "supported" : "unsupported";
|
|
4397
|
+
var GASFREE_CAPABILITIES = {
|
|
4398
|
+
"gasfree.info": gasfree,
|
|
4399
|
+
"gasfree.transfer": gasfree,
|
|
4400
|
+
"gasfree.trace": gasfree
|
|
4401
|
+
};
|
|
4402
|
+
var GASFREE_DEFAULT_TOKEN = "USDT";
|
|
4403
|
+
|
|
4404
|
+
// packages/gasfree/domain/errors.ts
|
|
4405
|
+
var GASFREE_ERROR_CODES = {
|
|
4406
|
+
unsupported_token: {
|
|
4407
|
+
exit: 2,
|
|
4408
|
+
retry: "never",
|
|
4409
|
+
meaning: "the token standard is not one this command handles"
|
|
4410
|
+
},
|
|
4411
|
+
gasfree_auth_failed: {
|
|
4412
|
+
exit: 1,
|
|
4413
|
+
retry: "never",
|
|
4414
|
+
meaning: "the GasFree service rejected the request's credentials"
|
|
4415
|
+
},
|
|
4416
|
+
gasfree_integrity: {
|
|
4417
|
+
exit: 1,
|
|
4418
|
+
retry: "never",
|
|
4419
|
+
meaning: "the GasFree service's answer failed its integrity check"
|
|
4420
|
+
},
|
|
4421
|
+
gasfree_credentials_missing: {
|
|
4422
|
+
exit: 2,
|
|
4423
|
+
retry: "never",
|
|
4424
|
+
meaning: "no GasFree credentials are configured"
|
|
4425
|
+
},
|
|
4426
|
+
gasfree_rejected: {
|
|
4427
|
+
exit: 1,
|
|
4428
|
+
retry: "never",
|
|
4429
|
+
meaning: "the GasFree service refused the transfer"
|
|
4430
|
+
}
|
|
4431
|
+
};
|
|
4432
|
+
|
|
4433
|
+
// packages/gasfree/adapters/inbound/commands.ts
|
|
4434
|
+
import { z } from "@tron-walletcli/plugin-sdk/cli";
|
|
4435
|
+
import { isZeroAmount } from "@tron-walletcli/plugin-sdk/domain";
|
|
4436
|
+
|
|
4437
|
+
// packages/gasfree/adapters/inbound/render.ts
|
|
4438
|
+
import { fromBaseUnits } from "@tron-walletcli/plugin-sdk/domain";
|
|
4439
|
+
import { fail, ok, pending, query, receipt, table } from "@tron-walletcli/plugin-sdk/cli";
|
|
4440
|
+
function amount(value, decimals, symbol) {
|
|
4441
|
+
return `${fromBaseUnits(value, decimals)} ${symbol}`;
|
|
4442
|
+
}
|
|
4443
|
+
var GasFreeFormatters = {
|
|
4444
|
+
gasFreeInfo: (value) => [
|
|
4445
|
+
query([
|
|
4446
|
+
["Owner", value.ownerAddress],
|
|
4447
|
+
["GasFree address", value.gasFreeAddress],
|
|
4448
|
+
["Status", value.active ? "active" : "not activated"],
|
|
4449
|
+
["Nonce", value.nonce]
|
|
4450
|
+
]),
|
|
4451
|
+
table(
|
|
4452
|
+
["Token", "Balance", "Activation fee", "Transfer fee"],
|
|
4453
|
+
value.tokens.map((token) => [
|
|
4454
|
+
token.symbol,
|
|
4455
|
+
amount(token.balance, token.decimals, token.symbol),
|
|
4456
|
+
amount(token.activateFee, token.decimals, token.symbol),
|
|
4457
|
+
amount(token.transferFee, token.decimals, token.symbol)
|
|
4458
|
+
])
|
|
4459
|
+
)
|
|
4460
|
+
].join("\n\n"),
|
|
4461
|
+
gasFreeTransfer: (value) => {
|
|
4462
|
+
const marker = value.stage === "confirmed" ? ok() : value.stage === "failed" ? fail() : pending();
|
|
4463
|
+
const title = value.stage === "dry-run" ? `Dry run \u2014 GasFree transfer ${amount(value.amount, value.decimals, value.token)} (not submitted)` : value.stage === "confirmed" ? `Sent ${amount(value.amount, value.decimals, value.token)} via GasFree` : value.stage === "failed" ? "GasFree transfer failed" : `Submitted to GasFree \u2014 send ${amount(value.amount, value.decimals, value.token)}`;
|
|
4464
|
+
const result = receipt(marker, title, [
|
|
4465
|
+
["Trace ID", value.traceId ?? ""],
|
|
4466
|
+
["TxID", value.txId ?? ""],
|
|
4467
|
+
["From", value.from],
|
|
4468
|
+
["To", value.toContact ? `${value.toContact} (${value.to})` : value.to],
|
|
4469
|
+
["Service fee", amount(value.serviceFee, value.decimals, value.token)],
|
|
4470
|
+
["Activation fee", amount(value.activateFee, value.decimals, value.token)],
|
|
4471
|
+
["Authorized max fee", amount(value.authorizedMaxFee, value.decimals, value.token)],
|
|
4472
|
+
["Total", amount(value.totalDeducted, value.decimals, value.token)],
|
|
4473
|
+
[
|
|
4474
|
+
"Status",
|
|
4475
|
+
value.state?.toLowerCase() ?? (value.stage === "dry-run" ? "not submitted" : "accepted")
|
|
4476
|
+
],
|
|
4477
|
+
["Reason", value.failureReason ?? ""]
|
|
4478
|
+
]);
|
|
4479
|
+
return value.stage === "submitted" && value.traceId ? `${result}
|
|
4480
|
+
! Track it: wallet-cli gasfree trace ${value.traceId}` : result;
|
|
4481
|
+
},
|
|
4482
|
+
gasFreeTrace: (value) => query([
|
|
4483
|
+
["Trace ID", value.traceId],
|
|
4484
|
+
["Status", value.state.toLowerCase()],
|
|
4485
|
+
["TxID", value.txId ?? ""],
|
|
4486
|
+
["Token", value.token],
|
|
4487
|
+
["Amount", amount(value.amount, value.decimals, value.token)],
|
|
4488
|
+
["Service fee", amount(value.serviceFee, value.decimals, value.token)],
|
|
4489
|
+
["Activation fee", amount(value.activateFee, value.decimals, value.token)],
|
|
4490
|
+
["Total", amount(value.totalDeducted, value.decimals, value.token)],
|
|
4491
|
+
["To", value.to],
|
|
4492
|
+
["Reason", value.failureReason ?? ""]
|
|
4493
|
+
])
|
|
4494
|
+
};
|
|
4495
|
+
|
|
4496
|
+
// packages/gasfree/adapters/inbound/commands.ts
|
|
4497
|
+
var gasFreeInfoCommand = (service) => ({
|
|
4498
|
+
path: ["gasfree", "info"],
|
|
4499
|
+
families: ["tron"],
|
|
4500
|
+
wallet: "optional",
|
|
4501
|
+
auth: "none",
|
|
4502
|
+
capability: "gasfree.info",
|
|
4503
|
+
requires: ["config gasfreeApiKey / gasfreeApiSecret"],
|
|
4504
|
+
summary: "Show GasFree address, activation status, nonce, balances, and fees",
|
|
4505
|
+
description: "Show this account's GasFree address, activation status, nonce, supported tokens, balances, and current token-denominated fees.",
|
|
4506
|
+
fields: z.object({}),
|
|
4507
|
+
examples: [{ cmd: "wallet-cli gasfree info" }],
|
|
4508
|
+
formatText: GasFreeFormatters.gasFreeInfo,
|
|
4509
|
+
run: async (context, network) => service.info(context, network)
|
|
4510
|
+
});
|
|
4511
|
+
var transferFields = z.object({
|
|
4512
|
+
to: z.string().trim().min(1).max(128).describe("recipient TRON address or local contact name"),
|
|
4513
|
+
amount: z.string().regex(/^\d+(\.\d+)?$/, "must be a positive decimal amount").refine((value) => !isZeroAmount(value), "must be greater than zero").describe("human token amount to transfer, in token units"),
|
|
4514
|
+
token: z.string().trim().min(1).max(32).default(GASFREE_DEFAULT_TOKEN).describe("token symbol supported by the GasFree provider"),
|
|
4515
|
+
dryRun: z.boolean().default(false).describe(
|
|
4516
|
+
"check token balance and the fee breakdown without unlocking, signing, or submitting"
|
|
4517
|
+
)
|
|
4518
|
+
});
|
|
4519
|
+
var gasFreeTransferCommand = (service) => ({
|
|
4520
|
+
path: ["gasfree", "transfer"],
|
|
4521
|
+
families: ["tron"],
|
|
4522
|
+
wallet: "optional",
|
|
4523
|
+
auth: "conditional",
|
|
4524
|
+
broadcasts: true,
|
|
4525
|
+
capability: "gasfree.transfer",
|
|
4526
|
+
requires: ["config gasfreeApiKey / gasfreeApiSecret"],
|
|
4527
|
+
summary: "Sign and submit a TIP-712 GasFree token transfer",
|
|
4528
|
+
description: "Sign a GasFree PermitTransfer and submit it to the provider. No TRX is needed; --dry-run checks the token balance and fee breakdown without unlocking or signing.",
|
|
4529
|
+
fields: transferFields,
|
|
4530
|
+
examples: [
|
|
4531
|
+
{
|
|
4532
|
+
cmd: "wallet-cli gasfree transfer --to T... --amount 25 --password-stdin"
|
|
4533
|
+
},
|
|
4534
|
+
{
|
|
4535
|
+
cmd: "wallet-cli gasfree transfer --to alice --amount 25 --no-wait --password-stdin"
|
|
4536
|
+
}
|
|
4537
|
+
],
|
|
4538
|
+
formatText: GasFreeFormatters.gasFreeTransfer,
|
|
4539
|
+
run: async (context, network, input) => service.transfer(context, network, input)
|
|
4540
|
+
});
|
|
4541
|
+
var traceFields = z.object({
|
|
4542
|
+
traceId: z.string().trim().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._:-]*$/).describe("trace id returned by `gasfree transfer`")
|
|
4543
|
+
});
|
|
4544
|
+
var gasFreeTraceCommand = (service) => ({
|
|
4545
|
+
path: ["gasfree", "trace"],
|
|
4546
|
+
families: ["tron"],
|
|
4547
|
+
wallet: "none",
|
|
4548
|
+
auth: "none",
|
|
4549
|
+
capability: "gasfree.trace",
|
|
4550
|
+
requires: ["config gasfreeApiKey / gasfreeApiSecret"],
|
|
4551
|
+
positionals: [{ field: "traceId", placeholder: "traceId" }],
|
|
4552
|
+
summary: "Track a GasFree transfer by provider trace id",
|
|
4553
|
+
description: "Track a submitted GasFree transfer through WAITING, INPROGRESS, CONFIRMING, and the SUCCEED or FAILED terminal state.",
|
|
4554
|
+
fields: traceFields,
|
|
4555
|
+
examples: [
|
|
4556
|
+
{
|
|
4557
|
+
cmd: "wallet-cli gasfree trace 7f3e9a02-58c1-4d2e-b6a4-91d0c3f8e527"
|
|
4558
|
+
}
|
|
4559
|
+
],
|
|
4560
|
+
formatText: GasFreeFormatters.gasFreeTrace,
|
|
4561
|
+
run: async (context, network, input) => service.trace(context.deadline, network, input.traceId)
|
|
4562
|
+
});
|
|
4563
|
+
|
|
4564
|
+
// packages/gasfree/index.ts
|
|
4565
|
+
function register(host) {
|
|
4566
|
+
const { services } = host;
|
|
4567
|
+
const service = new GasFreeService(
|
|
4568
|
+
new GasFreeClient(services.config, services.broadcastGuard),
|
|
4569
|
+
services.gateways,
|
|
4570
|
+
services.signing,
|
|
4571
|
+
services.recipients,
|
|
4572
|
+
() => Date.now()
|
|
4573
|
+
);
|
|
4574
|
+
host.errorCodes(GASFREE_ERROR_CODES);
|
|
4575
|
+
host.capabilities(GASFREE_CAPABILITIES);
|
|
4576
|
+
host.command(gasFreeInfoCommand(service));
|
|
4577
|
+
host.command(gasFreeTransferCommand(service));
|
|
4578
|
+
host.command(gasFreeTraceCommand(service));
|
|
4579
|
+
}
|
|
4580
|
+
export {
|
|
4581
|
+
register
|
|
4582
|
+
};
|