Compare commits

..

31 Commits

Author SHA1 Message Date
Roshan
fd0ee7d3e9 fix: adjust the timing of initializing Feynman system contracts (#2203)
* fix: adjust the timing of initializing Feynman system contracts

* fix test case
2024-02-04 17:53:34 +08:00
Roshan
e7cd04b38e fix: add check for block number (#2199)
* fix: add check for block number

* fix review comments

* fix review comments
2024-02-02 14:13:57 +08:00
Roshan
d7e7f73718 chore: add initialize for TokenRecoverPortalContract (#2194) 2024-02-01 16:18:34 +08:00
zjubfd
fc9230e4e6 Merge pull request #2192 from Pythonberg1997/bc-fusion
chore: merge with develop branch
2024-01-30 16:55:08 +08:00
Roshan
2f0b2f0cf3 chore: resolve merge conflicts and fix review comments 2024-01-30 16:29:23 +08:00
Roshan
7f6c4cd7cd Merge remote-tracking branch 'BNB-chain/develop' into bc-fusion-roshan
# Conflicts:
#	cmd/geth/blsaccountcmd.go
#	miner/worker.go
2024-01-30 16:27:57 +08:00
Roshan
818379d999 fix: upgrade system contracts twice issue in traceBlockParallel (#2178)
* fix: upgrade system contracts twice issue in `traceBlockParallel`

* fix review comments
2024-01-25 19:40:26 +08:00
Roshan
65baf18031 chore: update the contracts' byte code of Feynman upgrade (#2175)
* chore: update the contracts' byte code of Feynman upgrade

* add `OverrideFeynman`
2024-01-22 13:01:16 +08:00
Roshan
13f17f2970 fix: adjusted the timing of UpgradeBuildInSystemContract (#2166)
* fix: adjusted the timing of `UpgradeBuildInSystemContract`

* fix review comments

* fix review comments

* fix review comments

* fix review comments

* add `UpgradeBuildInSystemContract` to `traceBlock`

* add `UpgradeBuildInSystemContract` to `traceBlock`

* add `UpgradeBuildInSystemContract` to all trace functions
2024-01-22 12:15:05 +08:00
Roshan
7ade1d2a5d fix: compare headers' number in Big.Int rather than Uint64 (#2158) 2024-01-15 10:54:54 +08:00
Roshan
e2e2ac750c chore: fix lint issue (#2139) 2024-01-08 12:06:27 +08:00
zjubfd
85c6750592 Merge pull request #2138 from Pythonberg1997/bc-fusion
chore: merge with develop branch
2024-01-08 11:49:07 +08:00
Roshan
7466f0a075 Merge branch 'develop' into bc-fusion
# Conflicts:
#	core/systemcontracts/upgrade.go
#	params/config.go
2024-01-08 11:37:58 +08:00
Roshan
64a57a3e2a chore: update abi and bytecode (#2137) 2024-01-08 11:15:14 +08:00
Roshan
e5822640c6 chore: add SystemTxsGas for Feynman upgrade (#2133) 2024-01-04 20:18:45 +08:00
Roshan
432085ea62 fix: avoid update validators on Feynman block (#2102) 2023-12-25 11:20:50 +08:00
zjubfd
aab5ad94b8 Merge pull request #2096 from Pythonberg1997/bc-fusion
chore: merge with develop branch
2023-12-21 16:30:35 +08:00
Roshan
c0df5e7000 chore: add new byte code of TokenHub and GovHub to Feynman upgrade 2023-12-21 16:15:10 +08:00
Roshan
167da21801 Merge branch 'develop' into merge
# Conflicts:
#	params/config.go
2023-12-21 16:14:09 +08:00
Roshan
08f75ca23f chore: update system contracts' byte code (#2093) 2023-12-20 17:17:43 +08:00
Roshan
6685f68995 chore: fix CI issues (#2085) 2023-12-19 09:46:15 +08:00
Roshan
d4f7313760 chore: remove unused code (#2061) 2023-12-13 15:53:36 +08:00
Roshan
94b68156c8 chore: update logic of determining breathe block and returned data of verifyDoubleSignEvidence (#2056) 2023-12-12 17:24:43 +08:00
Roshan
ab8793ae9f fix: bug in determining breathe block (#2055) 2023-12-12 14:21:30 +08:00
Roshan
6744d7c15f chore: modify breath block interval for test (#2054) 2023-12-11 17:12:42 +08:00
zjubfd
3414e5672a Merge pull request #2048 from Pythonberg1997/bc-fusion
chore: merge with develop branch
2023-12-08 16:26:32 +08:00
Roshan
8f3c525adc chore: resolve merge conflicts and fix review comments 2023-12-08 16:20:30 +08:00
Roshan
3e9e6423c0 Merge remote-tracking branch 'BNBChain/develop' into bc-fusion
# Conflicts:
#	cmd/geth/blsaccountcmd.go
#	params/config.go
2023-12-07 18:25:45 +08:00
Roshan
5743b067ba feat: add generate-proof to geth cmd (#2028)
* feat: add `generate-proof` to geth cmd

* chore: rename variable
2023-12-05 11:46:54 +08:00
Roshan
d3f882d799 chore: update contracts code (#2024) 2023-12-04 10:43:23 +08:00
Roshan
030e41607e feat: add new fork block and precompile contract for BEP294 and BEP299 (#1874) 2023-11-30 19:36:54 +08:00
28 changed files with 902 additions and 989 deletions

View File

@@ -1,37 +0,0 @@
name: Go Nancy
on:
# Scan changed files in PRs (diff-aware scanning):
pull_request: {}
# Scan on-demand through GitHub Actions interface:
workflow_dispatch: {}
# Scan mainline branches and report all findings:
push:
branches: ["master", "develop"]
jobs:
build:
strategy:
matrix:
go-version: [1.21.x]
os: [ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Set up Go 1.x in order to write go.list file
uses: actions/setup-go@v2
with:
go-version: ${{ matrix.go-version }}
- name: Go mod tidy
run: go mod tidy
- name: WriteGoList
run: go list -json -deps ./... > go.list
- name: Nancy
uses: sonatype-nexus-community/nancy-github-action@main
with:
nancyCommand: sleuth --loud

View File

@@ -1,22 +1,4 @@
# Changelog
## v1.3.10
FEATURE
* [\#2047](https://github.com/bnb-chain/bsc/pull/2047) feat: add new fork block and precompile contract for BEP294 and BEP299
## v1.3.9
FEATURE
* [\#2186](https://github.com/bnb-chain/bsc/pull/2186) log: support maxBackups in config.toml
BUGFIX
* [\#2160](https://github.com/bnb-chain/bsc/pull/2160) cmd: fix dump cli cannot work in path mode
* [\#2183](https://github.com/bnb-chain/bsc/pull/2183) p2p: resolved deadlock on p2p server shutdown
IMPROVEMENT
* [\#2177](https://github.com/bnb-chain/bsc/pull/0000) build(deps): bump github.com/quic-go/quic-go from 0.39.3 to 0.39.4
* [\#2185](https://github.com/bnb-chain/bsc/pull/2185) consensus/parlia: set nonce before evm run
* [\#2190](https://github.com/bnb-chain/bsc/pull/2190) fix(legacypool): deprecate already known error
* [\#2195](https://github.com/bnb-chain/bsc/pull/2195) eth/fetcher: downgrade state tx log
## v1.3.8
FEATURE
* [\#2074](https://github.com/bnb-chain/bsc/pull/2074) faucet: new faucet client

View File

@@ -633,24 +633,19 @@ func blsAccountDelete(ctx *cli.Context) error {
// blsAccountGenerateProof generate ownership proof for a selected BLS account.
func blsAccountGenerateProof(ctx *cli.Context) error {
addrString := ctx.Args().First()
if addrString == "" {
utils.Fatalf("Operator account must be given as argument.")
pubkeyString := ctx.Args().First()
if pubkeyString == "" {
utils.Fatalf("BLS account must be given as argument.")
}
addr := common.HexToAddress(addrString)
blsPubkeyString := ctx.Args().Get(1)
if blsPubkeyString == "" {
utils.Fatalf("BLS pubkey must be given as argument.")
}
blsPubkeyBz, err := hex.DecodeString(strings.TrimPrefix(blsPubkeyString, "0x"))
pubkeyBz, err := hex.DecodeString(strings.TrimPrefix(pubkeyString, "0x"))
if err != nil {
utils.Fatalf("Could not decode string %s as hex.", blsPubkeyString)
utils.Fatalf("Could not decode string %s as hex.", pubkeyString)
}
blsPublicKey, err := bls.PublicKeyFromBytes(blsPubkeyBz)
blsPublicKey, err := bls.PublicKeyFromBytes(pubkeyBz)
if err != nil {
utils.Fatalf("%#x is not a valid BLS public key.", blsPubkeyBz)
utils.Fatalf("%#x is not a valid BLS public key.", pubkeyBz)
}
blsPublicKeyBz := blsPublicKey.Marshal()
cfg := gethConfig{Node: defaultNodeConfig()}
// Load config file.
@@ -687,10 +682,10 @@ func blsAccountGenerateProof(ctx *cli.Context) error {
chainId := new(big.Int).SetInt64(chainIdInt64)
paddedChainIdBytes := make([]byte, 32)
copy(paddedChainIdBytes[32-len(chainId.Bytes()):], chainId.Bytes())
msgHash := crypto.Keccak256(append(addr.Bytes(), append(blsPublicKey.Marshal(), paddedChainIdBytes...)...))
msgHash := crypto.Keccak256(append(blsPublicKeyBz, paddedChainIdBytes...))
req := &validatorpb.SignRequest{
PublicKey: blsPublicKey.Marshal(),
PublicKey: blsPublicKeyBz,
SigningRoot: msgHash,
}
sig, err := km.Sign(context.Background(), req)

View File

@@ -18,6 +18,7 @@
package utils
import (
"bufio"
"context"
"crypto/ecdsa"
"encoding/hex"
@@ -1888,7 +1889,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
if ctx.IsSet(StateHistoryFlag.Name) {
cfg.StateHistory = ctx.Uint64(StateHistoryFlag.Name)
}
scheme, err := ParseCLIAndConfigStateScheme(ctx.String(StateSchemeFlag.Name), cfg.StateScheme)
scheme, err := CompareStateSchemeCLIWithConfig(ctx)
if err != nil {
Fatalf("%v", err)
}
@@ -2357,7 +2358,11 @@ func MakeChain(ctx *cli.Context, stack *node.Node, readonly bool) (*core.BlockCh
if gcmode := ctx.String(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
}
scheme, err := rawdb.ParseStateScheme(ctx.String(StateSchemeFlag.Name), chainDb)
provided, err := CompareStateSchemeCLIWithConfig(ctx)
if err != nil {
Fatalf("%v", err)
}
scheme, err := rawdb.ParseStateScheme(provided, chainDb)
if err != nil {
Fatalf("%v", err)
}
@@ -2425,7 +2430,11 @@ func MakeTrieDatabase(ctx *cli.Context, disk ethdb.Database, preimage bool, read
config := &trie.Config{
Preimages: preimage,
}
scheme, err := rawdb.ParseStateScheme(ctx.String(StateSchemeFlag.Name), disk)
provided, err := CompareStateSchemeCLIWithConfig(ctx)
if err != nil {
Fatalf("%v", err)
}
scheme, err := rawdb.ParseStateScheme(provided, disk)
if err != nil {
Fatalf("%v", err)
}
@@ -2444,15 +2453,27 @@ func MakeTrieDatabase(ctx *cli.Context, disk ethdb.Database, preimage bool, read
return trie.NewDatabase(disk, config)
}
// ParseCLIAndConfigStateScheme parses state scheme in CLI and config.
func ParseCLIAndConfigStateScheme(cliScheme, cfgScheme string) (string, error) {
if cliScheme == "" {
// CompareStateSchemeCLIWithConfig compare state scheme in CLI with config whether are equal.
func CompareStateSchemeCLIWithConfig(ctx *cli.Context) (string, error) {
var (
cfgScheme string
err error
)
if file := ctx.String("config"); file != "" {
// we don't validate cfgScheme because it's already checked in cmd/geth/loadBaseConfig
if cfgScheme, err = scanConfigForStateScheme(file); err != nil {
log.Error("Failed to parse config file", "error", err)
return "", err
}
}
if !ctx.IsSet(StateSchemeFlag.Name) {
if cfgScheme != "" {
log.Info("Use config state scheme", "config", cfgScheme)
}
return cfgScheme, nil
}
cliScheme := ctx.String(StateSchemeFlag.Name)
if !rawdb.ValidateStateScheme(cliScheme) {
return "", fmt.Errorf("invalid state scheme in CLI: %s", cliScheme)
}
@@ -2462,3 +2483,35 @@ func ParseCLIAndConfigStateScheme(cliScheme, cfgScheme string) (string, error) {
}
return "", fmt.Errorf("incompatible state scheme, CLI: %s, config: %s", cliScheme, cfgScheme)
}
func scanConfigForStateScheme(file string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
targetStr := "StateScheme"
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, targetStr) {
return indexStateScheme(line), nil
}
}
if err = scanner.Err(); err != nil {
return "", err
}
return "", nil
}
func indexStateScheme(str string) string {
i1 := strings.Index(str, "\"")
i2 := strings.LastIndex(str, "\"")
if i1 != -1 && i2 != -1 && i1 < i2 {
return str[i1+1 : i2]
}
return ""
}

View File

@@ -18,8 +18,13 @@
package utils
import (
"os"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
"github.com/ethereum/go-ethereum/core/rawdb"
)
func Test_SplitTagsFlag(t *testing.T) {
@@ -62,3 +67,126 @@ func Test_SplitTagsFlag(t *testing.T) {
})
}
}
func Test_parseConfig(t *testing.T) {
tests := []struct {
name string
fn func() string
wantedResult string
wantedIsErr bool
wantedErrStr string
}{
{
name: "path",
fn: func() string {
tomlString := `[Eth]NetworkId = 56StateScheme = "path"`
return createTempTomlFile(t, tomlString)
},
wantedResult: rawdb.PathScheme,
wantedIsErr: false,
wantedErrStr: "",
},
{
name: "hash",
fn: func() string {
tomlString := `[Eth]NetworkId = 56StateScheme = "hash"`
return createTempTomlFile(t, tomlString)
},
wantedResult: rawdb.HashScheme,
wantedIsErr: false,
wantedErrStr: "",
},
{
name: "empty state scheme",
fn: func() string {
tomlString := `[Eth]NetworkId = 56StateScheme = ""`
return createTempTomlFile(t, tomlString)
},
wantedResult: "",
wantedIsErr: false,
wantedErrStr: "",
},
{
name: "unset state scheme",
fn: func() string {
tomlString := `[Eth]NetworkId = 56`
return createTempTomlFile(t, tomlString)
},
wantedResult: "",
wantedIsErr: false,
wantedErrStr: "",
},
{
name: "failed to open file",
fn: func() string { return "" },
wantedResult: "",
wantedIsErr: true,
wantedErrStr: "open : no such file or directory",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := scanConfigForStateScheme(tt.fn())
if tt.wantedIsErr {
assert.Contains(t, err.Error(), tt.wantedErrStr)
} else {
assert.Nil(t, err)
}
assert.Equal(t, tt.wantedResult, result)
})
}
}
// createTempTomlFile is a helper function to create a temp file with the provided TOML content
func createTempTomlFile(t *testing.T, content string) string {
t.Helper()
dir := t.TempDir()
file, err := os.CreateTemp(dir, "config.toml")
if err != nil {
t.Fatalf("Unable to create temporary file: %v", err)
}
defer file.Close()
_, err = file.WriteString(content)
if err != nil {
t.Fatalf("Unable to write to temporary file: %v", err)
}
return file.Name()
}
func Test_parseString(t *testing.T) {
tests := []struct {
name string
arg string
wantResult string
}{
{
name: "hash string",
arg: "\"hash\"",
wantResult: rawdb.HashScheme,
},
{
name: "path string",
arg: "\"path\"",
wantResult: rawdb.PathScheme,
},
{
name: "empty string",
arg: "",
wantResult: "",
},
{
name: "empty string",
arg: "\"\"",
wantResult: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := indexStateScheme(tt.arg); got != tt.wantResult {
t.Errorf("parseString() = %v, want %v", got, tt.wantResult)
}
})
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,10 @@ import (
"github.com/ethereum/go-ethereum/rpc"
)
const SecondsPerDay uint64 = 86400
// TODO: SecondsPerDay represents the seconds in a day, it should be 86400
// We set it to 60 for testing purpose and we will change it back to 86400 when launching
// const SecondsPerDay uint64 = 86400
const SecondsPerDay uint64 = 60
// the params should be two blocks' time(timestamp)
func sameDayInUTC(first, second uint64) bool {

View File

@@ -1629,7 +1629,7 @@ func (p *Parlia) getCurrentValidators(blockHash common.Hash, blockNum *big.Int)
return valSet, voteAddrMap, nil
}
// distributeIncoming distributes system incoming of the block
// slash spoiled validators
func (p *Parlia) distributeIncoming(val common.Address, state *state.StateDB, header *types.Header, chain core.ChainContext,
txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {
coinbase := header.Coinbase
@@ -1719,7 +1719,7 @@ func (p *Parlia) distributeToSystem(amount *big.Int, state *state.StateDB, heade
return p.applyTransaction(msg, state, header, chain, txs, receipts, receivedTxs, usedGas, mining)
}
// distributeToValidator deposits validator reward to validator contract
// slash spoiled validators
func (p *Parlia) distributeToValidator(amount *big.Int, validator common.Address,
state *state.StateDB, header *types.Header, chain core.ChainContext,
txs *[]*types.Transaction, receipts *[]*types.Receipt, receivedTxs *[]*types.Transaction, usedGas *uint64, mining bool) error {

View File

@@ -335,7 +335,7 @@ func ParseStateScheme(provided string, disk ethdb.Database) (string, error) {
if stored == "" {
// use default scheme for empty database, flip it when
// path mode is chosen as default
log.Info("State scheme set to default", "scheme", "hash")
log.Info("State schema set to default", "scheme", "hash")
return HashScheme, nil
}
log.Info("State scheme set to already existing disk db", "scheme", stored)

View File

@@ -129,8 +129,6 @@ func InspectFreezerTable(ancient string, freezerName string, tableName string, s
switch freezerName {
case chainFreezerName:
path, tables = resolveChainFreezerDir(ancient), chainFreezerNoSnappy
case stateFreezerName:
path, tables = filepath.Join(ancient, freezerName), stateFreezerNoSnappy
default:
return fmt.Errorf("unknown freezer, supported ones: %v", freezers)
}

View File

@@ -188,27 +188,19 @@ func (batch *freezerTableBatch) maybeCommit() error {
// commit writes the batched items to the backing freezerTable.
func (batch *freezerTableBatch) commit() error {
// Write data. The head file is fsync'd after write to ensure the
// data is truly transferred to disk.
// Write data.
_, err := batch.t.head.Write(batch.dataBuffer)
if err != nil {
return err
}
if err := batch.t.head.Sync(); err != nil {
return err
}
dataSize := int64(len(batch.dataBuffer))
batch.dataBuffer = batch.dataBuffer[:0]
// Write indices. The index file is fsync'd after write to ensure the
// data indexes are truly transferred to disk.
// Write indices.
_, err = batch.t.index.Write(batch.indexBuffer)
if err != nil {
return err
}
if err := batch.t.index.Sync(); err != nil {
return err
}
indexSize := int64(len(batch.indexBuffer))
batch.indexBuffer = batch.indexBuffer[:0]

View File

@@ -223,9 +223,7 @@ func (t *freezerTable) repair() error {
if t.readonly {
return fmt.Errorf("index file(path: %s, name: %s) size is not a multiple of %d", t.path, t.name, indexEntrySize)
}
if err := truncateFreezerFile(t.index, stat.Size()-overflow); err != nil {
return err
} // New file can't trigger this path
truncateFreezerFile(t.index, stat.Size()-overflow) // New file can't trigger this path
}
// Retrieve the file sizes and prepare for truncation
if stat, err = t.index.Stat(); err != nil {
@@ -270,8 +268,8 @@ func (t *freezerTable) repair() error {
// Print an error log if the index is corrupted due to an incorrect
// last index item. While it is theoretically possible to have a zero offset
// by storing all zero-size items, it is highly unlikely to occur in practice.
if lastIndex.offset == 0 && offsetsSize/indexEntrySize > 1 {
log.Error("Corrupted index file detected", "lastOffset", lastIndex.offset, "indexes", offsetsSize/indexEntrySize)
if lastIndex.offset == 0 && offsetsSize%indexEntrySize > 1 {
log.Error("Corrupted index file detected", "lastOffset", lastIndex.offset, "items", offsetsSize%indexEntrySize-1)
}
if t.readonly {
t.head, err = t.openFile(lastIndex.filenum, openFreezerFileForReadOnly)
@@ -426,9 +424,6 @@ func (t *freezerTable) truncateHead(items uint64) error {
if err := truncateFreezerFile(t.index, int64(length+1)*indexEntrySize); err != nil {
return err
}
if err := t.index.Sync(); err != nil {
return err
}
// Calculate the new expected size of the data file and truncate it
var expected indexEntry
if length == 0 {
@@ -451,7 +446,6 @@ func (t *freezerTable) truncateHead(items uint64) error {
// Release any files _after the current head -- both the previous head
// and any files which may have been opened for reading
t.releaseFilesAfter(expected.filenum, true)
// Set back the historic head
t.head = newHead
t.headId = expected.filenum
@@ -459,9 +453,6 @@ func (t *freezerTable) truncateHead(items uint64) error {
if err := truncateFreezerFile(t.head, int64(expected.offset)); err != nil {
return err
}
if err := t.head.Sync(); err != nil {
return err
}
// All data files truncated, set internal counters and return
t.headBytes = int64(expected.offset)
t.items.Store(items)
@@ -606,12 +597,10 @@ func (t *freezerTable) Close() error {
// error on Windows.
doClose(t.index, true, true)
doClose(t.meta, true, true)
// The preopened non-head data-files are all opened in readonly.
// The head is opened in rw-mode, so we sync it here - but since it's also
// part of t.files, it will be closed in the loop below.
doClose(t.head, true, false) // sync but do not close
for _, f := range t.files {
doClose(f, false, true) // close but do not sync
}

View File

@@ -73,7 +73,11 @@ func copyFrom(srcPath, destPath string, offset uint64, before func(f *os.File) e
return err
}
f = nil
return os.Rename(fname, destPath)
if err := os.Rename(fname, destPath); err != nil {
return err
}
return nil
}
// openFreezerFileForAppend opens a freezer table file and seeks to the end

File diff suppressed because one or more lines are too long

View File

@@ -233,7 +233,7 @@ var PrecompiledContractsFeynman = map[common.Address]PrecompiledContract{
common.BytesToAddress([]byte{2}): &sha256hash{},
common.BytesToAddress([]byte{3}): &ripemd160hash{},
common.BytesToAddress([]byte{4}): &dataCopy{},
common.BytesToAddress([]byte{5}): &bigModExp{eip2565: true},
common.BytesToAddress([]byte{5}): &bigModExp{},
common.BytesToAddress([]byte{6}): &bn256AddIstanbul{},
common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{},
common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{},
@@ -242,7 +242,7 @@ var PrecompiledContractsFeynman = map[common.Address]PrecompiledContract{
common.BytesToAddress([]byte{100}): &tmHeaderValidate{},
common.BytesToAddress([]byte{101}): &iavlMerkleProofValidatePlato{},
common.BytesToAddress([]byte{102}): &blsSignatureVerify{},
common.BytesToAddress([]byte{103}): &cometBFTLightBlockValidateHertz{},
common.BytesToAddress([]byte{103}): &cometBFTLightBlockValidate{},
common.BytesToAddress([]byte{104}): &verifyDoubleSignEvidence{},
common.BytesToAddress([]byte{105}): &secp256k1SignatureRecover{},
}

View File

@@ -408,23 +408,23 @@ func (c *secp256k1SignatureRecover) RequiredGas(input []byte) uint64 {
}
const (
secp256k1PubKeyLength uint8 = 33
secp256k1SignatureLength uint8 = 64
secp256k1SignatureMsgHashLength uint8 = 32
tmPubKeyLength uint8 = 33
tmSignatureLength uint8 = 64
tmSignatureMsgHashLength uint8 = 32
)
// input:
// | PubKey | Signature | SignatureMsgHash |
// | tmPubKey | tmSignature | tmSignatureMsgHash |
// | 33 bytes | 64 bytes | 32 bytes |
func (c *secp256k1SignatureRecover) Run(input []byte) (result []byte, err error) {
if len(input) != int(secp256k1PubKeyLength)+int(secp256k1SignatureLength)+int(secp256k1SignatureMsgHashLength) {
if len(input) != int(tmPubKeyLength)+int(tmSignatureLength)+int(tmSignatureMsgHashLength) {
return nil, fmt.Errorf("invalid input")
}
return c.runTMSecp256k1Signature(
input[:secp256k1PubKeyLength],
input[secp256k1PubKeyLength:secp256k1PubKeyLength+secp256k1SignatureLength],
input[secp256k1PubKeyLength+secp256k1SignatureLength:],
input[:tmPubKeyLength],
input[tmPubKeyLength:tmPubKeyLength+tmSignatureLength],
input[tmPubKeyLength+tmSignatureLength:],
)
}

View File

@@ -411,7 +411,7 @@ func TestDoubleSignSlash(t *testing.T) {
tc := precompiledTest{
Input: "f906278202cab9030ff9030ca01062d3d5015b9242bc193a9b0769f3d3780ecb55f97f40a752ae26d0b68cd0d8a0fae1a05fcb14bfd9b8a9f2b65007a9b6c2000de0627a73be644dd993d32342c494976ea74026e726554db657fa54763abd0c3a0aa9a0f385cc58ed297ff0d66eb5580b02853d3478ba418b1819ac659ee05df49b9794a0bf88464af369ed6b8cf02db00f0b9556ffa8d49cd491b00952a7f83431446638a00a6d0870e586a76278fbfdcedf76ef6679af18fc1f9137cfad495f434974ea81b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001820cdf830f4240830f4240846555fa64b90111d983010301846765746888676f312e32302e378664617277696e00007abd731ef8ae07b86091cb8836d58f5444b883422a18825d899035d3e6ea39ad1a50069bf0b86da8b5573dde1cb4a0a34f19ce94e0ef78ff7518c80265b8a3ca56e3c60167523590d4e8dcc324900559465fc0fa403774096614e135de280949b58a45cc96f2ba9e17f848820d41a08429d0d8b33ee72a84f750fefea846cbca54e487129c7961c680bb72309ca888820d42a08c9db14d938b19f9e2261bbeca2679945462be2b58103dfff73665d0d150fb8a804ae755e0fe64b59753f4db6308a1f679747bce186aa2c62b95fa6eeff3fbd08f3b0667e45428a54ade15bad19f49641c499b431b36f65803ea71b379e6b61de501a0232c9ba2d41b40d36ed794c306747bcbc49bf61a0f37409c18bfe2b5bef26a2d880000000000000000b9030ff9030ca01062d3d5015b9242bc193a9b0769f3d3780ecb55f97f40a752ae26d0b68cd0d8a0b2789a5357827ed838335283e15c4dcc42b9bebcbf2919a18613246787e2f96094976ea74026e726554db657fa54763abd0c3a0aa9a071ce4c09ee275206013f0063761bc19c93c13990582f918cc57333634c94ce89a00e095703e5c9b149f253fe89697230029e32484a410b4b1f2c61442d73c3095aa0d317ae19ede7c8a2d3ac9ef98735b049bcb7278d12f48c42b924538b60a25e12b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001820cdf830f4240830f4240846555fa64b90111d983010301846765746888676f312e32302e378664617277696e00007abd731ef8ae07b86091cb8836d58f5444b883422a18825d899035d3e6ea39ad1a50069bf0b86da8b5573dde1cb4a0a34f19ce94e0ef78ff7518c80265b8a3ca56e3c60167523590d4e8dcc324900559465fc0fa403774096614e135de280949b58a45cc96f2ba9e17f848820d41a08429d0d8b33ee72a84f750fefea846cbca54e487129c7961c680bb72309ca888820d42a08c9db14d938b19f9e2261bbeca2679945462be2b58103dfff73665d0d150fb8a80c0b17bfe88534296ff064cb7156548f6deba2d6310d5044ed6485f087dc6ef232e051c28e1909c2b50a3b4f29345d66681c319bef653e52e5d746480d5a3983b00a0b56228685be711834d0f154292d07826dea42a0fad3e4f56c31470b7fbfbea26880000000000000000",
Expected: "15d34aaf54267db7d7c367839aaf71a00a2c6a650000000000000000000000000000000000000000000000000000000000000cdf",
Gas: 10000,
Gas: 1000,
Name: "",
}

View File

@@ -338,7 +338,7 @@ func (f *TxFetcher) Enqueue(peer string, txs []*types.Transaction, direct bool)
// If 'other reject' is >25% of the deliveries in any batch, sleep a bit.
if otherreject > 128/4 {
time.Sleep(200 * time.Millisecond)
log.Debug("Peer delivering stale transactions", "peer", peer, "rejected", otherreject)
log.Warn("Peer delivering stale transactions", "peer", peer, "rejected", otherreject)
}
}
select {

View File

@@ -227,8 +227,8 @@ func (oracle *Oracle) FeeHistory(ctx context.Context, blocks uint64, unresolvedL
if p < 0 || p > 100 {
return common.Big0, nil, nil, nil, fmt.Errorf("%w: %f", errInvalidPercentile, p)
}
if i > 0 && p <= rewardPercentiles[i-1] {
return common.Big0, nil, nil, nil, fmt.Errorf("%w: #%d:%f >= #%d:%f", errInvalidPercentile, i-1, rewardPercentiles[i-1], i, p)
if i > 0 && p < rewardPercentiles[i-1] {
return common.Big0, nil, nil, nil, fmt.Errorf("%w: #%d:%f > #%d:%f", errInvalidPercentile, i-1, rewardPercentiles[i-1], i, p)
}
}
var (

View File

@@ -10,8 +10,6 @@ import (
"time"
)
const backupTimeFormat = "2006-01-02_15"
type TimeTicker struct {
stop chan struct{}
C <-chan time.Time
@@ -71,24 +69,19 @@ type AsyncFileWriter struct {
buf chan []byte
stop chan struct{}
timeTicker *TimeTicker
rotateHours uint
maxBackups int
}
func NewAsyncFileWriter(filePath string, maxBytesSize int64, maxBackups int, rotateHours uint) *AsyncFileWriter {
func NewAsyncFileWriter(filePath string, maxBytesSize int64, rotateHours uint) *AsyncFileWriter {
absFilePath, err := filepath.Abs(filePath)
if err != nil {
panic(fmt.Sprintf("get file path of logger error. filePath=%s, err=%s", filePath, err))
}
return &AsyncFileWriter{
filePath: absFilePath,
buf: make(chan []byte, maxBytesSize),
stop: make(chan struct{}),
rotateHours: rotateHours,
maxBackups: maxBackups,
timeTicker: NewTimeTicker(rotateHours),
filePath: absFilePath,
buf: make(chan []byte, maxBytesSize),
stop: make(chan struct{}),
timeTicker: NewTimeTicker(rotateHours),
}
}
@@ -185,9 +178,6 @@ func (w *AsyncFileWriter) rotateFile() {
if err := w.initLogFile(); err != nil {
fmt.Fprintf(os.Stderr, "init log file error. err=%s", err)
}
if err := w.removeExpiredFile(); err != nil {
fmt.Fprintf(os.Stderr, "remove expired file error. err=%s", err)
}
default:
}
}
@@ -232,29 +222,5 @@ func (w *AsyncFileWriter) flushAndClose() error {
}
func (w *AsyncFileWriter) timeFilePath(filePath string) string {
return filePath + "." + time.Now().Format(backupTimeFormat)
}
func (w *AsyncFileWriter) getExpiredFile(filePath string, maxBackups int, rotateHours uint) string {
if rotateHours > 0 {
maxBackups = int(rotateHours) * maxBackups
}
return filePath + "." + time.Now().Add(-time.Hour*time.Duration(maxBackups)).Format(backupTimeFormat)
}
func (w *AsyncFileWriter) removeExpiredFile() error {
if w.maxBackups == 0 {
return nil
}
oldFilepath := w.getExpiredFile(w.filePath, w.maxBackups, w.rotateHours)
_, err := os.Stat(oldFilepath)
if os.IsNotExist(err) {
return nil
}
errRemove := os.Remove(oldFilepath)
if err != nil {
return errRemove
}
return err
return filePath + "." + time.Now().Format("2006-01-02_15")
}

View File

@@ -6,12 +6,10 @@ import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestWriterHourly(t *testing.T) {
w := NewAsyncFileWriter("./hello.log", 100, 1, 1)
w := NewAsyncFileWriter("./hello.log", 100, 1)
w.Start()
w.Write([]byte("hello\n"))
w.Write([]byte("world\n"))
@@ -69,22 +67,3 @@ func TestGetNextRotationHour(t *testing.T) {
t.Run("TestGetNextRotationHour_"+strconv.Itoa(i), test(tc.now, tc.delta, tc.expectedHour))
}
}
func TestClearBackups(t *testing.T) {
dir := "./test"
os.Mkdir(dir, 0700)
w := NewAsyncFileWriter("./test/bsc.log", 100, 1, 1)
defer os.RemoveAll(dir)
fakeCurrentTime := time.Now()
name := ""
data := []byte("data")
for i := 0; i < 5; i++ {
name = w.filePath + "." + fakeCurrentTime.Format(backupTimeFormat)
_ = os.WriteFile(name, data, 0700)
fakeCurrentTime = fakeCurrentTime.Add(-time.Hour * 1)
}
oldFile := w.getExpiredFile(w.filePath, w.maxBackups, w.rotateHours)
w.removeExpiredFile()
_, err := os.Stat(oldFile)
assert.True(t, os.IsNotExist(err))
}

View File

@@ -75,14 +75,14 @@ func FileHandler(path string, fmtr Format) (Handler, error) {
// RotatingFileHandler returns a handler which writes log records to file chunks
// at the given path. When a file's size reaches the limit, the handler creates
// a new file named after the timestamp of the first log record it will contain.
func RotatingFileHandler(filePath string, limit uint, maxBackups uint, formatter Format, rotateHours uint) (Handler, error) {
func RotatingFileHandler(filePath string, limit uint, formatter Format, rotateHours uint) (Handler, error) {
if _, err := os.Stat(path.Dir(filePath)); os.IsNotExist(err) {
err := os.MkdirAll(path.Dir(filePath), 0755)
if err != nil {
return nil, fmt.Errorf("could not create directory %s, %v", path.Dir(filePath), err)
}
}
fileWriter := NewAsyncFileWriter(filePath, int64(limit), int(maxBackups), rotateHours)
fileWriter := NewAsyncFileWriter(filePath, int64(limit), rotateHours)
fileWriter.Start()
return StreamHandler(fileWriter, formatter), nil
}

View File

@@ -290,8 +290,8 @@ func (c Ctx) toArray() []interface{} {
return arr
}
func NewFileLvlHandler(logPath string, maxBytesSize uint, maxBackups uint, level string, rotateHours uint) Handler {
rfh, err := RotatingFileHandler(logPath, maxBytesSize, maxBackups, LogfmtFormat(), rotateHours)
func NewFileLvlHandler(logPath string, maxBytesSize uint, level string, rotateHours uint) Handler {
rfh, err := RotatingFileHandler(logPath, maxBytesSize, LogfmtFormat(), rotateHours)
if err != nil {
panic(err)
}

View File

@@ -513,7 +513,6 @@ type LogConfig struct {
MaxBytesSize *uint `toml:",omitempty"`
Level *string `toml:",omitempty"`
RotateHours *uint `toml:",omitempty"`
MaxBackups *uint `toml:",omitempty"`
// TermTimeFormat is the time format used for console logging.
TermTimeFormat *string `toml:",omitempty"`

View File

@@ -118,12 +118,7 @@ func New(conf *Config) (*Node, error) {
rotateHours = *conf.LogConfig.RotateHours
}
maxBackups := uint(0)
if conf.LogConfig.MaxBackups != nil {
maxBackups = *conf.LogConfig.MaxBackups
}
log.Root().SetHandler(log.NewFileLvlHandler(logFilePath, *conf.LogConfig.MaxBytesSize, maxBackups, *conf.LogConfig.Level, rotateHours))
log.Root().SetHandler(log.NewFileLvlHandler(logFilePath, *conf.LogConfig.MaxBytesSize, *conf.LogConfig.Level, rotateHours))
}
}
if conf.Logger == nil {

View File

@@ -186,7 +186,9 @@ var (
// UnixTime: 1702972800 is December 19, 2023 8:00:00 AM UTC
ShanghaiTime: newUint64(1702972800),
KeplerTime: newUint64(1702972800),
FeynmanTime: newUint64(1710136800),
// TODO
FeynmanTime: nil,
Parlia: &ParliaConfig{
Period: 3,

View File

@@ -135,16 +135,16 @@ const (
IAVLMerkleProofValidateGas uint64 = 3000 // Gas for validate merkle proof
CometBFTLightBlockValidateGas uint64 = 3000 // Gas for validate cometBFT light block
EcrecoverGas uint64 = 3000 // Elliptic curve sender recovery gas price
Sha256BaseGas uint64 = 60 // Base price for a SHA256 operation
Sha256PerWordGas uint64 = 12 // Per-word price for a SHA256 operation
Ripemd160BaseGas uint64 = 600 // Base price for a RIPEMD160 operation
Ripemd160PerWordGas uint64 = 120 // Per-word price for a RIPEMD160 operation
IdentityBaseGas uint64 = 15 // Base price for a data copy operation
IdentityPerWordGas uint64 = 3 // Per-work price for a data copy operation
BlsSignatureVerifyBaseGas uint64 = 1000 // base price for a BLS signature verify operation
BlsSignatureVerifyPerKeyGas uint64 = 3500 // Per-key price for a BLS signature verify operation
DoubleSignEvidenceVerifyGas uint64 = 10000 // Gas for verify double sign evidence
EcrecoverGas uint64 = 3000 // Elliptic curve sender recovery gas price
Sha256BaseGas uint64 = 60 // Base price for a SHA256 operation
Sha256PerWordGas uint64 = 12 // Per-word price for a SHA256 operation
Ripemd160BaseGas uint64 = 600 // Base price for a RIPEMD160 operation
Ripemd160PerWordGas uint64 = 120 // Per-word price for a RIPEMD160 operation
IdentityBaseGas uint64 = 15 // Base price for a data copy operation
IdentityPerWordGas uint64 = 3 // Per-work price for a data copy operation
BlsSignatureVerifyBaseGas uint64 = 1000 // base price for a BLS signature verify operation
BlsSignatureVerifyPerKeyGas uint64 = 3500 // Per-key price for a BLS signature verify operation
DoubleSignEvidenceVerifyGas uint64 = 1000 // Gas for verify double sign evidence
Bn256AddGasByzantium uint64 = 500 // Byzantium gas needed for an elliptic curve addition
Bn256AddGasIstanbul uint64 = 150 // Gas needed for an elliptic curve addition

View File

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