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.

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