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.

1423 lines
45 KiB

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