Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chainhash: JSON Unmarshal hash from appropriate string. #1952

Merged
merged 2 commits into from
Mar 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions chaincfg/chainhash/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,21 @@ func (hash Hash) MarshalJSON() ([]byte, error) {
return json.Marshal(hash.String())
}

// UnmarshalJSON parses the hash with JSON appropriate string value.
func (hash *Hash) UnmarshalJSON(input []byte) error {
var sh string
err := json.Unmarshal(input, &sh)
if err != nil {
return err
}
newHash, err := NewHashFromStr(sh)
if err != nil {
return err
}

return hash.SetBytes(newHash[:])
}

// NewHash returns a new Hash from a byte slice. An error is returned if
// the number of bytes passed in is not HashSize.
func NewHash(newHash []byte) (*Hash, error) {
Expand Down
26 changes: 26 additions & 0 deletions chaincfg/chainhash/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package chainhash
import (
"bytes"
"encoding/hex"
"encoding/json"
"testing"
)

Expand Down Expand Up @@ -194,3 +195,28 @@ func TestNewHashFromStr(t *testing.T) {
}
}
}

// TestHashJsonMarshal tests json marshal and unmarshal.
func TestHashJsonMarshal(t *testing.T) {
hashStr := "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"

hash, err := NewHashFromStr(hashStr)
if err != nil {
t.Errorf("NewHashFromStr error:%v, hashStr:%s", err, hashStr)
}

hashBytes, err := json.Marshal(hash)
if err != nil {
t.Errorf("Marshal json error:%v, hash:%v", err, hashBytes)
}

var newHash Hash
err = json.Unmarshal(hashBytes, &newHash)
if err != nil {
t.Errorf("Unmarshal json error:%v, hash:%v", err, hashBytes)
}

if !hash.IsEqual(&newHash) {
t.Errorf("String: wrong hash string - got %v, want %v", newHash.String(), hashStr)
}
}