Skip to content

Commit 0e2fae5

Browse files
committed
* main to dev branch (#1) * zjubfd: add no trie options, support fastnode * no truncate * add prune path db * fix destruction error * update parallel param * fix possible prefetch panic * protect from nil root * add the cache size of code * mute unnecessary log * Dev (OffchainLabs#4) * add initial commit of trade * fix root 00 issue * refine the sync to target * refine the sync to target * add tg bots and more * update gas price for test mode * refine the order update * refine the order update * refine fee calculate * update * update * update * update * update * update * update * update better tg message * add pair price track * update test case * add webscoket * decouple trade module * extract seracher as a processer * update trade * add executor wallets * update * remove duplicate ws * add prefetch routine * update v2 calculation method * add test code * add test code * add test code * add crypty code * update some test log * update some test log * update some test log * update some test log * update some test log * update some test log * update * support limit order
1 parent fe26733 commit 0e2fae5

39 files changed

+881
-235
lines changed

.gitignore

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@
3030
/geth*.zip.sig
3131
/geth*.zip.asc
3232

33+
./trade/binance_test.go
34+
trade/binance_test.go
35+
trade/crypto_test.go
36+
trade/config/config.json
37+
trade/txhistory.md
38+
trade/pair_executor_test.go
39+
trade/network-info.md
40+
trade/metrics/*
41+
3342

3443
# travis
3544
profile.tmp
@@ -43,3 +52,4 @@ profile.cov
4352
.vscode
4453

4554
tests/spec-tests/
55+
trade/config/config copy.json

Makefile

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# with Go source code. If you know what GOPATH is then you probably
33
# don't need to bother with make.
44

5-
.PHONY: geth all test lint fmt clean devtools help
5+
.PHONY: geth searcher all test lint fmt clean devtools help
66

77
GOBIN = ./build/bin
88
GO ?= latest
@@ -14,6 +14,12 @@ geth:
1414
@echo "Done building."
1515
@echo "Run \"$(GOBIN)/geth\" to launch geth."
1616

17+
#? searcher: Build the MEV searcher.
18+
searcher:
19+
$(GORUN) build/ci.go install ./cmd/searcher
20+
@echo "Done building."
21+
@echo "Run \"$(GOBIN)/searcher\" to launch the MEV searcher."
22+
1723
#? all: Build all packages and executables.
1824
all:
1925
$(GORUN) build/ci.go install

accounts/abi/bind/base.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,10 +334,13 @@ func (c *BoundContract) createDynamicTx(opts *TransactOpts, contract *common.Add
334334
gasLimit := opts.GasLimit
335335
if opts.GasLimit == 0 {
336336
var err error
337+
// TODO 这里给一个合适的gas limit, 防止迭代次数太多
337338
gasLimit, err = c.estimateGasLimit(opts, contract, input, nil, gasTipCap, gasFeeCap, value)
338339
if err != nil {
339340
return nil, err
340341
}
342+
// TODO 需要优化
343+
gasLimit = gasLimit * 3 / 2
341344
}
342345
// create the transaction
343346
nonce, err := c.getNonce(opts)
@@ -409,8 +412,10 @@ func (c *BoundContract) estimateGasLimit(opts *TransactOpts, contract *common.Ad
409412
return 0, ErrNoCode
410413
}
411414
}
415+
// Note: 这里给一个比较小的的gas limit, 防止迭代次数太多
412416
msg := ethereum.CallMsg{
413417
From: opts.From,
418+
Gas: 1000000,
414419
To: contract,
415420
GasPrice: gasPrice,
416421
GasTipCap: gasTipCap,

cmd/geth/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ var (
8080
utils.BlobPoolDataCapFlag,
8181
utils.BlobPoolPriceBumpFlag,
8282
utils.SyncModeFlag,
83+
utils.TriesNoVerifyFlag,
8384
utils.SyncTargetFlag,
8485
utils.ExitWhenSyncedFlag,
8586
utils.GCModeFlag,
@@ -256,6 +257,7 @@ func init() {
256257
debug.Flags,
257258
metricsFlags,
258259
)
260+
259261
flags.AutoEnvVars(app.Flags, "GETH")
260262

261263
app.Before = func(ctx *cli.Context) error {

cmd/geth/snapshot.go

Lines changed: 124 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ package main
1818

1919
import (
2020
"bytes"
21+
"encoding/binary"
2122
"encoding/json"
2223
"errors"
2324
"fmt"
25+
"math"
2426
"os"
2527
"slices"
2628
"time"
@@ -33,6 +35,7 @@ import (
3335
"github.com/ethereum/go-ethereum/core/state/snapshot"
3436
"github.com/ethereum/go-ethereum/core/types"
3537
"github.com/ethereum/go-ethereum/crypto"
38+
"github.com/ethereum/go-ethereum/ethdb"
3639
"github.com/ethereum/go-ethereum/log"
3740
"github.com/ethereum/go-ethereum/rlp"
3841
"github.com/ethereum/go-ethereum/trie"
@@ -63,6 +66,29 @@ two version states are available: genesis and the specific one.
6366
The default pruning target is the HEAD-127 state.
6467
6568
WARNING: it's only supported in hash mode(--state.scheme=hash)".
69+
`,
70+
},
71+
{
72+
Name: "insecure-prune-pathdb",
73+
Usage: "Prune all pathdb state data, it will break storage for fullnode, only suitable for fast node " +
74+
"who do not need trie storage at all",
75+
ArgsUsage: "",
76+
Action: prunePathDB,
77+
Category: "MISCELLANEOUS COMMANDS",
78+
Flags: []cli.Flag{
79+
utils.DataDirFlag,
80+
utils.AncientFlag,
81+
},
82+
Description: `
83+
will prune all historical trie state data except genesis block.
84+
All trie nodes will be deleted from the database.
85+
86+
It expects the genesis file as argument.
87+
88+
WARNING: It's necessary to delete the trie clean cache after the pruning.
89+
If you specify another directory for the trie clean cache via "--cache.trie.journal"
90+
during the use of Geth, please also specify it here for correct deletion. Otherwise
91+
the trie clean cache with default directory will be deleted.
6692
`,
6793
},
6894
{
@@ -165,6 +191,101 @@ the expected order for the overlay tree migration.
165191
}
166192
)
167193

194+
// rangeCompactionThreshold is the minimal deleted entry number for
195+
// triggering range compaction. It's a quite arbitrary number but just
196+
// to avoid triggering range compaction because of small deletion.
197+
const rangeCompactionThreshold = 1000000
198+
199+
func prunePathDB(ctx *cli.Context) error {
200+
stack, _ := makeConfigNode(ctx)
201+
defer stack.Close()
202+
203+
pruneDB := utils.MakeChainDatabase(ctx, stack, false)
204+
defer pruneDB.Close()
205+
206+
var (
207+
count int
208+
size common.StorageSize
209+
pstart = time.Now()
210+
logged = time.Now()
211+
batch = pruneDB.NewBatch()
212+
iter = pruneDB.NewIterator(nil, nil)
213+
stateIDPrefix = []byte("L")
214+
)
215+
for iter.Next() {
216+
key := iter.Key()
217+
doDelete := false
218+
switch {
219+
case rawdb.IsLegacyTrieNode(key, iter.Value()):
220+
doDelete = true
221+
case bytes.HasPrefix(key, stateIDPrefix) && len(key) == len(stateIDPrefix)+common.HashLength:
222+
doDelete = true
223+
case rawdb.IsAccountTrieNode(key):
224+
doDelete = true
225+
case rawdb.IsStorageTrieNode(key):
226+
doDelete = true
227+
default:
228+
}
229+
if doDelete {
230+
count += 1
231+
size += common.StorageSize(len(key) + len(iter.Value()))
232+
batch.Delete(key)
233+
234+
var eta time.Duration // Realistically will never remain uninited
235+
if done := binary.BigEndian.Uint64(key[:8]); done > 0 {
236+
var (
237+
left = math.MaxUint64 - binary.BigEndian.Uint64(key[:8])
238+
speed = done/uint64(time.Since(pstart)/time.Millisecond+1) + 1 // +1s to avoid division by zero
239+
)
240+
eta = time.Duration(left/speed) * time.Millisecond
241+
}
242+
if time.Since(logged) > 8*time.Second {
243+
log.Info("Pruning state data", "nodes", count, "size", size,
244+
"elapsed", common.PrettyDuration(time.Since(pstart)), "eta", common.PrettyDuration(eta))
245+
logged = time.Now()
246+
}
247+
// Recreate the iterator after every batch commit in order
248+
// to allow the underlying compactor to delete the entries.
249+
if batch.ValueSize() >= ethdb.IdealBatchSize {
250+
batch.Write()
251+
batch.Reset()
252+
253+
iter.Release()
254+
iter = pruneDB.NewIterator(nil, key)
255+
}
256+
}
257+
}
258+
if batch.ValueSize() > 0 {
259+
batch.Write()
260+
batch.Reset()
261+
}
262+
iter.Release()
263+
log.Info("Pruned path db data", "nodes", count, "size", size, "elapsed", common.PrettyDuration(time.Since(pstart)))
264+
265+
// Start compactions, will remove the deleted data from the disk immediately.
266+
// Note for small pruning, the compaction is skipped.
267+
if count >= rangeCompactionThreshold {
268+
cstart := time.Now()
269+
for b := 0x00; b <= 0xf0; b += 0x10 {
270+
var (
271+
start = []byte{byte(b)}
272+
end = []byte{byte(b + 0x10)}
273+
)
274+
if b == 0xf0 {
275+
end = nil
276+
}
277+
log.Info("Compacting database", "range", fmt.Sprintf("%#x-%#x", start, end), "elapsed", common.PrettyDuration(time.Since(cstart)))
278+
if err := pruneDB.Compact(start, end); err != nil {
279+
log.Error("Database compaction failed", "error", err)
280+
return err
281+
}
282+
}
283+
log.Info("Database compaction finished", "elapsed", common.PrettyDuration(time.Since(cstart)))
284+
}
285+
286+
return nil
287+
}
288+
168289
// Deprecation: this command should be deprecated once the hash-based
169290
// scheme is deprecated.
170291
func pruneState(ctx *cli.Context) error {
@@ -230,7 +351,7 @@ func verifyState(ctx *cli.Context) error {
230351
NoBuild: true,
231352
AsyncBuild: false,
232353
}
233-
snaptree, err := snapshot.New(snapConfig, chaindb, triedb, headBlock.Root())
354+
snaptree, err := snapshot.New(snapConfig, chaindb, triedb, headBlock.Root(), false)
234355
if err != nil {
235356
log.Error("Failed to open snapshot tree", "err", err)
236357
return err
@@ -561,7 +682,7 @@ func dumpState(ctx *cli.Context) error {
561682
NoBuild: true,
562683
AsyncBuild: false,
563684
}
564-
snaptree, err := snapshot.New(snapConfig, db, triedb, root)
685+
snaptree, err := snapshot.New(snapConfig, db, triedb, root, false)
565686
if err != nil {
566687
return err
567688
}
@@ -658,7 +779,7 @@ func snapshotExportPreimages(ctx *cli.Context) error {
658779
NoBuild: true,
659780
AsyncBuild: false,
660781
}
661-
snaptree, err := snapshot.New(snapConfig, chaindb, triedb, root)
782+
snaptree, err := snapshot.New(snapConfig, chaindb, triedb, root, false)
662783
if err != nil {
663784
return err
664785
}

cmd/utils/flags.go

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,13 @@ var (
222222
Usage: "Reduce key-derivation RAM & CPU usage at some expense of KDF strength",
223223
Category: flags.AccountCategory,
224224
}
225+
226+
TriesNoVerifyFlag = &cli.BoolFlag{
227+
Name: "tries-no-verify",
228+
Usage: "no merkle state root verification at all",
229+
Category: flags.FastNodeCategory,
230+
}
231+
225232
EthRequiredBlocksFlag = &cli.StringFlag{
226233
Name: "eth.requiredblocks",
227234
Usage: "Comma separated block number-to-hash mappings to require for peering (<number>=<hash>)",
@@ -901,7 +908,6 @@ Please note that --` + MetricsHTTPFlag.Name + ` must be set to start the server.
901908
Value: metrics.DefaultConfig.InfluxDBTags,
902909
Category: flags.MetricsCategory,
903910
}
904-
905911
MetricsEnableInfluxDBV2Flag = &cli.BoolFlag{
906912
Name: "metrics.influxdbv2",
907913
Usage: "Enable metrics export/push to an external InfluxDB v2 database",
@@ -928,6 +934,23 @@ Please note that --` + MetricsHTTPFlag.Name + ` must be set to start the server.
928934
Value: metrics.DefaultConfig.InfluxDBOrganization,
929935
Category: flags.MetricsCategory,
930936
}
937+
938+
// Searcher flag group
939+
SearcherEnabledFlag = &cli.BoolFlag{
940+
Name: "searcher",
941+
Usage: "Enable MEV searcher functionality",
942+
Category: flags.EthCategory,
943+
}
944+
SearcherConfigFlag = &cli.StringFlag{
945+
Name: "searcher.config",
946+
Usage: "Path to the searcher configuration file",
947+
Category: flags.EthCategory,
948+
}
949+
SearcherDecryptKeyFlag = &cli.StringFlag{
950+
Name: "searcher.decryptkey-password",
951+
Usage: "Password for deriving searcher decryption key (will be securely hashed to generate a 32-byte key)",
952+
Category: flags.EthCategory,
953+
}
931954
)
932955

933956
var (
@@ -1621,6 +1644,9 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
16211644
cfg.StateScheme = rawdb.HashScheme
16221645
log.Warn("Forcing hash state-scheme for archive mode")
16231646
}
1647+
if ctx.IsSet(TriesNoVerifyFlag.Name) {
1648+
cfg.TriesNoVerify = ctx.Bool(TriesNoVerifyFlag.Name)
1649+
}
16241650
if ctx.IsSet(CacheFlag.Name) || ctx.IsSet(CacheTrieFlag.Name) {
16251651
cfg.TrieCleanCache = ctx.Int(CacheFlag.Name) * ctx.Int(CacheTrieFlag.Name) / 100
16261652
}

0 commit comments

Comments
 (0)