istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/ledger/smt_tools.go (about)

     1  // Copyright 2019 Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package ledger
    16  
    17  import (
    18  	"bytes"
    19  )
    20  
    21  // Get fetches the value of a key by going down the current trie root.
    22  func (s *smt) Get(key []byte) ([]byte, error) {
    23  	return s.GetPreviousValue(s.Root(), key)
    24  }
    25  
    26  // GetPreviousValue returns the value as of the specified root hash.
    27  func (s *smt) GetPreviousValue(prevRoot []byte, key []byte) ([]byte, error) {
    28  	s.lock.RLock()
    29  	defer s.lock.RUnlock()
    30  	s.atomicUpdate = false
    31  	return s.get(prevRoot, key, nil, 0, s.trieHeight)
    32  }
    33  
    34  // get fetches the value of a key given a trie root
    35  func (s *smt) get(root []byte, key []byte, batch [][]byte, iBatch, height int) ([]byte, error) {
    36  	if len(root) == 0 {
    37  		return nil, nil
    38  	}
    39  	if height == 0 {
    40  		return root[:hashLength], nil
    41  	}
    42  	// Fetch the children of the node
    43  	batch, iBatch, lnode, rnode, isShortcut, err := s.loadChildren(root, height, iBatch, batch)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	if isShortcut {
    48  		if bytes.Equal(lnode[:hashLength], key) {
    49  			return rnode[:hashLength], nil
    50  		}
    51  		return nil, nil
    52  	}
    53  	if bitIsSet(key, s.trieHeight-height) {
    54  		// visit right node
    55  		return s.get(rnode, key, batch, 2*iBatch+2, height-1)
    56  	}
    57  	// visit left node
    58  	return s.get(lnode, key, batch, 2*iBatch+1, height-1)
    59  }
    60  
    61  // DefaultHash is a getter for the defaultHashes array
    62  func (s *smt) DefaultHash(height int) []byte {
    63  	return s.defaultHashes[height]
    64  }