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.

273 lines
9.0 KiB

  1. # Tendermint 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>
  39. <Length> <ByteArray>`. In other words, to encode any type listed below you do not need to be
  40. familiar with amino encoding.
  41. You can simply use below table and concatenate Prefix || Length (of raw bytes) || raw bytes
  42. ( while || stands for byte concatenation here).
  43. | Type | Name | Prefix | Length |
  44. | ---- | ---- | ------ | ----- |
  45. | PubKeyEd25519 | tendermint/PubKeyEd25519 | 0x1624DE62 | 0x20 |
  46. | PubKeyLedgerEd25519 | tendermint/PubKeyLedgerEd25519 | 0x5C3453B2 | 0x20 |
  47. | PubKeySecp256k1 | tendermint/PubKeySecp256k1 | 0xEB5AE982 | 0x21 |
  48. | PrivKeyEd25519 | tendermint/PrivKeyEd25519 | 0xA3288912 | 0x40 |
  49. | PrivKeySecp256k1 | tendermint/PrivKeySecp256k1 | 0xE1B0F79A | 0x20 |
  50. | PrivKeyLedgerSecp256k1 | tendermint/PrivKeyLedgerSecp256k1 | 0x10CAB393 | variable |
  51. | PrivKeyLedgerEd25519 | tendermint/PrivKeyLedgerEd25519 | 0x0CFEEF9B | variable |
  52. | SignatureEd25519 | tendermint/SignatureKeyEd25519 | 0x3DA1DB2A | 0x40 |
  53. | SignatureSecp256k1 | tendermint/SignatureKeySecp256k1 | 0x16E1FEEA | variable |
  54. ### Examples
  55. 1. For example, the 33-byte (or 0x21-byte in hex) Secp256k1 pubkey
  56. `020BD40F225A57ED383B440CF073BC5539D0341F5767D2BF2D78406D00475A2EE9`
  57. would be encoded as
  58. `EB5AE98221020BD40F225A57ED383B440CF073BC5539D0341F5767D2BF2D78406D00475A2EE9`
  59. 2. For example, the variable size Secp256k1 signature (in this particular example 70 or 0x46 bytes)
  60. `304402201CD4B8C764D2FD8AF23ECFE6666CA8A53886D47754D951295D2D311E1FEA33BF02201E0F906BB1CF2C30EAACFFB032A7129358AFF96B9F79B06ACFFB18AC90C2ADD7`
  61. would be encoded as
  62. `16E1FEEA46304402201CD4B8C764D2FD8AF23ECFE6666CA8A53886D47754D951295D2D311E1FEA33BF02201E0F906BB1CF2C30EAACFFB032A7129358AFF96B9F79B06ACFFB18AC90C2ADD7`
  63. ### Addresses
  64. Addresses for each public key types are computed as follows:
  65. #### Ed25519
  66. First 20-bytes of the SHA256 hash of the raw 32-byte public key:
  67. ```
  68. address = SHA256(pubkey)[:20]
  69. ```
  70. NOTE: before v0.22.0, this was the RIPEMD160 of the Amino encoded public key.
  71. #### Secp256k1
  72. RIPEMD160 hash of the SHA256 hash of the OpenSSL compressed public key:
  73. ```
  74. address = RIPEMD160(SHA256(pubkey))
  75. ```
  76. This is the same as Bitcoin.
  77. ## Other Common Types
  78. ### BitArray
  79. The BitArray is used in block headers and some consensus messages to signal
  80. whether or not something was done by each validator. BitArray is represented
  81. with a struct containing the number of bits (`Bits`) and the bit-array itself
  82. encoded in base64 (`Elems`).
  83. ```go
  84. type BitArray struct {
  85. Bits int
  86. Elems []uint64
  87. }
  88. ```
  89. This type is easily encoded directly by Amino.
  90. Note BitArray receives a special JSON encoding in the form of `x` and `_`
  91. representing `1` and `0`. Ie. the BitArray `10110` would be JSON encoded as
  92. `"x_xx_"`
  93. ### Part
  94. Part is used to break up blocks into pieces that can be gossiped in parallel
  95. and securely verified using a Merkle tree of the parts.
  96. Part contains the index of the part in the larger set (`Index`), the actual
  97. underlying data of the part (`Bytes`), and a simple Merkle proof that the part is contained in
  98. the larger set (`Proof`).
  99. ```go
  100. type Part struct {
  101. Index int
  102. Bytes byte[]
  103. Proof byte[]
  104. }
  105. ```
  106. ### MakeParts
  107. Encode an object using Amino and slice it into parts.
  108. ```go
  109. func MakeParts(obj interface{}, partSize int) []Part
  110. ```
  111. ## Merkle Trees
  112. Simple Merkle trees are used in numerous places in Tendermint to compute a cryptographic digest of a data structure.
  113. RIPEMD160 is always used as the hashing function.
  114. ### Simple Merkle Root
  115. The function `SimpleMerkleRoot` is a simple recursive function defined as follows:
  116. ```go
  117. func SimpleMerkleRoot(hashes [][]byte) []byte{
  118. switch len(hashes) {
  119. case 0:
  120. return nil
  121. case 1:
  122. return hashes[0]
  123. default:
  124. left := SimpleMerkleRoot(hashes[:(len(hashes)+1)/2])
  125. right := SimpleMerkleRoot(hashes[(len(hashes)+1)/2:])
  126. return SimpleConcatHash(left, right)
  127. }
  128. }
  129. func SimpleConcatHash(left, right []byte) []byte{
  130. left = encodeByteSlice(left)
  131. right = encodeByteSlice(right)
  132. return RIPEMD160 (append(left, right))
  133. }
  134. ```
  135. Note that the leaves are Amino encoded as byte-arrays (ie. simple Uvarint length
  136. prefix) before being concatenated together and hashed.
  137. Note: we will abuse notion and invoke `SimpleMerkleRoot` with arguments of type `struct` or type `[]struct`.
  138. For `struct` arguments, we compute a `[][]byte` by sorting elements of the `struct` according to
  139. field name and then hashing them.
  140. For `[]struct` arguments, we compute a `[][]byte` by hashing the individual `struct` elements.
  141. ### Simple Merkle Proof
  142. Proof that a leaf is in a Merkle tree consists of a simple structure:
  143. ```
  144. type SimpleProof struct {
  145. Aunts [][]byte
  146. }
  147. ```
  148. Which is verified using the following:
  149. ```
  150. func (proof SimpleProof) Verify(index, total int, leafHash, rootHash []byte) bool {
  151. computedHash := computeHashFromAunts(index, total, leafHash, proof.Aunts)
  152. return computedHash == rootHash
  153. }
  154. func computeHashFromAunts(index, total int, leafHash []byte, innerHashes [][]byte) []byte{
  155. assert(index < total && index >= 0 && total > 0)
  156. if total == 1{
  157. assert(len(proof.Aunts) == 0)
  158. return leafHash
  159. }
  160. assert(len(innerHashes) > 0)
  161. numLeft := (total + 1) / 2
  162. if index < numLeft {
  163. leftHash := computeHashFromAunts(index, numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  164. assert(leftHash != nil)
  165. return SimpleHashFromTwoHashes(leftHash, innerHashes[len(innerHashes)-1])
  166. }
  167. rightHash := computeHashFromAunts(index-numLeft, total-numLeft, leafHash, innerHashes[:len(innerHashes)-1])
  168. assert(rightHash != nil)
  169. return SimpleHashFromTwoHashes(innerHashes[len(innerHashes)-1], rightHash)
  170. }
  171. ```
  172. ## JSON
  173. ### Amino
  174. TODO: improve this
  175. Amino also supports JSON encoding - registered types are simply encoded as:
  176. ```
  177. {
  178. "type": "<DisfixBytes>",
  179. "value": <JSON>
  180. }
  181. ```
  182. For instance, an ED25519 PubKey would look like:
  183. ```
  184. {
  185. "type": "tendermint/PubKeyEd25519",
  186. "value": "uZ4h63OFWuQ36ZZ4Bd6NF+/w9fWUwrOncrQsackrsTk="
  187. }
  188. ```
  189. Where the `"value"` is the base64 encoding of the raw pubkey bytes, and the
  190. `"type"` is the full disfix bytes for Ed25519 pubkeys.
  191. ### Signed Messages
  192. Signed messages (eg. votes, proposals) in the consensus are encoded using Amino-JSON, rather than in the standard binary format.
  193. When signing, the elements of a message are sorted by key and the sorted message is embedded in an
  194. outer JSON that includes a `chain_id` field.
  195. We call this encoding the CanonicalSignBytes. For instance, CanonicalSignBytes for a vote would look
  196. like:
  197. ```json
  198. {"chain_id":"my-chain-id","vote":{"block_id":{"hash":DEADBEEF,"parts":{"hash":BEEFDEAD,"total":3}},"height":3,"round":2,"timestamp":1234567890, "type":2}
  199. ```
  200. Note how the fields within each level are sorted.