+
Skip to content

Fix IDFromInt for cases when bytes representation of Int is less then… #427

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

Merged
merged 1 commit into from
Jun 21, 2022
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: 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())
}
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载