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.

544 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. ```go
  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. ```go
  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. For evidence to be committed onchain, it must adhere to the validation rules of each evidence and must not be expired. The expiration age, measured in both block height and time is set in `EvidenceParams`. Each evidence uses
  173. the timestamp of the block that the evidence occured at to indicate the age of the evidence.
  174. ### DuplicateVoteEvidence
  175. `DuplicateVoteEvidence` represents a validator that has voted for two different blocks
  176. in the same round of the same height. Votes are lexicographically sorted on `BlockID`.
  177. ```go
  178. type DuplicateVoteEvidence struct {
  179. VoteA *Vote
  180. VoteB *Vote
  181. Timestamp time.Time
  182. }
  183. ```
  184. Valid Duplicate Vote Evidence must adhere to the following rules:
  185. - Validator Address, Height, Round and Type of vote must be the same for both votes
  186. - BlockID must be different for both votes (BlockID can be for a nil block)
  187. - Validator must have been in the validator set at that height
  188. - Vote signature must be valid (using the chainID)
  189. - Time must be equal to the block time
  190. ## Validation
  191. Here we describe the validation rules for every element in a block.
  192. Blocks which do not satisfy these rules are considered invalid.
  193. We abuse notation by using something that looks like Go, supplemented with English.
  194. A statement such as `x == y` is an assertion - if it fails, the item is invalid.
  195. We refer to certain globally available objects:
  196. `block` is the block under consideration,
  197. `prevBlock` is the `block` at the previous height,
  198. and `state` keeps track of the validator set, the consensus parameters
  199. and other results from the application. At the point when `block` is the block under consideration,
  200. the current version of the `state` corresponds to the state
  201. after executing transactions from the `prevBlock`.
  202. Elements of an object are accessed as expected,
  203. ie. `block.Header`.
  204. See the [definition of `State`](./state.md).
  205. ### Header
  206. A Header is valid if its corresponding fields are valid.
  207. ### Version
  208. ```go
  209. block.Version.Block == state.Version.Consensus.Block
  210. block.Version.App == state.Version.Consensus.App
  211. ```
  212. The block version must match consensus version from the state.
  213. ### ChainID
  214. ```go
  215. len(block.ChainID) < 50
  216. ```
  217. ChainID must be less than 50 bytes.
  218. ### Height
  219. ```go
  220. block.Header.Height > 0
  221. block.Header.Height >= state.InitialHeight
  222. block.Header.Height == prevBlock.Header.Height + 1
  223. ```
  224. The height is an incrementing integer. The first block has `block.Header.Height == state.InitialHeight`, derived from the genesis file.
  225. ### Time
  226. ```go
  227. block.Header.Timestamp >= prevBlock.Header.Timestamp + state.consensusParams.Block.TimeIotaMs
  228. block.Header.Timestamp == MedianTime(block.LastCommit, state.LastValidators)
  229. ```
  230. The block timestamp must be monotonic.
  231. It must equal the weighted median of the timestamps of the valid signatures in the block.LastCommit.
  232. Note: the timestamp of a vote must be greater by at least one millisecond than that of the
  233. block being voted on.
  234. The timestamp of the first block must be equal to the genesis time (since
  235. there's no votes to compute the median).
  236. ```go
  237. if block.Header.Height == state.InitialHeight {
  238. block.Header.Timestamp == genesisTime
  239. }
  240. ```
  241. See the section on [BFT time](../consensus/bft-time.md) for more details.
  242. ### LastBlockID
  243. LastBlockID is the previous block's BlockID:
  244. ```go
  245. prevBlockParts := MakeParts(prevBlock)
  246. block.Header.LastBlockID == BlockID {
  247. Hash: MerkleRoot(prevBlock.Header),
  248. PartsHeader{
  249. Hash: MerkleRoot(prevBlockParts),
  250. Total: len(prevBlockParts),
  251. },
  252. }
  253. ```
  254. The first block has `block.Header.LastBlockID == BlockID{}`.
  255. ### LastCommitHash
  256. ```go
  257. block.Header.LastCommitHash == MerkleRoot(block.LastCommit.Signatures)
  258. ```
  259. MerkleRoot of the signatures included in the block.
  260. These are the commit signatures of the validators that committed the previous
  261. block.
  262. The first block has `block.Header.LastCommitHash == []byte{}`
  263. ### DataHash
  264. ```go
  265. block.Header.DataHash == MerkleRoot(Hashes(block.Txs.Txs))
  266. ```
  267. MerkleRoot of the hashes of transactions included in the block.
  268. Note the transactions are hashed before being included in the Merkle tree,
  269. so the leaves of the Merkle tree are the hashes, not the transactions
  270. themselves. This is because transaction hashes are regularly used as identifiers for
  271. transactions.
  272. ### ValidatorsHash
  273. ```go
  274. block.ValidatorsHash == MerkleRoot(state.Validators)
  275. ```
  276. MerkleRoot of the current validator set that is committing the block.
  277. This can be used to validate the `LastCommit` included in the next block.
  278. Note the validators are sorted by their voting power before computing the MerkleRoot.
  279. ### NextValidatorsHash
  280. ```go
  281. block.NextValidatorsHash == MerkleRoot(state.NextValidators)
  282. ```
  283. MerkleRoot of the next validator set that will be the validator set that commits the next block.
  284. This is included so that the current validator set gets a chance to sign the
  285. next validator sets Merkle root.
  286. Note the validators are sorted by their voting power before computing the MerkleRoot.
  287. ### ConsensusHash
  288. ```go
  289. block.ConsensusHash == state.ConsensusParams.Hash()
  290. ```
  291. Hash of the amino-encoding of a subset of the consensus parameters.
  292. ### AppHash
  293. ```go
  294. block.AppHash == state.AppHash
  295. ```
  296. 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.
  297. The first block's `block.Header.AppHash` is given by `ResponseInitChain.app_hash`.
  298. ### LastResultsHash
  299. ```go
  300. block.LastResultsHash == MerkleRoot([]ResponseDeliverTx)
  301. ```
  302. `LastResultsHash` is the root hash of a Merkle tree built from `ResponseDeliverTx` responses (`Log`,`Info`, `Codespace` and `Events` fields are ignored).
  303. The first block has `block.Header.ResultsHash == MerkleRoot(nil)`, i.e. the hash of an empty input, for RFC-6962 conformance.
  304. ## EvidenceHash
  305. ```go
  306. block.EvidenceHash == MerkleRoot(block.Evidence)
  307. ```
  308. MerkleRoot of the evidence of Byzantine behaviour included in this block.
  309. ### ProposerAddress
  310. ```go
  311. block.Header.ProposerAddress in state.Validators
  312. ```
  313. Address of the original proposer of the block. Must be a current validator.
  314. ## Txs
  315. Arbitrary length array of arbitrary length byte-arrays.
  316. ## LastCommit
  317. The first height is an exception - it requires the `LastCommit` to be empty:
  318. ```go
  319. if block.Header.Height == state.InitialHeight {
  320. len(b.LastCommit) == 0
  321. }
  322. ```
  323. Otherwise, we require:
  324. ```go
  325. len(block.LastCommit) == len(state.LastValidators)
  326. talliedVotingPower := 0
  327. for i, commitSig := range block.LastCommit.Signatures {
  328. if commitSig.Absent() {
  329. continue
  330. }
  331. vote.BlockID == block.LastBlockID
  332. val := state.LastValidators[i]
  333. vote.Verify(block.ChainID, val.PubKey) == true
  334. talliedVotingPower += val.VotingPower
  335. }
  336. talliedVotingPower > (2/3)*TotalVotingPower(state.LastValidators)
  337. ```
  338. Includes one vote for every current validator.
  339. All votes must either be for the previous block, nil or absent.
  340. All votes must have a valid signature from the corresponding validator.
  341. The sum total of the voting power of the validators that voted
  342. must be greater than 2/3 of the total voting power of the complete validator set.
  343. The number of votes in a commit is limited to 10000 (see `types.MaxVotesCount`).
  344. ### Vote
  345. A vote is a signed message broadcast in the consensus for a particular block at a particular height and round.
  346. When stored in the blockchain or propagated over the network, votes are encoded in Amino.
  347. For signing, votes are represented via `CanonicalVote` and also encoded using amino (protobuf compatible) via
  348. `Vote.SignBytes` which includes the `ChainID`, and uses a different ordering of
  349. the fields.
  350. We define a method `Verify` that returns `true` if the signature verifies against the pubkey for the `SignBytes`
  351. using the given ChainID:
  352. ```go
  353. func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
  354. if !bytes.Equal(pubKey.Address(), vote.ValidatorAddress) {
  355. return ErrVoteInvalidValidatorAddress
  356. }
  357. if !pubKey.VerifyBytes(vote.SignBytes(chainID), vote.Signature) {
  358. return ErrVoteInvalidSignature
  359. }
  360. return nil
  361. }
  362. ```
  363. where `pubKey.Verify` performs the appropriate digital signature verification of the `pubKey`
  364. against the given signature and message bytes.
  365. ## Execution
  366. Once a block is validated, it can be executed against the state.
  367. The state follows this recursive equation:
  368. ```go
  369. state(initialHeight) = InitialState
  370. state(h+1) <- Execute(state(h), ABCIApp, block(h))
  371. ```
  372. where `InitialState` includes the initial consensus parameters and validator set,
  373. and `ABCIApp` is an ABCI application that can return results and changes to the validator
  374. set (TODO). Execute is defined as:
  375. ```go
  376. func Execute(s State, app ABCIApp, block Block) State {
  377. // Fuction ApplyBlock executes block of transactions against the app and returns the new root hash of the app state,
  378. // modifications to the validator set and the changes of the consensus parameters.
  379. AppHash, ValidatorChanges, ConsensusParamChanges := app.ApplyBlock(block)
  380. nextConsensusParams := UpdateConsensusParams(state.ConsensusParams, ConsensusParamChanges)
  381. return State{
  382. ChainID: state.ChainID,
  383. InitialHeight: state.InitialHeight,
  384. LastResults: abciResponses.DeliverTxResults,
  385. AppHash: AppHash,
  386. InitialHeight: state.InitialHeight,
  387. LastValidators: state.Validators,
  388. Validators: state.NextValidators,
  389. NextValidators: UpdateValidators(state.NextValidators, ValidatorChanges),
  390. ConsensusParams: nextConsensusParams,
  391. Version: {
  392. Consensus: {
  393. AppVersion: nextConsensusParams.Version.AppVersion,
  394. },
  395. },
  396. }
  397. }
  398. ```