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.

912 lines
28 KiB

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