There are two buzz words that we have been hearing a lot these last years: Smart Contracts and Blockchain.
The intention of this article is to explain what a smart contract is, starting from the beginning, first explaining the whole ecosystem that allows it to work. It will focus on a particular blockchain [³] network called Ethereum. Explaining, among other things, the protocols that are being used, alternative forks to it that allow having public and private networks and the inner working that happens under the hood.
It will start by describing all the background required to understand blockchain basic concepts and what smart contract is, how you can create it and its different usages today.
What’s a blockchain?
A blockchain is a list of records, called blocks [²], where each one contains transaction data, a cryptographic hash of the previous record (the first block is called the Genesis block), and a timestamp. The hash to the previous record in each block links the blocks together, forming a chain. This is why it’s called blockchain. This “chain” forms a hash tree where the root is the Genesis block. Essentially, a blockchain is an open, distributed ledger that can record transactions between two parties efficiently and in a verifiable and permanent way.
Every time a transaction [²⁸] is conducted on a blockchain, the transaction data will be stored in a new block. This new block will then be added to the blockchain. Before the block can be added to the chain, the information contained in it must be verified by the network. This happens by creating a hash. A hash is a 256-bit number that identifies the data in the block. To create this hash a mathematical equation must be solved. This process is called mining [¹⁶]. Mining requires high computational power and specialized hardware. In public blockchains, miners’ incentive to mine new blocks is the mining reward, which is generally paid in the native cryptocurrency, which can be profitable depending on the energy consumption invested in solving the equation. Blockchains are distributed along many devices (called “nodes”). Each node stores the entire history of transactions, the whole blockchain. If the transaction data of a block were modified, the hash of that block would be updated. Therefore, the hashes of the blocks that referenced that block would be updated too, which would change their own hashes, and this would spread through the whole chain. So, if a malicious actor wanted to alter a block, they would have to modify the entire blockchain, which is practically impossible because of the necessary computing power.
The idea of blockchain began in 1982 when David Chaum proposed a blockchain-like protocol in his paper Computer Systems Established, Maintained, and Trusted by Mutually Suspicious Groups , yet the first implementation of a blockchain was 27 years later, on 3 January 2009, when Satoshi Nakamoto mined the genesis block of Bitcoin . In 2011 other cryptocurrencies began to emerge such as Litecoin, Namecoin and Swiftcoin. In 2013 the Ethereum cryptocurrency was created beginning what is known as the second generation of blockchain technology, with the introduction of smart contracts [²⁶] that are computer programs that can run on the blockchain, which allows rules to be imposed automatically when a transaction ocurrs. Today there are hundreds of cryptocurrencies, you can find them all here .
Consensus Mechanism [⁵]
Proof of Work (PoW) [²²]
Proof of Stake (PoS) [²¹]
The main benefits of using blockchain are:
Improved times: Every actor involved can check data as it is ready.
Transparency: Viewing data is simple, and it is available to all members.
Immutability: The immutability of transactions makes it easy to track things or check logs.
Each person that participates in a blockchain has a private key [¹⁸] and a public key [²³]. When using a person’s public key, it is possible to encrypt a message so only that person with the private key can decrypt and read it. Using a private key, a digital signature can be created so that anyone with the corresponding public key can verify that the message was created by the private key owner and was not modified since then. This signature is used to confirm that the transaction has come from the user and prevents the transaction from being altered by anyone once issued.
The private key is used to mathematically derive the public key, which is then transformed with a hash function to produce the address that other people can see.
The main difference is that in private blockchain networks, those who want to participate need a user with specific permissions established by the blockchain administrator [¹]. In public blockchains, anyone can participate. That’s why private and public networks are also known as permissioned and permissionless networks, respectively.
Public networks are decentralized, and the data can’t be changed once validated on the blockchain, and users are anonymous. These properties are useful in scenarios where transactional history, openness, and user anonymity are essential, such as cryptocurrencies.
On the other hand, private networks are better suited for scenarios where sensitive data is involved. In private networks, it can be specified who can read or write which data. They provide faster transactions because there are fewer nodes and better scalability since the administrator can add nodes and services on demand.
A protocol is a set of rules or procedures that govern data transfer between two or more electronic devices. Since a blockchain is a network of multiple devices, it needs a protocol to validate transactions and define an algorithm for all participating nodes to interact with each other. The protocol of a blockchain is accepted by all the participating nodes in the network. A blockchain protocol must include:
An algorithm that defines the mechanism for all participating nodes to interact with each other.
Defined rules on how transactions are governed and validated.
A Blockchain protocol operates on top of the Internet, on a peer-to-peer network of electronic devices that all run the protocol and hold an identical copy of the ledger of transactions, enabling transactions without a central authority though machine consensus.
Different blockchains implement different protocols. Depending on the objective of the blockchain, the mechanisms for the interaction between the nodes can vary from having each node being equally important as happens in bitcoin, or having a central administrator that validates transactions and creates blocks as happens in private networks. The crypto-economic rulesets of the blockchain protocol (consensus layer) regulate the behavioral rulesets and incentive mechanism of all stakeholders in the network.
To understand better why there are different blockchain protocols, let’s see some examples and analyze the pros and cons that each protocol has:
Public, permissionless blockchain which anyone can join. It’s as easy as following the steps described on how to run a full node .
Decentralized network: Every node has access to complete information on the blockchain.
Underlying technology components: Cryptographic hash function (used in blocks), peer-to-peer network, digital signature, and private-and-public key encryption (to ensure the authenticity of the actors of the transaction).
Users can conduct non-reversible transactions without the need to explicitly trust a third-party. As we mentioned, bitcoin has a consensus mechanism known as proof-of-work, removing the need for a trusting central authority.
This protocol has the benefit of being very transparent since everyone can see in every transaction when it happened, the accounts involved and how much was exchanged, which gives users a great deal of trust in the system, a key value when dealing with money. However, these benefits have their counterpart. When someone creates a new transaction it must be appended to a block, and then that block needs to be mined, which takes more than 10 minutes, a lot of time compared to the immediate transactions that most banks offer, also it takes a great deal of computational power and electricity compared to a simple transaction in a private system. Plus, what makes it so transparent, can be a problem, especially for companies that want to keep their transactions as private as possible to avoid risking for the competence to know their earnings and spending.
Hyperledger Fabric protocol:
The ledger can only be updated by consensus of the participants, and once recorded, information can never be altered.
Each recorded transaction is cryptographically verifiable with proof of agreement from the participants.
Transactions are secured, private, and confidential.
Each participant registers with proof of identity to the network membership services to gain access to the system.
Transactions are issued with derived certificates untraceable to the individual participant, offering a complete anonymity on the network.
Implements the practical Byzantine Fault Tolerance consensus algorithm. The goal is that all honest nodes help in reaching a consensus regarding the state of the system using the majority rule.
As you can see this protocol is quite different from the bitcoin one, that’s because the Hyperledger fabric protocol was designed to be used by companies. Companies are interested in using a blockchain because every transaction is immutable, so the ledger allows compliance with regulations as ledger entries are auditable in whole or in part, and the directives it stockholders can have a registry of transaction in which they can fully trust that no one has modified it for personal gain.
Quorum [²⁴] protocol:
A single member [¹⁴] can own all the nodes, or a consortium [⁶] blockchain network, where multiple members own a portion of the network each.
Private, permissioned network.
Members of a Quorum network can send private transactions that are addressed to a subset of nodes.
The primary purpose of the Quorum project was to develop an enterprise Ethereum client for businesses, so the main benefit is that it supports smart contracts, and being a private network it has all the benefits that private blockchains have for businesses, and it is more flexible than the Hyperledger Fabric since it supports the Clique and Raft [²⁵] consensus algorithms which allows businesses to have absolute control over the accepted transactions by being the member that owns all the nodes.
Quorum is an enterprise blockchain platform. It is a fork of the public Ethereum client gethwith several protocol level enhancements to support business needs. On Ethereum, users can build blockchain applications accessible anywhere in the world. Quorum is an Ethereum-based distributed ledger protocol with transaction/contract privacy and new consensus mechanisms.
A node can be any system that has storage capacity and internet connectivity. There are two main types of nodes — full nodes and light nodes (see this link for more details).
Full Nodes: They contain а copy of the blockchain’s history, including all blocks created. Full nodes act as a server in a decentralized network. Their main tasks include maintaining the consensus between other nodes and verification of transactions. When making decisions for the future of a network, full nodes are the ones that vote on proposals.
Pruned full node: It begins downloading blocks from the beginning and once it reaches a set limit, deletes the oldest ones, retaining only their headers and chain placement.
Archival full nodes: Envision a server that hosts the full blockchain in its database.
Staking Nodes: The end goal is to determine, based on a pre-defined set of rules and luck chance factored in, who will be next to create a block and get rewarded.
Authority Nodes: The task of these nodes is to create and validate blocks, while at the same time distributing information to users on the network. All participants, not chosen to be an authority node, will be running light nodes that depend on the broadcasted data to operate on the blockchain.
Light Nodes: Only download have the headers of blocks and save hard drive space for users.
Master Nodes: These nodes cannot add blocks to the blockchain. Their only purpose is to keep a record of transactions and validate them.
Miner Nodes: These are nodes (either full or light ones) which aim to prove that they’ve completed the required work to create a block. To complete the task, miners need to either be a full archival node or receive data from other full nodes on the network to know the blockchain’s status and the next block’s required parameters in line.
When a transaction is created, it needs to be allocated in a block so the sender can specify a limit to the “gas” [¹¹] they are willing to spend for the transaction. The transaction then waits in the transaction pending pool until it gets picked and executed by a miner. After a miner successfully generates a new block, all the block transactions are appended to the end of the chain.
Not every node will accept a transaction. Some nodes might have a setting to accept only transactions with a certain minimum gas price. If a transaction gas price is lower than that limit, that node will ignore the transaction.
A successful transaction follows the steps indicated below (to learn more about the transaction lifecycle, visit this page ).
A user requests a transaction.
The transaction is broadcasted to every node in the specific blockchain network.
Every node in the network validates the transaction against the validation rules set by the creators of the blockchain network.
Validated transactions are stored into a block and are sealed with a hash.
This block becomes part of the blockchain when the other nodes in the network validate the block’s hash.
The block becomes part of the blockchain.
In the case of IBFT, the transactions validation loop is depicted below (check Quorum documentation for details):
What happens if there is an error in the transaction lifecycle?
When there is an error in a node, it broadcasts a “ROUND CHANGE” message.
Round change flow
There are three conditions that would trigger [³²] a ROUND CHANGE:
Round change timer expires.
Invalid PREPREPARE message.
Block insertion fails.
2. When a validator node notices that one of the above conditions applies, it broadcasts a ROUND CHANGE message along with the proposed round number. It waits for ROUND CHANGE messages from other validators. The proposed round number is selected based on the following condition:
If the validator has received ROUND CHANGE messages from its peers, it picks the largest round number, which has F + 1 of ROUND CHANGE messages.
Otherwise, it picks 1 + current round number as the proposed round number.
3. Whenever a validator receives F + 1 of ROUND CHANGE messages on the same proposed round number, it compares the received one with its own. If the received is larger, the validator broadcasts the ROUND CHANGE message again with the received number.
4. Upon receiving ceil(2N/3) of the ROUND CHANGE messages on the same proposed round number, the validator exits the round change loop, calculates the new proposer, and then enters NEW ROUND state.
5. Another condition that a validator jumps out of round change loop is when it receives verified block(s) through peer synchronization.
Private transactions in Ethereum
GoQuorum introduces the notion of public transactions and private transactions. Note that this is a notional concept only and GoQuorum does not introduce new transaction types, but rather, the Ethereum Transaction Model has been extended to include an optional privateFor parameter. The sequence of diagrams ahead illustrates the private transaction process:
Participant A sends a transaction to their GoQuorum Node (Validator node), specifying the transaction payload and setting privateFor to be the public keys for Participants A and B (Participant A is optional).
Participant A’s GoQuorum Node passes the transaction on to its paired Transaction Manager, requesting that it encrypt and store the transaction payload before forwarding it on to the recipients of the transaction (i.e. Participant B).
Participant A’s Transaction Manager makes a call to its associated Enclave to encrypt the payload for the given recipients. Participant A’s Enclave encrypts the private transaction payload and sends it to recipients’ Transaction Manager (see the image below).
4. Participant A’s Transaction Manager stores the response from the Enclave and forwards to the private transaction, as shown in the image below.
5. The tx-key is encrypted with the shared-key and the other nonce [¹⁷] (this is done for all recipients).
6. A block containing transaction AB is created and distributed to each GoQuorum node in the network.
7. In processing the block, all GoQuorum nodes attempt to process the transaction. Recognizing that the transaction data is a hash due to the v value, each node will make a call to its Transaction Manager to determine if it is party to the transaction (i.e. there is an entry for the given hash in its database). In this example, Participant A & B’s Transaction Managers will determine that they are party to the transaction whereas Participant C’s Transaction Manager will determine that it is not.
8. Participant A & B’s Transaction Managers make a call to their associated Enclaves to decrypt the payload.
9. Participant A and B’s Enclaves decrypt the transaction payload (see the image below).
10. The Transaction Manager’s return their results to their GoQuorum nodes:
Participant A & B’s Transaction Managers return the decrypted private transaction data to their GoQuorum nodes which can now execute the transaction as normal, thus updating their respective Private StateDB. GoQuorum discards the decrypted private transaction data once used.
Participant C’s Transaction Manager returns a 404 NOT FOUND to its GoQuorum node as it is not a recipient of the transaction. Recognizing that it is not party to this private transaction, the GoQuorum node will skip the execution of the transaction, so that no changes to its Private StateDB are made.
OpenZeppelin is an open-source framework to build secure smart contracts. It’s meant to provide secure, tested, and audited code to enable the new generation of distributed applications, protocols, and organizations. OpenZeppelin is open-source, and MIT licensed. Any organization can be modeled as a set of contracts and rules that define interactions, rights, and obligations between parties. OpenZeppelin aims to model simple business rules with code, turning basic components of an organization into software.
Smart contracts [²⁶] remove the need for trusted intermediaries. They are pieces of software for a wealth of next-generation decentralized applications without involving a trusted third-party.
Benefits of smart contracts:
Autonomy: You’re the one making the agreement. There’s no need to rely on intermediaries, which removes the danger of manipulating data by a third-party since execution is managed automatically by the network, rather than by one or more, possibly biased, individuals.
Trust: Your documents are encrypted on a shared ledger. Both sides of the transaction are sure to have the same documents.
Backup: Imagine if your bank lost your savings account. On the blockchain, every node has a backup of all the transactions. Your documents are duplicated many times over.
Safety: Cryptography, the encryption of websites, keeps your documents safe. There is no hacking.
Speed: You’d ordinarily have to spend a lot of time and paperwork to manually process documents. Smart contracts use software code to automate tasks.
Savings: Smart contracts save money since they remove the need for an intermediary. There is no need to pay a notary to witness your transaction.
How to create a smart contract
The first step to create a smart contract is choosing the blockchain platform that best suits the situation, since different platforms have different advantages and disadvantages. Here is a summary of the main blockchain platforms that support smart contracts:
Ethereum [⁹]: Is one of the most popular smart contract platforms where developers can build decentralized apps through its Ether or ERC-20 tokens. The platform is powered by the Ethereum Virtual Machine (EVM), which is a software that executes all smart contracts. The platform functionality is further enhanced by its proprietary smart contract coding language, Solidity. This makes it easy for developers to not only set up contracts but also build blockchain apps. Ethereum smart contracts can also be developed in Vyper , which is a Pythonic programming language. However, it has less features than Solidity with the aim of making contracts more secure and easier to audit. The beauty of Ethereum smart contracts lies in the support and standardization it offers. Developing smart contracts in Ethereum is easy and less risky as the rules a developer needs to adhere to are clearly published. Ethereum has the biggest market capitalization among all the smart contract platforms. On the downside, however, Ethereum is vulnerable to security threats and bugs in its code.
Stellar: Is designed to facilitate low-cost remittance transactions across borders. For simple, smart contracts such as ICOs , Stellar is the ideal platform to use. It may not be as straightforward as NEM, but it’s more user-friendly than Ethereum. Stellar smart contracts can be written in all major programming languages, including those that the community provides an API for. The contracts are interconnected and executed using various constraints such as batching, multi-signatures, sequence, and time bounds.
EOS: The platform works on an ownership model whereby each user is entitled to resources proportional to their stake. Contracts on the EOS platform are coded in C++ language, which helps improve scalability. The contracts are then implemented into the blockchain in the form of a pre-compiled coding language known as WebAssembly (WASM), which promotes faster execution of contracts. It has near-zero transaction fees topped by the ability to process numerous transactions within a second. Given its architecture and functionality, EOS is suited for building industry scale dApps. If you were to build such applications on a platform such as Ethereum, running it would be overly expensive owing to the transaction fees charged on each function.
NEM: The “New Economy Movement” is a technology platform that seeks to be an efficient way to manage assets and data easily and at low cost. NEM offers seamless ability to interface between public and private blockchains. It enables easy transfer of any digital asset — like tokens, contract, or files — from a privately held internal enterprise network, routed via a public blockchain, and finally to another business’s private network. It has now become the first choice of many developers as it is written using JAVA. It is highly scalable. While Ethereum can process 15 transactions per second, NEM manages to process a 100.
Following, we provide an example to demonstrate the necessary steps to create a smart contract in Ethereum using Solidity. We chose Ethereum because it’s the most widely used blockchain platform that supports smart contracts, plus there is an online IDE called Remix that allows to quickly develop, test and deploy smart contract. It’s the IDE we used for the description of the smart contract creation.
Create a new file called ‘HelloWorld.sol’.
Add this code to the file:
3. On the left side click on the compiler tab and compile the project, as shown in the following picture:
4. Click the “run” icon and deploy the contract as in the following picture:
5. Those are the four steps to deploy a smart contract. To have a better understanding of what was deployed, as shown in the previous image, the deployment of the “HelloWorld” project should appear under “Deployed Contracts” and at the bottom of the page, in the console, there should be a green icon showing a message, that is the output of the deployment.
6. To run the function, there should be an arrow next to the “HelloWorld” contract (under “Deployed Contracts”), by clicking on it the contract should expand and show a button with “greet”, the only function that the contract has. By clicking that button the function will be executed and the output should appear on the terminal. To access the details of the execution, on the terminal, click on the little arrow on the right side and the details of the execution should appear, with the transaction hash and more information. At “decoded output” the “Hello World!” message should appear.
Current applications of Smart Contracts
In this section we will explore the different usages that global companies are giving to smart contracts and why they chose to use them over the traditional contracts.
Populous is taking the invoice financial process and making it easy to use for anyone who wants to buy and sell invoices, applying smart contracts instead of the lawyers and notaries that were necessary to validate the invoices to prevent frauds. The benefit of removing the middleman, and using smart contracts, is the speed at which the process can move while mitigating the risks, including manual human error and duplication of invoice financing. Within Populous, once the invoice seller uploads the invoice and terms, buyers simply choose to finance the money and all transactions are automatically facilitated via smart contract terms.
Propy is one of the first companies to use smart contracts in the real estate business. This “across-borders” real estate marketplace allows owners and brokers to list properties, where buyers can also search and negotiate the sale. Both parties participate in the smart contract together and specific steps are taken throughout the process to ensure fair and legal play. All paperwork and signatures are facilitated remote, through the app, making it easy to buy and sell property, regardless of where you live. Propy had the first transaction in September of 2017, when someone purchased a $60,000 apartment in Ukraine. However, Titles are still sent through local authorities as well, ensuring that every piece of the process follows necessary and legal protocol.
[¹] Administrator Role:
Privileged participants who can take consortium management actions and can participate in blockchain transactions.
Where transaction data is stored, each block contains a hash of the previous block and is linked on the blockchain.
A globally shared, transactional databases that is made up of blocks which contains transaction data and a hash form the previous block.
Made up of a growing list of blocks that are linked with records of transactions.
[⁵] Consensus Mechanism:
A mechanism used by the nodes that are part of the blockchain to check that a transaction is valid.
Used to create private blockchain networks. It can contain two types of member roles: Administrator and User.
[⁷] Contract Address:
The unique address of a smart contract when its deployed to the blockchain.
[⁸] Contract Application Binary Interface (ABI):
The standard way to interact with contracts in the Ethereum ecosystem.
A global, decentralized platform for applications where users can build blockchain applications.
Inheritable members of contracts. A way for smart contracts written in Solidity to log when something occurs.
The fee to complete a successful transaction or execute a contract on the Ethereum blockchain platform.
In Solidity, the indexed parameters for logged events will allow you to search for events.
[¹³] Istanbul Byzantine Fault Tolerance (IBFT):
A consensus algorithm for production enterprise permissioned networks. Blocks in IBFT are final. No fork can occur, validators reach consensus on the current block by appending COMMIT signatures to the extraData field of the header.
A member in a consortium has access to the private consortium blockchain network and can either have a role of a user or administrator.
The dynamic staging area in front of the blockchain that enables transaction ordering, transaction fee prioritization, and general block construction.
The process of creating a new block on the blockchain through the creation of a hash which has a 256-bit number that identifies the data in the block.
A nonce is an arbitrary number used only once in a cryptographic communication. They are often random or pseudo-random numbers. To ensure that a nonce is used only once, it should be time-variant (including a suitably fine-grained timestamp in its value), or generated with enough random bits to ensure a probabilistically insignificant chance of repeating a previously generated value.
[¹⁸] Private Key:
Grants a user ownership of the funds on a given address. The keys are kept private and used for authentication and encryption.
[¹⁹] Private Transactions:
Transactions whose payload is only visible to the network participants whose public keys are specified in the privateFor parameters of the transactions.
[²⁰] Proof of Authority (PoA):
Is a reputation-based consensus algorithm that introduces a practical and efficient solution for blockchain network.
[²¹] Proof of Stake (PoS):
Instead of having nodes compete for the mining reward, a single node is selected to validate the next hash, based on its wealth (its stake on the network). In PoS, the reward is not paid in newly issued coins, but the node will receive a transaction fee.
[²²] Proof of Work (PoW):
Once a new block needs to be created, all miners on the network will start working on the hash puzzle. The miner who solves it first, receives the mining reward.
[²³] Public Key:
Are publicly known and essential for identification, the address that can be used in transactions is a shorter representative form of the public key.
An open source blockchain protocol specially designed for use in a private blockchain network, where there is only a single member owning all the nodes, or a consortium blockchain network, where multiple members each own a portion of the network. It is derived from Ethereum.
A fast consensus algorithm with a default block minting at 50ms, it has immediate transaction finality.
[²⁶] Smart Contract:
A set of logic rules in the form of a coded script which can be embedded into the blockchain to govern a transaction.