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.

1315 lines
42 KiB

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