Uinspire Blockchain Course {Lesson 3: Unlocking smart contracts — Ethereum}

Alfonso Delgado
Uinspire
Published in
12 min readApr 24, 2018

In Lesson 2, we learned that Bitcoin consists of a peer-to-peer payment system with an in-built virtual currency (BTC). A user can transfer the ownership of BTC by sending a transaction to the network and waiting for this to be confirmed, which will take place once the transaction is included in a new valid block. BTC is valuable because (i) it is limited in supply; (ii) it can be sent globally; (iii) transactions tend to be fast and cheap; and (iv) coins cannot be issued or spent without authorisation.

In this Lesson, we explore how the Ethereum network differs from Bitcoin. We also examine the nature of smart contracts and discuss the role that they play in the Ethereum network. As we go along, we will build on the technical concepts discussed in the previous Lessons — make sure you check those out!

Between Bitcoin and Ethereum

Bitcoin is an open source project, which means that users can audit the code base that fuels the Bitcoin protocol and network. This transparency allows developers to verify the technical elements of the network and to flag up any vulnerabilities. At the same time, developers can copy Bitcoin’s code base and make some alterations to launch their own peer-to-peer payment networks. For instance, the team behind Litecoin decided to reduce the block-creation interval to 2.5 minutes and to create a native currency (LTC). Dogecoin is another Bitcoin-derived network that has its own native currency (DOGE). While this network was initially created as a joke, it has attracted a loyal following and is now valued at $461 million.

We encourage you to watch the video in the Dogecoin website. Share your thoughts on our Telegram group

Within Bitcoin itself, users devised ways to transact with assets beyond BTC without having to change its code base. A popular way of achieving this involved “colouring” a particular set of coins (UTXOs) by embedding some metadata within a transaction. These coloured coins could be made to represent some right (e.g. access to a subscription service), another digital asset (e.g. an alternative cryptocurrency), or a real-world object (e.g. a share). By accessing the relevant coloured coin wallet, users could transfer and track the ownership of the coloured coins. This allowed users to take advantage of Bitcoin’s distributed infrastructure and robust consensus mechanism while using non-BTC assets. However, it meant that trust had to be placed on an external institution (and wallet software) to recognise the legitimacy of these coins, as the Bitcoin protocol does not recognise this metadata.

In the years that followed Bitcoin’s launch, many DLT networks were built from the ground up to offer support for services beyond processing payments. These include public networks like Nxt and Bitshares (decentralised exchanges) and permissioned networks like RippleNet (settlement of interbank transfers). However, each of these networks specialises in providing a particular service, which means that there is no one-shop-stop for users who wish to consume distributed services. To upgrade this set of features, the consent of most of the network participants will be needed, which can make the process of expanding the range of use cases very difficult.

The Ethereum network

Having been active in the Bitcoin community for some time, Vitalik Buterin noted the inefficiencies associated with having many application-specific DLT networks. Instead, Vitalik envisioned a single network capable of supporting many different applications from the get-go. In early 2014, Vitalik produced a whitepaper outlining the inner workings of the Ethereum network, which he conceived with the sole purpose of addressing this challenge.

Following a successful crowdfunding round in 2014, the team behind Ethereum raised $15 million to work on the development of the network. Ethereum went live in 2015 and has now become the second most valuable DLT network, with a market valuation of $59 billion. While Bitcoin still dominates the crypto-asset market, Ethereum tends to have around 3X as many transactions per day as Bitcoin. In addition, most of the other crypto-assets have been launched on top of the Ethereum network (Lesson 4). Advocates of Ethereum jokingly refer to the day in which the network will surpass Bitcoin’s market valuation as the “Flippening”.

Vitalik Buterin at TechCrunch Disrupt in 2017. He is currently 24 years olds and is widely regarded as a genius

Though Ethereum was built from the ground up to serve as a general purpose platform, it borrows a number of technical features from the Bitcoin network. For instance, it is a public DLT network that relies on the blockchain data structure to group ledger entries and uses proof-of-work as its consensus mechanism. In addition, Ethereum has an native currency called ether (ETH) that can also be used as a means of payment.

On the other hand, Ethereum does not limit itself to the transfer of ether between users. Instead, it is a general purpose platform that is capable of supporting a wide range of applications and use cases. There are a number of other consequential differences between each of these networks. For instance, Ethereum’s block-creation interval is set at approximately 15 seconds, as opposed to 10 minutes. Ethereum also uses a hashing algorithm as part of its mining process that is resilient against ASICs, though high levels of hash rate concentration can still be observed.

(i) Turing-completeness & smart contracts

There are two features of the Ethereum ecosystem that allow it to offer support for a wide range of applications. In this section we focus on the first of these features: Ethereum’s support for Turing-complete programming languages. This feature allows users to send any arbitrary instruction to the network that is capable of being processed by a computer (given enough time and storage space). The pieces of code that are embedded into transactions by way of instructions are referred to as smart contracts.

At its core, a smart contract is simply a computer program, that is, encoded logic that processes a set of inputs to arrive at one of several predefined outputs. Users can programme smart contracts to perform calculations, store data or hold tokens in escrow until some predefined condition is met.

We examine the notion of state below. Source: Gendal

Example: Alice programs a smart contract to send 5 ether to Bob each month, thereby creating a direct debit that does not involve an intermediating bank.

It is helpful to examine in more detail some of the common use cases for smart contracts:

  • Creating state-contingent payments: these are payments that will only be carried out once a predetermined set of conditions is met, such as the consent of several parties (as with multi-signature signatures), the receipt of funds (as in an ICO), or the occurrence of an external event (such as a fall in a stock’s price).
  • Acting as a data source: smart contracts can store data to create libraries that other contracts can access. In addition, smart contracts can be prompted to forward data to other smart contracts.
  • Storing valuable data: users may choose to store encrypted data within a smart contract, allowing entities who hold the decryption key to access the data remotely. In addition, meta-data (such as a hashes) can be stored in a smart contract to proof that a document was in existence at a specific point in time.
  • Creating new tokens and digital rights: smart contracts can be used to generate new Ethereum-based tokens and to govern a set of ongoing relations between a subset of networks users (Lesson 4).

Ethereum’s support for various Turing-complete programming languages stands in sharp contract to Bitcoin. The latter has an in-built language called Script that is limited in functionality by design, as it is optimised to handle simple payment instructions and aims to reduce the network’s attack surface. Nevertheless, apart from enabling the creation of coloured coins, Script does allow users to create simple forms of smart contracts. For instance, users can create an on-chain escrow mechanism, where the BTC sent are encumbered by making a multi-signature (M-of-N) transaction that requires each of the specified key-owners to authorise the expenditure of those funds.

(ii) The Ethereum Virtual Machine

The second feature that allows Ethereum to function as a general purpose platform is the Ethereum Virtual Machine (EVM). Instead of running a decentralised payment system, Ethereum is using the network’s computing resources to run a decentralised world computer (the EVM). By way of analogy, we can think of the EVM as an operating system that allows users to execute various types of programs (smart contracts).

Just as each node maintains its own copy of the ledger, each node runs its own EVM and executes instructions independently. The purpose of this is to prevent any tampering by ensuring that every node in the network registers the right output and stores the same data.

Ethereum’s state richfulness

DLT networks can be described as transaction-based state machines. In this context, state refers to the current allocation of data and tokens in the network. Transactions push new data into the network, thereby triggering a change of state. While each transaction has the capacity to alter the network’s state, these changes are effected periodically when a new block is confirmed. The diagram below shows the state transitions from the genesis state to the current state (n).

Source: Kasireddy

In the context of Ethereum, it is helpful to distinguish between the global state and state of a smart contract. The global state refers to the current distribution of data and tokens at the network-wide level. In contrast, a smart contract’s state merely represents the data and tokens that the smart contract is currently storing internally. In contrast to Bitcoin, where funds can only be spent or unspent, Ethereum provides rich statefulness by supporting Turing-complete programming languages, allowing multi-stage contracts to be formed.

Types of accounts

Ethereum’s global state is comprised of many objects (called “accounts”) that can interact with one another through a message-passing framework. Each account has a unique address, which comprises a 20-byte alphanumeric string, and an ether balance. In turn, accounts can be subdivided into two mutually exclusive types:

  • Externally-owned accounts have an associated private key that enables its holder to send (or “fire”) transactions to other accounts.
  • Contract accounts do not have a private key and cannot send transactions, though they may be able to interact with other accounts when prompted to do so. Apart from having an ether balance, a contract code stores executable (smart contract) code and has internal storage.

When a user sends ether to another user, the transaction is merely taking place between two externally-owned accounts. To deploy a smart contract, a contract-creating transaction bearing the smart contract’s code must be sent from an externally-owned account. This transaction will also generate a contract account (with an associated address) for the code to reside in. The transaction will be packaged by a miner into a new block, and, in the process of validating that block, other nodes will register the transaction into their own versions of the ledger. This reconciliation process allows the nodes to agree on a new global state, in which the relevant smart contract is registered as deployed.

An important characteristic of blocks in Ethereum is that, apart from containing a list of new transactions, they contain a snapshot (in the form of a hash) of the latest state of every account. To overwrite the state of a contract account, a transaction will need to be sent from an externally-owned account to the contract account’s address. This transaction will specify in the data field the function to be called and the parameters to be inputted. However, the transaction may instruct the smart contract to send a “message” to another contract account, which would serve as an indirect way of updating a contract account’s state. Unlike transactions, messages sent between contract accounts are not serialised and only exist within the EVM.

Source: LuxSci

The components of a transaction

The following diagram depicts the fields that can be filled within a transaction:

Note that state transitions take place collectively in blocks. Source: Kasireddy
  • The nonce field shows the number of transactions that have been sent from the sender’s account and seeks to prevent users from double-spending funds.
  • The gasPrice and gasLimit fields are used to indicate the maximum “gas” fee that the sender is willing to pay to have the transaction confirmed by a miner. The concept of gas is discussed below in further detail.
  • To indicates the address of the transaction recipient. While this must be specified when transferring ether to a pre-existing account, the field is left empty in a contract-creating transaction.
  • The value field contains the amount of ether (in wei subunits) that the sender wishes to transfer to the specified account. In the case of a contract-creating transaction, the value field serves as the starting balance of theassigned contract account.
  • The v, r, s fields of a transaction are used to generate the sender’s signature.
  • The init component is only present in contract-creating transactions and is used to initialise the contract. In contrast, the data field is used only when sending instructions to a pre-existing contract account, for instance to call a function in the smart contract code.

Gas: fees for computation and storage

Every single operation on the Ethereum network is executed independently by each full node on their EVM. This helps to prevent malicious actors from tampering with the execution, as nodes will be able to detect an inconsistency with their own output. As a result of this redundancy, it is generally expensive to request that computational steps be carried out or to reserve storage space. Therefore, users must pay ether (by way of gas fees) to reward miners for registering new transactions within a block and executing the embedded instructions on their EVM. Gas is also required upfront to fuel any sub-executions that occur as a result of a transaction, such as messages sent from one contract account to another.

Given that Ethereum’s programming languages allow for loops, gas also helps to address vulnerabilities related to unbounded execution or non-termination of code. The gas balance that users commit to a transaction is depleted as each small instruction (or “opcode”) is carried out sequentially. Each opcode has a fixed gas cost which varies with the complexity of the instruction. If the gas runs out before the execution is complete, the node will throw an out-of-gas exception and exit the process. Any changes made during the execution to a contract account’s state will be reverted. Further, the gas fees will be kept by the miner to compensate for the wasted work. The gas mechanism also prevents malicious users from carrying out distributed denial-of-service (DDoS) attacks, as it would be prohibitively expensive to flood the network with resource-intensive instructions.

When sending a transaction, users specify a gas limit, representing the maximum units that they are willing to pay for, and a gas price per unit. The following equation is then applied:

gasPaid = gasPrice * min(gasUsed, gasLimit)

A high gas price can be used to incentivise a miner to confirm the transaction by prioritising its inclusion within a new block.

Lesson recap

In this Lesson, we learned that Ethereum is a general purpose platform that uses smart contracts to allow users to build their own decentralised applications. These smart contracts can be thought of as programs that have an ether balance and an internal storage. Users can track the state of a smart contract to keep track of their obligations and examine the history of transactions that have been sent to and from the associated contract account.

Consolidation exercises

  1. Browse the most recent block of transactions on Etherscan and note how its contents differ from those of Bitcoin
  2. You can view stats for the network in real time, such as the recommended gas price, on the following site
  3. Use MyEtherWallet to create a wallet for Ethereum-based cryptocurrencies. No need to buy ether, but keep your private key safe!

Extend your knowledge

Finally, watch the following video of Vitalik to wrap it all up:

In Lesson 4, we consider DApps, DAOs and ICOs, which are all powered by smart contracts.

--

--