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

lightningnetwork / lnd / 13536249039

26 Feb 2025 03:42AM UTC coverage: 57.462% (-1.4%) from 58.835%
13536249039

Pull #8453

github

Roasbeef
peer: update chooseDeliveryScript to gen script if needed

In this commit, we update `chooseDeliveryScript` to generate a new
script if needed. This allows us to fold in a few other lines that
always followed this function into this expanded function.

The tests have been updated accordingly.
Pull Request #8453: [4/4] - multi: integrate new rbf coop close FSM into the existing peer flow

275 of 1318 new or added lines in 22 files covered. (20.86%)

19521 existing lines in 257 files now uncovered.

103858 of 180741 relevant lines covered (57.46%)

24750.23 hits per line

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

76.06
/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] {
31✔
203

31✔
204
        return StateMachine[Event, Env]{
31✔
205
                cfg: cfg,
31✔
206
                log: log.WithPrefix(
31✔
207
                        fmt.Sprintf("FSM(%v):", cfg.Env.Name()),
31✔
208
                ),
31✔
209
                events:         make(chan Event, 1),
31✔
210
                stateQuery:     make(chan stateQuery[Event, Env]),
31✔
211
                gm:             *fn.NewGoroutineManager(),
31✔
212
                newStateEvents: fn.NewEventDistributor[State[Event, Env]](),
31✔
213
                quit:           make(chan struct{}),
31✔
214
        }
31✔
215
}
31✔
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) {
31✔
220
        s.startOnce.Do(func() {
62✔
221
                _ = s.gm.Go(ctx, func(ctx context.Context) {
62✔
222
                        s.driveMachine(ctx)
31✔
223
                })
31✔
224
        })
225
}
226

227
// Stop stops the state machine. This will block until the state machine has
228
// reached a stopping point.
229
func (s *StateMachine[Event, Env]) Stop() {
42✔
230
        s.stopOnce.Do(func() {
73✔
231
                close(s.quit)
31✔
232
                s.gm.Stop()
31✔
233
        })
31✔
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) {
38✔
240
        s.log.DebugS(ctx, "Sending event",
38✔
241
                "event", lnutils.SpewLogClosure(event))
38✔
242

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

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

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

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

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

279
        s.log.DebugS(ctx, "Sending msg", "msg", lnutils.SpewLogClosure(msg))
1✔
280

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

1✔
288
                event.WhenSome(func(event Event) {
2✔
289
                        s.SendEvent(ctx, event)
1✔
290

1✔
291
                        processed = true
1✔
292
                })
1✔
293
        })
294

295
        return processed
1✔
296
}
297

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

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

308
        return fn.RecvOrTimeout(query.CurrentState, time.Second)
18✔
309
}
310

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

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

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

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

31✔
324
        s.newStateEvents.RegisterSubscriber(subscriber)
31✔
325

31✔
326
        return subscriber
31✔
327
}
31✔
328

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

31✔
334
        _ = s.newStateEvents.RemoveSubscriber(sub)
31✔
335
}
31✔
336

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

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

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

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

2✔
368
                                                s.SendEvent(ctx, event)
2✔
369
                                        },
2✔
370
                                )
371

372
                                if !launched {
2✔
373
                                        return ErrStateMachineShutdown
×
374
                                }
×
375

376
                                return nil
2✔
377
                        })
378
                }
379

380
                // If this doesn't have a SendWhen predicate, then we can just
381
                // send it off right away.
382
                if !daemonEvent.SendWhen.IsSome() {
29✔
383
                        return sendAndCleanUp()
13✔
384
                }
13✔
385

386
                // Otherwise, this has a SendWhen predicate, so we'll need
387
                // launch a goroutine to poll the SendWhen, then send only once
388
                // the predicate is true.
389
                launched := s.gm.Go(ctx, func(ctx context.Context) {
6✔
390
                        predicateTicker := time.NewTicker(
3✔
391
                                s.cfg.CustomPollInterval.UnwrapOr(pollInterval),
3✔
392
                        )
3✔
393
                        defer predicateTicker.Stop()
3✔
394

3✔
395
                        s.log.InfoS(ctx, "Waiting for send predicate to be true")
3✔
396

3✔
397
                        for {
8✔
398
                                select {
5✔
399
                                case <-predicateTicker.C:
4✔
400
                                        canSend := fn.MapOptionZ(
4✔
401
                                                daemonEvent.SendWhen,
4✔
402
                                                func(pred SendPredicate) bool {
8✔
403
                                                        return pred()
4✔
404
                                                },
4✔
405
                                        )
406

407
                                        if canSend {
6✔
408
                                                s.log.InfoS(ctx, "Send active predicate")
2✔
409

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

415
                                                return
2✔
416
                                        }
417

418
                                case <-ctx.Done():
1✔
419
                                        return
1✔
420
                                }
421
                        }
422
                })
423

424
                if !launched {
3✔
425
                        return ErrStateMachineShutdown
×
426
                }
×
427

428
                return nil
3✔
429

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

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

443
                return nil
7✔
444

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

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

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

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

476
                                        return
×
477

478
                                case <-ctx.Done():
27✔
479
                                        return
27✔
480
                                }
481
                        }
482
                })
483

484
                if !launched {
27✔
485
                        return ErrStateMachineShutdown
×
486
                }
×
487

488
                return nil
27✔
489

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

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

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

520
                                        return
×
521

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

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

532
                return nil
×
533
        }
534

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

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

38✔
545
        s.log.DebugS(ctx, "Applying new event",
38✔
546
                "event", lnutils.SpewLogClosure(newEvent))
38✔
547

38✔
548
        eventQueue := fn.NewQueue(newEvent)
38✔
549

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

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

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

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

5✔
592
                                        eventQueue.Enqueue(inEvent)
5✔
593
                                }
5✔
594

595
                                return nil
22✔
596
                        })
597
                        if err != nil {
32✔
598
                                return err
×
599
                        }
×
600

601
                        s.log.InfoS(ctx, "State transition",
32✔
602
                                btclog.Fmt("from_state", "%v", currentState),
32✔
603
                                btclog.Fmt("to_state", "%v", transition.NextState))
32✔
604

32✔
605
                        // With our events processed, we'll now update our
32✔
606
                        // internal state.
32✔
607
                        currentState = transition.NextState
32✔
608

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

32✔
615
                        return nil
32✔
616
                })
617
                if err != nil {
54✔
618
                        return currentState, err
11✔
619
                }
11✔
620
        }
621

622
        return currentState, nil
27✔
623
}
624

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

31✔
631
        currentState := s.cfg.InitialState
31✔
632

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

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

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

11✔
659
                                s.log.ErrorS(ctx, "Unable to apply event", err)
11✔
660

11✔
661
                                // An error occurred, so we'll tear down the
11✔
662
                                // entire state machine as we can't proceed.
11✔
663
                                go s.Stop()
11✔
664

11✔
665
                                return
11✔
666
                        }
11✔
667

668
                        currentState = newState
27✔
669

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

677
                case <-s.gm.Done():
20✔
678
                        return
20✔
679
                }
680
        }
681
}
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