Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

24.5. fabric-samples

安裝 fabric-samples

		
git clone https://github.com/hyperledger/fabric-samples.git
cd fabric-samples
		
	

fabric-samples 包含了很多例子,我們只運行幾個常用的例子。

24.5.1. test-network

進入fabric-samples/test-network目錄啟動 Hyperledger Fabric 2.0,測試網絡是否可用

		
[root@localhost ~]# cd fabric-samples/test-network/
[root@localhost ~]# ./network.sh up	
		
		

如果現實如下,恭喜!你的Hyperledger Fabric 2.0已經安裝成功!

		
Creating network "net_test" with the default driver
Creating volume "net_orderer.example.com" with default driver
Creating volume "net_peer0.org1.example.com" with default driver
Creating volume "net_peer0.org2.example.com" with default driver
Creating orderer.example.com    ... done
Creating peer0.org2.example.com ... done
Creating peer0.org1.example.com ... done
CONTAINER ID        IMAGE                               COMMAND             CREATED             STATUS                  PORTS                              NAMES
8d0c74b9d6af        hyperledger/fabric-orderer:latest   "orderer"           4 seconds ago       Up Less than a second   0.0.0.0:7050->7050/tcp             orderer.example.com
ea1cf82b5b99        hyperledger/fabric-peer:latest      "peer node start"   4 seconds ago       Up Less than a second   0.0.0.0:7051->7051/tcp             peer0.org1.example.com
cd8d9b23cb56        hyperledger/fabric-peer:latest      "peer node start"   4 seconds ago       Up 1 second             7051/tcp, 0.0.0.0:9051->9051/tcp   peer0.org2.example.com		
		
		

24.5.2. fabcar

			
cd fabric-samples/fabcar				
			
		

啟動

			
[root@localhost fabcar]# ./startFabric.sh 

# don't rewrite paths for Windows Git Bash users
export MSYS_NO_PATHCONV=1

docker-compose -f docker-compose.yml down
Stopping peer0.org1.example.com ... done
Stopping couchdb ... done
Stopping orderer.example.com ... done
Stopping ca.example.com ... done
Removing peer0.org1.example.com ... done
Removing couchdb ... done
Removing orderer.example.com ... done
Removing ca.example.com ... done
Removing network net_basic

docker-compose -f docker-compose.yml up -d ca.example.com orderer.example.com peer0.org1.example.com couchdb
Creating network "net_basic" with the default driver
Creating couchdb
Creating orderer.example.com
Creating ca.example.com
Creating peer0.org1.example.com

# wait for Hyperledger Fabric to start
# incase of errors when running later commands, issue export FABRIC_START_TIMEOUT=<larger number>
export FABRIC_START_TIMEOUT=10
#echo ${FABRIC_START_TIMEOUT}
sleep ${FABRIC_START_TIMEOUT}

# Create the channel
docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer channel create -o orderer.example.com:7050 -c mychannel -f /etc/hyperledger/configtx/channel.tx
2018-02-06 04:27:38.822 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:38.822 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:38.825 UTC [channelCmd] InitCmdFactory -> INFO 003 Endorser and orderer connections initialized
2018-02-06 04:27:38.825 UTC [msp] GetLocalMSP -> DEBU 004 Returning existing local MSP
2018-02-06 04:27:38.825 UTC [msp] GetDefaultSigningIdentity -> DEBU 005 Obtaining default signing identity
2018-02-06 04:27:38.826 UTC [msp] GetLocalMSP -> DEBU 006 Returning existing local MSP
2018-02-06 04:27:38.826 UTC [msp] GetDefaultSigningIdentity -> DEBU 007 Obtaining default signing identity
2018-02-06 04:27:38.826 UTC [msp/identity] Sign -> DEBU 008 Sign: plaintext: 0A88060A074F7267314D535012FC052D...53616D706C65436F6E736F727469756D 
2018-02-06 04:27:38.826 UTC [msp/identity] Sign -> DEBU 009 Sign: digest: D2F2DB3135CE892465FB7B6C2C89A6C566EC6E0081034AF00AF62014ED098E10 
2018-02-06 04:27:38.827 UTC [msp] GetLocalMSP -> DEBU 00a Returning existing local MSP
2018-02-06 04:27:38.827 UTC [msp] GetDefaultSigningIdentity -> DEBU 00b Obtaining default signing identity
2018-02-06 04:27:38.827 UTC [msp] GetLocalMSP -> DEBU 00c Returning existing local MSP
2018-02-06 04:27:38.827 UTC [msp] GetDefaultSigningIdentity -> DEBU 00d Obtaining default signing identity
2018-02-06 04:27:38.827 UTC [msp/identity] Sign -> DEBU 00e Sign: plaintext: 0ABF060A1508021A0608BADDE4D30522...4447D0A2A449E39255165BEE40760F3E 
2018-02-06 04:27:38.827 UTC [msp/identity] Sign -> DEBU 00f Sign: digest: BE32EAB1C6CE6A2C7F79FED4D1C646702EE07A3D64014B5EE2B77F8B35E9CF5F 
2018-02-06 04:27:38.935 UTC [msp] GetLocalMSP -> DEBU 010 Returning existing local MSP
2018-02-06 04:27:38.935 UTC [msp] GetDefaultSigningIdentity -> DEBU 011 Obtaining default signing identity
2018-02-06 04:27:38.935 UTC [msp] GetLocalMSP -> DEBU 012 Returning existing local MSP
2018-02-06 04:27:38.935 UTC [msp] GetDefaultSigningIdentity -> DEBU 013 Obtaining default signing identity
2018-02-06 04:27:38.935 UTC [msp/identity] Sign -> DEBU 014 Sign: plaintext: 0ABF060A1508021A0608BADDE4D30522...96444BF5E3AA12080A021A0012021A00 
2018-02-06 04:27:38.936 UTC [msp/identity] Sign -> DEBU 015 Sign: digest: 11D42E8978C507DC0C33304B81E089DB5DAB72967A153BD52932C5A4054C3D4B 
2018-02-06 04:27:38.937 UTC [channelCmd] readBlock -> DEBU 016 Got status: &{NOT_FOUND}
2018-02-06 04:27:38.937 UTC [msp] GetLocalMSP -> DEBU 017 Returning existing local MSP
2018-02-06 04:27:38.937 UTC [msp] GetDefaultSigningIdentity -> DEBU 018 Obtaining default signing identity
2018-02-06 04:27:38.939 UTC [channelCmd] InitCmdFactory -> INFO 019 Endorser and orderer connections initialized
2018-02-06 04:27:39.139 UTC [msp] GetLocalMSP -> DEBU 01a Returning existing local MSP
2018-02-06 04:27:39.139 UTC [msp] GetDefaultSigningIdentity -> DEBU 01b Obtaining default signing identity
2018-02-06 04:27:39.140 UTC [msp] GetLocalMSP -> DEBU 01c Returning existing local MSP
2018-02-06 04:27:39.140 UTC [msp] GetDefaultSigningIdentity -> DEBU 01d Obtaining default signing identity
2018-02-06 04:27:39.140 UTC [msp/identity] Sign -> DEBU 01e Sign: plaintext: 0ABF060A1508021A0608BBDDE4D30522...75CF3E958E8612080A021A0012021A00 
2018-02-06 04:27:39.140 UTC [msp/identity] Sign -> DEBU 01f Sign: digest: 26B8D88C16CF0DC0573F9BB9A69EC1BF1FEA8C12D052F832B3DB7B2A10D2CA6D 
2018-02-06 04:27:39.145 UTC [channelCmd] readBlock -> DEBU 020 Received block: 0
2018-02-06 04:27:39.146 UTC [main] main -> INFO 021 Exiting.....
# Join peer0.org1.example.com to the channel.
docker exec -e "CORE_PEER_LOCALMSPID=Org1MSP" -e "CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/msp/users/Admin@org1.example.com/msp" peer0.org1.example.com peer channel join -b mychannel.block
2018-02-06 04:27:39.465 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:39.465 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:39.467 UTC [channelCmd] InitCmdFactory -> INFO 003 Endorser and orderer connections initialized
2018-02-06 04:27:39.468 UTC [msp/identity] Sign -> DEBU 004 Sign: plaintext: 0A86070A5C08011A0C08BBDDE4D30510...2A0C0B6B1D4B1A080A000A000A000A00 
2018-02-06 04:27:39.468 UTC [msp/identity] Sign -> DEBU 005 Sign: digest: 455E4221B3AE6DD1238BF5C8893970131846C096F1465D4CA89385AF3C7C0B2F 
2018-02-06 04:27:39.991 UTC [channelCmd] executeJoin -> INFO 006 Peer joined the channel!
2018-02-06 04:27:39.991 UTC [main] main -> INFO 007 Exiting.....
Creating cli
2018-02-06 04:27:46.123 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:46.123 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:46.123 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-06 04:27:46.123 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-06 04:27:47.513 UTC [golang-platform] getCodeFromFS -> DEBU 005 getCodeFromFS github.com/fabcar
2018-02-06 04:27:48.448 UTC [golang-platform] func1 -> DEBU 006 Discarding GOROOT package bytes
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 007 Discarding GOROOT package encoding/json
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 008 Discarding GOROOT package fmt
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 009 Discarding provided package github.com/hyperledger/fabric/core/chaincode/shim
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 00a Discarding provided package github.com/hyperledger/fabric/protos/peer
2018-02-06 04:27:48.449 UTC [golang-platform] func1 -> DEBU 00b Discarding GOROOT package strconv
2018-02-06 04:27:48.449 UTC [golang-platform] GetDeploymentPayload -> DEBU 00c done
2018-02-06 04:27:48.458 UTC [msp/identity] Sign -> DEBU 00d Sign: plaintext: 0A86070A5C08031A0C08C4DDE4D30510...939FFF060000FFFF9C08DC0700200000 
2018-02-06 04:27:48.459 UTC [msp/identity] Sign -> DEBU 00e Sign: digest: 881EE9535C8EC4371B72CE38BC52BD950864D1CA50F1F64B707EC7492B38AC75 
2018-02-06 04:27:48.512 UTC [chaincodeCmd] install -> DEBU 00f Installed remotely response:<status:200 payload:"OK" > 
2018-02-06 04:27:48.512 UTC [main] main -> INFO 010 Exiting.....
2018-02-06 04:27:48.845 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:27:48.845 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:27:48.847 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-06 04:27:48.848 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-06 04:27:48.849 UTC [msp/identity] Sign -> DEBU 005 Sign: plaintext: 0A91070A6708031A0C08C4DDE4D30510...324D53500A04657363630A0476736363 
2018-02-06 04:27:48.849 UTC [msp/identity] Sign -> DEBU 006 Sign: digest: 7279142B6DCADB92F178A42EB4812C9103108F2AEE8F40F8AD0125D3E13AEC25 
2018-02-06 04:28:51.790 UTC [msp/identity] Sign -> DEBU 007 Sign: plaintext: 0A91070A6708031A0C08C4DDE4D30510...33975E7D10605FC261528FBDEEC0A9A8 
2018-02-06 04:28:51.790 UTC [msp/identity] Sign -> DEBU 008 Sign: digest: 6A3D493ACD5E447FAD3D91C518CD60C45D0DB8E20D5DCFB70B45DA7572C666C0 
2018-02-06 04:28:51.885 UTC [main] main -> INFO 009 Exiting.....
2018-02-06 04:29:02.974 UTC [msp] GetLocalMSP -> DEBU 001 Returning existing local MSP
2018-02-06 04:29:02.974 UTC [msp] GetDefaultSigningIdentity -> DEBU 002 Obtaining default signing identity
2018-02-06 04:29:02.976 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default escc
2018-02-06 04:29:02.976 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 004 Using default vscc
2018-02-06 04:29:02.977 UTC [msp/identity] Sign -> DEBU 005 Sign: plaintext: 0A93070A6908031A0C088EDEE4D30510...1A0E0A0A696E69744C65646765720A00 
2018-02-06 04:29:02.977 UTC [msp/identity] Sign -> DEBU 006 Sign: digest: F5979DA908E3058B28762469FEECB498F506FB2A7D62F01ED56C5CCE3354D5CE 
2018-02-06 04:29:03.103 UTC [msp/identity] Sign -> DEBU 007 Sign: plaintext: 0A93070A6908031A0C088EDEE4D30510...EEB1365266BC4EF15DDAB42DD4202559 
2018-02-06 04:29:03.103 UTC [msp/identity] Sign -> DEBU 008 Sign: digest: 027F185369407246B34B7247E6B83E08078761FFA13C43F508CD7257BBF5BC7B 
2018-02-06 04:29:03.113 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> DEBU 009 ESCC invoke result: version:1 response:<status:200 message:"OK" > payload:"\n e\350\256\026\2161o\374\224\311\210g\322\001\234\332Vt\026+\204\034\013\310;\371\234\353\030`:\360\022\267\006\n\240\006\022\205\006\n\006fabcar\022\372\005\032J\n\004CAR0\032B{\"make\":\"Toyota\",\"model\":\"Prius\",\"colour\":\"blue\",\"owner\":\"Tomoko\"}\032G\n\004CAR1\032?{\"make\":\"Ford\",\"model\":\"Mustang\",\"colour\":\"red\",\"owner\":\"Brad\"}\032N\n\004CAR2\032F{\"make\":\"Hyundai\",\"model\":\"Tucson\",\"colour\":\"green\",\"owner\":\"Jin Soo\"}\032N\n\004CAR3\032F{\"make\":\"Volkswagen\",\"model\":\"Passat\",\"colour\":\"yellow\",\"owner\":\"Max\"}\032G\n\004CAR4\032?{\"make\":\"Tesla\",\"model\":\"S\",\"colour\":\"black\",\"owner\":\"Adriana\"}\032K\n\004CAR5\032C{\"make\":\"Peugeot\",\"model\":\"205\",\"colour\":\"purple\",\"owner\":\"Michel\"}\032H\n\004CAR6\032@{\"make\":\"Chery\",\"model\":\"S22L\",\"colour\":\"white\",\"owner\":\"Aarav\"}\032H\n\004CAR7\032@{\"make\":\"Fiat\",\"model\":\"Punto\",\"colour\":\"violet\",\"owner\":\"Pari\"}\032J\n\004CAR8\032B{\"make\":\"Tata\",\"model\":\"Nano\",\"colour\":\"indigo\",\"owner\":\"Valeria\"}\032M\n\004CAR9\032E{\"make\":\"Holden\",\"model\":\"Barina\",\"colour\":\"brown\",\"owner\":\"Shotaro\"}\022\026\n\004lscc\022\016\n\014\n\006fabcar\022\002\010\001\032\003\010\310\001\"\r\022\006fabcar\032\0031.0" endorsement:<endorser:"\n\007Org1MSP\022\200\006-----BEGIN -----\nMIICGjCCAcCgAwIBAgIRAPlwF/rUZUP9mqN4wSml4iswCgYIKoZIzj0EAwIwczEL\nMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNhbiBG\ncmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMTcwODMxMDkxNDMyWhcNMjcwODI5MDkxNDMy\nWjBbMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN\nU2FuIEZyYW5jaXNjbzEfMB0GA1UEAxMWcGVlcjAub3JnMS5leGFtcGxlLmNvbTBZ\nMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHihxW6ks3B2+5XdbAVq3CBgxRRRZ22x\nzzpqnD86nKkz7fBElBuhlXl2K6rTxyY2OBOB0ts8keqZ93xueRGymrajTTBLMA4G\nA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8EAjAAMCsGA1UdIwQkMCKAIEI5qg3Ndtru\nuLoM2nAYUdFFBNMarRst3dusalc2Xkl8MAoGCCqGSM49BAMCA0gAMEUCIQD4j0Rn\ne1rrd0FSCzsR6u+IuuPK5dI/kR/bh7+VLf0TNgIgCfUtkJvfvzVEwZLFoFyjoHtr\ntvwzNUS1U0hEqIaDeo4=\n-----END -----\n" signature:"0E\002!\000\271u\265\3621\223\255|\353h\003\364g\363\3474\310>\032\351\225\326\306z\356\324\013\366\235\334J\237\002 ^>\200AhmDWh\261\301\204Ye\346\345\356\2616Rf\274N\361]\332\264-\324 %Y" > 
2018-02-06 04:29:03.113 UTC [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 00a Chaincode invoke successful. result: status:200 
2018-02-06 04:29:03.113 UTC [main] main -> INFO 00b Exiting.....

Total setup execution time : 136 secs ...


Start by installing required packages run 'npm install'
Then run 'node enrollAdmin.js', then 'node registerUser'

The 'node invoke.js' will fail until it has been updated with valid arguments
The 'node query.js' may be run at anytime once the user has been registered
		
		

至此 hyperledger 開發環境已經啟動完畢

			
node enrollAdmin.js
node registerUser.js 
node invoke.js
node query.js 		
			
		
			
[root@localhost fabcar]# node enrollAdmin.js
 Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded admin from persistence
Assigned the admin user to the fabric client ::{"name":"admin","mspid":"Org1MSP","roles":null,"affiliation":"","enrollmentSecret":"","enrollment":{"signingIdentity":"9995fba0ac327e43983b07d09a50423de8cb510176484566abfce0cb86e5f594","identity":{"certificate":"-----BEGIN CERTIFICATE-----\nMIIB8TCCAZegAwIBAgIUNH9h0PUYxF1vpUqzEXKRfVc2a7YwCgYIKoZIzj0EAwIw\nczELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMT\nE2NhLm9yZzEuZXhhbXBsZS5jb20wHhcNMTgwMjA2MDQ0NTAwWhcNMTkwMjA2MDQ0\nNTAwWjAQMQ4wDAYDVQQDEwVhZG1pbjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IA\nBEhyVSI9Dl7S2fIYQdiJAB2zeXR9aHIQSVSG7auK3y3yVvABOQPA/Kyn2iMAl4rr\nky/0FYY5B+lxYLLSype/2zKjbDBqMA4GA1UdDwEB/wQEAwIHgDAMBgNVHRMBAf8E\nAjAAMB0GA1UdDgQWBBRotEXOHR/h1ZLwHV/eAUT80bIQFTArBgNVHSMEJDAigCBC\nOaoNzXba7ri6DNpwGFHRRQTTGq0bLd3brGpXNl5JfDAKBggqhkjOPQQDAgNIADBF\nAiEAnBH8WJvb24o2eC5VmMvtQMoB8NDBTpdq5RNyVJx97HcCIBhWMM6R7crkL8M7\n3wmZ1lNNkAJmpRoes7cNxO/ak5Xy\n-----END CERTIFICATE-----\n"}}}

[root@localhost fabcar]# node registerUser.js 
 Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded admin from persistence
Successfully registered user1 - secret:ZjzLwIaVjEAV
Successfully enrolled member user "user1" 
User1 was successfully registered and enrolled and is ready to intreact with the fabric network

[root@localhost fabcar]# node query.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  [{"Key":"CAR0", "Record":{"colour":"blue","make":"Toyota","model":"Prius","owner":"Tomoko"}},{"Key":"CAR1", "Record":{"colour":"red","make":"Ford","model":"Mustang","owner":"Brad"}},{"Key":"CAR2", "Record":{"colour":"green","make":"Hyundai","model":"Tucson","owner":"Jin Soo"}},{"Key":"CAR3", "Record":{"colour":"yellow","make":"Volkswagen","model":"Passat","owner":"Max"}},{"Key":"CAR4", "Record":{"colour":"black","make":"Tesla","model":"S","owner":"Adriana"}},{"Key":"CAR5", "Record":{"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}},{"Key":"CAR6", "Record":{"colour":"white","make":"Chery","model":"S22L","owner":"Aarav"}},{"Key":"CAR7", "Record":{"colour":"violet","make":"Fiat","model":"Punto","owner":"Pari"}},{"Key":"CAR8", "Record":{"colour":"indigo","make":"Tata","model":"Nano","owner":"Valeria"}},{"Key":"CAR9", "Record":{"colour":"brown","make":"Holden","model":"Barina","owner":"Shotaro"}}]		
			
		

invoke.js 腳本會出現下面錯誤

			
[root@localhost fabcar]# node invoke.js
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  424c946e96d43005e4b815f56fa43bd58d1370404f6713b3ce267928d4499b78
error: [client-utils.js]: sendPeersProposal - Promise is rejected: Error: 2 UNKNOWN: chaincode error (status: 500, message: Invalid Smart Contract function name.)
    at new createStatusError (/root/fabric-samples/fabcar/node_modules/grpc/src/client.js:65:15)
    at /root/fabric-samples/fabcar/node_modules/grpc/src/client.js:568:15
Transaction proposal was bad
Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...
Failed to invoke successfully :: Error: Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...			
			
		

這裡出錯,是因為沒有提供相關的調用方法和參數,暫時不去糾結,繼續做實驗。

24.5.2.1. 智能合約

				
[root@localhost fabric-samples]# cat chaincode/fabcar/fabcar.go 
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * The sample smart contract for documentation topic:
 * Writing Your First Blockchain Application
 */

package main

/* Imports
 * 4 utility libraries for formatting, handling bytes, reading and writing JSON, and string manipulation
 * 2 specific Hyperledger Fabric specific libraries for Smart Contracts
 */
import (
	"bytes"
	"encoding/json"
	"fmt"
	"strconv"

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

// Define the Smart Contract structure
type SmartContract struct {
}

// Define the car structure, with 4 properties.  Structure tags are used by encoding/json library
type Car struct {
	Make   string `json:"make"`
	Model  string `json:"model"`
	Colour string `json:"colour"`
	Owner  string `json:"owner"`
}

/*
 * The Init method is called when the Smart Contract "fabcar" is instantiated by the blockchain network
 * Best practice is to have any Ledger initialization in separate function -- see initLedger()
 */
func (s *SmartContract) Init(APIstub shim.ChaincodeStubInterface) sc.Response {
	return shim.Success(nil)
}

/*
 * The Invoke method is called as a result of an application request to run the Smart Contract "fabcar"
 * The calling application program has also specified the particular smart contract function to be called, with arguments
 */
func (s *SmartContract) Invoke(APIstub shim.ChaincodeStubInterface) sc.Response {

	// Retrieve the requested Smart Contract function and arguments
	function, args := APIstub.GetFunctionAndParameters()
	// Route to the appropriate handler function to interact with the ledger appropriately
	if function == "queryCar" {
		return s.queryCar(APIstub, args)
	} else if function == "initLedger" {
		return s.initLedger(APIstub)
	} else if function == "createCar" {
		return s.createCar(APIstub, args)
	} else if function == "queryAllCars" {
		return s.queryAllCars(APIstub)
	} else if function == "changeCarOwner" {
		return s.changeCarOwner(APIstub, args)
	}

	return shim.Error("Invalid Smart Contract function name.")
}

func (s *SmartContract) queryCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

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

	carAsBytes, _ := APIstub.GetState(args[0])
	return shim.Success(carAsBytes)
}

func (s *SmartContract) initLedger(APIstub shim.ChaincodeStubInterface) sc.Response {
	cars := []Car{
		Car{Make: "Toyota", Model: "Prius", Colour: "blue", Owner: "Tomoko"},
		Car{Make: "Ford", Model: "Mustang", Colour: "red", Owner: "Brad"},
		Car{Make: "Hyundai", Model: "Tucson", Colour: "green", Owner: "Jin Soo"},
		Car{Make: "Volkswagen", Model: "Passat", Colour: "yellow", Owner: "Max"},
		Car{Make: "Tesla", Model: "S", Colour: "black", Owner: "Adriana"},
		Car{Make: "Peugeot", Model: "205", Colour: "purple", Owner: "Michel"},
		Car{Make: "Chery", Model: "S22L", Colour: "white", Owner: "Aarav"},
		Car{Make: "Fiat", Model: "Punto", Colour: "violet", Owner: "Pari"},
		Car{Make: "Tata", Model: "Nano", Colour: "indigo", Owner: "Valeria"},
		Car{Make: "Holden", Model: "Barina", Colour: "brown", Owner: "Shotaro"},
	}

	i := 0
	for i < len(cars) {
		fmt.Println("i is ", i)
		carAsBytes, _ := json.Marshal(cars[i])
		APIstub.PutState("CAR"+strconv.Itoa(i), carAsBytes)
		fmt.Println("Added", cars[i])
		i = i + 1
	}

	return shim.Success(nil)
}

func (s *SmartContract) createCar(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

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

	var car = Car{Make: args[1], Model: args[2], Colour: args[3], Owner: args[4]}

	carAsBytes, _ := json.Marshal(car)
	APIstub.PutState(args[0], carAsBytes)

	return shim.Success(nil)
}

func (s *SmartContract) queryAllCars(APIstub shim.ChaincodeStubInterface) sc.Response {

	startKey := "CAR0"
	endKey := "CAR999"

	resultsIterator, err := APIstub.GetStateByRange(startKey, endKey)
	if err != nil {
		return shim.Error(err.Error())
	}
	defer resultsIterator.Close()

	// buffer is a JSON array containing QueryResults
	var buffer bytes.Buffer
	buffer.WriteString("[")

	bArrayMemberAlreadyWritten := false
	for resultsIterator.HasNext() {
		queryResponse, err := resultsIterator.Next()
		if err != nil {
			return shim.Error(err.Error())
		}
		// Add a comma before array members, suppress it for the first array member
		if bArrayMemberAlreadyWritten == true {
			buffer.WriteString(",")
		}
		buffer.WriteString("{\"Key\":")
		buffer.WriteString("\"")
		buffer.WriteString(queryResponse.Key)
		buffer.WriteString("\"")

		buffer.WriteString(", \"Record\":")
		// Record is a JSON object, so we write as-is
		buffer.WriteString(string(queryResponse.Value))
		buffer.WriteString("}")
		bArrayMemberAlreadyWritten = true
	}
	buffer.WriteString("]")

	fmt.Printf("- queryAllCars:\n%s\n", buffer.String())

	return shim.Success(buffer.Bytes())
}

func (s *SmartContract) changeCarOwner(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {

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

	carAsBytes, _ := APIstub.GetState(args[0])
	car := Car{}

	json.Unmarshal(carAsBytes, &car)
	car.Owner = args[1]

	carAsBytes, _ = json.Marshal(car)
	APIstub.PutState(args[0], carAsBytes)

	return shim.Success(nil)
}

// The main function is only relevant in unit test mode. Only included here for completeness.
func main() {

	// Create a new Smart Contract
	err := shim.Start(new(SmartContract))
	if err != nil {
		fmt.Printf("Error creating new Smart Contract: %s", err)
	}
}				
				
			

24.5.2.2. 創建記錄

				
[root@localhost fabcar]# cp invoke.js createCar.js
[root@localhost fabcar]# vim createCar.js
				
			
				
var request = {
                //targets: let default to the peer assigned to the client
                chaincodeId: 'fabcar',
                fcn: '',
                args: [''],
                chainId: 'mychannel',
                txId: tx_id
        };
				
			

改為

				
	var request = {
		//targets: let default to the peer assigned to the client
		chaincodeId: 'fabcar',
		fcn: 'createCar',
		args: ['CAR10', 'Chevy', 'Volt', 'Red', 'Nick'],
		chainId: 'mychannel',
		txId: tx_id
	};				
				
			

運行結果

				
[root@localhost fabcar]# node createCar.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  907d35d7c5debf952f28135b2c341797acdb7ef1f1389607fb04891a27e8ba19
Transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message - "OK"
info: [EventHub.js]: _connect - options {}
The transaction has been committed on peer localhost:7053
Send transaction promise and event listener promise have completed
Successfully sent transaction to the orderer.
Successfully committed the change to the ledger by the peer				
				
			

24.5.2.3. 查詢單條記錄

查找 CAR5 這條記錄的數據。

				
[root@localhost fabcar]# node queryOne.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  {"colour":"purple","make":"Peugeot","model":"205","owner":"Michel"}
[root@localhost fabcar]# cat queryOne.js 
'use strict';
/*
* Copyright IBM Corp All Rights Reserved
*
* SPDX-License-Identifier: Apache-2.0
*/
/*
 * Chaincode query
 */

var Fabric_Client = require('fabric-client');
var path = require('path');
var util = require('util');
var os = require('os');

//
var fabric_client = new Fabric_Client();

// setup the fabric network
var channel = fabric_client.newChannel('mychannel');
var peer = fabric_client.newPeer('grpc://localhost:7051');
channel.addPeer(peer);

//
var member_user = null;
var store_path = path.join(__dirname, 'hfc-key-store');
console.log('Store path:'+store_path);
var tx_id = null;

// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
	// assign the store to the fabric client
	fabric_client.setStateStore(state_store);
	var crypto_suite = Fabric_Client.newCryptoSuite();
	// use the same location for the state store (where the users' certificate are kept)
	// and the crypto store (where the users' keys are kept)
	var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
	crypto_suite.setCryptoKeyStore(crypto_store);
	fabric_client.setCryptoSuite(crypto_suite);

	// get the enrolled user from persistence, this user will sign all requests
	return fabric_client.getUserContext('user1', true);
}).then((user_from_store) => {
	if (user_from_store && user_from_store.isEnrolled()) {
		console.log('Successfully loaded user1 from persistence');
		member_user = user_from_store;
	} else {
		throw new Error('Failed to get user1.... run registerUser.js');
	}

	// queryCar chaincode function - requires 1 argument, ex: args: ['CAR4'],
	// queryAllCars chaincode function - requires no arguments , ex: args: [''],
	const request = {
		//targets : --- letting this default to the peers assigned to the channel
		chaincodeId: 'fabcar',
		fcn: 'queryCar',
		args: ['CAR10']
	};

	// send the query proposal to the peer
	return channel.queryByChaincode(request);
}).then((query_responses) => {
	console.log("Query has completed, checking results");
	// query_responses could have more than one  results if there multiple peers were used as targets
	if (query_responses && query_responses.length == 1) {
		if (query_responses[0] instanceof Error) {
			console.error("error from query = ", query_responses[0]);
		} else {
			console.log("Response is ", query_responses[0].toString());
		}
	} else {
		console.log("No payloads were returned from query");
	}
}).catch((err) => {
	console.error('Failed to query successfully :: ' + err);
});

				
			

運行結果

				
[root@localhost fabcar]# node queryOne.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  {"colour":"Red","make":"Chevy","model":"Volt","owner":"Nick"}			
				
			

24.5.2.4. 修改汽車所有者

				
[root@localhost fabcar]# cp invoke.js changeCarOwner.js
[root@localhost fabcar]# vim changeCarOwner.js 				
				
			
				
        var request = {
                //targets: let default to the peer assigned to the client
                chaincodeId: 'fabcar',
                fcn: '',
                args: [''],
                chainId: 'mychannel',
                txId: tx_id
        };				
				
			

修改為

				
        var request = {
                //targets: let default to the peer assigned to the client
                chaincodeId: 'fabcar',
                fcn: 'changeCarOwner',
                args: ['CAR10', 'Neo'],
                chainId: 'mychannel',
                txId: tx_id
        };				
				
			

運行結果

				
[root@localhost fabcar]# node changeCarOwner.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Assigning transaction_id:  b183a7bac6161ff7c7e9974e20bb1a72b2ac5f11ab698a2ae4f63cfdbc33a735
Transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message - "OK"
info: [EventHub.js]: _connect - options {}
The transaction has been committed on peer localhost:7053
Send transaction promise and event listener promise have completed
Successfully sent transaction to the orderer.
Successfully committed the change to the ledger by the peer


[root@localhost fabcar]# node queryOne.js 
Store path:/root/fabric-samples/fabcar/hfc-key-store
Successfully loaded user1 from persistence
Query has completed, checking results
Response is  {"colour":"Red","make":"Chevy","model":"Volt","owner":"Neo"}
				
			

現在我們可以看到 所有者已經改為 Neo

24.5.3. balance-transfer

			
[root@localhost fabric-samples]# cd balance-transfer/
[root@localhost balance-transfer]# ./runApp.sh 

Stopping peer0.org1.example.com ... done
Stopping peer0.org2.example.com ... done
Stopping peer1.org2.example.com ... done
Stopping peer1.org1.example.com ... done
Stopping ca_peerOrg1 ... done
Stopping orderer.example.com ... done
Stopping ca_peerOrg2 ... done
Removing peer0.org1.example.com ... done
Removing peer0.org2.example.com ... done
Removing peer1.org2.example.com ... done
Removing peer1.org1.example.com ... done
Removing ca_peerOrg1 ... done
Removing orderer.example.com ... done
Removing ca_peerOrg2 ... done
Removing network artifacts_default

========== No containers available for deletion ==========


========== No images available for deletion ===========

Creating network "artifacts_default" with the default driver
Creating ca_peerOrg2
Creating orderer.example.com
Creating ca_peerOrg1
Creating peer1.org2.example.com
Creating peer0.org2.example.com
Creating peer0.org1.example.com
Creating peer1.org1.example.com
/root/fabric-samples/balance-transfer


============== node modules installed already =============

[2018-02-06 09:14:54.916] [DEBUG] Helper - [crypto_ecdsa_aes]: constructor, keySize: 256
[2018-02-06 09:14:54.921] [DEBUG] Helper - [crypto_ecdsa_aes]: Hash algorithm: SHA2, hash output size: 256
[2018-02-06 09:14:55.046] [DEBUG] Helper - [utils.CryptoKeyStore]: CryptoKeyStore, constructor - start
[2018-02-06 09:14:55.048] [DEBUG] Helper - [utils.CryptoKeyStore]: constructor, no super class specified, using config: fabric-client/lib/impl/FileKeyValueStore.js
[2018-02-06 09:14:55.056] [DEBUG] Helper - [crypto_ecdsa_aes]: constructor, keySize: 256
[2018-02-06 09:14:55.056] [DEBUG] Helper - [crypto_ecdsa_aes]: Hash algorithm: SHA2, hash output size: 256
[2018-02-06 09:14:55.057] [DEBUG] Helper - [utils.CryptoKeyStore]: CryptoKeyStore, constructor - start
[2018-02-06 09:14:55.057] [DEBUG] Helper - [utils.CryptoKeyStore]: constructor, no super class specified, using config: fabric-client/lib/impl/FileKeyValueStore.js
[2018-02-06 09:14:55.082] [INFO] SampleWebApp - ****************** SERVER STARTED ************************
[2018-02-06 09:14:55.082] [INFO] SampleWebApp - **************  http://localhost:4000  ******************

			
		

安裝 jq 工具

			
yum install -y jq			
			
		

API 測試結果

			
[root@localhost balance-transfer]# ./testAPIs.sh 
POST request Enroll on Org1  ...

{"success":true,"secret":"uXlJIPvBgLbh","message":"Jim enrolled Successfully","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDUsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MTc5MjcwMDV9.pBqwAVac32NIA_x5S163h9_lRfIHMx4shX05D0geO5k"}

ORG1 token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDUsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MTc5MjcwMDV9.pBqwAVac32NIA_x5S163h9_lRfIHMx4shX05D0geO5k

POST request Enroll on Org2 ...

{"success":true,"secret":"kXcltqsAoiDf","message":"Barry enrolled Successfully","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDcsInVzZXJuYW1lIjoiQmFycnkiLCJvcmdOYW1lIjoib3JnMiIsImlhdCI6MTUxNzkyNzAwN30.ePexFJ2r9WoYNma5iKomJu3anEvg3PTgBEqI6K-s6F0"}

ORG2 token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTc5NjMwMDcsInVzZXJuYW1lIjoiQmFycnkiLCJvcmdOYW1lIjoib3JnMiIsImlhdCI6MTUxNzkyNzAwN30.ePexFJ2r9WoYNma5iKomJu3anEvg3PTgBEqI6K-s6F0


POST request Create channel  ...

{"success":true,"message":"Channel 'mychannel' created Successfully"}

POST request Join channel on Org1

{"success":true,"message":"Successfully joined peers in organization org1 to the channel 'mychannel'"}

POST request Join channel on Org2

{"success":true,"message":"Successfully joined peers in organization org2 to the channel 'mychannel'"}

POST Install chaincode on Org1

Successfully Installed chaincode on organization org1

POST Install chaincode on Org2

Successfully Installed chaincode on organization org2

POST instantiate chaincode on peer1 of Org1

Failed to order the transaction. Error code: undefined

POST invoke chaincode on peers of Org1 and Org2

Transacton ID is Failed to order the transaction. Error code: undefined


GET query chaincode on peer1 of Org1

a now has Error: 2 UNKNOWN: could not find chaincode with name 'mycc' - make sure the chaincode mycc has been successfully instantiated and try again after the move

GET query Block by blockNumber

Error: 2 UNKNOWN: chaincode error (status: 500, message: Failed to get block number 1, error Entry not found in index)
    at new createStatusError (/root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:65:15)
    at /root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:568:15

GET query Transaction by TransactionID

Error: 2 UNKNOWN: chaincode error (status: 500, message: Failed to get transaction with id Failed, error Entry not found in index)
    at new createStatusError (/root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:65:15)
    at /root/fabric-samples/balance-transfer/node_modules/grpc/src/client.js:568:15


GET query ChainInfo

{"height":{"low":1,"high":0,"unsigned":true},"currentBlockHash":{"buffer":{"type":"Buffer","data":[8,1,18,32,180,19,234,224,76,239,188,107,147,219,120,185,108,73,201,120,81,0,242,221,32,3,94,175,16,200,181,113,100,97,129,57]},"offset":4,"markedOffset":-1,"limit":36,"littleEndian":true,"noAssert":false},"previousBlockHash":{"buffer":{"type":"Buffer","data":[]},"offset":0,"markedOffset":-1,"limit":0,"littleEndian":false,"noAssert":false}}

GET query Installed chaincodes

["name: mycc, version: v0, path: github.com/example_cc"]

GET query Instantiated chaincodes

[]

GET query Channels

{"channels":[{"channel_id":"mychannel"}]}

Total execution time : 364 secs ...			
			
		

上面 ERROR 可能是因為 hyperledger v1.1.0 版本的緣故。此時的 fabric-samples 僅僅支持 v1.0.0。

24.5.4. first-network

			
cd fabric-samples/first-network			
			
		
			
[root@localhost first-network]# ./byfn.sh -m generate 
Generating certs and genesis block for with channel 'mychannel' and CLI timeout of '10'
Continue (y/n)? y
proceeding ...
which: no cryptogen in (/root/fabric-samples/first-network/../bin:/root/fabric-samples/first-network:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/srv/php/bin::/root/bin:/usr/local/src/phalcon-devtools)
cryptogen tool not found. exiting			
			
		
			
[root@localhost first-network]# ./byfn.sh -m up