github.com/igggame/nebulas-go@v2.1.0+incompatible/common/trie/trie.go (about)

     1  // Copyright (C) 2017 go-nebulas authors
     2  //
     3  // This file is part of the go-nebulas library.
     4  //
     5  // the go-nebulas library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // the go-nebulas library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13  // GNU General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU General Public License
    16  // along with the go-nebulas library.  If not, see <http://www.gnu.org/licenses/>.
    17  //
    18  
    19  package trie
    20  
    21  import (
    22  	"errors"
    23  
    24  	"github.com/gogo/protobuf/proto"
    25  	"github.com/nebulasio/go-nebulas/common/trie/pb"
    26  	"github.com/nebulasio/go-nebulas/crypto/hash"
    27  	"github.com/nebulasio/go-nebulas/storage"
    28  )
    29  
    30  // Errors
    31  var (
    32  	ErrNotFound           = storage.ErrKeyNotFound
    33  	ErrInvalidProtoToNode = errors.New("Pb Message cannot be converted into Trie Node")
    34  )
    35  
    36  // Action represents operation types in Trie
    37  type Action int
    38  
    39  // Action constants
    40  const (
    41  	Insert Action = iota
    42  	Update
    43  	Delete
    44  )
    45  
    46  // Entry in log, [key, old value, new value]
    47  type Entry struct {
    48  	action Action
    49  	key    []byte
    50  	old    []byte
    51  	update []byte
    52  }
    53  
    54  // Flag to identify the type of node
    55  type ty int
    56  
    57  const (
    58  	unknown ty = iota
    59  	ext
    60  	leaf
    61  	branch
    62  )
    63  
    64  // Node in trie, three kinds,
    65  // Branch Node [hash_0, hash_1, ..., hash_f]
    66  // Extension Node [flag, encodedPath, next hash]
    67  // Leaf Node [flag, encodedPath, value]
    68  type node struct {
    69  	Hash  []byte
    70  	Bytes []byte
    71  	Val   [][]byte
    72  }
    73  
    74  func (n *node) ToProto() (proto.Message, error) {
    75  	return &triepb.Node{
    76  		Val: n.Val,
    77  	}, nil
    78  }
    79  
    80  func (n *node) FromProto(msg proto.Message) error {
    81  	if msg, ok := msg.(*triepb.Node); ok {
    82  		if msg != nil {
    83  			bytes, err := proto.Marshal(msg)
    84  			if err != nil {
    85  				return err
    86  			}
    87  			n.Bytes = bytes
    88  			n.Hash = hash.Sha3256(n.Bytes)
    89  			n.Val = msg.Val
    90  			return nil
    91  		}
    92  		return ErrInvalidProtoToNode
    93  	}
    94  	return ErrInvalidProtoToNode
    95  }
    96  
    97  // Type of node, e.g. Branch, Extension, Leaf Node
    98  func (n *node) Type() (ty, error) {
    99  	if n.Val == nil {
   100  		return unknown, errors.New("nil node")
   101  	}
   102  	switch len(n.Val) {
   103  	case 16: // Branch Node
   104  		return branch, nil
   105  	case 3: // Extension Node or Leaf Node
   106  		if n.Val[0] == nil {
   107  			return unknown, errors.New("unknown node type")
   108  		}
   109  		return ty(n.Val[0][0]), nil
   110  	default:
   111  		return unknown, errors.New("wrong node value, expect [16][]byte or [3][]byte, get [" + string(len(n.Val)) + "][]byte")
   112  	}
   113  }
   114  
   115  // Trie is a Merkle Patricia Trie, consists of three kinds of nodes,
   116  // Branch Node: 16-elements array, value is [hash_0, hash_1, ..., hash_f, hash]
   117  // Extension Node: 3-elements array, value is [ext flag, prefix path, next hash]
   118  // Leaf Node: 3-elements array, value is [leaf flag, suffix path, value]
   119  type Trie struct {
   120  	rootHash      []byte
   121  	storage       storage.Storage
   122  	changelog     []*Entry
   123  	needChangelog bool
   124  }
   125  
   126  // CreateNode in trie
   127  func (t *Trie) createNode(val [][]byte) (*node, error) {
   128  	n := &node{Val: val}
   129  	if err := t.commitNode(n); err != nil {
   130  		return nil, err
   131  	}
   132  	return n, nil
   133  }
   134  
   135  // FetchNode in trie
   136  func (t *Trie) fetchNode(hash []byte) (*node, error) {
   137  	ir, err := t.storage.Get(hash)
   138  
   139  	if err != nil {
   140  		return nil, err
   141  	}
   142  
   143  	pb := new(triepb.Node)
   144  	if err := proto.Unmarshal(ir, pb); err != nil {
   145  		return nil, err
   146  	}
   147  	n := new(node)
   148  	if err := n.FromProto(pb); err != nil {
   149  		return nil, err
   150  	}
   151  	return n, nil
   152  }
   153  
   154  // CommitNode node in trie into storage
   155  func (t *Trie) commitNode(n *node) error {
   156  	pb, err := n.ToProto()
   157  	if err != nil {
   158  		return err
   159  	}
   160  	n.Bytes, err = proto.Marshal(pb)
   161  	if err != nil {
   162  		return err
   163  	}
   164  	n.Hash = hash.Sha3256(n.Bytes)
   165  
   166  	return t.storage.Put(n.Hash, n.Bytes)
   167  }
   168  
   169  // NewTrie if rootHash is nil, create a new Trie, otherwise, build an existed trie
   170  func NewTrie(rootHash []byte, storage storage.Storage, needChangelog bool) (*Trie, error) {
   171  	t := &Trie{
   172  		rootHash:      rootHash,
   173  		storage:       storage,
   174  		needChangelog: needChangelog,
   175  	}
   176  	if t.rootHash == nil || len(t.rootHash) == 0 {
   177  		return t, nil
   178  	} else if _, err := t.storage.Get(rootHash); err != nil {
   179  		return nil, err
   180  	}
   181  	return t, nil
   182  }
   183  
   184  // RootHash return the rootHash of trie
   185  func (t *Trie) RootHash() []byte {
   186  	return t.rootHash
   187  }
   188  
   189  // Empty return if the trie is empty
   190  func (t *Trie) Empty() bool {
   191  	return t.rootHash == nil
   192  }
   193  
   194  // Get the value to the key in trie
   195  func (t *Trie) Get(key []byte) ([]byte, error) {
   196  	return t.get(t.rootHash, keyToRoute(key))
   197  }
   198  
   199  func (t *Trie) get(rootHash []byte, route []byte) ([]byte, error) {
   200  	curRootHash := rootHash
   201  	curRoute := route
   202  	for len(curRoute) >= 0 {
   203  		rootNode, err := t.fetchNode(curRootHash)
   204  		if err != nil {
   205  			return nil, err
   206  		}
   207  		flag, err := rootNode.Type()
   208  		if err != nil {
   209  			return nil, err
   210  		}
   211  		if len(curRoute) == 0 && flag != leaf {
   212  			return nil, errors.New("wrong key, too short")
   213  		}
   214  		switch flag {
   215  		case branch:
   216  			curRootHash = rootNode.Val[curRoute[0]]
   217  			curRoute = curRoute[1:]
   218  			break
   219  		case ext:
   220  			path := rootNode.Val[1]
   221  			next := rootNode.Val[2]
   222  			matchLen := prefixLen(path, curRoute)
   223  			if matchLen != len(path) {
   224  				return nil, ErrNotFound
   225  			}
   226  			curRootHash = next
   227  			curRoute = curRoute[matchLen:]
   228  			break
   229  		case leaf:
   230  			path := rootNode.Val[1]
   231  			matchLen := prefixLen(path, curRoute)
   232  			if matchLen != len(path) || matchLen != len(curRoute) {
   233  				return nil, ErrNotFound
   234  			}
   235  			return rootNode.Val[2], nil
   236  		default:
   237  			return nil, errors.New("unknown node type")
   238  		}
   239  	}
   240  	return nil, ErrNotFound
   241  }
   242  
   243  // Put the key-value pair in trie
   244  func (t *Trie) Put(key []byte, val []byte) ([]byte, error) {
   245  	newHash, err := t.update(t.rootHash, keyToRoute(key), val)
   246  	if err != nil {
   247  		return nil, err
   248  	}
   249  	t.rootHash = newHash
   250  
   251  	if t.needChangelog {
   252  		entry := &Entry{Update, key, nil, val}
   253  		t.changelog = append(t.changelog, entry)
   254  	}
   255  
   256  	return newHash, nil
   257  }
   258  
   259  func (t *Trie) update(root []byte, route []byte, val []byte) ([]byte, error) {
   260  	if root == nil || len(root) == 0 {
   261  		// directly add leaf node
   262  		value := [][]byte{[]byte{byte(leaf)}, route, val}
   263  		node, err := t.createNode(value)
   264  		if err != nil {
   265  			return nil, err
   266  		}
   267  		return node.Hash, nil
   268  	}
   269  	rootNode, err := t.fetchNode(root)
   270  	if err != nil {
   271  		return nil, err
   272  	}
   273  	flag, err := rootNode.Type()
   274  	if err != nil {
   275  		return nil, err
   276  	}
   277  	switch flag {
   278  	case branch:
   279  		return t.updateWhenMeetBranch(rootNode, route, val)
   280  	case ext:
   281  		return t.updateWhenMeetExt(rootNode, route, val)
   282  	case leaf:
   283  		return t.updateWhenMeetLeaf(rootNode, route, val)
   284  	default:
   285  		return nil, errors.New("unknown node type")
   286  	}
   287  }
   288  
   289  // add new node to one branch of branch node's 16 branches according to route
   290  func (t *Trie) updateWhenMeetBranch(rootNode *node, route []byte, val []byte) ([]byte, error) {
   291  	// update sub-trie
   292  	newHash, err := t.update(rootNode.Val[route[0]], route[1:], val)
   293  	if err != nil {
   294  		return nil, err
   295  	}
   296  	// update the branch hash
   297  	rootNode.Val[route[0]] = newHash
   298  	// save updated node to storage
   299  	t.commitNode(rootNode)
   300  	return rootNode.Hash, nil
   301  }
   302  
   303  // split ext node's into an ext node and a branch node based on
   304  // the longest common prefix between route and ext node's path
   305  // add ext node's child and new node to the branch node
   306  func (t *Trie) updateWhenMeetExt(rootNode *node, route []byte, val []byte) ([]byte, error) {
   307  	var err error
   308  	path := rootNode.Val[1]
   309  	next := rootNode.Val[2]
   310  	if len(path) > len(route) {
   311  		return nil, errors.New("wrong key, too short")
   312  	}
   313  	matchLen := prefixLen(path, route)
   314  	// add new node to the ext node's sub-trie
   315  	if matchLen == len(path) {
   316  		newHash, err := t.update(next, route[matchLen:], val)
   317  		if err != nil {
   318  			return nil, err
   319  		}
   320  		// update the new hash
   321  		rootNode.Val[2] = newHash
   322  		// save updated node to storage
   323  		t.commitNode(rootNode)
   324  		return rootNode.Hash, nil
   325  	}
   326  	// create a new branch for the new node
   327  	brNode := emptyBranchNode()
   328  	// 4 situations
   329  	// 1. matchLen > 0 && matchLen == len(path), 24 meets 24... => ext - branch - ...
   330  	// 2. matchLen > 0 && matchLen + 1 < len(path), 23... meets 24... => ext - branch - ext ...
   331  	// 3. matchLen = 0 && len(path) = 1, 1 meets 2 => branch - ...
   332  	if matchLen > 0 || len(path) == 1 {
   333  		// a branch to hold the ext node's sub-trie
   334  		brNode.Val[path[matchLen]] = next
   335  		if matchLen > 0 && matchLen+1 < len(path) {
   336  			value := [][]byte{[]byte{byte(ext)}, path[matchLen+1:], next}
   337  			extNode, err := t.createNode(value)
   338  			if err != nil {
   339  				return nil, err
   340  			}
   341  			brNode.Val[path[matchLen]] = extNode.Hash
   342  		}
   343  		// a branch to hold the new node
   344  		if brNode.Val[route[matchLen]], err = t.update(nil, route[matchLen+1:], val); err != nil {
   345  			return nil, err
   346  		}
   347  		// save branch to the storage
   348  		if err := t.commitNode(brNode); err != nil {
   349  			return nil, err
   350  		}
   351  		// if no common prefix, replace the ext node with the new branch node
   352  		if matchLen == 0 {
   353  			return brNode.Hash, nil
   354  		}
   355  		// use the new branch node as the ext node's sub-trie
   356  		rootNode.Val[1] = path[0:matchLen]
   357  		rootNode.Val[2] = brNode.Hash
   358  		if err := t.commitNode(rootNode); err != nil {
   359  			return nil, err
   360  		}
   361  		return rootNode.Hash, nil
   362  	}
   363  	// 4. matchLen = 0 && len(path) > 1, 12... meets 23... => branch - ext - ...
   364  	rootNode.Val[1] = path[1:]
   365  	// save ext node to storage
   366  	if err := t.commitNode(rootNode); err != nil {
   367  		return nil, err
   368  	}
   369  	brNode.Val[path[matchLen]] = rootNode.Hash
   370  	// a branch to hold the new node
   371  	if brNode.Val[route[matchLen]], err = t.update(nil, route[matchLen+1:], val); err != nil {
   372  		return nil, err
   373  	}
   374  	// save branch to the storage
   375  	if err := t.commitNode(brNode); err != nil {
   376  		return nil, err
   377  	}
   378  	return brNode.Hash, nil
   379  }
   380  
   381  // split leaf node's into an ext node and a branch node based on
   382  // the longest common prefix between route and leaf node's path
   383  // add new node to the branch node
   384  func (t *Trie) updateWhenMeetLeaf(rootNode *node, route []byte, val []byte) ([]byte, error) {
   385  	var err error
   386  	path := rootNode.Val[1]
   387  	leafVal := rootNode.Val[2]
   388  	if len(path) > len(route) {
   389  		return nil, errors.New("wrong key, too short")
   390  	}
   391  	matchLen := prefixLen(path, route)
   392  
   393  	// node exists, update its value
   394  	if matchLen == len(path) {
   395  
   396  		if len(route) > matchLen {
   397  			return nil, errors.New("wrong key, too long")
   398  		}
   399  		rootNode.Val[2] = val
   400  		// save updated node to storage
   401  		t.commitNode(rootNode)
   402  		return rootNode.Hash, nil
   403  	}
   404  	// create a new branch for the new node
   405  	brNode := emptyBranchNode()
   406  	// a branch to hold the leaf node
   407  	if brNode.Val[path[matchLen]], err = t.update(nil, path[matchLen+1:], leafVal); err != nil {
   408  		return nil, err
   409  	}
   410  	// a branch to hold the new node
   411  	if brNode.Val[route[matchLen]], err = t.update(nil, route[matchLen+1:], val); err != nil {
   412  		return nil, err
   413  	}
   414  	// save the new branch node to storage
   415  	if err := t.commitNode(brNode); err != nil {
   416  		return nil, err
   417  	}
   418  	// if no common prefix, replace the leaf node with the new branch node
   419  	if matchLen == 0 {
   420  		return brNode.Hash, nil
   421  	}
   422  	// create a new ext node, and use the new branch node as the new ext node's sub-trie
   423  	rootNode.Val[0] = []byte{byte(ext)}
   424  	rootNode.Val[1] = path[0:matchLen]
   425  	rootNode.Val[2] = brNode.Hash
   426  	if err := t.commitNode(rootNode); err != nil {
   427  		return nil, err
   428  	}
   429  	return rootNode.Hash, nil
   430  }
   431  
   432  // Del the node's value in trie
   433  /*
   434  	1. ext(ext->leaf-->leaf,ext->ext--->ext)
   435  	2. branch(branch->leaf-->leaf,branch->branch-->ext->branch,branch->ext-->ext)
   436  
   437  	 ext		 ext
   438  	  | 		  |
   439  	branch 	-->	 leaf	-->	leaf
   440  	/	\
   441  [leaf]	leaf
   442  
   443    	branch					 ext
   444  	/	\					  |
   445  [leaf]	ext		--> 	    branch
   446  		 |
   447  	   branch
   448  
   449    	branch					 ext
   450  	/	\					  |
   451  [leaf]	branch		--> 	branch
   452  		/	\				/	\
   453  		leaf leaf			leaf leaf
   454  
   455  */
   456  func (t *Trie) Del(key []byte) ([]byte, error) {
   457  	newHash, err := t.del(t.rootHash, keyToRoute(key))
   458  	if err != nil {
   459  		return nil, err
   460  	}
   461  	t.rootHash = newHash
   462  
   463  	if t.needChangelog {
   464  		entry := &Entry{Delete, key, nil, nil}
   465  		t.changelog = append(t.changelog, entry)
   466  	}
   467  	return newHash, nil
   468  }
   469  
   470  func (t *Trie) del(root []byte, route []byte) ([]byte, error) {
   471  	if root == nil || len(root) == 0 {
   472  		return nil, ErrNotFound
   473  	}
   474  	// fetch sub-trie root node
   475  	rootNode, err := t.fetchNode(root)
   476  	if err != nil {
   477  		return nil, err
   478  	}
   479  	flag, err := rootNode.Type()
   480  	if err != nil {
   481  		return nil, err
   482  	}
   483  	switch flag {
   484  	case branch:
   485  		newHash, err := t.del(rootNode.Val[route[0]], route[1:])
   486  		if err != nil {
   487  			return nil, err
   488  		}
   489  		rootNode.Val[route[0]] = newHash
   490  
   491  		// remove empty branch node
   492  		if isEmptyBranch(rootNode) {
   493  			return nil, nil
   494  		}
   495  		if lenBranch(rootNode) == 1 {
   496  			return t.deleteWhenMeetSingleBranch(rootNode)
   497  		}
   498  
   499  		if err := t.commitNode(rootNode); err != nil {
   500  			return nil, err
   501  		}
   502  		return rootNode.Hash, nil
   503  
   504  	case ext:
   505  		path := rootNode.Val[1]
   506  		next := rootNode.Val[2]
   507  		matchLen := prefixLen(path, route)
   508  		if matchLen != len(path) {
   509  			return nil, ErrNotFound
   510  		}
   511  		childHash, err := t.del(next, route[matchLen:])
   512  		if err != nil {
   513  			return nil, err
   514  		}
   515  		// remove empty ext node
   516  		if childHash == nil {
   517  			return nil, nil
   518  		}
   519  
   520  		// child hash
   521  		var newHash []byte
   522  		newHash, err = t.deleteWhenMeetSingleExt(rootNode, childHash)
   523  		if err != nil {
   524  			return nil, err
   525  		}
   526  		if newHash != nil {
   527  			return newHash, nil
   528  		}
   529  
   530  		rootNode.Val[2] = childHash
   531  		if err := t.commitNode(rootNode); err != nil {
   532  			return nil, err
   533  		}
   534  		return rootNode.Hash, nil
   535  	case leaf:
   536  		path := rootNode.Val[1]
   537  		matchLen := prefixLen(path, route)
   538  		if matchLen != len(path) {
   539  			return nil, ErrNotFound
   540  		}
   541  		return nil, nil
   542  	default:
   543  		return nil, errors.New("unknown node type")
   544  	}
   545  }
   546  
   547  // deleteWhenMeetSingleExt
   548  func (t *Trie) deleteWhenMeetSingleExt(rootNode *node, hash []byte) ([]byte, error) {
   549  	childNode, err := t.fetchNode(hash)
   550  	if err != nil {
   551  		return nil, err
   552  	}
   553  	flag, err := childNode.Type()
   554  	if err != nil {
   555  		return nil, err
   556  	}
   557  
   558  	if flag == ext { //ext->ext --> ext
   559  		childNode.Val[1] = append(rootNode.Val[1], childNode.Val[1]...)
   560  
   561  		if err := t.commitNode(childNode); err != nil {
   562  			return nil, err
   563  		}
   564  		return childNode.Hash, nil
   565  
   566  	} else if flag == leaf { //ext->leaf --> leaf
   567  
   568  		childNode.Val[1] = append(rootNode.Val[1], childNode.Val[1]...)
   569  		if err := t.commitNode(childNode); err != nil {
   570  			return nil, err
   571  		}
   572  		return childNode.Hash, nil
   573  	}
   574  	return nil, nil
   575  }
   576  
   577  // deleteWhenMeetSingleBranch
   578  func (t *Trie) deleteWhenMeetSingleBranch(rootNode *node) ([]byte, error) {
   579  	for idx := range rootNode.Val {
   580  		if len(rootNode.Val[idx]) != 0 {
   581  
   582  			childNode, err := t.fetchNode(rootNode.Val[idx])
   583  			if err != nil {
   584  				return nil, err
   585  			}
   586  			flag, err := childNode.Type()
   587  			switch flag {
   588  			case branch: //branch->branche --> ext-->branche
   589  				value := [][]byte{[]byte{byte(ext)}, []byte{byte(idx)}, rootNode.Val[idx]}
   590  				extNode, err := t.createNode(value)
   591  				if err != nil {
   592  					return nil, err
   593  				}
   594  				return extNode.Hash, nil
   595  			case ext: // branche->ext --> ext
   596  				childNode.Val[1] = append([]byte{byte(idx)}, childNode.Val[1]...)
   597  				if err := t.commitNode(childNode); err != nil {
   598  					return nil, err
   599  				}
   600  				return childNode.Hash, nil
   601  
   602  			case leaf: // branch->leaf-->leaf
   603  				childNode.Val[1] = append([]byte{byte(idx)}, childNode.Val[1]...)
   604  				if err := t.commitNode(childNode); err != nil {
   605  					return nil, err
   606  				}
   607  				return childNode.Hash, nil
   608  			default:
   609  				return nil, errors.New("unknown node type")
   610  			}
   611  		}
   612  
   613  	}
   614  	return nil, nil
   615  }
   616  
   617  // Clone the trie to create a new trie sharing the same storage
   618  func (t *Trie) Clone() (*Trie, error) {
   619  	return &Trie{rootHash: t.rootHash, storage: t.storage, needChangelog: t.needChangelog}, nil
   620  }
   621  
   622  // CopyTo copy the trie structure into the given storage
   623  func (t *Trie) CopyTo(storage storage.Storage, needChangelog bool) (*Trie, error) {
   624  	return &Trie{rootHash: t.rootHash, storage: storage, needChangelog: needChangelog}, nil
   625  }
   626  
   627  // Replay return roothash not save key to storage
   628  func (t *Trie) Replay(ft *Trie) ([]byte, error) {
   629  
   630  	needChangelog := t.needChangelog
   631  	t.needChangelog = false
   632  
   633  	var err error
   634  	var rootHash []byte
   635  
   636  	for _, entry := range ft.changelog {
   637  		switch entry.action {
   638  		case Delete:
   639  			rootHash, err = t.Del(entry.key)
   640  			break
   641  		case Update, Insert:
   642  			rootHash, err = t.Put(entry.key, entry.update)
   643  			break
   644  		default:
   645  			err = nil
   646  		}
   647  
   648  		if err != nil {
   649  			t.needChangelog = needChangelog
   650  			return nil, err
   651  		}
   652  	}
   653  	ft.changelog = make([]*Entry, 0)
   654  
   655  	t.needChangelog = needChangelog
   656  	return rootHash, nil
   657  }
   658  
   659  // prefixLen returns the length of the common prefix between a and b.
   660  func prefixLen(a, b []byte) int {
   661  	var i, length = 0, len(a)
   662  	if len(b) < length {
   663  		length = len(b)
   664  	}
   665  	for ; i < length; i++ {
   666  		if a[i] != b[i] {
   667  			break
   668  		}
   669  	}
   670  	return i
   671  }
   672  
   673  // keyToRoute returns hex bytes
   674  // e.g {0xa1, 0xf2} -> {0xa, 0x1, 0xf, 0x2}
   675  func keyToRoute(key []byte) []byte {
   676  	l := len(key) * 2
   677  	var route = make([]byte, l)
   678  	for i, b := range key {
   679  		route[i*2] = b / 16
   680  		route[i*2+1] = b % 16
   681  	}
   682  	return route
   683  }
   684  
   685  // routeToKey returns native bytes
   686  // e.g {0xa, 0x1, 0xf, 0x2} -> {0xa1, 0xf2}
   687  func routeToKey(route []byte) []byte {
   688  	l := len(route) / 2
   689  	var key = make([]byte, l)
   690  	for i := 0; i < l; i++ {
   691  		key[i] = route[i*2]<<4 + route[i*2+1]
   692  	}
   693  	return key
   694  }
   695  
   696  func emptyBranchNode() *node {
   697  	empty := &node{Val: [][]byte{nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil}}
   698  	pb, _ := empty.ToProto()
   699  	empty.Bytes, _ = proto.Marshal(pb)
   700  	empty.Hash = hash.Sha3256(empty.Bytes)
   701  	return empty
   702  }
   703  
   704  func isEmptyBranch(n *node) bool {
   705  	for idx := range n.Val {
   706  		if len(n.Val[idx]) != 0 {
   707  			return false
   708  		}
   709  	}
   710  	return true
   711  }
   712  func lenBranch(n *node) int {
   713  	l := 0
   714  	for idx := range n.Val {
   715  		if len(n.Val[idx]) != 0 {
   716  			l++
   717  		}
   718  	}
   719  	return l
   720  }