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