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