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.

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