Skip to content

Commit 3627816

Browse files
committed
chainhash: add support to legacy-marshaled hashes
Recent commits 1d6e578 and 72ea23e introduced a change in the way Hashes are serialized and deserialized. This change could cause errors in downstream applications that persisted hashes serialized using the previous methods. This introduces support for legacy-serialized hashes unmarshaling and restores the compatibility with previous versions.
1 parent 40d7a0a commit 3627816

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

chaincfg/chainhash/hash.go

+20
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,12 @@ func (hash Hash) MarshalJSON() ([]byte, error) {
118118

119119
// UnmarshalJSON parses the hash with JSON appropriate string value.
120120
func (hash *Hash) UnmarshalJSON(input []byte) error {
121+
// If the first byte indicates an array, the hash could have been marshalled
122+
// using the legacy method and e.g. persisted.
123+
if len(input) > 0 && input[0] == '[' {
124+
return decodeLegacy(hash, input)
125+
}
126+
121127
var sh string
122128
err := json.Unmarshal(input, &sh)
123129
if err != nil {
@@ -217,3 +223,17 @@ func Decode(dst *Hash, src string) error {
217223

218224
return nil
219225
}
226+
227+
// decodeLegacy decodes an Hash that has been encoded with the legacy method
228+
// (i.e. represented as a bytes array) to a destination.
229+
func decodeLegacy(dst *Hash, src []byte) error {
230+
var hashBytes []byte
231+
err := json.Unmarshal(src, &hashBytes)
232+
if err != nil {
233+
return err
234+
}
235+
if len(hashBytes) != HashSize {
236+
return ErrHashStrSize
237+
}
238+
return dst.SetBytes(hashBytes)
239+
}

chaincfg/chainhash/hash_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ func TestNewHashFromStr(t *testing.T) {
199199
// TestHashJsonMarshal tests json marshal and unmarshal.
200200
func TestHashJsonMarshal(t *testing.T) {
201201
hashStr := "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
202+
legacyHashStr := []byte("[6,229,51,253,26,218,134,57,31,63,108,52,50,4,176,210,120,212,170,236,28,11,32,170,39,186,3,0,0,0,0,0]")
202203

203204
hash, err := NewHashFromStr(hashStr)
204205
if err != nil {
@@ -219,4 +220,13 @@ func TestHashJsonMarshal(t *testing.T) {
219220
if !hash.IsEqual(&newHash) {
220221
t.Errorf("String: wrong hash string - got %v, want %v", newHash.String(), hashStr)
221222
}
223+
224+
err = newHash.UnmarshalJSON(legacyHashStr)
225+
if err != nil {
226+
t.Errorf("Unmarshal legacy json error:%v, hash:%v", err, legacyHashStr)
227+
}
228+
229+
if !hash.IsEqual(&newHash) {
230+
t.Errorf("String: wrong hash string - got %v, want %v", newHash.String(), hashStr)
231+
}
222232
}

0 commit comments

Comments
 (0)