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.

373 lines
12 KiB

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