github.com/lzl124631x/go-ethereum@v1.8.12-0.20180615081455-574378edb50c/eth/handler.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 package eth 18 19 import ( 20 "encoding/json" 21 "errors" 22 "fmt" 23 "math" 24 "math/big" 25 "sync" 26 "sync/atomic" 27 "time" 28 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/consensus" 31 "github.com/ethereum/go-ethereum/consensus/misc" 32 "github.com/ethereum/go-ethereum/core" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/eth/downloader" 35 "github.com/ethereum/go-ethereum/eth/fetcher" 36 "github.com/ethereum/go-ethereum/ethdb" 37 "github.com/ethereum/go-ethereum/event" 38 "github.com/ethereum/go-ethereum/log" 39 "github.com/ethereum/go-ethereum/p2p" 40 "github.com/ethereum/go-ethereum/p2p/discover" 41 "github.com/ethereum/go-ethereum/params" 42 "github.com/ethereum/go-ethereum/rlp" 43 ) 44 45 const ( 46 softResponseLimit = 2 * 1024 * 1024 // Target maximum size of returned blocks, headers or node data. 47 estHeaderRlpSize = 500 // Approximate size of an RLP encoded block header 48 49 // txChanSize is the size of channel listening to NewTxsEvent. 50 // The number is referenced from the size of tx pool. 51 txChanSize = 4096 52 ) 53 54 var ( 55 daoChallengeTimeout = 15 * time.Second // Time allowance for a node to reply to the DAO handshake challenge 56 ) 57 58 // errIncompatibleConfig is returned if the requested protocols and configs are 59 // not compatible (low protocol version restrictions and high requirements). 60 var errIncompatibleConfig = errors.New("incompatible configuration") 61 62 func errResp(code errCode, format string, v ...interface{}) error { 63 return fmt.Errorf("%v - %v", code, fmt.Sprintf(format, v...)) 64 } 65 66 type ProtocolManager struct { 67 networkID uint64 68 69 fastSync uint32 // Flag whether fast sync is enabled (gets disabled if we already have blocks) 70 acceptTxs uint32 // Flag whether we're considered synchronised (enables transaction processing) 71 72 txpool txPool 73 blockchain *core.BlockChain 74 chainconfig *params.ChainConfig 75 maxPeers int 76 77 downloader *downloader.Downloader 78 fetcher *fetcher.Fetcher 79 peers *peerSet 80 81 SubProtocols []p2p.Protocol 82 83 eventMux *event.TypeMux 84 txsCh chan core.NewTxsEvent 85 txsSub event.Subscription 86 minedBlockSub *event.TypeMuxSubscription 87 88 // channels for fetcher, syncer, txsyncLoop 89 newPeerCh chan *peer 90 txsyncCh chan *txsync 91 quitSync chan struct{} 92 noMorePeers chan struct{} 93 94 // wait group is used for graceful shutdowns during downloading 95 // and processing 96 wg sync.WaitGroup 97 } 98 99 // NewProtocolManager returns a new Ethereum sub protocol manager. The Ethereum sub protocol manages peers capable 100 // with the Ethereum network. 101 func NewProtocolManager(config *params.ChainConfig, mode downloader.SyncMode, networkID uint64, mux *event.TypeMux, txpool txPool, engine consensus.Engine, blockchain *core.BlockChain, chaindb ethdb.Database) (*ProtocolManager, error) { 102 // Create the protocol manager with the base fields 103 manager := &ProtocolManager{ 104 networkID: networkID, 105 eventMux: mux, 106 txpool: txpool, 107 blockchain: blockchain, 108 chainconfig: config, 109 peers: newPeerSet(), 110 newPeerCh: make(chan *peer), 111 noMorePeers: make(chan struct{}), 112 txsyncCh: make(chan *txsync), 113 quitSync: make(chan struct{}), 114 } 115 // Figure out whether to allow fast sync or not 116 if mode == downloader.FastSync && blockchain.CurrentBlock().NumberU64() > 0 { 117 log.Warn("Blockchain not empty, fast sync disabled") 118 mode = downloader.FullSync 119 } 120 if mode == downloader.FastSync { 121 manager.fastSync = uint32(1) 122 } 123 // Initiate a sub-protocol for every implemented version we can handle 124 manager.SubProtocols = make([]p2p.Protocol, 0, len(ProtocolVersions)) 125 for i, version := range ProtocolVersions { 126 // Skip protocol version if incompatible with the mode of operation 127 if mode == downloader.FastSync && version < eth63 { 128 continue 129 } 130 // Compatible; initialise the sub-protocol 131 version := version // Closure for the run 132 manager.SubProtocols = append(manager.SubProtocols, p2p.Protocol{ 133 Name: ProtocolName, 134 Version: version, 135 Length: ProtocolLengths[i], 136 Run: func(p *p2p.Peer, rw p2p.MsgReadWriter) error { 137 peer := manager.newPeer(int(version), p, rw) 138 select { 139 case manager.newPeerCh <- peer: 140 manager.wg.Add(1) 141 defer manager.wg.Done() 142 return manager.handle(peer) 143 case <-manager.quitSync: 144 return p2p.DiscQuitting 145 } 146 }, 147 NodeInfo: func() interface{} { 148 return manager.NodeInfo() 149 }, 150 PeerInfo: func(id discover.NodeID) interface{} { 151 if p := manager.peers.Peer(fmt.Sprintf("%x", id[:8])); p != nil { 152 return p.Info() 153 } 154 return nil 155 }, 156 }) 157 } 158 if len(manager.SubProtocols) == 0 { 159 return nil, errIncompatibleConfig 160 } 161 // Construct the different synchronisation mechanisms 162 manager.downloader = downloader.New(mode, chaindb, manager.eventMux, blockchain, nil, manager.removePeer) 163 164 validator := func(header *types.Header) error { 165 return engine.VerifyHeader(blockchain, header, true) 166 } 167 heighter := func() uint64 { 168 return blockchain.CurrentBlock().NumberU64() 169 } 170 inserter := func(blocks types.Blocks) (int, error) { 171 // If fast sync is running, deny importing weird blocks 172 if atomic.LoadUint32(&manager.fastSync) == 1 { 173 log.Warn("Discarded bad propagated block", "number", blocks[0].Number(), "hash", blocks[0].Hash()) 174 return 0, nil 175 } 176 atomic.StoreUint32(&manager.acceptTxs, 1) // Mark initial sync done on any fetcher import 177 return manager.blockchain.InsertChain(blocks) 178 } 179 manager.fetcher = fetcher.New(blockchain.GetBlockByHash, validator, manager.BroadcastBlock, heighter, inserter, manager.removePeer) 180 181 return manager, nil 182 } 183 184 func (pm *ProtocolManager) removePeer(id string) { 185 // Short circuit if the peer was already removed 186 peer := pm.peers.Peer(id) 187 if peer == nil { 188 return 189 } 190 log.Debug("Removing Ethereum peer", "peer", id) 191 192 // Unregister the peer from the downloader and Ethereum peer set 193 pm.downloader.UnregisterPeer(id) 194 if err := pm.peers.Unregister(id); err != nil { 195 log.Error("Peer removal failed", "peer", id, "err", err) 196 } 197 // Hard disconnect at the networking layer 198 if peer != nil { 199 peer.Peer.Disconnect(p2p.DiscUselessPeer) 200 } 201 } 202 203 func (pm *ProtocolManager) Start(maxPeers int) { 204 pm.maxPeers = maxPeers 205 206 // broadcast transactions 207 pm.txsCh = make(chan core.NewTxsEvent, txChanSize) 208 pm.txsSub = pm.txpool.SubscribeNewTxsEvent(pm.txsCh) 209 go pm.txBroadcastLoop() 210 211 // broadcast mined blocks 212 pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{}) 213 go pm.minedBroadcastLoop() 214 215 // start sync handlers 216 go pm.syncer() 217 go pm.txsyncLoop() 218 } 219 220 func (pm *ProtocolManager) Stop() { 221 log.Info("Stopping Ethereum protocol") 222 223 pm.txsSub.Unsubscribe() // quits txBroadcastLoop 224 pm.minedBlockSub.Unsubscribe() // quits blockBroadcastLoop 225 226 // Quit the sync loop. 227 // After this send has completed, no new peers will be accepted. 228 pm.noMorePeers <- struct{}{} 229 230 // Quit fetcher, txsyncLoop. 231 close(pm.quitSync) 232 233 // Disconnect existing sessions. 234 // This also closes the gate for any new registrations on the peer set. 235 // sessions which are already established but not added to pm.peers yet 236 // will exit when they try to register. 237 pm.peers.Close() 238 239 // Wait for all peer handler goroutines and the loops to come down. 240 pm.wg.Wait() 241 242 log.Info("Ethereum protocol stopped") 243 } 244 245 func (pm *ProtocolManager) newPeer(pv int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer { 246 return newPeer(pv, p, newMeteredMsgWriter(rw)) 247 } 248 249 // handle is the callback invoked to manage the life cycle of an eth peer. When 250 // this function terminates, the peer is disconnected. 251 func (pm *ProtocolManager) handle(p *peer) error { 252 // Ignore maxPeers if this is a trusted peer 253 if pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted { 254 return p2p.DiscTooManyPeers 255 } 256 p.Log().Debug("Ethereum peer connected", "name", p.Name()) 257 258 // Execute the Ethereum handshake 259 var ( 260 genesis = pm.blockchain.Genesis() 261 head = pm.blockchain.CurrentHeader() 262 hash = head.Hash() 263 number = head.Number.Uint64() 264 td = pm.blockchain.GetTd(hash, number) 265 ) 266 if err := p.Handshake(pm.networkID, td, hash, genesis.Hash()); err != nil { 267 p.Log().Debug("Ethereum handshake failed", "err", err) 268 return err 269 } 270 if rw, ok := p.rw.(*meteredMsgReadWriter); ok { 271 rw.Init(p.version) 272 } 273 // Register the peer locally 274 if err := pm.peers.Register(p); err != nil { 275 p.Log().Error("Ethereum peer registration failed", "err", err) 276 return err 277 } 278 defer pm.removePeer(p.id) 279 280 // Register the peer in the downloader. If the downloader considers it banned, we disconnect 281 if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil { 282 return err 283 } 284 // Propagate existing transactions. new transactions appearing 285 // after this will be sent via broadcasts. 286 pm.syncTransactions(p) 287 288 // If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork 289 if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil { 290 // Request the peer's DAO fork header for extra-data validation 291 if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil { 292 return err 293 } 294 // Start a timer to disconnect if the peer doesn't reply in time 295 p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() { 296 p.Log().Debug("Timed out DAO fork-check, dropping") 297 pm.removePeer(p.id) 298 }) 299 // Make sure it's cleaned up if the peer dies off 300 defer func() { 301 if p.forkDrop != nil { 302 p.forkDrop.Stop() 303 p.forkDrop = nil 304 } 305 }() 306 } 307 // main loop. handle incoming messages. 308 for { 309 if err := pm.handleMsg(p); err != nil { 310 p.Log().Debug("Ethereum message handling failed", "err", err) 311 return err 312 } 313 } 314 } 315 316 // handleMsg is invoked whenever an inbound message is received from a remote 317 // peer. The remote connection is torn down upon returning any error. 318 func (pm *ProtocolManager) handleMsg(p *peer) error { 319 // Read the next message from the remote peer, and ensure it's fully consumed 320 msg, err := p.rw.ReadMsg() 321 if err != nil { 322 return err 323 } 324 if msg.Size > ProtocolMaxMsgSize { 325 return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize) 326 } 327 defer msg.Discard() 328 329 // Handle the message depending on its contents 330 switch { 331 case msg.Code == StatusMsg: 332 // Status messages should never arrive after the handshake 333 return errResp(ErrExtraStatusMsg, "uncontrolled status message") 334 335 // Block header query, collect the requested headers and reply 336 case msg.Code == GetBlockHeadersMsg: 337 // Decode the complex header query 338 var query getBlockHeadersData 339 if err := msg.Decode(&query); err != nil { 340 return errResp(ErrDecode, "%v: %v", msg, err) 341 } 342 hashMode := query.Origin.Hash != (common.Hash{}) 343 first := true 344 maxNonCanonical := uint64(100) 345 346 // Gather headers until the fetch or network limits is reached 347 var ( 348 bytes common.StorageSize 349 headers []*types.Header 350 unknown bool 351 ) 352 for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch { 353 // Retrieve the next header satisfying the query 354 var origin *types.Header 355 if hashMode { 356 if first { 357 first = false 358 origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash) 359 if origin != nil { 360 query.Origin.Number = origin.Number.Uint64() 361 } 362 } else { 363 origin = pm.blockchain.GetHeader(query.Origin.Hash, query.Origin.Number) 364 } 365 } else { 366 origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number) 367 } 368 if origin == nil { 369 break 370 } 371 headers = append(headers, origin) 372 bytes += estHeaderRlpSize 373 374 // Advance to the next header of the query 375 switch { 376 case hashMode && query.Reverse: 377 // Hash based traversal towards the genesis block 378 ancestor := query.Skip + 1 379 if ancestor == 0 { 380 unknown = true 381 } else { 382 query.Origin.Hash, query.Origin.Number = pm.blockchain.GetAncestor(query.Origin.Hash, query.Origin.Number, ancestor, &maxNonCanonical) 383 unknown = (query.Origin.Hash == common.Hash{}) 384 } 385 case hashMode && !query.Reverse: 386 // Hash based traversal towards the leaf block 387 var ( 388 current = origin.Number.Uint64() 389 next = current + query.Skip + 1 390 ) 391 if next <= current { 392 infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ") 393 p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos) 394 unknown = true 395 } else { 396 if header := pm.blockchain.GetHeaderByNumber(next); header != nil { 397 nextHash := header.Hash() 398 expOldHash, _ := pm.blockchain.GetAncestor(nextHash, next, query.Skip+1, &maxNonCanonical) 399 if expOldHash == query.Origin.Hash { 400 query.Origin.Hash, query.Origin.Number = nextHash, next 401 } else { 402 unknown = true 403 } 404 } else { 405 unknown = true 406 } 407 } 408 case query.Reverse: 409 // Number based traversal towards the genesis block 410 if query.Origin.Number >= query.Skip+1 { 411 query.Origin.Number -= query.Skip + 1 412 } else { 413 unknown = true 414 } 415 416 case !query.Reverse: 417 // Number based traversal towards the leaf block 418 query.Origin.Number += query.Skip + 1 419 } 420 } 421 return p.SendBlockHeaders(headers) 422 423 case msg.Code == BlockHeadersMsg: 424 // A batch of headers arrived to one of our previous requests 425 var headers []*types.Header 426 if err := msg.Decode(&headers); err != nil { 427 return errResp(ErrDecode, "msg %v: %v", msg, err) 428 } 429 // If no headers were received, but we're expending a DAO fork check, maybe it's that 430 if len(headers) == 0 && p.forkDrop != nil { 431 // Possibly an empty reply to the fork header checks, sanity check TDs 432 verifyDAO := true 433 434 // If we already have a DAO header, we can check the peer's TD against it. If 435 // the peer's ahead of this, it too must have a reply to the DAO check 436 if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil { 437 if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 { 438 verifyDAO = false 439 } 440 } 441 // If we're seemingly on the same chain, disable the drop timer 442 if verifyDAO { 443 p.Log().Debug("Seems to be on the same side of the DAO fork") 444 p.forkDrop.Stop() 445 p.forkDrop = nil 446 return nil 447 } 448 } 449 // Filter out any explicitly requested headers, deliver the rest to the downloader 450 filter := len(headers) == 1 451 if filter { 452 // If it's a potential DAO fork check, validate against the rules 453 if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 { 454 // Disable the fork drop timer 455 p.forkDrop.Stop() 456 p.forkDrop = nil 457 458 // Validate the header and either drop the peer or continue 459 if err := misc.VerifyDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil { 460 p.Log().Debug("Verified to be on the other side of the DAO fork, dropping") 461 return err 462 } 463 p.Log().Debug("Verified to be on the same side of the DAO fork") 464 return nil 465 } 466 // Irrelevant of the fork checks, send the header to the fetcher just in case 467 headers = pm.fetcher.FilterHeaders(p.id, headers, time.Now()) 468 } 469 if len(headers) > 0 || !filter { 470 err := pm.downloader.DeliverHeaders(p.id, headers) 471 if err != nil { 472 log.Debug("Failed to deliver headers", "err", err) 473 } 474 } 475 476 case msg.Code == GetBlockBodiesMsg: 477 // Decode the retrieval message 478 msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size)) 479 if _, err := msgStream.List(); err != nil { 480 return err 481 } 482 // Gather blocks until the fetch or network limits is reached 483 var ( 484 hash common.Hash 485 bytes int 486 bodies []rlp.RawValue 487 ) 488 for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch { 489 // Retrieve the hash of the next block 490 if err := msgStream.Decode(&hash); err == rlp.EOL { 491 break 492 } else if err != nil { 493 return errResp(ErrDecode, "msg %v: %v", msg, err) 494 } 495 // Retrieve the requested block body, stopping if enough was found 496 if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 { 497 bodies = append(bodies, data) 498 bytes += len(data) 499 } 500 } 501 return p.SendBlockBodiesRLP(bodies) 502 503 case msg.Code == BlockBodiesMsg: 504 // A batch of block bodies arrived to one of our previous requests 505 var request blockBodiesData 506 if err := msg.Decode(&request); err != nil { 507 return errResp(ErrDecode, "msg %v: %v", msg, err) 508 } 509 // Deliver them all to the downloader for queuing 510 transactions := make([][]*types.Transaction, len(request)) 511 uncles := make([][]*types.Header, len(request)) 512 513 for i, body := range request { 514 transactions[i] = body.Transactions 515 uncles[i] = body.Uncles 516 } 517 // Filter out any explicitly requested bodies, deliver the rest to the downloader 518 filter := len(transactions) > 0 || len(uncles) > 0 519 if filter { 520 transactions, uncles = pm.fetcher.FilterBodies(p.id, transactions, uncles, time.Now()) 521 } 522 if len(transactions) > 0 || len(uncles) > 0 || !filter { 523 err := pm.downloader.DeliverBodies(p.id, transactions, uncles) 524 if err != nil { 525 log.Debug("Failed to deliver bodies", "err", err) 526 } 527 } 528 529 case p.version >= eth63 && msg.Code == GetNodeDataMsg: 530 // Decode the retrieval message 531 msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size)) 532 if _, err := msgStream.List(); err != nil { 533 return err 534 } 535 // Gather state data until the fetch or network limits is reached 536 var ( 537 hash common.Hash 538 bytes int 539 data [][]byte 540 ) 541 for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch { 542 // Retrieve the hash of the next state entry 543 if err := msgStream.Decode(&hash); err == rlp.EOL { 544 break 545 } else if err != nil { 546 return errResp(ErrDecode, "msg %v: %v", msg, err) 547 } 548 // Retrieve the requested state entry, stopping if enough was found 549 if entry, err := pm.blockchain.TrieNode(hash); err == nil { 550 data = append(data, entry) 551 bytes += len(entry) 552 } 553 } 554 return p.SendNodeData(data) 555 556 case p.version >= eth63 && msg.Code == NodeDataMsg: 557 // A batch of node state data arrived to one of our previous requests 558 var data [][]byte 559 if err := msg.Decode(&data); err != nil { 560 return errResp(ErrDecode, "msg %v: %v", msg, err) 561 } 562 // Deliver all to the downloader 563 if err := pm.downloader.DeliverNodeData(p.id, data); err != nil { 564 log.Debug("Failed to deliver node state data", "err", err) 565 } 566 567 case p.version >= eth63 && msg.Code == GetReceiptsMsg: 568 // Decode the retrieval message 569 msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size)) 570 if _, err := msgStream.List(); err != nil { 571 return err 572 } 573 // Gather state data until the fetch or network limits is reached 574 var ( 575 hash common.Hash 576 bytes int 577 receipts []rlp.RawValue 578 ) 579 for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch { 580 // Retrieve the hash of the next block 581 if err := msgStream.Decode(&hash); err == rlp.EOL { 582 break 583 } else if err != nil { 584 return errResp(ErrDecode, "msg %v: %v", msg, err) 585 } 586 // Retrieve the requested block's receipts, skipping if unknown to us 587 results := pm.blockchain.GetReceiptsByHash(hash) 588 if results == nil { 589 if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash { 590 continue 591 } 592 } 593 // If known, encode and queue for response packet 594 if encoded, err := rlp.EncodeToBytes(results); err != nil { 595 log.Error("Failed to encode receipt", "err", err) 596 } else { 597 receipts = append(receipts, encoded) 598 bytes += len(encoded) 599 } 600 } 601 return p.SendReceiptsRLP(receipts) 602 603 case p.version >= eth63 && msg.Code == ReceiptsMsg: 604 // A batch of receipts arrived to one of our previous requests 605 var receipts [][]*types.Receipt 606 if err := msg.Decode(&receipts); err != nil { 607 return errResp(ErrDecode, "msg %v: %v", msg, err) 608 } 609 // Deliver all to the downloader 610 if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil { 611 log.Debug("Failed to deliver receipts", "err", err) 612 } 613 614 case msg.Code == NewBlockHashesMsg: 615 var announces newBlockHashesData 616 if err := msg.Decode(&announces); err != nil { 617 return errResp(ErrDecode, "%v: %v", msg, err) 618 } 619 // Mark the hashes as present at the remote node 620 for _, block := range announces { 621 p.MarkBlock(block.Hash) 622 } 623 // Schedule all the unknown hashes for retrieval 624 unknown := make(newBlockHashesData, 0, len(announces)) 625 for _, block := range announces { 626 if !pm.blockchain.HasBlock(block.Hash, block.Number) { 627 unknown = append(unknown, block) 628 } 629 } 630 for _, block := range unknown { 631 pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies) 632 } 633 634 case msg.Code == NewBlockMsg: 635 // Retrieve and decode the propagated block 636 var request newBlockData 637 if err := msg.Decode(&request); err != nil { 638 return errResp(ErrDecode, "%v: %v", msg, err) 639 } 640 request.Block.ReceivedAt = msg.ReceivedAt 641 request.Block.ReceivedFrom = p 642 643 // Mark the peer as owning the block and schedule it for import 644 p.MarkBlock(request.Block.Hash()) 645 pm.fetcher.Enqueue(p.id, request.Block) 646 647 // Assuming the block is importable by the peer, but possibly not yet done so, 648 // calculate the head hash and TD that the peer truly must have. 649 var ( 650 trueHead = request.Block.ParentHash() 651 trueTD = new(big.Int).Sub(request.TD, request.Block.Difficulty()) 652 ) 653 // Update the peers total difficulty if better than the previous 654 if _, td := p.Head(); trueTD.Cmp(td) > 0 { 655 p.SetHead(trueHead, trueTD) 656 657 // Schedule a sync if above ours. Note, this will not fire a sync for a gap of 658 // a singe block (as the true TD is below the propagated block), however this 659 // scenario should easily be covered by the fetcher. 660 currentBlock := pm.blockchain.CurrentBlock() 661 if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 { 662 go pm.synchronise(p) 663 } 664 } 665 666 case msg.Code == TxMsg: 667 // Transactions arrived, make sure we have a valid and fresh chain to handle them 668 if atomic.LoadUint32(&pm.acceptTxs) == 0 { 669 break 670 } 671 // Transactions can be processed, parse all of them and deliver to the pool 672 var txs []*types.Transaction 673 if err := msg.Decode(&txs); err != nil { 674 return errResp(ErrDecode, "msg %v: %v", msg, err) 675 } 676 for i, tx := range txs { 677 // Validate and mark the remote transaction 678 if tx == nil { 679 return errResp(ErrDecode, "transaction %d is nil", i) 680 } 681 p.MarkTransaction(tx.Hash()) 682 } 683 pm.txpool.AddRemotes(txs) 684 685 default: 686 return errResp(ErrInvalidMsgCode, "%v", msg.Code) 687 } 688 return nil 689 } 690 691 // BroadcastBlock will either propagate a block to a subset of it's peers, or 692 // will only announce it's availability (depending what's requested). 693 func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) { 694 hash := block.Hash() 695 peers := pm.peers.PeersWithoutBlock(hash) 696 697 // If propagation is requested, send to a subset of the peer 698 if propagate { 699 // Calculate the TD of the block (it's not imported yet, so block.Td is not valid) 700 var td *big.Int 701 if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil { 702 td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1)) 703 } else { 704 log.Error("Propagating dangling block", "number", block.Number(), "hash", hash) 705 return 706 } 707 // Send the block to a subset of our peers 708 transfer := peers[:int(math.Sqrt(float64(len(peers))))] 709 for _, peer := range transfer { 710 peer.AsyncSendNewBlock(block, td) 711 } 712 log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt))) 713 return 714 } 715 // Otherwise if the block is indeed in out own chain, announce it 716 if pm.blockchain.HasBlock(hash, block.NumberU64()) { 717 for _, peer := range peers { 718 peer.AsyncSendNewBlockHash(block) 719 } 720 log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt))) 721 } 722 } 723 724 // BroadcastTxs will propagate a batch of transactions to all peers which are not known to 725 // already have the given transaction. 726 func (pm *ProtocolManager) BroadcastTxs(txs types.Transactions) { 727 var txset = make(map[*peer]types.Transactions) 728 729 // Broadcast transactions to a batch of peers not knowing about it 730 for _, tx := range txs { 731 peers := pm.peers.PeersWithoutTx(tx.Hash()) 732 for _, peer := range peers { 733 txset[peer] = append(txset[peer], tx) 734 } 735 log.Trace("Broadcast transaction", "hash", tx.Hash(), "recipients", len(peers)) 736 } 737 // FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))] 738 for peer, txs := range txset { 739 peer.AsyncSendTransactions(txs) 740 } 741 } 742 743 // Mined broadcast loop 744 func (pm *ProtocolManager) minedBroadcastLoop() { 745 // automatically stops if unsubscribe 746 for obj := range pm.minedBlockSub.Chan() { 747 switch ev := obj.Data.(type) { 748 case core.NewMinedBlockEvent: 749 pm.BroadcastBlock(ev.Block, true) // First propagate block to peers 750 pm.BroadcastBlock(ev.Block, false) // Only then announce to the rest 751 } 752 } 753 } 754 755 func (pm *ProtocolManager) txBroadcastLoop() { 756 for { 757 select { 758 case event := <-pm.txsCh: 759 pm.BroadcastTxs(event.Txs) 760 761 // Err() channel will be closed when unsubscribing. 762 case <-pm.txsSub.Err(): 763 return 764 } 765 } 766 } 767 768 // NodeInfo represents a short summary of the Ethereum sub-protocol metadata 769 // known about the host peer. 770 type NodeInfo struct { 771 Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4) 772 Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain 773 Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block 774 Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules 775 Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block 776 } 777 778 // NodeInfo retrieves some protocol metadata about the running host node. 779 func (pm *ProtocolManager) NodeInfo() *NodeInfo { 780 currentBlock := pm.blockchain.CurrentBlock() 781 return &NodeInfo{ 782 Network: pm.networkID, 783 Difficulty: pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()), 784 Genesis: pm.blockchain.Genesis().Hash(), 785 Config: pm.blockchain.Config(), 786 Head: currentBlock.Hash(), 787 } 788 }