### Install ldkgo package Source: https://github.com/lescuer97/ldkgo/blob/main/README.md Use go get to add the ldkgo dependency to your project. ```bash go get github.com/lescuer97/ldkgo ``` -------------------------------- ### Build and Start LDK Node with Filesystem Store Source: https://context7.com/lescuer97/ldkgo/llms.txt Builds and instantiates an LDK Node using filesystem storage for persistence. This example demonstrates setting up the node with testnet configuration and starting it. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Generate entropy mnemonic := ldk.GenerateEntropyMnemonic(nil) entropy := ldk.NodeEntropyFromBip39Mnemonic(mnemonic, nil) // Configure builder builder := ldk.NewBuilder() builder.SetStorageDirPath("/tmp/ldk_testnet_node") builder.SetNetwork(ldk.NetworkTestnet) builder.SetChainSourceEsplora("https://blockstream.info/testnet/api", nil) // Build node with filesystem store (recommended for persistence) node, err := builder.BuildWithFsStore(entropy) if err != nil { panic(fmt.Sprintf("Failed to build node: %v", err)) } defer node.Destroy() // Start the node if err := node.Start(); err != nil { panic(fmt.Sprintf("Failed to start node: %v", err)) } fmt.Println("Node ID:", node.NodeId()) } ``` -------------------------------- ### Start and Stop LDK Node Source: https://context7.com/lescuer97/ldkgo/llms.txt Initializes, starts, and gracefully stops the LDK node. Requires setting up storage, network, and chain source. Handles OS signals for shutdown. ```go package main import ( "fmt" "os" "os/signal" "syscall" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Setup node (abbreviated) mnemonic := ldk.GenerateEntropyMnemonic(nil) entropy := ldk.NodeEntropyFromBip39Mnemonic(mnemonic, nil) builder := ldk.NewBuilder() builder.SetStorageDirPath("/tmp/ldk_node") builder.SetNetwork(ldk.NetworkTestnet) builder.SetChainSourceEsplora("https://blockstream.info/testnet/api", nil) node, err := builder.BuildWithFsStore(entropy) if err != nil { panic(err) } defer node.Destroy() // Start the node if err := node.Start(); err != nil { panic(fmt.Sprintf("Failed to start: %v", err)) } fmt.Println("Node started with ID:", node.NodeId()) // Handle graceful shutdown sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) <-sigChan // Stop the node gracefully if err := node.Stop(); err != nil { fmt.Printf("Error stopping node: %v\n", err) } fmt.Println("Node stopped") } ``` -------------------------------- ### Create and Pay BOLT11 Invoices Source: https://context7.com/lescuer97/ldkgo/llms.txt Use the Bolt11Payment handler to create invoices for receiving payments and to pay existing BOLT11 invoices. Ensure the node is set up and started before using these methods. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { var node *ldk.Node // ... node setup and started // Get the BOLT11 payment handler bolt11 := node.Bolt11Payment() // Create an invoice to receive 50,000 sats amountMsat := uint64(50000 * 1000) // Amount in millisatoshis description := ldk.Bolt11InvoiceDescriptionDirect{ Description: "Payment for coffee", } expirySecs := uint32(3600) // 1 hour expiry invoice, err := bolt11.Receive(amountMsat, description, expirySecs) if err != nil { fmt.Printf("Failed to create invoice: %v\n", err) return } fmt.Printf("Invoice: %s\n", invoice.UniffiTraitDisplay()) // Create a zero-amount (variable amount) invoice zeroAmountInvoice, err := bolt11.ReceiveVariableAmount(description, expirySecs) if err != nil { fmt.Printf("Failed to create zero-amount invoice: %v\n", err) } fmt.Printf("Zero-amount invoice: %s\n", zeroAmountInvoice.UniffiTraitDisplay()) // Pay a BOLT11 invoice invoiceStr := "lntb..." // Invoice string to pay invoiceToPay, err := ldk.Bolt11InvoiceFromStr(invoiceStr) if err != nil { fmt.Printf("Failed to parse invoice: %v\n", err) return } paymentId, err := bolt11.Send(invoiceToPay, nil) if err != nil { fmt.Printf("Failed to send payment: %v\n", err) return } fmt.Printf("Payment sent, ID: %v\n", paymentId) } ``` -------------------------------- ### Get Default LDK Node Configuration Source: https://context7.com/lescuer97/ldkgo/llms.txt Retrieves the default configuration for an LDK Node. These defaults are suitable for most use cases and can be customized. ```go package main import ( ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Get default configuration config := ldk.DefaultConfig() // Default values include: // - StorageDirPath: "/tmp/ldk_node/" // - Network: Bitcoin mainnet // - ProbingLiquidityLimitMultiplier: 3 // Customize as needed config.StorageDirPath = "/path/to/my/node/data" config.Network = ldk.NetworkTestnet } ``` -------------------------------- ### Builder.Build / BuildWithFsStore Source: https://context7.com/lescuer97/ldkgo/llms.txt Instantiates an LDK Node using a configured builder. ```APIDOC ## Builder.Build / BuildWithFsStore ### Description Builds and instantiates the LDK Node with the configured settings, using either in-memory or filesystem storage. ### Parameters #### Request Body - **entropy** (NodeEntropy) - Required - The entropy object derived from a mnemonic. ### Response - **node** (Node) - The instantiated LDK Node instance. - **err** (error) - Error object if the build process fails. ``` -------------------------------- ### Validate and build bindings Source: https://github.com/lescuer97/ldkgo/blob/main/README.md Use make commands to verify bindings and run tests. Requires CGO_ENABLED=1. ```bash make generate # validate checked-in Linux binding artifacts and refresh checksums make verify # CGO_ENABLED=1 go test ./bindings/ldk_node_ffi make clean # remove generated linker stub ``` -------------------------------- ### Create and Configure LDK Node Builder Source: https://context7.com/lescuer97/ldkgo/llms.txt Initializes a new LDK Node builder, allowing for detailed configuration of node settings such as storage path, network, and chain/gossip sources. ```go package main import ( ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Option 1: Create builder with defaults builder := ldk.NewBuilder() // Configure the builder builder.SetStorageDirPath("/path/to/node/data") builder.SetNetwork(ldk.NetworkTestnet) builder.SetChainSourceEsplora("https://blockstream.info/testnet/api", nil) builder.SetGossipSourceRgs("https://rapidsync.lightningdevkit.org/testnet/snapshot") // Option 2: Create builder from existing config config := ldk.DefaultConfig() config.StorageDirPath = "/my/custom/path" config.Network = ldk.NetworkTestnet builderFromConfig := ldk.BuilderFromConfig(config) builderFromConfig.SetChainSourceEsplora("https://blockstream.info/testnet/api", nil) } ``` -------------------------------- ### Synchronize On-Chain Wallets Source: https://context7.com/lescuer97/ldkgo/llms.txt Shows how to perform manual wallet synchronization and implement a periodic sync loop using a ticker. ```go package main import ( "fmt" "time" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { var node *ldk.Node // ... node setup and started // Manual sync if err := node.SyncWallets(); err != nil { fmt.Printf("Sync failed: %v\n", err) return } fmt.Println("Wallets synced successfully") // Check updated balances after sync balances := node.ListBalances() fmt.Printf("Total on-chain: %d sats\n", balances.TotalOnchainBalanceSats) // Periodic sync pattern go func() { ticker := time.NewTicker(5 * time.Minute) defer ticker.Stop() for range ticker.C { if err := node.SyncWallets(); err != nil { fmt.Printf("Periodic sync failed: %v\n", err) } } }() } ``` -------------------------------- ### Import ldkgo Bindings Source: https://context7.com/lescuer97/ldkgo/llms.txt Import the necessary FFI bindings for LDK Node into your Go project. This makes the LDK Node functionalities available. ```go import "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ``` -------------------------------- ### Configure Builder Chain Source Source: https://context7.com/lescuer97/ldkgo/llms.txt Configures the blockchain backend and gossip source. Supports multiple backends including Esplora, Electrum, and Bitcoind. ```go package main import ( ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { builder := ldk.NewBuilder() builder.SetNetwork(ldk.NetworkTestnet) builder.SetStorageDirPath("/tmp/ldk_node") // Option 1: Esplora (HTTP REST API) builder.SetChainSourceEsplora("https://blockstream.info/testnet/api", nil) // Option 2: Electrum server // builder.SetChainSourceElectrum("ssl://electrum.blockstream.info:60002", nil) // Option 3: Bitcoind RPC // builder.SetChainSourceBitcoindRpc("127.0.0.1", 18332, "rpcuser", "rpcpassword") // Option 4: Bitcoind REST + RPC (faster block sync) // builder.SetChainSourceBitcoindRest( // "127.0.0.1", 18332, // REST // "127.0.0.1", 18332, // RPC // "rpcuser", "rpcpassword", // ) // Set gossip source for routing builder.SetGossipSourceRgs("https://rapidsync.lightningdevkit.org/testnet/snapshot") } ``` -------------------------------- ### DefaultConfig Source: https://context7.com/lescuer97/ldkgo/llms.txt Retrieves the default configuration settings for an LDK Node. ```APIDOC ## DefaultConfig ### Description Returns the default configuration for an LDK Node with sensible defaults for most use cases. ### Response - **config** (Config) - The default configuration object containing StorageDirPath, Network, and ProbingLiquidityLimitMultiplier. ``` -------------------------------- ### Connect and Disconnect from LDK Peer Source: https://context7.com/lescuer97/ldkgo/llms.txt Establishes and terminates connections to Lightning Network peers. Requires a valid peer public key and socket address. Can optionally persist peer information for reconnection. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Assume node is already created and started var node *ldk.Node // ... node setup // Parse peer public key peerPubKey := ldk.PublicKey("02...") // 33-byte compressed pubkey hex // Create socket address for peer address := ldk.SocketAddressTcpIpV4{ Addr: [4]byte{127, 0, 0, 1}, Port: 9735, } // Connect to peer (persist=true saves peer info for reconnection) err := node.Connect(peerPubKey, address, true) if err != nil { fmt.Printf("Failed to connect: %v\n", err) return } fmt.Println("Connected to peer") // List connected peers peers := node.ListPeers() for _, peer := range peers { fmt.Printf("Peer: %s, Connected: %v\n", peer.NodeId, peer.IsConnected) } // Disconnect from peer if err := node.Disconnect(peerPubKey); err != nil { fmt.Printf("Failed to disconnect: %v\n", err) } } ``` -------------------------------- ### Create Node Entropy from Mnemonic Source: https://context7.com/lescuer97/ldkgo/llms.txt Derives node entropy from a BIP39 mnemonic phrase, optionally using a passphrase for enhanced security. This entropy is used to build the LDK Node. ```go package main import ( ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Generate or use existing mnemonic mnemonic := ldk.GenerateEntropyMnemonic(nil) // Create entropy without passphrase entropy := ldk.NodeEntropyFromBip39Mnemonic(mnemonic, nil) // Create entropy with passphrase for additional security passphrase := "my-secure-passphrase" entropyWithPassphrase := ldk.NodeEntropyFromBip39Mnemonic(mnemonic, &passphrase) // Use entropy to build a node builder := ldk.NewBuilder() node, err := builder.Build(entropy) if err != nil { panic(err) } defer node.Destroy() } ``` -------------------------------- ### Generate BIP39 Mnemonic Phrase Source: https://context7.com/lescuer97/ldkgo/llms.txt Generates a new BIP39 mnemonic phrase for wallet seed entropy. Supports both 12 and 24-word configurations. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { // Generate a 24-word mnemonic (default) mnemonic := ldk.GenerateEntropyMnemonic(nil) fmt.Println("Generated mnemonic:", mnemonic) // Generate a 12-word mnemonic wordCount := ldk.WordCountWords12 mnemonic12 := ldk.GenerateEntropyMnemonic(&wordCount) fmt.Println("12-word mnemonic:", mnemonic12) } ``` -------------------------------- ### GenerateEntropyMnemonic Source: https://context7.com/lescuer97/ldkgo/llms.txt Generates a BIP39 mnemonic phrase for wallet seed entropy. ```APIDOC ## GenerateEntropyMnemonic ### Description Generates a new BIP39 mnemonic phrase for wallet seed entropy, supporting 12 or 24 word configurations. ### Parameters #### Request Body - **wordCount** (*WordCount) - Optional - The number of words for the mnemonic (e.g., WordCountWords12). Defaults to 24 words if nil. ### Response - **mnemonic** (string) - The generated BIP39 mnemonic phrase. ``` -------------------------------- ### Process Lightning Network Events Source: https://context7.com/lescuer97/ldkgo/llms.txt Demonstrates both blocking event loops and non-blocking event checks. Always call EventHandled after processing an event to prevent event queue buildup. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { var node *ldk.Node // ... node setup and started // Event loop pattern go func() { for { // Wait for the next event (blocking) event := node.WaitNextEvent() // Handle different event types switch e := event.(type) { case ldk.EventPaymentReceived: fmt.Printf("Payment received! ID: %v, Amount: %d msat\n", e.PaymentId, e.AmountMsat) case ldk.EventPaymentSuccessful: fmt.Printf("Payment successful! ID: %v\n", e.PaymentId) case ldk.EventPaymentFailed: fmt.Printf("Payment failed! ID: %v, Reason: %v\n", e.PaymentId, e.Reason) case ldk.EventChannelReady: fmt.Printf("Channel ready! ID: %v, Counterparty: %s\n", e.ChannelId, e.CounterpartyNodeId) case ldk.EventChannelClosed: fmt.Printf("Channel closed! ID: %v, Reason: %v\n", e.ChannelId, e.Reason) case ldk.EventChannelPending: fmt.Printf("Channel pending! ID: %v\n", e.ChannelId) default: fmt.Printf("Received event: %T\n", event) } // Mark event as handled (important!) if err := node.EventHandled(); err != nil { fmt.Printf("Failed to mark event handled: %v\n", err) } } }() // Non-blocking event check if event := node.NextEvent(); event != nil { fmt.Printf("Got event: %T\n", *event) node.EventHandled() } } ``` -------------------------------- ### Bolt12Payment API Source: https://context7.com/lescuer97/ldkgo/llms.txt Methods for creating BOLT12 offers and paying BOLT12 offers. ```APIDOC ## Bolt12Payment.Receive ### Description Creates a BOLT12 offer to receive a specific amount. ### Parameters - **amountMsat** (uint64) - Required - Amount in millisatoshis - **description** (string) - Optional - Offer description - **expirySecs** (uint32) - Optional - Expiry in seconds ## Bolt12Payment.Send ### Description Pays a BOLT12 offer. ### Parameters - **offer** (Offer) - Required - The offer to pay - **amountMsat** (uint64, optional) - Optional - Amount to pay - **payerNote** (string) - Optional - Note from the payer - **quantity** (uint64) - Optional - Quantity of items ``` -------------------------------- ### Open and Close LDK Channels Source: https://context7.com/lescuer97/ldkgo/llms.txt Opens and closes Lightning payment channels with connected peers. Supports both private and public channels, with options for initial push amounts and channel configurations. Includes cooperative and force close methods. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { var node *ldk.Node // ... node setup and started peerPubKey := ldk.PublicKey("02...") address := ldk.SocketAddressTcpIpV4{ Addr: [4]byte{127, 0, 0, 1}, Port: 9735, } // Open a private channel with 100,000 sats channelAmountSats := uint64(100000) channelId, err := node.OpenChannel( peerPubKey, address, channelAmountSats, nil, // pushToCounterpartyMsat (optional initial balance to push) nil, // channelConfig (use defaults) ) if err != nil { fmt.Printf("Failed to open channel: %v\n", err) return } fmt.Printf("Channel opening initiated, ID: %v\n", channelId) // Open a public (announced) channel publicChannelId, err := node.OpenAnnouncedChannel( peerPubKey, address, uint64(500000), // 500k sats nil, nil, ) if err != nil { fmt.Printf("Failed to open announced channel: %v\n", err) } // List channels channels := node.ListChannels() for _, ch := range channels { fmt.Printf("Channel: %v, Capacity: %d sats, Ready: %v\n", ch.ChannelId, ch.ChannelValueSats, ch.IsChannelReady) } // Close channel cooperatively if err := node.CloseChannel(channelId, peerPubKey); err != nil { fmt.Printf("Failed to close channel: %v\n", err) } // Force close channel (use only if cooperative close fails) reason := "Unresponsive peer" if err := node.ForceCloseChannel(publicChannelId, peerPubKey, &reason); err != nil { fmt.Printf("Failed to force close: %v\n", err) } } ``` -------------------------------- ### Create and Pay BOLT12 Offers Source: https://context7.com/lescuer97/ldkgo/llms.txt Utilize the Bolt12Payment handler to generate BOLT12 offers for receiving payments and to send payments against existing BOLT12 offers. These offer enhanced privacy features. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { var node *ldk.Node // ... node setup and started // Get the BOLT12 payment handler bolt12 := node.Bolt12Payment() // Create a BOLT12 offer to receive 100,000 sats amountMsat := uint64(100000 * 1000) description := "Buy my product" expirySecs := uint32(86400) // 24 hours offer, err := bolt12.Receive(amountMsat, &description, &expirySecs, nil) if err != nil { fmt.Printf("Failed to create offer: %v\n", err) return } fmt.Printf("BOLT12 Offer: %s\n", offer.UniffiTraitDisplay()) // Create variable amount offer varOffer, err := bolt12.ReceiveVariableAmount(&description, &expirySecs) if err != nil { fmt.Printf("Failed to create variable offer: %v\n", err) } fmt.Printf("Variable amount offer: %s\n", varOffer.UniffiTraitDisplay()) // Pay a BOLT12 offer offerStr := "lno1..." // Offer string to pay offerToPay, err := ldk.OfferFromStr(offerStr) if err != nil { fmt.Printf("Failed to parse offer: %v\n", err) return } payerNote := "Thanks for the product!" paymentId, err := bolt12.Send(offerToPay, nil, &payerNote, nil) if err != nil { fmt.Printf("Failed to pay offer: %v\n", err) return } fmt.Printf("BOLT12 payment sent, ID: %v\n", paymentId) } ``` -------------------------------- ### Bolt11Payment API Source: https://context7.com/lescuer97/ldkgo/llms.txt Methods for creating BOLT11 invoices and paying existing BOLT11 invoices. ```APIDOC ## Bolt11Payment.Receive ### Description Creates a BOLT11 invoice to receive a specific amount of sats. ### Parameters - **amountMsat** (uint64) - Required - Amount in millisatoshis - **description** (Bolt11InvoiceDescriptionDirect) - Required - Invoice description - **expirySecs** (uint32) - Required - Expiry in seconds ## Bolt11Payment.ReceiveVariableAmount ### Description Creates a BOLT11 invoice with a variable amount. ### Parameters - **description** (Bolt11InvoiceDescriptionDirect) - Required - Invoice description - **expirySecs** (uint32) - Required - Expiry in seconds ## Bolt11Payment.Send ### Description Pays a BOLT11 invoice. ### Parameters - **invoice** (Bolt11Invoice) - Required - The invoice to pay - **amountMsat** (uint64, optional) - Optional - Amount to pay if invoice is zero-amount ``` -------------------------------- ### NodeEntropyFromBip39Mnemonic Source: https://context7.com/lescuer97/ldkgo/llms.txt Derives node entropy from a BIP39 mnemonic. ```APIDOC ## NodeEntropyFromBip39Mnemonic ### Description Creates node entropy from a BIP39 mnemonic phrase with an optional passphrase for deterministic key derivation. ### Parameters #### Request Body - **mnemonic** (string) - Required - The BIP39 mnemonic phrase. - **passphrase** (*string) - Optional - An optional passphrase for additional security. ### Response - **entropy** (NodeEntropy) - The derived entropy object used to build a node. ``` -------------------------------- ### OnchainPayment API Source: https://context7.com/lescuer97/ldkgo/llms.txt Methods for managing on-chain Bitcoin addresses and transactions. ```APIDOC ## OnchainPayment.NewAddress ### Description Generates a new on-chain Bitcoin funding address. ## OnchainPayment.SendToAddress ### Description Sends a specified amount of sats to an on-chain address. ### Parameters - **address** (Address) - Required - Destination address - **amountSats** (uint64) - Required - Amount in sats - **feeRate** (uint32) - Optional - Fee rate ## OnchainPayment.SendAllToAddress ### Description Sends all available funds to an address. ### Parameters - **address** (Address) - Required - Destination address - **retainReserves** (bool) - Required - Whether to retain wallet reserves - **feeRate** (uint32) - Optional - Fee rate ``` -------------------------------- ### Manage On-Chain Bitcoin Transactions Source: https://context7.com/lescuer97/ldkgo/llms.txt Use the OnchainPayment handler to generate new Bitcoin addresses for receiving funds and to send Bitcoin to specified addresses. This is essential for funding your Lightning wallet and withdrawing funds. ```go package main import ( "fmt" ldk "github.com/lescuer97/ldkgo/bindings/ldk_node_ffi" ) func main() { var node *ldk.Node // ... node setup and started // Get the on-chain payment handler onchain := node.OnchainPayment() // Generate a new funding address address, err := onchain.NewAddress() if err != nil { fmt.Printf("Failed to get address: %v\n", err) return } fmt.Printf("Deposit address: %s\n", address) // Check balances balances := node.ListBalances() fmt.Printf("On-chain balance: %d sats\n", balances.TotalOnchainBalanceSats) fmt.Printf("Spendable on-chain: %d sats\n", balances.SpendableOnchainBalanceSats) fmt.Printf("Lightning balance: %d sats\n", balances.TotalLightningBalanceSats) // Send on-chain payment destinationAddress := ldk.Address("tb1q...") // Testnet address amountSats := uint64(50000) txid, err := onchain.SendToAddress(destinationAddress, amountSats, nil) if err != nil { fmt.Printf("Failed to send: %v\n", err) return } fmt.Printf("Transaction sent: %s\n", txid) // Send all funds (drain wallet) txid, err = onchain.SendAllToAddress(destinationAddress, true, nil) // retainReserves=true if err != nil { fmt.Printf("Failed to drain: %v\n", err) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.