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.

300 lines
10 KiB

  1. # Encoding
  2. ## Protocol Buffers
  3. Tendermint uses [Protocol Buffers](https://developers.google.com/protocol-buffers), specifically proto3, for all data structures.
  4. Please see the [Proto3 language guide](https://developers.google.com/protocol-buffers/docs/proto3) for more details.
  5. ## Byte Arrays
  6. The encoding of a byte array is simply the raw-bytes prefixed with the length of
  7. the array as a `UVarint` (what proto calls a `Varint`).
  8. For details on varints, see the [protobuf
  9. spec](https://developers.google.com/protocol-buffers/docs/encoding#varints).
  10. For example, the byte-array `[0xA, 0xB]` would be encoded as `0x020A0B`,
  11. while a byte-array containing 300 entires beginning with `[0xA, 0xB, ...]` would
  12. be encoded as `0xAC020A0B...` where `0xAC02` is the UVarint encoding of 300.
  13. ## Hashing
  14. Tendermint uses `SHA256` as its hash function.
  15. Objects are always Amino encoded before being hashed.
  16. So `SHA256(obj)` is short for `SHA256(ProtoEncoding(obj))`.
  17. ## Public Key Cryptography
  18. Tendermint uses Protobuf [Oneof](https://developers.google.com/protocol-buffers/docs/proto3#oneof)
  19. to distinguish between different types public keys, and signatures.
  20. Additionally, for each public key, Tendermint
  21. defines an Address function that can be used as a more compact identifier in
  22. place of the public key. Here we list the concrete types, their names,
  23. and prefix bytes for public keys and signatures, as well as the address schemes
  24. for each PubKey. Note for brevity we don't
  25. include details of the private keys beyond their type and name.
  26. ### Key Types
  27. Each type specifies it's own pubkey, address, and signature format.
  28. #### Ed25519
  29. The address is the first 20-bytes of the SHA256 hash of the raw 32-byte public key:
  30. ```go
  31. address = SHA256(pubkey)[:20]
  32. ```
  33. The signature is the raw 64-byte ED25519 signature.
  34. Tendermint adopted [zip215](https://zips.z.cash/zip-0215) for verification of ed25519 signatures.
  35. > Note: This change will be released in the next major release of Tendermint-Go (0.35).
  36. #### Secp256k1
  37. The address is the first 20-bytes of the SHA256 hash of the raw 32-byte public key:
  38. ```go
  39. address = SHA256(pubkey)[:20]
  40. ```
  41. ## Other Common Types
  42. ### BitArray
  43. The BitArray is used in some consensus messages to represent votes received from
  44. validators, or parts received in a block. It is represented
  45. with a struct containing the number of bits (`Bits`) and the bit-array itself
  46. encoded in base64 (`Elems`).
  47. | Name | Type |
  48. |-------|----------------------------|
  49. | bits | int64 |
  50. | elems | slice of int64 (`[]int64`) |
  51. Note BitArray receives a special JSON encoding in the form of `x` and `_`
  52. representing `1` and `0`. Ie. the BitArray `10110` would be JSON encoded as
  53. `"x_xx_"`
  54. ### Part
  55. Part is used to break up blocks into pieces that can be gossiped in parallel
  56. and securely verified using a Merkle tree of the parts.
  57. Part contains the index of the part (`Index`), the actual
  58. underlying data of the part (`Bytes`), and a Merkle proof that the part is contained in
  59. the set (`Proof`).
  60. | Name | Type |
  61. |-------|---------------------------|
  62. | index | uint32 |
  63. | bytes | slice of bytes (`[]byte`) |
  64. | proof | [proof](#merkle-proof) |
  65. See details of SimpleProof, below.
  66. ### MakeParts
  67. Encode an object using Protobuf and slice it into parts.
  68. Tendermint uses a part size of 65536 bytes, and allows a maximum of 1601 parts
  69. (see `types.MaxBlockPartsCount`). This corresponds to the hard-coded block size
  70. limit of 100MB.
  71. ```go
  72. func MakeParts(block Block) []Part
  73. ```
  74. ## Merkle Trees
  75. For an overview of Merkle trees, see
  76. [wikipedia](https://en.wikipedia.org/wiki/Merkle_tree)
  77. We use the RFC 6962 specification of a merkle tree, with sha256 as the hash function.
  78. Merkle trees are used throughout Tendermint to compute a cryptographic digest of a data structure.
  79. The differences between RFC 6962 and the simplest form a merkle tree are that:
  80. 1. leaf nodes and inner nodes have different hashes.
  81. This is for "second pre-image resistance", to prevent the proof to an inner node being valid as the proof of a leaf.
  82. The leaf nodes are `SHA256(0x00 || leaf_data)`, and inner nodes are `SHA256(0x01 || left_hash || right_hash)`.
  83. 2. When the number of items isn't a power of two, the left half of the tree is as big as it could be.
  84. (The largest power of two less than the number of items) This allows new leaves to be added with less
  85. recomputation. For example:
  86. ```md
  87. Simple Tree with 6 items Simple Tree with 7 items
  88. * *
  89. / \ / \
  90. / \ / \
  91. / \ / \
  92. / \ / \
  93. * * * *
  94. / \ / \ / \ / \
  95. / \ / \ / \ / \
  96. / \ / \ / \ / \
  97. * * h4 h5 * * * h6
  98. / \ / \ / \ / \ / \
  99. h0 h1 h2 h3 h0 h1 h2 h3 h4 h5
  100. ```
  101. ### MerkleRoot
  102. The function `MerkleRoot` is a simple recursive function defined as follows:
  103. ```go
  104. // SHA256([]byte{})
  105. func emptyHash() []byte {
  106. return tmhash.Sum([]byte{})
  107. }
  108. // SHA256(0x00 || leaf)
  109. func leafHash(leaf []byte) []byte {
  110. return tmhash.Sum(append(0x00, leaf...))
  111. }
  112. // SHA256(0x01 || left || right)
  113. func innerHash(left []byte, right []byte) []byte {
  114. return tmhash.Sum(append(0x01, append(left, right...)...))
  115. }
  116. // largest power of 2 less than k
  117. func getSplitPoint(k int) { ... }
  118. func MerkleRoot(items [][]byte) []byte{
  119. switch len(items) {
  120. case 0:
  121. return empthHash()
  122. case 1:
  123. return leafHash(items[0])
  124. default:
  125. k := getSplitPoint(len(items))
  126. left := MerkleRoot(items[:k])
  127. right := MerkleRoot(items[k:])
  128. return innerHash(left, right)
  129. }
  130. }
  131. ```
  132. Note: `MerkleRoot` operates on items which are arbitrary byte arrays, not
  133. necessarily hashes. For items which need to be hashed first, we introduce the
  134. `Hashes` function:
  135. ```go
  136. func Hashes(items [][]byte) [][]byte {
  137. return SHA256 of each item
  138. }
  139. ```
  140. Note: we will abuse notion and invoke `MerkleRoot` with arguments of type `struct` or type `[]struct`.
  141. For `struct` arguments, we compute a `[][]byte` containing the protobuf encoding of each
  142. field in the struct, in the same order the fields appear in the struct.
  143. For `[]struct` arguments, we compute a `[][]byte` by protobuf encoding the individual `struct` elements.
  144. ### Merkle Proof
  145. Proof that a leaf is in a Merkle tree is composed as follows:
  146. | Name | Type |
  147. |----------|----------------------------|
  148. | total | int64 |
  149. | index | int64 |
  150. | leafHash | slice of bytes (`[]byte`) |
  151. | aunts | Matrix of bytes ([][]byte) |
  152. Which is verified as follows:
  153. ```golang
  154. func (proof Proof) Verify(rootHash []byte, leaf []byte) bool {
  155. assert(proof.LeafHash, leafHash(leaf)
  156. computedHash := computeHashFromAunts(proof.Index, proof.Total, proof.LeafHash, proof.Aunts)
  157. return computedHash == rootHash
  158. }
  159. func computeHashFromAunts(index, total int, leafHash []byte, innerHashes [][]byte) []byte{
  160. assert(index < total && index >= 0 && total > 0)
  161. if total == 1{
  162. assert(len(proof.Aunts) == 0)
  163. return leafHash
  164. }
  165. assert(len(innerHashes) > 0)
  166. numLeft := getSplitPoint(total) // largest power of 2 less than total
  167. if index < numLeft {
  168. leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  169. assert(leftHash != nil)
  170. return innerHash(leftHash, innerHashes[len(innerHashes)-1])
  171. }
  172. rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  173. assert(rightHash != nil)
  174. return innerHash(innerHashes[len(innerHashes)-1], rightHash)
  175. }
  176. ```
  177. The number of aunts is limited to 100 (`MaxAunts`) to protect the node against DOS attacks.
  178. This limits the tree size to 2^100 leaves, which should be sufficient for any
  179. conceivable purpose.
  180. ### IAVL+ Tree
  181. Because Tendermint only uses a Simple Merkle Tree, application developers are expect to use their own Merkle tree in their applications. For example, the IAVL+ Tree - an immutable self-balancing binary tree for persisting application state is used by the [Cosmos SDK](https://github.com/cosmos/cosmos-sdk/blob/ae77f0080a724b159233bd9b289b2e91c0de21b5/docs/interfaces/lite/specification.md)
  182. ## JSON
  183. Tendermint has its own JSON encoding in order to keep backwards compatibility with the previous RPC layer.
  184. Registered types are encoded as:
  185. ```json
  186. {
  187. "type": "<type name>",
  188. "value": <JSON>
  189. }
  190. ```
  191. For instance, an ED25519 PubKey would look like:
  192. ```json
  193. {
  194. "type": "tendermint/PubKeyEd25519",
  195. "value": "uZ4h63OFWuQ36ZZ4Bd6NF+/w9fWUwrOncrQsackrsTk="
  196. }
  197. ```
  198. Where the `"value"` is the base64 encoding of the raw pubkey bytes, and the
  199. `"type"` is the type name for Ed25519 pubkeys.
  200. ### Signed Messages
  201. Signed messages (eg. votes, proposals) in the consensus are encoded using protobuf.
  202. When signing, the elements of a message are re-ordered so the fixed-length fields
  203. are first, making it easy to quickly check the type, height, and round.
  204. The `ChainID` is also appended to the end.
  205. We call this encoding the SignBytes. For instance, SignBytes for a vote is the protobuf encoding of the following struct:
  206. ```protobuf
  207. message CanonicalVote {
  208. SignedMsgType type = 1;
  209. sfixed64 height = 2; // canonicalization requires fixed size encoding here
  210. sfixed64 round = 3; // canonicalization requires fixed size encoding here
  211. CanonicalBlockID block_id = 4;
  212. google.protobuf.Timestamp timestamp = 5;
  213. string chain_id = 6;
  214. }
  215. ```
  216. The field ordering and the fixed sized encoding for the first three fields is optimized to ease parsing of SignBytes
  217. in HSMs. It creates fixed offsets for relevant fields that need to be read in this context.
  218. > Note: All canonical messages are length prefixed.
  219. For more details, see the [signing spec](../consensus/signing.md).
  220. Also, see the motivating discussion in
  221. [#1622](https://github.com/tendermint/tendermint/issues/1622).