github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/hyperledger/fabric-config/configtx/orderer.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package configtx
     8  
     9  import (
    10  	"encoding/pem"
    11  	"errors"
    12  	"fmt"
    13  	"github.com/hellobchain/newcryptosm/x509"
    14  	"github.com/hellobchain/third_party/hyperledger/fabric-config/configtx/orderer"
    15  	"math"
    16  	"reflect"
    17  	"strings"
    18  	"time"
    19  
    20  	"github.com/golang/protobuf/proto"
    21  	cb "github.com/hyperledger/fabric-protos-go/common"
    22  	ob "github.com/hyperledger/fabric-protos-go/orderer"
    23  	eb "github.com/hyperledger/fabric-protos-go/orderer/etcdraft"
    24  )
    25  
    26  const (
    27  	defaultHashingAlgorithm               = "SHA256"
    28  	defaultBlockDataHashingStructureWidth = math.MaxUint32
    29  )
    30  
    31  // Orderer configures the ordering service behavior for a channel.
    32  type Orderer struct {
    33  	// OrdererType is the type of orderer
    34  	// Options: `ConsensusTypeSolo`, `ConsensusTypeKafka` or `ConsensusTypeEtcdRaft`
    35  	OrdererType string
    36  	// BatchTimeout is the wait time between transactions.
    37  	BatchTimeout  time.Duration
    38  	BatchSize     orderer.BatchSize
    39  	Kafka         orderer.Kafka
    40  	EtcdRaft      orderer.EtcdRaft
    41  	Organizations []Organization
    42  	// MaxChannels is the maximum count of channels an orderer supports.
    43  	MaxChannels uint64
    44  	// Capabilities is a map of the capabilities the orderer supports.
    45  	Capabilities []string
    46  	Policies     map[string]Policy
    47  	// Options: `ConsensusStateNormal` and `ConsensusStateMaintenance`
    48  	State     orderer.ConsensusState
    49  	ModPolicy string
    50  }
    51  
    52  // OrdererGroup encapsulates the parts of the config that control
    53  // the orderering service behavior.
    54  type OrdererGroup struct {
    55  	channelGroup *cb.ConfigGroup
    56  	ordererGroup *cb.ConfigGroup
    57  }
    58  
    59  // OrdererOrg encapsulates the parts of the config that control
    60  // an orderer organization's configuration.
    61  type OrdererOrg struct {
    62  	orgGroup *cb.ConfigGroup
    63  	name     string
    64  }
    65  
    66  // MSP returns an OrganizationMSP object that can be used to configure the organization's MSP.
    67  func (o *OrdererOrg) MSP() *OrganizationMSP {
    68  	return &OrganizationMSP{
    69  		configGroup: o.orgGroup,
    70  	}
    71  }
    72  
    73  // EtcdRaftOptionsValue encapsulates the configuration functions used to modify an etcdraft configuration's options.
    74  type EtcdRaftOptionsValue struct {
    75  	value *cb.ConfigValue
    76  }
    77  
    78  // BatchSizeValue encapsulates the configuration functions used to modify an orderer configuration's batch size values.
    79  type BatchSizeValue struct {
    80  	value *cb.ConfigValue
    81  }
    82  
    83  // Orderer returns the orderer group from the updated config.
    84  func (c *ConfigTx) Orderer() *OrdererGroup {
    85  	channelGroup := c.updated.ChannelGroup
    86  	ordererGroup := channelGroup.Groups[OrdererGroupKey]
    87  	return &OrdererGroup{channelGroup: channelGroup, ordererGroup: ordererGroup}
    88  }
    89  
    90  // Organization returns the orderer org from the updated config.
    91  func (o *OrdererGroup) Organization(name string) *OrdererOrg {
    92  	orgGroup, ok := o.ordererGroup.Groups[name]
    93  	if !ok {
    94  		return nil
    95  	}
    96  	return &OrdererOrg{name: name, orgGroup: orgGroup}
    97  }
    98  
    99  // Configuration returns the existing orderer configuration values from the updated
   100  // config in a config transaction as an Orderer type. This can be used to retrieve
   101  // existing values for the orderer prior to updating the orderer configuration.
   102  func (o *OrdererGroup) Configuration() (Orderer, error) {
   103  	// CONSENSUS TYPE, STATE, AND METADATA
   104  	var etcdRaft orderer.EtcdRaft
   105  	kafkaBrokers := orderer.Kafka{}
   106  
   107  	consensusTypeProto := &ob.ConsensusType{}
   108  	err := unmarshalConfigValueAtKey(o.ordererGroup, orderer.ConsensusTypeKey, consensusTypeProto)
   109  	if err != nil {
   110  		return Orderer{}, errors.New("cannot determine consensus type of orderer")
   111  	}
   112  
   113  	ordererType := consensusTypeProto.Type
   114  	state := orderer.ConsensusState(ob.ConsensusType_State_name[int32(consensusTypeProto.State)])
   115  
   116  	switch consensusTypeProto.Type {
   117  	case orderer.ConsensusTypeSolo:
   118  	case orderer.ConsensusTypeKafka:
   119  		kafkaBrokersValue, ok := o.ordererGroup.Values[orderer.KafkaBrokersKey]
   120  		if !ok {
   121  			return Orderer{}, errors.New("unable to find kafka brokers for kafka orderer")
   122  		}
   123  
   124  		kafkaBrokersProto := &ob.KafkaBrokers{}
   125  		err := proto.Unmarshal(kafkaBrokersValue.Value, kafkaBrokersProto)
   126  		if err != nil {
   127  			return Orderer{}, fmt.Errorf("unmarshaling kafka brokers: %v", err)
   128  		}
   129  
   130  		kafkaBrokers.Brokers = kafkaBrokersProto.Brokers
   131  	case orderer.ConsensusTypeEtcdRaft:
   132  		etcdRaft, err = unmarshalEtcdRaftMetadata(consensusTypeProto.Metadata)
   133  		if err != nil {
   134  			return Orderer{}, fmt.Errorf("unmarshaling etcd raft metadata: %v", err)
   135  		}
   136  	default:
   137  		return Orderer{}, fmt.Errorf("config contains unknown consensus type '%s'", consensusTypeProto.Type)
   138  	}
   139  
   140  	// BATCHSIZE AND TIMEOUT
   141  	batchSize := &ob.BatchSize{}
   142  	err = unmarshalConfigValueAtKey(o.ordererGroup, orderer.BatchSizeKey, batchSize)
   143  	if err != nil {
   144  		return Orderer{}, err
   145  	}
   146  
   147  	batchTimeoutProto := &ob.BatchTimeout{}
   148  	err = unmarshalConfigValueAtKey(o.ordererGroup, orderer.BatchTimeoutKey, batchTimeoutProto)
   149  	if err != nil {
   150  		return Orderer{}, err
   151  	}
   152  
   153  	batchTimeout, err := time.ParseDuration(batchTimeoutProto.Timeout)
   154  	if err != nil {
   155  		return Orderer{}, fmt.Errorf("batch timeout configuration '%s' is not a duration string", batchTimeoutProto.Timeout)
   156  	}
   157  
   158  	// ORDERER ORGS
   159  	var ordererOrgs []Organization
   160  	for orgName := range o.ordererGroup.Groups {
   161  		orgConfig, err := o.Organization(orgName).Configuration()
   162  		if err != nil {
   163  			return Orderer{}, fmt.Errorf("retrieving orderer org %s: %v", orgName, err)
   164  		}
   165  
   166  		ordererOrgs = append(ordererOrgs, orgConfig)
   167  	}
   168  
   169  	// MAX CHANNELS
   170  	channelRestrictions := &ob.ChannelRestrictions{}
   171  	err = unmarshalConfigValueAtKey(o.ordererGroup, orderer.ChannelRestrictionsKey, channelRestrictions)
   172  	if err != nil {
   173  		return Orderer{}, err
   174  	}
   175  
   176  	// CAPABILITIES
   177  	capabilities, err := getCapabilities(o.ordererGroup)
   178  	if err != nil {
   179  		return Orderer{}, fmt.Errorf("retrieving orderer capabilities: %v", err)
   180  	}
   181  
   182  	// POLICIES
   183  	policies, err := o.Policies()
   184  	if err != nil {
   185  		return Orderer{}, fmt.Errorf("retrieving orderer policies: %v", err)
   186  	}
   187  
   188  	return Orderer{
   189  		OrdererType:  ordererType,
   190  		BatchTimeout: batchTimeout,
   191  		BatchSize: orderer.BatchSize{
   192  			MaxMessageCount:   batchSize.MaxMessageCount,
   193  			AbsoluteMaxBytes:  batchSize.AbsoluteMaxBytes,
   194  			PreferredMaxBytes: batchSize.PreferredMaxBytes,
   195  		},
   196  		Kafka:         kafkaBrokers,
   197  		EtcdRaft:      etcdRaft,
   198  		Organizations: ordererOrgs,
   199  		MaxChannels:   channelRestrictions.MaxCount,
   200  		Capabilities:  capabilities,
   201  		Policies:      policies,
   202  		State:         state,
   203  		ModPolicy:     o.ordererGroup.GetModPolicy(),
   204  	}, nil
   205  }
   206  
   207  // BatchSize returns a BatchSizeValue that can be used to configure an orderer configuration's batch size parameters.
   208  func (o *OrdererGroup) BatchSize() *BatchSizeValue {
   209  	return &BatchSizeValue{
   210  		value: o.ordererGroup.Values[orderer.BatchSizeKey],
   211  	}
   212  }
   213  
   214  // SetMaxMessageCount sets an orderer configuration's batch size max message count.
   215  func (b *BatchSizeValue) SetMaxMessageCount(maxMessageCount uint32) error {
   216  	batchSize := &ob.BatchSize{}
   217  	err := proto.Unmarshal(b.value.Value, batchSize)
   218  	if err != nil {
   219  		return err
   220  	}
   221  
   222  	batchSize.MaxMessageCount = maxMessageCount
   223  	b.value.Value, err = proto.Marshal(batchSize)
   224  
   225  	return err
   226  }
   227  
   228  // SetAbsoluteMaxBytes sets an orderer configuration's batch size max block size.
   229  func (b *BatchSizeValue) SetAbsoluteMaxBytes(maxBytes uint32) error {
   230  	batchSize := &ob.BatchSize{}
   231  	err := proto.Unmarshal(b.value.Value, batchSize)
   232  	if err != nil {
   233  		return err
   234  	}
   235  
   236  	batchSize.AbsoluteMaxBytes = maxBytes
   237  	b.value.Value, err = proto.Marshal(batchSize)
   238  
   239  	return err
   240  }
   241  
   242  // SetPreferredMaxBytes sets an orderer configuration's batch size preferred size of blocks.
   243  func (b *BatchSizeValue) SetPreferredMaxBytes(maxBytes uint32) error {
   244  	batchSize := &ob.BatchSize{}
   245  	err := proto.Unmarshal(b.value.Value, batchSize)
   246  	if err != nil {
   247  		return err
   248  	}
   249  
   250  	batchSize.PreferredMaxBytes = maxBytes
   251  	b.value.Value, err = proto.Marshal(batchSize)
   252  
   253  	return err
   254  }
   255  
   256  // SetBatchTimeout sets the wait time between transactions.
   257  func (o *OrdererGroup) SetBatchTimeout(timeout time.Duration) error {
   258  	return setValue(o.ordererGroup, batchTimeoutValue(timeout.String()), AdminsPolicyKey)
   259  }
   260  
   261  // SetMaxChannels sets the maximum count of channels an orderer supports.
   262  func (o *OrdererGroup) SetMaxChannels(max int) error {
   263  	return setValue(o.ordererGroup, channelRestrictionsValue(uint64(max)), AdminsPolicyKey)
   264  }
   265  
   266  // SetEtcdRaftConsensusType sets the orderer consensus type to etcdraft, sets etcdraft metadata, and consensus state.
   267  func (o *OrdererGroup) SetEtcdRaftConsensusType(consensusMetadata orderer.EtcdRaft, consensusState orderer.ConsensusState) error {
   268  	consensusMetadataBytes, err := marshalEtcdRaftMetadata(consensusMetadata)
   269  	if err != nil {
   270  		return fmt.Errorf("marshaling etcdraft metadata: %v", err)
   271  	}
   272  
   273  	return setValue(o.ordererGroup, consensusTypeValue(orderer.ConsensusTypeEtcdRaft, consensusMetadataBytes, ob.ConsensusType_State_value[string(consensusState)]), AdminsPolicyKey)
   274  }
   275  
   276  // SetConsensusState sets the consensus state.
   277  func (o *OrdererGroup) SetConsensusState(consensusState orderer.ConsensusState) error {
   278  	consensusTypeProto := &ob.ConsensusType{}
   279  	err := unmarshalConfigValueAtKey(o.ordererGroup, orderer.ConsensusTypeKey, consensusTypeProto)
   280  	if err != nil {
   281  		return err
   282  	}
   283  
   284  	return setValue(o.ordererGroup, consensusTypeValue(consensusTypeProto.Type, consensusTypeProto.Metadata, ob.ConsensusType_State_value[string(consensusState)]), AdminsPolicyKey)
   285  }
   286  
   287  // EtcdRaftOptions returns an EtcdRaftOptionsValue that can be used to configure an etcdraft configuration's options.
   288  func (o *OrdererGroup) EtcdRaftOptions() *EtcdRaftOptionsValue {
   289  	return &EtcdRaftOptionsValue{
   290  		value: o.ordererGroup.Values[orderer.ConsensusTypeKey],
   291  	}
   292  }
   293  
   294  func (e *EtcdRaftOptionsValue) etcdRaftConfig(consensusTypeProto *ob.ConsensusType) (orderer.EtcdRaft, error) {
   295  	err := proto.Unmarshal(e.value.Value, consensusTypeProto)
   296  	if err != nil {
   297  		return orderer.EtcdRaft{}, err
   298  	}
   299  
   300  	return unmarshalEtcdRaftMetadata(consensusTypeProto.Metadata)
   301  }
   302  
   303  func (e *EtcdRaftOptionsValue) setEtcdRaftConfig(consensusTypeProto *ob.ConsensusType, etcdRaft orderer.EtcdRaft) error {
   304  	consensusMetadata, err := marshalEtcdRaftMetadata(etcdRaft)
   305  	if err != nil {
   306  		return fmt.Errorf("marshaling etcdraft metadata: %v", err)
   307  	}
   308  
   309  	consensusTypeProto.Metadata = consensusMetadata
   310  
   311  	e.value.Value, err = proto.Marshal(consensusTypeProto)
   312  	return err
   313  }
   314  
   315  // SetTickInterval sets the Etcdraft's tick interval.
   316  func (e *EtcdRaftOptionsValue) SetTickInterval(interval string) error {
   317  	consensusTypeProto := &ob.ConsensusType{}
   318  	etcdRaft, err := e.etcdRaftConfig(consensusTypeProto)
   319  	if err != nil {
   320  		return nil
   321  	}
   322  
   323  	etcdRaft.Options.TickInterval = interval
   324  	return e.setEtcdRaftConfig(consensusTypeProto, etcdRaft)
   325  }
   326  
   327  // SetElectionInterval sets the Etcdraft's election interval.
   328  func (e *EtcdRaftOptionsValue) SetElectionInterval(interval uint32) error {
   329  	consensusTypeProto := &ob.ConsensusType{}
   330  	etcdRaft, err := e.etcdRaftConfig(consensusTypeProto)
   331  	if err != nil {
   332  		return nil
   333  	}
   334  
   335  	etcdRaft.Options.ElectionTick = interval
   336  	return e.setEtcdRaftConfig(consensusTypeProto, etcdRaft)
   337  }
   338  
   339  // SetHeartbeatTick sets the Etcdraft's heartbeat tick interval.
   340  func (e *EtcdRaftOptionsValue) SetHeartbeatTick(tick uint32) error {
   341  	consensusTypeProto := &ob.ConsensusType{}
   342  	etcdRaft, err := e.etcdRaftConfig(consensusTypeProto)
   343  	if err != nil {
   344  		return nil
   345  	}
   346  
   347  	etcdRaft.Options.HeartbeatTick = tick
   348  	return e.setEtcdRaftConfig(consensusTypeProto, etcdRaft)
   349  }
   350  
   351  // SetMaxInflightBlocks sets the Etcdraft's max inflight blocks.
   352  func (e *EtcdRaftOptionsValue) SetMaxInflightBlocks(maxBlks uint32) error {
   353  	consensusTypeProto := &ob.ConsensusType{}
   354  	etcdRaft, err := e.etcdRaftConfig(consensusTypeProto)
   355  	if err != nil {
   356  		return nil
   357  	}
   358  
   359  	etcdRaft.Options.MaxInflightBlocks = maxBlks
   360  	return e.setEtcdRaftConfig(consensusTypeProto, etcdRaft)
   361  }
   362  
   363  // SetSnapshotIntervalSize sets the Etcdraft's snapshot interval size.
   364  func (e *EtcdRaftOptionsValue) SetSnapshotIntervalSize(intervalSize uint32) error {
   365  	consensusTypeProto := &ob.ConsensusType{}
   366  	etcdRaft, err := e.etcdRaftConfig(consensusTypeProto)
   367  	if err != nil {
   368  		return nil
   369  	}
   370  
   371  	etcdRaft.Options.SnapshotIntervalSize = intervalSize
   372  	return e.setEtcdRaftConfig(consensusTypeProto, etcdRaft)
   373  }
   374  
   375  // Configuration retrieves an existing org's configuration from an
   376  // orderer organization config group in the updated config.
   377  func (o *OrdererOrg) Configuration() (Organization, error) {
   378  	org, err := getOrganization(o.orgGroup, o.name)
   379  	if err != nil {
   380  		return Organization{}, err
   381  	}
   382  
   383  	// OrdererEndpoints are optional when retrieving from an existing config
   384  	org.OrdererEndpoints = nil
   385  	_, ok := o.orgGroup.Values[EndpointsKey]
   386  	if ok {
   387  		endpointsProtos := &cb.OrdererAddresses{}
   388  		err = unmarshalConfigValueAtKey(o.orgGroup, EndpointsKey, endpointsProtos)
   389  		if err != nil {
   390  			return Organization{}, err
   391  		}
   392  		ordererEndpoints := make([]string, len(endpointsProtos.Addresses))
   393  		for i, address := range endpointsProtos.Addresses {
   394  			ordererEndpoints[i] = address
   395  		}
   396  		org.OrdererEndpoints = ordererEndpoints
   397  	}
   398  
   399  	// Remove AnchorPeers which are application org specific.
   400  	org.AnchorPeers = nil
   401  
   402  	return org, nil
   403  }
   404  
   405  // SetOrganization sets the organization config group for the given orderer
   406  // org key in an existing Orderer configuration's Groups map.
   407  // If the orderer org already exists in the current configuration, its value will be overwritten.
   408  func (o *OrdererGroup) SetOrganization(org Organization) error {
   409  	orgGroup, err := newOrdererOrgConfigGroup(org)
   410  	if err != nil {
   411  		return fmt.Errorf("failed to create orderer org %s: %v", org.Name, err)
   412  	}
   413  
   414  	o.ordererGroup.Groups[org.Name] = orgGroup
   415  
   416  	return nil
   417  }
   418  
   419  // RemoveOrganization removes an org from the Orderer group.
   420  // Removal will panic if the orderer group does not exist.
   421  func (o *OrdererGroup) RemoveOrganization(name string) {
   422  	delete(o.ordererGroup.Groups, name)
   423  }
   424  
   425  // SetConfiguration modifies an updated config's Orderer configuration
   426  // via the passed in Orderer values. It skips updating OrdererOrgGroups and Policies.
   427  func (o *OrdererGroup) SetConfiguration(ord Orderer) error {
   428  	// update orderer values
   429  	err := addOrdererValues(o.ordererGroup, ord)
   430  	if err != nil {
   431  		return err
   432  	}
   433  
   434  	return nil
   435  }
   436  
   437  // AddConsenter adds a consenter to an etcdraft configuration.
   438  func (o *OrdererGroup) AddConsenter(consenter orderer.Consenter) error {
   439  	cfg, err := o.Configuration()
   440  	if err != nil {
   441  		return err
   442  	}
   443  
   444  	if cfg.OrdererType != orderer.ConsensusTypeEtcdRaft {
   445  		return fmt.Errorf("consensus type %s is not etcdraft", cfg.OrdererType)
   446  	}
   447  
   448  	for _, c := range cfg.EtcdRaft.Consenters {
   449  		if reflect.DeepEqual(c, consenter) {
   450  			return nil
   451  		}
   452  	}
   453  
   454  	cfg.EtcdRaft.Consenters = append(cfg.EtcdRaft.Consenters, consenter)
   455  
   456  	consensusMetadata, err := marshalEtcdRaftMetadata(cfg.EtcdRaft)
   457  	if err != nil {
   458  		return fmt.Errorf("marshaling etcdraft metadata: %v", err)
   459  	}
   460  
   461  	consensusState, ok := ob.ConsensusType_State_value[string(cfg.State)]
   462  	if !ok {
   463  		return fmt.Errorf("unknown consensus state '%s'", cfg.State)
   464  	}
   465  
   466  	err = setValue(o.ordererGroup, consensusTypeValue(cfg.OrdererType, consensusMetadata, consensusState), AdminsPolicyKey)
   467  	if err != nil {
   468  		return err
   469  	}
   470  
   471  	return nil
   472  }
   473  
   474  // GetConsenter gets a consenter to an etcdraft configuration.
   475  func (o *OrdererGroup) GetConsenter(host string) (orderer.Consenter, error) {
   476  	cfg, err := o.Configuration()
   477  	if err != nil {
   478  		return orderer.Consenter{}, err
   479  	}
   480  
   481  	if cfg.OrdererType != orderer.ConsensusTypeEtcdRaft {
   482  		return orderer.Consenter{}, fmt.Errorf("consensus type %s is not etcdraft", cfg.OrdererType)
   483  	}
   484  
   485  	for _, c := range cfg.EtcdRaft.Consenters {
   486  		if strings.ContainsAny(c.Address.Host, host) {
   487  			return c, nil
   488  		}
   489  	}
   490  	return orderer.Consenter{}, fmt.Errorf("no find Consenter")
   491  }
   492  
   493  // RemoveConsenter removes a consenter from an etcdraft configuration.
   494  func (o *OrdererGroup) RemoveConsenter(consenter orderer.Consenter) error {
   495  	cfg, err := o.Configuration()
   496  	if err != nil {
   497  		return err
   498  	}
   499  
   500  	if cfg.OrdererType != orderer.ConsensusTypeEtcdRaft {
   501  		return fmt.Errorf("consensus type %s is not etcdraft", cfg.OrdererType)
   502  	}
   503  
   504  	consenters := cfg.EtcdRaft.Consenters[:]
   505  	for i, c := range cfg.EtcdRaft.Consenters {
   506  		if reflect.DeepEqual(c, consenter) {
   507  			consenters = append(consenters[:i], consenters[i+1:]...)
   508  			break
   509  		}
   510  	}
   511  
   512  	cfg.EtcdRaft.Consenters = consenters
   513  
   514  	consensusMetadata, err := marshalEtcdRaftMetadata(cfg.EtcdRaft)
   515  	if err != nil {
   516  		return fmt.Errorf("marshaling etcdraft metadata: %v", err)
   517  	}
   518  
   519  	consensusState, ok := ob.ConsensusType_State_value[string(cfg.State)]
   520  	if !ok {
   521  		return fmt.Errorf("unknown consensus state '%s'", cfg.State)
   522  	}
   523  
   524  	err = setValue(o.ordererGroup, consensusTypeValue(cfg.OrdererType, consensusMetadata, consensusState), AdminsPolicyKey)
   525  	if err != nil {
   526  		return err
   527  	}
   528  
   529  	return nil
   530  }
   531  
   532  // Capabilities returns a map of enabled orderer capabilities
   533  // from the updated config.
   534  func (o *OrdererGroup) Capabilities() ([]string, error) {
   535  	capabilities, err := getCapabilities(o.ordererGroup)
   536  	if err != nil {
   537  		return nil, fmt.Errorf("retrieving orderer capabilities: %v", err)
   538  	}
   539  
   540  	return capabilities, nil
   541  }
   542  
   543  // AddCapability adds capability to the provided channel config.
   544  // If the provided capability already exists in current configuration, this action
   545  // will be a no-op.
   546  func (o *OrdererGroup) AddCapability(capability string) error {
   547  	capabilities, err := o.Capabilities()
   548  	if err != nil {
   549  		return err
   550  	}
   551  
   552  	err = addCapability(o.ordererGroup, capabilities, AdminsPolicyKey, capability)
   553  	if err != nil {
   554  		return err
   555  	}
   556  
   557  	return nil
   558  }
   559  
   560  // RemoveCapability removes capability to the provided channel config.
   561  func (o *OrdererGroup) RemoveCapability(capability string) error {
   562  	capabilities, err := o.Capabilities()
   563  	if err != nil {
   564  		return err
   565  	}
   566  
   567  	err = removeCapability(o.ordererGroup, capabilities, AdminsPolicyKey, capability)
   568  	if err != nil {
   569  		return err
   570  	}
   571  
   572  	return nil
   573  }
   574  
   575  // SetEndpoint adds an orderer's endpoint to an existing channel config transaction.
   576  // If the same endpoint already exists in current configuration, this will be a no-op.
   577  func (o *OrdererOrg) SetEndpoint(endpoint Address) error {
   578  	ordererAddrProto := &cb.OrdererAddresses{}
   579  
   580  	if ordererAddrConfigValue, ok := o.orgGroup.Values[EndpointsKey]; ok {
   581  		err := proto.Unmarshal(ordererAddrConfigValue.Value, ordererAddrProto)
   582  		if err != nil {
   583  			return fmt.Errorf("failed unmarshaling endpoints for orderer org %s: %v", o.name, err)
   584  		}
   585  	}
   586  
   587  	endpointToAdd := fmt.Sprintf("%s:%d", endpoint.Host, endpoint.Port)
   588  
   589  	existingOrdererEndpoints := ordererAddrProto.Addresses
   590  	for _, e := range existingOrdererEndpoints {
   591  		if e == endpointToAdd {
   592  			return nil
   593  		}
   594  	}
   595  
   596  	existingOrdererEndpoints = append(existingOrdererEndpoints, endpointToAdd)
   597  
   598  	// Add orderer endpoints config value back to orderer org
   599  	err := setValue(o.orgGroup, endpointsValue(existingOrdererEndpoints), AdminsPolicyKey)
   600  	if err != nil {
   601  		return fmt.Errorf("failed to add endpoint %v to orderer org %s: %v", endpoint, o.name, err)
   602  	}
   603  
   604  	return nil
   605  }
   606  
   607  // RemoveEndpoint removes an orderer's endpoint from an existing channel config transaction.
   608  // Removal will panic if either the orderer group or orderer org group does not exist.
   609  func (o *OrdererOrg) RemoveEndpoint(endpoint Address) error {
   610  	ordererAddrProto := &cb.OrdererAddresses{}
   611  
   612  	if ordererAddrConfigValue, ok := o.orgGroup.Values[EndpointsKey]; ok {
   613  		err := proto.Unmarshal(ordererAddrConfigValue.Value, ordererAddrProto)
   614  		if err != nil {
   615  			return fmt.Errorf("failed unmarshaling endpoints for orderer org %s: %v", o.name, err)
   616  		}
   617  	}
   618  
   619  	endpointToRemove := fmt.Sprintf("%s:%d", endpoint.Host, endpoint.Port)
   620  
   621  	existingEndpoints := ordererAddrProto.Addresses[:0]
   622  	for _, e := range ordererAddrProto.Addresses {
   623  		if e != endpointToRemove {
   624  			existingEndpoints = append(existingEndpoints, e)
   625  		}
   626  	}
   627  
   628  	// Add orderer endpoints config value back to orderer org
   629  	err := setValue(o.orgGroup, endpointsValue(existingEndpoints), AdminsPolicyKey)
   630  	if err != nil {
   631  		return fmt.Errorf("failed to remove endpoint %v from orderer org %s: %v", endpoint, o.name, err)
   632  	}
   633  
   634  	return nil
   635  }
   636  
   637  // SetModPolicy sets the specified modification policy for the orderer group.
   638  func (o *OrdererGroup) SetModPolicy(modPolicy string) error {
   639  	if modPolicy == "" {
   640  		return errors.New("non empty mod policy is required")
   641  	}
   642  
   643  	o.ordererGroup.ModPolicy = modPolicy
   644  
   645  	return nil
   646  }
   647  
   648  // SetPolicy sets the specified policy in the orderer group's config policy map.
   649  // If the policy already exists in current configuration, its value will be overwritten.
   650  func (o *OrdererGroup) SetPolicy(policyName string, policy Policy) error {
   651  	err := setPolicy(o.ordererGroup, policyName, policy)
   652  	if err != nil {
   653  		return fmt.Errorf("failed to set policy '%s': %v", policyName, err)
   654  	}
   655  
   656  	return nil
   657  }
   658  
   659  // SetPolicies sets the specified policy in the orderer group's config policy map.
   660  // If the policies already exist in current configuration, the values will be replaced with new policies.
   661  func (o *OrdererGroup) SetPolicies(policies map[string]Policy) error {
   662  	if _, ok := policies[BlockValidationPolicyKey]; !ok {
   663  		return errors.New("BlockValidation policy must be defined")
   664  	}
   665  
   666  	err := setPolicies(o.ordererGroup, policies)
   667  	if err != nil {
   668  		return fmt.Errorf("failed to set policies: %v", err)
   669  	}
   670  
   671  	return nil
   672  }
   673  
   674  // RemovePolicy removes an existing orderer policy configuration.
   675  func (o *OrdererGroup) RemovePolicy(policyName string) error {
   676  	if policyName == BlockValidationPolicyKey {
   677  		return errors.New("BlockValidation policy must be defined")
   678  	}
   679  
   680  	policies, err := o.Policies()
   681  	if err != nil {
   682  		return err
   683  	}
   684  
   685  	removePolicy(o.ordererGroup, policyName, policies)
   686  	return nil
   687  }
   688  
   689  // Policies returns a map of policies for channel orderer in the
   690  // updated config.
   691  func (o *OrdererGroup) Policies() (map[string]Policy, error) {
   692  	return getPolicies(o.ordererGroup.Policies)
   693  }
   694  
   695  // SetMSP updates the MSP config for the specified orderer org
   696  // in the updated config.
   697  func (o *OrdererOrg) SetMSP(updatedMSP MSP) error {
   698  	currentMSP, err := o.MSP().Configuration()
   699  	if err != nil {
   700  		return fmt.Errorf("retrieving msp: %v", err)
   701  	}
   702  
   703  	if currentMSP.Name != updatedMSP.Name {
   704  		return errors.New("MSP name cannot be changed")
   705  	}
   706  
   707  	err = updatedMSP.validateCACerts()
   708  	if err != nil {
   709  		return err
   710  	}
   711  
   712  	err = updatedMSP.setConfig(o.orgGroup)
   713  	if err != nil {
   714  		return err
   715  	}
   716  
   717  	return nil
   718  }
   719  
   720  // SetModPolicy sets the specified modification policy for the orderer org group.
   721  func (o *OrdererOrg) SetModPolicy(modPolicy string) error {
   722  	if modPolicy == "" {
   723  		return errors.New("non empty mod policy is required")
   724  	}
   725  
   726  	o.orgGroup.ModPolicy = modPolicy
   727  
   728  	return nil
   729  }
   730  
   731  // SetPolicy sets the specified policy in the orderer org group's config policy map.
   732  // If the policy already exists in current configuration, its value will be overwritten.
   733  func (o *OrdererOrg) SetPolicy(policyName string, policy Policy) error {
   734  	return setPolicy(o.orgGroup, policyName, policy)
   735  }
   736  
   737  // SetPolicies sets the specified policies in the orderer org group's config policy map.
   738  // If the policies already exist in current configuration, the values will be replaced with new policies.
   739  func (o *OrdererOrg) SetPolicies(policies map[string]Policy) error {
   740  	return setPolicies(o.orgGroup, policies)
   741  }
   742  
   743  // RemovePolicy removes an existing policy from an orderer organization.
   744  func (o *OrdererOrg) RemovePolicy(policyName string) error {
   745  	policies, err := o.Policies()
   746  	if err != nil {
   747  		return err
   748  	}
   749  
   750  	removePolicy(o.orgGroup, policyName, policies)
   751  	return nil
   752  }
   753  
   754  // Policies returns a map of policies for a specific orderer org
   755  // in the updated config.
   756  func (o *OrdererOrg) Policies() (map[string]Policy, error) {
   757  	return getPolicies(o.orgGroup.Policies)
   758  }
   759  
   760  // RemoveLegacyKafkaBrokers removes the legacy kafka brokers config key and value from config.
   761  // In fabric 2.0, kafka was deprecated as a consensus type.
   762  func (o *OrdererGroup) RemoveLegacyKafkaBrokers() {
   763  	delete(o.ordererGroup.Values, orderer.KafkaBrokersKey)
   764  }
   765  
   766  // newOrdererGroup returns the orderer component of the channel configuration.
   767  // It defines parameters of the ordering service about how large blocks should be,
   768  // how frequently they should be emitted, etc. as well as the organizations of the ordering network.
   769  // It sets the mod_policy of all elements to "Admins".
   770  // This group is always present in any channel configuration.
   771  func newOrdererGroup(orderer Orderer) (*cb.ConfigGroup, error) {
   772  	ordererGroup := newConfigGroup()
   773  	ordererGroup.ModPolicy = AdminsPolicyKey
   774  
   775  	if orderer.ModPolicy != "" {
   776  		ordererGroup.ModPolicy = orderer.ModPolicy
   777  	}
   778  
   779  	if err := setOrdererPolicies(ordererGroup, orderer.Policies, AdminsPolicyKey); err != nil {
   780  		return nil, err
   781  	}
   782  
   783  	// add orderer values
   784  	err := addOrdererValues(ordererGroup, orderer)
   785  	if err != nil {
   786  		return nil, err
   787  	}
   788  
   789  	// add orderer groups
   790  	for _, org := range orderer.Organizations {
   791  		// As of fabric v1.4 we expect new system channels to contain orderer endpoints at the org level
   792  		if len(org.OrdererEndpoints) == 0 {
   793  			return nil, fmt.Errorf("orderer endpoints are not defined for org %s", org.Name)
   794  		}
   795  
   796  		ordererGroup.Groups[org.Name], err = newOrdererOrgConfigGroup(org)
   797  		if err != nil {
   798  			return nil, fmt.Errorf("org group '%s': %v", org.Name, err)
   799  		}
   800  	}
   801  
   802  	return ordererGroup, nil
   803  }
   804  
   805  // addOrdererValues adds configuration specified in Orderer to an orderer
   806  // *cb.ConfigGroup's Values map.
   807  func addOrdererValues(ordererGroup *cb.ConfigGroup, o Orderer) error {
   808  	err := setValue(ordererGroup, batchSizeValue(
   809  		o.BatchSize.MaxMessageCount,
   810  		o.BatchSize.AbsoluteMaxBytes,
   811  		o.BatchSize.PreferredMaxBytes,
   812  	), AdminsPolicyKey)
   813  	if err != nil {
   814  		return err
   815  	}
   816  
   817  	err = setValue(ordererGroup, batchTimeoutValue(o.BatchTimeout.String()), AdminsPolicyKey)
   818  	if err != nil {
   819  		return err
   820  	}
   821  
   822  	err = setValue(ordererGroup, channelRestrictionsValue(o.MaxChannels), AdminsPolicyKey)
   823  	if err != nil {
   824  		return err
   825  	}
   826  
   827  	if len(o.Capabilities) > 0 {
   828  		err = setValue(ordererGroup, capabilitiesValue(o.Capabilities), AdminsPolicyKey)
   829  		if err != nil {
   830  			return err
   831  		}
   832  	}
   833  
   834  	var consensusMetadata []byte
   835  
   836  	switch o.OrdererType {
   837  	case orderer.ConsensusTypeSolo:
   838  	case orderer.ConsensusTypeKafka:
   839  		err = setValue(ordererGroup, kafkaBrokersValue(o.Kafka.Brokers), AdminsPolicyKey)
   840  		if err != nil {
   841  			return err
   842  		}
   843  	case orderer.ConsensusTypeEtcdRaft:
   844  		if consensusMetadata, err = marshalEtcdRaftMetadata(o.EtcdRaft); err != nil {
   845  			return fmt.Errorf("marshaling etcdraft metadata for orderer type '%s': %v", orderer.ConsensusTypeEtcdRaft, err)
   846  		}
   847  	default:
   848  		return fmt.Errorf("unknown orderer type '%s'", o.OrdererType)
   849  	}
   850  
   851  	consensusState, ok := ob.ConsensusType_State_value[string(o.State)]
   852  	if !ok {
   853  		return fmt.Errorf("unknown consensus state '%s'", o.State)
   854  	}
   855  
   856  	err = setValue(ordererGroup, consensusTypeValue(o.OrdererType, consensusMetadata, consensusState), AdminsPolicyKey)
   857  	if err != nil {
   858  		return err
   859  	}
   860  
   861  	return nil
   862  }
   863  
   864  // setOrdererPolicies adds *cb.ConfigPolicies to the passed Orderer *cb.ConfigGroup's Policies map.
   865  // It checks that the BlockValidation policy is defined alongside the standard policy checks.
   866  func setOrdererPolicies(cg *cb.ConfigGroup, policyMap map[string]Policy, modPolicy string) error {
   867  	if policyMap == nil {
   868  		return errors.New("no policies defined")
   869  	}
   870  	if _, ok := policyMap[BlockValidationPolicyKey]; !ok {
   871  		return errors.New("no BlockValidation policy defined")
   872  	}
   873  
   874  	return setPolicies(cg, policyMap)
   875  }
   876  
   877  // batchSizeValue returns the config definition for the orderer batch size.
   878  // It is a value for the /Channel/Orderer group.
   879  func batchSizeValue(maxMessages, absoluteMaxBytes, preferredMaxBytes uint32) *standardConfigValue {
   880  	return &standardConfigValue{
   881  		key: orderer.BatchSizeKey,
   882  		value: &ob.BatchSize{
   883  			MaxMessageCount:   maxMessages,
   884  			AbsoluteMaxBytes:  absoluteMaxBytes,
   885  			PreferredMaxBytes: preferredMaxBytes,
   886  		},
   887  	}
   888  }
   889  
   890  // batchTimeoutValue returns the config definition for the orderer batch timeout.
   891  // It is a value for the /Channel/Orderer group.
   892  func batchTimeoutValue(timeout string) *standardConfigValue {
   893  	return &standardConfigValue{
   894  		key: orderer.BatchTimeoutKey,
   895  		value: &ob.BatchTimeout{
   896  			Timeout: timeout,
   897  		},
   898  	}
   899  }
   900  
   901  // endpointsValue returns the config definition for the orderer addresses at an org scoped level.
   902  // It is a value for the /Channel/Orderer/<OrgName> group.
   903  func endpointsValue(addresses []string) *standardConfigValue {
   904  	return &standardConfigValue{
   905  		key: EndpointsKey,
   906  		value: &cb.OrdererAddresses{
   907  			Addresses: addresses,
   908  		},
   909  	}
   910  }
   911  
   912  // channelRestrictionsValue returns the config definition for the orderer channel restrictions.
   913  // It is a value for the /Channel/Orderer group.
   914  func channelRestrictionsValue(maxChannelCount uint64) *standardConfigValue {
   915  	return &standardConfigValue{
   916  		key: orderer.ChannelRestrictionsKey,
   917  		value: &ob.ChannelRestrictions{
   918  			MaxCount: maxChannelCount,
   919  		},
   920  	}
   921  }
   922  
   923  // kafkaBrokersValue returns the config definition for the addresses of the ordering service's Kafka brokers.
   924  // It is a value for the /Channel/Orderer group.
   925  func kafkaBrokersValue(brokers []string) *standardConfigValue {
   926  	return &standardConfigValue{
   927  		key: orderer.KafkaBrokersKey,
   928  		value: &ob.KafkaBrokers{
   929  			Brokers: brokers,
   930  		},
   931  	}
   932  }
   933  
   934  // consensusTypeValue returns the config definition for the orderer consensus type.
   935  // It is a value for the /Channel/Orderer group.
   936  func consensusTypeValue(consensusType string, consensusMetadata []byte, consensusState int32) *standardConfigValue {
   937  	return &standardConfigValue{
   938  		key: orderer.ConsensusTypeKey,
   939  		value: &ob.ConsensusType{
   940  			Type:     consensusType,
   941  			Metadata: consensusMetadata,
   942  			State:    ob.ConsensusType_State(consensusState),
   943  		},
   944  	}
   945  }
   946  
   947  // marshalEtcdRaftMetadata serializes etcd RAFT metadata.
   948  func marshalEtcdRaftMetadata(md orderer.EtcdRaft) ([]byte, error) {
   949  	var consenters []*eb.Consenter
   950  
   951  	if len(md.Consenters) == 0 {
   952  		return nil, errors.New("consenters are required")
   953  	}
   954  
   955  	for _, c := range md.Consenters {
   956  		host := c.Address.Host
   957  		port := c.Address.Port
   958  
   959  		if c.ClientTLSCert == nil {
   960  			return nil, fmt.Errorf("client tls cert for consenter %s:%d is required", host, port)
   961  		}
   962  
   963  		if c.ServerTLSCert == nil {
   964  			return nil, fmt.Errorf("server tls cert for consenter %s:%d is required", host, port)
   965  		}
   966  
   967  		consenter := &eb.Consenter{
   968  			Host: host,
   969  			Port: uint32(port),
   970  			ClientTlsCert: pem.EncodeToMemory(&pem.Block{
   971  				Type:  "CERTIFICATE",
   972  				Bytes: c.ClientTLSCert.Raw,
   973  			}),
   974  			ServerTlsCert: pem.EncodeToMemory(&pem.Block{
   975  				Type:  "CERTIFICATE",
   976  				Bytes: c.ServerTLSCert.Raw,
   977  			}),
   978  		}
   979  
   980  		consenters = append(consenters, consenter)
   981  	}
   982  
   983  	configMetadata := &eb.ConfigMetadata{
   984  		Consenters: consenters,
   985  		Options: &eb.Options{
   986  			TickInterval:         md.Options.TickInterval,
   987  			ElectionTick:         md.Options.ElectionTick,
   988  			HeartbeatTick:        md.Options.HeartbeatTick,
   989  			MaxInflightBlocks:    md.Options.MaxInflightBlocks,
   990  			SnapshotIntervalSize: md.Options.SnapshotIntervalSize,
   991  		},
   992  	}
   993  
   994  	data, err := proto.Marshal(configMetadata)
   995  	if err != nil {
   996  		return nil, fmt.Errorf("marshaling config metadata: %v", err)
   997  	}
   998  
   999  	return data, nil
  1000  }
  1001  
  1002  // unmarshalEtcdRaftMetadata deserializes etcd RAFT metadata.
  1003  func unmarshalEtcdRaftMetadata(mdBytes []byte) (orderer.EtcdRaft, error) {
  1004  	etcdRaftMetadata := &eb.ConfigMetadata{}
  1005  	err := proto.Unmarshal(mdBytes, etcdRaftMetadata)
  1006  	if err != nil {
  1007  		return orderer.EtcdRaft{}, fmt.Errorf("unmarshaling etcd raft metadata: %v", err)
  1008  	}
  1009  
  1010  	consenters := []orderer.Consenter{}
  1011  
  1012  	for _, c := range etcdRaftMetadata.Consenters {
  1013  		clientTLSCertBlock, _ := pem.Decode(c.ClientTlsCert)
  1014  		if clientTLSCertBlock == nil {
  1015  			return orderer.EtcdRaft{}, fmt.Errorf("no PEM data found in client TLS cert[% x]", c.ClientTlsCert)
  1016  		}
  1017  		clientTLSCert, err := x509.ParseCertificate(clientTLSCertBlock.Bytes)
  1018  		if err != nil {
  1019  			return orderer.EtcdRaft{}, fmt.Errorf("unable to parse client tls cert: %v", err)
  1020  		}
  1021  		serverTLSCertBlock, _ := pem.Decode(c.ServerTlsCert)
  1022  		if serverTLSCertBlock == nil {
  1023  			return orderer.EtcdRaft{}, fmt.Errorf("no PEM data found in server TLS cert[% x]", c.ServerTlsCert)
  1024  		}
  1025  		serverTLSCert, err := x509.ParseCertificate(serverTLSCertBlock.Bytes)
  1026  		if err != nil {
  1027  			return orderer.EtcdRaft{}, fmt.Errorf("unable to parse server tls cert: %v", err)
  1028  		}
  1029  
  1030  		consenter := orderer.Consenter{
  1031  			Address: orderer.EtcdAddress{
  1032  				Host: c.Host,
  1033  				Port: int(c.Port),
  1034  			},
  1035  			ClientTLSCert: clientTLSCert,
  1036  			ServerTLSCert: serverTLSCert,
  1037  		}
  1038  
  1039  		consenters = append(consenters, consenter)
  1040  	}
  1041  
  1042  	if etcdRaftMetadata.Options == nil {
  1043  		return orderer.EtcdRaft{}, errors.New("missing etcdraft metadata options in config")
  1044  	}
  1045  
  1046  	return orderer.EtcdRaft{
  1047  		Consenters: consenters,
  1048  		Options: orderer.EtcdRaftOptions{
  1049  			TickInterval:         etcdRaftMetadata.Options.TickInterval,
  1050  			ElectionTick:         etcdRaftMetadata.Options.ElectionTick,
  1051  			HeartbeatTick:        etcdRaftMetadata.Options.HeartbeatTick,
  1052  			MaxInflightBlocks:    etcdRaftMetadata.Options.MaxInflightBlocks,
  1053  			SnapshotIntervalSize: etcdRaftMetadata.Options.SnapshotIntervalSize,
  1054  		},
  1055  	}, nil
  1056  }
  1057  
  1058  // getOrdererOrg returns the organization config group for an orderer org in the
  1059  // provided config. It returns nil if the org doesn't exist in the config.
  1060  func getOrdererOrg(config *cb.Config, orgName string) *cb.ConfigGroup {
  1061  	return config.ChannelGroup.Groups[OrdererGroupKey].Groups[orgName]
  1062  }
  1063  
  1064  // hashingAlgorithm returns the only currently valid hashing algorithm.
  1065  // It is a value for the /Channel group.
  1066  func hashingAlgorithmValue() *standardConfigValue {
  1067  	return &standardConfigValue{
  1068  		key: HashingAlgorithmKey,
  1069  		value: &cb.HashingAlgorithm{
  1070  			Name: defaultHashingAlgorithm,
  1071  		},
  1072  	}
  1073  }
  1074  
  1075  // blockDataHashingStructureValue returns the only currently valid block data hashing structure.
  1076  // It is a value for the /Channel group.
  1077  func blockDataHashingStructureValue() *standardConfigValue {
  1078  	return &standardConfigValue{
  1079  		key: BlockDataHashingStructureKey,
  1080  		value: &cb.BlockDataHashingStructure{
  1081  			Width: defaultBlockDataHashingStructureWidth,
  1082  		},
  1083  	}
  1084  }