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.

265 lines
7.5 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", len(b), IdxBytesLen))
  65. }
  66. var idxBytes [8]byte
  67. copy(idxBytes[2:], b[:])
  68. idx := binary.BigEndian.Uint64(idxBytes[:])
  69. return Idx(idx), nil
  70. }
  71. // IdxFromBigInt converts a *big.Int to Idx type
  72. func IdxFromBigInt(b *big.Int) (Idx, error) {
  73. if b.Int64() > maxIdxValue {
  74. return 0, tracerr.Wrap(ErrNumOverflow)
  75. }
  76. return Idx(uint64(b.Int64())), nil
  77. }
  78. // Nonce represents the nonce value in a uint64, which has the method Bytes
  79. // that returns a byte array of length 5 (40 bits).
  80. type Nonce uint64
  81. // Bytes returns a byte array of length 5 representing the Nonce
  82. func (n Nonce) Bytes() ([5]byte, error) {
  83. if n > maxNonceValue {
  84. return [5]byte{}, tracerr.Wrap(ErrNonceOverflow)
  85. }
  86. var nonceBytes [8]byte
  87. binary.BigEndian.PutUint64(nonceBytes[:], uint64(n))
  88. var b [5]byte
  89. copy(b[:], nonceBytes[3:])
  90. return b, nil
  91. }
  92. // BigInt returns the *big.Int representation of the Nonce value
  93. func (n Nonce) BigInt() *big.Int {
  94. return big.NewInt(int64(n))
  95. }
  96. // NonceFromBytes returns Nonce from a [5]byte
  97. func NonceFromBytes(b [5]byte) Nonce {
  98. var nonceBytes [8]byte
  99. copy(nonceBytes[3:], b[:])
  100. nonce := binary.BigEndian.Uint64(nonceBytes[:])
  101. return Nonce(nonce)
  102. }
  103. // Account is a struct that gives information of the holdings of an address and
  104. // a specific token. Is the data structure that generates the Value stored in
  105. // the leaf of the MerkleTree
  106. type Account struct {
  107. Idx Idx `meddler:"idx"`
  108. TokenID TokenID `meddler:"token_id"`
  109. BatchNum BatchNum `meddler:"batch_num"`
  110. BJJ babyjub.PublicKeyComp `meddler:"bjj"`
  111. EthAddr ethCommon.Address `meddler:"eth_addr"`
  112. Nonce Nonce `meddler:"-"` // max of 40 bits used
  113. Balance *big.Int `meddler:"-"` // max of 192 bits used
  114. }
  115. func (a *Account) String() string {
  116. buf := bytes.NewBufferString("")
  117. fmt.Fprintf(buf, "Idx: %v, ", a.Idx)
  118. fmt.Fprintf(buf, "BJJ: %s..., ", a.BJJ.String()[:10])
  119. fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
  120. fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
  121. fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
  122. fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
  123. fmt.Fprintf(buf, "BatchNum: %v, ", a.BatchNum)
  124. return buf.String()
  125. }
  126. // Bytes returns the bytes representing the Account, in a way that each BigInt
  127. // is represented by 32 bytes, in spite of the BigInt could be represented in
  128. // less bytes (due a small big.Int), so in this way each BigInt is always 32
  129. // bytes and can be automatically parsed from a byte array.
  130. func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
  131. var b [32 * NLeafElems]byte
  132. if a.Nonce > maxNonceValue {
  133. return b, tracerr.Wrap(fmt.Errorf("%s Nonce", ErrNumOverflow))
  134. }
  135. if len(a.Balance.Bytes()) > maxBalanceBytes {
  136. return b, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow))
  137. }
  138. nonceBytes, err := a.Nonce.Bytes()
  139. if err != nil {
  140. return b, tracerr.Wrap(err)
  141. }
  142. copy(b[28:32], a.TokenID.Bytes())
  143. copy(b[23:28], nonceBytes[:])
  144. pkSign, pkY := babyjub.UnpackSignY(a.BJJ)
  145. if pkSign {
  146. b[22] = 1
  147. }
  148. balanceBytes := a.Balance.Bytes()
  149. copy(b[64-len(balanceBytes):64], balanceBytes)
  150. ayBytes := pkY.Bytes()
  151. copy(b[96-len(ayBytes):96], ayBytes)
  152. copy(b[108:128], a.EthAddr.Bytes())
  153. return b, nil
  154. }
  155. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  156. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  157. e := [NLeafElems]*big.Int{}
  158. b, err := a.Bytes()
  159. if err != nil {
  160. return e, tracerr.Wrap(err)
  161. }
  162. e[0] = new(big.Int).SetBytes(b[0:32])
  163. e[1] = new(big.Int).SetBytes(b[32:64])
  164. e[2] = new(big.Int).SetBytes(b[64:96])
  165. e[3] = new(big.Int).SetBytes(b[96:128])
  166. return e, nil
  167. }
  168. // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
  169. func (a *Account) HashValue() (*big.Int, error) {
  170. bi, err := a.BigInts()
  171. if err != nil {
  172. return nil, tracerr.Wrap(err)
  173. }
  174. return poseidon.Hash(bi[:])
  175. }
  176. // AccountFromBigInts returns a Account from a [5]*big.Int
  177. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  178. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  179. return nil, tracerr.Wrap(ErrNotInFF)
  180. }
  181. e0B := e[0].Bytes()
  182. e1B := e[1].Bytes()
  183. e2B := e[2].Bytes()
  184. e3B := e[3].Bytes()
  185. var b [32 * NLeafElems]byte
  186. copy(b[32-len(e0B):32], e0B)
  187. copy(b[64-len(e1B):64], e1B)
  188. copy(b[96-len(e2B):96], e2B)
  189. copy(b[128-len(e3B):128], e3B)
  190. return AccountFromBytes(b)
  191. }
  192. // AccountFromBytes returns a Account from a byte array
  193. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  194. tokenID, err := TokenIDFromBytes(b[28:32])
  195. if err != nil {
  196. return nil, tracerr.Wrap(err)
  197. }
  198. var nonceBytes5 [5]byte
  199. copy(nonceBytes5[:], b[23:28])
  200. nonce := NonceFromBytes(nonceBytes5)
  201. sign := b[22] == 1
  202. balance := new(big.Int).SetBytes(b[40:64])
  203. // Balance is max of 192 bits (24 bytes)
  204. if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  205. return nil, tracerr.Wrap(fmt.Errorf("%s Balance", ErrNumOverflow))
  206. }
  207. ay := new(big.Int).SetBytes(b[64:96])
  208. publicKeyComp := babyjub.PackSignY(sign, ay)
  209. ethAddr := ethCommon.BytesToAddress(b[108:128])
  210. if !cryptoUtils.CheckBigIntInField(balance) {
  211. return nil, tracerr.Wrap(ErrNotInFF)
  212. }
  213. if !cryptoUtils.CheckBigIntInField(ay) {
  214. return nil, tracerr.Wrap(ErrNotInFF)
  215. }
  216. a := Account{
  217. TokenID: TokenID(tokenID),
  218. Nonce: nonce,
  219. Balance: balance,
  220. BJJ: publicKeyComp,
  221. EthAddr: ethAddr,
  222. }
  223. return &a, nil
  224. }
  225. // IdxNonce is a pair of Idx and Nonce representing an account
  226. type IdxNonce struct {
  227. Idx Idx `db:"idx"`
  228. Nonce Nonce `db:"nonce"`
  229. }