Hyperledger Fabric — Seashell Supplychain System II

0
49

Hyperledger Fabric — Seashell Supplychain System II

Now that we understand the fundamentals of blockchain and the high level structure of Hyperledger let’s use this knowledge to tackle a real world scenario.

Problem Context:

Our goal is to eliminate illegal, unreported, and unregulated seashell mining. We will use Hyperledger Fabric to bring transparency and clarity to a real-world example: the supply chain of seashells mining.

We will be describing how seashell mining can be improved, starting from the source, worker Sam, and the process by which his seashells ends up at Mira’s shop. In between, we’ll have other parties involved, such as the regulator who verify the validity of the data and the sustainability of the seashell catches.

We will be using Hyperledger Fabric’s framework to keep track of each part of this process.

Two things to keep in mind:

  1. There are many actors within the network, and you will see how these actors interact, and how a transaction is conducted.
  2. Private channels allow Sam and Mira to privately agree on the terms of their interaction, while still maintaining transparency, so other actors can corroborate and confirm their transaction.

Using private channels, regulators and shopkeepers can confirm whether a particular shipment of seashells was sustainably and legally sourced, without needing to see the details of the entire journey.

Stakeholders

  • Sam is the worker who sustainably and legally fetches seashells.
  • Regulators verify that the seashells have been legally and sustainably caught.
  • Mira is a shop owner who will serve as the end user, in this situation.
  • Carl is another shop owner , worker Sam can sell seashells to.

Summary of the Problem Architecture:

Below is a summary of the seashell fetch scenario presented in this section:

  1. Sam fetches a seashell and uses the supply chain application’s user interface to record all the details about the fetch to the ledger. Before it reaches the ledger, the transaction is passed to the endorsing peers on the network, where it is then endorsed. The endorsed transaction is sent to the ordering service, to be ordered into a block. This block is then sent to the committing peers in the network, where it is committed after being validated.
  2. As the seashell is passed along the supply chain, regulators may use their own application to query the ledger for details about specific catches (excluding price, since they do not have access to the price-related chaincode)
  3. Sam may enter into an agreement with a shopkeeper Carl, and agree on a price of $80 per pound. They use the blue channel for the chaincode contract stipulating $80/lb. The blue channel’s ledger is updated with a block containing this transaction.
  4. In a separate business agreement, Sam and Mira agree on a special price of $50 per pound. They use the red channel’s chaincode contract stipulating $50/lb. The red channel’s ledger is updated with a block containing this transaction.

The first step in implementing the solution to fix the seashell supplychain is setting up the technical environment and this is the first step to that. Installing Hyperledger Fabric and making sure the network is up and running.

Installing Hyperledger Fabric

Determine a location on your machine where you want to place the Hyperledger Fabric samples applications repository and open that in a terminal window. Then, execute the following commands:

git clone -b master https://github.com/sakshm-aurora/fabric-samples.git
cd fabric-samples
git checkout {TAG}

Note - To ensure the samples are compatible with the version of Fabric binaries you download below, checkout the samples {TAG} that matches your Fabric version, for example, v1.1.0. To see a list of all fabric-samples tags, use command “git tag”.

Download Platform-specific Binaries

Next, we will install the Hyperledger Fabric platform-specific binaries. This process was designed to complement the Hyperledger Fabric Samples above, but can be used independently. If you are not installing the samples above, then simply create and enter a directory into which to extract the contents of the platform-specific binaries.

Please execute the following command from within the directory into which you will extract the platform-specific binaries:

curl -sSL https://goo.gl/6wtTN5 | bash -s 1.1.0

The command above downloads and executes a bash script that will download and extract all of the platform-specific binaries you will need to set up your network and place them into the cloned repo you created above. It retrieves four platform-specific binaries:

  • cryptogen,
  • configtxgen,
  • configtxlator,
  • peer
  • orderer and
  • fabric-ca-client

and places them in the bin sub-directory of the current working directory.

You may want to add that to your PATH environment variable so that these can be picked up without fully qualifying the path to each binary. e.g.:

export PATH=<path to download location>/bin:$PATH

Test:

docker images
Expected Output

Starting a Test Hyperledger Fabric Network

Now that we have successfully installed Hyperledger Fabric, we can walk through setting up a simple network that has two members. To refer back to our demonstrated scenario, the network includes asset management of each seashell verified, transferred, and purchased between Sam, the worker, and Mira, the restaurateur. We’ll create a simple two member network consisting of two organizations (effectively, Sam and Mira), each maintaining two peers and an ordering service.

We will use Docker images to bootstrap our first Hyperledger Fabric network. It will also launch a container to run a scripted execution that will join peers to a channel, deploy, and instantiate the chaincode, and execute transactions against the chaincode.

cd first-network
./byfn.sh -m generate

A brief description will appear, along with a Y/N command line prompt. Respond with a Y <Enter> to continue.

This step generates all of the certificates and keys for all our various network entities, including the genesis block used to bootstrap the ordering service and a collection of configuration transactions required to create a channel.

Next, you can start the network with the following command:

./byfn.sh -m up

Another command line will appear, reply with Y <Enter> to continue.Finally, let’s test bringing down this network.Within the same terminal, do Control+C to exit the current execution.Then, run the following command:

./byfn.sh -m down

Another command line will appear, reply with Y <Enter> to continue.This command will kill your containers, remove the crypto material and four artifacts, and delete the chaincode images from your Docker Registry.

The above process is illustrated in the following GIF :

byfn.sh

Chaincode

In Hyperledger Fabric, chaincode is the ‘smart contract’ that runs on the peers and creates transactions. More broadly, it enables users to create transactions in the Hyperledger Fabric network’s shared ledger and update the world state of the assets.

There are two ways to develop smart contracts with Hyperledger Fabric:

  • Code individual contracts into standalone instances of chaincode
  • Use chaincode to create decentralized applications that manage the lifecycle of one or multiple types of business contracts, and let the end users instantiate instances of contracts within these applications. [More Efficient]

Overview of a Chaincode Program

When creating a chaincode, there are two methods that you will need to implement:

  • Init
    Called when a chaincode receives an instantiate or upgrade transaction. This is where you will initialize any application state.
  • Invoke
    Called when the invoke transaction is received to process any transaction proposals.

As a developer, one must create both an Init and an Invoke method within your chaincode. The chaincode must be installed using the peer chaincode install command, and instantiated using the peer chaincode instantiate command before the chaincode can be invoked. Then, transactions can be created using the peer chaincode invoke or peer chaincode query commands.

How can I see the chaincode logs?

You can inspect the individual chaincode containers to see the separate transactions executed against each container. Use the following command to find the list of running containers to find your chaincode containers:

$ docker ps -a

Understanding the Docker Compose Topology

The BYFN sample offers us two flavors of Docker Compose files, both of which are extended from the docker-compose-base.yaml (located in the base folder). Our first flavor, docker-compose-cli.yaml, provides us with a CLI container, along with an orderer, four peers. We use this file for the entirety of the instructions on this page.

The second flavor, docker-compose-e2e.yaml, is constructed to run end-to-end tests using the Node.js SDK. Aside from functioning with the SDK, its primary differentiation is that there are containers for the fabric-ca servers. As a result, we are able to send REST calls to the organizational CAs for user registration and enrollment.

Why CouchDB

CouchDB is a kind of NoSQL solution. It is a document-oriented database where document fields are stored as key-value maps. Fields can be either a simple key-value pair, list, or map. In addition to keyed/composite-key/key-range queries which are supported by LevelDB, CouchDB also supports full data rich queries capability, such as non-key queries against the whole blockchain data, since its data content is stored in JSON format and fully queryable. Therefore, CouchDB can meet chaincode, auditing, reporting requirements for many use cases that not supported by LevelDB.

We’ll be building on the tuna fishing supplychain system to then build our seashell suppychain system on it , following is the code for the same.

https://github.com/hyperledger/education/blob/master/LFS171x/fabric-material/chaincode/tuna-app/tuna-chaincode.go

Fabric Node.js SDK

Now ,we will be using the Node.js SDK (https://fabric-sdk-node.github.io/) to interact with the network, and, therefore, the ledger. The Hyperledger Fabric Client SDK makes it easy to use APIs to interact with a Hyperledger Fabric blockchain. This section will help you write your first application, starting with a test Hyperledger Fabric network, then learning the parameters of the sample smart contract, and lastly, developing the application to query and update ledger records.

For additional information, visit the Hyperledger Fabric Node SDK documentation: https://fabric-sdk-node.github.io/tutorial-app-dev-env-setup.html.

BlockChain Application

Be sure that you have the technical dependencies sorted out before you try to run this blockchain application.

This will be a two-part series on hyperledger, the framework to create, deploy, and maintain…

Step 1: Clone the repo

git clone https://github.com/sakshm-aurora/education.git
cd education/LFS171x/fabric-material/tuna-app

Make sure you have Docker running on your machine before you run the next command.Also, make sure that you have completed the Installing Hyperledger Fabric.

First, remove any pre-existing containers, as it may conflict with commands in this tutorial:

docker rm -f $(docker ps -aq)

Step 2: Start Fabric Network

Next, let’s start the Hyperledger Fabric network with the following command:

./startFabric.sh

Let’s break down what’s happening when you run this command in your terminal.

  1. Existing Network Artifacts are removed from Docker and just one organisation with a peer & couch DB is created along with an orderer.

As you can see in the code, the startfabric.Sh internally calls start.sh within basic-network folder.

Now, if you traverse to start.sh , you can see how the docker container is cleared and re-populated. Also, a channel is created and a peer is added.

Step 3: RegisterAdmin

Cool. Now that the network is up. Let’s registerAdmin.

node registerAdmin.js

You should get this output, basically an Admin is created with the required keys. You can open up registerAdmin.js to see the code. Basically, withe the Fabric CA client we check if an Admin is already registered, if not it enrolls with the CA client. Basic parameters such as enrollmentID, Secret are set. Then the user is created with FabricClient with membership ID, along with the public private key pair.

Step 4: RegisterUser

Now that the network and admin are set, let’s register an User.

node registerUser.js

If you open up registerUser.js, you can see that we register user with the CA server and then enroll.

Step 5: Run the server

This step is the final step to run the application. For that we gotta setup the nodejs server, call the needed packages, instantiate the app and listen on a particular port.

node server.js

BOOM..our applcation is live on port 8000

The UI has a button under 4 headings.

Query All Seashell Catches — triggers — queryAllTuna.js

Query Specific Seashells— triggers — queryTuna.js

Create Seashell Record — triggers — recordTuna.js

Change Seashell Holder — triggers — changeTunaHolder.js

All these js files are inturn defined within the chaincode tuna-chaincode.go

Note — As mentioned before the seashell application is built on Tuna Fishing Applicaion and hence uses the same scripts.

Output

  1. Query All Seashells — All the data we used in the chaincode to initLedger is pulled and shown here.

2. Query Seashell — Here we are sending a query to look for the record with the catch number 6.

3. Log a Seashell Catch — Here we’re creating a new record.

4. Change the Owner of Seashell — Here we send a POST request to query record with catch ID 12 and modify the name of holder to “Saksham”.

And hence we come to the end of our two part series.

Read Part 1 at :

https://medium.com/@saksham.aurora/this-will-be-a-two-part-series-on-hyperledger-the-framework-to-create-deploy-and-maintain-936ac2236c2f

References :

A lot of illustrations and content have been taken from the following blogs , all credits to them :


Hyperledger Fabric — Seashell Supplychain System II was originally published in Coinmonks on Medium, where people are continuing the conversation by highlighting and responding to this story.