github.com/ethereum/go-ethereum@v1.16.1/p2p/enode/nodedb.go (about) 1 // Copyright 2018 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 package enode 18 19 import ( 20 "bytes" 21 "crypto/rand" 22 "encoding/binary" 23 "fmt" 24 "net/netip" 25 "os" 26 "sync" 27 "time" 28 29 "github.com/ethereum/go-ethereum/p2p/enr" 30 "github.com/ethereum/go-ethereum/rlp" 31 "github.com/syndtr/goleveldb/leveldb" 32 "github.com/syndtr/goleveldb/leveldb/errors" 33 "github.com/syndtr/goleveldb/leveldb/iterator" 34 "github.com/syndtr/goleveldb/leveldb/opt" 35 "github.com/syndtr/goleveldb/leveldb/storage" 36 "github.com/syndtr/goleveldb/leveldb/util" 37 ) 38 39 // Keys in the node database. 40 const ( 41 dbVersionKey = "version" // Version of the database to flush if changes 42 dbNodePrefix = "n:" // Identifier to prefix node entries with 43 dbLocalPrefix = "local:" 44 dbDiscoverRoot = "v4" 45 dbDiscv5Root = "v5" 46 47 // These fields are stored per ID and IP, the full key is "n:<ID>:v4:<IP>:findfail". 48 // Use nodeItemKey to create those keys. 49 dbNodeFindFails = "findfail" 50 dbNodePing = "lastping" 51 dbNodePong = "lastpong" 52 dbNodeSeq = "seq" 53 54 // Local information is keyed by ID only, the full key is "local:<ID>:seq". 55 // Use localItemKey to create those keys. 56 dbLocalSeq = "seq" 57 ) 58 59 const ( 60 dbNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped. 61 dbCleanupCycle = time.Hour // Time period for running the expiration task. 62 dbVersion = 9 63 ) 64 65 var ( 66 errInvalidIP = errors.New("invalid IP") 67 ) 68 69 var zeroIP = netip.IPv6Unspecified() 70 71 // DB is the node database, storing previously seen nodes and any collected metadata about 72 // them for QoS purposes. 73 type DB struct { 74 lvl *leveldb.DB // Interface to the database itself 75 runner sync.Once // Ensures we can start at most one expirer 76 quit chan struct{} // Channel to signal the expiring thread to stop 77 } 78 79 // OpenDB opens a node database for storing and retrieving infos about known peers in the 80 // network. If no path is given an in-memory, temporary database is constructed. 81 func OpenDB(path string) (*DB, error) { 82 if path == "" { 83 return newMemoryDB() 84 } 85 return newPersistentDB(path) 86 } 87 88 // newMemoryDB creates a new in-memory node database without a persistent backend. 89 func newMemoryDB() (*DB, error) { 90 db, err := leveldb.Open(storage.NewMemStorage(), nil) 91 if err != nil { 92 return nil, err 93 } 94 return &DB{lvl: db, quit: make(chan struct{})}, nil 95 } 96 97 // newPersistentDB creates/opens a leveldb backed persistent node database, 98 // also flushing its contents in case of a version mismatch. 99 func newPersistentDB(path string) (*DB, error) { 100 opts := &opt.Options{OpenFilesCacheCapacity: 5} 101 db, err := leveldb.OpenFile(path, opts) 102 if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted { 103 db, err = leveldb.RecoverFile(path, nil) 104 } 105 if err != nil { 106 return nil, err 107 } 108 // The nodes contained in the cache correspond to a certain protocol version. 109 // Flush all nodes if the version doesn't match. 110 currentVer := make([]byte, binary.MaxVarintLen64) 111 currentVer = currentVer[:binary.PutVarint(currentVer, int64(dbVersion))] 112 113 blob, err := db.Get([]byte(dbVersionKey), nil) 114 switch err { 115 case leveldb.ErrNotFound: 116 // Version not found (i.e. empty cache), insert it 117 if err := db.Put([]byte(dbVersionKey), currentVer, nil); err != nil { 118 db.Close() 119 return nil, err 120 } 121 122 case nil: 123 // Version present, flush if different 124 if !bytes.Equal(blob, currentVer) { 125 db.Close() 126 if err = os.RemoveAll(path); err != nil { 127 return nil, err 128 } 129 return newPersistentDB(path) 130 } 131 } 132 return &DB{lvl: db, quit: make(chan struct{})}, nil 133 } 134 135 // nodeKey returns the database key for a node record. 136 func nodeKey(id ID) []byte { 137 key := append([]byte(dbNodePrefix), id[:]...) 138 key = append(key, ':') 139 key = append(key, dbDiscoverRoot...) 140 return key 141 } 142 143 // splitNodeKey returns the node ID of a key created by nodeKey. 144 func splitNodeKey(key []byte) (id ID, rest []byte) { 145 if !bytes.HasPrefix(key, []byte(dbNodePrefix)) { 146 return ID{}, nil 147 } 148 item := key[len(dbNodePrefix):] 149 copy(id[:], item[:len(id)]) 150 return id, item[len(id)+1:] 151 } 152 153 // nodeItemKey returns the database key for a node metadata field. 154 func nodeItemKey(id ID, ip netip.Addr, field string) []byte { 155 if !ip.IsValid() { 156 panic("invalid IP") 157 } 158 ip16 := ip.As16() 159 return bytes.Join([][]byte{nodeKey(id), ip16[:], []byte(field)}, []byte{':'}) 160 } 161 162 // splitNodeItemKey returns the components of a key created by nodeItemKey. 163 func splitNodeItemKey(key []byte) (id ID, ip netip.Addr, field string) { 164 id, key = splitNodeKey(key) 165 // Skip discover root. 166 if string(key) == dbDiscoverRoot { 167 return id, netip.Addr{}, "" 168 } 169 key = key[len(dbDiscoverRoot)+1:] 170 // Split out the IP. 171 ip, _ = netip.AddrFromSlice(key[:16]) 172 key = key[16+1:] 173 // Field is the remainder of key. 174 field = string(key) 175 return id, ip, field 176 } 177 178 func v5Key(id ID, ip netip.Addr, field string) []byte { 179 ip16 := ip.As16() 180 return bytes.Join([][]byte{ 181 []byte(dbNodePrefix), 182 id[:], 183 []byte(dbDiscv5Root), 184 ip16[:], 185 []byte(field), 186 }, []byte{':'}) 187 } 188 189 // localItemKey returns the key of a local node item. 190 func localItemKey(id ID, field string) []byte { 191 key := append([]byte(dbLocalPrefix), id[:]...) 192 key = append(key, ':') 193 key = append(key, field...) 194 return key 195 } 196 197 // fetchInt64 retrieves an integer associated with a particular key. 198 func (db *DB) fetchInt64(key []byte) int64 { 199 blob, err := db.lvl.Get(key, nil) 200 if err != nil { 201 return 0 202 } 203 val, read := binary.Varint(blob) 204 if read <= 0 { 205 return 0 206 } 207 return val 208 } 209 210 // storeInt64 stores an integer in the given key. 211 func (db *DB) storeInt64(key []byte, n int64) error { 212 blob := make([]byte, binary.MaxVarintLen64) 213 blob = blob[:binary.PutVarint(blob, n)] 214 return db.lvl.Put(key, blob, nil) 215 } 216 217 // fetchUint64 retrieves an integer associated with a particular key. 218 func (db *DB) fetchUint64(key []byte) uint64 { 219 blob, err := db.lvl.Get(key, nil) 220 if err != nil { 221 return 0 222 } 223 val, _ := binary.Uvarint(blob) 224 return val 225 } 226 227 // storeUint64 stores an integer in the given key. 228 func (db *DB) storeUint64(key []byte, n uint64) error { 229 blob := make([]byte, binary.MaxVarintLen64) 230 blob = blob[:binary.PutUvarint(blob, n)] 231 return db.lvl.Put(key, blob, nil) 232 } 233 234 // Node retrieves a node with a given id from the database. 235 func (db *DB) Node(id ID) *Node { 236 blob, err := db.lvl.Get(nodeKey(id), nil) 237 if err != nil { 238 return nil 239 } 240 return mustDecodeNode(id[:], blob) 241 } 242 243 func mustDecodeNode(id, data []byte) *Node { 244 var r enr.Record 245 if err := rlp.DecodeBytes(data, &r); err != nil { 246 panic(fmt.Errorf("p2p/enode: can't decode node %x in DB: %v", id, err)) 247 } 248 if len(id) != len(ID{}) { 249 panic(fmt.Errorf("invalid id length %d", len(id))) 250 } 251 return newNodeWithID(&r, ID(id)) 252 } 253 254 // UpdateNode inserts - potentially overwriting - a node into the peer database. 255 func (db *DB) UpdateNode(node *Node) error { 256 if node.Seq() < db.NodeSeq(node.ID()) { 257 return nil 258 } 259 blob, err := rlp.EncodeToBytes(&node.r) 260 if err != nil { 261 return err 262 } 263 if err := db.lvl.Put(nodeKey(node.ID()), blob, nil); err != nil { 264 return err 265 } 266 return db.storeUint64(nodeItemKey(node.ID(), zeroIP, dbNodeSeq), node.Seq()) 267 } 268 269 // NodeSeq returns the stored record sequence number of the given node. 270 func (db *DB) NodeSeq(id ID) uint64 { 271 return db.fetchUint64(nodeItemKey(id, zeroIP, dbNodeSeq)) 272 } 273 274 // Resolve returns the stored record of the node if it has a larger sequence 275 // number than n. 276 func (db *DB) Resolve(n *Node) *Node { 277 if n.Seq() > db.NodeSeq(n.ID()) { 278 return n 279 } 280 return db.Node(n.ID()) 281 } 282 283 // DeleteNode deletes all information associated with a node. 284 func (db *DB) DeleteNode(id ID) { 285 deleteRange(db.lvl, nodeKey(id)) 286 } 287 288 func deleteRange(db *leveldb.DB, prefix []byte) { 289 it := db.NewIterator(util.BytesPrefix(prefix), nil) 290 defer it.Release() 291 for it.Next() { 292 db.Delete(it.Key(), nil) 293 } 294 } 295 296 // ensureExpirer is a small helper method ensuring that the data expiration 297 // mechanism is running. If the expiration goroutine is already running, this 298 // method simply returns. 299 // 300 // The goal is to start the data evacuation only after the network successfully 301 // bootstrapped itself (to prevent dumping potentially useful seed nodes). Since 302 // it would require significant overhead to exactly trace the first successful 303 // convergence, it's simpler to "ensure" the correct state when an appropriate 304 // condition occurs (i.e. a successful bonding), and discard further events. 305 func (db *DB) ensureExpirer() { 306 db.runner.Do(func() { go db.expirer() }) 307 } 308 309 // expirer should be started in a go routine, and is responsible for looping ad 310 // infinitum and dropping stale data from the database. 311 func (db *DB) expirer() { 312 tick := time.NewTicker(dbCleanupCycle) 313 defer tick.Stop() 314 for { 315 select { 316 case <-tick.C: 317 db.expireNodes() 318 case <-db.quit: 319 return 320 } 321 } 322 } 323 324 // expireNodes iterates over the database and deletes all nodes that have not 325 // been seen (i.e. received a pong from) for some time. 326 func (db *DB) expireNodes() { 327 it := db.lvl.NewIterator(util.BytesPrefix([]byte(dbNodePrefix)), nil) 328 defer it.Release() 329 if !it.Next() { 330 return 331 } 332 333 var ( 334 threshold = time.Now().Add(-dbNodeExpiration).Unix() 335 youngestPong int64 336 atEnd = false 337 ) 338 for !atEnd { 339 id, ip, field := splitNodeItemKey(it.Key()) 340 if field == dbNodePong { 341 time, _ := binary.Varint(it.Value()) 342 if time > youngestPong { 343 youngestPong = time 344 } 345 if time < threshold { 346 // Last pong from this IP older than threshold, remove fields belonging to it. 347 deleteRange(db.lvl, nodeItemKey(id, ip, "")) 348 } 349 } 350 atEnd = !it.Next() 351 nextID, _ := splitNodeKey(it.Key()) 352 if atEnd || nextID != id { 353 // We've moved beyond the last entry of the current ID. 354 // Remove everything if there was no recent enough pong. 355 if youngestPong > 0 && youngestPong < threshold { 356 deleteRange(db.lvl, nodeKey(id)) 357 } 358 youngestPong = 0 359 } 360 } 361 } 362 363 // LastPingReceived retrieves the time of the last ping packet received from 364 // a remote node. 365 func (db *DB) LastPingReceived(id ID, ip netip.Addr) time.Time { 366 if !ip.IsValid() { 367 return time.Time{} 368 } 369 return time.Unix(db.fetchInt64(nodeItemKey(id, ip, dbNodePing)), 0) 370 } 371 372 // UpdateLastPingReceived updates the last time we tried contacting a remote node. 373 func (db *DB) UpdateLastPingReceived(id ID, ip netip.Addr, instance time.Time) error { 374 if !ip.IsValid() { 375 return errInvalidIP 376 } 377 return db.storeInt64(nodeItemKey(id, ip, dbNodePing), instance.Unix()) 378 } 379 380 // LastPongReceived retrieves the time of the last successful pong from remote node. 381 func (db *DB) LastPongReceived(id ID, ip netip.Addr) time.Time { 382 if !ip.IsValid() { 383 return time.Time{} 384 } 385 // Launch expirer 386 db.ensureExpirer() 387 return time.Unix(db.fetchInt64(nodeItemKey(id, ip, dbNodePong)), 0) 388 } 389 390 // UpdateLastPongReceived updates the last pong time of a node. 391 func (db *DB) UpdateLastPongReceived(id ID, ip netip.Addr, instance time.Time) error { 392 if !ip.IsValid() { 393 return errInvalidIP 394 } 395 return db.storeInt64(nodeItemKey(id, ip, dbNodePong), instance.Unix()) 396 } 397 398 // FindFails retrieves the number of findnode failures since bonding. 399 func (db *DB) FindFails(id ID, ip netip.Addr) int { 400 if !ip.IsValid() { 401 return 0 402 } 403 return int(db.fetchInt64(nodeItemKey(id, ip, dbNodeFindFails))) 404 } 405 406 // UpdateFindFails updates the number of findnode failures since bonding. 407 func (db *DB) UpdateFindFails(id ID, ip netip.Addr, fails int) error { 408 if !ip.IsValid() { 409 return errInvalidIP 410 } 411 return db.storeInt64(nodeItemKey(id, ip, dbNodeFindFails), int64(fails)) 412 } 413 414 // FindFailsV5 retrieves the discv5 findnode failure counter. 415 func (db *DB) FindFailsV5(id ID, ip netip.Addr) int { 416 if !ip.IsValid() { 417 return 0 418 } 419 return int(db.fetchInt64(v5Key(id, ip, dbNodeFindFails))) 420 } 421 422 // UpdateFindFailsV5 stores the discv5 findnode failure counter. 423 func (db *DB) UpdateFindFailsV5(id ID, ip netip.Addr, fails int) error { 424 if !ip.IsValid() { 425 return errInvalidIP 426 } 427 return db.storeInt64(v5Key(id, ip, dbNodeFindFails), int64(fails)) 428 } 429 430 // localSeq retrieves the local record sequence counter, defaulting to the current 431 // timestamp if no previous exists. This ensures that wiping all data associated 432 // with a node (apart from its key) will not generate already used sequence nums. 433 func (db *DB) localSeq(id ID) uint64 { 434 if seq := db.fetchUint64(localItemKey(id, dbLocalSeq)); seq > 0 { 435 return seq 436 } 437 return nowMilliseconds() 438 } 439 440 // storeLocalSeq stores the local record sequence counter. 441 func (db *DB) storeLocalSeq(id ID, n uint64) { 442 db.storeUint64(localItemKey(id, dbLocalSeq), n) 443 } 444 445 // QuerySeeds retrieves random nodes to be used as potential seed nodes 446 // for bootstrapping. 447 func (db *DB) QuerySeeds(n int, maxAge time.Duration) []*Node { 448 var ( 449 now = time.Now() 450 nodes = make([]*Node, 0, n) 451 it = db.lvl.NewIterator(nil, nil) 452 id ID 453 ) 454 defer it.Release() 455 456 seek: 457 for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ { 458 // Seek to a random entry. The first byte is incremented by a 459 // random amount each time in order to increase the likelihood 460 // of hitting all existing nodes in very small databases. 461 ctr := id[0] 462 rand.Read(id[:]) 463 id[0] = ctr + id[0]%16 464 it.Seek(nodeKey(id)) 465 466 n := nextNode(it) 467 if n == nil { 468 id[0] = 0 469 continue seek // iterator exhausted 470 } 471 if now.Sub(db.LastPongReceived(n.ID(), n.IPAddr())) > maxAge { 472 continue seek 473 } 474 for i := range nodes { 475 if nodes[i].ID() == n.ID() { 476 continue seek // duplicate 477 } 478 } 479 nodes = append(nodes, n) 480 } 481 return nodes 482 } 483 484 // reads the next node record from the iterator, skipping over other 485 // database entries. 486 func nextNode(it iterator.Iterator) *Node { 487 for end := false; !end; end = !it.Next() { 488 id, rest := splitNodeKey(it.Key()) 489 if string(rest) != dbDiscoverRoot { 490 continue 491 } 492 return mustDecodeNode(id[:], it.Value()) 493 } 494 return nil 495 } 496 497 // Close flushes and closes the database files. 498 func (db *DB) Close() { 499 select { 500 case <-db.quit: // already closed 501 default: 502 close(db.quit) 503 } 504 db.lvl.Close() 505 }