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

Fix 'big.Int' bytes representation in snapshot hasher #1334

Merged
merged 4 commits into from
Feb 14, 2024
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
60 changes: 6 additions & 54 deletions pkg/ride/functions_bigint.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (

"github.com/ericlagergren/decimal"
"github.com/pkg/errors"

"github.com/wavesplatform/gowaves/pkg/ride/math"
"github.com/wavesplatform/gowaves/pkg/util/common"
)

var (
Expand Down Expand Up @@ -438,7 +440,8 @@ func bigIntToBytes(_ environment, args ...rideType) (rideType, error) {
return nil, errors.Wrap(err, "bigIntToBytes")
}
i := new(big.Int).Set(v.v)
return rideByteVector(encode2CBigInt(i)), nil
r := common.Encode2CBigInt(i)
return rideByteVector(r), nil
}

func bytesToBigInt(_ environment, args ...rideType) (rideType, error) {
Expand All @@ -449,7 +452,7 @@ func bytesToBigInt(_ environment, args ...rideType) (rideType, error) {
if l := len(bts); l > 64 { // No more than 64 bytes can be converted to BigInt, max size of BigInt value is 512 bit.
return nil, errors.Errorf("bytesToBigInt: bytes array is too long (%d) for a BigInt", l)
}
r := decode2CBigInt(bts)
r := common.Decode2CBigInt(bts)
if r.Cmp(math.MinBigInt) < 0 || r.Cmp(math.MaxBigInt) > 0 {
return nil, errors.Errorf("bytesToBigInt: %s result is out of range", r.String())
}
Expand Down Expand Up @@ -483,7 +486,7 @@ func bytesToBigIntLim(_ environment, args ...rideType) (rideType, error) {
if end > l {
end = l
}
r := decode2CBigInt(bts[offset:end])
r := common.Decode2CBigInt(bts[offset:end])
if r.Cmp(math.MinBigInt) < 0 || r.Cmp(math.MaxBigInt) > 0 {
return nil, errors.Errorf("bytesToBigIntLim: %s result is out of range", r.String())
}
Expand Down Expand Up @@ -625,54 +628,3 @@ func toBigIntSlice(list rideList) (bigIntSlice, error) {
}
return items, nil
}

// decode2CBigInt decodes two's complement representation of BigInt from bytes slice
func decode2CBigInt(bytes []byte) *big.Int {
r := new(big.Int)
if len(bytes) > 0 && bytes[0]&0x80 == 0x80 { // Decode a negative number
notBytes := make([]byte, len(bytes))
for i := range notBytes {
notBytes[i] = ^bytes[i]
}
r.SetBytes(notBytes)
r.Add(r, math.OneBigInt)
r.Neg(r)
return r
}
r.SetBytes(bytes)
return r
}

// encode2CBigInt encodes BigInt into a two's compliment representation
func encode2CBigInt(n *big.Int) []byte {
if n.Sign() < 0 {
// Convert negative number into two's complement form
// Subtract 1 and invert
// If the most-significant-bit isn't set then we'll need to pad the beginning with 0xff in order to keep the number negative
nMinus1 := new(big.Int).Neg(n)
nMinus1.Sub(nMinus1, math.OneBigInt)
bytes := nMinus1.Bytes()
for i := range bytes {
bytes[i] ^= 0xff
}
if l := len(bytes); l == 0 || bytes[0]&0x80 == 0 {
return padBytes(0xff, bytes)
}
return bytes
} else if n.Sign() == 0 { // Zero is written as a single 0 zero rather than no bytes
return []byte{0x00}
} else {
bytes := n.Bytes()
if len(bytes) > 0 && bytes[0]&0x80 != 0 { // We'll have to pad this with 0x00 in order to stop it looking like a negative number
return padBytes(0x00, bytes)
}
return bytes
}
}

func padBytes(p byte, bytes []byte) []byte {
r := make([]byte, len(bytes)+1)
r[0] = p
copy(r[1:], bytes)
return r
}
15 changes: 13 additions & 2 deletions pkg/ride/functions_bigint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/wavesplatform/gowaves/pkg/crypto"
rideMath "github.com/wavesplatform/gowaves/pkg/ride/math"
"github.com/wavesplatform/gowaves/pkg/util/common"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -255,13 +256,23 @@ func TestModuloBigInt(t *testing.T) {
{[]rideType{toRideBigInt(10), toRideBigInt(-6)}, false, toRideBigInt(4)},
{[]rideType{toRideBigInt(-10), toRideBigInt(-6)}, false, toRideBigInt(-4)},
{[]rideType{toRideBigInt(2), toRideBigInt(2)}, false, toRideBigInt(0)},
{[]rideType{rideBigInt{v: decode2CBigInt(crypto.MustBytesFromBase58("A98D6oABd9yshGm29dpxXzSeMi1LhCBSPeGxm7MHVB1c"))}, toRideBigInt(330)}, false, toRideBigInt(-243)},
{[]rideType{rideBigInt{
v: common.Decode2CBigInt(crypto.MustBytesFromBase58("A98D6oABd9yshGm29dpxXzSeMi1LhCBSPeGxm7MHVB1c"))},
toRideBigInt(330)},
false,
toRideBigInt(-243),
},
{[]rideType{toRideBigInt(10), toRideBigInt(0)}, true, nil},
{[]rideType{toRideBigInt(1), rideUnit{}}, true, nil},
{[]rideType{toRideBigInt(1), rideString("x")}, true, nil},
{[]rideType{toRideBigInt(1)}, true, nil},
{[]rideType{}, true, nil},
{[]rideType{rideBigInt{v: decode2CBigInt(crypto.MustBytesFromBase58("EGhEd4At3siPKgnKdgEgtZvBUFNYn7EoKnsSx35HwJ4a"))}, toRideBigInt(100)}, false, toRideBigInt(-53)},
{[]rideType{rideBigInt{
v: common.Decode2CBigInt(crypto.MustBytesFromBase58("EGhEd4At3siPKgnKdgEgtZvBUFNYn7EoKnsSx35HwJ4a"))},
toRideBigInt(100)},
false,
toRideBigInt(-53),
},
} {
r, err := moduloBigInt(nil, test.args...)
if test.fail {
Expand Down
3 changes: 2 additions & 1 deletion pkg/state/snapshot_hasher.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/wavesplatform/gowaves/pkg/crypto"
"github.com/wavesplatform/gowaves/pkg/proto"
"github.com/wavesplatform/gowaves/pkg/util/common"
)

const (
Expand Down Expand Up @@ -264,7 +265,7 @@ func (h *txSnapshotHasher) ApplyAssetDescription(snapshot proto.AssetDescription
}

func (h *txSnapshotHasher) ApplyAssetVolume(snapshot proto.AssetVolumeSnapshot) error {
totalQuantityBytes := snapshot.TotalQuantity.Bytes() // here the number is represented in big-endian form
totalQuantityBytes := common.Encode2CBigInt(&snapshot.TotalQuantity)
buf := bytebufferpool.Get()

// Asset reissuability: asset_id || is_reissuable || total_quantity
Expand Down
7 changes: 7 additions & 0 deletions pkg/state/snapshot_hasher_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ func TestTxSnapshotHasher(t *testing.T) {
expectedStateHashHex: "6502773294f32cc1702d374ffc1e67ee278cd63c5f00432f80f64a689fcb17f9",
transactionIDBase58: "5gEi2kgbMSfUzdDXRKovEbEezq5ACpr8WTeafwkKQmHW",
},
{
testCaseName: "asset_volume_two's_complement",
pbInBase64: "MicKIOfYm9p3M/NiYXCvwCU3ho5eVFpwE5iekWev4QXhZMvuEAEaAcg=",
prevStateHashHex: "6502773294f32cc1702d374ffc1e67ee278cd63c5f00432f80f64a689fcb17f9",
expectedStateHashHex: "b5f7e36556cb0d9a72bc9612be017a3cf174cfcb059d86c91621bfe7e8b74ff1",
transactionIDBase58: "Gc2kPdPb1qrCPMy1Ga6SD5PDs2Equa6aazxhKjtDzrv1", // valid txID from testnet
},
}

hasher, hErr := newTxSnapshotHasherDefault()
Expand Down
66 changes: 66 additions & 0 deletions pkg/util/common/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/base64"
"encoding/hex"
"fmt"
"math/big"
"os/user"
"path/filepath"
"strconv"
Expand Down Expand Up @@ -178,3 +179,68 @@ func ReplaceInvalidUtf8Chars(s string) string {
}
return b.String()
}

const (
byte0x00 = 0x00
byte0x01 = 0x01
byte0x80 = 0x80
byte0xff = 0xff
)

// Decode2CBigInt decodes two's complement representation of BigInt from bytes slice.
func Decode2CBigInt(bytes []byte) *big.Int {
r := new(big.Int)
if len(bytes) > 0 && bytes[0]&byte0x80 == byte0x80 { // Decode a negative number
notBytes := make([]byte, len(bytes))
for i := range notBytes {
notBytes[i] = ^bytes[i]
}
bigOne := big.NewInt(byte0x01)
r.SetBytes(notBytes)
r.Add(r, bigOne)
r.Neg(r)
return r
}
r.SetBytes(bytes)
return r
}

// Encode2CBigInt encodes BigInt into a two's complement representation.
func Encode2CBigInt(n *big.Int) []byte {
switch sign := n.Sign(); {
case sign > 0:
bts := n.Bytes()
if len(bts) > 0 && bts[0]&byte0x80 != 0 {
// We'll have to pad this with 0x00 in order to stop it looking like a negative number
return padBytes(byte0x00, bts)
}
return bts
case sign == 0: // Zero is written as a single 0 zero rather than no bytes
return []byte{byte0x00}
case sign < 0:
// Convert negative number into two's complement form
// Subtract 1 and invert
// If the most-significant-bit isn't set then we'll need to pad the beginning
// with 0xff in order to keep the number negative
bigOne := big.NewInt(byte0x01)
nMinus1 := new(big.Int).Neg(n)
nMinus1.Sub(nMinus1, bigOne)
bts := nMinus1.Bytes()
for i := range bts {
bts[i] ^= byte0xff
}
if l := len(bts); l == 0 || bts[0]&byte0x80 == 0 {
return padBytes(byte0xff, bts)
}
return bts
default:
panic("unreachable point reached")
}
}

func padBytes(p byte, bytes []byte) []byte {
r := make([]byte, len(bytes)+1)
r[0] = p
copy(r[1:], bytes)
return r
}
54 changes: 54 additions & 0 deletions pkg/util/common/util_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package common

import (
"fmt"
"math"
"math/big"
"testing"
"time"

Expand Down Expand Up @@ -96,3 +98,55 @@ func TestHexJSONUtils(t *testing.T) {
require.NoError(t, err)
require.Equal(t, expectedBytes, res)
}

func Test2CBigInt(t *testing.T) {
tests := []struct {
num *big.Int
expected []int8
}{
{big.NewInt(0), []int8{0}},
{big.NewInt(1), []int8{1}},
{big.NewInt(-1), []int8{-1}},
{big.NewInt(127), []int8{127}},
{big.NewInt(-127), []int8{-127}},
{big.NewInt(128), []int8{0, -128}},
{big.NewInt(-128), []int8{-128}},
{big.NewInt(129), []int8{0, -127}},
{big.NewInt(-129), []int8{-1, 127}},
{big.NewInt(255), []int8{0, -1}},
{big.NewInt(-255), []int8{-1, 1}},
{big.NewInt(256), []int8{1, 0}},
{big.NewInt(-256), []int8{-1, 0}},
{big.NewInt(257), []int8{1, 1}},
{big.NewInt(-257), []int8{-2, -1}},
{big.NewInt(32767), []int8{127, -1}},
{big.NewInt(-32767), []int8{-128, 1}},
{big.NewInt(32768), []int8{0, -128, 0}},
{big.NewInt(-32768), []int8{-128, 0}},
{big.NewInt(32769), []int8{0, -128, 1}},
{big.NewInt(-32769), []int8{-1, 127, -1}},
{big.NewInt(65535), []int8{0, -1, -1}},
{big.NewInt(-65535), []int8{-1, 0, 1}},
{big.NewInt(65536), []int8{1, 0, 0}},
{big.NewInt(-65536), []int8{-1, 0, 0}},
{big.NewInt(65537), []int8{1, 0, 1}},
{big.NewInt(-65537), []int8{-2, -1, -1}},
}
for _, test := range tests {
name := fmt.Sprintf("number=%d", test.num)
t.Run(name, func(t *testing.T) {
expectedBytes := make([]byte, len(test.expected))
for i, v := range test.expected {
expectedBytes[i] = byte(v)
}
t.Run("Encode", func(t *testing.T) {
actual := Encode2CBigInt(test.num)
assert.Equal(t, expectedBytes, actual)
})
t.Run("Decode", func(t *testing.T) {
actual := Decode2CBigInt(expectedBytes)
assert.True(t, test.num.Cmp(actual) == 0, "expected %d, but got %d", test.num, actual)
})
})
}
}
Loading