peer.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. 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. propTxnOutPacketsMeter.Mark(1)
  109. for _, tx := range txs {
  110. propTxnOutTrafficMeter.Mark(tx.Size().Int64())
  111. p.knownTxs.Add(tx.Hash())
  112. }
  113. return p2p.Send(p.rw, TxMsg, txs)
  114. }
  115. // SendBlockHashes sends a batch of known hashes to the remote peer.
  116. func (p *peer) SendBlockHashes(hashes []common.Hash) error {
  117. reqHashOutPacketsMeter.Mark(1)
  118. reqHashOutTrafficMeter.Mark(int64(32 * len(hashes)))
  119. return p2p.Send(p.rw, BlockHashesMsg, hashes)
  120. }
  121. // SendBlocks sends a batch of blocks to the remote peer.
  122. func (p *peer) SendBlocks(blocks []*types.Block) error {
  123. reqBlockOutPacketsMeter.Mark(1)
  124. for _, block := range blocks {
  125. reqBlockOutTrafficMeter.Mark(block.Size().Int64())
  126. }
  127. return p2p.Send(p.rw, BlocksMsg, blocks)
  128. }
  129. // SendNewBlockHashes announces the availability of a number of blocks through
  130. // a hash notification.
  131. func (p *peer) SendNewBlockHashes(hashes []common.Hash) error {
  132. propHashOutPacketsMeter.Mark(1)
  133. propHashOutTrafficMeter.Mark(int64(32 * len(hashes)))
  134. for _, hash := range hashes {
  135. p.knownBlocks.Add(hash)
  136. }
  137. return p2p.Send(p.rw, NewBlockHashesMsg, hashes)
  138. }
  139. // SendNewBlock propagates an entire block to a remote peer.
  140. func (p *peer) SendNewBlock(block *types.Block) error {
  141. propBlockOutPacketsMeter.Mark(1)
  142. propBlockOutTrafficMeter.Mark(block.Size().Int64())
  143. p.knownBlocks.Add(block.Hash())
  144. return p2p.Send(p.rw, NewBlockMsg, []interface{}{block, block.Td})
  145. }
  146. // RequestHashes fetches a batch of hashes from a peer, starting at from, going
  147. // towards the genesis block.
  148. func (p *peer) RequestHashes(from common.Hash) error {
  149. glog.V(logger.Debug).Infof("Peer [%s] fetching hashes (%d) from %x...\n", p.id, downloader.MaxHashFetch, from[:4])
  150. return p2p.Send(p.rw, GetBlockHashesMsg, getBlockHashesData{from, uint64(downloader.MaxHashFetch)})
  151. }
  152. // RequestHashesFromNumber fetches a batch of hashes from a peer, starting at the
  153. // requested block number, going upwards towards the genesis block.
  154. func (p *peer) RequestHashesFromNumber(from uint64, count int) error {
  155. glog.V(logger.Debug).Infof("Peer [%s] fetching hashes (%d) from #%d...\n", p.id, count, from)
  156. return p2p.Send(p.rw, GetBlockHashesFromNumberMsg, getBlockHashesFromNumberData{from, uint64(count)})
  157. }
  158. // RequestBlocks fetches a batch of blocks corresponding to the specified hashes.
  159. func (p *peer) RequestBlocks(hashes []common.Hash) error {
  160. glog.V(logger.Debug).Infof("[%s] fetching %v blocks\n", p.id, len(hashes))
  161. return p2p.Send(p.rw, GetBlocksMsg, hashes)
  162. }
  163. // Handshake executes the eth protocol handshake, negotiating version number,
  164. // network IDs, difficulties, head and genesis blocks.
  165. func (p *peer) Handshake(td *big.Int, head common.Hash, genesis common.Hash) error {
  166. // Send out own handshake in a new thread
  167. errc := make(chan error, 1)
  168. go func() {
  169. errc <- p2p.Send(p.rw, StatusMsg, &statusData{
  170. ProtocolVersion: uint32(p.version),
  171. NetworkId: uint32(p.network),
  172. TD: td,
  173. CurrentBlock: head,
  174. GenesisBlock: genesis,
  175. })
  176. }()
  177. // In the mean time retrieve the remote status message
  178. msg, err := p.rw.ReadMsg()
  179. if err != nil {
  180. return err
  181. }
  182. if msg.Code != StatusMsg {
  183. return errResp(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
  184. }
  185. if msg.Size > ProtocolMaxMsgSize {
  186. return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
  187. }
  188. // Decode the handshake and make sure everything matches
  189. var status statusData
  190. if err := msg.Decode(&status); err != nil {
  191. return errResp(ErrDecode, "msg %v: %v", msg, err)
  192. }
  193. if status.GenesisBlock != genesis {
  194. return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesis)
  195. }
  196. if int(status.NetworkId) != p.network {
  197. return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, p.network)
  198. }
  199. if int(status.ProtocolVersion) != p.version {
  200. return errResp(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, p.version)
  201. }
  202. // Configure the remote peer, and sanity check out handshake too
  203. p.td, p.head = status.TD, status.CurrentBlock
  204. return <-errc
  205. }
  206. // String implements fmt.Stringer.
  207. func (p *peer) String() string {
  208. return fmt.Sprintf("Peer %s [%s]", p.id,
  209. fmt.Sprintf("eth/%2d", p.version),
  210. )
  211. }
  212. // peerSet represents the collection of active peers currently participating in
  213. // the Ethereum sub-protocol.
  214. type peerSet struct {
  215. peers map[string]*peer
  216. lock sync.RWMutex
  217. }
  218. // newPeerSet creates a new peer set to track the active participants.
  219. func newPeerSet() *peerSet {
  220. return &peerSet{
  221. peers: make(map[string]*peer),
  222. }
  223. }
  224. // Register injects a new peer into the working set, or returns an error if the
  225. // peer is already known.
  226. func (ps *peerSet) Register(p *peer) error {
  227. ps.lock.Lock()
  228. defer ps.lock.Unlock()
  229. if _, ok := ps.peers[p.id]; ok {
  230. return errAlreadyRegistered
  231. }
  232. ps.peers[p.id] = p
  233. return nil
  234. }
  235. // Unregister removes a remote peer from the active set, disabling any further
  236. // actions to/from that particular entity.
  237. func (ps *peerSet) Unregister(id string) error {
  238. ps.lock.Lock()
  239. defer ps.lock.Unlock()
  240. if _, ok := ps.peers[id]; !ok {
  241. return errNotRegistered
  242. }
  243. delete(ps.peers, id)
  244. return nil
  245. }
  246. // Peer retrieves the registered peer with the given id.
  247. func (ps *peerSet) Peer(id string) *peer {
  248. ps.lock.RLock()
  249. defer ps.lock.RUnlock()
  250. return ps.peers[id]
  251. }
  252. // Len returns if the current number of peers in the set.
  253. func (ps *peerSet) Len() int {
  254. ps.lock.RLock()
  255. defer ps.lock.RUnlock()
  256. return len(ps.peers)
  257. }
  258. // PeersWithoutBlock retrieves a list of peers that do not have a given block in
  259. // their set of known hashes.
  260. func (ps *peerSet) PeersWithoutBlock(hash common.Hash) []*peer {
  261. ps.lock.RLock()
  262. defer ps.lock.RUnlock()
  263. list := make([]*peer, 0, len(ps.peers))
  264. for _, p := range ps.peers {
  265. if !p.knownBlocks.Has(hash) {
  266. list = append(list, p)
  267. }
  268. }
  269. return list
  270. }
  271. // PeersWithoutTx retrieves a list of peers that do not have a given transaction
  272. // in their set of known hashes.
  273. func (ps *peerSet) PeersWithoutTx(hash common.Hash) []*peer {
  274. ps.lock.RLock()
  275. defer ps.lock.RUnlock()
  276. list := make([]*peer, 0, len(ps.peers))
  277. for _, p := range ps.peers {
  278. if !p.knownTxs.Has(hash) {
  279. list = append(list, p)
  280. }
  281. }
  282. return list
  283. }
  284. // BestPeer retrieves the known peer with the currently highest total difficulty.
  285. func (ps *peerSet) BestPeer() *peer {
  286. ps.lock.RLock()
  287. defer ps.lock.RUnlock()
  288. var (
  289. bestPeer *peer
  290. bestTd *big.Int
  291. )
  292. for _, p := range ps.peers {
  293. if td := p.Td(); bestPeer == nil || td.Cmp(bestTd) > 0 {
  294. bestPeer, bestTd = p, td
  295. }
  296. }
  297. return bestPeer
  298. }