Hyperledger Fabric 实战(1) fabric-sdk-node

淡淡的烟草味﹌ 2022-03-30 04:18 327阅读 0赞

Hyperledger Fabric 实战(1) fabric-sdk-node

    • 关于Fabric SDK
    • 安装环境
    • 创建node http服务器
    • invoke方法内容如下:
    • query方法内容如下:
    • 注意

关于Fabric SDK

目前Fabric官方提供了四种语言版本的SDK,分别如下:
1 Fabric Nodejs SDK
2 Fabric Java SDK
3 Fabric Go SDK
4 Fabric Python SDK

由于1.2版本没有java sdk(1.3版本java sdk 貌似坑也很多) Go 和 python相比node sdk 坑也多.
且Node.js SDK的编程模型得到改善,node.js的链码开发更直观,可更专注于业务逻辑,所以建议选择node sdk.

安装环境

首先安装node
版本最好为8.9,9.x以上不支持
node runtime LTS version 8.9.0 or higher, up to 9.0 ( Node v9.0+ is not supported )
npm tool version 5.5.1 or higher
gulp command (must be installed globaly with npm install -g gulp)
docker (not required if you only want to run the headless tests with npm test, see below)

创建node http服务器

创建一个node-demo project
app.js 里面的内容如下
const http = require(‘http’);

const hostname = ‘127.0.0.1’;
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hello World\n’);
});

server.listen(port, hostname, () => {
console.log(Server running at http://${hostname}:${port}/);
});
package.json文件添加如下内容
{
“name”: “fabcar”,
“version”: “1.0.0”,
“description”: “Hyperledger Fabric Car Sample Application”,
“main”: “fabcar.js”,
“scripts”: {
“test”: “echo “Error: no test specified” && exit 1”
},
“dependencies”: {
“fabric-ca-client”: “~1.2.0”,
“fabric-client”: “~1.2.0”,
“grpc”: “^1.6.0”
},
“author”: “Anthony O’Dowd”,
“license”: “Apache-2.0”,
“keywords”: [
“Hyperledger”,
“Fabric”,
“Car”,
“Sample”,
“Application”
]
}

invoke方法内容如下:

‘use strict’;
/*

  • Copyright IBM Corp All Rights Reserved
  • SPDX-License-Identifier: Apache-2.0
    /
    /
  • Chaincode Invoke
    */

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 order = fabric_client.newOrderer(‘grpc://localhost:7050’)
channel.addOrderer(order);

//
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);

  1. // get the enrolled user from persistence, this user will sign all requests
  2. 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’);
}

  1. // get a transaction id object based on the current user assigned to fabric client
  2. tx_id = fabric_client.newTransactionID();
  3. console.log("Assigning transaction_id: ", tx_id._transaction_id);
  4. // createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],
  5. // changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],
  6. // must send the proposal to endorsing peers
  7. var request = {
  8. //targets: let default to the peer assigned to the client
  9. chaincodeId: 'fabcar',
  10. fcn: '',
  11. args: [''],
  12. chainId: 'mychannel',
  13. txId: tx_id
  14. };
  15. // send the transaction proposal to the peers
  16. return channel.sendTransactionProposal(request);

}).then((results) => {
var proposalResponses = results[0];
var proposal = results[1];
let isProposalGood = false;
if (proposalResponses && proposalResponses[0].response &&
proposalResponses[0].response.status === 200) {
isProposalGood = true;
console.log(‘Transaction proposal was good’);
} else {
console.error(‘Transaction proposal was bad’);
}
if (isProposalGood) {
console.log(util.format(
‘Successfully sent Proposal and received ProposalResponse: Status - %s, message - “%s”’,
proposalResponses[0].response.status, proposalResponses[0].response.message));

  1. // build up the request for the orderer to have the transaction committed
  2. var request = {
  3. proposalResponses: proposalResponses,
  4. proposal: proposal
  5. };
  6. // set the transaction listener and set a timeout of 30 sec
  7. // if the transaction did not get committed within the timeout period,
  8. // report a TIMEOUT status
  9. var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing
  10. var promises = [];
  11. var sendPromise = channel.sendTransaction(request);
  12. promises.push(sendPromise); //we want the send transaction first, so that we know where to check status
  13. // get an eventhub once the fabric client has a user assigned. The user
  14. // is required bacause the event registration must be signed
  15. let event_hub = channel.newChannelEventHub(peer);
  16. // using resolve the promise so that result status may be processed
  17. // under the then clause rather than having the catch clause process
  18. // the status
  19. let txPromise = new Promise((resolve, reject) => {
  20. let handle = setTimeout(() => {
  21. event_hub.unregisterTxEvent(transaction_id_string);
  22. event_hub.disconnect();
  23. resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));
  24. }, 3000);
  25. event_hub.registerTxEvent(transaction_id_string, (tx, code) => {
  26. // this is the callback for transaction event status
  27. // first some clean up of event listener
  28. clearTimeout(handle);
  29. // now let the application know what happened
  30. var return_status = {event_status : code, tx_id : transaction_id_string};
  31. if (code !== 'VALID') {
  32. console.error('The transaction was invalid, code = ' + code);
  33. resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));
  34. } else {
  35. console.log('The transaction has been committed on peer ' + event_hub.getPeerAddr());
  36. resolve(return_status);
  37. }
  38. }, (err) => {
  39. //this is the callback if something goes wrong with the event registration or processing
  40. reject(new Error('There was a problem with the eventhub ::'+err));
  41. },
  42. {disconnect: true} //disconnect when complete
  43. );
  44. event_hub.connect();
  45. });
  46. promises.push(txPromise);
  47. return Promise.all(promises);
  48. } else {
  49. console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
  50. throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
  51. }

}).then((results) => {
console.log(‘Send transaction promise and event listener promise have completed’);
// check the results in the order the promises were added to the promise all list
if (results && results[0] && results[0].status === ‘SUCCESS’) {
console.log(‘Successfully sent transaction to the orderer.’);
} else {
console.error(‘Failed to order the transaction. Error code: ’ + results[0].status);
}

  1. if(results && results[1] && results[1].event_status === 'VALID') {
  2. console.log('Successfully committed the change to the ledger by the peer');
  3. } else {
  4. console.log('Transaction failed to be committed to the ledger due to ::'+results[1].event_status);
  5. }

}).catch((err) => {
console.error(‘Failed to invoke successfully :: ’ + err);
});

query方法内容如下:

‘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);

  1. // get the enrolled user from persistence, this user will sign all requests
  2. 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’);
}

  1. // queryCar chaincode function - requires 1 argument, ex: args: ['CAR4'],
  2. // queryAllCars chaincode function - requires no arguments , ex: args: [''],
  3. const request = {
  4. //targets : --- letting this default to the peers assigned to the channel
  5. chaincodeId: 'fabcar',
  6. fcn: 'queryAllCars',
  7. args: ['']
  8. };
  9. // send the query proposal to the peer
  10. 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);
});

注意

使用这两个方法前我们需要:
enrollAdmin 和 registerUser

发表评论

表情:
评论列表 (有 0 条评论,327人围观)

还没有评论,来说两句吧...

相关阅读