0

I have a struct where merkleTree.MerkleProof is an interface which is implemented by mTree.Proof:

type Checkpoint struct {
    Leaves      []Leaf
    MerkleProof merkleTree.MerkleProof
}

type MerkleProof interface {
    Verify(leafHash, treeRoot []byte) 
}

type Proof struct {
    Hashes  [][]byte
    Path    []byte
}

I am encoding a Checkpoint struct (with a Proof struct in the MerkleProof field) to a file with JSON or Gob and everything goes smoothly; the data is encoded correctly.

"Proof": {
    "Hashes": [
        "f8kfN1YkWAwRpj1wbX2izMGC5DbHel//d5y5hceamAc="
    ],
    "Path": "AA=="
}

When I go to decode the same encoded data I get the following error:

json: cannot unmarshal object into Go struct field Checkpoint.MerkleProof of type merkleTree.MerkleProof

Gob gives a similar error. How do I get the decoders to recognize that the Proof struct implement MerkleProof and can be stored in the field?

user1731199
  • 237
  • 1
  • 2
  • 10
  • 3
    I don't know about gob but as far as json is concerned you either have to initialize `MerkleProof` field to `*Proof` before unmarshaling, or you can't use an interface, not without some concrete type in-between that knows how the unmarshal raw json into the correct implementation. – mkopriva Apr 28 '20 at 17:13
  • 4
    The Gob decoder error tells you that the Proof type is not registered. Fix by [registering](https://godoc.org/encoding/gob#Register) the Proof type. – Charlie Tumahai Apr 28 '20 at 17:18
  • Thanks for the responses. I did try gob.Register(merkletree.Proof{}) and got this error: "gob: merkleTree.Proof is not assignable to type merkleTree.MerkleProof" – user1731199 Apr 28 '20 at 18:17
  • 3
    @user1731199 If it's the pointer type that implements the interface try `gob.Register(&merkletree.Proof{})`. – mkopriva Apr 28 '20 at 18:32
  • @mkopriva smh of course I forgot the pointer. That solved it for Gob, thank you! – user1731199 Apr 28 '20 at 19:03

0 Answers0