Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Note about hashing: sha256() and hash() #382

Open
Vladimir-Khm opened this issue Sep 8, 2024 · 0 comments
Open

Note about hashing: sha256() and hash() #382

Vladimir-Khm opened this issue Sep 8, 2024 · 0 comments

Comments

@Vladimir-Khm
Copy link

History of the problem

I was trying to create a small catalog in a map using a hash of an item as a key and value as a price. There was a struct item:

struct Item {
    prop1: String;
    prop2: String;
    prop3: String;
    prop4: String;
}

To calculate a hash of this item I used this code: sha256(msg.item.toCell().asSlice()) which seems to be fine, but suddenly I realized that smart contract does very strange things. After precise debugging, I found out the problem was that the code above returns absolutely the same hash despite all items being different. It is because sha256 is a math function that calculates a hash only of the first ref cell in my case. The ref cells of the struct were always the same, so the sha256() results were the same too. To calculate the hash of this struct you need to write this code: item.toCell().hash()

Proposal

From my point of view, it is an important note to prevent many hard-catching bugs and make smart contracts a little bit safer, so my suggestions are:

  1. Also write hash function for structs to simply write: someStruct.hash()
  2. Write down that if you want to calculate a hash of the object you need hash() and NOT sha256(). Emphases the difference between these two functions
  3. Write down small examples to make the difference clear
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant