github.com/murrekatt/go-ethereum@v1.5.8-0.20170123175102-fc52f2c007fb/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/ethereum/go-ethereum/crypto" 31 "github.com/ethereum/go-ethereum/logger" 32 "github.com/ethereum/go-ethereum/logger/glog" 33 "github.com/ethereum/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("failed to retrieve node %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 tick := time.Tick(nodeDBCleanupCycle) 232 for { 233 select { 234 case <-tick: 235 if err := db.expireNodes(); err != nil { 236 glog.V(logger.Error).Infof("Failed to expire nodedb items: %v", err) 237 } 238 239 case <-db.quit: 240 return 241 } 242 } 243 } 244 245 // expireNodes iterates over the database and deletes all nodes that have not 246 // been seen (i.e. received a pong from) for some allotted time. 247 func (db *nodeDB) expireNodes() error { 248 threshold := time.Now().Add(-nodeDBNodeExpiration) 249 250 // Find discovered nodes that are older than the allowance 251 it := db.lvl.NewIterator(nil, nil) 252 defer it.Release() 253 254 for it.Next() { 255 // Skip the item if not a discovery node 256 id, field := splitKey(it.Key()) 257 if field != nodeDBDiscoverRoot { 258 continue 259 } 260 // Skip the node if not expired yet (and not self) 261 if !bytes.Equal(id[:], db.self[:]) { 262 if seen := db.lastPong(id); seen.After(threshold) { 263 continue 264 } 265 } 266 // Otherwise delete all associated information 267 db.deleteNode(id) 268 } 269 return nil 270 } 271 272 // lastPing retrieves the time of the last ping packet send to a remote node, 273 // requesting binding. 274 func (db *nodeDB) lastPing(id NodeID) time.Time { 275 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0) 276 } 277 278 // updateLastPing updates the last time we tried contacting a remote node. 279 func (db *nodeDB) updateLastPing(id NodeID, instance time.Time) error { 280 return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix()) 281 } 282 283 // lastPong retrieves the time of the last successful contact from remote node. 284 func (db *nodeDB) lastPong(id NodeID) time.Time { 285 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0) 286 } 287 288 // updateLastPong updates the last time a remote node successfully contacted. 289 func (db *nodeDB) updateLastPong(id NodeID, instance time.Time) error { 290 return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix()) 291 } 292 293 // findFails retrieves the number of findnode failures since bonding. 294 func (db *nodeDB) findFails(id NodeID) int { 295 return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails))) 296 } 297 298 // updateFindFails updates the number of findnode failures since bonding. 299 func (db *nodeDB) updateFindFails(id NodeID, fails int) error { 300 return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails)) 301 } 302 303 // querySeeds retrieves random nodes to be used as potential seed nodes 304 // for bootstrapping. 305 func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node { 306 var ( 307 now = time.Now() 308 nodes = make([]*Node, 0, n) 309 it = db.lvl.NewIterator(nil, nil) 310 id NodeID 311 ) 312 defer it.Release() 313 314 seek: 315 for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ { 316 // Seek to a random entry. The first byte is incremented by a 317 // random amount each time in order to increase the likelihood 318 // of hitting all existing nodes in very small databases. 319 ctr := id[0] 320 rand.Read(id[:]) 321 id[0] = ctr + id[0]%16 322 it.Seek(makeKey(id, nodeDBDiscoverRoot)) 323 324 n := nextNode(it) 325 if n == nil { 326 id[0] = 0 327 continue seek // iterator exhausted 328 } 329 if n.ID == db.self { 330 continue seek 331 } 332 if now.Sub(db.lastPong(n.ID)) > maxAge { 333 continue seek 334 } 335 for i := range nodes { 336 if nodes[i].ID == n.ID { 337 continue seek // duplicate 338 } 339 } 340 nodes = append(nodes, n) 341 } 342 return nodes 343 } 344 345 // reads the next node record from the iterator, skipping over other 346 // database entries. 347 func nextNode(it iterator.Iterator) *Node { 348 for end := false; !end; end = !it.Next() { 349 id, field := splitKey(it.Key()) 350 if field != nodeDBDiscoverRoot { 351 continue 352 } 353 var n Node 354 if err := rlp.DecodeBytes(it.Value(), &n); err != nil { 355 if glog.V(logger.Warn) { 356 glog.Errorf("invalid node %x: %v", id, err) 357 } 358 continue 359 } 360 return &n 361 } 362 return nil 363 } 364 365 // close flushes and closes the database files. 366 func (db *nodeDB) close() { 367 close(db.quit) 368 db.lvl.Close() 369 }