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.

681 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. log.Error(err)
  294. return nil, nil, false, ErrToIdxNotFound
  295. }
  296. } else if !bytes.Equal(tx.ToEthAddr.Bytes(), common.EmptyAddr.Bytes()) && tx.ToBJJ != nil {
  297. // case ToEthAddr!=0 && ToBJJ!=0
  298. idx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ)
  299. if err != nil {
  300. log.Error(err)
  301. return nil, nil, false, ErrToIdxNotFound
  302. }
  303. } else {
  304. // rest of cases (included case ToEthAddr==0) are not possible
  305. log.Error(err)
  306. return nil, nil, false, ErrToIdxNotFound
  307. }
  308. s.zki.AuxToIdx[s.i] = idx.BigInt()
  309. }
  310. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  311. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  312. s.zki.OnChain[s.i] = big.NewInt(0)
  313. s.zki.NewAccount[s.i] = big.NewInt(0)
  314. // L2Txs
  315. // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
  316. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  317. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  318. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  319. s.zki.S[s.i] = tx.Signature.S
  320. s.zki.R8x[s.i] = tx.Signature.R8.X
  321. s.zki.R8y[s.i] = tx.Signature.R8.Y
  322. }
  323. switch tx.Type {
  324. case common.TxTypeTransfer:
  325. // go to the MT account of sender and receiver, and update
  326. // balance & nonce
  327. err = s.applyTransfer(tx.Tx())
  328. if err != nil {
  329. return nil, nil, false, err
  330. }
  331. case common.TxTypeExit:
  332. // execute exit flow
  333. exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
  334. if err != nil {
  335. return nil, nil, false, err
  336. }
  337. return &tx.FromIdx, exitAccount, newExit, nil
  338. default:
  339. }
  340. return nil, nil, false, nil
  341. }
  342. // applyCreateAccount creates a new account in the account of the depositer, it
  343. // stores the deposit value
  344. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  345. account := &common.Account{
  346. TokenID: tx.TokenID,
  347. Nonce: 0,
  348. Balance: tx.LoadAmount,
  349. PublicKey: tx.FromBJJ,
  350. EthAddr: tx.FromEthAddr,
  351. }
  352. p, err := s.CreateAccount(common.Idx(s.idx+1), account)
  353. if err != nil {
  354. return err
  355. }
  356. if s.zki != nil {
  357. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  358. s.zki.Nonce1[s.i] = big.NewInt(0)
  359. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  360. s.zki.Sign1[s.i] = big.NewInt(1)
  361. }
  362. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  363. s.zki.Balance1[s.i] = tx.LoadAmount
  364. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  365. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  366. if p.IsOld0 {
  367. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  368. }
  369. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  370. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  371. }
  372. s.idx = s.idx + 1
  373. return s.setIdx(s.idx)
  374. }
  375. // applyDeposit updates the balance in the account of the depositer, if
  376. // andTransfer parameter is set to true, the method will also apply the
  377. // Transfer of the L1Tx/DepositTransfer
  378. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  379. // deposit the tx.LoadAmount into the sender account
  380. accSender, err := s.GetAccount(tx.FromIdx)
  381. if err != nil {
  382. return err
  383. }
  384. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
  385. // in case that the tx is a L1Tx>DepositTransfer
  386. var accReceiver *common.Account
  387. if transfer {
  388. accReceiver, err = s.GetAccount(tx.ToIdx)
  389. if err != nil {
  390. return err
  391. }
  392. // subtract amount to the sender
  393. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  394. // add amount to the receiver
  395. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  396. }
  397. // update sender account in localStateDB
  398. p, err := s.UpdateAccount(tx.FromIdx, accSender)
  399. if err != nil {
  400. return err
  401. }
  402. if s.zki != nil {
  403. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  404. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  405. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  406. s.zki.Sign1[s.i] = big.NewInt(1)
  407. }
  408. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  409. s.zki.Balance1[s.i] = accSender.Balance
  410. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  411. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  412. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  413. }
  414. // this is done after updating Sender Account (depositer)
  415. if transfer {
  416. // update receiver account in localStateDB
  417. p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  418. if err != nil {
  419. return err
  420. }
  421. if s.zki != nil {
  422. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  423. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  424. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  425. s.zki.Sign2[s.i] = big.NewInt(1)
  426. }
  427. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  428. s.zki.Balance2[s.i] = accReceiver.Balance
  429. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  430. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  431. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  432. }
  433. }
  434. return nil
  435. }
  436. // applyTransfer updates the balance & nonce in the account of the sender, and
  437. // the balance in the account of the receiver
  438. func (s *StateDB) applyTransfer(tx *common.Tx) error {
  439. // get sender and receiver accounts from localStateDB
  440. accSender, err := s.GetAccount(tx.FromIdx)
  441. if err != nil {
  442. return err
  443. }
  444. accReceiver, err := s.GetAccount(tx.ToIdx)
  445. if err != nil {
  446. return err
  447. }
  448. // increment nonce
  449. accSender.Nonce++
  450. // subtract amount to the sender
  451. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  452. // add amount to the receiver
  453. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  454. // update sender account in localStateDB
  455. pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
  456. if err != nil {
  457. return err
  458. }
  459. if s.zki != nil {
  460. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  461. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  462. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  463. s.zki.Sign1[s.i] = big.NewInt(1)
  464. }
  465. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  466. s.zki.Balance1[s.i] = accSender.Balance
  467. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  468. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
  469. }
  470. // update receiver account in localStateDB
  471. pReceiver, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  472. if err != nil {
  473. return err
  474. }
  475. if s.zki != nil {
  476. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  477. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  478. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  479. s.zki.Sign2[s.i] = big.NewInt(1)
  480. }
  481. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  482. s.zki.Balance2[s.i] = accReceiver.Balance
  483. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  484. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  485. }
  486. return nil
  487. }
  488. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  489. // makes a deposit, and performs a transfer to another account
  490. func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  491. accSender := &common.Account{
  492. TokenID: tx.TokenID,
  493. Nonce: 0,
  494. Balance: tx.LoadAmount,
  495. PublicKey: tx.FromBJJ,
  496. EthAddr: tx.FromEthAddr,
  497. }
  498. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
  499. accReceiver, err := s.GetAccount(tx.ToIdx)
  500. if err != nil {
  501. return err
  502. }
  503. // subtract amount to the sender
  504. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  505. // add amount to the receiver
  506. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  507. // create Account of the Sender
  508. p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
  509. if err != nil {
  510. return err
  511. }
  512. if s.zki != nil {
  513. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  514. s.zki.Nonce1[s.i] = big.NewInt(0)
  515. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  516. s.zki.Sign1[s.i] = big.NewInt(1)
  517. }
  518. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  519. s.zki.Balance1[s.i] = tx.LoadAmount
  520. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  521. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  522. if p.IsOld0 {
  523. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  524. }
  525. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  526. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  527. }
  528. // update receiver account in localStateDB
  529. p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  530. if err != nil {
  531. return err
  532. }
  533. if s.zki != nil {
  534. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  535. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  536. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  537. s.zki.Sign2[s.i] = big.NewInt(1)
  538. }
  539. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  540. s.zki.Balance2[s.i] = accReceiver.Balance
  541. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  542. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  543. }
  544. s.idx = s.idx + 1
  545. return s.setIdx(s.idx)
  546. }
  547. // It returns the ExitAccount and a boolean determining if the Exit created a
  548. // new Leaf in the ExitTree.
  549. func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx *common.Tx) (*common.Account, bool, error) {
  550. // 0. subtract tx.Amount from current Account in StateMT
  551. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  552. acc, err := s.GetAccount(tx.FromIdx)
  553. if err != nil {
  554. return nil, false, err
  555. }
  556. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  557. p, err := s.UpdateAccount(tx.FromIdx, acc)
  558. if err != nil {
  559. return nil, false, err
  560. }
  561. if s.zki != nil {
  562. s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
  563. s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
  564. if babyjub.PointCoordSign(acc.PublicKey.X) {
  565. s.zki.Sign1[s.i] = big.NewInt(1)
  566. }
  567. s.zki.Ay1[s.i] = acc.PublicKey.Y
  568. s.zki.Balance1[s.i] = acc.Balance
  569. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  570. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  571. }
  572. if exitTree == nil {
  573. return nil, false, nil
  574. }
  575. exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  576. if err == db.ErrNotFound {
  577. // 1a. if idx does not exist in exitTree:
  578. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
  579. exitAccount := &common.Account{
  580. TokenID: acc.TokenID,
  581. Nonce: common.Nonce(1),
  582. Balance: tx.Amount,
  583. PublicKey: acc.PublicKey,
  584. EthAddr: acc.EthAddr,
  585. }
  586. _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  587. return exitAccount, true, err
  588. } else if err != nil {
  589. return exitAccount, false, err
  590. }
  591. // 1b. if idx already exist in exitTree:
  592. // update account, where account.Balance += exitAmount
  593. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  594. _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  595. return exitAccount, false, err
  596. }
  597. // getIdx returns the stored Idx from the localStateDB, which is the last Idx
  598. // used for an Account in the localStateDB.
  599. func (s *StateDB) getIdx() (common.Idx, error) {
  600. idxBytes, err := s.DB().Get(keyidx)
  601. if err == db.ErrNotFound {
  602. return 0, nil
  603. }
  604. if err != nil {
  605. return 0, err
  606. }
  607. return common.IdxFromBytes(idxBytes[:4])
  608. }
  609. // setIdx stores Idx in the localStateDB
  610. func (s *StateDB) setIdx(idx common.Idx) error {
  611. tx, err := s.DB().NewTx()
  612. if err != nil {
  613. return err
  614. }
  615. idxBytes, err := idx.Bytes()
  616. if err != nil {
  617. return err
  618. }
  619. err = tx.Put(keyidx, idxBytes[:])
  620. if err != nil {
  621. return err
  622. }
  623. if err := tx.Commit(); err != nil {
  624. return err
  625. }
  626. return nil
  627. }