Skip to content

Commit

Permalink
Fix IDFromInt for cases when bytes representation of Int is less then…
Browse files Browse the repository at this point in the history
… 31 bytes (#427)
  • Loading branch information
olomix authored Jun 21, 2022
1 parent ee449c3 commit 07a6279
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
14 changes: 12 additions & 2 deletions id.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type Hash [32]byte
Expand Down Expand Up @@ -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())
}

0 comments on commit 07a6279

Please sign in to comment.