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.

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