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.

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