github.com/soomindae/tendermint@v0.0.5-0.20210528140126-84a0c70c8162/light/detector.go (about)

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