Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but...

87
Blockchain Service Developer Guide Issue 01 Date 2020-04-21 HUAWEI TECHNOLOGIES CO., LTD.

Transcript of Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but...

Page 1: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Blockchain Service

Developer Guide

Issue 01

Date 2020-04-21

HUAWEI TECHNOLOGIES CO., LTD.

Page 2: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Copyright © Huawei Technologies Co., Ltd. 2020. All rights reserved.

No part of this document may be reproduced or transmitted in any form or by any means without priorwritten consent of Huawei Technologies Co., Ltd. Trademarks and Permissions

and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.All other trademarks and trade names mentioned in this document are the property of their respectiveholders. NoticeThe purchased products, services and features are stipulated by the contract made between Huawei andthe customer. All or part of the products, services and features described in this document may not bewithin the purchase scope or the usage scope. Unless otherwise specified in the contract, all statements,information, and recommendations in this document are provided "AS IS" without warranties, guaranteesor representations of any kind, either express or implied.

The information in this document is subject to change without notice. Every effort has been made in thepreparation of this document to ensure accuracy of the contents, but all statements, information, andrecommendations in this document do not constitute a warranty of any kind, express or implied.

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. i

Page 3: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Contents

1 Overview....................................................................................................................................1

2 Chaincode Development and Debugging.......................................................................... 22.1 Chaincode Development....................................................................................................................................................... 22.2 Chaincode Debugging............................................................................................................................................................52.3 Note............................................................................................................................................................................................. 72.3.1 Editing Chaincode................................................................................................................................................................ 72.3.2 Preventing Chaincode Container from Failing After a Panic................................................................................ 82.3.3 Querying Data in Batches................................................................................................................................................. 82.3.4 Using Indexes with CouchDB........................................................................................................................................... 92.3.5 Verifying Permissions....................................................................................................................................................... 132.3.6 Verifying Parameters........................................................................................................................................................ 142.3.7 Optimizing Logic................................................................................................................................................................152.3.8 Viewing Logs....................................................................................................................................................................... 152.4 Example Chaincode.............................................................................................................................................................. 16

3 Application Configuration and Development................................................................ 18

4 Encryption Using Chinese Cryptographic Algorithms...................................................214.1 Overview.................................................................................................................................................................................. 214.2 Use of SDKs.............................................................................................................................................................................224.3 Private Key Encryption Tool...............................................................................................................................................244.4 Appendixes.............................................................................................................................................................................. 25

5 Homomorphic Encryption................................................................................................... 275.1 Overview.................................................................................................................................................................................. 275.2 Use of the Homomorphic Encryption Library............................................................................................................. 285.3 AHE Lib APIs........................................................................................................................................................................... 305.4 Chaincode Library APIs....................................................................................................................................................... 345.5 IDChaincode............................................................................................................................................................................ 375.6 Sample Chaincode................................................................................................................................................................ 375.7 Sample Application.............................................................................................................................................................. 395.8 Transaction Verification with Homomorphic Encryption (Demo)....................................................................... 42

6 Demos...................................................................................................................................... 566.1 Java SDKs................................................................................................................................................................................. 56

Blockchain ServiceDeveloper Guide Contents

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. ii

Page 4: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

6.2 MySQL SDKs........................................................................................................................................................................... 626.3 RESTful APIs............................................................................................................................................................................ 686.4 Node.js SDKs........................................................................................................................................................................... 76

Blockchain ServiceDeveloper Guide Contents

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. iii

Page 5: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

1 Overview

HUAWEI CLOUD Blockchain Service (BCS) offers a highly available and secureblockchain platform with superb performance to enterprises and developers. Ithelps them efficiently create, deploy, and manage blockchain applications andbusiness smart contracts on HUAWEI CLOUD at the minimal cost.

To use BCS, you need to develop your own chaincodes (smart contracts) andapplications, as indicated by A and B in the following figure.

Before starting development, you can experience Huawei's best-practice-baseddemo applications to quickly get started.

If you have requirements for service chaincode or client app design and development, reachus by [email protected]. Then, BCS and its partners will provide you withcomprehensive solutions based on your business and HUAWEI CLOUD advantages andfeatures.

Blockchain ServiceDeveloper Guide 1 Overview

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 1

Page 6: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

2 Chaincode Development and Debugging

2.1 Chaincode DevelopmentChaincode is also called smart contract, which is the service logic of interactionbetween parties in a blockchain network. A chaincode encapsulates servicetransaction data into code, which runs in a Docker container. Currently, HUAWEICLOUD BCS supports Golang and Node.js for programming. The following usesGolang as an example.

Each chaincode is a Golang file. After creating such a file, you can performoperations such as function development.

Procedure

Step 1 Set up the Go development environment and editor.● Download and install Go. Version 1.11.12 is recommended.● Use an editor you prefer. GoLand is recommended.

Step 2 Download Fabric source code package as the third-party repository.

Download link: https://github.com/hyperledger/fabric

The Fabric source code package must match the BCS service version. If your BCS service isof version 2.x.x (corresponding to Fabric v1.1.0), the Fabric code version should be 1.1. Ifyour BCS service is of version 3.x.x (corresponding to Fabric v1.4.0), the Fabric code versionshould be 1.4.

Step 3 Create a project, create a chaincode file, and import package shim.

Package shim provides APIs to enable your chaincode to interact with the underlyingblockchain network to access status variables, transaction contexts, invoker certificates andattributes, and perform other operations such as invoking other chaincodes.

package test

import ( "fmt"

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 2

Page 7: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

"strconv"

"github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer")

Step 4 Compile the main function.

All Golang programs start with the main function, which is used to start a chaincode. Whena chaincode instance is deployed on a peer, the main function is executed.

// SimpleChaincode example simple Chaincode implementationtype SimpleChaincode struct {}func main() { err := shim.Start(new(SimpleChaincode)) if err != nil { fmt.Printf("Error starting Simple chaincode: %s", err) }}

Step 5 Implement the init method.

The init method is called when a chaincode is deployed on a blockchain network for thefirst time and is executed by each peer where instances of this chaincode are deployed. Thismethod can be used for all initialization, boot, or configuration tasks.

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { fmt.Println("ex02 Init") _, args := stub.GetFunctionAndParameters() var A, B string // Entities var Aval, Bval int // Asset holdings var err error

if len(args) != 4 { return shim.Error("Incorrect number of arguments. Expecting 4") }

// Initialize the chaincode A = args[0] Aval, err = strconv.Atoi(args[1]) if err != nil { return shim.Error("Expecting integer value for asset holding") } B = args[2] Bval, err = strconv.Atoi(args[3]) if err != nil { return shim.Error("Expecting integer value for asset holding") } fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

// Write the state to the ledger err = stub.PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return shim.Error(err.Error()) }

err = stub.PutState(B, []byte(strconv.Itoa(Bval))) if err != nil { return shim.Error(err.Error()) }

return shim.Success(nil)}

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 3

Page 8: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 6 Implement the invoke method.

The invoke method is invoked if the status of a blockchain is to be changed. All creation,update, and deletion operations must be encapsulated in the invoke method. This methodchanges the blockchain status. Therefore, the Fabric code of a blockchain automaticallycreates a transaction context for this method to be executed. Each invocation of thismethod is recorded as a transaction in a block.

func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response { fmt.Println("ex02 Invoke") function, args := stub.GetFunctionAndParameters() if function == "invoke" { // Make payment of X units from A to B return t.invoke(stub, args) } else if function == "delete" { // Deletes an entity from its state return t.delete(stub, args) } else if function == "query" { // the old "Query" is now implemtned in invoke return t.query(stub, args) }

return shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"")}// Transaction makes payment of X units from A to Bfunc (t *SimpleChaincode) invoke(stub shim.ChaincodeStubInterface, args []string) pb.Response { var A, B string // Entities var Aval, Bval int // Asset holdings var X int // Transaction value var err error

if len(args) != 3 { return shim.Error("Incorrect number of arguments. Expecting 3") }

A = args[0] B = args[1]

// Get the state from the ledger // TODO: will be nice to have a GetAllState call to ledger Avalbytes, err := stub.GetState(A) if err != nil { return shim.Error("Failed to get state") } if Avalbytes == nil { return shim.Error("Entity not found") } Aval, _ = strconv.Atoi(string(Avalbytes))

Bvalbytes, err := stub.GetState(B) if err != nil { return shim.Error("Failed to get state") } if Bvalbytes == nil { return shim.Error("Entity not found") } Bval, _ = strconv.Atoi(string(Bvalbytes))

// Perform the execution X, err = strconv.Atoi(args[2]) if err != nil { return shim.Error("Invalid transaction amount, expecting a integer value") } Aval = Aval - X Bval = Bval + X fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 4

Page 9: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

// Write the state back to the ledger err = stub.PutState(A, []byte(strconv.Itoa(Aval))) if err != nil { return shim.Error(err.Error()) }

err = stub.PutState(B, []byte(strconv.Itoa(Bval))) if err != nil { return shim.Error(err.Error()) }

return shim.Success(nil)}

// Deletes an entity from statefunc (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) pb.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") }

A := args[0]

// Delete the key from the state in ledger err := stub.DelState(A) if err != nil { return shim.Error("Failed to delete state") }

return shim.Success(nil)}// query callback representing the query of a chaincodefunc (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response { var A string // Entities var err error

if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting name of the person to query") }

A = args[0]

// Get the state from the ledger Avalbytes, err := stub.GetState(A) if err != nil { jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}" return shim.Error(jsonResp) }

if Avalbytes == nil { jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}" return shim.Error(jsonResp) }

jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}" fmt.Printf("Query Response:%s\n", jsonResp) return shim.Success(Avalbytes)}

----End

2.2 Chaincode DebuggingUse MockStub to perform unit tests on chaincodes. For details, see the officialFabric guide.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 5

Page 10: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

If the following error occurs during the debugging:

Press Alt+Shift+F10 to display the Run window. Then, click Edit Configurations.

In the displayed bigger Run window, enter -i -tags nopkcs11 for Go toolarguments and click Apply > Run.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 6

Page 11: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

2.3 Note

2.3.1 Editing ChaincodeYou can use the chaincode editor to write chaincodes and test simple interfaces(stub.PutState, stub.GetState, and stub.DelState) on the Blockchain Managementconsole.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 7

Page 12: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

2.3.2 Preventing Chaincode Container from Failing After aPanic

When the defer statement is added at the entry point of the Invoke function and apanic exception occurs, the chaincode container may be suspended and restarted.As a result, logs may not be found and faults cannot be located.

// Name the return value in the defer statement to ensure that the client can receive the value if a panic occurs.// Use debug.PrintStack() to print the stack trace to the standard output for fault locating.func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) (pr pb.Response) { defer func() { if err:=recover(); err != nil { fmt.Println("recover from invoke:", err) debug.PrintStack() pr = shim.Error(fmt.Sprintf("invoke painc. err: %v",err)) } }()

fmt.Println("ex02 Invoke") function, args := stub.GetFunctionAndParameters() if function == "invoke" { // Make payment of X units from A to B return t.invoke(stub, args) } else if function == "delete" { // Deletes an entity from its state return t.delete(stub, args) } else if function == "query" { // the old "Query" is now implemtned in invoke return t.query(stub, args) }

pr = shim.Error("Invalid invoke function name. Expecting \"invoke\" \"delete\" \"query\"") return pr}

2.3.3 Querying Data in BatchesDo not return too many records in one query. Otherwise, too many resources willbe occupied and the interface delay will be long. For example, if the interfacedelay exceeds 30s, the peer task will be interrupted. Therefore, estimate the datavolume in advance, and query data in batches if the data volume is large. Tomodify or delete the ledger data chaincode, consider performing operations inbatches based on the data volume.

// Query data in pages.func (t *SimpleChaincode) queryTestPagination(stub shim.ChaincodeStubInterface, args []string) pb.Response { if len(args) != 3 { return shim.Error("Incorrect number of arguments. Expecting 3") } // Obtain the start offset. offset, err := strconv.Atoi(args[1]) if err != nil { fmt.Println("Error offset: " + args[1]) return shim.Error("Error offset: " + args[1]) } // Obtain the number of records displayed on each page (pageSize). pageSize, err := strconv.Atoi(args[2]) if err != nil { fmt.Println("Error pageSize: " + args[2]) return shim.Error("Error pageSize: " + args[2]) }

// Obtain all composite keys.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 8

Page 13: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

resultIterator, err := stub.GetStateByPartialCompositeKey("TEST", []string{args[0]}) if err != nil { return shim.Error("GetStateByPartialCompositeKey failed. err:" + err.Error()) } defer resultIterator.Close()

var resp = []string{}

index := 0 // Traverse keys, query values, and combine the results obtained on each page. for resultIterator.HasNext() { index ++ item, _ := resultIterator.Next()

if (index >= offset) && len(resp) < pageSize { value, err := stub.GetState(item.Key) if err != nil { return shim.Error(err.Error()) } resp = append(resp, string(value)) } } fmt.Printf("Query Response:%v\n", resp) return shim.Success([]byte(""))}// Write data by using a composite key.func (t *SimpleChaincode) addTest(stub shim.ChaincodeStubInterface, args []string) pb.Response { if len(args) != 3 { return shim.Error("Incorrect number of arguments. Expecting 3") }

// Construct a composite key starting with TEST, for example, TEST A 1 TEST A 2... key, err := stub.CreateCompositeKey("TEST", []string{args[0], args[1]}) if err != nil { return shim.Error("Error CreateCompositeKey.") }

// Write data. err = stub.PutState(key, []byte(args[2])) if err != nil { return shim.Error(err.Error()) }

return shim.Success(nil)}

2.3.4 Using Indexes with CouchDBUsing indexes with CouchDB accelerates data querying, but slows data writing.Therefore, create indexes only for certain fields based on service requirements.

Fabric v1.1 does not support index creation using chaincodes. You need to configure theCouchDB access port. (Enabling the port may cause security risks. Disable the port afterusing it.) After logging in to CouchDB, manually create an index. If a peer organization hasmultiple peers, you need to use different browser clients or log in to and out of the peersrepeatedly to ensure that an index is created in the CouchDB for each peer.

Enabling the CouchDB Port1. Log in to the CCE console and choose Resource Management > Network.

Then, click Create Service.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 9

Page 14: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

2. Select NodePort.

3. Enter a service name, for example, peer-couchdb-nodeport.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 10

Page 15: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

4. Select a workload.

5. Specify the mapping ports.

6. Access CouchDB.Enter http://{EIP}:31984/_utils/index.html#verifyinstall in the address boxof a browser. Replace {EIP} with the actual public IP address.

7. Log in to CouchDB.On the login page, enter the username and password, and click Log In.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 11

Page 16: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

8. Access the database.Click the name of the created database (Channel name_Chaincode name).

9. Access the index management page.

Click on the right of testch_attestation and then choose MangoIndexes.

10. Create an index.Write the index statement in the Index text box and click Create Index.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 12

Page 17: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

After the index is created, you can view the index details on the right.

2.3.5 Verifying PermissionsVerify the permissions of the smart contract executor to prevent unauthorizedusers from executing chaincodes.

If no specified organization is required for the endorsement, select at least two endorsingorganizations to ensure that the chaincode data is not maliciously modified (such asinstalling invalid chaincode or processing data) by any other organizations.

// Organizations involved: cargo owner ("cargoOwner"), shipping company ("shipCompany"), customs, port, and regulators// The argument is orgid, which assigns organization roles.func (t *Logistics) Init(stub shim.ChaincodeStubInterface) pb.Response { _, args := stub.GetFunctionAndParameters() if len(args) != 2 { return shim.Error("Incorrect number of arguments. Expecting 2") } err := stub.PutState(args[0], []byte("cargoOwner,shipCompany,freightageAgent,customs")) if err != nil { return shim.Error(err.Error()) } err = stub.PutState(args[1], []byte("regulators")) if err != nil { return shim.Error(err.Error()) } return shim.Success(nil) }

// Parse the user certificate to obtain the user's role.func getuserrole (stub shim.ChaincodeStubInterface) []string { creatorByte, _ := stub.GetCreator() certStart := bytes.IndexAny(creatorByte, "-----BEGIN") if certStart == -1 { fmt.Errorf("No certificate found") }

certText := creatorByte[certStart:] bl, _ := pem.Decode(certText) if bl == nil { fmt.Errorf("Could not decode the PEM structure") }

cert, err := x509.ParseCertificate(bl.Bytes) if err != nil { fmt.Errorf("ParseCertificate failed") }

uname := cert.Subject.CommonName

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 13

Page 18: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

orgid := string([]rune(uname)[6:46])

roleByte, err := stub.GetState(orgid)

roleArray := []string{} if err != nil { fmt.Errorf("Could not get userrole") return roleArray } role := string(roleByte)

roleArray = strings.Split(role,",")

return roleArray }

// Check the user role.func checkRole(roleArray []string, role string) bool { flag := false for i := 0; i < len(roleArray); i++ { if (strings.Compare(roleArray[i], role) == 0) { flag = true; break; } }

return flag}

// Create an order. Parameters (orderid, shippinginfo, shipinfo, cargos, and username) are transferred in JSON format. // Generate orderid in the format of "o + timestamp" to facilitate querying.func Addorder(stub shim.ChaincodeStubInterface, args []string) (pb.Response) { roleArray := getuserrole(stub)

// If the user is not the cargo owner, the user does not have the operation permission. if(!checkRole(roleArray, "cargoOwner")){ return shim.Error("Permission denied") }

if len(args) != 6 { return shim.Error("Incorrect number of arguments. Expecting 6") }

orderjson, err := stub.GetState(orderid) if orderjson == nil { // Create an order. ...... return shim.Success(nil) } return shim.Error(err.Error())}

2.3.6 Verifying ParametersBefore parameters (including input parameters and parameters defined in code)are used, the quantity, type, length, and value range of the parameters must beverified to prevent array out-of-range.

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response { fmt.Println("ex02 Init") _, args := stub.GetFunctionAndParameters() var A, B string // Entities var Aval, Bval int // Asset holdings var err error

if len(args) != 4 {

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 14

Page 19: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

return shim.Error("Incorrect number of arguments. Expecting 4") }

// Initialize the chaincode A = args[0] Aval, err = strconv.Atoi(args[1]) if err != nil { return shim.Error("Expecting integer value for asset holding") } ... return shim.Success(nil)}

2.3.7 Optimizing LogicOptimize the function execution logic based on the service scenario. If an erroroccurs, print logs or stop the function to return the error information.

// query callback representing the query of a chaincodefunc (t *SimpleChaincode) query(stub shim.ChaincodeStubInterface, args []string) pb.Response { var A string // Entities var err error

if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting name of the person to query") }

A = args[0]

// Get the state from the ledger Avalbytes, err := stub.GetState(A) if err != nil { jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}" return shim.Error(jsonResp) }

if Avalbytes == nil { jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}" return shim.Error(jsonResp) }

jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}" fmt.Printf("Query Response:%s\n", jsonResp) return shim.Success(Avalbytes)}

2.3.8 Viewing LogsDuring the development of services that have a complex logic and are prone toerror, use fmt to print logs to facilitate debugging. fmt consumes a lot of timeand resources. Delete the logs after the debugging is complete.

1. Run the following command to find the chaincode container:docker ps -a | grep dev-peer | grep -v POD

2. To locate faults or view the chaincode execution duration, run the followingcommand to view the logs printed by using fmt during chaincode execution:docker logs -f Chaincode container ID

If the BCS service is deployed in a CCE cluster, you can also view thechaincode container logs on the Application Operations Management (AOM)console.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 15

Page 20: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

2.4 Example ChaincodeThe following chaincode is taken as an example, which is used to open aninterbank category II account with blockchain-based identity sharing.

fabbank.zip

● ScenarioA customer has submitted identity information (the name, ID card number,bank account name, and mobile number) to open a category I account ofbank A. Bank A stores the information in a blockchain. Then, the customerapplies for a category II account of bank B. Since the two banks reside in thesame blockchain network, bank B only needs to query the identity chain toopen the account, and the customer does not need to provide the identityinformation again.The procedure for invoking the application and chaincode is as follows:Bank B uses the bank login mode to log in to the blockchain system (forinterbank account opening) and import all the customer data of bank A(identity information of the category I account, that is, the name, ID cardnumber, bank account name, and mobile number) on the frontend UI. Thebackend interface FeedAccountInfo is invoked. After the parameters areverified, the Fabric SDK is used to call the chaincode API invoke and obtainthe function name creditAccountInfo and customer parameters. Thechaincode function creditAccountInfo is then executed, and the hashalgorithm is used to encrypt non-sharing information. After that, thecustomer data is stored in a block.The customer uses the customer login mode to log in to the blockchainsystem and enters parameter values on the frontend UI to apply for acategory II account of bank B. The backend API CreateType2Account isinvoked. After the parameters are verified, the Fabric SDK is used to call thechaincode API invoke, obtain the function name authAccount and accountparameters, execute the chaincode function authAccount, generate a hashbased on the identity information, query the identity chain, and send an SMSconfirmation code (this step is skipped in the example) to open the account.

● Scenario AnalysisThis scenario involves the following tasks:(1) Customer information verification: The initial verification of the bank iscompleted off the chain in a banking app.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 16

Page 21: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

(2) Creation of a category I account: The customer information is stored inthe blockchain.(3) Checking whether the customer already has a category I account ofanother bank based on the customer information.(4) Creation of a category II account based on the verification result.

Whether the category II account needs to be stored in the chaincode mainlydepends on whether consensus is required on the account data among multipleparties. In this example, the category II account exists only in bank B and is notstored in the blockchain. Therefore, tasks (2) and (3) can be performed by thechaincode, and the other tasks are implemented by an app.

Blockchain ServiceDeveloper Guide 2 Chaincode Development and Debugging

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 17

Page 22: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

3 Application Configuration andDevelopment

Before developing an application, you need to download certificates and SDKconfiguration file. Then, you can use Golang to develop your application and usethe available APIs in the Hyperledger Fabric SDK for Go to invoke the chaincode tocomplete transaction processing in the blockchain network.

Downloading CertificatesTwo types of certificates are now supported: administrator certificate and usercertificate. The administrator certificate is required to create, join, and update achannel, and install, instantiate, upgrade, and delete a chaincode. For transactionsand query, you are advised to use the user certificate.

NO TICE

The administrator certificate differs between an orderer and a peer. Formanagement within a channel, you need to use the administrator certificate forpeers instead of that for orderers.

Step 1 Download the certificates of a service on the Service Management page, asshown in the following figure.

Blockchain ServiceDeveloper Guide 3 Application Configuration and Development

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 18

Page 23: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 2 Decompress the downloaded certificate files and store the files in an applicationdirectory for the application to access.

----End

Downloading the SDK Configuration

Step 1 On the Service Management page, choose More > Download SDKConfiguration, as shown in the following figure.

Step 2 Configure the SDK file parameters, as shown in the following figure.

Blockchain ServiceDeveloper Guide 3 Application Configuration and Development

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 19

Page 24: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Table 3-1 Parameters

Parameter Description

ChaincodeName

Set it as required.

ChaincodeVersion

Set it as required.

CertificateRoot Path

Enter the root path of the certificates specified duringapplication compilation.

Channel Select a channel.

Member Select a peer organization in the channel.

Step 3 Click Download. The downloaded file package is named test-sdk-config.zip.

Step 4 Decompress the file package and store the retrieved test-sdk-config.yaml file

----End

Developing an ApplicationYou need to develop the service logic. The Chinese cryptographic algorithm SDKand homomorphic encryption library can be used for the application development.For details, see Encryption Using Chinese Cryptographic Algorithms andHomomorphic Encryption.

Configuring the ApplicationThe chaincode_id and channel_id values in the app.conf file must be the same asthe chaincode and channel IDs specified during chaincode installation.

Blockchain ServiceDeveloper Guide 3 Application Configuration and Development

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 20

Page 25: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

4 Encryption Using Chinese CryptographicAlgorithms

4.1 OverviewEncryption using Chinese cryptographic algorithms can improve the encryptionstrength and the performance of encryption and decryption. Support for theChinese cryptographic algorithms is an admission threshold in many industries.HUAWEI CLOUD BCS provides Chinese cryptographic algorithm SDKs andencryption tools for you to develop client programs while protecting your privatekeys.

Downloading Resources

Table 4-1 SDK list

MatchingHyperledger FabricVersion

SDK Version Link

Fabric v1.1.0 andFabric v1.4.0

1.8.5 SDK package

1.9.2 SDK package

NOTICE● Select a package of the same version as the local compilation environment. For

example, if the local Golang compiler is of version 1.8.5, download the SDK of version1.8.5.

● The Chinese cryptographic algorithm SDKs offer all functions of common SDKs andadditionally support the Chinese cryptographic algorithms.

After decompressing the downloaded package, you will obtain three directories:bin, src, and pkg. The following table lists the functions of the directories.

Blockchain ServiceDeveloper Guide

4 Encryption Using Chinese CryptographicAlgorithms

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 21

Page 26: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Directory Description

bin Stores the private key encryption tool encrypt_tool. Fordetails, see Private Key Encryption Tool.

src Stores empty source code files for use of static libraries.

pkg Stores the static library code.

4.2 Use of SDKs

Installing the Dependent Library FileA Chinese cryptographic algorithm SDK has a dependent library. The library isstored in the following src directory of the SDK according to Fabric 1.1:

src/github.com/hyperledger/fabric-sdk-go/deps/lib/

Copy the two dynamic library files to the /usr/local/include/openssl/ directory(create this directory if it does not exist). Then, set the following environmentvariable:

export LD_LIBRARY_PATH=/usr/local/include/openssl:$LD_LIBRARY_PATH

NO TICE

If the ltdl library is missing in the user environment, install the libtool. Theinstallation method depends on the Linux operating system (OS) packagemanagement tool. For example, use the apt-get install libtool command forUbuntu and yum install libtool-ltdl-devel for CentOS. Alternatively, downloadthe source code from https://www.gnu.org/software/libtool/, then compile andinstall the libtool.

Installing the SDKDecompress the downloaded package to the $GOPATH directory.

Developing a Client ProgramThe use of Chinese cryptographic algorithm SDKs is the same as that of the FabricSDKs. If the private key encryption tool provided by Huawei is used to encryptprivate keys, perform the following steps to invoke the SDKs to set the userpassword for decrypting private keys (the password must be the same as thatused for the private key encryption tool):

1. Use the following command to import the API package:import "github.com/hyperledger/fabric-sdk-go/api/apiuserpass"

2. Use the following code to invoke the function:err := apiuserpass.SetUserPassword("*********")if err != nil {fmt.Println("fail to set user password")}

Blockchain ServiceDeveloper Guide

4 Encryption Using Chinese CryptographicAlgorithms

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 22

Page 27: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

In the preceding code, ********* represents the encryption password, which must be setbased on the service requirements.

Modifying the Configuration FileBefore running the client program, you need to set the configuration file andcertificate file. Regarding the configuration file, ensure that the signaturealgorithm and the certificate file paths are correct.

● To use the ECDSA signature algorithm, set the parameters as follows in theconfiguration file:

● To use a Chinese cryptographic signature algorithm, set the parameters asfollows in the configuration file:

● Pay attention to the paths to the certificate files in the configuration file,including the MSP path and TLS CA certificate path, as shown in the followingfigures.

Blockchain ServiceDeveloper Guide

4 Encryption Using Chinese CryptographicAlgorithms

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 23

Page 28: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Running the Client Program

To run the client program, you need to set the configuration file path, channelname, chaincode name, and organization ID.

● Configuration file path: the path for storing the downloaded configuration file

● Channel name: the channel name specified for the BCS service

● Chaincode name: the name specified when the chaincode is installed for theBCS service

● Organization ID: 02f23ab00f6e1ffcde8a27bfd3ac2290edc18127 in thefollowing example configuration fileclient:organization: 02f23ab00f6e1ffcde8a27bfd3ac2290edc18127

4.3 Private Key Encryption ToolYou can encrypt the key in the form of a plaintext downloaded from HUAWEICLOUD BCS by using a password and save it locally. Huawei provides a private keyencryption tool, encrypt_tool, to help you convert a key plaintext into a keyprotected by a password. If a password-protected key is used in an SDK, the SDKAPI must be invoked to transfer the password to the SDK.

The private key encryption tool bin/encrypt_tool is a command line tool. Theinput parameters for tool execution are the plaintext of the path to the MSPprivate key, plaintext of the path to the TLS private key, ciphertext of the path tothe MSP private key, ciphertext of the path to the TLS private key, and private keytype. The received password must contain 8 to 32 characters. The following tablelists the parameters.

Blockchain ServiceDeveloper Guide

4 Encryption Using Chinese CryptographicAlgorithms

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 24

Page 29: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Flag Description

-pmsp Plaintext of the path to the MSP private key

-ptls Plaintext of the path to the TLS private key

-cmsp Encrypted path of the MSP private key

-ctls Encrypted path of the TLS private key

- keytype Algorithm for encrypting the private key. The options areas follows:sm: A Chinese cryptographic algorithm is used for fileencryption.sw: ECDSA is used for file encryption.You can set this parameter based on their need forChinese cryptographic algorithms.

NO TICE

The encryption tool has password complexity requirements. A password mustcontain at least six characters and contain at least two types of the followingcharacters:1. Uppercase letters2. Lowercase letters3. Digits4. Special characters (`~!@#$%^&*()-_=+\|[{}];:'",<.>/? and spaces)

Assume that the compiled private key encryption tool is encrypt_tool, the MSPprivate key to be encrypted is plainMSPKey, the TLS private key to be encrypted isplainTLSKey, and the encrypted MSP private key is cipherMSPKey, and theencrypted TLS private key is cipherTLSKey.

● To use a Chinese cryptographic algorithm to encrypt a private key, use thefollowing line:

./encrypt_tool –pmsp ./plainMSPKey –ptls ./plainTLSKey –cmsp ./cipherMSPKey –ctls ./cipherTLSKey –keytype sm

● To use ECDSA to encrypt a private key, use the following line:./encrypt_tool –pmsp ./plainMSPKey –ptls ./plainTLSKey –cmsp ./cipherMSPKey –ctls ./cipherTLSKey –keytype sw

After the command line is run, enter a password containing 8 to 32 characters asprompted.

4.4 AppendixesThe following table lists the directories of the third-party packages that fabric-sdk-client/go depends on.

Blockchain ServiceDeveloper Guide

4 Encryption Using Chinese CryptographicAlgorithms

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 25

Page 30: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

No. Package

1 vendor/github.com/Knetic/govaluate

2 vendor/github.com/cloudflare/cfssl

3 vendor/github.com/fsnotify/fsnotify

4 vendor/github.com/golang/groupcache

5 vendor/github.com/golang/mock

6 vendor/github.com/golang/protobuf

7 vendor/github.com/hashicorp/hcl

8 vendor/github.com/magiconair/properties

9 vendor/github.com/miekg/pkcs11

10 vendor/github.com/mitchellh/mapstructure

11 vendor/github.com/pelletier/go-toml

12 vendor/github.com/pkg/errors

13 vendor/github.com/spf13/afero

14 vendor/github.com/spf13/cast

15 vendor/github.com/spf13/jwalterweatherman

16 vendor/github.com/spf13/pflag

17 vendor/github.com/spf13/viper

18 vendor/golang.org/x/crypto

19 vendor/golang.org/x/net

20 vendor/golang.org/x/sync

21 vendor/golang.org/x/sys

22 vendor/golang.org/x/text

23 vendor/google.golang.org/genproto/googleapis

24 vendor/google.golang.org/grpc

25 vendor/gopkg.in/yaml.v2

Blockchain ServiceDeveloper Guide

4 Encryption Using Chinese CryptographicAlgorithms

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 26

Page 31: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

5 Homomorphic Encryption

5.1 OverviewHUAWEI CLOUD BCS provides a homomorphic encryption library to facilitatedevelopment. In addition to the encryption function offered by commonencryption algorithms, homomorphic encryption also allows computation andconversion of cipher texts, which is important for security. Homomorphicencryption enables users without keys to perform computing on ciphertexts. Inthis way, the communication cost can be reduced, computing tasks can betransferred, and the calculation costs can be balanced among the involved parties.By using the homomorphic encryption technology, a decryption party obtains onlythe decryption result, but cannot obtain each message ciphertext. This improvesinformation security.

HUAWEI CLOUD BCS provides homomorphic encryption libraries for clients andchaincodes. These libraries are mainly used for transaction ciphertext computingto ensure user privacy and security.

● Library for clients: It provides the additive homomorphic encryption functionand generates proofs of transaction amounts at clients.

● Homomorphic encryption chaincode IDChaincode.go: In a homomorphicencryption scenario, you need to download, install, and instantiate chaincodesfor BCS services before service deployment.

● Library for chaincodes: It provides the zero knowledge proof function to verifythe transaction proof of a user in a ciphertext case and generate post-transaction data. In this way, an endorser does not need to decrypt thetransaction data of the user to determine the balance range.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 27

Page 32: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Downloading Resources

Table 5-1 Library list

MatchingHyperledger FabricVersion

Library Version Link

Fabric v1.1.0 andFabric v1.4.0

1.8.5 Homomorphic encryptionlibrary

1.9.2 Homomorphic encryptionlibrary

● Homomorphic encryption chaincode: IDChaincode.go● Chaincode library API file: api_ahe_cc.tar.gz

NOTICE● Select a package of the same version as the local compilation environment. For

example, if the local Golang compiler is of version 1.8.5, download the library of version1.8.5.

● The Chinese cryptographic algorithm SDK must be installed before using ahomomorphic encryption library.

● The api_ahe_cc.tar.gz package is used only for local compilation.

5.2 Use of the Homomorphic Encryption Library

Buying a BCS Service and Downloading FilesWhen buying a BCS service, select ECDSA for Security Mechanism. After thesubscription, download the homomorphic encryption library ahex.x.x.tar.gz,Chinese cryptographic algorithm SDK sdkx.x.x.tar.gz in the client development kit,and the user certificates and configuration files of peers and orderers.

Installing the Client SDK LibraryDecompress the downloaded Chinese cryptographic algorithm SDK sdkx.x.x.tar.gzto the $GOPATH directory.

Installing the Homomorphic Encryption LibraryDecompress the downloaded homomorphic encryption library ahex.x.x.tar.gz tothe $GOPATH directory.

Installing the Dependent Library (Only for Fabric 1.1)The dependent library files are stored in the homomorphic encryption librarydirectory. The decompressed homomorphic encryption library file is stored in the$GOPATH/src/ahe/PSW/deps/lib directory. Copy all the files in this directory tothe local /usr/local/include/openssl/ directory. (If this directory does not exist,create it.) Then, run the following command to set the environment variables:

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 28

Page 33: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

export LD_LIBRARY_PATH=/usr/local/include/openssl:$LD_LIBRARY_PATH

NO TICE

If the system displays a message indicating that libgmp is missing, install the gmplibrary. For details about the installation method, see the Linux operating systempackage management tool. For example, if Ubuntu is used, run the apt-get installlibgmp10 command to install the library, or download the source code fromhttps://gmplib.org/, then compile and install the library.

Developing the Client Program and ChaincodeRefer to the API descriptions in sections 4.2.3 and 4.2.4 to develop the applicationand chaincode (smart contract).

The typical service logic of an application client is as follows:

1. Registering for a user2. Initializing the account balance3. Initiating a transaction

● When a user is registered, the key generation function can be invoked to generatepublic and private keys for the user.

● When the balance is initialized, the initial balance preparation function can beinvoked to generate initial balance data with privacy protected.

● During a transaction, the transaction preparation function can be invoked togenerate transaction data with privacy protected.

The typical service logic of a chaincode is as follows:

1. Storing the mapping between the user's public key and address2. Verifying the validity of the initial balance and generating an initial

transaction3. Verifying the validity of transaction data and generating the transaction result

● The chaincode can invoke the initial balance verification function to verify thevalidity of the initial balance.

● The transaction verification function is invoked to verify the validity of transactiondata.

● For details about the development process, refer to the API descriptions in sections4.2.3 and 4.2.4.

Installing the ChaincodeInstall and instantiate the developed chaincode for the subscribed BCS service onthe management page.

Deploying the ApplicationWhen developing the application, you can invoke the homomorphic encryptionlibrary to protect the transaction privacy. After the development is completed,

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 29

Page 34: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

deploy the application on the purchased server. After deployment, ensure that theconfiguration files, certificate files (user certificates of peers and orderers), andopenssl library are available in the environment.

5.3 AHE Lib APIsA homomorphic encryption library file is provided for integrating thehomomorphic encryption function in the client application during development.

The code for importing the library is import "ahe/PSW/api/ahelib".

GenerateKey● API prototype

func GenerateKey(pwd string) (privKeyStr string, pubKeyStr string, err error)

● Function description

Generating a key pair for homomorphic encryption

● Input

Parameter Type Description Mandatory orNot

pwd string Used to encrypt the generatedprivate keychain used forhomomorphic encryption.AES-128 is used for theencryption.The pwd value must contain:● At least six characters● At least two types of the

following characters:– Lowercase letters– Uppercase letters– Digits– Special characters (`~!@#$

%^&*()-_=+\|[{}];:'",<.>/?and spaces)

Yes

● Output

Parameter Type Description

privKeyStr string Homomorphic private key encrypted usingthe pwd

pubKeyStr string Public keychain for homomorphic encryption

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 30

Page 35: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Type Description

err error Error message

● Note

The complexity of keys depends on the actual application scenario. No restrictionsare imposed on a key used to invoke an underlying library.

Encypt● API prototype

func Encypt (secretNumStr string, pubKeyStr string) (ciphertext string, err error)

● Function description

Homomorphic encryption

● Input

Parameter Type Description Mandatory orNot

secretNumStr string Value to be encrypted. Thevalue must be a positiveinteger greater than or equalto 0. If the number containsdecimal places, the valuemust be multiplied toeliminate the decimal places.

Yes

pubKeyStr String Public key for homomorphicencryption

Yes

● Output

Parameter Type Description

ciphertext string Encrypted data

err error Error message

● Note

None

Decrypt● API prototype

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 31

Page 36: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

func Decrypt(ciphertext string, privKeyStr string, pwd string) (plainText*big.Int, err error)

● Function description

Homomorphic decryption

● Input

Parameter Type Description Mandatory orNot

ciphertext string Ciphertext to be decrypted Yes

privKeyStr string Private keychain encrypted usingthe pwd for protection

Yes

pwd string Character string used to protectthe private key

No

● Output

Parameter Type Description

plainText *big.int Decrypted data

err error Error message

● Note

None

Add● API prototype

func Add(cipher1, cipher2 string) (cipher string, err error)

● Function description

Additive homomorphic encryption

● Input

Parameter Type Description Mandatory orNot

cipher1 string Encrypted ciphertext 1 Yes

cipher2 string Encrypted ciphertext 2 Yes

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 32

Page 37: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

● Output

Parameter Type Description

cipher string Combined data

err error Error message

● Note

None

InitBalance● API prototype

func InitBalance(balanceStr string, pubKey string) (string, error)● Function description

Balance initialization

● Input

Parameter Type Description Mandatory orNot

pubKey string Public keychain Yes

balanceStr string Initial balance, which must be apositive integer greater than orequal to 0. If the number containsdecimal places, the value must bemultiplied to eliminate thedecimal places.

Yes

● Output

Parameter Type Description

balanceInfo string Transaction amountinformation

err error Error message

● Note

None

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 33

Page 38: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

PrepareTxInfo● API prototype

func PrepareTxInfo(cipherBalanceA string, transNumStr string, pubKeyA,pubKeyB string, privKeyA string,pwd string) (string, error)

● Function descriptionTransaction preparation

● Input

Parameter Type Description Mandatory orNot

cipherBalanceA

string Current balance of user A(ciphertext), which isobtained from theblockchain.

Yes

transNumStr string Transfer amount (plaintext) Yes

pubKeyA string Public keychain of user A Yes

pubKeyB string Public keychain of user B Yes

PrivKeyA string Private keychain of user A Yes

pwd string Character string used forencryption

No

● Output

Parameter Type Description

Txinfo string Transaction preparationdata

err error Error message

● Note

None

5.4 Chaincode Library APIsThe chaincode library is static and integrated in BCS services. When developing achaincode, you can use the API file to locally compile the chaincode.

Download the API file (for the download link, see Downloading Resources), anddecompress it to the local GOPATH directory. Refer to the example chaincodeprovided in section 4.2.6 to import the homomorphic encryption library. After thechaincode is developed, install it in the BCS service. The chaincode will

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 34

Page 39: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

automatically link to the library code in the service to invoke the homomorphicencryption library for the chaincode.

The code for importing the homomorphic encryption library for the chaincode isimport "ahe/PSW/api/ChainCode".

NO TICE

Do not modify this code line. Otherwise, the chaincode fails to invoke thehomomorphic encryption library.

ValidateInitBalance● API prototype

func ValidateInitBalance(BalanceInfo, PubKey string) (InitBalance string, err error)

● Function description

Verifies the validity of the balance proof in balanceinfo generated bysdk.InitBalance.

● Input

Parameter Type Description Mandatory orNot

BalanceInfo string Initial balance data Yes

Pubkey string Public key for balanceencryption

Yes

● Output

Parameter Type Description Mandatory orNot

InitBalance string Initial balance ciphertext Yes

err error Error message Yes

● ProcessingBalance ciphertext provided after the balance validity verification

● Note

The account balance authenticity is ensured by the application logic. Thechaincode can only check whether the amount is greater than 0 but cannotdetermine the actual balance of a user.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 35

Page 40: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

ValidateTxInfo● API prototype

ValidateTxInfo(txInfo, cipherBalanceA, cipherBalanceB string)(newCipherBalanceA,newCipherBalanceB,newCipherTxA,newCipherTxB string,errerror)

● Function description

Verifies the validity of the transaction proof in Txinfo generated by PrepareTxInfo.

● Input

Parameter Type Description Mandatory orNot

txinfo string

Transaction proof dataNOTE

The transaction data includes the transactionproof data in addition to the ciphertext of thetransaction data. It is obtained from txinforeturned using sdk.PrepareTxInfo.

Yes

cipherBalanceA

string

Current balance of user A (ciphertext) Yes

cipherBalanceB

string

Current balance of user B (ciphertext) Yes

● Output

Parameter Type Description

newCipherBalanceA string User A' balance to beupdated after thetransaction

newCipherBalanceB string User B' balance to beupdated after thetransaction

newCipherTxA string Transaction amount(encrypted using user A'homomorphic public-keyencryption)

newCipherTxB string Transaction amount(encrypted using user B'homomorphic public-keyencryption)

err error Error message

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 36

Page 41: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

● Note

In this money transfer transaction, user A is the payer, and B the payee.

5.5 IDChaincodeIDChaincode stores the public key and account data of a user. When a key pair forhomomorphic encryption is generated for a user, the public keys must beregistered with the IDchaincode so that the homomorphic-encryption public key ofthe payee can be queried using the account. For details about how to downloadIDChaincode.go, see Downloading Resources.

NO TICE

IDChaincode.go is provided by HUAWEI CLOUD BCS. You are advised not tomodify it. If you modify it, its logic may be different from that of the exampleprovided in section 4.2.6.

RegisterThe account address is obtained by converting the public key hash into ahexadecimal character string.

QueryThe account address is used to query the public key.

5.6 Sample ChaincodeA transaction chaincode implements the service logic. The example transactionchaincode provided in this section is used to transfer money between users. Thevalidity of the transaction data in the form of a ciphertext is verified using thehomomorphic encryption library to detect unauthorized operations, if any. Thischaincode implements the functions of balance initialization, balance query, andmoney transfer.

Initializing the BalanceAfter a user is registered successfully, the balance of the user must be initialized.The default value is 0.

● Input

Parameter Type Description Mandatory orNot

PubKey string Public key Yes

Balance string Initial balance Yes

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 37

Page 42: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

● ProcessingInvoking the ValidateInitBalance API to verify the validity of the balance rangefor endorsementPubKey := string(args[0])BalanceInfo := string(args[1]) //PubKey := string(args[2])

hashPubkey, err := t.calcAddr(PubKey)logger.Debug("encrypt initial balance")//validate balancecipherBalance,err := pswapi_cc.ValidateInitBalance(BalanceInfo,PubKey) if err != nil { logger.Error("fail to Validate InitBalance ") return shim.Error("fail toValidate InitBalance") }

● Output

Parameter Type Description

newCipherBalance string Balance ciphertext

Querying the Balance

The balance can be queried using the account address. For details, see thequeryBalance API of the transaction_demo.

The following table lists the parameters of the queryBalance API.

- Parameter Type Description

Input addr string Account address

Output cipherbalance string Ciphertext of the accountbalance

Output err error Error message

Money Transfer● Input

Parameter Type Description Mandatory orNot

AddrA string Address of user A (payer) Yes

AddrB string Address of user B (payee) Yes

txinfo String Transaction informationPrepareTxInfo

Yes

● Processing

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 38

Page 43: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

a. Obtain the current balances of users A and B (cipherBalanceAKeyABlockand cipherBalanceBKeyBBlock) from the ledger based on the accountaddresses.

b. Verify the validity of the certificates.newCipherBalanceA,newCipherBalanceB,newCipherTxA,newCipherTxB, err := pswapi_cc.ValidateTxInfo(txInfo, cipherBalanceAKeyABlock, cipherBalanceBKeyBBlock) if err != nil { logger.Error("fail to validate trans information") return shim.Error("fail to validate trans information") }

c. Provide the updated balances (ciphertext).

The ledger content of a service needs to be customized. The encryptedbalance amount is added to the users' ledgers. A storage structure isdefined in the demo. After the storage structure is saved, a transactionrecord object is saved in JSON format.type TransRecord struct { FromAddr string ToAddr string TXType string Balance string TX string remark string }

5.7 Sample ApplicationThis section provides an example application code and the correspondingchaincode to describe the use of the homomorphic encryption library. The mainfunction of this application is money transfer between users, and thehomomorphic encryption library is used to protect the transfer transactioninformation of the users.

The application involves three steps: user registration (including initializing theusers' balances), money transfer, and balance query.

The application uses the command line interface (CLI) to perform serviceoperations. The procedure is as follows.

Note

Query the domain names of orderers and peers in the downloaded sdk.yaml file,and add "EIP + Domain name of each orderer" and "EIP + Domain name of eachpeer" to the /etc/hosts file. When Fabric v1.1 is used, set public network IPaddresses as the EIPs of peers. When Fabric1.4 is used, set private network IPaddresses for the peers. Otherwise, the network cannot be connected, causingtransaction verification failures.

Perform the following steps to add the domain name mapping of the orderers andpeers to the /etc/hosts file:

X.X.X.X orderer-e5ad7831affbe8e6e2e7984b098f92406930a688-0.orderer-e5ad7831affbe8e6e2e7984b098f92406930a688.default.svc.cluster.localX.X.X.X peer-d524b0817aaed85490368776cb88042a149a56b5-0.peer-d524b0817aaed85490368776cb88042a149a56b5.default.svc.cluster.localX.X.X.X peer-d524b0817aaed85490368776cb88042a149a56b5-1.peer-d524b0817aaed85490368776cb88042a149a56b5.default.svc.cluster.local

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 39

Page 44: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Use real EIPs to replace X.X.X.X.

RegistrationUsage: appdemo register [flags]Flags: -C, --channel string channel id (default "mychannel") -c, --config string configuration file path (default "./config_test.yaml") -I, --idcc string idendity chaincode name (default "IDChaincode") -i, --initbalance string init initbalance -o, --orgid string organization id (default "org1") -p, --protectpwd string protect pwd -T, --txcc string transaction chaincode name (default "TxChaincode") -u, --userid string user id ./appdemo register -u A -p test -i 100

NO TICE

If you do not set certain parameters, the default values are used. For the defaultvalues, see the Flags part. If a configured value is different from the default value,specify it for the parameter.

● Generating a pair of public and private keys for homogenous encryption

When a new user registers, a pair of public and private keys are generated for theuser (identified by the user ID). This demo writes the key pair to the local ${userid} .data file for each user.

privKeyStr, pubKeyStr, err := pswapi_sdk.GenerateKey(propwd)check(err)fmt.Println("key is nil")userdata.PubKey = pubKeyStruserdata.PriKey = privKeyStr

● Registering the public key

The Fabric SDK API is invoked to initiate registration with the IDChaincode,carrying the generated public key.

The registration is implemented using the chaincode function of blockchains. Public keysare registered for sharing. During the money transfer transaction, the public key of thepayer is used to encrypt the transaction data to protect privacy. Only the private key holdercan decrypt the transaction data.

res, err := sdk_client.Invoke(setup, "Register", [][]byte{[]byte(userdata.PubKey), []byte(senderAddr)}) if err != nil { fmt.Println("Fail to register user pk ", err.Error()) } else { addrByte := res[0].ProposalResponse.GetResponse().Payload fmt.Println("Register addr: ", string(addrByte)) }

● Registering the initial balance

a. The sdk.InitBalance API is used to initialize and encrypt the balance,generating the initial balanceinfo.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 40

Page 45: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

b. The balanceinfo is sent to the transaction chaincode.balanceInfo, err := pswapi_sdk.InitBalance(initbalance, userdata.PubKey) check(err)setup.ChainCodeID = txchaincode_, err = sdk_client.Invoke(setup, "init", [][]byte{[]byte(userdata.PubKey), []byte(balanceInfo)}) if err != nil { fmt.Println("Initbalance error for user: ", senderAddr, err.Error()) } else { fmt.Println("init balance successfully: ", senderAddr) } check(err)

TransactionUsage: appdemo transaction [flags]Flags: -b, --AddrB string B' addr -t, --Tx string Transaction Num -C, --channel string channel id (default "mychannel") -c, --config string configuration file path (default "./config_test.yaml") -I, --idcc string idendity chaincode name (default "IDChaincode") -o, --orgid string organization id (default "org1") -p, --protectpwd string protect pwd -T, --txcc string transaction chaincode name (default "TxChaincode") -u, --userid string user id ./appdemo transaction -u A -p test -b a0760184f7ed24e0d86f5b2df40a973a9e1b5da9a1ae886532ac9cd634b59d59 -t 10Note: The character string following -b is the account address of user B (displayed upon successful registration of user B).

QueryUsage: appdemo querybalance [flags]Flags: -C, --channel string channel id (default "mychannel") -c, --config string configuration file path (default "./config_test.yaml") -I, --idcc string idendity chaincode name (default "IDChaincode") -o, --orgid string organization id (default "org1") -p, --protectpwd string protect pwd -T, --txcc string transaction chaincode name (default "TxChaincode") -u, --userid string user id./appdemo querybalance -p test -u A

Query code:

1. The InitBalance API provided by the SDK is invoked to initialize the balance.2. The Fabirc SDK is invoked to send the transaction information.

get balance setup.ChainCodeID = txchaincode transRec := sdk_client.TransRecord{}

fmt.Println("query balance")

resps, err := sdk_client.Query(setup, "QueryBalance", [][]byte{[]byte(addrA)}) if err != nil { fmt.Println("Fail to query balance :", err.Error()) return err }

err = json.Unmarshal(resps[0].ProposalResponse.GetResponse().Payload, &transRec) if err != nil { fmt.Println("unmarshal query result error: ", err.Error()) return err }

decrypt balance

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 41

Page 46: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

curbalance, err := pswapi_sdk.Decrypt(transRec.Balance, userdata.PriKey, propwd) if err != nil { fmt.Println("sdk Decrypt error: ", err.Error()) return err }

fmt.Println("current balance:" + curbalance.String())

5.8 Transaction Verification with HomomorphicEncryption (Demo)

This demo is used only for scenario experience and is not used in actual applications.

Step 1 Buy a BCS service.

Select a 3.x.x version (corresponding to Fabric v1.4.0) for Version, and ECDSA forSecurity Mechanism

Step 2 Install and instantiate chaincodes.

Install and instantiate the demo chaincodes transaction.zip and IDChaincode.zip.

● To facilitate subsequent operations, name the chaincodes transaction and idchaincode.

● In the transaction script provided in the demo chaincode, the chaincode version is fixedat 1.0. During chaincode installation, enter 1.0 for the chaincode version.

● If you develop the chaincode by yourself, you can use the chaincode library interface fileapi_ahe_cc.tar.gz.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 42

Page 47: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 3 Download the certificate files.

Download the administrator certificates of the orderer and the peer.

Step 4 Download the SDK configuration file, and set the parameters as follows:● Chaincode Name: transaction● Chaincode Version: 1.0● Certificate Root Path: /home/paas

Step 5 Install Golang on the local server.

1. Download the installation package, upload it to the /usr/local directory onthe local server, and decompress the package.tar -zxvf go1.11.5.linux-amd64.tar.gz

2. Add the following environment variables to the /etc/profile file:export GOROOT=/usr/local/goexport PATH=$PATH:$GOROOT/bin

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 43

Page 48: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

export GOPATH=/opt/gopathexport PAAS_CRYPTO_PATH=/opt/haoexport PAAS_SSL_ROOT=/opt/hao

3. Run the following command to make the environment variables take effect:source /etc/profile

Step 6 Compile appdemo.

1. Go to the /opt/gopath directory (if this directory does not exist, create itmanually), and upload the SDK library, homomorphic encryption library,and OpenSSL library. Run the following command to decompress thepackages to the current directory:tar -zxvf xxx

2. Go to the /opt/gopath/src/ahe/PSW/deps/lib directory and copy the files inthe directory to the /usr/local/include/openssl/ directory (if this directorydoes not exist, create it manually).

3. Go to the /opt/gopath/src/ahe/PSW/example/appdemo/ directory and runthe go build command to compile the appdemo file.

Step 7 Generate an image.

1. Create a folder, for example, mkdir cj, in the /home/paas/ directory togenerate an image.

2. In the /home/paas/cj directory, upload the administrator certificatesdownloaded in Step 3, and copy the appdemo file compiled in Step 6.3,OpenSSL library, SDK library, and Dockerfile to the current directory anddecompress them.

After decompression, add libltdl.so.7 and libltdl.so.7.3.0 to the /home/paas/cj/openssl directory.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 44

Page 49: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

3. Run the unzip xxx.zip command to decompress the administrator certificatesof the orderer and peers. Move the decompressed certificate files respectivelyto the /home/paas/cj/orderer and /home/paas/cj/peer directories (if thedirectories do not exist, create them manually).

4. Decompress the SDK configuration file downloaded in Step 4 to obtaina .yaml file and modify the certificate path configuration in the file.For example:

a. Change the peer domain name address in the cryptoPath configurationunder organizations to the peer address shown in the following figure.

b. Check the paths of the decompressed certificate. After the modification,the SDK configuration file does not contain paths with hash values.

c. Delete the code in the certificateAuthorities section from the SDKconfiguration file, save the file, and upload the file to the /home/paas/cjdirectory.

The following is an example of the modified SDK configuration file:name: "global-trade-network"

x-type: "hlfv1"x-loggingLevel: info

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 45

Page 50: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

description: "The network to be in if you want to stay in the global trade business"

version: 1.0.0

client:

organization: aa73c757c9026fb623495d7058ca177f6152bcea

logging: level: info

peer: timeout: connection: 10s queryResponse: 45s executeTxResponse: 120s eventService: timeout: connection: 10s registrationResponse: 50s orderer: timeout: connection: 10s response: 45s

cryptoconfig: path: /opt/gopath/src/github.com/hyperledger/fabric

credentialStore: path: "/tmp/hfc-kvs"

cryptoStore: path: /tmp/msp

wallet: wallet-name

BCCSP: security: enabled: true default: provider: "SW" hashAlgorithm: "SHA2" softVerify: true ephemeral: false level: 256

channels:

tongtai: orderers:

- orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9-0.orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9.default.svc.cluster.local

peers:

peer-aa73c757c9026fb623495d7058ca177f6152bcea-0.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local:30605: endorsingPeer: true chaincodeQuery: true ledgerQuery: true eventSource: true

peer-aa73c757c9026fb623495d7058ca177f6152bcea-1.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local:30606: endorsingPeer: true chaincodeQuery: true ledgerQuery: true

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 46

Page 51: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

eventSource: true

chaincodes: - transaction:1.0

organizations:

aa73c757c9026fb623495d7058ca177f6152bcea: mspid: aa73c757c9026fb623495d7058ca177f6152bceaMSP

cryptoPath: /home/paas/peer/msp tlsCryptoKeyPath: /home/paas/peer/tls/server.key tlsCryptoCertPath: /home/paas/peer/tls/server.crt

peers:

- peer-aa73c757c9026fb623495d7058ca177f6152bcea-0.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local:30605

- peer-aa73c757c9026fb623495d7058ca177f6152bcea-1.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local:30606

certificateAuthorities: - ca-org1

ordererorg: mspID: "2cf8802066c1c5011fd396c54c9126a17c9cfcc9MSP"

cryptoPath: /home/paas/orderer/msporderer-eip: 49.4.81.160orderers:

orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9-0.orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9.default.svc.cluster.local: url: grpcs://49.4.81.160:30805

grpcOptions: ssl-target-name-override: orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9-0.orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9.default.svc.cluster.local grpc-max-send-message-length: 15

tlsCACerts: path: /home/paas/orderer/msp/tlscacerts/tlsca.2cf8802066c1c5011fd396c54c9126a17c9cfcc9-cert.pem

peers:

peer-aa73c757c9026fb623495d7058ca177f6152bcea-0.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local:30605:

url: grpcs://49.4.81.160:30605

grpcOptions: ssl-target-name-override: peer-aa73c757c9026fb623495d7058ca177f6152bcea-0.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local grpc.http2.keepalive_time: 15

tlsCACerts: path: /home/paas/peer/msp/tlscacerts/tlsca.aa73c757c9026fb623495d7058ca177f6152bcea-cert.pem

peer-aa73c757c9026fb623495d7058ca177f6152bcea-1.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local:30606:

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 47

Page 52: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

url: grpcs://49.4.81.160:30606

grpcOptions: ssl-target-name-override: peer-aa73c757c9026fb623495d7058ca177f6152bcea-1.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local grpc.http2.keepalive_time: 15

tlsCACerts: path: /home/paas/peer/msp/tlscacerts/tlsca.aa73c757c9026fb623495d7058ca177f6152bcea-cert.pem

5. Edit the Dockerfile file, changing the name of the .yaml file to the name ofthe SDK file.

6. In the /home/paas/cj/ directory, run the following commands to package allfiles into an image:docker build -t tongtaidemotest:byl1 . docker save tongtaidemotest:byl1>tongtaitest.tar

Ensure that the EulerOS 2.2.5 image already exists on the local PC. Otherwise, thepackaging will fail.

Step 8 Upload the image.

1. Download the packaged image to the local PC. Log in to HUAWEI CLOUD andgo to the CCE console. Create a Deployment in the cluster where the BCSservice is deployed, setting the instance quantity to 1.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 48

Page 53: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

2. In the Add Container step, click Add Container.

3. Click Upload a container image. You will be redirected to the SoftwareRepository for Container (SWR) console to upload an image.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 49

Page 54: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

4. Select the packaged image file and wait until the upload is complete.

5. After the image is uploaded, the Create Deployment page is displayed.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 50

Page 55: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

6. In the Lifecycle section, set the Start Command.– Command: /bin/sh– Args:

-csleep 10000(Enter the arguments in two lines as shown in the following figure.)

7. Click Next and retain the default settings until the Deployment is createdsuccessfully.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 51

Page 56: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 9 Verify transactions.

1. Log in to the ECS where the cluster is deployed and run the followingcommand to check whether the application container is normal:docker ps -a | grep tongtai |grep container

2. You can view the name of the deployed application. Run the followingcommand to access the container:docker exec -it Container id bash

3. Add the domain name mapping between the orderer and peers to the /etc/hosts file.Query the domain names of the orderer and peers in the downloadedsdk.yaml file, and add "Private IP address + Domain name of orderer" and"Private IP address + Domain name of each peer" to the end of the /etc/hostsfile, as shown in the following figure:

x.x.x.x orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9-0.orderer-2cf8802066c1c5011fd396c54c9126a17c9cfcc9.default.svc.cluster.localx.x.x.x peer-aa73c757c9026fb623495d7058ca177f6152bcea-0.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.localx.x.x.x peer-aa73c757c9026fb623495d7058ca177f6152bcea-1.peer-aa73c757c9026fb623495d7058ca177f6152bcea.default.svc.cluster.local

4. Run the following command to configure environment variables and view theregistration command:export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/paas/opensslcd /home/paas./appdemo register -h

– If you log out of the container during demo transactions, run the environmentvariable configuration command again when logging in to the container next time.

– In the preceding command, ./appdemo register -h is used to view the registrationcommand parameters.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 52

Page 57: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

----End

Demo 1: Registering Accounts

Step 1 Run the following command to register account B with a balance of 100:./appdemo register -u B -p tongtaitestB -i 100 -c ./test-sdk-config.yaml -C tongtai -I idchaincode -T transaction -o aa73c757c9026fb623495d7058ca177f6152bcea

-u indicates the registered user name B.

-p indicates user B's password.

-c indicates the SDK configuration file name.

-C indicates the channel name for installing the chaincode.

-I indicates the actual chaincode name for installing the demo chaincode IDChaincode.

-T indicates the actual chaincode name for installing the demo chaincode Transaction.

-o indicates the organization ID of the peer, which can be queried on the ChannelManagement page.

The parameter description is the same in the following demos.

The returned value is an encrypted address, for example:

b22edf18d64f57954640c8f3f6cf67d9401f262daead588ddfexxxxx

Step 2 Repeat the previous step to register account A with a balance of 200../appdemo register -u A -p tongtaitestA -i 200 -c ./test-sdk-config.yaml -C tongtai -I idchaincode -T transaction -o aa73c757c9026fb623495d7058ca177f6152bcea

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 53

Page 58: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

The returned value is an encrypted address, for example:

2efc4639bc281060ce013dfea33a47b647b6f4a20103a6321c33dxxxxxx

----End

Demo 2: Account A Transfers Money to Account B

Step 1 Run the following command to transfer money (10) from A to B:./appdemo transaction -u A -p tongtaitestA -b b22edf18d64f57954640c8f3f6cf67d9401f262daead588ddfe8178xxxx -t 10 -c ./test-sdk-config.yaml -C tongtai -I idchaincode -T transaction -o aa73c757c9026fb623495d7058ca177f6152bcea

The random number in red is the return value of user B, that is, the address of user B.

The return value is the address of account A:2efc4639bc281060ce013dfea33a47b647b6f4a20103a6321c33d67d5xxxx.

----End

Demo 3: Querying the Account Balance

Step 1 Run the following command to query the balance of account A. The returnedvalue is the balance of account A.

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 54

Page 59: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

./appdemo querybalance -p tongtaitestA -u A -c ./test-sdk-config.yaml -C tongtai -I idchaincode -T transaction -o aa73c757c9026fb623495d7058ca177f6152bcea

Step 2 Run the following command to query the balance of account B. The returnedvalue is the balance of account B../appdemo querybalance -p tongtaitestB -u B -c ./test-sdk-config.yaml -C tongtai -I idchaincode -T transaction -o aa73c757c9026fb623495d7058ca177f6152bcea

----End

Demo 4: Querying the Total Balance of Accounts A and B

Step 1 Run the following command to query the total balance of accounts A and B:./appdemo homoadd -c ./test-sdk-config.yaml -C tongtai -T transaction -o aa73c757c9026fb623495d7058ca177f6152bcea

----End

Blockchain ServiceDeveloper Guide 5 Homomorphic Encryption

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 55

Page 60: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

6 Demos

6.1 Java SDKsThis section provides a demo application that uses a Java SDK and supports theChinese cryptographic algorithms.

This demo is used only for scenario experience and is not used in actual applications.

Preparation

Action Description

Install anintegrateddevelopmentenvironment(IDE).

Install Java Development Kit (JDK), Maven, and Eclipse. Youcan replace Eclipse with another IDE you prefer.The JDK version must be 1.8 (64-bit). If you have installedJDK, run the java -version command in the command lineto check the JDK version.

Buying a BCS Service

Step 1 Log in to the BCS console.

Step 2 Click Buy BCS Service in the upper right corner of the page and set theparameters.

Table 6-1 Parameters

Parameter Setting

Billing Mode Select Pay-per-use.

Region Retain the default value.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 56

Page 61: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Enterprise Project Select an existing enterprise project, forexample, default.If you have not enabled the enterprisemanagement service, this parameter isunavailable.

Service Name Enter java-sdk-demo.

Edition Select Basic. If Chinese cryptographicalgorithms must be used, select Enterprise.

Blockchain Type Select Private.

Consensus Mechanism Select Solo.

Resource Access InitialPassword

Enter a password.

Confirm Password Enter the password again.

Advanced Settings Select Configure.

Cluster Select Create a new CCE cluster.

AZ Select an AZ.

ECS Specifications Select the flavor of 4 vCPUs | 8 GB.

ECS Quantity Enter 1.

High Availability Select No.

VPC Select Automatically create VPC.

Subnet Select Automatically create subnet.

ECS Login Method Select Password.

Password of Root User If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Blockchain Mgmt. InitialPassword

If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Version Retain the default value.

Volume Type Select SFS.

Peer Organization A peer organization named organization hasbeen automatically created. Change the peerquantity to 1.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 57

Page 62: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Orderer Quantity Retain the default value 1.

Enable Data Aging onOrderers

Select No.

Security Mechanism Select ECDSA.NOTICE

The Chinese cryptographic algorithms option isavailable. If you select this option, othermodifications are required for the demo deployment.Pay attention to the descriptions of modifications.

Storage Capacity of PeerOrganization

Retain the default value.

Ledger Storage Select File database (goleveldb).

Channel Configuration The organization organization has been addedto the channel automatically. Retain thisdefault setting.

Enable Support for RESTfulAPIs

Select No.

Use EIP Select Yes.

EIP Billed By Select Bandwidth.

EIP Bandwidth Retain the default value.

Configure Block Generation Select No.

Step 3 Click Next, confirm the configurations, and click Submit. If the status of theservice and organization is Normal, the service has been successfully created.

----End

Installing and Instantiating a Chaincode

Step 1 Click Manage Blockchain in the Operation column of the BCS service you justcreated.

Step 2 On the login page, enter the username, password, and verification code, and clickLog In.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 58

Page 63: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

The username is admin, and the password is the Blockchain Mgmt. Initial Password setwhen you bought the BCS service. If you have not set this password, use the resource accessinitial password.

Step 3 Click in the upper left corner of the page.

The parameters for chaincode installation are as follows.

Parameter Setting

Chaincode Name Enter chaincode.

Chaincode Version Enter 2.0.

Ledger Storage File database (goleveldb)

Select All Peers Select the checkbox.

Organization & Peer Select peer-0.

Language Select Golang.

Chaincode File Add the downloaded chaincode filechaincode_example02.zip.

Chaincode Description Enter a description of the chaincode.

Step 4 Click Install to install the chaincode.

Step 5 After installing the chaincode, click Instantiate in the Operation column of thechaincode list.

The parameters for chaincode instantiation are as follows.

Parameter Setting

Chaincode Name chaincode

Channel Select channel.

Chaincode Version Select 2.0.

Initialization Function Enter init.

Chaincode Parameters Enter a,200,b,250.

Endorsement Policy Select Endorsement from any of thefollowing organizations.

Endorsing Organizations Select organization.

Privacy Protection Select No.

Step 6 Click Instantiate.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 59

Page 64: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Wait for 2 to 3 minutes and refresh the page. Click View more in theInstantiation column to check the instantiation status.

----End

Configuring the Application1. Import the project.

Download and decompress the project code. Right-click in Eclipse and chooseImport from the shortcut menu to import the javasdkdemo file (Mavenproject) to Eclipse.

2. Download the SDK configuration.

Click More > Download SDK Configuration in the Operation column on theService Management page.

Set the SDK file parameters.

Parameter

Setting

ChaincodeName

Enter chaincode.NOTICE

The chaincode name and version must be the same as those specified forchaincode installation and instantiation.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 60

Page 65: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter

Setting

ChaincodeVersion

Enter 2.0.

Certificate RootPath

Enter the path to the config folder of the javasdkdemo project.NOTICE

Backslashes (\) in the path must be changed to slashes (/), for example,D:/javasdkdemo/config.

Channel channel

Member Retain the default value.

Click Download and the SDK file will be saved to the config directory of thedemo project. The file name is java-sdk-demo-sdk-config.zip.

The Certificate Root Path specified in the SDK configuration parameters is not thedownload path of the SDK file. If you do not specify a path for downloading the SDKfile, the SDK file will be stored in the default download path of your system.

3. Download certificates.Download the administrator certificates of organizations java-sdk-demo-orderer and organization on the Service Management page, and save themto the config directory of the demo project.

4. Copy and decompress the packages.If no download path is specified, copy organization-admin.zip, java-sdk-demo-orderer-admin.zip, and java-sdk-demo-channel-sdk-config.zip fromthe default download path to the config directory of the demo project anddecompress the packages.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 61

Page 66: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Deploying the Application

Step 1 Find the Main.java file in the /javasdkdemo/src/main/java/handler/ directory,and change the file path in the following code of the Main class to the absolutepath of the java-sdk-demo-sdk-config.yaml file. Change the backslashes (\) toslashes (/).helper.setConfigCtx("E:/yourdir/huawei.yaml");

NO TICE

If Chinese cryptographic algorithms is selected for the BCS service, add thedependency upon fabric-sdk-java-1.4.0-jar-with-dependencies.jar in the libfolder of the project to pom.xml because Chinese cryptographic algorithms needto refer to the fabric-sdk dependency package of Huawei. To add the dependency,remove the comments on the dependency as shown in the following figure.

Step 2 Run the main function.

Each execution of the main function represents a transaction in which user Atransfers money (100) to user B, as shown in the following figure.

----End

6.2 MySQL SDKsThis topic uses a MySQL SDK-based demo application as an example to describehow to configure an application to enable connection to BCS and successfulrunning.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 62

Page 67: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

This demo is used only for scenario experience and is not used in actual applications.

Procedure

Step 1 Log in to the BCS console.

Click Buy BCS Service in the upper right corner of the page and set theparameters.

Table 6-2 Parameters

Parameter Setting

Billing Mode Select Pay-per-use.

Region Retain the default value.

Service Name Enter demo.

Edition Select Basic. If Chinese cryptographicalgorithms must be used, select Enterprise.

Blockchain Type Select either Private or Consortium.

Consensus Mechanism Select Solo.

Resource Access InitialPassword

Enter a password.

Confirm Password Enter the password again.

Advanced Settings Select Configure.

Cluster Select Create a new CCE cluster.

AZ Select an AZ.

ECS Specifications Select the flavor of 4 vCPUs | 8 GB.

ECS Quantity Enter 1.

High Availability Select No.

VPC Select Automatically create VPC.

Subnet Select Automatically create subnet.

ECS Login Method Select Password.

Password of Root User If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 63

Page 68: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Blockchain Mgmt. InitialPassword

If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Version Select a 2.X.X version (corresponding to Fabricv1.1.0).NOTE

This demo describes only the operation procedure forFabric v1.1.0.

Volume Type Select SFS.

Peer Organization Change the name of the automatically createdpeer organization to xxx1 and the peerquantity to 2.Select an existing RDS instance, and use theusername root and the password specifiedwhen the RDS instance was created.

Orderer Quantity Retain the default value 1.

Enable Data Aging onOrderers

Select No.

Security Mechanism Select ECDSA.NOTICE

The Chinese cryptographic algorithms option isavailable. If this option is selected,certain configurations of the demo application mustbe modified. Pay attention to the followingdescriptions.

Storage Capacity of PeerOrganization

Retain the default value.

Ledger Storage Select Relational database (MySQL).

Channel Configuration The xxx1 peer organization has been added tothe channel automatically. Retain this defaultsetting.

Enable Support for RESTfulAPIs

Select No.

Use EIP Select Yes.

EIP Billed By Select Bandwidth.

EIP Bandwidth Retain the default value.

Configure Block Generation Select No.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 64

Page 69: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Click Next, confirm the configurations, and click Submit. If the status of theservice and organization is Normal, the service has been successfully created.

Step 2 Click Manage Blockchain in the Operation column of the BCS service you justcreated.

On the login page, enter the username, password, and verification code, and clickLog In.

The username is admin, and the password is the Blockchain Mgmt. Initial Password setwhen you bought the BCS service. If you have not set this password, use the resource accessinitial password.

Step 3 Click in the upper left corner of the page.

The parameters for chaincode installation are as follows.

Parameter Setting

Chaincode Name bcsysq

Chaincode Version Enter 1.0.

Ledger Storage Select Relational database (MySQL).

Select All Peers Select the checkbox.

Organization & Peer Select peer-0.

Language Select Golang.

Chaincode File Add the downloaded chaincode fileaccount.zip.

Chaincode Description Enter a description of the chaincode.

Step 4 After installing the chaincode, click Instantiate in the Operation column of thechaincode list.

The parameters for chaincode instantiation are as follows.

Parameter Setting

Channel Select channel.

Chaincode Version Select 1.0.

Initialization Function Enter init.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 65

Page 70: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Chaincode Parameters Enter a,200,b,250.

Endorsement Policy Select Endorsement from any of thefollowing organizations.

Endorsing Organizations Select xxx1.

Privacy Protection Select No.

Step 5 Download the administrator certificates of the orderer and organization xxx1 onthe Service Management page.

Step 6 Download and decompress the SDK configuration file.

Step 7 Click More > Download SDK Configuration in the Operation column on theService Management page.

Set the SDK file parameters.

Parameter Setting

Chaincode Name Enter account.NOTICE

The chaincode name and version must be the same as thosespecified for chaincode installation and instantiation.

ChaincodeVersion

Enter 1.0.

Certificate RootPath

Specify a root path for storing certificates. In this example,the root path is src/main/fixture/chanmel.

Channel channel

Member Retain the default value.

Click Download and the file will be saved to the default download path of yoursystem.

Step 8 Modify the downloaded SDK configuration.

Add adminPrivateKey and signedCert, and set the path based on the certificatestorage path. The following figure shows an example after the modification.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 66

Page 71: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 9 Download the MySQL SDK demo package (Maven project) and import thepackage to Eclipse.

Project structure description:

● The storage path of the SDK configuration file is fixed to src/main/fixture/config.

● The file name can be set to any value.In the following figure, network-config.yaml in the config directory is anSDK configuration file.

● The peer and orderer certificates can be placed anywhere in the project, buttheir locations must be the same as those specified in the SDK configurationfile.As shown in the following figure, two certificates are located in the src/main/fixture/channel directory.

Step 10 Save the two downloaded certificates to the directory specified by the code, anddecompress them.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 67

Page 72: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 11 Save the modified SDK configuration file to src/main/fixture/config.

Step 12 Execute FabricJDBCWorkflowTest.java under src\test\java\com\huawei\fabricsql\jdbc to transfer money.

----End

6.3 RESTful APIsHUAWEI CLOUD BCS provides RESTful APIs to simplify the usage of blockchains.You only need to develop applications that support RESTful APIs to accessblockchains without the need to learn Hyperledger Fabric SDKs for Golang, Java,and Node.js. This demo uses a Golang client to show how RESTful APIs are used toinvoke a chaincode.

This demo is used only for scenario experience and is not used in actual applications.

Creating a BCS Service

Step 1 Log in to the BCS console.

Step 2 Click Buy BCS Service in the upper right corner of the page and set theparameters.

Parameter Setting

Billing Mode Select Pay-per-use.

Region Retain the default value.

Service Name Enter demo.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 68

Page 73: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Edition Select Basic or Professional.

Blockchain Type Select Private.

Consensus Mechanism Select Solo.

Resource Access InitialPassword

Enter a password.

Confirm Password Enter the password again.

Advanced Settings Select Configure.

Cluster Select Create a new CCE cluster.

AZ Select an AZ.

ECS Specifications Select the flavor of 4 vCPUs | 8 GB.

ECS Quantity Enter 1.

High Availability Select No.

VPC Select Automatically create VPC.

Subnet Select Automatically create subnet.

ECS Login Method Select Password.

Password of Root User If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Blockchain Mgmt. InitialPassword

If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Version Select the latest version.

Volume Type Select SFS.

Peer Organization A peer organization named organization with2 peers has been automatically created. Retainthe default settings.NOTE

If multiple organizations are involved in the service,you can select Professional for the Edition.

Orderer Quantity Retain the default value 1.

Enable Data Aging onOrderers

Select No.

Security Mechanism Only ECDSA can be selected.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 69

Page 74: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Storage Capacity of PeerOrganization

Retain the default value.

Ledger Storage Select File database (goleveldb).

Channel Configuration The organization organization has been addedto the channel automatically. Retain thisdefault setting.

Enable Support for RESTfulAPIs

Select Yes. If you select No, choose More >Enable Support for RESTful APIs in theOperation column on the ServiceManagement page to install RESTful APIs,after the service is created.

Use EIP Select Yes.

EIP Billed By Select Bandwidth.

EIP Bandwidth Set it to 5 Mbit/s.

Configure Block Generation Select No.

Click Next, confirm the configurations, and click Submit. If the status of theservice and organization is Normal, the service has been successfully created.

----End

Installing and Instantiating a Chaincode

Step 1 Click Manage Blockchain in the Operation column of the BCS service you justcreated.

Step 2 On the login page, enter the username, password, and verification code, and clickLog In.

The username is admin, and the password is the Blockchain Mgmt. Initial Password setwhen you bought the BCS service. If you have not set this password, use the resource accessinitial password.

Step 3 Click in the upper left corner of the page.

The parameters for chaincode installation are as follows.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 70

Page 75: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Chaincode Name Enter bcsysq.

Chaincode Version Enter 1.0.

Ledger Storage File database (goleveldb)

Select All Peers Select the checkbox.

Organization & Peer Select peer-0.

Language Select Golang.

Chaincode File Add the downloaded chaincode filechaincode_example02.zip.

Chaincode Description Enter a description of the chaincode.

Step 4 Click Install to install the chaincode.

Step 5 After installing the chaincode, click Instantiate in the Operation column of thechaincode list.

The parameters for chaincode instantiation are as follows.

Parameter Setting

Channel Select channel.

Chaincode Version Select 1.0.

Initialization Function Enter init.

Chaincode Parameters Enter a,200,b,250.

Endorsement Policy Select Endorsement from any of thefollowing organizations.

Endorsing Organizations Select organization.

Privacy Protection Select No.

----End

Configuring the Application

Step 1 On the Service Management page, download the user certificate of the peerorganization organization to the default local path.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 71

Page 76: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 2 Download and decompress the demo project code package fabric-restapi-demo.zip to the local PC, and use an IDE to open it.

This demo project is a RESTful client compiled using Golang. It enables chaincodeinvocation through RESTful APIs to achieve chaincode-based money transfer. Usean IDE such as GoLand to open the package. The following figure shows thecontent of the project.

Step 3 Decompress the downloaded user certificate to the usercrypto directory of theproject, as shown in the following figure.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 72

Page 77: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 4 Modify parameter settings.

1. Modify the parameters in the conf.yaml file in the config directory as shownand described in the following figure and tables.

2. Modify the main.go file in the src/restapi directory, as shown in the followingfigure and tables.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 73

Page 78: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

For each peer that needs to participate in the endorsement, construct an OrgPeerstructure including the organization ID and the domain name of the peer. Add thestructure to an array of the OrgPeer type, convert the structure into a byte array usingthe json.Marshal() method, and then convert the structure into a character string. TheOrgPeer structure is as follows:type OrgPeer struct {OrgId string `json:"orgId"`PeerDomainName string `json:"peerDomainName"`}

Table 6-3 Parameters

Parameter Description

Endpoint IP address and port number used to access RESTfulAPIs. To obtain an IP address, locate the service on theService Management page, and choose More > ViewService Details in the Operation column. The portnumber is always 32621.

Path Path to the RESTful APIs service. Retain the defaultvalue.

CryptoMethod Encryption algorithm. If the ECDSA algorithm is used,set this parameter to SW.

SignCert Path to the signature in the downloaded certificate

PrvKey Private key in the downloaded certificate

InvokeReq Request body parameters. Set these parameters basedon the deployed chaincode. The InvokeReq parameterdescriptions in the following table are for yourreference.

QueryReq Similar to InvokeReq. Set this parameter based on thedeployed chaincode.

Table 6-4 InvokeReq parameters

Parameter Description Example Value

SignGzipSwitch

Indication ofwhether GZIPcompression isenabled. 0indicates disabling,and 1 indicatesenabling.

1

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 74

Page 79: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Description Example Value

ChannelId Blockchain channelID

c123456

ChaincodeId Chaincode ID testcode

ChaincodeVersion

Chaincode version 1.0

UserId User ID issued bythe organization'sCA. The defaultvalue for BCS isUser1.

User1

OrgId Organization ID ina blockchain

1232b2032faafee152b58cd82cecf52e49a22a38

OrgPeers Organization IDand domain nameof each peer

"[{OrgId:"1232b2032faafee152b58cd82cecf52e49a22a38",PeerDomainName:"peer-1232b2032faafee152b58cd82cecf52e49a22a38-0.peer-1232b2032faafee152b58cd82cecf52e49a22a38.default.svc.cluster.local "}]"

Opmethod Purpose, that is, toinvoke or querychaincodes.

invoke

Args Chaincodeinvokingparameters

["invoke","a","b","100"]

Step 5 Build and run main().

The code will read the QueryReq and InvokeReq parameters in conf.yaml andmain.go and call /v1/chaincode/operation of the RESTful APIs to invoke thechaincode. The code running result is as follows.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 75

Page 80: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

This demo uses a simple REST client to invoke the chaincode through RESTful APIs. Thereturned invocation result is TransactionID encrypted using Base64, and the query result isdata encrypted using Base64. The code is for reference only. You can use this project codeto understand how to invoke RESTful APIs.

----End

6.4 Node.js SDKsThis demo provides a Node.js chaincode and a program that uses the HyperledgerFabric SDK for Node.js (fabric-nodejs-sdk) to invoke the chaincode to describe howto use a Node.js SDK to access the BCS. For details about the APIs of HyperledgerFabric SDK for Node.js, visit https://fabric-sdk-node.github.io/release-1.3/index.html.

This demo is used only for scenario experience and is not used in actual applications.

PreparationStep Action Description

1 Install adevelopmenttool.

Download and install the Node.js source code.

2 Download thedemo projectcode.

Project code: nodejs-demo.zip

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 76

Page 81: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Creating a BCS Service

Step 1 Log in to the BCS console.

Step 2 Click Buy BCS Service in the upper right corner of the page and set theparameters.

Parameter Setting

Billing Mode Select Pay-per-use.

Region Retain the default value.

Service Name Enter node-sdk-demo.

Edition Select Basic.

Blockchain Type Select Private.

Consensus Mechanism Select Solo.

Resource Access InitialPassword

Enter a password.

Confirm Password Enter the password again.

Advanced Settings Select Configure.

Cluster Select Create a new CCE cluster.

AZ Select an AZ.

ECS Specifications Select the flavor of 4 vCPUs | 8 GB.

ECS Quantity Enter 1.

High Availability Select No.

VPC Select Automatically create VPC.

Subnet Select Automatically create subnet.

ECS Login Method Select Password.

Password of Root User If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Blockchain Mgmt. InitialPassword

If you do not enter a password here, thepreviously specified resource access initialpassword will be used.

Confirm Password -

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 77

Page 82: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Version Select a 2.X.X version (corresponding to Fabricv1.1.0).NOTE

This demo describes only the operation procedure forFabric v1.1.0.

Volume Type Select SFS.

Peer Organization A peer organization named organization hasbeen automatically created. Change the peerquantity to 1.

Orderer Quantity Retain the default value 1.

Enable Data Aging onOrderers

Select No.

Security Mechanism Select ECDSA.

Storage Capacity of PeerOrganization

Retain the default value.

Ledger Storage Select File database (goleveldb).

Channel Configuration The organization organization has been addedto the channel automatically. Retain thisdefault setting.

Enable Support for RESTfulAPIs

Select No.

Use EIP Select Yes.

EIP Billed By Select Bandwidth.

EIP Bandwidth Set it to 5 Mbit/s.

Configure Block Generation Select No.

Click Next, confirm the configurations, and click Submit. If the status of theservice and organization is Normal, the service has been successfully created.

----End

Installing and Instantiating ChaincodesStep 1 Click Manage Blockchain in the Operation column of the BCS service you just

created.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 78

Page 83: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 2 On the login page, enter the username, password, and verification code, and clickLog In.

The username is admin, and the password is the Blockchain Mgmt. Initial Password setwhen you bought the BCS service. If you have not set this password, use the resource accessinitial password.

Step 3 Click in the upper left corner of the page.

The parameters for chaincode installation are as follows.

Parameter Setting

Chaincode Name Enter bcsysq.

Chaincode Version Enter 1.0.

Ledger Storage File database (goleveldb)

Select All Peers Select the checkbox.

Organization & Peer Select peer-0.

Language Select Node.js.

Chaincode File Add the downloaded chaincode file nodejs-chaincode.zip.

Chaincode Description Enter a description of the chaincode.

Step 4 Click Install to install the chaincode.

Step 5 After installing the chaincode, click Instantiate in the Operation column of thechaincode list.

The parameters for chaincode instantiation are as follows.

Parameter Setting

Chaincode Name bcsysq

Channel Select channel.

Chaincode Version Select 1.0.

Initialization Function Enter init.

Chaincode Parameters Enter a,200,b,250.

Endorsement Policy Select Endorsement from any of thefollowing organizations.

Endorsing Organizations Select organization.

Privacy Protection Select No.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 79

Page 84: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

----End

Deploying the Application

Step 1 Download the administrator certificates of the organizations node-sdk-demo-orderer and organization on the Service Management page, and save them tothe default local path.

Step 2 Download and decompress the demo project code package nodejs-demo.zip tothe local PC, and use an IDE to open it.

This demo is compiled using Node.js. It contains the fabric-client library to enablemoney transfer from user A to user B by running the chaincode. Use the IDE thatyou prefer to open the script. The following table lists the files included in theproject.

Table 6-5 Project content

File Description

invoke.js Invoking the chaincode to transfer money from user Ato user B.

query.js Querying the chaincode to determine the accountbalance of user A.

sdk-config.js Parsing the blockchain network configuration file sdk-config.json downloaded from the BCS console.

sdk-config.json Containing the blockchain network configuration data.

Step 3 Click More > Download SDK Configuration in the Operation column on theService Management page, and set the parameters.

Set the SDK file parameters.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 80

Page 85: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Parameter Setting

Chaincode Name Enter bcsysq.NOTICE

The chaincode name and version must be the same as thosespecified for chaincode installation and instantiation.

Chaincode Version Enter 1.0.

Certificate RootPath

Specify a root path for storing certificates. In this example,the root path is E:\code\temp.

Channel Select channel.

Member Retain the default value.

Step 4 Click Download. The downloaded file is node-sdk-demo-sdk-config.zip. Copy thefile to the path where the certificates are stored.

Step 5 Decompress the downloaded packages organization-admin.zip, node-sdk-demo-order-admin.zip, and node-sdk-demo-sdk-config.zip, and copy thedecompressed certificates (folders) and SDK configuration file (a .json file) asshown in the following figure.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 81

Page 86: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

----End

Debugging the Application

Step 1 Open the sdk-config.js file, and change the path of the SDK configuration file tothe path of node-sdk-demo-sdk-config.json.

Step 2 Run the node query.js command in the path where the project is located to querythe account balance of user A. (As shown in the following figure, user A's balanceis 10,000 in this example.)

Step 3 Run the node invoke.js command in the path where the project is located toexecute the chaincode to transfer money from user A to user B. As shown in thefollowing figure, the chaincode is successfully executed.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 82

Page 87: Developer Guide - HUAWEI CLOUDpreparation of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this document do not constitute

Step 4 Query the account balance of user A again. The result shows that the money hasbeen successfully transferred. (As shown in the following figure, user A's balance is9,990 in this example.)

----End

Note● This demo uses demos in the Fabric community as references. For more

demos, visit https://github.com/hyperledger/fabric-samples.● Method of customizing an npm repository in the chaincode

– Create a personal configuration file named .npmrc in the path of thechaincode package. The content of the file is as follows: Registry=https://registry.npm.taobao.org/

– In this way, when the chaincode container is instantiated, the class libraryis extracted from the specified repository.

– Run the npm config get registry command to check whether theaddress of the customized npm repository has been correctly configured.

Blockchain ServiceDeveloper Guide 6 Demos

Issue 01 (2020-04-21) Copyright © Huawei Technologies Co., Ltd. 83