-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathinitialization.go
684 lines (574 loc) · 17.4 KB
/
initialization.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
package initialization
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strconv"
"sync"
"sync/atomic"
"go.uber.org/zap"
"github.com/spacemeshos/post/config"
"github.com/spacemeshos/post/internal/postrs"
"github.com/spacemeshos/post/oracle"
"github.com/spacemeshos/post/persistence"
"github.com/spacemeshos/post/shared"
)
type (
Config = config.Config
InitOpts = config.InitOpts
Logger = zap.Logger
ConfigMismatchError = shared.ConfigMismatchError
Provider = postrs.Provider
)
type Status int
const (
StatusNotStarted Status = iota
StatusStarted
StatusInitializing
StatusCompleted
StatusError
)
// Providers returns a list of available compute providers.
func OpenCLProviders() ([]Provider, error) {
return postrs.OpenCLProviders()
}
// CPUProviderID returns the ID of the CPU provider or nil if the CPU provider is not available.
func CPUProviderID() uint32 {
return postrs.CPUProviderID()
}
type option struct {
nodeId []byte
commitmentAtxId []byte
commitment []byte
cfg *Config
initOpts *config.InitOpts
logger *Logger
powDifficultyFunc func(uint64) []byte
referenceOracle *oracle.WorkOracle
}
func (o *option) validate() error {
if o.nodeId == nil {
return errors.New("`nodeId` is required")
}
if o.commitmentAtxId == nil {
return errors.New("`commitmentAtxId` is required")
}
o.commitment = oracle.CommitmentBytes(o.nodeId, o.commitmentAtxId)
if o.cfg == nil {
return errors.New("no config provided")
}
if o.initOpts == nil {
return errors.New("no init options provided")
}
return config.Validate(*o.cfg, *o.initOpts)
}
type OptionFunc func(*option) error
// WithNodeId sets the ID of the Node.
func WithNodeId(nodeId []byte) OptionFunc {
return func(opts *option) error {
if len(nodeId) != 32 {
return fmt.Errorf("invalid `id` length; expected: 32, given: %v", len(nodeId))
}
opts.nodeId = nodeId
return nil
}
}
// WithCommitmentAtxId sets the ID of the CommitmentATX.
func WithCommitmentAtxId(id []byte) OptionFunc {
return func(opts *option) error {
if len(id) != 32 {
return fmt.Errorf("invalid `commitmentAtxId` length; expected: 32, given: %v", len(id))
}
opts.commitmentAtxId = id
return nil
}
}
// WithInitOpts sets the init options for the initializer.
func WithInitOpts(initOpts config.InitOpts) OptionFunc {
return func(opts *option) error {
opts.initOpts = &initOpts
return nil
}
}
// WithConfig sets the config for the initializer.
func WithConfig(cfg Config) OptionFunc {
return func(opts *option) error {
opts.cfg = &cfg
return nil
}
}
// WithLogger sets the logger for the initializer.
func WithLogger(logger *zap.Logger) OptionFunc {
return func(opts *option) error {
opts.logger = logger
return nil
}
}
// withDifficultyFunc sets the difficulty function for the initializer.
// NOTE: This is an internal option for tests and should not be used by external packages.
func withDifficultyFunc(powDifficultyFunc func(uint64) []byte) OptionFunc {
return func(opts *option) error {
if powDifficultyFunc == nil {
return errors.New("difficulty function is nil")
}
opts.powDifficultyFunc = powDifficultyFunc
return nil
}
}
// withReferenceOracle sets the reference oracle for the initializer.
// NOTE: This is an internal option for tests and should not be used by external packages.
func withReferenceOracle(referenceOracle *oracle.WorkOracle) OptionFunc {
return func(opts *option) error {
if referenceOracle == nil {
return errors.New("reference oracle is nil")
}
opts.referenceOracle = referenceOracle
return nil
}
}
// Initializer is responsible for initializing a new PoST commitment.
type Initializer struct {
nodeId []byte
commitmentAtxId []byte
commitment []byte
cfg Config
opts InitOpts
// these values are atomics so they can be read from multiple other goroutines safely
// write is protected by mtx
nonce atomic.Pointer[uint64]
nonceValue atomic.Pointer[[]byte]
lastPosition atomic.Pointer[uint64]
numLabelsWritten atomic.Uint64
diskState *DiskState
// TODO(mafa): we should lock with a lock file to prevent other processes from modifying the data concurrently
mtx sync.RWMutex
logger *Logger
referenceOracle *oracle.WorkOracle
powDifficultyFunc func(uint64) []byte
}
func NewInitializer(opts ...OptionFunc) (*Initializer, error) {
options := &option{
logger: zap.NewNop(),
powDifficultyFunc: shared.PowDifficulty,
}
for _, opt := range opts {
if err := opt(options); err != nil {
return nil, err
}
}
if err := options.validate(); err != nil {
return nil, err
}
init := &Initializer{
cfg: *options.cfg,
opts: *options.initOpts,
nodeId: options.nodeId,
commitmentAtxId: options.commitmentAtxId,
commitment: options.commitment,
diskState: NewDiskState(options.initOpts.DataDir, uint(config.BitsPerLabel)),
logger: options.logger,
powDifficultyFunc: options.powDifficultyFunc,
referenceOracle: options.referenceOracle,
}
numLabelsWritten, err := init.diskState.NumLabelsWritten()
if err != nil {
return nil, err
}
if numLabelsWritten > 0 {
m, err := init.loadMetadata()
if err != nil {
return nil, err
}
if err := init.verifyMetadata(m); err != nil {
return nil, err
}
init.nonce.Store(m.Nonce)
nonceValue := make([]byte, postrs.LabelLength)
copy(nonceValue, m.NonceValue)
init.nonceValue.Store(&nonceValue)
init.lastPosition.Store(m.LastPosition)
}
if err := init.saveMetadata(); err != nil {
return nil, err
}
return init, nil
}
// Initialize is the process in which the prover commits to store some data, by having its storage filled with
// pseudo-random data with respect to a specific id. This data is the result of a computationally-expensive operation.
func (init *Initializer) Initialize(ctx context.Context) error {
if !init.mtx.TryLock() {
return ErrAlreadyInitializing
}
defer init.mtx.Unlock()
layout, err := deriveFilesLayout(init.cfg, init.opts)
if err != nil {
return err
}
init.logger.Info("initialization started",
zap.String("datadir", init.opts.DataDir),
zap.Uint32("numUnits", init.opts.NumUnits),
zap.Uint64("maxFileSize", init.opts.MaxFileSize),
zap.Uint64("labelsPerUnit", init.cfg.LabelsPerUnit),
)
init.logger.Info("initialization file layout",
zap.Uint64("labelsPerFile", layout.FileNumLabels),
zap.Uint64("labelsLastFile", layout.LastFileNumLabels),
zap.Int("firstFileIndex", layout.FirstFileIdx),
zap.Int("lastFileIndex", layout.LastFileIdx),
)
if err := removeRedundantFiles(init.cfg, init.opts, init.logger); err != nil {
return err
}
numLabels := uint64(init.opts.NumUnits) * init.cfg.LabelsPerUnit
difficulty := init.powDifficultyFunc(numLabels)
batchSize := init.opts.ComputeBatchSize
wo, err := oracle.New(
oracle.WithProviderID(init.opts.ProviderID),
oracle.WithCommitment(init.commitment),
oracle.WithVRFDifficulty(difficulty),
oracle.WithScryptParams(init.opts.Scrypt),
oracle.WithLogger(init.logger),
)
if err != nil {
return err
}
defer wo.Close()
woReference := init.referenceOracle
if woReference == nil {
cpuProvider := CPUProviderID()
woReference, err = oracle.New(
oracle.WithProviderID(&cpuProvider),
oracle.WithCommitment(init.commitment),
oracle.WithVRFDifficulty(difficulty),
oracle.WithScryptParams(init.opts.Scrypt),
oracle.WithLogger(init.logger),
)
if err != nil {
return err
}
defer woReference.Close()
}
for i := layout.FirstFileIdx; i <= layout.LastFileIdx; i++ {
fileOffset := uint64(i) * layout.FileNumLabels
fileNumLabels := layout.FileNumLabels
if i == layout.LastFileIdx {
fileNumLabels = layout.LastFileNumLabels
}
if err := init.initFile(ctx, wo, woReference, i, batchSize, fileOffset, fileNumLabels); err != nil {
return err
}
}
if init.nonce.Load() != nil {
init.logger.Info("initialization: completed, found nonce", zap.Uint64("nonce", *init.nonce.Load()))
return nil
}
if layout.NumFiles() < init.opts.TotalFiles(init.cfg.LabelsPerUnit) {
init.logger.Info("initialization: no nonce found while computing labels")
return nil
}
init.logger.Info("initialization: no nonce found while computing labels, continue initializing")
if init.lastPosition.Load() == nil || *init.lastPosition.Load() < numLabels {
lastPos := numLabels
init.lastPosition.Store(&lastPos)
}
// continue searching for a nonce
defer init.saveMetadata()
for i := *init.lastPosition.Load(); i < math.MaxUint64; i += batchSize {
init.lastPosition.Store(&i)
select {
case <-ctx.Done():
init.logger.Info("initialization: stopped")
return ctx.Err()
default:
// continue looking for a nonce
}
init.logger.Debug("initialization: continue looking for a nonce",
zap.Uint64("startPosition", i),
zap.Uint64("batchSize", batchSize),
)
res, err := wo.Positions(i, i+batchSize-1)
if err != nil {
return err
}
if res.Nonce != nil {
init.logger.Debug("initialization: found nonce",
zap.Uint64("nonce", *res.Nonce),
)
init.nonce.Store(res.Nonce)
return nil
}
}
return errors.New("no nonce found")
}
func removeRedundantFiles(cfg config.Config, opts config.InitOpts, logger *zap.Logger) error {
// Go over all postdata_N.bin files in the data directory and remove the ones that are not needed.
// The files with indices from 0 to init.opts.TotalFiles(init.cfg.LabelsPerUnit) - 1 are preserved.
// The rest are redundant and can be removed.
maxFileIndex := opts.TotalFiles(cfg.LabelsPerUnit) - 1
logger.Debug("attempting to remove redundant files above index", zap.Int("maxFileIndex", maxFileIndex))
files, err := os.ReadDir(opts.DataDir)
if err != nil {
return err
}
for _, file := range files {
name := file.Name()
fileIndex, err := shared.ParseFileIndex(name)
if err != nil && name != MetadataFileName {
logger.Debug("found unrecognized file", zap.String("fileName", name))
continue
}
if fileIndex > maxFileIndex {
logger.Info("removing redundant file", zap.String("fileName", name))
path := filepath.Join(opts.DataDir, name)
if err := os.Remove(path); err != nil {
return fmt.Errorf("failed to delete file (%v): %w", path, err)
}
}
}
return nil
}
func (init *Initializer) NumLabelsWritten() uint64 {
return init.numLabelsWritten.Load()
}
func (init *Initializer) Nonce() *uint64 {
return init.nonce.Load()
}
func (init *Initializer) NonceValue() []byte {
if init.nonceValue.Load() == nil {
return nil
}
nonceValue := make([]byte, postrs.LabelLength)
copy(nonceValue, *init.nonceValue.Load())
return nonceValue
}
func (init *Initializer) Reset() error {
if !init.mtx.TryLock() {
return ErrCannotResetWhileInitializing
}
defer init.mtx.Unlock()
files, err := os.ReadDir(init.opts.DataDir)
if err != nil {
return err
}
for _, file := range files {
info, err := file.Info()
if err != nil {
continue
}
name := file.Name()
if shared.IsInitFile(info) || name == MetadataFileName {
path := filepath.Join(init.opts.DataDir, name)
if err := os.Remove(path); err != nil {
return fmt.Errorf("failed to delete file (%v): %w", path, err)
}
}
}
return nil
}
func (init *Initializer) Status() Status {
if !init.mtx.TryLock() {
return StatusInitializing
}
defer init.mtx.Unlock()
numLabelsWritten, err := init.diskState.NumLabelsWritten()
if err != nil {
return StatusError
}
target := uint64(init.opts.NumUnits) * uint64(init.cfg.LabelsPerUnit)
if numLabelsWritten == target {
return StatusCompleted
}
if numLabelsWritten > 0 {
return StatusStarted
}
return StatusNotStarted
}
func (init *Initializer) initFile(
ctx context.Context,
wo, woReference *oracle.WorkOracle,
fileIndex int,
batchSize, fileOffset, fileNumLabels uint64,
) error {
fileTargetPosition := fileOffset + fileNumLabels
// Initialize the labels file writer.
writer, err := persistence.NewLabelsWriter(init.opts.DataDir, fileIndex, config.BitsPerLabel)
if err != nil {
return err
}
defer writer.Close()
numLabelsWritten, err := writer.NumLabelsWritten()
if err != nil {
return err
}
fields := []zap.Field{
zap.Int("fileIndex", fileIndex),
zap.Uint64("currentNumLabels", numLabelsWritten),
zap.Uint64("targetNumLabels", fileNumLabels),
zap.Uint64("startPosition", fileOffset),
}
switch {
case numLabelsWritten == fileNumLabels:
init.logger.Info("initialization: file already initialized", fields...)
init.numLabelsWritten.Store(fileTargetPosition)
return nil
case numLabelsWritten > fileNumLabels:
init.logger.Info("initialization: truncating file")
if err := writer.Truncate(fileNumLabels); err != nil {
return err
}
init.numLabelsWritten.Store(fileTargetPosition)
return nil
case numLabelsWritten > 0:
init.logger.Info("initialization: continuing to write file", fields...)
default:
init.logger.Info("initialization: starting to write file", fields...)
}
for currentPosition := numLabelsWritten; currentPosition < fileNumLabels; currentPosition += batchSize {
select {
case <-ctx.Done():
init.logger.Info("initialization: stopped")
if err := writer.Flush(); err != nil {
return err
}
return ctx.Err()
default:
// continue initialization
}
// The last batch might need to be smaller.
remaining := fileNumLabels - currentPosition
if remaining < batchSize {
batchSize = remaining
}
init.logger.Debug("initialization: status",
zap.Int("fileIndex", fileIndex),
zap.Uint64("currentPosition", currentPosition),
zap.Uint64("remaining", remaining),
)
// Calculate labels of the batch position range.
startPosition := fileOffset + currentPosition
endPosition := startPosition + uint64(batchSize) - 1
res, err := wo.Positions(startPosition, endPosition)
if err != nil {
return fmt.Errorf("failed to compute labels: %w", err)
}
// sanity check with reference oracle
reference, err := woReference.Position(endPosition)
if err != nil {
return fmt.Errorf("failed to compute reference label: %w", err)
}
if !bytes.Equal(res.Output[(batchSize-1)*postrs.LabelLength:], reference.Output) {
return ErrReferenceLabelMismatch{
Index: endPosition,
Commitment: init.commitment,
Expected: reference.Output,
Actual: res.Output[(batchSize-1)*postrs.LabelLength:],
}
}
if res.Nonce != nil {
candidate := res.Output[(*res.Nonce-startPosition)*postrs.LabelLength:]
candidate = candidate[:postrs.LabelLength]
fields := []zap.Field{
zap.Int("fileIndex", fileIndex),
zap.Uint64("nonce", *res.Nonce),
zap.String("value", hex.EncodeToString(candidate)),
}
init.logger.Debug("initialization: found nonce", fields...)
if init.nonceValue.Load() == nil || bytes.Compare(candidate, *init.nonceValue.Load()) < 0 {
nonceValue := make([]byte, postrs.LabelLength)
copy(nonceValue, candidate)
init.logger.Info("initialization: found new best nonce", fields...)
init.nonce.Store(res.Nonce)
init.nonceValue.Store(&nonceValue)
init.saveMetadata()
}
}
// Write labels batch to disk.
if err := writer.Write(res.Output); err != nil {
return err
}
init.numLabelsWritten.Store(fileOffset + currentPosition + uint64(batchSize))
}
if err := writer.Flush(); err != nil {
return err
}
numLabelsWritten, err = writer.NumLabelsWritten()
if err != nil {
return err
}
init.logger.Info("initialization: completed",
zap.Int("fileIndex", fileIndex),
zap.Uint64("numLabelsWritten", numLabelsWritten),
)
return nil
}
func (init *Initializer) verifyMetadata(m *shared.PostMetadata) error {
if !bytes.Equal(init.nodeId, m.NodeId) {
return ConfigMismatchError{
Param: "NodeId",
Expected: hex.EncodeToString(init.nodeId),
Found: hex.EncodeToString(m.NodeId),
DataDir: init.opts.DataDir,
}
}
if !bytes.Equal(init.commitmentAtxId, m.CommitmentAtxId) {
return ConfigMismatchError{
Param: "CommitmentAtxId",
Expected: hex.EncodeToString(init.commitmentAtxId),
Found: hex.EncodeToString(m.CommitmentAtxId),
DataDir: init.opts.DataDir,
}
}
if init.cfg.LabelsPerUnit != m.LabelsPerUnit {
return ConfigMismatchError{
Param: "LabelsPerUnit",
Expected: strconv.FormatUint(init.cfg.LabelsPerUnit, 10),
Found: strconv.FormatUint(m.LabelsPerUnit, 10),
DataDir: init.opts.DataDir,
}
}
if init.opts.MaxFileSize != m.MaxFileSize {
return ConfigMismatchError{
Param: "MaxFileSize",
Expected: strconv.FormatUint(init.opts.MaxFileSize, 10),
Found: strconv.FormatUint(m.MaxFileSize, 10),
DataDir: init.opts.DataDir,
}
}
if init.opts.NumUnits > m.NumUnits {
return ConfigMismatchError{
Param: "NumUnits",
Expected: fmt.Sprintf(">= %d", init.opts.NumUnits),
Found: strconv.FormatUint(uint64(m.NumUnits), 10),
DataDir: init.opts.DataDir,
}
}
return nil
}
func (init *Initializer) saveMetadata() error {
v := shared.PostMetadata{
Version: 1,
NodeId: init.nodeId,
CommitmentAtxId: init.commitmentAtxId,
LabelsPerUnit: init.cfg.LabelsPerUnit,
NumUnits: init.opts.NumUnits,
MaxFileSize: init.opts.MaxFileSize,
Scrypt: init.opts.Scrypt,
Nonce: init.nonce.Load(),
LastPosition: init.lastPosition.Load(),
}
if init.nonceValue.Load() != nil {
v.NonceValue = *init.nonceValue.Load()
}
return SaveMetadata(init.opts.DataDir, &v)
}
func (init *Initializer) loadMetadata() (*shared.PostMetadata, error) {
if err := MigratePoST(init.opts.DataDir, init.logger); err != nil {
return nil, err
}
return LoadMetadata(init.opts.DataDir)
}