database.go 11 KB

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