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.

150 lines
4.6 KiB

  1. package common
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "math/big"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/iden3/go-iden3-crypto/babyjub"
  9. "github.com/iden3/go-iden3-crypto/poseidon"
  10. cryptoUtils "github.com/iden3/go-iden3-crypto/utils"
  11. )
  12. const (
  13. // NLeafElems is the number of elements for a leaf
  14. NLeafElems = 4
  15. // maxNonceValue is the maximum value that the Account.Nonce can have (40 bits: maxNonceValue=2**40-1)
  16. maxNonceValue = 0xffffffffff
  17. // maxBalanceBytes is the maximum bytes that can use the Account.Balance *big.Int
  18. maxBalanceBytes = 24
  19. )
  20. // 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
  21. type Account struct {
  22. TokenID TokenID
  23. Nonce Nonce // max of 40 bits used
  24. Balance *big.Int // max of 192 bits used
  25. PublicKey *babyjub.PublicKey
  26. EthAddr ethCommon.Address
  27. }
  28. func (a *Account) String() string {
  29. buf := bytes.NewBufferString("")
  30. fmt.Fprintf(buf, "PublicKey: %s..., ", a.PublicKey.String()[:10])
  31. fmt.Fprintf(buf, "EthAddr: %s..., ", a.EthAddr.String()[:10])
  32. fmt.Fprintf(buf, "TokenID: %v, ", a.TokenID)
  33. fmt.Fprintf(buf, "Nonce: %d, ", a.Nonce)
  34. fmt.Fprintf(buf, "Balance: %s, ", a.Balance.String())
  35. return buf.String()
  36. }
  37. // Bytes returns the bytes representing the Account, in a way that each BigInt is represented by 32 bytes, in spite of the BigInt could be represented in less bytes (due a small big.Int), so in this way each BigInt is always 32 bytes and can be automatically parsed from a byte array.
  38. func (a *Account) Bytes() ([32 * NLeafElems]byte, error) {
  39. var b [32 * NLeafElems]byte
  40. if a.Nonce > maxNonceValue {
  41. return b, fmt.Errorf("%s Nonce", ErrNumOverflow)
  42. }
  43. if len(a.Balance.Bytes()) > maxBalanceBytes {
  44. return b, fmt.Errorf("%s Balance", ErrNumOverflow)
  45. }
  46. nonceBytes, err := a.Nonce.Bytes()
  47. if err != nil {
  48. return b, err
  49. }
  50. copy(b[0:4], a.TokenID.Bytes())
  51. copy(b[4:9], nonceBytes[:])
  52. if babyjub.PointCoordSign(a.PublicKey.X) {
  53. b[10] = 1
  54. }
  55. copy(b[32:64], SwapEndianness(a.Balance.Bytes())) // SwapEndianness, as big.Int uses BigEndian
  56. copy(b[64:96], SwapEndianness(a.PublicKey.Y.Bytes()))
  57. copy(b[96:116], a.EthAddr.Bytes())
  58. return b, nil
  59. }
  60. // BigInts returns the [5]*big.Int, where each *big.Int is inside the Finite Field
  61. func (a *Account) BigInts() ([NLeafElems]*big.Int, error) {
  62. e := [NLeafElems]*big.Int{}
  63. b, err := a.Bytes()
  64. if err != nil {
  65. return e, err
  66. }
  67. e[0] = new(big.Int).SetBytes(SwapEndianness(b[0:32]))
  68. e[1] = new(big.Int).SetBytes(SwapEndianness(b[32:64]))
  69. e[2] = new(big.Int).SetBytes(SwapEndianness(b[64:96]))
  70. e[3] = new(big.Int).SetBytes(SwapEndianness(b[96:128]))
  71. return e, nil
  72. }
  73. // HashValue returns the value of the Account, which is the Poseidon hash of its *big.Int representation
  74. func (a *Account) HashValue() (*big.Int, error) {
  75. b0 := big.NewInt(0)
  76. toHash := []*big.Int{b0, b0, b0, b0, b0, b0}
  77. lBI, err := a.BigInts()
  78. if err != nil {
  79. return nil, err
  80. }
  81. copy(toHash[:], lBI[:])
  82. v, err := poseidon.Hash(toHash)
  83. return v, err
  84. }
  85. // AccountFromBigInts returns a Account from a [5]*big.Int
  86. func AccountFromBigInts(e [NLeafElems]*big.Int) (*Account, error) {
  87. if !cryptoUtils.CheckBigIntArrayInField(e[:]) {
  88. return nil, ErrNotInFF
  89. }
  90. var b [32 * NLeafElems]byte
  91. copy(b[0:32], SwapEndianness(e[0].Bytes())) // SwapEndianness, as big.Int uses BigEndian
  92. copy(b[32:64], SwapEndianness(e[1].Bytes()))
  93. copy(b[64:96], SwapEndianness(e[2].Bytes()))
  94. copy(b[96:128], SwapEndianness(e[3].Bytes()))
  95. return AccountFromBytes(b)
  96. }
  97. // AccountFromBytes returns a Account from a byte array
  98. func AccountFromBytes(b [32 * NLeafElems]byte) (*Account, error) {
  99. tokenID := binary.LittleEndian.Uint32(b[0:4])
  100. var nonceBytes5 [5]byte
  101. copy(nonceBytes5[:], b[4:9])
  102. nonce := NonceFromBytes(nonceBytes5)
  103. sign := b[10] == 1
  104. balance := new(big.Int).SetBytes(SwapEndianness(b[32:56])) // b[32:56], as Balance is 192 bits (24 bytes)
  105. if !bytes.Equal(b[56:64], []byte{0, 0, 0, 0, 0, 0, 0, 0}) {
  106. return nil, fmt.Errorf("%s Balance", ErrNumOverflow)
  107. }
  108. ay := new(big.Int).SetBytes(SwapEndianness(b[64:96]))
  109. pkPoint, err := babyjub.PointFromSignAndY(sign, ay)
  110. if err != nil {
  111. return nil, err
  112. }
  113. publicKey := babyjub.PublicKey(*pkPoint)
  114. ethAddr := ethCommon.BytesToAddress(b[96:116])
  115. if !cryptoUtils.CheckBigIntInField(balance) {
  116. return nil, ErrNotInFF
  117. }
  118. if !cryptoUtils.CheckBigIntInField(ay) {
  119. return nil, ErrNotInFF
  120. }
  121. a := Account{
  122. TokenID: TokenID(tokenID),
  123. Nonce: nonce,
  124. Balance: balance,
  125. PublicKey: &publicKey,
  126. EthAddr: ethAddr,
  127. }
  128. return &a, nil
  129. }