github.com/DFWallet/tendermint-cosmos@v0.0.2/docs/architecture/adr-059-evidence-composition-and-lifecycle.md (about)

     1  # ADR 059: Evidence Composition and Lifecycle
     2  
     3  ## Changelog
     4  
     5  - 04/09/2020: Initial Draft (Unabridged)
     6  - 07/09/2020: First Version
     7  - 13.03.21: Ammendment to accomodate forward lunatic attack
     8  
     9  ## Scope
    10  
    11  This document is designed to collate together and surface some predicaments involving evidence in Tendermint: both its composition and lifecycle. It then aims to find a solution to these. The scope does not extend to the verification nor detection of certain types of evidence but concerns itself mainly with the general form of evidence and how it moves from inception to application.
    12  
    13  ## Background
    14  
    15  For a long time `DuplicateVoteEvidence`, formed in the consensus reactor, was the only evidence Tendermint had. It was produced whenever two votes from the same validator in the same round
    16  was observed and thus it was designed that each evidence was for a single validator. It was predicted that there may come more forms of evidence and thus `DuplicateVoteEvidence` was used as the model for the `Evidence` interface and also for the form of the evidence data sent to the application. It is important to note that Tendermint concerns itself just with the detection and reporting of evidence and it is the responsibility of the application to exercise punishment.
    17  
    18  ```go
    19  type Evidence interface { //existing
    20    Height() int64                                     // height of the offense
    21    Time() time.Time                                   // time of the offense
    22    Address() []byte                                   // address of the offending validator
    23    Bytes() []byte                                     // bytes which comprise the evidence
    24    Hash() []byte                                      // hash of the evidence
    25    Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
    26    Equal(Evidence) bool                               // check equality of evidence
    27  
    28    ValidateBasic() error
    29    String() string
    30  }
    31  ```
    32  
    33  ```go
    34  type DuplicateVoteEvidence struct {
    35    VoteA *Vote
    36    VoteB *Vote
    37  
    38    timestamp time.Time // taken from the block time
    39  }
    40  ```
    41  
    42  Tendermint has now introduced a new type of evidence to protect light clients from being attacked. This `LightClientAttackEvidence` (see [here](https://github.com/informalsystems/tendermint-rs/blob/31ca3e64ce90786c1734caf186e30595832297a4/docs/spec/lightclient/attacks/evidence-handling.md) for more information) is vastly different to `DuplicateVoteEvidence` in that it is physically a much different size containing a complete signed header and validator set. It is formed within the light client, not the consensus reactor and requires a lot more information from state to verify (`VerifyLightClientAttack(commonHeader, trustedHeader *SignedHeader, commonVals *ValidatorSet)`  vs `VerifyDuplicateVote(chainID string, pubKey PubKey)`). Finally it batches validators together (a single piece of evidence that implicates multiple malicious validators at a height) as opposed to having individual evidence (each piece of evidence is per validator per height). This evidence stretches the existing mould that was used to accommodate new types of evidence and has thus caused us to reconsider how evidence should be formatted and processed.
    43  
    44  ```go
    45  type LightClientAttackEvidence struct { // proposed struct in spec
    46    ConflictingBlock *LightBlock
    47    CommonHeight int64
    48    Type  AttackType     // enum: {Lunatic|Equivocation|Amnesia}
    49  
    50    timestamp time.Time // taken from the block time at the common height
    51  }
    52  ```
    53  *Note: These three attack types have been proven by the research team to be exhaustive*
    54  
    55  ## Possible Approaches for Evidence Composition
    56  
    57  ### Individual framework
    58  
    59  Evidence remains on a per validator basis. This causes the least disruption to the current processes but requires that we break `LightClientAttackEvidence` into several pieces of evidence for each malicious validator. This not only has performance consequences in that there are n times as many database operations and that the gossiping of evidence will require more bandwidth then necessary (by requiring a header for each piece) but it potentially impacts our ability to validate it. In batch form, the full node can run the same process the light client did to see that 1/3 validating power was present in both the common block and the conflicting block whereas this becomes more difficult to verify individually without opening the possibility that malicious validators forge evidence against innocent . Not only that, but `LightClientAttackEvidence` also deals with amnesia attacks which unfortunately have the characteristic where we know the set of validators involved but not the subset that were actually malicious (more to be said about this later). And finally splitting the evidence into individual pieces makes it difficult to understand the severity of the attack (i.e. the total voting power involved in the attack)
    60  
    61  #### An example of a possible implementation path
    62  
    63  We would ignore amnesia evidence (as individually it's hard to make) and revert to the initial split we had before where `DuplicateVoteEvidence` is also used for light client equivocation attacks and thus we only need `LunaticEvidence`. We would also most likely need to remove `Verify` from the interface as this isn't really something that can be used.
    64  
    65  ``` go
    66  type LunaticEvidence struct { // individual lunatic attack
    67    header *Header
    68    commonHeight int64
    69    vote *Vote
    70  
    71    timestamp time.Time // once again taken from the block time at the height of the common header
    72  }
    73  ```
    74  
    75  ### Batch Framework
    76  
    77  The last approach of this category would be to consider batch only evidence. This works fine with `LightClientAttackEvidence` but would require alterations to `DuplicateVoteEvidence` which would most likely mean that the consensus would send conflicting votes to a buffer in the evidence module which would then wrap all the votes together per height before gossiping them to other nodes and trying to commit it on chain. At a glance this may improve IO and verification speed and perhaps more importantly grouping validators gives the application and Tendermint a better overview of the severity of the attack.
    78  
    79  However individual evidence has the advantage that it is easy to check if a node already has that evidence meaning we just need to check hashes to know that we've already verified this evidence before. Batching evidence would imply that each node may have a different combination of duplicate votes which may complicate things.
    80  
    81  #### An example of a possible implementation path
    82  
    83  `LightClientAttackEvidence` won't change but the evidence interface will need to look like the proposed one above and `DuplicateVoteEvidence` will need to change to encompass multiple double votes. A problem with batch evidence is that it needs to be unique to avoid people from submitting different permutations.
    84  
    85  ## Decision
    86  
    87  The decision is to adopt a hybrid design.
    88  
    89  We allow individual and batch evidence to coexist together, meaning that verification is done depending on the evidence type and that  the bulk of the work is done in the evidence pool itself (including forming the evidence to be sent to the application).
    90  
    91  
    92  ## Detailed Design
    93  
    94  Evidence has the following simple interface:
    95  
    96  ```go
    97  type Evidence interface {  //proposed
    98    Height() int64                                     // height of the offense
    99    Bytes() []byte                                     // bytes which comprise the evidence
   100    Hash() []byte                                      // hash of the evidence
   101    ValidateBasic() error
   102    String() string
   103  }
   104  ```
   105  
   106  The changing of the interface is backwards compatible as these methods are all present in the previous version of the interface. However, networks will need to upgrade to be able to process the new evidence as verification has changed.
   107  
   108  We have two concrete types of evidence that fulfil this interface
   109  
   110  ```go
   111  type LightClientAttackEvidence struct {
   112    ConflictingBlock *LightBlock
   113    CommonHeight int64 // the last height at which the primary provider and witness provider had the same header
   114  }
   115  ```
   116  where the `Hash()` is the hash of the header and commonHeight.
   117  
   118  Note: It was also discussed whether to include the commit hash which captures the validators that signed the header. However this would open the opportunity for someone to propose multiple permutations of the same evidence (through different commit signatures) hence it was omitted. Consequentially, when it comes to verifying evidence in a block, for `LightClientAttackEvidence` we can't just check the hashes because someone could have the same hash as us but a different commit where less than 1/3 validators voted which would be an invalid version of the evidence. (see `fastCheck` for more details)
   119  
   120  ```go
   121  type DuplicateVoteEvidence {
   122    VoteA *Vote
   123    VoteB *Vote
   124  }
   125  ```
   126  where the `Hash()` is the hash of the two votes
   127  
   128  For both of these types of evidence, `Bytes()` represents the proto-encoded byte array format of the evidence and `ValidateBasic` is
   129  an initial consistency check to make sure the evidence has a valid structure.
   130  
   131  ### The Evidence Pool
   132  
   133  `LightClientAttackEvidence` is generated in the light client and `DuplicateVoteEvidence` in consensus. Both are sent to the evidence pool through `AddEvidence(ev Evidence) error`. The evidence pool's primary purpose is to verify evidence. It also gossips evidence to other peers' evidence pool and serves it to consensus so it can be committed on chain and the relevant information can be sent to the application in order to exercise punishment. When evidence is added, the pool first runs `Has(ev Evidence)` to check if it has already received it (by comparing hashes) and then  `Verify(ev Evidence) error`.  Once verified the evidence pool stores it it's pending database. There are two databases: one for pending evidence that is not yet committed and another of the committed evidence (to avoid committing evidence twice)
   134  
   135  #### Verification
   136  
   137  `Verify()` does the following:
   138  
   139  - Use the hash to see if we already have this evidence in our committed database.
   140  
   141  - Use the height to check if the evidence hasn't expired.
   142  
   143  - If it has expired then use the height to find the block header and check if the time has also expired in which case we drop the evidence
   144  
   145  - Then proceed with switch statement for each of the two evidence:
   146  
   147  For `DuplicateVote`:
   148  
   149  - Check that height, round, type and validator address are the same
   150  
   151  - Check that the Block ID is different
   152  
   153  - Check the look up table for addresses to make sure there already isn't evidence against this validator
   154  
   155  - Fetch the validator set and confirm that the address is in the set at the height of the attack
   156  
   157  - Check that the chain ID and signature is valid.
   158  
   159  For `LightClientAttack`
   160  
   161  - Fetch the common signed header and val set from the common height and use skipping verification to verify the conflicting header
   162  
   163  - Fetch the trusted signed header at the same height as the conflicting header and compare with the conflicting header to work out which type of attack it is and in doing so return the malicious validators. NOTE: If the node doesn't have the signed header at the height of the conflicting header, it instead fetches the latest header it has and checks to see if it can prove the evidence based on a violation of header time. This is known as forward lunatic attack.
   164  
   165    - If equivocation, return the validators that signed for the commits of both the trusted and signed header
   166  
   167    - If lunatic, return the validators from the common val set that signed in the conflicting block
   168  
   169    - If amnesia, return no validators (since we can't know which validators are malicious). This also means that we don't currently send amnesia evidence to the application, although we will introduce more robust amnesia evidence handling in future Tendermint Core releases
   170  
   171  - Check that the hashes of the conflicting header and the trusted header are different
   172  
   173  - In the case of a forward lunatic attack, where the trusted header height is less than the conflicting header height, the node checks that the time of the trusted header is later than the time of conflicting header. This proves that the conflicting header breaks monotonically increasing time. If the node doesn't have a trusted header with a later time then it is unable to validate the evidence for now.
   174  
   175  - Lastly, for each validator, check the look up table to make sure there already isn't evidence against this validator
   176  
   177  After verification we persist the evidence with the key `height/hash` to the pending evidence database in the evidence pool with the following format:
   178  
   179  ```go
   180  type EvidenceInfo struct {
   181    ev Evidence
   182    time time.Time
   183    validators []Validator
   184    totalVotingPower int64
   185  }
   186  ```
   187  
   188  `time`, `validators` and `totalVotingPower` are need to form the `abci.Evidence` that we send to the application layer. More in this to come later.
   189  
   190  
   191  #### Broadcasting and receiving evidence
   192  
   193  The evidence pool also runs a reactor that broadcasts the newly validated
   194  evidence to all connected peers.
   195  
   196  Receiving evidence from other evidence reactors works in the same manner as receiving evidence from the consensus reactor or a light client.
   197  
   198  
   199  #### Proposing evidence on the block
   200  
   201  When it comes to prevoting and precomitting a proposal that contains evidence, the full node will once again
   202  call upon the evidence pool to verify the evidence using `CheckEvidence(ev []Evidence)`:
   203  
   204  This performs the following actions:
   205  
   206  1. Loops through all the evidence to check that nothing has been duplicated
   207  
   208  2. For each evidence, run `fastCheck(ev evidence)` which works similar to `Has` but instead for `LightClientAttackEvidence` if it has the
   209  same hash it then goes on to check that the validators it has are all signers in the commit of the conflicting header. If it doesn't pass fast check (because it hasn't seen the evidence before) then it will have to verify the evidence.
   210  
   211  3. runs `Verify(ev Evidence)` - Note: this also saves the evidence to the db as mentioned before.
   212  
   213  
   214  #### Updating application and pool
   215  
   216  The final part of the lifecycle is when the block is committed and the `BlockExecutor` then updates state. As part of this process, the `BlockExecutor` gets the evidence pool to create a simplified format for the evidence to be sent to the application. This happens in `ApplyBlock` where the executor calls `Update(Block, State) []abci.Evidence`.
   217  
   218  ```go
   219  abciResponses.BeginBlock.ByzantineValidators = evpool.Update(block, state)
   220  ```
   221  
   222  Here is the format of the evidence that the application will receive. As seen above, this is stored as an array within `BeginBlock`.
   223  The changes to the application are minimal (it is still formed one for each malicious validator) with the exception of using an enum instead of a string for the evidence type.
   224  
   225  ```go
   226  type Evidence struct {
   227    // either LightClientAttackEvidence or DuplicateVoteEvidence as an enum (abci.EvidenceType)
   228  	Type EvidenceType `protobuf:"varint,1,opt,name=type,proto3,enum=tendermint.abci.EvidenceType" json:"type,omitempty"`
   229  	// The offending validator
   230  	Validator Validator `protobuf:"bytes,2,opt,name=validator,proto3" json:"validator"`
   231  	// The height when the offense occurred
   232  	Height int64 `protobuf:"varint,3,opt,name=height,proto3" json:"height,omitempty"`
   233  	// The corresponding time where the offense occurred
   234  	Time time.Time `protobuf:"bytes,4,opt,name=time,proto3,stdtime" json:"time"`
   235  	// Total voting power of the validator set in case the ABCI application does
   236  	// not store historical validators.
   237  	// https://github.com/DFWallet/tendermint-cosmos/issues/4581
   238  	TotalVotingPower int64 `protobuf:"varint,5,opt,name=total_voting_power,json=totalVotingPower,proto3" json:"total_voting_power,omitempty"`
   239  }
   240  ```
   241  
   242  
   243  This `Update()` function does the following:
   244  
   245  - Increments state which keeps track of both the current time and height used for measuring expiry
   246  
   247  - Marks evidence as committed and saves to db. This prevents validators from proposing committed evidence in the future
   248    Note: the db just saves the height and the hash. There is no need to save the entire committed evidence
   249  
   250  - Forms ABCI evidence as such:  (note for `DuplicateVoteEvidence` the validators array size is 1)
   251    ```go
   252    for _, val := range evInfo.Validators {
   253      abciEv = append(abciEv, &abci.Evidence{
   254        Type: evType,   // either DuplicateVote or LightClientAttack
   255        Validator: val,   // the offending validator (which includes the address, pubkey and power)
   256        Height: evInfo.ev.Height(),    // the height when the offense happened
   257        Time: evInfo.time,      // the time when the offense happened
   258        TotalVotingPower: evInfo.totalVotingPower   // the total voting power of the validator set
   259      })
   260    }
   261    ```
   262  
   263  - Removes expired evidence from both pending and committed databases
   264  
   265  The ABCI evidence is then sent via the `BlockExecutor` to the application.
   266  
   267  #### Summary
   268  
   269  To summarize, we can see the lifecycle of evidence as such:
   270  
   271  ![evidence_lifecycle](../imgs/evidence_lifecycle.png)
   272  
   273  Evidence is first detected and created in the light client and consensus reactor. It is verified and stored as `EvidenceInfo` and gossiped to the evidence pools in other nodes. The consensus reactor later communicates with the evidence pool to either retrieve evidence to be put into a block, or verify the evidence the consensus reactor has retrieved in a block. Lastly when a block is added to the chain, the block executor sends the committed evidence back to the evidence pool so a pointer to the evidence can be stored in the evidence pool and it can update it's height and time. Finally, it turns the committed evidence into ABCI evidence and through the block executor passes the evidence to the application so the application can handle it.
   274  
   275  ## Status
   276  
   277  Implemented
   278  
   279  ## Consequences
   280  
   281  <!-- > This section describes the consequences, after applying the decision. All consequences should be summarized here, not just the "positive" ones. -->
   282  
   283  ### Positive
   284  
   285  - Evidence is better contained to the evidence pool / module
   286  - LightClientAttack is kept together (easier for verification and bandwidth)
   287  - Variations on commit sigs in LightClientAttack doesn't lead to multiple permutations and multiple evidence
   288  - Address to evidence map prevents DOS attacks, where a single validator could DOS the network by flooding it with evidence submissions
   289  
   290  ### Negative
   291  
   292  - Changes the `Evidence` interface and thus is a block breaking change
   293  - Changes the ABCI `Evidence` and is thus a ABCI breaking change
   294  - Unable to query evidence for address / time without evidence pool
   295  
   296  ### Neutral
   297  
   298  
   299  ## References
   300  
   301  <!-- > Are there any relevant PR comments, issues that led up to this, or articles referenced for why we made the given design choice? If so link them here! -->
   302  
   303  - [LightClientAttackEvidence](https://github.com/informalsystems/tendermint-rs/blob/31ca3e64ce90786c1734caf186e30595832297a4/docs/spec/lightclient/attacks/evidence-handling.md)