From 54d9762ff2fb60e08a8e4669fbb9ce6f66c3ddcb Mon Sep 17 00:00:00 2001 From: Andrew Ayer Date: Thu, 5 Jan 2017 15:43:26 -0800 Subject: [PATCH] Add JSON marshalling for MerkleTreeBuilder --- auditing.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/auditing.go b/auditing.go index a5768ec..f03006e 100644 --- a/auditing.go +++ b/auditing.go @@ -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 +}