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.

258 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, "Idx: %v, ", a.Idx)
  111. fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
  112. fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
  113. fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
  114. fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
  115. fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
  116. fmt.Fprintf(buf, "BatchNum: %v, ", a.BatchNum)
  117. return buf.String()
  118. }
  119. // Bytes returns the bytes representing the Account, in a way that each BigInt
  120. // is represented by 32 bytes, in spite of the BigInt could be represented in
  121. // less bytes (due a small big.Int), so in this way each BigInt is always 32
  122. // bytes and can be automatically parsed from a byte array.
  123. func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
  124. var b [32 * NLeafElems]byte
  125. if a.Nonce > maxNonceValue {
  126. return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
  127. }
  128. if len(a.Balance.Bytes()) > maxBalanceBytes {
  129. return b, fmt.Errorf("%s Balance", ErrNumOverflow)
  130. }
  131. nonceBytes, err := a.Nonce.Bytes()
  132. if err != nil {
  133. return b, err
  134. }
  135. copy(b[28:32], a.TokenID.Bytes())
  136. copy(b[23:28], nonceBytes[:])
  137. if a.PublicKey == nil {
  138. return b, fmt.Errorf("Account.PublicKey can not be nil")
  139. }
  140. if babyjub.PointCoordSign(a.PublicKey.X) {
  141. b[22] = 1
  142. }
  143. balanceBytes := a.Balance.Bytes()
  144. copy(b[64-len(balanceBytes):64], balanceBytes)
  145. ayBytes := a.PublicKey.Y.Bytes()
  146. copy(b[96-len(ayBytes):96], ayBytes)
  147. copy(b[108:128], a.EthAddr.Bytes())
  148. return b, nil
  149. }
  150. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  151. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  152. e := [NLeafElems]*big.Int{}
  153. b, err := a.Bytes()
  154. if err != nil {
  155. return e, err
  156. }
  157. e[0] = new(big.Int).SetBytes(b[0:32])
  158. e[1] = new(big.Int).SetBytes(b[32:64])
  159. e[2] = new(big.Int).SetBytes(b[64:96])
  160. e[3] = new(big.Int).SetBytes(b[96:128])
  161. return e, nil
  162. }
  163. // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
  164. func (a *Account) HashValue() (*big.Int, error) {
  165. bi, err := a.BigInts()
  166. if err != nil {
  167. return nil, err
  168. }
  169. return poseidon.Hash(bi[:])
  170. }
  171. // AccountFromBigInts returns a Account from a [5]*big.Int
  172. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  173. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  174. return nil, ErrNotInFF
  175. }
  176. e0B := e[0].Bytes()
  177. e1B := e[1].Bytes()
  178. e2B := e[2].Bytes()
  179. e3B := e[3].Bytes()
  180. var b [32 * NLeafElems]byte
  181. copy(b[32-len(e0B):32], e0B)
  182. copy(b[64-len(e1B):64], e1B)
  183. copy(b[96-len(e2B):96], e2B)
  184. copy(b[128-len(e3B):128], e3B)
  185. return AccountFromBytes(b)
  186. }
  187. // AccountFromBytes returns a Account from a byte array
  188. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  189. tokenID, err := TokenIDFromBytes(b[28:32])
  190. if err != nil {
  191. return nil, err
  192. }
  193. var nonceBytes5 [5]byte
  194. copy(nonceBytes5[:], b[23:28])
  195. nonce := NonceFromBytes(nonceBytes5)
  196. sign := b[22] == 1
  197. balance := new(big.Int).SetBytes(b[40:64])
  198. // Balance is max of 192 bits (24 bytes)
  199. if !bytes.Equal(b[32:40], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  200. return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
  201. }
  202. ay := new(big.Int).SetBytes(b[64:96])
  203. pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
  204. if err != nil {
  205. return nil, err
  206. }
  207. publicKey := babyjub.PublicKey(*pkPoint)
  208. ethAddr := ethCommon.BytesToAddress(b[108:128])
  209. if !cryptoUtils.CheckBigIntInField(balance) {
  210. return nil, ErrNotInFF
  211. }
  212. if !cryptoUtils.CheckBigIntInField(ay) {
  213. return nil, ErrNotInFF
  214. }
  215. a := Account{
  216. TokenID: TokenID(tokenID),
  217. Nonce: nonce,
  218. Balance: balance,
  219. PublicKey: &publicKey,
  220. EthAddr: ethAddr,
  221. }
  222. return &a, nil
  223. }