-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathDecryption.ts
More file actions
2477 lines (2172 loc) · 97.2 KB
/
Decryption.ts
File metadata and controls
2477 lines (2172 loc) · 97.2 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 { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { loadFixture } from "@nomicfoundation/hardhat-network-helpers";
import { expect } from "chai";
import { Wallet } from "ethers";
import hre from "hardhat";
import { approveContractWithMaxAllowance } from "../tasks/mockedTokenFund";
import {
CiphertextCommits,
Decryption,
Decryption__factory,
IDecryption,
ProtocolPayment,
ZamaOFT,
} from "../typechain-types";
// The type needs to be imported separately because it is not properly detected by the linter
// as this type is defined as a shared structs instead of directly in the IDecryption interface
import {
CtHandleContractPairStruct,
SnsCiphertextMaterialStruct,
} from "../typechain-types/contracts/interfaces/IDecryption";
import {
EIP712,
createAndFundRandomWallet,
createByteInput,
createBytes32,
createBytes32s,
createCtHandle,
createCtHandles,
createEIP712RequestDelegatedUserDecrypt,
createEIP712RequestUserDecrypt,
createEIP712ResponsePublicDecrypt,
createEIP712ResponseUserDecrypt,
createRandomAddress,
createRandomAddresses,
createRandomWallet,
getKeyId,
getPublicDecryptId,
getSignaturesDelegatedUserDecryptRequest,
getSignaturesPublicDecrypt,
getSignaturesUserDecryptRequest,
getSignaturesUserDecryptResponse,
getUserDecryptId,
loadHostChainIds,
loadTestVariablesFixture,
toValues,
} from "./utils";
// Constants for the Decryption contract
const MAX_USER_DECRYPT_DURATION_DAYS = 365;
const MAX_USER_DECRYPT_CONTRACT_ADDRESSES = 10;
const MAX_DECRYPTION_REQUEST_BITS = 2048;
// Get the current date in seconds. This is needed because Solidity works with seconds, not milliseconds
// See https://docs.soliditylang.org/en/develop/units-and-global-variables.html#time-units
function getDateInSeconds(): number {
return Math.floor(Date.now() / 1000);
}
describe("Decryption", function () {
// Get the registered host chains' chain IDs
const hostChainIds = loadHostChainIds();
const hostChainId = hostChainIds[0];
// Get the gateway's chain ID
const gatewayChainId = hre.network.config.chainId!;
// Define input values
const keyId = getKeyId(1);
const ciphertextDigest = createBytes32();
const snsCiphertextDigest = createBytes32();
// Define an euint256 ctHandle (which has a bit size of 256 bits)
const euint256CtHandle = createCtHandle(hostChainId, 8);
// Create ciphertext handles for the host chain ID with different TFHE-rs types
// Note that the list is made so that the total bit size represented by these handles (2+10+256=268 bits)
// does not exceed 2048 bits (the maximum allowed for a single list of handles)
const ctHandles = [createCtHandle(hostChainId, 0), createCtHandle(hostChainId, 2), euint256CtHandle];
const ctHandle = ctHandles[0];
// Define other valid ctHandles (they will not be added in the ciphertext commits contract and allowed for
// public decryption or account access by default)
const newCtHandles = createCtHandles(3, hostChainId);
const newCtHandle = newCtHandles[0];
// Define a new key ID
const newKeyId = getKeyId(2);
// Define a handle with an invalid FHE type (see `FheType.sol`)
const invalidFHEType = 255;
const invalidFHETypeCtHandle = createCtHandle(hostChainId, invalidFHEType);
// Define a handle with an unsupported FHE type (see `FHETypeBitSizes.sol`)
const unsupportedFHEType = 13;
const unsupportedFHETypeCtHandle = createCtHandle(hostChainId, unsupportedFHEType);
// Define fake values
const fakeTxSender = createRandomWallet();
const fakeSigner = createRandomWallet();
const tooLowDecryptionId = 0;
const tooHighDecryptionId = getPublicDecryptId(1000) + getUserDecryptId(1000);
const fakeHostChainId = 123;
const fakeChainIdCtHandle = createCtHandle(fakeHostChainId);
// Define extra data for version 0
const extraDataV0 = hre.ethers.solidityPacked(["uint8"], [0]);
// Add ciphertext materials
async function prepareAddCiphertextFixture() {
const fixtureData = await loadFixture(loadTestVariablesFixture);
const { ciphertextCommits, coprocessorTxSenders } = fixtureData;
let snsCiphertextMaterials: SnsCiphertextMaterialStruct[] = [];
// Allow public decryption
for (const ctHandle of ctHandles) {
for (let i = 0; i < coprocessorTxSenders.length; i++) {
await ciphertextCommits
.connect(coprocessorTxSenders[i])
.addCiphertextMaterial(ctHandle, keyId, ciphertextDigest, snsCiphertextDigest);
}
// Store the SNS ciphertext materials for event checks
snsCiphertextMaterials.push({
ctHandle,
keyId,
snsCiphertextDigest,
coprocessorTxSenderAddresses: coprocessorTxSenders.map((s) => s.address),
});
}
return { ...fixtureData, snsCiphertextMaterials, keyId };
}
describe("Deployment", function () {
let decryption: Decryption;
let owner: Wallet;
let decryptionFactory: Decryption__factory;
beforeEach(async function () {
const fixtureData = await loadFixture(loadTestVariablesFixture);
decryption = fixtureData.decryption;
owner = fixtureData.owner;
// Get the Decryption contract factory
decryptionFactory = await hre.ethers.getContractFactory("Decryption", owner);
});
it("Should revert because initialization is not from an empty proxy", async function () {
await expect(
hre.upgrades.upgradeProxy(decryption, decryptionFactory, {
call: { fn: "initializeFromEmptyProxy" },
}),
).to.be.revertedWithCustomError(decryption, "NotInitializingFromEmptyProxy");
});
});
describe("Public Decryption", function () {
let ciphertextCommits: CiphertextCommits;
let decryption: Decryption;
let protocolPayment: ProtocolPayment;
let mockedZamaOFT: ZamaOFT;
let pauser: Wallet;
let snsCiphertextMaterials: SnsCiphertextMaterialStruct[];
let kmsSignatures: string[];
let kmsTxSenders: HardhatEthersSigner[];
let kmsSigners: HardhatEthersSigner[];
let coprocessorTxSenders: HardhatEthersSigner[];
let publicDecryptionPrice: bigint;
let tokenFundedTxSender: Wallet;
let protocolPaymentAddress: string;
let decryptionAddress: string;
let mockedFeesSenderToBurnerAddress: string;
let eip712Message: EIP712;
// Expected decryption request ID (after a first request) for a public decryption request
// The IDs won't increase between requests made in different "describe" sections as the blockchain
// state is cleaned each time `loadFixture` is called
const decryptionId = getPublicDecryptId(1);
// Create input values
const decryptedResult = createByteInput();
// Define fake values
const fakeDecryptedResult = createByteInput();
// Prepare EIP712 messages for public decryption
async function preparePublicDecryptEIP712Fixture() {
const fixtureData = await loadFixture(prepareAddCiphertextFixture);
const { decryption, kmsSigners } = fixtureData;
// Create EIP712 messages
const decryptionAddress = await decryption.getAddress();
const eip712Message = createEIP712ResponsePublicDecrypt(
gatewayChainId,
decryptionAddress,
ctHandles,
decryptedResult,
extraDataV0,
);
// Sign the message with all KMS signers
const kmsSignatures = await getSignaturesPublicDecrypt(eip712Message, kmsSigners);
return { ...fixtureData, eip712Message, kmsSignatures, decryptionAddress };
}
beforeEach(async function () {
// Initialize globally used variables before each test
const fixtureData = await loadFixture(preparePublicDecryptEIP712Fixture);
ciphertextCommits = fixtureData.ciphertextCommits;
decryption = fixtureData.decryption;
protocolPayment = fixtureData.protocolPayment;
mockedZamaOFT = fixtureData.mockedZamaOFT;
mockedFeesSenderToBurnerAddress = fixtureData.mockedFeesSenderToBurnerAddress;
pauser = fixtureData.pauser;
snsCiphertextMaterials = fixtureData.snsCiphertextMaterials;
kmsSignatures = fixtureData.kmsSignatures;
kmsTxSenders = fixtureData.kmsTxSenders;
kmsSigners = fixtureData.kmsSigners;
coprocessorTxSenders = fixtureData.coprocessorTxSenders;
eip712Message = fixtureData.eip712Message;
decryptionAddress = fixtureData.decryptionAddress;
publicDecryptionPrice = fixtureData.publicDecryptionPrice;
tokenFundedTxSender = fixtureData.tokenFundedTxSender;
protocolPaymentAddress = await protocolPayment.getAddress();
});
it("Should request a public decryption with multiple ctHandles", async function () {
// Request public decryption
const requestTx = await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Check request event
await expect(requestTx)
.to.emit(decryption, "PublicDecryptionRequest")
.withArgs(decryptionId, toValues(snsCiphertextMaterials), extraDataV0);
});
it("Should request a public decryption with a single ctHandle", async function () {
// Request public decryption with a single ctHandle
const requestTx = await decryption
.connect(tokenFundedTxSender)
.publicDecryptionRequest([ctHandles[0]], extraDataV0);
const singleSnsCiphertextMaterials = snsCiphertextMaterials.slice(0, 1);
// Check request event
await expect(requestTx)
.to.emit(decryption, "PublicDecryptionRequest")
.withArgs(decryptionId, toValues(singleSnsCiphertextMaterials), extraDataV0);
});
it("Should revert because ctHandles list is empty", async function () {
// Check that the request fails because the list of handles is empty
await expect(
decryption.connect(tokenFundedTxSender).publicDecryptionRequest([], extraDataV0),
).to.be.revertedWithCustomError(decryption, "EmptyCtHandles");
});
it("Should revert because handle represents an invalid FHE type", async function () {
// Check that the request fails because the ctHandle represents an invalid FHE type
await expect(
decryption.connect(tokenFundedTxSender).publicDecryptionRequest([invalidFHETypeCtHandle], extraDataV0),
)
.to.be.revertedWithCustomError(decryption, "InvalidFHEType")
.withArgs(invalidFHEType);
});
it("Should revert because handle represents an unsupported FHE type", async function () {
// Check that the request fails because the ctHandle represents an unsupported FHE type
await expect(
decryption.connect(tokenFundedTxSender).publicDecryptionRequest([unsupportedFHETypeCtHandle], extraDataV0),
)
.to.be.revertedWithCustomError(decryption, "UnsupportedFHEType")
.withArgs(unsupportedFHEType);
});
it("Should revert because total bit size exceeds the maximum allowed", async function () {
// Create a list of 12 euint256 ctHandles (each has a bit size of 256 bits)
const numCtHandles = 12;
const largeBitSizeCtHandles = Array(numCtHandles).fill(euint256CtHandle);
// Calculate the new total bit size of this list
const totalBitSize = numCtHandles * 256;
// Check that the request fails because the total bit size exceeds the maximum allowed
await expect(decryption.connect(tokenFundedTxSender).publicDecryptionRequest(largeBitSizeCtHandles, extraDataV0))
.to.be.revertedWithCustomError(decryption, "MaxDecryptionRequestBitSizeExceeded")
.withArgs(MAX_DECRYPTION_REQUEST_BITS, totalBitSize);
});
it("Should revert because ciphertext material has not been added", async function () {
// Check that the request fails because the ciphertext material is unavailable
await expect(decryption.connect(tokenFundedTxSender).publicDecryptionRequest(newCtHandles, extraDataV0))
.to.be.revertedWithCustomError(ciphertextCommits, "CiphertextMaterialNotFound")
.withArgs(newCtHandles[0]);
});
it("Should revert because the message sender is not a KMS transaction sender", async function () {
// Request public decryption first so the decryptionId exists in state
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Check that the transaction fails because the recovered signer does not match the fake tx sender
await expect(
decryption
.connect(fakeTxSender)
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0),
)
.to.be.revertedWithCustomError(decryption, "KmsSignerDoesNotMatchTxSender")
.withArgs(kmsSigners[0].address, fakeTxSender.address);
});
it("Should revert because the signer is not a KMS signer", async function () {
// Request public decryption
// This step is necessary, else the decryptionId won't be set in the state and the
// signature verification will use wrong handles
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Create a fake signature from the fake signer
const [fakeSignature] = await getSignaturesPublicDecrypt(eip712Message, [fakeSigner]);
// Check that the signature verification fails because the signer is not a registered KMS signer
await expect(
decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, fakeSignature, extraDataV0),
)
.to.be.revertedWithCustomError(decryption, "NotKmsSigner")
.withArgs(fakeSigner.address);
});
it("Should revert because of two responses with same signature", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Trigger a first public decryption response
await decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0);
// Check that a KMS node cannot sign a second time for the same public decryption
await expect(
decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0),
)
.to.be.revertedWithCustomError(decryption, "KmsNodeAlreadySigned")
.withArgs(decryptionId, kmsSigners[0].address);
});
it("Should revert because of ctMaterials tied to different key IDs", async function () {
// Store the handles with a new key ID
for (const newCtHandle of newCtHandles) {
for (let i = 0; i < coprocessorTxSenders.length; i++) {
await ciphertextCommits
.connect(coprocessorTxSenders[i])
.addCiphertextMaterial(newCtHandle, newKeyId, ciphertextDigest, snsCiphertextDigest);
}
}
// Request public decryption with ctMaterials tied to different key IDs
const requestTx = decryption
.connect(tokenFundedTxSender)
.publicDecryptionRequest([...ctHandles, newCtHandle], extraDataV0);
// Check that different key IDs are not allowed for batched public decryption
await expect(requestTx)
.to.be.revertedWithCustomError(decryption, "DifferentKeyIdsNotAllowed")
.withArgs(
toValues(snsCiphertextMaterials[0]),
toValues({
ctHandle: newCtHandle,
keyId: newKeyId,
snsCiphertextDigest,
coprocessorTxSenderAddresses: coprocessorTxSenders.map((s) => s.address),
}),
);
});
it("Should emit an event when calling a single public decryption response", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
await expect(
decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0),
)
.to.emit(decryption, "PublicDecryptionResponseCall")
.withArgs(decryptionId, decryptedResult, kmsSignatures[0], kmsTxSenders[0].address, extraDataV0);
});
it("Should public decrypt with 3 valid responses", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Trigger three valid public decryption responses
await decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0);
await decryption
.connect(kmsTxSenders[1])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[1], extraDataV0);
const responseTx3 = await decryption
.connect(kmsTxSenders[2])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[2], extraDataV0);
// Consensus should be reached at the third response
// Check 3rd response event: it should only contain 3 valid signatures
await expect(responseTx3)
.to.emit(decryption, "PublicDecryptionResponse")
.withArgs(decryptionId, decryptedResult, [kmsSignatures[0], kmsSignatures[1], kmsSignatures[2]], extraDataV0);
// Check that the public decryption is done
expect(await decryption.isDecryptionDone(decryptionId)).to.be.true;
});
it("Should public decrypt with 3 valid responses and ignore the other valid one", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Trigger four valid public decryption responses
const responseTx1 = await decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0);
const responseTx2 = await decryption
.connect(kmsTxSenders[1])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[1], extraDataV0);
await decryption
.connect(kmsTxSenders[2])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[2], extraDataV0);
const responseTx4 = await decryption
.connect(kmsTxSenders[3])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[3], extraDataV0);
// Check that the 1st, 2nd and 4th responses do not emit an event:
// - 1st and 2nd responses are ignored because consensus is not reached yet
// - 4th response is ignored (not reverted) even though it is late
await expect(responseTx1).to.not.emit(decryption, "PublicDecryptionResponse");
await expect(responseTx2).to.not.emit(decryption, "PublicDecryptionResponse");
await expect(responseTx4).to.not.emit(decryption, "PublicDecryptionResponse");
});
it("Should public decrypt with 3 valid and 1 malicious signatures", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Create a malicious EIP712 message: the decryptedResult is different from the expected one
// but the signature is valid (the malicious decryptedResult is given to the response call)
const fakeEip712Message = createEIP712ResponsePublicDecrypt(
gatewayChainId,
decryptionAddress,
ctHandles,
fakeDecryptedResult,
extraDataV0,
);
const [fakeKmsSignature] = await getSignaturesPublicDecrypt(fakeEip712Message, kmsSigners.slice(0, 1));
// Trigger a malicious public decryption response with:
// - the first KMS transaction sender (expected)
// - a fake decrypted result (unexpected)
// - a fake signature based on the fake decrypted result (unexpected)
await decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, fakeDecryptedResult, fakeKmsSignature, extraDataV0);
// Trigger a first valid public decryption response with:
// - the second KMS transaction sender
// - the second KMS signer's signature
await decryption
.connect(kmsTxSenders[1])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[1], extraDataV0);
// Trigger a second valid public decryption response with:
// - the third KMS transaction sender
// - the third KMS signer's signature
const responseTx3 = await decryption
.connect(kmsTxSenders[2])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[2], extraDataV0);
// Trigger a third valid public decryption response with:
// - the fourth KMS transaction sender
// - the fourth KMS signer's signature
const responseTx4 = await decryption
.connect(kmsTxSenders[3])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[3], extraDataV0);
// Consensus should not be reached at the third transaction since the first was malicious
// Check 3rd transaction events: it should not emit an event for public decryption response
await expect(responseTx3).to.not.emit(decryption, "PublicDecryptionResponse");
// Consensus should be reached at the fourth transaction
// Check 4th transaction events: it should only contain 3 valid signatures
await expect(responseTx4)
.to.emit(decryption, "PublicDecryptionResponse")
.withArgs(decryptionId, decryptedResult, kmsSignatures.slice(1, 4), extraDataV0);
});
it("Should get all valid KMS transaction senders from public decryption consensus", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Trigger 2 valid public decryption responses
await decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0);
await decryption
.connect(kmsTxSenders[1])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[1], extraDataV0);
// Check that the KMS transaction senders list is empty because consensus is not reached yet
const decryptionConsensusTxSenders1 = await decryption.getDecryptionConsensusTxSenders(decryptionId);
expect(decryptionConsensusTxSenders1).to.deep.equal([]);
// Trigger a third valid public decryption response
await decryption
.connect(kmsTxSenders[2])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[2], extraDataV0);
const expectedKmsTxSenderAddresses2 = kmsTxSenders.slice(0, 3).map((s) => s.address);
// Check that the KMS transaction senders that were involved in the consensus are the 3 KMS
// transaction senders, at the moment the consensus is reached
const decryptionConsensusTxSenders2 = await decryption.getDecryptionConsensusTxSenders(decryptionId);
expect(decryptionConsensusTxSenders2).to.deep.equal(expectedKmsTxSenderAddresses2);
// Trigger a fourth valid public decryption response
await decryption
.connect(kmsTxSenders[3])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[3], extraDataV0);
const expectedKmsTxSenderAddresses3 = kmsTxSenders.map((s) => s.address);
// Check that the KMS transaction senders that were involved in the consensus are the 4 KMS
// transaction senders, after the consensus is reached
const decryptionConsensusTxSenders3 = await decryption.getDecryptionConsensusTxSenders(decryptionId);
expect(decryptionConsensusTxSenders3).to.deep.equal(expectedKmsTxSenderAddresses3);
});
it("Should get valid KMS transaction senders from public decryption consensus and ignore malicious ones", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Trigger 3 valid public decryption responses
await decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0);
await decryption
.connect(kmsTxSenders[1])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[1], extraDataV0);
await decryption
.connect(kmsTxSenders[2])
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[2], extraDataV0);
// Create a malicious EIP712 message: the decryptedResult is different from the expected one
// but the signature is valid (the malicious decryptedResult is given to the response call)
const fakeEip712Message = createEIP712ResponsePublicDecrypt(
gatewayChainId,
decryptionAddress,
ctHandles,
fakeDecryptedResult,
extraDataV0,
);
const [fakeKmsSignature] = await getSignaturesPublicDecrypt(fakeEip712Message, kmsSigners.slice(3, 4));
// Trigger a fourth invalid public decryption response
await decryption
.connect(kmsTxSenders[3])
.publicDecryptionResponse(decryptionId, fakeDecryptedResult, fakeKmsSignature, extraDataV0);
const expectedKmsTxSenderAddresses = kmsTxSenders.slice(0, 3).map((s) => s.address);
// Check that the KMS transaction senders that were involved in the consensus are the first 3
// KMS transaction senders (the fourth one is ignored because the response is invalid)
const decryptionConsensusTxSenders = await decryption.getDecryptionConsensusTxSenders(decryptionId);
expect(decryptionConsensusTxSenders).to.deep.equal(expectedKmsTxSenderAddresses);
});
it("Should revert in case of invalid decryptionId in public decryption response", async function () {
// Check that a public decryption response with a too low (invalid) decryptionId reverts
await expect(
decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(tooLowDecryptionId, decryptedResult, kmsSignatures[0], extraDataV0),
).to.be.revertedWithCustomError(decryption, "DecryptionNotRequested");
// Check that a public decryption response with too high (not requested yet) decryptionId reverts
await expect(
decryption
.connect(kmsTxSenders[0])
.publicDecryptionResponse(tooHighDecryptionId, decryptedResult, kmsSignatures[0], extraDataV0),
).to.be.revertedWithCustomError(decryption, "DecryptionNotRequested");
});
it("Should revert because the contract is paused", async function () {
// Pause the contract
await decryption.connect(pauser).pause();
// Try calling paused public decryption request
await expect(
decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0),
).to.be.revertedWithCustomError(decryption, "EnforcedPause");
});
it("Should revert because the signer and the tx sender do not correspond to the same KMS node", async function () {
// Request public decryption
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Check that triggering a public decryption response using a signature from the first KMS signer
// with the second KMS transaction sender reverts
const secondKmsTxSender = kmsTxSenders[1];
await expect(
decryption
.connect(secondKmsTxSender)
.publicDecryptionResponse(decryptionId, decryptedResult, kmsSignatures[0], extraDataV0),
)
.revertedWithCustomError(decryption, "KmsSignerDoesNotMatchTxSender")
.withArgs(kmsSigners[0].address, secondKmsTxSender.address);
});
describe("Checks", function () {
it("Should be true because public decryption is ready", async function () {
expect(await decryption.isPublicDecryptionReady(ctHandles, extraDataV0)).to.be.true;
});
it("Should be false because handles have not been allowed for public decryption", async function () {
expect(await decryption.isPublicDecryptionReady(newCtHandles, extraDataV0)).to.be.false;
});
it("Should be false because ciphertext material has not been added", async function () {
expect(await decryption.isPublicDecryptionReady(newCtHandles, extraDataV0)).to.be.false;
});
it("Should be false because the public decryption is not done", async function () {
expect(await decryption.isDecryptionDone(decryptionId)).to.be.false;
});
});
describe("$ZAMA fees collection", function () {
it("Should collect the $ZAMA fees for the public decryption", async function () {
const tokenFundedTxSenderBalance = await mockedZamaOFT.balanceOf(tokenFundedTxSender.address);
const feesSenderToBurnerBalance = await mockedZamaOFT.balanceOf(mockedFeesSenderToBurnerAddress);
// Trigger a public decryption request
await decryption.connect(tokenFundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0);
// Check that the $ZAMA fees have been collected from the funded signer and added to the
// FeesSenderToBurner contract's balance
const newTokenFundedTxSenderBalance = await mockedZamaOFT.balanceOf(tokenFundedTxSender.address);
const newFeesSenderToBurnerBalance = await mockedZamaOFT.balanceOf(mockedFeesSenderToBurnerAddress);
expect(newTokenFundedTxSenderBalance).to.equal(tokenFundedTxSenderBalance - publicDecryptionPrice);
expect(newFeesSenderToBurnerBalance).to.equal(feesSenderToBurnerBalance + publicDecryptionPrice);
});
it("Should revert because sender has not enough $ZAMA tokens", async function () {
// Get a new random wallet with no $ZAMA tokens
const tokenUnfundedTxSender = await createAndFundRandomWallet();
// Approve the ProtocolPayment contract with the maximum allowance over the signer's tokens
await approveContractWithMaxAllowance(tokenUnfundedTxSender, protocolPaymentAddress, hre.ethers);
await expect(decryption.connect(tokenUnfundedTxSender).publicDecryptionRequest(ctHandles, extraDataV0))
.to.be.revertedWithCustomError(mockedZamaOFT, "ERC20InsufficientBalance")
.withArgs(tokenUnfundedTxSender.address, 0, publicDecryptionPrice);
});
});
});
describe("User Decryption", function () {
let ciphertextCommits: CiphertextCommits;
let decryption: Decryption;
let protocolPayment: ProtocolPayment;
let mockedZamaOFT: ZamaOFT;
let pauser: Wallet;
let snsCiphertextMaterials: SnsCiphertextMaterialStruct[];
let kmsSignatures: string[];
let kmsTxSenders: HardhatEthersSigner[];
let kmsSigners: HardhatEthersSigner[];
let coprocessorTxSenders: HardhatEthersSigner[];
let userDecryptionPrice: bigint;
let tokenFundedTxSender: Wallet;
let protocolPaymentAddress: string;
let decryptionAddress: string;
let mockedFeesSenderToBurnerAddress: string;
let userSignature: string;
let userDecryptedShares: string[];
let eip712RequestMessage: EIP712;
let eip712ResponseMessages: EIP712[];
// Expected decryption request ID (after a first request) for a user decryption request
// The IDs won't increase between requests made in different "describe" sections as the blockchain
// state is cleaned each time `loadFixture` is called
const decryptionId = getUserDecryptId(1);
// Create valid input values
const user = createRandomWallet();
const contractAddress = createRandomAddress();
const publicKey = createByteInput();
const startTimestamp = getDateInSeconds();
const durationDays = 120;
const contractsInfo: IDecryption.ContractsInfoStruct = {
addresses: [contractAddress],
chainId: hostChainId,
};
const requestValidity: IDecryption.RequestValidityStruct = {
startTimestamp,
durationDays,
};
// Define the ctHandleContractPairs (the handles have been added and allowed by default)
const ctHandleContractPairs: CtHandleContractPairStruct[] = ctHandles.map((ctHandle) => ({
contractAddress,
ctHandle,
}));
// Define new valid inputs (the handles have neither been added nor allowed by default)
const newCtHandleContractPair: CtHandleContractPairStruct = {
contractAddress,
ctHandle: newCtHandle,
};
// Define fake values
const fakeContractAddresses = createRandomAddresses(3);
// Define utility values
const tenDaysInSeconds = 10 * 24 * 60 * 60;
// Prepare EIP712 messages for user decryption
async function prepareUserDecryptEIP712Fixture() {
const fixtureData = await loadFixture(prepareAddCiphertextFixture);
const { decryption, kmsSigners } = fixtureData;
// Create EIP712 messages
const decryptionAddress = await decryption.getAddress();
const eip712RequestMessage = createEIP712RequestUserDecrypt(
decryptionAddress,
publicKey,
contractsInfo.addresses as string[],
contractsInfo.chainId as number,
requestValidity.startTimestamp.toString(),
requestValidity.durationDays.toString(),
extraDataV0,
);
// Sign the message with the user
const [userSignature] = await getSignaturesUserDecryptRequest(eip712RequestMessage, [user]);
const userDecryptedShares = createBytes32s(kmsSigners.length);
const eip712ResponseMessages = userDecryptedShares.map((userDecryptedShare) =>
createEIP712ResponseUserDecrypt(
gatewayChainId,
decryptionAddress,
publicKey,
ctHandles,
userDecryptedShare,
extraDataV0,
),
);
// Sign the message with all KMS signers
const kmsSignatures = await getSignaturesUserDecryptResponse(eip712ResponseMessages, kmsSigners);
return {
...fixtureData,
userDecryptedShares,
eip712RequestMessage,
eip712ResponseMessages,
userSignature,
kmsSignatures,
requestValidity,
decryptionAddress,
};
}
beforeEach(async function () {
// Initialize globally used variables before each test
const fixtureData = await loadFixture(prepareUserDecryptEIP712Fixture);
ciphertextCommits = fixtureData.ciphertextCommits;
decryption = fixtureData.decryption;
protocolPayment = fixtureData.protocolPayment;
mockedZamaOFT = fixtureData.mockedZamaOFT;
mockedFeesSenderToBurnerAddress = fixtureData.mockedFeesSenderToBurnerAddress;
pauser = fixtureData.pauser;
snsCiphertextMaterials = fixtureData.snsCiphertextMaterials;
userSignature = fixtureData.userSignature;
kmsSignatures = fixtureData.kmsSignatures;
kmsTxSenders = fixtureData.kmsTxSenders;
kmsSigners = fixtureData.kmsSigners;
coprocessorTxSenders = fixtureData.coprocessorTxSenders;
userDecryptedShares = fixtureData.userDecryptedShares;
eip712RequestMessage = fixtureData.eip712RequestMessage;
eip712ResponseMessages = fixtureData.eip712ResponseMessages;
decryptionAddress = fixtureData.decryptionAddress;
userDecryptionPrice = fixtureData.userDecryptionPrice;
tokenFundedTxSender = fixtureData.tokenFundedTxSender;
protocolPaymentAddress = await protocolPayment.getAddress();
});
it("Should request a user decryption with multiple ctHandleContractPairs", async function () {
// Request user decryption
const requestTx = await decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
ctHandleContractPairs,
requestValidity,
contractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
);
// Check request event
await expect(requestTx)
.to.emit(decryption, "UserDecryptionRequest")
.withArgs(decryptionId, toValues(snsCiphertextMaterials), user.address, publicKey, extraDataV0);
});
it("Should request a user decryption with a single ctHandleContractPair", async function () {
// Create single list of inputs
const singleCtHandleContractPair: CtHandleContractPairStruct[] = ctHandleContractPairs.slice(0, 1);
const singleSnsCiphertextMaterials = snsCiphertextMaterials.slice(0, 1);
// Request user decryption
const requestTx = await decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
singleCtHandleContractPair,
requestValidity,
contractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
);
// Check request event
await expect(requestTx)
.to.emit(decryption, "UserDecryptionRequest")
.withArgs(decryptionId, toValues(singleSnsCiphertextMaterials), user.address, publicKey, extraDataV0);
});
it("Should revert because ctHandleContractPairs is empty", async function () {
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
[],
requestValidity,
contractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
),
).to.be.revertedWithCustomError(decryption, "EmptyCtHandleContractPairs");
});
it("Should revert because a ctHandleContractPair has a chain ID that differs from the contract chain ID", async function () {
const invalidChainIdCtHandleContractPairs: CtHandleContractPairStruct[] = [
{
contractAddress,
ctHandle: fakeChainIdCtHandle,
},
];
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
invalidChainIdCtHandleContractPairs,
requestValidity,
contractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
),
)
.to.be.revertedWithCustomError(decryption, "CtHandleChainIdDiffersFromContractChainId")
.withArgs(fakeChainIdCtHandle, fakeHostChainId, contractsInfo.chainId);
});
it("Should revert because contract chain ID is not registered in the GatewayConfig", async function () {
const invalidContractsInfo: IDecryption.ContractsInfoStruct = {
addresses: [contractAddress],
chainId: fakeHostChainId,
};
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
ctHandleContractPairs,
requestValidity,
invalidContractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
),
).to.be.revertedWithCustomError(decryption, "HostChainNotRegistered");
});
it("Should revert because contract addresses is empty", async function () {
const emptyContractsInfo: IDecryption.ContractsInfoStruct = {
addresses: [],
chainId: hostChainId,
};
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
ctHandleContractPairs,
requestValidity,
emptyContractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
),
).to.be.revertedWithCustomError(decryption, "EmptyContractAddresses");
});
it("Should revert because contract addresses exceeds maximum length allowed", async function () {
// Create a list of contract addresses exceeding the maximum length allowed
const largeContractsInfo: IDecryption.ContractsInfoStruct = {
addresses: createRandomAddresses(15),
chainId: hostChainId,
};
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
ctHandleContractPairs,
requestValidity,
largeContractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
),
)
.to.be.revertedWithCustomError(decryption, "ContractAddressesMaxLengthExceeded")
.withArgs(MAX_USER_DECRYPT_CONTRACT_ADDRESSES, largeContractsInfo.addresses.length);
});
it("Should revert because durationDays is null", async function () {
// Create an invalid validity request with a durationDays that is 0
const invalidRequestValidity: IDecryption.RequestValidityStruct = {
startTimestamp,
durationDays: 0,
};
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
ctHandleContractPairs,
invalidRequestValidity,
contractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,
),
)
.to.be.revertedWithCustomError(decryption, "InvalidNullDurationDays")
.withArgs();
});
it("Should revert because durationDays exceeds maximum allowed", async function () {
// Create an invalid validity request with a durationDays that exceeds the maximum allowed
const largeDurationDays = MAX_USER_DECRYPT_DURATION_DAYS + 1;
const invalidRequestValidity: IDecryption.RequestValidityStruct = {
startTimestamp,
durationDays: largeDurationDays,
};
await expect(
decryption
.connect(tokenFundedTxSender)
.userDecryptionRequest(
ctHandleContractPairs,
invalidRequestValidity,
contractsInfo,
user.address,
publicKey,
userSignature,
extraDataV0,