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.

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