/
chainmonitor.go
255 lines (218 loc) · 6.92 KB
/
chainmonitor.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Copyright (c) 2018, The Decred developers
// Copyright (c) 2017, Jonathan Chappelow
// See LICENSE for details.
package stakedb
import (
"fmt"
"sync"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil"
)
// ReorgData contains the information from a reoranization notification
type ReorgData struct {
OldChainHead chainhash.Hash
OldChainHeight int32
NewChainHead chainhash.Hash
NewChainHeight int32
WG *sync.WaitGroup
}
// ChainMonitor connects blocks to the stake DB as they come in.
type ChainMonitor struct {
db *StakeDatabase
quit chan struct{}
wg *sync.WaitGroup
blockChan chan *chainhash.Hash
reorgChan chan *ReorgData
syncConnect sync.Mutex
ConnectingLock chan struct{}
DoneConnecting chan struct{}
// reorg handling
sync.Mutex
reorgData *ReorgData
sideChain []chainhash.Hash
reorganizing bool
}
// NewChainMonitor creates a new ChainMonitor
func (db *StakeDatabase) NewChainMonitor(quit chan struct{}, wg *sync.WaitGroup,
blockChan chan *chainhash.Hash, reorgChan chan *ReorgData) *ChainMonitor {
return &ChainMonitor{
db: db,
quit: quit,
wg: wg,
blockChan: blockChan,
reorgChan: reorgChan,
ConnectingLock: make(chan struct{}, 1),
DoneConnecting: make(chan struct{}),
}
}
// BlockConnectedSync is the synchronous (blocking call) handler for the newly
// connected block given by the hash.
func (p *ChainMonitor) BlockConnectedSync(hash *chainhash.Hash) {
// Connections go one at a time so signals cannot be mixed
p.syncConnect.Lock()
defer p.syncConnect.Unlock()
// lock with buffered channel, accepting handoff in BlockConnectedHandler
p.ConnectingLock <- struct{}{}
p.blockChan <- hash
// wait
<-p.DoneConnecting
}
// BlockConnectedHandler handles block connected notifications, which trigger
// data collection and storage.
func (p *ChainMonitor) BlockConnectedHandler() {
defer p.wg.Done()
out:
for {
keepon:
select {
case hash, ok := <-p.blockChan:
p.Lock()
release := func() { p.Unlock() }
select {
case <-p.ConnectingLock:
// send on unbuffered channel
release = func() { p.Unlock(); p.DoneConnecting <- struct{}{} }
default:
}
if !ok {
log.Warnf("Block connected channel closed.")
release()
break out
}
// If reorganizing, the block will first go to a side chain
reorg, reorgData := p.reorganizing, p.reorgData
if reorg {
p.sideChain = append(p.sideChain, *hash)
log.Infof("Adding block %v to sidechain", *hash)
// Just append to side chain until the new main chain tip block is reached
if reorgData.NewChainHead != *hash {
release()
break keepon
}
// Once all blocks in side chain are lined up, switch over
log.Info("Switching to side chain...")
newHeight, newHash, err := p.switchToSideChain()
if err != nil {
panic(err)
}
if p.reorgData.NewChainHead != *newHash ||
p.reorgData.NewChainHeight != newHeight {
panic(fmt.Sprintf("Failed to reorg to %v. Got to %v (height %d) instead.",
p.reorgData.NewChainHead, newHash, newHeight))
}
// Reorg is complete
p.sideChain = nil
p.reorganizing = false
log.Infof("Reorganization to block %v (height %d) complete",
p.reorgData.NewChainHead, p.reorgData.NewChainHeight)
} else {
// Extend main chain
block, err := p.db.ConnectBlockHash(hash)
if err != nil {
release()
log.Error(err)
break keepon
}
log.Infof("Connected block %d to stake DB.", block.Height())
}
release()
case _, ok := <-p.quit:
if !ok {
log.Debugf("Got quit signal. Exiting block connected handler.")
break out
}
}
}
}
// switchToSideChain attempts to switch to a new side chain by: determining a
// common ancestor block, disconnecting blocks from the main chain back to this
// block, and connecting the side chain blocks onto the mainchain.
func (p *ChainMonitor) switchToSideChain() (int32, *chainhash.Hash, error) {
if len(p.sideChain) == 0 {
return 0, nil, fmt.Errorf("no side chain")
}
// Determine highest common ancestor of side chain and main chain
msgBlock, err := p.db.NodeClient.GetBlock(&p.sideChain[0])
if err != nil {
return 0, nil, fmt.Errorf("unable to get block at root of side chain")
}
block := dcrutil.NewBlock(msgBlock)
prevMsgBlock, err := p.db.NodeClient.GetBlock(&msgBlock.Header.PrevBlock)
if err != nil {
return 0, nil, fmt.Errorf("unable to get common ancestor on side chain")
}
prevBlock := dcrutil.NewBlock(prevMsgBlock)
commonAncestorHeight := block.Height() - 1
if prevBlock.Height() != commonAncestorHeight {
panic("Failed to determine common ancestor.")
}
mainTip := int64(p.db.Height())
// Disconnect blocks back to common ancestor
log.Debugf("Disconnecting %d blocks", mainTip-commonAncestorHeight)
if err = p.db.DisconnectBlocks(mainTip - commonAncestorHeight); err != nil {
return 0, nil, err
}
mainTip = int64(p.db.Height())
if mainTip != commonAncestorHeight {
panic(fmt.Sprintf("disconnect blocks failed: tip height %d, expected %d",
mainTip, commonAncestorHeight))
}
// Connect blocks in side chain onto main chain
log.Debugf("Connecting %d blocks", len(p.sideChain))
for i := range p.sideChain {
if block, err = p.db.ConnectBlockHash(&p.sideChain[i]); err != nil {
mainTip = int64(p.db.Height())
currentBlockHdr, _ := p.db.DBTipBlockHeader()
currentBlockHash := currentBlockHdr.BlockHash()
return int32(mainTip), ¤tBlockHash,
fmt.Errorf("error connecting block %v", p.sideChain[i])
}
log.Infof("Connected block %v (height %d) from side chain.",
block.Hash(), block.Height())
}
mainTip = int64(p.db.Height())
if mainTip != block.Height() {
panic("connected block height not db tip height")
}
return int32(mainTip), block.Hash(), nil
}
// ReorgHandler receives notification of a chain reorganization and initiates a
// corresponding reorganization of the stakedb.StakeDatabase.
func (p *ChainMonitor) ReorgHandler() {
defer p.wg.Done()
out:
for {
keepon:
select {
case reorgData, ok := <-p.reorgChan:
p.Lock()
if !ok {
p.Unlock()
log.Warnf("Reorg channel closed.")
break out
}
newHeight, oldHeight := reorgData.NewChainHeight, reorgData.OldChainHeight
newHash, oldHash := reorgData.NewChainHead, reorgData.OldChainHead
if p.reorganizing {
log.Errorf("Reorg notified for chain tip %v (height %v), but already "+
"processing a reorg to block %v", newHash, newHeight,
p.reorgData.NewChainHead)
p.Unlock()
break keepon
}
p.reorganizing = true
p.reorgData = reorgData
p.Unlock()
log.Infof("Reorganize started. NEW head block %v at height %d.",
newHash, newHeight)
log.Infof("Reorganize started. OLD head block %v at height %d.",
oldHash, oldHeight)
reorgData.WG.Done()
case _, ok := <-p.quit:
if !ok {
log.Debugf("Got quit signal. Exiting reorg notification handler.")
break out
}
}
}
}