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.

551 lines
15 KiB

  1. # Data Structures
  2. Here we describe the data structures in the Tendermint blockchain and the rules for validating them.
  3. The Tendermint blockchains consists of a short list of basic data types:
  4. - `Block`
  5. - `Header`
  6. - `Version`
  7. - `BlockID`
  8. - `Time`
  9. - `Data` (for transactions)
  10. - `Commit` and `Vote`
  11. - `EvidenceData` and `Evidence`
  12. ## Block
  13. A block consists of a header, transactions, votes (the commit),
  14. and a list of evidence of malfeasance (ie. signing conflicting votes).
  15. ```go
  16. type Block struct {
  17. Header Header
  18. Txs Data
  19. Evidence EvidenceData
  20. LastCommit Commit
  21. }
  22. ```
  23. Note the `LastCommit` is the set of signatures of validators that committed the last block.
  24. ## Header
  25. A block header contains metadata about the block and about the consensus, as well as commitments to
  26. the data in the current block, the previous block, and the results returned by the application:
  27. ```go
  28. type Header struct {
  29. // basic block info
  30. Version Version
  31. ChainID string
  32. Height int64
  33. Time Time
  34. // prev block info
  35. LastBlockID BlockID
  36. // hashes of block data
  37. LastCommitHash []byte // commit from validators from the last block
  38. DataHash []byte // MerkleRoot of transaction hashes
  39. // hashes from the app output from the prev block
  40. ValidatorsHash []byte // validators for the current block
  41. NextValidatorsHash []byte // validators for the next block
  42. ConsensusHash []byte // consensus params for current block
  43. AppHash []byte // state after txs from the previous block
  44. LastResultsHash []byte // root hash of all results from the txs from the previous block
  45. // consensus info
  46. EvidenceHash []byte // evidence included in the block
  47. ProposerAddress []byte // original proposer of the block
  48. ```
  49. Further details on each of these fields is described below.
  50. ## Version
  51. ```go
  52. type Version struct {
  53. Block uint64
  54. App uint64
  55. }
  56. ```
  57. The `Version` contains the protocol version for the blockchain and the
  58. application as two `uint64` values.
  59. ## BlockID
  60. The `BlockID` contains two distinct Merkle roots of the block.
  61. The first, used as the block's main hash, is the MerkleRoot
  62. of all the fields in the header (ie. `MerkleRoot(header)`.
  63. The second, used for secure gossipping of the block during consensus,
  64. is the MerkleRoot of the complete serialized block
  65. cut into parts (ie. `MerkleRoot(MakeParts(block))`).
  66. The `BlockID` includes these two hashes, as well as the number of
  67. parts (ie. `len(MakeParts(block))`)
  68. ```go
  69. type BlockID struct {
  70. Hash []byte
  71. PartsHeader PartSetHeader
  72. }
  73. type PartSetHeader struct {
  74. Total int32
  75. Hash []byte
  76. }
  77. ```
  78. See [MerkleRoot](./encoding.md#MerkleRoot) for details.
  79. ## Time
  80. Tendermint uses the
  81. [Google.Protobuf.WellKnownTypes.Timestamp](https://developers.google.com/protocol-buffers/docs/reference/csharp/class/google/protobuf/well-known-types/timestamp)
  82. format, which uses two integers, one for Seconds and for Nanoseconds.
  83. ## Data
  84. Data is just a wrapper for a list of transactions, where transactions are
  85. arbitrary byte arrays:
  86. ```
  87. type Data struct {
  88. Txs [][]byte
  89. }
  90. ```
  91. ## Commit
  92. Commit is a simple wrapper for a list of signatures, with one for each
  93. validator. It also contains the relevant BlockID, height and round:
  94. ```go
  95. type Commit struct {
  96. Height int64
  97. Round int
  98. BlockID BlockID
  99. Signatures []CommitSig
  100. }
  101. ```
  102. ## CommitSig
  103. `CommitSig` represents a signature of a validator, who has voted either for nil,
  104. a particular `BlockID` or was absent. It's a part of the `Commit` and can be used
  105. to reconstruct the vote set given the validator set.
  106. ```go
  107. type BlockIDFlag byte
  108. const (
  109. // BlockIDFlagAbsent - no vote was received from a validator.
  110. BlockIDFlagAbsent BlockIDFlag = 0x01
  111. // BlockIDFlagCommit - voted for the Commit.BlockID.
  112. BlockIDFlagCommit = 0x02
  113. // BlockIDFlagNil - voted for nil.
  114. BlockIDFlagNil = 0x03
  115. )
  116. type CommitSig struct {
  117. BlockIDFlag BlockIDFlag
  118. ValidatorAddress Address
  119. Timestamp time.Time
  120. Signature []byte
  121. }
  122. ```
  123. NOTE: `ValidatorAddress` and `Timestamp` fields may be removed in the future
  124. (see
  125. [ADR-25](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-025-commit.md)).
  126. ## Vote
  127. A vote is a signed message from a validator for a particular block.
  128. The vote includes information about the validator signing it.
  129. ```go
  130. type Vote struct {
  131. Type byte
  132. Height int64
  133. Round int
  134. BlockID BlockID
  135. Timestamp Time
  136. ValidatorAddress []byte
  137. ValidatorIndex int
  138. Signature []byte
  139. }
  140. ```
  141. There are two types of votes:
  142. a _prevote_ has `vote.Type == 1` and
  143. a _precommit_ has `vote.Type == 2`.
  144. ## Signature
  145. Signatures in Tendermint are raw bytes representing the underlying signature.
  146. See the [signature spec](./encoding.md#key-types) for more.
  147. ## EvidenceData
  148. EvidenceData is a simple wrapper for a list of evidence:
  149. ```
  150. type EvidenceData struct {
  151. Evidence []Evidence
  152. }
  153. ```
  154. ## Evidence
  155. Evidence in Tendermint is used to indicate breaches in the consensus by a validator.
  156. It is implemented as the following interface.
  157. ```go
  158. type Evidence interface {
  159. Height() int64 // height of the equivocation
  160. Time() time.Time // time of the equivocation
  161. Address() []byte // address of the equivocating validator
  162. Bytes() []byte // bytes which comprise the evidence
  163. Hash() []byte // hash of the evidence
  164. Verify(chainID string, pubKey crypto.PubKey) error // verify the evidence
  165. Equal(Evidence) bool // check equality of evidence
  166. ValidateBasic() error
  167. String() string
  168. }
  169. ```
  170. All evidence can be encoded and decoded to and from Protobuf with the `EvidenceToProto()`
  171. and `EvidenceFromProto()` functions. The [Fork Accountability](../consensus/light-client/accountability.md)
  172. document provides a good overview for the types of evidence and how they occur. Each evidence uses
  173. the timestamp of the block that the evidence occured at to indicate the age of the evidence.
  174. `DuplicateVoteEvidence` represents a validator that has voted for two different blocks
  175. in the same round of the same height. Votes are lexicographically sorted on `BlockID`.
  176. ```go
  177. type DuplicateVoteEvidence struct {
  178. VoteA *Vote
  179. VoteB *Vote
  180. Timestamp time.Time
  181. }
  182. ```
  183. `AmnesiaEvidence` represents a validator that has incorrectly voted for another block in a
  184. different round to the the block that the validator was previously locked on. This form
  185. of evidence is generated differently from the rest. See this
  186. [ADR](https://github.com/tendermint/tendermint/blob/master/docs/architecture/adr-056-proving-amnesia-attacks.md) for more information.
  187. ```go
  188. type AmnesiaEvidence struct {
  189. *PotentialAmnesiaEvidence
  190. Polc *ProofOfLockChange
  191. }
  192. ```
  193. `LunaticValidatorEvidence` represents a validator that has signed for an arbitrary application state.
  194. This attack only applies to Light clients.
  195. ```go
  196. type LunaticValidatorEvidence struct {
  197. Header *Header
  198. Vote *Vote
  199. InvalidHeaderField string
  200. Timestamp time.Time
  201. }
  202. ```
  203. ## Validation
  204. Here we describe the validation rules for every element in a block.
  205. Blocks which do not satisfy these rules are considered invalid.
  206. We abuse notation by using something that looks like Go, supplemented with English.
  207. A statement such as `x == y` is an assertion - if it fails, the item is invalid.
  208. We refer to certain globally available objects:
  209. `block` is the block under consideration,
  210. `prevBlock` is the `block` at the previous height,
  211. and `state` keeps track of the validator set, the consensus parameters
  212. and other results from the application. At the point when `block` is the block under consideration,
  213. the current version of the `state` corresponds to the state
  214. after executing transactions from the `prevBlock`.
  215. Elements of an object are accessed as expected,
  216. ie. `block.Header`.
  217. See the [definition of `State`](./state.md).
  218. ### Header
  219. A Header is valid if its corresponding fields are valid.
  220. ### Version
  221. ```
  222. block.Version.Block == state.Version.Consensus.Block
  223. block.Version.App == state.Version.Consensus.App
  224. ```
  225. The block version must match consensus version from the state.
  226. ### ChainID
  227. ```
  228. len(block.ChainID) < 50
  229. ```
  230. ChainID must be less than 50 bytes.
  231. ### Height
  232. ```go
  233. block.Header.Height > 0
  234. block.Header.Height == prevBlock.Header.Height + 1
  235. ```
  236. The height is an incrementing integer. The first block has `block.Header.Height == 1`.
  237. ### Time
  238. ```
  239. block.Header.Timestamp >= prevBlock.Header.Timestamp + state.consensusParams.Block.TimeIotaMs
  240. block.Header.Timestamp == MedianTime(block.LastCommit, state.LastValidators)
  241. ```
  242. The block timestamp must be monotonic.
  243. It must equal the weighted median of the timestamps of the valid signatures in the block.LastCommit.
  244. Note: the timestamp of a vote must be greater by at least one millisecond than that of the
  245. block being voted on.
  246. The timestamp of the first block must be equal to the genesis time (since
  247. there's no votes to compute the median).
  248. ```
  249. if block.Header.Height == 1 {
  250. block.Header.Timestamp == genesisTime
  251. }
  252. ```
  253. See the section on [BFT time](../consensus/bft-time.md) for more details.
  254. ### LastBlockID
  255. LastBlockID is the previous block's BlockID:
  256. ```go
  257. prevBlockParts := MakeParts(prevBlock)
  258. block.Header.LastBlockID == BlockID {
  259. Hash: MerkleRoot(prevBlock.Header),
  260. PartsHeader{
  261. Hash: MerkleRoot(prevBlockParts),
  262. Total: len(prevBlockParts),
  263. },
  264. }
  265. ```
  266. The first block has `block.Header.LastBlockID == BlockID{}`.
  267. ### LastCommitHash
  268. ```go
  269. block.Header.LastCommitHash == MerkleRoot(block.LastCommit.Signatures)
  270. ```
  271. MerkleRoot of the signatures included in the block.
  272. These are the commit signatures of the validators that committed the previous
  273. block.
  274. The first block has `block.Header.LastCommitHash == []byte{}`
  275. ### DataHash
  276. ```go
  277. block.Header.DataHash == MerkleRoot(Hashes(block.Txs.Txs))
  278. ```
  279. MerkleRoot of the hashes of transactions included in the block.
  280. Note the transactions are hashed before being included in the Merkle tree,
  281. so the leaves of the Merkle tree are the hashes, not the transactions
  282. themselves. This is because transaction hashes are regularly used as identifiers for
  283. transactions.
  284. ### ValidatorsHash
  285. ```go
  286. block.ValidatorsHash == MerkleRoot(state.Validators)
  287. ```
  288. MerkleRoot of the current validator set that is committing the block.
  289. This can be used to validate the `LastCommit` included in the next block.
  290. Note the validators are sorted by their voting power before computing the MerkleRoot.
  291. ### NextValidatorsHash
  292. ```go
  293. block.NextValidatorsHash == MerkleRoot(state.NextValidators)
  294. ```
  295. MerkleRoot of the next validator set that will be the validator set that commits the next block.
  296. This is included so that the current validator set gets a chance to sign the
  297. next validator sets Merkle root.
  298. Note the validators are sorted by their voting power before computing the MerkleRoot.
  299. ### ConsensusHash
  300. ```go
  301. block.ConsensusHash == state.ConsensusParams.Hash()
  302. ```
  303. Hash of the amino-encoding of a subset of the consensus parameters.
  304. ### AppHash
  305. ```go
  306. block.AppHash == state.AppHash
  307. ```
  308. Arbitrary byte array returned by the application after executing and commiting the previous block. It serves as the basis for validating any merkle proofs that comes from the ABCI application and represents the state of the actual application rather than the state of the blockchain itself.
  309. The first block has `block.Header.AppHash == []byte{}`.
  310. ### LastResultsHash
  311. ```go
  312. block.LastResultsHash == MerkleRoot([]ResponseDeliverTx)
  313. ```
  314. `LastResultsHash` is the root hash of a Merkle tree built from `ResponseDeliverTx` responses (`Log`,`Info`, `Codespace` and `Events` fields are ignored).
  315. The first block has `block.Header.ResultsHash == []byte{}`.
  316. ## EvidenceHash
  317. ```go
  318. block.EvidenceHash == MerkleRoot(block.Evidence)
  319. ```
  320. MerkleRoot of the evidence of Byzantine behaviour included in this block.
  321. ### ProposerAddress
  322. ```go
  323. block.Header.ProposerAddress in state.Validators
  324. ```
  325. Address of the original proposer of the block. Must be a current validator.
  326. ## Txs
  327. Arbitrary length array of arbitrary length byte-arrays.
  328. ## LastCommit
  329. The first height is an exception - it requires the `LastCommit` to be empty:
  330. ```go
  331. if block.Header.Height == 1 {
  332. len(b.LastCommit) == 0
  333. }
  334. ```
  335. Otherwise, we require:
  336. ```go
  337. len(block.LastCommit) == len(state.LastValidators)
  338. talliedVotingPower := 0
  339. for i, commitSig := range block.LastCommit.Signatures {
  340. if commitSig.Absent() {
  341. continue
  342. }
  343. vote.BlockID == block.LastBlockID
  344. val := state.LastValidators[i]
  345. vote.Verify(block.ChainID, val.PubKey) == true
  346. talliedVotingPower += val.VotingPower
  347. }
  348. talliedVotingPower > (2/3)*TotalVotingPower(state.LastValidators)
  349. ```
  350. Includes one vote for every current validator.
  351. All votes must either be for the previous block, nil or absent.
  352. All votes must have a valid signature from the corresponding validator.
  353. The sum total of the voting power of the validators that voted
  354. must be greater than 2/3 of the total voting power of the complete validator set.
  355. The number of votes in a commit is limited to 10000 (see `types.MaxVotesCount`).
  356. ### Vote
  357. A vote is a signed message broadcast in the consensus for a particular block at a particular height and round.
  358. When stored in the blockchain or propagated over the network, votes are encoded in Amino.
  359. For signing, votes are represented via `CanonicalVote` and also encoded using amino (protobuf compatible) via
  360. `Vote.SignBytes` which includes the `ChainID`, and uses a different ordering of
  361. the fields.
  362. We define a method `Verify` that returns `true` if the signature verifies against the pubkey for the `SignBytes`
  363. using the given ChainID:
  364. ```go
  365. func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
  366. if !bytes.Equal(pubKey.Address(), vote.ValidatorAddress) {
  367. return ErrVoteInvalidValidatorAddress
  368. }
  369. if !pubKey.VerifyBytes(vote.SignBytes(chainID), vote.Signature) {
  370. return ErrVoteInvalidSignature
  371. }
  372. return nil
  373. }
  374. ```
  375. where `pubKey.Verify` performs the appropriate digital signature verification of the `pubKey`
  376. against the given signature and message bytes.
  377. # Execution
  378. Once a block is validated, it can be executed against the state.
  379. The state follows this recursive equation:
  380. ```go
  381. state(1) = InitialState
  382. state(h+1) <- Execute(state(h), ABCIApp, block(h))
  383. ```
  384. where `InitialState` includes the initial consensus parameters and validator set,
  385. and `ABCIApp` is an ABCI application that can return results and changes to the validator
  386. set (TODO). Execute is defined as:
  387. ```go
  388. func Execute(s State, app ABCIApp, block Block) State {
  389. // Fuction ApplyBlock executes block of transactions against the app and returns the new root hash of the app state,
  390. // modifications to the validator set and the changes of the consensus parameters.
  391. AppHash, ValidatorChanges, ConsensusParamChanges := app.ApplyBlock(block)
  392. nextConsensusParams := UpdateConsensusParams(state.ConsensusParams, ConsensusParamChanges)
  393. return State{
  394. LastResults: abciResponses.DeliverTxResults,
  395. AppHash: AppHash,
  396. LastValidators: state.Validators,
  397. Validators: state.NextValidators,
  398. NextValidators: UpdateValidators(state.NextValidators, ValidatorChanges),
  399. ConsensusParams: nextConsensusParams,
  400. Version: {
  401. Consensus: {
  402. AppVersion: nextConsensusParams.Version.AppVersion,
  403. },
  404. },
  405. }
  406. }
  407. ```