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.

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