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.

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