handler_test.go 72.8 KB
Newer Older
1
2
3
4
5
6
/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

7
package chaincode_test
8
9

import (
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
	"io"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric/common/util"
	"github.com/hyperledger/fabric/core/aclmgmt/resources"
	"github.com/hyperledger/fabric/core/chaincode"
	"github.com/hyperledger/fabric/core/chaincode/fake"
	"github.com/hyperledger/fabric/core/chaincode/mock"
	"github.com/hyperledger/fabric/core/common/ccprovider"
	"github.com/hyperledger/fabric/core/common/sysccprovider"
	pb "github.com/hyperledger/fabric/protos/peer"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
	"github.com/pkg/errors"
	"golang.org/x/net/context"
27
28
)

29
30
var _ = Describe("Handler", func() {
	var (
31
32
33
34
35
36
37
38
39
40
		fakeTransactionRegistry        *mock.TransactionRegistry
		fakeContextRegistry            *fake.ContextRegistry
		fakeChatStream                 *mock.ChaincodeStream
		fakeSystemCCProvider           *mock.SystemCCProvider
		fakeTxSimulator                *mock.TxSimulator
		fakeHistoryQueryExecutor       *mock.HistoryQueryExecutor
		fakeQueryResponseBuilder       *fake.QueryResponseBuilder
		fakeACLProvider                *mock.ACLProvider
		fakeDefinitionGetter           *mock.ChaincodeDefinitionGetter
		fakeInstantiationPolicyChecker *mock.InstantiationPolicyChecker
41
		fakeInvoker                    *mock.Invoker
42
43
		fakeLedgerGetter               *mock.LedgerGetter
		fakeHandlerRegistry            *fake.Registry
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

		responseNotifier chan *pb.ChaincodeMessage
		txContext        *chaincode.TransactionContext

		handler *chaincode.Handler
	)

	BeforeEach(func() {
		fakeTransactionRegistry = &mock.TransactionRegistry{}
		fakeTransactionRegistry.AddReturns(true)

		fakeChatStream = &mock.ChaincodeStream{}
		fakeSystemCCProvider = &mock.SystemCCProvider{}

		fakeTxSimulator = &mock.TxSimulator{}
		fakeHistoryQueryExecutor = &mock.HistoryQueryExecutor{}
		responseNotifier = make(chan *pb.ChaincodeMessage, 1)
		txContext = &chaincode.TransactionContext{
			ChainID:              "channel-id",
			TXSimulator:          fakeTxSimulator,
			HistoryQueryExecutor: fakeHistoryQueryExecutor,
			ResponseNotifier:     responseNotifier,
66
67
		}

68
69
		fakeACLProvider = &mock.ACLProvider{}
		fakeDefinitionGetter = &mock.ChaincodeDefinitionGetter{}
70
		fakeInvoker = &mock.Invoker{}
71
		fakeLedgerGetter = &mock.LedgerGetter{}
72
		fakeInstantiationPolicyChecker = &mock.InstantiationPolicyChecker{}
73
74
75
76
77
78
79
80
		fakeQueryResponseBuilder = &fake.QueryResponseBuilder{}
		fakeHandlerRegistry = &fake.Registry{}

		fakeContextRegistry = &fake.ContextRegistry{}
		fakeContextRegistry.GetReturns(txContext)
		fakeContextRegistry.CreateReturns(txContext, nil)

		handler = &chaincode.Handler{
81
82
83
			ACLProvider:                fakeACLProvider,
			ActiveTransactions:         fakeTransactionRegistry,
			DefinitionGetter:           fakeDefinitionGetter,
84
			Invoker:                    fakeInvoker,
85
86
87
88
89
90
91
			LedgerGetter:               fakeLedgerGetter,
			InstantiationPolicyChecker: fakeInstantiationPolicyChecker,
			QueryResponseBuilder:       fakeQueryResponseBuilder,
			Registry:                   fakeHandlerRegistry,
			SystemCCProvider:           fakeSystemCCProvider,
			SystemCCVersion:            "system-cc-version",
			TXContexts:                 fakeContextRegistry,
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
			UUIDGenerator: chaincode.UUIDGeneratorFunc(func() string {
				return "generated-query-id"
			}),
		}
		chaincode.SetHandlerChatStream(handler, fakeChatStream)
		chaincode.SetHandlerChaincodeID(handler, &pb.ChaincodeID{Name: "test-handler-name"})
		chaincode.SetHandlerCCInstance(handler, &sysccprovider.ChaincodeInstance{ChaincodeName: "cc-instance-name"})
	})

	Describe("HandleTransaction", func() {
		var (
			incomingMessage    *pb.ChaincodeMessage
			fakeMessageHandler *fake.MessageHandler
			expectedResponse   *pb.ChaincodeMessage
		)

		BeforeEach(func() {
			incomingMessage = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_GET_STATE,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}

			expectedResponse = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_UNDEFINED,
				Payload:   []byte("handler-response-payload"),
				Txid:      "response-tx-id",
				ChannelId: "response-channel-id",
			}
			fakeMessageHandler = &fake.MessageHandler{}
			fakeMessageHandler.HandleReturns(expectedResponse, nil)
		})

		It("registers the transaction ID from the message", func() {
			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

			Expect(fakeTransactionRegistry.AddCallCount()).To(Equal(1))
			channelID, transactionID := fakeTransactionRegistry.AddArgsForCall(0)
			Expect(channelID).To(Equal("channel-id"))
			Expect(transactionID).To(Equal("tx-id"))
		})

		It("ensures there is a valid transaction simulator available in the context", func() {
			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

			Expect(fakeContextRegistry.GetCallCount()).To(Equal(1))
			channelID, txID := fakeContextRegistry.GetArgsForCall(0)
			Expect(channelID).To(Equal("channel-id"))
			Expect(txID).To(Equal("tx-id"))
		})

		It("calls the delegate with the correct arguments", func() {
			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

			Expect(fakeMessageHandler.HandleCallCount()).To(Equal(1))
			msg, ctx := fakeMessageHandler.HandleArgsForCall(0)
			Expect(msg).To(Equal(incomingMessage))
			Expect(ctx).To(Equal(txContext))
		})

		It("sends the response message returned by the delegate", func() {
			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

			Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
			msg := fakeChatStream.SendArgsForCall(0)
			Expect(msg).To(Equal(expectedResponse))
		})

160
161
162
163
164
		It("deregisters the transaction ID before sending the response", func() {
			fakeTransactionRegistry.RemoveStub = func(channelID, txID string) {
				Consistently(fakeChatStream.SendCallCount).Should(Equal(0))
			}

165
166
167
168
169
170
171
172
173
174
175
176
			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

			Expect(fakeTransactionRegistry.RemoveCallCount()).To(Equal(1))
			channelID, transactionID := fakeTransactionRegistry.RemoveArgsForCall(0)
			Expect(channelID).To(Equal("channel-id"))
			Expect(transactionID).To(Equal("tx-id"))
		})

		Context("wwhen the transaction ID has already been regustered", func() {
			BeforeEach(func() {
				fakeTransactionRegistry.AddReturns(false)
			})
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
			It("returns without sending a response", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
				Consistently(fakeChatStream.SendCallCount).Should(Equal(0))
			})

			It("does not call the delegate", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
				Expect(fakeMessageHandler.HandleCallCount()).To(Equal(0))
			})

			It("does not attempt to deregister the transaction ID", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
				Expect(fakeTransactionRegistry.RemoveCallCount()).To(Equal(0))
			})
		})

		Context("when the transaction context does not exist", func() {
			BeforeEach(func() {
				fakeContextRegistry.GetReturns(nil)
			})

			It("sends an error message", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

				Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
				msg := fakeChatStream.SendArgsForCall(0)
				Expect(msg).To(Equal(&pb.ChaincodeMessage{
					Type:      pb.ChaincodeMessage_ERROR,
					Payload:   []byte("GET_STATE failed: transaction ID: tx-id: no ledger context"),
					Txid:      "tx-id",
					ChannelId: "channel-id",
				}))
			})

			It("deregisters the message transaction ID", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

				Expect(fakeTransactionRegistry.RemoveCallCount()).To(Equal(1))
				channelID, transactionID := fakeTransactionRegistry.RemoveArgsForCall(0)
				Expect(channelID).To(Equal("channel-id"))
				Expect(transactionID).To(Equal("tx-id"))
			})
		})

		Context("when the transaction context is missing a transaction simulator", func() {
			BeforeEach(func() {
				txContext.TXSimulator = nil
			})

			It("sends an error response", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

				Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
				msg := fakeChatStream.SendArgsForCall(0)
				Expect(msg).To(Equal(&pb.ChaincodeMessage{
					Type:      pb.ChaincodeMessage_ERROR,
					Payload:   []byte("GET_STATE failed: transaction ID: tx-id: no ledger context"),
					Txid:      "tx-id",
					ChannelId: "channel-id",
				}))
			})

			It("deregisters the message transaction ID", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

				Expect(fakeTransactionRegistry.RemoveCallCount()).To(Equal(1))
				channelID, transactionID := fakeTransactionRegistry.RemoveArgsForCall(0)
				Expect(channelID).To(Equal("channel-id"))
				Expect(transactionID).To(Equal("tx-id"))
			})
		})

		Context("when the incoming message is INVOKE_CHAINCODE", func() {
			var chaincodeSpec *pb.ChaincodeSpec

			BeforeEach(func() {
				chaincodeSpec = &pb.ChaincodeSpec{
					Type: pb.ChaincodeSpec_GOLANG,
					ChaincodeId: &pb.ChaincodeID{
						Name:    "target-chaincode-name",
						Version: "target-chaincode-version",
					},
					Input: &pb.ChaincodeInput{
						Args: util.ToChaincodeArgs("command", "arg"),
					},
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
				payloadBytes, err := proto.Marshal(chaincodeSpec)
				Expect(err).NotTo(HaveOccurred())

				incomingMessage.Type = pb.ChaincodeMessage_INVOKE_CHAINCODE
				incomingMessage.Payload = payloadBytes
			})

			It("validates the transaction context", func() {
				txContext.TXSimulator = nil
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

				Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
				msg := fakeChatStream.SendArgsForCall(0)
				Expect(msg).To(Equal(&pb.ChaincodeMessage{
					Type:      pb.ChaincodeMessage_ERROR,
					Payload:   []byte("INVOKE_CHAINCODE failed: transaction ID: tx-id: could not get valid transaction"),
					Txid:      "tx-id",
					ChannelId: "channel-id",
				}))
			})

			Context("and the channel ID is not set", func() {
				BeforeEach(func() {
					incomingMessage.ChannelId = ""
				})

				It("checks if the target is system chaincode", func() {
					handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

					Expect(fakeSystemCCProvider.IsSysCCCallCount()).To(Equal(1))
					name := fakeSystemCCProvider.IsSysCCArgsForCall(0)
					Expect(name).To(Equal("target-chaincode-name"))
				})

				Context("when the target chaincode is not system chaincode", func() {
					BeforeEach(func() {
						fakeSystemCCProvider.IsSysCCReturns(false)
					})

					It("validates the transaction context", func() {
						txContext.TXSimulator = nil
						handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

						Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
						msg := fakeChatStream.SendArgsForCall(0)
						Expect(msg).To(Equal(&pb.ChaincodeMessage{
							Type:    pb.ChaincodeMessage_ERROR,
							Payload: []byte("INVOKE_CHAINCODE failed: transaction ID: tx-id: could not get valid transaction"),
							Txid:    "tx-id",
						}))
					})

					Context("when the target is system chaincode", func() {
						BeforeEach(func() {
							fakeSystemCCProvider.IsSysCCReturns(true)
						})

						It("gets the transaction context without validation", func() {
							txContext.TXSimulator = nil
							handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

							Expect(fakeContextRegistry.GetCallCount()).To(Equal(1))
							Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
							msg := fakeChatStream.SendArgsForCall(0)
							Expect(msg).To(Equal(expectedResponse))
						})

						Context("and the transaction context is missing", func() {
							It("returns an error", func() {
								fakeContextRegistry.GetReturns(nil)
								handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

								Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
								msg := fakeChatStream.SendArgsForCall(0)
								Expect(msg).To(Equal(&pb.ChaincodeMessage{
									Type:    pb.ChaincodeMessage_ERROR,
									Payload: []byte("INVOKE_CHAINCODE failed: transaction ID: tx-id: failed to get transaction context"),
									Txid:    "tx-id",
								}))
							})
						})
					})
				})

				Context("when the payload fails to unmarshal into a chaincode spec", func() {
					BeforeEach(func() {
						incomingMessage.Payload = []byte("this-is-a-bogus-payload")
					})

					It("sends an error response", func() {
						handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

						Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
						msg := fakeChatStream.SendArgsForCall(0)
						Expect(msg.Type).To(Equal(pb.ChaincodeMessage_ERROR))
						Expect(msg.Txid).To(Equal("tx-id"))
360
						Expect(string(msg.Payload)).To(HavePrefix("INVOKE_CHAINCODE failed: transaction ID: tx-id: unmarshal failed: proto: "))
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
					})
				})
			})
		})

		Context("when the delegate returns an error", func() {
			BeforeEach(func() {
				fakeMessageHandler.HandleReturns(nil, errors.New("watermelon-swirl"))
			})

			It("sends an error response", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)

				Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
				msg := fakeChatStream.SendArgsForCall(0)
				Expect(msg).To(Equal(&pb.ChaincodeMessage{
					Type:      pb.ChaincodeMessage_ERROR,
					Payload:   []byte("GET_STATE failed: transaction ID: tx-id: watermelon-swirl"),
					Txid:      "tx-id",
					ChannelId: "channel-id",
				}))
			})
		})
	})

	Describe("HandlePutState", func() {
		var incomingMessage *pb.ChaincodeMessage
		var request *pb.PutState

		BeforeEach(func() {
			request = &pb.PutState{
				Key:   "put-state-key",
				Value: []byte("put-state-value"),
			}
			payload, err := proto.Marshal(request)
			Expect(err).NotTo(HaveOccurred())

			incomingMessage = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_PUT_STATE,
				Payload:   payload,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}
		})

		It("returns a response message", func() {
			resp, err := handler.HandlePutState(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())
			Expect(resp).To(Equal(&pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_RESPONSE,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}))
		})

		Context("when unmarshaling the request fails", func() {
			BeforeEach(func() {
				incomingMessage.Payload = []byte("this-is-a-bogus-payload")
			})

			It("returns an error", func() {
				_, err := handler.HandlePutState(incomingMessage, txContext)
423
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
			})
		})

		Context("when the collection is not provided", func() {
			It("calls SetState on the transaction simulator", func() {
				_, err := handler.HandlePutState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.SetStateCallCount()).To(Equal(1))
				ccname, key, value := fakeTxSimulator.SetStateArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(key).To(Equal("put-state-key"))
				Expect(value).To(Equal([]byte("put-state-value")))
			})

			Context("when SeteState fails", func() {
				BeforeEach(func() {
					fakeTxSimulator.SetStateReturns(errors.New("king-kong"))
				})

				It("returns an error", func() {
					_, err := handler.HandlePutState(incomingMessage, txContext)
					Expect(err).To(MatchError("king-kong"))
				})
			})
		})

		Context("when the collection is provided", func() {
			BeforeEach(func() {
				request.Collection = "collection-name"
				payload, err := proto.Marshal(request)
				Expect(err).NotTo(HaveOccurred())
				incomingMessage.Payload = payload
			})

			It("calls SetPrivateData on the transaction simulator", func() {
				_, err := handler.HandlePutState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.SetPrivateDataCallCount()).To(Equal(1))
				ccname, collection, key, value := fakeTxSimulator.SetPrivateDataArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(collection).To(Equal("collection-name"))
				Expect(key).To(Equal("put-state-key"))
				Expect(value).To(Equal([]byte("put-state-value")))
			})

			Context("when SetPrivateData fails", func() {
				BeforeEach(func() {
					fakeTxSimulator.SetPrivateDataReturns(errors.New("godzilla"))
				})

				It("returns an error", func() {
					_, err := handler.HandlePutState(incomingMessage, txContext)
					Expect(err).To(MatchError("godzilla"))
				})
			})
		})
	})

	Describe("HandleDelState", func() {
		var incomingMessage *pb.ChaincodeMessage
		var request *pb.DelState

		BeforeEach(func() {
			request = &pb.DelState{
				Key: "del-state-key",
			}
			payload, err := proto.Marshal(request)
			Expect(err).NotTo(HaveOccurred())

			incomingMessage = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_DEL_STATE,
				Payload:   payload,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}
		})

		It("returns a response message", func() {
			resp, err := handler.HandleDelState(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())
			Expect(resp).To(Equal(&pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_RESPONSE,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}))
		})

		Context("when unmarshalling the request fails", func() {
			BeforeEach(func() {
				incomingMessage.Payload = []byte("this-is-a-bogus-payload")
			})

			It("returns an error", func() {
				_, err := handler.HandleDelState(incomingMessage, txContext)
520
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
			})
		})

		Context("when collection is not set", func() {
			It("calls DeleteState on the transaction simulator", func() {
				_, err := handler.HandleDelState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.DeleteStateCallCount()).To(Equal(1))
				ccname, key := fakeTxSimulator.DeleteStateArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(key).To(Equal("del-state-key"))
			})

			Context("when DeleteState returns an error", func() {
				BeforeEach(func() {
					fakeTxSimulator.DeleteStateReturns(errors.New("orange"))
				})

				It("return an error", func() {
					_, err := handler.HandleDelState(incomingMessage, txContext)
					Expect(err).To(MatchError("orange"))
				})
			})
		})

		Context("when collection is set", func() {
			BeforeEach(func() {
				request.Collection = "collection-name"
				payload, err := proto.Marshal(request)
				Expect(err).NotTo(HaveOccurred())
				incomingMessage.Payload = payload
			})

			It("calls DeletePrivateData on the transaction simulator", func() {
				_, err := handler.HandleDelState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.DeletePrivateDataCallCount()).To(Equal(1))
				ccname, collection, key := fakeTxSimulator.DeletePrivateDataArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(collection).To(Equal("collection-name"))
				Expect(key).To(Equal("del-state-key"))
			})

			Context("when DeletePrivateData returns an error", func() {
				BeforeEach(func() {
					fakeTxSimulator.DeletePrivateDataReturns(errors.New("mango"))
				})

				It("returns an error", func() {
					_, err := handler.HandleDelState(incomingMessage, txContext)
					Expect(err).To(MatchError("mango"))
				})
			})
		})
	})

	Describe("HandleGetState", func() {
		var (
			incomingMessage  *pb.ChaincodeMessage
			request          *pb.GetState
			expectedResponse *pb.ChaincodeMessage
		)

		BeforeEach(func() {
			request = &pb.GetState{
				Key: "get-state-key",
			}
			payload, err := proto.Marshal(request)
			Expect(err).NotTo(HaveOccurred())

			incomingMessage = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_GET_STATE,
				Payload:   payload,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}

			expectedResponse = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_RESPONSE,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}
		})

		Context("when unmarshalling the request fails", func() {
			BeforeEach(func() {
				incomingMessage.Payload = []byte("this-is-a-bogus-payload")
			})

			It("returns an error", func() {
				_, err := handler.HandleGetState(incomingMessage, txContext)
614
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
615
616
617
618
619
620
621
622
623
624
625
626
627
			})
		})

		Context("when collection is set", func() {
			BeforeEach(func() {
				request.Collection = "collection-name"
				payload, err := proto.Marshal(request)
				Expect(err).NotTo(HaveOccurred())
				incomingMessage.Payload = payload

				fakeTxSimulator.GetPrivateDataReturns([]byte("get-private-data-response"), nil)
				expectedResponse.Payload = []byte("get-private-data-response")
			})
628

629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
			It("calls GetPrivateData on the transaction simulator", func() {
				_, err := handler.HandleGetState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.GetPrivateDataCallCount()).To(Equal(1))
				ccname, collection, key := fakeTxSimulator.GetPrivateDataArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(collection).To(Equal("collection-name"))
				Expect(key).To(Equal("get-state-key"))
			})

			Context("and GetPrivateData fails", func() {
				BeforeEach(func() {
					fakeTxSimulator.GetPrivateDataReturns(nil, errors.New("french fries"))
				})

				It("returns the error from GetPrivateData", func() {
					_, err := handler.HandleGetState(incomingMessage, txContext)
					Expect(err).To(MatchError("french fries"))
				})
			})

			It("returns the response message from GetPrivateData", func() {
				resp, err := handler.HandleGetState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())
				Expect(resp).To(Equal(&pb.ChaincodeMessage{
					Type:      pb.ChaincodeMessage_RESPONSE,
					Payload:   []byte("get-private-data-response"),
					Txid:      "tx-id",
					ChannelId: "channel-id",
				}))
			})
		})

		Context("when collection is not set", func() {
			BeforeEach(func() {
				fakeTxSimulator.GetStateReturns([]byte("get-state-response"), nil)
				expectedResponse.Payload = []byte("get-state-response")
			})

			It("calls GetState on the transaction simulator", func() {
				_, err := handler.HandleGetState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.GetStateCallCount()).To(Equal(1))
				ccname, key := fakeTxSimulator.GetStateArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(key).To(Equal("get-state-key"))
			})

			Context("and GetState fails", func() {
				BeforeEach(func() {
					fakeTxSimulator.GetStateReturns(nil, errors.New("tomato"))
				})

				It("returns the error from GetState", func() {
					_, err := handler.HandleGetState(incomingMessage, txContext)
					Expect(err).To(MatchError("tomato"))
				})
			})

			It("returns the response from GetState", func() {
				resp, err := handler.HandleGetState(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())
				Expect(resp).To(Equal(&pb.ChaincodeMessage{
					Type:      pb.ChaincodeMessage_RESPONSE,
					Payload:   []byte("get-state-response"),
					Txid:      "tx-id",
					ChannelId: "channel-id",
				}))
			})
		})
	})

	Describe("HandleGetStateByRange", func() {
		var (
			incomingMessage       *pb.ChaincodeMessage
			request               *pb.GetStateByRange
			expectedResponse      *pb.ChaincodeMessage
			fakeIterator          *mock.ResultsIterator
			expectedQueryResponse *pb.QueryResponse
			expectedPayload       []byte
		)

		BeforeEach(func() {
			request = &pb.GetStateByRange{
				StartKey: "get-state-start-key",
				EndKey:   "get-state-end-key",
			}
			payload, err := proto.Marshal(request)
			Expect(err).NotTo(HaveOccurred())

			incomingMessage = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_GET_STATE,
				Payload:   payload,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}

			fakeIterator = &mock.ResultsIterator{}
			fakeTxSimulator.GetStateRangeScanIteratorReturns(fakeIterator, nil)

			expectedQueryResponse = &pb.QueryResponse{
				Results: nil,
				HasMore: true,
				Id:      "query-response-id",
			}
			fakeQueryResponseBuilder.BuildQueryResponseReturns(expectedQueryResponse, nil)

			expectedPayload, err = proto.Marshal(expectedQueryResponse)
			Expect(err).NotTo(HaveOccurred())

			expectedResponse = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_RESPONSE,
				Txid:      "tx-id",
				Payload:   expectedPayload,
				ChannelId: "channel-id",
			}
		})

		It("initializes a query context", func() {
			_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())

			pqr := txContext.GetPendingQueryResult("generated-query-id")
			Expect(pqr).To(Equal(&chaincode.PendingQueryResult{}))
			iter := txContext.GetQueryIterator("generated-query-id")
			Expect(iter).To(Equal(fakeIterator))
		})

		It("returns the response message", func() {
			resp, err := handler.HandleGetStateByRange(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())
			Expect(resp).To(Equal(expectedResponse))
		})

		Context("when collection is not set", func() {
			It("calls GetStateRangeScanIterator on the transaction simulator", func() {
				_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.GetStateRangeScanIteratorCallCount()).To(Equal(1))
				ccname, startKey, endKey := fakeTxSimulator.GetStateRangeScanIteratorArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(startKey).To(Equal("get-state-start-key"))
				Expect(endKey).To(Equal("get-state-end-key"))
			})

			Context("and GetStateRangeScanIterator fails", func() {
				BeforeEach(func() {
					fakeTxSimulator.GetStateRangeScanIteratorReturns(nil, errors.New("tomato"))
				})

				It("returns the error from GetStateRangeScanIterator", func() {
					_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
					Expect(err).To(MatchError("tomato"))
				})
			})

			It("returns the response from GetStateRangeScanIterator", func() {
				resp, err := handler.HandleGetStateByRange(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())
				Expect(resp).To(Equal(expectedResponse))
			})
		})

		Context("when collection is set", func() {
			BeforeEach(func() {
				request.Collection = "collection-name"
				payload, err := proto.Marshal(request)
				Expect(err).NotTo(HaveOccurred())
				incomingMessage.Payload = payload

				fakeTxSimulator.GetPrivateDataRangeScanIteratorReturns(fakeIterator, nil)
			})

			It("calls GetPrivateDataRangeScanIterator on the transaction simulator", func() {
				_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.GetPrivateDataRangeScanIteratorCallCount()).To(Equal(1))
				ccname, collection, startKey, endKey := fakeTxSimulator.GetPrivateDataRangeScanIteratorArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(collection).To(Equal("collection-name"))
				Expect(startKey).To(Equal("get-state-start-key"))
				Expect(endKey).To(Equal("get-state-end-key"))
			})

			Context("and GetPrivateDataRangeScanIterator fails", func() {
				BeforeEach(func() {
					fakeTxSimulator.GetPrivateDataRangeScanIteratorReturns(nil, errors.New("french fries"))
				})

				It("returns the error from GetPrivateDataRangeScanIterator", func() {
					_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
					Expect(err).To(MatchError("french fries"))
				})
			})
		})

		Context("when unmarshalling the request fails", func() {
			BeforeEach(func() {
				incomingMessage.Payload = []byte("this-is-a-bogus-payload")
			})

			It("returns an error", func() {
				_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
836
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
			})
		})

		Context("when building the query response fails", func() {
			BeforeEach(func() {
				fakeQueryResponseBuilder.BuildQueryResponseReturns(nil, errors.New("garbanzo"))
			})

			It("returns the error", func() {
				_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
				Expect(err).To(MatchError("garbanzo"))
			})

			It("cleans up the query context", func() {
				handler.HandleGetStateByRange(incomingMessage, txContext)

				pqr := txContext.GetPendingQueryResult("generated-query-id")
				Expect(pqr).To(BeNil())
				iter := txContext.GetQueryIterator("generated-query-id")
				Expect(iter).To(BeNil())
			})
		})

		Context("when marshling the response fails", func() {
			BeforeEach(func() {
				fakeQueryResponseBuilder.BuildQueryResponseReturns(nil, nil)
			})

			It("returns the error", func() {
				_, err := handler.HandleGetStateByRange(incomingMessage, txContext)
				Expect(err).To(MatchError("marshal failed: proto: Marshal called with nil"))
			})

			It("cleans up the query context", func() {
				handler.HandleGetStateByRange(incomingMessage, txContext)

				pqr := txContext.GetPendingQueryResult("generated-query-id")
				Expect(pqr).To(BeNil())
				iter := txContext.GetQueryIterator("generated-query-id")
				Expect(iter).To(BeNil())
			})
		})
	})

	Describe("HandleQueryStateNext", func() {
		var (
			fakeIterator          *mock.ResultsIterator
			expectedQueryResponse *pb.QueryResponse
			request               *pb.QueryStateNext
			incomingMessage       *pb.ChaincodeMessage
		)

		BeforeEach(func() {
			request = &pb.QueryStateNext{
				Id: "query-state-next-id",
			}
			payload, err := proto.Marshal(request)
			Expect(err).NotTo(HaveOccurred())

			fakeIterator = &mock.ResultsIterator{}
			txContext.InitializeQueryContext("query-state-next-id", fakeIterator)

			incomingMessage = &pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_GET_STATE,
				Payload:   payload,
				Txid:      "tx-id",
				ChannelId: "channel-id",
			}
			expectedQueryResponse = &pb.QueryResponse{
				Results: nil,
				HasMore: true,
				Id:      "query-response-id",
			}
			fakeQueryResponseBuilder.BuildQueryResponseReturns(expectedQueryResponse, nil)
		})

		It("builds a query response", func() {
			_, err := handler.HandleQueryStateNext(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())

			Expect(fakeQueryResponseBuilder.BuildQueryResponseCallCount()).To(Equal(1))
			tctx, iter, id := fakeQueryResponseBuilder.BuildQueryResponseArgsForCall(0)
			Expect(tctx).To(Equal(txContext))
			Expect(iter).To(Equal(fakeIterator))
			Expect(id).To(Equal("query-state-next-id"))
		})

		It("returns a chaincode message with the query response", func() {
			resp, err := handler.HandleQueryStateNext(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())

			expectedPayload, err := proto.Marshal(expectedQueryResponse)
			Expect(err).NotTo(HaveOccurred())

			Expect(resp).To(Equal(&pb.ChaincodeMessage{
				Type:      pb.ChaincodeMessage_RESPONSE,
				Payload:   expectedPayload,
				ChannelId: "channel-id",
				Txid:      "tx-id",
			}))
		})

		Context("when unmarshalling the request fails", func() {
			BeforeEach(func() {
				incomingMessage.Payload = []byte("this-is-a-bogus-payload")
			})

			It("returns an error", func() {
				_, err := handler.HandleQueryStateNext(incomingMessage, txContext)
946
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
			})
		})

		Context("when the query iterator is missing", func() {
			BeforeEach(func() {
				txContext.CleanupQueryContext("query-state-next-id")
			})

			It("returns an error", func() {
				_, err := handler.HandleQueryStateNext(incomingMessage, txContext)
				Expect(err).To(MatchError("query iterator not found"))
			})
		})

		Context("when building the query response fails", func() {
			BeforeEach(func() {
				fakeQueryResponseBuilder.BuildQueryResponseReturns(nil, errors.New("potato"))
			})

			It("returns an error", func() {
				_, err := handler.HandleQueryStateNext(incomingMessage, txContext)
				Expect(err).To(MatchError("potato"))
			})

			It("cleans up the query context", func() {
				handler.HandleQueryStateNext(incomingMessage, txContext)

				pqr := txContext.GetPendingQueryResult("generated-query-id")
				Expect(pqr).To(BeNil())
				iter := txContext.GetQueryIterator("generated-query-id")
				Expect(iter).To(BeNil())
			})
		})

		Context("when marshaling the query response fails", func() {
			BeforeEach(func() {
				fakeQueryResponseBuilder.BuildQueryResponseReturns(nil, nil)
			})

			It("returns an error", func() {
				_, err := handler.HandleQueryStateNext(incomingMessage, txContext)
				Expect(err).To(MatchError("marshal failed: proto: Marshal called with nil"))
			})

			It("cleans up the query context", func() {
				handler.HandleQueryStateNext(incomingMessage, txContext)

				pqr := txContext.GetPendingQueryResult("generated-query-id")
				Expect(pqr).To(BeNil())
				iter := txContext.GetQueryIterator("generated-query-id")
				Expect(iter).To(BeNil())
			})
		})
	})
For faster browsing, not all history is shown. View entire blame