peer.go 13 KB

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