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.

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