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