/
channel.go
executable file
·672 lines (608 loc) · 27.2 KB
/
channel.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
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
package utilities
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
mspclient "github.com/hyperledger/fabric-sdk-go/pkg/client/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
"github.com/hyperledger/fabric/protos/common"
"github.com/pkg/errors"
"github.com/xixuejia/digital-wallet/fabric/gosdk/channel/utilities/configtxlator"
hfrdcommon "github.com/xixuejia/digital-wallet/fabric/gosdk/common"
)
const (
REPLACE_ORDERER_ADDRESS = "replace"
ADD_ORDERER_ADDRESS = "add"
REMOVE_ORDERER_ADDRESS = "remove"
)
// CreatChannelTxEnvelope is used to build channel creation envelope
func CreatChannelTxEnvelope(applicationCapability string, channelId string, consortiumName string, mspIds ...string) ([]byte, error) {
configUpdate := &common.ConfigUpdate{}
configUpdate.ChannelId = channelId
readSet := &common.ConfigGroup{}
readSet.Version = 0
readSet.Values = map[string]*common.ConfigValue{}
readSet.Values["Consortium"] = &common.ConfigValue{}
readSet.Groups = map[string]*common.ConfigGroup{}
readSet.Groups["Application"] = &common.ConfigGroup{}
readSet.Groups["Application"].Groups = map[string]*common.ConfigGroup{}
for _, mspId := range mspIds {
readSet.Groups["Application"].Groups[mspId] = &common.ConfigGroup{}
}
configUpdate.ReadSet = readSet
writeSet := &common.ConfigGroup{}
writeSet.Values = map[string]*common.ConfigValue{}
writeSet.Values["Consortium"] = &common.ConfigValue{}
consortium := &common.Consortium{}
consortium.Name = consortiumName
consortiumBytes, err := proto.Marshal(consortium)
if err != nil {
return nil, err
}
writeSet.Values["Consortium"].Value = consortiumBytes
writeSet.Groups = map[string]*common.ConfigGroup{}
writeSet.Groups["Application"] = &common.ConfigGroup{}
writeSet.Groups["Application"].Version = 1
writeSet.Groups["Application"].Groups = map[string]*common.ConfigGroup{}
for _, mspId := range mspIds {
writeSet.Groups["Application"].Groups[mspId] = &common.ConfigGroup{}
}
writeSet.Groups["Application"].ModPolicy = "Admins"
writeSet.Groups["Application"].Policies = map[string]*common.ConfigPolicy{}
// Admins
writeSet.Groups["Application"].Policies["Admins"] = &common.ConfigPolicy{}
writeSet.Groups["Application"].Policies["Admins"].ModPolicy = "Admins"
adminsPolicy, err := makeImplicitMetaPolicy("Admins", common.ImplicitMetaPolicy_MAJORITY)
if err != nil {
return nil, err
}
writeSet.Groups["Application"].Policies["Admins"].Policy = adminsPolicy
// Readers
readersPolicy, err := makeImplicitMetaPolicy("Readers", common.ImplicitMetaPolicy_ANY)
if err != nil {
return nil, err
}
writeSet.Groups["Application"].Policies["Readers"] = &common.ConfigPolicy{}
writeSet.Groups["Application"].Policies["Readers"].ModPolicy = "Admins"
writeSet.Groups["Application"].Policies["Readers"].Policy = readersPolicy
// Writers
writersPolicy, err := makeImplicitMetaPolicy("Writers", common.ImplicitMetaPolicy_ANY)
if err != nil {
return nil, err
}
writeSet.Groups["Application"].Policies["Writers"] = &common.ConfigPolicy{}
writeSet.Groups["Application"].Policies["Writers"].ModPolicy = "Admins"
writeSet.Groups["Application"].Policies["Writers"].Policy = writersPolicy
capabilities := &common.Capabilities{
Capabilities: make(map[string]*common.Capability),
}
// Set Application Capability to V1_2 to enable private data
if !strings.Contains(applicationCapability, "1_1") {
capabilities.Capabilities["V1_2"] = &common.Capability{}
}
capBytes, err := proto.Marshal(capabilities)
if err != nil {
return nil, err
}
writeSet.Groups["Application"].Values = make(map[string]*common.ConfigValue)
writeSet.Groups["Application"].Values["Capabilities"] = &common.ConfigValue{}
writeSet.Groups["Application"].Values["Capabilities"].ModPolicy = "Admins"
writeSet.Groups["Application"].Values["Capabilities"].Value = capBytes
writeSet.Version = 0
configUpdate.WriteSet = writeSet
var configUpdateBytes []byte
if configUpdateBytes, err = proto.Marshal(configUpdate); err != nil {
return nil, err
}
configUpdateEnv := &common.ConfigUpdateEnvelope{
ConfigUpdate: configUpdateBytes,
}
//channel header
chHeader := &common.ChannelHeader{
Type: int32(common.HeaderType_CONFIG_UPDATE),
Version: int32(0),
Timestamp: ×tamp.Timestamp{
Seconds: time.Now().Unix(),
Nanos: 0,
},
ChannelId: channelId,
Epoch: uint64(0),
}
var chHeaderBytes []byte
var payloadBytes []byte
if chHeaderBytes, err = proto.Marshal(chHeader); err != nil {
return nil, err
}
header := &common.Header{
ChannelHeader: chHeaderBytes,
}
if dataBytes, err := proto.Marshal(configUpdateEnv); err != nil {
return nil, err
} else if payloadBytes, err = proto.Marshal(&common.Payload{
Header: header,
Data: dataBytes,
}); err != nil {
return nil, err
} else {
return proto.Marshal(&common.Envelope{
Payload: payloadBytes,
})
}
}
// QueryChannelConfig is used to query latest channel config block
func QueryChannelConfigBlock(ledgerClient *ledger.Client) ([]byte, error) {
ledgerInfo, err := ledgerClient.QueryInfo()
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("QueryInfo return error: %s", err))
return nil, err
}
currentBlock, err := ledgerClient.QueryBlockByHash(ledgerInfo.BCI.CurrentBlockHash)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("QueryBlockByHash return error: %s", err))
return nil, err
}
if currentBlock.Metadata == nil {
hfrdcommon.Logger.Error(fmt.Sprintf("QueryBlockByHash block data is nil"))
return nil, err
}
b, err := proto.Marshal(currentBlock)
if err != nil {
return nil, err
}
lc, err := GetLastConfigIndexFromBlock(b)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("GetLastConfigIndexFromBlock err: %s", err))
return nil, err
}
lastBlock, err := ledgerClient.QueryBlock(lc)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("Query Last Block err: %s", err))
}
b, err = proto.Marshal(lastBlock)
if err != nil {
return nil, err
}
return b, nil
}
// CreateUpdateEnvelope is used to build channel update envelope
func CreateUpdateEnvelope(updateOptions *UpdateOptions, configBlockBytes []byte) ([]byte, *UpdateOptions, error) {
// Decode channel block
originalChannelGroup, err := configtxlator.DecodeProto("common.Block", configBlockBytes)
if err != nil {
return nil, updateOptions, errors.Errorf("Error in decode proto : %s", err)
}
oriBuffer := EncodeAndReplaceNull(originalChannelGroup)
// Get the new channel group based on the update options
var updatedChannelGroup = make(map[string]interface{})
updatedChannelGroup, updateOptions, err = UpdateChannelGroup(originalChannelGroup, updateOptions)
if err != nil {
return nil, updateOptions, err
}
if !updateOptions.OrdererOrgUpdate && !updateOptions.OrdererAddressesUpdate && !updateOptions.PeerOrgUpdate {
return nil, updateOptions, errors.Errorf("The new config are exactly the same as current config")
}
updatedBuffer := EncodeAndReplaceNull(updatedChannelGroup)
// Encode and compute update proto bytes
originalProtoBytes, err := configtxlator.EncodeProto("common.Config", oriBuffer.Bytes())
if err != nil {
return nil, updateOptions, errors.Errorf("error in encode json to proto message : %s", err)
}
updatedProtoBytes, err := configtxlator.EncodeProto("common.Config", updatedBuffer.Bytes())
if err != nil {
return nil, updateOptions, errors.Errorf("error in encode json to proto message: %s", err)
}
computeUpdateBytes, err := configtxlator.ComputeUpdt(originalProtoBytes, updatedProtoBytes, updateOptions.ChannelID)
configUpdate, err := configtxlator.DecodeProto("common.ConfigUpdate", computeUpdateBytes)
if err != nil {
return nil, updateOptions, errors.Errorf("Error in decode proto : %s", err)
}
// Build config update envelope
configUpdateEnvelope := &ConfigUpdate{}
configUpdateEnvelope.Payload.Data.Config_update = configUpdate
configUpdateEnvelope.Payload.Header.Channel_header.Type = "2"
configUpdateEnvelope.Payload.Header.Channel_header.Channel_id = updateOptions.ChannelID
// Replace and lowercase some strings
var cueBuffer bytes.Buffer
encoderUpdated := json.NewEncoder(&cueBuffer)
encoderUpdated.SetIndent("", "\t")
encoderUpdated.Encode(configUpdateEnvelope)
cuestring := string(cueBuffer.Bytes())
r := regexp.MustCompile("\"value\": null,\n")
cuestring = r.ReplaceAllString(cuestring, "")
r = regexp.MustCompile("\"policy\": null,\n")
cuestring = r.ReplaceAllString(cuestring, "")
replaceKeys := []string{"Payload", "Header", "Channel_header", "Data", "Config_update", "Type", "Channel_id"}
cuestring = lowercaseStringWithKeys(cuestring, replaceKeys)
cueProtoBytes, err := configtxlator.EncodeProto("common.Envelope", []byte(cuestring))
if cueProtoBytes == nil {
return nil, updateOptions, errors.Errorf("Error in update channel : no update envelope provided")
}
return cueProtoBytes, updateOptions, nil
}
func UpdateChannelGroup(originalGroup map[string]interface{}, updateOptions *UpdateOptions) (map[string]interface{}, *UpdateOptions, error) {
var updatedChannelGroup = make(map[string]interface{})
updatedChannelGroup = originalGroup
batchTimeout, maxMessageCount, preferredMaxBytes, anchorPeerConfig, ordererCurrAddresses := GetConfigFromChannelGroup(updatedChannelGroup, updateOptions.MspID)
if maxMessageCount != updateOptions.MaxMessageCount && updateOptions.MaxMessageCount != 0 {
updatedChannelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Orderer"].(map[string]interface{})["values"].(map[string]interface{})["BatchSize"].(map[string]interface{})["value"].(map[string]interface{})["max_message_count"] = updateOptions.MaxMessageCount
updateOptions.OrdererOrgUpdate = true
}
if preferredMaxBytes != updateOptions.PreferredMaxBytes && updateOptions.PreferredMaxBytes != 0 {
updatedChannelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Orderer"].(map[string]interface{})["values"].(map[string]interface{})["BatchSize"].(map[string]interface{})["value"].(map[string]interface{})["preferred_max_bytes"] = updateOptions.PreferredMaxBytes
updateOptions.OrdererOrgUpdate = true
}
if batchTimeout != updateOptions.BatchTimeout && updateOptions.BatchTimeout != "" {
updatedChannelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Orderer"].(map[string]interface{})["values"].(map[string]interface{})["BatchTimeout"].(map[string]interface{})["value"].(map[string]interface{})["timeout"] = updateOptions.BatchTimeout
updateOptions.OrdererOrgUpdate = true
}
if len(updateOptions.OrdererAddresses) != 0 {
ordererCurrBytes, err := json.Marshal(ordererCurrAddresses)
if err != nil {
return nil, nil, err
}
var ordererAddresses []string
switch updateOptions.OrdererAddressesAction {
case REPLACE_ORDERER_ADDRESS:
ordererAddresses = updateOptions.OrdererAddresses
case ADD_ORDERER_ADDRESS:
for _, ordererAddress := range updateOptions.OrdererAddresses {
if contains(ordererCurrAddresses, ordererAddress) == -1 {
ordererCurrAddresses = append(ordererCurrAddresses, ordererAddress)
}
}
ordererAddresses = ordererCurrAddresses
case REMOVE_ORDERER_ADDRESS:
for _, ordererAddress := range updateOptions.OrdererAddresses {
for {
if index := contains(ordererCurrAddresses, ordererAddress); index != -1 {
ordererCurrAddresses = append(ordererCurrAddresses[:index], ordererCurrAddresses[index+1:]...)
} else {
break
}
}
}
ordererAddresses = ordererCurrAddresses
}
addressesValue := make(map[string][]string)
addressesValue["addresses"] = updateOptions.OrdererAddresses
ordererNewBytes, err := json.Marshal(ordererAddresses)
if err != nil {
return nil, nil, err
}
if string(ordererCurrBytes) != string(ordererNewBytes) {
updatedChannelGroup["channel_group"].(map[string]interface{})["values"].(map[string]interface{})["OrdererAddresses"].(map[string]interface{})["value"].(map[string]interface{})["addresses"] = ordererAddresses
updateOptions.OrdererAddressesUpdate = true
}
}
if len(updateOptions.AnchorPeers) != 0 {
var anchorPeers []map[string]interface{}
for _, anchorPeer := range updateOptions.AnchorPeers {
anchorConfig := make(map[string]interface{})
if len(strings.Split(anchorPeer, ":")) != 2 {
return nil, updateOptions, errors.Errorf("Please double check your anchor peers configurations.They must include both ip and port")
}
anchorConfig["host"] = strings.Split(anchorPeer, ":")[0]
port, err := strconv.ParseFloat(strings.Split(anchorPeer, ":")[1], 32)
if err != nil {
return nil, nil, err
}
anchorConfig["port"] = port
anchorPeers = append(anchorPeers, anchorConfig)
}
newAnchorConfig := make(map[string]interface{})
newAnchorConfig["mod_policy"] = "Admins"
anchorValue := make(map[string][]map[string]interface{})
anchorValue["anchor_peers"] = anchorPeers
newAnchorConfig["value"] = anchorValue
if anchorPeerConfig == nil {
updatedChannelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Application"].(map[string]interface{})["groups"].(map[string]interface{})[updateOptions.MspID].(map[string]interface{})["values"].(map[string]interface{})["AnchorPeers"] = newAnchorConfig
updateOptions.PeerOrgUpdate = true
} else {
anchorCurrBytes, err := json.Marshal(anchorPeerConfig["value"].(map[string]interface{})["anchor_peers"])
if err != nil {
return nil, nil, err
}
anchorNewBytes, err := json.Marshal(anchorPeers)
if err != nil {
return nil, nil, err
}
if string(anchorCurrBytes) != string(anchorNewBytes) {
updatedChannelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Application"].(map[string]interface{})["groups"].(map[string]interface{})[updateOptions.MspID].(map[string]interface{})["values"].(map[string]interface{})["AnchorPeers"].(map[string]interface{})["value"].(map[string]interface{})["anchor_peers"] = anchorPeers
updateOptions.PeerOrgUpdate = true
}
}
}
configOut := make(map[string]interface{})
configOut["channel_group"] = updatedChannelGroup["channel_group"]
return configOut, updateOptions, nil
}
// GetConfigFromChannelGroup will get batchTimeout/batchSize/AnchorPeers from channelGroup
func GetConfigFromChannelGroup(channelGroup map[string]interface{}, mspID string) (batchTimeout string, maxMessageCount float64, preferredMaxBytes float64, anchorPeers map[string]interface{}, orderers []string) {
maxMessageCount = channelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Orderer"].(map[string]interface{})["values"].(map[string]interface{})["BatchSize"].(map[string]interface{})["value"].(map[string]interface{})["max_message_count"].(float64)
preferredMaxBytes = channelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Orderer"].(map[string]interface{})["values"].(map[string]interface{})["BatchSize"].(map[string]interface{})["value"].(map[string]interface{})["preferred_max_bytes"].(float64)
batchTimeout = channelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Orderer"].(map[string]interface{})["values"].(map[string]interface{})["BatchTimeout"].(map[string]interface{})["value"].(map[string]interface{})["timeout"].(string)
mspValues := channelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Application"].(map[string]interface{})["groups"].(map[string]interface{})[mspID].(map[string]interface{})["values"].(map[string]interface{})
var orgAnchors map[string]interface{}
if _, ok := mspValues["AnchorPeers"]; ok {
orgAnchors = mspValues["AnchorPeers"].(map[string]interface{})
}
ordererAddressesValue := channelGroup["channel_group"].(map[string]interface{})["values"].(map[string]interface{})["OrdererAddresses"].(map[string]interface{})["value"].(map[string]interface{})
var ordererAddresses []string
if _, ok := ordererAddressesValue["addresses"]; ok {
for _, address := range ordererAddressesValue["addresses"].([]interface{}) {
ordererAddresses = append(ordererAddresses, address.(string))
}
}
return batchTimeout, maxMessageCount, preferredMaxBytes, orgAnchors, ordererAddresses
}
// PrintMSPidFromChannelGroup print MSPid list in given channel group config
func PrintMSPidFromChannelGroup(channelGroup map[string]interface{}) {
orgMspFromChannelConfig := channelGroup["channel_group"].(map[string]interface{})["groups"].(map[string]interface{})["Application"].(map[string]interface{})["groups"].(map[string]interface{})
var orgMSPId []string
for key := range orgMspFromChannelConfig {
orgMSPId = append(orgMSPId, key)
}
hfrdcommon.Logger.Info(fmt.Sprintf("org MSPID in channel config: %s", orgMSPId))
}
// GetLastConfigIndexFromBlock retrieves the index of the last config block as encoded in the block metadata
func GetLastConfigIndexFromBlock(blockBytes []byte) (uint64, error) {
block := &common.Block{}
proto.Unmarshal(blockBytes, block)
md, err := GetMetadataFromBlock(block, common.BlockMetadataIndex_LAST_CONFIG)
if err != nil {
return 0, err
}
lc := &common.LastConfig{}
err = proto.Unmarshal(md.Value, lc)
if err != nil {
return 0, err
}
return lc.Index, nil
}
// GetMetadataFromBlock retrieves metadata at the specified index.
func GetMetadataFromBlock(block *common.Block, index common.BlockMetadataIndex) (*common.Metadata, error) {
md := &common.Metadata{}
err := proto.Unmarshal(block.Metadata.Metadata[index], md)
if err != nil {
return nil, err
}
return md, nil
}
func makeImplicitMetaPolicy(subPolicyName string, rule common.ImplicitMetaPolicy_Rule) (*common.Policy, error) {
valueBytes, err := proto.Marshal(&common.ImplicitMetaPolicy{
Rule: rule,
SubPolicy: subPolicyName,
})
if err != nil {
return nil, err
}
return &common.Policy{
Type: int32(common.Policy_IMPLICIT_META),
Value: valueBytes,
}, nil
}
func UpdateChannel(sdk *fabsdk.FabricSDK, configuUpdateEnvelope []byte, updateOptions *UpdateOptions) error {
var mspClient *mspclient.Client
var signingIdentities []msp.SigningIdentity
var err error
if updateOptions.OrdererOrgUpdate || updateOptions.OrdererAddressesUpdate {
mspClient, err = mspclient.New(sdk.Context(), mspclient.WithOrg(updateOptions.OrdererOrgName))
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("Error creating msp client: %s", err))
return err
}
adminIdentity, err := mspClient.GetSigningIdentity(hfrdcommon.ADMIN)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("failed to get admin signing identity: %s", err))
return err
}
signingIdentities = append(signingIdentities, adminIdentity)
}
if updateOptions.PeerOrgUpdate {
mspClient, err = mspclient.New(sdk.Context(), mspclient.WithOrg(updateOptions.LedgerClientOrg))
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("Error creating msp client: %s", err))
return err
}
adminIdentity, err := mspClient.GetSigningIdentity(hfrdcommon.ADMIN)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("failed to get admin signing identity: %s", err))
return err
}
signingIdentities = append(signingIdentities, adminIdentity)
}
orgClientContext := sdk.Context(fabsdk.WithUser(hfrdcommon.ADMIN), fabsdk.WithOrg(updateOptions.LedgerClientOrg))
orgClient, err := resmgmt.New(orgClientContext)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("Error creating resource manager client: %s", err))
return err
}
req := resmgmt.SaveChannelRequest{ChannelID: updateOptions.ChannelID, ChannelConfig: bytes.NewReader(configuUpdateEnvelope),
SigningIdentities: signingIdentities}
res, err := orgClient.SaveChannel(req, resmgmt.WithOrdererEndpoint(updateOptions.OrdererName))
if err != nil || res.TransactionID == "" {
if strings.Contains(err.Error(), "error validating ReadSet") {
hfrdcommon.Logger.Error(fmt.Sprintf("The channel:%s might already exist, skip the error: %s", updateOptions.ChannelID, err))
return err
} else {
hfrdcommon.Logger.Error(fmt.Sprintf("failed to create channel with name %s: %s", updateOptions.ChannelID, err))
return err
}
}
return nil
}
func WaitUntilUpdateSucc(ledgerClient *ledger.Client, updateOptions *UpdateOptions) error {
var waitCount int
for {
waitCount++
configBlockBytes, err := QueryChannelConfigBlock(ledgerClient)
if err != nil {
return err
}
currentChannelGroup, err := configtxlator.DecodeProto("common.Block", configBlockBytes)
if err != nil {
return errors.Errorf("Error in decode proto : %s", err)
}
batchTimeout, maxMessageCount, preferredMaxBytes, anchorPeerConfig, ordererAddresses := GetConfigFromChannelGroup(currentChannelGroup, updateOptions.MspID)
if updateOptions.OrdererOrgUpdate {
if updateOptions.BatchTimeout != "" && updateOptions.BatchTimeout != batchTimeout {
continue
}
if updateOptions.MaxMessageCount != 0 && updateOptions.MaxMessageCount != maxMessageCount {
continue
}
if updateOptions.PreferredMaxBytes != 0 && updateOptions.PreferredMaxBytes != preferredMaxBytes {
continue
}
}
// Check if orderer addresses are updated successfully.Comment out for now.
//if updateOptions.OrdererAddressesUpdate {
// fmt.Printf("Current orderer addresses: %s \n", ordererAddresses)
//}
if updateOptions.PeerOrgUpdate {
if anchorPeerConfig == nil {
continue
}
}
hfrdcommon.Logger.Info(fmt.Sprintf("Successfully updated channel: %s", updateOptions.ChannelID))
hfrdcommon.Logger.Info(fmt.Sprintf(" Batchtimeout: %s", batchTimeout))
hfrdcommon.Logger.Info(fmt.Sprintf(" BatchSize.MaxMessageCount: %f", maxMessageCount))
hfrdcommon.Logger.Info(fmt.Sprintf(" BatchSize.PreferredMaxBytes: %f", preferredMaxBytes))
hfrdcommon.Logger.Info(fmt.Sprintf(" OrdererAddresses: %s", ordererAddresses))
hfrdcommon.Logger.Info(fmt.Sprintf(" Org anchor peers: %#v", anchorPeerConfig))
break
}
return nil
}
func EncodeAndReplaceNull(mapJson map[string]interface{}) *bytes.Buffer {
var updatedBuffer bytes.Buffer
encoderUpdated := json.NewEncoder(&updatedBuffer)
encoderUpdated.SetIndent("", "\t")
encoderUpdated.Encode(mapJson)
r := regexp.MustCompile("\"signing_identity\": null,\n")
out := r.ReplaceAllString(string(updatedBuffer.Bytes()), "")
r = regexp.MustCompile("\"fabricNodeOus\": null,\n")
out = r.ReplaceAllString(out, "")
r = regexp.MustCompile("\"value\": null,\n")
out = r.ReplaceAllString(out, "")
r = regexp.MustCompile("\"policy\": null,\n")
out = r.ReplaceAllString(out, "")
r = regexp.MustCompile("\"crypto_config\": null,\n")
out = r.ReplaceAllString(out, "")
return bytes.NewBuffer([]byte(out))
}
func lowercaseStringWithKeys(original string, keys []string) string {
if len(keys) == 0 {
return original
}
for _, key := range keys {
keyLowercase := strings.ToLower(key)
original = strings.Replace(original, key, keyLowercase, -1)
}
return original
}
// CreateNewOrgEnvelope used to build add new org channel update envelope
func CreateNewOrgEnvelope(origChannelGroup map[string]interface{}, modifiedChannelGroup map[string]interface{}, channelID string) ([]byte, error) {
//Encode channel group to buffer
oriBuffer := EncodeAndReplaceNull(origChannelGroup)
updatedBuffer := EncodeAndReplaceNull(modifiedChannelGroup)
//Encode and compute update proto bytes
originalProtoBytes, err := configtxlator.EncodeProto("common.Config", oriBuffer.Bytes())
if err != nil {
return nil, errors.Errorf("error in encode json to proto message : %s \n", err)
}
//for debug
//_ = originalProtoBytes
updatedProtoBytes, err := configtxlator.EncodeProto("common.Config", updatedBuffer.Bytes())
if err != nil {
return nil, errors.Errorf("error in encode json to proto message: %s \n", err)
}
computeUpdateBytes, err := configtxlator.ComputeUpdt(originalProtoBytes, updatedProtoBytes, channelID)
if err != nil {
return nil, errors.Errorf("Error in configtxlator.ComputeUpdt : %s \n", err)
}
configUpdate, err := configtxlator.DecodeProto("common.ConfigUpdate", computeUpdateBytes)
if err != nil {
return nil, errors.Errorf("Error in decode proto : %s \n", err)
}
// Build config update envelope
configUpdateEnvelope := &ConfigUpdate{}
configUpdateEnvelope.Payload.Data.Config_update = configUpdate
configUpdateEnvelope.Payload.Header.Channel_header.Type = "2"
configUpdateEnvelope.Payload.Header.Channel_header.Channel_id = channelID
// Replace and lowercase some strings
var cueBuffer bytes.Buffer
encoderUpdated := json.NewEncoder(&cueBuffer)
encoderUpdated.SetIndent("", "\t")
encoderUpdated.Encode(configUpdateEnvelope)
cuestring := string(cueBuffer.Bytes())
r := regexp.MustCompile("\"value\": null,\n")
cuestring = r.ReplaceAllString(cuestring, "")
r = regexp.MustCompile("\"policy\": null,\n")
cuestring = r.ReplaceAllString(cuestring, "")
r = regexp.MustCompile("\"signing_identity\": null,\n")
cuestring = r.ReplaceAllString(cuestring, "")
replaceKeys := []string{"Payload", "Header", "Channel_header", "Data", "Config_update", "Type", "Channel_id"}
cuestring = lowercaseStringWithKeys(cuestring, replaceKeys)
//return oriBuffer.Bytes(),err
cueProtoBytes, err := configtxlator.EncodeProto("common.Envelope", []byte(cuestring))
if cueProtoBytes == nil {
return nil, errors.Errorf("Error in update channel : no update envelope provided")
}
return cueProtoBytes, nil
}
//CollectSign collect SigningIdentity for provided members
func CollectSign(sdk *fabsdk.FabricSDK, requiredMember []string) ([]msp.SigningIdentity, error) {
var mspClient *mspclient.Client
var signingIdentities []msp.SigningIdentity
var err error
for _, peerOrg := range requiredMember {
mspClient, err = mspclient.New(sdk.Context(), mspclient.WithOrg(peerOrg))
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("Error creating msp client: %s", err))
return nil, err
}
adminIdentity, err := mspClient.GetSigningIdentity(hfrdcommon.ADMIN)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("failed to get admin signing identity: %s", err))
return nil, err
}
signingIdentities = append(signingIdentities, adminIdentity)
}
return signingIdentities, err
}
//AddOrgToChannel submit save channel request with provided channelID, transaction envelope and required signature to orderer name
func AddOrgToChannel(sdk *fabsdk.FabricSDK, channelID string, addOrgEnvelopByte []byte, signIdentities []msp.SigningIdentity, ledgerClientOrg string, ordererName string) error {
orgClientContext := sdk.Context(fabsdk.WithUser(hfrdcommon.ADMIN), fabsdk.WithOrg(ledgerClientOrg))
orgClient, err := resmgmt.New(orgClientContext)
if err != nil {
hfrdcommon.Logger.Error(fmt.Sprintf("Error creating resource manager client: %s", err))
return err
}
req := resmgmt.SaveChannelRequest{ChannelID: channelID, ChannelConfig: bytes.NewReader(addOrgEnvelopByte),
SigningIdentities: signIdentities}
res, err := orgClient.SaveChannel(req, resmgmt.WithOrdererEndpoint(ordererName))
if err != nil || res.TransactionID == "" {
hfrdcommon.Logger.Error(fmt.Sprintf("failed to add new org to channel with name %s: %s", channelID, err))
return err
}
hfrdcommon.Logger.Info(fmt.Sprintf("Successfully add new org to channel: %s, transactionID is %s", channelID, res.TransactionID))
return nil
}
func contains(s []string, e string) int {
for i, a := range s {
if a == e {
return i
}
}
return -1
}