Skip to content

Commit 92e21cc

Browse files
committed
fix testcase and lint
make diff block configable wait code write fix testcase resolve comments resolve comment
1 parent 1fbecfa commit 92e21cc

35 files changed

+159
-302
lines changed

cmd/faucet/faucet.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ func main() {
139139
log.Crit("Length of bep2eContracts, bep2eSymbols, bep2eAmounts mismatch")
140140
}
141141

142-
bep2eInfos := make(map[string]bep2eInfo, 0)
142+
bep2eInfos := make(map[string]bep2eInfo, len(symbols))
143143
for idx, s := range symbols {
144144
n, ok := big.NewInt(0).SetString(bep2eNumAmounts[idx], 10)
145145
if !ok {
@@ -148,7 +148,7 @@ func main() {
148148
amountStr := big.NewFloat(0).Quo(big.NewFloat(0).SetInt(n), big.NewFloat(0).SetInt64(params.Ether)).String()
149149

150150
bep2eInfos[s] = bep2eInfo{
151-
Contract: common.HexToAddress(contracts[idx]),
151+
Contract: common.HexToAddreparlia.goss(contracts[idx]),
152152
Amount: *n,
153153
AmountStr: amountStr,
154154
}

cmd/geth/main.go

+1
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ var (
117117
utils.CacheSnapshotFlag,
118118
utils.CachePreimagesFlag,
119119
utils.PersistDiffFlag,
120+
utils.DiffBlockFlag,
120121
utils.ListenPortFlag,
121122
utils.MaxPeersFlag,
122123
utils.MaxPendingPeersFlag,

cmd/utils/flags.go

+8
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,11 @@ var (
442442
Name: "persistdiff",
443443
Usage: "Enable persistence of the diff layer",
444444
}
445+
DiffBlockFlag = cli.Uint64Flag{
446+
Name: "diffblock",
447+
Usage: "The number of blocks should be persisted in db (default = 864000 )",
448+
Value: uint64(864000),
449+
}
445450
// Miner settings
446451
MiningEnabledFlag = cli.BoolFlag{
447452
Name: "mine",
@@ -1590,6 +1595,9 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
15901595
if ctx.GlobalIsSet(PersistDiffFlag.Name) {
15911596
cfg.PersistDiff = ctx.GlobalBool(PersistDiffFlag.Name)
15921597
}
1598+
if ctx.GlobalIsSet(DiffBlockFlag.Name) {
1599+
cfg.DiffBlock = ctx.GlobalUint64(DiffBlockFlag.Name)
1600+
}
15931601
if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
15941602
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
15951603
}

consensus/parlia/parlia.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -800,8 +800,9 @@ func (p *Parlia) Delay(chain consensus.ChainReader, header *types.Header) *time.
800800
}
801801
delay := p.delayForRamanujanFork(snap, header)
802802
// The blocking time should be no more than half of period
803-
if delay > time.Duration(p.config.Period)*time.Second/2 {
804-
delay = time.Duration(p.config.Period) * time.Second / 2
803+
half := time.Duration(p.config.Period) * time.Second / 2
804+
if delay > half {
805+
delay = half
805806
}
806807
return &delay
807808
}
@@ -895,7 +896,6 @@ func (p *Parlia) AllowLightProcess(chain consensus.ChainReader, currentHeader *t
895896
idx := snap.indexOfVal(p.val)
896897
// validator is not allowed to diff sync
897898
return idx < 0
898-
899899
}
900900

901901
func (p *Parlia) IsLocalBlock(header *types.Header) bool {

consensus/parlia/ramanujanfork.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ func (p *Parlia) delayForRamanujanFork(snap *Snapshot, header *types.Header) tim
2121
if header.Difficulty.Cmp(diffNoTurn) == 0 {
2222
// It's not our turn explicitly to sign, delay it a bit
2323
wiggle := time.Duration(len(snap.Validators)/2+1) * wiggleTimeBeforeFork
24-
delay += time.Duration(fixedBackOffTimeBeforeFork) + time.Duration(rand.Int63n(int64(wiggle)))
24+
delay += fixedBackOffTimeBeforeFork + time.Duration(rand.Int63n(int64(wiggle)))
2525
}
2626
return delay
2727
}

consensus/parlia/snapshot.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ func (s *Snapshot) enoughDistance(validator common.Address, header *types.Header
256256
if validator == header.Coinbase {
257257
return false
258258
}
259-
offset := (int64(s.Number) + 1) % int64(validatorNum)
259+
offset := (int64(s.Number) + 1) % validatorNum
260260
if int64(idx) >= offset {
261261
return int64(idx)-offset >= validatorNum-2
262262
} else {

core/blockchain.go

+26-21
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,6 @@ const (
9191
maxBeyondBlocks = 2048
9292

9393
diffLayerFreezerRecheckInterval = 3 * time.Second
94-
diffLayerFreezerBlockLimit = 864000 // The number of diff layers that should be kept in disk.
9594
diffLayerPruneRecheckInterval = 1 * time.Second // The interval to prune unverified diff layers
9695
maxDiffQueueDist = 2048 // Maximum allowed distance from the chain head to queue diffLayers
9796
maxDiffLimit = 2048 // Maximum number of unique diff layers a peer may have responded
@@ -213,9 +212,11 @@ type BlockChain struct {
213212
futureBlocks *lru.Cache // future blocks are blocks added for later processing
214213

215214
// trusted diff layers
216-
diffLayerCache *lru.Cache // Cache for the diffLayers
217-
diffLayerRLPCache *lru.Cache // Cache for the rlp encoded diffLayers
218-
diffQueue *prque.Prque // A Priority queue to store recent diff layer
215+
diffLayerCache *lru.Cache // Cache for the diffLayers
216+
diffLayerRLPCache *lru.Cache // Cache for the rlp encoded diffLayers
217+
diffQueue *prque.Prque // A Priority queue to store recent diff layer
218+
diffQueueBuffer chan *types.DiffLayer
219+
diffLayerFreezerBlockLimit uint64
219220

220221
// untrusted diff layers
221222
diffMux sync.RWMutex
@@ -285,6 +286,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
285286
engine: engine,
286287
vmConfig: vmConfig,
287288
diffQueue: prque.New(nil),
289+
diffQueueBuffer: make(chan *types.DiffLayer),
288290
blockHashToDiffLayers: make(map[common.Hash]map[common.Hash]*types.DiffLayer),
289291
diffHashToBlockHash: make(map[common.Hash]common.Hash),
290292
diffHashToPeers: make(map[common.Hash]map[string]struct{}),
@@ -444,7 +446,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
444446
}
445447
// Need persist and prune diff layer
446448
if bc.db.DiffStore() != nil {
447-
go bc.trustedDiffLayerFreezeLoop()
449+
go bc.trustedDiffLayerLoop()
448450
}
449451
go bc.untrustedDiffLayerPruneLoop()
450452

@@ -464,7 +466,7 @@ func (bc *BlockChain) cacheDiffLayer(diffLayer *types.DiffLayer) {
464466
bc.diffLayerCache.Add(diffLayer.BlockHash, diffLayer)
465467
if bc.db.DiffStore() != nil {
466468
// push to priority queue before persisting
467-
bc.diffQueue.Push(diffLayer, -(int64(diffLayer.Number)))
469+
bc.diffQueueBuffer <- diffLayer
468470
}
469471
}
470472

@@ -967,7 +969,7 @@ func (bc *BlockChain) GetDiffLayerRLP(blockHash common.Hash) rlp.RawValue {
967969
}
968970
rawData := rawdb.ReadDiffLayerRLP(diffStore, blockHash)
969971
if len(rawData) != 0 {
970-
bc.diffLayerRLPCache.Add(blockHash, rlp.RawValue(rawData))
972+
bc.diffLayerRLPCache.Add(blockHash, rawData)
971973
}
972974
return rawData
973975
}
@@ -2009,8 +2011,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, er
20092011
storageUpdateTimer.Update(statedb.StorageUpdates) // Storage updates are complete, we can mark them
20102012
snapshotAccountReadTimer.Update(statedb.SnapshotAccountReads) // Account reads are complete, we can mark them
20112013
snapshotStorageReadTimer.Update(statedb.SnapshotStorageReads) // Storage reads are complete, we can mark them
2012-
trieproc := statedb.SnapshotAccountReads + statedb.AccountReads + statedb.AccountUpdates
2013-
trieproc += statedb.SnapshotStorageReads + statedb.StorageReads + statedb.StorageUpdates
20142014

20152015
blockExecutionTimer.Update(time.Since(substart))
20162016

@@ -2401,12 +2401,14 @@ func (bc *BlockChain) update() {
24012401
}
24022402
}
24032403

2404-
func (bc *BlockChain) trustedDiffLayerFreezeLoop() {
2404+
func (bc *BlockChain) trustedDiffLayerLoop() {
24052405
recheck := time.Tick(diffLayerFreezerRecheckInterval)
24062406
bc.wg.Add(1)
24072407
defer bc.wg.Done()
24082408
for {
24092409
select {
2410+
case diff := <-bc.diffQueueBuffer:
2411+
bc.diffQueue.Push(diff, -(int64(diff.Number)))
24102412
case <-bc.quit:
24112413
// Persist all diffLayers when shutdown, it will introduce redundant storage, but it is acceptable.
24122414
// If the client been ungracefully shutdown, it will missing all cached diff layers, it is acceptable as well.
@@ -2451,7 +2453,7 @@ func (bc *BlockChain) trustedDiffLayerFreezeLoop() {
24512453
batch = bc.db.DiffStore().NewBatch()
24522454
}
24532455
rawdb.WriteDiffLayer(batch, diffLayer.BlockHash, diffLayer)
2454-
staleHash := bc.GetCanonicalHash(uint64(-prio) - diffLayerFreezerBlockLimit)
2456+
staleHash := bc.GetCanonicalHash(uint64(-prio) - bc.diffLayerFreezerBlockLimit)
24552457
rawdb.DeleteDiffLayer(batch, staleHash)
24562458
}
24572459
} else {
@@ -2511,16 +2513,12 @@ func (bc *BlockChain) removeDiffLayers(diffHash common.Hash) {
25112513
// Untrusted peers
25122514
pids := bc.diffHashToPeers[diffHash]
25132515
invalidDiffHashes := make(map[common.Hash]struct{})
2514-
if pids != nil {
2515-
for pid := range pids {
2516-
invaliDiffHashesPeer := bc.diffPeersToDiffHashes[pid]
2517-
if invaliDiffHashesPeer != nil {
2518-
for invaliDiffHash := range invaliDiffHashesPeer {
2519-
invalidDiffHashes[invaliDiffHash] = struct{}{}
2520-
}
2521-
}
2522-
delete(bc.diffPeersToDiffHashes, pid)
2516+
for pid := range pids {
2517+
invaliDiffHashesPeer := bc.diffPeersToDiffHashes[pid]
2518+
for invaliDiffHash := range invaliDiffHashesPeer {
2519+
invalidDiffHashes[invaliDiffHash] = struct{}{}
25232520
}
2521+
delete(bc.diffPeersToDiffHashes, pid)
25242522
}
25252523
for invalidDiffHash := range invalidDiffHashes {
25262524
delete(bc.diffHashToPeers, invalidDiffHash)
@@ -2602,7 +2600,7 @@ func (bc *BlockChain) pruneDiffLayer() {
26022600
break
26032601
}
26042602
}
2605-
staleDiffHashes := make(map[common.Hash]struct{}, 0)
2603+
staleDiffHashes := make(map[common.Hash]struct{})
26062604
for blockHash := range staleBlockHashes {
26072605
if diffHashes, exist := bc.blockHashToDiffLayers[blockHash]; exist {
26082606
for diffHash := range diffHashes {
@@ -2932,3 +2930,10 @@ func EnableLightProcessor(bc *BlockChain) *BlockChain {
29322930
bc.processor = NewLightStateProcessor(bc.Config(), bc, bc.engine)
29332931
return bc
29342932
}
2933+
2934+
func EnablePersistDiff(limit uint64) BlockChainOption {
2935+
return func(chain *BlockChain) *BlockChain {
2936+
chain.diffLayerFreezerBlockLimit = limit
2937+
return chain
2938+
}
2939+
}

core/blockchain_diff_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ func newTestBackendWithGenerator(blocks int, lightProcess bool) *testBackend {
7272
Alloc: GenesisAlloc{testAddr: {Balance: big.NewInt(100000000000000000)}},
7373
}).MustCommit(db)
7474

75-
chain, _ := NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil)
75+
chain, _ := NewBlockChain(db, nil, params.TestChainConfig, ethash.NewFaker(), vm.Config{}, nil, nil, EnablePersistDiff(860000))
7676
generator := func(i int, block *BlockGen) {
7777
// The chain maker doesn't have access to a chain, so the difficulty will be
7878
// lets unset (nil). Set it here to the correct value.

core/blockchain_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -1769,7 +1769,7 @@ func testSideImport(t *testing.T, numCanonBlocksInSidechain, blocksBetweenCommon
17691769
}
17701770

17711771
lastPrunedIndex := len(blocks) - TestTriesInMemory - 1
1772-
lastPrunedBlock := blocks[lastPrunedIndex]
1772+
lastPrunedBlock := blocks[lastPrunedIndex-1]
17731773
firstNonPrunedBlock := blocks[len(blocks)-TestTriesInMemory]
17741774

17751775
// Verify pruning of lastPrunedBlock
@@ -2420,7 +2420,7 @@ func TestSideImportPrunedBlocks(t *testing.T) {
24202420
}
24212421

24222422
lastPrunedIndex := len(blocks) - TestTriesInMemory - 1
2423-
lastPrunedBlock := blocks[lastPrunedIndex]
2423+
lastPrunedBlock := blocks[lastPrunedIndex-1]
24242424

24252425
// Verify pruning of lastPrunedBlock
24262426
if chain.HasBlockAndState(lastPrunedBlock.Hash(), lastPrunedBlock.NumberU64()) {

core/rawdb/freezer_table_test.go

+3-57
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,10 @@ package rawdb
1818

1919
import (
2020
"bytes"
21-
"encoding/binary"
2221
"fmt"
23-
"io/ioutil"
2422
"math/rand"
2523
"os"
2624
"path/filepath"
27-
"sync"
2825
"testing"
2926
"time"
3027

@@ -528,7 +525,6 @@ func TestOffset(t *testing.T) {
528525

529526
f.Append(4, getChunk(20, 0xbb))
530527
f.Append(5, getChunk(20, 0xaa))
531-
f.DumpIndex(0, 100)
532528
f.Close()
533529
}
534530
// Now crop it.
@@ -575,7 +571,6 @@ func TestOffset(t *testing.T) {
575571
if err != nil {
576572
t.Fatal(err)
577573
}
578-
f.DumpIndex(0, 100)
579574
// It should allow writing item 6
580575
f.Append(numDeleted+2, getChunk(20, 0x99))
581576

@@ -640,55 +635,6 @@ func TestOffset(t *testing.T) {
640635
// 1. have data files d0, d1, d2, d3
641636
// 2. remove d2,d3
642637
//
643-
// However, all 'normal' failure modes arising due to failing to sync() or save a file
644-
// should be handled already, and the case described above can only (?) happen if an
645-
// external process/user deletes files from the filesystem.
646-
647-
// TestAppendTruncateParallel is a test to check if the Append/truncate operations are
648-
// racy.
649-
//
650-
// The reason why it's not a regular fuzzer, within tests/fuzzers, is that it is dependent
651-
// on timing rather than 'clever' input -- there's no determinism.
652-
func TestAppendTruncateParallel(t *testing.T) {
653-
dir, err := ioutil.TempDir("", "freezer")
654-
if err != nil {
655-
t.Fatal(err)
656-
}
657-
defer os.RemoveAll(dir)
658-
659-
f, err := newCustomTable(dir, "tmp", metrics.NilMeter{}, metrics.NilMeter{}, metrics.NilGauge{}, 8, true)
660-
if err != nil {
661-
t.Fatal(err)
662-
}
663-
664-
fill := func(mark uint64) []byte {
665-
data := make([]byte, 8)
666-
binary.LittleEndian.PutUint64(data, mark)
667-
return data
668-
}
669-
670-
for i := 0; i < 5000; i++ {
671-
f.truncate(0)
672-
data0 := fill(0)
673-
f.Append(0, data0)
674-
data1 := fill(1)
675-
676-
var wg sync.WaitGroup
677-
wg.Add(2)
678-
go func() {
679-
f.truncate(0)
680-
wg.Done()
681-
}()
682-
go func() {
683-
f.Append(1, data1)
684-
wg.Done()
685-
}()
686-
wg.Wait()
687-
688-
if have, err := f.Retrieve(0); err == nil {
689-
if !bytes.Equal(have, data0) {
690-
t.Fatalf("have %x want %x", have, data0)
691-
}
692-
}
693-
}
694-
}
638+
// However, all 'normal' failure modes arising due to failing to sync() or save a file should be
639+
// handled already, and the case described above can only (?) happen if an external process/user
640+
// deletes files from the filesystem.

core/state/database.go

-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,6 @@ func (db *cachingDB) CacheStorage(addrHash common.Hash, root common.Hash, t Trie
243243
triesArray := [3]*triePair{{root: root, trie: tr.ResetCopy()}, nil, nil}
244244
db.storageTrieCache.Add(addrHash, triesArray)
245245
}
246-
return
247246
}
248247

249248
func (db *cachingDB) Purge() {

core/state/snapshot/disklayer_test.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ func TestDiskMerge(t *testing.T) {
121121
base.Storage(conNukeCache, conNukeCacheSlot)
122122

123123
// Modify or delete some accounts, flatten everything onto disk
124-
if err := snaps.Update(diffRoot, baseRoot, map[common.Hash]struct{}{
124+
if err := snaps.update(diffRoot, baseRoot, map[common.Hash]struct{}{
125125
accDelNoCache: {},
126126
accDelCache: {},
127127
conNukeNoCache: {},
@@ -344,7 +344,7 @@ func TestDiskPartialMerge(t *testing.T) {
344344
assertStorage(conNukeCache, conNukeCacheSlot, conNukeCacheSlot[:])
345345

346346
// Modify or delete some accounts, flatten everything onto disk
347-
if err := snaps.Update(diffRoot, baseRoot, map[common.Hash]struct{}{
347+
if err := snaps.update(diffRoot, baseRoot, map[common.Hash]struct{}{
348348
accDelNoCache: {},
349349
accDelCache: {},
350350
conNukeNoCache: {},
@@ -466,7 +466,7 @@ func TestDiskGeneratorPersistence(t *testing.T) {
466466
},
467467
}
468468
// Modify or delete some accounts, flatten everything onto disk
469-
if err := snaps.Update(diffRoot, baseRoot, nil, map[common.Hash][]byte{
469+
if err := snaps.update(diffRoot, baseRoot, nil, map[common.Hash][]byte{
470470
accTwo: accTwo[:],
471471
}, nil); err != nil {
472472
t.Fatalf("failed to update snapshot tree: %v", err)
@@ -484,7 +484,7 @@ func TestDiskGeneratorPersistence(t *testing.T) {
484484
}
485485
// Test scenario 2, the disk layer is fully generated
486486
// Modify or delete some accounts, flatten everything onto disk
487-
if err := snaps.Update(diffTwoRoot, diffRoot, nil, map[common.Hash][]byte{
487+
if err := snaps.update(diffTwoRoot, diffRoot, nil, map[common.Hash][]byte{
488488
accThree: accThree.Bytes(),
489489
}, map[common.Hash]map[common.Hash][]byte{
490490
accThree: {accThreeSlot: accThreeSlot.Bytes()},

0 commit comments

Comments
 (0)