peer.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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/log"
  26. "github.com/ethereum/go-ethereum/p2p"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. "gopkg.in/fatih/set.v0"
  29. )
  30. var (
  31. errClosed = errors.New("peer set is closed")
  32. errAlreadyRegistered = errors.New("peer is already registered")
  33. errNotRegistered = errors.New("peer is not registered")
  34. )
  35. const (
  36. maxKnownTxs = 32768 // Maximum transactions hashes to keep in the known list (prevent DOS)
  37. maxKnownBlocks = 1024 // Maximum block hashes to keep in the known list (prevent DOS)
  38. handshakeTimeout = 5 * time.Second
  39. )
  40. // PeerInfo represents a short summary of the Ethereum sub-protocol metadata known
  41. // about a connected peer.
  42. type PeerInfo struct {
  43. Version int `json:"version"` // Ethereum protocol version negotiated
  44. Difficulty *big.Int `json:"difficulty"` // Total difficulty of the peer's blockchain
  45. Head string `json:"head"` // SHA3 hash of the peer's best owned block
  46. }
  47. type peer struct {
  48. id string
  49. *p2p.Peer
  50. rw p2p.MsgReadWriter
  51. version int // Protocol version negotiated
  52. forkDrop *time.Timer // Timed connection dropper if forks aren't validated in time
  53. head common.Hash
  54. td *big.Int
  55. lock sync.RWMutex
  56. knownTxs *set.Set // Set of transaction hashes known to be known by this peer
  57. knownBlocks *set.Set // Set of block hashes known to be known by this peer
  58. }
  59. func newPeer(version int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  60. id := p.ID()
  61. return &peer{
  62. Peer: p,
  63. rw: rw,
  64. version: version,
  65. id: fmt.Sprintf("%x", id[:8]),
  66. knownTxs: set.New(),
  67. knownBlocks: set.New(),
  68. }
  69. }
  70. // Info gathers and returns a collection of metadata known about a peer.
  71. func (p *peer) Info() *PeerInfo {
  72. hash, td := p.Head()
  73. return &PeerInfo{
  74. Version: p.version,
  75. Difficulty: td,
  76. Head: hash.Hex(),
  77. }
  78. }
  79. // Head retrieves a copy of the current head hash and total difficulty of the
  80. // peer.
  81. func (p *peer) Head() (hash common.Hash, td *big.Int) {
  82. p.lock.RLock()
  83. defer p.lock.RUnlock()
  84. copy(hash[:], p.head[:])
  85. return hash, new(big.Int).Set(p.td)
  86. }
  87. // SetHead updates the head hash and total difficulty of the peer.
  88. func (p *peer) SetHead(hash common.Hash, td *big.Int) {
  89. p.lock.Lock()
  90. defer p.lock.Unlock()
  91. copy(p.head[:], hash[:])
  92. p.td.Set(td)
  93. }
  94. // MarkBlock marks a block as known for the peer, ensuring that the block will
  95. // never be propagated to this particular peer.
  96. func (p *peer) MarkBlock(hash common.Hash) {
  97. // If we reached the memory allowance, drop a previously known block hash
  98. for p.knownBlocks.Size() >= maxKnownBlocks {
  99. p.knownBlocks.Pop()
  100. }
  101. p.knownBlocks.Add(hash)
  102. }
  103. // MarkTransaction marks a transaction as known for the peer, ensuring that it
  104. // will never be propagated to this particular peer.
  105. func (p *peer) MarkTransaction(hash common.Hash) {
  106. // If we reached the memory allowance, drop a previously known transaction hash
  107. for p.knownTxs.Size() >= maxKnownTxs {
  108. p.knownTxs.Pop()
  109. }
  110. p.knownTxs.Add(hash)
  111. }
  112. // SendTransactions sends transactions to the peer and includes the hashes
  113. // in its transaction hash set for future reference.
  114. func (p *peer) SendTransactions(txs types.Transactions) error {
  115. for _, tx := range txs {
  116. p.knownTxs.Add(tx.Hash())
  117. }
  118. return p2p.Send(p.rw, TxMsg, txs)
  119. }
  120. // SendNewBlockHashes announces the availability of a number of blocks through
  121. // a hash notification.
  122. func (p *peer) SendNewBlockHashes(hashes []common.Hash, numbers []uint64) error {
  123. for _, hash := range hashes {
  124. p.knownBlocks.Add(hash)
  125. }
  126. request := make(newBlockHashesData, len(hashes))
  127. for i := 0; i < len(hashes); i++ {
  128. request[i].Hash = hashes[i]
  129. request[i].Number = numbers[i]
  130. }
  131. return p2p.Send(p.rw, NewBlockHashesMsg, request)
  132. }
  133. // SendNewBlock propagates an entire block to a remote peer.
  134. func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
  135. p.knownBlocks.Add(block.Hash())
  136. return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
  137. }
  138. // SendBlockHeaders sends a batch of block headers to the remote peer.
  139. func (p *peer) SendBlockHeaders(headers []*types.Header) error {
  140. return p2p.Send(p.rw, BlockHeadersMsg, headers)
  141. }
  142. // SendBlockBodies sends a batch of block contents to the remote peer.
  143. func (p *peer) SendBlockBodies(bodies []*blockBody) error {
  144. return p2p.Send(p.rw, BlockBodiesMsg, blockBodiesData(bodies))
  145. }
  146. // SendBlockBodiesRLP sends a batch of block contents to the remote peer from
  147. // an already RLP encoded format.
  148. func (p *peer) SendBlockBodiesRLP(bodies []rlp.RawValue) error {
  149. return p2p.Send(p.rw, BlockBodiesMsg, bodies)
  150. }
  151. // SendNodeDataRLP sends a batch of arbitrary internal data, corresponding to the
  152. // hashes requested.
  153. func (p *peer) SendNodeData(data [][]byte) error {
  154. return p2p.Send(p.rw, NodeDataMsg, data)
  155. }
  156. // SendReceiptsRLP sends a batch of transaction receipts, corresponding to the
  157. // ones requested from an already RLP encoded format.
  158. func (p *peer) SendReceiptsRLP(receipts []rlp.RawValue) error {
  159. return p2p.Send(p.rw, ReceiptsMsg, receipts)
  160. }
  161. // RequestHeaders is a wrapper around the header query functions to fetch a
  162. // single header. It is used solely by the fetcher.
  163. func (p *peer) RequestOneHeader(hash common.Hash) error {
  164. log.Debug(fmt.Sprintf("%v fetching a single header: %x", p, hash))
  165. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: hash}, Amount: uint64(1), Skip: uint64(0), Reverse: false})
  166. }
  167. // RequestHeadersByHash fetches a batch of blocks' headers corresponding to the
  168. // specified header query, based on the hash of an origin block.
  169. func (p *peer) RequestHeadersByHash(origin common.Hash, amount int, skip int, reverse bool) error {
  170. log.Debug(fmt.Sprintf("%v fetching %d headers from %x, skipping %d (reverse = %v)", p, amount, origin[:4], skip, reverse))
  171. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Hash: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
  172. }
  173. // RequestHeadersByNumber fetches a batch of blocks' headers corresponding to the
  174. // specified header query, based on the number of an origin block.
  175. func (p *peer) RequestHeadersByNumber(origin uint64, amount int, skip int, reverse bool) error {
  176. log.Debug(fmt.Sprintf("%v fetching %d headers from #%d, skipping %d (reverse = %v)", p, amount, origin, skip, reverse))
  177. return p2p.Send(p.rw, GetBlockHeadersMsg, &getBlockHeadersData{Origin: hashOrNumber{Number: origin}, Amount: uint64(amount), Skip: uint64(skip), Reverse: reverse})
  178. }
  179. // RequestBodies fetches a batch of blocks' bodies corresponding to the hashes
  180. // specified.
  181. func (p *peer) RequestBodies(hashes []common.Hash) error {
  182. log.Debug(fmt.Sprintf("%v fetching %d block bodies", p, len(hashes)))
  183. return p2p.Send(p.rw, GetBlockBodiesMsg, hashes)
  184. }
  185. // RequestNodeData fetches a batch of arbitrary data from a node's known state
  186. // data, corresponding to the specified hashes.
  187. func (p *peer) RequestNodeData(hashes []common.Hash) error {
  188. log.Debug(fmt.Sprintf("%v fetching %v state data", p, len(hashes)))
  189. return p2p.Send(p.rw, GetNodeDataMsg, hashes)
  190. }
  191. // RequestReceipts fetches a batch of transaction receipts from a remote node.
  192. func (p *peer) RequestReceipts(hashes []common.Hash) error {
  193. log.Debug(fmt.Sprintf("%v fetching %v receipts", p, len(hashes)))
  194. return p2p.Send(p.rw, GetReceiptsMsg, hashes)
  195. }
  196. // Handshake executes the eth protocol handshake, negotiating version number,
  197. // network IDs, difficulties, head and genesis blocks.
  198. func (p *peer) Handshake(network int, td *big.Int, head common.Hash, genesis common.Hash) error {
  199. // Send out own handshake in a new thread
  200. errc := make(chan error, 2)
  201. var status statusData // safe to read after two values have been received from errc
  202. go func() {
  203. errc <- p2p.Send(p.rw, StatusMsg, &statusData{
  204. ProtocolVersion: uint32(p.version),
  205. NetworkId: uint32(network),
  206. TD: td,
  207. CurrentBlock: head,
  208. GenesisBlock: genesis,
  209. })
  210. }()
  211. go func() {
  212. errc <- p.readStatus(network, &status, genesis)
  213. }()
  214. timeout := time.NewTimer(handshakeTimeout)
  215. defer timeout.Stop()
  216. for i := 0; i < 2; i++ {
  217. select {
  218. case err := <-errc:
  219. if err != nil {
  220. return err
  221. }
  222. case <-timeout.C:
  223. return p2p.DiscReadTimeout
  224. }
  225. }
  226. p.td, p.head = status.TD, status.CurrentBlock
  227. return nil
  228. }
  229. func (p *peer) readStatus(network int, status *statusData, genesis common.Hash) (err error) {
  230. msg, err := p.rw.ReadMsg()
  231. if err != nil {
  232. return err
  233. }
  234. if msg.Code != StatusMsg {
  235. return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  236. }
  237. if msg.Size > ProtocolMaxMsgSize {
  238. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  239. }
  240. // Decode the handshake and make sure everything matches
  241. if err := msg.Decode(&status); err != nil {
  242. return errResp(ErrDecode, "msg %v: %v", msg, err)
  243. }
  244. if status.GenesisBlock != genesis {
  245. return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock[:8], genesis[:8])
  246. }
  247. if int(status.NetworkId) != network {
  248. return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, network)
  249. }
  250. if int(status.ProtocolVersion) != p.version {
  251. return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
  252. }
  253. return nil
  254. }
  255. // String implements fmt.Stringer.
  256. func (p *peer) String() string {
  257. return fmt.Sprintf("Peer %s [%s]", p.id,
  258. fmt.Sprintf("eth/%2d", p.version),
  259. )
  260. }
  261. // peerSet represents the collection of active peers currently participating in
  262. // the Ethereum sub-protocol.
  263. type peerSet struct {
  264. peers map[string]*peer
  265. lock sync.RWMutex
  266. closed bool
  267. }
  268. // newPeerSet creates a new peer set to track the active participants.
  269. func newPeerSet() *peerSet {
  270. return &peerSet{
  271. peers: make(map[string]*peer),
  272. }
  273. }
  274. // Register injects a new peer into the working set, or returns an error if the
  275. // peer is already known.
  276. func (ps *peerSet) Register(p *peer) error {
  277. ps.lock.Lock()
  278. defer ps.lock.Unlock()
  279. if ps.closed {
  280. return errClosed
  281. }
  282. if _, ok := ps.peers[p.id]; ok {
  283. return errAlreadyRegistered
  284. }
  285. ps.peers[p.id] = p
  286. return nil
  287. }
  288. // Unregister removes a remote peer from the active set, disabling any further
  289. // actions to/from that particular entity.
  290. func (ps *peerSet) Unregister(id string) error {
  291. ps.lock.Lock()
  292. defer ps.lock.Unlock()
  293. if _, ok := ps.peers[id]; !ok {
  294. return errNotRegistered
  295. }
  296. delete(ps.peers, id)
  297. return nil
  298. }
  299. // Peer retrieves the registered peer with the given id.
  300. func (ps *peerSet) Peer(id string) *peer {
  301. ps.lock.RLock()
  302. defer ps.lock.RUnlock()
  303. return ps.peers[id]
  304. }
  305. // Len returns if the current number of peers in the set.
  306. func (ps *peerSet) Len() int {
  307. ps.lock.RLock()
  308. defer ps.lock.RUnlock()
  309. return len(ps.peers)
  310. }
  311. // PeersWithoutBlock retrieves a list of peers that do not have a given block in
  312. // their set of known hashes.
  313. func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
  314. ps.lock.RLock()
  315. defer ps.lock.RUnlock()
  316. list := make([]*peer, 0, len(ps.peers))
  317. for _, p := range ps.peers {
  318. if !p.knownBlocks.Has(hash) {
  319. list = append(list, p)
  320. }
  321. }
  322. return list
  323. }
  324. // PeersWithoutTx retrieves a list of peers that do not have a given transaction
  325. // in their set of known hashes.
  326. func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
  327. ps.lock.RLock()
  328. defer ps.lock.RUnlock()
  329. list := make([]*peer, 0, len(ps.peers))
  330. for _, p := range ps.peers {
  331. if !p.knownTxs.Has(hash) {
  332. list = append(list, p)
  333. }
  334. }
  335. return list
  336. }
  337. // BestPeer retrieves the known peer with the currently highest total difficulty.
  338. func (ps *peerSet) BestPeer() *peer {
  339. ps.lock.RLock()
  340. defer ps.lock.RUnlock()
  341. var (
  342. bestPeer *peer
  343. bestTd *big.Int
  344. )
  345. for _, p := range ps.peers {
  346. if _, td := p.Head(); bestPeer == nil || td.Cmp(bestTd) > 0 {
  347. bestPeer, bestTd = p, td
  348. }
  349. }
  350. return bestPeer
  351. }
  352. // Close disconnects all peers.
  353. // No new peers can be registered after Close has returned.
  354. func (ps *peerSet) Close() {
  355. ps.lock.Lock()
  356. defer ps.lock.Unlock()
  357. for _, p := range ps.peers {
  358. p.Disconnect(p2p.DiscQuitting)
  359. }
  360. ps.closed = true
  361. }