handler.go 52.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package chaincode

import (
20
	"bytes"
21
22
23
24
25
26
	"fmt"
	"io"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
27
	commonledger "github.com/hyperledger/fabric/common/ledger"
Jason Yellick's avatar
Jason Yellick committed
28
	"github.com/hyperledger/fabric/common/util"
29
	"github.com/hyperledger/fabric/core/common/ccprovider"
30
	ccintf "github.com/hyperledger/fabric/core/container/ccintf"
31
	"github.com/hyperledger/fabric/core/ledger"
32
	"github.com/hyperledger/fabric/core/peer"
33
	pb "github.com/hyperledger/fabric/protos/peer"
34
	"github.com/hyperledger/fabric/protos/utils"
35
	"github.com/looplab/fsm"
36
	logging "github.com/op/go-logging"
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
	"golang.org/x/net/context"
)

const (
	createdstate     = "created"     //start state
	establishedstate = "established" //in: CREATED, rcv:  REGISTER, send: REGISTERED, INIT
	initstate        = "init"        //in:ESTABLISHED, rcv:-, send: INIT
	readystate       = "ready"       //in:ESTABLISHED,TRANSACTION, rcv:COMPLETED
	endstate         = "end"         //in:INIT,ESTABLISHED, rcv: error, terminate container

)

var chaincodeLogger = logging.MustGetLogger("chaincode")

// MessageHandler interface for handling chaincode messages (common between Peer chaincode support and chaincode)
type MessageHandler interface {
	HandleMessage(msg *pb.ChaincodeMessage) error
	SendMessage(msg *pb.ChaincodeMessage) error
}

type transactionContext struct {
58
	chainID          string
59
60
	proposal         *pb.Proposal
	responseNotifier chan *pb.ChaincodeMessage
61
62

	// tracks open iterators used for range queries
63
	queryIteratorMap map[string]commonledger.ResultsIterator
64

65
	txsimulator ledger.TxSimulator
66
67
68
69
70
71
72
}

type nextStateInfo struct {
	msg      *pb.ChaincodeMessage
	sendToCC bool
}

73
74
75
76
77
78
79
80
//chaincode registered name is of the form
//    <name>:<version>/<suffix>
type ccParts struct {
	name    string //the main name of the chaincode
	version string //the version param if any (used for upgrade)
	suffix  string //for now just the chain name
}

81
82
83
84
85
86
87
88
// Handler responsbile for management of Peer's side of chaincode stream
type Handler struct {
	sync.RWMutex
	//peer to shim grpc serializer. User only in serialSend
	serialLock  sync.Mutex
	ChatStream  ccintf.ChaincodeStream
	FSM         *fsm.FSM
	ChaincodeID *pb.ChaincodeID
89
	ccCompParts *ccParts
90
91
92
93

	chaincodeSupport *ChaincodeSupport
	registered       bool
	readyNotify      chan bool
94
	// Map of tx txid to either invoke tx. Each tx will be
95
96
97
	// added prior to execute and remove when done execute
	txCtxs map[string]*transactionContext

Gabor Hosszu's avatar
Gabor Hosszu committed
98
	txidMap map[string]bool
99
100
101
102
103

	// used to do Send after making sure the state transition is complete
	nextState chan *nextStateInfo
}

Gabor Hosszu's avatar
Gabor Hosszu committed
104
105
106
func shorttxid(txid string) string {
	if len(txid) < 8 {
		return txid
107
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
108
	return txid[0:8]
109
110
}

111
112
113
114
115
116
117
118
//gets component parts from the canonical name of the chaincode.
//Called exactly once per chaincode when registering chaincode.
//This is needed for the "one-instance-per-chain" model when
//starting up the chaincode for each chain. It will still
//work for the "one-instance-for-all-chains" as the version
//and suffix will just be absent (also note that LCCC reserves
//"/:[]${}" as special chars mainly for such namespace uses)
func (handler *Handler) decomposeRegisteredName(cid *pb.ChaincodeID) {
119
120
121
122
123
124
	handler.ccCompParts = chaincodeIDParts(cid.Name)
}

func chaincodeIDParts(ccName string) *ccParts {
	b := []byte(ccName)
	p := &ccParts{}
125
126
127
128
129

	//compute suffix (ie, chain name)
	i := bytes.IndexByte(b, '/')
	if i >= 0 {
		if i < len(b)-1 {
130
			p.suffix = string(b[i+1:])
131
132
133
134
135
136
137
138
		}
		b = b[:i]
	}

	//compute version
	i = bytes.IndexByte(b, ':')
	if i >= 0 {
		if i < len(b)-1 {
139
			p.version = string(b[i+1:])
140
141
142
		}
		b = b[:i]
	}
143
144
	// remaining is the chaincode name
	p.name = string(b)
145

146
	return p
147
148
149
150
151
152
}

func (handler *Handler) getCCRootName() string {
	return handler.ccCompParts.name
}

153
//serialSend serializes msgs so gRPC will be happy
154
155
156
func (handler *Handler) serialSend(msg *pb.ChaincodeMessage) error {
	handler.serialLock.Lock()
	defer handler.serialLock.Unlock()
157
158
159
160
161

	var err error
	if err = handler.ChatStream.Send(msg); err != nil {
		err = fmt.Errorf("[%s]Error sending %s: %s", shorttxid(msg.Txid), msg.Type.String(), err)
		chaincodeLogger.Errorf("%s", err)
162
	}
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
	return err
}

//serialSendAsync serves the same purpose as serialSend (serializ 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 (handler *Handler) serialSendAsync(msg *pb.ChaincodeMessage, errc chan error) {
	go func() {
		err := handler.serialSend(msg)
		if errc != nil {
			errc <- err
		}
	}()
178
179
}

180
func (handler *Handler) createTxContext(ctxt context.Context, chainID string, txid string, prop *pb.Proposal) (*transactionContext, error) {
181
	if handler.txCtxs == nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
182
		return nil, fmt.Errorf("cannot create notifier for txid:%s", txid)
183
184
185
	}
	handler.Lock()
	defer handler.Unlock()
Gabor Hosszu's avatar
Gabor Hosszu committed
186
187
	if handler.txCtxs[txid] != nil {
		return nil, fmt.Errorf("txid:%s exists", txid)
188
	}
189
	txctx := &transactionContext{chainID: chainID, proposal: prop, responseNotifier: make(chan *pb.ChaincodeMessage, 1),
190
		queryIteratorMap: make(map[string]commonledger.ResultsIterator)}
Gabor Hosszu's avatar
Gabor Hosszu committed
191
	handler.txCtxs[txid] = txctx
192
	txctx.txsimulator = getTxSimulator(ctxt)
193

194
195
196
	return txctx, nil
}

Gabor Hosszu's avatar
Gabor Hosszu committed
197
func (handler *Handler) getTxContext(txid string) *transactionContext {
198
199
	handler.Lock()
	defer handler.Unlock()
Gabor Hosszu's avatar
Gabor Hosszu committed
200
	return handler.txCtxs[txid]
201
202
}

Gabor Hosszu's avatar
Gabor Hosszu committed
203
func (handler *Handler) deleteTxContext(txid string) {
204
205
206
	handler.Lock()
	defer handler.Unlock()
	if handler.txCtxs != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
207
		delete(handler.txCtxs, txid)
208
209
210
	}
}

211
func (handler *Handler) putQueryIterator(txContext *transactionContext, txid string,
212
	queryIterator commonledger.ResultsIterator) {
213
214
	handler.Lock()
	defer handler.Unlock()
215
	txContext.queryIteratorMap[txid] = queryIterator
216
217
}

218
func (handler *Handler) getQueryIterator(txContext *transactionContext, txid string) commonledger.ResultsIterator {
219
220
	handler.Lock()
	defer handler.Unlock()
221
	return txContext.queryIteratorMap[txid]
222
223
}

224
func (handler *Handler) deleteQueryIterator(txContext *transactionContext, txid string) {
225
226
	handler.Lock()
	defer handler.Unlock()
227
	delete(txContext.queryIteratorMap, txid)
228
229
}

230
231
232
233
234
235
236
237
238
239
// Check if the transactor is allow to call this chaincode on this channel
func (handler *Handler) checkACL(proposal *pb.Proposal, calledCC *ccParts) *pb.ChaincodeMessage {
	// TODO: Decide what to pass in to verify that this transactor can access this
	// channel (chID) and chaincode (ccID). Very likely we need the signedProposal
	// which contains the sig and creator cert

	// If error, return ChaincodeMessage with type ChaincodeMessage_ERROR
	return nil
}

240
241
//THIS CAN BE REMOVED ONCE WE FULL SUPPORT (Invoke) CONFIDENTIALITY WITH CC-CALLING-CC
//Only invocation are allowed
242
func (handler *Handler) canCallChaincode(txid string, isQuery bool) *pb.ChaincodeMessage {
243
	var errMsg string
Gabor Hosszu's avatar
Gabor Hosszu committed
244
	txctx := handler.getTxContext(txid)
245
	if txctx == nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
246
		errMsg = fmt.Sprintf("[%s]Error no context while checking for confidentiality. Sending %s", shorttxid(txid), pb.ChaincodeMessage_ERROR)
247
248
249
	}

	if errMsg != "" {
Gabor Hosszu's avatar
Gabor Hosszu committed
250
		return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(errMsg), Txid: txid}
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
	}

	//not CONFIDENTIAL transaction, OK to call CC
	return nil
}

func (handler *Handler) deregister() error {
	if handler.registered {
		handler.chaincodeSupport.deregisterHandler(handler)
	}
	return nil
}

func (handler *Handler) triggerNextState(msg *pb.ChaincodeMessage, send bool) {
	handler.nextState <- &nextStateInfo{msg, send}
}

func (handler *Handler) waitForKeepaliveTimer() <-chan time.Time {
	if handler.chaincodeSupport.keepalive > 0 {
		c := time.After(handler.chaincodeSupport.keepalive)
		return c
	}
	//no one will signal this channel, listner blocks forever
	c := make(chan time.Time, 1)
	return c
}

func (handler *Handler) processStream() error {
	defer handler.deregister()
	msgAvail := make(chan *pb.ChaincodeMessage)
	var nsInfo *nextStateInfo
	var in *pb.ChaincodeMessage
	var err error

	//recv is used to spin Recv routine after previous received msg
	//has been processed
	recv := true
288
289
290

	//catch send errors and bail now that sends aren't synchronous
	errc := make(chan error, 1)
291
292
293
294
295
296
297
298
299
300
301
302
303
	for {
		in = nil
		err = nil
		nsInfo = nil
		if recv {
			recv = false
			go func() {
				var in2 *pb.ChaincodeMessage
				in2, err = handler.ChatStream.Recv()
				msgAvail <- in2
			}()
		}
		select {
304
305
306
307
308
309
		case sendErr := <-errc:
			if sendErr != nil {
				return sendErr
			}
			//send was successful, just continue
			continue
310
311
312
313
314
315
316
317
318
319
320
321
322
		case in = <-msgAvail:
			// Defer the deregistering of the this handler.
			if err == io.EOF {
				chaincodeLogger.Debugf("Received EOF, ending chaincode support stream, %s", err)
				return err
			} else if err != nil {
				chaincodeLogger.Errorf("Error handling chaincode support stream: %s", err)
				return err
			} else if in == nil {
				err = fmt.Errorf("Received nil message, ending chaincode support stream")
				chaincodeLogger.Debug("Received nil message, ending chaincode support stream")
				return err
			}
Gabor Hosszu's avatar
Gabor Hosszu committed
323
			chaincodeLogger.Debugf("[%s]Received message %s from shim", shorttxid(in.Txid), in.Type.String())
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
			if in.Type.String() == pb.ChaincodeMessage_ERROR.String() {
				chaincodeLogger.Errorf("Got error: %s", string(in.Payload))
			}

			// we can spin off another Recv again
			recv = true

			if in.Type == pb.ChaincodeMessage_KEEPALIVE {
				chaincodeLogger.Debug("Received KEEPALIVE Response")
				// Received a keep alive message, we don't do anything with it for now
				// and it does not touch the state machine
				continue
			}
		case nsInfo = <-handler.nextState:
			in = nsInfo.msg
			if in == nil {
				err = fmt.Errorf("Next state nil message, ending chaincode support stream")
				chaincodeLogger.Debug("Next state nil message, ending chaincode support stream")
				return err
			}
Gabor Hosszu's avatar
Gabor Hosszu committed
344
			chaincodeLogger.Debugf("[%s]Move state message %s", shorttxid(in.Txid), in.Type.String())
345
346
347
348
349
350
		case <-handler.waitForKeepaliveTimer():
			if handler.chaincodeSupport.keepalive <= 0 {
				chaincodeLogger.Errorf("Invalid select: keepalive not on (keepalive=%d)", handler.chaincodeSupport.keepalive)
				continue
			}

351
352
353
			//if no error message from serialSend, KEEPALIVE happy, and don't care about error
			//(maybe it'll work later)
			handler.serialSendAsync(&pb.ChaincodeMessage{Type: pb.ChaincodeMessage_KEEPALIVE}, nil)
354
355
356
357
358
			continue
		}

		err = handler.HandleMessage(in)
		if err != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
359
			chaincodeLogger.Errorf("[%s]Error handling message, ending stream: %s", shorttxid(in.Txid), err)
360
361
362
363
			return fmt.Errorf("Error handling message, ending stream: %s", err)
		}

		if nsInfo != nil && nsInfo.sendToCC {
Gabor Hosszu's avatar
Gabor Hosszu committed
364
			chaincodeLogger.Debugf("[%s]sending state message %s", shorttxid(in.Txid), in.Type.String())
365
366
			//if error bail in select
			handler.serialSendAsync(in, errc)
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
		}
	}
}

// HandleChaincodeStream Main loop for handling the associated Chaincode stream
func HandleChaincodeStream(chaincodeSupport *ChaincodeSupport, ctxt context.Context, stream ccintf.ChaincodeStream) error {
	deadline, ok := ctxt.Deadline()
	chaincodeLogger.Debugf("Current context deadline = %s, ok = %v", deadline, ok)
	handler := newChaincodeSupportHandler(chaincodeSupport, stream)
	return handler.processStream()
}

func newChaincodeSupportHandler(chaincodeSupport *ChaincodeSupport, peerChatStream ccintf.ChaincodeStream) *Handler {
	v := &Handler{
		ChatStream: peerChatStream,
	}
	v.chaincodeSupport = chaincodeSupport
	//we want this to block
	v.nextState = make(chan *nextStateInfo)

	v.FSM = fsm.NewFSM(
		createdstate,
		fsm.Events{
			//Send REGISTERED, then, if deploy { trigger INIT(via INIT) } else { trigger READY(via COMPLETED) }
			{Name: pb.ChaincodeMessage_REGISTER.String(), Src: []string{createdstate}, Dst: establishedstate},
			{Name: pb.ChaincodeMessage_INIT.String(), Src: []string{establishedstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_READY.String(), Src: []string{establishedstate}, Dst: readystate},
394
395
396
397
398
399
400
			{Name: pb.ChaincodeMessage_PUT_STATE.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_PUT_STATE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_DEL_STATE.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_DEL_STATE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_INVOKE_CHAINCODE.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_INVOKE_CHAINCODE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_COMPLETED.String(), Src: []string{initstate, readystate}, Dst: readystate},
401
402
403
404
			{Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_GET_STATE.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_RANGE_QUERY_STATE.String(), Src: []string{initstate}, Dst: initstate},
405
406
407
408
409
410
			{Name: pb.ChaincodeMessage_EXECUTE_QUERY_STATE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_EXECUTE_QUERY_STATE.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_QUERY_STATE_NEXT.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_QUERY_STATE_NEXT.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_QUERY_STATE_CLOSE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_QUERY_STATE_CLOSE.String(), Src: []string{initstate}, Dst: initstate},
411
			{Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{initstate}, Dst: endstate},
412
413
414
415
			{Name: pb.ChaincodeMessage_ERROR.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{initstate}, Dst: initstate},
			{Name: pb.ChaincodeMessage_RESPONSE.String(), Src: []string{readystate}, Dst: readystate},
			{Name: pb.ChaincodeMessage_TRANSACTION.String(), Src: []string{readystate}, Dst: readystate},
416
417
		},
		fsm.Callbacks{
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
			"before_" + pb.ChaincodeMessage_REGISTER.String():           func(e *fsm.Event) { v.beforeRegisterEvent(e, v.FSM.Current()) },
			"before_" + pb.ChaincodeMessage_COMPLETED.String():          func(e *fsm.Event) { v.beforeCompletedEvent(e, v.FSM.Current()) },
			"before_" + pb.ChaincodeMessage_INIT.String():               func(e *fsm.Event) { v.beforeInitState(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_GET_STATE.String():           func(e *fsm.Event) { v.afterGetState(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_RANGE_QUERY_STATE.String():   func(e *fsm.Event) { v.afterRangeQueryState(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_EXECUTE_QUERY_STATE.String(): func(e *fsm.Event) { v.afterExecuteQueryState(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_QUERY_STATE_NEXT.String():    func(e *fsm.Event) { v.afterQueryStateNext(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_QUERY_STATE_CLOSE.String():   func(e *fsm.Event) { v.afterQueryStateClose(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_PUT_STATE.String():           func(e *fsm.Event) { v.enterBusyState(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_DEL_STATE.String():           func(e *fsm.Event) { v.enterBusyState(e, v.FSM.Current()) },
			"after_" + pb.ChaincodeMessage_INVOKE_CHAINCODE.String():    func(e *fsm.Event) { v.enterBusyState(e, v.FSM.Current()) },
			"enter_" + establishedstate:                                 func(e *fsm.Event) { v.enterEstablishedState(e, v.FSM.Current()) },
			"enter_" + initstate:                                        func(e *fsm.Event) { v.enterInitState(e, v.FSM.Current()) },
			"enter_" + readystate:                                       func(e *fsm.Event) { v.enterReadyState(e, v.FSM.Current()) },
			"enter_" + endstate:                                         func(e *fsm.Event) { v.enterEndState(e, v.FSM.Current()) },
433
434
435
436
437
438
		},
	)

	return v
}

Gabor Hosszu's avatar
Gabor Hosszu committed
439
440
func (handler *Handler) createTXIDEntry(txid string) bool {
	if handler.txidMap == nil {
441
442
443
444
		return false
	}
	handler.Lock()
	defer handler.Unlock()
Gabor Hosszu's avatar
Gabor Hosszu committed
445
	if handler.txidMap[txid] {
446
447
		return false
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
448
449
	handler.txidMap[txid] = true
	return handler.txidMap[txid]
450
451
}

Gabor Hosszu's avatar
Gabor Hosszu committed
452
func (handler *Handler) deleteTXIDEntry(txid string) {
453
454
	handler.Lock()
	defer handler.Unlock()
Gabor Hosszu's avatar
Gabor Hosszu committed
455
456
	if handler.txidMap != nil {
		delete(handler.txidMap, txid)
457
	} else {
Gabor Hosszu's avatar
Gabor Hosszu committed
458
		chaincodeLogger.Warningf("TXID %s not found!", txid)
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
	}
}

func (handler *Handler) notifyDuringStartup(val bool) {
	//if USER_RUNS_CC readyNotify will be nil
	if handler.readyNotify != nil {
		chaincodeLogger.Debug("Notifying during startup")
		handler.readyNotify <- val
	} else {
		chaincodeLogger.Debug("nothing to notify (dev mode ?)")
	}
}

// beforeRegisterEvent is invoked when chaincode tries to register.
func (handler *Handler) beforeRegisterEvent(e *fsm.Event, state string) {
	chaincodeLogger.Debugf("Received %s in state %s", e.Event, state)
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeID := &pb.ChaincodeID{}
	err := proto.Unmarshal(msg.Payload, chaincodeID)
	if err != nil {
		e.Cancel(fmt.Errorf("Error in received %s, could NOT unmarshal registration info: %s", pb.ChaincodeMessage_REGISTER, err))
		return
	}

	// Now register with the chaincodeSupport
	handler.ChaincodeID = chaincodeID
	err = handler.chaincodeSupport.registerHandler(handler)
	if err != nil {
		e.Cancel(err)
		handler.notifyDuringStartup(false)
		return
	}

496
497
498
499
	//get the component parts so we can use the root chaincode
	//name in keys
	handler.decomposeRegisteredName(handler.ChaincodeID)

500
501
502
503
504
505
506
507
508
509
510
	chaincodeLogger.Debugf("Got %s for chaincodeID = %s, sending back %s", e.Event, chaincodeID, pb.ChaincodeMessage_REGISTERED)
	if err := handler.serialSend(&pb.ChaincodeMessage{Type: pb.ChaincodeMessage_REGISTERED}); err != nil {
		e.Cancel(fmt.Errorf("Error sending %s: %s", pb.ChaincodeMessage_REGISTERED, err))
		handler.notifyDuringStartup(false)
		return
	}
}

func (handler *Handler) notify(msg *pb.ChaincodeMessage) {
	handler.Lock()
	defer handler.Unlock()
Gabor Hosszu's avatar
Gabor Hosszu committed
511
	tctx := handler.txCtxs[msg.Txid]
512
	if tctx == nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
513
		chaincodeLogger.Debugf("notifier Txid:%s does not exist", msg.Txid)
514
	} else {
Gabor Hosszu's avatar
Gabor Hosszu committed
515
		chaincodeLogger.Debugf("notifying Txid:%s", msg.Txid)
516
517
		tctx.responseNotifier <- msg

518
519
		// clean up queryIteratorMap
		for _, v := range tctx.queryIteratorMap {
520
521
522
523
524
			v.Close()
		}
	}
}

525
// beforeCompletedEvent is invoked when chaincode has completed execution of init, invoke.
526
527
528
529
530
531
532
func (handler *Handler) beforeCompletedEvent(e *fsm.Event, state string) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	// Notify on channel once into READY state
Gabor Hosszu's avatar
Gabor Hosszu committed
533
	chaincodeLogger.Debugf("[%s]beforeCompleted - not in ready state will notify when in readystate", shorttxid(msg.Txid))
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
	return
}

// beforeInitState is invoked before an init message is sent to the chaincode.
func (handler *Handler) beforeInitState(e *fsm.Event, state string) {
	chaincodeLogger.Debugf("Before state %s.. notifying waiter that we are up", state)
	handler.notifyDuringStartup(true)
}

// afterGetState handles a GET_STATE request from the chaincode.
func (handler *Handler) afterGetState(e *fsm.Event, state string) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
550
	chaincodeLogger.Debugf("[%s]Received %s, invoking get state from ledger", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_STATE)
551
552
553
554
555

	// Query ledger for state
	handler.handleGetState(msg)
}

556
557
558
559
560
561
562
563
564
565
566
567
// is this a txid for which there is a valid txsim
func (handler *Handler) isValidTxSim(txid string, fmtStr string, args ...interface{}) (*transactionContext, *pb.ChaincodeMessage) {
	txContext := handler.getTxContext(txid)
	if txContext == nil || txContext.txsimulator == nil {
		// Send error msg back to chaincode. No ledger context
		errStr := fmt.Sprintf(fmtStr, args...)
		chaincodeLogger.Errorf(errStr)
		return nil, &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(errStr), Txid: txid}
	}
	return txContext, nil
}

568
569
570
571
572
573
// Handles query to ledger to get state
func (handler *Handler) handleGetState(msg *pb.ChaincodeMessage) {
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the afterGetState function is exited. Interesting bug fix!!
	go func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
574
575
		// Check if this is the unique state request from this chaincode txid
		uniqueReq := handler.createTXIDEntry(msg.Txid)
576
577
		if !uniqueReq {
			// Drop this request
Gabor Hosszu's avatar
Gabor Hosszu committed
578
			chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.")
579
580
581
582
			return
		}

		var serialSendMsg *pb.ChaincodeMessage
583
584
585
		var txContext *transactionContext
		txContext, serialSendMsg = handler.isValidTxSim(msg.Txid,
			"[%s]No ledger context for GetState. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
586
587

		defer func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
588
			handler.deleteTXIDEntry(msg.Txid)
589
590
591
592
			if chaincodeLogger.IsEnabledFor(logging.DEBUG) {
				chaincodeLogger.Debugf("[%s]handleGetState serial send %s",
					shorttxid(serialSendMsg.Txid), serialSendMsg.Type)
			}
593
			handler.serialSendAsync(serialSendMsg, nil)
594
595
		}()

596
597
598
		if txContext == nil {
			return
		}
599

600
		key := string(msg.Payload)
601
		chaincodeID := handler.getCCRootName()
602
603
604
605
		if chaincodeLogger.IsEnabledFor(logging.DEBUG) {
			chaincodeLogger.Debugf("[%s] getting state for chaincode %s, key %s, channel %s",
				shorttxid(msg.Txid), chaincodeID, key, txContext.chainID)
		}
606

607
608
		var res []byte
		var err error
609
		res, err = txContext.txsimulator.GetState(chaincodeID, key)
610

611
612
613
		if err != nil {
			// Send error msg back to chaincode. GetState will not trigger event
			payload := []byte(err.Error())
614
615
			chaincodeLogger.Errorf("[%s]Failed to get chaincode state(%s). Sending %s",
				shorttxid(msg.Txid), err, pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
616
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
617
		} else if res == nil {
618
			//The state object being requested does not exist
619
620
			chaincodeLogger.Debugf("[%s]No state associated with key: %s. Sending %s with an empty payload",
				shorttxid(msg.Txid), key, pb.ChaincodeMessage_RESPONSE)
Gabor Hosszu's avatar
Gabor Hosszu committed
621
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid}
622
		} else {
623
			// Send response msg back to chaincode. GetState will not trigger event
624
625
626
			if chaincodeLogger.IsEnabledFor(logging.DEBUG) {
				chaincodeLogger.Debugf("[%s]Got state. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RESPONSE)
			}
627
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid}
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
		}

	}()
}

const maxRangeQueryStateLimit = 100

// afterRangeQueryState handles a RANGE_QUERY_STATE request from the chaincode.
func (handler *Handler) afterRangeQueryState(e *fsm.Event, state string) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("Received %s, invoking get state from ledger", pb.ChaincodeMessage_RANGE_QUERY_STATE)

	// Query ledger for state
	handler.handleRangeQueryState(msg)
	chaincodeLogger.Debug("Exiting GET_STATE")
}

// Handles query to ledger to rage query state
func (handler *Handler) handleRangeQueryState(msg *pb.ChaincodeMessage) {
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the afterRangeQueryState function is exited. Interesting bug fix!!
	go func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
655
656
		// Check if this is the unique state request from this chaincode txid
		uniqueReq := handler.createTXIDEntry(msg.Txid)
657
658
		if !uniqueReq {
			// Drop this request
Gabor Hosszu's avatar
Gabor Hosszu committed
659
			chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.")
660
661
662
663
664
665
			return
		}

		var serialSendMsg *pb.ChaincodeMessage

		defer func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
666
667
			handler.deleteTXIDEntry(msg.Txid)
			chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type)
668
			handler.serialSendAsync(serialSendMsg, nil)
669
670
671
672
673
674
675
		}()

		rangeQueryState := &pb.RangeQueryState{}
		unmarshalErr := proto.Unmarshal(msg.Payload, rangeQueryState)
		if unmarshalErr != nil {
			payload := []byte(unmarshalErr.Error())
			chaincodeLogger.Errorf("Failed to unmarshall range query request. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
676
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
677
678
679
			return
		}

680
		iterID := util.GenerateUUID()
681

682
683
684
685
686
687
		var txContext *transactionContext

		txContext, serialSendMsg = handler.isValidTxSim(msg.Txid, "[%s]No ledger context for RangeQueryState. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
		if txContext == nil {
			return
		}
688
		chaincodeID := handler.getCCRootName()
689

690
		rangeIter, err := txContext.txsimulator.GetStateRangeScanIterator(chaincodeID, rangeQueryState.StartKey, rangeQueryState.EndKey)
691
692
693
694
		if err != nil {
			// Send error msg back to chaincode. GetState will not trigger event
			payload := []byte(err.Error())
			chaincodeLogger.Errorf("Failed to get ledger scan iterator. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
695
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
696
697
698
			return
		}

699
		handler.putQueryIterator(txContext, iterID, rangeIter)
700

701
		var keysAndValues []*pb.QueryStateKeyValue
702
		var i = uint32(0)
703
		var qresult commonledger.QueryResult
manish's avatar
manish committed
704
		for ; i < maxRangeQueryStateLimit; i++ {
705
			qresult, err = rangeIter.Next()
706
707
708
709
			if err != nil {
				chaincodeLogger.Errorf("Failed to get query result from iterator. Sending %s", pb.ChaincodeMessage_ERROR)
				return
			}
manish's avatar
manish committed
710
711
712
			if qresult == nil {
				break
			}
713
			kv := qresult.(*ledger.KV)
714
			keyAndValue := pb.QueryStateKeyValue{Key: kv.Key, Value: kv.Value}
715
716
717
			keysAndValues = append(keysAndValues, &keyAndValue)
		}

manish's avatar
manish committed
718
		if qresult != nil {
719
			rangeIter.Close()
720
			handler.deleteQueryIterator(txContext, iterID)
721
722
		}

723
		payload := &pb.QueryStateResponse{KeysAndValues: keysAndValues, HasMore: qresult != nil, ID: iterID}
724
725
726
		payloadBytes, err := proto.Marshal(payload)
		if err != nil {
			rangeIter.Close()
727
			handler.deleteQueryIterator(txContext, iterID)
728
729
730
731

			// Send error msg back to chaincode. GetState will not trigger event
			payload := []byte(err.Error())
			chaincodeLogger.Errorf("Failed marshall resopnse. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
732
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
733
734
735
736
			return
		}

		chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE)
Gabor Hosszu's avatar
Gabor Hosszu committed
737
		serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid}
738
739
740
741

	}()
}

denyeart's avatar
denyeart committed
742
// afterQueryStateNext handles a QUERY_STATE_NEXT request from the chaincode.
743
func (handler *Handler) afterQueryStateNext(e *fsm.Event, state string) {
744
745
746
747
748
749
750
751
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("Received %s, invoking get state from ledger", pb.ChaincodeMessage_RANGE_QUERY_STATE)

	// Query ledger for state
752
	handler.handleQueryStateNext(msg)
denyeart's avatar
denyeart committed
753
	chaincodeLogger.Debug("Exiting QUERY_STATE_NEXT")
754
755
}

denyeart's avatar
denyeart committed
756
// Handles query to ledger for query state next
757
func (handler *Handler) handleQueryStateNext(msg *pb.ChaincodeMessage) {
758
759
760
761
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the afterRangeQueryState function is exited. Interesting bug fix!!
	go func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
762
763
		// Check if this is the unique state request from this chaincode txid
		uniqueReq := handler.createTXIDEntry(msg.Txid)
764
765
		if !uniqueReq {
			// Drop this request
Gabor Hosszu's avatar
Gabor Hosszu committed
766
			chaincodeLogger.Debug("Another state request pending for this Txid. Cannot process.")
767
768
769
770
771
772
			return
		}

		var serialSendMsg *pb.ChaincodeMessage

		defer func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
773
774
			handler.deleteTXIDEntry(msg.Txid)
			chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type)
775
			handler.serialSendAsync(serialSendMsg, nil)
776
777
		}()

778
779
		queryStateNext := &pb.QueryStateNext{}
		unmarshalErr := proto.Unmarshal(msg.Payload, queryStateNext)
780
781
		if unmarshalErr != nil {
			payload := []byte(unmarshalErr.Error())
denyeart's avatar
denyeart committed
782
			chaincodeLogger.Errorf("Failed to unmarshall state next query request. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
783
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
784
785
786
			return
		}

Gabor Hosszu's avatar
Gabor Hosszu committed
787
		txContext := handler.getTxContext(msg.Txid)
denyeart's avatar
denyeart committed
788
		queryIter := handler.getQueryIterator(txContext, queryStateNext.ID)
789

denyeart's avatar
denyeart committed
790
791
792
		if queryIter == nil {
			payload := []byte("query iterator not found")
			chaincodeLogger.Errorf("query iterator not found. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
793
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
794
795
796
			return
		}

797
		var keysAndValues []*pb.QueryStateKeyValue
798
		var i = uint32(0)
manish's avatar
manish committed
799

800
		var qresult commonledger.QueryResult
manish's avatar
manish committed
801
802
		var err error
		for ; i < maxRangeQueryStateLimit; i++ {
denyeart's avatar
denyeart committed
803
			qresult, err = queryIter.Next()
804
805
806
807
			if err != nil {
				chaincodeLogger.Errorf("Failed to get query result from iterator. Sending %s", pb.ChaincodeMessage_ERROR)
				return
			}
manish's avatar
manish committed
808
809
810
			if qresult != nil {
				break
			}
811
			kv := qresult.(*ledger.KV)
812
			keyAndValue := pb.QueryStateKeyValue{Key: kv.Key, Value: kv.Value}
813
814
815
			keysAndValues = append(keysAndValues, &keyAndValue)
		}

manish's avatar
manish committed
816
		if qresult != nil {
denyeart's avatar
denyeart committed
817
			queryIter.Close()
818
			handler.deleteQueryIterator(txContext, queryStateNext.ID)
819
820
		}

821
		payload := &pb.QueryStateResponse{KeysAndValues: keysAndValues, HasMore: qresult != nil, ID: queryStateNext.ID}
822
823
		payloadBytes, err := proto.Marshal(payload)
		if err != nil {
denyeart's avatar
denyeart committed
824
			queryIter.Close()
825
			handler.deleteQueryIterator(txContext, queryStateNext.ID)
826
827
828
829

			// Send error msg back to chaincode. GetState will not trigger event
			payload := []byte(err.Error())
			chaincodeLogger.Errorf("Failed marshall resopnse. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
830
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
831
832
833
834
			return
		}

		chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE)
Gabor Hosszu's avatar
Gabor Hosszu committed
835
		serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid}
836
837
838
839

	}()
}

denyeart's avatar
denyeart committed
840
// afterRangeQueryState handles a QUERY_STATE_CLOSE request from the chaincode.
841
func (handler *Handler) afterQueryStateClose(e *fsm.Event, state string) {
842
843
844
845
846
847
848
849
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("Received %s, invoking get state from ledger", pb.ChaincodeMessage_RANGE_QUERY_STATE)

	// Query ledger for state
850
	handler.handleQueryStateClose(msg)
denyeart's avatar
denyeart committed
851
	chaincodeLogger.Debug("Exiting QUERY_STATE_CLOSE")
852
853
854
}

// Handles the closing of a state iterator
855
func (handler *Handler) handleQueryStateClose(msg *pb.ChaincodeMessage) {
856
857
858
859
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the afterRangeQueryState function is exited. Interesting bug fix!!
	go func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
860
861
		// Check if this is the unique state request from this chaincode txid
		uniqueReq := handler.createTXIDEntry(msg.Txid)
862
863
		if !uniqueReq {
			// Drop this request
Gabor Hosszu's avatar
Gabor Hosszu committed
864
			chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.")
865
866
867
868
869
870
			return
		}

		var serialSendMsg *pb.ChaincodeMessage

		defer func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
871
872
			handler.deleteTXIDEntry(msg.Txid)
			chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type)
873
			handler.serialSendAsync(serialSendMsg, nil)
874
875
		}()

876
877
		queryStateClose := &pb.QueryStateClose{}
		unmarshalErr := proto.Unmarshal(msg.Payload, queryStateClose)
878
879
		if unmarshalErr != nil {
			payload := []byte(unmarshalErr.Error())
denyeart's avatar
denyeart committed
880
			chaincodeLogger.Errorf("Failed to unmarshall state query close request. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
881
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
882
883
884
			return
		}

Gabor Hosszu's avatar
Gabor Hosszu committed
885
		txContext := handler.getTxContext(msg.Txid)
886
		iter := handler.getQueryIterator(txContext, queryStateClose.ID)
887
888
		if iter != nil {
			iter.Close()
889
			handler.deleteQueryIterator(txContext, queryStateClose.ID)
890
891
		}

892
		payload := &pb.QueryStateResponse{HasMore: false, ID: queryStateClose.ID}
893
894
895
896
897
898
		payloadBytes, err := proto.Marshal(payload)
		if err != nil {

			// Send error msg back to chaincode. GetState will not trigger event
			payload := []byte(err.Error())
			chaincodeLogger.Errorf("Failed marshall resopnse. Sending %s", pb.ChaincodeMessage_ERROR)
Gabor Hosszu's avatar
Gabor Hosszu committed
899
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
900
901
902
903
			return
		}

		chaincodeLogger.Debugf("Closed. Sending %s", pb.ChaincodeMessage_RESPONSE)
Gabor Hosszu's avatar
Gabor Hosszu committed
904
		serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid}
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
const maxExecuteQueryStateLimit = 100

// afterExecuteQueryState handles a EXECUTE_QUERY_STATE request from the chaincode.
func (handler *Handler) afterExecuteQueryState(e *fsm.Event, state string) {
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
	chaincodeLogger.Debugf("Received %s, invoking get state from ledger", pb.ChaincodeMessage_EXECUTE_QUERY_STATE)

	// Query ledger for state
	handler.handleExecuteQueryState(msg)
	chaincodeLogger.Debug("Exiting EXECUTE_QUERY_STATE")
}

// Handles query to ledger to execute query state
func (handler *Handler) handleExecuteQueryState(msg *pb.ChaincodeMessage) {
	// The defer followed by triggering a go routine dance is needed to ensure that the previous state transition
	// is completed before the next one is triggered. The previous state transition is deemed complete only when
	// the afterQueryState function is exited. Interesting bug fix!!
	go func() {
		// Check if this is the unique state request from this chaincode txid
		uniqueReq := handler.createTXIDEntry(msg.Txid)
		if !uniqueReq {
			// Drop this request
			chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.")
			return
		}

		var serialSendMsg *pb.ChaincodeMessage

		defer func() {
			handler.deleteTXIDEntry(msg.Txid)
			chaincodeLogger.Debugf("[%s]handleExecuteQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type)
			handler.serialSendAsync(serialSendMsg, nil)
		}()

		executeQueryState := &pb.ExecuteQueryState{}
		unmarshalErr := proto.Unmarshal(msg.Payload, executeQueryState)
		if unmarshalErr != nil {
			payload := []byte(unmarshalErr.Error())
denyeart's avatar
denyeart committed
951
			chaincodeLogger.Errorf("Failed to unmarshall query request. Sending %s", pb.ChaincodeMessage_ERROR)
952
953
954
955
956
957
958
959
960
961
962
963
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
			return
		}

		iterID := util.GenerateUUID()

		var txContext *transactionContext

		txContext, serialSendMsg = handler.isValidTxSim(msg.Txid, "[%s]No ledger context for ExecuteQueryState. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
		if txContext == nil {
			return
		}
denyeart's avatar
denyeart committed
964

965
966
967
968
969
970
971
972
973
974
975
976
977
		executeIter, err := txContext.txsimulator.ExecuteQuery(executeQueryState.Query)
		if err != nil {
			// Send error msg back to chaincode. GetState will not trigger event
			payload := []byte(err.Error())
			chaincodeLogger.Errorf("Failed to get ledger scan iterator. Sending %s", pb.ChaincodeMessage_ERROR)
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
			return
		}

		handler.putQueryIterator(txContext, iterID, executeIter)

		var keysAndValues []*pb.QueryStateKeyValue
		var i = uint32(0)
978
		var qresult commonledger.QueryResult
979
		for ; i < maxExecuteQueryStateLimit; i++ {
980
			qresult, err = executeIter.Next()
981
982
983
984
985
986
987
			if err != nil {
				chaincodeLogger.Errorf("Failed to get query result from iterator. Sending %s", pb.ChaincodeMessage_ERROR)
				return
			}
			if qresult == nil {
				break
			}
denyeart's avatar
denyeart committed
988
989
			queryRecord := qresult.(*ledger.QueryRecord)
			keyAndValue := pb.QueryStateKeyValue{Key: queryRecord.Key, Value: queryRecord.Record}
990
991
992
993
994
995
996
997
			keysAndValues = append(keysAndValues, &keyAndValue)
		}

		if qresult != nil {
			executeIter.Close()
			handler.deleteQueryIterator(txContext, iterID)
		}

998
		var payloadBytes []byte
999
		payload := &pb.QueryStateResponse{KeysAndValues: keysAndValues, HasMore: qresult != nil, ID: iterID}
1000
		payloadBytes, err = proto.Marshal(payload)
For faster browsing, not all history is shown. View entire blame