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.

484 lines
14 KiB

  1. package statedb
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "math/big"
  7. ethCommon "github.com/ethereum/go-ethereum/common"
  8. "github.com/hermeznetwork/hermez-node/common"
  9. "github.com/iden3/go-iden3-crypto/poseidon"
  10. "github.com/iden3/go-merkletree"
  11. "github.com/iden3/go-merkletree/db"
  12. "github.com/iden3/go-merkletree/db/memory"
  13. )
  14. var (
  15. // keyidx is used as key in the db to store the current Idx
  16. keyidx = []byte("idx")
  17. ffAddr = ethCommon.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
  18. )
  19. func (s *StateDB) resetZKInputs() {
  20. s.zki = nil
  21. s.i = 0
  22. }
  23. // ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  24. // the StateDB depending on the transaction Type. Returns the common.ZKInputs
  25. // to generate the SnarkProof later used by the BatchBuilder, and if
  26. // cmpExitTree is set to true, returns common.ExitTreeLeaf that is later used
  27. // by the Synchronizer to update the HistoryDB.
  28. func (s *StateDB) ProcessTxs(cmpExitTree, cmpZKInputs bool, l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) (*common.ZKInputs, []*common.ExitInfo, error) {
  29. var err error
  30. var exitTree *merkletree.MerkleTree
  31. exits := make(map[common.Idx]common.Account)
  32. if s.zki != nil {
  33. return nil, nil, errors.New("Expected StateDB.zki==nil, something went wrong ans is not empty")
  34. }
  35. defer s.resetZKInputs()
  36. nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
  37. if nTx == 0 {
  38. return nil, nil, nil // TBD if return an error in the case of no Txs to process
  39. }
  40. if cmpZKInputs {
  41. s.zki = common.NewZKInputs(nTx, 24, 32) // TODO this values will be parameters of the function
  42. }
  43. // TBD if ExitTree is only in memory or stored in disk, for the moment
  44. // only needed in memory
  45. exitTree, err = merkletree.NewMerkleTree(memory.NewMemoryStorage(), s.mt.MaxLevels())
  46. if err != nil {
  47. return nil, nil, err
  48. }
  49. // assumption: l1usertx are sorted by L1Tx.Position
  50. for _, tx := range l1usertxs {
  51. exitIdx, exitAccount, err := s.processL1Tx(exitTree, tx)
  52. if err != nil {
  53. return nil, nil, err
  54. }
  55. if exitIdx != nil && cmpExitTree {
  56. exits[*exitIdx] = *exitAccount
  57. }
  58. if s.zki != nil {
  59. s.i++
  60. }
  61. }
  62. for _, tx := range l1coordinatortxs {
  63. exitIdx, exitAccount, err := s.processL1Tx(exitTree, tx)
  64. if err != nil {
  65. return nil, nil, err
  66. }
  67. if exitIdx != nil && cmpExitTree {
  68. exits[*exitIdx] = *exitAccount
  69. }
  70. if s.zki != nil {
  71. s.i++
  72. }
  73. }
  74. for _, tx := range l2txs {
  75. exitIdx, exitAccount, err := s.processL2Tx(exitTree, tx)
  76. if err != nil {
  77. return nil, nil, err
  78. }
  79. if exitIdx != nil && cmpExitTree {
  80. exits[*exitIdx] = *exitAccount
  81. }
  82. if s.zki != nil {
  83. s.i++
  84. }
  85. }
  86. if !cmpExitTree && !cmpZKInputs {
  87. return nil, nil, nil
  88. }
  89. // once all txs processed (exitTree root frozen), for each leaf
  90. // generate common.ExitInfo data
  91. var exitInfos []*common.ExitInfo
  92. for exitIdx, exitAccount := range exits {
  93. // 0. generate MerkleProof
  94. p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
  95. if err != nil {
  96. return nil, nil, err
  97. }
  98. // 1. compute nullifier
  99. exitAccStateValue, err := exitAccount.HashValue()
  100. if err != nil {
  101. return nil, nil, err
  102. }
  103. nullifier, err := poseidon.Hash([]*big.Int{
  104. exitAccStateValue,
  105. big.NewInt(int64(s.currentBatch)),
  106. exitTree.Root().BigInt(),
  107. })
  108. if err != nil {
  109. return nil, nil, err
  110. }
  111. // 2. generate common.ExitInfo
  112. ei := &common.ExitInfo{
  113. AccountIdx: exitIdx,
  114. MerkleProof: p,
  115. Nullifier: nullifier,
  116. Balance: exitAccount.Balance,
  117. }
  118. exitInfos = append(exitInfos, ei)
  119. }
  120. if !cmpZKInputs {
  121. return nil, exitInfos, nil
  122. }
  123. // compute last ZKInputs parameters
  124. s.zki.OldLastIdx = (s.idx - 1).BigInt()
  125. s.zki.OldStateRoot = s.mt.Root().BigInt()
  126. s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, get this from config file
  127. // zki.FeeIdxs = ? // TODO, this will be get from the config file
  128. tokenIDs, err := s.getTokenIDsBigInt(l1usertxs, l1coordinatortxs, l2txs)
  129. if err != nil {
  130. return nil, nil, err
  131. }
  132. s.zki.FeePlanTokens = tokenIDs
  133. // s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
  134. // compute fees
  135. // once fees are computed
  136. // return exitInfos, so Synchronizer will be able to store it into
  137. // HistoryDB for the concrete BatchNum
  138. return s.zki, exitInfos, nil
  139. }
  140. // getTokenIDsBigInt returns the list of TokenIDs in *big.Int format
  141. func (s *StateDB) getTokenIDsBigInt(l1usertxs, l1coordinatortxs []*common.L1Tx, l2txs []*common.PoolL2Tx) ([]*big.Int, error) {
  142. tokenIDs := make(map[common.TokenID]bool)
  143. for i := 0; i < len(l1usertxs); i++ {
  144. tokenIDs[l1usertxs[i].TokenID] = true
  145. }
  146. for i := 0; i < len(l1coordinatortxs); i++ {
  147. tokenIDs[l1coordinatortxs[i].TokenID] = true
  148. }
  149. for i := 0; i < len(l2txs); i++ {
  150. // as L2Tx does not have parameter TokenID, get it from the
  151. // AccountsDB (in the StateDB)
  152. acc, err := s.GetAccount(l2txs[i].ToIdx)
  153. if err != nil {
  154. return nil, err
  155. }
  156. tokenIDs[acc.TokenID] = true
  157. }
  158. var tBI []*big.Int
  159. for t := range tokenIDs {
  160. tBI = append(tBI, t.BigInt())
  161. }
  162. return tBI, nil
  163. }
  164. // processL1Tx process the given L1Tx applying the needed updates to the
  165. // StateDB depending on the transaction Type.
  166. func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, error) {
  167. // ZKInputs
  168. if s.zki != nil {
  169. // Txs
  170. // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
  171. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  172. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  173. s.zki.OnChain[s.i] = big.NewInt(1)
  174. // L1Txs
  175. s.zki.LoadAmountF[s.i] = tx.LoadAmount
  176. s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  177. if tx.FromBJJ != nil {
  178. s.zki.FromBJJCompressed[s.i] = common.BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
  179. }
  180. // Intermediate States
  181. s.zki.ISOnChain[s.i] = big.NewInt(1)
  182. }
  183. switch tx.Type {
  184. case common.TxTypeForceTransfer, common.TxTypeTransfer:
  185. // go to the MT account of sender and receiver, and update balance
  186. // & nonce
  187. err := s.applyTransfer(tx.Tx())
  188. if err != nil {
  189. return nil, nil, err
  190. }
  191. case common.TxTypeCreateAccountDeposit:
  192. // add new account to the MT, update balance of the MT account
  193. err := s.applyCreateAccount(tx)
  194. if err != nil {
  195. return nil, nil, err
  196. }
  197. if s.zki != nil {
  198. s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
  199. s.zki.NewAccount[s.i] = big.NewInt(1)
  200. }
  201. case common.TxTypeDeposit:
  202. // update balance of the MT account
  203. err := s.applyDeposit(tx, false)
  204. if err != nil {
  205. return nil, nil, err
  206. }
  207. case common.TxTypeDepositTransfer:
  208. // update balance in MT account, update balance & nonce of sender
  209. // & receiver
  210. err := s.applyDeposit(tx, true)
  211. if err != nil {
  212. return nil, nil, err
  213. }
  214. case common.TxTypeCreateAccountDepositTransfer:
  215. // add new account to the merkletree, update balance in MT account,
  216. // update balance & nonce of sender & receiver
  217. err := s.applyCreateAccount(tx)
  218. if err != nil {
  219. return nil, nil, err
  220. }
  221. err = s.applyTransfer(tx.Tx())
  222. if err != nil {
  223. return nil, nil, err
  224. }
  225. if s.zki != nil {
  226. s.zki.AuxFromIdx[s.i] = s.idx.BigInt() // last s.idx is the one used for creating the new account
  227. s.zki.NewAccount[s.i] = big.NewInt(1)
  228. }
  229. case common.TxTypeExit:
  230. // execute exit flow
  231. exitAccount, err := s.applyExit(exitTree, tx.Tx())
  232. if err != nil {
  233. return nil, nil, err
  234. }
  235. return &tx.FromIdx, exitAccount, nil
  236. default:
  237. }
  238. return nil, nil, nil
  239. }
  240. // processL2Tx process the given L2Tx applying the needed updates to
  241. // the StateDB depending on the transaction Type.
  242. func (s *StateDB) processL2Tx(exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, error) {
  243. // ZKInputs
  244. if s.zki != nil {
  245. // Txs
  246. // s.zki.TxCompressedData[s.i] = tx.TxCompressedData() // uncomment once L1Tx.TxCompressedData is ready
  247. // s.zki.TxCompressedDataV2[s.i] = tx.TxCompressedDataV2() // uncomment once L2Tx.TxCompressedDataV2 is ready
  248. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  249. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  250. // fill AuxToIdx if needed
  251. if tx.ToIdx == common.Idx(0) {
  252. // Idx not set in the Tx, get it from DB through ToEthAddr or ToBJJ
  253. var idx common.Idx
  254. if !bytes.Equal(tx.ToEthAddr.Bytes(), ffAddr.Bytes()) {
  255. idx = s.getIdxByEthAddr(tx.ToEthAddr)
  256. if idx == common.Idx(0) {
  257. return nil, nil, fmt.Errorf("Idx can not be found for given tx.FromEthAddr")
  258. }
  259. } else {
  260. idx = s.getIdxByBJJ(tx.ToBJJ)
  261. if idx == common.Idx(0) {
  262. return nil, nil, fmt.Errorf("Idx can not be found for given tx.FromBJJ")
  263. }
  264. }
  265. s.zki.AuxToIdx[s.i] = idx.BigInt()
  266. }
  267. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  268. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  269. s.zki.OnChain[s.i] = big.NewInt(0)
  270. s.zki.NewAccount[s.i] = big.NewInt(0)
  271. // L2Txs
  272. // s.zki.RqOffset[s.i] = // TODO
  273. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  274. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  275. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  276. s.zki.S[s.i] = tx.Signature.S
  277. s.zki.R8x[s.i] = tx.Signature.R8.X
  278. s.zki.R8y[s.i] = tx.Signature.R8.Y
  279. }
  280. switch tx.Type {
  281. case common.TxTypeTransfer:
  282. // go to the MT account of sender and receiver, and update
  283. // balance & nonce
  284. err := s.applyTransfer(tx.Tx())
  285. if err != nil {
  286. return nil, nil, err
  287. }
  288. case common.TxTypeExit:
  289. // execute exit flow
  290. exitAccount, err := s.applyExit(exitTree, tx.Tx())
  291. if err != nil {
  292. return nil, nil, err
  293. }
  294. return &tx.FromIdx, exitAccount, nil
  295. default:
  296. }
  297. return nil, nil, nil
  298. }
  299. // applyCreateAccount creates a new account in the account of the depositer, it
  300. // stores the deposit value
  301. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  302. account := &common.Account{
  303. TokenID: tx.TokenID,
  304. Nonce: 0,
  305. Balance: tx.LoadAmount,
  306. PublicKey: tx.FromBJJ,
  307. EthAddr: tx.FromEthAddr,
  308. }
  309. _, err := s.CreateAccount(common.Idx(s.idx+1), account)
  310. if err != nil {
  311. return err
  312. }
  313. s.idx = s.idx + 1
  314. return s.setIdx(s.idx)
  315. }
  316. // applyDeposit updates the balance in the account of the depositer, if
  317. // andTransfer parameter is set to true, the method will also apply the
  318. // Transfer of the L1Tx/DepositTransfer
  319. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  320. // deposit the tx.LoadAmount into the sender account
  321. accSender, err := s.GetAccount(tx.FromIdx)
  322. if err != nil {
  323. return err
  324. }
  325. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.LoadAmount)
  326. // in case that the tx is a L1Tx>DepositTransfer
  327. if transfer {
  328. accReceiver, err := s.GetAccount(tx.ToIdx)
  329. if err != nil {
  330. return err
  331. }
  332. // subtract amount to the sender
  333. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  334. // add amount to the receiver
  335. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  336. // update receiver account in localStateDB
  337. _, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  338. if err != nil {
  339. return err
  340. }
  341. }
  342. // update sender account in localStateDB
  343. _, err = s.UpdateAccount(tx.FromIdx, accSender)
  344. if err != nil {
  345. return err
  346. }
  347. return nil
  348. }
  349. // applyTransfer updates the balance & nonce in the account of the sender, and
  350. // the balance in the account of the receiver
  351. func (s *StateDB) applyTransfer(tx *common.Tx) error {
  352. // get sender and receiver accounts from localStateDB
  353. accSender, err := s.GetAccount(tx.FromIdx)
  354. if err != nil {
  355. return err
  356. }
  357. accReceiver, err := s.GetAccount(tx.ToIdx)
  358. if err != nil {
  359. return err
  360. }
  361. // increment nonce
  362. accSender.Nonce++
  363. // subtract amount to the sender
  364. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  365. // add amount to the receiver
  366. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  367. // update receiver account in localStateDB
  368. _, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  369. if err != nil {
  370. return err
  371. }
  372. // update sender account in localStateDB
  373. _, err = s.UpdateAccount(tx.FromIdx, accSender)
  374. if err != nil {
  375. return err
  376. }
  377. return nil
  378. }
  379. func (s *StateDB) applyExit(exitTree *merkletree.MerkleTree, tx *common.Tx) (*common.Account, error) {
  380. // 0. subtract tx.Amount from current Account in StateMT
  381. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  382. acc, err := s.GetAccount(tx.FromIdx)
  383. if err != nil {
  384. return nil, err
  385. }
  386. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  387. _, err = s.UpdateAccount(tx.FromIdx, acc)
  388. if err != nil {
  389. return nil, err
  390. }
  391. exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  392. if err == db.ErrNotFound {
  393. // 1a. if idx does not exist in exitTree:
  394. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
  395. exitAccount := &common.Account{
  396. TokenID: acc.TokenID,
  397. Nonce: common.Nonce(1),
  398. Balance: tx.Amount,
  399. PublicKey: acc.PublicKey,
  400. EthAddr: acc.EthAddr,
  401. }
  402. _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  403. return exitAccount, err
  404. } else if err != nil {
  405. return exitAccount, err
  406. }
  407. // 1b. if idx already exist in exitTree:
  408. // update account, where account.Balance += exitAmount
  409. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  410. _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  411. return exitAccount, err
  412. }
  413. // getIdx returns the stored Idx from the localStateDB, which is the last Idx
  414. // used for an Account in the localStateDB.
  415. func (s *StateDB) getIdx() (common.Idx, error) {
  416. idxBytes, err := s.DB().Get(keyidx)
  417. if err == db.ErrNotFound {
  418. return 0, nil
  419. }
  420. if err != nil {
  421. return 0, err
  422. }
  423. return common.IdxFromBytes(idxBytes[:4])
  424. }
  425. // setIdx stores Idx in the localStateDB
  426. func (s *StateDB) setIdx(idx common.Idx) error {
  427. tx, err := s.DB().NewTx()
  428. if err != nil {
  429. return err
  430. }
  431. err = tx.Put(keyidx, idx.Bytes())
  432. if err != nil {
  433. return err
  434. }
  435. if err := tx.Commit(); err != nil {
  436. return err
  437. }
  438. return nil
  439. }