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.

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