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.

254 lines
11 KiB

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