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.

66 lines
1.5 KiB

  1. package tree
  2. import (
  3. "github.com/vocdoni/go-iden3/db"
  4. "github.com/vocdoni/go-iden3/merkletree"
  5. mkcore "github.com/vocdoni/go-iden3/core"
  6. common3 "github.com/vocdoni/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. }
  56. func (t *Tree) GetRoot() (string) {
  57. return t.Tree.Root().Hex()
  58. }