11package  session
22
33import  (
4+ 	"context" 
45	"crypto/tls" 
56	"fmt" 
67	"sync" 
78	"time" 
89
910	"github.com/btcsuite/btcd/btcec/v2" 
1011	"github.com/lightninglabs/lightning-node-connect/mailbox" 
12+ 	"github.com/lightningnetwork/lnd/fn" 
1113	"github.com/lightningnetwork/lnd/keychain" 
1214	"google.golang.org/grpc" 
1315	"google.golang.org/grpc/credentials" 
@@ -21,8 +23,9 @@ type GRPCServerCreator func(opts ...grpc.ServerOption) *grpc.Server
2123type  mailboxSession  struct  {
2224	server  * grpc.Server 
2325
24- 	wg    sync.WaitGroup 
25- 	quit  chan  struct {}
26+ 	cancel  fn.Option [context.CancelFunc ]
27+ 	wg      sync.WaitGroup 
28+ 	quit    chan  struct {}
2629}
2730
2831func  newMailboxSession () * mailboxSession  {
@@ -33,7 +36,8 @@ func newMailboxSession() *mailboxSession {
3336
3437func  (m  * mailboxSession ) start (session  * Session ,
3538	serverCreator  GRPCServerCreator , authData  []byte ,
36- 	onUpdate  func (local , remote  * btcec.PublicKey ) error ,
39+ 	onUpdate  func (ctx  context.Context , local ,
40+ 		remote  * btcec.PublicKey ) error ,
3741	onNewStatus  func (s  mailbox.ServerStatus )) error  {
3842
3943	tlsConfig  :=  & tls.Config {}
@@ -43,10 +47,13 @@ func (m *mailboxSession) start(session *Session,
4347
4448	ecdh  :=  & keychain.PrivKeyECDH {PrivKey : session .LocalPrivateKey }
4549
50+ 	ctx , cancel  :=  context .WithCancel (context .Background ())
51+ 	m .cancel  =  fn .Some (cancel )
52+ 
4653	keys  :=  mailbox .NewConnData (
4754		ecdh , session .RemotePublicKey , session .PairingSecret [:],
4855		authData , func (key  * btcec.PublicKey ) error  {
49- 			return  onUpdate (session .LocalPublicKey , key )
56+ 			return  onUpdate (ctx ,  session .LocalPublicKey , key )
5057		}, nil ,
5158	)
5259
@@ -81,6 +88,7 @@ func (m *mailboxSession) run(mailboxServer *mailbox.Server) {
8188}
8289
8390func  (m  * mailboxSession ) stop () {
91+ 	m .cancel .WhenSome (func (fn  context.CancelFunc ) { fn () })
8492	m .server .Stop ()
8593	close (m .quit )
8694	m .wg .Wait ()
@@ -104,7 +112,8 @@ func NewServer(serverCreator GRPCServerCreator) *Server {
104112}
105113
106114func  (s  * Server ) StartSession (session  * Session , authData  []byte ,
107- 	onUpdate  func (local , remote  * btcec.PublicKey ) error ,
115+ 	onUpdate  func (ctx  context.Context , local ,
116+ 		remote  * btcec.PublicKey ) error ,
108117	onNewStatus  func (s  mailbox.ServerStatus )) (chan  struct {}, error ) {
109118
110119	s .activeSessionsMtx .Lock ()
0 commit comments