-
Notifications
You must be signed in to change notification settings - Fork 6
/
eventsclient.go
277 lines (243 loc) · 7.65 KB
/
eventsclient.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"flag"
"fmt"
"io/ioutil"
"math"
"os"
"strings"
"time"
"github.com/hyperledger/fabric/common/crypto"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/common/localmsp"
genesisconfig "github.com/hyperledger/fabric/common/tools/configtxgen/localconfig"
"github.com/hyperledger/fabric/common/tools/protolator"
"github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric/core/comm"
config2 "github.com/hyperledger/fabric/core/config"
"github.com/hyperledger/fabric/msp"
common2 "github.com/hyperledger/fabric/peer/common"
"github.com/hyperledger/fabric/protos/common"
"github.com/hyperledger/fabric/protos/orderer"
"github.com/hyperledger/fabric/protos/peer"
"github.com/hyperledger/fabric/protos/utils"
"github.com/spf13/viper"
)
var (
channelID string
serverAddr string
clientKeyPath string
clientCertPath string
serverRootCAPath string
seek int
quiet bool
filtered bool
tlsEnabled bool
mTlsEnabled bool
oldest = &orderer.SeekPosition{Type: &orderer.SeekPosition_Oldest{Oldest: &orderer.SeekOldest{}}}
newest = &orderer.SeekPosition{Type: &orderer.SeekPosition_Newest{Newest: &orderer.SeekNewest{}}}
maxStop = &orderer.SeekPosition{Type: &orderer.SeekPosition_Specified{Specified: &orderer.SeekSpecified{Number: math.MaxUint64}}}
)
const (
OLDEST = -2
NEWEST = -1
ROOT = "core"
)
var logger = flogging.MustGetLogger("eventsclient")
// deliverClient abstracts common interface
// for deliver and deliverfiltered services
type deliverClient interface {
Send(*common.Envelope) error
Recv() (*peer.DeliverResponse, error)
}
// eventsClient client to get connected to the
// events peer delivery system
type eventsClient struct {
client deliverClient
signer crypto.LocalSigner
tlsCertHash []byte
}
func (r *eventsClient) seekOldest() error {
return r.client.Send(r.seekHelper(oldest, maxStop))
}
func (r *eventsClient) seekNewest() error {
return r.client.Send(r.seekHelper(newest, maxStop))
}
func (r *eventsClient) seekSingle(blockNumber uint64) error {
specific := &orderer.SeekPosition{Type: &orderer.SeekPosition_Specified{Specified: &orderer.SeekSpecified{Number: blockNumber}}}
return r.client.Send(r.seekHelper(specific, specific))
}
func (r *eventsClient) seekHelper(start *orderer.SeekPosition, stop *orderer.SeekPosition) *common.Envelope {
env, err := utils.CreateSignedEnvelopeWithTLSBinding(common.HeaderType_DELIVER_SEEK_INFO, channelID, r.signer, &orderer.SeekInfo{
Start: start,
Stop: stop,
Behavior: orderer.SeekInfo_BLOCK_UNTIL_READY,
}, 0, 0, r.tlsCertHash)
if err != nil {
panic(err)
}
return env
}
func (r *eventsClient) readEventsStream() {
for {
msg, err := r.client.Recv()
if err != nil {
logger.Info("Error receiving:", err)
return
}
switch t := msg.Type.(type) {
case *peer.DeliverResponse_Status:
logger.Info("Got status ", t)
return
case *peer.DeliverResponse_Block:
if !quiet {
logger.Info("Received block: ")
err := protolator.DeepMarshalJSON(os.Stdout, t.Block)
if err != nil {
fmt.Printf(" Error pretty printing block: %s", err)
}
} else {
logger.Info("Received block: ", t.Block.Header.Number)
}
case *peer.DeliverResponse_FilteredBlock:
if !quiet {
logger.Info("Received filtered block: ")
err := protolator.DeepMarshalJSON(os.Stdout, t.FilteredBlock)
if err != nil {
fmt.Printf(" Error pretty printing filtered block: %s", err)
}
} else {
logger.Info("Received filtered block: ", t.FilteredBlock.Number)
}
}
}
}
func (r *eventsClient) seek(s int) error {
var err error
switch seek {
case OLDEST:
err = r.seekOldest()
case NEWEST:
err = r.seekNewest()
default:
err = r.seekSingle(uint64(seek))
}
return err
}
func main() {
initConfig()
initMSP()
readCLInputs()
if seek < OLDEST {
logger.Info("Invalid seek value")
flag.PrintDefaults()
return
}
clientConfig := comm.ClientConfig{
KaOpts: comm.DefaultKeepaliveOptions,
SecOpts: &comm.SecureOptions{},
Timeout: 5 * time.Minute,
}
if tlsEnabled {
clientConfig.SecOpts.UseTLS = true
rootCert, err := ioutil.ReadFile(serverRootCAPath)
if err != nil {
logger.Info("error loading TLS root certificate", err)
return
}
clientConfig.SecOpts.ServerRootCAs = [][]byte{rootCert}
if mTlsEnabled {
clientConfig.SecOpts.RequireClientCert = true
clientKey, err := ioutil.ReadFile(clientKeyPath)
if err != nil {
logger.Info("error loading client TLS key from", clientKeyPath)
return
}
clientConfig.SecOpts.Key = clientKey
clientCert, err := ioutil.ReadFile(clientCertPath)
if err != nil {
logger.Info("error loading client TLS certificate from path", clientCertPath)
return
}
clientConfig.SecOpts.Certificate = clientCert
}
}
grpcClient, err := comm.NewGRPCClient(clientConfig)
if err != nil {
logger.Info("Error creating grpc client:", err)
return
}
conn, err := grpcClient.NewConnection(serverAddr, "")
if err != nil {
logger.Info("Error connecting:", err)
return
}
var client deliverClient
if filtered {
client, err = peer.NewDeliverClient(conn).DeliverFiltered(context.Background())
} else {
client, err = peer.NewDeliverClient(conn).Deliver(context.Background())
}
if err != nil {
logger.Info("Error connecting:", err)
return
}
events := &eventsClient{
client: client,
signer: localmsp.NewSigner(),
}
if mTlsEnabled {
events.tlsCertHash = util.ComputeSHA256(grpcClient.Certificate().Certificate[0])
}
events.seek(seek)
if err != nil {
logger.Info("Received error:", err)
return
}
events.readEventsStream()
}
func readCLInputs() {
flag.StringVar(&serverAddr, "server", "localhost:7051", "The RPC server to connect to.")
flag.StringVar(&channelID, "channelID", genesisconfig.TestChainID, "The channel ID to deliver from.")
flag.BoolVar(&quiet, "quiet", false, "Only print the block number, will not attempt to print its block contents.")
flag.BoolVar(&filtered, "filtered", true, "Whenever to read filtered events from the peer delivery service or get regular blocks.")
flag.BoolVar(&tlsEnabled, "tls", false, "TLS enabled/disabled")
flag.BoolVar(&mTlsEnabled, "mTls", false, "Mutual TLS enabled/disabled (whenever server side validates clients TLS certificate)")
flag.StringVar(&clientKeyPath, "clientKey", "", "Specify path to the client TLS key")
flag.StringVar(&clientCertPath, "clientCert", "", "Specify path to the client TLS certificate")
flag.StringVar(&serverRootCAPath, "rootCert", "", "Specify path to the server root CA certificate")
flag.IntVar(&seek, "seek", OLDEST, "Specify the range of requested blocks."+
"Acceptable values:"+
"-2 (or -1) to start from oldest (or newest) and keep at it indefinitely."+
"N >= 0 to fetch block N only.")
flag.Parse()
}
func initMSP() {
// Init the MSP
var mspMgrConfigDir = config2.GetPath("peer.mspConfigPath")
var mspID = viper.GetString("peer.localMspId")
var mspType = viper.GetString("peer.localMspType")
if mspType == "" {
mspType = msp.ProviderTypeToString(msp.FABRIC)
}
err := common2.InitCrypto(mspMgrConfigDir, mspID, mspType)
if err != nil { // Handle errors reading the config file
panic(fmt.Sprintf("Cannot run client because %s", err.Error()))
}
}
func initConfig() {
// For environment variables.
viper.SetEnvPrefix(ROOT)
viper.AutomaticEnv()
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
err := common2.InitConfig(ROOT)
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("fatal error when initializing %s config : %s", ROOT, err))
}
}