From a337d1e4253d5c47aca5d33c46c3ae2c46ca4a76 Mon Sep 17 00:00:00 2001 From: RycCheen Date: Tue, 21 Feb 2023 19:53:42 +0800 Subject: [PATCH 1/2] chainhash: JSON Unmarshal hash from appropriate string. --- chaincfg/chainhash/hash.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/chaincfg/chainhash/hash.go b/chaincfg/chainhash/hash.go index d2c562ae6a..fc059787db 100644 --- a/chaincfg/chainhash/hash.go +++ b/chaincfg/chainhash/hash.go @@ -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) { From 197affab7f817298538885d2f891efc9ede05789 Mon Sep 17 00:00:00 2001 From: RycCheen Date: Fri, 24 Feb 2023 10:57:36 +0800 Subject: [PATCH 2/2] Supplementary chainhash test cases --- chaincfg/chainhash/hash_test.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/chaincfg/chainhash/hash_test.go b/chaincfg/chainhash/hash_test.go index 07f54c7763..19f34e3a93 100644 --- a/chaincfg/chainhash/hash_test.go +++ b/chaincfg/chainhash/hash_test.go @@ -7,6 +7,7 @@ package chainhash import ( "bytes" "encoding/hex" + "encoding/json" "testing" ) @@ -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) + } +}