Skip to content

Commit

Permalink
common/math: fix common.uint256 unmarshal behavior and tests
Browse files Browse the repository at this point in the history
Holimant's uint256 lib is stricter than big
about its encoding. It demands leading 0[X|x]
and wont accept leading zeros.

Date: 2024-02-27 13:06:02-07:00
Signed-off-by: meows <[email protected]>
  • Loading branch information
meowsbits committed Feb 27, 2024
1 parent 47b14b9 commit 80af048
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
9 changes: 5 additions & 4 deletions common/math/uint256.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,14 @@ func ParseUint256(s string) (*uint256.Int, bool) {
if s == "" {
return new(uint256.Int), true
}
var bigint *uint256.Int
var bigint = new(uint256.Int)
var ok bool
if len(s) >= 2 && (s[:2] == "0x" || s[:2] == "0X") {
// bigint, ok = new(uint256.Int).SetString(s[2:], 16)
bigint.SetFromHex(s)
} else {
bigint.SetFromHex("0X" + s)
if err := bigint.SetFromHex(s); err != nil {
return nil, false
}
ok = true
}
if ok && bigint.BitLen() > 256 {
bigint, ok = nil, false
Expand Down
13 changes: 7 additions & 6 deletions common/math/uint256_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,23 +29,24 @@ func TestHexOrDecimalUint256(t *testing.T) {
ok bool
}{
{"", uint256.NewInt(0), true},
{"0", uint256.NewInt(0), true},
{"0", uint256.NewInt(0), false},
{"0x0", uint256.NewInt(0), true},
{"12345678", uint256.NewInt(12345678), true},
{"12345678", uint256.NewInt(0), false},
{"0x12345678", uint256.NewInt(0x12345678), true},
{"0X12345678", uint256.NewInt(0x12345678), true},
// Tests for leading zero behaviour:
{"0123456789", uint256.NewInt(123456789), true}, // note: not octal
{"00", uint256.NewInt(0), true},
{"0x00", uint256.NewInt(0), true},
{"0x012345678abc", uint256.NewInt(0x12345678abc), true},
{"0123456789", uint256.NewInt(0), false}, // note: not octal
{"00", uint256.NewInt(0), false},
{"0x00", uint256.NewInt(0), false},
{"0x012345678abc", uint256.NewInt(0), false},
// Invalid syntax:
{"abcdef", nil, false},
{"0xgg", nil, false},
// Larger than 256 bits:
{"115792089237316195423570985008687907853269984665640564039457584007913129639936", nil, false},
}
for _, test := range tests {
t.Logf("Unmarshaling %q", test.input)
var num HexOrDecimalUint256
err := num.UnmarshalText([]byte(test.input))
if (err == nil) != test.ok {
Expand Down

0 comments on commit 80af048

Please sign in to comment.