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