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.

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