github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/p2p/discover/database.go (about)

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