做者: 李佶澳 轉載請保留:原文地址 發佈時間:2018/04/25 11:11:00html
這是「網易雲課堂IT技術快速入門學院」使用的素材。java
操做、配置文件和代碼講解視頻在網易雲課堂《HyperLeger Fabric進階實戰課》第五章中。node
當前(2018-04-25 11:16:23)fabric的SDK只有java和node是正式的,他倆的文檔也是最豐富的。當前支持的node版本是v8.9.0~v9.0,v9.0以上版本不支持(2018-07-15 14:11:01)。git
Hyperledger Fabric SDK for node.jsgithub
當前支持的node版本是v8.9.0~v9.0,v9.0以上版本不支持(2018-07-15 14:11:01)。npm
在mac上能夠用brew安裝node8:json
$ brew install node@8
$ echo 'export PATH="/usr/local/opt/node@8/bin:$PATH"' >> ~/.bash_profile
$ source ~/.bash_profile
$ node --version
v8.11.3
或者直接下載安裝:nodejs downloadbash
建立文件package.json:app
$ cat package.json
{
"dependencies": {
"fabric-ca-client": "1.1.2",
"fabric-client": "1.1.2",
"grpc": "^1.6.0"
},
"author": "Anthony O'Dowd",
"license": "Apache-2.0",
"keywords": [
"Hyperledger",
"Fabric",
"Car",
"Sample",
"Application"
]
}
用npm安裝依賴包:ide
npm config set registry https://registry.npm.taobao.org (設置淘寶提供的鏡像源)
npm install
調用mychannel中的mycc合約的query接口,參數爲key
:
node ./01-query-chaincode.js
代碼以下:
/*
* client.js
* Copyright (C) 2018 lijiaocn <lijiaocn@foxmail.com>
*
* Distributed under terms of the GPL license.
*/
var fs = require('fs');
var Fabric_Client = require('fabric-client');
//建立一個Client
Fabric_Client.newDefaultKeyValueStore({ path: '/tmp/xx/' }).then((state_store) => {
client=new Fabric_Client();
client.setStateStore(state_store)
//設置用戶信息
var userOpt = {
username: 'Admin@member1.example.com',
mspid: 'peers.member1.example.com',
cryptoContent: {
privateKey: './msp/keystore/09dd09cf530d8f0fa6cb383b5b409ae8e895d32d31f75823f3bdb3c1f3ee180a_sk',
signedCert: './msp/signcerts/Admin@member1.example.com-cert.pem'
}
}
return client.createUser(userOpt)
}).then((user)=>{
//設置要鏈接的Channel
var channel = client.newChannel('mychannel');
//設置要鏈接的Peer
var peer = client.newPeer(
'grpcs://peer0.member1.example.com:7051',
{
pem: fs.readFileSync('./tls/ca.crt', { encoding: 'utf8' }),
clientKey: fs.readFileSync('./tls/client.key', { encoding: 'utf8' }),
clientCert: fs.readFileSync('./tls/client.crt', { encoding: 'utf8' }),
'ssl-target-name-override': 'peer0.member1.example.com'
}
);
channel.addPeer(peer);
//調用chaincode
const request = {
chaincodeId: 'mycc', //chaincode名稱
fcn: 'query', //調用的函數名
args: ['key1'] //參數
};
// send the query proposal to the peer
return channel.queryByChaincode(request);
}).then((response)=>{
console.log('Response is', response.toString());
})
Hyperledger Fabric SDK for node.js中有每一個類說明,上面示例的源代碼託管在Github上: hyperledger-fabric-sdks-usage。
HyperLedger官方源代碼中還有更多的例子:fabric node sdk example
使用過程遇到的問題記錄在: 《超級帳本HyperLedger:Fabric的Node.js SDK使用時遇到的問題》