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.

1504 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.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  313. tp.i++
  314. }
  315. }
  316. // remove repeated CoordIdxs that are for the same TokenID (use the
  317. // first occurrence)
  318. usedCoordTokenIDs := make(map[common.TokenID]bool)
  319. var filteredCoordIdxs []common.Idx
  320. for i := 0; i < len(coordIdxs); i++ {
  321. accCoord, err := tp.s.GetAccount(coordIdxs[i])
  322. if err != nil {
  323. return nil, tracerr.Wrap(err)
  324. }
  325. if !usedCoordTokenIDs[accCoord.TokenID] {
  326. usedCoordTokenIDs[accCoord.TokenID] = true
  327. filteredCoordIdxs = append(filteredCoordIdxs, coordIdxs[i])
  328. }
  329. }
  330. coordIdxs = filteredCoordIdxs
  331. tp.AccumulatedFees = make(map[common.Idx]*big.Int)
  332. for _, idx := range coordIdxs {
  333. tp.AccumulatedFees[idx] = big.NewInt(0)
  334. }
  335. // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
  336. // coordIdxs. In this way, if a coordIdx uses an Idx that is being
  337. // created in the current batch, at this point the Idx will be created
  338. coordIdxsMap, err := tp.s.GetTokenIDsFromIdxs(coordIdxs)
  339. if err != nil {
  340. return nil, tracerr.Wrap(err)
  341. }
  342. // collectedFees will contain the amount of fee collected for each
  343. // TokenID
  344. var collectedFees map[common.TokenID]*big.Int
  345. if tp.s.Type() == statedb.TypeSynchronizer || tp.s.Type() == statedb.TypeBatchBuilder {
  346. collectedFees = make(map[common.TokenID]*big.Int)
  347. for tokenID := range coordIdxsMap {
  348. collectedFees[tokenID] = big.NewInt(0)
  349. }
  350. }
  351. if tp.zki != nil {
  352. // get the feePlanTokens
  353. feePlanTokens, err := tp.getFeePlanTokens(coordIdxs)
  354. if err != nil {
  355. log.Error(err)
  356. return nil, tracerr.Wrap(err)
  357. }
  358. copy(tp.zki.FeePlanTokens, feePlanTokens)
  359. }
  360. // Process L2Txs
  361. for i := 0; i < len(l2txs); i++ {
  362. exitIdx, exitAccount, newExit, err := tp.ProcessL2Tx(coordIdxsMap, collectedFees,
  363. exitTree, &l2txs[i])
  364. if err != nil {
  365. return nil, tracerr.Wrap(err)
  366. }
  367. if tp.zki != nil {
  368. l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(tp.zki.Metadata.NLevels)
  369. if err != nil {
  370. return nil, tracerr.Wrap(err)
  371. }
  372. tp.zki.Metadata.L2TxsData = append(tp.zki.Metadata.L2TxsData, l2TxData)
  373. // Intermediate States
  374. if tp.i < nTx-1 {
  375. tp.zki.ISOutIdx[tp.i] = tp.s.CurrentIdx().BigInt()
  376. tp.zki.ISStateRoot[tp.i] = tp.s.MT.Root().BigInt()
  377. tp.zki.ISAccFeeOut[tp.i] = formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
  378. if exitIdx == nil {
  379. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  380. }
  381. }
  382. }
  383. if tp.s.Type() == statedb.TypeSynchronizer || tp.s.Type() == statedb.TypeBatchBuilder {
  384. if exitIdx != nil && exitTree != nil {
  385. exits[tp.i] = processedExit{
  386. exit: true,
  387. newExit: newExit,
  388. idx: *exitIdx,
  389. acc: *exitAccount,
  390. }
  391. }
  392. tp.i++
  393. }
  394. }
  395. if tp.zki != nil {
  396. // Fill the empty slots in the ZKInputs remaining after
  397. // processing all L1 & L2 txs
  398. txCompressedDataEmpty := common.TxCompressedDataEmpty(tp.config.ChainID)
  399. last := tp.i - 1
  400. if tp.i == 0 {
  401. last = 0
  402. }
  403. for i := last; i < int(tp.config.MaxTx); i++ {
  404. if i < int(tp.config.MaxTx)-1 {
  405. tp.zki.ISOutIdx[i] = tp.s.CurrentIdx().BigInt()
  406. tp.zki.ISStateRoot[i] = tp.s.MT.Root().BigInt()
  407. tp.zki.ISAccFeeOut[i] = formatAccumulatedFees(collectedFees,
  408. tp.zki.FeePlanTokens, coordIdxs)
  409. tp.zki.ISExitRoot[i] = exitTree.Root().BigInt()
  410. }
  411. if i >= tp.i {
  412. tp.zki.TxCompressedData[i] = txCompressedDataEmpty
  413. }
  414. }
  415. isFinalAccFee := formatAccumulatedFees(collectedFees, tp.zki.FeePlanTokens, coordIdxs)
  416. copy(tp.zki.ISFinalAccFee, isFinalAccFee)
  417. // before computing the Fees txs, set the ISInitStateRootFee
  418. tp.zki.ISInitStateRootFee = tp.s.MT.Root().BigInt()
  419. }
  420. // distribute the AccumulatedFees from the processed L2Txs into the
  421. // Coordinator Idxs
  422. iFee := 0
  423. for _, idx := range coordIdxs {
  424. accumulatedFee := tp.AccumulatedFees[idx]
  425. // send the fee to the Idx of the Coordinator for the TokenID
  426. // (even if the AccumulatedFee==0, as is how the zk circuit
  427. // works)
  428. accCoord, err := tp.s.GetAccount(idx)
  429. if err != nil {
  430. log.Errorw("Can not distribute accumulated fees to coordinator account: "+
  431. "No coord Idx to receive fee", "idx", idx)
  432. return nil, tracerr.Wrap(err)
  433. }
  434. if tp.zki != nil {
  435. tp.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
  436. tp.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
  437. coordBJJSign, coordBJJY := babyjub.UnpackSignY(accCoord.BJJ)
  438. if coordBJJSign {
  439. tp.zki.Sign3[iFee] = big.NewInt(1)
  440. }
  441. tp.zki.Ay3[iFee] = coordBJJY
  442. tp.zki.Balance3[iFee] = accCoord.Balance
  443. tp.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
  444. }
  445. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  446. pFee, err := tp.updateAccount(idx, accCoord)
  447. if err != nil {
  448. log.Error(err)
  449. return nil, tracerr.Wrap(err)
  450. }
  451. if tp.zki != nil {
  452. tp.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
  453. tp.zki.ISStateRootFee[iFee] = tp.s.MT.Root().BigInt()
  454. }
  455. iFee++
  456. }
  457. if tp.zki != nil {
  458. for i := len(tp.AccumulatedFees); i < int(tp.config.MaxFeeTx)-1; i++ {
  459. tp.zki.ISStateRootFee[i] = tp.s.MT.Root().BigInt()
  460. }
  461. // add Coord Idx to ZKInputs.FeeTxsData
  462. for i := 0; i < len(coordIdxs); i++ {
  463. tp.zki.FeeIdxs[i] = coordIdxs[i].BigInt()
  464. }
  465. }
  466. if tp.s.Type() == statedb.TypeTxSelector {
  467. return nil, nil
  468. }
  469. if tp.s.Type() == statedb.TypeSynchronizer {
  470. // once all txs processed (exitTree root frozen), for each Exit,
  471. // generate common.ExitInfo data
  472. var exitInfos []common.ExitInfo
  473. exitInfosByIdx := make(map[common.Idx]*common.ExitInfo)
  474. for i := 0; i < nTx; i++ {
  475. if !exits[i].exit {
  476. continue
  477. }
  478. exitIdx := exits[i].idx
  479. exitAccount := exits[i].acc
  480. // 0. generate MerkleProof
  481. p, err := exitTree.GenerateSCVerifierProof(exitIdx.BigInt(), nil)
  482. if err != nil {
  483. return nil, tracerr.Wrap(err)
  484. }
  485. // 1. generate common.ExitInfo
  486. ei := common.ExitInfo{
  487. AccountIdx: exitIdx,
  488. MerkleProof: p,
  489. Balance: exitAccount.Balance,
  490. }
  491. if prevExit, ok := exitInfosByIdx[exitIdx]; !ok {
  492. exitInfos = append(exitInfos, ei)
  493. exitInfosByIdx[exitIdx] = &exitInfos[len(exitInfos)-1]
  494. } else {
  495. *prevExit = ei
  496. }
  497. }
  498. // retun exitInfos, createdAccounts and collectedFees, so Synchronizer will
  499. // be able to store it into HistoryDB for the concrete BatchNum
  500. return &ProcessTxOutput{
  501. ZKInputs: nil,
  502. ExitInfos: exitInfos,
  503. CreatedAccounts: createdAccounts,
  504. CoordinatorIdxsMap: coordIdxsMap,
  505. CollectedFees: collectedFees,
  506. UpdatedAccounts: tp.updatedAccounts,
  507. }, nil
  508. }
  509. // compute last ZKInputs parameters
  510. tp.zki.GlobalChainID = big.NewInt(int64(tp.config.ChainID))
  511. tp.zki.Metadata.NewStateRootRaw = tp.s.MT.Root()
  512. tp.zki.Metadata.NewExitRootRaw = exitTree.Root()
  513. // return ZKInputs as the BatchBuilder will return it to forge the Batch
  514. return &ProcessTxOutput{
  515. ZKInputs: tp.zki,
  516. ExitInfos: nil,
  517. CreatedAccounts: nil,
  518. CoordinatorIdxsMap: coordIdxsMap,
  519. CollectedFees: nil,
  520. }, nil
  521. }
  522. // getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
  523. // corresponding to the given CoordIdxs and the processed L2Txs
  524. func (tp *TxProcessor) getFeePlanTokens(coordIdxs []common.Idx) ([]*big.Int, error) {
  525. var tBI []*big.Int
  526. for i := 0; i < len(coordIdxs); i++ {
  527. acc, err := tp.s.GetAccount(coordIdxs[i])
  528. if err != nil {
  529. log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s",
  530. coordIdxs[i], err.Error())
  531. return nil, tracerr.Wrap(err)
  532. }
  533. tBI = append(tBI, acc.TokenID.BigInt())
  534. }
  535. return tBI, nil
  536. }
  537. // ProcessL1Tx process the given L1Tx applying the needed updates to the
  538. // StateDB depending on the transaction Type. It returns the 3 parameters
  539. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  540. // the Exit created a new Leaf in the ExitTree.
  541. // And another *common.Account parameter which contains the created account in
  542. // case that has been a new created account and that the StateDB is of type
  543. // TypeSynchronizer.
  544. func (tp *TxProcessor) ProcessL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx,
  545. *common.Account, bool, *common.Account, error) {
  546. // ZKInputs
  547. if tp.zki != nil {
  548. // Txs
  549. var err error
  550. tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
  551. if err != nil {
  552. log.Error(err)
  553. return nil, nil, false, nil, tracerr.Wrap(err)
  554. }
  555. tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
  556. tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
  557. tp.zki.OnChain[tp.i] = big.NewInt(1)
  558. // L1Txs
  559. depositAmountF40, err := common.NewFloat40(tx.DepositAmount)
  560. if err != nil {
  561. return nil, nil, false, nil, tracerr.Wrap(err)
  562. }
  563. tp.zki.DepositAmountF[tp.i] = big.NewInt(int64(depositAmountF40))
  564. tp.zki.FromEthAddr[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  565. if tx.FromBJJ != common.EmptyBJJComp {
  566. tp.zki.FromBJJCompressed[tp.i] = BJJCompressedTo256BigInts(tx.FromBJJ)
  567. }
  568. // Intermediate States, for all the transactions except for the last one
  569. if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
  570. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  571. }
  572. if tx.Type == common.TxTypeForceTransfer ||
  573. tx.Type == common.TxTypeDepositTransfer ||
  574. tx.Type == common.TxTypeCreateAccountDepositTransfer ||
  575. tx.Type == common.TxTypeForceExit {
  576. // in the cases where at L1Tx there is usage of the
  577. // Amount parameter, add it at the ZKInputs.AmountF
  578. // slot
  579. amountF40, err := common.NewFloat40(tx.Amount)
  580. if err != nil {
  581. return nil, nil, false, nil, tracerr.Wrap(err)
  582. }
  583. tp.zki.AmountF[tp.i] = big.NewInt(int64(amountF40))
  584. }
  585. }
  586. switch tx.Type {
  587. case common.TxTypeForceTransfer:
  588. tp.computeEffectiveAmounts(tx)
  589. // go to the MT account of sender and receiver, and update balance
  590. // & nonce
  591. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees.
  592. // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in
  593. // the Deposit type case.
  594. err := tp.applyTransfer(nil, nil, tx.Tx(), 0)
  595. if err != nil {
  596. log.Error(err)
  597. return nil, nil, false, nil, tracerr.Wrap(err)
  598. }
  599. case common.TxTypeCreateAccountDeposit:
  600. tp.computeEffectiveAmounts(tx)
  601. // add new account to the MT, update balance of the MT account
  602. err := tp.applyCreateAccount(tx)
  603. if err != nil {
  604. log.Error(err)
  605. return nil, nil, false, nil, tracerr.Wrap(err)
  606. }
  607. // TODO applyCreateAccount will return the created account,
  608. // which in the case type==TypeSynchronizer will be added to an
  609. // array of created accounts that will be returned
  610. case common.TxTypeDeposit:
  611. tp.computeEffectiveAmounts(tx)
  612. // update balance of the MT account
  613. err := tp.applyDeposit(tx, false)
  614. if err != nil {
  615. log.Error(err)
  616. return nil, nil, false, nil, tracerr.Wrap(err)
  617. }
  618. case common.TxTypeDepositTransfer:
  619. tp.computeEffectiveAmounts(tx)
  620. // update balance in MT account, update balance & nonce of sender
  621. // & receiver
  622. err := tp.applyDeposit(tx, true)
  623. if err != nil {
  624. log.Error(err)
  625. return nil, nil, false, nil, tracerr.Wrap(err)
  626. }
  627. case common.TxTypeCreateAccountDepositTransfer:
  628. tp.computeEffectiveAmounts(tx)
  629. // add new account to the merkletree, update balance in MT account,
  630. // update balance & nonce of sender & receiver
  631. err := tp.applyCreateAccountDepositTransfer(tx)
  632. if err != nil {
  633. log.Error(err)
  634. return nil, nil, false, nil, tracerr.Wrap(err)
  635. }
  636. case common.TxTypeForceExit:
  637. tp.computeEffectiveAmounts(tx)
  638. // execute exit flow
  639. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  640. exitAccount, newExit, err := tp.applyExit(nil, nil, exitTree, tx.Tx(), tx.Amount)
  641. if err != nil {
  642. log.Error(err)
  643. return nil, nil, false, nil, tracerr.Wrap(err)
  644. }
  645. return &tx.FromIdx, exitAccount, newExit, nil, nil
  646. default:
  647. }
  648. var createdAccount *common.Account
  649. if tp.s.Type() == statedb.TypeSynchronizer &&
  650. (tx.Type == common.TxTypeCreateAccountDeposit ||
  651. tx.Type == common.TxTypeCreateAccountDepositTransfer) {
  652. var err error
  653. createdAccount, err = tp.s.GetAccount(tp.s.CurrentIdx())
  654. if err != nil {
  655. log.Error(err)
  656. return nil, nil, false, nil, tracerr.Wrap(err)
  657. }
  658. }
  659. return nil, nil, false, createdAccount, nil
  660. }
  661. // ProcessL2Tx process the given L2Tx applying the needed updates to the
  662. // StateDB depending on the transaction Type. It returns the 3 parameters
  663. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  664. // the Exit created a new Leaf in the ExitTree.
  665. func (tp *TxProcessor) ProcessL2Tx(coordIdxsMap map[common.TokenID]common.Idx,
  666. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  667. tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  668. var err error
  669. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  670. if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
  671. if tp.s.Type() == statedb.TypeSynchronizer {
  672. // thisTypeould never be reached
  673. log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
  674. return nil, nil, false,
  675. tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
  676. }
  677. // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
  678. accSender, err := tp.s.GetAccount(tx.FromIdx)
  679. if err != nil {
  680. return nil, nil, false, tracerr.Wrap(err)
  681. }
  682. tx.AuxToIdx, err = tp.s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, accSender.TokenID)
  683. if err != nil {
  684. return nil, nil, false, tracerr.Wrap(err)
  685. }
  686. }
  687. // ZKInputs
  688. if tp.zki != nil {
  689. // Txs
  690. tp.zki.TxCompressedData[tp.i], err = tx.TxCompressedData(tp.config.ChainID)
  691. if err != nil {
  692. return nil, nil, false, tracerr.Wrap(err)
  693. }
  694. tp.zki.TxCompressedDataV2[tp.i], err = tx.TxCompressedDataV2()
  695. if err != nil {
  696. return nil, nil, false, tracerr.Wrap(err)
  697. }
  698. tp.zki.FromIdx[tp.i] = tx.FromIdx.BigInt()
  699. tp.zki.ToIdx[tp.i] = tx.ToIdx.BigInt()
  700. // fill AuxToIdx if needed
  701. if tx.ToIdx == 0 {
  702. // use toIdx that can have been filled by tx.ToIdx or
  703. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  704. // from db by ToEthAddr&ToBJJ
  705. tp.zki.AuxToIdx[tp.i] = tx.AuxToIdx.BigInt()
  706. }
  707. if tx.ToBJJ != common.EmptyBJJComp {
  708. _, tp.zki.ToBJJAy[tp.i] = babyjub.UnpackSignY(tx.ToBJJ)
  709. }
  710. tp.zki.ToEthAddr[tp.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  711. tp.zki.OnChain[tp.i] = big.NewInt(0)
  712. amountF40, err := common.NewFloat40(tx.Amount)
  713. if err != nil {
  714. return nil, nil, false, tracerr.Wrap(err)
  715. }
  716. tp.zki.AmountF[tp.i] = big.NewInt(int64(amountF40))
  717. tp.zki.NewAccount[tp.i] = big.NewInt(0)
  718. // L2Txs
  719. // tp.zki.RqOffset[tp.i] = // TODO Rq once TxSelector is ready
  720. // tp.zki.RqTxCompressedDataV2[tp.i] = // TODO
  721. // tp.zki.RqToEthAddr[tp.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  722. // tp.zki.RqToBJJAy[tp.i] = tx.ToBJJ.Y // TODO
  723. signature, err := tx.Signature.Decompress()
  724. if err != nil {
  725. log.Error(err)
  726. return nil, nil, false, tracerr.Wrap(err)
  727. }
  728. tp.zki.S[tp.i] = signature.S
  729. tp.zki.R8x[tp.i] = signature.R8.X
  730. tp.zki.R8y[tp.i] = signature.R8.Y
  731. }
  732. // if StateDB type==TypeSynchronizer, will need to add Nonce
  733. if tp.s.Type() == statedb.TypeSynchronizer {
  734. // as tType==TypeSynchronizer, always tx.ToIdx!=0
  735. acc, err := tp.s.GetAccount(tx.FromIdx)
  736. if err != nil {
  737. log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
  738. return nil, nil, false, tracerr.Wrap(err)
  739. }
  740. tx.Nonce = acc.Nonce
  741. tx.TokenID = acc.TokenID
  742. }
  743. switch tx.Type {
  744. case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
  745. // go to the MT account of sender and receiver, and update
  746. // balance & nonce
  747. err = tp.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
  748. if err != nil {
  749. log.Error(err)
  750. return nil, nil, false, tracerr.Wrap(err)
  751. }
  752. case common.TxTypeExit:
  753. // execute exit flow
  754. exitAccount, newExit, err := tp.applyExit(coordIdxsMap, collectedFees, exitTree,
  755. tx.Tx(), tx.Amount)
  756. if err != nil {
  757. log.Error(err)
  758. return nil, nil, false, tracerr.Wrap(err)
  759. }
  760. return &tx.FromIdx, exitAccount, newExit, nil
  761. default:
  762. }
  763. return nil, nil, false, nil
  764. }
  765. // applyCreateAccount creates a new account in the account of the depositer, it
  766. // stores the deposit value
  767. func (tp *TxProcessor) applyCreateAccount(tx *common.L1Tx) error {
  768. account := &common.Account{
  769. TokenID: tx.TokenID,
  770. Nonce: 0,
  771. Balance: tx.EffectiveDepositAmount,
  772. BJJ: tx.FromBJJ,
  773. EthAddr: tx.FromEthAddr,
  774. }
  775. p, err := tp.createAccount(common.Idx(tp.s.CurrentIdx()+1), account)
  776. if err != nil {
  777. return tracerr.Wrap(err)
  778. }
  779. if tp.zki != nil {
  780. tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
  781. tp.zki.Nonce1[tp.i] = big.NewInt(0)
  782. fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
  783. if fromBJJSign {
  784. tp.zki.Sign1[tp.i] = big.NewInt(1)
  785. }
  786. tp.zki.Ay1[tp.i] = fromBJJY
  787. tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
  788. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  789. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  790. if p.IsOld0 {
  791. tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
  792. }
  793. tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
  794. tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
  795. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
  796. tp.zki.AuxFromIdx[tp.i] = common.Idx(tp.s.CurrentIdx() + 1).BigInt()
  797. tp.zki.NewAccount[tp.i] = big.NewInt(1)
  798. if tp.i < len(tp.zki.ISOnChain) { // len(tp.zki.ISOnChain) == nTx
  799. // intermediate states
  800. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  801. }
  802. }
  803. return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
  804. }
  805. // createAccount is a wrapper over the StateDB.CreateAccount method that also
  806. // stores the created account in the updatedAccounts map in case the StateDB is
  807. // of TypeSynchronizer
  808. func (tp *TxProcessor) createAccount(idx common.Idx, account *common.Account) (
  809. *merkletree.CircomProcessorProof, error) {
  810. if tp.s.Type() == statedb.TypeSynchronizer {
  811. account.Idx = idx
  812. tp.updatedAccounts[idx] = account
  813. }
  814. return tp.s.CreateAccount(idx, account)
  815. }
  816. // updateAccount is a wrapper over the StateDB.UpdateAccount method that also
  817. // stores the updated account in the updatedAccounts map in case the StateDB is
  818. // of TypeSynchronizer
  819. func (tp *TxProcessor) updateAccount(idx common.Idx, account *common.Account) (
  820. *merkletree.CircomProcessorProof, error) {
  821. if tp.s.Type() == statedb.TypeSynchronizer {
  822. account.Idx = idx
  823. tp.updatedAccounts[idx] = account
  824. }
  825. return tp.s.UpdateAccount(idx, account)
  826. }
  827. // applyDeposit updates the balance in the account of the depositer, if
  828. // andTransfer parameter is set to true, the method will also apply the
  829. // Transfer of the L1Tx/DepositTransfer
  830. func (tp *TxProcessor) applyDeposit(tx *common.L1Tx, transfer bool) error {
  831. accSender, err := tp.s.GetAccount(tx.FromIdx)
  832. if err != nil {
  833. return tracerr.Wrap(err)
  834. }
  835. if tp.zki != nil {
  836. tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
  837. tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
  838. senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
  839. if senderBJJSign {
  840. tp.zki.Sign1[tp.i] = big.NewInt(1)
  841. }
  842. tp.zki.Ay1[tp.i] = senderBJJY
  843. tp.zki.Balance1[tp.i] = accSender.Balance
  844. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
  845. }
  846. // add the deposit to the sender
  847. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
  848. // subtract amount to the sender
  849. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  850. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  851. return newErrorNotEnoughBalance(tx.Tx())
  852. }
  853. // update sender account in localStateDB
  854. p, err := tp.updateAccount(tx.FromIdx, accSender)
  855. if err != nil {
  856. return tracerr.Wrap(err)
  857. }
  858. if tp.zki != nil {
  859. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  860. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  861. }
  862. // in case that the tx is a L1Tx>DepositTransfer
  863. var accReceiver *common.Account
  864. if transfer {
  865. if tx.ToIdx == tx.FromIdx {
  866. accReceiver = accSender
  867. } else {
  868. accReceiver, err = tp.s.GetAccount(tx.ToIdx)
  869. if err != nil {
  870. return tracerr.Wrap(err)
  871. }
  872. }
  873. if tp.zki != nil {
  874. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  875. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  876. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  877. if receiverBJJSign {
  878. tp.zki.Sign2[tp.i] = big.NewInt(1)
  879. }
  880. tp.zki.Ay2[tp.i] = receiverBJJY
  881. tp.zki.Balance2[tp.i] = accReceiver.Balance
  882. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  883. }
  884. // add amount to the receiver
  885. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  886. // update receiver account in localStateDB
  887. p, err := tp.updateAccount(tx.ToIdx, accReceiver)
  888. if err != nil {
  889. return tracerr.Wrap(err)
  890. }
  891. if tp.zki != nil {
  892. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  893. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  894. }
  895. }
  896. return nil
  897. }
  898. // applyTransfer updates the balance & nonce in the account of the sender, and
  899. // the balance in the account of the receiver.
  900. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  901. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  902. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  903. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  904. func (tp *TxProcessor) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
  905. collectedFees map[common.TokenID]*big.Int, tx common.Tx, auxToIdx common.Idx) error {
  906. if auxToIdx == common.Idx(0) {
  907. auxToIdx = tx.ToIdx
  908. }
  909. // get sender and receiver accounts from localStateDB
  910. accSender, err := tp.s.GetAccount(tx.FromIdx)
  911. if err != nil {
  912. log.Error(err)
  913. return tracerr.Wrap(err)
  914. }
  915. if tp.zki != nil {
  916. // Set the State1 before updating the Sender leaf
  917. tp.zki.TokenID1[tp.i] = accSender.TokenID.BigInt()
  918. tp.zki.Nonce1[tp.i] = accSender.Nonce.BigInt()
  919. senderBJJSign, senderBJJY := babyjub.UnpackSignY(accSender.BJJ)
  920. if senderBJJSign {
  921. tp.zki.Sign1[tp.i] = big.NewInt(1)
  922. }
  923. tp.zki.Ay1[tp.i] = senderBJJY
  924. tp.zki.Balance1[tp.i] = accSender.Balance
  925. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(accSender.EthAddr)
  926. }
  927. if !tx.IsL1 { // L2
  928. // increment nonce
  929. accSender.Nonce++
  930. // compute fee and subtract it from the accSender
  931. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  932. if err != nil {
  933. return tracerr.Wrap(err)
  934. }
  935. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  936. accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
  937. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  938. return newErrorNotEnoughBalance(tx)
  939. }
  940. if _, ok := coordIdxsMap[accSender.TokenID]; ok {
  941. accCoord, err := tp.s.GetAccount(coordIdxsMap[accSender.TokenID])
  942. if err != nil {
  943. return tracerr.Wrap(
  944. fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d",
  945. accSender.TokenID, coordIdxsMap[accSender.TokenID]))
  946. }
  947. // accumulate the fee for the Coord account
  948. accumulated := tp.AccumulatedFees[accCoord.Idx]
  949. accumulated.Add(accumulated, fee)
  950. if tp.s.Type() == statedb.TypeSynchronizer ||
  951. tp.s.Type() == statedb.TypeBatchBuilder {
  952. collected := collectedFees[accCoord.TokenID]
  953. collected.Add(collected, fee)
  954. }
  955. } else {
  956. log.Debugw("No coord Idx to receive fee", "tx", tx)
  957. }
  958. } else {
  959. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  960. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  961. return newErrorNotEnoughBalance(tx)
  962. }
  963. }
  964. // update sender account in localStateDB
  965. pSender, err := tp.updateAccount(tx.FromIdx, accSender)
  966. if err != nil {
  967. log.Error(err)
  968. return tracerr.Wrap(err)
  969. }
  970. if tp.zki != nil {
  971. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(pSender.Siblings)
  972. }
  973. var accReceiver *common.Account
  974. if auxToIdx == tx.FromIdx {
  975. // if Sender is the Receiver, reuse 'accSender' pointer,
  976. // because in the DB the account for 'auxToIdx' won't be
  977. // updated yet
  978. accReceiver = accSender
  979. } else {
  980. accReceiver, err = tp.s.GetAccount(auxToIdx)
  981. if err != nil {
  982. log.Error(err, auxToIdx)
  983. return tracerr.Wrap(err)
  984. }
  985. }
  986. if tp.zki != nil {
  987. // Set the State2 before updating the Receiver leaf
  988. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  989. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  990. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  991. if receiverBJJSign {
  992. tp.zki.Sign2[tp.i] = big.NewInt(1)
  993. }
  994. tp.zki.Ay2[tp.i] = receiverBJJY
  995. tp.zki.Balance2[tp.i] = accReceiver.Balance
  996. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  997. }
  998. // add amount-feeAmount to the receiver
  999. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  1000. // update receiver account in localStateDB
  1001. pReceiver, err := tp.updateAccount(auxToIdx, accReceiver)
  1002. if err != nil {
  1003. return tracerr.Wrap(err)
  1004. }
  1005. if tp.zki != nil {
  1006. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  1007. }
  1008. return nil
  1009. }
  1010. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  1011. // makes a deposit, and performs a transfer to another account
  1012. func (tp *TxProcessor) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  1013. auxFromIdx := common.Idx(tp.s.CurrentIdx() + 1)
  1014. accSender := &common.Account{
  1015. TokenID: tx.TokenID,
  1016. Nonce: 0,
  1017. Balance: tx.EffectiveDepositAmount,
  1018. BJJ: tx.FromBJJ,
  1019. EthAddr: tx.FromEthAddr,
  1020. }
  1021. if tp.zki != nil {
  1022. // Set the State1 before updating the Sender leaf
  1023. tp.zki.TokenID1[tp.i] = tx.TokenID.BigInt()
  1024. tp.zki.Nonce1[tp.i] = big.NewInt(0)
  1025. fromBJJSign, fromBJJY := babyjub.UnpackSignY(tx.FromBJJ)
  1026. if fromBJJSign {
  1027. tp.zki.Sign1[tp.i] = big.NewInt(1)
  1028. }
  1029. tp.zki.Ay1[tp.i] = fromBJJY
  1030. tp.zki.Balance1[tp.i] = tx.EffectiveDepositAmount
  1031. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  1032. }
  1033. // subtract amount to the sender
  1034. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  1035. if accSender.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1036. return newErrorNotEnoughBalance(tx.Tx())
  1037. }
  1038. // create Account of the Sender
  1039. p, err := tp.createAccount(common.Idx(tp.s.CurrentIdx()+1), accSender)
  1040. if err != nil {
  1041. return tracerr.Wrap(err)
  1042. }
  1043. if tp.zki != nil {
  1044. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1045. if p.IsOld0 {
  1046. tp.zki.IsOld0_1[tp.i] = big.NewInt(1)
  1047. }
  1048. tp.zki.OldKey1[tp.i] = p.OldKey.BigInt()
  1049. tp.zki.OldValue1[tp.i] = p.OldValue.BigInt()
  1050. tp.zki.Metadata.NewLastIdxRaw = tp.s.CurrentIdx() + 1
  1051. tp.zki.AuxFromIdx[tp.i] = auxFromIdx.BigInt()
  1052. tp.zki.NewAccount[tp.i] = big.NewInt(1)
  1053. // intermediate states
  1054. tp.zki.ISOnChain[tp.i] = big.NewInt(1)
  1055. }
  1056. var accReceiver *common.Account
  1057. if tx.ToIdx == auxFromIdx {
  1058. accReceiver = accSender
  1059. } else {
  1060. accReceiver, err = tp.s.GetAccount(tx.ToIdx)
  1061. if err != nil {
  1062. log.Error(err)
  1063. return tracerr.Wrap(err)
  1064. }
  1065. }
  1066. if tp.zki != nil {
  1067. // Set the State2 before updating the Receiver leaf
  1068. tp.zki.TokenID2[tp.i] = accReceiver.TokenID.BigInt()
  1069. tp.zki.Nonce2[tp.i] = accReceiver.Nonce.BigInt()
  1070. receiverBJJSign, receiverBJJY := babyjub.UnpackSignY(accReceiver.BJJ)
  1071. if receiverBJJSign {
  1072. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1073. }
  1074. tp.zki.Ay2[tp.i] = receiverBJJY
  1075. tp.zki.Balance2[tp.i] = accReceiver.Balance
  1076. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  1077. }
  1078. // add amount to the receiver
  1079. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  1080. // update receiver account in localStateDB
  1081. p, err = tp.updateAccount(tx.ToIdx, accReceiver)
  1082. if err != nil {
  1083. return tracerr.Wrap(err)
  1084. }
  1085. if tp.zki != nil {
  1086. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1087. }
  1088. return tp.s.SetCurrentIdx(tp.s.CurrentIdx() + 1)
  1089. }
  1090. // It returns the ExitAccount and a boolean determining if the Exit created a
  1091. // new Leaf in the ExitTree.
  1092. func (tp *TxProcessor) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
  1093. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  1094. tx common.Tx, originalAmount *big.Int) (*common.Account, bool, error) {
  1095. // 0. subtract tx.Amount from current Account in StateMT
  1096. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  1097. acc, err := tp.s.GetAccount(tx.FromIdx)
  1098. if err != nil {
  1099. return nil, false, tracerr.Wrap(err)
  1100. }
  1101. if tp.zki != nil {
  1102. tp.zki.TokenID1[tp.i] = acc.TokenID.BigInt()
  1103. tp.zki.Nonce1[tp.i] = acc.Nonce.BigInt()
  1104. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1105. if accBJJSign {
  1106. tp.zki.Sign1[tp.i] = big.NewInt(1)
  1107. }
  1108. tp.zki.Ay1[tp.i] = accBJJY
  1109. tp.zki.Balance1[tp.i] = acc.Balance
  1110. tp.zki.EthAddr1[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1111. }
  1112. if !tx.IsL1 {
  1113. // increment nonce
  1114. acc.Nonce++
  1115. // compute fee and subtract it from the accSender
  1116. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  1117. if err != nil {
  1118. return nil, false, tracerr.Wrap(err)
  1119. }
  1120. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  1121. acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
  1122. if acc.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1123. return nil, false, newErrorNotEnoughBalance(tx)
  1124. }
  1125. if _, ok := coordIdxsMap[acc.TokenID]; ok {
  1126. accCoord, err := tp.s.GetAccount(coordIdxsMap[acc.TokenID])
  1127. if err != nil {
  1128. return nil, false, tracerr.Wrap(
  1129. fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d",
  1130. acc.TokenID, coordIdxsMap[acc.TokenID]))
  1131. }
  1132. // accumulate the fee for the Coord account
  1133. accumulated := tp.AccumulatedFees[accCoord.Idx]
  1134. accumulated.Add(accumulated, fee)
  1135. if tp.s.Type() == statedb.TypeSynchronizer ||
  1136. tp.s.Type() == statedb.TypeBatchBuilder {
  1137. collected := collectedFees[accCoord.TokenID]
  1138. collected.Add(collected, fee)
  1139. }
  1140. } else {
  1141. log.Debugw("No coord Idx to receive fee", "tx", tx)
  1142. }
  1143. } else {
  1144. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  1145. if acc.Balance.Cmp(big.NewInt(0)) == -1 { // balance<0
  1146. return nil, false, newErrorNotEnoughBalance(tx)
  1147. }
  1148. }
  1149. p, err := tp.updateAccount(tx.FromIdx, acc)
  1150. if err != nil {
  1151. return nil, false, tracerr.Wrap(err)
  1152. }
  1153. if tp.zki != nil {
  1154. tp.zki.Siblings1[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1155. }
  1156. if exitTree == nil {
  1157. return nil, false, nil
  1158. }
  1159. // Do not add the Exit when Amount=0, not EffectiveAmount=0. In
  1160. // txprocessor.applyExit function, the tx.Amount is in reality the
  1161. // EffectiveAmount, that's why is used here the originalAmount
  1162. // parameter, which contains the real value of the tx.Amount (not
  1163. // tx.EffectiveAmount). This is a particularity of the approach of the
  1164. // circuit, the idea will be in the future to update the circuit and
  1165. // when Amount>0 but EffectiveAmount=0, to not add the Exit in the
  1166. // Exits MerkleTree, but for the moment the Go code is adapted to the
  1167. // circuit.
  1168. if originalAmount.Cmp(big.NewInt(0)) == 0 { // Amount == 0
  1169. // if the Exit Amount==0, the Exit is not added to the ExitTree
  1170. return nil, false, nil
  1171. }
  1172. exitAccount, err := statedb.GetAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  1173. if tracerr.Unwrap(err) == db.ErrNotFound {
  1174. // 1a. if idx does not exist in exitTree:
  1175. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance =
  1176. // exitAmount (exitAmount=tx.Amount)
  1177. exitAccount := &common.Account{
  1178. TokenID: acc.TokenID,
  1179. Nonce: common.Nonce(0),
  1180. // as is a common.Tx, the tx.Amount is already an
  1181. // EffectiveAmount
  1182. Balance: tx.Amount,
  1183. BJJ: acc.BJJ,
  1184. EthAddr: acc.EthAddr,
  1185. }
  1186. if tp.zki != nil {
  1187. // Set the State2 before creating the Exit leaf
  1188. tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
  1189. tp.zki.Nonce2[tp.i] = big.NewInt(0)
  1190. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1191. if accBJJSign {
  1192. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1193. }
  1194. tp.zki.Ay2[tp.i] = accBJJY
  1195. // Balance2 contains the ExitLeaf Balance before the
  1196. // leaf update, which is 0
  1197. tp.zki.Balance2[tp.i] = big.NewInt(0)
  1198. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1199. // as Leaf didn't exist in the ExitTree, set NewExit[i]=1
  1200. tp.zki.NewExit[tp.i] = big.NewInt(1)
  1201. }
  1202. p, err = statedb.CreateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  1203. if err != nil {
  1204. return nil, false, tracerr.Wrap(err)
  1205. }
  1206. if tp.zki != nil {
  1207. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1208. if p.IsOld0 {
  1209. tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
  1210. }
  1211. tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
  1212. tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
  1213. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  1214. }
  1215. return exitAccount, true, nil
  1216. } else if err != nil {
  1217. return nil, false, tracerr.Wrap(err)
  1218. }
  1219. // 1b. if idx already exist in exitTree:
  1220. if tp.zki != nil {
  1221. // Set the State2 before updating the Exit leaf
  1222. tp.zki.TokenID2[tp.i] = acc.TokenID.BigInt()
  1223. // increment nonce from existing ExitLeaf
  1224. tp.zki.Nonce2[tp.i] = exitAccount.Nonce.BigInt()
  1225. accBJJSign, accBJJY := babyjub.UnpackSignY(acc.BJJ)
  1226. if accBJJSign {
  1227. tp.zki.Sign2[tp.i] = big.NewInt(1)
  1228. }
  1229. tp.zki.Ay2[tp.i] = accBJJY
  1230. // Balance2 contains the ExitLeaf Balance before the leaf
  1231. // update
  1232. tp.zki.Balance2[tp.i] = exitAccount.Balance
  1233. tp.zki.EthAddr2[tp.i] = common.EthAddrToBigInt(acc.EthAddr)
  1234. }
  1235. // update account, where account.Balance += exitAmount
  1236. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  1237. p, err = statedb.UpdateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  1238. if err != nil {
  1239. return nil, false, tracerr.Wrap(err)
  1240. }
  1241. if tp.zki != nil {
  1242. tp.zki.Siblings2[tp.i] = siblingsToZKInputFormat(p.Siblings)
  1243. if p.IsOld0 {
  1244. tp.zki.IsOld0_2[tp.i] = big.NewInt(1)
  1245. }
  1246. tp.zki.OldKey2[tp.i] = p.OldKey.BigInt()
  1247. tp.zki.OldValue2[tp.i] = p.OldValue.BigInt()
  1248. tp.zki.ISExitRoot[tp.i] = exitTree.Root().BigInt()
  1249. }
  1250. return exitAccount, false, nil
  1251. }
  1252. // computeEffectiveAmounts checks that the L1Tx data is correct
  1253. func (tp *TxProcessor) computeEffectiveAmounts(tx *common.L1Tx) {
  1254. tx.EffectiveAmount = tx.Amount
  1255. tx.EffectiveDepositAmount = tx.DepositAmount
  1256. if !tx.UserOrigin {
  1257. // case where the L1Tx is generated by the Coordinator
  1258. tx.EffectiveAmount = big.NewInt(0)
  1259. tx.EffectiveDepositAmount = big.NewInt(0)
  1260. return
  1261. }
  1262. if tx.Type == common.TxTypeCreateAccountDeposit {
  1263. return
  1264. }
  1265. if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
  1266. // CreateAccountDepositTransfer case
  1267. cmp := tx.DepositAmount.Cmp(tx.Amount)
  1268. if cmp == -1 { // DepositAmount<Amount
  1269. tx.EffectiveAmount = big.NewInt(0)
  1270. return
  1271. }
  1272. // check if tx.TokenID==receiver.TokenID
  1273. accReceiver, err := tp.s.GetAccount(tx.ToIdx)
  1274. if err != nil {
  1275. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d",
  1276. tx.ToIdx)
  1277. tx.EffectiveDepositAmount = big.NewInt(0)
  1278. tx.EffectiveAmount = big.NewInt(0)
  1279. return
  1280. }
  1281. if tx.TokenID != accReceiver.TokenID {
  1282. log.Debugf("EffectiveAmount = 0: tx TokenID (%d) != receiver account TokenID (%d)",
  1283. tx.TokenID, accReceiver.TokenID)
  1284. tx.EffectiveAmount = big.NewInt(0)
  1285. return
  1286. }
  1287. return
  1288. }
  1289. accSender, err := tp.s.GetAccount(tx.FromIdx)
  1290. if err != nil {
  1291. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d",
  1292. tx.FromIdx)
  1293. tx.EffectiveDepositAmount = big.NewInt(0)
  1294. tx.EffectiveAmount = big.NewInt(0)
  1295. return
  1296. }
  1297. // check that tx.TokenID corresponds to the Sender account TokenID
  1298. if tx.TokenID != accSender.TokenID {
  1299. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: "+
  1300. "tx.TokenID (%d) !=sender account TokenID (%d)",
  1301. tx.TokenID, accSender.TokenID)
  1302. tx.EffectiveDepositAmount = big.NewInt(0)
  1303. tx.EffectiveAmount = big.NewInt(0)
  1304. return
  1305. }
  1306. // check that Sender has enough balance
  1307. bal := accSender.Balance
  1308. if tx.DepositAmount != nil {
  1309. bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
  1310. }
  1311. cmp := bal.Cmp(tx.Amount)
  1312. if cmp == -1 {
  1313. log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
  1314. tx.EffectiveAmount = big.NewInt(0)
  1315. return
  1316. }
  1317. // check that the tx.FromEthAddr is the same than the EthAddress of the
  1318. // Sender
  1319. if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
  1320. log.Debugf("EffectiveAmount = 0: tx.FromEthAddr (%s) must be the same EthAddr of "+
  1321. "the sender account by the Idx (%s)",
  1322. tx.FromEthAddr.Hex(), accSender.EthAddr.Hex())
  1323. tx.EffectiveAmount = big.NewInt(0)
  1324. }
  1325. if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
  1326. // if transfer is Exit type, there are no more checks
  1327. return
  1328. }
  1329. // check that TokenID is the same for Sender & Receiver account
  1330. accReceiver, err := tp.s.GetAccount(tx.ToIdx)
  1331. if err != nil {
  1332. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d",
  1333. tx.ToIdx)
  1334. tx.EffectiveDepositAmount = big.NewInt(0)
  1335. tx.EffectiveAmount = big.NewInt(0)
  1336. return
  1337. }
  1338. if accSender.TokenID != accReceiver.TokenID {
  1339. log.Debugf("EffectiveAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)",
  1340. accSender.TokenID, accReceiver.TokenID)
  1341. tx.EffectiveAmount = big.NewInt(0)
  1342. return
  1343. }
  1344. if tx.TokenID != accReceiver.TokenID {
  1345. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: "+
  1346. "tx TokenID (%d) != receiver account TokenID (%d)",
  1347. tx.TokenID, accReceiver.TokenID)
  1348. tx.EffectiveAmount = big.NewInt(0)
  1349. return
  1350. }
  1351. }
  1352. // CheckEnoughBalance returns true if the sender of the transaction has enough
  1353. // balance in the account to send the Amount+Fee, and also returns the account
  1354. // Balance and the Fee+Amount (which is used to give information about why the
  1355. // transaction is not selected in case that this method returns false.
  1356. func (tp *TxProcessor) CheckEnoughBalance(tx common.PoolL2Tx) (bool, *big.Int, *big.Int) {
  1357. acc, err := tp.s.GetAccount(tx.FromIdx)
  1358. if err != nil {
  1359. return false, nil, nil
  1360. }
  1361. fee, err := common.CalcFeeAmount(tx.Amount, tx.Fee)
  1362. if err != nil {
  1363. return false, nil, nil
  1364. }
  1365. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  1366. return acc.Balance.Cmp(feeAndAmount) != -1, // !=-1 balance<amount
  1367. acc.Balance, feeAndAmount
  1368. }