forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 6
/
handler.go
1317 lines (1116 loc) · 44.8 KB
/
handler.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
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
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
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
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
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
614
615
616
617
618
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
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
836
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
946
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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package chaincode
import (
"fmt"
"io"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/common/channelconfig"
"github.com/hyperledger/fabric/common/flogging"
commonledger "github.com/hyperledger/fabric/common/ledger"
"github.com/hyperledger/fabric/core/aclmgmt/resources"
"github.com/hyperledger/fabric/core/common/ccprovider"
"github.com/hyperledger/fabric/core/common/privdata"
"github.com/hyperledger/fabric/core/common/sysccprovider"
"github.com/hyperledger/fabric/core/container/ccintf"
"github.com/hyperledger/fabric/core/ledger"
"github.com/hyperledger/fabric/core/ledger/ledgerconfig"
"github.com/hyperledger/fabric/core/peer"
"github.com/hyperledger/fabric/protos/common"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/pkg/errors"
)
var chaincodeLogger = flogging.MustGetLogger("chaincode")
// An ACLProvider performs access control checks when invoking
// chaincode.
type ACLProvider interface {
CheckACL(resName string, channelID string, idinfo interface{}) error
}
// A Registry is responsible for tracking handlers.
type Registry interface {
Register(*Handler) error
Ready(cname string)
Failed(cname string, err error)
Deregister(cname string) error
}
// An Invoker invokes chaincode.
type Invoker interface {
Invoke(txParams *ccprovider.TransactionParams, cccid *ccprovider.CCContext, spec *pb.ChaincodeInput) (*pb.ChaincodeMessage, error)
}
// SystemCCProvider provides system chaincode metadata.
type SystemCCProvider interface {
IsSysCC(name string) bool
IsSysCCAndNotInvokableCC2CC(name string) bool
}
// TransactionRegistry tracks active transactions for each channel.
type TransactionRegistry interface {
Add(channelID, txID string) bool
Remove(channelID, txID string)
}
// A ContextRegistry is responsible for managing transaction contexts.
type ContextRegistry interface {
Create(txParams *ccprovider.TransactionParams) (*TransactionContext, error)
Get(chainID, txID string) *TransactionContext
Delete(chainID, txID string)
Close()
}
// InstantiationPolicyChecker is used to evaluate instantiation policies.
type InstantiationPolicyChecker interface {
CheckInstantiationPolicy(name, version string, cd *ccprovider.ChaincodeData) error
}
// Adapter from function to InstantiationPolicyChecker interface.
type CheckInstantiationPolicyFunc func(name, version string, cd *ccprovider.ChaincodeData) error
func (c CheckInstantiationPolicyFunc) CheckInstantiationPolicy(name, version string, cd *ccprovider.ChaincodeData) error {
return c(name, version, cd)
}
// QueryResponseBuilder is responsible for building QueryResponse messages for query
// transactions initiated by chaincode.
type QueryResponseBuilder interface {
BuildQueryResponse(txContext *TransactionContext, iter commonledger.ResultsIterator,
iterID string, isPaginated bool, totalReturnLimit int32) (*pb.QueryResponse, error)
}
// ChaincodeDefinitionGetter is responsible for retrieving a chaincode definition
// from the system. The definition is used by the InstantiationPolicyChecker.
type ChaincodeDefinitionGetter interface {
ChaincodeDefinition(chaincodeName string, txSim ledger.QueryExecutor) (ccprovider.ChaincodeDefinition, error)
}
// LedgerGetter is used to get ledgers for chaincode.
type LedgerGetter interface {
GetLedger(cid string) ledger.PeerLedger
}
// UUIDGenerator is responsible for creating unique query identifiers.
type UUIDGenerator interface {
New() string
}
type UUIDGeneratorFunc func() string
func (u UUIDGeneratorFunc) New() string { return u() }
// ApplicationConfigRetriever to retrieve the application configuration for a channel
type ApplicationConfigRetriever interface {
// GetApplicationConfig returns the channelconfig.Application for the channel
// and whether the Application config exists
GetApplicationConfig(cid string) (channelconfig.Application, bool)
}
// Handler implements the peer side of the chaincode stream.
type Handler struct {
// Keepalive specifies the interval at which keep-alive messages are sent.
Keepalive time.Duration
// SystemCCVersion specifies the current system chaincode version
SystemCCVersion string
// DefinitionGetter is used to retrieve the chaincode definition from the
// Lifecycle System Chaincode.
DefinitionGetter ChaincodeDefinitionGetter
// Invoker is used to invoke chaincode.
Invoker Invoker
// Registry is used to track active handlers.
Registry Registry
// ACLProvider is used to check if a chaincode invocation should be allowed.
ACLProvider ACLProvider
// TXContexts is a collection of TransactionContext instances
// that are accessed by channel name and transaction ID.
TXContexts ContextRegistry
// activeTransactions holds active transaction identifiers.
ActiveTransactions TransactionRegistry
// SystemCCProvider provides access to system chaincode metadata
SystemCCProvider SystemCCProvider
// InstantiationPolicyChecker is used to evaluate the chaincode instantiation policies.
InstantiationPolicyChecker InstantiationPolicyChecker
// QueryResponeBuilder is used to build query responses
QueryResponseBuilder QueryResponseBuilder
// LedgerGetter is used to get the ledger associated with a channel
LedgerGetter LedgerGetter
// UUIDGenerator is used to generate UUIDs
UUIDGenerator UUIDGenerator
// AppConfig is used to retrieve the application config for a channel
AppConfig ApplicationConfigRetriever
// Metrics holds chaincode handler metrics
Metrics *HandlerMetrics
// state holds the current handler state. It will be created, established, or
// ready.
state State
// chaincodeID holds the ID of the chaincode that registered with the peer.
chaincodeID *pb.ChaincodeID
// ccInstances holds information about the chaincode instance associated with
// the peer.
ccInstance *sysccprovider.ChaincodeInstance
// serialLock is used to serialize sends across the grpc chat stream.
serialLock sync.Mutex
// chatStream is the bidirectional grpc stream used to communicate with the
// chaincode instance.
chatStream ccintf.ChaincodeStream
// errChan is used to communicate errors from the async send to the receive loop
errChan chan error
// mutex is used to serialze the stream closed chan.
mutex sync.Mutex
// streamDoneChan is closed when the chaincode stream terminates.
streamDoneChan chan struct{}
}
// handleMessage is called by ProcessStream to dispatch messages.
func (h *Handler) handleMessage(msg *pb.ChaincodeMessage) error {
chaincodeLogger.Debugf("[%s] Fabric side handling ChaincodeMessage of type: %s in state %s", shorttxid(msg.Txid), msg.Type, h.state)
if msg.Type == pb.ChaincodeMessage_KEEPALIVE {
return nil
}
switch h.state {
case Created:
return h.handleMessageCreatedState(msg)
case Ready:
return h.handleMessageReadyState(msg)
default:
return errors.Errorf("handle message: invalid state %s for transaction %s", h.state, msg.Txid)
}
}
func (h *Handler) handleMessageCreatedState(msg *pb.ChaincodeMessage) error {
switch msg.Type {
case pb.ChaincodeMessage_REGISTER:
h.HandleRegister(msg)
default:
return fmt.Errorf("[%s] Fabric side handler cannot handle message (%s) while in created state", msg.Txid, msg.Type)
}
return nil
}
func (h *Handler) handleMessageReadyState(msg *pb.ChaincodeMessage) error {
switch msg.Type {
case pb.ChaincodeMessage_COMPLETED, pb.ChaincodeMessage_ERROR:
h.Notify(msg)
case pb.ChaincodeMessage_PUT_STATE:
go h.HandleTransaction(msg, h.HandlePutState)
case pb.ChaincodeMessage_DEL_STATE:
go h.HandleTransaction(msg, h.HandleDelState)
case pb.ChaincodeMessage_INVOKE_CHAINCODE:
go h.HandleTransaction(msg, h.HandleInvokeChaincode)
case pb.ChaincodeMessage_GET_STATE:
go h.HandleTransaction(msg, h.HandleGetState)
case pb.ChaincodeMessage_GET_STATE_BY_RANGE:
go h.HandleTransaction(msg, h.HandleGetStateByRange)
case pb.ChaincodeMessage_GET_QUERY_RESULT:
go h.HandleTransaction(msg, h.HandleGetQueryResult)
case pb.ChaincodeMessage_GET_HISTORY_FOR_KEY:
go h.HandleTransaction(msg, h.HandleGetHistoryForKey)
case pb.ChaincodeMessage_QUERY_STATE_NEXT:
go h.HandleTransaction(msg, h.HandleQueryStateNext)
case pb.ChaincodeMessage_QUERY_STATE_CLOSE:
go h.HandleTransaction(msg, h.HandleQueryStateClose)
case pb.ChaincodeMessage_GET_PRIVATE_DATA_HASH:
go h.HandleTransaction(msg, h.HandleGetPrivateDataHash)
case pb.ChaincodeMessage_GET_STATE_METADATA:
go h.HandleTransaction(msg, h.HandleGetStateMetadata)
case pb.ChaincodeMessage_PUT_STATE_METADATA:
go h.HandleTransaction(msg, h.HandlePutStateMetadata)
default:
return fmt.Errorf("[%s] Fabric side handler cannot handle message (%s) while in ready state", msg.Txid, msg.Type)
}
return nil
}
type MessageHandler interface {
Handle(*pb.ChaincodeMessage, *TransactionContext) (*pb.ChaincodeMessage, error)
}
type handleFunc func(*pb.ChaincodeMessage, *TransactionContext) (*pb.ChaincodeMessage, error)
// HandleTransaction is a middleware function that obtains and verifies a transaction
// context prior to forwarding the message to the provided delegate. Response messages
// returned by the delegate are sent to the chat stream. Any errors returned by the
// delegate are packaged as chaincode error messages.
func (h *Handler) HandleTransaction(msg *pb.ChaincodeMessage, delegate handleFunc) {
chaincodeLogger.Debugf("[%s] handling %s from chaincode", shorttxid(msg.Txid), msg.Type.String())
if !h.registerTxid(msg) {
return
}
startTime := time.Now()
var txContext *TransactionContext
var err error
if msg.Type == pb.ChaincodeMessage_INVOKE_CHAINCODE {
txContext, err = h.getTxContextForInvoke(msg.ChannelId, msg.Txid, msg.Payload, "")
} else {
txContext, err = h.isValidTxSim(msg.ChannelId, msg.Txid, "no ledger context")
}
chaincodeName := h.chaincodeID.Name + ":" + h.chaincodeID.Version
meterLabels := []string{
"type", msg.Type.String(),
"channel", msg.ChannelId,
"chaincode", chaincodeName,
}
h.Metrics.ShimRequestsReceived.With(meterLabels...).Add(1)
var resp *pb.ChaincodeMessage
if err == nil {
resp, err = delegate(msg, txContext)
}
if err != nil {
err = errors.Wrapf(err, "%s failed: transaction ID: %s", msg.Type, msg.Txid)
chaincodeLogger.Errorf("[%s] Failed to handle %s. error: %+v", shorttxid(msg.Txid), msg.Type, err)
resp = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(err.Error()), Txid: msg.Txid, ChannelId: msg.ChannelId}
}
chaincodeLogger.Debugf("[%s] Completed %s. Sending %s", shorttxid(msg.Txid), msg.Type, resp.Type)
h.ActiveTransactions.Remove(msg.ChannelId, msg.Txid)
h.serialSendAsync(resp)
meterLabels = append(meterLabels, "success", strconv.FormatBool(resp.Type != pb.ChaincodeMessage_ERROR))
h.Metrics.ShimRequestDuration.With(meterLabels...).Observe(time.Since(startTime).Seconds())
h.Metrics.ShimRequestsCompleted.With(meterLabels...).Add(1)
}
func shorttxid(txid string) string {
if len(txid) < 8 {
return txid
}
return txid[0:8]
}
// ParseName parses a chaincode name into a ChaincodeInstance. The name should
// be of the form "chaincode-name:version/channel-name" with optional elements.
func ParseName(ccName string) *sysccprovider.ChaincodeInstance {
ci := &sysccprovider.ChaincodeInstance{}
z := strings.SplitN(ccName, "/", 2)
if len(z) == 2 {
ci.ChainID = z[1]
}
z = strings.SplitN(z[0], ":", 2)
if len(z) == 2 {
ci.ChaincodeVersion = z[1]
}
ci.ChaincodeName = z[0]
return ci
}
func (h *Handler) ChaincodeName() string {
if h.ccInstance == nil {
return ""
}
return h.ccInstance.ChaincodeName
}
// serialSend serializes msgs so gRPC will be happy
func (h *Handler) serialSend(msg *pb.ChaincodeMessage) error {
h.serialLock.Lock()
defer h.serialLock.Unlock()
if err := h.chatStream.Send(msg); err != nil {
err = errors.WithMessage(err, fmt.Sprintf("[%s] error sending %s", shorttxid(msg.Txid), msg.Type))
chaincodeLogger.Errorf("%+v", err)
return err
}
return nil
}
// serialSendAsync serves the same purpose as serialSend (serialize msgs so gRPC will
// be happy). In addition, it is also asynchronous so send-remoterecv--localrecv loop
// can be nonblocking. Only errors need to be handled and these are handled by
// communication on supplied error channel. A typical use will be a non-blocking or
// nil channel
func (h *Handler) serialSendAsync(msg *pb.ChaincodeMessage) {
go func() {
if err := h.serialSend(msg); err != nil {
// provide an error response to the caller
resp := &pb.ChaincodeMessage{
Type: pb.ChaincodeMessage_ERROR,
Payload: []byte(err.Error()),
Txid: msg.Txid,
ChannelId: msg.ChannelId,
}
h.Notify(resp)
// surface send error to stream processing
h.errChan <- err
}
}()
}
// Check if the transactor is allow to call this chaincode on this channel
func (h *Handler) checkACL(signedProp *pb.SignedProposal, proposal *pb.Proposal, ccIns *sysccprovider.ChaincodeInstance) error {
// ensure that we don't invoke a system chaincode
// that is not invokable through a cc2cc invocation
if h.SystemCCProvider.IsSysCCAndNotInvokableCC2CC(ccIns.ChaincodeName) {
return errors.Errorf("system chaincode %s cannot be invoked with a cc2cc invocation", ccIns.ChaincodeName)
}
// if we are here, all we know is that the invoked chaincode is either
// - a system chaincode that *is* invokable through a cc2cc
// (but we may still have to determine whether the invoker can perform this invocation)
// - an application chaincode
// (and we still need to determine whether the invoker can invoke it)
if h.SystemCCProvider.IsSysCC(ccIns.ChaincodeName) {
// Allow this call
return nil
}
// A Nil signedProp will be rejected for non-system chaincodes
if signedProp == nil {
return errors.Errorf("signed proposal must not be nil from caller [%s]", ccIns.String())
}
return h.ACLProvider.CheckACL(resources.Peer_ChaincodeToChaincode, ccIns.ChainID, signedProp)
}
func (h *Handler) deregister() {
if h.chaincodeID != nil {
h.Registry.Deregister(h.chaincodeID.Name)
}
}
func (h *Handler) streamDone() <-chan struct{} {
h.mutex.Lock()
defer h.mutex.Unlock()
return h.streamDoneChan
}
func (h *Handler) ProcessStream(stream ccintf.ChaincodeStream) error {
defer h.deregister()
h.mutex.Lock()
h.streamDoneChan = make(chan struct{})
h.mutex.Unlock()
defer close(h.streamDoneChan)
h.chatStream = stream
h.errChan = make(chan error, 1)
var keepaliveCh <-chan time.Time
if h.Keepalive != 0 {
ticker := time.NewTicker(h.Keepalive)
defer ticker.Stop()
keepaliveCh = ticker.C
}
// holds return values from gRPC Recv below
type recvMsg struct {
msg *pb.ChaincodeMessage
err error
}
msgAvail := make(chan *recvMsg, 1)
receiveMessage := func() {
in, err := h.chatStream.Recv()
msgAvail <- &recvMsg{in, err}
}
go receiveMessage()
for {
select {
case rmsg := <-msgAvail:
switch {
// Defer the deregistering of the this handler.
case rmsg.err == io.EOF:
chaincodeLogger.Debugf("received EOF, ending chaincode support stream: %s", rmsg.err)
return rmsg.err
case rmsg.err != nil:
err := errors.Wrap(rmsg.err, "receive failed")
chaincodeLogger.Errorf("handling chaincode support stream: %+v", err)
return err
case rmsg.msg == nil:
err := errors.New("received nil message, ending chaincode support stream")
chaincodeLogger.Debugf("%+v", err)
return err
default:
err := h.handleMessage(rmsg.msg)
if err != nil {
err = errors.WithMessage(err, "error handling message, ending stream")
chaincodeLogger.Errorf("[%s] %+v", shorttxid(rmsg.msg.Txid), err)
return err
}
go receiveMessage()
}
case sendErr := <-h.errChan:
err := errors.Wrapf(sendErr, "received error while sending message, ending chaincode support stream")
chaincodeLogger.Errorf("%s", err)
return err
case <-keepaliveCh:
// if no error message from serialSend, KEEPALIVE happy, and don't care about error
// (maybe it'll work later)
h.serialSendAsync(&pb.ChaincodeMessage{Type: pb.ChaincodeMessage_KEEPALIVE})
continue
}
}
}
// sendReady sends READY to chaincode serially (just like REGISTER)
func (h *Handler) sendReady() error {
chaincodeLogger.Debugf("sending READY for chaincode %+v", h.chaincodeID)
ccMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_READY}
// if error in sending tear down the h
if err := h.serialSend(ccMsg); err != nil {
chaincodeLogger.Errorf("error sending READY (%s) for chaincode %+v", err, h.chaincodeID)
return err
}
h.state = Ready
chaincodeLogger.Debugf("Changed to state ready for chaincode %+v", h.chaincodeID)
return nil
}
// notifyRegistry will send ready on registration success and
// update the launch state of the chaincode in the handler registry.
func (h *Handler) notifyRegistry(err error) {
if err == nil {
err = h.sendReady()
}
if err != nil {
h.Registry.Failed(h.chaincodeID.Name, err)
chaincodeLogger.Errorf("failed to start %s", h.chaincodeID)
return
}
h.Registry.Ready(h.chaincodeID.Name)
}
// handleRegister is invoked when chaincode tries to register.
func (h *Handler) HandleRegister(msg *pb.ChaincodeMessage) {
chaincodeLogger.Debugf("Received %s in state %s", msg.Type, h.state)
chaincodeID := &pb.ChaincodeID{}
err := proto.Unmarshal(msg.Payload, chaincodeID)
if err != nil {
chaincodeLogger.Errorf("Error in received %s, could NOT unmarshal registration info: %s", pb.ChaincodeMessage_REGISTER, err)
return
}
// Now register with the chaincodeSupport
h.chaincodeID = chaincodeID
err = h.Registry.Register(h)
if err != nil {
h.notifyRegistry(err)
return
}
// get the component parts so we can use the root chaincode
// name in keys
h.ccInstance = ParseName(h.chaincodeID.Name)
chaincodeLogger.Debugf("Got %s for chaincodeID = %s, sending back %s", pb.ChaincodeMessage_REGISTER, chaincodeID, pb.ChaincodeMessage_REGISTERED)
if err := h.serialSend(&pb.ChaincodeMessage{Type: pb.ChaincodeMessage_REGISTERED}); err != nil {
chaincodeLogger.Errorf("error sending %s: %s", pb.ChaincodeMessage_REGISTERED, err)
h.notifyRegistry(err)
return
}
h.state = Established
chaincodeLogger.Debugf("Changed state to established for %+v", h.chaincodeID)
// for dev mode this will also move to ready automatically
h.notifyRegistry(nil)
}
func (h *Handler) Notify(msg *pb.ChaincodeMessage) {
tctx := h.TXContexts.Get(msg.ChannelId, msg.Txid)
if tctx == nil {
chaincodeLogger.Debugf("notifier Txid:%s, channelID:%s does not exist for handling message %s", msg.Txid, msg.ChannelId, msg.Type)
return
}
chaincodeLogger.Debugf("[%s] notifying Txid:%s, channelID:%s", shorttxid(msg.Txid), msg.Txid, msg.ChannelId)
tctx.ResponseNotifier <- msg
tctx.CloseQueryIterators()
}
// is this a txid for which there is a valid txsim
func (h *Handler) isValidTxSim(channelID string, txid string, fmtStr string, args ...interface{}) (*TransactionContext, error) {
txContext := h.TXContexts.Get(channelID, txid)
if txContext == nil || txContext.TXSimulator == nil {
err := errors.Errorf(fmtStr, args...)
chaincodeLogger.Errorf("no ledger context: %s %s\n\n %+v", channelID, txid, err)
return nil, err
}
return txContext, nil
}
// register Txid to prevent overlapping handle messages from chaincode
func (h *Handler) registerTxid(msg *pb.ChaincodeMessage) bool {
// Check if this is the unique state request from this chaincode txid
if h.ActiveTransactions.Add(msg.ChannelId, msg.Txid) {
return true
}
// Log the issue and drop the request
chaincodeName := "unknown"
if h.chaincodeID != nil {
chaincodeName = h.chaincodeID.Name
}
chaincodeLogger.Errorf("[%s] Another request pending for this CC: %s, Txid: %s, ChannelID: %s. Cannot process.", shorttxid(msg.Txid), chaincodeName, msg.Txid, msg.ChannelId)
return false
}
func (h *Handler) checkMetadataCap(msg *pb.ChaincodeMessage) error {
ac, exists := h.AppConfig.GetApplicationConfig(msg.ChannelId)
if !exists {
return errors.Errorf("application config does not exist for %s", msg.ChannelId)
}
if !ac.Capabilities().KeyLevelEndorsement() {
return errors.New("key level endorsement is not enabled, channel application capability of V1_3 or later is required")
}
return nil
}
func errorIfCreatorHasNoReadAccess(chaincodeName, collection string, txContext *TransactionContext) error {
accessAllowed, err := hasReadAccess(chaincodeName, collection, txContext)
if err != nil {
return err
}
if !accessAllowed {
return errors.Errorf("tx creator does not have read access permission on privatedata in chaincodeName:%s collectionName: %s",
chaincodeName, collection)
}
return nil
}
func hasReadAccess(chaincodeName, collection string, txContext *TransactionContext) (bool, error) {
// check to see if read access has already been checked in the scope of this chaincode simulation
if txContext.AllowedCollectionAccess[collection] {
return true, nil
}
cc := common.CollectionCriteria{
Channel: txContext.ChainID,
Namespace: chaincodeName,
Collection: collection,
}
accessAllowed, err := txContext.CollectionStore.HasReadAccess(cc, txContext.SignedProp, txContext.TXSimulator)
if err != nil {
return false, err
}
if accessAllowed {
txContext.AllowedCollectionAccess[collection] = accessAllowed
}
return accessAllowed, err
}
// Handles query to ledger to get state
func (h *Handler) HandleGetState(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
getState := &pb.GetState{}
err := proto.Unmarshal(msg.Payload, getState)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
var res []byte
chaincodeName := h.ChaincodeName()
collection := getState.Collection
chaincodeLogger.Debugf("[%s] getting state for chaincode %s, key %s, channel %s", shorttxid(msg.Txid), chaincodeName, getState.Key, txContext.ChainID)
if isCollectionSet(collection) {
if txContext.IsInitTransaction {
return nil, errors.New("private data APIs are not allowed in chaincode Init()")
}
if err := errorIfCreatorHasNoReadAccess(chaincodeName, collection, txContext); err != nil {
return nil, err
}
res, err = txContext.TXSimulator.GetPrivateData(chaincodeName, collection, getState.Key)
} else {
res, err = txContext.TXSimulator.GetState(chaincodeName, getState.Key)
}
if err != nil {
return nil, errors.WithStack(err)
}
if res == nil {
chaincodeLogger.Debugf("[%s] No state associated with key: %s. Sending %s with an empty payload", shorttxid(msg.Txid), getState.Key, pb.ChaincodeMessage_RESPONSE)
}
// Send response msg back to chaincode. GetState will not trigger event
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
func (h *Handler) HandleGetPrivateDataHash(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
getState := &pb.GetState{}
err := proto.Unmarshal(msg.Payload, getState)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
var res []byte
chaincodeName := h.ChaincodeName()
collection := getState.Collection
chaincodeLogger.Debugf("[%s] getting private data hash for chaincode %s, key %s, channel %s", shorttxid(msg.Txid), chaincodeName, getState.Key, txContext.ChainID)
if txContext.IsInitTransaction {
return nil, errors.New("private data APIs are not allowed in chaincode Init()")
}
res, err = txContext.TXSimulator.GetPrivateDataHash(chaincodeName, collection, getState.Key)
if err != nil {
return nil, errors.WithStack(err)
}
if res == nil {
chaincodeLogger.Debugf("[%s] No state associated with key: %s. Sending %s with an empty payload", shorttxid(msg.Txid), getState.Key, pb.ChaincodeMessage_RESPONSE)
}
// Send response msg back to chaincode. GetState will not trigger event
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
// Handles query to ledger to get state metadata
func (h *Handler) HandleGetStateMetadata(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
err := h.checkMetadataCap(msg)
if err != nil {
return nil, err
}
getStateMetadata := &pb.GetStateMetadata{}
err = proto.Unmarshal(msg.Payload, getStateMetadata)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
chaincodeName := h.ChaincodeName()
collection := getStateMetadata.Collection
chaincodeLogger.Debugf("[%s] getting state metadata for chaincode %s, key %s, channel %s", shorttxid(msg.Txid), chaincodeName, getStateMetadata.Key, txContext.ChainID)
var metadata map[string][]byte
if isCollectionSet(collection) {
if txContext.IsInitTransaction {
return nil, errors.New("private data APIs are not allowed in chaincode Init()")
}
if err := errorIfCreatorHasNoReadAccess(chaincodeName, collection, txContext); err != nil {
return nil, err
}
metadata, err = txContext.TXSimulator.GetPrivateDataMetadata(chaincodeName, collection, getStateMetadata.Key)
} else {
metadata, err = txContext.TXSimulator.GetStateMetadata(chaincodeName, getStateMetadata.Key)
}
if err != nil {
return nil, errors.WithStack(err)
}
var metadataResult pb.StateMetadataResult
for metakey := range metadata {
md := &pb.StateMetadata{Metakey: metakey, Value: metadata[metakey]}
metadataResult.Entries = append(metadataResult.Entries, md)
}
res, err := proto.Marshal(&metadataResult)
if err != nil {
return nil, errors.WithStack(err)
}
// Send response msg back to chaincode. GetState will not trigger event
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
// Handles query to ledger to rage query state
func (h *Handler) HandleGetStateByRange(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
getStateByRange := &pb.GetStateByRange{}
err := proto.Unmarshal(msg.Payload, getStateByRange)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
metadata, err := getQueryMetadataFromBytes(getStateByRange.Metadata)
if err != nil {
return nil, err
}
totalReturnLimit := calculateTotalReturnLimit(metadata)
iterID := h.UUIDGenerator.New()
var rangeIter commonledger.ResultsIterator
var paginationInfo map[string]interface{}
isPaginated := false
chaincodeName := h.ChaincodeName()
collection := getStateByRange.Collection
if isCollectionSet(collection) {
if txContext.IsInitTransaction {
return nil, errors.New("private data APIs are not allowed in chaincode Init()")
}
if err := errorIfCreatorHasNoReadAccess(chaincodeName, collection, txContext); err != nil {
return nil, err
}
rangeIter, err = txContext.TXSimulator.GetPrivateDataRangeScanIterator(chaincodeName, collection,
getStateByRange.StartKey, getStateByRange.EndKey)
} else if isMetadataSetForPagination(metadata) {
paginationInfo, err = createPaginationInfoFromMetadata(metadata, totalReturnLimit, pb.ChaincodeMessage_GET_STATE_BY_RANGE)
if err != nil {
return nil, err
}
isPaginated = true
startKey := getStateByRange.StartKey
if isMetadataSetForPagination(metadata) {
if metadata.Bookmark != "" {
startKey = metadata.Bookmark
}
}
rangeIter, err = txContext.TXSimulator.GetStateRangeScanIteratorWithMetadata(chaincodeName,
startKey, getStateByRange.EndKey, paginationInfo)
} else {
rangeIter, err = txContext.TXSimulator.GetStateRangeScanIterator(chaincodeName, getStateByRange.StartKey, getStateByRange.EndKey)
}
if err != nil {
return nil, errors.WithStack(err)
}
txContext.InitializeQueryContext(iterID, rangeIter)
payload, err := h.QueryResponseBuilder.BuildQueryResponse(txContext, rangeIter, iterID, isPaginated, totalReturnLimit)
if err != nil {
txContext.CleanupQueryContext(iterID)
return nil, errors.WithStack(err)
}
payloadBytes, err := proto.Marshal(payload)
if err != nil {
txContext.CleanupQueryContext(iterID)
return nil, errors.Wrap(err, "marshal failed")
}
chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE)
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
// Handles query to ledger for query state next
func (h *Handler) HandleQueryStateNext(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
queryStateNext := &pb.QueryStateNext{}
err := proto.Unmarshal(msg.Payload, queryStateNext)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
queryIter := txContext.GetQueryIterator(queryStateNext.Id)
if queryIter == nil {
return nil, errors.New("query iterator not found")
}
totalReturnLimit := calculateTotalReturnLimit(nil)
payload, err := h.QueryResponseBuilder.BuildQueryResponse(txContext, queryIter, queryStateNext.Id, false, totalReturnLimit)
if err != nil {
txContext.CleanupQueryContext(queryStateNext.Id)
return nil, errors.WithStack(err)
}
payloadBytes, err := proto.Marshal(payload)
if err != nil {
txContext.CleanupQueryContext(queryStateNext.Id)
return nil, errors.Wrap(err, "marshal failed")
}
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
// Handles the closing of a state iterator
func (h *Handler) HandleQueryStateClose(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
queryStateClose := &pb.QueryStateClose{}
err := proto.Unmarshal(msg.Payload, queryStateClose)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
iter := txContext.GetQueryIterator(queryStateClose.Id)
if iter != nil {
txContext.CleanupQueryContext(queryStateClose.Id)
}
payload := &pb.QueryResponse{HasMore: false, Id: queryStateClose.Id}
payloadBytes, err := proto.Marshal(payload)
if err != nil {
return nil, errors.Wrap(err, "marshal failed")
}
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
// Handles query to ledger to execute query state
func (h *Handler) HandleGetQueryResult(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
iterID := h.UUIDGenerator.New()
getQueryResult := &pb.GetQueryResult{}
err := proto.Unmarshal(msg.Payload, getQueryResult)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
metadata, err := getQueryMetadataFromBytes(getQueryResult.Metadata)
if err != nil {
return nil, err
}
totalReturnLimit := calculateTotalReturnLimit(metadata)
isPaginated := false
var executeIter commonledger.ResultsIterator
var paginationInfo map[string]interface{}
chaincodeName := h.ChaincodeName()
collection := getQueryResult.Collection
if isCollectionSet(collection) {
if txContext.IsInitTransaction {
return nil, errors.New("private data APIs are not allowed in chaincode Init()")
}
if err := errorIfCreatorHasNoReadAccess(chaincodeName, collection, txContext); err != nil {
return nil, err
}
executeIter, err = txContext.TXSimulator.ExecuteQueryOnPrivateData(chaincodeName, collection, getQueryResult.Query)
} else if isMetadataSetForPagination(metadata) {
paginationInfo, err = createPaginationInfoFromMetadata(metadata, totalReturnLimit, pb.ChaincodeMessage_GET_QUERY_RESULT)
if err != nil {
return nil, err
}
isPaginated = true
executeIter, err = txContext.TXSimulator.ExecuteQueryWithMetadata(chaincodeName,
getQueryResult.Query, paginationInfo)
} else {
executeIter, err = txContext.TXSimulator.ExecuteQuery(chaincodeName, getQueryResult.Query)
}
if err != nil {
return nil, errors.WithStack(err)
}
txContext.InitializeQueryContext(iterID, executeIter)
payload, err := h.QueryResponseBuilder.BuildQueryResponse(txContext, executeIter, iterID, isPaginated, totalReturnLimit)
if err != nil {
txContext.CleanupQueryContext(iterID)
return nil, errors.WithStack(err)
}
payloadBytes, err := proto.Marshal(payload)
if err != nil {
txContext.CleanupQueryContext(iterID)
return nil, errors.Wrap(err, "marshal failed")
}
chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE)
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
// Handles query to ledger history db
func (h *Handler) HandleGetHistoryForKey(msg *pb.ChaincodeMessage, txContext *TransactionContext) (*pb.ChaincodeMessage, error) {
iterID := h.UUIDGenerator.New()
chaincodeName := h.ChaincodeName()
getHistoryForKey := &pb.GetHistoryForKey{}
err := proto.Unmarshal(msg.Payload, getHistoryForKey)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
historyIter, err := txContext.HistoryQueryExecutor.GetHistoryForKey(chaincodeName, getHistoryForKey.Key)
if err != nil {
return nil, errors.WithStack(err)
}
totalReturnLimit := calculateTotalReturnLimit(nil)
txContext.InitializeQueryContext(iterID, historyIter)
payload, err := h.QueryResponseBuilder.BuildQueryResponse(txContext, historyIter, iterID, false, totalReturnLimit)
if err != nil {
txContext.CleanupQueryContext(iterID)
return nil, errors.WithStack(err)
}
payloadBytes, err := proto.Marshal(payload)
if err != nil {
txContext.CleanupQueryContext(iterID)
return nil, errors.Wrap(err, "marshal failed")
}
chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE)
return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid, ChannelId: msg.ChannelId}, nil
}
func isCollectionSet(collection string) bool {
return collection != ""
}
func isMetadataSetForPagination(metadata *pb.QueryMetadata) bool {
if metadata == nil {
return false
}
if metadata.PageSize == 0 && metadata.Bookmark == "" {
return false
}
return true
}
func getQueryMetadataFromBytes(metadataBytes []byte) (*pb.QueryMetadata, error) {
if metadataBytes != nil {
metadata := &pb.QueryMetadata{}
err := proto.Unmarshal(metadataBytes, metadata)
if err != nil {
return nil, errors.Wrap(err, "unmarshal failed")
}
return metadata, nil
}
return nil, nil
}
func createPaginationInfoFromMetadata(metadata *pb.QueryMetadata, totalReturnLimit int32, queryType pb.ChaincodeMessage_Type) (map[string]interface{}, error) {
paginationInfoMap := make(map[string]interface{})
switch queryType {
case pb.ChaincodeMessage_GET_QUERY_RESULT:
paginationInfoMap["bookmark"] = metadata.Bookmark
case pb.ChaincodeMessage_GET_STATE_BY_RANGE:
// this is a no-op for range query
default:
return nil, errors.New("query type must be either GetQueryResult or GetStateByRange")
}