/
beacon.go
402 lines (333 loc) · 10.1 KB
/
beacon.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Package beacon implements the tendermint backed beacon and epochtime
// backends.
package beacon
import (
"context"
"encoding/hex"
"fmt"
"sync"
"github.com/eapache/channels"
tmabcitypes "github.com/tendermint/tendermint/abci/types"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
tmtypes "github.com/tendermint/tendermint/types"
beaconAPI "github.com/oasisprotocol/oasis-core/go/beacon/api"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
memorySigner "github.com/oasisprotocol/oasis-core/go/common/crypto/signature/signers/memory"
"github.com/oasisprotocol/oasis-core/go/common/logging"
"github.com/oasisprotocol/oasis-core/go/common/pubsub"
consensus "github.com/oasisprotocol/oasis-core/go/consensus/api"
"github.com/oasisprotocol/oasis-core/go/consensus/api/events"
"github.com/oasisprotocol/oasis-core/go/consensus/api/transaction"
tmAPI "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/api"
app "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/beacon"
)
var TestSigner = memorySigner.NewTestSigner("oasis-core epochtime mock key seed")
// ServiceClient is the beacon service client interface.
type ServiceClient interface {
beaconAPI.Backend
tmAPI.ServiceClient
}
type serviceClient struct {
sync.RWMutex
tmAPI.BaseServiceClient
logger *logging.Logger
querier *app.QueryFactory
backend tmAPI.Backend
ctx context.Context
epochNotifier *pubsub.Broker
epochLastNotified beaconAPI.EpochTime
epoch beaconAPI.EpochTime
epochCurrentBlock int64
vrfNotifier *pubsub.Broker
vrfLastNotified hash.Hash
vrfEvent *beaconAPI.VRFEvent
initialNotify bool
baseEpoch beaconAPI.EpochTime
baseBlock int64
}
func (sc *serviceClient) StateToGenesis(ctx context.Context, height int64) (*beaconAPI.Genesis, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.Genesis(ctx)
}
func (sc *serviceClient) ConsensusParameters(ctx context.Context, height int64) (*beaconAPI.ConsensusParameters, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, fmt.Errorf("beacon: genesis query failed: %w", err)
}
return q.ConsensusParameters(ctx)
}
func (sc *serviceClient) GetBaseEpoch(ctx context.Context) (beaconAPI.EpochTime, error) {
return sc.baseEpoch, nil
}
func (sc *serviceClient) GetEpoch(ctx context.Context, height int64) (beaconAPI.EpochTime, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return beaconAPI.EpochInvalid, err
}
epoch, _, err := q.Epoch(ctx)
return epoch, err
}
func (sc *serviceClient) GetFutureEpoch(ctx context.Context, height int64) (*beaconAPI.EpochTimeState, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.FutureEpoch(ctx)
}
func (sc *serviceClient) GetEpochBlock(ctx context.Context, epoch beaconAPI.EpochTime) (int64, error) {
now, currentBlk := sc.currentEpochBlock()
if epoch == now {
return currentBlk, nil
}
// The epoch can't be earlier than the initial starting epoch.
switch {
case epoch < sc.baseEpoch:
return -1, fmt.Errorf("epoch predates base (base: %d requested: %d)", sc.baseEpoch, epoch)
case epoch == sc.baseEpoch:
return sc.baseBlock, nil
}
// Find historic epoch.
//
// TODO: This is really really inefficient, and should be optimized,
// maybe a cache of the last few epochs, or a binary search.
height := consensus.HeightLatest
for {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return -1, fmt.Errorf("failed to query epoch: %w", err)
}
var pastEpoch beaconAPI.EpochTime
pastEpoch, height, err = q.Epoch(ctx)
if err != nil {
return -1, fmt.Errorf("failed to query epoch: %w", err)
}
if epoch == pastEpoch {
return height, nil
}
height--
// The initial height can be > 1, but presumably this does not
// matter, since we validate that epoch > sc.baseEpoch.
if pastEpoch == 0 || height <= 1 {
return -1, fmt.Errorf("failed to find historic epoch (minimum: %d requested: %d)", pastEpoch, epoch)
}
}
}
func (sc *serviceClient) WaitEpoch(ctx context.Context, epoch beaconAPI.EpochTime) error {
ch, sub, err := sc.WatchEpochs(ctx)
if err != nil {
return err
}
defer sub.Close()
for {
select {
case <-sc.ctx.Done():
return sc.ctx.Err()
case <-ctx.Done():
return ctx.Err()
case e, ok := <-ch:
if !ok {
return context.Canceled
}
if e >= epoch {
return nil
}
}
}
}
func (sc *serviceClient) WatchEpochs(ctx context.Context) (<-chan beaconAPI.EpochTime, pubsub.ClosableSubscription, error) {
typedCh := make(chan beaconAPI.EpochTime)
sub := sc.epochNotifier.Subscribe()
sub.Unwrap(typedCh)
return typedCh, sub, nil
}
func (sc *serviceClient) WatchLatestEpoch(ctx context.Context) (<-chan beaconAPI.EpochTime, pubsub.ClosableSubscription, error) {
typedCh := make(chan beaconAPI.EpochTime)
sub := sc.epochNotifier.SubscribeBuffered(1)
sub.Unwrap(typedCh)
return typedCh, sub, nil
}
func (sc *serviceClient) GetBeacon(ctx context.Context, height int64) ([]byte, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.Beacon(ctx)
}
func (sc *serviceClient) GetVRFState(ctx context.Context, height int64) (*beaconAPI.VRFState, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.VRFState(ctx)
}
func (sc *serviceClient) WatchLatestVRFEvent(ctx context.Context) (<-chan *beaconAPI.VRFEvent, *pubsub.Subscription, error) {
typedCh := make(chan *beaconAPI.VRFEvent)
sub := sc.vrfNotifier.Subscribe()
sub.Unwrap(typedCh)
return typedCh, sub, nil
}
func (sc *serviceClient) SetEpoch(ctx context.Context, epoch beaconAPI.EpochTime) error {
ch, sub, err := sc.WatchEpochs(ctx)
if err != nil {
return fmt.Errorf("epochtime: watch epochs failed: %w", err)
}
defer sub.Close()
tx := transaction.NewTransaction(0, nil, app.MethodSetEpoch, epoch)
if err := consensus.SignAndSubmitTx(ctx, sc.backend, TestSigner, tx); err != nil {
return fmt.Errorf("epochtime: set epoch failed: %w", err)
}
for {
select {
case <-sc.ctx.Done():
return sc.ctx.Err()
case newEpoch, ok := <-ch:
if !ok {
return context.Canceled
}
if newEpoch == epoch {
return nil
}
case <-ctx.Done():
return ctx.Err()
}
}
}
func (sc *serviceClient) ServiceDescriptor() tmAPI.ServiceDescriptor {
return tmAPI.NewStaticServiceDescriptor("beacon", app.EventType, []tmpubsub.Query{app.QueryApp})
}
func (sc *serviceClient) DeliverBlock(ctx context.Context, height int64) error {
if sc.initialNotify {
return nil
}
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return fmt.Errorf("epochtime: failed to query state: %w", err)
}
var epoch beaconAPI.EpochTime
epoch, height, err = q.Epoch(ctx)
if err != nil {
return fmt.Errorf("epochtime: failed to query epoch: %w", err)
}
if sc.updateCachedEpoch(height, epoch) {
sc.epochNotifier.Broadcast(epoch)
}
var vrfState *beaconAPI.VRFState
vrfState, err = q.VRFState(ctx)
if err != nil {
return fmt.Errorf("beacon: failed to query VRF state: %w", err)
}
if vrfState != nil {
var event beaconAPI.VRFEvent
event.FromState(vrfState)
if sc.updateCachedVRFEvent(&event) {
sc.vrfNotifier.Broadcast(&event)
}
}
sc.initialNotify = true
return nil
}
func (sc *serviceClient) DeliverEvent(ctx context.Context, height int64, tx tmtypes.Tx, ev *tmabcitypes.Event) error {
for _, pair := range ev.GetAttributes() {
if events.IsAttributeKind(pair.GetKey(), &beaconAPI.EpochEvent{}) {
var event beaconAPI.EpochEvent
if err := events.DecodeValue(string(pair.GetValue()), &event); err != nil {
sc.logger.Error("epochtime: malformed epoch event value",
"err", err,
)
continue
}
if sc.updateCachedEpoch(height, event.Epoch) {
sc.epochNotifier.Broadcast(event.Epoch)
}
}
if events.IsAttributeKind(pair.GetKey(), &beaconAPI.VRFEvent{}) {
var event beaconAPI.VRFEvent
if err := events.DecodeValue(string(pair.GetValue()), &event); err != nil {
sc.logger.Error("beacon: malformed VRF event",
"err", err,
)
continue
}
if sc.updateCachedVRFEvent(&event) {
sc.vrfNotifier.Broadcast(&event)
}
}
}
return nil
}
func (sc *serviceClient) updateCachedEpoch(height int64, epoch beaconAPI.EpochTime) bool {
sc.Lock()
defer sc.Unlock()
sc.epoch = epoch
sc.epochCurrentBlock = height
if sc.epochLastNotified != epoch {
sc.logger.Debug("epoch transition",
"prev_epoch", sc.epochLastNotified,
"epoch", epoch,
"height", height,
)
sc.epochLastNotified = sc.epoch
return true
}
return false
}
func (sc *serviceClient) updateCachedVRFEvent(event *beaconAPI.VRFEvent) bool {
sc.Lock()
defer sc.Unlock()
sc.vrfEvent = event
cmp := hash.NewFrom(event)
if !cmp.Equal(&sc.vrfLastNotified) {
sc.logger.Debug("VRF round event",
"epoch", event.Epoch,
"alpha", hex.EncodeToString(event.Alpha),
"submit_after", event.SubmitAfter,
)
sc.vrfLastNotified = cmp
return true
}
return false
}
func (sc *serviceClient) currentEpochBlock() (beaconAPI.EpochTime, int64) {
sc.RLock()
defer sc.RUnlock()
return sc.epoch, sc.epochCurrentBlock
}
// New constructs a new tendermint backed beacon and epochtime Backend instance.
func New(ctx context.Context, backend tmAPI.Backend) (ServiceClient, error) {
// Initialize and register the tendermint service component.
a := app.New()
if err := backend.RegisterApplication(a); err != nil {
return nil, err
}
sc := &serviceClient{
logger: logging.GetLogger("beacon/tendermint"),
querier: a.QueryFactory().(*app.QueryFactory),
backend: backend,
ctx: ctx,
epochLastNotified: beaconAPI.EpochInvalid,
}
sc.epochNotifier = pubsub.NewBrokerEx(func(ch channels.Channel) {
sc.RLock()
defer sc.RUnlock()
if sc.epochLastNotified == sc.epoch {
ch.In() <- sc.epoch
}
})
sc.vrfNotifier = pubsub.NewBrokerEx(func(ch channels.Channel) {
sc.RLock()
defer sc.RUnlock()
if sc.vrfEvent != nil {
ch.In() <- sc.vrfEvent
}
})
genDoc, err := backend.GetGenesisDocument(ctx)
if err != nil {
return nil, err
}
sc.baseEpoch = genDoc.Beacon.Base
sc.baseBlock = genDoc.Height
return sc, nil
}