-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpte-main.js
More file actions
1665 lines (1492 loc) · 83.6 KB
/
Copy pathpte-main.js
File metadata and controls
1665 lines (1492 loc) · 83.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2016 IBM All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* usage:
* i. If using json, yml or yaml files
* node pte-main.js <Nid> <uiFile> <tStart> <PTEid>
* - Nid: Network id
* - uiFile: user input file
* - tStart: tStart
* - PTEid: PTE id
* ii. If using jsonObject
* node pte-main.js <Nid> <jsonObject> <tStart> <PTEid>
* - Nid: Network id
* - jsonObject: user input jsonObject
* - tStart: tStart
* - PTEid: PTE id
*/
// This is an end-to-end test that focuses on exercising all parts of the fabric APIs
// in a happy-path scenario
'use strict';
const child_process = require('child_process');
var hfc = require('fabric-client');
var fs = require('fs');
var path = require('path');
var util = require('util');
var testUtil = require('./pte-util.js');
var utils = require('fabric-common/lib/Utils.js');
hfc.setConfigSetting('crypto-keysize', 256);
var i = 0;
var procDone = 0;
// input: userinput json file
var PTEid = parseInt(process.argv[5]);
PTEid = PTEid ? PTEid : 0
var loggerMsg = 'PTE ' + PTEid + ' main';
var logger = new testUtil.PTELogger({ "prefix": loggerMsg, "level": "info" });
// output local time
var localTime = new Date();
logger.info('The local time is: %j', localTime.toLocaleString());
var Nid = parseInt(process.argv[2]);
var uiFile = process.argv[3];
var tStart = parseInt(process.argv[4]);
var txCfgPtr;
var txCfgTmp;
var ccDfnPtr;
var ccDfnTmp;
var uiContent;
if (uiFile.endsWith(".json") || uiFile.endsWith(".yaml") || uiFile.endsWith(".yml")) {
uiContent = testUtil.readConfigFileSubmitter(uiFile);
logger.debug('[Nid=%d pte-main] input uiContent[%s]: %j', Nid, uiFile, uiContent);
if (typeof (uiContent.txCfgPtr) === 'undefined') {
txCfgTmp = uiFile;
} else {
txCfgTmp = uiContent.txCfgPtr;
}
txCfgPtr = testUtil.readConfigFileSubmitter(txCfgTmp);
if (typeof (uiContent.ccDfnPtr) === 'undefined') {
ccDfnTmp = uiFile;
} else {
ccDfnTmp = uiContent.ccDfnPtr;
}
ccDfnPtr = testUtil.readConfigFileSubmitter(ccDfnTmp);
}
else {
uiContent = JSON.parse(uiFile)
logger.debug('[Nid=%d pte-main] input uiContent[%s]: %j', Nid, uiFile, uiContent.deploy);
txCfgPtr = uiContent;
ccDfnPtr = uiContent;
}
logger.debug('input parameters: Nid=%d, uiFile=%s, tStart=%d PTEid=%d', Nid, uiFile, tStart, PTEid);
logger.debug('[Nid=%d pte-main] input ccDfnPtr[%s]: %j input txCfgPtr: %j', Nid, ccDfnTmp, ccDfnPtr, txCfgPtr);
var TLS = testUtil.setTLS(txCfgPtr);
logger.info('[Nid=%d pte-main] TLS= %d', Nid, TLS);
var channelOpt = uiContent.channelOpt;
var channelName = channelOpt.name;
var channelOrgName = [];
for (i = 0; i < channelOpt.orgName.length; i++) {
channelOrgName.push(channelOpt.orgName[i]);
}
logger.info('[Nid=%d pte-main] channelName: %s', Nid, channelName);
logger.info('[Nid=%d pte-main] channelOrgName.length: %d, channelOrgName: %s', Nid, channelOrgName.length, channelOrgName);
// find all connection profiles
var cpList = [];
var cpPath = verifyIfPathExists(uiContent.ConnProfilePath);
logger.info('[Nid=%d pte-main] connection profile path: ', Nid, cpPath);
cpList = testUtil.getConnProfileListSubmitter(cpPath);
if (cpList.length === 0) {
logger.error('[Nid=%d pte-main] error: invalid connection profile path or no connection profiles found in the connection profile path: %s', Nid, cpPath);
process.exit(1);
}
logger.info('[Nid=%d pte-main] cpList; ', Nid, cpList);
var orderersCPFList = {};
orderersCPFList = testUtil.getNodetypeFromConnProfilesSubmitter(cpList, 'orderers');
var transType = txCfgPtr.transType.toUpperCase();
// timeout option
var timeoutOpt;
var cfgTimeout = 300000; // default 300 sec
var grpcTimeout = 3000; // default 3 sec
if ((typeof (txCfgPtr.timeoutOpt) !== 'undefined')) {
timeoutOpt = txCfgPtr.timeoutOpt;
logger.info('main - timeoutOpt: %j', timeoutOpt);
if ((typeof (timeoutOpt.preConfig) !== 'undefined')) {
cfgTimeout = parseInt(timeoutOpt.preConfig);
}
if ((typeof (timeoutOpt.grpcTimeout) !== 'undefined')) {
grpcTimeout = parseInt(timeoutOpt.grpcTimeout);
hfc.setConfigSetting('grpc-wait-for-ready-timeout', grpcTimeout);
}
}
logger.info('main - cfgTimeout: %d', cfgTimeout);
// default chaincode language: golang
var language = 'golang';
var testDeployArgs = [];
var chaincodePath;
var metadataPath;
var collectionsConfigPath;
function initDeploy(org, transType) {
if ((typeof (ccDfnPtr.deploy.language) !== 'undefined')) {
language = ccDfnPtr.deploy.language.toLowerCase();
}
if (transType) {
for (i = 0; i < ccDfnPtr.deploy.args.length; i++) {
testDeployArgs.push(ccDfnPtr.deploy.args[i]);
}
}
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
if (cpf === null) {
logger.error('[initDeploy] no connection profile is found for org (%s)', org);
process.exit(1);
}
if ((typeof (ccDfnPtr.deploy.chaincodePath) !== 'undefined')) {
if (language == "golang") {
chaincodePath = getRelativePath(ccDfnPtr.deploy.chaincodePath);
} else {
chaincodePath = verifyIfPathExists(ccDfnPtr.deploy.chaincodePath);
}
logger.info('chaincode language: %s, path: %s', language, chaincodePath);
}
if ((typeof (ccDfnPtr.deploy.metadataPath) !== 'undefined')) {
metadataPath = verifyIfPathExists(ccDfnPtr.deploy.metadataPath);
logger.info('metadataPath: %s', metadataPath);
}
//This part is untested, it might need to call the getRelativePath() function
if ((typeof (ccDfnPtr.deploy.collectionsConfigPath) !== 'undefined')) {
collectionsConfigPath = verifyIfPathExists(ccDfnPtr.deploy.collectionsConfigPath);
logger.info('collectionsConfigPath: %s', collectionsConfigPath);
}
}
function getRelativePath(inputPath) {
if (fs.existsSync(inputPath)) {
inputPath = inputPath.substring(inputPath.indexOf("github.com/hyperledger"), inputPath.length)
}
return inputPath
}
function verifyIfPathExists(inputPath) {
if (!fs.existsSync(inputPath)) {
let currentDirectory = __dirname
let homeDirectory = currentDirectory.split("/github.com")[0]
inputPath = path.join(homeDirectory, inputPath)
}
return inputPath
}
var tx_id = null;
var the_user = null;
var allEventhubs = [];
var org;
var orgName;
var orderer;
var sBlock = 0;
var eBlock = 0;
var maxWaitForFetchChannelBlock = 30;
var testSummaryArray = [];
function getOrgOrdererID(org) {
var ordererID;
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
if (0 === testUtil.getConnProfilePropCntSubmitter(cpf, 'orderers')) {
logger.error('[getOrgOrdererID] org: %s, no orderer found in the connection profile', org);
process.exit(1);
}
var cpOrgs = cpf['organizations'];
if (typeof cpOrgs[org].ordererID !== 'undefined') {
ordererID = cpOrgs[org].ordererID;
} else {
ordererID = Object.getOwnPropertyNames(orderersCPFList)[0];
}
return ordererID;
}
var chaincode_id;
var chaincode_ver;
function getCCID() {
var channelID = uiContent.channelID;
chaincode_id = uiContent.chaincodeID
if (channelID) {
chaincode_id = uiContent.chaincodeID + channelID;
}
chaincode_ver = uiContent.chaincodeVer;
logger.debug('[getCCID] Nid: %d, chaincode_id: %s, chaincode_ver: %s', Nid, chaincode_id, chaincode_ver);
}
// output report file
var rptFile = 'pteReport.txt';
var sTime = new Date();
// latency output
var latency_peer = [0, 0, 0, 0];
var latency_orderer = [0, 0, 0, 0];
var latency_event = [0, 0, 0, 0];
function update_latency_array(lat_new, rawText) {
var lat_tmp = [0, 0, 0, 0];
lat_tmp[0] = parseInt(rawText.substring(rawText.indexOf("tx num=") + 7, rawText.indexOf(", total")).trim());
lat_tmp[1] = parseInt(rawText.substring(rawText.indexOf("total time:") + 11, rawText.indexOf("ms")).trim());
lat_tmp[2] = parseInt(rawText.substring(rawText.indexOf("min=") + 4, rawText.indexOf("ms, max")).trim());
lat_tmp[3] = parseInt(rawText.substring(rawText.indexOf("max=") + 4, rawText.indexOf("ms, avg")).trim());
lat_new[0] = lat_new[0] + lat_tmp[0]; // time
lat_new[1] = lat_new[1] + lat_tmp[1]; // tx number
if (lat_new[2] == 0) { // min
lat_new[2] = lat_tmp[2];
} else if (lat_tmp[2] < lat_new[2]) {
lat_new[2] = lat_tmp[2];
}
if (lat_new[3] == 0) { // max
lat_new[3] = lat_tmp[3];
} else if (lat_tmp[3] > lat_new[3]) {
lat_new[3] = lat_tmp[3];
}
}
// test begins ....
performance_main();
// install chaincode
async function chaincodeInstall(client, org) {
try {
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
var channel
if (null === cpf) {
logger.error('[chaincodeInstall] no connection profile is found for org(%s)', org);
process.exit(1);
}
var cpOrgs = cpf['organizations'];
var orgName = cpOrgs[org].name;
logger.info('[chaincodeInstall] org: %s, org Name: %s', org, orgName);
var cryptoSuite = hfc.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({ path: testUtil.storePathForOrg(Nid, orgName) }));
client.setCryptoSuite(cryptoSuite);
// get client key
if (TLS == testUtil.TLSCLIENTAUTH) {
await testUtil.tlsEnroll(client, org, cpf);
logger.debug('[chaincodeInstall] got user private key: org= %s', org);
}
var targets;
var tgtOrg = [];
tgtOrg[0]=org;
var tgtPeers = [];
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, tgtOrg, 'ALLPEERS')
if ( tgtPeers ) {
targets = testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, null, null, null, null, null);
}
//sendInstallProposal
getCCID();
let baseDir = __dirname.split("/github.com/hyperledger/")[0];
baseDir = baseDir.endsWith("src") ? baseDir.substring(0, baseDir.length - 3) : baseDir;
var request_install = {
targets: targets,
chaincodePath: chaincodePath,
metadataPath: metadataPath,
chaincodeId: chaincode_id,
chaincodeType: language,
chaincodeVersion: chaincode_ver,
goPath: baseDir
};
logger.debug('request_install: %j', request_install.targets);
client.installChaincode(request_install, cfgTimeout)
.then(
function (results) {
var proposalResponses = results[0];
var all_good = true;
for (var i in proposalResponses) {
let one_good = false;
if (proposalResponses && proposalResponses[0].response && proposalResponses[0].response.status === 200) {
one_good = true;
logger.debug('[chaincodeInstall] org(%s): install proposal was good', org);
} else {
logger.error('[chaincodeInstall] org(%s) install proposal was bad:', org, proposalResponses[i]);
}
all_good = all_good & one_good;
}
if (all_good) {
logger.info(util.format('[chaincodeInstall] Successfully sent install Proposal to peers in (%s) and received ProposalResponse: Status - %s', orgName, proposalResponses[0].response.status));
evtDisconnect();
} else {
logger.error('[chaincodeInstall] install proposal failed, proposalResponses: %j', proposalResponses);
throw new Error('[chaincodeInstall] Failed to send install Proposal in (%s) or receive valid response. Response null or status is not 200. exiting...', orgName);
}
}).catch((err) => {
logger.error('[chaincodeInstall] Failed to install chaincode in (%s) due to error: ', orgName, err);
evtDisconnect();
process.exit(1);
});
} catch (err) {
logger.error(err)
evtDisconnect();
process.exit(1);
}
}
function buildChaincodeProposal(client, the_user, type, upgrade, transientMap) {
let tx_id = client.newTransactionID();
// send proposal to endorser
getCCID();
var request = {
chaincodePath: chaincodePath,
chaincodeId: chaincode_id,
chaincodeVersion: chaincode_ver,
fcn: ccDfnPtr.deploy.fcn,
args: testDeployArgs,
chainId: channelName,
chaincodeType: type,
'endorsement-policy': ccDfnPtr.deploy.endorsement,
'collections-config': collectionsConfigPath,
txId: tx_id
};
if (upgrade) {
// use this call to test the transient map support during chaincode instantiation
request.transientMap = transientMap;
}
return request;
}
//instantiate chaincode
async function chaincodeInstantiate(channel, client, org) {
try {
var eventHubs = [];
var cryptoSuite = hfc.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({ path: testUtil.storePathForOrg(Nid, orgName) }));
client.setCryptoSuite(cryptoSuite);
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
if (null === cpf) {
logger.error('[chaincodeInstantiate] no connection profile is found for org(%s)', org);
process.exit(1);
}
var cpOrgs = cpf['organizations'];
logger.info('[chaincodeInstantiate] org= %s, org name=%s, channel name=%s', org, orgName, channel.getName());
// get client key
if (TLS == testUtil.TLSCLIENTAUTH) {
await testUtil.tlsEnroll(client, org, cpf);
logger.debug('[chaincodeInstantiate] get user private key: org= %s', org);
}
testUtil.assignChannelOrdererSubmitter(channel, client, org, cpPath, TLS);
var ivar = 0
for (ivar = 0; ivar < channelOrgName.length; ivar++) {
var tgtOrg = [];
tgtOrg[0]=channelOrgName[ivar];
var tgtPeers = [];
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, tgtOrg, 'ALLPEERS')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, null, null, null, null, eventHubs);
}
}
logger.info('[chaincodeInstantiate:Nid=%d] ready to initialize channel[%s]', Nid, channel.getName());
channel.initialize()
.then((success) => {
logger.info('[chaincodeInstantiate:Nid=%d] Successfully initialized channel[%s]', Nid, channel.getName());
var upgrade = false;
var badTransientMap = { 'test1': 'transientValue' }; // have a different key than what the chaincode example_cc1.go expects in Init()
var request = buildChaincodeProposal(client, the_user, language, upgrade, badTransientMap);
tx_id = request.txId;
// sendInstantiateProposal
//logger.info('request_instantiate: ', request);
return channel.sendInstantiateProposal(request, cfgTimeout);
})
.then(
function (results) {
var proposalResponses = results[0];
var proposal = results[1];
var header = results[2];
var all_good = true;
for (var i in proposalResponses) {
let one_good = false;
if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) {
one_good = true;
logger.info('[chaincodeInstantiate:Nid=%d] channel(%s) chaincode instantiation was good', Nid, channelName);
} else {
logger.error('[chaincodeInstantiate:Nid=%d] channel(%s) chaincode instantiation was bad: results= %j', Nid, channelName, results);
}
all_good = all_good & one_good;
}
if (all_good) {
logger.info(util.format('[chaincodeInstantiate] Successfully sent chaincode instantiation Proposal and received ProposalResponse: Status - %s', proposalResponses[0].response.status));
var request = {
proposalResponses: proposalResponses,
proposal: proposal,
header: header
};
var deployId = tx_id.getTransactionID();
var eventPromises = [];
eventPromises.push(channel.sendTransaction(request));
eventHubs.forEach((eh) => {
let txPromise = new Promise((resolve, reject) => {
let handle = setTimeout(reject, cfgTimeout);
eh.registerTxEvent(deployId.toString(), (tx, code) => {
var tCurr1 = new Date().getTime();
clearTimeout(handle);
eh.unregisterTxEvent(deployId);
if (code !== 'VALID') {
logger.error('[chaincodeInstantiate] The chaincode instantiate transaction was invalid, code = ' + code);
reject();
} else {
logger.debug('[chaincodeInstantiate] The chaincode instantiate transaction was valid.');
resolve();
}
}, (err) => {
clearTimeout(handle);
reject();
}, {
disconnect: true
});
eh.connect();
});
logger.info('[chaincodeInstantiate] register eventhub %s with tx=%s', eh.getPeerAddr(), deployId);
eventPromises.push(txPromise);
});
var tCurr = new Date().getTime();
logger.debug('[chaincodeInstantiate] Promise.all tCurr=%d', tCurr);
return Promise.all(eventPromises)
.then((results) => {
logger.info('[chaincodeInstantiate] Event promise all complete and testing complete');
return results[0]; // the first returned value is from the 'sendPromise' which is from the 'sendTransaction()' call
}).catch((err) => {
var tCurr1 = new Date().getTime();
logger.error('[chaincodeInstantiate] failed to send instantiate transaction: tCurr=%d, elapse time=%d', tCurr, tCurr1 - tCurr);
//logger.error('Failed to send instantiate transaction and get notifications within the timeout period.');
evtDisconnect();
process.exit(1);
});
} else {
logger.error('[chaincodeInstantiate] Failed to send instantiate Proposal or receive valid response. Response results: %j', results);
evtDisconnect();
throw new Error('Failed to send instantiate Proposal or receive valid response. Response null or status is not 200. exiting...');
}
})
.then((response) => {
if (response.status === 'SUCCESS') {
logger.info('[chaincodeInstantiate(Nid=%d)] Successfully instantiate transaction on %s. ', Nid, channelName);
evtDisconnect();
return;
} else {
logger.error('[chaincodeInstantiate(Nid=%d)] Failed to instantiate transaction on %s. Error response: %j', Nid, channelName, response);
evtDisconnect();
throw new Error('Failed to instantiate transaction on %s. Response null or status is not 200. exiting...', channelName);
}
}).catch((err) => {
logger.error('[chaincodeInstantiate(Nid=%d)] Failed to instantiate transaction on %s due to error: ', Nid, channelName, err.stack ? err.stack : err);
evtDisconnect();
process.exit(1);
}
);
} catch (err) {
logger.error(err)
evtDisconnect();
process.exit(1)
}
}
//Upgrade chaincode
async function chaincodeUpgrade(channel, client, org) {
try {
var eventHubs = [];
var cryptoSuite = hfc.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({ path: testUtil.storePathForOrg(Nid, orgName) }));
client.setCryptoSuite(cryptoSuite);
logger.info('[chaincodeUpgrade] org= %s, org name=%s, channel name=%s', org, orgName, channel.getName());
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
if (null === cpf) {
logger.error('[chaincodeUpgrade] no connection profile is found for org(%s)', org);
process.exit(1);
}
// get client key
if (TLS == testUtil.TLSCLIENTAUTH) {
await testUtil.tlsEnroll(client, org, cpf);
logger.debug('[chaincodeUpgrade] get user private key: org= %s', org);
}
testUtil.assignChannelOrdererSubmitter(channel, client, org, cpPath, TLS);
var ivar = 0
for (ivar = 0; ivar < channelOrgName.length; ivar++) {
var tgtOrg = [];
tgtOrg[0]=channelOrgName[ivar];
var tgtPeers = [];
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, tgtOrg, 'ALLPEERS')
if ( tgtPeers ) {
testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, null, null, null, null, eventHubs);
}
}
logger.info('[chaincodeUpgrade:Nid=%d] ready to initialize channel[%s]', Nid, channel.getName());
channel.initialize()
.then((success) => {
logger.info('[chaincodeUpgrade:Nid=%d] Successfully initialized channel[%s]', Nid, channel.getName());
var upgrade = true;
var badTransientMap = { 'test1': 'transientValue' }; // have a different key than what the chaincode example_cc1.go expects in Init()
var transientMap = { 'test': 'transientValue' };
var request = buildChaincodeProposal(client, the_user, language, upgrade, badTransientMap);
tx_id = request.txId;
return channel.sendUpgradeProposal(request, cfgTimeout);
})
.then(
function (results) {
var proposalResponses = results[0];
var proposal = results[1];
var header = results[2];
var all_good = true;
for (var i in proposalResponses) {
let one_good = false;
if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) {
one_good = true;
logger.info('[chaincodeUpgrade:Nid=%d] channel(%s) chaincode upgrade was good', Nid, channelName);
} else {
logger.error('[chaincodeUpgrade:Nid=%d] channel(%s) chaincode upgrade was bad: results= %j', Nid, channelName, results);
process.exit(1);
}
all_good = all_good & one_good;
}
if (all_good) {
logger.info(util.format('[chaincodeUpgrade] Successfully sent chaincode upgrade Proposal and received ProposalResponse: Status - %s', proposalResponses[0].response.status));
var request = {
proposalResponses: proposalResponses,
proposal: proposal,
header: header
};
var deployId = tx_id.getTransactionID();
var eventPromises = [];
eventPromises.push(channel.sendTransaction(request));
eventHubs.forEach((eh) => {
let txPromise = new Promise((resolve, reject) => {
let handle = setTimeout(reject, cfgTimeout);
eh.registerTxEvent(deployId.toString(), (tx, code) => {
var tCurr1 = new Date().getTime();
clearTimeout(handle);
eh.unregisterTxEvent(deployId);
if (code !== 'VALID') {
logger.error('[chaincodeUpgrade] The chaincode upgrade transaction was invalid, code = ' + code);
reject();
} else {
logger.info('[chaincodeUpgrade] The chaincode upgrade transaction was valid.');
resolve();
}
}, (err) => {
clearTimeout(handle);
reject();
}, {
disconnect: true
});
eh.connect();
});
logger.info('[chaincodeUpgrade] register eventhub %s with tx=%s', eh.getPeerAddr(), deployId);
eventPromises.push(txPromise);
});
var tCurr = new Date().getTime();
logger.debug('[chaincodeUpgrade] Promise.all tCurr=%d', tCurr);
return Promise.all(eventPromises)
.then((results) => {
logger.info('[chaincodeUpgrade] Event promise all complete and testing complete');
return results[0]; // the first returned value is from the 'sendPromise' which is from the 'sendTransaction()' call
}).catch((err) => {
var tCurr1 = new Date().getTime();
logger.error('[chaincodeUpgrade] failed to send upgrade transaction: tCurr=%d, elapse time=%d', tCurr, tCurr1 - tCurr);
evtDisconnect();
process.exit(1);
});
} else {
logger.error('[chaincodeUpgrade] Failed to send upgrade Proposal or receive valid response. Response results: %j', results);
evtDisconnect();
throw new Error('Failed to send upgrade Proposal or receive valid response. Response null or status is not 200. exiting...');
}
})
.then((response) => {
if (response.status === 'SUCCESS') {
logger.info('[chaincodeUpgrade(Nid=%d)] Successfully Upgrade transaction on %s. ', Nid, channelName);
evtDisconnect();
return;
} else {
logger.error('[chaincodeUpgrade(Nid=%d)] Failed to Upgrade transaction on %s. Error response: %j', Nid, channelName, response);
evtDisconnect();
process.exit(1);
}
}).catch((err) => {
logger.error('[chaincodeUpgrade(Nid=%d)] Failed to upgrade transaction on %s due to error: ', Nid, channelName, err.stack ? err.stack : err);
evtDisconnect();
process.exit(1);
}
);
} catch (err) {
logger.error(err)
evtDisconnect();
process.exit(1);
}
}
//create or update channel
async function createOrUpdateOneChannel(client, channelOrgName) {
try {
var config;
var envelope_bytes;
var signatures = [];
var username;
var secret;
var submitter = null;
hfc.setConfigSetting('key-value-store', 'fabric-common/lib/impl/FileKeyValueStore.js');
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, channelOrgName[0]);
if (null === cpf) {
logger.error('[createOrUpdateOneChannel] no connection profile is found for org(%s)', org);
process.exit(1);
}
logger.info('[createOrUpdateOneChannel] org(%s) go path: %s', channelOrgName[0]);
var channelTX = channelOpt.channelTX;
if (!fs.existsSync(channelTX)) {
let currentPath = __dirname
let homeDirecotry = currentPath.split("github.com/")[0]
channelTX = path.join(homeDirecotry, channelTX)
}
logger.info('[createOrUpdateOneChannel] channelTX: ', channelTX);
envelope_bytes = fs.readFileSync(channelTX);
config = client.extractChannelConfig(envelope_bytes);
logger.info('[createOrUpdateOneChannel] Successfully extracted the config update from the configtx envelope: ', channelTX);
// get client key
if (TLS == testUtil.TLSCLIENTAUTH) {
await testUtil.tlsEnroll(client, channelOrgName[0], cpf);
logger.debug('[createOrUpdateOneChannel] get user private key: org= %s', channelOrgName[0]);
}
hfc.newDefaultKeyValueStore({
path: testUtil.storePathForOrg(Nid, orgName)
}).then((store) => {
client.setStateStore(store);
var cryptoSuite = hfc.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({ path: testUtil.storePathForOrg(org) }));
client.setCryptoSuite(cryptoSuite);
var submitePromises = [];
channelOrgName.forEach((org) => {
submitter = new Promise(function (resolve, reject) {
cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
var cpOrgs = cpf['organizations'];
username = testUtil.getOrgEnrollIdSubmitter(cpf, org);
secret = testUtil.getOrgEnrollSecretSubmitter(cpf, org);
orgName = cpOrgs[org].name;
logger.debug('[createOrUpdateOneChannel] org= %s, org name= %s, username= %s, secret= %s', org, orgName, username, secret);
client._userContext = null;
resolve(testUtil.getSubmitter(username, secret, client, true, Nid, org, cpf));
});
submitePromises.push(submitter);
});
// all the orgs
return Promise.all(submitePromises);
})
.then((results) => {
results.forEach(function (result) {
var signature = client.signChannelConfig(config);
logger.info('[createOrUpdateOneChannel] Successfully signed config update for one organization ');
// collect signature from org admin
signatures.push(signature);
});
return signatures;
}).then((sigs) => {
client._userContext = null;
return testUtil.getOrderAdminSubmitter(client, channelOrgName[0], cpPath);
}).then(async (admin) => {
the_user = admin;
logger.info('[createOrUpdateOneChannel] Successfully enrolled user \'admin\' for', "orderer");
var channelName = uiContent.ordererSystemChannel ? uiContent.ordererSystemChannel : "orderersystemchannel"
var sysChannel = client.newChannel(channelName);
testUtil.assignChannelOrdererSubmitter(sysChannel, client, channelOrgName[0], cpPath, TLS);
let tx_id_sysCh = client.newTransactionID();
var sysCh_request = {
txId: tx_id_sysCh
};
let retry = 0;
let block
while (retry < maxWaitForFetchChannelBlock ) {
try {
block = await sysChannel.getGenesisBlock(sysCh_request)
break
} catch (err) {
if ( retry < maxWaitForFetchChannelBlock ) {
await sleep(1000);
retry++
} else {
logger.error('[createOrUpdateOneChannel] Orderer system channel %s is not yet ready even after %d seconds, please try again later', channelName, retry);
process.exit(1);
}
}
}
if (block == undefined) {
logger.error('[createOrUpdateOneChannel] Unable to fetch genesis block for orderer system channel %s even after %d seconds, please try again later', channelName, retry);
process.exit(1);
} else {
return block
}
}).then((block) => {
var signature = client.signChannelConfig(config);
logger.info('[createOrUpdateOneChannel] Successfully signed config update: ', "orderer");
// collect signature from org admin
signatures.push(signature);
logger.debug('[createOrUpdateOneChannel] done signing: %s', channelName);
// add new orderer
orderer = testUtil.assignChannelOrdererSubmitter(null, client, channelOrgName[0], cpPath, TLS);
// build up the create request
let tx_id = client.newTransactionID();
let nonce = tx_id.getNonce();
var request = {
config: config,
signatures: signatures,
name: channelName,
orderer: orderer,
txId: tx_id,
nonce: nonce
};
//logger.info('request: ',request);
if (channelOpt.action.toUpperCase() == 'CREATE') {
return client.createChannel(request);
} else if (channelOpt.action.toUpperCase() == 'UPDATE') {
return client.updateChannel(request);
}
}).then((result) => {
if (result.status == 'SUCCESS') {
logger.info('[createOrUpdateOneChannel] Successfully created/updated the channel (%s) with result: %j', channelName, result);
evtDisconnect();
process.exit();
} else {
logger.error('[createOrUpdateOneChannel] Failed to created/updated the channel (%s) with result: %j', channelName, result);
evtDisconnect();
process.exit(1);
}
})
.then((nothing) => {
logger.info('Successfully waited to make sure new channel was created/updated.');
evtDisconnect();
process.exit();
}).catch((err) => {
logger.error('Failed due to error: ' + err.stack ? err.stack : err);
evtDisconnect();
process.exit(1);
});
} catch (err) {
logger.error(err)
evtDisconnect()
process.exit(1)
}
}
// join channel
async function joinChannel(channel, client, org) {
try {
var cpf = testUtil.findOrgConnProfileSubmitter(cpList, org);
if (null === cpf) {
logger.error('[joinChannel] no connection profile is found for org(%s)', org);
process.exit(1);
}
var cpOrgs = cpf['organizations'];
var orgName = cpOrgs[org].name;
logger.info('[joinChannel] Calling peers in organization (%s) to join the channel (%s)', orgName, channelName);
var username = testUtil.getOrgEnrollIdSubmitter(cpf, org);
var secret = testUtil.getOrgEnrollSecretSubmitter(cpf, org);
logger.debug('[joinChannel] user=%s, secret=%s', username, secret);
var genesis_block = null;
var eventHubs = [];
var blockCallbacks = [];
// get client key
if (TLS == testUtil.TLSCLIENTAUTH) {
await testUtil.tlsEnroll(client, org, cpf);
logger.debug('[joinChannel] get user private key: org= %s', org);
}
return hfc.newDefaultKeyValueStore({
path: testUtil.storePathForOrg(Nid, orgName)
}).then((store) => {
client.setStateStore(store);
client._userContext = null;
return testUtil.getOrderAdminSubmitter(client, org, cpPath)
}).then(async (admin) => {
logger.info('[joinChannel:%s] Successfully enrolled orderer \'admin\'', org);
the_user = admin;
logger.debug('[joinChannel] orderer admin: ', admin);
// add orderers
testUtil.assignChannelOrdererSubmitter(channel, client, org, cpPath, TLS);
let tx_id = client.newTransactionID();
var request = {
txId: tx_id
};
let retry = 0;
let block
while ( retry < maxWaitForFetchChannelBlock ) {
try {
block = await channel.getGenesisBlock(request);
break
} catch (err) {
if ( retry < maxWaitForFetchChannelBlock ) {
await sleep(1000);
retry++
} else {
logger.error('[joinChannel] Channel %s is not yet ready even after %d seconds, please try again later', channelName, retry);
process.exit(1);
}
}
}
if (block == undefined) {
logger.error('[joinChannel] Unable to fetch genesis block for Channel %s even after %d seconds, please try again later', channelName, retry);
process.exit(1);
} else {
return block
}
}).then((block) => {
logger.info('[joinChannel:org=%s:%s] Successfully got the genesis block', channelName, org);
genesis_block = block;
client._userContext = null;
return testUtil.getSubmitter(username, secret, client, true, Nid, org, cpf);
}).then((admin) => {
logger.info('[joinChannel] Successfully enrolled org:' + org + ' \'admin\'');
the_user = admin;
logger.debug('[joinChannel] org admin: ', admin);
// add peers and events
var targets;
var tgtOrg = [];
tgtOrg[0]=org;
var tgtPeers = [];
tgtPeers = testUtil.getTargetPeerListSubmitter(cpList, tgtOrg, 'ALLPEERS')
if ( tgtPeers ) {
targets = testUtil.assignChannelPeersSubmitter(cpList, channel, client, tgtPeers, TLS, cpPath, null, null, null, null, eventHubs);
}
tx_id = client.newTransactionID();
let request = {
targets: targets,
block: genesis_block,
txId: tx_id
};
return channel.joinChannel(request);
})
.then((results) => {
logger.debug(util.format('[joinChannel:%s] join Channel (%s) R E S P O N S E : %j', org, channelName, results));
if (results[0] && results[0].response && results[0].response.status == 200) {
logger.info('[joinChannel] Successfully joined peers in (%s:%s)', channelName, orgName);
evtDisconnect(eventHubs, blockCallbacks);
} else {
logger.error('[joinChannel] Failed to join peers in org (%s), Error: %j', orgName, results);
evtDisconnect(eventHubs, blockCallbacks);
throw new Error('[joinChannel] Failed to join channel');
}
}).catch((err) => {
logger.error('[joinChannel] --- Failed to join channel due to error: ' + err.stack ? err.stack : err);
evtDisconnect(eventHubs, blockCallbacks);
process.exit(1);
});
} catch (err) {
logger.error(err);
evtDisconnect();
process.exit(1);
}
}
var totalLength = 0;
async function execQueryBlock(channel, sB, eB) {
try {
var tmp = txCfgPtr.queryBlockOpt;
var tgtOrg = Object.keys(tmp)[0];
var qBlks = [];
for (i = sB; i <= eB; i++) {
qBlks.push(parseInt(i));
}
var qPromises = [];
var qb = null;
var qi = 0;
qBlks.forEach((qi) => {
qb = new Promise(function (resolve, reject) {
resolve(channel.queryBlock(qi));
});
qPromises.push(qb);
});
return Promise.all(qPromises).then((block) => {
block.forEach(function (block) {
totalLength = totalLength + block.data.data.length;
logger.info('[execQueryBlock] channel:peer:block:length:accu length=%s:%s:%d:%d:%d', channelName, tmp[tgtOrg][0], block.header.number, block.data.data.length, totalLength);
});
logger.info('[execQueryBlock] Summary channel:peer:starting block:ending block:length=%s:%s:%d:%d:%j', channelName, tmp[tgtOrg][0], sBlock, eB, totalLength);
}).catch((err) => {
logger.error(err.stack ? err.stack : err);
evtDisconnect();