-
Notifications
You must be signed in to change notification settings - Fork 37
/
encoding.go
60 lines (52 loc) · 1.29 KB
/
encoding.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
package merkletree
import (
"encoding/json"
"github.com/pkg/errors"
"github.com/wealdtech/go-merkletree/v2/blake2b"
"github.com/wealdtech/go-merkletree/v2/keccak256"
"github.com/wealdtech/go-merkletree/v2/poseidon"
"github.com/wealdtech/go-merkletree/v2/sha3"
)
// MarshalJSON implements json.Marshaler.
func (t *MerkleTree) MarshalJSON() ([]byte, error) {
type ExportTree MerkleTree
data, err := json.Marshal(&struct {
HashType string `json:"hash_type"`
*ExportTree
}{
HashType: t.Hash.HashName(),
ExportTree: (*ExportTree)(t),
})
if err != nil {
return nil, errors.Wrap(err, "failed to marshal JSON")
}
return data, nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (t *MerkleTree) UnmarshalJSON(data []byte) error {
type ExportTree MerkleTree
aux := &struct {
HashType string `json:"hash_type"`
*ExportTree
}{
ExportTree: (*ExportTree)(t),
}
if err := json.Unmarshal(data, &aux); err != nil {
return errors.Wrap(err, "failed to unmarshal JSON")
}
switch aux.HashType {
case "sha512":
aux.Hash = sha3.New512()
case "sha256":
aux.Hash = sha3.New256()
case "blake2b":
aux.Hash = blake2b.New()
case "keccak256":
aux.Hash = keccak256.New()
case "poseidon":
aux.Hash = poseidon.New()
default:
return errors.New("cannot parse hash type")
}
return nil
}