bindings.go 38.3 KB
Newer Older
1
package go_sectorbuilder
2
3

import (
4
	"bytes"
5
	"encoding/json"
6
7
	"os"
	"runtime"
8
	"sort"
9
10
11
	"time"
	"unsafe"

12
	"github.com/filecoin-project/go-sectorbuilder/sealed_sector_health"
13
	"github.com/filecoin-project/go-sectorbuilder/sealing_state"
14

15
16
17
18
	logging "github.com/ipfs/go-log"
	"github.com/pkg/errors"
)

19
20
21
// #cgo LDFLAGS: ${SRCDIR}/libsector_builder_ffi.a
// #cgo pkg-config: ${SRCDIR}/sector_builder_ffi.pc
// #include "./sector_builder_ffi.h"
22
23
24
25
26
27
28
29
30
31
32
import "C"

var log = logging.Logger("libsectorbuilder") // nolint: deadcode

func elapsed(what string) func() {
	start := time.Now()
	return func() {
		log.Debugf("%s took %v\n", what, time.Since(start))
	}
}

33
34
35
// SortedPublicSectorInfo is a slice of PublicSectorInfo sorted
// (lexicographically, ascending) by replica commitment (CommR).
type SortedPublicSectorInfo struct {
36
	f []PublicSectorInfo
37
38
39
40
41
}

// SortedPrivateSectorInfo is a slice of PrivateSectorInfo sorted
// (lexicographically, ascending) by replica commitment (CommR).
type SortedPrivateSectorInfo struct {
42
	f []PrivateSectorInfo
43
44
}

45
// SealTicket is required for the first step of Interactive PoRep.
46
47
48
49
50
type SealTicket struct {
	BlockHeight uint64
	TicketBytes [32]byte
}

51
52
53
54
55
56
// SealSeed is required for the second step of Interactive PoRep.
type SealSeed struct {
	BlockHeight uint64
	TicketBytes [32]byte
}

57
58
59
60
61
62
63
type Candidate struct {
	SectorID             uint64
	PartialTicket        [32]byte
	Ticket               [32]byte
	SectorChallengeIndex uint64
}

64
65
// NewSortedPublicSectorInfo returns a SortedPublicSectorInfo
func NewSortedPublicSectorInfo(sectorInfo ...PublicSectorInfo) SortedPublicSectorInfo {
66
67
68
69
70
71
	fn := func(i, j int) bool {
		return bytes.Compare(sectorInfo[i].CommR[:], sectorInfo[j].CommR[:]) == -1
	}

	sort.Slice(sectorInfo[:], fn)

72
	return SortedPublicSectorInfo{
73
74
75
76
		f: sectorInfo,
	}
}

77
78
// Values returns the sorted PublicSectorInfo as a slice
func (s *SortedPublicSectorInfo) Values() []PublicSectorInfo {
79
80
81
	return s.f
}

82
83
// MarshalJSON JSON-encodes and serializes the SortedPublicSectorInfo.
func (s SortedPublicSectorInfo) MarshalJSON() ([]byte, error) {
84
85
86
87
88
	return json.Marshal(s.f)
}

// UnmarshalJSON parses the JSON-encoded byte slice and stores the result in the
// value pointed to by s.f. Note that this method allows for construction of a
89
// SortedPublicSectorInfo which violates its invariant (that its PublicSectorInfo are sorted
90
91
// in some defined way). Callers should take care to never provide a byte slice
// which would violate this invariant.
92
func (s *SortedPublicSectorInfo) UnmarshalJSON(b []byte) error {
93
94
95
	return json.Unmarshal(b, &s.f)
}

96
type PublicSectorInfo struct {
97
	SectorID uint64
98
	CommR    [CommitmentBytesLen]byte
99
100
}

101
102
// NewSortedPrivateSectorInfo returns a SortedPrivateSectorInfo
func NewSortedPrivateSectorInfo(sectorInfo ...PrivateSectorInfo) SortedPrivateSectorInfo {
103
104
105
106
107
108
109
110
111
112
113
	fn := func(i, j int) bool {
		return bytes.Compare(sectorInfo[i].CommR[:], sectorInfo[j].CommR[:]) == -1
	}

	sort.Slice(sectorInfo[:], fn)

	return SortedPrivateSectorInfo{
		f: sectorInfo,
	}
}

114
115
// Values returns the sorted PrivateSectorInfo as a slice
func (s *SortedPrivateSectorInfo) Values() []PrivateSectorInfo {
116
117
118
119
120
121
122
123
124
125
126
127
	return s.f
}

// MarshalJSON JSON-encodes and serializes the SortedPrivateSectorInfo.
func (s SortedPrivateSectorInfo) MarshalJSON() ([]byte, error) {
	return json.Marshal(s.f)
}

func (s *SortedPrivateSectorInfo) UnmarshalJSON(b []byte) error {
	return json.Unmarshal(b, &s.f)
}

128
type PrivateSectorInfo struct {
129
130
131
132
133
134
	SectorID         uint64
	CommR            [CommitmentBytesLen]byte
	CacheDirPath     string
	SealedSectorPath string
}

135
136
137
// CommitmentBytesLen is the number of bytes in a CommR, CommD, CommP, and CommRStar.
const CommitmentBytesLen = 32

138
139
140
141
142
143
144
// StagedSectorMetadata is a sector into which we write user piece-data before
// sealing. Note: SectorID is unique across all staged and sealed sectors for a
// storage miner actor.
type StagedSectorMetadata struct {
	SectorID uint64
}

Sidney Keese's avatar
Sidney Keese committed
145
146
// SealedSectorMetadata represents a sector in the builder that has been sealed.
type SealedSectorMetadata struct {
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
	SectorID uint64
	CommD    [CommitmentBytesLen]byte
	CommR    [CommitmentBytesLen]byte
	Proof    []byte
	Pieces   []PieceMetadata
	Health   sealed_sector_health.Health
	Ticket   SealTicket
	Seed     SealSeed
}

// SealPreCommitOutput is used to acquire a seed from the chain for the second
// step of Interactive PoRep.
type SealPreCommitOutput struct {
	SectorID uint64
	CommD    [CommitmentBytesLen]byte
	CommR    [CommitmentBytesLen]byte
	Pieces   []PieceMetadata
	Ticket   SealTicket
}

167
168
169
170
171
172
173
174
175
176
177
// RawSealPreCommitOutput is used to acquire a seed from the chain for the
// second step of Interactive PoRep. The PersistentAux is not expected to appear
// on-chain, but is needed for committing. This struct is useful for standalone
// (e.g. no sector builder) sealing.
type RawSealPreCommitOutput struct {
	CommC     [CommitmentBytesLen]byte
	CommD     [CommitmentBytesLen]byte
	CommR     [CommitmentBytesLen]byte
	CommRLast [CommitmentBytesLen]byte
}

178
179
180
181
182
183
184
185
186
// SealCommitOutput is produced by the second step of Interactive PoRep.
type SealCommitOutput struct {
	SectorID uint64
	CommD    [CommitmentBytesLen]byte
	CommR    [CommitmentBytesLen]byte
	Proof    []byte
	Pieces   []PieceMetadata
	Ticket   SealTicket
	Seed     SealSeed
Sidney Keese's avatar
Sidney Keese committed
187
188
}

189
190
191
// SectorSealingStatus communicates how far along in the sealing process a
// sector has progressed.
type SectorSealingStatus struct {
192
193
194
	SectorID     uint64
	State        sealing_state.State
	SealErrorMsg string                   // will be nil unless State == Failed
195
196
197
198
199
200
	CommD        [CommitmentBytesLen]byte // will be empty unless State == Committed
	CommR        [CommitmentBytesLen]byte // will be empty unless State == Committed
	Proof        []byte                   // will be empty unless State == Committed
	Pieces       []PieceMetadata          // will be empty unless State == Committed
	Ticket       SealTicket               // will be empty unless State == Committed
	Seed         SealSeed                 // will be empty unless State == Committed
201
202
203
204
}

// PieceMetadata represents a piece stored by the sector builder.
type PieceMetadata struct {
205
206
207
208
209
210
211
212
213
	Key   string
	Size  uint64
	CommP [CommitmentBytesLen]byte
}

// PublicPieceInfo is an on-chain tuple of CommP and aligned piece-size.
type PublicPieceInfo struct {
	Size  uint64
	CommP [CommitmentBytesLen]byte
214
215
216
217
218
219
}

// VerifySeal returns true if the sealing operation from which its inputs were
// derived was valid, and false if not.
func VerifySeal(
	sectorSize uint64,
220
221
	commR [CommitmentBytesLen]byte,
	commD [CommitmentBytesLen]byte,
222
223
	proverID [32]byte,
	ticket [32]byte,
224
	seed [32]byte,
laser's avatar
laser committed
225
	sectorID uint64,
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
	proof []byte,
) (bool, error) {
	defer elapsed("VerifySeal")()

	commDCBytes := C.CBytes(commD[:])
	defer C.free(commDCBytes)

	commRCBytes := C.CBytes(commR[:])
	defer C.free(commRCBytes)

	proofCBytes := C.CBytes(proof[:])
	defer C.free(proofCBytes)

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

242
243
244
	ticketCBytes := C.CBytes(ticket[:])
	defer C.free(ticketCBytes)

245
246
247
	seedCBytes := C.CBytes(seed[:])
	defer C.free(seedCBytes)

248
	// a mutable pointer to a VerifySealResponse C-struct
249
	resPtr := C.sector_builder_ffi_reexported_verify_seal(
250
		C.uint64_t(sectorSize),
251
252
		(*[CommitmentBytesLen]C.uint8_t)(commRCBytes),
		(*[CommitmentBytesLen]C.uint8_t)(commDCBytes),
253
		(*[32]C.uint8_t)(proverIDCBytes),
laser's avatar
laser committed
254
		C.uint64_t(sectorID),
255
		(*[32]C.uint8_t)(ticketCBytes),
256
		(*[32]C.uint8_t)(seedCBytes),
257
258
		(*C.uint8_t)(proofCBytes),
		C.size_t(len(proof)),
259
	)
260
	defer C.sector_builder_ffi_reexported_destroy_verify_seal_response(resPtr)
261
262
263
264
265
266
267
268
269
270
271
272

	if resPtr.status_code != 0 {
		return false, errors.New(C.GoString(resPtr.error_msg))
	}

	return bool(resPtr.is_valid), nil
}

// VerifyPoSt returns true if the PoSt-generation operation from which its
// inputs were derived was valid, and false if not.
func VerifyPoSt(
	sectorSize uint64,
273
274
	sectorInfo SortedPublicSectorInfo,
	randomness [32]byte,
275
	challengeCount uint64,
laser's avatar
laser committed
276
	proof []byte,
277
278
	winners []Candidate,
	proverID [32]byte,
279
280
281
) (bool, error) {
	defer elapsed("VerifyPoSt")()

282
283
284
285
286
287
288
289
	// CommRs and sector ids must be provided to C.verify_post in the same order
	// that they were provided to the C.generate_post
	sortedCommRs := make([][CommitmentBytesLen]byte, len(sectorInfo.Values()))
	sortedSectorIds := make([]uint64, len(sectorInfo.Values()))
	for idx, v := range sectorInfo.Values() {
		sortedCommRs[idx] = v.CommR
		sortedSectorIds[idx] = v.SectorID
	}
290
291

	// flattening the byte slice makes it easier to copy into the C heap
292
293
	flattened := make([]byte, CommitmentBytesLen*len(sortedCommRs))
	for idx, commR := range sortedCommRs {
294
		copy(flattened[(CommitmentBytesLen*idx):(CommitmentBytesLen*(1+idx))], commR[:])
295
296
297
298
299
300
	}

	// copy bytes from Go to C heap
	flattenedCommRsCBytes := C.CBytes(flattened)
	defer C.free(flattenedCommRsCBytes)

301
302
	randomnessCBytes := C.CBytes(randomness[:])
	defer C.free(randomnessCBytes)
303

laser's avatar
laser committed
304
305
	proofCBytes := C.CBytes(proof)
	defer C.free(proofCBytes)
306
307

	// allocate fixed-length array of uint64s in C heap
laser's avatar
laser committed
308
309
310
	sectorIdsPtr, sectorIdsSize := cUint64s(sortedSectorIds)
	defer C.free(unsafe.Pointer(sectorIdsPtr))

311
312
313
314
315
	winnersPtr, winnersSize := cCandidates(winners)
	defer C.free(unsafe.Pointer(winnersPtr))

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)
316
317

	// a mutable pointer to a VerifyPoStResponse C-struct
318
	resPtr := C.sector_builder_ffi_reexported_verify_post(
319
		C.uint64_t(sectorSize),
320
		(*[32]C.uint8_t)(randomnessCBytes),
321
		C.uint64_t(challengeCount),
laser's avatar
laser committed
322
323
324
325
326
327
		sectorIdsPtr,
		sectorIdsSize,
		(*C.uint8_t)(flattenedCommRsCBytes),
		C.size_t(len(flattened)),
		(*C.uint8_t)(proofCBytes),
		C.size_t(len(proof)),
328
329
330
		winnersPtr,
		winnersSize,
		(*[32]C.uint8_t)(proverIDCBytes),
331
	)
332
	defer C.sector_builder_ffi_reexported_destroy_verify_post_response(resPtr)
333
334
335
336
337
338
339
340
341
342
343
344
345
346

	if resPtr.status_code != 0 {
		return false, errors.New(C.GoString(resPtr.error_msg))
	}

	return bool(resPtr.is_valid), nil
}

// GetMaxUserBytesPerStagedSector returns the number of user bytes that will fit
// into a staged sector. Due to bit-padding, the number of user bytes that will
// fit into the staged sector will be less than number of bytes in sectorSize.
func GetMaxUserBytesPerStagedSector(sectorSize uint64) uint64 {
	defer elapsed("GetMaxUserBytesPerStagedSector")()

347
	return uint64(C.sector_builder_ffi_reexported_get_max_user_bytes_per_staged_sector(C.uint64_t(sectorSize)))
348
349
350
351
352
353
354
355
}

// InitSectorBuilder allocates and returns a pointer to a sector builder.
func InitSectorBuilder(
	sectorSize uint64,
	poRepProofPartitions uint8,
	lastUsedSectorID uint64,
	metadataDir string,
356
	proverID [32]byte,
357
358
	sealedSectorDir string,
	stagedSectorDir string,
359
	sectorCacheRootDir string,
360
	maxNumOpenStagedSectors uint8,
361
	numWorkerThreads uint8,
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
) (unsafe.Pointer, error) {
	defer elapsed("InitSectorBuilder")()

	cMetadataDir := C.CString(metadataDir)
	defer C.free(unsafe.Pointer(cMetadataDir))

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

	cStagedSectorDir := C.CString(stagedSectorDir)
	defer C.free(unsafe.Pointer(cStagedSectorDir))

	cSealedSectorDir := C.CString(sealedSectorDir)
	defer C.free(unsafe.Pointer(cSealedSectorDir))

377
378
379
	cSectorCacheRootDir := C.CString(sectorCacheRootDir)
	defer C.free(unsafe.Pointer(cSectorCacheRootDir))

380
	resPtr := C.sector_builder_ffi_init_sector_builder(
381
		cSectorClass(sectorSize, poRepProofPartitions),
382
383
		C.uint64_t(lastUsedSectorID),
		cMetadataDir,
384
		(*[32]C.uint8_t)(proverIDCBytes),
385
386
		cSealedSectorDir,
		cStagedSectorDir,
387
		cSectorCacheRootDir,
388
		C.uint8_t(maxNumOpenStagedSectors),
389
		C.uint8_t(numWorkerThreads),
390
	)
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
	defer C.sector_builder_ffi_destroy_init_sector_builder_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

	return unsafe.Pointer(resPtr.sector_builder), nil
}

// DestroySectorBuilder deallocates the sector builder associated with the
// provided pointer. This function will panic if the provided pointer is null
// or if the sector builder has been previously deallocated.
func DestroySectorBuilder(sectorBuilderPtr unsafe.Pointer) {
	defer elapsed("DestroySectorBuilder")()

	C.sector_builder_ffi_destroy_sector_builder((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr))
}

409
// AddPiece writes the given piece into an unsealed sector and returns the id of that sector.
410
411
412
func AddPiece(
	sectorBuilderPtr unsafe.Pointer,
	pieceKey string,
413
	pieceBytes uint64,
414
	piecePath string,
415
) (uint64, error) {
416
417
	defer elapsed("AddPiece")()

418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
	pieceFile, err := os.Open(piecePath)
	if err != nil {
		return 0, err
	}

	return AddPieceFromFile(sectorBuilderPtr, pieceKey, pieceBytes, pieceFile)
}

// AddPieceFromFile writes the given piece into an unsealed sector and returns the id of that sector.
func AddPieceFromFile(
	sectorBuilderPtr unsafe.Pointer,
	pieceKey string,
	pieceBytes uint64,
	pieceFile *os.File,
) (sectorID uint64, retErr error) {
	defer elapsed("AddPieceFromFile")()

435
436
437
	cPieceKey := C.CString(pieceKey)
	defer C.free(unsafe.Pointer(cPieceKey))

438
	pieceFd := pieceFile.Fd()
439

440
441
442
443
444
445
446
447
448
449
	// TODO: The UTC time, in seconds, at which the sector builder can safely
	// delete the piece. This allows for co-location of pieces with similar time
	// constraints, and allows the sector builder to remove sectors containing
	// pieces whose deals have expired.
	//
	// This value is currently ignored by the sector builder.
	//
	// https://github.com/filecoin-project/rust-fil-sector-builder/issues/32
	pieceExpiryUtcSeconds := 0

450
	resPtr := C.sector_builder_ffi_add_piece(
451
452
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
		cPieceKey,
453
454
		C.int(pieceFd),
		C.uint64_t(pieceBytes),
455
		C.uint64_t(pieceExpiryUtcSeconds),
456
	)
457
458
	defer C.sector_builder_ffi_destroy_add_piece_response(resPtr)

459
460
461
	// Make sure our filedescriptor stays alive, stayin alive
	runtime.KeepAlive(pieceFile)

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
	if resPtr.status_code != 0 {
		return 0, errors.New(C.GoString(resPtr.error_msg))
	}

	return uint64(resPtr.sector_id), nil
}

// ReadPieceFromSealedSector produces a byte buffer containing the piece
// associated with the provided key. If the key is not associated with any piece
// yet sealed into a sector, an error will be returned.
func ReadPieceFromSealedSector(sectorBuilderPtr unsafe.Pointer, pieceKey string) ([]byte, error) {
	defer elapsed("ReadPieceFromSealedSector")()

	cPieceKey := C.CString(pieceKey)
	defer C.free(unsafe.Pointer(cPieceKey))

478
479
480
481
	resPtr := C.sector_builder_ffi_read_piece_from_sealed_sector(
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
		cPieceKey,
	)
482
483
484
485
486
487
488
489
490
	defer C.sector_builder_ffi_destroy_read_piece_from_sealed_sector_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

	return goBytes(resPtr.data_ptr, resPtr.data_len), nil
}

491
492
493
494
495
// SealPreCommit pre-commits the sector with the provided id to the ticket,
// blocking until completion. If no staged sector with the provided id exists in
// the FullyPacked or AcceptingPieces state, an error will be returned.
func SealPreCommit(sectorBuilderPtr unsafe.Pointer, sectorID uint64, ticket SealTicket) (SealPreCommitOutput, error) {
	defer elapsed("SealPreCommit")()
496
497
498
499
500
501
502
503
504

	cTicketBytes := C.CBytes(ticket.TicketBytes[:])
	defer C.free(cTicketBytes)

	cSealTicket := C.sector_builder_ffi_FFISealTicket{
		block_height: C.uint64_t(ticket.BlockHeight),
		ticket_bytes: *(*[32]C.uint8_t)(cTicketBytes),
	}

505
506
	resPtr := C.sector_builder_ffi_seal_pre_commit((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr), C.uint64_t(sectorID), cSealTicket)
	defer C.sector_builder_ffi_destroy_seal_pre_commit_response(resPtr)
507
508

	if resPtr.status_code != 0 {
509
		return SealPreCommitOutput{}, errors.New(C.GoString(resPtr.error_msg))
510
511
	}

512
	out, err := goSectorBuilderSealPreCommitOutput(resPtr)
513
	if err != nil {
514
		return SealPreCommitOutput{}, err
515
516
	}

517
	return out, nil
518
519
}

520
521
522
523
524
// ResumeSealPreCommit resumes the pre-commit operation for a sector with the
// provided id. If no sector exists with the given id that is in the
// PreCommittingPaused state, an error will be returned.
func ResumeSealPreCommit(sectorBuilderPtr unsafe.Pointer, sectorID uint64) (SealPreCommitOutput, error) {
	defer elapsed("ResumeSealPreCommit")()
525

526
527
	resPtr := C.sector_builder_ffi_resume_seal_pre_commit((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr), C.uint64_t(sectorID))
	defer C.sector_builder_ffi_destroy_resume_seal_pre_commit_response(resPtr)
528
529

	if resPtr.status_code != 0 {
530
		return SealPreCommitOutput{}, errors.New(C.GoString(resPtr.error_msg))
531
532
	}

533
	out, err := goResumeSealPreCommitOutput(resPtr)
534
	if err != nil {
535
		return SealPreCommitOutput{}, err
536
537
	}

538
	return out, nil
539
540
}

541
542
543
544
545
// SealCommit commits the sector with the provided id to the seed, blocking
// until completion. If no staged sector exists in the PreCommitted state with
// such an id, an error will be returned.
func SealCommit(sectorBuilderPtr unsafe.Pointer, sectorID uint64, seed SealSeed) (SealCommitOutput, error) {
	defer elapsed("SealCommit")()
546

547
548
	cSeedBytes := C.CBytes(seed.TicketBytes[:])
	defer C.free(cSeedBytes)
549

550
551
552
	cSealSeed := C.sector_builder_ffi_FFISealSeed{
		block_height: C.uint64_t(seed.BlockHeight),
		ticket_bytes: *(*[32]C.uint8_t)(cSeedBytes),
553
554
	}

555
556
	resPtr := C.sector_builder_ffi_seal_commit((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr), C.uint64_t(sectorID), cSealSeed)
	defer C.sector_builder_ffi_destroy_seal_commit_response(resPtr)
557
558

	if resPtr.status_code != 0 {
559
		return SealCommitOutput{}, errors.New(C.GoString(resPtr.error_msg))
560
561
	}

562
	out, err := goSectorBuilderSealCommitOutput(resPtr)
563
	if err != nil {
564
		return SealCommitOutput{}, err
565
566
	}

567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
	return out, nil
}

// ResumeSealCommit resumes sector commit (the second stage of Interactive
// PoRep) for a sector in the CommittingPaused state. If no staged sector exists
// in such a state, an error will be returned.
func ResumeSealCommit(sectorBuilderPtr unsafe.Pointer, sectorID uint64) (SealCommitOutput, error) {
	defer elapsed("ResumeSealCommit")()

	resPtr := C.sector_builder_ffi_resume_seal_commit((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr), C.uint64_t(sectorID))
	defer C.sector_builder_ffi_destroy_resume_seal_commit_response(resPtr)

	if resPtr.status_code != 0 {
		return SealCommitOutput{}, errors.New(C.GoString(resPtr.error_msg))
	}

	out, err := goResumeSealCommitOutput(resPtr)
	if err != nil {
		return SealCommitOutput{}, err
	}

	return out, nil
589
590
591
592
593
594
}

// GetAllStagedSectors returns a slice of all staged sector metadata for the sector builder.
func GetAllStagedSectors(sectorBuilderPtr unsafe.Pointer) ([]StagedSectorMetadata, error) {
	defer elapsed("GetAllStagedSectors")()

595
	resPtr := C.sector_builder_ffi_get_staged_sectors((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr))
596
597
598
599
600
601
	defer C.sector_builder_ffi_destroy_get_staged_sectors_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

602
	meta, err := goStagedSectorMetadata(resPtr.sectors_ptr, resPtr.sectors_len)
603
604
605
606
607
608
609
	if err != nil {
		return nil, err
	}

	return meta, nil
}

610
611
612
// GetAllSealedSectors returns a slice of all sealed sector metadata, excluding
// sector health.
func GetAllSealedSectors(sectorBuilderPtr unsafe.Pointer) ([]SealedSectorMetadata, error) {
Sidney Keese's avatar
Sidney Keese committed
613
614
	defer elapsed("GetAllSealedSectors")()

615
616
	return getAllSealedSectors(sectorBuilderPtr, false)
}
Sidney Keese's avatar
Sidney Keese committed
617

618
619
620
621
622
// GetAllSealedSectorsWithHealth returns a slice of all sealed sector metadata
// for the sector builder, including sector health info (which can be expensive
// to compute).
func GetAllSealedSectorsWithHealth(sectorBuilderPtr unsafe.Pointer) ([]SealedSectorMetadata, error) {
	defer elapsed("GetAllSealedSectorsWithHealth")()
Sidney Keese's avatar
Sidney Keese committed
623

624
	return getAllSealedSectors(sectorBuilderPtr, true)
Sidney Keese's avatar
Sidney Keese committed
625
626
}

627
628
629
// GetSectorSealingStatusByID produces sector sealing status (staged, sealing in
// progress, sealed, failed) for the provided sector id. If no sector
// corresponding to the provided id exists, this function returns an error.
630
631
632
func GetSectorSealingStatusByID(sectorBuilderPtr unsafe.Pointer, sectorID uint64) (SectorSealingStatus, error) {
	defer elapsed("GetSectorSealingStatusByID")()

633
634
635
636
	resPtr := C.sector_builder_ffi_get_seal_status(
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
		C.uint64_t(sectorID),
	)
637
638
639
640
641
642
643
	defer C.sector_builder_ffi_destroy_get_seal_status_response(resPtr)

	if resPtr.status_code != 0 {
		return SectorSealingStatus{}, errors.New(C.GoString(resPtr.error_msg))
	}

	if resPtr.seal_status_code == C.Failed {
644
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.Failed, SealErrorMsg: C.GoString(resPtr.seal_error_msg)}, nil
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
	} else if resPtr.seal_status_code == C.AcceptingPieces {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.AcceptingPieces}, nil
	} else if resPtr.seal_status_code == C.Committing {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.Committing}, nil
	} else if resPtr.seal_status_code == C.CommittingPaused {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.CommittingPaused}, nil
	} else if resPtr.seal_status_code == C.FullyPacked {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.FullyPacked}, nil
	} else if resPtr.seal_status_code == C.PreCommitted {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.PreCommitted}, nil
	} else if resPtr.seal_status_code == C.PreCommitting {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.PreCommitting}, nil
	} else if resPtr.seal_status_code == C.PreCommittingPaused {
		return SectorSealingStatus{SectorID: sectorID, State: sealing_state.PreCommittingPaused}, nil
	} else if resPtr.seal_status_code == C.Committed {
660
661
		commRSlice := goBytes(&resPtr.comm_r[0], CommitmentBytesLen)
		var commR [CommitmentBytesLen]byte
662
663
		copy(commR[:], commRSlice)

664
665
		commDSlice := goBytes(&resPtr.comm_d[0], CommitmentBytesLen)
		var commD [CommitmentBytesLen]byte
666
667
668
669
670
671
672
673
674
675
		copy(commD[:], commDSlice)

		proof := goBytes(resPtr.proof_ptr, resPtr.proof_len)

		ps, err := goPieceMetadata(resPtr.pieces_ptr, resPtr.pieces_len)
		if err != nil {
			return SectorSealingStatus{}, errors.Wrap(err, "failed to marshal from string to cid")
		}

		return SectorSealingStatus{
676
			SectorID: sectorID,
677
			State:    sealing_state.Committed,
678
679
680
681
682
			CommD:    commD,
			CommR:    commR,
			Proof:    proof,
			Pieces:   ps,
			Ticket:   goSealTicket(resPtr.seal_ticket),
683
			Seed:     goSealSeed(resPtr.seal_seed),
684
685
686
687
688
689
690
		}, nil
	} else {
		// unknown
		return SectorSealingStatus{}, errors.New("unexpected seal status")
	}
}

691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
// FinalizeTicket creates an actual ticket from a partial ticket.
func FinalizeTicket(partialTicket [32]byte) ([32]byte, error) {
	defer elapsed("FinalizeTicket")()

	partialTicketPtr := unsafe.Pointer(&(partialTicket)[0])
	resPtr := C.sector_builder_ffi_reexported_finalize_ticket(
		(*[32]C.uint8_t)(partialTicketPtr),
	)
	defer C.sector_builder_ffi_reexported_destroy_finalize_ticket_response(resPtr)

	if resPtr.status_code != 0 {
		return [32]byte{}, errors.New(C.GoString(resPtr.error_msg))
	}

	return goCommitment(&resPtr.ticket[0]), nil
}

// GenerateCandidates creates a list of election candidates.
func GenerateCandidates(
	sectorBuilderPtr unsafe.Pointer,
711
712
	sectorInfo SortedPublicSectorInfo,
	randomness [32]byte,
713
	challengeCount uint64,
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
	faults []uint64,
) ([]Candidate, error) {
	defer elapsed("GenerateCandidates")()

	// CommRs and sector ids must be provided to C.verify_post in the same order
	// that they were provided to the C.generate_post
	sortedCommRs := make([][CommitmentBytesLen]byte, len(sectorInfo.Values()))
	for idx, v := range sectorInfo.Values() {
		sortedCommRs[idx] = v.CommR
	}

	// flattening the byte slice makes it easier to copy into the C heap
	flattened := make([]byte, CommitmentBytesLen*len(sortedCommRs))
	for idx, commR := range sortedCommRs {
		copy(flattened[(CommitmentBytesLen*idx):(CommitmentBytesLen*(1+idx))], commR[:])
	}

	// copy the Go byte slice into C memory
	cflattened := C.CBytes(flattened)
	defer C.free(cflattened)

735
	randomnessPtr := unsafe.Pointer(&(randomness)[0])
736
737
738
739

	faultsPtr, faultsSize := cUint64s(faults)
	defer C.free(unsafe.Pointer(faultsPtr))

740
	// a mutable pointer to a SectorBuilderGenerateCandidatesResponse C-struct
741
742
743
744
	resPtr := C.sector_builder_ffi_generate_candidates(
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
		(*C.uint8_t)(cflattened),
		C.size_t(len(flattened)),
745
		(*[32]C.uint8_t)(randomnessPtr),
746
		C.uint64_t(challengeCount),
747
748
749
750
751
752
753
754
755
756
757
758
		faultsPtr,
		faultsSize,
	)
	defer C.sector_builder_ffi_destroy_generate_candidates_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

	return goCandidates(resPtr.candidates_ptr, resPtr.candidates_len)
}

759
760
761
// GeneratePoSt produces a proof-of-spacetime for the provided replica commitments.
func GeneratePoSt(
	sectorBuilderPtr unsafe.Pointer,
762
763
	sectorInfo SortedPublicSectorInfo,
	randomness [32]byte,
764
	challengeCount uint64,
765
	winners []Candidate,
laser's avatar
laser committed
766
) ([]byte, error) {
767
768
	defer elapsed("GeneratePoSt")()

769
770
771
772
773
774
775
	// CommRs and sector ids must be provided to C.verify_post in the same order
	// that they were provided to the C.generate_post
	sortedCommRs := make([][CommitmentBytesLen]byte, len(sectorInfo.Values()))
	for idx, v := range sectorInfo.Values() {
		sortedCommRs[idx] = v.CommR
	}

776
	// flattening the byte slice makes it easier to copy into the C heap
777
778
	flattened := make([]byte, CommitmentBytesLen*len(sortedCommRs))
	for idx, commR := range sortedCommRs {
779
		copy(flattened[(CommitmentBytesLen*idx):(CommitmentBytesLen*(1+idx))], commR[:])
780
781
782
783
784
785
	}

	// copy the Go byte slice into C memory
	cflattened := C.CBytes(flattened)
	defer C.free(cflattened)

786
	randomnessPtr := unsafe.Pointer(&(randomness)[0])
787

788
789
	winnersPtr, winnersSize := cCandidates(winners)
	defer C.free(unsafe.Pointer(winnersPtr))
laser's avatar
laser committed
790

791
	// a mutable pointer to a SectorBuilderGeneratePoStResponse C-struct
792
793
794
795
	resPtr := C.sector_builder_ffi_generate_post(
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
		(*C.uint8_t)(cflattened),
		C.size_t(len(flattened)),
796
		(*[32]C.uint8_t)(randomnessPtr),
797
		C.uint64_t(challengeCount),
798
799
		winnersPtr,
		winnersSize,
800
	)
801
802
803
	defer C.sector_builder_ffi_destroy_generate_post_response(resPtr)

	if resPtr.status_code != 0 {
laser's avatar
laser committed
804
		return nil, errors.New(C.GoString(resPtr.error_msg))
805
806
	}

807
	return goBytes(resPtr.flattened_proofs_ptr, resPtr.flattened_proofs_len), nil
808
}
809

810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
// AcquireSectorId returns a sector ID which can be used by out-of-band sealing.
func AcquireSectorId(
	sectorBuilderPtr unsafe.Pointer,
) (uint64, error) {
	defer elapsed("AcquireSectorId")()

	resPtr := C.sector_builder_ffi_acquire_sector_id(
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
	)
	defer C.sector_builder_ffi_destroy_acquire_sector_id_response(resPtr)

	if resPtr.status_code != 0 {
		return 0, errors.New(C.GoString(resPtr.error_msg))
	}

	return uint64(resPtr.sector_id), nil
}

// ImportSealedSector
func ImportSealedSector(
	sectorBuilderPtr unsafe.Pointer,
	sectorID uint64,
	sectorCacheDirPath string,
	sealedSectorPath string,
	ticket SealTicket,
	seed SealSeed,
	commR [CommitmentBytesLen]byte,
	commD [CommitmentBytesLen]byte,
	commC [CommitmentBytesLen]byte,
	commRLast [CommitmentBytesLen]byte,
	proof []byte,
	pieces []PieceMetadata,
) error {
	defer elapsed("ImportSealedSector")()

	cSectorCacheDirPath := C.CString(sectorCacheDirPath)
	defer C.free(unsafe.Pointer(cSectorCacheDirPath))

	cSealedSectorPath := C.CString(sealedSectorPath)
	defer C.free(unsafe.Pointer(cSealedSectorPath))

	cTicketBytes := C.CBytes(ticket.TicketBytes[:])
	defer C.free(cTicketBytes)

	cSealTicket := C.sector_builder_ffi_FFISealTicket{
		block_height: C.uint64_t(ticket.BlockHeight),
		ticket_bytes: *(*[32]C.uint8_t)(cTicketBytes),
	}

	cSeedBytes := C.CBytes(seed.TicketBytes[:])
	defer C.free(cSeedBytes)

	cSealSeed := C.sector_builder_ffi_FFISealSeed{
		block_height: C.uint64_t(seed.BlockHeight),
		ticket_bytes: *(*[32]C.uint8_t)(cSeedBytes),
	}

	commDCBytes := C.CBytes(commD[:])
	defer C.free(commDCBytes)

	commRCBytes := C.CBytes(commR[:])
	defer C.free(commRCBytes)

	commCCBytes := C.CBytes(commC[:])
	defer C.free(commCCBytes)

	commRLastCBytes := C.CBytes(commRLast[:])
	defer C.free(commRLastCBytes)

	proofCBytes := C.CBytes(proof[:])
	defer C.free(proofCBytes)

	piecesPtr, piecesLen := cPieceMetadata(pieces)
	defer C.free(unsafe.Pointer(piecesPtr))

	resPtr := C.sector_builder_ffi_import_sealed_sector(
		(*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr),
		C.uint64_t(sectorID),
		cSectorCacheDirPath,
		cSealedSectorPath,
		cSealTicket,
		cSealSeed,
		(*[CommitmentBytesLen]C.uint8_t)(commRCBytes),
		(*[CommitmentBytesLen]C.uint8_t)(commDCBytes),
		(*[CommitmentBytesLen]C.uint8_t)(commCCBytes),
		(*[CommitmentBytesLen]C.uint8_t)(commRLastCBytes),
		(*C.uint8_t)(proofCBytes),
		C.size_t(len(proof)),
		piecesPtr,
		piecesLen,
	)
	defer C.sector_builder_ffi_destroy_import_sealed_sector_response(resPtr)

	if resPtr.status_code != 0 {
		return errors.New(C.GoString(resPtr.error_msg))
	}

	return nil
}

910
// GeneratePieceCommitment produces a piece commitment for the provided data
911
912
913
914
915
916
// stored at a given path.
func GeneratePieceCommitment(piecePath string, pieceSize uint64) ([CommitmentBytesLen]byte, error) {
	pieceFile, err := os.Open(piecePath)
	if err != nil {
		return [CommitmentBytesLen]byte{}, err
	}
917

918
919
920
	return GeneratePieceCommitmentFromFile(pieceFile, pieceSize)
}

921
922
923
924
925
926
// GenerateDataCommitment produces a commitment for the sector containing the
// provided pieces.
func GenerateDataCommitment(sectorSize uint64, pieces []PublicPieceInfo) ([CommitmentBytesLen]byte, error) {
	cPiecesPtr, cPiecesLen := cPublicPieceInfo(pieces)
	defer C.free(unsafe.Pointer(cPiecesPtr))

927
928
	resPtr := C.sector_builder_ffi_reexported_generate_data_commitment(C.uint64_t(sectorSize), (*C.sector_builder_ffi_FFIPublicPieceInfo)(cPiecesPtr), cPiecesLen)
	defer C.sector_builder_ffi_reexported_destroy_generate_data_commitment_response(resPtr)
929
930
931
932
933

	if resPtr.status_code != 0 {
		return [CommitmentBytesLen]byte{}, errors.New(C.GoString(resPtr.error_msg))
	}

934
	return goCommitment(&resPtr.comm_d[0]), nil
935
936
}

937
938
939
940
941
// GeneratePieceCommitmentFromFile produces a piece commitment for the provided data
// stored in a given file.
func GeneratePieceCommitmentFromFile(pieceFile *os.File, pieceSize uint64) (commP [CommitmentBytesLen]byte, err error) {
	pieceFd := pieceFile.Fd()

942
943
	resPtr := C.sector_builder_ffi_reexported_generate_piece_commitment(C.int(pieceFd), C.uint64_t(pieceSize))
	defer C.sector_builder_ffi_reexported_destroy_generate_piece_commitment_response(resPtr)
944

945
946
947
	// Make sure our filedescriptor stays alive, stayin alive
	runtime.KeepAlive(pieceFile)

948
949
950
951
	if resPtr.status_code != 0 {
		return [CommitmentBytesLen]byte{}, errors.New(C.GoString(resPtr.error_msg))
	}

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
	return goCommitment(&resPtr.comm_p[0]), nil
}

// StandaloneWriteWithAlignment
func StandaloneWriteWithAlignment(
	pieceFile *os.File,
	pieceBytes uint64,
	stagedSectorFile *os.File,
	existingPieceSizes []uint64,
) (leftAlignment, total uint64, commP [CommitmentBytesLen]byte, retErr error) {
	defer elapsed("StandaloneWriteWithAlignment")()

	pieceFd := pieceFile.Fd()
	runtime.KeepAlive(pieceFile)

	stagedSectorFd := stagedSectorFile.Fd()
	runtime.KeepAlive(stagedSectorFile)

	ptr, len := cUint64s(existingPieceSizes)
	defer C.free(unsafe.Pointer(ptr))

	resPtr := C.sector_builder_ffi_reexported_write_with_alignment(
		C.int(pieceFd),
		C.uint64_t(pieceBytes),
		C.int(stagedSectorFd),
		ptr,
		len,
	)
	defer C.sector_builder_ffi_reexported_destroy_write_with_alignment_response(resPtr)

	if resPtr.status_code != 0 {
		return 0, 0, [CommitmentBytesLen]byte{}, errors.New(C.GoString(resPtr.error_msg))
	}

	return uint64(resPtr.left_alignment_unpadded), uint64(resPtr.total_write_unpadded), goCommitment(&resPtr.comm_p[0]), nil
}

// StandaloneWriteWithoutAlignment
func StandaloneWriteWithoutAlignment(
	pieceFile *os.File,
	pieceBytes uint64,
	stagedSectorFile *os.File,
) (uint64, [CommitmentBytesLen]byte, error) {
	defer elapsed("StandaloneWriteWithoutAlignment")()

	pieceFd := pieceFile.Fd()
	runtime.KeepAlive(pieceFile)

	stagedSectorFd := stagedSectorFile.Fd()
	runtime.KeepAlive(stagedSectorFile)

	resPtr := C.sector_builder_ffi_reexported_write_without_alignment(
		C.int(pieceFd),
		C.uint64_t(pieceBytes),
		C.int(stagedSectorFd),
	)
	defer C.sector_builder_ffi_reexported_destroy_write_without_alignment_response(resPtr)

	if resPtr.status_code != 0 {
		return 0, [CommitmentBytesLen]byte{}, errors.New(C.GoString(resPtr.error_msg))
	}

	return uint64(resPtr.total_write_unpadded), goCommitment(&resPtr.comm_p[0]), nil
}

// StandaloneSealPreCommit
func StandaloneSealPreCommit(
	sectorSize uint64,
	poRepProofPartitions uint8,
	cacheDirPath string,
	stagedSectorPath string,
	sealedSectorPath string,
	sectorID uint64,
1025
1026
	proverID [32]byte,
	ticket [32]byte,
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
	pieces []PublicPieceInfo,
) (RawSealPreCommitOutput, error) {
	defer elapsed("StandaloneSealPreCommit")()

	cCacheDirPath := C.CString(cacheDirPath)
	defer C.free(unsafe.Pointer(cCacheDirPath))

	cStagedSectorPath := C.CString(stagedSectorPath)
	defer C.free(unsafe.Pointer(cStagedSectorPath))

	cSealedSectorPath := C.CString(sealedSectorPath)
	defer C.free(unsafe.Pointer(cSealedSectorPath))

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

	ticketCBytes := C.CBytes(ticket[:])
	defer C.free(ticketCBytes)

	cPiecesPtr, cPiecesLen := cPublicPieceInfo(pieces)
	defer C.free(unsafe.Pointer(cPiecesPtr))

	resPtr := C.sector_builder_ffi_reexported_seal_pre_commit(
		cSectorClass(sectorSize, poRepProofPartitions),
		cCacheDirPath,
		cStagedSectorPath,
		cSealedSectorPath,
		C.uint64_t(sectorID),
		(*[32]C.uint8_t)(proverIDCBytes),
		(*[32]C.uint8_t)(ticketCBytes),
		(*C.sector_builder_ffi_FFIPublicPieceInfo)(cPiecesPtr),
		cPiecesLen,
	)
	defer C.sector_builder_ffi_reexported_destroy_seal_pre_commit_response(resPtr)

	if resPtr.status_code != 0 {
		return RawSealPreCommitOutput{}, errors.New(C.GoString(resPtr.error_msg))
	}

	return goRawSealPreCommitOutput(resPtr.seal_pre_commit_output), nil
}

// StandaloneSealCommit
func StandaloneSealCommit(
	sectorSize uint64,
	poRepProofPartitions uint8,
	cacheDirPath string,
	sectorID uint64,
1075
1076
1077
	proverID [32]byte,
	ticket [32]byte,
	seed [32]byte,
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
	pieces []PublicPieceInfo,
	rspco RawSealPreCommitOutput,
) ([]byte, error) {
	defer elapsed("StandaloneSealCommit")()

	cCacheDirPath := C.CString(cacheDirPath)
	defer C.free(unsafe.Pointer(cCacheDirPath))

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

	ticketCBytes := C.CBytes(ticket[:])
	defer C.free(ticketCBytes)

	seedCBytes := C.CBytes(seed[:])
	defer C.free(seedCBytes)

	cPiecesPtr, cPiecesLen := cPublicPieceInfo(pieces)
	defer C.free(unsafe.Pointer(cPiecesPtr))

	resPtr := C.sector_builder_ffi_reexported_seal_commit(
		cSectorClass(sectorSize, poRepProofPartitions),
		cCacheDirPath,
		C.uint64_t(sectorID),
		(*[32]C.uint8_t)(proverIDCBytes),
		(*[32]C.uint8_t)(ticketCBytes),
		(*[32]C.uint8_t)(seedCBytes),
		(*C.sector_builder_ffi_FFIPublicPieceInfo)(cPiecesPtr),
		cPiecesLen,
		cSealPreCommitOutput(rspco),
	)
	defer C.sector_builder_ffi_reexported_destroy_seal_commit_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

	return C.GoBytes(unsafe.Pointer(resPtr.proof_ptr), C.int(resPtr.proof_len)), nil
}

// StandaloneUnseal
func StandaloneUnseal(
	sectorSize uint64,
	poRepProofPartitions uint8,
1122
	cacheDirPath string,
1123
1124
1125
	sealedSectorPath string,
	unsealOutputPath string,
	sectorID uint64,
1126
1127
	proverID [32]byte,
	ticket [32]byte,
1128
1129
1130
1131
	commD [CommitmentBytesLen]byte,
) error {
	defer elapsed("StandaloneUnseal")()

1132
1133
1134
	cCacheDirPath := C.CString(cacheDirPath)
	defer C.free(unsafe.Pointer(cCacheDirPath))

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
	cSealedSectorPath := C.CString(sealedSectorPath)
	defer C.free(unsafe.Pointer(cSealedSectorPath))

	cUnsealOutputPath := C.CString(unsealOutputPath)
	defer C.free(unsafe.Pointer(cUnsealOutputPath))

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

	ticketCBytes := C.CBytes(ticket[:])
	defer C.free(ticketCBytes)

	commDCBytes := C.CBytes(commD[:])
	defer C.free(commDCBytes)

	resPtr := C.sector_builder_ffi_reexported_unseal(
		cSectorClass(sectorSize, poRepProofPartitions),
1152
		cCacheDirPath,
1153
1154
1155
		cSealedSectorPath,
		cUnsealOutputPath,
		C.uint64_t(sectorID),
1156
1157
		(*[32]C.uint8_t)(proverIDCBytes),
		(*[32]C.uint8_t)(ticketCBytes),
1158
1159
1160
1161
1162
1163
1164
		(*[CommitmentBytesLen]C.uint8_t)(commDCBytes),
	)
	defer C.sector_builder_ffi_reexported_destroy_unseal_response(resPtr)

	if resPtr.status_code != 0 {
		return errors.New(C.GoString(resPtr.error_msg))
	}
1165

1166
	return nil
1167
}
1168

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
// StandaloneGenerateCandidates
func StandaloneGenerateCandidates(
	sectorSize uint64,
	proverID [32]byte,
	randomness [32]byte,
	challengeCount uint64,
	privateSectorInfo SortedPrivateSectorInfo,
) ([]Candidate, error) {
	defer elapsed("StandaloneGenerateCandidates")()

	randomessCBytes := C.CBytes(randomness[:])
	defer C.free(randomessCBytes)

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

	replicasPtr, replicasSize := cPrivateReplicaInfos(privateSectorInfo.Values())
	defer C.free(unsafe.Pointer(replicasPtr))

	resPtr := C.sector_builder_ffi_reexported_generate_candidates(
		C.uint64_t(sectorSize),
		(*[32]C.uint8_t)(randomessCBytes),
		C.uint64_t(challengeCount),
		replicasPtr,
		replicasSize,
		(*[32]C.uint8_t)(proverIDCBytes),
	)
	defer C.sector_builder_ffi_reexported_destroy_generate_candidates_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

	return goCandidates(resPtr.candidates_ptr, resPtr.candidates_len)
}

// StandaloneGeneratePoSt
func StandaloneGeneratePoSt(
	sectorSize uint64,
	proverID [32]byte,
	privateSectorInfo SortedPrivateSectorInfo,
	randomness [32]byte,
	winners []Candidate,
) ([]byte, error) {
	defer elapsed("StandaloneGeneratePoSt")()

	replicasPtr, replicasSize := cPrivateReplicaInfos(privateSectorInfo.Values())
	defer C.free(unsafe.Pointer(replicasPtr))

	winnersPtr, winnersSize := cCandidates(winners)
	defer C.free(unsafe.Pointer(winnersPtr))

	proverIDCBytes := C.CBytes(proverID[:])
	defer C.free(proverIDCBytes)

	resPtr := C.sector_builder_ffi_reexported_generate_post(
		C.uint64_t(sectorSize),
		(*[32]C.uint8_t)(unsafe.Pointer(&(randomness)[0])),
		replicasPtr,
		replicasSize,
		winnersPtr,
		winnersSize,
		(*[32]C.uint8_t)(proverIDCBytes),
	)
	defer C.sector_builder_ffi_reexported_destroy_generate_post_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

	return goBytes(resPtr.flattened_proofs_ptr, resPtr.flattened_proofs_len), nil
}

1242
1243
1244
1245
1246
1247
1248
1249
func getAllSealedSectors(sectorBuilderPtr unsafe.Pointer, performHealthchecks bool) ([]SealedSectorMetadata, error) {
	resPtr := C.sector_builder_ffi_get_sealed_sectors((*C.sector_builder_ffi_SectorBuilder)(sectorBuilderPtr), C.bool(performHealthchecks))
	defer C.sector_builder_ffi_destroy_get_sealed_sectors_response(resPtr)

	if resPtr.status_code != 0 {
		return nil, errors.New(C.GoString(resPtr.error_msg))
	}

1250
	meta, err := goSealedSectorMetadata(resPtr.meta_ptr, resPtr.meta_len)
1251
1252
1253
1254
1255
1256
	if err != nil {
		return nil, err
	}

	return meta, nil
}