github.com/annchain/OG@v0.0.9/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 "github.com/annchain/OG/arefactor/common/goroutine" 28 ogcrypto2 "github.com/annchain/OG/deprecated/ogcrypto" 29 "os" 30 "sync" 31 "time" 32 33 "github.com/syndtr/goleveldb/leveldb" 34 "github.com/syndtr/goleveldb/leveldb/errors" 35 "github.com/syndtr/goleveldb/leveldb/iterator" 36 "github.com/syndtr/goleveldb/leveldb/opt" 37 "github.com/syndtr/goleveldb/leveldb/storage" 38 "github.com/syndtr/goleveldb/leveldb/util" 39 ) 40 41 var ( 42 nodeDBNilNodeID = NodeID{} // Special node ID to use as a nil element. 43 nodeDBNodeExpiration = 24 * time.Hour // Time after which an unseen node should be dropped. 44 nodeDBCleanupCycle = time.Hour // Time period for running the expiration task. 45 ) 46 47 // nodeDB stores all nodes we know about. 48 type nodeDB struct { 49 lvl *leveldb.DB // Interface to the database itself 50 self NodeID // Own node id to prevent adding it into the database 51 runner sync.Once // Ensures we can start at most one expirer 52 quit chan struct{} // Channel to signal the expiring thread to stop 53 } 54 55 // Schema layout for the node database 56 var ( 57 nodeDBVersionKey = []byte("version") // Version of the database to flush if changes 58 nodeDBItemPrefix = []byte("n:") // Identifier to prefix node entries with 59 60 nodeDBDiscoverRoot = ":discover" 61 nodeDBDiscoverPing = nodeDBDiscoverRoot + ":lastping" 62 nodeDBDiscoverPong = nodeDBDiscoverRoot + ":lastpong" 63 nodeDBDiscoverFindFails = nodeDBDiscoverRoot + ":findfail" 64 nodeDBDiscoverLocalEndpoint = nodeDBDiscoverRoot + ":localendpoint" 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) storeData(key []byte, blob []byte) error { 180 181 return db.lvl.Put(key, blob, nil) 182 } 183 184 func (db *nodeDB) fetchData(key []byte) (blob []byte, err error) { 185 blob, err = db.lvl.Get(key, nil) 186 if err != nil { 187 return nil, err 188 } 189 return blob, err 190 } 191 192 // node retrieves a node with a given id from the database. 193 func (db *nodeDB) node(id NodeID) *Node { 194 var node Node 195 data, err := db.fetchData(makeKey(id, nodeDBDiscoverRoot)) 196 if err != nil { 197 return nil 198 } 199 _, err = node.UnmarshalMsg(data) 200 if err != nil { 201 return nil 202 } 203 node.sha = ogcrypto2.Keccak256Hash(node.ID[:]) 204 return &node 205 } 206 207 // updateNode inserts - potentially overwriting - a node into the peer database. 208 func (db *nodeDB) updateNode(node *Node) error { 209 data, _ := node.MarshalMsg(nil) 210 return db.storeData(makeKey(node.ID, nodeDBDiscoverRoot), data) 211 } 212 213 // deleteNode deletes all information/keys associated with a node. 214 func (db *nodeDB) deleteNode(id NodeID) error { 215 deleter := db.lvl.NewIterator(util.BytesPrefix(makeKey(id, "")), nil) 216 for deleter.Next() { 217 if err := db.lvl.Delete(deleter.Key(), nil); err != nil { 218 return err 219 } 220 } 221 return nil 222 } 223 224 // ensureExpirer is a small helper method ensuring that the data expiration 225 // mechanism is running. If the expiration goroutine is already running, this 226 // method simply returns. 227 // 228 // The goal is to start the data evacuation only after the network successfully 229 // bootstrapped itself (to prevent dumping potentially useful seed nodes). Since 230 // it would require significant overhead to exactly trace the first successful 231 // convergence, it's simpler to "ensure" the correct state when an appropriate 232 // condition occurs (i.e. a successful bonding), and discard further events. 233 func (db *nodeDB) ensureExpirer() { 234 db.runner.Do(func() { goroutine.New(db.expirer) }) 235 } 236 237 // expirer should be started in a go routine, and is responsible for looping ad 238 // infinitum and dropping stale data from the database. 239 func (db *nodeDB) expirer() { 240 tick := time.NewTicker(nodeDBCleanupCycle) 241 defer tick.Stop() 242 for { 243 select { 244 case <-tick.C: 245 if err := db.expireNodes(); err != nil { 246 log.Error(fmt.Sprintf("Failed to expire nodedb items: %v", err)) 247 } 248 case <-db.quit: 249 return 250 } 251 } 252 } 253 254 // expireNodes iterates over the database and deletes all nodes that have not 255 // been seen (i.e. received a pong from) for some allotted time. 256 func (db *nodeDB) expireNodes() error { 257 threshold := time.Now().Add(-nodeDBNodeExpiration) 258 259 // Find discovered nodes that are older than the allowance 260 it := db.lvl.NewIterator(nil, nil) 261 defer it.Release() 262 263 for it.Next() { 264 // Skip the item if not a discovery node 265 id, field := splitKey(it.Key()) 266 if field != nodeDBDiscoverRoot { 267 continue 268 } 269 // Skip the node if not expired yet (and not self) 270 if !bytes.Equal(id[:], db.self[:]) { 271 if seen := db.lastPong(id); seen.After(threshold) { 272 continue 273 } 274 } 275 // Otherwise delete all associated information 276 db.deleteNode(id) 277 } 278 return nil 279 } 280 281 // lastPing retrieves the time of the last ping packet send to a remote node, 282 // requesting binding. 283 func (db *nodeDB) lastPing(id NodeID) time.Time { 284 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPing)), 0) 285 } 286 287 // updateLastPing updates the last time we tried contacting a remote node. 288 func (db *nodeDB) updateLastPing(id NodeID, instance time.Time) error { 289 return db.storeInt64(makeKey(id, nodeDBDiscoverPing), instance.Unix()) 290 } 291 292 // lastPong retrieves the time of the last successful contact from remote node. 293 func (db *nodeDB) lastPong(id NodeID) time.Time { 294 return time.Unix(db.fetchInt64(makeKey(id, nodeDBDiscoverPong)), 0) 295 } 296 297 // updateLastPong updates the last time a remote node successfully contacted. 298 func (db *nodeDB) updateLastPong(id NodeID, instance time.Time) error { 299 return db.storeInt64(makeKey(id, nodeDBDiscoverPong), instance.Unix()) 300 } 301 302 // findFails retrieves the number of findnode failures since bonding. 303 func (db *nodeDB) findFails(id NodeID) int { 304 return int(db.fetchInt64(makeKey(id, nodeDBDiscoverFindFails))) 305 } 306 307 // updateFindFails updates the number of findnode failures since bonding. 308 func (db *nodeDB) updateFindFails(id NodeID, fails int) error { 309 return db.storeInt64(makeKey(id, nodeDBDiscoverFindFails), int64(fails)) 310 } 311 312 // localEndpoint returns the last local endpoint communicated to the 313 // given remote node. 314 func (db *nodeDB) localEndpoint(id NodeID) *RpcEndpoint { 315 var ep RpcEndpoint 316 317 data, err := db.fetchData(makeKey(id, nodeDBDiscoverLocalEndpoint)) 318 if err != nil { 319 return nil 320 } 321 _, err = ep.UnmarshalMsg(data) 322 if err != nil { 323 log.Warn("unmarshal RpcEndpoint err,", err) 324 return nil 325 } 326 return &ep 327 } 328 329 func (db *nodeDB) updateLocalEndpoint(id NodeID, ep RpcEndpoint) error { 330 data, _ := ep.MarshalMsg(nil) 331 return db.storeData(makeKey(id, nodeDBDiscoverLocalEndpoint), data) 332 } 333 334 // querySeeds retrieves random nodes to be used as potential seed nodes 335 // for bootstrapping. 336 func (db *nodeDB) querySeeds(n int, maxAge time.Duration) []*Node { 337 var ( 338 now = time.Now() 339 nodes = make([]*Node, 0, n) 340 it = db.lvl.NewIterator(nil, nil) 341 id NodeID 342 ) 343 defer it.Release() 344 345 seek: 346 for seeks := 0; len(nodes) < n && seeks < n*5; seeks++ { 347 // Seek to a random entry. The first byte is incremented by a 348 // random amount each time in order to increase the likelihood 349 // of hitting all existing nodes in very small databases. 350 ctr := id[0] 351 rand.Read(id[:]) 352 id[0] = ctr + id[0]%16 353 it.Seek(makeKey(id, nodeDBDiscoverRoot)) 354 355 n := nextNode(it) 356 if n == nil { 357 id[0] = 0 358 continue seek // iterator exhausted 359 } 360 if n.ID == db.self { 361 continue seek 362 } 363 if now.Sub(db.lastPong(n.ID)) > maxAge { 364 continue seek 365 } 366 for i := range nodes { 367 if nodes[i].ID == n.ID { 368 continue seek // duplicate 369 } 370 } 371 nodes = append(nodes, n) 372 } 373 return nodes 374 } 375 376 func (db *nodeDB) fetchTopicRegTickets(id NodeID) (issued, used uint32) { 377 key := makeKey(id, nodeDBTopicRegTickets) 378 blob, _ := db.lvl.Get(key, nil) 379 if len(blob) != 8 { 380 return 0, 0 381 } 382 issued = binary.BigEndian.Uint32(blob[0:4]) 383 used = binary.BigEndian.Uint32(blob[4:8]) 384 return 385 } 386 387 func (db *nodeDB) updateTopicRegTickets(id NodeID, issued, used uint32) error { 388 key := makeKey(id, nodeDBTopicRegTickets) 389 blob := make([]byte, 8) 390 binary.BigEndian.PutUint32(blob[0:4], issued) 391 binary.BigEndian.PutUint32(blob[4:8], used) 392 return db.lvl.Put(key, blob, nil) 393 } 394 395 // reads the next node record from the iterator, skipping over other 396 // database entries. 397 func nextNode(it iterator.Iterator) *Node { 398 for end := false; !end; end = !it.Next() { 399 id, field := splitKey(it.Key()) 400 if field != nodeDBDiscoverRoot { 401 continue 402 } 403 var n Node 404 if _, err := n.UnmarshalMsg(it.Value()); err != nil { 405 log.Warn(fmt.Sprintf("invalid node %x: %v", id, err)) 406 continue 407 } 408 return &n 409 } 410 return nil 411 } 412 413 // close flushes and closes the database files. 414 func (db *nodeDB) close() { 415 close(db.quit) 416 db.lvl.Close() 417 }