Skip to content

Commit

Permalink
Merge pull request #2825 from bnb-chain/develop
Browse files Browse the repository at this point in the history
some bug fix before release 1.5.2-alpha
  • Loading branch information
brilliant-lx authored Dec 25, 2024
2 parents a9f53ca + 9b0130f commit 3a6ef6a
Show file tree
Hide file tree
Showing 15 changed files with 144 additions and 102 deletions.
3 changes: 0 additions & 3 deletions cmd/geth/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,6 @@ func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
params.FixedTurnLength = ctx.Uint64(utils.OverrideFixedTurnLength.Name)
}

// Start metrics export if enabled
utils.SetupMetrics(&cfg.Metrics)

backend, eth := utils.RegisterEthService(stack, &cfg.Eth)

// Create gauge with geth system and build information
Expand Down
25 changes: 22 additions & 3 deletions cmd/jsutils/getchainstatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ const addrSlash = '0x0000000000000000000000000000000000001001';
const addrStakeHub = '0x0000000000000000000000000000000000002002';

const validatorSetAbi = [
"function validatorExtraSet(uint256 offset) external view returns (uint256, bool, bytes)",
"function getLivingValidators() external view returns (address[], bytes[])",
"function numOfCabinets() external view returns (uint256)",
"function maxNumOfCandidates() external view returns (uint256)",
Expand Down Expand Up @@ -277,6 +278,11 @@ async function getSlashCount() {
if (blockNum === 0) {
blockNum = await provider.getBlockNumber()
}
let slashScale = await validatorSet.maintainSlashScale({blockTag:blockNum})
let maxElected = await stakeHub.maxElectedValidators({blockTag:blockNum})
const maintainThreshold = BigInt(50) // governable, hardcode to avoid one RPC call
const felonyThreshold = BigInt(150) // governable, hardcode to avoid one RPC call

let block = await provider.getBlock(blockNum)
console.log("At block", blockNum, "time", block.date)
const data = await validatorSet.getLivingValidators({blockTag:blockNum})
Expand All @@ -285,9 +291,22 @@ async function getSlashCount() {
let addr = data[0][i];
var moniker = await getValidatorMoniker(addr, blockNum)
let info = await slashIndicator.getSlashIndicator(addr, {blockTag:blockNum})
let count = ethers.toNumber(info[1])
totalSlash += count
console.log("Slash:", count, addr, moniker)
let slashHeight = ethers.toNumber(info[0])
let slashCount = ethers.toNumber(info[1])
totalSlash += slashCount
console.log("Slash:", slashCount, addr, moniker, slashHeight)
if (slashCount >= maintainThreshold) {
let validatorExtra = await validatorSet.validatorExtraSet(i, {blockTag:blockNum})
let enterMaintenanceHeight = validatorExtra[0]
let isMaintaining = validatorExtra[1]
// let voteAddress = validatorExtra[2]
if (isMaintaining) {
let jailHeight = (felonyThreshold - slashCount) * slashScale * maxElected + BigInt(enterMaintenanceHeight)
console.log(" in maintenance mode since", enterMaintenanceHeight, "will jail after", ethers.toNumber(jailHeight))
} else {
console.log(" exited maintenance mode")
}
}
}
console.log("Total slash count", totalSlash)
};
Expand Down
8 changes: 4 additions & 4 deletions cmd/utils/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -2332,7 +2332,7 @@ type SetupMetricsOption func()
func EnableBuildInfo(gitCommit, gitDate string) SetupMetricsOption {
return func() {
// register build info into metrics
metrics.NewRegisteredLabel("build-info", nil).Mark(map[string]interface{}{
metrics.GetOrRegisterLabel("build-info", nil).Mark(map[string]interface{}{
"version": version.WithMeta,
"git-commit": gitCommit,
"git-commit-date": gitDate,
Expand All @@ -2349,7 +2349,7 @@ func EnableMinerInfo(ctx *cli.Context, minerConfig *minerconfig.Config) SetupMet
// register miner info into metrics
minerInfo := structs.Map(minerConfig)
minerInfo[UnlockedAccountFlag.Name] = ctx.String(UnlockedAccountFlag.Name)
metrics.NewRegisteredLabel("miner-info", nil).Mark(minerInfo)
metrics.GetOrRegisterLabel("miner-info", nil).Mark(minerInfo)
}
}
}
Expand All @@ -2369,7 +2369,7 @@ func RegisterFilterAPI(stack *node.Node, backend ethapi.Backend, ethcfg *ethconf
func EnableNodeInfo(poolConfig *legacypool.Config, nodeInfo *p2p.NodeInfo) SetupMetricsOption {
return func() {
// register node info into metrics
metrics.NewRegisteredLabel("node-info", nil).Mark(map[string]interface{}{
metrics.GetOrRegisterLabel("node-info", nil).Mark(map[string]interface{}{
"Enode": nodeInfo.Enode,
"ENR": nodeInfo.ENR,
"ID": nodeInfo.ID,
Expand All @@ -2389,7 +2389,7 @@ func EnableNodeTrack(ctx *cli.Context, cfg *ethconfig.Config, stack *node.Node)
nodeInfo := stack.Server().NodeInfo()
return func() {
// register node info into metrics
metrics.NewRegisteredLabel("node-stats", nil).Mark(map[string]interface{}{
metrics.GetOrRegisterLabel("node-stats", nil).Mark(map[string]interface{}{
"NodeType": parseNodeType(),
"ENR": nodeInfo.ENR,
"Mining": ctx.Bool(MiningEnabledFlag.Name),
Expand Down
2 changes: 1 addition & 1 deletion consensus/parlia/parlia.go
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@ func (p *Parlia) verifyHeader(chain consensus.ChainHeaderReader, header *types.H
prague := chain.Config().IsPrague(header.Number, header.Time)
if !prague {
if header.RequestsHash != nil {
return fmt.Errorf("invalid RequestsHash, have %#x, expected nil", header.ParentBeaconRoot)
return fmt.Errorf("invalid RequestsHash, have %#x, expected nil", header.RequestsHash)
}
} else {
if header.RequestsHash == nil {
Expand Down
2 changes: 2 additions & 0 deletions core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -434,12 +434,14 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis
var diskRoot common.Hash
if bc.cacheConfig.SnapshotLimit > 0 {
diskRoot = rawdb.ReadSnapshotRoot(bc.db)
log.Debug("Head state missing, ReadSnapshotRoot", "snap root", diskRoot)
}
if bc.triedb.Scheme() == rawdb.PathScheme && !bc.NoTries() {
recoverable, _ := bc.triedb.Recoverable(diskRoot)
if !bc.HasState(diskRoot) && !recoverable {
diskRoot = bc.triedb.Head()
}
log.Debug("Head state missing, check recoverable", "disk root", diskRoot, "recoverable", recoverable)
}
if diskRoot != (common.Hash{}) {
log.Warn("Head state missing, repairing", "number", head.Number, "hash", head.Hash(), "diskRoot", diskRoot)
Expand Down
10 changes: 9 additions & 1 deletion core/txpool/legacypool/legacypool.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,9 @@ func New(config Config, chain BlockChain) *LegacyPool {
// pool, specifically, whether it is a Legacy, AccessList or Dynamic transaction.
func (pool *LegacyPool) Filter(tx *types.Transaction) bool {
switch tx.Type() {
case types.LegacyTxType, types.AccessListTxType, types.DynamicFeeTxType:
// TODO(Nathan): add SetCodeTxType into LegacyPool for test
// finally will rollback and be consistent with upstream
case types.LegacyTxType, types.AccessListTxType, types.DynamicFeeTxType, types.SetCodeTxType:
return true
default:
return false
Expand Down Expand Up @@ -692,6 +694,12 @@ func (pool *LegacyPool) validateTxBasics(tx *types.Transaction, local bool) erro
MinTip: pool.gasTip.Load().ToBig(),
MaxGas: pool.GetMaxGas(),
}
// TODO(Nathan): ensure before prague, no SetCodeTxType will be accepted and propagated
// finally will rollback and be consistent with upstream
currentBlock := pool.chain.CurrentBlock()
if pool.chainconfig.IsPrague(currentBlock.Number, currentBlock.Time) {
opts.Accept |= 1 << types.SetCodeTxType
}
if local {
opts.MinTip = new(big.Int)
}
Expand Down
11 changes: 1 addition & 10 deletions core/vote/vote_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"math/big"
"sync"
"time"

"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -71,6 +70,7 @@ func NewVoteManager(eth Backend, chain *core.BlockChain, pool *VotePool, journal
}
log.Info("Create voteSigner successfully")
voteManager.signer = voteSigner
metrics.GetOrRegisterLabel("miner-info", nil).Mark(map[string]interface{}{"VoteKey": common.Bytes2Hex(voteManager.signer.PubKey[:])})

// Create voteJournal
voteJournal, err := NewVoteJournal(journalPath)
Expand Down Expand Up @@ -107,7 +107,6 @@ func (voteManager *VoteManager) loop() {

startVote := true
blockCountSinceMining := 0
var once sync.Once
for {
select {
case ev := <-dlEventCh:
Expand Down Expand Up @@ -166,14 +165,6 @@ func (voteManager *VoteManager) loop() {
continue
}

// Add VoteKey to `miner-info`
once.Do(func() {
minerInfo := metrics.Get("miner-info")
if minerInfo != nil {
minerInfo.(metrics.Label).Value()["VoteKey"] = common.Bytes2Hex(voteManager.signer.PubKey[:])
}
})

// Vote for curBlockHeader block.
vote := &types.VoteData{
TargetNumber: curHead.Number.Uint64(),
Expand Down
57 changes: 26 additions & 31 deletions eth/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ import (
"github.com/ethereum/go-ethereum/internal/shutdowncheck"
"github.com/ethereum/go-ethereum/internal/version"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/miner"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/p2p"
Expand Down Expand Up @@ -178,6 +177,32 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
if err != nil {
return nil, err
}
// Override the chain config with provided settings.
var overrides core.ChainOverrides
if config.OverridePassedForkTime != nil {
chainConfig.ShanghaiTime = config.OverridePassedForkTime
chainConfig.KeplerTime = config.OverridePassedForkTime
chainConfig.FeynmanTime = config.OverridePassedForkTime
chainConfig.FeynmanFixTime = config.OverridePassedForkTime
chainConfig.CancunTime = config.OverridePassedForkTime
chainConfig.HaberTime = config.OverridePassedForkTime
chainConfig.HaberFixTime = config.OverridePassedForkTime
chainConfig.BohrTime = config.OverridePassedForkTime
overrides.OverridePassedForkTime = config.OverridePassedForkTime
}
if config.OverridePascal != nil {
chainConfig.PascalTime = config.OverridePascal
overrides.OverridePascal = config.OverridePascal
}
if config.OverridePrague != nil {
chainConfig.PragueTime = config.OverridePrague
overrides.OverridePrague = config.OverridePrague
}
if config.OverrideVerkle != nil {
chainConfig.VerkleTime = config.OverrideVerkle
overrides.OverrideVerkle = config.OverrideVerkle
}

// startup ancient freeze
freezeDb := chainDb
if stack.CheckIfMultiDataBase() {
Expand Down Expand Up @@ -279,31 +304,6 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
}
vmConfig.Tracer = t
}
// Override the chain config with provided settings.
var overrides core.ChainOverrides
if config.OverridePassedForkTime != nil {
chainConfig.ShanghaiTime = config.OverridePassedForkTime
chainConfig.KeplerTime = config.OverridePassedForkTime
chainConfig.FeynmanTime = config.OverridePassedForkTime
chainConfig.FeynmanFixTime = config.OverridePassedForkTime
chainConfig.CancunTime = config.OverridePassedForkTime
chainConfig.HaberTime = config.OverridePassedForkTime
chainConfig.HaberFixTime = config.OverridePassedForkTime
chainConfig.BohrTime = config.OverridePassedForkTime
overrides.OverridePassedForkTime = config.OverridePassedForkTime
}
if config.OverridePascal != nil {
chainConfig.PascalTime = config.OverridePascal
overrides.OverridePascal = config.OverridePascal
}
if config.OverridePrague != nil {
chainConfig.PragueTime = config.OverridePrague
overrides.OverridePrague = config.OverridePrague
}
if config.OverrideVerkle != nil {
chainConfig.VerkleTime = config.OverrideVerkle
overrides.OverrideVerkle = config.OverrideVerkle
}

bcOps := make([]core.BlockChainOption, 0)
if config.PersistDiff {
Expand Down Expand Up @@ -510,11 +510,6 @@ func (s *Ethereum) StartMining() error {
return fmt.Errorf("signer missing: %v", err)
}
parlia.Authorize(eb, wallet.SignData, wallet.SignTx)

minerInfo := metrics.Get("miner-info")
if minerInfo != nil {
minerInfo.(metrics.Label).Value()["Etherbase"] = eb.String()
}
}
// If mining is started, we can disable the transaction rejection mechanism
// introduced to speed sync times.
Expand Down
4 changes: 2 additions & 2 deletions metrics/exp/exp.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ func (exp *exp) publishResettingTimer(name string, metric *metrics.ResettingTime
exp.getFloat(name + ".99-percentile").Set(ps[3])
}

func (exp *exp) publishLabel(name string, metric metrics.Label) {
func (exp *exp) publishLabel(name string, metric *metrics.Label) {
labels := metric.Value()
for k, v := range labels {
exp.getMap(name).Set(k, exp.interfaceToExpVal(v))
Expand Down Expand Up @@ -274,7 +274,7 @@ func (exp *exp) syncToExpvar() {
exp.publishTimer(name, i)
case *metrics.ResettingTimer:
exp.publishResettingTimer(name, i)
case metrics.Label:
case *metrics.Label:
exp.publishLabel(name, i)
default:
panic(fmt.Sprintf("unsupported type for '%s': %T", name, i))
Expand Down
37 changes: 16 additions & 21 deletions metrics/label.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,32 @@
package metrics

// Label hold an map[string]interface{} value that can be set arbitrarily.
type Label interface {
Value() map[string]interface{}
Mark(map[string]interface{})
// Label is the standard implementation of a Label.
type Label struct {
value map[string]interface{}
}

// NewRegisteredLabel constructs and registers a new StandardLabel.
func NewRegisteredLabel(name string, r Registry) Label {
c := NewStandardLabel()
if nil == r {
// GetOrRegisterLabel returns an existing Label or constructs and registers a
// new Label.
func GetOrRegisterLabel(name string, r Registry) *Label {
if r == nil {
r = DefaultRegistry
}
r.Register(name, c)
return c
return r.GetOrRegister(name, NewLabel).(*Label)
}

// NewStandardLabel constructs a new StandardLabel.
func NewStandardLabel() *StandardLabel {
return &StandardLabel{}
}

// StandardLabel is the standard implementation of a Label.
type StandardLabel struct {
value map[string]interface{}
// NewLabel constructs a new Label.
func NewLabel() *Label {
return &Label{value: make(map[string]interface{})}
}

// Value returns label values.
func (l *StandardLabel) Value() map[string]interface{} {
func (l *Label) Value() map[string]interface{} {
return l.value
}

// Mark records the label.
func (l *StandardLabel) Mark(value map[string]interface{}) {
l.value = value
func (l *Label) Mark(value map[string]interface{}) {
for k, v := range value {
l.value[k] = v
}
}
4 changes: 2 additions & 2 deletions metrics/prometheus/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (c *collector) Add(name string, i any) error {
c.addTimer(name, m.Snapshot())
case *metrics.ResettingTimer:
c.addResettingTimer(name, m.Snapshot())
case metrics.Label:
case *metrics.Label:
c.addLabel(name, m)
default:
return fmt.Errorf("unknown prometheus metric type %T", i)
Expand Down Expand Up @@ -138,7 +138,7 @@ func (c *collector) addResettingTimer(name string, m *metrics.ResettingTimerSnap
c.buff.WriteRune('\n')
}

func (c *collector) addLabel(name string, m metrics.Label) {
func (c *collector) addLabel(name string, m *metrics.Label) {
labels := make([]string, 0, len(m.Value()))
for k, v := range m.Value() {
labels = append(labels, fmt.Sprintf(`%s="%s"`, mutateKey(k), fmt.Sprint(v)))
Expand Down
17 changes: 2 additions & 15 deletions triedb/pathdb/asyncnodebuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,6 @@ func (a *asyncnodebuffer) revertTo(db ethdb.KeyValueReader, nodes map[common.Has
return a.current.revertTo(db, nodes, accounts, storages)
}

// reset cleans up the disk cache.
func (a *asyncnodebuffer) reset() {
a.mux.Lock()
defer a.mux.Unlock()

a.current.reset()
a.background.reset()
}

// empty returns an indicator if nodebuffer contains any state transition inside.
func (a *asyncnodebuffer) empty() bool {
a.mux.RLock()
Expand All @@ -116,10 +107,6 @@ func (a *asyncnodebuffer) empty() bool {
return a.current.empty() && a.background.empty()
}

func (a *asyncnodebuffer) full() bool {
return a.current.full()
}

// flush persists the in-memory dirty trie node into the disk if the configured
// memory threshold is reached. Note, all data must be written atomically.
func (a *asyncnodebuffer) flush(db ethdb.KeyValueStore, freezer ethdb.AncientWriter, clean *fastcache.Cache, id uint64, force bool) error {
Expand All @@ -142,7 +129,7 @@ func (a *asyncnodebuffer) flush(db ethdb.KeyValueStore, freezer ethdb.AncientWri
}
}

if !a.full() {
if !a.current.full() {
return nil
}

Expand Down Expand Up @@ -284,7 +271,7 @@ func copyNodeCache(n *nodecache) *nodecache {
if n == nil || n.buffer == nil {
return nil
}
nc := newNodeCache(int(n.limit), n.nodes, n.states, n.layers)
nc := newNodeCache(int(n.limit), nil, nil, n.layers)
nc.immutable = atomic.LoadUint64(&n.immutable)

for acc, subTree := range n.nodes.nodes {
Expand Down
Loading

0 comments on commit 3a6ef6a

Please sign in to comment.