github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/test/tools/PTE/pte-main.js (about) 1 /** 2 * Copyright 2016 IBM All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /* 18 * usage: 19 * node pte-main.js <ui file> <Nid> 20 * - ui file: user input file 21 * - Nid: Network id 22 */ 23 // This is an end-to-end test that focuses on exercising all parts of the fabric APIs 24 // in a happy-path scenario 25 'use strict'; 26 27 var log4js = require('log4js'); 28 var logger = log4js.getLogger('E2E'); 29 logger.setLevel('DEBUG'); 30 31 var path = require('path'); 32 33 var hfc = require('fabric-client'); 34 hfc.setLogger(logger); 35 var X509 = require('jsrsasign').X509; 36 37 var fs = require('fs'); 38 var grpc = require('grpc'); 39 var util = require('util'); 40 var testUtil = require('./pte-util.js'); 41 var utils = require('fabric-client/lib/utils.js'); 42 var Peer = require('fabric-client/lib/Peer.js'); 43 var Orderer = require('fabric-client/lib/Orderer.js'); 44 var EventHub = require('fabric-client/lib/EventHub.js'); 45 var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl'); 46 var FabricCAClient = FabricCAServices.FabricCAClient; 47 var User = require('fabric-client/lib/User.js'); 48 var Client = require('fabric-client/lib/Client.js'); 49 var _commonProto = grpc.load(path.join(__dirname, '../../fabric-client/lib/protos/common/common.proto')).common; 50 51 var gopath=process.env.GOPATH; 52 console.log('GOPATH: ', gopath); 53 54 utils.setConfigSetting('crypto-keysize', 256); 55 56 const child_process = require('child_process'); 57 58 var webUser = null; 59 var tmp; 60 var i=0; 61 62 //testUtil.setupChaincodeDeploy(); 63 64 65 // input: userinput json file 66 var Nid = parseInt(process.argv[2]); 67 var uiFile = process.argv[3]; 68 var tStart = parseInt(process.argv[4]); 69 console.log('input parameters: Nid=%d, uiFile=%s, tStart=%d', Nid, uiFile, tStart); 70 var uiContent = JSON.parse(fs.readFileSync(uiFile)); 71 72 var TLS=uiContent.TLS; 73 var channelID = uiContent.channelID; 74 var chaincode_id = uiContent.chaincodeID+channelID; 75 var chaincode_ver = uiContent.chaincodeVer; 76 var chain_id = uiContent.chainID+channelID; 77 console.log('chaincode_id: %s, chaincode_ver: %s, chain_id: %s', Nid, chaincode_id, chaincode_ver, chain_id); 78 79 var channelOpt=uiContent.channelOpt; 80 var channelName=channelOpt.name; 81 var channelOrgName = []; 82 for (i=0; i<channelOpt.orgName.length; i++) { 83 channelOrgName.push(channelOpt.orgName[i]); 84 } 85 console.log('TLS: %s', TLS.toUpperCase()); 86 console.log('channelName: %s', channelName); 87 console.log('channelOrgName.length: %d, channelOrgName: %s', channelOrgName.length, channelOrgName); 88 89 var svcFile = uiContent.SCFile[0].ServiceCredentials; 90 console.log('svcFile; ', svcFile); 91 hfc.addConfigFile(path.join(__dirname, svcFile)); 92 var ORGS = hfc.getConfigSetting('test-network'); 93 94 var users = hfc.getConfigSetting('users'); 95 96 97 var transType = uiContent.transType; 98 var nRequest = parseInt(uiContent.nRequest); 99 var nProc = parseInt(uiContent.nProc); 100 var tCurr; 101 102 103 var testDeployArgs = []; 104 for (i=0; i<uiContent.deploy.args.length; i++) { 105 testDeployArgs.push(uiContent.deploy.args[i]); 106 } 107 108 var tx_id = null; 109 var nonce = null; 110 111 var the_user = null; 112 var g_len = nProc; 113 114 var cfgtxFile; 115 var allEventhubs = []; 116 var org; 117 var orgName; 118 119 var targets = []; 120 var eventHubs=[]; 121 var orderer; 122 123 124 function printChainInfo(chain) { 125 console.log('[printChainInfo] chain name: ', chain.getName()); 126 console.log('[printChainInfo] orderers: ', chain.getOrderers()); 127 console.log('[printChainInfo] peers: ', chain.getPeers()); 128 console.log('[printChainInfo] events: ', eventHubs); 129 } 130 131 function clientNewOrderer(client, org) { 132 if (TLS.toUpperCase() == 'ENABLED') { 133 var caRootsPath = ORGS.orderer.tls_cacerts; 134 let data = fs.readFileSync(caRootsPath); 135 let caroots = Buffer.from(data).toString(); 136 137 orderer = client.newOrderer( 138 ORGS.orderer.url, 139 { 140 'pem': caroots, 141 'ssl-target-name-override': ORGS.orderer['server-hostname'] 142 } 143 ); 144 } else { 145 orderer = client.newOrderer(ORGS.orderer.url); 146 } 147 console.log('[clientNewOrderer] orderer: %s', ORGS.orderer.url); 148 } 149 150 function chainAddOrderer(chain, client, org) { 151 console.log('[chainAddOrderer] chain name: ', chain.getName()); 152 if (TLS.toUpperCase() == 'ENABLED') { 153 var caRootsPath = ORGS.orderer.tls_cacerts; 154 var data = fs.readFileSync(caRootsPath); 155 let caroots = Buffer.from(data).toString(); 156 157 chain.addOrderer( 158 client.newOrderer( 159 ORGS.orderer.url, 160 { 161 'pem': caroots, 162 'ssl-target-name-override': ORGS.orderer['server-hostname'] 163 } 164 ) 165 ); 166 } else { 167 chain.addOrderer( 168 client.newOrderer(ORGS.orderer.url) 169 ); 170 } 171 } 172 173 function channelAddAllPeer(chain, client) { 174 console.log('[channelAddAllPeer] chain name: ', chain.getName()); 175 var peerTmp; 176 var data; 177 var eh; 178 for (let key1 in ORGS) { 179 if (ORGS.hasOwnProperty(key1)) { 180 for (let key in ORGS[key1]) { 181 if (key.indexOf('peer') === 0) { 182 if (TLS.toUpperCase() == 'ENABLED') { 183 data = fs.readFileSync(ORGS[key1][key].tls_cacerts); 184 peerTmp = client.newPeer( 185 ORGS[key1][key].requests, 186 { 187 pem: Buffer.from(data).toString(), 188 'ssl-target-name-override': ORGS[key1][key]['server-hostname'] 189 } 190 ); 191 targets.push(peerTmp); 192 chain.addPeer(peerTmp); 193 } else { 194 peerTmp = client.newPeer( ORGS[key1][key].requests); 195 targets.push(peerTmp); 196 chain.addPeer(peerTmp); 197 } 198 199 eh=new EventHub(client); 200 if (TLS.toUpperCase() == 'ENABLED') { 201 eh.setPeerAddr( 202 ORGS[key1][key].events, 203 { 204 pem: Buffer.from(data).toString(), 205 'ssl-target-name-override': ORGS[key1][key]['server-hostname'] 206 } 207 ); 208 } else { 209 eh.setPeerAddr(ORGS[key1][key].events); 210 } 211 eh.connect(); 212 eventHubs.push(eh); 213 } 214 } 215 } 216 } 217 } 218 219 function channelRemoveAllPeer(chain, client) { 220 console.log('[channelRemoveAllPeer] chain name: ', chain.getName()); 221 var peerTmp; 222 var data; 223 var eh; 224 for (let key1 in ORGS) { 225 if (ORGS.hasOwnProperty(key1)) { 226 for (let key in ORGS[key1]) { 227 if (key.indexOf('peer') === 0) { 228 if (TLS.toUpperCase() == 'ENABLED') { 229 data = fs.readFileSync(ORGS[key1][key].tls_cacerts); 230 peerTmp = client.newPeer( 231 ORGS[key1][key].requests, 232 { 233 pem: Buffer.from(data).toString(), 234 'ssl-target-name-override': ORGS[key1][key]['server-hostname'] 235 } 236 ); 237 if (chain.isValidPeer(peerTmp)) { 238 console.log('[channelRemoveAllPeer] chain remove peer: ', ORGS[key1][key].requests); 239 chain.removePeer(peerTmp); 240 } 241 } else { 242 peerTmp = client.newPeer( ORGS[key1][key].requests); 243 if (chain.isValidPeer(peerTmp)) { 244 console.log('[channelRemoveAllPeer] chain remove peer: ', ORGS[key1][key].requests); 245 chain.removePeer(peerTmp); 246 } 247 } 248 249 } 250 } 251 } 252 } 253 } 254 255 function channelAddAnchorPeer(chain, client, org) { 256 console.log('[channelAddAnchorPeer] chain name: ', chain.getName()); 257 var peerTmp; 258 var data; 259 var eh; 260 for (let key in ORGS) { 261 if (ORGS.hasOwnProperty(key) && typeof ORGS[key].peer1 !== 'undefined') { 262 if (TLS.toUpperCase() == 'ENABLED') { 263 data = fs.readFileSync(ORGS[key].peer1['tls_cacerts']); 264 peerTmp = client.newPeer( 265 ORGS[key].peer1.requests, 266 { 267 pem: Buffer.from(data).toString(), 268 'ssl-target-name-override': ORGS[key].peer1['server-hostname'] 269 } 270 ); 271 targets.push(peerTmp); 272 chain.addPeer(peerTmp); 273 } else { 274 peerTmp = client.newPeer( ORGS[key].peer1.requests); 275 targets.push(peerTmp); 276 chain.addPeer(peerTmp); 277 } 278 console.log('[channelAddAnchorPeer] requests: %s', ORGS[key].peer1.requests); 279 280 //an event listener can only register with a peer in its own org 281 if ( key == org ) { 282 eh=new EventHub(client); 283 if (TLS.toUpperCase() == 'ENABLED') { 284 eh.setPeerAddr( 285 ORGS[key].peer1.events, 286 { 287 pem: Buffer.from(data).toString(), 288 'ssl-target-name-override': ORGS[key].peer1['server-hostname'] 289 } 290 ); 291 } else { 292 eh.setPeerAddr(ORGS[key].peer1.events); 293 } 294 eh.connect(); 295 eventHubs.push(eh); 296 console.log('[channelAddAnchorPeer] events: %s ', ORGS[key].peer1.events); 297 } 298 } 299 } 300 } 301 302 function channelAddPeer(chain, client, org) { 303 console.log('[channelAddPeer] chain name: ', chain.getName()); 304 var peerTmp; 305 var eh; 306 for (let key in ORGS[org]) { 307 if (ORGS[org].hasOwnProperty(key)) { 308 if (key.indexOf('peer') === 0) { 309 if (TLS.toUpperCase() == 'ENABLED') { 310 let data = fs.readFileSync(ORGS[org][key]['tls_cacerts']); 311 peerTmp = client.newPeer( 312 ORGS[org][key].requests, 313 { 314 pem: Buffer.from(data).toString(), 315 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 316 } 317 ); 318 targets.push(peerTmp); 319 chain.addPeer(peerTmp); 320 } else { 321 peerTmp = client.newPeer( ORGS[org][key].requests); 322 targets.push(peerTmp); 323 chain.addPeer(peerTmp); 324 } 325 } 326 } 327 } 328 } 329 330 function channelRemovePeer(chain, client, org) { 331 console.log('[channelRemovePeer] chain name: ', chain.getName()); 332 var peerTmp; 333 var eh; 334 for (let key in ORGS[org]) { 335 if (ORGS[org].hasOwnProperty(key)) { 336 if (key.indexOf('peer') === 0) { 337 if (TLS.toUpperCase() == 'ENABLED') { 338 let data = fs.readFileSync(ORGS[org][key]['tls_cacerts']); 339 peerTmp = client.newPeer( 340 ORGS[org][key].requests, 341 { 342 pem: Buffer.from(data).toString(), 343 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 344 } 345 ); 346 chain.removePeer(peerTmp); 347 } else { 348 peerTmp = client.newPeer( ORGS[org][key].requests); 349 targets.push(peerTmp); 350 chain.removePeer(peerTmp); 351 } 352 } 353 } 354 } 355 } 356 357 358 function channelAddPeerEventJoin(chain, client, org) { 359 console.log('[channelAddPeerEvent] chain name: ', chain.getName()); 360 var eh; 361 var peerTmp; 362 for (let key in ORGS[org]) { 363 if (ORGS[org].hasOwnProperty(key)) { 364 if (key.indexOf('peer') === 0) { 365 if (TLS.toUpperCase() == 'ENABLED') { 366 let data = fs.readFileSync(ORGS[org][key]['tls_cacerts']); 367 targets.push( 368 client.newPeer( 369 ORGS[org][key].requests, 370 { 371 pem: Buffer.from(data).toString(), 372 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 373 } 374 ) 375 ); 376 } else { 377 targets.push( 378 client.newPeer( 379 ORGS[org][key].requests 380 ) 381 ); 382 console.log('[channelAddPeerEvent] peer: ', ORGS[org][key].requests); 383 } 384 385 eh=new EventHub(client); 386 if (TLS.toUpperCase() == 'ENABLED') { 387 let data = fs.readFileSync(ORGS[org][key]['tls_cacerts']); 388 eh.setPeerAddr( 389 ORGS[org][key].events, 390 { 391 pem: Buffer.from(data).toString(), 392 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 393 } 394 ); 395 } else { 396 eh.setPeerAddr(ORGS[org][key].events); 397 } 398 eh.connect(); 399 eventHubs.push(eh); 400 console.log('[channelAddPeerEvent] requests: %s, events: %s ', ORGS[org][key].requests, ORGS[org][key].events); 401 } 402 } 403 } 404 } 405 406 function channelAddPeerEvent(chain, client, org) { 407 console.log('[channelAddPeerEvent] chain name: ', chain.getName()); 408 var eh; 409 var peerTmp; 410 for (let key in ORGS[org]) { 411 if (ORGS[org].hasOwnProperty(key)) { 412 if (key.indexOf('peer') === 0) { 413 if (TLS.toUpperCase() == 'ENABLED') { 414 let data = fs.readFileSync(ORGS[org][key]['tls_cacerts']); 415 peerTmp = client.newPeer( 416 ORGS[org][key].requests, 417 { 418 pem: Buffer.from(data).toString(), 419 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 420 } 421 ); 422 targets.push(peerTmp); 423 chain.addPeer(peerTmp); 424 } else { 425 peerTmp = client.newPeer( 426 ORGS[org][key].requests 427 ); 428 chain.addPeer(peerTmp); 429 console.log('[channelAddPeerEvent] peer: ', ORGS[org][key].requests); 430 } 431 432 eh=new EventHub(client); 433 if (TLS.toUpperCase() == 'ENABLED') { 434 let data = fs.readFileSync(ORGS[org][key]['tls_cacerts']); 435 eh.setPeerAddr( 436 ORGS[org][key].events, 437 { 438 pem: Buffer.from(data).toString(), 439 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 440 } 441 ); 442 } else { 443 eh.setPeerAddr(ORGS[org][key].events); 444 } 445 eh.connect(); 446 eventHubs.push(eh); 447 console.log('[channelAddPeerEvent] requests: %s, events: %s ', ORGS[org][key].requests, ORGS[org][key].events); 448 } 449 } 450 } 451 } 452 function channelAddEvent(chain, client, org) { 453 console.log('[channelAddEvent] chain name: ', chain.getName()); 454 var eh; 455 var peerTmp; 456 for (let key in ORGS[org]) { 457 if (ORGS[org].hasOwnProperty(key)) { 458 if (key.indexOf('peer') === 0) { 459 460 eh=new EventHub(client); 461 if (TLS.toUpperCase() == 'ENABLED') { 462 eh.setPeerAddr( 463 ORGS[org][key].events, 464 { 465 pem: Buffer.from(data).toString(), 466 'ssl-target-name-override': ORGS[org][key]['server-hostname'] 467 } 468 ); 469 } else { 470 eh.setPeerAddr(ORGS[org][key].events); 471 } 472 eh.connect(); 473 eventHubs.push(eh); 474 console.log('[channelAddEvent] requests: %s, events: %s ', ORGS[org][key].requests, ORGS[org][key].events); 475 } 476 } 477 console.log('[channelAddEvent] event: ', eventHubs); 478 } 479 } 480 481 // test begins .... 482 performance_main(); 483 484 // install chaincode 485 function chaincodeInstall(chain, client, org) { 486 console.log('[chaincodeInstall]: ', org); 487 orgName = ORGS[org].name; 488 489 chainAddOrderer(chain, client, org); 490 491 channelAddPeer(chain, client, org); 492 //printChainInfo(chain); 493 494 nonce = utils.getNonce(); 495 tx_id = hfc.buildTransactionID(nonce, the_user); 496 nonce = utils.getNonce(); 497 var request_install = { 498 targets: targets, 499 chaincodePath: uiContent.deploy.chaincodePath, 500 chaincodeId: chaincode_id, 501 chaincodeVersion: chaincode_ver, 502 txId: tx_id, 503 nonce: nonce 504 }; 505 506 console.log('request_install: ', request_install); 507 508 //sendInstallProposal 509 client.installChaincode(request_install) 510 .then( 511 function(results) { 512 var proposalResponses = results[0]; 513 var proposal = results[1]; 514 var header = results[2]; 515 var all_good = true; 516 for(var i in proposalResponses) { 517 let one_good = false; 518 if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) { 519 one_good = true; 520 logger.info('install proposal(%s) was good', orgName); 521 } else { 522 logger.error('install proposal(%s) was bad', orgName); 523 } 524 all_good = all_good & one_good; 525 } 526 if (all_good) { 527 console.log(util.format('[chaincodeInstall] Successfully sent install Proposal to peers in (%s:%s) and received ProposalResponse: Status - %s', chain.getName(), orgName, proposalResponses[0].response.status)); 528 evtDisconnect(); 529 process.exit(); 530 } else { 531 console.log('[chaincodeInstall] Failed to send install Proposal in (%s:%s) or receive valid response. Response null or status is not 200. exiting...', chain.getName(), orgName); 532 evtDisconnect(); 533 process.exit(); 534 } 535 536 }, (err) => { 537 console.log('Failed to enroll user \'admin\'. ' + err); 538 evtDisconnect(); 539 process.exit(); 540 541 }); 542 } 543 544 function buildChaincodeProposal(the_user, upgrade, transientMap) { 545 let nonce = utils.getNonce(); 546 let tx_id = hfc.buildTransactionID(nonce, the_user); 547 548 // send proposal to endorser 549 var request = { 550 chaincodePath: uiContent.deploy.chaincodePath, 551 chaincodeId: chaincode_id, 552 chaincodeVersion: chaincode_ver, 553 fcn: uiContent.deploy.fcn, 554 args: testDeployArgs, 555 chainId: channelName, 556 txId: tx_id, 557 nonce: nonce 558 // use this to demonstrate the following policy: 559 // 'if signed by org1 admin, then that's the only signature required, 560 // but if that signature is missing, then the policy can also be fulfilled 561 // when members (non-admin) from both orgs signed' 562 /* 563 'endorsement-policy': { 564 identities: [ 565 { role: { name: 'member', mspId: ORGS['org1'].mspid }}, 566 { role: { name: 'member', mspId: ORGS['org2'].mspid }}, 567 { role: { name: 'admin', mspId: ORGS['org1'].mspid }} 568 ], 569 policy: { 570 '1-of': [ 571 { 'signed-by': 2}, 572 { '2-of': [{ 'signed-by': 0}, { 'signed-by': 1 }]} 573 ] 574 } 575 } 576 */ 577 }; 578 579 if(upgrade) { 580 // use this call to test the transient map support during chaincode instantiation 581 request.transientMap = transientMap; 582 } 583 584 return { request: request, tx_id: tx_id }; 585 } 586 587 //instantiate chaincode 588 function chaincodeInstantiate(chain, client, org) { 589 console.log('[chaincodeInstantiate] org= %s, org name=%s, chain name=%s', org, orgName, chain.getName()); 590 591 chainAddOrderer(chain, client, org); 592 //channelAddPeerEvent(chain, client, org); 593 channelAddAnchorPeer(chain, client, org); 594 //printChainInfo(chain); 595 596 chain.initialize() 597 .then((success) => { 598 console.log('[chaincodeInstantiate:Nid=%d] Successfully initialize chain[%s]', Nid, chain.getName()); 599 var upgrade = false; 600 601 var badTransientMap = { 'test1': 'transientValue' }; // have a different key than what the chaincode example_cc1.go expects in Init() 602 var transientMap = { 'test': 'transientValue' }; 603 var request = buildChaincodeProposal(the_user, upgrade, badTransientMap); 604 tx_id = request.tx_id; 605 request = request.request; 606 607 608 // sendInstantiateProposal 609 //console.log('request_instantiate: ', request_instantiate); 610 return chain.sendInstantiateProposal(request); 611 }, 612 function(err) { 613 console.log('Failed to initialize chain[%s] due to error: ', chain.getName(), err.stack ? err.stack : err); 614 evtDisconnect(); 615 process.exit(); 616 }) 617 .then( 618 function(results) { 619 var proposalResponses = results[0]; 620 var proposal = results[1]; 621 var header = results[2]; 622 var all_good = true; 623 for(var i in proposalResponses) { 624 let one_good = false; 625 if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) { 626 one_good = true; 627 logger.info('chaincode instantiation was good'); 628 } else { 629 logger.error('chaincode instantiation was bad'); 630 } 631 all_good = all_good & one_good; 632 } 633 if (all_good) { 634 console.log(util.format('[chaincodeInstantiate] Successfully sent chaincode instantiation 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)); 635 636 637 var request = { 638 proposalResponses: proposalResponses, 639 proposal: proposal, 640 header: header 641 }; 642 643 var deployId = tx_id.toString(); 644 var eventPromises = []; 645 eventHubs.forEach((eh) => { 646 let txPromise = new Promise((resolve, reject) => { 647 let handle = setTimeout(reject, 120000); 648 649 eh.registerTxEvent(deployId.toString(), (tx, code) => { 650 var tCurr1=new Date().getTime(); 651 console.log('[chaincodeInstantiate] tCurr=%d, The chaincode instantiate transaction time=%d', tCurr, tCurr1-tCurr); 652 //console.log('[chaincodeInstantiate] The chaincode instantiate transaction has been committed on peer '+ eh.ep.addr); 653 clearTimeout(handle); 654 eh.unregisterTxEvent(deployId); 655 656 if (code !== 'VALID') { 657 console.log('[chaincodeInstantiate] The chaincode instantiate transaction was invalid, code = ' + code); 658 reject(); 659 } else { 660 console.log('[chaincodeInstantiate] The chaincode instantiate transaction was valid.'); 661 resolve(); 662 } 663 }); 664 }); 665 666 eventPromises.push(txPromise); 667 }); 668 669 var sendPromise = chain.sendTransaction(request); 670 var tCurr=new Date().getTime(); 671 console.log('[chaincodeInstantiate] Promise.all tCurr=%d', tCurr); 672 return Promise.all([sendPromise].concat(eventPromises)) 673 674 .then((results) => { 675 676 console.log('[chaincodeInstantiate] Event promise all complete and testing complete'); 677 return results[0]; // the first returned value is from the 'sendPromise' which is from the 'sendTransaction()' call 678 }).catch((err) => { 679 var tCurr1=new Date().getTime(); 680 console.log('[chaincodeInstantiate] failed to send instantiate transaction: tCurr=%d, elapse time=%d', tCurr, tCurr1-tCurr); 681 //console.log('Failed to send instantiate transaction and get notifications within the timeout period.'); 682 evtDisconnect(); 683 throw new Error('Failed to send instantiate transaction and get notifications within the timeout period.'); 684 685 }); 686 } else { 687 console.log('[chaincodeInstantiate] Failed to send instantiate Proposal or receive valid response. Response null or status is not 200. exiting...'); 688 evtDisconnect(); 689 throw new Error('Failed to send instantiate Proposal or receive valid response. Response null or status is not 200. exiting...'); 690 } 691 }, 692 function(err) { 693 694 console.log('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); 695 evtDisconnect(); 696 throw new Error('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err); 697 }) 698 .then((response) => { 699 if (response.status === 'SUCCESS') { 700 console.log('[chaincodeInstantiate(Nid=%d)] Successfully instantiate transaction on %s. ', Nid, chain.getName()); 701 evtDisconnect(); 702 return; 703 } else { 704 console.log('[chaincodeInstantiate(Nid=%d)] Failed to instantiate transaction on %s. Error code: ', Nid, chain.getName(), response.status); 705 evtDisconnect(); 706 } 707 708 }, (err) => { 709 console.log('[chaincodeInstantiate(Nid=%d)] Failed to instantiate transaction on %s due to error: ', Nid, chain.getName(), err.stack ? err.stack : err); 710 evtDisconnect(); 711 } 712 ); 713 } 714 715 function readAllFiles(dir) { 716 var files = fs.readdirSync(dir); 717 var certs = []; 718 files.forEach((file_name) => { 719 let file_path = path.join(dir,file_name); 720 console.log('[readAllFiles] looking at file ::'+file_path); 721 let data = fs.readFileSync(file_path); 722 certs.push(data); 723 }); 724 return certs; 725 } 726 727 728 function pushMSP(client, msps) { 729 730 for (let key in ORGS) { 731 console.log('[pushMSP] key: %s, ORGS[key].mspid: %s', key, ORGS[key].mspid); 732 if (key.indexOf('orderer') === 0) { 733 var msp = {}; 734 var comName = ORGS[key].comName; 735 msp.id = ORGS[key].mspid; 736 msp.rootCerts = readAllFiles(path.join(ORGS[key].mspPath+'/ordererOrganizations/'+comName+'/msp/', 'cacerts')); 737 msp.admin = readAllFiles(path.join(ORGS[key].mspPath+'/ordererOrganizations/'+comName+'/msp/', 'admincerts')); 738 msps.push(client.newMSP(msp)); 739 } else if (key.indexOf('org') === 0) { 740 var msp = {}; 741 var comName = ORGS[key].comName; 742 msp.id = ORGS[key].mspid; 743 msp.rootCerts = readAllFiles(path.join(ORGS[key].mspPath+'/peerOrganizations/'+key+'.'+comName+'/msp/', 'cacerts')); 744 msp.admin = readAllFiles(path.join(ORGS[key].mspPath+'/peerOrganizations/'+key+'.'+comName+'/msp/', 'admincerts')); 745 msps.push(client.newMSP(msp)); 746 } 747 } 748 } 749 750 //create channel 751 function createOneChannel(client, org) { 752 orgName = ORGS[org].name; 753 console.log('[createOneChannel] org= %s, org name= %s', org, orgName); 754 var username = ORGS[org].username; 755 var secret = ORGS[org].secret; 756 console.log('[createOneChannel] user= %s, secret= %s', username, secret); 757 758 clientNewOrderer(client, org); 759 760 var config = null; 761 var envelope_bytes = null; 762 var signatures = []; 763 var msps = []; 764 var key; 765 766 pushMSP(client, msps); 767 768 utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js'); 769 770 hfc.newDefaultKeyValueStore({ 771 path: testUtil.storePathForOrg(orgName) 772 }) 773 .then((store) => { 774 client.setStateStore(store); 775 776 key = 'org1'; 777 username=ORGS[key].username; 778 secret=ORGS[key].secret; 779 client._userContext = null; 780 return testUtil.getSubmitter(username, secret, client, true, key, svcFile); 781 }).then((admin) => { 782 //the_user = admin; 783 console.log('[createOneChannel] Successfully enrolled user \'admin\' for', key); 784 var channelTX=channelOpt.channelTX; 785 console.log('[createOneChannel] channelTX: ', channelTX); 786 envelope_bytes = fs.readFileSync(channelTX); 787 config = client.extractChannelConfig(envelope_bytes); 788 console.log('[createOneChannel] Successfull extracted the config update from the configtx envelope: ', channelTX); 789 790 var signature = client.signChannelConfig(config); 791 console.log('[createOneChannel] Successfully signed config update: ', key); 792 // collect signature from org1 admin 793 // TODO: signature counting against policies on the orderer 794 // at the moment is being investigated, but it requires this 795 // weird double-signature from each org admin 796 signatures.push(signature); 797 signatures.push(signature); 798 //console.log('[createOneChannel] org-signature: ', signature); 799 800 key = 'org2'; 801 username=ORGS[key].username; 802 secret=ORGS[key].secret; 803 client._userContext = null; 804 return testUtil.getSubmitter(username, secret, client, true, key, svcFile); 805 }).then((admin) => { 806 //the_user = admin; 807 console.log('[createOneChannel] Successfully enrolled user \'admin\' for', key); 808 var signature = client.signChannelConfig(config); 809 console.log('[createOneChannel] Successfully signed config update: ', key); 810 // collect signature from org1 admin 811 // TODO: signature counting against policies on the orderer 812 // at the moment is being investigated, but it requires this 813 // weird double-signature from each org admin 814 signatures.push(signature); 815 signatures.push(signature); 816 //console.log('[createOneChannel] org-signature: ', signature); 817 818 key='orderer'; 819 client._userContext = null; 820 return testUtil.getOrderAdminSubmitter(client, key, svcFile); 821 }).then((admin) => { 822 the_user = admin; 823 console.log('[createOneChannel] Successfully enrolled user \'admin\' for', key); 824 var signature = client.signChannelConfig(config); 825 console.log('[createOneChannel] Successfully signed config update: ', key); 826 console.log('[createOneChannel] admin : ', admin); 827 // collect signature from org1 admin 828 // TODO: signature counting against policies on the orderer 829 // at the moment is being investigated, but it requires this 830 // weird double-signature from each org admin 831 signatures.push(signature); 832 signatures.push(signature); 833 //console.log('[createOneChannel] orderer-signature: ', signature); 834 835 // sign config for all org 836 /* 837 838 for (let key in ORGS) { 839 console.log('[createOneChannel] key: %s ', key); 840 841 if ( key.indexOf('org') === 0) { 842 username=ORGS[key].username; 843 secret=ORGS[key].secret; 844 console.log('[createOneChannel] key: %s, username: %s, secret: %s', key, username, secret); 845 client._userContext = null; 846 testUtil.getSubmitter(username, secret, client, true, key, svcFile) 847 .then((admin) => { 848 console.log('[createOneChannel] Successfully enrolled user \'admin\' for', key); 849 var signature = client.signChannelConfig(config); 850 console.log('[createOneChannel] Successfully signed config update: ', key); 851 // collect signature from org1 admin 852 // TODO: signature counting against policies on the orderer 853 // at the moment is being investigated, but it requires this 854 // weird double-signature from each org admin 855 signatures.push(signature); 856 signatures.push(signature); 857 console.log('[createOneChannel] org-signature: ', signature); 858 } 859 ) 860 } 861 } 862 var key='orderer'; 863 client._userContext = null; 864 testUtil.getOrderAdminSubmitter(client, key, svcFile) 865 .then((admin) => { 866 the_user = admin; 867 console.log('[createOneChannel] Successfully enrolled user \'admin\' for', key); 868 var signature = client.signChannelConfig(config); 869 console.log('[createOneChannel] Successfully signed config update: ', key); 870 // collect signature from org1 admin 871 // TODO: signature counting against policies on the orderer 872 // at the moment is being investigated, but it requires this 873 // weird double-signature from each org admin 874 signatures.push(signature); 875 signatures.push(signature); 876 console.log('[createOneChannel] orderer-signature: ', signature); 877 } 878 ) 879 */ 880 881 882 //console.log('[createOneChannel] signatures: ', signatures); 883 console.log('[createOneChannel] done signing: %s', channelName); 884 885 // build up the create request 886 let nonce = utils.getNonce(); 887 let tx_id = Client.buildTransactionID(nonce, the_user); 888 var request = { 889 config: config, 890 signatures : signatures, 891 name : channelName, 892 orderer : orderer, 893 txId : tx_id, 894 nonce : nonce 895 }; 896 897 //FIXME: temporary fix until mspid is configured into Chain 898 //the_user.mspImpl._id = ORGS[org].mspid; 899 900 // readin the envelope to send to the orderer 901 /* 902 cfgtxFile=gopath+'/src/github.com/hyperledger/fabric/common/tools/cryptogen/crypto-config/ordererOrganizations/'+channelName+'.tx'; 903 var data =fs.readFileSync(cfgtxFile); 904 console.log('[createOneChannel] Successfully read file: %s', cfgtxFile); 905 var request = { 906 envelope : data, 907 name : channelName, 908 orderer : orderer 909 }; 910 */ 911 // send to orderer 912 //console.log('chain orderer: ', chain.getOrderers()); 913 console.log('request: ',request); 914 return client.createChannel(request); 915 }, (err) => { 916 console.log('Failed to enroll user \'admin\'. ' + err); 917 evtDisconnect(); 918 process.exit(); 919 }) 920 .then((result) => { 921 922 console.log('[createOneChannel] Successfully created the channel (%s).', channelName); 923 evtDisconnect(); 924 process.exit(); 925 926 }, (err) => { 927 console.log('Failed to create the channel (%s) ', channelName); 928 console.log('Failed to create the channel:: %j '+ err.stack ? err.stack : err); 929 evtDisconnect(); 930 process.exit(); 931 }) 932 .then((nothing) => { 933 console.log('Successfully waited to make sure new channel was created.'); 934 evtDisconnect(); 935 process.exit(); 936 }, (err) => { 937 console.log('Failed due to error: ' + err.stack ? err.stack : err); 938 evtDisconnect(); 939 process.exit(); 940 }); 941 } 942 943 // join channel 944 function joinChannel(chain, client, org) { 945 orgName = ORGS[org].name; 946 console.log('[joinChannel] Calling peers in organization "%s" to join the channel "%s"', orgName, chain.getName()); 947 var username = ORGS[org].username; 948 var secret = ORGS[org].secret; 949 console.log('[joinChannel] user=%s, secret=%s', username, secret); 950 var genesis_block = null; 951 952 // add orderers 953 chainAddOrderer(chain, client, org); 954 955 //printChainInfo(chain); 956 957 return hfc.newDefaultKeyValueStore({ 958 path: testUtil.storePathForOrg(orgName) 959 }).then((store) => { 960 client.setStateStore(store); 961 client._userContext = null; 962 return testUtil.getOrderAdminSubmitter(client, org, svcFile) 963 }).then((admin) => { 964 console.log('[joinChannel:%s] Successfully enrolled user \'admin\'', org); 965 the_user = admin; 966 console.log('[joinChannel] orderer admin: ', admin); 967 968 nonce = utils.getNonce(); 969 tx_id = hfc.buildTransactionID(nonce, the_user); 970 var request = { 971 txId : tx_id, 972 nonce : nonce 973 }; 974 return chain.getGenesisBlock(request); 975 }).then((block) =>{ 976 console.log('[joinChannel:org=%s:%s] Successfully got the genesis block', channelName, org); 977 genesis_block = block; 978 979 client._userContext = null; 980 return testUtil.getSubmitter(username, secret, client, true, org, svcFile); 981 }).then((admin) => { 982 console.log('[joinChannel] Successfully enrolled org:' + org + ' \'admin\''); 983 the_user = admin; 984 console.log('[joinChannel] org admin: ', admin); 985 986 // add peers and events 987 //channelAddPeerEvent(chain, client, org); 988 channelAddPeerEventJoin(chain, client, org); 989 990 991 var eventPromises = []; 992 //console.log('[joinChannel] for each', eventHubs); 993 994 eventHubs.forEach((eh) => { 995 let txPromise = new Promise((resolve, reject) => { 996 let handle = setTimeout(reject, 30000); 997 998 eh.registerBlockEvent((block) => { 999 clearTimeout(handle); 1000 1001 // in real-world situations, a peer may have more than one channels so 1002 // we must check that this block came from the channel we asked the peer to join 1003 if(block.data.data.length === 1) { 1004 // Config block must only contain one transaction 1005 var envelope = _commonProto.Envelope.decode(block.data.data[0]); 1006 var payload = _commonProto.Payload.decode(envelope.payload); 1007 var channel_header = _commonProto.ChannelHeader.decode(payload.header.channel_header); 1008 1009 if (channel_header.channel_id === channelName) { 1010 console.log('The new channel has been successfully joined on peer '+ eh.ep._endpoint.addr); 1011 resolve(); 1012 } 1013 } 1014 }, (err) => { 1015 console.log('Failed to registerBlockEvent due to error: ' + err.stack ? err.stack : err); 1016 throw new Error('Failed to registerBlockEvent due to error: ' + err.stack ? err.stack : err); 1017 }); 1018 }, (err) => { 1019 console.log('Failed to Promise due to error: ' + err.stack ? err.stack : err); 1020 throw new Error('Failed to Promise due to error: ' + err.stack ? err.stack : err); 1021 }); 1022 1023 eventPromises.push(txPromise); 1024 }); 1025 1026 //console.log('[joinChannel] targets: ', targets); 1027 nonce = utils.getNonce(); 1028 tx_id = hfc.buildTransactionID(nonce, the_user); 1029 let request = { 1030 targets : targets, 1031 block : genesis_block, 1032 txId : tx_id, 1033 nonce : nonce 1034 }; 1035 1036 var sendPromise = chain.joinChannel(request); 1037 console.log('[joinChannel] sendPromise '); 1038 return Promise.all([sendPromise].concat(eventPromises)); 1039 }, (err) => { 1040 console.log('[joinChannel] Failed to enroll user \'admin\' due to error: ' + err.stack ? err.stack : err); 1041 evtDisconnect(); 1042 throw new Error('[joinChannel] Failed to enroll user \'admin\' due to error: ' + err.stack ? err.stack : err); 1043 }) 1044 .then((results) => { 1045 console.log(util.format('[joinChannel] join Channel R E S P O N S E : %j', results)); 1046 1047 if(results[0] && results[0][0] && results[0][0].response && results[0][0].response.status == 200) { 1048 console.log('[joinChannel] Successfully joined peers in (%s:%s)', channelName, orgName); 1049 evtDisconnect(); 1050 } else { 1051 console.log('[joinChannel] Failed to join peers in (%s:%s)', channelName, orgName); 1052 evtDisconnect(); 1053 throw new Error('Failed to join channel'); 1054 } 1055 }, (err) => { 1056 console.log('Failed to join channel due to error: ' + err.stack ? err.stack : err); 1057 evtDisconnect(); 1058 }); 1059 } 1060 1061 function joinOneChannel(chain, client, org) { 1062 console.log('joinOneChannel:', org); 1063 console.log('[joinOneChannel] chain name: ', chain.getName()); 1064 1065 joinChannel(chain, client, org) 1066 .then(() => { 1067 console.log('[joinOneChannel] Successfully joined peers in organization %s to join the channel %s', ORGS[org].name, channelName); 1068 process.exit(); 1069 }, (err) => { 1070 console.log(util.format('[joinOneChannel] Failed to join peers in organization "%s" to the channel', ORGS[org].name)); 1071 process.exit(); 1072 }) 1073 .catch(function(err) { 1074 console.log('Failed request. ' + err); 1075 process.exit(); 1076 }); 1077 1078 } 1079 1080 // performance main 1081 function performance_main() { 1082 // send proposal to endorser 1083 for (i=0; i<channelOrgName.length; i++ ) { 1084 org = channelOrgName[i]; 1085 orgName=ORGS[org].name; 1086 console.log('[performance_main] org= %s, org Name= %s', org, orgName); 1087 var client = new hfc(); 1088 1089 if ( transType.toUpperCase() == 'INSTALL' ) { 1090 var username = ORGS[org].username; 1091 var secret = ORGS[org].secret; 1092 console.log('[performance_main] Deploy: user= %s, secret= %s', username, secret); 1093 1094 hfc.newDefaultKeyValueStore({ 1095 path: testUtil.storePathForOrg(orgName) 1096 }) 1097 .then((store) => { 1098 client.setStateStore(store); 1099 testUtil.getSubmitter(username, secret, client, true, org, svcFile) 1100 .then( 1101 function(admin) { 1102 console.log('[performance_main:Nid=%d] Successfully enrolled user \'admin\'', Nid); 1103 the_user = admin; 1104 var chain = client.newChain(channelName); 1105 console.log('[performance_main] chain name: ', chain.getName()); 1106 chaincodeInstall(chain, client, org); 1107 }, 1108 function(err) { 1109 console.log('[Nid=%d] Failed to wait due to error: ', Nid, err.stack ? err.stack : err); 1110 evtDisconnect(); 1111 1112 return; 1113 } 1114 ); 1115 }); 1116 } else if ( transType.toUpperCase() == 'INSTANTIATE' ) { 1117 var username = ORGS[org].username; 1118 var secret = ORGS[org].secret; 1119 console.log('[performance_main] Deploy: user= %s, secret= %s', username, secret); 1120 1121 hfc.setConfigSetting('request-timeout', 60000); 1122 hfc.newDefaultKeyValueStore({ 1123 path: testUtil.storePathForOrg(orgName) 1124 }) 1125 .then((store) => { 1126 client.setStateStore(store); 1127 testUtil.getSubmitter(username, secret, client, true, org, svcFile) 1128 .then( 1129 function(admin) { 1130 console.log('[performance_main:Nid=%d] Successfully enrolled user \'admin\'', Nid); 1131 the_user = admin; 1132 var chain = client.newChain(channelName); 1133 console.log('[performance_main] chain name: ', chain.getName()); 1134 chaincodeInstantiate(chain, client, org); 1135 }, 1136 function(err) { 1137 console.log('[Nid=%d] Failed to wait due to error: ', Nid, err.stack ? err.stack : err); 1138 evtDisconnect(); 1139 1140 return; 1141 } 1142 ); 1143 }); 1144 } else if ( transType.toUpperCase() == 'CHANNEL' ) { 1145 if ( channelOpt.action.toUpperCase() == 'CREATE' ) { 1146 createOneChannel(client, org); 1147 } else if ( channelOpt.action.toUpperCase() == 'JOIN' ) { 1148 var chain = client.newChain(channelName); 1149 console.log('[performance_main] chain name: ', chain.getName()); 1150 joinChannel(chain, client, org); 1151 } 1152 } else if ( transType.toUpperCase() == 'INVOKE' ) { 1153 // spawn off processes for transactions 1154 for (var j = 0; j < nProc; j++) { 1155 var workerProcess = child_process.spawn('node', ['./pte-execRequest.js', j, Nid, uiFile, tStart, org]); 1156 1157 workerProcess.stdout.on('data', function (data) { 1158 console.log('stdout: ' + data); 1159 }); 1160 1161 workerProcess.stderr.on('data', function (data) { 1162 console.log('stderr: ' + data); 1163 }); 1164 1165 workerProcess.on('close', function (code) { 1166 }); 1167 } 1168 } else { 1169 console.log('[Nid=%d] invalid transType: %s', Nid, transType); 1170 } 1171 1172 } 1173 } 1174 1175 function readFile(path) { 1176 return new Promise(function(resolve, reject) { 1177 fs.readFile(path, function(err, data) { 1178 if (err) { 1179 reject(err); 1180 } else { 1181 resolve(data); 1182 } 1183 }); 1184 }); 1185 } 1186 1187 function sleep(ms) { 1188 return new Promise(resolve => setTimeout(resolve, ms)); 1189 } 1190 1191 function evtDisconnect() { 1192 for ( i=0; i<g_len; i++) { 1193 if (eventHubs[i] && eventHubs[i].isconnected()) { 1194 logger.info('Disconnecting the event hub: %d', i); 1195 eventHubs[i].disconnect(); 1196 } 1197 } 1198 }