/
db_manager.go
1579 lines (1362 loc) · 50.6 KB
/
db_manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The klaytn Authors
// This file is part of the klaytn library.
//
// The klaytn library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The klaytn library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
package database
import (
"bytes"
"encoding/binary"
"encoding/json"
"github.com/klaytn/klaytn/blockchain/types"
"github.com/klaytn/klaytn/common"
"github.com/klaytn/klaytn/log"
"github.com/klaytn/klaytn/params"
"github.com/klaytn/klaytn/ser/rlp"
"github.com/pkg/errors"
"math/big"
"path/filepath"
)
var logger = log.NewModuleLogger(log.StorageDatabase)
type DBManager interface {
IsParallelDBWrite() bool
Close()
NewBatch(dbType DBEntryType) Batch
GetMemDB() *MemDB
GetDBConfig() *DBConfig
// from accessors_chain.go
ReadCanonicalHash(number uint64) common.Hash
WriteCanonicalHash(hash common.Hash, number uint64)
DeleteCanonicalHash(number uint64)
ReadHeadHeaderHash() common.Hash
WriteHeadHeaderHash(hash common.Hash)
ReadHeadBlockHash() common.Hash
WriteHeadBlockHash(hash common.Hash)
ReadHeadFastBlockHash() common.Hash
WriteHeadFastBlockHash(hash common.Hash)
ReadFastTrieProgress() uint64
WriteFastTrieProgress(count uint64)
HasHeader(hash common.Hash, number uint64) bool
ReadHeader(hash common.Hash, number uint64) *types.Header
ReadHeaderRLP(hash common.Hash, number uint64) rlp.RawValue
WriteHeader(header *types.Header)
DeleteHeader(hash common.Hash, number uint64)
ReadHeaderNumber(hash common.Hash) *uint64
HasBody(hash common.Hash, number uint64) bool
ReadBody(hash common.Hash, number uint64) *types.Body
ReadBodyInCache(hash common.Hash) *types.Body
ReadBodyRLP(hash common.Hash, number uint64) rlp.RawValue
ReadBodyRLPByHash(hash common.Hash) rlp.RawValue
WriteBody(hash common.Hash, number uint64, body *types.Body)
PutBodyToBatch(batch Batch, hash common.Hash, number uint64, body *types.Body)
WriteBodyRLP(hash common.Hash, number uint64, rlp rlp.RawValue)
DeleteBody(hash common.Hash, number uint64)
ReadTd(hash common.Hash, number uint64) *big.Int
WriteTd(hash common.Hash, number uint64, td *big.Int)
DeleteTd(hash common.Hash, number uint64)
ReadReceipt(txHash common.Hash) (*types.Receipt, common.Hash, uint64, uint64)
ReadReceipts(blockHash common.Hash, number uint64) types.Receipts
ReadReceiptsByBlockHash(hash common.Hash) types.Receipts
WriteReceipts(hash common.Hash, number uint64, receipts types.Receipts)
PutReceiptsToBatch(batch Batch, hash common.Hash, number uint64, receipts types.Receipts)
DeleteReceipts(hash common.Hash, number uint64)
ReadBlock(hash common.Hash, number uint64) *types.Block
ReadBlockByHash(hash common.Hash) *types.Block
ReadBlockByNumber(number uint64) *types.Block
HasBlock(hash common.Hash, number uint64) bool
WriteBlock(block *types.Block)
DeleteBlock(hash common.Hash, number uint64)
FindCommonAncestor(a, b *types.Header) *types.Header
ReadIstanbulSnapshot(hash common.Hash) ([]byte, error)
WriteIstanbulSnapshot(hash common.Hash, blob []byte) error
WriteMerkleProof(key, value []byte)
ReadCachedTrieNode(hash common.Hash) ([]byte, error)
ReadCachedTrieNodePreimage(secureKey []byte) ([]byte, error)
ReadStateTrieNode(key []byte) ([]byte, error)
HasStateTrieNode(key []byte) (bool, error)
// from accessors_indexes.go
ReadTxLookupEntry(hash common.Hash) (common.Hash, uint64, uint64)
WriteTxLookupEntries(block *types.Block)
WriteAndCacheTxLookupEntries(block *types.Block) error
PutTxLookupEntriesToBatch(batch Batch, block *types.Block)
DeleteTxLookupEntry(hash common.Hash)
ReadTxAndLookupInfo(hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64)
NewSenderTxHashToTxHashBatch() Batch
PutSenderTxHashToTxHashToBatch(batch Batch, senderTxHash, txHash common.Hash) error
ReadTxHashFromSenderTxHash(senderTxHash common.Hash) common.Hash
ReadBloomBits(bloomBitsKey []byte) ([]byte, error)
WriteBloomBits(bloomBitsKey []byte, bits []byte) error
ReadValidSections() ([]byte, error)
WriteValidSections(encodedSections []byte)
ReadSectionHead(encodedSection []byte) ([]byte, error)
WriteSectionHead(encodedSection []byte, hash common.Hash)
DeleteSectionHead(encodedSection []byte)
// from accessors_metadata.go
ReadDatabaseVersion() *uint64
WriteDatabaseVersion(version uint64)
ReadChainConfig(hash common.Hash) *params.ChainConfig
WriteChainConfig(hash common.Hash, cfg *params.ChainConfig)
ReadPreimage(hash common.Hash) []byte
WritePreimages(number uint64, preimages map[common.Hash][]byte)
// below operations are used in parent chain side, not child chain side.
WriteChildChainTxHash(ccBlockHash common.Hash, ccTxHash common.Hash)
ConvertChildChainBlockHashToParentChainTxHash(scBlockHash common.Hash) common.Hash
WriteLastIndexedBlockNumber(blockNum uint64)
GetLastIndexedBlockNumber() uint64
// below operations are used in child chain side, not parent chain side.
WriteAnchoredBlockNumber(blockNum uint64)
ReadAnchoredBlockNumber() uint64
WriteReceiptFromParentChain(blockHash common.Hash, receipt *types.Receipt)
ReadReceiptFromParentChain(blockHash common.Hash) *types.Receipt
WriteHandleTxHashFromRequestTxHash(rTx, hTx common.Hash)
ReadHandleTxHashFromRequestTxHash(rTx common.Hash) common.Hash
// cacheManager related functions.
ClearHeaderChainCache()
ClearBlockChainCache()
ReadTxAndLookupInfoInCache(hash common.Hash) (*types.Transaction, common.Hash, uint64, uint64)
ReadBlockReceiptsInCache(blockHash common.Hash) types.Receipts
ReadTxReceiptInCache(txHash common.Hash) *types.Receipt
// snapshot in clique(ConsensusClique) consensus
WriteCliqueSnapshot(snapshotBlockHash common.Hash, encodedSnapshot []byte) error
ReadCliqueSnapshot(snapshotBlockHash common.Hash) ([]byte, error)
// Governance related functions
WriteGovernance(data map[string]interface{}, num uint64) error
WriteGovernanceIdx(num uint64) error
ReadGovernance(num uint64) (map[string]interface{}, error)
ReadRecentGovernanceIdx(count int) ([]uint64, error)
ReadGovernanceAtNumber(num uint64, epoch uint64) (uint64, map[string]interface{}, error)
WriteGovernanceState(b []byte) error
ReadGovernanceState() ([]byte, error)
}
type DBEntryType uint8
const (
headerDB DBEntryType = iota
BodyDB
ReceiptsDB
StateTrieDB
TxLookUpEntryDB
MiscDB
bridgeServiceDB
// databaseEntryTypeSize should be the last item in this list!!
databaseEntryTypeSize
)
var dbDirs = [databaseEntryTypeSize]string{
"header",
"body",
"receipts",
"statetrie",
"txlookup",
"misc",
"bridgeservice",
}
// Sum of dbConfigRatio should be 100.
// Otherwise, logger.Crit will be called at checkDBEntryConfigRatio.
var dbConfigRatio = [databaseEntryTypeSize]int{
6, // headerDB
21, // BodyDB
21, // ReceiptsDB
23, // StateTrieDB
21, // TXLookUpEntryDB
3, // MiscDB
5, // bridgeServiceDB
}
// checkDBEntryConfigRatio checks if sum of dbConfigRatio is 100.
// If it isn't, logger.Crit is called.
func checkDBEntryConfigRatio() {
entryConfigRatioSum := 0
for i := 0; i < int(databaseEntryTypeSize); i++ {
entryConfigRatioSum += dbConfigRatio[i]
}
if entryConfigRatioSum != 100 {
logger.Crit("Sum of dbConfigRatio elements should be 100", "actual", entryConfigRatioSum)
}
}
// getDBEntryConfig returns a new DBConfig with original DBConfig and DBEntryType.
// It adjusts configuration according to the ratio specified in dbConfigRatio and dbDirs.
func getDBEntryConfig(originalDBC *DBConfig, i DBEntryType) *DBConfig {
newDBC := *originalDBC
ratio := dbConfigRatio[i]
newDBC.LevelDBCacheSize = originalDBC.LevelDBCacheSize * ratio / 100
newDBC.OpenFilesLimit = originalDBC.OpenFilesLimit * ratio / 100
// Update dir to each Database specific directory.
newDBC.Dir = filepath.Join(originalDBC.Dir, dbDirs[i])
return &newDBC
}
type databaseManager struct {
config *DBConfig
dbs []Database
cm *cacheManager
}
func NewMemoryDBManager() DBManager {
dbc := &DBConfig{DBType: MemoryDB}
dbm := databaseManager{
config: dbc,
dbs: make([]Database, 1, 1),
cm: newCacheManager(),
}
dbm.dbs[0] = NewMemDB()
return &dbm
}
// DBConfig handles database related configurations.
type DBConfig struct {
// General configurations for all types of DB.
Dir string
DBType DBType
Partitioned bool
NumStateTriePartitions uint
ParallelDBWrite bool
OpenFilesLimit int
// LevelDB related configurations.
LevelDBCacheSize int // LevelDBCacheSize = BlockCacheCapacity + WriteBuffer
LevelDBCompression LevelDBCompressionType
LevelDBBufferPool bool
}
const dbMetricPrefix = "klay/db/chaindata/"
// singleDatabaseDBManager returns DBManager which handles one single Database.
// Each Database will share one common Database.
func singleDatabaseDBManager(dbc *DBConfig) (DBManager, error) {
dbm := newDatabaseManager(dbc)
db, err := newDatabase(dbc, 0)
if err != nil {
return nil, err
}
db.Meter(dbMetricPrefix)
for i := 0; i < int(databaseEntryTypeSize); i++ {
dbm.dbs[i] = db
}
return dbm, nil
}
// partitionedDatabaseDBManager returns DBManager which handles partitioned Database.
// Each Database will have its own separated Database.
func partitionedDatabaseDBManager(dbc *DBConfig) (DBManager, error) {
dbm := newDatabaseManager(dbc)
var db Database
var err error
for et := 0; et < int(databaseEntryTypeSize); et++ {
entryType := DBEntryType(et)
newDBC := getDBEntryConfig(dbc, entryType)
if entryType == StateTrieDB && dbc.NumStateTriePartitions > 1 {
db, err = newPartitionedDB(newDBC, entryType, dbc.NumStateTriePartitions)
} else {
db, err = newDatabase(newDBC, entryType)
}
if err != nil {
logger.Crit("Failed while generating a partition of LevelDB", "partition", dbDirs[et], "err", err)
}
dbm.dbs[et] = db
db.Meter(dbMetricPrefix + dbDirs[et] + "/") // Each partition collects metrics independently.
}
return dbm, nil
}
// newDatabase returns Database interface with given DBConfig.
func newDatabase(dbc *DBConfig, entryType DBEntryType) (Database, error) {
switch dbc.DBType {
case LevelDB:
return NewLevelDB(dbc, entryType)
case BadgerDB:
return NewBadgerDB(dbc.Dir)
case MemoryDB:
return NewMemDB(), nil
default:
logger.Info("database type is not set, fall back to default LevelDB")
return NewLevelDB(dbc, 0)
}
}
// newDatabaseManager returns the pointer of databaseManager with default configuration.
func newDatabaseManager(dbc *DBConfig) *databaseManager {
return &databaseManager{
config: dbc,
dbs: make([]Database, databaseEntryTypeSize),
cm: newCacheManager(),
}
}
// NewDBManager returns DBManager interface.
// If Partitioned is true, each Database will have its own LevelDB.
// If not, each Database will share one common LevelDB.
func NewDBManager(dbc *DBConfig) DBManager {
if !dbc.Partitioned {
logger.Info("Non-partitioned database is used for persistent storage", "DBType", dbc.DBType)
if dbm, err := singleDatabaseDBManager(dbc); err != nil {
logger.Crit("Failed to create non-partitioned database", "DBType", dbc.DBType, "err", err)
} else {
return dbm
}
} else {
checkDBEntryConfigRatio()
logger.Info("Partitioned database is used for persistent storage", "DBType", dbc.DBType)
if dbm, err := partitionedDatabaseDBManager(dbc); err != nil {
logger.Crit("Failed to partitioned database", "DBType", dbc.DBType, "err", err)
} else {
return dbm
}
}
logger.Crit("Must not reach here!")
return nil
}
func (dbm *databaseManager) IsParallelDBWrite() bool {
return dbm.config.ParallelDBWrite
}
func (dbm *databaseManager) NewBatch(dbEntryType DBEntryType) Batch {
return dbm.getDatabase(dbEntryType).NewBatch()
}
func (dbm *databaseManager) GetMemDB() *MemDB {
if dbm.config.DBType == MemoryDB {
if memDB, ok := dbm.dbs[0].(*MemDB); ok {
return memDB
} else {
logger.Error("DBManager is set as memory DBManager, but actual value is not set as memory DBManager.")
return nil
}
}
logger.Error("GetMemDB() call to non memory DBManager object.")
return nil
}
// GetDBConfig returns DBConfig of the DB manager.
func (dbm *databaseManager) GetDBConfig() *DBConfig {
return dbm.config
}
func (dbm *databaseManager) getDatabase(dbEntryType DBEntryType) Database {
if dbm.config.DBType == MemoryDB {
return dbm.dbs[headerDB]
} else {
return dbm.dbs[dbEntryType]
}
}
func (dbm *databaseManager) Close() {
// If not partitioned, only close the first database.
if !dbm.config.Partitioned {
dbm.dbs[0].Close()
return
}
// If partitioned, close all databases.
for _, db := range dbm.dbs {
db.Close()
}
}
// TODO-Klaytn Some of below need to be invisible outside database package
// Canonical Hash operations.
// ReadCanonicalHash retrieves the hash assigned to a canonical block number.
func (dbm *databaseManager) ReadCanonicalHash(number uint64) common.Hash {
if cached := dbm.cm.readCanonicalHashCache(number); !common.EmptyHash(cached) {
return cached
}
db := dbm.getDatabase(headerDB)
data, _ := db.Get(headerHashKey(number))
if len(data) == 0 {
return common.Hash{}
}
hash := common.BytesToHash(data)
dbm.cm.writeCanonicalHashCache(number, hash)
return hash
}
// WriteCanonicalHash stores the hash assigned to a canonical block number.
func (dbm *databaseManager) WriteCanonicalHash(hash common.Hash, number uint64) {
db := dbm.getDatabase(headerDB)
if err := db.Put(headerHashKey(number), hash.Bytes()); err != nil {
logger.Crit("Failed to store number to hash mapping", "err", err)
}
dbm.cm.writeCanonicalHashCache(number, hash)
}
// DeleteCanonicalHash removes the number to hash canonical mapping.
func (dbm *databaseManager) DeleteCanonicalHash(number uint64) {
db := dbm.getDatabase(headerDB)
if err := db.Delete(headerHashKey(number)); err != nil {
logger.Crit("Failed to delete number to hash mapping", "err", err)
}
dbm.cm.writeCanonicalHashCache(number, common.Hash{})
}
// Head Header Hash operations.
// ReadHeadHeaderHash retrieves the hash of the current canonical head header.
func (dbm *databaseManager) ReadHeadHeaderHash() common.Hash {
db := dbm.getDatabase(headerDB)
data, _ := db.Get(headHeaderKey)
if len(data) == 0 {
return common.Hash{}
}
return common.BytesToHash(data)
}
// WriteHeadHeaderHash stores the hash of the current canonical head header.
func (dbm *databaseManager) WriteHeadHeaderHash(hash common.Hash) {
db := dbm.getDatabase(headerDB)
if err := db.Put(headHeaderKey, hash.Bytes()); err != nil {
logger.Crit("Failed to store last header's hash", "err", err)
}
}
// Block Hash operations.
func (dbm *databaseManager) ReadHeadBlockHash() common.Hash {
db := dbm.getDatabase(headerDB)
data, _ := db.Get(headBlockKey)
if len(data) == 0 {
return common.Hash{}
}
return common.BytesToHash(data)
}
// WriteHeadBlockHash stores the head block's hash.
func (dbm *databaseManager) WriteHeadBlockHash(hash common.Hash) {
db := dbm.getDatabase(headerDB)
if err := db.Put(headBlockKey, hash.Bytes()); err != nil {
logger.Crit("Failed to store last block's hash", "err", err)
}
}
// Head Fast Block Hash operations.
// ReadHeadFastBlockHash retrieves the hash of the current fast-sync head block.
func (dbm *databaseManager) ReadHeadFastBlockHash() common.Hash {
db := dbm.getDatabase(headerDB)
data, _ := db.Get(headFastBlockKey)
if len(data) == 0 {
return common.Hash{}
}
return common.BytesToHash(data)
}
// WriteHeadFastBlockHash stores the hash of the current fast-sync head block.
func (dbm *databaseManager) WriteHeadFastBlockHash(hash common.Hash) {
db := dbm.getDatabase(headerDB)
if err := db.Put(headFastBlockKey, hash.Bytes()); err != nil {
logger.Crit("Failed to store last fast block's hash", "err", err)
}
}
// Fast Trie Progress operations.
// ReadFastTrieProgress retrieves the number of tries nodes fast synced to allow
// reporting correct numbers across restarts.
func (dbm *databaseManager) ReadFastTrieProgress() uint64 {
db := dbm.getDatabase(MiscDB)
data, _ := db.Get(fastTrieProgressKey)
if len(data) == 0 {
return 0
}
return new(big.Int).SetBytes(data).Uint64()
}
// WriteFastTrieProgress stores the fast sync trie process counter to support
// retrieving it across restarts.
func (dbm *databaseManager) WriteFastTrieProgress(count uint64) {
db := dbm.getDatabase(MiscDB)
if err := db.Put(fastTrieProgressKey, new(big.Int).SetUint64(count).Bytes()); err != nil {
logger.Crit("Failed to store fast sync trie progress", "err", err)
}
}
// (Block)Header operations.
// HasHeader verifies the existence of a block header corresponding to the hash.
func (dbm *databaseManager) HasHeader(hash common.Hash, number uint64) bool {
if dbm.cm.hasHeaderInCache(hash) {
return true
}
db := dbm.getDatabase(headerDB)
if has, err := db.Has(headerKey(number, hash)); !has || err != nil {
return false
}
return true
}
// ReadHeader retrieves the block header corresponding to the hash.
func (dbm *databaseManager) ReadHeader(hash common.Hash, number uint64) *types.Header {
if cachedHeader := dbm.cm.readHeaderCache(hash); cachedHeader != nil {
return cachedHeader
}
data := dbm.ReadHeaderRLP(hash, number)
if len(data) == 0 {
return nil
}
header := new(types.Header)
if err := rlp.Decode(bytes.NewReader(data), header); err != nil {
logger.Error("Invalid block header RLP", "hash", hash, "err", err)
return nil
}
// Write to cache before returning found value.
dbm.cm.writeHeaderCache(hash, header)
return header
}
// ReadHeaderRLP retrieves a block header in its raw RLP database encoding.
func (dbm *databaseManager) ReadHeaderRLP(hash common.Hash, number uint64) rlp.RawValue {
db := dbm.getDatabase(headerDB)
data, _ := db.Get(headerKey(number, hash))
return data
}
// WriteHeader stores a block header into the database and also stores the hash-
// to-number mapping.
func (dbm *databaseManager) WriteHeader(header *types.Header) {
db := dbm.getDatabase(headerDB)
// Write the hash -> number mapping
var (
hash = header.Hash()
number = header.Number.Uint64()
encoded = encodeBlockNumber(number)
)
key := headerNumberKey(hash)
if err := db.Put(key, encoded); err != nil {
logger.Crit("Failed to store hash to number mapping", "err", err)
}
// Write the encoded header
data, err := rlp.EncodeToBytes(header)
if err != nil {
logger.Crit("Failed to RLP encode header", "err", err)
}
key = headerKey(number, hash)
if err := db.Put(key, data); err != nil {
logger.Crit("Failed to store header", "err", err)
}
// Write to cache at the end of successful write.
dbm.cm.writeHeaderCache(hash, header)
dbm.cm.writeBlockNumberCache(hash, number)
}
// DeleteHeader removes all block header data associated with a hash.
func (dbm *databaseManager) DeleteHeader(hash common.Hash, number uint64) {
db := dbm.getDatabase(headerDB)
if err := db.Delete(headerKey(number, hash)); err != nil {
logger.Crit("Failed to delete header", "err", err)
}
if err := db.Delete(headerNumberKey(hash)); err != nil {
logger.Crit("Failed to delete hash to number mapping", "err", err)
}
// Delete cache at the end of successful delete.
dbm.cm.deleteHeaderCache(hash)
dbm.cm.deleteBlockNumberCache(hash)
}
// Head Number operations.
// ReadHeaderNumber returns the header number assigned to a hash.
func (dbm *databaseManager) ReadHeaderNumber(hash common.Hash) *uint64 {
if cachedHeaderNumber := dbm.cm.readBlockNumberCache(hash); cachedHeaderNumber != nil {
return cachedHeaderNumber
}
db := dbm.getDatabase(headerDB)
data, _ := db.Get(headerNumberKey(hash))
if len(data) != 8 {
return nil
}
number := binary.BigEndian.Uint64(data)
// Write to cache before returning found value.
dbm.cm.writeBlockNumberCache(hash, number)
return &number
}
// (Block)Body operations.
// HasBody verifies the existence of a block body corresponding to the hash.
func (dbm *databaseManager) HasBody(hash common.Hash, number uint64) bool {
db := dbm.getDatabase(BodyDB)
if has, err := db.Has(blockBodyKey(number, hash)); !has || err != nil {
return false
}
return true
}
// ReadBody retrieves the block body corresponding to the hash.
func (dbm *databaseManager) ReadBody(hash common.Hash, number uint64) *types.Body {
if cachedBody := dbm.cm.readBodyCache(hash); cachedBody != nil {
return cachedBody
}
data := dbm.ReadBodyRLP(hash, number)
if len(data) == 0 {
return nil
}
body := new(types.Body)
if err := rlp.Decode(bytes.NewReader(data), body); err != nil {
logger.Error("Invalid block body RLP", "hash", hash, "err", err)
return nil
}
// Write to cache at the end of successful read.
dbm.cm.writeBodyCache(hash, body)
return body
}
// ReadBodyInCache retrieves the block body in bodyCache.
// It only searches cache.
func (dbm *databaseManager) ReadBodyInCache(hash common.Hash) *types.Body {
return dbm.cm.readBodyCache(hash)
}
// ReadBodyRLP retrieves the block body (transactions) in RLP encoding.
func (dbm *databaseManager) ReadBodyRLP(hash common.Hash, number uint64) rlp.RawValue {
// Short circuit if the rlp encoded body's already in the cache, retrieve otherwise
if cachedBodyRLP := dbm.readBodyRLPInCache(hash); cachedBodyRLP != nil {
return cachedBodyRLP
}
// find cached body and encode it to return
if cachedBody := dbm.ReadBodyInCache(hash); cachedBody != nil {
if bodyRLP, err := rlp.EncodeToBytes(cachedBody); err != nil {
dbm.cm.writeBodyRLPCache(hash, bodyRLP)
return bodyRLP
}
}
// not found in cache, find body in database
db := dbm.getDatabase(BodyDB)
data, _ := db.Get(blockBodyKey(number, hash))
// Write to cache at the end of successful read.
dbm.cm.writeBodyRLPCache(hash, data)
return data
}
// ReadBodyRLPByHash retrieves the block body (transactions) in RLP encoding.
func (dbm *databaseManager) ReadBodyRLPByHash(hash common.Hash) rlp.RawValue {
// Short circuit if the rlp encoded body's already in the cache, retrieve otherwise
if cachedBodyRLP := dbm.readBodyRLPInCache(hash); cachedBodyRLP != nil {
return cachedBodyRLP
}
// find cached body and encode it to return
if cachedBody := dbm.ReadBodyInCache(hash); cachedBody != nil {
if bodyRLP, err := rlp.EncodeToBytes(cachedBody); err != nil {
dbm.cm.writeBodyRLPCache(hash, bodyRLP)
return bodyRLP
}
}
// not found in cache, find body in database
number := dbm.ReadHeaderNumber(hash)
if number == nil {
return nil
}
db := dbm.getDatabase(BodyDB)
data, _ := db.Get(blockBodyKey(*number, hash))
// Write to cache at the end of successful read.
dbm.cm.writeBodyRLPCache(hash, data)
return data
}
// readBodyRLPInCache retrieves the block body (transactions) in RLP encoding
// in bodyRLPCache. It only searches cache.
func (dbm *databaseManager) readBodyRLPInCache(hash common.Hash) rlp.RawValue {
return dbm.cm.readBodyRLPCache(hash)
}
// WriteBody storea a block body into the database.
func (dbm *databaseManager) WriteBody(hash common.Hash, number uint64, body *types.Body) {
data, err := rlp.EncodeToBytes(body)
if err != nil {
logger.Crit("Failed to RLP encode body", "err", err)
}
dbm.WriteBodyRLP(hash, number, data)
}
func (dbm *databaseManager) PutBodyToBatch(batch Batch, hash common.Hash, number uint64, body *types.Body) {
data, err := rlp.EncodeToBytes(body)
if err != nil {
logger.Crit("Failed to RLP encode body", "err", err)
}
if err := batch.Put(blockBodyKey(number, hash), data); err != nil {
logger.Crit("Failed to store block body", "err", err)
}
}
// WriteBodyRLP stores an RLP encoded block body into the database.
func (dbm *databaseManager) WriteBodyRLP(hash common.Hash, number uint64, rlp rlp.RawValue) {
db := dbm.getDatabase(BodyDB)
if err := db.Put(blockBodyKey(number, hash), rlp); err != nil {
logger.Crit("Failed to store block body", "err", err)
}
if common.WriteThroughCaching {
dbm.cm.writeBodyRLPCache(hash, rlp)
}
}
// DeleteBody removes all block body data associated with a hash.
func (dbm *databaseManager) DeleteBody(hash common.Hash, number uint64) {
db := dbm.getDatabase(BodyDB)
if err := db.Delete(blockBodyKey(number, hash)); err != nil {
logger.Crit("Failed to delete block body", "err", err)
}
dbm.cm.deleteBodyCache(hash)
}
// TotalDifficulty operations.
// ReadTd retrieves a block's total blockscore corresponding to the hash.
func (dbm *databaseManager) ReadTd(hash common.Hash, number uint64) *big.Int {
if cachedTd := dbm.cm.readTdCache(hash); cachedTd != nil {
return cachedTd
}
db := dbm.getDatabase(MiscDB)
data, _ := db.Get(headerTDKey(number, hash))
if len(data) == 0 {
return nil
}
td := new(big.Int)
if err := rlp.Decode(bytes.NewReader(data), td); err != nil {
logger.Error("Invalid block total blockscore RLP", "hash", hash, "err", err)
return nil
}
// Write to cache before returning found value.
dbm.cm.writeTdCache(hash, td)
return td
}
// WriteTd stores the total blockscore of a block into the database.
func (dbm *databaseManager) WriteTd(hash common.Hash, number uint64, td *big.Int) {
db := dbm.getDatabase(MiscDB)
data, err := rlp.EncodeToBytes(td)
if err != nil {
logger.Crit("Failed to RLP encode block total blockscore", "err", err)
}
if err := db.Put(headerTDKey(number, hash), data); err != nil {
logger.Crit("Failed to store block total blockscore", "err", err)
}
// Write to cache at the end of successful write.
dbm.cm.writeTdCache(hash, td)
}
// DeleteTd removes all block total blockscore data associated with a hash.
func (dbm *databaseManager) DeleteTd(hash common.Hash, number uint64) {
db := dbm.getDatabase(MiscDB)
if err := db.Delete(headerTDKey(number, hash)); err != nil {
logger.Crit("Failed to delete block total blockscore", "err", err)
}
// Delete cache at the end of successful delete.
dbm.cm.deleteTdCache(hash)
}
// Receipts operations.
// ReadReceipt retrieves a receipt, blockHash, blockNumber and receiptIndex found by the given txHash.
func (dbm *databaseManager) ReadReceipt(txHash common.Hash) (*types.Receipt, common.Hash, uint64, uint64) {
blockHash, blockNumber, receiptIndex := dbm.ReadTxLookupEntry(txHash)
if blockHash == (common.Hash{}) {
return nil, common.Hash{}, 0, 0
}
receipts := dbm.ReadReceipts(blockHash, blockNumber)
if len(receipts) <= int(receiptIndex) {
logger.Error("Receipt refereced missing", "number", blockNumber, "txHash", blockHash, "index", receiptIndex)
return nil, common.Hash{}, 0, 0
}
return receipts[receiptIndex], blockHash, blockNumber, receiptIndex
}
// ReadReceipts retrieves all the transaction receipts belonging to a block.
func (dbm *databaseManager) ReadReceipts(blockHash common.Hash, number uint64) types.Receipts {
db := dbm.getDatabase(ReceiptsDB)
// Retrieve the flattened receipt slice
data, _ := db.Get(blockReceiptsKey(number, blockHash))
if len(data) == 0 {
return nil
}
// Convert the revceipts from their database form to their internal representation
storageReceipts := []*types.ReceiptForStorage{}
if err := rlp.DecodeBytes(data, &storageReceipts); err != nil {
logger.Error("Invalid receipt array RLP", "blockHash", blockHash, "err", err)
return nil
}
receipts := make(types.Receipts, len(storageReceipts))
for i, receipt := range storageReceipts {
receipts[i] = (*types.Receipt)(receipt)
}
return receipts
}
func (dbm *databaseManager) ReadReceiptsByBlockHash(hash common.Hash) types.Receipts {
receipts := dbm.ReadBlockReceiptsInCache(hash)
if receipts != nil {
return receipts
}
number := dbm.ReadHeaderNumber(hash)
if number == nil {
return nil
}
return dbm.ReadReceipts(hash, *number)
}
// WriteReceipts stores all the transaction receipts belonging to a block.
func (dbm *databaseManager) WriteReceipts(hash common.Hash, number uint64, receipts types.Receipts) {
db := dbm.getDatabase(ReceiptsDB)
// When putReceiptsToPutter is called from WriteReceipts, txReceipt is cached.
dbm.putReceiptsToPutter(db, hash, number, receipts, true)
if common.WriteThroughCaching {
// TODO-Klaytn goroutine for performance
dbm.cm.writeBlockReceiptsCache(hash, receipts)
}
}
func (dbm *databaseManager) PutReceiptsToBatch(batch Batch, hash common.Hash, number uint64, receipts types.Receipts) {
// When putReceiptsToPutter is called from PutReceiptsToBatch, txReceipt is not cached.
dbm.putReceiptsToPutter(batch, hash, number, receipts, false)
}
func (dbm *databaseManager) putReceiptsToPutter(putter Putter, hash common.Hash, number uint64, receipts types.Receipts, addToCache bool) {
// Convert the receipts into their database form and serialize them
storageReceipts := make([]*types.ReceiptForStorage, len(receipts))
for i, receipt := range receipts {
storageReceipts[i] = (*types.ReceiptForStorage)(receipt)
if addToCache {
dbm.cm.writeTxReceiptCache(receipt.TxHash, receipt)
}
}
bytes, err := rlp.EncodeToBytes(storageReceipts)
if err != nil {
logger.Crit("Failed to encode block receipts", "err", err)
}
// Store the flattened receipt slice
if err := putter.Put(blockReceiptsKey(number, hash), bytes); err != nil {
logger.Crit("Failed to store block receipts", "err", err)
}
}
// DeleteReceipts removes all receipt data associated with a block hash.
func (dbm *databaseManager) DeleteReceipts(hash common.Hash, number uint64) {
receipts := dbm.ReadReceipts(hash, number)
db := dbm.getDatabase(ReceiptsDB)
if err := db.Delete(blockReceiptsKey(number, hash)); err != nil {
logger.Crit("Failed to delete block receipts", "err", err)
}
// Delete blockReceiptsCache and txReceiptCache.
dbm.cm.deleteBlockReceiptsCache(hash)
if receipts != nil {
for _, receipt := range receipts {
dbm.cm.deleteTxReceiptCache(receipt.TxHash)
}
}
}
// Block operations.
// ReadBlock retrieves an entire block corresponding to the hash, assembling it
// back from the stored header and body. If either the header or body could not
// be retrieved nil is returned.
//
// Note, due to concurrent download of header and block body the header and thus
// canonical hash can be stored in the database but the body data not (yet).
func (dbm *databaseManager) ReadBlock(hash common.Hash, number uint64) *types.Block {
if cachedBlock := dbm.cm.readBlockCache(hash); cachedBlock != nil {
return cachedBlock
}
header := dbm.ReadHeader(hash, number)
if header == nil {
return nil
}
body := dbm.ReadBody(hash, number)
if body == nil {
return nil
}
block := types.NewBlockWithHeader(header).WithBody(body.Transactions)
// Write to cache at the end of successful write.
dbm.cm.writeBlockCache(hash, block)
return block
}
func (dbm *databaseManager) ReadBlockByHash(hash common.Hash) *types.Block {
if cachedBlock := dbm.cm.readBlockCache(hash); cachedBlock != nil {
return cachedBlock
}
number := dbm.ReadHeaderNumber(hash)
if number == nil {
return nil
}
header := dbm.ReadHeader(hash, *number)
if header == nil {
return nil
}
body := dbm.ReadBody(hash, *number)
if body == nil {
return nil
}
block := types.NewBlockWithHeader(header).WithBody(body.Transactions)
// Write to cache at the end of successful write.
dbm.cm.writeBlockCache(hash, block)
return block
}
func (dbm *databaseManager) ReadBlockByNumber(number uint64) *types.Block {
hash := dbm.ReadCanonicalHash(number)
if hash == (common.Hash{}) {
return nil
}
return dbm.ReadBlock(hash, number)
}
func (dbm *databaseManager) HasBlock(hash common.Hash, number uint64) bool {
if dbm.cm.hasBlockInCache(hash) {
return true
}
return dbm.HasBody(hash, number)
}
func (dbm *databaseManager) WriteBlock(block *types.Block) {
dbm.WriteBody(block.Hash(), block.NumberU64(), block.Body())
dbm.WriteHeader(block.Header())
if common.WriteThroughCaching {
dbm.cm.writeBodyCache(block.Hash(), block.Body())
dbm.cm.blockCache.Add(block.Hash(), block)
}