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.

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