peer.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/core/types"
  25. "github.com/ethereum/go-ethereum/p2p"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "gopkg.in/fatih/set.v0"
  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. forkDrop *time.Timer // Timed connection dropper if forks aren't validated in time
  69. head common.Hash
  70. td *big.Int
  71. lock sync.RWMutex
  72. knownTxs *set.Set // Set of transaction hashes known to be known by this peer
  73. knownBlocks *set.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: set.New(),
  86. knownBlocks: set.New(),
  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.Size() >= 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.Size() >= 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. for _, tx := range txs {
  169. p.knownTxs.Add(tx.Hash())
  170. }
  171. return p2p.Send(p.rw, TxMsg, txs)
  172. }
  173. // AsyncSendTransactions queues list of transactions propagation to a remote
  174. // peer. If the peer's broadcast queue is full, the event is silently dropped.
  175. func (p *peer) AsyncSendTransactions(txs []*types.Transaction) {
  176. select {
  177. case p.queuedTxs <- txs:
  178. for _, tx := range txs {
  179. p.knownTxs.Add(tx.Hash())
  180. }
  181. default:
  182. p.Log().Debug("Dropping transaction propagation", "count", len(txs))
  183. }
  184. }
  185. // SendNewBlockHashes announces the availability of a number of blocks through
  186. // a hash notification.
  187. func (p *peer) SendNewBlockHashes(hashes []common.Hash, numbers []uint64) error {
  188. for _, hash := range hashes {
  189. p.knownBlocks.Add(hash)
  190. }
  191. request := make(newBlockHashesData, len(hashes))
  192. for i := 0; i < len(hashes); i++ {
  193. request[i].Hash = hashes[i]
  194. request[i].Number = numbers[i]
  195. }
  196. return p2p.Send(p.rw, NewBlockHashesMsg, request)
  197. }
  198. // AsyncSendNewBlockHash queues the availability of a block for propagation to a
  199. // remote peer. If the peer's broadcast queue is full, the event is silently
  200. // dropped.
  201. func (p *peer) AsyncSendNewBlockHash(block *types.Block) {
  202. select {
  203. case p.queuedAnns <- block:
  204. p.knownBlocks.Add(block.Hash())
  205. default:
  206. p.Log().Debug("Dropping block announcement", "number", block.NumberU64(), "hash", block.Hash())
  207. }
  208. }
  209. // SendNewBlock propagates an entire block to a remote peer.
  210. func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
  211. p.knownBlocks.Add(block.Hash())
  212. return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
  213. }
  214. // AsyncSendNewBlock queues an entire block for propagation to a remote peer. If
  215. // the peer's broadcast queue is full, the event is silently dropped.
  216. func (p *peer) AsyncSendNewBlock(block *types.Block, td *big.Int) {
  217. select {
  218. case p.queuedProps <- &propEvent{block: block, td: td}:
  219. p.knownBlocks.Add(block.Hash())
  220. default:
  221. p.Log().Debug("Dropping block propagation", "number", block.NumberU64(), "hash", block.Hash())
  222. }
  223. }
  224. // SendBlockHeaders sends a batch of block headers to the remote peer.
  225. func (p *peer) SendBlockHeaders(headers []*types.Header) error {
  226. return p2p.Send(p.rw, BlockHeadersMsg, headers)
  227. }
  228. // SendBlockBodies sends a batch of block contents to the remote peer.
  229. func (p *peer) SendBlockBodies(bodies []*blockBody) error {
  230. return p2p.Send(p.rw, BlockBodiesMsg, blockBodiesData(bodies))
  231. }
  232. // SendBlockBodiesRLP sends a batch of block contents to the remote peer from
  233. // an already RLP encoded format.
  234. func (p *peer) SendBlockBodiesRLP(bodies []rlp.RawValue) error {
  235. return p2p.Send(p.rw, BlockBodiesMsg, bodies)
  236. }
  237. // SendNodeDataRLP sends a batch of arbitrary internal data, corresponding to the
  238. // hashes requested.
  239. func (p *peer) SendNodeData(data [][]byte) error {
  240. return p2p.Send(p.rw, NodeDataMsg, data)
  241. }
  242. // SendReceiptsRLP sends a batch of transaction receipts, corresponding to the
  243. // ones requested from an already RLP encoded format.
  244. func (p *peer) SendReceiptsRLP(receipts []rlp.RawValue) error {
  245. return p2p.Send(p.rw, ReceiptsMsg, receipts)
  246. }
  247. // RequestOneHeader is a wrapper around the header query functions to fetch a
  248. // single header. It is used solely by the fetcher.
  249. func (p *peer) RequestOneHeader(hash common.Hash) error {
  250. p.Log().Debug("Fetching single header", "hash", hash)
  251. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: uint64(1), Skip: uint64(0), Reverse: false})
  252. }
  253. // RequestHeadersByHash fetches a batch of blocks' headers corresponding to the
  254. // specified header query, based on the hash of an origin block.
  255. func (p *peer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
  256. p.Log().Debug("Fetching batch of headers", "count", amount, "fromhash", origin, "skip", skip, "reverse", reverse)
  257. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
  258. }
  259. // RequestHeadersByNumber fetches a batch of blocks' headers corresponding to the
  260. // specified header query, based on the number of an origin block.
  261. func (p *peer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
  262. p.Log().Debug("Fetching batch of headers", "count", amount, "fromnum", origin, "skip", skip, "reverse", reverse)
  263. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
  264. }
  265. // RequestBodies fetches a batch of blocks' bodies corresponding to the hashes
  266. // specified.
  267. func (p *peer) RequestBodies(hashes []common.Hash) error {
  268. p.Log().Debug("Fetching batch of block bodies", "count", len(hashes))
  269. return p2p.Send(p.rw, GetBlockBodiesMsg, hashes)
  270. }
  271. // RequestNodeData fetches a batch of arbitrary data from a node's known state
  272. // data, corresponding to the specified hashes.
  273. func (p *peer) RequestNodeData(hashes []common.Hash) error {
  274. p.Log().Debug("Fetching batch of state data", "count", len(hashes))
  275. return p2p.Send(p.rw, GetNodeDataMsg, hashes)
  276. }
  277. // RequestReceipts fetches a batch of transaction receipts from a remote node.
  278. func (p *peer) RequestReceipts(hashes []common.Hash) error {
  279. p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
  280. return p2p.Send(p.rw, GetReceiptsMsg, hashes)
  281. }
  282. // Handshake executes the eth protocol handshake, negotiating version number,
  283. // network IDs, difficulties, head and genesis blocks.
  284. func (p *peer) Handshake(network uint64, td *big.Int, head common.Hash, genesis common.Hash) error {
  285. // Send out own handshake in a new thread
  286. errc := make(chan error, 2)
  287. var status statusData // safe to read after two values have been received from errc
  288. go func() {
  289. errc <- p2p.Send(p.rw, StatusMsg, &statusData{
  290. ProtocolVersion: uint32(p.version),
  291. NetworkId: network,
  292. TD: td,
  293. CurrentBlock: head,
  294. GenesisBlock: genesis,
  295. })
  296. }()
  297. go func() {
  298. errc <- p.readStatus(network, &status, genesis)
  299. }()
  300. timeout := time.NewTimer(handshakeTimeout)
  301. defer timeout.Stop()
  302. for i := 0; i < 2; i++ {
  303. select {
  304. case err := <-errc:
  305. if err != nil {
  306. return err
  307. }
  308. case <-timeout.C:
  309. return p2p.DiscReadTimeout
  310. }
  311. }
  312. p.td, p.head = status.TD, status.CurrentBlock
  313. return nil
  314. }
  315. func (p *peer) readStatus(network uint64, status *statusData, genesis common.Hash) (err error) {
  316. msg, err := p.rw.ReadMsg()
  317. if err != nil {
  318. return err
  319. }
  320. if msg.Code != StatusMsg {
  321. return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  322. }
  323. if msg.Size > ProtocolMaxMsgSize {
  324. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  325. }
  326. // Decode the handshake and make sure everything matches
  327. if err := msg.Decode(&status); err != nil {
  328. return errResp(ErrDecode, "msg %v: %v", msg, err)
  329. }
  330. if status.GenesisBlock != genesis {
  331. return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock[:8], genesis[:8])
  332. }
  333. if status.NetworkId != network {
  334. return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, network)
  335. }
  336. if int(status.ProtocolVersion) != p.version {
  337. return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
  338. }
  339. return nil
  340. }
  341. // String implements fmt.Stringer.
  342. func (p *peer) String() string {
  343. return fmt.Sprintf("Peer %s [%s]", p.id,
  344. fmt.Sprintf("eth/%2d", p.version),
  345. )
  346. }
  347. // peerSet represents the collection of active peers currently participating in
  348. // the Ethereum sub-protocol.
  349. type peerSet struct {
  350. peers map[string]*peer
  351. lock sync.RWMutex
  352. closed bool
  353. }
  354. // newPeerSet creates a new peer set to track the active participants.
  355. func newPeerSet() *peerSet {
  356. return &peerSet{
  357. peers: make(map[string]*peer),
  358. }
  359. }
  360. // Register injects a new peer into the working set, or returns an error if the
  361. // peer is already known. If a new peer it registered, its broadcast loop is also
  362. // started.
  363. func (ps *peerSet) Register(p *peer) error {
  364. ps.lock.Lock()
  365. defer ps.lock.Unlock()
  366. if ps.closed {
  367. return errClosed
  368. }
  369. if _, ok := ps.peers[p.id]; ok {
  370. return errAlreadyRegistered
  371. }
  372. ps.peers[p.id] = p
  373. go p.broadcast()
  374. return nil
  375. }
  376. // Unregister removes a remote peer from the active set, disabling any further
  377. // actions to/from that particular entity.
  378. func (ps *peerSet) Unregister(id string) error {
  379. ps.lock.Lock()
  380. defer ps.lock.Unlock()
  381. p, ok := ps.peers[id]
  382. if !ok {
  383. return errNotRegistered
  384. }
  385. delete(ps.peers, id)
  386. p.close()
  387. return nil
  388. }
  389. // Peer retrieves the registered peer with the given id.
  390. func (ps *peerSet) Peer(id string) *peer {
  391. ps.lock.RLock()
  392. defer ps.lock.RUnlock()
  393. return ps.peers[id]
  394. }
  395. // Len returns if the current number of peers in the set.
  396. func (ps *peerSet) Len() int {
  397. ps.lock.RLock()
  398. defer ps.lock.RUnlock()
  399. return len(ps.peers)
  400. }
  401. // PeersWithoutBlock retrieves a list of peers that do not have a given block in
  402. // their set of known hashes.
  403. func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
  404. ps.lock.RLock()
  405. defer ps.lock.RUnlock()
  406. list := make([]*peer, 0, len(ps.peers))
  407. for _, p := range ps.peers {
  408. if !p.knownBlocks.Has(hash) {
  409. list = append(list, p)
  410. }
  411. }
  412. return list
  413. }
  414. // PeersWithoutTx retrieves a list of peers that do not have a given transaction
  415. // in their set of known hashes.
  416. func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
  417. ps.lock.RLock()
  418. defer ps.lock.RUnlock()
  419. list := make([]*peer, 0, len(ps.peers))
  420. for _, p := range ps.peers {
  421. if !p.knownTxs.Has(hash) {
  422. list = append(list, p)
  423. }
  424. }
  425. return list
  426. }
  427. // BestPeer retrieves the known peer with the currently highest total difficulty.
  428. func (ps *peerSet) BestPeer() *peer {
  429. ps.lock.RLock()
  430. defer ps.lock.RUnlock()
  431. var (
  432. bestPeer *peer
  433. bestTd *big.Int
  434. )
  435. for _, p := range ps.peers {
  436. if _, td := p.Head(); bestPeer == nil || td.Cmp(bestTd) > 0 {
  437. bestPeer, bestTd = p, td
  438. }
  439. }
  440. return bestPeer
  441. }
  442. // Close disconnects all peers.
  443. // No new peers can be registered after Close has returned.
  444. func (ps *peerSet) Close() {
  445. ps.lock.Lock()
  446. defer ps.lock.Unlock()
  447. for _, p := range ps.peers {
  448. p.Disconnect(p2p.DiscQuitting)
  449. }
  450. ps.closed = true
  451. }