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.

200 lines
5.9 KiB

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