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.

277 lines
7.9 KiB

  1. package common
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "math/big"
  7. "strconv"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/iden3/go-iden3-crypto/babyjub"
  11. "github.com/iden3/go-iden3-crypto/poseidon"
  12. cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
  13. )
  14. const (
  15. // NLeafElems is the number of elements for a leaf
  16. NLeafElems = 4
  17. // maxNonceValue is the maximum value that the Account.Nonce can have
  18. // (40 bits: maxNonceValue=2**40-1)
  19. maxNonceValue = 0xffffffffff
  20. // maxBalanceBytes is the maximum bytes that can use the
  21. // Account.Balance *big.Int
  22. maxBalanceBytes = 24
  23. // IdxBytesLen idx bytes
  24. IdxBytesLen = 6
  25. // maxIdxValue is the maximum value that Idx can have (48 bits:
  26. // maxIdxValue=2**48-1)
  27. maxIdxValue = 0xffffffffffff
  28. // UserThreshold determines the threshold from the User Idxs can be
  29. UserThreshold = 256
  30. // IdxUserThreshold is a Idx type value that determines the threshold
  31. // from the User Idxs can be
  32. IdxUserThreshold = Idx(UserThreshold)
  33. )
  34. var (
  35. // FFAddr is used to check if an ethereum address is 0xff..ff
  36. FFAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
  37. // EmptyAddr is used to check if an ethereum address is 0
  38. EmptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
  39. )
  40. // Idx represents the account Index in the MerkleTree
  41. type Idx uint64
  42. // String returns a string representation of the Idx
  43. func (idx Idx) String() string {
  44. return strconv.Itoa(int(idx))
  45. }
  46. // Bytes returns a byte array representing the Idx
  47. func (idx Idx) Bytes() ([6]byte, error) {
  48. if idx > maxIdxValue {
  49. return [6]byte{}, tracerr.Wrap(ErrIdxOverflow)
  50. }
  51. var idxBytes [8]byte
  52. binary.BigEndian.PutUint64(idxBytes[:], uint64(idx))
  53. var b [6]byte
  54. copy(b[:], idxBytes[2:])
  55. return b, nil
  56. }
  57. // BigInt returns a *big.Int representing the Idx
  58. func (idx Idx) BigInt() *big.Int {
  59. return big.NewInt(int64(idx))
  60. }
  61. // IdxFromBytes returns Idx from a byte array
  62. func IdxFromBytes(b []byte) (Idx, error) {
  63. if len(b) != IdxBytesLen {
  64. return 0, tracerr.Wrap(fmt.Errorf("can not parse Idx, bytes len %d, expected %d",
  65. len(b), IdxBytesLen))
  66. }
  67. var idxBytes [8]byte
  68. copy(idxBytes[2:], b[:])
  69. idx := binary.BigEndian.Uint64(idxBytes[:])
  70. return Idx(idx), nil
  71. }
  72. // IdxFromBigInt converts a *big.Int to Idx type
  73. func IdxFromBigInt(b *big.Int) (Idx, error) {
  74. if b.Int64() > maxIdxValue {
  75. return 0, tracerr.Wrap(ErrNumOverflow)
  76. }
  77. return Idx(uint64(b.Int64())), nil
  78. }
  79. // Nonce represents the nonce value in a uint64, which has the method Bytes
  80. // that returns a byte array of length 5 (40 bits).
  81. type Nonce uint64
  82. // Bytes returns a byte array of length 5 representing the Nonce
  83. func (n Nonce) Bytes() ([5]byte, error) {
  84. if n > maxNonceValue {
  85. return [5]byte{}, tracerr.Wrap(ErrNonceOverflow)
  86. }
  87. var nonceBytes [8]byte
  88. binary.BigEndian.PutUint64(nonceBytes[:], uint64(n))
  89. var b [5]byte
  90. copy(b[:], nonceBytes[3:])
  91. return b, nil
  92. }
  93. // BigInt returns the *big.Int representation of the Nonce value
  94. func (n Nonce) BigInt() *big.Int {
  95. return big.NewInt(int64(n))
  96. }
  97. // NonceFromBytes returns Nonce from a [5]byte
  98. func NonceFromBytes(b [5]byte) Nonce {
  99. var nonceBytes [8]byte
  100. copy(nonceBytes[3:], b[:])
  101. nonce := binary.BigEndian.Uint64(nonceBytes[:])
  102. return Nonce(nonce)
  103. }
  104. // Account is a struct that gives information of the holdings of an address and
  105. // a specific token. Is the data structure that generates the Value stored in
  106. // the leaf of the MerkleTree
  107. type Account struct {
  108. Idx Idx `meddler:"idx"`
  109. TokenID TokenID `meddler:"token_id"`
  110. BatchNum BatchNum `meddler:"batch_num"`
  111. BJJ babyjub.PublicKeyComp `meddler:"bjj"`
  112. EthAddr ethCommon.Address `meddler:"eth_addr"`
  113. Nonce Nonce `meddler:"-"` // max of 40 bits used
  114. Balance *big.Int `meddler:"-"` // max of 192 bits used
  115. }
  116. func (a *Account) String() string {
  117. buf := bytes.NewBufferString("")
  118. fmt.Fprintf(buf, "Idx: %v, ", a.Idx)
  119. fmt.Fprintf(buf, "BJJ: %s..., ", a.BJJ.String()[:10])
  120. fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
  121. fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
  122. fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
  123. fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
  124. fmt.Fprintf(buf, "BatchNum: %v, ", a.BatchNum)
  125. return buf.String()
  126. }
  127. // Bytes returns the bytes representing the Account, in a way that each BigInt
  128. // is represented by 32 bytes, in spite of the BigInt could be represented in
  129. // less bytes (due a small big.Int), so in this way each BigInt is always 32
  130. // bytes and can be automatically parsed from a byte array.
  131. func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
  132. var b [32 * NLeafElems]byte
  133. if a.Nonce > maxNonceValue {
  134. return b, tracerr.Wrap(fmt.Errorf("%s Nonce", ErrNumOverflow))
  135. }
  136. if len(a.Balance.Bytes()) > maxBalanceBytes {
  137. return b, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow))
  138. }
  139. nonceBytes, err := a.Nonce.Bytes()
  140. if err != nil {
  141. return b, tracerr.Wrap(err)
  142. }
  143. copy(b[28:32], a.TokenID.Bytes())
  144. copy(b[23:28], nonceBytes[:])
  145. pkSign, pkY := babyjub.UnpackSignY(a.BJJ)
  146. if pkSign {
  147. b[22] = 1
  148. }
  149. balanceBytes := a.Balance.Bytes()
  150. copy(b[64-len(balanceBytes):64], balanceBytes)
  151. ayBytes := pkY.Bytes()
  152. copy(b[96-len(ayBytes):96], ayBytes)
  153. copy(b[108:128], a.EthAddr.Bytes())
  154. return b, nil
  155. }
  156. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  157. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  158. e := [NLeafElems]*big.Int{}
  159. b, err := a.Bytes()
  160. if err != nil {
  161. return e, tracerr.Wrap(err)
  162. }
  163. e[0] = new(big.Int).SetBytes(b[0:32])
  164. e[1] = new(big.Int).SetBytes(b[32:64])
  165. e[2] = new(big.Int).SetBytes(b[64:96])
  166. e[3] = new(big.Int).SetBytes(b[96:128])
  167. return e, nil
  168. }
  169. // HashValue returns the value of the Account, which is the Poseidon hash of its
  170. // *big.Int representation
  171. func (a *Account) HashValue() (*big.Int, error) {
  172. bi, err := a.BigInts()
  173. if err != nil {
  174. return nil, tracerr.Wrap(err)
  175. }
  176. return poseidon.Hash(bi[:])
  177. }
  178. // AccountFromBigInts returns a Account from a [5]*big.Int
  179. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  180. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  181. return nil, tracerr.Wrap(ErrNotInFF)
  182. }
  183. e0B := e[0].Bytes()
  184. e1B := e[1].Bytes()
  185. e2B := e[2].Bytes()
  186. e3B := e[3].Bytes()
  187. var b [32 * NLeafElems]byte
  188. copy(b[32-len(e0B):32], e0B)
  189. copy(b[64-len(e1B):64], e1B)
  190. copy(b[96-len(e2B):96], e2B)
  191. copy(b[128-len(e3B):128], e3B)
  192. return AccountFromBytes(b)
  193. }
  194. // AccountFromBytes returns a Account from a byte array
  195. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  196. tokenID, err := TokenIDFromBytes(b[28:32])
  197. if err != nil {
  198. return nil, tracerr.Wrap(err)
  199. }
  200. var nonceBytes5 [5]byte
  201. copy(nonceBytes5[:], b[23:28])
  202. nonce := NonceFromBytes(nonceBytes5)
  203. sign := b[22] == 1
  204. balance := new(big.Int).SetBytes(b[40:64])
  205. // Balance is max of 192 bits (24 bytes)
  206. if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  207. return nil, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow))
  208. }
  209. ay := new(big.Int).SetBytes(b[64:96])
  210. publicKeyComp := babyjub.PackSignY(sign, ay)
  211. ethAddr := ethCommon.BytesToAddress(b[108:128])
  212. if !cryptoUtils.CheckBigIntInField(balance) {
  213. return nil, tracerr.Wrap(ErrNotInFF)
  214. }
  215. if !cryptoUtils.CheckBigIntInField(ay) {
  216. return nil, tracerr.Wrap(ErrNotInFF)
  217. }
  218. a := Account{
  219. TokenID: TokenID(tokenID),
  220. Nonce: nonce,
  221. Balance: balance,
  222. BJJ: publicKeyComp,
  223. EthAddr: ethAddr,
  224. }
  225. return &a, nil
  226. }
  227. // IdxNonce is a pair of Idx and Nonce representing an account
  228. type IdxNonce struct {
  229. Idx Idx `db:"idx"`
  230. Nonce Nonce `db:"nonce"`
  231. }
  232. // AccountUpdate represents an account balance and/or nonce update after a
  233. // processed batch
  234. type AccountUpdate struct {
  235. EthBlockNum int64 `meddler:"eth_block_num"`
  236. BatchNum BatchNum `meddler:"batch_num"`
  237. Idx Idx `meddler:"idx"`
  238. Nonce Nonce `meddler:"nonce"`
  239. Balance *big.Int `meddler:"balance,bigint"`
  240. }