Add JSON marshalling for MerkleTreeBuilder

This commit is contained in:
Andrew Ayer 2017-01-05 15:43:26 -08:00
parent 7c55be7d5c
commit 54d9762ff2
1 changed files with 24 additions and 0 deletions

View File

@ -12,6 +12,7 @@ package certspotter
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"software.sslmate.com/src/certspotter/ct"
)
@ -188,3 +189,26 @@ func (builder *MerkleTreeBuilder) CalculateRoot() ct.MerkleTreeNode {
func (builder *MerkleTreeBuilder) GetNumLeaves() uint64 {
return builder.numLeaves
}
func (builder *MerkleTreeBuilder) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"stack": builder.stack,
"num_leaves": builder.numLeaves,
})
}
func (builder *MerkleTreeBuilder) UnmarshalJSON(b []byte) error {
var rawBuilder struct {
Stack []ct.MerkleTreeNode `json:"stack"`
NumLeaves uint64 `json:"num_leaves"`
}
if err := json.Unmarshal(b, &rawBuilder); err != nil {
return errors.New("Failed to unmarshal MerkleTreeBuilder: " + err.Error())
}
if len(rawBuilder.Stack) != calculateStackSize(rawBuilder.NumLeaves) {
return errors.New("Failed to unmarshal MerkleTreeBuilder: invalid stack size")
}
builder.numLeaves = rawBuilder.NumLeaves
builder.stack = rawBuilder.Stack
return nil
}