forked from hyperledger/fabric-config
/
config.go
641 lines (531 loc) · 18.4 KB
/
config.go
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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
// Package configtx provides utilities to create and modify a channel configuration transaction.
// Channel transactions contain the configuration data defining members and policies for a
// system or application channel and can be used to either create or modify existing channels.
// Both the creation of a new channel or modification of an existing channel outputs an unsigned
// transaction represented in a protobuf binary format that must be signed by the requisite number
// of members such that the transaction fulfills the channel's modification policy.
//
// See https://hyperledger-fabric.readthedocs.io/en/master/configtx.html#anatomy-of-a-configuration
// for an in-depth description of channel configuration's anatomy.
package configtx
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
cb "github.com/ZihuaZhang/fabric-protos-go/common"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
mb "github.com/hyperledger/fabric-protos-go/msp"
)
// Channel is a channel configuration.
type Channel struct {
Consortium string
Application Application
Orderer Orderer
Consortiums []Consortium
Capabilities []string
Policies map[string]Policy
ModPolicy string
}
// Policy is an expression used to define rules for access to channels, chaincodes, etc.
type Policy struct {
Type string
Rule string
ModPolicy string
}
// Organization is an organization in the channel configuration.
type Organization struct {
Name string
Policies map[string]Policy
MSP MSP
// AnchorPeers contains the endpoints of anchor peers for each
// application organization.
AnchorPeers []Address
OrdererEndpoints []string
ModPolicy string
}
// Address contains the hostname and port for an endpoint.
type Address struct {
Host string
Port int
}
type standardConfigValue struct {
key string
value proto.Message
}
type standardConfigPolicy struct {
key string
value *cb.Policy
}
// ConfigTx wraps a config transaction.
type ConfigTx struct {
// original state of the config
original *cb.Config
// modified state of the config
updated *cb.Config
}
// New creates a new ConfigTx from a Config protobuf.
// New will panic if given an empty config.
func New(config *cb.Config) ConfigTx {
return ConfigTx{
original: config,
// Clone the base config for processing updates
updated: proto.Clone(config).(*cb.Config),
}
}
// OriginalConfig returns the original unedited config.
func (c *ConfigTx) OriginalConfig() *cb.Config {
return c.original
}
// UpdatedConfig returns the modified config.
func (c *ConfigTx) UpdatedConfig() *cb.Config {
return c.updated
}
// ComputeMarshaledUpdate computes the ConfigUpdate from a base and modified
// config transaction and returns the marshaled bytes.
func (c *ConfigTx) ComputeMarshaledUpdate(channelID string) ([]byte, error) {
if channelID == "" {
return nil, errors.New("channel ID is required")
}
update, err := computeConfigUpdate(c.original, c.updated)
if err != nil {
return nil, fmt.Errorf("failed to compute update: %v", err)
}
update.ChannelId = channelID
marshaledUpdate, err := proto.Marshal(update)
if err != nil {
return nil, fmt.Errorf("marshaling config update: %v", err)
}
return marshaledUpdate, nil
}
// NewEnvelope creates an envelope with the provided marshaled config update
// and config signatures.
func NewEnvelope(marshaledUpdate []byte, signatures ...*cb.ConfigSignature) (*cb.Envelope, error) {
configUpdateEnvelope := &cb.ConfigUpdateEnvelope{
ConfigUpdate: marshaledUpdate,
Signatures: signatures,
}
c := &cb.ConfigUpdate{}
err := proto.Unmarshal(marshaledUpdate, c)
if err != nil {
return nil, fmt.Errorf("unmarshaling config update: %v", err)
}
envelope, err := newEnvelope(cb.HeaderType_CONFIG_UPDATE, c.ChannelId, configUpdateEnvelope)
if err != nil {
return nil, err
}
return envelope, nil
}
// NewMarshaledCreateChannelTx creates a create channel config update
// transaction using the provided application channel configuration and returns
// the marshaled bytes.
func NewMarshaledCreateChannelTx(channelConfig Channel, channelID string) ([]byte, error) {
if channelID == "" {
return nil, errors.New("profile's channel ID is required")
}
ct, err := defaultConfigTemplate(channelConfig)
if err != nil {
return nil, fmt.Errorf("creating default config template: %v", err)
}
update, err := newChannelCreateConfigUpdate(channelID, channelConfig, ct)
if err != nil {
return nil, fmt.Errorf("creating channel create config update: %v", err)
}
marshaledUpdate, err := proto.Marshal(update)
if err != nil {
return nil, fmt.Errorf("marshaling config update: %v", err)
}
return marshaledUpdate, nil
}
// NewSystemChannelGenesisBlock creates a genesis block using the provided
// consortiums and orderer configuration and returns a block.
func NewSystemChannelGenesisBlock(channelConfig Channel, channelID string) (*cb.Block, error) {
if channelID == "" {
return nil, errors.New("system channel ID is required")
}
systemChannelGroup, err := newSystemChannelGroup(channelConfig)
if err != nil {
return nil, fmt.Errorf("creating system channel group: %v", err)
}
block, err := newGenesisBlock(systemChannelGroup, channelID)
if err != nil {
return nil, fmt.Errorf("creating system channel genesis block: %v", err)
}
return block, nil
}
// NewApplicationChannelGenesisBlock creates a genesis block using the provided
// application and orderer configuration and returns a block.
func NewApplicationChannelGenesisBlock(channelConfig Channel, channelID string) (*cb.Block, error) {
if channelID == "" {
return nil, errors.New("application channel ID is required")
}
applicationChannelGroup, err := newApplicationChannelGroup(channelConfig)
if err != nil {
return nil, fmt.Errorf("creating application channel group: %v", err)
}
block, err := newGenesisBlock(applicationChannelGroup, channelID)
if err != nil {
return nil, fmt.Errorf("creating application channel genesis block: %v", err)
}
return block, nil
}
// newSystemChannelGroup defines the root of the system channel configuration.
func newSystemChannelGroup(channelConfig Channel) (*cb.ConfigGroup, error) {
channelGroup, err := newChannelGroupWithOrderer(channelConfig)
if err != nil {
return nil, err
}
consortiumsGroup, err := newConsortiumsGroup(channelConfig.Consortiums)
if err != nil {
return nil, err
}
channelGroup.Groups[ConsortiumsGroupKey] = consortiumsGroup
channelGroup.ModPolicy = AdminsPolicyKey
if channelConfig.ModPolicy != "" {
channelGroup.ModPolicy = channelConfig.ModPolicy
}
return channelGroup, nil
}
// newApplicationChannelGroup defines the root of the application
// channel configuration.
func newApplicationChannelGroup(channelConfig Channel) (*cb.ConfigGroup, error) {
channelGroup, err := newChannelGroupWithOrderer(channelConfig)
if err != nil {
return nil, err
}
applicationGroup, err := newApplicationGroup(channelConfig.Application)
if err != nil {
return nil, err
}
channelGroup.Groups[ApplicationGroupKey] = applicationGroup
channelGroup.ModPolicy = AdminsPolicyKey
if channelConfig.ModPolicy != "" {
channelGroup.ModPolicy = channelConfig.ModPolicy
}
return channelGroup, nil
}
func newChannelGroupWithOrderer(channelConfig Channel) (*cb.ConfigGroup, error) {
channelGroup := newConfigGroup()
err := setPolicies(channelGroup, channelConfig.Policies)
if err != nil {
return nil, fmt.Errorf("setting channel policies: %v", err)
}
err = setValue(channelGroup, hashingAlgorithmValue(), AdminsPolicyKey)
if err != nil {
return nil, err
}
err = setValue(channelGroup, blockDataHashingStructureValue(), AdminsPolicyKey)
if err != nil {
return nil, err
}
if len(channelConfig.Capabilities) == 0 {
return nil, errors.New("capabilities is not defined in channel config")
}
err = setValue(channelGroup, capabilitiesValue(channelConfig.Capabilities), AdminsPolicyKey)
if err != nil {
return nil, err
}
ordererGroup, err := newOrdererGroup(channelConfig.Orderer)
if err != nil {
return nil, err
}
channelGroup.Groups[OrdererGroupKey] = ordererGroup
return channelGroup, nil
}
// newGenesisBlock generates a genesis block from the config group and
// channel ID. The block number is always zero.
func newGenesisBlock(cg *cb.ConfigGroup, channelID string) (*cb.Block, error) {
payloadChannelHeader := channelHeader(cb.HeaderType_CONFIG, msgVersion, channelID, epoch)
nonce, err := newNonce()
if err != nil {
return nil, fmt.Errorf("creating nonce: %v", err)
}
payloadSignatureHeader := &cb.SignatureHeader{Creator: nil, Nonce: nonce}
payloadChannelHeader.TxId = computeTxID(payloadSignatureHeader.Nonce, payloadSignatureHeader.Creator)
payloadHeader, err := payloadHeader(payloadChannelHeader, payloadSignatureHeader)
if err != nil {
return nil, fmt.Errorf("construct payload header: %v", err)
}
payloadData, err := proto.Marshal(&cb.ConfigEnvelope{Config: &cb.Config{ChannelGroup: cg}})
if err != nil {
return nil, fmt.Errorf("marshaling payload data: %v", err)
}
payload := &cb.Payload{Header: payloadHeader, Data: payloadData}
envelopePayload, err := proto.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("marshaling envelope payload: %v", err)
}
envelope := &cb.Envelope{Payload: envelopePayload, Signature: nil}
blockData, err := proto.Marshal(envelope)
if err != nil {
return nil, fmt.Errorf("marshaling envelope: %v", err)
}
block := newBlock(0, nil)
block.Data = &cb.BlockData{Data: [][]byte{blockData}}
block.Header.DataHash = blockDataHash(block.Data)
lastConfigValue, err := proto.Marshal(&cb.LastConfig{Index: 0})
if err != nil {
return nil, fmt.Errorf("marshaling metadata last config value: %v", err)
}
lastConfigMetadata, err := proto.Marshal(&cb.Metadata{Value: lastConfigValue})
if err != nil {
return nil, fmt.Errorf("marshaling metadata last config: %v", err)
}
block.Metadata.Metadata[cb.BlockMetadataIndex_LAST_CONFIG] = lastConfigMetadata
signatureValue, err := proto.Marshal(&cb.OrdererBlockMetadata{
LastConfig: &cb.LastConfig{Index: 0},
})
if err != nil {
return nil, fmt.Errorf("marshaling metadata signature value: %v", err)
}
signatureMetadata, err := proto.Marshal(&cb.Metadata{Value: signatureValue})
if err != nil {
return nil, fmt.Errorf("marshaling metadata signature: %v", err)
}
block.Metadata.Metadata[cb.BlockMetadataIndex_SIGNATURES] = signatureMetadata
return block, nil
}
// setValue sets the value as ConfigValue in the ConfigGroup.
func setValue(cg *cb.ConfigGroup, value *standardConfigValue, modPolicy string) error {
v, err := proto.Marshal(value.value)
if err != nil {
return fmt.Errorf("marshaling standard config value '%s': %v", value.key, err)
}
if cg.Values == nil {
cg.Values = map[string]*cb.ConfigValue{}
}
cg.Values[value.key] = &cb.ConfigValue{
Value: v,
ModPolicy: modPolicy,
}
return nil
}
// implicitMetaFromString parses a *cb.ImplicitMetaPolicy from an input string.
func implicitMetaFromString(input string) (*cb.ImplicitMetaPolicy, error) {
args := strings.Split(input, " ")
if len(args) != 2 {
return nil, fmt.Errorf("expected two space separated tokens, but got %d", len(args))
}
res := &cb.ImplicitMetaPolicy{
SubPolicy: args[1],
}
switch args[0] {
case cb.ImplicitMetaPolicy_ANY.String():
res.Rule = cb.ImplicitMetaPolicy_ANY
case cb.ImplicitMetaPolicy_ALL.String():
res.Rule = cb.ImplicitMetaPolicy_ALL
case cb.ImplicitMetaPolicy_MAJORITY.String():
res.Rule = cb.ImplicitMetaPolicy_MAJORITY
default:
return nil, fmt.Errorf("unknown rule type '%s', expected ALL, ANY, or MAJORITY", args[0])
}
return res, nil
}
// mspValue returns the config definition for an MSP.
// It is a value for the /Channel/Orderer/*, /Channel/Application/*, and /Channel/Consortiums/*/*/* groups.
func mspValue(mspDef *mb.MSPConfig) *standardConfigValue {
return &standardConfigValue{
key: MSPKey,
value: mspDef,
}
}
// defaultConfigTemplate generates a config template based on the assumption that
// the input profile is a channel creation template and no system channel context
// is available.
func defaultConfigTemplate(channelConfig Channel) (*cb.ConfigGroup, error) {
channelGroup, err := newChannelGroup(channelConfig)
if err != nil {
return nil, err
}
if _, ok := channelGroup.Groups[ApplicationGroupKey]; !ok {
return nil, errors.New("channel template config must contain an application section")
}
channelGroup.Groups[ApplicationGroupKey].Values = nil
channelGroup.Groups[ApplicationGroupKey].Policies = nil
return channelGroup, nil
}
// newChannelGroup defines the root of the channel configuration.
func newChannelGroup(channelConfig Channel) (*cb.ConfigGroup, error) {
channelGroup := newConfigGroup()
if channelConfig.Consortium == "" {
return nil, errors.New("consortium is not defined in channel config")
}
err := setValue(channelGroup, consortiumValue(channelConfig.Consortium), "")
if err != nil {
return nil, err
}
channelGroup.Groups[ApplicationGroupKey], err = newApplicationGroupTemplate(channelConfig.Application)
if err != nil {
return nil, fmt.Errorf("failed to create application group: %v", err)
}
channelGroup.ModPolicy = AdminsPolicyKey
if channelConfig.ModPolicy != "" {
channelGroup.ModPolicy = channelConfig.ModPolicy
}
return channelGroup, nil
}
// newChannelCreateConfigUpdate generates a ConfigUpdate which can be sent to the orderer to create a new channel.
// Optionally, the channel group of the ordering system channel may be passed in, and the resulting ConfigUpdate
// will extract the appropriate versions from this file.
func newChannelCreateConfigUpdate(channelID string, channelConfig Channel, templateConfig *cb.ConfigGroup) (*cb.ConfigUpdate, error) {
newChannelGroup, err := newChannelGroup(channelConfig)
if err != nil {
return nil, err
}
updt, err := computeConfigUpdate(&cb.Config{ChannelGroup: templateConfig}, &cb.Config{ChannelGroup: newChannelGroup})
if err != nil {
return nil, fmt.Errorf("computing update: %v", err)
}
wsValue, err := proto.Marshal(&cb.Consortium{
Name: channelConfig.Consortium,
})
if err != nil {
return nil, fmt.Errorf("marshaling consortium: %v", err)
}
// Add the consortium name to create the channel for into the write set as required
updt.ChannelId = channelID
updt.ReadSet.Values[ConsortiumKey] = &cb.ConfigValue{Version: 0}
updt.WriteSet.Values[ConsortiumKey] = &cb.ConfigValue{
Version: 0,
Value: wsValue,
}
return updt, nil
}
// newConfigGroup creates an empty *cb.ConfigGroup.
func newConfigGroup() *cb.ConfigGroup {
return &cb.ConfigGroup{
Groups: map[string]*cb.ConfigGroup{},
Values: map[string]*cb.ConfigValue{},
Policies: map[string]*cb.ConfigPolicy{},
}
}
// newEnvelope creates an unsigned envelope of the desired type containing
// a payload Header and the marshaled proto message as the payload Data.
func newEnvelope(
txType cb.HeaderType,
channelID string,
dataMsg proto.Message,
) (*cb.Envelope, error) {
payloadChannelHeader := channelHeader(txType, msgVersion, channelID, epoch)
payloadSignatureHeader := &cb.SignatureHeader{}
data, err := proto.Marshal(dataMsg)
if err != nil {
return nil, fmt.Errorf("marshaling envelope data: %v", err)
}
payloadHeader, err := payloadHeader(payloadChannelHeader, payloadSignatureHeader)
if err != nil {
return nil, fmt.Errorf("making payload header: %v", err)
}
paylBytes, err := proto.Marshal(
&cb.Payload{
Header: payloadHeader,
Data: data,
},
)
if err != nil {
return nil, fmt.Errorf("marshaling payload: %v", err)
}
env := &cb.Envelope{
Payload: paylBytes,
}
return env, nil
}
// channelHeader creates a ChannelHeader.
func channelHeader(headerType cb.HeaderType, version int32, channelID string, epoch uint64) *cb.ChannelHeader {
return &cb.ChannelHeader{
Type: int32(headerType),
Version: version,
Timestamp: ×tamp.Timestamp{
Seconds: ptypes.TimestampNow().GetSeconds(),
},
ChannelId: channelID,
Epoch: epoch,
}
}
// payloadHeader creates a Payload Header.
func payloadHeader(ch *cb.ChannelHeader, sh *cb.SignatureHeader) (*cb.Header, error) {
channelHeader, err := proto.Marshal(ch)
if err != nil {
return nil, fmt.Errorf("marshaling channel header: %v", err)
}
signatureHeader, err := proto.Marshal(sh)
if err != nil {
return nil, fmt.Errorf("marshaling signature header: %v", err)
}
return &cb.Header{
ChannelHeader: channelHeader,
SignatureHeader: signatureHeader,
}, nil
}
// concatenateBytes combines multiple arrays of bytes, for signatures or digests
// over multiple fields.
func concatenateBytes(data ...[]byte) []byte {
res := []byte{}
for i := range data {
res = append(res, data[i]...)
}
return res
}
// unmarshalConfigValueAtKey unmarshals the value for the specified key in a config group
// into the designated proto message.
func unmarshalConfigValueAtKey(group *cb.ConfigGroup, key string, msg proto.Message) error {
valueAtKey, ok := group.Values[key]
if !ok {
return fmt.Errorf("config does not contain value for %s", key)
}
err := proto.Unmarshal(valueAtKey.Value, msg)
if err != nil {
return fmt.Errorf("unmarshaling %s: %v", key, err)
}
return nil
}
func parseAddress(address string) (string, int, error) {
hostport := strings.Split(address, ":")
if len(hostport) != 2 {
return "", 0, fmt.Errorf("unable to parse host and port from %s", address)
}
host := hostport[0]
port := hostport[1]
portNum, err := strconv.Atoi(port)
if err != nil {
return "", 0, err
}
return host, portNum, nil
}
// newBlock constructs a block with no data and no metadata.
func newBlock(seqNum uint64, previousHash []byte) *cb.Block {
block := &cb.Block{}
block.Header = &cb.BlockHeader{}
block.Header.Number = seqNum
block.Header.PreviousHash = previousHash
block.Header.DataHash = []byte{}
block.Data = &cb.BlockData{}
var metadataContents [][]byte
for i := 0; i < len(cb.BlockMetadataIndex_name); i++ {
metadataContents = append(metadataContents, []byte{})
}
block.Metadata = &cb.BlockMetadata{Metadata: metadataContents}
return block
}
// computeTxID computes TxID as the Hash computed
// over the concatenation of nonce and creator.
func computeTxID(nonce, creator []byte) string {
hasher := sha256.New()
hasher.Write(nonce)
hasher.Write(creator)
return hex.EncodeToString(hasher.Sum(nil))
}
// blockDataHash computes block data as the Hash
func blockDataHash(b *cb.BlockData) []byte {
sum := sha256.Sum256(bytes.Join(b.Data, nil))
return sum[:]
}