forked from hyperledger/fabric-sdk-go
/
eventmocks.go
348 lines (296 loc) · 9.21 KB
/
eventmocks.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package events
import (
"encoding/hex"
"fmt"
"testing"
"time"
"github.com/hyperledger/fabric-sdk-go/config"
fabricClient "github.com/hyperledger/fabric-sdk-go/fabric-client"
consumer "github.com/hyperledger/fabric-sdk-go/fabric-client/events/consumer"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/bccsp/factory"
bccspFactory "github.com/hyperledger/fabric/bccsp/factory"
ledger_util "github.com/hyperledger/fabric/core/ledger/util"
fcConsumer "github.com/hyperledger/fabric/events/consumer"
"github.com/hyperledger/fabric/protos/common"
pb "github.com/hyperledger/fabric/protos/peer"
)
type mockEventClientMockEventRegistration struct {
Action string
ies []*pb.Interest
}
type mockEventClient struct {
PeerAddress string
RegTimeout time.Duration
Adapter fcConsumer.EventAdapter
Started int
Stopped int
Registrations []mockEventClientMockEventRegistration
events chan pb.Event
}
type mockEventClientFactory struct {
clients []*mockEventClient
}
func (mecf *mockEventClientFactory) newEventsClient(client fabricClient.Client, peerAddress string, certificate string, serverHostOverride string, regTimeout time.Duration, adapter fcConsumer.EventAdapter) (consumer.EventsClient, error) {
mec := &mockEventClient{
PeerAddress: peerAddress,
RegTimeout: regTimeout,
Adapter: adapter,
events: make(chan pb.Event),
}
mecf.clients = append(mecf.clients, mec)
return mec, nil
}
// MockEvent mocks an event
func (mec *mockEventClient) MockEvent(msg *pb.Event) (bool, error) {
if mec.Started > mec.Stopped {
return mec.Adapter.Recv(msg)
}
mec.events <- *msg
return true, nil
}
// RegisterAsync does not register anything anywhere but acts like all is well
func (mec *mockEventClient) RegisterAsync(ies []*pb.Interest) error {
mec.Registrations = append(mec.Registrations, mockEventClientMockEventRegistration{
Action: "register",
ies: ies,
})
return nil
}
// UnregisterAsync does not unregister anything anywhere but acts like all is well
func (mec *mockEventClient) UnregisterAsync(ies []*pb.Interest) error {
mec.Registrations = append(mec.Registrations, mockEventClientMockEventRegistration{
Action: "register",
ies: ies,
})
return nil
}
// Unregister does not unregister anything anywhere but acts like all is well
func (mec *mockEventClient) Unregister(ies []*pb.Interest) error {
return mec.UnregisterAsync(ies)
}
// Recv will return mock events sent to the event channel. Warning! This might block indefinitely
func (mec *mockEventClient) Recv() (*pb.Event, error) {
event := <-mec.events
return &event, nil
}
// Start does not start anything
func (mec *mockEventClient) Start() error {
mec.Started++
return nil
}
// Stop does not stop anything
func (mec *mockEventClient) Stop() error {
mec.Stopped++
return nil
}
func createMockedEventHub(t *testing.T) (*eventHub, *mockEventClientFactory) {
// Initialize bccsp factories before calling get client
err := bccspFactory.InitFactories(config.GetCSPConfig())
if err != nil {
t.Fatalf("Failed getting ephemeral software-based BCCSP [%s]", err)
}
eh, err := NewEventHub(fabricClient.NewClient())
if err != nil {
t.Fatalf("Error creating event hub: %v", err)
}
eventHub, ok := eh.(*eventHub)
if !ok {
t.Fatalf("Could not create eventHub")
return nil, nil
}
var clientFactory mockEventClientFactory
eventHub.eventsClientFactory = &clientFactory
eventHub.SetPeerAddr("mock://mock", "", "")
err = eventHub.Connect()
if err != nil {
t.Fatalf("Failed to connect: %v", err)
return nil, nil
}
return eventHub, &clientFactory
}
// MockTxEventBuilder builds a mock TX event block
type MockTxEventBuilder struct {
ChannelID string
TxID string
}
// MockCCEventBuilder builds a mock chaincode event
type MockCCEventBuilder struct {
CCID string
EventName string
Payload []byte
}
// MockCCBlockEventBuilder builds a mock CC event block
type MockCCBlockEventBuilder struct {
CCID string
EventName string
ChannelID string
TxID string
Payload []byte
}
// Build builds a mock TX event block
func (b *MockTxEventBuilder) Build() *pb.Event_Block {
return &pb.Event_Block{
Block: &common.Block{
Header: &common.BlockHeader{},
Metadata: b.buildBlockMetadata(),
Data: &common.BlockData{
Data: [][]byte{fabricClient.MarshalOrPanic(b.buildEnvelope())},
},
},
}
}
func (b *MockTxEventBuilder) buildBlockMetadata() *common.BlockMetadata {
return &common.BlockMetadata{
Metadata: [][]byte{
[]byte{},
[]byte{},
b.buildTransactionsFilterMetaDataBytes(),
[]byte{},
},
}
}
func (b *MockTxEventBuilder) buildTransactionsFilterMetaDataBytes() []byte {
return []byte(ledger_util.TxValidationFlags{uint8(pb.TxValidationCode_VALID)})
}
// Build builds a mock chaincode event
func (b *MockCCEventBuilder) Build() *pb.Event_ChaincodeEvent {
return &pb.Event_ChaincodeEvent{
ChaincodeEvent: &pb.ChaincodeEvent{
ChaincodeId: b.CCID,
EventName: b.EventName,
Payload: b.Payload,
},
}
}
func (b *MockTxEventBuilder) buildEnvelope() *common.Envelope {
return &common.Envelope{
Payload: fabricClient.MarshalOrPanic(b.buildPayload()),
}
}
func (b *MockTxEventBuilder) buildPayload() *common.Payload {
return &common.Payload{
Header: &common.Header{
ChannelHeader: fabricClient.MarshalOrPanic(b.buildChannelHeader()),
},
}
}
func (b *MockTxEventBuilder) buildChannelHeader() *common.ChannelHeader {
return &common.ChannelHeader{
TxId: b.TxID,
ChannelId: b.ChannelID,
}
}
// Build builds a mock chaincode event block
func (b *MockCCBlockEventBuilder) Build() *pb.Event_Block {
return &pb.Event_Block{
Block: &common.Block{
Header: &common.BlockHeader{},
Metadata: b.buildBlockMetadata(),
Data: &common.BlockData{
Data: [][]byte{fabricClient.MarshalOrPanic(b.buildEnvelope())},
},
},
}
}
func (b *MockCCBlockEventBuilder) buildBlockMetadata() *common.BlockMetadata {
return &common.BlockMetadata{
Metadata: [][]byte{
[]byte{},
[]byte{},
b.buildTransactionsFilterMetaDataBytes(),
[]byte{},
},
}
}
func (b *MockCCBlockEventBuilder) buildEnvelope() *common.Envelope {
return &common.Envelope{
Payload: fabricClient.MarshalOrPanic(b.buildPayload()),
}
}
func (b *MockCCBlockEventBuilder) buildTransactionsFilterMetaDataBytes() []byte {
return []byte(ledger_util.TxValidationFlags{uint8(pb.TxValidationCode_VALID)})
}
func (b *MockCCBlockEventBuilder) buildPayload() *common.Payload {
fmt.Printf("MockCCBlockEventBuilder.buildPayload\n")
return &common.Payload{
Header: &common.Header{
ChannelHeader: fabricClient.MarshalOrPanic(b.buildChannelHeader()),
},
Data: fabricClient.MarshalOrPanic(b.buildTransaction()),
}
}
func (b *MockCCBlockEventBuilder) buildChannelHeader() *common.ChannelHeader {
return &common.ChannelHeader{
Type: int32(common.HeaderType_ENDORSER_TRANSACTION),
TxId: b.TxID,
ChannelId: b.ChannelID,
}
}
func (b *MockCCBlockEventBuilder) buildTransaction() *pb.Transaction {
return &pb.Transaction{
Actions: []*pb.TransactionAction{b.buildTransactionAction()},
}
}
func (b *MockCCBlockEventBuilder) buildTransactionAction() *pb.TransactionAction {
return &pb.TransactionAction{
Header: []byte{},
Payload: fabricClient.MarshalOrPanic(b.buildChaincodeActionPayload()),
}
}
func (b *MockCCBlockEventBuilder) buildChaincodeActionPayload() *pb.ChaincodeActionPayload {
return &pb.ChaincodeActionPayload{
Action: b.buildChaincodeEndorsedAction(),
ChaincodeProposalPayload: []byte{},
}
}
func (b *MockCCBlockEventBuilder) buildChaincodeEndorsedAction() *pb.ChaincodeEndorsedAction {
return &pb.ChaincodeEndorsedAction{
ProposalResponsePayload: fabricClient.MarshalOrPanic(b.buildProposalResponsePayload()),
Endorsements: []*pb.Endorsement{},
}
}
func (b *MockCCBlockEventBuilder) buildProposalResponsePayload() *pb.ProposalResponsePayload {
return &pb.ProposalResponsePayload{
ProposalHash: []byte("somehash"),
Extension: fabricClient.MarshalOrPanic(b.buildChaincodeAction()),
}
}
func (b *MockCCBlockEventBuilder) buildChaincodeAction() *pb.ChaincodeAction {
return &pb.ChaincodeAction{
Events: fabricClient.MarshalOrPanic(b.buildChaincodeEvent()),
}
}
func (b *MockCCBlockEventBuilder) buildChaincodeEvent() *pb.ChaincodeEvent {
return &pb.ChaincodeEvent{
ChaincodeId: b.CCID,
EventName: b.EventName,
TxId: b.TxID,
Payload: b.Payload,
}
}
func generateTxID() string {
nonce, err := fabricClient.GenerateRandomNonce()
if err != nil {
panic(fmt.Errorf("error generating nonce: %v", err))
}
digest, err := factory.GetDefault().Hash(
nonce,
&bccsp.SHA256Opts{})
if err != nil {
panic(fmt.Errorf("error hashing nonce: %v", err))
}
return hex.EncodeToString(digest)
}