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