• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lightningnetwork / lnd / 14471480810

15 Apr 2025 02:05PM UTC coverage: 58.611% (-10.5%) from 69.088%
14471480810

Pull #9702

github

web-flow
Merge 811aac3b1 into 014706cc3
Pull Request #9702: multi: make payment address mandatory

2 of 4 new or added lines in 1 file covered. (50.0%)

28451 existing lines in 450 files now uncovered.

97194 of 165828 relevant lines covered (58.61%)

1.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

66.97
/protofsm/state_machine.go
1
package protofsm
2

3
import (
4
        "context"
5
        "fmt"
6
        "sync"
7
        "time"
8

9
        "github.com/btcsuite/btcd/btcec/v2"
10
        "github.com/btcsuite/btcd/chaincfg/chainhash"
11
        "github.com/btcsuite/btcd/wire"
12
        "github.com/btcsuite/btclog/v2"
13
        "github.com/lightningnetwork/lnd/chainntnfs"
14
        "github.com/lightningnetwork/lnd/fn/v2"
15
        "github.com/lightningnetwork/lnd/lnutils"
16
        "github.com/lightningnetwork/lnd/lnwire"
17
        "github.com/lightningnetwork/lnd/msgmux"
18
)
19

20
const (
21
        // pollInterval is the interval at which we'll poll the SendWhen
22
        // predicate if specified.
23
        pollInterval = time.Millisecond * 100
24
)
25

26
var (
27
        // ErrStateMachineShutdown occurs when trying to feed an event to a
28
        // StateMachine that has been asked to Stop.
29
        ErrStateMachineShutdown = fmt.Errorf("StateMachine is shutting down")
30
)
31

32
// EmittedEvent is a special type that can be emitted by a state transition.
33
// This can container internal events which are to be routed back to the state,
34
// or external events which are to be sent to the daemon.
35
type EmittedEvent[Event any] struct {
36
        // InternalEvent is an optional internal event that is to be routed
37
        // back to the target state. This enables state to trigger one or many
38
        // state transitions without a new external event.
39
        InternalEvent []Event
40

41
        // ExternalEvent is an optional external event that is to be sent to
42
        // the daemon for dispatch. Usually, this is some form of I/O.
43
        ExternalEvents DaemonEventSet
44
}
45

46
// StateTransition is a state transition type. It denotes the next state to go
47
// to, and also the set of events to emit.
48
type StateTransition[Event any, Env Environment] struct {
49
        // NextState is the next state to transition to.
50
        NextState State[Event, Env]
51

52
        // NewEvents is the set of events to emit.
53
        NewEvents fn.Option[EmittedEvent[Event]]
54
}
55

56
// Environment is an abstract interface that represents the environment that
57
// the state machine will execute using. From the PoV of the main state machine
58
// executor, we just care about being able to clean up any resources that were
59
// allocated by the environment.
60
type Environment interface {
61
        // Name returns the name of the environment. This is used to uniquely
62
        // identify the environment of related state machines.
63
        Name() string
64
}
65

66
// State defines an abstract state along, namely its state transition function
67
// that takes as input an event and an environment, and returns a state
68
// transition (next state, and set of events to emit). As state can also either
69
// be terminal, or not, a terminal event causes state execution to halt.
70
type State[Event any, Env Environment] interface {
71
        // ProcessEvent takes an event and an environment, and returns a new
72
        // state transition. This will be iteratively called until either a
73
        // terminal state is reached, or no further internal events are
74
        // emitted.
75
        ProcessEvent(event Event, env Env) (*StateTransition[Event, Env], error)
76

77
        // IsTerminal returns true if this state is terminal, and false
78
        // otherwise.
79
        IsTerminal() bool
80

81
        // String returns a human readable string that represents the state.
82
        String() string
83
}
84

85
// DaemonAdapters is a set of methods that server as adapters to bridge the
86
// pure world of the FSM to the real world of the daemon. These will be used to
87
// do things like broadcast transactions, or send messages to peers.
88
type DaemonAdapters interface {
89
        // SendMessages sends the target set of messages to the target peer.
90
        SendMessages(btcec.PublicKey, []lnwire.Message) error
91

92
        // BroadcastTransaction broadcasts a transaction with the target label.
93
        BroadcastTransaction(*wire.MsgTx, string) error
94

95
        // RegisterConfirmationsNtfn registers an intent to be notified once
96
        // txid reaches numConfs confirmations. We also pass in the pkScript as
97
        // the default light client instead needs to match on scripts created
98
        // in the block. If a nil txid is passed in, then not only should we
99
        // match on the script, but we should also dispatch once the
100
        // transaction containing the script reaches numConfs confirmations.
101
        // This can be useful in instances where we only know the script in
102
        // advance, but not the transaction containing it.
103
        //
104
        // TODO(roasbeef): could abstract further?
105
        RegisterConfirmationsNtfn(txid *chainhash.Hash, pkScript []byte,
106
                numConfs, heightHint uint32,
107
                opts ...chainntnfs.NotifierOption,
108
        ) (*chainntnfs.ConfirmationEvent, error)
109

110
        // RegisterSpendNtfn registers an intent to be notified once the target
111
        // outpoint is successfully spent within a transaction. The script that
112
        // the outpoint creates must also be specified. This allows this
113
        // interface to be implemented by BIP 158-like filtering.
114
        RegisterSpendNtfn(outpoint *wire.OutPoint, pkScript []byte,
115
                heightHint uint32) (*chainntnfs.SpendEvent, error)
116
}
117

118
// stateQuery is used by outside callers to query the internal state of the
119
// state machine.
120
type stateQuery[Event any, Env Environment] struct {
121
        // CurrentState is a channel that will be sent the current state of the
122
        // state machine.
123
        CurrentState chan State[Event, Env]
124
}
125

126
// StateMachine represents an abstract FSM that is able to process new incoming
127
// events and drive a state machine to termination. This implementation uses
128
// type params to abstract over the types of events and environment. Events
129
// trigger new state transitions, that use the environment to perform some
130
// action.
131
//
132
// TODO(roasbeef): terminal check, daemon event execution, init?
133
type StateMachine[Event any, Env Environment] struct {
134
        cfg StateMachineCfg[Event, Env]
135

136
        log btclog.Logger
137

138
        // events is the channel that will be used to send new events to the
139
        // FSM.
140
        events chan Event
141

142
        // newStateEvents is an EventDistributor that will be used to notify
143
        // any relevant callers of new state transitions that occur.
144
        newStateEvents *fn.EventDistributor[State[Event, Env]]
145

146
        // stateQuery is a channel that will be used by outside callers to
147
        // query the internal state machine state.
148
        stateQuery chan stateQuery[Event, Env]
149

150
        gm   fn.GoroutineManager
151
        quit chan struct{}
152

153
        startOnce sync.Once
154
        stopOnce  sync.Once
155
}
156

157
// ErrorReporter is an interface that's used to report errors that occur during
158
// state machine execution.
159
type ErrorReporter interface {
160
        // ReportError is a method that's used to report an error that occurred
161
        // during state machine execution.
162
        ReportError(err error)
163
}
164

165
// StateMachineCfg is a configuration struct that's used to create a new state
166
// machine.
167
type StateMachineCfg[Event any, Env Environment] struct {
168
        // ErrorReporter is used to report errors that occur during state
169
        // transitions.
170
        ErrorReporter ErrorReporter
171

172
        // Daemon is a set of adapters that will be used to bridge the FSM to
173
        // the daemon.
174
        Daemon DaemonAdapters
175

176
        // InitialState is the initial state of the state machine.
177
        InitialState State[Event, Env]
178

179
        // Env is the environment that the state machine will use to execute.
180
        Env Env
181

182
        // InitEvent is an optional event that will be sent to the state
183
        // machine as if it was emitted at the onset of the state machine. This
184
        // can be used to set up tracking state such as a txid confirmation
185
        // event.
186
        InitEvent fn.Option[DaemonEvent]
187

188
        // MsgMapper is an optional message mapper that can be used to map
189
        // normal wire messages into FSM events.
190
        MsgMapper fn.Option[MsgMapper[Event]]
191

192
        // CustomPollInterval is an optional custom poll interval that can be
193
        // used to set a quicker interval for tests.
194
        CustomPollInterval fn.Option[time.Duration]
195
}
196

197
// NewStateMachine creates a new state machine given a set of daemon adapters,
198
// an initial state, an environment, and an event to process as if emitted at
199
// the onset of the state machine. Such an event can be used to set up tracking
200
// state such as a txid confirmation event.
201
func NewStateMachine[Event any, Env Environment](
202
        cfg StateMachineCfg[Event, Env]) StateMachine[Event, Env] {
3✔
203

3✔
204
        return StateMachine[Event, Env]{
3✔
205
                cfg: cfg,
3✔
206
                log: log.WithPrefix(
3✔
207
                        fmt.Sprintf("FSM(%v):", cfg.Env.Name()),
3✔
208
                ),
3✔
209
                events:         make(chan Event, 1),
3✔
210
                stateQuery:     make(chan stateQuery[Event, Env]),
3✔
211
                gm:             *fn.NewGoroutineManager(),
3✔
212
                newStateEvents: fn.NewEventDistributor[State[Event, Env]](),
3✔
213
                quit:           make(chan struct{}),
3✔
214
        }
3✔
215
}
3✔
216

217
// Start starts the state machine. This will spawn a goroutine that will drive
218
// the state machine to completion.
219
func (s *StateMachine[Event, Env]) Start(ctx context.Context) {
3✔
220
        s.startOnce.Do(func() {
6✔
221
                _ = s.gm.Go(ctx, func(ctx context.Context) {
6✔
222
                        s.driveMachine(ctx)
3✔
223
                })
3✔
224
        })
225
}
226

227
// Stop stops the state machine. This will block until the state machine has
228
// reached a stopping point.
UNCOV
229
func (s *StateMachine[Event, Env]) Stop() {
×
UNCOV
230
        s.stopOnce.Do(func() {
×
UNCOV
231
                close(s.quit)
×
UNCOV
232
                s.gm.Stop()
×
UNCOV
233
        })
×
234
}
235

236
// SendEvent sends a new event to the state machine.
237
//
238
// TODO(roasbeef): bool if processed?
239
func (s *StateMachine[Event, Env]) SendEvent(ctx context.Context, event Event) {
3✔
240
        s.log.Debugf("Sending event %T", event)
3✔
241

3✔
242
        select {
3✔
243
        case s.events <- event:
3✔
244
        case <-ctx.Done():
×
245
                return
×
246
        case <-s.quit:
×
247
                return
×
248
        }
249
}
250

251
// CanHandle returns true if the target message can be routed to the state
252
// machine.
253
func (s *StateMachine[Event, Env]) CanHandle(msg msgmux.PeerMsg) bool {
3✔
254
        cfgMapper := s.cfg.MsgMapper
3✔
255
        return fn.MapOptionZ(cfgMapper, func(mapper MsgMapper[Event]) bool {
6✔
256
                return mapper.MapMsg(msg).IsSome()
3✔
257
        })
3✔
258
}
259

260
// Name returns the name of the state machine's environment.
261
func (s *StateMachine[Event, Env]) Name() string {
3✔
262
        return s.cfg.Env.Name()
3✔
263
}
3✔
264

265
// SendMessage attempts to send a wire message to the state machine. If the
266
// message can be mapped using the default message mapper, then true is
267
// returned indicating that the message was processed. Otherwise, false is
268
// returned.
269
func (s *StateMachine[Event, Env]) SendMessage(ctx context.Context,
270
        msg msgmux.PeerMsg) bool {
3✔
271

3✔
272
        // If we have no message mapper, then return false as we can't process
3✔
273
        // this message.
3✔
274
        if !s.cfg.MsgMapper.IsSome() {
3✔
275
                return false
×
276
        }
×
277

278
        s.log.DebugS(ctx, "Sending msg", "msg", lnutils.SpewLogClosure(msg))
3✔
279

3✔
280
        // Otherwise, try to map the message using the default message mapper.
3✔
281
        // If we can't extract an event, then we'll return false to indicate
3✔
282
        // that the message wasn't processed.
3✔
283
        var processed bool
3✔
284
        s.cfg.MsgMapper.WhenSome(func(mapper MsgMapper[Event]) {
6✔
285
                event := mapper.MapMsg(msg)
3✔
286

3✔
287
                event.WhenSome(func(event Event) {
6✔
288
                        s.SendEvent(ctx, event)
3✔
289

3✔
290
                        processed = true
3✔
291
                })
3✔
292
        })
293

294
        return processed
3✔
295
}
296

297
// CurrentState returns the current state of the state machine.
298
func (s *StateMachine[Event, Env]) CurrentState() (State[Event, Env], error) {
3✔
299
        query := stateQuery[Event, Env]{
3✔
300
                CurrentState: make(chan State[Event, Env], 1),
3✔
301
        }
3✔
302

3✔
303
        if !fn.SendOrQuit(s.stateQuery, query, s.quit) {
3✔
304
                return nil, ErrStateMachineShutdown
×
305
        }
×
306

307
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
3✔
308
}
309

310
// StateSubscriber represents an active subscription to be notified of new
311
// state transitions.
312
type StateSubscriber[E any, F Environment] *fn.EventReceiver[State[E, F]]
313

314
// RegisterStateEvents registers a new event listener that will be notified of
315
// new state transitions.
316
func (s *StateMachine[Event, Env]) RegisterStateEvents() StateSubscriber[
317
        Event, Env] {
3✔
318

3✔
319
        subscriber := fn.NewEventReceiver[State[Event, Env]](10)
3✔
320

3✔
321
        // TODO(roasbeef): instead give the state and the input event?
3✔
322

3✔
323
        s.newStateEvents.RegisterSubscriber(subscriber)
3✔
324

3✔
325
        return subscriber
3✔
326
}
3✔
327

328
// RemoveStateSub removes the target state subscriber from the set of active
329
// subscribers.
330
func (s *StateMachine[Event, Env]) RemoveStateSub(sub StateSubscriber[
331
        Event, Env]) {
3✔
332

3✔
333
        _ = s.newStateEvents.RemoveSubscriber(sub)
3✔
334
}
3✔
335

336
// executeDaemonEvent executes a daemon event, which is a special type of event
337
// that can be emitted as part of the state transition function of the state
338
// machine. An error is returned if the type of event is unknown.
339
func (s *StateMachine[Event, Env]) executeDaemonEvent(ctx context.Context,
340
        event DaemonEvent) error {
3✔
341

3✔
342
        switch daemonEvent := event.(type) {
3✔
343
        // This is a send message event, so we'll send the event, and also mind
344
        // any preconditions as well as post-send events.
345
        case *SendMsgEvent[Event]:
3✔
346
                sendAndCleanUp := func() error {
6✔
347
                        s.log.DebugS(ctx, "Sending message:",
3✔
348
                                btclog.Hex6("target", daemonEvent.TargetPeer.SerializeCompressed()),
3✔
349
                                "messages", lnutils.SpewLogClosure(daemonEvent.Msgs))
3✔
350

3✔
351
                        err := s.cfg.Daemon.SendMessages(
3✔
352
                                daemonEvent.TargetPeer, daemonEvent.Msgs,
3✔
353
                        )
3✔
354
                        if err != nil {
3✔
355
                                return fmt.Errorf("unable to send msgs: %w",
×
356
                                        err)
×
357
                        }
×
358

359
                        // If a post-send event was specified, then we'll funnel
360
                        // that back into the main state machine now as well.
361
                        return fn.MapOptionZ(daemonEvent.PostSendEvent, func(event Event) error { //nolint:ll
6✔
362
                                launched := s.gm.Go(
3✔
363
                                        ctx, func(ctx context.Context) {
6✔
364
                                                s.log.DebugS(ctx, "Sending post-send event",
3✔
365
                                                        "event", lnutils.SpewLogClosure(event))
3✔
366

3✔
367
                                                s.SendEvent(ctx, event)
3✔
368
                                        },
3✔
369
                                )
370

371
                                if !launched {
3✔
372
                                        return ErrStateMachineShutdown
×
373
                                }
×
374

375
                                return nil
3✔
376
                        })
377
                }
378

379
                canSend := func() bool {
6✔
380
                        return fn.MapOptionZ(
3✔
381
                                daemonEvent.SendWhen,
3✔
382
                                func(pred SendPredicate) bool {
6✔
383
                                        return pred()
3✔
384
                                },
3✔
385
                        )
386
                }
387

388
                // If this doesn't have a SendWhen predicate, or if it's already
389
                // true, then we can just send it off right away.
390
                if !daemonEvent.SendWhen.IsSome() || canSend() {
6✔
391
                        return sendAndCleanUp()
3✔
392
                }
3✔
393

394
                // Otherwise, this has a SendWhen predicate, so we'll need
395
                // launch a goroutine to poll the SendWhen, then send only once
396
                // the predicate is true.
UNCOV
397
                launched := s.gm.Go(ctx, func(ctx context.Context) {
×
UNCOV
398
                        predicateTicker := time.NewTicker(
×
UNCOV
399
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
×
UNCOV
400
                        )
×
UNCOV
401
                        defer predicateTicker.Stop()
×
UNCOV
402

×
UNCOV
403
                        s.log.InfoS(ctx, "Waiting for send predicate to be true")
×
UNCOV
404

×
UNCOV
405
                        for {
×
UNCOV
406
                                select {
×
UNCOV
407
                                case <-predicateTicker.C:
×
UNCOV
408
                                        if canSend() {
×
UNCOV
409
                                                s.log.InfoS(ctx, "Send active predicate")
×
UNCOV
410

×
UNCOV
411
                                                err := sendAndCleanUp()
×
UNCOV
412
                                                if err != nil {
×
413
                                                        s.log.ErrorS(ctx, "Unable to send message", err)
×
414
                                                }
×
415

UNCOV
416
                                                return
×
417
                                        }
418

UNCOV
419
                                case <-ctx.Done():
×
UNCOV
420
                                        return
×
421
                                }
422
                        }
423
                })
424

UNCOV
425
                if !launched {
×
426
                        return ErrStateMachineShutdown
×
427
                }
×
428

UNCOV
429
                return nil
×
430

431
        // If this is a broadcast transaction event, then we'll broadcast with
432
        // the label attached.
433
        case *BroadcastTxn:
3✔
434
                s.log.DebugS(ctx, "Broadcasting txn",
3✔
435
                        "txid", daemonEvent.Tx.TxHash())
3✔
436

3✔
437
                err := s.cfg.Daemon.BroadcastTransaction(
3✔
438
                        daemonEvent.Tx, daemonEvent.Label,
3✔
439
                )
3✔
440
                if err != nil {
6✔
441
                        log.Errorf("unable to broadcast txn: %v", err)
3✔
442
                }
3✔
443

444
                return nil
3✔
445

446
        // The state machine has requested a new event to be sent once a
447
        // transaction spending a specified outpoint has confirmed.
448
        case *RegisterSpend[Event]:
3✔
449
                s.log.DebugS(ctx, "Registering spend",
3✔
450
                        "outpoint", daemonEvent.OutPoint)
3✔
451

3✔
452
                spendEvent, err := s.cfg.Daemon.RegisterSpendNtfn(
3✔
453
                        &daemonEvent.OutPoint, daemonEvent.PkScript,
3✔
454
                        daemonEvent.HeightHint,
3✔
455
                )
3✔
456
                if err != nil {
3✔
457
                        return fmt.Errorf("unable to register spend: %w", err)
×
458
                }
×
459

460
                launched := s.gm.Go(ctx, func(ctx context.Context) {
6✔
461
                        for {
6✔
462
                                select {
3✔
463
                                case spend, ok := <-spendEvent.Spend:
3✔
464
                                        if !ok {
6✔
465
                                                return
3✔
466
                                        }
3✔
467

468
                                        // If there's a post-send event, then
469
                                        // we'll send that into the current
470
                                        // state now.
471
                                        postSpend := daemonEvent.PostSpendEvent
3✔
472
                                        postSpend.WhenSome(func(f SpendMapper[Event]) { //nolint:ll
6✔
473
                                                customEvent := f(spend)
3✔
474
                                                s.SendEvent(ctx, customEvent)
3✔
475
                                        })
3✔
476

477
                                        return
3✔
478

UNCOV
479
                                case <-ctx.Done():
×
UNCOV
480
                                        return
×
481
                                }
482
                        }
483
                })
484

485
                if !launched {
3✔
486
                        return ErrStateMachineShutdown
×
487
                }
×
488

489
                return nil
3✔
490

491
        // The state machine has requested a new event to be sent once a
492
        // specified txid+pkScript pair has confirmed.
493
        case *RegisterConf[Event]:
×
494
                s.log.DebugS(ctx, "Registering conf",
×
495
                        "txid", daemonEvent.Txid)
×
496

×
497
                numConfs := daemonEvent.NumConfs.UnwrapOr(1)
×
498
                confEvent, err := s.cfg.Daemon.RegisterConfirmationsNtfn(
×
499
                        &daemonEvent.Txid, daemonEvent.PkScript,
×
500
                        numConfs, daemonEvent.HeightHint,
×
501
                )
×
502
                if err != nil {
×
503
                        return fmt.Errorf("unable to register conf: %w", err)
×
504
                }
×
505

506
                launched := s.gm.Go(ctx, func(ctx context.Context) {
×
507
                        for {
×
508
                                select {
×
509
                                case <-confEvent.Confirmed:
×
510
                                        // If there's a post-conf event, then
×
511
                                        // we'll send that into the current
×
512
                                        // state now.
×
513
                                        //
×
514
                                        // TODO(roasbeef): refactor to
×
515
                                        // dispatchAfterRecv w/ above
×
516
                                        postConf := daemonEvent.PostConfEvent
×
517
                                        postConf.WhenSome(func(e Event) {
×
518
                                                s.SendEvent(ctx, e)
×
519
                                        })
×
520

521
                                        return
×
522

523
                                case <-ctx.Done():
×
524
                                        return
×
525
                                }
526
                        }
527
                })
528

529
                if !launched {
×
530
                        return ErrStateMachineShutdown
×
531
                }
×
532

533
                return nil
×
534
        }
535

536
        return fmt.Errorf("unknown daemon event: %T", event)
×
537
}
538

539
// applyEvents applies a new event to the state machine. This will continue
540
// until no further events are emitted by the state machine. Along the way,
541
// we'll also ensure to execute any daemon events that are emitted.
542
func (s *StateMachine[Event, Env]) applyEvents(ctx context.Context,
543
        currentState State[Event, Env], newEvent Event) (State[Event, Env],
544
        error) {
3✔
545

3✔
546
        eventQueue := fn.NewQueue(newEvent)
3✔
547

3✔
548
        // Given the next event to handle, we'll process the event, then add
3✔
549
        // any new emitted internal events to our event queue. This continues
3✔
550
        // until we reach a terminal state, or we run out of internal events to
3✔
551
        // process.
3✔
552
        //
3✔
553
        //nolint:ll
3✔
554
        for nextEvent := eventQueue.Dequeue(); nextEvent.IsSome(); nextEvent = eventQueue.Dequeue() {
6✔
555
                err := fn.MapOptionZ(nextEvent, func(event Event) error {
6✔
556
                        s.log.DebugS(ctx, "Processing event",
3✔
557
                                "event", lnutils.SpewLogClosure(event))
3✔
558

3✔
559
                        // Apply the state transition function of the current
3✔
560
                        // state given this new event and our existing env.
3✔
561
                        transition, err := currentState.ProcessEvent(
3✔
562
                                event, s.cfg.Env,
3✔
563
                        )
3✔
564
                        if err != nil {
3✔
UNCOV
565
                                return err
×
UNCOV
566
                        }
×
567

568
                        newEvents := transition.NewEvents
3✔
569
                        err = fn.MapOptionZ(newEvents, func(events EmittedEvent[Event]) error { //nolint:ll
6✔
570
                                // With the event processed, we'll process any
3✔
571
                                // new daemon events that were emitted as part
3✔
572
                                // of this new state transition.
3✔
573
                                for _, dEvent := range events.ExternalEvents {
6✔
574
                                        err := s.executeDaemonEvent(
3✔
575
                                                ctx, dEvent,
3✔
576
                                        )
3✔
577
                                        if err != nil {
3✔
578
                                                return err
×
579
                                        }
×
580
                                }
581

582
                                // Next, we'll add any new emitted events to our
583
                                // event queue.
584
                                //
585
                                //nolint:ll
586
                                for _, inEvent := range events.InternalEvent {
6✔
587
                                        s.log.DebugS(ctx, "Adding new internal event to queue",
3✔
588
                                                "event", lnutils.SpewLogClosure(inEvent))
3✔
589

3✔
590
                                        eventQueue.Enqueue(inEvent)
3✔
591
                                }
3✔
592

593
                                return nil
3✔
594
                        })
595
                        if err != nil {
3✔
596
                                return err
×
597
                        }
×
598

599
                        s.log.InfoS(ctx, "State transition",
3✔
600
                                btclog.Fmt("from_state", "%v", currentState),
3✔
601
                                btclog.Fmt("to_state", "%v", transition.NextState))
3✔
602

3✔
603
                        // With our events processed, we'll now update our
3✔
604
                        // internal state.
3✔
605
                        currentState = transition.NextState
3✔
606

3✔
607
                        // Notify our subscribers of the new state transition.
3✔
608
                        //
3✔
609
                        // TODO(roasbeef): will only give us the outer state?
3✔
610
                        //  * let FSMs choose which state to emit?
3✔
611
                        s.newStateEvents.NotifySubscribers(currentState)
3✔
612

3✔
613
                        return nil
3✔
614
                })
615
                if err != nil {
3✔
UNCOV
616
                        return currentState, err
×
UNCOV
617
                }
×
618
        }
619

620
        return currentState, nil
3✔
621
}
622

623
// driveMachine is the main event loop of the state machine. It accepts any new
624
// incoming events, and then drives the state machine forward until it reaches
625
// a terminal state.
626
func (s *StateMachine[Event, Env]) driveMachine(ctx context.Context) {
3✔
627
        s.log.DebugS(ctx, "Starting state machine")
3✔
628

3✔
629
        currentState := s.cfg.InitialState
3✔
630

3✔
631
        // Before we start, if we have an init daemon event specified, then
3✔
632
        // we'll handle that now.
3✔
633
        err := fn.MapOptionZ(s.cfg.InitEvent, func(event DaemonEvent) error {
6✔
634
                return s.executeDaemonEvent(ctx, event)
3✔
635
        })
3✔
636
        if err != nil {
3✔
637
                s.log.ErrorS(ctx, "Unable to execute init event", err)
×
638
                return
×
639
        }
×
640

641
        // We just started driving the state machine, so we'll notify our
642
        // subscribers of this starting state.
643
        s.newStateEvents.NotifySubscribers(currentState)
3✔
644

3✔
645
        for {
6✔
646
                select {
3✔
647
                // We have a new external event, so we'll drive the state
648
                // machine forward until we either run out of internal events,
649
                // or we reach a terminal state.
650
                case newEvent := <-s.events:
3✔
651
                        newState, err := s.applyEvents(
3✔
652
                                ctx, currentState, newEvent,
3✔
653
                        )
3✔
654
                        if err != nil {
3✔
UNCOV
655
                                s.cfg.ErrorReporter.ReportError(err)
×
UNCOV
656

×
UNCOV
657
                                s.log.ErrorS(ctx, "Unable to apply event", err)
×
UNCOV
658

×
UNCOV
659
                                // An error occurred, so we'll tear down the
×
UNCOV
660
                                // entire state machine as we can't proceed.
×
UNCOV
661
                                go s.Stop()
×
UNCOV
662

×
UNCOV
663
                                return
×
UNCOV
664
                        }
×
665

666
                        currentState = newState
3✔
667

668
                // An outside caller is querying our state, so we'll return the
669
                // latest state.
670
                case stateQuery := <-s.stateQuery:
3✔
671
                        if !fn.SendOrQuit(stateQuery.CurrentState, currentState, s.quit) { //nolint:ll
3✔
672
                                return
×
673
                        }
×
674

UNCOV
675
                case <-s.gm.Done():
×
UNCOV
676
                        return
×
677
                }
678
        }
679
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc