You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
11 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package evidence
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime/debug"
  6. "sync"
  7. "time"
  8. clist "github.com/tendermint/tendermint/internal/libs/clist"
  9. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  10. "github.com/tendermint/tendermint/internal/p2p"
  11. "github.com/tendermint/tendermint/libs/log"
  12. "github.com/tendermint/tendermint/libs/service"
  13. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  14. "github.com/tendermint/tendermint/types"
  15. )
  16. var _ service.Service = (*Reactor)(nil)
  17. const (
  18. EvidenceChannel = p2p.ChannelID(0x38)
  19. maxMsgSize = 1048576 // 1MB TODO make it configurable
  20. // broadcast all uncommitted evidence this often. This sets when the reactor
  21. // goes back to the start of the list and begins sending the evidence again.
  22. // Most evidence should be committed in the very next block that is why we wait
  23. // just over the block production rate before sending evidence again.
  24. broadcastEvidenceIntervalS = 10
  25. )
  26. // GetChannelDescriptor produces an instance of a descriptor for this
  27. // package's required channels.
  28. func GetChannelDescriptor() *p2p.ChannelDescriptor {
  29. return &p2p.ChannelDescriptor{
  30. ID: EvidenceChannel,
  31. MessageType: new(tmproto.EvidenceList),
  32. Priority: 6,
  33. RecvMessageCapacity: maxMsgSize,
  34. RecvBufferCapacity: 32,
  35. }
  36. }
  37. // Reactor handles evpool evidence broadcasting amongst peers.
  38. type Reactor struct {
  39. service.BaseService
  40. evpool *Pool
  41. evidenceCh *p2p.Channel
  42. peerUpdates *p2p.PeerUpdates
  43. closeCh chan struct{}
  44. peerWG sync.WaitGroup
  45. mtx tmsync.Mutex
  46. peerRoutines map[types.NodeID]*tmsync.Closer
  47. }
  48. // NewReactor returns a reference to a new evidence reactor, which implements the
  49. // service.Service interface. It accepts a p2p Channel dedicated for handling
  50. // envelopes with EvidenceList messages.
  51. func NewReactor(
  52. logger log.Logger,
  53. evidenceCh *p2p.Channel,
  54. peerUpdates *p2p.PeerUpdates,
  55. evpool *Pool,
  56. ) *Reactor {
  57. r := &Reactor{
  58. evpool: evpool,
  59. evidenceCh: evidenceCh,
  60. peerUpdates: peerUpdates,
  61. closeCh: make(chan struct{}),
  62. peerRoutines: make(map[types.NodeID]*tmsync.Closer),
  63. }
  64. r.BaseService = *service.NewBaseService(logger, "Evidence", r)
  65. return r
  66. }
  67. // OnStart starts separate go routines for each p2p Channel and listens for
  68. // envelopes on each. In addition, it also listens for peer updates and handles
  69. // messages on that p2p channel accordingly. The caller must be sure to execute
  70. // OnStop to ensure the outbound p2p Channels are closed. No error is returned.
  71. func (r *Reactor) OnStart(ctx context.Context) error {
  72. go r.processEvidenceCh()
  73. go r.processPeerUpdates()
  74. return nil
  75. }
  76. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  77. // blocking until they all exit.
  78. func (r *Reactor) OnStop() {
  79. r.mtx.Lock()
  80. for _, c := range r.peerRoutines {
  81. c.Close()
  82. }
  83. r.mtx.Unlock()
  84. // Wait for all spawned peer evidence broadcasting goroutines to gracefully
  85. // exit.
  86. r.peerWG.Wait()
  87. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  88. // p2p Channels should execute Close().
  89. close(r.closeCh)
  90. // Wait for all p2p Channels to be closed before returning. This ensures we
  91. // can easily reason about synchronization of all p2p Channels and ensure no
  92. // panics will occur.
  93. <-r.evidenceCh.Done()
  94. <-r.peerUpdates.Done()
  95. }
  96. // handleEvidenceMessage handles envelopes sent from peers on the EvidenceChannel.
  97. // It returns an error only if the Envelope.Message is unknown for this channel
  98. // or if the given evidence is invalid. This should never be called outside of
  99. // handleMessage.
  100. func (r *Reactor) handleEvidenceMessage(envelope p2p.Envelope) error {
  101. logger := r.Logger.With("peer", envelope.From)
  102. switch msg := envelope.Message.(type) {
  103. case *tmproto.EvidenceList:
  104. // TODO: Refactor the Evidence type to not contain a list since we only ever
  105. // send and receive one piece of evidence at a time. Or potentially consider
  106. // batching evidence.
  107. //
  108. // see: https://github.com/tendermint/tendermint/issues/4729
  109. for i := 0; i < len(msg.Evidence); i++ {
  110. ev, err := types.EvidenceFromProto(&msg.Evidence[i])
  111. if err != nil {
  112. logger.Error("failed to convert evidence", "err", err)
  113. continue
  114. }
  115. if err := r.evpool.AddEvidence(ev); err != nil {
  116. // If we're given invalid evidence by the peer, notify the router that
  117. // we should remove this peer by returning an error.
  118. if _, ok := err.(*types.ErrInvalidEvidence); ok {
  119. return err
  120. }
  121. }
  122. }
  123. default:
  124. return fmt.Errorf("received unknown message: %T", msg)
  125. }
  126. return nil
  127. }
  128. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  129. // It will handle errors and any possible panics gracefully. A caller can handle
  130. // any error returned by sending a PeerError on the respective channel.
  131. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  132. defer func() {
  133. if e := recover(); e != nil {
  134. err = fmt.Errorf("panic in processing message: %v", e)
  135. r.Logger.Error(
  136. "recovering from processing message panic",
  137. "err", err,
  138. "stack", string(debug.Stack()),
  139. )
  140. }
  141. }()
  142. r.Logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  143. switch chID {
  144. case EvidenceChannel:
  145. err = r.handleEvidenceMessage(envelope)
  146. default:
  147. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  148. }
  149. return err
  150. }
  151. // processEvidenceCh implements a blocking event loop where we listen for p2p
  152. // Envelope messages from the evidenceCh.
  153. func (r *Reactor) processEvidenceCh() {
  154. defer r.evidenceCh.Close()
  155. for {
  156. select {
  157. case envelope := <-r.evidenceCh.In:
  158. if err := r.handleMessage(r.evidenceCh.ID, envelope); err != nil {
  159. r.Logger.Error("failed to process message", "ch_id", r.evidenceCh.ID, "envelope", envelope, "err", err)
  160. r.evidenceCh.Error <- p2p.PeerError{
  161. NodeID: envelope.From,
  162. Err: err,
  163. }
  164. }
  165. case <-r.closeCh:
  166. r.Logger.Debug("stopped listening on evidence channel; closing...")
  167. return
  168. }
  169. }
  170. }
  171. // processPeerUpdate processes a PeerUpdate. For new or live peers it will check
  172. // if an evidence broadcasting goroutine needs to be started. For down or
  173. // removed peers, it will check if an evidence broadcasting goroutine
  174. // exists and signal that it should exit.
  175. //
  176. // FIXME: The peer may be behind in which case it would simply ignore the
  177. // evidence and treat it as invalid. This would cause the peer to disconnect.
  178. // The peer may also receive the same piece of evidence multiple times if it
  179. // connects/disconnects frequently from the broadcasting peer(s).
  180. //
  181. // REF: https://github.com/tendermint/tendermint/issues/4727
  182. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  183. r.Logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  184. r.mtx.Lock()
  185. defer r.mtx.Unlock()
  186. switch peerUpdate.Status {
  187. case p2p.PeerStatusUp:
  188. // Do not allow starting new evidence broadcast loops after reactor shutdown
  189. // has been initiated. This can happen after we've manually closed all
  190. // peer broadcast loops and closed r.closeCh, but the router still sends
  191. // in-flight peer updates.
  192. if !r.IsRunning() {
  193. return
  194. }
  195. // Check if we've already started a goroutine for this peer, if not we create
  196. // a new done channel so we can explicitly close the goroutine if the peer
  197. // is later removed, we increment the waitgroup so the reactor can stop
  198. // safely, and finally start the goroutine to broadcast evidence to that peer.
  199. _, ok := r.peerRoutines[peerUpdate.NodeID]
  200. if !ok {
  201. closer := tmsync.NewCloser()
  202. r.peerRoutines[peerUpdate.NodeID] = closer
  203. r.peerWG.Add(1)
  204. go r.broadcastEvidenceLoop(peerUpdate.NodeID, closer)
  205. }
  206. case p2p.PeerStatusDown:
  207. // Check if we've started an evidence broadcasting goroutine for this peer.
  208. // If we have, we signal to terminate the goroutine via the channel's closure.
  209. // This will internally decrement the peer waitgroup and remove the peer
  210. // from the map of peer evidence broadcasting goroutines.
  211. closer, ok := r.peerRoutines[peerUpdate.NodeID]
  212. if ok {
  213. closer.Close()
  214. }
  215. }
  216. }
  217. // processPeerUpdates initiates a blocking process where we listen for and handle
  218. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  219. // close the p2p PeerUpdatesCh gracefully.
  220. func (r *Reactor) processPeerUpdates() {
  221. defer r.peerUpdates.Close()
  222. for {
  223. select {
  224. case peerUpdate := <-r.peerUpdates.Updates():
  225. r.processPeerUpdate(peerUpdate)
  226. case <-r.closeCh:
  227. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  228. return
  229. }
  230. }
  231. }
  232. // broadcastEvidenceLoop starts a blocking process that continuously reads pieces
  233. // of evidence off of a linked-list and sends the evidence in a p2p Envelope to
  234. // the given peer by ID. This should be invoked in a goroutine per unique peer
  235. // ID via an appropriate PeerUpdate. The goroutine can be signaled to gracefully
  236. // exit by either explicitly closing the provided doneCh or by the reactor
  237. // signaling to stop.
  238. //
  239. // TODO: This should be refactored so that we do not blindly gossip evidence
  240. // that the peer has already received or may not be ready for.
  241. //
  242. // REF: https://github.com/tendermint/tendermint/issues/4727
  243. func (r *Reactor) broadcastEvidenceLoop(peerID types.NodeID, closer *tmsync.Closer) {
  244. var next *clist.CElement
  245. defer func() {
  246. r.mtx.Lock()
  247. delete(r.peerRoutines, peerID)
  248. r.mtx.Unlock()
  249. r.peerWG.Done()
  250. if e := recover(); e != nil {
  251. r.Logger.Error(
  252. "recovering from broadcasting evidence loop",
  253. "err", e,
  254. "stack", string(debug.Stack()),
  255. )
  256. }
  257. }()
  258. for {
  259. // This happens because the CElement we were looking at got garbage
  260. // collected (removed). That is, .NextWaitChan() returned nil. So we can go
  261. // ahead and start from the beginning.
  262. if next == nil {
  263. select {
  264. case <-r.evpool.EvidenceWaitChan(): // wait until next evidence is available
  265. if next = r.evpool.EvidenceFront(); next == nil {
  266. continue
  267. }
  268. case <-closer.Done():
  269. // The peer is marked for removal via a PeerUpdate as the doneCh was
  270. // explicitly closed to signal we should exit.
  271. return
  272. case <-r.closeCh:
  273. // The reactor has signaled that we are stopped and thus we should
  274. // implicitly exit this peer's goroutine.
  275. return
  276. }
  277. }
  278. ev := next.Value.(types.Evidence)
  279. evProto, err := types.EvidenceToProto(ev)
  280. if err != nil {
  281. panic(fmt.Errorf("failed to convert evidence: %w", err))
  282. }
  283. // Send the evidence to the corresponding peer. Note, the peer may be behind
  284. // and thus would not be able to process the evidence correctly. Also, the
  285. // peer may receive this piece of evidence multiple times if it added and
  286. // removed frequently from the broadcasting peer.
  287. r.evidenceCh.Out <- p2p.Envelope{
  288. To: peerID,
  289. Message: &tmproto.EvidenceList{
  290. Evidence: []tmproto.Evidence{*evProto},
  291. },
  292. }
  293. r.Logger.Debug("gossiped evidence to peer", "evidence", ev, "peer", peerID)
  294. select {
  295. case <-time.After(time.Second * broadcastEvidenceIntervalS):
  296. // start from the beginning after broadcastEvidenceIntervalS seconds
  297. next = nil
  298. case <-next.NextWaitChan():
  299. next = next.Next()
  300. case <-closer.Done():
  301. // The peer is marked for removal via a PeerUpdate as the doneCh was
  302. // explicitly closed to signal we should exit.
  303. return
  304. case <-r.closeCh:
  305. // The reactor has signaled that we are stopped and thus we should
  306. // implicitly exit this peer's goroutine.
  307. return
  308. }
  309. }
  310. }