/
timemanager.go
284 lines (237 loc) · 8.9 KB
/
timemanager.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package tangle
import (
"context"
"sync"
"time"
"github.com/cockroachdb/errors"
"github.com/iotaledger/hive.go/cerrors"
"github.com/iotaledger/hive.go/generics/event"
"github.com/iotaledger/hive.go/kvstore"
"github.com/iotaledger/hive.go/serix"
"github.com/iotaledger/hive.go/stringify"
"github.com/iotaledger/hive.go/timeutil"
"github.com/iotaledger/goshimmer/packages/clock"
"github.com/iotaledger/goshimmer/packages/epoch"
)
const (
lastConfirmedKey = "LastAcceptedBlock"
)
// region TimeManager //////////////////////////////////////////////////////////////////////////////////////////////////
// TimeManager is a Tangle component that keeps track of the TangleTime. The TangleTime can be seen as a clock for the
// entire network as it tracks the time of the last confirmed block. Comparing the issuing time of the last confirmed
// block to the node's current wall clock time then yields a reasonable assessment of how much in sync the node is.
type TimeManager struct {
Events *TimeManagerEvents
tangle *Tangle
startSynced bool
lastAcceptedMutex sync.RWMutex
lastAcceptedBlock LastBlock
lastSyncedMutex sync.RWMutex
lastSynced bool
bootstrapped bool
ctx context.Context
cancel context.CancelFunc
}
// NewTimeManager is the constructor for TimeManager.
func NewTimeManager(tangle *Tangle) *TimeManager {
t := &TimeManager{
Events: newTimeManagerEvents(),
tangle: tangle,
startSynced: tangle.Options.StartSynced,
}
t.ctx, t.cancel = context.WithCancel(context.Background())
// initialize with Genesis
t.lastAcceptedBlock = LastBlock{
BlockID: EmptyBlockID,
BlockTime: tangle.Options.GenesisTime,
}
marshaledLastConfirmedBlock, err := tangle.Options.Store.Get(kvstore.Key(lastConfirmedKey))
if err != nil && !errors.Is(err, kvstore.ErrKeyNotFound) {
panic(err)
}
// load from storage if key was found
if marshaledLastConfirmedBlock != nil {
if t.lastAcceptedBlock, _, err = lastBlockFromBytes(marshaledLastConfirmedBlock); err != nil {
panic(err)
}
}
// initialize the synced status
t.lastSynced = t.synced()
t.bootstrapped = t.lastSynced
return t
}
// Start starts the TimeManager.
func (t *TimeManager) Start() {
go t.mainLoop()
}
// Setup sets up the behavior of the component by making it attach to the relevant events of other components.
func (t *TimeManager) Setup() {
t.tangle.ConfirmationOracle.Events().BlockAccepted.Attach(event.NewClosure(func(event *BlockAcceptedEvent) {
t.updateTime(event.Block)
t.updateSyncedState()
}))
t.Start()
}
// Shutdown shuts down the TimeManager and persists its state.
func (t *TimeManager) Shutdown() {
t.lastAcceptedMutex.RLock()
defer t.lastAcceptedMutex.RUnlock()
if err := t.tangle.Options.Store.Set(kvstore.Key(lastConfirmedKey), t.lastAcceptedBlock.Bytes()); err != nil {
t.tangle.Events.Error.Trigger(errors.Errorf("failed to persists LastAcceptedBlock (%v): %w", err, cerrors.ErrFatal))
return
}
// cancel the internal context
t.cancel()
}
// LastAcceptedBlock returns the last confirmed block.
func (t *TimeManager) LastAcceptedBlock() LastBlock {
t.lastAcceptedMutex.RLock()
defer t.lastAcceptedMutex.RUnlock()
return t.lastAcceptedBlock
}
// LastConfirmedBlock returns the last confirmed block.
func (t *TimeManager) LastConfirmedBlock() LastBlock {
t.lastAcceptedMutex.RLock()
defer t.lastAcceptedMutex.RUnlock()
return t.lastAcceptedBlock
}
// ATT returns the Acceptance Tangle Time, i.e., the issuing time of the last accepted block.
func (t *TimeManager) ATT() time.Time {
t.lastAcceptedMutex.RLock()
defer t.lastAcceptedMutex.RUnlock()
return t.lastAcceptedBlock.BlockTime
}
// CTT returns the confirmed tangle time, i.e. the issuing time of the last confirmed block.
// For now, it's just a stub, it actually returns ATT.
func (t *TimeManager) CTT() time.Time {
return t.ATT()
}
// RATT return relative acceptance tangle time, i.e., ATT + time since last update of ATT.
func (t *TimeManager) RATT() time.Time {
timeSinceLastUpdate := time.Now().Sub(t.lastAcceptedTime())
return t.ATT().Add(timeSinceLastUpdate)
}
// RCTT return relative acceptance tangle time, i.e., CTT + time since last update of CTT.
// For now, it's just a stub, it actually returns RATT.
func (t *TimeManager) RCTT() time.Time {
return t.RATT()
}
// ActivityTime return the time used for defining nodes' activity window.
func (t *TimeManager) ActivityTime() time.Time {
// Until we have accepted any block, return static ATT. After accepting anything, return RATT so that the node can recognize nodes that are not active.
if t.lastAcceptedTime().IsZero() {
return t.ATT()
}
return t.RATT()
}
// Bootstrapped returns whether the node has bootstrapped based on the difference between CTT and the current wall time which can
// be configured via SyncTimeWindow.
// When the node becomes bootstrapped and this method returns true, it can't return false after that.
func (t *TimeManager) Bootstrapped() bool {
t.lastSyncedMutex.RLock()
defer t.lastSyncedMutex.RUnlock()
return t.bootstrapped
}
// Synced returns whether the node is in sync based on the difference between CTT and the current wall time which can
// be configured via SyncTimeWindow.
func (t *TimeManager) Synced() bool {
t.lastSyncedMutex.RLock()
defer t.lastSyncedMutex.RUnlock()
return t.lastSynced
}
func (t *TimeManager) synced() bool {
if t.startSynced && t.CTT().Unix() == epoch.GenesisTime {
return true
}
return clock.Since(t.CTT()) < t.tangle.Options.SyncTimeWindow
}
// checks whether the synced state needs to be updated and if so,
// triggers a corresponding event reflecting the new state.
func (t *TimeManager) updateSyncedState() {
t.lastSyncedMutex.Lock()
defer t.lastSyncedMutex.Unlock()
if newSynced := t.synced(); t.lastSynced != newSynced {
t.lastSynced = newSynced
// trigger the event inside the lock to assure that the status is still correct
t.Events.SyncChanged.Trigger(&SyncChangedEvent{Synced: newSynced})
if newSynced {
t.bootstrapped = true
t.Events.Bootstrapped.Trigger(&BootstrappedEvent{})
}
}
}
// updateTime updates the last confirmed block.
func (t *TimeManager) updateTime(block *Block) {
t.lastAcceptedMutex.Lock()
defer t.lastAcceptedMutex.Unlock()
if t.lastAcceptedBlock.BlockTime.After(block.IssuingTime()) {
return
}
t.lastAcceptedBlock = LastBlock{
BlockID: block.ID(),
BlockTime: block.IssuingTime(),
UpdateTime: time.Now(),
}
t.Events.AcceptanceTimeUpdated.Trigger(&TimeUpdate{
BlockID: t.lastAcceptedBlock.BlockID,
ATT: t.lastAcceptedBlock.BlockTime,
UpdateTime: t.lastAcceptedBlock.UpdateTime,
})
t.Events.ConfirmedTimeUpdated.Trigger(&TimeUpdate{
BlockID: t.lastAcceptedBlock.BlockID,
ATT: t.lastAcceptedBlock.BlockTime,
UpdateTime: t.lastAcceptedBlock.UpdateTime,
})
}
func (t *TimeManager) lastAcceptedTime() time.Time {
t.lastAcceptedMutex.RLock()
defer t.lastAcceptedMutex.RUnlock()
return t.lastAcceptedBlock.UpdateTime
}
// the main loop runs the updateSyncedState at least every synced time window interval to keep the synced state updated
// even if no updateTime is ever called.
func (t *TimeManager) mainLoop() {
timeutil.NewTicker(t.updateSyncedState, func() time.Duration {
if t.tangle.Options.SyncTimeWindow == 0 {
return DefaultSyncTimeWindow
}
return t.tangle.Options.SyncTimeWindow
}(), t.ctx).WaitForShutdown()
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// region LastAcceptedBlock /////////////////////////////////////////////////////////////////////////////////////////
// LastBlock is a wrapper type for the last confirmed block, consisting of BlockID, BlockTime and UpdateTime.
type LastBlock struct {
BlockID BlockID `serix:"0"`
// BlockTime field is the time of the last confirmed block.
BlockTime time.Time `serix:"1"`
// UpdateTime field is the time when the last confirmed block was updated.
UpdateTime time.Time
}
// lastBlockFromBytes unmarshals a LastBlock object from a sequence of bytes.
func lastBlockFromBytes(data []byte) (lcm LastBlock, consumedBytes int, err error) {
consumedBytes, err = serix.DefaultAPI.Decode(context.Background(), data, &lcm, serix.WithValidation())
if err != nil {
err = errors.Errorf("failed to parse Background: %w", err)
return
}
return
}
// Bytes returns a marshaled version of the LastBlock.
func (l LastBlock) Bytes() (marshaledLastConfirmedBlock []byte) {
objBytes, err := serix.DefaultAPI.Encode(context.Background(), l, serix.WithValidation())
if err != nil {
// TODO: what do?
panic(err)
}
return objBytes
}
// String returns a human-readable version of the LastBlock.
func (l LastBlock) String() string {
return stringify.Struct("LastBlock",
stringify.StructField("BlockID", l.BlockID),
stringify.StructField("BlockTime", l.BlockTime),
stringify.StructField("UpdateTime", l.UpdateTime),
)
}
// endregion ///////////////////////////////////////////////////////////////////////////////////////////////////////////