github.com/ewagmig/fabric@v2.1.1+incompatible/cmd/common/comm/config.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package comm
     8  
     9  import (
    10  	"io/ioutil"
    11  	"time"
    12  
    13  	"github.com/hyperledger/fabric/common/crypto/tlsgen"
    14  	"github.com/hyperledger/fabric/internal/pkg/comm"
    15  	"github.com/pkg/errors"
    16  )
    17  
    18  type genTLSCertFunc func() (*tlsgen.CertKeyPair, error)
    19  
    20  // Config defines configuration of a Client
    21  type Config struct {
    22  	CertPath       string
    23  	KeyPath        string
    24  	PeerCACertPath string
    25  	Timeout        time.Duration
    26  }
    27  
    28  // ToSecureOptions converts this Config to SecureOptions.
    29  // The given function generates a self signed client TLS certificate if
    30  // the TLS certificate and key aren't present at the config
    31  func (conf Config) ToSecureOptions(newSelfSignedTLSCert genTLSCertFunc) (comm.SecureOptions, error) {
    32  	if conf.PeerCACertPath == "" {
    33  		return comm.SecureOptions{}, nil
    34  	}
    35  	caBytes, err := loadFile(conf.PeerCACertPath)
    36  	if err != nil {
    37  		return comm.SecureOptions{}, errors.WithStack(err)
    38  	}
    39  	var keyBytes, certBytes []byte
    40  	// If TLS key and certificate aren't given, generate a self signed one on the fly
    41  	if conf.KeyPath == "" && conf.CertPath == "" {
    42  		tlsCert, err := newSelfSignedTLSCert()
    43  		if err != nil {
    44  			return comm.SecureOptions{}, err
    45  		}
    46  		keyBytes, certBytes = tlsCert.Key, tlsCert.Cert
    47  	} else {
    48  		keyBytes, err = loadFile(conf.KeyPath)
    49  		if err != nil {
    50  			return comm.SecureOptions{}, errors.WithStack(err)
    51  		}
    52  		certBytes, err = loadFile(conf.CertPath)
    53  		if err != nil {
    54  			return comm.SecureOptions{}, errors.WithStack(err)
    55  		}
    56  	}
    57  	return comm.SecureOptions{
    58  		Key:               keyBytes,
    59  		Certificate:       certBytes,
    60  		UseTLS:            true,
    61  		ServerRootCAs:     [][]byte{caBytes},
    62  		RequireClientCert: true,
    63  	}, nil
    64  }
    65  
    66  func loadFile(path string) ([]byte, error) {
    67  	b, err := ioutil.ReadFile(path)
    68  	if err != nil {
    69  		return nil, errors.Errorf("Failed opening file %s: %v", path, err)
    70  	}
    71  	return b, nil
    72  }