ethereum safety

A Consultant at Mavens of London, Vlad Zamfir has stated that Ethereum is not safe, scalable and an immature experimental technology.Zamfir has, therefore, urged the community not to rely on it for critical mission applications except if it is utterly unavoidable.This sedate observation was first made in a Twitter post, and later, the POS aficionados and researchers took to his blog to elaborate it.It comes as very surprising looking at where it is coming from since Zamfir is a leading member of the Ethereum community."I say it because I want you to understand where I’m coming from when I react to feeling euphoria in the Ethereum community.I felt euphoria for about the first eight to 12 months of becoming involved in Ethereum— I am not feeling any euphoria anymore.I am mostly filled with concern about how everything could go horribly wrong, with feelings of being overwhelmed, with being unable to keep up with everything that I feel requires my attention."He recognizes the fact that when the Ethereum community grows with Ether price going up, many more people will come to depend on the platform stationing decentralized applications on it and that the situation will make the network heavier but not lighter.

"While you are feeling growing euphoria because you think Ethereum is definitely the best Blockchain around, I am feeling more concerned and more stressed," Zamfir communicated.There has been a lot of controversies surrounding Ethereum in recent times.The platform witnessed a lot of criticism and attacks last year.
litecoin price expectationsSo far it has undergone four hard forks with the second being the most provocative.
lost bitcoin wallet fileActually, this particular fork altered the network's transaction history resulting in splitting the network into two.
trade bitcoin on fidelityThat was the genesis of the birth of Ethereum Classic.
bitcoin on centos

Zamfir noted in his blog post that Blockchains are not toys, they are neither get rich quick schemes nor a shiny tool for automating business processes."They are powerful technology that have the potential to do unspeakable harm.But they can also provide the basis for solutions to serious global problems," he pointed out.
bitcoin on centosHowever, he maintains he is not rubbishing Ethereum because it is not an exciting technology or he doesn't care about all the work the community is doing.
ethereal spanish translationHe claims he is very optimistic about the future of the platform but troubled by the no room for opposition."I didn’t make that tweet because Ethereum isn’t safe or scalable, really, I did it because I find the current level of euphoria quite offensive.Maybe it isn’t my place to keep euphoria in check.But I will probably continue to express myself by turning my feelings into radical, unnuanced tweets nonetheless."

Moreso, the consultant admitted Ethereum is not safe and he cannot guarantee there won't be a 51 percent attack on the network unless there is a hard fork to minimize the damage.Likewise, on smart contracts, he has the same opinion.Interestingly, he conceded a lot of smart people in the Ethereum community are working hard to make Ethereum safe and secure with smart contract formal verification efforts and with proof-of-stake consensus protocol research."I think that we will continue to make steady and impressive progress on these safety problems," Zamfir acknowledged.In the final Analysis, the Ethereum enthusiast doesn't think Ethereum is safe or scalable but optimistic that it will get better: "Granted that all Blockchains suck.Is Ethereum at least more safe or scalable than other Blockchains?But that is a nuanced discussion that won’t fit in this margin."The community is encouraged to keep this wiki updated: it becomes more complete as more contributions are added.Currently this wiki is out-of-date and see its source "Smart Contract Best Practices" for more recent updates and corrections.

We especially welcome content in the following areas: Ethereum and complex blockchain programs are new and highly experimental.Therefore, you should expect constant changes in the security landscape, as new bugs and security risks are discovered, and new best practices are developed.Following the security practices in this document is therefore only the beginning of the security work you will need to do as a smart contract developer.Smart contract programming requires a different engineering mindset than you may be used to.The cost of failure can be high, and change can be difficult, making it in some ways more similar to hardware programming or financial services programming than web or mobile development.It is therefore not enough to defend against known vulnerabilities.Instead, you will need to learn a new philosophy of development: Prepare for failure.Any non-trivial contract will have errors in it.Your code must therefore be able to respond to bugs and vulnerabilities gracefully.

Pause the contract when things are going wrong ('circuit breaker') Manage the amount of money at risk (rate limiting, maximum usage) Have an effective upgrade path for bugfixes and improvements Roll out carefully.It is always better to catch bugs before a full production release.Test contracts thoroughly, and add tests whenever new attack vectors are discovered Provide bug bounties starting from alpha testnet releases Rollout in phases, with increasing usage and testing in each phase Keep contracts simple.Complexity increases the likelihood of errors.Ensure the contract logic is simple Modularize code to keep contracts and functions small Use already-written tools or code where possible (eg.don't roll your own random number generator) Prefer clarity to performance whenever possible Only use the blockchain for the parts of your system that require decentralization Stay up to date.Use the resources listed in the next section to keep track of new security developments.

Check your contracts for any new bug that's discovered Upgrade to the latest version of any tool or library as soon as possible Adopt new security techniques that appear useful Be aware of blockchain properties.While much of your programming experience will be relevant to Ethereum programming, there are some pitfalls to be aware of.Be extremely careful about external contract calls, which may execute malicious code and change control flow.Understand that your public functions are public, and may be called maliciously.Your private data is also viewable by anyone.Keep gas costs and the block gas limit in mind.This is a list of resources that will often highlight discovered exploits in Ethereum or Solidity.The official source of security notifications is the Ethereum Blog, but in many cases vulnerabilities will be disclosed and discussed earlier in other locations.It's highly recommended that you regularly read all these sources, as exploits they note may impact your contracts.

Additionally, here is a list of Ethereum core developers who may write about security, and see the bibliography for more from the community.Beyond following core developers, it is critical to participate in the wider blockchain-related security community - as security disclosures or observations will come through a variety of parties.Calls to untrusted contracts can introduce several unexpected risks or errors.External calls may execute malicious code in that contract or any other contract that it depends upon.As such, every external call should be treated as a potential security risk, and removed if possible.When it is not possible to remove external calls, use the recommendations in the rest of this section to minimize the danger.When sending Ether, use someAddress.send() and avoid someAddress.call.value()().External calls such as someAddress.call.value()() can trigger malicious code.While send() also triggers code, it is safe because it only has access to gas stipend of 2,300 gas.Currently, this is only enough to log an event, not enough to launch an attack.

Solidity offers low-level call methods that work on raw addresses: address.call(), address.callcode(), address.delegatecall(), and address.send.These low-level methods never throw an exception, but will return false if the call encounters an exception.On the other hand, contract calls (e.g., ExternalContract.doSomething()) will automatically propagate a throw (for example, ExternalContract.doSomething() will also throw if doSomething() throws).If you choose to use the low-level call methods, make sure to handle the possibility that the call will fail, by checking the return value.Note that the Call Depth Attack can cause any call to fail, even if the external contract's code is working and non-malicious.Whether using raw calls or contract calls, assume that malicious code will execute if ExternalContract is untrusted.Even if ExternalContract is not malicious, malicious code can be executed by any contracts it calls.One particular danger is malicious code may hijack the control flow, leading to race conditions.

(See Race Conditions for a fuller discussion of this problem).As we've seen, external calls can fail for a number of reasons, including external errors and malicious Call Depth Attacks.To minimize the damage caused by such failures, it is often better to isolate each external call into its own transaction that can be initiated by the recipient of the call.This is especially relevant for payments, where it is better to let users withdraw funds rather than push funds to them automatically.(This also reduces the chance of problems with the gas limit.)When interacting with external contracts, name your variables, methods, and contract interfaces in a way that makes it clear that interacting with them is potentially unsafe.This applies to your own functions that call external contracts.All integer divison rounds down to the nearest integer.If you need more precision, consider using a multiplier, or store both the numerator and denominator.(In the future, Solidity will have a fixed-point type, which will make this easier.)

Many applications require submitted data to be private up until some point in time in order to work.on-chain rock-paper-scissors) and auction mechanisms (eg.sealed-bid second-price auctions) are two major categories of examples.If you are building an application where privacy is an issue, take care to avoid requiring users to publish information too early.Do not make refund or claim processes dependent on a specific party performing a particular action with no other way of getting the funds out.For example, in a rock-paper-scissors game, one common mistake is to not make a payout until both players submit their moves; however, a malicious player can "grief" the other by simply never submitting their move - in fact, if a player sees the other player's revealed move and determiners that they lost, they have no reason to submit their own move at all.This issue may also arise in the context of state channel settlement.When such situations are an issue, (1) provide a way of circumventing non-participating participants, perhaps through a time limit, and (2) consider adding an additional economic incentive for participants to submit information in all of the situations in which they are supposed to do so.

Fallback functions are called when a contract is sent a message with no arguments (or when no function matches), and only has access to 2,300 gas when called from a .send().If you wish to be able to receive Ether from a .send(), the most you can do in a fallback function is log an event.Use a proper function if a computation or more gas is required.Explicitly label the visibility of functions and state variables.Functions can be specified as being external, public, internal or private.For state variables, external is not possible.Labeling the visibility explicitly will make it easier to catch incorrect assumptions about who can call the function or access the variable.Currently, Solidity returns zero and does not throw an exception when a number is divided by zero.You therefore need to check for division by zero manually.Favor capitalization and a prefix in front of events (we suggest Log), to prevent the risk of confusion between functions and events.For functions, always start with a lowercase letter, except for the constructor.

With the Call Depth Attack, any call (even a fully trusted and correct one) can fail.This is because there is a limit on how deep the "call stack" can go.If the attacker does a bunch of recursive calls and brings the stack depth to 1023, then they can call your function and automatically cause all of its subcalls to fail (subcalls include send()).An example based on the previous auction code: The send() can fail if the call depth is too large, causing ether to not be sent.However, the rest of the function would succeed, including the previous line which set the victim's refund balance to 0.The solution is to explicitly check for errors, as discussed previously: One of the major dangers of calling external contracts is that they can take over the control flow, and make changes to your data that the calling function wasn't expecting.This class of bug can take many forms, and both of the major bugs that led to the DAO's collapse were bugs of this sort.The first version of this bug to be noticed involved functions that could be called repeatedly, before the first invocation of the function was finished.

This may cause the different invocations of the function to interact in destructive ways.Since the user's balance is not set to 0 until the very end of the function, the second (and later) invocations will still succeed, and will withdraw the balance over and over again.A very similar bug was one of the vulnerabilities in the DAO attack.In the example given, the best way to avoid the problem is to use send() instead of call.value()().This will prevent any external code from being executed.However, if you can't remove the external call, the next simplest way to prevent this attack is to make sure you don't call an external function until you've done all the internal work you need to do: Note that if you had another function which called withdrawBalance(), it would be potentially subject to the same attack, so you must treat any function which calls an untrusted contract as itself untrusted.See below for further discussion of potential solutions.An attacker may also be able to do a similar attack using two different functions that share the same state.

In this case, the attacker calls transfer() when their code is executed on the external call in withdrawBalance.Since their balance has not yet been set to 0, they are able to transfer the tokens even though they already received the withdrawal.This vulnerability was also used in the DAO attack.The same solutions will work, with the same caveats.Also note that in this example, both functions were part of the same contract.However, the same bug can occur across multiple contracts, if those contracts share state.Since race conditions can occur across multiple functions, and even multiple contracts, any solution aimed at preventing reentry will not be sufficient.Instead, we have recommended finishing all internal work first, and only then calling the external function.This rule, if followed carefully, will allow you to avoid race conditions.However, you need to not only avoid calling external functions too soon, but also avoid calling functions which call external functions.For example, the following is insecure: Even though getFirstWithdrawalBonus() doesn't directly call an external contract, the call in withdraw() is enough to make it vulnerable to a race condition.

you therefore need to treat withdraw() as if it were also untrusted.In addition to the fix making reentry impossible, untrusted functions have been marked.This same pattern repeats at every level: since untrustedGetFirstWithdrawalBonus() calls untrustedWithdraw(), which calls an external contract, you must also treat untrustedGetFirstWithdrawalBonus() as insecure.Another solution often suggested is a mutex.This allows you to "lock" some state so it can only be changed by the owner of the lock.A simple example might look like this: If the user tries to call withdraw() again before the first call finishes, the lock will prevent it from having any effect.This can be an effective pattern, but it gets tricky when you have multiple contracts that need to cooperate.The following is insecure: An attacker can call getLock(), and then never call releaseLock().If they do this, then the contract will be locked forever, and no further changes will be able to be made.If you use mutexes to protect against race conditions, you will need to carefully ensure that there are no ways for a lock to be claimed and never released.

(There are other potential dangers when programming with mutexes, such as deadlocks and livelocks.You should consult the large amount of literature already written on mutexes, if you decide to go this route.)Consider a simple auction contract: When it tries to refund the old leader, it throws if the refund fails.This means that a malicious bidder can become the leader, while making sure that any refunds to their address will always fail.In this way, they can prevent anyone else from calling the bid() function, and stay the leader forever.A natural solution might be to continue even if the refund fails, under the theory that it's their own fault if they can't accept the refund.But this is vulnerable to the Call Depth Attack!So instead, you should set up a pull payment system instead, as described earlier.Another example is when a contract may iterate through an array to pay users (e.g., supporters in a crowdfunding contract).It's common to want to make sure that each payment succeeds.

If not, one should throw.The issue is that if one call fails, you are reverting the whole payout system, meaning the loop will never complete.No one gets paid, because one address is forcing an error.Again, the recommended solution is to favor pull over push payments.You may have noticed another problem with the previous example: by paying out to everyone at once, you risk running into the block gas limit.Each Ethereum block can process a certain maximum amount of computation.If you try to go over that, your transaction will fail.This can lead to problems even in the absence of an intentional attack.However, it's especially bad if an attacker can manipulate the amount of gas needed.In the case of the previous example, the attacker could add a bunch of addresses, each of which needs to get a very small refund.The gas cost of refunding each of the attacker's addresses could therefore end up being more than the gas limit, blocking the refund transaction from happening at all.This is another reason to favor pull over push payments.

If you absolutely must loop over an array of unknown size, then you should plan for it to potentially take multiple blocks, and therefore require multiple transactions.You will need to keep track of how far you've gone, and be able to resume from that point, as in the following example: Note that this is vulnerable to the Call Depth Attack, however.And you will need to make sure that nothing bad will happen if other transactions are processed while waiting for the next iteration of the payOut() function.So only use this pattern if absolutely necessary.The timestamp of the block can be manipulated by the miner, and so should not be used for critical components of the contract.Block numbers and average block time can be used to estimate time, but this is not future proof as block times may change (such as the changes expected during Casper).Since a transaction is in the mempool for a short while, one can know what actions will occur, before it is included in a block.This can be troublesome for things like decentralized markets, where a transaction to buy some tokens can be seen, and a market order implemented before the other transaction gets included.

Protecting against this is difficult, as it would come down to the specific contract itself.For example, in markets, it would be better to implement batch auctions (this also protects against high frequency trading concerns).Another way to use a pre-commit scheme (“I’m going to submit the details later”).As we discussed in the General Philosophy section, it is not enough to protect yourself against the known attacks.Since the cost of failure on a blockchain can be very high, you must also adapt the way you write software, to account for that risk.The approach we advocate is to "prepare for failure".It is impossible to know in advance whether your code is secure.However, you can architect your contracts in a way that allows them to fail gracefully, and with minimal damage.This section presents a variety of techniques that will help you prepare for failure.Note: There's always a risk when you add a new component to your system.A badly designed fail-safe could itself become a vulnerability - as can the interaction between a number of well designed fail-safes.

Be thoughtful about each technique you use in your contracts, and consider carefully how they work together to create a robust system.Code will need to be changed if errors are discovered or if improvements need to be made.It is no good to discover a bug, but have no way to deal with it.Designing an effective upgrade system for smart contracts is an area of active research, and we won't be able to cover all of the complications in this document.However, there are two basic approaches that are most commonly used.The simpler of the two is to have a registry contract that holds the address of the latest version of the contract.A more seamless approach for contract users is to have a contract that forwards calls and data onto the latest version of the contract.Whatever the technique, it's important to have modularization and good separation between components, so that code changes do not break functionality, orphan data, or require substantial costs to port.In particular, it is usually beneficial to separate complex logic from your data storage, so that you do not have to recreate all of the data in order to change the functionality.

It's also critical to have a secure way for parties to decide to upgrade the code.Depending on your contract, code changes may need to be approved by a single trusted party, a group of members, or a vote of the full set of stakeholders.If this process can take some time, you will want to consider if there are other ways to react more quickly in case of an attack, such as an emergency stop or circuit-breaker.Example 1: Use a registry contract to store latest version of a contract In this example, the calls aren't forwarded, so users should fetch the current address each time before interacting with it.There are two main disadvantages to this approach: The alternate approach is to have a contract forward calls and data to the latest version of the contract: Example 2: Use a DELEGATECALL to forward data and calls This approach avoids the previous problems, but has problems of its own.You must be extremely careful with how you store data in this contract.If your new contract has a different storage layout than the first, your data may end up corrupted.

Additionally, this simple version of the pattern cannot return values from functions, only forward them, which limits its applicability.(More complex implementations attempt to solve this with in-line assembly code and a registry of return sizes.)Regardless of your approach, it is important to have some way to upgrade your contracts, or they will become unusable when the inevitable bugs are discovered in them.Circuit breakers stop execution if certain conditions are met, and can be useful when new errors are discovered.For example, most actions may be suspended in a contract if a bug is discovered, and the only action now active is a withdrawal.You can either give certain trusted parties the ability to trigger the circuit breaker, or else have programmatic rules that automatically trigger the certain breaker when certain conditions are met.Speed bumps slow down actions, so that if malicious actions occur, there is time to recover.For example, The DAO required 27 days between a successful request to split the DAO and the ability to do so.

This ensured the funds were kept within the contract, increasing the likelihood of recovery.In the case of the DAO, there was no effective action that could be taken during the time given by the speed bump, but in combination with our other techniques, they can be quite effective.Rate limiting halts or requires approval for substantial changes.For example, a depositor may only be allowed to withdraw a certain amount or percentage of total deposits over a certain time period (e.g., max 100 ether over 1 day) - additional withdrawals in that time period may fail or require some sort of special approval.Or the rate limit could be at the contract level, with only a certain amount of tokens issued by the contract over a time period.An assert guard triggers when an assertion fails - such as an invariant property changing.For example, the token to ether issuance ratio, in a token issuance contract, may be fixed.You can verify that this is the case at all times with an assertion.Assert guards should often be combined with other techniques, such as pausing the contract and allowing upgrades.

(Otherwise you may end up stuck, with an assertion that is always failing.)The following example reverts transactions if the ratio of ether to total number of tokens changes: Contracts should have a substantial and prolonged testing period - before substantial money is put at risk.During testing, you can force an automatic deprecation by preventing any actions, after a certain time period.For example, an alpha contract may work for several weeks and then automatically shut down all actions, except for the final withdrawal.In the early stages, you can restrict the amount of Ether for any user (or for the entire contract) - reducing the risk.When launching a contract that will have substantial funds or is required to be mission critical, it is important to include proper documentation.Some documentation related to security includes: Oyente - An upcoming tool, will analyze Ethereum code to find common vulnerabilities (e.g., Transaction Order Dependence, no checking for exceptions) Solgraph - Generates a DOT graph that visualizes function control flow of a Solidity contract and highlights potential security vulnerabilities.

solint - Another upcoming tool, will provide Solidity linting that helps you enforce consistent conventions and avoid errors in your Solidity smart-contracts.Editor Security Warnings: Editors will soon alert for common security errors, not just compilation errors.Browser Solidity is getting these features soon.New functional languages that compile to EVM bytecode: Functional languages gives certain guarantees over procedural languages like Solidity, namely immutability within a function and strong compile time checking.This can reduce the risk of errors by providing deterministic behavior.(for more see this, Curry-Howard correspondence, and linear logic) A lot of this document contains code, examples and insights gained from various parts already written by the community.Here are some of them.Feel free to add more.This work, "Safety", is a derivative of "Smart Contract Best Practices", used under CC BY."Safety" is licensed under CC BY by the Ethereum community.Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International