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.

248 lines
10 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. // This may not be valid because the witness itself is at fault. So now we reverse it, examining the
  80. // trace provided by the witness and holding the primary as the source of truth. Note: primary may not
  81. // respond but this is okay as we will halt anyway.
  82. primaryTrace, witnessBlock, err := c.examineConflictingHeaderAgainstTrace(
  83. ctx,
  84. witnessTrace,
  85. primaryBlock.SignedHeader,
  86. c.primary,
  87. now,
  88. )
  89. if err != nil {
  90. c.logger.Info("Error validating primary's divergent header", "primary", c.primary, "err", err)
  91. continue
  92. }
  93. // We now use the primary trace to create evidence against the witness and send it to the primary
  94. witnessEv := newLightClientAttackEvidence(witnessBlock, primaryTrace[len(primaryTrace)-1], primaryTrace[0])
  95. c.logger.Error("Sending evidence against witness by primary", "ev", witnessEv,
  96. "primary", c.primary, "witness", supportingWitness)
  97. c.sendEvidence(ctx, witnessEv, c.primary)
  98. // We return the error and don't process anymore witnesses
  99. return e
  100. case errBadWitness:
  101. c.logger.Info("Witness returned an error during header comparison", "witness", c.witnesses[e.WitnessIndex],
  102. "err", err)
  103. // if witness sent us an invalid header, then remove it. If it didn't respond or couldn't find the block, then we
  104. // ignore it and move on to the next witness
  105. if _, ok := e.Reason.(provider.ErrBadLightBlock); ok {
  106. c.logger.Info("Witness sent us invalid header / vals -> removing it", "witness", c.witnesses[e.WitnessIndex])
  107. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  108. }
  109. }
  110. }
  111. // we need to make sure that we remove witnesses by index in the reverse
  112. // order so as to not affect the indexes themselves
  113. sort.Ints(witnessesToRemove)
  114. for i := len(witnessesToRemove) - 1; i >= 0; i-- {
  115. c.removeWitness(witnessesToRemove[i])
  116. }
  117. // 1. If we had at least one witness that returned the same header then we
  118. // conclude that we can trust the header
  119. if headerMatched {
  120. return nil
  121. }
  122. // 2. ELse all witnesses have either not responded, don't have the block or sent invalid blocks.
  123. return ErrFailedHeaderCrossReferencing
  124. }
  125. // compareNewHeaderWithWitness takes the verified header from the primary and compares it with a
  126. // header from a specified witness. The function can return one of three errors:
  127. //
  128. // 1: errConflictingHeaders -> there may have been an attack on this light client
  129. // 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one
  130. // Note: In the case of an invalid header we remove the witness
  131. // 3: nil -> the hashes of the two headers match
  132. func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader,
  133. witness provider.Provider, witnessIndex int) {
  134. lightBlock, err := witness.LightBlock(ctx, h.Height)
  135. if err != nil {
  136. errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
  137. return
  138. }
  139. if !bytes.Equal(h.Hash(), lightBlock.Hash()) {
  140. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  141. }
  142. c.logger.Debug("Matching header received by witness", "height", h.Height, "witness", witnessIndex)
  143. errc <- nil
  144. }
  145. // sendEvidence sends evidence to a provider on a best effort basis.
  146. func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) {
  147. err := receiver.ReportEvidence(ctx, ev)
  148. if err != nil {
  149. c.logger.Error("Failed to report evidence to provider", "ev", ev, "provider", receiver)
  150. }
  151. }
  152. // examineConflictingHeaderAgainstTrace takes a trace from one provider and a divergent header that
  153. // it has received from another and preforms verifySkipping at the heights of each of the intermediate
  154. // headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen.
  155. //
  156. // 1. The light client verifies a header that is different to the intermediate header in the trace. This
  157. // is the bifurcation point and the light client can create evidence from it
  158. // 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
  159. // return the error and remove the witness
  160. func (c *Client) examineConflictingHeaderAgainstTrace(
  161. ctx context.Context,
  162. trace []*types.LightBlock,
  163. divergentHeader *types.SignedHeader,
  164. source provider.Provider, now time.Time) ([]*types.LightBlock, *types.LightBlock, error) {
  165. var previouslyVerifiedBlock *types.LightBlock
  166. for idx, traceBlock := range trace {
  167. // The first block in the trace MUST be the same to the light block that the source produces
  168. // else we cannot continue with verification.
  169. sourceBlock, err := source.LightBlock(ctx, traceBlock.Height)
  170. if err != nil {
  171. return nil, nil, err
  172. }
  173. if idx == 0 {
  174. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  175. return nil, nil, fmt.Errorf("trusted block is different to the source's first block (%X = %X)",
  176. thash, shash)
  177. }
  178. previouslyVerifiedBlock = sourceBlock
  179. continue
  180. }
  181. // we check that the source provider can verify a block at the same height of the
  182. // intermediate height
  183. trace, err := c.verifySkipping(ctx, source, previouslyVerifiedBlock, sourceBlock, now)
  184. if err != nil {
  185. return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
  186. }
  187. // check if the headers verified by the source has diverged from the trace
  188. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  189. // Bifurcation point found!
  190. return trace, traceBlock, nil
  191. }
  192. // headers are still the same. update the previouslyVerifiedBlock
  193. previouslyVerifiedBlock = sourceBlock
  194. }
  195. // We have reached the end of the trace without observing a divergence. The last header is thus different
  196. // from the divergent header that the source originally sent us, then we return an error.
  197. return nil, nil, fmt.Errorf("source provided different header to the original header it provided (%X != %X)",
  198. previouslyVerifiedBlock.Hash(), divergentHeader.Hash())
  199. }
  200. // newLightClientAttackEvidence determines the type of attack and then forms the evidence filling out
  201. // all the fields such that it is ready to be sent to a full node.
  202. func newLightClientAttackEvidence(conflicted, trusted, common *types.LightBlock) *types.LightClientAttackEvidence {
  203. ev := &types.LightClientAttackEvidence{ConflictingBlock: conflicted}
  204. // if this is an equivocation or amnesia attack, i.e. the validator sets are the same, then we
  205. // return the height of the conflicting block else if it is a lunatic attack and the validator sets
  206. // are not the same then we send the height of the common header.
  207. if ev.ConflictingHeaderIsInvalid(trusted.Header) {
  208. ev.CommonHeight = common.Height
  209. ev.Timestamp = common.Time
  210. ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower()
  211. } else {
  212. ev.CommonHeight = trusted.Height
  213. ev.Timestamp = trusted.Time
  214. ev.TotalVotingPower = trusted.ValidatorSet.TotalVotingPower()
  215. }
  216. ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader)
  217. return ev
  218. }