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.

213 lines
6.3 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/iden3/go-iden3-crypto/babyjub"
  10. "github.com/iden3/go-iden3-crypto/poseidon"
  11. cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
  12. )
  13. const (
  14. // NLeafElems is the number of elements for a leaf
  15. NLeafElems = 4
  16. // maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1)
  17. maxNonceValue = 0xffffffffff
  18. // maxBalanceBytes is the maximum bytes that can use the Account.Balance *big.Int
  19. maxBalanceBytes = 24
  20. idxBytesLen = 4
  21. // maxIdxValue is the maximum value that Idx can have (32 bits: maxIdxValue=2**32-1)
  22. maxIdxValue = 0xffffffff
  23. // userThreshold determines the threshold from the User Idxs can be
  24. userThreshold = 256
  25. // IdxUserThreshold is a Idx type value that determines the threshold
  26. // from the User Idxs can be
  27. IdxUserThreshold = Idx(userThreshold)
  28. )
  29. var (
  30. // FFAddr is used to check if an ethereum address is 0xff..ff
  31. FFAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
  32. // EmptyAddr is used to check if an ethereum address is 0
  33. EmptyAddr = ethCommon.HexToAddress("0x0000000000000000000000000000000000000000")
  34. )
  35. // Idx represents the account Index in the MerkleTree
  36. type Idx uint32
  37. // String returns a string representation of the Idx
  38. func (idx Idx) String() string {
  39. return strconv.Itoa(int(idx))
  40. }
  41. // Bytes returns a byte array representing the Idx
  42. func (idx Idx) Bytes() []byte {
  43. var b [4]byte
  44. binary.BigEndian.PutUint32(b[:], uint32(idx))
  45. return b[:]
  46. }
  47. // BigInt returns a *big.Int representing the Idx
  48. func (idx Idx) BigInt() *big.Int {
  49. return big.NewInt(int64(idx))
  50. }
  51. // IdxFromBytes returns Idx from a byte array
  52. func IdxFromBytes(b []byte) (Idx, error) {
  53. if len(b) != idxBytesLen {
  54. return 0, fmt.Errorf("can not parse Idx, bytes len %d, expected 4", len(b))
  55. }
  56. idx := binary.BigEndian.Uint32(b[:4])
  57. return Idx(idx), nil
  58. }
  59. // IdxFromBigInt converts a *big.Int to Idx type
  60. func IdxFromBigInt(b *big.Int) (Idx, error) {
  61. if b.Int64() > maxIdxValue {
  62. return 0, ErrNumOverflow
  63. }
  64. return Idx(uint32(b.Int64())), nil
  65. }
  66. // 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
  67. type Account struct {
  68. Idx Idx `meddler:"idx"`
  69. TokenID TokenID `meddler:"token_id"`
  70. BatchNum BatchNum `meddler:"batch_num"`
  71. PublicKey *babyjub.PublicKey `meddler:"bjj"`
  72. EthAddr ethCommon.Address `meddler:"eth_addr"`
  73. Nonce Nonce `meddler:"-"` // max of 40 bits used
  74. Balance *big.Int `meddler:"-"` // max of 192 bits used
  75. }
  76. func (a *Account) String() string {
  77. buf := bytes.NewBufferString("")
  78. fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
  79. fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
  80. fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
  81. fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
  82. fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
  83. return buf.String()
  84. }
  85. // Bytes returns the bytes representing the Account, in a way that each BigInt
  86. // is represented by 32 bytes, in spite of the BigInt could be represented in
  87. // less bytes (due a small big.Int), so in this way each BigInt is always 32
  88. // bytes and can be automatically parsed from a byte array.
  89. func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
  90. var b [32 * NLeafElems]byte
  91. if a.Nonce > maxNonceValue {
  92. return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
  93. }
  94. if len(a.Balance.Bytes()) > maxBalanceBytes {
  95. return b, fmt.Errorf("%s Balance", ErrNumOverflow)
  96. }
  97. nonceBytes, err := a.Nonce.Bytes()
  98. if err != nil {
  99. return b, err
  100. }
  101. copy(b[0:4], a.TokenID.Bytes())
  102. copy(b[4:9], nonceBytes[:])
  103. if babyjub.PointCoordSign(a.PublicKey.X) {
  104. b[10] = 1
  105. }
  106. copy(b[32:64], SwapEndianness(a.Balance.Bytes()))
  107. copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
  108. copy(b[96:116], a.EthAddr.Bytes())
  109. return b, nil
  110. }
  111. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  112. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  113. e := [NLeafElems]*big.Int{}
  114. b, err := a.Bytes()
  115. if err != nil {
  116. return e, err
  117. }
  118. e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
  119. e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
  120. e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
  121. e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
  122. return e, nil
  123. }
  124. // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
  125. func (a *Account) HashValue() (*big.Int, error) {
  126. b0 := big.NewInt(0)
  127. toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
  128. lBI, err := a.BigInts()
  129. if err != nil {
  130. return nil, err
  131. }
  132. copy(toHash[:], lBI[:])
  133. v, err := poseidon.Hash(toHash)
  134. return v, err
  135. }
  136. // AccountFromBigInts returns a Account from a [5]*big.Int
  137. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  138. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  139. return nil, ErrNotInFF
  140. }
  141. var b [32 * NLeafElems]byte
  142. copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
  143. copy(b[32:64], SwapEndianness(e[1].Bytes()))
  144. copy(b[64:96], SwapEndianness(e[2].Bytes()))
  145. copy(b[96:128], SwapEndianness(e[3].Bytes()))
  146. return AccountFromBytes(b)
  147. }
  148. // AccountFromBytes returns a Account from a byte array
  149. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  150. tokenID, err := TokenIDFromBytes(b[0:4])
  151. if err != nil {
  152. return nil, err
  153. }
  154. var nonceBytes5 [5]byte
  155. copy(nonceBytes5[:], b[4:9])
  156. nonce := NonceFromBytes(nonceBytes5)
  157. sign := b[10] == 1
  158. balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
  159. if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  160. return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
  161. }
  162. ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
  163. pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
  164. if err != nil {
  165. return nil, err
  166. }
  167. publicKey := babyjub.PublicKey(*pkPoint)
  168. ethAddr := ethCommon.BytesToAddress(b[96:116])
  169. if !cryptoUtils.CheckBigIntInField(balance) {
  170. return nil, ErrNotInFF
  171. }
  172. if !cryptoUtils.CheckBigIntInField(ay) {
  173. return nil, ErrNotInFF
  174. }
  175. a := Account{
  176. TokenID: TokenID(tokenID),
  177. Nonce: nonce,
  178. Balance: balance,
  179. PublicKey: &publicKey,
  180. EthAddr: ethAddr,
  181. }
  182. return &a, nil
  183. }