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.

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