mirror of
https://github.com/luxfi/node.git
synced 2026-07-27 03:39:39 +00:00
- constants v1.5.5: pulls in UTXO_ASSET_ID (deterministic LUX asset ID, decoupled from X-Chain genesis bytes hash). Makes X-Chain optional — P-only L2s can ship without X-Chain bake. - genesis v1.11.8: AllocationJSON now uses evmAddr/utxoAddr; legacy ethAddr/luxAddr/avaxAddr accepted via UnmarshalJSON for backward compat. - builder.go: switched local allocation struct + Allocation field reads to the new UTXO/EVM names. Build + tests green. Unblocks "P+Q-only" L2 topology.
1009 lines
32 KiB
Go
1009 lines
32 KiB
Go
// Copyright (C) 2019-2025, Lux Industries Inc. All rights reserved.
|
|
// See the file LICENSE for licensing terms.
|
|
|
|
// Package builder provides genesis byte generation for Lux networks.
|
|
// This package depends on node types and is responsible for building
|
|
// the actual genesis state from genesis config.
|
|
package builder
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"path"
|
|
"time"
|
|
|
|
"github.com/luxfi/address"
|
|
"github.com/luxfi/constants"
|
|
"github.com/luxfi/container/sampler"
|
|
"github.com/luxfi/formatting"
|
|
"github.com/luxfi/ids"
|
|
"github.com/luxfi/math/set"
|
|
"github.com/luxfi/net/endpoints"
|
|
"github.com/luxfi/node/vms/components/gas"
|
|
exchangevm "github.com/luxfi/node/vms/xvm"
|
|
"github.com/luxfi/node/vms/xvm/fxs"
|
|
xchaintxs "github.com/luxfi/node/vms/xvm/txs"
|
|
"github.com/luxfi/node/vms/platformvm/genesis"
|
|
"github.com/luxfi/node/vms/platformvm/reward"
|
|
"github.com/luxfi/node/vms/platformvm/signer"
|
|
pchaintxs "github.com/luxfi/node/vms/platformvm/txs"
|
|
"github.com/luxfi/node/vms/platformvm/validators/fee"
|
|
"github.com/luxfi/utxo/bls12381fx"
|
|
"github.com/luxfi/utxo/ed25519fx"
|
|
"github.com/luxfi/utxo/mldsafx"
|
|
"github.com/luxfi/utxo/nftfx"
|
|
"github.com/luxfi/utxo/propertyfx"
|
|
"github.com/luxfi/utxo/schnorrfx"
|
|
"github.com/luxfi/utxo/secp256k1fx"
|
|
"github.com/luxfi/utxo/secp256r1fx"
|
|
"github.com/luxfi/utxo/slhdsafx"
|
|
|
|
genesiscfg "github.com/luxfi/genesis/pkg/genesis"
|
|
genesisconfigs "github.com/luxfi/genesis/configs"
|
|
)
|
|
|
|
var (
|
|
// PChainAliases are the default aliases for the P-Chain
|
|
PChainAliases = []string{"P", "platform"}
|
|
// XChainAliases are the default aliases for the X-Chain
|
|
XChainAliases = []string{"X", "xvm"}
|
|
// CChainAliases are the default aliases for the C-Chain
|
|
CChainAliases = []string{"C", "evm"}
|
|
// DChainAliases are the default aliases for the D-Chain (DEX)
|
|
DChainAliases = []string{"D", "dex", "dexvm"}
|
|
// QChainAliases are the default aliases for the Q-Chain (Quantum)
|
|
QChainAliases = []string{"Q", "quantum", "quantumvm", "pq"}
|
|
// AChainAliases are the default aliases for the A-Chain (Attestation/AI)
|
|
AChainAliases = []string{"A", "attest", "ai", "aivm"}
|
|
// BChainAliases are the default aliases for the B-Chain (Bridge)
|
|
BChainAliases = []string{"B", "bridge", "bridgevm"}
|
|
// TChainAliases are the default aliases for the T-Chain (Threshold)
|
|
TChainAliases = []string{"T", "threshold", "thresholdvm", "mpc"}
|
|
// ZChainAliases are the default aliases for the Z-Chain (ZK)
|
|
ZChainAliases = []string{"Z", "zk", "zkvm"}
|
|
// GChainAliases are the default aliases for the G-Chain (Graph)
|
|
GChainAliases = []string{"G", "graph", "graphvm", "dgraph"}
|
|
// KChainAliases are the default aliases for the K-Chain (KMS)
|
|
KChainAliases = []string{"K", "key", "keyvm"}
|
|
|
|
// Network-specific genesis messages (Latin for mainnet, descriptive for others)
|
|
// Mainnet: "Lux et Libertas" - Light and Liberty
|
|
MainnetChainGenesis = `{"version":1,"message":"Lux et Libertas"}`
|
|
// Testnet: "Per Aspera ad Astra" - Through hardships to the stars
|
|
TestnetChainGenesis = `{"version":1,"message":"Per Aspera ad Astra"}`
|
|
// Devnet: "In Silico Veritas" - Truth in silicon
|
|
DevnetChainGenesis = `{"version":1,"message":"In Silico Veritas"}`
|
|
// Local/Custom: "Carpe Diem" - Seize the day
|
|
LocalChainGenesis = `{"version":1,"message":"Carpe Diem"}`
|
|
|
|
// VMAliases are the default aliases for VMs
|
|
VMAliases = map[ids.ID][]string{
|
|
constants.PlatformVMID: {"platform"},
|
|
constants.XVMID: {"xvm"},
|
|
constants.EVMID: {"evm"},
|
|
constants.DexVMID: {"dexvm", "dex"},
|
|
constants.QuantumVMID: {"quantumvm", "quantum", "pq"},
|
|
constants.AIVMID: {"aivm", "attest", "ai"},
|
|
constants.BridgeVMID: {"bridgevm", "bridge"},
|
|
constants.ThresholdVMID: {"thresholdvm", "threshold", "mpc"},
|
|
constants.ZKVMID: {"zkvm", "zk"},
|
|
constants.GraphVMID: {"graphvm", "graph", "dgraph"},
|
|
constants.KeyVMID: {"keyvm", "key"},
|
|
secp256k1fx.ID: {"secp256k1fx"},
|
|
nftfx.ID: {"nftfx"},
|
|
propertyfx.ID: {"propertyfx"},
|
|
mldsafx.ID: {"mldsafx"},
|
|
slhdsafx.ID: {"slhdsafx"},
|
|
ed25519fx.ID: {"ed25519fx"},
|
|
secp256r1fx.ID: {"secp256r1fx"},
|
|
schnorrfx.ID: {"schnorrfx"},
|
|
bls12381fx.ID: {"bls12381fx"},
|
|
}
|
|
|
|
errNoTxs = errors.New("genesis creates no transactions")
|
|
errOverridesStandardNetworkConfig = errors.New("overrides standard network genesis config")
|
|
)
|
|
|
|
// Bootstrapper represents a network bootstrap node with parsed types.
|
|
// Supports both IP addresses and hostnames for the endpoint.
|
|
type Bootstrapper struct {
|
|
ID ids.NodeID
|
|
Endpoint endpoints.Endpoint
|
|
}
|
|
|
|
// IP returns the IP address if this is an IP-based endpoint.
|
|
// For hostname endpoints, this returns an invalid AddrPort.
|
|
// Deprecated: Use Endpoint directly for new code.
|
|
func (b Bootstrapper) IP() endpoints.Endpoint {
|
|
return b.Endpoint
|
|
}
|
|
|
|
// ParseBootstrapper converts a genesis config bootstrapper to a parsed Bootstrapper.
|
|
// The IP field can be either an IP:port (e.g., "1.2.3.4:9631") or a hostname:port
|
|
// (e.g., "luxd-0.luxd-headless.lux-mainnet.svc.cluster.local:9631").
|
|
func ParseBootstrapper(b genesiscfg.Bootstrapper) (Bootstrapper, error) {
|
|
nodeID, err := ids.NodeIDFromString(b.ID)
|
|
if err != nil {
|
|
return Bootstrapper{}, fmt.Errorf("invalid bootstrapper ID %q: %w", b.ID, err)
|
|
}
|
|
endpoint, err := endpoints.ParseEndpoint(b.IP)
|
|
if err != nil {
|
|
return Bootstrapper{}, fmt.Errorf("invalid bootstrapper endpoint %q: %w", b.IP, err)
|
|
}
|
|
return Bootstrapper{ID: nodeID, Endpoint: endpoint}, nil
|
|
}
|
|
|
|
// parseProofOfPossession converts a genesis config ProofOfPossession (with hex strings)
|
|
// to a node signer.ProofOfPossession (with byte arrays).
|
|
func parseProofOfPossession(pop *genesiscfg.ProofOfPossession) (*signer.ProofOfPossession, error) {
|
|
if pop == nil {
|
|
return nil, nil
|
|
}
|
|
|
|
// Decode the public key from hex string (may have 0x prefix)
|
|
pkBytes, err := formatting.Decode(formatting.HexNC, pop.PublicKey)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decode publicKey: %w", err)
|
|
}
|
|
|
|
// Decode the proof of possession from hex string (may have 0x prefix)
|
|
popBytes, err := formatting.Decode(formatting.HexNC, pop.ProofOfPossession)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to decode proofOfPossession: %w", err)
|
|
}
|
|
|
|
result := &signer.ProofOfPossession{}
|
|
copy(result.PublicKey[:], pkBytes)
|
|
copy(result.ProofOfPossession[:], popBytes)
|
|
|
|
// Verify the proof of possession is valid
|
|
if err := result.Verify(); err != nil {
|
|
return nil, fmt.Errorf("invalid proof of possession: %w", err)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// GetBootstrappers returns parsed bootstrappers for the network
|
|
func GetBootstrappers(networkID uint32) ([]Bootstrapper, error) {
|
|
cfgBootstrappers := genesiscfg.GetBootstrappers(networkID)
|
|
result := make([]Bootstrapper, 0, len(cfgBootstrappers))
|
|
for _, b := range cfgBootstrappers {
|
|
parsed, err := ParseBootstrapper(b)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result = append(result, parsed)
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
// SampleBootstrappers returns a random sample of bootstrappers for the network
|
|
func SampleBootstrappers(networkID uint32, count int) ([]Bootstrapper, error) {
|
|
allBootstrappers, err := GetBootstrappers(networkID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
count = min(count, len(allBootstrappers))
|
|
if count <= 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
s := sampler.NewUniform()
|
|
s.Initialize(uint64(len(allBootstrappers)))
|
|
indices, _ := s.Sample(count)
|
|
|
|
sampled := make([]Bootstrapper, 0, len(indices))
|
|
for _, index := range indices {
|
|
sampled = append(sampled, allBootstrappers[int(index)])
|
|
}
|
|
return sampled, nil
|
|
}
|
|
|
|
// StakingConfig is the staking configuration with time.Duration types
|
|
type StakingConfig struct {
|
|
UptimeRequirement float64
|
|
MinValidatorStake uint64
|
|
MaxValidatorStake uint64
|
|
MinDelegatorStake uint64
|
|
MinDelegationFee uint32
|
|
MinStakeDuration time.Duration
|
|
MaxStakeDuration time.Duration
|
|
RewardConfig reward.Config
|
|
|
|
// BLS key information for genesis replay
|
|
NodeID string `json:"nodeID"`
|
|
BLSPublicKey []byte `json:"blsPublicKey"`
|
|
BLSProofOfPossession []byte `json:"blsProofOfPossession"`
|
|
}
|
|
|
|
// GetStakingConfig returns the staking config with time.Duration types
|
|
func GetStakingConfig(networkID uint32) StakingConfig {
|
|
cfg := genesiscfg.GetStakingConfig(networkID)
|
|
return StakingConfig{
|
|
UptimeRequirement: cfg.UptimeRequirement,
|
|
MinValidatorStake: cfg.MinValidatorStake,
|
|
MaxValidatorStake: cfg.MaxValidatorStake,
|
|
MinDelegatorStake: cfg.MinDelegatorStake,
|
|
MinDelegationFee: cfg.MinDelegationFee,
|
|
MinStakeDuration: time.Duration(cfg.MinStakeDuration) * time.Second,
|
|
MaxStakeDuration: time.Duration(cfg.MaxStakeDuration) * time.Second,
|
|
RewardConfig: reward.Config{
|
|
MaxConsumptionRate: cfg.RewardConfig.MaxConsumptionRate,
|
|
MinConsumptionRate: cfg.RewardConfig.MinConsumptionRate,
|
|
MintingPeriod: time.Duration(cfg.RewardConfig.MintingPeriod) * time.Second,
|
|
SupplyCap: cfg.RewardConfig.SupplyCap,
|
|
},
|
|
}
|
|
}
|
|
|
|
// TxFeeConfig contains transaction fee configuration
|
|
// This includes the basic fee config from genesis plus dynamic/validator fees
|
|
type TxFeeConfig struct {
|
|
TxFee uint64 `json:"txFee"`
|
|
CreateAssetTxFee uint64 `json:"createAssetTxFee"`
|
|
DynamicFeeConfig gas.Config `json:"dynamicFeeConfig"`
|
|
ValidatorFeeConfig fee.Config `json:"validatorFeeConfig"`
|
|
}
|
|
|
|
// Default dynamic fee parameters
|
|
var (
|
|
MainnetDynamicFeeConfig = gas.Config{
|
|
Weights: gas.Dimensions{
|
|
gas.Bandwidth: 1,
|
|
gas.DBRead: 1,
|
|
gas.DBWrite: 1,
|
|
gas.Compute: 1,
|
|
},
|
|
MaxCapacity: 1_000_000,
|
|
MaxPerSecond: 100_000,
|
|
TargetPerSecond: 50_000,
|
|
MinPrice: 1,
|
|
ExcessConversionConstant: 5_000,
|
|
}
|
|
|
|
TestnetDynamicFeeConfig = gas.Config{
|
|
Weights: gas.Dimensions{
|
|
gas.Bandwidth: 1,
|
|
gas.DBRead: 1,
|
|
gas.DBWrite: 1,
|
|
gas.Compute: 1,
|
|
},
|
|
MaxCapacity: 1_000_000,
|
|
MaxPerSecond: 100_000,
|
|
TargetPerSecond: 50_000,
|
|
MinPrice: 1,
|
|
ExcessConversionConstant: 5_000,
|
|
}
|
|
|
|
LocalDynamicFeeConfig = gas.Config{
|
|
Weights: gas.Dimensions{
|
|
gas.Bandwidth: 1,
|
|
gas.DBRead: 1,
|
|
gas.DBWrite: 1,
|
|
gas.Compute: 1,
|
|
},
|
|
MaxCapacity: 1_000_000,
|
|
MaxPerSecond: 100_000,
|
|
TargetPerSecond: 50_000,
|
|
MinPrice: 1,
|
|
ExcessConversionConstant: 5_000,
|
|
}
|
|
|
|
MainnetValidatorFeeConfig = fee.Config{
|
|
Capacity: 20_000,
|
|
Target: 10_000,
|
|
MinPrice: 512,
|
|
ExcessConversionConstant: 1_587,
|
|
}
|
|
|
|
TestnetValidatorFeeConfig = fee.Config{
|
|
Capacity: 20_000,
|
|
Target: 10_000,
|
|
MinPrice: 512,
|
|
ExcessConversionConstant: 1_587,
|
|
}
|
|
|
|
LocalValidatorFeeConfig = fee.Config{
|
|
Capacity: 20_000,
|
|
Target: 10_000,
|
|
MinPrice: 512,
|
|
ExcessConversionConstant: 1_587,
|
|
}
|
|
)
|
|
|
|
// GetTxFeeConfig returns the tx fee config
|
|
func GetTxFeeConfig(networkID uint32) TxFeeConfig {
|
|
cfg := genesiscfg.GetTxFeeConfig(networkID)
|
|
|
|
var dynamicCfg gas.Config
|
|
var validatorCfg fee.Config
|
|
|
|
switch networkID {
|
|
case constants.MainnetID:
|
|
dynamicCfg = MainnetDynamicFeeConfig
|
|
validatorCfg = MainnetValidatorFeeConfig
|
|
case constants.TestnetID:
|
|
dynamicCfg = TestnetDynamicFeeConfig
|
|
validatorCfg = TestnetValidatorFeeConfig
|
|
default:
|
|
dynamicCfg = LocalDynamicFeeConfig
|
|
validatorCfg = LocalValidatorFeeConfig
|
|
}
|
|
|
|
return TxFeeConfig{
|
|
TxFee: cfg.TxFee,
|
|
CreateAssetTxFee: cfg.CreateAssetTxFee,
|
|
DynamicFeeConfig: dynamicCfg,
|
|
ValidatorFeeConfig: validatorCfg,
|
|
}
|
|
}
|
|
|
|
// GetConfig returns the genesis config for the given network ID
|
|
func GetConfig(networkID uint32) *genesiscfg.Config {
|
|
// Use embedded genesis configs (//go:embed) first.
|
|
// The genesis/pkg/genesis.GetConfig() checks filesystem paths which
|
|
// don't exist in Docker containers, returning an empty config.
|
|
if cfg, err := genesisconfigs.GetConfig(networkID); err == nil && len(cfg.Allocations) > 0 {
|
|
return cfg
|
|
}
|
|
// Fallback to filesystem-based config (local dev)
|
|
return genesiscfg.GetConfig(networkID)
|
|
}
|
|
|
|
// FromConfig builds genesis bytes from a config
|
|
func FromConfig(config *genesiscfg.Config) ([]byte, ids.ID, error) {
|
|
// Build XVM (X-Chain) genesis
|
|
lux := exchangevm.GenesisAssetDefinition{
|
|
Name: "Lux",
|
|
Symbol: "LUX",
|
|
Denomination: 9,
|
|
InitialState: exchangevm.AssetInitialState{},
|
|
}
|
|
memoBytes := []byte{}
|
|
|
|
// Sort allocations for deterministic output
|
|
type allocation struct {
|
|
EVMAddr ids.ShortID
|
|
UTXOAddr ids.ShortID
|
|
InitialAmount uint64
|
|
}
|
|
xAllocations := []allocation{}
|
|
for _, a := range config.Allocations {
|
|
if a.InitialAmount > 0 {
|
|
xAllocations = append(xAllocations, allocation{
|
|
EVMAddr: a.EVMAddr,
|
|
UTXOAddr: a.UTXOAddr,
|
|
InitialAmount: a.InitialAmount,
|
|
})
|
|
}
|
|
}
|
|
|
|
// Get HRP for this network to format bech32 addresses
|
|
hrp := constants.GetHRP(config.NetworkID)
|
|
|
|
for _, a := range xAllocations {
|
|
// Format address as bech32 for the X-Chain
|
|
bech32Addr, err := address.FormatBech32(hrp, a.UTXOAddr[:])
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to format bech32 address: %w", err)
|
|
}
|
|
lux.InitialState.FixedCap = append(lux.InitialState.FixedCap, exchangevm.GenesisHolder{
|
|
Amount: a.InitialAmount,
|
|
Address: bech32Addr,
|
|
})
|
|
// Add ETH address to memo for reference
|
|
ethAddrStr := a.EVMAddr.Hex()
|
|
if len(ethAddrStr) > 2 { // "0x" prefix
|
|
memoBytes = append(memoBytes, []byte(ethAddrStr[2:])...)
|
|
}
|
|
}
|
|
lux.Memo = memoBytes
|
|
|
|
xvmGenesis, err := exchangevm.NewGenesis(
|
|
config.NetworkID,
|
|
map[string]exchangevm.GenesisAssetDefinition{
|
|
"LUX": lux,
|
|
},
|
|
)
|
|
if err != nil {
|
|
return nil, ids.Empty, err
|
|
}
|
|
xvmGenesisBytes, err := xvmGenesis.Bytes()
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("couldn't serialize xvm genesis: %w", err)
|
|
}
|
|
|
|
// LUX asset ID is a network-wide constant (constants.UTXO_ASSET_ID), not
|
|
// derived from X-Chain genesis bytes. This decouples the asset from the
|
|
// X-Chain so X-Chain can be made optional for P-only L2s.
|
|
//
|
|
// We still build xvmGenesisBytes above so X-Chain (when baked) has a
|
|
// consistent initial-supply view, but the asset ID itself is the
|
|
// deterministic constant — all chains reference the same ID regardless
|
|
// of whether X-Chain is part of the chain set.
|
|
_ = xvmGenesisBytes // bytes still used downstream when X-Chain is baked
|
|
xAssetID := constants.UTXO_ASSET_ID
|
|
|
|
genesisTime := time.Unix(int64(config.StartTime), 0)
|
|
|
|
// Calculate initial supply
|
|
initialSupply := uint64(0)
|
|
for _, a := range config.Allocations {
|
|
initialSupply += a.InitialAmount
|
|
for _, unlock := range a.UnlockSchedule {
|
|
initialSupply += unlock.Amount
|
|
}
|
|
}
|
|
|
|
// Build platform allocations
|
|
initiallyStaked := set.Set[ids.ShortID]{}
|
|
for _, addr := range config.InitialStakedFunds {
|
|
initiallyStaked.Add(addr)
|
|
}
|
|
|
|
platformAllocations := []genesis.Allocation{}
|
|
skippedAllocations := []genesiscfg.Allocation{}
|
|
for _, a := range config.Allocations {
|
|
if initiallyStaked.Contains(a.UTXOAddr) {
|
|
skippedAllocations = append(skippedAllocations, a)
|
|
continue
|
|
}
|
|
for _, unlock := range a.UnlockSchedule {
|
|
if unlock.Amount > 0 {
|
|
// Format address as bech32 for the P-Chain
|
|
bech32Addr, err := address.FormatBech32(hrp, a.UTXOAddr[:])
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to format bech32 address for P-chain: %w", err)
|
|
}
|
|
platformAllocations = append(platformAllocations, genesis.Allocation{
|
|
Locktime: unlock.Locktime,
|
|
Amount: unlock.Amount,
|
|
Address: bech32Addr,
|
|
Message: a.EVMAddr.Bytes(),
|
|
})
|
|
}
|
|
}
|
|
|
|
// Also create P-Chain UTXO for initialAmount (spendable, no locktime)
|
|
if a.InitialAmount > 0 {
|
|
bech32Addr, err := address.FormatBech32(hrp, a.UTXOAddr[:])
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to format bech32 address for P-chain initialAmount: %w", err)
|
|
}
|
|
platformAllocations = append(platformAllocations, genesis.Allocation{
|
|
Locktime: 0, // immediately spendable
|
|
Amount: a.InitialAmount,
|
|
Address: bech32Addr,
|
|
Message: a.EVMAddr.Bytes(),
|
|
})
|
|
}
|
|
}
|
|
|
|
// Build validators
|
|
validators := []genesis.PermissionlessValidator{}
|
|
allNodeAllocations := splitAllocations(skippedAllocations, len(config.InitialStakers))
|
|
endStakingTime := genesisTime.Add(time.Duration(config.InitialStakeDuration) * time.Second)
|
|
stakingOffset := time.Duration(0)
|
|
|
|
for i, staker := range config.InitialStakers {
|
|
// Safely get node allocations (may be empty if no initialStakedFunds)
|
|
var nodeAllocations []genesiscfg.Allocation
|
|
if i < len(allNodeAllocations) {
|
|
nodeAllocations = allNodeAllocations[i]
|
|
}
|
|
|
|
// Use explicit staker times if provided, otherwise use calculated values
|
|
startTime := uint64(genesisTime.Unix())
|
|
if staker.StartTime > 0 {
|
|
startTime = staker.StartTime
|
|
}
|
|
|
|
endTime := endStakingTime.Add(-stakingOffset)
|
|
stakingOffset += time.Duration(config.InitialStakeDurationOffset) * time.Second
|
|
endTimeUnix := uint64(endTime.Unix())
|
|
if staker.EndTime > 0 {
|
|
endTimeUnix = staker.EndTime
|
|
}
|
|
|
|
allocations := []genesis.Allocation{}
|
|
for _, a := range nodeAllocations {
|
|
for _, unlock := range a.UnlockSchedule {
|
|
// Format address as bech32 for staker allocations
|
|
bech32Addr, err := address.FormatBech32(hrp, a.UTXOAddr[:])
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to format bech32 address for staker allocation: %w", err)
|
|
}
|
|
allocations = append(allocations, genesis.Allocation{
|
|
Locktime: unlock.Locktime,
|
|
Amount: unlock.Amount,
|
|
Address: bech32Addr,
|
|
Message: a.EVMAddr.Bytes(),
|
|
})
|
|
}
|
|
}
|
|
|
|
// Calculate weight from allocations or use explicit weight
|
|
weight := staker.Weight
|
|
if weight == 0 {
|
|
for _, a := range allocations {
|
|
weight += a.Amount
|
|
}
|
|
}
|
|
|
|
// Format reward address as bech32
|
|
rewardBech32, err := address.FormatBech32(hrp, staker.RewardAddress[:])
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to format bech32 reward address: %w", err)
|
|
}
|
|
|
|
// Parse the BLS proof of possession if present
|
|
var blsSigner *signer.ProofOfPossession
|
|
if staker.Signer != nil {
|
|
blsSigner, err = parseProofOfPossession(staker.Signer)
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to parse proof of possession for staker %d: %w", i, err)
|
|
}
|
|
}
|
|
|
|
validators = append(validators, genesis.PermissionlessValidator{
|
|
Validator: genesis.Validator{
|
|
StartTime: startTime,
|
|
EndTime: endTimeUnix,
|
|
Weight: weight,
|
|
NodeID: staker.NodeID,
|
|
},
|
|
RewardOwner: &genesis.Owner{
|
|
Threshold: 1,
|
|
Addresses: []string{rewardBech32},
|
|
},
|
|
Staked: allocations,
|
|
ExactDelegationFee: staker.DelegationFee,
|
|
Signer: blsSigner,
|
|
})
|
|
}
|
|
|
|
// Primary-network chain set is data-driven.
|
|
//
|
|
// Mandatory:
|
|
// P-Chain — implicit (the platform genesis itself).
|
|
// X-Chain — staking and tx-fee UTXOs are anchored here; removing it
|
|
// requires a new native fee asset. Always baked.
|
|
//
|
|
// Opt-in (every other chain):
|
|
// Each XChainGenesis string in the config is the gate. Non-empty →
|
|
// the chain is included in the primary-network CreateChainTx set.
|
|
// Downstream forks (Liquidity etc.) that only want P+X just leave
|
|
// their other genesis fields empty in the config JSON / shard tree;
|
|
// no env knob per chain, no compile-time hack.
|
|
//
|
|
// Runtime tracking is separate: an operator decides which of the
|
|
// baked chains this node actually runs via --track-chains /
|
|
// --track-all-chains. Baked-but-untracked chains stay dormant.
|
|
chains := []genesis.Chain{}
|
|
|
|
// X-Chain — staking + LUX asset, always present.
|
|
chains = append(chains, genesis.Chain{
|
|
GenesisData: xvmGenesisBytes,
|
|
ChainID: constants.PrimaryNetworkID,
|
|
VMID: constants.XVMID,
|
|
FxIDs: []ids.ID{
|
|
secp256k1fx.ID,
|
|
nftfx.ID,
|
|
propertyfx.ID,
|
|
mldsafx.ID,
|
|
slhdsafx.ID,
|
|
ed25519fx.ID,
|
|
secp256r1fx.ID,
|
|
schnorrfx.ID,
|
|
bls12381fx.ID,
|
|
},
|
|
Name: "X-Chain",
|
|
})
|
|
|
|
// Every other chain is opt-in via a non-empty genesis string in the
|
|
// resolved Config. Table-driven so adding a new primary-network chain
|
|
// is one row, not a new env knob.
|
|
optIn := []struct {
|
|
genesisData string
|
|
vmID ids.ID
|
|
name string
|
|
}{
|
|
{config.CChainGenesis, constants.EVMID, "C-Chain"},
|
|
{config.DChainGenesis, constants.DexVMID, "D-Chain"},
|
|
{config.BChainGenesis, constants.BridgeVMID, "B-Chain"},
|
|
{config.TChainGenesis, constants.ThresholdVMID, "T-Chain"},
|
|
{config.QChainGenesis, constants.QuantumVMID, "Q-Chain"},
|
|
{config.ZChainGenesis, constants.ZKVMID, "Z-Chain"},
|
|
}
|
|
for _, c := range optIn {
|
|
if c.genesisData == "" {
|
|
continue
|
|
}
|
|
chains = append(chains, genesis.Chain{
|
|
GenesisData: []byte(c.genesisData),
|
|
ChainID: constants.PrimaryNetworkID,
|
|
VMID: c.vmID,
|
|
Name: c.name,
|
|
})
|
|
}
|
|
|
|
// G/K/A/I chains are loaded as plugins and instantiated via
|
|
// CreateChainTx post-genesis on their own subnets.
|
|
|
|
pChainGenesis, err := genesis.New(
|
|
xAssetID,
|
|
config.NetworkID,
|
|
platformAllocations,
|
|
validators,
|
|
chains,
|
|
config.StartTime,
|
|
initialSupply,
|
|
config.Message,
|
|
)
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("problem while building platform chain's genesis state: %w", err)
|
|
}
|
|
pChainGenesisBytes, err := pChainGenesis.Bytes()
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("problem while serializing platform chain's genesis state: %w", err)
|
|
}
|
|
return pChainGenesisBytes, xAssetID, nil
|
|
}
|
|
|
|
// FromFile loads genesis config from file and builds genesis bytes.
|
|
// Caller owns the choice — if a genesis file is set, we use it. No
|
|
// "is this networkID standard?" guard, no allow-flag. Operator-owned
|
|
// chainset.
|
|
func FromFile(networkID uint32, filepath string, stakingCfg *StakingConfig) ([]byte, ids.ID, error) {
|
|
config, err := genesiscfg.GetConfigFile(filepath)
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to load genesis file %s: %w", filepath, err)
|
|
}
|
|
if err := validateConfig(networkID, config, stakingCfg); err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("genesis config validation failed: %w", err)
|
|
}
|
|
return FromConfig(config)
|
|
}
|
|
|
|
// FromFlag parses base64-encoded genesis content and builds genesis bytes.
|
|
// Same contract as FromFile — caller owns the override.
|
|
func FromFlag(networkID uint32, genesisContent string, stakingCfg *StakingConfig) ([]byte, ids.ID, error) {
|
|
data, err := base64.StdEncoding.DecodeString(genesisContent)
|
|
if err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to decode base64 genesis content: %w", err)
|
|
}
|
|
var config genesiscfg.Config
|
|
if err := json.Unmarshal(data, &config); err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("failed to parse genesis config: %w", err)
|
|
}
|
|
if err := validateConfig(networkID, &config, stakingCfg); err != nil {
|
|
return nil, ids.Empty, fmt.Errorf("genesis config validation failed: %w", err)
|
|
}
|
|
return FromConfig(&config)
|
|
}
|
|
|
|
// FromDatabase returns genesis data for database replay mode
|
|
func FromDatabase(networkID uint32, dbPath string, dbType string, stakingCfg *StakingConfig) ([]byte, ids.ID, error) {
|
|
config := genesiscfg.GetConfig(constants.LocalID)
|
|
config.NetworkID = networkID
|
|
config.Message = "DATABASE_REPLAY_MODE"
|
|
return FromConfig(config)
|
|
}
|
|
|
|
// VMGenesis returns the genesis tx for a specific VM
|
|
func VMGenesis(genesisBytes []byte, vmID ids.ID) (*pchaintxs.Tx, error) {
|
|
gen, err := genesis.Parse(genesisBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to parse genesis: %w", err)
|
|
}
|
|
for _, chain := range gen.Chains {
|
|
uChain := chain.Unsigned.(*pchaintxs.CreateChainTx)
|
|
if uChain.VMID == vmID {
|
|
return chain, nil
|
|
}
|
|
}
|
|
return nil, fmt.Errorf("couldn't find blockchain with VM ID %s", vmID)
|
|
}
|
|
|
|
// Aliases returns the default aliases for chains and APIs
|
|
func Aliases(genesisBytes []byte) (map[string][]string, map[ids.ID][]string, error) {
|
|
apiAliases := map[string][]string{
|
|
path.Join(constants.ChainAliasPrefix, constants.PlatformChainID.String()): {
|
|
"P",
|
|
"platform",
|
|
path.Join(constants.ChainAliasPrefix, "P"),
|
|
path.Join(constants.ChainAliasPrefix, "platform"),
|
|
},
|
|
}
|
|
chainAliases := map[ids.ID][]string{
|
|
constants.PlatformChainID: PChainAliases,
|
|
}
|
|
|
|
gen, err := genesis.Parse(genesisBytes)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
for _, chain := range gen.Chains {
|
|
uChain := chain.Unsigned.(*pchaintxs.CreateChainTx)
|
|
chainID := chain.ID()
|
|
endpoint := path.Join(constants.ChainAliasPrefix, chainID.String())
|
|
switch uChain.VMID {
|
|
case constants.XVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"X",
|
|
"xvm",
|
|
path.Join(constants.ChainAliasPrefix, "X"),
|
|
path.Join(constants.ChainAliasPrefix, "xvm"),
|
|
}
|
|
chainAliases[chainID] = XChainAliases
|
|
case constants.EVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"C",
|
|
"evm",
|
|
path.Join(constants.ChainAliasPrefix, "C"),
|
|
path.Join(constants.ChainAliasPrefix, "evm"),
|
|
}
|
|
chainAliases[chainID] = CChainAliases
|
|
case constants.DexVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"D",
|
|
"dex",
|
|
"dexvm",
|
|
path.Join(constants.ChainAliasPrefix, "D"),
|
|
path.Join(constants.ChainAliasPrefix, "dex"),
|
|
path.Join(constants.ChainAliasPrefix, "dexvm"),
|
|
}
|
|
chainAliases[chainID] = DChainAliases
|
|
case constants.QuantumVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"Q",
|
|
"quantum",
|
|
"quantumvm",
|
|
"pq",
|
|
path.Join(constants.ChainAliasPrefix, "Q"),
|
|
path.Join(constants.ChainAliasPrefix, "quantum"),
|
|
}
|
|
chainAliases[chainID] = QChainAliases
|
|
case constants.AIVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"A",
|
|
"attest",
|
|
"ai",
|
|
"aivm",
|
|
path.Join(constants.ChainAliasPrefix, "A"),
|
|
path.Join(constants.ChainAliasPrefix, "attest"),
|
|
}
|
|
chainAliases[chainID] = AChainAliases
|
|
case constants.BridgeVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"B",
|
|
"bridge",
|
|
"bridgevm",
|
|
path.Join(constants.ChainAliasPrefix, "B"),
|
|
path.Join(constants.ChainAliasPrefix, "bridge"),
|
|
}
|
|
chainAliases[chainID] = BChainAliases
|
|
case constants.ThresholdVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"T",
|
|
"threshold",
|
|
"thresholdvm",
|
|
"mpc",
|
|
path.Join(constants.ChainAliasPrefix, "T"),
|
|
path.Join(constants.ChainAliasPrefix, "threshold"),
|
|
}
|
|
chainAliases[chainID] = TChainAliases
|
|
case constants.ZKVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"Z",
|
|
"zk",
|
|
"zkvm",
|
|
path.Join(constants.ChainAliasPrefix, "Z"),
|
|
path.Join(constants.ChainAliasPrefix, "zk"),
|
|
}
|
|
chainAliases[chainID] = ZChainAliases
|
|
case constants.GraphVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"G",
|
|
"graph",
|
|
"graphvm",
|
|
"dgraph",
|
|
path.Join(constants.ChainAliasPrefix, "G"),
|
|
path.Join(constants.ChainAliasPrefix, "graph"),
|
|
}
|
|
chainAliases[chainID] = GChainAliases
|
|
case constants.KeyVMID:
|
|
apiAliases[endpoint] = []string{
|
|
"K",
|
|
"kms",
|
|
"keyvm",
|
|
path.Join(constants.ChainAliasPrefix, "K"),
|
|
path.Join(constants.ChainAliasPrefix, "kms"),
|
|
}
|
|
chainAliases[chainID] = KChainAliases
|
|
}
|
|
}
|
|
return apiAliases, chainAliases, nil
|
|
}
|
|
|
|
// XAssetID returns the LUX asset ID from XVM genesis bytes
|
|
func XAssetID(xvmGenesisBytes []byte) (ids.ID, error) {
|
|
parser, err := xchaintxs.NewParser(
|
|
[]fxs.Fx{
|
|
&secp256k1fx.Fx{},
|
|
},
|
|
)
|
|
if err != nil {
|
|
return ids.Empty, err
|
|
}
|
|
|
|
genesisCodec := parser.GenesisCodec()
|
|
gen := exchangevm.Genesis{}
|
|
if _, err := genesisCodec.Unmarshal(xvmGenesisBytes, &gen); err != nil {
|
|
return ids.Empty, err
|
|
}
|
|
|
|
if len(gen.Txs) == 0 {
|
|
return ids.Empty, errNoTxs
|
|
}
|
|
genesisTx := gen.Txs[0]
|
|
|
|
tx := xchaintxs.Tx{Unsigned: &genesisTx.CreateAssetTx}
|
|
if err := tx.Initialize(genesisCodec); err != nil {
|
|
return ids.Empty, err
|
|
}
|
|
return tx.ID(), nil
|
|
}
|
|
|
|
// validateConfig validates the genesis config
|
|
func validateConfig(networkID uint32, config *genesiscfg.Config, stakingCfg *StakingConfig) error {
|
|
if config.NetworkID != networkID {
|
|
return fmt.Errorf("network ID mismatch: expected %d, got %d", networkID, config.NetworkID)
|
|
}
|
|
if config.InitialStakeDuration > uint64(stakingCfg.MaxStakeDuration.Seconds()) {
|
|
return fmt.Errorf("initial stake duration %d exceeds max %d", config.InitialStakeDuration, uint64(stakingCfg.MaxStakeDuration.Seconds()))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DevModeConfig holds configuration for dev mode genesis
|
|
type DevModeConfig struct {
|
|
NodeID ids.NodeID // The validator node ID
|
|
BLSPublicKey string // BLS public key hex
|
|
BLSPopProof string // BLS proof of possession hex
|
|
RewardAddress ids.ShortID // Reward/allocation address
|
|
CChainGenesis string // C-Chain genesis JSON
|
|
StartTime uint64 // Genesis start time (if 0, uses time.Now())
|
|
}
|
|
|
|
// ForDevMode creates a genesis configuration suitable for single-node development mode.
|
|
// It creates a single validator with far-future stake time and funds the treasury address.
|
|
func ForDevMode(cfg DevModeConfig, stakingCfg *StakingConfig) ([]byte, ids.ID, error) {
|
|
// Genesis start time: use provided time or fall back to now
|
|
startTime := cfg.StartTime
|
|
if startTime == 0 {
|
|
startTime = uint64(time.Now().Unix())
|
|
}
|
|
|
|
// Far-future stake duration: 100 years in seconds
|
|
// This ensures the validator never expires during development
|
|
const hundredYears = 100 * 365 * 24 * 60 * 60
|
|
|
|
// Create allocation for the reward address
|
|
// Initial staked amount: 1B LUX (enough to be a validator)
|
|
const oneMillionLUX = 1_000_000_000_000_000 // 1M LUX in nLUX
|
|
const oneBillionLUX = 1_000_000_000_000_000_000 // 1B LUX in nLUX
|
|
|
|
allocation := genesiscfg.Allocation{
|
|
EVMAddr: cfg.RewardAddress, // Same as LUX addr for simplicity
|
|
UTXOAddr: cfg.RewardAddress,
|
|
InitialAmount: oneMillionLUX, // Initial unlocked amount
|
|
UnlockSchedule: []genesiscfg.LockedAmount{
|
|
{
|
|
Amount: oneBillionLUX, // Staked amount
|
|
Locktime: 0, // No lock time
|
|
},
|
|
},
|
|
}
|
|
|
|
// Create the single staker
|
|
var signer *genesiscfg.ProofOfPossession
|
|
if cfg.BLSPublicKey != "" && cfg.BLSPopProof != "" {
|
|
signer = &genesiscfg.ProofOfPossession{
|
|
PublicKey: cfg.BLSPublicKey,
|
|
ProofOfPossession: cfg.BLSPopProof,
|
|
}
|
|
}
|
|
|
|
staker := genesiscfg.Staker{
|
|
NodeID: cfg.NodeID,
|
|
RewardAddress: cfg.RewardAddress,
|
|
DelegationFee: 1000000, // 100% delegation fee (no delegators in dev mode)
|
|
Signer: signer,
|
|
Weight: oneBillionLUX,
|
|
StartTime: startTime,
|
|
EndTime: startTime + hundredYears,
|
|
}
|
|
|
|
// Build the genesis config
|
|
config := &genesiscfg.Config{
|
|
NetworkID: constants.LocalID,
|
|
Allocations: []genesiscfg.Allocation{allocation},
|
|
StartTime: startTime,
|
|
InitialStakeDuration: hundredYears,
|
|
InitialStakeDurationOffset: 0,
|
|
InitialStakedFunds: []ids.ShortID{cfg.RewardAddress},
|
|
InitialStakers: []genesiscfg.Staker{staker},
|
|
CChainGenesis: cfg.CChainGenesis,
|
|
Message: "Lux Development Mode Genesis",
|
|
}
|
|
|
|
return FromConfig(config)
|
|
}
|
|
|
|
// splitAllocations splits allocations across multiple stakers
|
|
func splitAllocations(allocations []genesiscfg.Allocation, numSplits int) [][]genesiscfg.Allocation {
|
|
if numSplits == 0 {
|
|
return [][]genesiscfg.Allocation{}
|
|
}
|
|
|
|
totalAmount := uint64(0)
|
|
for _, a := range allocations {
|
|
for _, unlock := range a.UnlockSchedule {
|
|
totalAmount += unlock.Amount
|
|
}
|
|
}
|
|
|
|
nodeWeight := totalAmount / uint64(numSplits)
|
|
allNodeAllocations := make([][]genesiscfg.Allocation, 0, numSplits)
|
|
|
|
currentNodeAllocation := []genesiscfg.Allocation{}
|
|
currentNodeAmount := uint64(0)
|
|
|
|
for _, allocation := range allocations {
|
|
currentAllocation := allocation
|
|
currentAllocation.InitialAmount = 0
|
|
currentAllocation.UnlockSchedule = nil
|
|
|
|
for _, unlock := range allocation.UnlockSchedule {
|
|
for currentNodeAmount+unlock.Amount > nodeWeight && len(allNodeAllocations) < numSplits-1 {
|
|
amountToAdd := nodeWeight - currentNodeAmount
|
|
currentAllocation.UnlockSchedule = append(currentAllocation.UnlockSchedule, genesiscfg.LockedAmount{
|
|
Amount: amountToAdd,
|
|
Locktime: unlock.Locktime,
|
|
})
|
|
unlock.Amount -= amountToAdd
|
|
|
|
currentNodeAllocation = append(currentNodeAllocation, currentAllocation)
|
|
allNodeAllocations = append(allNodeAllocations, currentNodeAllocation)
|
|
|
|
currentNodeAllocation = nil
|
|
currentNodeAmount = 0
|
|
|
|
currentAllocation = allocation
|
|
currentAllocation.InitialAmount = 0
|
|
currentAllocation.UnlockSchedule = nil
|
|
}
|
|
|
|
if unlock.Amount == 0 {
|
|
continue
|
|
}
|
|
|
|
currentAllocation.UnlockSchedule = append(currentAllocation.UnlockSchedule, genesiscfg.LockedAmount{
|
|
Amount: unlock.Amount,
|
|
Locktime: unlock.Locktime,
|
|
})
|
|
currentNodeAmount += unlock.Amount
|
|
}
|
|
|
|
if len(currentAllocation.UnlockSchedule) > 0 {
|
|
currentNodeAllocation = append(currentNodeAllocation, currentAllocation)
|
|
}
|
|
}
|
|
|
|
return append(allNodeAllocations, currentNodeAllocation)
|
|
}
|