Skip to content

Commit 536b3b4

Browse files
committed
cosensus, core, eth, params, trie: fixes + clique history cap
1 parent 37d280d commit 536b3b4

12 files changed

Lines changed: 112 additions & 53 deletions

File tree

‎consensus/clique/clique.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,8 +365,11 @@ func (c *Clique) snapshot(chain consensus.ChainReader, number uint64, hash commo
365365
break
366366
}
367367
}
368-
// If we're at an checkpoint block, make a snapshot if it's known
369-
if number == 0 || (number%c.config.Epoch == 0 && chain.GetHeaderByNumber(number-1) == nil) {
368+
// If we're at the genesis, snapshot the initial state. Alternatively if we're
369+
// at a checkpoint block without a parent (light client CHT), or we have piled
370+
// up more headers than allowed to be reorged (chain reinit from a freezer),
371+
// consider the checkpoint trusted and snapshot it.
372+
if number == 0 || (number%c.config.Epoch == 0 && (len(headers) > params.ImmutabilityThreshold || chain.GetHeaderByNumber(number-1) == nil)) {
370373
checkpoint := chain.GetHeaderByNumber(number)
371374
if checkpoint != nil {
372375
hash := checkpoint.Hash()

‎consensus/clique/snapshot.go‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@ import (
2020
"bytes"
2121
"encoding/json"
2222
"sort"
23+
"time"
2324

2425
"github.com/ethereum/go-ethereum/common"
2526
"github.com/ethereum/go-ethereum/core/types"
2627
"github.com/ethereum/go-ethereum/ethdb"
28+
"github.com/ethereum/go-ethereum/log"
2729
"github.com/ethereum/go-ethereum/params"
2830
lru "github.com/hashicorp/golang-lru"
2931
)
@@ -197,7 +199,11 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
197199
// Iterate through the headers and create a new snapshot
198200
snap := s.copy()
199201

200-
for _, header := range headers {
202+
var (
203+
start = time.Now()
204+
logged = time.Now()
205+
)
206+
for i, header := range headers {
201207
// Remove any votes on checkpoint blocks
202208
number := header.Number.Uint64()
203209
if number%s.config.Epoch == 0 {
@@ -285,6 +291,14 @@ func (s *Snapshot) apply(headers []*types.Header) (*Snapshot, error) {
285291
}
286292
delete(snap.Tally, header.Coinbase)
287293
}
294+
// If we're taking too much time (ecrecover), notify the user once a while
295+
if time.Since(logged) > 8*time.Second {
296+
log.Info("Reconstructing voting history", "processed", i, "total", len(headers), "elapsed", common.PrettyDuration(time.Since(start)))
297+
logged = time.Now()
298+
}
299+
}
300+
if time.Since(start) > 8*time.Second {
301+
log.Info("Reconstructed voting history", "processed", len(headers), "elapsed", common.PrettyDuration(time.Since(start)))
288302
}
289303
snap.Number += uint64(len(headers))
290304
snap.Hash = headers[len(headers)-1].Hash()

‎consensus/ethash/sealer.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ func (ethash *Ethash) remote(notify []string, noverify bool) {
270270
start := time.Now()
271271
if !noverify {
272272
if err := ethash.verifySeal(nil, header, true); err != nil {
273-
log.Warn("Invalid proof-of-work submitted", "sealhash", sealhash, "elapsed", time.Since(start), "err", err)
273+
log.Warn("Invalid proof-of-work submitted", "sealhash", sealhash, "elapsed", common.PrettyDuration(time.Since(start)), "err", err)
274274
return false
275275
}
276276
}
@@ -279,7 +279,7 @@ func (ethash *Ethash) remote(notify []string, noverify bool) {
279279
log.Warn("Ethash result channel is empty, submitted mining result is rejected")
280280
return false
281281
}
282-
log.Trace("Verified correct proof-of-work", "sealhash", sealhash, "elapsed", time.Since(start))
282+
log.Trace("Verified correct proof-of-work", "sealhash", sealhash, "elapsed", common.PrettyDuration(time.Since(start)))
283283

284284
// Solutions seems to be valid, return to the miner and notify acceptance.
285285
solution := block.WithSeal(header)

‎core/blockchain.go‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,10 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
221221
// Initialize the chain with ancient data if it isn't empty.
222222
if bc.empty() {
223223
if frozen, err := bc.db.Ancients(); err == nil && frozen > 0 {
224+
var (
225+
start = time.Now()
226+
logged time.Time
227+
)
224228
for i := uint64(0); i < frozen; i++ {
225229
// Inject hash<->number mapping.
226230
hash := rawdb.ReadCanonicalHash(bc.db, i)
@@ -235,12 +239,23 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
235239
return nil, errors.New("broken ancient database")
236240
}
237241
rawdb.WriteTxLookupEntries(bc.db, block)
242+
243+
// If we've spent too much time already, notify the user of what we're doing
244+
if time.Since(logged) > 8*time.Second {
245+
log.Info("Initializing chain from ancient data", "number", i, "hash", hash, "total", frozen-1, "elapsed", common.PrettyDuration(time.Since(start)))
246+
logged = time.Now()
247+
}
238248
}
239249
hash := rawdb.ReadCanonicalHash(bc.db, frozen-1)
240250
rawdb.WriteHeadHeaderHash(bc.db, hash)
241251
rawdb.WriteHeadFastBlockHash(bc.db, hash)
242252

243-
log.Info("Initialized chain with ancients", "number", frozen-1, "hash", hash)
253+
// The first thing the node will do is reconstruct the verification data for
254+
// the head block (ethash cache or clique voting snapshot). Might as well do
255+
// it in advance.
256+
bc.engine.VerifyHeader(bc, rawdb.ReadHeader(bc.db, hash, frozen-1), true)
257+
258+
log.Info("Initialized chain from ancient data", "number", frozen-1, "hash", hash, "elapsed", common.PrettyDuration(time.Since(start)))
244259
}
245260
}
246261
if err := bc.loadLastState(); err != nil {

‎core/rawdb/database.go‎

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -179,17 +179,18 @@ func InspectDatabase(db ethdb.Database) error {
179179
logged = time.Now()
180180

181181
// Key-value store statistics
182-
total common.StorageSize
183-
headerSize common.StorageSize
184-
bodySize common.StorageSize
185-
receiptSize common.StorageSize
186-
tdSize common.StorageSize
187-
numHashPairing common.StorageSize
188-
hashNumPairing common.StorageSize
189-
trieSize common.StorageSize
190-
txlookupSize common.StorageSize
191-
preimageSize common.StorageSize
192-
bloomBitsSize common.StorageSize
182+
total common.StorageSize
183+
headerSize common.StorageSize
184+
bodySize common.StorageSize
185+
receiptSize common.StorageSize
186+
tdSize common.StorageSize
187+
numHashPairing common.StorageSize
188+
hashNumPairing common.StorageSize
189+
trieSize common.StorageSize
190+
txlookupSize common.StorageSize
191+
preimageSize common.StorageSize
192+
bloomBitsSize common.StorageSize
193+
cliqueSnapsSize common.StorageSize
193194

194195
// Ancient store statistics
195196
ancientHeaders common.StorageSize
@@ -199,8 +200,12 @@ func InspectDatabase(db ethdb.Database) error {
199200
ancientTds common.StorageSize
200201

201202
// Les statistic
202-
ChtTrieNodes common.StorageSize
203-
BloomTrieNodes common.StorageSize
203+
chtTrieNodes common.StorageSize
204+
bloomTrieNodes common.StorageSize
205+
206+
// Meta- and unaccounted data
207+
metadata common.StorageSize
208+
unaccounted common.StorageSize
204209
)
205210
// Inspect key-value database first.
206211
for it.Next() {
@@ -228,12 +233,26 @@ func InspectDatabase(db ethdb.Database) error {
228233
preimageSize += size
229234
case bytes.HasPrefix(key, bloomBitsPrefix) && len(key) == (len(bloomBitsPrefix)+10+common.HashLength):
230235
bloomBitsSize += size
236+
case bytes.HasPrefix(key, []byte("clique-")) && len(key) == 7+common.HashLength:
237+
cliqueSnapsSize += size
231238
case bytes.HasPrefix(key, []byte("cht-")) && len(key) == 4+common.HashLength:
232-
ChtTrieNodes += size
239+
chtTrieNodes += size
233240
case bytes.HasPrefix(key, []byte("blt-")) && len(key) == 4+common.HashLength:
234-
BloomTrieNodes += size
241+
bloomTrieNodes += size
235242
case len(key) == common.HashLength:
236243
trieSize += size
244+
default:
245+
var accounted bool
246+
for _, meta := range [][]byte{databaseVerisionKey, headHeaderKey, headBlockKey, headFastBlockKey, fastTrieProgressKey, ancientKey} {
247+
if bytes.Equal(key, meta) {
248+
metadata += size
249+
accounted = true
250+
break
251+
}
252+
}
253+
if !accounted {
254+
unaccounted += size
255+
}
237256
}
238257
count += 1
239258
if count%1000 == 0 && time.Since(logged) > 8*time.Second {
@@ -261,18 +280,24 @@ func InspectDatabase(db ethdb.Database) error {
261280
{"Key-Value store", "Bloombit index", bloomBitsSize.String()},
262281
{"Key-Value store", "Trie nodes", trieSize.String()},
263282
{"Key-Value store", "Trie preimages", preimageSize.String()},
283+
{"Key-Value store", "Clique snapshots", cliqueSnapsSize.String()},
284+
{"Key-Value store", "Singleton metadata", metadata.String()},
264285
{"Ancient store", "Headers", ancientHeaders.String()},
265286
{"Ancient store", "Bodies", ancientBodies.String()},
266287
{"Ancient store", "Receipts", ancientReceipts.String()},
267288
{"Ancient store", "Difficulties", ancientTds.String()},
268289
{"Ancient store", "Block number->hash", ancientHashes.String()},
269-
{"Light client", "CHT trie nodes", ChtTrieNodes.String()},
270-
{"Light client", "Bloom trie nodes", BloomTrieNodes.String()},
290+
{"Light client", "CHT trie nodes", chtTrieNodes.String()},
291+
{"Light client", "Bloom trie nodes", bloomTrieNodes.String()},
271292
}
272293
table := tablewriter.NewWriter(os.Stdout)
273294
table.SetHeader([]string{"Database", "Category", "Size"})
274295
table.SetFooter([]string{"", "Total", total.String()})
275296
table.AppendBulk(stats)
276297
table.Render()
298+
299+
if unaccounted > 0 {
300+
log.Error("Database contains unaccounted data", "size", unaccounted)
301+
}
277302
return nil
278303
}

‎core/rawdb/freezer.go‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
"github.com/ethereum/go-ethereum/ethdb"
3030
"github.com/ethereum/go-ethereum/log"
3131
"github.com/ethereum/go-ethereum/metrics"
32+
"github.com/ethereum/go-ethereum/params"
3233
"github.com/prometheus/tsdb/fileutil"
3334
)
3435

@@ -52,11 +53,6 @@ const (
5253
// storage.
5354
freezerRecheckInterval = time.Minute
5455

55-
// freezerBlockGraduation is the number of confirmations a block must achieve
56-
// before it becomes elligible for chain freezing. This must exceed any chain
57-
// reorg depth, since the freezer also deletes all block siblings.
58-
freezerBlockGraduation = 90000
59-
6056
// freezerBatchLimit is the maximum number of blocks to freeze in one batch
6157
// before doing an fsync and deleting it from the key-value store.
6258
freezerBatchLimit = 30000
@@ -268,12 +264,12 @@ func (f *freezer) freeze(db ethdb.KeyValueStore) {
268264
time.Sleep(freezerRecheckInterval)
269265
continue
270266

271-
case *number < freezerBlockGraduation:
272-
log.Debug("Current full block not old enough", "number", *number, "hash", hash, "delay", freezerBlockGraduation)
267+
case *number < params.ImmutabilityThreshold:
268+
log.Debug("Current full block not old enough", "number", *number, "hash", hash, "delay", params.ImmutabilityThreshold)
273269
time.Sleep(freezerRecheckInterval)
274270
continue
275271

276-
case *number-freezerBlockGraduation <= f.frozen:
272+
case *number-params.ImmutabilityThreshold <= f.frozen:
277273
log.Debug("Ancient blocks frozen already", "number", *number, "hash", hash, "frozen", f.frozen)
278274
time.Sleep(freezerRecheckInterval)
279275
continue
@@ -285,7 +281,7 @@ func (f *freezer) freeze(db ethdb.KeyValueStore) {
285281
continue
286282
}
287283
// Seems we have data ready to be frozen, process in usable batches
288-
limit := *number - freezerBlockGraduation
284+
limit := *number - params.ImmutabilityThreshold
289285
if limit-f.frozen > freezerBatchLimit {
290286
limit = f.frozen + freezerBatchLimit
291287
}

‎core/rawdb/freezer_table_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func init() {
3535
// Gets a chunk of data, filled with 'b'
3636
func getChunk(size int, b int) []byte {
3737
data := make([]byte, size)
38-
for i, _ := range data {
38+
for i := range data {
3939
data[i] = byte(b)
4040
}
4141
return data

‎eth/downloader/downloader.go‎

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import (
2525
"sync/atomic"
2626
"time"
2727

28-
ethereum "github.com/ethereum/go-ethereum"
28+
"github.com/ethereum/go-ethereum"
2929
"github.com/ethereum/go-ethereum/common"
3030
"github.com/ethereum/go-ethereum/core/rawdb"
3131
"github.com/ethereum/go-ethereum/core/types"
@@ -46,20 +46,20 @@ var (
4646
MaxReceiptFetch = 256 // Amount of transaction receipts to allow fetching per request
4747
MaxStateFetch = 384 // Amount of node state values to allow fetching per request
4848

49-
MaxForkAncestry = 3 * params.EpochDuration // Maximum chain reorganisation
50-
rttMinEstimate = 2 * time.Second // Minimum round-trip time to target for download requests
51-
rttMaxEstimate = 20 * time.Second // Maximum round-trip time to target for download requests
52-
rttMinConfidence = 0.1 // Worse confidence factor in our estimated RTT value
53-
ttlScaling = 3 // Constant scaling factor for RTT -> TTL conversion
54-
ttlLimit = time.Minute // Maximum TTL allowance to prevent reaching crazy timeouts
49+
rttMinEstimate = 2 * time.Second // Minimum round-trip time to target for download requests
50+
rttMaxEstimate = 20 * time.Second // Maximum round-trip time to target for download requests
51+
rttMinConfidence = 0.1 // Worse confidence factor in our estimated RTT value
52+
ttlScaling = 3 // Constant scaling factor for RTT -> TTL conversion
53+
ttlLimit = time.Minute // Maximum TTL allowance to prevent reaching crazy timeouts
5554

5655
qosTuningPeers = 5 // Number of peers to tune based on (best peers)
5756
qosConfidenceCap = 10 // Number of peers above which not to modify RTT confidence
5857
qosTuningImpact = 0.25 // Impact that a new tuning target has on the previous value
5958

60-
maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection)
61-
maxHeadersProcess = 2048 // Number of header download results to import at once into the chain
62-
maxResultsProcess = 2048 // Number of content download results to import at once into the chain
59+
maxQueuedHeaders = 32 * 1024 // [eth/62] Maximum number of headers to queue for import (DOS protection)
60+
maxHeadersProcess = 2048 // Number of header download results to import at once into the chain
61+
maxResultsProcess = 2048 // Number of content download results to import at once into the chain
62+
maxForkAncestry uint64 = params.ImmutabilityThreshold // Maximum chain reorganisation (locally redeclared so tests can reduce it)
6363

6464
reorgProtThreshold = 48 // Threshold number of recent blocks to disable mini reorg protection
6565
reorgProtHeaderDelay = 2 // Number of headers to delay delivering to cover mini reorgs
@@ -439,7 +439,7 @@ func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.I
439439

440440
log.Debug("Synchronising with the network", "peer", p.id, "eth", p.version, "head", hash, "td", td, "mode", d.mode)
441441
defer func(start time.Time) {
442-
log.Debug("Synchronisation terminated", "elapsed", time.Since(start))
442+
log.Debug("Synchronisation terminated", "elapsed", common.PrettyDuration(time.Since(start)))
443443
}(time.Now())
444444

445445
// Look up the sync boundaries: the common ancestor and the target block
@@ -491,10 +491,10 @@ func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.I
491491
// The peer would start to feed us valid blocks until head, resulting in all of
492492
// the blocks might be written into the ancient store. A following mini-reorg
493493
// could cause issues.
494-
if d.checkpoint != 0 && d.checkpoint > MaxForkAncestry+1 {
494+
if d.checkpoint != 0 && d.checkpoint > maxForkAncestry+1 {
495495
d.ancientLimit = d.checkpoint
496-
} else if height > MaxForkAncestry+1 {
497-
d.ancientLimit = height - MaxForkAncestry - 1
496+
} else if height > maxForkAncestry+1 {
497+
d.ancientLimit = height - maxForkAncestry - 1
498498
}
499499
frozen, _ := d.stateDB.Ancients() // Ignore the error here since light client can also hit here.
500500
// If a part of blockchain data has already been written into active store,
@@ -725,9 +725,9 @@ func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header)
725725
p.log.Debug("Looking for common ancestor", "local", localHeight, "remote", remoteHeight)
726726

727727
// Recap floor value for binary search
728-
if localHeight >= MaxForkAncestry {
728+
if localHeight >= maxForkAncestry {
729729
// We're above the max reorg threshold, find the earliest fork point
730-
floor = int64(localHeight - MaxForkAncestry)
730+
floor = int64(localHeight - maxForkAncestry)
731731
}
732732
// If we're doing a light sync, ensure the floor doesn't go below the CHT, as
733733
// all headers before that point will be missing.

‎eth/downloader/downloader_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ import (
3737

3838
// Reduce some of the parameters to make the tester faster.
3939
func init() {
40-
MaxForkAncestry = uint64(10000)
40+
maxForkAncestry = 10000
4141
blockCacheItems = 1024
4242
fsHeaderContCheck = 500 * time.Millisecond
4343
}

‎eth/downloader/testchain_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ var testChainBase = newTestChain(blockCacheItems+200, testGenesis)
4545
var testChainForkLightA, testChainForkLightB, testChainForkHeavy *testChain
4646

4747
func init() {
48-
var forkLen = int(MaxForkAncestry + 50)
48+
var forkLen = int(maxForkAncestry + 50)
4949
var wg sync.WaitGroup
5050
wg.Add(3)
5151
go func() { testChainForkLightA = testChainBase.makeFork(forkLen, false, 1); wg.Done() }()

0 commit comments

Comments
 (0)