peer.go 14 KB

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