github.com/ledgerwatch/erigon-lib@v1.0.0/kv/temporal/historyv2/account_changeset.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  	"encoding/binary"
    22  	"fmt"
    23  	"sort"
    24  
    25  	"github.com/ledgerwatch/erigon-lib/common/hexutility"
    26  	"github.com/ledgerwatch/erigon-lib/common/length"
    27  	"github.com/ledgerwatch/erigon-lib/kv"
    28  )
    29  
    30  type Encoder func(blockN uint64, s *ChangeSet, f func(k, v []byte) error) error
    31  type Decoder func(dbKey, dbValue []byte) (blockN uint64, k, v []byte, err error)
    32  
    33  func NewAccountChangeSet() *ChangeSet {
    34  	return &ChangeSet{
    35  		Changes: make([]Change, 0),
    36  		keyLen:  length.Addr,
    37  	}
    38  }
    39  
    40  func EncodeAccounts(blockN uint64, s *ChangeSet, f func(k, v []byte) error) error {
    41  	sort.Sort(s)
    42  	newK := hexutility.EncodeTs(blockN)
    43  	for _, cs := range s.Changes {
    44  		newV := make([]byte, len(cs.Key)+len(cs.Value))
    45  		copy(newV, cs.Key)
    46  		copy(newV[len(cs.Key):], cs.Value)
    47  		if err := f(newK, newV); err != nil {
    48  			return err
    49  		}
    50  	}
    51  	return nil
    52  }
    53  
    54  func DecodeAccounts(dbKey, dbValue []byte) (uint64, []byte, []byte, error) {
    55  	blockN := binary.BigEndian.Uint64(dbKey)
    56  	if len(dbValue) < length.Addr {
    57  		return 0, nil, nil, fmt.Errorf("account changes purged for block %d", blockN)
    58  	}
    59  	k := dbValue[:length.Addr]
    60  	v := dbValue[length.Addr:]
    61  	return blockN, k, v, nil
    62  }
    63  
    64  func FindAccount(c kv.CursorDupSort, blockNumber uint64, key []byte) ([]byte, error) {
    65  	k := hexutility.EncodeTs(blockNumber)
    66  	v, err := c.SeekBothRange(k, key)
    67  	if err != nil {
    68  		return nil, err
    69  	}
    70  	_, k, v, err = DecodeAccounts(k, v)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  	if !bytes.HasPrefix(k, key) {
    75  		return nil, nil
    76  	}
    77  	return v, nil
    78  }