-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathevent.go
385 lines (343 loc) · 10.1 KB
/
event.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
Copyright: Cognition Foundry. All Rights Reserved.
License: Apache License Version 2.0
*/
package gohfc
import (
"context"
"google.golang.org/grpc"
"time"
"fmt"
"github.com/hyperledger/fabric/protos/orderer"
"math"
"github.com/hyperledger/fabric/protos/common"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/protos/peer"
)
const (
EventTypeFullBlock = iota
EventTypeFiltered
)
const (
maxRecvMsgSize = 100 * 1024 * 1024
maxSendMsgSize = 100 * 1024 * 1024
)
var (
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}}}
)
type deliveryClient interface {
Send(*common.Envelope) error
Recv() (*peer.DeliverResponse, error)
}
type EventListener struct {
Peer Peer
Context context.Context
Identity Identity
Crypto CryptoSuite
ChannelId string
ListenerType int
FullBlock bool
connection *grpc.ClientConn
client deliveryClient
}
type EventBlockResponse struct {
Error error
ChannelId string
BlockHeight uint64
Transactions []EventBlockResponseTransaction
RawBlock []byte
}
type EventBlockResponseTransaction struct {
Id string
Type string
Status string
ChainCodeId string
Events []EventBlockResponseTransactionEvent
}
type EventBlockResponseTransactionEvent struct {
Name string
Value []byte
}
func (e *EventListener) newConnection() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
conn, err := grpc.DialContext(ctx, e.Peer.Uri, e.Peer.Opts...)
if err != nil {
return fmt.Errorf("cannot make new connection to: %s err: %v", e.Peer.Uri, err)
}
e.connection = conn
switch e.ListenerType {
case EventTypeFiltered:
client, err := peer.NewDeliverClient(e.connection).DeliverFiltered(e.Context)
if err != nil {
return err
}
e.client = client
case EventTypeFullBlock:
client, err := peer.NewDeliverClient(e.connection).Deliver(e.Context)
if err != nil {
return err
}
e.client = client
default:
return fmt.Errorf("invalid listener type provided")
}
return nil
}
func (e *EventListener) SeekNewest() error {
if e.connection == nil || e.client == nil {
return fmt.Errorf("cannot seek no connection or client")
}
seek, err := e.createSeekEnvelope(newest, maxStop)
if err != nil {
return err
}
return e.client.Send(seek)
}
func (e *EventListener) SeekOldest() error {
if e.connection == nil || e.client == nil {
return fmt.Errorf("cannot seek no connection or client")
}
seek, err := e.createSeekEnvelope(oldest, maxStop)
if err != nil {
return err
}
return e.client.Send(seek)
}
func (e *EventListener) SeekSingle(num uint64) error {
if e.connection == nil || e.client == nil {
return fmt.Errorf("cannot seek no connection or client")
}
pos := &orderer.SeekPosition{Type: &orderer.SeekPosition_Specified{Specified: &orderer.SeekSpecified{Number: num}}}
seek, err := e.createSeekEnvelope(pos, pos)
if err != nil {
return err
}
return e.client.Send(seek)
}
func (e *EventListener) SeekRange(start, end uint64) error {
if e.connection == nil || e.client == nil {
return fmt.Errorf("cannot seek no connection or client")
}
if start > end {
return fmt.Errorf("start: %d cannot be bigger than end: %d", start, end)
}
startPos := &orderer.SeekPosition{Type: &orderer.SeekPosition_Specified{Specified: &orderer.SeekSpecified{Number: start}}}
endPos := &orderer.SeekPosition{Type: &orderer.SeekPosition_Specified{Specified: &orderer.SeekSpecified{Number: end}}}
seek, err := e.createSeekEnvelope(startPos, endPos)
if err != nil {
return err
}
return e.client.Send(seek)
}
func (e *EventListener) Listen(response chan<- EventBlockResponse) {
go func() {
for {
msg, err := e.client.Recv()
if err != nil {
response <- EventBlockResponse{Error: fmt.Errorf("error receiving data:%v", err)}
return
}
switch t := msg.Type.(type) {
case *peer.DeliverResponse_Block:
response <- *e.parseFullBlock(t, e.FullBlock)
case *peer.DeliverResponse_FilteredBlock:
response <- *e.parseFilteredBlock(t, e.FullBlock)
}
}
}()
}
func (e *EventListener) parseFilteredBlock(block *peer.DeliverResponse_FilteredBlock, fullBlock bool) (*EventBlockResponse) {
response := &EventBlockResponse{
ChannelId: block.FilteredBlock.ChannelId,
BlockHeight: block.FilteredBlock.Number,
Transactions: make([]EventBlockResponseTransaction, len(block.FilteredBlock.FilteredTransactions)),
}
if fullBlock {
m, err := proto.Marshal(block.FilteredBlock)
if err != nil {
response.Error = err
return response
}
response.RawBlock = m
}
for _, t := range block.FilteredBlock.FilteredTransactions {
transaction := EventBlockResponseTransaction{
Type: common.HeaderType_name[int32(t.Type)],
Id: t.Txid,
Status: peer.TxValidationCode_name[int32(t.TxValidationCode)],
}
if t.Type != common.HeaderType_ENDORSER_TRANSACTION {
continue
}
switch data := t.Data.(type) {
case *peer.FilteredTransaction_TransactionActions:
if len(data.TransactionActions.ChaincodeActions) > 0 {
transaction.ChainCodeId = data.TransactionActions.ChaincodeActions[0].ChaincodeEvent.ChaincodeId
for _, e := range data.TransactionActions.ChaincodeActions {
transaction.Events = append(transaction.Events, EventBlockResponseTransactionEvent{
Name: e.ChaincodeEvent.EventName,
})
}
}
response.Transactions = append(response.Transactions, transaction)
default:
response.Error = fmt.Errorf("filterd actions are with unknown type: %T", t.Data)
return response
}
}
return response
}
func (e *EventListener) parseFullBlock(block *peer.DeliverResponse_Block, fullBlock bool) (*EventBlockResponse) {
response := &EventBlockResponse{
BlockHeight: block.Block.Header.Number,
}
if fullBlock {
m, err := proto.Marshal(block.Block)
if err != nil {
response.Error = err
return response
}
response.RawBlock = m
}
for idx, pl := range block.Block.Data.Data {
transaction := EventBlockResponseTransaction{}
envelope := new(common.Envelope)
payload := new(common.Payload)
header := new(common.ChannelHeader)
ex := &peer.ChaincodeHeaderExtension{}
if err := proto.Unmarshal(pl, envelope); err != nil {
response.Error = err
return response
}
if err := proto.Unmarshal(envelope.Payload, payload); err != nil {
response.Error = err
}
if err := proto.Unmarshal(payload.Header.ChannelHeader, header); err != nil {
response.Error = err
return response
}
if err := proto.Unmarshal(header.Extension, ex); err != nil {
response.Error = err
return response
}
response.ChannelId = header.ChannelId
transaction.Id = header.TxId
transaction.Status = peer.TxValidationCode_name[int32(block.Block.Metadata.Metadata[2][idx])]
transaction.Type = common.HeaderType_name[header.Type]
if common.HeaderType(header.Type) == common.HeaderType_ENDORSER_TRANSACTION {
transaction.ChainCodeId = ex.ChaincodeId.Name
tx := &peer.Transaction{}
err := proto.Unmarshal(payload.Data, tx)
if err != nil {
response.Error = err
return response
}
chainCodeActionPayload := &peer.ChaincodeActionPayload{}
err = proto.Unmarshal(tx.Actions[0].Payload, chainCodeActionPayload)
if err != nil {
response.Error = err
return response
}
propRespPayload := &peer.ProposalResponsePayload{}
err = proto.Unmarshal(chainCodeActionPayload.Action.ProposalResponsePayload, propRespPayload)
if err != nil {
response.Error = err
return response
}
caPayload := &peer.ChaincodeAction{}
err = proto.Unmarshal(propRespPayload.Extension, caPayload)
if err != nil {
response.Error = err
return response
}
ccEvent := &peer.ChaincodeEvent{}
err = proto.Unmarshal(caPayload.Events, ccEvent)
if err != nil {
response.Error = err
return response
}
if ccEvent != nil {
transaction.Events = append(transaction.Events,
EventBlockResponseTransactionEvent{Name: ccEvent.EventName, Value: ccEvent.Payload})
}
}
response.Transactions = append(response.Transactions, transaction)
}
return response
}
func (e *EventListener) createSeekEnvelope(start *orderer.SeekPosition, stop *orderer.SeekPosition) (*common.Envelope, error) {
marshaledIdentity, err := marshalProtoIdentity(e.Identity)
if err != nil {
return nil, err
}
nonce, err := generateRandomBytes(24)
if err != nil {
return nil, err
}
channelHeader, err := proto.Marshal(&common.ChannelHeader{
Type: int32(common.HeaderType_DELIVER_SEEK_INFO),
Version: 0,
Timestamp: ×tamp.Timestamp{
Seconds: time.Now().Unix(),
Nanos: 0,
},
ChannelId: e.ChannelId,
Epoch: 0,
// TlsCertHash:[]
})
if err != nil {
return nil, err
}
sigHeader, err := proto.Marshal(&common.SignatureHeader{
Creator: marshaledIdentity,
Nonce: nonce,
})
if err != nil {
return nil, err
}
data, err := proto.Marshal(&orderer.SeekInfo{
Start: start,
Stop: stop,
Behavior: orderer.SeekInfo_BLOCK_UNTIL_READY,
})
if err != nil {
return nil, err
}
payload, err := proto.Marshal(&common.Payload{
Header: &common.Header{
ChannelHeader: channelHeader,
SignatureHeader: sigHeader,
},
Data: data,
})
if err != nil {
return nil, err
}
sig, err := e.Crypto.Sign(payload, e.Identity.PrivateKey)
if err != nil {
return nil, err
}
return &common.Envelope{Payload: payload, Signature: sig}, nil
}
func NewEventListener(ctx context.Context, crypto CryptoSuite, identity Identity, p Peer, channelId string, listenerType int) (*EventListener, error) {
if crypto == nil {
return nil, fmt.Errorf("cryptoSuite cannot be nil")
}
listener := EventListener{
Context: ctx,
Peer: p,
Identity: identity,
ChannelId: channelId,
Crypto: crypto,
ListenerType: listenerType,
FullBlock: false,
}
if err := listener.newConnection(); err != nil {
return nil, err
}
return &listener, nil
}