Skip to content

Commit

Permalink
Some bug fix (#533)
Browse files Browse the repository at this point in the history
  • Loading branch information
blxdyx authored Oct 15, 2024
1 parent aba2217 commit 671833a
Show file tree
Hide file tree
Showing 33 changed files with 122 additions and 261 deletions.
2 changes: 0 additions & 2 deletions cmd/state/commands/opcode_tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,6 @@ func (ot *opcodeTracer) CaptureTxStart(gasLimit uint64) {}

func (ot *opcodeTracer) CaptureTxEnd(restGas uint64) {}

func (ot *opcodeTracer) CaptureSystemTxEnd(restGas uint64) {}

func (ot *opcodeTracer) captureStartOrEnter(from, to libcommon.Address, create bool, input []byte) {
//fmt.Fprint(ot.summary, ot.lastLine)

Expand Down
5 changes: 2 additions & 3 deletions cmd/state/exec3/calltracer_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,8 @@ func (ct *CallTracer) Reset() {
func (ct *CallTracer) Froms() map[libcommon.Address]struct{} { return ct.froms }
func (ct *CallTracer) Tos() map[libcommon.Address]struct{} { return ct.tos }

func (ct *CallTracer) CaptureTxStart(gasLimit uint64) {}
func (ct *CallTracer) CaptureTxEnd(restGas uint64) {}
func (ct *CallTracer) CaptureSystemTxEnd(intrinsicGas uint64) {}
func (ct *CallTracer) CaptureTxStart(gasLimit uint64) {}
func (ct *CallTracer) CaptureTxEnd(restGas uint64) {}
func (ct *CallTracer) CaptureStart(env *vm.EVM, from libcommon.Address, to libcommon.Address, precompile bool, create bool, input []byte, gas uint64, value *uint256.Int, code []byte) {
if ct.froms == nil {
ct.froms = map[libcommon.Address]struct{}{}
Expand Down
20 changes: 15 additions & 5 deletions cmd/state/exec3/historical_trace_worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,11 @@ func (rw *HistoricalTraceWorker) RunTxTask(txTask *state.TxTask) {
rw.stateReader.SetTxNum(txTask.TxNum)
rw.stateReader.ResetReadSet()
rw.stateWriter = state.NewNoopWriter()
//rw.stateReader.SetTrace(true)

rw.ibs.Reset()
ibs := rw.ibs
//ibs.SetTrace(true)

rules := txTask.Rules
var err error
Expand Down Expand Up @@ -193,7 +195,7 @@ func (rw *HistoricalTraceWorker) RunTxTask(txTask *state.TxTask) {
return core.SysCallContract(contract, data, rw.execArgs.ChainConfig, ibs, header, rw.execArgs.Engine, false /* constCall */)
}

_, _, _, err := rw.execArgs.Engine.Finalize(rw.execArgs.ChainConfig, types.CopyHeader(header), ibs, txTask.Txs, txTask.Uncles, txTask.BlockReceipts, txTask.Withdrawals, txTask.Requests, rw.chain, syscall, nil, 0, nil, rw.logger)
_, _, _, err := rw.execArgs.Engine.Finalize(rw.execArgs.ChainConfig, types.CopyHeader(header), ibs, txTask.Txs, txTask.Uncles, txTask.BlockReceipts, txTask.Withdrawals, txTask.Requests, rw.chain, syscall, nil, txTask.TxIndex, rw.chainTx, rw.logger)
if err != nil {
txTask.Error = err
}
Expand All @@ -202,21 +204,27 @@ func (rw *HistoricalTraceWorker) RunTxTask(txTask *state.TxTask) {
return core.SysCallContract(contract, data, rw.execArgs.ChainConfig, ibs, header, rw.execArgs.Engine, false /* constCall */)
}

systemCall := func(ibs *state.IntraBlockState, index int) ([]byte, bool, error) {
systemCall := func(ibs *state.IntraBlockState) ([]byte, bool, error) {

rw.taskGasPool.Reset(txTask.Tx.GetGas(), rw.execArgs.ChainConfig.GetMaxBlobGasPerBlock())
rw.taskGasPool.Reset(txTask.Tx.GetGas(), txTask.Tx.GetBlobGas())
if tracer := rw.consumer.NewTracer(); tracer != nil {
rw.vmConfig.Debug = true
rw.vmConfig.Tracer = tracer
}
rw.vmConfig.SkipAnalysis = txTask.SkipAnalysis
msg := txTask.TxAsMessage
ibs.SetTxContext(txTask.TxIndex, txTask.BlockNum)
msg.SetCheckNonce(!rw.vmConfig.StatelessExec)
if rw.execArgs.ChainConfig.IsCancun(header.Number.Uint64(), header.Time) {
rules := rw.execArgs.ChainConfig.Rules(header.Number.Uint64(), header.Time)
ibs.Prepare(rules, msg.From(), txTask.EvmBlockContext.Coinbase, msg.To(), vm.ActivePrecompiles(rules), msg.AccessList(), nil)
}
rw.evm.ResetBetweenBlocks(txTask.EvmBlockContext, core.NewEVMTxContext(msg), ibs, *rw.vmConfig, rules)

txContext := core.NewEVMTxContext(msg)
if rw.vmConfig.TraceJumpDest {
txContext.TxHash = txTask.Tx.Hash()
}
rw.evm.ResetBetweenBlocks(txTask.EvmBlockContext, txContext, ibs, *rw.vmConfig, rules)
// Increment the nonce for the next transaction
ibs.SetNonce(msg.From(), ibs.GetNonce(msg.From())+1)
ret, leftOverGas, err := rw.evm.Call(
Expand All @@ -240,8 +248,9 @@ func (rw *HistoricalTraceWorker) RunTxTask(txTask *state.TxTask) {
return ret, true, nil
}

_, _, _, err := rw.execArgs.Engine.Finalize(rw.execArgs.ChainConfig, types.CopyHeader(header), ibs, txTask.Txs, txTask.Uncles, txTask.BlockReceipts, txTask.Withdrawals, txTask.Requests, rw.chain, syscall, systemCall, txTask.TxIndex, nil, rw.logger)
_, _, _, err := rw.execArgs.Engine.Finalize(rw.execArgs.ChainConfig, types.CopyHeader(header), ibs, txTask.Txs, txTask.Uncles, txTask.BlockReceipts, txTask.Withdrawals, txTask.Requests, rw.chain, syscall, systemCall, txTask.TxIndex, rw.chainTx, rw.logger)
if err != nil {
log.Error("run system tx err", "block Number", txTask.BlockNum, "txIndex", txTask.TxIndex, "err", err)
txTask.Error = err
}
default:
Expand Down Expand Up @@ -271,6 +280,7 @@ func (rw *HistoricalTraceWorker) RunTxTask(txTask *state.TxTask) {
// MA applytx
applyRes, err := core.ApplyMessage(rw.evm, msg, rw.taskGasPool, true /* refunds */, false /* gasBailout */)
if err != nil {
log.Error("run tx err", "block Number", txTask.BlockNum, "txIndex", txTask.TxIndex, "err", err)
txTask.Error = err
} else {
txTask.Failed = applyRes.Failed()
Expand Down
15 changes: 1 addition & 14 deletions cmd/state/exec3/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ func (rw *Worker) RunTxTaskNoLock(txTask *state.TxTask, isMining bool) {
return core.SysCallContract(contract, data, rw.chainConfig, ibs, header, rw.engine, false /* constCall */)
}

systemCall := func(ibs *state.IntraBlockState, index int) ([]byte, bool, error) {
systemCall := func(ibs *state.IntraBlockState) ([]byte, bool, error) {
rw.taskGasPool.Reset(txTask.Tx.GetGas(), rw.chainConfig.GetMaxBlobGasPerBlock())
rw.callTracer.Reset()
rw.vmCfg.SkipAnalysis = txTask.SkipAnalysis
Expand Down Expand Up @@ -308,19 +308,6 @@ func (rw *Worker) RunTxTaskNoLock(txTask *state.TxTask, isMining bool) {
txTask.TraceFroms = rw.callTracer.Froms()
txTask.TraceTos = rw.callTracer.Tos()
}

if txTask.Error == nil {
txTask.BalanceIncreaseSet = ibs.BalanceIncreaseSet()
//for addr, bal := range txTask.BalanceIncreaseSet {
// fmt.Printf("BalanceIncreaseSet [%x]=>[%d]\n", addr, &bal)
//}
if err = ibs.MakeWriteSet(rules, rw.stateWriter); err != nil {
panic(err)
}
txTask.ReadLists = rw.stateReader.ReadSet()
txTask.WriteLists = rw.stateWriter.WriteSet()
txTask.AccountPrevs, txTask.AccountDels, txTask.StoragePrevs, txTask.CodePrevs = rw.stateWriter.PrevAndDels()
}
return ret, true, nil
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/state/exec3/state_recon.go
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ func (rw *ReconWorker) runTxTask(txTask *state.TxTask) error {
return core.SysCallContract(contract, data, rw.chainConfig, ibs, header, rw.engine, false /* constCall */)
}

systemCall := func(ibs *state.IntraBlockState, index int) ([]byte, bool, error) {
systemCall := func(ibs *state.IntraBlockState) ([]byte, bool, error) {
vmConfig := vm.Config{NoReceipts: true, SkipAnalysis: txTask.SkipAnalysis}
msg := txTask.TxAsMessage
ibs.SetTxContext(txTask.TxIndex, txTask.BlockNum)
Expand Down
2 changes: 1 addition & 1 deletion consensus/consensus.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ type ChainReader interface {

type SystemCall func(contract libcommon.Address, data []byte) ([]byte, error)

type SystemTxCall func(ibs *state.IntraBlockState, index int) ([]byte, bool, error)
type SystemTxCall func(ibs *state.IntraBlockState) ([]byte, bool, error)

// Use more options to call contract
type SysCallCustom func(contract libcommon.Address, data []byte, ibs *state.IntraBlockState, header *types.Header, constCall bool) ([]byte, error)
Expand Down
2 changes: 1 addition & 1 deletion consensus/parlia/bohrFork.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func (p *Parlia) getTurnLength(chain consensus.ChainHeaderReader, header *types.
} else {
turnLength = defaultTurnLength
}
log.Debug("getTurnLength", "turnLength", turnLength)
log.Trace("getTurnLength", "turnLength", turnLength)

return &turnLength, nil
}
Expand Down
147 changes: 66 additions & 81 deletions consensus/parlia/parlia.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ import (
"github.com/erigontech/erigon/crypto/cryptopool"
"github.com/erigontech/erigon/turbo/services"

"github.com/Giulio2002/bls"
"github.com/erigontech/erigon-lib/chain"
libcommon "github.com/erigontech/erigon-lib/common"
"github.com/erigontech/erigon-lib/common/length"
"github.com/erigontech/erigon/common"
"github.com/erigontech/erigon/common/math"
lru "github.com/hashicorp/golang-lru/arc/v2"
"github.com/prysmaticlabs/prysm/v5/crypto/bls"
"github.com/willf/bitset"

"github.com/erigontech/erigon-lib/common/hexutility"
Expand Down Expand Up @@ -99,7 +99,6 @@ var (

validatorItemsCache []ValidatorItem
maxElectedValidatorsCache = big.NewInt(0)
doDistributeSysReward = false
)

// Various error messages to mark blocks invalid. These should be private to
Expand Down Expand Up @@ -485,7 +484,7 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header
continue
}

voteAddr, err := bls.PublicKeyFromBytes(snap.Validators[val].VoteAddress[:])
voteAddr, err := bls.NewPublicKeyFromBytes(snap.Validators[val].VoteAddress[:])
if err != nil {
return fmt.Errorf("BLS public key converts failed: %v", err)
}
Expand All @@ -497,12 +496,11 @@ func (p *Parlia) verifyVoteAttestation(chain consensus.ChainHeaderReader, header
return errors.New("invalid attestation, not enough validators voted")
}

// Verify the aggregated signature.
aggSig, err := bls.SignatureFromBytes(attestation.AggSignature[:])
aggSig, err := bls.NewSignatureFromBytes(attestation.AggSignature[:])
if err != nil {
return fmt.Errorf("BLS signature converts failed: %v", err)
}
if !aggSig.FastAggregateVerify(votedAddrs, attestation.Data.Hash()) {
if !aggSig.VerifyAggregate(attestation.Data.Hash().Bytes(), votedAddrs) {
return errors.New("invalid attestation, signature verify failed")
}

Expand Down Expand Up @@ -892,7 +890,7 @@ func (p *Parlia) verifyTurnLength(chain consensus.ChainHeaderReader, header *typ
return err
}
if turnLength != nil && *turnLength == *turnLengthFromHeader {
log.Debug("verifyTurnLength", "turnLength", *turnLength)
log.Trace("verifyTurnLength", "turnLength", *turnLength)
return nil
}
}
Expand Down Expand Up @@ -1042,7 +1040,13 @@ func (p *Parlia) finalize(header *types.Header, ibs *state.IntraBlockState, txs
}
}
}
finish, err = p.distributeIncoming(header.Coinbase, ibs, header, &txs, &receipts, &systemTxs, &header.GasUsed, mining, systemTxCall, &curIndex, &txIndex)
finish, err = p.distributeToSystem(header.Coinbase, ibs, header, &txs, &receipts, &systemTxs, &header.GasUsed, mining, systemTxCall, &curIndex, &txIndex)
if err != nil || finish {
//log.Error("distributeIncoming", "block hash", header.Hash(), "error", err, "systemTxs", len(systemTxs))
return nil, nil, nil, err
}

finish, err = p.distributeToValidator(header.Coinbase, ibs, header, &txs, &receipts, &systemTxs, &header.GasUsed, mining, systemTxCall, &curIndex, &txIndex)
if err != nil || finish {
//log.Error("distributeIncoming", "block hash", header.Hash(), "error", err, "systemTxs", len(systemTxs))
return nil, nil, nil, err
Expand Down Expand Up @@ -1352,47 +1356,6 @@ func (p *Parlia) getCurrentValidators(header *types.Header, ibs *state.IntraBloc
return valSet, voteAddrmap, nil
}

// distributeToValidator deposits validator reward to validator contract
func (p *Parlia) distributeIncoming(val libcommon.Address, state *state.IntraBlockState, header *types.Header,
txs *types.Transactions, receipts *types.Receipts, systemTxs *types.Transactions,
usedGas *uint64, mining bool, systemTxCall consensus.SystemTxCall, curIndex *int, txIndex *int) (bool, error) {
coinbase := header.Coinbase
balance := state.GetBalance(consensus.SystemAddress).Clone()
if balance.Cmp(u256.Num0) <= 0 && *curIndex == *txIndex {
return false, nil
}
if *curIndex == *txIndex {
doDistributeSysReward = !p.chainConfig.IsKepler(header.Number.Uint64(), header.Time) &&
state.GetBalance(systemcontracts.SystemRewardContract).Cmp(maxSystemBalance) < 0
if doDistributeSysReward {
rewards := new(uint256.Int)
rewards = rewards.Rsh(balance, systemRewardPercent)
state.SetBalance(consensus.SystemAddress, balance.Sub(balance, rewards), tracing.BalanceDecreaseGasBuy)
state.AddBalance(coinbase, rewards, tracing.BalanceDecreaseGasBuy)
if rewards.Cmp(u256.Num0) > 0 {
finish, err := p.distributeToSystem(rewards, state, header, txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
if err != nil {
return true, err
} else if finish {
return finish, nil
}
}
}
}
if *curIndex != *txIndex && doDistributeSysReward {
*curIndex++
}
if *curIndex == *txIndex {
state.SetBalance(consensus.SystemAddress, u256.Num0, tracing.BalanceDecreaseGasBuy)
state.AddBalance(coinbase, balance, tracing.BalanceDecreaseGasBuy)
//log.Debug("[parlia] distribute to validator contract", "block hash", header.Hash(), "amount", balance)
return p.distributeToValidator(balance, val, state, header, txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
}
*curIndex++
return false, nil

}

// slash spoiled validators
func (p *Parlia) slash(spoiledVal libcommon.Address, state *state.IntraBlockState, header *types.Header,
txs *types.Transactions, receipts *types.Receipts, systemTxs *types.Transactions, usedGas *uint64, mining bool,
Expand Down Expand Up @@ -1439,48 +1402,72 @@ func (p *Parlia) initContract(state *state.IntraBlockState, header *types.Header
p.logger.Error("[parlia] Unable to pack tx for init validator set", "err", err)
return false, err
}
for i, c := range contracts {
for _, c := range contracts {
p.logger.Info("Init contracts", "len(systemTxs)", len(*systemTxs), "len(txs)", len(*txs))
if *curIndex == *txIndex {
finish, err = p.applyTransaction(header.Coinbase, c, u256.Num0, data, state, header, txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
if err != nil {
return false, err
} else if finish {
p.logger.Info("[parlia] init contract", "block hash", header.Hash(), "i", i, "contract", c)
return finish, nil
}
return p.applyTransaction(header.Coinbase, c, u256.Num0, data, state, header, txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
}
*curIndex++
}
return false, nil
}

func (p *Parlia) distributeToSystem(amount *uint256.Int, state *state.IntraBlockState, header *types.Header,
func (p *Parlia) distributeToSystem(val libcommon.Address, ibs *state.IntraBlockState, header *types.Header,
txs *types.Transactions, receipts *types.Receipts, systemTxs *types.Transactions,
usedGas *uint64, mining bool, systemTxCall consensus.SystemTxCall, curIndex *int,
) (bool, error) {
return p.applyTransaction(header.Coinbase, systemcontracts.SystemRewardContract, amount, nil, state, header,
txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
usedGas *uint64, mining bool, systemTxCall consensus.SystemTxCall, curIndex, txIndex *int) (bool, error) {
if *curIndex == *txIndex {
balance := ibs.GetBalance(consensus.SystemAddress).Clone()
if balance.Cmp(u256.Num0) <= 0 {
return false, nil
}
doDistributeSysReward := !p.chainConfig.IsKepler(header.Number.Uint64(), header.Time) &&
ibs.GetBalance(systemcontracts.SystemRewardContract).Cmp(maxSystemBalance) < 0
if doDistributeSysReward {
rewards := new(uint256.Int)
rewards = rewards.Rsh(balance, systemRewardPercent)

ibs.SetBalance(consensus.SystemAddress, balance.Sub(balance, rewards), tracing.BalanceDecreaseGasBuy)
ibs.AddBalance(val, rewards, tracing.BalanceDecreaseGasBuy)
if rewards.Cmp(u256.Num0) > 0 {
return p.applyTransaction(val, systemcontracts.SystemRewardContract, rewards, nil, ibs, header,
txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
}
}
return false, nil
}
*curIndex++
return false, nil
}

// slash spoiled validators
func (p *Parlia) distributeToValidator(amount *uint256.Int, validator libcommon.Address, state *state.IntraBlockState, header *types.Header,
// distributeToValidator deposits validator reward to validator contract
func (p *Parlia) distributeToValidator(val libcommon.Address, ibs *state.IntraBlockState, header *types.Header,
txs *types.Transactions, receipts *types.Receipts, systemTxs *types.Transactions,
usedGas *uint64, mining bool, systemTxCall consensus.SystemTxCall, curIndex *int,
) (bool, error) {
// method
method := "deposit"
usedGas *uint64, mining bool, systemTxCall consensus.SystemTxCall, curIndex, txIndex *int) (bool, error) {

// get packed data
data, err := p.validatorSetABI.Pack(method,
validator,
)
if err != nil {
p.logger.Error("[parlia] Unable to pack tx for deposit", "err", err)
return true, err
if *curIndex == *txIndex {
balance := ibs.GetBalance(consensus.SystemAddress).Clone()

if balance.Cmp(u256.Num0) <= 0 {
return false, nil
}
ibs.SetBalance(consensus.SystemAddress, u256.Num0, tracing.BalanceDecreaseGasBuy)
ibs.AddBalance(val, balance, tracing.BalanceDecreaseGasBuy)
// method
method := "deposit"

// get packed data
data, err := p.validatorSetABI.Pack(method,
val,
)
if err != nil {
p.logger.Error("[parlia] Unable to pack tx for deposit", "err", err)
return true, err
}
// apply message
return p.applyTransaction(val, systemcontracts.ValidatorContract, balance, data, ibs, header, txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
}
// apply message
return p.applyTransaction(header.Coinbase, systemcontracts.ValidatorContract, amount, data, state, header, txs, receipts, systemTxs, usedGas, mining, systemTxCall, curIndex)
*curIndex++
return false, nil
}

func (p *Parlia) applyTransaction(from libcommon.Address, to libcommon.Address, value *uint256.Int, data []byte,
Expand All @@ -1493,9 +1480,7 @@ func (p *Parlia) applyTransaction(from libcommon.Address, to libcommon.Address,
if len(*systemTxs) == 0 {
return false, errors.New("supposed to get a actual transaction, but get none")
}
if actualTx == nil {
return false, errors.New("supposed to get a actual transaction, but get nil")
}

actualHash := actualTx.SigningHash(p.chainConfig.ChainID)
if !bytes.Equal(actualHash.Bytes(), expectedHash.Bytes()) {
return false, fmt.Errorf("expected system tx (hash %v, nonce %d, to %s, value %s, gas %d, gasPrice %s, data %s), actual tx (hash %v, nonce %d, to %s, value %s, gas %d, gasPrice %s, data %s)",
Expand All @@ -1515,7 +1500,7 @@ func (p *Parlia) applyTransaction(from libcommon.Address, to libcommon.Address,
hex.EncodeToString(actualTx.GetData()),
)
}
_, shouldBreak, err := systemTxCall(ibs, *curIndex)
_, shouldBreak, err := systemTxCall(ibs)
if err != nil {
return false, err
}
Expand Down
Loading

0 comments on commit 671833a

Please sign in to comment.