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