peer.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. package eth
  17. import (
  18. "errors"
  19. "fmt"
  20. "math/big"
  21. "sync"
  22. "time"
  23. mapset "github.com/deckarep/golang-set"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. var (
  30. errClosed = errors.New("peer set is closed")
  31. errAlreadyRegistered = errors.New("peer is already registered")
  32. errNotRegistered = errors.New("peer is not registered")
  33. )
  34. const (
  35. maxKnownTxs = 32768 // Maximum transactions hashes to keep in the known list (prevent DOS)
  36. maxKnownBlocks = 1024 // Maximum block hashes to keep in the known list (prevent DOS)
  37. // maxQueuedTxs is the maximum number of transaction lists to queue up before
  38. // dropping broadcasts. This is a sensitive number as a transaction list might
  39. // contain a single transaction, or thousands.
  40. maxQueuedTxs = 128
  41. // maxQueuedProps is the maximum number of block propagations to queue up before
  42. // dropping broadcasts. There's not much point in queueing stale blocks, so a few
  43. // that might cover uncles should be enough.
  44. maxQueuedProps = 4
  45. // maxQueuedAnns is the maximum number of block announcements to queue up before
  46. // dropping broadcasts. Similarly to block propagations, there's no point to queue
  47. // above some healthy uncle limit, so use that.
  48. maxQueuedAnns = 4
  49. handshakeTimeout = 5 * time.Second
  50. )
  51. // PeerInfo represents a short summary of the Ethereum sub-protocol metadata known
  52. // about a connected peer.
  53. type PeerInfo struct {
  54. Version int `json:"version"` // Ethereum protocol version negotiated
  55. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the peer's blockchain
  56. Head string `json:"head"` // SHA3 hash of the peer's best owned block
  57. }
  58. // propEvent is a block propagation, waiting for its turn in the broadcast queue.
  59. type propEvent struct {
  60. block *types.Block
  61. td *big.Int
  62. }
  63. type peer struct {
  64. id string
  65. *p2p.Peer
  66. rw p2p.MsgReadWriter
  67. version int // Protocol version negotiated
  68. syncDrop *time.Timer // Timed connection dropper if sync progress isn't validated in time
  69. head common.Hash
  70. td *big.Int
  71. lock sync.RWMutex
  72. knownTxs mapset.Set // Set of transaction hashes known to be known by this peer
  73. knownBlocks mapset.Set // Set of block hashes known to be known by this peer
  74. queuedTxs chan []*types.Transaction // Queue of transactions to broadcast to the peer
  75. queuedProps chan *propEvent // Queue of blocks to broadcast to the peer
  76. queuedAnns chan *types.Block // Queue of blocks to announce to the peer
  77. term chan struct{} // Termination channel to stop the broadcaster
  78. }
  79. func newPeer(version int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  80. return &peer{
  81. Peer: p,
  82. rw: rw,
  83. version: version,
  84. id: fmt.Sprintf("%x", p.ID().Bytes()[:8]),
  85. knownTxs: mapset.NewSet(),
  86. knownBlocks: mapset.NewSet(),
  87. queuedTxs: make(chan []*types.Transaction, maxQueuedTxs),
  88. queuedProps: make(chan *propEvent, maxQueuedProps),
  89. queuedAnns: make(chan *types.Block, maxQueuedAnns),
  90. term: make(chan struct{}),
  91. }
  92. }
  93. // broadcast is a write loop that multiplexes block propagations, announcements
  94. // and transaction broadcasts into the remote peer. The goal is to have an async
  95. // writer that does not lock up node internals.
  96. func (p *peer) broadcast() {
  97. for {
  98. select {
  99. case txs := <-p.queuedTxs:
  100. if err := p.SendTransactions(txs); err != nil {
  101. return
  102. }
  103. p.Log().Trace("Broadcast transactions", "count", len(txs))
  104. case prop := <-p.queuedProps:
  105. if err := p.SendNewBlock(prop.block, prop.td); err != nil {
  106. return
  107. }
  108. p.Log().Trace("Propagated block", "number", prop.block.Number(), "hash", prop.block.Hash(), "td", prop.td)
  109. case block := <-p.queuedAnns:
  110. if err := p.SendNewBlockHashes([]common.Hash{block.Hash()}, []uint64{block.NumberU64()}); err != nil {
  111. return
  112. }
  113. p.Log().Trace("Announced block", "number", block.Number(), "hash", block.Hash())
  114. case <-p.term:
  115. return
  116. }
  117. }
  118. }
  119. // close signals the broadcast goroutine to terminate.
  120. func (p *peer) close() {
  121. close(p.term)
  122. }
  123. // Info gathers and returns a collection of metadata known about a peer.
  124. func (p *peer) Info() *PeerInfo {
  125. hash, td := p.Head()
  126. return &PeerInfo{
  127. Version: p.version,
  128. Difficulty: td,
  129. Head: hash.Hex(),
  130. }
  131. }
  132. // Head retrieves a copy of the current head hash and total difficulty of the
  133. // peer.
  134. func (p *peer) Head() (hash common.Hash, td *big.Int) {
  135. p.lock.RLock()
  136. defer p.lock.RUnlock()
  137. copy(hash[:], p.head[:])
  138. return hash, new(big.Int).Set(p.td)
  139. }
  140. // SetHead updates the head hash and total difficulty of the peer.
  141. func (p *peer) SetHead(hash common.Hash, td *big.Int) {
  142. p.lock.Lock()
  143. defer p.lock.Unlock()
  144. copy(p.head[:], hash[:])
  145. p.td.Set(td)
  146. }
  147. // MarkBlock marks a block as known for the peer, ensuring that the block will
  148. // never be propagated to this particular peer.
  149. func (p *peer) MarkBlock(hash common.Hash) {
  150. // If we reached the memory allowance, drop a previously known block hash
  151. for p.knownBlocks.Cardinality() >= maxKnownBlocks {
  152. p.knownBlocks.Pop()
  153. }
  154. p.knownBlocks.Add(hash)
  155. }
  156. // MarkTransaction marks a transaction as known for the peer, ensuring that it
  157. // will never be propagated to this particular peer.
  158. func (p *peer) MarkTransaction(hash common.Hash) {
  159. // If we reached the memory allowance, drop a previously known transaction hash
  160. for p.knownTxs.Cardinality() >= maxKnownTxs {
  161. p.knownTxs.Pop()
  162. }
  163. p.knownTxs.Add(hash)
  164. }
  165. // SendTransactions sends transactions to the peer and includes the hashes
  166. // in its transaction hash set for future reference.
  167. func (p *peer) SendTransactions(txs types.Transactions) error {
  168. // Mark all the transactions as known, but ensure we don't overflow our limits
  169. for _, tx := range txs {
  170. p.knownTxs.Add(tx.Hash())
  171. }
  172. for p.knownTxs.Cardinality() >= maxKnownTxs {
  173. p.knownTxs.Pop()
  174. }
  175. return p2p.Send(p.rw, TxMsg, txs)
  176. }
  177. // AsyncSendTransactions queues list of transactions propagation to a remote
  178. // peer. If the peer's broadcast queue is full, the event is silently dropped.
  179. func (p *peer) AsyncSendTransactions(txs []*types.Transaction) {
  180. select {
  181. case p.queuedTxs <- txs:
  182. // Mark all the transactions as known, but ensure we don't overflow our limits
  183. for _, tx := range txs {
  184. p.knownTxs.Add(tx.Hash())
  185. }
  186. for p.knownTxs.Cardinality() >= maxKnownTxs {
  187. p.knownTxs.Pop()
  188. }
  189. default:
  190. p.Log().Debug("Dropping transaction propagation", "count", len(txs))
  191. }
  192. }
  193. // SendNewBlockHashes announces the availability of a number of blocks through
  194. // a hash notification.
  195. func (p *peer) SendNewBlockHashes(hashes []common.Hash, numbers []uint64) error {
  196. // Mark all the block hashes as known, but ensure we don't overflow our limits
  197. for _, hash := range hashes {
  198. p.knownBlocks.Add(hash)
  199. }
  200. for p.knownBlocks.Cardinality() >= maxKnownBlocks {
  201. p.knownBlocks.Pop()
  202. }
  203. request := make(newBlockHashesData, len(hashes))
  204. for i := 0; i < len(hashes); i++ {
  205. request[i].Hash = hashes[i]
  206. request[i].Number = numbers[i]
  207. }
  208. return p2p.Send(p.rw, NewBlockHashesMsg, request)
  209. }
  210. // AsyncSendNewBlockHash queues the availability of a block for propagation to a
  211. // remote peer. If the peer's broadcast queue is full, the event is silently
  212. // dropped.
  213. func (p *peer) AsyncSendNewBlockHash(block *types.Block) {
  214. select {
  215. case p.queuedAnns <- block:
  216. // Mark all the block hash as known, but ensure we don't overflow our limits
  217. p.knownBlocks.Add(block.Hash())
  218. for p.knownBlocks.Cardinality() >= maxKnownBlocks {
  219. p.knownBlocks.Pop()
  220. }
  221. default:
  222. p.Log().Debug("Dropping block announcement", "number", block.NumberU64(), "hash", block.Hash())
  223. }
  224. }
  225. // SendNewBlock propagates an entire block to a remote peer.
  226. func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
  227. // Mark all the block hash as known, but ensure we don't overflow our limits
  228. p.knownBlocks.Add(block.Hash())
  229. for p.knownBlocks.Cardinality() >= maxKnownBlocks {
  230. p.knownBlocks.Pop()
  231. }
  232. return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
  233. }
  234. // AsyncSendNewBlock queues an entire block for propagation to a remote peer. If
  235. // the peer's broadcast queue is full, the event is silently dropped.
  236. func (p *peer) AsyncSendNewBlock(block *types.Block, td *big.Int) {
  237. select {
  238. case p.queuedProps <- &propEvent{block: block, td: td}:
  239. // Mark all the block hash as known, but ensure we don't overflow our limits
  240. p.knownBlocks.Add(block.Hash())
  241. for p.knownBlocks.Cardinality() >= maxKnownBlocks {
  242. p.knownBlocks.Pop()
  243. }
  244. default:
  245. p.Log().Debug("Dropping block propagation", "number", block.NumberU64(), "hash", block.Hash())
  246. }
  247. }
  248. // SendBlockHeaders sends a batch of block headers to the remote peer.
  249. func (p *peer) SendBlockHeaders(headers []*types.Header) error {
  250. return p2p.Send(p.rw, BlockHeadersMsg, headers)
  251. }
  252. // SendBlockBodies sends a batch of block contents to the remote peer.
  253. func (p *peer) SendBlockBodies(bodies []*blockBody) error {
  254. return p2p.Send(p.rw, BlockBodiesMsg, blockBodiesData(bodies))
  255. }
  256. // SendBlockBodiesRLP sends a batch of block contents to the remote peer from
  257. // an already RLP encoded format.
  258. func (p *peer) SendBlockBodiesRLP(bodies []rlp.RawValue) error {
  259. return p2p.Send(p.rw, BlockBodiesMsg, bodies)
  260. }
  261. // SendNodeDataRLP sends a batch of arbitrary internal data, corresponding to the
  262. // hashes requested.
  263. func (p *peer) SendNodeData(data [][]byte) error {
  264. return p2p.Send(p.rw, NodeDataMsg, data)
  265. }
  266. // SendReceiptsRLP sends a batch of transaction receipts, corresponding to the
  267. // ones requested from an already RLP encoded format.
  268. func (p *peer) SendReceiptsRLP(receipts []rlp.RawValue) error {
  269. return p2p.Send(p.rw, ReceiptsMsg, receipts)
  270. }
  271. // RequestOneHeader is a wrapper around the header query functions to fetch a
  272. // single header. It is used solely by the fetcher.
  273. func (p *peer) RequestOneHeader(hash common.Hash) error {
  274. p.Log().Debug("Fetching single header", "hash", hash)
  275. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: uint64(1), Skip: uint64(0), Reverse: false})
  276. }
  277. // RequestHeadersByHash fetches a batch of blocks' headers corresponding to the
  278. // specified header query, based on the hash of an origin block.
  279. func (p *peer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
  280. p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse)
  281. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
  282. }
  283. // RequestHeadersByNumber fetches a batch of blocks' headers corresponding to the
  284. // specified header query, based on the number of an origin block.
  285. func (p *peer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
  286. p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse)
  287. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
  288. }
  289. // RequestBodies fetches a batch of blocks' bodies corresponding to the hashes
  290. // specified.
  291. func (p *peer) RequestBodies(hashes []common.Hash) error {
  292. p.Log().Debug("Fetching batch of block bodies", "count", len(hashes))
  293. return p2p.Send(p.rw, GetBlockBodiesMsg, hashes)
  294. }
  295. // RequestNodeData fetches a batch of arbitrary data from a node's known state
  296. // data, corresponding to the specified hashes.
  297. func (p *peer) RequestNodeData(hashes []common.Hash) error {
  298. p.Log().Debug("Fetching batch of state data", "count", len(hashes))
  299. return p2p.Send(p.rw, GetNodeDataMsg, hashes)
  300. }
  301. // RequestReceipts fetches a batch of transaction receipts from a remote node.
  302. func (p *peer) RequestReceipts(hashes []common.Hash) error {
  303. p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
  304. return p2p.Send(p.rw, GetReceiptsMsg, hashes)
  305. }
  306. // Handshake executes the eth protocol handshake, negotiating version number,
  307. // network IDs, difficulties, head and genesis blocks.
  308. func (p *peer) Handshake(network uint64, td *big.Int, head common.Hash, genesis common.Hash) error {
  309. // Send out own handshake in a new thread
  310. errc := make(chan error, 2)
  311. var status statusData // safe to read after two values have been received from errc
  312. go func() {
  313. errc <- p2p.Send(p.rw, StatusMsg, &statusData{
  314. ProtocolVersion: uint32(p.version),
  315. NetworkId: network,
  316. TD: td,
  317. CurrentBlock: head,
  318. GenesisBlock: genesis,
  319. })
  320. }()
  321. go func() {
  322. errc <- p.readStatus(network, &status, genesis)
  323. }()
  324. timeout := time.NewTimer(handshakeTimeout)
  325. defer timeout.Stop()
  326. for i := 0; i < 2; i++ {
  327. select {
  328. case err := <-errc:
  329. if err != nil {
  330. return err
  331. }
  332. case <-timeout.C:
  333. return p2p.DiscReadTimeout
  334. }
  335. }
  336. p.td, p.head = status.TD, status.CurrentBlock
  337. return nil
  338. }
  339. func (p *peer) readStatus(network uint64, status *statusData, genesis common.Hash) (err error) {
  340. msg, err := p.rw.ReadMsg()
  341. if err != nil {
  342. return err
  343. }
  344. if msg.Code != StatusMsg {
  345. return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  346. }
  347. if msg.Size > protocolMaxMsgSize {
  348. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, protocolMaxMsgSize)
  349. }
  350. // Decode the handshake and make sure everything matches
  351. if err := msg.Decode(&status); err != nil {
  352. return errResp(ErrDecode, "msg %v: %v", msg, err)
  353. }
  354. if status.GenesisBlock != genesis {
  355. return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock[:8], genesis[:8])
  356. }
  357. if status.NetworkId != network {
  358. return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, network)
  359. }
  360. if int(status.ProtocolVersion) != p.version {
  361. return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
  362. }
  363. return nil
  364. }
  365. // String implements fmt.Stringer.
  366. func (p *peer) String() string {
  367. return fmt.Sprintf("Peer %s [%s]", p.id,
  368. fmt.Sprintf("eth/%2d", p.version),
  369. )
  370. }
  371. // peerSet represents the collection of active peers currently participating in
  372. // the Ethereum sub-protocol.
  373. type peerSet struct {
  374. peers map[string]*peer
  375. lock sync.RWMutex
  376. closed bool
  377. }
  378. // newPeerSet creates a new peer set to track the active participants.
  379. func newPeerSet() *peerSet {
  380. return &peerSet{
  381. peers: make(map[string]*peer),
  382. }
  383. }
  384. // Register injects a new peer into the working set, or returns an error if the
  385. // peer is already known. If a new peer it registered, its broadcast loop is also
  386. // started.
  387. func (ps *peerSet) Register(p *peer) error {
  388. ps.lock.Lock()
  389. defer ps.lock.Unlock()
  390. if ps.closed {
  391. return errClosed
  392. }
  393. if _, ok := ps.peers[p.id]; ok {
  394. return errAlreadyRegistered
  395. }
  396. ps.peers[p.id] = p
  397. go p.broadcast()
  398. return nil
  399. }
  400. // Unregister removes a remote peer from the active set, disabling any further
  401. // actions to/from that particular entity.
  402. func (ps *peerSet) Unregister(id string) error {
  403. ps.lock.Lock()
  404. defer ps.lock.Unlock()
  405. p, ok := ps.peers[id]
  406. if !ok {
  407. return errNotRegistered
  408. }
  409. delete(ps.peers, id)
  410. p.close()
  411. return nil
  412. }
  413. // Peer retrieves the registered peer with the given id.
  414. func (ps *peerSet) Peer(id string) *peer {
  415. ps.lock.RLock()
  416. defer ps.lock.RUnlock()
  417. return ps.peers[id]
  418. }
  419. // Len returns if the current number of peers in the set.
  420. func (ps *peerSet) Len() int {
  421. ps.lock.RLock()
  422. defer ps.lock.RUnlock()
  423. return len(ps.peers)
  424. }
  425. // PeersWithoutBlock retrieves a list of peers that do not have a given block in
  426. // their set of known hashes.
  427. func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
  428. ps.lock.RLock()
  429. defer ps.lock.RUnlock()
  430. list := make([]*peer, 0, len(ps.peers))
  431. for _, p := range ps.peers {
  432. if !p.knownBlocks.Contains(hash) {
  433. list = append(list, p)
  434. }
  435. }
  436. return list
  437. }
  438. // PeersWithoutTx retrieves a list of peers that do not have a given transaction
  439. // in their set of known hashes.
  440. func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
  441. ps.lock.RLock()
  442. defer ps.lock.RUnlock()
  443. list := make([]*peer, 0, len(ps.peers))
  444. for _, p := range ps.peers {
  445. if !p.knownTxs.Contains(hash) {
  446. list = append(list, p)
  447. }
  448. }
  449. return list
  450. }
  451. // BestPeer retrieves the known peer with the currently highest total difficulty.
  452. func (ps *peerSet) BestPeer() *peer {
  453. ps.lock.RLock()
  454. defer ps.lock.RUnlock()
  455. var (
  456. bestPeer *peer
  457. bestTd *big.Int
  458. )
  459. for _, p := range ps.peers {
  460. if _, td := p.Head(); bestPeer == nil || td.Cmp(bestTd) > 0 {
  461. bestPeer, bestTd = p, td
  462. }
  463. }
  464. return bestPeer
  465. }
  466. // Close disconnects all peers.
  467. // No new peers can be registered after Close has returned.
  468. func (ps *peerSet) Close() {
  469. ps.lock.Lock()
  470. defer ps.lock.Unlock()
  471. for _, p := range ps.peers {
  472. p.Disconnect(p2p.DiscQuitting)
  473. }
  474. ps.closed = true
  475. }