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.

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