diff --git a/bddtests/peer_basic.feature b/bddtests/peer_basic.feature index 277ac56639d..0317a6fcc5f 100644 --- a/bddtests/peer_basic.feature +++ b/bddtests/peer_basic.feature @@ -350,7 +350,8 @@ Feature: Network of Peers # @doNotDecompose # @wip # Arg[0] = a, base64 = 'YQ==' -# sha256 = 'ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb' +# sha256 = 'acfb280369a87a57b1954210081d78943f1a0adb5368184984e8852a42c14df8' +# calculated using all the args Scenario: chaincode map single peer content generated ID Given we compose "docker-compose-1.yml" When requesting "/chain" from "vp0" @@ -361,12 +362,12 @@ Feature: Network of Peers Then I should have received a chaincode name Then I wait up to "60" seconds for transaction to be committed to all peers - When I invoke chaincode "map" function name "put" on "vp0" with "sha256base64" + When I invoke chaincode "map" function name "put" on "vp0" with "sha256" | arg1 |arg2| | YQ== | 10 | Then I should have received a transactionID Then I wait up to "25" seconds for transaction to be committed to all peers - Then I check the transaction ID if it is "ca978112-ca1b-bdca-fac2-31b39a23dc4d" + Then I check the transaction ID if it is "acfb280369a87a57b1954210081d78943f1a0adb5368184984e8852a42c14df8" Scenario: chaincode example 01 single peer rejection message Given we compose "docker-compose-1-exp.yml" @@ -1106,7 +1107,7 @@ Feature: Network of Peers @issue_1942 -#@doNotDecompose +# @doNotDecompose Scenario: chaincode example02 with 4 peers, stop and start alternates, reverse Given we compose "docker-compose-4-consensus-batch.yml" And I register with CA supplying username "binhn" and secret "7avZQLwcUe9q" on peers: @@ -1152,15 +1153,14 @@ Scenario: chaincode example02 with 4 peers, stop and start alternates, reverse Given I start peers: | vp2 | - And I wait "30" seconds + And I wait "30" seconds Given I stop peers: | vp1 | When I invoke chaincode "example2" function name "invoke" on "vp3" "20" times |arg1|arg2|arg3| | a | b | 1 | - Then I should have received a transactionID - Then I wait up to "300" seconds for transaction to be committed to peers: + Then I wait up to "300" seconds for transactions to be committed to peers: | vp0 | vp2 | vp3 | When I query chaincode "example2" function name "query" with value "a" on peers: diff --git a/bddtests/steps/peer_basic_impl.py b/bddtests/steps/peer_basic_impl.py index e802e7aaf7d..1aa8951d14d 100644 --- a/bddtests/steps/peer_basic_impl.py +++ b/bddtests/steps/peer_basic_impl.py @@ -311,6 +311,12 @@ def step_impl(context, chaincodeName, functionName, containerName, idGenAlg): @when(u'I invoke chaincode "{chaincodeName}" function name "{functionName}" on "{containerName}" "{times}" times') def step_impl(context, chaincodeName, functionName, containerName, times): assert 'chaincodeSpec' in context, "chaincodeSpec not found in context" + ipAddress = bdd_test_util.ipFromContainerNamePart(containerName, context.compose_containers) + request_url = buildUrl(context, ipAddress, "/chain") + resp = requests.get(request_url, headers={'Accept': 'application/json'}, verify=False) + assert resp.status_code == 200, "Failed to get chain height %s: %s" % (request_url,resp.text) + context.chainheight = getAttributeFromJSON("height", resp.json(), "Height not found in response.") + context.txcount = times for i in range(int(times)): invokeChaincode(context, "invoke", functionName, containerName) @@ -577,6 +583,49 @@ def step_impl(context, seconds): print("Result of request to all peers = {0}".format(respMap)) print("") +@then(u'I wait up to "{seconds}" seconds for transactions to be committed to peers') +def step_impl(context, seconds): + assert 'chainheight' in context, "chainheight not found in context" + assert 'txcount' in context, "txcount not found in context" + assert 'compose_containers' in context, "compose_containers not found in context" + assert 'table' in context, "table (of peers) not found in context" + + aliases = context.table.headings + containerDataList = bdd_test_util.getContainerDataValuesFromContext(context, aliases, lambda containerData: containerData) + + # Build map of "containerName" : resp.statusCode + respMap = {container.containerName:0 for container in containerDataList} + + # Set the max time before stopping attempts + maxTime = datetime.now() + timedelta(seconds = int(seconds)) + for container in containerDataList: + ipAddress = container.ipAddress + request_url = buildUrl(context, ipAddress, "/chain") + + # Loop unless failure or time exceeded + while (datetime.now() < maxTime): + print("{0} GETing path = {1}".format(currentTime(), request_url)) + resp = requests.get(request_url, headers={'Accept': 'application/json'}, verify=False) + if resp.status_code == 404: + # Pause then try again + respMap[container.containerName] = 404 + time.sleep(1) + continue + elif resp.status_code == 200: + height = getAttributeFromJSON("height", resp.json(), "Height not found in response.") + if height >= int(context.chainheight) + int(context.txcount): + # Success, continue + respMap[container.containerName] = 200 + break + else: + continue + else: + raise Exception("Error requesting {0}, returned result code = {1}".format(request_url, resp.status_code)) + else: + raise Exception("Max time exceeded waiting for transactions with current response map = {0}".format(respMap)) + print("Result of request to all peers = {0}".format(respMap)) + print("") + @then(u'I should get a rejection message in the listener after stopping it') def step_impl(context): diff --git a/bddtests/syschaincode/noop/chaincode.go b/bddtests/syschaincode/noop/chaincode.go index 3d2204053e9..a4923615871 100644 --- a/bddtests/syschaincode/noop/chaincode.go +++ b/bddtests/syschaincode/noop/chaincode.go @@ -30,7 +30,7 @@ import ( var logger = shim.NewLogger("noop") type ledgerHandler interface { - GetTransactionByUUID(txUUID string) (*protos.Transaction, error) + GetTransactionByID(txID string) (*protos.Transaction, error) } // SystemChaincode is type representing the chaincode @@ -86,7 +86,7 @@ func (t *SystemChaincode) Query(stub *shim.ChaincodeStub, function string, args logger.Infof("--> %x", args[0]) var txHashHex = args[0] - var tx, txerr = t.getLedger().GetTransactionByUUID(txHashHex) + var tx, txerr = t.getLedger().GetTransactionByID(txHashHex) if nil != txerr || nil == tx { return nil, txerr } diff --git a/bddtests/syschaincode/noop/chaincode_test.go b/bddtests/syschaincode/noop/chaincode_test.go index 13d46866eb5..b9e51efdb00 100644 --- a/bddtests/syschaincode/noop/chaincode_test.go +++ b/bddtests/syschaincode/noop/chaincode_test.go @@ -111,8 +111,8 @@ func TestQueryGetTranExisting(t *testing.T) { type mockLedger struct { } -func (ml mockLedger) GetTransactionByUUID(txUUID string) (*protos.Transaction, error) { - if txUUID == "noSuchTX" { +func (ml mockLedger) GetTransactionByID(txID string) (*protos.Transaction, error) { + if txID == "noSuchTX" { return nil, fmt.Errorf("Some error") } newCCIS := &protos.ChaincodeInvocationSpec{ChaincodeSpec: &protos.ChaincodeSpec{CtorMsg: &protos.ChaincodeInput{Function: "execute", Args: []string{something}}}} diff --git a/consensus/helper/engine.go b/consensus/helper/engine.go index e7defc8ae26..9d8c158a6d5 100644 --- a/consensus/helper/engine.go +++ b/consensus/helper/engine.go @@ -67,7 +67,7 @@ func (eng *EngineImpl) ProcessTransactionMsg(msg *pb.Message, tx *pb.Transaction } } else { // Chaincode Transaction - response = &pb.Response{Status: pb.Response_SUCCESS, Msg: []byte(tx.Uuid)} + response = &pb.Response{Status: pb.Response_SUCCESS, Msg: []byte(tx.Txid)} //TODO: Do we need to verify security, or can we supply a flag on the invoke ot this functions // If we fail to marshal or verify the tx, don't send it to consensus plugin diff --git a/consensus/helper/helper.go b/consensus/helper/helper.go index ad473fcf228..e28d9c22097 100644 --- a/consensus/helper/helper.go +++ b/consensus/helper/helper.go @@ -191,9 +191,9 @@ func (h *Helper) ExecTxs(id interface{}, txs []*pb.Transaction) ([]byte, error) for i, e := range txerrs { //NOTE- it'll be nice if we can have error values. For now success == 0, error == 1 if txerrs[i] != nil { - txresults[i] = &pb.TransactionResult{Uuid: txs[i].Uuid, Error: e.Error(), ErrorCode: 1, ChaincodeEvent: ccevents[i]} + txresults[i] = &pb.TransactionResult{Txid: txs[i].Txid, Error: e.Error(), ErrorCode: 1, ChaincodeEvent: ccevents[i]} } else { - txresults[i] = &pb.TransactionResult{Uuid: txs[i].Uuid, ChaincodeEvent: ccevents[i]} + txresults[i] = &pb.TransactionResult{Txid: txs[i].Txid, ChaincodeEvent: ccevents[i]} } } h.curBatchErrs = append(h.curBatchErrs, txresults...) // TODO, remove after issue 579 diff --git a/consensus/noops/noops.go b/consensus/noops/noops.go index db64177e9c9..0914b752cb3 100644 --- a/consensus/noops/noops.go +++ b/consensus/noops/noops.go @@ -105,7 +105,7 @@ func (i *Noops) RecvMsg(msg *pb.Message, senderHandle *pb.PeerID) error { return err } if logger.IsEnabledFor(logging.DEBUG) { - logger.Debugf("Sending to channel tx uuid: %s", tx.Uuid) + logger.Debugf("Sending to channel tx uuid: %s", tx.Txid) } i.channel <- tx } diff --git a/consensus/pbft/batch.go b/consensus/pbft/batch.go index ce834aac852..40e7942a102 100644 --- a/consensus/pbft/batch.go +++ b/consensus/pbft/batch.go @@ -192,9 +192,9 @@ func (op *obcBatch) execute(seqNo uint64, reqBatch *RequestBatch) { logger.Warningf("Batch replica %d could not unmarshal transaction %s", op.pbft.id, err) continue } - logger.Debugf("Batch replica %d executing request with transaction %s from outstandingReqs, seqNo=%d", op.pbft.id, tx.Uuid, seqNo) + logger.Debugf("Batch replica %d executing request with transaction %s from outstandingReqs, seqNo=%d", op.pbft.id, tx.Txid, seqNo) if outstanding, pending := op.reqStore.remove(req); !outstanding || !pending { - logger.Debugf("Batch replica %d missing transaction %s outstanding=%v, pending=%v", op.pbft.id, tx.Uuid, outstanding, pending) + logger.Debugf("Batch replica %d missing transaction %s outstanding=%v, pending=%v", op.pbft.id, tx.Txid, outstanding, pending) } txs = append(txs, tx) op.deduplicator.Execute(req) @@ -314,7 +314,7 @@ func (op *obcBatch) logAddTxFromRequest(req *Request) { if err != nil { logger.Errorf("Replica %d was sent a transaction which did not unmarshal: %s", op.pbft.id, err) } else { - logger.Debugf("Replica %d adding request from %d with transaction %s into outstandingReqs", op.pbft.id, req.ReplicaId, tx.Uuid) + logger.Debugf("Replica %d adding request from %d with transaction %s into outstandingReqs", op.pbft.id, req.ReplicaId, tx.Txid) } } } diff --git a/core/chaincode/chaincode_support.go b/core/chaincode/chaincode_support.go index 71b461effb4..8c999def66f 100644 --- a/core/chaincode/chaincode_support.go +++ b/core/chaincode/chaincode_support.go @@ -212,7 +212,7 @@ func (chaincodeSupport *ChaincodeSupport) registerHandler(chaincodehandler *Hand //now we are ready to receive messages and send back responses chaincodehandler.txCtxs = make(map[string]*transactionContext) - chaincodehandler.uuidMap = make(map[string]bool) + chaincodehandler.txidMap = make(map[string]bool) chaincodehandler.isTransaction = make(map[string]bool) chaincodeLogger.Debugf("registered handler complete for chaincode %s", key) @@ -243,7 +243,7 @@ func (chaincodeSupport *ChaincodeSupport) deregisterHandler(chaincodehandler *Ha } // Based on state of chaincode send either init or ready to move to ready state -func (chaincodeSupport *ChaincodeSupport) sendInitOrReady(context context.Context, uuid string, chaincode string, f *string, initArgs []string, timeout time.Duration, tx *pb.Transaction, depTx *pb.Transaction) error { +func (chaincodeSupport *ChaincodeSupport) sendInitOrReady(context context.Context, txid string, chaincode string, f *string, initArgs []string, timeout time.Duration, tx *pb.Transaction, depTx *pb.Transaction) error { chaincodeSupport.runningChaincodes.Lock() //if its in the map, there must be a connected stream...nothing to do var chrte *chaincodeRTEnv @@ -257,7 +257,7 @@ func (chaincodeSupport *ChaincodeSupport) sendInitOrReady(context context.Contex var notfy chan *pb.ChaincodeMessage var err error - if notfy, err = chrte.handler.initOrReady(uuid, f, initArgs, tx, depTx); err != nil { + if notfy, err = chrte.handler.initOrReady(txid, f, initArgs, tx, depTx); err != nil { return fmt.Errorf("Error sending %s: %s", pb.ChaincodeMessage_INIT, err) } if notfy != nil { @@ -272,7 +272,7 @@ func (chaincodeSupport *ChaincodeSupport) sendInitOrReady(context context.Contex } //if initOrReady succeeded, our responsibility to delete the context - chrte.handler.deleteTxContext(uuid) + chrte.handler.deleteTxContext(txid) return err } @@ -309,7 +309,7 @@ func (chaincodeSupport *ChaincodeSupport) getArgsAndEnv(cID *pb.ChaincodeID, cLa } // launchAndWaitForRegister will launch container if not already running. Use the targz to create the image if not found -func (chaincodeSupport *ChaincodeSupport) launchAndWaitForRegister(ctxt context.Context, cds *pb.ChaincodeDeploymentSpec, cID *pb.ChaincodeID, uuid string, cLang pb.ChaincodeSpec_Type, targz io.Reader) (bool, error) { +func (chaincodeSupport *ChaincodeSupport) launchAndWaitForRegister(ctxt context.Context, cds *pb.ChaincodeDeploymentSpec, cID *pb.ChaincodeID, txid string, cLang pb.ChaincodeSpec_Type, targz io.Reader) (bool, error) { chaincode := cID.Name if chaincode == "" { return false, fmt.Errorf("chaincode name not set") @@ -359,10 +359,10 @@ func (chaincodeSupport *ChaincodeSupport) launchAndWaitForRegister(ctxt context. select { case ok := <-notfy: if !ok { - err = fmt.Errorf("registration failed for %s(networkid:%s,peerid:%s,tx:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID, uuid) + err = fmt.Errorf("registration failed for %s(networkid:%s,peerid:%s,tx:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID, txid) } case <-time.After(chaincodeSupport.ccStartupTimeout): - err = fmt.Errorf("Timeout expired while starting chaincode %s(networkid:%s,peerid:%s,tx:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID, uuid) + err = fmt.Errorf("Timeout expired while starting chaincode %s(networkid:%s,peerid:%s,tx:%s)", chaincode, chaincodeSupport.peerNetworkID, chaincodeSupport.peerID, txid) } if err != nil { chaincodeLogger.Debugf("stopping due to error while launching %s", err) @@ -486,7 +486,7 @@ func (chaincodeSupport *ChaincodeSupport) Launch(context context.Context, t *pb. } //hopefully we are restarting from existing image and the deployed transaction exists - depTx, ledgerErr = ledger.GetTransactionByUUID(chaincode) + depTx, ledgerErr = ledger.GetTransactionByID(chaincode) if ledgerErr != nil { return cID, cMsg, fmt.Errorf("Could not get deployment transaction for %s - %s", chaincode, ledgerErr) } @@ -514,7 +514,7 @@ func (chaincodeSupport *ChaincodeSupport) Launch(context context.Context, t *pb. //launch container if it is a System container or not in dev mode if (!chaincodeSupport.userRunsCC || cds.ExecEnv == pb.ChaincodeDeploymentSpec_SYSTEM) && (chrte == nil || chrte.handler == nil) { var targz io.Reader = bytes.NewBuffer(cds.CodePackage) - _, err = chaincodeSupport.launchAndWaitForRegister(context, cds, cID, t.Uuid, cLang, targz) + _, err = chaincodeSupport.launchAndWaitForRegister(context, cds, cID, t.Txid, cLang, targz) if err != nil { chaincodeLogger.Errorf("launchAndWaitForRegister failed %s", err) return cID, cMsg, err @@ -523,7 +523,7 @@ func (chaincodeSupport *ChaincodeSupport) Launch(context context.Context, t *pb. if err == nil { //send init (if (f,args)) and wait for ready state - err = chaincodeSupport.sendInitOrReady(context, t.Uuid, chaincode, f, initargs, chaincodeSupport.ccStartupTimeout, t, depTx) + err = chaincodeSupport.sendInitOrReady(context, t.Txid, chaincode, f, initargs, chaincodeSupport.ccStartupTimeout, t, depTx) if err != nil { chaincodeLogger.Errorf("sending init failed(%s)", err) err = fmt.Errorf("Failed to init chaincode(%s)", err) @@ -615,22 +615,22 @@ func (chaincodeSupport *ChaincodeSupport) Register(stream pb.ChaincodeSupport_Re } // createTransactionMessage creates a transaction message. -func createTransactionMessage(uuid string, cMsg *pb.ChaincodeInput) (*pb.ChaincodeMessage, error) { +func createTransactionMessage(txid string, cMsg *pb.ChaincodeInput) (*pb.ChaincodeMessage, error) { payload, err := proto.Marshal(cMsg) if err != nil { fmt.Printf(err.Error()) return nil, err } - return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_TRANSACTION, Payload: payload, Uuid: uuid}, nil + return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_TRANSACTION, Payload: payload, Txid: txid}, nil } // createQueryMessage creates a query message. -func createQueryMessage(uuid string, cMsg *pb.ChaincodeInput) (*pb.ChaincodeMessage, error) { +func createQueryMessage(txid string, cMsg *pb.ChaincodeInput) (*pb.ChaincodeMessage, error) { payload, err := proto.Marshal(cMsg) if err != nil { return nil, err } - return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY, Payload: payload, Uuid: uuid}, nil + return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY, Payload: payload, Txid: txid}, nil } // Execute executes a transaction and waits for it to complete until a timeout value. @@ -660,7 +660,7 @@ func (chaincodeSupport *ChaincodeSupport) Execute(ctxt context.Context, chaincod } //our responsibility to delete transaction context if sendExecuteMessage succeeded - chrte.handler.deleteTxContext(msg.Uuid) + chrte.handler.deleteTxContext(msg.Txid) return ccresp, err } diff --git a/core/chaincode/exectransaction.go b/core/chaincode/exectransaction.go index 56bf26359c2..9888f0b6397 100644 --- a/core/chaincode/exectransaction.go +++ b/core/chaincode/exectransaction.go @@ -86,12 +86,12 @@ func Execute(ctxt context.Context, chain *ChaincodeSupport, t *pb.Transaction) ( var ccMsg *pb.ChaincodeMessage if t.Type == pb.Transaction_CHAINCODE_INVOKE { - ccMsg, err = createTransactionMessage(t.Uuid, cMsg) + ccMsg, err = createTransactionMessage(t.Txid, cMsg) if err != nil { return nil, nil, fmt.Errorf("Failed to transaction message(%s)", err) } } else { - ccMsg, err = createQueryMessage(t.Uuid, cMsg) + ccMsg, err = createQueryMessage(t.Txid, cMsg) if err != nil { return nil, nil, fmt.Errorf("Failed to query message(%s)", err) } @@ -106,11 +106,11 @@ func Execute(ctxt context.Context, chain *ChaincodeSupport, t *pb.Transaction) ( } else if resp == nil { // Rollback transaction markTxFinish(ledger, t, false) - return nil, nil, fmt.Errorf("Failed to receive a response for (%s)", t.Uuid) + return nil, nil, fmt.Errorf("Failed to receive a response for (%s)", t.Txid) } else { if resp.ChaincodeEvent != nil { resp.ChaincodeEvent.ChaincodeID = chaincode - resp.ChaincodeEvent.TxID = t.Uuid + resp.ChaincodeEvent.TxID = t.Txid } if resp.Type == pb.ChaincodeMessage_COMPLETED || resp.Type == pb.ChaincodeMessage_QUERY_COMPLETED { @@ -123,7 +123,7 @@ func Execute(ctxt context.Context, chain *ChaincodeSupport, t *pb.Transaction) ( return nil, resp.ChaincodeEvent, fmt.Errorf("Transaction or query returned with failure: %s", string(resp.Payload)) } markTxFinish(ledger, t, false) - return resp.Payload, nil, fmt.Errorf("receive a response for (%s) but in invalid state(%d)", t.Uuid, resp.Type) + return resp.Payload, nil, fmt.Errorf("receive a response for (%s) but in invalid state(%d)", t.Txid, resp.Type) } } else { @@ -184,9 +184,9 @@ func getTimeout(cID *pb.ChaincodeID) (time.Duration, error) { ledger, err := ledger.GetLedger() if err == nil { chaincodeID := cID.Name - txUUID, err := ledger.GetState(chaincodeID, "github.com_openblockchain_obc-peer_chaincode_id", true) + txID, err := ledger.GetState(chaincodeID, "github.com_openblockchain_obc-peer_chaincode_id", true) if err == nil { - tx, err := ledger.GetTransactionByUUID(string(txUUID)) + tx, err := ledger.GetTransactionByID(string(txID)) if err == nil { chaincodeDeploymentSpec := &pb.ChaincodeDeploymentSpec{} proto.Unmarshal(tx.Payload, chaincodeDeploymentSpec) @@ -204,14 +204,14 @@ func markTxBegin(ledger *ledger.Ledger, t *pb.Transaction) { if t.Type == pb.Transaction_CHAINCODE_QUERY { return } - ledger.TxBegin(t.Uuid) + ledger.TxBegin(t.Txid) } func markTxFinish(ledger *ledger.Ledger, t *pb.Transaction, successful bool) { if t.Type == pb.Transaction_CHAINCODE_QUERY { return } - ledger.TxFinished(t.Uuid, successful) + ledger.TxFinished(t.Txid, successful) } func sendTxRejectedEvent(tx *pb.Transaction, errorMsg string) { diff --git a/core/chaincode/handler.go b/core/chaincode/handler.go index 089c898da8f..a967f6f5695 100644 --- a/core/chaincode/handler.go +++ b/core/chaincode/handler.go @@ -83,24 +83,24 @@ type Handler struct { chaincodeSupport *ChaincodeSupport registered bool readyNotify chan bool - // Map of tx uuid to either invoke or query tx (decrypted). Each tx will be + // Map of tx txid to either invoke or query tx (decrypted). Each tx will be // added prior to execute and remove when done execute txCtxs map[string]*transactionContext - uuidMap map[string]bool + txidMap map[string]bool - // Track which UUIDs are queries; Although the shim maintains this, it cannot be trusted. + // Track which TXIDs are queries; Although the shim maintains this, it cannot be trusted. isTransaction map[string]bool // used to do Send after making sure the state transition is complete nextState chan *nextStateInfo } -func shortuuid(uuid string) string { - if len(uuid) < 8 { - return uuid +func shorttxid(txid string) string { + if len(txid) < 8 { + return txid } - return uuid[0:8] + return txid[0:8] } func (handler *Handler) serialSend(msg *pb.ChaincodeMessage) error { @@ -113,92 +113,92 @@ func (handler *Handler) serialSend(msg *pb.ChaincodeMessage) error { return nil } -func (handler *Handler) createTxContext(uuid string, tx *pb.Transaction) (*transactionContext, error) { +func (handler *Handler) createTxContext(txid string, tx *pb.Transaction) (*transactionContext, error) { if handler.txCtxs == nil { - return nil, fmt.Errorf("cannot create notifier for Uuid:%s", uuid) + return nil, fmt.Errorf("cannot create notifier for txid:%s", txid) } handler.Lock() defer handler.Unlock() - if handler.txCtxs[uuid] != nil { - return nil, fmt.Errorf("Uuid:%s exists", uuid) + if handler.txCtxs[txid] != nil { + return nil, fmt.Errorf("txid:%s exists", txid) } txctx := &transactionContext{transactionSecContext: tx, responseNotifier: make(chan *pb.ChaincodeMessage, 1), rangeQueryIteratorMap: make(map[string]statemgmt.RangeScanIterator)} - handler.txCtxs[uuid] = txctx + handler.txCtxs[txid] = txctx return txctx, nil } -func (handler *Handler) getTxContext(uuid string) *transactionContext { +func (handler *Handler) getTxContext(txid string) *transactionContext { handler.Lock() defer handler.Unlock() - return handler.txCtxs[uuid] + return handler.txCtxs[txid] } -func (handler *Handler) deleteTxContext(uuid string) { +func (handler *Handler) deleteTxContext(txid string) { handler.Lock() defer handler.Unlock() if handler.txCtxs != nil { - delete(handler.txCtxs, uuid) + delete(handler.txCtxs, txid) } } -func (handler *Handler) putRangeQueryIterator(txContext *transactionContext, uuid string, +func (handler *Handler) putRangeQueryIterator(txContext *transactionContext, txid string, rangeScanIterator statemgmt.RangeScanIterator) { handler.Lock() defer handler.Unlock() - txContext.rangeQueryIteratorMap[uuid] = rangeScanIterator + txContext.rangeQueryIteratorMap[txid] = rangeScanIterator } -func (handler *Handler) getRangeQueryIterator(txContext *transactionContext, uuid string) statemgmt.RangeScanIterator { +func (handler *Handler) getRangeQueryIterator(txContext *transactionContext, txid string) statemgmt.RangeScanIterator { handler.Lock() defer handler.Unlock() - return txContext.rangeQueryIteratorMap[uuid] + return txContext.rangeQueryIteratorMap[txid] } -func (handler *Handler) deleteRangeQueryIterator(txContext *transactionContext, uuid string) { +func (handler *Handler) deleteRangeQueryIterator(txContext *transactionContext, txid string) { handler.Lock() defer handler.Unlock() - delete(txContext.rangeQueryIteratorMap, uuid) + delete(txContext.rangeQueryIteratorMap, txid) } //THIS CAN BE REMOVED ONCE WE SUPPORT CONFIDENTIALITY WITH CC-CALLING-CC //we dissallow chaincode-chaincode interactions till confidentiality implications are understood -func (handler *Handler) canCallChaincode(uuid string) *pb.ChaincodeMessage { +func (handler *Handler) canCallChaincode(txid string) *pb.ChaincodeMessage { secHelper := handler.chaincodeSupport.getSecHelper() if secHelper == nil { return nil } var errMsg string - txctx := handler.getTxContext(uuid) + txctx := handler.getTxContext(txid) if txctx == nil { - errMsg = fmt.Sprintf("[%s]Error no context while checking for confidentiality. Sending %s", shortuuid(uuid), pb.ChaincodeMessage_ERROR) + errMsg = fmt.Sprintf("[%s]Error no context while checking for confidentiality. Sending %s", shorttxid(txid), pb.ChaincodeMessage_ERROR) } else if txctx.transactionSecContext == nil { - errMsg = fmt.Sprintf("[%s]Error transaction context is nil while checking for confidentiality. Sending %s", shortuuid(uuid), pb.ChaincodeMessage_ERROR) + errMsg = fmt.Sprintf("[%s]Error transaction context is nil while checking for confidentiality. Sending %s", shorttxid(txid), pb.ChaincodeMessage_ERROR) } else if txctx.transactionSecContext.ConfidentialityLevel != pb.ConfidentialityLevel_PUBLIC { - errMsg = fmt.Sprintf("[%s]Error chaincode-chaincode interactions not supported for with privacy enabled. Sending %s", shortuuid(uuid), pb.ChaincodeMessage_ERROR) + errMsg = fmt.Sprintf("[%s]Error chaincode-chaincode interactions not supported for with privacy enabled. Sending %s", shorttxid(txid), pb.ChaincodeMessage_ERROR) } if errMsg != "" { - return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(errMsg), Uuid: uuid} + return &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(errMsg), Txid: txid} } //not CONFIDENTIAL transaction, OK to call CC return nil } -func (handler *Handler) encryptOrDecrypt(encrypt bool, uuid string, payload []byte) ([]byte, error) { +func (handler *Handler) encryptOrDecrypt(encrypt bool, txid string, payload []byte) ([]byte, error) { secHelper := handler.chaincodeSupport.getSecHelper() if secHelper == nil { return payload, nil } - txctx := handler.getTxContext(uuid) + txctx := handler.getTxContext(txid) if txctx == nil { - return nil, fmt.Errorf("[%s]No context for uuid %s", shortuuid(uuid), uuid) + return nil, fmt.Errorf("[%s]No context for txid %s", shorttxid(txid), txid) } if txctx.transactionSecContext == nil { - return nil, fmt.Errorf("[%s]transaction context is nil for uuid %s", shortuuid(uuid), uuid) + return nil, fmt.Errorf("[%s]transaction context is nil for txid %s", shorttxid(txid), txid) } // TODO: this must be removed if txctx.transactionSecContext.ConfidentialityLevel == pb.ConfidentialityLevel_PUBLIC { @@ -219,10 +219,10 @@ func (handler *Handler) encryptOrDecrypt(encrypt bool, uuid string, payload []by return nil, fmt.Errorf("invalid transaction type %s", txctx.transactionSecContext.Type.String()) } if enc == nil { - return nil, fmt.Errorf("secure context returns nil encryptor for tx %s", uuid) + return nil, fmt.Errorf("secure context returns nil encryptor for tx %s", txid) } if chaincodeLogger.IsEnabledFor(logging.DEBUG) { - chaincodeLogger.Debugf("[%s]Payload before encrypt/decrypt: %v", shortuuid(uuid), payload) + chaincodeLogger.Debugf("[%s]Payload before encrypt/decrypt: %v", shorttxid(txid), payload) } if encrypt { payload, err = enc.Encrypt(payload) @@ -230,18 +230,18 @@ func (handler *Handler) encryptOrDecrypt(encrypt bool, uuid string, payload []by payload, err = enc.Decrypt(payload) } if chaincodeLogger.IsEnabledFor(logging.DEBUG) { - chaincodeLogger.Debugf("[%s]Payload after encrypt/decrypt: %v", shortuuid(uuid), payload) + chaincodeLogger.Debugf("[%s]Payload after encrypt/decrypt: %v", shorttxid(txid), payload) } return payload, err } -func (handler *Handler) decrypt(uuid string, payload []byte) ([]byte, error) { - return handler.encryptOrDecrypt(false, uuid, payload) +func (handler *Handler) decrypt(txid string, payload []byte) ([]byte, error) { + return handler.encryptOrDecrypt(false, txid, payload) } -func (handler *Handler) encrypt(uuid string, payload []byte) ([]byte, error) { - return handler.encryptOrDecrypt(true, uuid, payload) +func (handler *Handler) encrypt(txid string, payload []byte) ([]byte, error) { + return handler.encryptOrDecrypt(true, txid, payload) } func (handler *Handler) getSecurityBinding(tx *pb.Transaction) ([]byte, error) { @@ -310,7 +310,7 @@ func (handler *Handler) processStream() error { chaincodeLogger.Debug("Received nil message, ending chaincode support stream") return err } - chaincodeLogger.Debugf("[%s]Received message %s from shim", shortuuid(in.Uuid), in.Type.String()) + chaincodeLogger.Debugf("[%s]Received message %s from shim", shorttxid(in.Txid), in.Type.String()) if in.Type.String() == pb.ChaincodeMessage_ERROR.String() { chaincodeLogger.Errorf("Got error: %s", string(in.Payload)) } @@ -331,7 +331,7 @@ func (handler *Handler) processStream() error { chaincodeLogger.Debug("Next state nil message, ending chaincode support stream") return err } - chaincodeLogger.Debugf("[%s]Move state message %s", shortuuid(in.Uuid), in.Type.String()) + chaincodeLogger.Debugf("[%s]Move state message %s", shorttxid(in.Txid), in.Type.String()) case <-handler.waitForKeepaliveTimer(): if handler.chaincodeSupport.keepalive <= 0 { chaincodeLogger.Errorf("Invalid select: keepalive not on (keepalive=%d)", handler.chaincodeSupport.keepalive) @@ -351,15 +351,15 @@ func (handler *Handler) processStream() error { err = handler.HandleMessage(in) if err != nil { - chaincodeLogger.Errorf("[%s]Error handling message, ending stream: %s", shortuuid(in.Uuid), err) + chaincodeLogger.Errorf("[%s]Error handling message, ending stream: %s", shorttxid(in.Txid), err) return fmt.Errorf("Error handling message, ending stream: %s", err) } if nsInfo != nil && nsInfo.sendToCC { - chaincodeLogger.Debugf("[%s]sending state message %s", shortuuid(in.Uuid), in.Type.String()) + chaincodeLogger.Debugf("[%s]sending state message %s", shorttxid(in.Txid), in.Type.String()) if err = handler.serialSend(in); err != nil { - chaincodeLogger.Errorf("[%s]serial sending received error %s", shortuuid(in.Uuid), err) - return fmt.Errorf("[%s]serial sending received error %s", shortuuid(in.Uuid), err) + chaincodeLogger.Debugf("[%s]serial sending received error %s", shorttxid(in.Txid), err) + return fmt.Errorf("[%s]serial sending received error %s", shorttxid(in.Txid), err) } } } @@ -446,54 +446,54 @@ func newChaincodeSupportHandler(chaincodeSupport *ChaincodeSupport, peerChatStre return v } -func (handler *Handler) createUUIDEntry(uuid string) bool { - if handler.uuidMap == nil { +func (handler *Handler) createTXIDEntry(txid string) bool { + if handler.txidMap == nil { return false } handler.Lock() defer handler.Unlock() - if handler.uuidMap[uuid] { + if handler.txidMap[txid] { return false } - handler.uuidMap[uuid] = true - return handler.uuidMap[uuid] + handler.txidMap[txid] = true + return handler.txidMap[txid] } -func (handler *Handler) deleteUUIDEntry(uuid string) { +func (handler *Handler) deleteTXIDEntry(txid string) { handler.Lock() defer handler.Unlock() - if handler.uuidMap != nil { - delete(handler.uuidMap, uuid) + if handler.txidMap != nil { + delete(handler.txidMap, txid) } else { - chaincodeLogger.Errorf("UUID %s not found!", uuid) + chaincodeLogger.Warningf("TXID %s not found!", txid) } } -// markIsTransaction marks a UUID as a transaction or a query; true = transaction, false = query -func (handler *Handler) markIsTransaction(uuid string, isTrans bool) bool { +// markIsTransaction marks a TXID as a transaction or a query; true = transaction, false = query +func (handler *Handler) markIsTransaction(txid string, isTrans bool) bool { handler.Lock() defer handler.Unlock() if handler.isTransaction == nil { return false } - handler.isTransaction[uuid] = isTrans + handler.isTransaction[txid] = isTrans return true } -func (handler *Handler) getIsTransaction(uuid string) bool { +func (handler *Handler) getIsTransaction(txid string) bool { handler.Lock() defer handler.Unlock() if handler.isTransaction == nil { return false } - return handler.isTransaction[uuid] + return handler.isTransaction[txid] } -func (handler *Handler) deleteIsTransaction(uuid string) { +func (handler *Handler) deleteIsTransaction(txid string) { handler.Lock() defer handler.Unlock() if handler.isTransaction != nil { - delete(handler.isTransaction, uuid) + delete(handler.isTransaction, txid) } } @@ -542,11 +542,11 @@ func (handler *Handler) beforeRegisterEvent(e *fsm.Event, state string) { func (handler *Handler) notify(msg *pb.ChaincodeMessage) { handler.Lock() defer handler.Unlock() - tctx := handler.txCtxs[msg.Uuid] + tctx := handler.txCtxs[msg.Txid] if tctx == nil { - chaincodeLogger.Debugf("notifier Uuid:%s does not exist", msg.Uuid) + chaincodeLogger.Debugf("notifier Txid:%s does not exist", msg.Txid) } else { - chaincodeLogger.Debugf("notifying Uuid:%s", msg.Uuid) + chaincodeLogger.Debugf("notifying Txid:%s", msg.Txid) tctx.responseNotifier <- msg // clean up rangeQueryIteratorMap @@ -564,7 +564,7 @@ func (handler *Handler) beforeCompletedEvent(e *fsm.Event, state string) { return } // Notify on channel once into READY state - chaincodeLogger.Debugf("[%s]beforeCompleted - not in ready state will notify when in readystate", shortuuid(msg.Uuid)) + chaincodeLogger.Debugf("[%s]beforeCompleted - not in ready state will notify when in readystate", shorttxid(msg.Txid)) return } @@ -581,7 +581,7 @@ func (handler *Handler) afterGetState(e *fsm.Event, state string) { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]Received %s, invoking get state from ledger", shortuuid(msg.Uuid), pb.ChaincodeMessage_GET_STATE) + chaincodeLogger.Debugf("[%s]Received %s, invoking get state from ledger", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_STATE) // Query ledger for state handler.handleGetState(msg) @@ -593,19 +593,19 @@ func (handler *Handler) handleGetState(msg *pb.ChaincodeMessage) { // 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() { - // Check if this is the unique state request from this chaincode uuid - uniqueReq := handler.createUUIDEntry(msg.Uuid) + // 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 Uuid. Cannot process.") + chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.") return } var serialSendMsg *pb.ChaincodeMessage defer func() { - handler.deleteUUIDEntry(msg.Uuid) - chaincodeLogger.Debugf("[%s]handleGetState serial send %s", shortuuid(serialSendMsg.Uuid), serialSendMsg.Type) + handler.deleteTXIDEntry(msg.Txid) + chaincodeLogger.Debugf("[%s]handleGetState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type) handler.serialSend(serialSendMsg) }() @@ -615,36 +615,36 @@ func (handler *Handler) handleGetState(msg *pb.ChaincodeMessage) { // Send error msg back to chaincode. GetState will not trigger event payload := []byte(ledgerErr.Error()) chaincodeLogger.Errorf("Failed to get chaincode state(%s). Sending %s", ledgerErr, pb.ChaincodeMessage_ERROR) - // Remove uuid from current set - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + // Remove txid from current set + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } // Invoke ledger to get state chaincodeID := handler.ChaincodeID.Name - readCommittedState := !handler.getIsTransaction(msg.Uuid) + readCommittedState := !handler.getIsTransaction(msg.Txid) res, err := ledgerObj.GetState(chaincodeID, key, readCommittedState) if err != nil { // Send error msg back to chaincode. GetState will not trigger event payload := []byte(err.Error()) - chaincodeLogger.Errorf("[%s]Failed to get chaincode state(%s). Sending %s", shortuuid(msg.Uuid), err, pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Errorf("[%s]Failed to get chaincode state(%s). Sending %s", shorttxid(msg.Txid), err, pb.ChaincodeMessage_ERROR) + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} } else if res == nil { //The state object being requested does not exist, so don't attempt to decrypt it - chaincodeLogger.Debugf("[%s]No state associated with key: %s. Sending %s with an empty payload", shortuuid(msg.Uuid), key, pb.ChaincodeMessage_RESPONSE) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]No state associated with key: %s. Sending %s with an empty payload", shorttxid(msg.Txid), key, pb.ChaincodeMessage_RESPONSE) + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid} } else { // Decrypt the data if the confidential is enabled - if res, err = handler.decrypt(msg.Uuid, res); err == nil { + if res, err = handler.decrypt(msg.Txid, res); err == nil { // Send response msg back to chaincode. GetState will not trigger event - chaincodeLogger.Debugf("[%s]Got state. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RESPONSE) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]Got state. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RESPONSE) + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Txid: msg.Txid} } else { // Send err msg back to chaincode. - chaincodeLogger.Errorf("[%s]Got error (%s) while decrypting. Sending %s", shortuuid(msg.Uuid), err, pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Got error (%s) while decrypting. Sending %s", shorttxid(msg.Txid), err, pb.ChaincodeMessage_ERROR) errBytes := []byte(err.Error()) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: errBytes, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: errBytes, Txid: msg.Txid} } } @@ -674,19 +674,19 @@ func (handler *Handler) handleRangeQueryState(msg *pb.ChaincodeMessage) { // 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() { - // Check if this is the unique state request from this chaincode uuid - uniqueReq := handler.createUUIDEntry(msg.Uuid) + // 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 Uuid. Cannot process.") + chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.") return } var serialSendMsg *pb.ChaincodeMessage defer func() { - handler.deleteUUIDEntry(msg.Uuid) - chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shortuuid(serialSendMsg.Uuid), serialSendMsg.Type) + handler.deleteTXIDEntry(msg.Txid) + chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type) handler.serialSend(serialSendMsg) }() @@ -695,7 +695,7 @@ func (handler *Handler) handleRangeQueryState(msg *pb.ChaincodeMessage) { if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) chaincodeLogger.Errorf("Failed to unmarshall range query request. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } @@ -706,24 +706,24 @@ func (handler *Handler) handleRangeQueryState(msg *pb.ChaincodeMessage) { // Send error msg back to chaincode. GetState will not trigger event payload := []byte(ledgerErr.Error()) chaincodeLogger.Errorf("Failed to get ledger. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } chaincodeID := handler.ChaincodeID.Name - readCommittedState := !handler.getIsTransaction(msg.Uuid) + readCommittedState := !handler.getIsTransaction(msg.Txid) rangeIter, err := ledger.GetStateRangeScanIterator(chaincodeID, rangeQueryState.StartKey, rangeQueryState.EndKey, readCommittedState) 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, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } iterID := util.GenerateUUID() - txContext := handler.getTxContext(msg.Uuid) + txContext := handler.getTxContext(msg.Txid) handler.putRangeQueryIterator(txContext, iterID, rangeIter) hasNext = rangeIter.Next() @@ -733,11 +733,11 @@ func (handler *Handler) handleRangeQueryState(msg *pb.ChaincodeMessage) { for ; hasNext && i < maxRangeQueryStateLimit; i++ { key, value := rangeIter.GetKeyValue() // Decrypt the data if the confidential is enabled - decryptedValue, decryptErr := handler.decrypt(msg.Uuid, value) + decryptedValue, decryptErr := handler.decrypt(msg.Txid, value) if decryptErr != nil { payload := []byte(decryptErr.Error()) chaincodeLogger.Errorf("Failed decrypt value. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} rangeIter.Close() handler.deleteRangeQueryIterator(txContext, iterID) @@ -764,12 +764,12 @@ func (handler *Handler) handleRangeQueryState(msg *pb.ChaincodeMessage) { // 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) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid} }() } @@ -794,19 +794,19 @@ func (handler *Handler) handleRangeQueryStateNext(msg *pb.ChaincodeMessage) { // 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() { - // Check if this is the unique state request from this chaincode uuid - uniqueReq := handler.createUUIDEntry(msg.Uuid) + // Check if this is the unique state request from this chaincode txid + uniqueReq := handler.createTXIDEntry(msg.Txid) if !uniqueReq { // Drop this request - chaincodeLogger.Debug("Another state request pending for this Uuid. Cannot process.") + chaincodeLogger.Debug("Another state request pending for this Txid. Cannot process.") return } var serialSendMsg *pb.ChaincodeMessage defer func() { - handler.deleteUUIDEntry(msg.Uuid) - chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shortuuid(serialSendMsg.Uuid), serialSendMsg.Type) + handler.deleteTXIDEntry(msg.Txid) + chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type) handler.serialSend(serialSendMsg) }() @@ -815,17 +815,17 @@ func (handler *Handler) handleRangeQueryStateNext(msg *pb.ChaincodeMessage) { if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) chaincodeLogger.Errorf("Failed to unmarshall state range next query request. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } - txContext := handler.getTxContext(msg.Uuid) + txContext := handler.getTxContext(msg.Txid) rangeIter := handler.getRangeQueryIterator(txContext, rangeQueryStateNext.ID) if rangeIter == nil { payload := []byte("Range query iterator not found") chaincodeLogger.Errorf("Range query iterator not found. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } @@ -835,11 +835,11 @@ func (handler *Handler) handleRangeQueryStateNext(msg *pb.ChaincodeMessage) { for ; hasNext && i < maxRangeQueryStateLimit; i++ { key, value := rangeIter.GetKeyValue() // Decrypt the data if the confidential is enabled - decryptedValue, decryptErr := handler.decrypt(msg.Uuid, value) + decryptedValue, decryptErr := handler.decrypt(msg.Txid, value) if decryptErr != nil { payload := []byte(decryptErr.Error()) chaincodeLogger.Errorf("Failed decrypt value. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} rangeIter.Close() handler.deleteRangeQueryIterator(txContext, rangeQueryStateNext.ID) @@ -866,12 +866,12 @@ func (handler *Handler) handleRangeQueryStateNext(msg *pb.ChaincodeMessage) { // 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) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } chaincodeLogger.Debugf("Got keys and values. Sending %s", pb.ChaincodeMessage_RESPONSE) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid} }() } @@ -896,19 +896,19 @@ func (handler *Handler) handleRangeQueryStateClose(msg *pb.ChaincodeMessage) { // 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() { - // Check if this is the unique state request from this chaincode uuid - uniqueReq := handler.createUUIDEntry(msg.Uuid) + // 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 Uuid. Cannot process.") + chaincodeLogger.Error("Another state request pending for this Txid. Cannot process.") return } var serialSendMsg *pb.ChaincodeMessage defer func() { - handler.deleteUUIDEntry(msg.Uuid) - chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shortuuid(serialSendMsg.Uuid), serialSendMsg.Type) + handler.deleteTXIDEntry(msg.Txid) + chaincodeLogger.Debugf("[%s]handleRangeQueryState serial send %s", shorttxid(serialSendMsg.Txid), serialSendMsg.Type) handler.serialSend(serialSendMsg) }() @@ -917,11 +917,11 @@ func (handler *Handler) handleRangeQueryStateClose(msg *pb.ChaincodeMessage) { if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) chaincodeLogger.Errorf("Failed to unmarshall state range query close request. Sending %s", pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } - txContext := handler.getTxContext(msg.Uuid) + txContext := handler.getTxContext(msg.Txid) iter := handler.getRangeQueryIterator(txContext, rangeQueryStateClose.ID) if iter != nil { iter.Close() @@ -935,12 +935,12 @@ func (handler *Handler) handleRangeQueryStateClose(msg *pb.ChaincodeMessage) { // 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) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } chaincodeLogger.Debugf("Closed. Sending %s", pb.ChaincodeMessage_RESPONSE) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: payloadBytes, Txid: msg.Txid} }() } @@ -985,29 +985,29 @@ func (handler *Handler) afterInvokeChaincode(e *fsm.Event, state string) { func (handler *Handler) enterBusyState(e *fsm.Event, state string) { go func() { msg, _ := e.Args[0].(*pb.ChaincodeMessage) - // First check if this UUID is a transaction; error otherwise - if !handler.getIsTransaction(msg.Uuid) { + // First check if this TXID is a transaction; error otherwise + if !handler.getIsTransaction(msg.Txid) { payload := []byte(fmt.Sprintf("Cannot handle %s in query context", msg.Type.String())) - chaincodeLogger.Errorf("[%s]Cannot handle %s in query context. Sending %s", shortuuid(msg.Uuid), msg.Type.String(), pb.ChaincodeMessage_ERROR) - errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]Cannot handle %s in query context. Sending %s", shorttxid(msg.Txid), msg.Type.String(), pb.ChaincodeMessage_ERROR) + errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} handler.triggerNextState(errMsg, true) return } - chaincodeLogger.Debugf("[%s]state is %s", shortuuid(msg.Uuid), state) - // Check if this is the unique request from this chaincode uuid - uniqueReq := handler.createUUIDEntry(msg.Uuid) + chaincodeLogger.Debugf("[%s]state is %s", shorttxid(msg.Txid), state) + // Check if this is the unique request from this chaincode txid + uniqueReq := handler.createTXIDEntry(msg.Txid) if !uniqueReq { // Drop this request - chaincodeLogger.Error("Another request pending for this Uuid. Cannot process.") + chaincodeLogger.Debug("Another request pending for this Txid. Cannot process.") return } var triggerNextStateMsg *pb.ChaincodeMessage defer func() { - handler.deleteUUIDEntry(msg.Uuid) - chaincodeLogger.Debugf("[%s]enterBusyState trigger event %s", shortuuid(triggerNextStateMsg.Uuid), triggerNextStateMsg.Type) + handler.deleteTXIDEntry(msg.Txid) + chaincodeLogger.Debugf("[%s]enterBusyState trigger event %s", shorttxid(triggerNextStateMsg.Txid), triggerNextStateMsg.Type) handler.triggerNextState(triggerNextStateMsg, true) }() @@ -1015,8 +1015,8 @@ func (handler *Handler) enterBusyState(e *fsm.Event, state string) { if ledgerErr != nil { // Send error msg back to chaincode and trigger event payload := []byte(ledgerErr.Error()) - chaincodeLogger.Errorf("[%s]Failed to handle %s. Sending %s", shortuuid(msg.Uuid), msg.Type.String(), pb.ChaincodeMessage_ERROR) - triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%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} return } @@ -1029,14 +1029,14 @@ func (handler *Handler) enterBusyState(e *fsm.Event, state string) { unmarshalErr := proto.Unmarshal(msg.Payload, putStateInfo) if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) - chaincodeLogger.Errorf("[%s]Unable to decipher payload. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } var pVal []byte // Encrypt the data if the confidential is enabled - if pVal, err = handler.encrypt(msg.Uuid, putStateInfo.Value); err == nil { + if pVal, err = handler.encrypt(msg.Txid, putStateInfo.Value); err == nil { // Invoke ledger to put state err = ledgerObj.SetState(chaincodeID, putStateInfo.Key, pVal) } @@ -1046,15 +1046,15 @@ func (handler *Handler) enterBusyState(e *fsm.Event, state string) { err = ledgerObj.DeleteState(chaincodeID, key) } else if msg.Type.String() == pb.ChaincodeMessage_INVOKE_CHAINCODE.String() { //check and prohibit C-call-C for CONFIDENTIAL txs - if triggerNextStateMsg = handler.canCallChaincode(msg.Uuid); triggerNextStateMsg != nil { + if triggerNextStateMsg = handler.canCallChaincode(msg.Txid); triggerNextStateMsg != nil { return } chaincodeSpec := &pb.ChaincodeSpec{} unmarshalErr := proto.Unmarshal(msg.Payload, chaincodeSpec) if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) - chaincodeLogger.Errorf("[%s]Unable to decipher payload. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } @@ -1063,21 +1063,21 @@ func (handler *Handler) enterBusyState(e *fsm.Event, state string) { // Create the transaction object chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: chaincodeSpec} - transaction, _ := pb.NewChaincodeExecute(chaincodeInvocationSpec, msg.Uuid, pb.Transaction_CHAINCODE_INVOKE) + transaction, _ := pb.NewChaincodeExecute(chaincodeInvocationSpec, msg.Txid, pb.Transaction_CHAINCODE_INVOKE) // Launch the new chaincode if not already running _, chaincodeInput, launchErr := handler.chaincodeSupport.Launch(context.Background(), transaction) if launchErr != nil { payload := []byte(launchErr.Error()) - chaincodeLogger.Errorf("[%s]Failed to launch invoked chaincode. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } // TODO: Need to handle timeout correctly timeout := time.Duration(30000) * time.Millisecond - ccMsg, _ := createTransactionMessage(transaction.Uuid, chaincodeInput) + ccMsg, _ := createTransactionMessage(transaction.Txid, chaincodeInput) // Execute the chaincode //NOTE: when confidential C-call-C is understood, transaction should have the correct sec context for enc/dec @@ -1096,14 +1096,14 @@ func (handler *Handler) enterBusyState(e *fsm.Event, state string) { if err != nil { // Send error msg back to chaincode and trigger event payload := []byte(err.Error()) - chaincodeLogger.Errorf("[%s]Failed to handle %s. Sending %s", shortuuid(msg.Uuid), msg.Type.String(), pb.ChaincodeMessage_ERROR) - triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } // Send response msg back to chaincode. - chaincodeLogger.Debugf("[%s]Completed %s. Sending %s", shortuuid(msg.Uuid), msg.Type.String(), pb.ChaincodeMessage_RESPONSE) - triggerNextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: res, Uuid: msg.Uuid} + 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} }() } @@ -1117,13 +1117,13 @@ func (handler *Handler) enterInitState(e *fsm.Event, state string) { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]Entered state %s", shortuuid(ccMsg.Uuid), state) + chaincodeLogger.Debugf("[%s]Entered state %s", shorttxid(ccMsg.Txid), state) //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 - handler.markIsTransaction(ccMsg.Uuid, true) + handler.markIsTransaction(ccMsg.Txid, true) if err := handler.serialSend(ccMsg); err != nil { - errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(fmt.Sprintf("Error sending %s: %s", pb.ChaincodeMessage_INIT, err)), Uuid: ccMsg.Uuid} + errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: []byte(fmt.Sprintf("Error sending %s: %s", pb.ChaincodeMessage_INIT, err)), Txid: ccMsg.Txid} handler.notify(errMsg) } } @@ -1136,18 +1136,18 @@ func (handler *Handler) enterReadyState(e *fsm.Event, state string) { //it is needed by the event system to filter clients by if ok && msg.ChaincodeEvent != nil && msg.ChaincodeEvent.Payload != nil { var err error - if msg.Payload, err = handler.encrypt(msg.Uuid, msg.Payload); nil != err { - chaincodeLogger.Errorf("[%s]Failed to encrypt chaincode event payload", msg.Uuid) + if msg.Payload, err = handler.encrypt(msg.Txid, msg.Payload); nil != err { + chaincodeLogger.Errorf("[%s]Failed to encrypt chaincode event payload", msg.Txid) msg.Payload = []byte(fmt.Sprintf("Failed to encrypt chaincode event payload %s", err.Error())) msg.Type = pb.ChaincodeMessage_ERROR } } - handler.deleteIsTransaction(msg.Uuid) + handler.deleteIsTransaction(msg.Txid) if !ok { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]Entered state %s", shortuuid(msg.Uuid), state) + chaincodeLogger.Debugf("[%s]Entered state %s", shorttxid(msg.Txid), state) handler.notify(msg) } @@ -1155,12 +1155,12 @@ func (handler *Handler) enterEndState(e *fsm.Event, state string) { defer handler.deregister() // Now notify msg, ok := e.Args[0].(*pb.ChaincodeMessage) - handler.deleteIsTransaction(msg.Uuid) + handler.deleteIsTransaction(msg.Txid) if !ok { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]Entered state %s", shortuuid(msg.Uuid), state) + chaincodeLogger.Debugf("[%s]Entered state %s", shorttxid(msg.Txid), state) handler.notify(msg) e.Cancel(fmt.Errorf("Entered end state")) } @@ -1258,11 +1258,11 @@ func (handler *Handler) setChaincodeSecurityContext(tx *pb.Transaction, msg *pb. //if initArgs is set (should be for "deploy" only) move to Init //else move to ready -func (handler *Handler) initOrReady(uuid string, f *string, initArgs []string, tx *pb.Transaction, depTx *pb.Transaction) (chan *pb.ChaincodeMessage, error) { +func (handler *Handler) initOrReady(txid string, f *string, initArgs []string, tx *pb.Transaction, depTx *pb.Transaction) (chan *pb.ChaincodeMessage, error) { var ccMsg *pb.ChaincodeMessage var send bool - txctx, funcErr := handler.createTxContext(uuid, tx) + txctx, funcErr := handler.createTxContext(txid, tx) if funcErr != nil { return nil, funcErr } @@ -1278,19 +1278,19 @@ func (handler *Handler) initOrReady(uuid string, f *string, initArgs []string, t funcArgsMsg := &pb.ChaincodeInput{Function: f2, Args: initArgs} var payload []byte if payload, funcErr = proto.Marshal(funcArgsMsg); funcErr != nil { - handler.deleteTxContext(uuid) + handler.deleteTxContext(txid) return nil, fmt.Errorf("Failed to marshall %s : %s\n", ccMsg.Type.String(), funcErr) } - ccMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INIT, Payload: payload, Uuid: uuid} + ccMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INIT, Payload: payload, Txid: txid} send = false } else { chaincodeLogger.Debug("sending READY") - ccMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_READY, Uuid: uuid} + ccMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_READY, Txid: txid} send = true } if err := handler.initializeSecContext(tx, depTx); err != nil { - handler.deleteTxContext(uuid) + handler.deleteTxContext(txid) return nil, err } @@ -1307,23 +1307,23 @@ func (handler *Handler) initOrReady(uuid string, f *string, initArgs []string, t // Handles request to query another chaincode func (handler *Handler) handleQueryChaincode(msg *pb.ChaincodeMessage) { go func() { - // Check if this is the unique request from this chaincode uuid - uniqueReq := handler.createUUIDEntry(msg.Uuid) + // Check if this is the unique request from this chaincode txid + uniqueReq := handler.createTXIDEntry(msg.Txid) if !uniqueReq { // Drop this request - chaincodeLogger.Errorf("[%s]Another request pending for this Uuid. Cannot process.", shortuuid(msg.Uuid)) + chaincodeLogger.Debugf("[%s]Another request pending for this Txid. Cannot process.", shorttxid(msg.Txid)) return } var serialSendMsg *pb.ChaincodeMessage defer func() { - handler.deleteUUIDEntry(msg.Uuid) + handler.deleteTXIDEntry(msg.Txid) handler.serialSend(serialSendMsg) }() //check and prohibit C-call-C for CONFIDENTIAL txs - if serialSendMsg = handler.canCallChaincode(msg.Uuid); serialSendMsg != nil { + if serialSendMsg = handler.canCallChaincode(msg.Txid); serialSendMsg != nil { return } @@ -1331,8 +1331,8 @@ func (handler *Handler) handleQueryChaincode(msg *pb.ChaincodeMessage) { unmarshalErr := proto.Unmarshal(msg.Payload, chaincodeSpec) if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) - chaincodeLogger.Errorf("[%s]Unable to decipher payload. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } @@ -1341,21 +1341,21 @@ func (handler *Handler) handleQueryChaincode(msg *pb.ChaincodeMessage) { // Create the transaction object chaincodeInvocationSpec := &pb.ChaincodeInvocationSpec{ChaincodeSpec: chaincodeSpec} - transaction, _ := pb.NewChaincodeExecute(chaincodeInvocationSpec, msg.Uuid, pb.Transaction_CHAINCODE_QUERY) + transaction, _ := pb.NewChaincodeExecute(chaincodeInvocationSpec, msg.Txid, pb.Transaction_CHAINCODE_QUERY) // Launch the new chaincode if not already running _, chaincodeInput, launchErr := handler.chaincodeSupport.Launch(context.Background(), transaction) if launchErr != nil { payload := []byte(launchErr.Error()) - chaincodeLogger.Errorf("[%s]Failed to launch invoked chaincode. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } // TODO: Need to handle timeout correctly timeout := time.Duration(30000) * time.Millisecond - ccMsg, _ := createQueryMessage(transaction.Uuid, chaincodeInput) + ccMsg, _ := createQueryMessage(transaction.Txid, chaincodeInput) // Query the chaincode //NOTE: when confidential C-call-C is understood, transaction should have the correct sec context for enc/dec @@ -1364,8 +1364,8 @@ func (handler *Handler) handleQueryChaincode(msg *pb.ChaincodeMessage) { if execErr != nil { // Send error msg back to chaincode and trigger event payload := []byte(execErr.Error()) - chaincodeLogger.Errorf("[%s]Failed to handle %s. Sending %s", shortuuid(msg.Uuid), msg.Type.String(), pb.ChaincodeMessage_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + 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} return } @@ -1374,63 +1374,63 @@ func (handler *Handler) handleQueryChaincode(msg *pb.ChaincodeMessage) { //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 { - chaincodeLogger.Errorf("[%s]Error marshaling response. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Error marshaling response. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR) payload := []byte(execErr.Error()) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} } else { - chaincodeLogger.Debugf("[%s]Completed %s. Sending %s", shortuuid(msg.Uuid), msg.Type.String(), pb.ChaincodeMessage_RESPONSE) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RESPONSE, Payload: respBytes, Uuid: msg.Uuid} + 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} } }() } // HandleMessage implementation of MessageHandler interface. Peer's handling of Chaincode messages. func (handler *Handler) HandleMessage(msg *pb.ChaincodeMessage) error { - chaincodeLogger.Debugf("[%s]Handling ChaincodeMessage of type: %s in state %s", shortuuid(msg.Uuid), msg.Type, handler.FSM.Current()) + chaincodeLogger.Debugf("[%s]Handling ChaincodeMessage of type: %s in state %s", shorttxid(msg.Txid), msg.Type, handler.FSM.Current()) //QUERY_COMPLETED message can happen ONLY for Transaction_QUERY (stateless) if msg.Type == pb.ChaincodeMessage_QUERY_COMPLETED { - chaincodeLogger.Debugf("[%s]HandleMessage- QUERY_COMPLETED. Notify", msg.Uuid) - handler.deleteIsTransaction(msg.Uuid) + chaincodeLogger.Debugf("[%s]HandleMessage- QUERY_COMPLETED. Notify", msg.Txid) + handler.deleteIsTransaction(msg.Txid) var err error - if msg.Payload, err = handler.encrypt(msg.Uuid, msg.Payload); nil != err { - chaincodeLogger.Errorf("[%s]Failed to encrypt query result %s", msg.Uuid, string(msg.Payload)) + 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)) 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 { - chaincodeLogger.Debugf("[%s]HandleMessage- QUERY_ERROR (%s). Notify", msg.Uuid, string(msg.Payload)) - handler.deleteIsTransaction(msg.Uuid) + chaincodeLogger.Debugf("[%s]HandleMessage- QUERY_ERROR (%s). Notify", msg.Txid, string(msg.Payload)) + handler.deleteIsTransaction(msg.Txid) handler.notify(msg) return nil } else if msg.Type == pb.ChaincodeMessage_INVOKE_QUERY { // Received request to query another chaincode from shim - chaincodeLogger.Debugf("[%s]HandleMessage- Received request to query another chaincode", msg.Uuid) + chaincodeLogger.Debugf("[%s]HandleMessage- Received request to query another chaincode", msg.Txid) 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() { - // Check if this UUID is a transaction - if !handler.getIsTransaction(msg.Uuid) { - payload := []byte(fmt.Sprintf("[%s]Cannot handle %s in query context", msg.Uuid, msg.Type.String())) - chaincodeLogger.Errorf("[%s]Cannot handle %s in query context. Sending %s", msg.Uuid, msg.Type.String(), pb.ChaincodeMessage_ERROR) - errMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + // 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} handler.serialSend(errMsg) return fmt.Errorf("Cannot handle %s in query context", msg.Type.String()) } } // Other errors - return fmt.Errorf("[%s]Chaincode handler validator FSM cannot handle message (%s) with payload size (%d) while in state: %s", msg.Uuid, msg.Type.String(), len(msg.Payload), handler.FSM.Current()) + 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()) } eventErr := handler.FSM.Event(msg.Type.String(), msg) filteredErr := filterError(eventErr) if filteredErr != nil { - chaincodeLogger.Errorf("[%s]Failed to trigger FSM event %s: %s", msg.Uuid, msg.Type.String(), filteredErr) + chaincodeLogger.Errorf("[%s]Failed to trigger FSM event %s: %s", msg.Txid, msg.Type.String(), filteredErr) } return filteredErr @@ -1458,17 +1458,17 @@ func filterError(errFromFSMEvent error) error { } func (handler *Handler) sendExecuteMessage(msg *pb.ChaincodeMessage, tx *pb.Transaction) (chan *pb.ChaincodeMessage, error) { - txctx, err := handler.createTxContext(msg.Uuid, tx) + txctx, err := handler.createTxContext(msg.Txid, tx) if err != nil { return nil, err } - // Mark UUID as either transaction or query - chaincodeLogger.Debugf("[%s]Inside sendExecuteMessage. Message %s", shortuuid(msg.Uuid), msg.Type.String()) + // Mark TXID as either transaction or query + chaincodeLogger.Debugf("[%s]Inside sendExecuteMessage. Message %s", shorttxid(msg.Txid), msg.Type.String()) if msg.Type.String() == pb.ChaincodeMessage_QUERY.String() { - handler.markIsTransaction(msg.Uuid, false) + handler.markIsTransaction(msg.Txid, false) } else { - handler.markIsTransaction(msg.Uuid, true) + handler.markIsTransaction(msg.Txid, true) } //if security is disabled the context elements will just be nil @@ -1478,14 +1478,14 @@ func (handler *Handler) sendExecuteMessage(msg *pb.ChaincodeMessage, tx *pb.Tran // Trigger FSM event if it is a transaction if msg.Type.String() == pb.ChaincodeMessage_TRANSACTION.String() { - chaincodeLogger.Debugf("[%s]sendExecuteMsg trigger event %s", shortuuid(msg.Uuid), msg.Type) + chaincodeLogger.Debugf("[%s]sendExecuteMsg trigger event %s", shorttxid(msg.Txid), msg.Type) handler.triggerNextState(msg, true) } else { // Send the message to shim - chaincodeLogger.Debugf("[%s]sending query", shortuuid(msg.Uuid)) + chaincodeLogger.Debugf("[%s]sending query", shorttxid(msg.Txid)) if err = handler.serialSend(msg); err != nil { - handler.deleteTxContext(msg.Uuid) - return nil, fmt.Errorf("[%s]SendMessage error sending (%s)", shortuuid(msg.Uuid), err) + handler.deleteTxContext(msg.Txid) + return nil, fmt.Errorf("[%s]SendMessage error sending (%s)", shorttxid(msg.Txid), err) } } @@ -1508,22 +1508,22 @@ func (handler *Handler) isRunning() bool { /**************** func (handler *Handler) initEvent() (chan *pb.ChaincodeMessage, error) { if handler.responseNotifiers == nil { - return nil,fmt.Errorf("SendMessage called before registration for Uuid:%s", msg.Uuid) + return nil,fmt.Errorf("SendMessage called before registration for Txid:%s", msg.Txid) } var notfy chan *pb.ChaincodeMessage handler.Lock() - if handler.responseNotifiers[msg.Uuid] != nil { + if handler.responseNotifiers[msg.Txid] != nil { handler.Unlock() - return nil, fmt.Errorf("SendMessage Uuid:%s exists", msg.Uuid) + return nil, fmt.Errorf("SendMessage Txid:%s exists", msg.Txid) } //note the explicit use of buffer 1. We won't block if the receiver times outi and does not wait //for our response - handler.responseNotifiers[msg.Uuid] = make(chan *pb.ChaincodeMessage, 1) + handler.responseNotifiers[msg.Txid] = make(chan *pb.ChaincodeMessage, 1) handler.Unlock() if err := c.serialSend(msg); err != nil { - deleteNotifier(msg.Uuid) - return nil, fmt.Errorf("SendMessage error sending %s(%s)", msg.Uuid, err) + deleteNotifier(msg.Txid) + return nil, fmt.Errorf("SendMessage error sending %s(%s)", msg.Txid, err) } return notfy, nil } diff --git a/core/chaincode/shim/chaincode.go b/core/chaincode/shim/chaincode.go index 1dbefaa4d13..4753c0995c1 100644 --- a/core/chaincode/shim/chaincode.go +++ b/core/chaincode/shim/chaincode.go @@ -208,14 +208,14 @@ func chatWithPeer(chaincodename string, stream PeerChaincodeStream, cc Chaincode chaincodeLogger.Debug("Received nil message, ending chaincode stream") return } - chaincodeLogger.Debugf("[%s]Received message %s from shim", shortuuid(in.Uuid), in.Type.String()) + chaincodeLogger.Debugf("[%s]Received message %s from shim", shorttxid(in.Txid), in.Type.String()) recv = true case nsInfo = <-handler.nextState: in = nsInfo.msg if in == nil { panic("nil msg") } - chaincodeLogger.Debugf("[%s]Move state message %s", shortuuid(in.Uuid), in.Type.String()) + chaincodeLogger.Debugf("[%s]Move state message %s", shorttxid(in.Txid), in.Type.String()) } // Call FSM.handleMessage() @@ -230,7 +230,7 @@ func chatWithPeer(chaincodename string, stream PeerChaincodeStream, cc Chaincode if in.Type == pb.ChaincodeMessage_KEEPALIVE { chaincodeLogger.Debug("Sending KEEPALIVE response") } else { - chaincodeLogger.Debugf("[%s]send state message %s", shortuuid(in.Uuid), in.Type.String()) + chaincodeLogger.Debugf("[%s]send state message %s", shorttxid(in.Txid), in.Type.String()) } if err = handler.serialSend(in); err != nil { err = fmt.Errorf("Error sending %s: %s", in.Type.String(), err) diff --git a/core/chaincode/shim/handler.go b/core/chaincode/shim/handler.go index f6975c19849..05a3ce0f96f 100644 --- a/core/chaincode/shim/handler.go +++ b/core/chaincode/shim/handler.go @@ -51,42 +51,42 @@ type Handler struct { ChatStream PeerChaincodeStream FSM *fsm.FSM cc Chaincode - // Multiple queries (and one transaction) with different Uuids can be executing in parallel for this chaincode + // Multiple queries (and one transaction) with different txids can be executing in parallel for this chaincode // responseChannel is the channel on which responses are communicated by the shim to the chaincodeStub. responseChannel map[string]chan pb.ChaincodeMessage - // Track which UUIDs are transactions and which are queries, to decide whether get/put state and invoke chaincode are allowed. + // Track which TXIDs are transactions and which are queries, to decide whether get/put state and invoke chaincode are allowed. isTransaction map[string]bool nextState chan *nextStateInfo } -func shortuuid(uuid string) string { - if len(uuid) < 8 { - return uuid +func shorttxid(txid string) string { + if len(txid) < 8 { + return txid } - return uuid[0:8] + return txid[0:8] } func (handler *Handler) serialSend(msg *pb.ChaincodeMessage) error { handler.serialLock.Lock() defer handler.serialLock.Unlock() if err := handler.ChatStream.Send(msg); err != nil { - chaincodeLogger.Errorf("[%s]Error sending %s: %s", shortuuid(msg.Uuid), msg.Type.String(), err) + chaincodeLogger.Errorf("[%s]Error sending %s: %s", shorttxid(msg.Txid), msg.Type.String(), err) return fmt.Errorf("Error sending %s: %s", msg.Type.String(), err) } return nil } -func (handler *Handler) createChannel(uuid string) (chan pb.ChaincodeMessage, error) { +func (handler *Handler) createChannel(txid string) (chan pb.ChaincodeMessage, error) { handler.Lock() defer handler.Unlock() if handler.responseChannel == nil { - return nil, fmt.Errorf("[%s]Cannot create response channel", shortuuid(uuid)) + return nil, fmt.Errorf("[%s]Cannot create response channel", shorttxid(txid)) } - if handler.responseChannel[uuid] != nil { - return nil, fmt.Errorf("[%s]Channel exists", shortuuid(uuid)) + if handler.responseChannel[txid] != nil { + return nil, fmt.Errorf("[%s]Channel exists", shorttxid(txid)) } c := make(chan pb.ChaincodeMessage) - handler.responseChannel[uuid] = c + handler.responseChannel[txid] = c return c, nil } @@ -94,15 +94,15 @@ func (handler *Handler) sendChannel(msg *pb.ChaincodeMessage) error { handler.Lock() defer handler.Unlock() if handler.responseChannel == nil { - return fmt.Errorf("[%s]Cannot send message response channel", shortuuid(msg.Uuid)) + return fmt.Errorf("[%s]Cannot send message response channel", shorttxid(msg.Txid)) } - if handler.responseChannel[msg.Uuid] == nil { - return fmt.Errorf("[%s]sendChannel does not exist", shortuuid(msg.Uuid)) + if handler.responseChannel[msg.Txid] == nil { + return fmt.Errorf("[%s]sendChannel does not exist", shorttxid(msg.Txid)) } - chaincodeLogger.Debugf("[%s]before send", shortuuid(msg.Uuid)) - handler.responseChannel[msg.Uuid] <- *msg - chaincodeLogger.Debugf("[%s]after send", shortuuid(msg.Uuid)) + chaincodeLogger.Debugf("[%s]before send", shorttxid(msg.Txid)) + handler.responseChannel[msg.Txid] <- *msg + chaincodeLogger.Debugf("[%s]after send", shorttxid(msg.Txid)) return nil } @@ -112,29 +112,29 @@ func (handler *Handler) receiveChannel(c chan pb.ChaincodeMessage) (pb.Chaincode return msg, val } -func (handler *Handler) deleteChannel(uuid string) { +func (handler *Handler) deleteChannel(txid string) { handler.Lock() defer handler.Unlock() if handler.responseChannel != nil { - delete(handler.responseChannel, uuid) + delete(handler.responseChannel, txid) } } -// markIsTransaction marks a UUID as a transaction or a query; true = transaction, false = query -func (handler *Handler) markIsTransaction(uuid string, isTrans bool) bool { +// markIsTransaction marks a TXID as a transaction or a query; true = transaction, false = query +func (handler *Handler) markIsTransaction(txid string, isTrans bool) bool { if handler.isTransaction == nil { return false } handler.Lock() defer handler.Unlock() - handler.isTransaction[uuid] = isTrans + handler.isTransaction[txid] = isTrans return true } -func (handler *Handler) deleteIsTransaction(uuid string) { +func (handler *Handler) deleteIsTransaction(txid string) { handler.Lock() if handler.isTransaction != nil { - delete(handler.isTransaction, uuid) + delete(handler.isTransaction, txid) } handler.Unlock() } @@ -211,34 +211,34 @@ func (handler *Handler) handleInit(msg *pb.ChaincodeMessage) { if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) // Send ERROR message to chaincode support and change state - chaincodeLogger.Debugf("[%s]Incorrect payload format. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]Incorrect payload format. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR) + nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } // Mark as a transaction (allow put/del state) - handler.markIsTransaction(msg.Uuid, true) + handler.markIsTransaction(msg.Txid, true) // Call chaincode's Run // Create the ChaincodeStub which the chaincode can use to callback stub := new(ChaincodeStub) - stub.init(msg.Uuid, msg.SecurityContext) + stub.init(msg.Txid, msg.SecurityContext) res, err := handler.cc.Init(stub, input.Function, input.Args) // delete isTransaction entry - handler.deleteIsTransaction(msg.Uuid) + handler.deleteIsTransaction(msg.Txid) if err != nil { payload := []byte(err.Error()) // Send ERROR message to chaincode support and change state - chaincodeLogger.Errorf("[%s]Init failed. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid, ChaincodeEvent: stub.chaincodeEvent} + chaincodeLogger.Errorf("[%s]Init failed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR) + nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid, ChaincodeEvent: stub.chaincodeEvent} return } // Send COMPLETED message to chaincode support and change state - nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_COMPLETED, Payload: res, Uuid: msg.Uuid, ChaincodeEvent: stub.chaincodeEvent} - chaincodeLogger.Debugf("[%s]Init succeeded. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_COMPLETED) + nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_COMPLETED, Payload: res, Txid: msg.Txid, ChaincodeEvent: stub.chaincodeEvent} + chaincodeLogger.Debugf("[%s]Init succeeded. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_COMPLETED) }() } @@ -250,7 +250,7 @@ func (handler *Handler) enterInitState(e *fsm.Event) { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]Received %s, initializing chaincode", shortuuid(msg.Uuid), msg.Type.String()) + chaincodeLogger.Debugf("[%s]Received %s, initializing chaincode", shorttxid(msg.Txid), msg.Type.String()) if msg.Type.String() == pb.ChaincodeMessage_INIT.String() { // Call the chaincode's Run function to initialize handler.handleInit(msg) @@ -278,34 +278,34 @@ func (handler *Handler) handleTransaction(msg *pb.ChaincodeMessage) { if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) // Send ERROR message to chaincode support and change state - chaincodeLogger.Debugf("[%s]Incorrect payload format. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]Incorrect payload format. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR) + nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} return } // Mark as a transaction (allow put/del state) - handler.markIsTransaction(msg.Uuid, true) + handler.markIsTransaction(msg.Txid, true) // Call chaincode's Run // Create the ChaincodeStub which the chaincode can use to callback stub := new(ChaincodeStub) - stub.init(msg.Uuid, msg.SecurityContext) + stub.init(msg.Txid, msg.SecurityContext) res, err := handler.cc.Invoke(stub, input.Function, input.Args) // delete isTransaction entry - handler.deleteIsTransaction(msg.Uuid) + handler.deleteIsTransaction(msg.Txid) if err != nil { payload := []byte(err.Error()) // Send ERROR message to chaincode support and change state - chaincodeLogger.Errorf("[%s]Transaction execution failed. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_ERROR) - nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid, ChaincodeEvent: stub.chaincodeEvent} + chaincodeLogger.Errorf("[%s]Transaction execution failed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_ERROR) + nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid, ChaincodeEvent: stub.chaincodeEvent} return } // Send COMPLETED message to chaincode support and change state - chaincodeLogger.Debugf("[%s]Transaction completed. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_COMPLETED) - nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_COMPLETED, Payload: res, Uuid: msg.Uuid, ChaincodeEvent: stub.chaincodeEvent} + chaincodeLogger.Debugf("[%s]Transaction completed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_COMPLETED) + nextStateMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_COMPLETED, Payload: res, Txid: msg.Txid, ChaincodeEvent: stub.chaincodeEvent} }() } @@ -325,34 +325,34 @@ func (handler *Handler) handleQuery(msg *pb.ChaincodeMessage) { if unmarshalErr != nil { payload := []byte(unmarshalErr.Error()) // Send ERROR message to chaincode support and change state - chaincodeLogger.Debugf("[%s]Incorrect payload format. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_QUERY_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]Incorrect payload format. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_ERROR) + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_ERROR, Payload: payload, Txid: msg.Txid} return } // Mark as a query (do not allow put/del state) - handler.markIsTransaction(msg.Uuid, false) + handler.markIsTransaction(msg.Txid, false) // Call chaincode's Query // Create the ChaincodeStub which the chaincode can use to callback stub := new(ChaincodeStub) - stub.init(msg.Uuid, msg.SecurityContext) + stub.init(msg.Txid, msg.SecurityContext) res, err := handler.cc.Query(stub, input.Function, input.Args) // delete isTransaction entry - handler.deleteIsTransaction(msg.Uuid) + handler.deleteIsTransaction(msg.Txid) if err != nil { payload := []byte(err.Error()) // Send ERROR message to chaincode support and change state - chaincodeLogger.Errorf("[%s]Query execution failed. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_QUERY_ERROR) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_ERROR, Payload: payload, Uuid: msg.Uuid} + chaincodeLogger.Errorf("[%s]Query execution failed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_ERROR) + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_ERROR, Payload: payload, Txid: msg.Txid} return } // Send COMPLETED message to chaincode support - chaincodeLogger.Debugf("[%s]Query completed. Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_QUERY_COMPLETED) - serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_COMPLETED, Payload: res, Uuid: msg.Uuid} + chaincodeLogger.Debugf("[%s]Query completed. Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_QUERY_COMPLETED) + serialSendMsg = &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_QUERY_COMPLETED, Payload: res, Txid: msg.Txid} }() } @@ -363,7 +363,7 @@ func (handler *Handler) enterTransactionState(e *fsm.Event) { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]Received %s, invoking transaction on chaincode(Src:%s, Dst:%s)", shortuuid(msg.Uuid), msg.Type.String(), e.Src, e.Dst) + chaincodeLogger.Debugf("[%s]Received %s, invoking transaction on chaincode(Src:%s, Dst:%s)", shorttxid(msg.Txid), msg.Type.String(), e.Src, e.Dst) if msg.Type.String() == pb.ChaincodeMessage_TRANSACTION.String() { // Call the chaincode's Run function to invoke transaction handler.handleTransaction(msg) @@ -380,7 +380,7 @@ func (handler *Handler) afterCompleted(e *fsm.Event) { e.Cancel(fmt.Errorf("Received unexpected message type")) return } - chaincodeLogger.Debugf("[%s]sending COMPLETED to validator for tid", shortuuid(msg.Uuid)) + chaincodeLogger.Debugf("[%s]sending COMPLETED to validator for tid", shorttxid(msg.Txid)) if err := handler.serialSend(msg); err != nil { e.Cancel(fmt.Errorf("send COMPLETED failed %s", err)) } @@ -407,9 +407,9 @@ func (handler *Handler) afterResponse(e *fsm.Event) { } if err := handler.sendChannel(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending %s (state:%s): %s", shortuuid(msg.Uuid), msg.Type, handler.FSM.Current(), err) + chaincodeLogger.Errorf("[%s]error sending %s (state:%s): %s", shorttxid(msg.Txid), msg.Type, handler.FSM.Current(), err) } else { - chaincodeLogger.Debugf("[%s]Received %s, communicated (state:%s)", shortuuid(msg.Uuid), msg.Type, handler.FSM.Current()) + chaincodeLogger.Debugf("[%s]Received %s, communicated (state:%s)", shorttxid(msg.Txid), msg.Type, handler.FSM.Current()) } } @@ -426,59 +426,59 @@ func (handler *Handler) afterError(e *fsm.Event) { * 2. The chaincode has initiated a request (get/put/del state) to the validator and is expecting a response on the responseChannel; If ERROR is received from validator, this needs to be notified on the responseChannel. */ if err := handler.sendChannel(msg); err == nil { - chaincodeLogger.Debugf("[%s]Error received from validator %s, communicated(state:%s)", shortuuid(msg.Uuid), msg.Type, handler.FSM.Current()) + chaincodeLogger.Debugf("[%s]Error received from validator %s, communicated(state:%s)", shorttxid(msg.Txid), msg.Type, handler.FSM.Current()) } } // TODO: Implement method to get and put entire state map and not one key at a time? // handleGetState communicates with the validator to fetch the requested state information from the ledger. -func (handler *Handler) handleGetState(key string, uuid string) ([]byte, error) { +func (handler *Handler) handleGetState(key string, txid string) ([]byte, error) { // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Debug("Another state request pending for this Uuid. Cannot process.") + chaincodeLogger.Debug("Another state request pending for this Txid. Cannot process.") return nil, uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send GET_STATE message to validator chaincode support payload := []byte(key) - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_GET_STATE, Payload: payload, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_GET_STATE) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_GET_STATE, Payload: payload, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_GET_STATE) if err := handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending GET_STATE %s", shortuuid(uuid), err) + chaincodeLogger.Errorf("[%s]error sending GET_STATE %s", shorttxid(txid), err) return nil, errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", shortuuid(responseMsg.Uuid)) + chaincodeLogger.Errorf("[%s]Received unexpected message type", shorttxid(responseMsg.Txid)) return nil, errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]GetState received payload %s", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]GetState received payload %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) return responseMsg.Payload, nil } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]GetState received error %s", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]GetState received error %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR) return nil, errors.New(string(responseMsg.Payload[:])) } // Incorrect chaincode message received - chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shortuuid(responseMsg.Uuid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) return nil, errors.New("Incorrect chaincode message received") } // handlePutState communicates with the validator to put state information into the ledger. -func (handler *Handler) handlePutState(key string, value []byte, uuid string) error { +func (handler *Handler) handlePutState(key string, value []byte, txid string) error { // Check if this is a transaction - chaincodeLogger.Debugf("[%s]Inside putstate, isTransaction = %t", shortuuid(uuid), handler.isTransaction[uuid]) - if !handler.isTransaction[uuid] { + chaincodeLogger.Debugf("[%s]Inside putstate, isTransaction = %t", shorttxid(txid), handler.isTransaction[txid]) + if !handler.isTransaction[txid] { return errors.New("Cannot put state in query context") } @@ -489,103 +489,103 @@ func (handler *Handler) handlePutState(key string, value []byte, uuid string) er } // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Errorf("[%s]Another state request pending for this Uuid. Cannot process.", shortuuid(uuid)) + chaincodeLogger.Errorf("[%s]Another state request pending for this Txid. Cannot process.", shorttxid(txid)) return uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send PUT_STATE message to validator chaincode support - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_PUT_STATE, Payload: payloadBytes, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_PUT_STATE) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_PUT_STATE, Payload: payloadBytes, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_PUT_STATE) if err = handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending PUT_STATE %s", msg.Uuid, err) + chaincodeLogger.Errorf("[%s]error sending PUT_STATE %s", msg.Txid, err) return errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", msg.Uuid) + chaincodeLogger.Errorf("[%s]Received unexpected message type", msg.Txid) return errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully updated state", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully updated state", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) return nil } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s. Payload: %s", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR, responseMsg.Payload) + chaincodeLogger.Errorf("[%s]Received %s. Payload: %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR, responseMsg.Payload) return errors.New(string(responseMsg.Payload[:])) } // Incorrect chaincode message received - chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shortuuid(responseMsg.Uuid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) return errors.New("Incorrect chaincode message received") } // handleDelState communicates with the validator to delete a key from the state in the ledger. -func (handler *Handler) handleDelState(key string, uuid string) error { +func (handler *Handler) handleDelState(key string, txid string) error { // Check if this is a transaction - if !handler.isTransaction[uuid] { + if !handler.isTransaction[txid] { return errors.New("Cannot del state in query context") } // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Errorf("[%s]Another state request pending for this Uuid. Cannot process create createChannel.", shortuuid(uuid)) + chaincodeLogger.Errorf("[%s]Another state request pending for this Txid. Cannot process create createChannel.", shorttxid(txid)) return uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send DEL_STATE message to validator chaincode support payload := []byte(key) - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_DEL_STATE, Payload: payload, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_DEL_STATE) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_DEL_STATE, Payload: payload, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_DEL_STATE) if err := handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending DEL_STATE %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_DEL_STATE) + chaincodeLogger.Errorf("[%s]error sending DEL_STATE %s", shorttxid(msg.Txid), pb.ChaincodeMessage_DEL_STATE) return errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", shortuuid(msg.Uuid)) + chaincodeLogger.Errorf("[%s]Received unexpected message type", shorttxid(msg.Txid)) return errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully deleted state", msg.Uuid, pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully deleted state", msg.Txid, pb.ChaincodeMessage_RESPONSE) return nil } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s. Payload: %s", msg.Uuid, pb.ChaincodeMessage_ERROR, responseMsg.Payload) + chaincodeLogger.Errorf("[%s]Received %s. Payload: %s", msg.Txid, pb.ChaincodeMessage_ERROR, responseMsg.Payload) return errors.New(string(responseMsg.Payload[:])) } // Incorrect chaincode message received - chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shortuuid(responseMsg.Uuid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) return errors.New("Incorrect chaincode message received") } -func (handler *Handler) handleRangeQueryState(startKey, endKey string, uuid string) (*pb.RangeQueryStateResponse, error) { +func (handler *Handler) handleRangeQueryState(startKey, endKey string, txid string) (*pb.RangeQueryStateResponse, error) { // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Debugf("[%s]Another state request pending for this Uuid. Cannot process.", shortuuid(uuid)) + chaincodeLogger.Debugf("[%s]Another state request pending for this Txid. Cannot process.", shorttxid(txid)) return nil, uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send RANGE_QUERY_STATE message to validator chaincode support payload := &pb.RangeQueryState{StartKey: startKey, EndKey: endKey} @@ -593,28 +593,28 @@ func (handler *Handler) handleRangeQueryState(startKey, endKey string, uuid stri if err != nil { return nil, errors.New("Failed to process range query state request") } - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RANGE_QUERY_STATE, Payload: payloadBytes, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RANGE_QUERY_STATE) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RANGE_QUERY_STATE, Payload: payloadBytes, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RANGE_QUERY_STATE) if err = handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RANGE_QUERY_STATE) + chaincodeLogger.Errorf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RANGE_QUERY_STATE) return nil, errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", uuid) + chaincodeLogger.Errorf("[%s]Received unexpected message type", txid) return nil, errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) rangeQueryResponse := &pb.RangeQueryStateResponse{} unmarshalErr := proto.Unmarshal(responseMsg.Payload, rangeQueryResponse) if unmarshalErr != nil { - chaincodeLogger.Errorf("[%s]unmarshall error", shortuuid(responseMsg.Uuid)) + chaincodeLogger.Errorf("[%s]unmarshall error", shorttxid(responseMsg.Txid)) return nil, errors.New("Error unmarshalling RangeQueryStateResponse.") } @@ -622,7 +622,7 @@ func (handler *Handler) handleRangeQueryState(startKey, endKey string, uuid stri } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR) return nil, errors.New(string(responseMsg.Payload[:])) } @@ -631,15 +631,15 @@ func (handler *Handler) handleRangeQueryState(startKey, endKey string, uuid stri return nil, errors.New("Incorrect chaincode message received") } -func (handler *Handler) handleRangeQueryStateNext(id, uuid string) (*pb.RangeQueryStateResponse, error) { +func (handler *Handler) handleRangeQueryStateNext(id, txid string) (*pb.RangeQueryStateResponse, error) { // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Debugf("[%s]Another state request pending for this Uuid. Cannot process.", shortuuid(uuid)) + chaincodeLogger.Debugf("[%s]Another state request pending for this Txid. Cannot process.", shorttxid(txid)) return nil, uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send RANGE_QUERY_STATE_NEXT message to validator chaincode support payload := &pb.RangeQueryStateNext{ID: id} @@ -647,28 +647,28 @@ func (handler *Handler) handleRangeQueryStateNext(id, uuid string) (*pb.RangeQue if err != nil { return nil, errors.New("Failed to process range query state next request") } - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RANGE_QUERY_STATE_NEXT, Payload: payloadBytes, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RANGE_QUERY_STATE_NEXT) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RANGE_QUERY_STATE_NEXT, Payload: payloadBytes, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RANGE_QUERY_STATE_NEXT) if err = handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RANGE_QUERY_STATE_NEXT) + chaincodeLogger.Errorf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RANGE_QUERY_STATE_NEXT) return nil, errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", uuid) + chaincodeLogger.Errorf("[%s]Received unexpected message type", txid) return nil, errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) rangeQueryResponse := &pb.RangeQueryStateResponse{} unmarshalErr := proto.Unmarshal(responseMsg.Payload, rangeQueryResponse) if unmarshalErr != nil { - chaincodeLogger.Errorf("[%s]unmarshall error", shortuuid(responseMsg.Uuid)) + chaincodeLogger.Errorf("[%s]unmarshall error", shorttxid(responseMsg.Txid)) return nil, errors.New("Error unmarshalling RangeQueryStateResponse.") } @@ -676,7 +676,7 @@ func (handler *Handler) handleRangeQueryStateNext(id, uuid string) (*pb.RangeQue } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR) return nil, errors.New(string(responseMsg.Payload[:])) } @@ -685,15 +685,15 @@ func (handler *Handler) handleRangeQueryStateNext(id, uuid string) (*pb.RangeQue return nil, errors.New("Incorrect chaincode message received") } -func (handler *Handler) handleRangeQueryStateClose(id, uuid string) (*pb.RangeQueryStateResponse, error) { +func (handler *Handler) handleRangeQueryStateClose(id, txid string) (*pb.RangeQueryStateResponse, error) { // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Debugf("[%s]Another state request pending for this Uuid. Cannot process.", shortuuid(uuid)) + chaincodeLogger.Debugf("[%s]Another state request pending for this Txid. Cannot process.", shorttxid(txid)) return nil, uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send RANGE_QUERY_STATE_CLOSE message to validator chaincode support payload := &pb.RangeQueryStateClose{ID: id} @@ -701,28 +701,28 @@ func (handler *Handler) handleRangeQueryStateClose(id, uuid string) (*pb.RangeQu if err != nil { return nil, errors.New("Failed to process range query state close request") } - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RANGE_QUERY_STATE_CLOSE, Payload: payloadBytes, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RANGE_QUERY_STATE_CLOSE) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_RANGE_QUERY_STATE_CLOSE, Payload: payloadBytes, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RANGE_QUERY_STATE_CLOSE) if err = handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_RANGE_QUERY_STATE_CLOSE) + chaincodeLogger.Errorf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_RANGE_QUERY_STATE_CLOSE) return nil, errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", uuid) + chaincodeLogger.Errorf("[%s]Received unexpected message type", txid) return nil, errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully got range", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) rangeQueryResponse := &pb.RangeQueryStateResponse{} unmarshalErr := proto.Unmarshal(responseMsg.Payload, rangeQueryResponse) if unmarshalErr != nil { - chaincodeLogger.Errorf("[%s]unmarshall error", shortuuid(responseMsg.Uuid)) + chaincodeLogger.Errorf("[%s]unmarshall error", shorttxid(responseMsg.Txid)) return nil, errors.New("Error unmarshalling RangeQueryStateResponse.") } @@ -730,7 +730,7 @@ func (handler *Handler) handleRangeQueryStateClose(id, uuid string) (*pb.RangeQu } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Received %s", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR) return nil, errors.New(string(responseMsg.Payload[:])) } @@ -740,9 +740,9 @@ func (handler *Handler) handleRangeQueryStateClose(id, uuid string) (*pb.RangeQu } // handleInvokeChaincode communicates with the validator to invoke another chaincode. -func (handler *Handler) handleInvokeChaincode(chaincodeName string, function string, args []string, uuid string) ([]byte, error) { +func (handler *Handler) handleInvokeChaincode(chaincodeName string, function string, args []string, txid string) ([]byte, error) { // Check if this is a transaction - if !handler.isTransaction[uuid] { + if !handler.isTransaction[txid] { return nil, errors.New("Cannot invoke chaincode in query context") } @@ -755,58 +755,58 @@ func (handler *Handler) handleInvokeChaincode(chaincodeName string, function str } // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Errorf("[%s]Another request pending for this Uuid. Cannot process.", uuid) + chaincodeLogger.Errorf("[%s]Another request pending for this Txid. Cannot process.", txid) return nil, uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send INVOKE_CHAINCODE message to validator chaincode support - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INVOKE_CHAINCODE, Payload: payloadBytes, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_INVOKE_CHAINCODE) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INVOKE_CHAINCODE, Payload: payloadBytes, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_INVOKE_CHAINCODE) if err = handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_INVOKE_CHAINCODE) + chaincodeLogger.Errorf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_INVOKE_CHAINCODE) return nil, errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", shortuuid(msg.Uuid)) + chaincodeLogger.Errorf("[%s]Received unexpected message type", shorttxid(msg.Txid)) return nil, errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully invoked chaincode", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully invoked chaincode", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) respMsg := &pb.ChaincodeMessage{} if err := proto.Unmarshal(responseMsg.Payload, respMsg); err != nil { - chaincodeLogger.Errorf("[%s]Error unmarshaling called chaincode response: %s", shortuuid(responseMsg.Uuid), err) + chaincodeLogger.Errorf("[%s]Error unmarshaling called chaincode response: %s", shorttxid(responseMsg.Txid), err) return nil, err } if respMsg.Type == pb.ChaincodeMessage_COMPLETED { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully invoed chaincode", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully invoed chaincode", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) return respMsg.Payload, nil } - chaincodeLogger.Errorf("[%s]Received %s. Error from chaincode", shortuuid(responseMsg.Uuid), respMsg.Type.String()) + chaincodeLogger.Errorf("[%s]Received %s. Error from chaincode", shorttxid(responseMsg.Txid), respMsg.Type.String()) return nil, errors.New(string(respMsg.Payload[:])) } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s.", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Received %s.", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR) return nil, errors.New(string(responseMsg.Payload[:])) } // Incorrect chaincode message received - chaincodeLogger.Debugf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shortuuid(responseMsg.Uuid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) + chaincodeLogger.Debugf("[%s]Incorrect chaincode message %s received. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) return nil, errors.New("Incorrect chaincode message received") } // handleQueryChaincode communicates with the validator to query another chaincode. -func (handler *Handler) handleQueryChaincode(chaincodeName string, function string, args []string, uuid string) ([]byte, error) { +func (handler *Handler) handleQueryChaincode(chaincodeName string, function string, args []string, txid string) ([]byte, error) { chaincodeID := &pb.ChaincodeID{Name: chaincodeName} input := &pb.ChaincodeInput{Function: function, Args: args} payload := &pb.ChaincodeSpec{ChaincodeID: chaincodeID, CtorMsg: input} @@ -816,51 +816,51 @@ func (handler *Handler) handleQueryChaincode(chaincodeName string, function stri } // Create the channel on which to communicate the response from validating peer - respChan, uniqueReqErr := handler.createChannel(uuid) + respChan, uniqueReqErr := handler.createChannel(txid) if uniqueReqErr != nil { - chaincodeLogger.Debug("Another request pending for this Uuid. Cannot process.") + chaincodeLogger.Debug("Another request pending for this Txid. Cannot process.") return nil, uniqueReqErr } - defer handler.deleteChannel(uuid) + defer handler.deleteChannel(txid) // Send INVOKE_QUERY message to validator chaincode support - msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INVOKE_QUERY, Payload: payloadBytes, Uuid: uuid} - chaincodeLogger.Debugf("[%s]Sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_INVOKE_QUERY) + msg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_INVOKE_QUERY, Payload: payloadBytes, Txid: txid} + chaincodeLogger.Debugf("[%s]Sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_INVOKE_QUERY) if err = handler.serialSend(msg); err != nil { - chaincodeLogger.Errorf("[%s]error sending %s", shortuuid(msg.Uuid), pb.ChaincodeMessage_INVOKE_QUERY) + chaincodeLogger.Errorf("[%s]error sending %s", shorttxid(msg.Txid), pb.ChaincodeMessage_INVOKE_QUERY) return nil, errors.New("could not send msg") } // Wait on responseChannel for response responseMsg, ok := handler.receiveChannel(respChan) if !ok { - chaincodeLogger.Errorf("[%s]Received unexpected message type", shortuuid(msg.Uuid)) + chaincodeLogger.Errorf("[%s]Received unexpected message type", shorttxid(msg.Txid)) return nil, errors.New("Received unexpected message type") } if responseMsg.Type.String() == pb.ChaincodeMessage_RESPONSE.String() { respMsg := &pb.ChaincodeMessage{} if err := proto.Unmarshal(responseMsg.Payload, respMsg); err != nil { - chaincodeLogger.Errorf("[%s]Error unmarshaling called chaincode responseP: %s", shortuuid(responseMsg.Uuid), err) + chaincodeLogger.Errorf("[%s]Error unmarshaling called chaincode responseP: %s", shorttxid(responseMsg.Txid), err) return nil, err } if respMsg.Type == pb.ChaincodeMessage_QUERY_COMPLETED { // Success response - chaincodeLogger.Debugf("[%s]Received %s. Successfully queried chaincode", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_RESPONSE) + chaincodeLogger.Debugf("[%s]Received %s. Successfully queried chaincode", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_RESPONSE) return respMsg.Payload, nil } - chaincodeLogger.Errorf("[%s]Error from chaincode: %s", shortuuid(responseMsg.Uuid), string(respMsg.Payload[:])) + chaincodeLogger.Errorf("[%s]Error from chaincode: %s", shorttxid(responseMsg.Txid), string(respMsg.Payload[:])) return nil, errors.New(string(respMsg.Payload[:])) } if responseMsg.Type.String() == pb.ChaincodeMessage_ERROR.String() { // Error response - chaincodeLogger.Errorf("[%s]Received %s.", shortuuid(responseMsg.Uuid), pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Received %s.", shorttxid(responseMsg.Txid), pb.ChaincodeMessage_ERROR) return nil, errors.New(string(responseMsg.Payload[:])) } // Incorrect chaincode message received - chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s recieved. Expecting %s or %s", shortuuid(responseMsg.Uuid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) + chaincodeLogger.Errorf("[%s]Incorrect chaincode message %s recieved. Expecting %s or %s", shorttxid(responseMsg.Txid), responseMsg.Type, pb.ChaincodeMessage_RESPONSE, pb.ChaincodeMessage_ERROR) return nil, errors.New("Incorrect chaincode message received") } @@ -871,12 +871,12 @@ func (handler *Handler) handleMessage(msg *pb.ChaincodeMessage) error { // and it does not touch the state machine return nil } - chaincodeLogger.Debugf("[%s]Handling ChaincodeMessage of type: %s(state:%s)", shortuuid(msg.Uuid), msg.Type, handler.FSM.Current()) + chaincodeLogger.Debugf("[%s]Handling ChaincodeMessage of type: %s(state:%s)", shorttxid(msg.Txid), msg.Type, handler.FSM.Current()) if handler.FSM.Cannot(msg.Type.String()) { - errStr := fmt.Sprintf("[%s]Chaincode handler FSM cannot handle message (%s) with payload size (%d) while in state: %s", msg.Uuid, msg.Type.String(), len(msg.Payload), handler.FSM.Current()) + errStr := fmt.Sprintf("[%s]Chaincode handler FSM cannot handle message (%s) with payload size (%d) while in state: %s", msg.Txid, msg.Type.String(), len(msg.Payload), handler.FSM.Current()) err := errors.New(errStr) payload := []byte(err.Error()) - errorMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Uuid: msg.Uuid} + errorMsg := &pb.ChaincodeMessage{Type: pb.ChaincodeMessage_ERROR, Payload: payload, Txid: msg.Txid} handler.serialSend(errorMsg) return err } diff --git a/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/ChaincodeBase.java b/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/ChaincodeBase.java index ea5a8dbcdd9..32e4e2f9a05 100644 --- a/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/ChaincodeBase.java +++ b/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/ChaincodeBase.java @@ -127,7 +127,7 @@ public void chatWithPeer(ManagedChannel connection) { public void onNext(ChaincodeMessage message) { try { logger.debug(String.format("[%s]Received message %s from org.hyperledger.java.shim", - Handler.shortUUID(message.getUuid()), message.getType())); + Handler.shortID(message.getTxid()), message.getType())); handler.handleMessage(message); } catch (Exception e) { e.printStackTrace(); @@ -187,7 +187,7 @@ public void onCompleted() { if (message.getType() == Type.KEEPALIVE){ logger.debug("Sending KEEPALIVE response"); }else { - logger.debug("[" + Handler.shortUUID(message.getUuid()) + "]Send state message " + message.getType()); + logger.debug("[" + Handler.shortID(message.getTxid()) + "]Send state message " + message.getType()); } handler.serialSend(message); } diff --git a/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/Handler.java b/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/Handler.java index a8c2702e4d0..babbcce6676 100644 --- a/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/Handler.java +++ b/core/chaincode/shim/java/src/main/java/org/hyperledger/java/shim/Handler.java @@ -33,7 +33,6 @@ Licensed to the Apache Software Foundation (ASF) under one import static protos.Chaincode.ChaincodeMessage.Type.QUERY; import static protos.Chaincode.ChaincodeMessage.Type.QUERY_COMPLETED; import static protos.Chaincode.ChaincodeMessage.Type.QUERY_ERROR; -import static protos.Chaincode.ChaincodeMessage.Type.RANGE_QUERY_STATE; import static protos.Chaincode.ChaincodeMessage.Type.READY; import static protos.Chaincode.ChaincodeMessage.Type.REGISTERED; import static protos.Chaincode.ChaincodeMessage.Type.RESPONSE; @@ -113,7 +112,7 @@ public Handler(StreamObserver chatStream, ChaincodeBase chainc ); } - public static String shortUUID(String uuid) { + public static String shortID(String uuid) { if (uuid.length() < 8) { return uuid; } else { @@ -131,7 +130,7 @@ public synchronized void serialSend(ChaincodeMessage message) { chatStream.onNext(message); } catch (Exception e) { logger.error(String.format("[%s]Error sending %s: %s", - shortUUID(message), message.getType(), e)); + shortID(message), message.getType(), e)); throw new RuntimeException(String.format("Error sending %s: %s", message.getType(), e)); } if(logger.isTraceEnabled())logger.trace("serialSend complete for message "+message); @@ -139,7 +138,7 @@ public synchronized void serialSend(ChaincodeMessage message) { public synchronized Channel createChannel(String uuid) { if (responseChannel.containsKey(uuid)) { - throw new IllegalStateException("[" + shortUUID(uuid) + "] Channel exists"); + throw new IllegalStateException("[" + shortID(uuid) + "] Channel exists"); } Channel channel = new Channel(); @@ -150,13 +149,13 @@ public synchronized Channel createChannel(String uuid) { } public synchronized void sendChannel(ChaincodeMessage message) { - if (!responseChannel.containsKey(message.getUuid())) { - throw new IllegalStateException("[" + shortUUID(message) + "]sendChannel does not exist"); + if (!responseChannel.containsKey(message.getTxid())) { + throw new IllegalStateException("[" + shortID(message) + "]sendChannel does not exist"); } - logger.debug(String.format("[%s]Before send", shortUUID(message))); - responseChannel.get(message.getUuid()).add(message); - logger.debug(String.format("[%s]After send", shortUUID(message))); + logger.debug(String.format("[%s]Before send", shortID(message))); + responseChannel.get(message.getTxid()).add(message); + logger.debug(String.format("[%s]After send", shortID(message))); } public ChaincodeMessage receiveChannel(Channel channel) { @@ -220,16 +219,16 @@ public void handleInit(ChaincodeMessage message) { } catch (Exception e) { // payload = []byte(unmarshalErr.Error()) // // Send ERROR message to chaincode support and change state - // logger.debug(String.format("[%s]Incorrect payload format. Sending %s", shortUUID(message), ERROR) - // nextStatemessage = ChaincodeMessage.newBuilder(){Type: ERROR, Payload: payload, Uuid: message.getUuid()} + // logger.debug(String.format("[%s]Incorrect payload format. Sending %s", shortID(message), ERROR) + // nextStatemessage = ChaincodeMessage.newBuilder(){Type: ERROR, Payload: payload, Uuid: message.getTxid()} return; } // // Mark as a transaction (allow put/del state) - markIsTransaction(message.getUuid(), true); + markIsTransaction(message.getTxid(), true); // Create the ChaincodeStub which the chaincode can use to callback - ChaincodeStub stub = new ChaincodeStub(message.getUuid(), this); + ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this); // Call chaincode's Run ByteString result; @@ -237,27 +236,27 @@ public void handleInit(ChaincodeMessage message) { result = chaincode.runHelper(stub, input.getFunction(), arrayHelper(input.getArgsList())); } catch (Exception e) { // Send ERROR message to chaincode support and change state - logger.debug(String.format("[%s]Init failed. Sending %s", shortUUID(message), ERROR)); + logger.debug(String.format("[%s]Init failed. Sending %s", shortID(message), ERROR)); nextStatemessage = ChaincodeMessage.newBuilder() .setType(ERROR) .setPayload(ByteString.copyFromUtf8(e.getMessage())) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); return; } finally { // delete isTransaction entry - deleteIsTransaction(message.getUuid()); + deleteIsTransaction(message.getTxid()); } // Send COMPLETED message to chaincode support and change state nextStatemessage = ChaincodeMessage.newBuilder() .setType(COMPLETED) .setPayload(result) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); logger.debug(String.format(String.format("[%s]Init succeeded. Sending %s", - shortUUID(message), COMPLETED))); + shortID(message), COMPLETED))); //TODO put in all exception states } catch (Exception e) { @@ -283,7 +282,7 @@ public void enterInitState(Event event) { logger.debug(String.format("Entered state %s", fsm.current())); ChaincodeMessage message = messageHelper(event); logger.debug(String.format("[%s]Received %s, initializing chaincode", - shortUUID(message), message.getType().toString())); + shortID(message), message.getType().toString())); if (message.getType() == INIT) { // Call the chaincode's Run function to initialize handleInit(message); @@ -308,21 +307,21 @@ public void handleTransaction(ChaincodeMessage message) { try { input = ChaincodeInput.parseFrom(message.getPayload()); } catch (Exception e) { - logger.debug(String.format("[%s]Incorrect payload format. Sending %s", shortUUID(message), ERROR)); + logger.debug(String.format("[%s]Incorrect payload format. Sending %s", shortID(message), ERROR)); // Send ERROR message to chaincode support and change state nextStatemessage = ChaincodeMessage.newBuilder() .setType(ERROR) .setPayload(message.getPayload()) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); return; } // Mark as a transaction (allow put/del state) - markIsTransaction(message.getUuid(), true); + markIsTransaction(message.getTxid(), true); // Create the ChaincodeStub which the chaincode can use to callback - ChaincodeStub stub = new ChaincodeStub(message.getUuid(), this); + ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this); // Call chaincode's Run ByteString response; @@ -333,24 +332,24 @@ public void handleTransaction(ChaincodeMessage message) { System.err.flush(); // Send ERROR message to chaincode support and change state logger.error(String.format("[%s]Error running chaincode. Transaction execution failed. Sending %s", - shortUUID(message), ERROR)); + shortID(message), ERROR)); nextStatemessage = ChaincodeMessage.newBuilder() .setType(ERROR) .setPayload(message.getPayload()) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); return; } finally { - deleteIsTransaction(message.getUuid()); + deleteIsTransaction(message.getTxid()); } logger.debug(String.format("[%s]Transaction completed. Sending %s", - shortUUID(message), COMPLETED)); + shortID(message), COMPLETED)); // Send COMPLETED message to chaincode support and change state Builder builder = ChaincodeMessage.newBuilder() .setType(COMPLETED) - .setUuid(message.getUuid()); + .setTxid(message.getTxid()); if (response != null) builder.setPayload(response); nextStatemessage = builder.build(); } finally { @@ -374,21 +373,21 @@ public void handleQuery(ChaincodeMessage message) { } catch (Exception e) { // Send ERROR message to chaincode support and change state logger.debug(String.format("[%s]Incorrect payload format. Sending %s", - shortUUID(message), QUERY_ERROR)); + shortID(message), QUERY_ERROR)); serialSendMessage = ChaincodeMessage.newBuilder() .setType(QUERY_ERROR) .setPayload(ByteString.copyFromUtf8(e.getMessage())) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); return; } // Mark as a query (do not allow put/del state) - markIsTransaction(message.getUuid(), false); + markIsTransaction(message.getTxid(), false); // Call chaincode's Query // Create the ChaincodeStub which the chaincode can use to callback - ChaincodeStub stub = new ChaincodeStub(message.getUuid(), this); + ChaincodeStub stub = new ChaincodeStub(message.getTxid(), this); ByteString response; @@ -397,23 +396,23 @@ public void handleQuery(ChaincodeMessage message) { } catch (Exception e) { // Send ERROR message to chaincode support and change state logger.debug(String.format("[%s]Query execution failed. Sending %s", - shortUUID(message), QUERY_ERROR)); + shortID(message), QUERY_ERROR)); serialSendMessage = ChaincodeMessage.newBuilder() .setType(QUERY_ERROR) .setPayload(ByteString.copyFromUtf8(e.getMessage())) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); return; } finally { - deleteIsTransaction(message.getUuid()); + deleteIsTransaction(message.getTxid()); } // Send COMPLETED message to chaincode support - logger.debug("["+shortUUID(message)+"]Query completed. Sending "+ QUERY_COMPLETED); + logger.debug("["+ shortID(message)+"]Query completed. Sending "+ QUERY_COMPLETED); serialSendMessage = ChaincodeMessage.newBuilder() .setType(QUERY_COMPLETED) .setPayload(response) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); } finally { serialSend(serialSendMessage); @@ -427,7 +426,7 @@ public void handleQuery(ChaincodeMessage message) { public void enterTransactionState(Event event) { ChaincodeMessage message = messageHelper(event); logger.debug(String.format("[%s]Received %s, invoking transaction on chaincode(src:%s, dst:%s)", - shortUUID(message), message.getType().toString(), event.src, event.dst)); + shortID(message), message.getType().toString(), event.src, event.dst)); if (message.getType() == TRANSACTION) { // Call the chaincode's Run function to invoke transaction handleTransaction(message); @@ -437,7 +436,7 @@ public void enterTransactionState(Event event) { // afterCompleted will need to handle COMPLETED event by sending message to the peer public void afterCompleted(Event event) { ChaincodeMessage message = messageHelper(event); - logger.debug(String.format("[%s]sending COMPLETED to validator for tid", shortUUID(message))); + logger.debug(String.format("[%s]sending COMPLETED to validator for tid", shortID(message))); try { serialSend(message); } catch (Exception e) { @@ -457,9 +456,9 @@ public void afterResponse(Event event) { try { sendChannel(message); logger.debug(String.format("[%s]Received %s, communicated (state:%s)", - shortUUID(message), message.getType(), fsm.current())); + shortID(message), message.getType(), fsm.current())); } catch (Exception e) { - logger.error(String.format("[%s]error sending %s (state:%s): %s", shortUUID(message), + logger.error(String.format("[%s]error sending %s (state:%s): %s", shortID(message), message.getType(), fsm.current(), e)); } } @@ -485,7 +484,7 @@ public void afterError(Event event) { sendChannel(message); } catch (Exception e) { logger.debug(String.format("[%s]Error received from validator %s, communicated(state:%s)", - shortUUID(message), message.getType(), fsm.current())); + shortID(message), message.getType(), fsm.current())); } } @@ -507,14 +506,14 @@ public ByteString handleGetState(String key, String uuid) { ChaincodeMessage message = ChaincodeMessage.newBuilder() .setType(GET_STATE) .setPayload(ByteString.copyFromUtf8(key)) - .setUuid(uuid) + .setTxid(uuid) .build(); - logger.debug(String.format("[%s]Sending %s", shortUUID(message), GET_STATE)); + logger.debug(String.format("[%s]Sending %s", shortID(message), GET_STATE)); try { serialSend(message); } catch (Exception e) { - logger.error(String.format("[%s]error sending GET_STATE %s", shortUUID(uuid), e)); + logger.error(String.format("[%s]error sending GET_STATE %s", shortID(uuid), e)); throw new RuntimeException("could not send message"); } @@ -523,25 +522,25 @@ public ByteString handleGetState(String key, String uuid) { try { response = receiveChannel(responseChannel); } catch (Exception e) { - logger.error(String.format("[%s]Received unexpected message type", shortUUID(uuid))); + logger.error(String.format("[%s]Received unexpected message type", shortID(uuid))); throw new RuntimeException("Received unexpected message type"); } // Success response if (response.getType() == RESPONSE) { - logger.debug(String.format("[%s]GetState received payload %s", shortUUID(response.getUuid()), RESPONSE)); + logger.debug(String.format("[%s]GetState received payload %s", shortID(response.getTxid()), RESPONSE)); return response.getPayload(); } // Error response if (response.getType() == ERROR) { - logger.error(String.format("[%s]GetState received error %s", shortUUID(response.getUuid()), ERROR)); + logger.error(String.format("[%s]GetState received error %s", shortID(response.getTxid()), ERROR)); throw new RuntimeException(response.getPayload().toString()); } // Incorrect chaincode message received logger.error(String.format("[%s]Incorrect chaincode message %s received. Expecting %s or %s", - shortUUID(response.getUuid()), response.getType(), RESPONSE, ERROR)); + shortID(response.getTxid()), response.getType(), RESPONSE, ERROR)); throw new RuntimeException("Incorrect chaincode message received"); } finally { deleteChannel(uuid); @@ -554,7 +553,7 @@ private boolean isTransaction(String uuid) { public void handlePutState(String key, ByteString value, String uuid) { // Check if this is a transaction - logger.debug("["+shortUUID(uuid)+"]Inside putstate (\""+key+"\":\""+value+"\"), isTransaction = "+isTransaction(uuid)); + logger.debug("["+ shortID(uuid)+"]Inside putstate (\""+key+"\":\""+value+"\"), isTransaction = "+isTransaction(uuid)); if (!isTransaction(uuid)) { throw new IllegalStateException("Cannot put state in query context"); @@ -570,7 +569,7 @@ public void handlePutState(String key, ByteString value, String uuid) { try { responseChannel = createChannel(uuid); } catch (Exception e) { - logger.error(String.format("[%s]Another state request pending for this Uuid. Cannot process.", shortUUID(uuid))); + logger.error(String.format("[%s]Another state request pending for this Uuid. Cannot process.", shortID(uuid))); throw e; } @@ -580,15 +579,15 @@ public void handlePutState(String key, ByteString value, String uuid) { ChaincodeMessage message = ChaincodeMessage.newBuilder() .setType(PUT_STATE) .setPayload(payload.toByteString()) - .setUuid(uuid) + .setTxid(uuid) .build(); - logger.debug(String.format("[%s]Sending %s", shortUUID(message), PUT_STATE)); + logger.debug(String.format("[%s]Sending %s", shortID(message), PUT_STATE)); try { serialSend(message); } catch (Exception e) { - logger.error(String.format("[%s]error sending PUT_STATE %s", message.getUuid(), e)); + logger.error(String.format("[%s]error sending PUT_STATE %s", message.getTxid(), e)); throw new RuntimeException("could not send message"); } @@ -604,19 +603,19 @@ public void handlePutState(String key, ByteString value, String uuid) { // Success response if (response.getType() == RESPONSE) { - logger.debug(String.format("[%s]Received %s. Successfully updated state", shortUUID(response.getUuid()), RESPONSE)); + logger.debug(String.format("[%s]Received %s. Successfully updated state", shortID(response.getTxid()), RESPONSE)); return; } // Error response if (response.getType() == ERROR) { - logger.error(String.format("[%s]Received %s. Payload: %s", shortUUID(response.getUuid()), ERROR, response.getPayload())); + logger.error(String.format("[%s]Received %s. Payload: %s", shortID(response.getTxid()), ERROR, response.getPayload())); throw new RuntimeException(response.getPayload().toStringUtf8()); } // Incorrect chaincode message received logger.error(String.format("[%s]Incorrect chaincode message %s received. Expecting %s or %s", - shortUUID(response.getUuid()), response.getType(), RESPONSE, ERROR)); + shortID(response.getTxid()), response.getType(), RESPONSE, ERROR)); throw new RuntimeException("Incorrect chaincode message received"); } catch (Exception e) { @@ -638,7 +637,7 @@ public void handleDeleteState(String key, String uuid) { responseChannel = createChannel(uuid); } catch (Exception e) { logger.error(String.format("[%s]Another state request pending for this Uuid." - + " Cannot process create createChannel.",shortUUID(uuid))); + + " Cannot process create createChannel.", shortID(uuid))); throw e; } @@ -648,13 +647,13 @@ public void handleDeleteState(String key, String uuid) { ChaincodeMessage message = ChaincodeMessage.newBuilder() .setType(DEL_STATE) .setPayload(ByteString.copyFromUtf8(key)) - .setUuid(uuid) + .setTxid(uuid) .build(); - logger.debug(String.format("[%s]Sending %s", shortUUID(uuid), DEL_STATE)); + logger.debug(String.format("[%s]Sending %s", shortID(uuid), DEL_STATE)); try { serialSend(message); } catch (Exception e) { - logger.error(String.format("[%s]error sending DEL_STATE %s", shortUUID(message), DEL_STATE)); + logger.error(String.format("[%s]error sending DEL_STATE %s", shortID(message), DEL_STATE)); throw new RuntimeException("could not send message"); } @@ -663,25 +662,25 @@ public void handleDeleteState(String key, String uuid) { try { response = receiveChannel(responseChannel); } catch (Exception e) { - logger.error(String.format("[%s]Received unexpected message type", shortUUID(message))); + logger.error(String.format("[%s]Received unexpected message type", shortID(message))); throw new RuntimeException("Received unexpected message type"); } if (response.getType() == RESPONSE) { // Success response - logger.debug(String.format("[%s]Received %s. Successfully deleted state", message.getUuid(), RESPONSE)); + logger.debug(String.format("[%s]Received %s. Successfully deleted state", message.getTxid(), RESPONSE)); return; } if (response.getType() == ERROR) { // Error response - logger.error(String.format("[%s]Received %s. Payload: %s", message.getUuid(), ERROR, response.getPayload())); + logger.error(String.format("[%s]Received %s. Payload: %s", message.getTxid(), ERROR, response.getPayload())); throw new RuntimeException(response.getPayload().toStringUtf8()); } // Incorrect chaincode message received logger.error(String.format("[%s]Incorrect chaincode message %s received. Expecting %s or %s", - shortUUID(response.getUuid()), response.getType(), RESPONSE, ERROR)); + shortID(response.getTxid()), response.getType(), RESPONSE, ERROR)); throw new RuntimeException("Incorrect chaincode message received"); } finally { deleteChannel(uuid); @@ -695,7 +694,7 @@ public void handleDeleteState(String key, String uuid) { // responseChannel = createChannel(uuid); // } catch (Exception e) { // logger.debug(String.format("[%s]Another state request pending for this Uuid." -// + " Cannot process.", shortUUID(uuid))); +// + " Cannot process.", shortID(uuid))); // throw e; // } // @@ -711,14 +710,14 @@ public void handleDeleteState(String key, String uuid) { // ChaincodeMessage message = ChaincodeMessage.newBuilder() // .setType(RANGE_QUERY_STATE) // .setPayload(payload.toByteString()) -// .setUuid(uuid) +// .setTxid(uuid) // .build(); // -// logger.debug(String.format("[%s]Sending %s", shortUUID(message), RANGE_QUERY_STATE)); +// logger.debug(String.format("[%s]Sending %s", shortID(message), RANGE_QUERY_STATE)); // try { // serialSend(message); // } catch (Exception e){ -// logger.error(String.format("[%s]error sending %s", shortUUID(message), RANGE_QUERY_STATE)); +// logger.error(String.format("[%s]error sending %s", shortID(message), RANGE_QUERY_STATE)); // throw new RuntimeException("could not send message"); // } // @@ -734,13 +733,13 @@ public void handleDeleteState(String key, String uuid) { // if (response.getType() == RESPONSE) { // // Success response // logger.debug(String.format("[%s]Received %s. Successfully got range", -// shortUUID(response.getUuid()), RESPONSE)); +// shortID(response.getTxid()), RESPONSE)); // // RangeQueryStateResponse rangeQueryResponse; // try { // rangeQueryResponse = RangeQueryStateResponse.parseFrom(response.getPayload()); // } catch (Exception e) { -// logger.error(String.format("[%s]unmarshall error", shortUUID(response.getUuid()))); +// logger.error(String.format("[%s]unmarshall error", shortID(response.getTxid()))); // throw new RuntimeException("Error unmarshalling RangeQueryStateResponse."); // } // @@ -750,7 +749,7 @@ public void handleDeleteState(String key, String uuid) { // if (response.getType() == ERROR) { // // Error response // logger.error(String.format("[%s]Received %s", -// shortUUID(response.getUuid()), ERROR)); +// shortID(response.getTxid()), ERROR)); // throw new RuntimeException(response.getPayload().toStringUtf8()); // } // @@ -785,7 +784,7 @@ public ByteString handleInvokeChaincode(String chaincodeName, String function, S try { responseChannel = createChannel(uuid); } catch (Exception e) { - logger.error(String.format("[%s]Another state request pending for this Uuid. Cannot process.", shortUUID(uuid))); + logger.error(String.format("[%s]Another state request pending for this Uuid. Cannot process.", shortID(uuid))); throw e; } @@ -795,16 +794,16 @@ public ByteString handleInvokeChaincode(String chaincodeName, String function, S ChaincodeMessage message = ChaincodeMessage.newBuilder() .setType(INVOKE_CHAINCODE) .setPayload(payload.toByteString()) - .setUuid(uuid) + .setTxid(uuid) .build(); logger.debug(String.format("[%s]Sending %s", - shortUUID(message), INVOKE_CHAINCODE)); + shortID(message), INVOKE_CHAINCODE)); try { serialSend(message); } catch (Exception e) { - logger.error("["+shortUUID(message)+"]Error sending "+INVOKE_CHAINCODE+": "+e.getMessage()); + logger.error("["+ shortID(message)+"]Error sending "+INVOKE_CHAINCODE+": "+e.getMessage()); throw e; } @@ -813,25 +812,25 @@ public ByteString handleInvokeChaincode(String chaincodeName, String function, S try { response = receiveChannel(responseChannel); } catch (Exception e) { - logger.error(String.format("[%s]Received unexpected message type", shortUUID(message))); + logger.error(String.format("[%s]Received unexpected message type", shortID(message))); throw new RuntimeException("Received unexpected message type"); } if (response.getType() == RESPONSE) { // Success response - logger.debug(String.format("[%s]Received %s. Successfully invoked chaincode", shortUUID(response.getUuid()), RESPONSE)); + logger.debug(String.format("[%s]Received %s. Successfully invoked chaincode", shortID(response.getTxid()), RESPONSE)); return response.getPayload(); } if (response.getType() == ERROR) { // Error response - logger.error(String.format("[%s]Received %s.", shortUUID(response.getUuid()), ERROR)); + logger.error(String.format("[%s]Received %s.", shortID(response.getTxid()), ERROR)); throw new RuntimeException(response.getPayload().toStringUtf8()); } // Incorrect chaincode message received logger.debug(String.format("[%s]Incorrect chaincode message %s received. Expecting %s or %s", - shortUUID(response.getUuid()), response.getType(), RESPONSE, ERROR)); + shortID(response.getTxid()), response.getType(), RESPONSE, ERROR)); throw new RuntimeException("Incorrect chaincode message received"); } finally { deleteChannel(uuid); @@ -865,15 +864,15 @@ public ByteString handleQueryChaincode(String chaincodeName, String function, St ChaincodeMessage message = ChaincodeMessage.newBuilder() .setType(INVOKE_QUERY) .setPayload(payload.toByteString()) - .setUuid(uuid) + .setTxid(uuid) .build(); - logger.debug(String.format("[%s]Sending %s", shortUUID(message), INVOKE_QUERY)); + logger.debug(String.format("[%s]Sending %s", shortID(message), INVOKE_QUERY)); try { serialSend(message); } catch (Exception e) { - logger.error(String.format("[%s]error sending %s", shortUUID(message), INVOKE_QUERY)); + logger.error(String.format("[%s]error sending %s", shortID(message), INVOKE_QUERY)); throw new RuntimeException("could not send message"); } @@ -882,27 +881,27 @@ public ByteString handleQueryChaincode(String chaincodeName, String function, St try { response = receiveChannel(responseChannel); } catch (Exception e) { - logger.error(String.format("[%s]Received unexpected message type", shortUUID(message))); + logger.error(String.format("[%s]Received unexpected message type", shortID(message))); throw new RuntimeException("Received unexpected message type"); } if (response.getType() == RESPONSE) { // Success response logger.debug(String.format("[%s]Received %s. Successfully queried chaincode", - shortUUID(response.getUuid()), RESPONSE)); + shortID(response.getTxid()), RESPONSE)); return response.getPayload(); } if (response.getType() == ERROR) { // Error response logger.error(String.format("[%s]Received %s.", - shortUUID(response.getUuid()), ERROR)); + shortID(response.getTxid()), ERROR)); throw new RuntimeException(response.getPayload().toStringUtf8()); } // Incorrect chaincode message received logger.error(String.format("[%s]Incorrect chaincode message %s recieved. Expecting %s or %s", - shortUUID(response.getUuid()), response.getType(), RESPONSE, ERROR)); + shortID(response.getTxid()), response.getType(), RESPONSE, ERROR)); throw new RuntimeException("Incorrect chaincode message received"); } finally { deleteChannel(uuid); @@ -915,22 +914,22 @@ public synchronized void handleMessage(ChaincodeMessage message) throws Exceptio if (message.getType() == ChaincodeMessage.Type.KEEPALIVE){ logger.debug(String.format("[%s] Recieved KEEPALIVE message, do nothing", - shortUUID(message))); + shortID(message))); // Received a keep alive message, we don't do anything with it for now // and it does not touch the state machine return; } logger.debug(String.format("[%s]Handling ChaincodeMessage of type: %s(state:%s)", - shortUUID(message), message.getType(), fsm.current())); + shortID(message), message.getType(), fsm.current())); if (fsm.eventCannotOccur(message.getType().toString())) { String errStr = String.format("[%s]Chaincode handler org.hyperledger.java.fsm cannot handle message (%s) with payload size (%d) while in state: %s", - message.getUuid(), message.getType(), message.getPayload().size(), fsm.current()); + message.getTxid(), message.getType(), message.getPayload().size(), fsm.current()); ByteString payload = ByteString.copyFromUtf8(errStr); ChaincodeMessage errormessage = ChaincodeMessage.newBuilder() .setType(ERROR) .setPayload(payload) - .setUuid(message.getUuid()) + .setTxid(message.getTxid()) .build(); serialSend(errormessage); throw new RuntimeException(errStr); @@ -942,15 +941,15 @@ public synchronized void handleMessage(ChaincodeMessage message) throws Exceptio fsm.raiseEvent(message.getType().toString(), message); } catch (NoTransitionException e) { if (e.error != null) throw e; - logger.debug("["+shortUUID(message)+"]Ignoring NoTransitionError"); + logger.debug("["+ shortID(message)+"]Ignoring NoTransitionError"); } catch (CancelledException e) { if (e.error != null) throw e; - logger.debug("["+shortUUID(message)+"]Ignoring CanceledError"); + logger.debug("["+ shortID(message)+"]Ignoring CanceledError"); } } - private String shortUUID(ChaincodeMessage message) { - return shortUUID(message.getUuid()); + private String shortID(ChaincodeMessage message) { + return shortID(message.getTxid()); } } diff --git a/core/chaincode/shim/java/src/main/proto/chaincode.proto b/core/chaincode/shim/java/src/main/proto/chaincode.proto index 94f034759c0..efb80a31c71 100644 --- a/core/chaincode/shim/java/src/main/proto/chaincode.proto +++ b/core/chaincode/shim/java/src/main/proto/chaincode.proto @@ -98,7 +98,7 @@ message ChaincodeInvocationSpec { ChaincodeSpec chaincodeSpec = 1; // This field can contain a user-specified ID generation algorithm // If supplied, this will be used to generate a ID - // If not supplied (left empty), a random UUID will be generated + // If not supplied (left empty), sha256base64 will be used // The algorithm consists of two parts: // 1, a hash function // 2, a decoding used to decode user (string) input to bytes @@ -149,7 +149,7 @@ message ChaincodeMessage { Type type = 1; google.protobuf.Timestamp timestamp = 2; bytes payload = 3; - string uuid = 4; + string txid = 4; ChaincodeSecurityContext securityContext = 5; //event emmited by chaincode. Used only with Init or Invoke. diff --git a/core/devops.go b/core/devops.go index 4fd3d4c54fd..16660fc92aa 100644 --- a/core/devops.go +++ b/core/devops.go @@ -193,7 +193,7 @@ func (d *Devops) Deploy(ctx context.Context, spec *pb.ChaincodeSpec) (*pb.Chainc } if devopsLogger.IsEnabledFor(logging.DEBUG) { - devopsLogger.Debugf("Sending deploy transaction (%s) to validator", tx.Uuid) + devopsLogger.Debugf("Sending deploy transaction (%s) to validator", tx.Txid) } resp := d.coord.ExecuteTransaction(tx) if resp.Status == pb.Response_FAILURE { @@ -213,13 +213,9 @@ func (d *Devops) invokeOrQuery(ctx context.Context, chaincodeInvocationSpec *pb. var customIDgenAlg = strings.ToLower(chaincodeInvocationSpec.IdGenerationAlg) var id string var generr error - if customIDgenAlg != "" { - id, generr = util.GenerateIDWithAlg(customIDgenAlg, chaincodeInvocationSpec.ChaincodeSpec.CtorMsg.Args[0]) - if generr != nil { - return nil, generr - } - } else { - id = util.GenerateUUID() + id, generr = util.GenerateIDWithAlg(customIDgenAlg, chaincodeInvocationSpec.ChaincodeSpec.CtorMsg.Args) + if generr != nil { + return nil, generr } devopsLogger.Infof("Transaction ID: %v", id) var transaction *pb.Transaction @@ -243,7 +239,7 @@ func (d *Devops) invokeOrQuery(ctx context.Context, chaincodeInvocationSpec *pb. return nil, err } if devopsLogger.IsEnabledFor(logging.DEBUG) { - devopsLogger.Debugf("Sending invocation transaction (%s) to validator", transaction.Uuid) + devopsLogger.Debugf("Sending invocation transaction (%s) to validator", transaction.Txid) } resp := d.coord.ExecuteTransaction(transaction) if resp.Status == pb.Response_FAILURE { @@ -448,7 +444,10 @@ func (d *Devops) EXP_ExecuteWithBinding(ctx context.Context, executeWithBinding return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte(err.Error())}, nil } - tid := util.GenerateUUID() + tid, generr := util.GenerateIDWithAlg("", executeWithBinding.ChaincodeInvocationSpec.ChaincodeSpec.CtorMsg.Args) + if generr != nil { + return nil, fmt.Errorf("Error: cannot generate TX ID (executing with binding)") + } tx, err := txHandler.NewChaincodeExecute(executeWithBinding.ChaincodeInvocationSpec, tid) if err != nil { diff --git a/core/ledger/blockchain.go b/core/ledger/blockchain.go index 4732439078e..abc7cbaf044 100644 --- a/core/ledger/blockchain.go +++ b/core/ledger/blockchain.go @@ -108,8 +108,8 @@ func (blockchain *blockchain) getBlockByHash(blockHash []byte) (*protos.Block, e return blockchain.getBlock(blockNumber) } -func (blockchain *blockchain) getTransactionByUUID(txUUID string) (*protos.Transaction, error) { - blockNumber, txIndex, err := blockchain.indexer.fetchTransactionIndexByUUID(txUUID) +func (blockchain *blockchain) getTransactionByID(txID string) (*protos.Transaction, error) { + blockNumber, txIndex, err := blockchain.indexer.fetchTransactionIndexByID(txID) if err != nil { return nil, err } diff --git a/core/ledger/blockchain_indexes.go b/core/ledger/blockchain_indexes.go index 5252f513891..9e17b7469e9 100644 --- a/core/ledger/blockchain_indexes.go +++ b/core/ledger/blockchain_indexes.go @@ -28,7 +28,7 @@ import ( var indexLogger = logging.MustGetLogger("indexes") var prefixBlockHashKey = byte(1) -var prefixTxUUIDKey = byte(2) +var prefixTxIDKey = byte(2) var prefixAddressBlockNumCompositeKey = byte(3) type blockchainIndexer interface { @@ -37,7 +37,7 @@ type blockchainIndexer interface { createIndexesSync(block *protos.Block, blockNumber uint64, blockHash []byte, writeBatch *gorocksdb.WriteBatch) error createIndexesAsync(block *protos.Block, blockNumber uint64, blockHash []byte) error fetchBlockNumberByBlockHash(blockHash []byte) (uint64, error) - fetchTransactionIndexByUUID(txUUID string) (uint64, uint64, error) + fetchTransactionIndexByID(txID string) (uint64, uint64, error) stop() } @@ -70,8 +70,8 @@ func (indexer *blockchainIndexerSync) fetchBlockNumberByBlockHash(blockHash []by return fetchBlockNumberByBlockHashFromDB(blockHash) } -func (indexer *blockchainIndexerSync) fetchTransactionIndexByUUID(txUUID string) (uint64, uint64, error) { - return fetchTransactionIndexByUUIDFromDB(txUUID) +func (indexer *blockchainIndexerSync) fetchTransactionIndexByID(txID string) (uint64, uint64, error) { + return fetchTransactionIndexByIDFromDB(txID) } func (indexer *blockchainIndexerSync) stop() { @@ -92,8 +92,8 @@ func addIndexDataForPersistence(block *protos.Block, blockNumber uint64, blockHa transactions := block.GetTransactions() for txIndex, tx := range transactions { - // add TxUUID -> (blockNumber,indexWithinBlock) - writeBatch.PutCF(cf, encodeTxUUIDKey(tx.Uuid), encodeBlockNumTxIndex(blockNumber, uint64(txIndex))) + // add TxID -> (blockNumber,indexWithinBlock) + writeBatch.PutCF(cf, encodeTxIDKey(tx.Txid), encodeBlockNumTxIndex(blockNumber, uint64(txIndex))) txExecutingAddress := getTxExecutingAddress(tx) addressToTxIndexesMap[txExecutingAddress] = append(addressToTxIndexesMap[txExecutingAddress], uint64(txIndex)) @@ -126,8 +126,8 @@ func fetchBlockNumberByBlockHashFromDB(blockHash []byte) (uint64, error) { return blockNumber, nil } -func fetchTransactionIndexByUUIDFromDB(txUUID string) (uint64, uint64, error) { - blockNumTxIndexBytes, err := db.GetDBHandle().GetFromIndexesCF(encodeTxUUIDKey(txUUID)) +func fetchTransactionIndexByIDFromDB(txID string) (uint64, uint64, error) { + blockNumTxIndexBytes, err := db.GetDBHandle().GetFromIndexesCF(encodeTxIDKey(txID)) if err != nil { return 0, 0, err } @@ -191,9 +191,9 @@ func encodeBlockHashKey(blockHash []byte) []byte { return prependKeyPrefix(prefixBlockHashKey, blockHash) } -// encode TxUUIDKey -func encodeTxUUIDKey(txUUID string) []byte { - return prependKeyPrefix(prefixTxUUIDKey, []byte(txUUID)) +// encode TxIDKey +func encodeTxIDKey(txID string) []byte { + return prependKeyPrefix(prefixTxIDKey, []byte(txID)) } func encodeAddressBlockNumCompositeKey(address string, blockNumber uint64) []byte { diff --git a/core/ledger/blockchain_indexes_async.go b/core/ledger/blockchain_indexes_async.go index 11b6484507e..d89528b6435 100644 --- a/core/ledger/blockchain_indexes_async.go +++ b/core/ledger/blockchain_indexes_async.go @@ -136,13 +136,13 @@ func (indexer *blockchainIndexerAsync) fetchBlockNumberByBlockHash(blockHash []b return fetchBlockNumberByBlockHashFromDB(blockHash) } -func (indexer *blockchainIndexerAsync) fetchTransactionIndexByUUID(txUUID string) (uint64, uint64, error) { +func (indexer *blockchainIndexerAsync) fetchTransactionIndexByID(txID string) (uint64, uint64, error) { err := indexer.indexerState.checkError() if err != nil { return 0, 0, err } indexer.indexerState.waitForLastCommittedBlock() - return fetchTransactionIndexByUUIDFromDB(txUUID) + return fetchTransactionIndexByIDFromDB(txID) } func (indexer *blockchainIndexerAsync) indexPendingBlocks() error { diff --git a/core/ledger/blockchain_indexes_async_test.go b/core/ledger/blockchain_indexes_async_test.go index 9d756c26b79..10d189f9631 100644 --- a/core/ledger/blockchain_indexes_async_test.go +++ b/core/ledger/blockchain_indexes_async_test.go @@ -62,11 +62,11 @@ func TestIndexesAsync_GetTransactionByBlockHashAndTxIndex(t *testing.T) { testIndexesGetTransactionByBlockHashAndTxIndex(t) } -func TestIndexesAsync_GetTransactionByUUID(t *testing.T) { +func TestIndexesAsync_GetTransactionByID(t *testing.T) { defaultSetting := indexBlockDataSynchronously indexBlockDataSynchronously = false defer func() { indexBlockDataSynchronously = defaultSetting }() - testIndexesGetTransactionByUUID(t) + testIndexesGetTransactionByID(t) } func TestIndexesAsync_IndexingErrorScenario(t *testing.T) { @@ -164,7 +164,7 @@ func (noop *NoopIndexer) createIndexesAsync(block *protos.Block, blockNumber uin func (noop *NoopIndexer) fetchBlockNumberByBlockHash(blockHash []byte) (uint64, error) { return 0, nil } -func (noop *NoopIndexer) fetchTransactionIndexByUUID(txUUID string) (uint64, uint64, error) { +func (noop *NoopIndexer) fetchTransactionIndexByID(txID string) (uint64, uint64, error) { return 0, 0, nil } func (noop *NoopIndexer) stop() { diff --git a/core/ledger/blockchain_indexes_test.go b/core/ledger/blockchain_indexes_test.go index 6e6016f241b..0239200d73d 100644 --- a/core/ledger/blockchain_indexes_test.go +++ b/core/ledger/blockchain_indexes_test.go @@ -58,11 +58,11 @@ func TestIndexes_GetTransactionByBlockHashAndTxIndex(t *testing.T) { testIndexesGetTransactionByBlockHashAndTxIndex(t) } -func TestIndexes_GetTransactionByUUID(t *testing.T) { +func TestIndexes_GetTransactionByID(t *testing.T) { defaultSetting := indexBlockDataSynchronously indexBlockDataSynchronously = true defer func() { indexBlockDataSynchronously = defaultSetting }() - testIndexesGetTransactionByUUID(t) + testIndexesGetTransactionByID(t) } func testIndexesGetBlockByBlockNumber(t *testing.T) { @@ -140,7 +140,7 @@ func testIndexesGetTransactionByBlockHashAndTxIndex(t *testing.T) { } } -func testIndexesGetTransactionByUUID(t *testing.T) { +func testIndexesGetTransactionByID(t *testing.T) { testDBWrapper.CleanDB(t) testBlockchainWrapper := newTestBlockchainWrapper(t) defer func() { testBlockchainWrapper.blockchain.indexer.stop() }() @@ -154,8 +154,8 @@ func testIndexesGetTransactionByUUID(t *testing.T) { block2 := protos.NewBlock([]*protos.Transaction{tx3, tx4}, nil) testBlockchainWrapper.addNewBlock(block2, []byte("stateHash2")) - testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByUUID(uuid1), tx1) - testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByUUID(uuid2), tx2) - testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByUUID(uuid3), tx3) - testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByUUID(uuid4), tx4) + testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByID(uuid1), tx1) + testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByID(uuid2), tx2) + testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByID(uuid3), tx3) + testutil.AssertEquals(t, testBlockchainWrapper.getTransactionByID(uuid4), tx4) } diff --git a/core/ledger/blockchain_test.go b/core/ledger/blockchain_test.go index d3e17b0b970..5cd8623e1a5 100644 --- a/core/ledger/blockchain_test.go +++ b/core/ledger/blockchain_test.go @@ -60,7 +60,7 @@ func TestBlockChain_SingleBlock(t *testing.T) { ChaincodeID: &protos.ChaincodeID{Path: "Contracts"}, CtorMsg: &protos.ChaincodeInput{Function: "Initialize", Args: []string{"param1"}}} chaincodeDeploymentSepc := &protos.ChaincodeDeploymentSpec{ChaincodeSpec: chaincodeSpec} - uuid := testutil.GenerateUUID(t) + uuid := testutil.GenerateID(t) newChaincodeTx, err := protos.NewChaincodeDeployTransaction(chaincodeDeploymentSepc, uuid) testutil.AssertNoError(t, err, "Failed to create new chaincode Deployment Transaction") t.Logf("New chaincode tx: %v", newChaincodeTx) diff --git a/core/ledger/ledger.go b/core/ledger/ledger.go index fbabab8eb81..c0160867ca6 100644 --- a/core/ledger/ledger.go +++ b/core/ledger/ledger.go @@ -227,14 +227,14 @@ func (ledger *Ledger) RollbackTxBatch(id interface{}) error { } // TxBegin - Marks the begin of a new transaction in the ongoing batch -func (ledger *Ledger) TxBegin(txUUID string) { - ledger.state.TxBegin(txUUID) +func (ledger *Ledger) TxBegin(txID string) { + ledger.state.TxBegin(txID) } // TxFinished - Marks the finish of the on-going transaction. // If txSuccessful is false, the state changes made by the transaction are discarded -func (ledger *Ledger) TxFinished(txUUID string, txSuccessful bool) { - ledger.state.TxFinish(txUUID, txSuccessful) +func (ledger *Ledger) TxFinished(txID string, txSuccessful bool) { + ledger.state.TxFinish(txID, txSuccessful) } /////////////////// world-state related methods ///////////////////////////////////// @@ -406,9 +406,9 @@ func (ledger *Ledger) GetBlockchainSize() uint64 { return ledger.blockchain.getSize() } -// GetTransactionByUUID return transaction by it's uuid -func (ledger *Ledger) GetTransactionByUUID(txUUID string) (*protos.Transaction, error) { - return ledger.blockchain.getTransactionByUUID(txUUID) +// GetTransactionByID return transaction by it's txId +func (ledger *Ledger) GetTransactionByID(txID string) (*protos.Transaction, error) { + return ledger.blockchain.getTransactionByID(txID) } // PutRawBlock puts a raw block on the chain. This function should only be diff --git a/core/ledger/ledger_test.go b/core/ledger/ledger_test.go index c4e014e966f..66d8cbe499d 100644 --- a/core/ledger/ledger_test.go +++ b/core/ledger/ledger_test.go @@ -683,7 +683,7 @@ func TestPreviewTXBatchBlock(t *testing.T) { testutil.AssertEquals(t, previewBlockInfo, committedBlockInfo) } -func TestGetTransactionByUUID(t *testing.T) { +func TestGetTransactionByID(t *testing.T) { ledgerTestWrapper := createFreshDBAndTestLedgerWrapper(t) ledger := ledgerTestWrapper.ledger @@ -697,11 +697,11 @@ func TestGetTransactionByUUID(t *testing.T) { transaction, uuid := buildTestTx(t) ledger.CommitTxBatch(0, []*protos.Transaction{transaction}, nil, []byte("proof")) - ledgerTransaction, err := ledger.GetTransactionByUUID(uuid) - testutil.AssertNoError(t, err, "Error fetching transaction by UUID.") + ledgerTransaction, err := ledger.GetTransactionByID(uuid) + testutil.AssertNoError(t, err, "Error fetching transaction by ID.") testutil.AssertEquals(t, transaction, ledgerTransaction) - ledgerTransaction, err = ledger.GetTransactionByUUID("InvalidUUID") + ledgerTransaction, err = ledger.GetTransactionByID("InvalidID") testutil.AssertEquals(t, err, ErrResourceNotFound) testutil.AssertNil(t, ledgerTransaction) } @@ -834,9 +834,9 @@ func TestGetSetMultipleKeys(t *testing.T) { ledgerTestWrapper := createFreshDBAndTestLedgerWrapper(t) l := ledgerTestWrapper.ledger l.BeginTxBatch(1) - l.TxBegin("txUUID") + l.TxBegin("txID") l.SetStateMultipleKeys("chaincodeID", map[string][]byte{"key1": []byte("value1"), "key2": []byte("value2")}) - l.TxFinished("txUUID", true) + l.TxFinished("txID", true) tx, _ := buildTestTx(t) l.CommitTxBatch(1, []*protos.Transaction{tx}, nil, nil) @@ -848,17 +848,17 @@ func TestCopyState(t *testing.T) { ledgerTestWrapper := createFreshDBAndTestLedgerWrapper(t) l := ledgerTestWrapper.ledger l.BeginTxBatch(1) - l.TxBegin("txUUID") + l.TxBegin("txID") l.SetStateMultipleKeys("chaincodeID1", map[string][]byte{"key1": []byte("value1"), "key2": []byte("value2")}) l.SetState("chaincodeID1", "key3", []byte("value3")) - l.TxFinished("txUUID", true) + l.TxFinished("txID", true) tx, _ := buildTestTx(t) l.CommitTxBatch(1, []*protos.Transaction{tx}, nil, nil) l.BeginTxBatch(2) - l.TxBegin("txUUID") + l.TxBegin("txID") l.CopyState("chaincodeID1", "chaincodeID2") - l.TxFinished("txUUID", true) + l.TxFinished("txID", true) tx, _ = buildTestTx(t) l.CommitTxBatch(2, []*protos.Transaction{tx}, nil, nil) @@ -870,9 +870,9 @@ func TestLedgerEmptyArrayValue(t *testing.T) { ledgerTestWrapper := createFreshDBAndTestLedgerWrapper(t) l := ledgerTestWrapper.ledger l.BeginTxBatch(1) - l.TxBegin("txUUID") + l.TxBegin("txID") l.SetState("chaincodeID1", "key1", []byte{}) - l.TxFinished("txUUID", true) + l.TxFinished("txID", true) tx, _ := buildTestTx(t) l.CommitTxBatch(1, []*protos.Transaction{tx}, nil, nil) @@ -891,7 +891,7 @@ func TestLedgerInvalidInput(t *testing.T) { ledgerTestWrapper := createFreshDBAndTestLedgerWrapper(t) l := ledgerTestWrapper.ledger l.BeginTxBatch(1) - l.TxBegin("txUUID") + l.TxBegin("txID") // nil value input err := l.SetState("chaincodeID1", "key1", nil) @@ -910,7 +910,7 @@ func TestLedgerInvalidInput(t *testing.T) { } l.SetState("chaincodeID1", "key1", []byte("value1")) - l.TxFinished("txUUID", true) + l.TxFinished("txID", true) tx, _ := buildTestTx(t) l.CommitTxBatch(1, []*protos.Transaction{tx}, nil, nil) value, _ := l.GetState("chaincodeID1", "key1", true) diff --git a/core/ledger/pkg_test.go b/core/ledger/pkg_test.go index 4d5cdcdc8f9..cea669fbd28 100644 --- a/core/ledger/pkg_test.go +++ b/core/ledger/pkg_test.go @@ -93,8 +93,8 @@ func (testWrapper *blockchainTestWrapper) getTransactionByBlockHash(blockHash [] return tx } -func (testWrapper *blockchainTestWrapper) getTransactionByUUID(txUUID string) *protos.Transaction { - tx, err := testWrapper.blockchain.getTransactionByUUID(txUUID) +func (testWrapper *blockchainTestWrapper) getTransactionByID(txID string) *protos.Transaction { + tx, err := testWrapper.blockchain.getTransactionByID(txID) testutil.AssertNoError(testWrapper.t, err, "Error while getting tx from blockchain") return tx } @@ -104,7 +104,7 @@ func (testWrapper *blockchainTestWrapper) populateBlockChainWithSampleData() (bl // ------------------------------------------------------------ // Add the first (genesis block) - block1 := protos.NewBlock(nil, []byte(testutil.GenerateUUID(testWrapper.t))) + block1 := protos.NewBlock(nil, []byte(testutil.GenerateID(testWrapper.t))) allBlocks = append(allBlocks, block1) allHashes = append(allHashes, []byte("stateHash1")) testWrapper.addNewBlock(block1, []byte("stateHash1")) @@ -113,7 +113,7 @@ func (testWrapper *blockchainTestWrapper) populateBlockChainWithSampleData() (bl // ------------------------------------------------------------------ // Deploy a chaincode - transaction2a, err := protos.NewTransaction(protos.ChaincodeID{Path: "Contracts"}, testutil.GenerateUUID(testWrapper.t), "NewContract", []string{"name: MyContract1, code: var x; function setX(json) {x = json.x}}"}) + transaction2a, err := protos.NewTransaction(protos.ChaincodeID{Path: "Contracts"}, testutil.GenerateID(testWrapper.t), "NewContract", []string{"name: MyContract1, code: var x; function setX(json) {x = json.x}}"}) if err != nil { return nil, nil, err } @@ -128,7 +128,7 @@ func (testWrapper *blockchainTestWrapper) populateBlockChainWithSampleData() (bl // ------------------------------------------------------------------ // Create a transaction - transaction3a, err := protos.NewTransaction(protos.ChaincodeID{Path: "MyContract"}, testutil.GenerateUUID(testWrapper.t), "setX", []string{"{x: \"hello\"}"}) + transaction3a, err := protos.NewTransaction(protos.ChaincodeID{Path: "MyContract"}, testutil.GenerateID(testWrapper.t), "setX", []string{"{x: \"hello\"}"}) if err != nil { return nil, nil, err } diff --git a/core/ledger/statemgmt/state/state.go b/core/ledger/statemgmt/state/state.go index dd7838ba96b..320091c48f0 100644 --- a/core/ledger/statemgmt/state/state.go +++ b/core/ledger/statemgmt/state/state.go @@ -42,7 +42,7 @@ type State struct { stateImpl statemgmt.HashableState stateDelta *statemgmt.StateDelta currentTxStateDelta *statemgmt.StateDelta - currentTxUUID string + currentTxID string txStateDeltaHash map[string][]byte updateStateImpl bool historyStateDeltaSize uint64 @@ -71,36 +71,36 @@ func NewState() *State { } // TxBegin marks begin of a new tx. If a tx is already in progress, this call panics -func (state *State) TxBegin(txUUID string) { - logger.Debugf("txBegin() for txUuid [%s]", txUUID) +func (state *State) TxBegin(txID string) { + logger.Debugf("txBegin() for txId [%s]", txID) if state.txInProgress() { - panic(fmt.Errorf("A tx [%s] is already in progress. Received call for begin of another tx [%s]", state.currentTxUUID, txUUID)) + panic(fmt.Errorf("A tx [%s] is already in progress. Received call for begin of another tx [%s]", state.currentTxID, txID)) } - state.currentTxUUID = txUUID + state.currentTxID = txID } -// TxFinish marks the completion of on-going tx. If txUUID is not same as of the on-going tx, this call panics -func (state *State) TxFinish(txUUID string, txSuccessful bool) { - logger.Debugf("txFinish() for txUuid [%s], txSuccessful=[%t]", txUUID, txSuccessful) - if state.currentTxUUID != txUUID { - panic(fmt.Errorf("Different Uuid in tx-begin [%s] and tx-finish [%s]", state.currentTxUUID, txUUID)) +// TxFinish marks the completion of on-going tx. If txID is not same as of the on-going tx, this call panics +func (state *State) TxFinish(txID string, txSuccessful bool) { + logger.Debugf("txFinish() for txUuid [%s], txSuccessful=[%t]", txID, txSuccessful) + if state.currentTxID != txID { + panic(fmt.Errorf("Different Uuid in tx-begin [%s] and tx-finish [%s]", state.currentTxID, txID)) } if txSuccessful { if !state.currentTxStateDelta.IsEmpty() { - logger.Debugf("txFinish() for txUuid [%s] merging state changes", txUUID) + logger.Debugf("txFinish() for txUuid [%s] merging state changes", txID) state.stateDelta.ApplyChanges(state.currentTxStateDelta) - state.txStateDeltaHash[txUUID] = state.currentTxStateDelta.ComputeCryptoHash() + state.txStateDeltaHash[txID] = state.currentTxStateDelta.ComputeCryptoHash() state.updateStateImpl = true } else { - state.txStateDeltaHash[txUUID] = nil + state.txStateDeltaHash[txID] = nil } } state.currentTxStateDelta = statemgmt.NewStateDelta() - state.currentTxUUID = "" + state.currentTxID = "" } func (state *State) txInProgress() bool { - return state.currentTxUUID != "" + return state.currentTxID != "" } // Get returns state for chaincodeID and key. If committed is false, this first looks in memory and if missing, diff --git a/core/ledger/test/ledger_test.go b/core/ledger/test/ledger_test.go index 331f3f3edfb..b8ccec4096b 100644 --- a/core/ledger/test/ledger_test.go +++ b/core/ledger/test/ledger_test.go @@ -123,14 +123,14 @@ var _ = Describe("Ledger", func() { Expect(err).To(BeNil()) Expect(previewBlockInfo).To(Equal(commitedBlockInfo)) }) - It("can get a transaction by it's UUID", func() { + It("can get a transaction by it's ID", func() { uuid := util.GenerateUUID() tx, err := protos.NewTransaction(protos.ChaincodeID{Path: "testUrl"}, uuid, "anyfunction", []string{"param1, param2"}) Expect(err).To(BeNil()) err = ledgerPtr.CommitTxBatch(1, []*protos.Transaction{tx}, nil, []byte("proof")) Expect(err).To(BeNil()) - ledgerTransaction, err := ledgerPtr.GetTransactionByUUID(uuid) + ledgerTransaction, err := ledgerPtr.GetTransactionByID(uuid) Expect(err).To(BeNil()) Expect(tx).To(Equal(ledgerTransaction)) state, _ := ledgerPtr.GetState("chaincode1", "key1", true) @@ -162,7 +162,7 @@ var _ = Describe("Ledger", func() { }) It("commits and validates a batch with a bad transaction result", func() { uuid := util.GenerateUUID() - transactionResult := &protos.TransactionResult{Uuid: uuid, ErrorCode: 500, Error: "bad"} + transactionResult := &protos.TransactionResult{Txid: uuid, ErrorCode: 500, Error: "bad"} tx, err := protos.NewTransaction(protos.ChaincodeID{Path: "testUrl"}, uuid, "anyfunction", []string{"param1, param2"}) ledgerPtr.CommitTxBatch(1, []*protos.Transaction{tx}, []*protos.TransactionResult{transactionResult}, []byte("proof")) diff --git a/core/ledger/testutil/test_util.go b/core/ledger/testutil/test_util.go index ee91c951d3a..a9379312a71 100644 --- a/core/ledger/testutil/test_util.go +++ b/core/ledger/testutil/test_util.go @@ -179,9 +179,8 @@ func AppendAll(content ...[]byte) []byte { return combinedContent } -func GenerateUUID(t *testing.T) string { - uuid := util.GenerateUUID() - return uuid +func GenerateID(t *testing.T) string { + return util.GenerateUUID() } func ConstructRandomBytes(t testing.TB, size int) []byte { diff --git a/core/peer/peer.go b/core/peer/peer.go index f90436b306a..a8ec366c9cb 100644 --- a/core/peer/peer.go +++ b/core/peer/peer.go @@ -283,13 +283,13 @@ func (p *Impl) Chat(stream pb.Peer_ChatServer) error { // ProcessTransaction implementation of the ProcessTransaction RPC function func (p *Impl) ProcessTransaction(ctx context.Context, tx *pb.Transaction) (response *pb.Response, err error) { - peerLogger.Debugf("ProcessTransaction processing transaction uuid = %s", tx.Uuid) + peerLogger.Debugf("ProcessTransaction processing transaction txid = %s", tx.Txid) // Need to validate the Tx's signature if we are a validator. if p.isValidator { // Verify transaction signature if security is enabled secHelper := p.secHelper if nil != secHelper { - peerLogger.Debugf("Verifying transaction signature %s", tx.Uuid) + peerLogger.Debugf("Verifying transaction signature %s", tx.Txid) if tx, err = secHelper.TransactionPreValidation(tx); err != nil { peerLogger.Errorf("ProcessTransaction failed to verify transaction %v", err) return &pb.Response{Status: pb.Response_FAILURE, Msg: []byte(err.Error())}, nil diff --git a/core/rest/api.go b/core/rest/api.go index 0af8f3e1e3a..fe14a36a842 100644 --- a/core/rest/api.go +++ b/core/rest/api.go @@ -148,9 +148,9 @@ func (s *ServerOpenchain) GetState(ctx context.Context, chaincodeID, key string) return s.ledger.GetState(chaincodeID, key, true) } -// GetTransactionByUUID returns a transaction matching the specified UUID -func (s *ServerOpenchain) GetTransactionByUUID(ctx context.Context, txUUID string) (*pb.Transaction, error) { - transaction, err := s.ledger.GetTransactionByUUID(txUUID) +// GetTransactionByID returns a transaction matching the specified ID +func (s *ServerOpenchain) GetTransactionByID(ctx context.Context, txID string) (*pb.Transaction, error) { + transaction, err := s.ledger.GetTransactionByID(txID) if err != nil { switch err { case ledger.ErrResourceNotFound: diff --git a/core/rest/api_test.go b/core/rest/api_test.go index 11636796c93..c94b80b2173 100644 --- a/core/rest/api_test.go +++ b/core/rest/api_test.go @@ -278,9 +278,9 @@ func buildTestLedger1(ledger1 *ledger.Ledger, t *testing.T) { } // VM runs transaction1a and updates the global state with the result // In this case, the 'Contracts' contract stores 'MyContract1' in its state - ledger1.TxBegin(transaction1a.Uuid) + ledger1.TxBegin(transaction1a.Txid) ledger1.SetState("MyContract1", "code", []byte("code example")) - ledger1.TxFinished(transaction1a.Uuid, true) + ledger1.TxFinished(transaction1a.Txid, true) ledger1.CommitTxBatch(1, []*protos.Transaction{transaction1a}, nil, []byte("dummy-proof")) // ---------------------------------------------------------------- @@ -299,10 +299,10 @@ func buildTestLedger1(ledger1 *ledger.Ledger, t *testing.T) { } // Run this transction in the VM. The VM updates the state - ledger1.TxBegin(transaction2a.Uuid) + ledger1.TxBegin(transaction2a.Txid) ledger1.SetState("MyContract", "x", []byte("hello")) ledger1.SetState("MyOtherContract", "y", []byte("goodbuy")) - ledger1.TxFinished(transaction2a.Uuid, true) + ledger1.TxFinished(transaction2a.Txid, true) // Commit txbatch that creates the 2nd block on blockchain ledger1.CommitTxBatch(2, []*protos.Transaction{transaction2a, transaction2b}, nil, []byte("dummy-proof")) @@ -335,9 +335,9 @@ func buildTestLedger2(ledger *ledger.Ledger, t *testing.T) { } // VM runs transaction1a and updates the global state with the result // In this case, the 'Contracts' contract stores 'MyContract1' in its state - ledger.TxBegin(transaction1a.Uuid) + ledger.TxBegin(transaction1a.Txid) ledger.SetState("MyContract1", "code", []byte("code example")) - ledger.TxFinished(transaction1a.Uuid, true) + ledger.TxFinished(transaction1a.Txid, true) ledger.CommitTxBatch(1, []*protos.Transaction{transaction1a}, nil, []byte("dummy-proof")) // ---------------------------------------------------------------- @@ -357,10 +357,10 @@ func buildTestLedger2(ledger *ledger.Ledger, t *testing.T) { } // Run this transction in the VM. The VM updates the state - ledger.TxBegin(transaction2a.Uuid) + ledger.TxBegin(transaction2a.Txid) ledger.SetState("MyContract", "x", []byte("hello")) ledger.SetState("MyOtherContract", "y", []byte("goodbuy")) - ledger.TxFinished(transaction2a.Uuid, true) + ledger.TxFinished(transaction2a.Txid, true) // Commit txbatch that creates the 2nd block on blockchain ledger.CommitTxBatch(2, []*protos.Transaction{transaction2a, transaction2b}, nil, []byte("dummy-proof")) @@ -384,11 +384,11 @@ func buildTestLedger2(ledger *ledger.Ledger, t *testing.T) { t.Logf("Error creating NewTransaction: %s", err) t.Fail() } - ledger.TxBegin(transaction3a.Uuid) + ledger.TxBegin(transaction3a.Txid) ledger.SetState("MyContract", "x", []byte("hello")) ledger.SetState("MyOtherContract", "y", []byte("goodbuy")) ledger.SetState("MyImportantContract", "z", []byte("super")) - ledger.TxFinished(transaction3a.Uuid, true) + ledger.TxFinished(transaction3a.Txid, true) ledger.CommitTxBatch(3, []*protos.Transaction{transaction3a, transaction3b, transaction3c}, nil, []byte("dummy-proof")) // ---------------------------------------------------------------- @@ -421,12 +421,12 @@ func buildTestLedger2(ledger *ledger.Ledger, t *testing.T) { } // Run this transction in the VM. The VM updates the state - ledger.TxBegin(transaction4a.Uuid) + ledger.TxBegin(transaction4a.Txid) ledger.SetState("MyContract", "x", []byte("hello")) ledger.SetState("MyOtherContract", "y", []byte("goodbuy")) ledger.SetState("MyImportantContract", "z", []byte("super")) ledger.SetState("MyMEGAContract", "mega", []byte("MEGA")) - ledger.TxFinished(transaction4a.Uuid, true) + ledger.TxFinished(transaction4a.Txid, true) // Create the 4th block and add it to the chain ledger.CommitTxBatch(4, []*protos.Transaction{transaction4a, transaction4b, transaction4c, transaction4d}, nil, []byte("dummy-proof")) diff --git a/core/rest/rest_api.go b/core/rest/rest_api.go index 0668a49dbf3..2390428c773 100644 --- a/core/rest/rest_api.go +++ b/core/rest/rest_api.go @@ -689,13 +689,13 @@ func (s *ServerOpenchainREST) GetBlockByNumber(rw web.ResponseWriter, req *web.R encoder.Encode(block) } -// GetTransactionByUUID returns a transaction matching the specified UUID -func (s *ServerOpenchainREST) GetTransactionByUUID(rw web.ResponseWriter, req *web.Request) { - // Parse out the transaction UUID - txUUID := req.PathParams["uuid"] +// GetTransactionByID returns a transaction matching the specified ID +func (s *ServerOpenchainREST) GetTransactionByID(rw web.ResponseWriter, req *web.Request) { + // Parse out the transaction ID + txID := req.PathParams["id"] - // Retrieve the transaction matching the UUID - tx, err := s.server.GetTransactionByUUID(context.Background(), txUUID) + // Retrieve the transaction matching the ID + tx, err := s.server.GetTransactionByID(context.Background(), txID) encoder := json.NewEncoder(rw) @@ -704,17 +704,17 @@ func (s *ServerOpenchainREST) GetTransactionByUUID(rw web.ResponseWriter, req *w switch err { case ErrNotFound: rw.WriteHeader(http.StatusNotFound) - encoder.Encode(restResult{Error: fmt.Sprintf("Transaction %s is not found.", txUUID)}) + encoder.Encode(restResult{Error: fmt.Sprintf("Transaction %s is not found.", txID)}) default: rw.WriteHeader(http.StatusInternalServerError) - encoder.Encode(restResult{Error: fmt.Sprintf("Error retrieving transaction %s: %s.", txUUID, err)}) - restLogger.Errorf("Error retrieving transaction %s: %s", txUUID, err) + encoder.Encode(restResult{Error: fmt.Sprintf("Error retrieving transaction %s: %s.", txID, err)}) + restLogger.Errorf("Error retrieving transaction %s: %s", txID, err) } } else { // Return existing transaction rw.WriteHeader(http.StatusOK) encoder.Encode(tx) - restLogger.Infof("Successfully retrieved transaction: %s", txUUID) + restLogger.Infof("Successfully retrieved transaction: %s", txID) } } @@ -1000,13 +1000,13 @@ func (s *ServerOpenchainREST) Invoke(rw web.ResponseWriter, req *web.Request) { return } - // Clients will need the txuuid in order to track it after invocation - txuuid := resp.Msg + // Clients will need the txid in order to track it after invocation + txid := resp.Msg rw.WriteHeader(http.StatusOK) // Make a clarification in the invoke response message, that the transaction has been successfully submitted but not completed - fmt.Fprintf(rw, "{\"OK\": \"Successfully submitted invoke transaction.\",\"message\": \"%s\"}", string(txuuid)) - restLogger.Infof("Successfully submitted invoke transaction (%s).\n", string(txuuid)) + fmt.Fprintf(rw, "{\"OK\": \"Successfully submitted invoke transaction.\",\"message\": \"%s\"}", string(txid)) + restLogger.Infof("Successfully submitted invoke transaction (%s).\n", string(txid)) } // Query performs the requested query on the target Chaincode. @@ -1621,16 +1621,16 @@ func (s *ServerOpenchainREST) processChaincodeInvokeOrQuery(method string, spec // Invocation succeeded // - // Clients will need the txuuid in order to track it after invocation, record it - txuuid := string(resp.Msg) + // Clients will need the txid in order to track it after invocation, record it + txid := string(resp.Msg) // // Output correctly formatted response // - result = formatRPCOK(txuuid) + result = formatRPCOK(txid) // Make a clarification in the invoke response message, that the transaction has been successfully submitted but not completed - restLogger.Infof("Successfully submitted invoke transaction with txuuid (%s)", txuuid) + restLogger.Infof("Successfully submitted invoke transaction with txid (%s)", txid) } if method == "query" { @@ -1741,7 +1741,7 @@ func buildOpenchainRESTRouter() *web.Router { // The /chaincode endpoint which superceedes the /devops endpoint from above router.Post("/chaincode", (*ServerOpenchainREST).ProcessChaincode) - router.Get("/transactions/:uuid", (*ServerOpenchainREST).GetTransactionByUUID) + router.Get("/transactions/:id", (*ServerOpenchainREST).GetTransactionByID) router.Get("/network/peers", (*ServerOpenchainREST).GetPeers) diff --git a/core/rest/rest_api.json b/core/rest/rest_api.json index d2fbb9deadb..e6ed9c5c53b 100644 --- a/core/rest/rest_api.json +++ b/core/rest/rest_api.json @@ -69,16 +69,16 @@ } } }, - "/transactions/{UUID}": { + "/transactions/{ID}": { "get": { "summary": "Individual transaction contents", - "description": "The /transactions/{UUID} endpoint returns the transaction matching the specified UUID.", + "description": "The /transactions/{ID} endpoint returns the transaction matching the specified TXID.", "tags": [ "Transactions" ], "operationId": "getTransaction", "parameters": [{ - "name": "UUID", + "name": "ID", "in": "path", "description": "Transaction to retrieve from the blockchain.", "type": "string", @@ -103,7 +103,7 @@ "/devops/deploy": { "post": { "summary": "[DEPRECATED] Service endpoint for deploying Chaincode [DEPRECATED]", - "description": "The /devops/deploy endpoint receives Chaincode deployment requests. The Chaincode and the required entities are first packaged into a container and subsequently deployed to the blockchain. If the Chaincode build and deployment are successful, a confirmation message is returned. Otherwise, an error is displayed alongside with a reason for the failure. This service endpoint is being deprecated, please use the /chaincode endpoint instead.", + "description": "The /devops/deploy endpoint receives Chaincode deployment requests. The ChaincodTXand the required entities are first packaged into a container and subsequently deployed to the blockchain. If the Chaincode build and deployment are successful, a confirmation message is returned. Otherwise, an error is displayed alongside with a reason for the failure. This service endpoint is being deprecated, please use the /chaincode endpoint instead.", "tags": [ "Chaincode" ], @@ -504,7 +504,7 @@ "format": "bytes", "description": "Payload supplied for Chaincode function execution." }, - "uuid": { + "id": { "type": "string", "description": "Unique transaction identifier." }, diff --git a/core/rest/rest_api_test.go b/core/rest/rest_api_test.go index 0eec300a9c3..9f1af52a854 100644 --- a/core/rest/rest_api_test.go +++ b/core/rest/rest_api_test.go @@ -291,14 +291,14 @@ func TestServerOpenchainREST_API_GetTransactionByUUID(t *testing.T) { } firstTx := block1.Transactions[0] - body1 := performHTTPGet(t, httpServer.URL+"/transactions/"+firstTx.Uuid) + body1 := performHTTPGet(t, httpServer.URL+"/transactions/"+firstTx.Txid) var tx1 protos.Transaction err = json.Unmarshal(body1, &tx1) if err != nil { t.Fatalf("Invalid JSON response: %v", err) } - if tx1.Uuid != firstTx.Uuid { - t.Errorf("Expected transaction uuid to be '%v' but got '%v'", firstTx.Uuid, tx1.Uuid) + if tx1.Txid != firstTx.Txid { + t.Errorf("Expected transaction uuid to be '%v' but got '%v'", firstTx.Txid, tx1.Txid) } if tx1.Timestamp.Seconds < startTime { t.Errorf("Expected transaction timestamp (%v) to be after the start time (%v)", tx1.Timestamp.Seconds, startTime) diff --git a/core/util/utils.go b/core/util/utils.go index 9454efcbe2c..056a616e527 100644 --- a/core/util/utils.go +++ b/core/util/utils.go @@ -19,7 +19,6 @@ package util import ( "crypto/rand" "crypto/sha256" - "encoding/base64" "fmt" "io" "math/big" @@ -32,12 +31,13 @@ import ( ) type alg struct { - hashFun func([]byte) string - decoder func(string) ([]byte, error) + hashFun func([]string) string } +const defaultAlg = "sha256" + var availableIDgenAlgs = map[string]alg{ - "sha256base64": alg{GenerateUUIDfromTxSHAHash, base64.StdEncoding.DecodeString}, + defaultAlg: alg{GenerateIDfromTxSHAHash}, } // ComputeCryptoHash should be used in openchain code so that we can change the actual algo used for crypto-hash at one place @@ -74,7 +74,7 @@ func GenerateIntUUID() *big.Int { // GenerateUUID returns a UUID based on RFC 4122 func GenerateUUID() string { uuid := GenerateBytesUUID() - return uuidBytesToStr(uuid) + return idBytesToStr(uuid) } // CreateUtcTimestamp returns a google/protobuf/Timestamp in UTC @@ -101,28 +101,30 @@ func GenerateHashFromSignature(path string, ctor string, args []string) []byte { return hash } -// GenerateUUIDfromTxSHAHash generates SHA256 hash using Tx payload, and uses its first -// 128 bits as a UUID -func GenerateUUIDfromTxSHAHash(txData []byte) string { - txHash := sha256.Sum256(txData) - return uuidBytesToStr(txHash[0:16]) +// GenerateIDfromTxSHAHash generates SHA256 hash using Tx payload +func GenerateIDfromTxSHAHash(payload []string) string { + h := sha256.New() + for _, part := range payload { + utf8bytes := []byte(part) + h.Write(utf8bytes) + } + return fmt.Sprintf("%x", h.Sum([]byte{})) } // GenerateIDWithAlg generates an ID using a custom algorithm -func GenerateIDWithAlg(customIDgenAlg string, encodedPayload string) (string, error) { +func GenerateIDWithAlg(customIDgenAlg string, strPayload []string) (string, error) { + if customIDgenAlg == "" { + customIDgenAlg = defaultAlg + } var alg = availableIDgenAlgs[customIDgenAlg] - if alg.hashFun != nil && alg.decoder != nil { - var payload, err = alg.decoder(encodedPayload) - if err != nil { - return "", err - } - return alg.hashFun(payload), nil + if alg.hashFun != nil { + return alg.hashFun(strPayload), nil } - return "", fmt.Errorf("Wrong UUID generation algorithm was given.") + return "", fmt.Errorf("Wrong ID generation algorithm was given: %s", customIDgenAlg) } -func uuidBytesToStr(uuid []byte) string { - return fmt.Sprintf("%x-%x-%x-%x-%x", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:]) +func idBytesToStr(id []byte) string { + return fmt.Sprintf("%x-%x-%x-%x-%x", id[0:4], id[4:6], id[6:8], id[8:10], id[10:]) } // FindMissingElements identifies the elements of the first slice that are not present in the second diff --git a/examples/events/block-listener/block-listener.go b/examples/events/block-listener/block-listener.go index a670ed059d8..d661ff30e37 100644 --- a/examples/events/block-listener/block-listener.go +++ b/examples/events/block-listener/block-listener.go @@ -123,7 +123,7 @@ func main() { fmt.Printf("\n") fmt.Printf("Received rejected transaction\n") fmt.Printf("--------------\n") - fmt.Printf("Transaction error:\n%s\t%s\n", r.Rejection.Tx.Uuid, r.Rejection.ErrorMsg) + fmt.Printf("Transaction error:\n%s\t%s\n", r.Rejection.Tx.Txid, r.Rejection.ErrorMsg) case ce := <-a.cEvent: fmt.Printf("\n") fmt.Printf("\n") diff --git a/protos/block_test.go b/protos/block_test.go index a93e614afac..fdaef3312df 100644 --- a/protos/block_test.go +++ b/protos/block_test.go @@ -43,7 +43,7 @@ func Test_Block_CreateNew(t *testing.T) { if err != nil { t.Fatalf("Could not marshal chaincode: %s", err) } - transaction := &Transaction{Type: 2, ChaincodeID: cidBytes, Payload: data, Uuid: "001"} + transaction := &Transaction{Type: 2, ChaincodeID: cidBytes, Payload: data, Txid: "001"} t.Logf("Transaction: %v", transaction) block := NewBlock([]*Transaction{transaction}, nil) diff --git a/protos/chaincode.pb.go b/protos/chaincode.pb.go index 1c9e9eb04b5..acbfe93a20a 100644 --- a/protos/chaincode.pb.go +++ b/protos/chaincode.pb.go @@ -259,7 +259,7 @@ type ChaincodeInvocationSpec struct { ChaincodeSpec *ChaincodeSpec `protobuf:"bytes,1,opt,name=chaincodeSpec" json:"chaincodeSpec,omitempty"` // This field can contain a user-specified ID generation algorithm // If supplied, this will be used to generate a ID - // If not supplied (left empty), a random UUID will be generated + // If not supplied (left empty), sha256base64 will be used // The algorithm consists of two parts: // 1, a hash function // 2, a decoding used to decode user (string) input to bytes @@ -307,7 +307,7 @@ type ChaincodeMessage struct { Type ChaincodeMessage_Type `protobuf:"varint,1,opt,name=type,enum=protos.ChaincodeMessage_Type" json:"type,omitempty"` Timestamp *google_protobuf.Timestamp `protobuf:"bytes,2,opt,name=timestamp" json:"timestamp,omitempty"` Payload []byte `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` - Uuid string `protobuf:"bytes,4,opt,name=uuid" json:"uuid,omitempty"` + Txid string `protobuf:"bytes,4,opt,name=txid" json:"txid,omitempty"` SecurityContext *ChaincodeSecurityContext `protobuf:"bytes,5,opt,name=securityContext" json:"securityContext,omitempty"` // event emmited by chaincode. Used only with Init or Invoke. // This event is then stored (currently) diff --git a/protos/chaincode.proto b/protos/chaincode.proto index 94f034759c0..efb80a31c71 100644 --- a/protos/chaincode.proto +++ b/protos/chaincode.proto @@ -98,7 +98,7 @@ message ChaincodeInvocationSpec { ChaincodeSpec chaincodeSpec = 1; // This field can contain a user-specified ID generation algorithm // If supplied, this will be used to generate a ID - // If not supplied (left empty), a random UUID will be generated + // If not supplied (left empty), sha256base64 will be used // The algorithm consists of two parts: // 1, a hash function // 2, a decoding used to decode user (string) input to bytes @@ -149,7 +149,7 @@ message ChaincodeMessage { Type type = 1; google.protobuf.Timestamp timestamp = 2; bytes payload = 3; - string uuid = 4; + string txid = 4; ChaincodeSecurityContext securityContext = 5; //event emmited by chaincode. Used only with Init or Invoke. diff --git a/protos/fabric.pb.go b/protos/fabric.pb.go index 10e278dcff6..567e36a9b90 100644 --- a/protos/fabric.pb.go +++ b/protos/fabric.pb.go @@ -171,7 +171,7 @@ type Transaction struct { ChaincodeID []byte `protobuf:"bytes,2,opt,name=chaincodeID,proto3" json:"chaincodeID,omitempty"` Payload []byte `protobuf:"bytes,3,opt,name=payload,proto3" json:"payload,omitempty"` Metadata []byte `protobuf:"bytes,4,opt,name=metadata,proto3" json:"metadata,omitempty"` - Uuid string `protobuf:"bytes,5,opt,name=uuid" json:"uuid,omitempty"` + Txid string `protobuf:"bytes,5,opt,name=txid" json:"txid,omitempty"` Timestamp *google_protobuf.Timestamp `protobuf:"bytes,6,opt,name=timestamp" json:"timestamp,omitempty"` ConfidentialityLevel ConfidentialityLevel `protobuf:"varint,7,opt,name=confidentialityLevel,enum=protos.ConfidentialityLevel" json:"confidentialityLevel,omitempty"` ConfidentialityProtocolVersion string `protobuf:"bytes,8,opt,name=confidentialityProtocolVersion" json:"confidentialityProtocolVersion,omitempty"` @@ -210,13 +210,13 @@ func (m *TransactionBlock) GetTransactions() []*Transaction { // TransactionResult contains the return value of a transaction. It does // not track potential state changes that were a result of the transaction. -// uuid - The unique identifier of this transaction. +// txid - The unique identifier of this transaction. // result - The return value of the transaction. // errorCode - An error code. 5xx will be logged as a failure in the dashboard. // error - An error string for logging an issue. // chaincodeEvent - any event emitted by a transaction type TransactionResult struct { - Uuid string `protobuf:"bytes,1,opt,name=uuid" json:"uuid,omitempty"` + Txid string `protobuf:"bytes,1,opt,name=txid" json:"txid,omitempty"` Result []byte `protobuf:"bytes,2,opt,name=result,proto3" json:"result,omitempty"` ErrorCode uint32 `protobuf:"varint,3,opt,name=errorCode" json:"errorCode,omitempty"` Error string `protobuf:"bytes,4,opt,name=error" json:"error,omitempty"` diff --git a/protos/fabric.proto b/protos/fabric.proto index cc910f6d664..fabdf678f62 100644 --- a/protos/fabric.proto +++ b/protos/fabric.proto @@ -42,7 +42,7 @@ message Transaction { bytes chaincodeID = 2; bytes payload = 3; bytes metadata = 4; - string uuid = 5; + string txid = 5; google.protobuf.Timestamp timestamp = 6; ConfidentialityLevel confidentialityLevel = 7; @@ -61,13 +61,13 @@ message TransactionBlock { // TransactionResult contains the return value of a transaction. It does // not track potential state changes that were a result of the transaction. -// uuid - The unique identifier of this transaction. +// txid - The unique identifier of this transaction. // result - The return value of the transaction. // errorCode - An error code. 5xx will be logged as a failure in the dashboard. // error - An error string for logging an issue. // chaincodeEvent - any event emitted by a transaction message TransactionResult { - string uuid = 1; + string txid = 1; bytes result = 2; uint32 errorCode = 3; string error = 4; diff --git a/protos/transaction.go b/protos/transaction.go index 13308e1a78a..49360800b79 100644 --- a/protos/transaction.go +++ b/protos/transaction.go @@ -44,7 +44,7 @@ func NewTransaction(chaincodeID ChaincodeID, uuid string, function string, argum } transaction := new(Transaction) transaction.ChaincodeID = data - transaction.Uuid = uuid + transaction.Txid = uuid transaction.Timestamp = util.CreateUtcTimestamp() /* // Build the spec @@ -67,7 +67,7 @@ func NewTransaction(chaincodeID ChaincodeID, uuid string, function string, argum func NewChaincodeDeployTransaction(chaincodeDeploymentSpec *ChaincodeDeploymentSpec, uuid string) (*Transaction, error) { transaction := new(Transaction) transaction.Type = Transaction_CHAINCODE_DEPLOY - transaction.Uuid = uuid + transaction.Txid = uuid transaction.Timestamp = util.CreateUtcTimestamp() cID := chaincodeDeploymentSpec.ChaincodeSpec.GetChaincodeID() if cID != nil { @@ -94,7 +94,7 @@ func NewChaincodeDeployTransaction(chaincodeDeploymentSpec *ChaincodeDeploymentS func NewChaincodeExecute(chaincodeInvocationSpec *ChaincodeInvocationSpec, uuid string, typ Transaction_Type) (*Transaction, error) { transaction := new(Transaction) transaction.Type = typ - transaction.Uuid = uuid + transaction.Txid = uuid transaction.Timestamp = util.CreateUtcTimestamp() cID := chaincodeInvocationSpec.ChaincodeSpec.GetChaincodeID() if cID != nil {