handler_test.go 97.2 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
	"io"
	"time"

	"github.com/golang/protobuf/proto"
14
	"github.com/hyperledger/fabric/common/metrics/metricsfakes"
15
	"github.com/hyperledger/fabric/common/mocks/config"
16
17
18
19
20
21
22
23
24
25
26
27
	"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"
28
29
)

30
31
var _ = Describe("Handler", func() {
	var (
32
33
34
35
36
37
38
39
40
41
		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
42
		fakeInvoker                    *mock.Invoker
43
44
		fakeLedgerGetter               *mock.LedgerGetter
		fakeHandlerRegistry            *fake.Registry
45
		fakeApplicationConfigRetriever *fake.ApplicationConfigRetriever
46
		fakeCollectionStore            *mock.CollectionStore
47
48
49
		fakeShimRequestsReceived       *metricsfakes.Counter
		fakeShimRequestsCompleted      *metricsfakes.Counter
		fakeShimRequestDuration        *metricsfakes.Histogram
50
		fakeExecuteTimeouts            *metricsfakes.Counter
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

		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{}
67
68
		fakeCollectionStore = &mock.CollectionStore{}

69
70
		responseNotifier = make(chan *pb.ChaincodeMessage, 1)
		txContext = &chaincode.TransactionContext{
71
72
73
74
75
76
			ChainID:                 "channel-id",
			TXSimulator:             fakeTxSimulator,
			HistoryQueryExecutor:    fakeHistoryQueryExecutor,
			ResponseNotifier:        responseNotifier,
			CollectionStore:         fakeCollectionStore,
			AllowedCollectionAccess: make(map[string]bool),
77
78
		}

79
80
		fakeACLProvider = &mock.ACLProvider{}
		fakeDefinitionGetter = &mock.ChaincodeDefinitionGetter{}
81
		fakeInvoker = &mock.Invoker{}
82
		fakeLedgerGetter = &mock.LedgerGetter{}
83
		fakeInstantiationPolicyChecker = &mock.InstantiationPolicyChecker{}
84
85
86
87
88
89
90
		fakeQueryResponseBuilder = &fake.QueryResponseBuilder{}
		fakeHandlerRegistry = &fake.Registry{}

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

91
92
93
94
95
96
		fakeApplicationConfigRetriever = &fake.ApplicationConfigRetriever{}
		applicationCapability := &config.MockApplication{
			CapabilitiesRv: &config.MockApplicationCapabilities{KeyLevelEndorsementRv: true},
		}
		fakeApplicationConfigRetriever.GetApplicationConfigReturns(applicationCapability, true)

97
98
99
100
101
102
		fakeShimRequestsReceived = &metricsfakes.Counter{}
		fakeShimRequestsReceived.WithReturns(fakeShimRequestsReceived)
		fakeShimRequestsCompleted = &metricsfakes.Counter{}
		fakeShimRequestsCompleted.WithReturns(fakeShimRequestsCompleted)
		fakeShimRequestDuration = &metricsfakes.Histogram{}
		fakeShimRequestDuration.WithReturns(fakeShimRequestDuration)
103
104
		fakeExecuteTimeouts = &metricsfakes.Counter{}
		fakeExecuteTimeouts.WithReturns(fakeExecuteTimeouts)
105

Will Lahti's avatar
Will Lahti committed
106
		chaincodeMetrics := &chaincode.HandlerMetrics{
107
108
109
			ShimRequestsReceived:  fakeShimRequestsReceived,
			ShimRequestsCompleted: fakeShimRequestsCompleted,
			ShimRequestDuration:   fakeShimRequestDuration,
110
			ExecuteTimeouts:       fakeExecuteTimeouts,
111
112
		}

113
		handler = &chaincode.Handler{
114
115
116
			ACLProvider:                fakeACLProvider,
			ActiveTransactions:         fakeTransactionRegistry,
			DefinitionGetter:           fakeDefinitionGetter,
117
			Invoker:                    fakeInvoker,
118
119
120
121
122
123
124
			LedgerGetter:               fakeLedgerGetter,
			InstantiationPolicyChecker: fakeInstantiationPolicyChecker,
			QueryResponseBuilder:       fakeQueryResponseBuilder,
			Registry:                   fakeHandlerRegistry,
			SystemCCProvider:           fakeSystemCCProvider,
			SystemCCVersion:            "system-cc-version",
			TXContexts:                 fakeContextRegistry,
125
126
127
			UUIDGenerator: chaincode.UUIDGeneratorFunc(func() string {
				return "generated-query-id"
			}),
128
			AppConfig: fakeApplicationConfigRetriever,
129
			Metrics:   chaincodeMetrics,
130
131
		}
		chaincode.SetHandlerChatStream(handler, fakeChatStream)
132
		chaincode.SetHandlerChaincodeID(handler, &pb.ChaincodeID{Name: "test-handler-name", Version: "1.0"})
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
		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))
		})

195
196
197
198
199
		It("deregisters the transaction ID before sending the response", func() {
			fakeTransactionRegistry.RemoveStub = func(channelID, txID string) {
				Consistently(fakeChatStream.SendCallCount).Should(Equal(0))
			}

200
201
202
203
204
205
206
207
			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"))
		})

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
		It("records shim requests received before requests completed", func() {
			fakeShimRequestsReceived.AddStub = func(delta float64) {
				defer GinkgoRecover()
				Expect(fakeShimRequestsCompleted.AddCallCount()).To(Equal(0))
			}

			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
			Eventually(fakeChatStream.SendCallCount).Should(Equal(1))
			msg := fakeChatStream.SendArgsForCall(0)
			Expect(msg).To(Equal(expectedResponse))

			Expect(fakeShimRequestsReceived.WithCallCount()).To(Equal(1))
			labelValues := fakeShimRequestsReceived.WithArgsForCall(0)
			Expect(labelValues).To(Equal([]string{
				"type", "GET_STATE",
				"channel", "channel-id",
				"chaincode", "test-handler-name:1.0",
			}))
			Expect(fakeShimRequestsReceived.AddCallCount()).To(Equal(1))
			Expect(fakeShimRequestsReceived.AddArgsForCall(0)).To(BeNumerically("~", 1.0))
		})

		It("records transactions completed after transactions received", func() {
			fakeShimRequestsCompleted.AddStub = func(delta float64) {
				defer GinkgoRecover()
				Expect(fakeShimRequestsReceived.AddCallCount()).To(Equal(1))
			}

			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
			Eventually(fakeChatStream.SendCallCount).Should(Equal(1))

			Expect(fakeShimRequestsCompleted.WithCallCount()).To(Equal(1))
			labelValues := fakeShimRequestsCompleted.WithArgsForCall(0)
			Expect(labelValues).To(Equal([]string{
				"type", "GET_STATE",
				"channel", "channel-id",
				"chaincode", "test-handler-name:1.0",
				"success", "true",
			}))
			Expect(fakeShimRequestsCompleted.AddCallCount()).To(Equal(1))
			Expect(fakeShimRequestsCompleted.AddArgsForCall(0)).To(BeNumerically("~", 1.0))
		})

		It("records transactions duration", func() {
			handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
			Eventually(fakeChatStream.SendCallCount).Should(Equal(1))

			Expect(fakeShimRequestDuration.WithCallCount()).To(Equal(1))
			labelValues := fakeShimRequestDuration.WithArgsForCall(0)
			Expect(labelValues).To(Equal([]string{
				"type", "GET_STATE",
				"channel", "channel-id",
				"chaincode", "test-handler-name:1.0",
				"success", "true",
			}))
			Expect(fakeShimRequestDuration.ObserveArgsForCall(0)).NotTo(BeZero())
			Expect(fakeShimRequestDuration.ObserveArgsForCall(0)).To(BeNumerically("<", 1.0))
		})

		Context("when the transaction returns an error", func() {
			BeforeEach(func() {
				fakeMessageHandler.HandleReturns(nil, errors.New("I am a total failure"))
			})

			It("records metrics with success=false", func() {
				handler.HandleTransaction(incomingMessage, fakeMessageHandler.Handle)
				Eventually(fakeChatStream.SendCallCount).Should(Equal(1))

				Expect(fakeShimRequestsCompleted.WithCallCount()).To(Equal(1))
				labelValues := fakeShimRequestsCompleted.WithArgsForCall(0)
				Expect(labelValues).To(Equal([]string{
					"type", "GET_STATE",
					"channel", "channel-id",
					"chaincode", "test-handler-name:1.0",
					"success", "false",
				}))
				Expect(fakeShimRequestsCompleted.AddCallCount()).To(Equal(1))
				Expect(fakeShimRequestsCompleted.AddArgsForCall(0)).To(BeNumerically("~", 1.0))

				Expect(fakeShimRequestDuration.WithCallCount()).To(Equal(1))
				labelValues = fakeShimRequestDuration.WithArgsForCall(0)
				Expect(labelValues).To(Equal([]string{
					"type", "GET_STATE",
					"channel", "channel-id",
					"chaincode", "test-handler-name:1.0",
					"success", "false",
				}))
				Expect(fakeShimRequestDuration.ObserveArgsForCall(0)).NotTo(BeZero())
				Expect(fakeShimRequestDuration.ObserveArgsForCall(0)).To(BeNumerically("<", 1.0))
			})
		})

		Context("when the transaction ID has already been registered", func() {
301
302
303
			BeforeEach(func() {
				fakeTransactionRegistry.AddReturns(false)
			})
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
386
387
388
389
			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"),
					},
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
423
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
				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"))
487
						Expect(string(msg.Payload)).To(HavePrefix("INVOKE_CHAINCODE failed: transaction ID: tx-id: unmarshal failed: proto: "))
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
520
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
					})
				})
			})
		})

		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)
550
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
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
			})
		})

		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")))
			})

598
			Context("when SetPrivateData fails due to ledger error", func() {
599
600
601
602
603
604
605
606
607
				BeforeEach(func() {
					fakeTxSimulator.SetPrivateDataReturns(errors.New("godzilla"))
				})

				It("returns an error", func() {
					_, err := handler.HandlePutState(incomingMessage, txContext)
					Expect(err).To(MatchError("godzilla"))
				})
			})
608
609
610
611
612
613
614
615
616
617
618

			Context("when SetPrivateData fails due to Init transaction", func() {
				BeforeEach(func() {
					txContext.IsInitTransaction = true
				})

				It("returns the error from errorIfInitTransaction", func() {
					_, err := handler.HandlePutState(incomingMessage, txContext)
					Expect(err).To(MatchError("private data APIs are not allowed in chaincode Init()"))
				})
			})
619
620
621
		})
	})

622
623
624
625
626
627
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
	Describe("HandlePutStateMetadata", func() {
		var incomingMessage *pb.ChaincodeMessage
		var request *pb.PutStateMetadata

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

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

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

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
		It("acquires application config for the channel", func() {
			_, err := handler.HandlePutStateMetadata(incomingMessage, txContext)
			Expect(err).NotTo(HaveOccurred())

			Expect(fakeApplicationConfigRetriever.GetApplicationConfigCallCount()).To(Equal(1))
			cid := fakeApplicationConfigRetriever.GetApplicationConfigArgsForCall(0)
			Expect(cid).To(Equal("channel-id"))
		})

		Context("when getting the app config metadata fails", func() {
			BeforeEach(func() {
				fakeApplicationConfigRetriever.GetApplicationConfigReturns(nil, false)
			})

			It("returns an error", func() {
				_, err := handler.HandlePutStateMetadata(incomingMessage, txContext)
				Expect(err).To(MatchError("application config does not exist for channel-id"))
			})
		})

		Context("when key level endorsement is not supported", func() {
			BeforeEach(func() {
				applicationCapability := &config.MockApplication{
					CapabilitiesRv: &config.MockApplicationCapabilities{KeyLevelEndorsementRv: false},
				}
				fakeApplicationConfigRetriever.GetApplicationConfigReturns(applicationCapability, true)
			})

			It("returns an error", func() {
				_, err := handler.HandlePutStateMetadata(incomingMessage, txContext)
685
				Expect(err).To(MatchError("key level endorsement is not enabled, channel application capability of V1_3 or later is required"))
686
687
688
			})
		})

689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
		Context("when unmarshaling the request fails", func() {
			BeforeEach(func() {
				incomingMessage.Payload = []byte("this-is-a-bogus-payload")
			})

			It("returns an error", func() {
				_, err := handler.HandlePutStateMetadata(incomingMessage, txContext)
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
			})
		})

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

				Expect(fakeTxSimulator.SetStateMetadataCallCount()).To(Equal(1))
				ccname, key, value := fakeTxSimulator.SetStateMetadataArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(key).To(Equal("put-state-key"))
709
710
711
				Expect(value).To(Equal(map[string][]byte{
					"put-state-metakey": []byte("put-state-metadata-value"),
				}))
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
			})

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

				It("returns an error", func() {
					_, err := handler.HandlePutStateMetadata(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 SetPrivateDataMetadata on the transaction simulator", func() {
				_, err := handler.HandlePutStateMetadata(incomingMessage, txContext)
				Expect(err).NotTo(HaveOccurred())

				Expect(fakeTxSimulator.SetPrivateDataMetadataCallCount()).To(Equal(1))
				ccname, collection, key, value := fakeTxSimulator.SetPrivateDataMetadataArgsForCall(0)
				Expect(ccname).To(Equal("cc-instance-name"))
				Expect(collection).To(Equal("collection-name"))
				Expect(key).To(Equal("put-state-key"))
743
744
745
				Expect(value).To(Equal(map[string][]byte{
					"put-state-metakey": []byte("put-state-metadata-value"),
				}))
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
			})

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

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

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
	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)
797
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
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
836
837
838
839
840
841
842
			})
		})

		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"))
			})

843
			Context("when DeletePrivateData fails due to ledger error", func() {
844
845
846
847
848
849
850
851
852
				BeforeEach(func() {
					fakeTxSimulator.DeletePrivateDataReturns(errors.New("mango"))
				})

				It("returns an error", func() {
					_, err := handler.HandleDelState(incomingMessage, txContext)
					Expect(err).To(MatchError("mango"))
				})
			})
853
854
855
856
857
858
859
860
861
862
863

			Context("when DeletePrivateData fails due to Init transaction", func() {
				BeforeEach(func() {
					txContext.IsInitTransaction = true
				})

				It("returns the error from errorIfInitTransaction", func() {
					_, err := handler.HandleDelState(incomingMessage, txContext)
					Expect(err).To(MatchError("private data APIs are not allowed in chaincode Init()"))
				})
			})
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
		})
	})

	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)
902
				Expect(err).To(MatchError("unmarshal failed: proto: can't skip unknown wire type 4"))
903
904
905
906
907
908
909
910
911
912
			})
		})

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

913
				fakeCollectionStore.HasReadAccessReturns(true, nil)
914
915
916
				fakeTxSimulator.GetPrivateDataReturns([]byte("get-private-data-response"), nil)
				expectedResponse.Payload = []byte("get-private-data-response")
			})
917

918
919
920
921
922
923
924
925
926
927
928
			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"))
			})

929
			Context("and GetPrivateData fails due to ledger error", func() {
930
931
932
933
934
935
936
937
938
939
				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"))
				})
			})

940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
			Context("and GetPrivateData fails due to no read access", func() {
				BeforeEach(func() {
					fakeCollectionStore.HasReadAccessReturns(false, nil)
				})

				It("returns the error from errorIfCreatorHasNoReadAccess", func() {
					_, err := handler.HandleGetState(incomingMessage, txContext)
					Expect(err).To(MatchError("tx creator does not have read access" +
						" permission on privatedata in chaincodeName:cc-instance-name" +
						" collectionName: collection-name"))
				})
			})

			Context("and GetPrivateData fails due to error in checking the read access", func() {
				BeforeEach(func() {
					fakeCollectionStore.HasReadAccessReturns(false, errors.New("no collection config"))
				})

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

964
965
966
967
968
969
970
971
972
973
974
			Context("and GetPrivateData fails due to Init transaction", func() {
				BeforeEach(func() {
					txContext.IsInitTransaction = true
				})

				It("returns the error from errorIfInitTransaction", func() {
					_, err := handler.HandleGetState(incomingMessage, txContext)
					Expect(err).To(MatchError("private data APIs are not allowed in chaincode Init()"))
				})
			})

975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
			Context("and GetPrivateData returns the response message", func() {
				BeforeEach(func() {
					txContext.AllowedCollectionAccess["collection-name"] = true
					fakeCollectionStore.HasReadAccessReturns(false, nil) // to
					// ensure that the access cache is used
				})

				It("returns the 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",
					}))
				})
			})

994
995
996
997
998
999
1000
			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",
For faster browsing, not all history is shown. View entire blame