NEWTON
Asked
3 months ago
84
views
0
Everyone knows that secure code is essential. Can someone explain what is reentrancy? I am curious about the reentrancy attack in StarkNet – is it a problem in Cairo Language and how to protect my smart contract from this attack?
Newton
asked
3 months ago
1
Accepted answer
Reentrancy is a very common attack in smart contracts, due to contracts often being required to call other contracts. As we cannot control what another contract does, it might be possible that the called contract initiates a callback to the original contract. This can be very dangerous if the original contract does not follow the checks-effects-interaction pattern, which states that we should not make changes to state variables after interacting with an external entity.
For instance, let's take a (very generalized) contract which stores users balances and allows to make transfers using arbitrary tokens. In this case, the pattern should be the following:
Should step 2 and 3 be inverted, and the arbitrary contract called would perform a callback to our original contract, the balance of the user would not have been updated and another transfer could be made on its behalf.
On top of following the checks-effects-interaction pattern, we can use Reentrancy guards to protect our contracts. In Cairo, we have OpenZeppelin's implementation.
This is as simple as calling ReentrancyGuard._start()
at the beginning of a function, and ReentrancyGuard._end()
at the end. This will prevent any reentrant call in the code, as if the funciton is reentered, it will error out due the storage variable ReentrancyGuard_entered
being set to true. An example below:
@external func callback{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr}() { ReentrancyGuard._start(); _count(); ReentrancyGuard._end(); return (); }
ctrlc03
answered
3 months ago
What is the proxy pattern and how it can help make my smart contracts upgradable in Cairo Language?
What libraries are secure to use in Cairo?
What are events in Cairo Language?
Did you change the factory/create2 part (to compute pool addresses)? What's easier, adapt the create2 trick in Solidity then transpile or transpile first then adapt in Cairo?
How to submit a StarkNet contract?
How to fix invalid character error while invoking starknetjs frontend app in Cairo?
What if my solidity contract contains Assembly or special EVM calls ?
Cairo error: Accessing struct/tuple members for r-value structs is not supported yet
Is starknet.id legit?
Cairo Error calling function: Expected 'function_name' to be a struct. Found: 'function'.
Does cross-chain bridge produce its own block? Or it only verify the blocks from A/B chain?
How to make conditional expressions if..then..else in Cairo lang?
An issue while updating to 0.3.3 node StarkNet
Is there a way to find events in a block without getting receipt for all transactions on Starknet?