-
Notifications
You must be signed in to change notification settings - Fork 14
/
pte-main.js
1392 lines (1243 loc) · 58.9 KB
/
pte-main.js
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:
* node pte-main.js <Nid> <uiFile> <tStart> <PTEid>
* - Nid: Network id
* - uiFile: user input file
* - 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';
var path = require('path');
var hfc = require('fabric-client');
var X509 = require('jsrsasign').X509;
var fs = require('fs');
var grpc = require('grpc');
var util = require('util');
var testUtil = require('./pte-util.js');
var utils = require('fabric-client/lib/utils.js');
var Peer = require('fabric-client/lib/Peer.js');
var Orderer = require('fabric-client/lib/Orderer.js');
var EventHub = require('fabric-client/lib/EventHub.js');
var FabricCAServices = require('fabric-ca-client/lib/FabricCAClientImpl');
var FabricCAClient = FabricCAServices.FabricCAClient;
var User = require('fabric-client/lib/User.js');
var Client = require('fabric-client/lib/Client.js');
utils.setConfigSetting('crypto-keysize', 256);
const child_process = require('child_process');
var webUser = null;
var tmp;
var i=0;
var procDone=0;
// input: userinput json file
var PTEid = parseInt(process.argv[5]);
var loggerMsg='PTE ' + PTEid + ' main';
var logger = utils.getLogger(loggerMsg);
var Nid = parseInt(process.argv[2]);
var uiFile = process.argv[3];
var tStart = parseInt(process.argv[4]);
logger.info('input parameters: Nid=%d, uiFile=%s, tStart=%d PTEid=%d', Nid, uiFile, tStart, PTEid);
var uiContent = JSON.parse(fs.readFileSync(uiFile));
var TLS=uiContent.TLS;
var channelID = uiContent.channelID;
var chaincode_id = uiContent.chaincodeID+channelID;
var chaincode_ver = uiContent.chaincodeVer;
logger.info('Nid: %d, chaincode_id: %s, chaincode_ver: %s', Nid, chaincode_id, chaincode_ver);
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('TLS: %s', TLS.toUpperCase());
logger.info('channelName: %s', channelName);
logger.info('channelOrgName.length: %d, channelOrgName: %s', channelOrgName.length, channelOrgName);
var svcFile = uiContent.SCFile[0].ServiceCredentials;
logger.info('svcFile; ', svcFile);
hfc.addConfigFile(path.resolve(__dirname, svcFile));
var ORGS = hfc.getConfigSetting('test-network');
var goPath=process.env.GOPATH;
if ( typeof(ORGS.gopath) === 'undefined' ) {
goPath = '';
} else if ( ORGS.gopath == 'GOPATH') {
goPath = process.env['GOPATH'];
} else {
goPath = ORGS.gopath;
}
logger.info('GOPATH: ', goPath);
var users = hfc.getConfigSetting('users');
var transType = uiContent.transType;
var nProcPerOrg = parseInt(uiContent.nProcPerOrg);
logger.info('nProcPerOrg ', nProcPerOrg);
var tCurr;
// default chaincode language: golang
var language='golang';
var testDeployArgs = [];
var chaincodePath;
function initDeploy() {
if ((typeof( uiContent.deploy.language ) !== 'undefined')) {
language=uiContent.deploy.language.toLowerCase();
}
for (i=0; i<uiContent.deploy.args.length; i++) {
testDeployArgs.push(uiContent.deploy.args[i]);
}
chaincodePath = uiContent.deploy.chaincodePath;
if ( language === 'node' ) {
chaincodePath = path.resolve(goPath, 'src', chaincodePath);
}
logger.info('chaincode language: %s, path: %s', language, chaincodePath)
}
var tx_id = null;
var nonce = null;
var the_user = null;
var g_len = nProcPerOrg;
var cfgtxFile;
var allEventhubs = [];
var org;
var orgName;
var targets = [];
var eventHubs=[];
var orderer;
var sBlock = 0;
var eBlock = 0;
var qOrg ;
var qPeer ;
var testSummaryArray=[];
function printChainInfo(channel) {
logger.info('[printChainInfo] channel name: ', channel.getName());
logger.info('[printChainInfo] orderers: ', channel.getOrderers());
logger.info('[printChainInfo] peers: ', channel.getPeers());
logger.info('[printChainInfo] events: ', eventHubs);
}
function clientNewOrderer(client, org) {
var ordererID = ORGS[org].ordererID;
logger.info('[clientNewOrderer] org: %s, ordererID: %s', org, ordererID);
if (TLS.toUpperCase() == 'ENABLED') {
var caRootsPath = path.resolve(goPath, ORGS['orderer'][ordererID].tls_cacerts);
let data = fs.readFileSync(caRootsPath);
let caroots = Buffer.from(data).toString();
orderer = client.newOrderer(
ORGS['orderer'][ordererID].url,
{
'pem': caroots,
'ssl-target-name-override': ORGS['orderer'][ordererID]['server-hostname']
}
);
} else {
orderer = client.newOrderer(ORGS['orderer'][ordererID].url);
}
logger.info('[clientNewOrderer] orderer: %s', ORGS['orderer'][ordererID].url);
}
function chainAddOrderer(channel, client, org) {
logger.info('[chainAddOrderer] channel name: ', channel.getName());
var ordererID = ORGS[org].ordererID;
if (TLS.toUpperCase() == 'ENABLED') {
var caRootsPath = path.resolve(goPath, ORGS['orderer'][ordererID].tls_cacerts);
var data = fs.readFileSync(caRootsPath);
let caroots = Buffer.from(data).toString();
channel.addOrderer(
client.newOrderer(
ORGS['orderer'][ordererID].url,
{
'pem': caroots,
'ssl-target-name-override': ORGS['orderer'][ordererID]['server-hostname']
}
)
);
} else {
channel.addOrderer(
client.newOrderer(ORGS['orderer'][ordererID].url)
);
}
logger.info('[chainAddOrderer] channel orderers: ', channel.getOrderers());
}
function channelAddAllPeer(chain, client) {
logger.info('[channelAddAllPeer] channel name: ', channel.getName());
var peerTmp;
var data;
var eh;
for (let key1 in ORGS) {
if (ORGS.hasOwnProperty(key1)) {
for (let key in ORGS[key1]) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
data = fs.readFileSync(path.resolve(goPath, ORGS[key1][key].tls_cacerts));
peerTmp = client.newPeer(
ORGS[key1][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[key1][key]['server-hostname']
}
);
targets.push(peerTmp);
channel.addPeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[key1][key].requests);
targets.push(peerTmp);
channel.addPeer(peerTmp);
}
eh=client.newEventHub();
if (TLS.toUpperCase() == 'ENABLED') {
eh.setPeerAddr(
ORGS[key1][key].events,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[key1][key]['server-hostname']
}
);
} else {
eh.setPeerAddr(ORGS[key1][key].events);
}
eh.connect();
eventHubs.push(eh);
}
}
}
}
logger.debug('[channelAddAllPeer] channel peers: ', channel.getPeers());
}
function channelRemoveAllPeer(channel, client) {
logger.info('[channelRemoveAllPeer] channel name: ', channel.getName());
var peerTmp;
var data;
var eh;
for (let key1 in ORGS) {
if (ORGS.hasOwnProperty(key1)) {
for (let key in ORGS[key1]) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
data = fs.readFileSync(path.resolve(goPath, ORGS[key1][key].tls_cacerts));
peerTmp = client.newPeer(
ORGS[key1][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[key1][key]['server-hostname']
}
);
logger.info('[channelRemoveAllPeer] channel remove peer: ', ORGS[key1][key].requests);
channel.removePeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[key1][key].requests);
logger.info('[channelRemoveAllPeer] channel remove peer: ', ORGS[key1][key].requests);
channel.removePeer(peerTmp);
}
}
}
}
}
}
function channelAddAnchorPeer(channel, client, org) {
logger.info('[channelAddAnchorPeer] channel name: ', channel.getName());
var peerTmp;
var data;
var eh;
for (let key in ORGS) {
if (ORGS.hasOwnProperty(key) && typeof ORGS[key].peer1 !== 'undefined') {
if (TLS.toUpperCase() == 'ENABLED') {
data = fs.readFileSync(path.resolve(goPath, ORGS[key].peer1['tls_cacerts']));
peerTmp = client.newPeer(
ORGS[key].peer1.requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[key].peer1['server-hostname']
}
);
targets.push(peerTmp);
channel.addPeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[key].peer1.requests);
targets.push(peerTmp);
channel.addPeer(peerTmp);
}
logger.info('[channelAddAnchorPeer] requests: %s', ORGS[key].peer1.requests);
//an event listener can only register with a peer in its own org
if ( key == org ) {
eh=client.newEventHub();
if (TLS.toUpperCase() == 'ENABLED') {
eh.setPeerAddr(
ORGS[key].peer1.events,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[key].peer1['server-hostname']
}
);
} else {
eh.setPeerAddr(ORGS[key].peer1.events);
}
eh.connect();
eventHubs.push(eh);
logger.info('[channelAddAnchorPeer] events: %s ', ORGS[key].peer1.events);
}
}
}
logger.debug('[channelAddAnchorPeer] channel peers: ', channel.getPeers());
}
function channelAddPeer(channel, client, org) {
logger.info('[channelAddPeer] channel name: ', channel.getName());
var peerTmp;
var eh;
for (let key in ORGS[org]) {
if (ORGS[org].hasOwnProperty(key)) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
peerTmp = client.newPeer(
ORGS[org][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
targets.push(peerTmp);
channel.addPeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[org][key].requests);
targets.push(peerTmp);
channel.addPeer(peerTmp);
}
}
}
}
logger.info('[channelAddPeer] channel peers: ', channel.getPeers());
}
function channelAddQIPeer(channel, client, qorg, qpeer) {
logger.info('[channelAddQIPeer] channel name: ', channel.getName());
logger.info('[channelAddQIPeer] qorg %s qpeer: ', qorg,qpeer);
var peerTmp;
var eh;
for (let key in ORGS[qorg]) {
if (ORGS[qorg].hasOwnProperty(key)) {
if (key.indexOf(qpeer) === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[qorg][key]['tls_cacerts']));
peerTmp = client.newPeer(
ORGS[qorg][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[qorg][key]['server-hostname']
}
);
targets.push(peerTmp);
channel.addPeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[qorg][key].requests);
targets.push(peerTmp);
channel.addPeer(peerTmp);
}
}
}
}
logger.info('[channelAddQIPeer] channel peers: ', channel.getPeers());
}
function channelAddPeer1(channel, client, org) {
logger.info('[channelAddPeer1] channel name: %s, org: %s', channel.getName(), org);
var peerTmp;
var eh;
for (let key in ORGS[org]) {
if (ORGS[org].hasOwnProperty(key)) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
peerTmp = client.newPeer(
ORGS[org][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
targets.push(peerTmp);
channel.addPeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[org][key].requests);
targets.push(peerTmp);
channel.addPeer(peerTmp);
}
break;
}
}
}
logger.debug('[channelAddPeer1] org: %s, channel peers: ', org, channel.getPeers());
}
function channelRemovePeer(channel, client, org) {
logger.info('[channelRemovePeer] channel name: ', channel.getName());
var peerTmp;
var eh;
for (let key in ORGS[org]) {
if (ORGS[org].hasOwnProperty(key)) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
peerTmp = client.newPeer(
ORGS[org][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
channel.removePeer(peerTmp);
} else {
peerTmp = client.newPeer( ORGS[org][key].requests);
targets.push(peerTmp);
channel.removePeer(peerTmp);
}
}
}
}
}
function channelAddPeerEventJoin(channel, client, org) {
logger.info('[channelAddPeerEvent] channel name: ', channel.getName());
var eh;
var peerTmp;
for (let key in ORGS[org]) {
if (ORGS[org].hasOwnProperty(key)) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
targets.push(
client.newPeer(
ORGS[org][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
)
);
} else {
targets.push(
client.newPeer(
ORGS[org][key].requests
)
);
logger.info('[channelAddPeerEvent] peer: ', ORGS[org][key].requests);
}
eh=client.newEventHub();
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
eh.setPeerAddr(
ORGS[org][key].events,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
} else {
eh.setPeerAddr(ORGS[org][key].events);
}
eh.connect();
eventHubs.push(eh);
logger.info('[channelAddPeerEvent] requests: %s, events: %s ', ORGS[org][key].requests, ORGS[org][key].events);
}
}
}
}
function channelAddPeerEvent(channel, client, org) {
logger.info('[channelAddPeerEvent] channel name: ', channel.getName());
var eh;
var peerTmp;
for (let key in ORGS[org]) {
if (ORGS[org].hasOwnProperty(key)) {
if (key.indexOf('peer') === 0) {
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
peerTmp = client.newPeer(
ORGS[org][key].requests,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
targets.push(peerTmp);
channel.addPeer(peerTmp);
} else {
peerTmp = client.newPeer(
ORGS[org][key].requests
);
channel.addPeer(peerTmp);
logger.info('[channelAddPeerEvent] peer: ', ORGS[org][key].requests);
}
eh=client.newEventHub();
if (TLS.toUpperCase() == 'ENABLED') {
let data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
eh.setPeerAddr(
ORGS[org][key].events,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
} else {
eh.setPeerAddr(ORGS[org][key].events);
}
eh.connect();
eventHubs.push(eh);
logger.info('[channelAddPeerEvent] requests: %s, events: %s ', ORGS[org][key].requests, ORGS[org][key].events);
}
}
}
}
function channelAddEvent(channel, client, org) {
logger.info('[channelAddEvent] channel name: ', channel.getName());
var eh;
var peerTmp;
for (let key in ORGS[org]) {
if (ORGS[org].hasOwnProperty(key)) {
if (key.indexOf('peer') === 0) {
eh=client.newEventHub();
if (TLS.toUpperCase() == 'ENABLED') {
var data = fs.readFileSync(path.resolve(goPath, ORGS[org][key]['tls_cacerts']));
eh.setPeerAddr(
ORGS[org][key].events,
{
pem: Buffer.from(data).toString(),
'ssl-target-name-override': ORGS[org][key]['server-hostname']
}
);
} else {
eh.setPeerAddr(ORGS[org][key].events);
}
eh.connect();
eventHubs.push(eh);
logger.info('[channelAddEvent] requests: %s, events: %s ', ORGS[org][key].requests, ORGS[org][key].events);
break;
}
}
}
}
// test begins ....
performance_main();
// install chaincode
function chaincodeInstall(channel, client, org) {
orgName = ORGS[org].name;
logger.info('[chaincodeInstall] org: %s, org Name: %s, channel name: %s', org, orgName, channel.getName());
var cryptoSuite = hfc.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(hfc.newCryptoKeyStore({path: testUtil.storePathForOrg(Nid, orgName)}));
client.setCryptoSuite(cryptoSuite);
chainAddOrderer(channel, client, org);
channelAddPeer(channel, client, org);
//printChainInfo(channel);
//sendInstallProposal
var request_install = {
targets: targets,
chaincodePath: chaincodePath,
chaincodeId: chaincode_id,
chaincodeType: language,
chaincodeVersion: chaincode_ver
};
logger.info('request_install: ', request_install);
client.installChaincode(request_install)
.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[0].response && proposalResponses[0].response.status === 200) {
one_good = true;
logger.info('[chaincodeInstall] org(%s): install proposal was good', org);
} else {
logger.error('[chaincodeInstall] org(%s): install proposal was bad', org);
}
all_good = all_good & one_good;
}
if (all_good) {
logger.info(util.format('[chaincodeInstall] Successfully sent install Proposal to peers in (%s:%s) and received ProposalResponse: Status - %s', channelName, orgName, proposalResponses[0].response.status));
evtDisconnect();
process.exit();
} else {
logger.error('[chaincodeInstall] Failed to send install Proposal in (%s:%s) or receive valid response. Response null or status is not 200. exiting...', channelName, orgName);
evtDisconnect();
process.exit();
}
}, (err) => {
logger.error('Failed to enroll user \'admin\'. ' + err);
evtDisconn;
process.exit();
});
}
function buildChaincodeProposal(client, the_user, type, upgrade, transientMap) {
let tx_id = client.newTransactionID();
// send proposal to endorser
var request = {
chaincodePath: chaincodePath,
chaincodeId: chaincode_id,
chaincodeVersion: chaincode_ver,
fcn: uiContent.deploy.fcn,
args: testDeployArgs,
chainId: channelName,
chaincodeType: type,
'endorsement-policy': uiContent.deploy.endorsement,
txId: tx_id
// use this to demonstrate the following policy:
// 'if signed by org1 admin, then that's the only signature required,
// but if that signature is missing, then the policy can also be fulfilled
// when members (non-admin) from both orgs signed'
/*
'endorsement-policy': {
identities: [
{ role: { name: 'member', mspId: ORGS['org1'].mspid }},
{ role: { name: 'member', mspId: ORGS['org2'].mspid }},
{ role: { name: 'admin', mspId: ORGS['org1'].mspid }}
],
policy: {
'1-of': [
{ 'signed-by': 2},
{ '2-of': [{ 'signed-by': 0}, { 'signed-by': 1 }]}
]
}
}
*/
};
if(upgrade) {
// use this call to test the transient map support during chaincode instantiation
request.transientMap = transientMap;
}
return request;
}
//instantiate chaincode
function chaincodeInstantiate(channel, client, org) {
var cryptoSuite = Client.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(Client.newCryptoKeyStore({path: testUtil.storePathForOrg(Nid, orgName)}));
client.setCryptoSuite(cryptoSuite);
logger.info('[chaincodeInstantiate] org= %s, org name=%s, channel name=%s', org, orgName, channel.getName());
chainAddOrderer(channel, client, org);
//channelAddPeerEvent(chain, client, org);
//channelAddAnchorPeer(channel, client, org);
var ivar=0
for (ivar=0; ivar<channelOrgName.length; ivar++ ) {
var orgInstantiate = channelOrgName[ivar];
channelAddPeer1(channel, client, orgInstantiate);
}
channelAddEvent(channel, client, org);
//printChainInfo(channel);
channel.initialize()
.then((success) => {
logger.info('[chaincodeInstantiate:Nid=%d] Successfully initialize 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 transientMap = { 'test': 'transientValue' };
var request = buildChaincodeProposal(client, the_user, language, upgrade, badTransientMap);
tx_id = request.txId;
// sendInstantiateProposal
//logger.info('request_instantiate: ', request_instantiate);
return channel.sendInstantiateProposal(request, 120000);
},
function(err) {
logger.error('[chaincodeInstantiate:Nid=%d] Failed to initialize channel[%s] due to error: ', Nid, channelName, err.stack ? err.stack : err);
evtDisconnect();
process.exit();
})
.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[0].response && proposalResponses[0].response.status === 200) {
one_good = true;
logger.info('[chaincodeInstantiate] channelName(%s) chaincode instantiation was good', channelName);
} else {
logger.error('[chaincodeInstantiate] channelName(%s) chaincode instantiation was bad', channelName);
}
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 = [];
eventHubs.forEach((eh) => {
let txPromise = new Promise((resolve, reject) => {
let handle = setTimeout(reject, 120000);
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.info('[chaincodeInstantiate] The chaincode instantiate transaction was valid.');
resolve();
}
});
});
eventPromises.push(txPromise);
});
var sendPromise = channel.sendTransaction(request);
var tCurr=new Date().getTime();
logger.info('[chaincodeInstantiate] Promise.all tCurr=%d', tCurr);
return Promise.all([sendPromise].concat(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();
throw new Error('Failed to send instantiate transaction and get notifications within the timeout period.');
});
} else {
logger.error('[chaincodeInstantiate] Failed to send instantiate Proposal or receive valid response. Response null or status is not 200. exiting...');
evtDisconnect();
throw new Error('Failed to send instantiate Proposal or receive valid response. Response null or status is not 200. exiting...');
}
},
function(err) {
logger.error('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err);
evtDisconnect();
throw new Error('Failed to send instantiate proposal due to error: ' + err.stack ? err.stack : err);
})
.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 code: ', Nid, channelName, response.status);
evtDisconnect();
}
}, (err) => {
logger.error('[chaincodeInstantiate(Nid=%d)] Failed to instantiate transaction on %s due to error: ', Nid, channelName, err.stack ? err.stack : err);
evtDisconnect();
}
);
}
function readAllFiles(dir) {
var files = fs.readdirSync(dir);
var certs = [];
files.forEach((file_name) => {
let file_path = path.resolve(dir,file_name);
logger.info('[readAllFiles] looking at file ::'+file_path);
let data = fs.readFileSync(file_path);
certs.push(data);
});
return certs;
}
//create channel
function createOneChannel(client ,channelOrgName) {
var config;
var envelope_bytes;
var signatures = [];
var key;
var username ;
var secret;
var submitter = null;
utils.setConfigSetting('key-value-store', 'fabric-client/lib/impl/FileKeyValueStore.js');
var channelTX=channelOpt.channelTX;
logger.info('[createOneChannel] channelTX: ', channelTX);
envelope_bytes = fs.readFileSync(channelTX);
config = client.extractChannelConfig(envelope_bytes);
logger.info('[createOneChannel] Successfull extracted the config update from the configtx envelope: ', channelTX);
clientNewOrderer(client, channelOrgName[0]);
hfc.newDefaultKeyValueStore({
path: testUtil.storePathForOrg(Nid, orgName)
}).then((store) => {
client.setStateStore(store);
var submitePromises= [];
channelOrgName.forEach((org) => {
submitter = new Promise(function (resolve,reject) {
username=ORGS[org].username;
secret=ORGS[org].secret;
orgName = ORGS[org].name;
logger.info('[createOneChannel] org= %s, org name= %s', org, orgName);
client._userContext = null;
resolve(testUtil.getSubmitter(username, secret, client, true, Nid, org, svcFile));
});
submitePromises.push(submitter);
});
// all the orgs
return Promise.all(submitePromises);
})
.then((results) => {
results.forEach(function(result){
var signature = client.signChannelConfig(config);
logger.info('[createOneChannel] Successfully signed config update for one organization ');
// collect signature from org1 admin
// TODO: signature counting against policies on the orderer
// at the moment is being investigated, but it requires this
// weird double-signature from each org admin
signatures.push(signature);
signatures.push(signature);
});
return signatures;
}).then((sigs) =>{
client._userContext = null;
return testUtil.getOrderAdminSubmitter(client, channelOrgName[0], svcFile);
}).then((admin) => {
the_user = admin;
logger.info('[createOneChannel] Successfully enrolled user \'admin\' for', "orderer");
var signature = client.signChannelConfig(config);
logger.info('[createOneChannel] Successfully signed config update: ', "orderer");
// collect signature from org1 admin
// TODO: signature counting against policies on the orderer
// at the moment is being investigated, but it requires this
// weird double-signature from each org admin
signatures.push(signature);
signatures.push(signature);
//logger.info('[createOneChannel] signatures: ', signatures);
logger.info('[createOneChannel] done signing: %s', channelName);
// build up the create request
let nonce = utils.getNonce();
let tx_id = client.newTransactionID();
var request = {
config: config,
signatures : signatures,
name : channelName,
orderer : orderer,
txId : tx_id,
nonce : nonce
};
//logger.info('request: ',request);
return client.createChannel(request);
}, (err) => {
logger.error('Failed to enroll user \'admin\'. ' + err);
evtDisconnect();
process.exit();
}).then((result) => {
logger.info('[createOneChannel] Successfully created the channel (%s).', channelName);
evtDisconnect();
process.exit();
}, (err) => {
logger.error('Failed to create the channel (%s) ', channelName);
logger.error('Failed to create the channel:: %j '+ err.stack ? err.stack : err);
evtDisconnect();
process.exit();
})
.then((nothing) => {
logger.info('Successfully waited to make sure new channel was created.');
evtDisconnect();
process.exit();
}, (err) => {
logger.error('Failed due to error: ' + err.stack ? err.stack : err);
evtDisconnect();
process.exit();
});
}
// join channel
function joinChannel(channel, client, org) {
orgName = ORGS[org].name;
logger.info('[joinChannel] Calling peers in organization (%s) to join the channel (%s)', orgName, channelName);
var username = ORGS[org].username;
var secret = ORGS[org].secret;
logger.info('[joinChannel] user=%s, secret=%s', username, secret);
var genesis_block = null;
// add orderers
chainAddOrderer(channel, client, org);
//printChainInfo(channel);
return hfc.newDefaultKeyValueStore({
path: testUtil.storePathForOrg(Nid, orgName)
}).then((store) => {
client.setStateStore(store);
client._userContext = null;
return testUtil.getOrderAdminSubmitter(client, org, svcFile)
}).then((admin) => {
logger.info('[joinChannel:%s] Successfully enrolled orderer \'admin\'', org);
the_user = admin;
logger.debug('[joinChannel] orderer admin: ', admin);
tx_id = client.newTransactionID();
var request = {
txId : tx_id
};
return channel.getGenesisBlock(request);
}).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, svcFile);
}).then((admin) => {
logger.info('[joinChannel] Successfully enrolled org:' + org + ' \'admin\'');
the_user = admin;
logger.debug('[joinChannel] org admin: ', admin);
// add peers and events
channelAddPeerEventJoin(channel, client, org);
var eventPromises = [];
eventHubs.forEach((eh) => {
let txPromise = new Promise((resolve, reject) => {
let handle = setTimeout(reject, 30000);
eh.registerBlockEvent((block) => {
clearTimeout(handle);
// in real-world situations, a peer may have more than one channels so
// we must check that this block came from the channel we asked the peer to join
if(block.data.data.length === 1) {
// Config block must only contain one transaction
var channel_header = block.data.data[0].payload.header.channel_header;
if (channel_header.channel_id === channelName) {
logger.info('[joinChannel] The new channel has been successfully joined on peer '+ eh.getPeerAddr());
resolve();
} else {
//logger.error('[joinChannel] The new channel has not been succesfully joined');
//reject();
}
}
}, (err) => {
logger.error('[joinChannel] Failed to registerBlockEvent due to error: ' + err.stack ? err.stack : err);