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.

574 lines
16 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. PartSetHeader PartSetHeader
  72. }
  73. type PartSetHeader struct {
  74. Total uint32
  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 int32
  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 SignedMsgType
  132. Height int64
  133. Round int32
  134. BlockID BlockID
  135. Timestamp Time
  136. ValidatorAddress []byte
  137. ValidatorIndex int32
  138. Signature []byte
  139. }
  140. ```
  141. ```protobuf
  142. enum SignedMsgType {
  143. SIGNED_MSG_TYPE_UNKNOWN = 0;
  144. // Votes
  145. PREVOTE_TYPE = 1;
  146. PRECOMMIT_TYPE = 2;
  147. // Proposals
  148. PROPOSAL_TYPE = 32;
  149. }
  150. ```
  151. There are two types of votes:
  152. a _prevote_ has `vote.Type == 1` and
  153. a _precommit_ has `vote.Type == 2`.
  154. ## Signature
  155. Signatures in Tendermint are raw bytes representing the underlying signature.
  156. See the [signature spec](./encoding.md#key-types) for more.
  157. ## EvidenceData
  158. EvidenceData is a simple wrapper for a list of evidence:
  159. ```go
  160. type EvidenceData struct {
  161. Evidence []Evidence
  162. }
  163. ```
  164. ## Evidence
  165. Evidence in Tendermint is used to indicate breaches in the consensus by a validator.
  166. It is implemented as the following interface.
  167. ```go
  168. type Evidence interface {
  169. Height() int64 // height of the equivocation
  170. Bytes() []byte // bytes which comprise the evidence
  171. Hash() []byte // hash of the evidence (this is also used for equality)
  172. ValidateBasic() error // consistency check of the data
  173. String() string // string representation of the evidence
  174. }
  175. ```
  176. All evidence can be encoded and decoded to and from Protobuf with the `EvidenceToProto()`
  177. and `EvidenceFromProto()` functions. The [Fork Accountability](../consensus/light-client/accountability.md)
  178. 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
  179. the timestamp of the block that the evidence occured at to indicate the age of the evidence.
  180. ### DuplicateVoteEvidence
  181. `DuplicateVoteEvidence` represents a validator that has voted for two different blocks
  182. in the same round of the same height. Votes are lexicographically sorted on `BlockID`.
  183. ```go
  184. type DuplicateVoteEvidence struct {
  185. VoteA *Vote
  186. VoteB *Vote
  187. }
  188. ```
  189. Valid Duplicate Vote Evidence must adhere to the following rules:
  190. - Validator Address, Height, Round and Type must be the same for both votes
  191. - BlockID must be different for both votes (BlockID can be for a nil block)
  192. - Validator must have been in the validator set at that height
  193. - Vote signature must be valid (using the chainID)
  194. - Evidence must not have expired: either age in terms of height or time must be
  195. less than the age stated in the consensus params. Time is the block time that the
  196. votes were a part of.
  197. ### LightClientAttackEvidence
  198. ```go
  199. type LightClientAttackEvidence struct {
  200. ConflictingBlock *LightBlock
  201. CommonHeight int64
  202. }
  203. ```
  204. Valid Light Client Attack Evidence encompasses three types of attack and must adhere to the following rules
  205. - If the header of the light block is invalid, thus indicating a lunatic attack, the node must check that
  206. they can use `verifySkipping` from their header at the common height to the conflicting header
  207. - If the header is valid, then the validator sets are the same and this is either a form of equivocation
  208. or amnesia. We therefore check that 2/3 of the validator set also signed the conflicting header
  209. - The trusted header of the node at the same height as the conflicting header must have a different hash to
  210. the conflicting header.
  211. - Evidence must not have expired. The height (and thus the time) is taken from the common height.
  212. ## Validation
  213. Here we describe the validation rules for every element in a block.
  214. Blocks which do not satisfy these rules are considered invalid.
  215. We abuse notation by using something that looks like Go, supplemented with English.
  216. A statement such as `x == y` is an assertion - if it fails, the item is invalid.
  217. We refer to certain globally available objects:
  218. `block` is the block under consideration,
  219. `prevBlock` is the `block` at the previous height,
  220. and `state` keeps track of the validator set, the consensus parameters
  221. and other results from the application. At the point when `block` is the block under consideration,
  222. the current version of the `state` corresponds to the state
  223. after executing transactions from the `prevBlock`.
  224. Elements of an object are accessed as expected,
  225. ie. `block.Header`.
  226. See the [definition of `State`](./state.md).
  227. ### Header
  228. A Header is valid if its corresponding fields are valid.
  229. ### Version
  230. ```go
  231. block.Version.Block == state.Version.Consensus.Block
  232. block.Version.App == state.Version.Consensus.App
  233. ```
  234. The block version must match consensus version from the state.
  235. ### ChainID
  236. ```go
  237. len(block.ChainID) < 50
  238. ```
  239. ChainID must be less than 50 bytes.
  240. ### Height
  241. ```go
  242. block.Header.Height > 0
  243. block.Header.Height >= state.InitialHeight
  244. block.Header.Height == prevBlock.Header.Height + 1
  245. ```
  246. The height is an incrementing integer. The first block has `block.Header.Height == state.InitialHeight`, derived from the genesis file.
  247. ### Time
  248. ```go
  249. block.Header.Timestamp >= prevBlock.Header.Timestamp + state.consensusParams.Block.TimeIotaMs
  250. block.Header.Timestamp == MedianTime(block.LastCommit, state.LastValidators)
  251. ```
  252. The block timestamp must be monotonic.
  253. It must equal the weighted median of the timestamps of the valid signatures in the block.LastCommit.
  254. Note: the timestamp of a vote must be greater by at least one millisecond than that of the
  255. block being voted on.
  256. The timestamp of the first block must be equal to the genesis time (since
  257. there's no votes to compute the median).
  258. ```go
  259. if block.Header.Height == state.InitialHeight {
  260. block.Header.Timestamp == genesisTime
  261. }
  262. ```
  263. See the section on [BFT time](../consensus/bft-time.md) for more details.
  264. ### LastBlockID
  265. LastBlockID is the previous block's BlockID:
  266. ```go
  267. prevBlockParts := MakeParts(prevBlock)
  268. block.Header.LastBlockID == BlockID {
  269. Hash: MerkleRoot(prevBlock.Header),
  270. PartsHeader{
  271. Hash: MerkleRoot(prevBlockParts),
  272. Total: len(prevBlockParts),
  273. },
  274. }
  275. ```
  276. The first block has `block.Header.LastBlockID == BlockID{}`.
  277. ### LastCommitHash
  278. ```go
  279. block.Header.LastCommitHash == MerkleRoot(block.LastCommit.Signatures)
  280. ```
  281. MerkleRoot of the signatures included in the block.
  282. These are the commit signatures of the validators that committed the previous
  283. block.
  284. The first block has `block.Header.LastCommitHash == []byte{}`
  285. ### DataHash
  286. ```go
  287. block.Header.DataHash == MerkleRoot(Hashes(block.Txs.Txs))
  288. ```
  289. MerkleRoot of the hashes of transactions included in the block.
  290. Note the transactions are hashed before being included in the Merkle tree,
  291. so the leaves of the Merkle tree are the hashes, not the transactions
  292. themselves. This is because transaction hashes are regularly used as identifiers for
  293. transactions.
  294. ### ValidatorsHash
  295. ```go
  296. block.ValidatorsHash == MerkleRoot(state.Validators)
  297. ```
  298. MerkleRoot of the current validator set that is committing the block.
  299. This can be used to validate the `LastCommit` included in the next block.
  300. Note that before computing the MerkleRoot the validators are sorted
  301. first by voting power (descending), then by address (ascending).
  302. ### NextValidatorsHash
  303. ```go
  304. block.NextValidatorsHash == MerkleRoot(state.NextValidators)
  305. ```
  306. MerkleRoot of the next validator set that will be the validator set that commits the next block.
  307. This is included so that the current validator set gets a chance to sign the
  308. next validator sets Merkle root.
  309. Note that before computing the MerkleRoot the validators are sorted
  310. first by voting power (descending), then by address (ascending).
  311. ### ConsensusHash
  312. ```go
  313. block.ConsensusHash == state.ConsensusParams.Hash()
  314. ```
  315. Hash of the protobuf-encoding of a subset of the consensus parameters.
  316. ### AppHash
  317. ```go
  318. block.AppHash == state.AppHash
  319. ```
  320. 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.
  321. The first block's `block.Header.AppHash` is given by `ResponseInitChain.app_hash`.
  322. ### LastResultsHash
  323. ```go
  324. block.LastResultsHash == MerkleRoot([]ResponseDeliverTx)
  325. ```
  326. `LastResultsHash` is the root hash of a Merkle tree built from `ResponseDeliverTx` responses (`Log`,`Info`, `Codespace` and `Events` fields are ignored).
  327. The first block has `block.Header.ResultsHash == MerkleRoot(nil)`, i.e. the hash of an empty input, for RFC-6962 conformance.
  328. ## EvidenceHash
  329. ```go
  330. block.EvidenceHash == MerkleRoot(block.Evidence)
  331. ```
  332. MerkleRoot of the evidence of Byzantine behaviour included in this block.
  333. ### ProposerAddress
  334. ```go
  335. block.Header.ProposerAddress in state.Validators
  336. ```
  337. Address of the original proposer of the block. Must be a current validator.
  338. ## Txs
  339. Arbitrary length array of arbitrary length byte-arrays.
  340. ## LastCommit
  341. The first height is an exception - it requires the `LastCommit` to be empty:
  342. ```go
  343. if block.Header.Height == state.InitialHeight {
  344. len(b.LastCommit) == 0
  345. }
  346. ```
  347. Otherwise, we require:
  348. ```go
  349. len(block.LastCommit) == len(state.LastValidators)
  350. talliedVotingPower := 0
  351. for i, commitSig := range block.LastCommit.Signatures {
  352. if commitSig.Absent() {
  353. continue
  354. }
  355. vote.BlockID == block.LastBlockID
  356. val := state.LastValidators[i]
  357. vote.Verify(block.ChainID, val.PubKey) == true
  358. talliedVotingPower += val.VotingPower
  359. }
  360. talliedVotingPower > (2/3)*TotalVotingPower(state.LastValidators)
  361. ```
  362. Includes one vote for every current validator.
  363. All votes must either be for the previous block, nil or absent.
  364. All votes must have a valid signature from the corresponding validator.
  365. The sum total of the voting power of the validators that voted
  366. must be greater than 2/3 of the total voting power of the complete validator set.
  367. The number of votes in a commit is limited to 10000 (see `types.MaxVotesCount`).
  368. ### Vote
  369. A vote is a signed message broadcast in the consensus for a particular block at a particular height and round.
  370. When stored in the blockchain or propagated over the network, votes are encoded in Protobuf.
  371. For signing, votes are represented via `CanonicalVote` and also encoded using Protobuf via
  372. `VoteSignBytes` which includes the `ChainID`, and uses a different ordering of
  373. the fields.
  374. We define a method `Verify` that returns `true` if the signature verifies against the pubkey for the `SignBytes`
  375. using the given ChainID:
  376. ```go
  377. func (vote *Vote) Verify(chainID string, pubKey crypto.PubKey) error {
  378. if !bytes.Equal(pubKey.Address(), vote.ValidatorAddress) {
  379. return ErrVoteInvalidValidatorAddress
  380. }
  381. if !pubKey.VerifyBytes(vote.SignBytes(chainID), vote.Signature) {
  382. return ErrVoteInvalidSignature
  383. }
  384. return nil
  385. }
  386. ```
  387. where `pubKey.Verify` performs the appropriate digital signature verification of the `pubKey`
  388. against the given signature and message bytes.
  389. ## Execution
  390. Once a block is validated, it can be executed against the state.
  391. The state follows this recursive equation:
  392. ```go
  393. state(initialHeight) = InitialState
  394. state(h+1) <- Execute(state(h), ABCIApp, block(h))
  395. ```
  396. where `InitialState` includes the initial consensus parameters and validator set,
  397. and `ABCIApp` is an ABCI application that can return results and changes to the validator
  398. set (TODO). Execute is defined as:
  399. ```go
  400. func Execute(s State, app ABCIApp, block Block) State {
  401. // Fuction ApplyBlock executes block of transactions against the app and returns the new root hash of the app state,
  402. // modifications to the validator set and the changes of the consensus parameters.
  403. AppHash, ValidatorChanges, ConsensusParamChanges := app.ApplyBlock(block)
  404. nextConsensusParams := UpdateConsensusParams(state.ConsensusParams, ConsensusParamChanges)
  405. return State{
  406. ChainID: state.ChainID,
  407. InitialHeight: state.InitialHeight,
  408. LastResults: abciResponses.DeliverTxResults,
  409. AppHash: AppHash,
  410. InitialHeight: state.InitialHeight,
  411. LastValidators: state.Validators,
  412. Validators: state.NextValidators,
  413. NextValidators: UpdateValidators(state.NextValidators, ValidatorChanges),
  414. ConsensusParams: nextConsensusParams,
  415. Version: {
  416. Consensus: {
  417. AppVersion: nextConsensusParams.Version.AppVersion,
  418. },
  419. },
  420. }
  421. }
  422. ```