github.com/aquanetwork/aquachain@v1.7.8/p2p/discv5/database.go (about) 1 // Copyright 2015 The aquachain Authors 2 // This file is part of the aquachain library. 3 // 4 // The aquachain 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 aquachain 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 aquachain 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 discv5 21 22 import ( 23 "bytes" 24 "crypto/rand" 25 "encoding/binary" 26 "fmt" 27 "os" 28 "sync" 29 "time" 30 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 "gitlab.com/aquachain/aquachain/common/log" 38 "gitlab.com/aquachain/aquachain/crypto" 39 "gitlab.com/aquachain/aquachain/rlp" 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 // nodeDBDiscoverLocalEndpoint = nodeDBDiscoverRoot + ":localendpoint" 66 nodeDBTopicRegTickets = ":tickets" 67 ) 68 69 // newNodeDB creates a new node database for storing and retrieving infos about 70 // known peers in the network. If no path is given, an in-memory, temporary 71 // database is constructed. 72 func newNodeDB(path string, version int, self NodeID) (*nodeDB, error) { 73 if path == "" { 74 return newMemoryNodeDB(self) 75 } 76 return newPersistentNodeDB(path, version, self) 77 } 78 79 // newMemoryNodeDB creates a new in-memory node database without a persistent 80 // backend. 81 func newMemoryNodeDB(self NodeID) (*nodeDB, error) { 82 db, err := leveldb.Open(storage.NewMemStorage(), nil) 83 if err != nil { 84 return nil, err 85 } 86 return &nodeDB{ 87 lvl: db, 88 self: self, 89 quit: make(chan struct{}), 90 }, nil 91 } 92 93 // newPersistentNodeDB creates/opens a leveldb backed persistent node database, 94 // also flushing its contents in case of a version mismatch. 95 func newPersistentNodeDB(path string, version int, self NodeID) (*nodeDB, error) { 96 opts := &opt.Options{OpenFilesCacheCapacity: 5} 97 db, err := leveldb.OpenFile(path, opts) 98 if _, iscorrupted := err.(*errors.ErrCorrupted); iscorrupted { 99 db, err = leveldb.RecoverFile(path, nil) 100 } 101 if err != nil { 102 return nil, err 103 } 104 // The nodes contained in the cache correspond to a certain protocol version. 105 // Flush all nodes if the version doesn't match. 106 currentVer := make([]byte, binary.MaxVarintLen64) 107 currentVer = currentVer[:binary.PutVarint(currentVer, int64(version))] 108 109 blob, err := db.Get(nodeDBVersionKey, nil) 110 switch err { 111 case leveldb.ErrNotFound: 112 // Version not found (i.e. empty cache), insert it 113 if err := db.Put(nodeDBVersionKey, currentVer, nil); err != nil { 114 db.Close() 115 return nil, err 116 } 117 118 case nil: 119 // Version present, flush if different 120 if !bytes.Equal(blob, currentVer) { 121 db.Close() 122 if err = os.RemoveAll(path); err != nil { 123 return nil, err 124 } 125 return newPersistentNodeDB(path, version, self) 126 } 127 } 128 return &nodeDB{ 129 lvl: db, 130 self: self, 131 quit: make(chan struct{}), 132 }, nil 133 } 134 135 // makeKey generates the leveldb key-blob from a node id and its particular 136 // field of interest. 137 func makeKey(id NodeID, field string) []byte { 138 if bytes.Equal(id[:], nodeDBNilNodeID[:]) { 139 return []byte(field) 140 } 141 return append(nodeDBItemPrefix, append(id[:], field...)...) 142 } 143 144 // splitKey tries to split a database key into a node id and a field part. 145 func splitKey(key []byte) (id NodeID, field string) { 146 // If the key is not of a node, return it plainly 147 if !bytes.HasPrefix(key, nodeDBItemPrefix) { 148 return NodeID{}, string(key) 149 } 150 // Otherwise split the id and field 151 item := key[len(nodeDBItemPrefix):] 152 copy(id[:], item[:len(id)]) 153 field = string(item[len(id):]) 154 155 return id, field 156 } 157 158 // fetchInt64 retrieves an integer instance associated with a particular 159 // database key. 160 func (db *nodeDB) fetchInt64(key []byte) int64 { 161 blob, err := db.lvl.Get(key, nil) 162 if err != nil { 163 return 0 164 } 165 val, read := binary.Varint(blob) 166 if read <= 0 { 167 return 0 168 } 169 return val 170 } 171 172 // storeInt64 update a specific database entry to the current time instance as a 173 // unix timestamp. 174 func (db *nodeDB) storeInt64(key []byte, n int64) error { 175 blob := make([]byte, binary.MaxVarintLen64) 176 blob = blob[:binary.PutVarint(blob, n)] 177 return db.lvl.Put(key, blob, nil) 178 } 179 180 func (db *nodeDB) storeRLP(key []byte, val interface{}) error { 181 blob, err := rlp.EncodeToBytes(val) 182 if err != nil { 183 return err 184 } 185 return db.lvl.Put(key, blob, nil) 186 } 187 188 func (db *nodeDB) fetchRLP(key []byte, val interface{}) error { 189 blob, err := db.lvl.Get(key, nil) 190 if err != nil { 191 return err 192 } 193 err = rlp.DecodeBytes(blob, val) 194 if err != nil { 195 log.Warn(fmt.Sprintf("key %x (%T) %v", key, val, err)) 196 } 197 return err 198 } 199 200 // node retrieves a node with a given id from the database. 201 func (db *nodeDB) node(id NodeID) *Node { 202 var node Node 203 if err := db.fetchRLP(makeKey(id, nodeDBDiscoverRoot), &node); err != nil { 204 return nil 205 } 206 node.sha = crypto.Keccak256Hash(node.ID[:]) 207 return &node 208 } 209 210 // updateNode inserts - potentially overwriting - a node into the peer database. 211 func (db *nodeDB) updateNode(node *Node) error { 212 return db.storeRLP(makeKey(node.ID, nodeDBDiscoverRoot), node) 213 } 214 215 // deleteNode deletes all information/keys associated with a node. 216 func (db *nodeDB) deleteNode(id NodeID) error { 217 deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil) 218 for deleter.Next() { 219 if err := db.lvl.Delete(deleter.Key(), nil); err != nil { 220 return err 221 } 222 } 223 return nil 224 } 225 226 // ensureExpirer is a small helper method ensuring that the data expiration 227 // mechanism is running. If the expiration goroutine is already running, this 228 // method simply returns. 229 // 230 // The goal is to start the data evacuation only after the network successfully 231 // bootstrapped itself (to prevent dumping potentially useful seed nodes). Since 232 // it would require significant overhead to exactly trace the first successful 233 // convergence, it's simpler to "ensure" the correct state when an appropriate 234 // condition occurs (i.e. a successful bonding), and discard further events. 235 func (db *nodeDB) ensureExpirer() { 236 db.runner.Do(func() { go db.expirer() }) 237 } 238 239 // expirer should be started in a go routine, and is responsible for looping ad 240 // infinitum and dropping stale data from the database. 241 func (db *nodeDB) expirer() { 242 tick := time.NewTicker(nodeDBCleanupCycle) 243 defer tick.Stop() 244 for { 245 select { 246 case <-tick.C: 247 if err := db.expireNodes(); err != nil { 248 log.Error(fmt.Sprintf("Failed to expire nodedb items: %v", err)) 249 } 250 case <-db.quit: 251 return 252 } 253 } 254 } 255 256 // expireNodes iterates over the database and deletes all nodes that have not 257 // been seen (i.e. received a pong from) for some allotted time. 258 func (db *nodeDB) expireNodes() error { 259 threshold := time.Now().Add(-nodeDBNodeExpiration) 260 261 // Find discovered nodes that are older than the allowance 262 it := db.lvl.NewIterator(nil, nil) 263 defer it.Release() 264 265 for it.Next() { 266 // Skip the item if not a discovery node 267 id, field := splitKey(it.Key()) 268 if field != nodeDBDiscoverRoot { 269 continue 270 } 271 // Skip the node if not expired yet (and not self) 272 if !bytes.Equal(id[:], db.self[:]) { 273 if seen := db.lastPong(id); seen.After(threshold) { 274 continue 275 } 276 } 277 // Otherwise delete all associated information 278 db.deleteNode(id) 279 } 280 return nil 281 } 282 283 // lastPing retrieves the time of the last ping packet send to a remote node, 284 // requesting binding. 285 func (db *nodeDB) lastPing(id NodeID) time.Time { 286 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0) 287 } 288 289 // updateLastPing updates the last time we tried contacting a remote node. 290 func (db *nodeDB) updateLastPing(id NodeID, instance time.Time) error { 291 return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix()) 292 } 293 294 // lastPong retrieves the time of the last successful contact from remote node. 295 func (db *nodeDB) lastPong(id NodeID) time.Time { 296 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0) 297 } 298 299 // updateLastPong updates the last time a remote node successfully contacted. 300 func (db *nodeDB) updateLastPong(id NodeID, instance time.Time) error { 301 return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix()) 302 } 303 304 // findFails retrieves the number of findnode failures since bonding. 305 func (db *nodeDB) findFails(id NodeID) int { 306 return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails))) 307 } 308 309 // updateFindFails updates the number of findnode failures since bonding. 310 func (db *nodeDB) updateFindFails(id NodeID, fails int) error { 311 return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails)) 312 } 313 314 // querySeeds retrieves random nodes to be used as potential seed nodes 315 // for bootstrapping. 316 func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node { 317 var ( 318 now = time.Now() 319 nodes = make([]*Node, 0, n) 320 it = db.lvl.NewIterator(nil, nil) 321 id NodeID 322 ) 323 defer it.Release() 324 325 seek: 326 for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ { 327 // Seek to a random entry. The first byte is incremented by a 328 // random amount each time in order to increase the likelihood 329 // of hitting all existing nodes in very small databases. 330 ctr := id[0] 331 rand.Read(id[:]) 332 id[0] = ctr + id[0]%16 333 it.Seek(makeKey(id, nodeDBDiscoverRoot)) 334 335 n := nextNode(it) 336 if n == nil { 337 id[0] = 0 338 continue seek // iterator exhausted 339 } 340 if n.ID == db.self { 341 continue seek 342 } 343 if now.Sub(db.lastPong(n.ID)) > maxAge { 344 continue seek 345 } 346 for i := range nodes { 347 if nodes[i].ID == n.ID { 348 continue seek // duplicate 349 } 350 } 351 nodes = append(nodes, n) 352 } 353 return nodes 354 } 355 356 func (db *nodeDB) fetchTopicRegTickets(id NodeID) (issued, used uint32) { 357 key := makeKey(id, nodeDBTopicRegTickets) 358 blob, _ := db.lvl.Get(key, nil) 359 if len(blob) != 8 { 360 return 0, 0 361 } 362 issued = binary.BigEndian.Uint32(blob[0:4]) 363 used = binary.BigEndian.Uint32(blob[4:8]) 364 return 365 } 366 367 func (db *nodeDB) updateTopicRegTickets(id NodeID, issued, used uint32) error { 368 key := makeKey(id, nodeDBTopicRegTickets) 369 blob := make([]byte, 8) 370 binary.BigEndian.PutUint32(blob[0:4], issued) 371 binary.BigEndian.PutUint32(blob[4:8], used) 372 return db.lvl.Put(key, blob, nil) 373 } 374 375 // reads the next node record from the iterator, skipping over other 376 // database entries. 377 func nextNode(it iterator.Iterator) *Node { 378 for end := false; !end; end = !it.Next() { 379 id, field := splitKey(it.Key()) 380 if field != nodeDBDiscoverRoot { 381 continue 382 } 383 var n Node 384 if err := rlp.DecodeBytes(it.Value(), &n); err != nil { 385 log.Warn(fmt.Sprintf("invalid node %x: %v", id, err)) 386 continue 387 } 388 return &n 389 } 390 return nil 391 } 392 393 // close flushes and closes the database files. 394 func (db *nodeDB) close() { 395 close(db.quit) 396 db.lvl.Close() 397 }