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.

1317 lines
42 KiB

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