-
Notifications
You must be signed in to change notification settings - Fork 518
/
BlockDecoder.js
1341 lines (1204 loc) · 47.8 KB
/
BlockDecoder.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 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 grpc = require('grpc');
var util = require('util');
var path = require('path');
var utils = require('./utils.js');
var logger = utils.getLogger('BlockDecoder.js');
var _ccEventProto = grpc.load(__dirname + '/protos/peer/chaincode_event.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 _peerConfigurationProto = grpc.load(__dirname + '/protos/peer/configuration.proto').protos;
var _mspPrProto = grpc.load(__dirname + '/protos/msp/msp_principal.proto').common;
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 _commonConfigurationProto = grpc.load(__dirname + '/protos/common/configuration.proto').common;
var _ordererConfigurationProto = grpc.load(__dirname + '/protos/orderer/configuration.proto').orderer;
var _mspConfigProto = grpc.load(__dirname + '/protos/msp/msp_config.proto').msp;
var _identityProto = grpc.load(path.join(__dirname, '/protos/msp/identities.proto')).msp;
var _rwsetProto = grpc.load(path.join(__dirname, '/protos/ledger/rwset/rwset.proto')).rwset;
var _kv_rwsetProto = grpc.load(path.join(__dirname, '/protos/ledger/rwset/kvrwset/kv_rwset.proto')).kvrwset;
/**
* Utility class to convert a protobuf encoded byte array of a Hyperledger Fabric block
* message into a pure Javascript object
*
* @class
*/
var BlockDecoder = class {
/**
* An object of a fully decoded protobuf message "Block".
* <br><br>
* A Block may contain the configuration of the channel or transactions on the channel.
* <br><br>
* A Block object will have the following object structure.
<br><pre>
header
number -- {int}
previous_hash -- {byte[]}
data_hash -- {byte[]}
data
data -- {array}
signature -- {byte[]}
payload
header -- {{@link Header}}
data -- {{@link ConfigEnvelope} | {@link Transaction}}
metadata
metadata -- {array} #each array item has it's own layout
[0] #SIGNATURES
signatures -- {{@link MetadataSignature[]}}
[1] #LAST_CONFIG
value
index -- {number}
signatures -- {{@link MetadataSignature[]}}
[2] #TRANSACTIONS_FILTER
{int[]} #see TxValidationCode in proto/peer/transaction.proto
</pre>
*
* @typedef {Object} Block
*
* @example
* <caption>Get the block number:</caption>
* var block_num = block.header.number;
*
* @example
* <caption>Get the number of transactions, including the invalid transactions:</caption>
* var block_num = block.data.data.legnth;
*
* @example
* <caption>Get the Id of the first transaction in the block:</caption>
* var tx_id = block.data.data[0].payload.header.channel_header.tx_id;
*/
/**
* Headers describe basic information about a transaction record, such
* as its type (configuration update, or endorser transaction, etc.),
* the id of the channel it belongs to, the transaction id and so on.
* The header message also contains a common field {@link SignatureHeader}
* that describes critical information about how to verify signatures.
* <br><br>
* A "Header" will have the following object structure.
<br><pre>
channel_header
type -- {string}
version -- {int}
timestamp -- {time}
channel_id -- {string}
tx_id -- {string}
epoch -- {int}
signature_header -- {{@link SignatureHeader}}
</pre>
* @typedef {Object} Header
*/
/**
* A signature over the metadata of a block, to ensure the authenticity of
* the metadata that describes a Block.
<br><pre>
signature_header {{@link SignatureHeader}}
signature -- {byte[]}
</pre>
*
* @typedef {Object} MetadataSignature
*/
/**
* An object that is part of all signatures in Hyperledger Fabric. The "creator"
* field has two important pieces of information about the identity of the signer,
* the organization (Mspid) that the signer belongs to, and the certificate (IdBytes).
* The "nonce" field is a unique value to guard against replay attacks.
*
<br><pre>
creator
Mspid -- {string}
IdBytes -- {byte[]}
nonce -- {byte[]}
</pre>
* @typedef {Object} SignatureHeader
*/
/**
* A ConfigEnvelope contains the channel configurations data and is the
* main content of a configuration block. Another type of blocks are those
* that contain endorser transactions, where the main content is an array
* of {@link Transaction}.
* <br><br>
* A "ConfigEnvelope" will have the following object structure.
<br><pre>
config
sequence -- {int}
channel_group -- {{@link ConfigGroup}}
type -- {int}
last_update
signature -- {byte[]}
payload
header -- {{@link Header}}
data -- {{@link ConfigUpdateEnvelope}}
</pre>
* @typedef {Object} ConfigEnvelope
*/
/**
* A Transaction, or "Endorser Transaction", is the result of invoking chaincodes
* to collect endorsements, getting globally ordered in the context of a channel,
* and getting validated by the committer peer as part of a block before finally
* being formally "committed" to the ledger inside a Block. Each transaction contains
* an array of "actions" representing different steps for executing a transaction,
* and those steps will be processed atomically, meaning if any one step failed
* then the whole transaction will be marked as rejected.
* <br><br>
* Each entry of the "actions" array contains a chaincode proposal and corresponding proposal
* responses that encapsulate the endorsing peer's decisions on whether the proposal
* is considered valid. Note that even if a transaction proposal(s) is considered
* valid by the endorsing peers, it may still be rejected by the committers during
* transaction validation. Whether a transaction as a whole is valid or not, is not
* reflected in the transaction record itself, but rather recorded in a separate
* field in the Block's metadata.
* <br><br>
* A "Transaction" will have the following object structure.
<br><pre>
actions {array}
header -- {{@link SignatureHeader}}
payload
chaincode_proposal_payload
input -- {byte[]}
action
proposal_response_payload
proposal_hash -- {byte[]}
extension
results
data_model -- {int}
ns_rwset -- {array}
namespace -- {string}
rwset
reads -- {array}
key -- {string}
version
block_num -- {number}
tx_num -- {number}
range_queries_info -- {array}
writes -- {array}
key -- {string}
is_delete -- {boolean}
value -- {string}
events
chaincode_id -- {string}
tx_id -- {string}
event_name -- {string}
payload -- {byte[]}
response
status -- {int}
message -- {string}
payload -- {byte[]}
endorsements -- {{@link Endorsement}[]}
</pre>
* @typedef {Object} Transaction
*/
/**
* An object of a protobuf message "ConfigUpdateEnvelope".
* <br><br>
* A "ConfigUpdateEnvelope" will have the following object structure.
<br><pre>
config_update
channel_id -- {string}
read_set -- {{@link ChannelConfigGroup}}
write_set -- {{@link ChannelConfigGroup}}
type -- {int}
signatures -- {array}
signature_header -- {{@link SignatureHeader}}
signature -- {byte[]}
</pre>
* @typedef {Object} ConfigUpdateEnvelope
* @property {ChannelConfigGroup} config_update.read_set A set of the current version numbers of all
* configuration items being updated
* @property {ChannelConfigGroup} config_update.write_set A set of all configuration items being updated. Must have a
* version number one greater than the version number of the same item
* in the read_set along with the new value.
*/
/**
* The configuration settings that govern how the fabric should maintain
* a channel are included in the blocks of the channel itself. When a block contains
* the channel configuration, the channel configuration record is the only item in
* the block's data array. Every block, including the configuration blocks themselves,
* has a pointer to the latest configuration block, making it easy to query for the
* latest channel configuration settings.
* <br><br>
* A channel configuration record will have the following object structure.
<br><pre>
version -- {int}
mod_policy -- {string}
groups
Orderer
version -- {int}
groups
<orderer_org_name> -- {{@link OrganizationConfigGroup}}
values
ConsensusType
version -- {int}
mod_policy -- {string}
value
type -- {string}
BatchSize
version -- {int}
mod_policy -- {string}
value
max_message_count -- {int}
absolute_max_bytes -- {int}
preferred_max_bytes -- {int}
BatchTimeout
version -- {int}
mod_policy -- {string}
value
timeout -- {duration}
ChannelRestrictions
version -- {int}
mod_policy -- {string}
value
max_count -- {int}
policies
Admins
version -- {int}
mod_policy -- {string}
policy -- {{@link ImplicitMetaPolicy}}
Writers
version -- {int}
mod_policy -- {string}
policy -- {{@link ImplicitMetaPolicy}}
Readers
version -- {int}
mod_policy -- {string}
policy -- {{@link ImplicitMetaPolicy}}
BlockValidation
version -- {int}
mod_policy -- {string}
policy -- {{@link SignaturePolicy}}
Application
version -- {int}
groups
<peer_org_name> -- {{@link OrganizationConfigGroup}}
values
policies
Admins
version -- {int}
mod_policy -- {string}
policy -- {{@link ImplicitMetaPolicy}}
Writers
version -- {int}
mod_policy -- {string}
policy -- {{@link ImplicitMetaPolicy}}
Readers
version -- {int}
mod_policy -- {string}
policy -- {{@link ImplicitMetaPolicy}}
values
OrdererAddresses
version -- {int}
mod_policy -- {string}
value
addresses -- {array}
{string - host:port}
HashingAlgorithm
version -- {int}
mod_policy -- {string}
value
name -- {string}
BlockDataHashingStructure
version -- {int}
mod_policy -- {string}
value
width -- {int}
Consortium
version -- {int}
mod_policy -- {string}
value
name -- {string}
</pre>
* @typedef {Object} ChannelConfigGroup
* @property {OrganizationConfigGroup} groups.Orderer.groups.<orderer_org_name> These are the
* orderer organizatoin names defined on the network
* @property {OrganizationConfigGroup} groups.Application.groups.<peer_org_name> These are the
* peer organization names defined on the network
* @property {ImplicitMetaPolicy} policy These policies point to other policies and specify a
* threshold as in "ANY", "MAJORITY" or "ALL"
*/
/**
* Each participating organization of the channel gets represented in a section
* in the configuration block as described below. Critical information about the
* organzation such as its Membership Service Provider (MSP) content and its pre-defined
* policies that form the basis of the channel's access control policies (Admins, Writers
* and Readers) are contained in these sections.
* <br><br>
* A organizational configuration will have the following object structure.
<br><pre>
version -- {int}
mod_policy -- {string}
values
MSP
version -- {int}
mod_policy -- {string}
value
type -- {int}
config
name -- {string}
root_certs -- {string[]}
intermediate_certs -- {string[]}
admins -- {string[]}
revocation_list -- {string[]}
signing_identity -- {byte[]}
organizational_unit_identifiers -- {string[]}
policies
Admins
version -- {int}
mod_policy -- {string}
policy -- {{@link SignaturePolicy}}
Writers
version -- {int}
mod_policy -- {string}
policy -- {{@link SignaturePolicy}}
Readers
version -- {int}
mod_policy -- {string}
policy -- {{@link SignaturePolicy}}
</pre>
* @typedef {Object} OrganizationConfigGroup
*/
/**
* An endorsement is a signature of an endorser over a proposal response. By
* producing an endorsement message, an endorser implicitly "approves" that
* proposal response and the actions contained therein. When enough
* endorsements have been collected, a transaction can be generated out of a
* set of proposal responses
* <br><br>
* An endorsement message has the following structure:
<br><pre>
endorser
Mspid -- {string]
IdBytes -- {byte[]}
signature -- {byte[]}
</pre>
*
* @typedef {Object} Endorsement
*/
/**
* ImplicitMetaPolicy is a policy type which depends on the hierarchical nature of the configuration
* It is implicit because the rule is generate implicitly based on the number of sub policies
* It is meta because it depends only on the result of other policies
* <br><br>
* When evaluated, this policy iterates over all immediate child sub-groups, retrieves the policy
* of name sub_policy, evaluates the collection and applies the rule.
* <br><br>
* For example, with 4 sub-groups, and a policy name of "Readers", ImplicitMetaPolicy retrieves
* each sub-group, retrieves policy "Readers" for each subgroup, evaluates it, and, in the case of ANY
* 1 satisfied is sufficient, ALL would require 4 signatures, and MAJORITY would require 3 signatures.
* <br><br>
* An "ImplicitMetaPolicy" will have the following object structure.
<br><pre>
type -- IMPLICIT_META
policy
sub_policy -- {string}
rule -- ANY | ALL | MAJORITY
</pre>
* @typedef {Object} ImplicitMetaPolicy
*/
/**
* SignaturePolicy is a recursive message structure which defines a featherweight DSL for describing
* policies which are more complicated than 'exactly this signature'. The NOutOf operator is sufficent
* to express AND as well as OR, as well as of course N out of the following M policies.
* <br><br>
* SignedBy implies that the signature is from a valid certificate which is signed by the trusted
* authority specified in the bytes. This will be the certificate itself for a self-signed certificate
* and will be the CA for more traditional certificates
* <br><br>
* A "SignaturePolicy" will have the following object structure.
<br><pre>
type -- SIGNATURE
rule
Type -- n_out_of
n_out_of
N -- {int}
rules -- {array}
Type -- signed_by
signed_by -- {int}
identities -- {array}
principal_classification -- {int}
msp_identifier -- {string}
Role -- MEMBER | ADMIN
</pre>
* @typedef {Object} SignaturePolicy
*/
/**
* Constructs a JSON object containing all decoded values from the
* protobuf encoded `Block` bytes.
*
* @param {byte[]} block_bytes - The encoded bytes of a Block protobuf message
* @returns {Block} An object of the Block
*/
static decode(block_bytes) {
if (!block_bytes || !(block_bytes instanceof Buffer)) {
throw new Error('Block input data is not a byte buffer');
}
var block = {};
try {
var proto_block = _commonProto.Block.decode(block_bytes);
block.header = decodeBlockHeader(proto_block.getHeader());
block.data = decodeBlockData(proto_block.getData());
block.metadata = decodeBlockMetaData(proto_block.getMetadata());
} catch (error) {
logger.error('decode - ::' + error.stack ? error.stack : error);
throw error;
}
return block;
}
/**
* Constructs an object containing all decoded values from the
* protobuf encoded `Block` object
*
* @param {Object} block_data - an object that represents the protobuf common.Block
* @returns {Block} An object of the fully decoded protobuf common.Block
*/
static decodeBlock(block_data) {
if (!block_data) {
throw new Error('Block input data is missing');
}
var block = {};
try {
block.header = {
number: block_data.header.number.toString(),
previous_hash: block_data.header.previous_hash.toString('hex'),
data_hash: block_data.header.data_hash.toString('hex')
};
block.data = decodeBlockData(block_data.data, true);
block.metadata = decodeBlockMetaData(block_data.metadata);
} catch (error) {
logger.error('decode - ::' + error.stack ? error.stack : error);
throw new Error('Block decode has failed with ' + error.toString());
}
return block;
}
/**
* @typedef {Object} ProcessedTransaction
* @property {number} validationCode - See [this list]{@link https://github.com/hyperledger/fabric/blob/v1.0.0/protos/peer/transaction.proto#L125}
* for all the defined validation codes
* @property {Object} transactionEnvelope - Encapsulates the transaction and the signature over it.
* It has the following structure:
<br><pre>
signature -- {byte[]}
payload -- {}
header -- {{@link Header}}
data -- {{@link Transaction}}
</pre>
*/
/**
* Constructs an object containing all decoded values from the
* protobuf encoded "ProcessedTransaction" bytes
*
* @param {byte[]} processed_transaction_bytes - The encode bytes of a protobuf
* message "ProcessedTransaction"
* @returns {ProcessedTransaction} A fully decoded ProcessedTransaction object
*/
static decodeTransaction(processed_transaction_bytes) {
if (!(processed_transaction_bytes instanceof Buffer)) {
throw new Error('Proccesed transaction data is not a byte buffer');
}
let processed_transaction = {};
let proto_processed_transaction = _transProto.ProcessedTransaction.decode(processed_transaction_bytes);
processed_transaction.validationCode = proto_processed_transaction.getValidationCode();
processed_transaction.transactionEnvelope = decodeBlockDataEnvelope(proto_processed_transaction.getTransactionEnvelope());
return processed_transaction;
}
};
function decodeBlockHeader(proto_block_header) {
var block_header = {};
block_header.number = proto_block_header.getNumber().toString();
block_header.previous_hash = proto_block_header.getPreviousHash().toBuffer().toString('hex');
block_header.data_hash = proto_block_header.getDataHash().toBuffer().toString('hex');
return block_header;
}
function decodeBlockData(proto_block_data, not_proto) {
var data = {};
data.data = [];
for (var i in proto_block_data.data) {
var proto_envelope = null;
if (not_proto) {
proto_envelope = _commonProto.Envelope.decode(proto_block_data.data[i]);
} else {
proto_envelope = _commonProto.Envelope.decode(proto_block_data.data[i].toBuffer());
}
var envelope = decodeBlockDataEnvelope(proto_envelope);
data.data.push(envelope);
}
return data;
}
function decodeBlockMetaData(proto_block_metadata) {
var metadata = {};
metadata.metadata = [];
if (proto_block_metadata && proto_block_metadata.metadata) {
var signatures = decodeMetadataSignatures(proto_block_metadata.metadata[0]);
metadata.metadata.push(signatures);
var last_config = decodeLastConfigSequenceNumber(proto_block_metadata.metadata[1]);
metadata.metadata.push(last_config);
var transaction_filter = decodeTransactionFilter(proto_block_metadata.metadata[2]);
metadata.metadata.push(transaction_filter);
}
return metadata;
}
function decodeTransactionFilter(metadata_bytes) {
var transaction_filter = [];
if(!metadata_bytes) {
logger.debug('decodeTransactionFilter - no metadata');
return null;
}
if(!(metadata_bytes instanceof Buffer)) {
metadata_bytes = metadata_bytes.toBuffer();
}
logger.debug('decodeTransactionFilter - metadata length:%s',metadata_bytes.length);
for (let i = 0; i < metadata_bytes.length; i++) {
let value = parseInt(metadata_bytes[i]);
logger.debug('decodeTransactionFilter - looking at index:%s with value:%s',i,value);
transaction_filter.push(value);
}
return transaction_filter;
}
function decodeLastConfigSequenceNumber(metadata_bytes) {
var last_config = {};
last_config.value = {};
if (metadata_bytes) {
var proto_metadata = _commonProto.Metadata.decode(metadata_bytes);
var proto_last_config = _commonProto.LastConfig.decode(proto_metadata.getValue());
last_config.value.index = proto_last_config.getIndex().toString(); //unit64
last_config.signatures = decodeMetadataValueSignatures(proto_metadata.signatures);
}
return last_config;
}
function decodeMetadataSignatures(metadata_bytes) {
var metadata = {};
var proto_metadata = _commonProto.Metadata.decode(metadata_bytes);
metadata.value = proto_metadata.getValue().toBuffer().toString();
metadata.signatures = decodeMetadataValueSignatures(proto_metadata.signatures);
return metadata;
}
function decodeMetadataValueSignatures(proto_meta_signatures) {
var signatures = [];
if (proto_meta_signatures)
for (let i in proto_meta_signatures) {
var metadata_signature = {};
var proto_metadata_signature = _commonProto.MetadataSignature.decode(proto_meta_signatures[i].toBuffer());
metadata_signature.signature_header = decodeSignatureHeader(proto_metadata_signature.getSignatureHeader());
metadata_signature.signature = proto_metadata_signature.getSignature().toBuffer();
signatures.push(metadata_signature);
}
return signatures;
}
function decodeBlockDataEnvelope(proto_envelope) {
var envelope = {};
envelope.signature = proto_envelope.getSignature().toBuffer(); //leave as bytes
envelope.payload = {};
var proto_payload = _commonProto.Payload.decode(proto_envelope.getPayload().toBuffer());
envelope.payload.header = decodeHeader(proto_payload.getHeader());
envelope.payload.data = HeaderType.decodePayloadBasedOnType(proto_payload.getData().toBuffer(), envelope.payload.header.channel_header.type);
// let's also have the type as the enum string value so it is easier to read
envelope.payload.header.channel_header.typeString = HeaderType.convertToString(envelope.payload.header.channel_header.type);
return envelope;
}
function decodeEndorserTransaction(trans_bytes) {
var data = {};
try {
var transaction = _transProto.Transaction.decode(trans_bytes);
data.actions = [];
if (transaction && transaction.actions) {
for (let i in transaction.actions) {
var action = {};
action.header = decodeSignatureHeader(transaction.actions[i].header);
action.payload = decodeChaincodeActionPayload(transaction.actions[i].payload);
data.actions.push(action);
}
}
} catch(error) {
logger.error(' Unable to decodeEndorserTransaction :: %s',error);
}
return data;
}
function decodeConfigEnvelope(config_envelope_bytes) {
var config_envelope = {};
var proto_config_envelope = _configtxProto.ConfigEnvelope.decode(config_envelope_bytes);
config_envelope.config = decodeConfig(proto_config_envelope.getConfig());
logger.debug('decodeConfigEnvelope - decode complete for config envelope - start config update');
config_envelope.last_update = {};
var proto_last_update = proto_config_envelope.getLastUpdate(); //this is a common.Envelope
if (proto_last_update !== null) { // the orderer's genesis block may not have this field
config_envelope.last_update.payload = {};
var proto_payload = _commonProto.Payload.decode(proto_last_update.getPayload().toBuffer());
config_envelope.last_update.payload.header = decodeHeader(proto_payload.getHeader());
config_envelope.last_update.payload.data = decodeConfigUpdateEnvelope(proto_payload.getData().toBuffer());
config_envelope.last_update.signature = proto_last_update.getSignature().toBuffer(); //leave as bytes
}
return config_envelope;
}
function decodeConfig(proto_config) {
var config = {};
config.sequence = proto_config.getSequence().toString(); //unit64
config.channel_group = decodeConfigGroup(proto_config.getChannelGroup());
config.type = proto_config.getType();
return config;
}
function decodeConfigUpdateEnvelope(config_update_envelope_bytes) {
var config_update_envelope = {};
var proto_config_update_envelope = _configtxProto.ConfigUpdateEnvelope.decode(config_update_envelope_bytes);
config_update_envelope.config_update = decodeConfigUpdate(proto_config_update_envelope.getConfigUpdate().toBuffer());
var signatures = [];
for (var i in proto_config_update_envelope.signatures) {
let proto_configSignature = proto_config_update_envelope.signatures[i];
var config_signature = decodeConfigSignature(proto_configSignature);
signatures.push(config_signature);
}
config_update_envelope.signatures = signatures;
return config_update_envelope;
}
function decodeConfigUpdate(config_update_bytes) {
var config_update = {};
var proto_config_update = _configtxProto.ConfigUpdate.decode(config_update_bytes);
config_update.channel_id = proto_config_update.getChannelId();
config_update.read_set = decodeConfigGroup(proto_config_update.getReadSet());
config_update.write_set = decodeConfigGroup(proto_config_update.getWriteSet());
config_update.type = proto_config_update.getType();
return config_update;
}
function decodeConfigGroups(config_group_map) {
var config_groups = {};
var keys = Object.keys(config_group_map.map);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
config_groups[key] = decodeConfigGroup(config_group_map.map[key].value);
}
return config_groups;
}
function decodeConfigGroup(proto_config_group) {
if (!proto_config_group) return null;
var config_group = {};
config_group.version = decodeVersion(proto_config_group.getVersion());
config_group.groups = decodeConfigGroups(proto_config_group.getGroups());
config_group.values = decodeConfigValues(proto_config_group.getValues());
config_group.policies = decodeConfigPolicies(proto_config_group.getPolicies());
config_group.mod_policy = proto_config_group.getModPolicy(); //string
return config_group;
}
function decodeConfigValues(config_value_map) {
var config_values = {};
var keys = Object.keys(config_value_map.map);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
config_values[key] = decodeConfigValue(config_value_map.map[key]);
}
return config_values;
}
function decodeConfigValue(proto_config_value) {
var config_value = {};
logger.debug(' ======> Config item ::%s', proto_config_value.key);
config_value.version = decodeVersion(proto_config_value.value.getVersion());
config_value.mod_policy = proto_config_value.value.getModPolicy();
config_value.value = {};
switch(proto_config_value.key) {
case 'AnchorPeers':
var anchor_peers = [];
var proto_anchor_peers = _peerConfigurationProto.AnchorPeers.decode(proto_config_value.value.value);
if(proto_anchor_peers && proto_anchor_peers.anchor_peers) for(var i in proto_anchor_peers.anchor_peers) {
var anchor_peer = {
host : proto_anchor_peers.anchor_peers[i].host,
port : proto_anchor_peers.anchor_peers[i].port
};
anchor_peers.push(anchor_peer);
}
config_value.value.anchor_peers = anchor_peers;
break;
case 'MSP':
var msp_config = {};
var proto_msp_config = _mspConfigProto.MSPConfig.decode(proto_config_value.value.value);
if(proto_msp_config.getType() == 0) {
msp_config = decodeFabricMSPConfig(proto_msp_config.getConfig());
}
config_value.value.type = proto_msp_config.type;
config_value.value.config = msp_config;
break;
case 'ConsensusType':
var proto_consensus_type = _ordererConfigurationProto.ConsensusType.decode(proto_config_value.value.value);
config_value.value.type = proto_consensus_type.getType(); // string
break;
case 'BatchSize':
var proto_batch_size = _ordererConfigurationProto.BatchSize.decode(proto_config_value.value.value);
config_value.value.max_message_count = proto_batch_size.getMaxMessageCount(); //uint32
config_value.value.absolute_max_bytes = proto_batch_size.getAbsoluteMaxBytes(); //uint32
config_value.value.preferred_max_bytes = proto_batch_size.getPreferredMaxBytes(); //uint32
break;
case 'BatchTimeout':
var proto_batch_timeout = _ordererConfigurationProto.BatchTimeout.decode(proto_config_value.value.value);
config_value.value.timeout = proto_batch_timeout.getTimeout(); //string
break;
case 'ChannelRestrictions':
var proto_channel_restrictions = _ordererConfigurationProto.ChannelRestrictions.decode(proto_config_value.value.value);
config_value.value.max_count = proto_channel_restrictions.getMaxCount().toString(); //unit64
break;
case 'Consortium':
var consortium_name = _commonConfigurationProto.Consortium.decode(proto_config_value.value.value);
config_value.value.name = consortium_name.getName(); //string
break;
case 'HashingAlgorithm':
var proto_hashing_algorithm = _commonConfigurationProto.HashingAlgorithm.decode(proto_config_value.value.value);
config_value.value.name = proto_hashing_algorithm.getName();
break;
case 'BlockDataHashingStructure':
var proto_blockdata_hashing_structure = _commonConfigurationProto.BlockDataHashingStructure.decode(proto_config_value.value.value);
config_value.value.width = proto_blockdata_hashing_structure.getWidth(); //
break;
case 'OrdererAddresses':
var orderer_addresses = _commonConfigurationProto.OrdererAddresses.decode(proto_config_value.value.value);
var addresses = [];
var proto_addresses = orderer_addresses.getAddresses();
if(proto_addresses) for(let i in proto_addresses) {
addresses.push(proto_addresses[i]); //string
}
config_value.value.addresses = addresses;
break;
default:
// logger.debug('loadConfigValue - %s - value: %s', group_name, config_value.value.value);
}
return config_value;
}
function decodeConfigPolicies(config_policy_map) {
var config_policies = {};
var keys = Object.keys(config_policy_map.map);
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
config_policies[key] = decodeConfigPolicy(config_policy_map.map[key]);
}
return config_policies;
}
var Policy_PolicyType = ['UNKNOWN', 'SIGNATURE', 'MSP', 'IMPLICIT_META'];
function decodeConfigPolicy(proto_config_policy) {
var config_policy = {};
config_policy.version = decodeVersion(proto_config_policy.value.getVersion());
config_policy.mod_policy = proto_config_policy.value.getModPolicy();
config_policy.policy = {};
if (proto_config_policy.value.policy) {
config_policy.policy.type = Policy_PolicyType[proto_config_policy.value.policy.type];
logger.debug('decodeConfigPolicy ======> Policy item ::%s', proto_config_policy.key);
switch (proto_config_policy.value.policy.type) {
case _policiesProto.Policy.PolicyType.SIGNATURE:
config_policy.policy.value = decodeSignaturePolicyEnvelope(proto_config_policy.value.policy.value);
break;
case _policiesProto.Policy.PolicyType.MSP:
var proto_msp = _policiesProto.Policy.decode(proto_config_policy.value.policy.value);
logger.warn('decodeConfigPolicy - found a PolicyType of MSP. This policy type has not been implemented yet.');
break;
case _policiesProto.Policy.PolicyType.IMPLICIT_META:
config_policy.policy.value = decodeImplicitMetaPolicy(proto_config_policy.value.policy.value);
break;
default:
throw new Error('Unknown Policy type');
}
}
return config_policy;
}
var ImplicitMetaPolicy_Rule = ['ANY', 'ALL', 'MAJORITY'];
function decodeImplicitMetaPolicy(implicit_meta_policy_bytes) {
var implicit_meta_policy = {};
var proto_implicit_meta_policy = _policiesProto.ImplicitMetaPolicy.decode(implicit_meta_policy_bytes);
implicit_meta_policy.sub_policy = proto_implicit_meta_policy.getSubPolicy();
implicit_meta_policy.rule = ImplicitMetaPolicy_Rule[proto_implicit_meta_policy.getRule()];
return implicit_meta_policy;
}
function decodeSignaturePolicyEnvelope(signature_policy_envelope_bytes) {
var signature_policy_envelope = {};
var proto_signature_policy_envelope = _policiesProto.SignaturePolicyEnvelope.decode(signature_policy_envelope_bytes);
signature_policy_envelope.version = decodeVersion(proto_signature_policy_envelope.getVersion());
signature_policy_envelope.rule = decodeSignaturePolicy(proto_signature_policy_envelope.getRule());
var identities = [];
var proto_identities = proto_signature_policy_envelope.getIdentities();
if (proto_identities)
for (var i in proto_identities) {
var msp_principal = decodeMSPPrincipal(proto_identities[i]);
identities.push(msp_principal); //string
}
signature_policy_envelope.identities = identities;
return signature_policy_envelope;
}
function decodeSignaturePolicy(proto_signature_policy) {
var signature_policy = {};
signature_policy.Type = proto_signature_policy.Type;
if (signature_policy.Type == 'n_out_of') {
signature_policy.n_out_of = {};
signature_policy.n_out_of.N = proto_signature_policy.n_out_of.getN();
signature_policy.n_out_of.rules = [];
for (var i in proto_signature_policy.n_out_of.rules) {
var proto_policy = proto_signature_policy.n_out_of.rules[i];
var policy = decodeSignaturePolicy(proto_policy);
signature_policy.n_out_of.rules.push(policy);
}
} else if (signature_policy.Type == 'signed_by') {
signature_policy.signed_by = proto_signature_policy.getSignedBy();
} else {
throw new Error('unknown signature policy type');
}
return signature_policy;
}
function decodeMSPPrincipal(proto_msp_principal) {
var msp_principal = {};
msp_principal.principal_classification = proto_msp_principal.getPrincipalClassification();
var proto_principal = null;
switch (msp_principal.principal_classification) {
case _mspPrProto.MSPPrincipal.Classification.ROLE:
proto_principal = _mspPrProto.MSPRole.decode(proto_msp_principal.getPrincipal());
msp_principal.msp_identifier = proto_principal.getMspIdentifier();
if (proto_principal.getRole() === 0) {
msp_principal.Role = 'MEMBER';
} else if (proto_principal.getRole() === 1) {
msp_principal.Role = 'ADMIN';
}
break;
case _mspPrProto.MSPPrincipal.Classification.ORGANIZATION_UNIT:
proto_principal = _mspPrProto.OrganizationUnit.decode(proto_msp_principal.getPrincipal());
msp_principal.msp_identifier = proto_principal.getMspIdentifier(); //string
msp_principal.organizational_unit_identifier = proto_principal.getOrganizationalUnitIdentifier(); //string
msp_principal.certifiers_identifier = proto_principal.getCertifiersIdentifier().toBuffer(); //bytes
break;
case _mspPrProto.MSPPrincipal.Classification.IDENTITY:
msp_principal = decodeIdentity(proto_msp_principal.getPrincipal());
break;
}
return msp_principal;
}
function decodeConfigSignature(proto_configSignature) {
var config_signature = {};
config_signature.signature_header = decodeSignatureHeader(proto_configSignature.getSignatureHeader().toBuffer());
config_signature.sigature = proto_configSignature.getSignature().toBuffer();
return config_signature;
}
function decodeSignatureHeader(signature_header_bytes) {
//logger.debug('decodeSignatureHeader - %s',signature_header_bytes);
var signature_header = {};
var proto_signature_header = _commonProto.SignatureHeader.decode(signature_header_bytes);
signature_header.creator = decodeIdentity(proto_signature_header.getCreator().toBuffer());
signature_header.nonce = proto_signature_header.getNonce().toBuffer();
return signature_header;
}
function decodeIdentity(id_bytes) {
//logger.debug('decodeIdentity - %s',id_bytes);
var identity = {};
try {
var proto_identity = _identityProto.SerializedIdentity.decode(id_bytes);
identity.Mspid = proto_identity.getMspid();
identity.IdBytes = proto_identity.getIdBytes().toBuffer().toString();
} catch (err) {
logger.error('Failed to decode the identity: %s', err.stack ? err.stack : err);
}
return identity;
}
function decodeFabricMSPConfig(msp_config_bytes) {
var msp_config = {};
var proto_msp_config = _mspConfigProto.FabricMSPConfig.decode(msp_config_bytes);
msp_config.name = proto_msp_config.getName();
msp_config.root_certs = toPEMcerts(proto_msp_config.getRootCerts());
msp_config.intermediate_certs = toPEMcerts(proto_msp_config.getIntermediateCerts());
msp_config.admins = toPEMcerts(proto_msp_config.getAdmins());
msp_config.revocation_list = toPEMcerts(proto_msp_config.getRevocationList());
msp_config.signing_identity = decodeSigningIdentityInfo(proto_msp_config.getSigningIdentity());
msp_config.organizational_unit_identifiers = decodeFabricOUIdentifier(proto_msp_config.getOrganizationalUnitIdentifiers());
msp_config.tls_root_certs = toPEMcerts(proto_msp_config.getTlsRootCerts());
msp_config.tls_intermediate_certs = toPEMcerts(proto_msp_config.getTlsIntermediateCerts());
return msp_config;
}
function decodeFabricOUIdentifier(proto_organizational_unit_identitfiers) {