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.

526 lines
15 KiB

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