Skip to content

Commit

Permalink
[FAB-5303] Further balance-transfer code optimization
Browse files Browse the repository at this point in the history
- Made it possible to deploy the app (both the client and fabric
  backend) to a location other than localhost
- Made it possible to work with a backend over grpc instead of always
  assuming grpcs
- Made the list of target peers for instantiate and invoke calls
  to be optional
- Enabled target networks to be controlled by an env variable

Change-Id: Ie394cf7e8f6ed47d970d4be992f2f6a0394fff7f
Signed-off-by: Jim Zhang <jzhang@us.ibm.com>
  • Loading branch information
jimthematrix committed Jul 26, 2017
1 parent d9e2d5c commit 79cb041
Show file tree
Hide file tree
Showing 14 changed files with 190 additions and 161 deletions.
9 changes: 3 additions & 6 deletions balance-transfer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ curl -s -X POST \
-H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQ4NjU1OTEsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE0OTQ4NjE5OTF9.yWaJhFDuTvMQRaZIqg20Is5t-JJ_1BP58yrNLOKxtNI" \
-H "content-type: application/json" \
-d '{
"peers": ["localhost:7051","localhost:7056"]
"peers": ["peer1","peer2"]
}'
```
### Install chaincode
Expand All @@ -128,7 +128,7 @@ curl -s -X POST \
-H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQ4NjU1OTEsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE0OTQ4NjE5OTF9.yWaJhFDuTvMQRaZIqg20Is5t-JJ_1BP58yrNLOKxtNI" \
-H "content-type: application/json" \
-d '{
"peers": ["localhost:7051","localhost:7056"],
"peers": ["peer1","peer2"],
"chaincodeName":"mycc",
"chaincodePath":"github.com/example_cc",
"chaincodeVersion":"v0"
Expand All @@ -143,10 +143,8 @@ curl -s -X POST \
-H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQ4NjU1OTEsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE0OTQ4NjE5OTF9.yWaJhFDuTvMQRaZIqg20Is5t-JJ_1BP58yrNLOKxtNI" \
-H "content-type: application/json" \
-d '{
"peers": ["localhost:7051"],
"chaincodeName":"mycc",
"chaincodeVersion":"v0",
"fcn":"init",
"args":["a","100","b","200"]
}'
```
Expand All @@ -159,7 +157,6 @@ curl -s -X POST \
-H "authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0OTQ4NjU1OTEsInVzZXJuYW1lIjoiSmltIiwib3JnTmFtZSI6Im9yZzEiLCJpYXQiOjE0OTQ4NjE5OTF9.yWaJhFDuTvMQRaZIqg20Is5t-JJ_1BP58yrNLOKxtNI" \
-H "content-type: application/json" \
-d '{
"peers": ["localhost:7051", "localhost:7056"],
"fcn":"move",
"args":["a","b","10"]
}'
Expand Down Expand Up @@ -232,7 +229,7 @@ curl -s -X GET \

### Network configuration considerations

You have the ability to change configuration parameters by editing the network-config.json file.
You have the ability to change configuration parameters by either directly editing the network-config.json file or provide an additional file for an alternative target network. The app uses an optional environment variable "TARGET_NETWORK" to control the configuration files to use. For example, if you deployed the target network on Amazon Web Services EC2, you can add a file "network-config-aws.json", and set the "TARGET_NETWORK" environment to 'aws'. The app will pick up the settings inside the "network-config-aws.json" file.

#### IP Address** and PORT information

Expand Down
19 changes: 7 additions & 12 deletions balance-transfer/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@ var expressJWT = require('express-jwt');
var jwt = require('jsonwebtoken');
var bearerToken = require('express-bearer-token');
var cors = require('cors');
var config = require('./config.json');

require('./config.js');
var hfc = require('fabric-client');

var helper = require('./app/helper.js');
var channels = require('./app/create-channel.js');
var join = require('./app/join-channel.js');
var install = require('./app/install-chaincode.js');
var instantiate = require('./app/instantiate-chaincode.js');
var invoke = require('./app/invoke-transaction.js');
var query = require('./app/query.js');
var host = process.env.HOST || config.host;
var port = process.env.PORT || config.port;
var host = process.env.HOST || hfc.getConfigSetting('host');
var port = process.env.PORT || hfc.getConfigSetting('port');
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////// SET CONFIGURATONS ////////////////////////////
///////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -118,7 +121,7 @@ app.post('/users', function(req, res) {
return;
}
var token = jwt.sign({
exp: Math.floor(Date.now() / 1000) + parseInt(config.jwt_expiretime),
exp: Math.floor(Date.now() / 1000) + parseInt(hfc.getConfigSetting('jwt_expiretime')),
username: username,
orgName: orgName
}, app.get('secret'));
Expand Down Expand Up @@ -235,10 +238,6 @@ app.post('/channels/:channelName/chaincodes', function(req, res) {
res.json(getErrorMessage('\'channelName\''));
return;
}
if (!fcn) {
res.json(getErrorMessage('\'fcn\''));
return;
}
if (!args) {
res.json(getErrorMessage('\'args\''));
return;
Expand All @@ -260,10 +259,6 @@ app.post('/channels/:channelName/chaincodes/:chaincodeName', function(req, res)
logger.debug('chaincodeName : ' + chaincodeName);
logger.debug('fcn : ' + fcn);
logger.debug('args : ' + args);
if (!peers || peers.length == 0) {
res.json(getErrorMessage('\'peers\''));
return;
}
if (!chaincodeName) {
res.json(getErrorMessage('\'chaincodeName\''));
return;
Expand Down
123 changes: 45 additions & 78 deletions balance-transfer/app/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ var fs = require('fs-extra');
var User = require('fabric-client/lib/User.js');
var crypto = require('crypto');
var copService = require('fabric-ca-client');
var config = require('../config.json');

var hfc = require('fabric-client');
hfc.addConfigFile(path.join(__dirname, 'network-config.json'));
hfc.setLogger(logger);
var ORGS = hfc.getConfigSetting('network-config');

Expand All @@ -44,7 +42,7 @@ for (let key in ORGS) {
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({path: getKeyStoreForOrg(ORGS[key].name)}));
client.setCryptoSuite(cryptoSuite);

let channel = client.newChannel(config.channelName);
let channel = client.newChannel(hfc.getConfigSetting('channelName'));
channel.addOrderer(newOrderer(client));

clients[key] = client;
Expand All @@ -58,27 +56,26 @@ for (let key in ORGS) {
}

function setupPeers(channel, org, client) {
for (let key in ORGS[org]) {
if (key.indexOf('peer') === 0) {
let data = fs.readFileSync(path.join(__dirname, ORGS[org][key]['tls_cacerts']));
let peer = client.newPeer(
ORGS[org][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);

channel.addPeer(peer);
}
for (let key in ORGS[org].peers) {
let data = fs.readFileSync(path.join(__dirname, ORGS[org].peers[key]['tls_cacerts']));
let peer = client.newPeer(
ORGS[org].peers[key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org].peers[key]['server-hostname']
}
);
peer.setName(key);

channel.addPeer(peer);
}
}

function newOrderer(client) {
var caRootsPath = ORGS.orderer.tls_cacerts;
let data = fs.readFileSync(path.join(__dirname, caRootsPath));
let caroots = Buffer.from(data).toString();
return client.newOrderer(config.orderer, {
return client.newOrderer(ORGS.orderer.url, {
'pem': caroots,
'ssl-target-name-override': ORGS.orderer['server-hostname']
});
Expand All @@ -100,60 +97,36 @@ function getOrgName(org) {
}

function getKeyStoreForOrg(org) {
return config.keyValueStore + '_' + org;
return hfc.getConfigSetting('keyValueStore') + '_' + org;
}

function newRemotes(urls, forPeers, userOrg) {
var targets = [];
// find the peer that match the urls
outer:
for (let index in urls) {
let peerUrl = urls[index];

let found = false;
for (let key in ORGS) {
if (key.indexOf('org') === 0) {
// if looking for event hubs, an app can only connect to
// event hubs in its own org
if (!forPeers && key !== userOrg) {
continue;
}

let org = ORGS[key];
let client = getClientForOrg(key);

for (let prop in org) {
if (prop.indexOf('peer') === 0) {
if (org[prop]['requests'].indexOf(peerUrl) >= 0) {
// found a peer matching the subject url
if (forPeers) {
let data = fs.readFileSync(path.join(__dirname, org[prop]['tls_cacerts']));
targets.push(client.newPeer('grpcs://' + peerUrl, {
pem: Buffer.from(data).toString(),
'ssl-target-name-override': org[prop]['server-hostname']
}));

continue outer;
} else {
let eh = client.newEventHub();
let data = fs.readFileSync(path.join(__dirname, org[prop]['tls_cacerts']));
eh.setPeerAddr(org[prop]['events'], {
pem: Buffer.from(data).toString(),
'ssl-target-name-override': org[prop]['server-hostname']
});
targets.push(eh);

continue outer;
}
}
}
}
function newRemotes(names, forPeers, userOrg) {
let client = getClientForOrg(userOrg);

let targets = [];
// find the peer that match the names
for (let idx in names) {
let peerName = names[idx];
if (ORGS[userOrg].peers[peerName]) {
// found a peer matching the name
let data = fs.readFileSync(path.join(__dirname, ORGS[userOrg].peers[peerName]['tls_cacerts']));
let grpcOpts = {
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[userOrg].peers[peerName]['server-hostname']
};

if (forPeers) {
targets.push(client.newPeer(ORGS[userOrg].peers[peerName].requests, grpcOpts));
} else {
let eh = client.newEventHub();
eh.setPeerAddr(ORGS[userOrg].peers[peerName].events, grpcOpts);
targets.push(eh);
}
}
}

if (!found) {
logger.error(util.format('Failed to find a peer matching the url %s', peerUrl));
}
if (targets.length === 0) {
logger.error(util.format('Failed to find peers matching the names %s', names));
}

return targets;
Expand All @@ -170,12 +143,12 @@ var getClientForOrg = function(org) {
return clients[org];
};

var newPeers = function(urls) {
return newRemotes(urls, true);
var newPeers = function(names, org) {
return newRemotes(names, true, org);
};

var newEventHubs = function(urls, org) {
return newRemotes(urls, false, org);
var newEventHubs = function(names, org) {
return newRemotes(names, false, org);
};

var getMspID = function(org) {
Expand All @@ -184,7 +157,7 @@ var getMspID = function(org) {
};

var getAdminUser = function(userOrg) {
var users = config.users;
var users = hfc.getConfigSetting('admins');
var username = users[0].username;
var password = users[0].secret;
var member;
Expand Down Expand Up @@ -325,7 +298,7 @@ var getOrgAdmin = function(userOrg) {
};

var setupChaincodeDeploy = function() {
process.env.GOPATH = path.join(__dirname, config.GOPATH);
process.env.GOPATH = path.join(__dirname, hfc.getConfigSetting('CC_SRC_PATH'));
};

var getLogger = function(moduleName) {
Expand All @@ -334,11 +307,6 @@ var getLogger = function(moduleName) {
return logger;
};

var getPeerAddressByName = function(org, peer) {
var address = ORGS[org][peer].requests;
return address.split('grpcs://')[1];
};

exports.getChannelForOrg = getChannelForOrg;
exports.getClientForOrg = getClientForOrg;
exports.getLogger = getLogger;
Expand All @@ -347,6 +315,5 @@ exports.getMspID = getMspID;
exports.ORGS = ORGS;
exports.newPeers = newPeers;
exports.newEventHubs = newEventHubs;
exports.getPeerAddressByName = getPeerAddressByName;
exports.getRegisteredUsers = getRegisteredUsers;
exports.getOrgAdmin = getOrgAdmin;
2 changes: 1 addition & 1 deletion balance-transfer/app/install-chaincode.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ var installChaincode = function(peers, chaincodeName, chaincodePath,

return helper.getOrgAdmin(org).then((user) => {
var request = {
targets: helper.newPeers(peers),
targets: helper.newPeers(peers, org),
chaincodePath: chaincodePath,
chaincodeId: chaincodeName,
chaincodeVersion: chaincodeVersion
Expand Down
13 changes: 7 additions & 6 deletions balance-transfer/app/instantiate-chaincode.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ var util = require('util');
var hfc = require('fabric-client');
var Peer = require('fabric-client/lib/Peer.js');
var EventHub = require('fabric-client/lib/EventHub.js');
var config = require('../config.json');
var helper = require('./helper.js');
var logger = helper.getLogger('instantiate-chaincode');
hfc.addConfigFile(path.join(__dirname, 'network-config.json'));
var ORGS = hfc.getConfigSetting('network-config');
var tx_id = null;
var eh = null;
Expand All @@ -49,10 +47,13 @@ var instantiateChaincode = function(channelName, chaincodeName, chaincodeVersion
var request = {
chaincodeId: chaincodeName,
chaincodeVersion: chaincodeVersion,
fcn: functionName,
args: args,
txId: tx_id
};

if (functionName)
request.fcn = functionName;

return channel.sendInstantiateProposal(request);
}, (err) => {
logger.error('Failed to initialize the channel');
Expand Down Expand Up @@ -88,12 +89,12 @@ var instantiateChaincode = function(channelName, chaincodeName, chaincodeVersion
var deployId = tx_id.getTransactionID();

eh = client.newEventHub();
let data = fs.readFileSync(path.join(__dirname, ORGS[org]['peer1'][
let data = fs.readFileSync(path.join(__dirname, ORGS[org].peers['peer1'][
'tls_cacerts'
]));
eh.setPeerAddr(ORGS[org]['peer1']['events'], {
eh.setPeerAddr(ORGS[org].peers['peer1']['events'], {
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org]['peer1']['server-hostname']
'ssl-target-name-override': ORGS[org].peers['peer1']['server-hostname']
});
eh.connect();

Expand Down
Loading

0 comments on commit 79cb041

Please sign in to comment.