启动Fabric网络
service docker start
setenforce 0
cd $GOPATH/src/github.com/hyperledger/fabric/examples/e2e_cli/
./network_setup.sh up
安装Node.js
yum install -y nodejs
安装fabric-client模块
npm install fabric-client -g --registry=https://registry.npm.taobao.org
报错:make: g++: Command not found
解决办法:yum -y install gcc gcc-c++
代码
https://github.com/fengchunjian/nodejs_examples/tree/master/fabric
//queryV2.js
var hfc = require('fabric-client');
var path = require('path');
var sdkUtils = require('fabric-client/lib/utils');
var fs = require('fs');
var options = {
user_id : '[email protected]',
msp_id : 'Org1MSP',
channel_id : 'mychannel',
chaincode_id : 'mycc',
network_url : 'grpcs://localhost:7051',
privateKeyFolder : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/keystore',
signedCert : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/signcerts/[email protected]',
tls_cacerts : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt',
server_hostname : 'peer0.org1.example.com'
};
var channel = {};
var client = null;
var getKeyFilesInDir = function(dir) {
var files = fs.readdirSync(dir);
var keyFiles = [];
files.forEach(function(file_name) {
var filePath = path.join(dir, file_name);
if (file_name.endsWith('_sk')) {
keyFiles.push(filePath);
}
});
return keyFiles;
};
Promise.resolve().then(function() {
console.log('Load privateKey and signedCert');
client = new hfc();
var createUserOpt = {
username : options.user_id,
mspid : options.msp_id,
cryptoContent : {
privateKey : getKeyFilesInDir(options.privateKeyFolder)[0],
signedCert : options.signedCert
}
};
return sdkUtils.newKeyValueStore({
path : '/tmp/fabric-client-stateStore/'
}).then(function(store) {
client.setStateStore(store);
return client.createUser(createUserOpt);
});
}).then(function(user) {
channel = client.newChannel(options.channel_id);
var data = fs.readFileSync(options.tls_cacerts);
var peer = client.newPeer(options.network_url, {
pem : Buffer.from(data).toString(),
'ssl-target-name-override' : options.server_hostname
});
peer.setName('peer0');
channel.addPeer(peer);
return;
}).then(function() {
console.log('Make query');
var transaction_id = client.newTransactionID();
console.log('Assigning transaction_id: ', transaction_id._transaction_id);
var request = {
chaincodeId : options.chaincode_id,
txId : transaction_id,
fcn : 'query',
args : ['a']
};
return channel.queryByChaincode(request);
}).then(function(query_responses) {
console.log('returned from query');
if (!query_responses.length) {
console.log('No payloads were returned from query');
} else {
console.log('Query result count = ', query_responses.length);
}
if (query_responses[0] instanceof Error) {
console.error('error from query = ', query_responses[0]);
}
console.log('Response is ', query_responses[0].toString());
}).catch(function(err) {
console.error('Caught Error', err);
});
node queryV2.js
Load privateKey and signedCert
Make query
Assigning transaction_id: b11942efe97dc0c7b457f13de5481cbac385c7c8599ac86d8f33f4f086a2c018
returned from query
Query result count = 1
Response is 90
//invokeV2.js
var hfc = require('fabric-client');
var path = require('path');
var util = require('util');
var sdkUtils = require('fabric-client/lib/utils');
var fs = require('fs');
var options = {
user_id : '[email protected]',
msp_id : 'Org1MSP',
channel_id : 'mychannel',
chaincode_id : 'mycc',
peer_url : 'grpcs://localhost:7051',
event_url : 'grpcs://localhost:7053',
orderer_url : 'grpcs://localhost:7050',
privateKeyFolder : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/keystore',
signedCert : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp/signcerts/[email protected]',
peer_tls_cacerts : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt',
orderer_tls_cacerts : '/root/golang/src/github.com/hyperledger/fabric/examples/e2e_cli/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt',
server_hostname : 'peer0.org1.example.com'
};
var channel = {};
var client = null;
var targets = [];
var tx_id = null;
var getKeyFilesInDir = function(dir) {
var files = fs.readdirSync(dir);
var keyFiles = [];
files.forEach(function(file_name) {
var filePath = path.join(dir, file_name);
if (file_name.endsWith('_sk')) {
keyFiles.push(filePath);
}
});
return keyFiles;
};
Promise.resolve().then(function() {
console.log('Load privateKey and signedCert');
client = new hfc();
var createUserOpt = {
username : options.user_id,
mspid : options.msp_id,
cryptoContent : {
privateKey : getKeyFilesInDir(options.privateKeyFolder)[0],
signedCert : options.signedCert
}
};
return sdkUtils.newKeyValueStore({
path : '/tmp/fabric-client-stateStore'
}).then(function(store) {
client.setStateStore(store);
return client.createUser(createUserOpt);
});
}).then(function(user) {
channel = client.newChannel(options.channel_id);
var data = fs.readFileSync(options.peer_tls_cacerts);
var peer = client.newPeer(options.peer_url, {
pem : Buffer.from(data).toString(),
'ssl-target-name-override' : options.server_hostname
});
channel.addPeer(peer);
var odata = fs.readFileSync(options.orderer_tls_cacerts);
var caroots = Buffer.from(odata).toString();
var orderer = client.newOrderer(options.orderer_url, {
pem : caroots,
'ssl-target-name-override' : 'orderer.example.com'
});
channel.addOrderer(orderer);
targets.push(peer);
return;
}).then(function() {
tx_id = client.newTransactionID();
console.log('Assigning transaction_id :', tx_id._transaction_id);
var request = {
targets : targets,
chaincodeId : options.chaincode_id,
fcn : 'invoke',
args : ['a', 'b', '10'],
chainId : options.channel_id,
txId : tx_id
};
return channel.sendTransactionProposal(request);
}).then(function(results) {
var proposalResponses = results[0];
var proposal = results[1];
var header = results[2];
var isProposalGood = false;
if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) {
isProposalGood = true;
console.log('transaction proposal was good');
} else {
console.log('transaction proposal was bad');
}
if (isProposalGood) {
console.log(util.format(
'Successfully sent Proposal and received ProposalResponse: Status - %s, message - %s, metadata - %s, endorsement signature: %s',
proposalResponses[0].response.status,
proposalResponses[0].response.message,
proposalResponses[0].response.payload,
proposalResponses[0].endorsement.signature));
var request = {
proposalResponses : proposalResponses,
proposal : proposal,
header : header
};
var transactionID = tx_id.getTransactionID();
var eventPromises = [];
var eh = client.newEventHub();
var data = fs.readFileSync(options.peer_tls_cacerts);
var grpcOpts = {
pem : Buffer.from(data).toString(),
'ssl-target-name-override' : options.server_hostname
};
eh.setPeerAddr(options.event_url, grpcOpts);
eh.connect();
var txPromise = new Promise(function(resolve, reject) {
var handle = setTimeout(function() {
eh.disconnect();
reject();
}, 30000);
eh.registerTxEvent(transactionID, function(tx, code) {
clearTimeout(handle);
eh.unregisterTxEvent(transactionID);
eh.disconnect();
if (code !== 'VALID') {
console.error('The transaction was invalid, code = ' + code);
reject();
} else {
console.log('The transaction has been commited on peer ' + eh._ep._endpoint.addr);
resolve();
}
});
});
eventPromises.push(txPromise);
var sendPromise = channel.sendTransaction(request);
return Promise.all([sendPromise].concat(eventPromises)).then(function(results) {
console.log('event promise all complete and testing complete');
return results[0];
}).catch(function(err) {
console.error('Failed to send transaction and get notifications within the timeout period.');
return 'Failed to send transaction and get notifications within the timeout period.';
});
} else {
console.error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
return 'Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...';
}
}, function(err) {
console.error('Failed to send proposal due to error :' + err.stack? err.stack : err);
return 'Failed to send proposal due to error :' + err.stack? err.stack : err;
}).then(function(response) {
if (response.status === 'SUCCESS') {
console.log('Successfully sent transaction to the orderer.');
return tx_id.getTransactionID();
} else {
console.error('Failed to order the transaction. Error code:' + response.status);
return 'Failed to order the transaction. Error code:' + response.status;
}
}, function(err) {
console.error('Failed to send transaction due to error:' + err.stack? err.stack : err);
return 'Failed to send transaction due to error : '+ err.stack? err.stack : err;
});
node invokeV2.js
Load privateKey and signedCert
Assigning transaction_id : fb98f37b01993505403eeba7992d9da7db5b194164912b6e0a2df6c94d8dc177
transaction proposal was good
Successfully sent Proposal and received ProposalResponse: Status - 200, message = "OK", metadata - "", endorsement signature: 0D u=��˛��_1�8
,
�/���(O��
���?�(C�#���X�=��2�䂇�
info: [EventHub.js]: _connect - options {"grpc.ssl_target_name_override":"peer0.org1.example.com","grpc.default_authority":"peer0.org1.example.com"}
XshellThe transaction has been committed on peer localhost:7053
event promise all complete and testing complete
Successfully sent transaction to the orderer.
参考文档
使用Fabric Node SDK进行Invoke和Query
http://www.cnblogs.com/studyzy/p/7524245.html