github.com/0chain/gosdk@v1.17.11/zboxcore/fileref/hashnode.go (about)

     1  package fileref
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  
     7  	"github.com/0chain/gosdk/core/encryption"
     8  )
     9  
    10  // Hashnode ref node in hash tree
    11  type Hashnode struct {
    12  	// hash data
    13  	AllocationID    string `json:"allocation_id,omitempty"`
    14  	Type            string `json:"type,omitempty"`
    15  	Name            string `json:"name,omitempty"`
    16  	Path            string `json:"path,omitempty"`
    17  	ValidationRoot  string `json:"validation_root,omitempty"`
    18  	FixedMerkleRoot string `json:"fixed_merkle_root,omitempty"`
    19  	ActualFileHash  string `json:"actual_file_hash,omitempty"`
    20  	ChunkSize       int64  `json:"chunk_size,omitempty"`
    21  	Size            int64  `json:"size,omitempty"`
    22  	ActualFileSize  int64  `json:"actual_file_size,omitempty"`
    23  
    24  	Children   []*Hashnode `json:"children,omitempty"`
    25  	lookupHash string      `json:"-"`
    26  }
    27  
    28  func (n *Hashnode) AddChild(c *Hashnode) {
    29  	if n.Children == nil {
    30  		n.Children = make([]*Hashnode, 0, 10)
    31  	}
    32  
    33  	n.Children = append(n.Children, c)
    34  }
    35  
    36  // GetLookupHash get lookuphash
    37  func (n *Hashnode) GetLookupHash() string {
    38  	if n.lookupHash == "" {
    39  		n.lookupHash = encryption.Hash(n.AllocationID + ":" + n.Path)
    40  	}
    41  	return n.lookupHash
    42  }
    43  
    44  // GetHashCode get hash code
    45  func (n *Hashnode) GetHashCode() string {
    46  	// dir
    47  	if n.Type == DIRECTORY {
    48  		if len(n.Children) == 0 {
    49  			return ""
    50  		}
    51  
    52  		childHashes := make([]string, len(n.Children))
    53  
    54  		var size int64
    55  
    56  		for i, child := range n.Children {
    57  			childHashes[i] = child.GetHashCode()
    58  			size += child.Size
    59  		}
    60  
    61  		n.Size = size
    62  
    63  		return encryption.Hash(strings.Join(childHashes, ":"))
    64  
    65  	}
    66  
    67  	hashArray := []string{
    68  		n.AllocationID,
    69  		n.Type,
    70  		n.Name,
    71  		n.Path,
    72  		strconv.FormatInt(n.Size, 10),
    73  		n.ValidationRoot,
    74  		n.FixedMerkleRoot,
    75  		strconv.FormatInt(n.ActualFileSize, 10),
    76  		n.ActualFileHash,
    77  		strconv.FormatInt(n.ChunkSize, 10),
    78  	}
    79  
    80  	return encryption.Hash(strings.Join(hashArray, ":"))
    81  
    82  }