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.

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