lnd

package module
v0.0.0-...-7b26967 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 15 Imported by: 0

README

lnd Go SDK

这是 lnd 的 Go 高层 SDK. 它直接实现 lnd 的 HTTP(S) + REST + SSE 协议, 不依赖 cgo, 因此可以作为纯 Go module 使用.

这意味着只要仓库和 tag 可见, 外部项目可以直接:

go get github.com/azazo1/lnd/impls/go

当前前提:

  • 仓库路径已经是 github.com/azazo1/lnd
  • 需要发布对应 tag, 才适合给外部项目稳定引用

SDK 公开对象:

  • Client
  • DiscoveryFilter
  • AnnounceSpec
  • AddressSelection
  • AnnounceHandle
  • WatchHandle

自动发现域与可达域相关接口:

  • client.ListReachabilityScopes()

推荐模型是:

  • discovery_domain: 可选逻辑发现域
  • reachability_scopes: 本机子网前缀列表, 用于自动 overlap 匹配

最小示例:

client := lnd.NewClient("http://127.0.0.1:8765", "dev-token")
scopes, err := client.ListReachabilityScopes()
if err != nil {
	return err
}
filter := lnd.NewDiscoveryFilter().WithDiscoveryDomain("office-a").WithService("_http._tcp").AddTag("stable")
for _, scope := range scopes {
	filter = filter.AddReachabilityScope(scope)
}
nodes, err := client.Discover(
	context.Background(),
	filter,
)
if err != nil {
	return err
}
_ = nodes

它的 discover, announce, watch 语义与 Rust SDK 对齐, 包括:

  • client 侧自动 LAN 地址解析
  • AddressSelection 控制 loopback, IPv6, 接口白名单和黑名单
  • SSE watch 的断线重连, cursor 恢复和 reset 后快照重同步

Documentation

Index

Constants

View Source
const (
	// DefaultTTLSeconds is the default lease duration used by NewAnnounceSpec.
	//
	// The background announce loop renews at about one third of this value.
	// Increase it to reduce server traffic, or lower it to remove stale peers sooner.
	DefaultTTLSeconds uint64 = 30
	// DefaultSSEKeepaliveSeconds is the keepalive cadence emitted by the server watch stream.
	//
	// Watch clients do not need to send heartbeats themselves, but long running
	// reverse proxies should allow idle periods at least this long.
	DefaultSSEKeepaliveSeconds uint64 = 15
)

Variables

This section is empty.

Functions

func ListReachabilityScopes

func ListReachabilityScopes(selection AddressSelection) ([]string, error)

ListReachabilityScopes derives local subnet scopes from local interfaces.

func ResolveLanAddrsWithSelection

func ResolveLanAddrsWithSelection(port uint16, selection AddressSelection) ([]string, error)

ResolveLanAddrsWithSelection resolves local addresses using the given selection policy.

port is attached to every returned host address. The function skips interfaces whose addresses cannot be enumerated and deduplicates the final host:port list.

func ResolvePrivateIPv4Addrs

func ResolvePrivateIPv4Addrs(port uint16) ([]string, error)

ResolvePrivateIPv4Addrs resolves local private IPv4 addresses with the default policy.

This helper is equivalent to ResolveLanAddrsWithSelection(port, DefaultAddressSelection()).

Types

type AddressSelection

type AddressSelection struct {
	IncludePrivateIPv4   bool     `json:"include_private_ipv4"`
	IncludeLoopback      bool     `json:"include_loopback"`
	IncludeLinkLocalIPv4 bool     `json:"include_link_local_ipv4"`
	IncludeIPv6          bool     `json:"include_ipv6"`
	InterfaceAllowlist   []string `json:"interface_allowlist,omitempty"`
	InterfaceDenylist    []string `json:"interface_denylist,omitempty"`
}

AddressSelection controls which local interfaces and IP families may be included in automatic LAN address discovery.

The default policy only includes private IPv4 addresses. Loopback, IPv6 and link local IPv4 must be enabled explicitly.

func DefaultAddressSelection

func DefaultAddressSelection() AddressSelection

DefaultAddressSelection returns the default automatic address selection policy.

By default only private IPv4 addresses are included. The returned value can be refined with the WithXxx and Interface methods.

func (AddressSelection) DisableInterface

func (s AddressSelection) DisableInterface(name string) AddressSelection

DisableInterface appends one interface denylist item.

func (AddressSelection) EnableInterface

func (s AddressSelection) EnableInterface(name string) AddressSelection

EnableInterface appends one interface allowlist item.

func (AddressSelection) WithIPv6

func (s AddressSelection) WithIPv6(on bool) AddressSelection

WithIPv6 enables or disables IPv6 addresses in automatic selection.

func (AddressSelection) WithLinkLocalIPv4

func (s AddressSelection) WithLinkLocalIPv4(on bool) AddressSelection

WithLinkLocalIPv4 enables or disables link-local IPv4 addresses in automatic selection.

func (AddressSelection) WithLoopback

func (s AddressSelection) WithLoopback(on bool) AddressSelection

WithLoopback enables or disables loopback addresses in automatic selection.

func (AddressSelection) WithPrivateIPv4

func (s AddressSelection) WithPrivateIPv4(on bool) AddressSelection

WithPrivateIPv4 enables or disables private IPv4 addresses in automatic selection.

type AnnounceHandle

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

AnnounceHandle manages a background announce loop started by Client.Announce.

Call Close to stop renewals and wait for the goroutine to exit.

func (*AnnounceHandle) Close

func (h *AnnounceHandle) Close() error

Close stops the background announce loop and waits for it to exit.

It returns the final loop error, or nil when the loop stopped cleanly.

type AnnounceSpec

type AnnounceSpec struct {
	DiscoveryDomain        *string           `json:"discovery_domain,omitempty"`
	NodeID                 string            `json:"node_id"`
	Service                string            `json:"service"`
	DisplayName            string            `json:"display_name"`
	Port                   uint16            `json:"port"`
	LanAddrs               []string          `json:"lan_addrs,omitempty"`
	AutoLanAddrs           bool              `json:"auto_lan_addrs"`
	ReachabilityScopes     []string          `json:"reachability_scopes,omitempty"`
	AutoReachabilityScopes bool              `json:"auto_reachability_scopes"`
	Tags                   []string          `json:"tags,omitempty"`
	Metadata               map[string]string `json:"metadata,omitempty"`
	TTLSeconds             uint64            `json:"ttl_secs"`
	AddressSelection       *AddressSelection `json:"address_selection,omitempty"`
}

AnnounceSpec describes one node registration payload.

The spec can contain explicit LAN addresses, or it can ask the client to resolve addresses automatically from local interfaces.

Example:

spec := lnd.NewAnnounceSpec("node-1", "_http._tcp", "Demo Node", 8080).
	WithDiscoveryDomain("office-net").
	AddTag("blue").
	InsertMetadata("role", "api")

func NewAnnounceSpec

func NewAnnounceSpec(nodeID, service, displayName string, port uint16) AnnounceSpec

NewAnnounceSpec creates an announce specification with sensible defaults.

nodeID must remain stable across restarts. service identifies the protocol family and usually follows mDNS / DNS-SD service type conventions such as "_http._tcp". displayName is a human readable label, and port is the LAN service port advertised to peers.

The returned spec enables automatic LAN address discovery and uses DefaultTTLSeconds unless overridden.

func (AnnounceSpec) AddLanAddr

func (s AnnounceSpec) AddLanAddr(addr string) AnnounceSpec

AddLanAddr appends one explicit host:port address and returns the updated copy.

Keep AutoLanAddrs enabled if you want explicit addresses to be merged with automatically discovered interfaces. Disable AutoLanAddrs to advertise only the addresses provided here.

func (AnnounceSpec) AddReachabilityScope

func (s AnnounceSpec) AddReachabilityScope(scope string) AnnounceSpec

AddReachabilityScope appends one explicit reachability scope.

func (AnnounceSpec) AddTag

func (s AnnounceSpec) AddTag(tag string) AnnounceSpec

AddTag appends one announce tag and returns the updated copy.

func (AnnounceSpec) InsertMetadata

func (s AnnounceSpec) InsertMetadata(key, value string) AnnounceSpec

InsertMetadata inserts one metadata key/value pair and returns the updated copy.

Later calls with the same key replace the previous value.

func (AnnounceSpec) WithAddressSelection

func (s AnnounceSpec) WithAddressSelection(selection AddressSelection) AnnounceSpec

WithAddressSelection overrides automatic address selection for this spec.

This per spec override takes precedence over the client default policy when automatic LAN address discovery is enabled.

func (AnnounceSpec) WithDiscoveryDomain

func (s AnnounceSpec) WithDiscoveryDomain(discoveryDomain string) AnnounceSpec

WithDiscoveryDomain sets the logical discovery domain and returns the updated copy.

type Client

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

Client is the high level Go SDK entry point for discovery, announce and watch.

The client is safe to reuse across multiple operations. Default automatic address selection can be tuned with the SetIncludeXxx and Interface methods.

Example:

client := lnd.NewClient("https://registry.example.com", "secret-token")
nodes, err := client.Discover(
	context.Background(),
	lnd.NewDiscoveryFilter().WithDiscoveryDomain("office-net"),
)
if err != nil {
	return err
}
_ = nodes

func NewClient

func NewClient(baseURL, bearerToken string, opts ...ClientOption) *Client

NewClient creates a reusable Go SDK client.

baseURL must point at an lnd server root, for example https://registry.example.com. bearerToken is optional and may be empty.

The client does not contact the server during construction. Network and validation errors are returned by later API calls.

func (*Client) Announce

func (c *Client) Announce(ctx context.Context, spec AnnounceSpec) *AnnounceHandle

Announce starts a background announce loop.

The loop keeps renewing the lease roughly every TTLSeconds/3 with jitter, and it reconnects with exponential backoff after transient failures.

Call Close on the returned handle to stop it. The start itself is async, so initial errors are surfaced later by AnnounceHandle.Close.

func (*Client) AnnounceOnce

func (c *Client) AnnounceOnce(ctx context.Context, spec AnnounceSpec) (DiscoveredNode, error)

AnnounceOnce resolves addresses and performs one registration request.

The returned node is the server normalized record after deduplication and lease metadata attachment. Errors include local address resolution failures, HTTP transport failures, authentication failures and invalid server JSON.

func (*Client) ClearInterfaceFilters

func (c *Client) ClearInterfaceFilters() *Client

ClearInterfaceFilters clears the client default interface allowlist and denylist.

func (*Client) DisableInterface

func (c *Client) DisableInterface(name string) *Client

DisableInterface appends one interface denylist item to the client default policy.

Deny rules override allow rules when an interface appears in both lists.

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, filter DiscoveryFilter) ([]DiscoveredNode, error)

Discover performs one HTTP list request and returns the matching peers.

The method returns a slice of discovered nodes or an error when the request fails, the server rejects the filter, or the JSON response is invalid.

func (*Client) EnableInterface

func (c *Client) EnableInterface(name string) *Client

EnableInterface appends one interface allowlist item to the client default policy.

When the allowlist is non empty, only listed interfaces are considered.

func (*Client) ListReachabilityScopes

func (c *Client) ListReachabilityScopes() ([]string, error)

ListReachabilityScopes returns all locally derived subnet scopes.

func (*Client) ResolveAnnounceAddrs

func (c *Client) ResolveAnnounceAddrs(spec AnnounceSpec) ([]string, error)

ResolveAnnounceAddrs resolves the final address list for one announce specification.

The result merges explicit LanAddrs with automatically discovered addresses when AutoLanAddrs is enabled, and removes duplicates before returning.

func (*Client) ResolveReachabilityScopes

func (c *Client) ResolveReachabilityScopes(spec AnnounceSpec) ([]string, error)

ResolveReachabilityScopes resolves the final reachability scope list.

func (*Client) SetBearerToken

func (c *Client) SetBearerToken(token string) *Client

SetBearerToken updates the Bearer token for subsequent requests.

Pass an empty string to disable Authorization headers.

func (*Client) SetIncludeIPv6

func (c *Client) SetIncludeIPv6(on bool) *Client

SetIncludeIPv6 updates the default automatic address selection policy.

func (*Client) SetIncludeLinkLocalIPv4

func (c *Client) SetIncludeLinkLocalIPv4(on bool) *Client

SetIncludeLinkLocalIPv4 updates the default automatic address selection policy.

func (*Client) SetIncludeLoopback

func (c *Client) SetIncludeLoopback(on bool) *Client

SetIncludeLoopback updates the default automatic address selection policy.

This affects later address resolution unless a spec level override is set.

func (*Client) SetIncludePrivateIPv4

func (c *Client) SetIncludePrivateIPv4(on bool) *Client

SetIncludePrivateIPv4 updates the default automatic address selection policy.

func (*Client) SetServerURL

func (c *Client) SetServerURL(baseURL string) *Client

SetServerURL updates the server base URL for subsequent requests.

The value should be the server root URL without a trailing API path.

func (*Client) Watch

func (c *Client) Watch(ctx context.Context, filter DiscoveryFilter, callback func(DiscoveryEventEnvelope)) *WatchHandle

Watch starts a reconnecting watch loop.

callback receives parsed SSE events, including reset events and follow up snapshot resyncs. The loop automatically resumes from the latest cursor when the server supports replay.

Call Close on the returned handle to stop the watch. As with Announce, later stream setup errors are reported by WatchHandle.Close.

type ClientOption

type ClientOption func(*Client)

ClientOption customizes a Client created by NewClient.

func WithReconnectBackoff

func WithReconnectBackoff(min, max time.Duration) ClientOption

WithReconnectBackoff sets the reconnect backoff range.

min and max are used by the background watch and announce loops after transient failures.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the finite HTTP request timeout.

Use this when list or announce requests may traverse slower proxies or links. Long lived watch streams are not capped by this total timeout.

type DiscoveredNode

type DiscoveredNode struct {
	DiscoveryDomain    *string           `json:"discovery_domain"`
	NodeID             string            `json:"node_id"`
	Service            string            `json:"service"`
	DisplayName        string            `json:"display_name"`
	Port               uint16            `json:"port"`
	LanAddrs           []string          `json:"lan_addrs"`
	ReachabilityScopes []string          `json:"reachability_scopes"`
	Tags               []string          `json:"tags"`
	Metadata           map[string]string `json:"metadata"`
	Lease              LeaseInfo         `json:"lease"`
}

DiscoveredNode is the canonical peer record returned by list and watch calls.

type DiscoveryEvent

type DiscoveryEvent struct {
	Type  string           `json:"type"`
	Nodes []DiscoveredNode `json:"nodes,omitempty"`
	Node  *DiscoveredNode  `json:"node,omitempty"`
}

DiscoveryEvent describes one watch stream event.

Type is one of snapshot, upsert, remove, reset or keepalive.

type DiscoveryEventEnvelope

type DiscoveryEventEnvelope struct {
	Cursor *uint64        `json:"cursor"`
	Event  DiscoveryEvent `json:"event"`
}

DiscoveryEventEnvelope wraps a watch event with its latest resume cursor.

type DiscoveryFilter

type DiscoveryFilter struct {
	DiscoveryDomain    *string  `json:"discovery_domain,omitempty"`
	Service            string   `json:"service,omitempty"`
	Tags               []string `json:"tags,omitempty"`
	ReachabilityScopes []string `json:"reachability_scopes,omitempty"`
}

DiscoveryFilter describes which peers should be listed or watched.

DiscoveryDomain is optional and acts as a logical discovery domain. Service and Tags narrow the result set further. ReachabilityScopes require at least one overlap with the remote node.

Example:

filter := lnd.NewDiscoveryFilter().
	WithDiscoveryDomain("office-net").
	WithService("_http._tcp").
	AddTag("printer")

func NewDiscoveryFilter

func NewDiscoveryFilter() DiscoveryFilter

NewDiscoveryFilter creates a minimal discovery filter.

func (DiscoveryFilter) AddReachabilityScope

func (f DiscoveryFilter) AddReachabilityScope(scope string) DiscoveryFilter

AddReachabilityScope appends one scope overlap filter and returns the updated copy.

func (DiscoveryFilter) AddTag

func (f DiscoveryFilter) AddTag(tag string) DiscoveryFilter

AddTag appends one required tag filter and returns the updated copy.

A peer must contain every tag added to the filter to match.

func (DiscoveryFilter) WithDiscoveryDomain

func (f DiscoveryFilter) WithDiscoveryDomain(discoveryDomain string) DiscoveryFilter

WithDiscoveryDomain sets the logical discovery domain and returns the updated copy.

func (DiscoveryFilter) WithService

func (f DiscoveryFilter) WithService(service string) DiscoveryFilter

WithService sets the required service name and returns the updated copy.

Service names typically follow mDNS / DNS-SD service type conventions, for example "_http._tcp".

type LeaseInfo

type LeaseInfo struct {
	Revision        uint64 `json:"revision"`
	TTLSeconds      uint64 `json:"ttl_secs"`
	ExpiresAtUnixMS uint64 `json:"expires_at_unix_ms"`
	LastSeenUnixMS  uint64 `json:"last_seen_unix_ms"`
}

LeaseInfo contains server side lease state attached to a discovered node.

Revision increases whenever the server updates this node record.

type WatchHandle

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

WatchHandle manages a background watch loop started by Client.Watch.

Call Close to stop reconnection attempts and wait for the goroutine to exit.

func (*WatchHandle) Close

func (h *WatchHandle) Close() error

Close stops the background watch loop and waits for it to exit.

It returns the final loop error, or nil when the watch stopped cleanly.

Jump to

Keyboard shortcuts

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