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.

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