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.

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