दुर्गा बेरागी Durga Beragi, homeEnter the study →

Library › Cryptography, blockchain and crypto › Mastering Ethereum › Full text

Mastering Ethereum

Andreas M. Antonopoulos and Gavin Wood, 2018 · part 1 of 17 · 111,220 words

Openly licensed edition · source: GitHub (ethereumbook/ethereumbook, openedition branch) · CC-BY-SA-4.0

About this book, its key ideas and how to read it →

Preface

This book is a collaboration between Andreas M. Antonopoulos and Dr. Gavin Wood. A series of fortunate coincidences brought these two authors together in an effort that galvanized hundreds of contributors to produce this book, in the best spirit of open source and the creative commons culture.

Gavin had been wishing to write a book that expanded on the Yellow Paper (his technical description of the Ethereum protocol) for some time, primarily to open it up to a wider audience than the original Greek-letter-infused document could possibly allow.

Plans were underway—a publisher had been found—when Gavin got talking to Andreas, whom he had known from the very beginning of his tenure with Ethereum as a notable personality in the space.

Andreas had recently published the first edition of his book Mastering Bitcoin (O'Reilly), which quickly became the authoritative technical guide to Bitcoin and cryptocurrencies. Almost as soon as the book was published, his readers started asking him, "When will you write 'Mastering Ethereum'?" Andreas was already considering his next project and found Ethereum to be a compelling technical subject.

Finally, in May 2016, Gavin and Andreas were both coincidentally in the same city at the same time. They met up for a coffee to chat about working on the book together. With both Andreas and Gavin being devotees of the open source paradigm, they both committed to making this a collaborative effort, released under a Creative Commons license. Thankfully, the publisher, O'Reilly Media, was happy to agree, and the Mastering Ethereum project was officially launched.

How to Use This Book

The book is intended to serve both as a reference manual and as a cover-to-cover exploration of Ethereum. The first two chapters offer a gentle introduction, suitable for novice users, and the examples in those chapters can be completed by anyone with a bit of technical skill. Those two chapters will give you a good grasp of the basics and allow you to use the fundamental tools of Ethereum. Ethereum Clients and beyond are intended mainly for programmers and include many technical topics and programming examples.

To serve as both a reference manual and a cover-to-cover narrative about Ethereum, the book inevitably contains some duplication. Some topics, such as gas, have to be introduced early enough for the rest of the topics to make sense, but are also examined in depth in their own sections.

Finally, the book's index allows readers to find very specific topics and the relevant sections with ease, by keyword.

Intended Audience

This book is mostly intended for coders. If you can use a programming language, this book will teach you how smart contract blockchains work, how to use them, and how to develop smart contracts and decentralized applications with them. The first few chapters are also suitable as an in-depth introduction to Ethereum for noncoders.

Conventions Used in This Book

The following typographical conventions are used in this book:

  • Italic: Indicates new terms, URLs, email addresses, filenames, and file extensions.
  • Constant width: Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.
  • Constant width bold: Shows commands or other text that should be typed literally by the user.
  • Constant width italic: Shows text that should be replaced with user-supplied values or values determined by context.

Tip: This icon signifies a tip or suggestion.

Note: This icon signifies a general note.

Warning: This icon indicates a warning or caution.

Code Examples

The examples are illustrated in Solidity, Vyper, and JavaScript, and using the command line of a Unix-like operating system. All code snippets are available in the GitHub repository under the code subdirectory. Fork the book code, try the code examples, or submit corrections via GitHub: https://github.com/ethereumbook/ethereumbook.

All the code snippets can be replicated on most operating systems with a minimal installation of compilers, interpreters, and libraries for the corresponding languages. Where necessary, we provide basic installation instructions and step-by-step examples of the output of those instructions.

Some of the code snippets and code output have been reformatted for print. In all such cases, the lines have been split by a backslash (\) character, followed by a newline character. When transcribing the examples, remove those two characters and join the lines again and you should see identical results to those shown in the example.

All the code snippets use real values and calculations where possible, so that you can build from example to example and see the same results in any code you write to calculate the same values. For example, the private keys and corresponding public keys and addresses are all real. The sample transactions, contracts, blocks, and blockchain references have all been introduced to the actual Ethereum blockchain and are part of the public ledger, so you can review them.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, ISBN, and copyright. For example: “Mastering Ethereum by Andreas M. Antonopoulos and Dr. Gavin Wood. Copyright 2019 The Ethereum Book LLC and Gavin Wood"

Mastering Ethereum is offered under the Creative Commons Attribution-ShareAlike International License (CC BY SA 4.0).

References to Companies and Products

All references to companies and products are intended for educational, demonstration, and reference purposes. The authors do not endorse any of the companies or products mentioned. We have not tested the operation or security of any of the products, projects, or code segments shown in this book. Use them at your own risk!

Ethereum Addresses and Transactions in this Book

The Ethereum addresses, transactions, keys, QR codes, and blockchain data used in this book are, for the most part, real. That means you can browse the blockchain, look at the transactions offered as examples, retrieve them with your own scripts or programs, etc.

However, note that the private keys used to construct the addresses printed in this book have been "burned." This means that if you send money to any of these addresses, the money will either be lost forever or (more likely) appropriated, since anyone who reads the book can take it using the private keys printed herein.

Warning: DO NOT SEND MONEY TO ANY OF THE ADDRESSES IN THIS BOOK. Your money will be taken by another reader, or lost forever.

Contacting Andreas

You can contact Andreas M. Antonopoulos on his personal site: https://antonopoulos.com/

Subscribe to Andreas's channel on YouTube: https://www.youtube.com/aantonop

Like Andreas's page on Facebook: https://www.facebook.com/AndreasMAntonopoulos

Follow Andreas on Twitter: https://twitter.com/aantonop

Connect with Andreas on LinkedIn: https://linkedin.com/company/aantonop

Andreas would also like to thank all of the patrons who support his work through monthly donations. You can support Andreas on Patreon at https://patreon.com/aantonop.

Contacting Gavin

You can contact Dr. Gavin Wood on his personal site: http://gavwood.com/

Follow Gavin on Twitter: https://twitter.com/gavofyork

Gavin generally hangs out in the Polkadot Watercooler on Riot.im: http://bit.ly/2xciG68

Acknowledgments by Andreas

I owe my love of words and books to my mother, Theresa, who raised me in a house with books lining every wall. My mother also bought me my first computer in 1982, despite being a self-described technophobe. My father, Menelaos, a civil engineer who published his first book at 80 years old, was the one who taught me logical and analytical thinking and a love of science and engineering.

Thank you all for supporting me throughout this journey.

Acknowledgments by Gavin

My mother secured my first computer for me from a neighbor when I was 9 years old, without which my technical progress would no doubt have been lessened. I also owe her my childhood fear of electricity and must acknowledge Trevor and my grandparents, who performed the grave duty of "watching me plug it in" time after time, and without whom said computer would have been useless. I must also acknowledge the various educators I have been lucky to have through my life, from said neighbor Sean (who taught me my first computer program), to Mr. Quinn my primary school teacher, who fixed it for me to do more programming and less history, through to secondary-school teachers like Richard Furlong-Brown, who fixed it for me to do more programming and less rugby.

I must thank the mother of my children, Jutta, for her continued support, and the many people in my life, friends new and old, that keep me, roughly speaking, sane. Finally, a huge dollop of thanks must go to Aeron Buchanan, without whom the last five years of my life could never possibly have unfolded in the way they did and without whose time, support, and guidance this book would not be in as good shape as it is.

Sources

This book references various public and open-licensed sources:

https://github.com/ethereum/vyper/blob/master/README.md:: The MIT License (MIT)

https://vyper.readthedocs.io/en/latest/:: The MIT License (MIT)

https://solidity.readthedocs.io/en/v0.4.21/common-patterns.html:: The MIT License (MIT)

https://arxiv.org/pdf/1802.06038.pdf:: Arxiv Non-Exclusive-Distribution

https://github.com/ethereum/solidity/blob/release/docs/contracts.rst#inheritance:: The MIT License (MIT)

https://github.com/trailofbits/evm-opcodes:: Apache 2.0

https://github.com/ethereum/EIPs/:: Creative Commons CC0

https://blog.sigmaprime.io/solidity-security.html:: Creative Commons CC BY 4.0

Quick Glossary

This quick glossary contains many of the terms used in relation to Ethereum. These terms are used throughout the book, so bookmark this for quick reference.

  • Account: An object containing an address, balance, nonce, and optional storage and code. An account can be a contract account or an externally owned account (EOA).
  • Address: Most generally, this represents an EOA or contract that can receive (destination address) or send (source address) transactions on the blockchain. More specifically, it is the rightmost 160 bits of a Keccak hash of an ECDSA public key.
  • Assert: In Solidity, assert(false) compiles to 0xfe, an invalid opcode, which uses up all remaining gas and reverts all changes. When an assert() statement fails, something very wrong and unexpected is happening, and you will need to fix your code. You should use assert() to avoid conditions that should never, ever occur.
  • Big-endian: A positional number representation where the most significant digit is first. The opposite of little-endian, where the least significant digit is first.
  • BIPs: Bitcoin Improvement Proposals. A set of proposals that members of the Bitcoin community have submitted to improve Bitcoin. For example, BIP-21 is a proposal to improve the Bitcoin uniform resource identifier (URI) scheme.
  • Block: A collection of required information (a block header) about the comprised transactions, and a set of other block headers known as ommers. Blocks are added to the Ethereum network by miners.
  • Blockchain: In Ethereum, a sequence of blocks validated by the proof-of-work system, each linking to its predecessor all the way to the genesis block. This varies from the Bitcoin protocol in that it does not have a block size limit; it instead uses varying gas limits.
  • Bytecode: An abstract instruction set designed for efficient execution by a software interpreter or a virtual machine. Unlike human-readable source code, bytecode is expressed in numeric format.
  • Byzantium fork: The first of two hard forks for the Metropolis development stage. It included EIP-649: Metropolis Difficulty Bomb Delay and Block Reward Reduction, where the Ice Age (see below) was delayed by 1 year and the block reward was reduced from 5 to 3 ether.
  • Compiling: Converting code written in a high-level programming language (e.g., Solidity) into a lower-level language (e.g., EVM bytecode).
  • Consensus: When numerous nodes—usually most nodes on the network—all have the same blocks in their locally validated best blockchain. Not to be confused with consensus rules.
  • Consensus rules: The block validation rules that full nodes follow to stay in consensus with other nodes. Not to be confused with consensus.
  • Constantinople fork: The second part of the Metropolis stage, originally planned for mid-2018. Expected to include a switch to a hybrid proof-of-work/proof-of-stake consensus algorithm, among other changes.
  • Contract account: An account containing code that executes whenever it receives a transaction from another account (EOA or contract).
  • Contract creation transaction: A special transaction, with the "zero address" as the recipient, that is used to register a contract and record it on the Ethereum blockchain (see "zero address").
  • DAO: Decentralized Autonomous Organization. A company or other organization that operates without hierarchical management. Also may refer to a contract named "The DAO" launched on April 30, 2016, which was then hacked in June 2016; this ultimately motivated a hard fork (codenamed DAO) at block #1,192,000, which reversed the hacked DAO contract and caused Ethereum and Ethereum Classic to split into two competing systems.
  • DApp: Decentralized application. At a minimum, it is a smart contract and a web user interface. More broadly, a DApp is a web application that is built on top of open, decentralized, peer-to-peer infrastructure services. In addition, many DApps include decentralized storage and/or a message protocol and platform.
  • Deed: Non-fungible token (NFT) standard introduced by the ERC721 proposal. Unlike ERC20 tokens, deeds prove ownership and are not interchangeable, though they are not recognized as legal documents in any jurisdiction—at least not currently (see also "NFT").
  • Difficulty: A network-wide setting that controls how much computation is required to produce a proof of work.
  • Digital signature: A short string of data a user produces for a document using a private key such that anyone with the corresponding public key, the signature, and the document can verify that (1) the document was "signed" by the owner of that particular private key, and (2) the document was not changed after it was signed.
  • ECDSA: Elliptic Curve Digital Signature Algorithm. A cryptographic algorithm used by Ethereum to ensure that funds can only be spent by their owners.
  • EIP: Ethereum Improvement Proposal. A design document providing information to the Ethereum community, describing a proposed new feature or its processes or environment. For more information, see https://github.com/ethereum/EIPs (see also "ERC").
  • ENS: Ethereum Name Service. For more information, see https://github.com/ethereum/ens/.
  • Entropy: In the context of cryptography, lack of predictability or level of randomness. When generating secret information, such as private keys, algorithms usually rely on a source of high entropy to ensure the output is unpredictable.
  • EOA: Externally Owned Account. An account created by or for human users of the Ethereum network.
  • ERC: Ethereum Request for Comments. A label given to some EIPs that attempt to define a specific standard of Ethereum usage.
  • Ethash: A proof-of-work algorithm for Ethereum 1.0. For more information, see https://github.com/ethereum/wiki/wiki/Ethash.
  • Ether: The native cryptocurrency used by the Ethereum ecosystem, which covers gas costs when executing smart contracts. Its symbol is Ξ, the Greek uppercase Xi character.
  • Event: Allows the use of EVM logging facilities. DApps can listen for events and use them to trigger JavaScript callbacks in the user interface. For more information, see http://solidity.readthedocs.io/en/develop/contracts.html#events.
  • EVM: Ethereum Virtual Machine. A stack-based virtual machine that executes bytecode. In Ethereum, the execution model specifies how the system state is altered given a series of bytecode instructions and a small tuple of environmental data. This is specified through a formal model of a virtual state machine.
  • EVM assembly language: A human-readable form of EVM bytecode.
  • Fallback function: A default function called in the absence of data or a declared function name.
  • Faucet: A service that dispenses funds in the form of free test ether that can be used on a testnet.
  • Finney: A denomination of ether. 1 finney = 10^15 wei, 10^3 finney = 1 ether.
  • Fork: A change in protocol causing the creation of an alternative chain, or a temporal divergence in two potential block paths during mining.
  • Frontier: The initial test development stage of Ethereum, which lasted from July 2015 to March 2016.
  • Ganache: A personal Ethereum blockchain that you can use to run tests, execute commands, and inspect state while controlling how the chain operates.
  • Gas: A virtual fuel used in Ethereum to execute smart contracts. The EVM uses an accounting mechanism to measure the consumption of gas and limit the consumption of computing resources (see "Turing complete").
  • Gas limit: The maximum amount of gas a transaction or block may consume.
  • Gavin Wood: A British programmer who is the cofounder and former CTO of Ethereum. In August 2014 he proposed Solidity, a contract-oriented programming language for writing smart contracts.
  • Genesis block: The first block in a blockchain, used to initialize a particular network and its cryptocurrency.
  • Geth: Go Ethereum. One of the most prominent implementations of the Ethereum protocol, written in Go.
  • Hard fork: A permanent divergence in the blockchain; also known as a hard-forking change. One commonly occurs when nonupgraded nodes can't validate blocks created by upgraded nodes that follow newer consensus rules. Not to be confused with a fork, soft fork, software fork, or Git fork.
  • Hash: A fixed-length fingerprint of variable-size input, produced by a hash function.
  • HD wallet: A wallet using the hierarchical deterministic (HD) key creation and transfer protocol (BIP-32).
  • HD wallet seed: A value used to generate the master private key and master chain code for an HD wallet. The wallet seed can be represented by mnemonic words, making it easier for humans to copy, back up, and restore private keys.
  • Homestead: The second development stage of Ethereum, launched in March 2016 at block #1,150,000.
  • ICAP: Inter-exchange Client Address Protocol. An Ethereum address encoding that is partly compatible with the International Bank Account Number (IBAN) encoding, offering a versatile, checksummed, and interoperable encoding for Ethereum addresses. ICAP addresses use a new IBAN pseudo-country code: XE, standing for "eXtended Ethereum," as used in nonjurisdictional currencies (e.g., XBT, XRP, XCP).
  • Ice Age: A hard fork of Ethereum at block #200,000 to introduce an exponential difficulty increase (aka Difficulty Bomb), motivating a transition to proof of stake.
  • IDE: Integrated Development Environment. A user interface that typically combines a code editor, compiler, runtime, and debugger.
  • Immutable deployed code problem: Once a contract's (or library's) code is deployed, it becomes immutable. Standard software development practices rely on being able to fix possible bugs and add new features, so this represents a challenge for smart contract development.
  • Internal transaction (also "message"): A transaction sent from a contract account to another contract account or an EOA.
  • IPFS: InterPlanetary File System. A protocol, network, and open source project designed to create a content-addressable, peer-to-peer method of storing and sharing hypermedia in a distributed filesystem.
  • KDF: Key Derivation Function. Also known as a "password stretching algorithm," it is used by keystore formats to protect against brute-force, dictionary, and rainbow table attacks on passphrase encryption, by repeatedly hashing the passphrase.
  • Keccak-256: Cryptographic hash function used in Ethereum. Keccak-256 was standardized as SHA-3.
  • Keystore file: A JSON-encoded file that contains a single (randomly generated) private key, encrypted by a passphrase for extra security.
  • LevelDB: An open source on-disk key–value store, implemented as a lightweight, single-purpose library, with bindings to many platforms.
  • Library: A special type of contract that has no payable functions, no fallback function, and no data storage. Therefore, it cannot receive or hold ether, or store data. A library serves as previously deployed code that other contracts can call for read-only computation.
  • Lightweight client: An Ethereum client that does not store a local copy of the blockchain, or validate blocks and transactions. It offers the functions of a wallet and can create and broadcast transactions.
  • Merkle Patricia Tree: A data structure used in Ethereum to efficiently store key–value pairs.
  • Message: An internal transaction that is never serialized and only sent within the EVM.
  • Message call: The act of passing a message from one account to another. If the destination account is associated with EVM code, then the VM will be started with the state of that object and the message acted upon.
  • METoken: Mastering Ethereum Token. An ERC20 token used for demonstration in this book.
  • Metropolis: The third development stage of Ethereum, launched in October 2017.
  • Miner: A network node that finds valid proof of work for new blocks, by repeated hashing.
  • Mist: The first Ethereum-enabled browser, built by the Ethereum Foundation. It contains a browser-based wallet that was the first implementation of the ERC20 token standard (Fabian Vogelsteller, author of ERC20, was also the main developer of Mist). Mist was also the first wallet to introduce the camelCase checksum (EIP-55; see Hex Encoding with Checksum in Capitalization (EIP-55)). Mist runs a full node and offers a full DApp browser with support for Swarm-based storage and ENS addresses.
  • Network: Referring to the Ethereum network, a peer-to-peer network that propagates transactions and blocks to every Ethereum node (network participant).
  • NFT: A non-fungible token (also known as a "deed"). This is a token standard introduced by the ERC721 proposal. NFTs can be tracked and traded, but each token is unique and distinct; they are not interchangeable like ERC20 tokens. NFTs can represent ownership of digital or physical assets.
  • Node: A software client that participates in the network.
  • Nonce: In cryptography, a value that can only be used once. There are two types of nonce used in Ethereum: an account nonce is a transaction counter in each account, which is used to prevent replay attacks; a proof-of-work nonce is the random value in a block that was used to satisfy the proof of work.
  • Ommer: A child block of an ancestor that is not itself an ancestor. When a miner finds a valid block, another miner may have published a competing block which is added to the tip of the blockchain. Unlike with Bitcoin, orphaned blocks in Ethereum can be included by newer blocks as ommers and receive a partial block reward. The term "ommer" is the preferred gender-neutral term for the sibling of a parent block, but this is also sometimes referred to as an "uncle."
  • Parity: One of the most prominent interoperable implementations of the Ethereum client software.
  • Private key: See “secret key.”
  • Proof of stake (PoS): A method by which a cryptocurrency blockchain protocol aims to achieve distributed consensus. PoS asks users to prove ownership of a certain amount of cryptocurrency (their "stake" in the network) in order to be able to participate in the validation of transactions.
  • Proof of work (PoW): A piece of data (the proof) that requires significant computation to find. In Ethereum, miners must find a numeric solution to the Ethash algorithm that meets a network-wide difficulty target.
  • Public key: A number, derived via a one-way function from a private key, which can be shared publicly and used by anyone to verify a digital signature made with the corresponding private key.
  • Receipt: Data returned by an Ethereum client to represent the result of a particular transaction, including a hash of the transaction, its block number, the amount of gas used, and, in case of deployment of a smart contract, the address of the contract.
  • Re-entrancy attack: An attack that consists of an attacker contract calling a victim contract function in such a way that during execution the victim calls the attacker contract again, recursively. This can result, for example, in the theft of funds by skipping parts of the victim contract that update balances or count withdrawal amounts.
  • Reward: An amount of ether included in each new block as a reward by the network to the miner who found the proof-of-work solution.
  • RLP: Recursive Length Prefix. An encoding standard designed by the Ethereum developers to encode and serialize objects (data structures) of arbitrary complexity and length.
  • Satoshi Nakamoto: The name used by the person or people who designed Bitcoin, created its original reference implementation, and were the first to solve the double-spend problem for digital currency. Their real identity remains unknown.
  • Secret key (aka private key): The secret number that allows Ethereum users to prove ownership of an account or contracts, by producing a digital signature (see “public key,” “address,” “ECDSA”).
  • Serenity: The fourth and final development stage of Ethereum. Serenity does not yet have a planned release date.
  • Serpent: A procedural (imperative) smart contract programming language with syntax similar to Python.
  • SHA: Secure Hash Algorithm. A family of cryptographic hash functions published by the National Institute of Standards and Technology (NIST).
  • Singleton: A computer programming term that describes an object of which only a single instance can exist.
  • Smart contract: A program that executes on the Ethereum computing infrastructure.
  • Solidity: A procedural (imperative) programming language with syntax that is similar to JavaScript, C++, or Java. The most popular and most frequently used language for Ethereum smart contracts. Created by Dr. Gavin Wood (coauthor of this book).
  • Solidity inline assembly: EVM assembly language in a Solidity program. Solidity's support for inline assembly makes it easier to write certain operations.
  • Spurious Dragon: A hard fork of the Ethereum blockchain, which occurred at block #2,675,000 to address more denial-of-service attack vectors and clear state (see also "Tangerine Whistle"). Also, a replay attack protection mechanism.
  • Swarm: A decentralized (P2P) storage network, used along with Web3 and Whisper to build DApps.
  • Szabo: A denomination of ether. 1 szabo = 10^12 wei, 10^6 szabo = 1 ether.
  • Tangerine Whistle: A hard fork of the Ethereum blockchain, which occurred at block #2,463,000 to change the gas calculation for certain I/O-intensive operations and to clear the accumulated state from a denial-of-service attack, which exploited the low gas cost of those operations.
  • Testnet: Short for "test network," a network used to simulate the behavior of the main Ethereum network.
  • Transaction: Data committed to the Ethereum Blockchain signed by an originating account, targeting a specific address. The transaction contains metadata such as the gas limit for that transaction.
  • Truffle: One of the most commonly used Ethereum development frameworks.
  • Turing complete: A concept named after English mathematician and computer scientist Alan Turing: a system of data-manipulation rules (such as a computer's instruction set, a programming language, or a cellular automaton) is said to be "Turing complete" or "computationally universal" if it can be used to simulate any Turing machine.
  • Vitalik Buterin: A Russian–Canadian programmer and writer primarily known as the cofounder of Ethereum and of Bitcoin Magazine.
  • Vyper: A high-level programming language, similar to Serpent, with Python-like syntax. Intended to get closer to a pure functional language. Created by Vitalik Buterin.
  • Wallet: Software that holds secret keys. Used to access and control Ethereum accounts and interact with smart contracts. Keys need not be stored in a wallet, and can instead be retrieved from offline storage (e.g., a memory card or paper) for improved security. Despite the name, wallets never store the actual coins or tokens.
  • Web3: The third version of the web. First proposed by Dr. Gavin Wood, Web3 represents a new vision and focus for web applications: from centrally owned and managed applications, to applications built on decentralized protocols.
  • Wei: The smallest denomination of ether. 10^18 wei = 1 ether.
  • Whisper: A decentralized (P2P) messaging service. It is used along with Web3 and Swarm to build DApps.
  • Zero address: A special Ethereum address, composed entirely of zeros, that is specified as the destination address of a contract creation transaction.

What Is Ethereum?

Ethereum is often described as "the world computer.” But what does that mean? Let's start with a computer science–focused description, and then try to decipher that with a more practical analysis of Ethereum's capabilities and characteristics, while comparing it to Bitcoin and other decentralized information exchange platforms (or "blockchains" for short).

From a computer science perspective, Ethereum is a deterministic but practically unbounded state machine, consisting of a globally accessible singleton state and a virtual machine that applies changes to that state.

From a more practical perspective, Ethereum is an open source, globally decentralized computing infrastructure that executes programs called smart contracts. It uses a blockchain to synchronize and store the system’s state changes, along with a cryptocurrency called ether to meter and constrain execution resource costs.

The Ethereum platform enables developers to build powerful decentralized applications with built-in economic functions. While providing high availability, auditability, transparency, and neutrality, it also reduces or eliminates censorship and reduces certain counterparty risks.

Compared to Bitcoin

Many people will come to Ethereum with some prior experience of cryptocurrencies, specifically Bitcoin. Ethereum shares many common elements with other open blockchains: a peer-to-peer network connecting participants, a Byzantine fault–tolerant consensus algorithm for synchronization of state updates (a proof-of-work blockchain), the use of cryptographic primitives such as digital signatures and hashes, and a digital currency (ether).

Yet in many ways, both the purpose and construction of Ethereum are strikingly different from those of the open blockchains that preceded it, including Bitcoin.

Ethereum's purpose is not primarily to be a digital currency payment network. While the digital currency ether is both integral to and necessary for the operation of Ethereum, ether is intended as a utility currency to pay for use of the Ethereum platform as the world computer.

Unlike Bitcoin, which has a very limited scripting language, Ethereum is designed to be a general-purpose programmable blockchain that runs a virtual machine capable of executing code of arbitrary and unbounded complexity. Where Bitcoin's Script language is, intentionally, constrained to simple true/false evaluation of spending conditions, Ethereum's language is Turing complete, meaning that Ethereum can straightforwardly function as a general-purpose computer.

Components of a Blockchain

The components of an open, public blockchain are (usually):

  • A peer-to-peer (P2P) network connecting participants and propagating transactions and blocks of verified transactions, based on a standardized "gossip" protocol
  • Messages, in the form of transactions, representing state transitions
  • A set of consensus rules, governing what constitutes a transaction and what makes for a valid state transition
  • A state machine that processes transactions according to the consensus rules
  • A chain of cryptographically secured blocks that acts as a journal of all the verified and accepted state transitions
  • A consensus algorithm that decentralizes control over the blockchain, by forcing participants to cooperate in the enforcement of the consensus rules
  • A game-theoretically sound incentivization scheme (e.g., proof-of-work costs plus block rewards) to economically secure the state machine in an open environment
  • One or more open source software implementations of the above ("clients")

All or most of these components are usually combined in a single software client. For example, in Bitcoin, the reference implementation is developed by the Bitcoin Core open source project and implemented as the bitcoind client. In Ethereum, rather than a reference implementation there is a reference specification, a mathematical description of the system in the Yellow Paper (see Further Reading). There are a number of clients, which are built according to the reference specification.

In the past, we used the term "blockchain" to represent all of the components just listed, as a shorthand reference to the combination of technologies that encompass all of the characteristics described. Today, however, there are a huge variety of blockchains with different properties. We need qualifiers to help us understand the characteristics of the blockchain in question, such as open, public, global, decentralized, neutral, and censorship-resistant, to identify the important emergent characteristics of a "blockchain" system that these components allow.

Not all blockchains are created equal. When someone tells you that something is a blockchain, you have not received an answer; rather, you need to start asking a lot of questions to clarify what they mean when they use the word "blockchain." Start by asking for a description of the components in the preceding list, then ask whether this "blockchain" exhibits the characteristics of being open, public, etc.

The Birth of Ethereum

All great innovations solve real problems, and Ethereum is no exception. Ethereum was conceived at a time when people recognized the power of the Bitcoin model, and were trying to move beyond cryptocurrency applications. But developers faced a conundrum: they either needed to build on top of Bitcoin or start a new blockchain. Building upon Bitcoin meant living within the intentional constraints of the network and trying to find workarounds. The limited set of transaction types, data types, and sizes of data storage seemed to limit the sorts of applications that could run directly on Bitcoin; anything else needed additional off-chain layers, and that immediately negated many of the advantages of using a public blockchain. For projects that needed more freedom and flexibility while staying on-chain, a new blockchain was the only option. But that meant a lot of work: bootstrapping all the infrastructure elements, exhaustive testing, etc.

Toward the end of 2013, Vitalik Buterin, a young programmer and Bitcoin enthusiast, started thinking about further extending the capabilities of Bitcoin and Mastercoin (an overlay protocol that extended Bitcoin to offer rudimentary smart contracts). In October of that year, Vitalik proposed a more generalized approach to the Mastercoin team, one that allowed flexible and scriptable (but not Turing-complete) contracts to replace the specialized contract language of Mastercoin. While the Mastercoin team were impressed, this proposal was too radical a change to fit into their development roadmap.

In December 2013, Vitalik started sharing a whitepaper that outlined the idea behind Ethereum: a Turing-complete, general-purpose blockchain. A few dozen people saw this early draft and offered feedback, helping Vitalik evolve the proposal.

Both of the authors of this book received an early draft of the whitepaper and commented on it. Andreas M. Antonopoulos was intrigued by the idea and asked Vitalik many questions about the use of a separate blockchain to enforce consensus rules on smart contract execution and the implications of a Turing-complete language. Andreas continued to follow Ethereum's progress with great interest but was in the early stages of writing his book Mastering Bitcoin, and did not participate directly in Ethereum until much later. Dr. Gavin Wood, however, was one of the first people to reach out to Vitalik and offer to help with his C++ programming skills. Gavin became Ethereum's cofounder, codesigner, and CTO.

As Vitalik recounts in his "Ethereum Prehistory" post:

This was the time when the Ethereum protocol was entirely my own creation. From here on, however, new participants started to join the fold. By far the most prominent on the protocol side was Gavin Wood...

Gavin can also be largely credited for the subtle change in vision from viewing Ethereum as a platform for building programmable money, with blockchain-based contracts that can hold digital assets and transfer them according to pre-set rules, to a general-purpose computing platform. This started with subtle changes in emphasis and terminology, and later this influence became stronger with the increasing emphasis on the “Web 3” ensemble, which saw Ethereum as being one piece of a suite of decentralized technologies, the other two being Whisper and Swarm.

Starting in December 2013, Vitalik and Gavin refined and evolved the idea, together building the protocol layer that became Ethereum.

Ethereum's founders were thinking about a blockchain without a specific purpose, that could support a broad variety of applications by being programmed. The idea was that by using a general-purpose blockchain like Ethereum, a developer could program their particular application without having to implement the underlying mechanisms of peer-to-peer networks, blockchains, consensus algorithms, etc. The Ethereum platform was designed to abstract these details and provide a deterministic and secure programming environment for decentralized blockchain applications.

Much like Satoshi, Vitalik and Gavin didn't just invent a new technology; they combined new inventions with existing technologies in a novel way and delivered the prototype code to prove their ideas to the world.

The founders worked for years, building and refining the vision. And on July 30, 2015, the first Ethereum block was mined. The world's computer started serving the world.

Note: Vitalik Buterin's article "A Prehistory of Ethereum" was published in September 2017 and provides a fascinating first-person view of Ethereum's earliest moments.

You can read it at https://vitalik.ca/general/2017/09/14/prehistory.html.

Ethereum's Four Stages of Development

Ethereum's development was planned over four distinct stages, with major changes occurring at each stage. A stage may include subreleases, known as "hard forks," that change functionality in a way that is not backward compatible.

The four main development stages are codenamed Frontier, Homestead, Metropolis, and Serenity. The intermediate hard forks that have occurred (or are planned) to date are codenamed Ice Age, DAO, Tangerine Whistle, Spurious Dragon, Byzantium, and Constantinople. Both the development stages and the intermediate hard forks are shown on the following timeline, which is "dated" by block number:

  • Block #0: Frontier—The initial stage of Ethereum, lasting from July 30, 2015, to March 2016.
  • Block #200,000: Ice Age—A hard fork to introduce an exponential difficulty increase, to motivate a transition to PoS when ready.
  • Block #1,150,000: Homestead—The second stage of Ethereum, launched in March 2016.
  • Block #1,192,000: DAO—A hard fork that reimbursed victims of the hacked DAO contract and caused Ethereum and Ethereum Classic to split into two competing systems.
  • Block #2,463,000: Tangerine Whistle—A hard fork to change the gas calculation for certain I/O-heavy operations and to clear the accumulated state from a denial-of-service (DoS) attack that exploited the low gas cost of those operations.
  • Block #2,675,000: Spurious Dragon—A hard fork to address more DoS attack vectors, and another state clearing. Also, a replay attack protection mechanism.
  • Block #4,370,000: Metropolis Byzantium—Metropolis is the third stage of Ethereum, current at the time of writing this book, launched in October 2017. Byzantium is the first of two hard forks planned for Metropolis.

After Byzantium, there is one more hard fork planned for Metropolis: Constantinople. Metropolis will be followed by the final stage of Ethereum's deployment, codenamed Serenity.

Ethereum: A General-Purpose Blockchain

The original blockchain, namely Bitcoin's blockchain, tracks the state of units of bitcoin and their ownership. You can think of Bitcoin as a distributed consensus state machine, where transactions cause a global state transition, altering the ownership of coins. The state transitions are constrained by the rules of consensus, allowing all participants to (eventually) converge on a common (consensus) state of the system, after several blocks are mined.

Ethereum is also a distributed state machine. But instead of tracking only the state of currency ownership, Ethereum tracks the state transitions of a general-purpose data store, i.e., a store that can hold any data expressible as a key–value tuple. A key–value data store holds arbitrary values, each referenced by some key; for example, the value "Mastering Ethereum" referenced by the key "Book Title". In some ways, this serves the same purpose as the data storage model of Random Access Memory (RAM) used by most general-purpose computers. Ethereum has memory that stores both code and data, and it uses the Ethereum blockchain to track how this memory changes over time. Like a general-purpose stored-program computer, Ethereum can load code into its state machine and run that code, storing the resulting state changes in its blockchain. Two of the critical differences from most general-purpose computers are that Ethereum state changes are governed by the rules of consensus and the state is distributed globally. Ethereum answers the question: "What if we could track any arbitrary state and program the state machine to create a world-wide computer operating under consensus?"