The eyes are afraid, and the hands itch!
In past articles, we figured out the technologies on which blockchains are built (
What should we build a blockchain for? ) And cases that can be implemented with their help (
What should we build a case? ). It’s time to work with your hands! For the implementation of pilots and PoC (Proof of Concept), I prefer to use clouds, because they can be accessed from anywhere in the world and often do not have to spend time tedious installation of the environment, because There are predefined configurations. So, let's do something simple, for example, a network for transferring coins between participants and call it modestly Citcoin. For this, we will use the IBM cloud and the universal blockchain Hyperledger Fabric. First, let's see why Hyperledger Fabric is called a universal blockchain?
Hyperledger Fabric - a universal blockchain
Generally speaking, the universal information system is:
- A set of servers and a software core that performs business logic;
- Interfaces for interacting with the system;
- Means for registration, authentication and authorization of devices / people;
- Database storing operational and archive data:
The official version of what Hyperledger Fabric is can be read on the
site , and in short, Hyperledger Fabric is an opensource platform that allows you to build closed blockchains and execute arbitrary smart contracts written in the JS and Go programming languages. Let's take a look at the architecture of the Hyperledger Fabric in detail and make sure that it is a universal system that only has the specifics of storing and recording data. The specificity is that the data, as in all blockchains, is stored in blocks that are placed on the blockchain only if the participants reached a consensus and after recording the data cannot be discreetly corrected or deleted.
Hyperledger Fabric Architecture
The diagram shows the architecture of the Hyperledger Fabric:
Organizations - organizations contain peers, i.e. blockchain exists due to the support of organizations. Different organizations may be members of the same channel.
Channel - a logical structure that unites peers into groups, i.e. Blockchain is set. Hyperledger Fabric can simultaneously process several blockchains with different business logic.
Membership Services Provider (MSP) is a CA (Certificate Authority) for issuing identity and assigning roles. To create a node, you need to interact with MSP.
Peer nodes - verify transactions, store the blockchain, execute smart contracts and interact with applications. Peers have an identity (digital certificate) that issues an MSP. Unlike the Bitcoin or Etherium network, where all nodes are equal, in the Hyperledger Fabric nodes play different roles:
- Peer can be endorsing peer (EP) and execute smart contracts.
- Committing peer (CP) - only save data on the blockchain and update the “World state”.
- Anchor Peer (AP) - if several organizations participate in the blockchain, then anchor peers are used to communicate between them. Each organization must have one or more anchor peers. With the help of AP, any peer in the organization can get information about all peers in other organizations. The gossip protocol is used to synchronize information between APs.
- Leader Peer - if the organization has several peers, then only the peer leader will receive blocks from the Ordering service and give them to the other peers. A leader can be either set statically or dynamically selected by peers in an organization. The gossip protocol is also used to synchronize leader information.
Assets are entities of value that are stored on the blockchain. More specifically, this is key-value data in JSON format. It is these data that are recorded in the Blockchain. They have a story that is stored on the blockchain and the current state, which is stored in the World state database. Data structures are filled randomly depending on business tasks. There are no required fields, the only recommendation is that assets should have an owner and be valuable.
Ledger - consists of the blockchain "Blockchain" and the database "Word state", which stores the current state of the assets. World state uses LevelDB or CouchDB.
Smart contract - using smart contracts, the business logic of the system is implemented. In Hyperledger Fabric, smart contracts are called chaincode. With the help of chaincode, assets and transactions over them are defined. Speaking in technical language, smart contracts are software modules implemented in the JS or Go programming languages.
Endorsement policy - for each chaincode, you can set how many policies and from whom you want to expect confirmations for the transaction. If the policy is not set, then by default it is used: “the transaction must be confirmed by any member of any organization in the channel”. Examples of policies:
- Any administrator of the organization must confirm the transaction;
- Any member or client of the organization must confirm;
- Must confirm any peer organization.
Ordering service - packs transactions into blocks and sends peers to the channel. Guarantees delivery of messages to all peers on the network. For industrial systems, the
Kafka message broker is used to develop and test
Solo .
Callflow
- Application interacts with Hyperledger Fabric using Go, Node.js or Java SDK;
- The client creates a tx transaction and sends it to endorsing peers;
- Peer verifies the client’s signature, completes the transaction, and sends the endorsement signature back to the client. Chaincode is executed only on the endorsing peer, and the result of its execution is sent to all peers. This algorithm of work is called - PBFT (Practical Byzantine Fault Tolerant) consensus. It differs from the classic BFT in that the message is sent and confirmation is not expected from all participants, but only from a specific set;
- After the client has received the number of responses corresponding to the endorsement policy, it sends the transaction to the Ordering service;
- Ordering service forms a block and sends it to all committing peers. Ordering service provides sequential writing of blocks, which excludes the so-called ledger fork ( see the "Forks" section );
- Peers receive a block, check the endorsement policy again, write the block to the blockchain, and change the state in the “World state” DB.
Those. it turns out the separation of roles between nodes. This provides scalability and blockchain security:
- Smart contracts (chaincode) perform endorsing peers. This ensures the confidentiality of smart contracts, as it is not stored by all participants, but only on endorsing peers.
- Ordering should work fast. This is ensured by the fact that Ordering only forms a block and sends it to a fixed set of leader peers.
- Committing peers only store the blockchain - there can be a lot of them and they do not require a lot of power and instant work.
For more information on Hyperledger Fabric's architectural solutions and why it works this way, you can look here:
Architecture Origins or here:
Hyperledger Fabric: A Distributed Operating System for Permissioned Blockchains .
So, Hyperledger Fabric is a truly universal system with which you can:
- Implement arbitrary business logic using the smart contract mechanism;
- Write and receive data from a blockchain database in JSON format;
- Provide and verify access to the API using Certificate Authority.
Now that we’ve figured out the specifics of the Hyperledger Fabric a bit, let's finally do something useful!
Expand Blockchain
Formulation of the problem
The task is to implement the Citcoin network with the following functions: create an account, get a balance, replenish an account, transfer coins from one account to another. We will draw an object model, which we will further implement in a smart contract. So, we will have accounts that are identified by names and contain a balance and a list of accounts. Accounts and a list of accounts are in terms of Hyperledger Fabric assets. Accordingly, they have a history and current status. I'll try to draw it clearly:
The upper figures are the current state, which is stored in the World state database. Below them are figures showing the story that is stored on the blockchain. The current state of assets is changed by transactions. Asset changes only in its entirety, therefore, as a result of the transaction, a new object is created, and the current value of the asset goes into history.
IBM Cloud
Create an account in
the IBM cloud . To use the blockchain platform, you need to upgrade it to Pay-As-You-Go. This process may not be fast, because IBM requests additional information and verifies it manually. From the positive, I can say that IBM has good training materials that allow you to deploy Hyperledger Fabric in their cloud. I liked the following series of articles and examples:
The following are screenshots of the IBM Blockchain platform. This is not an instruction for creating a blockchain, but simply a demonstration of the scope of the task. So, for our purposes, we make one Organization:
In it we create nodes: Orderer CA, Org1 CA, Orderer Peer:
We start users:
Create a Channel and call it citcoin:
In essence, Channel is a blockchain, so it starts with a zero block (Genesis block):
Writing a Smart Contract
'use strict'; const { Contract } = require('fabric-contract-api'); const maxAccounts = 5; class CitcoinEvents extends Contract { async instantiate(ctx) { console.info('instantiate'); let emptyList = []; await ctx.stub.putState('accounts', Buffer.from(JSON.stringify(emptyList))); }
Intuitively, everything should be clear here:
- There are several functions (AddAccount, GetAccounts, SendFrom, GetBalance, RefillBalance) that the demo program will call using the Hyperledger Fabric API.
- The SendFrom and RefillBalance functions generate events (Event) that the demo program will receive.
- Function instantiate - is called once at the instance of a smart contract. In fact, it is called not once, but every time a version of a smart contract is changed. Therefore, initializing a list with an empty array is a bad idea, because Now, when changing the version of a smart contract, we will lose the current list. But nothing, I'm just learning).
- Accounts and a list of accounts (accounts) are JSON data structures. For data manipulation, JS is used.
- You can get the current value of an asset by calling the getState function, and update it using putState.
- When creating an Account, the AddAccount function is called, in which a comparison is made for the maximum number of account in the blockchain (maxAccounts = 5). And there is a jamb (noticed?), Which leads to an infinite increase in the number of accounts. Such errors must be avoided)
Next, upload the smart contract to Channel and install it:
We look at the transaction for installing Smart Contract:
We look at the details of our Channel:
As a result, we get the following blockchain network diagram in the IBM cloud. Also on the diagram there is a demo program running in the Amazon cloud on a virtual server (it will be described in detail in the next section):
Creating a GUI for Hyperledger Fabric API Calls
Hyperledger Fabric has an API that can be used to:
- Creations channel;
- Peer connections to channel;
- Installation and installation of smart contracts in the channel;
- Transaction call;
- Request for information on the blockchain.
Application development
In our demo program, we will use the API only to invoke transactions and request information, because we have already taken the remaining steps using the IBM blockchain platform. We write a GUI using a standard technology stack: Express.js + Vue.js + Node.js. You can write a separate article on how to start creating modern web applications. Here I will leave a link to the lecture series that I liked the most:
Full Stack Web App using Vue.js & Express.js . The result is a client-server application with a familiar graphical interface in the style of Material Design from Google. The REST API between a client and a server consists of several calls:
- HyperledgerDemo / v1 / init - initialize the blockchain;
- HyperledgerDemo / v1 / accounts / list - get a list of all accounts
- HyperledgerDemo / v1 / account? Name = Bob & balance = 100 - create Bob account;
- HyperledgerDemo / v1 / info? Account = Bob - get information about Bob account;
- HyperledgerDemo / v1 / transaction? From = Bob & to = Alice & volume = 2 - transfer two coins from Bob to Alice;
- HyperledgerDemo / v1 / disconnect - close the connection to the blockchain.
I put the API description with examples on
the Postman website , a well-known program for testing the HTTP API.
Amazon Cloud Demo App
The application was uploaded to Amazon, because IBM has so far failed to upgrade my account and allow the creation of virtual servers. How the cherry attached the domain:
www.citcoin.info . I will keep the server turned on for a bit, then turn it off, because cents for rent are dripping, and citcoin coins are not yet quoted on the exchange) I place screenshots of a demo in the article so that the logic of work is clear. Demo application can:
- Initialize the blockchain;
- Create an Account (but now do not create a new Account, because the maximum number of accounts prescribed in the smart contract has been reached in the blockchain);
- Get a list of Accounts;
- Transfer citcoin coins between Alice, Bob and Alex;
- Receive events (but now there is no way to show events, therefore, for simplicity, the interface says that events are not supported);
- Log actions.
First, initialize the blockchain:
Next, start your account, do not trifle with balance:
We get a list of all available accounts:
We select the sender and the recipient, we get their balances. If the sender and the recipient are the same, then their account will be replenished:
In the log, we monitor the execution of transactions:
Actually, with a demo program, that's all. Next, you can see our transaction in the blockchain:
And a general list of transactions:
With this, we successfully completed the implementation of PoC to create the Citcoin network. What else needs to be done for Citcoin to become a full-fledged coin transfer network? Very little:
- At the stage of creating an account, implement the generation of a private / public key. The private key must be stored by the user account, public in the blockchain.
- Make a coin transfer in which a public key is used to identify the user, not a name.
- Encrypt transactions going from the user to the server with his private key.
Conclusion
We have implemented a Citcoin network with functions: add an account, get a balance, replenish your account, transfer coins from one account to another. So, what did it cost us to build PoC?
- We need to study blockchain in general and Hyperledger Fabric in particular;
- Learn to use the IBM or Amazon clouds;
- Learn the JS programming language and some web framework;
- If some data needs to be stored not in the blockchain, but in a separate database, then learn how to integrate, for example, with PostgreSQL;
- And last but not least - without knowledge of Linux in the modern world, nowhere!)
Of course, not rocket science, but you have to sweat!
GitHub sources
He put the source code on
GitHub . A brief description of the repository:
Directory "
server " - Node.js server
Directory "
client " - Node.js client
The "
blockchain " directory (parameter values ​​and keys, of course, are inoperative and are given only as an example):
- contract - source of the smart contract
- wallet - user keys for using the Hyperledger Fabric API.
- * .cds - compiled versions of smart contracts
- * .json files - example configuration files for using the Hyperledger Fabric API
It's only the beginning!