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.

62 lines
1.4 KiB

  1. package tree
  2. import (
  3. "github.com/iden3/go-iden3/db"
  4. "github.com/iden3/go-iden3/merkletree"
  5. mkcore "github.com/iden3/go-iden3/core"
  6. common3 "github.com/iden3/go-iden3/common"
  7. "os/user"
  8. )
  9. type Tree struct {
  10. namespace string
  11. storage string
  12. tree *merkletree.MerkleTree
  13. }
  14. func (t *Tree) init() error {
  15. if len(t.storage) < 1 {
  16. usr, err := user.Current()
  17. if err == nil {
  18. t.storage = usr.HomeDir + "/.dvote/Tree"
  19. } else { t.storage = "./dvoteTree" }
  20. }
  21. mtdb, err := db.NewLevelDbStorage(t.storage, false)
  22. if err != nil {
  23. return err
  24. }
  25. mt, err := merkletree.New(mtdb, 140)
  26. if err != nil {
  27. return err
  28. }
  29. t.tree = mt
  30. return nil
  31. }
  32. func (t *Tree) close() {
  33. defer t.tree.Storage().Close()
  34. }
  35. func (t *Tree) addClaim(data []byte) error {
  36. claim := mkcore.NewGenericClaim(t.namespace, "default", data, nil)
  37. return t.tree.Add(claim)
  38. }
  39. func (t *Tree) genProof(data []byte) (string, error) {
  40. claim := mkcore.NewGenericClaim(t.namespace, "default", data, nil)
  41. mp, err := t.tree.GenerateProof(claim.Hi())
  42. if err!=nil {
  43. return "", err
  44. }
  45. mpHex := common3.BytesToHex(mp)
  46. return mpHex, nil
  47. }
  48. func (t *Tree) checkProof(data []byte, mpHex string) (bool, error) {
  49. mp, err := common3.HexToBytes(mpHex)
  50. if err != nil {
  51. return false, err
  52. }
  53. claim := mkcore.NewGenericClaim(t.namespace, "default", data, nil)
  54. return merkletree.CheckProof(t.tree.Root(), mp, claim.Hi(), claim.Ht(), t.tree.NumLevels()), nil
  55. }