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.

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