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.

256 lines
7.2 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[28:32], a.TokenID.Bytes())
  134. copy(b[23:28], nonceBytes[:])
  135. if a.PublicKey == nil {
  136. return b, fmt.Errorf("Account.PublicKey can not be nil")
  137. }
  138. if babyjub.PointCoordSign(a.PublicKey.X) {
  139. b[22] = 1
  140. }
  141. balanceBytes := a.Balance.Bytes()
  142. copy(b[64-len(balanceBytes):64], balanceBytes)
  143. ayBytes := a.PublicKey.Y.Bytes()
  144. copy(b[96-len(ayBytes):96], ayBytes)
  145. copy(b[108:128], a.EthAddr.Bytes())
  146. return b, nil
  147. }
  148. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  149. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  150. e := [NLeafElems]*big.Int{}
  151. b, err := a.Bytes()
  152. if err != nil {
  153. return e, err
  154. }
  155. e[0] = new(big.Int).SetBytes(b[0:32])
  156. e[1] = new(big.Int).SetBytes(b[32:64])
  157. e[2] = new(big.Int).SetBytes(b[64:96])
  158. e[3] = new(big.Int).SetBytes(b[96:128])
  159. return e, nil
  160. }
  161. // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
  162. func (a *Account) HashValue() (*big.Int, error) {
  163. bi, err := a.BigInts()
  164. if err != nil {
  165. return nil, err
  166. }
  167. return poseidon.Hash(bi[:])
  168. }
  169. // AccountFromBigInts returns a Account from a [5]*big.Int
  170. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  171. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  172. return nil, ErrNotInFF
  173. }
  174. e0B := e[0].Bytes()
  175. e1B := e[1].Bytes()
  176. e2B := e[2].Bytes()
  177. e3B := e[3].Bytes()
  178. var b [32 * NLeafElems]byte
  179. copy(b[32-len(e0B):32], e0B)
  180. copy(b[64-len(e1B):64], e1B)
  181. copy(b[96-len(e2B):96], e2B)
  182. copy(b[128-len(e3B):128], e3B)
  183. return AccountFromBytes(b)
  184. }
  185. // AccountFromBytes returns a Account from a byte array
  186. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  187. tokenID, err := TokenIDFromBytes(b[28:32])
  188. if err != nil {
  189. return nil, err
  190. }
  191. var nonceBytes5 [5]byte
  192. copy(nonceBytes5[:], b[23:28])
  193. nonce := NonceFromBytes(nonceBytes5)
  194. sign := b[22] == 1
  195. balance := new(big.Int).SetBytes(b[40:64])
  196. // Balance is max of 192 bits (24 bytes)
  197. if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  198. return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
  199. }
  200. ay := new(big.Int).SetBytes(b[64:96])
  201. pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
  202. if err != nil {
  203. return nil, err
  204. }
  205. publicKey := babyjub.PublicKey(*pkPoint)
  206. ethAddr := ethCommon.BytesToAddress(b[108:128])
  207. if !cryptoUtils.CheckBigIntInField(balance) {
  208. return nil, ErrNotInFF
  209. }
  210. if !cryptoUtils.CheckBigIntInField(ay) {
  211. return nil, ErrNotInFF
  212. }
  213. a := Account{
  214. TokenID: TokenID(tokenID),
  215. Nonce: nonce,
  216. Balance: balance,
  217. PublicKey: &publicKey,
  218. EthAddr: ethAddr,
  219. }
  220. return &a, nil
  221. }