-
Notifications
You must be signed in to change notification settings - Fork 401
/
fabric.js
2115 lines (1779 loc) · 95.3 KB
/
fabric.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
/*
* 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.
*/
'use strict';
const FabricClient = require('fabric-client');
const FabricConstants = require('fabric-client/lib/Constants');
const {google, common} = require('fabric-protos');
const {ConnectorBase, CaliperUtils, TxStatus, Version, ConfigUtil} = require('@hyperledger/caliper-core');
const FabricNetwork = require('../../fabricNetwork.js');
const fs = require('fs');
const logger = CaliperUtils.getLogger('connectors/v1/fabric');
//////////////////////
// TYPE DEFINITIONS //
//////////////////////
/**
* @typedef {Object} EventSource
*
* @property {string[]} channel The list of channels this event source listens on. Only meaningful for Fabric v1.0.
* @property {string} peer The name of the peer the event source connects to.
* @property {EventHub|ChannelEventHub} eventHub The event hub object representing the connection.
*/
/////////////////////////////
// END OF TYPE DEFINITIONS //
/////////////////////////////
/**
* Extends {BlockchainConnector} for a Fabric backend, utilizing the SDK's Common Connection Profile.
*
* @property {Version} version Contains the version information about the used Fabric SDK.
* @property {Map<string, FabricClient>} clientProfiles Contains the initialized and user-specific SDK client profiles
* for each defined user. Maps the custom user names to the Client instances.
* @property {Map<string, FabricClient>} adminProfiles Contains the initialized and admin-specific SDK client profiles
* for each defined admin. Maps the custom organization names to the Client instances
* (since only one admin per org is supported).
* @property {Map<string, FabricClient>} registrarProfiles Contains the initialized and registrar-specific SDK client
* profiles for each defined registrar. Maps the custom organization names to the Client instances
* (since only one registrar per org is supported).
* @property {EventSource[]} eventSources Collection of potential event sources to listen to for transaction confirmation events.
* @property {number} workerIndex The index of the client process using the adapter that is set in the constructor
* @property {number} txIndex A counter for keeping track of the index of the currently submitted transaction.
* @property {FabricNetwork} networkUtil Utility object containing easy-to-query information about the topology
* and settings of the network.
* @property {Map<string, Map<string, Map<string, string[]>>>} randomTargetPeerCache Contains the target peers of contracts
* grouped by channels and organizations: Channel -> Contract -> Org -> Peers
* @property {Map<string, EventSource[]>} channelEventSourcesCache Contains the list of event sources for every channel.
* @property {Map<string, string[]>} randomTargetOrdererCache Contains the list of target orderers of channels.
* @property {string} defaultInvoker The name of the client to use if an invoker is not specified.
* @property {number} configSmallestTimeout The timeout value to use when the user-provided timeout is too small.
* @property {number} configSleepAfterCreateChannel The sleep duration in milliseconds after creating the channels.
* @property {number} configSleepAfterJoinChannel The sleep duration in milliseconds after joining the channels.
* @property {number} configSleepAfterInstantiateContract The sleep duration in milliseconds after instantiating the contracts.
* @property {boolean} configVerifyProposalResponse Indicates whether to verify the proposal responses of the endorsers.
* @property {boolean} configVerifyReadWriteSets Indicates whether to verify the matching of the returned read-write sets.
* @property {number} configLatencyThreshold The network latency threshold to use for calculating the final commit time of transactions.
* @property {boolean} configOverwriteGopath Indicates whether GOPATH should be set to the Caliper root directory.
* @property {number} configContractInstantiateTimeout The timeout in milliseconds for the contract instantiation endorsement.
* @property {number} configContractInstantiateEventTimeout The timeout in milliseconds for receiving the contract instantion event.
* @property {number} configDefaultTimeout The default timeout in milliseconds to use for invoke/query transactions.
* @property {string} configClientBasedLoadBalancing The value indicating the type of automatic load balancing to use.
* @property {boolean} configCountQueryAsLoad Indicates whether queries should be counted as workload.
*/
class LegacyV1Fabric extends ConnectorBase {
/**
* Initializes the Fabric adapter.
* @param {object} networkObject The parsed network configuration.
* @param {number} workerIndex the worker index
* @param {string} bcType The target SUT type
*/
constructor(networkObject, workerIndex, bcType) {
super(workerIndex, bcType);
this.version = new Version(require('fabric-client/package').version);
// clone the object to prevent modification by other objects
this.network = CaliperUtils.parseYamlString(CaliperUtils.stringifyYaml(networkObject));
this.clientProfiles = new Map();
this.adminProfiles = new Map();
this.registrarProfiles = new Map();
this.eventSources = [];
this.txIndex = -1;
this.randomTargetPeerCache = new Map();
this.channelEventSourcesCache = new Map();
this.randomTargetOrdererCache = new Map();
this.userContracts = new Map();
this.context = undefined;
// this value is hardcoded, if it's used, that means that the provided timeouts are not sufficient
this.configSmallestTimeout = 1000;
this.configSleepAfterCreateChannel = ConfigUtil.get(ConfigUtil.keys.Fabric.SleepAfter.CreateChannel, 5000);
this.configSleepAfterJoinChannel = ConfigUtil.get(ConfigUtil.keys.Fabric.SleepAfter.JoinChannel, 3000);
this.configSleepAfterInstantiateContract = ConfigUtil.get(ConfigUtil.keys.Fabric.SleepAfter.InstantiateContract, 5000);
this.configVerifyProposalResponse = ConfigUtil.get(ConfigUtil.keys.Fabric.Verify.ProposalResponse, true);
this.configVerifyReadWriteSets = ConfigUtil.get(ConfigUtil.keys.Fabric.Verify.ReadWriteSets, true);
this.configLatencyThreshold = ConfigUtil.get(ConfigUtil.keys.Fabric.LatencyThreshold, 1.0);
this.configOverwriteGopath = ConfigUtil.get(ConfigUtil.keys.Fabric.OverwriteGopath, true);
this.configContractInstantiateTimeout = ConfigUtil.get(ConfigUtil.keys.Fabric.Timeout.ContractInstantiate, 300000);
this.configContractInstantiateEventTimeout = ConfigUtil.get(ConfigUtil.keys.Fabric.Timeout.ContractInstantiateEvent, 300000);
this.configDefaultTimeout = ConfigUtil.get(ConfigUtil.keys.Fabric.Timeout.InvokeOrQuery, 60);
this.configClientBasedLoadBalancing = ConfigUtil.get(ConfigUtil.keys.Fabric.LoadBalancing, 'client') === 'client';
this.configCountQueryAsLoad = ConfigUtil.get(ConfigUtil.keys.Fabric.CountQueryAsLoad, true);
this.networkUtil = new FabricNetwork(this.network);
this.defaultInvoker = Array.from(this.networkUtil.getClients())[0];
// NOTE: regardless of the version of the Fabric backend, the SDK must be at least v1.1.0 in order to
// use the common connection profile feature
if (this.version.lessThan('1.1.0')) {
throw new Error(`Fabric SDK ${this.version.toString()} is not supported, use at least version 1.1.0`);
}
if (this.networkUtil.isInCompatibilityMode() && this.version.greaterThan('1.1.0')) {
throw new Error(`Fabric 1.0 compatibility mode is detected, but SDK version ${this.version.toString()} is used`);
}
this._prepareCaches();
}
//////////////////////////
// PUBLIC API FUNCTIONS //
//////////////////////////
/**
* Initializes the Fabric adapter: sets up clients, admins, registrars, channels and contracts.
* @param {boolean} workerInit Indicates whether the initialization happens in the worker process.
* @async
*/
async init(workerInit = false) {
const tlsInfo = this.networkUtil.isMutualTlsEnabled() ? 'mutual'
: (this.networkUtil.isTlsEnabled() ? 'server' : 'none');
const compMode = this.networkUtil.isInCompatibilityMode() ? '; Fabric v1.0 compatibility mode' : '';
logger.info(`Fabric SDK version: ${this.version.toString()}; TLS: ${tlsInfo}${compMode}`);
// TODO: only required for specific scenarios, means network config has to have more info defined
await this._initializeRegistrars(workerInit);
await this._initializeAdmins(workerInit);
await this._initializeUsers(workerInit);
this.initPhaseCompleted = true;
if (!workerInit) {
if (await this._createChannels()) {
logger.info(`Sleeping ${this.configSleepAfterCreateChannel / 1000.0}s...`);
await CaliperUtils.sleep(this.configSleepAfterCreateChannel);
}
if (await this._joinChannels()) {
logger.info(`Sleeping ${this.configSleepAfterJoinChannel / 1000.0}s...`);
await CaliperUtils.sleep(this.configSleepAfterJoinChannel);
}
}
}
/**
* Prepares the adapter by loading user data and connection to the event hubs.
*
* @param {Number} roundIndex The zero-based round index of the test.
* @param {Array<string>} args Unused.
* @return {Promise<{networkInfo : FabricNetwork, eventSources: EventSource[]}>} Returns the network utility object.
* @async
*/
async getContext(roundIndex, args) {
// Reset counter for new test round
this.txIndex = -1;
if (!this.context) {
this.context = {
networkInfo: this.networkUtil,
clientIdx: this.workerIndex
};
await this._initializeChannelsAndEventHubs();
}
return this.context;
}
/**
* Releases the resources of the adapter.
* @async
*/
async releaseContext() {
this.eventSources.forEach((es) => {
if (es.eventHub.isconnected()) {
es.eventHub.disconnect();
}
});
this.eventSources = [];
this.context = undefined;
}
/**
* Installs and initializes the specified contracts.
* @async
*/
async installSmartContract() {
// With flow conditioning, this phase is conditionally required
if (!this.initPhaseCompleted ) {
await this._initializeRegistrars(true);
await this._initializeAdmins(true);
await this._initializeUsers(true);
}
await this._installContracts();
if (await this._instantiateContracts()) {
logger.info(`Sleeping ${this.configSleepAfterInstantiateContract / 1000.0}s...`);
await CaliperUtils.sleep(this.configSleepAfterInstantiateContract);
}
}
////////////////////////////////
// INTERNAL UTILITY FUNCTIONS //
////////////////////////////////
/**
* Assembles the event sources based on explicitly given target peers.
* @param {string} channel The name of channel containing the target peers. Doesn't matter if peer-level event service is used in compatibility mode.
* @param {string[]} targetPeers The list of peers to connect to.
* @return {EventSource[]} The list of event sources.
* @private
*/
_assembleTargetEventSources(channel, targetPeers) {
const eventSources = [];
if (this.networkUtil.isInCompatibilityMode()) {
// NOTE: for old event hubs we have a single connection to every peer set as an event source
const EventHub = require('fabric-client/lib/EventHub.js');
for (const peer of targetPeers) {
const org = this.networkUtil.getOrganizationOfPeer(peer);
const admin = this.adminProfiles.get(org);
const eventHub = new EventHub(admin);
eventHub.setPeerAddr(this.networkUtil.getPeerEventUrl(peer),
this.networkUtil.getGrpcOptionsOfPeer(peer));
eventSources.push({
channel: [channel], // unused during contract instantiation
peer: peer,
eventHub: eventHub
});
}
} else {
for (const peer of targetPeers) {
const org = this.networkUtil.getOrganizationOfPeer(peer);
const admin = this.adminProfiles.get(org);
const eventHub = admin.getChannel(channel, true).newChannelEventHub(peer);
eventSources.push({
channel: [channel], // unused during contract instantiation
peer: peer,
eventHub: eventHub
});
}
}
return eventSources;
}
/**
* Collects all peers that are endorsing peers belonging to a set of organizations
* @param {*} channel The name of the channel
* @param {string[]} endorsingOrgs An array of the required orgs to target
* @returns {ChannelPeer[]} Array containing the set of peers
*/
_getEndorsingPeersForOrgs(channel, endorsingOrgs) {
const channelPeers = channel.getChannelPeers();
const filteredPeers = channelPeers.filter((channelPeer) => {
return channelPeer.isInRole(FabricConstants.NetworkConfig.ENDORSING_PEER_ROLE) &&
endorsingOrgs.some((org) => channelPeer.isInOrg(org));
});
return filteredPeers;
}
/**
* Assembles random target peers for the channel from every organization that has the contract deployed.
* @param {string} channel The name of the channel.
* @param {string} contractId The name/ID of the contract.
* @param {string} contractVersion The version of the contract.
* @returns {string[]} Array containing a random peer from each needed organization.
* @private
*/
_assembleRandomTargetPeers(channel, contractId, contractVersion) {
const targets = [];
const contractOrgs = this.randomTargetPeerCache.get(channel).get(`${contractId}@${contractVersion}`);
for (const entries of contractOrgs.entries()) {
const peers = entries[1];
// represents the load balancing mechanism
const loadBalancingCounter = this.configClientBasedLoadBalancing ? this.workerIndex : this.txIndex;
targets.push(peers[loadBalancingCounter % peers.length]);
}
return targets;
}
/**
* Creates the specified channels if necessary.
* @return {boolean} True, if at least one channel was created. Otherwise, false.
* @private
* @async
*/
async _createChannels() {
const channels = this.networkUtil.getChannels();
let channelCreated = false;
for (const channel of channels) {
const channelObject = this.networkUtil.getNetworkObject().channels[channel];
if (CaliperUtils.checkProperty(channelObject, 'created') && channelObject.created) {
logger.info(`Channel '${channel}' is configured as created, skipping creation`);
continue;
}
if (ConfigUtil.get(ConfigUtil.keys.Fabric.SkipCreateChannelPrefix + channel, false)) {
logger.info(`Creation of Channel '${channel}' is configured to skip`);
continue;
}
channelCreated = true;
let configUpdate;
if (CaliperUtils.checkProperty(channelObject, 'configBinary')) {
logger.info(`Channel '${channel}' definiton being retrieved from file`);
configUpdate = this._getChannelConfigFromFile(channelObject, channel);
}
else {
logger.info(`Channel '${channel}' definiton being generated from description`);
const channelTx = this._createChannelTxEnvelope(channelObject.definition, channel);
const payload = common.Payload.decode(channelTx.getPayload().toBuffer());
const configtx = common.ConfigUpdateEnvelope.decode(payload.getData().toBuffer());
configUpdate = configtx.getConfigUpdate().toBuffer();
}
// NOTE: without knowing the system channel policies, signing with every org admin is a safe bet
const orgs = this.networkUtil.getOrganizationsOfChannel(channel);
let admin; // declared here to keep the admin of the last org of the channel
const signatures = [];
for (const org of orgs) {
admin = this.adminProfiles.get(org);
try {
signatures.push(admin.signChannelConfig(configUpdate));
} catch (err) {
throw new Error(`${org}'s admin couldn't sign the configuration update of Channel '${channel}': ${err.message}`);
}
}
const txId = admin.newTransactionID(true);
const request = {
config: configUpdate,
signatures: signatures,
name: channel,
txId: txId
};
try {
/** @link{BroadcastResponse} */
const broadcastResponse = await admin.createChannel(request);
CaliperUtils.assertDefined(broadcastResponse, `The returned broadcast response for creating Channel '${channel}' is undefined`);
CaliperUtils.assertProperty(broadcastResponse, 'broadcastResponse', 'status');
if (broadcastResponse.status !== 'SUCCESS') {
throw new Error(`Orderer response indicated unsuccessful Channel '${channel}' creation: ${broadcastResponse.status}`);
}
} catch (err) {
throw new Error(`Couldn't create Channel '${channel}': ${err.message}`);
}
logger.info(`Channel '${channel}' successfully created`);
}
return channelCreated;
}
/**
*
* @param {EventSource} eventSource The event source to use for registering the Tx event.
* @param {string} txId The transaction ID.
* @param {TxStatus} invokeStatus The transaction status object.
* @param {number} startTime The epoch of the transaction start time.
* @param {number} timeout The timeout for the transaction life-cycle.
* @return {Promise<{successful: boolean, message: string, time: number}>} The details of the event notification.
* @private
*/
_createEventRegistrationPromise(eventSource, txId, invokeStatus, startTime, timeout) {
return new Promise(resolve => {
const handle = setTimeout(() => {
// give the other event hub connections a chance
// to verify the Tx status, so resolve the promise
eventSource.eventHub.unregisterTxEvent(txId);
const time = Date.now();
invokeStatus.Set(`commit_timeout_${eventSource.peer}`, 'TIMEOUT');
// resolve the failed transaction with the current time and error message
resolve({
successful: false,
message: `Commit timeout on ${eventSource.peer} for transaction ${txId}`,
time: time
});
}, this._getRemainingTimeout(startTime, timeout));
eventSource.eventHub.registerTxEvent(txId, (tx, code) => {
clearTimeout(handle);
const time = Date.now();
eventSource.eventHub.unregisterTxEvent(txId);
// either explicit invalid event or valid event, verified in both cases by at least one peer
// TODO: what about when a transient error occurred on a peer?
invokeStatus.SetVerification(true);
if (code !== 'VALID') {
invokeStatus.Set(`commit_error_${eventSource.peer}`, code);
resolve({
successful: false,
message: `Commit error on ${eventSource.peer} with code ${code}`,
time: time
});
} else {
invokeStatus.Set(`commit_success_${eventSource.peer}`, time);
resolve({
successful: true,
message: 'undefined',
time: time
});
}
}, (err) => {
clearTimeout(handle);
eventSource.eventHub.unregisterTxEvent(txId);
const time = Date.now();
// we don't know what happened, but give the other event hub connections a chance
// to verify the Tx status, so resolve this promise
invokeStatus.Set(`event_hub_error_${eventSource.peer}`, err.message);
resolve({
successful: false,
message: `Event hub error on ${eventSource.peer}: ${err.message}`,
time: time
});
});
});
}
/**
* Creates and sets a User object as the context based on the provided identity information.
* @param {Client} profile The Client object whose user context must be set.
* @param {string} org The name of the user's organization.
* @param {string} userName The name of the user.
* @param {{privateKeyPEM: Buffer, signedCertPEM: Buffer}} cryptoContent The object containing the signing key and cert in PEM format.
* @param {string} profileName Optional name of the profile that will appear in error messages.
* @returns {FabricClient.User} The User object created
* @private
* @async
*/
async _createUser(profile, org, userName, cryptoContent, profileName) {
// set the user explicitly based on its crypto materials
// createUser also sets the user context
try {
return await profile.createUser({
username: userName,
mspid: this.networkUtil.getMspIdOfOrganization(org),
cryptoContent: cryptoContent,
skipPersistence: true
});
} catch (err) {
throw new Error(`Couldn't create ${profileName || ''} user object: ${err.message}`);
}
}
/**
* Enrolls the given user through its corresponding CA.
* @param {Client} profile The Client object whose user must be enrolled.
* @param {string} id The enrollment ID.
* @param {string} secret The enrollment secret.
* @param {string} profileName Optional name of the profile that will appear in error messages.
* @return {Promise<{key: ECDSA_KEY, certificate: string}>} The resulting private key and certificate.
* @private
* @async
*/
async _enrollUser(profile, id, secret, profileName) {
// this call will throw an error if the CA configuration is not found
// this error should propagate up
const ca = profile.getCertificateAuthority();
try {
return await ca.enroll({
enrollmentID: id,
enrollmentSecret: secret
});
} catch (err) {
throw new Error(`Couldn't enroll ${profileName || 'user'}: ${err.message}`);
}
}
/**
* Populate an envelope with a channel creation transaction
* @param {object} channelObject The channel configuration object.
* @param {string} channelName The name of the channel.
* @return {Buffer} The extracted channel configuration bytes.
* @private
*/
_createChannelTxEnvelope(channelObject, channelName) {
// Versioning
const readVersion = 0;
const writeVersion = 0;
const appVersion = 1;
const policyVersion = 0;
// Build the readSet
const readValues = {};
readValues.Consortium = new common.ConfigValue();
const readAppGroup = {};
for (const mspId of channelObject.msps) {
readAppGroup[mspId] = new common.ConfigGroup();
}
const readGroups = {};
readGroups.Application = new common.ConfigGroup({ groups: readAppGroup });
const readSet = new common.ConfigGroup({ version: readVersion, groups: readGroups, values: readValues });
// Build the writeSet (based on consortium name and passed Capabiliites)
const modPolicy = 'Admins';
const writeValues = {};
const consortium = new common.Consortium({ name: channelObject.consortium });
writeValues.Consortium = new common.ConfigValue({ version: writeVersion, value: consortium.toBuffer() });
if (channelObject.capabilities) {
const capabilities = this._populateCapabilities(channelObject.capabilities);
writeValues.Capabilities = new common.ConfigValue({ version: writeVersion, value: capabilities.toBuffer(), mod_policy: modPolicy });
}
// Write Policy
const writePolicies = this._generateWritePolicy(policyVersion, modPolicy);
// Write Application Groups
const writeAppGroup = {};
for (const mspId of channelObject.msps) {
writeAppGroup[mspId] = new common.ConfigGroup();
}
const writeGroups = {};
writeGroups.Application = new common.ConfigGroup({ version: appVersion, groups: writeAppGroup, policies: writePolicies, mod_policy: modPolicy });
const writeSet = new common.ConfigGroup({ version: writeVersion, groups: writeGroups, values: writeValues });
// Now create the configUpdate and configUpdateEnv
const configUpdate = new common.ConfigUpdate({ channel_id: channelName, read_set: readSet, write_set: writeSet});
const configUpdateEnv= new common.ConfigUpdateEnvelope({ config_update: configUpdate.toBuffer(), signatures: [] });
// Channel header
const channelTimestamp = new google.protobuf.Timestamp({ seconds: Date.now()/1000, nanos: 0 }); // Date.now() is millis since 1970 epoch, we need seconds
const channelEpoch = 0;
const chHeader = new common.ChannelHeader({ type: common.HeaderType.CONFIG_UPDATE, version: channelObject.version, timestamp: channelTimestamp, channel_id: channelName, epoch: channelEpoch });
// Common header
const header = new common.Header({ channel_header: chHeader.toBuffer() });
// Form the payload header/data
const payload = new common.Payload({ header: header, data: configUpdateEnv.toBuffer() });
// Form and return the envelope
const envelope = new common.Envelope({ payload: payload.toBuffer() });
return envelope;
}
/**
* Populate a Capabilities protobuf
* @param {Array<string>} applicationCapabilities the application capability keys
* @returns {common.Capabilities} Capabilities in a protobuff
*/
_populateCapabilities(applicationCapabilities) {
const capabilities = {};
for (const capability of applicationCapabilities) {
capabilities[capability] = new common.Capability();
}
return new common.Capabilities({ capabilities: capabilities });
}
/**
* Form a populted Poicy protobuf that contains an ImplicitMetaPolicy
* @param {String} subPolicyName the sub policy name
* @param {common.Policy.PolicyType} rule the rule type
* @returns {common.Policy} the policy protobuf
*/
_makeImplicitMetaPolicy(subPolicyName, rule){
const metaPolicy = new common.ImplicitMetaPolicy({ sub_policy: subPolicyName, rule: rule });
const policy= new common.Policy({ type: common.Policy.PolicyType.IMPLICIT_META, value: metaPolicy.toBuffer() });
return policy;
}
/**
* Generate a write policy
* @param {number} version the policy version
* @param {string} modPolicy the modification policy
* @returns {Object} an object of Admin/Reader/Writer keys mapping to populated ConfigPolicy protobuffs
*/
_generateWritePolicy(version, modPolicy) {
// Write Policy
const writePolicies = {};
// admins
const adminsPolicy = this._makeImplicitMetaPolicy('Admins', common.ImplicitMetaPolicy.Rule.MAJORITY); // majority
writePolicies.Admins = new common.ConfigPolicy({ version: version, policy: adminsPolicy, mod_policy: modPolicy });
// Readers
const readersPolicy = this._makeImplicitMetaPolicy('Readers', common.ImplicitMetaPolicy.Rule.ANY); // Any
writePolicies.Readers = new common.ConfigPolicy({ version: version, policy: readersPolicy, mod_policy: modPolicy });
// Writers
const writersPolicy = this._makeImplicitMetaPolicy('Writers', common.ImplicitMetaPolicy.Rule.ANY); // Any
writePolicies.Writers = new common.ConfigPolicy({ version: version, policy: writersPolicy, mod_policy: modPolicy });
return writePolicies;
}
/**
* Extracts the channel configuration from the configured file.
* @param {object} channelObject The channel configuration object.
* @param {string} channelName The name of the channel.
* @return {Buffer} The extracted channel configuration bytes.
* @private
*/
_getChannelConfigFromFile(channelObject, channelName) {
// extracting the config from the binary file
const binaryPath = CaliperUtils.resolvePath(channelObject.configBinary);
let envelopeBytes;
try {
envelopeBytes = fs.readFileSync(binaryPath);
} catch (err) {
throw new Error(`Couldn't read configuration binary for ${channelName}: ${err.message}`);
}
try {
return new FabricClient().extractChannelConfig(envelopeBytes);
} catch (err) {
throw new Error(`Couldn't extract configuration object for ${channelName}: ${err.message}`);
}
}
/**
* Gets a random target orderer for the given channel.
* @param {string} channel The name of the channel.
* @return {string} The name of the target orderer.
* @private
*/
_getRandomTargetOrderer(channel) {
const orderers = this.randomTargetOrdererCache.get(channel);
// represents the load balancing mechanism
const loadBalancingCounter = this.configClientBasedLoadBalancing ? this.workerIndex : this.txIndex;
return orderers[loadBalancingCounter % orderers.length];
}
/**
* Calculates the remaining time to timeout based on the original timeout and a starting time.
* @param {number} start The epoch of the start time in ms.
* @param {number} original The original timeout in ms.
* @returns {number} The remaining time until the timeout in ms.
* @private
*/
_getRemainingTimeout(start, original) {
let newTimeout = original - (Date.now() - start);
if (newTimeout < this.configSmallestTimeout) {
logger.warn(`Timeout is too small, default value of ${this.configSmallestTimeout}ms is used instead`);
newTimeout = this.configSmallestTimeout;
}
return newTimeout;
}
/**
* Checks whether the user materials are already persisted in the local store and sets the user context if found.
* @param {Client} profile The Client object to fill with the User instance.
* @param {string} userName The name of the user to check and load.
* @param {string} profileName Optional name of the profile that will appear in error messages.
* @return {Promise<User>} The loaded User object
* @private
* @async
*/
async _getUserContext(profile, userName, profileName) {
// Check whether the materials are already saved
// getUserContext automatically sets the user if found
try {
return await profile.getUserContext(userName, true);
} catch (err) {
throw new Error(`Couldn't check whether ${profileName || 'the user'}'s materials are available locally: ${err.message}`);
}
}
/**
* Initializes the admins of the organizations.
*
* @param {boolean} workerInit Indicates whether the initialization happens in the worker process.
* @private
* @async
*/
async _initializeAdmins(workerInit) {
const orgs = this.networkUtil.getOrganizations();
for (const org of orgs) {
const adminName = `admin.${org}`;
// build the common part of the profile
const adminProfile = await this._prepareClientProfile(org, undefined, `${org}'s admin`);
// Check if the materials already exist locally in file system key-value stores.
const admin = await this._getUserContext(adminProfile, adminName, `${org}'s admin`);
if (admin) {
this.adminProfiles.set(org, adminProfile);
if (this.networkUtil.isMutualTlsEnabled()) {
this._setTlsAdminCertAndKey(org);
}
if (!workerInit) {
logger.warn(`${org}'s admin's materials found locally in file system key-value stores. Make sure it is the right one!`);
}
continue;
}
// Set the admin explicitly based on its crypto materials either provided in the connection profile
const cryptoContent = this.networkUtil.getAdminCryptoContentOfOrganization(org);
await this._createUser(adminProfile, org, adminName, cryptoContent,`${org}'s admin`);
this.adminProfiles.set(org, adminProfile);
if (this.networkUtil.isMutualTlsEnabled()) {
this._setTlsAdminCertAndKey(org);
}
logger.info(`${org}'s admin's materials are successfully loaded`);
}
}
/**
* Initializes the given channel of every client profile to be able to verify proposal responses.
* @param {Map<string, FabricClient>} profiles The collection of client profiles.
* @param {string} channel The name of the channel to initialize.
* @param {boolean} admin Indicates whether the profiles are admin profiles.
* @private
* @async
*/
async _initializeChannel(profiles, channel, admin) {
// initialize the channel for every client profile from the local config
for (const profile of profiles.entries()) {
const profileOrg = admin ? profile[0] : this.networkUtil.getOrganizationOfClient(profile[0]);
const channelOrgs = this.networkUtil.getOrganizationsOfChannel(channel);
// skip init for profiles whose org is a not a member of the channel
if (!channelOrgs.has(profileOrg)) {
continue;
}
const ch = profile[1].getChannel(channel, false);
if (ch) {
try {
await ch.initialize();
} catch (err) {
logger.error(`Couldn't initialize ${channel} for ${profile[0]}: ${err.message}`);
throw err;
}
}
}
}
/**
* Initializes the registrars of the organizations.
*
* @param {boolean} workerInit Indicates whether the initialization happens in the worker process.
* @private
* @async
*/
async _initializeRegistrars(workerInit) {
const orgs = this.networkUtil.getOrganizations();
for (const org of orgs) {
// providing registrar information is optional and only needed for user registration and enrollment
const registrarInfo = this.networkUtil.getRegistrarOfOrganization(org);
if (!registrarInfo) {
if (!workerInit) {
logger.warn(`${org}'s registrar information not provided.`);
}
continue;
}
// build the common part of the profile
const registrarProfile = await this._prepareClientProfile(org, undefined, 'registrar');
// check if the materials already exist locally in the file system key-value stores
const registrar = await this._getUserContext(registrarProfile, registrarInfo.enrollId, `${org}'s registrar`);
if (registrar) {
if (!workerInit) {
logger.warn(`${org}'s registrar's materials found locally in file system key-value stores. Make sure it is the right one!`);
}
this.registrarProfiles.set(org, registrarProfile);
continue;
}
// set the registrar identity as the current user context
await this._setUserContextByEnrollment(registrarProfile, registrarInfo.enrollId,
registrarInfo.enrollSecret, `${org}'s registrar`);
this.registrarProfiles.set(org, registrarProfile);
if (!workerInit) {
logger.info(`${org}'s registrar enrolled successfully`);
}
}
}
/**
* Registers and enrolls the specified users if necessary.
*
* @param {boolean} workerInit Indicates whether the initialization happens in the worker process.
* @private
* @async
*/
async _initializeUsers(workerInit) {
const clients = this.networkUtil.getClients();
// register and enroll each client with its organization's CA
for (const client of clients) {
const org = this.networkUtil.getOrganizationOfClient(client);
// create the profile based on the connection profile
const clientProfile = await this._prepareClientProfile(org, client, client);
this.clientProfiles.set(client, clientProfile);
// check if the materials already exist locally in the file system key-value stores
const user = await this._getUserContext(clientProfile, client, client);
if (user) {
if (this.networkUtil.isMutualTlsEnabled()) {
// "retrieve" and set the deserialized cert and key
clientProfile.setTlsClientCertAndKey(user.getIdentity()._certificate, user.getSigningIdentity()._signer._key.toBytes());
}
if (!workerInit) {
logger.warn(`${client}'s materials found locally in file system key-value stores. Make sure it is the right one!`);
}
continue;
}
const cryptoContent = this.networkUtil.getClientCryptoContent(client);
if (cryptoContent) {
// the client is already enrolled, just create and persist the User object
await this._createUser(clientProfile, org, client, cryptoContent, client);
if (this.networkUtil.isMutualTlsEnabled()) {
// the materials are included in the configuration file
const crypto = this.networkUtil.getClientCryptoContent(client);
clientProfile.setTlsClientCertAndKey(crypto.signedCertPEM.toString(), crypto.privateKeyPEM.toString());
}
if (!workerInit) {
logger.info(`${client}'s materials are successfully loaded`);
}
continue;
}
// The user needs to be enrolled or even registered
// if the enrollment ID and secret is provided, then enroll the already registered user
const enrollmentSecret = this.networkUtil.getClientEnrollmentSecret(client);
if (enrollmentSecret) {
const enrollment = await this._enrollUser(clientProfile, client, enrollmentSecret, client);
// create the new user based on the retrieved materials
await this._createUser(clientProfile, org, client,
{
privateKeyPEM: enrollment.key.toBytes(),
signedCertPEM: Buffer.from(enrollment.certificate)
}, client);
if (this.networkUtil.isMutualTlsEnabled()) {
// set the received cert and key for mutual TLS
clientProfile.setTlsClientCertAndKey(Buffer.from(enrollment.certificate).toString(), enrollment.key.toString());
}
if (!workerInit) {
logger.info(`${client} successfully enrolled`);
}
continue;
}
// Otherwise, register then enroll the user
let secret;
try {
const registrarProfile = this.registrarProfiles.get(org);
if (!registrarProfile) {
throw new Error(`Registrar identity is not provided for ${org}`);
}
const registrarInfo = this.networkUtil.getRegistrarOfOrganization(org);
const registrar = await registrarProfile.getUserContext(registrarInfo.enrollId, true);
// this call will throw an error if the CA configuration is not found
// this error should propagate up
const ca = clientProfile.getCertificateAuthority();
const userAffiliation = this.networkUtil.getAffiliationOfUser(client);
// if not in compatibility mode (i.e., at least SDK v1.1), check whether the affiliation is already registered or not
if (!this.networkUtil.isInCompatibilityMode()) {
const affService = ca.newAffiliationService();
let affiliationExists = false;
try {
await affService.getOne(userAffiliation, registrar);
affiliationExists = true;
} catch (err) {
if (!workerInit) {
logger.info(`${userAffiliation} affiliation doesn't exists`);
}
}
if (!affiliationExists) {
await affService.create({name: userAffiliation, force: true}, registrar);
if (!workerInit) {
logger.info(`${userAffiliation} affiliation added`);
}
}
}
const attributes = this.networkUtil.getAttributesOfUser(client);
attributes.push({name: 'hf.Registrar.Roles', value: 'client'});
secret = await ca.register({
enrollmentID: client,
affiliation: userAffiliation,
role: 'client',
attrs: attributes
}, registrar);
} catch (err) {
throw new Error(`Couldn't register ${client}: ${err.message}`);
}
if (!workerInit) {
logger.info(`${client} successfully registered`);
}
const enrollment = await this._enrollUser(clientProfile, client, secret, client);
// create the new user based on the retrieved materials
await this._createUser(clientProfile, org, client,
{privateKeyPEM: enrollment.key.toBytes(), signedCertPEM: Buffer.from(enrollment.certificate)}, client);
if (this.networkUtil.isMutualTlsEnabled()) {
// set the received cert and key for mutual TLS
clientProfile.setTlsClientCertAndKey(Buffer.from(enrollment.certificate).toString(), enrollment.key.toString());
//this._setTlsClientCertAndKey(client);
}
if (!workerInit) {
logger.info(`${client} successfully enrolled`);
}
}
}
/**
* Install the specified contracts to their target peers.
* @private
* @async
*/
async _installContracts() {
if (this.configOverwriteGopath) {
process.env.GOPATH = CaliperUtils.resolvePath('.');
}
const errors = [];
const channels = this.networkUtil.getChannels();
for (const channel of channels) {
logger.info(`Installing contracts for ${channel}...`);
// proceed cc by cc for the channel
const contractInfos = this.networkUtil.getContractsOfChannel(channel);
for (const contractInfo of contractInfos) {
const ccObject = this.networkUtil.getNetworkObject().channels[channel].contracts.find(
cc => cc.id === contractInfo.id && cc.version === contractInfo.version);
const targetPeers = this.networkUtil.getTargetPeersOfContractOfChannel(contractInfo, channel);