github.com/phillinzzz/newBsc@v1.1.6/p2p/enode/nodedb.go (about)

     1  // Copyright 2018 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  	"net"
    25  	"os"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/phillinzzz/newBsc/common/gopool"
    30  	"github.com/phillinzzz/newBsc/rlp"
    31  	"github.com/syndtr/goleveldb/leveldb"
    32  	"github.com/syndtr/goleveldb/leveldb/errors"
    33  	"github.com/syndtr/goleveldb/leveldb/iterator"
    34  	"github.com/syndtr/goleveldb/leveldb/opt"
    35  	"github.com/syndtr/goleveldb/leveldb/storage"
    36  	"github.com/syndtr/goleveldb/leveldb/util"
    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() {
   308  		gopool.Submit(func() {
   309  			db.expirer()
   310  		})
   311  	})
   312  }
   313  
   314  // expirer should be started in a go routine, and is responsible for looping ad
   315  // infinitum and dropping stale data from the database.
   316  func (db *DB) expirer() {
   317  	tick := time.NewTicker(dbCleanupCycle)
   318  	defer tick.Stop()
   319  	for {
   320  		select {
   321  		case <-tick.C:
   322  			db.expireNodes()
   323  		case <-db.quit:
   324  			return
   325  		}
   326  	}
   327  }
   328  
   329  // expireNodes iterates over the database and deletes all nodes that have not
   330  // been seen (i.e. received a pong from) for some time.
   331  func (db *DB) expireNodes() {
   332  	it := db.lvl.NewIterator(util.BytesPrefix([]byte(dbNodePrefix)), nil)
   333  	defer it.Release()
   334  	if !it.Next() {
   335  		return
   336  	}
   337  
   338  	var (
   339  		threshold    = time.Now().Add(-dbNodeExpiration).Unix()
   340  		youngestPong int64
   341  		atEnd        = false
   342  	)
   343  	for !atEnd {
   344  		id, ip, field := splitNodeItemKey(it.Key())
   345  		if field == dbNodePong {
   346  			time, _ := binary.Varint(it.Value())
   347  			if time > youngestPong {
   348  				youngestPong = time
   349  			}
   350  			if time < threshold {
   351  				// Last pong from this IP older than threshold, remove fields belonging to it.
   352  				deleteRange(db.lvl, nodeItemKey(id, ip, ""))
   353  			}
   354  		}
   355  		atEnd = !it.Next()
   356  		nextID, _ := splitNodeKey(it.Key())
   357  		if atEnd || nextID != id {
   358  			// We've moved beyond the last entry of the current ID.
   359  			// Remove everything if there was no recent enough pong.
   360  			if youngestPong > 0 && youngestPong < threshold {
   361  				deleteRange(db.lvl, nodeKey(id))
   362  			}
   363  			youngestPong = 0
   364  		}
   365  	}
   366  }
   367  
   368  // LastPingReceived retrieves the time of the last ping packet received from
   369  // a remote node.
   370  func (db *DB) LastPingReceived(id ID, ip net.IP) time.Time {
   371  	if ip = ip.To16(); ip == nil {
   372  		return time.Time{}
   373  	}
   374  	return time.Unix(db.fetchInt64(nodeItemKey(id, ip, dbNodePing)), 0)
   375  }
   376  
   377  // UpdateLastPingReceived updates the last time we tried contacting a remote node.
   378  func (db *DB) UpdateLastPingReceived(id ID, ip net.IP, instance time.Time) error {
   379  	if ip = ip.To16(); ip == nil {
   380  		return errInvalidIP
   381  	}
   382  	return db.storeInt64(nodeItemKey(id, ip, dbNodePing), instance.Unix())
   383  }
   384  
   385  // LastPongReceived retrieves the time of the last successful pong from remote node.
   386  func (db *DB) LastPongReceived(id ID, ip net.IP) time.Time {
   387  	if ip = ip.To16(); ip == nil {
   388  		return time.Time{}
   389  	}
   390  	// Launch expirer
   391  	db.ensureExpirer()
   392  	return time.Unix(db.fetchInt64(nodeItemKey(id, ip, dbNodePong)), 0)
   393  }
   394  
   395  // UpdateLastPongReceived updates the last pong time of a node.
   396  func (db *DB) UpdateLastPongReceived(id ID, ip net.IP, instance time.Time) error {
   397  	if ip = ip.To16(); ip == nil {
   398  		return errInvalidIP
   399  	}
   400  	return db.storeInt64(nodeItemKey(id, ip, dbNodePong), instance.Unix())
   401  }
   402  
   403  // FindFails retrieves the number of findnode failures since bonding.
   404  func (db *DB) FindFails(id ID, ip net.IP) int {
   405  	if ip = ip.To16(); ip == nil {
   406  		return 0
   407  	}
   408  	return int(db.fetchInt64(nodeItemKey(id, ip, dbNodeFindFails)))
   409  }
   410  
   411  // UpdateFindFails updates the number of findnode failures since bonding.
   412  func (db *DB) UpdateFindFails(id ID, ip net.IP, fails int) error {
   413  	if ip = ip.To16(); ip == nil {
   414  		return errInvalidIP
   415  	}
   416  	return db.storeInt64(nodeItemKey(id, ip, dbNodeFindFails), int64(fails))
   417  }
   418  
   419  // FindFailsV5 retrieves the discv5 findnode failure counter.
   420  func (db *DB) FindFailsV5(id ID, ip net.IP) int {
   421  	if ip = ip.To16(); ip == nil {
   422  		return 0
   423  	}
   424  	return int(db.fetchInt64(v5Key(id, ip, dbNodeFindFails)))
   425  }
   426  
   427  // UpdateFindFailsV5 stores the discv5 findnode failure counter.
   428  func (db *DB) UpdateFindFailsV5(id ID, ip net.IP, fails int) error {
   429  	if ip = ip.To16(); ip == nil {
   430  		return errInvalidIP
   431  	}
   432  	return db.storeInt64(v5Key(id, ip, dbNodeFindFails), int64(fails))
   433  }
   434  
   435  // LocalSeq retrieves the local record sequence counter.
   436  func (db *DB) localSeq(id ID) uint64 {
   437  	return db.fetchUint64(localItemKey(id, dbLocalSeq))
   438  }
   439  
   440  // storeLocalSeq stores the local record sequence counter.
   441  func (db *DB) storeLocalSeq(id ID, n uint64) {
   442  	db.storeUint64(localItemKey(id, dbLocalSeq), n)
   443  }
   444  
   445  // QuerySeeds retrieves random nodes to be used as potential seed nodes
   446  // for bootstrapping.
   447  func (db *DB) QuerySeeds(n int, maxAge time.Duration) []*Node {
   448  	var (
   449  		now   = time.Now()
   450  		nodes = make([]*Node, 0, n)
   451  		it    = db.lvl.NewIterator(nil, nil)
   452  		id    ID
   453  	)
   454  	defer it.Release()
   455  
   456  seek:
   457  	for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ {
   458  		// Seek to a random entry. The first byte is incremented by a
   459  		// random amount each time in order to increase the likelihood
   460  		// of hitting all existing nodes in very small databases.
   461  		ctr := id[0]
   462  		rand.Read(id[:])
   463  		id[0] = ctr + id[0]%16
   464  		it.Seek(nodeKey(id))
   465  
   466  		n := nextNode(it)
   467  		if n == nil {
   468  			id[0] = 0
   469  			continue seek // iterator exhausted
   470  		}
   471  		if now.Sub(db.LastPongReceived(n.ID(), n.IP())) > maxAge {
   472  			continue seek
   473  		}
   474  		for i := range nodes {
   475  			if nodes[i].ID() == n.ID() {
   476  				continue seek // duplicate
   477  			}
   478  		}
   479  		nodes = append(nodes, n)
   480  	}
   481  	return nodes
   482  }
   483  
   484  // reads the next node record from the iterator, skipping over other
   485  // database entries.
   486  func nextNode(it iterator.Iterator) *Node {
   487  	for end := false; !end; end = !it.Next() {
   488  		id, rest := splitNodeKey(it.Key())
   489  		if string(rest) != dbDiscoverRoot {
   490  			continue
   491  		}
   492  		return mustDecodeNode(id[:], it.Value())
   493  	}
   494  	return nil
   495  }
   496  
   497  // close flushes and closes the database files.
   498  func (db *DB) Close() {
   499  	close(db.quit)
   500  	db.lvl.Close()
   501  }