peer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/core/types"
  24. "github.com/ethereum/go-ethereum/eth/downloader"
  25. "github.com/ethereum/go-ethereum/logger"
  26. "github.com/ethereum/go-ethereum/logger/glog"
  27. "github.com/ethereum/go-ethereum/p2p"
  28. "gopkg.in/fatih/set.v0"
  29. )
  30. var (
  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. )
  38. type peer struct {
  39. *p2p.Peer
  40. rw p2p.MsgReadWriter
  41. version int // Protocol version negotiated
  42. network int // Network ID being on
  43. id string
  44. head common.Hash
  45. td *big.Int
  46. lock sync.RWMutex
  47. knownTxs *set.Set // Set of transaction hashes known to be known by this peer
  48. knownBlocks *set.Set // Set of block hashes known to be known by this peer
  49. }
  50. func newPeer(version, network int, p *p2p.Peer, rw p2p.MsgReadWriter) *peer {
  51. id := p.ID()
  52. return &peer{
  53. Peer: p,
  54. rw: rw,
  55. version: version,
  56. network: network,
  57. id: fmt.Sprintf("%x", id[:8]),
  58. knownTxs: set.New(),
  59. knownBlocks: set.New(),
  60. }
  61. }
  62. // Head retrieves a copy of the current head (most recent) hash of the peer.
  63. func (p *peer) Head() (hash common.Hash) {
  64. p.lock.RLock()
  65. defer p.lock.RUnlock()
  66. copy(hash[:], p.head[:])
  67. return hash
  68. }
  69. // SetHead updates the head (most recent) hash of the peer.
  70. func (p *peer) SetHead(hash common.Hash) {
  71. p.lock.Lock()
  72. defer p.lock.Unlock()
  73. copy(p.head[:], hash[:])
  74. }
  75. // Td retrieves the current total difficulty of a peer.
  76. func (p *peer) Td() *big.Int {
  77. p.lock.RLock()
  78. defer p.lock.RUnlock()
  79. return new(big.Int).Set(p.td)
  80. }
  81. // SetTd updates the current total difficulty of a peer.
  82. func (p *peer) SetTd(td *big.Int) {
  83. p.lock.Lock()
  84. defer p.lock.Unlock()
  85. p.td.Set(td)
  86. }
  87. // MarkBlock marks a block as known for the peer, ensuring that the block will
  88. // never be propagated to this particular peer.
  89. func (p *peer) MarkBlock(hash common.Hash) {
  90. // If we reached the memory allowance, drop a previously known block hash
  91. for p.knownBlocks.Size() >= maxKnownBlocks {
  92. p.knownBlocks.Pop()
  93. }
  94. p.knownBlocks.Add(hash)
  95. }
  96. // MarkTransaction marks a transaction as known for the peer, ensuring that it
  97. // will never be propagated to this particular peer.
  98. func (p *peer) MarkTransaction(hash common.Hash) {
  99. // If we reached the memory allowance, drop a previously known transaction hash
  100. for p.knownTxs.Size() >= maxKnownTxs {
  101. p.knownTxs.Pop()
  102. }
  103. p.knownTxs.Add(hash)
  104. }
  105. // SendTransactions sends transactions to the peer and includes the hashes
  106. // in its transaction hash set for future reference.
  107. func (p *peer) SendTransactions(txs types.Transactions) error {
  108. for _, tx := range txs {
  109. p.knownTxs.Add(tx.Hash())
  110. }
  111. return p2p.Send(p.rw, TxMsg, txs)
  112. }
  113. // SendBlockHashes sends a batch of known hashes to the remote peer.
  114. func (p *peer) SendBlockHashes(hashes []common.Hash) error {
  115. return p2p.Send(p.rw, BlockHashesMsg, hashes)
  116. }
  117. // SendBlocks sends a batch of blocks to the remote peer.
  118. func (p *peer) SendBlocks(blocks []*types.Block) error {
  119. return p2p.Send(p.rw, BlocksMsg, blocks)
  120. }
  121. // SendNewBlockHashes announces the availability of a number of blocks through
  122. // a hash notification.
  123. func (p *peer) SendNewBlockHashes(hashes []common.Hash) error {
  124. for _, hash := range hashes {
  125. p.knownBlocks.Add(hash)
  126. }
  127. return p2p.Send(p.rw, NewBlockHashesMsg, hashes)
  128. }
  129. // SendNewBlock propagates an entire block to a remote peer.
  130. func (p *peer) SendNewBlock(block *types.Block, td *big.Int) error {
  131. p.knownBlocks.Add(block.Hash())
  132. return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, td})
  133. }
  134. // SendBlockHeaders sends a batch of block headers to the remote peer.
  135. func (p *peer) SendBlockHeaders(headers []*types.Header) error {
  136. return p2p.Send(p.rw, BlockHeadersMsg, headers)
  137. }
  138. // SendNodeData sends a batch of arbitrary internal data, corresponding to the
  139. // hashes requested.
  140. func (p *peer) SendNodeData(data [][]byte) error {
  141. return p2p.Send(p.rw, NodeDataMsg, data)
  142. }
  143. // RequestHashes fetches a batch of hashes from a peer, starting at from, going
  144. // towards the genesis block.
  145. func (p *peer) RequestHashes(from common.Hash) error {
  146. glog.V(logger.Debug).Infof("%v fetching hashes (%d) from %x...\n", p, downloader.MaxHashFetch, from[:4])
  147. return p2p.Send(p.rw, GetBlockHashesMsg, getBlockHashesData{from, uint64(downloader.MaxHashFetch)})
  148. }
  149. // RequestHashesFromNumber fetches a batch of hashes from a peer, starting at
  150. // the requested block number, going upwards towards the genesis block.
  151. func (p *peer) RequestHashesFromNumber(from uint64, count int) error {
  152. glog.V(logger.Debug).Infof("%v fetching hashes (%d) from #%d...\n", p, count, from)
  153. return p2p.Send(p.rw, GetBlockHashesFromNumberMsg, getBlockHashesFromNumberData{from, uint64(count)})
  154. }
  155. // RequestBlocks fetches a batch of blocks corresponding to the specified hashes.
  156. func (p *peer) RequestBlocks(hashes []common.Hash) error {
  157. glog.V(logger.Debug).Infof("%v fetching %v blocks\n", p, len(hashes))
  158. return p2p.Send(p.rw, GetBlocksMsg, hashes)
  159. }
  160. // RequestHeaders fetches a batch of blocks' headers corresponding to the
  161. // specified hashes.
  162. func (p *peer) RequestHeaders(hashes []common.Hash) error {
  163. glog.V(logger.Debug).Infof("%v fetching %v headers\n", p, len(hashes))
  164. return p2p.Send(p.rw, GetBlockHeadersMsg, hashes)
  165. }
  166. // RequestNodeData fetches a batch of arbitrary data from a node's known state
  167. // data, corresponding to the specified hashes.
  168. func (p *peer) RequestNodeData(hashes []common.Hash) error {
  169. glog.V(logger.Debug).Infof("%v fetching %v state data\n", p, len(hashes))
  170. return p2p.Send(p.rw, GetNodeDataMsg, hashes)
  171. }
  172. // Handshake executes the eth protocol handshake, negotiating version number,
  173. // network IDs, difficulties, head and genesis blocks.
  174. func (p *peer) Handshake(td *big.Int, head common.Hash, genesis common.Hash) error {
  175. // Send out own handshake in a new thread
  176. errc := make(chan error, 1)
  177. go func() {
  178. errc <- p2p.Send(p.rw, StatusMsg, &statusData{
  179. ProtocolVersion: uint32(p.version),
  180. NetworkId: uint32(p.network),
  181. TD: td,
  182. CurrentBlock: head,
  183. GenesisBlock: genesis,
  184. })
  185. }()
  186. // In the mean time retrieve the remote status message
  187. msg, err := p.rw.ReadMsg()
  188. if err != nil {
  189. return err
  190. }
  191. if msg.Code != StatusMsg {
  192. return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  193. }
  194. if msg.Size > ProtocolMaxMsgSize {
  195. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  196. }
  197. // Decode the handshake and make sure everything matches
  198. var status statusData
  199. if err := msg.Decode(&status); err != nil {
  200. return errResp(ErrDecode, "msg %v: %v", msg, err)
  201. }
  202. if status.GenesisBlock != genesis {
  203. return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesis)
  204. }
  205. if int(status.NetworkId) != p.network {
  206. return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, p.network)
  207. }
  208. if int(status.ProtocolVersion) != p.version {
  209. return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
  210. }
  211. // Configure the remote peer, and sanity check out handshake too
  212. p.td, p.head = status.TD, status.CurrentBlock
  213. return <-errc
  214. }
  215. // String implements fmt.Stringer.
  216. func (p *peer) String() string {
  217. return fmt.Sprintf("Peer %s [%s]", p.id,
  218. fmt.Sprintf("eth/%2d", p.version),
  219. )
  220. }
  221. // peerSet represents the collection of active peers currently participating in
  222. // the Ethereum sub-protocol.
  223. type peerSet struct {
  224. peers map[string]*peer
  225. lock sync.RWMutex
  226. }
  227. // newPeerSet creates a new peer set to track the active participants.
  228. func newPeerSet() *peerSet {
  229. return &peerSet{
  230. peers: make(map[string]*peer),
  231. }
  232. }
  233. // Register injects a new peer into the working set, or returns an error if the
  234. // peer is already known.
  235. func (ps *peerSet) Register(p *peer) error {
  236. ps.lock.Lock()
  237. defer ps.lock.Unlock()
  238. if _, ok := ps.peers[p.id]; ok {
  239. return errAlreadyRegistered
  240. }
  241. ps.peers[p.id] = p
  242. return nil
  243. }
  244. // Unregister removes a remote peer from the active set, disabling any further
  245. // actions to/from that particular entity.
  246. func (ps *peerSet) Unregister(id string) error {
  247. ps.lock.Lock()
  248. defer ps.lock.Unlock()
  249. if _, ok := ps.peers[id]; !ok {
  250. return errNotRegistered
  251. }
  252. delete(ps.peers, id)
  253. return nil
  254. }
  255. // Peer retrieves the registered peer with the given id.
  256. func (ps *peerSet) Peer(id string) *peer {
  257. ps.lock.RLock()
  258. defer ps.lock.RUnlock()
  259. return ps.peers[id]
  260. }
  261. // Len returns if the current number of peers in the set.
  262. func (ps *peerSet) Len() int {
  263. ps.lock.RLock()
  264. defer ps.lock.RUnlock()
  265. return len(ps.peers)
  266. }
  267. // PeersWithoutBlock retrieves a list of peers that do not have a given block in
  268. // their set of known hashes.
  269. func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
  270. ps.lock.RLock()
  271. defer ps.lock.RUnlock()
  272. list := make([]*peer, 0, len(ps.peers))
  273. for _, p := range ps.peers {
  274. if !p.knownBlocks.Has(hash) {
  275. list = append(list, p)
  276. }
  277. }
  278. return list
  279. }
  280. // PeersWithoutTx retrieves a list of peers that do not have a given transaction
  281. // in their set of known hashes.
  282. func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
  283. ps.lock.RLock()
  284. defer ps.lock.RUnlock()
  285. list := make([]*peer, 0, len(ps.peers))
  286. for _, p := range ps.peers {
  287. if !p.knownTxs.Has(hash) {
  288. list = append(list, p)
  289. }
  290. }
  291. return list
  292. }
  293. // BestPeer retrieves the known peer with the currently highest total difficulty.
  294. func (ps *peerSet) BestPeer() *peer {
  295. ps.lock.RLock()
  296. defer ps.lock.RUnlock()
  297. var (
  298. bestPeer *peer
  299. bestTd *big.Int
  300. )
  301. for _, p := range ps.peers {
  302. if td := p.Td(); bestPeer == nil || td.Cmp(bestTd) > 0 {
  303. bestPeer, bestTd = p, td
  304. }
  305. }
  306. return bestPeer
  307. }