ids

package module
v1.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2025 License: BSD-3-Clause Imports: 14 Imported by: 592

README

Lux IDs Package

Go Reference Go Report Card

Overview

The ids package provides strongly-typed identifiers for the Lux Network. It includes implementations for various ID types used throughout the ecosystem, ensuring type safety and preventing ID misuse.

Features

  • Type-Safe IDs: Prevent mixing different ID types at compile time
  • Human-Readable Formats: CB58 encoding for user-facing representations
  • Efficient Storage: 32-byte arrays with optimized operations
  • Comprehensive Types: NodeID, ID, ShortID, and RequestID
  • Deterministic Generation: Consistent ID generation from inputs
  • Sorting Support: IDs implement sort.Interface

Installation

go get github.com/luxfi/ids

ID Types

ID

General-purpose 32-byte identifier used for transactions, blocks, chains, and subnets.

import "github.com/luxfi/ids"

// Create from bytes
var idBytes [32]byte
copy(idBytes[:], []byte("some data"))
id := ids.ID(idBytes)

// Parse from string
id, err := ids.FromString("TtF4d2QWbk5vzQGTEPrN48x6vwgAoAmKQ9cbp79inpQmcRKES")

// Convert to string
str := id.String() // CB58 encoded

// Prefix support
prefixedStr := id.PrefixedString(ids.PlatformChainID) // "P-TtF4d2..."

// Empty check
if id == ids.Empty {
    // Handle empty ID
}
NodeID

20-byte identifier for network nodes, derived from TLS certificates.

// From certificate
cert := &ids.Certificate{
    Raw:       tlsCert.Raw,
    PublicKey: tlsCert.PublicKey,
}
nodeID := ids.NodeIDFromCert(cert)

// From string
nodeID, err := ids.NodeIDFromString("NodeID-E5ecNPHk46SaKZYz6WM1PFMvgtU4sQxzG")

// Convert to string
str := nodeID.String() // Always prefixed with "NodeID-"

// Short string (for logs)
shortStr := nodeID.ShortString() // "E5ecNP..."
ShortID

20-byte identifier for addresses.

// Create from bytes
var shortBytes [20]byte
shortID := ids.ShortID(shortBytes)

// Generate from larger data
data := []byte("some larger data")
shortID = ids.ShortID(hashing.ComputeHash160Array(data))

// String conversion
str := shortID.String() // CB58 encoded
RequestID

32-bit identifier for RPC requests.

// Create new request ID
requestID := ids.RequestID(12345)

// String representation
str := requestID.String() // "12345"

// Check if set
if requestID == 0 {
    // Unset request ID
}

Advanced Usage

ID Generation
// Generate ID from transaction bytes
txBytes := []byte{...}
txID := hashing.ComputeHash256Array(txBytes)

// Generate deterministic IDs
message := []byte("deterministic input")
id := ids.ID(hashing.ComputeHash256Array(message))
Aliasing
// Create aliased ID
chainAlias := ids.Aliaser{}
chainAlias.Alias(ids.ID{1, 2, 3}, "X")

// Lookup by alias
id, err := chainAlias.Lookup("X")

// Reverse lookup
aliases, err := chainAlias.Aliases(id)
Sorting
// IDs are sortable
idSlice := []ids.ID{id1, id2, id3}
sort.Sort(ids.SortIDs(idSlice))

// NodeIDs too
nodeIDs := []ids.NodeID{node1, node2, node3}
sort.Sort(ids.SortNodeIDs(nodeIDs))
Bags (Multisets)
// Create a bag of IDs
bag := ids.NewBag()
bag.Add(id1)
bag.AddCount(id2, 5)

// Check count
count := bag.Count(id2) // returns 5

// Operations
bag.Remove(id1)
list := bag.List() // Unique IDs
Sets
// Bounded set
set := ids.NewBoundedSet(10) // Max 10 elements
set.Add(id1, id2, id3)

// Operations
if set.Contains(id1) {
    // id1 is in the set
}

// Clear if over threshold
set.ClearIfSize(8) // Clear if size >= 8

Working with Different ID Types

Chain IDs
// Platform Chain
platformChainID := ids.Empty

// Contract chains
xChainID, _ := ids.FromString("2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm")
cChainID, _ := ids.FromString("E1Cjwns27F8vLXbdqg7JdsHuwjNty5mMwVg7CgEXhhJVUmhp8")
Generating Compatible IDs
// Generate Ethereum-compatible address
privKey, _ := secp256k1.NewPrivateKey()
pubKey := privKey.PublicKey()
ethAddress := pubKey.Address()
shortID := ids.ShortID(ethAddress)

Performance Considerations

  1. String Conversion: Cache string representations if used frequently
  2. Comparison: Direct byte comparison is fastest
  3. Hashing: IDs can be used as map keys efficiently
  4. Serialization: Use raw bytes for storage, strings for display

Best Practices

  1. Type Safety: Use specific ID types (NodeID vs ID) to prevent errors
  2. Validation: Always validate IDs from external sources
  3. Encoding: Use CB58 for user-facing, hex for debugging
  4. Prefixes: Include chain prefixes for cross-chain IDs
  5. Error Handling: Check for Empty ID before operations

Examples

Creating a Transaction ID
// Transaction struct
tx := &Transaction{
    BaseTx: BaseTx{
        NetworkID:    1,
        BlockchainID: chainID,
        Outs:         outputs,
        Ins:          inputs,
    },
}

// Serialize
txBytes, err := Codec.Marshal(tx)
if err != nil {
    return err
}

// Generate ID
txID := ids.ID(hashing.ComputeHash256Array(txBytes))
Working with Aliases
aliaser := ids.NewAliaser()

// Register blockchain aliases
aliaser.Alias(xChainID, "X")
aliaser.Alias(cChainID, "C")
aliaser.Alias(platformChainID, "P")

// Parse with alias
chainID, err := aliaser.Parse("X")

Testing

Run tests:

# All tests
go test ./...

# With race detection
go test -race ./...

# Benchmarks
go test -bench=. ./...

Contributing

We welcome contributions! Please see our Contributing Guidelines.

License

This project is licensed under the BSD 3-Clause License. See the LICENSE file for details.

References

Documentation

Index

Constants

View Source
const (

	// Precomputed full strings for each chain
	PChainIDStr = nativeChainPrefix + "P"
	CChainIDStr = nativeChainPrefix + "C"
	XChainIDStr = nativeChainPrefix + "X"
	QChainIDStr = nativeChainPrefix + "Q"
	AChainIDStr = nativeChainPrefix + "A"
	BChainIDStr = nativeChainPrefix + "B"
	TChainIDStr = nativeChainPrefix + "T"
	ZChainIDStr = nativeChainPrefix + "Z"
	GChainIDStr = nativeChainPrefix + "G" // Coming soon
	IChainIDStr = nativeChainPrefix + "I" // Coming soon
	KChainIDStr = nativeChainPrefix + "K" // Coming soon
)

Native chain constants - precomputed for maximum speed

View Source
const (
	NodeIDPrefix = "NodeID-"
	NodeIDLen    = ShortIDLen
)
View Source
const BitsPerByte = 8

BitsPerByte is the number of bits per byte

View Source
const (
	IDLen = 32
)
View Source
const NumBits = 256

NumBits is the number of bits this patricia tree manages

View Source
const ShortIDLen = 20

Variables

View Source
var (
	// Empty is a useful all zero value
	Empty = ID{}
)
View Source
var (
	EmptyNodeID = NodeID{}
)
View Source
var (
	ErrNoIDWithAlias = errors.New("there is no ID with alias")
)
View Source
var (
	ShortEmpty = ShortID{}
)

ShortEmpty is a useful all zero value

Functions

func EqualSubset

func EqualSubset(start, stop int, id1, id2 ID) bool

EqualSubset takes in two indices and two ids and returns if the ids are equal from bit start to bit end (non-inclusive). Bit indices are defined as: [7 6 5 4 3 2 1 0] [15 14 13 12 11 10 9 8] ... [255 254 253 252 251 250 249 248] Where index 7 is the MSB of byte 0.

func FirstDifferenceSubset

func FirstDifferenceSubset(start, stop int, id1, id2 ID) (int, bool)

FirstDifferenceSubset takes in two indices and two ids and returns the index of the first difference between the ids inside bit start to bit end (non-inclusive). Bit indices are defined above

func GetRelevantAliases

func GetRelevantAliases(aliaser Aliaser, ids []ID) (map[ID][]string, error)

GetRelevantAliases returns the aliases with the redundant identity alias removed (each id is aliased to at least itself).

func IsNativeChain added in v1.2.0

func IsNativeChain(id ID) bool

IsNativeChain returns true if the ID is a well-known native chain ID. This is the fastest possible check - just verify all zeros except valid last byte.

func NativeChainAlias added in v1.2.0

func NativeChainAlias(id ID) string

NativeChainAlias returns the single-letter alias for a native chain (P, C, X, Q, A, B, T, Z, G, I, K). Returns empty string if not a native chain.

func NativeChainString added in v1.2.0

func NativeChainString(id ID) string

NativeChainString returns the human-friendly string for a native chain ID. Returns empty string if not a native chain. This is the fast-path for String().

func ShortIDsToStrings

func ShortIDsToStrings(ids []ShortID) []string

ShortIDsToStrings converts an array of shortIDs to an array of their string representations

Types

type Aliaser

type Aliaser interface {
	AliaserReader
	AliaserWriter

	// PrimaryAliasOrDefault returns the first alias of [id], or ID string as a
	// default if no alias exists
	PrimaryAliasOrDefault(id ID) string
}

Aliaser allows one to give an ID aliases and lookup the aliases given to an ID.

func NewAliaser

func NewAliaser() Aliaser

type AliaserReader

type AliaserReader interface {
	// Lookup returns the ID associated with alias
	Lookup(alias string) (ID, error)

	// PrimaryAlias returns the first alias of [id]
	PrimaryAlias(id ID) (string, error)

	// Aliases returns the aliases of an ID
	Aliases(id ID) ([]string, error)
}

AliaserReader allows one to lookup the aliases given to an ID.

type AliaserWriter

type AliaserWriter interface {
	// Alias gives [id] the alias [alias]
	Alias(id ID, alias string) error

	// RemoveAliases of the provided ID
	RemoveAliases(id ID)
}

AliaserWriter allows one to give an ID aliases. An ID can have arbitrarily many aliases; two IDs may not have the same alias.

type Certificate

type Certificate struct {
	// Raw contains the complete ASN.1 DER content of the certificate
	Raw []byte
	// PublicKey contains the public key from the certificate
	PublicKey crypto.PublicKey
}

Certificate represents a TLS certificate

type ID

type ID [IDLen]byte

ID wraps a 32 byte hash used as an identifier

var (
	// PChainID is the well-known P-Chain (Platform) ID
	PChainID ID

	// CChainID is the well-known C-Chain (Contract/EVM) ID
	CChainID ID

	// XChainID is the well-known X-Chain (Exchange/DAG) ID
	XChainID ID

	// QChainID is the well-known Q-Chain (Quantum) ID
	QChainID ID

	// AChainID is the well-known A-Chain (AI) ID
	AChainID ID

	// BChainID is the well-known B-Chain (Bridge) ID
	BChainID ID

	// TChainID is the well-known T-Chain (Threshold) ID
	TChainID ID

	// ZChainID is the well-known Z-Chain (Zero-knowledge) ID
	ZChainID ID

	// GChainID is the well-known G-Chain (Graph/dgraph) ID - COMING SOON
	GChainID ID

	// IChainID is the well-known I-Chain (Identity) ID - COMING SOON
	IChainID ID

	// KChainID is the well-known K-Chain (KMS) ID - COMING SOON
	KChainID ID
)

func AllNativeChainIDs added in v1.2.0

func AllNativeChainIDs() []ID

AllNativeChainIDs returns all well-known native chain IDs.

func Checksum256

func Checksum256(data []byte) ID

Checksum256 computes SHA256 checksum and returns an ID

func FromString

func FromString(idStr string) (ID, error)

FromString is the inverse of ID.String()

func FromStringOrPanic

func FromStringOrPanic(idStr string) ID

FromStringOrPanic is the same as FromString, but will panic on error

func FromStringWithForce

func FromStringWithForce(idStr string, forceIgnoreChecksum bool) (ID, error)

FromStringWithForce is like FromString but can force ignore checksum errors

func GenerateNodeIDFromBytes

func GenerateNodeIDFromBytes(bytes []byte) ID

GenerateNodeIDFromBytes generates a node ID from bytes

func GenerateTestID

func GenerateTestID() ID

GenerateTestID returns a new ID that should only be used for testing

func NativeChainFromString added in v1.2.0

func NativeChainFromString(s string) (ID, bool)

NativeChainFromString parses a native chain string and returns the ID. Supports full strings (11111111111111111111111111111111P) and aliases (P, p). Returns Empty and false if not a native chain string.

func NativeChainIDFromLetter added in v1.2.0

func NativeChainIDFromLetter(letter byte) (ID, bool)

NativeChainIDFromLetter returns the chain ID for a given letter. Returns Empty and false if the letter is not a valid chain identifier.

func ToID

func ToID(bytes []byte) (ID, error)

ToID attempt to convert a byte slice into an id

func (ID) Append

func (id ID) Append(suffixes ...uint32) ID

Append this id with the provided suffixes and re-hash the result. This returns a new ID and does not modify the original ID.

This is used to generate LP-77 validationIDs.

Ref: https://github.com/luxfi/LPs/tree/e333b335c34c8692d84259d21bd07b2bb849dc2c/LPs/77-reinventing-subnets#convertsubnettol1tx

func (ID) Bit

func (id ID) Bit(i uint) int

Bit returns the bit value at the ith index of the byte array. Returns 0 or 1

func (ID) Compare

func (id ID) Compare(other ID) int

func (ID) Hex

func (id ID) Hex() string

Hex returns a hex encoded string of this id.

func (ID) IsZero

func (id ID) IsZero() bool

IsZero returns true if the ID is all zeros

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

func (ID) MarshalText

func (id ID) MarshalText() ([]byte, error)

func (ID) Prefix

func (id ID) Prefix(prefixes ...uint64) ID

Prefix this id to create a more selective id. This can be used to store multiple values under the same key. For example: prefix1(id) -> confidence prefix2(id) -> vertex This will return a new id and not modify the original id.

func (ID) String

func (id ID) String() string

func (ID) ToShortID

func (id ID) ToShortID() ShortID

ToShortID converts this ID to a ShortID by taking the first 20 bytes

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(b []byte) error

func (*ID) UnmarshalText

func (id *ID) UnmarshalText(text []byte) error

func (ID) XOR

func (id ID) XOR(other ID) ID

XOR this id and the provided id and return the resulting id.

Note: this id is not modified.

type NodeID

type NodeID ShortID

func BuildTestNodeID

func BuildTestNodeID(src []byte) NodeID

BuildTestNodeID is an utility to build NodeID from bytes in UTs It must not be used in production code. In production code we should use ToNodeID, which performs proper length checking.

func GenerateTestNodeID

func GenerateTestNodeID() NodeID

GenerateTestNodeID returns a new ID that should only be used for testing

func NodeIDFromCert

func NodeIDFromCert(cert *Certificate) NodeID

func NodeIDFromString

func NodeIDFromString(nodeIDStr string) (NodeID, error)

NodeIDFromString is the inverse of NodeID.String()

func ToNodeID

func ToNodeID(bytes []byte) (NodeID, error)

ToNodeID attempt to convert a byte slice into a node id

func (NodeID) Bytes

func (id NodeID) Bytes() []byte

func (NodeID) Compare

func (id NodeID) Compare(other NodeID) int

func (NodeID) MarshalJSON

func (id NodeID) MarshalJSON() ([]byte, error)

func (NodeID) MarshalText

func (id NodeID) MarshalText() ([]byte, error)

func (NodeID) String

func (id NodeID) String() string

func (*NodeID) UnmarshalJSON

func (id *NodeID) UnmarshalJSON(b []byte) error

func (*NodeID) UnmarshalText

func (id *NodeID) UnmarshalText(text []byte) error

type RequestID

type RequestID struct {
	// The node this request came from
	NodeID NodeID
	// The chain this request came from
	SourceChainID ID
	// The chain the expected response should come from
	DestinationChainID ID
	// The unique identifier for this request
	RequestID uint32
	// The message opcode
	Op byte
}

RequestID is a unique identifier for an in-flight request pending a response.

type ShortID

type ShortID [ShortIDLen]byte

ShortID wraps a 20 byte hash as an identifier

func GenerateTestShortID

func GenerateTestShortID() ShortID

GenerateTestShortID returns a new ID that should only be used for testing

func ShortFromPrefixedString

func ShortFromPrefixedString(idStr, prefix string) (ShortID, error)

ShortFromPrefixedString returns a ShortID assuming the cb58 format is prefixed

func ShortFromString

func ShortFromString(idStr string) (ShortID, error)

ShortFromString is the inverse of ShortID.String()

func ToShortID

func ToShortID(bytes []byte) (ShortID, error)

ToShortID attempt to convert a byte slice into an id

func (ShortID) Bytes

func (id ShortID) Bytes() []byte

Bytes returns the 20 byte hash as a slice. It is assumed this slice is not modified.

func (ShortID) Compare

func (id ShortID) Compare(other ShortID) int

func (ShortID) Hex

func (id ShortID) Hex() string

Hex returns a hex encoded string of this id.

func (ShortID) MarshalJSON

func (id ShortID) MarshalJSON() ([]byte, error)

func (ShortID) MarshalText

func (id ShortID) MarshalText() ([]byte, error)

func (ShortID) PrefixedString

func (id ShortID) PrefixedString(prefix string) string

PrefixedString returns the String representation with a prefix added

func (ShortID) String

func (id ShortID) String() string

func (*ShortID) UnmarshalJSON

func (id *ShortID) UnmarshalJSON(b []byte) error

func (*ShortID) UnmarshalText

func (id *ShortID) UnmarshalText(text []byte) error

Directories

Path Synopsis
cmd
test_native command
Package codectest provides a test suite for testing functionality related to IDs.
Package codectest provides a test suite for testing functionality related to IDs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL