github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/p2p/enode/nodedb.go (about)

     1  // Copyright 2015 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 enode
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/rand"
    22  	"encoding/binary"
    23  	"fmt"
    24  	"os"
    25  	"sync"
    26  	"time"
    27  
    28  	"github.com/ethereum/go-ethereum/log"
    29  	"github.com/ethereum/go-ethereum/rlp"
    30  	"github.com/syndtr/goleveldb/leveldb"
    31  	"github.com/syndtr/goleveldb/leveldb/errors"
    32  	"github.com/syndtr/goleveldb/leveldb/iterator"
    33  	"github.com/syndtr/goleveldb/leveldb/opt"
    34  	"github.com/syndtr/goleveldb/leveldb/storage"
    35  	"github.com/syndtr/goleveldb/leveldb/util"
    36  )
    37  
    38  // Keys in the node database.
    39  const (
    40  	dbVersionKey = "version" // Version of the database to flush if changes
    41  	dbItemPrefix = "n:"      // Identifier to prefix node entries with
    42  
    43  	dbDiscoverRoot      = ":discover"
    44  	dbDiscoverSeq       = dbDiscoverRoot + ":seq"
    45  	dbDiscoverPing      = dbDiscoverRoot + ":lastping"
    46  	dbDiscoverPong      = dbDiscoverRoot + ":lastpong"
    47  	dbDiscoverFindFails = dbDiscoverRoot + ":findfail"
    48  	dbLocalRoot         = ":local"
    49  	dbLocalSeq          = dbLocalRoot + ":seq"
    50  )
    51  
    52  var (
    53  	dbNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped.
    54  	dbCleanupCycle   = time.Hour      // Time period for running the expiration task.
    55  	dbVersion        = 7
    56  )
    57  
    58  // DB is the node database, storing previously seen nodes and any collected metadata about
    59  // them for QoS purposes.
    60  type DB struct {
    61  	lvl    *leveldb.DB   // Interface to the database itself
    62  	runner sync.Once     // Ensures we can start at most one expirer
    63  	quit   chan struct{} // Channel to signal the expiring thread to stop
    64  }
    65  
    66  // OpenDB opens a node database for storing and retrieving infos about known peers in the
    67  // network. If no path is given an in-memory, temporary database is constructed.
    68  func OpenDB(path string) (*DB, error) {
    69  	if path == "" {
    70  		return newMemoryDB()
    71  	}
    72  	return newPersistentDB(path)
    73  }
    74  
    75  // newMemoryNodeDB creates a new in-memory node database without a persistent backend.
    76  func newMemoryDB() (*DB, error) {
    77  	db, err := leveldb.Open(storage.NewMemStorage(), nil)
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  	return &DB{lvl: db, quit: make(chan struct{})}, nil
    82  }
    83  
    84  // newPersistentNodeDB creates/opens a leveldb backed persistent node database,
    85  // also flushing its contents in case of a version mismatch.
    86  func newPersistentDB(path string) (*DB, error) {
    87  	opts := &opt.Options{OpenFilesCacheCapacity: 5}
    88  	db, err := leveldb.OpenFile(path, opts)
    89  	if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted {
    90  		db, err = leveldb.RecoverFile(path, nil)
    91  	}
    92  	if err != nil {
    93  		return nil, err
    94  	}
    95  	// The nodes contained in the cache correspond to a certain protocol version.
    96  	// Flush all nodes if the version doesn't match.
    97  	currentVer := make([]byte, binary.MaxVarintLen64)
    98  	currentVer = currentVer[:binary.PutVarint(currentVer, int64(dbVersion))]
    99  
   100  	blob, err := db.Get([]byte(dbVersionKey), nil)
   101  	switch err {
   102  	case leveldb.ErrNotFound:
   103  		// Version not found (i.e. empty cache), insert it
   104  		if err := db.Put([]byte(dbVersionKey), currentVer, nil); err != nil {
   105  			db.Close()
   106  			return nil, err
   107  		}
   108  
   109  	case nil:
   110  		// Version present, flush if different
   111  		if !bytes.Equal(blob, currentVer) {
   112  			db.Close()
   113  			if err = os.RemoveAll(path); err != nil {
   114  				return nil, err
   115  			}
   116  			return newPersistentDB(path)
   117  		}
   118  	}
   119  	return &DB{lvl: db, quit: make(chan struct{})}, nil
   120  }
   121  
   122  // makeKey generates the leveldb key-blob from a node id and its particular
   123  // field of interest.
   124  func makeKey(id ID, field string) []byte {
   125  	if (id == ID{}) {
   126  		return []byte(field)
   127  	}
   128  	return append([]byte(dbItemPrefix), append(id[:], field...)...)
   129  }
   130  
   131  // splitKey tries to split a database key into a node id and a field part.
   132  func splitKey(key []byte) (id ID, field string) {
   133  	// If the key is not of a node, return it plainly
   134  	if !bytes.HasPrefix(key, []byte(dbItemPrefix)) {
   135  		return ID{}, string(key)
   136  	}
   137  	// Otherwise split the id and field
   138  	item := key[len(dbItemPrefix):]
   139  	copy(id[:], item[:len(id)])
   140  	field = string(item[len(id):])
   141  
   142  	return id, field
   143  }
   144  
   145  // fetchInt64 retrieves an integer associated with a particular key.
   146  func (db *DB) fetchInt64(key []byte) int64 {
   147  	blob, err := db.lvl.Get(key, nil)
   148  	if err != nil {
   149  		return 0
   150  	}
   151  	val, read := binary.Varint(blob)
   152  	if read <= 0 {
   153  		return 0
   154  	}
   155  	return val
   156  }
   157  
   158  // storeInt64 stores an integer in the given key.
   159  func (db *DB) storeInt64(key []byte, n int64) error {
   160  	blob := make([]byte, binary.MaxVarintLen64)
   161  	blob = blob[:binary.PutVarint(blob, n)]
   162  	return db.lvl.Put(key, blob, nil)
   163  }
   164  
   165  // fetchUint64 retrieves an integer associated with a particular key.
   166  func (db *DB) fetchUint64(key []byte) uint64 {
   167  	blob, err := db.lvl.Get(key, nil)
   168  	if err != nil {
   169  		return 0
   170  	}
   171  	val, _ := binary.Uvarint(blob)
   172  	return val
   173  }
   174  
   175  // storeUint64 stores an integer in the given key.
   176  func (db *DB) storeUint64(key []byte, n uint64) error {
   177  	blob := make([]byte, binary.MaxVarintLen64)
   178  	blob = blob[:binary.PutUvarint(blob, n)]
   179  	return db.lvl.Put(key, blob, nil)
   180  }
   181  
   182  // Node retrieves a node with a given id from the database.
   183  func (db *DB) Node(id ID) *Node {
   184  	blob, err := db.lvl.Get(makeKey(id, dbDiscoverRoot), nil)
   185  	if err != nil {
   186  		return nil
   187  	}
   188  	return mustDecodeNode(id[:], blob)
   189  }
   190  
   191  func mustDecodeNode(id, data []byte) *Node {
   192  	node := new(Node)
   193  	if err := rlp.DecodeBytes(data, &node.r); err != nil {
   194  		panic(fmt.Errorf("p2p/enode: can't decode node %x in DB: %v", id, err))
   195  	}
   196  	// Restore node id cache.
   197  	copy(node.id[:], id)
   198  	return node
   199  }
   200  
   201  // UpdateNode inserts - potentially overwriting - a node into the peer database.
   202  func (db *DB) UpdateNode(node *Node) error {
   203  	if node.Seq() < db.NodeSeq(node.ID()) {
   204  		return nil
   205  	}
   206  	blob, err := rlp.EncodeToBytes(&node.r)
   207  	if err != nil {
   208  		return err
   209  	}
   210  	if err := db.lvl.Put(makeKey(node.ID(), dbDiscoverRoot), blob, nil); err != nil {
   211  		return err
   212  	}
   213  	return db.storeUint64(makeKey(node.ID(), dbDiscoverSeq), node.Seq())
   214  }
   215  
   216  // NodeSeq returns the stored record sequence number of the given node.
   217  func (db *DB) NodeSeq(id ID) uint64 {
   218  	return db.fetchUint64(makeKey(id, dbDiscoverSeq))
   219  }
   220  
   221  // Resolve returns the stored record of the node if it has a larger sequence
   222  // number than n.
   223  func (db *DB) Resolve(n *Node) *Node {
   224  	if n.Seq() > db.NodeSeq(n.ID()) {
   225  		return n
   226  	}
   227  	return db.Node(n.ID())
   228  }
   229  
   230  // DeleteNode deletes all information/keys associated with a node.
   231  func (db *DB) DeleteNode(id ID) error {
   232  	deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil)
   233  	for deleter.Next() {
   234  		if err := db.lvl.Delete(deleter.Key(), nil); err != nil {
   235  			return err
   236  		}
   237  	}
   238  	return nil
   239  }
   240  
   241  // ensureExpirer is a small helper method ensuring that the data expiration
   242  // mechanism is running. If the expiration goroutine is already running, this
   243  // method simply returns.
   244  //
   245  // The goal is to start the data evacuation only after the network successfully
   246  // bootstrapped itself (to prevent dumping potentially useful seed nodes). Since
   247  // it would require significant overhead to exactly trace the first successful
   248  // convergence, it's simpler to "ensure" the correct state when an appropriate
   249  // condition occurs (i.e. a successful bonding), and discard further events.
   250  func (db *DB) ensureExpirer() {
   251  	db.runner.Do(func() { go db.expirer() })
   252  }
   253  
   254  // expirer should be started in a go routine, and is responsible for looping ad
   255  // infinitum and dropping stale data from the database.
   256  func (db *DB) expirer() {
   257  	tick := time.NewTicker(dbCleanupCycle)
   258  	defer tick.Stop()
   259  	for {
   260  		select {
   261  		case <-tick.C:
   262  			if err := db.expireNodes(); err != nil {
   263  				log.Error("Failed to expire nodedb items", "err", err)
   264  			}
   265  		case <-db.quit:
   266  			return
   267  		}
   268  	}
   269  }
   270  
   271  // expireNodes iterates over the database and deletes all nodes that have not
   272  // been seen (i.e. received a pong from) for some allotted time.
   273  func (db *DB) expireNodes() error {
   274  	threshold := time.Now().Add(-dbNodeExpiration)
   275  
   276  	// Find discovered nodes that are older than the allowance
   277  	it := db.lvl.NewIterator(nil, nil)
   278  	defer it.Release()
   279  
   280  	for it.Next() {
   281  		// Skip the item if not a discovery node
   282  		id, field := splitKey(it.Key())
   283  		if field != dbDiscoverRoot {
   284  			continue
   285  		}
   286  		// Skip the node if not expired yet (and not self)
   287  		if seen := db.LastPongReceived(id); seen.After(threshold) {
   288  			continue
   289  		}
   290  		// Otherwise delete all associated information
   291  		db.DeleteNode(id)
   292  	}
   293  	return nil
   294  }
   295  
   296  // LastPingReceived retrieves the time of the last ping packet received from
   297  // a remote node.
   298  func (db *DB) LastPingReceived(id ID) time.Time {
   299  	return time.Unix(db.fetchInt64(makeKey(id, dbDiscoverPing)), 0)
   300  }
   301  
   302  // UpdateLastPingReceived updates the last time we tried contacting a remote node.
   303  func (db *DB) UpdateLastPingReceived(id ID, instance time.Time) error {
   304  	return db.storeInt64(makeKey(id, dbDiscoverPing), instance.Unix())
   305  }
   306  
   307  // LastPongReceived retrieves the time of the last successful pong from remote node.
   308  func (db *DB) LastPongReceived(id ID) time.Time {
   309  	// Launch expirer
   310  	db.ensureExpirer()
   311  	return time.Unix(db.fetchInt64(makeKey(id, dbDiscoverPong)), 0)
   312  }
   313  
   314  // UpdateLastPongReceived updates the last pong time of a node.
   315  func (db *DB) UpdateLastPongReceived(id ID, instance time.Time) error {
   316  	return db.storeInt64(makeKey(id, dbDiscoverPong), instance.Unix())
   317  }
   318  
   319  // FindFails retrieves the number of findnode failures since bonding.
   320  func (db *DB) FindFails(id ID) int {
   321  	return int(db.fetchInt64(makeKey(id, dbDiscoverFindFails)))
   322  }
   323  
   324  // UpdateFindFails updates the number of findnode failures since bonding.
   325  func (db *DB) UpdateFindFails(id ID, fails int) error {
   326  	return db.storeInt64(makeKey(id, dbDiscoverFindFails), int64(fails))
   327  }
   328  
   329  // LocalSeq retrieves the local record sequence counter.
   330  func (db *DB) localSeq(id ID) uint64 {
   331  	return db.fetchUint64(makeKey(id, dbLocalSeq))
   332  }
   333  
   334  // storeLocalSeq stores the local record sequence counter.
   335  func (db *DB) storeLocalSeq(id ID, n uint64) {
   336  	db.storeUint64(makeKey(id, dbLocalSeq), n)
   337  }
   338  
   339  // QuerySeeds retrieves random nodes to be used as potential seed nodes
   340  // for bootstrapping.
   341  func (db *DB) QuerySeeds(n int, maxAge time.Duration) []*Node {
   342  	var (
   343  		now   = time.Now()
   344  		nodes = make([]*Node, 0, n)
   345  		it    = db.lvl.NewIterator(nil, nil)
   346  		id    ID
   347  	)
   348  	defer it.Release()
   349  
   350  seek:
   351  	for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ {
   352  		// Seek to a random entry. The first byte is incremented by a
   353  		// random amount each time in order to increase the likelihood
   354  		// of hitting all existing nodes in very small databases.
   355  		ctr := id[0]
   356  		rand.Read(id[:])
   357  		id[0] = ctr + id[0]%16
   358  		it.Seek(makeKey(id, dbDiscoverRoot))
   359  
   360  		n := nextNode(it)
   361  		if n == nil {
   362  			id[0] = 0
   363  			continue seek // iterator exhausted
   364  		}
   365  		if now.Sub(db.LastPongReceived(n.ID())) > maxAge {
   366  			continue seek
   367  		}
   368  		for i := range nodes {
   369  			if nodes[i].ID() == n.ID() {
   370  				continue seek // duplicate
   371  			}
   372  		}
   373  		nodes = append(nodes, n)
   374  	}
   375  	return nodes
   376  }
   377  
   378  // reads the next node record from the iterator, skipping over other
   379  // database entries.
   380  func nextNode(it iterator.Iterator) *Node {
   381  	for end := false; !end; end = !it.Next() {
   382  		id, field := splitKey(it.Key())
   383  		if field != dbDiscoverRoot {
   384  			continue
   385  		}
   386  		return mustDecodeNode(id[:], it.Value())
   387  	}
   388  	return nil
   389  }
   390  
   391  // close flushes and closes the database files.
   392  func (db *DB) Close() {
   393  	close(db.quit)
   394  	db.lvl.Close()
   395  }