2015-07-06 17:54:22 -07:00
|
|
|
// Copyright 2015 The go-ethereum Authors
|
2015-07-22 09:48:40 -07:00
|
|
|
// This file is part of the go-ethereum library.
|
2015-07-06 17:54:22 -07:00
|
|
|
//
|
2015-07-23 09:35:11 -07:00
|
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
2015-07-06 17:54:22 -07:00
|
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
//
|
2015-07-22 09:48:40 -07:00
|
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
2015-07-06 17:54:22 -07:00
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
2015-07-22 09:48:40 -07:00
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
2015-07-06 17:54:22 -07:00
|
|
|
// GNU Lesser General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Lesser General Public License
|
2015-07-22 09:48:40 -07:00
|
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
2015-07-06 17:54:22 -07:00
|
|
|
|
2015-04-24 08:04:41 -07:00
|
|
|
// Contains the node database, storing previously seen nodes and any collected
|
|
|
|
// metadata about them for QoS purposes.
|
|
|
|
|
|
|
|
package discover
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2015-09-29 20:01:49 -07:00
|
|
|
"crypto/rand"
|
2015-04-24 08:04:41 -07:00
|
|
|
"encoding/binary"
|
|
|
|
"os"
|
2015-04-27 07:38:28 -07:00
|
|
|
"sync"
|
2015-04-24 08:04:41 -07:00
|
|
|
"time"
|
|
|
|
|
2015-04-23 03:11:21 -07:00
|
|
|
"github.com/ethereum/go-ethereum/crypto"
|
2017-02-22 04:10:07 -08:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2015-04-24 08:04:41 -07:00
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb"
|
2015-04-28 03:57:57 -07:00
|
|
|
"github.com/syndtr/goleveldb/leveldb/errors"
|
2015-04-27 04:45:35 -07:00
|
|
|
"github.com/syndtr/goleveldb/leveldb/iterator"
|
2015-05-14 06:01:13 -07:00
|
|
|
"github.com/syndtr/goleveldb/leveldb/opt"
|
2015-04-24 08:04:41 -07:00
|
|
|
"github.com/syndtr/goleveldb/leveldb/storage"
|
2015-04-28 03:57:57 -07:00
|
|
|
"github.com/syndtr/goleveldb/leveldb/util"
|
2015-04-24 08:04:41 -07:00
|
|
|
)
|
|
|
|
|
2015-04-27 07:38:28 -07:00
|
|
|
var (
|
|
|
|
nodeDBNilNodeID = NodeID{} // Special node ID to use as a nil element.
|
|
|
|
nodeDBNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped.
|
|
|
|
nodeDBCleanupCycle = time.Hour // Time period for running the expiration task.
|
|
|
|
)
|
2015-04-27 02:33:06 -07:00
|
|
|
|
2015-04-24 08:04:41 -07:00
|
|
|
// nodeDB stores all nodes we know about.
|
|
|
|
type nodeDB struct {
|
2015-09-29 20:01:49 -07:00
|
|
|
lvl *leveldb.DB // Interface to the database itself
|
|
|
|
self NodeID // Own node id to prevent adding it into the database
|
2015-04-27 07:38:28 -07:00
|
|
|
runner sync.Once // Ensures we can start at most one expirer
|
|
|
|
quit chan struct{} // Channel to signal the expiring thread to stop
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Schema layout for the node database
|
|
|
|
var (
|
|
|
|
nodeDBVersionKey = []byte("version") // Version of the database to flush if changes
|
|
|
|
nodeDBItemPrefix = []byte("n:") // Identifier to prefix node entries with
|
|
|
|
|
2015-05-25 05:04:05 -07:00
|
|
|
nodeDBDiscoverRoot = ":discover"
|
|
|
|
nodeDBDiscoverPing = nodeDBDiscoverRoot + ":lastping"
|
|
|
|
nodeDBDiscoverPong = nodeDBDiscoverRoot + ":lastpong"
|
|
|
|
nodeDBDiscoverFindFails = nodeDBDiscoverRoot + ":findfail"
|
2015-04-24 08:04:41 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// newNodeDB creates a new node database for storing and retrieving infos about
|
|
|
|
// known peers in the network. If no path is given, an in-memory, temporary
|
|
|
|
// database is constructed.
|
2015-05-21 09:41:46 -07:00
|
|
|
func newNodeDB(path string, version int, self NodeID) (*nodeDB, error) {
|
2015-04-24 08:04:41 -07:00
|
|
|
if path == "" {
|
2015-05-21 09:41:46 -07:00
|
|
|
return newMemoryNodeDB(self)
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
2015-05-21 09:41:46 -07:00
|
|
|
return newPersistentNodeDB(path, version, self)
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// newMemoryNodeDB creates a new in-memory node database without a persistent
|
|
|
|
// backend.
|
2015-05-21 09:41:46 -07:00
|
|
|
func newMemoryNodeDB(self NodeID) (*nodeDB, error) {
|
2015-04-24 08:04:41 -07:00
|
|
|
db, err := leveldb.Open(storage.NewMemStorage(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-04-27 07:38:28 -07:00
|
|
|
return &nodeDB{
|
|
|
|
lvl: db,
|
2015-05-21 09:41:46 -07:00
|
|
|
self: self,
|
2015-04-27 07:38:28 -07:00
|
|
|
quit: make(chan struct{}),
|
|
|
|
}, nil
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// newPersistentNodeDB creates/opens a leveldb backed persistent node database,
|
|
|
|
// also flushing its contents in case of a version mismatch.
|
2015-05-21 09:41:46 -07:00
|
|
|
func newPersistentNodeDB(path string, version int, self NodeID) (*nodeDB, error) {
|
2015-05-14 06:01:13 -07:00
|
|
|
opts := &opt.Options{OpenFilesCacheCapacity: 5}
|
|
|
|
db, err := leveldb.OpenFile(path, opts)
|
2015-04-28 03:57:57 -07:00
|
|
|
if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted {
|
2015-04-24 08:04:41 -07:00
|
|
|
db, err = leveldb.RecoverFile(path, nil)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// The nodes contained in the cache correspond to a certain protocol version.
|
|
|
|
// Flush all nodes if the version doesn't match.
|
|
|
|
currentVer := make([]byte, binary.MaxVarintLen64)
|
2015-04-27 05:28:17 -07:00
|
|
|
currentVer = currentVer[:binary.PutVarint(currentVer, int64(version))]
|
2015-04-24 08:04:41 -07:00
|
|
|
|
|
|
|
blob, err := db.Get(nodeDBVersionKey, nil)
|
|
|
|
switch err {
|
|
|
|
case leveldb.ErrNotFound:
|
|
|
|
// Version not found (i.e. empty cache), insert it
|
2015-04-27 00:19:16 -07:00
|
|
|
if err := db.Put(nodeDBVersionKey, currentVer, nil); err != nil {
|
|
|
|
db.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-04-24 08:04:41 -07:00
|
|
|
|
|
|
|
case nil:
|
|
|
|
// Version present, flush if different
|
|
|
|
if !bytes.Equal(blob, currentVer) {
|
|
|
|
db.Close()
|
|
|
|
if err = os.RemoveAll(path); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-05-21 09:41:46 -07:00
|
|
|
return newPersistentNodeDB(path, version, self)
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
}
|
2015-04-27 07:38:28 -07:00
|
|
|
return &nodeDB{
|
|
|
|
lvl: db,
|
2015-05-21 09:41:46 -07:00
|
|
|
self: self,
|
2015-04-27 07:38:28 -07:00
|
|
|
quit: make(chan struct{}),
|
|
|
|
}, nil
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
2015-04-27 00:19:16 -07:00
|
|
|
// makeKey generates the leveldb key-blob from a node id and its particular
|
|
|
|
// field of interest.
|
|
|
|
func makeKey(id NodeID, field string) []byte {
|
2015-04-27 02:33:06 -07:00
|
|
|
if bytes.Equal(id[:], nodeDBNilNodeID[:]) {
|
|
|
|
return []byte(field)
|
|
|
|
}
|
2015-04-24 08:04:41 -07:00
|
|
|
return append(nodeDBItemPrefix, append(id[:], field...)...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// splitKey tries to split a database key into a node id and a field part.
|
2015-04-27 00:19:16 -07:00
|
|
|
func splitKey(key []byte) (id NodeID, field string) {
|
2015-04-24 08:04:41 -07:00
|
|
|
// If the key is not of a node, return it plainly
|
|
|
|
if !bytes.HasPrefix(key, nodeDBItemPrefix) {
|
|
|
|
return NodeID{}, string(key)
|
|
|
|
}
|
|
|
|
// Otherwise split the id and field
|
|
|
|
item := key[len(nodeDBItemPrefix):]
|
|
|
|
copy(id[:], item[:len(id)])
|
|
|
|
field = string(item[len(id):])
|
|
|
|
|
|
|
|
return id, field
|
|
|
|
}
|
|
|
|
|
2015-04-27 00:19:16 -07:00
|
|
|
// fetchInt64 retrieves an integer instance associated with a particular
|
|
|
|
// database key.
|
|
|
|
func (db *nodeDB) fetchInt64(key []byte) int64 {
|
2015-04-24 08:04:41 -07:00
|
|
|
blob, err := db.lvl.Get(key, nil)
|
|
|
|
if err != nil {
|
2015-04-27 00:19:16 -07:00
|
|
|
return 0
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
2015-04-27 00:19:16 -07:00
|
|
|
val, read := binary.Varint(blob)
|
|
|
|
if read <= 0 {
|
|
|
|
return 0
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
2015-04-27 00:19:16 -07:00
|
|
|
return val
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
2015-04-27 00:19:16 -07:00
|
|
|
// storeInt64 update a specific database entry to the current time instance as a
|
2015-04-24 08:04:41 -07:00
|
|
|
// unix timestamp.
|
2015-04-27 00:19:16 -07:00
|
|
|
func (db *nodeDB) storeInt64(key []byte, n int64) error {
|
|
|
|
blob := make([]byte, binary.MaxVarintLen64)
|
|
|
|
blob = blob[:binary.PutVarint(blob, n)]
|
|
|
|
|
2015-04-24 08:04:41 -07:00
|
|
|
return db.lvl.Put(key, blob, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
// node retrieves a node with a given id from the database.
|
|
|
|
func (db *nodeDB) node(id NodeID) *Node {
|
2015-04-27 00:19:16 -07:00
|
|
|
blob, err := db.lvl.Get(makeKey(id, nodeDBDiscoverRoot), nil)
|
2015-04-24 08:04:41 -07:00
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
node := new(Node)
|
|
|
|
if err := rlp.DecodeBytes(blob, node); err != nil {
|
2017-02-24 00:58:04 -08:00
|
|
|
log.Error("Failed to decode node RLP", "err", err)
|
2015-04-24 08:04:41 -07:00
|
|
|
return nil
|
|
|
|
}
|
2016-02-21 10:40:27 -08:00
|
|
|
node.sha = crypto.Keccak256Hash(node.ID[:])
|
2015-04-24 08:04:41 -07:00
|
|
|
return node
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateNode inserts - potentially overwriting - a node into the peer database.
|
|
|
|
func (db *nodeDB) updateNode(node *Node) error {
|
|
|
|
blob, err := rlp.EncodeToBytes(node)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2015-04-27 00:19:16 -07:00
|
|
|
return db.lvl.Put(makeKey(node.ID, nodeDBDiscoverRoot), blob, nil)
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
2015-05-21 09:41:46 -07:00
|
|
|
// deleteNode deletes all information/keys associated with a node.
|
|
|
|
func (db *nodeDB) deleteNode(id NodeID) error {
|
|
|
|
deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil)
|
|
|
|
for deleter.Next() {
|
|
|
|
if err := db.lvl.Delete(deleter.Key(), nil); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-04-28 00:28:04 -07:00
|
|
|
// ensureExpirer is a small helper method ensuring that the data expiration
|
|
|
|
// mechanism is running. If the expiration goroutine is already running, this
|
|
|
|
// method simply returns.
|
|
|
|
//
|
|
|
|
// The goal is to start the data evacuation only after the network successfully
|
|
|
|
// bootstrapped itself (to prevent dumping potentially useful seed nodes). Since
|
|
|
|
// it would require significant overhead to exactly trace the first successful
|
|
|
|
// convergence, it's simpler to "ensure" the correct state when an appropriate
|
|
|
|
// condition occurs (i.e. a successful bonding), and discard further events.
|
|
|
|
func (db *nodeDB) ensureExpirer() {
|
|
|
|
db.runner.Do(func() { go db.expirer() })
|
|
|
|
}
|
|
|
|
|
2015-04-27 07:38:28 -07:00
|
|
|
// expirer should be started in a go routine, and is responsible for looping ad
|
|
|
|
// infinitum and dropping stale data from the database.
|
|
|
|
func (db *nodeDB) expirer() {
|
2017-12-17 19:03:48 -08:00
|
|
|
tick := time.NewTicker(nodeDBCleanupCycle)
|
|
|
|
defer tick.Stop()
|
2015-04-28 00:28:04 -07:00
|
|
|
for {
|
|
|
|
select {
|
2017-12-17 19:03:48 -08:00
|
|
|
case <-tick.C:
|
2015-04-28 00:28:04 -07:00
|
|
|
if err := db.expireNodes(); err != nil {
|
2017-02-24 00:58:04 -08:00
|
|
|
log.Error("Failed to expire nodedb items", "err", err)
|
2015-04-27 07:38:28 -07:00
|
|
|
}
|
2015-04-28 00:28:04 -07:00
|
|
|
case <-db.quit:
|
|
|
|
return
|
2015-04-27 07:38:28 -07:00
|
|
|
}
|
2015-04-28 00:28:04 -07:00
|
|
|
}
|
2015-04-27 07:38:28 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// expireNodes iterates over the database and deletes all nodes that have not
|
2016-07-12 02:42:47 -07:00
|
|
|
// been seen (i.e. received a pong from) for some allotted time.
|
2015-04-27 07:38:28 -07:00
|
|
|
func (db *nodeDB) expireNodes() error {
|
|
|
|
threshold := time.Now().Add(-nodeDBNodeExpiration)
|
|
|
|
|
|
|
|
// Find discovered nodes that are older than the allowance
|
|
|
|
it := db.lvl.NewIterator(nil, nil)
|
|
|
|
defer it.Release()
|
|
|
|
|
|
|
|
for it.Next() {
|
|
|
|
// Skip the item if not a discovery node
|
|
|
|
id, field := splitKey(it.Key())
|
|
|
|
if field != nodeDBDiscoverRoot {
|
|
|
|
continue
|
|
|
|
}
|
2015-05-21 09:41:46 -07:00
|
|
|
// Skip the node if not expired yet (and not self)
|
2017-01-06 07:44:20 -08:00
|
|
|
if !bytes.Equal(id[:], db.self[:]) {
|
2018-02-16 11:16:23 -08:00
|
|
|
if seen := db.bondTime(id); seen.After(threshold) {
|
2015-05-21 09:41:46 -07:00
|
|
|
continue
|
2015-04-27 07:38:28 -07:00
|
|
|
}
|
|
|
|
}
|
2015-05-21 09:41:46 -07:00
|
|
|
// Otherwise delete all associated information
|
|
|
|
db.deleteNode(id)
|
2015-04-27 07:38:28 -07:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-04-24 08:04:41 -07:00
|
|
|
// lastPing retrieves the time of the last ping packet send to a remote node,
|
|
|
|
// requesting binding.
|
|
|
|
func (db *nodeDB) lastPing(id NodeID) time.Time {
|
2015-04-27 00:19:16 -07:00
|
|
|
return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0)
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// updateLastPing updates the last time we tried contacting a remote node.
|
|
|
|
func (db *nodeDB) updateLastPing(id NodeID, instance time.Time) error {
|
2015-04-27 00:19:16 -07:00
|
|
|
return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix())
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
2018-02-16 11:16:23 -08:00
|
|
|
// bondTime retrieves the time of the last successful pong from remote node.
|
|
|
|
func (db *nodeDB) bondTime(id NodeID) time.Time {
|
2015-04-27 02:33:06 -07:00
|
|
|
return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0)
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
2018-02-16 11:16:23 -08:00
|
|
|
// hasBond reports whether the given node is considered bonded.
|
|
|
|
func (db *nodeDB) hasBond(id NodeID) bool {
|
|
|
|
return time.Since(db.bondTime(id)) < nodeDBNodeExpiration
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateBondTime updates the last pong time of a node.
|
|
|
|
func (db *nodeDB) updateBondTime(id NodeID, instance time.Time) error {
|
2015-04-27 02:33:06 -07:00
|
|
|
return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix())
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
2015-05-25 05:04:05 -07:00
|
|
|
// findFails retrieves the number of findnode failures since bonding.
|
|
|
|
func (db *nodeDB) findFails(id NodeID) int {
|
|
|
|
return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails)))
|
|
|
|
}
|
|
|
|
|
|
|
|
// updateFindFails updates the number of findnode failures since bonding.
|
|
|
|
func (db *nodeDB) updateFindFails(id NodeID, fails int) error {
|
|
|
|
return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails))
|
|
|
|
}
|
|
|
|
|
2015-09-29 20:01:49 -07:00
|
|
|
// querySeeds retrieves random nodes to be used as potential seed nodes
|
|
|
|
// for bootstrapping.
|
|
|
|
func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node {
|
|
|
|
var (
|
|
|
|
now = time.Now()
|
|
|
|
nodes = make([]*Node, 0, n)
|
|
|
|
it = db.lvl.NewIterator(nil, nil)
|
|
|
|
id NodeID
|
|
|
|
)
|
|
|
|
defer it.Release()
|
|
|
|
|
|
|
|
seek:
|
|
|
|
for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ {
|
|
|
|
// Seek to a random entry. The first byte is incremented by a
|
|
|
|
// random amount each time in order to increase the likelihood
|
|
|
|
// of hitting all existing nodes in very small databases.
|
|
|
|
ctr := id[0]
|
|
|
|
rand.Read(id[:])
|
|
|
|
id[0] = ctr + id[0]%16
|
|
|
|
it.Seek(makeKey(id, nodeDBDiscoverRoot))
|
|
|
|
|
|
|
|
n := nextNode(it)
|
|
|
|
if n == nil {
|
|
|
|
id[0] = 0
|
|
|
|
continue seek // iterator exhausted
|
|
|
|
}
|
|
|
|
if n.ID == db.self {
|
|
|
|
continue seek
|
|
|
|
}
|
2018-02-16 11:16:23 -08:00
|
|
|
if now.Sub(db.bondTime(n.ID)) > maxAge {
|
2015-09-29 20:01:49 -07:00
|
|
|
continue seek
|
|
|
|
}
|
|
|
|
for i := range nodes {
|
|
|
|
if nodes[i].ID == n.ID {
|
|
|
|
continue seek // duplicate
|
|
|
|
}
|
|
|
|
}
|
|
|
|
nodes = append(nodes, n)
|
2015-04-27 04:45:35 -07:00
|
|
|
}
|
2015-09-29 20:01:49 -07:00
|
|
|
return nodes
|
|
|
|
}
|
|
|
|
|
|
|
|
// reads the next node record from the iterator, skipping over other
|
|
|
|
// database entries.
|
|
|
|
func nextNode(it iterator.Iterator) *Node {
|
|
|
|
for end := false; !end; end = !it.Next() {
|
|
|
|
id, field := splitKey(it.Key())
|
2015-04-24 08:04:41 -07:00
|
|
|
if field != nodeDBDiscoverRoot {
|
|
|
|
continue
|
|
|
|
}
|
2015-09-29 20:01:49 -07:00
|
|
|
var n Node
|
|
|
|
if err := rlp.DecodeBytes(it.Value(), &n); err != nil {
|
2017-02-24 00:58:04 -08:00
|
|
|
log.Warn("Failed to decode node RLP", "id", id, "err", err)
|
2015-05-21 09:41:46 -07:00
|
|
|
continue
|
|
|
|
}
|
2015-09-29 20:01:49 -07:00
|
|
|
return &n
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
2015-09-29 20:01:49 -07:00
|
|
|
return nil
|
2015-04-24 08:04:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// close flushes and closes the database files.
|
|
|
|
func (db *nodeDB) close() {
|
2015-04-27 07:38:28 -07:00
|
|
|
close(db.quit)
|
2015-04-24 08:04:41 -07:00
|
|
|
db.lvl.Close()
|
|
|
|
}
|