This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
/
WithdrawManager.sol
427 lines (381 loc) · 15.7 KB
/
WithdrawManager.sol
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
pragma solidity ^0.5.2;
import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import {ERC721} from "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol";
import {Math} from "openzeppelin-solidity/contracts/math/Math.sol";
import {RLPReader} from "solidity-rlp/contracts/RLPReader.sol";
import {Merkle} from "../../common/lib/Merkle.sol";
import {MerklePatriciaProof} from "../../common/lib/MerklePatriciaProof.sol";
import {PriorityQueue} from "../../common/lib/PriorityQueue.sol";
import {ExitPayloadReader} from "../../common/lib/ExitPayloadReader.sol";
import {ExitNFT} from "./ExitNFT.sol";
import {DepositManager} from "../depositManager/DepositManager.sol";
import {IPredicate} from "../predicates/IPredicate.sol";
import {IWithdrawManager} from "./IWithdrawManager.sol";
import {RootChainHeader} from "../RootChainStorage.sol";
import {Registry} from "../../common/Registry.sol";
import {WithdrawManagerStorage} from "./WithdrawManagerStorage.sol";
contract WithdrawManager is WithdrawManagerStorage, IWithdrawManager {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
using ExitPayloadReader for bytes;
using ExitPayloadReader for ExitPayloadReader.ExitPayload;
using ExitPayloadReader for ExitPayloadReader.Receipt;
using ExitPayloadReader for ExitPayloadReader.Log;
using ExitPayloadReader for ExitPayloadReader.LogTopics;
modifier isBondProvided() {
require(msg.value == BOND_AMOUNT, "Invalid Bond amount");
_;
}
modifier isPredicateAuthorized() {
require(registry.predicates(msg.sender) != Registry.Type.Invalid, "PREDICATE_NOT_AUTHORIZED");
_;
}
modifier checkPredicateAndTokenMapping(address rootToken) {
Registry.Type _type = registry.predicates(msg.sender);
require(registry.rootToChildToken(rootToken) != address(0x0), "rootToken not supported");
if (_type == Registry.Type.ERC20) {
require(registry.isERC721(rootToken) == false, "Predicate supports only ERC20 tokens");
} else if (_type == Registry.Type.ERC721) {
require(registry.isERC721(rootToken) == true, "Predicate supports only ERC721 tokens");
} else if (_type == Registry.Type.Custom) {} else {
revert("PREDICATE_NOT_AUTHORIZED");
}
_;
}
/**
* @dev Receive bond for bonded exits
*/
function() external payable {}
function createExitQueue(address token) external {
require(msg.sender == address(registry), "UNAUTHORIZED_REGISTRY_ONLY");
exitsQueues[token] = address(new PriorityQueue());
}
/**
During coverage tests verifyInclusion fails co compile with "stack too deep" error.
*/
struct VerifyInclusionVars {
uint256 headerNumber;
uint256 blockNumber;
uint256 createdAt;
uint256 branchMask;
bytes32 txRoot;
bytes32 receiptRoot;
bytes branchMaskBytes;
}
/**
* @dev Verify the inclusion of the receipt in the checkpoint
* @param data RLP encoded data of the reference tx(s) that encodes the following fields for each tx
* headerNumber Header block number of which the reference tx was a part of
* blockProof Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* blockNumber Block number of which the reference tx is a part of
* blockTime Reference tx block time
* blocktxRoot Transactions root of block
* blockReceiptsRoot Receipts root of block
* receipt Receipt of the reference transaction
* receiptProof Merkle proof of the reference receipt
* branchMask Merkle proof branchMask for the receipt
* logIndex Log Index to read from the receipt
* @param offset offset in the data array
* @param verifyTxInclusion Whether to also verify the inclusion of the raw tx in the txRoot
* @return ageOfInput Measure of the position of the receipt and the log in the child chain
*/
function verifyInclusion(
bytes calldata data,
uint8 offset,
bool verifyTxInclusion
)
external
view
returns (
uint256 /* ageOfInput */
)
{
ExitPayloadReader.ExitPayload memory payload = data.toExitPayload();
VerifyInclusionVars memory vars;
vars.headerNumber = payload.getHeaderNumber();
vars.branchMaskBytes = payload.getBranchMaskAsBytes();
vars.txRoot = payload.getTxRoot();
vars.receiptRoot = payload.getReceiptRoot();
require(
MerklePatriciaProof.verify(
payload.getReceipt().toBytes(),
vars.branchMaskBytes,
payload.getReceiptProof(),
vars.receiptRoot
),
"INVALID_RECEIPT_MERKLE_PROOF"
);
if (verifyTxInclusion) {
require(
MerklePatriciaProof.verify(
payload.getTx(),
vars.branchMaskBytes,
payload.getTxProof(),
vars.txRoot
),
"INVALID_TX_MERKLE_PROOF"
);
}
vars.blockNumber = payload.getBlockNumber();
vars.createdAt = checkBlockMembershipInCheckpoint(
vars.blockNumber,
payload.getBlockTime(),
vars.txRoot,
vars.receiptRoot,
vars.headerNumber,
payload.getBlockProof()
);
vars.branchMask = payload.getBranchMaskAsUint();
require(
vars.branchMask & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0,
"Branch mask should be 32 bits"
);
// ageOfInput is denoted as
// 1 reserve bit (see last 2 lines in comment)
// 128 bits for exitableAt timestamp
// 95 bits for child block number
// 32 bits for receiptPos + logIndex * MAX_LOGS + oIndex
// In predicates, the exitId will be evaluated by shifting the ageOfInput left by 1 bit
// (Only in erc20Predicate) Last bit is to differentiate whether the sender or receiver of the in-flight tx is starting an exit
return (getExitableAt(vars.createdAt) << 127) | (vars.blockNumber << 32) | vars.branchMask;
}
function startExitWithDepositedTokens(
uint256 depositId,
address token,
uint256 amountOrToken
) external payable isBondProvided {
// (bytes32 depositHash, uint256 createdAt) = getDepositManager().deposits(depositId);
// require(keccak256(abi.encodePacked(msg.sender, token, amountOrToken)) == depositHash, "UNAUTHORIZED_EXIT");
// uint256 ageOfInput = getExitableAt(createdAt) << 127 | (depositId % 10000 /* MAX_DEPOSITS */);
// uint256 exitId = ageOfInput << 1;
// address predicate = registry.isTokenMappedAndGetPredicate(token);
// _addExitToQueue(
// msg.sender,
// token,
// amountOrToken,
// bytes32(0), /* txHash */
// false, /* isRegularExit */
// exitId,
// predicate
// );
// _addInput(
// exitId,
// ageOfInput,
// msg.sender, /* utxoOwner */
// predicate,
// token
// );
}
function addExitToQueue(
address exitor,
address childToken,
address rootToken,
uint256 exitAmountOrTokenId,
bytes32 txHash,
bool isRegularExit,
uint256 priority
) external checkPredicateAndTokenMapping(rootToken) {
require(registry.rootToChildToken(rootToken) == childToken, "INVALID_ROOT_TO_CHILD_TOKEN_MAPPING");
_addExitToQueue(exitor, rootToken, exitAmountOrTokenId, txHash, isRegularExit, priority, msg.sender);
}
function challengeExit(
uint256 exitId,
uint256 inputId,
bytes calldata challengeData,
address adjudicatorPredicate
) external {
PlasmaExit storage exit = exits[exitId];
Input storage input = exit.inputs[inputId];
require(exit.owner != address(0x0) && input.utxoOwner != address(0x0), "Invalid exit or input id");
require(registry.predicates(adjudicatorPredicate) != Registry.Type.Invalid, "INVALID_PREDICATE");
require(
IPredicate(adjudicatorPredicate).verifyDeprecation(
encodeExit(exit),
encodeInputUtxo(inputId, input),
challengeData
),
"Challenge failed"
);
// In the call to burn(exitId), there is an implicit check that prevents challenging the same exit twice
ExitNFT(exitNft).burn(exitId);
// Send bond amount to challenger
msg.sender.send(BOND_AMOUNT);
// delete exits[exitId];
emit ExitCancelled(exitId);
}
function processExits(address _token) public {
uint256 exitableAt;
uint256 exitId;
PriorityQueue exitQueue = PriorityQueue(exitsQueues[_token]);
while (exitQueue.currentSize() > 0 && gasleft() > ON_FINALIZE_GAS_LIMIT) {
(exitableAt, exitId) = exitQueue.getMin();
exitId = (exitableAt << 128) | exitId;
PlasmaExit memory currentExit = exits[exitId];
// Stop processing exits if the exit that is next is queue is still in its challenge period
if (exitableAt > block.timestamp) return;
exitQueue.delMin();
// If the exitNft was deleted as a result of a challenge, skip processing this exit
if (!exitNft.exists(exitId)) continue;
address exitor = exitNft.ownerOf(exitId);
exits[exitId].owner = exitor;
exitNft.burn(exitId);
// If finalizing a particular exit is reverting, it will block any following exits from being processed.
// Hence, call predicate.onFinalizeExit in a revertless manner.
// (bool success, bytes memory result) =
currentExit.predicate.call(
abi.encodeWithSignature("onFinalizeExit(bytes)", encodeExitForProcessExit(exitId))
);
emit Withdraw(exitId, exitor, _token, currentExit.receiptAmountOrNFTId);
if (!currentExit.isRegularExit) {
// return the bond amount if this was a MoreVp style exit
address(uint160(exitor)).send(BOND_AMOUNT);
}
}
}
function processExitsBatch(address[] calldata _tokens) external {
for (uint256 i = 0; i < _tokens.length; i++) {
processExits(_tokens[i]);
}
}
/**
* @dev Add a state update (UTXO style input) to an exit
* @param exitId Exit ID
* @param age age of the UTXO style input
* @param utxoOwner User for whom the input acts as a proof-of-funds
* (alternate expression) User who could have potentially spent this UTXO
* @param token Token (Think of it like Utxo color)
*/
function addInput(
uint256 exitId,
uint256 age,
address utxoOwner,
address token
) external isPredicateAuthorized {
PlasmaExit storage exitObject = exits[exitId];
require(exitObject.owner != address(0x0), "INVALID_EXIT_ID");
_addInput(
exitId,
age,
utxoOwner,
/* predicate */
msg.sender,
token
);
}
function _addInput(
uint256 exitId,
uint256 age,
address utxoOwner,
address predicate,
address token
) internal {
exits[exitId].inputs[age] = Input(utxoOwner, predicate, token);
emit ExitUpdated(exitId, age, utxoOwner);
}
function encodeExit(PlasmaExit storage exit) internal view returns (bytes memory) {
return
abi.encode(
exit.owner,
registry.rootToChildToken(exit.token),
exit.receiptAmountOrNFTId,
exit.txHash,
exit.isRegularExit
);
}
function encodeExitForProcessExit(uint256 exitId) internal view returns (bytes memory) {
PlasmaExit storage exit = exits[exitId];
return abi.encode(exitId, exit.token, exit.owner, exit.receiptAmountOrNFTId);
}
function encodeInputUtxo(uint256 age, Input storage input) internal view returns (bytes memory) {
return abi.encode(age, input.utxoOwner, input.predicate, registry.rootToChildToken(input.token));
}
function _addExitToQueue(
address exitor,
address rootToken,
uint256 exitAmountOrTokenId,
bytes32 txHash,
bool isRegularExit,
uint256 exitId,
address predicate
) internal {
require(exits[exitId].token == address(0x0), "EXIT_ALREADY_EXISTS");
exits[exitId] = PlasmaExit(
exitAmountOrTokenId,
txHash,
exitor,
rootToken,
isRegularExit,
predicate
);
PlasmaExit storage _exitObject = exits[exitId];
bytes32 key = getKey(_exitObject.token, _exitObject.owner, _exitObject.receiptAmountOrNFTId);
if (isRegularExit) {
require(!isKnownExit[uint128(exitId)], "KNOWN_EXIT");
isKnownExit[uint128(exitId)] = true;
} else {
// a user cannot start 2 MoreVP exits for the same erc20 token or nft
require(ownerExits[key] == 0, "EXIT_ALREADY_IN_PROGRESS");
ownerExits[key] = exitId;
}
PriorityQueue queue = PriorityQueue(exitsQueues[_exitObject.token]);
// Way priority queue is implemented is such that it expects 2 uint256 params with most significant 128 bits masked out
// This is a workaround to split exitId, which otherwise is conclusive in itself
// exitId >> 128 gives 128 most significant bits
// uint256(uint128(exitId)) gives 128 least significant bits
// @todo Fix this mess
queue.insert(exitId >> 128, uint256(uint128(exitId)));
// create exit nft
exitNft.mint(_exitObject.owner, exitId);
emit ExitStarted(exitor, exitId, rootToken, exitAmountOrTokenId, isRegularExit);
}
function checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
)
internal
view
returns (
uint256 /* createdAt */
)
{
(bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = rootChain.headerBlocks(headerNumber);
require(
keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership(
blockNumber - startBlock,
headerRoot,
blockProof
),
"WITHDRAW_BLOCK_NOT_A_PART_OF_SUBMITTED_HEADER"
);
return createdAt;
}
function getKey(
address token,
address exitor,
uint256 amountOrToken
) internal view returns (bytes32 key) {
if (registry.isERC721(token)) {
key = keccak256(abi.encodePacked(token, exitor, amountOrToken));
} else {
// validate amount
require(amountOrToken > 0, "CANNOT_EXIT_ZERO_AMOUNTS");
key = keccak256(abi.encodePacked(token, exitor));
}
}
function getDepositManager() internal view returns (DepositManager) {
return DepositManager(address(uint160(registry.getDepositManagerAddress())));
}
function getExitableAt(uint256 createdAt) internal view returns (uint256) {
return Math.max(createdAt + 2 * HALF_EXIT_PERIOD, now + HALF_EXIT_PERIOD);
}
// Housekeeping function. @todo remove later
function updateExitPeriod(uint256 halfExitPeriod) public onlyOwner {
emit ExitPeriodUpdate(HALF_EXIT_PERIOD, halfExitPeriod);
HALF_EXIT_PERIOD = halfExitPeriod;
}
}