/
Channel.js
executable file
·2349 lines (2154 loc) · 90.8 KB
/
Channel.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, 2017 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.
*/
'use strict';
var utils = require('./utils.js');
var clientUtils = require('./client-utils.js');
var util = require('util');
var path = require('path');
var ChannelEventHub = require('./ChannelEventHub.js');
var BlockDecoder = require('./BlockDecoder.js');
var TransactionID = require('./TransactionID.js');
var grpc = require('grpc');
var logger = utils.getLogger('Channel.js');
var MSPManager = require('./msp/msp-manager.js');
var Policy = require('./Policy.js');
var Constants = require('./Constants.js');
var _ccProto = grpc.load(__dirname + '/protos/peer/chaincode.proto').protos;
var _transProto = grpc.load(__dirname + '/protos/peer/transaction.proto').protos;
var _proposalProto = grpc.load(__dirname + '/protos/peer/proposal.proto').protos;
var _responseProto = grpc.load(__dirname + '/protos/peer/proposal_response.proto').protos;
var _queryProto = grpc.load(__dirname + '/protos/peer/query.proto').protos;
var _peerConfigurationProto = grpc.load(__dirname + '/protos/peer/configuration.proto').protos;
var _commonProto = grpc.load(__dirname + '/protos/common/common.proto').common;
var _configtxProto = grpc.load(__dirname + '/protos/common/configtx.proto').common;
var _policiesProto = grpc.load(__dirname + '/protos/common/policies.proto').common;
var _ledgerProto = grpc.load(__dirname + '/protos/common/ledger.proto').common;
var _commonConfigurationProto = grpc.load(__dirname + '/protos/common/configuration.proto').common;
var _ordererConfigurationProto = grpc.load(__dirname + '/protos/orderer/configuration.proto').orderer;
var _abProto = grpc.load(__dirname + '/protos/orderer/ab.proto').orderer;
var _mspConfigProto = grpc.load(__dirname + '/protos/msp/msp_config.proto').msp;
var _mspPrincipalProto = grpc.load(__dirname + '/protos/msp/msp_principal.proto').common;
var _identityProto = grpc.load(path.join(__dirname, '/protos/msp/identities.proto')).msp;
const ImplicitMetaPolicy_Rule = { 0: 'ANY', 1: 'ALL', 2: 'MAJORITY' };
/**
* In fabric v1.0, channels are the recommended way to isolate data and maintain privacy.
* <br><br>
* A Channel object captures the settings needed to interact with a fabric backend in the
* context of a channel. These settings including the list of participating organizations,
* represented by instances of Membership Service Providers (MSP), the list of endorsing peers,
* and an orderer.
* <br><br>
* A client application can use the Channel object to create new channels with the orderer,
* update an existing channel, send various channel-aware requests to the peers such as
* invoking chaincodes to process transactions or queries.
* <br><br>
* A Channel object is also responsible for verifying endorsement signatures in transaction
* proposal responses. A channel object must be initialized after it has been configured with
* the list of peers and orderers. The initialization sends a get configuration block request
* to the primary orderer to retrieve the configuration settings for this channel.
*
* @class
*/
var Channel = class {
/**
* Returns a new instance of the class. This is a client-side-only call. To create a new channel
* in the fabric, call [createChannel()]{@link Client#createChannel}.
*
* @param {string} name - Name to identify the channel. This value is used as the identifier
* of the channel when making channel-aware requests with the fabric,
* such as invoking chaincodes to endorse transactions. The naming of
* channels is enforced by the ordering service and must be unique within
* the fabric backend
* @param {Client} clientContext - The client instance, which provides operational context
* such as the signing identity
*/
constructor(name, clientContext) {
// name is required
if (typeof name === 'undefined' || !name) {
logger.error('Failed to create Channel. Missing requirement "name" parameter.');
throw new Error('Failed to create Channel. Missing requirement "name" parameter.');
}
if (typeof clientContext === 'undefined' || !clientContext) {
logger.error('Failed to create Channel. Missing requirement "clientContext" parameter.');
throw new Error('Failed to create Channel. Missing requirement "clientContext" parameter.');
}
this._name = name;
this._peers = [];
this._anchor_peers = [];
this._orderers = [];
this._kafka_brokers = [];
this._clientContext = clientContext;
this._msp_manager = new MSPManager();
//to do update logger
logger.debug('Constructed Channel instance: name - %s, ' +
'network mode: %s',
this._name,
!this._devMode);
}
/**
* Close the service connection off all assigned peers and orderers
*/
close() {
logger.info('close - closing connections');
var closer = function (ep) {
ep.close();
};
this._peers.map(closer);
this._orderers.map(closer);
}
/**
* Initializes the channel object with the Membership Service Providers (MSPs). The channel's
* MSPs are critical in providing applications the ability to validate certificates and verify
* signatures in messages received from the fabric backend. For instance, after calling
* [sendTransactionProposal()]{@link Channel#sendTransactionProposal}, the application can
* verify the signatures in the proposal response's endorsements to ensure they have not been
* tampered with.
* <br><br>
* This method retrieves the configuration from the orderer if no "config" parameter is passed in.
* Optionally a configuration may be passed in to initialize this channel without making the call
* to the orderer.
*
* @param {byte[]} config - Optional. An encoded (a.k.a un-decoded) byte array of the protobuf "ConfigUpdate"
* @return {Promise} A Promise that will resolve when the action is complete
*/
initialize(config_update) {
if (config_update) {
this.loadConfigUpdate(config_update);
return Promise.resolve(true);
}
var self = this;
return this.getChannelConfig()
.then(
function (config_envelope) {
logger.debug('initialize - got config envelope from getChannelConfig :: %j', config_envelope);
var config_items = self.loadConfigEnvelope(config_envelope);
return Promise.resolve(config_items);
}
)
.catch(
function (error) {
logger.error('initialize - system error ::' + error.stack ? error.stack : error);
return Promise.reject(new Error(error));
}
);
}
/**
* Get the channel name.
* @returns {string} The name of the channel.
*/
getName() {
return this._name;
}
/**
* Get organization identifiers from the MSP's for this channel
* @returns {string[]} Array of MSP identifiers representing the channel's
* participating organizations
*/
getOrganizations() {
logger.debug('getOrganizationUnits - start');
var msps = this._msp_manager.getMSPs();
var orgs = [];
if (msps) {
var keys = Object.keys(msps);
for (var key in keys) {
var msp = msps[keys[key]];
var msp_org = { id: msp.getId() };
logger.debug('getOrganizationUnits - found %j', msp_org);
orgs.push(msp_org);
}
}
logger.debug('getOrganizationUnits - orgs::%j', orgs);
return orgs;
}
/**
* Set the MSP Manager for this channel. This utility method will
* not normally be use as the [initialize()]{@link Channel#initialize}
* method will read this channel's current configuration and reset
* MSPManager with the MSP's found in the channel configuration.
*
* @param {MSPManager} msp_manager - The msp manager for this channel
*/
setMSPManager(msp_manager) {
this._msp_manager = msp_manager;
}
/**
* Get the MSP Manager for this channel
* @returns {MSPManager}
*/
getMSPManager() {
return this._msp_manager;
}
/**
* Add the peer object to the channel object. A channel object can be optionally
* configured with a list of peer objects, which will be used when calling certain
* methods such as [sendInstantiateProposal()]{@link Channel#sendInstantiateProposal},
* [sendUpgradeProposal()]{@link Channel#sendUpgradeProposal},
* [sendTransactionProposal]{@link Channel#sendTransactionProposal}.
*
* @param {Peer} peer - An instance of the Peer class that has been initialized with URL
* and other gRPC options such as TLS credentials and request timeout.
*/
addPeer(peer) {
var url = peer.getUrl();
for (let i = 0; i < this._peers.length; i++) {
if (this._peers[i].getUrl() === url) {
var error = new Error();
error.name = 'DuplicatePeer';
error.message = 'Peer with URL ' + url + ' already exists';
logger.error(error.message);
throw error;
}
}
this._peers.push(peer);
}
/**
* Remove the first peer object in the channel object's list of peers
* whose endpoint url property matches the url of the peer that is
* passed in.
*
* @param {Peer} peer - An instance of the Peer class.
*/
removePeer(peer) {
var url = peer.getUrl();
for (let i = 0; i < this._peers.length; i++) {
if (this._peers[i].getUrl() === url) {
this._peers.splice(i, 1);
logger.debug('Removed peer with url "%s".', url);
return;
}
}
}
/**
* Returns the list of peers of this channel object.
* @returns {Peer[]} The peer list on the channel.
*/
getPeers() {
logger.debug('getPeers - list size: %s.', this._peers.length);
return this._peers;
}
/**
* Add the orderer object to the channel object, this is a client-side-only operation.
* An application may add more than one orderer object to the channel object, however
* the SDK only uses the first one in the list to send broadcast messages to the
* orderer backend.
*
* @param {Orderer} orderer - An instance of the Orderer class.
*/
addOrderer(orderer) {
var url = orderer.getUrl();
for (let i = 0; i < this._orderers.length; i++) {
if (this._orderers[i].getUrl() === url) {
var error = new Error();
error.name = 'DuplicateOrderer';
error.message = 'Orderer with URL ' + url + ' already exists';
logger.error(error.message);
throw error;
}
}
this._orderers.push(orderer);
}
/**
* Remove the first orderer object in the channel object's list of orderers
* whose endpoint url property matches the url of the orderer that is
* passed in.
*
* @param {Orderer} orderer - An instance of the Orderer class.
*/
removeOrderer(orderer) {
var url = orderer.getUrl();
for (let i = 0; i < this._orderers.length; i++) {
if (this._orderers[i].getUrl() === url) {
this._orderers.splice(i, 1);
logger.debug('Removed orderer with url "%s".', url);
return;
}
}
}
/**
* Returns the orderers of this channel object.
* @returns {Orderer[]} The list of orderers in the channel object
*/
getOrderers() {
return this._orderers;
}
/**
* Returns an {@link ChannelEventHub} object. An event hub object encapsulates the
* properties of an event stream on a peer node, through which the peer publishes
* notifications of blocks being committed in the channel's ledger.
*
* @returns {ChannelEventHub} The ChannnelEventHub instance
*/
newChannelEventHub(peer) {
peer = this._getPeerForEvents(peer);
var event_hub = new ChannelEventHub(this, peer);
return event_hub;
}
/**
* Returns a list of {@link ChannelEventHub} based on the peers that are
* defined in this channel that are in the named orgainization of the
* currently loaded connection profile. If no connetion profile is loaded,
* an error will be thrown.
* When called with no organization name, the organization named in the
* currently active connection profile configuration's client section will
* be used. A peer with the "eventSource" role setting of true will be added
* to the list (a role will default to true if not defined).
*
* @param {string} org_name - Optional - The name of an organization
* @returns {ChannelEventHub[]} An array of ChannelEventHub instances
*/
getChannelEventHubsForOrg(org_name) {
let method = 'getChannelEventHubsForOrg';
logger.debug('%s - starting', method);
var channel_event_hubs = [];
let working_org_name = null;
let found_peers = {};
if (this._clientContext && this._clientContext._network_config) {
if (!org_name && this._clientContext._network_config.hasClient()) {
let client = this._clientContext._network_config.getClientConfig();
working_org_name = client.organization;
} else {
working_org_name = org_name;
}
if (working_org_name) {
let organization = this._clientContext._network_config.getOrganization(working_org_name);
if (organization) {
let channel_peers = this.getPeers();
let org_peers = organization.getPeers();
for (let j in channel_peers) {
let channel_peer = channel_peers[j];
logger.debug('%s - looking at channel peer:%s', method, channel_peer.getName());
if (channel_peer.isInRole(Constants.NetworkConfig.EVENT_SOURCE_ROLE)) {
for (let k in org_peers) {
let org_peer = org_peers[k];
logger.debug('%s - looking at org peer:%s', method, org_peer.getName());
if (org_peer.getName() === channel_peer.getName()) {
found_peers[org_peer.getName()] = org_peer;//to avoid Duplicate Peers
logger.debug('%s - adding peer to list:%s', method, org_peer.getName());
}
}
}
}
} else {
throw new Error(util.format('Organization definition not found for %s', working_org_name));
}
} else {
throw new Error('No organization name provided');
}
} else {
throw new Error('No connecton profile has been loaded');
}
for (let name in found_peers) {
logger.debug('%s - final list has:%s', method, name);
let peer = found_peers[name];
let channel_event_hub = new ChannelEventHub(this, peer);
channel_event_hubs.push(channel_event_hub);
}
return channel_event_hubs;
}
/**
* @typedef {Object} OrdererRequest
* @property {TransactionID} txId - Optional. Object with the transaction id and nonce
* @property {Orderer} orderer - Optional. The orderer instance or string name
* of the orderer to retrieve genesis block from
*/
/**
* A channel's first block is called the "genesis block". This block captures the
* initial channel configuration. For a peer node to join the channel, it must be
* provided the genesis block. This method must be called before calling
* [joinChannel()]{@link Channel#joinChannel}.
*
* @param {OrdererRequest} request - Optional - A transaction ID object
* @returns {Promise} A Promise for an encoded protobuf "Block"
*/
getGenesisBlock(request) {
logger.debug('getGenesisBlock - start');
if (!request) {
request = {};
}
// verify that we have an orderer configured
var orderer = this._clientContext.getTargetOrderer(request.orderer, this._orderers, this._name);
var signer = null;
var tx_id = request.txId;
if (!tx_id) {
signer = this._clientContext._getSigningIdentity(true);
tx_id = new TransactionID(signer, true);
} else {
signer = this._clientContext._getSigningIdentity(tx_id.isAdmin());
}
// now build the seek info, will be used once the channel is created
// to get the genesis block back
// build start
var seekSpecifiedStart = new _abProto.SeekSpecified();
seekSpecifiedStart.setNumber(0);
var seekStart = new _abProto.SeekPosition();
seekStart.setSpecified(seekSpecifiedStart);
// build stop
var seekSpecifiedStop = new _abProto.SeekSpecified();
seekSpecifiedStop.setNumber(0);
var seekStop = new _abProto.SeekPosition();
seekStop.setSpecified(seekSpecifiedStop);
// seek info with all parts
var seekInfo = new _abProto.SeekInfo();
seekInfo.setStart(seekStart);
seekInfo.setStop(seekStop);
seekInfo.setBehavior(_abProto.SeekInfo.SeekBehavior.BLOCK_UNTIL_READY);
// build the header for use with the seekInfo payload
var seekInfoHeader = clientUtils.buildChannelHeader(
_commonProto.HeaderType.DELIVER_SEEK_INFO,
this._name,
tx_id.getTransactionID(),
this._initial_epoch,
null,
clientUtils.buildCurrentTimestamp(),
orderer.getClientCertHash()
);
var seekHeader = clientUtils.buildHeader(signer, seekInfoHeader, tx_id.getNonce());
var seekPayload = new _commonProto.Payload();
seekPayload.setHeader(seekHeader);
seekPayload.setData(seekInfo.toBuffer());
var seekPayloadBytes = seekPayload.toBuffer();
let sig = signer.sign(seekPayloadBytes);
let signature = Buffer.from(sig);
// building manually or will get protobuf errors on send
var envelope = {
signature: signature,
payload: seekPayloadBytes
};
return orderer.sendDeliver(envelope);
}
/**
* A protobuf message that gets returned by endorsing peers on proposal requests.
* The peer node runs the target chaincode, as designated by the proposal, and
* decides on whether to endorse the proposal or not, and sends back the endorsement
* result along with the [read and write sets]{@link http://hyperledger-fabric.readthedocs.io/en/latest/arch-deep-dive.html?highlight=readset#the-endorsing-peer-simulates-a-transaction-and-produces-an-endorsement-signature}
* inside the proposal response message.
*
* @typedef {Object} ProposalResponse
* @property {number} version
* @property {Timestamp} timestamp - Time the proposal was created by the submitter
* @property {Response} response
* @property {byte[]} payload - The payload of the response. It is the encoded bytes of
* the "ProposalResponsePayload" protobuf message
* @property {Endorsement} endorsement - The endorsement of the proposal, basically the
* endorser's signature over the payload
*/
/**
* A response message indicating whether the endorsement of the proposal was successful
*
* @typedef {Object} Response
* @property {number} status - Status code. Follows [HTTP status code definitions]{@link https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html}
* @property {string} message - A message associated with the response status code
* @property {byte[]} payload - A payload that can be used to include metadata with this response
*/
/**
* @typedef {Object} JoinChannelRequest
* @property {Peer[]} targets - Optional. An array of Peer objects or Peer names that will
* be asked to join this channel. When using Peer names or left
* empty (use default targets) there must be a loaded network
* configuration.
* See [loadFromConfig()]{@link Client#loadFromConfig}
* @property {byte[]} block - The encoded bytes of the channel's genesis block.
* See [getGenesisBlock()]{@link Channel#getGenesisBlock} method
* @property {TransactionID} txId - Required. TransactionID object with the transaction id and nonce
*/
/**
* For a peer node to become part of a channel, it must be sent the genesis
* block, as explained [here]{@link Channel#getGenesisBlock}. This method
* sends a join channel proposal to one or more endorsing peers.
*
* @param {JoinChannelRequest} request
* @param {Number} timeout - A number indicating milliseconds to wait on the
* response before rejecting the promise with a
* timeout error. This overrides the default timeout
* of the {@link Peer} instance(s) and the global timeout in the config settings.
* @returns {Promise} A Promise for an array of {@link ProposalResponse} from the target peers
*/
joinChannel(request, timeout) {
logger.debug('joinChannel - start');
var errorMsg = null;
// verify that we have targets (Peers) to join this channel
// defined by the caller
if (!request) {
errorMsg = 'Missing all required input request parameters';
}
// verify that we have transaction id
else if (!request.txId) {
errorMsg = 'Missing txId input parameter with the required transaction identifier';
}
else if (!request.block) {
errorMsg = 'Missing block input parameter with the required genesis block';
}
if (errorMsg) {
logger.error('joinChannel - error ' + errorMsg);
throw new Error(errorMsg);
}
var targets = this._getTargets(request.targets); //no role, will get all peers
var signer = this._clientContext._getSigningIdentity(request.txId.isAdmin());
var chaincodeInput = new _ccProto.ChaincodeInput();
var args = [];
args.push(Buffer.from('JoinChain', 'utf8'));
args.push(request.block.toBuffer());
chaincodeInput.setArgs(args);
var chaincodeID = new _ccProto.ChaincodeID();
chaincodeID.setName(Constants.CSCC);
var chaincodeSpec = new _ccProto.ChaincodeSpec();
chaincodeSpec.setType(_ccProto.ChaincodeSpec.Type.GOLANG);
chaincodeSpec.setChaincodeId(chaincodeID);
chaincodeSpec.setInput(chaincodeInput);
var channelHeader = clientUtils.buildChannelHeader(
_commonProto.HeaderType.ENDORSER_TRANSACTION,
'',
request.txId.getTransactionID(),
null, //no epoch
Constants.CSCC,
clientUtils.buildCurrentTimestamp(),
targets[0].getClientCertHash()
);
var header = clientUtils.buildHeader(signer, channelHeader, request.txId.getNonce());
var proposal = clientUtils.buildProposal(chaincodeSpec, header);
var signed_proposal = clientUtils.signProposal(signer, proposal);
return clientUtils.sendPeersProposal(targets, signed_proposal, timeout)
.then(
function (responses) {
return Promise.resolve(responses);
}
).catch(
function (err) {
logger.error('joinChannel - Failed Proposal. Error: %s', err.stack ? err.stack : err);
return Promise.reject(err);
}
);
}
/**
* Asks the peer for the current (latest) configuration block for this channel.
* @param {string | Peer} target - Optional. The peer to be used to make the
* request.
* @returns {Promise} A Promise for a {@link ConfigEnvelope} object containing the configuration items.
*/
getChannelConfig(target) {
let method = 'getChannelConfig';
logger.debug('%s - start for channel %s', method, this._name);
var targets = this._getTargetForQuery(target);
var signer = this._clientContext._getSigningIdentity(true);
var tx_id = new TransactionID(signer, true);
var request = {
targets: targets,
chaincodeId: Constants.CSCC,
txId: tx_id,
signer: signer,
fcn: 'GetConfigBlock',
args: [this._name]
};
return this.sendTransactionProposal(request)
.then(
function (results) {
var responses = results[0];
// var proposal = results[1];
logger.debug('%s - results received', method);
if (responses && Array.isArray(responses)) {
let response = responses[0];
if (response instanceof Error) {
return Promise.reject(response);
}
else if (response.response && response.response.payload) {
let block = _commonProto.Block.decode(response.response.payload);
let envelope = _commonProto.Envelope.decode(block.data.data[0]);
let payload = _commonProto.Payload.decode(envelope.payload);
let config_envelope = _configtxProto.ConfigEnvelope.decode(payload.data);
return Promise.resolve(config_envelope);
}
else {
logger.error('%s - unknown response ::%s', method, response);
return Promise.reject(new Error(response));
}
}
return Promise.reject(new Error('Payload results are missing from the get channel config'));
}
).catch(
function (err) {
logger.error('%s - Failed getting channel config. Error: %s', method, err.stack ? err.stack : err);
return Promise.reject(err);
}
);
}
/**
* Asks the orderer for the current (latest) configuration block for this channel.
* This is similar to [getGenesisBlock()]{@link Channel#getGenesisBlock}, except
* that instead of getting block number 0 it gets the latest block that contains
* the channel configuration, and only returns the decoded {@link ConfigEnvelope}.
*
* @returns {Promise} A Promise for a {@link ConfigEnvelope} object containing the configuration items.
*/
getChannelConfigFromOrderer() {
let method = 'getChannelConfigFromOrderer';
logger.debug('%s - start for channel %s', method, this._name);
var self = this;
var orderer = this._clientContext.getTargetOrderer(null, this._orderers, this._name);
var signer = this._clientContext._getSigningIdentity(true);
var txId = new TransactionID(signer, true);
// seek the latest block
var seekSpecifiedStart = new _abProto.SeekNewest();
var seekStart = new _abProto.SeekPosition();
seekStart.setNewest(seekSpecifiedStart);
var seekSpecifiedStop = new _abProto.SeekNewest();
var seekStop = new _abProto.SeekPosition();
seekStop.setNewest(seekSpecifiedStop);
// seek info with all parts
var seekInfo = new _abProto.SeekInfo();
seekInfo.setStart(seekStart);
seekInfo.setStop(seekStop);
seekInfo.setBehavior(_abProto.SeekInfo.SeekBehavior.BLOCK_UNTIL_READY);
// build the header for use with the seekInfo payload
var seekInfoHeader = clientUtils.buildChannelHeader(
_commonProto.HeaderType.DELIVER_SEEK_INFO,
self._name,
txId.getTransactionID(),
self._initial_epoch,
null,
clientUtils.buildCurrentTimestamp(),
orderer.getClientCertHash()
);
var seekHeader = clientUtils.buildHeader(signer, seekInfoHeader, txId.getNonce());
var seekPayload = new _commonProto.Payload();
seekPayload.setHeader(seekHeader);
seekPayload.setData(seekInfo.toBuffer());
var seekPayloadBytes = seekPayload.toBuffer();
let sig = signer.sign(seekPayloadBytes);
let signature = Buffer.from(sig);
// building manually or will get protobuf errors on send
var envelope = {
signature: signature,
payload: seekPayloadBytes
};
// This will return us a block
return orderer.sendDeliver(envelope)
.then(
function (block) {
logger.debug('%s - good results from seek block ', method); // :: %j',results);
// verify that we have the genesis block
if (block) {
logger.debug('%s - found latest block', method);
}
else {
logger.error('%s - did not find latest block', method);
return Promise.reject(new Error('Failed to retrieve latest block', method));
}
logger.debug('%s - latest block is block number %s', block.header.number);
// get the last config block number
var metadata = _commonProto.Metadata.decode(block.metadata.metadata[_commonProto.BlockMetadataIndex.LAST_CONFIG]);
var last_config = _commonProto.LastConfig.decode(metadata.value);
logger.debug('%s - latest block has config block of %s', method, last_config.index);
var txId = new TransactionID(signer);
// now build the seek info to get the block called out
// as the latest config block
var seekSpecifiedStart = new _abProto.SeekSpecified();
seekSpecifiedStart.setNumber(last_config.index);
var seekStart = new _abProto.SeekPosition();
seekStart.setSpecified(seekSpecifiedStart);
// build stop
var seekSpecifiedStop = new _abProto.SeekSpecified();
seekSpecifiedStop.setNumber(last_config.index);
var seekStop = new _abProto.SeekPosition();
seekStop.setSpecified(seekSpecifiedStop);
// seek info with all parts
var seekInfo = new _abProto.SeekInfo();
seekInfo.setStart(seekStart);
seekInfo.setStop(seekStop);
seekInfo.setBehavior(_abProto.SeekInfo.SeekBehavior.BLOCK_UNTIL_READY);
//logger.debug('initializeChannel - seekInfo ::' + JSON.stringify(seekInfo));
// build the header for use with the seekInfo payload
var seekInfoHeader = clientUtils.buildChannelHeader(
_commonProto.HeaderType.DELIVER_SEEK_INFO,
self._name,
txId.getTransactionID(),
self._initial_epoch,
null,
clientUtils.buildCurrentTimestamp(),
orderer.getClientCertHash()
);
var seekHeader = clientUtils.buildHeader(signer, seekInfoHeader, txId.getNonce());
var seekPayload = new _commonProto.Payload();
seekPayload.setHeader(seekHeader);
seekPayload.setData(seekInfo.toBuffer());
var seekPayloadBytes = seekPayload.toBuffer();
let sig = signer.sign(seekPayloadBytes);
let signature = Buffer.from(sig);
// building manually or will get protobuf errors on send
var envelope = {
signature: signature,
payload: seekPayloadBytes
};
// this will return us a block
return orderer.sendDeliver(envelope);
}
).then(
function (block) {
if (!block) {
return Promise.reject(new Error('Config block was not found'));
}
// lets have a look at the block
logger.debug('%s - config block number ::%s -- numberof tx :: %s', method, block.header.number, block.data.data.length);
if (block.data.data.length != 1) {
return Promise.reject(new Error('Config block must only contain one transaction'));
}
var envelope = _commonProto.Envelope.decode(block.data.data[0]);
var payload = _commonProto.Payload.decode(envelope.payload);
var channel_header = _commonProto.ChannelHeader.decode(payload.header.channel_header);
if (channel_header.type != _commonProto.HeaderType.CONFIG) {
return Promise.reject(new Error(util.format('Block must be of type "CONFIG" (%s), but got "%s" instead', _commonProto.HeaderType.CONFIG, channel_header.type)));
}
var config_envelope = _configtxProto.ConfigEnvelope.decode(payload.data);
// send back the envelope
return Promise.resolve(config_envelope);
}
).catch(
function (err) {
logger.error('%s - Failed Proposal. Error: %s', method, err.stack ? err.stack : err);
return Promise.reject(err);
}
);
}
/*
* Utility method to load this channel with configuration information
* from an Envelope that contains a Configuration
* @param {byte[]} the envelope with the configuration update items
* @see /protos/common/configtx.proto
*/
loadConfigUpdateEnvelope(data) {
logger.debug('loadConfigUpdateEnvelope - start');
var envelope = _commonProto.Envelope.decode(data);
var payload = _commonProto.Payload.decode(envelope.payload);
var channel_header = _commonProto.ChannelHeader.decode(payload.header.channel_header);
if (channel_header.type != _commonProto.HeaderType.CONFIG_UPDATE) {
return new Error('Data must be of type "CONFIG_UPDATE"');
}
var config_update_envelope = _configtxProto.ConfigUpdateEnvelope.decode(payload.data);
return this.loadConfigUpdate(config_update_envelope.config_update);
}
loadConfigUpdate(config_update_bytes) {
var config_update = _configtxProto.ConfigUpdate.decode(config_update_bytes);
logger.debug('loadConfigData - channel ::' + config_update.channel_id);
let read_group = config_update.read_set;
let write_group = config_update.write_set;
var config_items = {};
config_items.msps = []; //save all the MSP's found
config_items['anchor-peers'] = []; //save all the MSP's found
config_items.orderers = [];
config_items['kafka-brokers'] = [];
config_items.settings = {};
config_items.versions = {};
config_items.versions.read_group = {};
config_items.versions.write_group = {};
loadConfigGroup(config_items, config_items.versions.read_group, read_group, 'read_set', null, true, false);
// do the write_set second so they update anything in the read set
loadConfigGroup(config_items, config_items.versions.write_group, write_group, 'write_set', null, true, false);
this._msp_manager.loadMSPs(config_items.msps);
this._anchor_peers = config_items.anchor_peers;
//TODO should we create orderers and endorsing peers
return config_items;
}
/*
* Utility method to load this channel with configuration information
* from a Configuration block
* @param {ConfigEnvelope} the envelope with the configuration items
* @see /protos/common/configtx.proto
*/
loadConfigEnvelope(config_envelope) {
logger.debug('loadConfigEnvelope - start');
let group = config_envelope.config.channel_group;
var config_items = {};
config_items.msps = []; //save all the MSP's found
config_items['anchor-peers'] = []; //save all the MSP's found
config_items.orderers = [];
config_items['kafka-brokers'] = [];
config_items.versions = {};
config_items.versions.channel = {};
loadConfigGroup(config_items, config_items.versions.channel, group, 'base', null, true, true);
this._msp_manager.loadMSPs(config_items.msps);
this._anchor_peers = config_items.anchor_peers;
//TODO should we create orderers and endorsing peers
return config_items;
}
/**
* @typedef {Object} BlockchainInfo
* @property {number} height - How many blocks exist on the channel's ledger
* @property {byte[]} currentBlockHash - A block hash is calculated by hashing over the concatenated
* ASN.1 encoded bytes of: the block number, previous block hash,
* and current block data hash. It's the chain of the block
* hashs that guarantees the immutability of the ledger
* @property {byte[]} previousBlockHash - The block hash of the previous block.
*/
/**
* Queries for various useful information on the state of the Channel
* (height, known peers).
*
* @param {Peer} target - Optional. The peer that is the target for this query. If no target is passed,
* the query will use the first peer that was added to the channel object.
* @param {boolean} useAdmin - Optional. Indicates that the admin credentials should be used in making
* this call to the peer.
* @returns {Promise} A Promise for a {@link BlockchainInfo} object with blockchain height,
* current block hash and previous block hash.
*/
queryInfo(target, useAdmin) {
logger.debug('queryInfo - start');
var targets = this._getTargetForQuery(target);
var signer = this._clientContext._getSigningIdentity(useAdmin);
var tx_id = new TransactionID(signer, useAdmin);
var request = {
targets: targets,
chaincodeId: Constants.QSCC,
txId: tx_id,
signer: signer,
fcn: 'GetChainInfo',
args: [this._name]
};
return this.sendTransactionProposal(request)
.then(
function (results) {
var responses = results[0];
if (responses && Array.isArray(responses)) {
logger.debug('queryInfo - got responses=' + responses.length);
//will only be one response as we are only querying the primary peer
if (responses.length > 1) {
return Promise.reject(new Error('Too many results returned'));
}
let response = responses[0];
if (response instanceof Error) {
return Promise.reject(response);
}
if (response.response) {
logger.debug('queryInfo - response status %d:', response.response.status);
var chain_info = _ledgerProto.BlockchainInfo.decode(response.response.payload);
return Promise.resolve(chain_info);
}
// no idea what we have, lets fail it and send it back
return Promise.reject(response);
}
return Promise.reject(new Error('Payload results are missing from the query channel info'));
}
).catch(
function (err) {
logger.error('Failed Query channel info. Error: %s', err.stack ? err.stack : err);
return Promise.reject(err);
}
);
}
/**
* Queries the ledger on the target peer for a Block TransactionID.
*
* @param {string} tx_id - The TransactionID of the Block in question.
* @param {Peer} target - Optional. The peer to send the query to. If no target is passed,
* the query is sent to the first peer that was added to the channel object.
* @param {boolean} useAdmin - Optional. Indicates that the admin credentials should be used in making
* this call to the peer.
* @returns {Promise} A Promise for a {@link Block} matching the tx_id, fully decoded into an object.
*/
queryBlockByTxID(tx_id, target, useAdmin) {
logger.debug('queryBlockByTxID - start');
if (!tx_id || !(typeof tx_id === 'string')) {
throw new Error('tx_id as string is required');
}
const args = [this._name,tx_id];
const targets = this._getTargetForQuery(target);
const signer = this._clientContext._getSigningIdentity(useAdmin);
const request = {
targets,
chaincodeId: Constants.QSCC,
txId: new TransactionID(signer,useAdmin),
fcn: 'GetBlockByTxID',
args
};
return this.sendTransactionProposal(request)
.then((results)=> {
const responses = results[0];
if (responses && Array.isArray(responses)) {
logger.debug('queryBlockByTxID - got response',responses.length);
//will only be one response as we are only querying the primary peer
if (responses.length > 1) {
return Promise.reject(new Error('Too many results returned'));
}
const response = responses[0];
if (response instanceof Error) {
return Promise.reject(response);
}
if (response.response) {
logger.debug('queryBlockByTxID - response status %d:', response.response.status);
const block = BlockDecoder.decode(response.response.payload);
logger.debug('queryBlockByTxID - looking at block :: %s', block.header.number);
return Promise.resolve(block);
}
// no idea what we have, lets fail it and send it back
return Promise.reject(response);
}
return Promise.reject(new Error('Payload results are missing from the query'));
}).catch((err)=> {
logger.error('Failed Query block. Error: %s', err.stack ? err.stack : err);
return Promise.reject(err);
});
}
/**
* Queries the ledger on the target peer for a Block by block hash.
*
* @param {byte[]} block hash of the Block in question.
* @param {Peer} target - Optional. The peer to send the query to. If no target is passed,
* the query is sent to the first peer that was added to the channel object.
* @param {boolean} useAdmin - Optional. Indicates that the admin credentials should be used in making