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: add support to legacy-marshaled hashes #2025

Merged
merged 1 commit into from
Sep 1, 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
20 changes: 20 additions & 0 deletions chaincfg/chainhash/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,12 @@ func (hash Hash) MarshalJSON() ([]byte, error) {

// UnmarshalJSON parses the hash with JSON appropriate string value.
func (hash *Hash) UnmarshalJSON(input []byte) error {
// If the first byte indicates an array, the hash could have been marshalled
// using the legacy method and e.g. persisted.
if len(input) > 0 && input[0] == '[' {
return decodeLegacy(hash, input)
}

var sh string
err := json.Unmarshal(input, &sh)
if err != nil {
Expand Down Expand Up @@ -217,3 +223,17 @@ func Decode(dst *Hash, src string) error {

return nil
}

// decodeLegacy decodes an Hash that has been encoded with the legacy method
// (i.e. represented as a bytes array) to a destination.
func decodeLegacy(dst *Hash, src []byte) error {
guggero marked this conversation as resolved.
Show resolved Hide resolved
var hashBytes []byte
err := json.Unmarshal(src, &hashBytes)
if err != nil {
return err
}
if len(hashBytes) != HashSize {
return ErrHashStrSize
}
return dst.SetBytes(hashBytes)
}
10 changes: 10 additions & 0 deletions chaincfg/chainhash/hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ func TestNewHashFromStr(t *testing.T) {
// TestHashJsonMarshal tests json marshal and unmarshal.
func TestHashJsonMarshal(t *testing.T) {
hashStr := "000000000003ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506"
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]")

hash, err := NewHashFromStr(hashStr)
if err != nil {
Expand All @@ -219,4 +220,13 @@ func TestHashJsonMarshal(t *testing.T) {
if !hash.IsEqual(&newHash) {
t.Errorf("String: wrong hash string - got %v, want %v", newHash.String(), hashStr)
}

err = newHash.UnmarshalJSON(legacyHashStr)
if err != nil {
t.Errorf("Unmarshal legacy json error:%v, hash:%v", err, legacyHashStr)
}

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