区块链研习社

Hyperledger Fabric SDK 示例《balan

2017-10-17  本文已影响0人  BigManing

前言

上一篇文章我们已经启动了fabric网络/node服务,这篇文章主要来详细分析用户注册的过程。

具体实现

找到app.js中关于users的路由:

//注册用户 
app.post('/users', function(req, res) {
    // 1 参数校验
    var username = req.body.username;
    var orgName = req.body.orgName;
    logger.debug('End point : /users');
    logger.debug('User name : ' + username);
    logger.debug('Org name  : ' + orgName);
    if (!username) {
        res.json(getErrorMessage('\'username\''));
        return;
    }
    if (!orgName) {
        res.json(getErrorMessage('\'orgName\''));
        return;
    }
    // 2 生成jwt  添加用户名以及组织信息
    var token = jwt.sign({
        exp: Math.floor(Date.now() / 1000) + parseInt(hfc.getConfigSetting('jwt_expiretime')),
        username: username,
        orgName: orgName
    }, app.get('secret'));
    // 3  注册用户  如果成功连同jwt一起返回
    helper.getRegisteredUsers(username, orgName, true).then(function(response) {
        if (response && typeof response !== 'string') {
            response.token = token;
            res.json(response);
        } else {
            res.json({
                success: false,
                message: response
            });
        }
    });
});

从上面得知要看具体实现,还需要进入helper.js中查看getRegisteredUsers()

var getRegisteredUsers = function(username, userOrg, isJson) {
    var member;
    var client = getClientForOrg(userOrg);
    var enrollmentSecret = null;
//   设置公私钥存储的地方   
    return hfc.newDefaultKeyValueStore({
        //  这里只要求path参数  来作为存储的地方
        path: getKeyStoreForOrg(getOrgName(userOrg))
    }).then((store) => {
        //  设置状态持久化存储(如(证书,私钥。。))
        client.setStateStore(store);
        // clearing the user context before switching
        client._userContext = null;
        //1  获取用户信息  (从 内存-->statestore  依次查找)
        return client.getUserContext(username, true).then((user) => {
            if (user && user.isEnrolled()) {
                //  从持久化中 成功加载此 user
                logger.info('Successfully loaded member from persistence');
                return user;
            } else {
                let caClient = caClients[userOrg];
                //2  获得adminuser 来注册账户
                return getAdminUser(userOrg).then(function(adminUserObj) {
                    member = adminUserObj;
                    return caClient.register({
                        enrollmentID: username,
                        //  与此用户关联的隶属关系
                        affiliation: userOrg + '.department1'
                    }, member); // 注册员
                }).then((secret) => {
                    enrollmentSecret = secret;
                    logger.debug(username + ' registered successfully');
                    //3  注册成功后  拿着secret  来enroll
                    return caClient.enroll({
                        enrollmentID: username,
                        enrollmentSecret: secret
                    });
                }, (err) => {
                    logger.debug(username + ' failed to register');
                    return '' + err;
                    //return 'Failed to register '+username+'. Error: ' + err.stack ? err.stack : err;
                }).then((message) => {  // enroll 返回的信息
                    if (message && typeof message === 'string' && message.includes(
                            'Error:')) {
                        logger.error(username + ' enrollment failed');
                        return message;
                    }
                    logger.debug(username + ' enrolled successfully');
                    // 构建user对象 
                    member = new User(username);
                    member._enrollmentSecret = enrollmentSecret;
                    //4  设置此User实例的注册对象  来持久化在client中
                    return member.setEnrollment(message.key, message.certificate, getMspID(userOrg));
                }).then(() => {
                    //5  保存用户的上下文环境(e.g 证书 私钥 ) 用户签名 各种请求
                    client.setUserContext(member);
                    return member;
                }, (err) => {
                    logger.error(util.format('%s enroll failed: %s', username, err.stack ? err.stack : err));
                    return '' + err;
                });;
            }
        });
    }).then((user) => {
        // 6 返回用户信息
        if (isJson && isJson === true) {
            var response = {
                success: true,
                secret: user._enrollmentSecret,
                message: username + ' enrolled Successfully',
            };
            return response;
        }
        return user;
    }, (err) => {
        logger.error(util.format('Failed to get registered user: %s, error: %s', username, err.stack ? err.stack : err));
        return '' + err;
    });
};

基本流程

API访问

org1组织建立一个用户名为Jim的用户。在命令行里输入:

echo "POST request Enroll on Org1  ..."
echo
ORG1_TOKEN=$(curl -s -X POST \
  http://localhost:4000/users \
  -H "content-type: application/x-www-form-urlencoded" \
  -d 'username=Jim&orgName=org1')    
echo $ORG1_TOKEN

控制面板打印结果:

POST request Enroll on Org1  ...

{"success":true,"secret":"xDfluXIPURbu","message":"Jim enrolled Successfully","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDgxNTkyMjQsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MDgxMjMyMjR9.rE5UuViSzmDcdHNZRXt22izpopY5eVkJ7YbfXILjSQk"}


ORG1 token is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDgxNTkyMjQsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE1MDgxMjMyMjR9.rE5UuViSzmDcdHNZRXt22izpopY5eVkJ7YbfXILjSQk


// 上面的token是 访问后面API的必要参数

可以看出 Jim已经成功被注册了,其公私钥存放在/tmp/fabric-client-kvs_peerOrg1中(可在config.json中自定义keyValueStore路径):

这里写图片描述

node服务后台打印:

[2017-10-16 11:07:04.222] [DEBUG] SampleWebApp - End point : /users
[2017-10-16 11:07:04.222] [DEBUG] SampleWebApp - User name : Jim
[2017-10-16 11:07:04.222] [DEBUG] SampleWebApp - Org name  : org1
[2017-10-16 11:07:04.226] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-10-16 11:07:04.228] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- getValue
[2017-10-16 11:07:04.230] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-10-16 11:07:04.231] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- getValue

//----->公私钥存放路径

[2017-10-16 11:07:04.310] [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:04.311] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-10-16 11:07:04.311] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore returning ks
[2017-10-16 11:07:04.312] [DEBUG] Helper - [crypto_ecdsa_aes]: generateKey, store.setValue
[2017-10-16 11:07:04.313] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 5f8df5637db9f5e75af2990de09b57214b1eefcf834002cd79e6e7a634a23b68
[2017-10-16 11:07:04.313] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: bc8ce6511008bff20bb18ad6f105af889eb3c880cd2275cd97184d3378c47751
[2017-10-16 11:07:04.319] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue

//----->获取admin

[2017-10-16 11:07:04.715] [INFO] Helper - Successfully enrolled user 'admin'
[2017-10-16 11:07:04.716] [DEBUG] Helper - Msp ID : Org1MSP
[2017-10-16 11:07:04.717] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - start
[2017-10-16 11:07:04.721] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - have the key [Circular]
[2017-10-16 11:07:04.722] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-10-16 11:07:04.723] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 5f8df5637db9f5e75af2990de09b57214b1eefcf834002cd79e6e7a634a23b68
[2017-10-16 11:07:04.723] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: bc8ce6511008bff20bb18ad6f105af889eb3c880cd2275cd97184d3378c47751
[2017-10-16 11:07:04.724] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-10-16 11:07:04.726] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 5f8df5637db9f5e75af2990de09b57214b1eefcf834002cd79e6e7a634a23b68
[2017-10-16 11:07:04.726] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: bc8ce6511008bff20bb18ad6f105af889eb3c880cd2275cd97184d3378c47751
[2017-10-16 11:07:04.727] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 5f8df5637db9f5e75af2990de09b57214b1eefcf834002cd79e6e7a634a23b68
[2017-10-16 11:07:04.727] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: bc8ce6511008bff20bb18ad6f105af889eb3c880cd2275cd97184d3378c47751
[2017-10-16 11:07:04.728] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: 5f8df5637db9f5e75af2990de09b57214b1eefcf834002cd79e6e7a634a23b68
[2017-10-16 11:07:04.728] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: bc8ce6511008bff20bb18ad6f105af889eb3c880cd2275cd97184d3378c47751
[2017-10-16 11:07:04.728] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-10-16 11:07:04.743] [DEBUG] Helper - [crypto_ecdsa_aes]: ecdsa signature:  Signature {
  r: <BN: f1034e3347d230585a94f1ea21318d6217a20774754798641f599e33b8a9571f>,
  s: <BN: 5e4d05280fe82c2bbe93eb0e8fefb8998bacf160b6422e370b561c109b1c0ef2>,
  recoveryParam: 0 }
 
  //-----> Jim  register 成功
  
[2017-10-16 11:07:04.950] [DEBUG] Helper - Jim registered successfully
[2017-10-16 11:07:05.033] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore resolving store
[2017-10-16 11:07:05.034] [DEBUG] Helper - [crypto_ecdsa_aes]: generateKey, store.setValue
[2017-10-16 11:07:05.034] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: b3e2a75b9a4fd2b081589b1c45bde49f583aea9d7d466798c7b765c4ca96973d
[2017-10-16 11:07:05.034] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: c58820e5a9db75ab17841ac158e9389ad0d130a6827dc0682dcb2d2c5dccb349

 //-----> Jim  enrolled 成功
 
[2017-10-16 11:07:05.391] [DEBUG] Helper - Jim enrolled successfully
[2017-10-16 11:07:05.391] [DEBUG] Helper - Msp ID : Org1MSP
[2017-10-16 11:07:05.392] [DEBUG] Helper - [crypto_ecdsa_aes]: constructor, keySize: 256
[2017-10-16 11:07:05.392] [DEBUG] Helper - [crypto_ecdsa_aes]: Hash algorithm: SHA2, hash output size: 256
[2017-10-16 11:07:05.392] [DEBUG] Helper - [utils.CryptoKeyStore]: CryptoKeyStore, constructor - start
[2017-10-16 11:07:05.393] [DEBUG] Helper - [utils.CryptoKeyStore]: constructor, no super class specified, using config: fabric-client/lib/impl/FileKeyValueStore.js
[2017-10-16 11:07:05.393] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - start
[2017-10-16 11:07:05.393] [DEBUG] Helper - [crypto_ecdsa_aes]: importKey - have the key [Circular]
[2017-10-16 11:07:05.393] [DEBUG] Helper - [utils.CryptoKeyStore]: This class requires a CryptoKeyStore to save keys, using the store: {"opts":{"path":"/home/jiang/.hfc-key-store"}}
[2017-10-16 11:07:05.393] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore.js - constructor
[2017-10-16 11:07:05.394] [DEBUG] Helper - [utils.CryptoKeyStore]: _getKeyStore returning ks
[2017-10-16 11:07:05.394] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: b3e2a75b9a4fd2b081589b1c45bde49f583aea9d7d466798c7b765c4ca96973d
[2017-10-16 11:07:05.394] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: c58820e5a9db75ab17841ac158e9389ad0d130a6827dc0682dcb2d2c5dccb349
[2017-10-16 11:07:05.395] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
[2017-10-16 11:07:05.396] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: b3e2a75b9a4fd2b081589b1c45bde49f583aea9d7d466798c7b765c4ca96973d
[2017-10-16 11:07:05.397] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: c58820e5a9db75ab17841ac158e9389ad0d130a6827dc0682dcb2d2c5dccb349
[2017-10-16 11:07:05.398] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: b3e2a75b9a4fd2b081589b1c45bde49f583aea9d7d466798c7b765c4ca96973d
[2017-10-16 11:07:05.398] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: c58820e5a9db75ab17841ac158e9389ad0d130a6827dc0682dcb2d2c5dccb349
[2017-10-16 11:07:05.399] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param X: b3e2a75b9a4fd2b081589b1c45bde49f583aea9d7d466798c7b765c4ca96973d
[2017-10-16 11:07:05.400] [DEBUG] Helper - [ecdsa/key.js]: ECDSA curve param Y: c58820e5a9db75ab17841ac158e9389ad0d130a6827dc0682dcb2d2c5dccb349
[2017-10-16 11:07:05.400] [DEBUG] Helper - [FileKeyValueStore.js]: FileKeyValueStore -- setValue
上一篇下一篇

猜你喜欢

热点阅读