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.

312 lines
11 KiB

  1. # Encoding
  2. ## Amino
  3. Tendermint uses the proto3 derivative [Amino](https://github.com/tendermint/go-amino) for all data structures.
  4. Think of Amino as an object-oriented proto3 with native JSON support.
  5. The goal of the Amino encoding protocol is to bring parity between application
  6. logic objects and persistence objects.
  7. Please see the [Amino
  8. specification](https://github.com/tendermint/go-amino#amino-encoding-for-go) for
  9. more details.
  10. Notably, every object that satisfies an interface (eg. a particular kind of p2p message,
  11. or a particular kind of pubkey) is registered with a global name, the hash of
  12. which is included in the object's encoding as the so-called "prefix bytes".
  13. We define the `func AminoEncode(obj interface{}) []byte` function to take an
  14. arbitrary object and return the Amino encoded bytes.
  15. ## Byte Arrays
  16. The encoding of a byte array is simply the raw-bytes prefixed with the length of
  17. the array as a `UVarint` (what proto calls a `Varint`).
  18. For details on varints, see the [protobuf
  19. spec](https://developers.google.com/protocol-buffers/docs/encoding#varints).
  20. For example, the byte-array `[0xA, 0xB]` would be encoded as `0x020A0B`,
  21. while a byte-array containing 300 entires beginning with `[0xA, 0xB, ...]` would
  22. be encoded as `0xAC020A0B...` where `0xAC02` is the UVarint encoding of 300.
  23. ## Public Key Cryptography
  24. Tendermint uses Amino to distinguish between different types of private keys,
  25. public keys, and signatures. Additionally, for each public key, Tendermint
  26. defines an Address function that can be used as a more compact identifier in
  27. place of the public key. Here we list the concrete types, their names,
  28. and prefix bytes for public keys and signatures, as well as the address schemes
  29. for each PubKey. Note for brevity we don't
  30. include details of the private keys beyond their type and name, as they can be
  31. derived the same way as the others using Amino.
  32. All registered objects are encoded by Amino using a 4-byte PrefixBytes that
  33. uniquely identifies the object and includes information about its underlying
  34. type. For details on how PrefixBytes are computed, see the [Amino
  35. spec](https://github.com/tendermint/go-amino#computing-the-prefix-and-disambiguation-bytes).
  36. In what follows, we provide the type names and prefix bytes directly.
  37. Notice that when encoding byte-arrays, the length of the byte-array is appended
  38. to the PrefixBytes. Thus the encoding of a byte array becomes `<PrefixBytes> <Length> <ByteArray>`. In other words, to encode any type listed below you do not need to be
  39. familiar with amino encoding.
  40. You can simply use below table and concatenate Prefix || Length (of raw bytes) || raw bytes
  41. ( while || stands for byte concatenation here).
  42. | Type | Name | Prefix | Length | Notes |
  43. | ------------------ | ----------------------------- | ---------- | -------- | ----- |
  44. | PubKeyEd25519 | tendermint/PubKeyEd25519 | 0x1624DE64 | 0x20 | |
  45. | PubKeySecp256k1 | tendermint/PubKeySecp256k1 | 0xEB5AE987 | 0x21 | |
  46. | PrivKeyEd25519 | tendermint/PrivKeyEd25519 | 0xA3288910 | 0x40 | |
  47. | PrivKeySecp256k1 | tendermint/PrivKeySecp256k1 | 0xE1B0F79B | 0x20 | |
  48. | PubKeyMultisigThreshold | tendermint/PubKeyMultisigThreshold | 0x22C1F7E2 | variable | |
  49. ### Example
  50. For example, the 33-byte (or 0x21-byte in hex) Secp256k1 pubkey
  51. `020BD40F225A57ED383B440CF073BC5539D0341F5767D2BF2D78406D00475A2EE9`
  52. would be encoded as
  53. `EB5AE98721020BD40F225A57ED383B440CF073BC5539D0341F5767D2BF2D78406D00475A2EE9`
  54. ### Addresses
  55. Addresses for each public key types are computed as follows:
  56. #### Ed25519
  57. First 20-bytes of the SHA256 hash of the raw 32-byte public key:
  58. ```
  59. address = SHA256(pubkey)[:20]
  60. ```
  61. NOTE: before v0.22.0, this was the RIPEMD160 of the Amino encoded public key.
  62. #### Secp256k1
  63. RIPEMD160 hash of the SHA256 hash of the OpenSSL compressed public key:
  64. ```
  65. address = RIPEMD160(SHA256(pubkey))
  66. ```
  67. This is the same as Bitcoin.
  68. ## Other Common Types
  69. ### BitArray
  70. The BitArray is used in block headers and some consensus messages to signal
  71. whether or not something was done by each validator. BitArray is represented
  72. with a struct containing the number of bits (`Bits`) and the bit-array itself
  73. encoded in base64 (`Elems`).
  74. ```go
  75. type BitArray struct {
  76. Bits int
  77. Elems []uint64
  78. }
  79. ```
  80. This type is easily encoded directly by Amino.
  81. Note BitArray receives a special JSON encoding in the form of `x` and `_`
  82. representing `1` and `0`. Ie. the BitArray `10110` would be JSON encoded as
  83. `"x_xx_"`
  84. ### Part
  85. Part is used to break up blocks into pieces that can be gossiped in parallel
  86. and securely verified using a Merkle tree of the parts.
  87. Part contains the index of the part in the larger set (`Index`), the actual
  88. underlying data of the part (`Bytes`), and a simple Merkle proof that the part is contained in
  89. the larger set (`Proof`).
  90. ```go
  91. type Part struct {
  92. Index int
  93. Bytes byte[]
  94. Proof byte[]
  95. }
  96. ```
  97. ### MakeParts
  98. Encode an object using Amino and slice it into parts.
  99. ```go
  100. func MakeParts(obj interface{}, partSize int) []Part
  101. ```
  102. ## Merkle Trees
  103. For an overview of Merkle trees, see
  104. [wikipedia](https://en.wikipedia.org/wiki/Merkle_tree)
  105. A Simple Tree is a simple compact binary tree for a static list of items. Simple Merkle trees are used in numerous places in Tendermint to compute a cryptographic digest of a data structure. In a Simple Tree, the transactions and validation signatures of a block are hashed using this simple merkle tree logic.
  106. If the number of items is not a power of two, the tree will not be full
  107. and some leaf nodes will be at different levels. Simple Tree tries to
  108. keep both sides of the tree the same size, but the left side may be one
  109. greater, for example:
  110. ```
  111. Simple Tree with 6 items Simple Tree with 7 items
  112. * *
  113. / \ / \
  114. / \ / \
  115. / \ / \
  116. / \ / \
  117. * * * *
  118. / \ / \ / \ / \
  119. / \ / \ / \ / \
  120. / \ / \ / \ / \
  121. * h2 * h5 * * * h6
  122. / \ / \ / \ / \ / \
  123. h0 h1 h3 h4 h0 h1 h2 h3 h4 h5
  124. ```
  125. Tendermint always uses the `TMHASH` hash function, which is equivalent to
  126. SHA256:
  127. ```
  128. func TMHASH(bz []byte) []byte {
  129. return SHA256(bz)
  130. }
  131. ```
  132. ### Simple Merkle Root
  133. The function `SimpleMerkleRoot` is a simple recursive function defined as follows:
  134. ```go
  135. func SimpleMerkleRoot(hashes [][]byte) []byte{
  136. switch len(hashes) {
  137. case 0:
  138. return nil
  139. case 1:
  140. return hashes[0]
  141. default:
  142. left := SimpleMerkleRoot(hashes[:(len(hashes)+1)/2])
  143. right := SimpleMerkleRoot(hashes[(len(hashes)+1)/2:])
  144. return SimpleConcatHash(left, right)
  145. }
  146. }
  147. func SimpleConcatHash(left, right []byte) []byte{
  148. left = encodeByteSlice(left)
  149. right = encodeByteSlice(right)
  150. return TMHASH(append(left, right))
  151. }
  152. ```
  153. Note that the leaves are Amino encoded as byte-arrays (ie. simple Uvarint length
  154. prefix) before being concatenated together and hashed.
  155. Note: we will abuse notion and invoke `SimpleMerkleRoot` with arguments of type `struct` or type `[]struct`.
  156. For `struct` arguments, we compute a `[][]byte` containing the hash of each
  157. field in the struct, in the same order the fields appear in the struct.
  158. For `[]struct` arguments, we compute a `[][]byte` by hashing the individual `struct` elements.
  159. ### Simple Merkle Proof
  160. Proof that a leaf is in a Merkle tree consists of a simple structure:
  161. ```
  162. type SimpleProof struct {
  163. Aunts [][]byte
  164. }
  165. ```
  166. Which is verified using the following:
  167. ```
  168. func (proof SimpleProof) Verify(index, total int, leafHash, rootHash []byte) bool {
  169. computedHash := computeHashFromAunts(index, total, leafHash, proof.Aunts)
  170. return computedHash == rootHash
  171. }
  172. func computeHashFromAunts(index, total int, leafHash []byte, innerHashes [][]byte) []byte{
  173. assert(index < total && index >= 0 && total > 0)
  174. if total == 1{
  175. assert(len(proof.Aunts) == 0)
  176. return leafHash
  177. }
  178. assert(len(innerHashes) > 0)
  179. numLeft := (total + 1) / 2
  180. if index < numLeft {
  181. leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  182. assert(leftHash != nil)
  183. return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1])
  184. }
  185. rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  186. assert(rightHash != nil)
  187. return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash)
  188. }
  189. ```
  190. ### Simple Tree with Dictionaries
  191. The Simple Tree is used to merkelize a list of items, so to merkelize a
  192. (short) dictionary of key-value pairs, encode the dictionary as an
  193. ordered list of `KVPair` structs. The block hash is such a hash
  194. derived from all the fields of the block `Header`. The state hash is
  195. similarly derived.
  196. ### IAVL+ Tree
  197. 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/develop/docs/sdk/core/multistore.md)
  198. ## JSON
  199. ### Amino
  200. Amino also supports JSON encoding - registered types are simply encoded as:
  201. ```
  202. {
  203. "type": "<amino type name>",
  204. "value": <JSON>
  205. }
  206. ```
  207. For instance, an ED25519 PubKey would look like:
  208. ```
  209. {
  210. "type": "tendermint/PubKeyEd25519",
  211. "value": "uZ4h63OFWuQ36ZZ4Bd6NF+/w9fWUwrOncrQsackrsTk="
  212. }
  213. ```
  214. Where the `"value"` is the base64 encoding of the raw pubkey bytes, and the
  215. `"type"` is the amino name for Ed25519 pubkeys.
  216. ### Signed Messages
  217. Signed messages (eg. votes, proposals) in the consensus are encoded using Amino.
  218. When signing, the elements of a message are re-ordered so the fixed-length fields
  219. are first, making it easy to quickly check the type, height, and round.
  220. The `ChainID` is also appended to the end.
  221. We call this encoding the SignBytes. For instance, SignBytes for a vote is the Amino encoding of the following struct:
  222. ```go
  223. type CanonicalVote struct {
  224. Type byte
  225. Height int64 `binary:"fixed64"`
  226. Round int64 `binary:"fixed64"`
  227. Timestamp time.Time
  228. BlockID CanonicalBlockID
  229. ChainID string
  230. }
  231. ```
  232. The field ordering and the fixed sized encoding for the first three fields is optimized to ease parsing of SignBytes
  233. in HSMs. It creates fixed offsets for relevant fields that need to be read in this context.
  234. See [#1622](https://github.com/tendermint/tendermint/issues/1622) for more details.