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.

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