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.

85 lines
2.1 KiB

  1. package batchbuilder
  2. import (
  3. "math/big"
  4. "github.com/hermeznetwork/hermez-node/common"
  5. "github.com/iden3/go-merkletree/db"
  6. )
  7. // TODO next iteration move the methods of this file into StateDB, which Synchronizer will use in the disk DB, and BatchBuilder will use with the MemoryDB
  8. // GetBalance returns the balance for a given Idx from the DB
  9. func (bb *BatchBuilder) GetBalance(tx db.Tx, idx common.Idx) (*common.Account, error) {
  10. idxBytes := idx.Bytes()
  11. vBytes, err := tx.Get(idxBytes[:])
  12. if err != nil {
  13. return nil, err
  14. }
  15. var b [32 * common.NLEAFELEMS]byte
  16. copy(b[:], vBytes)
  17. leaf, err := common.AccountFromBytes(b)
  18. if err != nil {
  19. return nil, err
  20. }
  21. return leaf, nil
  22. }
  23. // CreateBalance stores the Account into the Idx position in the MerkleTree, also adds db entry for the Account value
  24. func (bb *BatchBuilder) CreateBalance(tx db.Tx, idx common.Idx, leaf common.Account) error {
  25. // store at the DB the key: v, and value: leaf.Bytes()
  26. v, err := leaf.HashValue()
  27. if err != nil {
  28. return err
  29. }
  30. leafBytes, err := leaf.Bytes()
  31. if err != nil {
  32. return err
  33. }
  34. // store the Account value
  35. tx.Put(v.Bytes(), leafBytes[:])
  36. // Add k & v into the MT
  37. err = bb.mt.Add(idx.BigInt(), v)
  38. if err != nil {
  39. return err
  40. }
  41. return nil
  42. }
  43. // UpdateBalance updates the balance of the leaf of a given Idx.
  44. // If sending==true: will substract the amount, if sending==false will add the ammount
  45. func (bb *BatchBuilder) UpdateBalance(tx db.Tx, idx common.Idx, amount *big.Int, sending bool) error {
  46. leaf, err := bb.GetBalance(tx, idx)
  47. if err != nil {
  48. return err
  49. }
  50. // TODO add checks that the numbers are correct and there is no missing value neither impossible values
  51. if sending {
  52. leaf.Balance = new(big.Int).Sub(leaf.Balance, amount)
  53. } else {
  54. leaf.Balance = new(big.Int).Add(leaf.Balance, amount)
  55. }
  56. // store at the DB the key: v, and value: leaf.Bytes()
  57. v, err := leaf.HashValue()
  58. if err != nil {
  59. return err
  60. }
  61. leafBytes, err := leaf.Bytes()
  62. if err != nil {
  63. return err
  64. }
  65. // store the Account value
  66. tx.Put(v.Bytes(), leafBytes[:])
  67. // Add k & v into the MT
  68. _, err = bb.mt.Update(idx.BigInt(), v)
  69. if err != nil {
  70. return err
  71. }
  72. return nil
  73. }