github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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/ethereumproject/go-ethereum/crypto" 31 "github.com/ethereumproject/go-ethereum/logger" 32 "github.com/ethereumproject/go-ethereum/logger/glog" 33 "github.com/ethereumproject/go-ethereum/rlp" 34 "github.com/syndtr/goleveldb/leveldb" 35 "github.com/syndtr/goleveldb/leveldb/errors" 36 "github.com/syndtr/goleveldb/leveldb/iterator" 37 "github.com/syndtr/goleveldb/leveldb/opt" 38 "github.com/syndtr/goleveldb/leveldb/storage" 39 "github.com/syndtr/goleveldb/leveldb/util" 40 ) 41 42 var ( 43 nodeDBNilNodeID = NodeID{} // Special node ID to use as a nil element. 44 nodeDBNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped. 45 nodeDBCleanupCycle = time.Hour // Time period for running the expiration task. 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 glog.V(logger.Detail).Infof("node does not exist in database: %v: %v", id, err) 184 return nil 185 } 186 node := new(Node) 187 if err := rlp.DecodeBytes(blob, node); err != nil { 188 glog.V(logger.Warn).Infof("failed to decode node RLP: %v", err) 189 return nil 190 } 191 node.sha = crypto.Keccak256Hash(node.ID[:]) 192 return node 193 } 194 195 // updateNode inserts - potentially overwriting - a node into the peer database. 196 func (db *nodeDB) updateNode(node *Node) error { 197 blob, err := rlp.EncodeToBytes(node) 198 if err != nil { 199 return err 200 } 201 return db.lvl.Put(makeKey(node.ID, nodeDBDiscoverRoot), blob, nil) 202 } 203 204 // deleteNode deletes all information/keys associated with a node. 205 func (db *nodeDB) deleteNode(id NodeID) error { 206 deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil) 207 for deleter.Next() { 208 if err := db.lvl.Delete(deleter.Key(), nil); err != nil { 209 return err 210 } 211 } 212 return nil 213 } 214 215 // ensureExpirer is a small helper method ensuring that the data expiration 216 // mechanism is running. If the expiration goroutine is already running, this 217 // method simply returns. 218 // 219 // The goal is to start the data evacuation only after the network successfully 220 // bootstrapped itself (to prevent dumping potentially useful seed nodes). Since 221 // it would require significant overhead to exactly trace the first successful 222 // convergence, it's simpler to "ensure" the correct state when an appropriate 223 // condition occurs (i.e. a successful bonding), and discard further events. 224 func (db *nodeDB) ensureExpirer() { 225 db.runner.Do(func() { go db.expirer() }) 226 } 227 228 // expirer should be started in a go routine, and is responsible for looping ad 229 // infinitum and dropping stale data from the database. 230 func (db *nodeDB) expirer() { 231 ticker := time.NewTicker(nodeDBCleanupCycle) 232 defer ticker.Stop() 233 234 for { 235 select { 236 case <-ticker.C: 237 if err := db.expireNodes(); err != nil { 238 glog.Error("Failed to expire nodedb items: ", err) 239 } 240 241 case <-db.quit: 242 return 243 } 244 } 245 } 246 247 // expireNodes iterates over the database and deletes all nodes that have not 248 // been seen (i.e. received a pong from) for some alloted time. 249 func (db *nodeDB) expireNodes() error { 250 threshold := time.Now().Add(-nodeDBNodeExpiration) 251 252 // Find discovered nodes that are older than the allowance 253 it := db.lvl.NewIterator(nil, nil) 254 defer it.Release() 255 256 for it.Next() { 257 // Skip the item if not a discovery node 258 id, field := splitKey(it.Key()) 259 if field != nodeDBDiscoverRoot { 260 continue 261 } 262 // Skip the node if not expired yet (and not self) 263 if bytes.Compare(id[:], db.self[:]) != 0 { 264 if seen := db.lastPong(id); seen.After(threshold) { 265 continue 266 } 267 } 268 // Otherwise delete all associated information 269 db.deleteNode(id) 270 } 271 return nil 272 } 273 274 // lastPing retrieves the time of the last ping packet send to a remote node, 275 // requesting binding. 276 func (db *nodeDB) lastPing(id NodeID) time.Time { 277 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0) 278 } 279 280 // updateLastPing updates the last time we tried contacting a remote node. 281 func (db *nodeDB) updateLastPing(id NodeID, instance time.Time) error { 282 return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix()) 283 } 284 285 // lastPong retrieves the time of the last successful contact from remote node. 286 func (db *nodeDB) lastPong(id NodeID) time.Time { 287 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0) 288 } 289 290 // updateLastPong updates the last time a remote node successfully contacted. 291 func (db *nodeDB) updateLastPong(id NodeID, instance time.Time) error { 292 return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix()) 293 } 294 295 // findFails retrieves the number of findnode failures since bonding. 296 func (db *nodeDB) findFails(id NodeID) int { 297 return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails))) 298 } 299 300 // updateFindFails updates the number of findnode failures since bonding. 301 func (db *nodeDB) updateFindFails(id NodeID, fails int) error { 302 return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails)) 303 } 304 305 // querySeeds retrieves random nodes to be used as potential seed nodes 306 // for bootstrapping. 307 func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node { 308 var ( 309 now = time.Now() 310 nodes = make([]*Node, 0, n) 311 it = db.lvl.NewIterator(nil, nil) 312 id NodeID 313 ) 314 defer it.Release() 315 316 seek: 317 for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ { 318 // Seek to a random entry. The first byte is incremented by a 319 // random amount each time in order to increase the likelihood 320 // of hitting all existing nodes in very small databases. 321 ctr := id[0] 322 rand.Read(id[:]) 323 id[0] = ctr + id[0]%16 324 it.Seek(makeKey(id, nodeDBDiscoverRoot)) 325 326 n := nextNode(it) 327 if n == nil { 328 id[0] = 0 329 continue seek // iterator exhausted 330 } 331 if n.ID == db.self { 332 continue seek 333 } 334 if now.Sub(db.lastPong(n.ID)) > maxAge { 335 continue seek 336 } 337 for i := range nodes { 338 if nodes[i].ID == n.ID { 339 continue seek // duplicate 340 } 341 } 342 nodes = append(nodes, n) 343 } 344 return nodes 345 } 346 347 // reads the next node record from the iterator, skipping over other 348 // database entries. 349 func nextNode(it iterator.Iterator) *Node { 350 for end := false; !end; end = !it.Next() { 351 id, field := splitKey(it.Key()) 352 if field != nodeDBDiscoverRoot { 353 continue 354 } 355 var n Node 356 if err := rlp.DecodeBytes(it.Value(), &n); err != nil { 357 if glog.V(logger.Warn) { 358 glog.Errorf("invalid node %x: %v", id, err) 359 } 360 continue 361 } 362 return &n 363 } 364 return nil 365 } 366 367 // close flushes and closes the database files. 368 func (db *nodeDB) close() { 369 close(db.quit) 370 db.lvl.Close() 371 }