github.com/Hnampk/fabric@v2.1.1+incompatible/cmd/common/comm/client.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  	"time"
    11  
    12  	"github.com/hyperledger/fabric/common/crypto/tlsgen"
    13  	"github.com/hyperledger/fabric/common/util"
    14  	"github.com/hyperledger/fabric/internal/pkg/comm"
    15  	"github.com/pkg/errors"
    16  	"google.golang.org/grpc"
    17  )
    18  
    19  const defaultTimeout = time.Second * 5
    20  
    21  // Client deals with TLS connections
    22  // to the discovery server
    23  type Client struct {
    24  	TLSCertHash []byte
    25  	*comm.GRPCClient
    26  }
    27  
    28  // NewClient creates a new comm client out of the given configuration
    29  func NewClient(conf Config) (*Client, error) {
    30  	if conf.Timeout == time.Duration(0) {
    31  		conf.Timeout = defaultTimeout
    32  	}
    33  	sop, err := conf.ToSecureOptions(newSelfSignedTLSCert)
    34  	if err != nil {
    35  		return nil, errors.WithStack(err)
    36  	}
    37  	cl, err := comm.NewGRPCClient(comm.ClientConfig{
    38  		SecOpts: sop,
    39  		Timeout: conf.Timeout,
    40  	})
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	return &Client{GRPCClient: cl, TLSCertHash: util.ComputeSHA256(sop.Certificate)}, nil
    45  }
    46  
    47  // NewDialer creates a new dialer from the given endpoint
    48  func (c *Client) NewDialer(endpoint string) func() (*grpc.ClientConn, error) {
    49  	return func() (*grpc.ClientConn, error) {
    50  		conn, err := c.NewConnection(endpoint)
    51  		if err != nil {
    52  			return nil, errors.WithStack(err)
    53  		}
    54  		return conn, nil
    55  	}
    56  }
    57  
    58  func newSelfSignedTLSCert() (*tlsgen.CertKeyPair, error) {
    59  	ca, err := tlsgen.NewCA()
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	return ca.NewClientCertKeyPair()
    64  }