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.

1503 lines
49 KiB

  1. /*
  2. Package txprocessor is the module that takes the transactions from the input and
  3. processes them, updating the Balances and Nonces of the Accounts in the StateDB.
  4. It's a package used by 3 other different packages, and its behaviour will differ
  5. depending on the Type of the StateDB of the TxProcessor:
  6. - TypeSynchronizer:
  7. - The StateDB contains the full State MerkleTree, where the leafs are
  8. the accounts
  9. - Updates the StateDB and as output returns: ExitInfos, CreatedAccounts,
  10. CoordinatorIdxsMap, CollectedFees, UpdatedAccounts
  11. - Internally computes the ExitTree
  12. - TypeTxSelector:
  13. - The StateDB contains only the Accounts, which are the equivalent to
  14. only the leafs of the State MerkleTree
  15. - Updates the Accounts from the StateDB
  16. - TypeBatchBuilder:
  17. - The StateDB contains the full State MerkleTree, where the leafs are
  18. the accounts
  19. - Updates the StateDB. As output returns: ZKInputs, CoordinatorIdxsMap
  20. - Internally computes the ZKInputs
  21. Packages dependency overview:
  22. Outputs: + ExitInfos + + +
  23. | CreatedAccounts | | |
  24. | CoordinatorIdxsMap | | ZKInputs |
  25. | CollectedFees | | CoordinatorIdxsMap |
  26. | UpdatedAccounts | | |
  27. +------------------------+----------------+ +-----------------------+
  28. +------------+ +----------+ +------------+
  29. |Synchronizer| |TxSelector| |BatchBuilder|
  30. +-----+------+ +-----+----+ +-----+------+
  31. | | |
  32. v v v
  33. TxProcessor TxProcessor TxProcessor
  34. + + +
  35. | | |
  36. +----+----+ v +----+----+
  37. | | StateDB | |
  38. v v + v v
  39. StateDB ExitTree | StateDB ExitTree
  40. + +----+----+ +
  41. | | | |
  42. +----+----+ v v +----+----+
  43. | | KVDB AccountsDB | |
  44. v v v v
  45. KVDB MerkleTree KVDB MerkleTree
  46. The structure of the TxProcessor can be understand as:
  47. - StateDB: where the Rollup state is stored. It contains the Accounts &
  48. MerkleTree.
  49. - Config: parameters of the configuration of the circuit
  50. - ZKInputs: computed inputs for the circuit, depends on the Config parameters
  51. - ExitTree: only in the TypeSynchronizer & TypeBatchBuilder, contains
  52. the MerkleTree with the processed Exits of the Batch
  53. The main exposed method of the TxProcessor is `ProcessTxs`, which as general
  54. lines does:
  55. - if type==(Synchronizer || BatchBuilder), creates an ephemeral ExitTree
  56. - processes:
  57. - L1UserTxs --> for each tx calls ProcessL1Tx()
  58. - L1CoordinatorTxs --> for each tx calls ProcessL1Tx()
  59. - L2Txs --> for each tx calls ProcessL2Tx()
  60. - internally, it computes the Fees
  61. - each transaction processment includes:
  62. - updating the Account Balances (for sender & receiver, and in
  63. case that there is fee, updates the fee receiver account)
  64. - which includes updating the State MerkleTree (except
  65. for the type==TxSelector, which only updates the
  66. Accounts (leafs))
  67. - in case of Synchronizer & BatchBuilder, updates the ExitTree
  68. for the txs of type Exit (L1 & L2)
  69. - in case of BatchBuilder, computes the ZKInputs while processing the txs
  70. - if type==Synchronizer, once all the txs are processed, for each Exit
  71. it generates the ExitInfo data
  72. */
  73. package txprocessor
  74. import (
  75. "bytes"
  76. "errors"
  77. "fmt"
  78. "io/ioutil"
  79. "math/big"
  80. "os"
  81. "github.com/hermeznetwork/hermez-node/common"
  82. "github.com/hermeznetwork/hermez-node/db/statedb"
  83. "github.com/hermeznetwork/hermez-node/log"
  84. "github.com/hermeznetwork/tracerr"
  85. "github.com/iden3/go-iden3-crypto/babyjub"
  86. "github.com/iden3/go-merkletree"
  87. "github.com/iden3/go-merkletree/db"
  88. "github.com/iden3/go-merkletree/db/pebble"
  89. )
  90. // TxProcessor represents the TxProcessor object
  91. type TxProcessor struct {
  92. s *statedb.StateDB
  93. zki *common.ZKInputs
  94. // i is the current transaction index in the ZKInputs generation (zki)
  95. i int
  96. // AccumulatedFees contains the accumulated fees for each token (Coord
  97. // Idx) in the processed batch
  98. AccumulatedFees map[common.Idx]*big.Int
  99. // updatedAccounts stores the last version of the account when it has
  100. // been created/updated by any of the processed transactions.
  101. updatedAccounts map[common.Idx]*common.Account
  102. config Config
  103. }
  104. // Config contains the TxProcessor configuration parameters
  105. type Config struct {
  106. NLevels uint32
  107. // MaxFeeTx is the maximum number of coordinator accounts that can receive fees
  108. MaxFeeTx uint32
  109. MaxTx uint32
  110. MaxL1Tx uint32
  111. // ChainID of the blockchain
  112. ChainID uint16
  113. }
  114. type processedExit struct {
  115. exit bool
  116. newExit bool
  117. idx common.Idx
  118. acc common.Account
  119. }
  120. // ProcessTxOutput contains the output of the ProcessTxs method
  121. type ProcessTxOutput struct {
  122. ZKInputs *common.ZKInputs
  123. ExitInfos []common.ExitInfo
  124. CreatedAccounts []common.Account
  125. CoordinatorIdxsMap map[common.TokenID]common.Idx
  126. CollectedFees map[common.TokenID]*big.Int
  127. // UpdatedAccounts returns the current state of each account
  128. // created/updated by any of the processed transactions.
  129. UpdatedAccounts map[common.Idx]*common.Account
  130. }
  131. func newErrorNotEnoughBalance(tx common.Tx) error {
  132. var msg error
  133. if tx.IsL1 {
  134. msg = fmt.Errorf("Invalid transaction, not enough balance on sender account. "+
  135. "TxID: %s, TxType: %s, FromIdx: %d, ToIdx: %d, Amount: %d",
  136. tx.TxID, tx.Type, tx.FromIdx, tx.ToIdx, tx.Amount)
  137. } else {
  138. msg = fmt.Errorf("Invalid transaction, not enough balance on sender account. "+
  139. "TxID: %s, TxType: %s, FromIdx: %d, ToIdx: %d, Amount: %d, Fee: %d",
  140. tx.TxID, tx.Type, tx.FromIdx, tx.ToIdx, tx.Amount, tx.Fee)
  141. }
  142. return tracerr.Wrap(msg)
  143. }
  144. // NewTxProcessor returns a new TxProcessor with the given *StateDB & Config
  145. func NewTxProcessor(sdb *statedb.StateDB, config Config) *TxProcessor {
  146. return &TxProcessor{
  147. s: sdb,
  148. zki: nil,
  149. i: 0,
  150. config: config,
  151. }
  152. }
  153. // StateDB returns a pointer to the StateDB of the TxProcessor
  154. func (tp *TxProcessor) StateDB() *statedb.StateDB {
  155. return tp.s
  156. }
  157. func (tp *TxProcessor) resetZKInputs() {
  158. tp.zki = nil
  159. tp.i = 0 // initialize current transaction index in the ZKInputs generation
  160. }
  161. // ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  162. // the StateDB depending on the transaction Type. If StateDB
  163. // type==TypeBatchBuilder, returns the common.ZKInputs to generate the
  164. // SnarkProof later used by the BatchBuilder. If StateDB
  165. // type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
  166. // returns common.ExitTreeLeaf that is later used by the Synchronizer to update
  167. // the HistoryDB, and adds Nonce & TokenID to the L2Txs.
  168. // And if TypeSynchronizer returns an array of common.Account with all the
  169. // created accounts.
  170. func (tp *TxProcessor) ProcessTxs(coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx,
  171. l2txs []common.PoolL2Tx) (ptOut *ProcessTxOutput, err error) {
  172. defer func() {
  173. if err == nil {
  174. err = tp.s.MakeCheckpoint()
  175. }
  176. }()
  177. var exitTree *merkletree.MerkleTree
  178. var createdAccounts []common.Account
  179. if tp.zki != nil {
  180. return nil, tracerr.Wrap(
  181. errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty"))
  182. }
  183. defer tp.resetZKInputs()
  184. if len(coordIdxs) >= int(tp.config.MaxFeeTx) {
  185. return nil, tracerr.Wrap(
  186. fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)",
  187. len(coordIdxs), tp.config.MaxFeeTx))
  188. }
  189. nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
  190. if nTx > int(tp.config.MaxTx) {
  191. return nil, tracerr.Wrap(
  192. fmt.Errorf("L1UserTx + L1CoordinatorTx + L2Tx (%d) can not be bigger than MaxTx (%d)",
  193. nTx, tp.config.MaxTx))
  194. }
  195. if len(l1usertxs)+len(l1coordinatortxs) > int(tp.config.MaxL1Tx) {
  196. return nil,
  197. tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx (%d) can not be bigger than MaxL1Tx (%d)",
  198. len(l1usertxs)+len(l1coordinatortxs), tp.config.MaxTx))
  199. }
  200. if tp.s.Type() == statedb.TypeSynchronizer {
  201. tp.updatedAccounts = make(map[common.Idx]*common.Account)
  202. }
  203. exits := make([]processedExit, nTx)
  204. if tp.s.Type() == statedb.TypeBatchBuilder {
  205. tp.zki = common.NewZKInputs(tp.config.ChainID, tp.config.MaxTx, tp.config.MaxL1Tx,
  206. tp.config.MaxFeeTx, tp.config.NLevels, (tp.s.CurrentBatch() + 1).BigInt())
  207. tp.zki.OldLastIdx = tp.s.CurrentIdx().BigInt()
  208. tp.zki.OldStateRoot = tp.s.MT.Root().BigInt()
  209. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx()
  210. }
  211. // TBD if ExitTree is only in memory or stored in disk, for the moment
  212. // is only needed in memory
  213. if tp.s.Type() == statedb.TypeSynchronizer || tp.s.Type() == statedb.TypeBatchBuilder {
  214. tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
  215. if err != nil {
  216. return nil, tracerr.Wrap(err)
  217. }
  218. defer func() {
  219. if err := os.RemoveAll(tmpDir); err != nil {
  220. log.Errorw("Deleting statedb temp exit tree", "err", err)
  221. }
  222. }()
  223. sto, err := pebble.NewPebbleStorage(tmpDir, false)
  224. if err != nil {
  225. return nil, tracerr.Wrap(err)
  226. }
  227. defer sto.Close()
  228. exitTree, err = merkletree.NewMerkleTree(sto, tp.s.MT.MaxLevels())
  229. if err != nil {
  230. return nil, tracerr.Wrap(err)
  231. }
  232. }
  233. // Process L1UserTxs
  234. for i := 0; i < len(l1usertxs); i++ {
  235. // assumption: l1usertx are sorted by L1Tx.Position
  236. exitIdx, exitAccount, newExit, createdAccount, err := tp.ProcessL1Tx(exitTree,
  237. &l1usertxs[i])
  238. if err != nil {
  239. return nil, tracerr.Wrap(err)
  240. }
  241. if tp.s.Type() == statedb.TypeSynchronizer {
  242. if createdAccount != nil {
  243. createdAccounts = append(createdAccounts, *createdAccount)
  244. l1usertxs[i].EffectiveFromIdx = createdAccount.Idx
  245. } else {
  246. l1usertxs[i].EffectiveFromIdx = l1usertxs[i].FromIdx
  247. }
  248. }
  249. if tp.zki != nil {
  250. l1TxData, err := l1usertxs[i].BytesGeneric()
  251. if err != nil {
  252. return nil, tracerr.Wrap(err)
  253. }
  254. tp.zki.Metadata.L1TxsData = append(tp.zki.Metadata.L1TxsData, l1TxData)
  255. l1TxDataAvailability, err :=
  256. l1usertxs[i].BytesDataAvailability(tp.zki.Metadata.NLevels)
  257. if err != nil {
  258. return nil, tracerr.Wrap(err)
  259. }
  260. tp.zki.Metadata.L1TxsDataAvailability =
  261. append(tp.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
  262. tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
  263. tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
  264. if exitIdx == nil {
  265. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  266. }
  267. }
  268. if tp.s.Type() == statedb.TypeSynchronizer || tp.s.Type() == statedb.TypeBatchBuilder {
  269. if exitIdx != nil && exitTree != nil && exitAccount != nil {
  270. exits[tp.i] = processedExit{
  271. exit: true,
  272. newExit: newExit,
  273. idx: *exitIdx,
  274. acc: *exitAccount,
  275. }
  276. }
  277. tp.i++
  278. }
  279. }
  280. // Process L1CoordinatorTxs
  281. for i := 0; i < len(l1coordinatortxs); i++ {
  282. exitIdx, _, _, createdAccount, err := tp.ProcessL1Tx(exitTree, &l1coordinatortxs[i])
  283. if err != nil {
  284. return nil, tracerr.Wrap(err)
  285. }
  286. if exitIdx != nil {
  287. log.Error("Unexpected Exit in L1CoordinatorTx")
  288. }
  289. if tp.s.Type() == statedb.TypeSynchronizer {
  290. if createdAccount != nil {
  291. createdAccounts = append(createdAccounts, *createdAccount)
  292. l1coordinatortxs[i].EffectiveFromIdx = createdAccount.Idx
  293. } else {
  294. l1coordinatortxs[i].EffectiveFromIdx = l1coordinatortxs[i].FromIdx
  295. }
  296. }
  297. if tp.zki != nil {
  298. l1TxData, err := l1coordinatortxs[i].BytesGeneric()
  299. if err != nil {
  300. return nil, tracerr.Wrap(err)
  301. }
  302. tp.zki.Metadata.L1TxsData = append(tp.zki.Metadata.L1TxsData, l1TxData)
  303. l1TxDataAvailability, err :=
  304. l1coordinatortxs[i].BytesDataAvailability(tp.zki.Metadata.NLevels)
  305. if err != nil {
  306. return nil, tracerr.Wrap(err)
  307. }
  308. tp.zki.Metadata.L1TxsDataAvailability =
  309. append(tp.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
  310. tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
  311. tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
  312. tp.i++
  313. }
  314. }
  315. // remove repeated CoordIdxs that are for the same TokenID (use the
  316. // first occurrence)
  317. usedCoordTokenIDs := make(map[common.TokenID]bool)
  318. var filteredCoordIdxs []common.Idx
  319. for i := 0; i < len(coordIdxs); i++ {
  320. accCoord, err := tp.s.GetAccount(coordIdxs[i])
  321. if err != nil {
  322. return nil, tracerr.Wrap(err)
  323. }
  324. if !usedCoordTokenIDs[accCoord.TokenID] {
  325. usedCoordTokenIDs[accCoord.TokenID] = true
  326. filteredCoordIdxs = append(filteredCoordIdxs, coordIdxs[i])
  327. }
  328. }
  329. coordIdxs = filteredCoordIdxs
  330. tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  331. for _, idx := range coordIdxs {
  332. tp.AccumulatedFees[idx] = big.NewInt(0)
  333. }
  334. // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
  335. // coordIdxs. In this way, if a coordIdx uses an Idx that is being
  336. // created in the current batch, at this point the Idx will be created
  337. coordIdxsMap, err := tp.s.GetTokenIDsFromIdxs(coordIdxs)
  338. if err != nil {
  339. return nil, tracerr.Wrap(err)
  340. }
  341. // collectedFees will contain the amount of fee collected for each
  342. // TokenID
  343. var collectedFees map[common.TokenID]*big.Int
  344. if tp.s.Type() == statedb.TypeSynchronizer || tp.s.Type() == statedb.TypeBatchBuilder {
  345. collectedFees = make(map[common.TokenID]*big.Int)
  346. for tokenID := range coordIdxsMap {
  347. collectedFees[tokenID] = big.NewInt(0)
  348. }
  349. }
  350. if tp.zki != nil {
  351. // get the feePlanTokens
  352. feePlanTokens, err := tp.getFeePlanTokens(coordIdxs)
  353. if err != nil {
  354. log.Error(err)
  355. return nil, tracerr.Wrap(err)
  356. }
  357. copy(tp.zki.FeePlanTokens, feePlanTokens)
  358. }
  359. // Process L2Txs
  360. for i := 0; i < len(l2txs); i++ {
  361. exitIdx, exitAccount, newExit, err := tp.ProcessL2Tx(coordIdxsMap, collectedFees,
  362. exitTree, &l2txs[i])
  363. if err != nil {
  364. return nil, tracerr.Wrap(err)
  365. }
  366. if tp.zki != nil {
  367. l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(tp.zki.Metadata.NLevels)
  368. if err != nil {
  369. return nil, tracerr.Wrap(err)
  370. }
  371. tp.zki.Metadata.L2TxsData = append(tp.zki.Metadata.L2TxsData, l2TxData)
  372. // Intermediate States
  373. if tp.i < nTx-1 {
  374. tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
  375. tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
  376. tp.zki.ISAccFeeOut[tp.i] = formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
  377. if exitIdx == nil {
  378. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  379. }
  380. }
  381. }
  382. if tp.s.Type() == statedb.TypeSynchronizer || tp.s.Type() == statedb.TypeBatchBuilder {
  383. if exitIdx != nil && exitTree != nil {
  384. exits[tp.i] = processedExit{
  385. exit: true,
  386. newExit: newExit,
  387. idx: *exitIdx,
  388. acc: *exitAccount,
  389. }
  390. }
  391. tp.i++
  392. }
  393. }
  394. if tp.zki != nil {
  395. // Fill the empty slots in the ZKInputs remaining after
  396. // processing all L1 & L2 txs
  397. txCompressedDataEmpty := common.TxCompressedDataEmpty(tp.config.ChainID)
  398. last := tp.i - 1
  399. if tp.i == 0 {
  400. last = 0
  401. }
  402. for i := last; i < int(tp.config.MaxTx); i++ {
  403. if i < int(tp.config.MaxTx)-1 {
  404. tp.zki.ISOutIdx[i] = tp.s.CurrentIdx().BigInt()
  405. tp.zki.ISStateRoot[i] = tp.s.MT.Root().BigInt()
  406. tp.zki.ISAccFeeOut[i] = formatAccumulatedFees(collectedFees,
  407. tp.zki.FeePlanTokens, coordIdxs)
  408. tp.zki.ISExitRoot[i] = exitTree.Root().BigInt()
  409. }
  410. if i >= tp.i {
  411. tp.zki.TxCompressedData[i] = txCompressedDataEmpty
  412. }
  413. }
  414. isFinalAccFee := formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
  415. copy(tp.zki.ISFinalAccFee, isFinalAccFee)
  416. // before computing the Fees txs, set the ISInitStateRootFee
  417. tp.zki.ISInitStateRootFee = tp.s.MT.Root().BigInt()
  418. }
  419. // distribute the AccumulatedFees from the processed L2Txs into the
  420. // Coordinator Idxs
  421. iFee := 0
  422. for _, idx := range coordIdxs {
  423. accumulatedFee := tp.AccumulatedFees[idx]
  424. // send the fee to the Idx of the Coordinator for the TokenID
  425. // (even if the AccumulatedFee==0, as is how the zk circuit
  426. // works)
  427. accCoord, err := tp.s.GetAccount(idx)
  428. if err != nil {
  429. log.Errorw("Can not distribute accumulated fees to coordinator account: "+
  430. "No coord Idx to receive fee", "idx", idx)
  431. return nil, tracerr.Wrap(err)
  432. }
  433. if tp.zki != nil {
  434. tp.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
  435. tp.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
  436. coordBJJSign, coordBJJY := babyjub.UnpackSignY(accCoord.BJJ)
  437. if coordBJJSign {
  438. tp.zki.Sign3[iFee] = big.NewInt(1)
  439. }
  440. tp.zki.Ay3[iFee] = coordBJJY
  441. tp.zki.Balance3[iFee] = accCoord.Balance
  442. tp.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
  443. }
  444. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  445. pFee, err := tp.updateAccount(idx, accCoord)
  446. if err != nil {
  447. log.Error(err)
  448. return nil, tracerr.Wrap(err)
  449. }
  450. if tp.zki != nil {
  451. tp.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
  452. tp.zki.ISStateRootFee[iFee] = tp.s.MT.Root().BigInt()
  453. }
  454. iFee++
  455. }
  456. if tp.zki != nil {
  457. for i := len(tp.AccumulatedFees); i < int(tp.config.MaxFeeTx)-1; i++ {
  458. tp.zki.ISStateRootFee[i] = tp.s.MT.Root().BigInt()
  459. }
  460. // add Coord Idx to ZKInputs.FeeTxsData
  461. for i := 0; i < len(coordIdxs); i++ {
  462. tp.zki.FeeIdxs[i] = coordIdxs[i].BigInt()
  463. }
  464. }
  465. if tp.s.Type() == statedb.TypeTxSelector {
  466. return nil, nil
  467. }
  468. if tp.s.Type() == statedb.TypeSynchronizer {
  469. // once all txs processed (exitTree root frozen), for each Exit,
  470. // generate common.ExitInfo data
  471. var exitInfos []common.ExitInfo
  472. exitInfosByIdx := make(map[common.Idx]*common.ExitInfo)
  473. for i := 0; i < nTx; i++ {
  474. if !exits[i].exit {
  475. continue
  476. }
  477. exitIdx := exits[i].idx
  478. exitAccount := exits[i].acc
  479. // 0. generate MerkleProof
  480. p, err := exitTree.GenerateSCVerifierProof(exitIdx.BigInt(), nil)
  481. if err != nil {
  482. return nil, tracerr.Wrap(err)
  483. }
  484. // 1. generate common.ExitInfo
  485. ei := common.ExitInfo{
  486. AccountIdx: exitIdx,
  487. MerkleProof: p,
  488. Balance: exitAccount.Balance,
  489. }
  490. if prevExit, ok := exitInfosByIdx[exitIdx]; !ok {
  491. exitInfos = append(exitInfos, ei)
  492. exitInfosByIdx[exitIdx] = &exitInfos[len(exitInfos)-1]
  493. } else {
  494. *prevExit = ei
  495. }
  496. }
  497. // retun exitInfos, createdAccounts and collectedFees, so Synchronizer will
  498. // be able to store it into HistoryDB for the concrete BatchNum
  499. return &ProcessTxOutput{
  500. ZKInputs: nil,
  501. ExitInfos: exitInfos,
  502. CreatedAccounts: createdAccounts,
  503. CoordinatorIdxsMap: coordIdxsMap,
  504. CollectedFees: collectedFees,
  505. UpdatedAccounts: tp.updatedAccounts,
  506. }, nil
  507. }
  508. // compute last ZKInputs parameters
  509. tp.zki.GlobalChainID = big.NewInt(int64(tp.config.ChainID))
  510. tp.zki.Metadata.NewStateRootRaw = tp.s.MT.Root()
  511. tp.zki.Metadata.NewExitRootRaw = exitTree.Root()
  512. // return ZKInputs as the BatchBuilder will return it to forge the Batch
  513. return &ProcessTxOutput{
  514. ZKInputs: tp.zki,
  515. ExitInfos: nil,
  516. CreatedAccounts: nil,
  517. CoordinatorIdxsMap: coordIdxsMap,
  518. CollectedFees: nil,
  519. }, nil
  520. }
  521. // getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
  522. // corresponding to the given CoordIdxs and the processed L2Txs
  523. func (tp *TxProcessor) getFeePlanTokens(coordIdxs []common.Idx) ([]*big.Int, error) {
  524. var tBI []*big.Int
  525. for i := 0; i < len(coordIdxs); i++ {
  526. acc, err := tp.s.GetAccount(coordIdxs[i])
  527. if err != nil {
  528. log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s",
  529. coordIdxs[i], err.Error())
  530. return nil, tracerr.Wrap(err)
  531. }
  532. tBI = append(tBI, acc.TokenID.BigInt())
  533. }
  534. return tBI, nil
  535. }
  536. // ProcessL1Tx process the given L1Tx applying the needed updates to the
  537. // StateDB depending on the transaction Type. It returns the 3 parameters
  538. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  539. // the Exit created a new Leaf in the ExitTree.
  540. // And another *common.Account parameter which contains the created account in
  541. // case that has been a new created account and that the StateDB is of type
  542. // TypeSynchronizer.
  543. func (tp *TxProcessor) ProcessL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx,
  544. *common.Account, bool, *common.Account, error) {
  545. // ZKInputs
  546. if tp.zki != nil {
  547. // Txs
  548. var err error
  549. tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
  550. if err != nil {
  551. log.Error(err)
  552. return nil, nil, false, nil, tracerr.Wrap(err)
  553. }
  554. tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
  555. tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
  556. tp.zki.OnChain[tp.i] = big.NewInt(1)
  557. // L1Txs
  558. depositAmountF40, err := common.NewFloat40(tx.DepositAmount)
  559. if err != nil {
  560. return nil, nil, false, nil, tracerr.Wrap(err)
  561. }
  562. tp.zki.DepositAmountF[tp.i] = big.NewInt(int64(depositAmountF40))
  563. tp.zki.FromEthAddr[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  564. if tx.FromBJJ != common.EmptyBJJComp {
  565. tp.zki.FromBJJCompressed[tp.i] = BJJCompressedTo256BigInts(tx.FromBJJ)
  566. }
  567. // Intermediate States, for all the transactions except for the last one
  568. if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
  569. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  570. }
  571. if tx.Type == common.TxTypeForceTransfer ||
  572. tx.Type == common.TxTypeDepositTransfer ||
  573. tx.Type == common.TxTypeCreateAccountDepositTransfer ||
  574. tx.Type == common.TxTypeForceExit {
  575. // in the cases where at L1Tx there is usage of the
  576. // Amount parameter, add it at the ZKInputs.AmountF
  577. // slot
  578. amountF40, err := common.NewFloat40(tx.Amount)
  579. if err != nil {
  580. return nil, nil, false, nil, tracerr.Wrap(err)
  581. }
  582. tp.zki.AmountF[tp.i] = big.NewInt(int64(amountF40))
  583. }
  584. }
  585. switch tx.Type {
  586. case common.TxTypeForceTransfer:
  587. tp.computeEffectiveAmounts(tx)
  588. // go to the MT account of sender and receiver, and update balance
  589. // & nonce
  590. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees.
  591. // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in
  592. // the Deposit type case.
  593. err := tp.applyTransfer(nil, nil, tx.Tx(), 0)
  594. if err != nil {
  595. log.Error(err)
  596. return nil, nil, false, nil, tracerr.Wrap(err)
  597. }
  598. case common.TxTypeCreateAccountDeposit:
  599. tp.computeEffectiveAmounts(tx)
  600. // add new account to the MT, update balance of the MT account
  601. err := tp.applyCreateAccount(tx)
  602. if err != nil {
  603. log.Error(err)
  604. return nil, nil, false, nil, tracerr.Wrap(err)
  605. }
  606. // TODO applyCreateAccount will return the created account,
  607. // which in the case type==TypeSynchronizer will be added to an
  608. // array of created accounts that will be returned
  609. case common.TxTypeDeposit:
  610. tp.computeEffectiveAmounts(tx)
  611. // update balance of the MT account
  612. err := tp.applyDeposit(tx, false)
  613. if err != nil {
  614. log.Error(err)
  615. return nil, nil, false, nil, tracerr.Wrap(err)
  616. }
  617. case common.TxTypeDepositTransfer:
  618. tp.computeEffectiveAmounts(tx)
  619. // update balance in MT account, update balance & nonce of sender
  620. // & receiver
  621. err := tp.applyDeposit(tx, true)
  622. if err != nil {
  623. log.Error(err)
  624. return nil, nil, false, nil, tracerr.Wrap(err)
  625. }
  626. case common.TxTypeCreateAccountDepositTransfer:
  627. tp.computeEffectiveAmounts(tx)
  628. // add new account to the merkletree, update balance in MT account,
  629. // update balance & nonce of sender & receiver
  630. err := tp.applyCreateAccountDepositTransfer(tx)
  631. if err != nil {
  632. log.Error(err)
  633. return nil, nil, false, nil, tracerr.Wrap(err)
  634. }
  635. case common.TxTypeForceExit:
  636. tp.computeEffectiveAmounts(tx)
  637. // execute exit flow
  638. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  639. exitAccount, newExit, err := tp.applyExit(nil, nil, exitTree, tx.Tx(), tx.Amount)
  640. if err != nil {
  641. log.Error(err)
  642. return nil, nil, false, nil, tracerr.Wrap(err)
  643. }
  644. return &tx.FromIdx, exitAccount, newExit, nil, nil
  645. default:
  646. }
  647. var createdAccount *common.Account
  648. if tp.s.Type() == statedb.TypeSynchronizer &&
  649. (tx.Type == common.TxTypeCreateAccountDeposit ||
  650. tx.Type == common.TxTypeCreateAccountDepositTransfer) {
  651. var err error
  652. createdAccount, err = tp.s.GetAccount(tp.s.CurrentIdx())
  653. if err != nil {
  654. log.Error(err)
  655. return nil, nil, false, nil, tracerr.Wrap(err)
  656. }
  657. }
  658. return nil, nil, false, createdAccount, nil
  659. }
  660. // ProcessL2Tx process the given L2Tx applying the needed updates to the
  661. // StateDB depending on the transaction Type. It returns the 3 parameters
  662. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  663. // the Exit created a new Leaf in the ExitTree.
  664. func (tp *TxProcessor) ProcessL2Tx(coordIdxsMap map[common.TokenID]common.Idx,
  665. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  666. tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  667. var err error
  668. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  669. if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
  670. if tp.s.Type() == statedb.TypeSynchronizer {
  671. // thisTypeould never be reached
  672. log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
  673. return nil, nil, false,
  674. tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
  675. }
  676. // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
  677. accSender, err := tp.s.GetAccount(tx.FromIdx)
  678. if err != nil {
  679. return nil, nil, false, tracerr.Wrap(err)
  680. }
  681. tx.AuxToIdx, err = tp.s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, accSender.TokenID)
  682. if err != nil {
  683. return nil, nil, false, tracerr.Wrap(err)
  684. }
  685. }
  686. // ZKInputs
  687. if tp.zki != nil {
  688. // Txs
  689. tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
  690. if err != nil {
  691. return nil, nil, false, tracerr.Wrap(err)
  692. }
  693. tp.zki.TxCompressedDataV2[tp.i], err = tx.TxCompressedDataV2()
  694. if err != nil {
  695. return nil, nil, false, tracerr.Wrap(err)
  696. }
  697. tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
  698. tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
  699. // fill AuxToIdx if needed
  700. if tx.ToIdx == 0 {
  701. // use toIdx that can have been filled by tx.ToIdx or
  702. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  703. // from db by ToEthAddr&ToBJJ
  704. tp.zki.AuxToIdx[tp.i] = tx.AuxToIdx.BigInt()
  705. }
  706. if tx.ToBJJ != common.EmptyBJJComp {
  707. _, tp.zki.ToBJJAy[tp.i] = babyjub.UnpackSignY(tx.ToBJJ)
  708. }
  709. tp.zki.ToEthAddr[tp.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  710. tp.zki.OnChain[tp.i] = big.NewInt(0)
  711. amountF40, err := common.NewFloat40(tx.Amount)
  712. if err != nil {
  713. return nil, nil, false, tracerr.Wrap(err)
  714. }
  715. tp.zki.AmountF[tp.i] = big.NewInt(int64(amountF40))
  716. tp.zki.NewAccount[tp.i] = big.NewInt(0)
  717. // L2Txs
  718. // tp.zki.RqOffset[tp.i] = // TODO Rq once TxSelector is ready
  719. // tp.zki.RqTxCompressedDataV2[tp.i] = // TODO
  720. // tp.zki.RqToEthAddr[tp.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  721. // tp.zki.RqToBJJAy[tp.i] = tx.ToBJJ.Y // TODO
  722. signature, err := tx.Signature.Decompress()
  723. if err != nil {
  724. log.Error(err)
  725. return nil, nil, false, tracerr.Wrap(err)
  726. }
  727. tp.zki.S[tp.i] = signature.S
  728. tp.zki.R8x[tp.i] = signature.R8.X
  729. tp.zki.R8y[tp.i] = signature.R8.Y
  730. }
  731. // if StateDB type==TypeSynchronizer, will need to add Nonce
  732. if tp.s.Type() == statedb.TypeSynchronizer {
  733. // as tType==TypeSynchronizer, always tx.ToIdx!=0
  734. acc, err := tp.s.GetAccount(tx.FromIdx)
  735. if err != nil {
  736. log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
  737. return nil, nil, false, tracerr.Wrap(err)
  738. }
  739. tx.Nonce = acc.Nonce
  740. tx.TokenID = acc.TokenID
  741. }
  742. switch tx.Type {
  743. case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
  744. // go to the MT account of sender and receiver, and update
  745. // balance & nonce
  746. err = tp.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
  747. if err != nil {
  748. log.Error(err)
  749. return nil, nil, false, tracerr.Wrap(err)
  750. }
  751. case common.TxTypeExit:
  752. // execute exit flow
  753. exitAccount, newExit, err := tp.applyExit(coordIdxsMap, collectedFees, exitTree,
  754. tx.Tx(), tx.Amount)
  755. if err != nil {
  756. log.Error(err)
  757. return nil, nil, false, tracerr.Wrap(err)
  758. }
  759. return &tx.FromIdx, exitAccount, newExit, nil
  760. default:
  761. }
  762. return nil, nil, false, nil
  763. }
  764. // applyCreateAccount creates a new account in the account of the depositer, it
  765. // stores the deposit value
  766. func (tp *TxProcessor) applyCreateAccount(tx *common.L1Tx) error {
  767. account := &common.Account{
  768. TokenID: tx.TokenID,
  769. Nonce: 0,
  770. Balance: tx.EffectiveDepositAmount,
  771. BJJ: tx.FromBJJ,
  772. EthAddr: tx.FromEthAddr,
  773. }
  774. p, err := tp.createAccount(common.Idx(tp.s.CurrentIdx()+1), account)
  775. if err != nil {
  776. return tracerr.Wrap(err)
  777. }
  778. if tp.zki != nil {
  779. tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
  780. tp.zki.Nonce1[tp.i] = big.NewInt(0)
  781. fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
  782. if fromBJJSign {
  783. tp.zki.Sign1[tp.i] = big.NewInt(1)
  784. }
  785. tp.zki.Ay1[tp.i] = fromBJJY
  786. tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
  787. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  788. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  789. if p.IsOld0 {
  790. tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
  791. }
  792. tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
  793. tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
  794. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
  795. tp.zki.AuxFromIdx[tp.i] = common.Idx(tp.s.CurrentIdx() + 1).BigInt()
  796. tp.zki.NewAccount[tp.i] = big.NewInt(1)
  797. if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
  798. // intermediate states
  799. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  800. }
  801. }
  802. return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
  803. }
  804. // createAccount is a wrapper over the StateDB.CreateAccount method that also
  805. // stores the created account in the updatedAccounts map in case the StateDB is
  806. // of TypeSynchronizer
  807. func (tp *TxProcessor) createAccount(idx common.Idx, account *common.Account) (
  808. *merkletree.CircomProcessorProof, error) {
  809. if tp.s.Type() == statedb.TypeSynchronizer {
  810. account.Idx = idx
  811. tp.updatedAccounts[idx] = account
  812. }
  813. return tp.s.CreateAccount(idx, account)
  814. }
  815. // updateAccount is a wrapper over the StateDB.UpdateAccount method that also
  816. // stores the updated account in the updatedAccounts map in case the StateDB is
  817. // of TypeSynchronizer
  818. func (tp *TxProcessor) updateAccount(idx common.Idx, account *common.Account) (
  819. *merkletree.CircomProcessorProof, error) {
  820. if tp.s.Type() == statedb.TypeSynchronizer {
  821. account.Idx = idx
  822. tp.updatedAccounts[idx] = account
  823. }
  824. return tp.s.UpdateAccount(idx, account)
  825. }
  826. // applyDeposit updates the balance in the account of the depositer, if
  827. // andTransfer parameter is set to true, the method will also apply the
  828. // Transfer of the L1Tx/DepositTransfer
  829. func (tp *TxProcessor) applyDeposit(tx *common.L1Tx, transfer bool) error {
  830. accSender, err := tp.s.GetAccount(tx.FromIdx)
  831. if err != nil {
  832. return tracerr.Wrap(err)
  833. }
  834. if tp.zki != nil {
  835. tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
  836. tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
  837. senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
  838. if senderBJJSign {
  839. tp.zki.Sign1[tp.i] = big.NewInt(1)
  840. }
  841. tp.zki.Ay1[tp.i] = senderBJJY
  842. tp.zki.Balance1[tp.i] = accSender.Balance
  843. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
  844. }
  845. // add the deposit to the sender
  846. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
  847. // subtract amount to the sender
  848. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  849. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  850. return newErrorNotEnoughBalance(tx.Tx())
  851. }
  852. // update sender account in localStateDB
  853. p, err := tp.updateAccount(tx.FromIdx, accSender)
  854. if err != nil {
  855. return tracerr.Wrap(err)
  856. }
  857. if tp.zki != nil {
  858. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  859. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  860. }
  861. // in case that the tx is a L1Tx>DepositTransfer
  862. var accReceiver *common.Account
  863. if transfer {
  864. if tx.ToIdx == tx.FromIdx {
  865. accReceiver = accSender
  866. } else {
  867. accReceiver, err = tp.s.GetAccount(tx.ToIdx)
  868. if err != nil {
  869. return tracerr.Wrap(err)
  870. }
  871. }
  872. if tp.zki != nil {
  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.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. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  893. }
  894. }
  895. return nil
  896. }
  897. // applyTransfer updates the balance & nonce in the account of the sender, and
  898. // the balance in the account of the receiver.
  899. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  900. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  901. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  902. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  903. func (tp *TxProcessor) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
  904. collectedFees map[common.TokenID]*big.Int, tx common.Tx, auxToIdx common.Idx) error {
  905. if auxToIdx == common.Idx(0) {
  906. auxToIdx = tx.ToIdx
  907. }
  908. // get sender and receiver accounts from localStateDB
  909. accSender, err := tp.s.GetAccount(tx.FromIdx)
  910. if err != nil {
  911. log.Error(err)
  912. return tracerr.Wrap(err)
  913. }
  914. if tp.zki != nil {
  915. // Set the State1 before updating the Sender leaf
  916. tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
  917. tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
  918. senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
  919. if senderBJJSign {
  920. tp.zki.Sign1[tp.i] = big.NewInt(1)
  921. }
  922. tp.zki.Ay1[tp.i] = senderBJJY
  923. tp.zki.Balance1[tp.i] = accSender.Balance
  924. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
  925. }
  926. if !tx.IsL1 { // L2
  927. // increment nonce
  928. accSender.Nonce++
  929. // compute fee and subtract it from the accSender
  930. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  931. if err != nil {
  932. return tracerr.Wrap(err)
  933. }
  934. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  935. accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
  936. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  937. return newErrorNotEnoughBalance(tx)
  938. }
  939. if _, ok := coordIdxsMap[accSender.TokenID]; ok {
  940. accCoord, err := tp.s.GetAccount(coordIdxsMap[accSender.TokenID])
  941. if err != nil {
  942. return tracerr.Wrap(
  943. fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d",
  944. accSender.TokenID, coordIdxsMap[accSender.TokenID]))
  945. }
  946. // accumulate the fee for the Coord account
  947. accumulated := tp.AccumulatedFees[accCoord.Idx]
  948. accumulated.Add(accumulated, fee)
  949. if tp.s.Type() == statedb.TypeSynchronizer ||
  950. tp.s.Type() == statedb.TypeBatchBuilder {
  951. collected := collectedFees[accCoord.TokenID]
  952. collected.Add(collected, fee)
  953. }
  954. } else {
  955. log.Debugw("No coord Idx to receive fee", "tx", tx)
  956. }
  957. } else {
  958. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  959. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  960. return newErrorNotEnoughBalance(tx)
  961. }
  962. }
  963. // update sender account in localStateDB
  964. pSender, err := tp.updateAccount(tx.FromIdx, accSender)
  965. if err != nil {
  966. log.Error(err)
  967. return tracerr.Wrap(err)
  968. }
  969. if tp.zki != nil {
  970. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(pSender.Siblings)
  971. }
  972. var accReceiver *common.Account
  973. if auxToIdx == tx.FromIdx {
  974. // if Sender is the Receiver, reuse 'accSender' pointer,
  975. // because in the DB the account for 'auxToIdx' won't be
  976. // updated yet
  977. accReceiver = accSender
  978. } else {
  979. accReceiver, err = tp.s.GetAccount(auxToIdx)
  980. if err != nil {
  981. log.Error(err, auxToIdx)
  982. return tracerr.Wrap(err)
  983. }
  984. }
  985. if tp.zki != nil {
  986. // Set the State2 before updating the Receiver leaf
  987. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  988. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  989. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  990. if receiverBJJSign {
  991. tp.zki.Sign2[tp.i] = big.NewInt(1)
  992. }
  993. tp.zki.Ay2[tp.i] = receiverBJJY
  994. tp.zki.Balance2[tp.i] = accReceiver.Balance
  995. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  996. }
  997. // add amount-feeAmount to the receiver
  998. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  999. // update receiver account in localStateDB
  1000. pReceiver, err := tp.updateAccount(auxToIdx, accReceiver)
  1001. if err != nil {
  1002. return tracerr.Wrap(err)
  1003. }
  1004. if tp.zki != nil {
  1005. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  1006. }
  1007. return nil
  1008. }
  1009. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  1010. // makes a deposit, and performs a transfer to another account
  1011. func (tp *TxProcessor) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  1012. auxFromIdx := common.Idx(tp.s.CurrentIdx() + 1)
  1013. accSender := &common.Account{
  1014. TokenID: tx.TokenID,
  1015. Nonce: 0,
  1016. Balance: tx.EffectiveDepositAmount,
  1017. BJJ: tx.FromBJJ,
  1018. EthAddr: tx.FromEthAddr,
  1019. }
  1020. if tp.zki != nil {
  1021. // Set the State1 before updating the Sender leaf
  1022. tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
  1023. tp.zki.Nonce1[tp.i] = big.NewInt(0)
  1024. fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
  1025. if fromBJJSign {
  1026. tp.zki.Sign1[tp.i] = big.NewInt(1)
  1027. }
  1028. tp.zki.Ay1[tp.i] = fromBJJY
  1029. tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
  1030. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  1031. }
  1032. // subtract amount to the sender
  1033. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  1034. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1035. return newErrorNotEnoughBalance(tx.Tx())
  1036. }
  1037. // create Account of the Sender
  1038. p, err := tp.createAccount(common.Idx(tp.s.CurrentIdx()+1), accSender)
  1039. if err != nil {
  1040. return tracerr.Wrap(err)
  1041. }
  1042. if tp.zki != nil {
  1043. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1044. if p.IsOld0 {
  1045. tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
  1046. }
  1047. tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
  1048. tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
  1049. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
  1050. tp.zki.AuxFromIdx[tp.i] = auxFromIdx.BigInt()
  1051. tp.zki.NewAccount[tp.i] = big.NewInt(1)
  1052. // intermediate states
  1053. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  1054. }
  1055. var accReceiver *common.Account
  1056. if tx.ToIdx == auxFromIdx {
  1057. accReceiver = accSender
  1058. } else {
  1059. accReceiver, err = tp.s.GetAccount(tx.ToIdx)
  1060. if err != nil {
  1061. log.Error(err)
  1062. return tracerr.Wrap(err)
  1063. }
  1064. }
  1065. if tp.zki != nil {
  1066. // Set the State2 before updating the Receiver leaf
  1067. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  1068. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  1069. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  1070. if receiverBJJSign {
  1071. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1072. }
  1073. tp.zki.Ay2[tp.i] = receiverBJJY
  1074. tp.zki.Balance2[tp.i] = accReceiver.Balance
  1075. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  1076. }
  1077. // add amount to the receiver
  1078. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  1079. // update receiver account in localStateDB
  1080. p, err = tp.updateAccount(tx.ToIdx, accReceiver)
  1081. if err != nil {
  1082. return tracerr.Wrap(err)
  1083. }
  1084. if tp.zki != nil {
  1085. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1086. }
  1087. return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
  1088. }
  1089. // It returns the ExitAccount and a boolean determining if the Exit created a
  1090. // new Leaf in the ExitTree.
  1091. func (tp *TxProcessor) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
  1092. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  1093. tx common.Tx, originalAmount *big.Int) (*common.Account, bool, error) {
  1094. // 0. subtract tx.Amount from current Account in StateMT
  1095. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  1096. acc, err := tp.s.GetAccount(tx.FromIdx)
  1097. if err != nil {
  1098. return nil, false, tracerr.Wrap(err)
  1099. }
  1100. if tp.zki != nil {
  1101. tp.zki.TokenID1[tp.i] = acc.TokenID.BigInt()
  1102. tp.zki.Nonce1[tp.i] = acc.Nonce.BigInt()
  1103. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1104. if accBJJSign {
  1105. tp.zki.Sign1[tp.i] = big.NewInt(1)
  1106. }
  1107. tp.zki.Ay1[tp.i] = accBJJY
  1108. tp.zki.Balance1[tp.i] = acc.Balance
  1109. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1110. }
  1111. if !tx.IsL1 {
  1112. // increment nonce
  1113. acc.Nonce++
  1114. // compute fee and subtract it from the accSender
  1115. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  1116. if err != nil {
  1117. return nil, false, tracerr.Wrap(err)
  1118. }
  1119. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  1120. acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
  1121. if acc.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1122. return nil, false, newErrorNotEnoughBalance(tx)
  1123. }
  1124. if _, ok := coordIdxsMap[acc.TokenID]; ok {
  1125. accCoord, err := tp.s.GetAccount(coordIdxsMap[acc.TokenID])
  1126. if err != nil {
  1127. return nil, false, tracerr.Wrap(
  1128. fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d",
  1129. acc.TokenID, coordIdxsMap[acc.TokenID]))
  1130. }
  1131. // accumulate the fee for the Coord account
  1132. accumulated := tp.AccumulatedFees[accCoord.Idx]
  1133. accumulated.Add(accumulated, fee)
  1134. if tp.s.Type() == statedb.TypeSynchronizer ||
  1135. tp.s.Type() == statedb.TypeBatchBuilder {
  1136. collected := collectedFees[accCoord.TokenID]
  1137. collected.Add(collected, fee)
  1138. }
  1139. } else {
  1140. log.Debugw("No coord Idx to receive fee", "tx", tx)
  1141. }
  1142. } else {
  1143. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  1144. if acc.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1145. return nil, false, newErrorNotEnoughBalance(tx)
  1146. }
  1147. }
  1148. p, err := tp.updateAccount(tx.FromIdx, acc)
  1149. if err != nil {
  1150. return nil, false, tracerr.Wrap(err)
  1151. }
  1152. if tp.zki != nil {
  1153. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1154. }
  1155. if exitTree == nil {
  1156. return nil, false, nil
  1157. }
  1158. // Do not add the Exit when Amount=0, not EffectiveAmount=0. In
  1159. // txprocessor.applyExit function, the tx.Amount is in reality the
  1160. // EffectiveAmount, that's why is used here the originalAmount
  1161. // parameter, which contains the real value of the tx.Amount (not
  1162. // tx.EffectiveAmount). This is a particularity of the approach of the
  1163. // circuit, the idea will be in the future to update the circuit and
  1164. // when Amount>0 but EffectiveAmount=0, to not add the Exit in the
  1165. // Exits MerkleTree, but for the moment the Go code is adapted to the
  1166. // circuit.
  1167. if originalAmount.Cmp(big.NewInt(0)) == 0 { // Amount == 0
  1168. // if the Exit Amount==0, the Exit is not added to the ExitTree
  1169. return nil, false, nil
  1170. }
  1171. exitAccount, err := statedb.GetAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  1172. if tracerr.Unwrap(err) == db.ErrNotFound {
  1173. // 1a. if idx does not exist in exitTree:
  1174. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance =
  1175. // exitAmount (exitAmount=tx.Amount)
  1176. exitAccount := &common.Account{
  1177. TokenID: acc.TokenID,
  1178. Nonce: common.Nonce(0),
  1179. // as is a common.Tx, the tx.Amount is already an
  1180. // EffectiveAmount
  1181. Balance: tx.Amount,
  1182. BJJ: acc.BJJ,
  1183. EthAddr: acc.EthAddr,
  1184. }
  1185. if tp.zki != nil {
  1186. // Set the State2 before creating the Exit leaf
  1187. tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
  1188. tp.zki.Nonce2[tp.i] = big.NewInt(0)
  1189. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1190. if accBJJSign {
  1191. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1192. }
  1193. tp.zki.Ay2[tp.i] = accBJJY
  1194. // Balance2 contains the ExitLeaf Balance before the
  1195. // leaf update, which is 0
  1196. tp.zki.Balance2[tp.i] = big.NewInt(0)
  1197. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1198. // as Leaf didn't exist in the ExitTree, set NewExit[i]=1
  1199. tp.zki.NewExit[tp.i] = big.NewInt(1)
  1200. }
  1201. p, err = statedb.CreateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  1202. if err != nil {
  1203. return nil, false, tracerr.Wrap(err)
  1204. }
  1205. if tp.zki != nil {
  1206. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1207. if p.IsOld0 {
  1208. tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
  1209. }
  1210. tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
  1211. tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
  1212. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  1213. }
  1214. return exitAccount, true, nil
  1215. } else if err != nil {
  1216. return exitAccount, false, tracerr.Wrap(err)
  1217. }
  1218. // 1b. if idx already exist in exitTree:
  1219. if tp.zki != nil {
  1220. // Set the State2 before updating the Exit leaf
  1221. tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
  1222. // increment nonce from existing ExitLeaf
  1223. tp.zki.Nonce2[tp.i] = exitAccount.Nonce.BigInt()
  1224. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1225. if accBJJSign {
  1226. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1227. }
  1228. tp.zki.Ay2[tp.i] = accBJJY
  1229. // Balance2 contains the ExitLeaf Balance before the leaf
  1230. // update
  1231. tp.zki.Balance2[tp.i] = exitAccount.Balance
  1232. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1233. }
  1234. // update account, where account.Balance += exitAmount
  1235. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  1236. p, err = statedb.UpdateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  1237. if err != nil {
  1238. return nil, false, tracerr.Wrap(err)
  1239. }
  1240. if tp.zki != nil {
  1241. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1242. if p.IsOld0 {
  1243. tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
  1244. }
  1245. tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
  1246. tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
  1247. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  1248. }
  1249. return exitAccount, false, nil
  1250. }
  1251. // computeEffectiveAmounts checks that the L1Tx data is correct
  1252. func (tp *TxProcessor) computeEffectiveAmounts(tx *common.L1Tx) {
  1253. tx.EffectiveAmount = tx.Amount
  1254. tx.EffectiveDepositAmount = tx.DepositAmount
  1255. if !tx.UserOrigin {
  1256. // case where the L1Tx is generated by the Coordinator
  1257. tx.EffectiveAmount = big.NewInt(0)
  1258. tx.EffectiveDepositAmount = big.NewInt(0)
  1259. return
  1260. }
  1261. if tx.Type == common.TxTypeCreateAccountDeposit {
  1262. return
  1263. }
  1264. if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
  1265. // CreateAccountDepositTransfer case
  1266. cmp := tx.DepositAmount.Cmp(tx.Amount)
  1267. if cmp == -1 { // DepositAmount<Amount
  1268. tx.EffectiveAmount = big.NewInt(0)
  1269. return
  1270. }
  1271. // check if tx.TokenID==receiver.TokenID
  1272. accReceiver, err := tp.s.GetAccount(tx.ToIdx)
  1273. if err != nil {
  1274. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d",
  1275. tx.ToIdx)
  1276. tx.EffectiveDepositAmount = big.NewInt(0)
  1277. tx.EffectiveAmount = big.NewInt(0)
  1278. return
  1279. }
  1280. if tx.TokenID != accReceiver.TokenID {
  1281. log.Debugf("EffectiveAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)",
  1282. tx.TokenID, accReceiver.TokenID)
  1283. tx.EffectiveAmount = big.NewInt(0)
  1284. return
  1285. }
  1286. return
  1287. }
  1288. accSender, err := tp.s.GetAccount(tx.FromIdx)
  1289. if err != nil {
  1290. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d",
  1291. tx.FromIdx)
  1292. tx.EffectiveDepositAmount = big.NewInt(0)
  1293. tx.EffectiveAmount = big.NewInt(0)
  1294. return
  1295. }
  1296. // check that tx.TokenID corresponds to the Sender account TokenID
  1297. if tx.TokenID != accSender.TokenID {
  1298. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: "+
  1299. "tx.TokenID (%d) !=sender account TokenID (%d)",
  1300. tx.TokenID, accSender.TokenID)
  1301. tx.EffectiveDepositAmount = big.NewInt(0)
  1302. tx.EffectiveAmount = big.NewInt(0)
  1303. return
  1304. }
  1305. // check that Sender has enough balance
  1306. bal := accSender.Balance
  1307. if tx.DepositAmount != nil {
  1308. bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
  1309. }
  1310. cmp := bal.Cmp(tx.Amount)
  1311. if cmp == -1 {
  1312. log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
  1313. tx.EffectiveAmount = big.NewInt(0)
  1314. return
  1315. }
  1316. // check that the tx.FromEthAddr is the same than the EthAddress of the
  1317. // Sender
  1318. if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
  1319. log.Debugf("EffectiveAmount = 0: tx.FromEthAddr (%s) must be the same EthAddr of "+
  1320. "the sender account by the Idx (%s)",
  1321. tx.FromEthAddr.Hex(), accSender.EthAddr.Hex())
  1322. tx.EffectiveAmount = big.NewInt(0)
  1323. }
  1324. if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
  1325. // if transfer is Exit type, there are no more checks
  1326. return
  1327. }
  1328. // check that TokenID is the same for Sender & Receiver account
  1329. accReceiver, err := tp.s.GetAccount(tx.ToIdx)
  1330. if err != nil {
  1331. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d",
  1332. tx.ToIdx)
  1333. tx.EffectiveDepositAmount = big.NewInt(0)
  1334. tx.EffectiveAmount = big.NewInt(0)
  1335. return
  1336. }
  1337. if accSender.TokenID != accReceiver.TokenID {
  1338. log.Debugf("EffectiveAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)",
  1339. accSender.TokenID, accReceiver.TokenID)
  1340. tx.EffectiveAmount = big.NewInt(0)
  1341. return
  1342. }
  1343. if tx.TokenID != accReceiver.TokenID {
  1344. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: "+
  1345. "tx TokenID (%d) != receiver account TokenID (%d)",
  1346. tx.TokenID, accReceiver.TokenID)
  1347. tx.EffectiveAmount = big.NewInt(0)
  1348. return
  1349. }
  1350. }
  1351. // CheckEnoughBalance returns true if the sender of the transaction has enough
  1352. // balance in the account to send the Amount+Fee, and also returns the account
  1353. // Balance and the Fee+Amount (which is used to give information about why the
  1354. // transaction is not selected in case that this method returns false.
  1355. func (tp *TxProcessor) CheckEnoughBalance(tx common.PoolL2Tx) (bool, *big.Int, *big.Int) {
  1356. acc, err := tp.s.GetAccount(tx.FromIdx)
  1357. if err != nil {
  1358. return false, nil, nil
  1359. }
  1360. fee, err := common.CalcFeeAmount(tx.Amount, tx.Fee)
  1361. if err != nil {
  1362. return false, nil, nil
  1363. }
  1364. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  1365. return acc.Balance.Cmp(feeAndAmount) != -1, // !=-1 balance<amount
  1366. acc.Balance, feeAndAmount
  1367. }