nodedb.go 14 KB

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