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.

1337 lines
43 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. if tp.s.Type() == statedb.TypeSynchronizer {
  374. // once all txs processed (exitTree root frozen), for each
  375. // Exit, generate common.ExitInfo data
  376. var exitInfos []common.ExitInfo
  377. exitInfosByIdx := make(map[common.Idx]*common.ExitInfo)
  378. for i := 0; i < nTx; i++ {
  379. if !exits[i].exit {
  380. continue
  381. }
  382. exitIdx := exits[i].idx
  383. exitAccount := exits[i].acc
  384. // 0. generate MerkleProof
  385. p, err := exitTree.GenerateSCVerifierProof(exitIdx.BigInt(), nil)
  386. if err != nil {
  387. return nil, tracerr.Wrap(err)
  388. }
  389. // 1. generate common.ExitInfo
  390. ei := common.ExitInfo{
  391. AccountIdx: exitIdx,
  392. MerkleProof: p,
  393. Balance: exitAccount.Balance,
  394. }
  395. if prevExit, ok := exitInfosByIdx[exitIdx]; !ok {
  396. exitInfos = append(exitInfos, ei)
  397. exitInfosByIdx[exitIdx] = &exitInfos[len(exitInfos)-1]
  398. } else {
  399. *prevExit = ei
  400. }
  401. }
  402. // return exitInfos, createdAccounts and collectedFees, so
  403. // Synchronizer will be able to store it into HistoryDB for the
  404. // concrete BatchNum
  405. return &ProcessTxOutput{
  406. ZKInputs: nil,
  407. ExitInfos: exitInfos,
  408. CreatedAccounts: createdAccounts,
  409. CoordinatorIdxsMap: coordIdxsMap,
  410. CollectedFees: collectedFees,
  411. }, nil
  412. }
  413. // compute last ZKInputs parameters
  414. tp.zki.GlobalChainID = big.NewInt(int64(tp.config.ChainID))
  415. tp.zki.Metadata.NewStateRootRaw = tp.s.MT.Root()
  416. tp.zki.Metadata.NewExitRootRaw = exitTree.Root()
  417. // return ZKInputs as the BatchBuilder will return it to forge the Batch
  418. return &ProcessTxOutput{
  419. ZKInputs: tp.zki,
  420. ExitInfos: nil,
  421. CreatedAccounts: nil,
  422. CoordinatorIdxsMap: coordIdxsMap,
  423. CollectedFees: nil,
  424. }, nil
  425. }
  426. // getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
  427. // corresponding to the given CoordIdxs and the processed L2Txs
  428. func (tp *TxProcessor) getFeePlanTokens(coordIdxs []common.Idx) ([]*big.Int, error) {
  429. var tBI []*big.Int
  430. for i := 0; i < len(coordIdxs); i++ {
  431. acc, err := tp.s.GetAccount(coordIdxs[i])
  432. if err != nil {
  433. log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error())
  434. return nil, tracerr.Wrap(err)
  435. }
  436. tBI = append(tBI, acc.TokenID.BigInt())
  437. }
  438. return tBI, nil
  439. }
  440. // ProcessL1Tx process the given L1Tx applying the needed updates to the
  441. // StateDB depending on the transaction Type. It returns the 3 parameters
  442. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  443. // the Exit created a new Leaf in the ExitTree.
  444. // And another *common.Account parameter which contains the created account in
  445. // case that has been a new created account and that the StateDB is of type
  446. // TypeSynchronizer.
  447. func (tp *TxProcessor) ProcessL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx,
  448. *common.Account, bool, *common.Account, error) {
  449. // ZKInputs
  450. if tp.zki != nil {
  451. // Txs
  452. var err error
  453. tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
  454. if err != nil {
  455. log.Error(err)
  456. return nil, nil, false, nil, tracerr.Wrap(err)
  457. }
  458. tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
  459. tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
  460. tp.zki.OnChain[tp.i] = big.NewInt(1)
  461. // L1Txs
  462. depositAmountF40, err := common.NewFloat40(tx.DepositAmount)
  463. if err != nil {
  464. return nil, nil, false, nil, tracerr.Wrap(err)
  465. }
  466. tp.zki.DepositAmountF[tp.i] = big.NewInt(int64(depositAmountF40))
  467. tp.zki.FromEthAddr[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  468. if tx.FromBJJ != common.EmptyBJJComp {
  469. tp.zki.FromBJJCompressed[tp.i] = BJJCompressedTo256BigInts(tx.FromBJJ)
  470. }
  471. // Intermediate States, for all the transactions except for the last one
  472. if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
  473. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  474. }
  475. if tx.Type == common.TxTypeForceTransfer ||
  476. tx.Type == common.TxTypeDepositTransfer ||
  477. tx.Type == common.TxTypeCreateAccountDepositTransfer ||
  478. tx.Type == common.TxTypeForceExit {
  479. // in the cases where at L1Tx there is usage of the
  480. // Amount parameter, add it at the ZKInputs.AmountF
  481. // slot
  482. amountF40, err := common.NewFloat40(tx.Amount)
  483. if err != nil {
  484. return nil, nil, false, nil, tracerr.Wrap(err)
  485. }
  486. tp.zki.AmountF[tp.i] = big.NewInt(int64(amountF40))
  487. }
  488. }
  489. switch tx.Type {
  490. case common.TxTypeForceTransfer:
  491. tp.computeEffectiveAmounts(tx)
  492. // go to the MT account of sender and receiver, and update balance
  493. // & nonce
  494. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees.
  495. // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in
  496. // the Deposit type case.
  497. err := tp.applyTransfer(nil, nil, tx.Tx(), 0)
  498. if err != nil {
  499. log.Error(err)
  500. return nil, nil, false, nil, tracerr.Wrap(err)
  501. }
  502. case common.TxTypeCreateAccountDeposit:
  503. tp.computeEffectiveAmounts(tx)
  504. // add new account to the MT, update balance of the MT account
  505. err := tp.applyCreateAccount(tx)
  506. if err != nil {
  507. log.Error(err)
  508. return nil, nil, false, nil, tracerr.Wrap(err)
  509. }
  510. // TODO applyCreateAccount will return the created account,
  511. // which in the case type==TypeSynchronizer will be added to an
  512. // array of created accounts that will be returned
  513. case common.TxTypeDeposit:
  514. tp.computeEffectiveAmounts(tx)
  515. // update balance of the MT account
  516. err := tp.applyDeposit(tx, false)
  517. if err != nil {
  518. log.Error(err)
  519. return nil, nil, false, nil, tracerr.Wrap(err)
  520. }
  521. case common.TxTypeDepositTransfer:
  522. tp.computeEffectiveAmounts(tx)
  523. // update balance in MT account, update balance & nonce of sender
  524. // & receiver
  525. err := tp.applyDeposit(tx, true)
  526. if err != nil {
  527. log.Error(err)
  528. return nil, nil, false, nil, tracerr.Wrap(err)
  529. }
  530. case common.TxTypeCreateAccountDepositTransfer:
  531. tp.computeEffectiveAmounts(tx)
  532. // add new account to the merkletree, update balance in MT account,
  533. // update balance & nonce of sender & receiver
  534. err := tp.applyCreateAccountDepositTransfer(tx)
  535. if err != nil {
  536. log.Error(err)
  537. return nil, nil, false, nil, tracerr.Wrap(err)
  538. }
  539. case common.TxTypeForceExit:
  540. tp.computeEffectiveAmounts(tx)
  541. // execute exit flow
  542. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  543. exitAccount, newExit, err := tp.applyExit(nil, nil, exitTree, tx.Tx())
  544. if err != nil {
  545. log.Error(err)
  546. return nil, nil, false, nil, tracerr.Wrap(err)
  547. }
  548. return &tx.FromIdx, exitAccount, newExit, nil, nil
  549. default:
  550. }
  551. var createdAccount *common.Account
  552. if tp.s.Type() == statedb.TypeSynchronizer &&
  553. (tx.Type == common.TxTypeCreateAccountDeposit ||
  554. tx.Type == common.TxTypeCreateAccountDepositTransfer) {
  555. var err error
  556. createdAccount, err = tp.s.GetAccount(tp.s.CurrentIdx())
  557. if err != nil {
  558. log.Error(err)
  559. return nil, nil, false, nil, tracerr.Wrap(err)
  560. }
  561. }
  562. return nil, nil, false, createdAccount, nil
  563. }
  564. // ProcessL2Tx process the given L2Tx applying the needed updates to the
  565. // StateDB depending on the transaction Type. It returns the 3 parameters
  566. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  567. // the Exit created a new Leaf in the ExitTree.
  568. func (tp *TxProcessor) ProcessL2Tx(coordIdxsMap map[common.TokenID]common.Idx,
  569. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  570. tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  571. var err error
  572. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  573. if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
  574. if tp.s.Type() == statedb.TypeSynchronizer {
  575. // thisTypeould never be reached
  576. log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
  577. return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
  578. }
  579. // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
  580. accSender, err := tp.s.GetAccount(tx.FromIdx)
  581. if err != nil {
  582. return nil, nil, false, tracerr.Wrap(err)
  583. }
  584. tx.AuxToIdx, err = tp.s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, accSender.TokenID)
  585. if err != nil {
  586. return nil, nil, false, tracerr.Wrap(err)
  587. }
  588. }
  589. // ZKInputs
  590. if tp.zki != nil {
  591. // Txs
  592. tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
  593. if err != nil {
  594. return nil, nil, false, tracerr.Wrap(err)
  595. }
  596. tp.zki.TxCompressedDataV2[tp.i], err = tx.TxCompressedDataV2()
  597. if err != nil {
  598. return nil, nil, false, tracerr.Wrap(err)
  599. }
  600. tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
  601. tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
  602. // fill AuxToIdx if needed
  603. if tx.ToIdx == 0 {
  604. // use toIdx that can have been filled by tx.ToIdx or
  605. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  606. // from db by ToEthAddr&ToBJJ
  607. tp.zki.AuxToIdx[tp.i] = tx.AuxToIdx.BigInt()
  608. }
  609. if tx.ToBJJ != common.EmptyBJJComp {
  610. _, tp.zki.ToBJJAy[tp.i] = babyjub.UnpackSignY(tx.ToBJJ)
  611. }
  612. tp.zki.ToEthAddr[tp.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  613. tp.zki.OnChain[tp.i] = big.NewInt(0)
  614. amountF40, err := common.NewFloat40(tx.Amount)
  615. if err != nil {
  616. return nil, nil, false, tracerr.Wrap(err)
  617. }
  618. tp.zki.AmountF[tp.i] = big.NewInt(int64(amountF40))
  619. tp.zki.NewAccount[tp.i] = big.NewInt(0)
  620. // L2Txs
  621. // tp.zki.RqOffset[tp.i] = // TODO Rq once TxSelector is ready
  622. // tp.zki.RqTxCompressedDataV2[tp.i] = // TODO
  623. // tp.zki.RqToEthAddr[tp.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  624. // tp.zki.RqToBJJAy[tp.i] = tx.ToBJJ.Y // TODO
  625. signature, err := tx.Signature.Decompress()
  626. if err != nil {
  627. log.Error(err)
  628. return nil, nil, false, tracerr.Wrap(err)
  629. }
  630. tp.zki.S[tp.i] = signature.S
  631. tp.zki.R8x[tp.i] = signature.R8.X
  632. tp.zki.R8y[tp.i] = signature.R8.Y
  633. }
  634. // if StateDB type==TypeSynchronizer, will need to add Nonce
  635. if tp.s.Type() == statedb.TypeSynchronizer {
  636. // as tType==TypeSynchronizer, always tx.ToIdx!=0
  637. acc, err := tp.s.GetAccount(tx.FromIdx)
  638. if err != nil {
  639. log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
  640. return nil, nil, false, tracerr.Wrap(err)
  641. }
  642. tx.Nonce = acc.Nonce
  643. tx.TokenID = acc.TokenID
  644. }
  645. switch tx.Type {
  646. case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
  647. // go to the MT account of sender and receiver, and update
  648. // balance & nonce
  649. err = tp.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
  650. if err != nil {
  651. log.Error(err)
  652. return nil, nil, false, tracerr.Wrap(err)
  653. }
  654. case common.TxTypeExit:
  655. // execute exit flow
  656. exitAccount, newExit, err := tp.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
  657. if err != nil {
  658. log.Error(err)
  659. return nil, nil, false, tracerr.Wrap(err)
  660. }
  661. return &tx.FromIdx, exitAccount, newExit, nil
  662. default:
  663. }
  664. return nil, nil, false, nil
  665. }
  666. // applyCreateAccount creates a new account in the account of the depositer, it
  667. // stores the deposit value
  668. func (tp *TxProcessor) applyCreateAccount(tx *common.L1Tx) error {
  669. account := &common.Account{
  670. TokenID: tx.TokenID,
  671. Nonce: 0,
  672. Balance: tx.EffectiveDepositAmount,
  673. BJJ: tx.FromBJJ,
  674. EthAddr: tx.FromEthAddr,
  675. }
  676. p, err := tp.s.CreateAccount(common.Idx(tp.s.CurrentIdx()+1), account)
  677. if err != nil {
  678. return tracerr.Wrap(err)
  679. }
  680. if tp.zki != nil {
  681. tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
  682. tp.zki.Nonce1[tp.i] = big.NewInt(0)
  683. fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
  684. if fromBJJSign {
  685. tp.zki.Sign1[tp.i] = big.NewInt(1)
  686. }
  687. tp.zki.Ay1[tp.i] = fromBJJY
  688. tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
  689. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  690. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  691. if p.IsOld0 {
  692. tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
  693. }
  694. tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
  695. tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
  696. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
  697. tp.zki.AuxFromIdx[tp.i] = common.Idx(tp.s.CurrentIdx() + 1).BigInt()
  698. tp.zki.NewAccount[tp.i] = big.NewInt(1)
  699. if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
  700. // intermediate states
  701. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  702. }
  703. }
  704. return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
  705. }
  706. // applyDeposit updates the balance in the account of the depositer, if
  707. // andTransfer parameter is set to true, the method will also apply the
  708. // Transfer of the L1Tx/DepositTransfer
  709. func (tp *TxProcessor) applyDeposit(tx *common.L1Tx, transfer bool) error {
  710. accSender, err := tp.s.GetAccount(tx.FromIdx)
  711. if err != nil {
  712. return tracerr.Wrap(err)
  713. }
  714. if tp.zki != nil {
  715. tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
  716. tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
  717. senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
  718. if senderBJJSign {
  719. tp.zki.Sign1[tp.i] = big.NewInt(1)
  720. }
  721. tp.zki.Ay1[tp.i] = senderBJJY
  722. tp.zki.Balance1[tp.i] = accSender.Balance
  723. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
  724. }
  725. // add the deposit to the sender
  726. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
  727. // subtract amount to the sender
  728. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  729. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  730. return newErrorNotEnoughBalance(tx.Tx())
  731. }
  732. // update sender account in localStateDB
  733. p, err := tp.s.UpdateAccount(tx.FromIdx, accSender)
  734. if err != nil {
  735. return tracerr.Wrap(err)
  736. }
  737. if tp.zki != nil {
  738. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  739. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  740. }
  741. // in case that the tx is a L1Tx>DepositTransfer
  742. var accReceiver *common.Account
  743. if transfer {
  744. if tx.ToIdx == tx.FromIdx {
  745. accReceiver = accSender
  746. } else {
  747. accReceiver, err = tp.s.GetAccount(tx.ToIdx)
  748. if err != nil {
  749. return tracerr.Wrap(err)
  750. }
  751. }
  752. if tp.zki != nil {
  753. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  754. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  755. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  756. if receiverBJJSign {
  757. tp.zki.Sign2[tp.i] = big.NewInt(1)
  758. }
  759. tp.zki.Ay2[tp.i] = receiverBJJY
  760. tp.zki.Balance2[tp.i] = accReceiver.Balance
  761. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  762. }
  763. // add amount to the receiver
  764. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  765. // update receiver account in localStateDB
  766. p, err := tp.s.UpdateAccount(tx.ToIdx, accReceiver)
  767. if err != nil {
  768. return tracerr.Wrap(err)
  769. }
  770. if tp.zki != nil {
  771. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  772. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  773. }
  774. }
  775. return nil
  776. }
  777. // applyTransfer updates the balance & nonce in the account of the sender, and
  778. // the balance in the account of the receiver.
  779. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  780. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  781. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  782. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  783. func (tp *TxProcessor) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
  784. collectedFees map[common.TokenID]*big.Int, tx common.Tx, auxToIdx common.Idx) error {
  785. if auxToIdx == common.Idx(0) {
  786. auxToIdx = tx.ToIdx
  787. }
  788. // get sender and receiver accounts from localStateDB
  789. accSender, err := tp.s.GetAccount(tx.FromIdx)
  790. if err != nil {
  791. log.Error(err)
  792. return tracerr.Wrap(err)
  793. }
  794. if tp.zki != nil {
  795. // Set the State1 before updating the Sender leaf
  796. tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
  797. tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
  798. senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
  799. if senderBJJSign {
  800. tp.zki.Sign1[tp.i] = big.NewInt(1)
  801. }
  802. tp.zki.Ay1[tp.i] = senderBJJY
  803. tp.zki.Balance1[tp.i] = accSender.Balance
  804. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
  805. }
  806. if !tx.IsL1 { // L2
  807. // increment nonce
  808. accSender.Nonce++
  809. // compute fee and subtract it from the accSender
  810. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  811. if err != nil {
  812. return tracerr.Wrap(err)
  813. }
  814. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  815. accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
  816. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  817. return newErrorNotEnoughBalance(tx)
  818. }
  819. if _, ok := coordIdxsMap[accSender.TokenID]; ok {
  820. accCoord, err := tp.s.GetAccount(coordIdxsMap[accSender.TokenID])
  821. if err != nil {
  822. 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]))
  823. }
  824. // accumulate the fee for the Coord account
  825. accumulated := tp.AccumulatedFees[accCoord.Idx]
  826. accumulated.Add(accumulated, fee)
  827. if tp.s.Type() == statedb.TypeSynchronizer ||
  828. tp.s.Type() == statedb.TypeBatchBuilder {
  829. collected := collectedFees[accCoord.TokenID]
  830. collected.Add(collected, fee)
  831. }
  832. } else {
  833. log.Debugw("No coord Idx to receive fee", "tx", tx)
  834. }
  835. } else {
  836. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  837. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  838. return newErrorNotEnoughBalance(tx)
  839. }
  840. }
  841. // update sender account in localStateDB
  842. pSender, err := tp.s.UpdateAccount(tx.FromIdx, accSender)
  843. if err != nil {
  844. log.Error(err)
  845. return tracerr.Wrap(err)
  846. }
  847. if tp.zki != nil {
  848. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(pSender.Siblings)
  849. }
  850. var accReceiver *common.Account
  851. if auxToIdx == tx.FromIdx {
  852. // if Sender is the Receiver, reuse 'accSender' pointer,
  853. // because in the DB the account for 'auxToIdx' won't be
  854. // updated yet
  855. accReceiver = accSender
  856. } else {
  857. accReceiver, err = tp.s.GetAccount(auxToIdx)
  858. if err != nil {
  859. log.Error(err, auxToIdx)
  860. return tracerr.Wrap(err)
  861. }
  862. }
  863. if tp.zki != nil {
  864. // Set the State2 before updating the Receiver leaf
  865. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  866. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  867. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  868. if receiverBJJSign {
  869. tp.zki.Sign2[tp.i] = big.NewInt(1)
  870. }
  871. tp.zki.Ay2[tp.i] = receiverBJJY
  872. tp.zki.Balance2[tp.i] = accReceiver.Balance
  873. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  874. }
  875. // add amount-feeAmount to the receiver
  876. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  877. // update receiver account in localStateDB
  878. pReceiver, err := tp.s.UpdateAccount(auxToIdx, accReceiver)
  879. if err != nil {
  880. return tracerr.Wrap(err)
  881. }
  882. if tp.zki != nil {
  883. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  884. }
  885. return nil
  886. }
  887. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  888. // makes a deposit, and performs a transfer to another account
  889. func (tp *TxProcessor) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  890. auxFromIdx := common.Idx(tp.s.CurrentIdx() + 1)
  891. accSender := &common.Account{
  892. TokenID: tx.TokenID,
  893. Nonce: 0,
  894. Balance: tx.EffectiveDepositAmount,
  895. BJJ: tx.FromBJJ,
  896. EthAddr: tx.FromEthAddr,
  897. }
  898. if tp.zki != nil {
  899. // Set the State1 before updating the Sender leaf
  900. tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
  901. tp.zki.Nonce1[tp.i] = big.NewInt(0)
  902. fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
  903. if fromBJJSign {
  904. tp.zki.Sign1[tp.i] = big.NewInt(1)
  905. }
  906. tp.zki.Ay1[tp.i] = fromBJJY
  907. tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
  908. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  909. }
  910. // subtract amount to the sender
  911. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  912. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  913. return newErrorNotEnoughBalance(tx.Tx())
  914. }
  915. // create Account of the Sender
  916. p, err := tp.s.CreateAccount(common.Idx(tp.s.CurrentIdx()+1), accSender)
  917. if err != nil {
  918. return tracerr.Wrap(err)
  919. }
  920. if tp.zki != nil {
  921. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  922. if p.IsOld0 {
  923. tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
  924. }
  925. tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
  926. tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
  927. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
  928. tp.zki.AuxFromIdx[tp.i] = auxFromIdx.BigInt()
  929. tp.zki.NewAccount[tp.i] = big.NewInt(1)
  930. // intermediate states
  931. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  932. }
  933. var accReceiver *common.Account
  934. if tx.ToIdx == auxFromIdx {
  935. accReceiver = accSender
  936. } else {
  937. accReceiver, err = tp.s.GetAccount(tx.ToIdx)
  938. if err != nil {
  939. log.Error(err)
  940. return tracerr.Wrap(err)
  941. }
  942. }
  943. if tp.zki != nil {
  944. // Set the State2 before updating the Receiver leaf
  945. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  946. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  947. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  948. if receiverBJJSign {
  949. tp.zki.Sign2[tp.i] = big.NewInt(1)
  950. }
  951. tp.zki.Ay2[tp.i] = receiverBJJY
  952. tp.zki.Balance2[tp.i] = accReceiver.Balance
  953. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  954. }
  955. // add amount to the receiver
  956. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  957. // update receiver account in localStateDB
  958. p, err = tp.s.UpdateAccount(tx.ToIdx, accReceiver)
  959. if err != nil {
  960. return tracerr.Wrap(err)
  961. }
  962. if tp.zki != nil {
  963. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  964. }
  965. return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
  966. }
  967. // It returns the ExitAccount and a boolean determining if the Exit created a
  968. // new Leaf in the ExitTree.
  969. func (tp *TxProcessor) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
  970. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  971. tx common.Tx) (*common.Account, bool, error) {
  972. // 0. subtract tx.Amount from current Account in StateMT
  973. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  974. acc, err := tp.s.GetAccount(tx.FromIdx)
  975. if err != nil {
  976. return nil, false, tracerr.Wrap(err)
  977. }
  978. if tp.zki != nil {
  979. tp.zki.TokenID1[tp.i] = acc.TokenID.BigInt()
  980. tp.zki.Nonce1[tp.i] = acc.Nonce.BigInt()
  981. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  982. if accBJJSign {
  983. tp.zki.Sign1[tp.i] = big.NewInt(1)
  984. }
  985. tp.zki.Ay1[tp.i] = accBJJY
  986. tp.zki.Balance1[tp.i] = acc.Balance
  987. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  988. }
  989. if !tx.IsL1 {
  990. // increment nonce
  991. acc.Nonce++
  992. // compute fee and subtract it from the accSender
  993. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  994. if err != nil {
  995. return nil, false, tracerr.Wrap(err)
  996. }
  997. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  998. acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
  999. if acc.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1000. return nil, false, newErrorNotEnoughBalance(tx)
  1001. }
  1002. if _, ok := coordIdxsMap[acc.TokenID]; ok {
  1003. accCoord, err := tp.s.GetAccount(coordIdxsMap[acc.TokenID])
  1004. if err != nil {
  1005. 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]))
  1006. }
  1007. // accumulate the fee for the Coord account
  1008. accumulated := tp.AccumulatedFees[accCoord.Idx]
  1009. accumulated.Add(accumulated, fee)
  1010. if tp.s.Type() == statedb.TypeSynchronizer ||
  1011. tp.s.Type() == statedb.TypeBatchBuilder {
  1012. collected := collectedFees[accCoord.TokenID]
  1013. collected.Add(collected, fee)
  1014. }
  1015. } else {
  1016. log.Debugw("No coord Idx to receive fee", "tx", tx)
  1017. }
  1018. } else {
  1019. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  1020. if acc.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1021. return nil, false, newErrorNotEnoughBalance(tx)
  1022. }
  1023. }
  1024. p, err := tp.s.UpdateAccount(tx.FromIdx, acc)
  1025. if err != nil {
  1026. return nil, false, tracerr.Wrap(err)
  1027. }
  1028. if tp.zki != nil {
  1029. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1030. }
  1031. if exitTree == nil {
  1032. return nil, false, nil
  1033. }
  1034. exitAccount, err := statedb.GetAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  1035. if tracerr.Unwrap(err) == db.ErrNotFound {
  1036. // 1a. if idx does not exist in exitTree:
  1037. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance =
  1038. // exitAmount (exitAmount=tx.Amount)
  1039. exitAccount := &common.Account{
  1040. TokenID: acc.TokenID,
  1041. Nonce: common.Nonce(0),
  1042. Balance: tx.Amount,
  1043. BJJ: acc.BJJ,
  1044. EthAddr: acc.EthAddr,
  1045. }
  1046. if tp.zki != nil {
  1047. // Set the State2 before creating the Exit leaf
  1048. tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
  1049. tp.zki.Nonce2[tp.i] = big.NewInt(0)
  1050. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1051. if accBJJSign {
  1052. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1053. }
  1054. tp.zki.Ay2[tp.i] = accBJJY
  1055. tp.zki.Balance2[tp.i] = tx.Amount
  1056. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1057. // as Leaf didn't exist in the ExitTree, set NewExit[i]=1
  1058. tp.zki.NewExit[tp.i] = big.NewInt(1)
  1059. }
  1060. p, err = statedb.CreateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  1061. if err != nil {
  1062. return nil, false, tracerr.Wrap(err)
  1063. }
  1064. if tp.zki != nil {
  1065. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1066. if p.IsOld0 {
  1067. tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
  1068. }
  1069. tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
  1070. tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
  1071. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  1072. }
  1073. return exitAccount, true, nil
  1074. } else if err != nil {
  1075. return exitAccount, false, tracerr.Wrap(err)
  1076. }
  1077. // 1b. if idx already exist in exitTree:
  1078. if tp.zki != nil {
  1079. // Set the State2 before updating the Exit leaf
  1080. tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
  1081. // increment nonce from existing ExitLeaf
  1082. tp.zki.Nonce2[tp.i] = exitAccount.Nonce.BigInt()
  1083. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1084. if accBJJSign {
  1085. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1086. }
  1087. tp.zki.Ay2[tp.i] = accBJJY
  1088. tp.zki.Balance2[tp.i] = tx.Amount
  1089. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1090. }
  1091. // update account, where account.Balance += exitAmount
  1092. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  1093. p, err = statedb.UpdateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  1094. if err != nil {
  1095. return nil, false, tracerr.Wrap(err)
  1096. }
  1097. if tp.zki != nil {
  1098. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1099. if p.IsOld0 {
  1100. tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
  1101. }
  1102. tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
  1103. tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
  1104. }
  1105. return exitAccount, false, nil
  1106. }
  1107. // computeEffectiveAmounts checks that the L1Tx data is correct
  1108. func (tp *TxProcessor) computeEffectiveAmounts(tx *common.L1Tx) {
  1109. tx.EffectiveAmount = tx.Amount
  1110. tx.EffectiveDepositAmount = tx.DepositAmount
  1111. if !tx.UserOrigin {
  1112. // case where the L1Tx is generated by the Coordinator
  1113. tx.EffectiveAmount = big.NewInt(0)
  1114. tx.EffectiveDepositAmount = big.NewInt(0)
  1115. return
  1116. }
  1117. if tx.Type == common.TxTypeCreateAccountDeposit {
  1118. return
  1119. }
  1120. if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
  1121. // CreateAccountDepositTransfer case
  1122. cmp := tx.DepositAmount.Cmp(tx.Amount)
  1123. if cmp == -1 { // DepositAmount<Amount
  1124. tx.EffectiveAmount = big.NewInt(0)
  1125. return
  1126. }
  1127. // check if tx.TokenID==receiver.TokenID
  1128. accReceiver, err := tp.s.GetAccount(tx.ToIdx)
  1129. if err != nil {
  1130. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
  1131. tx.EffectiveDepositAmount = big.NewInt(0)
  1132. tx.EffectiveAmount = big.NewInt(0)
  1133. return
  1134. }
  1135. if tx.TokenID != accReceiver.TokenID {
  1136. log.Debugf("EffectiveAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accReceiver.TokenID)
  1137. tx.EffectiveAmount = big.NewInt(0)
  1138. return
  1139. }
  1140. return
  1141. }
  1142. accSender, err := tp.s.GetAccount(tx.FromIdx)
  1143. if err != nil {
  1144. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d", tx.FromIdx)
  1145. tx.EffectiveDepositAmount = big.NewInt(0)
  1146. tx.EffectiveAmount = big.NewInt(0)
  1147. return
  1148. }
  1149. // check that tx.TokenID corresponds to the Sender account TokenID
  1150. if tx.TokenID != accSender.TokenID {
  1151. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.TokenID (%d) !=sender account TokenID (%d)", tx.TokenID, accSender.TokenID)
  1152. tx.EffectiveDepositAmount = big.NewInt(0)
  1153. tx.EffectiveAmount = big.NewInt(0)
  1154. return
  1155. }
  1156. // check that Sender has enough balance
  1157. bal := accSender.Balance
  1158. if tx.DepositAmount != nil {
  1159. bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
  1160. }
  1161. cmp := bal.Cmp(tx.Amount)
  1162. if cmp == -1 {
  1163. log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
  1164. tx.EffectiveAmount = big.NewInt(0)
  1165. return
  1166. }
  1167. // check that the tx.FromEthAddr is the same than the EthAddress of the
  1168. // Sender
  1169. if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
  1170. 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())
  1171. tx.EffectiveAmount = big.NewInt(0)
  1172. }
  1173. if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
  1174. // if transfer is Exit type, there are no more checks
  1175. return
  1176. }
  1177. // check that TokenID is the same for Sender & Receiver account
  1178. accReceiver, err := tp.s.GetAccount(tx.ToIdx)
  1179. if err != nil {
  1180. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
  1181. tx.EffectiveDepositAmount = big.NewInt(0)
  1182. tx.EffectiveAmount = big.NewInt(0)
  1183. return
  1184. }
  1185. if accSender.TokenID != accReceiver.TokenID {
  1186. log.Debugf("EffectiveAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)", accSender.TokenID, accReceiver.TokenID)
  1187. tx.EffectiveAmount = big.NewInt(0)
  1188. return
  1189. }
  1190. if tx.TokenID != accReceiver.TokenID {
  1191. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accReceiver.TokenID)
  1192. tx.EffectiveAmount = big.NewInt(0)
  1193. return
  1194. }
  1195. }
  1196. // CheckEnoughBalance returns true if the sender of the transaction has enough
  1197. // balance in the account to send the Amount+Fee, and also returns the account
  1198. // Balance and the Fee+Amount (which is used to give information about why the
  1199. // transaction is not selected in case that this method returns false.
  1200. func (tp *TxProcessor) CheckEnoughBalance(tx common.PoolL2Tx) (bool, *big.Int, *big.Int) {
  1201. acc, err := tp.s.GetAccount(tx.FromIdx)
  1202. if err != nil {
  1203. return false, nil, nil
  1204. }
  1205. fee, err := common.CalcFeeAmount(tx.Amount, tx.Fee)
  1206. if err != nil {
  1207. return false, nil, nil
  1208. }
  1209. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  1210. return acc.Balance.Cmp(feeAndAmount) != -1, // !=-1 balance<amount
  1211. acc.Balance, feeAndAmount
  1212. }