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.

529 lines
16 KiB

Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
3 years ago
Update coordinator to work better under real net - cli / node - Update handler of SIGINT so that after 3 SIGINTs, the process terminates unconditionally - coordinator - Store stats without pointer - In all functions that send a variable via channel, check for context done to avoid deadlock (due to no process reading from the channel, which has no queue) when the node is stopped. - Abstract `canForge` so that it can be used outside of the `Coordinator` - In `canForge` check the blockNumber in current and next slot. - Update tests due to smart contract changes in slot handling, and minimum bid defaults - TxManager - Add consts, vars and stats to allow evaluating `canForge` - Add `canForge` method (not used yet) - Store batch and nonces status (last success and last pending) - Track nonces internally instead of relying on the ethereum node (this is required to work with ganache when there are pending txs) - Handle the (common) case of the receipt not being found after the tx is sent. - Don't start the main loop until we get an initial messae fo the stats and vars (so that in the loop the stats and vars are set to synchronizer values) - When a tx fails, check and discard all the failed transactions before sending the message to stop the pipeline. This will avoid sending consecutive messages of stop the pipeline when multiple txs are detected to be failed consecutively. Also, future txs of the same pipeline after a discarded txs are discarded, and their nonces reused. - Robust handling of nonces: - If geth returns nonce is too low, increase it - If geth returns nonce too hight, decrease it - If geth returns underpriced, increase gas price - If geth returns replace underpriced, increase gas price - Add support for resending transactions after a timeout - Store `BatchInfos` in a queue - Pipeline - When an error is found, stop forging batches and send a message to the coordinator to stop the pipeline with information of the failed batch number so that in a restart, non-failed batches are not repated. - When doing a reset of the stateDB, if possible reset from the local checkpoint instead of resetting from the synchronizer. This allows resetting from a batch that is valid but not yet sent / synced. - Every time a pipeline is started, assign it a number from a counter. This allows the TxManager to ignore batches from stopped pipelines, via a message sent by the coordinator. - Avoid forging when we haven't reached the rollup genesis block number. - Add config parameter `StartSlotBlocksDelay`: StartSlotBlocksDelay is the number of blocks of delay to wait before starting the pipeline when we reach a slot in which we can forge. - When detecting a reorg, only reset the pipeline if the batch from which the pipeline started changed and wasn't sent by us. - Add config parameter `ScheduleBatchBlocksAheadCheck`: ScheduleBatchBlocksAheadCheck is the number of blocks ahead in which the forger address is checked to be allowed to forge (apart from checking the next block), used to decide when to stop scheduling new batches (by stopping the pipeline). For example, if we are at block 10 and ScheduleBatchBlocksAheadCheck is 5, eventhough at block 11 we canForge, the pipeline will be stopped if we can't forge at block 15. This value should be the expected number of blocks it takes between scheduling a batch and having it mined. - Add config parameter `SendBatchBlocksMarginCheck`: SendBatchBlocksMarginCheck is the number of margin blocks ahead in which the coordinator is also checked to be allowed to forge, apart from the next block; used to decide when to stop sending batches to the smart contract. For example, if we are at block 10 and SendBatchBlocksMarginCheck is 5, eventhough at block 11 we canForge, the batch will be discarded if we can't forge at block 15. - Add config parameter `TxResendTimeout`: TxResendTimeout is the timeout after which a non-mined ethereum transaction will be resent (reusing the nonce) with a newly calculated gas price - Add config parameter `MaxGasPrice`: MaxGasPrice is the maximum gas price allowed for ethereum transactions - Add config parameter `NoReuseNonce`: NoReuseNonce disables reusing nonces of pending transactions for new replacement transactions. This is useful for testing with Ganache. - Extend BatchInfo with more useful information for debugging - eth / ethereum client - Add necessary methods to create the auth object for transactions manually so that we can set the nonce, gas price, gas limit, etc manually - Update `RollupForgeBatch` to take an auth object as input (so that the coordinator can set parameters manually) - synchronizer - In stats, add `NextSlot` - In stats, store full last batch instead of just last batch number - Instead of calculating a nextSlot from scratch every time, update the current struct (only updating the forger info if we are Synced) - Afer every processed batch, check that the calculated StateDB MTRoot matches the StateRoot found in the forgeBatch event.
3 years ago
Update coordinator to work better under real net - cli / node - Update handler of SIGINT so that after 3 SIGINTs, the process terminates unconditionally - coordinator - Store stats without pointer - In all functions that send a variable via channel, check for context done to avoid deadlock (due to no process reading from the channel, which has no queue) when the node is stopped. - Abstract `canForge` so that it can be used outside of the `Coordinator` - In `canForge` check the blockNumber in current and next slot. - Update tests due to smart contract changes in slot handling, and minimum bid defaults - TxManager - Add consts, vars and stats to allow evaluating `canForge` - Add `canForge` method (not used yet) - Store batch and nonces status (last success and last pending) - Track nonces internally instead of relying on the ethereum node (this is required to work with ganache when there are pending txs) - Handle the (common) case of the receipt not being found after the tx is sent. - Don't start the main loop until we get an initial messae fo the stats and vars (so that in the loop the stats and vars are set to synchronizer values) - When a tx fails, check and discard all the failed transactions before sending the message to stop the pipeline. This will avoid sending consecutive messages of stop the pipeline when multiple txs are detected to be failed consecutively. Also, future txs of the same pipeline after a discarded txs are discarded, and their nonces reused. - Robust handling of nonces: - If geth returns nonce is too low, increase it - If geth returns nonce too hight, decrease it - If geth returns underpriced, increase gas price - If geth returns replace underpriced, increase gas price - Add support for resending transactions after a timeout - Store `BatchInfos` in a queue - Pipeline - When an error is found, stop forging batches and send a message to the coordinator to stop the pipeline with information of the failed batch number so that in a restart, non-failed batches are not repated. - When doing a reset of the stateDB, if possible reset from the local checkpoint instead of resetting from the synchronizer. This allows resetting from a batch that is valid but not yet sent / synced. - Every time a pipeline is started, assign it a number from a counter. This allows the TxManager to ignore batches from stopped pipelines, via a message sent by the coordinator. - Avoid forging when we haven't reached the rollup genesis block number. - Add config parameter `StartSlotBlocksDelay`: StartSlotBlocksDelay is the number of blocks of delay to wait before starting the pipeline when we reach a slot in which we can forge. - When detecting a reorg, only reset the pipeline if the batch from which the pipeline started changed and wasn't sent by us. - Add config parameter `ScheduleBatchBlocksAheadCheck`: ScheduleBatchBlocksAheadCheck is the number of blocks ahead in which the forger address is checked to be allowed to forge (apart from checking the next block), used to decide when to stop scheduling new batches (by stopping the pipeline). For example, if we are at block 10 and ScheduleBatchBlocksAheadCheck is 5, eventhough at block 11 we canForge, the pipeline will be stopped if we can't forge at block 15. This value should be the expected number of blocks it takes between scheduling a batch and having it mined. - Add config parameter `SendBatchBlocksMarginCheck`: SendBatchBlocksMarginCheck is the number of margin blocks ahead in which the coordinator is also checked to be allowed to forge, apart from the next block; used to decide when to stop sending batches to the smart contract. For example, if we are at block 10 and SendBatchBlocksMarginCheck is 5, eventhough at block 11 we canForge, the batch will be discarded if we can't forge at block 15. - Add config parameter `TxResendTimeout`: TxResendTimeout is the timeout after which a non-mined ethereum transaction will be resent (reusing the nonce) with a newly calculated gas price - Add config parameter `MaxGasPrice`: MaxGasPrice is the maximum gas price allowed for ethereum transactions - Add config parameter `NoReuseNonce`: NoReuseNonce disables reusing nonces of pending transactions for new replacement transactions. This is useful for testing with Ganache. - Extend BatchInfo with more useful information for debugging - eth / ethereum client - Add necessary methods to create the auth object for transactions manually so that we can set the nonce, gas price, gas limit, etc manually - Update `RollupForgeBatch` to take an auth object as input (so that the coordinator can set parameters manually) - synchronizer - In stats, add `NextSlot` - In stats, store full last batch instead of just last batch number - Instead of calculating a nextSlot from scratch every time, update the current struct (only updating the forger info if we are Synced) - Afer every processed batch, check that the calculated StateDB MTRoot matches the StateRoot found in the forgeBatch event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
Fix eth events query and sync inconsistent state - kvdb - Fix path in Last when doing `setNew` - Only close if db != nil, and after closing, always set db to nil - This will avoid a panic in the case where the db is closed but there's an error soon after, and a future call tries to close again. This is because pebble.Close() will panic if the db is already closed. - Avoid calling pebble methods when a the Storage interface already implements that method (like Close). - statedb - In test, avoid calling KVDB method if the same method is available for the StateDB (like MakeCheckpoint, CurrentBatch). - eth - In *EventByBlock methods, take blockHash as input argument and use it when querying the event logs. Previously the blockHash was only taken from the logs results *only if* there was any log. This caused the following issue: if there was no logs, it was not possible to know if the result was from the expected block or an uncle block! By querying logs by blockHash we make sure that even if there are no logs, they are from the right block. - Note that now the function can either be called with a blockNum or blockHash, but not both at the same time. - sync - If there's an error during call to Sync call resetState, which internally resets the stateDB to avoid stale checkpoints (and a corresponding invalid increase in the StateDB batchNum). - During a Sync, after very batch processed, make sure that the StateDB currentBatch corresponds to the batchNum in the smart contract log/event.
3 years ago
  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. "github.com/iden3/go-merkletree/db/pebble"
  13. )
  14. var (
  15. // ErrStateDBWithoutMT is used when a method that requires a MerkleTree
  16. // is called in a StateDB that does not have a MerkleTree defined
  17. ErrStateDBWithoutMT = errors.New("Can not call method to use MerkleTree in a StateDB without MerkleTree")
  18. // ErrAccountAlreadyExists is used when CreateAccount is called and the
  19. // Account already exists
  20. ErrAccountAlreadyExists = errors.New("Can not CreateAccount because Account already exists")
  21. // ErrIdxNotFound is used when trying to get the Idx from EthAddr or
  22. // EthAddr&ToBJJ
  23. ErrIdxNotFound = errors.New("Idx can not be found")
  24. // ErrGetIdxNoCase is used when trying to get the Idx from EthAddr &
  25. // BJJ with not compatible combination
  26. ErrGetIdxNoCase = errors.New("Can not get Idx due unexpected combination of ethereum Address & BabyJubJub PublicKey")
  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. // TypeSynchronizer defines a StateDB used by the Synchronizer, that
  40. // generates the ExitTree when processing the txs
  41. TypeSynchronizer = "synchronizer"
  42. // TypeTxSelector defines a StateDB used by the TxSelector, without
  43. // computing ExitTree neither the ZKInputs
  44. TypeTxSelector = "txselector"
  45. // TypeBatchBuilder defines a StateDB used by the BatchBuilder, that
  46. // generates the ExitTree and the ZKInput when processing the txs
  47. TypeBatchBuilder = "batchbuilder"
  48. // MaxNLevels is the maximum value of NLevels for the merkle tree,
  49. // which comes from the fact that AccountIdx has 48 bits.
  50. MaxNLevels = 48
  51. )
  52. // TypeStateDB determines the type of StateDB
  53. type TypeStateDB string
  54. // Config of the StateDB
  55. type Config struct {
  56. // Path where the checkpoints will be stored
  57. Path string
  58. // Keep is the number of old checkpoints to keep. If 0, all
  59. // checkpoints are kept.
  60. Keep int
  61. // NoLast skips having an opened DB with a checkpoint to the last
  62. // batchNum for thread-safe reads.
  63. NoLast bool
  64. // Type of StateDB (
  65. Type TypeStateDB
  66. // NLevels is the number of merkle tree levels in case the Type uses a
  67. // merkle tree. If the Type doesn't use a merkle tree, NLevels should
  68. // be 0.
  69. NLevels int
  70. // At every checkpoint, check that there are no gaps between the
  71. // checkpoints
  72. noGapsCheck bool
  73. }
  74. // StateDB represents the StateDB object
  75. type StateDB struct {
  76. cfg Config
  77. db *kvdb.KVDB
  78. MT *merkletree.MerkleTree
  79. }
  80. // Last offers a subset of view methods of the StateDB that can be
  81. // called via the LastRead method of StateDB in a thread-safe manner to obtain
  82. // a consistent view to the last batch of the StateDB.
  83. type Last struct {
  84. db db.Storage
  85. }
  86. // GetAccount returns the account for the given Idx
  87. func (s *Last) GetAccount(idx common.Idx) (*common.Account, error) {
  88. return GetAccountInTreeDB(s.db, idx)
  89. }
  90. // GetCurrentBatch returns the current BatchNum stored in Last.db
  91. func (s *Last) GetCurrentBatch() (common.BatchNum, error) {
  92. cbBytes, err := s.db.Get(kvdb.KeyCurrentBatch)
  93. if tracerr.Unwrap(err) == db.ErrNotFound {
  94. return 0, nil
  95. } else if err != nil {
  96. return 0, tracerr.Wrap(err)
  97. }
  98. return common.BatchNumFromBytes(cbBytes)
  99. }
  100. // DB returns the underlying storage of Last
  101. func (s *Last) DB() db.Storage {
  102. return s.db
  103. }
  104. // GetAccounts returns all the accounts in the db. Use for debugging pruposes
  105. // only.
  106. func (s *Last) GetAccounts() ([]common.Account, error) {
  107. return getAccounts(s.db)
  108. }
  109. // NewStateDB creates a new StateDB, allowing to use an in-memory or in-disk
  110. // storage. Checkpoints older than the value defined by `keep` will be
  111. // deleted.
  112. // func NewStateDB(pathDB string, keep int, typ TypeStateDB, nLevels int) (*StateDB, error) {
  113. func NewStateDB(cfg Config) (*StateDB, error) {
  114. var kv *kvdb.KVDB
  115. var err error
  116. kv, err = kvdb.NewKVDB(kvdb.Config{Path: cfg.Path, Keep: cfg.Keep,
  117. NoGapsCheck: cfg.noGapsCheck, NoLast: cfg.NoLast})
  118. if err != nil {
  119. return nil, tracerr.Wrap(err)
  120. }
  121. var mt *merkletree.MerkleTree = nil
  122. if cfg.Type == TypeSynchronizer || cfg.Type == TypeBatchBuilder {
  123. mt, err = merkletree.NewMerkleTree(kv.StorageWithPrefix(PrefixKeyMT), cfg.NLevels)
  124. if err != nil {
  125. return nil, tracerr.Wrap(err)
  126. }
  127. }
  128. if cfg.Type == TypeTxSelector && cfg.NLevels != 0 {
  129. return nil, tracerr.Wrap(fmt.Errorf("invalid StateDB parameters: StateDB type==TypeStateDB can not have nLevels!=0"))
  130. }
  131. return &StateDB{
  132. cfg: cfg,
  133. db: kv,
  134. MT: mt,
  135. }, nil
  136. }
  137. // Type returns the StateDB configured Type
  138. func (s *StateDB) Type() TypeStateDB {
  139. return s.cfg.Type
  140. }
  141. // LastRead is a thread-safe method to query the last checkpoint of the StateDB
  142. // via the Last type methods
  143. func (s *StateDB) LastRead(fn func(sdbLast *Last) error) error {
  144. return s.db.LastRead(
  145. func(db *pebble.Storage) error {
  146. return fn(&Last{
  147. db: db,
  148. })
  149. },
  150. )
  151. }
  152. // LastGetAccount is a thread-safe method to query an account in the last
  153. // checkpoint of the StateDB.
  154. func (s *StateDB) LastGetAccount(idx common.Idx) (*common.Account, error) {
  155. var account *common.Account
  156. if err := s.LastRead(func(sdb *Last) error {
  157. var err error
  158. account, err = sdb.GetAccount(idx)
  159. return err
  160. }); err != nil {
  161. return nil, tracerr.Wrap(err)
  162. }
  163. return account, nil
  164. }
  165. // LastGetCurrentBatch is a thread-safe method to get the current BatchNum in
  166. // the last checkpoint of the StateDB.
  167. func (s *StateDB) LastGetCurrentBatch() (common.BatchNum, error) {
  168. var batchNum common.BatchNum
  169. if err := s.LastRead(func(sdb *Last) error {
  170. var err error
  171. batchNum, err = sdb.GetCurrentBatch()
  172. return err
  173. }); err != nil {
  174. return 0, tracerr.Wrap(err)
  175. }
  176. return batchNum, nil
  177. }
  178. // LastMTGetRoot returns the root of the underlying Merkle Tree in the last
  179. // checkpoint of the StateDB.
  180. func (s *StateDB) LastMTGetRoot() (*big.Int, error) {
  181. var root *big.Int
  182. if err := s.LastRead(func(sdb *Last) error {
  183. mt, err := merkletree.NewMerkleTree(sdb.DB().WithPrefix(PrefixKeyMT), s.cfg.NLevels)
  184. if err != nil {
  185. return tracerr.Wrap(err)
  186. }
  187. root = mt.Root().BigInt()
  188. return nil
  189. }); err != nil {
  190. return nil, tracerr.Wrap(err)
  191. }
  192. return root, nil
  193. }
  194. // MakeCheckpoint does a checkpoint at the given batchNum in the defined path.
  195. // Internally this advances & stores the current BatchNum, and then stores a
  196. // Checkpoint of the current state of the StateDB.
  197. func (s *StateDB) MakeCheckpoint() error {
  198. log.Debugw("Making StateDB checkpoint", "batch", s.CurrentBatch()+1, "type", s.cfg.Type)
  199. return s.db.MakeCheckpoint()
  200. }
  201. // CurrentBatch returns the current in-memory CurrentBatch of the StateDB.db
  202. func (s *StateDB) CurrentBatch() common.BatchNum {
  203. return s.db.CurrentBatch
  204. }
  205. // CurrentIdx returns the current in-memory CurrentIdx of the StateDB.db
  206. func (s *StateDB) CurrentIdx() common.Idx {
  207. return s.db.CurrentIdx
  208. }
  209. // getCurrentBatch returns the current BatchNum stored in the StateDB.db
  210. func (s *StateDB) getCurrentBatch() (common.BatchNum, error) {
  211. return s.db.GetCurrentBatch()
  212. }
  213. // GetCurrentIdx returns the stored Idx from the localStateDB, which is the
  214. // last Idx used for an Account in the localStateDB.
  215. func (s *StateDB) GetCurrentIdx() (common.Idx, error) {
  216. return s.db.GetCurrentIdx()
  217. }
  218. // SetCurrentIdx stores Idx in the StateDB
  219. func (s *StateDB) SetCurrentIdx(idx common.Idx) error {
  220. return s.db.SetCurrentIdx(idx)
  221. }
  222. // Reset resets the StateDB to the checkpoint at the given batchNum. Reset
  223. // does not delete the checkpoints between old current and the new current,
  224. // those checkpoints will remain in the storage, and eventually will be
  225. // deleted when MakeCheckpoint overwrites them.
  226. func (s *StateDB) Reset(batchNum common.BatchNum) error {
  227. log.Debugw("Making StateDB Reset", "batch", batchNum, "type", s.cfg.Type)
  228. if err := s.db.Reset(batchNum); err != nil {
  229. return tracerr.Wrap(err)
  230. }
  231. if s.MT != nil {
  232. // open the MT for the current s.db
  233. mt, err := merkletree.NewMerkleTree(s.db.StorageWithPrefix(PrefixKeyMT), s.MT.MaxLevels())
  234. if err != nil {
  235. return tracerr.Wrap(err)
  236. }
  237. s.MT = mt
  238. }
  239. return nil
  240. }
  241. // GetAccount returns the account for the given Idx
  242. func (s *StateDB) GetAccount(idx common.Idx) (*common.Account, error) {
  243. return GetAccountInTreeDB(s.db.DB(), idx)
  244. }
  245. // AccountsIter iterates over all the accounts in db, calling fn for each one
  246. func AccountsIter(db db.Storage, fn func(a *common.Account) (bool, error)) error {
  247. idxDB := db.WithPrefix(PrefixKeyIdx)
  248. if err := idxDB.Iterate(func(k []byte, v []byte) (bool, error) {
  249. idx, err := common.IdxFromBytes(k)
  250. if err != nil {
  251. return false, tracerr.Wrap(err)
  252. }
  253. acc, err := GetAccountInTreeDB(db, idx)
  254. if err != nil {
  255. return false, tracerr.Wrap(err)
  256. }
  257. ok, err := fn(acc)
  258. if err != nil {
  259. return false, tracerr.Wrap(err)
  260. }
  261. return ok, nil
  262. }); err != nil {
  263. return tracerr.Wrap(err)
  264. }
  265. return nil
  266. }
  267. func getAccounts(db db.Storage) ([]common.Account, error) {
  268. accs := []common.Account{}
  269. if err := accountsIter(
  270. db,
  271. func(a *common.Account) (bool, error) {
  272. accs = append(accs, *a)
  273. return true, nil
  274. },
  275. ); err != nil {
  276. return nil, tracerr.Wrap(err)
  277. }
  278. return accs, nil
  279. }
  280. // TestGetAccounts returns all the accounts in the db. Use only in tests.
  281. // Outside tests getting all the accounts is discouraged because it's an
  282. // expensive operation, but if you must do it, use `LastRead()` method to get a
  283. // thread-safe and consistent view of the stateDB.
  284. func (s *StateDB) TestGetAccounts() ([]common.Account, error) {
  285. return getAccounts(s.db.DB())
  286. }
  287. // GetAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  288. // from ExitTree. GetAccount returns the account for the given Idx
  289. func GetAccountInTreeDB(sto db.Storage, idx common.Idx) (*common.Account, error) {
  290. idxBytes, err := idx.Bytes()
  291. if err != nil {
  292. return nil, tracerr.Wrap(err)
  293. }
  294. vBytes, err := sto.Get(append(PrefixKeyIdx, idxBytes[:]...))
  295. if err != nil {
  296. return nil, tracerr.Wrap(err)
  297. }
  298. accBytes, err := sto.Get(append(PrefixKeyAccHash, vBytes...))
  299. if err != nil {
  300. return nil, tracerr.Wrap(err)
  301. }
  302. var b [32 * common.NLeafElems]byte
  303. copy(b[:], accBytes)
  304. account, err := common.AccountFromBytes(b)
  305. if err != nil {
  306. return nil, tracerr.Wrap(err)
  307. }
  308. account.Idx = idx
  309. return account, nil
  310. }
  311. // CreateAccount creates a new Account in the StateDB for the given Idx. If
  312. // StateDB.MT==nil, MerkleTree is not affected, otherwise updates the
  313. // MerkleTree, returning a CircomProcessorProof.
  314. func (s *StateDB) CreateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  315. cpp, err := CreateAccountInTreeDB(s.db.DB(), s.MT, idx, account)
  316. if err != nil {
  317. return cpp, tracerr.Wrap(err)
  318. }
  319. // store idx by EthAddr & BJJ
  320. err = s.setIdxByEthAddrBJJ(idx, account.EthAddr, account.BJJ, account.TokenID)
  321. return cpp, tracerr.Wrap(err)
  322. }
  323. // CreateAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  324. // from ExitTree. Creates a new Account in the StateDB for the given Idx. If
  325. // StateDB.MT==nil, MerkleTree is not affected, otherwise updates the
  326. // MerkleTree, returning a CircomProcessorProof.
  327. func CreateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  328. // store at the DB the key: v, and value: leaf.Bytes()
  329. v, err := account.HashValue()
  330. if err != nil {
  331. return nil, tracerr.Wrap(err)
  332. }
  333. accountBytes, err := account.Bytes()
  334. if err != nil {
  335. return nil, tracerr.Wrap(err)
  336. }
  337. // store the Leaf value
  338. tx, err := sto.NewTx()
  339. if err != nil {
  340. return nil, tracerr.Wrap(err)
  341. }
  342. idxBytes, err := idx.Bytes()
  343. if err != nil {
  344. return nil, tracerr.Wrap(err)
  345. }
  346. _, err = tx.Get(append(PrefixKeyIdx, idxBytes[:]...))
  347. if tracerr.Unwrap(err) != db.ErrNotFound {
  348. return nil, tracerr.Wrap(ErrAccountAlreadyExists)
  349. }
  350. err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
  351. if err != nil {
  352. return nil, tracerr.Wrap(err)
  353. }
  354. err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
  355. if err != nil {
  356. return nil, tracerr.Wrap(err)
  357. }
  358. if err := tx.Commit(); err != nil {
  359. return nil, tracerr.Wrap(err)
  360. }
  361. if mt != nil {
  362. return mt.AddAndGetCircomProof(idx.BigInt(), v)
  363. }
  364. return nil, nil
  365. }
  366. // UpdateAccount updates the Account in the StateDB for the given Idx. If
  367. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  368. // MerkleTree, returning a CircomProcessorProof.
  369. func (s *StateDB) UpdateAccount(idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  370. return UpdateAccountInTreeDB(s.db.DB(), s.MT, idx, account)
  371. }
  372. // UpdateAccountInTreeDB is abstracted from StateDB to be used from StateDB and
  373. // from ExitTree. Updates the Account in the StateDB for the given Idx. If
  374. // StateDB.mt==nil, MerkleTree is not affected, otherwise updates the
  375. // MerkleTree, returning a CircomProcessorProof.
  376. func UpdateAccountInTreeDB(sto db.Storage, mt *merkletree.MerkleTree, idx common.Idx, account *common.Account) (*merkletree.CircomProcessorProof, error) {
  377. // store at the DB the key: v, and value: account.Bytes()
  378. v, err := account.HashValue()
  379. if err != nil {
  380. return nil, tracerr.Wrap(err)
  381. }
  382. accountBytes, err := account.Bytes()
  383. if err != nil {
  384. return nil, tracerr.Wrap(err)
  385. }
  386. tx, err := sto.NewTx()
  387. if err != nil {
  388. return nil, tracerr.Wrap(err)
  389. }
  390. err = tx.Put(append(PrefixKeyAccHash, v.Bytes()...), accountBytes[:])
  391. if err != nil {
  392. return nil, tracerr.Wrap(err)
  393. }
  394. idxBytes, err := idx.Bytes()
  395. if err != nil {
  396. return nil, tracerr.Wrap(err)
  397. }
  398. err = tx.Put(append(PrefixKeyIdx, idxBytes[:]...), v.Bytes())
  399. if err != nil {
  400. return nil, tracerr.Wrap(err)
  401. }
  402. if err := tx.Commit(); err != nil {
  403. return nil, tracerr.Wrap(err)
  404. }
  405. if mt != nil {
  406. proof, err := mt.Update(idx.BigInt(), v)
  407. return proof, tracerr.Wrap(err)
  408. }
  409. return nil, nil
  410. }
  411. // MTGetProof returns the CircomVerifierProof for a given Idx
  412. func (s *StateDB) MTGetProof(idx common.Idx) (*merkletree.CircomVerifierProof, error) {
  413. if s.MT == nil {
  414. return nil, tracerr.Wrap(ErrStateDBWithoutMT)
  415. }
  416. p, err := s.MT.GenerateSCVerifierProof(idx.BigInt(), s.MT.Root())
  417. if err != nil {
  418. return nil, tracerr.Wrap(err)
  419. }
  420. return p, nil
  421. }
  422. // Close the StateDB
  423. func (s *StateDB) Close() {
  424. s.db.Close()
  425. }
  426. // LocalStateDB represents the local StateDB which allows to make copies from
  427. // the synchronizer StateDB, and is used by the tx-selector and the
  428. // batch-builder. LocalStateDB is an in-memory storage.
  429. type LocalStateDB struct {
  430. *StateDB
  431. synchronizerStateDB *StateDB
  432. }
  433. // NewLocalStateDB returns a new LocalStateDB connected to the given
  434. // synchronizerDB. Checkpoints older than the value defined by `keep` will be
  435. // deleted.
  436. func NewLocalStateDB(cfg Config, synchronizerDB *StateDB) (*LocalStateDB, error) {
  437. cfg.noGapsCheck = true
  438. cfg.NoLast = true
  439. s, err := NewStateDB(cfg)
  440. if err != nil {
  441. return nil, tracerr.Wrap(err)
  442. }
  443. return &LocalStateDB{
  444. s,
  445. synchronizerDB,
  446. }, nil
  447. }
  448. // CheckpointExists returns true if the checkpoint exists
  449. func (l *LocalStateDB) CheckpointExists(batchNum common.BatchNum) (bool, error) {
  450. return l.db.CheckpointExists(batchNum)
  451. }
  452. // Reset performs a reset in the LocaStateDB. If fromSynchronizer is true, it
  453. // gets the state from LocalStateDB.synchronizerStateDB for the given batchNum.
  454. // If fromSynchronizer is false, get the state from LocalStateDB checkpoints.
  455. func (l *LocalStateDB) Reset(batchNum common.BatchNum, fromSynchronizer bool) error {
  456. if fromSynchronizer {
  457. log.Debugw("Making StateDB ResetFromSynchronizer", "batch", batchNum, "type", l.cfg.Type)
  458. if err := l.db.ResetFromSynchronizer(batchNum, l.synchronizerStateDB.db); err != nil {
  459. return tracerr.Wrap(err)
  460. }
  461. // open the MT for the current s.db
  462. if l.MT != nil {
  463. mt, err := merkletree.NewMerkleTree(l.db.StorageWithPrefix(PrefixKeyMT),
  464. l.MT.MaxLevels())
  465. if err != nil {
  466. return tracerr.Wrap(err)
  467. }
  468. l.MT = mt
  469. }
  470. return nil
  471. }
  472. // use checkpoint from LocalStateDB
  473. return l.StateDB.Reset(batchNum)
  474. }