Announcement of imminent hard fork for EIP150 gas cost changes


During the last couple of weeks, the Ethereum network has been the target of a sustained attack. The attacker(s) have been very crafty in locating vulnerabilities in the client implementations as well as the protocol specification.

While the recent patches have led to an overall increased resiliency in the client implementations, the attacks have also demonstrated that a lower-level change to the EVM pricing model is needed.

For many users, the most visible consequence is probably that they are having difficulties getting transactions included in blocks, and full nodes are facing memory limitations in managing the bloated state.

This is our strategy to address these issues:

  • As a temporary measure to minimize the effects of the most recent attack, we recommend all miners to lower the gaslimit to 500K gas.
  • A hard-fork based on EIP 150 version 1c will be put into effect at block 2457000. This will reprice certain operations to correspond better to the underlying computational complexity.
  • A second hard-fork will follow shortly after, aimed at reverting the current “state-bloat” introduced by the attacks. This second fork will serve to remove accounts which are empty; lacking code, balance, storage and nonce == 0.

We have implemented the changes required in the clients and are currently extending and adding tests in an effort to prevent the introduction of consensus-breaking vulnerabilities.

And as a reminder, the Ethereum Bug Bounty [2] is open and includes the new hardfork-implementations.

The post Announcement of imminent hard fork for EIP150 gas cost changes appeared first on Ethereum Blog.

Transaction spam attack: Next Steps

Today the network was attacked by a transaction spam attack that repeatedly called the EXTCODESIZE opcode (see trace sample here), thereby creating blocks that take up to ~20-60 seconds to validate due to the ~50,000 disk fetches needed to process the transaction. The result of this was a ~2-3x reduction in the rate of block creation while the attack was taking place; there was NO consensus failure (ie. network fork) and neither the network nor any client at any point fully halted. The attack has since, as of the time of this writing, mostly halted, and the network has for the time being recovered.

The short-term fix is for users, including miners, enterprise users (including exchanges) and individuals to run geth with the flags:

--cache 1024 --targetgaslimit 1500000 --gasprice 20000000000

Or Parity with the flags:

--cache-size-db 1024 --gas-floor-target 1500000 --gasprice 20000000000 --gas-cap 1500000

This (i) increases the cache size, reducing the number of disk reads that nodes need to make, and (ii) votes the gas limit down by ~3x, reducing the maximum processing time of a block by a similar factor.

In the medium term (ie. several days to a week), we are actively working on several fixes for the Go client that should both provide a more stable resolution for the present issue and mitigate the risk of similar attacks, including:

  • A change to miner software that automatically temporarily cuts the gas limit target by 2x when the miner sees a block that takes longer than 5 seconds to process, allowing for adjustments similar to what was coordinated today to happen automatically (see here for a pull request; note that this is a miner strategy change and NOT a soft fork or hard fork)
  • Numerical tweaks to cache settings
  • Adding additional caches
  • Adding an additional cache for EXTCODESIZE specifically (as it is likely that EXTCODESIZE reads are several times slower than other IO-heavy operations since the contracts that are being read are ~18 KB long)
  • An on-disk cache of state values that allows them to be more quickly (ie. O(log(n)) speedup) accessed

We are also exploring the option of replacing the leveldb database with something more performant and optimized for our use case, though such a change would not come soon. The Parity team is working on their own performance improvements.

In the longer term, there are low-level protocol changes that can also be explored. For example it may be wise to add a feature to Metropolis to increase the gas costs of opcodes that require reads of account state (SLOAD, EXTCODESIZE, CALL, etc), and especially read operations that read external accounts; increasing the gas cost of all of these operations to at least 500 would likely be sufficient, though care would need to be taken to avoid breaking existing contracts (eg. simultaneously implementing EIP 90 would suffice).

This would put a much lower upper bound on the maximum number of bytes that a transaction may read, increasing safety against all potential attacks of this kind, and reducing the size of Merkle proofs and hence improving security for both light clients and sharding as a side effect. At present, we are focusing on the more immediate software-level changes; however, in the long term such proposals should be discussed and contract developers should be aware that changes of this sort may take place.

The post Transaction spam attack: Next Steps appeared first on Ethereum Blog.

from Ethereum Blog

The Ethereum network is currently undergoing a DoS attack

URGENT ALL MINERS: The network is under attack. The attack is a computational DDoS, ie. miners and nodes need to spend a very long time processing some blocks. This is due to the EXTCODESIZE opcode, which has a fairly low gasprice but which requires nodes to read state information from disk; the attack transactions are calling this opcode roughly 50,000 times per block. The consequence of this is that the network is greatly slowing down, but there is NO consensus failure or memory overload. We have currently identified several routes for a more sustainable medium-term fix and have developers working on implementation.

It is highly reccomended to switch to Parity mining. Use these settings:

–cache-size-db 1024 –gas-floor-target 1000000 –gasprice 500000000000

Parity mining guides:

If you continue to use geth, use the following settings:

–cache 1024 –targetgaslimit 1000000 –gasprice 50000000000

The post The Ethereum network is currently undergoing a DoS attack appeared first on Ethereum Blog.

from Ethereum Blog


Security alert – All geth nodes crash due to an out of memory bug

Security Alert

Affected configurations: Geth

Likelihood: High

Severity: High

Summary: geth nodes running out of memory and crashing on block

Details: TBD

Proposed solution: Switch to an alternative client until fix is provided:

The post Security alert – All geth nodes crash due to an out of memory bug appeared first on Ethereum Blog.

from Ethereum Blog


NSA Hacked? Cyber Super-Weapons for sale?


A group of hackers, using the moniker “The Shadow Brokers”, claim to have done the unthinkable – hacked the NSA. To backup this claim they are auctioning off their spoils of cyber-war – The NSA’s prize arsenal of cyber-super-weapons – for a cool $1m in bitcoin.

The group have posted their manifesto up on pastebin, github and tumblr. It is interesting that the group refer to their victim as “The Equation Group”, which is the well known codename for the government agency.

The interesting element to this is that posted a collection of NSA malware scripts. It’s unclear at this time whether these are connected, but the cryptome source appears to be Wikileaks. Looking at the contents of each leak, the names of the malware seem to link up, although the cryptome leak is less substantial.


For more details:


Daily Dot


Onward from the Hard Fork

The foundation has committed to support the community consensus on the admittedly difficult hard fork decision. Seeing the results of various metrics, including carbonvote, dapp and ecosystem infrastructure adoption, this means that we will focus our resources and attention on the chain which is now called ETH (ie. the fork chain). That said, we recognize that the Ethereum code can be used to instantiate other blockchains with the same consensus rules, including testnets, consortium and private chains, clones and spinoffs, and have never been opposed to such instantiations.

All users who had ETH before block 1920000 now have both ETH (the fork chain) and ETC (the community effort to continue the no-fork chain). Users are generally advised that most Ethereum client defaults will select the ETH chain; if you are offered a choice on a fork in the Mist interface, then selecting “Yes” on this choice will direct you to this chain.

Users who are interested in taking any actions with their ETC, including creating and participating in applications, converting to another asset, etc are advised to use the splitter contract at address 0xaa1a6e3e6ef20068f7f8d8c835d2d22fd5116444 to move their ETC to a separate newly created account so as to avoid replay attacks; we also encourage the ETC community to consider adopting a secondary hard fork to change transaction formats to make further replay attacks impossible. Until and unless that happens, once ETH and ETC are “split” they should be managed via separate wallets.

To use the splitter contract from inside of the Ethereum Wallet, click on Contracts -> Watch Contract, copy the address and ABI from the above linked etherscan page, and click “OK”; then, click on the contract in the Contracts tab, select “Write to Contract”, and select the “Split” function. It will ask for two addresses; for the first, put the address where you want your ETH to go (feel free to put the same address you are sending from), for the second put the address where you want the ETC to go. Make sure to try this with a very small amount of ether first to verify that it works before increasing the amount. You may use the Ethereum Classic Explorer here to verify that ETC balances have been transferred. A more detailed community-provided guide can be found here.

The post Onward from the Hard Fork appeared first on Ethereum Blog.

from Ethereum Blog

Hive: How we strived for a clean fork

The DAO soft-fork attempt was difficult. Not only did it turn out that we underestimated the side effects on the consensus protocol (i.e. DoS vulnerability), but we also managed to introduce a data race into the rushed implementation that was a ticking time bomb. It was not ideal, and even though averted at the last instance, the fast approaching hard-fork deadline looked eerily bleak to say the least. We needed a new strategy…

The stepping stone towards this was an idea borrowed from Google (courtesy of Nick Johnson): writing up a detailed postmortem of the event, aiming to assess the root causes of the issue, focusing solely on the technical aspects and appropriate measures to prevent recurrence.

Technical solutions scale and persist; blaming people does not. ~ Nick

From the postmortem, one interesting discovery from the perspective of this blog post was made. The soft-fork code inside go-ethereum seemed solid from all perspectives: a) it was thoroughly covered by unit tests with a 3:1 test-to-code ratio; b) it was thoroughly reviewed by six foundation developers; and c) it was even manually live tested on a private network… Yet still, a fatal data race remained, which could have potentially caused severe network disruption.

It transpired that the flaw could only ever occur in a network consisting of multiple nodes, multiple miners and multiple blocks being minted simultaneously. Even if all of those scenarios held true, there was only a slight chance for the bug to surface. Unit tests cannot catch it, code reviewers may or may not catch it, and manual testing catching it would be unlikely. Our conclusion was that the development teams needed more tools to perform reproducible tests that would cover the intricate interplay of multiple nodes in a concurrent networked scenario. Without such a tool, manually checking the various edge cases is unwieldy; and without doing these checks continuously as part of the development workflow, rare errors would become impossible to discover in time.

And thus, hive was born…

What is hive?

Ethereum grew large to the point where testing implementations became a huge burden. Unit tests are fine for checking various implementation quirks, but validating that a client conforms to some baseline quality, or validating that clients can play nicely together in a multi client environment, is all but simple.

Hive is meant to serve as an easily expandable test harness where anyone can add tests (be those simple validations or network simulations) in any programming language that they are comfortable with, and hive should simultaneously be able to run those tests against all potential clients. As such, the harness is meant to do black box testing where no client specific internal details/state can be tested and/or inspected, rather emphasis would be put on adherence to official specs or behaviors under different circumstances.

Most importantly, hive was designed from the ground up to run as part of any clients’ CI workflow!

How does hive work?

Hive’s body and soul is docker. Every client implementation is a docker image; every validation suite is a docker image; and every network simulation is a docker image. Hive itself is an all encompassing docker image. This is a very powerful abstraction…

Since Ethereum clients are docker images in hive, developers of the clients can assemble the best possible environment for their clients to run in (dependency, tooling and configuration wise). Hive will spin up as many instances as needed, all of them running in their own Linux systems.

Similarly, as test suites validating Ethereum clients are docker images, the writer of the tests can use any programing environment he is most familiar with. Hive will ensure a client is running when it starts the tester, which can then validate if the particular client conforms to some desired behavior.

Lastly, network simulations are yet again defined by docker images, but compared to simple tests, simulators not only execute code against a running client, but can actually start and terminate clients at will. These clients run in the same virtual network and can freely (or as dictated by the simulator container) connect to each other, forming an on-demand private Ethereum network.

How did hive aid the fork?

Hive is neither a replacement for unit testing nor for thorough reviewing. All current employed practices are essential to get a clean implementation of any feature. Hive can provide validation beyond what’s feasible from an average developer’s perspective: running extensive tests that can require complex execution environments; and checking networking corner cases that can take hours to set up.

In the case of the DAO hard-fork, beyond all the consensus and unit tests, we needed to ensure most importantly that nodes partition cleanly into two subsets at the networking level: one supporting and one opposing the fork. This was essential since it’s impossible to predict what adverse effects running two competing chains in one network might have, especially from the minority’s perspective.

As such we’ve implemented three specific network simulations in hive:

  • The first to check that miners running the full Ethash DAGs generate correct block extra-data fields for both pro-forkers and no-forkers, even when trying to naively spoof.

  • The second to verify that a network consisting of mixed pro-fork and no-fork nodes/miners correctly splits into two when the fork block arrives, also maintaining the split afterwards.

  • The third to check that given an already forked network, newly joining nodes can sync, fast sync and light sync to the chain of their choice.

The interesting question though is: did hive actually catch any errors, or did is just act as an extra confirmation that everything’s all right? And the answer is, both. Hive caught three fork-unrelated bugs in Geth, but also heavily aided Geth’s hard-fork development by continuously providing feedback on how changes affected network behavior.

There was some criticism of the go-ethereum team for taking their time on the hard-fork implementation. Hopefully people will now see what we were up to, while concurrently implementing the fork itself. All in all, I believe hive turned out to play quite an important role in the cleanness of this transition.

What is hive’s future?

The Ethereum GitHub organization features 4 test tools already, with at least one EVM benchmark tool cooking in some external repository. They are not being utilised to their full extent. They have a ton of dependencies, generate a ton of junk and are very complicated to use.

With hive, we’re aiming to aggregate all the various scattered tests under one universal client validator that has minimal dependencies, can be extended by anyone, and can run as part of the daily CI workflow of client developers.

We welcome anyone to make contributions to the project, be that adding new clients to validate, validators to test with, or simulators to find interesting networking issues. In the meantime, we’ll try to further polish hive itself, adding support for running benchmarks as well as mixed-client simulations.

With a bit or work, maybe we’ll even have support for running hive in the cloud, allowing it to run network simulations at a much more interesting scale.

The post Hive: How we strived for a clean fork appeared first on Ethereum Blog.

from Ethereum Blog

Hard Fork Completed

We would like to congratulate the Ethereum community on a successfully completed hard fork. Block 1920000 contained the execution of an irregular state change which transferred ~12 million ETH from the “Dark DAO” and “Whitehat DAO” contracts into the WithdrawDAO recovery contract. The fork itself took place smoothly, with roughly 85% of miners mining on the fork:


You can see ongoing fork progress here. EthStats shows Go, Java and Parity (Rust) nodes successfully synchronized to the fork chain.

The recovery contract is already returning DAO token holders’ ether; about 4.5 million ETH has been sent to DAO token holders, and about 463000 ETH is in the control of the curator; a contract to facilitate extrabalance payments is currently undergoing security review.

Users who are interested only in participating in the fork chain should upgrade their clients to a fork-compatible version if they have not already done so; the upgraded Go client (version 1.4.10) is available here. If any users continue to be interested in following the non-fork chain, they should still update, but run with the --oppose-dao-fork flag enabled, though they should beware of transaction replay attacks and take appropriate steps to guard against them; users with no interest in the non-fork chain do not need to worry about transaction replay attack concerns.

We thank our developers and the community for working together to make the transition as smooth as it has been, and look forward to working together to continue to make the Ethereum ecosystem and protocol a success.

The post Hard Fork Completed appeared first on Ethereum Blog.

from Ethereum Blog


To fork or not to fork’s “The DAO” has been a hot topic as of late, both internally in the organisation as well as within our community. The Hard Fork is a delicate topic and the way we see it, no decision is the right one. As this is not a decision that can be made by the foundation or any other single entity, we again turn towards the community to assess its wishes in order to provide the most appropriate protocol change.

The specification proposed for the hard fork that is being implemented in the Geth client is as follows:

The DAO (0xbb9bc244d798123fde783fcc1c72d3bb8c189413), its extraBalance (0x807640a13483f8ac783c557fcdf27be11ea4ac7a), all children of the DAO creator (0x4a574510c7014e4ae985403536074abe582adfc8) and the extrabalance of each child are encoded into a list L at block 1880000. The contents of L can be viewed here. At the beginning of block X (X = 1920000, on July 20 or 21 depending on your time zone), all ether throughout all accounts in L will be transferred to contract account C, which is at (0xbf4ed7b27f1d666546e30d74d50d173d20bca754). You can verify the solidity source code of C on etherscan. From this contract, DAO token holders can submit their DAO in order to withdraw ETH at a rate of 1 ETH = 100 DAO. The extrabalance, as well as some additional ether that remains due to complications in the interactions between the re-entrancy exploit and the splitting mechanism, will be withdrawable by the DAO curator to be distributed as appropriate to cover all edge cases.

Additional information to facilitate verification of the fork spec and implementation is expected to be released separately by the community; consensus code in Geth that implements the fork logic is covered by the bug bounty program.

Unfortunately time limits require swift adoption before a protocol change becomes impractical. The community tool carbonvote will be used to set the default fork option for Geth. At block number 1894000 the votes will be tallied, and the outcome will determine whether the default is set to fork on not to fork. Then merging the DAO fork PRs will proceed, followed shortly by a release for both Geth and Mist. Users with business-critical applications who need to update quickly should frequently check the blog and social media for ongoing updates.

The post To fork or not to fork appeared first on Ethereum Blog.

from Ethereum Blog


How to build server less applications for Mist

Ethereum is not meant to be a platform to build esoteric smart contract applications that require a STEM degree to understand, but it aims to be one pillar of a different architecture for applications on the world wide web. With this post we will try to elucidate how this can be done and give some basic examples on how to start building a decentralized app.

Who is this for?

This text is intended at those who have a basic understanding of web technology and how to build a simple javascript and html app, and want to convert these skills into building apps for the Ethereum ecosystem.

How can apps run without servers?

Currently servers in web apps do much more than what they were originally intended to. Besides serving static web pages, they also keep private information, handle user authentication and deal with all the complicated ways in which data is analyzed and saved. All the user computer does – a device which would be considered a super computer when the web was invented – is to load and display that information to the user.

Current server models

Instead, a more decentralized architecture would allow a much more modular approach, in which different machines and different protocols would handle specific tasks, some on the user’s side and some in specialized machines deployed on a peer to peer network. Therefore all the Data logic (what gets saved, who saves it, how to solve conflicts etc) is handled by smart contracts on the blockchain, static files are served via Swarm and realtime communication over Whisper. The user device keeps the user authentication and runs the application interface.

Doing this would remove the danger of data breach and attacks as there are less single nodes keeping tons of unencrypted data, while also removing the load and cost of serving apps by distributing it across the network. Since all those protocols are decentralized, anyone can connect to the network and start providing a specialized service: if the user is browsing from a powerful laptop, for instance, they can also serve static files to network neighbors.


Decentralised Server models

A decentralized architecture also encourages innovation: since the interface is detached from the data, anyone can come up with a new interface to the same app, creating a more vibrant and competing ecosystem. Arguably, one of the most interesting and innovative periods in Twitter history was when it served mostly as a central data hub and anyone could build their  Twitter Application.

See it working

If you want to experiment with the app before learning it, we recommend you download Mist and read our introductory tutorial to how to install the app and run it. If you just want to see the whole app instead, you can download it directly from the Stake Voice Github repository.


Stake Voice running on the Mist Browser

Let’s get to it

We are going to build a very simple application called “Stake Voice”. The idea is to allow ether stakers to vote on anything they want, and the app will tally the total ether balance of all those who agree or disagree with the statement.

The app underlying contract is written in Solidity, a javascript-like language and is very simple:

contract EtherVote {
    event LogVote(bytes32 indexed proposalHash, bool pro, address addr);
    function vote(bytes32 proposalHash, bool pro) {
<sp        if (msg.value > 0) throw;
        LogVote(proposalHash, pro, msg.sender);
    function () { throw; }

The first line sets up the contract name and the second creates an event called “LogVote”, which will output in the log the following:

  • a hash of the proposal being voted on
  • if the voter agrees or disagrees with it
  • the address of the voter

The function “vote” will then fire the log, which the application later will count. It also has a check that no ether can be sent accidentally. The “anonymous”  function is executed when any ether is deposited on the smart contract and will then automatically reject it.

If you want to learn more about coding in Solidity we recommend you start on the ethereum solidity tutorials, read the  official documentation page and try it on your browser using the online compiler.

That’s essentially it: you choose a hash, choose a side and execute Vote(). So how does this translates into a polling app?

Serverless Architecture

Following the principle of KISS, we are doing the minimum product possible that is still usable, meaning we won’t be using databases for storing proposals or using any feature that requires anything other than vanilla javascript and pure html.

So we will use the URL of the app itself to keep the proposal text, and we will use that to display it to the user and generate a hash that can then be used to check the votes. The users can use social media to share which proposals they want to debate or simply use direct links.

// On the initial startup function:
proposal = decodeURI(getParameterByName('proposal'));

// get parameter function
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));

Start with basics

So grab your favorite html framework and get a basic website on your local machine and open it on Mist. All pages in Mist have access to a javascript object called web3 which will where you will be working the most.  First thing we need to do is check if web3 is present or not:

Function init() {
if(typeof web3 == 'undefined') {
    // Alert the user they are not in a web3 compatible browser

Some application developers might want to load their own web3 object, to guarantee forward compatibility. To do that, just add just before </body> tag:


And then add this on your initial function to load your own custom web3 provider:

// Checks Web3 support
if(typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {
    // If there's a web3 library loaded, then make your own web3
    web3 = new Web3(web3.currentProvider);
} else if (typeof Web3 !== 'undefined') {
    // If there isn't then set a provider
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
} else if(typeof web3 == 'undefined') {
    // Alert the user he is not in a web3 compatible browser

Load information from the blockchain

You checked you are connected to a blockchain, but which one? Is it the main ethereum network? Maybe a testnet or a private network? Maybe it’s a fork in the future and your chain is a brand new one. The best way to check this is to see if the contract address you want to load has any code on it.

Furthermore, to execute a contract you need to know two basic things: it’s address and the ABI, which will be a json encoded file containing interface information.

var contractAddress = '0x1e9d5e4ed8ef31cfece10b4c92c9057f991f36bc';
var contractABI = [{"constant":false,"inputs":[{"name":"proposalHash","type":"bytes32"},{"name":"pro","type":"bool"}],"name":"vote","outputs":[],"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"proposalHash","type":"bytes32"},{"indexed":false,"name":"pro","type":"bool"},{"indexed":false,"name":"addr","type":"address"}],"name":"LogVote","type":"event"}];

Now that you have those, you can check if the contract exist on the startup function:

// Load the contract
web3.eth.getCode(contractAddress, function(e, r) { 
    if (!e && r.length > 3) 

You can even run this command recursively, to try connecting to it again using another address (in case you are actually on the testnet). Once you have found your contract you can load it up here:

Function   loadContract() {
// load the contract to javascript
      ethervoteContract = web3.eth.contract(contractABI);
      ethervote =;

You are using the web3 object to create a new a javascript object that will be able to execute all the ethereum commands directly from the browser. If you want to load only a single instance of the contract, then you can even do it in one line:

ethervote = web3.eth.contract(contractABI).at(contractAddress);

Identify the user

Knowing the user’s account reveals a lot of information about the user: how much ether and any other tokens it has on its balance, and their transaction history. So having all apps know this by default would create a super cookie and would be an unacceptable invasion of privacy. On the other hand, requiring the user to create an user account with login information for each site is not only a pain for the user, but also puts your private information in control of third parties, which creates giant honey pots that can be breached by hackers.

As a result of this dilemma most users have most of their personal information and authentication information handled by a half dozen billion dollar corporation. Privacy should not be a compromise we accept in exchange of practicality: users should be able to easily authenticate into any app while being in control of their own personal information.

Using Mist, apps have no information about the user, until the user decides to reveal itself to the app. When you want to query what you know about the accounts, you should call the getAccounts function:

    if (!e) {
        // do something with the accounts

Currently, the returning object is an array that holds simple accounts that the user has local access to, but in the future it will also hold smart contract accounts the user uses to identify themselves. This will allow the user to have access to features currently available only to centralized authenticators, like two factor authentication or cloud backup, and to future improvements only available to smart contracts, like allowing a few trusted friends to give you access to an account for which you lost keys or having automatic inheritance of inactive accounts.

Each future Ethereum browser will handle how users identify themselves to the App. In Mist we have two ways: either the user can initiate it by clicking the “connect” button (currently it’s just called a “no accounts” button) or the App can request the authentication by calling the “requestAccount” api.

Attention: the accounts on this list are just one which the user claims to hold the key to, but the user has provided no proof of doing, therefore you can show a different UI, but don’t send the user any secret information intended only to that account. If you require the user to prove their identity you need them to sign a message, while Mist will also support that in the future, keep it in mind that it would force the user to add an extra step and type their password, so you should only use that when absolutely necessary.



Once you have the contract as an object, voting is a matter of calling it from javascript. This will pop up a Mist transaction pane, where the user will be able to check the transaction and then type their password. So first we will create two clickable objects that calls a vote function:

document.getElementById('vote-support').addEventListener('click', function(){ vote(true);}, false);
document.getElementById('vote-against').addEventListener('click', function(){ vote(false);}, false);

Notice that one calls the function with a true parameter and the other false. The function vote could be as simple as:

Function vote() {, support, {from: web3.eth.accounts[0]});

“Ethervote” is the object we created before, and “vote” is one of its functions, which correspond to one of the contract functions:

function vote(bytes32 proposalHash, bool pro) {

We pass the two parameters demanded by the function and then add a third object containing transaction informations, like who is it being sent from and optionally, how much gas to include or how much to pay for the gas.

Consequently this would generate a panel asking the user to confirm the transaction – but most likely it will return an error because currently the web3.eth.accounts object is an empty array by default, so you have to check for that and if empty, request the accounts to the user:

function vote(support) {
        // Check if there are accounts available
        if (!e && accounts && accounts.length > 0) {
            // Create a dialog requesting the transaction
  , support, {from: accounts[0]})

          } else {
            mist.requestAccount(function(e, account) {
                if(!e) {
                    // Create a dialog requesting the transaction
          , support, {from: account.toLowerCase()})


You should only request an account once the user initiated an action: pinging a transaction out of nowhere will deservedly irritate the user and probably make him close your app. If we observe abuses from apps using this feature, we might add more strict requirements to when an alert will show up.

Watch the contract

Finally, to count up all the votes we need to watch the contract events and see what votes were cast. To do that, we have to run this function once to start watching the events, after we instantiated “ethervote”:

ethervote = web3.eth.contract(contractABI).at(contractAddress);
var logVotes = ethervote.LogVote({proposalHash: proposalHash}, {fromBlock: 1800000});
// Wait for the events to be loaded, result){
    if (!error) {            
        // Do something whenever the event happens

The above code will start reading all blocks from number 1.8M (when the contract was uploaded) onwards and then execute the receivedEvent() function once for each event. Whenever a new block arrives with an event this function will be triggered again so you won’t need to call continuously. So what would this function do?

Var voteMap = {};
Function receivedEvent(event) {
    // Get the current balance of a voter             
    var bal = Number(web3.fromWei(web3.eth.getBalance(event.args.addr), "finney"));
    voteMap[res.args.addr] = {balance: bal, support:}; 

From the original solidity contract, you can see that the LogVote event comes with three argumenst, proposalHash, Pro and Addr:

event LogVote(bytes32 indexed proposalHash, bool pro, address addr);

So what this function does is that it will use the function web3.eth.getBalance to check the current ether balance of the address that voted. All balances always return numbers in wei, which is a 1/1000000000000000000 of an ether and is not very useful for this particular application, so we also use another included web3 function which converts that to any ether unit we want. In this case we will be using the finney, which is a thousandth of an ether.

Then the function will save the balance, along with the position of the voter to a map based on the address. One advantage of using a map instead of an array is that this will automatically overwrite any previous information about that same address, so if someone votes twice, only their last opinion will be kept.

Another thing we could do is identify the user and show them if they voted or not.

// Check if the current owner has already voted and show that on the interface
    if (!e && accounts && accounts[0] == res.args.addr) {
        if ( {
            // User has voted yes!
        } else {
            // User has voted against! 

Tally up the votes

Finally, we should add a separate function to calculate the sums of the votes:


Why do we want to tally up the votes on a separate function? Because since the vote weight is based on the current balance of each account, we should recalculate the balances at every new block, event if we received no new event. To do this you can add this function that will execute automatically everytime a new block arrives:

web3.eth.filter('latest').watch(function(e, result){
    if(!e) {

Finally, up to calculating the final tally. We have previously used eth.getBalance in synchronous mode, where the app would wait for the result of the previous action to proceed. Here, since we can be calling a lot of actions every block, we will use it in asynchronous mode: you call the node and execute the action whenever it replies without freezing the interface.

var totalPro, totalAgainst, totalVotes;
function calculateVotes() {
    totalPro = 0;
    totalAgainst = 0;
    totalVotes = 0;
    Object.keys(voteMap).map(function(a) { 
        // call the function asynchronously 
        web3.eth.getBalance(a, function(e,r) {
            voteMap[a].balance = Number(web3.fromWei(r, 'finney'));
            if (voteMap[a].support)
                totalPro += parseFloat(voteMap[a].balance); 
                totalAgainst += parseFloat(voteMap[a].balance);
            // do something cool with the results!            

As you can follow on the code, what the app is doing is looping in each of the voting addresses and getting their balance, and as soon as it returns, it will either add it to the pro or against camp and sum the totals.

Some extras

A few extra caveats: when there are no events, nothing will be returned and votes won’t be calculated so you should add a timeout function on all functions that rely on events from the blockchain.

        // If the app doesn't respond after a timeout it probably has no votes
    }, 3000);

Now you can feel free to use all your current webdeveloper foo to work whatever magic you want. Use the numbers to build a nice visualization in 3D or connect to your favorite social media to share the best questions.

One great thing about ethereum is that you can expand on this simple contract functionality without needing permission: you can add all extra functionality on separate contracts, keeping every single one of them simple and easier to debug. It also means other people can use the contracts you created to their own apps and give new functionality. Meanwhile, all the apps use the same data and backend.

You can play with this app live hosted on github pages, but this isn’t the canonical source of truth, just one of the many possible interfaces to it. The same app will also work as a local html file on your computer or on an IPFS network and in the future it will be downloaded directly via Mist using Swarm.

Some ideas on how you can try:

  • Create a listing of currently available statements. Anyone can check them by seeing the sha3 of the proposal text, so you don’t need permission.
  • Create threaded comments where users can reply to statements and then upvote or downvote them, sort of like a decentralized stake based Reddit
  • Instead of (or in addition to) using ether balance, you can use some other ethereum token, like The DAO or Digix Gold to weight your questions differently. Since all that the original contract stores is the sender, you can check all balances. Or maybe you can create your own currency that is based on reputation, karma or some other way.


The post How to build server less applications for Mist appeared first on Ethereum Blog.

from Ethereum Blog