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