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.

387 lines
12 KiB

  1. package statedb
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/big"
  6. "github.com/hermeznetwork/hermez-node/common"
  7. "github.com/hermeznetwork/hermez-node/db/kvdb"
  8. "github.com/hermeznetwork/hermez-node/log"
  9. "github.com/hermeznetwork/tracerr"
  10. "github.com/iden3/go-merkletree"
  11. "github.com/iden3/go-merkletree/db"
  12. )
  13. var (
  14. // ErrStateDBWithoutMT is used when a method that requires a MerkleTree
  15. // is called in a StateDB that does not have a MerkleTree defined
  16. ErrStateDBWithoutMT = errors.New("Can not call method to use MerkleTree in a StateDB without MerkleTree")
  17. // ErrAccountAlreadyExists is used when CreateAccount is called and the
  18. // Account already exists
  19. ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists")
  20. // ErrToIdxNotFound is used when trying to get the ToIdx from ToEthAddr
  21. // or ToEthAddr&ToBJJ
  22. ErrToIdxNotFound = errors.New("ToIdx can not be found")
  23. // ErrGetIdxNoCase is used when trying to get the Idx from EthAddr &
  24. // BJJ with not compatible combination
  25. ErrGetIdxNoCase = errors.New("Can not get Idx due unexpected combination of ethereum Address & BabyJubJub PublicKey")
  26. // PrefixKeyIdx is the key prefix for idx in the db
  27. PrefixKeyIdx = []byte("i:")
  28. // PrefixKeyAccHash is the key prefix for account hash in the db
  29. PrefixKeyAccHash = []byte("h:")
  30. // PrefixKeyMT is the key prefix for merkle tree in the db
  31. PrefixKeyMT = []byte("m:")
  32. // PrefixKeyAddr is the key prefix for address in the db
  33. PrefixKeyAddr = []byte("a:")
  34. // PrefixKeyAddrBJJ is the key prefix for address-babyjubjub in the db
  35. PrefixKeyAddrBJJ = []byte("ab:")
  36. )
  37. const (
  38. // TypeSynchronizer defines a StateDB used by the Synchronizer, that
  39. // generates the ExitTree when processing the txs
  40. TypeSynchronizer = "synchronizer"
  41. // TypeTxSelector defines a StateDB used by the TxSelector, without
  42. // computing ExitTree neither the ZKInputs
  43. TypeTxSelector = "txselector"
  44. // TypeBatchBuilder defines a StateDB used by the BatchBuilder, that
  45. // generates the ExitTree and the ZKInput when processing the txs
  46. TypeBatchBuilder = "batchbuilder"
  47. )
  48. // TypeStateDB determines the type of StateDB
  49. type TypeStateDB string
  50. // StateDB represents the StateDB object
  51. type StateDB struct {
  52. path string
  53. Typ TypeStateDB
  54. db *kvdb.KVDB
  55. MT *merkletree.MerkleTree
  56. keep int
  57. }
  58. // NewStateDB creates a new StateDB, allowing to use an in-memory or in-disk
  59. // storage. Checkpoints older than the value defined by `keep` will be
  60. // deleted.
  61. func NewStateDB(pathDB string, keep int, typ TypeStateDB, nLevels int) (*StateDB, error) {
  62. var kv *kvdb.KVDB
  63. var err error
  64. kv, err = kvdb.NewKVDB(pathDB, keep)
  65. if err != nil {
  66. return nil, tracerr.Wrap(err)
  67. }
  68. var mt *merkletree.MerkleTree = nil
  69. if typ == TypeSynchronizer || typ == TypeBatchBuilder {
  70. mt, err = merkletree.NewMerkleTree(kv.StorageWithPrefix(PrefixKeyMT), nLevels)
  71. if err != nil {
  72. return nil, tracerr.Wrap(err)
  73. }
  74. }
  75. if typ == TypeTxSelector && nLevels != 0 {
  76. return nil, tracerr.Wrap(fmt.Errorf("invalid StateDB parameters: StateDB type==TypeStateDB can not have nLevels!=0"))
  77. }
  78. return &StateDB{
  79. path: pathDB,
  80. db: kv,
  81. MT: mt,
  82. Typ: typ,
  83. keep: keep,
  84. }, nil
  85. }
  86. // MakeCheckpoint does a checkpoint at the given batchNum in the defined path.
  87. // Internally this advances & stores the current BatchNum, and then stores a
  88. // Checkpoint of the current state of the StateDB.
  89. func (s *StateDB) MakeCheckpoint() error {
  90. log.Debugw("Making StateDB checkpoint", "batch", s.CurrentBatch())
  91. return s.db.MakeCheckpoint()
  92. }
  93. // CurrentBatch returns the current in-memory CurrentBatch of the StateDB.db
  94. func (s *StateDB) CurrentBatch() common.BatchNum {
  95. return s.db.CurrentBatch
  96. }
  97. // CurrentIdx returns the current in-memory CurrentIdx of the StateDB.db
  98. func (s *StateDB) CurrentIdx() common.Idx {
  99. return s.db.CurrentIdx
  100. }
  101. // GetCurrentBatch returns the current BatchNum stored in the StateDB.db
  102. func (s *StateDB) GetCurrentBatch() (common.BatchNum, error) {
  103. return s.db.GetCurrentBatch()
  104. }
  105. // GetCurrentIdx returns the stored Idx from the localStateDB, which is the
  106. // last Idx used for an Account in the localStateDB.
  107. func (s *StateDB) GetCurrentIdx() (common.Idx, error) {
  108. return s.db.GetCurrentIdx()
  109. }
  110. // SetCurrentIdx stores Idx in the StateDB
  111. func (s *StateDB) SetCurrentIdx(idx common.Idx) error {
  112. return s.db.SetCurrentIdx(idx)
  113. }
  114. // Reset resets the StateDB to the checkpoint at the given batchNum. Reset
  115. // does not delete the checkpoints between old current and the new current,
  116. // those checkpoints will remain in the storage, and eventually will be
  117. // deleted when MakeCheckpoint overwrites them.
  118. func (s *StateDB) Reset(batchNum common.BatchNum) error {
  119. err := s.db.Reset(batchNum)
  120. if err != nil {
  121. return tracerr.Wrap(err)
  122. }
  123. if s.MT != nil {
  124. // open the MT for the current s.db
  125. mt, err := merkletree.NewMerkleTree(s.db.StorageWithPrefix(PrefixKeyMT), s.MT.MaxLevels())
  126. if err != nil {
  127. return tracerr.Wrap(err)
  128. }
  129. s.MT = mt
  130. }
  131. return nil
  132. }
  133. // GetAccount returns the account for the given Idx
  134. func (s *StateDB) GetAccount(idx common.Idx) (*common.Account, error) {
  135. return GetAccountInTreeDB(s.db.DB(), idx)
  136. }
  137. // GetAccounts returns all the accounts in the db. Use for debugging pruposes
  138. // only.
  139. func (s *StateDB) GetAccounts() ([]common.Account, error) {
  140. idxDB := s.db.StorageWithPrefix(PrefixKeyIdx)
  141. idxs := []common.Idx{}
  142. // NOTE: Current implementation of Iterate in the pebble interface is
  143. // not efficient, as it iterates over all keys. Improve it following
  144. // this example: https://github.com/cockroachdb/pebble/pull/923/files
  145. if err := idxDB.Iterate(func(k []byte, v []byte) (bool, error) {
  146. idx, err := common.IdxFromBytes(k)
  147. if err != nil {
  148. return false, tracerr.Wrap(err)
  149. }
  150. idxs = append(idxs, idx)
  151. return true, nil
  152. }); err != nil {
  153. return nil, tracerr.Wrap(err)
  154. }
  155. accs := []common.Account{}
  156. for i := range idxs {
  157. acc, err := s.GetAccount(idxs[i])
  158. if err != nil {
  159. return nil, tracerr.Wrap(err)
  160. }
  161. accs = append(accs, *acc)
  162. }
  163. return accs, nil
  164. }
  165. // GetAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  166. // from ExitTree. GetAccount returns the account for the given Idx
  167. func GetAccountInTreeDB(sto db.Storage, idx common.Idx) (*common.Account, error) {
  168. idxBytes, err := idx.Bytes()
  169. if err != nil {
  170. return nil, tracerr.Wrap(err)
  171. }
  172. vBytes, err := sto.Get(append(PrefixKeyIdx, idxBytes[:]...))
  173. if err != nil {
  174. return nil, tracerr.Wrap(err)
  175. }
  176. accBytes, err := sto.Get(append(PrefixKeyAccHash, vBytes...))
  177. if err != nil {
  178. return nil, tracerr.Wrap(err)
  179. }
  180. var b [32 * common.NLeafElems]byte
  181. copy(b[:], accBytes)
  182. account, err := common.AccountFromBytes(b)
  183. if err != nil {
  184. return nil, tracerr.Wrap(err)
  185. }
  186. account.Idx = idx
  187. return account, nil
  188. }
  189. // CreateAccount creates a new Account in the StateDB for the given Idx. If
  190. // StateDB.MT==nil, MerkleTree is not affected, otherwise updates the
  191. // MerkleTree, returning a CircomProcessorProof.
  192. func (s *StateDB) CreateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  193. cpp, err := CreateAccountInTreeDB(s.db.DB(), s.MT, idx, account)
  194. if err != nil {
  195. return cpp, tracerr.Wrap(err)
  196. }
  197. // store idx by EthAddr & BJJ
  198. err = s.setIdxByEthAddrBJJ(idx, account.EthAddr, account.PublicKey, account.TokenID)
  199. return cpp, tracerr.Wrap(err)
  200. }
  201. // CreateAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  202. // from ExitTree. Creates a new Account in the StateDB for the given Idx. If
  203. // StateDB.MT==nil, MerkleTree is not affected, otherwise updates the
  204. // MerkleTree, returning a CircomProcessorProof.
  205. func CreateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  206. // store at the DB the key: v, and value: leaf.Bytes()
  207. v, err := account.HashValue()
  208. if err != nil {
  209. return nil, tracerr.Wrap(err)
  210. }
  211. accountBytes, err := account.Bytes()
  212. if err != nil {
  213. return nil, tracerr.Wrap(err)
  214. }
  215. // store the Leaf value
  216. tx, err := sto.NewTx()
  217. if err != nil {
  218. return nil, tracerr.Wrap(err)
  219. }
  220. idxBytes, err := idx.Bytes()
  221. if err != nil {
  222. return nil, tracerr.Wrap(err)
  223. }
  224. _, err = tx.Get(append(PrefixKeyIdx, idxBytes[:]...))
  225. if tracerr.Unwrap(err) != db.ErrNotFound {
  226. return nil, tracerr.Wrap(ErrAccountAlreadyExists)
  227. }
  228. err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
  229. if err != nil {
  230. return nil, tracerr.Wrap(err)
  231. }
  232. err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
  233. if err != nil {
  234. return nil, tracerr.Wrap(err)
  235. }
  236. if err := tx.Commit(); err != nil {
  237. return nil, tracerr.Wrap(err)
  238. }
  239. if mt != nil {
  240. return mt.AddAndGetCircomProof(idx.BigInt(), v)
  241. }
  242. return nil, nil
  243. }
  244. // UpdateAccount updates the Account in the StateDB for the given Idx. If
  245. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  246. // MerkleTree, returning a CircomProcessorProof.
  247. func (s *StateDB) UpdateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  248. return UpdateAccountInTreeDB(s.db.DB(), s.MT, idx, account)
  249. }
  250. // UpdateAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  251. // from ExitTree. Updates the Account in the StateDB for the given Idx. If
  252. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  253. // MerkleTree, returning a CircomProcessorProof.
  254. func UpdateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  255. // store at the DB the key: v, and value: account.Bytes()
  256. v, err := account.HashValue()
  257. if err != nil {
  258. return nil, tracerr.Wrap(err)
  259. }
  260. accountBytes, err := account.Bytes()
  261. if err != nil {
  262. return nil, tracerr.Wrap(err)
  263. }
  264. tx, err := sto.NewTx()
  265. if err != nil {
  266. return nil, tracerr.Wrap(err)
  267. }
  268. err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
  269. if err != nil {
  270. return nil, tracerr.Wrap(err)
  271. }
  272. idxBytes, err := idx.Bytes()
  273. if err != nil {
  274. return nil, tracerr.Wrap(err)
  275. }
  276. err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
  277. if err != nil {
  278. return nil, tracerr.Wrap(err)
  279. }
  280. if err := tx.Commit(); err != nil {
  281. return nil, tracerr.Wrap(err)
  282. }
  283. if mt != nil {
  284. proof, err := mt.Update(idx.BigInt(), v)
  285. return proof, tracerr.Wrap(err)
  286. }
  287. return nil, nil
  288. }
  289. // MTGetProof returns the CircomVerifierProof for a given Idx
  290. func (s *StateDB) MTGetProof(idx common.Idx) (*merkletree.CircomVerifierProof, error) {
  291. if s.MT == nil {
  292. return nil, tracerr.Wrap(ErrStateDBWithoutMT)
  293. }
  294. p, err := s.MT.GenerateSCVerifierProof(idx.BigInt(), s.MT.Root())
  295. if err != nil {
  296. return nil, tracerr.Wrap(err)
  297. }
  298. return p, nil
  299. }
  300. // MTGetRoot returns the current root of the underlying Merkle Tree
  301. func (s *StateDB) MTGetRoot() *big.Int {
  302. return s.MT.Root().BigInt()
  303. }
  304. // LocalStateDB represents the local StateDB which allows to make copies from
  305. // the synchronizer StateDB, and is used by the tx-selector and the
  306. // batch-builder. LocalStateDB is an in-memory storage.
  307. type LocalStateDB struct {
  308. *StateDB
  309. synchronizerStateDB *StateDB
  310. }
  311. // NewLocalStateDB returns a new LocalStateDB connected to the given
  312. // synchronizerDB. Checkpoints older than the value defined by `keep` will be
  313. // deleted.
  314. func NewLocalStateDB(path string, keep int, synchronizerDB *StateDB, typ TypeStateDB,
  315. nLevels int) (*LocalStateDB, error) {
  316. s, err := NewStateDB(path, keep, typ, nLevels)
  317. if err != nil {
  318. return nil, tracerr.Wrap(err)
  319. }
  320. return &LocalStateDB{
  321. s,
  322. synchronizerDB,
  323. }, nil
  324. }
  325. // Reset performs a reset in the LocaStateDB. If fromSynchronizer is true, it
  326. // gets the state from LocalStateDB.synchronizerStateDB for the given batchNum.
  327. // If fromSynchronizer is false, get the state from LocalStateDB checkpoints.
  328. func (l *LocalStateDB) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
  329. if fromSynchronizer {
  330. err := l.db.ResetFromSynchronizer(batchNum, l.synchronizerStateDB.db)
  331. if err != nil {
  332. return tracerr.Wrap(err)
  333. }
  334. // open the MT for the current s.db
  335. if l.MT != nil {
  336. mt, err := merkletree.NewMerkleTree(l.db.StorageWithPrefix(PrefixKeyMT), l.MT.MaxLevels())
  337. if err != nil {
  338. return tracerr.Wrap(err)
  339. }
  340. l.MT = mt
  341. }
  342. return nil
  343. }
  344. // use checkpoint from LocalStateDB
  345. return l.StateDB.Reset(batchNum)
  346. }