diff --git a/Makefile b/Makefile index dcdb13c13d..693576058f 100644 --- a/Makefile +++ b/Makefile @@ -287,7 +287,7 @@ itest-cc: build-itest-integrated clean-cc-itest-logs itest-cc-compat: build-itest-integrated clean-cc-itest-logs @$(call print, "Running backward compatibility integration tests.") date - CGO_ENABLED=0 $(GOTEST) ./itest/custom_channels -v -tags="$(ITEST_TAGS)" -test.run='TestBackwardsCompatChannels|TestSpenderLeafUpgrade' -test.timeout=60m -logdir=regtest/.logs + CGO_ENABLED=0 $(GOTEST) ./itest/custom_channels -v -tags="$(ITEST_TAGS)" -test.run='TestBackwardsCompatChannels|TestSpenderLeafUpgrade|TestDeterministicHtlcsUpgrade' -test.timeout=60m -logdir=regtest/.logs build-compat-binary: @$(call print, "Building compat binary for $(version).") diff --git a/asset/sign_descriptor.go b/asset/sign_descriptor.go index 68b5710cd8..dee463448d 100644 --- a/asset/sign_descriptor.go +++ b/asset/sign_descriptor.go @@ -16,12 +16,13 @@ type SignDescriptor struct { KeyDesc keychain.KeyDescriptor // SingleTweak is a scalar that is added to the private key before - // signing. At most one of SingleTweak and DoubleTweak is set. + // signing. When both tweaks are set, lnd applies DoubleTweak first + // and SingleTweak second. SingleTweak []byte // DoubleTweak is a private key that is combined with the signing key - // in a revocation style derivation before signing. At most one of - // SingleTweak and DoubleTweak is set. + // in a revocation style derivation before signing. Second-level HTLC + // signing for aux channels sets it together with SingleTweak. DoubleTweak *btcec.PrivateKey // TapTweak is the input to the taproot tweak that turns the internal diff --git a/cmd/tapd-integrated/main.go b/cmd/tapd-integrated/main.go index 5f2aff8d70..4783dac01f 100644 --- a/cmd/tapd-integrated/main.go +++ b/cmd/tapd-integrated/main.go @@ -15,6 +15,7 @@ import ( "os" "path/filepath" "sync" + "time" "github.com/btcsuite/btclog/v2" "github.com/jessevdk/go-flags" @@ -278,6 +279,7 @@ func run() error { BlockUntilChainNotifier: true, BlockUntilUnlocked: true, CallerCtx: ctx, + RPCTimeout: 2 * time.Minute, } if cfg.Lnd.NoMacaroons { // Use a dummy macaroon that lndclient can deserialize. diff --git a/go.mod b/go.mod index 5d668a1381..e0d983bba6 100644 --- a/go.mod +++ b/go.mod @@ -192,7 +192,7 @@ require ( go.etcd.io/etcd/server/v3 v3.5.12 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect go.opentelemetry.io/otel v1.47.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 // indirect @@ -236,5 +236,24 @@ replace github.com/prometheus/common => github.com/prometheus/common v0.66.1 // Note this is a temporary replace and will be removed when taprpc is tagged. replace github.com/lightninglabs/taproot-assets/taprpc => ./taprpc -// lnd master uses queries of its sqldb submodule that are not tagged yet. -replace github.com/lightningnetwork/lnd/sqldb => github.com/lightningnetwork/lnd/sqldb v1.0.13-0.20261125195613-f7e5f83a1f59 +replace github.com/lightningnetwork/lnd => github.com/GeorgeTsagk/lnd v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/sqldb => github.com/GeorgeTsagk/lnd/sqldb v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/tlv => github.com/GeorgeTsagk/lnd/tlv v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/cert => github.com/GeorgeTsagk/lnd/cert v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/clock => github.com/GeorgeTsagk/lnd/clock v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/healthcheck => github.com/GeorgeTsagk/lnd/healthcheck v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/kvdb => github.com/GeorgeTsagk/lnd/kvdb v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/queue => github.com/GeorgeTsagk/lnd/queue v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/tor => github.com/GeorgeTsagk/lnd/tor v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/actor => github.com/GeorgeTsagk/lnd/actor v0.0.0-20261126091253-3188f00ea5f8 + +replace github.com/lightningnetwork/lnd/fn/v2 => github.com/GeorgeTsagk/lnd/fn/v2 v2.0.0-20261126091253-3188f00ea5f8 diff --git a/go.sum b/go.sum index 4a5d852612..0b3c38e91e 100644 --- a/go.sum +++ b/go.sum @@ -603,6 +603,28 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/GeorgeTsagk/lnd v0.0.0-20261126091253-3188f00ea5f8 h1:/aulCTSFePCPw1yaGQHmJ/7bk7paGlUHhkccl+Qnsn8= +github.com/GeorgeTsagk/lnd v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:aj4fTi1Fbh8RN/doRXug7X7/a/z6Tpc/btno0j5Ed5k= +github.com/GeorgeTsagk/lnd/actor v0.0.0-20261126091253-3188f00ea5f8 h1:XYTLqv+ZaukWVXGmzRRVN0EXVKz+ulXE5UJob44QA4A= +github.com/GeorgeTsagk/lnd/actor v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:A8xDEjgZR3QwKYkj+Qwkm1QFNfV3SVsMPgyQSax4tkI= +github.com/GeorgeTsagk/lnd/cert v0.0.0-20261126091253-3188f00ea5f8 h1:9fB0Y4fl0ezRWGIrTQFuERnd9joM8XuwFluVKNmYby0= +github.com/GeorgeTsagk/lnd/cert v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:9Zsr3g1UgJifCVBzJA5OXDjeXryO8zBK1TlkPjlZgfY= +github.com/GeorgeTsagk/lnd/clock v0.0.0-20261126091253-3188f00ea5f8 h1:gPvaMmjPkVYviOEyHrPGBY/lZ5B5okNz39XHW/D+rmY= +github.com/GeorgeTsagk/lnd/clock v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:XKU9tG3Q4zGwdxf0dsT7ejMwI958eaqJQ/n3SKglzvw= +github.com/GeorgeTsagk/lnd/fn/v2 v2.0.0-20261126091253-3188f00ea5f8 h1:FqnhHduDq2ZQledj0PS5KZKgL+tU6/C5uC3CAG/TB9g= +github.com/GeorgeTsagk/lnd/fn/v2 v2.0.0-20261126091253-3188f00ea5f8/go.mod h1:ovPhLFStKt4eru5U1prNLII22/XZdio7xgyZb4JLk0w= +github.com/GeorgeTsagk/lnd/healthcheck v0.0.0-20261126091253-3188f00ea5f8 h1:rLpUisrQsBggPSpmxYmAxmyKWJpui4Yk5C+oxBeGNaw= +github.com/GeorgeTsagk/lnd/healthcheck v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:VIkkpPrBNGZeh9wugLXJ1tAlsEkAfMD05uC9klwxy3o= +github.com/GeorgeTsagk/lnd/kvdb v0.0.0-20261126091253-3188f00ea5f8 h1:3x+z/3Mq9bjudOLDNCJBsqX26aqyYUWbx+9B9zX2ANs= +github.com/GeorgeTsagk/lnd/kvdb v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:Ugkbzzhy7wcYEqv3FeB7UubIskZv+i6No803FOBThYs= +github.com/GeorgeTsagk/lnd/queue v0.0.0-20261126091253-3188f00ea5f8 h1:gQGwHhrKQRJPE8pTVI4ZfvMS05Icf//ONLcSbFFE84o= +github.com/GeorgeTsagk/lnd/queue v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:PqIifmqlwdKsazsCaTtSpOc8KzZQNy88dGGZCOy8gc4= +github.com/GeorgeTsagk/lnd/sqldb v0.0.0-20261126091253-3188f00ea5f8 h1:9pEO+7qTmKfE8hwCC7bMgxuMCPlysCzl+yTQs1IBhxY= +github.com/GeorgeTsagk/lnd/sqldb v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:DRKd6xYKPANEzUpRLD27JUt0pR8KI8snDAgrNhIfbSY= +github.com/GeorgeTsagk/lnd/tlv v0.0.0-20261126091253-3188f00ea5f8 h1:dTMTeMsi49H8tSTKzGdbBrWK62MpnUN2ZVU2b85xlTA= +github.com/GeorgeTsagk/lnd/tlv v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:Tj4LzBXL5SIZdU/p1B4RF/qjcu6ob+r1nyzi8T85n8E= +github.com/GeorgeTsagk/lnd/tor v0.0.0-20261126091253-3188f00ea5f8 h1:KsjvCmmD4aPVy+ABBzjqJ6y2WNZe8MtYu6HMEJByMHQ= +github.com/GeorgeTsagk/lnd/tor v0.0.0-20261126091253-3188f00ea5f8/go.mod h1:pkKYUO+cGOUuFg52FH3RMcm2luHTHkrlsf2Lm6ceazA= github.com/JohnCGriffin/overflow v0.0.0-20211019200055-46fa312c352c/go.mod h1:X0CRv0ky0k6m906ixxpzmDRLvX58TFUKS2eePweuyxk= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= @@ -1067,30 +1089,8 @@ github.com/lightninglabs/protobuf-go-hex-display v1.34.2-hex-display h1:w7FM5LH9 github.com/lightninglabs/protobuf-go-hex-display v1.34.2-hex-display/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= github.com/lightningnetwork/lightning-onion v1.4.0 h1:qWE1icOH4AKXRcq1KCzt6P/TesqptgBTP++V7wowTc0= github.com/lightningnetwork/lightning-onion v1.4.0/go.mod h1:YDPkvVTVQ6FBBE6Yj93tDd7zA3iTSrryi9xq46i7bKE= -github.com/lightningnetwork/lnd v0.21.0-beta.rc2.0.20261125195613-f7e5f83a1f59 h1:13Wr8meYwF5JXffRXrLU29aBiNBETQcyOAr58zfzcdg= -github.com/lightningnetwork/lnd v0.21.0-beta.rc2.0.20261125195613-f7e5f83a1f59/go.mod h1:aj4fTi1Fbh8RN/doRXug7X7/a/z6Tpc/btno0j5Ed5k= -github.com/lightningnetwork/lnd/actor v0.0.6 h1:Ge8N2wivARG+27qJBwTlB0vwsypStZYZy8vk4Zl38sU= -github.com/lightningnetwork/lnd/actor v0.0.6/go.mod h1:YAsoniSbY/cAM9HTVNfZLvt7RI6swDxy6wzPspTcMZg= -github.com/lightningnetwork/lnd/cert v1.2.2 h1:71YK6hogeJtxSxw2teq3eGeuy4rHGKcFf0d0Uy4qBjI= -github.com/lightningnetwork/lnd/cert v1.2.2/go.mod h1:jQmFn/Ez4zhDgq2hnYSw8r35bqGVxViXhX6Cd7HXM6U= -github.com/lightningnetwork/lnd/clock v1.1.1 h1:OfR3/zcJd2RhH0RU+zX/77c0ZiOnIMsDIBjgjWdZgA0= -github.com/lightningnetwork/lnd/clock v1.1.1/go.mod h1:mGnAhPyjYZQJmebS7aevElXKTFDuO+uNFFfMXK1W8xQ= -github.com/lightningnetwork/lnd/fn/v2 v2.0.10 h1:8GiXDXmF9QPnphLVxcn0KAgDTfRsyQoaIJmh7GXX4Ng= -github.com/lightningnetwork/lnd/fn/v2 v2.0.10/go.mod h1:wg3OyJ9eS14Az8HAZMMxqVjJ+nkKw97uPF/45ICOvs4= -github.com/lightningnetwork/lnd/healthcheck v1.2.6 h1:1sWhqr93GdkWy4+6U7JxBfcyZIE78MhIHTJZfPx7qqI= -github.com/lightningnetwork/lnd/healthcheck v1.2.6/go.mod h1:Mu02um4CWY/zdTOvFje7WJgJcHyX2zq/FG3MhOAiGaQ= -github.com/lightningnetwork/lnd/kvdb v1.5.1 h1:OG5cDbqggxiCFKAJbSPw0PfQovi+0odCZAAU5r5b+ho= -github.com/lightningnetwork/lnd/kvdb v1.5.1/go.mod h1:5lubXYoXHDBWBYKmC+2we7qgkjjz0cEZ/5QSQkxQSec= -github.com/lightningnetwork/lnd/queue v1.2.1 h1:51M3axuVk/Fu7YzpcsZ1WA1JRlbop/6NnuT+B2KD0VQ= -github.com/lightningnetwork/lnd/queue v1.2.1/go.mod h1:KxEQGFi10Y+fM32d8pIQif775dqIbZbyy2JhfSojilw= -github.com/lightningnetwork/lnd/sqldb v1.0.13-0.20261125195613-f7e5f83a1f59 h1:hR0hqvxygVm0L2ELBz5imQ0TeYkZ7YluU2jwciwj2Zk= -github.com/lightningnetwork/lnd/sqldb v1.0.13-0.20261125195613-f7e5f83a1f59/go.mod h1:DRKd6xYKPANEzUpRLD27JUt0pR8KI8snDAgrNhIfbSY= github.com/lightningnetwork/lnd/ticker v1.1.1 h1:J/b6N2hibFtC7JLV77ULQp++QLtCwT6ijJlbdiZFbSM= github.com/lightningnetwork/lnd/ticker v1.1.1/go.mod h1:waPTRAAcwtu7Ji3+3k+u/xH5GHovTsCoSVpho0KDvdA= -github.com/lightningnetwork/lnd/tlv v1.4.1 h1:cCx8H4mC6TZ2Pc0aNEYxTqdZoRQA7+XNJa95gciKXNU= -github.com/lightningnetwork/lnd/tlv v1.4.1/go.mod h1:RvxxfVTCctKzKVWJDyQZqSdu3JV7OjaiQGF06hBCZ+s= -github.com/lightningnetwork/lnd/tor v1.2.0 h1:Xled9KE+rdTPEMDVJE5VrSoMNkJq6EfH3NCF6pLP4h4= -github.com/lightningnetwork/lnd/tor v1.2.0/go.mod h1:tB6/Hsk5nIm6xkOPaidd4q1at4x4gF6Bpu/t2UQxYgM= github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796 h1:sjOGyegMIhvgfq5oaue6Td+hxZuf3tDC8lAPrFldqFw= github.com/ltcsuite/ltcd v0.0.0-20190101042124-f37f8bf35796/go.mod h1:3p7ZTf9V1sNPI5H8P3NkTFF4LuwMdPl2DodF60qAKqY= github.com/ltcsuite/ltcutil v0.0.0-20181217130922-17f3b04680b6/go.mod h1:8Vg/LTOO0KYa/vlHWJ6XZAevPQThGH5sufO0Hrou/lA= @@ -1281,8 +1281,8 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg= go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= diff --git a/itest/custom_channels/assertions.go b/itest/custom_channels/assertions.go index 822eb9eb92..401f230ab0 100644 --- a/itest/custom_channels/assertions.go +++ b/itest/custom_channels/assertions.go @@ -305,7 +305,7 @@ func mineBlocksSlow(t *ccHarnessTest, net *itest.IntegratedNetworkHarness, var txids []*chainhash.Hash var err error if numTxs > 0 { - txids, err = waitForNTxsInMempool( + txids, err = waitForAtLeastNTxsInMempool( net.Miner, numTxs, wait.MinerMempoolTimeout, ) @@ -367,8 +367,8 @@ func waitForNTxsInMempool(m *miner.HarnessMiner, n int, } } -// waitForAtLeastNTxsInMempool polls until finding at least n transactions -// in the miner's mempool, returning all txids present. +// waitForAtLeastNTxsInMempool polls until finding at least n +// transactions in the miner's mempool, returning all txids present. func waitForAtLeastNTxsInMempool(m *miner.HarnessMiner, n int, timeout time.Duration) ([]*chainhash.Hash, error) { @@ -388,7 +388,8 @@ func waitForAtLeastNTxsInMempool(m *miner.HarnessMiner, n int, if len(mempool) >= n { result := make( - []*chainhash.Hash, len(mempool), + []*chainhash.Hash, + len(mempool), ) for i := range mempool { result[i] = &mempool[i] @@ -399,6 +400,14 @@ func waitForAtLeastNTxsInMempool(m *miner.HarnessMiner, n int, } } +// waitForNonEmptyMempool polls until the mempool is non-empty, then +// returns a snapshot of its current contents. +func waitForNonEmptyMempool(m *miner.HarnessMiner, + timeout time.Duration) ([]*chainhash.Hash, error) { + + return waitForAtLeastNTxsInMempool(m, 1, timeout) +} + // assertTxInBlock asserts that a transaction with the given hash is included // in the block. func assertTxInBlock(t *ccHarnessTest, block *wire.MsgBlock, diff --git a/itest/custom_channels/breach_test.go b/itest/custom_channels/breach_test.go index d273cb48d4..be3dc07faf 100644 --- a/itest/custom_channels/breach_test.go +++ b/itest/custom_channels/breach_test.go @@ -4,11 +4,15 @@ package custom_channels import ( "context" + "encoding/hex" "fmt" + "os" "slices" + "strconv" "time" "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/wire/v2" "github.com/lightninglabs/taproot-assets/itest" "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/taprpc" @@ -17,36 +21,164 @@ import ( "github.com/lightninglabs/taproot-assets/tapscript" fn "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/lnrpc" + "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc" "github.com/lightningnetwork/lnd/lntest/node" "github.com/lightningnetwork/lnd/lntest/port" + "github.com/lightningnetwork/lnd/lntest/wait" "github.com/lightningnetwork/lnd/lnwallet/chainfee" "github.com/stretchr/testify/require" ) +const breachNumHodlInvoicesEnv = "TAPD_BREACH_HODL_INVOICES_PER_SIDE" + +func numBreachHodlInvoices(t *ccHarnessTest) int { + // Default to the most demanding scenario the breach recovery path + // currently supports, so the test exercises the full pre-signed + // second-level HTLC flow out of the box. The env var still allows + // scaling the same breach flow down or up without editing the test + // body. + raw := os.Getenv(breachNumHodlInvoicesEnv) + if raw == "" { + return 6 + } + + numInvoices, err := strconv.Atoi(raw) + require.NoErrorf( + t.t, err, "invalid %s value %q", breachNumHodlInvoicesEnv, raw, + ) + require.GreaterOrEqualf( + t.t, numInvoices, 1, "%s must be at least 1", + breachNumHodlInvoicesEnv, + ) + + return numInvoices +} + +func currentAssetBalance(node *itest.IntegratedNode, assetID []byte) uint64 { + resp, err := asTapd(node).ListBalances( + context.Background(), &taprpc.ListBalancesRequest{ + GroupBy: &taprpc.ListBalancesRequest_AssetId{ + AssetId: true, + }, + AssetFilter: assetID, + }, + ) + if err != nil { + return 0 + } + + balance, ok := resp.AssetBalances[hex.EncodeToString(assetID)] + if !ok { + return 0 + } + + return balance.Balance +} + +func logRecentTransfers(t *ccHarnessTest, node *itest.IntegratedNode) { + resp, err := asTapd(node).ListTransfers( + context.Background(), &taprpc.ListTransfersRequest{}, + ) + require.NoError(t.t, err) + + start := max(0, len(resp.Transfers)-8) + t.t.Logf("%s recent transfers (%d total):", node.Cfg.Name, + len(resp.Transfers)) + for i := start; i < len(resp.Transfers); i++ { + tr := resp.Transfers[i] + t.t.Logf(" [%d] label=%q height_hint=%d block_height=%d "+ + "outputs=%d", + i, tr.Label, tr.AnchorTxHeightHint, + tr.AnchorTxBlockHeight, len(tr.Outputs)) + } +} + +// breachTestOpts selects the variant of the breach scenario to run. +type breachTestOpts struct { + // collideHtlcIndexes makes the HTLCs offered by each party on the + // revoked state share their HTLC indexes. Both parties count the + // HTLCs they offer from zero, so this is what any channel with + // traffic in both directions looks like, and an HTLC index alone + // must never be taken to identify an HTLC. + collideHtlcIndexes bool + + // settleOnBreach makes the breaching party learn the preimages of + // the HTLCs it accepted on the revoked state, so it takes them to + // the second level through the success path. Without it only the + // HTLCs it offered go to the second level, through the timeout path, + // and the accepted ones are punished on the commitment itself. + settleOnBreach bool +} + // testCustomChannelsBreach tests the breach/justice scenario for custom -// channels. Dave backs up his DB state, one more payment advances the state, -// then Dave restores the old state and force-closes (broadcasting a revoked -// commitment). Charlie detects the breach and sweeps both outputs, recovering -// all channel funds. +// channels with in-flight HTLCs. Dave backs up his DB state (which has active +// hodl invoice HTLCs), the HTLCs are settled to advance the state, then Dave +// restores the old state and force-closes (broadcasting a revoked commitment +// with HTLC outputs). Charlie is suspended during the breach so Dave can +// advance HTLCs to second level. Charlie is then resumed, detects the breach, +// and sweeps all outputs including second-level HTLC outputs. +// +// In this variant the HTLCs Dave offered time out and go to the second +// level, while the ones he accepted stay on the commitment and are punished +// there. func testCustomChannelsBreach(ctx context.Context, net *itest.IntegratedNetworkHarness, t *ccHarnessTest) { + runCustomChannelsBreach(ctx, net, t, breachTestOpts{}) +} + +// testCustomChannelsBreachSecondLevelSuccess runs the breach scenario with +// every HTLC of the revoked state taken to the second level: the ones Dave +// offered through the timeout path, and the ones he accepted through the +// success path, with preimages he learns after the breach. The HTLCs of the +// two parties also share their HTLC indexes. +func testCustomChannelsBreachSecondLevelSuccess(ctx context.Context, + net *itest.IntegratedNetworkHarness, t *ccHarnessTest) { + + runCustomChannelsBreach(ctx, net, t, breachTestOpts{ + collideHtlcIndexes: true, + settleOnBreach: true, + }) +} + +// runCustomChannelsBreach runs the breach/justice scenario described on +// testCustomChannelsBreach in the given variant. +func runCustomChannelsBreach(ctx context.Context, + net *itest.IntegratedNetworkHarness, t *ccHarnessTest, + opts breachTestOpts) { + // Bump the fee rate so the justice transaction has enough fee to // pass btcd's minimum relay fee check. The default FeePerKwFloor // is borderline for the larger justice transaction. net.FeeService.SetFeeRate(chainfee.SatPerKWeight(1000), 1) lndArgs := slices.Clone(lndArgsTemplate) + lndArgs = append(lndArgs, "--bitcoin.defaultremotedelay=144") tapdArgs := slices.Clone(tapdArgsTemplate) - // We use Charlie as the proof courier. But in order for Charlie to - // also use itself, we need to define its port upfront. - charliePort := port.NextAvailablePort() + // After the breach Charlie sends his recovered assets on. That send + // spends the small asset outputs the justice sweeps created, and + // the fee of spending several of them can exceed their BTC value, + // which the default fee ratio does not allow. + tapdArgs = append(tapdArgs, "--wallet.psbt-max-fee-ratio=3.0") + + // Use Zane as a dedicated universe node that stays online as proof + // courier, so that Dave can still import proofs and advance HTLCs + // to second level even when Charlie is suspended. + // + // We allocate a port for Zane's RPC upfront and add it as an extra + // --rpclisten so the proof courier address is known before Zane + // starts (same pattern as core_test.go). + zanePort := port.NextAvailablePort() + zaneLndArgs := append(slices.Clone(lndArgs), fmt.Sprintf( + "--rpclisten=127.0.0.1:%d", zanePort, + )) tapdArgs = append(tapdArgs, fmt.Sprintf( "--proofcourieraddr=%s://%s", proof.UniverseRpcCourierType, - fmt.Sprintf(node.ListenerFormat, charliePort), + fmt.Sprintf(node.ListenerFormat, zanePort), )) + zane := net.NewNode("Zane", zaneLndArgs, tapdArgs) // Charlie will be the breached party. We set --nolisten to ensure // Dave won't be able to connect to him and trigger the channel @@ -56,9 +188,6 @@ func testCustomChannelsBreach(ctx context.Context, charlieLndArgs := append( slices.Clone(lndArgs), "--nolisten", "--minbackoff=1h", ) - charlieLndArgs = append(charlieLndArgs, fmt.Sprintf( - "--rpclisten=127.0.0.1:%d", charliePort, - )) // For this simple test, we'll just have Charlie -> Dave as an assets // channel. @@ -71,6 +200,11 @@ func testCustomChannelsBreach(ctx context.Context, connectAllNodes(t.t, net, nodes) fundAllNodes(t.t, net, nodes) + // Connect Zane to Dave directly, and have Charlie connect outbound + // to Zane (since Charlie has --nolisten and can't accept inbound). + net.EnsureConnected(t.t, zane, dave) + net.EnsureConnected(t.t, charlie, zane) + // Now we'll make an asset for Charlie that we'll use in the test to // open a channel. mintedAssets := itest.MintAssetsConfirmBatch( @@ -85,7 +219,7 @@ func testCustomChannelsBreach(ctx context.Context, assetID := cents.AssetGenesis.AssetId t.Logf("Minted %d lightning cents, syncing universes...", cents.Amount) - syncUniverses(t.t, charlie, dave) + syncUniverses(t.t, charlie, zane, dave) t.Logf("Universes synced between all nodes, distributing assets...") // Next we can open an asset channel from Charlie -> Dave, then kick @@ -119,12 +253,12 @@ func testCustomChannelsBreach(ctx context.Context, ) // Make sure that Charlie properly uploaded funding proof to the - // Universe server. + // Universe server (Zane is the proof courier). fundingScriptTree := tapscript.NewChannelFundingScriptTree() fundingScriptKey := fundingScriptTree.TaprootKey fundingScriptTreeBytes := fundingScriptKey.SerializeCompressed() assertUniverseProofExists( - t.t, charlie, assetID, nil, fundingScriptTreeBytes, + t.t, zane, assetID, nil, fundingScriptTreeBytes, fmt.Sprintf( "%v:%v", assetFundResp.Txid, assetFundResp.OutputIndex, @@ -141,33 +275,155 @@ func testCustomChannelsBreach(ctx context.Context, require.NoError(t.t, net.AssertNodeKnown(charlie, dave)) require.NoError(t.t, net.AssertNodeKnown(dave, charlie)) - // Next, we'll make keysend payments from Charlie to Dave. We'll use - // this to reach a state where both parties have funds in the channel. - const ( - numPayments = 5 - keySendAmount = 100 - btcAmt = int64(5_000) - ) - for i := 0; i < numPayments; i++ { + numHodlInvoices := numBreachHodlInvoices(t) + + // Next, we'll make keysend payments from Charlie to Dave. We scale + // the number of rebalancing payments with the requested HTLC count so + // Dave has enough BTC to carry the higher-count in-flight HTLC set on + // his local commitment without falling below reserve/fee constraints. + // Without this, higher-count variants can fail before the breach with + // one HTLC missing from the intended revoked state. + // + // When the HTLC indexes are to collide, Dave pays some of it back + // through keysends of his own below, so he is given a bit more. + keySendAmount := uint64(200) + btcAmt := int64(10_000) + if opts.collideHtlcIndexes { + keySendAmount = 250 + btcAmt = 13_000 + } + numBalancePayments := max(5, numHodlInvoices) + for i := 0; i < numBalancePayments; i++ { sendAssetKeySendPayment( t.t, charlie, dave, keySendAmount, assetID, fn.Some(btcAmt), ) } - logBalance(t.t, nodes, assetID, "after keysend -- breach state") + // Charlie's keysends advanced his HTLC counter. Advance Dave's by the + // same number of payments, so the hodl HTLCs each of them is about to + // offer get the very same HTLC indexes. + if opts.collideHtlcIndexes { + for i := 0; i < numBalancePayments; i++ { + sendAssetKeySendPayment( + t.t, dave, charlie, 30, assetID, + fn.None[int64](), + ) + } + } + + logBalance(t.t, nodes, assetID, "after keysend -- balanced state") + + // Now create hodl invoices on both sides to ensure HTLCs exist on + // the commitment we're about to backup. This tests the revoked HTLC + // sweep paths (TaprootHtlcOfferedRevoke, TaprootHtlcAcceptedRevoke). + const ( + htlcAmount = 200 + ) + var ( + daveHodlInvoices []assetHodlInvoice + charlieHodlInvoices []assetHodlInvoice + ) + + t.Logf("Creating %d hodl invoices per peer...", numHodlInvoices) + + // Use a shorter invoice expiry so that the RFQ quote's 5-minute + // lifetime is always sufficient, even when creating many invoices. + shortExpiry := withInvoiceExpiry(120) + + // Create Dave's hodl invoices (Charlie pays = outgoing HTLCs). + for i := 0; i < numHodlInvoices; i++ { + daveHodlInvoices = append( + daveHodlInvoices, createAssetHodlInvoice( + t.t, charlie, dave, htlcAmount, assetID, + shortExpiry, + ), + ) + } + + // Create Charlie's hodl invoices (Dave pays = incoming HTLCs). + for i := 0; i < numHodlInvoices; i++ { + charlieHodlInvoices = append( + charlieHodlInvoices, createAssetHodlInvoice( + t.t, dave, charlie, htlcAmount, assetID, + shortExpiry, + ), + ) + } + + // Pay all invoices but don't settle (HTLCs stay in flight). + payOpt := withFailure( + lnrpc.Payment_IN_FLIGHT, + lnrpc.PaymentFailureReason_FAILURE_REASON_NONE, + ) + + t.Logf("Paying hodl invoices to create HTLCs on commitment...") + + for _, daveInv := range daveHodlInvoices { + payInvoiceWithAssets( + t.t, charlie, dave, daveInv.payReq, assetID, payOpt, + ) + } + + for _, charlieInv := range charlieHodlInvoices { + payInvoiceWithAssets( + t.t, dave, charlie, charlieInv.payReq, assetID, payOpt, + ) + } + + // Verify HTLCs are active on both sides. + expectedHtlcs := numHodlInvoices * 2 + assertNumHtlcs(t.t, charlie, expectedHtlcs) + assertNumHtlcs(t.t, dave, expectedHtlcs) + + logBalance(t.t, nodes, assetID, "after hodl invoices -- breach state") // Now we'll create an on disk snapshot that we'll use to restore - // back to as our breached state. + // back to as our breached state. This state has active HTLCs! require.NoError(t.t, net.StopAndBackupDB(dave)) connectAllNodes(t.t, net, nodes) - // We'll send one more keysend payment now to revoke the state we - // were just at above. + // Settle all the hodl invoices to revoke the state with HTLCs. + // This will cause the backed-up state to become revoked, which + // will trigger the breach detection when Dave broadcasts it. + t.Logf("Settling hodl invoices to revoke breach state...") + + for _, daveInv := range daveHodlInvoices { + _, err := dave.InvoicesClient.SettleInvoice( + ctx, &invoicesrpc.SettleInvoiceMsg{ + Preimage: daveInv.preimage[:], + }, + ) + require.NoError(t.t, err) + } + + for _, charlieInv := range charlieHodlInvoices { + _, err := charlie.InvoicesClient.SettleInvoice( + ctx, &invoicesrpc.SettleInvoiceMsg{ + Preimage: charlieInv.preimage[:], + }, + ) + require.NoError(t.t, err) + } + + // Wait for all settled HTLCs to clear from the channel state before we + // send one more keysend. At higher HTLC counts the settlement wave can + // lag the immediate post-settle payment and leave the channel balance + // temporarily unavailable for another asset payment, making the setup + // fail for reasons unrelated to the breach-recovery logic. + assertNumHtlcs(t.t, charlie, 0) + assertNumHtlcs(t.t, dave, 0) + + // Send one more keysend to ensure the state with settled HTLCs is + // committed and the previous state (with active HTLCs) is revoked. sendAssetKeySendPayment( t.t, charlie, dave, keySendAmount, assetID, fn.Some(btcAmt), ) - logBalance(t.t, nodes, assetID, "after keysend -- final state") + + assertNumHtlcs(t.t, charlie, 0) + assertNumHtlcs(t.t, dave, 0) + + logBalance(t.t, nodes, assetID, "after settling HTLCs -- final state") // With the final state achieved, we'll now restore Dave (who will // be force closing) to that old state, the breach state. @@ -181,43 +437,387 @@ func testCustomChannelsBreach(ctx context.Context, FundingTxidStr: assetFundResp.Txid, }, } + + // Suspend Charlie BEFORE the breach so Dave can advance HTLCs to + // second level without Charlie's justice tx interfering. + t.Logf("Suspending Charlie before breach...") + restartCharlie, err := net.SuspendNode(charlie) + require.NoError(t.t, err) + _, breachTxid, err := net.CloseChannel(dave, daveChanPoint, true) require.NoError(t.t, err) t.Logf("Channel closed! Mining blocks, close_txid=%v", breachTxid) - // Next, we'll mine a block to confirm the breach transaction. + // Mine a block to confirm the breach transaction. mineBlocks(t, net, 1, 1) - // We should be able to find the transfer of the breach for both - // parties. - locateAssetTransfers(t.t, charlie, *breachTxid) - locateAssetTransfers(t.t, dave, *breachTxid) + // Dave's restored state still holds the hodl invoices as accepted. + // Settling them now hands him the preimages of the HTLCs Charlie + // offered on the revoked state, which he then takes to the second + // level through the success path. + if opts.settleOnBreach { + for _, daveInv := range daveHodlInvoices { + _, err := dave.InvoicesClient.SettleInvoice( + ctx, &invoicesrpc.SettleInvoiceMsg{ + Preimage: daveInv.preimage[:], + }, + ) + require.NoError(t.t, err) + } + } - // With the breach transaction mined, Charlie should now have a - // transaction in the mempool sweeping *both* commitment outputs. - // We use a generous timeout because Charlie needs to process the - // block, detect the breach, and construct the justice transaction. - charlieJusticeTxid, err := waitForNTxsInMempool( - net.Miner, 1, time.Second*30, + // Mine blocks to let Dave's HTLC timeout resolvers advance HTLCs to + // second level. CLTV delta is 80, so we need ~100 blocks. We must + // NOT mine enough for the CSV delay (144) on second-level outputs + // to expire, or Dave will sweep them before Charlie can. + // + // We mine in small batches and check the mempool between batches to + // give Dave's sweeper time to broadcast second-level HTLC txs. + t.Logf("Mining blocks to let Dave advance HTLCs to 2nd level...") + var secondLevelTxns []*wire.MsgTx + breachHash := breachTxid + const ( + totalBlocks = 100 + batchSize = 10 ) + var allBlocks []*wire.MsgBlock + for mined := uint32(0); mined < totalBlocks; { + // Check mempool before mining the next batch. + mempool := net.Miner.GetRawMempool() + if len(mempool) > 0 { + t.Logf("Mempool has %d txns at height offset %d", + len(mempool), mined) + for _, txid := range mempool { + rawTx := net.Miner.GetRawTransaction(txid) + tx := rawTx.MsgTx() + for _, txIn := range tx.TxIn { + op := txIn.PreviousOutPoint + if op.Hash != *breachHash { + continue + } + + t.Logf("Found 2nd-level tx %v in "+ + "mempool spending breach "+ + "output %d", tx.TxHash(), + op.Index) + } + } + } + + // Mine a batch, including any mempool txs in first block. + n := batchSize + if mined+uint32(n) > totalBlocks { + n = int(totalBlocks - mined) + } + blocks := mineBlocks(t, net, uint32(n), len(mempool)) + allBlocks = append(allBlocks, blocks...) + mined += uint32(n) + + t.Logf("Mined %d/%d blocks", mined, totalBlocks) + } + + // Dave's node processes the blocks on its own schedule and may only + // now reach the height his timeout transactions become final at. Wait + // for all the second-level transactions we expect of him to confirm, + // mining them as they show up. The few extra blocks this takes stay + // far below the CSV delay of the second-level outputs. + numTimeoutTxs := numHodlInvoices + numSuccessTxs := 0 + if opts.settleOnBreach { + numSuccessTxs = numHodlInvoices + } + err = wait.NoError(func() error { + minedTxs := blockTxs(allBlocks...) + timeoutTxs := preSignedSecondLevelTxs( + minedTxs, *breachHash, true, + ) + successTxs := preSignedSecondLevelTxs( + minedTxs, *breachHash, false, + ) + if len(timeoutTxs) >= numTimeoutTxs && + len(successTxs) >= numSuccessTxs { + + return nil + } + + mempool := net.Miner.GetRawMempool() + if len(mempool) > 0 { + allBlocks = append( + allBlocks, + mineBlocks(t, net, 1, len(mempool))..., + ) + } + + return fmt.Errorf("found %d of %d second-level timeout txs "+ + "and %d of %d second-level success txs", + len(timeoutTxs), numTimeoutTxs, len(successTxs), + numSuccessTxs) + }, wait.DefaultTimeout) require.NoError(t.t, err) - t.Logf("Charlie justice txid: %v", charlieJusticeTxid) + // Scan all mined blocks for second-level txns (txs spending from + // the breach transaction). + for _, block := range allBlocks { + for _, tx := range block.Transactions { + for _, txIn := range tx.TxIn { + if txIn.PreviousOutPoint.Hash == *breachHash { + t.Logf("Found 2nd-level tx %v "+ + "spending breach output %d", + tx.TxHash(), + txIn.PreviousOutPoint.Index) + + secondLevelTxns = append( + secondLevelTxns, tx, + ) + } + } + } + } + t.Logf("Found %d second-level txns total", len(secondLevelTxns)) + require.NotEmpty(t.t, secondLevelTxns, + "expected second-level HTLC transactions") + + // Dave took every HTLC he offered to the second level through its + // pre-signed timeout tx, and, if he learned the preimages, every HTLC + // he accepted through its pre-signed success tx. Each of them has + // the deterministic shape: one input, the HTLC output and its CPFP + // anchor. + timeoutTxs := preSignedSecondLevelTxs( + blockTxs(allBlocks...), *breachHash, true, + ) + successTxs := preSignedSecondLevelTxs( + blockTxs(allBlocks...), *breachHash, false, + ) + require.Len( + t.t, timeoutTxs, numTimeoutTxs, "expected one second-level "+ + "timeout tx per HTLC Dave offered", + ) + require.Len( + t.t, successTxs, numSuccessTxs, "unexpected number of "+ + "second-level success txs", + ) - // Next, we'll mine a block to confirm Charlie's justice transaction. - mineBlocks(t, net, 1, 1) + // Log the breach tx outputs for reference. + breachTx := net.Miner.GetRawTransaction(*breachTxid) + for i, out := range breachTx.MsgTx().TxOut { + t.Logf("Breach output %d: value=%d pkscript=%x", + i, out.Value, out.PkScript) + } + + // Log second-level tx details. + for i, tx := range secondLevelTxns { + for j, out := range tx.TxOut { + t.Logf("2nd-level tx %d output %d: value=%d "+ + "pkscript=%x", i, j, out.Value, out.PkScript) + } + } + + // justiceBlocks collects the blocks mined while Charlie serves + // justice, so the spends of the second-level outputs can be inspected + // afterwards. + var justiceBlocks []*wire.MsgBlock + mineJustice := func(num uint32, numTxs int) { + justiceBlocks = append( + justiceBlocks, mineBlocks(t, net, num, numTxs)..., + ) + } + + // Now resume Charlie. She should detect the breach and attempt + // justice, including sweeping any second-level HTLC outputs. + t.Logf("Resuming Charlie...") + restartCharlie() + + // Wait for Charlie's justice tx(s) in the mempool. The breach + // arbitrator can publish a variable number of justice variants here + // depending on how many HTLCs have already moved to second level, and + // it may replace them while converging on the final set. Wait for the + // mempool to become non-empty, then mine whatever set is present. + t.Logf("Waiting for Charlie's justice txns in mempool...") + charlieJusticeTxids, err := waitForNonEmptyMempool( + net.Miner, wait.MinerMempoolTimeout, + ) + require.NoError(t.t, err, + "expected Charlie's justice tx(s) in mempool") + + t.Logf("Charlie justice txids: %v", charlieJusticeTxids) + + // Log justice tx details. The BRAR may replace txs between our + // mempool query and the GetRawTransaction call, so tolerate errors. + for _, txid := range charlieJusticeTxids { + justiceTx := net.Miner.GetRawTransaction(*txid) + t.Logf("Justice tx %v has %d inputs:", + txid, len(justiceTx.MsgTx().TxIn)) + for _, txIn := range justiceTx.MsgTx().TxIn { + t.Logf(" input: %v (witness len=%d)", + txIn.PreviousOutPoint, len(txIn.Witness)) + } + for i, out := range justiceTx.MsgTx().TxOut { + t.Logf(" output %d: value=%d", i, out.Value) + } + } + + // Mine the justice transaction(s). The breach arbiter may create + // multiple justice tx variants (spendAll, split variants, and + // individual second-level sweeps). Poll the mempool briefly in + // case more txs arrive, then mine a block. + mp := net.Miner.GetRawMempool() + t.Logf("Mempool has %d txs before mining justice block", + len(mp)) + mineJustice(1, len(mp)) + t.Logf("Justice tx confirmed") + + // After the first justice tx confirms, the breach arbiter may detect + // that some outputs were spent to second level and create follow-up + // justice txs. Give it a few blocks to react. + t.Logf("Mining blocks to let breach arbiter react to " + + "second-level...") + for i := 0; i < 10; i++ { + // Give the breach arbiter time to detect spends, + // morph inputs, and broadcast new justice tx variants. + time.Sleep(2 * time.Second) + + mp := net.Miner.GetRawMempool() + + if len(mp) > 0 { + t.Logf("Found %d txns in mempool after %d blocks:", + len(mp), i) + for _, txid := range mp { + raw := net.Miner.GetRawTransaction(txid) + tx := raw.MsgTx() + t.Logf(" tx %v: %d inputs, %d outputs", + txid, len(tx.TxIn), len(tx.TxOut)) + for _, in := range tx.TxIn { + t.Logf(" input: %v "+ + "(witness len=%d)", + in.PreviousOutPoint, + len(in.Witness)) + } + for j, out := range tx.TxOut { + t.Logf(" output %d: value=%d", + j, out.Value) + } + } + + mineJustice(1, len(mp)) + t.Logf("Mined second-level justice tx") + } else { + mineJustice(1, 0) + } + } + + // Mine a few more blocks to trigger the porter's confirmation + // detection for all justice sweep transfers. The porter processes + // transfers sequentially and needs block notifications to complete + // the historical confirmation scan. + mineJustice(3, 0) + + // After sweeping, Charlie should have all the asset balance back. + // For larger HTLC counts the porter can need significantly more + // block notifications to reconcile all confirmed justice sweeps. Poll + // balance directly here so the stress variants fail with useful + // transfer-state logs instead of a generic final-balance mismatch. + var balanceChecks int + require.Eventually(t.t, func() bool { + balanceChecks++ + currentBalance := currentAssetBalance(charlie, assetID) + if currentBalance == + ccItestAsset.Amount { + + return true + } + + if balanceChecks == 1 || balanceChecks%10 == 0 { + t.Logf("Charlie recovered balance still pending: "+ + "got=%d want=%d after %d checks", + currentBalance, ccItestAsset.Amount, + balanceChecks) + logRecentTransfers(t, charlie) + } + + mineJustice(1, 0) + time.Sleep(time.Second) + + return false + }, 2*time.Minute, 2*time.Second) + + assertBalance( + t.t, charlie, ccItestAsset.Amount, + itest.WithAssetID(assetID), + ) - // Charlie should now have a transfer for his justice transaction. - locateAssetTransfers(t.t, charlie, *charlieJusticeTxid[0]) + t.Logf("Charlie balance restored after breach") + + // The final balance alone does not show how the second-level outputs + // were recovered. Each second-level HTLC output must have been spent + // by Charlie's justice, which claims it through the revocation key: + // a taproot key spend, whose witness is the signature and nothing + // else. Dave's own claim after the CSV delay would be a script path + // spend, and the delay has not passed anyway. + spenders := make(map[wire.OutPoint]*wire.TxIn) + for _, tx := range blockTxs(justiceBlocks...) { + for _, txIn := range tx.TxIn { + spenders[txIn.PreviousOutPoint] = txIn + } + } + for _, secondLevelTx := range append(timeoutTxs, successTxs...) { + htlcOutput := wire.OutPoint{ + Hash: secondLevelTx.TxHash(), + Index: 0, + } + + spender, ok := spenders[htlcOutput] + require.True( + t.t, ok, "second-level HTLC output %v was not swept", + htlcOutput, + ) + require.Len( + t.t, spender.Witness, 1, "second-level HTLC output "+ + "%v was not swept through the revocation key", + htlcOutput, + ) + } + + // Give the porter time to fully finalize all justice sweep + // transfers. The balance assertion above succeeds as soon as the + // assets appear, but the anchor output metadata may still be + // processing. + mineBlocks(t, net, 3, 0) + + // Verify the recovered assets are spendable by sending ALL of + // them from Charlie to Dave. This proves the full proof chain + // (funding → commitment → second-level → justice → spend) is + // valid end-to-end for every recovered output. + sendAmt := ccItestAsset.Amount + ctxSend := context.Background() + daveAddr, err := asTapd(dave).NewAddr( + ctxSend, &taprpc.NewAddrRequest{ + Amt: sendAmt, + AssetId: assetID, + ProofCourierAddr: fmt.Sprintf( + "%s://%s", + proof.UniverseRpcCourierType, + zane.RPCAddr(), + ), + }, + ) + require.NoError(t.t, err) + + itest.AssertAddrCreated(t.t, asTapd(dave), cents, daveAddr) + _, err = asTapd(charlie).SendAsset( + ctxSend, &taprpc.SendAssetRequest{ + TapAddrs: []string{daveAddr.Encoded}, + }, + ) + require.NoError(t.t, err) + + // Mine the send transaction. + mineBlocks(t, net, 1, 1) - // Charlie's balance should now be the same as before the breach - // attempt: the amount he minted at the very start. - charlieBalance := ccItestAsset.Amount + // Verify Dave received all the assets. assertBalance( - t.t, charlie, charlieBalance, itest.WithAssetID(assetID), - itest.WithNumUtxos(3), + t.t, dave, sendAmt, itest.WithAssetID(assetID), ) - t.Logf("Charlie balance after breach: %d", charlieBalance) + t.Logf("Post-breach on-chain spend successful: proof chain valid") } diff --git a/itest/custom_channels/core_test.go b/itest/custom_channels/core_test.go index 75a3acc6b9..58dac2edff 100644 --- a/itest/custom_channels/core_test.go +++ b/itest/custom_channels/core_test.go @@ -193,7 +193,7 @@ func testCustomChannels(ctx context.Context, // Dave, making it possible to send another asset HTLC below, sending // all assets back to Charlie (so we have enough balance for further // tests). - sendKeySendPayment(t.t, charlie, dave, 2000) + sendKeySendPayment(t.t, charlie, dave, 10_000) logBalance(t.t, nodes, assetID, "after BTC only keysend") // Let's keysend the rest of the balance back to Charlie. diff --git a/itest/custom_channels/custom_channels_test.go b/itest/custom_channels/custom_channels_test.go index 53cac31663..7c59bda512 100644 --- a/itest/custom_channels/custom_channels_test.go +++ b/itest/custom_channels/custom_channels_test.go @@ -143,6 +143,10 @@ var testCases = []*ccTestCase{ name: "breach", test: testCustomChannelsBreach, }, + { + name: "breach second level success", + test: testCustomChannelsBreachSecondLevelSuccess, + }, { name: "v1 upgrade", test: testCustomChannelsV1Upgrade, diff --git a/itest/custom_channels/deterministic_htlcs_upgrade_test.go b/itest/custom_channels/deterministic_htlcs_upgrade_test.go new file mode 100644 index 0000000000..78bb128aec --- /dev/null +++ b/itest/custom_channels/deterministic_htlcs_upgrade_test.go @@ -0,0 +1,41 @@ +//go:build itest + +package custom_channels + +import ( + "context" + "testing" + + "github.com/lightninglabs/taproot-assets/itest" +) + +// deterministicHtlcsUpgradeVersion is a release whose asset channels know +// nothing of deterministic second-level HTLCs. +const deterministicHtlcsUpgradeVersion = "v0.8.4" + +// TestDeterministicHtlcsUpgrade tests that an asset channel opened before +// deterministic second-level HTLCs existed moves over to them once both +// peers run a build that negotiates the feature. Both peers open the channel +// and exchange payments on the old release, then upgrade and reconnect. The +// commitments that exist at that point were built with the legacy HTLC +// sighash and must keep being treated as such, while every commitment +// created afterwards uses the deterministic form. Payments in both +// directions take the channel across that switch. +// +// The channel is then force closed with HTLCs in flight in both directions, +// and the full HTLC force close scenario must play out exactly as it does +// for a channel that was deterministic from the start: pre-signed +// second-level HTLC transactions with a CPFP anchor, their imports and all +// sweeps. This only works if lnd and tapd agreed on the sighash of every +// commitment throughout the switch. +func TestDeterministicHtlcsUpgrade(t *testing.T) { + oldBinary := buildCompatBinary(t, deterministicHtlcsUpgradeVersion) + t.Logf("Using compat binary for %s: %s", + deterministicHtlcsUpgradeVersion, oldBinary) + + runWithCompatHarness(t, func(ctx context.Context, + net *itest.IntegratedNetworkHarness, ht *ccHarnessTest) { + + runCustomChannelsHtlcForceClose(ctx, ht, net, false, oldBinary) + }) +} diff --git a/itest/custom_channels/force_close_test.go b/itest/custom_channels/force_close_test.go index 4d1314a64b..d7946bb169 100644 --- a/itest/custom_channels/force_close_test.go +++ b/itest/custom_channels/force_close_test.go @@ -226,7 +226,7 @@ func testCustomChannelsForceClose(ctx context.Context, t.Logf("Universe proofs located!") // We should also have a new sweep transaction in the mempool. - _, err = waitForNTxsInMempool( + _, err = waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) @@ -250,7 +250,7 @@ func testCustomChannelsForceClose(ctx context.Context, mineBlocks(t, net, 2, 0) // We expect that Charlie's sweep transaction has been broadcast. - charlieSweepTxid, err := waitForNTxsInMempool( + charlieSweepTxid, err := waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) diff --git a/itest/custom_channels/forward_bandwidth_test.go b/itest/custom_channels/forward_bandwidth_test.go index 774eb5adfa..04b0c9b8f2 100644 --- a/itest/custom_channels/forward_bandwidth_test.go +++ b/itest/custom_channels/forward_bandwidth_test.go @@ -138,7 +138,7 @@ func testCustomChannelsForwardBandwidth(ctx context.Context, ) // Test case 2: We cannot pay an invoice from Charlie to Fabia. - invoiceResp := createAssetInvoice(t.t, erin, fabia, 123, assetID) + invoiceResp := createAssetInvoice(t.t, erin, fabia, 200, assetID) payInvoiceWithSatoshi( t.t, charlie, invoiceResp, withFailure(lnrpc.Payment_FAILED, failureNoRoute), @@ -216,7 +216,7 @@ func testCustomChannelsForwardBandwidth(ctx context.Context, // Let's make sure we can still use the channel between Erin and Fabia // by doing a satoshi keysend payment. - sendKeySendPayment(t.t, erin, fabia, 2000) + sendKeySendPayment(t.t, erin, fabia, 10_000) logBalance(t.t, nodes, assetID, "after BTC only keysend") // Finally, we close the channel between Erin and Fabia to make sure diff --git a/itest/custom_channels/group_tranches_force_close_test.go b/itest/custom_channels/group_tranches_force_close_test.go index 2592ba14a1..b13bafffdc 100644 --- a/itest/custom_channels/group_tranches_force_close_test.go +++ b/itest/custom_channels/group_tranches_force_close_test.go @@ -240,7 +240,7 @@ func testCustomChannelsGroupTranchesForceClose(ctx context.Context, t.Logf("Universe proofs located!") // We should also have a new sweep transaction in the mempool. - fabiaSweepTxid, err := waitForNTxsInMempool( + fabiaSweepTxid, err := waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) @@ -260,7 +260,7 @@ func testCustomChannelsGroupTranchesForceClose(ctx context.Context, mineBlocks(t, net, 2, 0) // We expect that Erin's sweep transaction has been broadcast. - _, err = waitForNTxsInMempool( + _, err = waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) diff --git a/itest/custom_channels/grouped_asset_test.go b/itest/custom_channels/grouped_asset_test.go index 0049d28802..bce9aea3fd 100644 --- a/itest/custom_channels/grouped_asset_test.go +++ b/itest/custom_channels/grouped_asset_test.go @@ -169,7 +169,7 @@ func testCustomChannelsGroupedAsset(_ context.Context, // We should also be able to do a non-asset (BTC only) keysend // payment. - sendKeySendPayment(t.t, charlie, dave, 2000) + sendKeySendPayment(t.t, charlie, dave, 10_000) logBalance(t.t, nodes, assetID, "after BTC only keysend") // ------------ diff --git a/itest/custom_channels/helpers.go b/itest/custom_channels/helpers.go index b31a6d0eb0..98adcef15f 100644 --- a/itest/custom_channels/helpers.go +++ b/itest/custom_channels/helpers.go @@ -214,6 +214,7 @@ type invoiceConfig struct { groupKey []byte msats lnwire.MilliSatoshi routeHints []*lnrpc.RouteHint + expiry int64 } func defaultInvoiceConfig() *invoiceConfig { @@ -230,6 +231,12 @@ func withInvoiceErrSubStr(errSubStr string) invoiceOpt { } } +func withInvoiceExpiry(seconds int64) invoiceOpt { + return func(c *invoiceConfig) { + c.expiry = seconds + } +} + func withInvGroupKey(groupKey []byte) invoiceOpt { return func(c *invoiceConfig) { c.groupKey = groupKey @@ -1323,8 +1330,10 @@ func sendAssetKeySendPayment(t *testing.T, src, dst *itest.IntegratedNode, customRecords[record.KeySendType] = preimage[:] sendReq := &routerrpc.SendPaymentRequest{ - Dest: dst.PubKey[:], - Amt: btcAmt.UnwrapOr(500), + Dest: dst.PubKey[:], + Amt: btcAmt.UnwrapOr( + int64(rfqmath.DefaultOnChainHtlcSat), + ), DestCustomRecords: customRecords, PaymentHash: hash[:], TimeoutSeconds: int32(PaymentTimeout.Seconds()), @@ -1716,11 +1725,22 @@ func defaultCoOpCloseBalanceCheck(t *testing.T, outIdx := 0 dummyAmt := int64(1000) - require.LessOrEqual(t, closeTx.TxOut[outIdx].Value, dummyAmt) + + // A party whose total BTC balance exceeds the 1k sat asset anchor + // amount by less than the dust limit has the sub-dust remainder + // folded into its asset output instead of creating an unspendable + // BTC output. Under DeterministicHTLCs the received HTLCs carry + // 1200 sats each, so a receiver of a single HTLC ends up with + // 1000 + 200 on its asset output. + dustLimit := int64(354) + maxAssetOutAmt := dummyAmt + dustLimit + require.LessOrEqual(t, closeTx.TxOut[outIdx].Value, maxAssetOutAmt) if remoteAssetBalance { outIdx++ - require.LessOrEqual(t, closeTx.TxOut[outIdx].Value, dummyAmt) + require.LessOrEqual( + t, closeTx.TxOut[outIdx].Value, maxAssetOutAmt, + ) } require.Len(t, closeUpdate.AdditionalOutputs, additionalOutputs) @@ -2527,6 +2547,9 @@ func createAssetHodlInvoice(t *testing.T, dstRfqPeer, defer cancel() timeoutSeconds := int64(rfq.DefaultInvoiceExpiry.Seconds()) + if cfg.expiry > 0 { + timeoutSeconds = cfg.expiry + } var rfqPeer []byte if dstRfqPeer != nil { @@ -2766,6 +2789,44 @@ func assertSpendableBalance(t *testing.T, client *itest.IntegratedNode, } } +// mineUntilSpendableBalance drives block production until the node's +// spendable asset balance reaches the expected value, and returns the blocks +// it mined. Under the async pre-signed publish + CPFP anchor design, +// force-close transactions (the pre-signed second-level HTLC txs, +// sweeper-driven sweeps and anchor CPFP sweeps) reach the mempool on their +// own schedule and may confirm during earlier block batches, so +// outcome-driven block production is more robust than asserting on transient +// PendingSweeps or mempool snapshots. +func mineUntilSpendableBalance(t *ccHarnessTest, + net *itest.IntegratedNetworkHarness, node *itest.IntegratedNode, + assetID, groupKey []byte, expectedBalance uint64) []*wire.MsgBlock { + + t.t.Helper() + + var blocks []*wire.MsgBlock + for i := 0; i < 6; i++ { + balance, err := spendableBalance(node, assetID, groupKey) + if err == nil && balance == expectedBalance { + return blocks + } + + // Confirm whatever is waiting in the mempool; if nothing is + // waiting, mine an empty block to tick the sweeper. + numTxs, _ := waitForAtLeastNTxsInMempool( + net.Miner, 1, ccShortTimeout, + ) + blocks = append( + blocks, mineBlocks(t, net, 1, len(numTxs))..., + ) + } + + assertSpendableBalance( + t.t, node, assetID, groupKey, expectedBalance, + ) + + return blocks +} + // locateAssetTransfers finds and returns the asset transfer for the given // transaction ID. func locateAssetTransfers(t *testing.T, node *itest.IntegratedNode, @@ -2803,6 +2864,197 @@ func locateAssetTransfers(t *testing.T, node *itest.IntegratedNode, return transfer } +// nodeSweepTxids returns the txids of the sweep transactions the sweeper of +// the node's lnd has published. +func nodeSweepTxids(node *itest.IntegratedNode) (map[string]struct{}, error) { + sweeps, err := node.WalletKitClient.ListSweeps( + context.Background(), &walletrpc.ListSweepsRequest{}, + ) + if err != nil { + return nil, fmt.Errorf("unable to list %v sweeps: %w", + node.Cfg.Name, err) + } + + txids := make(map[string]struct{}) + for _, txid := range sweeps.GetTransactionIds().GetTransactionIds() { + txids[txid] = struct{}{} + } + + return txids, nil +} + +// confirmedSweepTransfer looks through the given blocks for a transaction +// that is both a sweep published by the node's lnd sweeper and the anchor of +// a confirmed asset transfer of the node, and returns the first such +// transfer. Both +// conditions together pin the transfer to the node's own asset sweep: a +// sweep block also carries transactions of the other party, and pure-BTC +// sweeps of the node itself (the CPFP anchor sweeps of pre-signed +// second-level HTLC txs), neither of which may be taken for it. +func confirmedSweepTransfer(node *itest.IntegratedNode, + blocks []*wire.MsgBlock) (*taprpc.AssetTransfer, error) { + + sweepTxids, err := nodeSweepTxids(node) + if err != nil { + return nil, err + } + + ctxb := context.Background() + var found []*taprpc.AssetTransfer + for _, block := range blocks { + for _, tx := range block.Transactions[1:] { + txid := tx.TxHash().String() + if _, ok := sweepTxids[txid]; !ok { + continue + } + + resp, err := node.ListTransfers( + ctxb, &taprpc.ListTransfersRequest{ + AnchorTxid: txid, + }, + ) + if err != nil { + return nil, fmt.Errorf("unable to list %v "+ + "transfers: %w", node.Cfg.Name, err) + } + if len(resp.Transfers) != 1 { + continue + } + if resp.Transfers[0].AnchorTxBlockHash == nil { + continue + } + + found = append(found, resp.Transfers[0]) + } + } + + if len(found) == 0 { + return nil, fmt.Errorf("%v: no sweep with a confirmed asset "+ + "transfer found in %d blocks", node.Cfg.Name, + len(blocks)) + } + + return found[0], nil +} + +// locateBlockAssetTransfer locates the confirmed asset transfer of the +// node's sweep transaction in the given block. With the CPFP anchor design, +// a sweep block may also contain pure-BTC transactions (e.g. second-level +// anchor sweeps) that never produce an asset transfer, so we can't assume a +// fixed transaction index. The sweep is instead identified as the +// transaction lnd's sweeper reports as its own, see confirmedSweepTransfer. +func locateBlockAssetTransfer(t *testing.T, node *itest.IntegratedNode, + block *wire.MsgBlock) *taprpc.AssetTransfer { + + var transfer *taprpc.AssetTransfer + err := wait.NoError(func() error { + var err error + transfer, err = confirmedSweepTransfer( + node, []*wire.MsgBlock{block}, + ) + + return err + }, ccTransferTimeout) + require.NoError(t, err) + + return transfer +} + +// locateSweepAssetTransfer locates the confirmed asset transfer of the +// node's sweep transaction in one of the already-mined sweep blocks, mining +// up to a few extra blocks if needed. Under the CPFP anchor design a mined +// block may contain only pure-BTC transactions (e.g. second-level anchor +// sweeps) while the asset-bearing sweep is still pending in the sweeper, so +// we keep confirming mempool transactions until the transfer shows up. The +// sweep is identified as the transaction lnd's sweeper reports as its own, +// see confirmedSweepTransfer. +func locateSweepAssetTransfer(t *ccHarnessTest, + net *itest.IntegratedNetworkHarness, node *itest.IntegratedNode, + initial []*wire.MsgBlock) *taprpc.AssetTransfer { + + blocks := append([]*wire.MsgBlock{}, initial...) + + probe := func(timeout time.Duration) (*taprpc.AssetTransfer, error) { + var transfer *taprpc.AssetTransfer + err := wait.NoError(func() error { + var err error + transfer, err = confirmedSweepTransfer(node, blocks) + + return err + }, timeout) + + return transfer, err + } + + // Probe the blocks we have, mining a few extra blocks to flush any + // still-pending sweeps out of the sweeper and mempool. + for i := 0; i < 3; i++ { + if transfer, err := probe(ccShortTimeout); err == nil { + return transfer + } + + // Confirm whatever is waiting in the mempool. If nothing is + // waiting, mine an empty block anyway: the sweeper batches + // pending sweeps on block ticks, so an empty block can be + // exactly what flushes the next sweep transaction out. + memTxs, _ := waitForAtLeastNTxsInMempool( + net.Miner, 1, ccShortTimeout, + ) + + blocks = append(blocks, mineBlocks(t, net, 1, len(memTxs))[0]) + } + + transfer, err := probe(ccTransferTimeout) + require.NoError(t.t, err) + + return transfer +} + +// secondLevelAnchorValue is the value of the CPFP anchor output of a +// pre-signed second-level HTLC transaction. +const secondLevelAnchorValue = 330 + +// preSignedSecondLevelTxs returns the pre-signed second-level HTLC +// transactions of the given commitment among the passed transactions. Under +// DeterministicHTLCs such a transaction is published verbatim: it has a +// single input, the HTLC output of the commitment, and exactly two outputs, +// the second-level HTLC output followed by its CPFP anchor. The timeout +// variant carries the HTLC's absolute timeout as locktime, the success +// variant has none. +func preSignedSecondLevelTxs(txs []*wire.MsgTx, commitTxid chainhash.Hash, + timeout bool) []*wire.MsgTx { + + var secondLevelTxs []*wire.MsgTx + for _, tx := range txs { + if len(tx.TxIn) != 1 || len(tx.TxOut) != 2 { + continue + } + if tx.TxIn[0].PreviousOutPoint.Hash != commitTxid { + continue + } + if tx.TxOut[1].Value != secondLevelAnchorValue { + continue + } + if (tx.LockTime != 0) != timeout { + continue + } + + secondLevelTxs = append(secondLevelTxs, tx) + } + + return secondLevelTxs +} + +// blockTxs returns the non-coinbase transactions of the given blocks. +func blockTxs(blocks ...*wire.MsgBlock) []*wire.MsgTx { + var txs []*wire.MsgTx + for _, block := range blocks { + txs = append(txs, block.Transactions[1:]...) + } + + return txs +} + // --------------------------------------------------------------------------- // HTLC event helpers // --------------------------------------------------------------------------- @@ -3302,7 +3554,7 @@ func assertForceCloseSweeps(ctx context.Context, walletrpc.WitnessType_TAPROOT_HTLC_ACCEPTED_REMOTE_SUCCESS, ) - _, err = waitForNTxsInMempool( + memTxs, err := waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) @@ -3311,27 +3563,25 @@ func assertForceCloseSweeps(ctx context.Context, // both his commitment output, and the incoming HTLC that we just // settled above. We use the txid from the mined block (not from the // mempool check above) because the sweeper may RBF between the two. - bobSweepBlocks1 := mineBlocks(t, net, 1, 1) + bobSweepBlocks1 := mineBlocks(t, net, 1, len(memTxs)) // At this point, we should have the next sweep transaction in the // mempool: Bob's incoming HTLC sweep directly off the commitment // transaction. - _, err = waitForNTxsInMempool( + memTxs, err = waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) // We'll now mine the next block, which should confirm Bob's HTLC sweep // transaction. - bobSweepBlocks2 := mineBlocks(t, net, 1, 1) + bobSweepBlocks2 := mineBlocks(t, net, 1, len(memTxs)) // Wait for tapd to process the confirmed sweep transactions before // checking balances. We extract the txid from the mined blocks rather // than from the earlier mempool checks to avoid RBF mismatches. - bobSweepTxHash1 := bobSweepBlocks1[0].Transactions[1].TxHash() - bobSweepTxHash2 := bobSweepBlocks2[0].Transactions[1].TxHash() - locateAssetTransfers(t.t, bob, bobSweepTxHash1) - locateAssetTransfers(t.t, bob, bobSweepTxHash2) + locateBlockAssetTransfer(t.t, bob, bobSweepBlocks1[0]) + locateBlockAssetTransfer(t.t, bob, bobSweepBlocks2[0]) t.Logf("Confirming Bob's remote HTLC success sweep") @@ -3352,17 +3602,16 @@ func assertForceCloseSweeps(ctx context.Context, // sweep her to-local output. mineBlocks(t, net, 1, 0) - _, err = waitForNTxsInMempool( + memTxs, err = waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) - aliceToLocalBlocks := mineBlocks(t, net, 1, 1) + aliceToLocalBlocks := mineBlocks(t, net, 1, len(memTxs)) // Wait for tapd to register the to-local sweep transfer. We use the // txid from the mined block to avoid RBF mismatches. - aliceToLocalHash := aliceToLocalBlocks[0].Transactions[1].TxHash() - locateAssetTransfers(t.t, alice, aliceToLocalHash) + locateBlockAssetTransfer(t.t, alice, aliceToLocalBlocks[0]) t.Logf("Confirming Alice's to-local sweep") @@ -3385,33 +3634,49 @@ func assertForceCloseSweeps(ctx context.Context, ) require.NoError(t.t, err) - // We'll pause here for Alice to extend the sweep request to the - // sweeper. - assertSweepExists( - t.t, alice, - walletrpc.WitnessType_TAPROOT_HTLC_ACCEPTED_LOCAL_SUCCESS, - ) - - // We'll now mine a block, which should trigger Alice's broadcast of the - // second level sweep transaction. - sweepBlocks := mineBlocks(t, net, 1, 0) + // Under the negotiated DeterministicHTLCs feature, the htlc success + // resolver hands the pre-signed 2nd-level HTLC success tx to the + // sweeper to publish verbatim (SigHashDefault, baked-in fees), so no + // TAPROOT_HTLC_ACCEPTED_LOCAL_SUCCESS entry ever shows up in lnd's + // PendingSweeps. We wait for exactly that transaction in the mempool + // instead: a single input spending the commitment, the HTLC output + // and its CPFP anchor, and no locktime. + var successTxs []*wire.MsgTx + err = wait.NoError(func() error { + var mempoolTxs []*wire.MsgTx + for _, txid := range net.Miner.GetRawMempool() { + tx := net.Miner.GetRawTransaction(txid) + mempoolTxs = append(mempoolTxs, tx.MsgTx()) + } - // If the block mined above didn't also mine our sweep, then we'll mine - // one final block which will confirm Alice's sweep transaction. - if len(sweepBlocks[0].Transactions) == 1 { - _, err := waitForNTxsInMempool( - net.Miner, 1, ccShortTimeout, + successTxs = preSignedSecondLevelTxs( + mempoolTxs, *closeTxid, false, ) - require.NoError(t.t, err) + if len(successTxs) == 0 { + return fmt.Errorf("pre-signed second-level success " + + "tx not in mempool") + } - // With the sweep transaction in the mempool, we'll mine a block - // to confirm the sweep. - sweepBlocks = mineBlocks(t, net, 1, 1) - } + return nil + }, ccShortTimeout) + require.NoError(t.t, err) - // Use the txid from the mined block to avoid RBF mismatches. - sweepTxHash := sweepBlocks[0].Transactions[1].TxHash() - locateAssetTransfers(t.t, alice, sweepTxHash) + memTxs, err = waitForAtLeastNTxsInMempool( + net.Miner, 1, ccShortTimeout, + ) + require.NoError(t.t, err) + + // Mine a block to confirm the pre-signed 2nd-level HTLC success tx. + // tapd only records an asset transfer for it once the resolver + // resolves the second-level output sweep, so the transfer is asserted + // below, after that sweep. + successBlocks := mineBlocks(t, net, 1, len(memTxs)) + for _, successTx := range successTxs { + require.Contains( + t.t, blockTxs(successBlocks...), successTx, + "pre-signed second-level success tx not mined", + ) + } t.Logf("Confirming Alice's second level remote HTLC success sweep") @@ -3431,21 +3696,27 @@ func assertForceCloseSweeps(ctx context.Context, // Now that we know the sweep was offered, we'll mine an extra block to // actually trigger a sweeper broadcast. - sweepBlocks = mineBlocks(t, net, 1, 0) + sweepBlocks := mineBlocks(t, net, 1, 0) // If the block mined above didn't also mine our sweep, then we'll mine // one final block which will confirm Alice's sweep transaction. if len(sweepBlocks[0].Transactions) == 1 { - _, err := waitForNTxsInMempool( + memTxs, err := waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) require.NoError(t.t, err) - sweepBlocks = mineBlocks(t, net, 1, 1) + sweepBlocks = mineBlocks(t, net, 1, len(memTxs)) } - sweepTxHash = sweepBlocks[0].Transactions[1].TxHash() - locateAssetTransfers(t.t, alice, sweepTxHash) + locateSweepAssetTransfer(t, net, alice, sweepBlocks) + + // By now Alice has also imported the second-level success tx itself: + // the transfer from the commitment HTLC output to the second-level + // output must be there, anchored in exactly that transaction. + for _, successTx := range successTxs { + locateAssetTransfers(t.t, alice, successTx.TxHash()) + } // With the sweep transaction confirmed, Alice's balance should have // incremented by the amt of the HTLC. @@ -3462,18 +3733,26 @@ func assertForceCloseSweeps(ctx context.Context, blockToMine := closeExpiryInfo.blockTillExpiry( aliceHodlInvoices[1].preimage.Hash(), ) - mineBlocks(t, net, blockToMine, 0) - // We'll wait for both Alice and Bob to present their respective sweeps - // to the sweeper. + // Mine all but the final block first, then trigger the expiry with a + // single block. If we mined the whole batch at once, the sweeper + // could broadcast the remote-timeout sweep mid-batch and a later + // block of the same batch would confirm it, so it would no longer be + // listed as pending by the time we assert below. + if blockToMine > 1 { + mineBlocks(t, net, blockToMine-1, 0) + } + mineBlocks(t, net, 1, 0) + + // We'll wait for Bob to present his remote-timeout sweep to the + // sweeper. Alice's local outgoing HTLC times out via the pre-signed + // 2nd-level timeout tx under DeterministicHTLCs (SigHashDefault, + // baked-in fees), which the sweeper publishes verbatim, so it never + // appears in lnd's PendingSweeps. It is asserted on chain below. numTimeoutHTLCs := 1 if mpp { numTimeoutHTLCs += numAdditionalShards } - assertSweepExists( - t.t, alice, - walletrpc.WitnessType_TAPROOT_HTLC_LOCAL_OFFERED_TIMEOUT, - ) assertSweepExists( t.t, bob, walletrpc.WitnessType_TAPROOT_HTLC_OFFERED_REMOTE_TIMEOUT, @@ -3481,47 +3760,14 @@ func assertForceCloseSweeps(ctx context.Context, t.Logf("Confirming initial HTLC timeout txns") - // Mine the HTLC timeout sweeps sequentially. A wallet UTXO - // selection bug in the sweeper can cause competing InputSets - // to pick the same fee-paying UTXO, so both sweeps may not - // coexist in the mempool simultaneously. We mine what's - // available and let the sweeper retry on the next tick. - _, err = waitForAtLeastNTxsInMempool( - net.Miner, 1, wait.DefaultTimeout, - ) - require.NoError(t.t, err) - - // Mine a block containing whatever timeout sweeps are - // currently in the mempool. - sweepBlocks = mineBlocks(t, net, 1, 0) - numMined := len(sweepBlocks[0].Transactions) - 1 - - // Collect txids from the mined block for Bob's sweep - // identification below. - var timeoutSweeps []*chainhash.Hash - for i := range sweepBlocks[0].Transactions[1:] { - hash := sweepBlocks[0].Transactions[i+1].TxHash() - timeoutSweeps = append(timeoutSweeps, &hash) - } - - // If only one sweep was mined (the other was RBF'd out due to - // a UTXO collision), wait for the sweeper to retry and mine - // the second sweep. - if numMined < 2 { - _, err = waitForAtLeastNTxsInMempool( - net.Miner, 1, wait.DefaultTimeout, - ) - require.NoError(t.t, err) - - sweepBlocks2 := mineBlocks(t, net, 1, 0) - for i := range sweepBlocks2[0].Transactions[1:] { - hash := sweepBlocks2[0].Transactions[i+1].TxHash() - timeoutSweeps = append(timeoutSweeps, &hash) - } - } - - t.Logf("Asserting balance on sweeps: %v", timeoutSweeps) + // timeoutBlocks collects every block mined from here on, so the + // pre-signed second-level timeout txs of Alice can be picked out of + // them once they all confirmed. + var timeoutBlocks []*wire.MsgBlock + // countBobSweptHTLCs returns the number of timed out HTLCs that the + // sweep transactions of Bob among the given blocks claim. + // // The sweeper records a sweep in its store only after its own // publish path has completed, which can lag the transaction's // appearance in the mempool (and its confirmation, since we mine @@ -3532,116 +3778,149 @@ func assertForceCloseSweeps(ctx context.Context, // transactions, so we count HTLC inputs over all of them. There's // always an extra input that pays for the fees, so we can only count // the remainder of each transaction's inputs as HTLC inputs. - var numSweptHTLCs int - err = wait.NoError(func() error { + countBobSweptHTLCs := func(blocks []*wire.MsgBlock) (int, error) { + minedTxids := make(map[string]struct{}) + for _, tx := range blockTxs(blocks...) { + minedTxids[tx.TxHash().String()] = struct{}{} + } + bobSweeps, err := bob.WalletKitClient.ListSweeps( ctx, &walletrpc.ListSweepsRequest{ Verbose: true, }, ) if err != nil { - return err + return 0, err } - var found bool - numSweptHTLCs = 0 + var numSwept int txns := bobSweeps.GetTransactionDetails().Transactions for _, sweep := range txns { - for _, tx := range timeoutSweeps { - if sweep.TxHash != tx.String() { - continue - } - - txBytes, err := hex.DecodeString( - sweep.RawTxHex, - ) - if err != nil { - return err - } + if _, ok := minedTxids[sweep.TxHash]; !ok { + continue + } - var sweepTx wire.MsgTx - err = sweepTx.Deserialize( - bytes.NewReader(txBytes), - ) - if err != nil { - return err - } + txBytes, err := hex.DecodeString(sweep.RawTxHex) + if err != nil { + return 0, err + } - numSweptHTLCs += len(sweepTx.TxIn) - 1 - found = true + var sweepTx wire.MsgTx + err = sweepTx.Deserialize(bytes.NewReader(txBytes)) + if err != nil { + return 0, err } - } - if !found { - return fmt.Errorf("bob's sweep transaction not found") + numSwept += len(sweepTx.TxIn) - 1 } - return nil - }, ccShortTimeout) - require.NoError(t.t, err) - - // If we didn't yet sweep all HTLCs, then we need to wait for another - // sweep. - if numSweptHTLCs < numTimeoutHTLCs { - // nolint:lll - assertSweepExists( - t.t, bob, - walletrpc.WitnessType_TAPROOT_HTLC_OFFERED_REMOTE_TIMEOUT, - ) - - t.Logf("Confirming additional HTLC timeout sweep txns") + return numSwept, nil + } - _, err := waitForAtLeastNTxsInMempool( + // Mine the HTLC timeout transactions as they show up. Alice's + // pre-signed second-level timeout txs, their anchor sweeps and Bob's + // remote-timeout sweeps reach the mempool on their own schedule, and + // a wallet UTXO selection bug in the sweeper can cause competing + // InputSets to pick the same fee-paying UTXO, so they may not all + // coexist in the mempool. We mine what's available and let the + // sweeper retry on the next tick, until Bob's sweeps have claimed + // every timed out HTLC. + var numSweptHTLCs int + for i := 0; i < 6 && numSweptHTLCs < numTimeoutHTLCs; i++ { + memTxs, _ := waitForAtLeastNTxsInMempool( net.Miner, 1, ccShortTimeout, ) - require.NoError(t.t, err) + timeoutBlocks = append( + timeoutBlocks, mineBlocks(t, net, 1, len(memTxs))..., + ) - // Mine a block to confirm the additional sweeps. - mineBlocks(t, net, 1, 0) + err = wait.NoError(func() error { + numSweptHTLCs, err = countBobSweptHTLCs(timeoutBlocks) + if err != nil { + return err + } + if numSweptHTLCs < numTimeoutHTLCs { + return fmt.Errorf("bob swept %d of %d timed "+ + "out HTLCs", numSweptHTLCs, + numTimeoutHTLCs) + } + + return nil + }, ccShortTimeout) + if err != nil { + t.Logf("Waiting for more of Bob's timeout sweeps: %v", + err) + } } + require.GreaterOrEqual( + t.t, numSweptHTLCs, numTimeoutHTLCs, "Bob's remote-timeout "+ + "sweeps did not claim every timed out HTLC", + ) // At this point, Bob's balance should be incremented by an additional // HTLC value. bobExpectedBalance += uint64(assetInvoiceAmt - 1) - assertSpendableBalance( - t.t, bob, assetID, groupKey, bobExpectedBalance, + timeoutBlocks = append(timeoutBlocks, mineUntilSpendableBalance( + t, net, bob, assetID, groupKey, bobExpectedBalance, + )...) + + // Alice's remaining outgoing HTLC timed out through her pre-signed + // second-level timeout tx: a single input spending the commitment, + // the HTLC output and its CPFP anchor, with the HTLC's timeout as + // locktime. She paid Bob's invoices without splitting them, so there + // is exactly one such HTLC, and its timeout tx has confirmed by now + // or is about to. + const numAliceTimeoutTxs = 1 + var timeoutTxs []*wire.MsgTx + for i := 0; i < 3; i++ { + timeoutTxs = preSignedSecondLevelTxs( + blockTxs(timeoutBlocks...), *closeTxid, true, + ) + if len(timeoutTxs) >= numAliceTimeoutTxs { + break + } + + memTxs, _ := waitForAtLeastNTxsInMempool( + net.Miner, 1, ccShortTimeout, + ) + timeoutBlocks = append( + timeoutBlocks, mineBlocks(t, net, 1, len(memTxs))..., + ) + } + require.Len( + t.t, timeoutTxs, numAliceTimeoutTxs, "expected one "+ + "pre-signed second-level timeout tx for the HTLC "+ + "Alice offered", ) t.Logf("Mining extra blocks for Alice's CSV to expire on 2nd level txn") // Next, we'll mine additional blocks so Alice's CSV delay expires for - // the second level timeout output. - mineBlocks(t, net, closeExpiryInfo.csvDelay, 0) - - // Wait for Alice to extend the second level output to the sweeper - // before we mine the next block to the sweeper. - assertSweepExists( - t.t, alice, - walletrpc.WitnessType_TAPROOT_HTLC_OFFERED_TIMEOUT_SECOND_LEVEL, - ) + // the second level timeout output. The sweeper may already broadcast + // the sweep while these blocks are being mined (the CSV expires one + // block before the last), so these blocks are included in the probe + // set below. + csvBlocks := mineBlocks(t, net, closeExpiryInfo.csvDelay, 0) t.Logf("Confirming Alice's final timeout sweep") - // With the way the sweeper works, we'll now need to mine an extra block - // to trigger the sweep. + // With the way the sweeper works, we'll now need to mine an extra + // block to trigger the sweep. The sweep may need additional block + // ticks to broadcast and confirm; locateSweepAssetTransfer drives + // block production until Alice's transfer for the swept second-level + // timeout output shows up. sweepBlocks = mineBlocks(t, net, 1, 0) + locateSweepAssetTransfer( + t, net, alice, append(csvBlocks, sweepBlocks...), + ) - // If the block mined above didn't also mine our sweep, then we'll mine - // one final block which will confirm Alice's sweep transaction. - if len(sweepBlocks[0].Transactions) == 1 { - _, err := waitForNTxsInMempool( - net.Miner, 1, ccShortTimeout, - ) - require.NoError(t.t, err) - - // We'll mine one final block which will confirm Alice's sweep - // transaction. - sweepBlocks = mineBlocks(t, net, 1, 1) + // Alice has imported the second-level timeout txs themselves as + // well: each anchors the transfer from its commitment HTLC output to + // the second-level output. + for _, timeoutTx := range timeoutTxs { + locateAssetTransfers(t.t, alice, timeoutTx.TxHash()) } - sweepTxHash = sweepBlocks[0].Transactions[1].TxHash() - locateAssetTransfers(t.t, alice, sweepTxHash) - return aliceExpectedBalance, bobExpectedBalance } diff --git a/itest/custom_channels/htlc_force_close_test.go b/itest/custom_channels/htlc_force_close_test.go index 0d24525c71..36235d299b 100644 --- a/itest/custom_channels/htlc_force_close_test.go +++ b/itest/custom_channels/htlc_force_close_test.go @@ -23,7 +23,7 @@ import ( func testCustomChannelsHtlcForceClose(ctx context.Context, net *itest.IntegratedNetworkHarness, t *ccHarnessTest) { - runCustomChannelsHtlcForceClose(ctx, t, net, false) + runCustomChannelsHtlcForceClose(ctx, t, net, false, "") } // testCustomChannelsHtlcForceCloseMpp tests that we can force close a channel @@ -32,15 +32,19 @@ func testCustomChannelsHtlcForceClose(ctx context.Context, func testCustomChannelsHtlcForceCloseMpp(ctx context.Context, net *itest.IntegratedNetworkHarness, t *ccHarnessTest) { - runCustomChannelsHtlcForceClose(ctx, t, net, true) + runCustomChannelsHtlcForceClose(ctx, t, net, true, "") } // runCustomChannelsHtlcForceClose is a helper function that runs the HTLC force // close test with the given MPP setting. +// +// If oldBinary is set, Alice and Bob open the channel and exchange their +// first payments on that older release, and are upgraded to the current +// build before the HTLCs of the main test are added. func runCustomChannelsHtlcForceClose(ctx context.Context, t *ccHarnessTest, - net *itest.IntegratedNetworkHarness, mpp bool) { + net *itest.IntegratedNetworkHarness, mpp bool, oldBinary string) { - t.Logf("Running test with MPP: %v", mpp) + t.Logf("Running test with MPP: %v, old binary: %q", mpp, oldBinary) lndArgs := slices.Clone(lndArgsTemplate) tapdArgs := slices.Clone(tapdArgsTemplate) @@ -55,8 +59,16 @@ func runCustomChannelsHtlcForceClose(ctx context.Context, t *ccHarnessTest, // Next, we'll make Alice and Bob, who will be the main nodes under // test. - alice := net.NewNode("Alice", lndArgs, tapdArgs) - bob := net.NewNode("Bob", lndArgs, tapdArgs) + var alice, bob *itest.IntegratedNode + if oldBinary != "" { + alice = net.NewNodeWithBinary( + "Alice", oldBinary, lndArgs, tapdArgs, + ) + bob = net.NewNodeWithBinary("Bob", oldBinary, lndArgs, tapdArgs) + } else { + alice = net.NewNode("Alice", lndArgs, tapdArgs) + bob = net.NewNode("Bob", lndArgs, tapdArgs) + } // Now we'll connect all nodes, and also fund them with some coins. nodes := []*itest.IntegratedNode{alice, bob} @@ -133,6 +145,34 @@ func runCustomChannelsHtlcForceClose(ctx context.Context, t *ccHarnessTest, logBalance(t.t, nodes, assetID, "after keysends to Bob") + // The channel now has a history of commitments built by the old + // release. Upgrade both peers. From here on they negotiate the + // features of the current build, so the commitments they create next + // follow them, while the ones that exist stay what they were built + // as. A few payments in each direction take the channel across that + // switch, revoking the last commitments of the old release on the + // way. + if oldBinary != "" { + t.Logf("Upgrading Alice and Bob to the current build...") + for _, node := range nodes { + net.UpgradeNode(node) + } + net.EnsureConnected(t.t, alice, bob) + + for i := 0; i < 3; i++ { + sendAssetKeySendPayment( + t.t, alice, bob, keySendAssetAmount, assetID, + fn.None[int64](), + ) + sendAssetKeySendPayment( + t.t, bob, alice, keySendAssetAmount, assetID, + fn.None[int64](), + ) + } + + logBalance(t.t, nodes, assetID, "after upgrade") + } + // Now that both parties have some funds, we'll move onto the main test. // // We'll make 2 hodl invoice for each peer, so 4 total. From Alice's diff --git a/itest/custom_channels/limit_constraints_test.go b/itest/custom_channels/limit_constraints_test.go index 90b78a91a6..86698dab82 100644 --- a/itest/custom_channels/limit_constraints_test.go +++ b/itest/custom_channels/limit_constraints_test.go @@ -394,7 +394,7 @@ func testCustomChannelsLimitConstraints(_ context.Context, TaprootAssetChannelsClient.AddInvoice( ctxb, &tchrpc.AddInvoiceRequest{ AssetId: assetID, - AssetAmount: 1_000_000, + AssetAmount: 2_000_000, PeerPubkey: charlie.PubKey[:], InvoiceRequest: &lnrpc.Invoice{ Expiry: 60, @@ -422,7 +422,7 @@ func testCustomChannelsLimitConstraints(_ context.Context, TaprootAssetChannelsClient.AddInvoice( ctxb, &tchrpc.AddInvoiceRequest{ AssetId: assetID, - AssetAmount: 1_000_000, + AssetAmount: 2_000_000, PeerPubkey: charlie.PubKey[:], InvoiceRequest: &lnrpc.Invoice{ Expiry: 60, @@ -442,12 +442,12 @@ func testCustomChannelsLimitConstraints(_ context.Context, TaprootAssetChannelsClient.AddInvoice( ctxb, &tchrpc.AddInvoiceRequest{ AssetId: assetID, - AssetAmount: 1_000_000, + AssetAmount: 2_000_000, PeerPubkey: charlie.PubKey[:], InvoiceRequest: &lnrpc.Invoice{ Expiry: 60, }, - AssetMinAmt: fn.Ptr[uint64](2_000_000), + AssetMinAmt: fn.Ptr[uint64](3_000_000), }, ) require.ErrorContains(t.t, err, "exceeds max amount") diff --git a/itest/custom_channels/liquidity_test.go b/itest/custom_channels/liquidity_test.go index b50accec1b..eeb08cc6b2 100644 --- a/itest/custom_channels/liquidity_test.go +++ b/itest/custom_channels/liquidity_test.go @@ -336,8 +336,8 @@ func testCustomChannelsLiquidityEdgeCasesCore(ctx context.Context, // Edge case: Now Charlie creates a tiny asset invoice to be paid for by // Yara with satoshi. This is a multi-hop payment going over 2 asset - // channels, where the total asset value is less than the default anchor - // amount of 354 sats. + // channels, where the total asset value is less than the default + // on-chain HTLC amount (rfqmath.DefaultOnChainHtlcSat). createAssetInvoice( t.t, dave, charlie, 1, assetID, withInvoiceErrSubStr( "minimal transportable amount", diff --git a/itest/custom_channels/self_payment_test.go b/itest/custom_channels/self_payment_test.go index a9c2d014ad..925f7ab9b4 100644 --- a/itest/custom_channels/self_payment_test.go +++ b/itest/custom_channels/self_payment_test.go @@ -32,7 +32,6 @@ func testCustomChannelsSelfPayment(_ context.Context, lndArgs := slices.Clone(lndArgsTemplate) tapdArgs := slices.Clone(tapdArgsTemplate) - // We use Alice as the proof courier. But in order for Alice to also // use itself, we need to define its port upfront. alicePort := port.NextAvailablePort() @@ -128,12 +127,22 @@ func testCustomChannelsSelfPayment(_ context.Context, t.Logf("Key sending 15k assets from Alice to Bob...") const ( assetKeySendAmount = 15_000 - numInvoicePayments = 10 + numInvoicePayments = 5 assetInvoiceAmount = 1_234 btcInvoiceAmount = 10_000 btcKeySendAmount = 200_000 btcReserveAmount = 2000 - btcHtlcCost = numInvoicePayments * 354 + + // Bob pays the on-chain carrier value of each asset HTLC he + // sends in the first round (rfqmath.DefaultOnChainHtlcSat). + // He must not be handed more than that: the asset HTLCs + // Alice sends in the second round give the carrier value + // back, and with a surplus Bob's BTC balance in the asset + // channel would grow large enough to forward a BTC payment + // over it. lnd picks randomly among the eligible links to + // a peer, so the BTC leg would no longer be pinned to the + // BTC channel. + btcHtlcCost = numInvoicePayments * 1200 ) sendAssetKeySendPayment( t.t, alice, bob, assetKeySendAmount, assetID, diff --git a/itest/custom_channels/strict_forwarding_test.go b/itest/custom_channels/strict_forwarding_test.go index 2fd5b8bb2b..25ab75bc8c 100644 --- a/itest/custom_channels/strict_forwarding_test.go +++ b/itest/custom_channels/strict_forwarding_test.go @@ -149,7 +149,7 @@ func testCustomChannelsStrictForwarding(_ context.Context, // satoshi, where we will check whether Dave's strict forwarding // works as expected. Charlie is only used as a dummy RFQ peer in this // case, Erin totally ignores the RFQ hint and just pays with sats. - assetInvoice := createAssetInvoice(t.t, charlie, dave, 40, assetID) + assetInvoice := createAssetInvoice(t.t, charlie, dave, 200, assetID) ctx := context.Background() assetInvoiceStream, err := dave.InvoicesClient.SubscribeSingleInvoice( @@ -193,7 +193,7 @@ func testCustomChannelsStrictForwarding(_ context.Context, // Edge case: We now try the opposite: Dave creates a BTC invoice but // Charlie tries to pay it with assets. This should fail as well. - btcInvoice := createNormalInvoice(t.t, dave, 1_000) + btcInvoice := createNormalInvoice(t.t, dave, 5_000) btcInvoiceStream, err := dave.InvoicesClient.SubscribeSingleInvoice( ctx, &invoicesrpc.SubscribeSingleInvoiceRequest{ RHash: btcInvoice.RHash, diff --git a/itest/custom_channels/v1_upgrade_test.go b/itest/custom_channels/v1_upgrade_test.go index eef59e663d..d11ec9e7cf 100644 --- a/itest/custom_channels/v1_upgrade_test.go +++ b/itest/custom_channels/v1_upgrade_test.go @@ -140,7 +140,7 @@ func testCustomChannelsV1Upgrade(ctx context.Context, sendAssetKeySendPayment( t.t, charlie, dave, 50, assetID, fn.None[int64](), ) - sendKeySendPayment(t.t, charlie, dave, 1_000) + sendKeySendPayment(t.t, charlie, dave, 10_000) } logBalance(t.t, nodes, assetID, "before upgrade") @@ -271,7 +271,7 @@ func testCustomChannelsV1Upgrade(ctx context.Context, // With the breach transaction mined, Dave should now have a // transaction in the mempool sweeping *both* commitment outputs. - daveJusticeTxid, err := waitForNTxsInMempool( + daveJusticeTxid, err := waitForAtLeastNTxsInMempool( net.Miner, 1, time.Second*5, ) require.NoError(t.t, err) diff --git a/itest/custom_channels/vars.go b/itest/custom_channels/vars.go index dc4fb8b15e..c5ae604495 100644 --- a/itest/custom_channels/vars.go +++ b/itest/custom_channels/vars.go @@ -120,7 +120,7 @@ const ( // DefaultPushSat is the default push amount in satoshis when opening // custom channels. - DefaultPushSat int64 = 1062 + DefaultPushSat int64 = 6372 // assetBurnConfirmationText is the text that needs to be set on the // RPC to confirm an asset burn. diff --git a/itest/integrated_harness.go b/itest/integrated_harness.go index 68d73a06f2..28ce704bb0 100644 --- a/itest/integrated_harness.go +++ b/itest/integrated_harness.go @@ -760,6 +760,25 @@ func (h *IntegratedNetworkHarness) StopAndRestoreDB( return nil } +// SuspendNode stops the given node without cleaning it up. It returns a +// closure that can be called to restart the node. +func (h *IntegratedNetworkHarness) SuspendNode( + node *IntegratedNode) (func(), error) { + + node.Stop() + + restart := func() { + // Remove the ready file so Start() waits for the new + // instance. + if node.readyFile != "" { + _ = os.Remove(node.readyFile) + } + node.Start() + } + + return restart, nil +} + // copyAll recursively copies all files and directories from srcDir to dstDir. func copyAll(dstDir, srcDir string) error { entries, err := os.ReadDir(srcDir) diff --git a/itest/rfq_test.go b/itest/rfq_test.go index db79bcd646..f7e50d8cec 100644 --- a/itest/rfq_test.go +++ b/itest/rfq_test.go @@ -533,9 +533,12 @@ func testRfqAssetSellHtlcIntercept(t *harnessTest) { expectedAssetID := mintedAssetIdBytes require.Equal(t.t, expectedAssetID, actualAssetID) // The original 42000-msat quote is below the real asset channel's - // 354000-msat HTLC dust threshold. Preserve that negotiation, then - // negotiate a second quote large enough for an actual asset HTLC. - const paymentAskAmt = uint64(420_000) + // HTLC dust threshold. Preserve that negotiation, then negotiate a + // second quote large enough for an actual asset HTLC. With + // deterministic HTLCs the threshold also covers the pre-signed + // second-level fee and its anchor, so we use the on-chain carrier + // value asset HTLCs normally get. + paymentAskAmt := uint64(rfqmath.DefaultOnChainHtlcMSat) oracle.On( "QueryAssetRates", oraclerpc.TransactionType_SALE, buySpecifier, mock.Anything, btcSpecifier, @@ -739,7 +742,6 @@ func testRfqAssetSellHtlcIntercept(t *harnessTest) { // Close event notification streams. require.NoError(t.t, aliceEventNtfns.CloseSend()) require.NoError(t.t, bobEventNtfns.CloseSend()) - } // testRfqNegotiationGroupKey checks that two nodes can negotiate and register diff --git a/lndservices/wallet_anchor.go b/lndservices/wallet_anchor.go index b7830f70ce..55db09aa80 100644 --- a/lndservices/wallet_anchor.go +++ b/lndservices/wallet_anchor.go @@ -28,6 +28,17 @@ import ( // useful in high fee environments where we'd otherwise fail to fund the psbt. const DefaultPsbtMaxFeeRatio = 0.75 +// MaxPsbtMaxFeeRatio is the hard ceiling for the configurable +// psbt-max-fee-ratio. Values above 1.0 are valid: spending tiny asset-bearing +// UTXOs (e.g. post-sweep outputs near dust) can produce txs where the fee is +// several times the total output BTC value. They are only accepted by lnd +// versions whose FundPsbt allows a fee ratio above 1.0 though, which is why +// the default stays below it. The ceiling matches the one of such an lnd: any +// larger value would be rejected on every funding attempt, and a fat-fingered +// config value (e.g. 50 instead of 5.0) would otherwise silently authorize +// burning many times the output value in fees. +const MaxPsbtMaxFeeRatio = 5.0 + // LndRpcWalletAnchor is an implementation of the tapnode.WalletAnchor // interfaced backed by an active remote lnd node. type LndRpcWalletAnchor struct { diff --git a/rfq/manager_test.go b/rfq/manager_test.go index 9967fdb854..7c0743f772 100644 --- a/rfq/manager_test.go +++ b/rfq/manager_test.go @@ -465,7 +465,7 @@ func createChannelWithCustomData(t *testing.T, id asset.ID, localBalance, ), }, nil, nil, lnwallet.CommitAuxLeaves{}, - false, false, + false, false, tpchmsg.SigHashAll, ), OpenChan: *tpchmsg.NewOpenChannel( []*tpchmsg.AssetOutput{ diff --git a/rfq/order.go b/rfq/order.go index d34cb7ed3d..7194e7d7d2 100644 --- a/rfq/order.go +++ b/rfq/order.go @@ -539,7 +539,16 @@ func (c *AssetSalePolicy) GenerateInterceptorResponse( htlc lndclient.InterceptedHtlc) (*lndclient.InterceptedHtlcResponse, error) { - outgoingAmt := rfqmath.DefaultOnChainHtlcMSat + // The on-chain BTC amount the outgoing HTLC carries: the + // deterministic-HTLC carrier value when the peer negotiated + // DeterministicHTLCs, the legacy just-above-dust value otherwise. + outgoingAmt := rfqmath.LegacyOnChainHtlcMSat + if c.auxChanNegotiator != nil { + features := c.auxChanNegotiator.GetPeerFeatures(c.peer) + if features.HasFeature(tapfeatures.DeterministicHTLCsOptional) { + outgoingAmt = rfqmath.DefaultOnChainHtlcMSat + } + } var assetID asset.ID diff --git a/rfqmath/convert.go b/rfqmath/convert.go index 52cf2b0091..3925c6f420 100644 --- a/rfqmath/convert.go +++ b/rfqmath/convert.go @@ -16,18 +16,70 @@ import ( var ErrMsatOverflow = errors.New("rfqmath: mSat amount exceeds uint64") var ( - // DefaultOnChainHtlcSat is the default amount that we consider as the - // smallest HTLC amount that can be sent on-chain. This needs to be - // greater than the dust limit for an HTLC. - DefaultOnChainHtlcSat = lnwallet.DustLimitForSize( - input.UnknownWitnessSize, - ) + // DefaultOnChainHtlcSat is the default amount that we consider as + // the smallest HTLC amount that can be sent on-chain. Under + // DeterministicHTLCs the on-chain value of an HTLC is split three + // ways by the pre-signed second-level tx: + // + // 1. Its baked-in fee, which lnd sets to 1.1x the relay floor + // (chainfee.FeePerKwFloor) over the second-level weight + // including the anchor output: ~227 sats for the timeout + // variant, ~243 sats for the success variant. The fee cannot + // be changed later, since the peer's signature commits to the + // whole transaction. + // + // 2. A 330-sat (lnwallet.AnchorSize) CPFP anchor output, which is + // how the transaction gets fee-bumped: the sweeper spends it + // with a wallet-funded child. + // + // 3. The remaining second-level HTLC output, which must clear the + // 354-sat dust limit AND still be able to fund the sweep that + // finally claims it (the CSV sweep, or the justice sweep after + // a breach), which needs sweepAnchorOutputAmt on its own + // output. + // + // That puts the strict minimum at ~930 sats (243 + 330 + 354). 1200 + // sats keeps headroom for point 3 and rounds the user-facing minimum + // to a clean value. Replaces the prior 6x-the-dust-limit multiplier; + // the anchor (rather than fee headroom on the HTLC itself) handles + // fee bumping under DeterministicHTLCs. + // + // TODO(GeorgeTsagk): revisit this once package relay is available. + // Both deductions above exist only because the pre-signed parent has + // to be independently relayable today, and that is also why it is + // pinned to a mere 1.1x the relay floor (~1.11 sat/vB): a parent the + // mempool rejects cannot be CPFP'd by its own anchor, so it becomes + // unrelayable whenever the dynamic mempool minimum climbs above that + // (i.e. any time the mempool is full and evicting above ~1 sat/vB). + // Submitting the parent together with its fee-paying child via + // package relay removes both constraints at once: the package feerate + // is what gets evaluated, so the parent no longer needs its own fee, + // and with a TRUC/v3 parent the anchor can be a 0-value P2A output. + // Deduction 1 and 2 then go to zero, and this constant can drop to + // roughly what point 3 alone requires (~600 sats), which also lowers + // the minimum asset payment we quote over RFQ. + DefaultOnChainHtlcSat = btcutil.Amount(1200) // DefaultOnChainHtlcMSat is the default amount that we consider as the // smallest HTLC amount that can be sent on-chain in milli-satoshis. DefaultOnChainHtlcMSat = lnwire.NewMSatFromSatoshis( DefaultOnChainHtlcSat, ) + + // LegacyOnChainHtlcSat is the on-chain BTC amount an asset HTLC + // carries on channels that did NOT negotiate DeterministicHTLCs: + // just above the dust limit, since none of the deductions the + // deterministic carrier value pays for exist there. Using the + // larger deterministic value for such channels would needlessly + // raise the minimum quotable payment. + LegacyOnChainHtlcSat = lnwallet.DustLimitForSize( + input.UnknownWitnessSize, + ) + + // LegacyOnChainHtlcMSat is LegacyOnChainHtlcSat in milli-satoshis. + LegacyOnChainHtlcMSat = lnwire.NewMSatFromSatoshis( + LegacyOnChainHtlcSat, + ) ) // defaultArithmeticScale is the default scale used for arithmetic operations. diff --git a/rfqmath/convert_test.go b/rfqmath/convert_test.go index 953b746a34..923d577743 100644 --- a/rfqmath/convert_test.go +++ b/rfqmath/convert_test.go @@ -391,7 +391,7 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { }, expectedUnits: 1, expectedMinTransportUnits: 1, - expectedMinTransportMSat: 20_354_000, + expectedMinTransportMSat: 21_200_000, }, { // 5k USD per BTC @ decimal display 6. @@ -402,7 +402,7 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { }.ScaleTo(6), expectedUnits: 10_000, expectedMinTransportUnits: 1, - expectedMinTransportMSat: 20_354_000, + expectedMinTransportMSat: 21_200_000, }, { // 50k USD per BTC @ decimal display 6. @@ -413,7 +413,7 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { }.ScaleTo(6), expectedUnits: 1000, expectedMinTransportUnits: 1, - expectedMinTransportMSat: 2_326_308, + expectedMinTransportMSat: 3_172_308, }, { // 50M USD per BTC @ decimal display 6. @@ -423,8 +423,8 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { Scale: 2, }.ScaleTo(6), expectedUnits: 62595061158, - expectedMinTransportUnits: 179, - expectedMinTransportMSat: 355_972, + expectedMinTransportUnits: 608, + expectedMinTransportMSat: 1_201_972, }, { // 50k USD per BTC @ decimal display 6. @@ -435,7 +435,7 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { }.ScaleTo(6), expectedUnits: 2_570, expectedMinTransportUnits: 1, - expectedMinTransportMSat: 2_326_304, + expectedMinTransportMSat: 3_172_304, }, { // 7.341M JPY per BTC @ decimal display 6. @@ -445,8 +445,8 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { Scale: 0, }.ScaleTo(6), expectedUnits: 367_092, - expectedMinTransportUnits: 25, - expectedMinTransportMSat: 367_620, + expectedMinTransportUnits: 88, + expectedMinTransportMSat: 1_213_620, }, { // 7.341M JPY per BTC @ decimal display 2. @@ -456,8 +456,8 @@ func TestConvertMilliSatoshiToUnits(t *testing.T) { Scale: 0, }.ScaleTo(4), expectedUnits: 3_670, - expectedMinTransportUnits: 25, - expectedMinTransportMSat: 367_620, + expectedMinTransportUnits: 88, + expectedMinTransportMSat: 1_213_620, }, } diff --git a/sample-tapd.conf b/sample-tapd.conf index bbb8a75837..045a02298d 100644 --- a/sample-tapd.conf +++ b/sample-tapd.conf @@ -449,7 +449,10 @@ [wallet] ; The maximum ratio of fees to total output amount for the wallet funded PSBTs. -; Value must be a valid float ranging from 0.00 to 1.00. +; Value must be a valid float greater than 0.00 and at most 5.00. Values above +; 1.00 are valid because spending small asset-bearing UTXOs can cost more in +; fees than their BTC value, but need an lnd version whose FundPsbt accepts a +; fee ratio above 1.00. ; wallet.psbt-max-fee-ratio=0.75 ; Disable sweeping orphaned UTXOs into send and burn anchor transactions. diff --git a/server.go b/server.go index 8cb01dce7a..c3f8c52982 100644 --- a/server.go +++ b/server.go @@ -1,6 +1,7 @@ package taprootassets import ( + "bytes" "context" "fmt" "net/http" @@ -12,6 +13,7 @@ import ( "github.com/btcsuite/btcd/btcutil/v2" "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" proxy "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/lightninglabs/lndclient" @@ -27,6 +29,7 @@ import ( "github.com/lightninglabs/taproot-assets/tapchannel" cmsg "github.com/lightninglabs/taproot-assets/tapchannelmsg" "github.com/lightninglabs/taproot-assets/tapconfig" + "github.com/lightninglabs/taproot-assets/tapfeatures" "github.com/lightninglabs/taproot-assets/taprpc" "github.com/lightningnetwork/lnd/build" "github.com/lightningnetwork/lnd/channeldb" @@ -1078,20 +1081,20 @@ func (s *Server) FetchLeavesFromCommit(chanState lnwl.AuxChanState, // // NOTE: This method is part of the lnwallet.AuxLeafStore interface. func (s *Server) FetchLeavesFromRevocation( - r *channeldb.RevocationLog) lfn.Result[lnwl.CommitDiffAuxResult] { + req lnwl.RevocationLeavesReq) lfn.Result[lnwl.CommitDiffAuxResult] { srvrLog.Debugf("FetchLeavesFromRevocation called, ourBalance=%v, "+ - "teirBalance=%v, numHtlcs=%d", r.OurBalance, r.TheirBalance, - len(r.HTLCEntries)) + "teirBalance=%v, numHtlcs=%d", req.Revocation.OurBalance, + req.Revocation.TheirBalance, len(req.Revocation.HTLCEntries)) // Record the HTLC set of this revoked commitment, so the aux // sweeper can derive exclusion proofs for plain BTC-only HTLC // outputs when importing the revoked commitment transaction. - tapchannel.StashRevokedHtlcs(s.htlcStash, r) + tapchannel.StashRevokedHtlcs(s.htlcStash, req.Revocation) // The aux leaf creator is fully stateless, and we don't need to wait // for the server to be started before being able to use it. - return tapchannel.FetchLeavesFromRevocation(r) + return tapchannel.FetchLeavesFromRevocation(req, s.chainParams) } // ApplyHtlcView serves as the state transition function for the custom @@ -1237,6 +1240,80 @@ func (s *Server) VerifySecondLevelSigs(chanState lnwl.AuxChanState, ) } +// HtlcSigHashType returns the sighash type to use for HTLC second-level +// transactions for the given channel. The request carries either a ChanID +// (for live feature-negotiation lookups on new commitments) or a CommitBlob +// (for existing commitments), or both. +// +// When a ChanID is present and the server is configured, the live negotiated +// features are checked first. The CommitBlob is used as a fallback (or as +// the sole source when no ChanID is provided). +// +// NOTE: This method is part of the lnwallet.AuxSigner interface. +func (s *Server) HtlcSigHashType( + req lnwl.HtlcSigHashReq) lfn.Option[txscript.SigHashType] { + + // If a ChanID was provided and the server is fully configured, + // check live feature negotiation state first. + if req.ChanID.IsSome() && s != nil && s.cfg != nil && + s.cfg.AuxChanNegotiator != nil { + + chanID := req.ChanID.UnwrapOr(lnwire.ChannelID{}) + + features := s.cfg.AuxChanNegotiator.GetChannelFeatures( + chanID, + ) + + hasSigHashDefault := features.HasFeature( + tapfeatures.DeterministicHTLCsOptional, + ) + + srvrLog.Debugf("HtlcSigHashType called for "+ + "chan_id=%x, "+ + "deterministic_htlcs_negotiated=%v", + chanID[:], hasSigHashDefault) + + if hasSigHashDefault { + return lfn.Some(txscript.SigHashDefault) + } + } + + // Fall back to the commitment blob cache. + return s.htlcSigHashFromBlob(req.CommitBlob) +} + +// htlcSigHashFromBlob decodes the commitment blob and checks the cached +// SigHashDefault flag. This is used for existing commitments (breach, +// resolution) where the blob is the source of truth, and as a fallback +// during startup when the peer hasn't reconnected yet. +func (s *Server) htlcSigHashFromBlob( + commitBlob lfn.Option[tlv.Blob]) lfn.Option[txscript.SigHashType] { + + blob, err := commitBlob.UnwrapOrErr( + fmt.Errorf("no commit blob"), + ) + if err != nil { + return lfn.None[txscript.SigHashType]() + } + + var c cmsg.Commitment + if decErr := c.Decode(bytes.NewReader(blob)); decErr != nil { + srvrLog.Errorf("HtlcSigHashType: unable to decode "+ + "commit blob (%d bytes): %v", len(blob), decErr) + + return lfn.None[txscript.SigHashType]() + } + + if c.SigHashDefault.Val { + srvrLog.Debugf("HtlcSigHashType: using cached " + + "SigHashDefault from commit blob") + + return lfn.Some(txscript.SigHashDefault) + } + + return lfn.None[txscript.SigHashType]() +} + // DescFromPendingChanID takes a pending channel ID, that may already be // known due to prior custom channel messages, and maybe returns an aux // funding desc which can be used to modify how a channel is funded. @@ -1542,24 +1619,25 @@ func (s *Server) ExtraBudgetForInputs( return tapchannel.ExtraBudgetForInputs(inputs) } -// NotifyBroadcast is used to notify external callers of the broadcast of a -// sweep transaction, generated by the passed BumpRequest. +// NotifyBroadcast is called by lnd's sweeper to notify us of a sweep +// transaction broadcast, generated by the passed BumpRequest. // // NOTE: This method is part of the sweep.AuxSweeper interface. func (s *Server) NotifyBroadcast(req *sweep.BumpRequest, tx *wire.MsgTx, fee btcutil.Amount, - outpointToTxIndex map[wire.OutPoint]int) error { + outpointToTxIndex map[wire.OutPoint]int, + opts sweep.AuxNotifyOpts) error { - srvrLog.Tracef("NotifyBroadcast called, req=%v, tx=%v, fee=%v, "+ - "out_index=%v", lnutils.SpewLogClosure(req), - lnutils.SpewLogClosure(tx), fee, - lnutils.SpewLogClosure(outpointToTxIndex)) + srvrLog.Infof("NotifyBroadcast called, skip_broadcast=%v, tx=%v, "+ + "fee=%v", opts.SkipBroadcast, tx.TxHash(), fee) if err := s.waitForReady(); err != nil { return err } - return s.cfg.AuxSweeper.NotifyBroadcast(req, tx, fee, outpointToTxIndex) + return s.cfg.AuxSweeper.NotifyBroadcast( + req, tx, fee, outpointToTxIndex, opts, + ) } // GetInitRecords is called when sending an init message to a peer. It returns diff --git a/tapcfg/config.go b/tapcfg/config.go index 75137d6910..92102e1b7d 100644 --- a/tapcfg/config.go +++ b/tapcfg/config.go @@ -324,8 +324,10 @@ type WalletConfig struct { // be anchored to outpoints that may carry relatively small bitcoin // amounts it is useful to pick a high value for this argument as in // high fee environments the total fees paid may outweigh the anchor - // amount. The allowed values for this argument range from 0.00 to 1.00. - PsbtMaxFeeRatio float64 `long:"psbt-max-fee-ratio" description:"The maximum fees to total output amount ratio to use when funding PSBTs for asset transfers. Value must be between 0.00 and 1.00"` + // amount. The value must be greater than 0.00. Values above 1.00 are + // allowed and are useful when spending tiny asset-bearing UTXOs, but + // need an lnd version whose FundPsbt accepts them. + PsbtMaxFeeRatio float64 `long:"psbt-max-fee-ratio" description:"The maximum fees to total output amount ratio to use when funding PSBTs for asset transfers. Value must be greater than 0.00 and at most 5.00. Values above 1.00 need an lnd version whose FundPsbt accepts them."` // DisableSweepOrphanUtxos, when true, disables sweeping of orphaned // UTXOs into anchor transactions created during sends and burns. @@ -1118,14 +1120,19 @@ func ValidateConfig(cfg Config, cfgLogger btclog.Logger) (*Config, error) { return nil, err } - // Let's validate that the wallet's psbt max fee ratio is within the - // expected range. - switch { - case cfg.Wallet.PsbtMaxFeeRatio < 0.00: - fallthrough - case cfg.Wallet.PsbtMaxFeeRatio > 1.00: - return nil, fmt.Errorf("psbt-max-fee-ratio must be set in " + - "range of 0.00 to 1.00") + // Let's validate that the wallet's psbt max fee ratio is positive and + // within the allowed ceiling. Values above 1.0 are allowed: spending + // tiny asset-bearing UTXOs (e.g. post-sweep outputs near dust) can + // legitimately produce txs where the fee is several times the total + // output BTC value. The ceiling matches lnd's FundPsbt sanity check: + // a larger value would be rejected by lnd on every funding attempt + // anyway, and the bound catches order-of-magnitude typos. + if cfg.Wallet.PsbtMaxFeeRatio <= 0.00 || + cfg.Wallet.PsbtMaxFeeRatio > + lndservices.MaxPsbtMaxFeeRatio { + + return nil, fmt.Errorf("psbt-max-fee-ratio must be between "+ + "0.00 and %.2f", lndservices.MaxPsbtMaxFeeRatio) } // Validate the healthcheck config. diff --git a/tapchannel/auf_leaf_signer_test.go b/tapchannel/auf_leaf_signer_test.go index 89fbe58345..4a54780361 100644 --- a/tapchannel/auf_leaf_signer_test.go +++ b/tapchannel/auf_leaf_signer_test.go @@ -113,7 +113,7 @@ func setupAuxLeafSigner(t *testing.T, numJobs int32) (*AuxLeafSigner, com := cmsg.NewCommitment( nil, nil, outgoingHtlcs, nil, lnwallet.CommitAuxLeaves{}, false, - false, + false, cmsg.SigHashAll, ) cancelChan := make(chan struct{}) diff --git a/tapchannel/aux_funding_controller.go b/tapchannel/aux_funding_controller.go index 11b488ff9a..2ddee29937 100644 --- a/tapchannel/aux_funding_controller.go +++ b/tapchannel/aux_funding_controller.go @@ -520,6 +520,8 @@ type pendingAssetFunding struct { stxoFeatures STXOFeatures + sigHashDefault bool + amt uint64 pushAmt btcutil.Amount @@ -738,8 +740,8 @@ func newCommitBlobAndLeaves(pendingFunding *pendingAssetFunding, lndOpenChan lnwallet.AuxChanState, assetOpenChan *cmsg.OpenChannel, keyRing lntypes.Dual[lnwallet.CommitmentKeyRing], whoseCommit lntypes.ChannelParty, - stxoFeatures STXOFeatures) ([]byte, lnwallet.CommitAuxLeaves, - error) { + stxoFeatures STXOFeatures, sigHashDefault bool) ([]byte, + lnwallet.CommitAuxLeaves, error) { chanAssets := assetOpenChan.FundedAssets.Val.Outputs @@ -802,7 +804,7 @@ func newCommitBlobAndLeaves(pendingFunding *pendingAssetFunding, // needs the sum of the remote+local assets, so we'll populate that. fakePrevState := cmsg.NewCommitment( localAssets, remoteAssets, nil, nil, lnwallet.CommitAuxLeaves{}, - stxoFeatures.STXO, stxoFeatures.Spender, + stxoFeatures.STXO, stxoFeatures.Spender, cmsg.SigHashAll, ) // Just like above, we don't have a real HTLC view here, so we'll pass @@ -815,7 +817,7 @@ func newCommitBlobAndLeaves(pendingFunding *pendingAssetFunding, fakePrevState, lndOpenChan, assetOpenChan, whoseCommit, localSatBalance, remoteSatBalance, fakeView, pendingFunding.chainParams, keyRing.GetForParty(whoseCommit), - stxoFeatures, + stxoFeatures, sigHashDefault, ) if err != nil { return nil, lnwallet.CommitAuxLeaves{}, err @@ -858,14 +860,14 @@ func (p *pendingAssetFunding) toAuxFundingDesc(req *bindFundingReq, // This will be the information for the very first state (state 0). localCommitBlob, localAuxLeaves, err := newCommitBlobAndLeaves( p, req.openChan, openChanDesc, req.keyRing, lntypes.Local, - p.stxoFeatures, + p.stxoFeatures, p.sigHashDefault, ) if err != nil { return nil, err } remoteCommitBlob, remoteAuxLeaves, err := newCommitBlobAndLeaves( p, req.openChan, openChanDesc, req.keyRing, lntypes.Remote, - p.stxoFeatures, + p.stxoFeatures, p.sigHashDefault, ) if err != nil { return nil, err @@ -2175,6 +2177,9 @@ func (f *FundingController) processFundingReq(fundingFlows fundingFlowIndex, stxoFeatures := NewSTXOFeatures(features) fundingState.stxoFeatures = stxoFeatures + fundingState.sigHashDefault = features.HasFeature( + tapfeatures.DeterministicHTLCsOptional, + ) // Now that we know the final funding asset root along with the splits, // we can derive the tapscript root that'll be used alongside the diff --git a/tapchannel/aux_leaf_creator.go b/tapchannel/aux_leaf_creator.go index 7daea43688..d52cb2b810 100644 --- a/tapchannel/aux_leaf_creator.go +++ b/tapchannel/aux_leaf_creator.go @@ -66,12 +66,25 @@ func FetchLeavesFromView(chainParams *address.ChainParams, ), ) - stxoFeatures := NewSTXOFeatures(features) + // The live feature map is only populated once the peer has + // (re)connected. Around a restart it can be empty, so the STXO + // features fall back to the flags cached in the previous commitment. + stxoFeatures := NewSTXOFeatures(features).Or( + CommitmentSTXOFeatures(prevState), + ) + + // The sighash mode of the commitment is not ours to derive. Whoever + // signs a commitment decides its mode and states it on the + // commitment_signed, which can be retransmitted in a later connection + // with different features negotiated. lnd hands us the mode of the + // commitment being built, for the ones it signs and the ones it + // verifies alike, so both peers build the same second-level layout. + sigHashDefault := in.SigHashDefault allocations, newCommitment, err := GenerateCommitmentAllocations( prevState, in.ChannelState, chanAssetState, in.WhoseCommit, in.OurBalance, in.TheirBalance, in.UnfilteredView, chainParams, - in.KeyRing, stxoFeatures, + in.KeyRing, stxoFeatures, sigHashDefault, ) if err != nil { return lfn.Err[returnType](fmt.Errorf("unable to generate "+ @@ -118,6 +131,7 @@ func FetchLeavesFromCommit(chainParams *address.ChainParams, stxoFeatures := CommitmentSTXOFeatures(commitment) warnMissingSpenderLeaves(chanState.FundingOutpoint, stxoFeatures) + sigHashDefault := commitment.SigHashDefault.Val incomingHtlcs := commitment.IncomingHtlcAssets.Val.HtlcOutputs incomingHtlcLeaves := commitment.AuxLeaves.Val.IncomingHtlcLeaves. @@ -150,7 +164,7 @@ func FetchLeavesFromCommit(chainParams *address.ChainParams, leaf, err := CreateSecondLevelHtlcTx( chanState, com.CommitTx, htlc.Amt.ToSatoshis(), keys, chainParams, htlcOutputs, cltvTimeout, - htlc.HtlcIndex, stxoFeatures, + htlc.HtlcIndex, stxoFeatures, sigHashDefault, ) if err != nil { return lfn.Err[returnType](fmt.Errorf("unable "+ @@ -191,7 +205,7 @@ func FetchLeavesFromCommit(chainParams *address.ChainParams, leaf, err := CreateSecondLevelHtlcTx( chanState, com.CommitTx, htlc.Amt.ToSatoshis(), keys, chainParams, htlcOutputs, cltvTimeout, - htlc.HtlcIndex, stxoFeatures, + htlc.HtlcIndex, stxoFeatures, sigHashDefault, ) if err != nil { return lfn.Err[returnType](fmt.Errorf("unable "+ @@ -221,13 +235,17 @@ func FetchLeavesFromCommit(chainParams *address.ChainParams, // FetchLeavesFromRevocation attempts to fetch the auxiliary leaves // from a channel revocation that stores balance + blob information. -func FetchLeavesFromRevocation( - r *channeldb.RevocationLog) lfn.Result[lnwl.CommitDiffAuxResult] { +// The req carries the chanState, keys, and commitTx needed to compute +// second-level HTLC auxiliary leaves at runtime, since these are not +// stored in the commitment blob. chainParams is passed alongside since +// it is a server-level concern, not part of the lnwallet request. +func FetchLeavesFromRevocation(req lnwl.RevocationLeavesReq, + chainParams *address.ChainParams) lfn.Result[lnwl.CommitDiffAuxResult] { type returnType = lnwl.CommitDiffAuxResult return lfn.MapOptionZ( - r.CustomBlob.ValOpt(), + req.Revocation.CustomBlob.ValOpt(), func(blob tlv.Blob) lfn.Result[lnwl.CommitDiffAuxResult] { commitment, err := cmsg.DecodeCommitment(blob) if err != nil { @@ -235,13 +253,139 @@ func FetchLeavesFromRevocation( "to decode commitment: %w", err)) } + leaves := commitment.Leaves() + + // If we have the commit tx and chain params, we + // can compute the second-level HTLC aux leaves + // that aren't stored in the commitment blob. + if req.CommitTx != nil && chainParams != nil { + err = populateSecondLevelLeaves( + req.Revocation, commitment, + req.ChanState, req.Keys, req.CommitTx, + chainParams, &leaves, + ) + if err != nil { + return lfn.Err[returnType]( + fmt.Errorf("unable to "+ + "populate second "+ + "level leaves: %w", + err), + ) + } + } + return lfn.Ok(lnwl.CommitDiffAuxResult{ - AuxLeaves: lfn.Some(commitment.Leaves()), + AuxLeaves: lfn.Some(leaves), }) }, ) } +// populateSecondLevelLeaves computes the second-level HTLC aux leaves +// for each HTLC in the revocation log and populates them in the given +// leaves struct. This mirrors the logic in FetchLeavesFromCommit. +func populateSecondLevelLeaves(r *channeldb.RevocationLog, + commitment *cmsg.Commitment, chanState lnwl.AuxChanState, + keys lnwl.CommitmentKeyRing, commitTx *wire.MsgTx, + chainParams *address.ChainParams, + leaves *lnwl.CommitAuxLeaves) error { + + stxoFeatures := CommitmentSTXOFeatures(commitment) + sigHashDefault := commitment.SigHashDefault.Val + + incomingHtlcs := commitment.IncomingHtlcAssets.Val.HtlcOutputs + incomingHtlcLeaves := commitment.AuxLeaves.Val. + IncomingHtlcLeaves.Val.HtlcAuxLeaves + outgoingHtlcs := commitment.OutgoingHtlcAssets.Val.HtlcOutputs + outgoingHtlcLeaves := commitment.AuxLeaves.Val. + OutgoingHtlcLeaves.Val.HtlcAuxLeaves + + for _, htlcEntry := range r.HTLCEntries { + // Skip HTLCs without an index. + htlcIdxOpt := htlcEntry.HtlcIndex.ValOpt() + if htlcIdxOpt.IsNone() { + continue + } + + htlcIdx := htlcIdxOpt.UnsafeFromSome().Int() + htlcAmt := htlcEntry.Amt.Val.Int() + + if htlcEntry.Incoming.Val { + htlcOutputs := incomingHtlcs[htlcIdx].Outputs + auxLeaf := incomingHtlcLeaves[htlcIdx].AuxLeaf + + if len(htlcOutputs) == 0 { + continue + } + + // For incoming HTLCs on the remote party's + // commitment, they'll need to go to the second + // level to time it out. + cltvTimeout := fn.Some( + htlcEntry.RefundTimeout.Val, + ) + + leaf, err := CreateSecondLevelHtlcTx( + chanState, commitTx, htlcAmt, + keys, chainParams, htlcOutputs, + cltvTimeout, htlcIdx, stxoFeatures, + sigHashDefault, + ) + if err != nil { + return fmt.Errorf("unable to create "+ + "second level incoming HTLC "+ + "leaf: %w", err) + } + + existingLeaf := lfn.MapOption( + func(l cmsg.TapLeafRecord) txscript.TapLeaf { + return l.Leaf + }, + )(auxLeaf.ValOpt()) + + leaves.IncomingHtlcLeaves[htlcIdx] = input.HtlcAuxLeaf{ + AuxTapLeaf: existingLeaf, + SecondLevelLeaf: leaf, + } + } else { + htlcOutputs := outgoingHtlcs[htlcIdx].Outputs + auxLeaf := outgoingHtlcLeaves[htlcIdx].AuxLeaf + + if len(htlcOutputs) == 0 { + continue + } + + // For outgoing HTLCs on the remote party's + // commitment, they don't need a CLTV timeout + // (they go to second level via the success path). + leaf, err := CreateSecondLevelHtlcTx( + chanState, commitTx, htlcAmt, + keys, chainParams, htlcOutputs, + fn.None[uint32](), htlcIdx, + stxoFeatures, sigHashDefault, + ) + if err != nil { + return fmt.Errorf("unable to create "+ + "second level outgoing HTLC "+ + "leaf: %w", err) + } + + existingLeaf := lfn.MapOption( + func(l cmsg.TapLeafRecord) txscript.TapLeaf { + return l.Leaf + }, + )(auxLeaf.ValOpt()) + + leaves.OutgoingHtlcLeaves[htlcIdx] = input.HtlcAuxLeaf{ + AuxTapLeaf: existingLeaf, + SecondLevelLeaf: leaf, + } + } + } + + return nil +} + // ApplyHtlcView serves as the state transition function for the custom // channel's blob. Given the old blob, and an HTLC view, then a new // blob should be returned that reflects the pending updates. @@ -276,12 +420,18 @@ func ApplyHtlcView(chainParams *address.ChainParams, ), ) - stxoFeatures := NewSTXOFeatures(features) + // Same as above: the STXO features fall back to the previous + // commitment, the sighash mode is the one lnd states for the + // commitment being built and is recorded in the new blob. + stxoFeatures := NewSTXOFeatures(features).Or( + CommitmentSTXOFeatures(prevState), + ) + sigHashDefault := in.SigHashDefault _, newCommitment, err := GenerateCommitmentAllocations( prevState, in.ChannelState, chanAssetState, in.WhoseCommit, in.OurBalance, in.TheirBalance, in.UnfilteredView, chainParams, - in.KeyRing, stxoFeatures, + in.KeyRing, stxoFeatures, sigHashDefault, ) if err != nil { return lfn.Err[returnType](fmt.Errorf("unable to generate "+ diff --git a/tapchannel/aux_leaf_creator_test.go b/tapchannel/aux_leaf_creator_test.go new file mode 100644 index 0000000000..6d118ae48a --- /dev/null +++ b/tapchannel/aux_leaf_creator_test.go @@ -0,0 +1,293 @@ +package tapchannel + +import ( + "fmt" + "testing" + + "github.com/btcsuite/btcd/btcutil/v2" + "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/fn" + "github.com/lightninglabs/taproot-assets/internal/test" + "github.com/lightninglabs/taproot-assets/internal/test/lndmock" + "github.com/lightninglabs/taproot-assets/rfqmath" + "github.com/lightninglabs/taproot-assets/rfqmsg" + cmsg "github.com/lightninglabs/taproot-assets/tapchannelmsg" + "github.com/lightninglabs/taproot-assets/tapfeatures" + "github.com/lightningnetwork/lnd/channeldb" + lfn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/lntypes" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwallet/chainfee" + "github.com/lightningnetwork/lnd/lnwire" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// TestPopulateSecondLevelLeaves asserts that second-level HTLC aux leaves are +// derived from a revocation log for exactly the HTLCs that carry assets: an +// incoming asset HTLC gets a second-level leaf with a CLTV timeout, an +// outgoing asset HTLC gets one without, HTLCs without asset outputs are +// skipped, and revocation log entries without an HTLC index are ignored. +func TestPopulateSecondLevelLeaves(t *testing.T) { + t.Parallel() + + commitTx := randProof(t).AnchorTx + keyRing := lndmock.RandCommitmentKeyRing(t) + + groupKey := &asset.GroupKey{ + GroupPubKey: *test.RandPubKey(t), + } + + newHtlcOutputs := func() []*cmsg.AssetOutput { + assetID, p := htlcGroupProof(t, groupKey, commitTx) + return []*cmsg.AssetOutput{ + cmsg.NewAssetOutput(assetID, p.Asset.Amount, *p), + } + } + + const ( + incomingIdx = uint64(1) + outgoingIdx = uint64(2) + btcOnlyIdx = uint64(3) + ) + + incomingHtlcs := map[input.HtlcIndex][]*cmsg.AssetOutput{ + incomingIdx: newHtlcOutputs(), + } + outgoingHtlcs := map[input.HtlcIndex][]*cmsg.AssetOutput{ + outgoingIdx: newHtlcOutputs(), + } + + commitment := cmsg.NewCommitment( + nil, nil, outgoingHtlcs, incomingHtlcs, + lnwallet.CommitAuxLeaves{}, false, false, cmsg.SigHashAll, + ) + + newEntry := func(idx uint64, incoming bool) *channeldb.HTLCEntry { + entry, err := channeldb.NewHTLCEntryFromHTLC(channeldb.HTLC{ + RHash: [32]byte{byte(idx)}, + RefundTimeout: 800_000 + uint32(idx), + Incoming: incoming, + Amt: lnwire.NewMSatFromSatoshis( + 354, + ), + HtlcIndex: idx, + }) + require.NoError(t, err) + + return entry + } + + revLog := &channeldb.RevocationLog{ + HTLCEntries: []*channeldb.HTLCEntry{ + newEntry(incomingIdx, true), + newEntry(outgoingIdx, false), + // A BTC-only HTLC: present in the log, but carries no + // asset outputs in the commitment. + newEntry(btcOnlyIdx, true), + // An entry without an HTLC index must be skipped. + {}, + }, + } + + leaves := lnwallet.CommitAuxLeaves{ + IncomingHtlcLeaves: make(input.HtlcAuxLeaves), + OutgoingHtlcLeaves: make(input.HtlcAuxLeaves), + } + + err := populateSecondLevelLeaves( + revLog, commitment, chanState, keyRing, &commitTx, + testChainParams, &leaves, + ) + require.NoError(t, err) + + // The incoming asset HTLC must have produced a second-level leaf. + incomingLeaf, ok := leaves.IncomingHtlcLeaves[incomingIdx] + require.True(t, ok, "incoming asset HTLC missing second-level leaf") + require.True(t, incomingLeaf.SecondLevelLeaf.IsSome()) + + // Same for the outgoing asset HTLC. + outgoingLeaf, ok := leaves.OutgoingHtlcLeaves[outgoingIdx] + require.True(t, ok, "outgoing asset HTLC missing second-level leaf") + require.True(t, outgoingLeaf.SecondLevelLeaf.IsSome()) + + // The incoming and outgoing leaves must differ: the incoming path + // commits to a CLTV timeout while the outgoing one does not. + require.NotEqual( + t, + incomingLeaf.SecondLevelLeaf.UnwrapOrFail(t).Script, + outgoingLeaf.SecondLevelLeaf.UnwrapOrFail(t).Script, + ) + + // The BTC-only HTLC and the index-less entry must not have produced + // any leaves. + require.NotContains(t, leaves.IncomingHtlcLeaves, btcOnlyIdx) + require.Len(t, leaves.IncomingHtlcLeaves, 1) + require.Len(t, leaves.OutgoingHtlcLeaves, 1) +} + +// fixedFeatures is a FeatureBitFetcher that reports the same features for +// every channel. +type fixedFeatures struct { + bits []lnwire.FeatureBit +} + +// GetChannelFeatures returns the configured features. +func (f fixedFeatures) GetChannelFeatures( + _ lnwire.ChannelID) lnwire.FeatureVector { + + return *lnwire.NewFeatureVector( + lnwire.NewRawFeatureVector(f.bits...), nil, + ) +} + +// TestLeafStoreSigHashModeFromRequest asserts that the sighash mode of a +// commitment being built is the one lnd states in the request, for the leaves +// and for the blob alike, whatever the live feature negotiation and the +// previous commitment say. +// +// The signer of a commitment decides its mode and states it on the +// commitment_signed. That message can be retransmitted after both peers +// upgraded, so the receiver has to build a legacy commitment while the +// feature is already negotiated. Deriving the mode here would record +// SigHashDefault for a commitment that was signed as legacy. +func TestLeafStoreSigHashModeFromRequest(t *testing.T) { + t.Parallel() + + channel := newOneSidedChannel(t) + fundedAsset := channel.fundingProof.Asset.ID() + chanAssetState := cmsg.NewOpenChannel( + []*cmsg.AssetOutput{channel.assetOutput}, 0, nil, + ) + + chanType := channeldb.SingleFunderTweaklessBit | + channeldb.AnchorOutputsBit | channeldb.ScidAliasChanBit | + channeldb.SimpleTaprootFeatureBit | channeldb.TapscriptRootBit + chanState := lnwallet.AuxChanState{ + ChanType: chanType, + CustomBlob: lfn.Some[tlv.Blob](chanAssetState.Bytes()), + } + dustLimit := rfqmath.LegacyOnChainHtlcSat + chanState.LocalChanCfg.DustLimit = dustLimit + + // The legacy carrier of an asset HTLC has an output on a legacy + // commitment and is dust on a SigHashDefault one, where it must also + // pay for the fee and the anchor of the second-level transaction. A + // commitment that would trim an asset HTLC is refused, which makes + // the mode the allocations were generated with observable. + legacyCarrier := rfqmath.LegacyOnChainHtlcSat + feePerKw := chainfee.FeePerKwFloor + require.False(t, lnwallet.HtlcIsDust( + chanType, true, lntypes.Local, feePerKw, legacyCarrier, + dustLimit, false, + )) + require.True(t, lnwallet.HtlcIsDust( + chanType, true, lntypes.Local, feePerKw, legacyCarrier, + dustLimit, true, + )) + + htlcRecord := rfqmsg.NewHtlc( + []*rfqmsg.AssetBalance{ + rfqmsg.NewAssetBalance( + fundedAsset, channel.fundingProof.Asset.Amount, + ), + }, + fn.None[rfqmsg.ID](), fn.None[[]rfqmsg.ID](), + ) + records, err := lnwire.ParseCustomRecords(htlcRecord.Bytes()) + require.NoError(t, err) + + newInput := func(prevDefault, sigHashDefault bool, + carrier btcutil.Amount) lnwallet.CommitDiffAuxInput { + + prevState := cmsg.NewCommitment( + nil, []*cmsg.AssetOutput{channel.assetOutput}, nil, + nil, lnwallet.CommitAuxLeaves{}, false, false, + cmsg.SigHashTypeFromBool(prevDefault), + ) + desc := lnwallet.NewTestAuxHtlcDescriptor( + lnwire.ChannelID{}, lnwallet.PaymentHash{1}, + uint32(carrier), lnwire.NewMSatFromSatoshis(carrier), + 0, 0, uint8(lnwallet.Add), records, 1, 0, 0, 0, + ) + + var view lnwallet.AuxHtlcView + view.NextHeight = 1 + view.FeePerKw = feePerKw + view.Updates.Remote = []lnwallet.AuxHtlcDescriptor{desc} + + return lnwallet.CommitDiffAuxInput{ + ChannelState: chanState, + PrevBlob: prevState.Bytes(), + UnfilteredView: view, + WhoseCommit: lntypes.Local, + OurBalance: lnwire.MilliSatoshi(1_000_000_000), + TheirBalance: lnwire.MilliSatoshi(1_000_000_000), + KeyRing: lndmock.RandCommitmentKeyRing(t), + SigHashDefault: sigHashDefault, + } + } + + negotiated := fixedFeatures{ + bits: []lnwire.FeatureBit{ + tapfeatures.DeterministicHTLCsOptional, + }, + } + + for _, features := range []fixedFeatures{{}, negotiated} { + for _, prevDefault := range []bool{false, true} { + name := fmt.Sprintf("negotiated=%v prev_default=%v", + len(features.bits) > 0, prevDefault) + + // The blob records the mode of the request. + for _, mode := range []bool{false, true} { + in := newInput( + prevDefault, mode, + rfqmath.DefaultOnChainHtlcSat, + ) + blob, err := ApplyHtlcView( + testChainParams, in, features, + ).Unpack() + require.NoError(t, err, name) + + commit, err := cmsg.DecodeCommitment( + blob.UnwrapOr(nil), + ) + require.NoError(t, err, name) + recorded := commit.SigHashDefault.Val + require.Equal(t, mode, recorded, name) + + _, err = FetchLeavesFromView( + testChainParams, in, features, + ).Unpack() + require.NoError(t, err, name) + } + + // The allocations behind the leaves and the blob are + // generated with that mode as well: the legacy carrier + // passes as legacy and is refused as SigHashDefault. + legacy := newInput(prevDefault, false, legacyCarrier) + _, err := FetchLeavesFromView( + testChainParams, legacy, features, + ).Unpack() + require.NoError(t, err, name) + _, err = ApplyHtlcView( + testChainParams, legacy, features, + ).Unpack() + require.NoError(t, err, name) + + deterministic := newInput( + prevDefault, true, legacyCarrier, + ) + _, err = FetchLeavesFromView( + testChainParams, deterministic, features, + ).Unpack() + require.Error(t, err, name) + _, err = ApplyHtlcView( + testChainParams, deterministic, features, + ).Unpack() + require.Error(t, err, name) + } + } +} diff --git a/tapchannel/aux_leaf_signer.go b/tapchannel/aux_leaf_signer.go index 30f4d56c33..1f47b77023 100644 --- a/tapchannel/aux_leaf_signer.go +++ b/tapchannel/aux_leaf_signer.go @@ -24,7 +24,6 @@ import ( "github.com/lightninglabs/taproot-assets/vm" lfn "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/input" - "github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/lnwallet" "github.com/lightningnetwork/lnd/lnwallet/btcwallet" "github.com/lightningnetwork/lnd/lnwire" @@ -183,17 +182,19 @@ func VerifySecondLevelSigs(chainParams *address.ChainParams, for idx := range verifyJobs { verifyJob := verifyJobs[idx] - // If there is no signature blob, this isn't a custom channel. - if verifyJob.SigBlob.IsNone() { - continue - } - - assetSigs, err := cmsg.DecodeAssetSigListRecord( - verifyJob.SigBlob.UnsafeFromSome(), - ) - if err != nil { - return fmt.Errorf("error decoding asset sig list "+ - "record: %w", err) + // Decode the signature blob if there is one. Whether its + // absence is acceptable is decided below, once we know if + // the HTLC carries assets. + var assetSigs *cmsg.AssetSigListRecord + if verifyJob.SigBlob.IsSome() { + var err error + assetSigs, err = cmsg.DecodeAssetSigListRecord( + verifyJob.SigBlob.UnsafeFromSome(), + ) + if err != nil { + return fmt.Errorf("error decoding asset sig "+ + "list record: %w", err) + } } // If there is no commit blob, this isn't a custom channel. @@ -229,14 +230,32 @@ func VerifySecondLevelSigs(chainParams *address.ChainParams, continue } + // An asset HTLC owes a signature. The caller hands us a job + // for every HTLC, signed or not, precisely because only we + // can tell which ones carry assets. A peer that leaves the + // signature out must not get away with it: without it we + // could not build the second-level asset transition of this + // HTLC, on our own commitment or after a breach of theirs. + if assetSigs == nil { + return fmt.Errorf("missing second level sig for asset "+ + "HTLC (idx=%d htlcIdx=%d incoming=%v "+ + "whoseCommit=%v)", idx, + verifyJob.HTLC.HtlcIndex, verifyJob.Incoming, + verifyJob.WhoseCommit) + } + err = verifyHtlcSignature( chainParams, chanState, commitTx, verifyJobs[idx].KeyRing, assetSigs.Sigs, htlcOutputs, verifyJobs[idx].BaseAuxJob, ) if err != nil { - return fmt.Errorf("error verifying second level sig: "+ - "%w", err) + return fmt.Errorf("error verifying second "+ + "level sig (idx=%d htlcIdx=%d "+ + "incoming=%v whoseCommit=%v): %w", + idx, verifyJob.HTLC.HtlcIndex, + verifyJob.Incoming, + verifyJob.WhoseCommit, err) } } @@ -361,17 +380,21 @@ func verifyHtlcSignature(chainParams *address.ChainParams, keyRing lnwallet.CommitmentKeyRing, sigs []*cmsg.AssetSig, htlcOutputs []*cmsg.AssetOutput, baseJob lnwallet.BaseAuxJob) error { - // If we're validating a signature for an outgoing HTLC, then it's an - // outgoing HTLC for the remote party, so we'll need to sign it with the - // proper lock time. - var htlcTimeout fn.Option[uint32] - if !baseJob.Incoming { - htlcTimeout = fn.Some(baseJob.HTLC.Timeout) - } + // The job carries the timeout to use explicitly: lnd sets it for both + // the CommitSig flow and the revocation flow, from the second-level + // path the signature is for. We must NOT re-derive it from the + // direction here: the two flows sign for opposite commitments, so the + // same direction means the timeout path in one and the success path + // (which has no locktime) in the other. + htlcTimeout := fn.None[uint32]() + baseJob.HtlcTimeout.WhenSome(func(v uint32) { + htlcTimeout = fn.Some(v) + }) vPackets, err := htlcSecondLevelPacketsFromCommit( chainParams, chanState, commitTx, baseJob.KeyRing, htlcOutputs, baseJob, htlcTimeout, baseJob.HTLC.HtlcIndex, + sigHashDefaultFromCommitBlob(baseJob.CommitBlob), ) if err != nil { return fmt.Errorf("error generating second level packets: %w", @@ -410,9 +433,10 @@ func verifyHtlcSignature(chainParams *address.ChainParams, return err } - // We are always verifying the signature of the remote party, - // which are for our commitment transaction. - const whoseCommit = lntypes.Local + // Use the WhoseCommit field from the job. For the normal + // CommitSig verification flow this is Local (verifying + // remote's sigs on our commitment). + whoseCommit := baseJob.WhoseCommit htlcScript, err := lnwallet.GenTaprootHtlcScript( baseJob.Incoming, whoseCommit, baseJob.HTLC.Timeout, @@ -424,8 +448,10 @@ func verifyHtlcSignature(chainParams *address.ChainParams, "verify second level: %w", err) } + wsToSign := htlcScript.WitnessScriptToSign() + leafToVerify := txscript.TapLeaf{ - Script: htlcScript.WitnessScriptToSign(), + Script: wsToSign, LeafVersion: txscript.BaseLeafVersion, } validator := &schnorrSigValidator{ @@ -456,52 +482,70 @@ func verifyHtlcSignature(chainParams *address.ChainParams, // applySignDescToVIn applies the sign descriptor to the virtual input. This // entails updating all the input bip32, taproot, and witness fields with the // information from the sign descriptor. This function returns the public key -// that should be used to verify the generated signature, and also the leaf to -// be signed. +// that should be used to verify the generated signature. For scriptspend, it +// also returns the leaf to be signed. For breach scenarios (keyspend), the +// leaf will be empty. +// +// The isBreach parameter must be true when the input is spent as part of a +// breach (justice) key spend: the signer then derives the signing key by +// applying both the revocation DoubleTweak and the HTLC index SingleTweak, +// and no leaf script is attached to the input. Callers supply this from the +// sweep descriptor context (the resolution type, equivalently the absence of +// a control block), so there is a single source of truth for the decision +// rather than re-deriving it here from tweak presence. func applySignDescToVIn(signDesc input.SignDescriptor, vIn *tappsbt.VInput, - chainParams *address.ChainParams, - tapscriptRoot []byte) (btcec.PublicKey, txscript.TapLeaf) { + chainParams *address.ChainParams, tapscriptRoot []byte, + isBreach bool) (btcec.PublicKey, txscript.TapLeaf) { - leafToSign := txscript.TapLeaf{ - Script: signDesc.WitnessScript, - LeafVersion: txscript.BaseLeafVersion, - } - vIn.TaprootLeafScript = []*psbt.TaprootTapLeafScript{ - { - Script: leafToSign.Script, - LeafVersion: leafToSign.LeafVersion, - }, - } + var leafToSign txscript.TapLeaf + // Set up derivation paths for the key. deriv, trDeriv := tappsbt.Bip32DerivationFromKeyDesc( signDesc.KeyDesc, chainParams.HDCoinType, ) vIn.Bip32Derivation = []*psbt.Bip32Derivation{deriv} - vIn.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{ - trDeriv, - } - vIn.TaprootBip32Derivation[0].LeafHashes = [][]byte{ - fn.ByteSlice(leafToSign.TapHash()), + vIn.TaprootBip32Derivation = []*psbt.TaprootBip32Derivation{trDeriv} + + if !isBreach { + // For normal sweeps (scriptspend), set up the leaf script. + leafToSign = txscript.TapLeaf{ + Script: signDesc.WitnessScript, + LeafVersion: txscript.BaseLeafVersion, + } + vIn.TaprootLeafScript = []*psbt.TaprootTapLeafScript{ + { + Script: leafToSign.Script, + LeafVersion: leafToSign.LeafVersion, + }, + } + vIn.TaprootBip32Derivation[0].LeafHashes = [][]byte{ + fn.ByteSlice(leafToSign.TapHash()), + } } + vIn.SighashType = signDesc.HashType vIn.TaprootMerkleRoot = tapscriptRoot - // Apply single or double tweaks if present in the sign - // descriptor. At the same time, we apply the tweaks to a copy - // of the public key, so we can validate the produced signature. + // Apply single or double tweaks if present in the sign descriptor. At + // the same time, we apply the tweaks to a copy of the public key, so we + // can validate the produced signature. + // + // For breach scenarios, both DoubleTweak and SingleTweak are present + // and both are added to the PSBT unknowns keyed by their type. Two + // distinct lnd signer paths consume this pair and BOTH must combine + // them (double/revocation first, then single/HTLC index, since + // DeriveRevocationPrivKey hashes its input key and the operations do + // not commute): maybeTweakPrivKey in lnwallet/btcwallet/signer.go + // (local signer, reads the SignDescriptor fields) and + // maybeTweakPrivKeyPsbt in lnwallet/btcwallet/psbt.go (remote + // signer, reads these unknowns). The verification public key derived + // below applies the same order. + // + // For normal force closes, only one tweak is present at a time. signingKey := signDesc.KeyDesc.PubKey - if len(signDesc.SingleTweak) > 0 { - key := btcwallet.PsbtKeyTypeInputSignatureTweakSingle - vIn.Unknowns = append(vIn.Unknowns, &psbt.Unknown{ - Key: key, - Value: signDesc.SingleTweak, - }) - signingKey = input.TweakPubKeyWithTweak( - signingKey, signDesc.SingleTweak, - ) - } - if signDesc.DoubleTweak != nil { + if isBreach { + // Breach scenario: set both tweaks in PSBT unknowns. key := btcwallet.PsbtKeyTypeInputSignatureTweakDouble vIn.Unknowns = append(vIn.Unknowns, &psbt.Unknown{ Key: key, @@ -511,6 +555,41 @@ func applySignDescToVIn(signDesc input.SignDescriptor, vIn *tappsbt.VInput, signingKey = input.DeriveRevocationPubkey( signingKey, signDesc.DoubleTweak.PubKey(), ) + + key = btcwallet.PsbtKeyTypeInputSignatureTweakSingle + vIn.Unknowns = append(vIn.Unknowns, &psbt.Unknown{ + Key: key, + Value: signDesc.SingleTweak, + }) + + signingKey = input.TweakPubKeyWithTweak( + signingKey, signDesc.SingleTweak, + ) + } else { + // Normal force close: Apply tweaks in the original order. + // Apply SingleTweak first (if present), then DoubleTweak. + if len(signDesc.SingleTweak) > 0 { + key := btcwallet.PsbtKeyTypeInputSignatureTweakSingle + vIn.Unknowns = append(vIn.Unknowns, &psbt.Unknown{ + Key: key, + Value: signDesc.SingleTweak, + }) + + signingKey = input.TweakPubKeyWithTweak( + signingKey, signDesc.SingleTweak, + ) + } + if signDesc.DoubleTweak != nil { + key := btcwallet.PsbtKeyTypeInputSignatureTweakDouble + vIn.Unknowns = append(vIn.Unknowns, &psbt.Unknown{ + Key: key, + Value: signDesc.DoubleTweak.Serialize(), + }) + + signingKey = input.DeriveRevocationPubkey( + signingKey, signDesc.DoubleTweak.PubKey(), + ) + } } return *signingKey, leafToSign @@ -523,26 +602,28 @@ func (s *AuxLeafSigner) generateHtlcSignature(chanState lnwallet.AuxChanState, signDesc input.SignDescriptor, baseJob lnwallet.BaseAuxJob) (lnwallet.AuxSigJobResp, error) { - // If we're generating a signature for an incoming HTLC, then it's an - // outgoing HTLC for the remote party, so we'll need to sign it with the - // proper lock time. - var htlcTimeout fn.Option[uint32] - if baseJob.Incoming { - htlcTimeout = fn.Some(baseJob.HTLC.Timeout) - } + // The job carries the timeout to use explicitly (see + // verifyHtlcSignature for why it must not be re-derived from the + // HTLC direction here). + htlcTimeout := fn.None[uint32]() + baseJob.HtlcTimeout.WhenSome(func(v uint32) { + htlcTimeout = fn.Some(v) + }) vPackets, err := htlcSecondLevelPacketsFromCommit( s.cfg.ChainParams, chanState, commitTx, baseJob.KeyRing, htlcOutputs, baseJob, htlcTimeout, baseJob.HTLC.HtlcIndex, + sigHashDefaultFromCommitBlob(baseJob.CommitBlob), ) if err != nil { return lnwallet.AuxSigJobResp{}, fmt.Errorf("error generating "+ "second level packets: %w", err) } - // We are always signing the commitment transaction of the remote party, - // which is why we set whoseCommit to remote. - const whoseCommit = lntypes.Remote + // Use the WhoseCommit field from the job to determine which + // party's commitment we're signing. For the normal CommitSig + // flow this is Remote; for revocation self-signing this is Local. + whoseCommit := baseJob.WhoseCommit htlcScript, err := lnwallet.GenTaprootHtlcScript( baseJob.Incoming, whoseCommit, baseJob.HTLC.Timeout, @@ -562,6 +643,7 @@ func (s *AuxLeafSigner) generateHtlcSignature(chanState lnwallet.AuxChanState, signingKey, leafToSign := applySignDescToVIn( signDesc, vIn, s.cfg.ChainParams, tapscriptRoot, + false, ) // We can now sign this virtual packet, as we've given the @@ -623,11 +705,13 @@ func htlcSecondLevelPacketsFromCommit(chainParams *address.ChainParams, chanState lnwallet.AuxChanState, commitTx *wire.MsgTx, keyRing lnwallet.CommitmentKeyRing, htlcOutputs []*cmsg.AssetOutput, baseJob lnwallet.BaseAuxJob, htlcTimeout fn.Option[uint32], - htlcIndex uint64) ([]*tappsbt.VPacket, error) { + htlcIndex uint64, + addAnchor bool) ([]*tappsbt.VPacket, error) { packets, _, err := CreateSecondLevelHtlcPackets( chanState, commitTx, baseJob.HTLC.Amount.ToSatoshis(), keyRing, chainParams, htlcOutputs, htlcTimeout, htlcIndex, + addAnchor, ) if err != nil { return nil, fmt.Errorf("error creating second level HTLC "+ @@ -637,6 +721,25 @@ func htlcSecondLevelPacketsFromCommit(chainParams *address.ChainParams, return packets, nil } +// sigHashDefaultFromCommitBlob extracts the cached DeterministicHTLCs +// flag from a commitment blob. Returns false when the blob is absent or +// malformed (the safe default: no anchor on the 2nd-level tx). +func sigHashDefaultFromCommitBlob( + blob lfn.Option[tlv.Blob]) bool { + + raw, err := blob.UnwrapOrErr(fmt.Errorf("no commit blob")) + if err != nil { + return false + } + + c, err := cmsg.DecodeCommitment(raw) + if err != nil { + return false + } + + return c.SigHashDefault.Val +} + // schnorrSigValidator validates a single Schnorr signature against the given // public key. type schnorrSigValidator struct { diff --git a/tapchannel/aux_leaf_signer_test.go b/tapchannel/aux_leaf_signer_test.go index 0dcdc64a28..0837370c30 100644 --- a/tapchannel/aux_leaf_signer_test.go +++ b/tapchannel/aux_leaf_signer_test.go @@ -476,7 +476,7 @@ func htlcVerifyJob(t *testing.T, numSigs int) (*wire.MsgTx, com := cmsg.NewCommitment( nil, nil, outgoingHtlcs, nil, lnwallet.CommitAuxLeaves{}, false, - false, + false, cmsg.SigHashAll, ) sigs := make([]*cmsg.AssetSig, numSigs) @@ -679,6 +679,7 @@ func TestVerifyHtlcSignatureMultiAsset(t *testing.T) { vPackets, err := htlcSecondLevelPacketsFromCommit( testChainParams, chanState, &commitTx, keyRing, htlcOutputs, baseJob, fn.Some(baseJob.HTLC.Timeout), baseJob.HTLC.HtlcIndex, + false, ) require.NoError(t, err) require.Len(t, vPackets, len(htlcOutputs)) @@ -743,3 +744,73 @@ func TestVerifyHtlcSignatureMultiAsset(t *testing.T) { htlcOutputs, baseJob, ), "signature verification failed") } + +// TestSecondLevelPacketsLockTime pins the semantics of the HtlcTimeout job +// field: the second-level packets carry a locktime exactly when the job says +// so, and None means NO locktime. The revocation flow deliberately sends +// None for success-path signatures (the canonical success transition has no +// locktime), so the packet builder must never re-derive a timeout from the +// HTLC direction; doing so would make signing and verification agree with +// each other while diverging from the transition the sweeper later +// reconstructs on the breach path. +func TestSecondLevelPacketsLockTime(t *testing.T) { + privKey := test.RandPrivKey() + + keyRing := lndmock.RandCommitmentKeyRing(t) + keyRing.RemoteHtlcKey = privKey.PubKey() + + commitTx := randProof(t).AnchorTx + + groupKey := &asset.GroupKey{ + GroupPubKey: *test.RandPubKey(t), + } + assetID, p := htlcGroupProof(t, groupKey, commitTx) + htlcOutputs := []*cmsg.AssetOutput{ + cmsg.NewAssetOutput(assetID, p.Asset.Amount, *p), + } + + // An incoming HTLC: the legacy CommitSig-time convention would have + // derived a timeout for it, which is exactly what the explicit None + // must override on the revocation success path. + baseJob := lnwallet.BaseAuxJob{ + KeyRing: keyRing, + Incoming: true, + HTLC: lnwallet.AuxHtlcDescriptor{ + HtlcIndex: 0, + Timeout: 800_000, + Amount: lnwire.NewMSatFromSatoshis(354), + EntryType: lnwallet.Add, + }, + } + + // HtlcTimeout of None must yield packets with no locktime. + vPackets, err := htlcSecondLevelPacketsFromCommit( + testChainParams, chanState, &commitTx, keyRing, htlcOutputs, + baseJob, fn.None[uint32](), baseJob.HTLC.HtlcIndex, false, + ) + require.NoError(t, err) + require.NotEmpty(t, vPackets) + for _, vPkt := range vPackets { + for _, vOut := range vPkt.Outputs { + require.EqualValues(t, 0, vOut.LockTime, + "None timeout must not produce a locktime") + } + } + + // An explicit timeout must be carried through verbatim. + vPackets, err = htlcSecondLevelPacketsFromCommit( + testChainParams, chanState, &commitTx, keyRing, htlcOutputs, + baseJob, fn.Some(baseJob.HTLC.Timeout), + baseJob.HTLC.HtlcIndex, false, + ) + require.NoError(t, err) + require.NotEmpty(t, vPackets) + for _, vPkt := range vPackets { + for _, vOut := range vPkt.Outputs { + require.EqualValues( + t, baseJob.HTLC.Timeout, vOut.LockTime, + "explicit timeout must be carried through", + ) + } + } +} diff --git a/tapchannel/aux_sweeper.go b/tapchannel/aux_sweeper.go index 379fc7e32e..1150fb786a 100644 --- a/tapchannel/aux_sweeper.go +++ b/tapchannel/aux_sweeper.go @@ -3,8 +3,8 @@ package tapchannel import ( "bytes" "context" + "crypto/sha256" "fmt" - "math" "net/url" "slices" "sync" @@ -17,6 +17,7 @@ import ( "github.com/btcsuite/btcd/wire/v2" "github.com/lightninglabs/taproot-assets/address" "github.com/lightninglabs/taproot-assets/asset" + "github.com/lightninglabs/taproot-assets/commitment" "github.com/lightninglabs/taproot-assets/fn" "github.com/lightninglabs/taproot-assets/proof" "github.com/lightninglabs/taproot-assets/tapchannelmsg" @@ -26,6 +27,7 @@ import ( "github.com/lightninglabs/taproot-assets/tappsbt" "github.com/lightninglabs/taproot-assets/tapscript" "github.com/lightninglabs/taproot-assets/tapsend" + "github.com/lightningnetwork/lnd/channeldb" lfn "github.com/lightningnetwork/lnd/fn/v2" "github.com/lightningnetwork/lnd/input" "github.com/lightningnetwork/lnd/keychain" @@ -44,6 +46,16 @@ const ( // outputs on chain, we'll need an increased budget (the amount we // should spend on fees) to make sure the outputs are always swept. sweeperBudgetMultiplier = 20 + + // sweepAnchorOutputAmt is the BTC value placed on the asset-bearing + // output of a sweep transaction. We use a value just above the + // taproot dust limit (rather than tapsend.DummyAmtSats=1000) so the + // sweep can be funded entirely from the small second-level HTLC + // output value (~626 sats at floor rate) without pulling in any + // wallet UTXOs, since the wallet's UTXO accounting can be off by + // the AnchorSize amount in chains where the immediate parent tx + // contains an anchor output. + sweepAnchorOutputAmt = btcutil.Amount(400) ) // resolutionReq carries a request to resolve a contract output along with a @@ -89,6 +101,9 @@ type broadcastReq struct { // sure we make proofs properly for the pre-signed HTLC transactions. outpointToTxIndex map[wire.OutPoint]int + // opts contains the notify options from the caller. + opts sweep.AuxNotifyOpts + // resp is the error result of the broadcast. resp chan error } @@ -249,12 +264,26 @@ func (a *AuxSweeper) createSweepVpackets(sweepInputs []*cmsg.AssetOutput, cltvTimeout = fn.Some(uint32(delay)) }) - htlcIndex := resReq.HtlcID.UnwrapOr(math.MaxUint64) + // A second-level sweep is always tied to a specific HTLC, so + // a missing HTLC ID is a hard error: falling back to a bogus + // index would make the allocation lookups below silently + // return nothing. + htlcIndex, err := resReq.HtlcID.UnwrapOrErr( + fmt.Errorf("second-level sweep missing HTLC ID"), + ) + if err != nil { + return lfn.Err[returnType](err) + } + + // addAnchor is false here: we're allocating for the SWEEP of + // the second-level HTLC output, not constructing the + // second-level tx itself. The on-chain anchor (if any) is + // independent of this sweep. alloc, err := createSecondLevelHtlcAllocations( resReq.ChanType, resReq.Initiator, sweepInputs, resReq.HtlcAmt, resReq.CommitCsvDelay, *resReq.KeyRing, fn.Some(resReq.ContractPoint.Index), cltvTimeout, - htlcIndex, + htlcIndex, false, ) if err != nil { return lfn.Err[returnType](err) @@ -298,7 +327,7 @@ func (a *AuxSweeper) createSweepVpackets(sweepInputs []*cmsg.AssetOutput, OutputIndex: 0, Amount: sweepAssetSum, AssetVersion: asset.V1, - BtcAmount: tapsend.DummyAmtSats, + BtcAmount: sweepAnchorOutputAmt, GenScriptKey: scriptKeyGen, }) } @@ -381,30 +410,84 @@ func (a *AuxSweeper) signSweepVpackets(vPackets []*tappsbt.VPacket, // single asset from our commitment output. vIn := vPacket.Inputs[0] - // Next, we'll apply the sign desc to the vIn, setting the PSBT - // specific fields. Along the way, we'll apply any relevant - // tweaks to generate the key we'll use to verify the - // signature. - signingKey, leafToSign := applySignDescToVIn( - signDesc, vIn, &a.cfg.ChainParams, tapTweak, + // Detect breach scenario: no control block means keyspend + // (revocation). Normal force close uses scriptspend + // (control block present). See also aux_leaf_signer.go + // which uses DoubleTweak+SingleTweak for the same + // detection when the control block isn't available. + isBreach := len(ctrlBlock) == 0 + + var ( + signingKey btcec.PublicKey + leafToSign txscript.TapLeaf + signMethod input.SignMethod + tapLeafOpt lfn.Option[txscript.TapLeaf] ) - // In this case, the witness isn't special, so we'll set the - // control block now for it. - vIn.TaprootLeafScript[0].ControlBlock = ctrlBlock + if isBreach { + // For breach scenarios (HTLC revocations), the + // common function applies both DoubleTweak + // (revocation) and SingleTweak (HTLC index) to + // derive the private key for signing. We discard + // the returned signingKey and leaf because for + // breach verification we use the asset's script + // key instead (see below). + _, _ = applySignDescToVIn( + signDesc, vIn, &a.cfg.ChainParams, tapTweak, + true, + ) + + // For keyspend, we need to verify the signature against + // the asset's script key, not the derived signing key. + // The asset script key was set during commitment + // creation and incorporates both the revocation key + // derivation and the HTLC index tweak via + // TweakHtlcTree(), which also recomputes the taproot + // output key with the script root. + inputAsset := vIn.Asset() + signingKey = *inputAsset.ScriptKey.PubKey + signMethod = input.TaprootKeySpendSignMethod + + tapLeafOpt = lfn.None[txscript.TapLeaf]() + } else { + // For normal force close sweeps, we use scriptspend. + signingKey, leafToSign = applySignDescToVIn( + signDesc, vIn, &a.cfg.ChainParams, tapTweak, + false, + ) + + // This is a normal scriptspend (not a breach + // keyspend), so set the control block that + // applySignDescToVIn prepared. + vIn.TaprootLeafScript[0].ControlBlock = ctrlBlock - log.Debugf("signing vPacket for input=%v", - limitSpewer.Sdump(vIn.PrevID)) + signMethod = input.TaprootScriptSpendSignMethod + + tapLeafOpt = lfn.Some(leafToSign) + } + + log.Tracef("signing vPacket[%d]: isBreach=%v, "+ + "signMethod=%v, signingKey=%x, "+ + "inputScriptKey=%x, tapTweak=%x, "+ + "singleTweak=%x, doubleTweak=%v", + vPktIndex, isBreach, + signMethod, + signingKey.SerializeCompressed(), + vIn.Asset().ScriptKey.PubKey. + SerializeCompressed(), + tapTweak, + signDesc.SingleTweak, + signDesc.DoubleTweak != nil) // With everything set, we can now sign the new leaf we'll // sweep into. ctxb := context.Background() signed, err := a.cfg.Signer.SignVirtualPacket( - ctxb, vPacket, tapfreighter.SkipInputProofVerify(), + ctxb, vPacket, tapfreighter.WithValidator(&schnorrSigValidator{ pubKey: signingKey, - tapLeaf: lfn.Some(leafToSign), - signMethod: input.TaprootScriptSpendSignMethod, + tapLeaf: tapLeafOpt, + signMethod: signMethod, }), ) if err != nil { @@ -638,6 +721,32 @@ func (a *AuxSweeper) createAndSignSweepVpackets( }, )(desc.auxSigInfo).UnwrapOr(resReq.SignDesc) + // For HTLC revocation sweeps (breach scenarios), we need to + // apply the HTLC index tweak to the SignDesc. This is indicated + // by an empty control block (keyspend path). The HTLC index is + // passed in resReq.HtlcID. This tweak is applied at the ASSET + // level only (not Bitcoin level). + // + // IMPORTANT: Only apply this for breach scenarios, NOT for + // normal force close HTLC sweeps. + isBreach := len(desc.ctrlBlockBytes) == 0 + if isBreach { + // For breach scenarios, the HTLC ID must be present + // to compute the single tweak. + htlcID, err := resReq.HtlcID.UnwrapOrErr(errNoHtlcID) + if err != nil { + return lfn.Err[returnType](err) + } + + // Derive the single tweak from the HTLC index, + // using the same function used during commitment + // creation to ensure consistency. + tweakScalar := ScriptKeyTweakFromHtlcIndex(htlcID) + var singleTweak [32]byte + tweakScalar.PutBytesUnchecked(singleTweak[:]) + signDesc.SingleTweak = singleTweak[:] + } + err := a.signSweepVpackets( vPkts, signDesc, desc.scriptTree.TapTweak(), desc.ctrlBlockBytes, desc.auxSigInfo, @@ -994,7 +1103,7 @@ func localHtlcTimeoutSweepDesc(req lnwallet.ResolutionReq, ctrlBlockBytes: ctrlBlockBytes, relativeDelay: lfn.Some(uint64(req.CsvDelay)), absoluteDelay: lfn.Some(uint64(htlcExpiry)), - auxSigInfo: req.AuxSigDesc, + auxSigInfo: breachAuxSigInfo(req), secondLevelSigIndex: sigIndex, }, secondLevel: lfn.Some(secondLevelDesc), @@ -1095,13 +1204,248 @@ func localHtlcSuccessSweepDesc(req lnwallet.ResolutionReq, scriptTree: htlcScriptTree, ctrlBlockBytes: ctrlBlockBytes, relativeDelay: lfn.Some(uint64(req.CsvDelay)), - auxSigInfo: req.AuxSigDesc, + auxSigInfo: breachAuxSigInfo(req), secondLevelSigIndex: sigIndex, }, secondLevel: lfn.Some(secondLevelDesc), }) } +// tweakHtlcScriptTree applies the HTLC index tweak to the script tree's +// internal key, returning a new HtlcScriptTree with the tweaked keys but +// the original leaves and tapscript structure preserved. +func tweakHtlcScriptTree(tree *input.HtlcScriptTree, + index input.HtlcIndex) *input.HtlcScriptTree { + + tweakedTree := TweakHtlcTree(tree.ScriptTree, index) + + return &input.HtlcScriptTree{ + ScriptTree: input.ScriptTree{ + InternalKey: tweakedTree.InternalKey, + TaprootKey: tweakedTree.TaprootKey, + TapscriptTree: tree.TapscriptTree, + TapscriptRoot: tree.TapscriptRoot, + }, + SuccessTapLeaf: tree.SuccessTapLeaf, + TimeoutTapLeaf: tree.TimeoutTapLeaf, + } +} + +// htlcOfferedRevokeSweepDesc creates a sweep descriptor for a revoked HTLC +// where htlc.Incoming=false in the remote's commitment log (meaning we're +// sending to them). We use the revocation key to keyspend immediately. +// +// IMPORTANT: Like all other HTLC sweep descriptors, we must use a TWEAKED +// keyring where the RevocationKey has the HTLC index tweak applied. This +// matches how the HTLC was created during commitment generation. +func htlcOfferedRevokeSweepDesc(originalKeyRing *lnwallet.CommitmentKeyRing, + payHash []byte, htlcExpiry uint32, + index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] { + + type returnType = tapscriptSweepDescs + + // IMPORTANT: We must match the creation flow exactly: + // 1. Create script tree with UNTWEAKED keyring + // 2. Then apply HTLC index tweak to the tree's internal key + htlcScriptTree, err := input.ReceiverHTLCScriptTaproot( + htlcExpiry, originalKeyRing.LocalHtlcKey, + originalKeyRing.RemoteHtlcKey, originalKeyRing.RevocationKey, + payHash, lntypes.Remote, input.NoneTapLeaf(), + ) + if err != nil { + return lfn.Err[returnType](err) + } + + // Apply the HTLC index tweak to the tree, matching how HTLCs are + // created in commitment.go. + tweakedHtlcTree := tweakHtlcScriptTree(htlcScriptTree, index) + + // For revoked HTLCs, we use keyspend (not scriptspend), so we don't + // need a control block. The revocation key spend path allows immediate + // sweep without CSV delays. + return lfn.Ok(tapscriptSweepDescs{ + firstLevel: tapscriptSweepDesc{ + scriptTree: tweakedHtlcTree, + }, + }) +} + +// htlcAcceptedRevokeSweepDesc creates a sweep descriptor for a revoked HTLC +// that was accepted by the remote party (incoming from their perspective). We +// use the revocation key to keyspend immediately. +// +// IMPORTANT: Like all other HTLC sweep descriptors, we must use a TWEAKED +// keyring where the RevocationKey has the HTLC index tweak applied. This +// matches how the HTLC was created during commitment generation. +func htlcAcceptedRevokeSweepDesc(originalKeyRing *lnwallet.CommitmentKeyRing, + payHash []byte, index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] { + + type returnType = tapscriptSweepDescs + + // IMPORTANT: We must match the creation flow exactly: + // 1. Create script tree with UNTWEAKED keyring + // 2. Then apply HTLC index tweak to the tree's internal key + htlcScriptTree, err := input.SenderHTLCScriptTaproot( + originalKeyRing.RemoteHtlcKey, originalKeyRing.LocalHtlcKey, + originalKeyRing.RevocationKey, payHash, lntypes.Remote, + input.NoneTapLeaf(), + ) + if err != nil { + return lfn.Err[returnType](err) + } + + // Apply the HTLC index tweak to the tree, matching how HTLCs are + // created in commitment.go. + tweakedHtlcTree := tweakHtlcScriptTree(htlcScriptTree, index) + + // For revoked HTLCs, we use keyspend (not scriptspend), so we don't + // need a control block. The revocation key spend path allows immediate + // sweep without CSV delays. + return lfn.Ok(tapscriptSweepDescs{ + firstLevel: tapscriptSweepDesc{ + scriptTree: tweakedHtlcTree, + }, + }) +} + +// htlcSecondLevelRevokeSweepDesc creates a sweep descriptor for a revoked +// second-level HTLC transaction. The revocation key is the internal key of +// the second-level script tree, so we sweep via keyspend (no control block +// needed), matching the LND-side TaprootHtlcSpendRevoke witness generation. +// +// IMPORTANT: Like all other HTLC sweep descriptors, we must use a TWEAKED +// keyring where the RevocationKey has the HTLC index tweak applied. This +// matches how the HTLC was created during commitment generation. +func htlcSecondLevelRevokeSweepDesc( + originalKeyRing *lnwallet.CommitmentKeyRing, csvDelay uint32, + index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] { + + type returnType = tapscriptSweepDescs + + // IMPORTANT: We must match the creation flow exactly: + // 1. Create script tree with UNTWEAKED keyring and NO aux leaf + // 2. Then apply HTLC index tweak to the tree's internal key + // + // The aux leaf is intentionally omitted here. During commitment + // generation, the ASSET-level script key is derived from the tree + // WITHOUT the aux leaf (createSecondLevelHtlcAllocations passes + // None). The aux leaf only affects the BTC-level on-chain output, + // not the asset-level script key derivation. + secondLevelScriptTree, err := input.TaprootSecondLevelScriptTree( + originalKeyRing.RevocationKey, originalKeyRing.ToLocalKey, + csvDelay, lfn.None[txscript.TapLeaf](), + ) + if err != nil { + return lfn.Err[returnType](err) + } + + // Now apply the HTLC index tweak to the tree, matching how HTLCs + // are created in commitment.go. + tweakedTree := TweakHtlcTree(secondLevelScriptTree.ScriptTree, index) + + // Create a new SecondLevelScriptTree with the tweaked keys. + tweakedScriptTree := &input.SecondLevelScriptTree{ + ScriptTree: input.ScriptTree{ + InternalKey: tweakedTree.InternalKey, + TaprootKey: tweakedTree.TaprootKey, + TapscriptTree: secondLevelScriptTree.TapscriptTree, + TapscriptRoot: secondLevelScriptTree.TapscriptRoot, + }, + } + + // For second-level revocations, we use keyspend (the internal key + // is the revocation key), so no control block is needed. + return lfn.Ok(tapscriptSweepDescs{ + firstLevel: tapscriptSweepDesc{ + scriptTree: tweakedScriptTree, + }, + }) +} + +// secondLevelHtlcOutputSweepDesc creates a sweep descriptor for the +// non-breach sweep of a second-level HTLC tx output (post-CSV). The +// second-level output is a taproot script-path spend over the second-level +// script tree using the success/timeout path (which the local party +// signs). The auxLeaf parameter must be the same aux leaf the channel +// peer baked into the pre-signed 2nd-level tx output at commitment +// construction time; without it the control block's merkle path won't +// reproduce the on-chain taproot output key and the sweep proof will +// fail to verify against the on-chain pkScript. +func secondLevelHtlcOutputSweepDesc(keyRing *lnwallet.CommitmentKeyRing, + csvDelay uint32, auxLeaf lfn.Option[txscript.TapLeaf], + htlcIndex lfn.Option[input.HtlcIndex], + assetLevel bool) lfn.Result[tapscriptSweepDescs] { + + type returnType = tapscriptSweepDescs + + // For BTC-level (breach justice tx witness), the script tree + // includes the asset commitment aux leaf as a sibling. + // For ASSET-level (non-breach 2nd-level OUTPUT sweep proof + // verification), the asset commitment was constructed with + // auxLeaf=None (see createSecondLevelHtlcAllocations), so the + // asset-level tree only contains the CSV leaf: no aux leaf + // sibling. + scriptTreeAuxLeaf := auxLeaf + if assetLevel { + scriptTreeAuxLeaf = lfn.None[txscript.TapLeaf]() + } + + secondLevelScriptTree, err := input.TaprootSecondLevelScriptTree( + keyRing.RevocationKey, keyRing.ToLocalKey, csvDelay, + scriptTreeAuxLeaf, + ) + if err != nil { + return lfn.Errf[returnType]("error creating second level "+ + "htlc script: %w", err) + } + + // For ASSET-level use, the internal key is tweaked with the HTLC + // index: this mirrors createSecondLevelHtlcAllocations which + // applies TweakHtlcTree to the asset-level script tree to ensure + // uniqueness across HTLCs with the same payment hash and timeout. + // The asset's ScriptKey on the 2nd-level output is therefore + // tweakedTree.TaprootKey, and the asset-level proof verifier + // compares the witness's control-block-derived key against that. + if assetLevel { + idx, idxErr := htlcIndex.UnwrapOrErr( + fmt.Errorf("htlc index required for asset-level " + + "2nd-level output sweep desc"), + ) + if idxErr != nil { + return lfn.Err[returnType](idxErr) + } + tweakedInternal := TweakPubKeyWithIndex( + secondLevelScriptTree.InternalKey, idx, + ) + tweakedTaprootKey := txscript.ComputeTaprootOutputKey( + tweakedInternal, secondLevelScriptTree.TapscriptRoot, + ) + secondLevelScriptTree.InternalKey = tweakedInternal + secondLevelScriptTree.TaprootKey = tweakedTaprootKey + secondLevelScriptTree.ScriptTree.InternalKey = tweakedInternal + secondLevelScriptTree.ScriptTree.TaprootKey = tweakedTaprootKey + } + + ctrlBlock, err := secondLevelScriptTree.CtrlBlockForPath( + input.ScriptPathSuccess, + ) + if err != nil { + return lfn.Err[returnType](err) + } + ctrlBlockBytes, err := ctrlBlock.ToBytes() + if err != nil { + return lfn.Err[returnType](err) + } + + return lfn.Ok(tapscriptSweepDescs{ + firstLevel: tapscriptSweepDesc{ + scriptTree: secondLevelScriptTree, + relativeDelay: lfn.Some(uint64(csvDelay)), + ctrlBlockBytes: ctrlBlockBytes, + }, + }) +} + // assetOutputToVPacket converts an asset outputs to the corresponding vPackets // that can be used to complete the proof needed to import a commitment // transaction. This new vPacket is added to the specified map. @@ -1163,9 +1507,14 @@ func assetOutputToVPacket(fundingInputProofs map[asset.ID]*proof.Proof, ProofSuffix: &assetProof, } - // While we're here, we'll also replace the transaction stored in the - // proof with the correct one. + // Replace the transaction stored in the proof with the real + // commitment tx, and set PrevOut to the funding outpoint (the + // input the commitment tx spends). The virtual proof from the + // commitment blob has placeholder values for these fields. vOut.ProofSuffix.AnchorTx = *commitTx + if len(commitTx.TxIn) > 0 { + vOut.ProofSuffix.PrevOut = commitTx.TxIn[0].PreviousOutPoint + } // Finally, we'll set the delivery address to the default courier, so // we publish the proof in the specified Universe. @@ -2260,123 +2609,763 @@ func (a *AuxSweeper) importCommitTx(req lnwallet.ResolutionReq, heightHint = fn.Some(req.CommitTxBlockHeight) } + // We set the skipBroadcast flag because this is called after a force + // close - the commitment transaction is already confirmed on-chain. return shipChannelTxn( a.cfg.TxSender, req.CommitTx, outCommitments, vPackets, int64(req.CommitFee), heightHint, ) } -// errNoPayHash is an error returned when no payment hash is provided. -var errNoPayHash = fmt.Errorf("no payment hash provided") +// breachAuxSigInfo returns the AuxSigDesc for non-breach resolution +// requests. For breach cases (Breach close type), AuxSigDesc contains +// the HTLC-level sig for the proof import: NOT for the justice sweep. +// Passing it to the sweep descriptor would corrupt the keyspend witness. +func breachAuxSigInfo( + req lnwallet.ResolutionReq) lfn.Option[lnwallet.AuxSigDesc] { -// resolveContract takes in a resolution request and resolves it by creating a -// serialized resolution blob that contains the virtual packets needed to sweep -// the funds from the contract. -func (a *AuxSweeper) resolveContract( - req lnwallet.ResolutionReq) lfn.Result[tlv.Blob] { + if req.CloseType == lnwallet.Breach { + return lfn.None[lnwallet.AuxSigDesc]() + } - type returnType = tlv.Blob + return req.AuxSigDesc +} - // If there's no commit blob, then there's nothing to resolve. - if req.CommitBlob.IsNone() { - return lfn.Err[tlv.Blob](nil) +// secondLevelHtlcIncoming returns the direction of the HTLC a second-level +// resolution request is about, from our point of view: true if we received +// the HTLC, false if we offered it. +// +// The commitment blob indexes its HTLC asset buckets from our point of view +// by HTLC index. Both parties count the HTLCs they offer from zero, so an +// index regularly exists in both buckets and never tells the direction. For +// the second-level sweeps of our own commitment the witness type does. For +// the second-level revocation of a breach it no longer does, as the same +// type covers both directions, so lnd states the direction on the request. +func secondLevelHtlcIncoming(req lnwallet.ResolutionReq) (bool, error) { + switch req.Type { + case input.TaprootHtlcAcceptedSuccessSecondLevel: + return true, nil + + case input.TaprootHtlcOfferedTimeoutSecondLevel: + return false, nil + + case input.TaprootHtlcSecondLevelRevoke: + return req.HtlcIncoming.UnwrapOrErr(fmt.Errorf("no HTLC "+ + "direction on %v resolution request for chan_point=%v", + req.Type, req.ChanPoint)) + + default: + return false, fmt.Errorf("%v is not a second-level HTLC "+ + "resolution type", req.Type) } +} - log.Infof("Generating resolution_blob for contract_type=%v, "+ - "chan_point=%v", req.Type, req.ChanPoint) +// verifyRemoteAuxSig checks whether a remote schnorr signature is valid for +// the given witness, leaf script, and virtual transaction components, under +// the remote party's HTLC key. That key is one of the two signing keys of +// the 2-of-2 leaf being spent, and the only one the remote party can have +// signed with. The sighash is computed with the signature's recorded sighash +// type, so legacy (non SigHashDefault) signatures verify as well. +func verifyRemoteAuxSig(witness wire.TxWitness, remoteSigBytes []byte, + sigHashType txscript.SigHashType, vIn *tappsbt.VInput, + newAsset *asset.Asset, remoteKey *btcec.PublicKey) error { - // As we have a commit blob, we'll decode the commit blob, so we can - // have access to all the active outputs. We'll also decode the funding - // blob, so we can make vInt from it. - commitState, err := tapchannelmsg.DecodeCommitment( - req.CommitBlob.UnwrapOr(nil), - ) + if len(witness) < 4 { + return fmt.Errorf("witness has %d elements, need at least 4", + len(witness)) + } + if remoteKey == nil { + return fmt.Errorf("no remote HTLC key") + } + + sig, err := schnorr.ParseSignature(remoteSigBytes) if err != nil { - return lfn.Err[returnType](err) + return fmt.Errorf("parsing signature: %w", err) } - fundingInfo, err := tapchannelmsg.DecodeOpenChannel( - req.FundingBlob.UnwrapOr(nil), + + // The key must actually be one of the keys of the leaf being spent. + leafScript := witness[len(witness)-2] + xOnlyKey := schnorr.SerializePubKey(remoteKey) + var keyInLeaf bool + tokenizer := txscript.MakeScriptTokenizer(0, leafScript) + for tokenizer.Next() { + if bytes.Equal(tokenizer.Data(), xOnlyKey) { + keyInLeaf = true + } + } + if err := tokenizer.Err(); err != nil { + return fmt.Errorf("parsing leaf script: %w", err) + } + if !keyInLeaf { + return fmt.Errorf("remote HTLC key %x is not part of the "+ + "spent leaf", xOnlyKey) + } + + tapLeaf := txscript.NewBaseTapLeaf(leafScript) + prevAsset := vIn.Asset() + pof, err := tapscript.InputPrevOutFetcher(*prevAsset) + if err != nil { + return fmt.Errorf("creating prev out fetcher: %w", err) + } + + prevID := newAsset.PrevWitnesses[0].PrevID + virtualTx, _, err := tapscript.VirtualTx( + newAsset, commitment.InputSet{ + *prevID: prevAsset, + }, ) if err != nil { - return lfn.Err[returnType](err) + return fmt.Errorf("creating virtual tx: %w", err) } - var ( - sweepDesc lfn.Result[tapscriptSweepDescs] - assetOutputs []*cmsg.AssetOutput - needsSecondLevel bool + vtCopy := asset.VirtualTxWithInput( + virtualTx, newAsset.LockTime, + newAsset.RelativeLockTime, 0, witness, ) + sh := txscript.NewTxSigHashes(vtCopy, pof) + sigHash, err := txscript.CalcTapscriptSignaturehash( + sh, sigHashType, vtCopy, 0, pof, tapLeaf, + ) + if err != nil { + return fmt.Errorf("computing sighash: %w", err) + } - switch req.Type { - // A non-delay output. This means the remote party force closed on - // chain. - case input.TaprootRemoteCommitSpend: - // In this case, we'll be resolving the set of remote - // assets, on the remote party's commitment, which are actually - // our assets. - assetOutputs = commitState.RemoteAssets.Val.Outputs + verifyKey, err := schnorr.ParsePubKey(xOnlyKey) + if err != nil { + return fmt.Errorf("parsing remote HTLC key: %w", err) + } + if !sig.Verify(sigHash, verifyKey) { + return fmt.Errorf("signature does not verify under the "+ + "remote HTLC key %x", xOnlyKey) + } - // First, we'll make a sweep desc for the commitment txn. This - // contains the tapscript tree, and also the control block - // needed for a valid spend. - sweepDesc = commitNoDelaySweepDesc(req.KeyRing, req.CsvDelay) + return nil +} - // A normal delay output. This means we force closed, so we'll need to - // mind the CSV when we sweep the output. - case input.TaprootLocalCommitSpend: - // In this case, we'll be resolving the set of local assets on - // our commitment. - assetOutputs = commitState.LocalAssets.Val.Outputs +// signSecondLevelImport constructs valid asset-level witnesses for +// second-level HTLC vPackets. If AuxSigDesc is present (breach case), +// it signs with our local HTLC key and inserts the remote party's +// pre-stored signature to produce a full 2-of-2 witness. If AuxSigDesc +// is absent, falls back to a placeholder witness. +func (a *AuxSweeper) signSecondLevelImport( + req lnwallet.ResolutionReq, + secondLevelPkts []*tappsbt.VPacket, + commitState *cmsg.Commitment) error { + + // Without the stored AuxSigDesc (the counterparty's asset-level + // signature) there is no way to produce a valid 2-of-2 witness, and + // a placeholder witness would fail proof verification further down + // anyway. Fail loudly instead of pretending: the error is returned + // to lnd. This can only happen for channel states created before + // the revocation AuxSigs were exchanged and persisted. + auxSigDesc, err := req.AuxSigDesc.UnwrapOrErr( + fmt.Errorf("no AuxSigDesc on resolution request: second-"+ + "level witness for chan_point=%v cannot be "+ + "constructed (state predates stored revocation aux "+ + "sigs)", req.ChanPoint), + ) + if err != nil { + return err + } - // Next, we'll make a sweep desc for this output. It's - // dependent on the CSV delay we have in this channel, so we'll - // pass that in as well. - sweepDesc = commitDelaySweepDesc(req.KeyRing, req.CsvDelay) + htlcID, idErr := req.HtlcID.UnwrapOrErr( + fmt.Errorf("no HTLC ID for second-level sign"), + ) + if idErr != nil { + return idErr + } - // The remote party has breached the channel. We'll sweep the revoked - // key that we learned in the past. - case input.TaprootCommitmentRevoke: - // outputs, as they broadcast a revoked commitment. For the - // In this case, we'll be sweeping the remote party's asset - // remote party, this is actually their local output. - assetOutputs = commitState.LocalAssets.Val.Outputs + // The direction of the HTLC, from our point of view, decides which + // HTLC script it has on the commitment. + isIncoming, dirErr := secondLevelHtlcIncoming(req) + if dirErr != nil { + return dirErr + } - // Next, we'll make a sweep desk capable of sweeping the remote - // party's local output. - sweepDesc = commitRevokeSweepDesc(req.KeyRing, req.CsvDelay) + // Reconstruct the HTLC script using the commitment-construction + // perspective. The asset-level HTLC script key was created with + // (isIncoming, whoseCommit, no aux leaf): see + // aux_leaf_creator.go where leaves are computed per-commit. For + // breach we look at the breaching party's commit, which is + // REMOTE from our perspective; for our own local force-close + // success/timeout flows the commit is LOCAL. + whoseCommit := lntypes.Remote + switch req.Type { + case input.TaprootHtlcAcceptedSuccessSecondLevel, + input.TaprootHtlcOfferedTimeoutSecondLevel: + whoseCommit = lntypes.Local + } - // The remote party broadcasted a commitment transaction which held an - // HTLC that we can timeout eventually. - case input.TaprootHtlcOfferedRemoteTimeout: - // In this case, we're interested in sweeping the incoming - // assets for the remote party, which are actually the HTLCs we - // sent outgoing. We only care about this particular HTLC, so - // we'll filter out the rest. - htlcID := req.HtlcID.UnwrapOr(math.MaxUint64) - htlcOutputs := commitState.OutgoingHtlcAssets.Val - assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) + payHash, pErr := req.PayHash.UnwrapOrErr(errNoPayHash) + if pErr != nil { + return pErr + } - payHash, err := req.PayHash.UnwrapOrErr(errNoPayHash) - if err != nil { - return lfn.Err[tlv.Blob](err) - } + htlcTimeout := req.CltvDelay.UnwrapOr(0) - // Now that we know which output we'll be sweeping, we'll make a - // sweep desc for the timeout txn. - sweepDesc = remoteHtlcTimeoutSweepDesc( - req.KeyRing, payHash[:], req.CsvDelay, - req.CltvDelay.UnwrapOr(0), htlcID, - ) + // Build the commitment-perspective HTLC script for the control + // block and script tree. This matches the asset's script key. + htlcScript, sErr := lnwallet.GenTaprootHtlcScript( + isIncoming, whoseCommit, htlcTimeout, payHash, + req.KeyRing, lfn.None[txscript.TapLeaf](), + ) + if sErr != nil { + return fmt.Errorf("generating HTLC script: %w", sErr) + } + + // The AuxSig was signed by the breaching party from their LOCAL + // perspective. Both perspectives produce the SAME leaves (just + // mapped to different path names). The signer uses: + // incoming → success path (claim with preimage) + // outgoing → timeout path (reclaim after timeout) + // Both perspectives produce byte-identical leaves, so we can + // use the commitment script tree directly. We just need to + // select the correct leaf. + // Determine the spending path from the on-chain second-level + // tx. The asset-level mirrors the BTC-level: if the BTC + // witness of the input spending the commitment HTLC output + // contains the 32-byte preimage of this HTLC's payment hash, + // it's the success path; otherwise it's the timeout path. + // + // The preimage's position depends on the witness layout: + // + // * Success spend: + // [sender_sig, receiver_sig, preimage, success_script, cb] + // -> preimage at witness index 2; some legacy/anchor + // variants place it at index 1. + // + // Only the input that actually spends the commitment tx is + // inspected (a legacy sweeper tx may carry unrelated wallet + // inputs whose witnesses are attacker-observable), and a + // candidate element only counts as the preimage if it hashes + // to the HTLC's payment hash. + isSuccessPath := false + var preimage []byte + req.SecondLevel.WhenSome(func(sl lnwallet.SecondLevelInfo) { + commitTxHash := req.CommitTx.TxHash() + for _, txIn := range sl.Tx.TxIn { + if txIn.PreviousOutPoint.Hash != commitTxHash { + continue + } + if len(txIn.Witness) < 4 { + continue + } - // The remote party broadcasted a commitment transaction which held an - // outgoing HTLC that we may claim with a preimage. - case input.TaprootHtlcAcceptedRemoteSuccess: - // In this case, it's an outgoing HTLC from the PoV of the - // remote party, which is incoming for us. We'll only sweep this - // HTLC, so we'll filter out the rest. - htlcID := req.HtlcID.UnwrapOr(math.MaxUint64) - htlcOutputs := commitState.IncomingHtlcAssets.Val - assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) + isPreimage := func(c []byte) bool { + return len(c) == 32 && + sha256.Sum256(c) == payHash + } + + // Try index 2 first (taproot success layout), + // then the legacy variant at index 1. + if len(txIn.Witness) >= 5 && + isPreimage(txIn.Witness[2]) { + + isSuccessPath = true + preimage = txIn.Witness[2] + break + } + if isPreimage(txIn.Witness[1]) { + isSuccessPath = true + preimage = txIn.Witness[1] + break + } + } + }) + + var ( + scriptPath input.ScriptPath + witnessScript []byte + ) + if isSuccessPath { + scriptPath = input.ScriptPathSuccess + witnessScript = htlcScript.SuccessTapLeaf.Script + } else { + scriptPath = input.ScriptPathTimeout + witnessScript = htlcScript.TimeoutTapLeaf.Script + } + _, htlcTree, tErr := LeavesFromTapscriptScriptTree(htlcScript) + if tErr != nil { + return fmt.Errorf("extracting HTLC tree: %w", tErr) + } + + tweakedTree := TweakHtlcTree(htlcTree, htlcID) + tapscriptRoot := tweakedTree.TapscriptRoot + + ctrlBlock, cbErr := htlcScript.CtrlBlockForPath(scriptPath) + if cbErr != nil { + return fmt.Errorf("getting ctrl block: %w", cbErr) + } + ctrlBlock.InternalKey = tweakedTree.InternalKey + ctrlBlock.OutputKeyYIsOdd = tweakedTree.TaprootKey. + SerializeCompressed()[0] == 0x03 + + ctrlBlockBytes, cbErr := ctrlBlock.ToBytes() + if cbErr != nil { + return fmt.Errorf("serializing ctrl block: %w", cbErr) + } + + // Sign each vPacket with our local HTLC key and insert the + // remote party's signature. + signDesc := auxSigDesc.SignDetails.SignDesc + signDesc.WitnessScript = witnessScript + + for vPktIdx, vPkt := range secondLevelPkts { + if len(vPkt.Inputs) != 1 { + return fmt.Errorf("expected 1 input, got %d", + len(vPkt.Inputs)) + } + + vIn := vPkt.Inputs[0] + + // Set up the vInput for signing with our HTLC key. + signingKey, leafToSign := applySignDescToVIn( + signDesc, vIn, &a.cfg.ChainParams, + tapscriptRoot, false, + ) + + if len(vIn.TaprootLeafScript) > 0 { + vIn.TaprootLeafScript[0].ControlBlock = ctrlBlockBytes + } + + // Sign the virtual packet with our key. + ctxb := context.Background() + signed, signErr := a.cfg.Signer.SignVirtualPacket( + ctxb, vPkt, + tapfreighter.WithValidator( + &schnorrSigValidator{ + pubKey: signingKey, + tapLeaf: lfn.Some(leafToSign), + signMethod: input. + TaprootScriptSpendSignMethod, + }, + ), + ) + if signErr != nil { + return fmt.Errorf("signing vPacket %d: %w", + vPktIdx, signErr) + } + + if len(signed) != 1 || signed[0] != 0 { + return fmt.Errorf("unexpected sign result for " + + "vPacket") + } + + // Insert the remote party's pre-stored sig (AuxSig) + // into the witness so we end up with a valid 2-of-2 + // asset-level witness. + // + // After SignVirtualPacket the base witness is + // [ourSig, script, cb] (3 elements). The destination + // position for AuxSig depends on which role *we* play + // in the original HTLC's local commitment script: + // + // Breach (TaprootHtlcSecondLevelRevoke): + // We're sweeping the breaching party's revoked + // 2nd-level tx. The original HTLC was sent by us + // to them: we are the SENDER. The breaching + // party broadcast a success/timeout tx with + // on-chain witness order [sender_sig, receiver_sig, + // …]. ourSig (sender) belongs at index 0, AuxSig + // (receiver) at index 1. + // Final witness: [ourSig, AuxSig, (preimage,) script, cb] + // + // Non-breach success (TaprootHtlcAcceptedSuccessSecondLevel): + // We *received* the HTLC on our local commit and + // are sweeping via the success path. We are the + // RECEIVER. On-chain witness order is still + // [sender_sig, receiver_sig, preimage, …], so + // AuxSig (sender) belongs at index 0, ourSig + // (receiver) at index 1. + // Final witness: [AuxSig, ourSig, preimage, script, cb] + // + // Non-breach timeout (TaprootHtlcOfferedTimeoutSecondLevel): + // We *sent* the HTLC on our local commit and are + // timing out. The sender-script timeout leaf has + // witness order [receiver_sig, sender_sig, …], so + // AuxSig (receiver) belongs at index 0, ourSig + // (sender) at index 1. + // Final witness: [AuxSig, ourSig, script, cb] + // + // In all three cases the *other party's* sig is the + // AuxSig and ours is the one we just produced with + // SignVirtualPacket; only the relative ordering on the + // stack differs. + isBreach := req.Type == input.TaprootHtlcSecondLevelRevoke + auxSigInsertIdx := 0 + if isBreach { + auxSigInsertIdx = 1 + } + + // The AuxSig is the remote party's signature for exactly + // the path that was taken on chain: its own second-level + // path is the only 2-of-2 path the HTLC has on the + // commitment it sits on. + assetSigs, decErr := cmsg.DecodeAssetSigListRecord( + auxSigDesc.AuxSig, + ) + if decErr != nil { + return fmt.Errorf("decoding aux sig: %w", decErr) + } + if vPktIdx >= len(assetSigs.Sigs) { + return fmt.Errorf("vPkt index %d out of range (have "+ + "%d aux sigs)", vPktIdx, len(assetSigs.Sigs)) + } + + newAsset := vPkt.Outputs[0].Asset + basePrevWitness := newAsset.PrevWitnesses[0].TxWitness + + remoteSig := assetSigs.Sigs[vPktIdx] + remoteSigBytes := remoteSig.Sig.Val.RawBytes() + remoteSigHashType := txscript.SigHashType( + remoteSig.SigHashType.Val, + ) + + // The witness element must carry the sighash byte when the + // recorded type is not SigHashDefault (BIP 342: 64-byte + // sigs imply default, 65-byte sigs carry the explicit + // flag). Legacy SINGLE|ANYONECANPAY signatures would + // otherwise fail script validation on proof import. + witnessSig := remoteSigBytes + if remoteSigHashType != txscript.SigHashDefault { + sigLen := len(witnessSig) + witnessSig = append( + witnessSig[:sigLen:sigLen], + byte(remoteSigHashType), + ) + } + + bestWitness := make(wire.TxWitness, len(basePrevWitness)) + copy(bestWitness, basePrevWitness) + bestWitness = slices.Insert( + bestWitness, auxSigInsertIdx, witnessSig, + ) + if isSuccessPath && len(preimage) > 0 { + bestWitness = slices.Insert(bestWitness, 2, preimage) + } + + // The sig was verified when we accepted it, but a witness + // built around a sig that does not verify would only fail + // much later, when the proof is checked. So verify it again + // here, against the remote party's HTLC key, and fail right + // away rather than hand out a proof we know to be invalid. + verifyErr := verifyRemoteAuxSig( + bestWitness, remoteSigBytes, remoteSigHashType, vIn, + newAsset, req.KeyRing.RemoteHtlcKey, + ) + if verifyErr != nil { + return fmt.Errorf("aux sig of vPacket %d (htlc_id=%d, "+ + "incoming=%v) is invalid: %w", vPktIdx, htlcID, + isIncoming, verifyErr) + } + + if wErr := newAsset.UpdateTxWitness( + 0, bestWitness, + ); wErr != nil { + return fmt.Errorf("updating witness: %w", wErr) + } + } + + return nil +} + +// importSecondLevelHtlcTx imports the second-level HTLC transition +// proof into the archive with valid asset-level witnesses. +// outCommitments should be the pre-computed output commitments from +// the caller's CreateOutputCommitments call: we must NOT call +// CreateOutputCommitments again because commitPacket mutates +// vOut.AltLeaves in place (appends STXO assets), and a second call +// would produce duplicate alt leaf keys. +func (a *AuxSweeper) importSecondLevelHtlcTx( + req lnwallet.ResolutionReq, + secondLevelPkts []*tappsbt.VPacket, + secondLevelAllocs []*tapsend.Allocation, + outCommitments tappsbt.OutputCommitments, + commitState *cmsg.Commitment) error { + + secondLevel, err := req.SecondLevel.UnwrapOrErr( + fmt.Errorf("no second-level tx provided"), + ) + if err != nil { + return err + } + secondLevelTx := secondLevel.Tx + secondLevelBlockHeight := secondLevel.BlockHeight + + ctx := context.Background() + secondLevelTxHash := secondLevelTx.TxHash() + + // Check if the transfer was already shipped on a previous attempt. + // Even if it was, we must NOT return early here: the caller works + // with freshly reconstructed packets and relies on this function to + // populate their ProofSuffix (via the signing and proof-suffix steps + // below). Returning early would leave the packets without suffixes + // and the caller without valid proofs. Only the final shipping step + // is skipped when the parcel already exists, which makes this + // function idempotent. + existingParcels, err := a.cfg.TxSender.QueryParcels( + ctx, fn.Some(secondLevelTxHash), false, + ) + if err != nil { + return fmt.Errorf("querying second-level parcels: %w", err) + } + alreadyImported := len(existingParcels) > 0 + + log.Infof("Importing second-level HTLC tx %v (height=%d, "+ + "already_imported=%v)", secondLevelTxHash, + secondLevelBlockHeight, alreadyImported) + + stxoFeatures := CommitmentSTXOFeatures(commitState) + + // NOTE: We intentionally skip PrepareOutputAssets here because + // CreateSecondLevelHtlcPackets (the caller that produced + // secondLevelPkts) already calls PrepareOutputAssets. Calling it + // twice would add duplicate alt leaves and cause + // CreateOutputCommitments to fail with ErrDuplicateAltLeafKey. + + // If the AuxSigDesc is available, construct valid asset-level + // witnesses by signing with our local HTLC key and combining + // with the remote party's pre-stored signature. This makes the + // proof chain fully valid and the recovered assets spendable. + log.Infof("Signing second-level HTLC import for tx %v", + secondLevelTxHash) + if err := a.signSecondLevelImport( + req, secondLevelPkts, commitState, + ); err != nil { + return fmt.Errorf("signing second-level import: %w", err) + } + + // NOTE: We use the pre-computed outCommitments passed by the + // caller. We must NOT call CreateOutputCommitments again because + // commitPacket mutates vOut.AltLeaves in place (appends STXO + // assets). A second call would produce duplicate alt leaf keys. + // Similarly, AssignOutputCommitments was already called by the + // caller. + + // The proofs must carry the same alt leaves the pre-signed + // second-level output commits to. + proofOpts := stxoFeatures.ProofOpts() + + // Create proof suffixes. With SIGHASH_DEFAULT, the second-level + // tx is deterministic (1 output), so our allocations cover all + // outputs and exclusion proofs can be properly created. + exclusionCreator := tapsend.NonAssetExclusionProofs( + secondLevelAllocs, + ) + for idx := range secondLevelPkts { + vPkt := secondLevelPkts[idx] + for outIdx := range vPkt.Outputs { + proofSuffix, err := tapsend.CreateProofSuffixCustom( + secondLevelTx, vPkt, outCommitments, + outIdx, secondLevelPkts, + exclusionCreator, proofOpts..., + ) + if err != nil { + return fmt.Errorf("unable to create proof "+ + "suffix for output %d: %w", + outIdx, err) + } + + vPkt.Outputs[outIdx].ProofSuffix = proofSuffix + + log.Debugf("Second-level proof suffix created, "+ + "PrevOut=%v, AnchorTx=%v", + proofSuffix.PrevOut, + proofSuffix.AnchorTx.TxHash()) + } + } + + // Ship the second-level tx. It's already confirmed. + heightHint := fn.None[uint32]() + if secondLevelBlockHeight > 0 { + heightHint = fn.Some(secondLevelBlockHeight) + } + + // If the parcel already exists (a previous attempt shipped it), the + // work above still populated the fresh packets' proof suffixes, and + // re-shipping would only fail on the duplicate. + if alreadyImported { + log.Infof("Second-level tx %v already imported, skipping "+ + "shipping", secondLevelTxHash) + return nil + } + + log.Infof("Shipping second-level HTLC tx %v (height=%d)", + secondLevelTxHash, secondLevelBlockHeight) + err = shipChannelTxn( + a.cfg.TxSender, secondLevelTx, outCommitments, + secondLevelPkts, 0, heightHint, + ) + if err != nil { + return fmt.Errorf("shipping second-level tx: %w", err) + } + + log.Infof("Second-level HTLC import succeeded for tx %v", + secondLevelTxHash) + + return nil +} + +// emptyAssetResolution returns an encoded ContractResolution that carries no +// asset-level packets. It is used on breach paths when the asset-level +// resolution for a single HTLC cannot be constructed (e.g. a revocation log +// written before the HtlcIndex record existed): returning an error would +// abort lnd's NewBreachRetribution as a whole and block the BTC-level +// justice sweep for the entire channel, which is strictly worse than +// forgoing the asset leg of one HTLC. +func emptyAssetResolution() lfn.Result[tlv.Blob] { + res := cmsg.NewContractResolution( + nil, nil, lfn.None[cmsg.TapscriptSigDesc](), false, false, + ) + + var b bytes.Buffer + if err := res.Encode(&b); err != nil { + return lfn.Err[tlv.Blob](err) + } + + return lfn.Ok(b.Bytes()) +} + +// htlcBucketKeys returns the sorted HTLC indices present in the given asset +// bucket, for diagnostics. +func htlcBucketKeys(bucket cmsg.HtlcAssetOutput) []uint64 { + keys := make([]uint64, 0, len(bucket.HtlcOutputs)) + for k := range bucket.HtlcOutputs { + keys = append(keys, k) + } + slices.Sort(keys) + + return keys +} + +// errNoPayHash is an error returned when no payment hash is provided. +var errNoPayHash = fmt.Errorf("no payment hash provided") + +// errNoHtlcID is an error returned when no HTLC ID is provided for a keyspend +// scenario that requires it. +var errNoHtlcID = fmt.Errorf("no HTLC ID provided for keyspend") + +// resolveContract takes in a resolution request and resolves it by creating a +// serialized resolution blob that contains the virtual packets needed to sweep +// the funds from the contract. +func (a *AuxSweeper) resolveContract( + req lnwallet.ResolutionReq) lfn.Result[tlv.Blob] { + + type returnType = tlv.Blob + + // If there's no commit blob, then there's nothing to resolve. + if req.CommitBlob.IsNone() { + return lfn.Err[tlv.Blob](nil) + } + + log.Infof("Generating resolution_blob for contract_type=%v, "+ + "chan_point=%v", req.Type, req.ChanPoint) + + // As we have a commit blob, we'll decode the commit blob, so we can + // have access to all the active outputs. We'll also decode the funding + // blob, so we can make vInt from it. + commitState, err := tapchannelmsg.DecodeCommitment( + req.CommitBlob.UnwrapOr(nil), + ) + if err != nil { + return lfn.Err[returnType](err) + } + fundingInfo, err := tapchannelmsg.DecodeOpenChannel( + req.FundingBlob.UnwrapOr(nil), + ) + if err != nil { + return lfn.Err[returnType](err) + } + + // Extract the HTLC ID from the request. HTLC resolution types + // require a valid ID; commit output types don't use it. We + // unwrap here and check the error in cases that need it, + // rather than silently using a bogus index with + // FilterByHtlcIndex. + htlcID, htlcIDErr := req.HtlcID.UnwrapOrErr( + fmt.Errorf("no HTLC ID in resolution request"), + ) + + var ( + sweepDesc lfn.Result[tapscriptSweepDescs] + assetOutputs []*cmsg.AssetOutput + needsSecondLevel bool + ) + + switch req.Type { + // A non-delay output. This means the remote party force closed on + // chain. + case input.TaprootRemoteCommitSpend: + // In this case, we'll be resolving the set of remote + // assets, on the remote party's commitment, which are actually + // our assets. + assetOutputs = commitState.RemoteAssets.Val.Outputs + + // First, we'll make a sweep desc for the commitment txn. This + // contains the tapscript tree, and also the control block + // needed for a valid spend. + sweepDesc = commitNoDelaySweepDesc(req.KeyRing, req.CsvDelay) + + // A normal delay output. This means we force closed, so we'll need to + // mind the CSV when we sweep the output. + case input.TaprootLocalCommitSpend: + // In this case, we'll be resolving the set of local assets on + // our commitment. + assetOutputs = commitState.LocalAssets.Val.Outputs + + // Next, we'll make a sweep desc for this output. It's + // dependent on the CSV delay we have in this channel, so we'll + // pass that in as well. + sweepDesc = commitDelaySweepDesc(req.KeyRing, req.CsvDelay) + + // The remote party has breached the channel. We'll sweep the revoked + // key that we learned in the past. + case input.TaprootCommitmentRevoke: + // outputs, as they broadcast a revoked commitment. For the + // In this case, we'll be sweeping the remote party's asset + // remote party, this is actually their local output. + assetOutputs = commitState.LocalAssets.Val.Outputs + + // Next, we'll make a sweep desk capable of sweeping the remote + // party's local output. + sweepDesc = commitRevokeSweepDesc(req.KeyRing, req.CsvDelay) + + // The remote party broadcasted a commitment transaction which held an + // HTLC that we can timeout eventually. + case input.TaprootHtlcOfferedRemoteTimeout: + // In this case, we're interested in sweeping the incoming + // assets for the remote party, which are actually the HTLCs we + // sent outgoing. We only care about this particular HTLC, so + // we'll filter out the rest. + if htlcIDErr != nil { + return lfn.Err[returnType](htlcIDErr) + } + htlcOutputs := commitState.OutgoingHtlcAssets.Val + assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) + + payHash, err := req.PayHash.UnwrapOrErr(errNoPayHash) + if err != nil { + return lfn.Err[tlv.Blob](err) + } + + // Now that we know which output we'll be sweeping, we'll make a + // sweep desc for the timeout txn. + sweepDesc = remoteHtlcTimeoutSweepDesc( + req.KeyRing, payHash[:], req.CsvDelay, + req.CltvDelay.UnwrapOr(0), htlcID, + ) + + // The remote party broadcasted a commitment transaction which held an + // outgoing HTLC that we may claim with a preimage. + case input.TaprootHtlcAcceptedRemoteSuccess: + // In this case, it's an outgoing HTLC from the PoV of the + // remote party, which is incoming for us. We'll only sweep this + // HTLC, so we'll filter out the rest. + if htlcIDErr != nil { + return lfn.Err[returnType](htlcIDErr) + } + htlcOutputs := commitState.IncomingHtlcAssets.Val + assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) payHash, err := req.PayHash.UnwrapOrErr(errNoPayHash) if err != nil { @@ -2396,7 +3385,9 @@ func (a *AuxSweeper) resolveContract( case input.TaprootHtlcLocalOfferedTimeout: // Like the other HTLC cases, there's only a single output we // care about here. - htlcID := req.HtlcID.UnwrapOr(math.MaxUint64) + if htlcIDErr != nil { + return lfn.Err[returnType](htlcIDErr) + } htlcOutputs := commitState.OutgoingHtlcAssets.Val assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) @@ -2411,7 +3402,9 @@ func (a *AuxSweeper) resolveContract( // needed to sweep both this output, as well as the second level // output it creates. case input.TaprootHtlcAcceptedLocalSuccess: - htlcID := req.HtlcID.UnwrapOr(math.MaxUint64) + if htlcIDErr != nil { + return lfn.Err[returnType](htlcIDErr) + } htlcOutputs := commitState.IncomingHtlcAssets.Val assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) @@ -2421,14 +3414,528 @@ func (a *AuxSweeper) resolveContract( needsSecondLevel = true - default: - // TODO(guggero): Need to do HTLC revocation cases here. - // IMPORTANT: Remember that we applied the HTLC index as a tweak - // to the revocation key on the asset level! That means the - // tweak to the first-level HTLC script key's internal key - // (which is the revocation key) MUST be applied when creating - // a breach sweep transaction! + // Revoked HTLC offered by remote party (outgoing HTLC from their side). + // We sweep this using the revocation key (keyspend). + case input.TaprootHtlcOfferedRevoke: + // Filter for the specific HTLC we're sweeping. + // TaprootHtlcOfferedRevoke covers an HTLC that we offered to + // the remote party (see input/witnessgen.go), i.e. our + // outgoing HTLC. The commitment blob indexes the HTLC asset + // buckets from our perspective, so it lives in + // OutgoingHtlcAssets. We sweep it using the revocation key + // since they broadcast a revoked state. + if htlcIDErr != nil { + // A missing HTLC ID on the breach path must not + // abort the whole retribution: degrade to an empty + // asset resolution so the BTC-level justice sweep + // can proceed. + log.Errorf("No HTLC ID for %v resolution "+ + "(chan_point=%v, commit_height=%d), "+ + "returning empty asset resolution: %v", + req.Type, req.ChanPoint, + req.CommitTxBlockHeight, htlcIDErr) + + return emptyAssetResolution() + } + htlcOutputs := commitState.OutgoingHtlcAssets.Val + assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) + + if len(assetOutputs) == 0 { + log.Errorf("HTLC ID %d not found in outgoing assets "+ + "for %v resolution (chan_point=%v, "+ + "num_outgoing=%d, num_incoming=%d), asset "+ + "leg of this HTLC will not be swept", htlcID, + req.Type, req.ChanPoint, + len(commitState.OutgoingHtlcAssets.Val. + HtlcOutputs), + len(commitState.IncomingHtlcAssets.Val. + HtlcOutputs)) + } + + payHash, err := req.PayHash.UnwrapOrErr(errNoPayHash) + if err != nil { + return lfn.Err[tlv.Blob](err) + } + + htlcExpiry := req.CltvDelay.UnwrapOr(0) + + // Create sweep descriptor for revoked offered HTLC. + sweepDesc = htlcOfferedRevokeSweepDesc( + req.KeyRing, payHash[:], htlcExpiry, htlcID, + ) + + // Revoked HTLC accepted by remote party (incoming HTLC from their + // side). We sweep this using the revocation key (keyspend). + case input.TaprootHtlcAcceptedRevoke: + // Filter for the specific HTLC we're sweeping. We sent this + // HTLC to the remote party (they accepted/received it), so from + // their PoV it's incoming and stored in their + // IncomingHtlcAssets. We sweep it using the revocation key + // since they broadcast a revoked state. + if htlcIDErr != nil { + // See the TaprootHtlcOfferedRevoke case above: on the + // breach path we degrade instead of aborting the + // whole retribution. + log.Errorf("No HTLC ID for %v resolution "+ + "(chan_point=%v, commit_height=%d), "+ + "returning empty asset resolution: %v", + req.Type, req.ChanPoint, + req.CommitTxBlockHeight, htlcIDErr) + + return emptyAssetResolution() + } + htlcOutputs := commitState.IncomingHtlcAssets.Val + assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) + + if len(assetOutputs) == 0 { + log.Errorf("HTLC ID %d not found in incoming assets "+ + "for %v resolution (chan_point=%v, "+ + "num_outgoing=%d, num_incoming=%d), asset "+ + "leg of this HTLC will not be swept", htlcID, + req.Type, req.ChanPoint, + len(commitState.OutgoingHtlcAssets.Val. + HtlcOutputs), + len(commitState.IncomingHtlcAssets.Val. + HtlcOutputs)) + } + + payHash, err := req.PayHash.UnwrapOrErr(errNoPayHash) + if err != nil { + return lfn.Err[tlv.Blob](err) + } + + // Create sweep descriptor for revoked accepted HTLC. + sweepDesc = htlcAcceptedRevokeSweepDesc( + req.KeyRing, payHash[:], htlcID, + ) + + // Second-level HTLC sweeps: + // + // * TaprootHtlcSecondLevelRevoke: breach justice flow. + // * TaprootHtlcAcceptedSuccessSecondLevel: non-breach local + // incoming HTLC, after we settled and our pre-signed + // 2nd-level success tx has confirmed. + // * TaprootHtlcOfferedTimeoutSecondLevel: non-breach local + // outgoing HTLC, after timeout and our pre-signed 2nd-level + // timeout tx has confirmed. + // + // All three need the same proof-archive import side-effect for + // the second-level tx (the htlc_success/timeout resolvers + // re-resolve here once the 2nd-level tx confirms; the breach + // arbitrator does it as part of justice-tx assembly). They differ + // only in which HTLC asset bucket holds the outputs and in the + // final sweep descriptor. + case input.TaprootHtlcSecondLevelRevoke, + input.TaprootHtlcAcceptedSuccessSecondLevel, + input.TaprootHtlcOfferedTimeoutSecondLevel: + + isRevoke := req.Type == input.TaprootHtlcSecondLevelRevoke + + // Extract the optional second-level tx info once for use + // throughout this branch. The Option is None when the + // resolver hasn't yet observed the second-level tx on + // chain (e.g. early breach paths). + var ( + secondLevelTx *wire.MsgTx + secondLevelTxBlockHeight uint32 + ) + req.SecondLevel.WhenSome(func(sl lnwallet.SecondLevelInfo) { + secondLevelTx = sl.Tx + secondLevelTxBlockHeight = sl.BlockHeight + }) + + if htlcIDErr != nil { + // On the breach path a missing HTLC ID must not + // abort the whole retribution (see the + // TaprootHtlcOfferedRevoke case above). The + // non-breach second-level requests are made per HTLC + // by the resolvers, which always know the index, so + // a hard error there only fails that HTLC's + // resolution. + if isRevoke { + log.Errorf("No HTLC ID for %v resolution "+ + "(chan_point=%v, commit_height=%d), "+ + "returning empty asset resolution: %v", + req.Type, req.ChanPoint, + req.CommitTxBlockHeight, htlcIDErr) + + return emptyAssetResolution() + } + + return lfn.Err[returnType](htlcIDErr) + } + + // These flows rest on the pre-signed, deterministic + // second-level HTLC tx: one input, the commitment HTLC + // output, and the HTLC output at index 0. On a commitment + // that was built without DeterministicHTLCs the second-level + // tx is rebuilt by the sweeper and may bundle other inputs + // and outputs, which none of what follows accounts for. + // lnd is told so and keeps resolving the HTLC the way it did + // before these flows existed. + if !commitState.SigHashDefault.Val { + return lfn.Errf[returnType]("%v resolution is not "+ + "supported for chan_point=%v: its commitment "+ + "was built without deterministic HTLCs", + req.Type, req.ChanPoint) + } + if secondLevelTx == nil { + return lfn.Errf[returnType]("no second-level tx on "+ + "%v resolution request for chan_point=%v", + req.Type, req.ChanPoint) + } + commitTxHash := req.CommitTx.TxHash() + if len(secondLevelTx.TxIn) != 1 || + secondLevelTx.TxIn[0].PreviousOutPoint.Hash != + commitTxHash { + + return lfn.Errf[returnType]("second-level tx %v of "+ + "chan_point=%v is not a deterministic HTLC tx "+ + "spending commitment %v", + secondLevelTx.TxHash(), req.ChanPoint, + commitTxHash) + } + + // The commitment blob indexes the HTLC asset buckets from + // our point of view by HTLC index. An index regularly exists + // in both buckets, so the bucket is picked by the HTLC's + // direction, never by probing for the index. + incoming, err := secondLevelHtlcIncoming(req) + if err != nil { + return lfn.Err[returnType](err) + } + + auxLeaves := commitState.AuxLeaves.Val + htlcOutputs := commitState.OutgoingHtlcAssets.Val + htlcLeaves := auxLeaves.OutgoingHtlcLeaves.Val.HtlcAuxLeaves + if incoming { + htlcOutputs = commitState.IncomingHtlcAssets.Val + htlcLeaves = auxLeaves.IncomingHtlcLeaves.Val. + HtlcAuxLeaves + } + assetOutputs = htlcOutputs.FilterByHtlcIndex(htlcID) + + // The aux leaf of the second-level output commits to the + // CLTV timeout exactly when the second-level tx is a timeout + // tx, which is the path of the party that offered the HTLC + // on its own commitment. See aux_leaf_creator.go, where the + // leaves are computed per commitment. We must mirror that + // here so the reconstructed asset commitment matches the + // on-chain one. + // + // * Breach: the commitment is the remote party's, and it + // offered the HTLCs that are incoming to us. + // * Our own commitment: we offered the outgoing HTLCs. + var cltvTimeout fn.Option[uint32] + if incoming == isRevoke { + req.CltvDelay.WhenSome(func(v uint32) { + cltvTimeout = fn.Some(v) + }) + } + // An HTLC that is not in its asset bucket AND has no aux leaf + // is a BTC-only HTLC on an asset channel: it needs no + // asset-level resolution and this is the common, legitimate + // case. An HTLC that has an aux leaf but no bucket entry is + // an asset HTLC we failed to locate, which means its asset + // leg will not be swept: that is an error worth shouting + // about. + if len(assetOutputs) == 0 { + _, hasLeaf := htlcLeaves[htlcID] + if hasLeaf { + log.Errorf("HTLC ID %d (incoming=%v) has an "+ + "aux leaf but no asset bucket entry "+ + "(chan_point=%v, bucket_ids=%v), "+ + "asset leg of this HTLC will not be "+ + "swept", htlcID, incoming, + req.ChanPoint, + htlcBucketKeys(htlcOutputs)) + } else { + log.Debugf("HTLC ID %d (incoming=%v) not "+ + "found in its asset bucket and has "+ + "no aux leaf, treating as BTC-only "+ + "HTLC", htlcID, incoming) + } + } + + // Save the commitment-level asset outputs before they're + // replaced, as we need them for importing the second-level + // tx (which takes commitment-level inputs). + commitAssetOutputs := assetOutputs + + // Re-anchor the commitment-level asset outputs to the real + // commitment tx BEFORE creating second-level packets. + // CreateSecondLevelHtlcPackets copies the proofs from + // these outputs, so the proofs must have correct block + // headers before the copy. + // + // A failure here is returned rather than papered over: the + // packets built from proofs that are not anchored to the + // real commitment tx could never yield a valid proof chain. + // lnd then sweeps the BTC of this output without the asset + // leg, and every other output of the channel is unaffected. + ctxImport := context.Background() + if err := reanchorAssetOutputs( + ctxImport, a.cfg.ChainBridge, *req.CommitTx, + req.CommitTxBlockHeight, commitAssetOutputs, + ); err != nil { + return lfn.Errf[returnType]("unable to re-anchor "+ + "commit asset outputs for second-level "+ + "import: %w", err) + } + + // Construct a minimal AuxChanState for the second-level + // packet creation. The CSV delay here must be the + // commitment CSV (req.CommitCsvDelay), which is what + // createSecondLevelHtlcAllocations reads via + // chanState.LocalChanCfg.CsvDelay. The breach path + // historically passed req.CsvDelay because for breach + // resolution req.CsvDelay carries the breaching party's + // commit CSV; for the non-breach success/timeout flows + // req.CsvDelay is the HTLC CSV and we must use + // CommitCsvDelay instead. + commitCsv := req.CommitCsvDelay + if isRevoke { + commitCsv = req.CsvDelay + } + auxChanState := lnwallet.AuxChanState{ + ChanType: req.ChanType, + IsInitiator: req.Initiator, + LocalChanCfg: channeldb.ChannelConfig{ + CommitmentParams: channeldb.CommitmentParams{ + CsvDelay: uint16(commitCsv), + }, + }, + } + + // Create the second-level virtual packets. This gives us + // both the aux leaf (for the sweep descriptor) AND the + // output assets with the correct second-level script keys. + // The proofs from commitAssetOutputs are now re-anchored + // with the correct block headers. + // + // Use the actual on-chain second-level tx output value (after + // fee deduction) rather than the HTLC amount. The signer used + // the fee-deducted value when creating the second-level tx. + // + // The pre-signed deterministic tx has its HTLC output at + // index 0, followed by the anchor. + secondLevelBtcAmt := btcutil.Amount( + secondLevelTx.TxOut[0].Value, + ) + secondLevelHasAnchor := len(secondLevelTx.TxOut) > 1 + + secondLevelPkts, secondLevelAllocs, err := + CreateSecondLevelHtlcPackets( + auxChanState, req.CommitTx, + secondLevelBtcAmt, *req.KeyRing, + &a.cfg.ChainParams, assetOutputs, + cltvTimeout, htlcID, secondLevelHasAnchor, + ) + if err != nil { + return lfn.Errf[returnType]("unable to create "+ + "second-level packets: %w", err) + } + + // Compute the aux leaf from the allocations (same as + // CreateSecondLevelHtlcTx does), with the same alt leaves + // the pre-signed output commits to. + stxoFeatures := CommitmentSTXOFeatures(commitState) + outCommitments, err := tapsend.CreateOutputCommitments( + secondLevelPkts, stxoFeatures.CommitOpts()..., + ) + if err != nil { + return lfn.Errf[returnType]("unable to create "+ + "output commitments: %w", err) + } + err = tapsend.AssignOutputCommitments( + secondLevelAllocs, outCommitments, + ) + if err != nil { + return lfn.Errf[returnType]("unable to assign "+ + "output commitments: %w", err) + } + + // Import the second-level tx into the proof archive. This + // creates the commitment → second-level proof transition + // so the sweep can build a valid proof chain. + // + // If the import fails, so does the resolution. There is no + // useful blob to hand out without it: a sweep built on a + // proof we could not produce, or know to be invalid, fails + // proof verification once it is broadcast, at which point + // nothing can be done about it anymore. lnd handles the + // error by sweeping the BTC of this output without the asset + // leg. + if len(assetOutputs) > 0 { + err = a.importSecondLevelHtlcTx( + req, secondLevelPkts, secondLevelAllocs, + outCommitments, commitState, + ) + if err != nil { + return lfn.Errf[returnType]("unable to import "+ + "second-level HTLC tx: %w", err) + } + } + + // Replace the commitment-level asset outputs with the + // second-level outputs from the vPackets. After a + // successful import, each vPkt output has a valid + // ProofSuffix with correct inclusion proof, block + // header, merkle proof, and asset data. Use that + // directly instead of building a stub from the + // commitment-level proof. + // Match each second-level packet back to the commitment-level + // asset output it spends via the packet input's PrevID + // (asset ID + script key): packet generation groups and + // orders by asset ID, so the packet list is NOT positionally + // aligned with the blob's output list (grouped assets or + // multiple UTXOs per HTLC would be paired with the wrong + // proof otherwise). + findSourceOutput := func( + vPkt *tappsbt.VPacket) *cmsg.AssetOutput { + + if len(vPkt.Inputs) == 0 { + return nil + } + prevID := vPkt.Inputs[0].PrevID + + for _, ao := range assetOutputs { + srcAsset := ao.Proof.Val.Asset + srcKey := asset.ToSerialized( + srcAsset.ScriptKey.PubKey, + ) + if srcAsset.ID() == prevID.ID && + srcKey == prevID.ScriptKey { + + return ao + } + } + + return nil + } + + var secondLevelAssetOutputs []*cmsg.AssetOutput + for i, vPkt := range secondLevelPkts { + if len(vPkt.Outputs) == 0 { + continue + } + + vOut := vPkt.Outputs[0] + srcOut := findSourceOutput(vPkt) + if srcOut == nil { + log.Errorf("No commitment-level asset "+ + "output matches second-level "+ + "packet %d (num_outputs=%d), "+ + "skipping", i, len(assetOutputs)) + + continue + } + + if vOut.ProofSuffix == nil { + return lfn.Errf[returnType]("second-level "+ + "packet %d has no proof suffix after "+ + "import", i) + } + + // Use the proof suffix from the successful import: + // it has the correct inclusion proof and taproot + // commitment for the 2nd-level output. But the block + // data may not be populated yet (the porter + // finalizes asynchronously), so we add it here. + if secondLevelTxBlockHeight > 0 { + stxParams, err := proofParamsForCommitTx( + ctxImport, a.cfg.ChainBridge, + secondLevelTxBlockHeight, + *secondLevelTx, + ) + if err != nil { + return lfn.Errf[returnType]("unable "+ + "to get proof params for "+ + "second-level tx: %w", err) + } + + err = vOut.ProofSuffix.UpdateTransitionProof( + &stxParams, + ) + if err != nil { + return lfn.Errf[returnType]("unable "+ + "to update second-level "+ + "proof: %w", err) + } + } + + secondLevelAssetOutputs = append( + secondLevelAssetOutputs, + cmsg.NewAssetOutput( + vOut.Asset.ID(), vOut.Asset.Amount, + *vOut.ProofSuffix, + ), + ) + } + + if len(secondLevelAssetOutputs) > 0 { + assetOutputs = secondLevelAssetOutputs + } + + log.Infof("Second-level sweep: type=%v, htlcID=%d, "+ + "numAssetOutputs=%d, csvDelay=%d", + req.Type, htlcID, len(assetOutputs), req.CsvDelay) + + for i, ao := range assetOutputs { + log.Infof(" assetOutput[%d]: scriptKey=%x, "+ + "amount=%d", + i, + ao.Proof.Val.Asset.ScriptKey.PubKey. + SerializeCompressed(), + ao.Amount.Val) + } + + // Select the sweep descriptor based on the witness type. + // The breach path uses the revocation keyspend (the + // 2nd-level output's tap tree's INTERNAL KEY is the + // revocation key, so no merkle path is needed). The + // non-breach success/timeout paths spend via the + // CSV-delayed success leaf, so the control block must + // commit to the full on-chain tap tree which includes + // the asset commitment's AUX LEAF as a sibling. We get + // the aux leaf from the allocation we just produced (it + // matches the leaf the channel peer baked into the + // pre-signed 2nd-level tx at commitment construction). + switch { + case isRevoke: + sweepDesc = htlcSecondLevelRevokeSweepDesc( + req.KeyRing, req.CsvDelay, htlcID, + ) + default: + var auxLeaf lfn.Option[txscript.TapLeaf] + if len(secondLevelAllocs) > 0 { + l, leafErr := secondLevelAllocs[0].AuxLeaf() + if leafErr != nil { + return lfn.Errf[returnType]( + "unable to derive second-"+ + "level aux leaf: %w", + leafErr, + ) + } + auxLeaf = lfn.Some(l) + } + // For non-breach 2nd-level OUTPUT sweep (success or + // timeout), the witness must verify against the + // asset-level script key, which is the tweaked + // taproot key of the asset-level tree. For breach + // (TaprootHtlcSecondLevelRevoke), keyspend is used + // and no control-block verification path runs - + // keep the existing BTC-level desc to avoid + // disturbing the breach flow. + assetLevelDesc := !isRevoke + sweepDesc = secondLevelHtlcOutputSweepDesc( + req.KeyRing, req.CommitCsvDelay, auxLeaf, + req.HtlcID, assetLevelDesc, + ) + } + + default: return lfn.Errf[returnType]("unknown resolution type: %v", req.Type) } @@ -2496,12 +4003,25 @@ func (a *AuxSweeper) resolveContract( // The input proofs above were made originally using the fake commit tx // as an anchor. We now know the real commit tx, so we'll bind each // proof to the actual commitment output that carries the asset. - if err := reanchorAssetOutputs( - ctx, a.cfg.ChainBridge, commitTx, req.CommitTxBlockHeight, - assetOutputs, - ); err != nil { - return lfn.Errf[returnType]("unable to re-anchor asset "+ - "outputs: %w", err) + // For all second-level sweep flows the asset outputs have already + // been replaced with second-level outputs (anchored to the + // second-level tx) earlier in this function, so we skip re-anchoring + // to the commitment tx: doing so would fail to find a matching + // commit output. + isSecondLevelSweep := req.Type == input.TaprootHtlcSecondLevelRevoke || + req.Type == input.TaprootHtlcAcceptedSuccessSecondLevel || + req.Type == input.TaprootHtlcOfferedTimeoutSecondLevel + if !isSecondLevelSweep { + // For second-level sweeps, the proof's AnchorTx and + // OutputIndex are set above to reference the second-level + // tx. For all other types, re-anchor to the commitment tx. + if err := reanchorAssetOutputs( + ctx, a.cfg.ChainBridge, commitTx, + req.CommitTxBlockHeight, assetOutputs, + ); err != nil { + return lfn.Errf[returnType]("unable to re-anchor "+ + "asset outputs: %w", err) + } } // With the proofs bound to the confirmed commitment transaction, we @@ -2522,6 +4042,29 @@ func (a *AuxSweeper) resolveContract( len(assetOutputs), needsSecondLevel, limitSpewer.Sdump(assetOutputs)) + // For the non-breach 2nd-level OUTPUT sweep types we don't have a + // real first-level sweep to construct: the corresponding 2nd-level + // HTLC tx was already published by lnd's resolver directly, and what + // we're producing here is just the asset-level blob for the + // subsequent output sweep. Construct that blob directly using the + // placeholder secondLevelPkts pattern that the existing + // needsSecondLevel branch relies on, so the sweeper's later + // SetAnchorInternalKey / signSweepVpackets steps work the same way + // they do for a normal force-close OUTPUT sweep. + // + // The breach revocation case (isRevoke) keeps the original + // firstLevel-only blob shape: its OUTPUT sweep is a single keyspend + // via the revocation key, no second-level signing layer is needed. + isNonBreachSecondLevelOutput := + req.Type == input.TaprootHtlcAcceptedSuccessSecondLevel || + req.Type == input.TaprootHtlcOfferedTimeoutSecondLevel + if isNonBreachSecondLevelOutput { + return a.buildSecondLevelOutputSweepBlob( + req, assetOutputs, tapSweepDesc, + CommitmentSTXOFeatures(commitState), + ) + } + // With the sweep desc constructed above, we'll create vPackets for each // of the local assets, then sign them all. firstLevelPkts, err := a.createAndSignSweepVpackets( @@ -2617,6 +4160,90 @@ func (a *AuxSweeper) resolveContract( return lfn.Ok(b.Bytes()) } +// buildSecondLevelOutputSweepBlob constructs the resolution blob returned +// for the non-breach 2nd-level output sweep witness types +// (TaprootHtlcAcceptedSuccessSecondLevel / +// TaprootHtlcOfferedTimeoutSecondLevel). +// +// Under DeterministicHTLCs the second-level HTLC tx is published directly +// by the resolver via PublishTx; we're called from the sweep success / +// timeout resolver's re-resolve hook after it's already confirmed, with +// assetOutputs already replaced by the post-import second-level outputs. +// +// The resulting blob mirrors the *second-level half* that the original +// force-close blob would have carried under the normal needsSecondLevel +// path: a single placeholder second-level vPacket whose AnchorOutputIndex +// and AnchorOutputInternalKey are left for the sweeper to fill in at +// sweep time, plus a TapscriptSigDesc that tells the sweeper how to +// re-sign once the actual sweep tx is known. +func (a *AuxSweeper) buildSecondLevelOutputSweepBlob(req lnwallet.ResolutionReq, + assetOutputs []*cmsg.AssetOutput, tapSweepDesc tapscriptSweepDescs, + stxoFeatures STXOFeatures) lfn.Result[tlv.Blob] { + + type returnType = tlv.Blob + + // We carry the asset state at the 2nd-level output into the + // sweep packets as placeholders: exactly as the + // needsSecondLevel branch does. The sweeper later updates the + // AnchorOutputInternalKey on each output and re-signs via + // signSweepVpackets using the TapscriptSigDesc we attach below. + secondLevelInputs := fn.Map( + assetOutputs, + func(a *cmsg.AssetOutput) *cmsg.AssetOutput { + return cmsg.NewAssetOutput( + a.AssetID.Val, a.Amount.Val, a.Proof.Val, + ) + }, + ) + + secondLevelPkts, err := a.createSweepVpackets( + secondLevelInputs, lfn.Ok(tapSweepDesc.firstLevel), req, + ).Unpack() + if err != nil { + return lfn.Errf[returnType]("unable to build second-level "+ + "output sweep pkts: %w", err) + } + + // Bind each vPacket input to the actual asset state at the + // 2nd-level output (the asset whose proof we just imported). + for pktIdx, vPkt := range secondLevelPkts { + if pktIdx >= len(assetOutputs) { + return lfn.Errf[returnType]("vPkt index %d out of "+ + "range (have %d assetOutputs)", pktIdx, + len(assetOutputs)) + } + prevAsset := assetOutputs[pktIdx].Proof.Val.Asset + + for inputIdx, vIn := range vPkt.Inputs { + vIn.PrevID.ScriptKey = asset.ToSerialized( + prevAsset.ScriptKey.PubKey, + ) + vPkt.SetInputAsset(inputIdx, &prevAsset) + } + } + + // Synthesize the SigDesc from the same sweep descriptor we built + // for the output spend. The sweeper uses TapTweak / CtrlBlock to + // produce the sweep tx's spending witness once the sweep txid is + // known. + secondLevelSigDesc := lfn.Some(cmsg.NewTapscriptSigDesc( + tapSweepDesc.firstLevel.scriptTree.TapTweak(), + tapSweepDesc.firstLevel.ctrlBlockBytes, + )) + + res := cmsg.NewContractResolution( + nil, secondLevelPkts, secondLevelSigDesc, stxoFeatures.STXO, + stxoFeatures.Spender, + ) + + var b bytes.Buffer + if err := res.Encode(&b); err != nil { + return lfn.Err[tlv.Blob](err) + } + + return lfn.Ok(b.Bytes()) +} + // preimageDesc is a helper struct that contains the preimage and the witness // index that the preimage should be placed within the witness stack. This is // useful as in an earlier step, we've already pre-signed the witness, but will @@ -2943,7 +4570,7 @@ func (a *AuxSweeper) sweepContracts(inputs []input.Input, return lfn.Ok(sweep.SweepOutput{ TxOut: wire.TxOut{ PkScript: anchorPkScript, - Value: int64(tapsend.DummyAmtSats), + Value: int64(sweepAnchorOutputAmt), }, IsExtra: true, InternalKey: lfn.Some(internalKey), @@ -3062,7 +4689,8 @@ func reanchorDirectSweeps(directPkts []*tappsbt.VPacket, sweepTx *wire.MsgTx, // transition proof for it, then registering the sweep with the porter. func (a *AuxSweeper) registerAndBroadcastSweep(req *sweep.BumpRequest, sweepTx *wire.MsgTx, fee btcutil.Amount, - outpointToTxIndex map[wire.OutPoint]int) error { + outpointToTxIndex map[wire.OutPoint]int, + opts sweep.AuxNotifyOpts) error { // Replacement handling. A sweep replacement (RBF, CPFP, or an // input-set change on fee-bump) reaches here as a fresh call @@ -3076,6 +4704,24 @@ func (a *AuxSweeper) registerAndBroadcastSweep(req *sweep.BumpRequest, // UTXOs unswept, leases released, passive assets restored), so // no upsert-in-place is required here — form-change composition // handles it structurally. + + // Check if this sweep was already registered (e.g. after a + // restart). The porter's InsertAssetTransfer is a plain INSERT, + // so duplicate calls would create duplicate transfer rows. + sweepTxHash := sweepTx.TxHash() + + existingParcels, err := a.cfg.TxSender.QueryParcels( + context.Background(), fn.Some(sweepTxHash), false, + ) + if err != nil { + return fmt.Errorf("querying sweep parcels: %w", err) + } + if len(existingParcels) > 0 { + log.Infof("Sweep tx %v already registered, skipping", + sweepTxHash) + return nil + } + log.Infof("Register broadcast of sweep_tx=%v", limitSpewer.Sdump(sweepTx)) @@ -3116,6 +4762,76 @@ func (a *AuxSweeper) registerAndBroadcastSweep(req *sweep.BumpRequest, return err } + // For first level outputs, ensure PrevID.OutPoint matches the actual + // BTC input outpoint. This is critical for second-level revoke inputs + // where the vPacket's PrevID.OutPoint still references the commitment + // HTLC output, but the justice tx actually spends the second-level tx + // output. Without this update, the Porter cannot find the input proof. + for _, sweepSet := range vPkts.firstLevel { + actualOutpoint := sweepSet.btcInput.OutPoint() + for _, vPkt := range sweepSet.vPkts { + for _, vIn := range vPkt.Inputs { + if vIn.PrevID.OutPoint != actualOutpoint { + log.Infof("Updating firstLevel "+ + "PrevID.OutPoint from %v "+ + "to %v", + vIn.PrevID.OutPoint, + actualOutpoint) + + vIn.PrevID.OutPoint = actualOutpoint + } + } + + for _, vOut := range vPkt.Outputs { + prevWit := &vOut.Asset.PrevWitnesses[0] + if prevWit.PrevID.OutPoint != actualOutpoint { + prevWit.PrevID.OutPoint = actualOutpoint + } + } + } + } + + // If LookupInputProofs is set, replace the stale proofs in the + // vPacket inputs with the latest proofs from the archive. This + // is needed when the resolution blob carries a commit-level + // proof but the asset has since been imported at the + // second-level (e.g. after a breach second-level HTLC import). + if opts.LookupInputProofs { + ctx := context.Background() + + // Only look up proofs for inputs that are spending + // second-level HTLC outputs. These carry stale + // commit-level proofs that need replacing with the + // imported second-level proof. Regular first-level + // sweeps have correct proofs in their resolution blob. + isSecondLevelInput := func(inp input.Input) bool { + wt := inp.WitnessType() + return wt == input.HtlcSecondLevelRevoke || + wt == input.TaprootHtlcSecondLevelRevoke + } + for _, sweepPkt := range vPkts.firstLevel { + if !isSecondLevelInput(sweepPkt.btcInput) { + continue + } + for _, vPkt := range sweepPkt.vPkts { + for _, vIn := range vPkt.Inputs { + last, err := a.fetchInputProof(ctx, vIn) + if err != nil { + return err + } + + log.Infof("Replaced input proof for "+ + "%v (AnchorTx=%v, PrevOut=%v)", + vIn.PrevID.OutPoint, + last.AnchorTx.TxHash(), + last.PrevOut) + + vIn.Proof = last + } + } + } + } + // For any second level outputs we're sweeping, we'll need to sign for // it, as now we know the txid of the sweeping transaction. for _, sweepSet := range vPkts.secondLevel { @@ -3216,28 +4932,80 @@ func (a *AuxSweeper) registerAndBroadcastSweep(req *sweep.BumpRequest, log.Infof("Proofs generated for sweep_tx=%v", limitSpewer.Sdump(sweepTx)) - // Add a best-effort height hint for sweep transactions. If the sweep is - // mined quickly, this helps the confirmation registration catch up - // deterministically when we hand the parcel to the porter. + // Add a best-effort height hint for sweep transactions. If the + // caller provided a confirmation height (e.g. from a confirmed + // justice tx), use it directly: this is critical when the tx was + // confirmed several blocks ago and the chain tip has advanced past + // it. Otherwise, fall back to the current height. heightHint := fn.None[uint32]() - currentHeight, err := a.cfg.ChainBridge.CurrentHeight( - context.Background(), - ) - if err != nil { - log.Warnf("Unable to fetch current height for sweep tx %v "+ - "height hint: %v", sweepTx.TxHash(), err) + if opts.ConfirmHeight > 0 { + heightHint = fn.Some(opts.ConfirmHeight) } else { - heightHint = fn.Some(currentHeight) + currentHeight, err := a.cfg.ChainBridge.CurrentHeight( + context.Background(), + ) + if err != nil { + log.Warnf("Unable to fetch current height for "+ + "sweep tx %v height hint: %v", + sweepTx.TxHash(), err) + } else { + heightHint = fn.Some(currentHeight) + } } // With the output commitments re-created, we have all we need to log - // and ship the transaction. + // and ship the transaction. The broadcast of a sweep is always owned + // by lnd, so the porter only records the transfer and watches for + // its confirmation, whether or not the transaction already confirmed. return shipChannelTxn( a.cfg.TxSender, sweepTx, outCommitments, allVpkts, int64(fee), heightHint, ) } +// fetchInputProof fetches the latest proof of the asset a virtual input +// spends from the proof archive. The asset ID is part of the lookup: the +// assets of several tranches of a grouped asset channel sit at the same +// outpoint under the same script key, and only the asset ID tells their +// proofs apart. +// +// A failure is returned to the caller, not skipped: the proof this replaces +// is known to be stale, so going on without the lookup could only produce a +// transfer whose proofs do not verify. lnd retries the notification. +func (a *AuxSweeper) fetchInputProof(ctx context.Context, + vIn *tappsbt.VInput) (*proof.Proof, error) { + + assetID := vIn.PrevID.ID + locator := proof.Locator{ + AssetID: &assetID, + ScriptKey: *vIn.Asset().ScriptKey.PubKey, + OutPoint: &vIn.PrevID.OutPoint, + } + + proofBlob, err := a.cfg.ProofArchive.FetchProof(ctx, locator) + if err != nil { + return nil, fmt.Errorf("unable to look up input proof for "+ + "%v (asset_id=%v): %w", vIn.PrevID.OutPoint, assetID, + err) + } + + var f proof.File + if err := f.Decode(bytes.NewReader(proofBlob)); err != nil { + return nil, fmt.Errorf("unable to decode input proof for "+ + "%v (asset_id=%v): %w", vIn.PrevID.OutPoint, assetID, + err) + } + + last, err := f.LastProof() + if err != nil { + return nil, fmt.Errorf("unable to get last input proof for "+ + "%v (asset_id=%v): %w", vIn.PrevID.OutPoint, assetID, + err) + } + + return last, nil +} + // createSweepProofSuffixes creates the proof suffixes of the outputs of the // vPkts of the given packet set, for the given sweep transaction. func createSweepProofSuffixes(sweepTx *wire.MsgTx, set vPktsWithInput, @@ -3281,7 +5049,7 @@ func (a *AuxSweeper) contractResolver() { case req := <-a.broadcastReqs: req.resp <- a.registerAndBroadcastSweep( req.req, req.tx, req.fee, - req.outpointToTxIndex, + req.outpointToTxIndex, req.opts, ) case <-a.quit: @@ -3343,22 +5111,39 @@ func (a *AuxSweeper) DeriveSweepAddr(inputs []input.Input, // ExtraBudgetForInputs takes a set of inputs and maybe returns an extra budget // that should be added to the sweep transaction. func ExtraBudgetForInputs(inputs []input.Input) lfn.Result[btcutil.Amount] { - inputsWithBlobs := fn.Filter(inputs, func(i input.Input) bool { - return i.ResolutionBlob().IsSome() - }) - + // Asset-carrying outputs hold a token BTC amount that is unrelated to + // the value of the assets they carry, so the sweeper generally needs + // extra budget (pulled from wallet UTXOs) to get an asset sweep + // confirmed. + // + // The exception is second-level HTLC outputs: under + // DeterministicHTLCs they self-fund (after the pre-signed second + // level fee and anchor are deducted they still carry enough BTC to + // cover floor-rate sweep fees), and any positive budget drives lnd + // to pull wallet UTXOs into the sweep tx, where the chained anchor + // outputs make btcwallet's UTXO accounting drift from btcd's by + // AnchorSize-sized increments and the bundled sweep is rejected from + // the mempool. We therefore return zero budget for second-level + // output sweeps only, and keep the regular budget for every other + // aux input (commitment sweeps, breach keyspends, first-level HTLC + // sweeps), whose asset value would otherwise be lost whenever fees + // exceed the token BTC amount. var extraBudget btcutil.Amount - if len(inputsWithBlobs) != 0 { - // In this case, just 1k sats (tapsend.DummyAmtSats) may not be - // enough budget to pay for sweeping. So instead, we'll use a - // multiple of this to ensure that any time we care about an - // output, we're pretty much always able to sweep it. - // - // TODO(roasbeef): return the sats equiv budget of the asset - // amount - extraBudget = tapsend.DummyAmtSats * btcutil.Amount( - sweeperBudgetMultiplier*len(inputsWithBlobs), - ) + for _, inp := range inputs { + if inp.ResolutionBlob().IsNone() { + continue + } + + switch inp.WitnessType() { + case input.TaprootHtlcAcceptedSuccessSecondLevel, + input.TaprootHtlcAcceptedSuccessSecondLevelFinal, + input.TaprootHtlcOfferedTimeoutSecondLevel, + input.TaprootHtlcOfferedTimeoutSecondLevelFinal: + + continue + } + + extraBudget += tapsend.DummyAmtSats * sweeperBudgetMultiplier } return lfn.Ok(extraBudget) @@ -3376,13 +5161,15 @@ func (a *AuxSweeper) ExtraBudgetForInputs( // sweep transaction, generated by the passed BumpRequest. func (a *AuxSweeper) NotifyBroadcast(req *sweep.BumpRequest, tx *wire.MsgTx, fee btcutil.Amount, - outpointToTxIndex map[wire.OutPoint]int) error { + outpointToTxIndex map[wire.OutPoint]int, + opts sweep.AuxNotifyOpts) error { auxReq := &broadcastReq{ req: req, tx: tx, fee: fee, outpointToTxIndex: outpointToTxIndex, + opts: opts, resp: make(chan error, 1), } diff --git a/tapchannel/aux_sweeper_test.go b/tapchannel/aux_sweeper_test.go index 69741d46c8..c5ae0f9226 100644 --- a/tapchannel/aux_sweeper_test.go +++ b/tapchannel/aux_sweeper_test.go @@ -4,11 +4,16 @@ import ( "bytes" "context" "crypto/rand" + "crypto/sha256" "net/url" + "slices" "sync" "testing" + "github.com/btcsuite/btcd/btcec/v2" + "github.com/btcsuite/btcd/btcec/v2/schnorr" "github.com/btcsuite/btcd/chainhash/v2" + "github.com/btcsuite/btcd/psbt/v2" "github.com/btcsuite/btcd/txscript/v2" "github.com/btcsuite/btcd/wire/v2" "github.com/lightninglabs/taproot-assets/address" @@ -31,6 +36,7 @@ import ( "github.com/lightningnetwork/lnd/keychain" "github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/lnwallet/btcwallet" "github.com/lightningnetwork/lnd/lnwire" "github.com/lightningnetwork/lnd/sweep" "github.com/stretchr/testify/require" @@ -695,6 +701,7 @@ func TestResolveContractNoAssetOutputs(t *testing.T) { commit := cmsg.NewCommitment( localAssets, remoteAssets, nil, nil, lnwallet.CommitAuxLeaves{}, false, false, + cmsg.SigHashAll, ) fundingProof := channel.fundingProof funding := cmsg.NewOpenChannel( @@ -1121,6 +1128,7 @@ func TestRegisterAndBroadcastSweepLayout(t *testing.T) { err = sweeper.registerAndBroadcastSweep( req, sweepTx, 1_000, outpointToTxIndex, + sweep.AuxNotifyOpts{}, ) require.NoError(t, err) @@ -1671,3 +1679,342 @@ func TestImportCommitTxHtlcVariants(t *testing.T) { }) } } + +// TestRevocationSweepDescSignVerify tests that the revocation sweep descriptor +// functions produce taproot output keys consistent with the signing key derived +// from the same base material. For each revocation type (offered, accepted, +// second-level), it performs a full sign+verify round-trip using the same +// routines used in production to create the scripts and derive the keys. +func TestRevocationSweepDescSignVerify(t *testing.T) { + t.Parallel() + + // Generate base key material. In production, revokeBasePriv is our + // revocation base point secret, and commitSecret is the per-commitment + // secret revealed when the remote party broadcasts a revoked + // commitment. + revokeBasePriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + commitSecret, err := btcec.NewPrivateKey() + require.NoError(t, err) + + // Generate HTLC keys and delay key for the commitment keyring. + localHtlcPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + remoteHtlcPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + toLocalPriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + + // Derive the revocation public key using the standard LND routine. + // This key becomes the internal key of all HTLC taproot outputs. + revocationKey := input.DeriveRevocationPubkey( + revokeBasePriv.PubKey(), commitSecret.PubKey(), + ) + + keyRing := &lnwallet.CommitmentKeyRing{ + RevocationKey: revocationKey, + LocalHtlcKey: localHtlcPriv.PubKey(), + RemoteHtlcKey: remoteHtlcPriv.PubKey(), + ToLocalKey: toLocalPriv.PubKey(), + } + + payHash := sha256.Sum256([]byte("test preimage")) + htlcIndex := input.HtlcIndex(42) + csvDelay := uint32(144) + htlcExpiry := uint32(800_000) + + // Derive the signing private key that the LND signer computes when + // processing a breach sweep: + // 1. DeriveRevocationPrivKey (DoubleTweak): recovers the revocation + // private key from our base secret and the revealed commit secret. + // 2. TweakPrivKey with HTLC index (SingleTweak): applies the + // asset-level HTLC index tweak. + revocationPriv := input.DeriveRevocationPrivKey( + revokeBasePriv, commitSecret, + ) + + tweakScalar := ScriptKeyTweakFromHtlcIndex(htlcIndex) + var singleTweak [32]byte + tweakScalar.PutBytesUnchecked(singleTweak[:]) + signingPriv := input.TweakPrivKey(revocationPriv, singleTweak[:]) + + // Verify that the private key tweak path is consistent with the public + // key tweak path. This confirms that TweakPrivKey + SingleTweak on the + // private side produces the same result as TweakPubKeyWithTweak on the + // public side. + derivedInternalKey := input.TweakPubKeyWithTweak( + revocationKey, singleTweak[:], + ) + require.Equal( + t, derivedInternalKey.SerializeCompressed(), + signingPriv.PubKey().SerializeCompressed(), + "private key tweak path should match public key tweak path", + ) + + testCases := []struct { + name string + getSweepDescs func() lfn.Result[tapscriptSweepDescs] + }{ + { + name: "offered HTLC revocation", + getSweepDescs: func() lfn.Result[tapscriptSweepDescs] { + return htlcOfferedRevokeSweepDesc( + keyRing, payHash[:], htlcExpiry, + htlcIndex, + ) + }, + }, + { + name: "accepted HTLC revocation", + getSweepDescs: func() lfn.Result[tapscriptSweepDescs] { + return htlcAcceptedRevokeSweepDesc( + keyRing, payHash[:], htlcIndex, + ) + }, + }, + { + name: "second-level HTLC revocation", + getSweepDescs: func() lfn.Result[tapscriptSweepDescs] { + return htlcSecondLevelRevokeSweepDesc( + keyRing, csvDelay, htlcIndex, + ) + }, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + // Get the sweep descriptor. + descs := tc.getSweepDescs().UnwrapOrFail(t) + desc := descs.firstLevel + + // Revocation sweeps use keyspend (no control block). + require.Empty(t, desc.ctrlBlockBytes, + "revocation sweep should use keyspend") + + // Verify the descriptor's internal key matches what + // we derived from applying both tweaks to the base + // keys on the public key side. + tree := desc.scriptTree.Tree() + require.Equal( + t, + derivedInternalKey.SerializeCompressed(), + tree.InternalKey.SerializeCompressed(), + "descriptor internal key should match "+ + "derived key", + ) + + // Apply the taproot tweak for keyspend signing. + // This mirrors what RawTxInTaprootSignature does + // internally. + tapTweak := desc.scriptTree.TapTweak() + taprootPriv := txscript.TweakTaprootPrivKey( + *signingPriv, tapTweak, + ) + + // Sign a test message. + testMsg := sha256.Sum256([]byte(tc.name)) + sig, err := schnorr.Sign(taprootPriv, testMsg[:]) + require.NoError(t, err) + + // Verify the signature against the taproot output + // key from the descriptor. This is the key that the + // UTXO is locked to on-chain. + require.True( + t, sig.Verify(testMsg[:], tree.TaprootKey), + "signature should verify against taproot "+ + "output key", + ) + }) + } + + // Finally, close the loop with the commitment-construction path: + // the second-level revoke desc must reproduce the exact asset-level + // script key that createSecondLevelHtlcAllocations committed to when + // the second-level transaction was originally constructed. Otherwise + // the sweep desc would sign for a key that never appeared on the + // revoked commitment. + t.Run("second-level desc matches allocation script key", + func(t *testing.T) { + chanType := channeldb.SimpleTaprootFeatureBit | + channeldb.AnchorOutputsBit | + channeldb.ZeroHtlcTxFeeBit | + channeldb.SingleFunderTweaklessBit | + channeldb.TapscriptRootBit + + allocs, err := createSecondLevelHtlcAllocations( + chanType, true, nil, 1200, csvDelay, *keyRing, + fn.None[uint32](), fn.None[uint32](), + htlcIndex, true, + ) + require.NoError(t, err) + require.NotEmpty(t, allocs) + + allocScriptKey, err := allocs[0].GenScriptKey( + asset.ID{}, + ) + require.NoError(t, err) + + descs := htlcSecondLevelRevokeSweepDesc( + keyRing, csvDelay, htlcIndex, + ).UnwrapOrFail(t) + tree := descs.firstLevel.scriptTree.Tree() + + // Compare x-only: the two paths may normalize the + // key's Y parity differently, which is irrelevant + // for taproot outputs. + require.Equal( + t, + schnorr.SerializePubKey(allocScriptKey.PubKey), + schnorr.SerializePubKey(tree.TaprootKey), + "revoke sweep desc must sign for the script "+ + "key committed at commitment "+ + "construction", + ) + }) +} + +// TestApplySignDescTweakRoundTrip closes the loop between the sweeper's PSBT +// encoding and the wallet signer's decoding: applySignDescToVIn packs the +// revocation (double) and HTLC index (single) tweaks as PSBT unknowns on the +// virtual input, and lnd's wallet signer re-derives the signing key from +// those unknowns in the order they appear. This test re-derives the private +// key exactly like the signer does and asserts it matches both the manual +// derivation chain and the public key applySignDescToVIn reports. +func TestApplySignDescTweakRoundTrip(t *testing.T) { + t.Parallel() + + revokeBasePriv, err := btcec.NewPrivateKey() + require.NoError(t, err) + commitSecret, err := btcec.NewPrivateKey() + require.NoError(t, err) + + revocationKey := input.DeriveRevocationPubkey( + revokeBasePriv.PubKey(), commitSecret.PubKey(), + ) + + htlcIndex := input.HtlcIndex(42) + tweakScalar := ScriptKeyTweakFromHtlcIndex(htlcIndex) + var singleTweak [32]byte + tweakScalar.PutBytesUnchecked(singleTweak[:]) + + // The manual derivation chain, mirroring what the breach sweep needs: + // base -> DoubleTweak (revocation) -> SingleTweak (HTLC index). + expectedPriv := input.TweakPrivKey( + input.DeriveRevocationPrivKey(revokeBasePriv, commitSecret), + singleTweak[:], + ) + + signDesc := input.SignDescriptor{ + KeyDesc: keychain.KeyDescriptor{ + PubKey: revokeBasePriv.PubKey(), + }, + SingleTweak: singleTweak[:], + DoubleTweak: commitSecret, + } + + vIn := &tappsbt.VInput{} + signingKey, leaf := applySignDescToVIn( + signDesc, vIn, testChainParams, nil, true, + ) + + // Breach key spends carry no leaf script. + require.Empty(t, leaf.Script) + + // The reported signing key must equal the tweaked revocation key. + expectedPub := input.TweakPubKeyWithTweak( + revocationKey, singleTweak[:], + ) + require.Equal( + t, expectedPub.SerializeCompressed(), + signingKey.SerializeCompressed(), + ) + + // Drive the actual consumer used on tapd's own signing path: + // tapsend.AddKeyTweaks reads the unknowns back into a sign + // descriptor before SignOutputRaw. Both tweaks must survive the + // round trip. + var spendDesc asset.SignDescriptor + tapsend.AddKeyTweaks(vIn.Unknowns, &spendDesc) + require.Equal(t, singleTweak[:], spendDesc.SingleTweak) + require.NotNil(t, spendDesc.DoubleTweak) + require.Equal( + t, commitSecret.Serialize(), + spendDesc.DoubleTweak.Serialize(), + ) + + // lnd's direct signer (lnwallet/btcwallet/signer.go, + // maybeTweakPrivKey) derives from the SignDescriptor fields: double + // (revocation) tweak first, then single (HTLC index). + signerPriv := input.TweakPrivKey( + input.DeriveRevocationPrivKey( + revokeBasePriv, spendDesc.DoubleTweak, + ), + spendDesc.SingleTweak, + ) + require.Equal( + t, expectedPriv.PubKey().SerializeCompressed(), + signerPriv.PubKey().SerializeCompressed(), + ) + + // lnd's remote-signer path (lnwallet/btcwallet/psbt.go, + // maybeTweakPrivKeyPsbt) collects the tweaks from the PSBT unknowns + // and applies them combined in the same double-then-single order, + // regardless of the order the unknowns appear in. Replicate that + // derivation for both orderings of the unknowns to pin the + // order-independence this comment block relies on. + psbtDerive := func(unknowns []*psbt.Unknown) *btcec.PrivateKey { + var single, double []byte + for _, unknown := range unknowns { + if bytes.Equal( + unknown.Key, + btcwallet.PsbtKeyTypeInputSignatureTweakSingle, + ) { + + single = unknown.Value + } + if bytes.Equal( + unknown.Key, + btcwallet.PsbtKeyTypeInputSignatureTweakDouble, + ) { + + double = unknown.Value + } + } + require.NotNil(t, single) + require.NotNil(t, double) + + doubleTweak, _ := btcec.PrivKeyFromBytes(double) + return input.TweakPrivKey( + input.DeriveRevocationPrivKey( + revokeBasePriv, doubleTweak, + ), + single, + ) + } + + psbtPriv := psbtDerive(vIn.Unknowns) + + reversed := make([]*psbt.Unknown, len(vIn.Unknowns)) + copy(reversed, vIn.Unknowns) + slices.Reverse(reversed) + psbtPrivReversed := psbtDerive(reversed) + + // All derivation paths must land on the same key, which is the + // public key the sweeper verifies against. + require.Equal( + t, expectedPriv.PubKey().SerializeCompressed(), + psbtPriv.PubKey().SerializeCompressed(), + ) + require.Equal( + t, psbtPriv.PubKey().SerializeCompressed(), + psbtPrivReversed.PubKey().SerializeCompressed(), + ) + require.Equal( + t, signingKey.SerializeCompressed(), + psbtPriv.PubKey().SerializeCompressed(), + ) +} diff --git a/tapchannel/aux_traffic_shaper.go b/tapchannel/aux_traffic_shaper.go index 18059ef6e0..ad64c5a517 100644 --- a/tapchannel/aux_traffic_shaper.go +++ b/tapchannel/aux_traffic_shaper.go @@ -122,6 +122,24 @@ func (s *AuxTrafficShaper) ShouldHandleTraffic(cid lnwire.ShortChannelID, // is no bandwidth available. To find out if a channel is a custom channel that // should be handled by the traffic shaper, the HandleTraffic method should be // called first. +// onChainHtlcAmt returns the on-chain BTC amount an asset HTLC to the given +// peer carries: the deterministic-HTLC carrier value (which funds the +// pre-signed second-level fee, its CPFP anchor and the eventual sweep) when +// the peer negotiated DeterministicHTLCs, and the legacy just-above-dust +// value otherwise. Channels without the feature get nothing in return for a +// larger carrier, so they must not pay for it (nor have their minimum +// quotable payment raised by it). +func (s *AuxTrafficShaper) onChainHtlcAmt( + peer route.Vertex) lnwire.MilliSatoshi { + + features := s.cfg.AuxChanNegotiator.GetPeerFeatures(peer) + if features.HasFeature(tapfeatures.DeterministicHTLCsOptional) { + return rfqmath.DefaultOnChainHtlcMSat + } + + return rfqmath.LegacyOnChainHtlcMSat +} + func (s *AuxTrafficShaper) PaymentBandwidth(fundingBlob, htlcBlob, commitmentBlob lfn.Option[tlv.Blob], linkBandwidth, htlcAmt lnwire.MilliSatoshi, htlcView lnwallet.AuxHtlcView, @@ -202,8 +220,8 @@ func (s *AuxTrafficShaper) PaymentBandwidth(fundingBlob, htlcBlob, return prettyPrintLocalView(*decodedView) })) - // Get the minimum HTLC amount, which is just above dust. - minHtlcAmt := rfqmath.DefaultOnChainHtlcMSat + // Get the minimum HTLC amount this channel's HTLCs carry on-chain. + minHtlcAmt := s.onChainHtlcAmt(peer) // LND calls this hook twice. Once to see if the overall budget of the // node is enough, and then during pathfinding to actually see if @@ -590,9 +608,10 @@ func (s *AuxTrafficShaper) ProduceHtlcExtraData(totalAmount lnwire.MilliSatoshi, } // Encode the updated HTLC TLV back into a blob and return it with the - // amount that should be sent on-chain, which is a value in satoshi that - // is just above the dust limit. - htlcAmountMSat := rfqmath.DefaultOnChainHtlcMSat + // amount that should be sent on-chain: the deterministic-HTLC carrier + // value when the peer negotiated DeterministicHTLCs, the legacy + // just-above-dust value otherwise. + htlcAmountMSat := s.onChainHtlcAmt(peer) // Now we set the flag that marks this HTLC as a noop_add, which means // that the above dust will eventually return to us. This means that diff --git a/tapchannel/commitment.go b/tapchannel/commitment.go index 4b61a4ff2e..95e39ff65c 100644 --- a/tapchannel/commitment.go +++ b/tapchannel/commitment.go @@ -410,8 +410,8 @@ func processAddEntry(htlc *DecodedDescriptor, ourBalance, theirBalance uint64, func SanityCheckAmounts(ourBalance, theirBalance btcutil.Amount, ourAssetBalance, theirAssetBalance uint64, assetView, nonAssetView *DecodedView, chanType channeldb.ChannelType, - whoseCommit lntypes.ChannelParty, dustLimit btcutil.Amount) (bool, bool, - error) { + whoseCommit lntypes.ChannelParty, dustLimit btcutil.Amount, + sigHashDefault bool) (bool, bool, error) { log.Tracef("Sanity checking amounts, whoseCommit=%v, ourBalance=%d, "+ "theirBalance=%d, ourAssetBalance=%d, theirAssetBalance=%d", @@ -431,6 +431,7 @@ func SanityCheckAmounts(ourBalance, theirBalance btcutil.Amount, if !lnwallet.HtlcIsDust( chanType, false, whoseCommit, feePerKw, entry.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { numHTLCs++ @@ -440,6 +441,7 @@ func SanityCheckAmounts(ourBalance, theirBalance btcutil.Amount, if !lnwallet.HtlcIsDust( chanType, true, whoseCommit, feePerKw, entry.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) { numHTLCs++ @@ -452,6 +454,7 @@ func SanityCheckAmounts(ourBalance, theirBalance btcutil.Amount, isDust := lnwallet.HtlcIsDust( chanType, false, whoseCommit, feePerKw, entry.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) if rfqmsg.Sum(entry.AssetBalances) > 0 && isDust { return false, false, fmt.Errorf("outgoing HTLC asset "+ @@ -467,6 +470,7 @@ func SanityCheckAmounts(ourBalance, theirBalance btcutil.Amount, isDust := lnwallet.HtlcIsDust( chanType, true, whoseCommit, feePerKw, entry.Amount.ToSatoshis(), dustLimit, + sigHashDefault, ) if rfqmsg.Sum(entry.AssetBalances) > 0 && isDust { return false, false, fmt.Errorf("incoming HTLC asset "+ @@ -518,8 +522,8 @@ func GenerateCommitmentAllocations(prevState *cmsg.Commitment, whoseCommit lntypes.ChannelParty, ourBalance, theirBalance lnwire.MilliSatoshi, originalView lnwallet.AuxHtlcView, chainParams *address.ChainParams, - keys lnwallet.CommitmentKeyRing, - stxoFeatures STXOFeatures) ([]*tapsend.Allocation, *cmsg.Commitment, + keys lnwallet.CommitmentKeyRing, stxoFeatures STXOFeatures, + sigHashDefault bool) ([]*tapsend.Allocation, *cmsg.Commitment, error) { log.Tracef("Generating allocations, whoseCommit=%v, ourBalance=%d, "+ @@ -615,7 +619,7 @@ func GenerateCommitmentAllocations(prevState *cmsg.Commitment, wantLocalAnchor, wantRemoteAnchor, err := SanityCheckAmounts( ourBalance.ToSatoshis(), theirBalance.ToSatoshis(), ourAssetBalance, theirAssetBalance, filteredView, nonAssetView, - chanState.ChanType, whoseCommit, dustLimit, + chanState.ChanType, whoseCommit, dustLimit, sigHashDefault, ) if err != nil { return nil, nil, fmt.Errorf("error checking amounts: %w", err) @@ -629,6 +633,7 @@ func GenerateCommitmentAllocations(prevState *cmsg.Commitment, chanState, ourBalance.ToSatoshis(), theirBalance.ToSatoshis(), ourAssetBalance, theirAssetBalance, wantLocalAnchor, wantRemoteAnchor, filteredView, whoseCommit, keys, nonAssetView, + sigHashDefault, ) if err != nil { return nil, nil, fmt.Errorf("unable to create allocations: %w", @@ -720,7 +725,7 @@ func GenerateCommitmentAllocations(prevState *cmsg.Commitment, // those construct our Commitment struct that will in the end also hold // our proof suffixes. newCommitment, err := ToCommitment( - allocations, vPackets, stxoFeatures, + allocations, vPackets, stxoFeatures, sigHashDefault, ) if err != nil { return nil, nil, fmt.Errorf("unable to convert to commitment: "+ @@ -735,8 +740,8 @@ func CreateAllocations(chanState lnwallet.AuxChanState, ourBalance, theirBalance btcutil.Amount, ourAssetBalance, theirAssetBalance uint64, wantLocalCommitAnchor, wantRemoteCommitAnchor bool, filteredView *DecodedView, whoseCommit lntypes.ChannelParty, - keys lnwallet.CommitmentKeyRing, - nonAssetView *DecodedView) ([]*tapsend.Allocation, error) { + keys lnwallet.CommitmentKeyRing, nonAssetView *DecodedView, + sigHashDefault bool) ([]*tapsend.Allocation, error) { log.Tracef("Creating allocations, whoseCommit=%v, initiator=%v, "+ "ourBalance=%d, theirBalance=%d, ourAssetBalance=%d, "+ @@ -855,7 +860,7 @@ func CreateAllocations(chanState lnwallet.AuxChanState, ourBalance, isDust := lnwallet.HtlcIsDust( chanState.ChanType, isIncoming, whoseCommit, filteredView.FeePerKw, htlc.Amount.ToSatoshis(), - dustLimit, + dustLimit, sigHashDefault, ) if isDust { // We need to error out, as a dust HTLC carrying assets @@ -952,7 +957,7 @@ func CreateAllocations(chanState lnwallet.AuxChanState, ourBalance, isDust := lnwallet.HtlcIsDust( chanState.ChanType, isIncoming, whoseCommit, filteredView.FeePerKw, htlc.Amount.ToSatoshis(), - dustLimit, + dustLimit, sigHashDefault, ) if isDust { return nil @@ -1228,8 +1233,8 @@ func LeavesFromTapscriptScriptTree( // ToCommitment converts the allocations to a Commitment struct. func ToCommitment(allocations []*tapsend.Allocation, - vPackets []*tappsbt.VPacket, - stxoFeatures STXOFeatures) (*cmsg.Commitment, error) { + vPackets []*tappsbt.VPacket, stxoFeatures STXOFeatures, + sigHashDefault bool) (*cmsg.Commitment, error) { var ( localAssets []*cmsg.AssetOutput @@ -1353,6 +1358,7 @@ func ToCommitment(allocations []*tapsend.Allocation, return cmsg.NewCommitment( localAssets, remoteAssets, outgoingHtlcs, incomingHtlcs, auxLeaves, stxoFeatures.STXO, stxoFeatures.Spender, + cmsg.SigHashTypeFromBool(sigHashDefault), ), nil } @@ -1388,11 +1394,17 @@ func collectOutputs(a *tapsend.Allocation, // createSecondLevelHtlcAllocations creates the allocations for the second level // HTLCs. This will be used to generate the vPkts that corresponds to the second // level HTLC sweep. +// +// When addAnchor is true, a second AllocationTypeNoAssets entry for the +// CPFP anchor output at index 1 is appended, and AnchorSize sats are +// taken from the HTLC allocation's BtcAmount to fund it. This mirrors +// the BTC-level layout produced by lnwallet.CreateHtlcSuccessTx / +// CreateHtlcTimeoutTx under DeterministicHTLCs. func createSecondLevelHtlcAllocations(chanType channeldb.ChannelType, initiator bool, htlcOutputs []*cmsg.AssetOutput, htlcAmt btcutil.Amount, commitCsvDelay uint32, keys lnwallet.CommitmentKeyRing, outputIndex fn.Option[uint32], htlcTimeout fn.Option[uint32], - htlcIndex uint64) ([]*tapsend.Allocation, error) { + htlcIndex uint64, addAnchor bool) ([]*tapsend.Allocation, error) { // TODO(roasbeef): thaw height not implemented for taproot chans rn // (lease expiry) @@ -1427,13 +1439,14 @@ func createSecondLevelHtlcAllocations(chanType channeldb.ChannelType, schnorr.SerializePubKey(htlcTree.TaprootKey), schnorr.SerializePubKey(tweakedTree.TaprootKey)) + htlcOutputIndex := outputIndex.UnwrapOr(0) allocations := []*tapsend.Allocation{{ Type: tapsend.SecondLevelHtlcAllocation, // If we're making the second-level transaction just to sign, // then we'll have an output index of zero. Otherwise, we'll // want to use the output index as appears in the final // commitment transaction. - OutputIndex: outputIndex.UnwrapOr(0), + OutputIndex: htlcOutputIndex, Amount: cmsg.OutputSum(htlcOutputs), AssetVersion: asset.V1, BtcAmount: htlcAmt, @@ -1454,21 +1467,57 @@ func createSecondLevelHtlcAllocations(chanType channeldb.ChannelType, HtlcIndex: htlcIndex, }} + if addAnchor { + // The CPFP anchor that lnwallet.CreateHtlc{Success,Timeout}Tx + // appends at index 1. Anyone-can-spend after 16 CSV blocks + // via script path, or by the broadcaster (key-path) using + // ToLocalKey before then. Tapd must include it in the + // allocations so exclusion proofs are generated for it. + anchor, err := input.NewAnchorScriptTree(keys.ToLocalKey) + if err != nil { + return nil, fmt.Errorf("error creating second-level "+ + "anchor script tree: %w", err) + } + anchorLeaves, anchorTree, err := LeavesFromTapscriptScriptTree( + anchor, + ) + if err != nil { + return nil, fmt.Errorf("error creating second-level "+ + "anchor sibling: %w", err) + } + + allocations = append(allocations, &tapsend.Allocation{ + // Anchor outputs never carry assets. + Type: tapsend.AllocationTypeNoAssets, + OutputIndex: htlcOutputIndex + 1, + Amount: 0, + BtcAmount: lnwallet.AnchorSize, + InternalKey: anchorTree.InternalKey, + NonAssetLeaves: anchorLeaves, + SortTaprootKeyBytes: schnorr.SerializePubKey( + anchorTree.TaprootKey, + ), + }) + } + return allocations, nil } // CreateSecondLevelHtlcPackets creates the virtual packets for the second level -// HTLC. +// HTLC. When addAnchor is true (DeterministicHTLCs), the allocations +// include a CPFP anchor output at index 1 mirroring the BTC-level layout +// from lnwallet.CreateHtlc{Success,Timeout}Tx. func CreateSecondLevelHtlcPackets(chanState lnwallet.AuxChanState, commitTx *wire.MsgTx, htlcAmt btcutil.Amount, keys lnwallet.CommitmentKeyRing, chainParams *address.ChainParams, htlcOutputs []*cmsg.AssetOutput, htlcTimeout fn.Option[uint32], - htlcIndex uint64) ([]*tappsbt.VPacket, []*tapsend.Allocation, error) { + htlcIndex uint64, + addAnchor bool) ([]*tappsbt.VPacket, []*tapsend.Allocation, error) { allocations, err := createSecondLevelHtlcAllocations( chanState.ChanType, chanState.IsInitiator, htlcOutputs, htlcAmt, uint32(chanState.LocalChanCfg.CsvDelay), - keys, fn.None[uint32](), htlcTimeout, htlcIndex, + keys, fn.None[uint32](), htlcTimeout, htlcIndex, addAnchor, ) if err != nil { return nil, nil, err @@ -1511,19 +1560,22 @@ func CreateSecondLevelHtlcPackets(chanState lnwallet.AuxChanState, } // CreateSecondLevelHtlcTx creates the auxiliary leaf for a successful or timed -// out second level HTLC transaction. +// out second level HTLC transaction. addAnchor signals that the BTC-level +// second-level tx includes a CPFP anchor output at index 1 (under +// DeterministicHTLCs): the allocation set then carries an exclusion-only +// entry for that output. func CreateSecondLevelHtlcTx(chanState lnwallet.AuxChanState, commitTx *wire.MsgTx, htlcAmt btcutil.Amount, keys lnwallet.CommitmentKeyRing, chainParams *address.ChainParams, htlcOutputs []*cmsg.AssetOutput, htlcTimeout fn.Option[uint32], - htlcIndex uint64, stxoFeatures STXOFeatures) (input.AuxTapLeaf, - error) { + htlcIndex uint64, stxoFeatures STXOFeatures, + addAnchor bool) (input.AuxTapLeaf, error) { none := input.NoneTapLeaf() vPackets, allocations, err := CreateSecondLevelHtlcPackets( chanState, commitTx, htlcAmt, keys, chainParams, htlcOutputs, - htlcTimeout, htlcIndex, + htlcTimeout, htlcIndex, addAnchor, ) if err != nil { return none, fmt.Errorf("error creating second level HTLC "+ diff --git a/tapchannel/commitment_bench_test.go b/tapchannel/commitment_bench_test.go index 4d357a9b71..5b7652caa6 100644 --- a/tapchannel/commitment_bench_test.go +++ b/tapchannel/commitment_bench_test.go @@ -26,7 +26,7 @@ func BenchmarkCommitmentBlob(b *testing.B) { } com := cmsg.NewCommitment( []*cmsg.AssetOutput{newOutput()}, nil, outgoing, nil, - lnwallet.CommitAuxLeaves{}, false, false, + lnwallet.CommitAuxLeaves{}, false, false, cmsg.SigHashAll, ) b.ReportAllocs() diff --git a/tapchannel/htlc_revocation_test.go b/tapchannel/htlc_revocation_test.go new file mode 100644 index 0000000000..095286ee16 --- /dev/null +++ b/tapchannel/htlc_revocation_test.go @@ -0,0 +1,179 @@ +package tapchannel + +import ( + "testing" + + "github.com/btcsuite/btcd/wire/v2" + lfn "github.com/lightningnetwork/lnd/fn/v2" + "github.com/lightningnetwork/lnd/input" + "github.com/lightningnetwork/lnd/lnwallet" + "github.com/lightningnetwork/lnd/tlv" + "github.com/stretchr/testify/require" +) + +// TestVerifySecondLevelSigMissing tests that a verification job that carries +// no signature is only accepted for an HTLC that carries no assets. lnd hands +// us a job for every HTLC of a commitment, signed or not, because only we +// know which of them carry assets. A peer that simply leaves the signature +// of an asset HTLC out must be rejected: without it the second-level asset +// transition of that HTLC cannot be built, neither on our own commitment nor +// after a breach of theirs, which is exactly when the peer would benefit +// from having withheld it. +// +// The asset buckets of a commitment are keyed by HTLC index per direction, +// and both parties count their HTLCs from zero. So whether an HTLC carries +// assets must be decided in the bucket of the job's direction only. +func TestVerifySecondLevelSigMissing(t *testing.T) { + t.Parallel() + + // The commitment holds assets for the outgoing HTLC with index 0 and + // nothing else. + commitTx, assetJob := htlcVerifyJob(t, 1) + + withoutSig := func(job lnwallet.AuxVerifyJob) lnwallet.AuxVerifyJob { + job.SigBlob = lfn.None[tlv.Blob]() + + return job + } + + testCases := []struct { + name string + job func() lnwallet.AuxVerifyJob + wantErr string + }{{ + name: "asset HTLC without a sig", + job: func() lnwallet.AuxVerifyJob { + return withoutSig(assetJob) + }, + wantErr: "missing second level sig for asset HTLC", + }, { + // The incoming HTLC with the same index carries no assets. + name: "BTC-only HTLC sharing the index of an asset HTLC", + job: func() lnwallet.AuxVerifyJob { + job := withoutSig(assetJob) + job.Incoming = true + + return job + }, + }, { + name: "BTC-only HTLC with another index", + job: func() lnwallet.AuxVerifyJob { + job := withoutSig(assetJob) + job.HTLC.HtlcIndex = 7 + + return job + }, + }, { + name: "no commit blob", + job: func() lnwallet.AuxVerifyJob { + job := withoutSig(assetJob) + job.CommitBlob = lfn.None[tlv.Blob]() + + return job + }, + }, { + // A sig blob that does not decode is rejected even for an + // HTLC that would not need one. + name: "BTC-only HTLC with a malformed sig", + job: func() lnwallet.AuxVerifyJob { + job := assetJob + job.Incoming = true + job.SigBlob = lfn.Some(tlv.Blob{0xff, 0xff, 0xff}) + + return job + }, + wantErr: "error decoding asset sig list record", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + err := VerifySecondLevelSigs( + testChainParams, chanState, commitTx, + []lnwallet.AuxVerifyJob{tc.job()}, + ) + if tc.wantErr == "" { + require.NoError(t, err) + + return + } + + require.ErrorContains(t, err, tc.wantErr) + }) + } +} + +// TestSecondLevelHtlcIncoming tests that the direction of the HTLC behind a +// second-level resolution request is taken from the request and never +// guessed. For the sweeps of our own commitment the witness type tells it. +// For a breach it does not, as one type covers both directions, so the +// request must state it, and a request that does not is refused rather than +// resolved with the HTLC of the other direction that happens to share its +// index. +func TestSecondLevelHtlcIncoming(t *testing.T) { + t.Parallel() + + chanPoint := wire.OutPoint{Index: 1} + + testCases := []struct { + name string + reqType input.WitnessType + incoming lfn.Option[bool] + wantIncoming bool + wantErr string + }{{ + name: "local success is incoming", + reqType: input.TaprootHtlcAcceptedSuccessSecondLevel, + wantIncoming: true, + }, { + // The stated direction is irrelevant when the type tells it. + name: "local success ignores the stated direction", + reqType: input.TaprootHtlcAcceptedSuccessSecondLevel, + incoming: lfn.Some(false), + wantIncoming: true, + }, { + name: "local timeout is outgoing", + reqType: input.TaprootHtlcOfferedTimeoutSecondLevel, + }, { + name: "breach, incoming", + reqType: input.TaprootHtlcSecondLevelRevoke, + incoming: lfn.Some(true), + wantIncoming: true, + }, { + name: "breach, outgoing", + reqType: input.TaprootHtlcSecondLevelRevoke, + incoming: lfn.Some(false), + }, { + name: "breach without a direction", + reqType: input.TaprootHtlcSecondLevelRevoke, + wantErr: "no HTLC direction", + }, { + name: "not a second-level type", + reqType: input.TaprootHtlcOfferedRevoke, + incoming: lfn.Some(true), + wantErr: "is not a second-level HTLC resolution type", + }} + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + incoming, err := secondLevelHtlcIncoming( + lnwallet.ResolutionReq{ + ChanPoint: chanPoint, + Type: tc.reqType, + HtlcIncoming: tc.incoming, + }, + ) + if tc.wantErr != "" { + require.ErrorContains(t, err, tc.wantErr) + + return + } + + require.NoError(t, err) + require.Equal(t, tc.wantIncoming, incoming) + }) + } +} diff --git a/tapchannel/issue115_test.go b/tapchannel/issue115_test.go index 7ef81249ce..0fa1ee95b5 100644 --- a/tapchannel/issue115_test.go +++ b/tapchannel/issue115_test.go @@ -33,6 +33,7 @@ func TestIssue115ForeignAssetIdRejected(t *testing.T) { prevState := tapchannelmsg.NewCommitment( nil, []*tapchannelmsg.AssetOutput{channel.assetOutput}, nil, nil, lnwallet.CommitAuxLeaves{}, false, false, + tapchannelmsg.SigHashAll, ) chanAssetState := tapchannelmsg.NewOpenChannel( []*tapchannelmsg.AssetOutput{channel.assetOutput}, 0, nil, @@ -73,6 +74,7 @@ func TestIssue115ForeignAssetIdRejected(t *testing.T) { lnwire.MilliSatoshi(1_000_000_000), makeView(fundedAsset), testChainParams, lndmock.RandCommitmentKeyRing(t), STXOFeatures{}, + false, ) require.NoError(t, err, "HTLC declaring the funded asset must pass") @@ -88,6 +90,7 @@ func TestIssue115ForeignAssetIdRejected(t *testing.T) { lnwire.MilliSatoshi(1_000_000_000), makeView(foreignAsset), testChainParams, lndmock.RandCommitmentKeyRing(t), STXOFeatures{}, + false, ) require.Error(t, err, "whoseCommit=%v: HTLC declaring an asset the channel "+ @@ -108,6 +111,7 @@ func TestIssue115ForeignAssetIdRejected(t *testing.T) { lnwire.MilliSatoshi(1_000_000_000), makeView(groupPlaceholder), testChainParams, lndmock.RandCommitmentKeyRing(t), STXOFeatures{}, + false, ) require.NoError(t, err, "the funding group's placeholder ID must be accepted") @@ -123,6 +127,7 @@ func TestIssue115ForeignAssetIdRejected(t *testing.T) { makeView(foreignPlaceholder), testChainParams, lndmock.RandCommitmentKeyRing(t), STXOFeatures{}, + false, ) require.Error(t, err, "a foreign group's placeholder ID must be rejected") diff --git a/tapchannel/issue121_test.go b/tapchannel/issue121_test.go index 0b6f14d265..fa4697cdbe 100644 --- a/tapchannel/issue121_test.go +++ b/tapchannel/issue121_test.go @@ -35,6 +35,7 @@ func TestIssue121CarrierDustEvaluation(t *testing.T) { prevState := tapchannelmsg.NewCommitment( nil, []*tapchannelmsg.AssetOutput{channel.assetOutput}, nil, nil, lnwallet.CommitAuxLeaves{}, false, false, + tapchannelmsg.SigHashAll, ) chanAssetState := tapchannelmsg.NewOpenChannel( []*tapchannelmsg.AssetOutput{channel.assetOutput}, 0, nil, @@ -62,6 +63,7 @@ func TestIssue121CarrierDustEvaluation(t *testing.T) { require.False(t, lnwallet.HtlcIsDust( taprootChanType, false, lntypes.Remote, feePerKw, carrierSat, 0, + false, ), "carrier must not be dust for taproot channels at "+ "feePerKw=%v", feePerKw) @@ -99,6 +101,7 @@ func TestIssue121CarrierDustEvaluation(t *testing.T) { lnwire.MilliSatoshi(1_000_000_000), view, testChainParams, lndmock.RandCommitmentKeyRing(t), STXOFeatures{}, + false, ) require.NoError(t, err, "asset commitment must assemble at feePerKw=%v for a "+ @@ -142,6 +145,7 @@ func TestIssue121CarrierDustEvaluation(t *testing.T) { lnwire.MilliSatoshi(1_000_000_000), view, testChainParams, lndmock.RandCommitmentKeyRing(t), STXOFeatures{}, + false, ) require.Error(t, err, "a carrier below the negotiated dust limit must still be "+ diff --git a/tapchannel/stxo_features.go b/tapchannel/stxo_features.go index 337ba5fd04..7d37c11c6d 100644 --- a/tapchannel/stxo_features.go +++ b/tapchannel/stxo_features.go @@ -44,6 +44,16 @@ func CommitmentSTXOFeatures(commitment *cmsg.Commitment) STXOFeatures { } } +// Or returns the union of the two feature sets. It is used to fall back to +// the flags cached in a commitment when the live feature vector of the peer +// is not populated yet. +func (f STXOFeatures) Or(other STXOFeatures) STXOFeatures { + return STXOFeatures{ + STXO: f.STXO || other.STXO, + Spender: f.Spender || other.Spender, + } +} + // CommitOpts returns the options for creating output commitments that carry // the leaves of the features. func (f STXOFeatures) CommitOpts() []tapsend.OutputCommitmentOption { diff --git a/tapchannel/stxo_features_test.go b/tapchannel/stxo_features_test.go index c511b3a116..76d12442eb 100644 --- a/tapchannel/stxo_features_test.go +++ b/tapchannel/stxo_features_test.go @@ -92,6 +92,7 @@ func TestCommitmentSTXOFeatures(t *testing.T) { commitment := cmsg.NewCommitment( nil, nil, nil, nil, lnwallet.CommitAuxLeaves{}, stxoFeatures.STXO, stxoFeatures.Spender, + cmsg.SigHashAll, ) require.Equal( t, stxoFeatures, CommitmentSTXOFeatures(commitment), @@ -106,6 +107,7 @@ func TestCommitmentSTXOFeatures(t *testing.T) { // carries no alt leaves at all. commitment := cmsg.NewCommitment( nil, nil, nil, nil, lnwallet.CommitAuxLeaves{}, false, true, + cmsg.SigHashAll, ) require.Equal(t, STXOFeatures{}, CommitmentSTXOFeatures(commitment)) @@ -113,6 +115,7 @@ func TestCommitmentSTXOFeatures(t *testing.T) { // STXO flag alone. legacy := cmsg.NewCommitment( nil, nil, nil, nil, lnwallet.CommitAuxLeaves{}, true, true, + cmsg.SigHashAll, ) var encoded bytes.Buffer require.NoError(t, legacy.Encode(&encoded)) diff --git a/tapchannelmsg/custom_channel_data_test.go b/tapchannelmsg/custom_channel_data_test.go index 0ace0bd1a7..3889e5b697 100644 --- a/tapchannelmsg/custom_channel_data_test.go +++ b/tapchannelmsg/custom_channel_data_test.go @@ -72,7 +72,7 @@ func testReadChannelCustomData(t *testing.T, stxo, spender bool) { }, map[input.HtlcIndex][]*AssetOutput{ 2: {output4}, }, lnwallet.CommitAuxLeaves{}, - stxo, spender, + stxo, spender, SigHashAll, ) fundingBlob := fundingState.Bytes() @@ -182,18 +182,21 @@ func TestReadBalanceCustomData(t *testing.T) { openChannel1 := NewCommitment( []*AssetOutput{output1}, []*AssetOutput{output2}, nil, nil, lnwallet.CommitAuxLeaves{}, false, false, + SigHashAll, ) openChannel2 := NewCommitment( []*AssetOutput{output2}, []*AssetOutput{output3}, nil, nil, lnwallet.CommitAuxLeaves{}, false, false, + SigHashAll, ) pendingChannel1 := NewCommitment( []*AssetOutput{output3}, nil, nil, nil, lnwallet.CommitAuxLeaves{}, false, false, + SigHashAll, ) pendingChannel2 := NewCommitment( nil, []*AssetOutput{output1}, nil, nil, - lnwallet.CommitAuxLeaves{}, false, false, + lnwallet.CommitAuxLeaves{}, false, false, SigHashAll, ) var customChannelData bytes.Buffer diff --git a/tapchannelmsg/records.go b/tapchannelmsg/records.go index 3610e83c58..0ff4f97686 100644 --- a/tapchannelmsg/records.go +++ b/tapchannelmsg/records.go @@ -471,16 +471,52 @@ type Commitment struct { // proofs. STXO tlv.RecordT[tlv.TlvType5, bool] + // SigHashDefault is a flag indicating whether HTLC second-level + // transactions for this commitment use SigHashDefault. This is cached + // from the negotiated feature bits so that it is available after + // restart without requiring the peer to be online. + SigHashDefault tlv.RecordT[tlv.TlvType6, bool] + // Spender is a flag indicating whether this commitment also commits // to the spender leaves of the inputs, next to their STXOs. Spender tlv.RecordT[tlv.TlvType7, bool] } +// SigHashType indicates the sighash mode used for HTLC second-level +// transactions in a commitment. +type SigHashType uint8 + +const ( + // SigHashAll indicates standard SigHashAll signing, where the + // sweeper can add wallet inputs to bump fees. + SigHashAll SigHashType = iota + + // SigHashDefault indicates SigHashDefault signing with baked-in + // fees, used for taproot asset channels. + SigHashDefault +) + +// IsSigHashDefault returns true if this is SigHashDefault mode. +func (s SigHashType) IsSigHashDefault() bool { + return s == SigHashDefault +} + +// SigHashTypeFromBool converts a boolean sigHashDefault flag to a +// SigHashType value. +func SigHashTypeFromBool(sigHashDefault bool) SigHashType { + if sigHashDefault { + return SigHashDefault + } + + return SigHashAll +} + // NewCommitment creates a new Commitment record with the given local and remote // assets, and incoming and outgoing HTLCs. func NewCommitment(localAssets, remoteAssets []*AssetOutput, outgoingHtlcs, incomingHtlcs map[input.HtlcIndex][]*AssetOutput, - auxLeaves lnwallet.CommitAuxLeaves, stxo, spender bool) *Commitment { + auxLeaves lnwallet.CommitAuxLeaves, stxo, spender bool, + sigHashType SigHashType) *Commitment { return &Commitment{ LocalAssets: tlv.NewRecordT[tlv.TlvType0]( @@ -506,7 +542,10 @@ func NewCommitment(localAssets, remoteAssets []*AssetOutput, outgoingHtlcs, auxLeaves.IncomingHtlcLeaves, ), ), - STXO: tlv.NewPrimitiveRecord[tlv.TlvType5](stxo), + STXO: tlv.NewPrimitiveRecord[tlv.TlvType5](stxo), + SigHashDefault: tlv.NewPrimitiveRecord[tlv.TlvType6]( + sigHashType.IsSigHashDefault(), + ), Spender: tlv.NewPrimitiveRecord[tlv.TlvType7](spender), } } @@ -520,6 +559,7 @@ func (c *Commitment) records() []tlv.Record { c.IncomingHtlcAssets.Record(), c.AuxLeaves.Record(), c.STXO.Record(), + c.SigHashDefault.Record(), c.Spender.Record(), } } diff --git a/tapchannelmsg/records_test.go b/tapchannelmsg/records_test.go index 7402f97798..01e68f1591 100644 --- a/tapchannelmsg/records_test.go +++ b/tapchannelmsg/records_test.go @@ -216,7 +216,7 @@ func TestCommitment(t *testing.T) { name: "commitment with empty HTLC maps", commitment: NewCommitment( nil, nil, nil, nil, lnwallet.CommitAuxLeaves{}, - false, false, + false, false, SigHashAll, ), }, { @@ -231,7 +231,7 @@ func TestCommitment(t *testing.T) { [32]byte{1}, 1000, *randProof, ), }, nil, nil, lnwallet.CommitAuxLeaves{}, false, - false, + false, SigHashAll, ), }, { @@ -246,7 +246,7 @@ func TestCommitment(t *testing.T) { [32]byte{1}, 1000, *randProof, ), }, nil, nil, lnwallet.CommitAuxLeaves{}, true, - false, + false, SigHashAll, ), }, { @@ -261,7 +261,7 @@ func TestCommitment(t *testing.T) { [32]byte{1}, 1000, *randProof, ), }, nil, nil, lnwallet.CommitAuxLeaves{}, true, - true, + true, SigHashAll, ), }, { @@ -352,7 +352,7 @@ func TestCommitment(t *testing.T) { }, }, }, - false, false, + false, false, SigHashAll, ), }, } diff --git a/tapdb/assets_store_test.go b/tapdb/assets_store_test.go index 5662c15724..3226cbd0b6 100644 --- a/tapdb/assets_store_test.go +++ b/tapdb/assets_store_test.go @@ -2318,6 +2318,9 @@ func TestAssetExportLog(t *testing.T) { require.NoError(t, assetsStore.LogPendingParcel( ctx, spendDelta, leaseOwner, leaseExpiry, )) + require.NoError(t, assetsStore.LogPendingParcel( + ctx, spendDelta, leaseOwner, leaseExpiry, + )) assetID := inputAsset.ID() receiverIdentifier := tapfreighter.NewOutputIdentifier( diff --git a/tapdb/freighter_anchoring.go b/tapdb/freighter_anchoring.go index 27d988ec8a..bf8e221077 100644 --- a/tapdb/freighter_anchoring.go +++ b/tapdb/freighter_anchoring.go @@ -69,6 +69,24 @@ func (a *AssetStore) applyPendingParcel(ctx context.Context, return fmt.Errorf("unable to insert new chain tx: %w", err) } + // Breach recovery can re-deliver a NotifyBroadcast for the same + // pre-anchored sweep/import tx. Treat the transfer shell as + // idempotent by anchor txid so we don't strand duplicate pending + // rows for the same on-chain spend. + existingTransfers, err := q.QueryAssetTransfers(ctx, TransferQuery{ + AnchorTxHash: newAnchorTXID[:], + }) + if err != nil { + return fmt.Errorf("unable to query existing asset "+ + "transfers: %w", err) + } + if len(existingTransfers) > 0 { + log.Warnf("Skipping duplicate pending parcel for "+ + "anchor_txid=%v", newAnchorTXID) + + return nil + } + // The transfer itself is just a shell which the inputs and // outputs will reference. We'll insert this next, so we can use // its ID. diff --git a/tapdb/postgres.go b/tapdb/postgres.go index 834812c5aa..8c017670f7 100644 --- a/tapdb/postgres.go +++ b/tapdb/postgres.go @@ -80,7 +80,7 @@ type PostgresStore struct { func NewPostgresStore(cfg *PostgresConfig) (*PostgresStore, error) { log.Infof("Using SQL database '%s'", cfg.DSN(true)) - rawDb, err := sql.Open("pgx", cfg.DSN(false)) + rawDb, err := sql.Open("pgx/v5", cfg.DSN(false)) if err != nil { return nil, MapSQLError(err) } diff --git a/tapfeatures/aux_feature_bits.go b/tapfeatures/aux_feature_bits.go index 7b172a1397..4de4459e5d 100644 --- a/tapfeatures/aux_feature_bits.go +++ b/tapfeatures/aux_feature_bits.go @@ -50,6 +50,19 @@ const ( // flow. Both peers need to signal it for an asset channel to use the // RBF flow, otherwise the legacy close negotiation is used. RbfCoopCloseOptional lnwire.FeatureBit = 9 + + // DeterministicHTLCsRequired is a feature bit that enables + // deterministic second-level HTLC transactions as a required + // feature. When negotiated, second-level HTLC transactions use + // SigHashDefault (making them fully deterministic), and the + // revoking party includes dual-path AuxSigs in RevokeAndAck + // so the honest party can reconstruct valid proofs for breach + // recovery. + DeterministicHTLCsRequired lnwire.FeatureBit = 10 + + // DeterministicHTLCsOptional is the optional variant of the + // deterministic HTLCs feature bit. + DeterministicHTLCsOptional lnwire.FeatureBit = 11 ) // featureNames keeps track of the string description of known features. @@ -64,8 +77,10 @@ var featureNames = map[lnwire.FeatureBit]string{ NegotiatedChanCfgRequired: "negotiated-chan-cfg", NegotiatedChanCfgOptional: "negotiated-chan-cfg", - RbfCoopCloseRequired: "rbf-coop-close", - RbfCoopCloseOptional: "rbf-coop-close", + RbfCoopCloseRequired: "rbf-coop-close", + RbfCoopCloseOptional: "rbf-coop-close", + DeterministicHTLCsRequired: "deterministic-htlcs", + DeterministicHTLCsOptional: "deterministic-htlcs", } // ourFeatures returns a slice containing all of the locally supported features. @@ -78,6 +93,7 @@ func ourFeatures() []lnwire.FeatureBit { STXOSpenderOptional, NegotiatedChanCfgOptional, RbfCoopCloseOptional, + DeterministicHTLCsOptional, } } diff --git a/tapsend/send.go b/tapsend/send.go index 1fb032db51..1909740143 100644 --- a/tapsend/send.go +++ b/tapsend/send.go @@ -823,7 +823,7 @@ func CreateTaprootSignature(vIn *tappsbt.VInput, virtualTx *wire.MsgTx, } // Add any tweak parameters that may be present in the PSBT. - addKeyTweaks(vIn.Unknowns, &spendDesc) + AddKeyTweaks(vIn.Unknowns, &spendDesc) // There are three possible signing cases: BIP-0086 key spend path, key // spend path with a script root, and script spend path. @@ -903,13 +903,15 @@ func CreateTaprootSignature(vIn *tappsbt.VInput, virtualTx *wire.MsgTx, return witness, nil } -// addKeyTweaks examines if there are any tweak parameters given in the -// custom/proprietary PSBT fields and may add them to the given sign descriptor. -func addKeyTweaks(unknowns []*psbt.Unknown, desc *asset.SignDescriptor) { - // There can be other custom/unknown keys in a PSBT that we just ignore. - // Key tweaking is optional and only one tweak (single _or_ double) can - // ever be applied (at least for any use cases described in the BOLT - // spec). +// AddKeyTweaks examines if there are any tweak parameters given in the +// custom/proprietary PSBT fields and may add them to the given sign +// descriptor. +func AddKeyTweaks(unknowns []*psbt.Unknown, desc *asset.SignDescriptor) { + // There can be other custom/unknown keys in a PSBT that we just + // ignore. Key tweaking is optional. Historically only one tweak + // (single _or_ double) was ever set, but second-level HTLC signing + // for aux channels sets both, and lnd's signer applies them combined + // (double/revocation first, then single/HTLC index). for _, u := range unknowns { if bytes.Equal(u.Key, psbtKeyTypeInputSignatureTweakSingle) { desc.SingleTweak = u.Value