github.com/0chain/gosdk@v1.17.11/core/util/merkle_tree_interface.go (about) 1 package util 2 3 import ( 4 "encoding/hex" 5 6 "github.com/0chain/gosdk/core/encryption" 7 "github.com/minio/sha256-simd" 8 ) 9 10 /*MerkleTreeI - a merkle tree interface required for constructing and providing verification */ 11 type MerkleTreeI interface { 12 //API to create a tree from leaf nodes 13 ComputeTree(hashes []Hashable) 14 GetRoot() string 15 GetTree() []string 16 17 //API to load an existing tree 18 SetTree(leavesCount int, tree []string) error 19 20 // API for verification when the leaf node is known 21 GetPath(hash Hashable) *MTPath // Server needs to provide this 22 VerifyPath(hash Hashable, path *MTPath) bool //This is only required by a client but useful for testing 23 24 /* API for random verification when the leaf node is uknown 25 (verification of the data to hash used as leaf node is outside this API) */ 26 GetPathByIndex(idx int) *MTPath 27 } 28 29 /*MTPath - The merkle tree path*/ 30 type MTPath struct { 31 Nodes []string `json:"nodes"` 32 LeafIndex int `json:"leaf_index"` 33 } 34 35 /*Hash - the hashing used for the merkle tree construction */ 36 func Hash(text string) string { 37 return encryption.Hash(text) 38 } 39 40 func MHashBytes(h1, h2 []byte) []byte { 41 buf := make([]byte, len(h1)+len(h2)) 42 copy(buf, h1) 43 copy(buf[len(h1):], h2) 44 hash := sha256.New() 45 _, _ = hash.Write(buf) 46 return hash.Sum(nil) 47 } 48 49 /*MHash - merkle hashing of a pair of child hashes */ 50 func MHash(h1 string, h2 string) string { 51 return Hash(h1 + h2) 52 } 53 54 // DecodeAndMHash will decode hex-encoded string to []byte format. 55 // This function should only be used with hex-encoded string otherwise the result will 56 // be obsolute. 57 func DecodeAndMHash(h1, h2 string) string { 58 b1, _ := hex.DecodeString(h1) 59 60 b2, _ := hex.DecodeString(h2) 61 62 b3 := MHashBytes(b1, b2) 63 return hex.EncodeToString(b3) 64 } 65 66 type StringHashable struct { 67 Hash string 68 } 69 70 func NewStringHashable(hash string) *StringHashable { 71 return &StringHashable{Hash: hash} 72 } 73 74 func (sh *StringHashable) GetHash() string { 75 return sh.Hash 76 } 77 func (sh *StringHashable) GetHashBytes() []byte { 78 return []byte(sh.Hash) 79 } 80 81 func (StringHashable) Write(_ []byte) (int, error) { 82 return 0, nil 83 }