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.

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