-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathdelegatedUserDecryption.ts
More file actions
348 lines (301 loc) · 13.3 KB
/
delegatedUserDecryption.ts
File metadata and controls
348 lines (301 loc) · 13.3 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
import { expect } from 'chai';
import { ethers } from 'hardhat';
import { createInstances } from '../instance';
import { getSigners, initSigners } from '../signers';
import { delegatedUserDecryptSingleHandle, waitForBlock } from '../utils';
const NOT_ALLOWED_ON_HOST_ACL = 'not_allowed_on_host_acl';
describe('Delegated user decryption', function () {
before(async function () {
await initSigners(5);
this.signers = await getSigners();
this.instances = await createInstances(this.signers);
// Deploy the EncryptedERC20 token contract.
const tokenFactory = await ethers.getContractFactory('EncryptedERC20');
this.token = await tokenFactory.connect(this.signers.alice).deploy('Zama Confidential Token', 'ZAMA');
await this.token.waitForDeployment();
this.tokenAddress = await this.token.getAddress();
// Deploy SmartWalletWithDelegation with Bob as the owner.
const smartWalletFactory = await ethers.getContractFactory('SmartWalletWithDelegation');
this.smartWallet = await smartWalletFactory.connect(this.signers.bob).deploy(this.signers.bob.address);
await this.smartWallet.waitForDeployment();
this.smartWalletAddress = await this.smartWallet.getAddress();
// Alice mints tokens to herself.
const mintAmount = 1000000n;
const mintTx = await this.token.connect(this.signers.alice).mint(mintAmount);
await mintTx.wait();
// Alice transfers some tokens to the smartWallet contract.
const transferAmount = 500000n;
const input = this.instances.alice.createEncryptedInput(this.tokenAddress, this.signers.alice.address);
input.add64(transferAmount);
const encryptedTransferAmount = await input.encrypt();
const transferTx = await this.token
.connect(this.signers.alice)
['transfer(address,bytes32,bytes)'](
this.smartWalletAddress,
encryptedTransferAmount.handles[0],
encryptedTransferAmount.inputProof,
);
await transferTx.wait();
});
it('test delegated user decryption - smartWallet owner delegates his own EOA to decrypt the smartWallet balance', async function () {
// Bob (smartWallet owner) delegates decryption rights to his own EOA.
const expirationTimestamp = Math.floor(Date.now() / 1000) + 86400; // 24 hours from now
const delegateTx = await this.smartWallet
.connect(this.signers.bob)
.delegateUserDecryption(
this.signers.bob.address,
this.tokenAddress,
expirationTimestamp,
);
await delegateTx.wait();
// Wait for 15 blocks to ensure delegation is propagated by the coprocessor.
const currentBlock = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock + 15);
// Get the encrypted balance handle of the smartWallet.
const balanceHandle = await this.token.balanceOf(this.smartWalletAddress);
// Bob's EOA can now decrypt the smartWallet's confidential balance.
const { publicKey, privateKey } = this.instances.bob.generateKeypair();
const decryptedBalance = await delegatedUserDecryptSingleHandle(
this.instances.bob,
balanceHandle,
this.tokenAddress,
this.smartWalletAddress,
this.signers.bob.address,
this.signers.bob,
privateKey,
publicKey,
);
// Verify the decrypted balance matches what was transferred.
expect(decryptedBalance).to.equal(500000n);
});
it('test delegated user decryption - smartWallet owner delegates a third EOA to decrypt the smartWallet balance', async function () {
// Bob (smartWallet owner) delegates decryption rights to Carol's EOA.
const expirationTimestamp = Math.floor(Date.now() / 1000) + 86400; // 24 hours from now
const delegateTx = await this.smartWallet
.connect(this.signers.bob)
.delegateUserDecryption(
this.signers.carol.address,
this.tokenAddress,
expirationTimestamp,
);
await delegateTx.wait();
// Wait for 15 blocks to ensure delegation is propagated by the coprocessor.
const currentBlock = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock + 15);
// Get the encrypted balance handle of the smartWallet.
const balanceHandle = await this.token.balanceOf(this.smartWalletAddress);
// Carol's EOA can now decrypt the smartWallet's confidential balance.
const { publicKey, privateKey } = this.instances.carol.generateKeypair();
const decryptedBalance = await delegatedUserDecryptSingleHandle(
this.instances.carol,
balanceHandle,
this.tokenAddress,
this.smartWalletAddress,
this.signers.carol.address,
this.signers.carol,
privateKey,
publicKey,
);
// Verify the decrypted balance matches what was transferred.
expect(decryptedBalance).to.equal(500000n);
});
it('test delegated user decryption - smartWallet can execute transference of funds to a third EOA', async function () {
// First, Bob needs to delegate so the smartWallet can initiate transfers.
const expirationTimestamp = Math.floor(Date.now() / 1000) + 86400;
const delegateTx = await this.smartWallet
.connect(this.signers.bob)
.delegateUserDecryption(
this.signers.bob.address,
this.tokenAddress,
expirationTimestamp,
);
await delegateTx.wait();
// Wait for 15 blocks to ensure delegation is propagated by the coprocessor.
let currentBlock = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock + 15);
// Get the current smartWallet balance before transfer
const smartWalletBalanceBefore = await this.token.balanceOf(this.smartWalletAddress);
const { publicKey: pkBefore, privateKey: skBefore } = this.instances.bob.generateKeypair();
const decryptedBalanceBefore = await delegatedUserDecryptSingleHandle(
this.instances.bob,
smartWalletBalanceBefore,
this.tokenAddress,
this.smartWalletAddress,
this.signers.bob.address,
this.signers.bob,
skBefore,
pkBefore,
);
// Bob proposes a transaction from the smartWallet to transfer tokens to Carol.
// The encrypted input must be created for the smartWallet address since it will be the msg.sender.
const transferAmount = 100000n;
const input = this.instances.bob.createEncryptedInput(this.tokenAddress, this.smartWalletAddress);
input.add64(transferAmount);
const encryptedTransferAmount = await input.encrypt();
// Encode the transfer function call with full signature to avoid ambiguity.
const transferData = this.token.interface.encodeFunctionData(
'transfer(address,bytes32,bytes)',
[
this.signers.carol.address,
encryptedTransferAmount.handles[0],
encryptedTransferAmount.inputProof,
]
);
// Propose the transaction.
const proposeTx = await this.smartWallet
.connect(this.signers.bob)
.proposeTx(this.tokenAddress, transferData);
await proposeTx.wait();
// Get the transaction ID.
const txId = await this.smartWallet.txCounter();
// Execute the transaction.
const executeTx = await this.smartWallet
.connect(this.signers.bob)
.executeTx(txId);
await executeTx.wait();
// Verify the smartWallet balance decreased.
const smartWalletBalanceAfter = await this.token.balanceOf(this.smartWalletAddress);
const { publicKey: pkAfter, privateKey: skAfter } = this.instances.bob.generateKeypair();
const decryptedBalanceAfter = await delegatedUserDecryptSingleHandle(
this.instances.bob,
smartWalletBalanceAfter,
this.tokenAddress,
this.smartWalletAddress,
this.signers.bob.address,
this.signers.bob,
skAfter,
pkAfter,
);
// The smartWallet balance should have decreased by the transfer amount.
expect(Number(decryptedBalanceBefore) - Number(decryptedBalanceAfter)).to.equal(Number(transferAmount));
});
describe('negative-acl', function () {
it('should reject when delegation has been revoked', async function () {
// First, ensure Bob has delegation.
const expirationTimestamp = Math.floor(Date.now() / 1000) + 86400;
const delegateTx = await this.smartWallet
.connect(this.signers.bob)
.delegateUserDecryption(
this.signers.bob.address,
this.tokenAddress,
expirationTimestamp,
);
await delegateTx.wait();
// Wait for 15 blocks to ensure delegation is propagated by the coprocessor.
const currentBlock1 = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock1 + 15);
// Revoke the delegation for Bob's EOA.
const revokeTx = await this.smartWallet
.connect(this.signers.bob)
.revokeUserDecryptionDelegation(
this.signers.bob.address,
this.tokenAddress,
);
await revokeTx.wait();
// Wait for 15 blocks to ensure revocation is propagated by the coprocessor.
const currentBlock2 = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock2 + 15);
// Try to decrypt the smartWallet balance with Bob's EOA, which should now fail.
const balanceHandle = await this.token.balanceOf(this.smartWalletAddress);
const { publicKey, privateKey } = this.instances.bob.generateKeypair();
try {
await delegatedUserDecryptSingleHandle(
this.instances.bob,
balanceHandle,
this.tokenAddress,
this.smartWalletAddress,
this.signers.bob.address,
this.signers.bob,
privateKey,
publicKey,
);
expect.fail('Expected delegated user decrypt to be rejected after revocation');
} catch (err: any) {
expect(err.relayerApiError?.label).to.equal(NOT_ALLOWED_ON_HOST_ACL);
}
});
it('should reject when no delegation exists', async function () {
const balanceHandle = await this.token.balanceOf(this.smartWalletAddress);
const { publicKey, privateKey } = this.instances.dave.generateKeypair();
try {
await delegatedUserDecryptSingleHandle(
this.instances.dave,
balanceHandle,
this.tokenAddress,
this.smartWalletAddress,
this.signers.dave.address,
this.signers.dave,
privateKey,
publicKey,
);
expect.fail('Expected delegated user decrypt to be rejected without delegation');
} catch (err: any) {
expect(err.relayerApiError?.label).to.equal(NOT_ALLOWED_ON_HOST_ACL);
}
});
it('should reject when delegation is for wrong contract', async function () {
const dummyFactory = await ethers.getContractFactory('UserDecrypt');
const dummy = await dummyFactory.connect(this.signers.alice).deploy();
await dummy.waitForDeployment();
const wrongAddress = await dummy.getAddress();
const expirationTimestamp = Math.floor(Date.now() / 1000) + 86400;
const tx = await this.smartWallet
.connect(this.signers.bob)
.delegateUserDecryption(this.signers.eve.address, wrongAddress, expirationTimestamp);
await tx.wait();
const currentBlock = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock + 15);
const balanceHandle = await this.token.balanceOf(this.smartWalletAddress);
const { publicKey, privateKey } = this.instances.eve.generateKeypair();
try {
await delegatedUserDecryptSingleHandle(
this.instances.eve,
balanceHandle,
this.tokenAddress,
this.smartWalletAddress,
this.signers.eve.address,
this.signers.eve,
privateKey,
publicKey,
);
expect.fail('Expected delegated user decrypt to be rejected for wrong contract');
} catch (err: any) {
expect(err.relayerApiError?.label).to.equal(NOT_ALLOWED_ON_HOST_ACL);
}
});
it('should reject when delegation has expired', async function () {
// Expiration must be >1h from chain time (FHE library constraint).
// Use block timestamp, not Date.now(), since evm_increaseTime shifts chain clock.
const oneHour = 3600;
const buffer = 60;
const latestBlock = await ethers.provider.getBlock('latest');
const expirationTimestamp = latestBlock!.timestamp + oneHour + buffer;
const tx = await this.smartWallet
.connect(this.signers.bob)
.delegateUserDecryption(this.signers.eve.address, this.tokenAddress, expirationTimestamp);
await tx.wait();
// Fast-forward time past the expiration.
await ethers.provider.send('evm_increaseTime', [oneHour + buffer + 1]);
await ethers.provider.send('evm_mine', []);
const currentBlock = await ethers.provider.getBlockNumber();
await waitForBlock(currentBlock + 15);
const balanceHandle = await this.token.balanceOf(this.smartWalletAddress);
const { publicKey, privateKey } = this.instances.eve.generateKeypair();
try {
await delegatedUserDecryptSingleHandle(
this.instances.eve,
balanceHandle,
this.tokenAddress,
this.smartWalletAddress,
this.signers.eve.address,
this.signers.eve,
privateKey,
publicKey,
);
expect.fail('Expected delegated user decrypt to be rejected for expired delegation');
} catch (err: any) {
expect(err.relayerApiError?.label).to.equal(NOT_ALLOWED_ON_HOST_ACL);
}
});
});
});