database.go 11 KB

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