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