peer.go 13 KB

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