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.

178 lines
5.9 KiB

  1. package statedb
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/big"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. "github.com/hermeznetwork/hermez-node/common"
  8. "github.com/hermeznetwork/hermez-node/log"
  9. "github.com/iden3/go-iden3-crypto/babyjub"
  10. "github.com/iden3/go-merkletree"
  11. )
  12. func concatEthAddrTokenID(addr ethCommon.Address, tokenID common.TokenID) []byte {
  13. var b []byte
  14. b = append(b, addr.Bytes()...)
  15. b = append(b[:], tokenID.Bytes()[:]...)
  16. return b
  17. }
  18. func concatEthAddrBJJTokenID(addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) []byte {
  19. pkComp := pk.Compress()
  20. var b []byte
  21. b = append(b, addr.Bytes()...)
  22. b = append(b[:], pkComp[:]...)
  23. b = append(b[:], tokenID.Bytes()[:]...)
  24. return b
  25. }
  26. // setIdxByEthAddrBJJ stores the given Idx in the StateDB as follows:
  27. // - key: Eth Address, value: idx
  28. // - key: EthAddr & BabyJubJub PublicKey Compressed, value: idx
  29. // If Idx already exist for the given EthAddr & BJJ, the remaining Idx will be
  30. // always the smallest one.
  31. func (s *StateDB) setIdxByEthAddrBJJ(idx common.Idx, addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) error {
  32. oldIdx, err := s.GetIdxByEthAddrBJJ(addr, pk, tokenID)
  33. if err == nil {
  34. // EthAddr & BJJ already have an Idx
  35. // check which Idx is smaller
  36. // if new idx is smaller, store the new one
  37. // if new idx is bigger, don't store and return, as the used one will be the old
  38. if idx >= oldIdx {
  39. log.Debug("StateDB.setIdxByEthAddrBJJ: Idx not stored because there already exist a smaller Idx for the given EthAddr & BJJ")
  40. return nil
  41. }
  42. }
  43. if pk == nil {
  44. return fmt.Errorf("BabyJubJub pk not defined")
  45. }
  46. // store idx for EthAddr & BJJ assuming that EthAddr & BJJ still don't
  47. // have an Idx stored in the DB, and if so, the already stored Idx is
  48. // bigger than the given one, so should be updated to the new one
  49. // (smaller)
  50. tx, err := s.db.NewTx()
  51. if err != nil {
  52. return err
  53. }
  54. idxBytes, err := idx.Bytes()
  55. if err != nil {
  56. return err
  57. }
  58. // store Addr&BJJ-idx
  59. k := concatEthAddrBJJTokenID(addr, pk, tokenID)
  60. err = tx.Put(append(PrefixKeyAddrBJJ, k...), idxBytes[:])
  61. if err != nil {
  62. return err
  63. }
  64. // store Addr-idx
  65. k = concatEthAddrTokenID(addr, tokenID)
  66. err = tx.Put(append(PrefixKeyAddr, k...), idxBytes[:])
  67. if err != nil {
  68. return err
  69. }
  70. err = tx.Commit()
  71. if err != nil {
  72. return err
  73. }
  74. return nil
  75. }
  76. // GetIdxByEthAddr returns the smallest Idx in the StateDB for the given
  77. // Ethereum Address. Will return common.Idx(0) and error in case that Idx is
  78. // not found in the StateDB.
  79. func (s *StateDB) GetIdxByEthAddr(addr ethCommon.Address, tokenID common.TokenID) (common.Idx, error) {
  80. k := concatEthAddrTokenID(addr, tokenID)
  81. b, err := s.db.Get(append(PrefixKeyAddr, k...))
  82. if err != nil {
  83. return common.Idx(0), fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), tokenID)
  84. }
  85. idx, err := common.IdxFromBytes(b)
  86. if err != nil {
  87. return common.Idx(0), fmt.Errorf("GetIdxByEthAddr: %s: ToEthAddr: %s, TokenID: %d", err, addr.Hex(), tokenID)
  88. }
  89. return idx, nil
  90. }
  91. // GetIdxByEthAddrBJJ returns the smallest Idx in the StateDB for the given
  92. // Ethereum Address AND the given BabyJubJub PublicKey. If `addr` is the zero
  93. // address, it's ignored in the query. If `pk` is nil, it's ignored in the
  94. // query. Will return common.Idx(0) and error in case that Idx is not found in
  95. // the StateDB.
  96. func (s *StateDB) GetIdxByEthAddrBJJ(addr ethCommon.Address, pk *babyjub.PublicKey, tokenID common.TokenID) (common.Idx, error) {
  97. if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk == nil {
  98. // ToEthAddr
  99. // case ToEthAddr!=0 && ToBJJ=0
  100. return s.GetIdxByEthAddr(addr, tokenID)
  101. } else if !bytes.Equal(addr.Bytes(), common.EmptyAddr.Bytes()) && pk != nil {
  102. // case ToEthAddr!=0 && ToBJJ!=0
  103. k := concatEthAddrBJJTokenID(addr, pk, tokenID)
  104. b, err := s.db.Get(append(PrefixKeyAddrBJJ, k...))
  105. if err != nil {
  106. return common.Idx(0), fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrToIdxNotFound, addr.Hex(), pk, tokenID)
  107. }
  108. idx, err := common.IdxFromBytes(b)
  109. if err != nil {
  110. return common.Idx(0), fmt.Errorf("GetIdxByEthAddrBJJ: %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", err, addr.Hex(), pk, tokenID)
  111. }
  112. return idx, nil
  113. }
  114. // rest of cases (included case ToEthAddr==0) are not possible
  115. return common.Idx(0), fmt.Errorf("GetIdxByEthAddrBJJ: Not found, %s: ToEthAddr: %s, ToBJJ: %s, TokenID: %d", ErrGetIdxNoCase, addr.Hex(), pk, tokenID)
  116. }
  117. func (s *StateDB) getTokenIDsFromIdxs(idxs []common.Idx) (map[common.TokenID]common.Idx, error) {
  118. m := make(map[common.TokenID]common.Idx)
  119. for i := 0; i < len(idxs); i++ {
  120. a, err := s.GetAccount(idxs[i])
  121. if err != nil {
  122. return nil, fmt.Errorf("getTokenIDsFromIdxs error on GetAccount with Idx==%d: %s", idxs[i], err.Error())
  123. }
  124. m[a.TokenID] = idxs[i]
  125. }
  126. return m, nil
  127. }
  128. func siblingsToZKInputFormat(s []*merkletree.Hash) []*big.Int {
  129. b := make([]*big.Int, len(s))
  130. for i := 0; i < len(s); i++ {
  131. b[i] = s[i].BigInt()
  132. }
  133. return b
  134. }
  135. // BJJCompressedTo256BigInts returns a [256]*big.Int array with the bit
  136. // representation of the babyjub.PublicKeyComp
  137. func BJJCompressedTo256BigInts(pkComp babyjub.PublicKeyComp) [256]*big.Int {
  138. var r [256]*big.Int
  139. b := pkComp[:]
  140. for i := 0; i < 256; i++ {
  141. if b[i/8]&(1<<(i%8)) == 0 {
  142. r[i] = big.NewInt(0)
  143. } else {
  144. r[i] = big.NewInt(1)
  145. }
  146. }
  147. return r
  148. }
  149. // formatAccumulatedFees returns an array of [nFeeAccounts]*big.Int containing
  150. // the balance of each FeeAccount, taken from the 'collectedFees' map, in the
  151. // order of the 'orderTokenIDs'
  152. func formatAccumulatedFees(collectedFees map[common.TokenID]*big.Int, orderTokenIDs []*big.Int) []*big.Int {
  153. accFeeOut := make([]*big.Int, len(orderTokenIDs))
  154. for i := 0; i < len(orderTokenIDs); i++ {
  155. tokenID := common.TokenIDFromBigInt(orderTokenIDs[i])
  156. if _, ok := collectedFees[tokenID]; ok {
  157. accFeeOut[i] = collectedFees[tokenID]
  158. } else {
  159. accFeeOut[i] = big.NewInt(0)
  160. }
  161. }
  162. return accFeeOut
  163. }