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.

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