Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the principles of Fabric chain code development?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the principles of Fabric chain code development, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. Enable the development mode of peer node

Use development mode to start your Hyperledger Fabric chain code development process. This point cannot be overemphasized, and it will save you a lot of time and effort, because you are free to modify the code without redeploying and activating the chain code, or restarting the network over and over again.

2. Log using Fabric chain code

This may be the first useful skill to help you debug the Hyperledger Fabric chain code and quickly find the chain code bug. Chain code log is easy to use, just use logger built in Fabric.

3. Avoid using global keys in Fabric chain codes

When developing Hyperledger Fabric chain codes, we often find that there are many limitations in searching data, so to track keys registered in the key-value library, we sometimes try to use some global data.

For example, when you track registered marbles in the Hyperledger Fabric application, you may want to create a global counter to generate the next ID of the marbles. But when you do this, you introduce a dependency on this variable. This doesn't seem like a problem at first, but you can make mistakes when you submit concurrent transactions. Why? Let me explain.

Take a look at the chain code:

Package mainimport (/ / other imports "github.com/hyperledger/fabric/core/chaincode/shim" pb "github.com/hyperledger/fabric/protos/peer") / / Don't do this! TotalNumberOfMarbles: = 0func (t * SimpleChaincode) initMarble (stub shim.ChaincodeStubInterface, args [] string) pb.Response {var err error marbleId: = fmt.Sprintf ("MARBLE_d", totalNumberOfMarbles) marbleName: = args [0] color: = strings.ToLower (args [1]) owner: = strings.ToLower (args [3]) size Err: = strconv.Atoi (args [2]) / / other code to initialize objectType: = "marble" marble: = & marble {objectType, marbleId, marbleName, color, size, owner} / /-CODE SMELL- / / BIG source of Non-determinism as well as performance hit. TotalNumberOfMarbles = totalNumberOfMarbles + 1 / /-CODE SMELL- / / regular stuff... Err = stub.PutState (marbleId, marbleJSONasBytes) if err! = nil {return shim.Error (err.Error ())}}

So, why don't I like it?

The first reason. Suppose you have completed the Fabric chain code, and everything is fine until one day, a peer node running the chain code crashes. Although the ledger data are still there, something terrible has happened inside. You may restart the peer node and everything looks fine at first. But suddenly, all the deals endorsed by this node began to fail. Why? It is because the global count variable can no longer track the real value correctly. Other peer nodes count to, say, 15K, and this node suddenly starts counting from zero, and the ID of your marbles starts from zero again. Therefore, when you send the transaction to the sorting node (Orderer) and reach the submission node (Peer), the verification system (Validation System Chaincode) on the submission node will compare the proposal responses of all endorsement transactions and check if there are enough signatures, and if one proposal response does not match, the submission node will throw an ENDORSEMENT_POLICY_FAILURE exception.

The second reason. Now let's try to solve the above problem by adding the following code at the end of the Fabric chain code:

Stub.PutState ("marble_count", totalNumberOfMarbles)

Would that be better? Noooooooooooooooooo!

Imagine two concurrent transactions trying to insert new marbles.

For example, a transaction needs to update the value of marble_count to 34. The new version of the status of MarbleCount is 10. Another deal updates the value of marble_count to 35, which also considers the new version of marble_count to be 10. Remember, because the two transactions are concurrent, both transactions see current_version (marble_count) = 09.

Now one of the transactions will arrive at the sorting node of Fabric before another transaction, and the marble_ count key has been updated to the new value, so the version of marble_count is already 10, so the later transaction will fail because the version of marble_count is already 10, and the subsequent transaction still thinks that it is reading version 09 and will be updated to version 10. This is the classic double flower problem (double spending) in blockchain.

Hyperledger Fabric uses an optimized locking model when submitting transactions. As I have already explained, the proposal response is collected by the client from the endorsement node, then sent to the sorting node and eventually distributed to the submission node by the sorting node. During this two-step process, if the version of some keys read during the endorsement phase changes, you will get a MVCC_READ_CONFLICT error. This problem can occur when there are concurrent transactions while updating the same key.

For a detailed explanation of this point, you can refer to this article.

4. Use CouchDB query wisely

Couch DB queries (also known as Mongo queries) are useful when searching for data in the key-value library of Fabric nodes, but there are some holes you need to be aware of.

The Couch DB query does not modify the READ SET of the transaction

The Mongo query is only used to query the node's key-value library, that is, the state library. It does not modify the read set of the deal. This can lead to phantom reads in the transaction.

You can only search for data that has been stored in CouchDB

Do not try to search with the Mongo query button name. Although you can access the Fauxton console of CouchDB, you cannot press the key to query. For example, querying channelName\ 0000KeyName is not allowed. A better way is to save the key as an attribute of your own data.

5. Write deterministic Fabric chain codes

Never write uncertain chain codes. It means that if I execute the chain code at many different times and in different environments, I should always get the same result. For example, avoid using things like rand.New (...). Or code such as t: = time.Now (), or rely on a variable that is not persisted in the account book.

This is because Hyperledger Fabric's verification system chain code (Validation System Chaincode) rejects the transaction and throws an ENDORSEMENT_POLICY_FAILURE exception if the generated read-write set is different.

6. Be careful when calling the Fabric chain codes of other channels

It's okay to call another chain code in the same channel in the chain code, but understand that if you want to call the chain code of another channel, you can only get the return result of the chain code method, and there will not be any submission in the account book of the other channel. Currently, cross-channel chain code calls do not modify data, so only one channel can be written to a transaction at a time.

7. Remember to set the execution timeout of the Fabric chain code

Under high load, your Hyperledger Fabric chain code may not be completed within 30 seconds. Therefore, it is a good practice to customize the chain code execution timeout value according to the requirements. This is determined by the parameters in core.yaml. You can set the following settings in the docker compose file:

Example: CORE_CHAINCODE_EXECUTETIMEOUT=60s8, avoid accessing external resources from Fabric chain codes

Accessing external resources may expose system vulnerabilities and introduce security threats to your Hyperledger Fabric chain code. In any case, you don't want malicious code in external resources to affect your chain code logic. Therefore, please avoid accessing resources outside the block chain in the Fabric chain code as much as possible.

Thank you for reading this article carefully. I hope the article "what are the principles of Fabric chain code development" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report