From 762aba21de098264e150021e5d4311915b7f0151 Mon Sep 17 00:00:00 2001 From: Oleg Lomaka Date: Tue, 21 Jun 2022 13:07:51 +0300 Subject: [PATCH] Fix IDFromInt for cases when bytes representation of Int is less then 31 bytes --- id.go | 14 ++++++++++++-- id_test.go | 15 +++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/id.go b/id.go index 7adef94..d50098f 100644 --- a/id.go +++ b/id.go @@ -19,11 +19,13 @@ var ( TypeReadOnly = [2]byte{0b00000000, 0b00000001} ) +const idLength = 31 + // ID is a byte array with // [ type | root_genesis | checksum ] // [2 bytes | 27 bytes | 2 bytes ] // where the root_genesis are the first 28 bytes from the hash root_genesis -type ID [31]byte +type ID [idLength]byte // NewID creates a new ID from a type and genesis func NewID(typ [2]byte, genesis [27]byte) ID { @@ -102,6 +104,12 @@ func IDFromBytes(b []byte) (ID, error) { // IDFromInt returns the ID from a given big.Int func IDFromInt(i *big.Int) (ID, error) { b := intToBytes(i) + if len(b) > idLength { + return ID{}, errors.New("IDFromInt error: big.Int too large") + } + for len(b) < idLength { + b = append(b, make([]byte, idLength-len(b))...) + } return IDFromBytes(b) } @@ -148,7 +156,9 @@ func CheckChecksum(id ID) bool { } // IdGenesisFromIdenState calculates the genesis ID from an Identity State. -func IdGenesisFromIdenState(typ [2]byte, state *big.Int) (*ID, error) { //nolint:revive +func IdGenesisFromIdenState(typ [2]byte, //nolint:revive + state *big.Int) (*ID, error) { + var idGenesisBytes [27]byte idenStateData, err := NewElemBytesFromInt(state) diff --git a/id_test.go b/id_test.go index 4e6585d..e3ecdf6 100644 --- a/id_test.go +++ b/id_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type Hash [32]byte @@ -149,3 +150,17 @@ func TestIDFromInt(t *testing.T) { assert.Equal(t, id, got) } + +func TestIDFromIntStr(t *testing.T) { + idStr := "11BBCPZ6Zq9HX1JhHrHT3QKUFD9kFDEyJFoAVMpuZR" + + idFromStr, err := IDFromString(idStr) + require.NoError(t, err) + + intFromIDFromStr := idFromStr.BigInt() + + id, err := IDFromInt(intFromIDFromStr) + require.NoError(t, err) + + require.Equal(t, idStr, id.String()) +}