github.com/vantum/vantum@v0.0.0-20180815184342-fe37d5f7a990/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/vantum/vantum/common" 30 "github.com/vantum/vantum/consensus" 31 "github.com/vantum/vantum/consensus/misc" 32 "github.com/vantum/vantum/core" 33 "github.com/vantum/vantum/core/types" 34 "github.com/vantum/vantum/eth/downloader" 35 "github.com/vantum/vantum/eth/fetcher" 36 "github.com/vantum/vantum/ethdb" 37 "github.com/vantum/vantum/event" 38 "github.com/vantum/vantum/log" 39 "github.com/vantum/vantum/p2p" 40 "github.com/vantum/vantum/p2p/discover" 41 "github.com/vantum/vantum/params" 42 "github.com/vantum/vantum/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 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 txCh chan core.TxPreEvent 85 txSub 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.txCh = make(chan core.TxPreEvent, txChanSize) 208 pm.txSub = pm.txpool.SubscribeTxPreEvent(pm.txCh) 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.txSub.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 if pm.peers.Len() >= pm.maxPeers { 253 return p2p.DiscTooManyPeers 254 } 255 p.Log().Debug("Ethereum peer connected", "name", p.Name()) 256 257 // Execute the Ethereum handshake 258 var ( 259 genesis = pm.blockchain.Genesis() 260 head = pm.blockchain.CurrentHeader() 261 hash = head.Hash() 262 number = head.Number.Uint64() 263 td = pm.blockchain.GetTd(hash, number) 264 ) 265 if err := p.Handshake(pm.networkId, td, hash, genesis.Hash()); err != nil { 266 p.Log().Debug("Ethereum handshake failed", "err", err) 267 return err 268 } 269 if rw, ok := p.rw.(*meteredMsgReadWriter); ok { 270 rw.Init(p.version) 271 } 272 // Register the peer locally 273 if err := pm.peers.Register(p); err != nil { 274 p.Log().Error("Ethereum peer registration failed", "err", err) 275 return err 276 } 277 defer pm.removePeer(p.id) 278 279 // Register the peer in the downloader. If the downloader considers it banned, we disconnect 280 if err := pm.downloader.RegisterPeer(p.id, p.version, p); err != nil { 281 return err 282 } 283 // Propagate existing transactions. new transactions appearing 284 // after this will be sent via broadcasts. 285 pm.syncTransactions(p) 286 287 // If we're DAO hard-fork aware, validate any remote peer with regard to the hard-fork 288 if daoBlock := pm.chainconfig.DAOForkBlock; daoBlock != nil { 289 // Request the peer's DAO fork header for extra-data validation 290 if err := p.RequestHeadersByNumber(daoBlock.Uint64(), 1, 0, false); err != nil { 291 return err 292 } 293 // Start a timer to disconnect if the peer doesn't reply in time 294 p.forkDrop = time.AfterFunc(daoChallengeTimeout, func() { 295 p.Log().Debug("Timed out DAO fork-check, dropping") 296 pm.removePeer(p.id) 297 }) 298 // Make sure it's cleaned up if the peer dies off 299 defer func() { 300 if p.forkDrop != nil { 301 p.forkDrop.Stop() 302 p.forkDrop = nil 303 } 304 }() 305 } 306 // main loop. handle incoming messages. 307 for { 308 if err := pm.handleMsg(p); err != nil { 309 p.Log().Debug("Ethereum message handling failed", "err", err) 310 return err 311 } 312 } 313 } 314 315 // handleMsg is invoked whenever an inbound message is received from a remote 316 // peer. The remote connection is torn down upon returning any error. 317 func (pm *ProtocolManager) handleMsg(p *peer) error { 318 // Read the next message from the remote peer, and ensure it's fully consumed 319 msg, err := p.rw.ReadMsg() 320 if err != nil { 321 return err 322 } 323 if msg.Size > ProtocolMaxMsgSize { 324 return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize) 325 } 326 defer msg.Discard() 327 328 // Handle the message depending on its contents 329 switch { 330 case msg.Code == StatusMsg: 331 // Status messages should never arrive after the handshake 332 return errResp(ErrExtraStatusMsg, "uncontrolled status message") 333 334 // Block header query, collect the requested headers and reply 335 case msg.Code == GetBlockHeadersMsg: 336 // Decode the complex header query 337 var query getBlockHeadersData 338 if err := msg.Decode(&query); err != nil { 339 return errResp(ErrDecode, "%v: %v", msg, err) 340 } 341 hashMode := query.Origin.Hash != (common.Hash{}) 342 343 // Gather headers until the fetch or network limits is reached 344 var ( 345 bytes common.StorageSize 346 headers []*types.Header 347 unknown bool 348 ) 349 for !unknown && len(headers) < int(query.Amount) && bytes < softResponseLimit && len(headers) < downloader.MaxHeaderFetch { 350 // Retrieve the next header satisfying the query 351 var origin *types.Header 352 if hashMode { 353 origin = pm.blockchain.GetHeaderByHash(query.Origin.Hash) 354 } else { 355 origin = pm.blockchain.GetHeaderByNumber(query.Origin.Number) 356 } 357 if origin == nil { 358 break 359 } 360 number := origin.Number.Uint64() 361 headers = append(headers, origin) 362 bytes += estHeaderRlpSize 363 364 // Advance to the next header of the query 365 switch { 366 case query.Origin.Hash != (common.Hash{}) && query.Reverse: 367 // Hash based traversal towards the genesis block 368 for i := 0; i < int(query.Skip)+1; i++ { 369 if header := pm.blockchain.GetHeader(query.Origin.Hash, number); header != nil { 370 query.Origin.Hash = header.ParentHash 371 number-- 372 } else { 373 unknown = true 374 break 375 } 376 } 377 case query.Origin.Hash != (common.Hash{}) && !query.Reverse: 378 // Hash based traversal towards the leaf block 379 var ( 380 current = origin.Number.Uint64() 381 next = current + query.Skip + 1 382 ) 383 if next <= current { 384 infos, _ := json.MarshalIndent(p.Peer.Info(), "", " ") 385 p.Log().Warn("GetBlockHeaders skip overflow attack", "current", current, "skip", query.Skip, "next", next, "attacker", infos) 386 unknown = true 387 } else { 388 if header := pm.blockchain.GetHeaderByNumber(next); header != nil { 389 if pm.blockchain.GetBlockHashesFromHash(header.Hash(), query.Skip+1)[query.Skip] == query.Origin.Hash { 390 query.Origin.Hash = header.Hash() 391 } else { 392 unknown = true 393 } 394 } else { 395 unknown = true 396 } 397 } 398 case query.Reverse: 399 // Number based traversal towards the genesis block 400 if query.Origin.Number >= query.Skip+1 { 401 query.Origin.Number -= query.Skip + 1 402 } else { 403 unknown = true 404 } 405 406 case !query.Reverse: 407 // Number based traversal towards the leaf block 408 query.Origin.Number += query.Skip + 1 409 } 410 } 411 return p.SendBlockHeaders(headers) 412 413 case msg.Code == BlockHeadersMsg: 414 // A batch of headers arrived to one of our previous requests 415 var headers []*types.Header 416 if err := msg.Decode(&headers); err != nil { 417 return errResp(ErrDecode, "msg %v: %v", msg, err) 418 } 419 // If no headers were received, but we're expending a DAO fork check, maybe it's that 420 if len(headers) == 0 && p.forkDrop != nil { 421 // Possibly an empty reply to the fork header checks, sanity check TDs 422 verifyDAO := true 423 424 // If we already have a DAO header, we can check the peer's TD against it. If 425 // the peer's ahead of this, it too must have a reply to the DAO check 426 if daoHeader := pm.blockchain.GetHeaderByNumber(pm.chainconfig.DAOForkBlock.Uint64()); daoHeader != nil { 427 if _, td := p.Head(); td.Cmp(pm.blockchain.GetTd(daoHeader.Hash(), daoHeader.Number.Uint64())) >= 0 { 428 verifyDAO = false 429 } 430 } 431 // If we're seemingly on the same chain, disable the drop timer 432 if verifyDAO { 433 p.Log().Debug("Seems to be on the same side of the DAO fork") 434 p.forkDrop.Stop() 435 p.forkDrop = nil 436 return nil 437 } 438 } 439 // Filter out any explicitly requested headers, deliver the rest to the downloader 440 filter := len(headers) == 1 441 if filter { 442 // If it's a potential DAO fork check, validate against the rules 443 if p.forkDrop != nil && pm.chainconfig.DAOForkBlock.Cmp(headers[0].Number) == 0 { 444 // Disable the fork drop timer 445 p.forkDrop.Stop() 446 p.forkDrop = nil 447 448 // Validate the header and either drop the peer or continue 449 if err := misc.VerifyDAOHeaderExtraData(pm.chainconfig, headers[0]); err != nil { 450 p.Log().Debug("Verified to be on the other side of the DAO fork, dropping") 451 return err 452 } 453 p.Log().Debug("Verified to be on the same side of the DAO fork") 454 return nil 455 } 456 // Irrelevant of the fork checks, send the header to the fetcher just in case 457 headers = pm.fetcher.FilterHeaders(p.id, headers, time.Now()) 458 } 459 if len(headers) > 0 || !filter { 460 err := pm.downloader.DeliverHeaders(p.id, headers) 461 if err != nil { 462 log.Debug("Failed to deliver headers", "err", err) 463 } 464 } 465 466 case msg.Code == GetBlockBodiesMsg: 467 // Decode the retrieval message 468 msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size)) 469 if _, err := msgStream.List(); err != nil { 470 return err 471 } 472 // Gather blocks until the fetch or network limits is reached 473 var ( 474 hash common.Hash 475 bytes int 476 bodies []rlp.RawValue 477 ) 478 for bytes < softResponseLimit && len(bodies) < downloader.MaxBlockFetch { 479 // Retrieve the hash of the next block 480 if err := msgStream.Decode(&hash); err == rlp.EOL { 481 break 482 } else if err != nil { 483 return errResp(ErrDecode, "msg %v: %v", msg, err) 484 } 485 // Retrieve the requested block body, stopping if enough was found 486 if data := pm.blockchain.GetBodyRLP(hash); len(data) != 0 { 487 bodies = append(bodies, data) 488 bytes += len(data) 489 } 490 } 491 return p.SendBlockBodiesRLP(bodies) 492 493 case msg.Code == BlockBodiesMsg: 494 // A batch of block bodies arrived to one of our previous requests 495 var request blockBodiesData 496 if err := msg.Decode(&request); err != nil { 497 return errResp(ErrDecode, "msg %v: %v", msg, err) 498 } 499 // Deliver them all to the downloader for queuing 500 trasactions := make([][]*types.Transaction, len(request)) 501 uncles := make([][]*types.Header, len(request)) 502 503 for i, body := range request { 504 trasactions[i] = body.Transactions 505 uncles[i] = body.Uncles 506 } 507 // Filter out any explicitly requested bodies, deliver the rest to the downloader 508 filter := len(trasactions) > 0 || len(uncles) > 0 509 if filter { 510 trasactions, uncles = pm.fetcher.FilterBodies(p.id, trasactions, uncles, time.Now()) 511 } 512 if len(trasactions) > 0 || len(uncles) > 0 || !filter { 513 err := pm.downloader.DeliverBodies(p.id, trasactions, uncles) 514 if err != nil { 515 log.Debug("Failed to deliver bodies", "err", err) 516 } 517 } 518 519 case p.version >= eth63 && msg.Code == GetNodeDataMsg: 520 // Decode the retrieval message 521 msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size)) 522 if _, err := msgStream.List(); err != nil { 523 return err 524 } 525 // Gather state data until the fetch or network limits is reached 526 var ( 527 hash common.Hash 528 bytes int 529 data [][]byte 530 ) 531 for bytes < softResponseLimit && len(data) < downloader.MaxStateFetch { 532 // Retrieve the hash of the next state entry 533 if err := msgStream.Decode(&hash); err == rlp.EOL { 534 break 535 } else if err != nil { 536 return errResp(ErrDecode, "msg %v: %v", msg, err) 537 } 538 // Retrieve the requested state entry, stopping if enough was found 539 if entry, err := pm.blockchain.TrieNode(hash); err == nil { 540 data = append(data, entry) 541 bytes += len(entry) 542 } 543 } 544 return p.SendNodeData(data) 545 546 case p.version >= eth63 && msg.Code == NodeDataMsg: 547 // A batch of node state data arrived to one of our previous requests 548 var data [][]byte 549 if err := msg.Decode(&data); err != nil { 550 return errResp(ErrDecode, "msg %v: %v", msg, err) 551 } 552 // Deliver all to the downloader 553 if err := pm.downloader.DeliverNodeData(p.id, data); err != nil { 554 log.Debug("Failed to deliver node state data", "err", err) 555 } 556 557 case p.version >= eth63 && msg.Code == GetReceiptsMsg: 558 // Decode the retrieval message 559 msgStream := rlp.NewStream(msg.Payload, uint64(msg.Size)) 560 if _, err := msgStream.List(); err != nil { 561 return err 562 } 563 // Gather state data until the fetch or network limits is reached 564 var ( 565 hash common.Hash 566 bytes int 567 receipts []rlp.RawValue 568 ) 569 for bytes < softResponseLimit && len(receipts) < downloader.MaxReceiptFetch { 570 // Retrieve the hash of the next block 571 if err := msgStream.Decode(&hash); err == rlp.EOL { 572 break 573 } else if err != nil { 574 return errResp(ErrDecode, "msg %v: %v", msg, err) 575 } 576 // Retrieve the requested block's receipts, skipping if unknown to us 577 results := pm.blockchain.GetReceiptsByHash(hash) 578 if results == nil { 579 if header := pm.blockchain.GetHeaderByHash(hash); header == nil || header.ReceiptHash != types.EmptyRootHash { 580 continue 581 } 582 } 583 // If known, encode and queue for response packet 584 if encoded, err := rlp.EncodeToBytes(results); err != nil { 585 log.Error("Failed to encode receipt", "err", err) 586 } else { 587 receipts = append(receipts, encoded) 588 bytes += len(encoded) 589 } 590 } 591 return p.SendReceiptsRLP(receipts) 592 593 case p.version >= eth63 && msg.Code == ReceiptsMsg: 594 // A batch of receipts arrived to one of our previous requests 595 var receipts [][]*types.Receipt 596 if err := msg.Decode(&receipts); err != nil { 597 return errResp(ErrDecode, "msg %v: %v", msg, err) 598 } 599 // Deliver all to the downloader 600 if err := pm.downloader.DeliverReceipts(p.id, receipts); err != nil { 601 log.Debug("Failed to deliver receipts", "err", err) 602 } 603 604 case msg.Code == NewBlockHashesMsg: 605 var announces newBlockHashesData 606 if err := msg.Decode(&announces); err != nil { 607 return errResp(ErrDecode, "%v: %v", msg, err) 608 } 609 // Mark the hashes as present at the remote node 610 for _, block := range announces { 611 p.MarkBlock(block.Hash) 612 } 613 // Schedule all the unknown hashes for retrieval 614 unknown := make(newBlockHashesData, 0, len(announces)) 615 for _, block := range announces { 616 if !pm.blockchain.HasBlock(block.Hash, block.Number) { 617 unknown = append(unknown, block) 618 } 619 } 620 for _, block := range unknown { 621 pm.fetcher.Notify(p.id, block.Hash, block.Number, time.Now(), p.RequestOneHeader, p.RequestBodies) 622 } 623 624 case msg.Code == NewBlockMsg: 625 // Retrieve and decode the propagated block 626 var request newBlockData 627 if err := msg.Decode(&request); err != nil { 628 return errResp(ErrDecode, "%v: %v", msg, err) 629 } 630 request.Block.ReceivedAt = msg.ReceivedAt 631 request.Block.ReceivedFrom = p 632 633 // Mark the peer as owning the block and schedule it for import 634 p.MarkBlock(request.Block.Hash()) 635 pm.fetcher.Enqueue(p.id, request.Block) 636 637 // Assuming the block is importable by the peer, but possibly not yet done so, 638 // calculate the head hash and TD that the peer truly must have. 639 var ( 640 trueHead = request.Block.ParentHash() 641 trueTD = new(big.Int).Sub(request.TD, request.Block.Difficulty()) 642 ) 643 // Update the peers total difficulty if better than the previous 644 if _, td := p.Head(); trueTD.Cmp(td) > 0 { 645 p.SetHead(trueHead, trueTD) 646 647 // Schedule a sync if above ours. Note, this will not fire a sync for a gap of 648 // a singe block (as the true TD is below the propagated block), however this 649 // scenario should easily be covered by the fetcher. 650 currentBlock := pm.blockchain.CurrentBlock() 651 if trueTD.Cmp(pm.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64())) > 0 { 652 go pm.synchronise(p) 653 } 654 } 655 656 case msg.Code == TxMsg: 657 // Transactions arrived, make sure we have a valid and fresh chain to handle them 658 if atomic.LoadUint32(&pm.acceptTxs) == 0 { 659 break 660 } 661 // Transactions can be processed, parse all of them and deliver to the pool 662 var txs []*types.Transaction 663 if err := msg.Decode(&txs); err != nil { 664 return errResp(ErrDecode, "msg %v: %v", msg, err) 665 } 666 for i, tx := range txs { 667 // Validate and mark the remote transaction 668 if tx == nil { 669 return errResp(ErrDecode, "transaction %d is nil", i) 670 } 671 p.MarkTransaction(tx.Hash()) 672 } 673 pm.txpool.AddRemotes(txs) 674 675 default: 676 return errResp(ErrInvalidMsgCode, "%v", msg.Code) 677 } 678 return nil 679 } 680 681 // BroadcastBlock will either propagate a block to a subset of it's peers, or 682 // will only announce it's availability (depending what's requested). 683 func (pm *ProtocolManager) BroadcastBlock(block *types.Block, propagate bool) { 684 hash := block.Hash() 685 peers := pm.peers.PeersWithoutBlock(hash) 686 687 // If propagation is requested, send to a subset of the peer 688 if propagate { 689 // Calculate the TD of the block (it's not imported yet, so block.Td is not valid) 690 var td *big.Int 691 if parent := pm.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1); parent != nil { 692 td = new(big.Int).Add(block.Difficulty(), pm.blockchain.GetTd(block.ParentHash(), block.NumberU64()-1)) 693 } else { 694 log.Error("Propagating dangling block", "number", block.Number(), "hash", hash) 695 return 696 } 697 // Send the block to a subset of our peers 698 transfer := peers[:int(math.Sqrt(float64(len(peers))))] 699 for _, peer := range transfer { 700 peer.SendNewBlock(block, td) 701 } 702 log.Trace("Propagated block", "hash", hash, "recipients", len(transfer), "duration", common.PrettyDuration(time.Since(block.ReceivedAt))) 703 return 704 } 705 // Otherwise if the block is indeed in out own chain, announce it 706 if pm.blockchain.HasBlock(hash, block.NumberU64()) { 707 for _, peer := range peers { 708 peer.SendNewBlockHashes([]common.Hash{hash}, []uint64{block.NumberU64()}) 709 } 710 log.Trace("Announced block", "hash", hash, "recipients", len(peers), "duration", common.PrettyDuration(time.Since(block.ReceivedAt))) 711 } 712 } 713 714 // BroadcastTx will propagate a transaction to all peers which are not known to 715 // already have the given transaction. 716 func (pm *ProtocolManager) BroadcastTx(hash common.Hash, tx *types.Transaction) { 717 // Broadcast transaction to a batch of peers not knowing about it 718 peers := pm.peers.PeersWithoutTx(hash) 719 //FIXME include this again: peers = peers[:int(math.Sqrt(float64(len(peers))))] 720 for _, peer := range peers { 721 peer.SendTransactions(types.Transactions{tx}) 722 } 723 log.Trace("Broadcast transaction", "hash", hash, "recipients", len(peers)) 724 } 725 726 // Mined broadcast loop 727 func (self *ProtocolManager) minedBroadcastLoop() { 728 // automatically stops if unsubscribe 729 for obj := range self.minedBlockSub.Chan() { 730 switch ev := obj.Data.(type) { 731 case core.NewMinedBlockEvent: 732 self.BroadcastBlock(ev.Block, true) // First propagate block to peers 733 self.BroadcastBlock(ev.Block, false) // Only then announce to the rest 734 } 735 } 736 } 737 738 func (self *ProtocolManager) txBroadcastLoop() { 739 for { 740 select { 741 case event := <-self.txCh: 742 self.BroadcastTx(event.Tx.Hash(), event.Tx) 743 744 // Err() channel will be closed when unsubscribing. 745 case <-self.txSub.Err(): 746 return 747 } 748 } 749 } 750 751 // NodeInfo represents a short summary of the Ethereum sub-protocol metadata 752 // known about the host peer. 753 type NodeInfo struct { 754 Network uint64 `json:"network"` // Ethereum network ID (1=Frontier, 2=Morden, Ropsten=3, Rinkeby=4) 755 Difficulty *big.Int `json:"difficulty"` // Total difficulty of the host's blockchain 756 Genesis common.Hash `json:"genesis"` // SHA3 hash of the host's genesis block 757 Config *params.ChainConfig `json:"config"` // Chain configuration for the fork rules 758 Head common.Hash `json:"head"` // SHA3 hash of the host's best owned block 759 } 760 761 // NodeInfo retrieves some protocol metadata about the running host node. 762 func (self *ProtocolManager) NodeInfo() *NodeInfo { 763 currentBlock := self.blockchain.CurrentBlock() 764 return &NodeInfo{ 765 Network: self.networkId, 766 Difficulty: self.blockchain.GetTd(currentBlock.Hash(), currentBlock.NumberU64()), 767 Genesis: self.blockchain.Genesis().Hash(), 768 Config: self.blockchain.Config(), 769 Head: currentBlock.Hash(), 770 } 771 }