-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathcoprocessorUtils.ts
More file actions
1324 lines (1198 loc) · 51.5 KB
/
coprocessorUtils.ts
File metadata and controls
1324 lines (1198 loc) · 51.5 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import dotenv from 'dotenv';
import type { ethers as EthersT } from 'ethers';
import { log2 } from 'extra-bigint';
import * as fs from 'fs';
import { ethers } from 'hardhat';
import { Database } from 'sqlite3';
import type { FheTypeInfo } from '../lib-js/common';
import { ALL_FHE_TYPE_INFOS } from '../lib-js/fheTypeInfos';
import { ALL_OPERATORS_PRICES } from '../lib-js/operatorsPrices';
const parsedEnvCoprocessor = dotenv.parse(fs.readFileSync('./fhevmTemp/addresses/.env.host'));
const coprocAddress = parsedEnvCoprocessor.FHEVM_EXECUTOR_CONTRACT_ADDRESS;
let firstBlockListening = 0;
let lastBlockSnapshot = 0;
let lastCounterRand = 0;
let counterRand = 0;
let chainId: number;
//const db = new Database('./sql.db'); // on-disk db for debugging
const db = new Database(':memory:');
export function insertSQL(handle: string, clearText: BigInt | string, replace: boolean = false) {
if (replace) {
// this is useful if using snapshots while sampling different random numbers on each revert
db.run('INSERT OR REPLACE INTO ciphertexts (handle, clearText) VALUES (?, ?)', [handle, clearText.toString()]);
} else {
db.run('INSERT OR IGNORE INTO ciphertexts (handle, clearText) VALUES (?, ?)', [handle, clearText.toString()]);
}
}
// Decrypt any handle, bypassing ACL
// WARNING : only for testing or internal use
export const getClearText = async (handle: string | bigint): Promise<string> => {
return new Promise((resolve, reject) => {
let attempts = 0;
const maxRetries = 100;
function executeQuery() {
db.get('SELECT clearText FROM ciphertexts WHERE handle = ?', [handle], (err, row) => {
if (err) {
reject(new Error(`Error querying database: ${err.message}`));
} else if (row) {
resolve((row as any).clearText);
} else if (attempts < maxRetries) {
attempts++;
executeQuery();
} else {
reject(new Error('No record found after maximum retries'));
}
});
}
executeQuery();
});
};
db.serialize(() => db.run('CREATE TABLE IF NOT EXISTS ciphertexts (handle BINARY PRIMARY KEY,clearText TEXT)'));
interface FHEVMEvent {
eventName: string;
args: EthersT.Result;
}
const NumBits = {
0: 1n, //ebool
2: 8n, //euint8
3: 16n, //euint16
4: 32n, //euint32
5: 64n, //euint64
6: 128n, //euint128
7: 160n, //eaddress
8: 256n, //euint256
};
export function numberToEvenHexString(num: number) {
if (typeof num !== 'number' || num < 0) {
throw new Error('Input should be a non-negative number.');
}
let hexString = num.toString(16);
if (hexString.length % 2 !== 0) {
hexString = '0' + hexString;
}
return hexString;
}
function getRandomBigInt(numBits: number): bigint {
if (numBits <= 0) {
throw new Error('Number of bits must be greater than 0');
}
const numBytes = Math.ceil(numBits / 8);
const randomBytes = new Uint8Array(numBytes);
crypto.getRandomValues(randomBytes);
let randomBigInt = BigInt(0);
for (let i = 0; i < numBytes; i++) {
randomBigInt = (randomBigInt << BigInt(8)) | BigInt(randomBytes[i]);
}
const mask = (BigInt(1) << BigInt(numBits)) - BigInt(1);
randomBigInt = randomBigInt & mask;
return randomBigInt;
}
function bitwiseNotUintBits(value: BigInt, numBits: number) {
if (typeof value !== 'bigint') {
throw new TypeError('The input value must be a BigInt.');
}
if (typeof numBits !== 'number' || numBits <= 0) {
throw new TypeError('The numBits parameter must be a positive integer.');
}
// Create the mask with numBits bits set to 1
const BIT_MASK = (BigInt(1) << BigInt(numBits)) - BigInt(1);
return ~value & BIT_MASK;
}
export const awaitCoprocessor = async (): Promise<void> => {
chainId = Number((await ethers.provider.getNetwork()).chainId);
await processAllPastFHEVMExecutorEvents();
};
const abi = [
'event FheAdd(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheSub(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheMul(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheDiv(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheRem(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheBitAnd(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheBitOr(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheBitXor(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheShl(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheShr(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheRotl(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheRotr(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheEq(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheEqBytes(address indexed caller, bytes32 lhs, bytes rhs, bytes1 scalarByte, bytes32 result)',
'event FheNe(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheNeBytes(address indexed caller, bytes32 lhs, bytes rhs, bytes1 scalarByte, bytes32 result)',
'event FheGe(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheGt(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheLe(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheLt(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheMin(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheMax(address indexed caller, bytes32 lhs, bytes32 rhs, bytes1 scalarByte, bytes32 result)',
'event FheNeg(address indexed caller, bytes32 ct, bytes32 result)',
'event FheNot(address indexed caller, bytes32 ct, bytes32 result)',
'event VerifyInput(address indexed caller, bytes32 inputHandle, address userAddress, bytes inputProof, uint8 inputType, bytes32 result)',
'event Cast(address indexed caller, bytes32 ct, uint8 toType, bytes32 result)',
'event TrivialEncrypt(address indexed caller, uint256 pt, uint8 toType, bytes32 result)',
'event TrivialEncryptBytes(address indexed caller, bytes pt, uint8 toType, bytes32 result)',
'event FheIfThenElse(address indexed caller, bytes32 control, bytes32 ifTrue, bytes32 ifFalse, bytes32 result)',
'event FheRand(address indexed caller, uint8 randType, bytes16 seed, bytes32 result)',
'event FheRandBounded(address indexed caller, uint256 upperBound, uint8 randType, bytes16 seed, bytes32 result)',
];
async function processAllPastFHEVMExecutorEvents() {
const provider = ethers.provider;
const latestBlockNumber = await provider.getBlockNumber();
if (process.env.SOLIDITY_COVERAGE !== 'true') {
// evm_snapshot is not supported in coverage mode
[lastBlockSnapshot, lastCounterRand] = await provider.send('get_lastBlockSnapshot');
if (lastBlockSnapshot < firstBlockListening) {
firstBlockListening = lastBlockSnapshot + 1;
counterRand = Number(lastCounterRand);
}
}
const contract = new ethers.Contract(coprocAddress, abi, provider);
// Fetch all events emitted by the contract
const filter = {
address: coprocAddress,
fromBlock: firstBlockListening,
toBlock: latestBlockNumber,
};
const logs = await provider.getLogs(filter);
const events: FHEVMEvent[] = logs
.map((log) => {
try {
const parsedLog = contract.interface.parseLog(log);
return {
eventName: parsedLog!.name,
args: parsedLog!.args,
};
} catch (e) {
// If the log cannot be parsed, skip it
return null;
}
})
.filter((event) => event !== null);
firstBlockListening = latestBlockNumber + 1;
if (process.env.SOLIDITY_COVERAGE !== 'true') {
// evm_snapshot is not supported in coverage mode
await provider.send('set_lastBlockSnapshot', [firstBlockListening]);
}
events.map(async (event) => await insertHandleFromEvent(event));
}
async function insertHandleFromEvent(event: FHEVMEvent) {
let handle;
let clearText;
let clearLHS;
let clearRHS;
let resultType: number;
let shift;
switch (event.eventName) {
case 'TrivialEncrypt':
clearText = event.args[1];
handle = ethers.toBeHex(event.args[3], 32);
insertSQL(handle, clearText);
break;
case 'TrivialEncryptBytes':
clearText = event.args[1];
handle = ethers.toBeHex(event.args[3], 32);
insertSQL(handle, BigInt(clearText));
break;
case 'FheAdd':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) + BigInt(event.args[2]);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) + BigInt(clearRHS);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(ethers.toBeHex(handle, 32), clearText);
break;
case 'FheSub':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) - BigInt(event.args[2]);
if (clearText < 0n) clearText = clearText + 2n ** NumBits[resultType as keyof typeof NumBits];
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) - BigInt(clearRHS);
if (clearText < 0n) clearText = clearText + 2n ** NumBits[resultType as keyof typeof NumBits];
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheMul':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) * BigInt(event.args[2]);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) * BigInt(clearRHS);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheDiv':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) / BigInt(event.args[2]);
} else {
throw new Error('Non-scalar div not implemented yet');
}
insertSQL(handle, clearText);
break;
case 'FheRem':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) % BigInt(event.args[2]);
} else {
throw new Error('Non-scalar rem not implemented yet');
}
insertSQL(handle, clearText);
break;
case 'FheBitAnd':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) & BigInt(event.args[2]);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) & BigInt(clearRHS);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheBitOr':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) | BigInt(event.args[2]);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) | BigInt(clearRHS);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheBitXor':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) ^ BigInt(event.args[2]);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) ^ BigInt(clearRHS);
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheShl':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) << BigInt(event.args[2]) % NumBits[resultType as keyof typeof NumBits];
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) << BigInt(clearRHS) % NumBits[resultType as keyof typeof NumBits];
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheShr':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) >> BigInt(event.args[2]) % NumBits[resultType as keyof typeof NumBits];
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) >> BigInt(clearRHS) % NumBits[resultType as keyof typeof NumBits];
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheRotl':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
shift = BigInt(event.args[2]) % NumBits[resultType as keyof typeof NumBits];
clearText =
(BigInt(clearLHS) << shift) | (BigInt(clearLHS) >> (NumBits[resultType as keyof typeof NumBits] - shift));
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
shift = BigInt(clearRHS) % NumBits[resultType as keyof typeof NumBits];
clearText =
(BigInt(clearLHS) << shift) | (BigInt(clearLHS) >> (NumBits[resultType as keyof typeof NumBits] - shift));
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheRotr':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
shift = BigInt(event.args[2]) % NumBits[resultType as keyof typeof NumBits];
clearText =
(BigInt(clearLHS) >> shift) | (BigInt(clearLHS) << (NumBits[resultType as keyof typeof NumBits] - shift));
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
} else {
clearRHS = await getClearText(event.args[2]);
shift = BigInt(clearRHS) % NumBits[resultType as keyof typeof NumBits];
clearText =
(BigInt(clearLHS) >> shift) | (BigInt(clearLHS) << (NumBits[resultType as keyof typeof NumBits] - shift));
clearText = clearText % 2n ** NumBits[resultType as keyof typeof NumBits];
}
insertSQL(handle, clearText);
break;
case 'FheEq':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) === BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = clearLHS === clearRHS ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheEqBytes':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) === BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) === BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheNe':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) !== BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) !== BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheNeBytes':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) !== BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) !== BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheGe':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) >= BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) >= BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheGt':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) > BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) > BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheLe':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) <= BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) <= BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheLt':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) < BigInt(event.args[2]) ? 1n : 0n;
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) < BigInt(clearRHS) ? 1n : 0n;
}
insertSQL(handle, clearText);
break;
case 'FheMax':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) > BigInt(event.args[2]) ? clearLHS : BigInt(event.args[2]);
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) > BigInt(clearRHS) ? clearLHS : clearRHS;
}
insertSQL(handle, clearText);
break;
case 'FheMin':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearLHS = await getClearText(event.args[1]);
if (event.args[3] === '0x01') {
clearText = BigInt(clearLHS) < BigInt(event.args[2]) ? clearLHS : BigInt(event.args[2]);
} else {
clearRHS = await getClearText(event.args[2]);
clearText = BigInt(clearLHS) < BigInt(clearRHS) ? clearLHS : clearRHS;
}
insertSQL(handle, clearText);
break;
case 'Cast':
resultType = parseInt(event.args[2]);
handle = ethers.toBeHex(event.args[3], 32);
clearText = BigInt(await getClearText(event.args[1])) % 2n ** NumBits[resultType as keyof typeof NumBits];
insertSQL(handle, clearText);
break;
case 'FheNot':
handle = ethers.toBeHex(event.args[2], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearText = BigInt(await getClearText(event.args[1]));
clearText = bitwiseNotUintBits(clearText, Number(NumBits[resultType as keyof typeof NumBits]));
insertSQL(handle, clearText);
break;
case 'FheNeg':
handle = ethers.toBeHex(event.args[2], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
clearText = BigInt(await getClearText(event.args[1]));
clearText = bitwiseNotUintBits(clearText, Number(NumBits[resultType as keyof typeof NumBits]));
clearText = (clearText + 1n) % 2n ** NumBits[resultType as keyof typeof NumBits];
insertSQL(handle, clearText);
break;
case 'VerifyInput':
handle = event.args[1];
try {
await getClearText(BigInt(handle));
} catch {
throw Error('User input was not found in DB');
}
break;
case 'FheIfThenElse':
handle = ethers.toBeHex(event.args[4], 32);
resultType = parseInt(handle.slice(-4, -2), 16);
handle = ethers.toBeHex(event.args[4], 32);
const clearControl = BigInt(await getClearText(event.args[1]));
const clearIfTrue = BigInt(await getClearText(event.args[2]));
const clearIfFalse = BigInt(await getClearText(event.args[3]));
if (clearControl === 1n) {
clearText = clearIfTrue;
} else {
clearText = clearIfFalse;
}
insertSQL(handle, clearText);
break;
case 'FheRand':
resultType = parseInt(event.args[1]);
handle = ethers.toBeHex(event.args[3], 32);
clearText = getRandomBigInt(Number(NumBits[resultType as keyof typeof NumBits]));
insertSQL(handle, clearText, true);
counterRand++;
break;
case 'FheRandBounded':
resultType = parseInt(event.args[2]);
handle = ethers.toBeHex(event.args[4], 32);
clearText = getRandomBigInt(Number(log2(BigInt(event.args[1]))));
insertSQL(handle, clearText, true);
counterRand++;
break;
}
}
export function getTxHCUFromTxReceipt(
receipt: EthersT.TransactionReceipt,
FheTypeInfos: FheTypeInfo[] = ALL_FHE_TYPE_INFOS,
): {
globalTxHCU: number;
maxTxHCUDepth: number;
HCUDepthPerHandle: Record<string, number>;
} {
if (receipt.status === 0) {
throw new Error('Transaction reverted');
}
function readFromHCUMap(handle: string): number {
if (hcuMap[handle] === undefined) {
return 0;
}
return hcuMap[handle];
}
let hcuMap: Record<string, number> = {};
let handleSet: Set<string> = new Set();
const contract = new ethers.Contract(coprocAddress, abi, ethers.provider);
const relevantLogs = receipt.logs.filter((log: EthersT.Log) => {
if (log.address.toLowerCase() !== coprocAddress.toLowerCase()) {
return false;
}
try {
const parsedLog = contract.interface.parseLog({
topics: log.topics,
data: log.data,
})!;
return abi.some((item) => item.startsWith(`event ${parsedLog.name}`) && parsedLog.name !== 'VerifyInput');
} catch {
return false;
}
});
const FHELogs = relevantLogs.map((log: EthersT.Log) => {
const parsedLog = contract.interface.parseLog({
topics: log.topics,
data: log.data,
})!;
return {
name: parsedLog.name,
args: parsedLog.args,
};
});
let totalHCUConsumed = 0;
for (const event of FHELogs) {
let type: string | undefined;
let typeIndex: number;
let handle: string;
let handleResult: string;
let hcuConsumed: number;
switch (event.name) {
case 'TrivialEncrypt':
typeIndex = parseInt(event.args[2]);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
hcuConsumed = (ALL_OPERATORS_PRICES['trivialEncrypt'].types as Record<string, number>)[type];
totalHCUConsumed += hcuConsumed;
handleResult = ethers.toBeHex(event.args[3], 32);
hcuMap[handleResult] = hcuConsumed;
handleSet.add(handleResult);
break;
case 'TrivialEncryptBytes':
typeIndex = parseInt(event.args[2]);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
hcuConsumed = (ALL_OPERATORS_PRICES['trivialEncrypt'].types as Record<string, number>)[type];
totalHCUConsumed += hcuConsumed;
handleResult = ethers.toBeHex(event.args[3], 32);
hcuMap[handleResult] = hcuConsumed;
handleSet.add(handleResult);
break;
case 'FheAdd':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheAdd'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheAdd'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheSub':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheSub'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheSub'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheMul':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheMul'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheMul'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheDiv':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheDiv'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
throw new Error('Non-scalar div not implemented yet');
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheRem':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheRem'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
throw new Error('Non-scalar rem not implemented yet');
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheBitAnd':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheBitAnd'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheBitAnd'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheBitOr':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheBitOr'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheBitOr'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheBitXor':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheBitXor'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheBitXor'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheShl':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheShl'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheShl'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheShr':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheShr'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheShr'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheRotl':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheRotl'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheRotl'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheRotr':
handleResult = ethers.toBeHex(event.args[4], 32);
typeIndex = parseInt(handleResult.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheRotr'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheRotr'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheEq':
handleResult = ethers.toBeHex(event.args[4], 32);
handle = ethers.toBeHex(event.args[1], 32);
typeIndex = parseInt(handle.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {
throw new Error(`Invalid FheType index: ${typeIndex}`);
}
if (event.args[3] === '0x01') {
hcuConsumed = (ALL_OPERATORS_PRICES['fheEq'].scalar as Record<string, number>)[type];
hcuMap[handleResult] = hcuConsumed + readFromHCUMap(ethers.toBeHex(event.args[1], 32));
} else {
hcuConsumed = (ALL_OPERATORS_PRICES['fheEq'].nonScalar as Record<string, number>)[type];
hcuMap[handleResult] =
hcuConsumed +
Math.max(
readFromHCUMap(ethers.toBeHex(event.args[1], 32)),
readFromHCUMap(ethers.toBeHex(event.args[2], 32)),
);
}
handleSet.add(handleResult);
totalHCUConsumed += hcuConsumed;
break;
case 'FheEqBytes':
handleResult = ethers.toBeHex(event.args[4], 32);
handle = ethers.toBeHex(event.args[1], 32);
typeIndex = parseInt(handle.slice(-4, -2), 16);
type = FheTypeInfos.find((t) => t.value === typeIndex)?.type;
if (!type) {