Fabric1.4 新特性简介

发布时间:2018年12月21日 价值:20000.00 / 共识:44

Fabric1.4 新特性简介

更多Fabric区块链技术相关文章, 请关注知乎-区块链技术学习专栏

1. 两个方面的新特性

近日,官方推出了Fabric1.4版本,其新特性主要体现在两个方面

Fabric1.4新特性

可服务性和操作性 (Serviceability and Operations)

感觉很抽象,对吗?其实这里的可服务性和操作性,主要是指对区块链网络的操作人员而言。Fabric v1.4在日志记录改进、健康检查和操作指标方面取得了巨大的进步.除了关注稳定性和修复之外,Fabric v1.4也是生产操作的推荐版本。

新的Restful操作服务为操作人员提供了三个服务,用于监视和管理对等节点和订单节点操作.

日志/logspec端点
允许操作人员动态获取和设置对等节点和订单节点的日志级别。
/healthz端点
允许操作人员和容器编配服务检查对等节点和订单节点的活动性和健康状况。
metrics端点
允许操作人员利用Prometheus从对等节点和订单节点提取操作指标。
可以看到,这一方面的升级,使得检测网络的状态更加方便了。特别是日志级别的更新,使得调试网络,查找Bug更加方便了。

改进了开发应用程序的应用开发模型

区块链应用程序的开发, 主要是根据官方提供的SDK。目前已知的sdk有很多,比如fabric-java-sdk,fabric-python-sdk,fabric-nodejs-sdk等等.这次之所以改进了应用开发模型,主要是官方进一步封装了fabric-nodejs-sdk的开发包,使得开发更加简单了。(fabric-nodejs-sdk是目前唯一的一个官方维护的sdk,所以,改进了开发应用程序的应用开发模型,主要是指fabric-nodejs-sdk)。

改进了开发应用程序的应用开发模型,带来了什么好处呢?

简单来说,就是:

新的nodejs SDK包和chaincode编程模型使得开发分布式应用更加容易,让开发人员能够专注于应用程序的逻辑,提高了开发人员的工作效率。通过使用商业票据业务网络场景,新的文档可以帮助您了解为超分类帐织物创建分散应用程序的各个方面。
确实,新的nodejs SDK在原来的基础上进一步封装了,感觉开发程序简化了很多。如果你想好好学习这个新的开发模型,可以按照官方提供的新教程:
商业票据教程

2.举例分析

代码更简洁!!!编程更容易理解!!!之所以会变得简洁,是因为新版的nodejs-sdk进一步封装了接口,提出了walletGateway等新的概念,使得编程进一步简化。

对比改进之前与改进之后的代码,便可发现,改进的多么的方便。
这里,对比的是fabric-sample里面的fabcar项目中的invoke.js代码原来要写163行的代码,现在只要写56行

新版的invoke.js源码如下:

invoke.js 示例:

  1. /*
  2. * SPDX-License-Identifier: Apache-2.0
  3. */
  4. 'use strict';
  5. const { FileSystemWallet, Gateway } = require('fabric-network');
  6. const fs = require('fs');
  7. const path = require('path');
  8. const ccpPath = path.resolve(__dirname, '..', '..', 'basic-network', 'connection.json');
  9. const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
  10. const ccp = JSON.parse(ccpJSON);
  11. async function main() {
  12. try {
  13. // Create a new file system based wallet for managing identities.
  14. const walletPath = path.join(process.cwd(), 'wallet');
  15. const wallet = new FileSystemWallet(walletPath);
  16. console.log(`Wallet path: ${walletPath}`);
  17. // Check to see if we've already enrolled the user.
  18. const userExists = await wallet.exists('user1');
  19. if (!userExists) {
  20. console.log('An identity for the user "user1" does not exist in the wallet');
  21. console.log('Run the registerUser.js application before retrying');
  22. return;
  23. }
  24. // Create a new gateway for connecting to our peer node.
  25. const gateway = new Gateway();
  26. await gateway.connect(ccp, { wallet, identity: 'user1', discovery: { enabled: false } });
  27. // Get the network (channel) our contract is deployed to.
  28. const network = await gateway.getNetwork('mychannel');
  29. // Get the contract from the network.
  30. const contract = network.getContract('fabcar');
  31. // Submit the specified transaction.
  32. // createCar transaction - requires 5 argument, ex: ('createCar', 'CAR12', 'Honda', 'Accord', 'Black', 'Tom')
  33. // changeCarOwner transaction - requires 2 args , ex: ('changeCarOwner', 'CAR10', 'Dave')
  34. await contract.submitTransaction('createCar', 'CAR12', 'Honda', 'Accord', 'Black', 'Tom');
  35. console.log('Transaction has been submitted');
  36. // Disconnect from the gateway.
  37. await gateway.disconnect();
  38. } catch (error) {
  39. console.error(`Failed to submit transaction: ${error}`);
  40. process.exit(1);
  41. }
  42. }
  43. main();

旧版的invoke.js代码如下:

  1. 'use strict';
  2. /*
  3. * Copyright IBM Corp All Rights Reserved
  4. *
  5. * SPDX-License-Identifier: Apache-2.0
  6. */
  7. /*
  8. * Chaincode Invoke
  9. */
  10. var Fabric_Client = require('fabric-client');
  11. var path = require('path');
  12. var util = require('util');
  13. var os = require('os');
  14. //
  15. var fabric_client = new Fabric_Client();
  16. // setup the fabric network
  17. var channel = fabric_client.newChannel('mychannel');
  18. var peer = fabric_client.newPeer('grpc://localhost:7051');
  19. channel.addPeer(peer);
  20. var order = fabric_client.newOrderer('grpc://localhost:7050')
  21. channel.addOrderer(order);
  22. //
  23. var member_user = null;
  24. var store_path = path.join(__dirname, 'hfc-key-store');
  25. console.log('Store path:'+store_path);
  26. var tx_id = null;
  27. // create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
  28. Fabric_Client.newDefaultKeyValueStore({ path: store_path
  29. }).then((state_store) => {
  30. // assign the store to the fabric client
  31. fabric_client.setStateStore(state_store);
  32. var crypto_suite = Fabric_Client.newCryptoSuite();
  33. // use the same location for the state store (where the users' certificate are kept)
  34. // and the crypto store (where the users' keys are kept)
  35. var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
  36. crypto_suite.setCryptoKeyStore(crypto_store);
  37. fabric_client.setCryptoSuite(crypto_suite);
  38. // get the enrolled user from persistence, this user will sign all requests
  39. return fabric_client.getUserContext('user1', true);
  40. }).then((user_from_store) => {
  41. if (user_from_store && user_from_store.isEnrolled()) {
  42. console.log('Successfully loaded user1 from persistence');
  43. member_user = user_from_store;
  44. } else {
  45. throw new Error('Failed to get user1.... run registerUser.js');
  46. }
  47. // get a transaction id object based on the current user assigned to fabric client
  48. tx_id = fabric_client.newTransactionID();
  49. console.log("Assigning transaction_id: ", tx_id._transaction_id);
  50. // createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],
  51. // changeCarOwner chaincode function - requires 2 args , ex: args: ['CAR10', 'Dave'],
  52. // must send the proposal to endorsing peers
  53. var request = {
  54. //targets: let default to the peer assigned to the client
  55. chaincodeId: 'fabcar',
  56. fcn: '',
  57. args: [''],
  58. chainId: 'mychannel',
  59. txId: tx_id
  60. };
  61. // send the transaction proposal to the peers
  62. return channel.sendTransactionProposal(request);
  63. }).then((results) => {
  64. var proposalResponses = results[0];
  65. var proposal = results[1];
  66. let isProposalGood = false;
  67. if (proposalResponses && proposalResponses[0].response &&
  68. proposalResponses[0].response.status === 200) {
  69. isProposalGood = true;
  70. console.log('Transaction proposal was good');
  71. } else {
  72. console.error('Transaction proposal was bad');
  73. }
  74. if (isProposalGood) {
  75. console.log(util.format(
  76. 'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s"',
  77. proposalResponses[0].response.status, proposalResponses[0].response.message));
  78. // build up the request for the orderer to have the transaction committed
  79. var request = {
  80. proposalResponses: proposalResponses,
  81. proposal: proposal
  82. };
  83. // set the transaction listener and set a timeout of 30 sec
  84. // if the transaction did not get committed within the timeout period,
  85. // report a TIMEOUT status
  86. var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing
  87. var promises = [];
  88. var sendPromise = channel.sendTransaction(request);
  89. promises.push(sendPromise); //we want the send transaction first, so that we know where to check status
  90. // get an eventhub once the fabric client has a user assigned. The user
  91. // is required bacause the event registration must be signed
  92. let event_hub = channel.newChannelEventHub(peer);
  93. // using resolve the promise so that result status may be processed
  94. // under the then clause rather than having the catch clause process
  95. // the status
  96. let txPromise = new Promise((resolve, reject) => {
  97. let handle = setTimeout(() => {
  98. event_hub.unregisterTxEvent(transaction_id_string);
  99. event_hub.disconnect();
  100. resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));
  101. }, 3000);
  102. event_hub.registerTxEvent(transaction_id_string, (tx, code) => {
  103. // this is the callback for transaction event status
  104. // first some clean up of event listener
  105. clearTimeout(handle);
  106. // now let the application know what happened
  107. var return_status = {event_status : code, tx_id : transaction_id_string};
  108. if (code !== 'VALID') {
  109. console.error('The transaction was invalid, code = ' + code);
  110. resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code));
  111. } else {
  112. console.log('The transaction has been committed on peer ' + event_hub.getPeerAddr());
  113. resolve(return_status);
  114. }
  115. }, (err) => {
  116. //this is the callback if something goes wrong with the event registration or processing
  117. reject(new Error('There was a problem with the eventhub ::'+err));
  118. },
  119. {disconnect: true} //disconnect when complete
  120. );
  121. event_hub.connect();
  122. });
  123. promises.push(txPromise);
  124. return Promise.all(promises);
  125. } else {
  126. console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
  127. throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
  128. }
  129. }).then((results) => {
  130. console.log('Send transaction promise and event listener promise have completed');
  131. // check the results in the order the promises were added to the promise all list
  132. if (results && results[0] && results[0].status === 'SUCCESS') {
  133. console.log('Successfully sent transaction to the orderer.');
  134. } else {
  135. console.error('Failed to order the transaction. Error code: ' + results[0].status);
  136. }
  137. if(results && results[1] && results[1].event_status === 'VALID') {
  138. console.log('Successfully committed the change to the ledger by the peer');
  139. } else {
  140. console.log('Transaction failed to be committed to the ledger due to ::'+results[1].event_status);
  141. }
  • 分享 收藏
2 条评论
  • 苏小乐 硕士在读 大学

    @Silver
    谢谢夸奖。坐标南京,今后可能去深圳。项目的话,目前可能没时间。

    2019-01-12 23:26
  • Silver 成员 IPSE Foundation

    fabric用的不错,在深圳吗?能接项目不?

    2019-01-06 22:17