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.

244 lines
10 KiB

  1. package light
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "time"
  8. "github.com/tendermint/tendermint/light/provider"
  9. "github.com/tendermint/tendermint/types"
  10. )
  11. // The detector component of the light client detect and handles attacks on the light client.
  12. // More info here:
  13. // tendermint/docs/architecture/adr-047-handling-evidence-from-light-client.md
  14. // detectDivergence is a second wall of defense for the light client.
  15. //
  16. // It takes the target verified header and compares it with the headers of a set of
  17. // witness providers that the light client is connected to. If a conflicting header
  18. // is returned it verifies and examines the conflicting header against the verified
  19. // trace that was produced from the primary. If successful it produces two sets of evidence
  20. // and sends them to the opposite provider before halting.
  21. //
  22. // If there are no conflictinge headers, the light client deems the verified target header
  23. // trusted and saves it to the trusted store.
  24. func (c *Client) detectDivergence(ctx context.Context, primaryTrace []*types.LightBlock, now time.Time) error {
  25. if primaryTrace == nil || len(primaryTrace) < 2 {
  26. return errors.New("nil or single block primary trace")
  27. }
  28. var (
  29. headerMatched bool
  30. lastVerifiedHeader = primaryTrace[len(primaryTrace)-1].SignedHeader
  31. witnessesToRemove = make([]int, 0)
  32. )
  33. c.logger.Debug("Running detector against trace", "endBlockHeight", lastVerifiedHeader.Height,
  34. "endBlockHash", lastVerifiedHeader.Hash, "length", len(primaryTrace))
  35. c.providerMutex.Lock()
  36. defer c.providerMutex.Unlock()
  37. if len(c.witnesses) == 0 {
  38. return errNoWitnesses{}
  39. }
  40. // launch one goroutine per witness to retrieve the light block of the target height
  41. // and compare it with the header from the primary
  42. errc := make(chan error, len(c.witnesses))
  43. for i, witness := range c.witnesses {
  44. go c.compareNewHeaderWithWitness(ctx, errc, lastVerifiedHeader, witness, i)
  45. }
  46. // handle errors from the header comparisons as they come in
  47. for i := 0; i < cap(errc); i++ {
  48. err := <-errc
  49. switch e := err.(type) {
  50. case nil: // at least one header matched
  51. headerMatched = true
  52. case errConflictingHeaders:
  53. // We have conflicting headers. This could possibly imply an attack on the light client.
  54. // First we need to verify the witness's header using the same skipping verification and then we
  55. // need to find the point that the headers diverge and examine this for any evidence of an attack.
  56. //
  57. // We combine these actions together, verifying the witnesses headers and outputting the trace
  58. // which captures the bifurcation point and if successful provides the information to create
  59. supportingWitness := c.witnesses[e.WitnessIndex]
  60. witnessTrace, primaryBlock, err := c.examineConflictingHeaderAgainstTrace(
  61. ctx,
  62. primaryTrace,
  63. e.Block.SignedHeader,
  64. supportingWitness,
  65. now,
  66. )
  67. if err != nil {
  68. c.logger.Info("Error validating witness's divergent header", "witness", supportingWitness, "err", err)
  69. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  70. continue
  71. }
  72. // We are suspecting that the primary is faulty, hence we hold the witness as the source of truth
  73. // and generate evidence against the primary that we can send to the witness
  74. primaryEv := newLightClientAttackEvidence(primaryBlock, witnessTrace[len(witnessTrace)-1], witnessTrace[0])
  75. c.logger.Error("Attempted attack detected. Sending evidence againt primary by witness", "ev", primaryEv,
  76. "primary", c.primary, "witness", supportingWitness)
  77. c.sendEvidence(ctx, primaryEv, supportingWitness)
  78. // This may not be valid because the witness itself is at fault. So now we reverse it, examining the
  79. // trace provided by the witness and holding the primary as the source of truth. Note: primary may not
  80. // respond but this is okay as we will halt anyway.
  81. primaryTrace, witnessBlock, err := c.examineConflictingHeaderAgainstTrace(
  82. ctx,
  83. witnessTrace,
  84. primaryBlock.SignedHeader,
  85. c.primary,
  86. now,
  87. )
  88. if err != nil {
  89. c.logger.Info("Error validating primary's divergent header", "primary", c.primary, "err", err)
  90. continue
  91. }
  92. // We now use the primary trace to create evidence against the witness and send it to the primary
  93. witnessEv := newLightClientAttackEvidence(witnessBlock, primaryTrace[len(primaryTrace)-1], primaryTrace[0])
  94. c.logger.Error("Sending evidence against witness by primary", "ev", witnessEv,
  95. "primary", c.primary, "witness", supportingWitness)
  96. c.sendEvidence(ctx, witnessEv, c.primary)
  97. // We return the error and don't process anymore witnesses
  98. return e
  99. case errBadWitness:
  100. c.logger.Info("Witness returned an error during header comparison", "witness", c.witnesses[e.WitnessIndex],
  101. "err", err)
  102. // if witness sent us an invalid header, then remove it. If it didn't respond or couldn't find the block, then we
  103. // ignore it and move on to the next witness
  104. if _, ok := e.Reason.(provider.ErrBadLightBlock); ok {
  105. c.logger.Info("Witness sent us invalid header / vals -> removing it", "witness", c.witnesses[e.WitnessIndex])
  106. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  107. }
  108. }
  109. }
  110. for _, idx := range witnessesToRemove {
  111. c.removeWitness(idx)
  112. }
  113. // 1. If we had at least one witness that returned the same header then we
  114. // conclude that we can trust the header
  115. if headerMatched {
  116. return nil
  117. }
  118. // 2. ELse all witnesses have either not responded, don't have the block or sent invalid blocks.
  119. return ErrFailedHeaderCrossReferencing
  120. }
  121. // compareNewHeaderWithWitness takes the verified header from the primary and compares it with a
  122. // header from a specified witness. The function can return one of three errors:
  123. //
  124. // 1: errConflictingHeaders -> there may have been an attack on this light client
  125. // 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one
  126. // Note: In the case of an invalid header we remove the witness
  127. // 3: nil -> the hashes of the two headers match
  128. func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader,
  129. witness provider.Provider, witnessIndex int) {
  130. lightBlock, err := witness.LightBlock(ctx, h.Height)
  131. if err != nil {
  132. errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
  133. return
  134. }
  135. if !bytes.Equal(h.Hash(), lightBlock.Hash()) {
  136. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  137. }
  138. c.logger.Debug("Matching header received by witness", "height", h.Height, "witness", witnessIndex)
  139. errc <- nil
  140. }
  141. // sendEvidence sends evidence to a provider on a best effort basis.
  142. func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) {
  143. err := receiver.ReportEvidence(ctx, ev)
  144. if err != nil {
  145. c.logger.Error("Failed to report evidence to provider", "ev", ev, "provider", receiver)
  146. }
  147. }
  148. // examineConflictingHeaderAgainstTrace takes a trace from one provider and a divergent header that
  149. // it has received from another and preforms verifySkipping at the heights of each of the intermediate
  150. // headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen.
  151. //
  152. // 1. The light client verifies a header that is different to the intermediate header in the trace. This
  153. // is the bifurcation point and the light client can create evidence from it
  154. // 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
  155. // return the error and remove the witness
  156. func (c *Client) examineConflictingHeaderAgainstTrace(
  157. ctx context.Context,
  158. trace []*types.LightBlock,
  159. divergentHeader *types.SignedHeader,
  160. source provider.Provider, now time.Time) ([]*types.LightBlock, *types.LightBlock, error) {
  161. var previouslyVerifiedBlock *types.LightBlock
  162. for idx, traceBlock := range trace {
  163. // The first block in the trace MUST be the same to the light block that the source produces
  164. // else we cannot continue with verification.
  165. sourceBlock, err := source.LightBlock(ctx, traceBlock.Height)
  166. if err != nil {
  167. return nil, nil, err
  168. }
  169. if idx == 0 {
  170. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  171. return nil, nil, fmt.Errorf("trusted block is different to the source's first block (%X = %X)",
  172. thash, shash)
  173. }
  174. previouslyVerifiedBlock = sourceBlock
  175. continue
  176. }
  177. // we check that the source provider can verify a block at the same height of the
  178. // intermediate height
  179. trace, err := c.verifySkipping(ctx, source, previouslyVerifiedBlock, sourceBlock, now)
  180. if err != nil {
  181. return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
  182. }
  183. // check if the headers verified by the source has diverged from the trace
  184. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  185. // Bifurcation point found!
  186. return trace, traceBlock, nil
  187. }
  188. // headers are still the same. update the previouslyVerifiedBlock
  189. previouslyVerifiedBlock = sourceBlock
  190. }
  191. // We have reached the end of the trace without observing a divergence. The last header is thus different
  192. // from the divergent header that the source originally sent us, then we return an error.
  193. return nil, nil, fmt.Errorf("source provided different header to the original header it provided (%X != %X)",
  194. previouslyVerifiedBlock.Hash(), divergentHeader.Hash())
  195. }
  196. // newLightClientAttackEvidence determines the type of attack and then forms the evidence filling out
  197. // all the fields such that it is ready to be sent to a full node.
  198. func newLightClientAttackEvidence(conflicted, trusted, common *types.LightBlock) *types.LightClientAttackEvidence {
  199. ev := &types.LightClientAttackEvidence{ConflictingBlock: conflicted}
  200. // if this is an equivocation or amnesia attack, i.e. the validator sets are the same, then we
  201. // return the height of the conflicting block else if it is a lunatic attack and the validator sets
  202. // are not the same then we send the height of the common header.
  203. if ev.ConflictingHeaderIsInvalid(trusted.Header) {
  204. ev.CommonHeight = common.Height
  205. ev.Timestamp = common.Time
  206. ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower()
  207. } else {
  208. ev.CommonHeight = trusted.Height
  209. ev.Timestamp = trusted.Time
  210. ev.TotalVotingPower = trusted.ValidatorSet.TotalVotingPower()
  211. }
  212. ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader)
  213. return ev
  214. }