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.

415 lines
17 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 detects 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 valid evidence.
  59. err := c.handleConflictingHeaders(ctx, primaryTrace, e.Block, e.WitnessIndex, now)
  60. if err != nil {
  61. // return information of the attack
  62. return err
  63. }
  64. // if attempt to generate conflicting headers failed then remove witness
  65. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  66. case errBadWitness:
  67. c.logger.Info("witness returned an error during header comparison, removing...",
  68. "witness", c.witnesses[e.WitnessIndex], "err", err)
  69. witnessesToRemove = append(witnessesToRemove, e.WitnessIndex)
  70. default:
  71. if errors.Is(e, context.Canceled) || errors.Is(e, context.DeadlineExceeded) {
  72. return e
  73. }
  74. c.logger.Info("error in light block request to witness", "err", err)
  75. }
  76. }
  77. // remove witnesses that have misbehaved
  78. if err := c.removeWitnesses(witnessesToRemove); err != nil {
  79. return err
  80. }
  81. // 1. If we had at least one witness that returned the same header then we
  82. // conclude that we can trust the header
  83. if headerMatched {
  84. return nil
  85. }
  86. // 2. Else all witnesses have either not responded, don't have the block or sent invalid blocks.
  87. return ErrFailedHeaderCrossReferencing
  88. }
  89. // compareNewHeaderWithWitness takes the verified header from the primary and compares it with a
  90. // header from a specified witness. The function can return one of three errors:
  91. //
  92. // 1: errConflictingHeaders -> there may have been an attack on this light client
  93. // 2: errBadWitness -> the witness has either not responded, doesn't have the header or has given us an invalid one
  94. // Note: In the case of an invalid header we remove the witness
  95. // 3: nil -> the hashes of the two headers match
  96. func (c *Client) compareNewHeaderWithWitness(ctx context.Context, errc chan error, h *types.SignedHeader,
  97. witness provider.Provider, witnessIndex int) {
  98. lightBlock, err := witness.LightBlock(ctx, h.Height)
  99. switch err {
  100. // no error means we move on to checking the hash of the two headers
  101. case nil:
  102. break
  103. // the witness hasn't been helpful in comparing headers, we mark the response and continue
  104. // comparing with the rest of the witnesses
  105. case provider.ErrNoResponse, provider.ErrLightBlockNotFound, context.DeadlineExceeded, context.Canceled:
  106. errc <- err
  107. return
  108. // the witness' head of the blockchain is lower than the height of the primary. This could be one of
  109. // two things:
  110. // 1) The witness is lagging behind
  111. // 2) The primary may be performing a lunatic attack with a height and time in the future
  112. case provider.ErrHeightTooHigh:
  113. // The light client now asks for the latest header that the witness has
  114. var isTargetHeight bool
  115. isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
  116. if err != nil {
  117. errc <- err
  118. return
  119. }
  120. // if the witness caught up and has returned a block of the target height then we can
  121. // break from this switch case and continue to verify the hashes
  122. if isTargetHeight {
  123. break
  124. }
  125. // witness' last header is below the primary's header. We check the times to see if the blocks
  126. // have conflicting times
  127. if !lightBlock.Time.Before(h.Time) {
  128. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  129. return
  130. }
  131. // the witness is behind. We wait for a period WAITING = 2 * DRIFT + LAG.
  132. // This should give the witness ample time if it is a participating member
  133. // of consensus to produce a block that has a time that is after the primary's
  134. // block time. If not the witness is too far behind and the light client removes it
  135. time.Sleep(2*c.maxClockDrift + c.maxBlockLag)
  136. isTargetHeight, lightBlock, err = c.getTargetBlockOrLatest(ctx, h.Height, witness)
  137. if err != nil {
  138. errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
  139. return
  140. }
  141. if isTargetHeight {
  142. break
  143. }
  144. // the witness still doesn't have a block at the height of the primary.
  145. // Check if there is a conflicting time
  146. if !lightBlock.Time.Before(h.Time) {
  147. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  148. return
  149. }
  150. // Following this request response procedure, the witness has been unable to produce a block
  151. // that can somehow conflict with the primary's block. We thus conclude that the witness
  152. // is too far behind and thus we return a no response error.
  153. //
  154. // NOTE: If the clock drift / lag has been miscalibrated it is feasible that the light client has
  155. // drifted too far ahead for any witness to be able provide a comparable block and thus may allow
  156. // for a malicious primary to attack it
  157. errc <- provider.ErrNoResponse
  158. return
  159. default:
  160. // all other errors (i.e. invalid block, closed connection or unreliable provider) we mark the
  161. // witness as bad and remove it
  162. errc <- errBadWitness{Reason: err, WitnessIndex: witnessIndex}
  163. return
  164. }
  165. if !bytes.Equal(h.Header.Hash(), lightBlock.Header.Hash()) {
  166. errc <- errConflictingHeaders{Block: lightBlock, WitnessIndex: witnessIndex}
  167. }
  168. c.logger.Debug("matching header received by witness", "height", h.Height, "witness", witnessIndex)
  169. errc <- nil
  170. }
  171. // sendEvidence sends evidence to a provider on a best effort basis.
  172. func (c *Client) sendEvidence(ctx context.Context, ev *types.LightClientAttackEvidence, receiver provider.Provider) {
  173. err := receiver.ReportEvidence(ctx, ev)
  174. if err != nil {
  175. c.logger.Error("failed to report evidence to provider", "ev", ev, "provider", receiver)
  176. }
  177. }
  178. // handleConflictingHeaders handles the primary style of attack, which is where a primary and witness have
  179. // two headers of the same height but with different hashes
  180. func (c *Client) handleConflictingHeaders(
  181. ctx context.Context,
  182. primaryTrace []*types.LightBlock,
  183. challendingBlock *types.LightBlock,
  184. witnessIndex int,
  185. now time.Time,
  186. ) error {
  187. supportingWitness := c.witnesses[witnessIndex]
  188. witnessTrace, primaryBlock, err := c.examineConflictingHeaderAgainstTrace(
  189. ctx,
  190. primaryTrace,
  191. challendingBlock,
  192. supportingWitness,
  193. now,
  194. )
  195. if err != nil {
  196. c.logger.Info("error validating witness's divergent header", "witness", supportingWitness, "err", err)
  197. return nil
  198. }
  199. // We are suspecting that the primary is faulty, hence we hold the witness as the source of truth
  200. // and generate evidence against the primary that we can send to the witness
  201. commonBlock, trustedBlock := witnessTrace[0], witnessTrace[len(witnessTrace)-1]
  202. evidenceAgainstPrimary := newLightClientAttackEvidence(primaryBlock, trustedBlock, commonBlock)
  203. c.logger.Error("ATTEMPTED ATTACK DETECTED. Sending evidence againt primary by witness", "ev", evidenceAgainstPrimary,
  204. "primary", c.primary, "witness", supportingWitness)
  205. c.sendEvidence(ctx, evidenceAgainstPrimary, supportingWitness)
  206. if primaryBlock.Commit.Round != witnessTrace[len(witnessTrace)-1].Commit.Round {
  207. c.logger.Info("The light client has detected, and prevented, an attempted amnesia attack." +
  208. " We think this attack is pretty unlikely, so if you see it, that's interesting to us." +
  209. " Can you let us know by opening an issue through https://github.com/tendermint/tendermint/issues/new?")
  210. }
  211. // This may not be valid because the witness itself is at fault. So now we reverse it, examining the
  212. // trace provided by the witness and holding the primary as the source of truth. Note: primary may not
  213. // respond but this is okay as we will halt anyway.
  214. primaryTrace, witnessBlock, err := c.examineConflictingHeaderAgainstTrace(
  215. ctx,
  216. witnessTrace,
  217. primaryBlock,
  218. c.primary,
  219. now,
  220. )
  221. if err != nil {
  222. c.logger.Info("Error validating primary's divergent header", "primary", c.primary, "err", err)
  223. return ErrLightClientAttack
  224. }
  225. // We now use the primary trace to create evidence against the witness and send it to the primary
  226. commonBlock, trustedBlock = primaryTrace[0], primaryTrace[len(primaryTrace)-1]
  227. evidenceAgainstWitness := newLightClientAttackEvidence(witnessBlock, trustedBlock, commonBlock)
  228. c.logger.Error("Sending evidence against witness by primary", "ev", evidenceAgainstWitness,
  229. "primary", c.primary, "witness", supportingWitness)
  230. c.sendEvidence(ctx, evidenceAgainstWitness, c.primary)
  231. // We return the error and don't process anymore witnesses
  232. return ErrLightClientAttack
  233. }
  234. // examineConflictingHeaderAgainstTrace takes a trace from one provider and a divergent header that
  235. // it has received from another and preforms verifySkipping at the heights of each of the intermediate
  236. // headers in the trace until it reaches the divergentHeader. 1 of 2 things can happen.
  237. //
  238. // 1. The light client verifies a header that is different to the intermediate header in the trace. This
  239. // is the bifurcation point and the light client can create evidence from it
  240. // 2. The source stops responding, doesn't have the block or sends an invalid header in which case we
  241. // return the error and remove the witness
  242. //
  243. // CONTRACT:
  244. // 1. Trace can not be empty len(trace) > 0
  245. // 2. The last block in the trace can not be of a lower height than the target block
  246. // trace[len(trace)-1].Height >= targetBlock.Height
  247. // 3. The
  248. func (c *Client) examineConflictingHeaderAgainstTrace(
  249. ctx context.Context,
  250. trace []*types.LightBlock,
  251. targetBlock *types.LightBlock,
  252. source provider.Provider, now time.Time,
  253. ) ([]*types.LightBlock, *types.LightBlock, error) {
  254. var (
  255. previouslyVerifiedBlock, sourceBlock *types.LightBlock
  256. sourceTrace []*types.LightBlock
  257. err error
  258. )
  259. if targetBlock.Height < trace[0].Height {
  260. return nil, nil, fmt.Errorf("target block has a height lower than the trusted height (%d < %d)",
  261. targetBlock.Height, trace[0].Height)
  262. }
  263. for idx, traceBlock := range trace {
  264. // this case only happens in a forward lunatic attack. We treat the block with the
  265. // height directly after the targetBlock as the divergent block
  266. if traceBlock.Height > targetBlock.Height {
  267. // sanity check that the time of the traceBlock is indeed less than that of the targetBlock. If the trace
  268. // was correctly verified we should expect monotonically increasing time. This means that if the block at
  269. // the end of the trace has a lesser time than the target block then all blocks in the trace should have a
  270. // lesser time
  271. if traceBlock.Time.After(targetBlock.Time) {
  272. return nil, nil,
  273. errors.New("sanity check failed: expected traceblock to have a lesser time than the target block")
  274. }
  275. // before sending back the divergent block and trace we need to ensure we have verified
  276. // the final gap between the previouslyVerifiedBlock and the targetBlock
  277. if previouslyVerifiedBlock.Height != targetBlock.Height {
  278. sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, targetBlock, now)
  279. if err != nil {
  280. return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
  281. }
  282. }
  283. return sourceTrace, traceBlock, nil
  284. }
  285. // get the corresponding block from the source to verify and match up against the traceBlock
  286. if traceBlock.Height == targetBlock.Height {
  287. sourceBlock = targetBlock
  288. } else {
  289. sourceBlock, err = source.LightBlock(ctx, traceBlock.Height)
  290. if err != nil {
  291. return nil, nil, fmt.Errorf("failed to examine trace: %w", err)
  292. }
  293. }
  294. // The first block in the trace MUST be the same to the light block that the source produces
  295. // else we cannot continue with verification.
  296. if idx == 0 {
  297. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  298. return nil, nil, fmt.Errorf("trusted block is different to the source's first block (%X = %X)",
  299. thash, shash)
  300. }
  301. previouslyVerifiedBlock = sourceBlock
  302. continue
  303. }
  304. // we check that the source provider can verify a block at the same height of the
  305. // intermediate height
  306. sourceTrace, err = c.verifySkipping(ctx, source, previouslyVerifiedBlock, sourceBlock, now)
  307. if err != nil {
  308. return nil, nil, fmt.Errorf("verifySkipping of conflicting header failed: %w", err)
  309. }
  310. // check if the headers verified by the source has diverged from the trace
  311. if shash, thash := sourceBlock.Hash(), traceBlock.Hash(); !bytes.Equal(shash, thash) {
  312. // Bifurcation point found!
  313. return sourceTrace, traceBlock, nil
  314. }
  315. // headers are still the same. update the previouslyVerifiedBlock
  316. previouslyVerifiedBlock = sourceBlock
  317. }
  318. // We have reached the end of the trace. This should never happen. This can only happen if one of the stated
  319. // prerequisites to this function were not met. Namely that either trace[len(trace)-1].Height < targetBlock.Height
  320. // or that trace[i].Hash() != targetBlock.Hash()
  321. return nil, nil, errNoDivergence
  322. }
  323. // getTargetBlockOrLatest gets the latest height, if it is greater than the target height then it queries
  324. // the target heght else it returns the latest. returns true if it successfully managed to acquire the target
  325. // height.
  326. func (c *Client) getTargetBlockOrLatest(
  327. ctx context.Context,
  328. height int64,
  329. witness provider.Provider,
  330. ) (bool, *types.LightBlock, error) {
  331. lightBlock, err := witness.LightBlock(ctx, 0)
  332. if err != nil {
  333. return false, nil, err
  334. }
  335. if lightBlock.Height == height {
  336. // the witness has caught up to the height of the provider's signed header. We
  337. // can resume with checking the hashes.
  338. return true, lightBlock, nil
  339. }
  340. if lightBlock.Height > height {
  341. // the witness has caught up. We recursively call the function again. However in order
  342. // to avoud a wild goose chase where the witness sends us one header below and one header
  343. // above the height we set a timeout to the context
  344. lightBlock, err := witness.LightBlock(ctx, height)
  345. return true, lightBlock, err
  346. }
  347. return false, lightBlock, nil
  348. }
  349. // newLightClientAttackEvidence determines the type of attack and then forms the evidence filling out
  350. // all the fields such that it is ready to be sent to a full node.
  351. func newLightClientAttackEvidence(conflicted, trusted, common *types.LightBlock) *types.LightClientAttackEvidence {
  352. ev := &types.LightClientAttackEvidence{ConflictingBlock: conflicted}
  353. // We use the common height to indicate the form of the attack.
  354. // if this is an equivocation or amnesia attack, i.e. the validator sets are the same, then we
  355. // return the height of the conflicting block as the common height. If instead it is a lunatic
  356. // attack and the validator sets are not the same then we send the height of the common header.
  357. if ev.ConflictingHeaderIsInvalid(trusted.Header) {
  358. ev.CommonHeight = common.Height
  359. ev.Timestamp = common.Time
  360. ev.TotalVotingPower = common.ValidatorSet.TotalVotingPower()
  361. } else {
  362. ev.CommonHeight = trusted.Height
  363. ev.Timestamp = trusted.Time
  364. ev.TotalVotingPower = trusted.ValidatorSet.TotalVotingPower()
  365. }
  366. ev.ByzantineValidators = ev.GetByzantineValidators(common.ValidatorSet, trusted.SignedHeader)
  367. return ev
  368. }