-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathaux_funding_controller.go
2076 lines (1727 loc) · 64.4 KB
/
aux_funding_controller.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tapchannel
import (
"bytes"
"context"
crand "crypto/rand"
"errors"
"fmt"
"io"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/btcutil/psbt"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew"
"github.com/lightninglabs/lndclient"
"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/rfq"
cmsg "github.com/lightninglabs/taproot-assets/tapchannelmsg"
"github.com/lightninglabs/taproot-assets/tapdb"
"github.com/lightninglabs/taproot-assets/tapfreighter"
"github.com/lightninglabs/taproot-assets/tapgarden"
"github.com/lightninglabs/taproot-assets/tappsbt"
"github.com/lightninglabs/taproot-assets/tapscript"
"github.com/lightninglabs/taproot-assets/tapsend"
"github.com/lightninglabs/taproot-assets/vm"
lfn "github.com/lightningnetwork/lnd/fn"
"github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/keychain"
"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/msgmux"
)
const (
// MsgEndpointName is the name of the endpoint that we'll use to
// register the funding controller with the peer message handler.
MsgEndpointName = "taproot assets channel funding"
// ackTimeout is the amount of time we'll wait to receive the protocol
// level ACK from the remote party before timing out.
ackTimeout = time.Second * 30
// maxNumAssetIDs is the maximum number of fungible asset pieces (asset
// IDs) that can be committed to a single channel. The number needs to
// be limited to prevent the number of required HTLC signatures to be
// too large for a single CommitSig wire message to carry them. This
// value is tightly coupled with the number of HTLCs that can be added
// to a channel at the same time (maxNumHTLCs). The values were
// determined with the TestMaxCommitSigMsgSize test in
// aux_leaf_signer_test.go then a set was chosen that would allow for
// a decent number of HTLCs (and also a number that is divisible by two
// because each side will only be allowed to add half of the total).
maxNumAssetIDs = 3
// maxNumHTLCs is the maximum number of HTLCs there can be in an asset
// channel to avoid the number of signatures exceeding the maximum
// message size of a CommitSig message. See maxNumAssetIDs for more
// information.
maxNumHTLCs = 166
// maxNumHTLCsPerParty is the maximum number of HTLCs that can be added
// by a single party to a channel.
maxNumHTLCsPerParty = maxNumHTLCs / 2
)
// ErrorReporter is used to report an error back to the caller and/or peer that
// we're communicating with.
type ErrorReporter interface {
// ReportError reports an error that occurred during the funding
// process.
ReportError(ctx context.Context, peer btcec.PublicKey,
pid funding.PendingChanID, err error)
}
// PeerMessenger is an interface that allows us to send messages to a remote LN
// peer.
type PeerMessenger interface {
// SendMessage sends a message to a remote peer.
SendMessage(ctx context.Context, peer btcec.PublicKey,
msg lnwire.Message) error
}
// ErrNoPeer is returned when a peer can't be found.
var ErrNoPeer = errors.New("peer not found")
// FeatureBitVerifer is an interface that allows us to verify that a peer has a
// given feature bit set.
type FeatureBitVerifer interface {
// HasFeature returns true if the peer has the given feature bit set.
// If the peer can't be found, then ErrNoPeer is returned.
HasFeature(ctx context.Context, peerPub btcec.PublicKey,
bit lnwire.FeatureBit) (bool, error)
}
// OpenChanReq is a request to open a new asset channel with a remote peer.
type OpenChanReq struct {
// ChanAmt is the amount of BTC to put into the channel. Some BTC is
// required atm to pay on chain fees for the channel. Note that
// additional fees can be added in the event of a force close by using
// CPFP with the channel anchor outputs.
ChanAmt btcutil.Amount
// PushAmt is the amount of BTC to push to the remote peer.
PushAmt btcutil.Amount
// RemoteMaxHtlc is the maximum number of HTLCs we allow the remote to
// add to the channel. If this is zero, then the default value defined
// by lnd (and dependent on the channel capacity) will be used.
RemoteMaxHtlc uint32
// PeerPub is the identity public key of the remote peer we wish to
// open the channel with.
PeerPub btcec.PublicKey
// TempPID is the temporary channel ID to use for this channel.
TempPID funding.PendingChanID
// PsbtTemplate is the PSBT template that we'll use to fund the channel.
// This should already have all the inputs spending asset UTXOs added.
PsbtTemplate *psbt.Packet
}
// AssetChanIntent is a handle returned by the PsbtChannelFunder that can be
// used to drive the new asset channel to completion. The intent includes the
// PSBT template returned by lnd which has the funding output for the new
// channel already populated.
type AssetChanIntent interface {
// FundingPsbt is the original PsbtTemplate, plus the P2TR funding
// output that'll create the channel.
FundingPsbt() (*psbt.Packet, error)
// BindPsbt accepts a new *unsigned* PSBT with any additional inputs or
// outputs (for change) added. This PSBT is still unsigned. This step
// performs final verification to ensure the PSBT is crafted in a manner
// that'll properly open the channel once broadcaster.
BindPsbt(context.Context, *psbt.Packet) error
}
// PsbtChannelFunder is an interface that abstracts the necessary steps needed
// fund a PSBT channel on using lnd.
type PsbtChannelFunder interface {
// OpenChannel attempts to open a new asset holding private channel
// using the backing lnd node. The PSBT flow is by default. An
// AssetChanIntent is returned that includes the updated PSBT template
// that includes the funding output. Once all other inputs+outputs have
// been added, then BindPsbt should be called to progress the funding
// process. Afterward, the funding transaction should be signed and
// broadcast.
OpenChannel(context.Context, OpenChanReq) (AssetChanIntent, error)
// ChannelAcceptor is used to accept and potentially influence
// parameters of incoming channels.
ChannelAcceptor(ctx context.Context,
acceptor lndclient.AcceptorFunction) (chan error, error)
}
// TxPublisher is an interface used to publish transactions.
type TxPublisher interface {
// PublishTransaction attempts to publish a new transaction to the
// network.
PublishTransaction(context.Context, *wire.MsgTx) error
}
// AssetSyncer is used to ensure that we know of the set of assets that'll be
// used as funding input to an accepted channel.
type AssetSyncer interface {
// QueryAssetInfo attempts to locate asset genesis information by
// querying geneses already known to this node. If asset issuance was
// not previously verified, we then query universes in our federation
// for issuance proofs.
QueryAssetInfo(ctx context.Context,
id asset.ID) (*asset.AssetGroup, error)
}
// FundingControllerCfg is a configuration struct that houses the necessary
// abstractions needed to drive funding.
type FundingControllerCfg struct {
// HeaderVerifier is used to verify headers in a proof.
HeaderVerifier proof.HeaderVerifier
// GroupVerifier is used to verify group keys in a proof.
GroupVerifier proof.GroupVerifier
// ErrReporter is used to report errors back to the caller and/or peer.
ErrReporter ErrorReporter
// AssetWallet is the wallet that we'll use to handle the asset
// specific steps of the funding process.
AssetWallet tapfreighter.Wallet
// CoinSelector is used to select assets for funding.
CoinSelector tapfreighter.CoinSelector
// AddrBook is used to manage script keys and addresses.
AddrBook *tapdb.TapAddressBook
// ChainParams is the chain params of the chain we operate on.
ChainParams address.ChainParams
// ChainBridge provides access to the chain for confirmation
// notification, and other block related actions.
ChainBridge tapfreighter.ChainBridge
// GroupKeyIndex is used to query the group key for an asset ID.
GroupKeyIndex tapsend.AssetGroupQuerier
// PeerMessenger is used to send messages to a remote peer.
PeerMessenger PeerMessenger
// ChannelFunder is used to fund a new channel using a PSBT template.
ChannelFunder PsbtChannelFunder
// TxPublisher is used to publish transactions.
TxPublisher TxPublisher
// ChainWallet is the wallet that we'll use to handle the chain
// specific
ChainWallet tapfreighter.WalletAnchor
// TxSender is what we'll use to broadcast a transaction to the
// network, while ensuring we also update all our asset and UTXO state
// on disk (insert a proper transfer, etc., etc.).
TxSender tapfreighter.Porter
// RfqManager is used to manage RFQs.
RfqManager *rfq.Manager
// DefaultCourierAddr is the default address the funding controller uses
// to deliver the funding output proofs to the channel peer.
DefaultCourierAddr *url.URL
// AssetSyncer is used to ensure that we've already verified the asset
// genesis for any assets used within channels.
AssetSyncer AssetSyncer
// FeatureBits is used to verify that the peer has the required feature
// to fund asset channels.
FeatureBits FeatureBitVerifer
// ErrChan is used to report errors back to the main server.
ErrChan chan<- error
}
// bindFundingReq is a request to bind a pending channel ID to a complete aux
// funding desc. This is used by the initiator+responder after the pre-funding
// messages and interaction is complete.
type bindFundingReq struct {
initiator bool
pendingChanID funding.PendingChanID
openChan lnwallet.AuxChanState
keyRing lntypes.Dual[lnwallet.CommitmentKeyRing]
resp chan lfn.Option[lnwallet.AuxFundingDesc]
}
// assetRootReq is a message sent by lnd once we've sent or received the
// OpenChannel message. We'll reply with a tapscript root if we know of one for
// this pid, which lets lnd derive the proper funding output.
type assetRootReq struct {
pendingChanID funding.PendingChanID
resp chan lfn.Option[chainhash.Hash]
}
// FundingController is used to drive TAP aware channel funding using a backing
// lnd node and an active connection to a tapd instance.
type FundingController struct {
started atomic.Bool
stopped atomic.Bool
cfg FundingControllerCfg
msgs chan msgmux.PeerMsg
bindFundingReqs chan *bindFundingReq
newFundingReqs chan *FundReq
rootReqs chan *assetRootReq
finalizedChans chan funding.PendingChanID
// ContextGuard provides a wait group and main quit channel that can be
// used to create guarded contexts.
*fn.ContextGuard
}
// NewFundingController creates a new instance of the FundingController.
func NewFundingController(cfg FundingControllerCfg) *FundingController {
return &FundingController{
cfg: cfg,
msgs: make(chan msgmux.PeerMsg, 10),
bindFundingReqs: make(chan *bindFundingReq, 10),
newFundingReqs: make(chan *FundReq, 10),
rootReqs: make(chan *assetRootReq, 10),
finalizedChans: make(chan funding.PendingChanID, 10),
ContextGuard: &fn.ContextGuard{
DefaultTimeout: DefaultTimeout,
Quit: make(chan struct{}),
},
}
}
// Start starts the funding controller.
func (f *FundingController) Start() error {
if !f.started.CompareAndSwap(false, true) {
return nil
}
log.Infof("Starting FundingController")
f.Wg.Add(1)
go f.chanFunder()
f.Wg.Add(1)
go func() {
defer f.Wg.Done()
ctx, cancel := f.WithCtxQuitNoTimeout()
defer cancel()
errChan, err := f.cfg.ChannelFunder.ChannelAcceptor(
ctx, f.channelAcceptor,
)
if err != nil {
err = fmt.Errorf("unable to start channel acceptor: %w",
err)
f.cfg.ErrChan <- err
return
}
// We'll accept channels for as long as the funding controller
// is running or until we receive an error.
select {
case err := <-errChan:
err = fmt.Errorf("channel acceptor error: %w", err)
f.cfg.ErrChan <- err
case <-f.Quit:
log.Infof("Stopping channel acceptor, funding " +
"controller shutting down")
}
}()
return nil
}
// Stop stops the funding controller.
func (f *FundingController) Stop() error {
if !f.stopped.CompareAndSwap(true, false) {
return nil
}
log.Infof("Stopping FundingController")
close(f.Quit)
f.Wg.Wait()
return nil
}
// newPendingChanID generates a new pending channel ID using a CSPRG.
func newPendingChanID() (funding.PendingChanID, error) {
var id funding.PendingChanID
if _, err := io.ReadFull(crand.Reader, id[:]); err != nil {
return id, err
}
return id, nil
}
// pendingAssetFunding represents all the state needed to keep track of a
// pending asset channel funding flow.
type pendingAssetFunding struct {
chainParams *address.ChainParams
peerPub btcec.PublicKey
pid funding.PendingChanID
initiator bool
amt uint64
pushAmt btcutil.Amount
inputProofs []*proof.Proof
feeRate chainfee.SatPerVByte
lockedInputs []wire.OutPoint
lockedAssetInputs []wire.OutPoint
fundingAssetCommitment *commitment.TapCommitment
fundingOutputProofs []*proof.Proof
fundingAckChan chan bool
fundingFinalizedSignal chan struct{}
finalizedCloseOnce sync.Once
}
// addInputProof adds a new proof to the set of proofs that'll be used to fund
// the new channel.
func (p *pendingAssetFunding) addInputProof(proof *proof.Proof) {
p.inputProofs = append(p.inputProofs, proof)
}
// assetOutputs returns the set of asset outputs that'll be used to fund the
// new asset channel.
func (p *pendingAssetFunding) assetOutputs() []*cmsg.AssetOutput {
return fn.Map(
p.fundingOutputProofs, func(p *proof.Proof) *cmsg.AssetOutput {
return cmsg.NewAssetOutput(
p.Asset.ID(), p.Asset.Amount, *p,
)
},
)
}
// addToFundingCommitment adds a new asset to the funding commitment.
func (p *pendingAssetFunding) addToFundingCommitment(a *asset.Asset) error {
newCommitment, err := commitment.FromAssets(
fn.Ptr(commitment.TapCommitmentV2), a,
)
if err != nil {
return fmt.Errorf("unable to create commitment: %w", err)
}
// If we don't already have a commitment, then we'll use the one created
// just now and don't need to merge anything.
if p.fundingAssetCommitment == nil {
p.fundingAssetCommitment = newCommitment
return nil
}
// If we've already got one, then we need to merge the two.
return p.fundingAssetCommitment.Merge(newCommitment)
}
// newCommitBlobAndLeaves creates a new commitment blob that'll be stored in
// the channel state for the specified party.
func newCommitBlobAndLeaves(pendingFunding *pendingAssetFunding,
lndOpenChan lnwallet.AuxChanState, assetOpenChan *cmsg.OpenChannel,
keyRing lntypes.Dual[lnwallet.CommitmentKeyRing],
whoseCommit lntypes.ChannelParty) ([]byte, lnwallet.CommitAuxLeaves,
error) {
chanAssets := assetOpenChan.FundedAssets.Val.Outputs
var (
localAssets, remoteAssets []*cmsg.AssetOutput
)
// Only assign the balances according to whether this is our commit or
// not. The balances will be used correctly in the generateAllocations
// call. This is required to mirror the case where we create a
// commitment from a previous state. If it's not our commitment, then
// the balances in the previous state are reversed and
// generateAllocations will flip them back.
switch {
case pendingFunding.initiator && whoseCommit.IsLocal():
localAssets = chanAssets
case pendingFunding.initiator && whoseCommit.IsRemote():
remoteAssets = chanAssets
case !pendingFunding.initiator && whoseCommit.IsLocal():
remoteAssets = chanAssets
case !pendingFunding.initiator && whoseCommit.IsRemote():
localAssets = chanAssets
}
var localSatBalance, remoteSatBalance lnwire.MilliSatoshi
// We don't have a real prev state at this point, the leaf creator only
// needs the sum of the remote+local assets, so we'll populate that.
fakePrevState := cmsg.NewCommitment(
localAssets, remoteAssets, nil, nil, lnwallet.CommitAuxLeaves{},
)
// Just like above, we don't have a real HTLC view here, so we'll pass
// in a blank view.
fakeView := &lnwallet.HtlcView{}
// With all the above, we'll generate the first commitment that'll be
// stored
_, firstCommit, err := GenerateCommitmentAllocations(
fakePrevState, lndOpenChan, assetOpenChan, whoseCommit,
localSatBalance, remoteSatBalance, fakeView,
pendingFunding.chainParams, keyRing.GetForParty(whoseCommit),
)
if err != nil {
return nil, lnwallet.CommitAuxLeaves{}, err
}
var b bytes.Buffer
if err := firstCommit.Encode(&b); err != nil {
return nil, lnwallet.CommitAuxLeaves{}, err
}
auxLeaves := firstCommit.Leaves()
return b.Bytes(), auxLeaves, nil
}
// toAuxFundingDesc converts the pending asset funding into a full aux funding
// desc. This is the final step in the modified funding process, as after this,
// both sides are able to construct the funding output, and will be able to
// store the appropriate funding blobs.
func (p *pendingAssetFunding) toAuxFundingDesc(
req *bindFundingReq) (*lnwallet.AuxFundingDesc, error) {
// First, we'll map all the assets into asset outputs that'll be stored
// in the open channel struct on the lnd side.
assetOutputs := p.assetOutputs()
// With all the outputs assembled, we'll now map that to the open
// channel wrapper that'll go in the set of TLV blobs.
openChanDesc := cmsg.NewOpenChannel(assetOutputs)
// Now we'll encode the 3 TLV blobs that lnd will store: the main one
// for the funding details, and then the blobs for the local and remote
// commitment
customFundingBlob := openChanDesc.Bytes()
// Encode the commitment blobs for both the local and remote party.
// This will be the information for the very first state (state 0).
localCommitBlob, localAuxLeaves, err := newCommitBlobAndLeaves(
p, req.openChan, openChanDesc, req.keyRing, lntypes.Local,
)
if err != nil {
return nil, err
}
remoteCommitBlob, remoteAuxLeaves, err := newCommitBlobAndLeaves(
p, req.openChan, openChanDesc, req.keyRing, lntypes.Remote,
)
if err != nil {
return nil, err
}
return &lnwallet.AuxFundingDesc{
CustomFundingBlob: customFundingBlob,
CustomLocalCommitBlob: localCommitBlob,
CustomRemoteCommitBlob: remoteCommitBlob,
LocalInitAuxLeaves: localAuxLeaves,
RemoteInitAuxLeaves: remoteAuxLeaves,
}, nil
}
// unlockInputs unlocks any inputs that were locked during the funding process.
func (p *pendingAssetFunding) unlockInputs(ctx context.Context,
wallet tapgarden.WalletAnchor) error {
for _, outpoint := range p.lockedInputs {
if err := wallet.UnlockInput(ctx, outpoint); err != nil {
return fmt.Errorf("unable to unlock outpoint %v: %w",
outpoint, err)
}
}
return nil
}
// unlockAssetInputs unlocks any asset inputs that were locked during the
// funding process.
func (p *pendingAssetFunding) unlockAssetInputs(ctx context.Context,
coinSelect tapfreighter.CoinSelector) error {
log.Debugf("unlocking asset inputs: %v",
spew.Sdump(p.lockedAssetInputs))
err := coinSelect.ReleaseCoins(ctx, p.lockedAssetInputs...)
if err != nil {
return fmt.Errorf("unable to unlock asset outpoints %v: %w",
p.lockedAssetInputs, err)
}
return nil
}
// msgToAssetProof converts a wire message to an assetProof.
func msgToAssetProof(msg lnwire.Message) (cmsg.AssetFundingMsg, error) {
switch msg := msg.(type) {
case *lnwire.Custom:
switch msg.Type {
case cmsg.TxAssetInputProofType:
var assetProof cmsg.TxAssetInputProof
err := assetProof.Decode(bytes.NewReader(msg.Data), 0)
if err != nil {
return nil, fmt.Errorf("error decoding as "+
"tx asset input proof: %w", err)
}
return &assetProof, nil
case cmsg.TxAssetOutputProofType:
var assetProof cmsg.TxAssetOutputProof
err := assetProof.Decode(bytes.NewReader(msg.Data), 0)
if err != nil {
return nil, fmt.Errorf("error decoding as "+
"tx asset output proof: %w", err)
}
return &assetProof, nil
case cmsg.AssetFundingCreatedType:
var assetProof cmsg.AssetFundingCreated
err := assetProof.Decode(bytes.NewReader(msg.Data), 0)
if err != nil {
return nil, fmt.Errorf("error decoding as "+
"asset funding created: %w", err)
}
return &assetProof, nil
case cmsg.AssetFundingAckType:
var fundingAck cmsg.AssetFundingAck
err := fundingAck.Decode(bytes.NewReader(msg.Data), 0)
if err != nil {
return nil, fmt.Errorf("error decoding as "+
"asset funding created: %w", err)
}
return &fundingAck, nil
default:
return nil, fmt.Errorf("unknown custom message "+
"type: %v", msg.Type)
}
case *cmsg.TxAssetInputProof:
return msg, nil
case *cmsg.TxAssetOutputProof:
return msg, nil
case *cmsg.AssetFundingCreated:
return msg, nil
case *cmsg.AssetFundingAck:
return msg, nil
default:
return nil, fmt.Errorf("unknown message type: %T", msg)
}
}
// fundingFlowIndex is a map from pending channel ID to the current state of
// the funding flow.
type fundingFlowIndex map[funding.PendingChanID]*pendingAssetFunding
// fromMsg attempts to match an incoming message to the pending funding flow,
// and extracts the asset proof from the message.
func (f *fundingFlowIndex) fromMsg(chainParams *address.ChainParams,
msg msgmux.PeerMsg) (cmsg.AssetFundingMsg, *pendingAssetFunding,
error) {
assetProof, err := msgToAssetProof(msg.Message)
if err != nil {
return nil, nil, fmt.Errorf("error converting to asset proof: "+
"%w", err)
}
pid := assetProof.PID()
// Next, we'll see if this is already part of an active funding flow.
// If not, then we'll make a new one to accumulate this new proof.
assetFunding, ok := (*f)[pid]
if !ok {
assetFunding = &pendingAssetFunding{
chainParams: chainParams,
pid: pid,
peerPub: msg.PeerPub,
amt: assetProof.Amt().UnwrapOr(0),
fundingAckChan: make(chan bool, 1),
fundingFinalizedSignal: make(chan struct{}),
}
(*f)[pid] = assetFunding
}
return assetProof, assetFunding, nil
}
// fundVirtualPacket attempts to fund a new vPacket using the asset wallet to
// find the asset inputs required to satisfy a funding request.
func (f *FundingController) fundVirtualPacket(ctx context.Context,
assetID asset.ID, amt uint64) (*tapfreighter.FundedVPacket, error) {
log.Infof("Funding new vPacket channel, asset_id=%v, amt=%v",
assetID, amt)
// Our funding script key will be the OP_TRUE addr that we'll use as
// the funding script on the asset level.
fundingScriptTree := tapscript.NewChannelFundingScriptTree()
fundingTaprootKey, _ := schnorr.ParsePubKey(
schnorr.SerializePubKey(fundingScriptTree.TaprootKey),
)
fundingScriptKey := asset.ScriptKey{
PubKey: fundingTaprootKey,
TweakedScriptKey: &asset.TweakedScriptKey{
RawKey: keychain.KeyDescriptor{
PubKey: fundingScriptTree.InternalKey,
},
Tweak: fundingScriptTree.TapscriptRoot,
},
}
// We'll also need to import the funding script key into the wallet so
// the asset will be materialized in the asset table and show up in the
// balance correctly.
err := f.cfg.AddrBook.InsertScriptKey(ctx, fundingScriptKey, true)
if err != nil {
return nil, fmt.Errorf("unable to insert script key: %w", err)
}
// Next, we'll use the asset wallet to fund a new vPSBT which'll be
// used as the asset level funding output for this transaction. In this
// case our destination will just be the OP_TRUE tapscript that we use
// for the funding output.
pktTemplate := &tappsbt.VPacket{
Inputs: []*tappsbt.VInput{{
PrevID: asset.PrevID{
ID: assetID,
},
}},
Outputs: []*tappsbt.VOutput{{
Amount: amt,
AssetVersion: asset.V1,
Interactive: true,
AnchorOutputIndex: 0,
ScriptKey: fundingScriptKey,
}},
ChainParams: &f.cfg.ChainParams,
Version: tappsbt.V1,
}
fundDesc, err := tapsend.DescribeRecipients(
ctx, pktTemplate, f.cfg.GroupKeyIndex,
)
if err != nil {
return nil, fmt.Errorf("unable to describe recipients: %w", err)
}
// Fund the packet. This will derive an anchor internal key for us, but
// we'll overwrite that later on.
fundDesc.CoinSelectType = tapsend.Bip86Only
return f.cfg.AssetWallet.FundPacket(ctx, fundDesc, pktTemplate)
}
// sendInputOwnershipProofs sends the input ownership proofs to the remote
// party during the validation phase of the funding process.
func (f *FundingController) sendInputOwnershipProofs(peerPub btcec.PublicKey,
vPkt *tappsbt.VPacket, fundingState *pendingAssetFunding) error {
ctx, done := f.WithCtxQuit()
defer done()
log.Infof("Generating input ownership proofs for %v inputs",
len(vPkt.Inputs))
// For each of the inputs we selected, we'll create a new ownership
// proof for each of them. We'll send this to the peer, so they can
// verify that we actually own the inputs we're using to fund
// the channel.
for _, assetInput := range vPkt.Inputs {
// First, we'll grab the proof for the asset input, then
// generate the challenge witness to place in the proof so it
challengeWitness, err := f.cfg.AssetWallet.SignOwnershipProof(
assetInput.Asset(), fn.None[[32]byte](),
)
if err != nil {
return fmt.Errorf("error signing ownership proof: %w",
err)
}
// TODO(roasbeef): use the temp chan ID above? as part of
// challenge
// With the witness obtained, we'll emplace it, then add this
// to our set of relevant input proofs. But we create a copy of
// the proof first, to make sure we don't modify the vPacket.
var proofBuf bytes.Buffer
err = assetInput.Proof.Encode(&proofBuf)
if err != nil {
return fmt.Errorf("error serializing proof: %w", err)
}
proofCopy := &proof.Proof{}
if err := proofCopy.Decode(&proofBuf); err != nil {
return fmt.Errorf("error decoding proof: %w", err)
}
proofCopy.ChallengeWitness = challengeWitness
fundingState.inputProofs = append(
fundingState.inputProofs, proofCopy,
)
}
// With all our proofs assembled, we'll now send each of them to the
// remote peer in series.
for i := range fundingState.inputProofs {
proofBytes, _ := proof.Encode(fundingState.inputProofs[i])
log.Tracef("Sending input ownership proof to remote party: %x",
proofBytes)
inputProof := cmsg.NewTxAssetInputProof(
fundingState.pid, *fundingState.inputProofs[i],
)
// Finally, we'll send the proof to the remote peer.
err := f.cfg.PeerMessenger.SendMessage(ctx, peerPub, inputProof)
if err != nil {
return fmt.Errorf("unable to send proof to peer: %w",
err)
}
}
// Now that we've sent the proofs for the input assets, we'll send them
// a fully signed asset funding output. We can send this safely as they
// can't actually broadcast this without our signed Bitcoin inputs.
signedInputs, err := f.cfg.AssetWallet.SignVirtualPacket(vPkt)
if err != nil {
return fmt.Errorf("unable to sign funding inputs: %w", err)
}
if len(signedInputs) != len(vPkt.Inputs) {
return fmt.Errorf("expected %v signed inputs, got %v",
len(vPkt.Inputs), len(signedInputs))
}
// We'll now send the signed inputs to the remote party.
//
// TODO(roasbeef): generalize for multi-asset
fundingAsset := vPkt.Outputs[0].Asset.Copy()
assetOutputMsg := cmsg.NewTxAssetOutputProof(
fundingState.pid, *fundingAsset, true,
)
log.Debugf("Sending TLV for funding asset output to remote party: %v",
limitSpewer.Sdump(fundingAsset))
err = f.cfg.PeerMessenger.SendMessage(ctx, peerPub, assetOutputMsg)
if err != nil {
return fmt.Errorf("unable to send proof to peer: %w", err)
}
return nil
}
// fundPsbt takes our PSBT anchor template and has lnd fund the PSBT with
// enough inputs and a proper change output.
func (f *FundingController) fundPsbt(
ctx context.Context, psbtPkt *psbt.Packet,
feeRate chainfee.SatPerKWeight) (*tapsend.FundedPsbt, error) {
// We set the change index to be a new, 3rd output by specifying -1
// (which means: please add change output). We could instead have it be
// the second output, but that would mingle lnd's funds with outputs
// that mainly store assets.
changeIndex := int32(-1)
return f.cfg.ChainWallet.FundPsbt(ctx, psbtPkt, 1, feeRate, changeIndex)
}
// signAllVPackets takes the funding vPSBT, signs all the explicit transfer,
// and then derives all the passive transfers that also needs to be signed, and
// then signs those. A single slice of all the passive and active assets signed
// is returned.
func (f *FundingController) signAllVPackets(ctx context.Context,
fundingVpkt *tapfreighter.FundedVPacket) ([]*tappsbt.VPacket,
[]*tappsbt.VPacket, []*tappsbt.VPacket, error) {
log.Infof("Signing all funding vPackets")
activePkt := fundingVpkt.VPacket
encoded, err := tappsbt.Encode(activePkt)
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to encode active "+
"packet: %w", err)
}
log.Debugf("Active packet: %x", encoded)
_, err = f.cfg.AssetWallet.SignVirtualPacket(activePkt)
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to sign and commit "+
"virtual packet: %w", err)
}
passivePkts, err := f.cfg.AssetWallet.CreatePassiveAssets(
ctx, []*tappsbt.VPacket{activePkt},
fundingVpkt.InputCommitments,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to create passive "+
"assets: %w", err)
}
err = f.cfg.AssetWallet.SignPassiveAssets(passivePkts)
if err != nil {
return nil, nil, nil, fmt.Errorf("unable to sign passive "+
"assets: %w", err)
}
allPackets := append([]*tappsbt.VPacket{}, activePkt)
allPackets = append(allPackets, passivePkts...)
err = tapsend.ValidateVPacketVersions(allPackets)
if err != nil {
return nil, nil, nil, fmt.Errorf("signed packets: %w", err)
}
return allPackets, []*tappsbt.VPacket{activePkt}, passivePkts, nil
}
// anchorVPackets anchors the vPackets to the funding PSBT, creating a
// complete, but unsigned PSBT packet that can be used to create out asset
// channel.
func (f *FundingController) anchorVPackets(fundedPkt *tapsend.FundedPsbt,
allPackets []*tappsbt.VPacket,
fundingScriptKey asset.ScriptKey) ([]*proof.Proof, error) {
log.Infof("Anchoring funding vPackets to funding PSBT")
// Given the set of vPackets we've created, we'll now merge them all to
// create a map from output index to final tap commitment.
outputCommitments, err := tapsend.CreateOutputCommitments(allPackets)
if err != nil {
return nil, fmt.Errorf("unable to create new output "+
"commitments: %w", err)
}
// Now that we know all the output commitments, we can modify the
// Bitcoin PSBT to have the proper pkScript that commits to the newly
// anchored assets.
for _, vPkt := range allPackets {
err = tapsend.UpdateTaprootOutputKeys(
fundedPkt.Pkt, vPkt, outputCommitments,
)
if err != nil {
return nil, fmt.Errorf("error updating taproot output "+
"keys: %w", err)
}
}
var fundingProofs []*proof.Proof
// We're done creating the output commitments, we can now create the
// transition proof suffixes. This'll be the new proof we submit to
// relevant universe (or not) to update the new resting place of these
// assets.
for idx := range allPackets {
vPkt := allPackets[idx]
for vOutIdx := range vPkt.Outputs {
proofSuffix, err := tapsend.CreateProofSuffix(
fundedPkt.Pkt.UnsignedTx, fundedPkt.Pkt.Outputs,
vPkt, outputCommitments, vOutIdx, allPackets,
)
if err != nil {
return nil, fmt.Errorf("unable to create "+
"proof suffix for output %d of vPSBT "+
"%d: %w", vOutIdx, idx, err)
}
vPkt.Outputs[vOutIdx].ProofSuffix = proofSuffix
if proofSuffix.Asset.ScriptKey.PubKey.IsEqual(
fundingScriptKey.PubKey,
) {
fundingProofs = append(
fundingProofs, proofSuffix,
)
}
}
}
return fundingProofs, nil
}
// signAndFinalizePsbt signs and finalizes the PSBT, then returns the finalized