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.

694 lines
21 KiB

  1. package statedb
  2. import (
  3. "errors"
  4. "math/big"
  5. "github.com/hermeznetwork/hermez-node/common"
  6. "github.com/hermeznetwork/hermez-node/log"
  7. "github.com/iden3/go-iden3-crypto/babyjub"
  8. "github.com/iden3/go-merkletree"
  9. "github.com/iden3/go-merkletree/db"
  10. "github.com/iden3/go-merkletree/db/memory"
  11. )
  12. var (
  13. // keyidx is used as key in the db to store the current Idx
  14. keyidx = []byte("idx")
  15. )
  16. func (s *StateDB) resetZKInputs() {
  17. s.zki = nil
  18. s.i = 0
  19. }
  20. type processedExit struct {
  21. exit bool
  22. newExit bool
  23. idx common.Idx
  24. acc common.Account
  25. }
  26. // ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  27. // the StateDB depending on the transaction Type. If StateDB
  28. // type==TypeBatchBuilder, returns the common.ZKInputs to generate the
  29. // SnarkProof later used by the BatchBuilder. If StateDB
  30. // type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
  31. // returns common.ExitTreeLeaf that is later used by the Synchronizer to update
  32. // the HistoryDB, and adds Nonce & TokenID to the L2Txs.
  33. func (s *StateDB) ProcessTxs(l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) (*common.ZKInputs, []common.ExitInfo, error) {
  34. var err error
  35. var exitTree *merkletree.MerkleTree
  36. if s.zki != nil {
  37. return nil, nil, errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty")
  38. }
  39. defer s.resetZKInputs()
  40. nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
  41. if nTx == 0 {
  42. // TODO return ZKInputs of batch without txs
  43. return nil, nil, nil
  44. }
  45. exits := make([]processedExit, nTx)
  46. if s.typ == TypeBatchBuilder {
  47. s.zki = common.NewZKInputs(nTx, 24, 32) // TODO this values will be parameters of the function, taken from config file/coordinator call
  48. s.zki.OldLastIdx = (s.idx - 1).BigInt()
  49. s.zki.OldStateRoot = s.mt.Root().BigInt()
  50. }
  51. // TBD if ExitTree is only in memory or stored in disk, for the moment
  52. // only needed in memory
  53. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  54. exitTree, err = merkletree.NewMerkleTree(memory.NewMemoryStorage(), s.mt.MaxLevels())
  55. if err != nil {
  56. return nil, nil, err
  57. }
  58. }
  59. // assumption: l1usertx are sorted by L1Tx.Position
  60. for _, tx := range l1usertxs {
  61. exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, tx)
  62. if err != nil {
  63. return nil, nil, err
  64. }
  65. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  66. if exitIdx != nil && exitTree != nil {
  67. exits[s.i] = processedExit{
  68. exit: true,
  69. newExit: newExit,
  70. idx: *exitIdx,
  71. acc: *exitAccount,
  72. }
  73. }
  74. s.i++
  75. }
  76. }
  77. for _, tx := range l1coordinatortxs {
  78. exitIdx, exitAccount, newExit, err := s.processL1Tx(exitTree, tx)
  79. if err != nil {
  80. return nil, nil, err
  81. }
  82. if exitIdx != nil {
  83. log.Error("Unexpected Exit in L1CoordinatorTx")
  84. }
  85. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  86. if exitIdx != nil && exitTree != nil {
  87. exits[s.i] = processedExit{
  88. exit: true,
  89. newExit: newExit,
  90. idx: *exitIdx,
  91. acc: *exitAccount,
  92. }
  93. }
  94. s.i++
  95. }
  96. }
  97. for _, tx := range l2txs {
  98. exitIdx, exitAccount, newExit, err := s.processL2Tx(exitTree, tx)
  99. if err != nil {
  100. return nil, nil, err
  101. }
  102. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  103. if exitIdx != nil && exitTree != nil {
  104. exits[s.i] = processedExit{
  105. exit: true,
  106. newExit: newExit,
  107. idx: *exitIdx,
  108. acc: *exitAccount,
  109. }
  110. }
  111. s.i++
  112. }
  113. }
  114. if s.typ == TypeTxSelector {
  115. return nil, nil, nil
  116. }
  117. // once all txs processed (exitTree root frozen), for each Exit,
  118. // generate common.ExitInfo data
  119. var exitInfos []common.ExitInfo
  120. for i := 0; i < nTx; i++ {
  121. if !exits[i].exit {
  122. continue
  123. }
  124. exitIdx := exits[i].idx
  125. exitAccount := exits[i].acc
  126. // 0. generate MerkleProof
  127. p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
  128. if err != nil {
  129. return nil, nil, err
  130. }
  131. // 1. generate common.ExitInfo
  132. ei := common.ExitInfo{
  133. AccountIdx: exitIdx,
  134. MerkleProof: p,
  135. Balance: exitAccount.Balance,
  136. }
  137. exitInfos = append(exitInfos, ei)
  138. if s.zki != nil {
  139. s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
  140. s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
  141. if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
  142. s.zki.Sign2[i] = big.NewInt(1)
  143. }
  144. s.zki.Ay2[i] = exitAccount.PublicKey.Y
  145. s.zki.Balance2[i] = exitAccount.Balance
  146. s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
  147. s.zki.Siblings2[i] = p.Siblings
  148. if exits[i].newExit {
  149. s.zki.NewExit[i] = big.NewInt(1)
  150. }
  151. if p.IsOld0 {
  152. s.zki.IsOld0_2[i] = big.NewInt(1)
  153. }
  154. s.zki.OldKey2[i] = p.OldKey.BigInt()
  155. s.zki.OldValue2[i] = p.OldValue.BigInt()
  156. }
  157. }
  158. if s.typ == TypeSynchronizer {
  159. return nil, exitInfos, nil
  160. }
  161. // compute last ZKInputs parameters
  162. s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
  163. // zki.FeeIdxs = ? // TODO, this will be get from the config file
  164. tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
  165. if err != nil {
  166. return nil, nil, err
  167. }
  168. s.zki.FeePlanTokens = tokenIDs
  169. // s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
  170. // TODO once the Node Config sets the Accounts where to send the Fees
  171. // compute fees & update ZKInputs
  172. // return exitInfos, so Synchronizer will be able to store it into
  173. // HistoryDB for the concrete BatchNum
  174. return s.zki, exitInfos, nil
  175. }
  176. // getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
  177. func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) ([]*big.Int, error) {
  178. tokenIDs := make(map[common.TokenID]bool)
  179. for i := 0; i < len(l1usertxs); i++ {
  180. tokenIDs[l1usertxs[i].TokenID] = true
  181. }
  182. for i := 0; i < len(l1coordinatortxs); i++ {
  183. tokenIDs[l1coordinatortxs[i].TokenID] = true
  184. }
  185. for i := 0; i < len(l2txs); i++ {
  186. // as L2Tx does not have parameter TokenID, get it from the
  187. // AccountsDB (in the StateDB)
  188. acc, err := s.GetAccount(l2txs[i].ToIdx)
  189. if err != nil {
  190. return nil, err
  191. }
  192. tokenIDs[acc.TokenID] = true
  193. }
  194. var tBI []*big.Int
  195. for t := range tokenIDs {
  196. tBI = append(tBI, t.BigInt())
  197. }
  198. return tBI, nil
  199. }
  200. // processL1Tx process the given L1Tx applying the needed updates to the
  201. // StateDB depending on the transaction Type. It returns the 3 parameters
  202. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  203. // the Exit created a new Leaf in the ExitTree.
  204. func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, error) {
  205. // ZKInputs
  206. if s.zki != nil {
  207. // Txs
  208. // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
  209. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  210. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  211. s.zki.OnChain[s.i] = big.NewInt(1)
  212. // L1Txs
  213. s.zki.LoadAmountF[s.i] = tx.LoadAmount
  214. s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  215. if tx.FromBJJ != nil {
  216. s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
  217. }
  218. // Intermediate States
  219. s.zki.ISOnChain[s.i] = big.NewInt(1)
  220. }
  221. switch tx.Type {
  222. case common.TxTypeForceTransfer, common.TxTypeTransfer:
  223. // go to the MT account of sender and receiver, and update balance
  224. // & nonce
  225. err := s.applyTransfer(tx.Tx(), 0) // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
  226. if err != nil {
  227. return nil, nil, false, err
  228. }
  229. case common.TxTypeCreateAccountDeposit:
  230. // add new account to the MT, update balance of the MT account
  231. err := s.applyCreateAccount(tx)
  232. if err != nil {
  233. return nil, nil, false, err
  234. }
  235. if s.zki != nil {
  236. s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
  237. s.zki.NewAccount[s.i] = big.NewInt(1)
  238. }
  239. case common.TxTypeDeposit:
  240. // update balance of the MT account
  241. err := s.applyDeposit(tx, false)
  242. if err != nil {
  243. return nil, nil, false, err
  244. }
  245. case common.TxTypeDepositTransfer:
  246. // update balance in MT account, update balance & nonce of sender
  247. // & receiver
  248. err := s.applyDeposit(tx, true)
  249. if err != nil {
  250. return nil, nil, false, err
  251. }
  252. case common.TxTypeCreateAccountDepositTransfer:
  253. // add new account to the merkletree, update balance in MT account,
  254. // update balance & nonce of sender & receiver
  255. err := s.applyCreateAccountDepositTransfer(tx)
  256. if err != nil {
  257. return nil, nil, false, err
  258. }
  259. if s.zki != nil {
  260. s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
  261. s.zki.NewAccount[s.i] = big.NewInt(1)
  262. }
  263. case common.TxTypeExit:
  264. // execute exit flow
  265. exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
  266. if err != nil {
  267. return nil, nil, false, err
  268. }
  269. return &tx.FromIdx, exitAccount, newExit, nil
  270. default:
  271. }
  272. return nil, nil, false, nil
  273. }
  274. // processL2Tx process the given L2Tx applying the needed updates to the
  275. // StateDB depending on the transaction Type. It returns the 3 parameters
  276. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  277. // the Exit created a new Leaf in the ExitTree.
  278. func (s *StateDB) processL2Tx(exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  279. var err error
  280. var auxToIdx common.Idx
  281. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  282. if tx.ToIdx == common.Idx(0) {
  283. auxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ)
  284. if err != nil {
  285. log.Error(err)
  286. return nil, nil, false, err
  287. }
  288. }
  289. // ZKInputs
  290. if s.zki != nil {
  291. // Txs
  292. // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
  293. // s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
  294. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  295. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  296. // fill AuxToIdx if needed
  297. if tx.ToIdx == common.Idx(0) {
  298. // use toIdx that can have been filled by tx.ToIdx or
  299. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  300. // from db by ToEthAddr&ToBJJ
  301. s.zki.AuxToIdx[s.i] = auxToIdx.BigInt()
  302. }
  303. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  304. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  305. s.zki.OnChain[s.i] = big.NewInt(0)
  306. s.zki.NewAccount[s.i] = big.NewInt(0)
  307. // L2Txs
  308. // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
  309. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  310. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  311. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  312. s.zki.S[s.i] = tx.Signature.S
  313. s.zki.R8x[s.i] = tx.Signature.R8.X
  314. s.zki.R8y[s.i] = tx.Signature.R8.Y
  315. }
  316. // if StateDB type==TypeSynchronizer, will need to add Nonce and
  317. // TokenID to the transaction
  318. if s.typ == TypeSynchronizer {
  319. acc, err := s.GetAccount(tx.ToIdx)
  320. if err != nil {
  321. return nil, nil, false, err
  322. }
  323. tx.Nonce = acc.Nonce
  324. tx.TokenID = acc.TokenID
  325. }
  326. switch tx.Type {
  327. case common.TxTypeTransfer:
  328. // go to the MT account of sender and receiver, and update
  329. // balance & nonce
  330. err = s.applyTransfer(tx.Tx(), auxToIdx)
  331. if err != nil {
  332. return nil, nil, false, err
  333. }
  334. case common.TxTypeExit:
  335. // execute exit flow
  336. exitAccount, newExit, err := s.applyExit(exitTree, tx.Tx())
  337. if err != nil {
  338. return nil, nil, false, err
  339. }
  340. return &tx.FromIdx, exitAccount, newExit, nil
  341. default:
  342. }
  343. return nil, nil, false, nil
  344. }
  345. // applyCreateAccount creates a new account in the account of the depositer, it
  346. // stores the deposit value
  347. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  348. account := &common.Account{
  349. TokenID: tx.TokenID,
  350. Nonce: 0,
  351. Balance: tx.LoadAmount,
  352. PublicKey: tx.FromBJJ,
  353. EthAddr: tx.FromEthAddr,
  354. }
  355. p, err := s.CreateAccount(common.Idx(s.idx+1), account)
  356. if err != nil {
  357. return err
  358. }
  359. if s.zki != nil {
  360. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  361. s.zki.Nonce1[s.i] = big.NewInt(0)
  362. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  363. s.zki.Sign1[s.i] = big.NewInt(1)
  364. }
  365. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  366. s.zki.Balance1[s.i] = tx.LoadAmount
  367. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  368. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  369. if p.IsOld0 {
  370. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  371. }
  372. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  373. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  374. }
  375. s.idx = s.idx + 1
  376. return s.setIdx(s.idx)
  377. }
  378. // applyDeposit updates the balance in the account of the depositer, if
  379. // andTransfer parameter is set to true, the method will also apply the
  380. // Transfer of the L1Tx/DepositTransfer
  381. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  382. // deposit the tx.LoadAmount into the sender account
  383. accSender, err := s.GetAccount(tx.FromIdx)
  384. if err != nil {
  385. return err
  386. }
  387. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
  388. // in case that the tx is a L1Tx>DepositTransfer
  389. var accReceiver *common.Account
  390. if transfer {
  391. accReceiver, err = s.GetAccount(tx.ToIdx)
  392. if err != nil {
  393. return err
  394. }
  395. // subtract amount to the sender
  396. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  397. // add amount to the receiver
  398. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  399. }
  400. // update sender account in localStateDB
  401. p, err := s.UpdateAccount(tx.FromIdx, accSender)
  402. if err != nil {
  403. return err
  404. }
  405. if s.zki != nil {
  406. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  407. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  408. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  409. s.zki.Sign1[s.i] = big.NewInt(1)
  410. }
  411. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  412. s.zki.Balance1[s.i] = accSender.Balance
  413. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  414. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  415. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  416. }
  417. // this is done after updating Sender Account (depositer)
  418. if transfer {
  419. // update receiver account in localStateDB
  420. p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  421. if err != nil {
  422. return err
  423. }
  424. if s.zki != nil {
  425. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  426. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  427. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  428. s.zki.Sign2[s.i] = big.NewInt(1)
  429. }
  430. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  431. s.zki.Balance2[s.i] = accReceiver.Balance
  432. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  433. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  434. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  435. }
  436. }
  437. return nil
  438. }
  439. // applyTransfer updates the balance & nonce in the account of the sender, and
  440. // the balance in the account of the receiver.
  441. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  442. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  443. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  444. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  445. func (s *StateDB) applyTransfer(tx *common.Tx, auxToIdx common.Idx) error {
  446. if auxToIdx == 0 {
  447. auxToIdx = tx.ToIdx
  448. }
  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(auxToIdx)
  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(auxToIdx, 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. idxBytes, err := idx.Bytes()
  626. if err != nil {
  627. return err
  628. }
  629. err = tx.Put(keyidx, idxBytes[:])
  630. if err != nil {
  631. return err
  632. }
  633. if err := tx.Commit(); err != nil {
  634. return err
  635. }
  636. return nil
  637. }