Hyperledger Fabric Architecture Part 1

In a previous article, you have learned that Hyperledger Fabric has a highly modular and configurable architecture.  In this article, we shall examine the architecture in more details.

Hyperledger Fabric Network

Hyperledger Fabric is a permissioned blockchain network that provides ledger services to application clients and administrators. It allows multiple organizations to collaborate as a consortium to form the network.  The permissions to join the network are determined by a set of policies that are agreed to by the consortium when the network is configured. The network policies may change over time subject to the agreement of the organizations in the consortium.

The Hyperledger Fabric network comprises the following components:

  • Ledger 
  • Peers
  • Ordering service
  • Chaincode (aka smart contract)
  • Channels
  • Membership service provider

The Hyperledger ecosystem also consists of the client applications that allow users to interact with the network.  Moreover, The Hyperledger Fabric application SDK provides a powerful API for developers to program applications to interact with the blockchain network on behalf of the users.  

Peers

The Fabric network is comprised primarily of a set of peers or nodes. Peers maintain the state of the network and a copy of the ledger. In addition,  they also host smart contracts(chaincode).

There are two different types of peers in Fabric, the endorsing peer and the committing peer. The endorsing peers (aka endorsers) simulate and endorse transactions. On the other hand, the committing peers (aka committers) verify endorsements and validate transactions before committing transactions to the blockchain. On a separate note, the endorsing peers can also commit transactions to the blockchain. Indeed, the endorsers are special kind of committers. However, the committers cannot be the endorsers.  All peers can commit blocks to the distributed ledger.

Ordering Service

The ordering service is  made up of a cluster of special nodes known as orderers. The ordering service accepts the endorsed transactions and specifies the order in which those transactions will be committed to the ledger.  However, It does not process transactions, smart contracts, or maintains the shared ledger. 

The Transaction workflow

Let’s examine the transaction workflow that involves the client applications, the peers and the orderers.  By examining the entire transaction workflow, we will learn how consensus is reached in the process.

The transaction flow to reach consensus consists of three phases:

  • Transaction endorsement
  • Ordering
  • Validation and commitment

Phase 1 Transaction Endorsement

Transactions begin with client applications sending transaction proposals to the endorsing peers, as shown in the following diagram:

Phase 2 Transactions Simulation

At this phase, the endorsers will simulate the proposed transactions, without actually updating the ledger.  The Endorsers must hold smart contracts in order to simulate the transaction proposals. In the simulation process, the endorsing peers will capture the set of Read and Written data, known as RW Sets.

These RW sets contain data that was read from the current world state while simulating the transaction, as well as data that would have been written to the world state had the transaction been executed. The endorsing peers then sign these RW sets and send them back to the client application for use in the next phase of the transaction flow, as shown below:

Phase 3 Ordering 

At this phase,  the client application submits the endorsed transactions and the RW sets to the ordering service. The ordering service will take the endorsed transactions and RW sets and orders them into a block and delivers the block to all committing peers.

The order of transactions needs to be established to ensure that the updates to the world state are valid when they are committed to the network. Unlike the Bitcoin blockchain or Ethereum, where ordering occurs through mining, Hyperledger Fabric allows the organizations to choose the ordering mechanism that best suits that network.

Hyperledger Fabric provides three ordering mechanisms i.e. SOLO, Kafka, and Simplified Byzantine Fault Tolerance (SBFT). However, SOLO is used only for experimentation purposes and SBFT has not yet been implemented. Therefore, Kafka is the default ordering mechanism for production use. The Kafka mechanism provides a crash fault-tolerant solution to ordering.

Phase 4 Transactions Validation

At this final phase, the committing peers validate the transactions by checking that the RW sets still match the current world state. In addition, they need to ensure that Read data that existed during the simulation process is identical to the current world state.

After the committing peers validated the transactions, the transactions are then written to the ledger, and the world state is updated with the Write data from the RW Set. Committing peers are responsible for adding blocks of transactions to the blockchain and updating the world state.  Lastly, the committing peers asynchronously notify the client application the results of the transactions.

I shall discuss channels, membership service provider and chaincode in another article.

Gas, Gas Price and Gas Limit

What is Gas?

By definition, gas is a unit that measures the amount of computational effort that it will take to execute certain operations on the Ethereum blockchain. The operations include sending tokens, deploying a smart contract, interacting with a contract, sending some ETH, launching an ICO, or anything else on the blockchain. Gas is needed to power the Ethereum Ecosystem, just like fuel is needed to power a car.

What is Gas Price?

As I have mentioned earlier, we need to use gas for every operation made on ethereum, regardless of whether your transaction succeeds or fails. Gas does not come free, we need to pay for it, just like paying for the gasoline in order to drive our cars. How much transaction fee we need to pay depends on the gas price and the gas limit.

Gas price is the amount of Ether you need to pay per unit of gas. It is measured in Gwei (1Gwei=0.0000000001 ETH).  Its value is determined by the miners, who can refuse to process the transaction with less than a certain gas price. The transaction fee is paid to the successful miner as a form of incentive that motivates the miners to maintain the nodes. Therefore, they have the controlling power over the gas price. We must have enough ether in our wallet to pay for the gas fees.

The transaction fee is calculated using the following formula

Transaction fee= Gas unit used x Gas price

For example, for a certain transaction,

gas unit used=103631

Gas price= 1Gwei or 0.000000001 Eth

So transaction fee= 103631×0.000000001 Eth=0.000103631 Eth  

You can see the actual output in a smart contract deployment on Etherescan, as shown in the figure below:

In addition, you can “bribe” the miners to do your work first by paying more gas fees. In this way, you can jump to the front of the queue so that your transaction can be processed first.  Even if the transaction fails, you still need to pay for the transaction fee because the miners must validate and execute your transaction.

Gas Limit

The Gas Limit is an estimation of the total amount of work to perform a transaction. It is not easy to compute the gas limit. Fortunately, there are many apps that set the limit for us. Typically, 21,000 Gas will satisfy most transactions. However, for more complex transactions such as sending ETH to an ICO smart contract, the gas limit will be much higher. The reason is such a transaction requires much more computational power.

If you set the limit is too low, your transaction may take too long to process and even fail. As a result, you will lose ETH for nothing. On the other hand, if your transaction was completed before reaching the gas limit, you get back the balance ETH. The Gas Limit protects you from spending unlimited ETH, just like what banks set your credit card limit so that you will not overspend.

Solidity Data Types

Solidity is a statically typed programming language, which means that the type of each variable needs to be specified at compile-time. Solidity provides several categories of data types, as listed below:

  • Value types
  • Reference types
  • Mappings

Value Types

These types of data are called value types because variables of these types will always be passed by value. There are several value types in solidity, as listed below:

  • Boolean
  • Integer
  • Fixed Point Number
  • String
  • Address
  • Array
  • Literal
  • Enum

We shall focus on boolean, integer and string data types first and discuss other data types in future articles.

Boolean

Boolean is a data type that only produces two possible values, true or false. They can be used together with some common operators, as follows:

OperatorMeaning
!Logical negation
&&Logical conjunction  “and”
||Logical disjunction “or’
==Equality
!=Inequality

We declare a Boolean variable using the keyword bool

Integer

There are two types of integer, the signed integers, and the unsigned integers. The keyword to declare signed integers is int and the keyword to declare unsigned integers is uint. In addition, we can assign the number of bits a signed integer can hold using int8, int16 until int256. Similarly, we can use uint8 until uint256 for unsigned integers.

We declare an integer variable using the keyword int or uint

We can use various operators to deal with operations that involve integers. The operators are listed as follows:

Comparison Operators<=  < ==  != >=  >
Bit Operators&  |  ^ and   ~
Arithmetic Operators –  * /   % **  << >>

String

The string is a data type that cannot be operated arithmetically. String literals are written with either double or single-quotes, for example, “Abraham”, “007”, “abc%&$” and more.

We declare a string variable using the keyword string .

Example: This example The string two types of variables, unsigned integer and boolean. We also use the keyword if and the operator > to check whether the outcome is true or false.

The code

pragma solidity ^0.4.24;

contract myContract2 {
      uint private a;
      uint private b;
      bool ans;
   
 function getValue1(uint num1) public{
    a = num1;
 }

  function getValue2(uint num2) public{
    b = num2;
 }
 
  function checkAns() public view returns (bool){ 
      if (a>b)
          ans=true;
      else
      ans=false;
      
      return ans;
  }

 
}

After we compiled and deployed the contract, we get the following output. We can test the results by entering different values in getValue1 and getValue2. The results will be either true or false.

The output on Remix iDE

Introduction to Solidity

What is Solidity?

Solidity is a high-level programming language that is used to create and implement smart contracts in Ethereum. The smart contracts created using Solidity can be used for financial transactions, crowdfunding, voting, intelligent supply chain management, improvement of  IoT workflow, ride sharing automation, smart city administration and more.

It has Python, C++ and JavaScript influences and is used for Ethereum Virtual Machine ( EVM ). As a result, it is fairly convenient and easy to grasp for those that are already familiar with the Python, C++ or JavaScript.

The IDE for Developing Smart Contracts

The best tool to write, compile, test and deploy smart contracts is  Remix.  Remix is a browser-based IDE that provides an inbuilt compiler as a well as runtime environment without server-side components.

We can also use other code editors for Solidity. I suggest we use Visual Studio Code or Solidity Plugin for Visual Studio. For the Solidity plugin, you need to download it from https://marketplace.visualstudio.com/items?itemName=ConsenSys.Solidity
Besides that, you need to install Visual Studio 2015.

Writing Your First Smart Contract in Solidity

A smart contract is a data, that can be referred to as its state, and code, which can be referred to as its functions, collection, that resides on a specific address in the Ethereum blockchain.

The first line of the smart contract is always 

pragma solidity ^0.4.24;

pragma is a keyword which is used to instruct the compiler how the source code should be treated. In this example, the pragma specified that the source code is written for the Solidity Library version 0.4.24

To define a contract, we use the statement

contract contractName {

}


You can use any name for the contract, but any meaningful name will be better. For example

Contract  NewCoin{

}

indicates that you intend to create a contract for a new cryptocurrency.

Assigning variables

Next, we would like to introduce some variables into the contract. First of all, let’s assign some string variables and some integer variables.

To assign a string variable, the syntax is

string myName;

In Solidity, there are two types of integers, the signed integer and the unsigned integer.

A signed integer means it can store positive or negative values while an unsigned integer can only store positive values.

To specify that it will be an unsigned integer, we use the keyword uint before the name of the new variable.

To assign an unsigned integer, the syntax is as follows;

uint MyAge;

Access Modifier

You may want to add the access modifier(or visibility modifier) private or public to the variable. Most programming languages put access modifier in front of the datatype  specifier like private string name but in Solidity, we put access modifier between datatype specifier and the variable name, as follows:

string private myName; 
String public myName
uint private MyAge;
uint public  MyAge;

Writing the Smart Contract Code

Now launch Remix IDE. Create your first smart contract by clicking on the little + button on the far left corner of the Remix IDE.  A new dialog will appear and you can create a new Solidity file.

After creating the new file, a new window will appear on a new tab displaying your new file. The file will also be show on the left pane of the IDE under the browser.

Now, let’s create a new contract by entering the following code into the Remix IDE.

pragma solidity ^0.4.24;

contract myContract {
    string private name;
    uint private age;
}

The first line inside the contract itself declares a string name and an unsigned integer variable called age.

We have already created a simple smart contract though it does not do anything yet. You can compile and deploy it if you want to.

Now let’s add some functions to the smart contract

pragma solidity ^0.4.24;

contract myContract {
    string private name;
    uint private age;
   
 function setName(string newName) public{
    name = newName;
 }

  function getName() public view returns (string){ 
    return name; 
  } 
  
  function setAge(uint newAge) public{
      age=newAge;
  }
  function getAge() public view returns (uint){ 
      return age;
  }
}

We create the function setName to allow the user inputs a string value. Set the modifier to public as we want to permit everyone to see it. Otherwise, when you deploy the contract you will not be able to view the function on the Remix IDE.

To return the value of name entered by a user, we create the function getName

The view keyword in public view returns is  the replacement for constant. It indicates that the function will not alter the storage state in any way.

Next, we create the function setAge by declaring  a parameter newAge as an unsigned integer. The setAge function will allow the user input an integer value when you deploy the contract.

To return the value of age entered by the user,  we create the function getAge

Now compile and deploy the Remix IDE, the output is shown in the following figure:

Deployed Contract

When you deploy the contract, a transaction is executed from your wallet address to the contract. A gas fee is charged in the process. You can view the transaction on Etherscan, as shown below:

When you click on the setName function, a transaction will also occur. You need to wait for the transaction to complete before you click on the getName function. You can see that whatever you entered in the setName box will appear on the getName box. You can do the same for the setAge and getAge functions.

Introduction to Corda

A Brief History

Corda is another enterprise-ready blockchain platform other than Hyperledger.  It was developed and launched by R3 in 2016. R3 is an enterprise software firm which focuses on distributed ledger technology.  It collaborates with more than 200 members and partners across multiple industries from both the private and public sectors to work on the Corda project.

Besides that, R3 has assembled a global team of over 180 professionals in 13 countries and over 2,000 technology, financial, and legal experts drawn from its global member base. (www.r3.com)

Key Concepts of Corda

Corda is an open source blockchain project, designed for business from the start.  It allows businesses to build interoperable blockchain networks that transact in strict privacy. Similar to Ethereum, Corda also features smart contracts that facilitate direct transactions among the businesses. However, its smart contracts are written in Java and other JVM languages instead of Solidity.  Also, it enables the development and deployment of distributed apps called CorDapps.

In addition, the Corda platform implements the flow framework to manage communication and negotiation between participants in the network. The Corda network is made up of a peer-to-peer network of nodes. One of the key concepts of Corda’s is its network service known as the notary.   The notary service provides uniqueness consensus for verification of transactions. I shall discuss uniqueness consensus in future articles.

The Corda Architecture

Although we often refer to Corda as a blockchain platform, strictly speaking, it is not a blockchain-based ecosystem. It is a kind of decentralized ledger technology network system that is not built by blocks. Instead, it looks a bit similar to the Tangle system in IOTA.

The Corda Network

The Corda network is an authenticated peer-to-peer network of nodes. Each node is a JVM run-time environment hosting Corda services and executing applications known as CorDapps. We can visualize the Corda network as a fully-connected graph. The nodes on the graph  can communicate with other nodes, as shown in the diagram below:

Corda Network

How does Corda differ from other DLT Platforms?

The Corda platform is different from other DLT platforms because 
 the structure is block-less. Also, the way it propagates data is also different.  Other DLT  platforms use global broadcast and gossip networks to propagate data. However, Corda does not employ the global broadcast method. Instead, It uses point to point messaging to transmit data.


According to the Corda white paper, all communication between nodes is direct, with TLS-encrypted messages sent over the AMQP. This means that data is shared only on a need-to-know basis. (*TLS stands for Transport Layer Security.  AMQP stands for Advanced Message Queuing Protocol,  an open standard application layer protocol for message-oriented middleware)

Corda nodes discover each other via the Network Map Service. The network map service publishes the IP addresses through which every node on the network can be reached. Also, it broadcasts the identity certificates of those nodes and the services they provide. You can imagine the service as a phone book, which publishes a list of peer nodes containing some information.

The Doorman

Corda networks are semi-private,  which means it needs to impose a kind of gateway control before a node can join a network. This control is called doorman. Each network has a doorman service that enforces rules regarding the information that nodes must provide. These nodes need to go through the know-your-customer (KYC)process before being admitted to the network.

To join the network, a node must contact the doorman and provide the required information. If the doorman is satisfied, the node will receive a root-authority-signed TLS certificate from the network’s permissioning service. This certificate certifies the node’s identity when communicating with other participants on the network.

That’s all for now. I shall discuss more about Corda in future articles.