Develop your first blockchain application with hyperledger fabric


Original address:

By topjohn

Develop your first blockchain application with hyperledger fabric

The sample of this article comes fromfabric-samplesMediumfabcar…

In this example, we use a simple sample program to understand how fabric applications work. The applications and smart contracts (chain codes) used in this example are collectively referred to asFabCar。 This example provides a good starting point for understandingHyperledger Fabric。 Here, you will learn how to develop an application and smart contract to query and update account books, and how to useCATo generate the X.509 certificate needed by an application to interact with the blockchain.

We use the application SDK to query and update the ledger in the smart contract, which is implemented in the smart contract with the help of the underlying interface.

We will explain it in three steps:

  1. Build development environment。 Our applications need to interact with the network, so we need a base network for smart contracts and applications.

Develop your first blockchain application with hyperledger fabric

  1. Learn a simple smart contract, fabcar。 We useJavaScriptDevelop smart contracts. We learn how applications use smart contracts to send transactions and use smart contracts to query and update ledgers by looking at smart contracts.
  2. Developing a simple application with fabcar。 Our application will useFabCarSmart contract to query and update the car assets in the account book. We will go into the code of the application to learn how to create a transaction, including querying the information of a car, querying the information of a batch of cars and creating a car.

Set up blockchain network

Note: the following sections need to enter the localfabric-samplesWarehousefirst-networkSubdirectory.

If you’ve learned Building Your First Network, you should have downloadedfabric-samplesAnd a network is running. Before you start this tutorial, you need to stop this network:

./ down

If you’ve run this tutorial before, use the following command to turn off all stopped or running containers. Note that this will turn offAllWhether or not related to fabric.

docker rm -f $(docker ps -aq)
docker rmi -f $(docker images | grep fabcar | awk '{print $3}')

If you do not have the development environment and components related to this network and application, please visit the prerequisites page to ensure that your machine has the necessary dependencies installed.

Next, if you haven’t already done so, please browse the install samples, binaries and docker images page and follow the above steps. When you clonefabric-samplesWarehouse, download the latest stable version of fabric image and related tools and return to the tutorial.

If you are using Mac OS and mojava, you need to install Xcode.

Start up network

The following sections need to be enteredfabric-samplesWarehousefabcarSubdirectory.

UsestartFabric.shTo start your network. This command will start a blockchain network, which is composed of peer node, sorting node, Certificate Authorization Service, etc. It will also install and initialize the JavaScript version of theFabCarSmart contract, through which our application will operate the ledger. We will learn more about these components in this tutorial.

./ javascript

Now we have a sample network running, installed and initializedFabCarSmart contracts. In order to run our application, we need to install some dependencies, and let’s see how they work.

Install application

Note: the next section needs to go to the localfabric-samplesWarehousefabcar/javascriptSubdirectory.
The following command installs fabric related dependencies required by the application. It will take about 1 minute:

npm install

This instruction is used to install the dependencies required by the application, which are defined in thepackage.jsonMedium. The most important one isfabric-networkClass; it allows applications to use identities, wallets, and gateways to connect to channels, as well as submit transactions and wait for notifications. This tutorial will also usefabric-ca-clientClass to register users and their authorization certificates to generate afabric-networkThe legal identity used.

oncenpm installExecution is successful and everything you need to run the application is ready. In this tutorial, you will mainly usefabcar/javascriptDirectory to operate the application. Let’s take a look at the documents:


You will see the following documents:

enrollAdmin.js  node_modules       package.json  registerUser.js
invoke.js       package-lock.json  query.js      wallet

There are also some other programming language files, such asfabcar/typescriptDirectory. When you’ve used JavaScript samples – they’re all similar.

If you’re using Mac OS and running mojava, you need to[install Xcode] ( HTML)

Register administrator user

The following section deals with the process of communicating with the CA server. When you execute the following program, open a terminal to executedocker logs -f ca.example.comIt will be very helpful to check the log of ca.

When we create a network, aadminThe user for has been created by the authorization server (CA) asRegistrar。 Our first step is to useenroll.jsProcedure foradminGenerate private key, public key and X.509 certificate. This program uses a certificate signing request (CSR) – first generates the private key and public key locally, and then sends the public key to the Ca, which will issue a certificate used by the application. These three credentials will be saved in the wallet so that we can use the CA as an administrator.

Next, we will register and register a new application user, and we will use this user to interact with the blockchain through the application.

Let’s register oneadminUser:

node enrollAdmin.js

This command saves the CA administrator certificate in thewalletCatalog.

Registration and registrationuser1

Now we have the administrator’s certificate in our wallet. We can register a new user – user1 – to query and update the account book with this user:

node registerUser.js

Similar to the registration administrator, this program uses CSR to registeruser1And save its certificate toadminIn your wallet. Now we have two independent users–adminanduser1–They will all be used in our applications.

Next is the ledger interaction time

Inquiring account book

Each node in the blockchain network has a copy of the ledger. The application program can query the ledger by executing the latest ease on the smart contract query ledger, and return the results to the application program.

This is a simple description of how to query:

The application uses queries to read data from the ledger. The most common is to query the latest value in the current account book – World status. A world state is a collection of key value pairs that an application can query for data based on one or more keys. Moreover, when key value pairs exist in the form of JSON, world state can be configured to use databases (such as CouchDB) to support rich queries. This feature is useful for querying values that match specific keys, such as all cars of a person.

First, let’s usequery.jsProgram to find all the cars in the ledger. This program uses our second identity–user1–To operate the ledger.

node query.js

The output results are as follows:

Wallet path: ...fabric-samples/fabcar/javascript/wallet
Transaction has been evaluated, result is:
[{"Key":"CAR0", "Record":{"colour":"blue","make":"Toyota","model":"Prius","owner":"Tomoko"}},
{"Key":"CAR1", "Record":{"colour":"red","make":"Ford","model":"Mustang","owner":"Brad"}},
{"Key":"CAR2", "Record":{"colour":"green","make":"Hyundai","model":"Tucson","owner":"Jin Soo"}},
{"Key":"CAR3", "Record":{"colour":"yellow","make":"Volkswagen","model":"Passat","owner":"Max"}},
{"Key":"CAR4", "Record":{"colour":"black","make":"Tesla","model":"S","owner":"Adriana"}},
{"Key":"CAR5", "Record":{"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}},
{"Key":"CAR6", "Record":{"colour":"white","make":"Chery","model":"S22L","owner":"Aarav"}},
{"Key":"CAR7", "Record":{"colour":"violet","make":"Fiat","model":"Punto","owner":"Pari"}},
{"Key":"CAR8", "Record":{"colour":"indigo","make":"Tata","model":"Nano","owner":"Valeria"}},
{"Key":"CAR9", "Record":{"colour":"brown","make":"Holden","model":"Barina","owner":"Shotaro"}}]

Let’s take a closer look at the program. Open with a text editor such as atom or visual studioquery.js

From the beginning of the applicationfabric-networkModule introduces two key classesFileSystemWalletandGateway。 These two classes will be used to locate the walletuser1And use this identity to connect to the network:

const { FileSystemWallet, Gateway } = require('fabric-network');

The application uses a gateway to connect to the network:

const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: 'user1' });

This code creates a new gateway through which applications connect to the network.cppDescribes the gateway passing throughwalletMediumuser1To connect to the network. open../../basic-network/connection.jsonCheck it out.cppHow to parse a JSON file:

const ccpPath = path.resolve(__dirname, '..', '..', 'basic-network', 'connection.json');
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);

If you want to learn more about the structure of the connection profile and how it defines the network, please refer to the connection profile topic

A network can be divided into many channels. The next important thing in the code is to connect the application to a specific channelmychannelUpper:

In this passage, we can passfabcarSmart contracts to interact with ledgers:

const contract = network.getContract('fabcar');

stayfabcarThere are many different transactions in, our application uses firstqueryAllCarsTransactions to query the world status of the ledger:

const result = await contract.evaluateTransaction('queryAllCars');

evaluateTransactionMethod presents the simplest way to interact with smart contracts in blockchain networks. It simply connects a node according to the definition in the configuration file, then sends a request to the node, and executes the request within the node. The smart contract queries all the cars on the node ledger and returns the results to the application. This interaction did not update the ledger.

Fabcar smart contract

Let’s have a lookFabCarTransactions in smart contracts. Get intofabric-samplesSubdirectories underchaincode/fabcar/javascript/lib, and open it with your editorfabcar.js

Let’s see how our smart contract passesContractClass to define:

class FabCar extends Contract {...

In this class structure, you will see the following transactions defined:initLedgerqueryCarqueryAllCarscreateCarandchangeCarOwner。 For example:

async queryCar(ctx, carNumber) {...}
async queryAllCars(ctx) {...}

Let’s take a closer look at queryallcars and see how it interacts with the ledger.

async queryAllCars(ctx) {

  const startKey = 'CAR0';
  const endKey = 'CAR999';

  const iterator = await ctx.stub.getStateByRange(startKey, endKey);

This code defines the range of cars that queryallcars will get from the ledger. Each car from car0 to car999 — 1000 cars in total, assuming that each key is properly anchored — will be returned as a query result. The rest of the code iterates to package the query results into JSON and return it to the application.

The following shows how the application invokes different transactions in the smart contract. Each transaction uses a set of APIs such as getstatebyrange to interact with the ledger. Read more about the API in detail.

Develop your first blockchain application with hyperledger fabric

You can see ourqueryAllCarsTrade, another one calledcreateCar。 We’ll use them later in the tutorial to update the ledger and add new blocks.

But before that, back toqueryProgram, changingevaluateTransactionTo query forCAR4queryThe procedure is now as follows:

const result = await contract.evaluateTransaction('queryCar', 'CAR4');

Save the program and return tofabcar/javascriptCatalog. Now, run it againqueryProcedure:

node query.js

You should see the following:

Wallet path: ...fabric-samples/fabcar/javascript/wallet
Transaction has been evaluated, result is:

If you look beforequeryAllCarsYou’ll seeCAR4yesAdrianaOfBlack Tesla Model SThat is, the result returned here is the same.

We can usequeryCarTransaction to query any car, using its key (for exampleCAR0)Get information about the manufacturer, model, color and owner of the vehicle.

Very nice. Now you should have understood the basic query transaction in the smart contract and manually modified the parameters in the query program.

It’s time to update the books.

Update account book

Now that we have completed some account book query operations and added some codes, we are ready to update the account book. There are a lot of update operations we can do, but we start by creating a new car.

From an application perspective, updating a ledger is simple. The application submits a transaction to the blockchain network. When the transaction is verified and submitted, the application will receive a successful transaction reminder. But at the bottom, different consensus programs in each component of the blockchain network work together to ensure that every update proposal of the ledger is legal and has a consensus order.

Develop your first blockchain application with hyperledger fabric

In the figure above, we can see the main components to do this. At the same time, each node in multiple nodes has a copy of the ledger, and optionally a copy of the smart contract. There is also a sorting service in the network. The sorting service ensures the consistency of transactions in the network; it will also connect transactions of different applications in the network to generate blocks in a defined order.

Our first update to the ledger was to create a new car. We have a separate program calledinvoke.jsTo update the ledger. As with query, use an editor to open the program and locate the code segment where we build and submit the transaction to the network:

await contract.submitTransaction('createCar', 'CAR12', 'Honda', 'Accord', 'Black', 'Tom');

Take a look at how an application calls transactions for smart contractscreateCarTo create a black honda accord car with Tom as its owner. We useCAR12As a key here, it also means that we don’t have to use consecutive keys.

Save and run the program:

node invoke.js

If the execution is successful, you will see similar output:

Wallet path: ...fabric-samples/fabcar/javascript/wallet
2018-12-11T14:11:40.935Z - info: [TransactionEventHandler]: _strategySuccess: strategy success for transaction "9076cd4279a71ecf99665aed0ed3590a25bba040fa6b4dd6d010f42bb26ff5d1"
Transaction has been submitted

Be carefulinovkeThe program usessubmitTransactionAPI and blockchain network interact, notevaluateTransaction

await contract.submitTransaction('createCar', 'CAR12', 'Honda', 'Accord', 'Black', 'Tom');

submitTransactionthanevaluateTransactionIt’s a lot more complicated. Instead of just interacting with a single node, the SDK willsubmitTransactionThe proposal is sent to the nodes of every necessary organization in the blockchain network. Each node will execute the requested smart contract according to the proposal, generate a transaction response signed by the node and return it to the SDK. The SDK collects all signed transaction responses into a transaction, which will be sent to the sorting node. The sorting node collects and sorts the transactions of each application, and puts these transactions into a transaction block. Then the sorting node distributes these blocks to the nodes in the network, and each transaction will be verified and submitted in the node. Finally, the SDK will follow the reminder and return control to the application.

submitTransactionA monitor will also be included to ensure that transactions have been verified and submitted to the ledger. Applications need to use listeners orsubmitTransactionInterface, which has implemented the listener internally. If you don’t have a listener, you may not be able to determine whether the transaction has been sorted, verified, and submitted.

These tasks in the application are performed bysubmitTransactionFinish! Applications, smart contracts, nodes, and sorting services work together to ensure ledger consistency in the network.

To view the transactions written to the ledger, return to thequery.jsAnd parametersCAR4Change toCAR12

In other words, we will:

const result = await contract.evaluateTransaction('queryCar', 'CAR4');

Changed to:

const result = await contract.evaluateTransaction('queryCar', 'CAR12');

Save again and query:

node query.js

Will return:

Wallet path: ...fabric-samples/fabcar/javascript/wallet
Transaction has been evaluated, result is:

Congratulations. You create a car and verify that it’s on the ledger!

Now that we’ve finished, let’s assume Tom is generous and wants to give his Honda Accord to a man named Dave.

To do this, go back toinvoke.jsThen, using the input parameters, the transaction of smart contract is transferred fromcreateCarChange tochangeCarOwner

await contract.submitTransaction('changeCarOwner', 'CAR12', 'Dave');

First parameter—CAR12—A car that is about to change ownership. Second parameter—Dave—Indicates the new owner of the car.

Save and execute the program again:

node invoke.js

Now let’s check the ledger again to make sure Dave andCAR12The key is already associated:

node query.js

The following results will be returned:

Wallet path: ...fabric-samples/fabcar/javascript/wallet
Transaction has been evaluated, result is:

CAR12Our owner has changed from Tom to Dave.

In practical application, smart contract has authority control logic. For example, only authorized users can create a new car, and only the owner of the car can transfer the ownership of the car.


Now that we have finished the query and update of the ledger, you should also have a better understanding of how to query and update the ledger through the interaction between the smart contract and the blockchain. In the tutorial, I have explained the smart contract, API and SDK of query and update. I think you have some understanding of other business scenarios.

adoptFabCarIn this example, we can quickly learn how to use theNode SDKDevelop applications.