Merge pull request #4757 from Crypt-iQ/fmgr_1109

funding: move Manager to own package
This commit is contained in:
Eugene authored and GitHub committed 2020-12-17 11:43:12 -05:00
commit e0439965bb
15 files changed
+653 -657

No files matched your search

+12 -11
View File
@@ -27,6 +27,7 @@ import (
"github.com/lightningnetwork/lnd/chanbackup" "github.com/lightningnetwork/lnd/chanbackup"
"github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/discovery" "github.com/lightningnetwork/lnd/discovery"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/htlcswitch" "github.com/lightningnetwork/lnd/htlcswitch"
"github.com/lightningnetwork/lnd/htlcswitch/hodl" "github.com/lightningnetwork/lnd/htlcswitch/hodl"
"github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/input"
@@ -413,7 +414,7 @@ func DefaultConfig() Config {
Autopilot: &lncfg.AutoPilot{ Autopilot: &lncfg.AutoPilot{
MaxChannels: 5, MaxChannels: 5,
Allocation: 0.6, Allocation: 0.6,
MinChannelSize: int64(minChanFundingSize), MinChannelSize: int64(funding.MinChanFundingSize),
MaxChannelSize: int64(MaxFundingAmount), MaxChannelSize: int64(MaxFundingAmount),
MinConfs: 1, MinConfs: 1,
ConfTarget: autopilot.DefaultConfTarget, ConfTarget: autopilot.DefaultConfTarget,
@@ -429,7 +430,7 @@ func DefaultConfig() Config {
HeightHintCacheQueryDisable: defaultHeightHintCacheQueryDisable, HeightHintCacheQueryDisable: defaultHeightHintCacheQueryDisable,
Alias: defaultAlias, Alias: defaultAlias,
Color: defaultColor, Color: defaultColor,
MinChanSize: int64(minChanFundingSize), MinChanSize: int64(funding.MinChanFundingSize),
MaxChanSize: int64(0), MaxChanSize: int64(0),
DefaultRemoteMaxHtlcs: defaultRemoteMaxHtlcs, DefaultRemoteMaxHtlcs: defaultRemoteMaxHtlcs,
NumGraphSyncPeers: defaultMinPeers, NumGraphSyncPeers: defaultMinPeers,
@@ -689,8 +690,8 @@ func ValidateConfig(cfg Config, usageMessage string) (*Config, error) {
// Ensure that the specified values for the min and max channel size // Ensure that the specified values for the min and max channel size
// are within the bounds of the normal chan size constraints. // are within the bounds of the normal chan size constraints.
if cfg.Autopilot.MinChannelSize < int64(minChanFundingSize) { if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
cfg.Autopilot.MinChannelSize = int64(minChanFundingSize) cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
} }
if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) { if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount) cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
@@ -707,9 +708,9 @@ func ValidateConfig(cfg Config, usageMessage string) (*Config, error) {
// If unset (marked by 0 value), then enforce proper default. // If unset (marked by 0 value), then enforce proper default.
if cfg.MaxChanSize == 0 { if cfg.MaxChanSize == 0 {
if cfg.ProtocolOptions.Wumbo() { if cfg.ProtocolOptions.Wumbo() {
cfg.MaxChanSize = int64(MaxBtcFundingAmountWumbo) cfg.MaxChanSize = int64(funding.MaxBtcFundingAmountWumbo)
} else { } else {
cfg.MaxChanSize = int64(MaxBtcFundingAmount) cfg.MaxChanSize = int64(funding.MaxBtcFundingAmount)
} }
} }
@@ -857,7 +858,7 @@ func ValidateConfig(cfg Config, usageMessage string) (*Config, error) {
"litecoin.active must be set to 1 (true)", funcName) "litecoin.active must be set to 1 (true)", funcName)
case cfg.Litecoin.Active: case cfg.Litecoin.Active:
err := cfg.Litecoin.Validate(minTimeLockDelta, minLtcRemoteDelay) err := cfg.Litecoin.Validate(minTimeLockDelta, funding.MinLtcRemoteDelay)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -941,7 +942,7 @@ func ValidateConfig(cfg Config, usageMessage string) (*Config, error) {
// Finally we'll register the litecoin chain as our current // Finally we'll register the litecoin chain as our current
// primary chain. // primary chain.
cfg.registeredChains.RegisterPrimaryChain(chainreg.LitecoinChain) cfg.registeredChains.RegisterPrimaryChain(chainreg.LitecoinChain)
MaxFundingAmount = maxLtcFundingAmount MaxFundingAmount = funding.MaxLtcFundingAmount
case cfg.Bitcoin.Active: case cfg.Bitcoin.Active:
// Multiple networks can't be selected simultaneously. Count // Multiple networks can't be selected simultaneously. Count
@@ -982,7 +983,7 @@ func ValidateConfig(cfg Config, usageMessage string) (*Config, error) {
return nil, err return nil, err
} }
err := cfg.Bitcoin.Validate(minTimeLockDelta, minBtcRemoteDelay) err := cfg.Bitcoin.Validate(minTimeLockDelta, funding.MinBtcRemoteDelay)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -1060,8 +1061,8 @@ func ValidateConfig(cfg Config, usageMessage string) (*Config, error) {
// Ensure that the specified values for the min and max channel size // Ensure that the specified values for the min and max channel size
// don't are within the bounds of the normal chan size constraints. // don't are within the bounds of the normal chan size constraints.
if cfg.Autopilot.MinChannelSize < int64(minChanFundingSize) { if cfg.Autopilot.MinChannelSize < int64(funding.MinChanFundingSize) {
cfg.Autopilot.MinChannelSize = int64(minChanFundingSize) cfg.Autopilot.MinChannelSize = int64(funding.MinChanFundingSize)
} }
if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) { if cfg.Autopilot.MaxChannelSize > int64(MaxFundingAmount) {
cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount) cfg.Autopilot.MaxChannelSize = int64(MaxFundingAmount)
+7 -6
View File
@@ -1,20 +1,21 @@
package fmgr package funding
import ( import (
"github.com/lightningnetwork/lnd/lnpeer" "github.com/lightningnetwork/lnd/lnpeer"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
) )
// Manager is an interface that describes the basic operation of a funding // Controller is an interface with basic funding flow functions.
// manager. It should at a minimum process a subset of lnwire messages that // It describes the basic functionality of a funding manager.
// It should at a minimum process a subset of lnwire messages that
// are denoted as funding messages. // are denoted as funding messages.
type Manager interface { type Controller interface {
// ProcessFundingMsg processes a funding message represented by the // ProcessFundingMsg processes a funding message represented by the
// lnwire.Message parameter along with the Peer object representing a // lnwire.Message parameter along with the Peer object representing a
// connection to the counterparty. // connection to the counterparty.
ProcessFundingMsg(lnwire.Message, lnpeer.Peer) ProcessFundingMsg(lnwire.Message, lnpeer.Peer)
// IsPendingChannel is used to determine whether to send an Error message // IsPendingChannel returns whether a particular 32-byte identifier
// to the funding manager or not. // represents a pending channel in the Controller implementation.
IsPendingChannel([32]byte, lnpeer.Peer) bool IsPendingChannel([32]byte, lnpeer.Peer) bool
} }
+27
View File
@@ -0,0 +1,27 @@
package funding
import (
"github.com/btcsuite/btclog"
"github.com/lightningnetwork/lnd/build"
)
// Subsystem defines the logging code for this subsystem.
const Subsystem = "FNDG"
// log is a logger that is initialized with the btclog.Disabled logger.
var log btclog.Logger
// The default amount of logging is none.
func init() {
UseLogger(build.NewSubLogger(Subsystem, nil))
}
// DisableLog disables all logging output.
func DisableLog() {
UseLogger(btclog.Disabled)
}
// UseLogger uses a specified Logger to output package logging info.
func UseLogger(logger btclog.Logger) {
log = logger
}
File diff suppressed because it is too large. Load diff
+177 -160
View File
@@ -1,6 +1,6 @@
// +build !rpctest // +build !rpctest
package lnd package funding
import ( import (
"bytes" "bytes"
@@ -59,6 +59,10 @@ const (
// A dummy value to use for the funding broadcast height. // A dummy value to use for the funding broadcast height.
fundingBroadcastHeight = 123 fundingBroadcastHeight = 123
// defaultMaxLocalCSVDelay is the maximum delay we accept on our
// commitment output.
defaultMaxLocalCSVDelay = 10000
) )
var ( var (
@@ -184,7 +188,7 @@ type testNode struct {
msgChan chan lnwire.Message msgChan chan lnwire.Message
announceChan chan lnwire.Message announceChan chan lnwire.Message
publTxChan chan *wire.MsgTx publTxChan chan *wire.MsgTx
fundingMgr *fundingManager fundingMgr *Manager
newChannels chan *newChannelMsg newChannels chan *newChannelMsg
mockNotifier *mockNotifier mockNotifier *mockNotifier
mockChanEvent *mockChanEvent mockChanEvent *mockChanEvent
@@ -346,7 +350,7 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
chainedAcceptor := chanacceptor.NewChainedAcceptor() chainedAcceptor := chanacceptor.NewChainedAcceptor()
fundingCfg := fundingConfig{ fundingCfg := Config{
IDKey: privKey.PubKey(), IDKey: privKey.PubKey(),
Wallet: lnw, Wallet: lnw,
Notifier: chainNotifier, Notifier: chainNotifier,
@@ -433,7 +437,7 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
}, },
ZombieSweeperInterval: 1 * time.Hour, ZombieSweeperInterval: 1 * time.Hour,
ReservationTimeout: 1 * time.Nanosecond, ReservationTimeout: 1 * time.Nanosecond,
MaxChanSize: MaxFundingAmount, MaxChanSize: MaxBtcFundingAmount,
MaxLocalCSVDelay: defaultMaxLocalCSVDelay, MaxLocalCSVDelay: defaultMaxLocalCSVDelay,
MaxPendingChannels: lncfg.DefaultMaxPendingChannels, MaxPendingChannels: lncfg.DefaultMaxPendingChannels,
NotifyOpenChannelEvent: evt.NotifyOpenChannelEvent, NotifyOpenChannelEvent: evt.NotifyOpenChannelEvent,
@@ -446,7 +450,7 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
op(&fundingCfg) op(&fundingCfg)
} }
f, err := newFundingManager(fundingCfg) f, err := NewFundingManager(fundingCfg)
if err != nil { if err != nil {
t.Fatalf("failed creating fundingManager: %v", err) t.Fatalf("failed creating fundingManager: %v", err)
} }
@@ -480,9 +484,7 @@ func createTestFundingManager(t *testing.T, privKey *btcec.PrivateKey,
func recreateAliceFundingManager(t *testing.T, alice *testNode) { func recreateAliceFundingManager(t *testing.T, alice *testNode) {
// Stop the old fundingManager before creating a new one. // Stop the old fundingManager before creating a new one.
close(alice.shutdownChannel) close(alice.shutdownChannel)
if err := alice.fundingMgr.Stop(); err != nil { alice.fundingMgr.Stop()
t.Fatalf("unable to stop old fundingManager: %v", err)
}
aliceMsgChan := make(chan lnwire.Message) aliceMsgChan := make(chan lnwire.Message)
aliceAnnounceChan := make(chan lnwire.Message) aliceAnnounceChan := make(chan lnwire.Message)
@@ -493,7 +495,7 @@ func recreateAliceFundingManager(t *testing.T, alice *testNode) {
chainedAcceptor := chanacceptor.NewChainedAcceptor() chainedAcceptor := chanacceptor.NewChainedAcceptor()
f, err := newFundingManager(fundingConfig{ f, err := NewFundingManager(Config{
IDKey: oldCfg.IDKey, IDKey: oldCfg.IDKey,
Wallet: oldCfg.Wallet, Wallet: oldCfg.Wallet,
Notifier: oldCfg.Notifier, Notifier: oldCfg.Notifier,
@@ -558,7 +560,7 @@ func recreateAliceFundingManager(t *testing.T, alice *testNode) {
} }
} }
type cfgOption func(*fundingConfig) type cfgOption func(*Config)
func setupFundingManagers(t *testing.T, func setupFundingManagers(t *testing.T,
options ...cfgOption) (*testNode, *testNode) { options ...cfgOption) (*testNode, *testNode) {
@@ -620,12 +622,8 @@ func tearDownFundingManagers(t *testing.T, a, b *testNode) {
close(a.shutdownChannel) close(a.shutdownChannel)
close(b.shutdownChannel) close(b.shutdownChannel)
if err := a.fundingMgr.Stop(); err != nil { a.fundingMgr.Stop()
t.Fatalf("unable to stop fundingManager: %v", err) b.fundingMgr.Stop()
}
if err := b.fundingMgr.Stop(); err != nil {
t.Fatalf("unable to stop fundingManager: %v", err)
}
os.RemoveAll(a.testDir) os.RemoveAll(a.testDir)
os.RemoveAll(b.testDir) os.RemoveAll(b.testDir)
} }
@@ -656,25 +654,26 @@ func fundChannel(t *testing.T, alice, bob *testNode, localFundingAmt,
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
subtractFees: subtractFees, ChainHash: *fundingNetParams.GenesisHash,
localFundingAmt: localFundingAmt, SubtractFees: subtractFees,
pushAmt: lnwire.NewMSatFromSatoshis(pushAmt), LocalFundingAmt: localFundingAmt,
fundingFeePerKw: 1000, PushAmt: lnwire.NewMSatFromSatoshis(pushAmt),
private: !announceChan, FundingFeePerKw: 1000,
updates: updateChan, Private: !announceChan,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -1316,22 +1315,23 @@ func testLocalCSVLimit(t *testing.T, aliceMaxCSV, bobRequiredCSV uint16) {
// First, we will initiate an outgoing channel from Alice -> Bob. // First, we will initiate an outgoing channel from Alice -> Bob.
errChan := make(chan error, 1) errChan := make(chan error, 1)
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 200000, ChainHash: *fundingNetParams.GenesisHash,
fundingFeePerKw: 1000, LocalFundingAmt: 200000,
updates: updateChan, FundingFeePerKw: 1000,
err: errChan, Updates: updateChan,
Err: errChan,
} }
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
@@ -1381,23 +1381,24 @@ func testLocalCSVLimit(t *testing.T, aliceMaxCSV, bobRequiredCSV uint16) {
// handle incoming channels, opening a channel from Bob->Alice. // handle incoming channels, opening a channel from Bob->Alice.
errChan = make(chan error, 1) errChan = make(chan error, 1)
updateChan = make(chan *lnrpc.OpenStatusUpdate) updateChan = make(chan *lnrpc.OpenStatusUpdate)
initReq = &openChanReq{ initReq = &InitFundingMsg{
targetPubkey: alice.privKey.PubKey(), Peer: alice,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: alice.privKey.PubKey(),
localFundingAmt: 200000, ChainHash: *fundingNetParams.GenesisHash,
fundingFeePerKw: 1000, LocalFundingAmt: 200000,
updates: updateChan, FundingFeePerKw: 1000,
err: errChan, Updates: updateChan,
Err: errChan,
} }
bob.fundingMgr.initFundingWorkflow(alice, initReq) bob.fundingMgr.InitFundingWorkflow(initReq)
// Bob should have sent the OpenChannel message to Alice. // Bob should have sent the OpenChannel message to Alice.
var bobMsg lnwire.Message var bobMsg lnwire.Message
select { select {
case bobMsg = <-bob.msgChan: case bobMsg = <-bob.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("bob OpenChannel message failed: %v", err) t.Fatalf("bob OpenChannel message failed: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
@@ -1501,9 +1502,7 @@ func TestFundingManagerRestartBehavior(t *testing.T) {
// implementation, and expect it to retry sending the fundingLocked // implementation, and expect it to retry sending the fundingLocked
// message. We'll explicitly shut down Alice's funding manager to // message. We'll explicitly shut down Alice's funding manager to
// prevent a race when overriding the sendMessage implementation. // prevent a race when overriding the sendMessage implementation.
if err := alice.fundingMgr.Stop(); err != nil { alice.fundingMgr.Stop()
t.Fatalf("unable to stop alice's funding manager: %v", err)
}
bob.sendMessage = workingSendMessage bob.sendMessage = workingSendMessage
recreateAliceFundingManager(t, alice) recreateAliceFundingManager(t, alice)
@@ -1721,7 +1720,7 @@ func TestFundingManagerOfflinePeer(t *testing.T) {
// TestFundingManagerPeerTimeoutAfterInitFunding checks that the zombie sweeper // TestFundingManagerPeerTimeoutAfterInitFunding checks that the zombie sweeper
// will properly clean up a zombie reservation that times out after the // will properly clean up a zombie reservation that times out after the
// initFundingMsg has been handled. // InitFundingMsg has been handled.
func TestFundingManagerPeerTimeoutAfterInitFunding(t *testing.T) { func TestFundingManagerPeerTimeoutAfterInitFunding(t *testing.T) {
t.Parallel() t.Parallel()
@@ -1733,23 +1732,24 @@ func TestFundingManagerPeerTimeoutAfterInitFunding(t *testing.T) {
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 500000, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(0), LocalFundingAmt: 500000,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(0),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -1795,23 +1795,24 @@ func TestFundingManagerPeerTimeoutAfterFundingOpen(t *testing.T) {
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 500000, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(0), LocalFundingAmt: 500000,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(0),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -1866,23 +1867,24 @@ func TestFundingManagerPeerTimeoutAfterFundingAccept(t *testing.T) {
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 500000, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(0), LocalFundingAmt: 500000,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(0),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -2590,26 +2592,27 @@ func TestFundingManagerCustomChannelParameters(t *testing.T) {
// Create a funding request with the custom parameters and start the // Create a funding request with the custom parameters and start the
// workflow. // workflow.
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: localAmt, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(pushAmt), LocalFundingAmt: localAmt,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(pushAmt),
maxValueInFlight: maxValueInFlight, Private: false,
minHtlcIn: minHtlcIn, MaxValueInFlight: maxValueInFlight,
remoteCsvDelay: csvDelay, MinHtlcIn: minHtlcIn,
updates: updateChan, RemoteCsvDelay: csvDelay,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -2864,25 +2867,26 @@ func TestFundingManagerMaxPendingChannels(t *testing.T) {
t.Parallel() t.Parallel()
alice, bob := setupFundingManagers( alice, bob := setupFundingManagers(
t, func(cfg *fundingConfig) { t, func(cfg *Config) {
cfg.MaxPendingChannels = maxPending cfg.MaxPendingChannels = maxPending
}, },
) )
defer tearDownFundingManagers(t, alice, bob) defer tearDownFundingManagers(t, alice, bob)
// Create openChanReqs for maxPending+1 channels. // Create InitFundingMsg structs for maxPending+1 channels.
var initReqs []*openChanReq var initReqs []*InitFundingMsg
for i := 0; i < maxPending+1; i++ { for i := 0; i < maxPending+1; i++ {
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 5000000, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(0), LocalFundingAmt: 5000000,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(0),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
initReqs = append(initReqs, initReq) initReqs = append(initReqs, initReq)
} }
@@ -2891,13 +2895,13 @@ func TestFundingManagerMaxPendingChannels(t *testing.T) {
var accepts []*lnwire.AcceptChannel var accepts []*lnwire.AcceptChannel
var lastOpen *lnwire.OpenChannel var lastOpen *lnwire.OpenChannel
for i, initReq := range initReqs { for i, initReq := range initReqs {
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -2973,7 +2977,7 @@ func TestFundingManagerMaxPendingChannels(t *testing.T) {
// publish a funding tx to the network. // publish a funding tx to the network.
var pendingUpdate *lnrpc.OpenStatusUpdate var pendingUpdate *lnrpc.OpenStatusUpdate
select { select {
case pendingUpdate = <-initReqs[i].updates: case pendingUpdate = <-initReqs[i].Updates:
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenStatusUpdate_ChanPending") t.Fatalf("alice did not send OpenStatusUpdate_ChanPending")
} }
@@ -3036,7 +3040,7 @@ func TestFundingManagerRejectPush(t *testing.T) {
// Enable 'rejectpush' option and initialize funding managers. // Enable 'rejectpush' option and initialize funding managers.
alice, bob := setupFundingManagers( alice, bob := setupFundingManagers(
t, func(cfg *fundingConfig) { t, func(cfg *Config) {
cfg.RejectPush = true cfg.RejectPush = true
}, },
) )
@@ -3045,23 +3049,24 @@ func TestFundingManagerRejectPush(t *testing.T) {
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 500000, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(10), LocalFundingAmt: 500000,
private: true, PushAmt: lnwire.NewMSatFromSatoshis(10),
updates: updateChan, Private: true,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -3102,23 +3107,24 @@ func TestFundingManagerMaxConfs(t *testing.T) {
// Create a funding request and start the workflow. // Create a funding request and start the workflow.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: 500000, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(10), LocalFundingAmt: 500000,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(10),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
// Alice should have sent the OpenChannel message to Bob. // Alice should have sent the OpenChannel message to Bob.
var aliceMsg lnwire.Message var aliceMsg lnwire.Message
select { select {
case aliceMsg = <-alice.msgChan: case aliceMsg = <-alice.msgChan:
case err := <-initReq.err: case err := <-initReq.Err:
t.Fatalf("error init funding workflow: %v", err) t.Fatalf("error init funding workflow: %v", err)
case <-time.After(time.Second * 5): case <-time.After(time.Second * 5):
t.Fatalf("alice did not send OpenChannel message") t.Fatalf("alice did not send OpenChannel message")
@@ -3374,29 +3380,30 @@ func TestMaxChannelSizeConfig(t *testing.T) {
// Create a set of funding managers that will reject wumbo // Create a set of funding managers that will reject wumbo
// channels but set --maxchansize explicitly lower than soft-limit. // channels but set --maxchansize explicitly lower than soft-limit.
// Verify that wumbo rejecting funding managers will respect --maxchansize // Verify that wumbo rejecting funding managers will respect --maxchansize
// below 16777215 satoshi (MaxFundingAmount) limit. // below 16777215 satoshi (MaxBtcFundingAmount) limit.
alice, bob := setupFundingManagers(t, func(cfg *fundingConfig) { alice, bob := setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = true cfg.NoWumboChans = true
cfg.MaxChanSize = MaxFundingAmount - 1 cfg.MaxChanSize = MaxBtcFundingAmount - 1
}) })
// Attempt to create a channel above the limit // Attempt to create a channel above the limit
// imposed by --maxchansize, which should be rejected. // imposed by --maxchansize, which should be rejected.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: MaxFundingAmount, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(0), LocalFundingAmt: MaxBtcFundingAmount,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(0),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
// After processing the funding open message, bob should respond with // After processing the funding open message, bob should respond with
// an error rejecting the channel that exceeds size limit. // an error rejecting the channel that exceeds size limit.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg := expectOpenChannelMsg(t, alice.msgChan) openChanMsg := expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertErrorSent(t, bob.msgChan) assertErrorSent(t, bob.msgChan)
@@ -3405,13 +3412,16 @@ func TestMaxChannelSizeConfig(t *testing.T) {
// channels but set --maxchansize explicitly higher than soft-limit // channels but set --maxchansize explicitly higher than soft-limit
// A --maxchansize greater than this limit should have no effect. // A --maxchansize greater than this limit should have no effect.
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
alice, bob = setupFundingManagers(t, func(cfg *fundingConfig) { alice, bob = setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = true cfg.NoWumboChans = true
cfg.MaxChanSize = MaxFundingAmount + 1 cfg.MaxChanSize = MaxBtcFundingAmount + 1
}) })
// Reset the Peer to the newly created one.
initReq.Peer = bob
// We expect Bob to respond with an Accept channel message. // We expect Bob to respond with an Accept channel message.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg = expectOpenChannelMsg(t, alice.msgChan) openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertFundingMsgSent(t, bob.msgChan, "AcceptChannel") assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
@@ -3420,18 +3430,21 @@ func TestMaxChannelSizeConfig(t *testing.T) {
// Create the funding managers, this time allowing // Create the funding managers, this time allowing
// wumbo channels but setting --maxchansize explicitly. // wumbo channels but setting --maxchansize explicitly.
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
alice, bob = setupFundingManagers(t, func(cfg *fundingConfig) { alice, bob = setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = false cfg.NoWumboChans = false
cfg.MaxChanSize = btcutil.Amount(100000000) cfg.MaxChanSize = btcutil.Amount(100000000)
}) })
// Reset the Peer to the newly created one.
initReq.Peer = bob
// Attempt to create a channel above the limit // Attempt to create a channel above the limit
// imposed by --maxchansize, which should be rejected. // imposed by --maxchansize, which should be rejected.
initReq.localFundingAmt = btcutil.SatoshiPerBitcoin + 1 initReq.LocalFundingAmt = btcutil.SatoshiPerBitcoin + 1
// After processing the funding open message, bob should respond with // After processing the funding open message, bob should respond with
// an error rejecting the channel that exceeds size limit. // an error rejecting the channel that exceeds size limit.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg = expectOpenChannelMsg(t, alice.msgChan) openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertErrorSent(t, bob.msgChan) assertErrorSent(t, bob.msgChan)
@@ -3444,7 +3457,7 @@ func TestWumboChannelConfig(t *testing.T) {
// First we'll create a set of funding managers that will reject wumbo // First we'll create a set of funding managers that will reject wumbo
// channels. // channels.
alice, bob := setupFundingManagers(t, func(cfg *fundingConfig) { alice, bob := setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = true cfg.NoWumboChans = true
}) })
@@ -3453,29 +3466,30 @@ func TestWumboChannelConfig(t *testing.T) {
// funding process w/o issue. // funding process w/o issue.
updateChan := make(chan *lnrpc.OpenStatusUpdate) updateChan := make(chan *lnrpc.OpenStatusUpdate)
errChan := make(chan error, 1) errChan := make(chan error, 1)
initReq := &openChanReq{ initReq := &InitFundingMsg{
targetPubkey: bob.privKey.PubKey(), Peer: bob,
chainHash: *fundingNetParams.GenesisHash, TargetPubkey: bob.privKey.PubKey(),
localFundingAmt: MaxFundingAmount, ChainHash: *fundingNetParams.GenesisHash,
pushAmt: lnwire.NewMSatFromSatoshis(0), LocalFundingAmt: MaxBtcFundingAmount,
private: false, PushAmt: lnwire.NewMSatFromSatoshis(0),
updates: updateChan, Private: false,
err: errChan, Updates: updateChan,
Err: errChan,
} }
// We expect Bob to respond with an Accept channel message. // We expect Bob to respond with an Accept channel message.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg := expectOpenChannelMsg(t, alice.msgChan) openChanMsg := expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertFundingMsgSent(t, bob.msgChan, "AcceptChannel") assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
// We'll now attempt to create a channel above the wumbo mark, which // We'll now attempt to create a channel above the wumbo mark, which
// should be rejected. // should be rejected.
initReq.localFundingAmt = btcutil.SatoshiPerBitcoin initReq.LocalFundingAmt = btcutil.SatoshiPerBitcoin
// After processing the funding open message, bob should respond with // After processing the funding open message, bob should respond with
// an error rejecting the channel. // an error rejecting the channel.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg = expectOpenChannelMsg(t, alice.msgChan) openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertErrorSent(t, bob.msgChan) assertErrorSent(t, bob.msgChan)
@@ -3483,14 +3497,17 @@ func TestWumboChannelConfig(t *testing.T) {
// Next, we'll re-create the funding managers, but this time allowing // Next, we'll re-create the funding managers, but this time allowing
// wumbo channels explicitly. // wumbo channels explicitly.
tearDownFundingManagers(t, alice, bob) tearDownFundingManagers(t, alice, bob)
alice, bob = setupFundingManagers(t, func(cfg *fundingConfig) { alice, bob = setupFundingManagers(t, func(cfg *Config) {
cfg.NoWumboChans = false cfg.NoWumboChans = false
cfg.MaxChanSize = MaxBtcFundingAmountWumbo cfg.MaxChanSize = MaxBtcFundingAmountWumbo
}) })
// Reset the Peer to the newly created one.
initReq.Peer = bob
// We should now be able to initiate a wumbo channel funding w/o any // We should now be able to initiate a wumbo channel funding w/o any
// issues. // issues.
alice.fundingMgr.initFundingWorkflow(bob, initReq) alice.fundingMgr.InitFundingWorkflow(initReq)
openChanMsg = expectOpenChannelMsg(t, alice.msgChan) openChanMsg = expectOpenChannelMsg(t, alice.msgChan)
bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice) bob.fundingMgr.ProcessFundingMsg(openChanMsg, alice)
assertFundingMsgSent(t, bob.msgChan, "AcceptChannel") assertFundingMsgSent(t, bob.msgChan, "AcceptChannel")
+3 -3
View File
@@ -8,7 +8,7 @@ import (
"strings" "strings"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/lightningnetwork/lnd" "github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/lntest" "github.com/lightningnetwork/lnd/lntest"
) )
@@ -49,7 +49,7 @@ func testMaxChannelSize(net *lntest.NetworkHarness, t *harnessTest) {
t.Fatalf("unable to connect peers: %v", err) t.Fatalf("unable to connect peers: %v", err)
} }
chanAmt := lnd.MaxBtcFundingAmountWumbo + 1 chanAmt := funding.MaxBtcFundingAmountWumbo + 1
_, err = net.OpenChannel( _, err = net.OpenChannel(
ctxb, wumboNode, wumboNode2, lntest.OpenChannelParams{ ctxb, wumboNode, wumboNode2, lntest.OpenChannelParams{
Amt: chanAmt, Amt: chanAmt,
@@ -97,7 +97,7 @@ func testMaxChannelSize(net *lntest.NetworkHarness, t *harnessTest) {
// to accept our wumbo channel funding. // to accept our wumbo channel funding.
wumboNode3, err := net.NewNode( wumboNode3, err := net.NewNode(
"wumbo3", []string{"--protocol.wumbo-channels", "wumbo3", []string{"--protocol.wumbo-channels",
fmt.Sprintf("--maxchansize=%v", int64(lnd.MaxBtcFundingAmountWumbo+1))}, fmt.Sprintf("--maxchansize=%v", int64(funding.MaxBtcFundingAmountWumbo+1))},
) )
if err != nil { if err != nil {
t.Fatalf("unable to create new node: %v", err) t.Fatalf("unable to create new node: %v", err)
@@ -6,7 +6,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/lightningnetwork/lnd" "github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc" "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lntest" "github.com/lightningnetwork/lnd/lntest"
@@ -19,7 +19,7 @@ func testHtlcErrorPropagation(net *lntest.NetworkHarness, t *harnessTest) {
// In this test we wish to exercise the daemon's correct parsing, // In this test we wish to exercise the daemon's correct parsing,
// handling, and propagation of errors that occur while processing a // handling, and propagation of errors that occur while processing a
// multi-hop payment. // multi-hop payment.
const chanAmt = lnd.MaxBtcFundingAmount const chanAmt = funding.MaxBtcFundingAmount
// First establish a channel with a capacity of 0.5 BTC between Alice // First establish a channel with a capacity of 0.5 BTC between Alice
// and Bob. // and Bob.
@@ -102,7 +102,7 @@ func testHtlcErrorPropagation(net *lntest.NetworkHarness, t *harnessTest) {
t.Fatalf("unable to connect bob to carol: %v", err) t.Fatalf("unable to connect bob to carol: %v", err)
} }
ctxt, _ = context.WithTimeout(ctxb, channelOpenTimeout) ctxt, _ = context.WithTimeout(ctxb, channelOpenTimeout)
const bobChanAmt = lnd.MaxBtcFundingAmount const bobChanAmt = funding.MaxBtcFundingAmount
chanPointBob := openChannelAndAssert( chanPointBob := openChannelAndAssert(
ctxt, t, net, net.Bob, carol, ctxt, t, net, net.Bob, carol,
lntest.OpenChannelParams{ lntest.OpenChannelParams{
+2 -2
View File
@@ -8,7 +8,7 @@ import (
"github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/lightningnetwork/lnd" "github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc" "github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lntest" "github.com/lightningnetwork/lnd/lntest"
@@ -20,7 +20,7 @@ import (
// multisig funding output. // multisig funding output.
func testPsbtChanFunding(net *lntest.NetworkHarness, t *harnessTest) { func testPsbtChanFunding(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
const chanSize = lnd.MaxBtcFundingAmount const chanSize = funding.MaxBtcFundingAmount
// First, we'll create two new nodes that we'll use to open channels // First, we'll create two new nodes that we'll use to open channels
// between for this test. Dave gets some coins that will be used to // between for this test. Dave gets some coins that will be used to
+22 -21
View File
@@ -32,6 +32,7 @@ import (
"github.com/lightningnetwork/lnd" "github.com/lightningnetwork/lnd"
"github.com/lightningnetwork/lnd/chainreg" "github.com/lightningnetwork/lnd/chainreg"
"github.com/lightningnetwork/lnd/channeldb" "github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/labels" "github.com/lightningnetwork/lnd/labels"
"github.com/lightningnetwork/lnd/lncfg" "github.com/lightningnetwork/lnd/lncfg"
@@ -1250,7 +1251,7 @@ func basicChannelFundingTest(t *harnessTest, net *lntest.NetworkHarness,
alice *lntest.HarnessNode, bob *lntest.HarnessNode, alice *lntest.HarnessNode, bob *lntest.HarnessNode,
fundingShim *lnrpc.FundingShim) (*lnrpc.Channel, *lnrpc.Channel, func(), error) { fundingShim *lnrpc.FundingShim) (*lnrpc.Channel, *lnrpc.Channel, func(), error) {
chanAmt := lnd.MaxBtcFundingAmount chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(100000) pushAmt := btcutil.Amount(100000)
// Record nodes' channel balance before testing. // Record nodes' channel balance before testing.
@@ -1493,7 +1494,7 @@ func testUnconfirmedChannelFunding(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
const ( const (
chanAmt = lnd.MaxBtcFundingAmount chanAmt = funding.MaxBtcFundingAmount
pushAmt = btcutil.Amount(100000) pushAmt = btcutil.Amount(100000)
) )
@@ -1945,7 +1946,7 @@ func testUpdateChannelPolicy(net *lntest.NetworkHarness, t *harnessTest) {
defaultTimeLockDelta = chainreg.DefaultBitcoinTimeLockDelta defaultTimeLockDelta = chainreg.DefaultBitcoinTimeLockDelta
defaultMinHtlc = 1000 defaultMinHtlc = 1000
) )
defaultMaxHtlc := calculateMaxHtlc(lnd.MaxBtcFundingAmount) defaultMaxHtlc := calculateMaxHtlc(funding.MaxBtcFundingAmount)
// Launch notification clients for all nodes, such that we can // Launch notification clients for all nodes, such that we can
// get notified when they discover new channels and updates in the // get notified when they discover new channels and updates in the
@@ -1955,7 +1956,7 @@ func testUpdateChannelPolicy(net *lntest.NetworkHarness, t *harnessTest) {
bobSub := subscribeGraphNotifications(t, ctxb, net.Bob) bobSub := subscribeGraphNotifications(t, ctxb, net.Bob)
defer close(bobSub.quit) defer close(bobSub.quit)
chanAmt := lnd.MaxBtcFundingAmount chanAmt := funding.MaxBtcFundingAmount
pushAmt := chanAmt / 2 pushAmt := chanAmt / 2
// Create a channel Alice->Bob. // Create a channel Alice->Bob.
@@ -2518,7 +2519,7 @@ func testOpenChannelAfterReorg(net *lntest.NetworkHarness, t *harnessTest) {
// Create a new channel that requires 1 confs before it's considered // Create a new channel that requires 1 confs before it's considered
// open, then broadcast the funding transaction // open, then broadcast the funding transaction
chanAmt := lnd.MaxBtcFundingAmount chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(0) pushAmt := btcutil.Amount(0)
ctxt, _ := context.WithTimeout(ctxb, channelOpenTimeout) ctxt, _ := context.WithTimeout(ctxb, channelOpenTimeout)
pendingUpdate, err := net.OpenPendingChannel(ctxt, net.Alice, net.Bob, pendingUpdate, err := net.OpenPendingChannel(ctxt, net.Alice, net.Bob,
@@ -2738,7 +2739,7 @@ func testDisconnectingTargetPeer(net *lntest.NetworkHarness, t *harnessTest) {
t.Fatalf("unable to send coins to alice: %v", err) t.Fatalf("unable to send coins to alice: %v", err)
} }
chanAmt := lnd.MaxBtcFundingAmount chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(0) pushAmt := btcutil.Amount(0)
// Create a new channel that requires 1 confs before it's considered // Create a new channel that requires 1 confs before it's considered
@@ -2873,7 +2874,7 @@ func testDisconnectingTargetPeer(net *lntest.NetworkHarness, t *harnessTest) {
func testChannelFundingPersistence(net *lntest.NetworkHarness, t *harnessTest) { func testChannelFundingPersistence(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
chanAmt := lnd.MaxBtcFundingAmount chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(0) pushAmt := btcutil.Amount(0)
// As we need to create a channel that requires more than 1 // As we need to create a channel that requires more than 1
@@ -3061,7 +3062,7 @@ func testChannelBalance(net *lntest.NetworkHarness, t *harnessTest) {
// Open a channel with 0.16 BTC between Alice and Bob, ensuring the // Open a channel with 0.16 BTC between Alice and Bob, ensuring the
// channel has been opened properly. // channel has been opened properly.
amount := lnd.MaxBtcFundingAmount amount := funding.MaxBtcFundingAmount
// Creates a helper closure to be used below which asserts the proper // Creates a helper closure to be used below which asserts the proper
// response to a channel balance RPC. // response to a channel balance RPC.
@@ -6169,7 +6170,7 @@ func testSendToRouteErrorPropagation(net *lntest.NetworkHarness, t *harnessTest)
func testUnannouncedChannels(net *lntest.NetworkHarness, t *harnessTest) { func testUnannouncedChannels(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
amount := lnd.MaxBtcFundingAmount amount := funding.MaxBtcFundingAmount
// Open a channel between Alice and Bob, ensuring the // Open a channel between Alice and Bob, ensuring the
// channel has been opened properly. // channel has been opened properly.
@@ -7408,7 +7409,7 @@ func testBasicChannelCreationAndUpdates(net *lntest.NetworkHarness, t *harnessTe
ctxb := context.Background() ctxb := context.Background()
const ( const (
numChannels = 2 numChannels = 2
amount = lnd.MaxBtcFundingAmount amount = funding.MaxBtcFundingAmount
) )
// Subscribe Bob and Alice to channel event notifications. // Subscribe Bob and Alice to channel event notifications.
@@ -7572,7 +7573,7 @@ func testMaxPendingChannels(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
maxPendingChannels := lncfg.DefaultMaxPendingChannels + 1 maxPendingChannels := lncfg.DefaultMaxPendingChannels + 1
amount := lnd.MaxBtcFundingAmount amount := funding.MaxBtcFundingAmount
// Create a new node (Carol) with greater number of max pending // Create a new node (Carol) with greater number of max pending
// channels. // channels.
@@ -8183,7 +8184,7 @@ func testRevokedCloseRetribution(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
const ( const (
chanAmt = lnd.MaxBtcFundingAmount chanAmt = funding.MaxBtcFundingAmount
paymentAmt = 10000 paymentAmt = 10000
numInvoices = 6 numInvoices = 6
) )
@@ -8452,7 +8453,7 @@ func testRevokedCloseRetributionZeroValueRemoteOutput(net *lntest.NetworkHarness
ctxb := context.Background() ctxb := context.Background()
const ( const (
chanAmt = lnd.MaxBtcFundingAmount chanAmt = funding.MaxBtcFundingAmount
paymentAmt = 10000 paymentAmt = 10000
numInvoices = 6 numInvoices = 6
) )
@@ -8701,7 +8702,7 @@ func testRevokedCloseRetributionRemoteHodl(net *lntest.NetworkHarness,
ctxb := context.Background() ctxb := context.Background()
const ( const (
chanAmt = lnd.MaxBtcFundingAmount chanAmt = funding.MaxBtcFundingAmount
pushAmt = 200000 pushAmt = 200000
paymentAmt = 10000 paymentAmt = 10000
numInvoices = 6 numInvoices = 6
@@ -8747,7 +8748,7 @@ func testRevokedCloseRetributionRemoteHodl(net *lntest.NetworkHarness,
// In order to test Dave's response to an uncooperative channel closure // In order to test Dave's response to an uncooperative channel closure
// by Carol, we'll first open up a channel between them with a // by Carol, we'll first open up a channel between them with a
// lnd.MaxBtcFundingAmount (2^24) satoshis value. // funding.MaxBtcFundingAmount (2^24) satoshis value.
ctxt, _ = context.WithTimeout(ctxb, channelOpenTimeout) ctxt, _ = context.WithTimeout(ctxb, channelOpenTimeout)
chanPoint := openChannelAndAssert( chanPoint := openChannelAndAssert(
ctxt, t, net, dave, carol, ctxt, t, net, dave, carol,
@@ -9165,7 +9166,7 @@ func testRevokedCloseRetributionAltruistWatchtowerCase(
ctxb := context.Background() ctxb := context.Background()
const ( const (
chanAmt = lnd.MaxBtcFundingAmount chanAmt = funding.MaxBtcFundingAmount
paymentAmt = 10000 paymentAmt = 10000
numInvoices = 6 numInvoices = 6
externalIP = "1.2.3.4" externalIP = "1.2.3.4"
@@ -9739,7 +9740,7 @@ func assertDLPExecuted(net *lntest.NetworkHarness, t *harnessTest,
func testDataLossProtection(net *lntest.NetworkHarness, t *harnessTest) { func testDataLossProtection(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
const ( const (
chanAmt = lnd.MaxBtcFundingAmount chanAmt = funding.MaxBtcFundingAmount
paymentAmt = 10000 paymentAmt = 10000
numInvoices = 6 numInvoices = 6
) )
@@ -10329,7 +10330,7 @@ func subscribeGraphNotifications(t *harnessTest, ctxb context.Context,
func testGraphTopologyNotifications(net *lntest.NetworkHarness, t *harnessTest) { func testGraphTopologyNotifications(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
const chanAmt = lnd.MaxBtcFundingAmount const chanAmt = funding.MaxBtcFundingAmount
// Let Alice subscribe to graph notifications. // Let Alice subscribe to graph notifications.
graphSub := subscribeGraphNotifications( graphSub := subscribeGraphNotifications(
@@ -10656,7 +10657,7 @@ func testNodeAnnouncement(net *lntest.NetworkHarness, t *harnessTest) {
func testNodeSignVerify(net *lntest.NetworkHarness, t *harnessTest) { func testNodeSignVerify(net *lntest.NetworkHarness, t *harnessTest) {
ctxb := context.Background() ctxb := context.Background()
chanAmt := lnd.MaxBtcFundingAmount chanAmt := funding.MaxBtcFundingAmount
pushAmt := btcutil.Amount(100000) pushAmt := btcutil.Amount(100000)
// Create a channel between alice and bob. // Create a channel between alice and bob.
@@ -13198,7 +13199,7 @@ func testAbandonChannel(net *lntest.NetworkHarness, t *harnessTest) {
// First establish a channel between Alice and Bob. // First establish a channel between Alice and Bob.
channelParam := lntest.OpenChannelParams{ channelParam := lntest.OpenChannelParams{
Amt: lnd.MaxBtcFundingAmount, Amt: funding.MaxBtcFundingAmount,
PushAmt: btcutil.Amount(100000), PushAmt: btcutil.Amount(100000),
} }
@@ -13991,7 +13992,7 @@ func testExternalFundingChanPoint(net *lntest.NetworkHarness, t *harnessTest) {
// flow. To start with, we'll create a pending channel with a shim for // flow. To start with, we'll create a pending channel with a shim for
// a transaction that will never be published. // a transaction that will never be published.
const thawHeight uint32 = 10 const thawHeight uint32 = 10
const chanSize = lnd.MaxBtcFundingAmount const chanSize = funding.MaxBtcFundingAmount
fundingShim1, chanPoint1, _ := deriveFundingShim( fundingShim1, chanPoint1, _ := deriveFundingShim(
net, t, carol, dave, chanSize, thawHeight, 1, false, net, t, carol, dave, chanSize, thawHeight, 1, false,
) )
+2 -2
View File
@@ -5,7 +5,7 @@ import (
"strings" "strings"
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/lightningnetwork/lnd" "github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/lntest" "github.com/lightningnetwork/lnd/lntest"
) )
@@ -48,7 +48,7 @@ func testWumboChannels(net *lntest.NetworkHarness, t *harnessTest) {
t.Fatalf("unable to connect peers: %v", err) t.Fatalf("unable to connect peers: %v", err)
} }
chanAmt := lnd.MaxBtcFundingAmount + 1 chanAmt := funding.MaxBtcFundingAmount + 1
_, err = net.OpenChannel( _, err = net.OpenChannel(
ctxb, wumboNode, miniNode, lntest.OpenChannelParams{ ctxb, wumboNode, miniNode, lntest.OpenChannelParams{
Amt: chanAmt, Amt: chanAmt,
+2 -1
View File
@@ -18,6 +18,7 @@ import (
"github.com/lightningnetwork/lnd/channelnotifier" "github.com/lightningnetwork/lnd/channelnotifier"
"github.com/lightningnetwork/lnd/contractcourt" "github.com/lightningnetwork/lnd/contractcourt"
"github.com/lightningnetwork/lnd/discovery" "github.com/lightningnetwork/lnd/discovery"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/healthcheck" "github.com/lightningnetwork/lnd/healthcheck"
"github.com/lightningnetwork/lnd/htlcswitch" "github.com/lightningnetwork/lnd/htlcswitch"
"github.com/lightningnetwork/lnd/invoices" "github.com/lightningnetwork/lnd/invoices"
@@ -81,7 +82,6 @@ var (
ltndLog = addLndPkgLogger("LTND") ltndLog = addLndPkgLogger("LTND")
rpcsLog = addLndPkgLogger("RPCS") rpcsLog = addLndPkgLogger("RPCS")
srvrLog = addLndPkgLogger("SRVR") srvrLog = addLndPkgLogger("SRVR")
fndgLog = addLndPkgLogger("FNDG")
utxnLog = addLndPkgLogger("UTXN") utxnLog = addLndPkgLogger("UTXN")
brarLog = addLndPkgLogger("BRAR") brarLog = addLndPkgLogger("BRAR")
atplLog = addLndPkgLogger("ATPL") atplLog = addLndPkgLogger("ATPL")
@@ -135,6 +135,7 @@ func SetupLoggers(root *build.RotatingLogWriter) {
AddSubLogger(root, healthcheck.Subsystem, healthcheck.UseLogger) AddSubLogger(root, healthcheck.Subsystem, healthcheck.UseLogger)
AddSubLogger(root, chainreg.Subsystem, chainreg.UseLogger) AddSubLogger(root, chainreg.Subsystem, chainreg.UseLogger)
AddSubLogger(root, chanacceptor.Subsystem, chanacceptor.UseLogger) AddSubLogger(root, chanacceptor.Subsystem, chanacceptor.UseLogger)
AddSubLogger(root, funding.Subsystem, funding.UseLogger)
} }
// AddSubLogger is a helper method to conveniently create and register the // AddSubLogger is a helper method to conveniently create and register the
+3 -3
View File
@@ -24,7 +24,7 @@ import (
"github.com/lightningnetwork/lnd/contractcourt" "github.com/lightningnetwork/lnd/contractcourt"
"github.com/lightningnetwork/lnd/discovery" "github.com/lightningnetwork/lnd/discovery"
"github.com/lightningnetwork/lnd/feature" "github.com/lightningnetwork/lnd/feature"
"github.com/lightningnetwork/lnd/fmgr" "github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/htlcswitch" "github.com/lightningnetwork/lnd/htlcswitch"
"github.com/lightningnetwork/lnd/htlcswitch/hodl" "github.com/lightningnetwork/lnd/htlcswitch/hodl"
"github.com/lightningnetwork/lnd/htlcswitch/hop" "github.com/lightningnetwork/lnd/htlcswitch/hop"
@@ -273,8 +273,8 @@ type Config struct {
FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate, FetchLastChanUpdate func(lnwire.ShortChannelID) (*lnwire.ChannelUpdate,
error) error)
// FundingManager is an implementation of the fmgr.Manager interface. // FundingManager is an implementation of the funding.Controller interface.
FundingManager fmgr.Manager FundingManager funding.Controller
// Hodl is used when creating ChannelLinks to specify HodlFlags as // Hodl is used when creating ChannelLinks to specify HodlFlags as
// breakpoints in dev builds. // breakpoints in dev builds.
+13 -12
View File
@@ -10,6 +10,7 @@ import (
"github.com/btcsuite/btcutil" "github.com/btcsuite/btcutil"
"github.com/lightningnetwork/lnd/autopilot" "github.com/lightningnetwork/lnd/autopilot"
"github.com/lightningnetwork/lnd/chainreg" "github.com/lightningnetwork/lnd/chainreg"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/lncfg" "github.com/lightningnetwork/lnd/lncfg"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/tor" "github.com/lightningnetwork/lnd/tor"
@@ -97,18 +98,18 @@ func (c *chanController) OpenChannel(target *btcec.PublicKey,
// Construct the open channel request and send it to the server to begin // Construct the open channel request and send it to the server to begin
// the funding workflow. // the funding workflow.
req := &openChanReq{ req := &funding.InitFundingMsg{
targetPubkey: target, TargetPubkey: target,
chainHash: *c.netParams.GenesisHash, ChainHash: *c.netParams.GenesisHash,
subtractFees: true, SubtractFees: true,
localFundingAmt: amt, LocalFundingAmt: amt,
pushAmt: 0, PushAmt: 0,
minHtlcIn: c.chanMinHtlcIn, MinHtlcIn: c.chanMinHtlcIn,
fundingFeePerKw: feePerKw, FundingFeePerKw: feePerKw,
private: c.private, Private: c.private,
remoteCsvDelay: 0, RemoteCsvDelay: 0,
minConfs: c.minConfs, MinConfs: c.minConfs,
maxValueInFlight: 0, MaxValueInFlight: 0,
} }
updateStream, errChan := c.server.OpenChannel(req) updateStream, errChan := c.server.OpenChannel(req)
+29 -28
View File
@@ -42,6 +42,7 @@ import (
"github.com/lightningnetwork/lnd/contractcourt" "github.com/lightningnetwork/lnd/contractcourt"
"github.com/lightningnetwork/lnd/discovery" "github.com/lightningnetwork/lnd/discovery"
"github.com/lightningnetwork/lnd/feature" "github.com/lightningnetwork/lnd/feature"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/htlcswitch" "github.com/lightningnetwork/lnd/htlcswitch"
"github.com/lightningnetwork/lnd/htlcswitch/hop" "github.com/lightningnetwork/lnd/htlcswitch/hop"
"github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/input"
@@ -1760,11 +1761,11 @@ func (r *rpcServer) canOpenChannel() error {
return nil return nil
} }
// praseOpenChannelReq parses an OpenChannelRequest message into the server's // praseOpenChannelReq parses an OpenChannelRequest message into an InitFundingMsg
// native openChanReq struct. The logic is abstracted so that it can be shared // struct. The logic is abstracted so that it can be shared between OpenChannel
// between OpenChannel and OpenChannelSync. // and OpenChannelSync.
func (r *rpcServer) parseOpenChannelReq(in *lnrpc.OpenChannelRequest, func (r *rpcServer) parseOpenChannelReq(in *lnrpc.OpenChannelRequest,
isSync bool) (*openChanReq, error) { isSync bool) (*funding.InitFundingMsg, error) {
rpcsLog.Debugf("[openchannel] request to NodeKey(%x) "+ rpcsLog.Debugf("[openchannel] request to NodeKey(%x) "+
"allocation(us=%v, them=%v)", in.NodePubkey, "allocation(us=%v, them=%v)", in.NodePubkey,
@@ -1803,9 +1804,9 @@ func (r *rpcServer) parseOpenChannelReq(in *lnrpc.OpenChannelRequest,
// Restrict the size of the channel we'll actually open. At a later // Restrict the size of the channel we'll actually open. At a later
// level, we'll ensure that the output we create after accounting for // level, we'll ensure that the output we create after accounting for
// fees that a dust output isn't created. // fees that a dust output isn't created.
if localFundingAmt < minChanFundingSize { if localFundingAmt < funding.MinChanFundingSize {
return nil, fmt.Errorf("channel is too small, the minimum "+ return nil, fmt.Errorf("channel is too small, the minimum "+
"channel size is: %v SAT", int64(minChanFundingSize)) "channel size is: %v SAT", int64(funding.MinChanFundingSize))
} }
// Prevent users from submitting a max-htlc value that would exceed the // Prevent users from submitting a max-htlc value that would exceed the
@@ -1891,20 +1892,20 @@ func (r *rpcServer) parseOpenChannelReq(in *lnrpc.OpenChannelRequest,
// Instruct the server to trigger the necessary events to attempt to // Instruct the server to trigger the necessary events to attempt to
// open a new channel. A stream is returned in place, this stream will // open a new channel. A stream is returned in place, this stream will
// be used to consume updates of the state of the pending channel. // be used to consume updates of the state of the pending channel.
return &openChanReq{ return &funding.InitFundingMsg{
targetPubkey: nodePubKey, TargetPubkey: nodePubKey,
chainHash: *r.cfg.ActiveNetParams.GenesisHash, ChainHash: *r.cfg.ActiveNetParams.GenesisHash,
localFundingAmt: localFundingAmt, LocalFundingAmt: localFundingAmt,
pushAmt: lnwire.NewMSatFromSatoshis(remoteInitialBalance), PushAmt: lnwire.NewMSatFromSatoshis(remoteInitialBalance),
minHtlcIn: minHtlcIn, MinHtlcIn: minHtlcIn,
fundingFeePerKw: feeRate, FundingFeePerKw: feeRate,
private: in.Private, Private: in.Private,
remoteCsvDelay: remoteCsvDelay, RemoteCsvDelay: remoteCsvDelay,
minConfs: minConfs, MinConfs: minConfs,
shutdownScript: script, ShutdownScript: script,
maxValueInFlight: maxValue, MaxValueInFlight: maxValue,
maxHtlcs: maxHtlcs, MaxHtlcs: maxHtlcs,
maxLocalCsv: uint16(in.MaxLocalCsv), MaxLocalCsv: uint16(in.MaxLocalCsv),
}, nil }, nil
} }
@@ -1935,8 +1936,8 @@ func (r *rpcServer) OpenChannel(in *lnrpc.OpenChannelRequest,
// Map the channel point shim into a new // Map the channel point shim into a new
// chanfunding.CannedAssembler that the wallet will use // chanfunding.CannedAssembler that the wallet will use
// to obtain the channel point details. // to obtain the channel point details.
copy(req.pendingChanID[:], chanPointShim.PendingChanId) copy(req.PendingChanID[:], chanPointShim.PendingChanId)
req.chanFunder, err = newFundingShimAssembler( req.ChanFunder, err = newFundingShimAssembler(
chanPointShim, true, r.server.cc.KeyRing, chanPointShim, true, r.server.cc.KeyRing,
) )
if err != nil { if err != nil {
@@ -1953,9 +1954,9 @@ func (r *rpcServer) OpenChannel(in *lnrpc.OpenChannelRequest,
// Instruct the wallet to use the new // Instruct the wallet to use the new
// chanfunding.PsbtAssembler to construct the funding // chanfunding.PsbtAssembler to construct the funding
// transaction. // transaction.
copy(req.pendingChanID[:], psbtShim.PendingChanId) copy(req.PendingChanID[:], psbtShim.PendingChanId)
req.chanFunder, err = newPsbtAssembler( req.ChanFunder, err = newPsbtAssembler(
in, req.minConfs, psbtShim, in, req.MinConfs, psbtShim,
&r.server.cc.Wallet.Cfg.NetParams, &r.server.cc.Wallet.Cfg.NetParams,
) )
if err != nil { if err != nil {
@@ -1972,7 +1973,7 @@ out:
select { select {
case err := <-errChan: case err := <-errChan:
rpcsLog.Errorf("unable to open channel to NodeKey(%x): %v", rpcsLog.Errorf("unable to open channel to NodeKey(%x): %v",
req.targetPubkey.SerializeCompressed(), err) req.TargetPubkey.SerializeCompressed(), err)
return err return err
case fundingUpdate := <-updateChan: case fundingUpdate := <-updateChan:
rpcsLog.Tracef("[openchannel] sending update: %v", rpcsLog.Tracef("[openchannel] sending update: %v",
@@ -2004,7 +2005,7 @@ out:
} }
rpcsLog.Tracef("[openchannel] success NodeKey(%x), ChannelPoint(%v)", rpcsLog.Tracef("[openchannel] success NodeKey(%x), ChannelPoint(%v)",
req.targetPubkey.SerializeCompressed(), outpoint) req.TargetPubkey.SerializeCompressed(), outpoint)
return nil return nil
} }
@@ -2029,7 +2030,7 @@ func (r *rpcServer) OpenChannelSync(ctx context.Context,
// If an error occurs them immediately return the error to the client. // If an error occurs them immediately return the error to the client.
case err := <-errChan: case err := <-errChan:
rpcsLog.Errorf("unable to open channel to NodeKey(%x): %v", rpcsLog.Errorf("unable to open channel to NodeKey(%x): %v",
req.targetPubkey.SerializeCompressed(), err) req.TargetPubkey.SerializeCompressed(), err)
return nil, err return nil, err
// Otherwise, wait for the first channel update. The first update sent // Otherwise, wait for the first channel update. The first update sent
+35 -80
View File
@@ -39,6 +39,7 @@ import (
"github.com/lightningnetwork/lnd/contractcourt" "github.com/lightningnetwork/lnd/contractcourt"
"github.com/lightningnetwork/lnd/discovery" "github.com/lightningnetwork/lnd/discovery"
"github.com/lightningnetwork/lnd/feature" "github.com/lightningnetwork/lnd/feature"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/healthcheck" "github.com/lightningnetwork/lnd/healthcheck"
"github.com/lightningnetwork/lnd/htlcswitch" "github.com/lightningnetwork/lnd/htlcswitch"
"github.com/lightningnetwork/lnd/htlcswitch/hop" "github.com/lightningnetwork/lnd/htlcswitch/hop"
@@ -51,7 +52,6 @@ import (
"github.com/lightningnetwork/lnd/lnrpc/routerrpc" "github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwallet/chanfunding"
"github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/nat" "github.com/lightningnetwork/lnd/nat"
"github.com/lightningnetwork/lnd/netann" "github.com/lightningnetwork/lnd/netann"
@@ -114,6 +114,17 @@ var (
// validColorRegexp is a regexp that lets you check if a particular // validColorRegexp is a regexp that lets you check if a particular
// color string matches the standard hex color format #RRGGBB. // color string matches the standard hex color format #RRGGBB.
validColorRegexp = regexp.MustCompile("^#[A-Fa-f0-9]{6}$") validColorRegexp = regexp.MustCompile("^#[A-Fa-f0-9]{6}$")
// MaxFundingAmount is a soft-limit of the maximum channel size
// currently accepted within the Lightning Protocol. This is
// defined in BOLT-0002, and serves as an initial precautionary limit
// while implementations are battle tested in the real world.
//
// At the moment, this value depends on which chain is active. It is set
// to the value under the Bitcoin chain as default.
//
// TODO(roasbeef): add command line param to modify
MaxFundingAmount = funding.MaxBtcFundingAmount
) )
// errPeerAlreadyConnected is an error returned by the server when we're // errPeerAlreadyConnected is an error returned by the server when we're
@@ -207,7 +218,7 @@ type server struct {
cc *chainreg.ChainControl cc *chainreg.ChainControl
fundingMgr *fundingManager fundingMgr *funding.Manager
localChanDB *channeldb.DB localChanDB *channeldb.DB
@@ -977,12 +988,12 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
// Litecoin, depending on the primary registered chain. // Litecoin, depending on the primary registered chain.
primaryChain := cfg.registeredChains.PrimaryChain() primaryChain := cfg.registeredChains.PrimaryChain()
chainCfg := cfg.Bitcoin chainCfg := cfg.Bitcoin
minRemoteDelay := minBtcRemoteDelay minRemoteDelay := funding.MinBtcRemoteDelay
maxRemoteDelay := maxBtcRemoteDelay maxRemoteDelay := funding.MaxBtcRemoteDelay
if primaryChain == chainreg.LitecoinChain { if primaryChain == chainreg.LitecoinChain {
chainCfg = cfg.Litecoin chainCfg = cfg.Litecoin
minRemoteDelay = minLtcRemoteDelay minRemoteDelay = funding.MinLtcRemoteDelay
maxRemoteDelay = maxLtcRemoteDelay maxRemoteDelay = funding.MaxLtcRemoteDelay
} }
var chanIDSeed [32]byte var chanIDSeed [32]byte
@@ -990,7 +1001,7 @@ func newServer(cfg *Config, listenAddrs []net.Addr,
return nil, err return nil, err
} }
s.fundingMgr, err = newFundingManager(fundingConfig{ s.fundingMgr, err = funding.NewFundingManager(funding.Config{
NoWumboChans: !cfg.ProtocolOptions.Wumbo(), NoWumboChans: !cfg.ProtocolOptions.Wumbo(),
IDKey: nodeKeyECDH.PubKey(), IDKey: nodeKeyECDH.PubKey(),
Wallet: cc.Wallet, Wallet: cc.Wallet,
@@ -3472,63 +3483,6 @@ func (s *server) removePeer(p *peer.Brontide) {
s.peerNotifier.NotifyPeerOffline(pubKey) s.peerNotifier.NotifyPeerOffline(pubKey)
} }
// openChanReq is a message sent to the server in order to request the
// initiation of a channel funding workflow to the peer with either the
// specified relative peer ID, or a global lightning ID.
type openChanReq struct {
targetPubkey *btcec.PublicKey
chainHash chainhash.Hash
subtractFees bool
localFundingAmt btcutil.Amount
pushAmt lnwire.MilliSatoshi
fundingFeePerKw chainfee.SatPerKWeight
private bool
// minHtlcIn is the minimum incoming htlc that we accept.
minHtlcIn lnwire.MilliSatoshi
remoteCsvDelay uint16
// minConfs indicates the minimum number of confirmations that each
// output selected to fund the channel should satisfy.
minConfs int32
// shutdownScript is an optional upfront shutdown script for the channel.
// This value is optional, so may be nil.
shutdownScript lnwire.DeliveryAddress
// maxValueInFlight is the maximum amount of coins in millisatoshi that can
// be pending within the channel. It only applies to the remote party.
maxValueInFlight lnwire.MilliSatoshi
maxHtlcs uint16
// maxLocalCsv is the maximum local csv delay we will accept from our
// peer.
maxLocalCsv uint16
// TODO(roasbeef): add ability to specify channel constraints as well
// chanFunder is an optional channel funder that allows the caller to
// control exactly how the channel funding is carried out. If not
// specified, then the default chanfunding.WalletAssembler will be
// used.
chanFunder chanfunding.Assembler
// pendingChanID is not all zeroes (the default value), then this will
// be the pending channel ID used for the funding flow within the wire
// protocol.
pendingChanID [32]byte
updates chan *lnrpc.OpenStatusUpdate
err chan error
}
// ConnectToPeer requests that the server connect to a Lightning Network peer // ConnectToPeer requests that the server connect to a Lightning Network peer
// at the specified address. This function will *block* until either a // at the specified address. This function will *block* until either a
// connection is established, or the initial handshake process fails. // connection is established, or the initial handshake process fails.
@@ -3673,25 +3627,26 @@ func (s *server) DisconnectPeer(pubKey *btcec.PublicKey) error {
// //
// NOTE: This function is safe for concurrent access. // NOTE: This function is safe for concurrent access.
func (s *server) OpenChannel( func (s *server) OpenChannel(
req *openChanReq) (chan *lnrpc.OpenStatusUpdate, chan error) { req *funding.InitFundingMsg) (chan *lnrpc.OpenStatusUpdate, chan error) {
// The updateChan will have a buffer of 2, since we expect a ChanPending // The updateChan will have a buffer of 2, since we expect a ChanPending
// + a ChanOpen update, and we want to make sure the funding process is // + a ChanOpen update, and we want to make sure the funding process is
// not blocked if the caller is not reading the updates. // not blocked if the caller is not reading the updates.
req.updates = make(chan *lnrpc.OpenStatusUpdate, 2) req.Updates = make(chan *lnrpc.OpenStatusUpdate, 2)
req.err = make(chan error, 1) req.Err = make(chan error, 1)
// First attempt to locate the target peer to open a channel with, if // First attempt to locate the target peer to open a channel with, if
// we're unable to locate the peer then this request will fail. // we're unable to locate the peer then this request will fail.
pubKeyBytes := req.targetPubkey.SerializeCompressed() pubKeyBytes := req.TargetPubkey.SerializeCompressed()
s.mu.RLock() s.mu.RLock()
peer, ok := s.peersByPub[string(pubKeyBytes)] peer, ok := s.peersByPub[string(pubKeyBytes)]
if !ok { if !ok {
s.mu.RUnlock() s.mu.RUnlock()
req.err <- fmt.Errorf("peer %x is not online", pubKeyBytes) req.Err <- fmt.Errorf("peer %x is not online", pubKeyBytes)
return req.updates, req.err return req.Updates, req.Err
} }
req.Peer = peer
s.mu.RUnlock() s.mu.RUnlock()
// We'll wait until the peer is active before beginning the channel // We'll wait until the peer is active before beginning the channel
@@ -3699,32 +3654,32 @@ func (s *server) OpenChannel(
select { select {
case <-peer.ActiveSignal(): case <-peer.ActiveSignal():
case <-peer.QuitSignal(): case <-peer.QuitSignal():
req.err <- fmt.Errorf("peer %x disconnected", pubKeyBytes) req.Err <- fmt.Errorf("peer %x disconnected", pubKeyBytes)
return req.updates, req.err return req.Updates, req.Err
case <-s.quit: case <-s.quit:
req.err <- ErrServerShuttingDown req.Err <- ErrServerShuttingDown
return req.updates, req.err return req.Updates, req.Err
} }
// If the fee rate wasn't specified, then we'll use a default // If the fee rate wasn't specified, then we'll use a default
// confirmation target. // confirmation target.
if req.fundingFeePerKw == 0 { if req.FundingFeePerKw == 0 {
estimator := s.cc.FeeEstimator estimator := s.cc.FeeEstimator
feeRate, err := estimator.EstimateFeePerKW(6) feeRate, err := estimator.EstimateFeePerKW(6)
if err != nil { if err != nil {
req.err <- err req.Err <- err
return req.updates, req.err return req.Updates, req.Err
} }
req.fundingFeePerKw = feeRate req.FundingFeePerKw = feeRate
} }
// Spawn a goroutine to send the funding workflow request to the funding // Spawn a goroutine to send the funding workflow request to the funding
// manager. This allows the server to continue handling queries instead // manager. This allows the server to continue handling queries instead
// of blocking on this request which is exported as a synchronous // of blocking on this request which is exported as a synchronous
// request to the outside world. // request to the outside world.
go s.fundingMgr.initFundingWorkflow(peer, req) go s.fundingMgr.InitFundingWorkflow(req)
return req.updates, req.err return req.Updates, req.Err
} }
// Peers returns a slice of all active peers. // Peers returns a slice of all active peers.