超级帐本合约调用——fabric SDK Node调用TBaaS的合约

2020-09-22 16:33:27 浏览数 (1)

TBaaS使用原生sdk使用node sdk调用示例。用户证书就是代表组织的一个用户。Connection Profile描述了网络的拓扑结构,在调用时可以编写使用到的orderer,peer,organizations即可进行合约的调用。

Hyperledger Fabric智能合约调用示例.文中所使用的合约为官网示例

1. 安装npm

yum install npm -y

2. 升级node

node -v

如果版本低于10,则需要升级node,

  • Node.js, version 10 is supported from 10.15.3 and higher
  • Node.js, version 12 is supported from 12.13.1 and higher
  • npm tool version 6 or highe

可以参考如下步骤,升级node

npm install -g n

n stable

可选 npm rebuild

参考:https://juejin.im/post/5c09e47ee51d45721d71087d

3. 安装 sdk

npm install fabric-network@1.4.10

4. 调用sdk

4.1. 生成证书

根据文档https://cloud.tencent.com/document/product/663/38395 进行生成用户公私钥,其中out_sk文件放置到wallet目录下,csr文件登录控制台并上传至用户证书模块,以及下载用户证书并复制到wallet目录下命名,nginx证书下载并放置wallet目录下

wallet是自己创建的目录,不是必须存在的。

用户证书

下载用户证书下载用户证书

nginx证书:

4.2. 编写Connection Profile

新建Fabric SDK 文档中所描述的 Connection Profile

https://hyperledger-fabric.readthedocs.io/en/release-2.0/developapps/connectionprofile.html

示例:connection.yaml

代码语言:javascript复制
version: 1.0.0
client:
    organization: Neworg
    connection:
        timeout:
            peer:
                endorser: '300'
                eventHub: '60'
                eventReg: '3'
            orderer: '300'
channels:
    qtardngzy:
        orderers:
        - orderer0.bclpbtf9w1ne
        peers:
            peer0.neworg.bclpbtf9w1ne:
                endorsingPeer: true
                chaincodeQuery: true
                ledgerQuery: true
                eventSource: true
                discover: true
organizations:
    Neworg:
        mspid: NeworgMSP-bclpbtf9w1ne
        peers:
        - peer0.neworg.bclpbtf9w1ne
 
orderers:
    orderer0.bclpbtf9w1ne:
        url: grpcs://neworg-bclpbtf9w1ne.tbaas.tech:8080/orderer0.bclpbtf9w1ne
        grpcOptions:
            ssl-target-name-override: nginx.bclpbtf9w1ne.tbaas
            grpc.primary_user_agent: /orderer0.bclpbtf9w1ne
        tlsCACerts:
            path: /root/fabric/wallet/nginx.pem
peers:
    peer0.neworg.bclpbtf9w1ne:
        url: grpcs://neworg-bclpbtf9w1ne.tbaas.tech:8080/peer0.neworg.bclpbtf9w1ne
        grpcOptions:
            ssl-target-name-override: nginx.bclpbtf9w1ne.tbaas
            grpc.primary_user_agent: /peer0.neworg.bclpbtf9w1ne
        tlsCACerts:
            path: /root/fabric/wallet/nginx.pem

参数说明:

client:

organization: Neworg

组织名在组织管理页获取,client下其它参数不需要修改

channels:

选择要操作的channel,在通道管理页选择复制通道名

orderers,在运营监控,选择任意一个或者多个order节点

organizations:

organization: Neworg

mspid:NeworgMSP-bclpbtf9w1ne 

peers:peer0.neworg.bclpbtf9w1ne

组织管理页可以看到,选择当前帐号所在的组织的相关信息

组织组织

orderers:

url: grpcs://neworg-bclpbtf9w1ne.tbaas.tech:8080/orderer0.bclpbtf9w1ne

外网域名/order名称

概览页和访问管理页的外网域名

ssl-target-name-override:nginx.网络根域.tbaas

tlsCACerts

ng的证书路径

peers:

url: grpcs://neworg-bclpbtf9w1ne.tbaas.tech:8080/peer0.neworg.bclpbtf9w1ne

外网域名/peer名称

4.3. 调用合约

node invoke.js

代码语言:javascript复制
/*
 * SPDX-License-Identifier: Apache-2.0
 */
 
'use strict';
 
const Client = require('fabric-client');
const fs = require('fs');
const path = require('path');
 
const ccpPath = path.resolve(__dirname, 'wallet', 'connection.yaml');
const keyPath = path.resolve(__dirname, 'wallet', 'out_sk');
const certPath = path.resolve(__dirname, 'wallet', 'demo@neworg.bclpbtf9w1ne@client.pem');
 
var keyPEM = Buffer.from(fs.readFileSync(keyPath)).toString();
var certPEM = fs.readFileSync(certPath).toString();
 
 
async function main() {
    try {
    var client = Client.loadFromConfig(ccpPath);   
 
    await client.createUser({
        username: 'demo',
        mspid: 'NeworgMSP-bclpbtf9w1ne',
        cryptoContent: {
            privateKeyPEM: keyPEM,
            signedCertPEM: certPEM
        },
                skipPersistence: true
    });
 
    var channel = client.getChannel();
 
    var tx_object = client.newTransactionID();
     
 
    var request = {
            chaincodeId : 'qtaccgyhr',
            fcn: 'invoke',
            args: ['a', 'b','10'],
            txId: tx_object
    };
 
    var proposalResponse = await channel.sendTransactionProposal(request)
 
    request = {
            proposalResponses: proposalResponse[0],
            proposal: proposalResponse[1],
            header: proposalResponse[2]
        };
    await channel.sendTransaction(request);
 
    const tx_id = tx_object.getTransactionID();
 
    let channel_event_hubs = channel.getChannelEventHubsForOrg();
 
    const channel_event_hub = channel_event_hubs[0];
 
 
    let event_monitor = new Promise((resolve, reject) => {
        let handle = setTimeout(() => {
            channel_event_hub.unregisterTxEvent(tx_id);
                console.log('Timeout - Failed to receive the transaction event');
                reject(new Error('Timed out waiting for block event'));
        },20000);
 
        channel_event_hub.registerTxEvent(tx_id, (tx,code) => {
            channel_event_hub.unregisterTxEvent(tx_id);
                clearTimeout(handle);
                console.log(tx)
                console.log(code)
                console.log('Successfully received the transaction event');
                resolve();
        },(error)=> {
                clearTimeout(handle);
                console.log('Failed to receive the transaction event ::' error);
                reject(error);
            });
 
        channel_event_hub.connect();
    });
 
    await Promise.all([event_monitor]);
        process.exit(0);
    } catch (error) {
        console.error(`Failed to submit transaction: ${error}`);
        process.exit(1);
    }
}
 
 
 
main();
合约调用合约调用

Query

代码语言:javascript复制
/*
 * SPDX-License-Identifier: Apache-2.0
 */
 
'use strict';
 
const Client = require('fabric-client');
const fs = require('fs');
const path = require('path');
const util = require('util')
const ccpPath = path.resolve(__dirname, 'wallet', 'connection_sdk.yaml');
const keyPath = path.resolve(__dirname, 'wallet', 'sdk_out_sk');
const certPath = path.resolve(__dirname, 'wallet', 'sdktest@sdkorg.bclpbtf9w1ne@client.pem');
 
var keyPEM = Buffer.from(fs.readFileSync(keyPath)).toString();
var certPEM = fs.readFileSync(certPath).toString();
 
 
async function main() {
    try {
    var client = Client.loadFromConfig(ccpPath);   
 
    await client.createUser({
        username: 'sdktest',
        mspid: 'sdkOrgMSP-bclpbtf9w1ne',
        cryptoContent: {
            privateKeyPEM: keyPEM,
            signedCertPEM: certPEM
        },
                skipPersistence: true
    });
 
    var channel = client.getChannel();
 
    var tx_object = client.newTransactionID();
     
 
    var request = {
            chaincodeId : 'qtaccgyhr',
            fcn: 'query',
            args: ['b'],
            txId: tx_object
    };
     
     
    const responsePayloads = await channel.queryByChaincode(request);
    for (let i = 0; i < responsePayloads.length; i  ) {
        console.log(util.format('Query result from peer [%s]: %s', i, responsePayloads[i].toString('utf8')));
    }
 
        process.exit(0);
    } catch (error) {
        console.error(`Failed to submit transaction: ${error}`);
        process.exit(1);
    }
}
 
 
main();

0 人点赞