forked from tranvictor/ethashproof
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.go
67 lines (58 loc) · 1.48 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package ethashproof
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os/user"
"path/filepath"
"github.com/snowfork/ethashproof/mtree"
)
const CACHE_LEVEL uint64 = 15
type DatasetMerkleTreeCache struct {
Epoch uint64 `json:"epoch"`
ProofLength uint64 `json:"proof_length"`
CacheLength uint64 `json:"cache_length"`
RootHash mtree.Hash `json:"root_hash"`
Proofs [][]mtree.Hash `json:"proofs"`
}
func (self *DatasetMerkleTreeCache) Print() {
fmt.Printf("Epoch: %d\n", self.Epoch)
fmt.Printf("Merkle root: %s\n", self.RootHash.Hex())
fmt.Printf("Sub proofs:\n")
for i, proof := range self.Proofs {
fmt.Printf("%d. [", i)
for _, node := range proof {
fmt.Printf("%s, ", node.Hex())
}
fmt.Printf("]\n")
}
}
func getHomeDir() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
return usr.HomeDir
}
func PersistCache(cache *DatasetMerkleTreeCache, cacheDir string) error {
content, err := json.Marshal(cache)
if err != nil {
return err
}
path := filepath.Join(cacheDir, fmt.Sprintf("%d.json", cache.Epoch))
return ioutil.WriteFile(path, content, 0644)
}
func LoadCache(epoch int, cacheDir string) (*DatasetMerkleTreeCache, error) {
path := filepath.Join(cacheDir, fmt.Sprintf("%d.json", epoch))
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
result := &DatasetMerkleTreeCache{}
err = json.Unmarshal(content, &result)
if err != nil {
return nil, err
}
return result, nil
}