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.

334 lines
12 KiB

  1. package evidence
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "sort"
  7. "time"
  8. "github.com/tendermint/tendermint/light"
  9. "github.com/tendermint/tendermint/types"
  10. )
  11. // verify verifies the evidence fully by checking:
  12. // - It has not already been committed
  13. // - it is sufficiently recent (MaxAge)
  14. // - it is from a key who was a validator at the given height
  15. // - it is internally consistent with state
  16. // - it was properly signed by the alleged equivocator and meets the individual evidence verification requirements
  17. //
  18. // NOTE: Evidence may be provided that we do not have the block or validator
  19. // set for. In these cases, we do not return a ErrInvalidEvidence as not to have
  20. // the sending peer disconnect. All other errors are treated as invalid evidence
  21. // (i.e. ErrInvalidEvidence).
  22. func (evpool *Pool) verify(evidence types.Evidence) error {
  23. var (
  24. state = evpool.State()
  25. height = state.LastBlockHeight
  26. evidenceParams = state.ConsensusParams.Evidence
  27. ageNumBlocks = height - evidence.Height()
  28. )
  29. // ensure we have the block for the evidence height
  30. //
  31. // NOTE: It is currently possible for a peer to send us evidence we're not
  32. // able to process because we're too far behind (e.g. syncing), so we DO NOT
  33. // return an invalid evidence error because we do not want the peer to
  34. // disconnect or signal an error in this particular case.
  35. blockMeta := evpool.blockStore.LoadBlockMeta(evidence.Height())
  36. if blockMeta == nil {
  37. return fmt.Errorf("failed to verify evidence; missing block for height %d", evidence.Height())
  38. }
  39. // verify the time of the evidence
  40. evTime := blockMeta.Header.Time
  41. if evidence.Time() != evTime {
  42. return types.NewErrInvalidEvidence(
  43. evidence,
  44. fmt.Errorf(
  45. "evidence has a different time to the block it is associated with (%v != %v)",
  46. evidence.Time(), evTime,
  47. ),
  48. )
  49. }
  50. ageDuration := state.LastBlockTime.Sub(evTime)
  51. // check that the evidence hasn't expired
  52. if ageDuration > evidenceParams.MaxAgeDuration && ageNumBlocks > evidenceParams.MaxAgeNumBlocks {
  53. return types.NewErrInvalidEvidence(
  54. evidence,
  55. fmt.Errorf(
  56. "evidence from height %d (created at: %v) is too old; min height is %d and evidence can not be older than %v",
  57. evidence.Height(),
  58. evTime,
  59. height-evidenceParams.MaxAgeNumBlocks,
  60. state.LastBlockTime.Add(evidenceParams.MaxAgeDuration),
  61. ),
  62. )
  63. }
  64. // apply the evidence-specific verification logic
  65. switch ev := evidence.(type) {
  66. case *types.DuplicateVoteEvidence:
  67. valSet, err := evpool.stateDB.LoadValidators(evidence.Height())
  68. if err != nil {
  69. return err
  70. }
  71. if err := VerifyDuplicateVote(ev, state.ChainID, valSet); err != nil {
  72. return types.NewErrInvalidEvidence(evidence, err)
  73. }
  74. return nil
  75. case *types.LightClientAttackEvidence:
  76. commonHeader, err := getSignedHeader(evpool.blockStore, evidence.Height())
  77. if err != nil {
  78. return err
  79. }
  80. commonVals, err := evpool.stateDB.LoadValidators(evidence.Height())
  81. if err != nil {
  82. return err
  83. }
  84. trustedHeader := commonHeader
  85. // in the case of lunatic the trusted header is different to the common header
  86. if evidence.Height() != ev.ConflictingBlock.Height {
  87. trustedHeader, err = getSignedHeader(evpool.blockStore, ev.ConflictingBlock.Height)
  88. if err != nil {
  89. // FIXME: This multi step process is a bit unergonomic. We may want to consider a more efficient process
  90. // that doesn't require as much io and is atomic.
  91. // If the node doesn't have a block at the height of the conflicting block, then this could be
  92. // a forward lunatic attack. Thus the node must get the latest height it has
  93. latestHeight := evpool.blockStore.Height()
  94. trustedHeader, err = getSignedHeader(evpool.blockStore, latestHeight)
  95. if err != nil {
  96. return err
  97. }
  98. if trustedHeader.Time.Before(ev.ConflictingBlock.Time) {
  99. return fmt.Errorf("latest block time (%v) is before conflicting block time (%v)",
  100. trustedHeader.Time, ev.ConflictingBlock.Time,
  101. )
  102. }
  103. }
  104. }
  105. err = VerifyLightClientAttack(
  106. ev,
  107. commonHeader,
  108. trustedHeader,
  109. commonVals,
  110. state.LastBlockTime,
  111. state.ConsensusParams.Evidence.MaxAgeDuration,
  112. )
  113. if err != nil {
  114. return types.NewErrInvalidEvidence(evidence, err)
  115. }
  116. // Find out what type of attack this was and thus extract the malicious
  117. // validators. Note, in the case of an Amnesia attack we don't have any
  118. // malicious validators.
  119. validators := ev.GetByzantineValidators(commonVals, trustedHeader)
  120. // Ensure this matches the validators that are listed in the evidence. They
  121. // should be ordered based on power.
  122. if validators == nil && ev.ByzantineValidators != nil {
  123. return types.NewErrInvalidEvidence(
  124. evidence,
  125. fmt.Errorf(
  126. "expected nil validators from an amnesia light client attack but got %d",
  127. len(ev.ByzantineValidators),
  128. ),
  129. )
  130. }
  131. if exp, got := len(validators), len(ev.ByzantineValidators); exp != got {
  132. return types.NewErrInvalidEvidence(
  133. evidence,
  134. fmt.Errorf("expected %d byzantine validators from evidence but got %d", exp, got),
  135. )
  136. }
  137. // ensure that both validator arrays are in the same order
  138. sort.Sort(types.ValidatorsByVotingPower(ev.ByzantineValidators))
  139. for idx, val := range validators {
  140. if !bytes.Equal(ev.ByzantineValidators[idx].Address, val.Address) {
  141. return types.NewErrInvalidEvidence(
  142. evidence,
  143. fmt.Errorf(
  144. "evidence contained an unexpected byzantine validator address; expected: %v, got: %v",
  145. val.Address, ev.ByzantineValidators[idx].Address,
  146. ),
  147. )
  148. }
  149. if ev.ByzantineValidators[idx].VotingPower != val.VotingPower {
  150. return types.NewErrInvalidEvidence(
  151. evidence,
  152. fmt.Errorf(
  153. "evidence contained unexpected byzantine validator power; expected %d, got %d",
  154. val.VotingPower, ev.ByzantineValidators[idx].VotingPower,
  155. ),
  156. )
  157. }
  158. }
  159. return nil
  160. default:
  161. return types.NewErrInvalidEvidence(evidence, fmt.Errorf("unrecognized evidence type: %T", evidence))
  162. }
  163. }
  164. // VerifyLightClientAttack verifies LightClientAttackEvidence against the state of the full node. This involves
  165. // the following checks:
  166. // - the common header from the full node has at least 1/3 voting power which is also present in
  167. // the conflicting header's commit
  168. // - 2/3+ of the conflicting validator set correctly signed the conflicting block
  169. // - the nodes trusted header at the same height as the conflicting header has a different hash
  170. //
  171. // CONTRACT: must run ValidateBasic() on the evidence before verifying
  172. // must check that the evidence has not expired (i.e. is outside the maximum age threshold)
  173. func VerifyLightClientAttack(e *types.LightClientAttackEvidence, commonHeader, trustedHeader *types.SignedHeader,
  174. commonVals *types.ValidatorSet, now time.Time, trustPeriod time.Duration) error {
  175. // In the case of lunatic attack there will be a different commonHeader height. Therefore the node perform a single
  176. // verification jump between the common header and the conflicting one
  177. if commonHeader.Height != e.ConflictingBlock.Height {
  178. err := commonVals.VerifyCommitLightTrusting(trustedHeader.ChainID, e.ConflictingBlock.Commit, light.DefaultTrustLevel)
  179. if err != nil {
  180. return fmt.Errorf("skipping verification of conflicting block failed: %w", err)
  181. }
  182. // In the case of equivocation and amnesia we expect all header hashes to be correctly derived
  183. } else if isInvalidHeader(trustedHeader.Header, e.ConflictingBlock.Header) {
  184. return errors.New("common height is the same as conflicting block height so expected the conflicting" +
  185. " block to be correctly derived yet it wasn't")
  186. }
  187. // Verify that the 2/3+ commits from the conflicting validator set were for the conflicting header
  188. if err := e.ConflictingBlock.ValidatorSet.VerifyCommitLight(trustedHeader.ChainID, e.ConflictingBlock.Commit.BlockID,
  189. e.ConflictingBlock.Height, e.ConflictingBlock.Commit); err != nil {
  190. return fmt.Errorf("invalid commit from conflicting block: %w", err)
  191. }
  192. // Assert the correct amount of voting power of the validator set
  193. if evTotal, valsTotal := e.TotalVotingPower, commonVals.TotalVotingPower(); evTotal != valsTotal {
  194. return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)",
  195. evTotal, valsTotal)
  196. }
  197. // check in the case of a forward lunatic attack that monotonically increasing time has been violated
  198. if e.ConflictingBlock.Height > trustedHeader.Height && e.ConflictingBlock.Time.After(trustedHeader.Time) {
  199. return fmt.Errorf("conflicting block doesn't violate monotonically increasing time (%v is after %v)",
  200. e.ConflictingBlock.Time, trustedHeader.Time,
  201. )
  202. // In all other cases check that the hashes of the conflicting header and the trusted header are different
  203. } else if bytes.Equal(trustedHeader.Hash(), e.ConflictingBlock.Hash()) {
  204. return fmt.Errorf("trusted header hash matches the evidence's conflicting header hash: %X",
  205. trustedHeader.Hash())
  206. }
  207. return nil
  208. }
  209. // VerifyDuplicateVote verifies DuplicateVoteEvidence against the state of full node. This involves the
  210. // following checks:
  211. // - the validator is in the validator set at the height of the evidence
  212. // - the height, round, type and validator address of the votes must be the same
  213. // - the block ID's must be different
  214. // - The signatures must both be valid
  215. func VerifyDuplicateVote(e *types.DuplicateVoteEvidence, chainID string, valSet *types.ValidatorSet) error {
  216. _, val := valSet.GetByAddress(e.VoteA.ValidatorAddress)
  217. if val == nil {
  218. return fmt.Errorf("address %X was not a validator at height %d", e.VoteA.ValidatorAddress, e.Height())
  219. }
  220. pubKey := val.PubKey
  221. // H/R/S must be the same
  222. if e.VoteA.Height != e.VoteB.Height ||
  223. e.VoteA.Round != e.VoteB.Round ||
  224. e.VoteA.Type != e.VoteB.Type {
  225. return fmt.Errorf("h/r/s does not match: %d/%d/%v vs %d/%d/%v",
  226. e.VoteA.Height, e.VoteA.Round, e.VoteA.Type,
  227. e.VoteB.Height, e.VoteB.Round, e.VoteB.Type)
  228. }
  229. // Address must be the same
  230. if !bytes.Equal(e.VoteA.ValidatorAddress, e.VoteB.ValidatorAddress) {
  231. return fmt.Errorf("validator addresses do not match: %X vs %X",
  232. e.VoteA.ValidatorAddress,
  233. e.VoteB.ValidatorAddress,
  234. )
  235. }
  236. // BlockIDs must be different
  237. if e.VoteA.BlockID.Equals(e.VoteB.BlockID) {
  238. return fmt.Errorf(
  239. "block IDs are the same (%v) - not a real duplicate vote",
  240. e.VoteA.BlockID,
  241. )
  242. }
  243. // pubkey must match address (this should already be true, sanity check)
  244. addr := e.VoteA.ValidatorAddress
  245. if !bytes.Equal(pubKey.Address(), addr) {
  246. return fmt.Errorf("address (%X) doesn't match pubkey (%v - %X)",
  247. addr, pubKey, pubKey.Address())
  248. }
  249. // validator voting power and total voting power must match
  250. if val.VotingPower != e.ValidatorPower {
  251. return fmt.Errorf("validator power from evidence and our validator set does not match (%d != %d)",
  252. e.ValidatorPower, val.VotingPower)
  253. }
  254. if valSet.TotalVotingPower() != e.TotalVotingPower {
  255. return fmt.Errorf("total voting power from the evidence and our validator set does not match (%d != %d)",
  256. e.TotalVotingPower, valSet.TotalVotingPower())
  257. }
  258. va := e.VoteA.ToProto()
  259. vb := e.VoteB.ToProto()
  260. // Signatures must be valid
  261. if !pubKey.VerifySignature(types.VoteSignBytes(chainID, va), e.VoteA.Signature) {
  262. return fmt.Errorf("verifying VoteA: %w", types.ErrVoteInvalidSignature)
  263. }
  264. if !pubKey.VerifySignature(types.VoteSignBytes(chainID, vb), e.VoteB.Signature) {
  265. return fmt.Errorf("verifying VoteB: %w", types.ErrVoteInvalidSignature)
  266. }
  267. return nil
  268. }
  269. func getSignedHeader(blockStore BlockStore, height int64) (*types.SignedHeader, error) {
  270. blockMeta := blockStore.LoadBlockMeta(height)
  271. if blockMeta == nil {
  272. return nil, fmt.Errorf("don't have header at height #%d", height)
  273. }
  274. commit := blockStore.LoadBlockCommit(height)
  275. if commit == nil {
  276. return nil, fmt.Errorf("don't have commit at height #%d", height)
  277. }
  278. return &types.SignedHeader{
  279. Header: &blockMeta.Header,
  280. Commit: commit,
  281. }, nil
  282. }
  283. // isInvalidHeader takes a trusted header and matches it againt a conflicting header
  284. // to determine whether the conflicting header was the product of a valid state transition
  285. // or not. If it is then all the deterministic fields of the header should be the same.
  286. // If not, it is an invalid header and constitutes a lunatic attack.
  287. func isInvalidHeader(trusted, conflicting *types.Header) bool {
  288. return !bytes.Equal(trusted.ValidatorsHash, conflicting.ValidatorsHash) ||
  289. !bytes.Equal(trusted.NextValidatorsHash, conflicting.NextValidatorsHash) ||
  290. !bytes.Equal(trusted.ConsensusHash, conflicting.ConsensusHash) ||
  291. !bytes.Equal(trusted.AppHash, conflicting.AppHash) ||
  292. !bytes.Equal(trusted.LastResultsHash, conflicting.LastResultsHash)
  293. }