forked from lightningnetwork/lnd
/
initchainctrl_service.go
74 lines (64 loc) · 1.64 KB
/
initchainctrl_service.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
package initchainsyncrpc
import (
"fmt"
"time"
"github.com/decred/dcrlnd/lnwallet"
)
// Server implements the initial chain sync gRPC service server.
type Server struct {
chainCtrl lnwallet.WalletController
chainCtrlSetChan chan struct{}
}
// A compile time check to ensure that Server fully implements the
// InitialChainSync gRPC service.
var _ InitialChainSyncServer = (*Server)(nil)
// NewInitCHainSyncService initializes a new InitChainSyncService.
func New() *Server {
return &Server{
chainCtrlSetChan: make(chan struct{}),
}
}
// SetChainControl sets the internal chain/wallet controller. MUST only be
// called once.
func (s *Server) SetChainControl(cc lnwallet.WalletController) {
s.chainCtrl = cc
close(s.chainCtrlSetChan)
}
func (s *Server) SubscribeChainSync(sub *ChainSyncSubscription, svr InitialChainSync_SubscribeChainSyncServer) error {
// Wait until the chain control is set.
ccSet := false
for !ccSet {
select {
case <-s.chainCtrlSetChan:
ccSet = true
case <-svr.Context().Done():
return svr.Context().Err()
}
}
var synced = false
delay := time.Millisecond
for !synced {
select {
case <-svr.Context().Done():
return svr.Context().Err()
case <-s.chainCtrl.InitialSyncChannel():
synced = true
case <-time.After(delay):
}
height, hash, ts, err := s.chainCtrl.BestBlock()
if err != nil {
return fmt.Errorf("unable to fetch current best block: %v", err)
}
updt := &ChainSyncUpdate{
BlockHeight: height,
BlockHash: hash[:],
BlockTimestamp: ts,
Synced: synced,
}
if err := svr.Send(updt); err != nil {
return err
}
delay = 5 * time.Second
}
return nil
}