Skip to content

Commit b4e4d5c

Browse files
committed
loopd: block until lnd is synced to chain
1 parent 435238a commit b4e4d5c

File tree

1 file changed

+37
-7
lines changed

1 file changed

+37
-7
lines changed

loopd/run.go

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,19 @@ func newListenerCfg(config *Config, rpcCfg RPCConfig) *listenerCfg {
7070
getLnd: func(network lndclient.Network, cfg *lndConfig) (
7171
*lndclient.GrpcLndServices, error) {
7272

73+
syncCtx, cancel := context.WithCancel(
74+
context.Background(),
75+
)
76+
defer cancel()
77+
7378
svcCfg := &lndclient.LndServicesConfig{
74-
LndAddress: cfg.Host,
75-
Network: network,
76-
MacaroonDir: cfg.MacaroonDir,
77-
TLSPath: cfg.TLSPath,
78-
CheckVersion: LoopMinRequiredLndVersion,
79+
LndAddress: cfg.Host,
80+
Network: network,
81+
MacaroonDir: cfg.MacaroonDir,
82+
TLSPath: cfg.TLSPath,
83+
CheckVersion: LoopMinRequiredLndVersion,
84+
BlockUntilChainSynced: true,
85+
ChainSyncCtx: syncCtx,
7986
}
8087

8188
// If a custom lnd connection is specified we use that
@@ -87,6 +94,25 @@ func newListenerCfg(config *Config, rpcCfg RPCConfig) *listenerCfg {
8794
}
8895
}
8996

97+
// Before we try to get our client connection, setup
98+
// a goroutine which will cancel our lndclient if loopd
99+
// is terminated, or exit if our context is cancelled.
100+
go func() {
101+
select {
102+
// If the client decides to kill loop before
103+
// lnd is synced, we cancel our context, which
104+
// will unblock lndclient.
105+
case <-signal.ShutdownChannel():
106+
cancel()
107+
108+
// If our sync context was cancelled, we know
109+
// that the function exited, which means that
110+
// our client synced.
111+
case <-syncCtx.Done():
112+
}
113+
}()
114+
115+
// This will block until lnd is synced to chain.
90116
return lndclient.NewLndServices(svcCfg)
91117
},
92118
}
@@ -168,10 +194,14 @@ func Run(rpcCfg RPCConfig) error {
168194

169195
lisCfg := newListenerCfg(&config, rpcCfg)
170196

197+
// Start listening for signal interrupts regardless of which command
198+
// we are running. When our command tries to get a lnd connection, it
199+
// blocks until lnd is synced. We listen for interrupts so that we can
200+
// shutdown the daemon while waiting for sync to complete.
201+
signal.Intercept()
202+
171203
// Execute command.
172204
if parser.Active == nil {
173-
signal.Intercept()
174-
175205
daemon := New(&config, lisCfg)
176206
if err := daemon.Start(); err != nil {
177207
return err

0 commit comments

Comments
 (0)