lotus/lib/sectorbuilder/sectorbuilder.go

528 lines
14 KiB
Go
Raw Normal View History

2019-07-27 00:45:27 +00:00
package sectorbuilder
import (
2019-11-12 19:54:25 +00:00
"context"
"fmt"
"io"
"os"
2019-11-30 23:17:50 +00:00
"path/filepath"
"strconv"
"sync"
sectorbuilder "github.com/filecoin-project/filecoin-ffi"
"github.com/ipfs/go-datastore"
logging "github.com/ipfs/go-log"
2019-11-12 19:54:25 +00:00
"go.opencensus.io/trace"
2019-11-04 17:36:29 +00:00
"golang.org/x/xerrors"
2019-08-06 22:04:21 +00:00
2019-11-25 16:16:18 +00:00
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/address"
"github.com/filecoin-project/lotus/node/modules/dtypes"
2019-07-27 00:45:27 +00:00
)
2019-11-04 17:36:29 +00:00
const PoStReservedWorkers = 1
2019-11-07 16:39:27 +00:00
const PoRepProofPartitions = 2
2019-11-04 17:36:29 +00:00
2019-12-01 04:02:52 +00:00
var lastSectorIdKey = datastore.NewKey("/sectorbuilder/last")
var log = logging.Logger("sectorbuilder")
2019-11-25 04:45:13 +00:00
type SortedPublicSectorInfo = sectorbuilder.SortedPublicSectorInfo
type SortedPrivateSectorInfo = sectorbuilder.SortedPrivateSectorInfo
2019-09-18 03:32:52 +00:00
2019-10-27 08:56:53 +00:00
type SealTicket = sectorbuilder.SealTicket
2019-10-30 18:10:29 +00:00
type SealSeed = sectorbuilder.SealSeed
type SealPreCommitOutput = sectorbuilder.SealPreCommitOutput
2019-10-30 18:10:29 +00:00
type SealCommitOutput = sectorbuilder.SealCommitOutput
type PublicPieceInfo = sectorbuilder.PublicPieceInfo
2019-10-27 08:56:53 +00:00
2019-11-07 16:39:27 +00:00
type RawSealPreCommitOutput = sectorbuilder.RawSealPreCommitOutput
2019-11-21 22:21:45 +00:00
type EPostCandidate = sectorbuilder.Candidate
2019-07-27 00:45:27 +00:00
const CommLen = sectorbuilder.CommitmentBytesLen
type SectorBuilder struct {
ds dtypes.MetadataDS
idLk sync.Mutex
ssize uint64
lastID uint64
2019-11-04 17:36:29 +00:00
Miner address.Address
2019-12-01 17:58:31 +00:00
stagedDir string
sealedDir string
cacheDir string
unsealedDir string
unsealLk sync.Mutex
2019-11-07 16:39:27 +00:00
2019-11-04 17:36:29 +00:00
rateLimit chan struct{}
2019-07-27 00:45:27 +00:00
}
type Config struct {
SectorSize uint64
Miner address.Address
WorkerThreads uint8
CacheDir string
2019-07-27 00:45:27 +00:00
SealedDir string
StagedDir string
2019-12-01 17:58:31 +00:00
UnsealedDir string
2019-07-27 00:45:27 +00:00
}
func New(cfg *Config, ds dtypes.MetadataDS) (*SectorBuilder, error) {
2019-11-04 17:36:29 +00:00
if cfg.WorkerThreads <= PoStReservedWorkers {
2019-11-05 14:03:59 +00:00
return nil, xerrors.Errorf("minimum worker threads is %d, specified %d", PoStReservedWorkers+1, cfg.WorkerThreads)
2019-11-04 17:36:29 +00:00
}
2019-12-01 17:58:31 +00:00
for _, dir := range []string{cfg.StagedDir, cfg.SealedDir, cfg.CacheDir, cfg.UnsealedDir} {
if err := os.Mkdir(dir, 0755); err != nil {
if os.IsExist(err) {
continue
}
return nil, err
}
}
var lastUsedID uint64
2019-12-01 04:02:52 +00:00
b, err := ds.Get(lastSectorIdKey)
switch err {
case nil:
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return nil, err
}
lastUsedID = uint64(i)
case datastore.ErrNotFound:
default:
return nil, err
}
sb := &SectorBuilder{
ds: ds,
ssize: cfg.SectorSize,
lastID: lastUsedID,
2019-11-06 23:09:48 +00:00
stagedDir: cfg.StagedDir,
sealedDir: cfg.SealedDir,
cacheDir: cfg.CacheDir,
unsealedDir: cfg.UnsealedDir,
2019-11-07 16:39:27 +00:00
2019-11-05 18:40:51 +00:00
Miner: cfg.Miner,
2019-11-05 14:03:59 +00:00
rateLimit: make(chan struct{}, cfg.WorkerThreads-PoStReservedWorkers),
}
return sb, nil
2019-07-27 00:45:27 +00:00
}
func (sb *SectorBuilder) RateLimit() func() {
2019-11-04 17:36:29 +00:00
if cap(sb.rateLimit) == len(sb.rateLimit) {
log.Warn("rate-limiting sectorbuilder call")
}
sb.rateLimit <- struct{}{}
return func() {
<-sb.rateLimit
}
}
2019-11-08 18:15:13 +00:00
func (sb *SectorBuilder) WorkerStats() (free, reserved, total int) {
return cap(sb.rateLimit) - len(sb.rateLimit), PoStReservedWorkers, cap(sb.rateLimit) + PoStReservedWorkers
}
2019-10-21 11:58:41 +00:00
func addressToProverID(a address.Address) [32]byte {
var proverId [32]byte
copy(proverId[:], a.Payload())
return proverId
}
2019-11-07 16:39:27 +00:00
func (sb *SectorBuilder) AcquireSectorId() (uint64, error) {
sb.idLk.Lock()
defer sb.idLk.Unlock()
sb.lastID++
id := sb.lastID
2019-12-01 04:02:52 +00:00
err := sb.ds.Put(lastSectorIdKey, []byte(fmt.Sprint(id)))
if err != nil {
return 0, err
}
return id, nil
2019-11-07 16:39:27 +00:00
}
func (sb *SectorBuilder) AddPiece(pieceSize uint64, sectorId uint64, file io.Reader, existingPieceSizes []uint64) (PublicPieceInfo, error) {
ret := sb.RateLimit()
defer ret()
2019-09-23 10:50:28 +00:00
f, werr, err := toReadableFile(file, int64(pieceSize))
if err != nil {
2019-11-07 16:39:27 +00:00
return PublicPieceInfo{}, err
2019-09-23 10:50:28 +00:00
}
2019-11-07 16:39:27 +00:00
stagedFile, err := sb.stagedSectorFile(sectorId)
2019-09-23 10:50:28 +00:00
if err != nil {
2019-11-07 16:39:27 +00:00
return PublicPieceInfo{}, err
}
_, _, commP, err := sectorbuilder.WriteWithAlignment(f, pieceSize, stagedFile, existingPieceSizes)
2019-11-07 16:39:27 +00:00
if err != nil {
return PublicPieceInfo{}, err
}
if err := stagedFile.Close(); err != nil {
return PublicPieceInfo{}, err
}
if err := f.Close(); err != nil {
return PublicPieceInfo{}, err
2019-09-23 10:50:28 +00:00
}
2019-11-07 16:39:27 +00:00
return PublicPieceInfo{
Size: pieceSize,
CommP: commP,
}, werr()
2019-07-27 00:45:27 +00:00
}
2019-12-01 17:58:31 +00:00
func (sb *SectorBuilder) ReadPieceFromSealedSector(sectorID uint64, offset uint64, size uint64, ticket []byte, commD []byte) (io.ReadCloser, error) {
ret := sb.RateLimit() // TODO: check perf, consider remote unseal worker
2019-11-04 17:36:29 +00:00
defer ret()
2019-12-01 17:58:31 +00:00
sb.unsealLk.Lock() // TODO: allow unsealing unrelated sectors in parallel
defer sb.unsealLk.Unlock()
2019-12-01 17:58:31 +00:00
cacheDir, err := sb.sectorCacheDir(sectorID)
if err != nil {
return nil, err
}
sealedPath, err := sb.sealedSectorPath(sectorID)
if err != nil {
return nil, err
}
unsealedPath := sb.unsealedSectorPath(sectorID)
// 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))
f, err := os.OpenFile(unsealedPath, os.O_RDONLY, 0644)
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 = sectorbuilder.Unseal(sb.ssize,
PoRepProofPartitions,
cacheDir,
sealedPath,
unsealedPath,
sectorID,
addressToProverID(sb.Miner),
tkt,
commd)
if err != nil {
return nil, xerrors.Errorf("unseal failed: %w", err)
}
f, err = os.OpenFile(unsealedPath, os.O_RDONLY, 0644)
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
2019-07-27 00:45:27 +00:00
}
2019-11-07 16:39:27 +00:00
func (sb *SectorBuilder) SealPreCommit(sectorID uint64, ticket SealTicket, pieces []PublicPieceInfo) (RawSealPreCommitOutput, error) {
ret := sb.RateLimit()
2019-11-04 17:36:29 +00:00
defer ret()
2019-11-07 16:39:27 +00:00
cacheDir, err := sb.sectorCacheDir(sectorID)
if err != nil {
return RawSealPreCommitOutput{}, err
}
2019-11-07 16:39:27 +00:00
sealedPath, err := sb.sealedSectorPath(sectorID)
if err != nil {
return RawSealPreCommitOutput{}, err
}
2019-11-04 17:36:29 +00:00
2019-11-07 19:54:24 +00:00
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))
2019-11-07 19:54:24 +00:00
}
stagedPath := sb.stagedSectorPath(sectorID)
rspco, err := sectorbuilder.SealPreCommit(
2019-11-07 16:39:27 +00:00
sb.ssize,
PoRepProofPartitions,
cacheDir,
2019-11-07 19:54:24 +00:00
stagedPath,
2019-11-07 16:39:27 +00:00
sealedPath,
sectorID,
addressToProverID(sb.Miner),
ticket.TicketBytes,
pieces,
)
2019-11-07 19:54:24 +00:00
if err != nil {
return RawSealPreCommitOutput{}, xerrors.Errorf("presealing sector %d (%s): %w", sectorID, stagedPath, err)
}
return rspco, nil
2019-07-27 00:45:27 +00:00
}
func (sb *SectorBuilder) SealCommit(sectorID uint64, ticket SealTicket, seed SealSeed, pieces []PublicPieceInfo, rspco RawSealPreCommitOutput) (proof []byte, err error) {
ret := sb.RateLimit()
2019-11-04 17:36:29 +00:00
defer ret()
2019-11-07 16:39:27 +00:00
cacheDir, err := sb.sectorCacheDir(sectorID)
if err != nil {
return nil, err
}
proof, err = sectorbuilder.SealCommit(
2019-11-07 16:39:27 +00:00
sb.ssize,
PoRepProofPartitions,
cacheDir,
sectorID,
addressToProverID(sb.Miner),
ticket.TicketBytes,
seed.TicketBytes,
pieces,
rspco,
)
if err != nil {
return nil, xerrors.Errorf("SealCommit: %w", err)
2019-11-07 16:39:27 +00:00
}
return proof, nil
}
2019-11-06 23:09:48 +00:00
func (sb *SectorBuilder) SectorSize() uint64 {
return sb.ssize
}
2019-11-25 04:45:13 +00:00
func (sb *SectorBuilder) ComputeElectionPoSt(sectorInfo SortedPublicSectorInfo, challengeSeed []byte, winners []EPostCandidate) ([]byte, error) {
2019-11-21 22:21:45 +00:00
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)
2019-11-26 02:43:43 +00:00
privsects, err := sb.pubSectorToPriv(sectorInfo)
if err != nil {
return nil, err
}
2019-11-25 16:16:18 +00:00
2019-11-26 02:43:43 +00:00
proverID := addressToProverID(sb.Miner)
2019-11-30 23:17:50 +00:00
2019-11-27 22:34:48 +00:00
return sectorbuilder.GeneratePoSt(sb.ssize, proverID, privsects, cseed, winners)
2019-11-21 22:21:45 +00:00
}
2019-11-25 04:45:13 +00:00
func (sb *SectorBuilder) GenerateEPostCandidates(sectorInfo SortedPublicSectorInfo, challengeSeed [CommLen]byte, faults []uint64) ([]EPostCandidate, error) {
privsectors, err := sb.pubSectorToPriv(sectorInfo)
if err != nil {
return nil, err
}
2019-11-25 16:16:18 +00:00
challengeCount := ElectionPostChallengeCount(uint64(len(sectorInfo.Values())))
2019-11-25 16:16:18 +00:00
2019-11-25 04:45:13 +00:00
proverID := addressToProverID(sb.Miner)
2019-11-27 22:34:48 +00:00
return sectorbuilder.GenerateCandidates(sb.ssize, proverID, challengeSeed, challengeCount, privsectors)
2019-11-25 04:45:13 +00:00
}
func (sb *SectorBuilder) pubSectorToPriv(sectorInfo SortedPublicSectorInfo) (SortedPrivateSectorInfo, error) {
var out []sectorbuilder.PrivateSectorInfo
2019-11-25 04:45:13 +00:00
for _, s := range sectorInfo.Values() {
cachePath, err := sb.sectorCacheDir(s.SectorID)
if err != nil {
return SortedPrivateSectorInfo{}, xerrors.Errorf("getting cache path for sector %d: %w", s.SectorID, err)
}
sealedPath, err := sb.sealedSectorPath(s.SectorID)
if err != nil {
return SortedPrivateSectorInfo{}, xerrors.Errorf("getting sealed path for sector %d: %w", s.SectorID, err)
}
out = append(out, sectorbuilder.PrivateSectorInfo{
2019-11-25 04:45:13 +00:00
SectorID: s.SectorID,
CommR: s.CommR,
CacheDirPath: cachePath,
SealedSectorPath: sealedPath,
})
}
return NewSortedPrivateSectorInfo(out), nil
2019-11-21 22:21:45 +00:00
}
func (sb *SectorBuilder) GenerateFallbackPoSt(sectorInfo SortedPublicSectorInfo, challengeSeed [CommLen]byte, faults []uint64) ([]EPostCandidate, []byte, error) {
privsectors, err := sb.pubSectorToPriv(sectorInfo)
if err != nil {
return nil, nil, err
}
2019-11-28 12:46:56 +00:00
challengeCount := fallbackPostChallengeCount(uint64(len(sectorInfo.Values())))
proverID := addressToProverID(sb.Miner)
candidates, err := sectorbuilder.GenerateCandidates(sb.ssize, proverID, challengeSeed, challengeCount, privsectors)
if err != nil {
return nil, nil, err
}
proof, err := sectorbuilder.GeneratePoSt(sb.ssize, proverID, privsectors, challengeSeed, candidates)
return candidates, proof, err
2019-11-21 22:21:45 +00:00
}
var UserBytesForSectorSize = sectorbuilder.GetMaxUserBytesPerStagedSector
func VerifySeal(sectorSize uint64, commR, commD []byte, proverID address.Address, ticket []byte, seed []byte, sectorID uint64, proof []byte) (bool, error) {
2019-10-30 18:10:29 +00:00
var commRa, commDa, ticketa, seeda [32]byte
copy(commRa[:], commR)
copy(commDa[:], commD)
2019-10-21 11:58:41 +00:00
copy(ticketa[:], ticket)
2019-10-30 18:10:29 +00:00
copy(seeda[:], seed)
proverIDa := addressToProverID(proverID)
2019-11-27 22:34:48 +00:00
return sectorbuilder.VerifySeal(sectorSize, commRa, commDa, proverIDa, ticketa, seeda, sectorID, proof)
}
func NewSortedPrivateSectorInfo(sectors []sectorbuilder.PrivateSectorInfo) SortedPrivateSectorInfo {
return sectorbuilder.NewSortedPrivateSectorInfo(sectors...)
2019-11-25 04:45:13 +00:00
}
func NewSortedPublicSectorInfo(sectors []sectorbuilder.PublicSectorInfo) SortedPublicSectorInfo {
return sectorbuilder.NewSortedPublicSectorInfo(sectors...)
}
2019-11-28 12:46:56 +00:00
func VerifyElectionPost(ctx context.Context, sectorSize uint64, sectorInfo SortedPublicSectorInfo, challengeSeed []byte, proof []byte, candidates []EPostCandidate, proverID address.Address) (bool, error) {
challengeCount := ElectionPostChallengeCount(uint64(len(sectorInfo.Values())))
2019-11-28 12:46:56 +00:00
return verifyPost(ctx, sectorSize, sectorInfo, challengeCount, challengeSeed, proof, candidates, proverID)
}
func VerifyFallbackPost(ctx context.Context, sectorSize uint64, sectorInfo SortedPublicSectorInfo, challengeSeed []byte, proof []byte, candidates []EPostCandidate, proverID address.Address) (bool, error) {
challengeCount := fallbackPostChallengeCount(uint64(len(sectorInfo.Values())))
return verifyPost(ctx, sectorSize, sectorInfo, challengeCount, challengeSeed, proof, candidates, proverID)
}
func verifyPost(ctx context.Context, sectorSize uint64, sectorInfo SortedPublicSectorInfo, challengeCount uint64, challengeSeed []byte, proof []byte, candidates []EPostCandidate, proverID address.Address) (bool, error) {
if challengeCount != uint64(len(candidates)) {
log.Warnf("verifyPost with wrong candidate count: expected %d, got %d", challengeCount, len(candidates))
return false, nil // user input, dont't error
}
2019-11-21 22:21:45 +00:00
var challengeSeeda [CommLen]byte
copy(challengeSeeda[:], challengeSeed)
2019-11-12 19:54:25 +00:00
_, span := trace.StartSpan(ctx, "VerifyPoSt")
defer span.End()
2019-11-21 22:21:45 +00:00
prover := addressToProverID(proverID)
2019-11-28 12:46:56 +00:00
return sectorbuilder.VerifyPoSt(sectorSize, sectorInfo, challengeSeeda, challengeCount, proof, candidates, prover)
2019-07-27 00:45:27 +00:00
}
2019-09-23 10:50:28 +00:00
func GeneratePieceCommitment(piece io.Reader, pieceSize uint64) (commP [CommLen]byte, err error) {
f, werr, err := toReadableFile(piece, int64(pieceSize))
if err != nil {
return [32]byte{}, err
}
commP, err = sectorbuilder.GeneratePieceCommitmentFromFile(f, pieceSize)
if err != nil {
return [32]byte{}, err
}
return commP, werr()
}
func GenerateDataCommitment(ssize uint64, pieces []PublicPieceInfo) ([CommLen]byte, error) {
2019-11-27 22:34:48 +00:00
return sectorbuilder.GenerateDataCommitment(ssize, pieces)
}
2019-11-25 16:16:18 +00:00
func ElectionPostChallengeCount(sectors uint64) uint64 {
2019-11-25 16:16:18 +00:00
// ceil(sectors / build.SectorChallengeRatioDiv)
return (sectors + build.SectorChallengeRatioDiv - 1) / build.SectorChallengeRatioDiv
}
2019-11-28 12:46:56 +00:00
func fallbackPostChallengeCount(sectors uint64) uint64 {
challengeCount := ElectionPostChallengeCount(sectors)
2019-11-28 12:46:56 +00:00
if challengeCount > build.MaxFallbackPostChallengeCount {
return build.MaxFallbackPostChallengeCount
}
return challengeCount
}
2019-11-30 23:17:50 +00:00
func (sb *SectorBuilder) ImportFrom(osb *SectorBuilder) error {
if err := moveAllFiles(osb.cacheDir, sb.cacheDir); err != nil {
return err
}
if err := moveAllFiles(osb.sealedDir, sb.sealedDir); err != nil {
return err
}
if err := moveAllFiles(osb.stagedDir, sb.stagedDir); err != nil {
return err
}
2019-12-01 04:02:52 +00:00
val, err := osb.ds.Get(lastSectorIdKey)
2019-11-30 23:17:50 +00:00
if err != nil {
return err
}
2019-12-01 04:02:52 +00:00
if err := sb.ds.Put(lastSectorIdKey, val); err != nil {
2019-11-30 23:17:50 +00:00
return err
}
sb.lastID = osb.lastID
return nil
}
func moveAllFiles(from, to string) error {
dir, err := os.Open(from)
if err != nil {
return err
}
names, err := dir.Readdirnames(0)
if err != nil {
return xerrors.Errorf("failed to list items in dir: %w", err)
}
for _, n := range names {
if err := os.Rename(filepath.Join(from, n), filepath.Join(to, n)); err != nil {
return xerrors.Errorf("moving file failed: %w", err)
}
}
return nil
}