This repository has been archived by the owner on May 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 165
/
Bridge.sol
505 lines (440 loc) · 21.5 KB
/
Bridge.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
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
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.8.11;
pragma experimental ABIEncoderV2;
import "./utils/AccessControl.sol";
import "./utils/Pausable.sol";
import "./utils/SafeMath.sol";
import "./utils/SafeCast.sol";
import "./interfaces/IDepositExecute.sol";
import "./interfaces/IERCHandler.sol";
import "./interfaces/IGenericHandler.sol";
/**
@title Facilitates deposits, creation and voting of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl, SafeMath {
using SafeCast for *;
// Limit relayers number because proposal can fit only so much votes
uint256 constant public MAX_RELAYERS = 200;
uint8 public _domainID;
uint8 public _relayerThreshold;
uint128 public _fee;
uint40 public _expiry;
enum ProposalStatus {Inactive, Active, Passed, Executed, Cancelled}
struct Proposal {
ProposalStatus _status;
uint200 _yesVotes; // bitmap, 200 maximum votes
uint8 _yesVotesTotal;
uint40 _proposedBlock; // 1099511627775 maximum block
}
// destinationDomainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// forwarder address => is Valid
mapping(address => bool) public isValidForwarder;
// destinationDomainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) private _proposals;
event RelayerThresholdChanged(uint256 newThreshold);
event RelayerAdded(address relayer);
event RelayerRemoved(address relayer);
event Deposit(
uint8 destinationDomainID,
bytes32 resourceID,
uint64 depositNonce,
address indexed user,
bytes data,
bytes handlerResponse
);
event ProposalEvent(
uint8 originDomainID,
uint64 depositNonce,
ProposalStatus status,
bytes32 dataHash
);
event ProposalVote(
uint8 originDomainID,
uint64 depositNonce,
ProposalStatus status,
bytes32 dataHash
);
event FailedHandlerExecution(
bytes lowLevelData
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private view {
address sender = _msgSender();
require(hasRole(DEFAULT_ADMIN_ROLE, sender) || hasRole(RELAYER_ROLE, sender),
"sender is not relayer or admin");
}
function _onlyAdmin() private view {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "sender doesn't have admin role");
}
function _onlyRelayers() private view {
require(hasRole(RELAYER_ROLE, _msgSender()), "sender doesn't have relayer role");
}
function _relayerBit(address relayer) private view returns(uint) {
return uint(1) << sub(AccessControl.getRoleMemberIndex(RELAYER_ROLE, relayer), 1);
}
function _hasVoted(Proposal memory proposal, address relayer) private view returns(bool) {
return (_relayerBit(relayer) & uint(proposal._yesVotes)) > 0;
}
function _msgSender() internal override view returns (address) {
address signer = msg.sender;
if (msg.data.length >= 20 && isValidForwarder[signer]) {
assembly {
signer := shr(96, calldataload(sub(calldatasize(), 20)))
}
}
return signer;
}
/**
@notice Initializes Bridge, creates and grants {_msgSender()} the admin role,
creates and grants {initialRelayers} the relayer role.
@param domainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor (uint8 domainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry) public {
_domainID = domainID;
_relayerThreshold = initialRelayerThreshold.toUint8();
_fee = fee.toUint128();
_expiry = expiry.toUint40();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
}
}
/**
@notice Returns true if {relayer} has voted on {destNonce} {dataHash} proposal.
@notice Naming left unchanged for backward compatibility.
@param destNonce destinationDomainID + depositNonce of the proposal.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@param relayer Address to check.
*/
function _hasVotedOnProposal(uint72 destNonce, bytes32 dataHash, address relayer) public view returns(bool) {
return _hasVoted(_proposals[destNonce][dataHash], relayer);
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {_msgSender()} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
address sender = _msgSender();
require(sender != newAdmin, 'Cannot renounce oneself');
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause(_msgSender());
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause(_msgSender());
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold.toUint8();
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role.
@notice Only callable by an address that currently has the admin role, which is
checked in grantRole().
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
require(_totalRelayers() < MAX_RELAYERS, "relayers limit reached");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
}
/**
@notice Removes relayer role for {relayerAddress}.
@notice Only callable by an address that currently has the admin role, which is
checked in revokeRole().
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(address handlerAddress, bytes32 resourceID, address tokenAddress) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
uint256 depositFunctionDepositerOffset,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, depositFunctionDepositerOffset, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Sets the nonce for the specific domainID.
@notice Only callable by an address that currently has the admin role.
@param domainID Domain ID for increasing nonce.
@param nonce The nonce value to be set.
*/
function adminSetDepositNonce(uint8 domainID, uint64 nonce) external onlyAdmin {
require(nonce > _depositCounts[domainID], "Does not allow decrements of the nonce");
_depositCounts[domainID] = nonce;
}
/**
@notice Set a forwarder to be used.
@notice Only callable by an address that currently has the admin role.
@param forwarder Forwarder address to be added.
@param valid Decision for the specific forwarder.
*/
function adminSetForwarder(address forwarder, bool valid) external onlyAdmin {
isValidForwarder[forwarder] = valid;
}
/**
@notice Returns a proposal.
@param originDomainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(uint8 originDomainID, uint64 depositNonce, bytes32 dataHash) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originDomainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Returns total relayers number.
@notice Added for backwards compatibility.
*/
function _totalRelayers() public view returns (uint) {
return AccessControl.getRoleMemberCount(RELAYER_ROLE);
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee.toUint128();
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param data ABI-encoded withdrawal params relevant to the specified handler.
*/
function adminWithdraw(
address handlerAddress,
bytes memory data
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(data);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationDomainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event with all necessary parameters and a handler response.
- ERC20Handler: responds with an empty data.
- ERC721Handler: responds with the deposited token metadata acquired by calling a tokenURI method in the token contract.
- GenericHandler: responds with the raw bytes returned from the call to the target contract.
*/
function deposit(uint8 destinationDomainID, bytes32 resourceID, bytes calldata data) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationDomainID];
address sender = _msgSender();
IDepositExecute depositHandler = IDepositExecute(handler);
bytes memory handlerResponse = depositHandler.deposit(resourceID, sender, data);
emit Deposit(destinationDomainID, resourceID, depositNonce, sender, data, handlerResponse);
}
/**
@notice When called, {_msgSender()} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param domainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {_msgSender()} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(uint8 domainID, uint64 depositNonce, bytes32 resourceID, bytes calldata data) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(domainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal memory proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
if (proposal._status == ProposalStatus.Passed) {
executeProposal(domainID, depositNonce, data, resourceID, true);
return;
}
address sender = _msgSender();
require(uint(proposal._status) <= 1, "proposal already executed/cancelled");
require(!_hasVoted(proposal, sender), "relayer already voted");
if (proposal._status == ProposalStatus.Inactive) {
proposal = Proposal({
_status : ProposalStatus.Active,
_yesVotes : 0,
_yesVotesTotal : 0,
_proposedBlock : uint40(block.number) // Overflow is desired.
});
emit ProposalEvent(domainID, depositNonce, ProposalStatus.Active, dataHash);
} else if (uint40(sub(block.number, proposal._proposedBlock)) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(domainID, depositNonce, ProposalStatus.Cancelled, dataHash);
}
if (proposal._status != ProposalStatus.Cancelled) {
proposal._yesVotes = (proposal._yesVotes | _relayerBit(sender)).toUint200();
proposal._yesVotesTotal++; // TODO: check if bit counting is cheaper.
emit ProposalVote(domainID, depositNonce, proposal._status, dataHash);
// Finalize if _relayerThreshold has been reached
if (proposal._yesVotesTotal >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(domainID, depositNonce, ProposalStatus.Passed, dataHash);
}
}
_proposals[nonceAndID][dataHash] = proposal;
if (proposal._status == ProposalStatus.Passed) {
executeProposal(domainID, depositNonce, data, resourceID, false);
}
}
/**
@notice Cancels a deposit proposal that has not been executed yet.
@notice Only callable by relayers when Bridge is not paused.
@param domainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(uint8 domainID, uint64 depositNonce, bytes32 dataHash) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(domainID);
Proposal memory proposal = _proposals[nonceAndID][dataHash];
ProposalStatus currentStatus = proposal._status;
require(currentStatus == ProposalStatus.Active || currentStatus == ProposalStatus.Passed,
"Proposal cannot be cancelled");
require(uint40(sub(block.number, proposal._proposedBlock)) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
_proposals[nonceAndID][dataHash] = proposal;
emit ProposalEvent(domainID, depositNonce, ProposalStatus.Cancelled, dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param domainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@param revertOnFail Decision if the transaction should be reverted in case of handler's executeProposal is reverted or not.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
@notice Emits {FailedExecution} event with the failed reason.
*/
function executeProposal(uint8 domainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID, bool revertOnFail) public onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(domainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status == ProposalStatus.Passed, "Proposal must have Passed status");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(handler);
if (revertOnFail) {
depositHandler.executeProposal(resourceID, data);
} else {
try depositHandler.executeProposal(resourceID, data) {
} catch (bytes memory lowLevelData) {
proposal._status = ProposalStatus.Passed;
emit FailedHandlerExecution(lowLevelData);
return;
}
}
emit ProposalEvent(domainID, depositNonce, ProposalStatus.Executed, dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}