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.

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