github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/core/ledger/kvledger/txmgmt/privacyenabledstate/optimization.go (about)

     1  /*
     2  Copyright hechain. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package privacyenabledstate
     8  
     9  import (
    10  	"github.com/hechain20/hechain/common/ledger/util/leveldbhelper"
    11  )
    12  
    13  type metadataHint struct {
    14  	cache      map[string]bool
    15  	bookkeeper *leveldbhelper.DBHandle
    16  }
    17  
    18  func newMetadataHint(bookkeeper *leveldbhelper.DBHandle) (*metadataHint, error) {
    19  	cache := map[string]bool{}
    20  	itr, err := bookkeeper.GetIterator(nil, nil)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	defer itr.Release()
    25  	for itr.Next() {
    26  		namespace := string(itr.Key())
    27  		cache[namespace] = true
    28  	}
    29  	return &metadataHint{cache, bookkeeper}, nil
    30  }
    31  
    32  func (h *metadataHint) metadataEverUsedFor(namespace string) bool {
    33  	return h.cache[namespace]
    34  }
    35  
    36  func (h *metadataHint) setMetadataUsedFlag(updates *UpdateBatch) error {
    37  	batch := h.bookkeeper.NewUpdateBatch()
    38  	for ns := range filterNamespacesThatHasMetadata(updates) {
    39  		if h.cache[ns] {
    40  			continue
    41  		}
    42  		h.cache[ns] = true
    43  		batch.Put([]byte(ns), []byte{})
    44  	}
    45  	return h.bookkeeper.WriteBatch(batch, true)
    46  }
    47  
    48  func (h *metadataHint) importNamespacesThatUseMetadata(namespaces map[string]struct{}) error {
    49  	batch := h.bookkeeper.NewUpdateBatch()
    50  	for ns := range namespaces {
    51  		batch.Put([]byte(ns), []byte{})
    52  	}
    53  	return h.bookkeeper.WriteBatch(batch, true)
    54  }
    55  
    56  func filterNamespacesThatHasMetadata(updates *UpdateBatch) map[string]bool {
    57  	namespaces := map[string]bool{}
    58  	pubUpdates, hashUpdates := updates.PubUpdates, updates.HashUpdates
    59  	// add ns for public data
    60  	for _, ns := range pubUpdates.GetUpdatedNamespaces() {
    61  		for _, vv := range updates.PubUpdates.GetUpdates(ns) {
    62  			if vv.Metadata == nil {
    63  				continue
    64  			}
    65  			namespaces[ns] = true
    66  		}
    67  	}
    68  	// add ns for private hashes
    69  	for ns, nsBatch := range hashUpdates.UpdateMap {
    70  		for _, coll := range nsBatch.GetCollectionNames() {
    71  			for _, vv := range nsBatch.GetUpdates(coll) {
    72  				if vv.Metadata == nil {
    73  					continue
    74  				}
    75  				namespaces[ns] = true
    76  			}
    77  		}
    78  	}
    79  	return namespaces
    80  }