Compare commits

..

7 Commits

Author SHA1 Message Date
Matus Kysel
af34894fc3 add logs 2024-08-22 11:34:23 +02:00
Matus Kysel
7dcd01e9be statistics on stale peers 2024-08-22 09:23:58 +02:00
easyfold
3adcfabb41 core/systemcontracts: use vm.StateDB in UpgradeBuildInSystemContract (#2578) 2024-08-13 17:06:07 +08:00
buddho
b1f0a3c79b core: fix cache for receipts (#2643) 2024-08-13 14:02:38 +08:00
buddho
e988d1574e consensus/parlia: support recovery when snapshot of parlia gone in disk (#2587) 2024-08-08 14:53:51 +08:00
zzzckck
2cce9dd3de release: prepare for release v1.4.13 (#2632) 2024-08-07 17:53:24 +08:00
zzzckck
b7e678e93d config: setup Testnet Bohr hardfork date (#2634)
expected Bohr hard fork date:
- Testnet: 2024-08-20 01:23:16 AM UTC
- Mainnet: it is not determined yet, target Later Sep 2024
2024-08-07 16:24:28 +08:00
15 changed files with 178 additions and 256 deletions

View File

@@ -1,4 +1,31 @@
# Changelog # Changelog
## v1.4.13
### BUGFIX
* [\#2602](https://github.com/bnb-chain/bsc/pull/2602) fix: prune-state when specify --triesInMemory 32
* [\#2579](https://github.com/bnb-chain/bsc/pull/00025790) fix: only take non-mempool tx to calculate bid price
### FEATURE
* [\#2634](https://github.com/bnb-chain/bsc/pull/2634) config: setup Testnet Bohr hardfork date
* [\#2482](https://github.com/bnb-chain/bsc/pull/2482) BEP-341: Validators can produce consecutive blocks
* [\#2502](https://github.com/bnb-chain/bsc/pull/2502) BEP-402: Complete Missing Fields in Block Header to Generate Signature
* [\#2558](https://github.com/bnb-chain/bsc/pull/2558) BEP-404: Clear Miner History when Switching Validators Set
* [\#2605](https://github.com/bnb-chain/bsc/pull/2605) feat: add bohr upgrade contracts bytecode
* [\#2614](https://github.com/bnb-chain/bsc/pull/2614) fix: update stakehub bytecode after zero address agent issue fixed
* [\#2608](https://github.com/bnb-chain/bsc/pull/2608) consensus/parlia: modify mining time for last block in one turn
* [\#2618](https://github.com/bnb-chain/bsc/pull/2618) consensus/parlia: exclude inturn validator when calculate backoffTime
* [\#2621](https://github.com/bnb-chain/bsc/pull/2621) core: not record zero hash beacon block root with Parlia engine
### IMPROVEMENT
* [\#2589](https://github.com/bnb-chain/bsc/pull/2589) core/vote: vote before committing state and writing block
* [\#2596](https://github.com/bnb-chain/bsc/pull/2596) core: improve the network stability when double sign happens
* [\#2600](https://github.com/bnb-chain/bsc/pull/2600) core: cache block after wroten into db
* [\#2629](https://github.com/bnb-chain/bsc/pull/2629) utils: add GetTopAddr to analyse large traffic
* [\#2591](https://github.com/bnb-chain/bsc/pull/2591) consensus/parlia: add GetJustifiedNumber and GetFinalizedNumber
* [\#2611](https://github.com/bnb-chain/bsc/pull/2611) cmd/utils: add new flag OverridePassedForkTime
* [\#2603](https://github.com/bnb-chain/bsc/pull/2603) faucet: rate limit initial implementation
* [\#2622](https://github.com/bnb-chain/bsc/pull/2622) tests: fix evm-test CI
* [\#2628](https://github.com/bnb-chain/bsc/pull/2628) Makefile: use docker compose v2 instead of v1
## v1.4.12 ## v1.4.12
@@ -35,7 +62,6 @@
* [\#2534](https://github.com/bnb-chain/bsc/pull/2534) fix: nil pointer when clear simulating bid * [\#2534](https://github.com/bnb-chain/bsc/pull/2534) fix: nil pointer when clear simulating bid
* [\#2535](https://github.com/bnb-chain/bsc/pull/2535) upgrade: add HaberFix hardfork * [\#2535](https://github.com/bnb-chain/bsc/pull/2535) upgrade: add HaberFix hardfork
## v1.4.10 ## v1.4.10
### FEATURE ### FEATURE
NA NA

View File

@@ -54,7 +54,7 @@ const (
inMemoryHeaders = 86400 // Number of recent headers to keep in memory for double sign detection, inMemoryHeaders = 86400 // Number of recent headers to keep in memory for double sign detection,
checkpointInterval = 1024 // Number of blocks after which to save the snapshot to the database checkpointInterval = 1024 // Number of blocks after which to save the snapshot to the database
defaultEpochLength = uint64(100) // Default number of blocks of checkpoint to update validatorSet from contract defaultEpochLength = uint64(200) // Default number of blocks of checkpoint to update validatorSet from contract
defaultTurnLength = uint8(1) // Default consecutive number of blocks a validator receives priority for block production defaultTurnLength = uint8(1) // Default consecutive number of blocks a validator receives priority for block production
extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity extraVanity = 32 // Fixed number of extra-data prefix bytes reserved for signer vanity
@@ -739,13 +739,28 @@ func (p *Parlia) snapshot(chain consensus.ChainHeaderReader, number uint64, hash
} }
} }
// If we're at the genesis, snapshot the initial state. // If we're at the genesis, snapshot the initial state. Alternatively if we have
// piled up more headers than allowed to be reorged (chain reinit from a freezer),
// consider the checkpoint trusted and snapshot it.
// An offset `p.config.Epoch - 1` can ensure getting the right validators.
if number == 0 || ((number+1)%p.config.Epoch == 0 && (len(headers) > int(params.FullImmutabilityThreshold))) {
var (
checkpoint *types.Header
blockHash common.Hash
)
if number == 0 { if number == 0 {
checkpoint := chain.GetHeaderByNumber(number) checkpoint = chain.GetHeaderByNumber(0)
if checkpoint != nil { if checkpoint != nil {
// get checkpoint data blockHash = checkpoint.Hash()
hash := checkpoint.Hash() }
} else {
checkpoint = chain.GetHeaderByNumber(number + 1 - p.config.Epoch)
blockHeader := chain.GetHeaderByNumber(number)
if blockHeader != nil {
blockHash = blockHeader.Hash()
}
}
if checkpoint != nil && blockHash != (common.Hash{}) {
// get validators from headers // get validators from headers
validators, voteAddrs, err := parseValidators(checkpoint, p.chainConfig, p.config) validators, voteAddrs, err := parseValidators(checkpoint, p.chainConfig, p.config)
if err != nil { if err != nil {
@@ -753,11 +768,27 @@ func (p *Parlia) snapshot(chain consensus.ChainHeaderReader, number uint64, hash
} }
// new snapshot // new snapshot
snap = newSnapshot(p.config, p.signatures, number, hash, validators, voteAddrs, p.ethAPI) snap = newSnapshot(p.config, p.signatures, number, blockHash, validators, voteAddrs, p.ethAPI)
// get turnLength from headers and use that for new turnLength
turnLength, err := parseTurnLength(checkpoint, p.chainConfig, p.config)
if err != nil {
return nil, err
}
if turnLength != nil {
snap.TurnLength = *turnLength
}
// snap.Recents is currently empty, which affects the following:
// a. The function SignRecently - This is acceptable since an empty snap.Recents results in a more lenient check.
// b. The function blockTimeVerifyForRamanujanFork - This is also acceptable as it won't be invoked during `snap.apply`.
// c. This may cause a mismatch in the slash systemtx, but the transaction list is not verified during `snap.apply`.
// snap.Attestation is nil, but Snapshot.updateAttestation will handle it correctly.
if err := snap.store(p.db); err != nil { if err := snap.store(p.db); err != nil {
return nil, err return nil, err
} }
log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", hash) log.Info("Stored checkpoint snapshot to disk", "number", number, "hash", blockHash)
break break
} }
} }

View File

@@ -20,7 +20,6 @@ package core
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/triedb/versadb"
"io" "io"
"math/big" "math/big"
"runtime" "runtime"
@@ -197,11 +196,6 @@ func (c *CacheConfig) triedbConfig() *triedb.Config {
JournalFile: c.JournalFile, JournalFile: c.JournalFile,
} }
} }
if c.StateScheme == rawdb.VersaScheme {
config.VersaDB = &versadb.Config{
CleanCacheSize: c.TrieCleanLimit * 1024 * 1024,
}
}
return config return config
} }
@@ -1809,7 +1803,7 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types.
} }
bc.hc.tdCache.Add(block.Hash(), externTd) bc.hc.tdCache.Add(block.Hash(), externTd)
bc.blockCache.Add(block.Hash(), block) bc.blockCache.Add(block.Hash(), block)
bc.receiptsCache.Add(block.Hash(), receipts) bc.cacheReceipts(block.Hash(), receipts, block)
if bc.chainConfig.IsCancun(block.Number(), block.Time()) { if bc.chainConfig.IsCancun(block.Number(), block.Time()) {
bc.sidecarsCache.Add(block.Hash(), block.Sidecars()) bc.sidecarsCache.Add(block.Hash(), block.Sidecars())
} }
@@ -2326,8 +2320,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks, setHead bool) (int, error)
return it.index, err return it.index, err
} }
bc.cacheReceipts(block.Hash(), receipts, block)
// Update the metrics touched during block commit // Update the metrics touched during block commit
accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them accountCommitTimer.Update(statedb.AccountCommits) // Account commits are complete, we can mark them
storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them storageCommitTimer.Update(statedb.StorageCommits) // Storage commits are complete, we can mark them

View File

@@ -46,8 +46,6 @@ const HashScheme = "hash"
// on extra state diffs to survive deep reorg. // on extra state diffs to survive deep reorg.
const PathScheme = "path" const PathScheme = "path"
const VersaScheme = "versa"
// hasher is used to compute the sha256 hash of the provided data. // hasher is used to compute the sha256 hash of the provided data.
type hasher struct{ sha crypto.KeccakState } type hasher struct{ sha crypto.KeccakState }

View File

@@ -195,10 +195,6 @@ func (db *cachingDB) OpenTrie(root common.Hash) (Trie, error) {
if db.triedb.IsVerkle() { if db.triedb.IsVerkle() {
return trie.NewVerkleTrie(root, db.triedb, utils.NewPointCache(commitmentCacheItems)) return trie.NewVerkleTrie(root, db.triedb, utils.NewPointCache(commitmentCacheItems))
} }
// TODO, trie handler instead of tree pointer
if db.triedb.IsVersionedState() {
return trie.NewVersionTrie(root, db.triedb)
}
tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.triedb) tr, err := trie.NewStateTrie(trie.StateTrieID(root), db.triedb)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -218,10 +214,6 @@ func (db *cachingDB) OpenStorageTrie(stateRoot common.Hash, address common.Addre
if db.triedb.IsVerkle() { if db.triedb.IsVerkle() {
return self, nil return self, nil
} }
// TODO
if db.triedb.IsVersionedState() {
return trie.NewVersionTrie(root, db.triedb)
}
tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, crypto.Keccak256Hash(address.Bytes()), root), db.triedb) tr, err := trie.NewStateTrie(trie.StorageTrieID(stateRoot, crypto.Keccak256Hash(address.Bytes()), root), db.triedb)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@@ -4,10 +4,10 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"math/big" "math/big"
"reflect"
"strings" "strings"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/systemcontracts/bohr" "github.com/ethereum/go-ethereum/core/systemcontracts/bohr"
"github.com/ethereum/go-ethereum/core/systemcontracts/bruno" "github.com/ethereum/go-ethereum/core/systemcontracts/bruno"
"github.com/ethereum/go-ethereum/core/systemcontracts/euler" "github.com/ethereum/go-ethereum/core/systemcontracts/euler"
@@ -23,6 +23,7 @@ import (
"github.com/ethereum/go-ethereum/core/systemcontracts/planck" "github.com/ethereum/go-ethereum/core/systemcontracts/planck"
"github.com/ethereum/go-ethereum/core/systemcontracts/plato" "github.com/ethereum/go-ethereum/core/systemcontracts/plato"
"github.com/ethereum/go-ethereum/core/systemcontracts/ramanujan" "github.com/ethereum/go-ethereum/core/systemcontracts/ramanujan"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
) )
@@ -40,7 +41,7 @@ type Upgrade struct {
Configs []*UpgradeConfig Configs []*UpgradeConfig
} }
type upgradeHook func(blockNumber *big.Int, contractAddr common.Address, statedb *state.StateDB) error type upgradeHook func(blockNumber *big.Int, contractAddr common.Address, statedb vm.StateDB) error
const ( const (
mainNet = "Mainnet" mainNet = "Mainnet"
@@ -789,10 +790,11 @@ func init() {
} }
} }
func UpgradeBuildInSystemContract(config *params.ChainConfig, blockNumber *big.Int, lastBlockTime uint64, blockTime uint64, statedb *state.StateDB) { func UpgradeBuildInSystemContract(config *params.ChainConfig, blockNumber *big.Int, lastBlockTime uint64, blockTime uint64, statedb vm.StateDB) {
if config == nil || blockNumber == nil || statedb == nil { if config == nil || blockNumber == nil || statedb == nil || reflect.ValueOf(statedb).IsNil() {
return return
} }
var network string var network string
switch GenesisHash { switch GenesisHash {
/* Add mainnet genesis hash */ /* Add mainnet genesis hash */
@@ -876,7 +878,7 @@ func UpgradeBuildInSystemContract(config *params.ChainConfig, blockNumber *big.I
*/ */
} }
func applySystemContractUpgrade(upgrade *Upgrade, blockNumber *big.Int, statedb *state.StateDB, logger log.Logger) { func applySystemContractUpgrade(upgrade *Upgrade, blockNumber *big.Int, statedb vm.StateDB, logger log.Logger) {
if upgrade == nil { if upgrade == nil {
logger.Info("Empty upgrade config", "height", blockNumber.String()) logger.Info("Empty upgrade config", "height", blockNumber.String())
return return

View File

@@ -2,9 +2,13 @@ package systemcontracts
import ( import (
"crypto/sha256" "crypto/sha256"
"math/big"
"testing" "testing"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/params"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@@ -39,3 +43,31 @@ func TestAllCodesHash(t *testing.T) {
allCodeHash := sha256.Sum256(allCodes) allCodeHash := sha256.Sum256(allCodes)
require.Equal(t, allCodeHash[:], common.Hex2Bytes("833cc0fc87c46ad8a223e44ccfdc16a51a7e7383525136441bd0c730f06023df")) require.Equal(t, allCodeHash[:], common.Hex2Bytes("833cc0fc87c46ad8a223e44ccfdc16a51a7e7383525136441bd0c730f06023df"))
} }
func TestUpgradeBuildInSystemContractNilInterface(t *testing.T) {
var (
config = params.BSCChainConfig
blockNumber = big.NewInt(37959559)
lastBlockTime uint64 = 1713419337
blockTime uint64 = 1713419340
statedb vm.StateDB
)
GenesisHash = params.BSCGenesisHash
UpgradeBuildInSystemContract(config, blockNumber, lastBlockTime, blockTime, statedb)
}
func TestUpgradeBuildInSystemContractNilValue(t *testing.T) {
var (
config = params.BSCChainConfig
blockNumber = big.NewInt(37959559)
lastBlockTime uint64 = 1713419337
blockTime uint64 = 1713419340
statedb vm.StateDB = (*state.StateDB)(nil)
)
GenesisHash = params.BSCGenesisHash
UpgradeBuildInSystemContract(config, blockNumber, lastBlockTime, blockTime, statedb)
}

View File

@@ -369,6 +369,7 @@ func newHandler(config *handlerConfig) (*handler, error) {
} }
h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, addTxs, fetchTx, h.removePeer) h.txFetcher = fetcher.NewTxFetcher(h.txpool.Has, addTxs, fetchTx, h.removePeer)
h.chainSync = newChainSyncer(h) h.chainSync = newChainSyncer(h)
h.printPeerStatus()
return h, nil return h, nil
} }
@@ -1017,3 +1018,67 @@ func (h *handler) enableSyncedFeatures() {
// h.chain.TrieDB().SetBufferSize(pathdb.DefaultBufferSize) // h.chain.TrieDB().SetBufferSize(pathdb.DefaultBufferSize)
// } // }
} }
type PeerDummy struct {
ID string
Head common.Hash
TD *big.Int
TimeStamp time.Time
}
func (h *handler) printPeerStatus() {
go func() {
statusMap := make(map[string]PeerDummy)
for {
// run in timer very 1 minue of time
time.Sleep(1 * time.Minute)
// Create a set to track current peers
currentPeers := make(map[string]struct{})
// print peer status
h.peers.lock.RLock()
for _, peer := range h.peers.peers {
currentPeers[peer.Peer.ID()] = struct{}{}
head, td := peer.Peer.Head()
if p, ok := statusMap[peer.Peer.ID()]; ok {
if p.Head == head && p.TD.Cmp(td) == 0 {
continue
}
p.Head = head
p.TD = td
p.TimeStamp = time.Now()
statusMap[peer.Peer.ID()] = p
} else {
statusMap[peer.Peer.ID()] = PeerDummy{
ID: peer.Peer.ID(),
Head: head,
TD: td,
TimeStamp: time.Now(),
}
}
}
h.peers.lock.RUnlock()
// Remove peers from statusMap that are no longer in h.peers.peers
for id := range statusMap {
if _, exists := currentPeers[id]; !exists {
delete(statusMap, id)
}
}
var count int
for _, peer := range statusMap {
if peer.TimeStamp.Before(time.Now().Add(-60 * time.Minute)) {
count++
if count == 1 {
log.Warn("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
}
log.Warn("peer", peer.ID, "head", peer.Head, "TD", peer.TD, "TimeStamp", peer.TimeStamp)
}
}
if count > 0 {
log.Warn("Total peers: ", len(statusMap), "inactive peers: ", count)
log.Warn("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
}
}
}()
}

1
go.sum
View File

@@ -326,7 +326,6 @@ github.com/ethereum/c-kzg-4844 v0.4.0 h1:3MS1s4JtA868KpJxroZoepdV0ZKBp3u/O5HcZ7R
github.com/ethereum/c-kzg-4844 v0.4.0/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0= github.com/ethereum/c-kzg-4844 v0.4.0/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0=
github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=

View File

@@ -195,7 +195,7 @@ var (
CancunTime: newUint64(1713330442), // 2024-04-17 05:07:22 AM UTC CancunTime: newUint64(1713330442), // 2024-04-17 05:07:22 AM UTC
HaberTime: newUint64(1716962820), // 2024-05-29 06:07:00 AM UTC HaberTime: newUint64(1716962820), // 2024-05-29 06:07:00 AM UTC
HaberFixTime: newUint64(1719986788), // 2024-07-03 06:06:28 AM UTC HaberFixTime: newUint64(1719986788), // 2024-07-03 06:06:28 AM UTC
BohrTime: nil, BohrTime: newUint64(1724116996), // 2024-08-20 01:23:16 AM UTC
Parlia: &ParliaConfig{ Parlia: &ParliaConfig{
Period: 3, Period: 3,

View File

@@ -23,7 +23,7 @@ import (
const ( const (
VersionMajor = 1 // Major version component of the current release VersionMajor = 1 // Major version component of the current release
VersionMinor = 4 // Minor version component of the current release VersionMinor = 4 // Minor version component of the current release
VersionPatch = 12 // Patch version component of the current release VersionPatch = 13 // Patch version component of the current release
VersionMeta = "" // Version metadata to append to the version string VersionMeta = "" // Version metadata to append to the version string
) )

View File

@@ -23,7 +23,6 @@ type ID struct {
StateRoot common.Hash // The root of the corresponding state(block.root) StateRoot common.Hash // The root of the corresponding state(block.root)
Owner common.Hash // The contract address hash which the trie belongs to Owner common.Hash // The contract address hash which the trie belongs to
Root common.Hash // The root hash of trie Root common.Hash // The root hash of trie
Version uint64 // The version of a Versa tree
} }
// StateTrieID constructs an identifier for state trie with the provided state root. // StateTrieID constructs an identifier for state trie with the provided state root.

View File

@@ -1,119 +0,0 @@
package trie
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/triedb/database"
)
// VersionTrie is a wrapper around version state that implements the trie.Trie
// interface so that version trees can be reused verbatim.
type VersionTrie struct {
db database.Database
reader *trieReader
//tree TreeHandler
}
// NewVersionTrie constructs a version state tree based on the specified root hash.
func NewVersionTrie(root common.Hash, db database.Database) (*VersionTrie, error) {
reader, err := newTrieReader(root, common.Hash{}, db)
if err != nil {
return nil, err
}
// TODO
// Open a tree
// tree, err := OpenTree(state StateHandler, version int64, owner common.Hash, root common.Hash)
if err != nil {
return nil, err
}
return &VersionTrie{
db: db,
reader: reader,
// tree: tree,
}, nil
}
// GetKey returns the sha3 preimage of a hashed key that was previously used
// to store a value.
func (t *VersionTrie) GetKey(key []byte) []byte {
return key
}
// GetAccount implements state.Trie, retrieving the account with the specified
// account address. If the specified account is not in the tree, nil will
// be returned. If the tree is corrupted, an error will be returned.
func (t *VersionTrie) GetAccount(address common.Address) (*types.StateAccount, error) {
// TODO
}
// GetStorage returns the value for key stored in the trie. The value bytes
// must not be modified by the caller. If a node was not found in the database,
// a trie.MissingNodeError is returned.
func (t *VersionTrie) GetStorage(addr common.Address, key []byte) ([]byte, error) {
// TODO
}
// UpdateAccount abstracts an account write to the trie. It encodes the
// provided account object with associated algorithm and then updates it
// in the trie with provided address.
func (t *VersionTrie) UpdateAccount(address common.Address, account *types.StateAccount) error {
// TODO
}
// UpdateStorage associates key with value in the trie. If value has length zero,
// any existing value is deleted from the trie. The value bytes must not be modified
// by the caller while they are stored in the trie. If a node was not found in the
// database, a trie.MissingNodeError is returned.
func (t *VersionTrie) UpdateStorage(addr common.Address, key, value []byte) error {
// TODO
}
// DeleteAccount abstracts an account deletion from the trie.
func (t *VersionTrie) DeleteAccount(address common.Address) error {
// TODO
}
// DeleteStorage removes any existing value for key from the trie. If a node
// was not found in the database, a trie.MissingNodeError is returned.
func (t *VersionTrie) DeleteStorage(addr common.Address, key []byte) error {
// TODO
}
// UpdateContractCode abstracts code write to the trie. It is expected
// to be moved to the stateWriter interface when the latter is ready.
func (t *VersionTrie) UpdateContractCode(address common.Address, codeHash common.Hash, code []byte) error {
// TODO
}
// Hash returns the root hash of the trie. It does not write to the database and
// can be used even if the trie doesn't have one.
func (t *VersionTrie) Hash() common.Hash {
// TODO
}
// Commit collects all dirty nodes in the trie and replace them with the
// corresponding node hash.
func (t *VersionTrie) Commit(collectLeaf bool) (common.Hash, error) {
// TODO
}
// NodeIterator returns an iterator that returns nodes of the trie. Iteration
// starts at the key after the given start key. And error will be returned
// if fails to create node iterator.
func (t *VersionTrie) NodeIterator(startKey []byte) (trie.NodeIterator, error) {
// TODO
}
// Prove constructs a Merkle proof for key. The result contains all encoded nodes
// on the path to the value at key. The value itself is also included in the last
// node and can be retrieved by verifying the proof.
//
// If the trie does not contain a value for key, the returned proof contains all
// nodes of the longest existing prefix of the key (at least the root), ending
// with the node that proves the absence of the key.
func (t *VersionTrie) Prove(key []byte, proofDb ethdb.KeyValueWriter) error {
// TODO
}

View File

@@ -18,7 +18,6 @@ package triedb
import ( import (
"errors" "errors"
"github.com/ethereum/go-ethereum/triedb/versadb"
"strings" "strings"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
@@ -39,10 +38,8 @@ type Config struct {
Cache int Cache int
NoTries bool NoTries bool
IsVerkle bool // Flag whether the db is holding a verkle tree IsVerkle bool // Flag whether the db is holding a verkle tree
IsVersa bool
HashDB *hashdb.Config // Configs for hash-based scheme HashDB *hashdb.Config // Configs for hash-based scheme
PathDB *pathdb.Config // Configs for experimental path-based scheme PathDB *pathdb.Config // Configs for experimental path-based scheme
VersaDB *versadb.Config // TODO, Richard
} }
// HashDefaults represents a config for using hash-based scheme with // HashDefaults represents a config for using hash-based scheme with
@@ -151,11 +148,6 @@ func NewDatabase(diskdb ethdb.Database, config *Config) *Database {
config.PathDB = pathdb.Defaults config.PathDB = pathdb.Defaults
} }
db.backend = pathdb.New(triediskdb, config.PathDB) db.backend = pathdb.New(triediskdb, config.PathDB)
} else if strings.Compare(dbScheme, rawdb.VersaScheme) == 0 {
if config.VersaDB == nil {
config.VersaDB = versadb.Defaults
}
db.backend = versadb.New(triediskdb, config.VersaDB)
} else { } else {
var resolver hashdb.ChildResolver var resolver hashdb.ChildResolver
if config.IsVerkle { if config.IsVerkle {
@@ -417,8 +409,3 @@ func (db *Database) GetAllRooHash() [][]string {
func (db *Database) IsVerkle() bool { func (db *Database) IsVerkle() bool {
return db.config.IsVerkle return db.config.IsVerkle
} }
// IsVersionedState returns the indicator if the database is holding a versioned state.
func (db *Database) IsVersionedState() bool {
return db.config.IsVersa
}

View File

@@ -1,82 +0,0 @@
package versadb
import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/trie/trienode"
"github.com/ethereum/go-ethereum/trie/triestate"
"sync"
)
const (
// maxDiffLayers is the maximum diff layers allowed in the layer tree.
maxDiffLayers = 128
)
// Config contains the settings for database.
type Config struct {
CleanCacheSize int // Maximum memory allowance (in bytes) for caching clean nodes
}
// Defaults is the default setting for database if it's not specified. ,
var Defaults = &Config{
CleanCacheSize: 0,
}
type Database struct {
// readOnly is the flag whether the mutation is allowed to be applied.
// It will be set automatically when the database is journaled during
// the shutdown to reject all following unexpected mutations.
readOnly bool // Flag if database is opened in read only mode
config *Config // Configuration for database
lock sync.RWMutex // Lock to prevent mutations from happening at the same time
}
// New initializes the version state database.
func New(diskdb ethdb.Database, config *Config) *Database {
if config == nil {
config = Defaults
}
// TODO
db := VersaDB.NewVersaDB(nil)
return db
}
// Scheme returns the identifier of used storage scheme.
func (db *Database) Scheme() string {
return rawdb.VersaScheme
}
// Initialized returns an indicator if the state data is already initialized
// according to the state scheme.
func (db *Database) Initialized(genesisRoot common.Hash) bool {
// TODO
}
// Size returns the current storage size of the memory cache in front of the
// persistent database layer.
func (db *Database) Size() (common.StorageSize, common.StorageSize, common.StorageSize) {
// TODO
}
// Update performs a state transition by committing dirty nodes contained
// in the given set in order to update state from the specified parent to
// the specified root.
//
// The passed in maps(nodes, states) will be retained to avoid copying
// everything. Therefore, these maps must not be changed afterwards.
func (db *Database) Update(root common.Hash, parent common.Hash, block uint64, nodes *trienode.MergedNodeSet, states *triestate.Set) error {
// TODO
}
// Commit writes all relevant trie nodes belonging to the specified state
// to disk. Report specifies whether logs will be displayed in info level.
func (db *Database) Commit(root common.Hash, report bool) error {
// TODO
}
// Close closes the trie database backend and releases all held resources.
func (db *Database) Close() error {
// TODO
}