sectorbuild_cgo.go 10.6 KB
Newer Older
Jakub Sztandera's avatar
Jakub Sztandera committed
1
2
3
4
5
6
7
8
9
10
11
12
//+build cgo

package sectorbuilder

import (
	"context"
	"io"
	"os"
	"sync/atomic"

	ffi "github.com/filecoin-project/filecoin-ffi"
	"golang.org/x/xerrors"
Łukasz Magiera's avatar
Łukasz Magiera committed
13
14

	fs "github.com/filecoin-project/go-sectorbuilder/fs"
Jakub Sztandera's avatar
Jakub Sztandera committed
15
16
17
18
)

var _ Interface = &SectorBuilder{}

Łukasz Magiera's avatar
Łukasz Magiera committed
19
func (sb *SectorBuilder) AddPiece(ctx context.Context, pieceSize uint64, sectorId uint64, file io.Reader, existingPieceSizes []uint64) (PublicPieceInfo, error) {
Jakub Sztandera's avatar
Jakub Sztandera committed
20
21
22
23
24
25
26
27
28
29
	atomic.AddInt32(&sb.addPieceWait, 1)
	ret := sb.RateLimit()
	atomic.AddInt32(&sb.addPieceWait, -1)
	defer ret()

	f, werr, err := toReadableFile(file, int64(pieceSize))
	if err != nil {
		return PublicPieceInfo{}, err
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
30
31
32
33
34
35
36
37
38
39
40
41
42
	var stagedFile *os.File
	var stagedPath fs.SectorPath
	if len(existingPieceSizes) == 0 {
		stagedPath, err = sb.AllocSectorPath(fs.DataStaging, sectorId, true)
		if err != nil {
			return PublicPieceInfo{}, xerrors.Errorf("allocating sector: %w", err)
		}

		stagedFile, err = os.Create(string(stagedPath))
		if err != nil {
			return PublicPieceInfo{}, xerrors.Errorf("opening sector file: %w", err)
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
43
		defer sb.filesystem.Release(stagedPath, sb.ssize)
Łukasz Magiera's avatar
Łukasz Magiera committed
44
45
46
47
48
49
50
51
52
53
54
55
56
	} else {
		stagedPath, err = sb.SectorPath(fs.DataStaging, sectorId)
		if err != nil {
			return PublicPieceInfo{}, xerrors.Errorf("getting sector path: %w", err)
		}

		stagedFile, err = os.OpenFile(string(stagedPath), os.O_RDWR, 0644)
		if err != nil {
			return PublicPieceInfo{}, xerrors.Errorf("opening sector file: %w", err)
		}
	}

	if err := sb.filesystem.Lock(ctx, stagedPath); err != nil {
Jakub Sztandera's avatar
Jakub Sztandera committed
57
58
		return PublicPieceInfo{}, err
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
59
	defer sb.filesystem.Unlock(stagedPath)
Jakub Sztandera's avatar
Jakub Sztandera committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79

	_, _, commP, err := ffi.WriteWithAlignment(f, pieceSize, stagedFile, existingPieceSizes)
	if err != nil {
		return PublicPieceInfo{}, err
	}

	if err := stagedFile.Close(); err != nil {
		return PublicPieceInfo{}, err
	}

	if err := f.Close(); err != nil {
		return PublicPieceInfo{}, err
	}

	return PublicPieceInfo{
		Size:  pieceSize,
		CommP: commP,
	}, werr()
}

Łukasz Magiera's avatar
Łukasz Magiera committed
80
81
82
83
84
85
86
87
88
89
func (sb *SectorBuilder) ReadPieceFromSealedSector(ctx context.Context, sectorID uint64, offset uint64, size uint64, ticket []byte, commD []byte) (io.ReadCloser, error) {
	sfs := sb.filesystem

	// TODO: this needs to get smarter when we start supporting partial unseals
	unsealedPath, err := sfs.AllocSector(fs.DataUnsealed, sb.Miner, sb.ssize, true, sectorID)
	if err != nil {
		if !xerrors.Is(err, fs.ErrExists) {
			return nil, xerrors.Errorf("AllocSector: %w", err)
		}
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
90
	defer sfs.Release(unsealedPath, sb.ssize)
Jakub Sztandera's avatar
Jakub Sztandera committed
91

Łukasz Magiera's avatar
Łukasz Magiera committed
92
	if err := sfs.Lock(ctx, unsealedPath); err != nil {
Jakub Sztandera's avatar
Jakub Sztandera committed
93
94
		return nil, err
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
95
	defer sfs.Unlock(unsealedPath)
Jakub Sztandera's avatar
Jakub Sztandera committed
96
97
98
99
100
101
102
103
104
105

	atomic.AddInt32(&sb.unsealWait, 1)
	// TODO: Don't wait if cached
	ret := sb.RateLimit() // TODO: check perf, consider remote unseal worker
	defer ret()
	atomic.AddInt32(&sb.unsealWait, -1)

	sb.unsealLk.Lock() // TODO: allow unsealing unrelated sectors in parallel
	defer sb.unsealLk.Unlock()

Łukasz Magiera's avatar
Łukasz Magiera committed
106
	cacheDir, err := sb.SectorPath(fs.DataCache, sectorID)
Jakub Sztandera's avatar
Jakub Sztandera committed
107
108
109
110
	if err != nil {
		return nil, err
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
111
	sealedPath, err := sb.SectorPath(fs.DataSealed, sectorID)
Jakub Sztandera's avatar
Jakub Sztandera committed
112
113
114
115
116
117
118
	if err != nil {
		return nil, err
	}

	// TODO: GC for those
	//  (Probably configurable count of sectors to be kept unsealed, and just
	//   remove last used one (or use whatever other cache policy makes sense))
Łukasz Magiera's avatar
Łukasz Magiera committed
119
	f, err := os.OpenFile(string(unsealedPath), os.O_RDONLY, 0644)
Jakub Sztandera's avatar
Jakub Sztandera committed
120
121
122
123
124
125
126
127
128
129
130
131
132
	if err != nil {
		if !os.IsNotExist(err) {
			return nil, err
		}

		var commd [CommLen]byte
		copy(commd[:], commD)

		var tkt [CommLen]byte
		copy(tkt[:], ticket)

		err = ffi.Unseal(sb.ssize,
			PoRepProofPartitions,
Łukasz Magiera's avatar
Łukasz Magiera committed
133
134
135
			string(cacheDir),
			string(sealedPath),
			string(unsealedPath),
Jakub Sztandera's avatar
Jakub Sztandera committed
136
137
138
139
140
141
142
143
			sectorID,
			addressToProverID(sb.Miner),
			tkt,
			commd)
		if err != nil {
			return nil, xerrors.Errorf("unseal failed: %w", err)
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
144
		f, err = os.OpenFile(string(unsealedPath), os.O_RDONLY, 0644)
Jakub Sztandera's avatar
Jakub Sztandera committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
		if err != nil {
			return nil, err
		}
	}

	if _, err := f.Seek(int64(offset), io.SeekStart); err != nil {
		return nil, xerrors.Errorf("seek: %w", err)
	}

	lr := io.LimitReader(f, int64(size))

	return &struct {
		io.Reader
		io.Closer
	}{
		Reader: lr,
		Closer: f,
	}, nil
}

func (sb *SectorBuilder) SealPreCommit(ctx context.Context, sectorID uint64, ticket SealTicket, pieces []PublicPieceInfo) (RawSealPreCommitOutput, error) {
Łukasz Magiera's avatar
Łukasz Magiera committed
166
	sfs := sb.filesystem
Jakub Sztandera's avatar
Jakub Sztandera committed
167

Łukasz Magiera's avatar
Łukasz Magiera committed
168
	cacheDir, err := sfs.ForceAllocSector(fs.DataCache, sb.Miner, sb.ssize, true, sectorID)
169
170
171
172
	if err != nil {
		return RawSealPreCommitOutput{}, xerrors.Errorf("getting cache dir: %w", err)
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
173
	sealedPath, err := sfs.ForceAllocSector(fs.DataSealed, sb.Miner, sb.ssize, true, sectorID)
174
	if err != nil {
Łukasz Magiera's avatar
Łukasz Magiera committed
175
		return RawSealPreCommitOutput{}, xerrors.Errorf("getting sealed sector paths: %w", err)
176
177
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
178
179
	defer sfs.Release(cacheDir, sb.ssize)
	defer sfs.Release(sealedPath, sb.ssize)
180

Łukasz Magiera's avatar
Łukasz Magiera committed
181
182
	if err := sfs.Lock(ctx, cacheDir); err != nil {
		return RawSealPreCommitOutput{}, xerrors.Errorf("lock cache: %w", err)
Jakub Sztandera's avatar
Jakub Sztandera committed
183
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
184
185
	if err := sfs.Lock(ctx, sealedPath); err != nil {
		return RawSealPreCommitOutput{}, xerrors.Errorf("lock sealed: %w", err)
Jakub Sztandera's avatar
Jakub Sztandera committed
186
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
187
188
	defer sfs.Unlock(cacheDir)
	defer sfs.Unlock(sealedPath)
Jakub Sztandera's avatar
Jakub Sztandera committed
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

	call := workerCall{
		task: WorkerTask{
			Type:       WorkerPreCommit,
			TaskID:     atomic.AddUint64(&sb.taskCtr, 1),
			SectorID:   sectorID,
			SealTicket: ticket,
			Pieces:     pieces,
		},
		ret: make(chan SealRes),
	}

	atomic.AddInt32(&sb.preCommitWait, 1)

	select { // prefer remote
	case sb.precommitTasks <- call:
		return sb.sealPreCommitRemote(call)
	default:
	}

	sb.checkRateLimit()

	rl := sb.rateLimit
	if sb.noPreCommit {
		rl = make(chan struct{})
	}

	select { // use whichever is available
	case sb.precommitTasks <- call:
		return sb.sealPreCommitRemote(call)
	case rl <- struct{}{}:
	case <-ctx.Done():
		return RawSealPreCommitOutput{}, ctx.Err()
	}

	atomic.AddInt32(&sb.preCommitWait, -1)

	// local

	defer func() {
		<-sb.rateLimit
	}()

Łukasz Magiera's avatar
Łukasz Magiera committed
232
	e, err := os.OpenFile(string(sealedPath), os.O_RDWR|os.O_CREATE, 0644)
Jakub Sztandera's avatar
Jakub Sztandera committed
233
234
235
236
237
238
239
	if err != nil {
		return RawSealPreCommitOutput{}, xerrors.Errorf("ensuring sealed file exists: %w", err)
	}
	if err := e.Close(); err != nil {
		return RawSealPreCommitOutput{}, err
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
240
241
242
243
	if err := os.Mkdir(string(cacheDir), 0755); err != nil {
		return RawSealPreCommitOutput{}, err
	}

Jakub Sztandera's avatar
Jakub Sztandera committed
244
245
246
247
248
249
250
251
252
	var sum uint64
	for _, piece := range pieces {
		sum += piece.Size
	}
	ussize := UserBytesForSectorSize(sb.ssize)
	if sum != ussize {
		return RawSealPreCommitOutput{}, xerrors.Errorf("aggregated piece sizes don't match sector size: %d != %d (%d)", sum, ussize, int64(ussize-sum))
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
253
254
255
256
	stagedPath, err := sb.SectorPath(fs.DataStaging, sectorID)
	if err != nil {
		return RawSealPreCommitOutput{}, xerrors.Errorf("get staged: %w", err)
	}
Jakub Sztandera's avatar
Jakub Sztandera committed
257
258
259
260
	// TODO: context cancellation respect
	rspco, err := ffi.SealPreCommit(
		sb.ssize,
		PoRepProofPartitions,
Łukasz Magiera's avatar
Łukasz Magiera committed
261
262
263
		string(cacheDir),
		string(stagedPath),
		string(sealedPath),
Jakub Sztandera's avatar
Jakub Sztandera committed
264
265
266
267
268
269
270
271
272
273
274
275
		sectorID,
		addressToProverID(sb.Miner),
		ticket.TicketBytes,
		pieces,
	)
	if err != nil {
		return RawSealPreCommitOutput{}, xerrors.Errorf("presealing sector %d (%s): %w", sectorID, stagedPath, err)
	}

	return RawSealPreCommitOutput(rspco), nil
}

Łukasz Magiera's avatar
Łukasz Magiera committed
276
func (sb *SectorBuilder) sealCommitLocal(ctx context.Context, sectorID uint64, ticket SealTicket, seed SealSeed, pieces []PublicPieceInfo, rspco RawSealPreCommitOutput) (proof []byte, err error) {
Jakub Sztandera's avatar
Jakub Sztandera committed
277
278
279
280
281
282
	atomic.AddInt32(&sb.commitWait, -1)

	defer func() {
		<-sb.rateLimit
	}()

Łukasz Magiera's avatar
Łukasz Magiera committed
283
	cacheDir, err := sb.SectorPath(fs.DataCache, sectorID)
Jakub Sztandera's avatar
Jakub Sztandera committed
284
285
286
	if err != nil {
		return nil, err
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
287
288
289
290
	if err := sb.filesystem.Lock(ctx, cacheDir); err != nil {
		return nil, err
	}
	defer sb.filesystem.Unlock(cacheDir)
Jakub Sztandera's avatar
Jakub Sztandera committed
291
292
293
294

	proof, err = ffi.SealCommit(
		sb.ssize,
		PoRepProofPartitions,
Łukasz Magiera's avatar
Łukasz Magiera committed
295
		string(cacheDir),
Jakub Sztandera's avatar
Jakub Sztandera committed
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
		sectorID,
		addressToProverID(sb.Miner),
		ticket.TicketBytes,
		seed.TicketBytes,
		pieces,
		ffi.RawSealPreCommitOutput(rspco),
	)
	if err != nil {
		log.Warn("StandaloneSealCommit error: ", err)
		log.Warnf("sid:%d tkt:%v seed:%v, ppi:%v rspco:%v", sectorID, ticket, seed, pieces, rspco)

		return nil, xerrors.Errorf("StandaloneSealCommit: %w", err)
	}

	return proof, nil
}

func (sb *SectorBuilder) SealCommit(ctx context.Context, sectorID uint64, ticket SealTicket, seed SealSeed, pieces []PublicPieceInfo, rspco RawSealPreCommitOutput) (proof []byte, err error) {
	call := workerCall{
		task: WorkerTask{
			Type:       WorkerCommit,
			TaskID:     atomic.AddUint64(&sb.taskCtr, 1),
			SectorID:   sectorID,
			SealTicket: ticket,
			Pieces:     pieces,

			SealSeed: seed,
			Rspco:    rspco,
		},
		ret: make(chan SealRes),
	}

	atomic.AddInt32(&sb.commitWait, 1)

	select { // prefer remote
	case sb.commitTasks <- call:
		proof, err = sb.sealCommitRemote(call)
	default:
		sb.checkRateLimit()

		rl := sb.rateLimit
		if sb.noCommit {
			rl = make(chan struct{})
		}

		select { // use whichever is available
		case sb.commitTasks <- call:
			proof, err = sb.sealCommitRemote(call)
		case rl <- struct{}{}:
Łukasz Magiera's avatar
Łukasz Magiera committed
345
			proof, err = sb.sealCommitLocal(ctx, sectorID, ticket, seed, pieces, rspco)
Jakub Sztandera's avatar
Jakub Sztandera committed
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
		case <-ctx.Done():
			return nil, ctx.Err()
		}
	}
	if err != nil {
		return nil, xerrors.Errorf("commit: %w", err)
	}

	return proof, nil
}

func (sb *SectorBuilder) ComputeElectionPoSt(sectorInfo SortedPublicSectorInfo, challengeSeed []byte, winners []EPostCandidate) ([]byte, error) {
	if len(challengeSeed) != CommLen {
		return nil, xerrors.Errorf("given challenge seed was the wrong length: %d != %d", len(challengeSeed), CommLen)
	}
	var cseed [CommLen]byte
	copy(cseed[:], challengeSeed)

	privsects, err := sb.pubSectorToPriv(sectorInfo, nil) // TODO: faults
	if err != nil {
		return nil, err
	}

	proverID := addressToProverID(sb.Miner)

	return ffi.GeneratePoSt(sb.ssize, proverID, privsects, cseed, winners)
}

func (sb *SectorBuilder) GenerateEPostCandidates(sectorInfo SortedPublicSectorInfo, challengeSeed [CommLen]byte, faults []uint64) ([]EPostCandidate, error) {
	privsectors, err := sb.pubSectorToPriv(sectorInfo, faults)
	if err != nil {
		return nil, err
	}

	challengeCount := ElectionPostChallengeCount(uint64(len(sectorInfo.Values())), uint64(len(faults)))

	proverID := addressToProverID(sb.Miner)
	return ffi.GenerateCandidates(sb.ssize, proverID, challengeSeed, challengeCount, privsectors)
}

func (sb *SectorBuilder) GenerateFallbackPoSt(sectorInfo SortedPublicSectorInfo, challengeSeed [CommLen]byte, faults []uint64) ([]EPostCandidate, []byte, error) {
	privsectors, err := sb.pubSectorToPriv(sectorInfo, faults)
	if err != nil {
		return nil, nil, err
	}

	challengeCount := fallbackPostChallengeCount(uint64(len(sectorInfo.Values())), uint64(len(faults)))

	proverID := addressToProverID(sb.Miner)
	candidates, err := ffi.GenerateCandidates(sb.ssize, proverID, challengeSeed, challengeCount, privsectors)
	if err != nil {
		return nil, nil, err
	}

	proof, err := ffi.GeneratePoSt(sb.ssize, proverID, privsectors, challengeSeed, candidates)
	return candidates, proof, err
}