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.

579 lines
16 KiB

  1. package statedb
  2. import (
  3. "errors"
  4. "fmt"
  5. "math/big"
  6. "os"
  7. "strconv"
  8. "github.com/hermeznetwork/hermez-node/common"
  9. "github.com/hermeznetwork/hermez-node/log"
  10. "github.com/iden3/go-merkletree"
  11. "github.com/iden3/go-merkletree/db"
  12. "github.com/iden3/go-merkletree/db/pebble"
  13. )
  14. // TODO(Edu): Document here how StateDB is kept consistent
  15. var (
  16. // ErrStateDBWithoutMT is used when a method that requires a MerkleTree
  17. // is called in a StateDB that does not have a MerkleTree defined
  18. ErrStateDBWithoutMT = errors.New("Can not call method to use MerkleTree in a StateDB without MerkleTree")
  19. // ErrAccountAlreadyExists is used when CreateAccount is called and the
  20. // Account already exists
  21. ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists")
  22. // ErrToIdxNotFound is used when trying to get the ToIdx from ToEthAddr
  23. // or ToEthAddr&ToBJJ
  24. ErrToIdxNotFound = errors.New("ToIdx can not be found")
  25. // ErrGetIdxNoCase is used when trying to get the Idx from EthAddr &
  26. // BJJ with not compatible combination
  27. ErrGetIdxNoCase = errors.New("Can not get Idx due unexpected combination of ethereum Address & BabyJubJub PublicKey")
  28. // KeyCurrentBatch is used as key in the db to store the current BatchNum
  29. KeyCurrentBatch = []byte("k:currentbatch")
  30. // PrefixKeyIdx is the key prefix for idx in the db
  31. PrefixKeyIdx = []byte("i:")
  32. // PrefixKeyAccHash is the key prefix for account hash in the db
  33. PrefixKeyAccHash = []byte("h:")
  34. // PrefixKeyMT is the key prefix for merkle tree in the db
  35. PrefixKeyMT = []byte("m:")
  36. // PrefixKeyAddr is the key prefix for address in the db
  37. PrefixKeyAddr = []byte("a:")
  38. // PrefixKeyAddrBJJ is the key prefix for address-babyjubjub in the db
  39. PrefixKeyAddrBJJ = []byte("ab:")
  40. )
  41. const (
  42. // PathBatchNum defines the subpath of the Batch Checkpoint in the
  43. // subpath of the StateDB
  44. PathBatchNum = "/BatchNum"
  45. // PathCurrent defines the subpath of the current Batch in the subpath
  46. // of the StateDB
  47. PathCurrent = "/current"
  48. // TypeSynchronizer defines a StateDB used by the Synchronizer, that
  49. // generates the ExitTree when processing the txs
  50. TypeSynchronizer = "synchronizer"
  51. // TypeTxSelector defines a StateDB used by the TxSelector, without
  52. // computing ExitTree neither the ZKInputs
  53. TypeTxSelector = "txselector"
  54. // TypeBatchBuilder defines a StateDB used by the BatchBuilder, that
  55. // generates the ExitTree and the ZKInput when processing the txs
  56. TypeBatchBuilder = "batchbuilder"
  57. )
  58. // TypeStateDB determines the type of StateDB
  59. type TypeStateDB string
  60. // StateDB represents the StateDB object
  61. type StateDB struct {
  62. path string
  63. currentBatch common.BatchNum
  64. db *pebble.PebbleStorage
  65. mt *merkletree.MerkleTree
  66. typ TypeStateDB
  67. // idx holds the current Idx that the BatchBuilder is using
  68. idx common.Idx
  69. zki *common.ZKInputs
  70. // i is the current transaction index in the ZKInputs generation (zki)
  71. i int
  72. // accumulatedFees contains the accumulated fees for each token (Coord
  73. // Idx) in the processed batch
  74. accumulatedFees map[common.Idx]*big.Int
  75. }
  76. // NewStateDB creates a new StateDB, allowing to use an in-memory or in-disk
  77. // storage
  78. func NewStateDB(path string, typ TypeStateDB, nLevels int) (*StateDB, error) {
  79. var sto *pebble.PebbleStorage
  80. var err error
  81. sto, err = pebble.NewPebbleStorage(path+PathCurrent, false)
  82. if err != nil {
  83. return nil, err
  84. }
  85. var mt *merkletree.MerkleTree = nil
  86. if typ == TypeSynchronizer || typ == TypeBatchBuilder {
  87. mt, err = merkletree.NewMerkleTree(sto.WithPrefix(PrefixKeyMT), nLevels)
  88. if err != nil {
  89. return nil, err
  90. }
  91. }
  92. if typ == TypeTxSelector && nLevels != 0 {
  93. return nil, fmt.Errorf("invalid StateDB parameters: StateDB type==TypeStateDB can not have nLevels!=0")
  94. }
  95. sdb := &StateDB{
  96. path: path,
  97. db: sto,
  98. mt: mt,
  99. typ: typ,
  100. }
  101. // load currentBatch
  102. sdb.currentBatch, err = sdb.GetCurrentBatch()
  103. if err != nil {
  104. return nil, err
  105. }
  106. // make reset (get checkpoint) at currentBatch
  107. err = sdb.reset(sdb.currentBatch, false)
  108. if err != nil {
  109. return nil, err
  110. }
  111. return sdb, nil
  112. }
  113. // DB returns the *pebble.PebbleStorage from the StateDB
  114. func (s *StateDB) DB() *pebble.PebbleStorage {
  115. return s.db
  116. }
  117. // GetCurrentBatch returns the current BatchNum stored in the StateDB
  118. func (s *StateDB) GetCurrentBatch() (common.BatchNum, error) {
  119. cbBytes, err := s.db.Get(KeyCurrentBatch)
  120. if err == db.ErrNotFound {
  121. return 0, nil
  122. }
  123. if err != nil {
  124. return 0, err
  125. }
  126. return common.BatchNumFromBytes(cbBytes)
  127. }
  128. // setCurrentBatch stores the current BatchNum in the StateDB
  129. func (s *StateDB) setCurrentBatch() error {
  130. tx, err := s.db.NewTx()
  131. if err != nil {
  132. return err
  133. }
  134. err = tx.Put(KeyCurrentBatch, s.currentBatch.Bytes())
  135. if err != nil {
  136. return err
  137. }
  138. if err := tx.Commit(); err != nil {
  139. return err
  140. }
  141. return nil
  142. }
  143. // MakeCheckpoint does a checkpoint at the given batchNum in the defined path. Internally this advances & stores the current BatchNum, and then stores a Checkpoint of the current state of the StateDB.
  144. func (s *StateDB) MakeCheckpoint() error {
  145. // advance currentBatch
  146. s.currentBatch++
  147. log.Debugw("Making StateDB checkpoint", "batch", s.currentBatch, "type", s.typ)
  148. checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(s.currentBatch))
  149. err := s.setCurrentBatch()
  150. if err != nil {
  151. return err
  152. }
  153. // if checkpoint BatchNum already exist in disk, delete it
  154. if _, err := os.Stat(checkpointPath); !os.IsNotExist(err) {
  155. err := os.RemoveAll(checkpointPath)
  156. if err != nil {
  157. return err
  158. }
  159. } else if err != nil && !os.IsNotExist(err) {
  160. return err
  161. }
  162. // execute Checkpoint
  163. err = s.db.Pebble().Checkpoint(checkpointPath)
  164. if err != nil {
  165. return err
  166. }
  167. return nil
  168. }
  169. // DeleteCheckpoint removes if exist the checkpoint of the given batchNum
  170. func (s *StateDB) DeleteCheckpoint(batchNum common.BatchNum) error {
  171. checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(batchNum))
  172. if _, err := os.Stat(checkpointPath); os.IsNotExist(err) {
  173. return fmt.Errorf("Checkpoint with batchNum %d does not exist in DB", batchNum)
  174. }
  175. return os.RemoveAll(checkpointPath)
  176. }
  177. func pebbleMakeCheckpoint(source, dest string) error {
  178. // Remove dest folder (if it exists) before doing the checkpoint
  179. if _, err := os.Stat(dest); !os.IsNotExist(err) {
  180. err := os.RemoveAll(dest)
  181. if err != nil {
  182. return err
  183. }
  184. } else if err != nil && !os.IsNotExist(err) {
  185. return err
  186. }
  187. sto, err := pebble.NewPebbleStorage(source, false)
  188. if err != nil {
  189. return err
  190. }
  191. defer func() {
  192. errClose := sto.Pebble().Close()
  193. if errClose != nil {
  194. log.Errorw("Pebble.Close", "err", errClose)
  195. }
  196. }()
  197. // execute Checkpoint
  198. err = sto.Pebble().Checkpoint(dest)
  199. if err != nil {
  200. return err
  201. }
  202. return nil
  203. }
  204. // Reset resets the StateDB to the checkpoint at the given batchNum. Reset
  205. // does not delete the checkpoints between old current and the new current,
  206. // those checkpoints will remain in the storage, and eventually will be
  207. // deleted when MakeCheckpoint overwrites them.
  208. func (s *StateDB) Reset(batchNum common.BatchNum) error {
  209. return s.reset(batchNum, true)
  210. }
  211. // reset resets the StateDB to the checkpoint at the given batchNum. Reset
  212. // does not delete the checkpoints between old current and the new current,
  213. // those checkpoints will remain in the storage, and eventually will be
  214. // deleted when MakeCheckpoint overwrites them. `closeCurrent` will close the
  215. // currently opened db before doing the reset.
  216. func (s *StateDB) reset(batchNum common.BatchNum, closeCurrent bool) error {
  217. checkpointPath := s.path + PathBatchNum + strconv.Itoa(int(batchNum))
  218. currentPath := s.path + PathCurrent
  219. if closeCurrent {
  220. if err := s.db.Pebble().Close(); err != nil {
  221. return err
  222. }
  223. }
  224. // remove 'current'
  225. err := os.RemoveAll(currentPath)
  226. if err != nil {
  227. return err
  228. }
  229. if batchNum == 0 {
  230. // if batchNum == 0, open the new fresh 'current'
  231. sto, err := pebble.NewPebbleStorage(currentPath, false)
  232. if err != nil {
  233. return err
  234. }
  235. s.db = sto
  236. s.idx = 255
  237. s.currentBatch = batchNum
  238. return nil
  239. }
  240. // copy 'BatchNumX' to 'current'
  241. err = pebbleMakeCheckpoint(checkpointPath, currentPath)
  242. if err != nil {
  243. return err
  244. }
  245. // open the new 'current'
  246. sto, err := pebble.NewPebbleStorage(currentPath, false)
  247. if err != nil {
  248. return err
  249. }
  250. s.db = sto
  251. // get currentBatch num
  252. s.currentBatch, err = s.GetCurrentBatch()
  253. if err != nil {
  254. return err
  255. }
  256. // idx is obtained from the statedb reset
  257. s.idx, err = s.getIdx()
  258. if err != nil {
  259. return err
  260. }
  261. if s.mt != nil {
  262. // open the MT for the current s.db
  263. mt, err := merkletree.NewMerkleTree(s.db.WithPrefix(PrefixKeyMT), s.mt.MaxLevels())
  264. if err != nil {
  265. return err
  266. }
  267. s.mt = mt
  268. }
  269. return nil
  270. }
  271. // GetAccount returns the account for the given Idx
  272. func (s *StateDB) GetAccount(idx common.Idx) (*common.Account, error) {
  273. return getAccountInTreeDB(s.db, idx)
  274. }
  275. // GetAccounts returns all the accounts in the db. Use for debugging pruposes
  276. // only.
  277. func (s *StateDB) GetAccounts() ([]common.Account, error) {
  278. idxDB := s.db.WithPrefix(PrefixKeyIdx)
  279. idxs := []common.Idx{}
  280. // NOTE: Current implementation of Iterate in the pebble interface is
  281. // not efficient, as it iterates over all keys. Improve it following
  282. // this example: https://github.com/cockroachdb/pebble/pull/923/files
  283. if err := idxDB.Iterate(func(k []byte, v []byte) (bool, error) {
  284. idx, err := common.IdxFromBytes(k)
  285. if err != nil {
  286. return false, err
  287. }
  288. idxs = append(idxs, idx)
  289. return true, nil
  290. }); err != nil {
  291. return nil, err
  292. }
  293. accs := []common.Account{}
  294. for i := range idxs {
  295. acc, err := s.GetAccount(idxs[i])
  296. if err != nil {
  297. return nil, err
  298. }
  299. accs = append(accs, *acc)
  300. }
  301. return accs, nil
  302. }
  303. // getAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  304. // from ExitTree. GetAccount returns the account for the given Idx
  305. func getAccountInTreeDB(sto db.Storage, idx common.Idx) (*common.Account, error) {
  306. idxBytes, err := idx.Bytes()
  307. if err != nil {
  308. return nil, err
  309. }
  310. vBytes, err := sto.Get(append(PrefixKeyIdx, idxBytes[:]...))
  311. if err != nil {
  312. return nil, err
  313. }
  314. accBytes, err := sto.Get(append(PrefixKeyAccHash, vBytes...))
  315. if err != nil {
  316. return nil, err
  317. }
  318. var b [32 * common.NLeafElems]byte
  319. copy(b[:], accBytes)
  320. account, err := common.AccountFromBytes(b)
  321. if err != nil {
  322. return nil, err
  323. }
  324. account.Idx = idx
  325. return account, nil
  326. }
  327. // CreateAccount creates a new Account in the StateDB for the given Idx. If
  328. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  329. // MerkleTree, returning a CircomProcessorProof.
  330. func (s *StateDB) CreateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  331. cpp, err := createAccountInTreeDB(s.db, s.mt, idx, account)
  332. if err != nil {
  333. return cpp, err
  334. }
  335. // store idx by EthAddr & BJJ
  336. err = s.setIdxByEthAddrBJJ(idx, account.EthAddr, account.PublicKey, account.TokenID)
  337. return cpp, err
  338. }
  339. // createAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  340. // from ExitTree. Creates a new Account in the StateDB for the given Idx. If
  341. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  342. // MerkleTree, returning a CircomProcessorProof.
  343. func createAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  344. // store at the DB the key: v, and value: leaf.Bytes()
  345. v, err := account.HashValue()
  346. if err != nil {
  347. return nil, err
  348. }
  349. accountBytes, err := account.Bytes()
  350. if err != nil {
  351. return nil, err
  352. }
  353. // store the Leaf value
  354. tx, err := sto.NewTx()
  355. if err != nil {
  356. return nil, err
  357. }
  358. idxBytes, err := idx.Bytes()
  359. if err != nil {
  360. return nil, err
  361. }
  362. _, err = tx.Get(append(PrefixKeyIdx, idxBytes[:]...))
  363. if err != db.ErrNotFound {
  364. return nil, ErrAccountAlreadyExists
  365. }
  366. err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
  367. if err != nil {
  368. return nil, err
  369. }
  370. err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
  371. if err != nil {
  372. return nil, err
  373. }
  374. if err := tx.Commit(); err != nil {
  375. return nil, err
  376. }
  377. if mt != nil {
  378. return mt.AddAndGetCircomProof(idx.BigInt(), v)
  379. }
  380. return nil, nil
  381. }
  382. // UpdateAccount updates the Account in the StateDB for the given Idx. If
  383. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  384. // MerkleTree, returning a CircomProcessorProof.
  385. func (s *StateDB) UpdateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  386. return updateAccountInTreeDB(s.db, s.mt, idx, account)
  387. }
  388. // updateAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  389. // from ExitTree. Updates the Account in the StateDB for the given Idx. If
  390. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  391. // MerkleTree, returning a CircomProcessorProof.
  392. func updateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  393. // store at the DB the key: v, and value: account.Bytes()
  394. v, err := account.HashValue()
  395. if err != nil {
  396. return nil, err
  397. }
  398. accountBytes, err := account.Bytes()
  399. if err != nil {
  400. return nil, err
  401. }
  402. tx, err := sto.NewTx()
  403. if err != nil {
  404. return nil, err
  405. }
  406. err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
  407. if err != nil {
  408. return nil, err
  409. }
  410. idxBytes, err := idx.Bytes()
  411. if err != nil {
  412. return nil, err
  413. }
  414. err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
  415. if err != nil {
  416. return nil, err
  417. }
  418. if err := tx.Commit(); err != nil {
  419. return nil, err
  420. }
  421. if mt != nil {
  422. return mt.Update(idx.BigInt(), v)
  423. }
  424. return nil, nil
  425. }
  426. // MTGetProof returns the CircomVerifierProof for a given Idx
  427. func (s *StateDB) MTGetProof(idx common.Idx) (*merkletree.CircomVerifierProof, error) {
  428. if s.mt == nil {
  429. return nil, ErrStateDBWithoutMT
  430. }
  431. return s.mt.GenerateCircomVerifierProof(idx.BigInt(), s.mt.Root())
  432. }
  433. // MTGetRoot returns the current root of the underlying Merkle Tree
  434. func (s *StateDB) MTGetRoot() *big.Int {
  435. return s.mt.Root().BigInt()
  436. }
  437. // LocalStateDB represents the local StateDB which allows to make copies from
  438. // the synchronizer StateDB, and is used by the tx-selector and the
  439. // batch-builder. LocalStateDB is an in-memory storage.
  440. type LocalStateDB struct {
  441. *StateDB
  442. synchronizerStateDB *StateDB
  443. }
  444. // NewLocalStateDB returns a new LocalStateDB connected to the given
  445. // synchronizerDB
  446. func NewLocalStateDB(path string, synchronizerDB *StateDB, typ TypeStateDB, nLevels int) (*LocalStateDB, error) {
  447. s, err := NewStateDB(path, typ, nLevels)
  448. if err != nil {
  449. return nil, err
  450. }
  451. return &LocalStateDB{
  452. s,
  453. synchronizerDB,
  454. }, nil
  455. }
  456. // Reset performs a reset in the LocaStateDB. If fromSynchronizer is true, it
  457. // gets the state from LocalStateDB.synchronizerStateDB for the given batchNum. If fromSynchronizer is false, get the state from LocalStateDB checkpoints.
  458. func (l *LocalStateDB) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
  459. if batchNum == 0 {
  460. l.idx = 0
  461. return nil
  462. }
  463. synchronizerCheckpointPath := l.synchronizerStateDB.path + PathBatchNum + strconv.Itoa(int(batchNum))
  464. checkpointPath := l.path + PathBatchNum + strconv.Itoa(int(batchNum))
  465. currentPath := l.path + PathCurrent
  466. if fromSynchronizer {
  467. // use checkpoint from SynchronizerStateDB
  468. if _, err := os.Stat(synchronizerCheckpointPath); os.IsNotExist(err) {
  469. // if synchronizerStateDB does not have checkpoint at batchNum, return err
  470. return fmt.Errorf("Checkpoint not exist in Synchronizer")
  471. }
  472. if err := l.db.Pebble().Close(); err != nil {
  473. return err
  474. }
  475. // remove 'current'
  476. err := os.RemoveAll(currentPath)
  477. if err != nil {
  478. return err
  479. }
  480. // copy synchronizer'BatchNumX' to 'current'
  481. err = pebbleMakeCheckpoint(synchronizerCheckpointPath, currentPath)
  482. if err != nil {
  483. return err
  484. }
  485. // copy synchronizer'BatchNumX' to 'BatchNumX'
  486. err = pebbleMakeCheckpoint(synchronizerCheckpointPath, checkpointPath)
  487. if err != nil {
  488. return err
  489. }
  490. // open the new 'current'
  491. sto, err := pebble.NewPebbleStorage(currentPath, false)
  492. if err != nil {
  493. return err
  494. }
  495. l.db = sto
  496. // get currentBatch num
  497. l.currentBatch, err = l.GetCurrentBatch()
  498. if err != nil {
  499. return err
  500. }
  501. // open the MT for the current s.db
  502. mt, err := merkletree.NewMerkleTree(l.db.WithPrefix(PrefixKeyMT), l.mt.MaxLevels())
  503. if err != nil {
  504. return err
  505. }
  506. l.mt = mt
  507. return nil
  508. }
  509. // use checkpoint from LocalStateDB
  510. return l.StateDB.reset(batchNum, true)
  511. }