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.

1114 lines
34 KiB

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