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.

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