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

Serialize Uint64 to string in JSON #2229

Merged
merged 3 commits into from
Mar 15, 2019
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
14 changes: 14 additions & 0 deletions commands/chain_daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,18 @@ func TestChainDaemon(t *testing.T) {
assert.Contains(chainLsResult, "1")
assert.Contains(chainLsResult, "0")
})

t.Run("chain ls --long with JSON encoding returns integer string block height and nonce", func(t *testing.T) {
t.Parallel()
assert := assert.New(t)

daemon := th.NewDaemon(t, th.WithMiner(fixtures.TestMiners[0])).Start()
defer daemon.ShutdownSuccess()

daemon.RunSuccess("mining", "once", "--enc", "text")
chainLsResult := daemon.RunSuccess("chain", "ls", "--long", "--enc", "json").ReadStdoutTrimNewlines()
assert.Contains(chainLsResult, `"height":"0"`)
assert.Contains(chainLsResult, `"height":"1"`)
assert.Contains(chainLsResult, `"nonce":"0"`)
})
}
9 changes: 4 additions & 5 deletions types/uint64.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package types

import (
"encoding/base64"
"strconv"
"strings"

"gx/ipfs/QmSKyB5faguXT4NqbrXpnRXqaVj5DhSm7x9BtzFydBY1UK/go-leb128"
Expand Down Expand Up @@ -29,17 +29,16 @@ type Uint64 uint64

// MarshalJSON converts a Uint64 to a json string and returns it.
func (u Uint64) MarshalJSON() ([]byte, error) {
encoded := base64.StdEncoding.EncodeToString(leb128.FromUInt64(uint64(u)))
return []byte(`"` + encoded + `"`), nil
return []byte(`"` + strconv.FormatUint(uint64(u), 10) + `"`), nil
}

// UnmarshalJSON converts a json string to a Uint64.
func (u *Uint64) UnmarshalJSON(b []byte) error {
jd, err := base64.StdEncoding.DecodeString(strings.Trim(string(b), `"`))
val, err := strconv.ParseUint(strings.Trim(string(b), `"`), 10, 64)
if err != nil {
return err
}

*u = Uint64(leb128.ToUInt64(jd))
*u = Uint64(val)
return nil
}
1 change: 1 addition & 0 deletions types/uint64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func TestUint64Json(t *testing.T) {
v := Uint64(64)
m, err := json.Marshal(v)
assert.NoError(err)
assert.Equal(`"64"`, string(m))
var got Uint64
err = json.Unmarshal(m, &got)
assert.NoError(err)
Expand Down