github.com/ledgerwatch/erigon-lib@v1.0.0/kv/temporal/historyv2/find_by_history.go (about)

     1  /*
     2     Copyright 2022 Erigon contributors
     3  
     4     Licensed under the Apache License, Version 2.0 (the "License");
     5     you may not use this file except in compliance with the License.
     6     You may obtain a copy of the License at
     7  
     8         http://www.apache.org/licenses/LICENSE-2.0
     9  
    10     Unless required by applicable law or agreed to in writing, software
    11     distributed under the License is distributed on an "AS IS" BASIS,
    12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13     See the License for the specific language governing permissions and
    14     limitations under the License.
    15  */
    16  
    17  package historyv2
    18  
    19  import (
    20  	"bytes"
    21  	"errors"
    22  	"fmt"
    23  
    24  	"github.com/RoaringBitmap/roaring/roaring64"
    25  	"github.com/ledgerwatch/erigon-lib/common/length"
    26  	"github.com/ledgerwatch/erigon-lib/kv"
    27  	"github.com/ledgerwatch/erigon-lib/kv/bitmapdb"
    28  )
    29  
    30  func FindByHistory(indexC kv.Cursor, changesC kv.CursorDupSort, storage bool, key []byte, timestamp uint64) ([]byte, bool, error) {
    31  	var csBucket string
    32  	if storage {
    33  		csBucket = kv.StorageChangeSet
    34  	} else {
    35  		csBucket = kv.AccountChangeSet
    36  	}
    37  
    38  	k, v, seekErr := indexC.Seek(Mapper[csBucket].IndexChunkKey(key, timestamp))
    39  	if seekErr != nil {
    40  		return nil, false, seekErr
    41  	}
    42  
    43  	if k == nil {
    44  		return nil, false, nil
    45  	}
    46  	if storage {
    47  		if !bytes.Equal(k[:length.Addr], key[:length.Addr]) ||
    48  			!bytes.Equal(k[length.Addr:length.Addr+length.Hash], key[length.Addr+length.Incarnation:]) {
    49  			return nil, false, nil
    50  		}
    51  	} else {
    52  		if !bytes.HasPrefix(k, key) {
    53  			return nil, false, nil
    54  		}
    55  	}
    56  	index := roaring64.New()
    57  	if _, err := index.ReadFrom(bytes.NewReader(v)); err != nil {
    58  		return nil, false, err
    59  	}
    60  	found, ok := bitmapdb.SeekInBitmap64(index, timestamp)
    61  	changeSetBlock := found
    62  
    63  	var data []byte
    64  	var err error
    65  	if ok {
    66  		data, err = Mapper[csBucket].Find(changesC, changeSetBlock, key)
    67  		if err != nil {
    68  			if !errors.Is(err, ErrNotFound) {
    69  				return nil, false, fmt.Errorf("finding %x in the changeset %d: %w", key, changeSetBlock, err)
    70  			}
    71  			return nil, false, nil
    72  		}
    73  	} else {
    74  		return nil, false, nil
    75  	}
    76  
    77  	return data, true, nil
    78  }