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.

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