Skip to content

Commit 006c21e

Browse files
committed
cmd, core, eth, les, node: chain freezer on top of db rework
1 parent 0c5f8c0 commit 006c21e

15 files changed

Lines changed: 755 additions & 35 deletions

File tree

‎cmd/geth/chaincmd.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,9 +368,12 @@ func exportPreimages(ctx *cli.Context) error {
368368

369369
func copyDb(ctx *cli.Context) error {
370370
// Ensure we have a source chain directory to copy
371-
if len(ctx.Args()) != 1 {
371+
if len(ctx.Args()) < 1 {
372372
utils.Fatalf("Source chaindata directory path argument missing")
373373
}
374+
if len(ctx.Args()) < 2 {
375+
utils.Fatalf("Source ancient chain directory path argument missing")
376+
}
374377
// Initialize a new chain for the running node to sync into
375378
stack := makeFullNode(ctx)
376379
defer stack.Close()
@@ -385,7 +388,7 @@ func copyDb(ctx *cli.Context) error {
385388
dl := downloader.New(0, chainDb, syncBloom, new(event.TypeMux), chain, nil, nil)
386389

387390
// Create a source peer to satisfy downloader requests from
388-
db, err := rawdb.NewLevelDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, "")
391+
db, err := rawdb.NewLevelDBDatabaseWithFreezer(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, ctx.Args().Get(1), "")
389392
if err != nil {
390393
return err
391394
}

‎cmd/geth/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ var (
6262
utils.BootnodesV4Flag,
6363
utils.BootnodesV5Flag,
6464
utils.DataDirFlag,
65+
utils.AncientFlag,
6566
utils.KeyStoreDirFlag,
6667
utils.ExternalSignerFlag,
6768
utils.NoUSBFlag,

‎cmd/geth/usage.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ var AppHelpFlagGroups = []flagGroup{
6969
Flags: []cli.Flag{
7070
configFileFlag,
7171
utils.DataDirFlag,
72+
utils.AncientFlag,
7273
utils.KeyStoreDirFlag,
7374
utils.NoUSBFlag,
7475
utils.NetworkIdFlag,

‎cmd/utils/flags.go‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,10 @@ var (
117117
Usage: "Data directory for the databases and keystore",
118118
Value: DirectoryString{node.DefaultDataDir()},
119119
}
120+
AncientFlag = DirectoryFlag{
121+
Name: "datadir.ancient",
122+
Usage: "Data directory for ancient chain segments (default = inside chaindata)",
123+
}
120124
KeyStoreDirFlag = DirectoryFlag{
121125
Name: "keystore",
122126
Usage: "Directory for the keystore (default = inside the datadir)",
@@ -1378,6 +1382,9 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *eth.Config) {
13781382
cfg.DatabaseCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheDatabaseFlag.Name) / 100
13791383
}
13801384
cfg.DatabaseHandles = makeDatabaseHandles()
1385+
if ctx.GlobalIsSet(AncientFlag.Name) {
1386+
cfg.DatabaseFreezer = ctx.GlobalString(AncientFlag.Name)
1387+
}
13811388

13821389
if gcmode := ctx.GlobalString(GCModeFlag.Name); gcmode != "full" && gcmode != "archive" {
13831390
Fatalf("--%s must be either 'full' or 'archive'", GCModeFlag.Name)
@@ -1566,7 +1573,7 @@ func MakeChainDatabase(ctx *cli.Context, stack *node.Node) ethdb.Database {
15661573
if ctx.GlobalString(SyncModeFlag.Name) == "light" {
15671574
name = "lightchaindata"
15681575
}
1569-
chainDb, err := stack.OpenDatabase(name, cache, handles, "")
1576+
chainDb, err := stack.OpenDatabaseWithFreezer(name, cache, handles, "", "")
15701577
if err != nil {
15711578
Fatalf("Could not open database: %v", err)
15721579
}

‎core/rawdb/accessors_chain.go‎

Lines changed: 62 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,11 @@ import (
3030
)
3131

3232
// ReadCanonicalHash retrieves the hash assigned to a canonical block number.
33-
func ReadCanonicalHash(db ethdb.Reader, number uint64) common.Hash {
34-
data, _ := db.Get(headerHashKey(number))
33+
func ReadCanonicalHash(db ethdb.AncientReader, number uint64) common.Hash {
34+
data, _ := db.Ancient("hashes", number)
35+
if len(data) == 0 {
36+
data, _ = db.Get(headerHashKey(number))
37+
}
3538
if len(data) == 0 {
3639
return common.Hash{}
3740
}
@@ -52,6 +55,24 @@ func DeleteCanonicalHash(db ethdb.Writer, number uint64) {
5255
}
5356
}
5457

58+
// readAllHashes retrieves all the hashes assigned to blocks at a certain heights,
59+
// both canonical and reorged forks included.
60+
//
61+
// This method is a helper for the chain reader. It should never be exposed to the
62+
// outside world.
63+
func readAllHashes(db ethdb.Iteratee, number uint64) []common.Hash {
64+
prefix := headerKeyPrefix(number)
65+
66+
hashes := make([]common.Hash, 0, 1)
67+
it := db.NewIteratorWithPrefix(prefix)
68+
for it.Next() {
69+
if key := it.Key(); len(key) == len(prefix)+32 {
70+
hashes = append(hashes, common.BytesToHash(key[len(key)-32:]))
71+
}
72+
}
73+
return hashes
74+
}
75+
5576
// ReadHeaderNumber returns the header number assigned to a hash.
5677
func ReadHeaderNumber(db ethdb.Reader, hash common.Hash) *uint64 {
5778
data, _ := db.Get(headerNumberKey(hash))
@@ -129,21 +150,27 @@ func WriteFastTrieProgress(db ethdb.Writer, count uint64) {
129150
}
130151

131152
// ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
132-
func ReadHeaderRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
133-
data, _ := db.Get(headerKey(number, hash))
153+
func ReadHeaderRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
154+
data, _ := db.Ancient("headers", number)
155+
if len(data) == 0 {
156+
data, _ = db.Get(headerKey(number, hash))
157+
}
134158
return data
135159
}
136160

137161
// HasHeader verifies the existence of a block header corresponding to the hash.
138-
func HasHeader(db ethdb.Reader, hash common.Hash, number uint64) bool {
162+
func HasHeader(db ethdb.AncientReader, hash common.Hash, number uint64) bool {
163+
if has, err := db.Ancient("hashes", number); err == nil && common.BytesToHash(has) == hash {
164+
return true
165+
}
139166
if has, err := db.Has(headerKey(number, hash)); !has || err != nil {
140167
return false
141168
}
142169
return true
143170
}
144171

145172
// ReadHeader retrieves the block header corresponding to the hash.
146-
func ReadHeader(db ethdb.Reader, hash common.Hash, number uint64) *types.Header {
173+
func ReadHeader(db ethdb.AncientReader, hash common.Hash, number uint64) *types.Header {
147174
data := ReadHeaderRLP(db, hash, number)
148175
if len(data) == 0 {
149176
return nil
@@ -197,8 +224,11 @@ func deleteHeaderWithoutNumber(db ethdb.Writer, hash common.Hash, number uint64)
197224
}
198225

199226
// ReadBodyRLP retrieves the block body (transactions and uncles) in RLP encoding.
200-
func ReadBodyRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
201-
data, _ := db.Get(blockBodyKey(number, hash))
227+
func ReadBodyRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
228+
data, _ := db.Ancient("bodies", number)
229+
if len(data) == 0 {
230+
data, _ = db.Get(blockBodyKey(number, hash))
231+
}
202232
return data
203233
}
204234

@@ -210,15 +240,18 @@ func WriteBodyRLP(db ethdb.Writer, hash common.Hash, number uint64, rlp rlp.RawV
210240
}
211241

212242
// HasBody verifies the existence of a block body corresponding to the hash.
213-
func HasBody(db ethdb.Reader, hash common.Hash, number uint64) bool {
243+
func HasBody(db ethdb.AncientReader, hash common.Hash, number uint64) bool {
244+
if has, err := db.Ancient("hashes", number); err == nil && common.BytesToHash(has) == hash {
245+
return true
246+
}
214247
if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil {
215248
return false
216249
}
217250
return true
218251
}
219252

220253
// ReadBody retrieves the block body corresponding to the hash.
221-
func ReadBody(db ethdb.Reader, hash common.Hash, number uint64) *types.Body {
254+
func ReadBody(db ethdb.AncientReader, hash common.Hash, number uint64) *types.Body {
222255
data := ReadBodyRLP(db, hash, number)
223256
if len(data) == 0 {
224257
return nil
@@ -248,13 +281,16 @@ func DeleteBody(db ethdb.Writer, hash common.Hash, number uint64) {
248281
}
249282

250283
// ReadTdRLP retrieves a block's total difficulty corresponding to the hash in RLP encoding.
251-
func ReadTdRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
252-
data, _ := db.Get(headerTDKey(number, hash))
284+
func ReadTdRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
285+
data, _ := db.Ancient("diffs", number)
286+
if len(data) == 0 {
287+
data, _ = db.Get(headerTDKey(number, hash))
288+
}
253289
return data
254290
}
255291

256292
// ReadTd retrieves a block's total difficulty corresponding to the hash.
257-
func ReadTd(db ethdb.Reader, hash common.Hash, number uint64) *big.Int {
293+
func ReadTd(db ethdb.AncientReader, hash common.Hash, number uint64) *big.Int {
258294
data := ReadTdRLP(db, hash, number)
259295
if len(data) == 0 {
260296
return nil
@@ -287,23 +323,29 @@ func DeleteTd(db ethdb.Writer, hash common.Hash, number uint64) {
287323

288324
// HasReceipts verifies the existence of all the transaction receipts belonging
289325
// to a block.
290-
func HasReceipts(db ethdb.Reader, hash common.Hash, number uint64) bool {
326+
func HasReceipts(db ethdb.AncientReader, hash common.Hash, number uint64) bool {
327+
if has, err := db.Ancient("hashes", number); err == nil && common.BytesToHash(has) == hash {
328+
return true
329+
}
291330
if has, err := db.Has(blockReceiptsKey(number, hash)); !has || err != nil {
292331
return false
293332
}
294333
return true
295334
}
296335

297336
// ReadReceiptsRLP retrieves all the transaction receipts belonging to a block in RLP encoding.
298-
func ReadReceiptsRLP(db ethdb.Reader, hash common.Hash, number uint64) rlp.RawValue {
299-
data, _ := db.Get(blockReceiptsKey(number, hash))
337+
func ReadReceiptsRLP(db ethdb.AncientReader, hash common.Hash, number uint64) rlp.RawValue {
338+
data, _ := db.Ancient("receipts", number)
339+
if len(data) == 0 {
340+
data, _ = db.Get(blockReceiptsKey(number, hash))
341+
}
300342
return data
301343
}
302344

303345
// ReadRawReceipts retrieves all the transaction receipts belonging to a block.
304346
// The receipt metadata fields are not guaranteed to be populated, so they
305347
// should not be used. Use ReadReceipts instead if the metadata is needed.
306-
func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Receipts {
348+
func ReadRawReceipts(db ethdb.AncientReader, hash common.Hash, number uint64) types.Receipts {
307349
// Retrieve the flattened receipt slice
308350
data := ReadReceiptsRLP(db, hash, number)
309351
if len(data) == 0 {
@@ -329,7 +371,7 @@ func ReadRawReceipts(db ethdb.Reader, hash common.Hash, number uint64) types.Rec
329371
// The current implementation populates these metadata fields by reading the receipts'
330372
// corresponding block body, so if the block body is not found it will return nil even
331373
// if the receipt itself is stored.
332-
func ReadReceipts(db ethdb.Reader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts {
374+
func ReadReceipts(db ethdb.AncientReader, hash common.Hash, number uint64, config *params.ChainConfig) types.Receipts {
333375
// We're deriving many fields from the block body, retrieve beside the receipt
334376
receipts := ReadRawReceipts(db, hash, number)
335377
if receipts == nil {
@@ -377,7 +419,7 @@ func DeleteReceipts(db ethdb.Writer, hash common.Hash, number uint64) {
377419
//
378420
// Note, due to concurrent download of header and block body the header and thus
379421
// canonical hash can be stored in the database but the body data not (yet).
380-
func ReadBlock(db ethdb.Reader, hash common.Hash, number uint64) *types.Block {
422+
func ReadBlock(db ethdb.AncientReader, hash common.Hash, number uint64) *types.Block {
381423
header := ReadHeader(db, hash, number)
382424
if header == nil {
383425
return nil
@@ -413,7 +455,7 @@ func deleteBlockWithoutNumber(db ethdb.Writer, hash common.Hash, number uint64)
413455
}
414456

415457
// FindCommonAncestor returns the last common ancestor of two block headers
416-
func FindCommonAncestor(db ethdb.Reader, a, b *types.Header) *types.Header {
458+
func FindCommonAncestor(db ethdb.AncientReader, a, b *types.Header) *types.Header {
417459
for bn := b.Number.Uint64(); a.Number.Uint64() > bn; {
418460
a = ReadHeader(db, a.ParentHash, a.Number.Uint64()-1)
419461
if a == nil {

‎core/rawdb/accessors_indexes.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ func DeleteTxLookupEntry(db ethdb.Writer, hash common.Hash) {
6969

7070
// ReadTransaction retrieves a specific transaction from the database, along with
7171
// its added positional metadata.
72-
func ReadTransaction(db ethdb.Reader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
72+
func ReadTransaction(db ethdb.AncientReader, hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64) {
7373
blockNumber := ReadTxLookupEntry(db, hash)
7474
if blockNumber == nil {
7575
return nil, common.Hash{}, 0, 0
@@ -94,7 +94,7 @@ func ReadTransaction(db ethdb.Reader, hash common.Hash) (*types.Transaction, com
9494

9595
// ReadReceipt retrieves a specific transaction receipt from the database, along with
9696
// its added positional metadata.
97-
func ReadReceipt(db ethdb.Reader, hash common.Hash, config *params.ChainConfig) (*types.Receipt, common.Hash, uint64, uint64) {
97+
func ReadReceipt(db ethdb.AncientReader, hash common.Hash, config *params.ChainConfig) (*types.Receipt, common.Hash, uint64, uint64) {
9898
// Retrieve the context of the receipt based on the transaction hash
9999
blockNumber := ReadTxLookupEntry(db, hash)
100100
if blockNumber == nil {

‎core/rawdb/database.go‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,44 @@ import (
2222
"github.com/ethereum/go-ethereum/ethdb/memorydb"
2323
)
2424

25+
// freezerdb is a databse wrapper that enabled freezer data retrievals.
26+
type freezerdb struct {
27+
ethdb.KeyValueStore
28+
ethdb.Ancienter
29+
}
30+
31+
// nofreezedb is a database wrapper that disables freezer data retrievals.
32+
type nofreezedb struct {
33+
ethdb.KeyValueStore
34+
}
35+
36+
// Frozen returns nil as we don't have a backing chain freezer.
37+
func (db *nofreezedb) Ancient(kind string, number uint64) ([]byte, error) {
38+
return nil, errOutOfBounds
39+
}
40+
2541
// NewDatabase creates a high level database on top of a given key-value data
2642
// store without a freezer moving immutable chain segments into cold storage.
2743
func NewDatabase(db ethdb.KeyValueStore) ethdb.Database {
28-
return db
44+
return &nofreezedb{
45+
KeyValueStore: db,
46+
}
47+
}
48+
49+
// NewDatabaseWithFreezer creates a high level database on top of a given key-
50+
// value data store with a freezer moving immutable chain segments into cold
51+
// storage.
52+
func NewDatabaseWithFreezer(db ethdb.KeyValueStore, freezer string, namespace string) (ethdb.Database, error) {
53+
frdb, err := newFreezer(freezer, namespace)
54+
if err != nil {
55+
return nil, err
56+
}
57+
go frdb.freeze(db)
58+
59+
return &freezerdb{
60+
KeyValueStore: db,
61+
Ancienter: frdb,
62+
}, nil
2963
}
3064

3165
// NewMemoryDatabase creates an ephemeral in-memory key-value database without a
@@ -34,9 +68,9 @@ func NewMemoryDatabase() ethdb.Database {
3468
return NewDatabase(memorydb.New())
3569
}
3670

37-
// NewMemoryDatabaseWithCap creates an ephemeral in-memory key-value database with
38-
// an initial starting capacity, but without a freezer moving immutable chain
39-
// segments into cold storage.
71+
// NewMemoryDatabaseWithCap creates an ephemeral in-memory key-value database
72+
// with an initial starting capacity, but without a freezer moving immutable
73+
// chain segments into cold storage.
4074
func NewMemoryDatabaseWithCap(size int) ethdb.Database {
4175
return NewDatabase(memorydb.NewWithCap(size))
4276
}
@@ -50,3 +84,18 @@ func NewLevelDBDatabase(file string, cache int, handles int, namespace string) (
5084
}
5185
return NewDatabase(db), nil
5286
}
87+
88+
// NewLevelDBDatabaseWithFreezer creates a persistent key-value database with a
89+
// freezer moving immutable chain segments into cold storage.
90+
func NewLevelDBDatabaseWithFreezer(file string, cache int, handles int, freezer string, namespace string) (ethdb.Database, error) {
91+
kvdb, err := leveldb.New(file, cache, handles, namespace)
92+
if err != nil {
93+
return nil, err
94+
}
95+
frdb, err := NewDatabaseWithFreezer(kvdb, freezer, namespace)
96+
if err != nil {
97+
kvdb.Close()
98+
return nil, err
99+
}
100+
return frdb, nil
101+
}

0 commit comments

Comments
 (0)