database.go 12 KB

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