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.

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