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.

194 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.LittleEndian.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.LittleEndian.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 is represented by 32 bytes, in spite of the BigInt could be represented in less bytes (due a small big.Int), so in this way each BigInt is always 32 bytes and can be automatically parsed from a byte array.
  75. func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
  76. var b [32 * NLeafElems]byte
  77. if a.Nonce > maxNonceValue {
  78. return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
  79. }
  80. if len(a.Balance.Bytes()) > maxBalanceBytes {
  81. return b, fmt.Errorf("%s Balance", ErrNumOverflow)
  82. }
  83. nonceBytes, err := a.Nonce.Bytes()
  84. if err != nil {
  85. return b, err
  86. }
  87. copy(b[0:4], a.TokenID.Bytes())
  88. copy(b[4:9], nonceBytes[:])
  89. if babyjub.PointCoordSign(a.PublicKey.X) {
  90. b[10] = 1
  91. }
  92. copy(b[32:64], SwapEndianness(a.Balance.Bytes())) // SwapEndianness, as big.Int uses BigEndian
  93. copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
  94. copy(b[96:116], a.EthAddr.Bytes())
  95. return b, nil
  96. }
  97. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  98. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  99. e := [NLeafElems]*big.Int{}
  100. b, err := a.Bytes()
  101. if err != nil {
  102. return e, err
  103. }
  104. e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
  105. e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
  106. e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
  107. e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
  108. return e, nil
  109. }
  110. // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
  111. func (a *Account) HashValue() (*big.Int, error) {
  112. b0 := big.NewInt(0)
  113. toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
  114. lBI, err := a.BigInts()
  115. if err != nil {
  116. return nil, err
  117. }
  118. copy(toHash[:], lBI[:])
  119. v, err := poseidon.Hash(toHash)
  120. return v, err
  121. }
  122. // AccountFromBigInts returns a Account from a [5]*big.Int
  123. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  124. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  125. return nil, ErrNotInFF
  126. }
  127. var b [32 * NLeafElems]byte
  128. copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
  129. copy(b[32:64], SwapEndianness(e[1].Bytes()))
  130. copy(b[64:96], SwapEndianness(e[2].Bytes()))
  131. copy(b[96:128], SwapEndianness(e[3].Bytes()))
  132. return AccountFromBytes(b)
  133. }
  134. // AccountFromBytes returns a Account from a byte array
  135. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  136. tokenID := binary.LittleEndian.Uint32(b[0:4])
  137. var nonceBytes5 [5]byte
  138. copy(nonceBytes5[:], b[4:9])
  139. nonce := NonceFromBytes(nonceBytes5)
  140. sign := b[10] == 1
  141. balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
  142. if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  143. return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
  144. }
  145. ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
  146. pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
  147. if err != nil {
  148. return nil, err
  149. }
  150. publicKey := babyjub.PublicKey(*pkPoint)
  151. ethAddr := ethCommon.BytesToAddress(b[96:116])
  152. if !cryptoUtils.CheckBigIntInField(balance) {
  153. return nil, ErrNotInFF
  154. }
  155. if !cryptoUtils.CheckBigIntInField(ay) {
  156. return nil, ErrNotInFF
  157. }
  158. a := Account{
  159. TokenID: TokenID(tokenID),
  160. Nonce: nonce,
  161. Balance: balance,
  162. PublicKey: &publicKey,
  163. EthAddr: ethAddr,
  164. }
  165. return &a, nil
  166. }