Skip to content

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

Closed
@Vladimir-Khm

Description

@Vladimir-Khm

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

Metadata

Metadata

Assignees

Labels

kind: docsDocumentation for docs.tact-lang.org kept in docs folder

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions