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.

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