Mauro Krikorian
November 13, 2020
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.
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 .
Important concepts:
The main benefits of using blockchain are:
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.
See this article for more details.
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.
See this article for more information.
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:
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:
Bitcoin protocol:
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:
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:
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 geth with 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.
Key enhancements are:
Quorum 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.
Light Nodes: Only download have the headers of blocks and save hard drive space for users.
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.
See this article for more details.
A successful transaction follows the steps indicated below (to learn more about the transaction lifecycle, visit this page ).
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
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:
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.
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:
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:
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.
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:
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.
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.
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.
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.
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.
The unique address of a smart contract when its deployed to the blockchain.
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.
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.
Grants a user ownership of the funds on a given address. The keys are kept private and used for authentication and encryption.
Transactions whose payload is only visible to the network participants whose public keys are specified in the privateFor parameters of the transactions.
Is a reputation-based consensus algorithm that introduces a practical and efficient solution for blockchain network.
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.
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.
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.
A set of logic rules in the form of a coded script which can be embedded into the blockchain to govern a transaction.
An object-oriented programming language for writing smart contracts.
A change that one wants to make in the database that is either not done at all or completely applied.
The process of validation and addition of a transaction to the blockchain.
Used to send blockchain transactions to Azure Blockchain services through a public endpoint.
Contains all uncomforted transactions.
A tool that allows a developer to set a script that will be automatically called when a condition is met.
A development environment and testing framework for blockchain using Ethereum Virtual Machine.
Participants who cannot take any consortium management action but can participate in blockchain transaction.
Originally published by Mauro Krikorian for SOUTHWORKS on Medium 13 November 2020