声明使用的版本
- fabric版本如下:1.4.8
- node-sdk版本:1.4.8
- node版本:v8.11.1
- ubuntu版本:16.04
sdk使用到的头文件如下
'use strict';
const { FileSystemWallet, Gateway, X509WalletMixin } = require('fabric-network');
const Client = require('fabric-client');
const utils = require('fabric-client/lib/utils.js');
const fs = require('fs');
const path = require('path');
const util = require('util');
const userOpt = require('./userOpt');
const {incHashString, getConfig, loadWallet} = require('./utils');
var log4js = require('log4js');
var getLogger = function(moduleName) {
var logger = log4js.getLogger(moduleName);
// logger.setLevel('DEBUG');
logger.level = 'DEBUG';
return logger;
};
const logger = getLogger('test');
链码的基本操作
安装链码
安装链码在cli中只需要简单的一步
peer chaincode install -n mycc -v 1.0 -p github.com/hyperledger/fabric-samples-1.4.8/chaincode/chaincode_example02/go
使用sdk的时候也需要同时构造这么多参数
- 1、当前的身份
- 2、链码的路径
- 3、合约名
- 4、合约版本号
- 5、通道名
- 6、合约文件夹路径
安装链码的内容也很简单,只是找到对应的链码位置合约名、版本号,构造对应的请求,提交到对应的peer中便可以创建了
实现代码如下(还是需要网络连接json文件)
// 安装链码
async function install(orgName, orgAdminName, chaincodePath, chaincodeId, chaincodeVersion, channelName, chaincodeDir) {
try {
const ccpPath = path.resolve(__dirname, "connect-sdk.json");
const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));
const walletPath = path.join(process.cwd(), 'wallet');
const wallet = new FileSystemWallet(walletPath);
console.log(`Wallet path: ${walletPath}`);
let checkUserResult = await userOpt.checkUser(wallet, orgAdminName)
if(!checkUserResult) {
// 从crypto-config文件夹中导出org admin的身份,保存到钱包中
await getAdminIdentify(wallet, orgAdminName, ccp.organizations[orgName].adminPrivateKey.path, ccp.organizations[orgName].signedCert.path, ccp.organizations[orgName].mspid)
}
// let config = getConfig();
const gateway = new Gateway();
await gateway.connect(ccp, { wallet, identity: orgAdminName, discovery: { enabled: true, asLocalhost: false } });
var client = gateway.getClient()
const targets = [];
for(let peerName of ccp.organizations[orgName].peers) {
// 取出地址
targets.push(
client.newPeer(
ccp.peers[peerName].url,
{
pem: fs.readFileSync(ccp.peers[peerName].peerOrgTlsCaCrt.path, { encoding: 'utf8' }),
clientKey: fs.readFileSync(ccp.peers[peerName].peerOrgClientKey.path, { encoding: 'utf8' }),
clientCert: fs.readFileSync(ccp.peers[peerName].peerOrgClientCert.path, { encoding: 'utf8' }),
'ssl-target-name-override':