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.

693 lines
20 KiB

  1. package statedb
  2. import (
  3. "bytes"
  4. "errors"
  5. "math/big"
  6. "github.com/hermeznetwork/hermez-node/common"
  7. "github.com/hermeznetwork/hermez-node/log"
  8. "github.com/iden3/go-iden3-crypto/babyjub"
  9. "github.com/iden3/go-iden3-crypto/poseidon"
  10. "github.com/iden3/go-merkletree"
  11. "github.com/iden3/go-merkletree/db"
  12. "github.com/iden3/go-merkletree/db/memory"
  13. )
  14. var (
  15. // keyidx is used as key in the db to store the current Idx
  16. keyidx = []byte("idx")
  17. )
  18. func (s *StateDB) resetZKInputs() {
  19. s.zki = nil
  20. s.i = 0
  21. }
  22. type processedExit struct {
  23. exit bool
  24. newExit bool
  25. idx common.Idx
  26. acc common.Account
  27. }
  28. // ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  29. // the StateDB depending on the transaction Type. Returns the common.ZKInputs
  30. // to generate the SnarkProof later used by the BatchBuilder, and if
  31. // cmpExitTree is set to true, returns common.ExitTreeLeaf that is later used
  32. // by the Synchronizer to update the HistoryDB.
  33. func (s *StateDB) ProcessTxs(cmpExitTree, cmpZKInputs bool, l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) (*common.ZKInputs, []*common.ExitInfo, error) {
  34. var err error
  35. var exitTree *merkletree.MerkleTree
  36. if s.zki != nil {
  37. return nil, nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")
  38. }
  39. defer s.resetZKInputs()
  40. nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
  41. if nTx == 0 {
  42. // TODO return ZKInputs of batch without txs
  43. return nil, nil, nil
  44. }
  45. exits := make([]processedExit, nTx)
  46. if cmpZKInputs {
  47. s.zki = common.NewZKInputs(nTx, 24, 32) // TODO this values will be parameters of the function, taken from config file/coordinator call
  48. s.zki.OldLastIdx = (s.idx - 1).BigInt()
  49. s.zki.OldStateRoot = s.mt.Root().BigInt()
  50. }
  51. // TBD if ExitTree is only in memory or stored in disk, for the moment
  52. // only needed in memory
  53. if cmpExitTree {
  54. exitTree, err = merkletree.NewMerkleTree(memory.NewMemoryStorage(), s.mt.MaxLevels())
  55. if err != nil {
  56. return nil, nil, err
  57. }
  58. }
  59. // assumption: l1usertx are sorted by L1Tx.Position
  60. for _, tx := range l1usertxs {
  61. exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, tx)
  62. if err != nil {
  63. return nil, nil, err
  64. }
  65. if exitIdx != nil && cmpExitTree {
  66. exits[s.i] = processedExit{
  67. exit: true,
  68. newExit: newExit,
  69. idx: *exitIdx,
  70. acc: *exitAccount,
  71. }
  72. }
  73. if s.zki != nil {
  74. s.i++
  75. }
  76. }
  77. for _, tx := range l1coordinatortxs {
  78. exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, tx)
  79. if err != nil {
  80. return nil, nil, err
  81. }
  82. if exitIdx != nil {
  83. log.Error("Unexpected Exit in L1CoordinatorTx")
  84. }
  85. if exitIdx != nil && cmpExitTree {
  86. exits[s.i] = processedExit{
  87. exit: true,
  88. newExit: newExit,
  89. idx: *exitIdx,
  90. acc: *exitAccount,
  91. }
  92. }
  93. if s.zki != nil {
  94. s.i++
  95. }
  96. }
  97. for _, tx := range l2txs {
  98. exitIdx, exitAccount, newExit, err := s.processL2Tx(exitTree, tx)
  99. if err != nil {
  100. return nil, nil, err
  101. }
  102. if exitIdx != nil && cmpExitTree {
  103. exits[s.i] = processedExit{
  104. exit: true,
  105. newExit: newExit,
  106. idx: *exitIdx,
  107. acc: *exitAccount,
  108. }
  109. }
  110. if s.zki != nil {
  111. s.i++
  112. }
  113. }
  114. if !cmpExitTree && !cmpZKInputs {
  115. return nil, nil, nil
  116. }
  117. // once all txs processed (exitTree root frozen), for each Exit,
  118. // generate common.ExitInfo data
  119. var exitInfos []*common.ExitInfo
  120. for i := 0; i < nTx; i++ {
  121. if !exits[i].exit {
  122. continue
  123. }
  124. exitIdx := exits[i].idx
  125. exitAccount := exits[i].acc
  126. // 0. generate MerkleProof
  127. p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
  128. if err != nil {
  129. return nil, nil, err
  130. }
  131. // 1. compute nullifier
  132. exitAccStateValue, err := exitAccount.HashValue()
  133. if err != nil {
  134. return nil, nil, err
  135. }
  136. nullifier, err := poseidon.Hash([]*big.Int{
  137. exitAccStateValue,
  138. big.NewInt(int64(s.currentBatch)),
  139. exitTree.Root().BigInt(),
  140. })
  141. if err != nil {
  142. return nil, nil, err
  143. }
  144. // 2. generate common.ExitInfo
  145. ei := &common.ExitInfo{
  146. AccountIdx: exitIdx,
  147. MerkleProof: p,
  148. Nullifier: nullifier,
  149. Balance: exitAccount.Balance,
  150. }
  151. exitInfos = append(exitInfos, ei)
  152. if s.zki != nil {
  153. s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
  154. s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
  155. if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
  156. s.zki.Sign2[i] = big.NewInt(1)
  157. }
  158. s.zki.Ay2[i] = exitAccount.PublicKey.Y
  159. s.zki.Balance2[i] = exitAccount.Balance
  160. s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
  161. s.zki.Siblings2[i] = p.Siblings
  162. if exits[i].newExit {
  163. s.zki.NewExit[i] = big.NewInt(1)
  164. }
  165. if p.IsOld0 {
  166. s.zki.IsOld0_2[i] = big.NewInt(1)
  167. }
  168. s.zki.OldKey2[i] = p.OldKey.BigInt()
  169. s.zki.OldValue2[i] = p.OldValue.BigInt()
  170. }
  171. }
  172. if !cmpZKInputs {
  173. return nil, exitInfos, nil
  174. }
  175. // compute last ZKInputs parameters
  176. s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
  177. // zki.FeeIdxs = ? // TODO, this will be get from the config file
  178. tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
  179. if err != nil {
  180. return nil, nil, err
  181. }
  182. s.zki.FeePlanTokens = tokenIDs
  183. // s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
  184. // TODO once the Node Config sets the Accounts where to send the Fees
  185. // compute fees & update ZKInputs
  186. // return exitInfos, so Synchronizer will be able to store it into
  187. // HistoryDB for the concrete BatchNum
  188. return s.zki, exitInfos, nil
  189. }
  190. // getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
  191. func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) ([]*big.Int, error) {
  192. tokenIDs := make(map[common.TokenID]bool)
  193. for i := 0; i < len(l1usertxs); i++ {
  194. tokenIDs[l1usertxs[i].TokenID] = true
  195. }
  196. for i := 0; i < len(l1coordinatortxs); i++ {
  197. tokenIDs[l1coordinatortxs[i].TokenID] = true
  198. }
  199. for i := 0; i < len(l2txs); i++ {
  200. // as L2Tx does not have parameter TokenID, get it from the
  201. // AccountsDB (in the StateDB)
  202. acc, err := s.GetAccount(l2txs[i].ToIdx)
  203. if err != nil {
  204. return nil, err
  205. }
  206. tokenIDs[acc.TokenID] = true
  207. }
  208. var tBI []*big.Int
  209. for t := range tokenIDs {
  210. tBI = append(tBI, t.BigInt())
  211. }
  212. return tBI, nil
  213. }
  214. // processL1Tx process the given L1Tx applying the needed updates to the
  215. // StateDB depending on the transaction Type. It returns the 3 parameters
  216. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  217. // the Exit created a new Leaf in the ExitTree.
  218. func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, error) {
  219. // ZKInputs
  220. if s.zki != nil {
  221. // Txs
  222. // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
  223. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  224. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  225. s.zki.OnChain[s.i] = big.NewInt(1)
  226. // L1Txs
  227. s.zki.LoadAmountF[s.i] = tx.LoadAmount
  228. s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  229. if tx.FromBJJ != nil {
  230. s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
  231. }
  232. // Intermediate States
  233. s.zki.ISOnChain[s.i] = big.NewInt(1)
  234. }
  235. switch tx.Type {
  236. case common.TxTypeForceTransfer, common.TxTypeTransfer:
  237. // go to the MT account of sender and receiver, and update balance
  238. // & nonce
  239. err := s.applyTransfer(tx.Tx())
  240. if err != nil {
  241. return nil, nil, false, err
  242. }
  243. case common.TxTypeCreateAccountDeposit:
  244. // add new account to the MT, update balance of the MT account
  245. err := s.applyCreateAccount(tx)
  246. if err != nil {
  247. return nil, nil, false, err
  248. }
  249. if s.zki != nil {
  250. s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
  251. s.zki.NewAccount[s.i] = big.NewInt(1)
  252. }
  253. case common.TxTypeDeposit:
  254. // update balance of the MT account
  255. err := s.applyDeposit(tx, false)
  256. if err != nil {
  257. return nil, nil, false, err
  258. }
  259. case common.TxTypeDepositTransfer:
  260. // update balance in MT account, update balance & nonce of sender
  261. // & receiver
  262. err := s.applyDeposit(tx, true)
  263. if err != nil {
  264. return nil, nil, false, err
  265. }
  266. case common.TxTypeCreateAccountDepositTransfer:
  267. // add new account to the merkletree, update balance in MT account,
  268. // update balance & nonce of sender & receiver
  269. err := s.applyCreateAccountDepositTransfer(tx)
  270. if err != nil {
  271. return nil, nil, false, err
  272. }
  273. if s.zki != nil {
  274. s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
  275. s.zki.NewAccount[s.i] = big.NewInt(1)
  276. }
  277. case common.TxTypeExit:
  278. // execute exit flow
  279. exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
  280. if err != nil {
  281. return nil, nil, false, err
  282. }
  283. return &tx.FromIdx, exitAccount, newExit, nil
  284. default:
  285. }
  286. return nil, nil, false, nil
  287. }
  288. // processL2Tx process the given L2Tx applying the needed updates to the
  289. // StateDB depending on the transaction Type. It returns the 3 parameters
  290. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  291. // the Exit created a new Leaf in the ExitTree.
  292. func (s *StateDB) processL2Tx(exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  293. var err error
  294. // ZKInputs
  295. if s.zki != nil {
  296. // Txs
  297. // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
  298. // s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
  299. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  300. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  301. // fill AuxToIdx if needed
  302. if tx.ToIdx == common.Idx(0) {
  303. var idx common.Idx
  304. if !bytes.Equal(tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) && tx.ToBJJ == nil {
  305. // case ToEthAddr!=0 && ToBJJ=0
  306. idx, err = s.GetIdxByEthAddr(tx.ToEthAddr)
  307. if err != nil {
  308. return nil, nil, false, ErrToIdxNotFound
  309. }
  310. } else if !bytes.Equal(tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) && tx.ToBJJ != nil {
  311. // case ToEthAddr!=0 && ToBJJ!=0
  312. idx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ)
  313. if err != nil {
  314. return nil, nil, false, ErrToIdxNotFound
  315. }
  316. } else {
  317. // rest of cases (included case ToEthAddr==0) are not possible
  318. return nil, nil, false, ErrToIdxNotFound
  319. }
  320. s.zki.AuxToIdx[s.i] = idx.BigInt()
  321. }
  322. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  323. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  324. s.zki.OnChain[s.i] = big.NewInt(0)
  325. s.zki.NewAccount[s.i] = big.NewInt(0)
  326. // L2Txs
  327. // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
  328. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  329. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  330. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  331. s.zki.S[s.i] = tx.Signature.S
  332. s.zki.R8x[s.i] = tx.Signature.R8.X
  333. s.zki.R8y[s.i] = tx.Signature.R8.Y
  334. }
  335. switch tx.Type {
  336. case common.TxTypeTransfer:
  337. // go to the MT account of sender and receiver, and update
  338. // balance & nonce
  339. err = s.applyTransfer(tx.Tx())
  340. if err != nil {
  341. return nil, nil, false, err
  342. }
  343. case common.TxTypeExit:
  344. // execute exit flow
  345. exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
  346. if err != nil {
  347. return nil, nil, false, err
  348. }
  349. return &tx.FromIdx, exitAccount, newExit, nil
  350. default:
  351. }
  352. return nil, nil, false, nil
  353. }
  354. // applyCreateAccount creates a new account in the account of the depositer, it
  355. // stores the deposit value
  356. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  357. account := &common.Account{
  358. TokenID: tx.TokenID,
  359. Nonce: 0,
  360. Balance: tx.LoadAmount,
  361. PublicKey: tx.FromBJJ,
  362. EthAddr: tx.FromEthAddr,
  363. }
  364. p, err := s.CreateAccount(common.Idx(s.idx+1), account)
  365. if err != nil {
  366. return err
  367. }
  368. if s.zki != nil {
  369. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  370. s.zki.Nonce1[s.i] = big.NewInt(0)
  371. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  372. s.zki.Sign1[s.i] = big.NewInt(1)
  373. }
  374. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  375. s.zki.Balance1[s.i] = tx.LoadAmount
  376. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  377. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  378. if p.IsOld0 {
  379. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  380. }
  381. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  382. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  383. }
  384. s.idx = s.idx + 1
  385. return s.setIdx(s.idx)
  386. }
  387. // applyDeposit updates the balance in the account of the depositer, if
  388. // andTransfer parameter is set to true, the method will also apply the
  389. // Transfer of the L1Tx/DepositTransfer
  390. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  391. // deposit the tx.LoadAmount into the sender account
  392. accSender, err := s.GetAccount(tx.FromIdx)
  393. if err != nil {
  394. return err
  395. }
  396. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
  397. // in case that the tx is a L1Tx>DepositTransfer
  398. var accReceiver *common.Account
  399. if transfer {
  400. accReceiver, err = s.GetAccount(tx.ToIdx)
  401. if err != nil {
  402. return err
  403. }
  404. // subtract amount to the sender
  405. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  406. // add amount to the receiver
  407. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  408. }
  409. // update sender account in localStateDB
  410. p, err := s.UpdateAccount(tx.FromIdx, accSender)
  411. if err != nil {
  412. return err
  413. }
  414. if s.zki != nil {
  415. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  416. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  417. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  418. s.zki.Sign1[s.i] = big.NewInt(1)
  419. }
  420. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  421. s.zki.Balance1[s.i] = accSender.Balance
  422. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  423. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  424. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  425. }
  426. // this is done after updating Sender Account (depositer)
  427. if transfer {
  428. // update receiver account in localStateDB
  429. p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  430. if err != nil {
  431. return err
  432. }
  433. if s.zki != nil {
  434. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  435. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  436. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  437. s.zki.Sign2[s.i] = big.NewInt(1)
  438. }
  439. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  440. s.zki.Balance2[s.i] = accReceiver.Balance
  441. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  442. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  443. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  444. }
  445. }
  446. return nil
  447. }
  448. // applyTransfer updates the balance & nonce in the account of the sender, and
  449. // the balance in the account of the receiver
  450. func (s *StateDB) applyTransfer(tx *common.Tx) error {
  451. // get sender and receiver accounts from localStateDB
  452. accSender, err := s.GetAccount(tx.FromIdx)
  453. if err != nil {
  454. return err
  455. }
  456. accReceiver, err := s.GetAccount(tx.ToIdx)
  457. if err != nil {
  458. return err
  459. }
  460. // increment nonce
  461. accSender.Nonce++
  462. // subtract amount to the sender
  463. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  464. // add amount to the receiver
  465. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  466. // update sender account in localStateDB
  467. pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
  468. if err != nil {
  469. return err
  470. }
  471. if s.zki != nil {
  472. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  473. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  474. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  475. s.zki.Sign1[s.i] = big.NewInt(1)
  476. }
  477. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  478. s.zki.Balance1[s.i] = accSender.Balance
  479. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  480. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
  481. }
  482. // update receiver account in localStateDB
  483. pReceiver, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  484. if err != nil {
  485. return err
  486. }
  487. if s.zki != nil {
  488. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  489. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  490. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  491. s.zki.Sign2[s.i] = big.NewInt(1)
  492. }
  493. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  494. s.zki.Balance2[s.i] = accReceiver.Balance
  495. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  496. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  497. }
  498. return nil
  499. }
  500. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  501. // makes a deposit, and performs a transfer to another account
  502. func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  503. accSender := &common.Account{
  504. TokenID: tx.TokenID,
  505. Nonce: 0,
  506. Balance: tx.LoadAmount,
  507. PublicKey: tx.FromBJJ,
  508. EthAddr: tx.FromEthAddr,
  509. }
  510. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
  511. accReceiver, err := s.GetAccount(tx.ToIdx)
  512. if err != nil {
  513. return err
  514. }
  515. // subtract amount to the sender
  516. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  517. // add amount to the receiver
  518. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  519. // create Account of the Sender
  520. p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
  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. }
  540. // update receiver account in localStateDB
  541. p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  542. if err != nil {
  543. return err
  544. }
  545. if s.zki != nil {
  546. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  547. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  548. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  549. s.zki.Sign2[s.i] = big.NewInt(1)
  550. }
  551. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  552. s.zki.Balance2[s.i] = accReceiver.Balance
  553. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  554. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  555. }
  556. s.idx = s.idx + 1
  557. return s.setIdx(s.idx)
  558. }
  559. // It returns the ExitAccount and a boolean determining if the Exit created a
  560. // new Leaf in the ExitTree.
  561. func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx *common.Tx) (*common.Account, bool, error) {
  562. // 0. subtract tx.Amount from current Account in StateMT
  563. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  564. acc, err := s.GetAccount(tx.FromIdx)
  565. if err != nil {
  566. return nil, false, err
  567. }
  568. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  569. p, err := s.UpdateAccount(tx.FromIdx, acc)
  570. if err != nil {
  571. return nil, false, err
  572. }
  573. if s.zki != nil {
  574. s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
  575. s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
  576. if babyjub.PointCoordSign(acc.PublicKey.X) {
  577. s.zki.Sign1[s.i] = big.NewInt(1)
  578. }
  579. s.zki.Ay1[s.i] = acc.PublicKey.Y
  580. s.zki.Balance1[s.i] = acc.Balance
  581. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  582. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  583. }
  584. if exitTree == nil {
  585. return nil, false, nil
  586. }
  587. exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  588. if err == db.ErrNotFound {
  589. // 1a. if idx does not exist in exitTree:
  590. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
  591. exitAccount := &common.Account{
  592. TokenID: acc.TokenID,
  593. Nonce: common.Nonce(1),
  594. Balance: tx.Amount,
  595. PublicKey: acc.PublicKey,
  596. EthAddr: acc.EthAddr,
  597. }
  598. _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  599. return exitAccount, true, err
  600. } else if err != nil {
  601. return exitAccount, false, err
  602. }
  603. // 1b. if idx already exist in exitTree:
  604. // update account, where account.Balance += exitAmount
  605. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  606. _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  607. return exitAccount, false, err
  608. }
  609. // getIdx returns the stored Idx from the localStateDB, which is the last Idx
  610. // used for an Account in the localStateDB.
  611. func (s *StateDB) getIdx() (common.Idx, error) {
  612. idxBytes, err := s.DB().Get(keyidx)
  613. if err == db.ErrNotFound {
  614. return 0, nil
  615. }
  616. if err != nil {
  617. return 0, err
  618. }
  619. return common.IdxFromBytes(idxBytes[:4])
  620. }
  621. // setIdx stores Idx in the localStateDB
  622. func (s *StateDB) setIdx(idx common.Idx) error {
  623. tx, err := s.DB().NewTx()
  624. if err != nil {
  625. return err
  626. }
  627. idxBytes, err := idx.Bytes()
  628. if err != nil {
  629. return err
  630. }
  631. err = tx.Put(keyidx, idxBytes[:])
  632. if err != nil {
  633. return err
  634. }
  635. if err := tx.Commit(); err != nil {
  636. return err
  637. }
  638. return nil
  639. }