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.

725 lines
22 KiB

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