@p2pdotme/sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +155 -0
- package/dist/fraud-engine.cjs +598 -0
- package/dist/fraud-engine.cjs.map +1 -0
- package/dist/fraud-engine.d.cts +194 -0
- package/dist/fraud-engine.d.ts +194 -0
- package/dist/fraud-engine.mjs +549 -0
- package/dist/fraud-engine.mjs.map +1 -0
- package/dist/index.cjs +75 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +49 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.mjs +46 -0
- package/dist/index.mjs.map +1 -0
- package/dist/order-routing.cjs +882 -0
- package/dist/order-routing.cjs.map +1 -0
- package/dist/order-routing.d.cts +68 -0
- package/dist/order-routing.d.ts +68 -0
- package/dist/order-routing.mjs +854 -0
- package/dist/order-routing.mjs.map +1 -0
- package/dist/payload.cjs +3164 -0
- package/dist/payload.cjs.map +1 -0
- package/dist/payload.d.cts +162 -0
- package/dist/payload.d.ts +162 -0
- package/dist/payload.mjs +3120 -0
- package/dist/payload.mjs.map +1 -0
- package/dist/profile.cjs +695 -0
- package/dist/profile.cjs.map +1 -0
- package/dist/profile.d.cts +133 -0
- package/dist/profile.d.ts +133 -0
- package/dist/profile.mjs +667 -0
- package/dist/profile.mjs.map +1 -0
- package/dist/qr-parsers.cjs +366 -0
- package/dist/qr-parsers.cjs.map +1 -0
- package/dist/qr-parsers.d.cts +41 -0
- package/dist/qr-parsers.d.ts +41 -0
- package/dist/qr-parsers.mjs +338 -0
- package/dist/qr-parsers.mjs.map +1 -0
- package/dist/react.cjs +4803 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +511 -0
- package/dist/react.d.ts +511 -0
- package/dist/react.mjs +4759 -0
- package/dist/react.mjs.map +1 -0
- package/dist/zkkyc.cjs +868 -0
- package/dist/zkkyc.cjs.map +1 -0
- package/dist/zkkyc.d.cts +230 -0
- package/dist/zkkyc.d.ts +230 -0
- package/dist/zkkyc.mjs +824 -0
- package/dist/zkkyc.mjs.map +1 -0
- package/package.json +130 -0
package/dist/react.cjs
ADDED
|
@@ -0,0 +1,4803 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
|
|
26
|
+
mod2
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
|
|
29
|
+
|
|
30
|
+
// src/react/index.ts
|
|
31
|
+
var react_exports = {};
|
|
32
|
+
__export(react_exports, {
|
|
33
|
+
SdkProvider: () => SdkProvider,
|
|
34
|
+
useFingerprint: () => useFingerprint,
|
|
35
|
+
useFraudEngine: () => useFraudEngine,
|
|
36
|
+
useOrderRouter: () => useOrderRouter,
|
|
37
|
+
usePayloadGenerator: () => usePayloadGenerator,
|
|
38
|
+
useProfile: () => useProfile,
|
|
39
|
+
useSdk: () => useSdk,
|
|
40
|
+
useZkkyc: () => useZkkyc
|
|
41
|
+
});
|
|
42
|
+
module.exports = __toCommonJS(react_exports);
|
|
43
|
+
|
|
44
|
+
// src/react/sdk-provider.tsx
|
|
45
|
+
var import_react = require("react");
|
|
46
|
+
|
|
47
|
+
// src/fraud-engine/client.ts
|
|
48
|
+
var import_neverthrow3 = require("neverthrow");
|
|
49
|
+
|
|
50
|
+
// src/lib/encoding.ts
|
|
51
|
+
function hexToBytes(hex) {
|
|
52
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
53
|
+
for (let i = 0; i < hex.length; i += 2) {
|
|
54
|
+
bytes[i / 2] = Number.parseInt(hex.slice(i, i + 2), 16);
|
|
55
|
+
}
|
|
56
|
+
return bytes;
|
|
57
|
+
}
|
|
58
|
+
function bytesToBase64(bytes) {
|
|
59
|
+
let binary = "";
|
|
60
|
+
for (const byte of bytes) {
|
|
61
|
+
binary += String.fromCharCode(byte);
|
|
62
|
+
}
|
|
63
|
+
return btoa(binary);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// src/lib/logger.ts
|
|
67
|
+
var noop = () => {
|
|
68
|
+
};
|
|
69
|
+
var noopLogger = {
|
|
70
|
+
debug: noop,
|
|
71
|
+
info: noop,
|
|
72
|
+
warn: noop,
|
|
73
|
+
error: noop
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// src/lib/sleep.ts
|
|
77
|
+
function sleep(ms) {
|
|
78
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/fraud-engine/device.ts
|
|
82
|
+
function getBasicDeviceDetails() {
|
|
83
|
+
const nav = typeof navigator !== "undefined" ? navigator : void 0;
|
|
84
|
+
const win = typeof window !== "undefined" ? window : void 0;
|
|
85
|
+
return {
|
|
86
|
+
userAgent: nav?.userAgent ?? "",
|
|
87
|
+
platform: nav?.platform ?? "",
|
|
88
|
+
language: nav?.language ?? "",
|
|
89
|
+
languages: nav ? Array.from(nav.languages) : [],
|
|
90
|
+
screenWidth: win?.screen?.width ?? 0,
|
|
91
|
+
screenHeight: win?.screen?.height ?? 0,
|
|
92
|
+
devicePixelRatio: win?.devicePixelRatio ?? 1,
|
|
93
|
+
timezone: Intl?.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone ?? "",
|
|
94
|
+
timezoneOffset: (/* @__PURE__ */ new Date()).getTimezoneOffset(),
|
|
95
|
+
cookiesEnabled: nav?.cookieEnabled ?? false,
|
|
96
|
+
doNotTrack: nav?.doNotTrack ?? null,
|
|
97
|
+
online: nav?.onLine ?? true,
|
|
98
|
+
connectionType: nav?.connection?.effectiveType,
|
|
99
|
+
deviceMemory: nav?.deviceMemory,
|
|
100
|
+
hardwareConcurrency: nav?.hardwareConcurrency,
|
|
101
|
+
touchSupport: nav ? "ontouchstart" in window : false,
|
|
102
|
+
maxTouchPoints: nav?.maxTouchPoints ?? 0,
|
|
103
|
+
vendor: nav?.vendor ?? "",
|
|
104
|
+
appVersion: nav?.appVersion ?? "",
|
|
105
|
+
colorDepth: win?.screen?.colorDepth ?? 0,
|
|
106
|
+
pixelDepth: win?.screen?.pixelDepth ?? 0
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
async function fetchIpAddress() {
|
|
110
|
+
try {
|
|
111
|
+
const response = await fetch("https://api.ipify.org?format=json");
|
|
112
|
+
const data = await response.json();
|
|
113
|
+
return data.ip;
|
|
114
|
+
} catch {
|
|
115
|
+
return void 0;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function getDeviceDetails(seonSession) {
|
|
119
|
+
const basic = getBasicDeviceDetails();
|
|
120
|
+
const ip = await fetchIpAddress();
|
|
121
|
+
return { ...basic, ip, seonSession };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/validation/errors.ts
|
|
125
|
+
var SdkError = class extends Error {
|
|
126
|
+
code;
|
|
127
|
+
cause;
|
|
128
|
+
context;
|
|
129
|
+
constructor(message, options) {
|
|
130
|
+
super(message);
|
|
131
|
+
this.name = "SdkError";
|
|
132
|
+
this.code = options.code;
|
|
133
|
+
this.cause = options.cause;
|
|
134
|
+
this.context = options.context;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// src/validation/schemas.ts
|
|
139
|
+
var import_neverthrow = require("neverthrow");
|
|
140
|
+
var import_viem = require("viem");
|
|
141
|
+
var import_zod = require("zod");
|
|
142
|
+
var ZodAddressSchema = import_zod.z.string().refine((s) => (0, import_viem.isAddress)(s), { message: "Invalid Ethereum address" });
|
|
143
|
+
var ZodCurrencySchema = import_zod.z.enum([
|
|
144
|
+
"IDR",
|
|
145
|
+
"INR",
|
|
146
|
+
"BRL",
|
|
147
|
+
"ARS",
|
|
148
|
+
"MEX",
|
|
149
|
+
"VEN",
|
|
150
|
+
"EUR",
|
|
151
|
+
"NGN",
|
|
152
|
+
"USD"
|
|
153
|
+
]);
|
|
154
|
+
function validate(schema, data, toError) {
|
|
155
|
+
const result = schema.safeParse(data);
|
|
156
|
+
if (result.success) {
|
|
157
|
+
return (0, import_neverthrow.ok)(result.data);
|
|
158
|
+
}
|
|
159
|
+
return (0, import_neverthrow.err)(toError(import_zod.z.prettifyError(result.error), result.error, data));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/fraud-engine/errors.ts
|
|
163
|
+
var FraudEngineError = class extends SdkError {
|
|
164
|
+
constructor(message, options) {
|
|
165
|
+
super(message, options);
|
|
166
|
+
this.name = "FraudEngineError";
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
// src/fraud-engine/encryption.ts
|
|
171
|
+
async function getEncryptionKey(encryptionKeyHex) {
|
|
172
|
+
const keyBytes = hexToBytes(encryptionKeyHex);
|
|
173
|
+
return crypto.subtle.importKey(
|
|
174
|
+
"raw",
|
|
175
|
+
keyBytes.buffer,
|
|
176
|
+
{ name: "AES-GCM" },
|
|
177
|
+
false,
|
|
178
|
+
["encrypt"]
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
async function encryptPayload(payload, aad, encryptionKeyHex) {
|
|
182
|
+
try {
|
|
183
|
+
const key = await getEncryptionKey(encryptionKeyHex);
|
|
184
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
185
|
+
const encoded = new TextEncoder().encode(payload);
|
|
186
|
+
const aadEncoded = new TextEncoder().encode(aad);
|
|
187
|
+
const ciphertext = await crypto.subtle.encrypt(
|
|
188
|
+
{ name: "AES-GCM", iv, additionalData: aadEncoded, tagLength: 128 },
|
|
189
|
+
key,
|
|
190
|
+
encoded
|
|
191
|
+
);
|
|
192
|
+
const result = new Uint8Array(iv.length + ciphertext.byteLength);
|
|
193
|
+
result.set(iv, 0);
|
|
194
|
+
result.set(new Uint8Array(ciphertext), iv.length);
|
|
195
|
+
return bytesToBase64(result);
|
|
196
|
+
} catch (cause) {
|
|
197
|
+
throw new FraudEngineError("Encryption failed", {
|
|
198
|
+
code: "ENCRYPTION_ERROR",
|
|
199
|
+
cause
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/fraud-engine/fingerprint.ts
|
|
205
|
+
var import_fingerprintjs = __toESM(require("@fingerprintjs/fingerprintjs"), 1);
|
|
206
|
+
var agent = null;
|
|
207
|
+
var cachedResult = null;
|
|
208
|
+
async function loadFingerprintAgent() {
|
|
209
|
+
if (agent) return;
|
|
210
|
+
agent = await import_fingerprintjs.default.load();
|
|
211
|
+
}
|
|
212
|
+
async function getFingerprint(timeoutMs = 5e3) {
|
|
213
|
+
if (cachedResult) return cachedResult;
|
|
214
|
+
if (!agent) {
|
|
215
|
+
try {
|
|
216
|
+
await loadFingerprintAgent();
|
|
217
|
+
} catch {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const loadedAgent = agent;
|
|
222
|
+
if (!loadedAgent) return null;
|
|
223
|
+
try {
|
|
224
|
+
const result = await Promise.race([
|
|
225
|
+
loadedAgent.get(),
|
|
226
|
+
new Promise(
|
|
227
|
+
(_, reject) => setTimeout(() => reject(new Error("FingerprintJS timed out")), timeoutMs)
|
|
228
|
+
)
|
|
229
|
+
]);
|
|
230
|
+
cachedResult = {
|
|
231
|
+
visitorId: result.visitorId,
|
|
232
|
+
confidence: result.confidence.score
|
|
233
|
+
};
|
|
234
|
+
return cachedResult;
|
|
235
|
+
} catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// src/fraud-engine/seon.ts
|
|
241
|
+
var import_seon_javascript_sdk = __toESM(require("@seontechnologies/seon-javascript-sdk"), 1);
|
|
242
|
+
var initialized = false;
|
|
243
|
+
function initSeon() {
|
|
244
|
+
if (initialized) return;
|
|
245
|
+
import_seon_javascript_sdk.default.init();
|
|
246
|
+
initialized = true;
|
|
247
|
+
}
|
|
248
|
+
async function getSeonSession(region) {
|
|
249
|
+
try {
|
|
250
|
+
return await import_seon_javascript_sdk.default.getSession({
|
|
251
|
+
geolocation: { canPrompt: false },
|
|
252
|
+
networkTimeoutMs: 2e3,
|
|
253
|
+
fieldTimeoutMs: 2e3,
|
|
254
|
+
region,
|
|
255
|
+
silentMode: true
|
|
256
|
+
});
|
|
257
|
+
} catch {
|
|
258
|
+
return void 0;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
function cleanupSeonStorage() {
|
|
262
|
+
if (typeof localStorage === "undefined") return;
|
|
263
|
+
const keysToRemove = [];
|
|
264
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
265
|
+
const key = localStorage.key(i);
|
|
266
|
+
if (key?.startsWith("seon_session_sent_")) keysToRemove.push(key);
|
|
267
|
+
}
|
|
268
|
+
for (const key of keysToRemove) localStorage.removeItem(key);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/fraud-engine/signing.ts
|
|
272
|
+
async function getSignedHeaders(signer, action) {
|
|
273
|
+
const signingAddress = (signer.signerAddress ?? signer.address).toLowerCase();
|
|
274
|
+
const timestamp = Math.floor(Date.now() / 1e3).toString();
|
|
275
|
+
const message = `${action}:${signingAddress}:${timestamp}`;
|
|
276
|
+
try {
|
|
277
|
+
const signature = await signer.signMessage(message);
|
|
278
|
+
return {
|
|
279
|
+
"X-Signer-Address": signingAddress,
|
|
280
|
+
"X-Timestamp": timestamp,
|
|
281
|
+
"X-Signature": signature
|
|
282
|
+
};
|
|
283
|
+
} catch (cause) {
|
|
284
|
+
throw new FraudEngineError("Failed to sign message", {
|
|
285
|
+
code: "SIGNING_ERROR",
|
|
286
|
+
cause
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// src/fraud-engine/validation.ts
|
|
292
|
+
var import_neverthrow2 = require("neverthrow");
|
|
293
|
+
var import_zod2 = require("zod");
|
|
294
|
+
var ZodFraudEngineConfigSchema = import_zod2.z.object({
|
|
295
|
+
apiUrl: import_zod2.z.url(),
|
|
296
|
+
encryptionKey: import_zod2.z.string().min(1),
|
|
297
|
+
seonRegion: import_zod2.z.string().optional()
|
|
298
|
+
});
|
|
299
|
+
var ZodBuyOrderDetailsSchema = import_zod2.z.object({
|
|
300
|
+
cryptoAmount: import_zod2.z.number(),
|
|
301
|
+
fiatAmount: import_zod2.z.number(),
|
|
302
|
+
currency: import_zod2.z.string().min(1),
|
|
303
|
+
recipientAddress: import_zod2.z.string().min(1),
|
|
304
|
+
fee: import_zod2.z.number(),
|
|
305
|
+
amountAfterFee: import_zod2.z.number(),
|
|
306
|
+
paymentMethod: import_zod2.z.string().optional(),
|
|
307
|
+
estimatedProcessingTime: import_zod2.z.string().optional()
|
|
308
|
+
});
|
|
309
|
+
var ZodUserDetailsSchema = import_zod2.z.object({
|
|
310
|
+
currency: import_zod2.z.string().optional(),
|
|
311
|
+
country: import_zod2.z.string().optional(),
|
|
312
|
+
language: import_zod2.z.string().optional(),
|
|
313
|
+
loginMethod: import_zod2.z.enum(["email", "google", "phone", "passkey", "unknown"]).optional(),
|
|
314
|
+
loginEmail: import_zod2.z.string().optional(),
|
|
315
|
+
loginPhone: import_zod2.z.string().optional()
|
|
316
|
+
});
|
|
317
|
+
var ZodLinkOrderParamsSchema = import_zod2.z.object({
|
|
318
|
+
activityLogId: import_zod2.z.number().int().positive(),
|
|
319
|
+
orderId: import_zod2.z.string().min(1)
|
|
320
|
+
});
|
|
321
|
+
function validate2(schema, data) {
|
|
322
|
+
const result = schema.safeParse(data);
|
|
323
|
+
if (result.success) {
|
|
324
|
+
return (0, import_neverthrow2.ok)(result.data);
|
|
325
|
+
}
|
|
326
|
+
return (0, import_neverthrow2.err)(
|
|
327
|
+
new FraudEngineError(import_zod2.z.prettifyError(result.error), {
|
|
328
|
+
code: "VALIDATION_ERROR",
|
|
329
|
+
cause: result.error,
|
|
330
|
+
context: { data }
|
|
331
|
+
})
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// src/fraud-engine/client.ts
|
|
336
|
+
function createFraudEngine(config) {
|
|
337
|
+
const { apiUrl, encryptionKey } = config;
|
|
338
|
+
const seonRegion = config.seonRegion ?? "asia";
|
|
339
|
+
const logger = config.logger ?? noopLogger;
|
|
340
|
+
const configResult = validate2(ZodFraudEngineConfigSchema, {
|
|
341
|
+
apiUrl,
|
|
342
|
+
encryptionKey,
|
|
343
|
+
seonRegion
|
|
344
|
+
});
|
|
345
|
+
const configError = configResult.isErr() ? configResult.error : null;
|
|
346
|
+
if (configError) {
|
|
347
|
+
logger.error(
|
|
348
|
+
"Fraud engine config invalid; API methods will return VALIDATION_ERROR until fixed",
|
|
349
|
+
{ error: configError.message }
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
function linkOrderInternal(signer, activityLogId, orderId) {
|
|
353
|
+
return import_neverthrow3.ResultAsync.fromPromise(
|
|
354
|
+
(async () => {
|
|
355
|
+
logger.info("Linking order to activity log", { activityLogId, orderId });
|
|
356
|
+
const signedHeaders = await getSignedHeaders(signer, "link-order");
|
|
357
|
+
const response = await fetch(`${apiUrl}/activity-logs/link-order`, {
|
|
358
|
+
method: "PATCH",
|
|
359
|
+
headers: {
|
|
360
|
+
"Content-Type": "application/json",
|
|
361
|
+
...signedHeaders
|
|
362
|
+
},
|
|
363
|
+
body: JSON.stringify({
|
|
364
|
+
activity_log_id: activityLogId,
|
|
365
|
+
order_id: orderId,
|
|
366
|
+
user_address: signer.address.toLowerCase()
|
|
367
|
+
})
|
|
368
|
+
});
|
|
369
|
+
if (!response.ok) {
|
|
370
|
+
throw new FraudEngineError(`Link order API returned ${response.status}`, {
|
|
371
|
+
code: "API_ERROR",
|
|
372
|
+
context: { status: response.status }
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
const data = await response.json();
|
|
376
|
+
logger.info("Order linked successfully", { orderId });
|
|
377
|
+
return data;
|
|
378
|
+
})(),
|
|
379
|
+
(cause) => {
|
|
380
|
+
if (cause instanceof FraudEngineError) return cause;
|
|
381
|
+
return new FraudEngineError("Link order failed", {
|
|
382
|
+
code: "NETWORK_ERROR",
|
|
383
|
+
cause
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
async function checkBuyOrderInternal(params) {
|
|
389
|
+
logger.info("Checking buy order for fraud", {
|
|
390
|
+
currency: params.orderDetails.currency,
|
|
391
|
+
fiatAmount: params.orderDetails.fiatAmount
|
|
392
|
+
});
|
|
393
|
+
const [seonSession, deviceDetails, signedHeaders] = await Promise.all([
|
|
394
|
+
getSeonSession(seonRegion),
|
|
395
|
+
getDeviceDetails(),
|
|
396
|
+
getSignedHeaders(params.signer, "activity-log")
|
|
397
|
+
]);
|
|
398
|
+
const device = { ...deviceDetails, seonSession };
|
|
399
|
+
const userAddress = params.signer.address.toLowerCase();
|
|
400
|
+
const timestamp = Date.now();
|
|
401
|
+
const payload = JSON.stringify({
|
|
402
|
+
user_details: {
|
|
403
|
+
currency: params.userDetails?.currency,
|
|
404
|
+
country: params.userDetails?.country,
|
|
405
|
+
language: params.userDetails?.language,
|
|
406
|
+
login_method: params.userDetails?.loginMethod,
|
|
407
|
+
login_email: params.userDetails?.loginEmail,
|
|
408
|
+
login_phone: params.userDetails?.loginPhone
|
|
409
|
+
},
|
|
410
|
+
transaction_details: {
|
|
411
|
+
crypto_amount: params.orderDetails.cryptoAmount,
|
|
412
|
+
fiat_amount: params.orderDetails.fiatAmount,
|
|
413
|
+
currency: params.orderDetails.currency,
|
|
414
|
+
recipient_address: params.orderDetails.recipientAddress,
|
|
415
|
+
fee: params.orderDetails.fee,
|
|
416
|
+
amount_after_fee: params.orderDetails.amountAfterFee,
|
|
417
|
+
payment_method: params.orderDetails.paymentMethod,
|
|
418
|
+
estimated_processing_time: params.orderDetails.estimatedProcessingTime,
|
|
419
|
+
order_timestamp: timestamp,
|
|
420
|
+
order_source: params.orderSource
|
|
421
|
+
},
|
|
422
|
+
device_details: device
|
|
423
|
+
});
|
|
424
|
+
const aad = `buy_order|${userAddress}|${timestamp}`;
|
|
425
|
+
const encrypted = await encryptPayload(payload, aad, encryptionKey);
|
|
426
|
+
const response = await fetch(`${apiUrl}/activity-logs`, {
|
|
427
|
+
method: "POST",
|
|
428
|
+
headers: {
|
|
429
|
+
"Content-Type": "application/json",
|
|
430
|
+
...signedHeaders
|
|
431
|
+
},
|
|
432
|
+
body: JSON.stringify({
|
|
433
|
+
type: "buy_order",
|
|
434
|
+
user_address: userAddress,
|
|
435
|
+
timestamp,
|
|
436
|
+
encrypted_payload: encrypted
|
|
437
|
+
})
|
|
438
|
+
});
|
|
439
|
+
if (!response.ok) {
|
|
440
|
+
throw new FraudEngineError(`Fraud check API returned ${response.status}`, {
|
|
441
|
+
code: "API_ERROR",
|
|
442
|
+
context: { status: response.status }
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
const data = await response.json();
|
|
446
|
+
logger.info("Fraud check result", {
|
|
447
|
+
approved: data.approved,
|
|
448
|
+
activityLogId: data.activity_log_id
|
|
449
|
+
});
|
|
450
|
+
return data;
|
|
451
|
+
}
|
|
452
|
+
return {
|
|
453
|
+
async init() {
|
|
454
|
+
logger.info("Initializing fraud engine");
|
|
455
|
+
try {
|
|
456
|
+
initSeon();
|
|
457
|
+
} catch (cause) {
|
|
458
|
+
logger.error("SEON initialization failed", { cause: String(cause) });
|
|
459
|
+
}
|
|
460
|
+
try {
|
|
461
|
+
await loadFingerprintAgent();
|
|
462
|
+
} catch (cause) {
|
|
463
|
+
logger.error("FingerprintJS initialization failed", {
|
|
464
|
+
cause: String(cause)
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
logger.info("Fraud engine initialized");
|
|
468
|
+
},
|
|
469
|
+
checkBuyOrder(params) {
|
|
470
|
+
if (configError) return (0, import_neverthrow3.errAsync)(configError);
|
|
471
|
+
return import_neverthrow3.ResultAsync.fromPromise(
|
|
472
|
+
checkBuyOrderInternal(params).then((data) => ({
|
|
473
|
+
approved: data.approved,
|
|
474
|
+
activityLogId: data.activity_log_id,
|
|
475
|
+
message: data.message,
|
|
476
|
+
linkOrder: (orderId) => linkOrderInternal(params.signer, data.activity_log_id, orderId)
|
|
477
|
+
})),
|
|
478
|
+
(cause) => {
|
|
479
|
+
if (cause instanceof FraudEngineError) return cause;
|
|
480
|
+
return new FraudEngineError("Fraud check failed", {
|
|
481
|
+
code: "NETWORK_ERROR",
|
|
482
|
+
cause
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
);
|
|
486
|
+
},
|
|
487
|
+
processBuyOrder(params) {
|
|
488
|
+
if (configError) return (0, import_neverthrow3.errAsync)(configError);
|
|
489
|
+
return import_neverthrow3.ResultAsync.fromPromise(
|
|
490
|
+
(async () => {
|
|
491
|
+
let activityLogId = null;
|
|
492
|
+
try {
|
|
493
|
+
const fraudCheck = await checkBuyOrderInternal(params);
|
|
494
|
+
if (!fraudCheck.approved) {
|
|
495
|
+
return { status: "rejected", message: fraudCheck.message };
|
|
496
|
+
}
|
|
497
|
+
activityLogId = fraudCheck.activity_log_id;
|
|
498
|
+
} catch (cause) {
|
|
499
|
+
logger.error("Fraud check failed, proceeding with order (fail-open)", {
|
|
500
|
+
error: String(cause)
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
let orderId;
|
|
504
|
+
try {
|
|
505
|
+
orderId = await params.placeOrder();
|
|
506
|
+
} catch (cause) {
|
|
507
|
+
throw new FraudEngineError("Place order callback failed", {
|
|
508
|
+
code: "PLACE_ORDER_ERROR",
|
|
509
|
+
cause
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
if (activityLogId !== null) {
|
|
513
|
+
linkOrderInternal(params.signer, activityLogId, orderId).mapErr((e) => {
|
|
514
|
+
logger.error("Failed to link order to activity log", {
|
|
515
|
+
orderId,
|
|
516
|
+
activityLogId,
|
|
517
|
+
error: e.message
|
|
518
|
+
});
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
return { status: "placed", orderId };
|
|
522
|
+
})(),
|
|
523
|
+
(cause) => {
|
|
524
|
+
if (cause instanceof FraudEngineError) return cause;
|
|
525
|
+
return new FraudEngineError("Process buy order failed", {
|
|
526
|
+
code: "NETWORK_ERROR",
|
|
527
|
+
cause
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
);
|
|
531
|
+
},
|
|
532
|
+
logFingerprint(params) {
|
|
533
|
+
if (configError) return (0, import_neverthrow3.errAsync)(configError);
|
|
534
|
+
return import_neverthrow3.ResultAsync.fromPromise(
|
|
535
|
+
(async () => {
|
|
536
|
+
logger.info("Logging fingerprint");
|
|
537
|
+
const fingerprintResult = await getFingerprint(5e3);
|
|
538
|
+
if (!fingerprintResult) {
|
|
539
|
+
logger.warn("Fingerprint not available, skipping");
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
const signedHeaders = await getSignedHeaders(params.signer, "fingerprint-log");
|
|
543
|
+
const normalizedAddress = params.signer.address.toLowerCase();
|
|
544
|
+
const timestamp = Date.now();
|
|
545
|
+
const payload = JSON.stringify({
|
|
546
|
+
fingerprint_id: fingerprintResult.visitorId
|
|
547
|
+
});
|
|
548
|
+
const aad = `fingerprint|${normalizedAddress}|${timestamp}`;
|
|
549
|
+
const encrypted = await encryptPayload(payload, aad, encryptionKey);
|
|
550
|
+
const response = await fetch(`${apiUrl}/fingerprint-log`, {
|
|
551
|
+
method: "POST",
|
|
552
|
+
headers: {
|
|
553
|
+
"Content-Type": "application/json",
|
|
554
|
+
...signedHeaders
|
|
555
|
+
},
|
|
556
|
+
body: JSON.stringify({
|
|
557
|
+
user_address: normalizedAddress,
|
|
558
|
+
timestamp,
|
|
559
|
+
encrypted_payload: encrypted
|
|
560
|
+
})
|
|
561
|
+
});
|
|
562
|
+
if (!response.ok) {
|
|
563
|
+
throw new FraudEngineError(`Fingerprint log API returned ${response.status}`, {
|
|
564
|
+
code: "API_ERROR",
|
|
565
|
+
context: { status: response.status }
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
const data = await response.json();
|
|
569
|
+
logger.info("Fingerprint logged successfully");
|
|
570
|
+
return data;
|
|
571
|
+
})(),
|
|
572
|
+
(cause) => {
|
|
573
|
+
if (cause instanceof FraudEngineError) return cause;
|
|
574
|
+
return new FraudEngineError("Fingerprint log failed", {
|
|
575
|
+
code: "NETWORK_ERROR",
|
|
576
|
+
cause
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
);
|
|
580
|
+
},
|
|
581
|
+
async getFingerprint() {
|
|
582
|
+
return getFingerprint(5e3);
|
|
583
|
+
},
|
|
584
|
+
async getDeviceDetails() {
|
|
585
|
+
return getDeviceDetails();
|
|
586
|
+
},
|
|
587
|
+
cleanupSeonStorage() {
|
|
588
|
+
cleanupSeonStorage();
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// src/order-routing/client.ts
|
|
594
|
+
var import_viem6 = require("viem");
|
|
595
|
+
|
|
596
|
+
// src/contracts/abis/index.ts
|
|
597
|
+
var import_viem2 = require("viem");
|
|
598
|
+
|
|
599
|
+
// src/contracts/abis/order-flow-facet.ts
|
|
600
|
+
var orderFlowFacetAbi = [
|
|
601
|
+
{
|
|
602
|
+
inputs: [
|
|
603
|
+
{ internalType: "uint256", name: "circleId", type: "uint256" },
|
|
604
|
+
{ internalType: "uint256", name: "assignUpto", type: "uint256" },
|
|
605
|
+
{ internalType: "bytes32", name: "currency", type: "bytes32" },
|
|
606
|
+
{ internalType: "address", name: "user", type: "address" },
|
|
607
|
+
{ internalType: "uint256", name: "usdtAmount", type: "uint256" },
|
|
608
|
+
{ internalType: "uint256", name: "fiatAmount", type: "uint256" },
|
|
609
|
+
{ internalType: "int256", name: "orderType", type: "int256" },
|
|
610
|
+
{ internalType: "uint256", name: "preferredPCConfigId", type: "uint256" }
|
|
611
|
+
],
|
|
612
|
+
name: "getAssignableMerchantsFromCircle",
|
|
613
|
+
outputs: [{ internalType: "address[]", name: "", type: "address[]" }],
|
|
614
|
+
stateMutability: "view",
|
|
615
|
+
type: "function"
|
|
616
|
+
},
|
|
617
|
+
{
|
|
618
|
+
inputs: [
|
|
619
|
+
{ internalType: "address", name: "_user", type: "address" },
|
|
620
|
+
{ internalType: "bytes32", name: "_nativeCurrency", type: "bytes32" }
|
|
621
|
+
],
|
|
622
|
+
name: "userTxLimit",
|
|
623
|
+
outputs: [
|
|
624
|
+
{ internalType: "uint256", name: "", type: "uint256" },
|
|
625
|
+
{ internalType: "uint256", name: "", type: "uint256" }
|
|
626
|
+
],
|
|
627
|
+
stateMutability: "view",
|
|
628
|
+
type: "function"
|
|
629
|
+
}
|
|
630
|
+
];
|
|
631
|
+
|
|
632
|
+
// src/contracts/abis/p2p-config-facet.ts
|
|
633
|
+
var p2pConfigFacetAbi = [
|
|
634
|
+
{
|
|
635
|
+
inputs: [
|
|
636
|
+
{
|
|
637
|
+
internalType: "bytes32",
|
|
638
|
+
name: "_currency",
|
|
639
|
+
type: "bytes32"
|
|
640
|
+
}
|
|
641
|
+
],
|
|
642
|
+
name: "getPriceConfig",
|
|
643
|
+
outputs: [
|
|
644
|
+
{
|
|
645
|
+
components: [
|
|
646
|
+
{
|
|
647
|
+
internalType: "uint256",
|
|
648
|
+
name: "buyPrice",
|
|
649
|
+
type: "uint256"
|
|
650
|
+
},
|
|
651
|
+
{
|
|
652
|
+
internalType: "uint256",
|
|
653
|
+
name: "sellPrice",
|
|
654
|
+
type: "uint256"
|
|
655
|
+
},
|
|
656
|
+
{
|
|
657
|
+
internalType: "int256",
|
|
658
|
+
name: "buyPriceOffset",
|
|
659
|
+
type: "int256"
|
|
660
|
+
},
|
|
661
|
+
{
|
|
662
|
+
internalType: "uint256",
|
|
663
|
+
name: "baseSpread",
|
|
664
|
+
type: "uint256"
|
|
665
|
+
}
|
|
666
|
+
],
|
|
667
|
+
internalType: "struct P2pConfigStorage.PriceConfig",
|
|
668
|
+
name: "",
|
|
669
|
+
type: "tuple"
|
|
670
|
+
}
|
|
671
|
+
],
|
|
672
|
+
stateMutability: "view",
|
|
673
|
+
type: "function"
|
|
674
|
+
},
|
|
675
|
+
{
|
|
676
|
+
inputs: [
|
|
677
|
+
{
|
|
678
|
+
internalType: "bytes32",
|
|
679
|
+
name: "_nativeCurrency",
|
|
680
|
+
type: "bytes32"
|
|
681
|
+
}
|
|
682
|
+
],
|
|
683
|
+
name: "getRpPerUsdtLimitRational",
|
|
684
|
+
outputs: [
|
|
685
|
+
{
|
|
686
|
+
internalType: "uint256",
|
|
687
|
+
name: "numerator",
|
|
688
|
+
type: "uint256"
|
|
689
|
+
},
|
|
690
|
+
{
|
|
691
|
+
internalType: "uint256",
|
|
692
|
+
name: "denominator",
|
|
693
|
+
type: "uint256"
|
|
694
|
+
}
|
|
695
|
+
],
|
|
696
|
+
stateMutability: "view",
|
|
697
|
+
type: "function"
|
|
698
|
+
}
|
|
699
|
+
];
|
|
700
|
+
|
|
701
|
+
// src/contracts/abis/reputation-manager.ts
|
|
702
|
+
var reputationManagerAbi = [
|
|
703
|
+
{
|
|
704
|
+
inputs: [
|
|
705
|
+
{
|
|
706
|
+
internalType: "string",
|
|
707
|
+
name: "_socialName",
|
|
708
|
+
type: "string"
|
|
709
|
+
},
|
|
710
|
+
{
|
|
711
|
+
components: [
|
|
712
|
+
{
|
|
713
|
+
components: [
|
|
714
|
+
{
|
|
715
|
+
internalType: "string",
|
|
716
|
+
name: "provider",
|
|
717
|
+
type: "string"
|
|
718
|
+
},
|
|
719
|
+
{
|
|
720
|
+
internalType: "string",
|
|
721
|
+
name: "parameters",
|
|
722
|
+
type: "string"
|
|
723
|
+
},
|
|
724
|
+
{
|
|
725
|
+
internalType: "string",
|
|
726
|
+
name: "context",
|
|
727
|
+
type: "string"
|
|
728
|
+
}
|
|
729
|
+
],
|
|
730
|
+
internalType: "struct IReclaimSDK.ClaimInfo",
|
|
731
|
+
name: "claimInfo",
|
|
732
|
+
type: "tuple"
|
|
733
|
+
},
|
|
734
|
+
{
|
|
735
|
+
components: [
|
|
736
|
+
{
|
|
737
|
+
components: [
|
|
738
|
+
{
|
|
739
|
+
internalType: "bytes32",
|
|
740
|
+
name: "identifier",
|
|
741
|
+
type: "bytes32"
|
|
742
|
+
},
|
|
743
|
+
{
|
|
744
|
+
internalType: "address",
|
|
745
|
+
name: "owner",
|
|
746
|
+
type: "address"
|
|
747
|
+
},
|
|
748
|
+
{
|
|
749
|
+
internalType: "uint32",
|
|
750
|
+
name: "timestampS",
|
|
751
|
+
type: "uint32"
|
|
752
|
+
},
|
|
753
|
+
{
|
|
754
|
+
internalType: "uint32",
|
|
755
|
+
name: "epoch",
|
|
756
|
+
type: "uint32"
|
|
757
|
+
}
|
|
758
|
+
],
|
|
759
|
+
internalType: "struct IReclaimSDK.CompleteClaimData",
|
|
760
|
+
name: "claim",
|
|
761
|
+
type: "tuple"
|
|
762
|
+
},
|
|
763
|
+
{
|
|
764
|
+
internalType: "bytes[]",
|
|
765
|
+
name: "signatures",
|
|
766
|
+
type: "bytes[]"
|
|
767
|
+
}
|
|
768
|
+
],
|
|
769
|
+
internalType: "struct IReclaimSDK.SignedClaim",
|
|
770
|
+
name: "signedClaim",
|
|
771
|
+
type: "tuple"
|
|
772
|
+
}
|
|
773
|
+
],
|
|
774
|
+
internalType: "struct IReclaimSDK.Proof[]",
|
|
775
|
+
name: "proofs",
|
|
776
|
+
type: "tuple[]"
|
|
777
|
+
}
|
|
778
|
+
],
|
|
779
|
+
name: "socialVerify",
|
|
780
|
+
outputs: [],
|
|
781
|
+
stateMutability: "nonpayable",
|
|
782
|
+
type: "function"
|
|
783
|
+
},
|
|
784
|
+
{
|
|
785
|
+
inputs: [
|
|
786
|
+
{
|
|
787
|
+
internalType: "uint256",
|
|
788
|
+
name: "nullifierSeed",
|
|
789
|
+
type: "uint256"
|
|
790
|
+
},
|
|
791
|
+
{
|
|
792
|
+
internalType: "uint256",
|
|
793
|
+
name: "nullifier",
|
|
794
|
+
type: "uint256"
|
|
795
|
+
},
|
|
796
|
+
{
|
|
797
|
+
internalType: "uint256",
|
|
798
|
+
name: "timestamp",
|
|
799
|
+
type: "uint256"
|
|
800
|
+
},
|
|
801
|
+
{
|
|
802
|
+
internalType: "uint256",
|
|
803
|
+
name: "signal",
|
|
804
|
+
type: "uint256"
|
|
805
|
+
},
|
|
806
|
+
{
|
|
807
|
+
internalType: "uint256[4]",
|
|
808
|
+
name: "revealArray",
|
|
809
|
+
type: "uint256[4]"
|
|
810
|
+
},
|
|
811
|
+
{
|
|
812
|
+
internalType: "uint256[8]",
|
|
813
|
+
name: "groth16Proof",
|
|
814
|
+
type: "uint256[8]"
|
|
815
|
+
}
|
|
816
|
+
],
|
|
817
|
+
name: "submitAnonAadharProof",
|
|
818
|
+
outputs: [],
|
|
819
|
+
stateMutability: "nonpayable",
|
|
820
|
+
type: "function"
|
|
821
|
+
},
|
|
822
|
+
{
|
|
823
|
+
inputs: [
|
|
824
|
+
{
|
|
825
|
+
components: [
|
|
826
|
+
{
|
|
827
|
+
internalType: "bytes32",
|
|
828
|
+
name: "version",
|
|
829
|
+
type: "bytes32"
|
|
830
|
+
},
|
|
831
|
+
{
|
|
832
|
+
components: [
|
|
833
|
+
{
|
|
834
|
+
internalType: "bytes32",
|
|
835
|
+
name: "vkeyHash",
|
|
836
|
+
type: "bytes32"
|
|
837
|
+
},
|
|
838
|
+
{
|
|
839
|
+
internalType: "bytes",
|
|
840
|
+
name: "proof",
|
|
841
|
+
type: "bytes"
|
|
842
|
+
},
|
|
843
|
+
{
|
|
844
|
+
internalType: "bytes32[]",
|
|
845
|
+
name: "publicInputs",
|
|
846
|
+
type: "bytes32[]"
|
|
847
|
+
}
|
|
848
|
+
],
|
|
849
|
+
internalType: "struct ProofVerificationData",
|
|
850
|
+
name: "proofVerificationData",
|
|
851
|
+
type: "tuple"
|
|
852
|
+
},
|
|
853
|
+
{
|
|
854
|
+
internalType: "bytes",
|
|
855
|
+
name: "committedInputs",
|
|
856
|
+
type: "bytes"
|
|
857
|
+
},
|
|
858
|
+
{
|
|
859
|
+
components: [
|
|
860
|
+
{
|
|
861
|
+
internalType: "uint256",
|
|
862
|
+
name: "validityPeriodInSeconds",
|
|
863
|
+
type: "uint256"
|
|
864
|
+
},
|
|
865
|
+
{
|
|
866
|
+
internalType: "string",
|
|
867
|
+
name: "domain",
|
|
868
|
+
type: "string"
|
|
869
|
+
},
|
|
870
|
+
{
|
|
871
|
+
internalType: "string",
|
|
872
|
+
name: "scope",
|
|
873
|
+
type: "string"
|
|
874
|
+
},
|
|
875
|
+
{
|
|
876
|
+
internalType: "bool",
|
|
877
|
+
name: "devMode",
|
|
878
|
+
type: "bool"
|
|
879
|
+
}
|
|
880
|
+
],
|
|
881
|
+
internalType: "struct ServiceConfig",
|
|
882
|
+
name: "serviceConfig",
|
|
883
|
+
type: "tuple"
|
|
884
|
+
}
|
|
885
|
+
],
|
|
886
|
+
internalType: "struct ProofVerificationParams",
|
|
887
|
+
name: "params",
|
|
888
|
+
type: "tuple"
|
|
889
|
+
},
|
|
890
|
+
{
|
|
891
|
+
internalType: "bool",
|
|
892
|
+
name: "isIDCard",
|
|
893
|
+
type: "bool"
|
|
894
|
+
}
|
|
895
|
+
],
|
|
896
|
+
name: "zkPassportRegister",
|
|
897
|
+
outputs: [],
|
|
898
|
+
stateMutability: "nonpayable",
|
|
899
|
+
type: "function"
|
|
900
|
+
}
|
|
901
|
+
];
|
|
902
|
+
|
|
903
|
+
// src/contracts/abis/index.ts
|
|
904
|
+
var DIAMOND_ABI = [...orderFlowFacetAbi, ...p2pConfigFacetAbi];
|
|
905
|
+
var ABIS = {
|
|
906
|
+
DIAMOND: DIAMOND_ABI,
|
|
907
|
+
FACETS: {
|
|
908
|
+
ORDER_FLOW: orderFlowFacetAbi,
|
|
909
|
+
CONFIG: p2pConfigFacetAbi
|
|
910
|
+
},
|
|
911
|
+
EXTERNAL: {
|
|
912
|
+
USDC: import_viem2.erc20Abi,
|
|
913
|
+
REPUTATION_MANAGER: reputationManagerAbi
|
|
914
|
+
}
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
// src/contracts/order-flow/index.ts
|
|
918
|
+
var import_neverthrow4 = require("neverthrow");
|
|
919
|
+
|
|
920
|
+
// src/order-routing/errors.ts
|
|
921
|
+
var OrderRoutingError = class extends SdkError {
|
|
922
|
+
constructor(message, options) {
|
|
923
|
+
super(message, options);
|
|
924
|
+
this.name = "OrderRoutingError";
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
// src/order-routing/validation.ts
|
|
929
|
+
var import_zod3 = require("zod");
|
|
930
|
+
var ZodCircleScoreStateSchema = import_zod3.z.object({
|
|
931
|
+
activeMerchantsCount: import_zod3.z.coerce.number()
|
|
932
|
+
});
|
|
933
|
+
var ZodCircleMetricsForRoutingSchema = import_zod3.z.object({
|
|
934
|
+
circleScore: import_zod3.z.coerce.number(),
|
|
935
|
+
circleStatus: import_zod3.z.string(),
|
|
936
|
+
scoreState: ZodCircleScoreStateSchema
|
|
937
|
+
});
|
|
938
|
+
var ZodCircleForRoutingSchema = import_zod3.z.object({
|
|
939
|
+
circleId: import_zod3.z.string(),
|
|
940
|
+
currency: import_zod3.z.string(),
|
|
941
|
+
metrics: ZodCircleMetricsForRoutingSchema
|
|
942
|
+
});
|
|
943
|
+
var ZodCirclesForRoutingResponseSchema = import_zod3.z.object({
|
|
944
|
+
circles: import_zod3.z.array(ZodCircleForRoutingSchema)
|
|
945
|
+
});
|
|
946
|
+
var ZodCheckCircleEligibilityParamsSchema = import_zod3.z.object({
|
|
947
|
+
circleId: import_zod3.z.bigint(),
|
|
948
|
+
currency: import_zod3.z.string(),
|
|
949
|
+
user: ZodAddressSchema,
|
|
950
|
+
usdtAmount: import_zod3.z.bigint(),
|
|
951
|
+
fiatAmount: import_zod3.z.bigint(),
|
|
952
|
+
orderType: import_zod3.z.bigint(),
|
|
953
|
+
preferredPCConfigId: import_zod3.z.bigint()
|
|
954
|
+
});
|
|
955
|
+
var ZodSelectCircleParamsSchema = import_zod3.z.object({
|
|
956
|
+
currency: import_zod3.z.string().min(1),
|
|
957
|
+
user: ZodAddressSchema,
|
|
958
|
+
usdtAmount: import_zod3.z.bigint(),
|
|
959
|
+
fiatAmount: import_zod3.z.bigint(),
|
|
960
|
+
orderType: import_zod3.z.bigint(),
|
|
961
|
+
preferredPCConfigId: import_zod3.z.bigint()
|
|
962
|
+
});
|
|
963
|
+
|
|
964
|
+
// src/contracts/order-flow/index.ts
|
|
965
|
+
function checkCircleEligibility(publicClient, contractAddress, params, logger = noopLogger) {
|
|
966
|
+
return validate(
|
|
967
|
+
ZodCheckCircleEligibilityParamsSchema,
|
|
968
|
+
params,
|
|
969
|
+
(message, cause, d) => new OrderRoutingError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
|
|
970
|
+
).asyncAndThen((validated) => {
|
|
971
|
+
logger.debug("checking on-chain eligibility", {
|
|
972
|
+
circleId: String(validated.circleId),
|
|
973
|
+
contractAddress
|
|
974
|
+
});
|
|
975
|
+
return import_neverthrow4.ResultAsync.fromPromise(
|
|
976
|
+
publicClient.readContract({
|
|
977
|
+
address: contractAddress,
|
|
978
|
+
abi: ABIS.FACETS.ORDER_FLOW,
|
|
979
|
+
functionName: "getAssignableMerchantsFromCircle",
|
|
980
|
+
args: [
|
|
981
|
+
validated.circleId,
|
|
982
|
+
1n,
|
|
983
|
+
validated.currency,
|
|
984
|
+
validated.user,
|
|
985
|
+
validated.usdtAmount,
|
|
986
|
+
validated.fiatAmount,
|
|
987
|
+
validated.orderType,
|
|
988
|
+
validated.preferredPCConfigId
|
|
989
|
+
]
|
|
990
|
+
}),
|
|
991
|
+
(error) => new OrderRoutingError("Eligibility check failed", {
|
|
992
|
+
code: "CONTRACT_READ_ERROR",
|
|
993
|
+
cause: error,
|
|
994
|
+
context: { circleId: String(params.circleId) }
|
|
995
|
+
})
|
|
996
|
+
);
|
|
997
|
+
}).map((merchants) => {
|
|
998
|
+
const arr = merchants;
|
|
999
|
+
const eligible = arr.length >= 1;
|
|
1000
|
+
logger.debug("eligibility check result", {
|
|
1001
|
+
circleId: String(params.circleId),
|
|
1002
|
+
assignableMerchants: arr.length,
|
|
1003
|
+
eligible
|
|
1004
|
+
});
|
|
1005
|
+
return eligible;
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// src/contracts/p2p-config/index.ts
|
|
1010
|
+
var import_neverthrow5 = require("neverthrow");
|
|
1011
|
+
var import_viem3 = require("viem");
|
|
1012
|
+
|
|
1013
|
+
// src/profile/errors.ts
|
|
1014
|
+
var ProfileError = class extends SdkError {
|
|
1015
|
+
constructor(message, options) {
|
|
1016
|
+
super(message, options);
|
|
1017
|
+
this.name = "ProfileError";
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
// src/profile/validation.ts
|
|
1022
|
+
var import_zod4 = require("zod");
|
|
1023
|
+
var ZodUsdcBalanceParamsSchema = import_zod4.z.object({
|
|
1024
|
+
address: ZodAddressSchema
|
|
1025
|
+
});
|
|
1026
|
+
var ZodGetBalancesParamsSchema = import_zod4.z.object({
|
|
1027
|
+
address: ZodAddressSchema,
|
|
1028
|
+
currency: ZodCurrencySchema
|
|
1029
|
+
});
|
|
1030
|
+
var ZodTxLimitsParamsSchema = import_zod4.z.object({
|
|
1031
|
+
address: ZodAddressSchema,
|
|
1032
|
+
currency: ZodCurrencySchema
|
|
1033
|
+
});
|
|
1034
|
+
var ZodPriceConfigParamsSchema = import_zod4.z.object({
|
|
1035
|
+
currency: ZodCurrencySchema
|
|
1036
|
+
});
|
|
1037
|
+
|
|
1038
|
+
// src/contracts/p2p-config/index.ts
|
|
1039
|
+
function getPriceConfig(publicClient, diamondAddress, params) {
|
|
1040
|
+
return validate(
|
|
1041
|
+
ZodPriceConfigParamsSchema,
|
|
1042
|
+
params,
|
|
1043
|
+
(message, cause, data) => new ProfileError(message, {
|
|
1044
|
+
code: "VALIDATION_ERROR",
|
|
1045
|
+
cause,
|
|
1046
|
+
context: { params: data }
|
|
1047
|
+
})
|
|
1048
|
+
).asyncAndThen(
|
|
1049
|
+
(validated) => import_neverthrow5.ResultAsync.fromPromise(
|
|
1050
|
+
publicClient.readContract({
|
|
1051
|
+
address: diamondAddress,
|
|
1052
|
+
abi: ABIS.FACETS.CONFIG,
|
|
1053
|
+
functionName: "getPriceConfig",
|
|
1054
|
+
args: [(0, import_viem3.stringToHex)(validated.currency, { size: 32 })]
|
|
1055
|
+
}),
|
|
1056
|
+
(error) => new ProfileError("Failed to read price config", {
|
|
1057
|
+
code: "CONTRACT_READ_ERROR",
|
|
1058
|
+
cause: error,
|
|
1059
|
+
context: { currency: validated.currency, diamondAddress }
|
|
1060
|
+
})
|
|
1061
|
+
)
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// src/contracts/reputation-manager/writes.ts
|
|
1066
|
+
var import_neverthrow6 = require("neverthrow");
|
|
1067
|
+
var import_viem4 = require("viem");
|
|
1068
|
+
|
|
1069
|
+
// src/zkkyc/errors.ts
|
|
1070
|
+
var ZkkycError = class extends SdkError {
|
|
1071
|
+
constructor(message, options) {
|
|
1072
|
+
super(message, options);
|
|
1073
|
+
this.name = "ZkkycError";
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
// src/zkkyc/validation.ts
|
|
1078
|
+
var import_zod5 = require("zod");
|
|
1079
|
+
var ZodAnonAadharProofParamsSchema = import_zod5.z.object({
|
|
1080
|
+
nullifierSeed: import_zod5.z.bigint(),
|
|
1081
|
+
nullifier: import_zod5.z.bigint(),
|
|
1082
|
+
timestamp: import_zod5.z.bigint(),
|
|
1083
|
+
signal: import_zod5.z.bigint(),
|
|
1084
|
+
revealArray: import_zod5.z.tuple([import_zod5.z.bigint(), import_zod5.z.bigint(), import_zod5.z.bigint(), import_zod5.z.bigint()]),
|
|
1085
|
+
packedGroth16Proof: import_zod5.z.tuple([
|
|
1086
|
+
import_zod5.z.bigint(),
|
|
1087
|
+
import_zod5.z.bigint(),
|
|
1088
|
+
import_zod5.z.bigint(),
|
|
1089
|
+
import_zod5.z.bigint(),
|
|
1090
|
+
import_zod5.z.bigint(),
|
|
1091
|
+
import_zod5.z.bigint(),
|
|
1092
|
+
import_zod5.z.bigint(),
|
|
1093
|
+
import_zod5.z.bigint()
|
|
1094
|
+
])
|
|
1095
|
+
});
|
|
1096
|
+
var ZodSocialVerifyParamsSchema = import_zod5.z.object({
|
|
1097
|
+
_socialName: import_zod5.z.string(),
|
|
1098
|
+
proofs: import_zod5.z.array(
|
|
1099
|
+
import_zod5.z.object({
|
|
1100
|
+
claimInfo: import_zod5.z.object({
|
|
1101
|
+
provider: import_zod5.z.string(),
|
|
1102
|
+
parameters: import_zod5.z.string(),
|
|
1103
|
+
context: import_zod5.z.string()
|
|
1104
|
+
}),
|
|
1105
|
+
signedClaim: import_zod5.z.object({
|
|
1106
|
+
claim: import_zod5.z.object({
|
|
1107
|
+
identifier: import_zod5.z.string(),
|
|
1108
|
+
owner: ZodAddressSchema,
|
|
1109
|
+
timestampS: import_zod5.z.number(),
|
|
1110
|
+
epoch: import_zod5.z.number()
|
|
1111
|
+
}),
|
|
1112
|
+
signatures: import_zod5.z.array(import_zod5.z.string())
|
|
1113
|
+
})
|
|
1114
|
+
})
|
|
1115
|
+
)
|
|
1116
|
+
});
|
|
1117
|
+
var ZodSolidityVerifierParametersSchema = import_zod5.z.object({
|
|
1118
|
+
version: import_zod5.z.string().refine((val) => val.startsWith("0x"), {
|
|
1119
|
+
message: "Version must be a hex string"
|
|
1120
|
+
}),
|
|
1121
|
+
proofVerificationData: import_zod5.z.object({
|
|
1122
|
+
vkeyHash: import_zod5.z.string().refine((val) => /^0x[a-fA-F0-9]{64}$/.test(val), {
|
|
1123
|
+
message: "Invalid bytes32 hex string"
|
|
1124
|
+
}),
|
|
1125
|
+
proof: import_zod5.z.string().refine((val) => val.startsWith("0x"), {
|
|
1126
|
+
message: "Proof must be a hex string"
|
|
1127
|
+
}),
|
|
1128
|
+
publicInputs: import_zod5.z.array(
|
|
1129
|
+
import_zod5.z.string().refine((val) => /^0x[a-fA-F0-9]{64}$/.test(val), {
|
|
1130
|
+
message: "Each public input must be a valid bytes32 hex string"
|
|
1131
|
+
})
|
|
1132
|
+
)
|
|
1133
|
+
}),
|
|
1134
|
+
committedInputs: import_zod5.z.string().refine((val) => val.startsWith("0x"), {
|
|
1135
|
+
message: "Committed inputs must be a hex string"
|
|
1136
|
+
}),
|
|
1137
|
+
serviceConfig: import_zod5.z.object({
|
|
1138
|
+
validityPeriodInSeconds: import_zod5.z.number().int().nonnegative(),
|
|
1139
|
+
domain: import_zod5.z.string(),
|
|
1140
|
+
scope: import_zod5.z.string(),
|
|
1141
|
+
devMode: import_zod5.z.boolean()
|
|
1142
|
+
})
|
|
1143
|
+
});
|
|
1144
|
+
var ZodZkPassportRegisterParamsSchema = import_zod5.z.object({
|
|
1145
|
+
params: ZodSolidityVerifierParametersSchema,
|
|
1146
|
+
isIDCard: import_zod5.z.boolean()
|
|
1147
|
+
});
|
|
1148
|
+
|
|
1149
|
+
// src/contracts/reputation-manager/writes.ts
|
|
1150
|
+
function prepareSocialVerify(reputationManagerAddress, params) {
|
|
1151
|
+
return validate(
|
|
1152
|
+
ZodSocialVerifyParamsSchema,
|
|
1153
|
+
params,
|
|
1154
|
+
(message, cause, data) => new ZkkycError(message, { code: "VALIDATION_ERROR", cause, context: { params: data } })
|
|
1155
|
+
).andThen(
|
|
1156
|
+
(validated) => import_neverthrow6.Result.fromThrowable(
|
|
1157
|
+
() => ({
|
|
1158
|
+
to: reputationManagerAddress,
|
|
1159
|
+
data: (0, import_viem4.encodeFunctionData)({
|
|
1160
|
+
abi: ABIS.EXTERNAL.REPUTATION_MANAGER,
|
|
1161
|
+
functionName: "socialVerify",
|
|
1162
|
+
args: [
|
|
1163
|
+
validated._socialName,
|
|
1164
|
+
validated.proofs.map((proof) => ({
|
|
1165
|
+
...proof,
|
|
1166
|
+
signedClaim: {
|
|
1167
|
+
...proof.signedClaim,
|
|
1168
|
+
claim: {
|
|
1169
|
+
...proof.signedClaim.claim,
|
|
1170
|
+
identifier: proof.signedClaim.claim.identifier
|
|
1171
|
+
},
|
|
1172
|
+
signatures: proof.signedClaim.signatures
|
|
1173
|
+
}
|
|
1174
|
+
}))
|
|
1175
|
+
]
|
|
1176
|
+
})
|
|
1177
|
+
}),
|
|
1178
|
+
(error) => new ZkkycError("Failed to encode socialVerify", {
|
|
1179
|
+
code: "ENCODE_ERROR",
|
|
1180
|
+
cause: error
|
|
1181
|
+
})
|
|
1182
|
+
)()
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
function prepareSubmitAnonAadharProof(reputationManagerAddress, params) {
|
|
1186
|
+
return validate(
|
|
1187
|
+
ZodAnonAadharProofParamsSchema,
|
|
1188
|
+
params,
|
|
1189
|
+
(message, cause, data) => new ZkkycError(message, { code: "VALIDATION_ERROR", cause, context: { params: data } })
|
|
1190
|
+
).andThen(
|
|
1191
|
+
(validated) => import_neverthrow6.Result.fromThrowable(
|
|
1192
|
+
() => ({
|
|
1193
|
+
to: reputationManagerAddress,
|
|
1194
|
+
data: (0, import_viem4.encodeFunctionData)({
|
|
1195
|
+
abi: ABIS.EXTERNAL.REPUTATION_MANAGER,
|
|
1196
|
+
functionName: "submitAnonAadharProof",
|
|
1197
|
+
args: [
|
|
1198
|
+
validated.nullifierSeed,
|
|
1199
|
+
validated.nullifier,
|
|
1200
|
+
validated.timestamp,
|
|
1201
|
+
validated.signal,
|
|
1202
|
+
validated.revealArray,
|
|
1203
|
+
validated.packedGroth16Proof
|
|
1204
|
+
]
|
|
1205
|
+
})
|
|
1206
|
+
}),
|
|
1207
|
+
(error) => new ZkkycError("Failed to encode submitAnonAadharProof", {
|
|
1208
|
+
code: "ENCODE_ERROR",
|
|
1209
|
+
cause: error
|
|
1210
|
+
})
|
|
1211
|
+
)()
|
|
1212
|
+
);
|
|
1213
|
+
}
|
|
1214
|
+
function prepareZkPassportRegister(reputationManagerAddress, params) {
|
|
1215
|
+
return validate(
|
|
1216
|
+
ZodZkPassportRegisterParamsSchema,
|
|
1217
|
+
params,
|
|
1218
|
+
(message, cause, data) => new ZkkycError(message, { code: "VALIDATION_ERROR", cause, context: { params: data } })
|
|
1219
|
+
).andThen(
|
|
1220
|
+
(validated) => import_neverthrow6.Result.fromThrowable(
|
|
1221
|
+
() => {
|
|
1222
|
+
const { proofVerificationData, serviceConfig, committedInputs, version } = validated.params;
|
|
1223
|
+
const proofVerificationParams = {
|
|
1224
|
+
version,
|
|
1225
|
+
proofVerificationData: {
|
|
1226
|
+
vkeyHash: proofVerificationData.vkeyHash,
|
|
1227
|
+
proof: proofVerificationData.proof,
|
|
1228
|
+
publicInputs: proofVerificationData.publicInputs
|
|
1229
|
+
},
|
|
1230
|
+
committedInputs,
|
|
1231
|
+
serviceConfig: {
|
|
1232
|
+
validityPeriodInSeconds: BigInt(serviceConfig.validityPeriodInSeconds),
|
|
1233
|
+
domain: serviceConfig.domain,
|
|
1234
|
+
scope: serviceConfig.scope,
|
|
1235
|
+
devMode: serviceConfig.devMode
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
return {
|
|
1239
|
+
to: reputationManagerAddress,
|
|
1240
|
+
data: (0, import_viem4.encodeFunctionData)({
|
|
1241
|
+
abi: ABIS.EXTERNAL.REPUTATION_MANAGER,
|
|
1242
|
+
functionName: "zkPassportRegister",
|
|
1243
|
+
args: [proofVerificationParams, validated.isIDCard]
|
|
1244
|
+
})
|
|
1245
|
+
};
|
|
1246
|
+
},
|
|
1247
|
+
(error) => new ZkkycError("Failed to encode zkPassportRegister", {
|
|
1248
|
+
code: "ENCODE_ERROR",
|
|
1249
|
+
cause: error
|
|
1250
|
+
})
|
|
1251
|
+
)()
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
// src/contracts/tx-limits/index.ts
|
|
1256
|
+
var import_neverthrow7 = require("neverthrow");
|
|
1257
|
+
var import_viem5 = require("viem");
|
|
1258
|
+
function getTxLimits(publicClient, diamondAddress, params) {
|
|
1259
|
+
return validate(
|
|
1260
|
+
ZodTxLimitsParamsSchema,
|
|
1261
|
+
params,
|
|
1262
|
+
(message, cause, data) => new ProfileError(message, {
|
|
1263
|
+
code: "VALIDATION_ERROR",
|
|
1264
|
+
cause,
|
|
1265
|
+
context: { params: data }
|
|
1266
|
+
})
|
|
1267
|
+
).asyncAndThen(
|
|
1268
|
+
(validated) => import_neverthrow7.ResultAsync.fromPromise(
|
|
1269
|
+
publicClient.readContract({
|
|
1270
|
+
address: diamondAddress,
|
|
1271
|
+
abi: ABIS.FACETS.ORDER_FLOW,
|
|
1272
|
+
functionName: "userTxLimit",
|
|
1273
|
+
args: [validated.address, (0, import_viem5.stringToHex)(validated.currency, { size: 32 })]
|
|
1274
|
+
}),
|
|
1275
|
+
(error) => new ProfileError("Failed to read tx limits", {
|
|
1276
|
+
code: "CONTRACT_READ_ERROR",
|
|
1277
|
+
cause: error,
|
|
1278
|
+
context: { address: validated.address, currency: validated.currency, diamondAddress }
|
|
1279
|
+
})
|
|
1280
|
+
).map(([buyLimit, sellLimit]) => ({
|
|
1281
|
+
buyLimit: Number((0, import_viem5.formatUnits)(buyLimit, 6)),
|
|
1282
|
+
sellLimit: Number((0, import_viem5.formatUnits)(sellLimit, 6))
|
|
1283
|
+
}))
|
|
1284
|
+
);
|
|
1285
|
+
}
|
|
1286
|
+
function getRpPerUsdtLimitRational(publicClient, diamondAddress, params) {
|
|
1287
|
+
return validate(
|
|
1288
|
+
ZodPriceConfigParamsSchema,
|
|
1289
|
+
params,
|
|
1290
|
+
(message, cause, data) => new ProfileError(message, {
|
|
1291
|
+
code: "VALIDATION_ERROR",
|
|
1292
|
+
cause,
|
|
1293
|
+
context: { params: data }
|
|
1294
|
+
})
|
|
1295
|
+
).asyncAndThen(
|
|
1296
|
+
(validated) => import_neverthrow7.ResultAsync.fromPromise(
|
|
1297
|
+
publicClient.readContract({
|
|
1298
|
+
address: diamondAddress,
|
|
1299
|
+
abi: ABIS.DIAMOND,
|
|
1300
|
+
functionName: "getRpPerUsdtLimitRational",
|
|
1301
|
+
args: [(0, import_viem5.stringToHex)(validated.currency, { size: 32 })]
|
|
1302
|
+
}),
|
|
1303
|
+
(error) => new ProfileError("Failed to read RP per USDT limit rational", {
|
|
1304
|
+
code: "CONTRACT_READ_ERROR",
|
|
1305
|
+
cause: error,
|
|
1306
|
+
context: { currency: validated.currency, diamondAddress }
|
|
1307
|
+
})
|
|
1308
|
+
).map(([numerator, denominator]) => ({
|
|
1309
|
+
numerator,
|
|
1310
|
+
denominator,
|
|
1311
|
+
multiplier: numerator > 0n ? Number(denominator) / Number(numerator) : 0
|
|
1312
|
+
}))
|
|
1313
|
+
);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
// src/contracts/usdc/index.ts
|
|
1317
|
+
var import_neverthrow8 = require("neverthrow");
|
|
1318
|
+
function getUsdcBalance(publicClient, usdcAddress, params) {
|
|
1319
|
+
return validate(
|
|
1320
|
+
ZodUsdcBalanceParamsSchema,
|
|
1321
|
+
params,
|
|
1322
|
+
(message, cause, data) => new ProfileError(message, {
|
|
1323
|
+
code: "VALIDATION_ERROR",
|
|
1324
|
+
cause,
|
|
1325
|
+
context: { params: data }
|
|
1326
|
+
})
|
|
1327
|
+
).asyncAndThen(
|
|
1328
|
+
(validated) => import_neverthrow8.ResultAsync.fromPromise(
|
|
1329
|
+
publicClient.readContract({
|
|
1330
|
+
address: usdcAddress,
|
|
1331
|
+
abi: ABIS.EXTERNAL.USDC,
|
|
1332
|
+
functionName: "balanceOf",
|
|
1333
|
+
args: [validated.address]
|
|
1334
|
+
}),
|
|
1335
|
+
(error) => new ProfileError("Failed to read USDC balance", {
|
|
1336
|
+
code: "CONTRACT_READ_ERROR",
|
|
1337
|
+
cause: error,
|
|
1338
|
+
context: { address: validated.address, usdcAddress }
|
|
1339
|
+
})
|
|
1340
|
+
)
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
// src/order-routing/routing.ts
|
|
1345
|
+
var import_neverthrow9 = require("neverthrow");
|
|
1346
|
+
var EPSILON = 0.25;
|
|
1347
|
+
var RECOVERY_SCALE = 0.3;
|
|
1348
|
+
var BOOTSTRAP_MAX_WEIGHT = 25;
|
|
1349
|
+
var MAX_VALIDATION_ATTEMPTS = 3;
|
|
1350
|
+
function circleWeight(c) {
|
|
1351
|
+
const score = c.metrics.circleScore;
|
|
1352
|
+
if (c.metrics.circleStatus === "paused") {
|
|
1353
|
+
return score * RECOVERY_SCALE;
|
|
1354
|
+
}
|
|
1355
|
+
if (c.metrics.circleStatus === "bootstrap") {
|
|
1356
|
+
return Math.min(score, BOOTSTRAP_MAX_WEIGHT);
|
|
1357
|
+
}
|
|
1358
|
+
return score;
|
|
1359
|
+
}
|
|
1360
|
+
function filterEligibleCircles(circles, orderCurrency) {
|
|
1361
|
+
return circles.filter((c) => c.currency.toLowerCase() === orderCurrency.toLowerCase());
|
|
1362
|
+
}
|
|
1363
|
+
function weightedRandomChoice(arr, weights) {
|
|
1364
|
+
const totalWeight = weights.reduce((sum, w) => sum + w, 0);
|
|
1365
|
+
if (totalWeight === 0) {
|
|
1366
|
+
return arr[Math.floor(Math.random() * arr.length)];
|
|
1367
|
+
}
|
|
1368
|
+
let rand = Math.random() * totalWeight;
|
|
1369
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1370
|
+
rand -= weights[i];
|
|
1371
|
+
if (rand <= 0) {
|
|
1372
|
+
return arr[i];
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
return arr[arr.length - 1];
|
|
1376
|
+
}
|
|
1377
|
+
function selectCircle(eligible) {
|
|
1378
|
+
if (eligible.length === 0) {
|
|
1379
|
+
return null;
|
|
1380
|
+
}
|
|
1381
|
+
const activeCircles = eligible.filter((c) => c.metrics.circleStatus === "active");
|
|
1382
|
+
const isExplore = Math.random() < EPSILON;
|
|
1383
|
+
if (isExplore) {
|
|
1384
|
+
const weights2 = eligible.map(circleWeight);
|
|
1385
|
+
return weightedRandomChoice(eligible, weights2);
|
|
1386
|
+
}
|
|
1387
|
+
if (activeCircles.length === 0) {
|
|
1388
|
+
const weights2 = eligible.map(circleWeight);
|
|
1389
|
+
return weightedRandomChoice(eligible, weights2);
|
|
1390
|
+
}
|
|
1391
|
+
const weights = activeCircles.map((c) => c.metrics.circleScore);
|
|
1392
|
+
return weightedRandomChoice(activeCircles, weights);
|
|
1393
|
+
}
|
|
1394
|
+
function selectCircleForOrderAsync(circles, orderCurrency, validateCircle, logger = noopLogger) {
|
|
1395
|
+
const eligible = filterEligibleCircles(circles, orderCurrency);
|
|
1396
|
+
let remaining = [...eligible];
|
|
1397
|
+
logger.debug("filtering eligible circles", {
|
|
1398
|
+
total: circles.length,
|
|
1399
|
+
eligible: eligible.length,
|
|
1400
|
+
currency: orderCurrency,
|
|
1401
|
+
circles: eligible
|
|
1402
|
+
});
|
|
1403
|
+
if (eligible.length === 0) {
|
|
1404
|
+
logger.warn("no eligible circles found for currency", { currency: orderCurrency });
|
|
1405
|
+
}
|
|
1406
|
+
function attempt(attemptsLeft) {
|
|
1407
|
+
if (attemptsLeft <= 0 || remaining.length === 0) {
|
|
1408
|
+
logger.warn("exhausted all attempts or circles", {
|
|
1409
|
+
attemptsLeft,
|
|
1410
|
+
remainingCircles: remaining.length
|
|
1411
|
+
});
|
|
1412
|
+
return (0, import_neverthrow9.errAsync)(
|
|
1413
|
+
new OrderRoutingError("No eligible circles found", {
|
|
1414
|
+
code: "NO_ELIGIBLE_CIRCLES"
|
|
1415
|
+
})
|
|
1416
|
+
);
|
|
1417
|
+
}
|
|
1418
|
+
const selected = selectCircle(remaining);
|
|
1419
|
+
if (!selected) {
|
|
1420
|
+
return (0, import_neverthrow9.errAsync)(
|
|
1421
|
+
new OrderRoutingError("No eligible circles found", {
|
|
1422
|
+
code: "NO_ELIGIBLE_CIRCLES"
|
|
1423
|
+
})
|
|
1424
|
+
);
|
|
1425
|
+
}
|
|
1426
|
+
const circleId = BigInt(selected.circleId);
|
|
1427
|
+
logger.debug("selected circle, validating on-chain", {
|
|
1428
|
+
circleId: String(circleId),
|
|
1429
|
+
status: selected.metrics.circleStatus,
|
|
1430
|
+
score: selected.metrics.circleScore,
|
|
1431
|
+
attemptsLeft
|
|
1432
|
+
});
|
|
1433
|
+
return validateCircle(circleId).orElse((error) => {
|
|
1434
|
+
logger.warn("validation errored, treating as ineligible", {
|
|
1435
|
+
circleId: String(circleId),
|
|
1436
|
+
error: String(error)
|
|
1437
|
+
});
|
|
1438
|
+
return (0, import_neverthrow9.okAsync)(false);
|
|
1439
|
+
}).andThen((isValid) => {
|
|
1440
|
+
if (isValid) {
|
|
1441
|
+
logger.info("circle validated successfully", { circleId: String(circleId) });
|
|
1442
|
+
return (0, import_neverthrow9.okAsync)(circleId);
|
|
1443
|
+
}
|
|
1444
|
+
logger.debug("circle failed validation, retrying", {
|
|
1445
|
+
circleId: String(circleId),
|
|
1446
|
+
remainingCircles: remaining.length - 1
|
|
1447
|
+
});
|
|
1448
|
+
remaining = remaining.filter((c) => c.circleId !== selected.circleId);
|
|
1449
|
+
return attempt(attemptsLeft - 1);
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
return attempt(MAX_VALIDATION_ATTEMPTS);
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// src/order-routing/subgraph/client.ts
|
|
1456
|
+
var import_neverthrow10 = require("neverthrow");
|
|
1457
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
1458
|
+
var MAX_RETRIES = 3;
|
|
1459
|
+
var BACKOFF_MS = 500;
|
|
1460
|
+
function isTransient(error) {
|
|
1461
|
+
if (error instanceof OrderRoutingError) return false;
|
|
1462
|
+
if (error instanceof DOMException && error.name === "AbortError") return true;
|
|
1463
|
+
if (error instanceof TypeError) return true;
|
|
1464
|
+
return false;
|
|
1465
|
+
}
|
|
1466
|
+
function querySubgraph(url, params) {
|
|
1467
|
+
const timeoutMs = params.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1468
|
+
const fetchOnce = async () => {
|
|
1469
|
+
const controller = new AbortController();
|
|
1470
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
1471
|
+
try {
|
|
1472
|
+
const response = await fetch(url, {
|
|
1473
|
+
method: "POST",
|
|
1474
|
+
headers: { "Content-Type": "application/json" },
|
|
1475
|
+
body: JSON.stringify({
|
|
1476
|
+
query: params.query,
|
|
1477
|
+
variables: params.variables
|
|
1478
|
+
}),
|
|
1479
|
+
signal: controller.signal
|
|
1480
|
+
});
|
|
1481
|
+
if (!response.ok) {
|
|
1482
|
+
throw new OrderRoutingError(`Subgraph request failed (status: ${response.status})`, {
|
|
1483
|
+
code: "SUBGRAPH_ERROR",
|
|
1484
|
+
cause: response,
|
|
1485
|
+
context: { status: response.status }
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
const json = await response.json();
|
|
1489
|
+
if (json.errors?.length > 0) {
|
|
1490
|
+
throw new OrderRoutingError("Subgraph returned GraphQL errors", {
|
|
1491
|
+
code: "SUBGRAPH_ERROR",
|
|
1492
|
+
cause: json.errors,
|
|
1493
|
+
context: { errors: json.errors }
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
if (!json.data) {
|
|
1497
|
+
throw new OrderRoutingError("Subgraph returned no data", {
|
|
1498
|
+
code: "SUBGRAPH_ERROR",
|
|
1499
|
+
cause: "Missing data field in GraphQL response",
|
|
1500
|
+
context: { response: json }
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
return json.data;
|
|
1504
|
+
} finally {
|
|
1505
|
+
clearTimeout(timer);
|
|
1506
|
+
}
|
|
1507
|
+
};
|
|
1508
|
+
const fetchWithRetry = async () => {
|
|
1509
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
1510
|
+
try {
|
|
1511
|
+
return await fetchOnce();
|
|
1512
|
+
} catch (error) {
|
|
1513
|
+
const lastAttempt = attempt === MAX_RETRIES;
|
|
1514
|
+
if (lastAttempt || !isTransient(error)) throw error;
|
|
1515
|
+
await sleep(BACKOFF_MS * (attempt + 1));
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
throw new OrderRoutingError("Subgraph query exhausted retries", {
|
|
1519
|
+
code: "SUBGRAPH_ERROR"
|
|
1520
|
+
});
|
|
1521
|
+
};
|
|
1522
|
+
return import_neverthrow10.ResultAsync.fromPromise(
|
|
1523
|
+
fetchWithRetry(),
|
|
1524
|
+
(error) => error instanceof OrderRoutingError ? error : new OrderRoutingError("Subgraph query failed", {
|
|
1525
|
+
code: "SUBGRAPH_ERROR",
|
|
1526
|
+
cause: error
|
|
1527
|
+
})
|
|
1528
|
+
);
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
// src/order-routing/subgraph/queries.ts
|
|
1532
|
+
var CIRCLES_FOR_ROUTING_QUERY = (
|
|
1533
|
+
/* GraphQL */
|
|
1534
|
+
`
|
|
1535
|
+
query CirclesForRouting($currency: Bytes!) {
|
|
1536
|
+
circles(
|
|
1537
|
+
first: 1000
|
|
1538
|
+
where: {
|
|
1539
|
+
currency: $currency
|
|
1540
|
+
metrics_: {
|
|
1541
|
+
circleStatus_in: ["active", "bootstrap", "paused"]
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
) {
|
|
1545
|
+
circleId
|
|
1546
|
+
currency
|
|
1547
|
+
metrics {
|
|
1548
|
+
circleScore
|
|
1549
|
+
circleStatus
|
|
1550
|
+
scoreState {
|
|
1551
|
+
activeMerchantsCount
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
`
|
|
1557
|
+
);
|
|
1558
|
+
|
|
1559
|
+
// src/order-routing/subgraph/index.ts
|
|
1560
|
+
function getCirclesForRouting(subgraphUrl, currency, logger = noopLogger) {
|
|
1561
|
+
logger.debug("fetching circles from subgraph", { subgraphUrl, currency });
|
|
1562
|
+
return querySubgraph(subgraphUrl, {
|
|
1563
|
+
query: CIRCLES_FOR_ROUTING_QUERY,
|
|
1564
|
+
variables: { currency }
|
|
1565
|
+
}).andThen(
|
|
1566
|
+
(data) => validate(
|
|
1567
|
+
ZodCirclesForRoutingResponseSchema,
|
|
1568
|
+
data,
|
|
1569
|
+
(message, cause, d) => new OrderRoutingError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
|
|
1570
|
+
).map((validated) => {
|
|
1571
|
+
const circles = validated.circles.filter(
|
|
1572
|
+
(item) => Number(item.metrics.scoreState.activeMerchantsCount) > 0
|
|
1573
|
+
);
|
|
1574
|
+
logger.info("fetched circles from subgraph", {
|
|
1575
|
+
total: validated.circles.length,
|
|
1576
|
+
withActiveMerchants: circles.length,
|
|
1577
|
+
circles
|
|
1578
|
+
});
|
|
1579
|
+
return circles;
|
|
1580
|
+
})
|
|
1581
|
+
);
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
// src/order-routing/client.ts
|
|
1585
|
+
function createOrderRouter(config) {
|
|
1586
|
+
const { subgraphUrl, publicClient, contractAddress } = config;
|
|
1587
|
+
const logger = config.logger ?? noopLogger;
|
|
1588
|
+
return {
|
|
1589
|
+
selectCircle(params) {
|
|
1590
|
+
const currencyHex = (0, import_viem6.stringToHex)(params.currency, { size: 32 });
|
|
1591
|
+
logger.info("selectCircle started", {
|
|
1592
|
+
currency: params.currency,
|
|
1593
|
+
user: params.user,
|
|
1594
|
+
orderType: String(params.orderType)
|
|
1595
|
+
});
|
|
1596
|
+
return getCirclesForRouting(subgraphUrl, currencyHex, logger).andThen(
|
|
1597
|
+
(circles) => selectCircleForOrderAsync(
|
|
1598
|
+
circles,
|
|
1599
|
+
currencyHex,
|
|
1600
|
+
(circleId) => checkCircleEligibility(
|
|
1601
|
+
publicClient,
|
|
1602
|
+
contractAddress,
|
|
1603
|
+
{
|
|
1604
|
+
circleId,
|
|
1605
|
+
currency: currencyHex,
|
|
1606
|
+
user: params.user,
|
|
1607
|
+
usdtAmount: params.usdtAmount,
|
|
1608
|
+
fiatAmount: params.fiatAmount,
|
|
1609
|
+
orderType: params.orderType,
|
|
1610
|
+
preferredPCConfigId: params.preferredPCConfigId
|
|
1611
|
+
},
|
|
1612
|
+
logger
|
|
1613
|
+
),
|
|
1614
|
+
logger
|
|
1615
|
+
)
|
|
1616
|
+
);
|
|
1617
|
+
}
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
// src/payload/actions.ts
|
|
1622
|
+
var import_neverthrow13 = require("neverthrow");
|
|
1623
|
+
|
|
1624
|
+
// src/constants/orders.ts
|
|
1625
|
+
var ORDER_TYPE = {
|
|
1626
|
+
BUY: 0,
|
|
1627
|
+
SELL: 1,
|
|
1628
|
+
PAY: 2
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
// src/payload/crypto.ts
|
|
1632
|
+
var import_neverthrow12 = require("neverthrow");
|
|
1633
|
+
var import_viem8 = require("viem");
|
|
1634
|
+
var import_accounts2 = require("viem/accounts");
|
|
1635
|
+
var import_zod7 = require("zod");
|
|
1636
|
+
|
|
1637
|
+
// node_modules/@noble/ciphers/esm/utils.js
|
|
1638
|
+
function isBytes(a) {
|
|
1639
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
1640
|
+
}
|
|
1641
|
+
function abytes(b, ...lengths) {
|
|
1642
|
+
if (!isBytes(b))
|
|
1643
|
+
throw new Error("Uint8Array expected");
|
|
1644
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
1645
|
+
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
|
|
1646
|
+
}
|
|
1647
|
+
function u32(arr) {
|
|
1648
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
1649
|
+
}
|
|
1650
|
+
function clean(...arrays) {
|
|
1651
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
1652
|
+
arrays[i].fill(0);
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
1656
|
+
function overlapBytes(a, b) {
|
|
1657
|
+
return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
|
|
1658
|
+
a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
|
|
1659
|
+
b.byteOffset < a.byteOffset + a.byteLength;
|
|
1660
|
+
}
|
|
1661
|
+
function complexOverlapBytes(input, output) {
|
|
1662
|
+
if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
|
|
1663
|
+
throw new Error("complex overlap of input and output is not supported");
|
|
1664
|
+
}
|
|
1665
|
+
var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
|
|
1666
|
+
function wrappedCipher(key, ...args) {
|
|
1667
|
+
abytes(key);
|
|
1668
|
+
if (!isLE)
|
|
1669
|
+
throw new Error("Non little-endian hardware is not yet supported");
|
|
1670
|
+
if (params.nonceLength !== void 0) {
|
|
1671
|
+
const nonce = args[0];
|
|
1672
|
+
if (!nonce)
|
|
1673
|
+
throw new Error("nonce / iv required");
|
|
1674
|
+
if (params.varSizeNonce)
|
|
1675
|
+
abytes(nonce);
|
|
1676
|
+
else
|
|
1677
|
+
abytes(nonce, params.nonceLength);
|
|
1678
|
+
}
|
|
1679
|
+
const tagl = params.tagLength;
|
|
1680
|
+
if (tagl && args[1] !== void 0) {
|
|
1681
|
+
abytes(args[1]);
|
|
1682
|
+
}
|
|
1683
|
+
const cipher = constructor(key, ...args);
|
|
1684
|
+
const checkOutput = (fnLength, output) => {
|
|
1685
|
+
if (output !== void 0) {
|
|
1686
|
+
if (fnLength !== 2)
|
|
1687
|
+
throw new Error("cipher output not supported");
|
|
1688
|
+
abytes(output);
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
let called = false;
|
|
1692
|
+
const wrCipher = {
|
|
1693
|
+
encrypt(data, output) {
|
|
1694
|
+
if (called)
|
|
1695
|
+
throw new Error("cannot encrypt() twice with same key + nonce");
|
|
1696
|
+
called = true;
|
|
1697
|
+
abytes(data);
|
|
1698
|
+
checkOutput(cipher.encrypt.length, output);
|
|
1699
|
+
return cipher.encrypt(data, output);
|
|
1700
|
+
},
|
|
1701
|
+
decrypt(data, output) {
|
|
1702
|
+
abytes(data);
|
|
1703
|
+
if (tagl && data.length < tagl)
|
|
1704
|
+
throw new Error("invalid ciphertext length: smaller than tagLength=" + tagl);
|
|
1705
|
+
checkOutput(cipher.decrypt.length, output);
|
|
1706
|
+
return cipher.decrypt(data, output);
|
|
1707
|
+
}
|
|
1708
|
+
};
|
|
1709
|
+
return wrCipher;
|
|
1710
|
+
}
|
|
1711
|
+
Object.assign(wrappedCipher, params);
|
|
1712
|
+
return wrappedCipher;
|
|
1713
|
+
};
|
|
1714
|
+
function getOutput(expectedLength, out, onlyAligned = true) {
|
|
1715
|
+
if (out === void 0)
|
|
1716
|
+
return new Uint8Array(expectedLength);
|
|
1717
|
+
if (out.length !== expectedLength)
|
|
1718
|
+
throw new Error("invalid output length, expected " + expectedLength + ", got: " + out.length);
|
|
1719
|
+
if (onlyAligned && !isAligned32(out))
|
|
1720
|
+
throw new Error("invalid output, must be aligned");
|
|
1721
|
+
return out;
|
|
1722
|
+
}
|
|
1723
|
+
function isAligned32(bytes) {
|
|
1724
|
+
return bytes.byteOffset % 4 === 0;
|
|
1725
|
+
}
|
|
1726
|
+
function copyBytes(bytes) {
|
|
1727
|
+
return Uint8Array.from(bytes);
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
// node_modules/@noble/ciphers/esm/aes.js
|
|
1731
|
+
var BLOCK_SIZE = 16;
|
|
1732
|
+
var POLY = 283;
|
|
1733
|
+
function mul2(n) {
|
|
1734
|
+
return n << 1 ^ POLY & -(n >> 7);
|
|
1735
|
+
}
|
|
1736
|
+
function mul(a, b) {
|
|
1737
|
+
let res = 0;
|
|
1738
|
+
for (; b > 0; b >>= 1) {
|
|
1739
|
+
res ^= a & -(b & 1);
|
|
1740
|
+
a = mul2(a);
|
|
1741
|
+
}
|
|
1742
|
+
return res;
|
|
1743
|
+
}
|
|
1744
|
+
var sbox = /* @__PURE__ */ (() => {
|
|
1745
|
+
const t = new Uint8Array(256);
|
|
1746
|
+
for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
|
|
1747
|
+
t[i] = x;
|
|
1748
|
+
const box = new Uint8Array(256);
|
|
1749
|
+
box[0] = 99;
|
|
1750
|
+
for (let i = 0; i < 255; i++) {
|
|
1751
|
+
let x = t[255 - i];
|
|
1752
|
+
x |= x << 8;
|
|
1753
|
+
box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
|
|
1754
|
+
}
|
|
1755
|
+
clean(t);
|
|
1756
|
+
return box;
|
|
1757
|
+
})();
|
|
1758
|
+
var invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
|
|
1759
|
+
var rotr32_8 = (n) => n << 24 | n >>> 8;
|
|
1760
|
+
var rotl32_8 = (n) => n << 8 | n >>> 24;
|
|
1761
|
+
function genTtable(sbox2, fn) {
|
|
1762
|
+
if (sbox2.length !== 256)
|
|
1763
|
+
throw new Error("Wrong sbox length");
|
|
1764
|
+
const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
|
|
1765
|
+
const T1 = T0.map(rotl32_8);
|
|
1766
|
+
const T2 = T1.map(rotl32_8);
|
|
1767
|
+
const T3 = T2.map(rotl32_8);
|
|
1768
|
+
const T01 = new Uint32Array(256 * 256);
|
|
1769
|
+
const T23 = new Uint32Array(256 * 256);
|
|
1770
|
+
const sbox22 = new Uint16Array(256 * 256);
|
|
1771
|
+
for (let i = 0; i < 256; i++) {
|
|
1772
|
+
for (let j = 0; j < 256; j++) {
|
|
1773
|
+
const idx = i * 256 + j;
|
|
1774
|
+
T01[idx] = T0[i] ^ T1[j];
|
|
1775
|
+
T23[idx] = T2[i] ^ T3[j];
|
|
1776
|
+
sbox22[idx] = sbox2[i] << 8 | sbox2[j];
|
|
1777
|
+
}
|
|
1778
|
+
}
|
|
1779
|
+
return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
|
|
1780
|
+
}
|
|
1781
|
+
var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
|
|
1782
|
+
var tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14));
|
|
1783
|
+
var xPowers = /* @__PURE__ */ (() => {
|
|
1784
|
+
const p = new Uint8Array(16);
|
|
1785
|
+
for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
|
|
1786
|
+
p[i] = x;
|
|
1787
|
+
return p;
|
|
1788
|
+
})();
|
|
1789
|
+
function expandKeyLE(key) {
|
|
1790
|
+
abytes(key);
|
|
1791
|
+
const len = key.length;
|
|
1792
|
+
if (![16, 24, 32].includes(len))
|
|
1793
|
+
throw new Error("aes: invalid key size, should be 16, 24 or 32, got " + len);
|
|
1794
|
+
const { sbox2 } = tableEncoding;
|
|
1795
|
+
const toClean = [];
|
|
1796
|
+
if (!isAligned32(key))
|
|
1797
|
+
toClean.push(key = copyBytes(key));
|
|
1798
|
+
const k32 = u32(key);
|
|
1799
|
+
const Nk = k32.length;
|
|
1800
|
+
const subByte = (n) => applySbox(sbox2, n, n, n, n);
|
|
1801
|
+
const xk = new Uint32Array(len + 28);
|
|
1802
|
+
xk.set(k32);
|
|
1803
|
+
for (let i = Nk; i < xk.length; i++) {
|
|
1804
|
+
let t = xk[i - 1];
|
|
1805
|
+
if (i % Nk === 0)
|
|
1806
|
+
t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
|
|
1807
|
+
else if (Nk > 6 && i % Nk === 4)
|
|
1808
|
+
t = subByte(t);
|
|
1809
|
+
xk[i] = xk[i - Nk] ^ t;
|
|
1810
|
+
}
|
|
1811
|
+
clean(...toClean);
|
|
1812
|
+
return xk;
|
|
1813
|
+
}
|
|
1814
|
+
function expandKeyDecLE(key) {
|
|
1815
|
+
const encKey = expandKeyLE(key);
|
|
1816
|
+
const xk = encKey.slice();
|
|
1817
|
+
const Nk = encKey.length;
|
|
1818
|
+
const { sbox2 } = tableEncoding;
|
|
1819
|
+
const { T0, T1, T2, T3 } = tableDecoding;
|
|
1820
|
+
for (let i = 0; i < Nk; i += 4) {
|
|
1821
|
+
for (let j = 0; j < 4; j++)
|
|
1822
|
+
xk[i + j] = encKey[Nk - i - 4 + j];
|
|
1823
|
+
}
|
|
1824
|
+
clean(encKey);
|
|
1825
|
+
for (let i = 4; i < Nk - 4; i++) {
|
|
1826
|
+
const x = xk[i];
|
|
1827
|
+
const w = applySbox(sbox2, x, x, x, x);
|
|
1828
|
+
xk[i] = T0[w & 255] ^ T1[w >>> 8 & 255] ^ T2[w >>> 16 & 255] ^ T3[w >>> 24];
|
|
1829
|
+
}
|
|
1830
|
+
return xk;
|
|
1831
|
+
}
|
|
1832
|
+
function apply0123(T01, T23, s0, s1, s2, s3) {
|
|
1833
|
+
return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
|
|
1834
|
+
}
|
|
1835
|
+
function applySbox(sbox2, s0, s1, s2, s3) {
|
|
1836
|
+
return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
|
|
1837
|
+
}
|
|
1838
|
+
function encrypt(xk, s0, s1, s2, s3) {
|
|
1839
|
+
const { sbox2, T01, T23 } = tableEncoding;
|
|
1840
|
+
let k = 0;
|
|
1841
|
+
s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
|
|
1842
|
+
const rounds = xk.length / 4 - 2;
|
|
1843
|
+
for (let i = 0; i < rounds; i++) {
|
|
1844
|
+
const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
|
|
1845
|
+
const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
|
|
1846
|
+
const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
|
|
1847
|
+
const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
|
|
1848
|
+
s0 = t02, s1 = t12, s2 = t22, s3 = t32;
|
|
1849
|
+
}
|
|
1850
|
+
const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
|
|
1851
|
+
const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
|
|
1852
|
+
const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
|
|
1853
|
+
const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
|
|
1854
|
+
return { s0: t0, s1: t1, s2: t2, s3: t3 };
|
|
1855
|
+
}
|
|
1856
|
+
function decrypt(xk, s0, s1, s2, s3) {
|
|
1857
|
+
const { sbox2, T01, T23 } = tableDecoding;
|
|
1858
|
+
let k = 0;
|
|
1859
|
+
s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
|
|
1860
|
+
const rounds = xk.length / 4 - 2;
|
|
1861
|
+
for (let i = 0; i < rounds; i++) {
|
|
1862
|
+
const t02 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
|
|
1863
|
+
const t12 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
|
|
1864
|
+
const t22 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
|
|
1865
|
+
const t32 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
|
|
1866
|
+
s0 = t02, s1 = t12, s2 = t22, s3 = t32;
|
|
1867
|
+
}
|
|
1868
|
+
const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
|
|
1869
|
+
const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
|
|
1870
|
+
const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
|
|
1871
|
+
const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
|
|
1872
|
+
return { s0: t0, s1: t1, s2: t2, s3: t3 };
|
|
1873
|
+
}
|
|
1874
|
+
function validateBlockDecrypt(data) {
|
|
1875
|
+
abytes(data);
|
|
1876
|
+
if (data.length % BLOCK_SIZE !== 0) {
|
|
1877
|
+
throw new Error("aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size " + BLOCK_SIZE);
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
function validateBlockEncrypt(plaintext, pcks5, dst) {
|
|
1881
|
+
abytes(plaintext);
|
|
1882
|
+
let outLen = plaintext.length;
|
|
1883
|
+
const remaining = outLen % BLOCK_SIZE;
|
|
1884
|
+
if (!pcks5 && remaining !== 0)
|
|
1885
|
+
throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");
|
|
1886
|
+
if (!isAligned32(plaintext))
|
|
1887
|
+
plaintext = copyBytes(plaintext);
|
|
1888
|
+
const b = u32(plaintext);
|
|
1889
|
+
if (pcks5) {
|
|
1890
|
+
let left = BLOCK_SIZE - remaining;
|
|
1891
|
+
if (!left)
|
|
1892
|
+
left = BLOCK_SIZE;
|
|
1893
|
+
outLen = outLen + left;
|
|
1894
|
+
}
|
|
1895
|
+
dst = getOutput(outLen, dst);
|
|
1896
|
+
complexOverlapBytes(plaintext, dst);
|
|
1897
|
+
const o = u32(dst);
|
|
1898
|
+
return { b, o, out: dst };
|
|
1899
|
+
}
|
|
1900
|
+
function validatePCKS(data, pcks5) {
|
|
1901
|
+
if (!pcks5)
|
|
1902
|
+
return data;
|
|
1903
|
+
const len = data.length;
|
|
1904
|
+
if (!len)
|
|
1905
|
+
throw new Error("aes/pcks5: empty ciphertext not allowed");
|
|
1906
|
+
const lastByte = data[len - 1];
|
|
1907
|
+
if (lastByte <= 0 || lastByte > 16)
|
|
1908
|
+
throw new Error("aes/pcks5: wrong padding");
|
|
1909
|
+
const out = data.subarray(0, -lastByte);
|
|
1910
|
+
for (let i = 0; i < lastByte; i++)
|
|
1911
|
+
if (data[len - i - 1] !== lastByte)
|
|
1912
|
+
throw new Error("aes/pcks5: wrong padding");
|
|
1913
|
+
return out;
|
|
1914
|
+
}
|
|
1915
|
+
function padPCKS(left) {
|
|
1916
|
+
const tmp = new Uint8Array(16);
|
|
1917
|
+
const tmp32 = u32(tmp);
|
|
1918
|
+
tmp.set(left);
|
|
1919
|
+
const paddingByte = BLOCK_SIZE - left.length;
|
|
1920
|
+
for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
|
|
1921
|
+
tmp[i] = paddingByte;
|
|
1922
|
+
return tmp32;
|
|
1923
|
+
}
|
|
1924
|
+
var cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
|
|
1925
|
+
const pcks5 = !opts.disablePadding;
|
|
1926
|
+
return {
|
|
1927
|
+
encrypt(plaintext, dst) {
|
|
1928
|
+
const xk = expandKeyLE(key);
|
|
1929
|
+
const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);
|
|
1930
|
+
let _iv = iv;
|
|
1931
|
+
const toClean = [xk];
|
|
1932
|
+
if (!isAligned32(_iv))
|
|
1933
|
+
toClean.push(_iv = copyBytes(_iv));
|
|
1934
|
+
const n32 = u32(_iv);
|
|
1935
|
+
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
|
|
1936
|
+
let i = 0;
|
|
1937
|
+
for (; i + 4 <= b.length; ) {
|
|
1938
|
+
s0 ^= b[i + 0], s1 ^= b[i + 1], s2 ^= b[i + 2], s3 ^= b[i + 3];
|
|
1939
|
+
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
|
|
1940
|
+
o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
|
|
1941
|
+
}
|
|
1942
|
+
if (pcks5) {
|
|
1943
|
+
const tmp32 = padPCKS(plaintext.subarray(i * 4));
|
|
1944
|
+
s0 ^= tmp32[0], s1 ^= tmp32[1], s2 ^= tmp32[2], s3 ^= tmp32[3];
|
|
1945
|
+
({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
|
|
1946
|
+
o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
|
|
1947
|
+
}
|
|
1948
|
+
clean(...toClean);
|
|
1949
|
+
return _out;
|
|
1950
|
+
},
|
|
1951
|
+
decrypt(ciphertext, dst) {
|
|
1952
|
+
validateBlockDecrypt(ciphertext);
|
|
1953
|
+
const xk = expandKeyDecLE(key);
|
|
1954
|
+
let _iv = iv;
|
|
1955
|
+
const toClean = [xk];
|
|
1956
|
+
if (!isAligned32(_iv))
|
|
1957
|
+
toClean.push(_iv = copyBytes(_iv));
|
|
1958
|
+
const n32 = u32(_iv);
|
|
1959
|
+
dst = getOutput(ciphertext.length, dst);
|
|
1960
|
+
if (!isAligned32(ciphertext))
|
|
1961
|
+
toClean.push(ciphertext = copyBytes(ciphertext));
|
|
1962
|
+
complexOverlapBytes(ciphertext, dst);
|
|
1963
|
+
const b = u32(ciphertext);
|
|
1964
|
+
const o = u32(dst);
|
|
1965
|
+
let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
|
|
1966
|
+
for (let i = 0; i + 4 <= b.length; ) {
|
|
1967
|
+
const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
|
|
1968
|
+
s0 = b[i + 0], s1 = b[i + 1], s2 = b[i + 2], s3 = b[i + 3];
|
|
1969
|
+
const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
|
|
1970
|
+
o[i++] = o0 ^ ps0, o[i++] = o1 ^ ps1, o[i++] = o2 ^ ps2, o[i++] = o3 ^ ps3;
|
|
1971
|
+
}
|
|
1972
|
+
clean(...toClean);
|
|
1973
|
+
return validatePCKS(dst, pcks5);
|
|
1974
|
+
}
|
|
1975
|
+
};
|
|
1976
|
+
});
|
|
1977
|
+
|
|
1978
|
+
// node_modules/@noble/hashes/esm/cryptoNode.js
|
|
1979
|
+
var nc = __toESM(require("crypto"), 1);
|
|
1980
|
+
var crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
|
|
1981
|
+
|
|
1982
|
+
// node_modules/@noble/hashes/esm/utils.js
|
|
1983
|
+
function isBytes2(a) {
|
|
1984
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
1985
|
+
}
|
|
1986
|
+
function anumber(n) {
|
|
1987
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
1988
|
+
throw new Error("positive integer expected, got " + n);
|
|
1989
|
+
}
|
|
1990
|
+
function abytes2(b, ...lengths) {
|
|
1991
|
+
if (!isBytes2(b))
|
|
1992
|
+
throw new Error("Uint8Array expected");
|
|
1993
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
1994
|
+
throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
|
|
1995
|
+
}
|
|
1996
|
+
function ahash(h) {
|
|
1997
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
1998
|
+
throw new Error("Hash should be wrapped by utils.createHasher");
|
|
1999
|
+
anumber(h.outputLen);
|
|
2000
|
+
anumber(h.blockLen);
|
|
2001
|
+
}
|
|
2002
|
+
function aexists(instance, checkFinished = true) {
|
|
2003
|
+
if (instance.destroyed)
|
|
2004
|
+
throw new Error("Hash instance has been destroyed");
|
|
2005
|
+
if (checkFinished && instance.finished)
|
|
2006
|
+
throw new Error("Hash#digest() has already been called");
|
|
2007
|
+
}
|
|
2008
|
+
function aoutput(out, instance) {
|
|
2009
|
+
abytes2(out);
|
|
2010
|
+
const min = instance.outputLen;
|
|
2011
|
+
if (out.length < min) {
|
|
2012
|
+
throw new Error("digestInto() expects output buffer of length at least " + min);
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
function clean2(...arrays) {
|
|
2016
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
2017
|
+
arrays[i].fill(0);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
function createView2(arr) {
|
|
2021
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
2022
|
+
}
|
|
2023
|
+
function rotr(word, shift) {
|
|
2024
|
+
return word << 32 - shift | word >>> shift;
|
|
2025
|
+
}
|
|
2026
|
+
function utf8ToBytes(str) {
|
|
2027
|
+
if (typeof str !== "string")
|
|
2028
|
+
throw new Error("string expected");
|
|
2029
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
2030
|
+
}
|
|
2031
|
+
function toBytes(data) {
|
|
2032
|
+
if (typeof data === "string")
|
|
2033
|
+
data = utf8ToBytes(data);
|
|
2034
|
+
abytes2(data);
|
|
2035
|
+
return data;
|
|
2036
|
+
}
|
|
2037
|
+
function concatBytes2(...arrays) {
|
|
2038
|
+
let sum = 0;
|
|
2039
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
2040
|
+
const a = arrays[i];
|
|
2041
|
+
abytes2(a);
|
|
2042
|
+
sum += a.length;
|
|
2043
|
+
}
|
|
2044
|
+
const res = new Uint8Array(sum);
|
|
2045
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
2046
|
+
const a = arrays[i];
|
|
2047
|
+
res.set(a, pad);
|
|
2048
|
+
pad += a.length;
|
|
2049
|
+
}
|
|
2050
|
+
return res;
|
|
2051
|
+
}
|
|
2052
|
+
var Hash = class {
|
|
2053
|
+
};
|
|
2054
|
+
function createHasher(hashCons) {
|
|
2055
|
+
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
2056
|
+
const tmp = hashCons();
|
|
2057
|
+
hashC.outputLen = tmp.outputLen;
|
|
2058
|
+
hashC.blockLen = tmp.blockLen;
|
|
2059
|
+
hashC.create = () => hashCons();
|
|
2060
|
+
return hashC;
|
|
2061
|
+
}
|
|
2062
|
+
function randomBytes(bytesLength = 32) {
|
|
2063
|
+
if (crypto2 && typeof crypto2.getRandomValues === "function") {
|
|
2064
|
+
return crypto2.getRandomValues(new Uint8Array(bytesLength));
|
|
2065
|
+
}
|
|
2066
|
+
if (crypto2 && typeof crypto2.randomBytes === "function") {
|
|
2067
|
+
return Uint8Array.from(crypto2.randomBytes(bytesLength));
|
|
2068
|
+
}
|
|
2069
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
// node_modules/@noble/hashes/esm/_md.js
|
|
2073
|
+
function setBigUint642(view, byteOffset, value, isLE2) {
|
|
2074
|
+
if (typeof view.setBigUint64 === "function")
|
|
2075
|
+
return view.setBigUint64(byteOffset, value, isLE2);
|
|
2076
|
+
const _32n2 = BigInt(32);
|
|
2077
|
+
const _u32_max = BigInt(4294967295);
|
|
2078
|
+
const wh = Number(value >> _32n2 & _u32_max);
|
|
2079
|
+
const wl = Number(value & _u32_max);
|
|
2080
|
+
const h = isLE2 ? 4 : 0;
|
|
2081
|
+
const l = isLE2 ? 0 : 4;
|
|
2082
|
+
view.setUint32(byteOffset + h, wh, isLE2);
|
|
2083
|
+
view.setUint32(byteOffset + l, wl, isLE2);
|
|
2084
|
+
}
|
|
2085
|
+
function Chi(a, b, c) {
|
|
2086
|
+
return a & b ^ ~a & c;
|
|
2087
|
+
}
|
|
2088
|
+
function Maj(a, b, c) {
|
|
2089
|
+
return a & b ^ a & c ^ b & c;
|
|
2090
|
+
}
|
|
2091
|
+
var HashMD = class extends Hash {
|
|
2092
|
+
constructor(blockLen, outputLen, padOffset, isLE2) {
|
|
2093
|
+
super();
|
|
2094
|
+
this.finished = false;
|
|
2095
|
+
this.length = 0;
|
|
2096
|
+
this.pos = 0;
|
|
2097
|
+
this.destroyed = false;
|
|
2098
|
+
this.blockLen = blockLen;
|
|
2099
|
+
this.outputLen = outputLen;
|
|
2100
|
+
this.padOffset = padOffset;
|
|
2101
|
+
this.isLE = isLE2;
|
|
2102
|
+
this.buffer = new Uint8Array(blockLen);
|
|
2103
|
+
this.view = createView2(this.buffer);
|
|
2104
|
+
}
|
|
2105
|
+
update(data) {
|
|
2106
|
+
aexists(this);
|
|
2107
|
+
data = toBytes(data);
|
|
2108
|
+
abytes2(data);
|
|
2109
|
+
const { view, buffer, blockLen } = this;
|
|
2110
|
+
const len = data.length;
|
|
2111
|
+
for (let pos = 0; pos < len; ) {
|
|
2112
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
2113
|
+
if (take === blockLen) {
|
|
2114
|
+
const dataView = createView2(data);
|
|
2115
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
2116
|
+
this.process(dataView, pos);
|
|
2117
|
+
continue;
|
|
2118
|
+
}
|
|
2119
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
2120
|
+
this.pos += take;
|
|
2121
|
+
pos += take;
|
|
2122
|
+
if (this.pos === blockLen) {
|
|
2123
|
+
this.process(view, 0);
|
|
2124
|
+
this.pos = 0;
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
this.length += data.length;
|
|
2128
|
+
this.roundClean();
|
|
2129
|
+
return this;
|
|
2130
|
+
}
|
|
2131
|
+
digestInto(out) {
|
|
2132
|
+
aexists(this);
|
|
2133
|
+
aoutput(out, this);
|
|
2134
|
+
this.finished = true;
|
|
2135
|
+
const { buffer, view, blockLen, isLE: isLE2 } = this;
|
|
2136
|
+
let { pos } = this;
|
|
2137
|
+
buffer[pos++] = 128;
|
|
2138
|
+
clean2(this.buffer.subarray(pos));
|
|
2139
|
+
if (this.padOffset > blockLen - pos) {
|
|
2140
|
+
this.process(view, 0);
|
|
2141
|
+
pos = 0;
|
|
2142
|
+
}
|
|
2143
|
+
for (let i = pos; i < blockLen; i++)
|
|
2144
|
+
buffer[i] = 0;
|
|
2145
|
+
setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE2);
|
|
2146
|
+
this.process(view, 0);
|
|
2147
|
+
const oview = createView2(out);
|
|
2148
|
+
const len = this.outputLen;
|
|
2149
|
+
if (len % 4)
|
|
2150
|
+
throw new Error("_sha2: outputLen should be aligned to 32bit");
|
|
2151
|
+
const outLen = len / 4;
|
|
2152
|
+
const state = this.get();
|
|
2153
|
+
if (outLen > state.length)
|
|
2154
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
2155
|
+
for (let i = 0; i < outLen; i++)
|
|
2156
|
+
oview.setUint32(4 * i, state[i], isLE2);
|
|
2157
|
+
}
|
|
2158
|
+
digest() {
|
|
2159
|
+
const { buffer, outputLen } = this;
|
|
2160
|
+
this.digestInto(buffer);
|
|
2161
|
+
const res = buffer.slice(0, outputLen);
|
|
2162
|
+
this.destroy();
|
|
2163
|
+
return res;
|
|
2164
|
+
}
|
|
2165
|
+
_cloneInto(to) {
|
|
2166
|
+
to || (to = new this.constructor());
|
|
2167
|
+
to.set(...this.get());
|
|
2168
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
2169
|
+
to.destroyed = destroyed;
|
|
2170
|
+
to.finished = finished;
|
|
2171
|
+
to.length = length;
|
|
2172
|
+
to.pos = pos;
|
|
2173
|
+
if (length % blockLen)
|
|
2174
|
+
to.buffer.set(buffer);
|
|
2175
|
+
return to;
|
|
2176
|
+
}
|
|
2177
|
+
clone() {
|
|
2178
|
+
return this._cloneInto();
|
|
2179
|
+
}
|
|
2180
|
+
};
|
|
2181
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
2182
|
+
1779033703,
|
|
2183
|
+
3144134277,
|
|
2184
|
+
1013904242,
|
|
2185
|
+
2773480762,
|
|
2186
|
+
1359893119,
|
|
2187
|
+
2600822924,
|
|
2188
|
+
528734635,
|
|
2189
|
+
1541459225
|
|
2190
|
+
]);
|
|
2191
|
+
var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
|
|
2192
|
+
1779033703,
|
|
2193
|
+
4089235720,
|
|
2194
|
+
3144134277,
|
|
2195
|
+
2227873595,
|
|
2196
|
+
1013904242,
|
|
2197
|
+
4271175723,
|
|
2198
|
+
2773480762,
|
|
2199
|
+
1595750129,
|
|
2200
|
+
1359893119,
|
|
2201
|
+
2917565137,
|
|
2202
|
+
2600822924,
|
|
2203
|
+
725511199,
|
|
2204
|
+
528734635,
|
|
2205
|
+
4215389547,
|
|
2206
|
+
1541459225,
|
|
2207
|
+
327033209
|
|
2208
|
+
]);
|
|
2209
|
+
|
|
2210
|
+
// node_modules/@noble/hashes/esm/_u64.js
|
|
2211
|
+
var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
2212
|
+
var _32n = /* @__PURE__ */ BigInt(32);
|
|
2213
|
+
function fromBig(n, le = false) {
|
|
2214
|
+
if (le)
|
|
2215
|
+
return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
|
|
2216
|
+
return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
2217
|
+
}
|
|
2218
|
+
function split(lst, le = false) {
|
|
2219
|
+
const len = lst.length;
|
|
2220
|
+
let Ah = new Uint32Array(len);
|
|
2221
|
+
let Al = new Uint32Array(len);
|
|
2222
|
+
for (let i = 0; i < len; i++) {
|
|
2223
|
+
const { h, l } = fromBig(lst[i], le);
|
|
2224
|
+
[Ah[i], Al[i]] = [h, l];
|
|
2225
|
+
}
|
|
2226
|
+
return [Ah, Al];
|
|
2227
|
+
}
|
|
2228
|
+
var shrSH = (h, _l, s) => h >>> s;
|
|
2229
|
+
var shrSL = (h, l, s) => h << 32 - s | l >>> s;
|
|
2230
|
+
var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
|
|
2231
|
+
var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
|
|
2232
|
+
var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
|
|
2233
|
+
var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
|
|
2234
|
+
function add(Ah, Al, Bh, Bl) {
|
|
2235
|
+
const l = (Al >>> 0) + (Bl >>> 0);
|
|
2236
|
+
return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
|
|
2237
|
+
}
|
|
2238
|
+
var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
|
2239
|
+
var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
|
|
2240
|
+
var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
|
2241
|
+
var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
|
|
2242
|
+
var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
|
2243
|
+
var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
|
|
2244
|
+
|
|
2245
|
+
// node_modules/@noble/hashes/esm/sha2.js
|
|
2246
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
2247
|
+
1116352408,
|
|
2248
|
+
1899447441,
|
|
2249
|
+
3049323471,
|
|
2250
|
+
3921009573,
|
|
2251
|
+
961987163,
|
|
2252
|
+
1508970993,
|
|
2253
|
+
2453635748,
|
|
2254
|
+
2870763221,
|
|
2255
|
+
3624381080,
|
|
2256
|
+
310598401,
|
|
2257
|
+
607225278,
|
|
2258
|
+
1426881987,
|
|
2259
|
+
1925078388,
|
|
2260
|
+
2162078206,
|
|
2261
|
+
2614888103,
|
|
2262
|
+
3248222580,
|
|
2263
|
+
3835390401,
|
|
2264
|
+
4022224774,
|
|
2265
|
+
264347078,
|
|
2266
|
+
604807628,
|
|
2267
|
+
770255983,
|
|
2268
|
+
1249150122,
|
|
2269
|
+
1555081692,
|
|
2270
|
+
1996064986,
|
|
2271
|
+
2554220882,
|
|
2272
|
+
2821834349,
|
|
2273
|
+
2952996808,
|
|
2274
|
+
3210313671,
|
|
2275
|
+
3336571891,
|
|
2276
|
+
3584528711,
|
|
2277
|
+
113926993,
|
|
2278
|
+
338241895,
|
|
2279
|
+
666307205,
|
|
2280
|
+
773529912,
|
|
2281
|
+
1294757372,
|
|
2282
|
+
1396182291,
|
|
2283
|
+
1695183700,
|
|
2284
|
+
1986661051,
|
|
2285
|
+
2177026350,
|
|
2286
|
+
2456956037,
|
|
2287
|
+
2730485921,
|
|
2288
|
+
2820302411,
|
|
2289
|
+
3259730800,
|
|
2290
|
+
3345764771,
|
|
2291
|
+
3516065817,
|
|
2292
|
+
3600352804,
|
|
2293
|
+
4094571909,
|
|
2294
|
+
275423344,
|
|
2295
|
+
430227734,
|
|
2296
|
+
506948616,
|
|
2297
|
+
659060556,
|
|
2298
|
+
883997877,
|
|
2299
|
+
958139571,
|
|
2300
|
+
1322822218,
|
|
2301
|
+
1537002063,
|
|
2302
|
+
1747873779,
|
|
2303
|
+
1955562222,
|
|
2304
|
+
2024104815,
|
|
2305
|
+
2227730452,
|
|
2306
|
+
2361852424,
|
|
2307
|
+
2428436474,
|
|
2308
|
+
2756734187,
|
|
2309
|
+
3204031479,
|
|
2310
|
+
3329325298
|
|
2311
|
+
]);
|
|
2312
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
2313
|
+
var SHA256 = class extends HashMD {
|
|
2314
|
+
constructor(outputLen = 32) {
|
|
2315
|
+
super(64, outputLen, 8, false);
|
|
2316
|
+
this.A = SHA256_IV[0] | 0;
|
|
2317
|
+
this.B = SHA256_IV[1] | 0;
|
|
2318
|
+
this.C = SHA256_IV[2] | 0;
|
|
2319
|
+
this.D = SHA256_IV[3] | 0;
|
|
2320
|
+
this.E = SHA256_IV[4] | 0;
|
|
2321
|
+
this.F = SHA256_IV[5] | 0;
|
|
2322
|
+
this.G = SHA256_IV[6] | 0;
|
|
2323
|
+
this.H = SHA256_IV[7] | 0;
|
|
2324
|
+
}
|
|
2325
|
+
get() {
|
|
2326
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
2327
|
+
return [A, B, C, D, E, F, G, H];
|
|
2328
|
+
}
|
|
2329
|
+
// prettier-ignore
|
|
2330
|
+
set(A, B, C, D, E, F, G, H) {
|
|
2331
|
+
this.A = A | 0;
|
|
2332
|
+
this.B = B | 0;
|
|
2333
|
+
this.C = C | 0;
|
|
2334
|
+
this.D = D | 0;
|
|
2335
|
+
this.E = E | 0;
|
|
2336
|
+
this.F = F | 0;
|
|
2337
|
+
this.G = G | 0;
|
|
2338
|
+
this.H = H | 0;
|
|
2339
|
+
}
|
|
2340
|
+
process(view, offset) {
|
|
2341
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
2342
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
2343
|
+
for (let i = 16; i < 64; i++) {
|
|
2344
|
+
const W15 = SHA256_W[i - 15];
|
|
2345
|
+
const W2 = SHA256_W[i - 2];
|
|
2346
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
2347
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
2348
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
2349
|
+
}
|
|
2350
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
2351
|
+
for (let i = 0; i < 64; i++) {
|
|
2352
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
2353
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
2354
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
2355
|
+
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
2356
|
+
H = G;
|
|
2357
|
+
G = F;
|
|
2358
|
+
F = E;
|
|
2359
|
+
E = D + T1 | 0;
|
|
2360
|
+
D = C;
|
|
2361
|
+
C = B;
|
|
2362
|
+
B = A;
|
|
2363
|
+
A = T1 + T2 | 0;
|
|
2364
|
+
}
|
|
2365
|
+
A = A + this.A | 0;
|
|
2366
|
+
B = B + this.B | 0;
|
|
2367
|
+
C = C + this.C | 0;
|
|
2368
|
+
D = D + this.D | 0;
|
|
2369
|
+
E = E + this.E | 0;
|
|
2370
|
+
F = F + this.F | 0;
|
|
2371
|
+
G = G + this.G | 0;
|
|
2372
|
+
H = H + this.H | 0;
|
|
2373
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
2374
|
+
}
|
|
2375
|
+
roundClean() {
|
|
2376
|
+
clean2(SHA256_W);
|
|
2377
|
+
}
|
|
2378
|
+
destroy() {
|
|
2379
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
2380
|
+
clean2(this.buffer);
|
|
2381
|
+
}
|
|
2382
|
+
};
|
|
2383
|
+
var K512 = /* @__PURE__ */ (() => split([
|
|
2384
|
+
"0x428a2f98d728ae22",
|
|
2385
|
+
"0x7137449123ef65cd",
|
|
2386
|
+
"0xb5c0fbcfec4d3b2f",
|
|
2387
|
+
"0xe9b5dba58189dbbc",
|
|
2388
|
+
"0x3956c25bf348b538",
|
|
2389
|
+
"0x59f111f1b605d019",
|
|
2390
|
+
"0x923f82a4af194f9b",
|
|
2391
|
+
"0xab1c5ed5da6d8118",
|
|
2392
|
+
"0xd807aa98a3030242",
|
|
2393
|
+
"0x12835b0145706fbe",
|
|
2394
|
+
"0x243185be4ee4b28c",
|
|
2395
|
+
"0x550c7dc3d5ffb4e2",
|
|
2396
|
+
"0x72be5d74f27b896f",
|
|
2397
|
+
"0x80deb1fe3b1696b1",
|
|
2398
|
+
"0x9bdc06a725c71235",
|
|
2399
|
+
"0xc19bf174cf692694",
|
|
2400
|
+
"0xe49b69c19ef14ad2",
|
|
2401
|
+
"0xefbe4786384f25e3",
|
|
2402
|
+
"0x0fc19dc68b8cd5b5",
|
|
2403
|
+
"0x240ca1cc77ac9c65",
|
|
2404
|
+
"0x2de92c6f592b0275",
|
|
2405
|
+
"0x4a7484aa6ea6e483",
|
|
2406
|
+
"0x5cb0a9dcbd41fbd4",
|
|
2407
|
+
"0x76f988da831153b5",
|
|
2408
|
+
"0x983e5152ee66dfab",
|
|
2409
|
+
"0xa831c66d2db43210",
|
|
2410
|
+
"0xb00327c898fb213f",
|
|
2411
|
+
"0xbf597fc7beef0ee4",
|
|
2412
|
+
"0xc6e00bf33da88fc2",
|
|
2413
|
+
"0xd5a79147930aa725",
|
|
2414
|
+
"0x06ca6351e003826f",
|
|
2415
|
+
"0x142929670a0e6e70",
|
|
2416
|
+
"0x27b70a8546d22ffc",
|
|
2417
|
+
"0x2e1b21385c26c926",
|
|
2418
|
+
"0x4d2c6dfc5ac42aed",
|
|
2419
|
+
"0x53380d139d95b3df",
|
|
2420
|
+
"0x650a73548baf63de",
|
|
2421
|
+
"0x766a0abb3c77b2a8",
|
|
2422
|
+
"0x81c2c92e47edaee6",
|
|
2423
|
+
"0x92722c851482353b",
|
|
2424
|
+
"0xa2bfe8a14cf10364",
|
|
2425
|
+
"0xa81a664bbc423001",
|
|
2426
|
+
"0xc24b8b70d0f89791",
|
|
2427
|
+
"0xc76c51a30654be30",
|
|
2428
|
+
"0xd192e819d6ef5218",
|
|
2429
|
+
"0xd69906245565a910",
|
|
2430
|
+
"0xf40e35855771202a",
|
|
2431
|
+
"0x106aa07032bbd1b8",
|
|
2432
|
+
"0x19a4c116b8d2d0c8",
|
|
2433
|
+
"0x1e376c085141ab53",
|
|
2434
|
+
"0x2748774cdf8eeb99",
|
|
2435
|
+
"0x34b0bcb5e19b48a8",
|
|
2436
|
+
"0x391c0cb3c5c95a63",
|
|
2437
|
+
"0x4ed8aa4ae3418acb",
|
|
2438
|
+
"0x5b9cca4f7763e373",
|
|
2439
|
+
"0x682e6ff3d6b2b8a3",
|
|
2440
|
+
"0x748f82ee5defb2fc",
|
|
2441
|
+
"0x78a5636f43172f60",
|
|
2442
|
+
"0x84c87814a1f0ab72",
|
|
2443
|
+
"0x8cc702081a6439ec",
|
|
2444
|
+
"0x90befffa23631e28",
|
|
2445
|
+
"0xa4506cebde82bde9",
|
|
2446
|
+
"0xbef9a3f7b2c67915",
|
|
2447
|
+
"0xc67178f2e372532b",
|
|
2448
|
+
"0xca273eceea26619c",
|
|
2449
|
+
"0xd186b8c721c0c207",
|
|
2450
|
+
"0xeada7dd6cde0eb1e",
|
|
2451
|
+
"0xf57d4f7fee6ed178",
|
|
2452
|
+
"0x06f067aa72176fba",
|
|
2453
|
+
"0x0a637dc5a2c898a6",
|
|
2454
|
+
"0x113f9804bef90dae",
|
|
2455
|
+
"0x1b710b35131c471b",
|
|
2456
|
+
"0x28db77f523047d84",
|
|
2457
|
+
"0x32caab7b40c72493",
|
|
2458
|
+
"0x3c9ebe0a15c9bebc",
|
|
2459
|
+
"0x431d67c49c100d4c",
|
|
2460
|
+
"0x4cc5d4becb3e42b6",
|
|
2461
|
+
"0x597f299cfc657e2a",
|
|
2462
|
+
"0x5fcb6fab3ad6faec",
|
|
2463
|
+
"0x6c44198c4a475817"
|
|
2464
|
+
].map((n) => BigInt(n))))();
|
|
2465
|
+
var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
|
|
2466
|
+
var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
|
|
2467
|
+
var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
|
|
2468
|
+
var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
|
|
2469
|
+
var SHA512 = class extends HashMD {
|
|
2470
|
+
constructor(outputLen = 64) {
|
|
2471
|
+
super(128, outputLen, 16, false);
|
|
2472
|
+
this.Ah = SHA512_IV[0] | 0;
|
|
2473
|
+
this.Al = SHA512_IV[1] | 0;
|
|
2474
|
+
this.Bh = SHA512_IV[2] | 0;
|
|
2475
|
+
this.Bl = SHA512_IV[3] | 0;
|
|
2476
|
+
this.Ch = SHA512_IV[4] | 0;
|
|
2477
|
+
this.Cl = SHA512_IV[5] | 0;
|
|
2478
|
+
this.Dh = SHA512_IV[6] | 0;
|
|
2479
|
+
this.Dl = SHA512_IV[7] | 0;
|
|
2480
|
+
this.Eh = SHA512_IV[8] | 0;
|
|
2481
|
+
this.El = SHA512_IV[9] | 0;
|
|
2482
|
+
this.Fh = SHA512_IV[10] | 0;
|
|
2483
|
+
this.Fl = SHA512_IV[11] | 0;
|
|
2484
|
+
this.Gh = SHA512_IV[12] | 0;
|
|
2485
|
+
this.Gl = SHA512_IV[13] | 0;
|
|
2486
|
+
this.Hh = SHA512_IV[14] | 0;
|
|
2487
|
+
this.Hl = SHA512_IV[15] | 0;
|
|
2488
|
+
}
|
|
2489
|
+
// prettier-ignore
|
|
2490
|
+
get() {
|
|
2491
|
+
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
|
|
2492
|
+
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
|
|
2493
|
+
}
|
|
2494
|
+
// prettier-ignore
|
|
2495
|
+
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
|
|
2496
|
+
this.Ah = Ah | 0;
|
|
2497
|
+
this.Al = Al | 0;
|
|
2498
|
+
this.Bh = Bh | 0;
|
|
2499
|
+
this.Bl = Bl | 0;
|
|
2500
|
+
this.Ch = Ch | 0;
|
|
2501
|
+
this.Cl = Cl | 0;
|
|
2502
|
+
this.Dh = Dh | 0;
|
|
2503
|
+
this.Dl = Dl | 0;
|
|
2504
|
+
this.Eh = Eh | 0;
|
|
2505
|
+
this.El = El | 0;
|
|
2506
|
+
this.Fh = Fh | 0;
|
|
2507
|
+
this.Fl = Fl | 0;
|
|
2508
|
+
this.Gh = Gh | 0;
|
|
2509
|
+
this.Gl = Gl | 0;
|
|
2510
|
+
this.Hh = Hh | 0;
|
|
2511
|
+
this.Hl = Hl | 0;
|
|
2512
|
+
}
|
|
2513
|
+
process(view, offset) {
|
|
2514
|
+
for (let i = 0; i < 16; i++, offset += 4) {
|
|
2515
|
+
SHA512_W_H[i] = view.getUint32(offset);
|
|
2516
|
+
SHA512_W_L[i] = view.getUint32(offset += 4);
|
|
2517
|
+
}
|
|
2518
|
+
for (let i = 16; i < 80; i++) {
|
|
2519
|
+
const W15h = SHA512_W_H[i - 15] | 0;
|
|
2520
|
+
const W15l = SHA512_W_L[i - 15] | 0;
|
|
2521
|
+
const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
|
|
2522
|
+
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
|
|
2523
|
+
const W2h = SHA512_W_H[i - 2] | 0;
|
|
2524
|
+
const W2l = SHA512_W_L[i - 2] | 0;
|
|
2525
|
+
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
|
|
2526
|
+
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
|
|
2527
|
+
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
|
|
2528
|
+
const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
|
|
2529
|
+
SHA512_W_H[i] = SUMh | 0;
|
|
2530
|
+
SHA512_W_L[i] = SUMl | 0;
|
|
2531
|
+
}
|
|
2532
|
+
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
|
|
2533
|
+
for (let i = 0; i < 80; i++) {
|
|
2534
|
+
const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
|
|
2535
|
+
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
|
|
2536
|
+
const CHIh = Eh & Fh ^ ~Eh & Gh;
|
|
2537
|
+
const CHIl = El & Fl ^ ~El & Gl;
|
|
2538
|
+
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
|
|
2539
|
+
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
|
|
2540
|
+
const T1l = T1ll | 0;
|
|
2541
|
+
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
|
|
2542
|
+
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
|
|
2543
|
+
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
|
|
2544
|
+
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
|
|
2545
|
+
Hh = Gh | 0;
|
|
2546
|
+
Hl = Gl | 0;
|
|
2547
|
+
Gh = Fh | 0;
|
|
2548
|
+
Gl = Fl | 0;
|
|
2549
|
+
Fh = Eh | 0;
|
|
2550
|
+
Fl = El | 0;
|
|
2551
|
+
({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
|
|
2552
|
+
Dh = Ch | 0;
|
|
2553
|
+
Dl = Cl | 0;
|
|
2554
|
+
Ch = Bh | 0;
|
|
2555
|
+
Cl = Bl | 0;
|
|
2556
|
+
Bh = Ah | 0;
|
|
2557
|
+
Bl = Al | 0;
|
|
2558
|
+
const All = add3L(T1l, sigma0l, MAJl);
|
|
2559
|
+
Ah = add3H(All, T1h, sigma0h, MAJh);
|
|
2560
|
+
Al = All | 0;
|
|
2561
|
+
}
|
|
2562
|
+
({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
|
|
2563
|
+
({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
|
|
2564
|
+
({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
|
|
2565
|
+
({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
|
|
2566
|
+
({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
|
|
2567
|
+
({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
|
|
2568
|
+
({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
|
|
2569
|
+
({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
|
|
2570
|
+
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
|
|
2571
|
+
}
|
|
2572
|
+
roundClean() {
|
|
2573
|
+
clean2(SHA512_W_H, SHA512_W_L);
|
|
2574
|
+
}
|
|
2575
|
+
destroy() {
|
|
2576
|
+
clean2(this.buffer);
|
|
2577
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
|
|
2578
|
+
}
|
|
2579
|
+
};
|
|
2580
|
+
var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
|
|
2581
|
+
var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
|
|
2582
|
+
|
|
2583
|
+
// node_modules/@noble/hashes/esm/hmac.js
|
|
2584
|
+
var HMAC = class extends Hash {
|
|
2585
|
+
constructor(hash, _key) {
|
|
2586
|
+
super();
|
|
2587
|
+
this.finished = false;
|
|
2588
|
+
this.destroyed = false;
|
|
2589
|
+
ahash(hash);
|
|
2590
|
+
const key = toBytes(_key);
|
|
2591
|
+
this.iHash = hash.create();
|
|
2592
|
+
if (typeof this.iHash.update !== "function")
|
|
2593
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
2594
|
+
this.blockLen = this.iHash.blockLen;
|
|
2595
|
+
this.outputLen = this.iHash.outputLen;
|
|
2596
|
+
const blockLen = this.blockLen;
|
|
2597
|
+
const pad = new Uint8Array(blockLen);
|
|
2598
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
2599
|
+
for (let i = 0; i < pad.length; i++)
|
|
2600
|
+
pad[i] ^= 54;
|
|
2601
|
+
this.iHash.update(pad);
|
|
2602
|
+
this.oHash = hash.create();
|
|
2603
|
+
for (let i = 0; i < pad.length; i++)
|
|
2604
|
+
pad[i] ^= 54 ^ 92;
|
|
2605
|
+
this.oHash.update(pad);
|
|
2606
|
+
clean2(pad);
|
|
2607
|
+
}
|
|
2608
|
+
update(buf) {
|
|
2609
|
+
aexists(this);
|
|
2610
|
+
this.iHash.update(buf);
|
|
2611
|
+
return this;
|
|
2612
|
+
}
|
|
2613
|
+
digestInto(out) {
|
|
2614
|
+
aexists(this);
|
|
2615
|
+
abytes2(out, this.outputLen);
|
|
2616
|
+
this.finished = true;
|
|
2617
|
+
this.iHash.digestInto(out);
|
|
2618
|
+
this.oHash.update(out);
|
|
2619
|
+
this.oHash.digestInto(out);
|
|
2620
|
+
this.destroy();
|
|
2621
|
+
}
|
|
2622
|
+
digest() {
|
|
2623
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
2624
|
+
this.digestInto(out);
|
|
2625
|
+
return out;
|
|
2626
|
+
}
|
|
2627
|
+
_cloneInto(to) {
|
|
2628
|
+
to || (to = Object.create(Object.getPrototypeOf(this), {}));
|
|
2629
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
2630
|
+
to = to;
|
|
2631
|
+
to.finished = finished;
|
|
2632
|
+
to.destroyed = destroyed;
|
|
2633
|
+
to.blockLen = blockLen;
|
|
2634
|
+
to.outputLen = outputLen;
|
|
2635
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
2636
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
2637
|
+
return to;
|
|
2638
|
+
}
|
|
2639
|
+
clone() {
|
|
2640
|
+
return this._cloneInto();
|
|
2641
|
+
}
|
|
2642
|
+
destroy() {
|
|
2643
|
+
this.destroyed = true;
|
|
2644
|
+
this.oHash.destroy();
|
|
2645
|
+
this.iHash.destroy();
|
|
2646
|
+
}
|
|
2647
|
+
};
|
|
2648
|
+
var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
|
|
2649
|
+
hmac.create = (hash, key) => new HMAC(hash, key);
|
|
2650
|
+
|
|
2651
|
+
// node_modules/@noble/curves/esm/abstract/utils.js
|
|
2652
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
2653
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
2654
|
+
function isBytes3(a) {
|
|
2655
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
2656
|
+
}
|
|
2657
|
+
function abytes3(item) {
|
|
2658
|
+
if (!isBytes3(item))
|
|
2659
|
+
throw new Error("Uint8Array expected");
|
|
2660
|
+
}
|
|
2661
|
+
function abool(title, value) {
|
|
2662
|
+
if (typeof value !== "boolean")
|
|
2663
|
+
throw new Error(title + " boolean expected, got " + value);
|
|
2664
|
+
}
|
|
2665
|
+
function numberToHexUnpadded(num) {
|
|
2666
|
+
const hex = num.toString(16);
|
|
2667
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
2668
|
+
}
|
|
2669
|
+
function hexToNumber(hex) {
|
|
2670
|
+
if (typeof hex !== "string")
|
|
2671
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
2672
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
2673
|
+
}
|
|
2674
|
+
var hasHexBuiltin = (
|
|
2675
|
+
// @ts-ignore
|
|
2676
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
2677
|
+
);
|
|
2678
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
2679
|
+
function bytesToHex(bytes) {
|
|
2680
|
+
abytes3(bytes);
|
|
2681
|
+
if (hasHexBuiltin)
|
|
2682
|
+
return bytes.toHex();
|
|
2683
|
+
let hex = "";
|
|
2684
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
2685
|
+
hex += hexes[bytes[i]];
|
|
2686
|
+
}
|
|
2687
|
+
return hex;
|
|
2688
|
+
}
|
|
2689
|
+
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
2690
|
+
function asciiToBase16(ch) {
|
|
2691
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
2692
|
+
return ch - asciis._0;
|
|
2693
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
2694
|
+
return ch - (asciis.A - 10);
|
|
2695
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
2696
|
+
return ch - (asciis.a - 10);
|
|
2697
|
+
return;
|
|
2698
|
+
}
|
|
2699
|
+
function hexToBytes2(hex) {
|
|
2700
|
+
if (typeof hex !== "string")
|
|
2701
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
2702
|
+
if (hasHexBuiltin)
|
|
2703
|
+
return Uint8Array.fromHex(hex);
|
|
2704
|
+
const hl = hex.length;
|
|
2705
|
+
const al = hl / 2;
|
|
2706
|
+
if (hl % 2)
|
|
2707
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
2708
|
+
const array = new Uint8Array(al);
|
|
2709
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
2710
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
2711
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
2712
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
2713
|
+
const char = hex[hi] + hex[hi + 1];
|
|
2714
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
2715
|
+
}
|
|
2716
|
+
array[ai] = n1 * 16 + n2;
|
|
2717
|
+
}
|
|
2718
|
+
return array;
|
|
2719
|
+
}
|
|
2720
|
+
function bytesToNumberBE(bytes) {
|
|
2721
|
+
return hexToNumber(bytesToHex(bytes));
|
|
2722
|
+
}
|
|
2723
|
+
function bytesToNumberLE(bytes) {
|
|
2724
|
+
abytes3(bytes);
|
|
2725
|
+
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
|
|
2726
|
+
}
|
|
2727
|
+
function numberToBytesBE(n, len) {
|
|
2728
|
+
return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
2729
|
+
}
|
|
2730
|
+
function numberToBytesLE(n, len) {
|
|
2731
|
+
return numberToBytesBE(n, len).reverse();
|
|
2732
|
+
}
|
|
2733
|
+
function ensureBytes(title, hex, expectedLength) {
|
|
2734
|
+
let res;
|
|
2735
|
+
if (typeof hex === "string") {
|
|
2736
|
+
try {
|
|
2737
|
+
res = hexToBytes2(hex);
|
|
2738
|
+
} catch (e) {
|
|
2739
|
+
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
|
|
2740
|
+
}
|
|
2741
|
+
} else if (isBytes3(hex)) {
|
|
2742
|
+
res = Uint8Array.from(hex);
|
|
2743
|
+
} else {
|
|
2744
|
+
throw new Error(title + " must be hex string or Uint8Array");
|
|
2745
|
+
}
|
|
2746
|
+
const len = res.length;
|
|
2747
|
+
if (typeof expectedLength === "number" && len !== expectedLength)
|
|
2748
|
+
throw new Error(title + " of length " + expectedLength + " expected, got " + len);
|
|
2749
|
+
return res;
|
|
2750
|
+
}
|
|
2751
|
+
function concatBytes3(...arrays) {
|
|
2752
|
+
let sum = 0;
|
|
2753
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
2754
|
+
const a = arrays[i];
|
|
2755
|
+
abytes3(a);
|
|
2756
|
+
sum += a.length;
|
|
2757
|
+
}
|
|
2758
|
+
const res = new Uint8Array(sum);
|
|
2759
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
2760
|
+
const a = arrays[i];
|
|
2761
|
+
res.set(a, pad);
|
|
2762
|
+
pad += a.length;
|
|
2763
|
+
}
|
|
2764
|
+
return res;
|
|
2765
|
+
}
|
|
2766
|
+
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
2767
|
+
function inRange(n, min, max) {
|
|
2768
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
2769
|
+
}
|
|
2770
|
+
function aInRange(title, n, min, max) {
|
|
2771
|
+
if (!inRange(n, min, max))
|
|
2772
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
2773
|
+
}
|
|
2774
|
+
function bitLen(n) {
|
|
2775
|
+
let len;
|
|
2776
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
2777
|
+
;
|
|
2778
|
+
return len;
|
|
2779
|
+
}
|
|
2780
|
+
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
2781
|
+
var u8n = (len) => new Uint8Array(len);
|
|
2782
|
+
var u8fr = (arr) => Uint8Array.from(arr);
|
|
2783
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
2784
|
+
if (typeof hashLen !== "number" || hashLen < 2)
|
|
2785
|
+
throw new Error("hashLen must be a number");
|
|
2786
|
+
if (typeof qByteLen !== "number" || qByteLen < 2)
|
|
2787
|
+
throw new Error("qByteLen must be a number");
|
|
2788
|
+
if (typeof hmacFn !== "function")
|
|
2789
|
+
throw new Error("hmacFn must be a function");
|
|
2790
|
+
let v = u8n(hashLen);
|
|
2791
|
+
let k = u8n(hashLen);
|
|
2792
|
+
let i = 0;
|
|
2793
|
+
const reset = () => {
|
|
2794
|
+
v.fill(1);
|
|
2795
|
+
k.fill(0);
|
|
2796
|
+
i = 0;
|
|
2797
|
+
};
|
|
2798
|
+
const h = (...b) => hmacFn(k, v, ...b);
|
|
2799
|
+
const reseed = (seed = u8n(0)) => {
|
|
2800
|
+
k = h(u8fr([0]), seed);
|
|
2801
|
+
v = h();
|
|
2802
|
+
if (seed.length === 0)
|
|
2803
|
+
return;
|
|
2804
|
+
k = h(u8fr([1]), seed);
|
|
2805
|
+
v = h();
|
|
2806
|
+
};
|
|
2807
|
+
const gen = () => {
|
|
2808
|
+
if (i++ >= 1e3)
|
|
2809
|
+
throw new Error("drbg: tried 1000 values");
|
|
2810
|
+
let len = 0;
|
|
2811
|
+
const out = [];
|
|
2812
|
+
while (len < qByteLen) {
|
|
2813
|
+
v = h();
|
|
2814
|
+
const sl = v.slice();
|
|
2815
|
+
out.push(sl);
|
|
2816
|
+
len += v.length;
|
|
2817
|
+
}
|
|
2818
|
+
return concatBytes3(...out);
|
|
2819
|
+
};
|
|
2820
|
+
const genUntil = (seed, pred) => {
|
|
2821
|
+
reset();
|
|
2822
|
+
reseed(seed);
|
|
2823
|
+
let res = void 0;
|
|
2824
|
+
while (!(res = pred(gen())))
|
|
2825
|
+
reseed();
|
|
2826
|
+
reset();
|
|
2827
|
+
return res;
|
|
2828
|
+
};
|
|
2829
|
+
return genUntil;
|
|
2830
|
+
}
|
|
2831
|
+
var validatorFns = {
|
|
2832
|
+
bigint: (val) => typeof val === "bigint",
|
|
2833
|
+
function: (val) => typeof val === "function",
|
|
2834
|
+
boolean: (val) => typeof val === "boolean",
|
|
2835
|
+
string: (val) => typeof val === "string",
|
|
2836
|
+
stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val),
|
|
2837
|
+
isSafeInteger: (val) => Number.isSafeInteger(val),
|
|
2838
|
+
array: (val) => Array.isArray(val),
|
|
2839
|
+
field: (val, object) => object.Fp.isValid(val),
|
|
2840
|
+
hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
|
|
2841
|
+
};
|
|
2842
|
+
function validateObject(object, validators, optValidators = {}) {
|
|
2843
|
+
const checkField = (fieldName, type, isOptional) => {
|
|
2844
|
+
const checkVal = validatorFns[type];
|
|
2845
|
+
if (typeof checkVal !== "function")
|
|
2846
|
+
throw new Error("invalid validator function");
|
|
2847
|
+
const val = object[fieldName];
|
|
2848
|
+
if (isOptional && val === void 0)
|
|
2849
|
+
return;
|
|
2850
|
+
if (!checkVal(val, object)) {
|
|
2851
|
+
throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
|
|
2852
|
+
}
|
|
2853
|
+
};
|
|
2854
|
+
for (const [fieldName, type] of Object.entries(validators))
|
|
2855
|
+
checkField(fieldName, type, false);
|
|
2856
|
+
for (const [fieldName, type] of Object.entries(optValidators))
|
|
2857
|
+
checkField(fieldName, type, true);
|
|
2858
|
+
return object;
|
|
2859
|
+
}
|
|
2860
|
+
function memoized(fn) {
|
|
2861
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
2862
|
+
return (arg, ...args) => {
|
|
2863
|
+
const val = map.get(arg);
|
|
2864
|
+
if (val !== void 0)
|
|
2865
|
+
return val;
|
|
2866
|
+
const computed = fn(arg, ...args);
|
|
2867
|
+
map.set(arg, computed);
|
|
2868
|
+
return computed;
|
|
2869
|
+
};
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
// node_modules/@noble/curves/esm/abstract/modular.js
|
|
2873
|
+
var _0n2 = BigInt(0);
|
|
2874
|
+
var _1n2 = BigInt(1);
|
|
2875
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
2876
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
2877
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
2878
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
2879
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
2880
|
+
function mod(a, b) {
|
|
2881
|
+
const result = a % b;
|
|
2882
|
+
return result >= _0n2 ? result : b + result;
|
|
2883
|
+
}
|
|
2884
|
+
function pow2(x, power, modulo) {
|
|
2885
|
+
let res = x;
|
|
2886
|
+
while (power-- > _0n2) {
|
|
2887
|
+
res *= res;
|
|
2888
|
+
res %= modulo;
|
|
2889
|
+
}
|
|
2890
|
+
return res;
|
|
2891
|
+
}
|
|
2892
|
+
function invert(number, modulo) {
|
|
2893
|
+
if (number === _0n2)
|
|
2894
|
+
throw new Error("invert: expected non-zero number");
|
|
2895
|
+
if (modulo <= _0n2)
|
|
2896
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
2897
|
+
let a = mod(number, modulo);
|
|
2898
|
+
let b = modulo;
|
|
2899
|
+
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
2900
|
+
while (a !== _0n2) {
|
|
2901
|
+
const q = b / a;
|
|
2902
|
+
const r = b % a;
|
|
2903
|
+
const m = x - u * q;
|
|
2904
|
+
const n = y - v * q;
|
|
2905
|
+
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
2906
|
+
}
|
|
2907
|
+
const gcd = b;
|
|
2908
|
+
if (gcd !== _1n2)
|
|
2909
|
+
throw new Error("invert: does not exist");
|
|
2910
|
+
return mod(x, modulo);
|
|
2911
|
+
}
|
|
2912
|
+
function sqrt3mod4(Fp, n) {
|
|
2913
|
+
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
2914
|
+
const root = Fp.pow(n, p1div4);
|
|
2915
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
2916
|
+
throw new Error("Cannot find square root");
|
|
2917
|
+
return root;
|
|
2918
|
+
}
|
|
2919
|
+
function sqrt5mod8(Fp, n) {
|
|
2920
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
2921
|
+
const n2 = Fp.mul(n, _2n);
|
|
2922
|
+
const v = Fp.pow(n2, p5div8);
|
|
2923
|
+
const nv = Fp.mul(n, v);
|
|
2924
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
2925
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
2926
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
2927
|
+
throw new Error("Cannot find square root");
|
|
2928
|
+
return root;
|
|
2929
|
+
}
|
|
2930
|
+
function tonelliShanks(P) {
|
|
2931
|
+
if (P < BigInt(3))
|
|
2932
|
+
throw new Error("sqrt is not defined for small field");
|
|
2933
|
+
let Q = P - _1n2;
|
|
2934
|
+
let S = 0;
|
|
2935
|
+
while (Q % _2n === _0n2) {
|
|
2936
|
+
Q /= _2n;
|
|
2937
|
+
S++;
|
|
2938
|
+
}
|
|
2939
|
+
let Z = _2n;
|
|
2940
|
+
const _Fp = Field(P);
|
|
2941
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
2942
|
+
if (Z++ > 1e3)
|
|
2943
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
2944
|
+
}
|
|
2945
|
+
if (S === 1)
|
|
2946
|
+
return sqrt3mod4;
|
|
2947
|
+
let cc = _Fp.pow(Z, Q);
|
|
2948
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
2949
|
+
return function tonelliSlow(Fp, n) {
|
|
2950
|
+
if (Fp.is0(n))
|
|
2951
|
+
return n;
|
|
2952
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
2953
|
+
throw new Error("Cannot find square root");
|
|
2954
|
+
let M = S;
|
|
2955
|
+
let c = Fp.mul(Fp.ONE, cc);
|
|
2956
|
+
let t = Fp.pow(n, Q);
|
|
2957
|
+
let R = Fp.pow(n, Q1div2);
|
|
2958
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
2959
|
+
if (Fp.is0(t))
|
|
2960
|
+
return Fp.ZERO;
|
|
2961
|
+
let i = 1;
|
|
2962
|
+
let t_tmp = Fp.sqr(t);
|
|
2963
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
2964
|
+
i++;
|
|
2965
|
+
t_tmp = Fp.sqr(t_tmp);
|
|
2966
|
+
if (i === M)
|
|
2967
|
+
throw new Error("Cannot find square root");
|
|
2968
|
+
}
|
|
2969
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
2970
|
+
const b = Fp.pow(c, exponent);
|
|
2971
|
+
M = i;
|
|
2972
|
+
c = Fp.sqr(b);
|
|
2973
|
+
t = Fp.mul(t, c);
|
|
2974
|
+
R = Fp.mul(R, b);
|
|
2975
|
+
}
|
|
2976
|
+
return R;
|
|
2977
|
+
};
|
|
2978
|
+
}
|
|
2979
|
+
function FpSqrt(P) {
|
|
2980
|
+
if (P % _4n === _3n)
|
|
2981
|
+
return sqrt3mod4;
|
|
2982
|
+
if (P % _8n === _5n)
|
|
2983
|
+
return sqrt5mod8;
|
|
2984
|
+
return tonelliShanks(P);
|
|
2985
|
+
}
|
|
2986
|
+
var FIELD_FIELDS = [
|
|
2987
|
+
"create",
|
|
2988
|
+
"isValid",
|
|
2989
|
+
"is0",
|
|
2990
|
+
"neg",
|
|
2991
|
+
"inv",
|
|
2992
|
+
"sqrt",
|
|
2993
|
+
"sqr",
|
|
2994
|
+
"eql",
|
|
2995
|
+
"add",
|
|
2996
|
+
"sub",
|
|
2997
|
+
"mul",
|
|
2998
|
+
"pow",
|
|
2999
|
+
"div",
|
|
3000
|
+
"addN",
|
|
3001
|
+
"subN",
|
|
3002
|
+
"mulN",
|
|
3003
|
+
"sqrN"
|
|
3004
|
+
];
|
|
3005
|
+
function validateField(field) {
|
|
3006
|
+
const initial = {
|
|
3007
|
+
ORDER: "bigint",
|
|
3008
|
+
MASK: "bigint",
|
|
3009
|
+
BYTES: "isSafeInteger",
|
|
3010
|
+
BITS: "isSafeInteger"
|
|
3011
|
+
};
|
|
3012
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
3013
|
+
map[val] = "function";
|
|
3014
|
+
return map;
|
|
3015
|
+
}, initial);
|
|
3016
|
+
return validateObject(field, opts);
|
|
3017
|
+
}
|
|
3018
|
+
function FpPow(Fp, num, power) {
|
|
3019
|
+
if (power < _0n2)
|
|
3020
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
3021
|
+
if (power === _0n2)
|
|
3022
|
+
return Fp.ONE;
|
|
3023
|
+
if (power === _1n2)
|
|
3024
|
+
return num;
|
|
3025
|
+
let p = Fp.ONE;
|
|
3026
|
+
let d = num;
|
|
3027
|
+
while (power > _0n2) {
|
|
3028
|
+
if (power & _1n2)
|
|
3029
|
+
p = Fp.mul(p, d);
|
|
3030
|
+
d = Fp.sqr(d);
|
|
3031
|
+
power >>= _1n2;
|
|
3032
|
+
}
|
|
3033
|
+
return p;
|
|
3034
|
+
}
|
|
3035
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
3036
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
3037
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
3038
|
+
if (Fp.is0(num))
|
|
3039
|
+
return acc;
|
|
3040
|
+
inverted[i] = acc;
|
|
3041
|
+
return Fp.mul(acc, num);
|
|
3042
|
+
}, Fp.ONE);
|
|
3043
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
3044
|
+
nums.reduceRight((acc, num, i) => {
|
|
3045
|
+
if (Fp.is0(num))
|
|
3046
|
+
return acc;
|
|
3047
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
3048
|
+
return Fp.mul(acc, num);
|
|
3049
|
+
}, invertedAcc);
|
|
3050
|
+
return inverted;
|
|
3051
|
+
}
|
|
3052
|
+
function FpLegendre(Fp, n) {
|
|
3053
|
+
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
3054
|
+
const powered = Fp.pow(n, p1mod2);
|
|
3055
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
3056
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
3057
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
3058
|
+
if (!yes && !zero && !no)
|
|
3059
|
+
throw new Error("invalid Legendre symbol result");
|
|
3060
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
3061
|
+
}
|
|
3062
|
+
function nLength(n, nBitLength) {
|
|
3063
|
+
if (nBitLength !== void 0)
|
|
3064
|
+
anumber(nBitLength);
|
|
3065
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
3066
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
3067
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
3068
|
+
}
|
|
3069
|
+
function Field(ORDER, bitLen2, isLE2 = false, redef = {}) {
|
|
3070
|
+
if (ORDER <= _0n2)
|
|
3071
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
3072
|
+
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2);
|
|
3073
|
+
if (BYTES > 2048)
|
|
3074
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
3075
|
+
let sqrtP;
|
|
3076
|
+
const f = Object.freeze({
|
|
3077
|
+
ORDER,
|
|
3078
|
+
isLE: isLE2,
|
|
3079
|
+
BITS,
|
|
3080
|
+
BYTES,
|
|
3081
|
+
MASK: bitMask(BITS),
|
|
3082
|
+
ZERO: _0n2,
|
|
3083
|
+
ONE: _1n2,
|
|
3084
|
+
create: (num) => mod(num, ORDER),
|
|
3085
|
+
isValid: (num) => {
|
|
3086
|
+
if (typeof num !== "bigint")
|
|
3087
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
3088
|
+
return _0n2 <= num && num < ORDER;
|
|
3089
|
+
},
|
|
3090
|
+
is0: (num) => num === _0n2,
|
|
3091
|
+
isOdd: (num) => (num & _1n2) === _1n2,
|
|
3092
|
+
neg: (num) => mod(-num, ORDER),
|
|
3093
|
+
eql: (lhs, rhs) => lhs === rhs,
|
|
3094
|
+
sqr: (num) => mod(num * num, ORDER),
|
|
3095
|
+
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
|
|
3096
|
+
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
|
|
3097
|
+
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
|
|
3098
|
+
pow: (num, power) => FpPow(f, num, power),
|
|
3099
|
+
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
|
|
3100
|
+
// Same as above, but doesn't normalize
|
|
3101
|
+
sqrN: (num) => num * num,
|
|
3102
|
+
addN: (lhs, rhs) => lhs + rhs,
|
|
3103
|
+
subN: (lhs, rhs) => lhs - rhs,
|
|
3104
|
+
mulN: (lhs, rhs) => lhs * rhs,
|
|
3105
|
+
inv: (num) => invert(num, ORDER),
|
|
3106
|
+
sqrt: redef.sqrt || ((n) => {
|
|
3107
|
+
if (!sqrtP)
|
|
3108
|
+
sqrtP = FpSqrt(ORDER);
|
|
3109
|
+
return sqrtP(f, n);
|
|
3110
|
+
}),
|
|
3111
|
+
toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
|
|
3112
|
+
fromBytes: (bytes) => {
|
|
3113
|
+
if (bytes.length !== BYTES)
|
|
3114
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
3115
|
+
return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
3116
|
+
},
|
|
3117
|
+
// TODO: we don't need it here, move out to separate fn
|
|
3118
|
+
invertBatch: (lst) => FpInvertBatch(f, lst),
|
|
3119
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
3120
|
+
// and it's unclear what to return in there.
|
|
3121
|
+
cmov: (a, b, c) => c ? b : a
|
|
3122
|
+
});
|
|
3123
|
+
return Object.freeze(f);
|
|
3124
|
+
}
|
|
3125
|
+
function getFieldBytesLength(fieldOrder) {
|
|
3126
|
+
if (typeof fieldOrder !== "bigint")
|
|
3127
|
+
throw new Error("field order must be bigint");
|
|
3128
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
3129
|
+
return Math.ceil(bitLength / 8);
|
|
3130
|
+
}
|
|
3131
|
+
function getMinHashLength(fieldOrder) {
|
|
3132
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
3133
|
+
return length + Math.ceil(length / 2);
|
|
3134
|
+
}
|
|
3135
|
+
function mapHashToField(key, fieldOrder, isLE2 = false) {
|
|
3136
|
+
const len = key.length;
|
|
3137
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
3138
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
3139
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
3140
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
3141
|
+
const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
3142
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
3143
|
+
return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
// node_modules/@noble/curves/esm/abstract/curve.js
|
|
3147
|
+
var _0n3 = BigInt(0);
|
|
3148
|
+
var _1n3 = BigInt(1);
|
|
3149
|
+
function constTimeNegate(condition, item) {
|
|
3150
|
+
const neg = item.negate();
|
|
3151
|
+
return condition ? neg : item;
|
|
3152
|
+
}
|
|
3153
|
+
function validateW(W, bits) {
|
|
3154
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
3155
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
3156
|
+
}
|
|
3157
|
+
function calcWOpts(W, scalarBits) {
|
|
3158
|
+
validateW(W, scalarBits);
|
|
3159
|
+
const windows = Math.ceil(scalarBits / W) + 1;
|
|
3160
|
+
const windowSize = 2 ** (W - 1);
|
|
3161
|
+
const maxNumber = 2 ** W;
|
|
3162
|
+
const mask = bitMask(W);
|
|
3163
|
+
const shiftBy = BigInt(W);
|
|
3164
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
3165
|
+
}
|
|
3166
|
+
function calcOffsets(n, window2, wOpts) {
|
|
3167
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
3168
|
+
let wbits = Number(n & mask);
|
|
3169
|
+
let nextN = n >> shiftBy;
|
|
3170
|
+
if (wbits > windowSize) {
|
|
3171
|
+
wbits -= maxNumber;
|
|
3172
|
+
nextN += _1n3;
|
|
3173
|
+
}
|
|
3174
|
+
const offsetStart = window2 * windowSize;
|
|
3175
|
+
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
3176
|
+
const isZero = wbits === 0;
|
|
3177
|
+
const isNeg = wbits < 0;
|
|
3178
|
+
const isNegF = window2 % 2 !== 0;
|
|
3179
|
+
const offsetF = offsetStart;
|
|
3180
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
3181
|
+
}
|
|
3182
|
+
function validateMSMPoints(points, c) {
|
|
3183
|
+
if (!Array.isArray(points))
|
|
3184
|
+
throw new Error("array expected");
|
|
3185
|
+
points.forEach((p, i) => {
|
|
3186
|
+
if (!(p instanceof c))
|
|
3187
|
+
throw new Error("invalid point at index " + i);
|
|
3188
|
+
});
|
|
3189
|
+
}
|
|
3190
|
+
function validateMSMScalars(scalars, field) {
|
|
3191
|
+
if (!Array.isArray(scalars))
|
|
3192
|
+
throw new Error("array of scalars expected");
|
|
3193
|
+
scalars.forEach((s, i) => {
|
|
3194
|
+
if (!field.isValid(s))
|
|
3195
|
+
throw new Error("invalid scalar at index " + i);
|
|
3196
|
+
});
|
|
3197
|
+
}
|
|
3198
|
+
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
3199
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
3200
|
+
function getW(P) {
|
|
3201
|
+
return pointWindowSizes.get(P) || 1;
|
|
3202
|
+
}
|
|
3203
|
+
function wNAF(c, bits) {
|
|
3204
|
+
return {
|
|
3205
|
+
constTimeNegate,
|
|
3206
|
+
hasPrecomputes(elm) {
|
|
3207
|
+
return getW(elm) !== 1;
|
|
3208
|
+
},
|
|
3209
|
+
// non-const time multiplication ladder
|
|
3210
|
+
unsafeLadder(elm, n, p = c.ZERO) {
|
|
3211
|
+
let d = elm;
|
|
3212
|
+
while (n > _0n3) {
|
|
3213
|
+
if (n & _1n3)
|
|
3214
|
+
p = p.add(d);
|
|
3215
|
+
d = d.double();
|
|
3216
|
+
n >>= _1n3;
|
|
3217
|
+
}
|
|
3218
|
+
return p;
|
|
3219
|
+
},
|
|
3220
|
+
/**
|
|
3221
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
3222
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
3223
|
+
* Number of precomputed points depends on the curve size:
|
|
3224
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
3225
|
+
* - 𝑊 is the window size
|
|
3226
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
3227
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
3228
|
+
* @param elm Point instance
|
|
3229
|
+
* @param W window size
|
|
3230
|
+
* @returns precomputed point tables flattened to a single array
|
|
3231
|
+
*/
|
|
3232
|
+
precomputeWindow(elm, W) {
|
|
3233
|
+
const { windows, windowSize } = calcWOpts(W, bits);
|
|
3234
|
+
const points = [];
|
|
3235
|
+
let p = elm;
|
|
3236
|
+
let base = p;
|
|
3237
|
+
for (let window2 = 0; window2 < windows; window2++) {
|
|
3238
|
+
base = p;
|
|
3239
|
+
points.push(base);
|
|
3240
|
+
for (let i = 1; i < windowSize; i++) {
|
|
3241
|
+
base = base.add(p);
|
|
3242
|
+
points.push(base);
|
|
3243
|
+
}
|
|
3244
|
+
p = base.double();
|
|
3245
|
+
}
|
|
3246
|
+
return points;
|
|
3247
|
+
},
|
|
3248
|
+
/**
|
|
3249
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
3250
|
+
* @param W window size
|
|
3251
|
+
* @param precomputes precomputed tables
|
|
3252
|
+
* @param n scalar (we don't check here, but should be less than curve order)
|
|
3253
|
+
* @returns real and fake (for const-time) points
|
|
3254
|
+
*/
|
|
3255
|
+
wNAF(W, precomputes, n) {
|
|
3256
|
+
let p = c.ZERO;
|
|
3257
|
+
let f = c.BASE;
|
|
3258
|
+
const wo = calcWOpts(W, bits);
|
|
3259
|
+
for (let window2 = 0; window2 < wo.windows; window2++) {
|
|
3260
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo);
|
|
3261
|
+
n = nextN;
|
|
3262
|
+
if (isZero) {
|
|
3263
|
+
f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
|
|
3264
|
+
} else {
|
|
3265
|
+
p = p.add(constTimeNegate(isNeg, precomputes[offset]));
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
return { p, f };
|
|
3269
|
+
},
|
|
3270
|
+
/**
|
|
3271
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
3272
|
+
* @param W window size
|
|
3273
|
+
* @param precomputes precomputed tables
|
|
3274
|
+
* @param n scalar (we don't check here, but should be less than curve order)
|
|
3275
|
+
* @param acc accumulator point to add result of multiplication
|
|
3276
|
+
* @returns point
|
|
3277
|
+
*/
|
|
3278
|
+
wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
|
|
3279
|
+
const wo = calcWOpts(W, bits);
|
|
3280
|
+
for (let window2 = 0; window2 < wo.windows; window2++) {
|
|
3281
|
+
if (n === _0n3)
|
|
3282
|
+
break;
|
|
3283
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo);
|
|
3284
|
+
n = nextN;
|
|
3285
|
+
if (isZero) {
|
|
3286
|
+
continue;
|
|
3287
|
+
} else {
|
|
3288
|
+
const item = precomputes[offset];
|
|
3289
|
+
acc = acc.add(isNeg ? item.negate() : item);
|
|
3290
|
+
}
|
|
3291
|
+
}
|
|
3292
|
+
return acc;
|
|
3293
|
+
},
|
|
3294
|
+
getPrecomputes(W, P, transform) {
|
|
3295
|
+
let comp = pointPrecomputes.get(P);
|
|
3296
|
+
if (!comp) {
|
|
3297
|
+
comp = this.precomputeWindow(P, W);
|
|
3298
|
+
if (W !== 1)
|
|
3299
|
+
pointPrecomputes.set(P, transform(comp));
|
|
3300
|
+
}
|
|
3301
|
+
return comp;
|
|
3302
|
+
},
|
|
3303
|
+
wNAFCached(P, n, transform) {
|
|
3304
|
+
const W = getW(P);
|
|
3305
|
+
return this.wNAF(W, this.getPrecomputes(W, P, transform), n);
|
|
3306
|
+
},
|
|
3307
|
+
wNAFCachedUnsafe(P, n, transform, prev) {
|
|
3308
|
+
const W = getW(P);
|
|
3309
|
+
if (W === 1)
|
|
3310
|
+
return this.unsafeLadder(P, n, prev);
|
|
3311
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);
|
|
3312
|
+
},
|
|
3313
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
3314
|
+
// using windowed method. This specifies window size and
|
|
3315
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
3316
|
+
setWindowSize(P, W) {
|
|
3317
|
+
validateW(W, bits);
|
|
3318
|
+
pointWindowSizes.set(P, W);
|
|
3319
|
+
pointPrecomputes.delete(P);
|
|
3320
|
+
}
|
|
3321
|
+
};
|
|
3322
|
+
}
|
|
3323
|
+
function pippenger(c, fieldN, points, scalars) {
|
|
3324
|
+
validateMSMPoints(points, c);
|
|
3325
|
+
validateMSMScalars(scalars, fieldN);
|
|
3326
|
+
const plength = points.length;
|
|
3327
|
+
const slength = scalars.length;
|
|
3328
|
+
if (plength !== slength)
|
|
3329
|
+
throw new Error("arrays of points and scalars must have equal length");
|
|
3330
|
+
const zero = c.ZERO;
|
|
3331
|
+
const wbits = bitLen(BigInt(plength));
|
|
3332
|
+
let windowSize = 1;
|
|
3333
|
+
if (wbits > 12)
|
|
3334
|
+
windowSize = wbits - 3;
|
|
3335
|
+
else if (wbits > 4)
|
|
3336
|
+
windowSize = wbits - 2;
|
|
3337
|
+
else if (wbits > 0)
|
|
3338
|
+
windowSize = 2;
|
|
3339
|
+
const MASK = bitMask(windowSize);
|
|
3340
|
+
const buckets = new Array(Number(MASK) + 1).fill(zero);
|
|
3341
|
+
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
|
|
3342
|
+
let sum = zero;
|
|
3343
|
+
for (let i = lastBits; i >= 0; i -= windowSize) {
|
|
3344
|
+
buckets.fill(zero);
|
|
3345
|
+
for (let j = 0; j < slength; j++) {
|
|
3346
|
+
const scalar = scalars[j];
|
|
3347
|
+
const wbits2 = Number(scalar >> BigInt(i) & MASK);
|
|
3348
|
+
buckets[wbits2] = buckets[wbits2].add(points[j]);
|
|
3349
|
+
}
|
|
3350
|
+
let resI = zero;
|
|
3351
|
+
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
|
|
3352
|
+
sumI = sumI.add(buckets[j]);
|
|
3353
|
+
resI = resI.add(sumI);
|
|
3354
|
+
}
|
|
3355
|
+
sum = sum.add(resI);
|
|
3356
|
+
if (i !== 0)
|
|
3357
|
+
for (let j = 0; j < windowSize; j++)
|
|
3358
|
+
sum = sum.double();
|
|
3359
|
+
}
|
|
3360
|
+
return sum;
|
|
3361
|
+
}
|
|
3362
|
+
function validateBasic(curve) {
|
|
3363
|
+
validateField(curve.Fp);
|
|
3364
|
+
validateObject(curve, {
|
|
3365
|
+
n: "bigint",
|
|
3366
|
+
h: "bigint",
|
|
3367
|
+
Gx: "field",
|
|
3368
|
+
Gy: "field"
|
|
3369
|
+
}, {
|
|
3370
|
+
nBitLength: "isSafeInteger",
|
|
3371
|
+
nByteLength: "isSafeInteger"
|
|
3372
|
+
});
|
|
3373
|
+
return Object.freeze({
|
|
3374
|
+
...nLength(curve.n, curve.nBitLength),
|
|
3375
|
+
...curve,
|
|
3376
|
+
...{ p: curve.Fp.ORDER }
|
|
3377
|
+
});
|
|
3378
|
+
}
|
|
3379
|
+
|
|
3380
|
+
// node_modules/@noble/curves/esm/abstract/weierstrass.js
|
|
3381
|
+
function validateSigVerOpts(opts) {
|
|
3382
|
+
if (opts.lowS !== void 0)
|
|
3383
|
+
abool("lowS", opts.lowS);
|
|
3384
|
+
if (opts.prehash !== void 0)
|
|
3385
|
+
abool("prehash", opts.prehash);
|
|
3386
|
+
}
|
|
3387
|
+
function validatePointOpts(curve) {
|
|
3388
|
+
const opts = validateBasic(curve);
|
|
3389
|
+
validateObject(opts, {
|
|
3390
|
+
a: "field",
|
|
3391
|
+
b: "field"
|
|
3392
|
+
}, {
|
|
3393
|
+
allowInfinityPoint: "boolean",
|
|
3394
|
+
allowedPrivateKeyLengths: "array",
|
|
3395
|
+
clearCofactor: "function",
|
|
3396
|
+
fromBytes: "function",
|
|
3397
|
+
isTorsionFree: "function",
|
|
3398
|
+
toBytes: "function",
|
|
3399
|
+
wrapPrivateKey: "boolean"
|
|
3400
|
+
});
|
|
3401
|
+
const { endo, Fp, a } = opts;
|
|
3402
|
+
if (endo) {
|
|
3403
|
+
if (!Fp.eql(a, Fp.ZERO)) {
|
|
3404
|
+
throw new Error("invalid endo: CURVE.a must be 0");
|
|
3405
|
+
}
|
|
3406
|
+
if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
|
|
3407
|
+
throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
return Object.freeze({ ...opts });
|
|
3411
|
+
}
|
|
3412
|
+
var DERErr = class extends Error {
|
|
3413
|
+
constructor(m = "") {
|
|
3414
|
+
super(m);
|
|
3415
|
+
}
|
|
3416
|
+
};
|
|
3417
|
+
var DER = {
|
|
3418
|
+
// asn.1 DER encoding utils
|
|
3419
|
+
Err: DERErr,
|
|
3420
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
3421
|
+
_tlv: {
|
|
3422
|
+
encode: (tag, data) => {
|
|
3423
|
+
const { Err: E } = DER;
|
|
3424
|
+
if (tag < 0 || tag > 256)
|
|
3425
|
+
throw new E("tlv.encode: wrong tag");
|
|
3426
|
+
if (data.length & 1)
|
|
3427
|
+
throw new E("tlv.encode: unpadded data");
|
|
3428
|
+
const dataLen = data.length / 2;
|
|
3429
|
+
const len = numberToHexUnpadded(dataLen);
|
|
3430
|
+
if (len.length / 2 & 128)
|
|
3431
|
+
throw new E("tlv.encode: long form length too big");
|
|
3432
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
3433
|
+
const t = numberToHexUnpadded(tag);
|
|
3434
|
+
return t + lenLen + len + data;
|
|
3435
|
+
},
|
|
3436
|
+
// v - value, l - left bytes (unparsed)
|
|
3437
|
+
decode(tag, data) {
|
|
3438
|
+
const { Err: E } = DER;
|
|
3439
|
+
let pos = 0;
|
|
3440
|
+
if (tag < 0 || tag > 256)
|
|
3441
|
+
throw new E("tlv.encode: wrong tag");
|
|
3442
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
3443
|
+
throw new E("tlv.decode: wrong tlv");
|
|
3444
|
+
const first = data[pos++];
|
|
3445
|
+
const isLong = !!(first & 128);
|
|
3446
|
+
let length = 0;
|
|
3447
|
+
if (!isLong)
|
|
3448
|
+
length = first;
|
|
3449
|
+
else {
|
|
3450
|
+
const lenLen = first & 127;
|
|
3451
|
+
if (!lenLen)
|
|
3452
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
3453
|
+
if (lenLen > 4)
|
|
3454
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
3455
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
3456
|
+
if (lengthBytes.length !== lenLen)
|
|
3457
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
3458
|
+
if (lengthBytes[0] === 0)
|
|
3459
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
3460
|
+
for (const b of lengthBytes)
|
|
3461
|
+
length = length << 8 | b;
|
|
3462
|
+
pos += lenLen;
|
|
3463
|
+
if (length < 128)
|
|
3464
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
3465
|
+
}
|
|
3466
|
+
const v = data.subarray(pos, pos + length);
|
|
3467
|
+
if (v.length !== length)
|
|
3468
|
+
throw new E("tlv.decode: wrong value length");
|
|
3469
|
+
return { v, l: data.subarray(pos + length) };
|
|
3470
|
+
}
|
|
3471
|
+
},
|
|
3472
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
3473
|
+
// since we always use positive integers here. It must always be empty:
|
|
3474
|
+
// - add zero byte if exists
|
|
3475
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
3476
|
+
_int: {
|
|
3477
|
+
encode(num) {
|
|
3478
|
+
const { Err: E } = DER;
|
|
3479
|
+
if (num < _0n4)
|
|
3480
|
+
throw new E("integer: negative integers are not allowed");
|
|
3481
|
+
let hex = numberToHexUnpadded(num);
|
|
3482
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
3483
|
+
hex = "00" + hex;
|
|
3484
|
+
if (hex.length & 1)
|
|
3485
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
3486
|
+
return hex;
|
|
3487
|
+
},
|
|
3488
|
+
decode(data) {
|
|
3489
|
+
const { Err: E } = DER;
|
|
3490
|
+
if (data[0] & 128)
|
|
3491
|
+
throw new E("invalid signature integer: negative");
|
|
3492
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
3493
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
3494
|
+
return bytesToNumberBE(data);
|
|
3495
|
+
}
|
|
3496
|
+
},
|
|
3497
|
+
toSig(hex) {
|
|
3498
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
3499
|
+
const data = ensureBytes("signature", hex);
|
|
3500
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
3501
|
+
if (seqLeftBytes.length)
|
|
3502
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
3503
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
3504
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
3505
|
+
if (sLeftBytes.length)
|
|
3506
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
3507
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
3508
|
+
},
|
|
3509
|
+
hexFromSig(sig) {
|
|
3510
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
3511
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
3512
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
3513
|
+
const seq = rs + ss;
|
|
3514
|
+
return tlv.encode(48, seq);
|
|
3515
|
+
}
|
|
3516
|
+
};
|
|
3517
|
+
function numToSizedHex(num, size) {
|
|
3518
|
+
return bytesToHex(numberToBytesBE(num, size));
|
|
3519
|
+
}
|
|
3520
|
+
var _0n4 = BigInt(0);
|
|
3521
|
+
var _1n4 = BigInt(1);
|
|
3522
|
+
var _2n2 = BigInt(2);
|
|
3523
|
+
var _3n2 = BigInt(3);
|
|
3524
|
+
var _4n2 = BigInt(4);
|
|
3525
|
+
function weierstrassPoints(opts) {
|
|
3526
|
+
const CURVE = validatePointOpts(opts);
|
|
3527
|
+
const { Fp } = CURVE;
|
|
3528
|
+
const Fn = Field(CURVE.n, CURVE.nBitLength);
|
|
3529
|
+
const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => {
|
|
3530
|
+
const a = point.toAffine();
|
|
3531
|
+
return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
|
|
3532
|
+
});
|
|
3533
|
+
const fromBytes = CURVE.fromBytes || ((bytes) => {
|
|
3534
|
+
const tail = bytes.subarray(1);
|
|
3535
|
+
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
|
|
3536
|
+
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
|
|
3537
|
+
return { x, y };
|
|
3538
|
+
});
|
|
3539
|
+
function weierstrassEquation(x) {
|
|
3540
|
+
const { a, b } = CURVE;
|
|
3541
|
+
const x2 = Fp.sqr(x);
|
|
3542
|
+
const x3 = Fp.mul(x2, x);
|
|
3543
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
|
|
3544
|
+
}
|
|
3545
|
+
function isValidXY(x, y) {
|
|
3546
|
+
const left = Fp.sqr(y);
|
|
3547
|
+
const right = weierstrassEquation(x);
|
|
3548
|
+
return Fp.eql(left, right);
|
|
3549
|
+
}
|
|
3550
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
3551
|
+
throw new Error("bad curve params: generator point");
|
|
3552
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
3553
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
3554
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
3555
|
+
throw new Error("bad curve params: a or b");
|
|
3556
|
+
function isWithinCurveOrder(num) {
|
|
3557
|
+
return inRange(num, _1n4, CURVE.n);
|
|
3558
|
+
}
|
|
3559
|
+
function normPrivateKeyToScalar(key) {
|
|
3560
|
+
const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
|
|
3561
|
+
if (lengths && typeof key !== "bigint") {
|
|
3562
|
+
if (isBytes3(key))
|
|
3563
|
+
key = bytesToHex(key);
|
|
3564
|
+
if (typeof key !== "string" || !lengths.includes(key.length))
|
|
3565
|
+
throw new Error("invalid private key");
|
|
3566
|
+
key = key.padStart(nByteLength * 2, "0");
|
|
3567
|
+
}
|
|
3568
|
+
let num;
|
|
3569
|
+
try {
|
|
3570
|
+
num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
|
|
3571
|
+
} catch (error) {
|
|
3572
|
+
throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
|
|
3573
|
+
}
|
|
3574
|
+
if (wrapPrivateKey)
|
|
3575
|
+
num = mod(num, N);
|
|
3576
|
+
aInRange("private key", num, _1n4, N);
|
|
3577
|
+
return num;
|
|
3578
|
+
}
|
|
3579
|
+
function aprjpoint(other) {
|
|
3580
|
+
if (!(other instanceof Point))
|
|
3581
|
+
throw new Error("ProjectivePoint expected");
|
|
3582
|
+
}
|
|
3583
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
3584
|
+
const { px: x, py: y, pz: z9 } = p;
|
|
3585
|
+
if (Fp.eql(z9, Fp.ONE))
|
|
3586
|
+
return { x, y };
|
|
3587
|
+
const is0 = p.is0();
|
|
3588
|
+
if (iz == null)
|
|
3589
|
+
iz = is0 ? Fp.ONE : Fp.inv(z9);
|
|
3590
|
+
const ax = Fp.mul(x, iz);
|
|
3591
|
+
const ay = Fp.mul(y, iz);
|
|
3592
|
+
const zz = Fp.mul(z9, iz);
|
|
3593
|
+
if (is0)
|
|
3594
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
3595
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
3596
|
+
throw new Error("invZ was invalid");
|
|
3597
|
+
return { x: ax, y: ay };
|
|
3598
|
+
});
|
|
3599
|
+
const assertValidMemo = memoized((p) => {
|
|
3600
|
+
if (p.is0()) {
|
|
3601
|
+
if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
|
|
3602
|
+
return;
|
|
3603
|
+
throw new Error("bad point: ZERO");
|
|
3604
|
+
}
|
|
3605
|
+
const { x, y } = p.toAffine();
|
|
3606
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
3607
|
+
throw new Error("bad point: x or y not FE");
|
|
3608
|
+
if (!isValidXY(x, y))
|
|
3609
|
+
throw new Error("bad point: equation left != right");
|
|
3610
|
+
if (!p.isTorsionFree())
|
|
3611
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
3612
|
+
return true;
|
|
3613
|
+
});
|
|
3614
|
+
class Point {
|
|
3615
|
+
constructor(px, py, pz) {
|
|
3616
|
+
if (px == null || !Fp.isValid(px))
|
|
3617
|
+
throw new Error("x required");
|
|
3618
|
+
if (py == null || !Fp.isValid(py) || Fp.is0(py))
|
|
3619
|
+
throw new Error("y required");
|
|
3620
|
+
if (pz == null || !Fp.isValid(pz))
|
|
3621
|
+
throw new Error("z required");
|
|
3622
|
+
this.px = px;
|
|
3623
|
+
this.py = py;
|
|
3624
|
+
this.pz = pz;
|
|
3625
|
+
Object.freeze(this);
|
|
3626
|
+
}
|
|
3627
|
+
// Does not validate if the point is on-curve.
|
|
3628
|
+
// Use fromHex instead, or call assertValidity() later.
|
|
3629
|
+
static fromAffine(p) {
|
|
3630
|
+
const { x, y } = p || {};
|
|
3631
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
3632
|
+
throw new Error("invalid affine point");
|
|
3633
|
+
if (p instanceof Point)
|
|
3634
|
+
throw new Error("projective point not allowed");
|
|
3635
|
+
const is0 = (i) => Fp.eql(i, Fp.ZERO);
|
|
3636
|
+
if (is0(x) && is0(y))
|
|
3637
|
+
return Point.ZERO;
|
|
3638
|
+
return new Point(x, y, Fp.ONE);
|
|
3639
|
+
}
|
|
3640
|
+
get x() {
|
|
3641
|
+
return this.toAffine().x;
|
|
3642
|
+
}
|
|
3643
|
+
get y() {
|
|
3644
|
+
return this.toAffine().y;
|
|
3645
|
+
}
|
|
3646
|
+
/**
|
|
3647
|
+
* Takes a bunch of Projective Points but executes only one
|
|
3648
|
+
* inversion on all of them. Inversion is very slow operation,
|
|
3649
|
+
* so this improves performance massively.
|
|
3650
|
+
* Optimization: converts a list of projective points to a list of identical points with Z=1.
|
|
3651
|
+
*/
|
|
3652
|
+
static normalizeZ(points) {
|
|
3653
|
+
const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
|
|
3654
|
+
return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
|
|
3655
|
+
}
|
|
3656
|
+
/**
|
|
3657
|
+
* Converts hash string or Uint8Array to Point.
|
|
3658
|
+
* @param hex short/long ECDSA hex
|
|
3659
|
+
*/
|
|
3660
|
+
static fromHex(hex) {
|
|
3661
|
+
const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
|
|
3662
|
+
P.assertValidity();
|
|
3663
|
+
return P;
|
|
3664
|
+
}
|
|
3665
|
+
// Multiplies generator point by privateKey.
|
|
3666
|
+
static fromPrivateKey(privateKey) {
|
|
3667
|
+
return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
|
|
3668
|
+
}
|
|
3669
|
+
// Multiscalar Multiplication
|
|
3670
|
+
static msm(points, scalars) {
|
|
3671
|
+
return pippenger(Point, Fn, points, scalars);
|
|
3672
|
+
}
|
|
3673
|
+
// "Private method", don't use it directly
|
|
3674
|
+
_setWindowSize(windowSize) {
|
|
3675
|
+
wnaf.setWindowSize(this, windowSize);
|
|
3676
|
+
}
|
|
3677
|
+
// A point on curve is valid if it conforms to equation.
|
|
3678
|
+
assertValidity() {
|
|
3679
|
+
assertValidMemo(this);
|
|
3680
|
+
}
|
|
3681
|
+
hasEvenY() {
|
|
3682
|
+
const { y } = this.toAffine();
|
|
3683
|
+
if (Fp.isOdd)
|
|
3684
|
+
return !Fp.isOdd(y);
|
|
3685
|
+
throw new Error("Field doesn't support isOdd");
|
|
3686
|
+
}
|
|
3687
|
+
/**
|
|
3688
|
+
* Compare one point to another.
|
|
3689
|
+
*/
|
|
3690
|
+
equals(other) {
|
|
3691
|
+
aprjpoint(other);
|
|
3692
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
3693
|
+
const { px: X2, py: Y2, pz: Z2 } = other;
|
|
3694
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
3695
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
3696
|
+
return U1 && U2;
|
|
3697
|
+
}
|
|
3698
|
+
/**
|
|
3699
|
+
* Flips point to one corresponding to (x, -y) in Affine coordinates.
|
|
3700
|
+
*/
|
|
3701
|
+
negate() {
|
|
3702
|
+
return new Point(this.px, Fp.neg(this.py), this.pz);
|
|
3703
|
+
}
|
|
3704
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
3705
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
3706
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
3707
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
3708
|
+
double() {
|
|
3709
|
+
const { a, b } = CURVE;
|
|
3710
|
+
const b3 = Fp.mul(b, _3n2);
|
|
3711
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
3712
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
3713
|
+
let t0 = Fp.mul(X1, X1);
|
|
3714
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
3715
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
3716
|
+
let t3 = Fp.mul(X1, Y1);
|
|
3717
|
+
t3 = Fp.add(t3, t3);
|
|
3718
|
+
Z3 = Fp.mul(X1, Z1);
|
|
3719
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3720
|
+
X3 = Fp.mul(a, Z3);
|
|
3721
|
+
Y3 = Fp.mul(b3, t2);
|
|
3722
|
+
Y3 = Fp.add(X3, Y3);
|
|
3723
|
+
X3 = Fp.sub(t1, Y3);
|
|
3724
|
+
Y3 = Fp.add(t1, Y3);
|
|
3725
|
+
Y3 = Fp.mul(X3, Y3);
|
|
3726
|
+
X3 = Fp.mul(t3, X3);
|
|
3727
|
+
Z3 = Fp.mul(b3, Z3);
|
|
3728
|
+
t2 = Fp.mul(a, t2);
|
|
3729
|
+
t3 = Fp.sub(t0, t2);
|
|
3730
|
+
t3 = Fp.mul(a, t3);
|
|
3731
|
+
t3 = Fp.add(t3, Z3);
|
|
3732
|
+
Z3 = Fp.add(t0, t0);
|
|
3733
|
+
t0 = Fp.add(Z3, t0);
|
|
3734
|
+
t0 = Fp.add(t0, t2);
|
|
3735
|
+
t0 = Fp.mul(t0, t3);
|
|
3736
|
+
Y3 = Fp.add(Y3, t0);
|
|
3737
|
+
t2 = Fp.mul(Y1, Z1);
|
|
3738
|
+
t2 = Fp.add(t2, t2);
|
|
3739
|
+
t0 = Fp.mul(t2, t3);
|
|
3740
|
+
X3 = Fp.sub(X3, t0);
|
|
3741
|
+
Z3 = Fp.mul(t2, t1);
|
|
3742
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3743
|
+
Z3 = Fp.add(Z3, Z3);
|
|
3744
|
+
return new Point(X3, Y3, Z3);
|
|
3745
|
+
}
|
|
3746
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
3747
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
3748
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
3749
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
3750
|
+
add(other) {
|
|
3751
|
+
aprjpoint(other);
|
|
3752
|
+
const { px: X1, py: Y1, pz: Z1 } = this;
|
|
3753
|
+
const { px: X2, py: Y2, pz: Z2 } = other;
|
|
3754
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
3755
|
+
const a = CURVE.a;
|
|
3756
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
3757
|
+
let t0 = Fp.mul(X1, X2);
|
|
3758
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
3759
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
3760
|
+
let t3 = Fp.add(X1, Y1);
|
|
3761
|
+
let t4 = Fp.add(X2, Y2);
|
|
3762
|
+
t3 = Fp.mul(t3, t4);
|
|
3763
|
+
t4 = Fp.add(t0, t1);
|
|
3764
|
+
t3 = Fp.sub(t3, t4);
|
|
3765
|
+
t4 = Fp.add(X1, Z1);
|
|
3766
|
+
let t5 = Fp.add(X2, Z2);
|
|
3767
|
+
t4 = Fp.mul(t4, t5);
|
|
3768
|
+
t5 = Fp.add(t0, t2);
|
|
3769
|
+
t4 = Fp.sub(t4, t5);
|
|
3770
|
+
t5 = Fp.add(Y1, Z1);
|
|
3771
|
+
X3 = Fp.add(Y2, Z2);
|
|
3772
|
+
t5 = Fp.mul(t5, X3);
|
|
3773
|
+
X3 = Fp.add(t1, t2);
|
|
3774
|
+
t5 = Fp.sub(t5, X3);
|
|
3775
|
+
Z3 = Fp.mul(a, t4);
|
|
3776
|
+
X3 = Fp.mul(b3, t2);
|
|
3777
|
+
Z3 = Fp.add(X3, Z3);
|
|
3778
|
+
X3 = Fp.sub(t1, Z3);
|
|
3779
|
+
Z3 = Fp.add(t1, Z3);
|
|
3780
|
+
Y3 = Fp.mul(X3, Z3);
|
|
3781
|
+
t1 = Fp.add(t0, t0);
|
|
3782
|
+
t1 = Fp.add(t1, t0);
|
|
3783
|
+
t2 = Fp.mul(a, t2);
|
|
3784
|
+
t4 = Fp.mul(b3, t4);
|
|
3785
|
+
t1 = Fp.add(t1, t2);
|
|
3786
|
+
t2 = Fp.sub(t0, t2);
|
|
3787
|
+
t2 = Fp.mul(a, t2);
|
|
3788
|
+
t4 = Fp.add(t4, t2);
|
|
3789
|
+
t0 = Fp.mul(t1, t4);
|
|
3790
|
+
Y3 = Fp.add(Y3, t0);
|
|
3791
|
+
t0 = Fp.mul(t5, t4);
|
|
3792
|
+
X3 = Fp.mul(t3, X3);
|
|
3793
|
+
X3 = Fp.sub(X3, t0);
|
|
3794
|
+
t0 = Fp.mul(t3, t1);
|
|
3795
|
+
Z3 = Fp.mul(t5, Z3);
|
|
3796
|
+
Z3 = Fp.add(Z3, t0);
|
|
3797
|
+
return new Point(X3, Y3, Z3);
|
|
3798
|
+
}
|
|
3799
|
+
subtract(other) {
|
|
3800
|
+
return this.add(other.negate());
|
|
3801
|
+
}
|
|
3802
|
+
is0() {
|
|
3803
|
+
return this.equals(Point.ZERO);
|
|
3804
|
+
}
|
|
3805
|
+
wNAF(n) {
|
|
3806
|
+
return wnaf.wNAFCached(this, n, Point.normalizeZ);
|
|
3807
|
+
}
|
|
3808
|
+
/**
|
|
3809
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
3810
|
+
* It's faster, but should only be used when you don't care about
|
|
3811
|
+
* an exposed private key e.g. sig verification, which works over *public* keys.
|
|
3812
|
+
*/
|
|
3813
|
+
multiplyUnsafe(sc) {
|
|
3814
|
+
const { endo: endo2, n: N } = CURVE;
|
|
3815
|
+
aInRange("scalar", sc, _0n4, N);
|
|
3816
|
+
const I = Point.ZERO;
|
|
3817
|
+
if (sc === _0n4)
|
|
3818
|
+
return I;
|
|
3819
|
+
if (this.is0() || sc === _1n4)
|
|
3820
|
+
return this;
|
|
3821
|
+
if (!endo2 || wnaf.hasPrecomputes(this))
|
|
3822
|
+
return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);
|
|
3823
|
+
let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
|
|
3824
|
+
let k1p = I;
|
|
3825
|
+
let k2p = I;
|
|
3826
|
+
let d = this;
|
|
3827
|
+
while (k1 > _0n4 || k2 > _0n4) {
|
|
3828
|
+
if (k1 & _1n4)
|
|
3829
|
+
k1p = k1p.add(d);
|
|
3830
|
+
if (k2 & _1n4)
|
|
3831
|
+
k2p = k2p.add(d);
|
|
3832
|
+
d = d.double();
|
|
3833
|
+
k1 >>= _1n4;
|
|
3834
|
+
k2 >>= _1n4;
|
|
3835
|
+
}
|
|
3836
|
+
if (k1neg)
|
|
3837
|
+
k1p = k1p.negate();
|
|
3838
|
+
if (k2neg)
|
|
3839
|
+
k2p = k2p.negate();
|
|
3840
|
+
k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
|
|
3841
|
+
return k1p.add(k2p);
|
|
3842
|
+
}
|
|
3843
|
+
/**
|
|
3844
|
+
* Constant time multiplication.
|
|
3845
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
3846
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
3847
|
+
* Uses precomputes when available.
|
|
3848
|
+
* Uses endomorphism for Koblitz curves.
|
|
3849
|
+
* @param scalar by which the point would be multiplied
|
|
3850
|
+
* @returns New point
|
|
3851
|
+
*/
|
|
3852
|
+
multiply(scalar) {
|
|
3853
|
+
const { endo: endo2, n: N } = CURVE;
|
|
3854
|
+
aInRange("scalar", scalar, _1n4, N);
|
|
3855
|
+
let point, fake;
|
|
3856
|
+
if (endo2) {
|
|
3857
|
+
const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
|
|
3858
|
+
let { p: k1p, f: f1p } = this.wNAF(k1);
|
|
3859
|
+
let { p: k2p, f: f2p } = this.wNAF(k2);
|
|
3860
|
+
k1p = wnaf.constTimeNegate(k1neg, k1p);
|
|
3861
|
+
k2p = wnaf.constTimeNegate(k2neg, k2p);
|
|
3862
|
+
k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
|
|
3863
|
+
point = k1p.add(k2p);
|
|
3864
|
+
fake = f1p.add(f2p);
|
|
3865
|
+
} else {
|
|
3866
|
+
const { p, f } = this.wNAF(scalar);
|
|
3867
|
+
point = p;
|
|
3868
|
+
fake = f;
|
|
3869
|
+
}
|
|
3870
|
+
return Point.normalizeZ([point, fake])[0];
|
|
3871
|
+
}
|
|
3872
|
+
/**
|
|
3873
|
+
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
|
|
3874
|
+
* Not using Strauss-Shamir trick: precomputation tables are faster.
|
|
3875
|
+
* The trick could be useful if both P and Q are not G (not in our case).
|
|
3876
|
+
* @returns non-zero affine point
|
|
3877
|
+
*/
|
|
3878
|
+
multiplyAndAddUnsafe(Q, a, b) {
|
|
3879
|
+
const G = Point.BASE;
|
|
3880
|
+
const mul3 = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
|
|
3881
|
+
const sum = mul3(this, a).add(mul3(Q, b));
|
|
3882
|
+
return sum.is0() ? void 0 : sum;
|
|
3883
|
+
}
|
|
3884
|
+
// Converts Projective point to affine (x, y) coordinates.
|
|
3885
|
+
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
|
3886
|
+
// (x, y, z) ∋ (x=x/z, y=y/z)
|
|
3887
|
+
toAffine(iz) {
|
|
3888
|
+
return toAffineMemo(this, iz);
|
|
3889
|
+
}
|
|
3890
|
+
isTorsionFree() {
|
|
3891
|
+
const { h: cofactor, isTorsionFree } = CURVE;
|
|
3892
|
+
if (cofactor === _1n4)
|
|
3893
|
+
return true;
|
|
3894
|
+
if (isTorsionFree)
|
|
3895
|
+
return isTorsionFree(Point, this);
|
|
3896
|
+
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
|
|
3897
|
+
}
|
|
3898
|
+
clearCofactor() {
|
|
3899
|
+
const { h: cofactor, clearCofactor } = CURVE;
|
|
3900
|
+
if (cofactor === _1n4)
|
|
3901
|
+
return this;
|
|
3902
|
+
if (clearCofactor)
|
|
3903
|
+
return clearCofactor(Point, this);
|
|
3904
|
+
return this.multiplyUnsafe(CURVE.h);
|
|
3905
|
+
}
|
|
3906
|
+
toRawBytes(isCompressed = true) {
|
|
3907
|
+
abool("isCompressed", isCompressed);
|
|
3908
|
+
this.assertValidity();
|
|
3909
|
+
return toBytes2(Point, this, isCompressed);
|
|
3910
|
+
}
|
|
3911
|
+
toHex(isCompressed = true) {
|
|
3912
|
+
abool("isCompressed", isCompressed);
|
|
3913
|
+
return bytesToHex(this.toRawBytes(isCompressed));
|
|
3914
|
+
}
|
|
3915
|
+
}
|
|
3916
|
+
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
3917
|
+
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
3918
|
+
const { endo, nBitLength } = CURVE;
|
|
3919
|
+
const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);
|
|
3920
|
+
return {
|
|
3921
|
+
CURVE,
|
|
3922
|
+
ProjectivePoint: Point,
|
|
3923
|
+
normPrivateKeyToScalar,
|
|
3924
|
+
weierstrassEquation,
|
|
3925
|
+
isWithinCurveOrder
|
|
3926
|
+
};
|
|
3927
|
+
}
|
|
3928
|
+
function validateOpts(curve) {
|
|
3929
|
+
const opts = validateBasic(curve);
|
|
3930
|
+
validateObject(opts, {
|
|
3931
|
+
hash: "hash",
|
|
3932
|
+
hmac: "function",
|
|
3933
|
+
randomBytes: "function"
|
|
3934
|
+
}, {
|
|
3935
|
+
bits2int: "function",
|
|
3936
|
+
bits2int_modN: "function",
|
|
3937
|
+
lowS: "boolean"
|
|
3938
|
+
});
|
|
3939
|
+
return Object.freeze({ lowS: true, ...opts });
|
|
3940
|
+
}
|
|
3941
|
+
function weierstrass(curveDef) {
|
|
3942
|
+
const CURVE = validateOpts(curveDef);
|
|
3943
|
+
const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
|
|
3944
|
+
const compressedLen = Fp.BYTES + 1;
|
|
3945
|
+
const uncompressedLen = 2 * Fp.BYTES + 1;
|
|
3946
|
+
function modN(a) {
|
|
3947
|
+
return mod(a, CURVE_ORDER);
|
|
3948
|
+
}
|
|
3949
|
+
function invN(a) {
|
|
3950
|
+
return invert(a, CURVE_ORDER);
|
|
3951
|
+
}
|
|
3952
|
+
const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
|
|
3953
|
+
...CURVE,
|
|
3954
|
+
toBytes(_c, point, isCompressed) {
|
|
3955
|
+
const a = point.toAffine();
|
|
3956
|
+
const x = Fp.toBytes(a.x);
|
|
3957
|
+
const cat = concatBytes3;
|
|
3958
|
+
abool("isCompressed", isCompressed);
|
|
3959
|
+
if (isCompressed) {
|
|
3960
|
+
return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
|
|
3961
|
+
} else {
|
|
3962
|
+
return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
|
|
3963
|
+
}
|
|
3964
|
+
},
|
|
3965
|
+
fromBytes(bytes) {
|
|
3966
|
+
const len = bytes.length;
|
|
3967
|
+
const head = bytes[0];
|
|
3968
|
+
const tail = bytes.subarray(1);
|
|
3969
|
+
if (len === compressedLen && (head === 2 || head === 3)) {
|
|
3970
|
+
const x = bytesToNumberBE(tail);
|
|
3971
|
+
if (!inRange(x, _1n4, Fp.ORDER))
|
|
3972
|
+
throw new Error("Point is not on curve");
|
|
3973
|
+
const y2 = weierstrassEquation(x);
|
|
3974
|
+
let y;
|
|
3975
|
+
try {
|
|
3976
|
+
y = Fp.sqrt(y2);
|
|
3977
|
+
} catch (sqrtError) {
|
|
3978
|
+
const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
3979
|
+
throw new Error("Point is not on curve" + suffix);
|
|
3980
|
+
}
|
|
3981
|
+
const isYOdd = (y & _1n4) === _1n4;
|
|
3982
|
+
const isHeadOdd = (head & 1) === 1;
|
|
3983
|
+
if (isHeadOdd !== isYOdd)
|
|
3984
|
+
y = Fp.neg(y);
|
|
3985
|
+
return { x, y };
|
|
3986
|
+
} else if (len === uncompressedLen && head === 4) {
|
|
3987
|
+
const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
|
|
3988
|
+
const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
|
|
3989
|
+
return { x, y };
|
|
3990
|
+
} else {
|
|
3991
|
+
const cl = compressedLen;
|
|
3992
|
+
const ul = uncompressedLen;
|
|
3993
|
+
throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
});
|
|
3997
|
+
function isBiggerThanHalfOrder(number) {
|
|
3998
|
+
const HALF = CURVE_ORDER >> _1n4;
|
|
3999
|
+
return number > HALF;
|
|
4000
|
+
}
|
|
4001
|
+
function normalizeS(s) {
|
|
4002
|
+
return isBiggerThanHalfOrder(s) ? modN(-s) : s;
|
|
4003
|
+
}
|
|
4004
|
+
const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
|
|
4005
|
+
class Signature {
|
|
4006
|
+
constructor(r, s, recovery) {
|
|
4007
|
+
aInRange("r", r, _1n4, CURVE_ORDER);
|
|
4008
|
+
aInRange("s", s, _1n4, CURVE_ORDER);
|
|
4009
|
+
this.r = r;
|
|
4010
|
+
this.s = s;
|
|
4011
|
+
if (recovery != null)
|
|
4012
|
+
this.recovery = recovery;
|
|
4013
|
+
Object.freeze(this);
|
|
4014
|
+
}
|
|
4015
|
+
// pair (bytes of r, bytes of s)
|
|
4016
|
+
static fromCompact(hex) {
|
|
4017
|
+
const l = nByteLength;
|
|
4018
|
+
hex = ensureBytes("compactSignature", hex, l * 2);
|
|
4019
|
+
return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
|
|
4020
|
+
}
|
|
4021
|
+
// DER encoded ECDSA signature
|
|
4022
|
+
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
|
|
4023
|
+
static fromDER(hex) {
|
|
4024
|
+
const { r, s } = DER.toSig(ensureBytes("DER", hex));
|
|
4025
|
+
return new Signature(r, s);
|
|
4026
|
+
}
|
|
4027
|
+
/**
|
|
4028
|
+
* @todo remove
|
|
4029
|
+
* @deprecated
|
|
4030
|
+
*/
|
|
4031
|
+
assertValidity() {
|
|
4032
|
+
}
|
|
4033
|
+
addRecoveryBit(recovery) {
|
|
4034
|
+
return new Signature(this.r, this.s, recovery);
|
|
4035
|
+
}
|
|
4036
|
+
recoverPublicKey(msgHash) {
|
|
4037
|
+
const { r, s, recovery: rec } = this;
|
|
4038
|
+
const h = bits2int_modN(ensureBytes("msgHash", msgHash));
|
|
4039
|
+
if (rec == null || ![0, 1, 2, 3].includes(rec))
|
|
4040
|
+
throw new Error("recovery id invalid");
|
|
4041
|
+
const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
|
|
4042
|
+
if (radj >= Fp.ORDER)
|
|
4043
|
+
throw new Error("recovery id 2 or 3 invalid");
|
|
4044
|
+
const prefix = (rec & 1) === 0 ? "02" : "03";
|
|
4045
|
+
const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
|
|
4046
|
+
const ir = invN(radj);
|
|
4047
|
+
const u1 = modN(-h * ir);
|
|
4048
|
+
const u2 = modN(s * ir);
|
|
4049
|
+
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
|
|
4050
|
+
if (!Q)
|
|
4051
|
+
throw new Error("point at infinify");
|
|
4052
|
+
Q.assertValidity();
|
|
4053
|
+
return Q;
|
|
4054
|
+
}
|
|
4055
|
+
// Signatures should be low-s, to prevent malleability.
|
|
4056
|
+
hasHighS() {
|
|
4057
|
+
return isBiggerThanHalfOrder(this.s);
|
|
4058
|
+
}
|
|
4059
|
+
normalizeS() {
|
|
4060
|
+
return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
|
|
4061
|
+
}
|
|
4062
|
+
// DER-encoded
|
|
4063
|
+
toDERRawBytes() {
|
|
4064
|
+
return hexToBytes2(this.toDERHex());
|
|
4065
|
+
}
|
|
4066
|
+
toDERHex() {
|
|
4067
|
+
return DER.hexFromSig(this);
|
|
4068
|
+
}
|
|
4069
|
+
// padded bytes of r, then padded bytes of s
|
|
4070
|
+
toCompactRawBytes() {
|
|
4071
|
+
return hexToBytes2(this.toCompactHex());
|
|
4072
|
+
}
|
|
4073
|
+
toCompactHex() {
|
|
4074
|
+
const l = nByteLength;
|
|
4075
|
+
return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);
|
|
4076
|
+
}
|
|
4077
|
+
}
|
|
4078
|
+
const utils = {
|
|
4079
|
+
isValidPrivateKey(privateKey) {
|
|
4080
|
+
try {
|
|
4081
|
+
normPrivateKeyToScalar(privateKey);
|
|
4082
|
+
return true;
|
|
4083
|
+
} catch (error) {
|
|
4084
|
+
return false;
|
|
4085
|
+
}
|
|
4086
|
+
},
|
|
4087
|
+
normPrivateKeyToScalar,
|
|
4088
|
+
/**
|
|
4089
|
+
* Produces cryptographically secure private key from random of size
|
|
4090
|
+
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
|
|
4091
|
+
*/
|
|
4092
|
+
randomPrivateKey: () => {
|
|
4093
|
+
const length = getMinHashLength(CURVE.n);
|
|
4094
|
+
return mapHashToField(CURVE.randomBytes(length), CURVE.n);
|
|
4095
|
+
},
|
|
4096
|
+
/**
|
|
4097
|
+
* Creates precompute table for an arbitrary EC point. Makes point "cached".
|
|
4098
|
+
* Allows to massively speed-up `point.multiply(scalar)`.
|
|
4099
|
+
* @returns cached point
|
|
4100
|
+
* @example
|
|
4101
|
+
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
|
|
4102
|
+
* fast.multiply(privKey); // much faster ECDH now
|
|
4103
|
+
*/
|
|
4104
|
+
precompute(windowSize = 8, point = Point.BASE) {
|
|
4105
|
+
point._setWindowSize(windowSize);
|
|
4106
|
+
point.multiply(BigInt(3));
|
|
4107
|
+
return point;
|
|
4108
|
+
}
|
|
4109
|
+
};
|
|
4110
|
+
function getPublicKey(privateKey, isCompressed = true) {
|
|
4111
|
+
return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
|
|
4112
|
+
}
|
|
4113
|
+
function isProbPub(item) {
|
|
4114
|
+
if (typeof item === "bigint")
|
|
4115
|
+
return false;
|
|
4116
|
+
if (item instanceof Point)
|
|
4117
|
+
return true;
|
|
4118
|
+
const arr = ensureBytes("key", item);
|
|
4119
|
+
const len = arr.length;
|
|
4120
|
+
const fpl = Fp.BYTES;
|
|
4121
|
+
const compLen = fpl + 1;
|
|
4122
|
+
const uncompLen = 2 * fpl + 1;
|
|
4123
|
+
if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
|
|
4124
|
+
return void 0;
|
|
4125
|
+
} else {
|
|
4126
|
+
return len === compLen || len === uncompLen;
|
|
4127
|
+
}
|
|
4128
|
+
}
|
|
4129
|
+
function getSharedSecret(privateA, publicB, isCompressed = true) {
|
|
4130
|
+
if (isProbPub(privateA) === true)
|
|
4131
|
+
throw new Error("first arg must be private key");
|
|
4132
|
+
if (isProbPub(publicB) === false)
|
|
4133
|
+
throw new Error("second arg must be public key");
|
|
4134
|
+
const b = Point.fromHex(publicB);
|
|
4135
|
+
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
|
|
4136
|
+
}
|
|
4137
|
+
const bits2int = CURVE.bits2int || function(bytes) {
|
|
4138
|
+
if (bytes.length > 8192)
|
|
4139
|
+
throw new Error("input is too large");
|
|
4140
|
+
const num = bytesToNumberBE(bytes);
|
|
4141
|
+
const delta = bytes.length * 8 - nBitLength;
|
|
4142
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
4143
|
+
};
|
|
4144
|
+
const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
|
|
4145
|
+
return modN(bits2int(bytes));
|
|
4146
|
+
};
|
|
4147
|
+
const ORDER_MASK = bitMask(nBitLength);
|
|
4148
|
+
function int2octets(num) {
|
|
4149
|
+
aInRange("num < 2^" + nBitLength, num, _0n4, ORDER_MASK);
|
|
4150
|
+
return numberToBytesBE(num, nByteLength);
|
|
4151
|
+
}
|
|
4152
|
+
function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
|
|
4153
|
+
if (["recovered", "canonical"].some((k) => k in opts))
|
|
4154
|
+
throw new Error("sign() legacy options not supported");
|
|
4155
|
+
const { hash, randomBytes: randomBytes2 } = CURVE;
|
|
4156
|
+
let { lowS, prehash, extraEntropy: ent } = opts;
|
|
4157
|
+
if (lowS == null)
|
|
4158
|
+
lowS = true;
|
|
4159
|
+
msgHash = ensureBytes("msgHash", msgHash);
|
|
4160
|
+
validateSigVerOpts(opts);
|
|
4161
|
+
if (prehash)
|
|
4162
|
+
msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
|
|
4163
|
+
const h1int = bits2int_modN(msgHash);
|
|
4164
|
+
const d = normPrivateKeyToScalar(privateKey);
|
|
4165
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
4166
|
+
if (ent != null && ent !== false) {
|
|
4167
|
+
const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
|
|
4168
|
+
seedArgs.push(ensureBytes("extraEntropy", e));
|
|
4169
|
+
}
|
|
4170
|
+
const seed = concatBytes3(...seedArgs);
|
|
4171
|
+
const m = h1int;
|
|
4172
|
+
function k2sig(kBytes) {
|
|
4173
|
+
const k = bits2int(kBytes);
|
|
4174
|
+
if (!isWithinCurveOrder(k))
|
|
4175
|
+
return;
|
|
4176
|
+
const ik = invN(k);
|
|
4177
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
4178
|
+
const r = modN(q.x);
|
|
4179
|
+
if (r === _0n4)
|
|
4180
|
+
return;
|
|
4181
|
+
const s = modN(ik * modN(m + r * d));
|
|
4182
|
+
if (s === _0n4)
|
|
4183
|
+
return;
|
|
4184
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
4185
|
+
let normS = s;
|
|
4186
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
4187
|
+
normS = normalizeS(s);
|
|
4188
|
+
recovery ^= 1;
|
|
4189
|
+
}
|
|
4190
|
+
return new Signature(r, normS, recovery);
|
|
4191
|
+
}
|
|
4192
|
+
return { seed, k2sig };
|
|
4193
|
+
}
|
|
4194
|
+
const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
|
|
4195
|
+
const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
|
|
4196
|
+
function sign2(msgHash, privKey, opts = defaultSigOpts) {
|
|
4197
|
+
const { seed, k2sig } = prepSig(msgHash, privKey, opts);
|
|
4198
|
+
const C = CURVE;
|
|
4199
|
+
const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
|
|
4200
|
+
return drbg(seed, k2sig);
|
|
4201
|
+
}
|
|
4202
|
+
Point.BASE._setWindowSize(8);
|
|
4203
|
+
function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
|
|
4204
|
+
const sg = signature;
|
|
4205
|
+
msgHash = ensureBytes("msgHash", msgHash);
|
|
4206
|
+
publicKey = ensureBytes("publicKey", publicKey);
|
|
4207
|
+
const { lowS, prehash, format } = opts;
|
|
4208
|
+
validateSigVerOpts(opts);
|
|
4209
|
+
if ("strict" in opts)
|
|
4210
|
+
throw new Error("options.strict was renamed to lowS");
|
|
4211
|
+
if (format !== void 0 && format !== "compact" && format !== "der")
|
|
4212
|
+
throw new Error("format must be compact or der");
|
|
4213
|
+
const isHex2 = typeof sg === "string" || isBytes3(sg);
|
|
4214
|
+
const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
|
|
4215
|
+
if (!isHex2 && !isObj)
|
|
4216
|
+
throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
|
|
4217
|
+
let _sig = void 0;
|
|
4218
|
+
let P;
|
|
4219
|
+
try {
|
|
4220
|
+
if (isObj)
|
|
4221
|
+
_sig = new Signature(sg.r, sg.s);
|
|
4222
|
+
if (isHex2) {
|
|
4223
|
+
try {
|
|
4224
|
+
if (format !== "compact")
|
|
4225
|
+
_sig = Signature.fromDER(sg);
|
|
4226
|
+
} catch (derError) {
|
|
4227
|
+
if (!(derError instanceof DER.Err))
|
|
4228
|
+
throw derError;
|
|
4229
|
+
}
|
|
4230
|
+
if (!_sig && format !== "der")
|
|
4231
|
+
_sig = Signature.fromCompact(sg);
|
|
4232
|
+
}
|
|
4233
|
+
P = Point.fromHex(publicKey);
|
|
4234
|
+
} catch (error) {
|
|
4235
|
+
return false;
|
|
4236
|
+
}
|
|
4237
|
+
if (!_sig)
|
|
4238
|
+
return false;
|
|
4239
|
+
if (lowS && _sig.hasHighS())
|
|
4240
|
+
return false;
|
|
4241
|
+
if (prehash)
|
|
4242
|
+
msgHash = CURVE.hash(msgHash);
|
|
4243
|
+
const { r, s } = _sig;
|
|
4244
|
+
const h = bits2int_modN(msgHash);
|
|
4245
|
+
const is = invN(s);
|
|
4246
|
+
const u1 = modN(h * is);
|
|
4247
|
+
const u2 = modN(r * is);
|
|
4248
|
+
const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
|
|
4249
|
+
if (!R)
|
|
4250
|
+
return false;
|
|
4251
|
+
const v = modN(R.x);
|
|
4252
|
+
return v === r;
|
|
4253
|
+
}
|
|
4254
|
+
return {
|
|
4255
|
+
CURVE,
|
|
4256
|
+
getPublicKey,
|
|
4257
|
+
getSharedSecret,
|
|
4258
|
+
sign: sign2,
|
|
4259
|
+
verify,
|
|
4260
|
+
ProjectivePoint: Point,
|
|
4261
|
+
Signature,
|
|
4262
|
+
utils
|
|
4263
|
+
};
|
|
4264
|
+
}
|
|
4265
|
+
|
|
4266
|
+
// node_modules/@noble/curves/esm/_shortw_utils.js
|
|
4267
|
+
function getHash(hash) {
|
|
4268
|
+
return {
|
|
4269
|
+
hash,
|
|
4270
|
+
hmac: (key, ...msgs) => hmac(hash, key, concatBytes2(...msgs)),
|
|
4271
|
+
randomBytes
|
|
4272
|
+
};
|
|
4273
|
+
}
|
|
4274
|
+
function createCurve(curveDef, defHash) {
|
|
4275
|
+
const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });
|
|
4276
|
+
return { ...create(defHash), create };
|
|
4277
|
+
}
|
|
4278
|
+
|
|
4279
|
+
// node_modules/@noble/curves/esm/secp256k1.js
|
|
4280
|
+
var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
|
|
4281
|
+
var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
|
|
4282
|
+
var _0n5 = BigInt(0);
|
|
4283
|
+
var _1n5 = BigInt(1);
|
|
4284
|
+
var _2n3 = BigInt(2);
|
|
4285
|
+
var divNearest = (a, b) => (a + b / _2n3) / b;
|
|
4286
|
+
function sqrtMod(y) {
|
|
4287
|
+
const P = secp256k1P;
|
|
4288
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
4289
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
4290
|
+
const b2 = y * y * y % P;
|
|
4291
|
+
const b3 = b2 * b2 * y % P;
|
|
4292
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
4293
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
4294
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
4295
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
4296
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
4297
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
4298
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
4299
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
4300
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
4301
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
4302
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
4303
|
+
const root = pow2(t2, _2n3, P);
|
|
4304
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
4305
|
+
throw new Error("Cannot find square root");
|
|
4306
|
+
return root;
|
|
4307
|
+
}
|
|
4308
|
+
var Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
|
|
4309
|
+
var secp256k1 = createCurve({
|
|
4310
|
+
a: _0n5,
|
|
4311
|
+
b: BigInt(7),
|
|
4312
|
+
Fp: Fpk1,
|
|
4313
|
+
n: secp256k1N,
|
|
4314
|
+
Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
|
|
4315
|
+
Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
|
|
4316
|
+
h: BigInt(1),
|
|
4317
|
+
lowS: true,
|
|
4318
|
+
// Allow only low-S signatures by default in sign() and verify()
|
|
4319
|
+
endo: {
|
|
4320
|
+
// Endomorphism, see above
|
|
4321
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
4322
|
+
splitScalar: (k) => {
|
|
4323
|
+
const n = secp256k1N;
|
|
4324
|
+
const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
|
|
4325
|
+
const b1 = -_1n5 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
|
|
4326
|
+
const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
|
|
4327
|
+
const b2 = a1;
|
|
4328
|
+
const POW_2_128 = BigInt("0x100000000000000000000000000000000");
|
|
4329
|
+
const c1 = divNearest(b2 * k, n);
|
|
4330
|
+
const c2 = divNearest(-b1 * k, n);
|
|
4331
|
+
let k1 = mod(k - c1 * a1 - c2 * a2, n);
|
|
4332
|
+
let k2 = mod(-c1 * b1 - c2 * b2, n);
|
|
4333
|
+
const k1neg = k1 > POW_2_128;
|
|
4334
|
+
const k2neg = k2 > POW_2_128;
|
|
4335
|
+
if (k1neg)
|
|
4336
|
+
k1 = n - k1;
|
|
4337
|
+
if (k2neg)
|
|
4338
|
+
k2 = n - k2;
|
|
4339
|
+
if (k1 > POW_2_128 || k2 > POW_2_128) {
|
|
4340
|
+
throw new Error("splitScalar: Endomorphism failed, k=" + k);
|
|
4341
|
+
}
|
|
4342
|
+
return { k1neg, k1, k2neg, k2 };
|
|
4343
|
+
}
|
|
4344
|
+
}
|
|
4345
|
+
}, sha256);
|
|
4346
|
+
|
|
4347
|
+
// node_modules/@noble/hashes/esm/sha256.js
|
|
4348
|
+
var sha2562 = sha256;
|
|
4349
|
+
|
|
4350
|
+
// node_modules/@noble/hashes/esm/sha512.js
|
|
4351
|
+
var sha5122 = sha512;
|
|
4352
|
+
|
|
4353
|
+
// src/payload/ecies.ts
|
|
4354
|
+
function hexToBytes3(hex) {
|
|
4355
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
4356
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
4357
|
+
bytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
|
4358
|
+
}
|
|
4359
|
+
return bytes;
|
|
4360
|
+
}
|
|
4361
|
+
function bytesToHex2(bytes) {
|
|
4362
|
+
let hex = "";
|
|
4363
|
+
for (const b of bytes) {
|
|
4364
|
+
hex += b.toString(16).padStart(2, "0");
|
|
4365
|
+
}
|
|
4366
|
+
return hex;
|
|
4367
|
+
}
|
|
4368
|
+
function deriveKeys(sharedSecret) {
|
|
4369
|
+
const hash = sha5122(sharedSecret);
|
|
4370
|
+
return {
|
|
4371
|
+
encKey: hash.slice(0, 32),
|
|
4372
|
+
macKey: hash.slice(32)
|
|
4373
|
+
};
|
|
4374
|
+
}
|
|
4375
|
+
async function encryptWithPublicKey(publicKey, message) {
|
|
4376
|
+
const pubKeyBytes = hexToBytes3(`04${publicKey}`);
|
|
4377
|
+
const ephemPrivKey = randomBytes(32);
|
|
4378
|
+
const ephemPubKey = secp256k1.getPublicKey(ephemPrivKey, false);
|
|
4379
|
+
const sharedPoint = secp256k1.getSharedSecret(ephemPrivKey, pubKeyBytes, true);
|
|
4380
|
+
const sharedSecret = sharedPoint.slice(1);
|
|
4381
|
+
const { encKey, macKey } = deriveKeys(sharedSecret);
|
|
4382
|
+
const iv = randomBytes(16);
|
|
4383
|
+
const plaintext = new TextEncoder().encode(message);
|
|
4384
|
+
const cipher = cbc(encKey, iv);
|
|
4385
|
+
const ciphertext = cipher.encrypt(plaintext);
|
|
4386
|
+
const macData = concatBytes2(iv, ephemPubKey, ciphertext);
|
|
4387
|
+
const mac = hmac(sha2562, macKey, macData);
|
|
4388
|
+
return {
|
|
4389
|
+
iv: bytesToHex2(iv),
|
|
4390
|
+
ephemPublicKey: bytesToHex2(ephemPubKey),
|
|
4391
|
+
ciphertext: bytesToHex2(ciphertext),
|
|
4392
|
+
mac: bytesToHex2(mac)
|
|
4393
|
+
};
|
|
4394
|
+
}
|
|
4395
|
+
function cipherStringify(encrypted) {
|
|
4396
|
+
const ephemPubKeyBytes = hexToBytes3(encrypted.ephemPublicKey);
|
|
4397
|
+
const compressed = secp256k1.ProjectivePoint.fromHex(ephemPubKeyBytes).toRawBytes(true);
|
|
4398
|
+
const iv = hexToBytes3(encrypted.iv);
|
|
4399
|
+
const mac = hexToBytes3(encrypted.mac);
|
|
4400
|
+
const ciphertext = hexToBytes3(encrypted.ciphertext);
|
|
4401
|
+
return bytesToHex2(concatBytes2(iv, compressed, mac, ciphertext));
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
// src/payload/errors.ts
|
|
4405
|
+
var PayloadError = class extends SdkError {
|
|
4406
|
+
constructor(message, options) {
|
|
4407
|
+
super(message, options);
|
|
4408
|
+
this.name = "PayloadError";
|
|
4409
|
+
}
|
|
4410
|
+
};
|
|
4411
|
+
|
|
4412
|
+
// src/payload/relay-identity.ts
|
|
4413
|
+
var import_neverthrow11 = require("neverthrow");
|
|
4414
|
+
var import_viem7 = require("viem");
|
|
4415
|
+
var import_accounts = require("viem/accounts");
|
|
4416
|
+
var import_zod6 = require("zod");
|
|
4417
|
+
var ZodRelayIdentitySchema = import_zod6.z.object({
|
|
4418
|
+
address: import_zod6.z.string().refine(import_viem7.isAddress, { message: "Invalid relay identity address" }),
|
|
4419
|
+
publicKey: import_zod6.z.string().refine((val) => (0, import_viem7.isHex)(`0x${val}`), {
|
|
4420
|
+
message: "Invalid relay identity public key"
|
|
4421
|
+
}),
|
|
4422
|
+
privateKey: import_zod6.z.string().refine(import_viem7.isHex, { message: "Invalid relay identity private key" })
|
|
4423
|
+
});
|
|
4424
|
+
var STORAGE_KEY = "@P2PME:RELAY_IDENTITY";
|
|
4425
|
+
function createRelayIdentity() {
|
|
4426
|
+
const privateKey = (0, import_accounts.generatePrivateKey)();
|
|
4427
|
+
const account = (0, import_accounts.privateKeyToAccount)(privateKey);
|
|
4428
|
+
const rawPubKey = account.publicKey;
|
|
4429
|
+
const publicKey = rawPubKey.slice(4);
|
|
4430
|
+
const identity = {
|
|
4431
|
+
address: account.address,
|
|
4432
|
+
publicKey,
|
|
4433
|
+
privateKey
|
|
4434
|
+
};
|
|
4435
|
+
localStorage.setItem(STORAGE_KEY, JSON.stringify(identity));
|
|
4436
|
+
return identity;
|
|
4437
|
+
}
|
|
4438
|
+
function getRelayIdentity() {
|
|
4439
|
+
const data = localStorage.getItem(STORAGE_KEY);
|
|
4440
|
+
if (!data) {
|
|
4441
|
+
return (0, import_neverthrow11.ok)(createRelayIdentity());
|
|
4442
|
+
}
|
|
4443
|
+
let parsed;
|
|
4444
|
+
try {
|
|
4445
|
+
parsed = JSON.parse(data);
|
|
4446
|
+
} catch {
|
|
4447
|
+
return (0, import_neverthrow11.ok)(createRelayIdentity());
|
|
4448
|
+
}
|
|
4449
|
+
const result = validate(
|
|
4450
|
+
ZodRelayIdentitySchema,
|
|
4451
|
+
parsed,
|
|
4452
|
+
(message, cause, d) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data: d } })
|
|
4453
|
+
);
|
|
4454
|
+
if (result.isErr()) {
|
|
4455
|
+
return (0, import_neverthrow11.ok)(createRelayIdentity());
|
|
4456
|
+
}
|
|
4457
|
+
return result;
|
|
4458
|
+
}
|
|
4459
|
+
|
|
4460
|
+
// src/payload/crypto.ts
|
|
4461
|
+
function encryptPaymentAddress(paymentAddress, encryptionPublicKey) {
|
|
4462
|
+
return (0, import_neverthrow12.safeTry)(async function* () {
|
|
4463
|
+
const relayIdentity = yield* getRelayIdentity().mapErr(
|
|
4464
|
+
(e) => new PayloadError(`Relay identity error: ${e.message}`, {
|
|
4465
|
+
code: "ENCRYPTION_ERROR",
|
|
4466
|
+
cause: e
|
|
4467
|
+
})
|
|
4468
|
+
);
|
|
4469
|
+
const messageHash = (0, import_viem8.keccak256)((0, import_viem8.stringToHex)(paymentAddress));
|
|
4470
|
+
const signResult = yield* import_neverthrow12.ResultAsync.fromPromise(
|
|
4471
|
+
(0, import_accounts2.sign)({ hash: messageHash, privateKey: relayIdentity.privateKey }),
|
|
4472
|
+
(error) => new PayloadError(
|
|
4473
|
+
`Signing error: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
4474
|
+
{ code: "ENCRYPTION_ERROR", cause: error }
|
|
4475
|
+
)
|
|
4476
|
+
);
|
|
4477
|
+
const signature = (0, import_viem8.serializeSignature)(signResult);
|
|
4478
|
+
const payload = { message: paymentAddress, signature };
|
|
4479
|
+
const encrypted = yield* import_neverthrow12.ResultAsync.fromPromise(
|
|
4480
|
+
encryptWithPublicKey(encryptionPublicKey, JSON.stringify(payload)),
|
|
4481
|
+
(error) => new PayloadError(
|
|
4482
|
+
`Encryption error: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
4483
|
+
{ code: "ENCRYPTION_ERROR", cause: error }
|
|
4484
|
+
)
|
|
4485
|
+
);
|
|
4486
|
+
const safeCipherStringify = import_neverthrow12.Result.fromThrowable(
|
|
4487
|
+
(encryptedData) => cipherStringify(encryptedData),
|
|
4488
|
+
(error) => new PayloadError(
|
|
4489
|
+
`Stringify error: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
4490
|
+
{ code: "ENCRYPTION_ERROR", cause: error }
|
|
4491
|
+
)
|
|
4492
|
+
);
|
|
4493
|
+
const stringified = yield* safeCipherStringify(encrypted);
|
|
4494
|
+
return (0, import_neverthrow12.ok)(stringified);
|
|
4495
|
+
});
|
|
4496
|
+
}
|
|
4497
|
+
var ZodEncryptedDataSchema = import_zod7.z.object({
|
|
4498
|
+
ciphertext: import_zod7.z.string(),
|
|
4499
|
+
iv: import_zod7.z.string(),
|
|
4500
|
+
mac: import_zod7.z.string(),
|
|
4501
|
+
ephemPublicKey: import_zod7.z.string()
|
|
4502
|
+
});
|
|
4503
|
+
|
|
4504
|
+
// src/payload/validation.ts
|
|
4505
|
+
var import_zod8 = require("zod");
|
|
4506
|
+
var ZodPlaceOrderParamsSchema = import_zod8.z.object({
|
|
4507
|
+
amount: import_zod8.z.bigint(),
|
|
4508
|
+
recipientAddr: ZodAddressSchema,
|
|
4509
|
+
orderType: import_zod8.z.number().int().min(0).max(2),
|
|
4510
|
+
currency: ZodCurrencySchema,
|
|
4511
|
+
fiatAmount: import_zod8.z.bigint(),
|
|
4512
|
+
user: ZodAddressSchema,
|
|
4513
|
+
pubKey: import_zod8.z.string().optional(),
|
|
4514
|
+
preferredPaymentChannelConfigId: import_zod8.z.bigint().optional(),
|
|
4515
|
+
fiatAmountLimit: import_zod8.z.bigint().optional().default(0n)
|
|
4516
|
+
});
|
|
4517
|
+
var ZodSetSellOrderUpiParamsSchema = import_zod8.z.object({
|
|
4518
|
+
orderId: import_zod8.z.number().int().nonnegative(),
|
|
4519
|
+
paymentAddress: import_zod8.z.string().min(1),
|
|
4520
|
+
merchantPublicKey: import_zod8.z.string().min(1),
|
|
4521
|
+
updatedAmount: import_zod8.z.bigint()
|
|
4522
|
+
});
|
|
4523
|
+
|
|
4524
|
+
// src/payload/actions.ts
|
|
4525
|
+
function buildPlaceOrderPayload(orderRouter, params) {
|
|
4526
|
+
const validation = validate(
|
|
4527
|
+
ZodPlaceOrderParamsSchema,
|
|
4528
|
+
params,
|
|
4529
|
+
(message, cause, data) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data } })
|
|
4530
|
+
);
|
|
4531
|
+
if (validation.isErr()) {
|
|
4532
|
+
return (0, import_neverthrow13.errAsync)(validation.error);
|
|
4533
|
+
}
|
|
4534
|
+
const v = validation.value;
|
|
4535
|
+
const isBuy = v.orderType === ORDER_TYPE.BUY;
|
|
4536
|
+
const pcConfigId = v.preferredPaymentChannelConfigId ?? 0n;
|
|
4537
|
+
const circleResult = orderRouter.selectCircle({
|
|
4538
|
+
currency: v.currency,
|
|
4539
|
+
user: v.user,
|
|
4540
|
+
usdtAmount: v.amount,
|
|
4541
|
+
fiatAmount: v.fiatAmount,
|
|
4542
|
+
orderType: BigInt(v.orderType),
|
|
4543
|
+
preferredPCConfigId: pcConfigId
|
|
4544
|
+
});
|
|
4545
|
+
const relayResult = getRelayIdentity();
|
|
4546
|
+
if (relayResult.isErr()) {
|
|
4547
|
+
return (0, import_neverthrow13.errAsync)(relayResult.error);
|
|
4548
|
+
}
|
|
4549
|
+
const common = {
|
|
4550
|
+
amount: v.amount,
|
|
4551
|
+
recipientAddr: v.recipientAddr,
|
|
4552
|
+
orderType: v.orderType,
|
|
4553
|
+
userUpi: "",
|
|
4554
|
+
currency: v.currency,
|
|
4555
|
+
preferredPaymentChannelConfigId: pcConfigId,
|
|
4556
|
+
fiatAmountLimit: v.fiatAmountLimit
|
|
4557
|
+
};
|
|
4558
|
+
const pubKeyValue = v.pubKey ?? relayResult.value.publicKey;
|
|
4559
|
+
return circleResult.map((circleId) => ({
|
|
4560
|
+
...common,
|
|
4561
|
+
pubKey: isBuy ? pubKeyValue : "",
|
|
4562
|
+
userPubKey: isBuy ? "" : pubKeyValue,
|
|
4563
|
+
circleId
|
|
4564
|
+
})).mapErr(
|
|
4565
|
+
(e) => new PayloadError(e.message, {
|
|
4566
|
+
code: "CIRCLE_SELECTION_ERROR",
|
|
4567
|
+
cause: e
|
|
4568
|
+
})
|
|
4569
|
+
);
|
|
4570
|
+
}
|
|
4571
|
+
function buildSetSellOrderUpiPayload(params) {
|
|
4572
|
+
const validation = validate(
|
|
4573
|
+
ZodSetSellOrderUpiParamsSchema,
|
|
4574
|
+
params,
|
|
4575
|
+
(message, cause, data) => new PayloadError(message, { code: "VALIDATION_ERROR", cause, context: { data } })
|
|
4576
|
+
);
|
|
4577
|
+
if (validation.isErr()) {
|
|
4578
|
+
return (0, import_neverthrow13.errAsync)(validation.error);
|
|
4579
|
+
}
|
|
4580
|
+
const v = validation.value;
|
|
4581
|
+
return encryptPaymentAddress(v.paymentAddress, v.merchantPublicKey).map((userEncUpi) => ({
|
|
4582
|
+
orderId: v.orderId,
|
|
4583
|
+
userEncUpi,
|
|
4584
|
+
updatedAmount: v.updatedAmount
|
|
4585
|
+
}));
|
|
4586
|
+
}
|
|
4587
|
+
|
|
4588
|
+
// src/payload/client.ts
|
|
4589
|
+
function createPayloadGenerator(config) {
|
|
4590
|
+
return {
|
|
4591
|
+
placeOrder(params) {
|
|
4592
|
+
return buildPlaceOrderPayload(config.orderRouter, params);
|
|
4593
|
+
},
|
|
4594
|
+
setSellOrderUpi(params) {
|
|
4595
|
+
return buildSetSellOrderUpiPayload(params);
|
|
4596
|
+
}
|
|
4597
|
+
};
|
|
4598
|
+
}
|
|
4599
|
+
|
|
4600
|
+
// src/profile/contracts/actions.ts
|
|
4601
|
+
var import_neverthrow14 = require("neverthrow");
|
|
4602
|
+
var import_viem9 = require("viem");
|
|
4603
|
+
function getBalances(publicClient, usdcAddress, diamondAddress, params) {
|
|
4604
|
+
return validate(
|
|
4605
|
+
ZodGetBalancesParamsSchema,
|
|
4606
|
+
params,
|
|
4607
|
+
(message, cause, data) => new ProfileError(message, {
|
|
4608
|
+
code: "VALIDATION_ERROR",
|
|
4609
|
+
cause,
|
|
4610
|
+
context: { params: data }
|
|
4611
|
+
})
|
|
4612
|
+
).asyncAndThen(
|
|
4613
|
+
(validated) => import_neverthrow14.ResultAsync.combine([
|
|
4614
|
+
getUsdcBalance(publicClient, usdcAddress, {
|
|
4615
|
+
address: validated.address
|
|
4616
|
+
}),
|
|
4617
|
+
getPriceConfig(publicClient, diamondAddress, {
|
|
4618
|
+
currency: validated.currency
|
|
4619
|
+
})
|
|
4620
|
+
]).map(([usdc, priceConfig]) => {
|
|
4621
|
+
const usdcFormatted = Number((0, import_viem9.formatUnits)(usdc, 6));
|
|
4622
|
+
const sellPriceFormatted = Number((0, import_viem9.formatUnits)(priceConfig.sellPrice, 6));
|
|
4623
|
+
return {
|
|
4624
|
+
usdc: usdcFormatted,
|
|
4625
|
+
fiat: usdcFormatted * sellPriceFormatted,
|
|
4626
|
+
sellPrice: sellPriceFormatted
|
|
4627
|
+
};
|
|
4628
|
+
})
|
|
4629
|
+
);
|
|
4630
|
+
}
|
|
4631
|
+
|
|
4632
|
+
// src/profile/client.ts
|
|
4633
|
+
function createProfile(config) {
|
|
4634
|
+
const { publicClient, diamondAddress, usdcAddress } = config;
|
|
4635
|
+
return {
|
|
4636
|
+
getUsdcBalance: (params) => getUsdcBalance(publicClient, usdcAddress, params),
|
|
4637
|
+
getPriceConfig: (params) => getPriceConfig(publicClient, diamondAddress, params),
|
|
4638
|
+
getBalances: (params) => getBalances(publicClient, usdcAddress, diamondAddress, params),
|
|
4639
|
+
getTxLimits: (params) => getTxLimits(publicClient, diamondAddress, params),
|
|
4640
|
+
getRpPerUsdtLimitRational: (params) => getRpPerUsdtLimitRational(publicClient, diamondAddress, params)
|
|
4641
|
+
};
|
|
4642
|
+
}
|
|
4643
|
+
|
|
4644
|
+
// src/zkkyc/client.ts
|
|
4645
|
+
function createZkkyc(config) {
|
|
4646
|
+
const { reputationManagerAddress } = config;
|
|
4647
|
+
return {
|
|
4648
|
+
prepareSocialVerify: (params) => prepareSocialVerify(reputationManagerAddress, params),
|
|
4649
|
+
prepareSubmitAnonAadharProof: (params) => prepareSubmitAnonAadharProof(reputationManagerAddress, params),
|
|
4650
|
+
prepareZkPassportRegister: (params) => prepareZkPassportRegister(reputationManagerAddress, params)
|
|
4651
|
+
};
|
|
4652
|
+
}
|
|
4653
|
+
|
|
4654
|
+
// src/react/sdk-provider.tsx
|
|
4655
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
4656
|
+
var SdkContext = (0, import_react.createContext)(null);
|
|
4657
|
+
function SdkProvider({ children, ...config }) {
|
|
4658
|
+
const publicClientRef = (0, import_react.useRef)(config.publicClient);
|
|
4659
|
+
const loggerRef = (0, import_react.useRef)(config.logger);
|
|
4660
|
+
const publicClient = publicClientRef.current;
|
|
4661
|
+
const logger = loggerRef.current;
|
|
4662
|
+
const fraudEngineApiUrl = config.fraudEngine?.apiUrl;
|
|
4663
|
+
const fraudEngineEncryptionKey = config.fraudEngine?.encryptionKey;
|
|
4664
|
+
const fraudEngineSeonRegion = config.fraudEngine?.seonRegion;
|
|
4665
|
+
const fraudEngine = (0, import_react.useMemo)(() => {
|
|
4666
|
+
if (!fraudEngineApiUrl || !fraudEngineEncryptionKey) return void 0;
|
|
4667
|
+
return createFraudEngine({
|
|
4668
|
+
apiUrl: fraudEngineApiUrl,
|
|
4669
|
+
encryptionKey: fraudEngineEncryptionKey,
|
|
4670
|
+
seonRegion: fraudEngineSeonRegion,
|
|
4671
|
+
logger
|
|
4672
|
+
});
|
|
4673
|
+
}, [fraudEngineApiUrl, fraudEngineEncryptionKey, fraudEngineSeonRegion, logger]);
|
|
4674
|
+
const initedRef = (0, import_react.useRef)(null);
|
|
4675
|
+
(0, import_react.useEffect)(() => {
|
|
4676
|
+
if (!fraudEngine) return;
|
|
4677
|
+
if (initedRef.current === fraudEngine) return;
|
|
4678
|
+
initedRef.current = fraudEngine;
|
|
4679
|
+
fraudEngine.init();
|
|
4680
|
+
}, [fraudEngine]);
|
|
4681
|
+
const sdk = (0, import_react.useMemo)(() => {
|
|
4682
|
+
const orderRouter = createOrderRouter({
|
|
4683
|
+
publicClient,
|
|
4684
|
+
subgraphUrl: config.subgraphUrl,
|
|
4685
|
+
contractAddress: config.diamondAddress,
|
|
4686
|
+
logger
|
|
4687
|
+
});
|
|
4688
|
+
return {
|
|
4689
|
+
profile: createProfile({
|
|
4690
|
+
publicClient,
|
|
4691
|
+
diamondAddress: config.diamondAddress,
|
|
4692
|
+
usdcAddress: config.usdcAddress
|
|
4693
|
+
}),
|
|
4694
|
+
orderRouter,
|
|
4695
|
+
payload: createPayloadGenerator({ orderRouter }),
|
|
4696
|
+
zkkyc: config.reputationManagerAddress ? createZkkyc({
|
|
4697
|
+
reputationManagerAddress: config.reputationManagerAddress
|
|
4698
|
+
}) : void 0,
|
|
4699
|
+
fraudEngine
|
|
4700
|
+
};
|
|
4701
|
+
}, [
|
|
4702
|
+
publicClient,
|
|
4703
|
+
config.subgraphUrl,
|
|
4704
|
+
config.diamondAddress,
|
|
4705
|
+
config.usdcAddress,
|
|
4706
|
+
config.reputationManagerAddress,
|
|
4707
|
+
logger,
|
|
4708
|
+
fraudEngine
|
|
4709
|
+
]);
|
|
4710
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SdkContext.Provider, { value: sdk, children });
|
|
4711
|
+
}
|
|
4712
|
+
function useSdk() {
|
|
4713
|
+
const sdk = (0, import_react.useContext)(SdkContext);
|
|
4714
|
+
if (!sdk) {
|
|
4715
|
+
throw new Error("useSdk must be used within a <SdkProvider>");
|
|
4716
|
+
}
|
|
4717
|
+
return sdk;
|
|
4718
|
+
}
|
|
4719
|
+
function useProfile() {
|
|
4720
|
+
return useSdk().profile;
|
|
4721
|
+
}
|
|
4722
|
+
function useOrderRouter() {
|
|
4723
|
+
return useSdk().orderRouter;
|
|
4724
|
+
}
|
|
4725
|
+
function usePayloadGenerator() {
|
|
4726
|
+
return useSdk().payload;
|
|
4727
|
+
}
|
|
4728
|
+
function useZkkyc() {
|
|
4729
|
+
const zkkyc = useSdk().zkkyc;
|
|
4730
|
+
if (!zkkyc) {
|
|
4731
|
+
throw new Error("useZkkyc requires reputationManagerAddress to be passed to SdkProvider");
|
|
4732
|
+
}
|
|
4733
|
+
return zkkyc;
|
|
4734
|
+
}
|
|
4735
|
+
function useFraudEngine() {
|
|
4736
|
+
const fraudEngine = useSdk().fraudEngine;
|
|
4737
|
+
if (!fraudEngine) {
|
|
4738
|
+
throw new Error("useFraudEngine requires fraudEngine config to be passed to SdkProvider");
|
|
4739
|
+
}
|
|
4740
|
+
return fraudEngine;
|
|
4741
|
+
}
|
|
4742
|
+
|
|
4743
|
+
// src/fraud-engine/react/use-fingerprint.ts
|
|
4744
|
+
var import_react2 = require("react");
|
|
4745
|
+
function useFingerprint(enabled) {
|
|
4746
|
+
const [data, setData] = (0, import_react2.useState)(null);
|
|
4747
|
+
const [error, setError] = (0, import_react2.useState)(null);
|
|
4748
|
+
const [isLoading, setIsLoading] = (0, import_react2.useState)(false);
|
|
4749
|
+
(0, import_react2.useEffect)(() => {
|
|
4750
|
+
if (!enabled) return;
|
|
4751
|
+
let cancelled = false;
|
|
4752
|
+
setIsLoading(true);
|
|
4753
|
+
(async () => {
|
|
4754
|
+
try {
|
|
4755
|
+
await loadFingerprintAgent();
|
|
4756
|
+
const result = await getFingerprint(5e3);
|
|
4757
|
+
if (!cancelled) {
|
|
4758
|
+
setData(result);
|
|
4759
|
+
setError(null);
|
|
4760
|
+
}
|
|
4761
|
+
} catch (e) {
|
|
4762
|
+
if (!cancelled) {
|
|
4763
|
+
setError(e instanceof Error ? e : new Error(String(e)));
|
|
4764
|
+
setData(null);
|
|
4765
|
+
}
|
|
4766
|
+
} finally {
|
|
4767
|
+
if (!cancelled) setIsLoading(false);
|
|
4768
|
+
}
|
|
4769
|
+
})();
|
|
4770
|
+
return () => {
|
|
4771
|
+
cancelled = true;
|
|
4772
|
+
};
|
|
4773
|
+
}, [enabled]);
|
|
4774
|
+
return { data, error, isLoading };
|
|
4775
|
+
}
|
|
4776
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
4777
|
+
0 && (module.exports = {
|
|
4778
|
+
SdkProvider,
|
|
4779
|
+
useFingerprint,
|
|
4780
|
+
useFraudEngine,
|
|
4781
|
+
useOrderRouter,
|
|
4782
|
+
usePayloadGenerator,
|
|
4783
|
+
useProfile,
|
|
4784
|
+
useSdk,
|
|
4785
|
+
useZkkyc
|
|
4786
|
+
});
|
|
4787
|
+
/*! Bundled license information:
|
|
4788
|
+
|
|
4789
|
+
@noble/ciphers/esm/utils.js:
|
|
4790
|
+
(*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
|
|
4791
|
+
|
|
4792
|
+
@noble/hashes/esm/utils.js:
|
|
4793
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
4794
|
+
|
|
4795
|
+
@noble/curves/esm/abstract/utils.js:
|
|
4796
|
+
@noble/curves/esm/abstract/modular.js:
|
|
4797
|
+
@noble/curves/esm/abstract/curve.js:
|
|
4798
|
+
@noble/curves/esm/abstract/weierstrass.js:
|
|
4799
|
+
@noble/curves/esm/_shortw_utils.js:
|
|
4800
|
+
@noble/curves/esm/secp256k1.js:
|
|
4801
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
4802
|
+
*/
|
|
4803
|
+
//# sourceMappingURL=react.cjs.map
|