github.com/kaituanwang/hyperledger@v2.0.1+incompatible/msp/mgmt/principal.go (about)

     1  /*
     2  Copyright IBM Corp. 2017 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package mgmt
    18  
    19  import (
    20  	"github.com/golang/protobuf/proto"
    21  	"github.com/hyperledger/fabric-protos-go/msp"
    22  	"github.com/hyperledger/fabric/bccsp"
    23  	"github.com/pkg/errors"
    24  )
    25  
    26  const (
    27  	// Admins is the label for the local MSP admins
    28  	Admins = "Admins"
    29  
    30  	// Members is the label for the local MSP members
    31  	Members = "Members"
    32  )
    33  
    34  type MSPPrincipalGetter interface {
    35  	// Get returns an MSP principal for the given role
    36  	Get(role string) (*msp.MSPPrincipal, error)
    37  }
    38  
    39  func NewLocalMSPPrincipalGetter(cryptoProvider bccsp.BCCSP) MSPPrincipalGetter {
    40  	return &localMSPPrincipalGetter{
    41  		cryptoProvider: cryptoProvider,
    42  	}
    43  }
    44  
    45  type localMSPPrincipalGetter struct {
    46  	cryptoProvider bccsp.BCCSP
    47  }
    48  
    49  func (m *localMSPPrincipalGetter) Get(role string) (*msp.MSPPrincipal, error) {
    50  	mspid, err := GetLocalMSP(m.cryptoProvider).GetIdentifier()
    51  	if err != nil {
    52  		return nil, errors.WithMessage(err, "could not extract local msp identifier")
    53  	}
    54  
    55  	switch role {
    56  	case Admins:
    57  		principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_ADMIN, MspIdentifier: mspid})
    58  		if err != nil {
    59  			return nil, errors.Wrap(err, "marshalling failed")
    60  		}
    61  
    62  		return &msp.MSPPrincipal{
    63  			PrincipalClassification: msp.MSPPrincipal_ROLE,
    64  			Principal:               principalBytes}, nil
    65  	case Members:
    66  		principalBytes, err := proto.Marshal(&msp.MSPRole{Role: msp.MSPRole_MEMBER, MspIdentifier: mspid})
    67  		if err != nil {
    68  			return nil, errors.Wrap(err, "marshalling failed")
    69  		}
    70  
    71  		return &msp.MSPPrincipal{
    72  			PrincipalClassification: msp.MSPPrincipal_ROLE,
    73  			Principal:               principalBytes}, nil
    74  	default:
    75  		return nil, errors.Errorf("MSP Principal role [%s] not recognized", role)
    76  	}
    77  }