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.

343 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.Evidence),
  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. logger log.Logger
  41. evpool *Pool
  42. evidenceCh *p2p.Channel
  43. peerUpdates *p2p.PeerUpdates
  44. peerWG sync.WaitGroup
  45. mtx sync.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. ctx context.Context,
  53. logger log.Logger,
  54. chCreator p2p.ChannelCreator,
  55. peerUpdates *p2p.PeerUpdates,
  56. evpool *Pool,
  57. ) (*Reactor, error) {
  58. evidenceCh, err := chCreator(ctx, GetChannelDescriptor())
  59. if err != nil {
  60. return nil, err
  61. }
  62. r := &Reactor{
  63. logger: logger,
  64. evpool: evpool,
  65. evidenceCh: evidenceCh,
  66. peerUpdates: peerUpdates,
  67. peerRoutines: make(map[types.NodeID]*tmsync.Closer),
  68. }
  69. r.BaseService = *service.NewBaseService(logger, "Evidence", r)
  70. return r, err
  71. }
  72. // OnStart starts separate go routines for each p2p Channel and listens for
  73. // envelopes on each. In addition, it also listens for peer updates and handles
  74. // messages on that p2p channel accordingly. The caller must be sure to execute
  75. // OnStop to ensure the outbound p2p Channels are closed. No error is returned.
  76. func (r *Reactor) OnStart(ctx context.Context) error {
  77. go r.processEvidenceCh(ctx)
  78. go r.processPeerUpdates(ctx)
  79. return nil
  80. }
  81. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  82. // blocking until they all exit.
  83. func (r *Reactor) OnStop() {
  84. r.mtx.Lock()
  85. for _, c := range r.peerRoutines {
  86. c.Close()
  87. }
  88. r.mtx.Unlock()
  89. // Wait for all spawned peer evidence broadcasting goroutines to gracefully
  90. // exit.
  91. r.peerWG.Wait()
  92. // Close the evidence db
  93. r.evpool.Close()
  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.Evidence:
  103. // Process the evidence received from a peer
  104. // Evidence is sent and received one by one
  105. ev, err := types.EvidenceFromProto(msg)
  106. if err != nil {
  107. logger.Error("failed to convert evidence", "err", err)
  108. return err
  109. }
  110. if err := r.evpool.AddEvidence(ev); err != nil {
  111. // If we're given invalid evidence by the peer, notify the router that
  112. // we should remove this peer by returning an error.
  113. if _, ok := err.(*types.ErrInvalidEvidence); ok {
  114. return err
  115. }
  116. }
  117. default:
  118. return fmt.Errorf("received unknown message: %T", msg)
  119. }
  120. return nil
  121. }
  122. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  123. // It will handle errors and any possible panics gracefully. A caller can handle
  124. // any error returned by sending a PeerError on the respective channel.
  125. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope *p2p.Envelope) (err error) {
  126. defer func() {
  127. if e := recover(); e != nil {
  128. err = fmt.Errorf("panic in processing message: %v", e)
  129. r.logger.Error(
  130. "recovering from processing message panic",
  131. "err", err,
  132. "stack", string(debug.Stack()),
  133. )
  134. }
  135. }()
  136. r.logger.Debug("received message", "message", envelope.Message, "peer", envelope.From)
  137. switch chID {
  138. case EvidenceChannel:
  139. err = r.handleEvidenceMessage(envelope)
  140. default:
  141. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  142. }
  143. return err
  144. }
  145. // processEvidenceCh implements a blocking event loop where we listen for p2p
  146. // Envelope messages from the evidenceCh.
  147. func (r *Reactor) processEvidenceCh(ctx context.Context) {
  148. iter := r.evidenceCh.Receive(ctx)
  149. for iter.Next(ctx) {
  150. envelope := iter.Envelope()
  151. if err := r.handleMessage(r.evidenceCh.ID, envelope); err != nil {
  152. r.logger.Error("failed to process message", "ch_id", r.evidenceCh.ID, "envelope", envelope, "err", err)
  153. if serr := r.evidenceCh.SendError(ctx, p2p.PeerError{
  154. NodeID: envelope.From,
  155. Err: err,
  156. }); serr != nil {
  157. return
  158. }
  159. }
  160. }
  161. }
  162. // processPeerUpdate processes a PeerUpdate. For new or live peers it will check
  163. // if an evidence broadcasting goroutine needs to be started. For down or
  164. // removed peers, it will check if an evidence broadcasting goroutine
  165. // exists and signal that it should exit.
  166. //
  167. // FIXME: The peer may be behind in which case it would simply ignore the
  168. // evidence and treat it as invalid. This would cause the peer to disconnect.
  169. // The peer may also receive the same piece of evidence multiple times if it
  170. // connects/disconnects frequently from the broadcasting peer(s).
  171. //
  172. // REF: https://github.com/tendermint/tendermint/issues/4727
  173. func (r *Reactor) processPeerUpdate(ctx context.Context, peerUpdate p2p.PeerUpdate) {
  174. r.logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  175. r.mtx.Lock()
  176. defer r.mtx.Unlock()
  177. switch peerUpdate.Status {
  178. case p2p.PeerStatusUp:
  179. // Do not allow starting new evidence broadcast loops after reactor shutdown
  180. // has been initiated. This can happen after we've manually closed all
  181. // peer broadcast loops, but the router still sends in-flight peer updates.
  182. if !r.IsRunning() {
  183. return
  184. }
  185. // Check if we've already started a goroutine for this peer, if not we create
  186. // a new done channel so we can explicitly close the goroutine if the peer
  187. // is later removed, we increment the waitgroup so the reactor can stop
  188. // safely, and finally start the goroutine to broadcast evidence to that peer.
  189. _, ok := r.peerRoutines[peerUpdate.NodeID]
  190. if !ok {
  191. closer := tmsync.NewCloser()
  192. r.peerRoutines[peerUpdate.NodeID] = closer
  193. r.peerWG.Add(1)
  194. go r.broadcastEvidenceLoop(ctx, peerUpdate.NodeID, closer)
  195. }
  196. case p2p.PeerStatusDown:
  197. // Check if we've started an evidence broadcasting goroutine for this peer.
  198. // If we have, we signal to terminate the goroutine via the channel's closure.
  199. // This will internally decrement the peer waitgroup and remove the peer
  200. // from the map of peer evidence broadcasting goroutines.
  201. closer, ok := r.peerRoutines[peerUpdate.NodeID]
  202. if ok {
  203. closer.Close()
  204. }
  205. }
  206. }
  207. // processPeerUpdates initiates a blocking process where we listen for and handle
  208. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  209. // close the p2p PeerUpdatesCh gracefully.
  210. func (r *Reactor) processPeerUpdates(ctx context.Context) {
  211. for {
  212. select {
  213. case peerUpdate := <-r.peerUpdates.Updates():
  214. r.processPeerUpdate(ctx, peerUpdate)
  215. case <-ctx.Done():
  216. return
  217. }
  218. }
  219. }
  220. // broadcastEvidenceLoop starts a blocking process that continuously reads pieces
  221. // of evidence off of a linked-list and sends the evidence in a p2p Envelope to
  222. // the given peer by ID. This should be invoked in a goroutine per unique peer
  223. // ID via an appropriate PeerUpdate. The goroutine can be signaled to gracefully
  224. // exit by either explicitly closing the provided doneCh or by the reactor
  225. // signaling to stop.
  226. //
  227. // TODO: This should be refactored so that we do not blindly gossip evidence
  228. // that the peer has already received or may not be ready for.
  229. //
  230. // REF: https://github.com/tendermint/tendermint/issues/4727
  231. func (r *Reactor) broadcastEvidenceLoop(ctx context.Context, peerID types.NodeID, closer *tmsync.Closer) {
  232. var next *clist.CElement
  233. defer func() {
  234. r.mtx.Lock()
  235. delete(r.peerRoutines, peerID)
  236. r.mtx.Unlock()
  237. r.peerWG.Done()
  238. if e := recover(); e != nil {
  239. r.logger.Error(
  240. "recovering from broadcasting evidence loop",
  241. "err", e,
  242. "stack", string(debug.Stack()),
  243. )
  244. }
  245. }()
  246. for {
  247. // This happens because the CElement we were looking at got garbage
  248. // collected (removed). That is, .NextWaitChan() returned nil. So we can go
  249. // ahead and start from the beginning.
  250. if next == nil {
  251. select {
  252. case <-r.evpool.EvidenceWaitChan(): // wait until next evidence is available
  253. if next = r.evpool.EvidenceFront(); next == nil {
  254. continue
  255. }
  256. case <-ctx.Done():
  257. return
  258. case <-closer.Done():
  259. // The peer is marked for removal via a PeerUpdate as the doneCh was
  260. // explicitly closed to signal we should exit.
  261. return
  262. }
  263. }
  264. ev := next.Value.(types.Evidence)
  265. evProto, err := types.EvidenceToProto(ev)
  266. if err != nil {
  267. panic(fmt.Errorf("failed to convert evidence: %w", err))
  268. }
  269. // Send the evidence to the corresponding peer. Note, the peer may be behind
  270. // and thus would not be able to process the evidence correctly. Also, the
  271. // peer may receive this piece of evidence multiple times if it added and
  272. // removed frequently from the broadcasting peer.
  273. if err := r.evidenceCh.Send(ctx, p2p.Envelope{
  274. To: peerID,
  275. Message: evProto,
  276. }); err != nil {
  277. return
  278. }
  279. r.logger.Debug("gossiped evidence to peer", "evidence", ev, "peer", peerID)
  280. select {
  281. case <-time.After(time.Second * broadcastEvidenceIntervalS):
  282. // start from the beginning after broadcastEvidenceIntervalS seconds
  283. next = nil
  284. case <-next.NextWaitChan():
  285. next = next.Next()
  286. case <-closer.Done():
  287. // The peer is marked for removal via a PeerUpdate as the doneCh was
  288. // explicitly closed to signal we should exit.
  289. return
  290. case <-ctx.Done():
  291. return
  292. }
  293. }
  294. }