-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathchanges.patch
More file actions
350 lines (339 loc) · 25.9 KB
/
changes.patch
File metadata and controls
350 lines (339 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
diff --git a/ts/src/settle.ts b/ts/src/settle.ts
index 8b9df58..6bec791 100644
--- a/ts/src/settle.ts
+++ b/ts/src/settle.ts
@@ -1,10 +1,9 @@
import { ethers } from "ethers";
-import { ServiceHelper, get_mongoose_db, get_contract_addr, get_image_md5, modelBundle, get_settle_private_account, get_chain_id } from "./config.js";
+import { ServiceHelper, get_mongoose_db, get_contract_addr, get_image_md5, modelBundle, get_settle_private_account } from "./config.js";
import abiData from './Proxy.json' assert { type: 'json' };
import mongoose from 'mongoose';
-import { ZkWasmUtil, PaginationResult, QueryParams, Task, VerifyProofParams, AutoSubmitStatus, Round1Status, Round1Info } from "zkwasm-service-helper";
+import { PaginationResult, QueryParams, Task} from "zkwasm-service-helper";
import { U8ArrayUtil } from './lib.js';
-import { submitRawProof} from "./prover.js";
import { decodeWithdraw} from "./convention.js";
import dotenv from 'dotenv';
import { provider, getMerkle } from "./contract.js";
@@ -15,35 +14,8 @@ const signer = new ethers.Wallet(get_settle_private_account(), provider);
//
const constants = {
proxyAddress: get_contract_addr(),
- chainId: get_chain_id(),
};
-function convertToBigUint64Array(combinedRoot: bigint): BigUint64Array {
- const result = new BigUint64Array(4);
-
- for (let i = 3; i >= 0; i--) {
- result[i] = combinedRoot & BigInt(2n ** 64n - 1n);
- combinedRoot = combinedRoot >> 64n;
- }
-
- return result;
-}
-
-export async function getMerkleArray(): Promise<BigUint64Array>{
- // Connect to the Proxy contract
- const proxy = new ethers.Contract(constants.proxyAddress, abiData.abi, provider);
- // Fetch the proxy information
- let proxyInfo = await proxy.getProxyInfo();
- console.log("Proxy Info:", proxyInfo);
- // Extract the old Merkle root
- const oldRoot = proxyInfo.merkle_root;
- console.log("Type of oldRoot:", typeof oldRoot);
- console.log("Old Merkle Root:", oldRoot);
- console.log("Settle:Old Merkle Root in u64:",convertToBigUint64Array(oldRoot));
-
- return convertToBigUint64Array(oldRoot);
-}
-
mongoose.connect(get_mongoose_db(), {
//useNewUrlParser: true,
//useUnifiedTopology: true,
@@ -53,15 +25,15 @@ const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {console.log("Connected to the database")});
-async function getTask(taskid: string, d_state: string|null): Promise<Task> {
+async function getTask(taskid: string, d_state: string|null) {
const queryParams: QueryParams = {
- id: taskid,
- tasktype: "Prove",
- taskstatus: d_state,
- user_address: null,
- md5: get_image_md5(),
- total: 1,
- };
+ id: taskid,
+ tasktype: "Prove",
+ taskstatus: d_state,
+ user_address: null,
+ md5: get_image_md5(),
+ total: 1,
+ };
const response: PaginationResult<Task[]> = await ServiceHelper.loadTasks(
queryParams
@@ -70,15 +42,10 @@ async function getTask(taskid: string, d_state: string|null): Promise<Task> {
return response.data[0];
}
-async function getTaskWithTimeout(taskId: string, timeout: number): Promise<Task | null> {
- return Promise.race([
- getTask(taskId, "Done"),
- new Promise(
- (resolve:(v:null)=>void, reject) => setTimeout(
- () => reject(new Error('load proof task Timeout exceeded')), timeout
- )
- )
- ]);
+async function getTaskWithTimeout(taskId: string, timeout: number): Promise<any> {
+ return Promise.race([getTask(taskId, "Done"), new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('load proof task Timeout exceeded')), timeout))
+ ]);
}
export async function getWithdrawEventParameters(
@@ -100,8 +67,8 @@ export async function getWithdrawEventParameters(
if (decoded) {
const l1token = decoded.args.l1token;
const l1account = decoded.args.l1account;
- const amount = decoded.args.amount; //in Wei
- //console.log({ l1token, l1account, amount });
+ const amount = decoded.args.amount; //in Wei
+ //console.log({ l1token, l1account, amount });
r.push({
token: l1token,
address: l1account,
@@ -113,155 +80,90 @@ export async function getWithdrawEventParameters(
console.error("Log does not match event signature:", error);
}
});
+
} catch (error) {
console.error('Error retrieving withdraw event parameters:', error);
}
return r;
}
-/* We encode all params in string format of BN */
-interface ProofArgs {
- txData: Uint8Array,
- proofArr: Array<string>,
- verifyInstanceArr: Array<string>,
- auxArr: Array<string>,
- instArr: Array<string>,
-}
-
-async function prepareVerifyAttributesSingle(task: Task): Promise<ProofArgs> {
- let shadowInstances = task.shadow_instances;
- let batchInstances = task.batch_instances;
-
- let proofArr = new U8ArrayUtil(task.proof).toNumber();
- let auxArr = new U8ArrayUtil(task.aux).toNumber();
- let verifyInstancesArr = shadowInstances.length === 0
- ? new U8ArrayUtil(batchInstances).toNumber()
- : new U8ArrayUtil(shadowInstances).toNumber();
- let instArr = new U8ArrayUtil(task.instances).toNumber();
- console.log("txData_orig:", task.input_context);
- let txData = new Uint8Array(task.input_context);
- console.log("txData:", txData);
- console.log("txData.length:", txData.length);
- return {
- txData: txData,
- proofArr: proofArr,
- verifyInstanceArr: verifyInstancesArr,
- auxArr: auxArr,
- instArr: instArr,
- }
-}
-
-async function prepareVerifyAttributesBatch(task: Task): Promise<ProofArgs> {
- let txData = new Uint8Array(task.input_context);
- const round_1_info_response = await ServiceHelper.queryRound1Info({
- task_id: task._id.$oid,
- chain_id: constants.chainId,
- status: Round1Status.Batched,
- total: 1,
- });
-
- let shadowInstances = task.shadow_instances;
- let batchInstances = task.batch_instances;
-
- const round_1_output: Round1Info = round_1_info_response.data[0];
-
- let verifyInstancesArr = shadowInstances.length === 0
- ? new U8ArrayUtil(batchInstances).toNumber()
- : new U8ArrayUtil(shadowInstances).toNumber();
-
- const siblingInstances = new U8ArrayUtil(new Uint8Array(round_1_output.target_instances[0])).toNumber();
- const r1ShadowInstance = new U8ArrayUtil(new Uint8Array(round_1_output.shadow_instances!)).toNumber()[0];
-
- let instArr = new U8ArrayUtil(task.instances).toNumber();
-
- // Find the index of this proof in the round 1 output by comparing task_ids
- // This will be used to verify that this proof was included in a particular batch.
- // If it does not exist, the verification will fail
- const index = round_1_output.task_ids.findIndex(
- (id:any) => id === task._id["$oid"]
- );
-
- let proofArr = siblingInstances;
- proofArr.push(r1ShadowInstance);
-
- return {
- txData: txData,
- proofArr: proofArr,
- verifyInstanceArr: verifyInstancesArr,
- auxArr: [index.toString()],
- instArr: instArr,
- }
-}
-
-async function prepareVerifyAttributes(task: Task): Promise<ProofArgs> {
- if(task.proof_submit_mode == "Manual") {
- return await prepareVerifyAttributesSingle(task);
- } else {
- return await prepareVerifyAttributesBatch(task);
- }
-}
async function trySettle() {
let merkleRoot = await getMerkle();
console.log("typeof :", typeof(merkleRoot[0]));
console.log(merkleRoot);
- const proxy = new ethers.Contract(constants.proxyAddress, abiData.abi, signer);
-
try {
let record = await modelBundle.findOne({ merkleRoot: merkleRoot});
if (record) {
let taskId = record.taskId;
- let task = await getTaskWithTimeout(taskId, 60000);
- if (task!.proof_submit_mode == "Auto") {
- const isRegistered =
- task!.auto_submit_status === AutoSubmitStatus.RegisteredProof;
-
- if (!isRegistered) {
- console.log("waiting for proof to be registered ... ");
- return -1;
- }
+ let data0 = await getTaskWithTimeout(taskId, 60000);
+
+ //check failed or just timeout
+ if (data0.proof.length == 0) {
+ let data1 = await getTask(taskId, null);
+ if (data1.status === "DryRunFailed" || data1.status === "Unprovable") {
+ console.log("Crash(Need manual review): task failed with state:", taskId, data1.status, data1.input_context);
+ while(1); //This is serious error, while loop to trigger manual review.
+ return -1;
+ } else {
+ console.log(`Task: ${taskId}, ${data1.status}, retry settle later.`); //will restart settle
+ return -1;
+ }
}
-
- let attributes = await prepareVerifyAttributesSingle(task!);
+ let shadowInstances = data0.shadow_instances;
+ let batchInstances = data0.batch_instances;
+
+ let proofArr = new U8ArrayUtil(data0.proof).toNumber();
+ let auxArr = new U8ArrayUtil(data0.aux).toNumber();
+ let verifyInstancesArr = shadowInstances.length === 0
+ ? new U8ArrayUtil(batchInstances).toNumber()
+ : new U8ArrayUtil(shadowInstances).toNumber();
+ let instArr = new U8ArrayUtil(data0.instances).toNumber();
+ console.log("txData_orig:", data0.input_context);
+ let txData = new Uint8Array(data0.input_context);
+ console.log("txData:", txData);
+ console.log("txData.length:", txData.length);
+
+ const proxy = new ethers.Contract(constants.proxyAddress, abiData.abi, signer);
const tx = await proxy.verify(
- attributes.txData,
- attributes.proofArr,
- attributes.verifyInstanceArr,
- attributes.auxArr,
- [attributes.instArr],
+ txData,
+ proofArr,
+ verifyInstancesArr,
+ auxArr,
+ [instArr],
);
// wait for tx to be mined, can add no. of confirmations as arg
const receipt = await tx.wait();
console.log("transaction:", tx.hash);
console.log("receipt:", receipt);
- const r = decodeWithdraw(attributes.txData);
+ const r = decodeWithdraw(txData);
const s = await getWithdrawEventParameters(proxy, receipt);
const withdrawArray = [];
let status = 'Done';
if (r.length !== s.length) {
- status = 'Fail';
- console.error("Arrays have different lengths,",r,s);
+ status = 'Fail';
+ console.error("Arrays have different lengths,",r,s);
} else {
- for (let i = 0; i < r.length; i++) {
- const rItem = r[i];
- const sItem = s[i];
-
- if (rItem.address !== sItem.address || rItem.amount !== sItem.amount) {
- console.log("Crash(Need manual review):");
- console.error(`Mismatch found: ${rItem.address}:${rItem.amount} ${sItem.address}:${sItem.amount}`);
- while(1); //This is serious error, while loop to trigger manual review.
- status = 'Fail';
- break;
- } else {
- // Assuming rItem is defined and has address and amount
- record.withdrawArray.push({
- address: rItem.address,
- amount: rItem.amount,
- });
+ for (let i = 0; i < r.length; i++) {
+ const rItem = r[i];
+ const sItem = s[i];
+
+ if (rItem.address !== sItem.address || rItem.amount !== sItem.amount) {
+ console.log("Crash(Need manual review):");
+ console.error(`Mismatch found: ${rItem.address}:${rItem.amount} ${sItem.address}:${sItem.amount}`);
+ while(1); //This is serious error, while loop to trigger manual review.
+ status = 'Fail';
+ break;
+ } else {
+ // Assuming rItem is defined and has address and amount
+ record.withdrawArray.push({
+ address: rItem.address,
+ amount: rItem.amount,
+ });
+ }
}
- }
}
//update record
record.settleTxHash = tx.hash;
@@ -279,20 +181,20 @@ async function trySettle() {
// start monitoring and settle
async function main() {
- while (true) {
- try {
- await trySettle();
- } catch (error) {
- console.error("Error during trySettle:", error);
- }
- await new Promise(resolve => setTimeout(resolve, 60000));
- }
+ while (true) {
+ try {
+ await trySettle();
+ } catch (error) {
+ console.error("Error during trySettle:", error);
+ }
+ await new Promise(resolve => setTimeout(resolve, 60000));
+ }
}
// Check if this module is being run directly
if (import.meta.url === `file://${process.argv[1]}`) {
- console.log("Running settle.js directly");
- main().catch(console.error);
+ console.log("Running settle.js directly");
+ main().catch(console.error);
} else {
- console.log("settle.js is being imported as a module");
+ console.log("settle.js is being imported as a module");
}