|
| 1 | +// Copyright 2022 The go-ethereum Authors |
| 2 | +// This file is part of the go-ethereum library. |
| 3 | +// |
| 4 | +// The go-ethereum library is free software: you can redistribute it and/or modify |
| 5 | +// it under the terms of the GNU Lesser General Public License as published by |
| 6 | +// the Free Software Foundation, either version 3 of the License, or |
| 7 | +// (at your option) any later version. |
| 8 | +// |
| 9 | +// The go-ethereum library is distributed in the hope that it will be useful, |
| 10 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +// GNU Lesser General Public License for more details. |
| 13 | +// |
| 14 | +// You should have received a copy of the GNU Lesser General Public License |
| 15 | +// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +package rawdb |
| 18 | + |
| 19 | +import ( |
| 20 | + "fmt" |
| 21 | + "sync" |
| 22 | + "sync/atomic" |
| 23 | + "time" |
| 24 | + |
| 25 | + "github.com/ethereum/go-ethereum/common" |
| 26 | + "github.com/ethereum/go-ethereum/ethdb" |
| 27 | + "github.com/ethereum/go-ethereum/log" |
| 28 | + "github.com/ethereum/go-ethereum/params" |
| 29 | +) |
| 30 | + |
| 31 | +const ( |
| 32 | + // freezerRecheckInterval is the frequency to check the key-value database for |
| 33 | + // chain progression that might permit new blocks to be frozen into immutable |
| 34 | + // storage. |
| 35 | + freezerRecheckInterval = time.Minute |
| 36 | + |
| 37 | + // freezerBatchLimit is the maximum number of blocks to freeze in one batch |
| 38 | + // before doing an fsync and deleting it from the key-value store. |
| 39 | + freezerBatchLimit = 30000 |
| 40 | +) |
| 41 | + |
| 42 | +// chainFreezer is a wrapper of freezer with additional chain freezing feature. |
| 43 | +// The background thread will keep moving ancient chain segments from key-value |
| 44 | +// database to flat files for saving space on live database. |
| 45 | +type chainFreezer struct { |
| 46 | + *Freezer |
| 47 | + |
| 48 | + threshold uint64 // Number of recent blocks not to freeze (params.FullImmutabilityThreshold apart from tests) |
| 49 | + quit chan struct{} |
| 50 | + wg sync.WaitGroup |
| 51 | + closeOnce sync.Once |
| 52 | + trigger chan chan struct{} // Manual blocking freeze trigger, test determinism |
| 53 | +} |
| 54 | + |
| 55 | +// newChainFreezer initializes the freezer for ancient chain data. |
| 56 | +func newChainFreezer(datadir string, namespace string, readonly bool, maxTableSize uint32, tables map[string]bool) (*chainFreezer, error) { |
| 57 | + freezer, err := NewFreezer(datadir, namespace, readonly, maxTableSize, tables) |
| 58 | + if err != nil { |
| 59 | + return nil, err |
| 60 | + } |
| 61 | + return &chainFreezer{ |
| 62 | + Freezer: freezer, |
| 63 | + threshold: params.FullImmutabilityThreshold, |
| 64 | + quit: make(chan struct{}), |
| 65 | + trigger: make(chan chan struct{}), |
| 66 | + }, nil |
| 67 | +} |
| 68 | + |
| 69 | +// Close closes the chain freezer instance and terminates the background thread. |
| 70 | +func (f *chainFreezer) Close() error { |
| 71 | + err := f.Freezer.Close() |
| 72 | + select { |
| 73 | + case <-f.quit: |
| 74 | + default: |
| 75 | + close(f.quit) |
| 76 | + } |
| 77 | + f.wg.Wait() |
| 78 | + return err |
| 79 | +} |
| 80 | + |
| 81 | +// freeze is a background thread that periodically checks the blockchain for any |
| 82 | +// import progress and moves ancient data from the fast database into the freezer. |
| 83 | +// |
| 84 | +// This functionality is deliberately broken off from block importing to avoid |
| 85 | +// incurring additional data shuffling delays on block propagation. |
| 86 | +func (f *chainFreezer) freeze(db ethdb.KeyValueStore) { |
| 87 | + nfdb := &nofreezedb{KeyValueStore: db} |
| 88 | + |
| 89 | + var ( |
| 90 | + backoff bool |
| 91 | + triggered chan struct{} // Used in tests |
| 92 | + ) |
| 93 | + for { |
| 94 | + select { |
| 95 | + case <-f.quit: |
| 96 | + log.Info("Freezer shutting down") |
| 97 | + return |
| 98 | + default: |
| 99 | + } |
| 100 | + if backoff { |
| 101 | + // If we were doing a manual trigger, notify it |
| 102 | + if triggered != nil { |
| 103 | + triggered <- struct{}{} |
| 104 | + triggered = nil |
| 105 | + } |
| 106 | + select { |
| 107 | + case <-time.NewTimer(freezerRecheckInterval).C: |
| 108 | + backoff = false |
| 109 | + case triggered = <-f.trigger: |
| 110 | + backoff = false |
| 111 | + case <-f.quit: |
| 112 | + return |
| 113 | + } |
| 114 | + } |
| 115 | + // Retrieve the freezing threshold. |
| 116 | + hash := ReadHeadBlockHash(nfdb) |
| 117 | + if hash == (common.Hash{}) { |
| 118 | + log.Debug("Current full block hash unavailable") // new chain, empty database |
| 119 | + backoff = true |
| 120 | + continue |
| 121 | + } |
| 122 | + number := ReadHeaderNumber(nfdb, hash) |
| 123 | + threshold := atomic.LoadUint64(&f.threshold) |
| 124 | + |
| 125 | + switch { |
| 126 | + case number == nil: |
| 127 | + log.Error("Current full block number unavailable", "hash", hash) |
| 128 | + backoff = true |
| 129 | + continue |
| 130 | + |
| 131 | + case *number < threshold: |
| 132 | + log.Debug("Current full block not old enough", "number", *number, "hash", hash, "delay", threshold) |
| 133 | + backoff = true |
| 134 | + continue |
| 135 | + |
| 136 | + case *number-threshold <= f.frozen: |
| 137 | + log.Debug("Ancient blocks frozen already", "number", *number, "hash", hash, "frozen", f.frozen) |
| 138 | + backoff = true |
| 139 | + continue |
| 140 | + } |
| 141 | + head := ReadHeader(nfdb, hash, *number) |
| 142 | + if head == nil { |
| 143 | + log.Error("Current full block unavailable", "number", *number, "hash", hash) |
| 144 | + backoff = true |
| 145 | + continue |
| 146 | + } |
| 147 | + |
| 148 | + // Seems we have data ready to be frozen, process in usable batches |
| 149 | + var ( |
| 150 | + start = time.Now() |
| 151 | + first, _ = f.Ancients() |
| 152 | + limit = *number - threshold |
| 153 | + ) |
| 154 | + if limit-first > freezerBatchLimit { |
| 155 | + limit = first + freezerBatchLimit |
| 156 | + } |
| 157 | + ancients, err := f.freezeRange(nfdb, first, limit) |
| 158 | + if err != nil { |
| 159 | + log.Error("Error in block freeze operation", "err", err) |
| 160 | + backoff = true |
| 161 | + continue |
| 162 | + } |
| 163 | + |
| 164 | + // Batch of blocks have been frozen, flush them before wiping from leveldb |
| 165 | + if err := f.Sync(); err != nil { |
| 166 | + log.Crit("Failed to flush frozen tables", "err", err) |
| 167 | + } |
| 168 | + |
| 169 | + // Wipe out all data from the active database |
| 170 | + batch := db.NewBatch() |
| 171 | + for i := 0; i < len(ancients); i++ { |
| 172 | + // Always keep the genesis block in active database |
| 173 | + if first+uint64(i) != 0 { |
| 174 | + DeleteBlockWithoutNumber(batch, ancients[i], first+uint64(i)) |
| 175 | + DeleteCanonicalHash(batch, first+uint64(i)) |
| 176 | + } |
| 177 | + } |
| 178 | + if err := batch.Write(); err != nil { |
| 179 | + log.Crit("Failed to delete frozen canonical blocks", "err", err) |
| 180 | + } |
| 181 | + batch.Reset() |
| 182 | + |
| 183 | + // Wipe out side chains also and track dangling side chains |
| 184 | + var dangling []common.Hash |
| 185 | + for number := first; number < f.frozen; number++ { |
| 186 | + // Always keep the genesis block in active database |
| 187 | + if number != 0 { |
| 188 | + dangling = ReadAllHashes(db, number) |
| 189 | + for _, hash := range dangling { |
| 190 | + log.Trace("Deleting side chain", "number", number, "hash", hash) |
| 191 | + DeleteBlock(batch, hash, number) |
| 192 | + } |
| 193 | + } |
| 194 | + } |
| 195 | + if err := batch.Write(); err != nil { |
| 196 | + log.Crit("Failed to delete frozen side blocks", "err", err) |
| 197 | + } |
| 198 | + batch.Reset() |
| 199 | + |
| 200 | + // Step into the future and delete and dangling side chains |
| 201 | + if f.frozen > 0 { |
| 202 | + tip := f.frozen |
| 203 | + for len(dangling) > 0 { |
| 204 | + drop := make(map[common.Hash]struct{}) |
| 205 | + for _, hash := range dangling { |
| 206 | + log.Debug("Dangling parent from Freezer", "number", tip-1, "hash", hash) |
| 207 | + drop[hash] = struct{}{} |
| 208 | + } |
| 209 | + children := ReadAllHashes(db, tip) |
| 210 | + for i := 0; i < len(children); i++ { |
| 211 | + // Dig up the child and ensure it's dangling |
| 212 | + child := ReadHeader(nfdb, children[i], tip) |
| 213 | + if child == nil { |
| 214 | + log.Error("Missing dangling header", "number", tip, "hash", children[i]) |
| 215 | + continue |
| 216 | + } |
| 217 | + if _, ok := drop[child.ParentHash]; !ok { |
| 218 | + children = append(children[:i], children[i+1:]...) |
| 219 | + i-- |
| 220 | + continue |
| 221 | + } |
| 222 | + // Delete all block data associated with the child |
| 223 | + log.Debug("Deleting dangling block", "number", tip, "hash", children[i], "parent", child.ParentHash) |
| 224 | + DeleteBlock(batch, children[i], tip) |
| 225 | + } |
| 226 | + dangling = children |
| 227 | + tip++ |
| 228 | + } |
| 229 | + if err := batch.Write(); err != nil { |
| 230 | + log.Crit("Failed to delete dangling side blocks", "err", err) |
| 231 | + } |
| 232 | + } |
| 233 | + |
| 234 | + // Log something friendly for the user |
| 235 | + context := []interface{}{ |
| 236 | + "blocks", f.frozen - first, "elapsed", common.PrettyDuration(time.Since(start)), "number", f.frozen - 1, |
| 237 | + } |
| 238 | + if n := len(ancients); n > 0 { |
| 239 | + context = append(context, []interface{}{"hash", ancients[n-1]}...) |
| 240 | + } |
| 241 | + log.Info("Deep froze chain segment", context...) |
| 242 | + |
| 243 | + // Avoid database thrashing with tiny writes |
| 244 | + if f.frozen-first < freezerBatchLimit { |
| 245 | + backoff = true |
| 246 | + } |
| 247 | + } |
| 248 | +} |
| 249 | + |
| 250 | +func (f *chainFreezer) freezeRange(nfdb *nofreezedb, number, limit uint64) (hashes []common.Hash, err error) { |
| 251 | + hashes = make([]common.Hash, 0, limit-number) |
| 252 | + |
| 253 | + _, err = f.ModifyAncients(func(op ethdb.AncientWriteOp) error { |
| 254 | + for ; number <= limit; number++ { |
| 255 | + // Retrieve all the components of the canonical block. |
| 256 | + hash := ReadCanonicalHash(nfdb, number) |
| 257 | + if hash == (common.Hash{}) { |
| 258 | + return fmt.Errorf("canonical hash missing, can't freeze block %d", number) |
| 259 | + } |
| 260 | + header := ReadHeaderRLP(nfdb, hash, number) |
| 261 | + if len(header) == 0 { |
| 262 | + return fmt.Errorf("block header missing, can't freeze block %d", number) |
| 263 | + } |
| 264 | + body := ReadBodyRLP(nfdb, hash, number) |
| 265 | + if len(body) == 0 { |
| 266 | + return fmt.Errorf("block body missing, can't freeze block %d", number) |
| 267 | + } |
| 268 | + receipts := ReadReceiptsRLP(nfdb, hash, number) |
| 269 | + if len(receipts) == 0 { |
| 270 | + return fmt.Errorf("block receipts missing, can't freeze block %d", number) |
| 271 | + } |
| 272 | + td := ReadTdRLP(nfdb, hash, number) |
| 273 | + if len(td) == 0 { |
| 274 | + return fmt.Errorf("total difficulty missing, can't freeze block %d", number) |
| 275 | + } |
| 276 | + |
| 277 | + // Write to the batch. |
| 278 | + if err := op.AppendRaw(freezerHashTable, number, hash[:]); err != nil { |
| 279 | + return fmt.Errorf("can't write hash to Freezer: %v", err) |
| 280 | + } |
| 281 | + if err := op.AppendRaw(freezerHeaderTable, number, header); err != nil { |
| 282 | + return fmt.Errorf("can't write header to Freezer: %v", err) |
| 283 | + } |
| 284 | + if err := op.AppendRaw(freezerBodiesTable, number, body); err != nil { |
| 285 | + return fmt.Errorf("can't write body to Freezer: %v", err) |
| 286 | + } |
| 287 | + if err := op.AppendRaw(freezerReceiptTable, number, receipts); err != nil { |
| 288 | + return fmt.Errorf("can't write receipts to Freezer: %v", err) |
| 289 | + } |
| 290 | + if err := op.AppendRaw(freezerDifficultyTable, number, td); err != nil { |
| 291 | + return fmt.Errorf("can't write td to Freezer: %v", err) |
| 292 | + } |
| 293 | + |
| 294 | + hashes = append(hashes, hash) |
| 295 | + } |
| 296 | + return nil |
| 297 | + }) |
| 298 | + |
| 299 | + return hashes, err |
| 300 | +} |
0 commit comments