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.

1214 lines
38 KiB

  1. package statedb
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "math/big"
  8. "os"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/log"
  11. "github.com/hermeznetwork/tracerr"
  12. "github.com/iden3/go-iden3-crypto/babyjub"
  13. "github.com/iden3/go-merkletree"
  14. "github.com/iden3/go-merkletree/db"
  15. "github.com/iden3/go-merkletree/db/pebble"
  16. )
  17. var (
  18. // keyidx is used as key in the db to store the current Idx
  19. keyidx = []byte("k:idx")
  20. )
  21. func (s *StateDB) resetZKInputs() {
  22. s.zki = nil
  23. s.i = 0 // initialize current transaction index in the ZKInputs generation
  24. }
  25. type processedExit struct {
  26. exit bool
  27. newExit bool
  28. idx common.Idx
  29. acc common.Account
  30. }
  31. // ProcessTxOutput contains the output of the ProcessTxs method
  32. type ProcessTxOutput struct {
  33. ZKInputs *common.ZKInputs
  34. ExitInfos []common.ExitInfo
  35. CreatedAccounts []common.Account
  36. CoordinatorIdxsMap map[common.TokenID]common.Idx
  37. CollectedFees map[common.TokenID]*big.Int
  38. }
  39. // ProcessTxsConfig contains the config for ProcessTxs
  40. type ProcessTxsConfig struct {
  41. NLevels uint32
  42. MaxFeeTx uint32
  43. MaxTx uint32
  44. MaxL1Tx uint32
  45. }
  46. // ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  47. // the StateDB depending on the transaction Type. If StateDB
  48. // type==TypeBatchBuilder, returns the common.ZKInputs to generate the
  49. // SnarkProof later used by the BatchBuilder. If StateDB
  50. // type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
  51. // returns common.ExitTreeLeaf that is later used by the Synchronizer to update
  52. // the HistoryDB, and adds Nonce & TokenID to the L2Txs.
  53. // And if TypeSynchronizer returns an array of common.Account with all the
  54. // created accounts.
  55. func (s *StateDB) ProcessTxs(ptc ProcessTxsConfig, coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) (ptOut *ProcessTxOutput, err error) {
  56. defer func() {
  57. if err == nil {
  58. err = s.MakeCheckpoint()
  59. }
  60. }()
  61. var exitTree *merkletree.MerkleTree
  62. var createdAccounts []common.Account
  63. if s.zki != nil {
  64. return nil, tracerr.Wrap(errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty"))
  65. }
  66. defer s.resetZKInputs()
  67. if len(coordIdxs) >= int(ptc.MaxFeeTx) {
  68. return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), ptc.MaxFeeTx))
  69. }
  70. s.accumulatedFees = make(map[common.Idx]*big.Int)
  71. nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
  72. if nTx == 0 {
  73. // TODO return ZKInputs of batch without txs
  74. return &ProcessTxOutput{
  75. ZKInputs: nil,
  76. ExitInfos: nil,
  77. CreatedAccounts: nil,
  78. CoordinatorIdxsMap: nil,
  79. CollectedFees: nil,
  80. }, nil
  81. }
  82. if nTx > int(ptc.MaxTx) {
  83. return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx + L2Tx (%d) can not be bigger than MaxTx (%d)", nTx, ptc.MaxTx))
  84. }
  85. if len(l1usertxs)+len(l1coordinatortxs) > int(ptc.MaxL1Tx) {
  86. return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx (%d) can not be bigger than MaxL1Tx (%d)", len(l1usertxs)+len(l1coordinatortxs), ptc.MaxTx))
  87. }
  88. exits := make([]processedExit, nTx)
  89. if s.typ == TypeBatchBuilder {
  90. s.zki = common.NewZKInputs(ptc.MaxTx, ptc.MaxL1Tx, ptc.MaxTx, ptc.MaxFeeTx, ptc.NLevels, s.currentBatch.BigInt())
  91. s.zki.OldLastIdx = s.idx.BigInt()
  92. s.zki.OldStateRoot = s.mt.Root().BigInt()
  93. }
  94. // TBD if ExitTree is only in memory or stored in disk, for the moment
  95. // is only needed in memory
  96. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  97. tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
  98. if err != nil {
  99. return nil, tracerr.Wrap(err)
  100. }
  101. defer func() {
  102. if err := os.RemoveAll(tmpDir); err != nil {
  103. log.Errorw("Deleting statedb temp exit tree", "err", err)
  104. }
  105. }()
  106. sto, err := pebble.NewPebbleStorage(tmpDir, false)
  107. if err != nil {
  108. return nil, tracerr.Wrap(err)
  109. }
  110. exitTree, err = merkletree.NewMerkleTree(sto, s.mt.MaxLevels())
  111. if err != nil {
  112. return nil, tracerr.Wrap(err)
  113. }
  114. }
  115. // Process L1UserTxs
  116. for i := 0; i < len(l1usertxs); i++ {
  117. // assumption: l1usertx are sorted by L1Tx.Position
  118. exitIdx, exitAccount, newExit, createdAccount, err := s.processL1Tx(exitTree, &l1usertxs[i])
  119. if err != nil {
  120. return nil, tracerr.Wrap(err)
  121. }
  122. if s.typ == TypeSynchronizer && createdAccount != nil {
  123. createdAccounts = append(createdAccounts, *createdAccount)
  124. }
  125. if s.zki != nil {
  126. l1TxData, err := l1usertxs[i].BytesGeneric()
  127. if err != nil {
  128. return nil, tracerr.Wrap(err)
  129. }
  130. s.zki.Metadata.L1TxsData = append(s.zki.Metadata.L1TxsData, l1TxData)
  131. l1TxDataAvailability, err := l1usertxs[i].BytesDataAvailability(s.zki.Metadata.NLevels)
  132. if err != nil {
  133. return nil, tracerr.Wrap(err)
  134. }
  135. s.zki.Metadata.L1TxsDataAvailability = append(s.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
  136. s.zki.ISOutIdx[s.i] = s.idx.BigInt()
  137. s.zki.ISStateRoot[s.i] = s.mt.Root().BigInt()
  138. if exitIdx == nil {
  139. s.zki.ISExitRoot[s.i] = exitTree.Root().BigInt()
  140. }
  141. }
  142. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  143. if exitIdx != nil && exitTree != nil {
  144. exits[s.i] = processedExit{
  145. exit: true,
  146. newExit: newExit,
  147. idx: *exitIdx,
  148. acc: *exitAccount,
  149. }
  150. }
  151. s.i++
  152. }
  153. }
  154. // Process L1CoordinatorTxs
  155. for i := 0; i < len(l1coordinatortxs); i++ {
  156. exitIdx, _, _, createdAccount, err := s.processL1Tx(exitTree, &l1coordinatortxs[i])
  157. if err != nil {
  158. return nil, tracerr.Wrap(err)
  159. }
  160. if exitIdx != nil {
  161. log.Error("Unexpected Exit in L1CoordinatorTx")
  162. }
  163. if s.typ == TypeSynchronizer && createdAccount != nil {
  164. createdAccounts = append(createdAccounts, *createdAccount)
  165. }
  166. if s.zki != nil {
  167. l1TxData, err := l1coordinatortxs[i].BytesGeneric()
  168. if err != nil {
  169. return nil, tracerr.Wrap(err)
  170. }
  171. s.zki.Metadata.L1TxsData = append(s.zki.Metadata.L1TxsData, l1TxData)
  172. s.zki.ISOutIdx[s.i] = s.idx.BigInt()
  173. s.zki.ISStateRoot[s.i] = s.mt.Root().BigInt()
  174. s.i++
  175. }
  176. }
  177. s.accumulatedFees = make(map[common.Idx]*big.Int)
  178. for _, idx := range coordIdxs {
  179. s.accumulatedFees[idx] = big.NewInt(0)
  180. }
  181. // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
  182. // coordIdxs. In this way, if a coordIdx uses an Idx that is being
  183. // created in the current batch, at this point the Idx will be created
  184. coordIdxsMap, err := s.getTokenIDsFromIdxs(coordIdxs)
  185. if err != nil {
  186. return nil, tracerr.Wrap(err)
  187. }
  188. // collectedFees will contain the amount of fee collected for each
  189. // TokenID
  190. var collectedFees map[common.TokenID]*big.Int
  191. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  192. collectedFees = make(map[common.TokenID]*big.Int)
  193. for tokenID := range coordIdxsMap {
  194. collectedFees[tokenID] = big.NewInt(0)
  195. }
  196. }
  197. if s.zki != nil {
  198. // get the feePlanTokens
  199. feePlanTokens, err := s.getFeePlanTokens(coordIdxs, l2txs)
  200. if err != nil {
  201. log.Error(err)
  202. return nil, tracerr.Wrap(err)
  203. }
  204. copy(s.zki.FeePlanTokens, feePlanTokens)
  205. }
  206. // Process L2Txs
  207. for i := 0; i < len(l2txs); i++ {
  208. exitIdx, exitAccount, newExit, err := s.processL2Tx(coordIdxsMap, collectedFees, exitTree, &l2txs[i])
  209. if err != nil {
  210. return nil, tracerr.Wrap(err)
  211. }
  212. if s.zki != nil {
  213. l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(s.zki.Metadata.NLevels)
  214. if err != nil {
  215. return nil, tracerr.Wrap(err)
  216. }
  217. s.zki.Metadata.L2TxsData = append(s.zki.Metadata.L2TxsData, l2TxData)
  218. // Intermediate States
  219. if s.i < nTx-1 {
  220. s.zki.ISOutIdx[s.i] = s.idx.BigInt()
  221. s.zki.ISStateRoot[s.i] = s.mt.Root().BigInt()
  222. s.zki.ISAccFeeOut[s.i] = formatAccumulatedFees(collectedFees, s.zki.FeePlanTokens)
  223. if exitIdx == nil {
  224. s.zki.ISExitRoot[s.i] = exitTree.Root().BigInt()
  225. }
  226. }
  227. if s.i == nTx-1 {
  228. s.zki.ISFinalAccFee = formatAccumulatedFees(collectedFees, s.zki.FeePlanTokens)
  229. }
  230. }
  231. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  232. if exitIdx != nil && exitTree != nil {
  233. exits[s.i] = processedExit{
  234. exit: true,
  235. newExit: newExit,
  236. idx: *exitIdx,
  237. acc: *exitAccount,
  238. }
  239. }
  240. s.i++
  241. }
  242. }
  243. if s.zki != nil {
  244. for i := s.i - 1; i < int(ptc.MaxTx); i++ {
  245. if i < int(ptc.MaxTx)-1 {
  246. s.zki.ISOutIdx[i] = s.idx.BigInt()
  247. s.zki.ISStateRoot[i] = s.mt.Root().BigInt()
  248. s.zki.ISAccFeeOut[i] = formatAccumulatedFees(collectedFees, s.zki.FeePlanTokens)
  249. s.zki.ISExitRoot[i] = exitTree.Root().BigInt()
  250. }
  251. if i >= s.i {
  252. s.zki.TxCompressedData[i] = new(big.Int).SetBytes(common.SignatureConstantBytes)
  253. }
  254. }
  255. // before computing the Fees txs, set the ISInitStateRootFee
  256. s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
  257. }
  258. // distribute the AccumulatedFees from the processed L2Txs into the
  259. // Coordinator Idxs
  260. iFee := 0
  261. for idx, accumulatedFee := range s.accumulatedFees {
  262. // send the fee to the Idx of the Coordinator for the TokenID
  263. accCoord, err := s.GetAccount(idx)
  264. if err != nil {
  265. log.Errorw("Can not distribute accumulated fees to coordinator account: No coord Idx to receive fee", "idx", idx)
  266. return nil, tracerr.Wrap(err)
  267. }
  268. if s.zki != nil {
  269. s.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
  270. s.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
  271. if babyjub.PointCoordSign(accCoord.PublicKey.X) {
  272. s.zki.Sign3[iFee] = big.NewInt(1)
  273. }
  274. s.zki.Ay3[iFee] = accCoord.PublicKey.Y
  275. s.zki.Balance3[iFee] = accCoord.Balance
  276. s.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
  277. // add Coord Idx to ZKInputs.FeeTxsData
  278. s.zki.FeeIdxs[iFee] = idx.BigInt()
  279. }
  280. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  281. pFee, err := s.UpdateAccount(idx, accCoord)
  282. if err != nil {
  283. log.Error(err)
  284. return nil, tracerr.Wrap(err)
  285. }
  286. if s.zki != nil {
  287. s.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
  288. s.zki.ISStateRootFee[iFee] = s.mt.Root().BigInt()
  289. }
  290. iFee++
  291. }
  292. if s.zki != nil {
  293. for i := len(s.accumulatedFees); i < int(ptc.MaxFeeTx)-1; i++ {
  294. s.zki.ISStateRootFee[i] = s.mt.Root().BigInt()
  295. }
  296. }
  297. if s.typ == TypeTxSelector {
  298. return nil, nil
  299. }
  300. // once all txs processed (exitTree root frozen), for each Exit,
  301. // generate common.ExitInfo data
  302. var exitInfos []common.ExitInfo
  303. for i := 0; i < nTx; i++ {
  304. if !exits[i].exit {
  305. continue
  306. }
  307. exitIdx := exits[i].idx
  308. exitAccount := exits[i].acc
  309. // 0. generate MerkleProof
  310. p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
  311. if err != nil {
  312. return nil, tracerr.Wrap(err)
  313. }
  314. // 1. generate common.ExitInfo
  315. ei := common.ExitInfo{
  316. AccountIdx: exitIdx,
  317. MerkleProof: p,
  318. Balance: exitAccount.Balance,
  319. }
  320. exitInfos = append(exitInfos, ei)
  321. }
  322. if s.typ == TypeSynchronizer {
  323. // return exitInfos, createdAccounts and collectedFees, so Synchronizer will
  324. // be able to store it into HistoryDB for the concrete BatchNum
  325. return &ProcessTxOutput{
  326. ZKInputs: nil,
  327. ExitInfos: exitInfos,
  328. CreatedAccounts: createdAccounts,
  329. CoordinatorIdxsMap: coordIdxsMap,
  330. CollectedFees: collectedFees,
  331. }, nil
  332. }
  333. // compute last ZKInputs parameters
  334. s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
  335. // zki.FeeIdxs = ? // TODO, this will be get from the config file
  336. s.zki.Metadata.NewStateRootRaw = s.mt.Root()
  337. s.zki.Metadata.NewExitRootRaw = exitTree.Root()
  338. // return ZKInputs as the BatchBuilder will return it to forge the Batch
  339. return &ProcessTxOutput{
  340. ZKInputs: s.zki,
  341. ExitInfos: nil,
  342. CreatedAccounts: nil,
  343. CoordinatorIdxsMap: coordIdxsMap,
  344. CollectedFees: nil,
  345. }, nil
  346. }
  347. // getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
  348. // corresponding to the given CoordIdxs and the processed L2Txs
  349. func (s *StateDB) getFeePlanTokens(coordIdxs []common.Idx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
  350. // get Coordinator TokenIDs corresponding to the Idxs where the Fees
  351. // will be sent
  352. coordTokenIDs := make(map[common.TokenID]bool)
  353. for i := 0; i < len(coordIdxs); i++ {
  354. acc, err := s.GetAccount(coordIdxs[i])
  355. if err != nil {
  356. log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error())
  357. return nil, tracerr.Wrap(err)
  358. }
  359. coordTokenIDs[acc.TokenID] = true
  360. }
  361. tokenIDs := make(map[common.TokenID]bool)
  362. for i := 0; i < len(l2txs); i++ {
  363. // as L2Tx does not have parameter TokenID, get it from the
  364. // AccountsDB (in the StateDB)
  365. acc, err := s.GetAccount(l2txs[i].FromIdx)
  366. if err != nil {
  367. log.Errorf("could not get account to determine TokenID of L2Tx: FromIdx %d not found: %s", l2txs[i].FromIdx, err.Error())
  368. return nil, tracerr.Wrap(err)
  369. }
  370. if _, ok := coordTokenIDs[acc.TokenID]; ok {
  371. tokenIDs[acc.TokenID] = true
  372. }
  373. }
  374. var tBI []*big.Int
  375. for t := range tokenIDs {
  376. tBI = append(tBI, t.BigInt())
  377. }
  378. return tBI, nil
  379. }
  380. // processL1Tx process the given L1Tx applying the needed updates to the
  381. // StateDB depending on the transaction Type. It returns the 3 parameters
  382. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  383. // the Exit created a new Leaf in the ExitTree.
  384. // And another *common.Account parameter which contains the created account in
  385. // case that has been a new created account and that the StateDB is of type
  386. // TypeSynchronizer.
  387. func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, *common.Account, error) {
  388. // ZKInputs
  389. if s.zki != nil {
  390. // Txs
  391. var err error
  392. s.zki.TxCompressedData[s.i], err = tx.TxCompressedData()
  393. if err != nil {
  394. log.Error(err)
  395. return nil, nil, false, nil, tracerr.Wrap(err)
  396. }
  397. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  398. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  399. s.zki.OnChain[s.i] = big.NewInt(1)
  400. // L1Txs
  401. depositAmountF16, err := common.NewFloat16(tx.DepositAmount)
  402. if err != nil {
  403. return nil, nil, false, nil, tracerr.Wrap(err)
  404. }
  405. s.zki.DepositAmountF[s.i] = big.NewInt(int64(depositAmountF16))
  406. s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  407. if tx.FromBJJ != nil {
  408. s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
  409. }
  410. // Intermediate States, for all the transactions except for the last one
  411. if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
  412. s.zki.ISOnChain[s.i] = big.NewInt(1)
  413. }
  414. }
  415. switch tx.Type {
  416. case common.TxTypeForceTransfer:
  417. s.computeEffectiveAmounts(tx)
  418. // go to the MT account of sender and receiver, and update balance
  419. // & nonce
  420. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  421. // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
  422. err := s.applyTransfer(nil, nil, tx.Tx(), 0)
  423. if err != nil {
  424. log.Error(err)
  425. return nil, nil, false, nil, tracerr.Wrap(err)
  426. }
  427. case common.TxTypeCreateAccountDeposit:
  428. s.computeEffectiveAmounts(tx)
  429. // add new account to the MT, update balance of the MT account
  430. err := s.applyCreateAccount(tx)
  431. if err != nil {
  432. log.Error(err)
  433. return nil, nil, false, nil, tracerr.Wrap(err)
  434. }
  435. // TODO applyCreateAccount will return the created account,
  436. // which in the case type==TypeSynchronizer will be added to an
  437. // array of created accounts that will be returned
  438. case common.TxTypeDeposit:
  439. s.computeEffectiveAmounts(tx)
  440. // update balance of the MT account
  441. err := s.applyDeposit(tx, false)
  442. if err != nil {
  443. log.Error(err)
  444. return nil, nil, false, nil, tracerr.Wrap(err)
  445. }
  446. case common.TxTypeDepositTransfer:
  447. s.computeEffectiveAmounts(tx)
  448. // update balance in MT account, update balance & nonce of sender
  449. // & receiver
  450. err := s.applyDeposit(tx, true)
  451. if err != nil {
  452. log.Error(err)
  453. return nil, nil, false, nil, tracerr.Wrap(err)
  454. }
  455. case common.TxTypeCreateAccountDepositTransfer:
  456. s.computeEffectiveAmounts(tx)
  457. // add new account to the merkletree, update balance in MT account,
  458. // update balance & nonce of sender & receiver
  459. err := s.applyCreateAccountDepositTransfer(tx)
  460. if err != nil {
  461. log.Error(err)
  462. return nil, nil, false, nil, tracerr.Wrap(err)
  463. }
  464. case common.TxTypeForceExit:
  465. s.computeEffectiveAmounts(tx)
  466. // execute exit flow
  467. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  468. exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx())
  469. if err != nil {
  470. log.Error(err)
  471. return nil, nil, false, nil, tracerr.Wrap(err)
  472. }
  473. return &tx.FromIdx, exitAccount, newExit, nil, nil
  474. default:
  475. }
  476. var createdAccount *common.Account
  477. if s.typ == TypeSynchronizer && (tx.Type == common.TxTypeCreateAccountDeposit || tx.Type == common.TxTypeCreateAccountDepositTransfer) {
  478. var err error
  479. createdAccount, err = s.GetAccount(s.idx)
  480. if err != nil {
  481. log.Error(err)
  482. return nil, nil, false, nil, tracerr.Wrap(err)
  483. }
  484. }
  485. return nil, nil, false, createdAccount, nil
  486. }
  487. // processL2Tx process the given L2Tx applying the needed updates to the
  488. // StateDB depending on the transaction Type. It returns the 3 parameters
  489. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  490. // the Exit created a new Leaf in the ExitTree.
  491. func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
  492. exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  493. var err error
  494. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  495. if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
  496. if s.typ == TypeSynchronizer {
  497. // this should never be reached
  498. log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
  499. return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
  500. }
  501. // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
  502. tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID)
  503. if err != nil {
  504. return nil, nil, false, tracerr.Wrap(err)
  505. }
  506. }
  507. // ZKInputs
  508. if s.zki != nil {
  509. // Txs
  510. s.zki.TxCompressedData[s.i], err = tx.TxCompressedData()
  511. if err != nil {
  512. return nil, nil, false, tracerr.Wrap(err)
  513. }
  514. s.zki.TxCompressedDataV2[s.i], err = tx.TxCompressedDataV2()
  515. if err != nil {
  516. return nil, nil, false, tracerr.Wrap(err)
  517. }
  518. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  519. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  520. // fill AuxToIdx if needed
  521. if tx.ToIdx == 0 {
  522. // use toIdx that can have been filled by tx.ToIdx or
  523. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  524. // from db by ToEthAddr&ToBJJ
  525. s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
  526. }
  527. if tx.ToBJJ != nil {
  528. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  529. }
  530. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  531. s.zki.OnChain[s.i] = big.NewInt(0)
  532. s.zki.NewAccount[s.i] = big.NewInt(0)
  533. // L2Txs
  534. // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
  535. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  536. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  537. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  538. signature, err := tx.Signature.Decompress()
  539. if err != nil {
  540. log.Error(err)
  541. return nil, nil, false, tracerr.Wrap(err)
  542. }
  543. s.zki.S[s.i] = signature.S
  544. s.zki.R8x[s.i] = signature.R8.X
  545. s.zki.R8y[s.i] = signature.R8.Y
  546. }
  547. // if StateDB type==TypeSynchronizer, will need to add Nonce
  548. if s.typ == TypeSynchronizer {
  549. // as type==TypeSynchronizer, always tx.ToIdx!=0
  550. acc, err := s.GetAccount(tx.FromIdx)
  551. if err != nil {
  552. log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
  553. return nil, nil, false, tracerr.Wrap(err)
  554. }
  555. tx.Nonce = acc.Nonce + 1
  556. tx.TokenID = acc.TokenID
  557. }
  558. switch tx.Type {
  559. case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
  560. // go to the MT account of sender and receiver, and update
  561. // balance & nonce
  562. err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
  563. if err != nil {
  564. log.Error(err)
  565. return nil, nil, false, tracerr.Wrap(err)
  566. }
  567. case common.TxTypeExit:
  568. // execute exit flow
  569. exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
  570. if err != nil {
  571. log.Error(err)
  572. return nil, nil, false, tracerr.Wrap(err)
  573. }
  574. return &tx.FromIdx, exitAccount, newExit, nil
  575. default:
  576. }
  577. return nil, nil, false, nil
  578. }
  579. // applyCreateAccount creates a new account in the account of the depositer, it
  580. // stores the deposit value
  581. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  582. account := &common.Account{
  583. TokenID: tx.TokenID,
  584. Nonce: 0,
  585. Balance: tx.EffectiveDepositAmount,
  586. PublicKey: tx.FromBJJ,
  587. EthAddr: tx.FromEthAddr,
  588. }
  589. p, err := s.CreateAccount(common.Idx(s.idx+1), account)
  590. if err != nil {
  591. return tracerr.Wrap(err)
  592. }
  593. if s.zki != nil {
  594. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  595. s.zki.Nonce1[s.i] = big.NewInt(0)
  596. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  597. s.zki.Sign1[s.i] = big.NewInt(1)
  598. }
  599. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  600. s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
  601. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  602. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  603. if p.IsOld0 {
  604. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  605. }
  606. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  607. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  608. s.zki.Metadata.NewLastIdxRaw = s.idx + 1
  609. s.zki.AuxFromIdx[s.i] = common.Idx(s.idx + 1).BigInt()
  610. s.zki.NewAccount[s.i] = big.NewInt(1)
  611. if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
  612. // intermediate states
  613. s.zki.ISOnChain[s.i] = big.NewInt(1)
  614. }
  615. }
  616. s.idx = s.idx + 1
  617. return s.setIdx(s.idx)
  618. }
  619. // applyDeposit updates the balance in the account of the depositer, if
  620. // andTransfer parameter is set to true, the method will also apply the
  621. // Transfer of the L1Tx/DepositTransfer
  622. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  623. accSender, err := s.GetAccount(tx.FromIdx)
  624. if err != nil {
  625. return tracerr.Wrap(err)
  626. }
  627. if s.zki != nil {
  628. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  629. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  630. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  631. s.zki.Sign1[s.i] = big.NewInt(1)
  632. }
  633. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  634. s.zki.Balance1[s.i] = accSender.Balance
  635. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  636. }
  637. // add the deposit to the sender
  638. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
  639. // subtract amount to the sender
  640. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  641. // update sender account in localStateDB
  642. p, err := s.UpdateAccount(tx.FromIdx, accSender)
  643. if err != nil {
  644. return tracerr.Wrap(err)
  645. }
  646. if s.zki != nil {
  647. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  648. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  649. }
  650. // in case that the tx is a L1Tx>DepositTransfer
  651. var accReceiver *common.Account
  652. if transfer {
  653. if tx.ToIdx == tx.FromIdx {
  654. accReceiver = accSender
  655. } else {
  656. accReceiver, err = s.GetAccount(tx.ToIdx)
  657. if err != nil {
  658. return tracerr.Wrap(err)
  659. }
  660. }
  661. if s.zki != nil {
  662. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  663. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  664. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  665. s.zki.Sign2[s.i] = big.NewInt(1)
  666. }
  667. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  668. s.zki.Balance2[s.i] = accReceiver.Balance
  669. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  670. }
  671. // add amount to the receiver
  672. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  673. // update receiver account in localStateDB
  674. p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  675. if err != nil {
  676. return tracerr.Wrap(err)
  677. }
  678. if s.zki != nil {
  679. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  680. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  681. }
  682. }
  683. return nil
  684. }
  685. // applyTransfer updates the balance & nonce in the account of the sender, and
  686. // the balance in the account of the receiver.
  687. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  688. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  689. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  690. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  691. func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
  692. collectedFees map[common.TokenID]*big.Int,
  693. tx common.Tx, auxToIdx common.Idx) error {
  694. if auxToIdx == common.Idx(0) {
  695. auxToIdx = tx.ToIdx
  696. }
  697. // get sender and receiver accounts from localStateDB
  698. accSender, err := s.GetAccount(tx.FromIdx)
  699. if err != nil {
  700. log.Error(err)
  701. return tracerr.Wrap(err)
  702. }
  703. if s.zki != nil {
  704. // Set the State1 before updating the Sender leaf
  705. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  706. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  707. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  708. s.zki.Sign1[s.i] = big.NewInt(1)
  709. }
  710. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  711. s.zki.Balance1[s.i] = accSender.Balance
  712. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  713. }
  714. if !tx.IsL1 {
  715. // increment nonce
  716. accSender.Nonce++
  717. // compute fee and subtract it from the accSender
  718. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  719. if err != nil {
  720. return tracerr.Wrap(err)
  721. }
  722. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  723. accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
  724. if _, ok := coordIdxsMap[accSender.TokenID]; ok {
  725. accCoord, err := s.GetAccount(coordIdxsMap[accSender.TokenID])
  726. if err != nil {
  727. return tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", accSender.TokenID, coordIdxsMap[accSender.TokenID]))
  728. }
  729. // accumulate the fee for the Coord account
  730. accumulated := s.accumulatedFees[accCoord.Idx]
  731. accumulated.Add(accumulated, fee)
  732. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  733. collected := collectedFees[accCoord.TokenID]
  734. collected.Add(collected, fee)
  735. }
  736. } else {
  737. log.Debugw("No coord Idx to receive fee", "tx", tx)
  738. }
  739. } else {
  740. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  741. }
  742. // update sender account in localStateDB
  743. pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
  744. if err != nil {
  745. log.Error(err)
  746. return tracerr.Wrap(err)
  747. }
  748. if s.zki != nil {
  749. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
  750. }
  751. var accReceiver *common.Account
  752. if auxToIdx == tx.FromIdx {
  753. // if Sender is the Receiver, reuse 'accSender' pointer,
  754. // because in the DB the account for 'auxToIdx' won't be
  755. // updated yet
  756. accReceiver = accSender
  757. } else {
  758. accReceiver, err = s.GetAccount(auxToIdx)
  759. if err != nil {
  760. log.Error(err)
  761. return tracerr.Wrap(err)
  762. }
  763. }
  764. if s.zki != nil {
  765. // Set the State2 before updating the Receiver leaf
  766. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  767. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  768. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  769. s.zki.Sign2[s.i] = big.NewInt(1)
  770. }
  771. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  772. s.zki.Balance2[s.i] = accReceiver.Balance
  773. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  774. }
  775. // add amount-feeAmount to the receiver
  776. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  777. // update receiver account in localStateDB
  778. pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
  779. if err != nil {
  780. return tracerr.Wrap(err)
  781. }
  782. if s.zki != nil {
  783. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  784. }
  785. return nil
  786. }
  787. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  788. // makes a deposit, and performs a transfer to another account
  789. func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  790. auxFromIdx := common.Idx(s.idx + 1)
  791. accSender := &common.Account{
  792. TokenID: tx.TokenID,
  793. Nonce: 0,
  794. Balance: tx.EffectiveDepositAmount,
  795. PublicKey: tx.FromBJJ,
  796. EthAddr: tx.FromEthAddr,
  797. }
  798. if s.zki != nil {
  799. // Set the State1 before updating the Sender leaf
  800. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  801. s.zki.Nonce1[s.i] = big.NewInt(0)
  802. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  803. s.zki.Sign1[s.i] = big.NewInt(1)
  804. }
  805. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  806. s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
  807. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  808. }
  809. // subtract amount to the sender
  810. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  811. // create Account of the Sender
  812. p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
  813. if err != nil {
  814. return tracerr.Wrap(err)
  815. }
  816. if s.zki != nil {
  817. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  818. if p.IsOld0 {
  819. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  820. }
  821. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  822. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  823. s.zki.Metadata.NewLastIdxRaw = s.idx + 1
  824. s.zki.AuxFromIdx[s.i] = auxFromIdx.BigInt()
  825. s.zki.NewAccount[s.i] = big.NewInt(1)
  826. // intermediate states
  827. s.zki.ISOnChain[s.i] = big.NewInt(1)
  828. }
  829. var accReceiver *common.Account
  830. if tx.ToIdx == auxFromIdx {
  831. accReceiver = accSender
  832. } else {
  833. accReceiver, err = s.GetAccount(tx.ToIdx)
  834. if err != nil {
  835. log.Error(err)
  836. return tracerr.Wrap(err)
  837. }
  838. }
  839. if s.zki != nil {
  840. // Set the State2 before updating the Receiver leaf
  841. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  842. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  843. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  844. s.zki.Sign2[s.i] = big.NewInt(1)
  845. }
  846. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  847. s.zki.Balance2[s.i] = accReceiver.Balance
  848. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  849. }
  850. // add amount to the receiver
  851. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  852. // update receiver account in localStateDB
  853. p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  854. if err != nil {
  855. return tracerr.Wrap(err)
  856. }
  857. if s.zki != nil {
  858. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  859. }
  860. s.idx = s.idx + 1
  861. return s.setIdx(s.idx)
  862. }
  863. // It returns the ExitAccount and a boolean determining if the Exit created a
  864. // new Leaf in the ExitTree.
  865. func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
  866. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  867. tx common.Tx) (*common.Account, bool, error) {
  868. // 0. subtract tx.Amount from current Account in StateMT
  869. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  870. acc, err := s.GetAccount(tx.FromIdx)
  871. if err != nil {
  872. return nil, false, tracerr.Wrap(err)
  873. }
  874. if s.zki != nil {
  875. s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
  876. s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
  877. if babyjub.PointCoordSign(acc.PublicKey.X) {
  878. s.zki.Sign1[s.i] = big.NewInt(1)
  879. }
  880. s.zki.Ay1[s.i] = acc.PublicKey.Y
  881. s.zki.Balance1[s.i] = acc.Balance
  882. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  883. s.zki.NewExit[s.i] = big.NewInt(1)
  884. }
  885. if !tx.IsL1 {
  886. // increment nonce
  887. acc.Nonce++
  888. // compute fee and subtract it from the accSender
  889. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  890. if err != nil {
  891. return nil, false, tracerr.Wrap(err)
  892. }
  893. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  894. acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
  895. if _, ok := coordIdxsMap[acc.TokenID]; ok {
  896. accCoord, err := s.GetAccount(coordIdxsMap[acc.TokenID])
  897. if err != nil {
  898. return nil, false, tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", acc.TokenID, coordIdxsMap[acc.TokenID]))
  899. }
  900. // accumulate the fee for the Coord account
  901. accumulated := s.accumulatedFees[accCoord.Idx]
  902. accumulated.Add(accumulated, fee)
  903. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  904. collected := collectedFees[accCoord.TokenID]
  905. collected.Add(collected, fee)
  906. }
  907. } else {
  908. log.Debugw("No coord Idx to receive fee", "tx", tx)
  909. }
  910. } else {
  911. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  912. }
  913. p, err := s.UpdateAccount(tx.FromIdx, acc)
  914. if err != nil {
  915. return nil, false, tracerr.Wrap(err)
  916. }
  917. if s.zki != nil {
  918. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  919. }
  920. if exitTree == nil {
  921. return nil, false, nil
  922. }
  923. exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  924. if tracerr.Unwrap(err) == db.ErrNotFound {
  925. // 1a. if idx does not exist in exitTree:
  926. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
  927. exitAccount := &common.Account{
  928. TokenID: acc.TokenID,
  929. Nonce: common.Nonce(0),
  930. Balance: tx.Amount,
  931. PublicKey: acc.PublicKey,
  932. EthAddr: acc.EthAddr,
  933. }
  934. if s.zki != nil {
  935. // Set the State2 before creating the Exit leaf
  936. s.zki.TokenID2[s.i] = acc.TokenID.BigInt()
  937. s.zki.Nonce2[s.i] = big.NewInt(0)
  938. if babyjub.PointCoordSign(acc.PublicKey.X) {
  939. s.zki.Sign2[s.i] = big.NewInt(1)
  940. }
  941. s.zki.Ay2[s.i] = acc.PublicKey.Y
  942. s.zki.Balance2[s.i] = tx.Amount
  943. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  944. }
  945. p, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  946. if err != nil {
  947. return nil, false, tracerr.Wrap(err)
  948. }
  949. if s.zki != nil {
  950. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  951. if p.IsOld0 {
  952. s.zki.IsOld0_2[s.i] = big.NewInt(1)
  953. }
  954. s.zki.OldKey2[s.i] = p.OldKey.BigInt()
  955. s.zki.OldValue2[s.i] = p.OldValue.BigInt()
  956. s.zki.ISExitRoot[s.i] = exitTree.Root().BigInt()
  957. }
  958. return exitAccount, true, nil
  959. } else if err != nil {
  960. return exitAccount, false, tracerr.Wrap(err)
  961. }
  962. // 1b. if idx already exist in exitTree:
  963. if s.zki != nil {
  964. // Set the State2 before updating the Exit leaf
  965. s.zki.TokenID2[s.i] = acc.TokenID.BigInt()
  966. s.zki.Nonce2[s.i] = big.NewInt(0)
  967. if babyjub.PointCoordSign(acc.PublicKey.X) {
  968. s.zki.Sign2[s.i] = big.NewInt(1)
  969. }
  970. s.zki.Ay2[s.i] = acc.PublicKey.Y
  971. s.zki.Balance2[s.i] = tx.Amount
  972. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  973. }
  974. // update account, where account.Balance += exitAmount
  975. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  976. p, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  977. if err != nil {
  978. return nil, false, tracerr.Wrap(err)
  979. }
  980. if s.zki != nil {
  981. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  982. if p.IsOld0 {
  983. s.zki.IsOld0_2[s.i] = big.NewInt(1)
  984. }
  985. s.zki.OldKey2[s.i] = p.OldKey.BigInt()
  986. s.zki.OldValue2[s.i] = p.OldValue.BigInt()
  987. }
  988. return exitAccount, false, nil
  989. }
  990. // computeEffectiveAmounts checks that the L1Tx data is correct
  991. func (s *StateDB) computeEffectiveAmounts(tx *common.L1Tx) {
  992. if !tx.UserOrigin {
  993. // case where the L1Tx is generated by the Coordinator
  994. tx.EffectiveAmount = big.NewInt(0)
  995. tx.EffectiveDepositAmount = big.NewInt(0)
  996. return
  997. }
  998. tx.EffectiveAmount = tx.Amount
  999. tx.EffectiveDepositAmount = tx.DepositAmount
  1000. if tx.Type == common.TxTypeCreateAccountDeposit {
  1001. return
  1002. }
  1003. if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
  1004. // CreateAccountDepositTransfer case
  1005. cmp := tx.DepositAmount.Cmp(tx.Amount)
  1006. if cmp == -1 { // DepositAmount<Amount
  1007. tx.EffectiveAmount = big.NewInt(0)
  1008. return
  1009. }
  1010. return
  1011. }
  1012. accSender, err := s.GetAccount(tx.FromIdx)
  1013. if err != nil {
  1014. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d", tx.FromIdx)
  1015. tx.EffectiveDepositAmount = big.NewInt(0)
  1016. tx.EffectiveAmount = big.NewInt(0)
  1017. return
  1018. }
  1019. // check that tx.TokenID corresponds to the Sender account TokenID
  1020. if tx.TokenID != accSender.TokenID {
  1021. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.TokenID (%d) !=sender account TokenID (%d)", tx.TokenID, accSender.TokenID)
  1022. tx.EffectiveDepositAmount = big.NewInt(0)
  1023. tx.EffectiveAmount = big.NewInt(0)
  1024. return
  1025. }
  1026. // check that Sender has enough balance
  1027. bal := accSender.Balance
  1028. if tx.DepositAmount != nil {
  1029. bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
  1030. }
  1031. cmp := bal.Cmp(tx.Amount)
  1032. if cmp == -1 {
  1033. log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
  1034. tx.EffectiveAmount = big.NewInt(0)
  1035. return
  1036. }
  1037. // check that the tx.FromEthAddr is the same than the EthAddress of the
  1038. // Sender
  1039. if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
  1040. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.FromEthAddr (%s) must be the same EthAddr of the sender account by the Idx (%s)", tx.FromEthAddr.Hex(), accSender.EthAddr.Hex())
  1041. tx.EffectiveDepositAmount = big.NewInt(0)
  1042. tx.EffectiveAmount = big.NewInt(0)
  1043. return
  1044. }
  1045. if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
  1046. // if transfer is Exit type, there are no more checks
  1047. return
  1048. }
  1049. // check that TokenID is the same for Sender & Receiver account
  1050. accReceiver, err := s.GetAccount(tx.ToIdx)
  1051. if err != nil {
  1052. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
  1053. tx.EffectiveDepositAmount = big.NewInt(0)
  1054. tx.EffectiveAmount = big.NewInt(0)
  1055. return
  1056. }
  1057. if accSender.TokenID != accReceiver.TokenID {
  1058. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)", accSender.TokenID, accReceiver.TokenID)
  1059. tx.EffectiveDepositAmount = big.NewInt(0)
  1060. tx.EffectiveAmount = big.NewInt(0)
  1061. return
  1062. }
  1063. }
  1064. // GetIdx returns the stored Idx from the localStateDB, which is the last Idx
  1065. // used for an Account in the localStateDB.
  1066. func (s *StateDB) GetIdx() (common.Idx, error) {
  1067. idxBytes, err := s.DB().Get(keyidx)
  1068. if tracerr.Unwrap(err) == db.ErrNotFound {
  1069. return 0, nil
  1070. }
  1071. if err != nil {
  1072. return 0, tracerr.Wrap(err)
  1073. }
  1074. return common.IdxFromBytes(idxBytes[:])
  1075. }
  1076. // setIdx stores Idx in the localStateDB
  1077. func (s *StateDB) setIdx(idx common.Idx) error {
  1078. tx, err := s.DB().NewTx()
  1079. if err != nil {
  1080. return tracerr.Wrap(err)
  1081. }
  1082. idxBytes, err := idx.Bytes()
  1083. if err != nil {
  1084. return tracerr.Wrap(err)
  1085. }
  1086. err = tx.Put(keyidx, idxBytes[:])
  1087. if err != nil {
  1088. return tracerr.Wrap(err)
  1089. }
  1090. if err := tx.Commit(); err != nil {
  1091. return tracerr.Wrap(err)
  1092. }
  1093. return nil
  1094. }