美文网首页
编写nodejs代码

编写nodejs代码

作者: 凡星_ | 来源:发表于2020-05-23 16:27 被阅读0次

这部分内容参考:https://www.jianshu.com/p/a671c3002b64 并作为简化

先在github.com目录下创建一个项目目录,名叫xiaowei-app

 ` 

cd $GOPATH/src/github.com/

mkdir -p fabric-sdk/xiaowei-app

cd fabric-sdk/xiaowei-app

然后在这个目录创建几个js文件

1、新建 package.json

{

    "name": "fabcar",

    "version": "1.0.0",

    "description": "汽车资产管理应用",

    "main": "fabcar.js",

    "scripts": {

        "test": "echo \"Error: no test specified\" && exit 1"

    },

    "dependencies": {

        "fabric-ca-client": "~1.4.0",

        "fabric-client": "~1.4.0",

        "grpc": "^1.6.0"

    },

    "author": "小韦云",

    "license": "Apache-2.0",

    "keywords": []

}

 ` 

2、新建 enrollAdmin.js

 ` 

'use strict';

// 注册管理员用户

var Fabric_Client = require('fabric-client');

var Fabric_CA_Client = require('fabric-ca-client');

var path = require('path');

var util = require('util');

var os = require('os');

var fabric_client = new Fabric_Client();

var fabric_ca_client = null;

var admin_user = null;

var member_user = null;

var store_path = path.join(__dirname, 'hfc-key-store');

console.log(' Store path:'+store_path);

Fabric_Client.newDefaultKeyValueStore({ path: store_path

}).then((state_store) => {

    fabric_client.setStateStore(state_store);

    var crypto_suite = Fabric_Client.newCryptoSuite();

    var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});

    crypto_suite.setCryptoKeyStore(crypto_store);

    fabric_client.setCryptoSuite(crypto_suite);

    var tlsOptions = {

        trustedRoots: [],

        verify: false

    };

    fabric_ca_client = new Fabric_CA_Client('http://localhost:7054', tlsOptions , 'ca.example.com', crypto_suite);

    return fabric_client.getUserContext('admin', true);

}).then((user_from_store) => {

    if (user_from_store && user_from_store.isEnrolled()) {

        console.log('Successfully loaded admin from persistence');

        admin_user = user_from_store;

        return null;

    } else {

        return fabric_ca_client.enroll({

          enrollmentID: 'admin',

          enrollmentSecret: 'adminpw'

        }).then((enrollment) => {

          console.log('Successfully enrolled admin user "admin"');

          return fabric_client.createUser(

              {username: 'admin',

                  mspid: 'Org1MSP',

                  cryptoContent: { privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: enrollment.certificate }

              });

        }).then((user) => {

          admin_user = user;

          return fabric_client.setUserContext(admin_user);

        }).catch((err) => {

          console.error('Failed to enroll and persist admin. Error: ' + err.stack ? err.stack : err);

          throw new Error('Failed to enroll admin');

        });

    }

}).then(() => {

    console.log('Assigned the admin user to the fabric client ::' + admin_user.toString());

}).catch((err) => {

    console.error('Failed to enroll admin: ' + err);

});

 ` 

3、新建 registerUser.js.

 ` 

//注册普通用户

var Fabric_Client = require('fabric-client');

var Fabric_CA_Client = require('fabric-ca-client');

var path = require('path');

var util = require('util');

var os = require('os');

var fabric_client = new Fabric_Client();

var fabric_ca_client = null;

var admin_user = null;

var member_user = null;

var store_path = path.join(__dirname, 'hfc-key-store');

console.log(' Store path:'+store_path);

Fabric_Client.newDefaultKeyValueStore({ path: store_path

}).then((state_store) => {

    fabric_client.setStateStore(state_store);

    var crypto_suite = Fabric_Client.newCryptoSuite();

    var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});

    crypto_suite.setCryptoKeyStore(crypto_store);

    fabric_client.setCryptoSuite(crypto_suite);

    var tlsOptions = {

        trustedRoots: [],

        verify: false

    };

    fabric_ca_client = new Fabric_CA_Client('http://localhost:7054', null , '', crypto_suite);

    return fabric_client.getUserContext('admin', true);

}).then((user_from_store) => {

    if (user_from_store && user_from_store.isEnrolled()) {

        console.log('Successfully loaded admin from persistence');

        admin_user = user_from_store;

    } else {

        throw new Error('Failed to get admin.... run enrollAdmin.js');

    }

    return fabric_ca_client.register({enrollmentID: 'user1', affiliation: 'org1.department1',role: 'client'}, admin_user);

}).then((secret) => {

    console.log('Successfully registered user1 - secret:'+ secret);

    return fabric_ca_client.enroll({enrollmentID: 'user1', enrollmentSecret: secret});

}).then((enrollment) => {

  console.log('Successfully enrolled member user "user1" ');

  return fabric_client.createUser(

    {username: 'user1',

    mspid: 'Org1MSP',

    cryptoContent: { privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: enrollment.certificate }

    });

}).then((user) => {

    member_user = user;

    return fabric_client.setUserContext(member_user);

}).then(()=>{

    console.log('User1 was successfully registered and enrolled and is ready to interact with the fabric network');

}).catch((err) => {

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

    if(err.toString().indexOf('Authorization') > -1) {

        console.error('Authorization failures may be caused by having admin credentials from a previous CA instance.\n' +

        'Try again after deleting the contents of the store directory '+store_path);

    }

});

 ` 

4、新建 query.js

 ` 

'use strict';

//通过链码查询

var Fabric_Client = require('fabric-client');

var path = require('path');

var util = require('util');

var os = require('os');

var fabric_client = new Fabric_Client();

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;

Fabric_Client.newDefaultKeyValueStore({ path: store_path

}).then((state_store) => {

    fabric_client.setStateStore(state_store);

    var crypto_suite = Fabric_Client.newCryptoSuite();

    var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});

    crypto_suite.setCryptoKeyStore(crypto_store);

    fabric_client.setCryptoSuite(crypto_suite);

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

    }

    const request = {

        chaincodeId: 'fabcar',

        fcn: 'queryAllCars',

        args: ['']

    };

    return channel.queryByChaincode(request);

}).then((query_responses) => {

    console.log("Query has completed, checking results");

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

});

5、新建 invoke.js

'use strict';

//调用链码

var Fabric_Client = require('fabric-client');

var path = require('path');

var util = require('util');

var os = require('os');

var fabric_client = new Fabric_Client();

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;

Fabric_Client.newDefaultKeyValueStore({

    path: store_path

}).then((state_store) => {

    fabric_client.setStateStore(state_store);

    var crypto_suite = Fabric_Client.newCryptoSuite();

    var crypto_store = Fabric_Client.newCryptoKeyStore({ path: store_path });

    crypto_suite.setCryptoKeyStore(crypto_store);

    fabric_client.setCryptoSuite(crypto_suite);

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

    }

    tx_id = fabric_client.newTransactionID();

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

    var request = {

        chaincodeId: 'fabcar',

        fcn: 'createCar',

        args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],

        chainId: 'mychannel',

        txId: tx_id

    };

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

        var request = {

            proposalResponses: proposalResponses,

            proposal: proposal

        };

        var transaction_id_string = tx_id.getTransactionID();

        var promises = []; var sendPromise = channel.sendTransaction(request);

        promises.push(sendPromise);

        let txPromise = new Promise((resolve, reject) => {

            let handle = setTimeout(() => {

                event_hub.unregisterTxEvent(transaction_id_string);

                event_hub.disconnect();

                resolve({ event_status: 'TIMEOUT' });

            }, 3000);

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

                clearTimeout(handle);

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

                } else {

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

                    resolve(return_status);

                }

            }, (err) => {

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

            },

                { disconnect: true }

            );

            event_hub.connect();

        });

        promises.push(txPromise); return Promise.all(promises);

    } else {

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

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

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

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

});

 ` 

本文由小韦云原创,转载请注明出处:https://www.bctos.cn/doc/4/1825,否则追究其法律责任

相关文章

  • 编写nodejs代码

    这部分内容参考:https://www.jianshu.com/p/a671c3002b64并作为简化 先在git...

  • websocket及stomp.js

    websocket 服务端(node) 安装nodejs-websocket 编写最基本的服务的代码,可以查看文档...

  • NodeJs的安装及NPM使用

    Nodejs是一个应用编程平台,能运行javascript语言编写的代码,提供了javascript运行环境,基于...

  • 项目构建---全步骤

    nodeJS安装 1.使用bower必须要安装nodeJS,因为bower就是用nodeJS编写的,nodeJS是...

  • nodejs的基本操作

    nodejs的模块 代码展示: nodejs文件操作 代码展示: nodejs的io键盘交互 代码展示: node...

  • 2. 代码的组织和部署

    代码的组织和部署 有经验的C程序员在编写一个新程序时首先从make文件写起。同样的,使用NodeJS编写程序前,为...

  • gulp项目构建

    bower 的安装,需要nodejs 因为bower就是nodejs编写的,nodejs是他的运行平台。 安装no...

  • nodemon

    为什么要使用nodemon 在编写调试Nodejs项目的时候,如果修改了项目的代码,则需要频繁的手动close掉,...

  • nodejs-websocket代码nodejs版本

    nodejs-websocket代码nodejs版本

  • 网络爬虫实现批量下载图片

    需求:用nodejs编写代码实现下载某个网站单页面的所有图片 开发思路: 使用HTTP模块发起请求,获取到响应的数...

网友评论

      本文标题:编写nodejs代码

      本文链接:https://www.haomeiwen.com/subject/wrklahtx.html