github.com/core-coin/go-core/v2@v2.1.9/p2p/enode/nodedb.go (about)

     1  // Copyright 2018 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core 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  	"net"
    25  	"os"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/syndtr/goleveldb/leveldb"
    30  	"github.com/syndtr/goleveldb/leveldb/errors"
    31  	"github.com/syndtr/goleveldb/leveldb/iterator"
    32  	"github.com/syndtr/goleveldb/leveldb/opt"
    33  	"github.com/syndtr/goleveldb/leveldb/storage"
    34  	"github.com/syndtr/goleveldb/leveldb/util"
    35  
    36  	"github.com/core-coin/go-core/v2/rlp"
    37  )
    38  
    39  // Keys in the node database.
    40  const (
    41  	dbVersionKey   = "version" // Version of the database to flush if changes
    42  	dbNodePrefix   = "n:"      // Identifier to prefix node entries with
    43  	dbLocalPrefix  = "local:"
    44  	dbDiscoverRoot = "v4"
    45  	dbDiscv5Root   = "v5"
    46  
    47  	// These fields are stored per ID and IP, the full key is "n:<ID>:v4:<IP>:findfail".
    48  	// Use nodeItemKey to create those keys.
    49  	dbNodeFindFails = "findfail"
    50  	dbNodePing      = "lastping"
    51  	dbNodePong      = "lastpong"
    52  	dbNodeSeq       = "seq"
    53  
    54  	// Local information is keyed by ID only, the full key is "local:<ID>:seq".
    55  	// Use localItemKey to create those keys.
    56  	dbLocalSeq = "seq"
    57  )
    58  
    59  const (
    60  	dbNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped.
    61  	dbCleanupCycle   = time.Hour      // Time period for running the expiration task.
    62  	dbVersion        = 9
    63  )
    64  
    65  var (
    66  	errInvalidIP = errors.New("invalid IP")
    67  )
    68  
    69  var zeroIP = make(net.IP, 16)
    70  
    71  // DB is the node database, storing previously seen nodes and any collected metadata about
    72  // them for QoS purposes.
    73  type DB struct {
    74  	lvl    *leveldb.DB   // Interface to the database itself
    75  	runner sync.Once     // Ensures we can start at most one expirer
    76  	quit   chan struct{} // Channel to signal the expiring thread to stop
    77  }
    78  
    79  // OpenDB opens a node database for storing and retrieving infos about known peers in the
    80  // network. If no path is given an in-memory, temporary database is constructed.
    81  func OpenDB(path string) (*DB, error) {
    82  	if path == "" {
    83  		return newMemoryDB()
    84  	}
    85  	return newPersistentDB(path)
    86  }
    87  
    88  // newMemoryNodeDB creates a new in-memory node database without a persistent backend.
    89  func newMemoryDB() (*DB, error) {
    90  	db, err := leveldb.Open(storage.NewMemStorage(), nil)
    91  	if err != nil {
    92  		return nil, err
    93  	}
    94  	return &DB{lvl: db, quit: make(chan struct{})}, nil
    95  }
    96  
    97  // newPersistentNodeDB creates/opens a leveldb backed persistent node database,
    98  // also flushing its contents in case of a version mismatch.
    99  func newPersistentDB(path string) (*DB, error) {
   100  	opts := &opt.Options{OpenFilesCacheCapacity: 5}
   101  	db, err := leveldb.OpenFile(path, opts)
   102  	if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted {
   103  		db, err = leveldb.RecoverFile(path, nil)
   104  	}
   105  	if err != nil {
   106  		return nil, err
   107  	}
   108  	// The nodes contained in the cache correspond to a certain protocol version.
   109  	// Flush all nodes if the version doesn't match.
   110  	currentVer := make([]byte, binary.MaxVarintLen64)
   111  	currentVer = currentVer[:binary.PutVarint(currentVer, int64(dbVersion))]
   112  
   113  	blob, err := db.Get([]byte(dbVersionKey), nil)
   114  	switch err {
   115  	case leveldb.ErrNotFound:
   116  		// Version not found (i.e. empty cache), insert it
   117  		if err := db.Put([]byte(dbVersionKey), currentVer, nil); err != nil {
   118  			db.Close()
   119  			return nil, err
   120  		}
   121  
   122  	case nil:
   123  		// Version present, flush if different
   124  		if !bytes.Equal(blob, currentVer) {
   125  			db.Close()
   126  			if err = os.RemoveAll(path); err != nil {
   127  				return nil, err
   128  			}
   129  			return newPersistentDB(path)
   130  		}
   131  	}
   132  	return &DB{lvl: db, quit: make(chan struct{})}, nil
   133  }
   134  
   135  // nodeKey returns the database key for a node record.
   136  func nodeKey(id ID) []byte {
   137  	key := append([]byte(dbNodePrefix), id[:]...)
   138  	key = append(key, ':')
   139  	key = append(key, dbDiscoverRoot...)
   140  	return key
   141  }
   142  
   143  // splitNodeKey returns the node ID of a key created by nodeKey.
   144  func splitNodeKey(key []byte) (id ID, rest []byte) {
   145  	if !bytes.HasPrefix(key, []byte(dbNodePrefix)) {
   146  		return ID{}, nil
   147  	}
   148  	item := key[len(dbNodePrefix):]
   149  	copy(id[:], item[:len(id)])
   150  	return id, item[len(id)+1:]
   151  }
   152  
   153  // nodeItemKey returns the database key for a node metadata field.
   154  func nodeItemKey(id ID, ip net.IP, field string) []byte {
   155  	ip16 := ip.To16()
   156  	if ip16 == nil {
   157  		panic(fmt.Errorf("invalid IP (length %d)", len(ip)))
   158  	}
   159  	return bytes.Join([][]byte{nodeKey(id), ip16, []byte(field)}, []byte{':'})
   160  }
   161  
   162  // splitNodeItemKey returns the components of a key created by nodeItemKey.
   163  func splitNodeItemKey(key []byte) (id ID, ip net.IP, field string) {
   164  	id, key = splitNodeKey(key)
   165  	// Skip discover root.
   166  	if string(key) == dbDiscoverRoot {
   167  		return id, nil, ""
   168  	}
   169  	key = key[len(dbDiscoverRoot)+1:]
   170  	// Split out the IP.
   171  	ip = key[:16]
   172  	if ip4 := ip.To4(); ip4 != nil {
   173  		ip = ip4
   174  	}
   175  	key = key[16+1:]
   176  	// Field is the remainder of key.
   177  	field = string(key)
   178  	return id, ip, field
   179  }
   180  
   181  func v5Key(id ID, ip net.IP, field string) []byte {
   182  	return bytes.Join([][]byte{
   183  		[]byte(dbNodePrefix),
   184  		id[:],
   185  		[]byte(dbDiscv5Root),
   186  		ip.To16(),
   187  		[]byte(field),
   188  	}, []byte{':'})
   189  }
   190  
   191  // localItemKey returns the key of a local node item.
   192  func localItemKey(id ID, field string) []byte {
   193  	key := append([]byte(dbLocalPrefix), id[:]...)
   194  	key = append(key, ':')
   195  	key = append(key, field...)
   196  	return key
   197  }
   198  
   199  // fetchInt64 retrieves an integer associated with a particular key.
   200  func (db *DB) fetchInt64(key []byte) int64 {
   201  	blob, err := db.lvl.Get(key, nil)
   202  	if err != nil {
   203  		return 0
   204  	}
   205  	val, read := binary.Varint(blob)
   206  	if read <= 0 {
   207  		return 0
   208  	}
   209  	return val
   210  }
   211  
   212  // storeInt64 stores an integer in the given key.
   213  func (db *DB) storeInt64(key []byte, n int64) error {
   214  	blob := make([]byte, binary.MaxVarintLen64)
   215  	blob = blob[:binary.PutVarint(blob, n)]
   216  	return db.lvl.Put(key, blob, nil)
   217  }
   218  
   219  // fetchUint64 retrieves an integer associated with a particular key.
   220  func (db *DB) fetchUint64(key []byte) uint64 {
   221  	blob, err := db.lvl.Get(key, nil)
   222  	if err != nil {
   223  		return 0
   224  	}
   225  	val, _ := binary.Uvarint(blob)
   226  	return val
   227  }
   228  
   229  // storeUint64 stores an integer in the given key.
   230  func (db *DB) storeUint64(key []byte, n uint64) error {
   231  	blob := make([]byte, binary.MaxVarintLen64)
   232  	blob = blob[:binary.PutUvarint(blob, n)]
   233  	return db.lvl.Put(key, blob, nil)
   234  }
   235  
   236  // Node retrieves a node with a given id from the database.
   237  func (db *DB) Node(id ID) *Node {
   238  	blob, err := db.lvl.Get(nodeKey(id), nil)
   239  	if err != nil {
   240  		return nil
   241  	}
   242  	return mustDecodeNode(id[:], blob)
   243  }
   244  
   245  func mustDecodeNode(id, data []byte) *Node {
   246  	node := new(Node)
   247  	if err := rlp.DecodeBytes(data, &node.r); err != nil {
   248  		panic(fmt.Errorf("p2p/enode: can't decode node %x in DB: %v", id, err))
   249  	}
   250  	// Restore node id cache.
   251  	copy(node.id[:], id)
   252  	return node
   253  }
   254  
   255  // UpdateNode inserts - potentially overwriting - a node into the peer database.
   256  func (db *DB) UpdateNode(node *Node) error {
   257  	if node.Seq() < db.NodeSeq(node.ID()) {
   258  		return nil
   259  	}
   260  	blob, err := rlp.EncodeToBytes(&node.r)
   261  	if err != nil {
   262  		return err
   263  	}
   264  	if err := db.lvl.Put(nodeKey(node.ID()), blob, nil); err != nil {
   265  		return err
   266  	}
   267  	return db.storeUint64(nodeItemKey(node.ID(), zeroIP, dbNodeSeq), node.Seq())
   268  }
   269  
   270  // NodeSeq returns the stored record sequence number of the given node.
   271  func (db *DB) NodeSeq(id ID) uint64 {
   272  	return db.fetchUint64(nodeItemKey(id, zeroIP, dbNodeSeq))
   273  }
   274  
   275  // Resolve returns the stored record of the node if it has a larger sequence
   276  // number than n.
   277  func (db *DB) Resolve(n *Node) *Node {
   278  	if n.Seq() > db.NodeSeq(n.ID()) {
   279  		return n
   280  	}
   281  	return db.Node(n.ID())
   282  }
   283  
   284  // DeleteNode deletes all information associated with a node.
   285  func (db *DB) DeleteNode(id ID) {
   286  	deleteRange(db.lvl, nodeKey(id))
   287  }
   288  
   289  func deleteRange(db *leveldb.DB, prefix []byte) {
   290  	it := db.NewIterator(util.BytesPrefix(prefix), nil)
   291  	defer it.Release()
   292  	for it.Next() {
   293  		db.Delete(it.Key(), nil)
   294  	}
   295  }
   296  
   297  // ensureExpirer is a small helper method ensuring that the data expiration
   298  // mechanism is running. If the expiration goroutine is already running, this
   299  // method simply returns.
   300  //
   301  // The goal is to start the data evacuation only after the network successfully
   302  // bootstrapped itself (to prevent dumping potentially useful seed nodes). Since
   303  // it would require significant overhead to exactly trace the first successful
   304  // convergence, it's simpler to "ensure" the correct state when an appropriate
   305  // condition occurs (i.e. a successful bonding), and discard further events.
   306  func (db *DB) ensureExpirer() {
   307  	db.runner.Do(func() { go db.expirer() })
   308  }
   309  
   310  // expirer should be started in a go routine, and is responsible for looping ad
   311  // infinitum and dropping stale data from the database.
   312  func (db *DB) expirer() {
   313  	tick := time.NewTicker(dbCleanupCycle)
   314  	defer tick.Stop()
   315  	for {
   316  		select {
   317  		case <-tick.C:
   318  			db.expireNodes()
   319  		case <-db.quit:
   320  			return
   321  		}
   322  	}
   323  }
   324  
   325  // expireNodes iterates over the database and deletes all nodes that have not
   326  // been seen (i.e. received a pong from) for some time.
   327  func (db *DB) expireNodes() {
   328  	it := db.lvl.NewIterator(util.BytesPrefix([]byte(dbNodePrefix)), nil)
   329  	defer it.Release()
   330  	if !it.Next() {
   331  		return
   332  	}
   333  
   334  	var (
   335  		threshold    = time.Now().Add(-dbNodeExpiration).Unix()
   336  		youngestPong int64
   337  		atEnd        = false
   338  	)
   339  	for !atEnd {
   340  		id, ip, field := splitNodeItemKey(it.Key())
   341  		if field == dbNodePong {
   342  			time, _ := binary.Varint(it.Value())
   343  			if time > youngestPong {
   344  				youngestPong = time
   345  			}
   346  			if time < threshold {
   347  				// Last pong from this IP older than threshold, remove fields belonging to it.
   348  				deleteRange(db.lvl, nodeItemKey(id, ip, ""))
   349  			}
   350  		}
   351  		atEnd = !it.Next()
   352  		nextID, _ := splitNodeKey(it.Key())
   353  		if atEnd || nextID != id {
   354  			// We've moved beyond the last entry of the current ID.
   355  			// Remove everything if there was no recent enough pong.
   356  			if youngestPong > 0 && youngestPong < threshold {
   357  				deleteRange(db.lvl, nodeKey(id))
   358  			}
   359  			youngestPong = 0
   360  		}
   361  	}
   362  }
   363  
   364  // LastPingReceived retrieves the time of the last ping packet received from
   365  // a remote node.
   366  func (db *DB) LastPingReceived(id ID, ip net.IP) time.Time {
   367  	if ip = ip.To16(); ip == nil {
   368  		return time.Time{}
   369  	}
   370  	return time.Unix(db.fetchInt64(nodeItemKey(id, ip, dbNodePing)), 0)
   371  }
   372  
   373  // UpdateLastPingReceived updates the last time we tried contacting a remote node.
   374  func (db *DB) UpdateLastPingReceived(id ID, ip net.IP, instance time.Time) error {
   375  	if ip = ip.To16(); ip == nil {
   376  		return errInvalidIP
   377  	}
   378  	return db.storeInt64(nodeItemKey(id, ip, dbNodePing), instance.Unix())
   379  }
   380  
   381  // LastPongReceived retrieves the time of the last successful pong from remote node.
   382  func (db *DB) LastPongReceived(id ID, ip net.IP) time.Time {
   383  	if ip = ip.To16(); ip == nil {
   384  		return time.Time{}
   385  	}
   386  	// Launch expirer
   387  	db.ensureExpirer()
   388  	return time.Unix(db.fetchInt64(nodeItemKey(id, ip, dbNodePong)), 0)
   389  }
   390  
   391  // UpdateLastPongReceived updates the last pong time of a node.
   392  func (db *DB) UpdateLastPongReceived(id ID, ip net.IP, instance time.Time) error {
   393  	if ip = ip.To16(); ip == nil {
   394  		return errInvalidIP
   395  	}
   396  	return db.storeInt64(nodeItemKey(id, ip, dbNodePong), instance.Unix())
   397  }
   398  
   399  // FindFails retrieves the number of findnode failures since bonding.
   400  func (db *DB) FindFails(id ID, ip net.IP) int {
   401  	if ip = ip.To16(); ip == nil {
   402  		return 0
   403  	}
   404  	return int(db.fetchInt64(nodeItemKey(id, ip, dbNodeFindFails)))
   405  }
   406  
   407  // UpdateFindFails updates the number of findnode failures since bonding.
   408  func (db *DB) UpdateFindFails(id ID, ip net.IP, fails int) error {
   409  	if ip = ip.To16(); ip == nil {
   410  		return errInvalidIP
   411  	}
   412  	return db.storeInt64(nodeItemKey(id, ip, dbNodeFindFails), int64(fails))
   413  }
   414  
   415  // FindFailsV5 retrieves the discv5 findnode failure counter.
   416  func (db *DB) FindFailsV5(id ID, ip net.IP) int {
   417  	if ip = ip.To16(); ip == nil {
   418  		return 0
   419  	}
   420  	return int(db.fetchInt64(v5Key(id, ip, dbNodeFindFails)))
   421  }
   422  
   423  // UpdateFindFailsV5 stores the discv5 findnode failure counter.
   424  func (db *DB) UpdateFindFailsV5(id ID, ip net.IP, fails int) error {
   425  	if ip = ip.To16(); ip == nil {
   426  		return errInvalidIP
   427  	}
   428  	return db.storeInt64(v5Key(id, ip, dbNodeFindFails), int64(fails))
   429  }
   430  
   431  // LocalSeq retrieves the local record sequence counter.
   432  func (db *DB) localSeq(id ID) uint64 {
   433  	return db.fetchUint64(localItemKey(id, dbLocalSeq))
   434  }
   435  
   436  // storeLocalSeq stores the local record sequence counter.
   437  func (db *DB) storeLocalSeq(id ID, n uint64) {
   438  	db.storeUint64(localItemKey(id, dbLocalSeq), n)
   439  }
   440  
   441  // QuerySeeds retrieves random nodes to be used as potential seed nodes
   442  // for bootstrapping.
   443  func (db *DB) QuerySeeds(n int, maxAge time.Duration) []*Node {
   444  	var (
   445  		now   = time.Now()
   446  		nodes = make([]*Node, 0, n)
   447  		it    = db.lvl.NewIterator(nil, nil)
   448  		id    ID
   449  	)
   450  	defer it.Release()
   451  
   452  seek:
   453  	for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ {
   454  		// Seek to a random entry. The first byte is incremented by a
   455  		// random amount each time in order to increase the likelihood
   456  		// of hitting all existing nodes in very small databases.
   457  		ctr := id[0]
   458  		rand.Read(id[:])
   459  		id[0] = ctr + id[0]%16
   460  		it.Seek(nodeKey(id))
   461  
   462  		n := nextNode(it)
   463  		if n == nil {
   464  			id[0] = 0
   465  			continue seek // iterator exhausted
   466  		}
   467  		if now.Sub(db.LastPongReceived(n.ID(), n.IP())) > maxAge {
   468  			continue seek
   469  		}
   470  		for i := range nodes {
   471  			if nodes[i].ID() == n.ID() {
   472  				continue seek // duplicate
   473  			}
   474  		}
   475  		nodes = append(nodes, n)
   476  	}
   477  	return nodes
   478  }
   479  
   480  // reads the next node record from the iterator, skipping over other
   481  // database entries.
   482  func nextNode(it iterator.Iterator) *Node {
   483  	for end := false; !end; end = !it.Next() {
   484  		id, rest := splitNodeKey(it.Key())
   485  		if string(rest) != dbDiscoverRoot {
   486  			continue
   487  		}
   488  		return mustDecodeNode(id[:], it.Value())
   489  	}
   490  	return nil
   491  }
   492  
   493  // close flushes and closes the database files.
   494  func (db *DB) Close() {
   495  	close(db.quit)
   496  	db.lvl.Close()
   497  }