bridgevm

package
v1.2.7 Latest Latest
Warning

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

Go to latest
Published: May 28, 2026 License: BSD-3-Clause Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultBridgeFeeRate = 0.01  // 1% on Lux-family exits
	DefaultSlippage      = 0.025 // 2.5% min-receive tolerance
	DefaultEstimatedTime = 180   // seconds
	DefaultAvgCompletion = "00:03:00"
)

Defaults match the historical SDK assumptions so the on-wire shape stays stable across the daemon migration.

Variables

View Source
var (
	// ErrMessageNotSigned is returned when a bridge message lacks required signatures
	ErrMessageNotSigned = errors.New("bridge message not signed")

	// ErrInvalidBridgeSignature is returned when signature verification fails
	ErrInvalidBridgeSignature = errors.New("invalid bridge signature")

	// ErrDeliveryNotConfirmed is returned when message delivery is not confirmed
	ErrDeliveryNotConfirmed = errors.New("delivery not confirmed")
)
View Source
var (
	// ErrInsufficientSigners is returned when there aren't enough active signers
	ErrInsufficientSigners = errors.New("insufficient active signers for threshold")

	// ErrSigningTimeout is returned when signing times out
	ErrSigningTimeout = errors.New("signing timeout")

	// ErrInvalidShare is returned when a signature share is invalid
	ErrInvalidShare = errors.New("invalid signature share")

	// ErrNoKeyShare is returned when the node doesn't have a key share
	ErrNoKeyShare = errors.New("no key share available")
)
View Source
var ErrPriceUnknown = errors.New("bridgevm: price unknown for asset")

ErrPriceUnknown is returned by PriceFeed.Price when the asset is not priced. The RPC layer maps this to JSON-RPC code -32004 so callers (e.g. the daemon) can distinguish "transient miss" from "invalid params".

View Source
var ErrSwapNotFound = errors.New("bridgevm: swap not found")

ErrSwapNotFound is returned by Get / Patch when the id isn't present. Distinct from other failures so callers can branch on it.

View Source
var VMID = ids.ID{'b', 'r', 'i', 'd', 'g', 'e', 'v', 'm', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

VMID is the unique identifier for BridgeVM (B-Chain)

View Source
var (
	Version = &version.Semantic{
		Major: 1,
		Minor: 0,
		Patch: 0,
	}
)

Functions

This section is empty.

Types

type Block

type Block struct {
	ParentID_      ids.ID           `json:"parentId"` // Field renamed to avoid method collision
	BlockHeight    uint64           `json:"height"`
	BlockTimestamp int64            `json:"timestamp"`
	BridgeRequests []*BridgeRequest `json:"bridgeRequests"`

	// MPC signatures for this block (NodeID -> signature bytes)
	MPCSignatures map[ids.NodeID][]byte `json:"mpcSignatures"`

	// Cached values
	ID_ ids.ID
	// contains filtered or unexported fields
}

Block represents a block in the Bridge chain

func (*Block) Accept

func (b *Block) Accept(ctx context.Context) error

Accept marks the block as accepted

func (*Block) Bytes

func (b *Block) Bytes() []byte

Bytes returns the block bytes

func (*Block) Height

func (b *Block) Height() uint64

Height returns the block height

func (*Block) ID

func (b *Block) ID() ids.ID

ID returns the block ID

func (*Block) Parent

func (b *Block) Parent() ids.ID

Parent returns the parent block (for block.Block interface compatibility)

func (*Block) ParentID

func (b *Block) ParentID() ids.ID

ParentID returns the parent block ID

func (*Block) Reject

func (b *Block) Reject(ctx context.Context) error

Reject marks the block as rejected

func (*Block) Status

func (b *Block) Status() uint8

Status returns the block's status

func (*Block) Timestamp

func (b *Block) Timestamp() time.Time

Timestamp returns the block timestamp

func (*Block) Verify

func (b *Block) Verify(ctx context.Context) error

Verify verifies the block

type BridgeConfig

type BridgeConfig struct {
	// MPC configuration for secure cross-chain operations
	MPCThreshold    int `json:"mpcThreshold"`    // t: Threshold (t+1 parties needed)
	MPCTotalParties int `json:"mpcTotalParties"` // n: Total number of MPC nodes

	// Bridge parameters
	MinConfirmations uint32 `json:"minConfirmations"` // Confirmations required before bridging
	BridgeFee        uint64 `json:"bridgeFee"`        // Fee in LUX for bridge operations

	// Supported chains
	SupportedChains []string `json:"supportedChains"` // Chain IDs that can be bridged

	// Security settings
	MaxBridgeAmount      uint64 `json:"maxBridgeAmount"`      // Maximum amount per bridge transaction
	DailyBridgeLimit     uint64 `json:"dailyBridgeLimit"`     // Daily limit for bridge operations
	RequireValidatorBond uint64 `json:"requireValidatorBond"` // 1M LUX bond required (slashable, NOT staked)

	// LP-333: Opt-in Signer Set Management
	MaxSigners     int     `json:"maxSigners"`     // Maximum signers before set is frozen (default: 100)
	ThresholdRatio float64 `json:"thresholdRatio"` // Threshold as ratio of signers (default: 0.67 = 2/3)
}

BridgeConfig contains VM configuration

type BridgeMessage

type BridgeMessage struct {
	// Message identification
	ID        ids.ID    `json:"id"`
	Nonce     uint64    `json:"nonce"`
	Timestamp time.Time `json:"timestamp"`

	// Chain routing
	SourceChain string `json:"sourceChain"`
	DestChain   string `json:"destChain"`

	// Asset transfer
	Asset     ids.ID `json:"asset"`
	Amount    uint64 `json:"amount"`
	Recipient []byte `json:"recipient"`
	Sender    []byte `json:"sender"`

	// Source transaction proof
	SourceTxID    ids.ID `json:"sourceTxId"`
	Confirmations uint32 `json:"confirmations"`

	// Threshold signature
	Signature []byte `json:"signature"`
	SignedBy  []int  `json:"signedBy"` // Indices of signers who participated

	// Fee is the user-paid tx burn in nLUX. Must be >=
	// fee.MinTxFeeFloor; refused at the fee gate before any MPC
	// signing capacity is consumed.
	Fee uint64 `json:"fee"`

	// Delivery confirmation
	DeliveryConfirmation *DeliveryConfirmation `json:"deliveryConfirmation,omitempty"`
}

BridgeMessage represents a signed cross-chain message

func (*BridgeMessage) SigningMessage

func (m *BridgeMessage) SigningMessage() []byte

SigningMessage returns the canonical bytes to sign for a bridge message

func (*BridgeMessage) Verify

func (m *BridgeMessage) Verify(groupPublicKey []byte, verifier func([]byte, []byte) bool) error

Verify verifies the threshold signature on the message

type BridgeMessageValidator

type BridgeMessageValidator struct {
	// contains filtered or unexported fields
}

BridgeMessageValidator validates bridge messages and their delivery confirmations

func NewBridgeMessageValidator

func NewBridgeMessageValidator(
	bridgeSigner *BridgeSigner,
	deliverySigner *DeliveryConfirmationSigner,
	minConfirmations uint32,
	requireDeliveryConfirm bool,
	logger log.Logger,
) *BridgeMessageValidator

NewBridgeMessageValidator creates a new validator

func (*BridgeMessageValidator) ValidateAfterRelay

func (v *BridgeMessageValidator) ValidateAfterRelay(message *BridgeMessage) error

ValidateAfterRelay validates delivery confirmation after message is relayed

func (*BridgeMessageValidator) ValidateBeforeRelay

func (v *BridgeMessageValidator) ValidateBeforeRelay(message *BridgeMessage) error

ValidateBeforeRelay validates a message before relaying to destination chain

func (*BridgeMessageValidator) ValidateMessage

func (v *BridgeMessageValidator) ValidateMessage(message *BridgeMessage) error

ValidateMessage performs full validation of a bridge message

type BridgeRegistry

type BridgeRegistry struct {
	Validators       map[ids.NodeID]*BridgeValidator
	CompletedBridges map[ids.ID]*CompletedBridge
	DailyVolume      map[string]uint64 // chainID -> volume
	// contains filtered or unexported fields
}

BridgeRegistry tracks bridge operations and validators

type BridgeRequest

type BridgeRequest struct {
	ID            ids.ID    `json:"id"`
	SourceChain   string    `json:"sourceChain"`
	DestChain     string    `json:"destChain"`
	Asset         ids.ID    `json:"asset"`
	Amount        uint64    `json:"amount"`
	Recipient     []byte    `json:"recipient"`
	SourceTxID    ids.ID    `json:"sourceTxId"`
	Confirmations uint32    `json:"confirmations"`
	Status        string    `json:"status"` // pending, signing, completed, failed
	MPCSignatures [][]byte  `json:"mpcSignatures"`
	CreatedAt     time.Time `json:"createdAt"`
}

BridgeRequest represents a cross-chain bridge request

type BridgeRequestRecord added in v1.2.7

type BridgeRequestRecord struct {
	RequestID    string              `json:"requestId"`
	SourceChain  string              `json:"sourceChain"`
	DestChain    string              `json:"destChain"`
	SourceAsset  string              `json:"sourceAsset"`
	DestAsset    string              `json:"destAsset"`
	Amount       string              `json:"amount"`
	Recipient    string              `json:"recipient"`
	Sender       string              `json:"sender"`
	Status       BridgeRequestStatus `json:"status"`
	CreatedAt    int64               `json:"createdAt"`
	SourceTxHash string              `json:"sourceTxHash,omitempty"`
	DestTxHash   string              `json:"destTxHash,omitempty"`
	Signature    string              `json:"signature,omitempty"`
	FeeAmount    string              `json:"feeAmount,omitempty"`
	NetAmount    string              `json:"netAmount,omitempty"`
}

BridgeRequestRecord is the chain-side record of a bridge intent. Field naming matches the JSON-RPC wire shape the daemon's bchain client consumes (snake-cased via JSON tags).

type BridgeRequestStatus added in v1.2.7

type BridgeRequestStatus string

BridgeRequestStatus is the canonical on-chain lifecycle state.

const (
	StatusPending   BridgeRequestStatus = "pending"
	StatusDeposited BridgeRequestStatus = "deposited"
	StatusSigning   BridgeRequestStatus = "signing"
	StatusSigned    BridgeRequestStatus = "signed"
	StatusReleasing BridgeRequestStatus = "releasing"
	StatusCompleted BridgeRequestStatus = "completed"
	StatusFailed    BridgeRequestStatus = "failed"
	StatusCancelled BridgeRequestStatus = "cancelled"
)

type BridgeSigner

type BridgeSigner struct {
	// contains filtered or unexported fields
}

BridgeSigner handles signing of bridge messages using MPC

func NewBridgeSigner

func NewBridgeSigner(keyManager *MPCKeyManager, coordinator *MPCCoordinator, logger log.Logger) *BridgeSigner

NewBridgeSigner creates a new bridge signer

func (*BridgeSigner) CreateSignatureShare

func (s *BridgeSigner) CreateSignatureShare(ctx context.Context, message *BridgeMessage) ([]byte, []byte, error)

CreateSignatureShare creates this node's signature share for a bridge message

func (*BridgeSigner) GetSignature

func (s *BridgeSigner) GetSignature(ctx context.Context, sessionID string) ([]byte, error)

GetSignature retrieves the completed signature for a session

func (*BridgeSigner) RequestSignature

func (s *BridgeSigner) RequestSignature(ctx context.Context, message *BridgeMessage, signerIndices []int) (string, error)

RequestSignature initiates threshold signing for a bridge message

func (*BridgeSigner) SignBridgeMessage

func (s *BridgeSigner) SignBridgeMessage(ctx context.Context, message *BridgeMessage, activeSigners []int) error

SignBridgeMessage coordinates complete signing of a bridge message This is used by the coordinator node to orchestrate the signing

func (*BridgeSigner) VerifyBridgeMessage

func (s *BridgeSigner) VerifyBridgeMessage(message *BridgeMessage) error

VerifyBridgeMessage verifies a bridge message signature

type BridgeValidator

type BridgeValidator struct {
	NodeID       ids.NodeID
	StakeAmount  uint64
	MPCPublicKey []byte
	Active       bool
	TotalBridged uint64
	SuccessRate  float64
}

BridgeValidator represents a bridge validator node

type CancelRequestArgs added in v1.2.7

type CancelRequestArgs struct {
	RequestID string `json:"requestId"`
}

CancelRequestArgs is the bridge_cancelRequest request body.

type CancelRequestReply added in v1.2.7

type CancelRequestReply struct {
	Success bool `json:"success"`
}

CancelRequestReply is the bridge_cancelRequest response.

type ChainClient

type ChainClient interface {
	GetTransaction(ctx context.Context, txID ids.ID) (interface{}, error)
	GetConfirmations(ctx context.Context, txID ids.ID) (uint32, error)
	SendTransaction(ctx context.Context, tx interface{}) (ids.ID, error)
	ValidateAddress(address []byte) error
}

ChainClient interface for interacting with different chains

type CompletedBridge

type CompletedBridge struct {
	RequestID    ids.ID
	SourceTxID   ids.ID
	DestTxID     ids.ID
	CompletedAt  time.Time
	MPCSignature []byte
}

CompletedBridge represents a completed bridge operation

type CrossChainMPCRequest

type CrossChainMPCRequest struct {
	Type          MPCRequestType `json:"type"`
	SessionID     string         `json:"sessionId"`
	Epoch         uint64         `json:"epoch"`
	OldPartyIDs   []party.ID     `json:"oldPartyIds"`
	NewPartyIDs   []party.ID     `json:"newPartyIds"`
	Threshold     int            `json:"threshold"`
	SourceChainID []byte         `json:"sourceChainId"`
	Timestamp     int64          `json:"timestamp"`
}

CrossChainMPCRequest represents a cross-chain request to ThresholdVM for MPC operations

type DeliveryConfirmation

type DeliveryConfirmation struct {
	DestTxID         ids.ID    `json:"destTxId"`
	DestBlockHeight  uint64    `json:"destBlockHeight"`
	DestConfirms     uint32    `json:"destConfirms"`
	ConfirmedAt      time.Time `json:"confirmedAt"`
	ConfirmSignature []byte    `json:"confirmSignature"` // Threshold signature on delivery
}

DeliveryConfirmation proves message was delivered on destination chain

func (*DeliveryConfirmation) SigningMessage

func (dc *DeliveryConfirmation) SigningMessage(messageID ids.ID) []byte

SigningMessage returns the canonical bytes to sign for a delivery confirmation

type DeliveryConfirmationSigner

type DeliveryConfirmationSigner struct {
	// contains filtered or unexported fields
}

DeliveryConfirmationSigner handles signing of delivery confirmations

func NewDeliveryConfirmationSigner

func NewDeliveryConfirmationSigner(keyManager *MPCKeyManager, coordinator *MPCCoordinator, logger log.Logger) *DeliveryConfirmationSigner

NewDeliveryConfirmationSigner creates a new delivery confirmation signer

func (*DeliveryConfirmationSigner) SignDeliveryConfirmation

func (s *DeliveryConfirmationSigner) SignDeliveryConfirmation(ctx context.Context, messageID ids.ID, confirmation *DeliveryConfirmation, activeSigners []int) error

SignDeliveryConfirmation creates a threshold signature for delivery confirmation

func (*DeliveryConfirmationSigner) VerifyDeliveryConfirmation

func (s *DeliveryConfirmationSigner) VerifyDeliveryConfirmation(messageID ids.ID, confirmation *DeliveryConfirmation) error

VerifyDeliveryConfirmation verifies a delivery confirmation signature

type EstimateFeeArgs added in v1.2.7

type EstimateFeeArgs struct {
	SourceChain string `json:"sourceChain"`
	DestChain   string `json:"destChain"`
	SourceAsset string `json:"sourceAsset"`
	DestAsset   string `json:"destAsset"`
	Amount      string `json:"amount"`
	Refuel      bool   `json:"refuel,omitempty"`
}

EstimateFeeArgs are the bridge_estimateFee request body.

type EstimateFeeReply added in v1.2.7

type EstimateFeeReply struct {
	FeeAmount     string `json:"feeAmount"`
	NetAmount     string `json:"netAmount"`
	EstimatedTime int    `json:"estimatedTime"`
}

EstimateFeeReply is the bridge_estimateFee response.

type Factory

type Factory struct{}

Factory creates new BridgeVM instances

func (*Factory) New

func (f *Factory) New(logger log.Logger) (interface{}, error)

New returns a new instance of the BridgeVM

type Genesis

type Genesis struct {
	Timestamp int64 `json:"timestamp"`
}

Genesis represents the genesis state

type GetCurrentEpochArgs

type GetCurrentEpochArgs struct{}

GetCurrentEpochArgs are the arguments for bridge_getCurrentEpoch (empty)

type GetCurrentEpochReply

type GetCurrentEpochReply struct {
	Epoch        uint64 `json:"epoch"`
	TotalSigners int    `json:"totalSigners"`
	Threshold    int    `json:"threshold"`
	SetFrozen    bool   `json:"setFrozen"`
}

GetCurrentEpochReply is the reply for bridge_getCurrentEpoch

type GetMPCPublicKeyArgs added in v1.2.7

type GetMPCPublicKeyArgs struct{}

GetMPCPublicKeyArgs are empty.

type GetMPCPublicKeyReply added in v1.2.7

type GetMPCPublicKeyReply struct {
	PublicKey string `json:"publicKey"`
}

GetMPCPublicKeyReply is the bridge_getMPCPublicKey response.

type GetSignerSetInfoArgs

type GetSignerSetInfoArgs struct{}

GetSignerSetInfoArgs are the arguments for bridge_getSignerSetInfo (empty)

type GetSignerSetInfoReply

type GetSignerSetInfoReply struct {
	TotalSigners   int               `json:"totalSigners"`
	Threshold      int               `json:"threshold"`
	MaxSigners     int               `json:"maxSigners"`
	CurrentEpoch   uint64            `json:"currentEpoch"`
	SetFrozen      bool              `json:"setFrozen"`
	RemainingSlots int               `json:"remainingSlots"`
	WaitlistSize   int               `json:"waitlistSize"`
	Signers        []SignerInfoReply `json:"signers"`
	PublicKey      string            `json:"publicKey,omitempty"`
}

GetSignerSetInfoReply is the reply for bridge_getSignerSetInfo

type GetStatusArgs added in v1.2.7

type GetStatusArgs struct {
	RequestID string `json:"requestId"`
}

GetStatusArgs is the bridge_getStatus request body.

type GetStatusReply added in v1.2.7

type GetStatusReply BridgeRequestRecord

GetStatusReply is the bridge_getStatus response.

type GetWaitlistArgs

type GetWaitlistArgs struct{}

GetWaitlistArgs are the arguments for bridge_getWaitlist (empty)

type GetWaitlistReply

type GetWaitlistReply struct {
	WaitlistSize int      `json:"waitlistSize"`
	NodeIDs      []string `json:"nodeIds"`
}

GetWaitlistReply is the reply for bridge_getWaitlist

type HasSignerArgs

type HasSignerArgs struct {
	NodeID string `json:"nodeId"`
}

HasSignerArgs are the arguments for bridge_hasSigner

type HasSignerReply

type HasSignerReply struct {
	IsSigner bool `json:"isSigner"`
}

HasSignerReply is the reply for bridge_hasSigner

type HealthArgs added in v1.2.7

type HealthArgs struct{}

HealthArgs are empty (no params).

type HealthReply added in v1.2.7

type HealthReply struct {
	Status   string `json:"status"`
	MPCReady bool   `json:"mpcReady"`
}

HealthReply is the bridge_health response.

type MPCCoordinator

type MPCCoordinator struct {
	// contains filtered or unexported fields
}

MPCCoordinator coordinates threshold signing across multiple parties

func NewMPCCoordinator

func NewMPCCoordinator(keyManager *MPCKeyManager, logger log.Logger) *MPCCoordinator

NewMPCCoordinator creates a new MPC coordinator

func (*MPCCoordinator) GetSession

func (c *MPCCoordinator) GetSession(sessionID string) (*SigningSession, bool)

GetSession returns an active signing session

func (*MPCCoordinator) StartSigning

func (c *MPCCoordinator) StartSigning(ctx context.Context, sessionID string, message []byte, signers []int, timeout time.Duration) (*SigningSession, error)

StartSigning initiates a new signing session

type MPCKeyManager

type MPCKeyManager struct {
	// contains filtered or unexported fields
}

MPCKeyManager manages threshold key generation and shares

func NewMPCKeyManager

func NewMPCKeyManager(logger log.Logger) (*MPCKeyManager, error)

NewMPCKeyManager creates a new MPC key manager

func (*MPCKeyManager) AggregateSignature

func (m *MPCKeyManager) AggregateSignature(ctx context.Context, message []byte, shares []threshold.SignatureShare) ([]byte, error)

AggregateSignature combines signature shares into a final signature

func (*MPCKeyManager) GenerateKeys

func (m *MPCKeyManager) GenerateKeys(ctx context.Context, t, totalParties int) error

GenerateKeys performs distributed key generation using trusted dealer model In production, this would use proper DKG, but for initial implementation we use trusted dealer for simplicity

func (*MPCKeyManager) GetGroupPublicKey

func (m *MPCKeyManager) GetGroupPublicKey() []byte

GetGroupPublicKey returns the threshold group public key

func (*MPCKeyManager) GetKeyShareBytes

func (m *MPCKeyManager) GetKeyShareBytes() []byte

GetKeyShareBytes returns the serialized key share

func (*MPCKeyManager) SetKeyShare

func (m *MPCKeyManager) SetKeyShare(share threshold.KeyShare) error

SetKeyShare sets this node's key share (used when importing or receiving via DKG)

func (*MPCKeyManager) SignShare

func (m *MPCKeyManager) SignShare(ctx context.Context, message []byte) (threshold.SignatureShare, error)

SignShare creates a signature share for a message

func (*MPCKeyManager) VerifyShare

func (m *MPCKeyManager) VerifyShare(message []byte, share threshold.SignatureShare, publicShare []byte) error

VerifyShare verifies a signature share from another signer

func (*MPCKeyManager) VerifySignature

func (m *MPCKeyManager) VerifySignature(message, signature []byte) bool

VerifySignature verifies a final threshold signature

type MPCRequestType

type MPCRequestType uint8

MPCRequestType defines the type of MPC cross-chain request

const (
	// MPCRequestReshare triggers a key reshare protocol
	MPCRequestReshare MPCRequestType = iota
	// MPCRequestSign triggers a threshold signing operation
	MPCRequestSign
	// MPCRequestRefresh triggers a proactive key refresh
	MPCRequestRefresh
)

type PriceFeed added in v1.2.7

type PriceFeed interface {
	// Price returns the USD value of one unit of asset. Returns
	// ErrPriceUnknown when the asset is not priced.
	Price(asset string) (float64, error)
}

PriceFeed returns USD-denominated unit prices.

type QuoteEngine added in v1.2.7

type QuoteEngine struct {
	Feed     PriceFeed
	FeeRate  float64 // zero ⇒ DefaultBridgeFeeRate
	Slippage float64 // zero ⇒ DefaultSlippage
}

QuoteEngine computes settlement quotes for the B-Chain RPC layer. Concurrency-safe — PriceFeed is the only mutable dependency.

func (*QuoteEngine) Quote added in v1.2.7

func (q *QuoteEngine) Quote(in QuoteInput) (*QuoteResult, error)

Quote computes settlement economics for one bridge intent.

type QuoteInput added in v1.2.7

type QuoteInput struct {
	Amount             float64
	SourceNetwork      string
	SourceAsset        string
	DestinationNetwork string
	DestinationAsset   string
	Refuel             bool
}

QuoteInput is the engine's call payload.

type QuoteResult added in v1.2.7

type QuoteResult struct {
	ReceiveAmount    float64
	MinReceiveAmount float64
	ServiceFee       float64
	TotalFee         float64
	Slippage         float64
	EstimatedTime    int
	AvgCompletion    string
}

QuoteResult is the engine's output. Stringified amounts are emitted via the RPC layer (canonical bridge wire encoding).

type RegisterValidatorArgs

type RegisterValidatorArgs struct {
	NodeID     string `json:"nodeId"`
	BondAmount string `json:"bondAmount,omitempty"` // 100M LUX bond (slashable)
	MPCPubKey  string `json:"mpcPubKey,omitempty"`
}

RegisterValidatorArgs are the arguments for bridge_registerValidator

type RegisterValidatorInput

type RegisterValidatorInput struct {
	NodeID     string `json:"nodeId"`
	BondAmount string `json:"bondAmount,omitempty"` // 1M LUX bond (slashable)
	MPCPubKey  string `json:"mpcPubKey,omitempty"`
}

RegisterValidatorInput is the input for registering as a bridge signer

type RegisterValidatorReply

type RegisterValidatorReply struct {
	Success        bool   `json:"success"`
	NodeID         string `json:"nodeId"`
	Registered     bool   `json:"registered"`
	Waitlisted     bool   `json:"waitlisted"`
	SignerIndex    int    `json:"signerIndex"`
	WaitlistIndex  int    `json:"waitlistIndex,omitempty"`
	TotalSigners   int    `json:"totalSigners"`
	Threshold      int    `json:"threshold"`
	ReshareNeeded  bool   `json:"reshareNeeded"`
	CurrentEpoch   uint64 `json:"currentEpoch"`
	SetFrozen      bool   `json:"setFrozen"`
	RemainingSlots int    `json:"remainingSlots"`
	Message        string `json:"message"`
}

RegisterValidatorReply is the reply for bridge_registerValidator

type RegisterValidatorResult

type RegisterValidatorResult struct {
	Success        bool   `json:"success"`
	NodeID         string `json:"nodeId"`
	Registered     bool   `json:"registered"`
	Waitlisted     bool   `json:"waitlisted"`
	SignerIndex    int    `json:"signerIndex"`
	WaitlistIndex  int    `json:"waitlistIndex,omitempty"`
	TotalSigners   int    `json:"totalSigners"`
	Threshold      int    `json:"threshold"`
	ReshareNeeded  bool   `json:"reshareNeeded"` // Always false for opt-in (LP-333)
	CurrentEpoch   uint64 `json:"currentEpoch"`
	SetFrozen      bool   `json:"setFrozen"`
	RemainingSlots int    `json:"remainingSlots"`
	Message        string `json:"message"`
}

RegisterValidatorResult is the result of registering as a bridge signer

type ReplaceSignerArgs

type ReplaceSignerArgs struct {
	NodeID            string `json:"nodeId"`            // Signer to remove
	ReplacementNodeID string `json:"replacementNodeId"` // Explicit replacement (optional, uses waitlist if empty)
}

ReplaceSignerArgs are the arguments for bridge_replaceSigner

type ReplaceSignerReply

type ReplaceSignerReply struct {
	Success           bool   `json:"success"`
	RemovedNodeID     string `json:"removedNodeId,omitempty"`
	ReplacementNodeID string `json:"replacementNodeId,omitempty"`
	ReshareSession    string `json:"reshareSession,omitempty"`
	NewEpoch          uint64 `json:"newEpoch"`
	ActiveSigners     int    `json:"activeSigners"`
	Threshold         int    `json:"threshold"`
	Message           string `json:"message"`
}

ReplaceSignerReply is the reply for bridge_replaceSigner

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides JSON-RPC endpoints for BridgeVM:

  • LP-333 signer-set management (RegisterValidator, GetSignerSetInfo, …)
  • Permissionless bridge settlement (EstimateFee, SubmitRequest, GetStatus, CancelRequest, …)

Any client that can reach /ext/bc/B/rpc has equal authority — the daemon at cmd/bridge is one such client. There are no privileged methods on this surface; rate-limiting and auth (when desired) are applied at the ingress layer.

func NewService

func NewService(vm *VM) *Service

NewService returns a new Service instance

func (*Service) CancelRequest added in v1.2.7

func (s *Service) CancelRequest(_ *http.Request, args *CancelRequestArgs, reply *CancelRequestReply) error

CancelRequest answers bridge_cancelRequest. Idempotent — cancelling an already-terminal swap is a no-op success so retries are safe.

func (*Service) EstimateFee added in v1.2.7

func (s *Service) EstimateFee(_ *http.Request, args *EstimateFeeArgs, reply *EstimateFeeReply) error

EstimateFee answers bridge_estimateFee. Authoritative settlement math runs in the VM (see quote.go) so the result is what the chain will pay.

func (*Service) GetCurrentEpoch

func (s *Service) GetCurrentEpoch(_ *http.Request, _ *GetCurrentEpochArgs, reply *GetCurrentEpochReply) error

GetCurrentEpoch returns the current epoch (incremented only on reshare)

func (*Service) GetMPCPublicKey added in v1.2.7

func (s *Service) GetMPCPublicKey(_ *http.Request, _ *GetMPCPublicKeyArgs, reply *GetMPCPublicKeyReply) error

GetMPCPublicKey answers bridge_getMPCPublicKey with the active threshold-signing group public key.

func (*Service) GetSignerSetInfo

func (s *Service) GetSignerSetInfo(_ *http.Request, _ *GetSignerSetInfoArgs, reply *GetSignerSetInfoReply) error

GetSignerSetInfo returns information about the current signer set (LP-333)

func (*Service) GetStatus added in v1.2.7

func (s *Service) GetStatus(_ *http.Request, args *GetStatusArgs, reply *GetStatusReply) error

GetStatus answers bridge_getStatus from the authoritative swap store.

func (*Service) GetWaitlist

func (s *Service) GetWaitlist(_ *http.Request, _ *GetWaitlistArgs, reply *GetWaitlistReply) error

GetWaitlist returns the current waitlist of validators waiting for signer slots

func (*Service) HasSigner

func (s *Service) HasSigner(_ *http.Request, args *HasSignerArgs, reply *HasSignerReply) error

HasSigner checks if a node is in the active signer set

func (*Service) Health added in v1.2.7

func (s *Service) Health(_ *http.Request, _ *HealthArgs, reply *HealthReply) error

Health answers bridge_health. Liveness probe used by daemons + load balancers before routing traffic at this node.

func (*Service) RegisterValidator

func (s *Service) RegisterValidator(_ *http.Request, args *RegisterValidatorArgs, reply *RegisterValidatorReply) error

RegisterValidator registers a validator as a bridge signer (LP-333 opt-in model) First 100 validators are accepted directly without reshare. After 100 signers, new validators go to waitlist.

func (*Service) ReplaceSigner

func (s *Service) ReplaceSigner(_ *http.Request, args *ReplaceSignerArgs, reply *ReplaceSignerReply) error

ReplaceSigner removes a failed signer and triggers reshare (LP-333) This is the ONLY operation that triggers a reshare.

func (*Service) SlashSigner

func (s *Service) SlashSigner(_ *http.Request, args *SlashSignerArgs, reply *SlashSignerReply) error

SlashSigner slashes a misbehaving bridge signer's bond The bond is NOT stake - it's a slashable deposit that can be partially or fully seized

func (*Service) SubmitRequest added in v1.2.7

func (s *Service) SubmitRequest(_ *http.Request, args *SubmitRequestArgs, reply *SubmitRequestReply) error

SubmitRequest creates a new bridge request server-side and snapshots the quote into the record so the daemon's signing pipeline pays out what the chain committed to.

type SignerInfo

type SignerInfo struct {
	NodeID     ids.NodeID `json:"nodeId"`
	PartyID    party.ID   `json:"partyId"`
	BondAmount uint64     `json:"bondAmount"` // 1M LUX bond (slashable, NOT staked)
	MPCPubKey  []byte     `json:"mpcPubKey"`
	Active     bool       `json:"active"`
	JoinedAt   time.Time  `json:"joinedAt"`
	SlotIndex  int        `json:"slotIndex"`
	Slashed    bool       `json:"slashed"`    // True if this signer has been slashed
	SlashCount int        `json:"slashCount"` // Number of times slashed
}

SignerInfo contains information about a signer in the set

type SignerInfoReply

type SignerInfoReply struct {
	NodeID     string `json:"nodeId"`
	PartyID    string `json:"partyId"`
	BondAmount uint64 `json:"bondAmount"` // 100M LUX bond (slashable)
	Active     bool   `json:"active"`
	JoinedAt   string `json:"joinedAt"`
	SlotIndex  int    `json:"slotIndex"`
	Slashed    bool   `json:"slashed"`
	SlashCount int    `json:"slashCount"`
}

SignerInfoReply contains signer information for RPC replies

type SignerReplacementResult

type SignerReplacementResult struct {
	Success           bool   `json:"success"`
	RemovedNodeID     string `json:"removedNodeId,omitempty"`
	ReplacementNodeID string `json:"replacementNodeId,omitempty"`
	ReshareSession    string `json:"reshareSession,omitempty"`
	NewEpoch          uint64 `json:"newEpoch"`
	ActiveSigners     int    `json:"activeSigners"`
	Threshold         int    `json:"threshold"`
	Message           string `json:"message"`
}

SignerReplacementResult is the result of replacing a failed signer

type SignerSet

type SignerSet struct {
	Signers      []*SignerInfo `json:"signers"`      // Active signers (max 100)
	Waitlist     []ids.NodeID  `json:"waitlist"`     // Validators waiting for a slot
	CurrentEpoch uint64        `json:"currentEpoch"` // Increments ONLY on reshare (slot replacement)
	SetFrozen    bool          `json:"setFrozen"`    // True when len(Signers) >= MaxSigners
	ThresholdT   int           `json:"thresholdT"`   // Current t value (T+1 required to sign)
	PublicKey    []byte        `json:"publicKey"`    // Combined threshold public key
}

SignerSet tracks the current MPC signer set (LP-333) First 100 validators opt-in without reshare. Reshare ONLY on slot replacement.

type SignerSetInfo

type SignerSetInfo struct {
	TotalSigners   int           `json:"totalSigners"`
	Threshold      int           `json:"threshold"`
	MaxSigners     int           `json:"maxSigners"`
	CurrentEpoch   uint64        `json:"currentEpoch"`
	SetFrozen      bool          `json:"setFrozen"`
	RemainingSlots int           `json:"remainingSlots"`
	WaitlistSize   int           `json:"waitlistSize"`
	Signers        []*SignerInfo `json:"signers"`
	PublicKey      string        `json:"publicKey,omitempty"`
}

SignerSetInfo is the result of getting signer set information

type SigningSession

type SigningSession struct {
	// contains filtered or unexported fields
}

SigningSession manages a distributed signing session

func NewSigningSession

func NewSigningSession(sessionID string, message []byte, signers []int, timeout time.Duration, logger log.Logger) *SigningSession

NewSigningSession creates a new signing session

func (*SigningSession) AddShare

func (s *SigningSession) AddShare(signerIndex int, share threshold.SignatureShare, publicShare []byte) error

AddShare adds a signature share to the session

func (*SigningSession) GetShares

func (s *SigningSession) GetShares() []threshold.SignatureShare

GetShares returns all collected shares

func (*SigningSession) IsComplete

func (s *SigningSession) IsComplete(threshold int) bool

IsComplete checks if we have enough shares

func (*SigningSession) NumShares

func (s *SigningSession) NumShares() int

NumShares returns the number of collected shares

func (*SigningSession) SetResult

func (s *SigningSession) SetResult(signature []byte, err error)

SetResult sets the final signature or error

func (*SigningSession) Wait

func (s *SigningSession) Wait(ctx context.Context) ([]byte, error)

Wait waits for the session to complete or timeout

type SlashSignerArgs

type SlashSignerArgs struct {
	NodeID       string `json:"nodeId"`
	Reason       string `json:"reason"`
	SlashPercent int    `json:"slashPercent"` // Percentage of bond to slash (1-100)
	Evidence     string `json:"evidence"`     // Hex-encoded proof of misbehavior
}

SlashSignerArgs are the arguments for bridge_slashSigner

type SlashSignerInput

type SlashSignerInput struct {
	NodeID       ids.NodeID `json:"nodeId"`
	Reason       string     `json:"reason"`
	SlashPercent int        `json:"slashPercent"` // Percentage of bond to slash (1-100)
	Evidence     []byte     `json:"evidence"`     // Proof of misbehavior
}

SlashSignerInput is the input for slashing a bridge signer

type SlashSignerReply

type SlashSignerReply struct {
	Success         bool   `json:"success"`
	NodeID          string `json:"nodeId"`
	SlashedAmount   uint64 `json:"slashedAmount"`
	RemainingBond   uint64 `json:"remainingBond"`
	TotalSlashCount int    `json:"totalSlashCount"`
	RemovedFromSet  bool   `json:"removedFromSet"`
	Message         string `json:"message"`
}

SlashSignerReply is the reply for bridge_slashSigner

type SlashSignerResult

type SlashSignerResult struct {
	Success         bool   `json:"success"`
	NodeID          string `json:"nodeId"`
	SlashedAmount   uint64 `json:"slashedAmount"`
	RemainingBond   uint64 `json:"remainingBond"`
	TotalSlashCount int    `json:"totalSlashCount"`
	RemovedFromSet  bool   `json:"removedFromSet"`
	Message         string `json:"message"`
}

SlashSignerResult is the result of slashing a bridge signer

type StaticPriceFeed added in v1.2.7

type StaticPriceFeed struct {
	// contains filtered or unexported fields
}

StaticPriceFeed is a map-backed PriceFeed. Concurrency-safe. Asset symbols are matched case-insensitively.

func NewStaticPriceFeed added in v1.2.7

func NewStaticPriceFeed(prices map[string]float64) *StaticPriceFeed

NewStaticPriceFeed builds a feed from an initial table.

func (*StaticPriceFeed) Price added in v1.2.7

func (f *StaticPriceFeed) Price(asset string) (float64, error)

Price returns the USD value of one unit of asset.

func (*StaticPriceFeed) Set added in v1.2.7

func (f *StaticPriceFeed) Set(asset string, usd float64)

Set updates / inserts a price.

type SubmitRequestArgs added in v1.2.7

type SubmitRequestArgs struct {
	SourceChain string `json:"sourceChain"`
	DestChain   string `json:"destChain"`
	SourceAsset string `json:"sourceAsset"`
	DestAsset   string `json:"destAsset"`
	Amount      string `json:"amount"`
	Recipient   string `json:"recipient"`
	Sender      string `json:"sender"`
	Refuel      bool   `json:"refuel,omitempty"`
}

SubmitRequestArgs is the bridge_submitRequest request body.

type SubmitRequestReply added in v1.2.7

type SubmitRequestReply BridgeRequestRecord

SubmitRequestReply is the bridge_submitRequest response.

type SwapListFilter added in v1.2.7

type SwapListFilter struct {
	Status      BridgeRequestStatus
	SourceChain string
	Limit       int // 0 → no limit
}

SwapListFilter narrows List queries. Empty fields mean "any".

type SwapStore added in v1.2.7

type SwapStore interface {
	Put(rec *BridgeRequestRecord) error
	Get(requestID string) (*BridgeRequestRecord, error)
	Patch(requestID string, fn func(*BridgeRequestRecord)) (*BridgeRequestRecord, error)
	List(filter SwapListFilter) ([]*BridgeRequestRecord, error)
}

SwapStore is the chain-side record set. Concurrency-safe.

The interface is intentionally narrow — implementations decide whether records persist via the VM's database, are reconstructed from accepted blocks at startup, or both. The in-memory default (newInMemorySwapStore) covers the genesis case.

type VM

type VM struct {
	// contains filtered or unexported fields
}

VM implements the Bridge VM for cross-chain interoperability

func (*VM) BuildBlock

func (vm *VM) BuildBlock(ctx context.Context) (chain.Block, error)

BuildBlock implements the chain.ChainVM interface

func (*VM) ConfirmDelivery

func (vm *VM) ConfirmDelivery(ctx context.Context, message *BridgeMessage, confirmation *DeliveryConfirmation) error

ConfirmDelivery confirms delivery of a bridge message on the destination chain

func (*VM) Connected

func (vm *VM) Connected(ctx context.Context, nodeID ids.NodeID, nodeVersion *chain.VersionInfo) error

Connected implements the common.VM interface

func (*VM) CreateHandlers

func (vm *VM) CreateHandlers(ctx context.Context) (map[string]http.Handler, error)

CreateHandlers implements the common.VM interface

func (*VM) CreateRPCHandlers

func (vm *VM) CreateRPCHandlers() (map[string]http.Handler, error)

CreateRPCHandlers creates HTTP handlers for JSON-RPC endpoints

func (*VM) CreateStaticHandlers

func (vm *VM) CreateStaticHandlers(ctx context.Context) (map[string]http.Handler, error)

CreateStaticHandlers implements the common.VM interface

func (*VM) CrossChainRequest

func (vm *VM) CrossChainRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error

CrossChainRequest implements the common.VM interface

func (*VM) CrossChainRequestFailed

func (vm *VM) CrossChainRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *warp.Error) error

CrossChainRequestFailed implements the common.VM interface

func (*VM) CrossChainResponse

func (vm *VM) CrossChainResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error

CrossChainResponse implements the common.VM interface

func (*VM) Disconnected

func (vm *VM) Disconnected(ctx context.Context, nodeID ids.NodeID) error

Disconnected implements the common.VM interface

func (*VM) FeePolicy added in v1.2.6

func (vm *VM) FeePolicy() fee.Policy

FeePolicy exposes the chain's declared fee policy for diagnostics and the boot-time Validate gate.

func (*VM) GetBlock

func (vm *VM) GetBlock(ctx context.Context, id ids.ID) (chain.Block, error)

GetBlock implements the chain.ChainVM interface

func (*VM) GetBlockIDAtHeight

func (vm *VM) GetBlockIDAtHeight(ctx context.Context, height uint64) (ids.ID, error)

GetBlockIDAtHeight implements the chain.HeightIndexedChainVM interface

func (*VM) GetMPCStatus

func (vm *VM) GetMPCStatus() map[string]interface{}

GetMPCStatus returns the current MPC status

func (*VM) GetSignerSetInfo

func (vm *VM) GetSignerSetInfo() *SignerSetInfo

GetSignerSetInfo returns information about the current signer set

func (*VM) Gossip

func (vm *VM) Gossip(ctx context.Context, nodeID ids.NodeID, msg []byte) error

Gossip implements the common.VM interface

func (*VM) HandleSignatureShare

func (vm *VM) HandleSignatureShare(ctx context.Context, sessionID string, signerIndex int, shareBytes, publicShare []byte) error

AddShareToVM adds a VM method to handle incoming signature shares

func (*VM) HasSigner

func (vm *VM) HasSigner(nodeID ids.NodeID) bool

HasSigner checks if a node ID is in the active signer set

func (*VM) HealthCheck

func (vm *VM) HealthCheck(ctx context.Context) (chain.HealthResult, error)

HealthCheck implements the common.VM interface

func (*VM) Initialize

func (vm *VM) Initialize(
	ctx context.Context,
	vmInit vmcore.Init,
) error

Initialize implements the chain.ChainVM interface

func (*VM) InitializeMPCKeys

func (vm *VM) InitializeMPCKeys(ctx context.Context) error

InitializeMPCKeys performs threshold key generation when signer set is ready This should be called when the signer set reaches the threshold or is frozen

func (*VM) InitiateBridgeTransfer

func (vm *VM) InitiateBridgeTransfer(ctx context.Context, message *BridgeMessage) error

InitiateBridgeTransfer initiates a new bridge transfer with MPC signing. This is the canonical user-tx admission point on B-Chain. The FeePolicy gate refuses zero-fee transfers before any MPC signing capacity is consumed. Consensus-internal callers bypass by reaching pendingBridges / bridgeSigner directly.

func (*VM) LastAccepted

func (vm *VM) LastAccepted(ctx context.Context) (ids.ID, error)

LastAccepted implements the chain.ChainVM interface

func (*VM) NewHTTPHandler

func (vm *VM) NewHTTPHandler(ctx context.Context) (http.Handler, error)

NewHTTPHandler returns HTTP handlers for the VM

func (*VM) ParseBlock

func (vm *VM) ParseBlock(ctx context.Context, bytes []byte) (chain.Block, error)

ParseBlock implements the chain.ChainVM interface

func (*VM) ProcessBridgeMessage

func (vm *VM) ProcessBridgeMessage(ctx context.Context, message *BridgeMessage) error

ProcessBridgeMessage handles an incoming bridge message

func (*VM) RegisterService

func (vm *VM) RegisterService(server *rpc.Server) error

RegisterService registers the BridgeVM RPC handlers

func (*VM) RegisterValidator

func (vm *VM) RegisterValidator(input *RegisterValidatorInput) (*RegisterValidatorResult, error)

RegisterValidator registers a new validator as a bridge signer (opt-in model) LP-333: First 100 validators are accepted directly - NO reshare on join. After 100 signers, new validators go to waitlist until a slot opens.

func (*VM) RemoveSigner

func (vm *VM) RemoveSigner(nodeID ids.NodeID, replacementNodeID *ids.NodeID) (*SignerReplacementResult, error)

RemoveSigner removes a failed/stopped signer and triggers replacement LP-333: This is the ONLY operation that triggers a reshare. Epoch increments only when a signer is replaced.

func (*VM) Request

func (vm *VM) Request(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, request []byte) error

Request implements the common.VM interface

func (*VM) RequestFailed

func (vm *VM) RequestFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *warp.Error) error

RequestFailed implements the common.VM interface

func (*VM) Response

func (vm *VM) Response(ctx context.Context, nodeID ids.NodeID, requestID uint32, response []byte) error

Response implements the common.VM interface

func (*VM) SetPreference

func (vm *VM) SetPreference(ctx context.Context, id ids.ID) error

SetPreference implements the chain.ChainVM interface

func (*VM) SetState

func (vm *VM) SetState(ctx context.Context, state uint32) error

SetState implements the common.VM interface

func (*VM) Shutdown

func (vm *VM) Shutdown(ctx context.Context) error

Shutdown implements the common.VM interface

func (*VM) SlashSigner

func (vm *VM) SlashSigner(input *SlashSignerInput) (*SlashSignerResult, error)

SlashSigner slashes a misbehaving bridge signer's bond The bond is NOT stake - it's a slashable deposit that can be partially or fully seized

func (*VM) TriggerKeygen

func (vm *VM) TriggerKeygen(ctx context.Context) error

TriggerKeygen should be called when signer set changes

func (*VM) Version

func (vm *VM) Version(ctx context.Context) (string, error)

Version implements the common.VM interface

func (*VM) WaitForEvent

func (vm *VM) WaitForEvent(ctx context.Context) (vmcore.Message, error)

WaitForEvent blocks until an event occurs that should trigger block building

Directories

Path Synopsis
cmd
plugin command

Jump to

Keyboard shortcuts

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