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