There’s a reentrancy guard in the Sway libs. It looks good, but I can’t understand the following warning in its docs:
/// > Caution: While this can protect against both single-function reentrancy and cross-function
/// reentrancy attacks, it WILL NOT PREVENT a cross-contract reentrancy attack.
Could you please explain what is a “cross-contract reentrancy attack”?
Hey @mpoplavkov, you can have a look at the reentrancy guard here. lmk if this what you’re looking for or want anymore help
From the doc you shared:
While this can protect against both single-function reentrancy and cross-function reentrancy attacks, it WILL NOT PREVENT a cross-contract reentrancy attack.
Could you explain what does “cross-contract reentrancy attack” mean in this context?
Cross-contract reentrancy refers to a scenario that occurs when a function in one contract calls a function in another contract, which then calls back into the first contract before the initial execution is complete.
Example Scenario
- Contract A has a function
withdraw
that sends funds to a user.
- Contract B is a malicious contract that calls
withdraw
on Contract A.
- Contract A sends funds to Contract B, but before the
withdraw
function completes, Contract B calls withdraw
again on Contract A.
This can lead to Contract A’s withdraw
function being executed multiple times in a single transaction, potentially draining all funds from Contract A.
So you’re saying that this reentrancy guard won’t prevent this type of attacks? Like if the withdraw
function from your example had this guard, the second call in the same transaction won’t fail? What’s the purpose of such reentrancy guard then?
Hey @mpoplavkov, there is confusion in the above explanation of mine for the cross-contract explanation.
Here is the correct and detailed explanation.
We are reentrancy guards in our sway-libs. However, the reentrancy guard has a limitation, specifically, cross-contract reentrancy isn’t protected. You can read more about the reentrancy attacks here to distinguish between the reentrancy variants mentioned in the sway-libs in-line docs.
However, it is not necessary to use the reentrancy guard if the ‘checks-effects-interactions’ pattern is applied. In fact, the ‘checks-effects-interactions’ pattern remains the only way to prevent all types of reentrancy fully.
You can read more about our Reentrancy Guard Library in our docs here
1 Like