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.

683 lines
20 KiB

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