github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/core/state/snapshot/wipe.go (about)

     1  // Copyright 2021 The adkgo Authors
     2  // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8).
     3  //
     4  // the adkgo 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 adkgo 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 adkgo library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package snapshot
    18  
    19  import (
    20  	"bytes"
    21  	"time"
    22  
    23  	"github.com/aidoskuneen/adk-node/common"
    24  	"github.com/aidoskuneen/adk-node/core/rawdb"
    25  	"github.com/aidoskuneen/adk-node/ethdb"
    26  	"github.com/aidoskuneen/adk-node/log"
    27  	"github.com/aidoskuneen/adk-node/metrics"
    28  )
    29  
    30  // wipeSnapshot starts a goroutine to iterate over the entire key-value database
    31  // and delete all the data associated with the snapshot (accounts, storage,
    32  // metadata). After all is done, the snapshot range of the database is compacted
    33  // to free up unused data blocks.
    34  func wipeSnapshot(db ethdb.KeyValueStore, full bool) chan struct{} {
    35  	// Wipe the snapshot root marker synchronously
    36  	if full {
    37  		rawdb.DeleteSnapshotRoot(db)
    38  	}
    39  	// Wipe everything else asynchronously
    40  	wiper := make(chan struct{}, 1)
    41  	go func() {
    42  		if err := wipeContent(db); err != nil {
    43  			log.Error("Failed to wipe state snapshot", "err", err) // Database close will trigger this
    44  			return
    45  		}
    46  		close(wiper)
    47  	}()
    48  	return wiper
    49  }
    50  
    51  // wipeContent iterates over the entire key-value database and deletes all the
    52  // data associated with the snapshot (accounts, storage), but not the root hash
    53  // as the wiper is meant to run on a background thread but the root needs to be
    54  // removed in sync to avoid data races. After all is done, the snapshot range of
    55  // the database is compacted to free up unused data blocks.
    56  func wipeContent(db ethdb.KeyValueStore) error {
    57  	if err := wipeKeyRange(db, "accounts", rawdb.SnapshotAccountPrefix, nil, nil, len(rawdb.SnapshotAccountPrefix)+common.HashLength, snapWipedAccountMeter, true); err != nil {
    58  		return err
    59  	}
    60  	if err := wipeKeyRange(db, "storage", rawdb.SnapshotStoragePrefix, nil, nil, len(rawdb.SnapshotStoragePrefix)+2*common.HashLength, snapWipedStorageMeter, true); err != nil {
    61  		return err
    62  	}
    63  	// Compact the snapshot section of the database to get rid of unused space
    64  	start := time.Now()
    65  
    66  	log.Info("Compacting snapshot account area ")
    67  	end := common.CopyBytes(rawdb.SnapshotAccountPrefix)
    68  	end[len(end)-1]++
    69  
    70  	if err := db.Compact(rawdb.SnapshotAccountPrefix, end); err != nil {
    71  		return err
    72  	}
    73  	log.Info("Compacting snapshot storage area ")
    74  	end = common.CopyBytes(rawdb.SnapshotStoragePrefix)
    75  	end[len(end)-1]++
    76  
    77  	if err := db.Compact(rawdb.SnapshotStoragePrefix, end); err != nil {
    78  		return err
    79  	}
    80  	log.Info("Compacted snapshot area in database", "elapsed", common.PrettyDuration(time.Since(start)))
    81  
    82  	return nil
    83  }
    84  
    85  // wipeKeyRange deletes a range of keys from the database starting with prefix
    86  // and having a specific total key length. The start and limit is optional for
    87  // specifying a particular key range for deletion.
    88  //
    89  // Origin is included for wiping and limit is excluded if they are specified.
    90  func wipeKeyRange(db ethdb.KeyValueStore, kind string, prefix []byte, origin []byte, limit []byte, keylen int, meter metrics.Meter, report bool) error {
    91  	// Batch deletions together to avoid holding an iterator for too long
    92  	var (
    93  		batch = db.NewBatch()
    94  		items int
    95  	)
    96  	// Iterate over the key-range and delete all of them
    97  	start, logged := time.Now(), time.Now()
    98  
    99  	it := db.NewIterator(prefix, origin)
   100  	var stop []byte
   101  	if limit != nil {
   102  		stop = append(prefix, limit...)
   103  	}
   104  	for it.Next() {
   105  		// Skip any keys with the correct prefix but wrong length (trie nodes)
   106  		key := it.Key()
   107  		if !bytes.HasPrefix(key, prefix) {
   108  			break
   109  		}
   110  		if len(key) != keylen {
   111  			continue
   112  		}
   113  		if stop != nil && bytes.Compare(key, stop) >= 0 {
   114  			break
   115  		}
   116  		// Delete the key and periodically recreate the batch and iterator
   117  		batch.Delete(key)
   118  		items++
   119  
   120  		if items%10000 == 0 {
   121  			// Batch too large (or iterator too long lived, flush and recreate)
   122  			it.Release()
   123  			if err := batch.Write(); err != nil {
   124  				return err
   125  			}
   126  			batch.Reset()
   127  			seekPos := key[len(prefix):]
   128  			it = db.NewIterator(prefix, seekPos)
   129  
   130  			if time.Since(logged) > 8*time.Second && report {
   131  				log.Info("Deleting state snapshot leftovers", "kind", kind, "wiped", items, "elapsed", common.PrettyDuration(time.Since(start)))
   132  				logged = time.Now()
   133  			}
   134  		}
   135  	}
   136  	it.Release()
   137  	if err := batch.Write(); err != nil {
   138  		return err
   139  	}
   140  	if meter != nil {
   141  		meter.Mark(int64(items))
   142  	}
   143  	if report {
   144  		log.Info("Deleted state snapshot leftovers", "kind", kind, "wiped", items, "elapsed", common.PrettyDuration(time.Since(start)))
   145  	}
   146  	return nil
   147  }