Hyperledger Fabric SDK 示例fabric-samples-《balance-transfer》之四《安装chaincode》

本文已在我的公众号Fabric技术分享原创首发。
转载请标明出处:
https://blog.csdn.net/qq_27818541/article/details/78361292
本文出自:【BigManing的博客】

前言

使用sdk安装chaincode时需要指定以下参数

  • chaincode名称
  • chaincode版本
  • chaincode文件路径

在本文示例中传递的chaincode的路径为github.com/example_cc ,系统会加载gopath路径下src目录里面的github.com/example_cc下面的chaincode文件。设置gopath的操作,在具体实现里面提及到。

路由

app.js

//在指定peer上安装chaincode
app.post('/chaincodes', function(req, res) {
    //1 校验参数
    logger.debug('==================== INSTALL CHAINCODE ==================');
    var peers = req.body.peers;
    var chaincodeName = req.body.chaincodeName;
    var chaincodePath = req.body.chaincodePath;
    var chaincodeVersion = req.body.chaincodeVersion;
    //需要安装chaincode的peer
    logger.debug('peers : ' + peers); // target peers list
    //指定chaincode名称
    logger.debug('chaincodeName : ' + chaincodeName);
    //chaincode路径
    logger.debug('chaincodePath  : ' + chaincodePath);
    //chaincode版本
    logger.debug('chaincodeVersion  : ' + chaincodeVersion);
    if (!peers || peers.length == 0) {
        res.json(getErrorMessage('\'peers\''));
        return;
    }
    if (!chaincodeName) {
        res.json(getErrorMessage('\'chaincodeName\''));
        return;
    }
    if (!chaincodePath) {
        res.json(getErrorMessage('\'chaincodePath\''));
        return;
    }
    if (!chaincodeVersion) {
        res.json(getErrorMessage('\'chaincodeVersion\''));
        return;
    }
    // 2 由install-chaincode.js来具体实现
    install.installChaincode(peers, chaincodeName, chaincodePath, chaincodeVersion, req.username, req.orgname)
    .then(function(message) {
        res.send(message);
    });
});

这个路由只做了两件事

  • 必要参数校验
  • 调用封装好的installChaincode方法来具体实现安装chaincode

具体实现

install-chaincode.js

var path = require('path');
var fs = require('fs');
var util = require('util');
var config = require('../config.json');
var helper = require('./helper.js');
var logger = helper.getLogger('install-chaincode');
var tx_id = null;

var installChaincode = function(peers, chaincodeName, chaincodePath,
    chaincodeVersion, username, org) {
    logger.debug(
        '\n============ Install chaincode on organizations ============\n');
    //  设置gopath变量路径指向balance-transfer/artifacts/     加载chaincode使用
    helper.setupChaincodeDeploy();
    var channel = helper.getChannelForOrg(org);
    var client = helper.getClientForOrg(org);
    //1 获取该组织的admin
    return helper.getOrgAdmin(org).then((user) => {
        //2 封装request
        var request = {
            targets: helper.newPeers(peers, org), // peer对应的rpc地址
            chaincodePath: chaincodePath,
            chaincodeId: chaincodeName,
            chaincodeVersion: chaincodeVersion
        };
        //3 发送请求,安装chaincode
        return client.installChaincode(request);
    }, (err) => {
        logger.error('Failed to enroll user \'' + username + '\'. ' + err);
        throw new Error('Failed to enroll user \'' + username + '\'. ' + err);
    }).then((results) => {
        var proposalResponses = results[0];
        var proposal = results[1];
        var all_good = true;
        // 4 处理返回的结果
        for (var i in proposalResponses) {
            let one_good = false;
            if (proposalResponses && proposalResponses[i].response &&
                proposalResponses[i].response.status === 200) {
                one_good = true;
                logger.info('install proposal was good');
            } else {
                logger.error('install proposal was bad');
            }
            all_good = all_good & one_good;
        }
        // 是否都安装成功
        if (all_good) {
            logger.info(util.format(
                'Successfully sent install Proposal and received ProposalResponse: Status - %s',
                proposalResponses[0].response.status));
            logger.debug('\nSuccessfully Installed chaincode on organization ' + org +
                '\n');
            return 'Successfully Installed chaincode on organization ' + org;
        } else {
            logger.error(
                'Failed to send install Proposal or receive valid response. Response null or status is not 200. exiting...'
            );
            return 'Failed to send install Proposal or receive valid response. Response null or status is not 200. exiting...';
        }
    }, (err) => {
        logger.error('Failed to send install proposal due to error: ' + err.stack ?
            err.stack : err);
        throw new Error('Failed to send install proposal due to error: ' + err.stack ?
            err.stack : err);
    });
};
exports.installChaincode = installChaincode;

基本流程

Created with Raphaël 2.1.2 Start 设置gopath环境变量 获取到admin 组装request 调用client安装chaincode 处理结果,是否都安装成功 End yes no

API访问

github.com/example_cc 这个路径会从gopath环境变量中查找。

echo "POST Install chaincode on Org1"
echo
curl -s -X POST \
  http://localhost:4000/chaincodes \
  -H "authorization: Bearer $ORG1_TOKEN" \
  -H "content-type: application/json" \
  -d '{
    "peers": ["peer1", "peer2"],
    "chaincodeName":"mycc",
    "chaincodePath":"github.com/example_cc",
    "chaincodeVersion":"v0"
}'
echo
echo

控制台打印:

POST Install chaincode on Org1

Successfully Installed chaincode on organization org1

后台打印:

[2017-10-16 11:07:12.352] [DEBUG] SampleWebApp - Decoded from JWT token: username - Jim, orgname - org1
[2017-10-16 11:07:12.352] [DEBUG] SampleWebApp - ==================== INSTALL CHAINCODE ==================
[2017-10-16 11:07:12.352] [DEBUG] SampleWebApp - peers : peer1,peer2
[2017-10-16 11:07:12.352] [DEBUG] SampleWebApp - chaincodeName : mycc
[2017-10-16 11:07:12.353] [DEBUG] SampleWebApp - chaincodePath  : github.com/example_cc
[2017-10-16 11:07:12.353] [DEBUG] SampleWebApp - chaincodeVersion  : v0
[2017-10-16 11:07:12.353] [DEBUG] install-chaincode - 
============ Install chaincode on organizations ============

[2017-10-16 11:07:12.353] [DEBUG] Helper - [crypto_ecdsa_aes]: constructor, keySize: 256
[2017-10-16 11:07:12.354] [DEBUG] Helper - [crypto_ecdsa_aes]: Hash algorithm: SHA2, hash output size: 256
[2017-10-16 11:07:12.354] [DEBUG] Helper - [utils.CryptoKeyStore]: CryptoKeyStore, constructor - start
[2017-10-16 11:07:12.354] [DEBUG] Helper - [utils.CryptoKeyStore]: constructor, no super class specified, using config: fabric-client/lib/impl/FileKeyValueStore.js
[2017-10-16 11:07:12.354] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-10-16 11:07:12.354] [DEBUG] Helper - Msp ID : Org1MSP
[2017-10-16 11:07:12.354] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - start
[2017-10-16 11:07:12.355] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - have the key [Circular]
[2017-10-16 11:07:12.355] [DEBUG] Helper - [utils.CryptoKeyStore]: This class requires a CryptoKeyStore to save keys, using the store: {"opts":{"path":"/tmp/fabric-client-kvs_peerOrg1"}}
[2017-10-16 11:07:12.355] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-10-16 11:07:12.356] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore returning ks
[2017-10-16 11:07:12.356] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 0a66f3503a3322b2ca8e9dce03322d486ee6ec5970efaad3f153bc13aa2d942c
[2017-10-16 11:07:12.356] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: 312ad05190fa592fb9e8ac2dcdb23c84df7f49e4ee295c2aa1200a50c9146c46
[2017-10-16 11:07:12.356] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-10-16 11:07:12.357] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - start
[2017-10-16 11:07:12.357] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - have the key [Circular]
[2017-10-16 11:07:12.358] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-10-16 11:07:12.358] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 0a66f3503a3322b2ca8e9dce03322d486ee6ec5970efaad3f153bc13aa2d942c
[2017-10-16 11:07:12.359] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: 312ad05190fa592fb9e8ac2dcdb23c84df7f49e4ee295c2aa1200a50c9146c46
[2017-10-16 11:07:12.360] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-10-16 11:07:12.363] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 0a66f3503a3322b2ca8e9dce03322d486ee6ec5970efaad3f153bc13aa2d942c
[2017-10-16 11:07:12.363] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: 312ad05190fa592fb9e8ac2dcdb23c84df7f49e4ee295c2aa1200a50c9146c46
[2017-10-16 11:07:12.363] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 0a66f3503a3322b2ca8e9dce03322d486ee6ec5970efaad3f153bc13aa2d942c
[2017-10-16 11:07:12.363] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: 312ad05190fa592fb9e8ac2dcdb23c84df7f49e4ee295c2aa1200a50c9146c46
[2017-10-16 11:07:12.363] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 0a66f3503a3322b2ca8e9dce03322d486ee6ec5970efaad3f153bc13aa2d942c
[2017-10-16 11:07:12.363] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: 312ad05190fa592fb9e8ac2dcdb23c84df7f49e4ee295c2aa1200a50c9146c46
[2017-10-16 11:07:12.363] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
info: [packager/Golang.js]: packaging GOLANG from github.com/example_cc
[2017-10-16 11:07:12.384] [DEBUG] Helper - [crypto_ecdsa_aes]: ecdsa signature:  Signature {
  r: <BN: 98e0e079bcad1db53e72e6e001b03f8c76c50c499bc0237a1b8db341231a6341>,
  s: <BN: 23b0d0657eeaccc22def7a429c888c08a83dec55e56bc89fe34964319d6ac875>,
  recoveryParam: 1 }
[2017-10-16 11:07:12.400] [INFO] install-chaincode - install proposal was good
[2017-10-16 11:07:12.400] [INFO] install-chaincode - install proposal was good
[2017-10-16 11:07:12.401] [INFO] install-chaincode - Successfully sent install Proposal and received ProposalResponse: Status - 200
[2017-10-16 11:07:12.401] [DEBUG] install-chaincode - 
Successfully Installed chaincode on organization org1

猜你喜欢

转载自blog.csdn.net/qq_27818541/article/details/78361292