preface

This tutorial is basically a translation of project Marbles. If your English is good, you are advised to deploy the environment step by step according to the official operation instructions. You can also use this tutorial to deploy the project on your own host.

Marbles is introduced

About the Marbles

  • The underlying network for this application isHyperledger FabricThe latter is oneLinux FoundationThe project. You may want to consult the following instructions to get a sense of itHyperledger Fabric
  • This demo is intended to help developers understand the basics of chained code and how to develop applications using a Fabric network
  • This is a very simple asset transfer demo. Multiple users can create and transfer marbles to each other.

version

All versions of marbles exist simultaneously. This version is compatible with Hyperledger Fabric V1.1x. You can get different versions of MARBLE by checking out other branches, using ae4E37D in this example

Application Background

Keep your eyes on this application that demonstrates how Hyperledger Fabric can be used to transfer marbles between many pinball owners. We’ll do this using some GoLang code in Node.js. The back-end of the application will be GoLang code running on our blockchain network. From now on, these GoLang codes will be called “chain codes” or “CC”. The chain code itself creates a marble, which is stored in the chain code state. The chain code itself can store data as strings in key/value pair Settings. Therefore, we stringed the JSON object to store a more complex structure.

The attributes of marbles include:

  • ID (unique string that will be used as a key)
  • Color (string, CSS color name)
  • Dimensions (int, in mm)
  • Owner (string)

We will create a user interface that can set these values and store them in the ledger of the blockchain. A marble is actually a key-value pair. The key is the marble ID and the value is a JSON string containing the attributes of the marbles listed above. The interaction with CC is done by using the gRPC protocol on a peer node on the network. The details of the gRPC protocol are handled by an SDK called Hyperledger Fabric Client SDK. See the following figure for topology details.

Application communication flow

  • 1. Administrators will interact with our Node.js application Marbles in their browsers
  • 2. This client-side JS code will open a Websocket connection to the back-end Node.js application, and the client-side JS will send messages to the backend when the administrator interacts with the site
  • 3. Reading or writing to the ledger is called a proposal, which is built by Marbles (via the SDK) and then sent to a blockchain peer.
  • 4. The peer will communicate with its Marbles chain code container. The chain code container will run/simulate the transaction. If there are no problems, it endorses the deal and sends it back to our Marbles process.
  • 5. Marbles then sends the endorsed proposal to the subscription service (via the SDK). Subscribers package many proposals from across the network into one block. It then broadcasts the new block to its peers in the network
  • 6. Finally, the peer verifies the block and writes it to its own ledger, the transaction is now in effect, and all subsequent reads reflect the change.

Marbles Project environment configuration

A local Hyperledger Fabric network is used to deploy the project. If you want to use IBM Cloud IBM Blockchain Services to deploy the project, please refer to the official documentation provided in the introduction.

  • Note: The system environment used in this tutorial is:ubuntu16.04

Set up the Chaincode development environment

If you’ve already set up a Hyperledger Fabric network from my last blog post based on ubuntu16.04, then all you need to do is install node.js If you have not set up a Hyperledger Fabric network on the local PC, you are advised to set up a Hyperledger Fabric network environment on the local PC.

Verifying the Git environment

Generally speaking, the Linux system comes with Git. If the system does not have Git installed, you can use the following command to install Git

$ sudo apt-get install git
Copy the code

Verify after installation

Git version 2.7.4Copy the code

Verifying the GO environment

The Go installation installs a set of Go CLI tools that are useful when writing link code. For example, the Go Build command allows you to check that the chain code is actually compiled before trying to deploy it to the network.

  • Verifying the Installation Environment
$Go Version Go Version GO1.10 Linux/AMD64 $echo $GOPATH
/home/ubuntu/go
Copy the code

Ubuntu is my username, which means that my GOPATH directory is the Go folder in my home directory. Of course, your GOPATH doesn’t need to match the one above. It’s just important, but you must set this variable to a valid directory on the file system.

Install node.js

You can run the node -v and NPM -v commands to check whether the Node.js environment exists in the system. If it is not installed, run the following commands to install it:

$ sudo apt-get install nodejs
$ sudo apt install nodejs-legacy
$ sudo apt install npm
Copy the code

After installation, run the node -v and NPM -v commands to view the version information:

$node -v v4.2.6 $NPM -v 3.5.2Copy the code

Unfortunately, node.js installed in this way is of a lower version and does not meet the environmental requirements of our project (Node :v6.10.1; NPM :3.10.10), in order to avoid problems caused by different software versions, we also need to upgrade the Node and NPM versions

  • Configure the NPM repository first. Because of the domestic network environment, it is very slow to install software packages directly from the official NPM source
$ npm install -g nrm
Copy the code
  • After the installation is complete, list the available software sources
$ nrm ls
* npm ---- https://registry.npmjs.org/
  cnpm --- http://r.cnpmjs.org/
  taobao - https://registry.npm.taobao.org/
  nj ----- https://registry.nodejitsu.com/
  rednpm - http://registry.mirror.cqupt.edu.cn/
  npmMirror  https://skimdb.npmjs.com/registry/
  edunpm - http://registry.enpmjs.org/
Copy the code
  • You can switch to the source of Taobao, the speed is still very fast in China
$ nrm use taobao
Registry has been set to: https://registry.npm.taobao.org/
Copy the code
  • Install the Node version management tool n
$ npm install -g n
Copy the code
  • Use n to install the specified version
$n 6.10.1Copy the code
  • Run the node -v command again to view the current version
V6.10.1 $node - vCopy the code
  • Upgrade the NPM version number
$NPM install -g [email protected]Copy the code
  • Run the NPM -v command again to view the current version
3.10.10 $NPM - vCopy the code

At this point, the Node.js environment is complete

Hyperledger Fabric version switchover

The official document provides three options. One is that you do not want to modify the chain code. The following operations are unnecessary. Those who want to change the chain code themselves and want to use the latest version of Fabric can switch to the latest branch. Although this project is compatible with Hyperledger Fabric V1.1x, it is recommended to switch to the version ae4E37D used in the document to avoid unknown errors. The command for switching steps is as follows

  • Match this version to the submission hash of the network/Fabric (the first 7 characters will matter)
$ cd $GOPATH/src/github.com/hyperledger/fabric
$ git checkout ae4e37d
Copy the code

If configured as I did in my last blog, $GOPATH uses both the go folder in the user’s home directory,

  • Verify levels using git branches. It should display the submission level that matches the one you provide
$git branch * (HEAD detached at AE4e37d) release-1.1Copy the code

The ae4E37D branch is displayed. The latest version is 1.1. If you want to know more about the AE4E37D branch, run the following command:

$ git log -p
commit ae4e37dbafe74997534ab317dec5c3f4f53b6a84
Author: Gari Singh <[email protected]>
Date:   Mon Aug 7 17:50:39 2017 -0400

    FAB-5652 Prepare fabric for1.0.2 release-base version = 1.0.2 -prev version = 1.0.1 -is_release =false
    
    Change-Id: Ibce2a81193b09015eef896391b0e8166d40e7102
    Signed-off-by: Gari Singh <[email protected]>

diff --git a/Makefile b/Makefile
index d1febaa..ffe51f3 100755
--- a/Makefile
+++ b/Makefile
@@ -36,9 +36,9 @@
 # - unit-test-clean - cleans unit test state (particularly from docker)
 
 PROJECT_NAME   = hyperledger/fabric
Copy the code

As you can see from the command output above, this branch is based on version 1.0.2. After switching to the branch, you also need to verify the structure installation

  • Open a command prompt/terminal and enter a command
$ cd $GOPATH/src/github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02
$ go build --tags nopkcs11 ./
Copy the code

It should return no errors/warnings. You should also see an executable created in this directory. Note that the NOPKCS11 tag is important. PKCS 11 is a public key encryption standard that you are unlikely to use on your system. Remember to use this flag when developing/building chain codes. The official documentation recommends two Visual Studio Codes and Atom, and the specific IDE development environment configuration can be searched online.

Set up a local Hyperledger network

Here is the procedure for building a local Hyperledger network and then testing the network steps.

Download the Marbles project first

Marbles need to be downloaded to the local system. Let’s use Git to do this by cloning the repository. Even if you plan to host Marbles in the IBM Cloud, you need to do this by running the following command

$ cd ~
$ git clone https://github.com/IBM-Blockchain/marbles.git --depth 1
$ cd marbles
Copy the code

Note: I’ve cloned Marbles into the user’s home directory, so you can choose any directory that suits you

Download the official Hyperledger Fabric example

We will run the local network using the Hyperledger Fabric example. Their code has Fabric network Settings and link code examples. We will only use the network Settings section. Use the following command to download examples of their nodes:

$ git clone https://github.com/hyperledger/fabric-samples.git
$ cd fabric-samples
Copy the code

If you have not downloaded Docker images with various structures, you can use the following command to download them

$ curl -sSL: https://raw.githubusercontent.com/hyperledger/fabric/release-1.1/scripts/bootstrap-1.1.0-preview.sh - o setup_script.sh $ sudo bash setup_script.shCopy the code

Be sure to add these binaries to the PATH variable by running the following command or pasting them into your.profile file

  • Run the command
$ export PATH=$PWD/bin:$PATH
Copy the code
  • If you want to permanently add these binaries to the PATH variable, you can add them to the system environment variable
$ vim ~/.profile
Copy the code

Insert export PATH=/home/ Ubuntu /fabric-samples/bin:$PATH, where you can first use the PWD command to get the directory for your local fabric-samples and then put $PWD in the command above Finally, use :wq to save and exit, and run the following command to refresh

$ source  ~/.profile
Copy the code

Start the network

Next, we need to start Fabric. Run the script below to make everything happen

 $ cd ./fabcar
 $ sudo ./startFabric.sh
Copy the code

After a minute or two, the command prompt will return with the results shown below

Now run the docker ps command to view the docker container that is currently running. You should see something like the following:

CONTAINER ID        IMAGE                                   COMMAND                  CREATED             STATUS              PORTS                                            NAMES
01cdf948b39c        dev-peer0.org1.example.com-fabcar-1.0   "Chaincode - peer. Add..."2 minutes ago Up 2 minutes dev-peer0.org1.example.com- fabcar-1.02f79BAC1371e Hyperledger /fabric-tools"/bin/bash"              3 minutes ago       Up 3 minutes                                                         cli
648da0074a8d        hyperledger/fabric-peer                 "peer node start"3 minutes ago Up 3 minutes 0.0.0.0:7051->7051/ TCP, 0.0.0.0:7053-868 > 7053 / TCP peer0.org1.example.com e0f78f80e hyperledger/fabric - ca"Sh -c 'fabric - ca - se..."3 minutes ago Up 3 minutes 0.0.0.0:7054->7054/ TCP ca.example.com 4c385bb6aa9d Hyperledger/Fabric-couchdb"The observatory - / docker - ent..."3 minutes ago Up 3 minutes 4369/ TCP, 9100/ TCP, 0.0.0.0:5984->5984/ TCP couchdb 4b9a2b2b0718 Hyperledger /fabric-orderer"orderer"3 minutes ago Up 3 minutes 0.0.0.0:7050->7050/ TCP orderer.example.comCopy the code
  • If you don’t see all six containers running, something is wrong. You need to troubleshoot before continuing. I recommend entering a stopped container’s log sudo Docker logs Peer0 (replace peer0 with name W/e stopped).

  • If you see containerID already exists as a running Docker tool – component, then you need to remove the existing container. Docker rm -f $docker ps -aq

Install and instantiate the chain code

Good, we’re almost done! Now we need to run our Marbles chain code. Remember, the chain code is the key component that ultimately creates our Marbles transaction on the ledger. The chain code is GoLang code that needs to be installed on a peer node and then instantiated on a channel. This code has been written for you! We just have to run it

To prepare

We need some pinball dependencies to run the setup/instantiation script. Install Marbles NPM dependencies by returning the root of the Marbles directory and entering these commands:

$ cd ~/marbles
$ npm install
Copy the code

It is important that the installation does not return errors (warnings are good). If you have NPM installation errors, you must resolve and fix them before proceeding

Generate certificate and key files

This is a very important step! The installation and instantiation operations require an administrator certificate and a private key. If these files are not found, you will not be able to run any operations.

  • Step 1: Change the path to the fabric-samples/fabcar directory at terminal/command prompt:
$ cd ../fabric-samples/fabcar
Copy the code
  • Step 2: Run the command:
$ node enrollAdmin.js
 Store path:/home/ubuntu/fabric-samples/fabcar/hfc-key-store
Successfully enrolled admin user "admin"
Assigned the admin user to the fabric client ::{"name":"admin"."mspid":"Org1MSP"."roles":null,"affiliation":""."enrollmentSecret":""."enrollment": {"signingIdentity":"9b6f84a7672908c0629d9b3ad0bf23437d624089061e937af0b0476ec6dec81d"."identity": {"certificate":"-----BEGIN CERTIFICATE-----\nMIIB8DCCAZegAwIBAgIUeQVhK98LQFSz5Dz0bt3bB9Baom8wCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNh bGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5j b20wHhcNMTgwNTE1MTA1ODAwWhcNMTkwNTE1MTA1\nODAwWjAQMQ4wDAYDVQQDEwVhZG1pbjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA\nBPlS00VDvBQp smMFUGnNzEAQd7lgpTNgEDpzJGk4/xfBuechE8cfNH6WuibJtXxh\nsEQ4uLAlDcOAP1nfXq9oEtWjbDBqMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8E\n AjAAMB0GA1UdDgQWBBShJWerMoKEE2u+dn08UBkGs4tWzjArBgNVHSMEJDAigCBC\nOaoNzXba7ri6DNpwGFHRRQTTGq0bLd3brGpXNl5JfDAKBggqhkjOPQ QDAgNHADBE\nAiAmqy0J0M1aZlvuv6cDK8GjeMTMjN0V5dZIW/uBv+whtAIgCMbyQRtE+PDwsoSS\nG40hZ4UOoNS2tvIXHRglMMHvKjs=\n-----END CERTIFICATE-----\n"}}}
Copy the code
  • Step 3: Run the command:
$ node registerUser.js 
 Store path:/home/ubuntu/fabric-samples/fabcar/hfc-key-store
Successfully loaded admin from persistence
Successfully registered user1 - secret:PfPGkGQmNgfw
Successfully enrolled member user "user1" 
User1 was successfully registered and enrolled and is ready to intreact with the fabric network
Copy the code
  • Step 4: Double check that any key and certificate files are created in the folderfabric-samples/fabcar/hfc-key-store
  • Step 5: Next, we need to verify that the file path in the connection configuration file matches your installation.
    • Open your connection profile<marbles root>/config/connection_profile_local.json.
    • Find these three fields in the JSON:
      • organizations -> x-adminCert -> path
      • organizations -> x-adminKeyStore -> path
      • client -> credentialStore -> path
    • The value of PATH in each field needs to reflect your environment (your directory structure). You can browse through these folders and files to verify their existence.
    • You may need to place according to youfabric-samplesThe location of the directory and the location of the key store data to change these values. Once the path is valid, you can continue.
  • Step 6: You’re Done! Change the path to the springback root directory:cd ~/marblesProceed with the installation link code description below.

Install the chain code

Once done, we need to put the chain code into the file system of the peer node. Remember chaincode defines what marbles (assets) are the business logic for transactions in our system. You can find the

/chaincode/ SRC/in this directory. The files in this directory are chain code files.

We will use the script install_chaincode.js located in the scripts folder. It reads our pinball profile and connection profile data. You can change the project chaincode ID or version by editing the install_chaincode.js file. If you want to edit these files and want more information about their contents, open the configuration and Connection configuration file readme file below. If you have no problem with the default Settings, simply save these files separately and run the following command.

  • Configuration and Connection configuration file formats help install the pachinklink code file using the following command:
$ cd./scripts $ node install_chaincode.js ...... .Much of the output is omitted here. . --------------------------------------- info: Now we install --------------------------------------- debug: [fcw] Installing Chaincode debug: [fcw] Sending install req targets=[grpc.http2.keepalive_time=300, grpc.keepalive_time_ms=300000, grpc.http2.keepalive_timeout=35, grpc.keepalive_timeout_ms=3500, grpc.max_receive_message_length=-1, GRPC. Max_send_message_length = 1, GRPC. Primary_user_agent = GRPC - node / 1.10.1, _url = GRPC: / / localhost: 7051, addr=localhost:7051, , _request_timeout=90000, , _name=null], chaincodePath=marbles, chaincodeId=marbles, chaincodeVersion=v4 info: [packager/Golang.js]: packaging GOLANG from marbles debug: [fcw] Successfully obtained transaction endorsement --------------------------------------- info: Install done. Errors: nope ---------------------------------------Copy the code

If the preceding output is displayed, the chain code is successfully installed

Instantiate chain code

Next we need to instantiate the chain code. This causes your channel to launch the pinball chain code myChannel. Once completed, we are ready to record our system (Marbels) activity using the blockchain network. Use the following command to complete the instantiation:

$ node instantiate_chaincode.js ...... .Much of the output is omitted here. . --------------------------------------- info: Now we instantiate --------------------------------------- debug: [fcw] Instantiating Chaincode peer_urls=[grpc://localhost:7051], channel_id=mychannel, chaincode_id=marbles, chaincode_version=v4, cc_args=[12345], ssl-target-name-override=null, pem=null, grpc.http2.keepalive_time=300, grpc.keepalive_time_ms=300000, grpc.http2.keepalive_timeout=35, grpc.keepalive_timeout_ms=3500 debug: [fcw] Sending instantiate req targets=[grpc.http2.keepalive_time=300, grpc.keepalive_time_ms=300000, grpc.http2.keepalive_timeout=35, grpc.keepalive_timeout_ms=3500, grpc.max_receive_message_length=-1, GRPC. Max_send_message_length = 1, GRPC. Primary_user_agent = GRPC - node / 1.10.1, _url = GRPC: / / localhost: 7051, addr=localhost:7051, , _request_timeout=90000, , _name=null], chaincodeId=marbles, chaincodeVersion=v4, fcn=init, args=[12345], 0=214, 1=155, 2=127, 3=34, 4=197, 5=82, 6=208, 7=191, 8=141, 9=140, 10=57, 11=113, 12=46, 13=90, 14=76, 15=231, 16=170, 17=118, 18=197, 19=137, 20=186, 21=212, 22=64, 23=33, _transaction_id=d550ed194a2d798f2a6c2924c0302fdc6323fba2835e128f3dc541f1b6754525 debug: [fcw] Successfully obtained transaction endorsement debug: [fcw] Successfully ordered instantiate endorsement. --------------------------------------- info: Instantiate done. Errors: nope ---------------------------------------Copy the code

If the preceding output is displayed, the chain code is successfully instantiated

Running the Marble Project

With all of our environments configured, it’s time to run the project

Install dependencies

Open the command prompt/terminal and navigate to the Marbles directory and execute the following commands:

$ cd ~/marbles
$ sudo npm install gulp -g
$ sudo npm install
Copy the code

If you have NPM installation errors, you must resolve and fix them before proceeding

Run the project

Run the project using the following command:

$ gulp marbles_local ...... .Much of the output is omitted here. . ----------------------------------- Server Up - localhost:3001 ----------------------------------- Welcome aboard: United Marbles Channel: mychannel Org: Org1MSP CA: fabric-ca Orderer: fabric-orderer Peer: fabric-peer-org1 Chaincode ID: marbles Chaincode Version: v4 ------------------------------------------ Websocket Up ------------------------------------------ info: [fcw] Going to enroll peer_urls=[grpc://localhost:7051], channel_id=mychannel, uuid=marblesDockerComposeNetworkmychannelOrg1MSPfabricpeerorg1, ca_url=http://localhost:7054, orderer_url=grpc://localhost:7050, enroll_id=admin, enroll_secret=adminpw, msp_id=Org1MSP, kvs_path=/home/ubuntu/.hfc-key-store info: [fcw] Successfully loaded enrollment from persistence debug: added peer grpc://localhost:7051 debug: [fcw] Successfully got enrollment marblesDockerComposeNetworkmychannelOrg1MSPfabricpeerorg1 info: Success enrolling admin debug: Checkingif chaincode is already instantiated or not 1

info: Checking for chaincode...
debug: [fcw] Querying Chaincode: read()
debug: [fcw] Sending query req: chaincodeId=marbles, fcn=read, args=[selftest], txId=null
debug: [fcw] Peer Query Response - len: 5 type: number
debug: [fcw] Successful query transaction.

----------------------------- Chaincode found on channel "mychannel" -----------------------------


info: Checking chaincode and ui compatibility...
debug: [fcw] Querying Chaincode: read()
debug: [fcw] Sending query req: chaincodeId=marbles, fcn=read, args=[marbles_UI], txId= NULL WARN: [FCW] Warning-query RESp is not JSON, might be okay: string 4.0.1 debug: [fcw] Successful query transaction. info: Chaincode version is good info: Checking ledgerfor marble owners listed in the config file

info: Fetching EVERYTHING...
debug: [fcw] Querying Chaincode: read_everything()
debug: [fcw] Sending query req: chaincodeId=marbles, fcn=read_everything, args=[], txId=null
debug: [fcw] Peer Query Response - len: 30 type: object
debug: [fcw] Successful query transaction.
debug: This company has not registered marble owners
info: We need to make marble owners


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
info: Detected that we have NOT launched successfully yet
debug: Open your browser to http://localhost:3001 and login as "admin" to initiate startup
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Copy the code

If the above output is displayed, the project has started successfully. You can now access the project by typing http://localhost:3001 in your browser, and you do not need to enter a password or change the pre-filled user name admin.

Note: THE following error occurred when I used the gulp marbles_local command to start the project. This error may occur when you run the project:

Issues:208
bug
fabric-sdk-node
hfc-key-store
$HOME / .hfc-key-store
connection_profile_local.json
client.credentialStore.path

  • First thehfc-key-storeDirectories are copied to your home directory$HOME / .hfc-key-store:
$ cd ~/fabric-samples/fabcar
$ cp -r hfc-key-store  ~/.hfc-key-store
Copy the code
  • To reconfigureconnection_profile_local.jsontheclient.credentialStore.path:
$ cd ~/marbles/config
$ vim connection_profile_local.json
Copy the code

Locate the following fragment in the file:

"client": {
        "organization": "Org1MSP"."credentialStore": {
            "path": "/$HOME/.hfc-key-store"}},Copy the code

Change path to the above path (/$HOME/. Hfc-key-store).

  • Go back to the Marbles home directory and rerun the project
$ cd ~/marbles
$ gulp marbles_local
Copy the code

If this does not work, you can check issues to see if there is a similar error. If there is a solution process, you can follow the solution process and try to solve the problem yourself.

Running Configuration Screenshot

  • start

    Click the button to the right of selectionGuidedIn this way, you can learn about the Fabric and customize some of the Settings

  • Step 1: Check the connection configuration data

The first step is to examine your connection configuration JSON file. Check file is: marbles/config/marbles_local json and ` ` marbles/config/connection_profile_local json `

  • Step 2: Register an administrator

Next, we try to register you as your company’s administrator. This step contacts your certificate Authority (CA) and offers enrollID and Enrollment Secret from your connection profile

  • Step 3: Look up Chaincode

Now we need to find the chain code on your channel. Check or modify the link code configured in your connection profile named pinball channel myChannel.

  • Step 4: Create the asset

As a pinball trading company, you can carry new pinball owners. These pinball owners represent your user base. This step creates pinball users and each user has three marbles.

  • Please click before proceeding to the next stepCreateTo create a

  • Step 5: When the configuration is complete, press Enter to Enter the system

Once in the system, you can create a pinball asset for one user, or transfer a pinball asset to another user, as shown at the beginning of this tutorial or in the Gif below. You can also delete the marble asset.

  • Every time you click create, delete or trade assets, you are actually invoking the chain code operation, and this project also has animation to demonstrate the invocation of the chain code:

    Of course, there are many more features that you can play with after you deploy!

reference

  • IBM-Blockchain/ Marbles (official project address)
  • Troubleshooting Principle and solution of invalid Node version management tool N
  • Install NodeJS and NPM in Ubuntu
  • How to degrade the NPM version
  • issues:208