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.

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