github.com/lzy4123/fabric@v2.1.1+incompatible/gossip/util/grpc.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package util 8 9 import ( 10 "crypto/tls" 11 "crypto/x509" 12 "fmt" 13 "net" 14 "strconv" 15 "time" 16 17 "github.com/hyperledger/fabric/common/crypto/tlsgen" 18 "github.com/hyperledger/fabric/gossip/api" 19 "github.com/hyperledger/fabric/gossip/common" 20 "github.com/hyperledger/fabric/internal/pkg/comm" 21 "google.golang.org/grpc" 22 "google.golang.org/grpc/credentials" 23 ) 24 25 // CA that generates TLS key-pairs 26 var ca = createCAOrPanic() 27 28 func createCAOrPanic() tlsgen.CA { 29 ca, err := tlsgen.NewCA() 30 if err != nil { 31 panic(fmt.Sprintf("failed creating CA: %+v", err)) 32 } 33 return ca 34 } 35 36 // CreateGRPCLayer returns a new gRPC server with associated port, TLS certificates, SecureDialOpts and DialOption 37 func CreateGRPCLayer() (port int, gRPCServer *comm.GRPCServer, certs *common.TLSCertificates, 38 secureDialOpts api.PeerSecureDialOpts, dialOpts []grpc.DialOption) { 39 40 serverKeyPair, err := ca.NewServerCertKeyPair("127.0.0.1") 41 if err != nil { 42 panic(err) 43 } 44 clientKeyPair, err := ca.NewClientCertKeyPair() 45 if err != nil { 46 panic(err) 47 } 48 49 tlsServerCert, err := tls.X509KeyPair(serverKeyPair.Cert, serverKeyPair.Key) 50 if err != nil { 51 panic(err) 52 } 53 tlsClientCert, err := tls.X509KeyPair(clientKeyPair.Cert, clientKeyPair.Key) 54 if err != nil { 55 panic(err) 56 } 57 58 tlsConf := &tls.Config{ 59 Certificates: []tls.Certificate{tlsClientCert}, 60 ClientAuth: tls.RequestClientCert, 61 RootCAs: x509.NewCertPool(), 62 } 63 64 tlsConf.RootCAs.AppendCertsFromPEM(ca.CertBytes()) 65 66 ta := credentials.NewTLS(tlsConf) 67 dialOpts = append(dialOpts, grpc.WithTransportCredentials(ta)) 68 69 secureDialOpts = func() []grpc.DialOption { 70 return dialOpts 71 } 72 73 certs = &common.TLSCertificates{} 74 certs.TLSServerCert.Store(&tlsServerCert) 75 certs.TLSClientCert.Store(&tlsClientCert) 76 77 srvConfig := comm.ServerConfig{ 78 ConnectionTimeout: time.Second, 79 SecOpts: comm.SecureOptions{ 80 Key: serverKeyPair.Key, 81 Certificate: serverKeyPair.Cert, 82 UseTLS: true, 83 }, 84 } 85 gRPCServer, err = comm.NewGRPCServer("127.0.0.1:", srvConfig) 86 if err != nil { 87 panic(err) 88 } 89 90 _, portString, err := net.SplitHostPort(gRPCServer.Address()) 91 if err != nil { 92 panic(err) 93 } 94 portInt, err := strconv.Atoi(portString) 95 if err != nil { 96 panic(err) 97 } 98 99 return portInt, gRPCServer, certs, secureDialOpts, dialOpts 100 }