Is it possible to create a state variable that gets initialized at the start of a transaction and reset at the end?

I have to create a contract that sends value (ETH) to arbitrary addresses. I can not exclude contracts from the destinations and in order to avoid a reentrant attack, I would like to set the transaction in a executing state, so that I can verify that state at the start and react accordingly.

1 Answer 1


Short Answer.

There's no transaction-scoped state variables. In theory, you could (pseudo code)

bool private txnInProgress;

function exclusive() ...
  if(txnInProgress) throw;
  txnInProgress = true;
  // do stuff
  txnInProgress = false;

It will be harder in practice. This guy does a good job of explaining some ideas: http://www.blunderingcode.com/writing-secure-solidity/ See the bit about "Mutex".

Better answer is an opinion. It's generally better to try to negate the need for a lock. That would be preferrable IMO because it will help keep things simple.

Consider a three-step process:

  1. Optimistic accounting. Ensure the contract is in a "complete" state before interacting with an untrusted contract. For example, do the accounting, balanceOwed[user] -= amount;
  2. Attempt the interaction with the untrusted contract and test the result, e.g. if(!user.sender(amount)) ...
  3. Revert optimistic accounting in the case of failure, e.g. if(!user.send(amount)) throw; reverts the accounting performed in step 1. You safely Log success/fail events after you know the result of step 2. The take-away is that it's not safe to update the state vars after step 2.

... and preferring withdrawal patterns over pushy send patterns,

... and refraining from mixing up value transfers with other logic,

... and only talking to one untrusted contract at a time. Edge cases are more difficult to define and catch if these interactions are overly complex.

That first bit about optimistic accounting can go a long way toward re-entrance protection. One might argue that re-entrance isn't a problem unless the contract is in an incomplete state when control is transferred to an attacker.

I hope I described that reasonably well.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.