github.com/phillinzzz/newBsc@v1.1.6/eth/downloader/statesync.go (about) 1 // Copyright 2017 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 downloader 18 19 import ( 20 "fmt" 21 "sync" 22 "time" 23 24 "github.com/phillinzzz/newBsc/common" 25 "github.com/phillinzzz/newBsc/core/rawdb" 26 "github.com/phillinzzz/newBsc/core/state" 27 "github.com/phillinzzz/newBsc/crypto" 28 "github.com/phillinzzz/newBsc/ethdb" 29 "github.com/phillinzzz/newBsc/log" 30 "github.com/phillinzzz/newBsc/trie" 31 "golang.org/x/crypto/sha3" 32 ) 33 34 // stateReq represents a batch of state fetch requests grouped together into 35 // a single data retrieval network packet. 36 type stateReq struct { 37 nItems uint16 // Number of items requested for download (max is 384, so uint16 is sufficient) 38 trieTasks map[common.Hash]*trieTask // Trie node download tasks to track previous attempts 39 codeTasks map[common.Hash]*codeTask // Byte code download tasks to track previous attempts 40 timeout time.Duration // Maximum round trip time for this to complete 41 timer *time.Timer // Timer to fire when the RTT timeout expires 42 peer *peerConnection // Peer that we're requesting from 43 delivered time.Time // Time when the packet was delivered (independent when we process it) 44 response [][]byte // Response data of the peer (nil for timeouts) 45 dropped bool // Flag whether the peer dropped off early 46 } 47 48 // timedOut returns if this request timed out. 49 func (req *stateReq) timedOut() bool { 50 return req.response == nil 51 } 52 53 // stateSyncStats is a collection of progress stats to report during a state trie 54 // sync to RPC requests as well as to display in user logs. 55 type stateSyncStats struct { 56 processed uint64 // Number of state entries processed 57 duplicate uint64 // Number of state entries downloaded twice 58 unexpected uint64 // Number of non-requested state entries received 59 pending uint64 // Number of still pending state entries 60 } 61 62 // syncState starts downloading state with the given root hash. 63 func (d *Downloader) syncState(root common.Hash) *stateSync { 64 // Create the state sync 65 s := newStateSync(d, root) 66 select { 67 case d.stateSyncStart <- s: 68 // If we tell the statesync to restart with a new root, we also need 69 // to wait for it to actually also start -- when old requests have timed 70 // out or been delivered 71 <-s.started 72 case <-d.quitCh: 73 s.err = errCancelStateFetch 74 close(s.done) 75 } 76 return s 77 } 78 79 // stateFetcher manages the active state sync and accepts requests 80 // on its behalf. 81 func (d *Downloader) stateFetcher() { 82 for { 83 select { 84 case s := <-d.stateSyncStart: 85 for next := s; next != nil; { 86 next = d.runStateSync(next) 87 } 88 case <-d.stateCh: 89 // Ignore state responses while no sync is running. 90 case <-d.quitCh: 91 return 92 } 93 } 94 } 95 96 // runStateSync runs a state synchronisation until it completes or another root 97 // hash is requested to be switched over to. 98 func (d *Downloader) runStateSync(s *stateSync) *stateSync { 99 var ( 100 active = make(map[string]*stateReq) // Currently in-flight requests 101 finished []*stateReq // Completed or failed requests 102 timeout = make(chan *stateReq) // Timed out active requests 103 ) 104 log.Trace("State sync starting", "root", s.root) 105 106 defer func() { 107 // Cancel active request timers on exit. Also set peers to idle so they're 108 // available for the next sync. 109 for _, req := range active { 110 req.timer.Stop() 111 req.peer.SetNodeDataIdle(int(req.nItems), time.Now()) 112 } 113 }() 114 go s.run() 115 defer s.Cancel() 116 117 // Listen for peer departure events to cancel assigned tasks 118 peerDrop := make(chan *peerConnection, 1024) 119 peerSub := s.d.peers.SubscribePeerDrops(peerDrop) 120 defer peerSub.Unsubscribe() 121 122 for { 123 // Enable sending of the first buffered element if there is one. 124 var ( 125 deliverReq *stateReq 126 deliverReqCh chan *stateReq 127 ) 128 if len(finished) > 0 { 129 deliverReq = finished[0] 130 deliverReqCh = s.deliver 131 } 132 133 select { 134 // The stateSync lifecycle: 135 case next := <-d.stateSyncStart: 136 d.spindownStateSync(active, finished, timeout, peerDrop) 137 return next 138 139 case <-s.done: 140 d.spindownStateSync(active, finished, timeout, peerDrop) 141 return nil 142 143 // Send the next finished request to the current sync: 144 case deliverReqCh <- deliverReq: 145 // Shift out the first request, but also set the emptied slot to nil for GC 146 copy(finished, finished[1:]) 147 finished[len(finished)-1] = nil 148 finished = finished[:len(finished)-1] 149 150 // Handle incoming state packs: 151 case pack := <-d.stateCh: 152 // Discard any data not requested (or previously timed out) 153 req := active[pack.PeerId()] 154 if req == nil { 155 log.Debug("Unrequested node data", "peer", pack.PeerId(), "len", pack.Items()) 156 continue 157 } 158 // Finalize the request and queue up for processing 159 req.timer.Stop() 160 req.response = pack.(*statePack).states 161 req.delivered = time.Now() 162 163 finished = append(finished, req) 164 delete(active, pack.PeerId()) 165 166 // Handle dropped peer connections: 167 case p := <-peerDrop: 168 // Skip if no request is currently pending 169 req := active[p.id] 170 if req == nil { 171 continue 172 } 173 // Finalize the request and queue up for processing 174 req.timer.Stop() 175 req.dropped = true 176 req.delivered = time.Now() 177 178 finished = append(finished, req) 179 delete(active, p.id) 180 181 // Handle timed-out requests: 182 case req := <-timeout: 183 // If the peer is already requesting something else, ignore the stale timeout. 184 // This can happen when the timeout and the delivery happens simultaneously, 185 // causing both pathways to trigger. 186 if active[req.peer.id] != req { 187 continue 188 } 189 req.delivered = time.Now() 190 // Move the timed out data back into the download queue 191 finished = append(finished, req) 192 delete(active, req.peer.id) 193 194 // Track outgoing state requests: 195 case req := <-d.trackStateReq: 196 // If an active request already exists for this peer, we have a problem. In 197 // theory the trie node schedule must never assign two requests to the same 198 // peer. In practice however, a peer might receive a request, disconnect and 199 // immediately reconnect before the previous times out. In this case the first 200 // request is never honored, alas we must not silently overwrite it, as that 201 // causes valid requests to go missing and sync to get stuck. 202 if old := active[req.peer.id]; old != nil { 203 log.Warn("Busy peer assigned new state fetch", "peer", old.peer.id) 204 // Move the previous request to the finished set 205 old.timer.Stop() 206 old.dropped = true 207 old.delivered = time.Now() 208 finished = append(finished, old) 209 } 210 // Start a timer to notify the sync loop if the peer stalled. 211 req.timer = time.AfterFunc(req.timeout, func() { 212 timeout <- req 213 }) 214 active[req.peer.id] = req 215 } 216 } 217 } 218 219 // spindownStateSync 'drains' the outstanding requests; some will be delivered and other 220 // will time out. This is to ensure that when the next stateSync starts working, all peers 221 // are marked as idle and de facto _are_ idle. 222 func (d *Downloader) spindownStateSync(active map[string]*stateReq, finished []*stateReq, timeout chan *stateReq, peerDrop chan *peerConnection) { 223 log.Trace("State sync spinning down", "active", len(active), "finished", len(finished)) 224 for len(active) > 0 { 225 var ( 226 req *stateReq 227 reason string 228 ) 229 select { 230 // Handle (drop) incoming state packs: 231 case pack := <-d.stateCh: 232 req = active[pack.PeerId()] 233 reason = "delivered" 234 // Handle dropped peer connections: 235 case p := <-peerDrop: 236 req = active[p.id] 237 reason = "peerdrop" 238 // Handle timed-out requests: 239 case req = <-timeout: 240 reason = "timeout" 241 } 242 if req == nil { 243 continue 244 } 245 req.peer.log.Trace("State peer marked idle (spindown)", "req.items", int(req.nItems), "reason", reason) 246 req.timer.Stop() 247 delete(active, req.peer.id) 248 req.peer.SetNodeDataIdle(int(req.nItems), time.Now()) 249 } 250 // The 'finished' set contains deliveries that we were going to pass to processing. 251 // Those are now moot, but we still need to set those peers as idle, which would 252 // otherwise have been done after processing 253 for _, req := range finished { 254 req.peer.SetNodeDataIdle(int(req.nItems), time.Now()) 255 } 256 } 257 258 // stateSync schedules requests for downloading a particular state trie defined 259 // by a given state root. 260 type stateSync struct { 261 d *Downloader // Downloader instance to access and manage current peerset 262 263 root common.Hash // State root currently being synced 264 sched *trie.Sync // State trie sync scheduler defining the tasks 265 keccak crypto.KeccakState // Keccak256 hasher to verify deliveries with 266 267 trieTasks map[common.Hash]*trieTask // Set of trie node tasks currently queued for retrieval 268 codeTasks map[common.Hash]*codeTask // Set of byte code tasks currently queued for retrieval 269 270 numUncommitted int 271 bytesUncommitted int 272 273 started chan struct{} // Started is signalled once the sync loop starts 274 275 deliver chan *stateReq // Delivery channel multiplexing peer responses 276 cancel chan struct{} // Channel to signal a termination request 277 cancelOnce sync.Once // Ensures cancel only ever gets called once 278 done chan struct{} // Channel to signal termination completion 279 err error // Any error hit during sync (set before completion) 280 } 281 282 // trieTask represents a single trie node download task, containing a set of 283 // peers already attempted retrieval from to detect stalled syncs and abort. 284 type trieTask struct { 285 path [][]byte 286 attempts map[string]struct{} 287 } 288 289 // codeTask represents a single byte code download task, containing a set of 290 // peers already attempted retrieval from to detect stalled syncs and abort. 291 type codeTask struct { 292 attempts map[string]struct{} 293 } 294 295 // newStateSync creates a new state trie download scheduler. This method does not 296 // yet start the sync. The user needs to call run to initiate. 297 func newStateSync(d *Downloader, root common.Hash) *stateSync { 298 return &stateSync{ 299 d: d, 300 root: root, 301 sched: state.NewStateSync(root, d.stateDB, d.stateBloom, nil), 302 keccak: sha3.NewLegacyKeccak256().(crypto.KeccakState), 303 trieTasks: make(map[common.Hash]*trieTask), 304 codeTasks: make(map[common.Hash]*codeTask), 305 deliver: make(chan *stateReq), 306 cancel: make(chan struct{}), 307 done: make(chan struct{}), 308 started: make(chan struct{}), 309 } 310 } 311 312 // run starts the task assignment and response processing loop, blocking until 313 // it finishes, and finally notifying any goroutines waiting for the loop to 314 // finish. 315 func (s *stateSync) run() { 316 close(s.started) 317 if s.d.snapSync { 318 s.err = s.d.SnapSyncer.Sync(s.root, s.cancel) 319 } else { 320 s.err = s.loop() 321 } 322 close(s.done) 323 } 324 325 // Wait blocks until the sync is done or canceled. 326 func (s *stateSync) Wait() error { 327 <-s.done 328 return s.err 329 } 330 331 // Cancel cancels the sync and waits until it has shut down. 332 func (s *stateSync) Cancel() error { 333 s.cancelOnce.Do(func() { 334 close(s.cancel) 335 }) 336 return s.Wait() 337 } 338 339 // loop is the main event loop of a state trie sync. It it responsible for the 340 // assignment of new tasks to peers (including sending it to them) as well as 341 // for the processing of inbound data. Note, that the loop does not directly 342 // receive data from peers, rather those are buffered up in the downloader and 343 // pushed here async. The reason is to decouple processing from data receipt 344 // and timeouts. 345 func (s *stateSync) loop() (err error) { 346 // Listen for new peer events to assign tasks to them 347 newPeer := make(chan *peerConnection, 1024) 348 peerSub := s.d.peers.SubscribeNewPeers(newPeer) 349 defer peerSub.Unsubscribe() 350 defer func() { 351 cerr := s.commit(true) 352 if err == nil { 353 err = cerr 354 } 355 }() 356 357 // Keep assigning new tasks until the sync completes or aborts 358 for s.sched.Pending() > 0 { 359 if err = s.commit(false); err != nil { 360 return err 361 } 362 s.assignTasks() 363 // Tasks assigned, wait for something to happen 364 select { 365 case <-newPeer: 366 // New peer arrived, try to assign it download tasks 367 368 case <-s.cancel: 369 return errCancelStateFetch 370 371 case <-s.d.cancelCh: 372 return errCanceled 373 374 case req := <-s.deliver: 375 // Response, disconnect or timeout triggered, drop the peer if stalling 376 log.Trace("Received node data response", "peer", req.peer.id, "count", len(req.response), "dropped", req.dropped, "timeout", !req.dropped && req.timedOut()) 377 if req.nItems <= 2 && !req.dropped && req.timedOut() { 378 // 2 items are the minimum requested, if even that times out, we've no use of 379 // this peer at the moment. 380 log.Warn("Stalling state sync, dropping peer", "peer", req.peer.id) 381 if s.d.dropPeer == nil { 382 // The dropPeer method is nil when `--copydb` is used for a local copy. 383 // Timeouts can occur if e.g. compaction hits at the wrong time, and can be ignored 384 req.peer.log.Warn("Downloader wants to drop peer, but peerdrop-function is not set", "peer", req.peer.id) 385 } else { 386 s.d.dropPeer(req.peer.id) 387 388 // If this peer was the master peer, abort sync immediately 389 s.d.cancelLock.RLock() 390 master := req.peer.id == s.d.cancelPeer 391 s.d.cancelLock.RUnlock() 392 393 if master { 394 s.d.cancel() 395 return errTimeout 396 } 397 } 398 } 399 // Process all the received blobs and check for stale delivery 400 delivered, err := s.process(req) 401 req.peer.SetNodeDataIdle(delivered, req.delivered) 402 if err != nil { 403 log.Warn("Node data write error", "err", err) 404 return err 405 } 406 } 407 } 408 return nil 409 } 410 411 func (s *stateSync) commit(force bool) error { 412 if !force && s.bytesUncommitted < ethdb.IdealBatchSize { 413 return nil 414 } 415 start := time.Now() 416 b := s.d.stateDB.NewBatch() 417 if err := s.sched.Commit(b); err != nil { 418 return err 419 } 420 if err := b.Write(); err != nil { 421 return fmt.Errorf("DB write error: %v", err) 422 } 423 s.updateStats(s.numUncommitted, 0, 0, time.Since(start)) 424 s.numUncommitted = 0 425 s.bytesUncommitted = 0 426 return nil 427 } 428 429 // assignTasks attempts to assign new tasks to all idle peers, either from the 430 // batch currently being retried, or fetching new data from the trie sync itself. 431 func (s *stateSync) assignTasks() { 432 // Iterate over all idle peers and try to assign them state fetches 433 peers, _ := s.d.peers.NodeDataIdlePeers() 434 for _, p := range peers { 435 // Assign a batch of fetches proportional to the estimated latency/bandwidth 436 cap := p.NodeDataCapacity(s.d.requestRTT()) 437 req := &stateReq{peer: p, timeout: s.d.requestTTL()} 438 439 nodes, _, codes := s.fillTasks(cap, req) 440 441 // If the peer was assigned tasks to fetch, send the network request 442 if len(nodes)+len(codes) > 0 { 443 req.peer.log.Trace("Requesting batch of state data", "nodes", len(nodes), "codes", len(codes), "root", s.root) 444 select { 445 case s.d.trackStateReq <- req: 446 req.peer.FetchNodeData(append(nodes, codes...)) // Unified retrieval under eth/6x 447 case <-s.cancel: 448 case <-s.d.cancelCh: 449 } 450 } 451 } 452 } 453 454 // fillTasks fills the given request object with a maximum of n state download 455 // tasks to send to the remote peer. 456 func (s *stateSync) fillTasks(n int, req *stateReq) (nodes []common.Hash, paths []trie.SyncPath, codes []common.Hash) { 457 // Refill available tasks from the scheduler. 458 if fill := n - (len(s.trieTasks) + len(s.codeTasks)); fill > 0 { 459 nodes, paths, codes := s.sched.Missing(fill) 460 for i, hash := range nodes { 461 s.trieTasks[hash] = &trieTask{ 462 path: paths[i], 463 attempts: make(map[string]struct{}), 464 } 465 } 466 for _, hash := range codes { 467 s.codeTasks[hash] = &codeTask{ 468 attempts: make(map[string]struct{}), 469 } 470 } 471 } 472 // Find tasks that haven't been tried with the request's peer. Prefer code 473 // over trie nodes as those can be written to disk and forgotten about. 474 nodes = make([]common.Hash, 0, n) 475 paths = make([]trie.SyncPath, 0, n) 476 codes = make([]common.Hash, 0, n) 477 478 req.trieTasks = make(map[common.Hash]*trieTask, n) 479 req.codeTasks = make(map[common.Hash]*codeTask, n) 480 481 for hash, t := range s.codeTasks { 482 // Stop when we've gathered enough requests 483 if len(nodes)+len(codes) == n { 484 break 485 } 486 // Skip any requests we've already tried from this peer 487 if _, ok := t.attempts[req.peer.id]; ok { 488 continue 489 } 490 // Assign the request to this peer 491 t.attempts[req.peer.id] = struct{}{} 492 codes = append(codes, hash) 493 req.codeTasks[hash] = t 494 delete(s.codeTasks, hash) 495 } 496 for hash, t := range s.trieTasks { 497 // Stop when we've gathered enough requests 498 if len(nodes)+len(codes) == n { 499 break 500 } 501 // Skip any requests we've already tried from this peer 502 if _, ok := t.attempts[req.peer.id]; ok { 503 continue 504 } 505 // Assign the request to this peer 506 t.attempts[req.peer.id] = struct{}{} 507 508 nodes = append(nodes, hash) 509 paths = append(paths, t.path) 510 511 req.trieTasks[hash] = t 512 delete(s.trieTasks, hash) 513 } 514 req.nItems = uint16(len(nodes) + len(codes)) 515 return nodes, paths, codes 516 } 517 518 // process iterates over a batch of delivered state data, injecting each item 519 // into a running state sync, re-queuing any items that were requested but not 520 // delivered. Returns whether the peer actually managed to deliver anything of 521 // value, and any error that occurred. 522 func (s *stateSync) process(req *stateReq) (int, error) { 523 // Collect processing stats and update progress if valid data was received 524 duplicate, unexpected, successful := 0, 0, 0 525 526 defer func(start time.Time) { 527 if duplicate > 0 || unexpected > 0 { 528 s.updateStats(0, duplicate, unexpected, time.Since(start)) 529 } 530 }(time.Now()) 531 532 // Iterate over all the delivered data and inject one-by-one into the trie 533 for _, blob := range req.response { 534 hash, err := s.processNodeData(blob) 535 switch err { 536 case nil: 537 s.numUncommitted++ 538 s.bytesUncommitted += len(blob) 539 successful++ 540 case trie.ErrNotRequested: 541 unexpected++ 542 case trie.ErrAlreadyProcessed: 543 duplicate++ 544 default: 545 return successful, fmt.Errorf("invalid state node %s: %v", hash.TerminalString(), err) 546 } 547 // Delete from both queues (one delivery is enough for the syncer) 548 delete(req.trieTasks, hash) 549 delete(req.codeTasks, hash) 550 } 551 // Put unfulfilled tasks back into the retry queue 552 npeers := s.d.peers.Len() 553 for hash, task := range req.trieTasks { 554 // If the node did deliver something, missing items may be due to a protocol 555 // limit or a previous timeout + delayed delivery. Both cases should permit 556 // the node to retry the missing items (to avoid single-peer stalls). 557 if len(req.response) > 0 || req.timedOut() { 558 delete(task.attempts, req.peer.id) 559 } 560 // If we've requested the node too many times already, it may be a malicious 561 // sync where nobody has the right data. Abort. 562 if len(task.attempts) >= npeers { 563 return successful, fmt.Errorf("trie node %s failed with all peers (%d tries, %d peers)", hash.TerminalString(), len(task.attempts), npeers) 564 } 565 // Missing item, place into the retry queue. 566 s.trieTasks[hash] = task 567 } 568 for hash, task := range req.codeTasks { 569 // If the node did deliver something, missing items may be due to a protocol 570 // limit or a previous timeout + delayed delivery. Both cases should permit 571 // the node to retry the missing items (to avoid single-peer stalls). 572 if len(req.response) > 0 || req.timedOut() { 573 delete(task.attempts, req.peer.id) 574 } 575 // If we've requested the node too many times already, it may be a malicious 576 // sync where nobody has the right data. Abort. 577 if len(task.attempts) >= npeers { 578 return successful, fmt.Errorf("byte code %s failed with all peers (%d tries, %d peers)", hash.TerminalString(), len(task.attempts), npeers) 579 } 580 // Missing item, place into the retry queue. 581 s.codeTasks[hash] = task 582 } 583 return successful, nil 584 } 585 586 // processNodeData tries to inject a trie node data blob delivered from a remote 587 // peer into the state trie, returning whether anything useful was written or any 588 // error occurred. 589 func (s *stateSync) processNodeData(blob []byte) (common.Hash, error) { 590 res := trie.SyncResult{Data: blob} 591 s.keccak.Reset() 592 s.keccak.Write(blob) 593 s.keccak.Read(res.Hash[:]) 594 err := s.sched.Process(res) 595 return res.Hash, err 596 } 597 598 // updateStats bumps the various state sync progress counters and displays a log 599 // message for the user to see. 600 func (s *stateSync) updateStats(written, duplicate, unexpected int, duration time.Duration) { 601 s.d.syncStatsLock.Lock() 602 defer s.d.syncStatsLock.Unlock() 603 604 s.d.syncStatsState.pending = uint64(s.sched.Pending()) 605 s.d.syncStatsState.processed += uint64(written) 606 s.d.syncStatsState.duplicate += uint64(duplicate) 607 s.d.syncStatsState.unexpected += uint64(unexpected) 608 609 if written > 0 || duplicate > 0 || unexpected > 0 { 610 log.Info("Imported new state entries", "count", written, "elapsed", common.PrettyDuration(duration), "processed", s.d.syncStatsState.processed, "pending", s.d.syncStatsState.pending, "trieretry", len(s.trieTasks), "coderetry", len(s.codeTasks), "duplicate", s.d.syncStatsState.duplicate, "unexpected", s.d.syncStatsState.unexpected) 611 } 612 if written > 0 { 613 rawdb.WriteFastTrieProgress(s.d.stateDB, s.d.syncStatsState.processed) 614 } 615 }