hyperledger fabric nodejs SDK开发(四)------SDK修改账本机制

SDK修改账本机制

 async saveUser (ctx) {

                  const body = ctx.request.body; //获取请求内容

        console.log(`request`,body.k1) //打印请求k1内容

        var fabric_client = new Fabric_Client(); //新建一个客户端实例

                  // setup the fabric network

//发送消息到order来构建一个新的channel,命名为mychannel,返回一个空对象

                  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(os.homedir(), '.hfc-key-store'); //设置文件存储路径

                  console.log('Store path:'+store_path); //打印文件存储路径

                  var tx_id = null; //设置空的交易ID

                  // create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting

                  let result = await 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');

                      }

            //获取交易id:基于client对象上分配的用户身份

                      // get a transaction id object based on the current user assigned to fabric client

                      tx_id = fabric_client.newTransactionID();

                      console.log("Assigning transaction_id: ", tx_id._transaction_id);

             //构建请求

                      // recordTuna - requires 5 args, ID, vessel, location, timestamp,holder - ex: args: ['10', 'Hound', '-12.021, 28.012', '1504054225', 'Hansel'],

                      // send proposal to endorser

                      const request = {

                          //targets : --- letting this default to the peers assigned to the channel

                          chaincodeId: 'dateContract10',

                          fcn: 'writeContract',

                          args: [body.k0,body.k1,body.k2,body.k3,body.k4,body.k5,body.k6,body.k7,body.k8],

                          chainId: 'mychannel',

                          txId: tx_id

                      };

         //SDK根据request生成proposal,并调用sendPeersProposal()

        // 将提案发送给背书节点,然后将返回的提案响应连同交易提案一起打包返回给client

                      // send the transaction proposal to the peers

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

                //通过交易响应和提案,构建发送到排序服务的请求

                          // build up the request for the orderer to have the transaction committed

                          var request = {

                              proposalResponses: proposalResponses,

                              proposal: proposal

                          };

               

                          // set the transaction listener and set a timeout of 30 sec

                          // if the transaction did not get committed within the timeout period,

                          // report a TIMEOUT status

//获取事件处理所使用的事务ID字符串                    

var transaction_id_string = tx_id.getTransactionID(); //Get the transaction ID string to be used by the event processing

                          var promises = [];  //构建promises数组

                //将交易请求发送给orderer节点,内部调用sendBroadcast(envelope)

                          var sendPromise = channel.sendTransaction(request);

                //将获得的请求结果添加到数组中  

                         promises.push(sendPromise); //we want the send transaction first, so that we know where to check status

                // 一旦fabric客户端分配了用户,就得到Evestub。用户必须签名事件中心登记。

                          // get an eventhub once the fabric client has a user assigned. The user

                          // is required bacause the event registration must be signed

                          let event_hub = fabric_client.newEventHub();  //实例化一个事件中心

                          event_hub.setPeerAddr('grpc://localhost:7053'); //将事件中心绑定到一个新的节点上

                //设置promise

                          // using resolve the promise so that result status may be processed

                          // under the then clause rather than having the catch clause process

                          // the status

                          let txPromise = new Promise((resolve, reject) => { //设置一个promise实例(异步执行)

                              let handle = setTimeout(() => { //设置超时函数

                                  event_hub.disconnect();

                                  resolve({event_status : 'TIMEOUT'}); //we could use reject(new Error('Trnasaction did not complete within 30 seconds'));//我们也可以使用reject(newError(“Trnasaction在30秒内没有完成”));

                              }, 3000);

                              event_hub.connect();  //连接事件中心

                    //注册交易事件监听,当交易被peer提交到账本中时可以得到反馈

                              event_hub.registerTxEvent(transaction_id_string, (tx, code) => {

                                  // this is the callback for transaction event status

                        //这是交易事件状态的回调。

                                  // first some clean up of event listener

                        //首先对事件侦听器进行初始化

                                  clearTimeout(handle);

                        //解除事件监听

                                  event_hub.unregisterTxEvent(transaction_id_string);

                                  event_hub.disconnect(); //断开事件中心连接

                        //设置返回代码和交易ID

                                  // now let the application know what happened

                                  var return_status = {event_status : code, tx_id : transaction_id_string};      //如果代码不是有效的

                                  if (code !== 'VALID') {

                                      console.error('The transaction was invalid, code = ' + code);

                                      resolve(return_status); // we could use reject(new Error('Problem with the tranaction, event status ::'+code)); //同理可以使用reject函数

                                  } else {  //交易已经提交到账本

                                      console.log('The transaction has been committed on peer ' + event_hub._ep._endpoint.addr);

                                      resolve(return_status);

                                  }

                              }, (err) => {

                                  //this is the callback if something goes wrong with the event registration or processing如果事件注册或处理出现问题,则此回调

                                  reject(new Error('There was a problem with the eventhub ::'+err));

                              });

                          });

                          promises.push(txPromise);//将监听到的信息添加到promises



                          return Promise.all(promises); //返回promises对象

                      } else {

//如果出错,打印未能发送提案或收到有效响应。响应空或状态不是200。退出…

                          console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');

                          throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');

                      }

                  }).then((results) => {//打印发送交易背书和事件监听完成

                      console.log('Send transaction promise and event listener promise have completed');  //检查结果第一个参数交易提案是否在在order服务顺序的背书清单中

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

                                    //res.send(tx_id.getTransactionID());//获取交易ID

                                    return tx_id.getTransactionID();

                      } else {//打印出没有成功提交到排序服务

                          console.error('Failed to order the transaction. Error code: ' + response.status);

                      }

           //检查交易响应及其返回代码是否有效

                      if(results && results[1] && results[1].event_status === 'VALID') {

                          console.log('Successfully committed the change to the ledger by the peer');

                                    //res.send(tx_id.getTransactionID());//打印出交易ID

                                    return tx_id.getTransactionID();

                      } else { //交易没有成功添加到账本中

                          console.log('Transaction failed to be committed to the ledger due to ::'+results[1].event_status);

                      }

                  }).catch((err) => { //否则出现任何错误,打印调用账本失败

                      console.error('Failed to invoke successfully :: ' + err);

                  });

                  ctx.body = result  //获得交易ID

                  console.log('result===>',result) 打印出交易ID

    }

}

流程:

与前端交互,获取前端输入内容,然后初始化客户端,注册通道、背书节点、排序节点,空的交易ID、设置文件存储路径,然后设置加密模块以及文件路径,通过SDK构建请求,将其发送到背书节点,获得交易提案和交易提案响应,同时检查提案和响应,之后将提案和响应构建请求,发送到排序服务,构建promises数组,将排序结果添加到promises数组中,注册一个事件监听中心,初始化监听后进行监听,之后监听成功则断开监听,获得监听消息和代码后,加入promises数组,否则检查代码,打印错误是否提交到排序服务和账本。最后获得交易ID,打印出交易ID。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hyperledger Fabric是一个基于区块链技术的开源平台,用于构建企业级的去中心化应用程序。Hyperledger Fabric Node.js SDKHyperledger Fabric的官方软件开发工具包,用于在Node.js环境下开发和部署Fabric网络。 Hyperledger Fabric Node.js SDK开发流程如下: 1. 准备环境:首先需要安装Node.js和npm包管理器。可以从官方网站上下载并安装最新的Node.js版本。然后使用npm安装Hyperledger Fabric Node.js SDK。 2. 创建项目:在开发过程中,创建一个新的Node.js项目是一个好习惯。使用命令行工具或IDE创建一个新的文件夹,并在其中初始化一个新的Node.js项目。运行"npm init"命令,按照提示填写项目的基本信息。 3. 安装依赖:使用npm安装Hyperledger Fabric Node.js SDK以及其他依赖库。在项目的根目录下运行"npm install fabric-network fabric-ca-client"命令。 4. 配置文件:在项目中创建一个配置文件,用于指定Fabric网络的连接信息和身份认证信息。配置文件中包括Fabric网络的URL、通道名称、智能合约的名称等。 5. 连接网络:使用SDK的API连接到Fabric网络。使用配置文件中的连接信息创建一个新的Gateway对象,并调用connect()方法连接到指定的Fabric网络。 6. 身份认证:在连接到Fabric网络后,需要使用身份认证信息来访问链码(智能合约)。使用SDK的API提供的身份认证机制,来设置当前用户的身份认证信息。 7. 调用链码:一旦连接和身份认证都完成,就可以使用SDK的API调用链码的方法。通过调用链码的函数,可以查询或更新区块链上的数据。 8. 断开连接:在使用完SDK后,需要调用disconnect()方法断开与Fabric网络的连接,释放资源。 总结起来,Hyperledger Fabric Node.js SDK开发流程包括准备环境、创建项目、安装依赖、配置文件、连接网络、身份认证、调用链码和断开连接。开发人员可以使用SDK的API来完成Fabric网络的各项操作,从而实现企业级的区块链应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值