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.

1152 lines
36 KiB

  1. package statedb
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "math/big"
  8. "os"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/log"
  11. "github.com/hermeznetwork/tracerr"
  12. "github.com/iden3/go-iden3-crypto/babyjub"
  13. "github.com/iden3/go-merkletree"
  14. "github.com/iden3/go-merkletree/db"
  15. "github.com/iden3/go-merkletree/db/pebble"
  16. )
  17. var (
  18. // keyidx is used as key in the db to store the current Idx
  19. keyidx = []byte("k:idx")
  20. )
  21. func (s *StateDB) resetZKInputs() {
  22. s.zki = nil
  23. s.i = 0 // initialize current transaction index in the ZKInputs generation
  24. }
  25. type processedExit struct {
  26. exit bool
  27. newExit bool
  28. idx common.Idx
  29. acc common.Account
  30. }
  31. // ProcessTxOutput contains the output of the ProcessTxs method
  32. type ProcessTxOutput struct {
  33. ZKInputs *common.ZKInputs
  34. ExitInfos []common.ExitInfo
  35. CreatedAccounts []common.Account
  36. CoordinatorIdxsMap map[common.TokenID]common.Idx
  37. CollectedFees map[common.TokenID]*big.Int
  38. }
  39. // ProcessTxsConfig contains the config for ProcessTxs
  40. type ProcessTxsConfig struct {
  41. NLevels uint32
  42. MaxFeeTx uint32
  43. MaxTx uint32
  44. MaxL1Tx uint32
  45. }
  46. // ProcessTxs process the given L1Txs & L2Txs applying the needed updates to
  47. // the StateDB depending on the transaction Type. If StateDB
  48. // type==TypeBatchBuilder, returns the common.ZKInputs to generate the
  49. // SnarkProof later used by the BatchBuilder. If StateDB
  50. // type==TypeSynchronizer, assumes that the call is done from the Synchronizer,
  51. // returns common.ExitTreeLeaf that is later used by the Synchronizer to update
  52. // the HistoryDB, and adds Nonce & TokenID to the L2Txs.
  53. // And if TypeSynchronizer returns an array of common.Account with all the
  54. // created accounts.
  55. func (s *StateDB) ProcessTxs(ptc ProcessTxsConfig, coordIdxs []common.Idx, l1usertxs, l1coordinatortxs []common.L1Tx, l2txs []common.PoolL2Tx) (ptOut *ProcessTxOutput, err error) {
  56. defer func() {
  57. if err == nil {
  58. err = s.MakeCheckpoint()
  59. }
  60. }()
  61. var exitTree *merkletree.MerkleTree
  62. var createdAccounts []common.Account
  63. if s.zki != nil {
  64. return nil, tracerr.Wrap(errors.New("Expected StateDB.zki==nil, something went wrong and it's not empty"))
  65. }
  66. defer s.resetZKInputs()
  67. if len(coordIdxs) >= int(ptc.MaxFeeTx) {
  68. return nil, tracerr.Wrap(fmt.Errorf("CoordIdxs (%d) length must be smaller than MaxFeeTx (%d)", len(coordIdxs), ptc.MaxFeeTx))
  69. }
  70. s.accumulatedFees = make(map[common.Idx]*big.Int)
  71. nTx := len(l1usertxs) + len(l1coordinatortxs) + len(l2txs)
  72. if nTx == 0 {
  73. // TODO return ZKInputs of batch without txs
  74. return &ProcessTxOutput{
  75. ZKInputs: nil,
  76. ExitInfos: nil,
  77. CreatedAccounts: nil,
  78. CoordinatorIdxsMap: nil,
  79. CollectedFees: nil,
  80. }, nil
  81. }
  82. if nTx > int(ptc.MaxTx) {
  83. return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx + L2Tx (%d) can not be bigger than MaxTx (%d)", nTx, ptc.MaxTx))
  84. }
  85. if len(l1usertxs)+len(l1coordinatortxs) > int(ptc.MaxL1Tx) {
  86. return nil, tracerr.Wrap(fmt.Errorf("L1UserTx + L1CoordinatorTx (%d) can not be bigger than MaxL1Tx (%d)", len(l1usertxs)+len(l1coordinatortxs), ptc.MaxTx))
  87. }
  88. exits := make([]processedExit, nTx)
  89. if s.typ == TypeBatchBuilder {
  90. s.zki = common.NewZKInputs(ptc.MaxTx, ptc.MaxL1Tx, ptc.MaxTx, ptc.MaxFeeTx, ptc.NLevels, s.currentBatch.BigInt())
  91. s.zki.OldLastIdx = s.idx.BigInt()
  92. s.zki.OldStateRoot = s.mt.Root().BigInt()
  93. }
  94. // TBD if ExitTree is only in memory or stored in disk, for the moment
  95. // is only needed in memory
  96. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  97. tmpDir, err := ioutil.TempDir("", "hermez-statedb-exittree")
  98. if err != nil {
  99. return nil, tracerr.Wrap(err)
  100. }
  101. defer func() {
  102. if err := os.RemoveAll(tmpDir); err != nil {
  103. log.Errorw("Deleting statedb temp exit tree", "err", err)
  104. }
  105. }()
  106. sto, err := pebble.NewPebbleStorage(tmpDir, false)
  107. if err != nil {
  108. return nil, tracerr.Wrap(err)
  109. }
  110. exitTree, err = merkletree.NewMerkleTree(sto, s.mt.MaxLevels())
  111. if err != nil {
  112. return nil, tracerr.Wrap(err)
  113. }
  114. }
  115. // Process L1UserTxs
  116. for i := 0; i < len(l1usertxs); i++ {
  117. // assumption: l1usertx are sorted by L1Tx.Position
  118. exitIdx, exitAccount, newExit, createdAccount, err := s.processL1Tx(exitTree, &l1usertxs[i])
  119. if err != nil {
  120. return nil, tracerr.Wrap(err)
  121. }
  122. if s.typ == TypeSynchronizer && createdAccount != nil {
  123. createdAccounts = append(createdAccounts, *createdAccount)
  124. }
  125. if s.zki != nil {
  126. l1TxData, err := l1usertxs[i].BytesGeneric()
  127. if err != nil {
  128. return nil, tracerr.Wrap(err)
  129. }
  130. s.zki.Metadata.L1TxsData = append(s.zki.Metadata.L1TxsData, l1TxData)
  131. l1TxDataAvailability, err := l1usertxs[i].BytesDataAvailability(s.zki.Metadata.NLevels)
  132. if err != nil {
  133. return nil, tracerr.Wrap(err)
  134. }
  135. s.zki.Metadata.L1TxsDataAvailability = append(s.zki.Metadata.L1TxsDataAvailability, l1TxDataAvailability)
  136. s.zki.ISOutIdx[s.i] = s.idx.BigInt()
  137. s.zki.ISStateRoot[s.i] = s.mt.Root().BigInt()
  138. }
  139. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  140. if exitIdx != nil && exitTree != nil {
  141. exits[s.i] = processedExit{
  142. exit: true,
  143. newExit: newExit,
  144. idx: *exitIdx,
  145. acc: *exitAccount,
  146. }
  147. }
  148. s.i++
  149. }
  150. }
  151. // Process L1CoordinatorTxs
  152. for i := 0; i < len(l1coordinatortxs); i++ {
  153. exitIdx, _, _, createdAccount, err := s.processL1Tx(exitTree, &l1coordinatortxs[i])
  154. if err != nil {
  155. return nil, tracerr.Wrap(err)
  156. }
  157. if exitIdx != nil {
  158. log.Error("Unexpected Exit in L1CoordinatorTx")
  159. }
  160. if s.typ == TypeSynchronizer && createdAccount != nil {
  161. createdAccounts = append(createdAccounts, *createdAccount)
  162. }
  163. if s.zki != nil {
  164. l1TxData, err := l1coordinatortxs[i].BytesGeneric()
  165. if err != nil {
  166. return nil, tracerr.Wrap(err)
  167. }
  168. s.zki.Metadata.L1TxsData = append(s.zki.Metadata.L1TxsData, l1TxData)
  169. s.zki.ISOutIdx[s.i] = s.idx.BigInt()
  170. s.zki.ISStateRoot[s.i] = s.mt.Root().BigInt()
  171. s.i++
  172. }
  173. }
  174. s.accumulatedFees = make(map[common.Idx]*big.Int)
  175. for _, idx := range coordIdxs {
  176. s.accumulatedFees[idx] = big.NewInt(0)
  177. }
  178. // once L1UserTxs & L1CoordinatorTxs are processed, get TokenIDs of
  179. // coordIdxs. In this way, if a coordIdx uses an Idx that is being
  180. // created in the current batch, at this point the Idx will be created
  181. coordIdxsMap, err := s.getTokenIDsFromIdxs(coordIdxs)
  182. if err != nil {
  183. return nil, tracerr.Wrap(err)
  184. }
  185. // collectedFees will contain the amount of fee collected for each
  186. // TokenID
  187. var collectedFees map[common.TokenID]*big.Int
  188. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  189. collectedFees = make(map[common.TokenID]*big.Int)
  190. for tokenID := range coordIdxsMap {
  191. collectedFees[tokenID] = big.NewInt(0)
  192. }
  193. }
  194. if s.zki != nil {
  195. // get the feePlanTokens
  196. feePlanTokens, err := s.getFeePlanTokens(coordIdxs, l2txs)
  197. if err != nil {
  198. log.Error(err)
  199. return nil, tracerr.Wrap(err)
  200. }
  201. copy(s.zki.FeePlanTokens, feePlanTokens)
  202. }
  203. // Process L2Txs
  204. for i := 0; i < len(l2txs); i++ {
  205. exitIdx, exitAccount, newExit, err := s.processL2Tx(coordIdxsMap, collectedFees, exitTree, &l2txs[i])
  206. if err != nil {
  207. return nil, tracerr.Wrap(err)
  208. }
  209. if s.zki != nil {
  210. l2TxData, err := l2txs[i].L2Tx().BytesDataAvailability(s.zki.Metadata.NLevels)
  211. if err != nil {
  212. return nil, tracerr.Wrap(err)
  213. }
  214. s.zki.Metadata.L2TxsData = append(s.zki.Metadata.L2TxsData, l2TxData)
  215. if s.i < nTx-1 {
  216. // Intermediate States
  217. s.zki.ISOutIdx[s.i] = s.idx.BigInt()
  218. s.zki.ISStateRoot[s.i] = s.mt.Root().BigInt()
  219. s.zki.ISAccFeeOut[s.i] = formatAccumulatedFees(collectedFees, s.zki.FeePlanTokens)
  220. }
  221. if s.i == nTx-1 {
  222. s.zki.ISFinalAccFee = formatAccumulatedFees(collectedFees, s.zki.FeePlanTokens)
  223. }
  224. }
  225. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  226. if exitIdx != nil && exitTree != nil {
  227. exits[s.i] = processedExit{
  228. exit: true,
  229. newExit: newExit,
  230. idx: *exitIdx,
  231. acc: *exitAccount,
  232. }
  233. }
  234. s.i++
  235. }
  236. }
  237. if s.zki != nil {
  238. for i := s.i - 1; i < int(ptc.MaxTx); i++ {
  239. if i < int(ptc.MaxTx)-1 {
  240. s.zki.ISOutIdx[i] = s.idx.BigInt()
  241. s.zki.ISStateRoot[i] = s.mt.Root().BigInt()
  242. }
  243. if i >= s.i {
  244. s.zki.TxCompressedData[i] = new(big.Int).SetBytes(common.SignatureConstantBytes)
  245. }
  246. }
  247. // before computing the Fees txs, set the ISInitStateRootFee
  248. s.zki.ISInitStateRootFee = s.mt.Root().BigInt()
  249. }
  250. // distribute the AccumulatedFees from the processed L2Txs into the
  251. // Coordinator Idxs
  252. iFee := 0
  253. for idx, accumulatedFee := range s.accumulatedFees {
  254. // send the fee to the Idx of the Coordinator for the TokenID
  255. accCoord, err := s.GetAccount(idx)
  256. if err != nil {
  257. log.Errorw("Can not distribute accumulated fees to coordinator account: No coord Idx to receive fee", "idx", idx)
  258. return nil, tracerr.Wrap(err)
  259. }
  260. if s.zki != nil {
  261. s.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
  262. s.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
  263. if babyjub.PointCoordSign(accCoord.PublicKey.X) {
  264. s.zki.Sign3[iFee] = big.NewInt(1)
  265. }
  266. s.zki.Ay3[iFee] = accCoord.PublicKey.Y
  267. s.zki.Balance3[iFee] = accCoord.Balance
  268. s.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
  269. // add Coord Idx to ZKInputs.FeeTxsData
  270. s.zki.FeeIdxs[iFee] = idx.BigInt()
  271. }
  272. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  273. pFee, err := s.UpdateAccount(idx, accCoord)
  274. if err != nil {
  275. log.Error(err)
  276. return nil, tracerr.Wrap(err)
  277. }
  278. if s.zki != nil {
  279. s.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
  280. s.zki.ISStateRootFee[iFee] = s.mt.Root().BigInt()
  281. }
  282. iFee++
  283. }
  284. if s.zki != nil {
  285. for i := len(s.accumulatedFees); i < int(ptc.MaxFeeTx)-1; i++ {
  286. s.zki.ISStateRootFee[i] = s.mt.Root().BigInt()
  287. }
  288. }
  289. if s.typ == TypeTxSelector {
  290. return nil, nil
  291. }
  292. // once all txs processed (exitTree root frozen), for each Exit,
  293. // generate common.ExitInfo data
  294. var exitInfos []common.ExitInfo
  295. for i := 0; i < nTx; i++ {
  296. if !exits[i].exit {
  297. continue
  298. }
  299. exitIdx := exits[i].idx
  300. exitAccount := exits[i].acc
  301. // 0. generate MerkleProof
  302. p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
  303. if err != nil {
  304. return nil, tracerr.Wrap(err)
  305. }
  306. // 1. generate common.ExitInfo
  307. ei := common.ExitInfo{
  308. AccountIdx: exitIdx,
  309. MerkleProof: p,
  310. Balance: exitAccount.Balance,
  311. }
  312. exitInfos = append(exitInfos, ei)
  313. if s.zki != nil {
  314. s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
  315. s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
  316. if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
  317. s.zki.Sign2[i] = big.NewInt(1)
  318. }
  319. s.zki.Ay2[i] = exitAccount.PublicKey.Y
  320. s.zki.Balance2[i] = exitAccount.Balance
  321. s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
  322. for j := 0; j < len(p.Siblings); j++ {
  323. s.zki.Siblings2[i][j] = p.Siblings[j].BigInt()
  324. }
  325. if exits[i].newExit {
  326. s.zki.NewExit[i] = big.NewInt(1)
  327. }
  328. if p.IsOld0 {
  329. s.zki.IsOld0_2[i] = big.NewInt(1)
  330. }
  331. s.zki.OldKey2[i] = p.OldKey.BigInt()
  332. s.zki.OldValue2[i] = p.OldValue.BigInt()
  333. if i < nTx-1 {
  334. s.zki.ISExitRoot[i] = exitTree.Root().BigInt()
  335. }
  336. }
  337. }
  338. if s.typ == TypeSynchronizer {
  339. // return exitInfos, createdAccounts and collectedFees, so Synchronizer will
  340. // be able to store it into HistoryDB for the concrete BatchNum
  341. return &ProcessTxOutput{
  342. ZKInputs: nil,
  343. ExitInfos: exitInfos,
  344. CreatedAccounts: createdAccounts,
  345. CoordinatorIdxsMap: coordIdxsMap,
  346. CollectedFees: collectedFees,
  347. }, nil
  348. }
  349. // compute last ZKInputs parameters
  350. s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
  351. // zki.FeeIdxs = ? // TODO, this will be get from the config file
  352. s.zki.Metadata.NewStateRootRaw = s.mt.Root()
  353. s.zki.Metadata.NewExitRootRaw = exitTree.Root()
  354. // return ZKInputs as the BatchBuilder will return it to forge the Batch
  355. return &ProcessTxOutput{
  356. ZKInputs: s.zki,
  357. ExitInfos: nil,
  358. CreatedAccounts: nil,
  359. CoordinatorIdxsMap: coordIdxsMap,
  360. CollectedFees: nil,
  361. }, nil
  362. }
  363. // getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
  364. // corresponding to the given CoordIdxs and the processed L2Txs
  365. func (s *StateDB) getFeePlanTokens(coordIdxs []common.Idx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
  366. // get Coordinator TokenIDs corresponding to the Idxs where the Fees
  367. // will be sent
  368. coordTokenIDs := make(map[common.TokenID]bool)
  369. for i := 0; i < len(coordIdxs); i++ {
  370. acc, err := s.GetAccount(coordIdxs[i])
  371. if err != nil {
  372. log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error())
  373. return nil, tracerr.Wrap(err)
  374. }
  375. coordTokenIDs[acc.TokenID] = true
  376. }
  377. tokenIDs := make(map[common.TokenID]bool)
  378. for i := 0; i < len(l2txs); i++ {
  379. // as L2Tx does not have parameter TokenID, get it from the
  380. // AccountsDB (in the StateDB)
  381. acc, err := s.GetAccount(l2txs[i].FromIdx)
  382. if err != nil {
  383. log.Errorf("could not get account to determine TokenID of L2Tx: FromIdx %d not found: %s", l2txs[i].FromIdx, err.Error())
  384. return nil, tracerr.Wrap(err)
  385. }
  386. if _, ok := coordTokenIDs[acc.TokenID]; ok {
  387. tokenIDs[acc.TokenID] = true
  388. }
  389. }
  390. var tBI []*big.Int
  391. for t := range tokenIDs {
  392. tBI = append(tBI, t.BigInt())
  393. }
  394. return tBI, nil
  395. }
  396. // processL1Tx process the given L1Tx applying the needed updates to the
  397. // StateDB depending on the transaction Type. It returns the 3 parameters
  398. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  399. // the Exit created a new Leaf in the ExitTree.
  400. // And another *common.Account parameter which contains the created account in
  401. // case that has been a new created account and that the StateDB is of type
  402. // TypeSynchronizer.
  403. func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, *common.Account, error) {
  404. // ZKInputs
  405. if s.zki != nil {
  406. // Txs
  407. var err error
  408. s.zki.TxCompressedData[s.i], err = tx.TxCompressedData()
  409. if err != nil {
  410. log.Error(err)
  411. return nil, nil, false, nil, tracerr.Wrap(err)
  412. }
  413. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  414. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  415. s.zki.OnChain[s.i] = big.NewInt(1)
  416. // L1Txs
  417. depositAmountF16, err := common.NewFloat16(tx.DepositAmount)
  418. if err != nil {
  419. return nil, nil, false, nil, tracerr.Wrap(err)
  420. }
  421. s.zki.DepositAmountF[s.i] = big.NewInt(int64(depositAmountF16))
  422. s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  423. if tx.FromBJJ != nil {
  424. s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
  425. }
  426. // Intermediate States, for all the transactions except for the last one
  427. if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
  428. s.zki.ISOnChain[s.i] = big.NewInt(1)
  429. }
  430. }
  431. switch tx.Type {
  432. case common.TxTypeForceTransfer:
  433. s.computeEffectiveAmounts(tx)
  434. // go to the MT account of sender and receiver, and update balance
  435. // & nonce
  436. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  437. // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
  438. err := s.applyTransfer(nil, nil, tx.Tx(), 0)
  439. if err != nil {
  440. log.Error(err)
  441. return nil, nil, false, nil, tracerr.Wrap(err)
  442. }
  443. case common.TxTypeCreateAccountDeposit:
  444. s.computeEffectiveAmounts(tx)
  445. // add new account to the MT, update balance of the MT account
  446. err := s.applyCreateAccount(tx)
  447. if err != nil {
  448. log.Error(err)
  449. return nil, nil, false, nil, tracerr.Wrap(err)
  450. }
  451. // TODO applyCreateAccount will return the created account,
  452. // which in the case type==TypeSynchronizer will be added to an
  453. // array of created accounts that will be returned
  454. case common.TxTypeDeposit:
  455. s.computeEffectiveAmounts(tx)
  456. // update balance of the MT account
  457. err := s.applyDeposit(tx, false)
  458. if err != nil {
  459. log.Error(err)
  460. return nil, nil, false, nil, tracerr.Wrap(err)
  461. }
  462. case common.TxTypeDepositTransfer:
  463. s.computeEffectiveAmounts(tx)
  464. // update balance in MT account, update balance & nonce of sender
  465. // & receiver
  466. err := s.applyDeposit(tx, true)
  467. if err != nil {
  468. log.Error(err)
  469. return nil, nil, false, nil, tracerr.Wrap(err)
  470. }
  471. case common.TxTypeCreateAccountDepositTransfer:
  472. s.computeEffectiveAmounts(tx)
  473. // add new account to the merkletree, update balance in MT account,
  474. // update balance & nonce of sender & receiver
  475. err := s.applyCreateAccountDepositTransfer(tx)
  476. if err != nil {
  477. log.Error(err)
  478. return nil, nil, false, nil, tracerr.Wrap(err)
  479. }
  480. case common.TxTypeForceExit:
  481. s.computeEffectiveAmounts(tx)
  482. // execute exit flow
  483. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  484. exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx())
  485. if err != nil {
  486. log.Error(err)
  487. return nil, nil, false, nil, tracerr.Wrap(err)
  488. }
  489. return &tx.FromIdx, exitAccount, newExit, nil, nil
  490. default:
  491. }
  492. var createdAccount *common.Account
  493. if s.typ == TypeSynchronizer && (tx.Type == common.TxTypeCreateAccountDeposit || tx.Type == common.TxTypeCreateAccountDepositTransfer) {
  494. var err error
  495. createdAccount, err = s.GetAccount(s.idx)
  496. if err != nil {
  497. log.Error(err)
  498. return nil, nil, false, nil, tracerr.Wrap(err)
  499. }
  500. }
  501. return nil, nil, false, createdAccount, nil
  502. }
  503. // processL2Tx process the given L2Tx applying the needed updates to the
  504. // StateDB depending on the transaction Type. It returns the 3 parameters
  505. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  506. // the Exit created a new Leaf in the ExitTree.
  507. func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
  508. exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  509. var err error
  510. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  511. if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
  512. if s.typ == TypeSynchronizer {
  513. // this should never be reached
  514. log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
  515. return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
  516. }
  517. // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
  518. tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID)
  519. if err != nil {
  520. return nil, nil, false, tracerr.Wrap(err)
  521. }
  522. }
  523. // ZKInputs
  524. if s.zki != nil {
  525. // Txs
  526. s.zki.TxCompressedData[s.i], err = tx.TxCompressedData()
  527. if err != nil {
  528. return nil, nil, false, tracerr.Wrap(err)
  529. }
  530. s.zki.TxCompressedDataV2[s.i], err = tx.TxCompressedDataV2()
  531. if err != nil {
  532. return nil, nil, false, tracerr.Wrap(err)
  533. }
  534. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  535. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  536. // fill AuxToIdx if needed
  537. if tx.ToIdx == 0 {
  538. // use toIdx that can have been filled by tx.ToIdx or
  539. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  540. // from db by ToEthAddr&ToBJJ
  541. s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
  542. }
  543. if tx.ToBJJ != nil {
  544. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  545. }
  546. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  547. s.zki.OnChain[s.i] = big.NewInt(0)
  548. s.zki.NewAccount[s.i] = big.NewInt(0)
  549. // L2Txs
  550. // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
  551. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  552. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  553. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  554. signature, err := tx.Signature.Decompress()
  555. if err != nil {
  556. log.Error(err)
  557. return nil, nil, false, tracerr.Wrap(err)
  558. }
  559. s.zki.S[s.i] = signature.S
  560. s.zki.R8x[s.i] = signature.R8.X
  561. s.zki.R8y[s.i] = signature.R8.Y
  562. }
  563. // if StateDB type==TypeSynchronizer, will need to add Nonce
  564. if s.typ == TypeSynchronizer {
  565. // as type==TypeSynchronizer, always tx.ToIdx!=0
  566. acc, err := s.GetAccount(tx.FromIdx)
  567. if err != nil {
  568. log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
  569. return nil, nil, false, tracerr.Wrap(err)
  570. }
  571. tx.Nonce = acc.Nonce + 1
  572. tx.TokenID = acc.TokenID
  573. }
  574. switch tx.Type {
  575. case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
  576. // go to the MT account of sender and receiver, and update
  577. // balance & nonce
  578. err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
  579. if err != nil {
  580. log.Error(err)
  581. return nil, nil, false, tracerr.Wrap(err)
  582. }
  583. case common.TxTypeExit:
  584. // execute exit flow
  585. exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
  586. if err != nil {
  587. log.Error(err)
  588. return nil, nil, false, tracerr.Wrap(err)
  589. }
  590. return &tx.FromIdx, exitAccount, newExit, nil
  591. default:
  592. }
  593. return nil, nil, false, nil
  594. }
  595. // applyCreateAccount creates a new account in the account of the depositer, it
  596. // stores the deposit value
  597. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  598. account := &common.Account{
  599. TokenID: tx.TokenID,
  600. Nonce: 0,
  601. Balance: tx.EffectiveDepositAmount,
  602. PublicKey: tx.FromBJJ,
  603. EthAddr: tx.FromEthAddr,
  604. }
  605. p, err := s.CreateAccount(common.Idx(s.idx+1), account)
  606. if err != nil {
  607. return tracerr.Wrap(err)
  608. }
  609. if s.zki != nil {
  610. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  611. s.zki.Nonce1[s.i] = big.NewInt(0)
  612. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  613. s.zki.Sign1[s.i] = big.NewInt(1)
  614. }
  615. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  616. s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
  617. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  618. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  619. if p.IsOld0 {
  620. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  621. }
  622. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  623. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  624. s.zki.Metadata.NewLastIdxRaw = s.idx + 1
  625. s.zki.AuxFromIdx[s.i] = common.Idx(s.idx + 1).BigInt()
  626. s.zki.NewAccount[s.i] = big.NewInt(1)
  627. if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
  628. // intermediate states
  629. s.zki.ISOnChain[s.i] = big.NewInt(1)
  630. }
  631. }
  632. s.idx = s.idx + 1
  633. return s.setIdx(s.idx)
  634. }
  635. // applyDeposit updates the balance in the account of the depositer, if
  636. // andTransfer parameter is set to true, the method will also apply the
  637. // Transfer of the L1Tx/DepositTransfer
  638. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  639. // deposit the tx.EffectiveDepositAmount into the sender account
  640. accSender, err := s.GetAccount(tx.FromIdx)
  641. if err != nil {
  642. return tracerr.Wrap(err)
  643. }
  644. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
  645. // in case that the tx is a L1Tx>DepositTransfer
  646. var accReceiver *common.Account
  647. if transfer {
  648. accReceiver, err = s.GetAccount(tx.ToIdx)
  649. if err != nil {
  650. return tracerr.Wrap(err)
  651. }
  652. // subtract amount to the sender
  653. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  654. // add amount to the receiver
  655. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  656. }
  657. // update sender account in localStateDB
  658. p, err := s.UpdateAccount(tx.FromIdx, accSender)
  659. if err != nil {
  660. return tracerr.Wrap(err)
  661. }
  662. if s.zki != nil {
  663. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  664. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  665. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  666. s.zki.Sign1[s.i] = big.NewInt(1)
  667. }
  668. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  669. s.zki.Balance1[s.i] = accSender.Balance
  670. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  671. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  672. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  673. }
  674. // this is done after updating Sender Account (depositer)
  675. if transfer {
  676. // update receiver account in localStateDB
  677. p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  678. if err != nil {
  679. return tracerr.Wrap(err)
  680. }
  681. if s.zki != nil {
  682. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  683. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  684. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  685. s.zki.Sign2[s.i] = big.NewInt(1)
  686. }
  687. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  688. s.zki.Balance2[s.i] = accReceiver.Balance
  689. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  690. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  691. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  692. }
  693. }
  694. return nil
  695. }
  696. // applyTransfer updates the balance & nonce in the account of the sender, and
  697. // the balance in the account of the receiver.
  698. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  699. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  700. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  701. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  702. func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
  703. collectedFees map[common.TokenID]*big.Int,
  704. tx common.Tx, auxToIdx common.Idx) error {
  705. if auxToIdx == common.Idx(0) {
  706. auxToIdx = tx.ToIdx
  707. }
  708. // get sender and receiver accounts from localStateDB
  709. accSender, err := s.GetAccount(tx.FromIdx)
  710. if err != nil {
  711. log.Error(err)
  712. return tracerr.Wrap(err)
  713. }
  714. if s.zki != nil {
  715. // Set the State1 before updating the Sender leaf
  716. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  717. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  718. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  719. s.zki.Sign1[s.i] = big.NewInt(1)
  720. }
  721. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  722. s.zki.Balance1[s.i] = accSender.Balance
  723. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  724. }
  725. if !tx.IsL1 {
  726. // increment nonce
  727. accSender.Nonce++
  728. // compute fee and subtract it from the accSender
  729. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  730. if err != nil {
  731. return tracerr.Wrap(err)
  732. }
  733. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  734. accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
  735. if _, ok := coordIdxsMap[accSender.TokenID]; ok {
  736. accCoord, err := s.GetAccount(coordIdxsMap[accSender.TokenID])
  737. if err != nil {
  738. return tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", accSender.TokenID, coordIdxsMap[accSender.TokenID]))
  739. }
  740. // accumulate the fee for the Coord account
  741. accumulated := s.accumulatedFees[accCoord.Idx]
  742. accumulated.Add(accumulated, fee)
  743. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  744. collected := collectedFees[accCoord.TokenID]
  745. collected.Add(collected, fee)
  746. }
  747. } else {
  748. log.Debugw("No coord Idx to receive fee", "tx", tx)
  749. }
  750. } else {
  751. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  752. }
  753. // update sender account in localStateDB
  754. pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
  755. if err != nil {
  756. log.Error(err)
  757. return tracerr.Wrap(err)
  758. }
  759. if s.zki != nil {
  760. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
  761. }
  762. var accReceiver *common.Account
  763. if tx.FromIdx == auxToIdx {
  764. // if Sender is the Receiver, reuse 'accSender' pointer,
  765. // because in the DB the account for 'auxToIdx' won't be
  766. // updated yet
  767. accReceiver = accSender
  768. } else {
  769. accReceiver, err = s.GetAccount(auxToIdx)
  770. if err != nil {
  771. log.Error(err)
  772. return tracerr.Wrap(err)
  773. }
  774. }
  775. if s.zki != nil {
  776. // Set the State2 before updating the Receiver leaf
  777. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  778. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  779. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  780. s.zki.Sign2[s.i] = big.NewInt(1)
  781. }
  782. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  783. s.zki.Balance2[s.i] = accReceiver.Balance
  784. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  785. }
  786. // add amount-feeAmount to the receiver
  787. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  788. // update receiver account in localStateDB
  789. pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
  790. if err != nil {
  791. return tracerr.Wrap(err)
  792. }
  793. if s.zki != nil {
  794. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  795. }
  796. return nil
  797. }
  798. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  799. // makes a deposit, and performs a transfer to another account
  800. func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  801. accSender := &common.Account{
  802. TokenID: tx.TokenID,
  803. Nonce: 0,
  804. Balance: tx.EffectiveDepositAmount,
  805. PublicKey: tx.FromBJJ,
  806. EthAddr: tx.FromEthAddr,
  807. }
  808. accReceiver, err := s.GetAccount(tx.ToIdx)
  809. if err != nil {
  810. return tracerr.Wrap(err)
  811. }
  812. // subtract amount to the sender
  813. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  814. // add amount to the receiver
  815. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  816. // create Account of the Sender
  817. p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
  818. if err != nil {
  819. return tracerr.Wrap(err)
  820. }
  821. if s.zki != nil {
  822. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  823. s.zki.Nonce1[s.i] = big.NewInt(0)
  824. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  825. s.zki.Sign1[s.i] = big.NewInt(1)
  826. }
  827. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  828. s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
  829. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  830. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  831. if p.IsOld0 {
  832. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  833. }
  834. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  835. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  836. s.zki.Metadata.NewLastIdxRaw = s.idx + 1
  837. s.zki.AuxFromIdx[s.i] = common.Idx(s.idx + 1).BigInt()
  838. s.zki.NewAccount[s.i] = big.NewInt(1)
  839. // intermediate states
  840. s.zki.ISOnChain[s.i] = big.NewInt(1)
  841. }
  842. // update receiver account in localStateDB
  843. p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  844. if err != nil {
  845. return tracerr.Wrap(err)
  846. }
  847. if s.zki != nil {
  848. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  849. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  850. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  851. s.zki.Sign2[s.i] = big.NewInt(1)
  852. }
  853. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  854. s.zki.Balance2[s.i] = accReceiver.Balance
  855. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  856. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  857. }
  858. s.idx = s.idx + 1
  859. return s.setIdx(s.idx)
  860. }
  861. // It returns the ExitAccount and a boolean determining if the Exit created a
  862. // new Leaf in the ExitTree.
  863. func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
  864. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  865. tx common.Tx) (*common.Account, bool, error) {
  866. // 0. subtract tx.Amount from current Account in StateMT
  867. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  868. acc, err := s.GetAccount(tx.FromIdx)
  869. if err != nil {
  870. return nil, false, tracerr.Wrap(err)
  871. }
  872. if !tx.IsL1 {
  873. // increment nonce
  874. acc.Nonce++
  875. // compute fee and subtract it from the accSender
  876. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  877. if err != nil {
  878. return nil, false, tracerr.Wrap(err)
  879. }
  880. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  881. acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
  882. if _, ok := coordIdxsMap[acc.TokenID]; ok {
  883. accCoord, err := s.GetAccount(coordIdxsMap[acc.TokenID])
  884. if err != nil {
  885. return nil, false, tracerr.Wrap(fmt.Errorf("Can not use CoordIdx that does not exist in the tree. TokenID: %d, CoordIdx: %d", acc.TokenID, coordIdxsMap[acc.TokenID]))
  886. }
  887. // accumulate the fee for the Coord account
  888. accumulated := s.accumulatedFees[accCoord.Idx]
  889. accumulated.Add(accumulated, fee)
  890. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  891. collected := collectedFees[accCoord.TokenID]
  892. collected.Add(collected, fee)
  893. }
  894. } else {
  895. log.Debugw("No coord Idx to receive fee", "tx", tx)
  896. }
  897. } else {
  898. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  899. }
  900. p, err := s.UpdateAccount(tx.FromIdx, acc)
  901. if err != nil {
  902. return nil, false, tracerr.Wrap(err)
  903. }
  904. if s.zki != nil {
  905. s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
  906. s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
  907. if babyjub.PointCoordSign(acc.PublicKey.X) {
  908. s.zki.Sign1[s.i] = big.NewInt(1)
  909. }
  910. s.zki.Ay1[s.i] = acc.PublicKey.Y
  911. s.zki.Balance1[s.i] = acc.Balance
  912. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  913. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  914. }
  915. if exitTree == nil {
  916. return nil, false, nil
  917. }
  918. exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  919. if tracerr.Unwrap(err) == db.ErrNotFound {
  920. // 1a. if idx does not exist in exitTree:
  921. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
  922. exitAccount := &common.Account{
  923. TokenID: acc.TokenID,
  924. Nonce: common.Nonce(1),
  925. Balance: tx.Amount,
  926. PublicKey: acc.PublicKey,
  927. EthAddr: acc.EthAddr,
  928. }
  929. _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  930. return exitAccount, true, tracerr.Wrap(err)
  931. } else if err != nil {
  932. return exitAccount, false, tracerr.Wrap(err)
  933. }
  934. // 1b. if idx already exist in exitTree:
  935. // update account, where account.Balance += exitAmount
  936. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  937. _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  938. return exitAccount, false, tracerr.Wrap(err)
  939. }
  940. // computeEffectiveAmounts checks that the L1Tx data is correct
  941. func (s *StateDB) computeEffectiveAmounts(tx *common.L1Tx) {
  942. if !tx.UserOrigin {
  943. // case where the L1Tx is generated by the Coordinator
  944. tx.EffectiveAmount = big.NewInt(0)
  945. tx.EffectiveDepositAmount = big.NewInt(0)
  946. return
  947. }
  948. tx.EffectiveAmount = tx.Amount
  949. tx.EffectiveDepositAmount = tx.DepositAmount
  950. if tx.Type == common.TxTypeCreateAccountDeposit {
  951. return
  952. }
  953. if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
  954. // CreateAccountDepositTransfer case
  955. cmp := tx.DepositAmount.Cmp(tx.Amount)
  956. if cmp == -1 { // DepositAmount<Amount
  957. tx.EffectiveAmount = big.NewInt(0)
  958. return
  959. }
  960. return
  961. }
  962. accSender, err := s.GetAccount(tx.FromIdx)
  963. if err != nil {
  964. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d", tx.FromIdx)
  965. tx.EffectiveDepositAmount = big.NewInt(0)
  966. tx.EffectiveAmount = big.NewInt(0)
  967. return
  968. }
  969. // check that tx.TokenID corresponds to the Sender account TokenID
  970. if tx.TokenID != accSender.TokenID {
  971. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.TokenID (%d) !=sender account TokenID (%d)", tx.TokenID, accSender.TokenID)
  972. tx.EffectiveDepositAmount = big.NewInt(0)
  973. tx.EffectiveAmount = big.NewInt(0)
  974. return
  975. }
  976. // check that Sender has enough balance
  977. bal := accSender.Balance
  978. if tx.DepositAmount != nil {
  979. bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
  980. }
  981. cmp := bal.Cmp(tx.Amount)
  982. if cmp == -1 {
  983. log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
  984. tx.EffectiveAmount = big.NewInt(0)
  985. return
  986. }
  987. // check that the tx.FromEthAddr is the same than the EthAddress of the
  988. // Sender
  989. if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
  990. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.FromEthAddr (%s) must be the same EthAddr of the sender account by the Idx (%s)", tx.FromEthAddr.Hex(), accSender.EthAddr.Hex())
  991. tx.EffectiveDepositAmount = big.NewInt(0)
  992. tx.EffectiveAmount = big.NewInt(0)
  993. return
  994. }
  995. if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
  996. // if transfer is Exit type, there are no more checks
  997. return
  998. }
  999. // check that TokenID is the same for Sender & Receiver account
  1000. accReceiver, err := s.GetAccount(tx.ToIdx)
  1001. if err != nil {
  1002. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
  1003. tx.EffectiveDepositAmount = big.NewInt(0)
  1004. tx.EffectiveAmount = big.NewInt(0)
  1005. return
  1006. }
  1007. if accSender.TokenID != accReceiver.TokenID {
  1008. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accSender.TokenID)
  1009. tx.EffectiveDepositAmount = big.NewInt(0)
  1010. tx.EffectiveAmount = big.NewInt(0)
  1011. return
  1012. }
  1013. }
  1014. // GetIdx returns the stored Idx from the localStateDB, which is the last Idx
  1015. // used for an Account in the localStateDB.
  1016. func (s *StateDB) GetIdx() (common.Idx, error) {
  1017. idxBytes, err := s.DB().Get(keyidx)
  1018. if tracerr.Unwrap(err) == db.ErrNotFound {
  1019. return 0, nil
  1020. }
  1021. if err != nil {
  1022. return 0, tracerr.Wrap(err)
  1023. }
  1024. return common.IdxFromBytes(idxBytes[:])
  1025. }
  1026. // setIdx stores Idx in the localStateDB
  1027. func (s *StateDB) setIdx(idx common.Idx) error {
  1028. tx, err := s.DB().NewTx()
  1029. if err != nil {
  1030. return tracerr.Wrap(err)
  1031. }
  1032. idxBytes, err := idx.Bytes()
  1033. if err != nil {
  1034. return tracerr.Wrap(err)
  1035. }
  1036. err = tx.Put(keyidx, idxBytes[:])
  1037. if err != nil {
  1038. return tracerr.Wrap(err)
  1039. }
  1040. if err := tx.Commit(); err != nil {
  1041. return tracerr.Wrap(err)
  1042. }
  1043. return nil
  1044. }