handler.go 59.4 KB
Newer Older
Gabor Hosszu's avatar
Gabor Hosszu committed
1001
		uniqueReq := handler.createTXIDEntry(msg.Txid)
1002
1003
		if !uniqueReq {
			// Drop this request
Gabor Hosszu's avatar
Gabor Hosszu committed
1004
			chaincodeLogger.Debug("Another request pending for this Txid. Cannot process.")
1005
1006
1007
1008
1009
1010
			return
		}

		var triggerNextStateMsg *pb.ChaincodeMessage

		defer func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
1011
1012
			handler.deleteTXIDEntry(msg.Txid)
			chaincodeLogger.Debugf("[%s]enterBusyState trigger event %s", shorttxid(triggerNextStateMsg.Txid), triggerNextStateMsg.Type)
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
			handler.triggerNextState(triggerNextStateMsg, true)
		}()

		chaincodeID := handler.ChaincodeID.Name
		var err error
		var res []byte

		if msg.Type.String() == pb.ChaincodeMessage_PUT_STATE.String() {
			putStateInfo := &pb.PutStateInfo{}
			unmarshalErr := proto.Unmarshal(msg.Payload, putStateInfo)
			if unmarshalErr != nil {
				payload := []byte(unmarshalErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1025
1026
				chaincodeLogger.Debugf("[%s]Unable to decipher payload. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
				triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1027
1028
1029
1030
1031
				return
			}

			var pVal []byte
			// Encrypt the data if the confidential is enabled
Gabor Hosszu's avatar
Gabor Hosszu committed
1032
			if pVal, err = handler.encrypt(msg.Txid, putStateInfo.Value); err == nil {
1033
				// Invoke ledger to put state
1034
				txContext := handler.getTxContext(msg.Txid)
1035
				err = txContext.txsimulator.SetState(chaincodeID, putStateInfo.Key, pVal)
1036

1037
1038
1039
1040
			}
		} else if msg.Type.String() == pb.ChaincodeMessage_DEL_STATE.String() {
			// Invoke ledger to delete state
			key := string(msg.Payload)
1041
			txContext := handler.getTxContext(msg.Txid)
1042
			err = txContext.txsimulator.DeleteState(chaincodeID, key)
1043
1044
		} else if msg.Type.String() == pb.ChaincodeMessage_INVOKE_CHAINCODE.String() {
			//check and prohibit C-call-C for CONFIDENTIAL txs
1045
1046
1047
			chaincodeLogger.Debugf("[%s] C-call-C", shorttxid(msg.Txid))

			if triggerNextStateMsg = handler.canCallChaincode(msg.Txid, false); triggerNextStateMsg != nil {
1048
1049
1050
1051
1052
1053
				return
			}
			chaincodeSpec := &pb.ChaincodeSpec{}
			unmarshalErr := proto.Unmarshal(msg.Payload, chaincodeSpec)
			if unmarshalErr != nil {
				payload := []byte(unmarshalErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1054
1055
				chaincodeLogger.Debugf("[%s]Unable to decipher payload. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
				triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1056
1057
1058
1059
1060
				return
			}

			// Get the chaincodeID to invoke
			newChaincodeID := chaincodeSpec.ChaincodeID.Name
1061
			chaincodeLogger.Debugf("[%s] C-call-C %s", shorttxid(msg.Txid), newChaincodeID)
1062

1063
1064
1065
1066
			txContext := handler.getTxContext(msg.Txid)
			ctxt := context.Background()
			ctxt = context.WithValue(ctxt, TXSimulatorKey, txContext.txsimulator)

1067
1068
			// Create the transaction object
			chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: chaincodeSpec}
Gabor Hosszu's avatar
Gabor Hosszu committed
1069
			transaction, _ := pb.NewChaincodeExecute(chaincodeInvocationSpec, msg.Txid, pb.Transaction_CHAINCODE_INVOKE)
1070

1071
1072
			// Launch the new chaincode if not already running
			_, chaincodeInput, launchErr := handler.chaincodeSupport.Launch(ctxt, transaction)
1073
1074
			if launchErr != nil {
				payload := []byte(launchErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1075
1076
				chaincodeLogger.Debugf("[%s]Failed to launch invoked chaincode. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
				triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1077
1078
1079
1080
1081
1082
				return
			}

			// TODO: Need to handle timeout correctly
			timeout := time.Duration(30000) * time.Millisecond

Gabor Hosszu's avatar
Gabor Hosszu committed
1083
			ccMsg, _ := createTransactionMessage(transaction.Txid, chaincodeInput)
1084
1085
1086

			// Execute the chaincode
			//NOTE: when confidential C-call-C is understood, transaction should have the correct sec context for enc/dec
1087
			response, execErr := handler.chaincodeSupport.Execute(ctxt, newChaincodeID, ccMsg, timeout, transaction)
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101

			//payload is marshalled and send to the calling chaincode's shim which unmarshals and
			//sends it to chaincode
			res = nil
			if execErr != nil {
				err = execErr
			} else {
				res, err = proto.Marshal(response)
			}
		}

		if err != nil {
			// Send error msg back to chaincode and trigger event
			payload := []byte(err.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1102
1103
			chaincodeLogger.Errorf("[%s]Failed to handle %s. Sending %s", shorttxid(msg.Txid), msg.Type.String(), pb.ChaincodeMessage_ERROR)
			triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1104
1105
1106
1107
			return
		}

		// Send response msg back to chaincode.
Gabor Hosszu's avatar
Gabor Hosszu committed
1108
1109
		chaincodeLogger.Debugf("[%s]Completed %s. Sending %s", shorttxid(msg.Txid), msg.Type.String(), pb.ChaincodeMessage_RESPONSE)
		triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid}
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
	}()
}

func (handler *Handler) enterEstablishedState(e *fsm.Event, state string) {
	handler.notifyDuringStartup(true)
}

func (handler *Handler) enterInitState(e *fsm.Event, state string) {
	ccMsg, ok := e.Args[0].(*pb.ChaincodeMessage)
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
1123
	chaincodeLogger.Debugf("[%s]Entered state %s", shorttxid(ccMsg.Txid), state)
1124
1125
1126
	//very first time entering init state from established, send message to chaincode
	if ccMsg.Type == pb.ChaincodeMessage_INIT {
		// Mark isTransaction to allow put/del state and invoke other chaincodes
Gabor Hosszu's avatar
Gabor Hosszu committed
1127
		handler.markIsTransaction(ccMsg.Txid, true)
1128
		if err := handler.serialSend(ccMsg); err != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1129
			errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(fmt.Sprintf("Error sending %s: %s", pb.ChaincodeMessage_INIT, err)), Txid: ccMsg.Txid}
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
			handler.notify(errMsg)
		}
	}
}

func (handler *Handler) enterReadyState(e *fsm.Event, state string) {
	// Now notify
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
	//we have to encrypt chaincode event payload. We cannot encrypt event type as
	//it is needed by the event system to filter clients by
	if ok && msg.ChaincodeEvent != nil && msg.ChaincodeEvent.Payload != nil {
		var err error
Gabor Hosszu's avatar
Gabor Hosszu committed
1142
1143
		if msg.Payload, err = handler.encrypt(msg.Txid, msg.Payload); nil != err {
			chaincodeLogger.Errorf("[%s]Failed to encrypt chaincode event payload", msg.Txid)
1144
1145
1146
1147
			msg.Payload = []byte(fmt.Sprintf("Failed to encrypt chaincode event payload %s", err.Error()))
			msg.Type = pb.ChaincodeMessage_ERROR
		}
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
1148
	handler.deleteIsTransaction(msg.Txid)
1149
1150
1151
1152
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
1153
	chaincodeLogger.Debugf("[%s]Entered state %s", shorttxid(msg.Txid), state)
1154
1155
1156
1157
1158
1159
1160
	handler.notify(msg)
}

func (handler *Handler) enterEndState(e *fsm.Event, state string) {
	defer handler.deregister()
	// Now notify
	msg, ok := e.Args[0].(*pb.ChaincodeMessage)
Gabor Hosszu's avatar
Gabor Hosszu committed
1161
	handler.deleteIsTransaction(msg.Txid)
1162
1163
1164
1165
	if !ok {
		e.Cancel(fmt.Errorf("Received unexpected message type"))
		return
	}
Gabor Hosszu's avatar
Gabor Hosszu committed
1166
	chaincodeLogger.Debugf("[%s]Entered state %s", shorttxid(msg.Txid), state)
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
	handler.notify(msg)
	e.Cancel(fmt.Errorf("Entered end state"))
}

func (handler *Handler) cloneTx(tx *pb.Transaction) (*pb.Transaction, error) {
	raw, err := proto.Marshal(tx)
	if err != nil {
		chaincodeLogger.Errorf("Failed marshalling transaction [%s].", err.Error())
		return nil, err
	}

	clone := &pb.Transaction{}
	err = proto.Unmarshal(raw, clone)
	if err != nil {
		chaincodeLogger.Errorf("Failed unmarshalling transaction [%s].", err.Error())
		return nil, err
	}

	return clone, nil
}

func (handler *Handler) initializeSecContext(tx, depTx *pb.Transaction) error {
	//set deploy transaction on the handler
	if depTx != nil {
		//we are given a deep clone of depTx.. Just use it
		handler.deployTXSecContext = depTx
	} else {
		//nil depTx => tx is a deploy transaction, clone it
		var err error
		handler.deployTXSecContext, err = handler.cloneTx(tx)
		if err != nil {
			return fmt.Errorf("Failed to clone transaction: %s\n", err)
		}
	}

	//don't need the payload which is not useful and rather large
	handler.deployTXSecContext.Payload = nil

	//we need to null out path from depTx as invoke or queries don't have it
	cID := &pb.ChaincodeID{}
	err := proto.Unmarshal(handler.deployTXSecContext.ChaincodeID, cID)
	if err != nil {
		return fmt.Errorf("Failed to unmarshall : %s\n", err)
	}

	cID.Path = ""
	data, err := proto.Marshal(cID)
	if err != nil {
		return fmt.Errorf("Failed to marshall : %s\n", err)
	}

	handler.deployTXSecContext.ChaincodeID = data

	return nil
}

1223
func (handler *Handler) setChaincodeSecurityContext(tx, depTx *pb.Transaction, msg *pb.ChaincodeMessage) error {
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
	chaincodeLogger.Debug("setting chaincode security context...")
	if msg.SecurityContext == nil {
		msg.SecurityContext = &pb.ChaincodeSecurityContext{}
	}
	if tx != nil {
		chaincodeLogger.Debug("setting chaincode security context. Transaction different from nil")
		chaincodeLogger.Debugf("setting chaincode security context. Metadata [% x]", tx.Metadata)

		msg.SecurityContext.CallerCert = tx.Cert
		msg.SecurityContext.CallerSign = tx.Signature
		binding, err := handler.getSecurityBinding(tx)
		if err != nil {
			chaincodeLogger.Errorf("Failed getting binding [%s]", err)
			return err
		}
		msg.SecurityContext.Binding = binding
		msg.SecurityContext.Metadata = tx.Metadata

1242
1243
1244
1245
1246
		cis := &pb.ChaincodeInvocationSpec{}
		if err := proto.Unmarshal(tx.Payload, cis); err != nil {
			chaincodeLogger.Errorf("Failed getting payload [%s]", err)
			return err
		}
1247

1248
1249
1250
1251
		ctorMsgRaw, err := proto.Marshal(cis.ChaincodeSpec.GetCtorMsg())
		if err != nil {
			chaincodeLogger.Errorf("Failed getting ctorMsgRaw [%s]", err)
			return err
1252
		}
1253

1254
1255
1256
1257
1258
1259
1260
		msg.SecurityContext.Payload = ctorMsgRaw
		// TODO: add deploy metadata
		if depTx != nil {
			msg.SecurityContext.ParentMetadata = depTx.Metadata
		} else {
			msg.SecurityContext.ParentMetadata = handler.deployTXSecContext.Metadata
		}
1261
		msg.SecurityContext.Payload = ctorMsgRaw
1262
1263
1264
1265
1266
1267
1268
		msg.SecurityContext.TxTimestamp = tx.Timestamp
	}
	return nil
}

//if initArgs is set (should be for "deploy" only) move to Init
//else move to ready
1269
func (handler *Handler) initOrReady(ctxt context.Context, txid string, initArgs [][]byte, tx *pb.Transaction, depTx *pb.Transaction) (chan *pb.ChaincodeMessage, error) {
1270
1271
1272
	var ccMsg *pb.ChaincodeMessage
	var send bool

1273
	txctx, funcErr := handler.createTxContext(ctxt, txid, tx)
1274
1275
1276
1277
1278
1279
	if funcErr != nil {
		return nil, funcErr
	}

	notfy := txctx.responseNotifier

1280
	if initArgs != nil {
1281
		chaincodeLogger.Debug("sending INIT")
1282
		funcArgsMsg := &pb.ChaincodeInput{Args: initArgs}
1283
1284
		var payload []byte
		if payload, funcErr = proto.Marshal(funcArgsMsg); funcErr != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1285
			handler.deleteTxContext(txid)
1286
1287
			return nil, fmt.Errorf("Failed to marshall %s : %s\n", ccMsg.Type.String(), funcErr)
		}
Gabor Hosszu's avatar
Gabor Hosszu committed
1288
		ccMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INIT, Payload: payload, Txid: txid}
1289
1290
1291
		send = false
	} else {
		chaincodeLogger.Debug("sending READY")
Gabor Hosszu's avatar
Gabor Hosszu committed
1292
		ccMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_READY, Txid: txid}
1293
1294
1295
1296
		send = true
	}

	if err := handler.initializeSecContext(tx, depTx); err != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1297
		handler.deleteTxContext(txid)
1298
1299
1300
1301
		return nil, err
	}

	//if security is disabled the context elements will just be nil
1302
	if err := handler.setChaincodeSecurityContext(tx, depTx, ccMsg); err != nil {
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
		return nil, err
	}

	handler.triggerNextState(ccMsg, send)

	return notfy, nil
}

// Handles request to query another chaincode
func (handler *Handler) handleQueryChaincode(msg *pb.ChaincodeMessage) {
	go func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
1314
1315
		// Check if this is the unique request from this chaincode txid
		uniqueReq := handler.createTXIDEntry(msg.Txid)
1316
1317
		if !uniqueReq {
			// Drop this request
Gabor Hosszu's avatar
Gabor Hosszu committed
1318
			chaincodeLogger.Debugf("[%s]Another request pending for this Txid. Cannot process.", shorttxid(msg.Txid))
1319
1320
1321
1322
1323
1324
			return
		}

		var serialSendMsg *pb.ChaincodeMessage

		defer func() {
Gabor Hosszu's avatar
Gabor Hosszu committed
1325
			handler.deleteTXIDEntry(msg.Txid)
1326
1327
1328
1329
			handler.serialSend(serialSendMsg)
		}()

		//check and prohibit C-call-C for CONFIDENTIAL txs
1330
		if serialSendMsg = handler.canCallChaincode(msg.Txid, true); serialSendMsg != nil {
1331
1332
1333
1334
1335
1336
1337
			return
		}

		chaincodeSpec := &pb.ChaincodeSpec{}
		unmarshalErr := proto.Unmarshal(msg.Payload, chaincodeSpec)
		if unmarshalErr != nil {
			payload := []byte(unmarshalErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1338
1339
			chaincodeLogger.Debugf("[%s]Unable to decipher payload. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1340
1341
1342
1343
1344
1345
1346
1347
			return
		}

		// Get the chaincodeID to invoke
		newChaincodeID := chaincodeSpec.ChaincodeID.Name

		// Create the transaction object
		chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: chaincodeSpec}
Gabor Hosszu's avatar
Gabor Hosszu committed
1348
		transaction, _ := pb.NewChaincodeExecute(chaincodeInvocationSpec, msg.Txid, pb.Transaction_CHAINCODE_QUERY)
1349

1350
1351
1352
		txContext := handler.getTxContext(msg.Txid)
		ctxt := context.Background()
		ctxt = context.WithValue(ctxt, TXSimulatorKey, txContext.txsimulator)
1353

1354
		// Launch the new chaincode if not already running
1355
		_, chaincodeInput, launchErr := handler.chaincodeSupport.Launch(ctxt, transaction)
1356
1357
		if launchErr != nil {
			payload := []byte(launchErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1358
1359
			chaincodeLogger.Debugf("[%s]Failed to launch invoked chaincode. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1360
1361
1362
1363
1364
1365
			return
		}

		// TODO: Need to handle timeout correctly
		timeout := time.Duration(30000) * time.Millisecond

Gabor Hosszu's avatar
Gabor Hosszu committed
1366
		ccMsg, _ := createQueryMessage(transaction.Txid, chaincodeInput)
1367
1368
1369

		// Query the chaincode
		//NOTE: when confidential C-call-C is understood, transaction should have the correct sec context for enc/dec
1370
		response, execErr := handler.chaincodeSupport.Execute(ctxt, newChaincodeID, ccMsg, timeout, transaction)
1371
1372
1373
1374

		if execErr != nil {
			// Send error msg back to chaincode and trigger event
			payload := []byte(execErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1375
1376
			chaincodeLogger.Debugf("[%s]Failed to handle %s. Sending %s", shorttxid(msg.Txid), msg.Type.String(), pb.ChaincodeMessage_ERROR)
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1377
1378
1379
1380
1381
1382
1383
1384
			return
		}

		// Send response msg back to chaincode.

		//this is need to send the payload directly to calling chaincode without
		//interpreting (in particular, don't look for errors)
		if respBytes, err := proto.Marshal(response); err != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1385
			chaincodeLogger.Errorf("[%s]Error marshaling response. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR)
1386
			payload := []byte(execErr.Error())
Gabor Hosszu's avatar
Gabor Hosszu committed
1387
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1388
		} else {
Gabor Hosszu's avatar
Gabor Hosszu committed
1389
1390
			chaincodeLogger.Debugf("[%s]Completed %s. Sending %s", shorttxid(msg.Txid), msg.Type.String(), pb.ChaincodeMessage_RESPONSE)
			serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: respBytes, Txid: msg.Txid}
1391
1392
1393
1394
1395
1396
		}
	}()
}

// HandleMessage implementation of MessageHandler interface.  Peer's handling of Chaincode messages.
func (handler *Handler) HandleMessage(msg *pb.ChaincodeMessage) error {
Gabor Hosszu's avatar
Gabor Hosszu committed
1397
	chaincodeLogger.Debugf("[%s]Handling ChaincodeMessage of type: %s in state %s", shorttxid(msg.Txid), msg.Type, handler.FSM.Current())
1398
1399
1400

	//QUERY_COMPLETED message can happen ONLY for Transaction_QUERY (stateless)
	if msg.Type == pb.ChaincodeMessage_QUERY_COMPLETED {
Gabor Hosszu's avatar
Gabor Hosszu committed
1401
1402
		chaincodeLogger.Debugf("[%s]HandleMessage- QUERY_COMPLETED. Notify", msg.Txid)
		handler.deleteIsTransaction(msg.Txid)
1403
		var err error
Gabor Hosszu's avatar
Gabor Hosszu committed
1404
1405
		if msg.Payload, err = handler.encrypt(msg.Txid, msg.Payload); nil != err {
			chaincodeLogger.Errorf("[%s]Failed to encrypt query result %s", msg.Txid, string(msg.Payload))
1406
1407
1408
1409
1410
1411
			msg.Payload = []byte(fmt.Sprintf("Failed to encrypt query result %s", err.Error()))
			msg.Type = pb.ChaincodeMessage_QUERY_ERROR
		}
		handler.notify(msg)
		return nil
	} else if msg.Type == pb.ChaincodeMessage_QUERY_ERROR {
Gabor Hosszu's avatar
Gabor Hosszu committed
1412
1413
		chaincodeLogger.Debugf("[%s]HandleMessage- QUERY_ERROR (%s). Notify", msg.Txid, string(msg.Payload))
		handler.deleteIsTransaction(msg.Txid)
1414
1415
1416
1417
		handler.notify(msg)
		return nil
	} else if msg.Type == pb.ChaincodeMessage_INVOKE_QUERY {
		// Received request to query another chaincode from shim
Gabor Hosszu's avatar
Gabor Hosszu committed
1418
		chaincodeLogger.Debugf("[%s]HandleMessage- Received request to query another chaincode", msg.Txid)
1419
1420
1421
1422
1423
1424
		handler.handleQueryChaincode(msg)
		return nil
	}
	if handler.FSM.Cannot(msg.Type.String()) {
		// Check if this is a request from validator in query context
		if msg.Type.String() == pb.ChaincodeMessage_PUT_STATE.String() || msg.Type.String() == pb.ChaincodeMessage_DEL_STATE.String() || msg.Type.String() == pb.ChaincodeMessage_INVOKE_CHAINCODE.String() {
Gabor Hosszu's avatar
Gabor Hosszu committed
1425
1426
1427
1428
1429
			// Check if this TXID is a transaction
			if !handler.getIsTransaction(msg.Txid) {
				payload := []byte(fmt.Sprintf("[%s]Cannot handle %s in query context", msg.Txid, msg.Type.String()))
				chaincodeLogger.Errorf("[%s]Cannot handle %s in query context. Sending %s", msg.Txid, msg.Type.String(), pb.ChaincodeMessage_ERROR)
				errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid}
1430
1431
1432
1433
1434
1435
				handler.serialSend(errMsg)
				return fmt.Errorf("Cannot handle %s in query context", msg.Type.String())
			}
		}

		// Other errors
Gabor Hosszu's avatar
Gabor Hosszu committed
1436
		return fmt.Errorf("[%s]Chaincode handler validator FSM cannot handle message (%s) with payload size (%d) while in state: %s", msg.Txid, msg.Type.String(), len(msg.Payload), handler.FSM.Current())
1437
1438
1439
1440
	}
	eventErr := handler.FSM.Event(msg.Type.String(), msg)
	filteredErr := filterError(eventErr)
	if filteredErr != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1441
		chaincodeLogger.Errorf("[%s]Failed to trigger FSM event %s: %s", msg.Txid, msg.Type.String(), filteredErr)
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
	}

	return filteredErr
}

// Filter the Errors to allow NoTransitionError and CanceledError to not propagate for cases where embedded Err == nil
func filterError(errFromFSMEvent error) error {
	if errFromFSMEvent != nil {
		if noTransitionErr, ok := errFromFSMEvent.(*fsm.NoTransitionError); ok {
			if noTransitionErr.Err != nil {
				// Squash the NoTransitionError
				return errFromFSMEvent
			}
			chaincodeLogger.Debugf("Ignoring NoTransitionError: %s", noTransitionErr)
		}
		if canceledErr, ok := errFromFSMEvent.(*fsm.CanceledError); ok {
			if canceledErr.Err != nil {
				// Squash the CanceledError
				return canceledErr
			}
			chaincodeLogger.Debugf("Ignoring CanceledError: %s", canceledErr)
		}
	}
	return nil
}

1468
1469
func (handler *Handler) sendExecuteMessage(ctxt context.Context, msg *pb.ChaincodeMessage, tx *pb.Transaction) (chan *pb.ChaincodeMessage, error) {
	txctx, err := handler.createTxContext(ctxt, msg.Txid, tx)
1470
1471
1472
1473
	if err != nil {
		return nil, err
	}

Gabor Hosszu's avatar
Gabor Hosszu committed
1474
1475
	// Mark TXID as either transaction or query
	chaincodeLogger.Debugf("[%s]Inside sendExecuteMessage. Message %s", shorttxid(msg.Txid), msg.Type.String())
1476
	if msg.Type.String() == pb.ChaincodeMessage_QUERY.String() {
Gabor Hosszu's avatar
Gabor Hosszu committed
1477
		handler.markIsTransaction(msg.Txid, false)
1478
	} else {
Gabor Hosszu's avatar
Gabor Hosszu committed
1479
		handler.markIsTransaction(msg.Txid, true)
1480
1481
1482
	}

	//if security is disabled the context elements will just be nil
1483
	if err := handler.setChaincodeSecurityContext(tx, nil, msg); err != nil {
1484
1485
1486
1487
1488
		return nil, err
	}

	// Trigger FSM event if it is a transaction
	if msg.Type.String() == pb.ChaincodeMessage_TRANSACTION.String() {
Gabor Hosszu's avatar
Gabor Hosszu committed
1489
		chaincodeLogger.Debugf("[%s]sendExecuteMsg trigger event %s", shorttxid(msg.Txid), msg.Type)
1490
1491
1492
		handler.triggerNextState(msg, true)
	} else {
		// Send the message to shim
Gabor Hosszu's avatar
Gabor Hosszu committed
1493
		chaincodeLogger.Debugf("[%s]sending query", shorttxid(msg.Txid))
1494
		if err = handler.serialSend(msg); err != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1495
1496
			handler.deleteTxContext(msg.Txid)
			return nil, fmt.Errorf("[%s]SendMessage error sending (%s)", shorttxid(msg.Txid), err)
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
		}
	}

	return txctx.responseNotifier, nil
}

func (handler *Handler) isRunning() bool {
	switch handler.FSM.Current() {
	case createdstate:
		fallthrough
	case establishedstate:
		fallthrough
	case initstate:
		return false
	default:
		return true
	}
}

/****************
func (handler *Handler) initEvent() (chan *pb.ChaincodeMessage, error) {
	if handler.responseNotifiers == nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1519
		return nil,fmt.Errorf("SendMessage called before registration for Txid:%s", msg.Txid)
1520
1521
1522
	}
	var notfy chan *pb.ChaincodeMessage
	handler.Lock()
Gabor Hosszu's avatar
Gabor Hosszu committed
1523
	if handler.responseNotifiers[msg.Txid] != nil {
1524
		handler.Unlock()
Gabor Hosszu's avatar
Gabor Hosszu committed
1525
		return nil, fmt.Errorf("SendMessage Txid:%s exists", msg.Txid)
1526
1527
1528
	}
	//note the explicit use of buffer 1. We won't block if the receiver times outi and does not wait
	//for our response
Gabor Hosszu's avatar
Gabor Hosszu committed
1529
	handler.responseNotifiers[msg.Txid] = make(chan *pb.ChaincodeMessage, 1)
1530
1531
1532
	handler.Unlock()

	if err := c.serialSend(msg); err != nil {
Gabor Hosszu's avatar
Gabor Hosszu committed
1533
1534
		deleteNotifier(msg.Txid)
		return nil, fmt.Errorf("SendMessage error sending %s(%s)", msg.Txid, err)
1535
1536
1537
1538
	}
	return notfy, nil
}
*******************/
For faster browsing, not all history is shown. View entire blame