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.

1151 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. accCoord.Balance = new(big.Int).Add(accCoord.Balance, accumulatedFee)
  261. pFee, err := s.UpdateAccount(idx, accCoord)
  262. if err != nil {
  263. log.Error(err)
  264. return nil, tracerr.Wrap(err)
  265. }
  266. if s.zki != nil {
  267. s.zki.TokenID3[iFee] = accCoord.TokenID.BigInt()
  268. s.zki.Nonce3[iFee] = accCoord.Nonce.BigInt()
  269. if babyjub.PointCoordSign(accCoord.PublicKey.X) {
  270. s.zki.Sign3[iFee] = big.NewInt(1)
  271. }
  272. s.zki.Ay3[iFee] = accCoord.PublicKey.Y
  273. s.zki.Balance3[iFee] = accCoord.Balance
  274. s.zki.EthAddr3[iFee] = common.EthAddrToBigInt(accCoord.EthAddr)
  275. s.zki.Siblings3[iFee] = siblingsToZKInputFormat(pFee.Siblings)
  276. // add Coord Idx to ZKInputs.FeeTxsData
  277. s.zki.FeeIdxs[iFee] = idx.BigInt()
  278. s.zki.ISStateRootFee[iFee] = s.mt.Root().BigInt()
  279. }
  280. iFee++
  281. }
  282. if s.zki != nil {
  283. for i := len(s.accumulatedFees); i < int(ptc.MaxFeeTx)-1; i++ {
  284. s.zki.ISStateRootFee[i] = s.mt.Root().BigInt()
  285. }
  286. }
  287. if s.typ == TypeTxSelector {
  288. return nil, nil
  289. }
  290. // once all txs processed (exitTree root frozen), for each Exit,
  291. // generate common.ExitInfo data
  292. var exitInfos []common.ExitInfo
  293. for i := 0; i < nTx; i++ {
  294. if !exits[i].exit {
  295. continue
  296. }
  297. exitIdx := exits[i].idx
  298. exitAccount := exits[i].acc
  299. // 0. generate MerkleProof
  300. p, err := exitTree.GenerateCircomVerifierProof(exitIdx.BigInt(), nil)
  301. if err != nil {
  302. return nil, tracerr.Wrap(err)
  303. }
  304. // 1. generate common.ExitInfo
  305. ei := common.ExitInfo{
  306. AccountIdx: exitIdx,
  307. MerkleProof: p,
  308. Balance: exitAccount.Balance,
  309. }
  310. exitInfos = append(exitInfos, ei)
  311. if s.zki != nil {
  312. s.zki.TokenID2[i] = exitAccount.TokenID.BigInt()
  313. s.zki.Nonce2[i] = exitAccount.Nonce.BigInt()
  314. if babyjub.PointCoordSign(exitAccount.PublicKey.X) {
  315. s.zki.Sign2[i] = big.NewInt(1)
  316. }
  317. s.zki.Ay2[i] = exitAccount.PublicKey.Y
  318. s.zki.Balance2[i] = exitAccount.Balance
  319. s.zki.EthAddr2[i] = common.EthAddrToBigInt(exitAccount.EthAddr)
  320. for j := 0; j < len(p.Siblings); j++ {
  321. s.zki.Siblings2[i][j] = p.Siblings[j].BigInt()
  322. }
  323. if exits[i].newExit {
  324. s.zki.NewExit[i] = big.NewInt(1)
  325. }
  326. if p.IsOld0 {
  327. s.zki.IsOld0_2[i] = big.NewInt(1)
  328. }
  329. s.zki.OldKey2[i] = p.OldKey.BigInt()
  330. s.zki.OldValue2[i] = p.OldValue.BigInt()
  331. if i < nTx-1 {
  332. s.zki.ISExitRoot[i] = exitTree.Root().BigInt()
  333. }
  334. }
  335. }
  336. if s.typ == TypeSynchronizer {
  337. // return exitInfos, createdAccounts and collectedFees, so Synchronizer will
  338. // be able to store it into HistoryDB for the concrete BatchNum
  339. return &ProcessTxOutput{
  340. ZKInputs: nil,
  341. ExitInfos: exitInfos,
  342. CreatedAccounts: createdAccounts,
  343. CoordinatorIdxsMap: coordIdxsMap,
  344. CollectedFees: collectedFees,
  345. }, nil
  346. }
  347. // compute last ZKInputs parameters
  348. s.zki.GlobalChainID = big.NewInt(0) // TODO, 0: ethereum, this will be get from config file
  349. // zki.FeeIdxs = ? // TODO, this will be get from the config file
  350. s.zki.Metadata.NewStateRootRaw = s.mt.Root()
  351. s.zki.Metadata.NewExitRootRaw = exitTree.Root()
  352. // return ZKInputs as the BatchBuilder will return it to forge the Batch
  353. return &ProcessTxOutput{
  354. ZKInputs: s.zki,
  355. ExitInfos: nil,
  356. CreatedAccounts: nil,
  357. CoordinatorIdxsMap: coordIdxsMap,
  358. CollectedFees: nil,
  359. }, nil
  360. }
  361. // getFeePlanTokens returns an array of *big.Int containing a list of tokenIDs
  362. // corresponding to the given CoordIdxs and the processed L2Txs
  363. func (s *StateDB) getFeePlanTokens(coordIdxs []common.Idx, l2txs []common.PoolL2Tx) ([]*big.Int, error) {
  364. // get Coordinator TokenIDs corresponding to the Idxs where the Fees
  365. // will be sent
  366. coordTokenIDs := make(map[common.TokenID]bool)
  367. for i := 0; i < len(coordIdxs); i++ {
  368. acc, err := s.GetAccount(coordIdxs[i])
  369. if err != nil {
  370. log.Errorf("could not get account to determine TokenID of CoordIdx %d not found: %s", coordIdxs[i], err.Error())
  371. return nil, tracerr.Wrap(err)
  372. }
  373. coordTokenIDs[acc.TokenID] = true
  374. }
  375. tokenIDs := make(map[common.TokenID]bool)
  376. for i := 0; i < len(l2txs); i++ {
  377. // as L2Tx does not have parameter TokenID, get it from the
  378. // AccountsDB (in the StateDB)
  379. acc, err := s.GetAccount(l2txs[i].FromIdx)
  380. if err != nil {
  381. log.Errorf("could not get account to determine TokenID of L2Tx: FromIdx %d not found: %s", l2txs[i].FromIdx, err.Error())
  382. return nil, tracerr.Wrap(err)
  383. }
  384. if _, ok := coordTokenIDs[acc.TokenID]; ok {
  385. tokenIDs[acc.TokenID] = true
  386. }
  387. }
  388. var tBI []*big.Int
  389. for t := range tokenIDs {
  390. tBI = append(tBI, t.BigInt())
  391. }
  392. return tBI, nil
  393. }
  394. // processL1Tx process the given L1Tx applying the needed updates to the
  395. // StateDB depending on the transaction Type. It returns the 3 parameters
  396. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  397. // the Exit created a new Leaf in the ExitTree.
  398. // And another *common.Account parameter which contains the created account in
  399. // case that has been a new created account and that the StateDB is of type
  400. // TypeSynchronizer.
  401. func (s *StateDB) processL1Tx(exitTree *merkletree.MerkleTree, tx *common.L1Tx) (*common.Idx, *common.Account, bool, *common.Account, error) {
  402. // ZKInputs
  403. if s.zki != nil {
  404. // Txs
  405. var err error
  406. s.zki.TxCompressedData[s.i], err = tx.TxCompressedData()
  407. if err != nil {
  408. log.Error(err)
  409. return nil, nil, false, nil, tracerr.Wrap(err)
  410. }
  411. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  412. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  413. s.zki.OnChain[s.i] = big.NewInt(1)
  414. // L1Txs
  415. depositAmountF16, err := common.NewFloat16(tx.DepositAmount)
  416. if err != nil {
  417. return nil, nil, false, nil, tracerr.Wrap(err)
  418. }
  419. s.zki.DepositAmountF[s.i] = big.NewInt(int64(depositAmountF16))
  420. s.zki.FromEthAddr[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  421. if tx.FromBJJ != nil {
  422. s.zki.FromBJJCompressed[s.i] = BJJCompressedTo256BigInts(tx.FromBJJ.Compress())
  423. }
  424. // Intermediate States, for all the transactions except for the last one
  425. if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
  426. s.zki.ISOnChain[s.i] = big.NewInt(1)
  427. }
  428. }
  429. switch tx.Type {
  430. case common.TxTypeForceTransfer:
  431. s.computeEffectiveAmounts(tx)
  432. // go to the MT account of sender and receiver, and update balance
  433. // & nonce
  434. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  435. // 0 for the parameter toIdx, as at L1Tx ToIdx can only be 0 in the Deposit type case.
  436. err := s.applyTransfer(nil, nil, tx.Tx(), 0)
  437. if err != nil {
  438. log.Error(err)
  439. return nil, nil, false, nil, tracerr.Wrap(err)
  440. }
  441. case common.TxTypeCreateAccountDeposit:
  442. s.computeEffectiveAmounts(tx)
  443. // add new account to the MT, update balance of the MT account
  444. err := s.applyCreateAccount(tx)
  445. if err != nil {
  446. log.Error(err)
  447. return nil, nil, false, nil, tracerr.Wrap(err)
  448. }
  449. // TODO applyCreateAccount will return the created account,
  450. // which in the case type==TypeSynchronizer will be added to an
  451. // array of created accounts that will be returned
  452. case common.TxTypeDeposit:
  453. s.computeEffectiveAmounts(tx)
  454. // update balance of the MT account
  455. err := s.applyDeposit(tx, false)
  456. if err != nil {
  457. log.Error(err)
  458. return nil, nil, false, nil, tracerr.Wrap(err)
  459. }
  460. case common.TxTypeDepositTransfer:
  461. s.computeEffectiveAmounts(tx)
  462. // update balance in MT account, update balance & nonce of sender
  463. // & receiver
  464. err := s.applyDeposit(tx, true)
  465. if err != nil {
  466. log.Error(err)
  467. return nil, nil, false, nil, tracerr.Wrap(err)
  468. }
  469. case common.TxTypeCreateAccountDepositTransfer:
  470. s.computeEffectiveAmounts(tx)
  471. // add new account to the merkletree, update balance in MT account,
  472. // update balance & nonce of sender & receiver
  473. err := s.applyCreateAccountDepositTransfer(tx)
  474. if err != nil {
  475. log.Error(err)
  476. return nil, nil, false, nil, tracerr.Wrap(err)
  477. }
  478. case common.TxTypeForceExit:
  479. s.computeEffectiveAmounts(tx)
  480. // execute exit flow
  481. // coordIdxsMap is 'nil', as at L1Txs there is no L2 fees
  482. exitAccount, newExit, err := s.applyExit(nil, nil, exitTree, tx.Tx())
  483. if err != nil {
  484. log.Error(err)
  485. return nil, nil, false, nil, tracerr.Wrap(err)
  486. }
  487. return &tx.FromIdx, exitAccount, newExit, nil, nil
  488. default:
  489. }
  490. var createdAccount *common.Account
  491. if s.typ == TypeSynchronizer && (tx.Type == common.TxTypeCreateAccountDeposit || tx.Type == common.TxTypeCreateAccountDepositTransfer) {
  492. var err error
  493. createdAccount, err = s.GetAccount(s.idx)
  494. if err != nil {
  495. log.Error(err)
  496. return nil, nil, false, nil, tracerr.Wrap(err)
  497. }
  498. }
  499. return nil, nil, false, createdAccount, nil
  500. }
  501. // processL2Tx process the given L2Tx applying the needed updates to the
  502. // StateDB depending on the transaction Type. It returns the 3 parameters
  503. // related to the Exit (in case of): Idx, ExitAccount, boolean determining if
  504. // the Exit created a new Leaf in the ExitTree.
  505. func (s *StateDB) processL2Tx(coordIdxsMap map[common.TokenID]common.Idx, collectedFees map[common.TokenID]*big.Int,
  506. exitTree *merkletree.MerkleTree, tx *common.PoolL2Tx) (*common.Idx, *common.Account, bool, error) {
  507. var err error
  508. // if tx.ToIdx==0, get toIdx by ToEthAddr or ToBJJ
  509. if tx.ToIdx == common.Idx(0) && tx.AuxToIdx == common.Idx(0) {
  510. if s.typ == TypeSynchronizer {
  511. // this should never be reached
  512. log.Error("WARNING: In StateDB with Synchronizer mode L2.ToIdx can't be 0")
  513. return nil, nil, false, tracerr.Wrap(fmt.Errorf("In StateDB with Synchronizer mode L2.ToIdx can't be 0"))
  514. }
  515. // case when tx.Type== common.TxTypeTransferToEthAddr or common.TxTypeTransferToBJJ
  516. tx.AuxToIdx, err = s.GetIdxByEthAddrBJJ(tx.ToEthAddr, tx.ToBJJ, tx.TokenID)
  517. if err != nil {
  518. return nil, nil, false, tracerr.Wrap(err)
  519. }
  520. }
  521. // ZKInputs
  522. if s.zki != nil {
  523. // Txs
  524. s.zki.TxCompressedData[s.i], err = tx.TxCompressedData()
  525. if err != nil {
  526. return nil, nil, false, tracerr.Wrap(err)
  527. }
  528. s.zki.TxCompressedDataV2[s.i], err = tx.TxCompressedDataV2()
  529. if err != nil {
  530. return nil, nil, false, tracerr.Wrap(err)
  531. }
  532. s.zki.FromIdx[s.i] = tx.FromIdx.BigInt()
  533. s.zki.ToIdx[s.i] = tx.ToIdx.BigInt()
  534. // fill AuxToIdx if needed
  535. if tx.ToIdx == 0 {
  536. // use toIdx that can have been filled by tx.ToIdx or
  537. // if tx.Idx==0 (this case), toIdx is filled by the Idx
  538. // from db by ToEthAddr&ToBJJ
  539. s.zki.AuxToIdx[s.i] = tx.AuxToIdx.BigInt()
  540. }
  541. if tx.ToBJJ != nil {
  542. s.zki.ToBJJAy[s.i] = tx.ToBJJ.Y
  543. }
  544. s.zki.ToEthAddr[s.i] = common.EthAddrToBigInt(tx.ToEthAddr)
  545. s.zki.OnChain[s.i] = big.NewInt(0)
  546. s.zki.NewAccount[s.i] = big.NewInt(0)
  547. // L2Txs
  548. // s.zki.RqOffset[s.i] = // TODO Rq once TxSelector is ready
  549. // s.zki.RqTxCompressedDataV2[s.i] = // TODO
  550. // s.zki.RqToEthAddr[s.i] = common.EthAddrToBigInt(tx.RqToEthAddr) // TODO
  551. // s.zki.RqToBJJAy[s.i] = tx.ToBJJ.Y // TODO
  552. signature, err := tx.Signature.Decompress()
  553. if err != nil {
  554. log.Error(err)
  555. return nil, nil, false, tracerr.Wrap(err)
  556. }
  557. s.zki.S[s.i] = signature.S
  558. s.zki.R8x[s.i] = signature.R8.X
  559. s.zki.R8y[s.i] = signature.R8.Y
  560. }
  561. // if StateDB type==TypeSynchronizer, will need to add Nonce
  562. if s.typ == TypeSynchronizer {
  563. // as type==TypeSynchronizer, always tx.ToIdx!=0
  564. acc, err := s.GetAccount(tx.FromIdx)
  565. if err != nil {
  566. log.Errorw("GetAccount", "fromIdx", tx.FromIdx, "err", err)
  567. return nil, nil, false, tracerr.Wrap(err)
  568. }
  569. tx.Nonce = acc.Nonce + 1
  570. tx.TokenID = acc.TokenID
  571. }
  572. switch tx.Type {
  573. case common.TxTypeTransfer, common.TxTypeTransferToEthAddr, common.TxTypeTransferToBJJ:
  574. // go to the MT account of sender and receiver, and update
  575. // balance & nonce
  576. err = s.applyTransfer(coordIdxsMap, collectedFees, tx.Tx(), tx.AuxToIdx)
  577. if err != nil {
  578. log.Error(err)
  579. return nil, nil, false, tracerr.Wrap(err)
  580. }
  581. case common.TxTypeExit:
  582. // execute exit flow
  583. exitAccount, newExit, err := s.applyExit(coordIdxsMap, collectedFees, exitTree, tx.Tx())
  584. if err != nil {
  585. log.Error(err)
  586. return nil, nil, false, tracerr.Wrap(err)
  587. }
  588. return &tx.FromIdx, exitAccount, newExit, nil
  589. default:
  590. }
  591. return nil, nil, false, nil
  592. }
  593. // applyCreateAccount creates a new account in the account of the depositer, it
  594. // stores the deposit value
  595. func (s *StateDB) applyCreateAccount(tx *common.L1Tx) error {
  596. account := &common.Account{
  597. TokenID: tx.TokenID,
  598. Nonce: 0,
  599. Balance: tx.EffectiveDepositAmount,
  600. PublicKey: tx.FromBJJ,
  601. EthAddr: tx.FromEthAddr,
  602. }
  603. p, err := s.CreateAccount(common.Idx(s.idx+1), account)
  604. if err != nil {
  605. return tracerr.Wrap(err)
  606. }
  607. if s.zki != nil {
  608. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  609. s.zki.Nonce1[s.i] = big.NewInt(0)
  610. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  611. s.zki.Sign1[s.i] = big.NewInt(1)
  612. }
  613. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  614. s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
  615. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  616. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  617. if p.IsOld0 {
  618. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  619. }
  620. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  621. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  622. s.zki.Metadata.NewLastIdxRaw = s.idx + 1
  623. s.zki.AuxFromIdx[s.i] = common.Idx(s.idx + 1).BigInt()
  624. s.zki.NewAccount[s.i] = big.NewInt(1)
  625. if s.i < len(s.zki.ISOnChain) { // len(s.zki.ISOnChain) == nTx
  626. // intermediate states
  627. s.zki.ISOnChain[s.i] = big.NewInt(1)
  628. }
  629. }
  630. s.idx = s.idx + 1
  631. return s.setIdx(s.idx)
  632. }
  633. // applyDeposit updates the balance in the account of the depositer, if
  634. // andTransfer parameter is set to true, the method will also apply the
  635. // Transfer of the L1Tx/DepositTransfer
  636. func (s *StateDB) applyDeposit(tx *common.L1Tx, transfer bool) error {
  637. // deposit the tx.EffectiveDepositAmount into the sender account
  638. accSender, err := s.GetAccount(tx.FromIdx)
  639. if err != nil {
  640. return tracerr.Wrap(err)
  641. }
  642. accSender.Balance = new(big.Int).Add(accSender.Balance, tx.EffectiveDepositAmount)
  643. // in case that the tx is a L1Tx>DepositTransfer
  644. var accReceiver *common.Account
  645. if transfer {
  646. accReceiver, err = s.GetAccount(tx.ToIdx)
  647. if err != nil {
  648. return tracerr.Wrap(err)
  649. }
  650. // subtract amount to the sender
  651. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  652. // add amount to the receiver
  653. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  654. }
  655. // update sender account in localStateDB
  656. p, err := s.UpdateAccount(tx.FromIdx, accSender)
  657. if err != nil {
  658. return tracerr.Wrap(err)
  659. }
  660. if s.zki != nil {
  661. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  662. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  663. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  664. s.zki.Sign1[s.i] = big.NewInt(1)
  665. }
  666. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  667. s.zki.Balance1[s.i] = accSender.Balance
  668. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  669. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  670. // IsOld0_1, OldKey1, OldValue1 not needed as this is not an insert
  671. }
  672. // this is done after updating Sender Account (depositer)
  673. if transfer {
  674. // update receiver account in localStateDB
  675. p, err := s.UpdateAccount(tx.ToIdx, accReceiver)
  676. if err != nil {
  677. return tracerr.Wrap(err)
  678. }
  679. if s.zki != nil {
  680. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  681. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  682. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  683. s.zki.Sign2[s.i] = big.NewInt(1)
  684. }
  685. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  686. s.zki.Balance2[s.i] = accReceiver.Balance
  687. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  688. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  689. // IsOld0_2, OldKey2, OldValue2 not needed as this is not an insert
  690. }
  691. }
  692. return nil
  693. }
  694. // applyTransfer updates the balance & nonce in the account of the sender, and
  695. // the balance in the account of the receiver.
  696. // Parameter 'toIdx' should be at 0 if the tx already has tx.ToIdx!=0, if
  697. // tx.ToIdx==0, then toIdx!=0, and will be used the toIdx parameter as Idx of
  698. // the receiver. This parameter is used when the tx.ToIdx is not specified and
  699. // the real ToIdx is found trhrough the ToEthAddr or ToBJJ.
  700. func (s *StateDB) applyTransfer(coordIdxsMap map[common.TokenID]common.Idx,
  701. collectedFees map[common.TokenID]*big.Int,
  702. tx common.Tx, auxToIdx common.Idx) error {
  703. if auxToIdx == common.Idx(0) {
  704. auxToIdx = tx.ToIdx
  705. }
  706. // get sender and receiver accounts from localStateDB
  707. accSender, err := s.GetAccount(tx.FromIdx)
  708. if err != nil {
  709. log.Error(err)
  710. return tracerr.Wrap(err)
  711. }
  712. if s.zki != nil {
  713. // Set the State1 before updating the Sender leaf
  714. s.zki.TokenID1[s.i] = accSender.TokenID.BigInt()
  715. s.zki.Nonce1[s.i] = accSender.Nonce.BigInt()
  716. if babyjub.PointCoordSign(accSender.PublicKey.X) {
  717. s.zki.Sign1[s.i] = big.NewInt(1)
  718. }
  719. s.zki.Ay1[s.i] = accSender.PublicKey.Y
  720. s.zki.Balance1[s.i] = accSender.Balance
  721. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(accSender.EthAddr)
  722. }
  723. if !tx.IsL1 {
  724. // increment nonce
  725. accSender.Nonce++
  726. // compute fee and subtract it from the accSender
  727. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  728. if err != nil {
  729. return tracerr.Wrap(err)
  730. }
  731. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  732. accSender.Balance = new(big.Int).Sub(accSender.Balance, feeAndAmount)
  733. if _, ok := coordIdxsMap[accSender.TokenID]; ok {
  734. accCoord, err := s.GetAccount(coordIdxsMap[accSender.TokenID])
  735. if err != nil {
  736. 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]))
  737. }
  738. // accumulate the fee for the Coord account
  739. accumulated := s.accumulatedFees[accCoord.Idx]
  740. accumulated.Add(accumulated, fee)
  741. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  742. collected := collectedFees[accCoord.TokenID]
  743. collected.Add(collected, fee)
  744. }
  745. } else {
  746. log.Debugw("No coord Idx to receive fee", "tx", tx)
  747. }
  748. } else {
  749. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.Amount)
  750. }
  751. // update sender account in localStateDB
  752. pSender, err := s.UpdateAccount(tx.FromIdx, accSender)
  753. if err != nil {
  754. log.Error(err)
  755. return tracerr.Wrap(err)
  756. }
  757. if s.zki != nil {
  758. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(pSender.Siblings)
  759. }
  760. var accReceiver *common.Account
  761. if tx.FromIdx == auxToIdx {
  762. // if Sender is the Receiver, reuse 'accSender' pointer,
  763. // because in the DB the account for 'auxToIdx' won't be
  764. // updated yet
  765. accReceiver = accSender
  766. } else {
  767. accReceiver, err = s.GetAccount(auxToIdx)
  768. if err != nil {
  769. log.Error(err)
  770. return tracerr.Wrap(err)
  771. }
  772. }
  773. if s.zki != nil {
  774. // Set the State2 before updating the Receiver leaf
  775. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  776. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  777. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  778. s.zki.Sign2[s.i] = big.NewInt(1)
  779. }
  780. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  781. s.zki.Balance2[s.i] = accReceiver.Balance
  782. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  783. }
  784. // add amount-feeAmount to the receiver
  785. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.Amount)
  786. // update receiver account in localStateDB
  787. pReceiver, err := s.UpdateAccount(auxToIdx, accReceiver)
  788. if err != nil {
  789. return tracerr.Wrap(err)
  790. }
  791. if s.zki != nil {
  792. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(pReceiver.Siblings)
  793. }
  794. return nil
  795. }
  796. // applyCreateAccountDepositTransfer, in a single tx, creates a new account,
  797. // makes a deposit, and performs a transfer to another account
  798. func (s *StateDB) applyCreateAccountDepositTransfer(tx *common.L1Tx) error {
  799. accSender := &common.Account{
  800. TokenID: tx.TokenID,
  801. Nonce: 0,
  802. Balance: tx.EffectiveDepositAmount,
  803. PublicKey: tx.FromBJJ,
  804. EthAddr: tx.FromEthAddr,
  805. }
  806. accReceiver, err := s.GetAccount(tx.ToIdx)
  807. if err != nil {
  808. return tracerr.Wrap(err)
  809. }
  810. // subtract amount to the sender
  811. accSender.Balance = new(big.Int).Sub(accSender.Balance, tx.EffectiveAmount)
  812. // add amount to the receiver
  813. accReceiver.Balance = new(big.Int).Add(accReceiver.Balance, tx.EffectiveAmount)
  814. // create Account of the Sender
  815. p, err := s.CreateAccount(common.Idx(s.idx+1), accSender)
  816. if err != nil {
  817. return tracerr.Wrap(err)
  818. }
  819. if s.zki != nil {
  820. s.zki.TokenID1[s.i] = tx.TokenID.BigInt()
  821. s.zki.Nonce1[s.i] = big.NewInt(0)
  822. if babyjub.PointCoordSign(tx.FromBJJ.X) {
  823. s.zki.Sign1[s.i] = big.NewInt(1)
  824. }
  825. s.zki.Ay1[s.i] = tx.FromBJJ.Y
  826. s.zki.Balance1[s.i] = tx.EffectiveDepositAmount
  827. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(tx.FromEthAddr)
  828. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  829. if p.IsOld0 {
  830. s.zki.IsOld0_1[s.i] = big.NewInt(1)
  831. }
  832. s.zki.OldKey1[s.i] = p.OldKey.BigInt()
  833. s.zki.OldValue1[s.i] = p.OldValue.BigInt()
  834. s.zki.Metadata.NewLastIdxRaw = s.idx + 1
  835. s.zki.AuxFromIdx[s.i] = common.Idx(s.idx + 1).BigInt()
  836. s.zki.NewAccount[s.i] = big.NewInt(1)
  837. // intermediate states
  838. s.zki.ISOnChain[s.i] = big.NewInt(1)
  839. }
  840. // update receiver account in localStateDB
  841. p, err = s.UpdateAccount(tx.ToIdx, accReceiver)
  842. if err != nil {
  843. return tracerr.Wrap(err)
  844. }
  845. if s.zki != nil {
  846. s.zki.TokenID2[s.i] = accReceiver.TokenID.BigInt()
  847. s.zki.Nonce2[s.i] = accReceiver.Nonce.BigInt()
  848. if babyjub.PointCoordSign(accReceiver.PublicKey.X) {
  849. s.zki.Sign2[s.i] = big.NewInt(1)
  850. }
  851. s.zki.Ay2[s.i] = accReceiver.PublicKey.Y
  852. s.zki.Balance2[s.i] = accReceiver.Balance
  853. s.zki.EthAddr2[s.i] = common.EthAddrToBigInt(accReceiver.EthAddr)
  854. s.zki.Siblings2[s.i] = siblingsToZKInputFormat(p.Siblings)
  855. }
  856. s.idx = s.idx + 1
  857. return s.setIdx(s.idx)
  858. }
  859. // It returns the ExitAccount and a boolean determining if the Exit created a
  860. // new Leaf in the ExitTree.
  861. func (s *StateDB) applyExit(coordIdxsMap map[common.TokenID]common.Idx,
  862. collectedFees map[common.TokenID]*big.Int, exitTree *merkletree.MerkleTree,
  863. tx common.Tx) (*common.Account, bool, error) {
  864. // 0. subtract tx.Amount from current Account in StateMT
  865. // add the tx.Amount into the Account (tx.FromIdx) in the ExitMT
  866. acc, err := s.GetAccount(tx.FromIdx)
  867. if err != nil {
  868. return nil, false, tracerr.Wrap(err)
  869. }
  870. if !tx.IsL1 {
  871. // increment nonce
  872. acc.Nonce++
  873. // compute fee and subtract it from the accSender
  874. fee, err := common.CalcFeeAmount(tx.Amount, *tx.Fee)
  875. if err != nil {
  876. return nil, false, tracerr.Wrap(err)
  877. }
  878. feeAndAmount := new(big.Int).Add(tx.Amount, fee)
  879. acc.Balance = new(big.Int).Sub(acc.Balance, feeAndAmount)
  880. if _, ok := coordIdxsMap[acc.TokenID]; ok {
  881. accCoord, err := s.GetAccount(coordIdxsMap[acc.TokenID])
  882. if err != nil {
  883. 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]))
  884. }
  885. // accumulate the fee for the Coord account
  886. accumulated := s.accumulatedFees[accCoord.Idx]
  887. accumulated.Add(accumulated, fee)
  888. if s.typ == TypeSynchronizer || s.typ == TypeBatchBuilder {
  889. collected := collectedFees[accCoord.TokenID]
  890. collected.Add(collected, fee)
  891. }
  892. } else {
  893. log.Debugw("No coord Idx to receive fee", "tx", tx)
  894. }
  895. } else {
  896. acc.Balance = new(big.Int).Sub(acc.Balance, tx.Amount)
  897. }
  898. p, err := s.UpdateAccount(tx.FromIdx, acc)
  899. if err != nil {
  900. return nil, false, tracerr.Wrap(err)
  901. }
  902. if s.zki != nil {
  903. s.zki.TokenID1[s.i] = acc.TokenID.BigInt()
  904. s.zki.Nonce1[s.i] = acc.Nonce.BigInt()
  905. if babyjub.PointCoordSign(acc.PublicKey.X) {
  906. s.zki.Sign1[s.i] = big.NewInt(1)
  907. }
  908. s.zki.Ay1[s.i] = acc.PublicKey.Y
  909. s.zki.Balance1[s.i] = acc.Balance
  910. s.zki.EthAddr1[s.i] = common.EthAddrToBigInt(acc.EthAddr)
  911. s.zki.Siblings1[s.i] = siblingsToZKInputFormat(p.Siblings)
  912. }
  913. if exitTree == nil {
  914. return nil, false, nil
  915. }
  916. exitAccount, err := getAccountInTreeDB(exitTree.DB(), tx.FromIdx)
  917. if tracerr.Unwrap(err) == db.ErrNotFound {
  918. // 1a. if idx does not exist in exitTree:
  919. // add new leaf 'ExitTreeLeaf', where ExitTreeLeaf.Balance = exitAmount (exitAmount=tx.Amount)
  920. exitAccount := &common.Account{
  921. TokenID: acc.TokenID,
  922. Nonce: common.Nonce(1),
  923. Balance: tx.Amount,
  924. PublicKey: acc.PublicKey,
  925. EthAddr: acc.EthAddr,
  926. }
  927. _, err = createAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  928. return exitAccount, true, tracerr.Wrap(err)
  929. } else if err != nil {
  930. return exitAccount, false, tracerr.Wrap(err)
  931. }
  932. // 1b. if idx already exist in exitTree:
  933. // update account, where account.Balance += exitAmount
  934. exitAccount.Balance = new(big.Int).Add(exitAccount.Balance, tx.Amount)
  935. _, err = updateAccountInTreeDB(exitTree.DB(), exitTree, tx.FromIdx, exitAccount)
  936. return exitAccount, false, tracerr.Wrap(err)
  937. }
  938. // computeEffectiveAmounts checks that the L1Tx data is correct
  939. func (s *StateDB) computeEffectiveAmounts(tx *common.L1Tx) {
  940. if !tx.UserOrigin {
  941. // case where the L1Tx is generated by the Coordinator
  942. tx.EffectiveAmount = big.NewInt(0)
  943. tx.EffectiveDepositAmount = big.NewInt(0)
  944. return
  945. }
  946. tx.EffectiveAmount = tx.Amount
  947. tx.EffectiveDepositAmount = tx.DepositAmount
  948. if tx.Type == common.TxTypeCreateAccountDeposit {
  949. return
  950. }
  951. if tx.ToIdx >= common.UserThreshold && tx.FromIdx == common.Idx(0) {
  952. // CreateAccountDepositTransfer case
  953. cmp := tx.DepositAmount.Cmp(tx.Amount)
  954. if cmp == -1 { // DepositAmount<Amount
  955. tx.EffectiveAmount = big.NewInt(0)
  956. return
  957. }
  958. return
  959. }
  960. accSender, err := s.GetAccount(tx.FromIdx)
  961. if err != nil {
  962. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.FromIdx: %d", tx.FromIdx)
  963. tx.EffectiveDepositAmount = big.NewInt(0)
  964. tx.EffectiveAmount = big.NewInt(0)
  965. return
  966. }
  967. // check that tx.TokenID corresponds to the Sender account TokenID
  968. if tx.TokenID != accSender.TokenID {
  969. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: tx.TokenID (%d) !=sender account TokenID (%d)", tx.TokenID, accSender.TokenID)
  970. tx.EffectiveDepositAmount = big.NewInt(0)
  971. tx.EffectiveAmount = big.NewInt(0)
  972. return
  973. }
  974. // check that Sender has enough balance
  975. bal := accSender.Balance
  976. if tx.DepositAmount != nil {
  977. bal = new(big.Int).Add(bal, tx.EffectiveDepositAmount)
  978. }
  979. cmp := bal.Cmp(tx.Amount)
  980. if cmp == -1 {
  981. log.Debugf("EffectiveAmount = 0: Not enough funds (%s<%s)", bal.String(), tx.Amount.String())
  982. tx.EffectiveAmount = big.NewInt(0)
  983. return
  984. }
  985. // check that the tx.FromEthAddr is the same than the EthAddress of the
  986. // Sender
  987. if !bytes.Equal(tx.FromEthAddr.Bytes(), accSender.EthAddr.Bytes()) {
  988. 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())
  989. tx.EffectiveDepositAmount = big.NewInt(0)
  990. tx.EffectiveAmount = big.NewInt(0)
  991. return
  992. }
  993. if tx.ToIdx == common.Idx(1) || tx.ToIdx == common.Idx(0) {
  994. // if transfer is Exit type, there are no more checks
  995. return
  996. }
  997. // check that TokenID is the same for Sender & Receiver account
  998. accReceiver, err := s.GetAccount(tx.ToIdx)
  999. if err != nil {
  1000. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: can not get account for tx.ToIdx: %d", tx.ToIdx)
  1001. tx.EffectiveDepositAmount = big.NewInt(0)
  1002. tx.EffectiveAmount = big.NewInt(0)
  1003. return
  1004. }
  1005. if accSender.TokenID != accReceiver.TokenID {
  1006. log.Debugf("EffectiveAmount & EffectiveDepositAmount = 0: sender account TokenID (%d) != receiver account TokenID (%d)", tx.TokenID, accSender.TokenID)
  1007. tx.EffectiveDepositAmount = big.NewInt(0)
  1008. tx.EffectiveAmount = big.NewInt(0)
  1009. return
  1010. }
  1011. }
  1012. // getIdx returns the stored Idx from the localStateDB, which is the last Idx
  1013. // used for an Account in the localStateDB.
  1014. func (s *StateDB) getIdx() (common.Idx, error) {
  1015. idxBytes, err := s.DB().Get(keyidx)
  1016. if tracerr.Unwrap(err) == db.ErrNotFound {
  1017. return 0, nil
  1018. }
  1019. if err != nil {
  1020. return 0, tracerr.Wrap(err)
  1021. }
  1022. return common.IdxFromBytes(idxBytes[:])
  1023. }
  1024. // setIdx stores Idx in the localStateDB
  1025. func (s *StateDB) setIdx(idx common.Idx) error {
  1026. tx, err := s.DB().NewTx()
  1027. if err != nil {
  1028. return tracerr.Wrap(err)
  1029. }
  1030. idxBytes, err := idx.Bytes()
  1031. if err != nil {
  1032. return tracerr.Wrap(err)
  1033. }
  1034. err = tx.Put(keyidx, idxBytes[:])
  1035. if err != nil {
  1036. return tracerr.Wrap(err)
  1037. }
  1038. if err := tx.Commit(); err != nil {
  1039. return tracerr.Wrap(err)
  1040. }
  1041. return nil
  1042. }