diff --git a/.circleci/config.yml b/.circleci/config.yml index 46aa77fe..d07bcfb2 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -67,7 +67,6 @@ jobs: - run: cd rust && cargo install cargo-lipo - build_project - compile_tests - - ensure_generated_cgo_up_to_date publish_linux_staticlib: executor: golang steps: @@ -305,13 +304,6 @@ commands: name: Build project without CGO command: env CGO_ENABLED=0 go build . - ensure_generated_cgo_up_to_date: - steps: - - run: - name: Generate CGO bindings (using forked c-for-go) and compare with what's tracked by Git - command: | - make cgo-gen - git diff --exit-code ./generated/ run_tests: parameters: run_leak_detector: diff --git a/Makefile b/Makefile index ad52e244..aad6a4fb 100644 --- a/Makefile +++ b/Makefile @@ -34,10 +34,6 @@ cgo-leakdetect: runner valgrind --leak-check=full --show-leak-kinds=definite ./runner .PHONY: cgo-leakdetect -cgo-gen: $(DEPS) - go run github.com/xlab/c-for-go --nostamp filcrypto.yml -.PHONY: cgo-gen - runner: $(DEPS) rm -f ./runner go build -o ./runner ./cgoleakdetect/ diff --git a/README.md b/README.md index 243ead67..6276a230 100644 --- a/README.md +++ b/README.md @@ -82,13 +82,6 @@ $ make -C extern/filecoin-ffi $ go mod edit -replace=github.com/filecoin-project/filecoin-ffi=./extern/filecoin-ffi ``` -## Updating CGO Bindings - -The CGO bindings are generated using [c-for-go](https://github.com/xlab/c-for-go) -and committed to Git. To generate bindings yourself, install the c-for-go -binary, ensure that it's on your path, and then run `make cgo-gen`. CI builds -will fail if generated CGO diverges from what's checked into Git. - ## Updating the Changelog The `mkreleaselog` script (in the project root) can be used to generate a good diff --git a/bls.go b/bls.go index e639a1b5..6d680935 100644 --- a/bls.go +++ b/bls.go @@ -9,20 +9,16 @@ package ffi // #include "./filcrypto.h" import "C" import ( - "github.com/filecoin-project/filecoin-ffi/generated" + "github.com/filecoin-project/filecoin-ffi/cgo" ) // Hash computes the digest of a message func Hash(message Message) Digest { - resp := generated.FilHash(message, uint(len(message))) - resp.Deref() - resp.Digest.Deref() - - defer generated.FilDestroyHashResponse(resp) - - var out Digest - copy(out[:], resp.Digest.Inner[:]) - return out + digest := cgo.Hash(cgo.AsSliceRefUint8(message)) + if digest == nil { + return Digest{} + } + return *digest } // Verify verifies that a signature is the aggregated signature of digests - pubkeys @@ -38,9 +34,11 @@ func Verify(signature *Signature, digests []Digest, publicKeys []PublicKey) bool copy(flattenedPublicKeys[(PublicKeyBytes*idx):(PublicKeyBytes*(1+idx))], publicKey[:]) } - isValid := generated.FilVerify(signature[:], flattenedDigests, uint(len(flattenedDigests)), flattenedPublicKeys, uint(len(flattenedPublicKeys))) - - return isValid > 0 + return cgo.Verify( + cgo.AsSliceRefUint8(signature[:]), + cgo.AsSliceRefUint8(flattenedDigests), + cgo.AsSliceRefUint8(flattenedPublicKeys), + ) } // HashVerify verifies that a signature is the aggregated signature of hashed messages. @@ -57,9 +55,12 @@ func HashVerify(signature *Signature, messages []Message, publicKeys []PublicKey copy(flattenedPublicKeys[(PublicKeyBytes*idx):(PublicKeyBytes*(1+idx))], publicKey[:]) } - isValid := generated.FilHashVerify(signature[:], flattenedMessages, uint(len(flattenedMessages)), messagesSizes, uint(len(messagesSizes)), flattenedPublicKeys, uint(len(flattenedPublicKeys))) - - return isValid > 0 + return cgo.HashVerify( + cgo.AsSliceRefUint8(signature[:]), + cgo.AsSliceRefUint8(flattenedMessages), + cgo.AsSliceRefUint(messagesSizes), + cgo.AsSliceRefUint8(flattenedPublicKeys), + ) } // Aggregate aggregates signatures together into a new signature. If the @@ -72,84 +73,43 @@ func Aggregate(signatures []Signature) *Signature { copy(flattenedSignatures[(SignatureBytes*idx):(SignatureBytes*(1+idx))], sig[:]) } - resp := generated.FilAggregate(flattenedSignatures, uint(len(flattenedSignatures))) - if resp == nil { - return nil - } - - defer generated.FilDestroyAggregateResponse(resp) - - resp.Deref() - resp.Signature.Deref() - - var out Signature - copy(out[:], resp.Signature.Inner[:]) - return &out + return cgo.Aggregate(cgo.AsSliceRefUint8(flattenedSignatures)) } // PrivateKeyGenerate generates a private key func PrivateKeyGenerate() PrivateKey { - resp := generated.FilPrivateKeyGenerate() - resp.Deref() - resp.PrivateKey.Deref() - defer generated.FilDestroyPrivateKeyGenerateResponse(resp) - - var out PrivateKey - copy(out[:], resp.PrivateKey.Inner[:]) - return out + key := cgo.PrivateKeyGenerate() + if key == nil { + return PrivateKey{} + } + return *key } -// PrivateKeyGenerate generates a private key in a predictable manner +// PrivateKeyGenerate generates a private key in a predictable manner. func PrivateKeyGenerateWithSeed(seed PrivateKeyGenSeed) PrivateKey { - var ary generated.Fil32ByteArray - copy(ary.Inner[:], seed[:]) - - resp := generated.FilPrivateKeyGenerateWithSeed(ary) - resp.Deref() - resp.PrivateKey.Deref() - defer generated.FilDestroyPrivateKeyGenerateResponse(resp) - - var out PrivateKey - copy(out[:], resp.PrivateKey.Inner[:]) - return out + ary := cgo.AsByteArray32(seed[:]) + key := cgo.PrivateKeyGenerateWithSeed(&ary) + if key == nil { + return PrivateKey{} + } + return *key } // PrivateKeySign signs a message func PrivateKeySign(privateKey PrivateKey, message Message) *Signature { - resp := generated.FilPrivateKeySign(privateKey[:], message, uint(len(message))) - resp.Deref() - resp.Signature.Deref() - - defer generated.FilDestroyPrivateKeySignResponse(resp) - - var signature Signature - copy(signature[:], resp.Signature.Inner[:]) - return &signature + return cgo.PrivateKeySign(cgo.AsSliceRefUint8(privateKey[:]), cgo.AsSliceRefUint8(message)) } // PrivateKeyPublicKey gets the public key for a private key -func PrivateKeyPublicKey(privateKey PrivateKey) PublicKey { - resp := generated.FilPrivateKeyPublicKey(privateKey[:]) - resp.Deref() - resp.PublicKey.Deref() - - defer generated.FilDestroyPrivateKeyPublicKeyResponse(resp) - - var publicKey PublicKey - copy(publicKey[:], resp.PublicKey.Inner[:]) - return publicKey +func PrivateKeyPublicKey(privateKey PrivateKey) *PublicKey { + return cgo.PrivateKeyPublicKey(cgo.AsSliceRefUint8(privateKey[:])) } // CreateZeroSignature creates a zero signature, used as placeholder in filecoin. func CreateZeroSignature() Signature { - resp := generated.FilCreateZeroSignature() - resp.Deref() - resp.Signature.Deref() - - defer generated.FilDestroyZeroSignatureResponse(resp) - - var sig Signature - copy(sig[:], resp.Signature.Inner[:]) - - return sig + signature := cgo.CreateZeroSignature() + if signature == nil { + return Signature{} + } + return *signature } diff --git a/bls_test.go b/bls_test.go index 21d1c2b3..c013803a 100644 --- a/bls_test.go +++ b/bls_test.go @@ -51,30 +51,30 @@ func TestBLSSigningAndVerification(t *testing.T) { aggregateSign := Aggregate([]Signature{*fooSignature, *barSignature}) // assert the foo message was signed with the foo key - assert.True(t, Verify(fooSignature, []Digest{fooDigest}, []PublicKey{fooPublicKey})) + assert.True(t, Verify(fooSignature, []Digest{fooDigest}, []PublicKey{*fooPublicKey})) // assert the bar message was signed with the bar key - assert.True(t, Verify(barSignature, []Digest{barDigest}, []PublicKey{barPublicKey})) + assert.True(t, Verify(barSignature, []Digest{barDigest}, []PublicKey{*barPublicKey})) // assert the foo message was signed with the foo key - assert.True(t, HashVerify(fooSignature, []Message{fooMessage}, []PublicKey{fooPublicKey})) + assert.True(t, HashVerify(fooSignature, []Message{fooMessage}, []PublicKey{*fooPublicKey})) // assert the bar message was signed with the bar key - assert.True(t, HashVerify(barSignature, []Message{barMessage}, []PublicKey{barPublicKey})) + assert.True(t, HashVerify(barSignature, []Message{barMessage}, []PublicKey{*barPublicKey})) // assert the foo message was not signed by the bar key - assert.False(t, Verify(fooSignature, []Digest{fooDigest}, []PublicKey{barPublicKey})) + assert.False(t, Verify(fooSignature, []Digest{fooDigest}, []PublicKey{*barPublicKey})) // assert the bar/foo message was not signed by the foo/bar key - assert.False(t, Verify(barSignature, []Digest{barDigest}, []PublicKey{fooPublicKey})) - assert.False(t, Verify(barSignature, []Digest{fooDigest}, []PublicKey{barPublicKey})) - assert.False(t, Verify(fooSignature, []Digest{barDigest}, []PublicKey{fooPublicKey})) + assert.False(t, Verify(barSignature, []Digest{barDigest}, []PublicKey{*fooPublicKey})) + assert.False(t, Verify(barSignature, []Digest{fooDigest}, []PublicKey{*barPublicKey})) + assert.False(t, Verify(fooSignature, []Digest{barDigest}, []PublicKey{*fooPublicKey})) //assert the foo and bar message was signed with the foo and bar key - assert.True(t, HashVerify(aggregateSign, []Message{fooMessage, barMessage}, []PublicKey{fooPublicKey, barPublicKey})) + assert.True(t, HashVerify(aggregateSign, []Message{fooMessage, barMessage}, []PublicKey{*fooPublicKey, *barPublicKey})) //assert the bar and foo message was not signed by the foo and bar key - assert.False(t, HashVerify(aggregateSign, []Message{fooMessage, barMessage}, []PublicKey{fooPublicKey})) + assert.False(t, HashVerify(aggregateSign, []Message{fooMessage, barMessage}, []PublicKey{*fooPublicKey})) } func BenchmarkBLSVerify(b *testing.B) { @@ -90,7 +90,7 @@ func BenchmarkBLSVerify(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - if !Verify(sig, []Digest{digest}, []PublicKey{pubk}) { + if !Verify(sig, []Digest{digest}, []PublicKey{*pubk}) { b.Fatal("failed to verify") } } @@ -132,7 +132,7 @@ func benchmarkBLSVerifyBatchSize(size int) func(b *testing.B) { sig := PrivateKeySign(priv, msg) sigs = append(sigs, *sig) pubk := PrivateKeyPublicKey(priv) - pubks = append(pubks, pubk) + pubks = append(pubks, *pubk) } t := time.Now() @@ -161,7 +161,7 @@ func BenchmarkBLSHashAndVerify(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { digest := Hash(msg) - if !Verify(sig, []Digest{digest}, []PublicKey{pubk}) { + if !Verify(sig, []Digest{digest}, []PublicKey{*pubk}) { b.Fatal("failed to verify") } } @@ -179,7 +179,7 @@ func BenchmarkBLSHashVerify(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - if !HashVerify(sig, []Message{msg}, []PublicKey{pubk}) { + if !HashVerify(sig, []Message{msg}, []PublicKey{*pubk}) { b.Fatal("failed to verify") } } diff --git a/build.sh b/build.sh index 5a4fcd00..d4de9a52 100755 --- a/build.sh +++ b/build.sh @@ -9,9 +9,6 @@ rustup target add x86_64-apple-darwin --toolchain $(cat rust-toolchain) rustup target add aarch64-apple-darwin --toolchain $(cat rust-toolchain) cargo update -p "filecoin-proofs-api" cargo install cargo-lipo -cargo install cbindgen -cbindgen --clean --config cbindgen.toml --crate filcrypto --output ../include/filcrypto.h cd .. FFI_BUILD_FROM_SOURCE=1 make -make cgo-gen go mod tidy diff --git a/cgo/bls.go b/cgo/bls.go new file mode 100644 index 00000000..e91021e9 --- /dev/null +++ b/cgo/bls.go @@ -0,0 +1,61 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" + +func Hash(message SliceRefUint8) *[96]byte { + resp := C.hash(message) + defer resp.destroy() + return resp.copyAsArray() +} + +func Aggregate(flattenedSignatures SliceRefUint8) *[96]byte { + resp := C.aggregate(flattenedSignatures) + defer resp.destroy() + return resp.copyAsArray() +} + +func Verify(signature SliceRefUint8, flattenedDigests SliceRefUint8, flattenedPublicKeys SliceRefUint8) bool { + resp := C.verify(signature, flattenedDigests, flattenedPublicKeys) + return bool(resp) +} + +func HashVerify(signature SliceRefUint8, flattenedMessages SliceRefUint8, messageSizes SliceRefUint, flattenedPublicKeys SliceRefUint8) bool { + resp := C.hash_verify(signature, flattenedMessages, messageSizes, flattenedPublicKeys) + return bool(resp) +} + +func PrivateKeyGenerate() *[32]byte { + resp := C.private_key_generate() + defer resp.destroy() + return resp.copyAsArray() +} + +func PrivateKeyGenerateWithSeed(rawSeed *ByteArray32) *[32]byte { + resp := C.private_key_generate_with_seed(rawSeed) + defer resp.destroy() + return resp.copyAsArray() +} + +func PrivateKeySign(rawPrivateKey SliceRefUint8, message SliceRefUint8) *[96]byte { + resp := C.private_key_sign(rawPrivateKey, message) + defer resp.destroy() + return resp.copyAsArray() +} + +func PrivateKeyPublicKey(rawPrivateKey SliceRefUint8) *[48]byte { + resp := C.private_key_public_key(rawPrivateKey) + defer resp.destroy() + return resp.copyAsArray() +} + +func CreateZeroSignature() *[96]byte { + resp := C.create_zero_signature() + defer resp.destroy() + return resp.copyAsArray() +} diff --git a/cgo/const.go b/cgo/const.go new file mode 100644 index 00000000..795be491 --- /dev/null +++ b/cgo/const.go @@ -0,0 +1,54 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" + +const ( + FCPResponseStatusNoError = C.F_C_P_RESPONSE_STATUS_NO_ERROR + FCPResponseStatusUnclassifiedError = C.F_C_P_RESPONSE_STATUS_UNCLASSIFIED_ERROR + FCPResponseStatusCallerError = C.F_C_P_RESPONSE_STATUS_CALLER_ERROR + FCPResponseStatusReceiverError = C.F_C_P_RESPONSE_STATUS_RECEIVER_ERROR +) + +const ( + RegisteredSealProofStackedDrg2KiBV1 = C.REGISTERED_SEAL_PROOF_STACKED_DRG2_KI_B_V1 + RegisteredSealProofStackedDrg8MiBV1 = C.REGISTERED_SEAL_PROOF_STACKED_DRG8_MI_B_V1 + RegisteredSealProofStackedDrg512MiBV1 = C.REGISTERED_SEAL_PROOF_STACKED_DRG512_MI_B_V1 + RegisteredSealProofStackedDrg32GiBV1 = C.REGISTERED_SEAL_PROOF_STACKED_DRG32_GI_B_V1 + RegisteredSealProofStackedDrg64GiBV1 = C.REGISTERED_SEAL_PROOF_STACKED_DRG64_GI_B_V1 + RegisteredSealProofStackedDrg2KiBV11 = C.REGISTERED_SEAL_PROOF_STACKED_DRG2_KI_B_V1_1 + RegisteredSealProofStackedDrg8MiBV11 = C.REGISTERED_SEAL_PROOF_STACKED_DRG8_MI_B_V1_1 + RegisteredSealProofStackedDrg512MiBV11 = C.REGISTERED_SEAL_PROOF_STACKED_DRG512_MI_B_V1_1 + RegisteredSealProofStackedDrg32GiBV11 = C.REGISTERED_SEAL_PROOF_STACKED_DRG32_GI_B_V1_1 + RegisteredSealProofStackedDrg64GiBV11 = C.REGISTERED_SEAL_PROOF_STACKED_DRG64_GI_B_V1_1 +) + +const ( + RegisteredAggregationProofSnarkPackV1 = C.REGISTERED_AGGREGATION_PROOF_SNARK_PACK_V1 +) + +const ( + RegisteredPoStProofStackedDrgWinning2KiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINNING2_KI_B_V1 + RegisteredPoStProofStackedDrgWinning8MiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINNING8_MI_B_V1 + RegisteredPoStProofStackedDrgWinning512MiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINNING512_MI_B_V1 + RegisteredPoStProofStackedDrgWinning32GiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINNING32_GI_B_V1 + RegisteredPoStProofStackedDrgWinning64GiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINNING64_GI_B_V1 + RegisteredPoStProofStackedDrgWindow2KiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINDOW2_KI_B_V1 + RegisteredPoStProofStackedDrgWindow8MiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINDOW8_MI_B_V1 + RegisteredPoStProofStackedDrgWindow512MiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINDOW512_MI_B_V1 + RegisteredPoStProofStackedDrgWindow32GiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINDOW32_GI_B_V1 + RegisteredPoStProofStackedDrgWindow64GiBV1 = C.REGISTERED_PO_ST_PROOF_STACKED_DRG_WINDOW64_GI_B_V1 +) + +const ( + RegisteredUpdateProofStackedDrg2KiBV1 = C.REGISTERED_UPDATE_PROOF_STACKED_DRG2_KI_B_V1 + RegisteredUpdateProofStackedDrg8MiBV1 = C.REGISTERED_UPDATE_PROOF_STACKED_DRG8_MI_B_V1 + RegisteredUpdateProofStackedDrg512MiBV1 = C.REGISTERED_UPDATE_PROOF_STACKED_DRG512_MI_B_V1 + RegisteredUpdateProofStackedDrg32GiBV1 = C.REGISTERED_UPDATE_PROOF_STACKED_DRG32_GI_B_V1 + RegisteredUpdateProofStackedDrg64GiBV1 = C.REGISTERED_UPDATE_PROOF_STACKED_DRG64_GI_B_V1 +) diff --git a/cgo/errors.go b/cgo/errors.go index 40cd0c2a..d7e796c8 100644 --- a/cgo/errors.go +++ b/cgo/errors.go @@ -12,11 +12,11 @@ import ( ) const ( - ErrInvalidHandle = C.ERR_INVALID_HANDLE - ErrNotFound = C.ERR_NOT_FOUND - ErrIO = C.ERR_IO - ErrInvalidArgument = C.ERR_INVALID_ARGUMENT - ErrPanic = C.ERR_PANIC + ErrInvalidHandle = C.FVM_ERROR_INVALID_HANDLE + ErrNotFound = C.FVM_ERROR_NOT_FOUND + ErrIO = C.FVM_ERROR_IO + ErrInvalidArgument = C.FVM_ERROR_INVALID_ARGUMENT + ErrPanic = C.FVM_ERROR_PANIC ) func logPanic(err interface{}) { diff --git a/cgo/fvm.go b/cgo/fvm.go new file mode 100644 index 00000000..8b6cb54f --- /dev/null +++ b/cgo/fvm.go @@ -0,0 +1,62 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" + +func CreateFvmMachine(fvmVersion FvmRegisteredVersion, chainEpoch, baseFeeHi, baseFeeLo, baseCircSupplyHi, baseCircSupplyLo, networkVersion uint64, stateRoot SliceRefUint8, manifestCid SliceRefUint8, tracing bool, blockstoreId, externsId uint64) (*FvmMachine, error) { + resp := C.create_fvm_machine( + fvmVersion, + C.uint64_t(chainEpoch), + C.uint64_t(baseFeeHi), + C.uint64_t(baseFeeLo), + C.uint64_t(baseCircSupplyHi), + C.uint64_t(baseCircSupplyLo), + C.uint64_t(networkVersion), + stateRoot, + manifestCid, + C.bool(tracing), + C.uint64_t(blockstoreId), + C.uint64_t(externsId), + ) + // take out the pointer from the result to ensure it doesn't get freed + executor := resp.value + resp.value = nil + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return nil, err + } + + return executor, nil +} + +func FvmMachineExecuteMessage(executor *FvmMachine, message SliceRefUint8, chainLen, applyKind uint64) (FvmMachineExecuteResponseGo, error) { + resp := C.fvm_machine_execute_message( + executor, + message, + C.uint64_t(chainLen), + C.uint64_t(applyKind), + ) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return FvmMachineExecuteResponseGo{}, err + } + + return resp.value.copy(), nil +} + +func FvmMachineFlush(executor *FvmMachine) ([]byte, error) { + resp := C.fvm_machine_flush(executor) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} diff --git a/cgo/helpers.go b/cgo/helpers.go new file mode 100644 index 00000000..5e16a0e6 --- /dev/null +++ b/cgo/helpers.go @@ -0,0 +1,275 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" +import ( + "errors" + "unsafe" +) + +var ( + emptyUint8 C.uint8_t = 0 + emptyUint64 C.uint64_t = 0 + emptyUint C.size_t = 0 + emptyAggregationInputs C.AggregationInputs_t = C.AggregationInputs_t{} + emptyPublicReplicaInfo C.PublicReplicaInfo_t = C.PublicReplicaInfo_t{} + emptyPrivateReplicaInfo C.PrivateReplicaInfo_t = C.PrivateReplicaInfo_t{} + emptyPoStProof C.PoStProof_t = C.PoStProof_t{} + emptyPublicPieceInfo C.PublicPieceInfo_t = C.PublicPieceInfo_t{} + emptyByteArray32 C.uint8_32_array_t = C.uint8_32_array_t{} + emptySliceBoxedUint8 C.slice_boxed_uint8_t = C.slice_boxed_uint8_t{} +) + +func AsSliceRefUint8(goBytes []byte) SliceRefUint8 { + len := len(goBytes) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefUint8{ + ptr: &emptyUint8, + len: C.size_t(len), + } + } + return SliceRefUint8{ + ptr: (*C.uint8_t)(unsafe.Pointer(&goBytes[0])), + len: C.size_t(len), + } +} + +func AsSliceRefUint64(goBytes []uint64) SliceRefUint64 { + len := len(goBytes) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefUint64{ + ptr: &emptyUint64, + len: C.size_t(len), + } + } + return SliceRefUint64{ + ptr: (*C.uint64_t)(unsafe.Pointer(&goBytes[0])), + len: C.size_t(len), + } +} + +func AllocSliceBoxedUint8(goBytes []byte) SliceBoxedUint8 { + len := len(goBytes) + + ptr := C.alloc_boxed_slice(C.size_t(len)) + copy(ptr.slice(), goBytes) + + return ptr +} + +func AsSliceRefUint(goSlice []uint) SliceRefUint { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefUint{ + ptr: &emptyUint, + len: C.size_t(len), + } + } + + return SliceRefUint{ + ptr: (*C.size_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefAggregationInputs(goSlice []AggregationInputs) SliceRefAggregationInputs { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefAggregationInputs{ + ptr: &emptyAggregationInputs, + len: C.size_t(len), + } + } + + return SliceRefAggregationInputs{ + ptr: (*C.AggregationInputs_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefPublicReplicaInfo(goSlice []PublicReplicaInfo) SliceRefPublicReplicaInfo { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefPublicReplicaInfo{ + ptr: &emptyPublicReplicaInfo, + len: C.size_t(len), + } + } + + return SliceRefPublicReplicaInfo{ + ptr: (*C.PublicReplicaInfo_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefPrivateReplicaInfo(goSlice []PrivateReplicaInfo) SliceRefPrivateReplicaInfo { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefPrivateReplicaInfo{ + ptr: &emptyPrivateReplicaInfo, + len: C.size_t(len), + } + } + + return SliceRefPrivateReplicaInfo{ + ptr: (*C.PrivateReplicaInfo_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefPoStProof(goSlice []PoStProof) SliceRefPoStProof { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefPoStProof{ + ptr: &emptyPoStProof, + len: C.size_t(len), + } + } + + return SliceRefPoStProof{ + ptr: (*C.PoStProof_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefPublicPieceInfo(goSlice []PublicPieceInfo) SliceRefPublicPieceInfo { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefPublicPieceInfo{ + ptr: &emptyPublicPieceInfo, + len: C.size_t(len), + } + } + + return SliceRefPublicPieceInfo{ + ptr: (*C.PublicPieceInfo_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefByteArray32(goSlice []ByteArray32) SliceRefByteArray32 { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefByteArray32{ + ptr: &emptyByteArray32, + len: C.size_t(len), + } + } + + return SliceRefByteArray32{ + ptr: (*C.uint8_32_array_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsSliceRefSliceBoxedUint8(goSlice []SliceBoxedUint8) SliceRefSliceBoxedUint8 { + len := len(goSlice) + + if len == 0 { + // can't take element 0 of an empty slice + return SliceRefSliceBoxedUint8{ + ptr: &emptySliceBoxedUint8, + len: C.size_t(len), + } + } + + return SliceRefSliceBoxedUint8{ + ptr: (*C.slice_boxed_uint8_t)(unsafe.Pointer(&goSlice[0])), + len: C.size_t(len), + } +} + +func AsByteArray32(goSlice []byte) ByteArray32 { + var ary ByteArray32 + l := len(goSlice) + for idx := range goSlice { + if idx < l { + ary.idx[idx] = C.uchar(goSlice[idx]) + } + } + return ary +} + +// CheckErr returns `nil` if the `code` indicates success and an error otherwise. +func CheckErr(resp result) error { + if resp == nil { + return errors.New("nil result from Filecoin FFI") + } + if resp.statusCode() == FCPResponseStatusNoError { + return nil + } + + return errors.New(string(resp.errorMsg().slice())) +} + +func NewAggregationInputs(commR ByteArray32, commD ByteArray32, sectorId uint64, ticket ByteArray32, seed ByteArray32) AggregationInputs { + return AggregationInputs{ + comm_r: commR, + comm_d: commD, + sector_id: C.uint64_t(sectorId), + ticket: ticket, + seed: seed, + } +} + +func NewPrivateReplicaInfo(pp RegisteredPoStProof, cacheDirPath string, commR ByteArray32, replicaPath string, sectorId uint64) PrivateReplicaInfo { + return PrivateReplicaInfo{ + registered_proof: pp, + cache_dir_path: AllocSliceBoxedUint8([]byte(cacheDirPath)), + replica_path: AllocSliceBoxedUint8([]byte(replicaPath)), + sector_id: C.uint64_t(sectorId), + comm_r: commR, + } +} + +func NewPublicReplicaInfo(pp RegisteredPoStProof, commR ByteArray32, sectorId uint64) PublicReplicaInfo { + return PublicReplicaInfo{ + registered_proof: pp, + sector_id: C.uint64_t(sectorId), + comm_r: commR, + } +} + +func NewPoStProof(pp RegisteredPoStProof, proof []byte) PoStProof { + return PoStProof{ + registered_proof: pp, + proof: AllocSliceBoxedUint8(proof), + } +} + +func NewPublicPieceInfo(numBytes uint64, commP ByteArray32) PublicPieceInfo { + return PublicPieceInfo{ + num_bytes: C.uint64_t(numBytes), + comm_p: commP, + } +} + +func NewPartitionSnarkProof(pp RegisteredPoStProof, proof []byte) PartitionSnarkProof { + return PartitionSnarkProof{ + registered_proof: pp, + proof: AllocSliceBoxedUint8(proof), + } +} diff --git a/cgo/helpers_test.go b/cgo/helpers_test.go new file mode 100644 index 00000000..7d7697ff --- /dev/null +++ b/cgo/helpers_test.go @@ -0,0 +1,66 @@ +package cgo + +import ( + "testing" + "unsafe" + + "github.com/stretchr/testify/assert" +) + +func TestAsSliceRefUint8(t *testing.T) { + // some words + foo := []byte("hello world") + ref := AsSliceRefUint8(foo) + assert.Equal(t, unsafe.Slice((*byte)(unsafe.Pointer(ref.ptr)), int(ref.len)), foo) + + // empty + foo = []byte("") + ref = AsSliceRefUint8(foo) + assert.Equal(t, unsafe.Slice((*byte)(unsafe.Pointer(ref.ptr)), int(ref.len)), foo) +} + +func TestAsSliceRefUint(t *testing.T) { + foo := []uint{0, 1, 2} + ref := AsSliceRefUint(foo) + assert.Equal(t, unsafe.Slice((*uint)(unsafe.Pointer(ref.ptr)), int(ref.len)), foo) + + // empty + foo = []uint{} + ref = AsSliceRefUint(foo) + assert.Equal(t, unsafe.Slice((*uint)(unsafe.Pointer(ref.ptr)), int(ref.len)), foo) +} + +func TestByteArray32(t *testing.T) { + foo := make([]byte, 32) + for i := range foo { + foo[i] = 1 + } + ary := AsByteArray32(foo) + assert.Equal(t, ary.slice(), foo) + + ary2 := ary.copy() + assert.Equal(t, ary.slice(), ary2) + + // input too short + aryShort := AsByteArray32([]byte{0, 1, 2}) + slice := aryShort.slice() + for i := range slice { + if i == 0 { + assert.Equal(t, slice[i], byte(0)) + } else if i == 1 { + assert.Equal(t, slice[i], byte(1)) + } else if i == 2 { + assert.Equal(t, slice[i], byte(2)) + } else { + assert.Equal(t, slice[i], byte(0)) + } + } +} + +func TestAllocSliceBoxedUint8(t *testing.T) { + foo := []byte("hello world") + + boxed := AllocSliceBoxedUint8(foo) + defer boxed.Destroy() + assert.Equal(t, boxed.slice(), foo) +} diff --git a/generated/libs.go b/cgo/libs.go similarity index 77% rename from generated/libs.go rename to cgo/libs.go index 22976440..8e6fdda1 100644 --- a/generated/libs.go +++ b/cgo/libs.go @@ -1,10 +1,9 @@ -package generated +package cgo /* #cgo LDFLAGS: -L${SRCDIR}/.. -lfilcrypto #cgo pkg-config: ${SRCDIR}/../filcrypto.pc #include "../filcrypto.h" #include -#include "cgo_helpers.h" */ import "C" diff --git a/cgo/proofs.go b/cgo/proofs.go new file mode 100644 index 00000000..f00dcbd2 --- /dev/null +++ b/cgo/proofs.go @@ -0,0 +1,383 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" + +func VerifySeal(registeredProof RegisteredSealProof, commR *ByteArray32, commD *ByteArray32, proverId *ByteArray32, ticket *ByteArray32, seed *ByteArray32, sectorId uint64, proof SliceRefUint8) (bool, error) { + resp := C.verify_seal(registeredProof, commR, commD, proverId, ticket, seed, C.uint64_t(sectorId), proof) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return false, err + } + + return bool(resp.value), nil +} + +func VerifyAggregateSealProof(registeredProof RegisteredSealProof, registeredAggregation RegisteredAggregationProof, proverId *ByteArray32, proof SliceRefUint8, commitInputs SliceRefAggregationInputs) (bool, error) { + resp := C.verify_aggregate_seal_proof(registeredProof, registeredAggregation, proverId, proof, commitInputs) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return false, err + } + return bool(resp.value), nil +} + +func VerifyWinningPoSt(randomness *ByteArray32, replicas SliceRefPublicReplicaInfo, proofs SliceRefPoStProof, proverId *ByteArray32) (bool, error) { + resp := C.verify_winning_post(randomness, replicas, proofs, proverId) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return false, err + } + + return bool(resp.value), nil +} + +func VerifyWindowPoSt(randomness *ByteArray32, replicas SliceRefPublicReplicaInfo, proofs SliceRefPoStProof, proverId *ByteArray32) (bool, error) { + resp := C.verify_window_post(randomness, replicas, proofs, proverId) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return false, err + } + + return bool(resp.value), nil +} + +func GeneratePieceCommitment(registeredProof RegisteredSealProof, pieceFdRaw int32, unpaddedPieceSize uint64) ([]byte, error) { + resp := C.generate_piece_commitment(registeredProof, C.int32_t(pieceFdRaw), C.uint64_t(unpaddedPieceSize)) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.comm_p.copy(), nil +} + +func GenerateDataCommitment(registeredProof RegisteredSealProof, pieces SliceRefPublicPieceInfo) ([]byte, error) { + resp := C.generate_data_commitment(registeredProof, pieces) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copy(), nil +} + +func WriteWithAlignment(registeredProof RegisteredSealProof, srcFd int32, srcSize uint64, dstFd int32, existingPieceSizes SliceRefUint64) (uint64, uint64, []byte, error) { + resp := C.write_with_alignment(registeredProof, C.int32_t(srcFd), C.uint64_t(srcSize), C.int32_t(dstFd), existingPieceSizes) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return 0, 0, nil, err + } + + return uint64(resp.value.left_alignment_unpadded), uint64(resp.value.total_write_unpadded), resp.value.comm_p.copy(), nil +} + +func WriteWithoutAlignment(registeredProof RegisteredSealProof, srcFd int32, srcSize uint64, dstFd int32) (uint64, []byte, error) { + resp := C.write_without_alignment(registeredProof, C.int32_t(srcFd), C.uint64_t(srcSize), C.int32_t(dstFd)) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return 0, nil, err + } + + return uint64(resp.value.total_write_unpadded), resp.value.comm_p.copy(), nil +} + +func SealPreCommitPhase1(registeredProof RegisteredSealProof, cacheDirPath SliceRefUint8, stagedSectorPath SliceRefUint8, sealedSectorPath SliceRefUint8, sectorId uint64, proverId *ByteArray32, ticket *ByteArray32, pieces SliceRefPublicPieceInfo) ([]byte, error) { + resp := C.seal_pre_commit_phase1(registeredProof, cacheDirPath, stagedSectorPath, sealedSectorPath, C.uint64_t(sectorId), proverId, ticket, pieces) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +func SealPreCommitPhase2(sealPreCommitPhase1Output SliceRefUint8, cacheDirPath SliceRefUint8, sealedSectorPath SliceRefUint8) ([]byte, []byte, error) { + resp := C.seal_pre_commit_phase2(sealPreCommitPhase1Output, cacheDirPath, sealedSectorPath) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, nil, err + } + return resp.value.comm_r.copy(), resp.value.comm_d.copy(), nil +} + +func SealCommitPhase1(registeredProof RegisteredSealProof, commR *ByteArray32, commD *ByteArray32, cacheDirPath SliceRefUint8, replicaPath SliceRefUint8, sectorId uint64, proverId *ByteArray32, ticket *ByteArray32, seed *ByteArray32, pieces SliceRefPublicPieceInfo) ([]byte, error) { + resp := C.seal_commit_phase1(registeredProof, commR, commD, cacheDirPath, replicaPath, C.uint64_t(sectorId), proverId, ticket, seed, pieces) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copy(), nil +} + +func SealCommitPhase2(sealCommitPhase1Output SliceRefUint8, sectorId uint64, proverId *ByteArray32) ([]byte, error) { + resp := C.seal_commit_phase2(sealCommitPhase1Output, C.uint64_t(sectorId), proverId) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +func AggregateSealProofs(registeredProof RegisteredSealProof, registeredAggregation RegisteredAggregationProof, commRs SliceRefByteArray32, seeds SliceRefByteArray32, sealCommitResponses SliceRefSliceBoxedUint8) ([]byte, error) { + resp := C.aggregate_seal_proofs(registeredProof, registeredAggregation, commRs, seeds, sealCommitResponses) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +func UnsealRange(registeredProof RegisteredSealProof, cacheDirPath SliceRefUint8, sealedSectorFdRaw int32, unsealOutputFdRaw int32, sectorId uint64, proverId *ByteArray32, ticket *ByteArray32, commD *ByteArray32, unpaddedByteIndex uint64, unpaddedBytesAmount uint64) error { + resp := C.unseal_range(registeredProof, cacheDirPath, C.int32_t(sealedSectorFdRaw), C.int32_t(unsealOutputFdRaw), C.uint64_t(sectorId), proverId, ticket, commD, C.uint64_t(unpaddedByteIndex), C.uint64_t(unpaddedBytesAmount)) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return err + } + return nil +} + +func GenerateWinningPoStSectorChallenge(registeredProof RegisteredPoStProof, randomness *ByteArray32, sectorSetLen uint64, proverId *ByteArray32) ([]uint64, error) { + resp := C.generate_winning_post_sector_challenge(registeredProof, randomness, C.uint64_t(sectorSetLen), proverId) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +func GenerateWinningPoSt(randomness *ByteArray32, replicas SliceRefPrivateReplicaInfo, proverId *ByteArray32) ([]PoStProofGo, error) { + resp := C.generate_winning_post(randomness, replicas, proverId) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +func GenerateWindowPoSt(randomness *ByteArray32, replicas SliceRefPrivateReplicaInfo, proverId *ByteArray32) ([]PoStProofGo, []uint64, error) { + resp := C.generate_window_post(randomness, replicas, proverId) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + faults := resp.value.faulty_sectors.copy() + return nil, faults, err + } + + proofs := resp.value.proofs.copy() + return proofs, []uint64{}, nil +} + +func GetGpuDevices() ([]string, error) { + resp := C.get_gpu_devices() + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copyAsStrings(), nil +} + +func GetSealVersion(registeredProof RegisteredSealProof) (string, error) { + resp := C.get_seal_version(registeredProof) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return "", err + } + + return string(resp.value.copy()), nil +} + +func GetPoStVersion(registeredProof RegisteredPoStProof) (string, error) { + resp := C.get_post_version(registeredProof) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return "", err + } + + return string(resp.value.copy()), nil +} + +func GetNumPartitionForFallbackPost(registeredProof RegisteredPoStProof, numSectors uint) (uint, error) { + resp := C.get_num_partition_for_fallback_post(registeredProof, C.size_t(numSectors)) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return 0, err + } + + return uint(resp.value), nil +} + +func ClearCache(sectorSize uint64, cacheDirPath SliceRefUint8) error { + resp := C.clear_cache(C.uint64_t(sectorSize), cacheDirPath) + defer resp.destroy() + return CheckErr(resp) +} + +func Fauxrep(registeredProf RegisteredSealProof, cacheDirPath SliceRefUint8, sealedSectorPath SliceRefUint8) ([]byte, error) { + resp := C.fauxrep(registeredProf, cacheDirPath, sealedSectorPath) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +func Fauxrep2(registeredProf RegisteredSealProof, cacheDirPath SliceRefUint8, existingPAuxPath SliceRefUint8) ([]byte, error) { + resp := C.fauxrep2(registeredProf, cacheDirPath, existingPAuxPath) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copy(), nil +} + +// sector update + +func EmptySectorUpdateEncodeInto(registeredProof RegisteredUpdateProof, newReplicaPath SliceRefUint8, newCacheDirPath SliceRefUint8, sectorKeyPath SliceRefUint8, sectorKeyCacheDirPath SliceRefUint8, stagedDataPath SliceRefUint8, pieces SliceRefPublicPieceInfo) ([]byte, []byte, error) { + resp := C.empty_sector_update_encode_into(registeredProof, newReplicaPath, newCacheDirPath, sectorKeyPath, sectorKeyCacheDirPath, stagedDataPath, pieces) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, nil, err + } + return resp.value.comm_r_new.copy(), resp.value.comm_d_new.copy(), nil +} + +func EmptySectorUpdateDecodeFrom(registeredProof RegisteredUpdateProof, outDataPath SliceRefUint8, replicaPath SliceRefUint8, sectorKeyPath SliceRefUint8, sectorKeyCacheDirPath SliceRefUint8, commDNew *ByteArray32) error { + resp := C.empty_sector_update_decode_from(registeredProof, outDataPath, replicaPath, sectorKeyPath, sectorKeyCacheDirPath, commDNew) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return err + } + return nil +} + +func EmptySectorUpdateRemoveEncodedData(registeredProof RegisteredUpdateProof, sectorKeyPath, sectorKeyCacheDirPath, replicaPath, replicaCachePath, dataPath SliceRefUint8, commDNew *ByteArray32) error { + resp := C.empty_sector_update_remove_encoded_data(registeredProof, sectorKeyPath, sectorKeyCacheDirPath, replicaPath, replicaCachePath, dataPath, commDNew) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return err + } + return nil +} + +func GenerateEmptySectorUpdatePartitionProofs(registeredProof RegisteredUpdateProof, commROld, commRNew, commDNew *ByteArray32, sectorKeyPath, sectorKeyCacheDirPath, replicaPath, replicaCachePath SliceRefUint8) ([][]byte, error) { + resp := C.generate_empty_sector_update_partition_proofs(registeredProof, commROld, commRNew, commDNew, sectorKeyPath, sectorKeyCacheDirPath, replicaPath, replicaCachePath) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + return resp.value.copyAsBytes(), nil +} + +func VerifyEmptySectorUpdatePartitionProofs(registeredProof RegisteredUpdateProof, proofs SliceRefSliceBoxedUint8, commROld, commRNew, commDNew *ByteArray32) (bool, error) { + resp := C.verify_empty_sector_update_partition_proofs(registeredProof, proofs, commROld, commRNew, commDNew) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return false, err + } + + return bool(resp.value), nil +} + +func GenerateEmptySectorUpdateProofWithVanilla(registeredProof RegisteredUpdateProof, vanillaProofs SliceRefSliceBoxedUint8, commROld, commRNew, commDNew *ByteArray32) ([]byte, error) { + resp := C.generate_empty_sector_update_proof_with_vanilla(registeredProof, vanillaProofs, commROld, commRNew, commDNew) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copy(), nil +} + +func GenerateEmptySectorUpdateProof(registeredProof RegisteredUpdateProof, commROld, commRNew, commDNew *ByteArray32, sectorKeyPath, sectorKeyCacheDirPath, replicaPath, replicaCachePath SliceRefUint8) ([]byte, error) { + resp := C.generate_empty_sector_update_proof(registeredProof, commROld, commRNew, commDNew, sectorKeyPath, sectorKeyCacheDirPath, replicaPath, replicaCachePath) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copy(), nil +} + +func VerifyEmptySectorUpdateProof(registeredProof RegisteredUpdateProof, proof SliceRefUint8, commROld, commRNew, commDNew *ByteArray32) (bool, error) { + resp := C.verify_empty_sector_update_proof(registeredProof, proof, commROld, commRNew, commDNew) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return false, err + } + + return bool(resp.value), nil +} + +// -- distributed + +func GenerateFallbackSectorChallenges(registeredProof RegisteredPoStProof, randomness *ByteArray32, sectorIds SliceRefUint64, proverId *ByteArray32) ([]uint64, [][]uint64, error) { + resp := C.generate_fallback_sector_challenges(registeredProof, randomness, sectorIds, proverId) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, nil, err + } + + return resp.value.ids.copy(), resp.value.challenges.copy(), nil +} + +func GenerateSingleVanillaProof(replica PrivateReplicaInfo, challenges SliceRefUint64) ([]byte, error) { + resp := C.generate_single_vanilla_proof(replica, challenges) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copy(), nil +} + +func GenerateWinningPoStWithVanilla(registeredProof RegisteredPoStProof, randomness, proverId *ByteArray32, vanillaProofs SliceRefSliceBoxedUint8) ([]PoStProofGo, error) { + resp := C.generate_winning_post_with_vanilla(registeredProof, randomness, proverId, vanillaProofs) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, err + } + + return resp.value.copy(), nil +} + +func GenerateWindowPoStWithVanilla(registeredProof RegisteredPoStProof, randomness, proverId *ByteArray32, vanillaProofs SliceRefSliceBoxedUint8) ([]PoStProofGo, []uint64, error) { + resp := C.generate_window_post_with_vanilla(registeredProof, randomness, proverId, vanillaProofs) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return nil, nil, err + } + + return resp.value.proofs.copy(), resp.value.faulty_sectors.copy(), nil +} + +func GenerateSingleWindowPoStWithVanilla(registeredProof RegisteredPoStProof, randomness, proverId *ByteArray32, vanillaProofs SliceRefSliceBoxedUint8, partitionIndex uint) (PartitionSnarkProofGo, []uint64, error) { + resp := C.generate_single_window_post_with_vanilla(registeredProof, randomness, proverId, vanillaProofs, C.size_t(partitionIndex)) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return PartitionSnarkProofGo{}, nil, err + } + + return resp.value.partition_proof.copy(), resp.value.faulty_sectors.copy(), nil +} + +func MergeWindowPoStPartitionProofs(registeredProof RegisteredPoStProof, partitionProofs SliceRefSliceBoxedUint8) (PoStProofGo, error) { + resp := C.merge_window_post_partition_proofs(registeredProof, partitionProofs) + defer resp.destroy() + if err := CheckErr(resp); err != nil { + return PoStProofGo{}, err + } + + return resp.value.copy(), nil +} diff --git a/cgo/types.go b/cgo/types.go new file mode 100644 index 00000000..051c2034 --- /dev/null +++ b/cgo/types.go @@ -0,0 +1,649 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" +import ( + "unsafe" +) + +type FCPResponseStatus = int64 + +type RegisteredSealProof = C.RegisteredSealProof_t +type RegisteredAggregationProof = C.RegisteredAggregationProof_t +type RegisteredPoStProof = C.RegisteredPoStProof_t +type RegisteredUpdateProof = C.RegisteredUpdateProof_t + +type FvmRegisteredVersion = C.FvmRegisteredVersion_t + +type AggregationInputs = C.AggregationInputs_t + +type PublicReplicaInfo = C.PublicReplicaInfo_t +type PrivateReplicaInfo = C.PrivateReplicaInfo_t +type PartitionSnarkProof = C.PartitionSnarkProof_t +type PoStProof = C.PoStProof_t +type PublicPieceInfo = C.PublicPieceInfo_t + +type SliceRefPublicReplicaInfo = C.slice_ref_PublicReplicaInfo_t +type SliceRefPrivateReplicaInfo = C.slice_ref_PrivateReplicaInfo_t +type SliceRefByteArray32 = C.slice_ref_uint8_32_array_t +type SliceRefSliceBoxedUint8 = C.slice_ref_slice_boxed_uint8_t +type SliceRefUint64 = C.slice_ref_uint64_t +type SliceRefPoStProof = C.slice_ref_PoStProof_t +type SliceRefPublicPieceInfo = C.slice_ref_PublicPieceInfo_t +type SliceRefUint8 = C.slice_ref_uint8_t +type SliceRefUint = C.slice_ref_size_t +type SliceRefAggregationInputs = C.slice_ref_AggregationInputs_t + +type SliceBoxedPoStProof = C.struct_slice_boxed_PoStProof +type SliceBoxedUint64 = C.struct_slice_boxed_uint64 +type SliceBoxedSliceBoxedUint8 = C.slice_boxed_slice_boxed_uint8_t +type SliceBoxedSliceBoxedUint64 = C.slice_boxed_slice_boxed_uint64_t +type SliceBoxedUint8 = C.struct_slice_boxed_uint8 + +type ByteArray32 = C.uint8_32_array_t +type ByteArray48 = C.uint8_48_array_t +type ByteArray96 = C.uint8_96_array_t + +type FvmMachine = C.InnerFvmMachine_t +type FvmMachineExecuteResponse = C.FvmMachineExecuteResponse_t + +type resultBool = C.Result_bool_t +type resultGeneratePieceCommitment = C.Result_GeneratePieceCommitment_t +type resultWriteWithAlignment = C.Result_WriteWithAlignment_t +type resultWriteWithoutAlignment = C.Result_WriteWithoutAlignment_t +type resultByteArray32 = C.Result_uint8_32_array_t +type resultVoid = C.Result_void_t +type resultSealPreCommitPhase2 = C.Result_SealPreCommitPhase2_t +type resultSliceBoxedUint8 = C.Result_slice_boxed_uint8_t +type resultSliceBoxedPoStProof = C.Result_slice_boxed_PoStProof_t +type resultSliceBoxedUint64 = C.Result_slice_boxed_uint64_t +type resultUint = C.Result_size_t +type resultSliceBoxedSliceBoxedUint8 = C.Result_slice_boxed_slice_boxed_uint8_t +type resultGenerateWindowPoSt = C.Result_GenerateWindowPoSt_t +type resultEmptySectorUpdateEncodeInto = C.Result_EmptySectorUpdateEncodeInto_t +type resultGenerateFallbackSectorChallenges = C.Result_GenerateFallbackSectorChallenges_t +type resultGenerateSingleWindowPoStWithVanilla = C.Result_GenerateSingleWindowPoStWithVanilla_t +type resultPoStProof = C.Result_PoStProof_t + +type resultFvmMachine = C.Result_InnerFvmMachine_ptr_t +type resultFvmMachineExecuteResponse = C.Result_FvmMachineExecuteResponse_t + +type result interface { + statusCode() FCPResponseStatus + errorMsg() *SliceBoxedUint8 + destroy() +} + +// PartitionSnarkProofGo is a go allocated version of `PartitionSnarkProof`. +type PartitionSnarkProofGo struct { + RegisteredProof RegisteredPoStProof + Proof []byte +} + +// PoStProofGo is a go allocated version of `PoStProof`. +type PoStProofGo struct { + RegisteredProof RegisteredPoStProof + Proof []byte +} + +/// FvmMachineExecuteResponse is a go allocated version of `FvmMachineExecuteResponse`. +type FvmMachineExecuteResponseGo struct { + ExitCode uint64 + ReturnVal []byte + GasUsed uint64 + PenaltyHi uint64 + PenaltyLo uint64 + MinerTipHi uint64 + MinerTipLo uint64 + ExecTrace []byte + FailureInfo string +} + +func (ptr SliceBoxedUint8) slice() []byte { + if ptr.ptr == nil { + return nil + } + return unsafe.Slice((*byte)(ptr.ptr), int(ptr.len)) +} + +func (ptr SliceBoxedUint8) copy() []byte { + if ptr.ptr == nil { + return nil + } else if ptr.len == 0 { + return []byte{} + } + + res := make([]byte, int(ptr.len)) + copy(res, ptr.slice()) + return res +} + +func (ptr *resultBool) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultBool) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultBool) destroy() { + if ptr != nil { + // TODO: correct naming + C.destroy_verify_seal_response(ptr) + ptr = nil + } +} + +func (ptr *PoStProof) registeredProof() RegisteredPoStProof { + return ptr.registered_proof +} + +func (ptr *PoStProof) destroy() { + if ptr != nil { + ptr.proof.Destroy() + ptr = nil + } +} + +func (ptr *ByteArray96) destroy() { + if ptr != nil { + C.destroy_box_bls_digest(ptr) + ptr = nil + } +} + +func (ptr ByteArray96) slice() []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(&ptr.idx[0])), 96) +} + +func (ptr *ByteArray96) copyAsArray() *[96]byte { + if ptr == nil { + return nil + } + var res [96]byte + copy(res[:], ptr.slice()) + return &res +} + +func (ptr ByteArray48) slice() []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(&ptr.idx[0])), 48) +} + +func (ptr *ByteArray48) copyAsArray() *[48]byte { + if ptr == nil { + return nil + } + var res [48]byte + copy(res[:], ptr.slice()) + return &res +} + +func (ptr *ByteArray48) destroy() { + if ptr != nil { + C.destroy_box_bls_public_key(ptr) + ptr = nil + } +} + +func (ptr ByteArray32) slice() []byte { + return unsafe.Slice((*byte)(unsafe.Pointer(&ptr.idx[0])), 32) +} + +func (ptr *ByteArray32) copy() []byte { + res := make([]byte, 32) + if ptr != nil { + copy(res, ptr.slice()) + } + return res +} + +func (ptr *ByteArray32) copyAsArray() *[32]byte { + if ptr == nil { + return nil + } + var res [32]byte + copy(res[:], ptr.slice()) + return &res +} + +func (ptr *ByteArray32) destroy() { + if ptr != nil { + C.destroy_box_bls_private_key(ptr) + ptr = nil + } +} + +func (ptr *resultGeneratePieceCommitment) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultGeneratePieceCommitment) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultGeneratePieceCommitment) destroy() { + if ptr != nil { + C.destroy_generate_piece_commitment_response(ptr) + ptr = nil + } +} + +func (ptr *resultByteArray32) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultByteArray32) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultByteArray32) destroy() { + if ptr != nil { + // TODO: better naming + C.destroy_generate_data_commitment_response(ptr) + ptr = nil + } +} + +func (ptr *resultWriteWithAlignment) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultWriteWithAlignment) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultWriteWithAlignment) destroy() { + if ptr != nil { + C.destroy_write_with_alignment_response(ptr) + ptr = nil + } +} + +func (ptr *resultWriteWithoutAlignment) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultWriteWithoutAlignment) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultWriteWithoutAlignment) destroy() { + if ptr != nil { + C.destroy_write_without_alignment_response(ptr) + ptr = nil + } +} + +func (ptr *resultSliceBoxedUint8) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultSliceBoxedUint8) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultSliceBoxedUint8) destroy() { + if ptr != nil { + // TODO: naming + C.destroy_seal_pre_commit_phase1_response(ptr) + ptr = nil + } +} + +func (ptr *resultSealPreCommitPhase2) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultSealPreCommitPhase2) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultSealPreCommitPhase2) destroy() { + if ptr != nil { + C.destroy_seal_pre_commit_phase2_response(ptr) + ptr = nil + } +} + +func (ptr *resultVoid) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultVoid) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultVoid) destroy() { + if ptr != nil { + // TODO: correct naming + C.destroy_unseal_range_response(ptr) + ptr = nil + } +} + +func (ptr SliceBoxedUint64) slice() []uint64 { + if ptr.ptr == nil { + return nil + } + return unsafe.Slice((*uint64)(unsafe.Pointer(ptr.ptr)), int(ptr.len)) +} + +func (ptr SliceBoxedUint64) copy() []uint64 { + if ptr.ptr == nil { + return nil + } else if ptr.len == 0 { + return []uint64{} + } + + res := make([]uint64, int(ptr.len)) + copy(res, ptr.slice()) + return res +} + +func (ptr *resultSliceBoxedUint64) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultSliceBoxedUint64) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultSliceBoxedUint64) destroy() { + if ptr != nil { + // TODO: correct naming + C.destroy_generate_winning_post_sector_challenge(ptr) + ptr = nil + } +} + +func (ptr SliceBoxedPoStProof) slice() []PoStProof { + if ptr.ptr == nil { + return nil + } + return unsafe.Slice((*PoStProof)(unsafe.Pointer(ptr.ptr)), int(ptr.len)) +} + +func (ptr SliceBoxedPoStProof) copy() []PoStProofGo { + if ptr.ptr == nil { + return nil + } else if ptr.len == 0 { + return []PoStProofGo{} + } + + ref := ptr.slice() + res := make([]PoStProofGo, len(ref)) + for i := range ref { + res[i] = ref[i].copy() + } + + return res +} + +func (proof PoStProof) copy() PoStProofGo { + return PoStProofGo{ + RegisteredProof: proof.registered_proof, + Proof: proof.proof.copy(), + } +} + +func (ptr *resultSliceBoxedPoStProof) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultSliceBoxedPoStProof) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultSliceBoxedPoStProof) destroy() { + if ptr != nil { + // TODO: correct naming + C.destroy_generate_winning_post_response(ptr) + ptr = nil + } +} + +func (ptr *resultGenerateWindowPoSt) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultGenerateWindowPoSt) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultGenerateWindowPoSt) destroy() { + if ptr != nil { + C.destroy_generate_window_post_response(ptr) + ptr = nil + } +} + +func (ptr SliceBoxedSliceBoxedUint8) slice() []SliceBoxedUint8 { + if ptr.ptr == nil { + return nil + } + return unsafe.Slice((*SliceBoxedUint8)(unsafe.Pointer(ptr.ptr)), int(ptr.len)) +} + +func (ptr SliceBoxedSliceBoxedUint8) copyAsBytes() [][]byte { + if ptr.ptr == nil { + return nil + } else if ptr.len == 0 { + return [][]byte{} + } + + ref := ptr.slice() + res := make([][]byte, int(ptr.len)) + for i := range ref { + res[i] = ref[i].copy() + } + + return res +} + +func (ptr SliceBoxedSliceBoxedUint8) copyAsStrings() []string { + if ptr.ptr == nil { + return nil + } else if ptr.len == 0 { + return []string{} + } + ref := ptr.slice() + res := make([]string, int(ptr.len)) + for i := range ref { + res[i] = string(ref[i].copy()) + } + + return res +} + +func (ptr *resultSliceBoxedSliceBoxedUint8) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultSliceBoxedSliceBoxedUint8) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultSliceBoxedSliceBoxedUint8) destroy() { + if ptr != nil { + // TODO: naming + C.destroy_generate_empty_sector_update_partition_proof_response(ptr) + ptr = nil + } +} + +func (ptr *resultUint) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultUint) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultUint) destroy() { + if ptr != nil { + // TODO: naming + C.destroy_get_num_partition_for_fallback_post_response(ptr) + ptr = nil + } +} + +func (ptr *resultEmptySectorUpdateEncodeInto) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultEmptySectorUpdateEncodeInto) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultEmptySectorUpdateEncodeInto) destroy() { + if ptr != nil { + C.destroy_empty_sector_update_encode_into_response(ptr) + ptr = nil + } +} + +func (ptr SliceBoxedSliceBoxedUint64) slice() []SliceBoxedUint64 { + if ptr.ptr == nil { + return nil + } + return unsafe.Slice((*SliceBoxedUint64)(unsafe.Pointer(ptr.ptr)), int(ptr.len)) +} + +func (ptr SliceBoxedSliceBoxedUint64) copy() [][]uint64 { + if ptr.ptr == nil { + return nil + } else if ptr.len == 0 { + return [][]uint64{} + } + + ref := ptr.slice() + res := make([][]uint64, int(ptr.len)) + for i := range ref { + res[i] = ref[i].copy() + } + + return res +} + +func (ptr *resultGenerateFallbackSectorChallenges) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultGenerateFallbackSectorChallenges) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultGenerateFallbackSectorChallenges) destroy() { + if ptr != nil { + C.destroy_generate_fallback_sector_challenges_response(ptr) + ptr = nil + } +} + +func (proof PartitionSnarkProof) copy() PartitionSnarkProofGo { + return PartitionSnarkProofGo{ + RegisteredProof: proof.registered_proof, + Proof: proof.proof.copy(), + } +} + +func (ptr *resultGenerateSingleWindowPoStWithVanilla) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultGenerateSingleWindowPoStWithVanilla) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultGenerateSingleWindowPoStWithVanilla) destroy() { + if ptr != nil { + C.destroy_generate_single_window_post_with_vanilla_response(ptr) + ptr = nil + } +} + +func (ptr *resultPoStProof) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultPoStProof) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultPoStProof) destroy() { + if ptr != nil { + C.destroy_merge_window_post_partition_proofs_response(ptr) + ptr = nil + } +} + +func (ptr *SliceBoxedUint8) Destroy() { + if ptr.ptr != nil { + C.destroy_boxed_slice(*ptr) + ptr.ptr = nil + } +} + +func (ptr *PrivateReplicaInfo) Destroy() { + if ptr != nil { + ptr.cache_dir_path.Destroy() + ptr.replica_path.Destroy() + ptr = nil + } +} + +func (ptr *resultFvmMachineExecuteResponse) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultFvmMachineExecuteResponse) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultFvmMachineExecuteResponse) destroy() { + if ptr != nil { + C.destroy_fvm_machine_execute_response(ptr) + ptr = nil + } +} + +func (ptr *resultFvmMachine) statusCode() FCPResponseStatus { + return FCPResponseStatus(ptr.status_code) +} + +func (ptr *resultFvmMachine) errorMsg() *SliceBoxedUint8 { + return &ptr.error_msg +} + +func (ptr *resultFvmMachine) destroy() { + if ptr != nil { + C.destroy_create_fvm_machine_response(ptr) + ptr = nil + } +} + +func (ptr *FvmMachine) Destroy() { + if ptr != nil { + C.drop_fvm_machine(ptr) + ptr = nil + } +} + +func (r FvmMachineExecuteResponse) copy() FvmMachineExecuteResponseGo { + return FvmMachineExecuteResponseGo{ + ExitCode: uint64(r.exit_code), + ReturnVal: r.return_val.copy(), + GasUsed: uint64(r.gas_used), + PenaltyHi: uint64(r.penalty_hi), + PenaltyLo: uint64(r.penalty_lo), + MinerTipHi: uint64(r.miner_tip_hi), + MinerTipLo: uint64(r.miner_tip_lo), + ExecTrace: r.exec_trace.copy(), + FailureInfo: string(r.failure_info.slice()), + } +} diff --git a/cgo/util.go b/cgo/util.go new file mode 100644 index 00000000..83f20927 --- /dev/null +++ b/cgo/util.go @@ -0,0 +1,20 @@ +package cgo + +/* +#cgo LDFLAGS: -L${SRCDIR}/.. +#cgo pkg-config: ${SRCDIR}/../filcrypto.pc +#include "../filcrypto.h" +#include +*/ +import "C" + +func InitLogFd(fd int32) error { + resp := C.init_log_fd(C.int32_t(fd)) + defer resp.destroy() + + if err := CheckErr(resp); err != nil { + return err + } + + return nil +} diff --git a/cgoleakdetect/runner.go b/cgoleakdetect/runner.go index 2bfc33b9..2f4381ed 100644 --- a/cgoleakdetect/runner.go +++ b/cgoleakdetect/runner.go @@ -1,4 +1,5 @@ -//+build cgo +//go:build cgo +// +build cgo package main diff --git a/distributed.go b/distributed.go index bf34a386..6527d259 100644 --- a/distributed.go +++ b/distributed.go @@ -1,12 +1,12 @@ -//+build cgo +//go:build cgo +// +build cgo package ffi import ( - "github.com/filecoin-project/filecoin-ffi/generated" + "github.com/filecoin-project/filecoin-ffi/cgo" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/v5/actors/runtime/proof" - "github.com/pkg/errors" ) type FallbackChallenges struct { @@ -14,8 +14,6 @@ type FallbackChallenges struct { Challenges map[abi.SectorNumber][]uint64 } -type VanillaProof []byte - // GenerateWinningPoStSectorChallenge func GeneratePoStFallbackSectorChallenges( proofType abi.RegisteredPoStProof, @@ -33,35 +31,26 @@ func GeneratePoStFallbackSectorChallenges( return nil, err } - secIds := make([]uint64, len(sectorIds)) - for i, sid := range sectorIds { - secIds[i] = uint64(sid) + // this should be a simple cast.. + sectorIdsRaw := make([]uint64, len(sectorIds)) + for i := range sectorIds { + sectorIdsRaw[i] = uint64(sectorIds[i]) } - resp := generated.FilGenerateFallbackSectorChallenges( - pp, to32ByteArray(randomness), secIds, uint(len(secIds)), - proverID, - ) - resp.Deref() - resp.IdsPtr = resp.IdsPtr[:resp.IdsLen] - resp.ChallengesPtr = resp.ChallengesPtr[:resp.ChallengesLen] - - defer generated.FilDestroyGenerateFallbackSectorChallengesResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + randomnessBytes := cgo.AsByteArray32(randomness) + ids, challenges, err := cgo.GenerateFallbackSectorChallenges(pp, &randomnessBytes, cgo.AsSliceRefUint64(sectorIdsRaw), &proverID) + if err != nil { + return nil, err } - // copy from C memory space to Go - - var out FallbackChallenges - out.Sectors = make([]abi.SectorNumber, resp.IdsLen) - out.Challenges = make(map[abi.SectorNumber][]uint64) - stride := int(resp.ChallengesStride) - for idx := range resp.IdsPtr { - secNum := abi.SectorNumber(resp.IdsPtr[idx]) + out := FallbackChallenges{ + Sectors: make([]abi.SectorNumber, len(ids)), + Challenges: make(map[abi.SectorNumber][]uint64), + } + for idx := range ids { + secNum := abi.SectorNumber(ids[idx]) out.Sectors[idx] = secNum - out.Challenges[secNum] = append([]uint64{}, resp.ChallengesPtr[idx*stride:(idx+1)*stride]...) + out.Challenges[secNum] = challenges[idx] } return &out, nil @@ -69,26 +58,15 @@ func GeneratePoStFallbackSectorChallenges( func GenerateSingleVanillaProof( replica PrivateSectorInfo, - challange []uint64, + challenges []uint64, ) ([]byte, error) { - rep, free, err := toFilPrivateReplicaInfo(replica) + rep, err := toFilPrivateReplicaInfo(replica) if err != nil { return nil, err } - defer free() - - resp := generated.FilGenerateSingleVanillaProof(rep, challange, uint(len(challange))) - resp.Deref() - defer generated.FilDestroyGenerateSingleVanillaProofResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - resp.VanillaProof.Deref() - return copyBytes(resp.VanillaProof.ProofPtr, resp.VanillaProof.ProofLen), nil + return cgo.GenerateSingleVanillaProof(rep, cgo.AsSliceRefUint64(challenges)) } func GenerateWinningPoStWithVanilla( @@ -106,26 +84,16 @@ func GenerateWinningPoStWithVanilla( if err != nil { return nil, err } - fproofs, discard := toVanillaProofs(proofs) - defer discard() - - resp := generated.FilGenerateWinningPostWithVanilla( - pp, - to32ByteArray(randomness), - proverID, - fproofs, uint(len(proofs)), - ) - resp.Deref() - resp.ProofsPtr = make([]generated.FilPoStProof, resp.ProofsLen) - resp.Deref() + fproofs, cleanup := toVanillaProofs(proofs) + defer cleanup() - defer generated.FilDestroyGenerateWinningPostResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + randomnessBytes := cgo.AsByteArray32(randomness) + resp, err := cgo.GenerateWinningPoStWithVanilla(pp, &randomnessBytes, &proverID, cgo.AsSliceRefSliceBoxedUint8(fproofs)) + if err != nil { + return nil, err } - out, err := fromFilPoStProofs(resp.ProofsPtr) + out, err := fromFilPoStProofs(resp) if err != nil { return nil, err } @@ -148,26 +116,16 @@ func GenerateWindowPoStWithVanilla( if err != nil { return nil, err } - fproofs, discard := toVanillaProofs(proofs) - defer discard() + fproofs, cleaner := toVanillaProofs(proofs) + defer cleaner() - resp := generated.FilGenerateWindowPostWithVanilla( - pp, - to32ByteArray(randomness), - proverID, - fproofs, uint(len(proofs)), - ) - resp.Deref() - resp.ProofsPtr = make([]generated.FilPoStProof, resp.ProofsLen) - resp.Deref() - - defer generated.FilDestroyGenerateWindowPostResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + randomnessBytes := cgo.AsByteArray32(randomness) + rawProofs, _, err := cgo.GenerateWindowPoStWithVanilla(pp, &randomnessBytes, &proverID, cgo.AsSliceRefSliceBoxedUint8(fproofs)) + if err != nil { + return nil, err } - out, err := fromFilPoStProofs(resp.ProofsPtr) + out, err := fromFilPoStProofs(rawProofs) if err != nil { return nil, err } @@ -193,33 +151,29 @@ func GenerateSinglePartitionWindowPoStWithVanilla( if err != nil { return nil, err } - fproofs, discard := toVanillaProofs(proofs) - defer discard() + fproofs, cleaner := toVanillaProofs(proofs) + defer cleaner() - resp := generated.FilGenerateSingleWindowPostWithVanilla( + randomnessBytes := cgo.AsByteArray32(randomness) + resp, _, err := cgo.GenerateSingleWindowPoStWithVanilla( pp, - to32ByteArray(randomness), - proverID, - fproofs, uint(len(proofs)), + &randomnessBytes, + &proverID, + cgo.AsSliceRefSliceBoxedUint8(fproofs), partitionIndex, ) - resp.Deref() - resp.PartitionProof.Deref() - - defer generated.FilDestroyGenerateSingleWindowPostWithVanillaResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + if err != nil { + return nil, err } - dpp, err := fromFilRegisteredPoStProof(resp.PartitionProof.RegisteredProof) + dpp, err := fromFilRegisteredPoStProof(resp.RegisteredProof) if err != nil { return nil, err } out := PartitionProof{ PoStProof: dpp, - ProofBytes: copyBytes(resp.PartitionProof.ProofPtr, resp.PartitionProof.ProofLen), + ProofBytes: resp.Proof, } return &out, nil @@ -234,34 +188,32 @@ func MergeWindowPoStPartitionProofs( return nil, err } - fproofs, discard, err := toPartitionProofs(partitionProofs) - defer discard() + fproofs, cleaner := toPartitionProofs(partitionProofs) + defer cleaner() + + resp, err := cgo.MergeWindowPoStPartitionProofs(pp, cgo.AsSliceRefSliceBoxedUint8(fproofs)) if err != nil { return nil, err } - resp := generated.FilMergeWindowPostPartitionProofs( - pp, - fproofs, uint(len(fproofs)), - ) - resp.Deref() - resp.Proof.Deref() - - defer generated.FilDestroyMergeWindowPostPartitionProofsResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - dpp, err := fromFilRegisteredPoStProof(resp.Proof.RegisteredProof) + dpp, err := fromFilRegisteredPoStProof(resp.RegisteredProof) if err != nil { return nil, err } out := proof.PoStProof{ PoStProof: dpp, - ProofBytes: copyBytes(resp.Proof.ProofPtr, resp.Proof.ProofLen), + ProofBytes: resp.Proof, } return &out, nil } + +func toPartitionProofs(src []PartitionProof) ([]cgo.SliceBoxedUint8, func()) { + out := make([]cgo.SliceBoxedUint8, len(src)) + for idx := range out { + out[idx] = cgo.AllocSliceBoxedUint8(src[idx].ProofBytes) + } + + return out, makeCleanerSBU(out, len(src)) +} diff --git a/filcrypto.yml b/filcrypto.yml deleted file mode 100644 index aca48a51..00000000 --- a/filcrypto.yml +++ /dev/null @@ -1,50 +0,0 @@ ---- -GENERATOR: - PackageName: generated - PackageDescription: - PackageLicense: - Options: - SafeStrings: true - Includes: - - ../filcrypto.h - FlagGroups: - - name: LDFLAGS - traits: ["linux"] - flags: - - "-L${SRCDIR}/.." - - "-Wl,-unresolved-symbols=ignore-all" - - name: LDFLAGS - traits: ["darwin"] - flags: - - "-L${SRCDIR}/.." - - "-Wl,-undefined,dynamic_lookup" - - name: pkg-config - flags: - - "${SRCDIR}/../filcrypto.pc" - -PARSER: - Defines: - IncludePaths: - - ./headerstubs/ - SourcesPaths: - - ./filcrypto.h - -TRANSLATOR: - ConstCharIsString: true - ConstUCharIsString: false - ConstRules: - defines: expand - enum: cgo - PtrTips: - function: - - {target: "^fil_destroy", tips: [ref]} - Rules: - global: - - {action: accept, from: "^fil"} - - {action: accept, from: "^FCPResponseStatus"} - - {transform: export} - private: - - {transform: unexport} - post-global: - - {transform: export} - - {load: snakecase} diff --git a/fvm.go b/fvm.go index f2bbeb05..607f03d4 100644 --- a/fvm.go +++ b/fvm.go @@ -13,10 +13,8 @@ import ( "context" gobig "math/big" "runtime" - "unsafe" "github.com/filecoin-project/filecoin-ffi/cgo" - "github.com/filecoin-project/filecoin-ffi/generated" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/go-state-types/big" "github.com/filecoin-project/go-state-types/network" @@ -25,7 +23,7 @@ import ( ) type FVM struct { - executor unsafe.Pointer + executor *cgo.FvmMachine } const ( @@ -58,30 +56,24 @@ func CreateFVM(opts *FVMOpts) (*FVM, error) { } exHandle := cgo.Register(context.TODO(), opts.Externs) - resp := generated.FilCreateFvmMachine(generated.FilFvmRegisteredVersion(opts.FVMVersion), + executor, err := cgo.CreateFvmMachine(cgo.FvmRegisteredVersion(opts.FVMVersion), uint64(opts.Epoch), baseFeeHi, baseFeeLo, baseCircSupplyHi, baseCircSupplyLo, uint64(opts.NetworkVersion), - opts.StateBase.Bytes(), - uint(opts.StateBase.ByteLen()), - opts.Manifest.Bytes(), - uint(opts.Manifest.ByteLen()), + cgo.AsSliceRefUint8(opts.StateBase.Bytes()), + cgo.AsSliceRefUint8(opts.Manifest.Bytes()), opts.Tracing, exHandle, exHandle, ) - resp.Deref() - - defer generated.FilDestroyCreateFvmMachineResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, xerrors.New(generated.RawString(resp.ErrorMsg).Copy()) + if err != nil { + return nil, err } fvm := &FVM{ - executor: resp.Executor, + executor: executor, } runtime.SetFinalizer(fvm, func(f *FVM) { // Just to be extra safe @@ -91,7 +83,7 @@ func CreateFVM(opts *FVMOpts) (*FVM, error) { executor := f.executor f.executor = nil - generated.FilDropFvmMachine(executor) + executor.Destroy() cgo.Unregister(exHandle) }) @@ -104,70 +96,57 @@ func (f *FVM) ApplyMessage(msgBytes []byte, chainLen uint) (*ApplyRet, error) { // collect the FVM, causing us to run the finalizer while we're in the middle of using the // FVM. defer runtime.KeepAlive(f) - resp := generated.FilFvmMachineExecuteMessage(f.executor, - msgBytes, - uint(len(msgBytes)), + resp, err := cgo.FvmMachineExecuteMessage( + f.executor, + cgo.AsSliceRefUint8(msgBytes), uint64(chainLen), applyExplicit, ) - resp.Deref() - - defer generated.FilDestroyFvmMachineExecuteResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, xerrors.New(generated.RawString(resp.ErrorMsg).Copy()) + if err != nil { + return nil, err } return &ApplyRet{ - Return: copyBytes(resp.ReturnPtr, resp.ReturnLen), + Return: resp.ReturnVal, ExitCode: resp.ExitCode, GasUsed: int64(resp.GasUsed), MinerPenalty: reformBigInt(resp.PenaltyHi, resp.PenaltyLo), MinerTip: reformBigInt(resp.MinerTipHi, resp.MinerTipLo), - ExecTraceBytes: copyBytes(resp.ExecTracePtr, resp.ExecTraceLen), - FailureInfo: string(copyBytes(resp.FailureInfoPtr, resp.FailureInfoLen)), + ExecTraceBytes: resp.ExecTrace, + FailureInfo: resp.FailureInfo, }, nil } func (f *FVM) ApplyImplicitMessage(msgBytes []byte) (*ApplyRet, error) { defer runtime.KeepAlive(f) - resp := generated.FilFvmMachineExecuteMessage(f.executor, - msgBytes, - uint(len(msgBytes)), + resp, err := cgo.FvmMachineExecuteMessage( + f.executor, + cgo.AsSliceRefUint8(msgBytes), 0, // this isn't an on-chain message, so it has no chain length. applyImplicit, ) - resp.Deref() - - defer generated.FilDestroyFvmMachineExecuteResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, xerrors.New(generated.RawString(resp.ErrorMsg).Copy()) + if err != nil { + return nil, err } return &ApplyRet{ - Return: copyBytes(resp.ReturnPtr, resp.ReturnLen), + Return: resp.ReturnVal, ExitCode: resp.ExitCode, GasUsed: int64(resp.GasUsed), MinerPenalty: reformBigInt(resp.PenaltyHi, resp.PenaltyLo), MinerTip: reformBigInt(resp.MinerTipHi, resp.MinerTipLo), - FailureInfo: string(copyBytes(resp.FailureInfoPtr, resp.FailureInfoLen)), + FailureInfo: resp.FailureInfo, }, nil } func (f *FVM) Flush() (cid.Cid, error) { defer runtime.KeepAlive(f) - resp := generated.FilFvmMachineFlush(f.executor) - resp.Deref() - - defer generated.FilDestroyFvmMachineFlushResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, xerrors.New(generated.RawString(resp.ErrorMsg).Copy()) + stateRoot, err := cgo.FvmMachineFlush(f.executor) + if err != nil { + return cid.Undef, err } - // cast will copy internally. - return cid.Cast(resp.StateRootPtr[:resp.StateRootLen]) + return cid.Cast(stateRoot) } type ApplyRet struct { diff --git a/generated/cgo_helpers.go b/generated/cgo_helpers.go deleted file mode 100644 index c427aab0..00000000 --- a/generated/cgo_helpers.go +++ /dev/null @@ -1,6182 +0,0 @@ -// WARNING: This file has automatically been generated -// Code generated by https://git.io/c-for-go. DO NOT EDIT. - -package generated - -/* -#cgo linux LDFLAGS: -L${SRCDIR}/.. -Wl,-unresolved-symbols=ignore-all -#cgo darwin LDFLAGS: -L${SRCDIR}/.. -Wl,-undefined,dynamic_lookup -#cgo pkg-config: ${SRCDIR}/../filcrypto.pc -#include "../filcrypto.h" -#include -#include "cgo_helpers.h" -*/ -import "C" -import ( - "fmt" - "runtime" - "sync" - "unsafe" -) - -// cgoAllocMap stores pointers to C allocated memory for future reference. -type cgoAllocMap struct { - mux sync.RWMutex - m map[unsafe.Pointer]struct{} -} - -var cgoAllocsUnknown = new(cgoAllocMap) - -func (a *cgoAllocMap) Add(ptr unsafe.Pointer) { - a.mux.Lock() - if a.m == nil { - a.m = make(map[unsafe.Pointer]struct{}) - } - a.m[ptr] = struct{}{} - a.mux.Unlock() -} - -func (a *cgoAllocMap) IsEmpty() bool { - a.mux.RLock() - isEmpty := len(a.m) == 0 - a.mux.RUnlock() - return isEmpty -} - -func (a *cgoAllocMap) Borrow(b *cgoAllocMap) { - if b == nil || b.IsEmpty() { - return - } - b.mux.Lock() - a.mux.Lock() - for ptr := range b.m { - if a.m == nil { - a.m = make(map[unsafe.Pointer]struct{}) - } - a.m[ptr] = struct{}{} - delete(b.m, ptr) - } - a.mux.Unlock() - b.mux.Unlock() -} - -func (a *cgoAllocMap) Free() { - a.mux.Lock() - for ptr := range a.m { - C.free(ptr) - delete(a.m, ptr) - } - a.mux.Unlock() -} - -// allocFilBLSDigestMemory allocates memory for type C.fil_BLSDigest in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilBLSDigestMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilBLSDigestValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilBLSDigestValue = unsafe.Sizeof([1]C.fil_BLSDigest{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilBLSDigest) Ref() *C.fil_BLSDigest { - if x == nil { - return nil - } - return x.ref215fc78c -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilBLSDigest) Free() { - if x != nil && x.allocs215fc78c != nil { - x.allocs215fc78c.(*cgoAllocMap).Free() - x.ref215fc78c = nil - } -} - -// NewFilBLSDigestRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilBLSDigestRef(ref unsafe.Pointer) *FilBLSDigest { - if ref == nil { - return nil - } - obj := new(FilBLSDigest) - obj.ref215fc78c = (*C.fil_BLSDigest)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilBLSDigest) PassRef() (*C.fil_BLSDigest, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref215fc78c != nil { - return x.ref215fc78c, nil - } - mem215fc78c := allocFilBLSDigestMemory(1) - ref215fc78c := (*C.fil_BLSDigest)(mem215fc78c) - allocs215fc78c := new(cgoAllocMap) - allocs215fc78c.Add(mem215fc78c) - - var cinner_allocs *cgoAllocMap - ref215fc78c.inner, cinner_allocs = *(*[96]C.uint8_t)(unsafe.Pointer(&x.Inner)), cgoAllocsUnknown - allocs215fc78c.Borrow(cinner_allocs) - - x.ref215fc78c = ref215fc78c - x.allocs215fc78c = allocs215fc78c - return ref215fc78c, allocs215fc78c - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilBLSDigest) PassValue() (C.fil_BLSDigest, *cgoAllocMap) { - if x.ref215fc78c != nil { - return *x.ref215fc78c, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilBLSDigest) Deref() { - if x.ref215fc78c == nil { - return - } - x.Inner = *(*[96]byte)(unsafe.Pointer(&x.ref215fc78c.inner)) -} - -// allocFilHashResponseMemory allocates memory for type C.fil_HashResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilHashResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilHashResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilHashResponseValue = unsafe.Sizeof([1]C.fil_HashResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilHashResponse) Ref() *C.fil_HashResponse { - if x == nil { - return nil - } - return x.refc52a22ef -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilHashResponse) Free() { - if x != nil && x.allocsc52a22ef != nil { - x.allocsc52a22ef.(*cgoAllocMap).Free() - x.refc52a22ef = nil - } -} - -// NewFilHashResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilHashResponseRef(ref unsafe.Pointer) *FilHashResponse { - if ref == nil { - return nil - } - obj := new(FilHashResponse) - obj.refc52a22ef = (*C.fil_HashResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilHashResponse) PassRef() (*C.fil_HashResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refc52a22ef != nil { - return x.refc52a22ef, nil - } - memc52a22ef := allocFilHashResponseMemory(1) - refc52a22ef := (*C.fil_HashResponse)(memc52a22ef) - allocsc52a22ef := new(cgoAllocMap) - allocsc52a22ef.Add(memc52a22ef) - - var cdigest_allocs *cgoAllocMap - refc52a22ef.digest, cdigest_allocs = x.Digest.PassValue() - allocsc52a22ef.Borrow(cdigest_allocs) - - x.refc52a22ef = refc52a22ef - x.allocsc52a22ef = allocsc52a22ef - return refc52a22ef, allocsc52a22ef - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilHashResponse) PassValue() (C.fil_HashResponse, *cgoAllocMap) { - if x.refc52a22ef != nil { - return *x.refc52a22ef, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilHashResponse) Deref() { - if x.refc52a22ef == nil { - return - } - x.Digest = *NewFilBLSDigestRef(unsafe.Pointer(&x.refc52a22ef.digest)) -} - -// allocFilBLSSignatureMemory allocates memory for type C.fil_BLSSignature in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilBLSSignatureMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilBLSSignatureValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilBLSSignatureValue = unsafe.Sizeof([1]C.fil_BLSSignature{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilBLSSignature) Ref() *C.fil_BLSSignature { - if x == nil { - return nil - } - return x.refa2ac09ba -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilBLSSignature) Free() { - if x != nil && x.allocsa2ac09ba != nil { - x.allocsa2ac09ba.(*cgoAllocMap).Free() - x.refa2ac09ba = nil - } -} - -// NewFilBLSSignatureRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilBLSSignatureRef(ref unsafe.Pointer) *FilBLSSignature { - if ref == nil { - return nil - } - obj := new(FilBLSSignature) - obj.refa2ac09ba = (*C.fil_BLSSignature)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilBLSSignature) PassRef() (*C.fil_BLSSignature, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refa2ac09ba != nil { - return x.refa2ac09ba, nil - } - mema2ac09ba := allocFilBLSSignatureMemory(1) - refa2ac09ba := (*C.fil_BLSSignature)(mema2ac09ba) - allocsa2ac09ba := new(cgoAllocMap) - allocsa2ac09ba.Add(mema2ac09ba) - - var cinner_allocs *cgoAllocMap - refa2ac09ba.inner, cinner_allocs = *(*[96]C.uint8_t)(unsafe.Pointer(&x.Inner)), cgoAllocsUnknown - allocsa2ac09ba.Borrow(cinner_allocs) - - x.refa2ac09ba = refa2ac09ba - x.allocsa2ac09ba = allocsa2ac09ba - return refa2ac09ba, allocsa2ac09ba - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilBLSSignature) PassValue() (C.fil_BLSSignature, *cgoAllocMap) { - if x.refa2ac09ba != nil { - return *x.refa2ac09ba, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilBLSSignature) Deref() { - if x.refa2ac09ba == nil { - return - } - x.Inner = *(*[96]byte)(unsafe.Pointer(&x.refa2ac09ba.inner)) -} - -// allocFilAggregateResponseMemory allocates memory for type C.fil_AggregateResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilAggregateResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilAggregateResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilAggregateResponseValue = unsafe.Sizeof([1]C.fil_AggregateResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilAggregateResponse) Ref() *C.fil_AggregateResponse { - if x == nil { - return nil - } - return x.refb3efa36d -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilAggregateResponse) Free() { - if x != nil && x.allocsb3efa36d != nil { - x.allocsb3efa36d.(*cgoAllocMap).Free() - x.refb3efa36d = nil - } -} - -// NewFilAggregateResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilAggregateResponseRef(ref unsafe.Pointer) *FilAggregateResponse { - if ref == nil { - return nil - } - obj := new(FilAggregateResponse) - obj.refb3efa36d = (*C.fil_AggregateResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilAggregateResponse) PassRef() (*C.fil_AggregateResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refb3efa36d != nil { - return x.refb3efa36d, nil - } - memb3efa36d := allocFilAggregateResponseMemory(1) - refb3efa36d := (*C.fil_AggregateResponse)(memb3efa36d) - allocsb3efa36d := new(cgoAllocMap) - allocsb3efa36d.Add(memb3efa36d) - - var csignature_allocs *cgoAllocMap - refb3efa36d.signature, csignature_allocs = x.Signature.PassValue() - allocsb3efa36d.Borrow(csignature_allocs) - - x.refb3efa36d = refb3efa36d - x.allocsb3efa36d = allocsb3efa36d - return refb3efa36d, allocsb3efa36d - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilAggregateResponse) PassValue() (C.fil_AggregateResponse, *cgoAllocMap) { - if x.refb3efa36d != nil { - return *x.refb3efa36d, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilAggregateResponse) Deref() { - if x.refb3efa36d == nil { - return - } - x.Signature = *NewFilBLSSignatureRef(unsafe.Pointer(&x.refb3efa36d.signature)) -} - -// allocFilBLSPrivateKeyMemory allocates memory for type C.fil_BLSPrivateKey in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilBLSPrivateKeyMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilBLSPrivateKeyValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilBLSPrivateKeyValue = unsafe.Sizeof([1]C.fil_BLSPrivateKey{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilBLSPrivateKey) Ref() *C.fil_BLSPrivateKey { - if x == nil { - return nil - } - return x.ref2f77fe3a -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilBLSPrivateKey) Free() { - if x != nil && x.allocs2f77fe3a != nil { - x.allocs2f77fe3a.(*cgoAllocMap).Free() - x.ref2f77fe3a = nil - } -} - -// NewFilBLSPrivateKeyRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilBLSPrivateKeyRef(ref unsafe.Pointer) *FilBLSPrivateKey { - if ref == nil { - return nil - } - obj := new(FilBLSPrivateKey) - obj.ref2f77fe3a = (*C.fil_BLSPrivateKey)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilBLSPrivateKey) PassRef() (*C.fil_BLSPrivateKey, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref2f77fe3a != nil { - return x.ref2f77fe3a, nil - } - mem2f77fe3a := allocFilBLSPrivateKeyMemory(1) - ref2f77fe3a := (*C.fil_BLSPrivateKey)(mem2f77fe3a) - allocs2f77fe3a := new(cgoAllocMap) - allocs2f77fe3a.Add(mem2f77fe3a) - - var cinner_allocs *cgoAllocMap - ref2f77fe3a.inner, cinner_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.Inner)), cgoAllocsUnknown - allocs2f77fe3a.Borrow(cinner_allocs) - - x.ref2f77fe3a = ref2f77fe3a - x.allocs2f77fe3a = allocs2f77fe3a - return ref2f77fe3a, allocs2f77fe3a - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilBLSPrivateKey) PassValue() (C.fil_BLSPrivateKey, *cgoAllocMap) { - if x.ref2f77fe3a != nil { - return *x.ref2f77fe3a, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilBLSPrivateKey) Deref() { - if x.ref2f77fe3a == nil { - return - } - x.Inner = *(*[32]byte)(unsafe.Pointer(&x.ref2f77fe3a.inner)) -} - -// allocFilPrivateKeyGenerateResponseMemory allocates memory for type C.fil_PrivateKeyGenerateResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPrivateKeyGenerateResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPrivateKeyGenerateResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPrivateKeyGenerateResponseValue = unsafe.Sizeof([1]C.fil_PrivateKeyGenerateResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPrivateKeyGenerateResponse) Ref() *C.fil_PrivateKeyGenerateResponse { - if x == nil { - return nil - } - return x.ref2dba09f -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPrivateKeyGenerateResponse) Free() { - if x != nil && x.allocs2dba09f != nil { - x.allocs2dba09f.(*cgoAllocMap).Free() - x.ref2dba09f = nil - } -} - -// NewFilPrivateKeyGenerateResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPrivateKeyGenerateResponseRef(ref unsafe.Pointer) *FilPrivateKeyGenerateResponse { - if ref == nil { - return nil - } - obj := new(FilPrivateKeyGenerateResponse) - obj.ref2dba09f = (*C.fil_PrivateKeyGenerateResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPrivateKeyGenerateResponse) PassRef() (*C.fil_PrivateKeyGenerateResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref2dba09f != nil { - return x.ref2dba09f, nil - } - mem2dba09f := allocFilPrivateKeyGenerateResponseMemory(1) - ref2dba09f := (*C.fil_PrivateKeyGenerateResponse)(mem2dba09f) - allocs2dba09f := new(cgoAllocMap) - allocs2dba09f.Add(mem2dba09f) - - var cprivate_key_allocs *cgoAllocMap - ref2dba09f.private_key, cprivate_key_allocs = x.PrivateKey.PassValue() - allocs2dba09f.Borrow(cprivate_key_allocs) - - x.ref2dba09f = ref2dba09f - x.allocs2dba09f = allocs2dba09f - return ref2dba09f, allocs2dba09f - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPrivateKeyGenerateResponse) PassValue() (C.fil_PrivateKeyGenerateResponse, *cgoAllocMap) { - if x.ref2dba09f != nil { - return *x.ref2dba09f, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPrivateKeyGenerateResponse) Deref() { - if x.ref2dba09f == nil { - return - } - x.PrivateKey = *NewFilBLSPrivateKeyRef(unsafe.Pointer(&x.ref2dba09f.private_key)) -} - -// allocFil32ByteArrayMemory allocates memory for type C.fil_32ByteArray in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFil32ByteArrayMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFil32ByteArrayValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFil32ByteArrayValue = unsafe.Sizeof([1]C.fil_32ByteArray{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *Fil32ByteArray) Ref() *C.fil_32ByteArray { - if x == nil { - return nil - } - return x.ref373ec61a -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *Fil32ByteArray) Free() { - if x != nil && x.allocs373ec61a != nil { - x.allocs373ec61a.(*cgoAllocMap).Free() - x.ref373ec61a = nil - } -} - -// NewFil32ByteArrayRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFil32ByteArrayRef(ref unsafe.Pointer) *Fil32ByteArray { - if ref == nil { - return nil - } - obj := new(Fil32ByteArray) - obj.ref373ec61a = (*C.fil_32ByteArray)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *Fil32ByteArray) PassRef() (*C.fil_32ByteArray, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref373ec61a != nil { - return x.ref373ec61a, nil - } - mem373ec61a := allocFil32ByteArrayMemory(1) - ref373ec61a := (*C.fil_32ByteArray)(mem373ec61a) - allocs373ec61a := new(cgoAllocMap) - allocs373ec61a.Add(mem373ec61a) - - var cinner_allocs *cgoAllocMap - ref373ec61a.inner, cinner_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.Inner)), cgoAllocsUnknown - allocs373ec61a.Borrow(cinner_allocs) - - x.ref373ec61a = ref373ec61a - x.allocs373ec61a = allocs373ec61a - return ref373ec61a, allocs373ec61a - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x Fil32ByteArray) PassValue() (C.fil_32ByteArray, *cgoAllocMap) { - if x.ref373ec61a != nil { - return *x.ref373ec61a, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *Fil32ByteArray) Deref() { - if x.ref373ec61a == nil { - return - } - x.Inner = *(*[32]byte)(unsafe.Pointer(&x.ref373ec61a.inner)) -} - -// allocFilPrivateKeySignResponseMemory allocates memory for type C.fil_PrivateKeySignResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPrivateKeySignResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPrivateKeySignResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPrivateKeySignResponseValue = unsafe.Sizeof([1]C.fil_PrivateKeySignResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPrivateKeySignResponse) Ref() *C.fil_PrivateKeySignResponse { - if x == nil { - return nil - } - return x.refcdf97b28 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPrivateKeySignResponse) Free() { - if x != nil && x.allocscdf97b28 != nil { - x.allocscdf97b28.(*cgoAllocMap).Free() - x.refcdf97b28 = nil - } -} - -// NewFilPrivateKeySignResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPrivateKeySignResponseRef(ref unsafe.Pointer) *FilPrivateKeySignResponse { - if ref == nil { - return nil - } - obj := new(FilPrivateKeySignResponse) - obj.refcdf97b28 = (*C.fil_PrivateKeySignResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPrivateKeySignResponse) PassRef() (*C.fil_PrivateKeySignResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refcdf97b28 != nil { - return x.refcdf97b28, nil - } - memcdf97b28 := allocFilPrivateKeySignResponseMemory(1) - refcdf97b28 := (*C.fil_PrivateKeySignResponse)(memcdf97b28) - allocscdf97b28 := new(cgoAllocMap) - allocscdf97b28.Add(memcdf97b28) - - var csignature_allocs *cgoAllocMap - refcdf97b28.signature, csignature_allocs = x.Signature.PassValue() - allocscdf97b28.Borrow(csignature_allocs) - - x.refcdf97b28 = refcdf97b28 - x.allocscdf97b28 = allocscdf97b28 - return refcdf97b28, allocscdf97b28 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPrivateKeySignResponse) PassValue() (C.fil_PrivateKeySignResponse, *cgoAllocMap) { - if x.refcdf97b28 != nil { - return *x.refcdf97b28, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPrivateKeySignResponse) Deref() { - if x.refcdf97b28 == nil { - return - } - x.Signature = *NewFilBLSSignatureRef(unsafe.Pointer(&x.refcdf97b28.signature)) -} - -// allocFilBLSPublicKeyMemory allocates memory for type C.fil_BLSPublicKey in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilBLSPublicKeyMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilBLSPublicKeyValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilBLSPublicKeyValue = unsafe.Sizeof([1]C.fil_BLSPublicKey{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilBLSPublicKey) Ref() *C.fil_BLSPublicKey { - if x == nil { - return nil - } - return x.ref6d0cab13 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilBLSPublicKey) Free() { - if x != nil && x.allocs6d0cab13 != nil { - x.allocs6d0cab13.(*cgoAllocMap).Free() - x.ref6d0cab13 = nil - } -} - -// NewFilBLSPublicKeyRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilBLSPublicKeyRef(ref unsafe.Pointer) *FilBLSPublicKey { - if ref == nil { - return nil - } - obj := new(FilBLSPublicKey) - obj.ref6d0cab13 = (*C.fil_BLSPublicKey)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilBLSPublicKey) PassRef() (*C.fil_BLSPublicKey, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref6d0cab13 != nil { - return x.ref6d0cab13, nil - } - mem6d0cab13 := allocFilBLSPublicKeyMemory(1) - ref6d0cab13 := (*C.fil_BLSPublicKey)(mem6d0cab13) - allocs6d0cab13 := new(cgoAllocMap) - allocs6d0cab13.Add(mem6d0cab13) - - var cinner_allocs *cgoAllocMap - ref6d0cab13.inner, cinner_allocs = *(*[48]C.uint8_t)(unsafe.Pointer(&x.Inner)), cgoAllocsUnknown - allocs6d0cab13.Borrow(cinner_allocs) - - x.ref6d0cab13 = ref6d0cab13 - x.allocs6d0cab13 = allocs6d0cab13 - return ref6d0cab13, allocs6d0cab13 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilBLSPublicKey) PassValue() (C.fil_BLSPublicKey, *cgoAllocMap) { - if x.ref6d0cab13 != nil { - return *x.ref6d0cab13, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilBLSPublicKey) Deref() { - if x.ref6d0cab13 == nil { - return - } - x.Inner = *(*[48]byte)(unsafe.Pointer(&x.ref6d0cab13.inner)) -} - -// allocFilPrivateKeyPublicKeyResponseMemory allocates memory for type C.fil_PrivateKeyPublicKeyResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPrivateKeyPublicKeyResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPrivateKeyPublicKeyResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPrivateKeyPublicKeyResponseValue = unsafe.Sizeof([1]C.fil_PrivateKeyPublicKeyResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPrivateKeyPublicKeyResponse) Ref() *C.fil_PrivateKeyPublicKeyResponse { - if x == nil { - return nil - } - return x.refee14e59d -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPrivateKeyPublicKeyResponse) Free() { - if x != nil && x.allocsee14e59d != nil { - x.allocsee14e59d.(*cgoAllocMap).Free() - x.refee14e59d = nil - } -} - -// NewFilPrivateKeyPublicKeyResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPrivateKeyPublicKeyResponseRef(ref unsafe.Pointer) *FilPrivateKeyPublicKeyResponse { - if ref == nil { - return nil - } - obj := new(FilPrivateKeyPublicKeyResponse) - obj.refee14e59d = (*C.fil_PrivateKeyPublicKeyResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPrivateKeyPublicKeyResponse) PassRef() (*C.fil_PrivateKeyPublicKeyResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refee14e59d != nil { - return x.refee14e59d, nil - } - memee14e59d := allocFilPrivateKeyPublicKeyResponseMemory(1) - refee14e59d := (*C.fil_PrivateKeyPublicKeyResponse)(memee14e59d) - allocsee14e59d := new(cgoAllocMap) - allocsee14e59d.Add(memee14e59d) - - var cpublic_key_allocs *cgoAllocMap - refee14e59d.public_key, cpublic_key_allocs = x.PublicKey.PassValue() - allocsee14e59d.Borrow(cpublic_key_allocs) - - x.refee14e59d = refee14e59d - x.allocsee14e59d = allocsee14e59d - return refee14e59d, allocsee14e59d - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPrivateKeyPublicKeyResponse) PassValue() (C.fil_PrivateKeyPublicKeyResponse, *cgoAllocMap) { - if x.refee14e59d != nil { - return *x.refee14e59d, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPrivateKeyPublicKeyResponse) Deref() { - if x.refee14e59d == nil { - return - } - x.PublicKey = *NewFilBLSPublicKeyRef(unsafe.Pointer(&x.refee14e59d.public_key)) -} - -// allocFilZeroSignatureResponseMemory allocates memory for type C.fil_ZeroSignatureResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilZeroSignatureResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilZeroSignatureResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilZeroSignatureResponseValue = unsafe.Sizeof([1]C.fil_ZeroSignatureResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilZeroSignatureResponse) Ref() *C.fil_ZeroSignatureResponse { - if x == nil { - return nil - } - return x.ref835a0405 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilZeroSignatureResponse) Free() { - if x != nil && x.allocs835a0405 != nil { - x.allocs835a0405.(*cgoAllocMap).Free() - x.ref835a0405 = nil - } -} - -// NewFilZeroSignatureResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilZeroSignatureResponseRef(ref unsafe.Pointer) *FilZeroSignatureResponse { - if ref == nil { - return nil - } - obj := new(FilZeroSignatureResponse) - obj.ref835a0405 = (*C.fil_ZeroSignatureResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilZeroSignatureResponse) PassRef() (*C.fil_ZeroSignatureResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref835a0405 != nil { - return x.ref835a0405, nil - } - mem835a0405 := allocFilZeroSignatureResponseMemory(1) - ref835a0405 := (*C.fil_ZeroSignatureResponse)(mem835a0405) - allocs835a0405 := new(cgoAllocMap) - allocs835a0405.Add(mem835a0405) - - var csignature_allocs *cgoAllocMap - ref835a0405.signature, csignature_allocs = x.Signature.PassValue() - allocs835a0405.Borrow(csignature_allocs) - - x.ref835a0405 = ref835a0405 - x.allocs835a0405 = allocs835a0405 - return ref835a0405, allocs835a0405 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilZeroSignatureResponse) PassValue() (C.fil_ZeroSignatureResponse, *cgoAllocMap) { - if x.ref835a0405 != nil { - return *x.ref835a0405, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilZeroSignatureResponse) Deref() { - if x.ref835a0405 == nil { - return - } - x.Signature = *NewFilBLSSignatureRef(unsafe.Pointer(&x.ref835a0405.signature)) -} - -// allocFilCreateFvmMachineResponseMemory allocates memory for type C.fil_CreateFvmMachineResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilCreateFvmMachineResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilCreateFvmMachineResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilCreateFvmMachineResponseValue = unsafe.Sizeof([1]C.fil_CreateFvmMachineResponse{}) - -// unpackPCharString copies the data from Go string as *C.char. -func unpackPCharString(str string) (*C.char, *cgoAllocMap) { - allocs := new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - str = safeString(str) - mem0 := unsafe.Pointer(C.CString(str)) - allocs.Add(mem0) - return (*C.char)(mem0), allocs -} - -type stringHeader struct { - Data unsafe.Pointer - Len int -} - -// safeString ensures that the string is NULL-terminated, a NULL-terminated copy is created otherwise. -func safeString(str string) string { - if len(str) > 0 && str[len(str)-1] != '\x00' { - str = str + "\x00" - } else if len(str) == 0 { - str = "\x00" - } - return str -} - -// packPCharString creates a Go string backed by *C.char and avoids copying. -func packPCharString(p *C.char) (raw string) { - if p != nil && *p != 0 { - h := (*stringHeader)(unsafe.Pointer(&raw)) - h.Data = unsafe.Pointer(p) - for *p != 0 { - p = (*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1)) // p++ - } - h.Len = int(uintptr(unsafe.Pointer(p)) - uintptr(h.Data)) - } - return -} - -// RawString reperesents a string backed by data on the C side. -type RawString string - -// Copy returns a Go-managed copy of raw string. -func (raw RawString) Copy() string { - if len(raw) == 0 { - return "" - } - h := (*stringHeader)(unsafe.Pointer(&raw)) - return C.GoStringN((*C.char)(h.Data), C.int(h.Len)) -} - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilCreateFvmMachineResponse) Ref() *C.fil_CreateFvmMachineResponse { - if x == nil { - return nil - } - return x.ref40465416 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilCreateFvmMachineResponse) Free() { - if x != nil && x.allocs40465416 != nil { - x.allocs40465416.(*cgoAllocMap).Free() - x.ref40465416 = nil - } -} - -// NewFilCreateFvmMachineResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilCreateFvmMachineResponseRef(ref unsafe.Pointer) *FilCreateFvmMachineResponse { - if ref == nil { - return nil - } - obj := new(FilCreateFvmMachineResponse) - obj.ref40465416 = (*C.fil_CreateFvmMachineResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilCreateFvmMachineResponse) PassRef() (*C.fil_CreateFvmMachineResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref40465416 != nil { - return x.ref40465416, nil - } - mem40465416 := allocFilCreateFvmMachineResponseMemory(1) - ref40465416 := (*C.fil_CreateFvmMachineResponse)(mem40465416) - allocs40465416 := new(cgoAllocMap) - allocs40465416.Add(mem40465416) - - var cerror_msg_allocs *cgoAllocMap - ref40465416.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs40465416.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref40465416.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs40465416.Borrow(cstatus_code_allocs) - - var cexecutor_allocs *cgoAllocMap - ref40465416.executor, cexecutor_allocs = *(*unsafe.Pointer)(unsafe.Pointer(&x.Executor)), cgoAllocsUnknown - allocs40465416.Borrow(cexecutor_allocs) - - x.ref40465416 = ref40465416 - x.allocs40465416 = allocs40465416 - return ref40465416, allocs40465416 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilCreateFvmMachineResponse) PassValue() (C.fil_CreateFvmMachineResponse, *cgoAllocMap) { - if x.ref40465416 != nil { - return *x.ref40465416, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilCreateFvmMachineResponse) Deref() { - if x.ref40465416 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref40465416.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref40465416.status_code) - x.Executor = (unsafe.Pointer)(unsafe.Pointer(x.ref40465416.executor)) -} - -// allocFilFvmMachineExecuteResponseMemory allocates memory for type C.fil_FvmMachineExecuteResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilFvmMachineExecuteResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilFvmMachineExecuteResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilFvmMachineExecuteResponseValue = unsafe.Sizeof([1]C.fil_FvmMachineExecuteResponse{}) - -// copyPUint8TBytes copies the data from Go slice as *C.uint8_t. -func copyPUint8TBytes(slice *sliceHeader) (*C.uint8_t, *cgoAllocMap) { - allocs := new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - mem0 := unsafe.Pointer(C.CBytes(*(*[]byte)(unsafe.Pointer(&sliceHeader{ - Data: slice.Data, - Len: int(sizeOfUint8TValue) * slice.Len, - Cap: int(sizeOfUint8TValue) * slice.Len, - })))) - allocs.Add(mem0) - - return (*C.uint8_t)(mem0), allocs -} - -type sliceHeader struct { - Data unsafe.Pointer - Len int - Cap int -} - -// allocUint8TMemory allocates memory for type C.uint8_t in C. -// The caller is responsible for freeing the this memory via C.free. -func allocUint8TMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfUint8TValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfUint8TValue = unsafe.Sizeof([1]C.uint8_t{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilFvmMachineExecuteResponse) Ref() *C.fil_FvmMachineExecuteResponse { - if x == nil { - return nil - } - return x.ref88f63595 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilFvmMachineExecuteResponse) Free() { - if x != nil && x.allocs88f63595 != nil { - x.allocs88f63595.(*cgoAllocMap).Free() - x.ref88f63595 = nil - } -} - -// NewFilFvmMachineExecuteResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilFvmMachineExecuteResponseRef(ref unsafe.Pointer) *FilFvmMachineExecuteResponse { - if ref == nil { - return nil - } - obj := new(FilFvmMachineExecuteResponse) - obj.ref88f63595 = (*C.fil_FvmMachineExecuteResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilFvmMachineExecuteResponse) PassRef() (*C.fil_FvmMachineExecuteResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref88f63595 != nil { - return x.ref88f63595, nil - } - mem88f63595 := allocFilFvmMachineExecuteResponseMemory(1) - ref88f63595 := (*C.fil_FvmMachineExecuteResponse)(mem88f63595) - allocs88f63595 := new(cgoAllocMap) - allocs88f63595.Add(mem88f63595) - - var cerror_msg_allocs *cgoAllocMap - ref88f63595.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs88f63595.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref88f63595.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs88f63595.Borrow(cstatus_code_allocs) - - var cexit_code_allocs *cgoAllocMap - ref88f63595.exit_code, cexit_code_allocs = (C.uint64_t)(x.ExitCode), cgoAllocsUnknown - allocs88f63595.Borrow(cexit_code_allocs) - - var creturn_ptr_allocs *cgoAllocMap - ref88f63595.return_ptr, creturn_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ReturnPtr))) - allocs88f63595.Borrow(creturn_ptr_allocs) - - var creturn_len_allocs *cgoAllocMap - ref88f63595.return_len, creturn_len_allocs = (C.size_t)(x.ReturnLen), cgoAllocsUnknown - allocs88f63595.Borrow(creturn_len_allocs) - - var cgas_used_allocs *cgoAllocMap - ref88f63595.gas_used, cgas_used_allocs = (C.uint64_t)(x.GasUsed), cgoAllocsUnknown - allocs88f63595.Borrow(cgas_used_allocs) - - var cpenalty_hi_allocs *cgoAllocMap - ref88f63595.penalty_hi, cpenalty_hi_allocs = (C.uint64_t)(x.PenaltyHi), cgoAllocsUnknown - allocs88f63595.Borrow(cpenalty_hi_allocs) - - var cpenalty_lo_allocs *cgoAllocMap - ref88f63595.penalty_lo, cpenalty_lo_allocs = (C.uint64_t)(x.PenaltyLo), cgoAllocsUnknown - allocs88f63595.Borrow(cpenalty_lo_allocs) - - var cminer_tip_hi_allocs *cgoAllocMap - ref88f63595.miner_tip_hi, cminer_tip_hi_allocs = (C.uint64_t)(x.MinerTipHi), cgoAllocsUnknown - allocs88f63595.Borrow(cminer_tip_hi_allocs) - - var cminer_tip_lo_allocs *cgoAllocMap - ref88f63595.miner_tip_lo, cminer_tip_lo_allocs = (C.uint64_t)(x.MinerTipLo), cgoAllocsUnknown - allocs88f63595.Borrow(cminer_tip_lo_allocs) - - var cexec_trace_ptr_allocs *cgoAllocMap - ref88f63595.exec_trace_ptr, cexec_trace_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ExecTracePtr))) - allocs88f63595.Borrow(cexec_trace_ptr_allocs) - - var cexec_trace_len_allocs *cgoAllocMap - ref88f63595.exec_trace_len, cexec_trace_len_allocs = (C.size_t)(x.ExecTraceLen), cgoAllocsUnknown - allocs88f63595.Borrow(cexec_trace_len_allocs) - - var cfailure_info_ptr_allocs *cgoAllocMap - ref88f63595.failure_info_ptr, cfailure_info_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.FailureInfoPtr))) - allocs88f63595.Borrow(cfailure_info_ptr_allocs) - - var cfailure_info_len_allocs *cgoAllocMap - ref88f63595.failure_info_len, cfailure_info_len_allocs = (C.size_t)(x.FailureInfoLen), cgoAllocsUnknown - allocs88f63595.Borrow(cfailure_info_len_allocs) - - x.ref88f63595 = ref88f63595 - x.allocs88f63595 = allocs88f63595 - return ref88f63595, allocs88f63595 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilFvmMachineExecuteResponse) PassValue() (C.fil_FvmMachineExecuteResponse, *cgoAllocMap) { - if x.ref88f63595 != nil { - return *x.ref88f63595, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilFvmMachineExecuteResponse) Deref() { - if x.ref88f63595 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref88f63595.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref88f63595.status_code) - x.ExitCode = (uint64)(x.ref88f63595.exit_code) - hxfc4425b := (*sliceHeader)(unsafe.Pointer(&x.ReturnPtr)) - hxfc4425b.Data = unsafe.Pointer(x.ref88f63595.return_ptr) - hxfc4425b.Cap = 0x7fffffff - // hxfc4425b.Len = ? - - x.ReturnLen = (uint)(x.ref88f63595.return_len) - x.GasUsed = (uint64)(x.ref88f63595.gas_used) - x.PenaltyHi = (uint64)(x.ref88f63595.penalty_hi) - x.PenaltyLo = (uint64)(x.ref88f63595.penalty_lo) - x.MinerTipHi = (uint64)(x.ref88f63595.miner_tip_hi) - x.MinerTipLo = (uint64)(x.ref88f63595.miner_tip_lo) - hxf95e7c8 := (*sliceHeader)(unsafe.Pointer(&x.ExecTracePtr)) - hxf95e7c8.Data = unsafe.Pointer(x.ref88f63595.exec_trace_ptr) - hxf95e7c8.Cap = 0x7fffffff - // hxf95e7c8.Len = ? - - x.ExecTraceLen = (uint)(x.ref88f63595.exec_trace_len) - hxff2234b := (*sliceHeader)(unsafe.Pointer(&x.FailureInfoPtr)) - hxff2234b.Data = unsafe.Pointer(x.ref88f63595.failure_info_ptr) - hxff2234b.Cap = 0x7fffffff - // hxff2234b.Len = ? - - x.FailureInfoLen = (uint)(x.ref88f63595.failure_info_len) -} - -// allocFilFvmMachineFlushResponseMemory allocates memory for type C.fil_FvmMachineFlushResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilFvmMachineFlushResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilFvmMachineFlushResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilFvmMachineFlushResponseValue = unsafe.Sizeof([1]C.fil_FvmMachineFlushResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilFvmMachineFlushResponse) Ref() *C.fil_FvmMachineFlushResponse { - if x == nil { - return nil - } - return x.ref9eb3b4f4 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilFvmMachineFlushResponse) Free() { - if x != nil && x.allocs9eb3b4f4 != nil { - x.allocs9eb3b4f4.(*cgoAllocMap).Free() - x.ref9eb3b4f4 = nil - } -} - -// NewFilFvmMachineFlushResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilFvmMachineFlushResponseRef(ref unsafe.Pointer) *FilFvmMachineFlushResponse { - if ref == nil { - return nil - } - obj := new(FilFvmMachineFlushResponse) - obj.ref9eb3b4f4 = (*C.fil_FvmMachineFlushResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilFvmMachineFlushResponse) PassRef() (*C.fil_FvmMachineFlushResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref9eb3b4f4 != nil { - return x.ref9eb3b4f4, nil - } - mem9eb3b4f4 := allocFilFvmMachineFlushResponseMemory(1) - ref9eb3b4f4 := (*C.fil_FvmMachineFlushResponse)(mem9eb3b4f4) - allocs9eb3b4f4 := new(cgoAllocMap) - allocs9eb3b4f4.Add(mem9eb3b4f4) - - var cerror_msg_allocs *cgoAllocMap - ref9eb3b4f4.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs9eb3b4f4.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref9eb3b4f4.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs9eb3b4f4.Borrow(cstatus_code_allocs) - - var cstate_root_ptr_allocs *cgoAllocMap - ref9eb3b4f4.state_root_ptr, cstate_root_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.StateRootPtr))) - allocs9eb3b4f4.Borrow(cstate_root_ptr_allocs) - - var cstate_root_len_allocs *cgoAllocMap - ref9eb3b4f4.state_root_len, cstate_root_len_allocs = (C.size_t)(x.StateRootLen), cgoAllocsUnknown - allocs9eb3b4f4.Borrow(cstate_root_len_allocs) - - x.ref9eb3b4f4 = ref9eb3b4f4 - x.allocs9eb3b4f4 = allocs9eb3b4f4 - return ref9eb3b4f4, allocs9eb3b4f4 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilFvmMachineFlushResponse) PassValue() (C.fil_FvmMachineFlushResponse, *cgoAllocMap) { - if x.ref9eb3b4f4 != nil { - return *x.ref9eb3b4f4, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilFvmMachineFlushResponse) Deref() { - if x.ref9eb3b4f4 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref9eb3b4f4.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref9eb3b4f4.status_code) - hxff73280 := (*sliceHeader)(unsafe.Pointer(&x.StateRootPtr)) - hxff73280.Data = unsafe.Pointer(x.ref9eb3b4f4.state_root_ptr) - hxff73280.Cap = 0x7fffffff - // hxff73280.Len = ? - - x.StateRootLen = (uint)(x.ref9eb3b4f4.state_root_len) -} - -// allocFilWriteWithAlignmentResponseMemory allocates memory for type C.fil_WriteWithAlignmentResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilWriteWithAlignmentResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilWriteWithAlignmentResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilWriteWithAlignmentResponseValue = unsafe.Sizeof([1]C.fil_WriteWithAlignmentResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilWriteWithAlignmentResponse) Ref() *C.fil_WriteWithAlignmentResponse { - if x == nil { - return nil - } - return x.refa330e79 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilWriteWithAlignmentResponse) Free() { - if x != nil && x.allocsa330e79 != nil { - x.allocsa330e79.(*cgoAllocMap).Free() - x.refa330e79 = nil - } -} - -// NewFilWriteWithAlignmentResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilWriteWithAlignmentResponseRef(ref unsafe.Pointer) *FilWriteWithAlignmentResponse { - if ref == nil { - return nil - } - obj := new(FilWriteWithAlignmentResponse) - obj.refa330e79 = (*C.fil_WriteWithAlignmentResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilWriteWithAlignmentResponse) PassRef() (*C.fil_WriteWithAlignmentResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refa330e79 != nil { - return x.refa330e79, nil - } - mema330e79 := allocFilWriteWithAlignmentResponseMemory(1) - refa330e79 := (*C.fil_WriteWithAlignmentResponse)(mema330e79) - allocsa330e79 := new(cgoAllocMap) - allocsa330e79.Add(mema330e79) - - var ccomm_p_allocs *cgoAllocMap - refa330e79.comm_p, ccomm_p_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommP)), cgoAllocsUnknown - allocsa330e79.Borrow(ccomm_p_allocs) - - var cerror_msg_allocs *cgoAllocMap - refa330e79.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsa330e79.Borrow(cerror_msg_allocs) - - var cleft_alignment_unpadded_allocs *cgoAllocMap - refa330e79.left_alignment_unpadded, cleft_alignment_unpadded_allocs = (C.uint64_t)(x.LeftAlignmentUnpadded), cgoAllocsUnknown - allocsa330e79.Borrow(cleft_alignment_unpadded_allocs) - - var cstatus_code_allocs *cgoAllocMap - refa330e79.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsa330e79.Borrow(cstatus_code_allocs) - - var ctotal_write_unpadded_allocs *cgoAllocMap - refa330e79.total_write_unpadded, ctotal_write_unpadded_allocs = (C.uint64_t)(x.TotalWriteUnpadded), cgoAllocsUnknown - allocsa330e79.Borrow(ctotal_write_unpadded_allocs) - - x.refa330e79 = refa330e79 - x.allocsa330e79 = allocsa330e79 - return refa330e79, allocsa330e79 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilWriteWithAlignmentResponse) PassValue() (C.fil_WriteWithAlignmentResponse, *cgoAllocMap) { - if x.refa330e79 != nil { - return *x.refa330e79, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilWriteWithAlignmentResponse) Deref() { - if x.refa330e79 == nil { - return - } - x.CommP = *(*[32]byte)(unsafe.Pointer(&x.refa330e79.comm_p)) - x.ErrorMsg = packPCharString(x.refa330e79.error_msg) - x.LeftAlignmentUnpadded = (uint64)(x.refa330e79.left_alignment_unpadded) - x.StatusCode = (FCPResponseStatus)(x.refa330e79.status_code) - x.TotalWriteUnpadded = (uint64)(x.refa330e79.total_write_unpadded) -} - -// allocFilWriteWithoutAlignmentResponseMemory allocates memory for type C.fil_WriteWithoutAlignmentResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilWriteWithoutAlignmentResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilWriteWithoutAlignmentResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilWriteWithoutAlignmentResponseValue = unsafe.Sizeof([1]C.fil_WriteWithoutAlignmentResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilWriteWithoutAlignmentResponse) Ref() *C.fil_WriteWithoutAlignmentResponse { - if x == nil { - return nil - } - return x.refc8e1ed8 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilWriteWithoutAlignmentResponse) Free() { - if x != nil && x.allocsc8e1ed8 != nil { - x.allocsc8e1ed8.(*cgoAllocMap).Free() - x.refc8e1ed8 = nil - } -} - -// NewFilWriteWithoutAlignmentResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilWriteWithoutAlignmentResponseRef(ref unsafe.Pointer) *FilWriteWithoutAlignmentResponse { - if ref == nil { - return nil - } - obj := new(FilWriteWithoutAlignmentResponse) - obj.refc8e1ed8 = (*C.fil_WriteWithoutAlignmentResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilWriteWithoutAlignmentResponse) PassRef() (*C.fil_WriteWithoutAlignmentResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refc8e1ed8 != nil { - return x.refc8e1ed8, nil - } - memc8e1ed8 := allocFilWriteWithoutAlignmentResponseMemory(1) - refc8e1ed8 := (*C.fil_WriteWithoutAlignmentResponse)(memc8e1ed8) - allocsc8e1ed8 := new(cgoAllocMap) - allocsc8e1ed8.Add(memc8e1ed8) - - var ccomm_p_allocs *cgoAllocMap - refc8e1ed8.comm_p, ccomm_p_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommP)), cgoAllocsUnknown - allocsc8e1ed8.Borrow(ccomm_p_allocs) - - var cerror_msg_allocs *cgoAllocMap - refc8e1ed8.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsc8e1ed8.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - refc8e1ed8.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsc8e1ed8.Borrow(cstatus_code_allocs) - - var ctotal_write_unpadded_allocs *cgoAllocMap - refc8e1ed8.total_write_unpadded, ctotal_write_unpadded_allocs = (C.uint64_t)(x.TotalWriteUnpadded), cgoAllocsUnknown - allocsc8e1ed8.Borrow(ctotal_write_unpadded_allocs) - - x.refc8e1ed8 = refc8e1ed8 - x.allocsc8e1ed8 = allocsc8e1ed8 - return refc8e1ed8, allocsc8e1ed8 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilWriteWithoutAlignmentResponse) PassValue() (C.fil_WriteWithoutAlignmentResponse, *cgoAllocMap) { - if x.refc8e1ed8 != nil { - return *x.refc8e1ed8, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilWriteWithoutAlignmentResponse) Deref() { - if x.refc8e1ed8 == nil { - return - } - x.CommP = *(*[32]byte)(unsafe.Pointer(&x.refc8e1ed8.comm_p)) - x.ErrorMsg = packPCharString(x.refc8e1ed8.error_msg) - x.StatusCode = (FCPResponseStatus)(x.refc8e1ed8.status_code) - x.TotalWriteUnpadded = (uint64)(x.refc8e1ed8.total_write_unpadded) -} - -// allocFilFauxRepResponseMemory allocates memory for type C.fil_FauxRepResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilFauxRepResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilFauxRepResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilFauxRepResponseValue = unsafe.Sizeof([1]C.fil_FauxRepResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilFauxRepResponse) Ref() *C.fil_FauxRepResponse { - if x == nil { - return nil - } - return x.refaa003f71 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilFauxRepResponse) Free() { - if x != nil && x.allocsaa003f71 != nil { - x.allocsaa003f71.(*cgoAllocMap).Free() - x.refaa003f71 = nil - } -} - -// NewFilFauxRepResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilFauxRepResponseRef(ref unsafe.Pointer) *FilFauxRepResponse { - if ref == nil { - return nil - } - obj := new(FilFauxRepResponse) - obj.refaa003f71 = (*C.fil_FauxRepResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilFauxRepResponse) PassRef() (*C.fil_FauxRepResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refaa003f71 != nil { - return x.refaa003f71, nil - } - memaa003f71 := allocFilFauxRepResponseMemory(1) - refaa003f71 := (*C.fil_FauxRepResponse)(memaa003f71) - allocsaa003f71 := new(cgoAllocMap) - allocsaa003f71.Add(memaa003f71) - - var cerror_msg_allocs *cgoAllocMap - refaa003f71.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsaa003f71.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - refaa003f71.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsaa003f71.Borrow(cstatus_code_allocs) - - var ccommitment_allocs *cgoAllocMap - refaa003f71.commitment, ccommitment_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.Commitment)), cgoAllocsUnknown - allocsaa003f71.Borrow(ccommitment_allocs) - - x.refaa003f71 = refaa003f71 - x.allocsaa003f71 = allocsaa003f71 - return refaa003f71, allocsaa003f71 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilFauxRepResponse) PassValue() (C.fil_FauxRepResponse, *cgoAllocMap) { - if x.refaa003f71 != nil { - return *x.refaa003f71, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilFauxRepResponse) Deref() { - if x.refaa003f71 == nil { - return - } - x.ErrorMsg = packPCharString(x.refaa003f71.error_msg) - x.StatusCode = (FCPResponseStatus)(x.refaa003f71.status_code) - x.Commitment = *(*[32]byte)(unsafe.Pointer(&x.refaa003f71.commitment)) -} - -// allocFilSealPreCommitPhase1ResponseMemory allocates memory for type C.fil_SealPreCommitPhase1Response in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilSealPreCommitPhase1ResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilSealPreCommitPhase1ResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilSealPreCommitPhase1ResponseValue = unsafe.Sizeof([1]C.fil_SealPreCommitPhase1Response{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilSealPreCommitPhase1Response) Ref() *C.fil_SealPreCommitPhase1Response { - if x == nil { - return nil - } - return x.ref132bbfd8 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilSealPreCommitPhase1Response) Free() { - if x != nil && x.allocs132bbfd8 != nil { - x.allocs132bbfd8.(*cgoAllocMap).Free() - x.ref132bbfd8 = nil - } -} - -// NewFilSealPreCommitPhase1ResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilSealPreCommitPhase1ResponseRef(ref unsafe.Pointer) *FilSealPreCommitPhase1Response { - if ref == nil { - return nil - } - obj := new(FilSealPreCommitPhase1Response) - obj.ref132bbfd8 = (*C.fil_SealPreCommitPhase1Response)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilSealPreCommitPhase1Response) PassRef() (*C.fil_SealPreCommitPhase1Response, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref132bbfd8 != nil { - return x.ref132bbfd8, nil - } - mem132bbfd8 := allocFilSealPreCommitPhase1ResponseMemory(1) - ref132bbfd8 := (*C.fil_SealPreCommitPhase1Response)(mem132bbfd8) - allocs132bbfd8 := new(cgoAllocMap) - allocs132bbfd8.Add(mem132bbfd8) - - var cerror_msg_allocs *cgoAllocMap - ref132bbfd8.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs132bbfd8.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref132bbfd8.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs132bbfd8.Borrow(cstatus_code_allocs) - - var cseal_pre_commit_phase1_output_ptr_allocs *cgoAllocMap - ref132bbfd8.seal_pre_commit_phase1_output_ptr, cseal_pre_commit_phase1_output_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.SealPreCommitPhase1OutputPtr))) - allocs132bbfd8.Borrow(cseal_pre_commit_phase1_output_ptr_allocs) - - var cseal_pre_commit_phase1_output_len_allocs *cgoAllocMap - ref132bbfd8.seal_pre_commit_phase1_output_len, cseal_pre_commit_phase1_output_len_allocs = (C.size_t)(x.SealPreCommitPhase1OutputLen), cgoAllocsUnknown - allocs132bbfd8.Borrow(cseal_pre_commit_phase1_output_len_allocs) - - x.ref132bbfd8 = ref132bbfd8 - x.allocs132bbfd8 = allocs132bbfd8 - return ref132bbfd8, allocs132bbfd8 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilSealPreCommitPhase1Response) PassValue() (C.fil_SealPreCommitPhase1Response, *cgoAllocMap) { - if x.ref132bbfd8 != nil { - return *x.ref132bbfd8, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilSealPreCommitPhase1Response) Deref() { - if x.ref132bbfd8 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref132bbfd8.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref132bbfd8.status_code) - hxfa9955c := (*sliceHeader)(unsafe.Pointer(&x.SealPreCommitPhase1OutputPtr)) - hxfa9955c.Data = unsafe.Pointer(x.ref132bbfd8.seal_pre_commit_phase1_output_ptr) - hxfa9955c.Cap = 0x7fffffff - // hxfa9955c.Len = ? - - x.SealPreCommitPhase1OutputLen = (uint)(x.ref132bbfd8.seal_pre_commit_phase1_output_len) -} - -// allocFilPublicPieceInfoMemory allocates memory for type C.fil_PublicPieceInfo in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPublicPieceInfoMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPublicPieceInfoValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPublicPieceInfoValue = unsafe.Sizeof([1]C.fil_PublicPieceInfo{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPublicPieceInfo) Ref() *C.fil_PublicPieceInfo { - if x == nil { - return nil - } - return x.refd00025ac -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPublicPieceInfo) Free() { - if x != nil && x.allocsd00025ac != nil { - x.allocsd00025ac.(*cgoAllocMap).Free() - x.refd00025ac = nil - } -} - -// NewFilPublicPieceInfoRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPublicPieceInfoRef(ref unsafe.Pointer) *FilPublicPieceInfo { - if ref == nil { - return nil - } - obj := new(FilPublicPieceInfo) - obj.refd00025ac = (*C.fil_PublicPieceInfo)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPublicPieceInfo) PassRef() (*C.fil_PublicPieceInfo, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refd00025ac != nil { - return x.refd00025ac, nil - } - memd00025ac := allocFilPublicPieceInfoMemory(1) - refd00025ac := (*C.fil_PublicPieceInfo)(memd00025ac) - allocsd00025ac := new(cgoAllocMap) - allocsd00025ac.Add(memd00025ac) - - var cnum_bytes_allocs *cgoAllocMap - refd00025ac.num_bytes, cnum_bytes_allocs = (C.uint64_t)(x.NumBytes), cgoAllocsUnknown - allocsd00025ac.Borrow(cnum_bytes_allocs) - - var ccomm_p_allocs *cgoAllocMap - refd00025ac.comm_p, ccomm_p_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommP)), cgoAllocsUnknown - allocsd00025ac.Borrow(ccomm_p_allocs) - - x.refd00025ac = refd00025ac - x.allocsd00025ac = allocsd00025ac - return refd00025ac, allocsd00025ac - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPublicPieceInfo) PassValue() (C.fil_PublicPieceInfo, *cgoAllocMap) { - if x.refd00025ac != nil { - return *x.refd00025ac, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPublicPieceInfo) Deref() { - if x.refd00025ac == nil { - return - } - x.NumBytes = (uint64)(x.refd00025ac.num_bytes) - x.CommP = *(*[32]byte)(unsafe.Pointer(&x.refd00025ac.comm_p)) -} - -// allocFilSealPreCommitPhase2ResponseMemory allocates memory for type C.fil_SealPreCommitPhase2Response in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilSealPreCommitPhase2ResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilSealPreCommitPhase2ResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilSealPreCommitPhase2ResponseValue = unsafe.Sizeof([1]C.fil_SealPreCommitPhase2Response{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilSealPreCommitPhase2Response) Ref() *C.fil_SealPreCommitPhase2Response { - if x == nil { - return nil - } - return x.ref2aa6831d -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilSealPreCommitPhase2Response) Free() { - if x != nil && x.allocs2aa6831d != nil { - x.allocs2aa6831d.(*cgoAllocMap).Free() - x.ref2aa6831d = nil - } -} - -// NewFilSealPreCommitPhase2ResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilSealPreCommitPhase2ResponseRef(ref unsafe.Pointer) *FilSealPreCommitPhase2Response { - if ref == nil { - return nil - } - obj := new(FilSealPreCommitPhase2Response) - obj.ref2aa6831d = (*C.fil_SealPreCommitPhase2Response)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilSealPreCommitPhase2Response) PassRef() (*C.fil_SealPreCommitPhase2Response, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref2aa6831d != nil { - return x.ref2aa6831d, nil - } - mem2aa6831d := allocFilSealPreCommitPhase2ResponseMemory(1) - ref2aa6831d := (*C.fil_SealPreCommitPhase2Response)(mem2aa6831d) - allocs2aa6831d := new(cgoAllocMap) - allocs2aa6831d.Add(mem2aa6831d) - - var cerror_msg_allocs *cgoAllocMap - ref2aa6831d.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs2aa6831d.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref2aa6831d.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs2aa6831d.Borrow(cstatus_code_allocs) - - var cregistered_proof_allocs *cgoAllocMap - ref2aa6831d.registered_proof, cregistered_proof_allocs = (C.enum_fil_RegisteredSealProof)(x.RegisteredProof), cgoAllocsUnknown - allocs2aa6831d.Borrow(cregistered_proof_allocs) - - var ccomm_d_allocs *cgoAllocMap - ref2aa6831d.comm_d, ccomm_d_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommD)), cgoAllocsUnknown - allocs2aa6831d.Borrow(ccomm_d_allocs) - - var ccomm_r_allocs *cgoAllocMap - ref2aa6831d.comm_r, ccomm_r_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommR)), cgoAllocsUnknown - allocs2aa6831d.Borrow(ccomm_r_allocs) - - x.ref2aa6831d = ref2aa6831d - x.allocs2aa6831d = allocs2aa6831d - return ref2aa6831d, allocs2aa6831d - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilSealPreCommitPhase2Response) PassValue() (C.fil_SealPreCommitPhase2Response, *cgoAllocMap) { - if x.ref2aa6831d != nil { - return *x.ref2aa6831d, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilSealPreCommitPhase2Response) Deref() { - if x.ref2aa6831d == nil { - return - } - x.ErrorMsg = packPCharString(x.ref2aa6831d.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref2aa6831d.status_code) - x.RegisteredProof = (FilRegisteredSealProof)(x.ref2aa6831d.registered_proof) - x.CommD = *(*[32]byte)(unsafe.Pointer(&x.ref2aa6831d.comm_d)) - x.CommR = *(*[32]byte)(unsafe.Pointer(&x.ref2aa6831d.comm_r)) -} - -// allocFilSealCommitPhase1ResponseMemory allocates memory for type C.fil_SealCommitPhase1Response in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilSealCommitPhase1ResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilSealCommitPhase1ResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilSealCommitPhase1ResponseValue = unsafe.Sizeof([1]C.fil_SealCommitPhase1Response{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilSealCommitPhase1Response) Ref() *C.fil_SealCommitPhase1Response { - if x == nil { - return nil - } - return x.ref61ed8561 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilSealCommitPhase1Response) Free() { - if x != nil && x.allocs61ed8561 != nil { - x.allocs61ed8561.(*cgoAllocMap).Free() - x.ref61ed8561 = nil - } -} - -// NewFilSealCommitPhase1ResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilSealCommitPhase1ResponseRef(ref unsafe.Pointer) *FilSealCommitPhase1Response { - if ref == nil { - return nil - } - obj := new(FilSealCommitPhase1Response) - obj.ref61ed8561 = (*C.fil_SealCommitPhase1Response)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilSealCommitPhase1Response) PassRef() (*C.fil_SealCommitPhase1Response, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref61ed8561 != nil { - return x.ref61ed8561, nil - } - mem61ed8561 := allocFilSealCommitPhase1ResponseMemory(1) - ref61ed8561 := (*C.fil_SealCommitPhase1Response)(mem61ed8561) - allocs61ed8561 := new(cgoAllocMap) - allocs61ed8561.Add(mem61ed8561) - - var cstatus_code_allocs *cgoAllocMap - ref61ed8561.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs61ed8561.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref61ed8561.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs61ed8561.Borrow(cerror_msg_allocs) - - var cseal_commit_phase1_output_ptr_allocs *cgoAllocMap - ref61ed8561.seal_commit_phase1_output_ptr, cseal_commit_phase1_output_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.SealCommitPhase1OutputPtr))) - allocs61ed8561.Borrow(cseal_commit_phase1_output_ptr_allocs) - - var cseal_commit_phase1_output_len_allocs *cgoAllocMap - ref61ed8561.seal_commit_phase1_output_len, cseal_commit_phase1_output_len_allocs = (C.size_t)(x.SealCommitPhase1OutputLen), cgoAllocsUnknown - allocs61ed8561.Borrow(cseal_commit_phase1_output_len_allocs) - - x.ref61ed8561 = ref61ed8561 - x.allocs61ed8561 = allocs61ed8561 - return ref61ed8561, allocs61ed8561 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilSealCommitPhase1Response) PassValue() (C.fil_SealCommitPhase1Response, *cgoAllocMap) { - if x.ref61ed8561 != nil { - return *x.ref61ed8561, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilSealCommitPhase1Response) Deref() { - if x.ref61ed8561 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref61ed8561.status_code) - x.ErrorMsg = packPCharString(x.ref61ed8561.error_msg) - hxfa3f05c := (*sliceHeader)(unsafe.Pointer(&x.SealCommitPhase1OutputPtr)) - hxfa3f05c.Data = unsafe.Pointer(x.ref61ed8561.seal_commit_phase1_output_ptr) - hxfa3f05c.Cap = 0x7fffffff - // hxfa3f05c.Len = ? - - x.SealCommitPhase1OutputLen = (uint)(x.ref61ed8561.seal_commit_phase1_output_len) -} - -// allocFilAggregationInputsMemory allocates memory for type C.fil_AggregationInputs in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilAggregationInputsMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilAggregationInputsValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilAggregationInputsValue = unsafe.Sizeof([1]C.fil_AggregationInputs{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilAggregationInputs) Ref() *C.fil_AggregationInputs { - if x == nil { - return nil - } - return x.ref90b967c9 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilAggregationInputs) Free() { - if x != nil && x.allocs90b967c9 != nil { - x.allocs90b967c9.(*cgoAllocMap).Free() - x.ref90b967c9 = nil - } -} - -// NewFilAggregationInputsRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilAggregationInputsRef(ref unsafe.Pointer) *FilAggregationInputs { - if ref == nil { - return nil - } - obj := new(FilAggregationInputs) - obj.ref90b967c9 = (*C.fil_AggregationInputs)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilAggregationInputs) PassRef() (*C.fil_AggregationInputs, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref90b967c9 != nil { - return x.ref90b967c9, nil - } - mem90b967c9 := allocFilAggregationInputsMemory(1) - ref90b967c9 := (*C.fil_AggregationInputs)(mem90b967c9) - allocs90b967c9 := new(cgoAllocMap) - allocs90b967c9.Add(mem90b967c9) - - var ccomm_r_allocs *cgoAllocMap - ref90b967c9.comm_r, ccomm_r_allocs = x.CommR.PassValue() - allocs90b967c9.Borrow(ccomm_r_allocs) - - var ccomm_d_allocs *cgoAllocMap - ref90b967c9.comm_d, ccomm_d_allocs = x.CommD.PassValue() - allocs90b967c9.Borrow(ccomm_d_allocs) - - var csector_id_allocs *cgoAllocMap - ref90b967c9.sector_id, csector_id_allocs = (C.uint64_t)(x.SectorId), cgoAllocsUnknown - allocs90b967c9.Borrow(csector_id_allocs) - - var cticket_allocs *cgoAllocMap - ref90b967c9.ticket, cticket_allocs = x.Ticket.PassValue() - allocs90b967c9.Borrow(cticket_allocs) - - var cseed_allocs *cgoAllocMap - ref90b967c9.seed, cseed_allocs = x.Seed.PassValue() - allocs90b967c9.Borrow(cseed_allocs) - - x.ref90b967c9 = ref90b967c9 - x.allocs90b967c9 = allocs90b967c9 - return ref90b967c9, allocs90b967c9 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilAggregationInputs) PassValue() (C.fil_AggregationInputs, *cgoAllocMap) { - if x.ref90b967c9 != nil { - return *x.ref90b967c9, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilAggregationInputs) Deref() { - if x.ref90b967c9 == nil { - return - } - x.CommR = *NewFil32ByteArrayRef(unsafe.Pointer(&x.ref90b967c9.comm_r)) - x.CommD = *NewFil32ByteArrayRef(unsafe.Pointer(&x.ref90b967c9.comm_d)) - x.SectorId = (uint64)(x.ref90b967c9.sector_id) - x.Ticket = *NewFil32ByteArrayRef(unsafe.Pointer(&x.ref90b967c9.ticket)) - x.Seed = *NewFil32ByteArrayRef(unsafe.Pointer(&x.ref90b967c9.seed)) -} - -// allocFilSealCommitPhase2ResponseMemory allocates memory for type C.fil_SealCommitPhase2Response in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilSealCommitPhase2ResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilSealCommitPhase2ResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilSealCommitPhase2ResponseValue = unsafe.Sizeof([1]C.fil_SealCommitPhase2Response{}) - -// allocStructFilAggregationInputsMemory allocates memory for type C.struct_fil_AggregationInputs in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilAggregationInputsMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilAggregationInputsValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilAggregationInputsValue = unsafe.Sizeof([1]C.struct_fil_AggregationInputs{}) - -const sizeOfPtr = unsafe.Sizeof(&struct{}{}) - -// unpackSFilAggregationInputs transforms a sliced Go data structure into plain C format. -func unpackSFilAggregationInputs(x []FilAggregationInputs) (unpacked *C.struct_fil_AggregationInputs, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilAggregationInputsMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_AggregationInputs)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_AggregationInputs)(h.Data) - return -} - -// packSFilAggregationInputs reads sliced Go data structure out from plain C format. -func packSFilAggregationInputs(v []FilAggregationInputs, ptr0 *C.struct_fil_AggregationInputs) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilAggregationInputsValue]C.struct_fil_AggregationInputs)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilAggregationInputsRef(unsafe.Pointer(&ptr1)) - } -} - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilSealCommitPhase2Response) Ref() *C.fil_SealCommitPhase2Response { - if x == nil { - return nil - } - return x.ref5860b9a4 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilSealCommitPhase2Response) Free() { - if x != nil && x.allocs5860b9a4 != nil { - x.allocs5860b9a4.(*cgoAllocMap).Free() - x.ref5860b9a4 = nil - } -} - -// NewFilSealCommitPhase2ResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilSealCommitPhase2ResponseRef(ref unsafe.Pointer) *FilSealCommitPhase2Response { - if ref == nil { - return nil - } - obj := new(FilSealCommitPhase2Response) - obj.ref5860b9a4 = (*C.fil_SealCommitPhase2Response)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilSealCommitPhase2Response) PassRef() (*C.fil_SealCommitPhase2Response, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref5860b9a4 != nil { - return x.ref5860b9a4, nil - } - mem5860b9a4 := allocFilSealCommitPhase2ResponseMemory(1) - ref5860b9a4 := (*C.fil_SealCommitPhase2Response)(mem5860b9a4) - allocs5860b9a4 := new(cgoAllocMap) - allocs5860b9a4.Add(mem5860b9a4) - - var cstatus_code_allocs *cgoAllocMap - ref5860b9a4.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs5860b9a4.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref5860b9a4.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs5860b9a4.Borrow(cerror_msg_allocs) - - var cproof_ptr_allocs *cgoAllocMap - ref5860b9a4.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocs5860b9a4.Borrow(cproof_ptr_allocs) - - var cproof_len_allocs *cgoAllocMap - ref5860b9a4.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocs5860b9a4.Borrow(cproof_len_allocs) - - var ccommit_inputs_ptr_allocs *cgoAllocMap - ref5860b9a4.commit_inputs_ptr, ccommit_inputs_ptr_allocs = unpackSFilAggregationInputs(x.CommitInputsPtr) - allocs5860b9a4.Borrow(ccommit_inputs_ptr_allocs) - - var ccommit_inputs_len_allocs *cgoAllocMap - ref5860b9a4.commit_inputs_len, ccommit_inputs_len_allocs = (C.size_t)(x.CommitInputsLen), cgoAllocsUnknown - allocs5860b9a4.Borrow(ccommit_inputs_len_allocs) - - x.ref5860b9a4 = ref5860b9a4 - x.allocs5860b9a4 = allocs5860b9a4 - return ref5860b9a4, allocs5860b9a4 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilSealCommitPhase2Response) PassValue() (C.fil_SealCommitPhase2Response, *cgoAllocMap) { - if x.ref5860b9a4 != nil { - return *x.ref5860b9a4, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilSealCommitPhase2Response) Deref() { - if x.ref5860b9a4 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref5860b9a4.status_code) - x.ErrorMsg = packPCharString(x.ref5860b9a4.error_msg) - hxf0d18b7 := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxf0d18b7.Data = unsafe.Pointer(x.ref5860b9a4.proof_ptr) - hxf0d18b7.Cap = 0x7fffffff - // hxf0d18b7.Len = ? - - x.ProofLen = (uint)(x.ref5860b9a4.proof_len) - packSFilAggregationInputs(x.CommitInputsPtr, x.ref5860b9a4.commit_inputs_ptr) - x.CommitInputsLen = (uint)(x.ref5860b9a4.commit_inputs_len) -} - -// allocFilAggregateProofMemory allocates memory for type C.fil_AggregateProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilAggregateProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilAggregateProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilAggregateProofValue = unsafe.Sizeof([1]C.fil_AggregateProof{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilAggregateProof) Ref() *C.fil_AggregateProof { - if x == nil { - return nil - } - return x.ref22b6c4f6 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilAggregateProof) Free() { - if x != nil && x.allocs22b6c4f6 != nil { - x.allocs22b6c4f6.(*cgoAllocMap).Free() - x.ref22b6c4f6 = nil - } -} - -// NewFilAggregateProofRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilAggregateProofRef(ref unsafe.Pointer) *FilAggregateProof { - if ref == nil { - return nil - } - obj := new(FilAggregateProof) - obj.ref22b6c4f6 = (*C.fil_AggregateProof)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilAggregateProof) PassRef() (*C.fil_AggregateProof, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref22b6c4f6 != nil { - return x.ref22b6c4f6, nil - } - mem22b6c4f6 := allocFilAggregateProofMemory(1) - ref22b6c4f6 := (*C.fil_AggregateProof)(mem22b6c4f6) - allocs22b6c4f6 := new(cgoAllocMap) - allocs22b6c4f6.Add(mem22b6c4f6) - - var cstatus_code_allocs *cgoAllocMap - ref22b6c4f6.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs22b6c4f6.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref22b6c4f6.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs22b6c4f6.Borrow(cerror_msg_allocs) - - var cproof_len_allocs *cgoAllocMap - ref22b6c4f6.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocs22b6c4f6.Borrow(cproof_len_allocs) - - var cproof_ptr_allocs *cgoAllocMap - ref22b6c4f6.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocs22b6c4f6.Borrow(cproof_ptr_allocs) - - x.ref22b6c4f6 = ref22b6c4f6 - x.allocs22b6c4f6 = allocs22b6c4f6 - return ref22b6c4f6, allocs22b6c4f6 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilAggregateProof) PassValue() (C.fil_AggregateProof, *cgoAllocMap) { - if x.ref22b6c4f6 != nil { - return *x.ref22b6c4f6, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilAggregateProof) Deref() { - if x.ref22b6c4f6 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref22b6c4f6.status_code) - x.ErrorMsg = packPCharString(x.ref22b6c4f6.error_msg) - x.ProofLen = (uint)(x.ref22b6c4f6.proof_len) - hxf2fab0d := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxf2fab0d.Data = unsafe.Pointer(x.ref22b6c4f6.proof_ptr) - hxf2fab0d.Cap = 0x7fffffff - // hxf2fab0d.Len = ? - -} - -// allocFilVerifyAggregateSealProofResponseMemory allocates memory for type C.fil_VerifyAggregateSealProofResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVerifyAggregateSealProofResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVerifyAggregateSealProofResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVerifyAggregateSealProofResponseValue = unsafe.Sizeof([1]C.fil_VerifyAggregateSealProofResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVerifyAggregateSealProofResponse) Ref() *C.fil_VerifyAggregateSealProofResponse { - if x == nil { - return nil - } - return x.ref66180e0 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVerifyAggregateSealProofResponse) Free() { - if x != nil && x.allocs66180e0 != nil { - x.allocs66180e0.(*cgoAllocMap).Free() - x.ref66180e0 = nil - } -} - -// NewFilVerifyAggregateSealProofResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVerifyAggregateSealProofResponseRef(ref unsafe.Pointer) *FilVerifyAggregateSealProofResponse { - if ref == nil { - return nil - } - obj := new(FilVerifyAggregateSealProofResponse) - obj.ref66180e0 = (*C.fil_VerifyAggregateSealProofResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVerifyAggregateSealProofResponse) PassRef() (*C.fil_VerifyAggregateSealProofResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref66180e0 != nil { - return x.ref66180e0, nil - } - mem66180e0 := allocFilVerifyAggregateSealProofResponseMemory(1) - ref66180e0 := (*C.fil_VerifyAggregateSealProofResponse)(mem66180e0) - allocs66180e0 := new(cgoAllocMap) - allocs66180e0.Add(mem66180e0) - - var cstatus_code_allocs *cgoAllocMap - ref66180e0.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs66180e0.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref66180e0.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs66180e0.Borrow(cerror_msg_allocs) - - var cis_valid_allocs *cgoAllocMap - ref66180e0.is_valid, cis_valid_allocs = (C._Bool)(x.IsValid), cgoAllocsUnknown - allocs66180e0.Borrow(cis_valid_allocs) - - x.ref66180e0 = ref66180e0 - x.allocs66180e0 = allocs66180e0 - return ref66180e0, allocs66180e0 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVerifyAggregateSealProofResponse) PassValue() (C.fil_VerifyAggregateSealProofResponse, *cgoAllocMap) { - if x.ref66180e0 != nil { - return *x.ref66180e0, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVerifyAggregateSealProofResponse) Deref() { - if x.ref66180e0 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref66180e0.status_code) - x.ErrorMsg = packPCharString(x.ref66180e0.error_msg) - x.IsValid = (bool)(x.ref66180e0.is_valid) -} - -// allocFilUnsealRangeResponseMemory allocates memory for type C.fil_UnsealRangeResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilUnsealRangeResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilUnsealRangeResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilUnsealRangeResponseValue = unsafe.Sizeof([1]C.fil_UnsealRangeResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilUnsealRangeResponse) Ref() *C.fil_UnsealRangeResponse { - if x == nil { - return nil - } - return x.ref61e219c9 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilUnsealRangeResponse) Free() { - if x != nil && x.allocs61e219c9 != nil { - x.allocs61e219c9.(*cgoAllocMap).Free() - x.ref61e219c9 = nil - } -} - -// NewFilUnsealRangeResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilUnsealRangeResponseRef(ref unsafe.Pointer) *FilUnsealRangeResponse { - if ref == nil { - return nil - } - obj := new(FilUnsealRangeResponse) - obj.ref61e219c9 = (*C.fil_UnsealRangeResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilUnsealRangeResponse) PassRef() (*C.fil_UnsealRangeResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref61e219c9 != nil { - return x.ref61e219c9, nil - } - mem61e219c9 := allocFilUnsealRangeResponseMemory(1) - ref61e219c9 := (*C.fil_UnsealRangeResponse)(mem61e219c9) - allocs61e219c9 := new(cgoAllocMap) - allocs61e219c9.Add(mem61e219c9) - - var cstatus_code_allocs *cgoAllocMap - ref61e219c9.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs61e219c9.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref61e219c9.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs61e219c9.Borrow(cerror_msg_allocs) - - x.ref61e219c9 = ref61e219c9 - x.allocs61e219c9 = allocs61e219c9 - return ref61e219c9, allocs61e219c9 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilUnsealRangeResponse) PassValue() (C.fil_UnsealRangeResponse, *cgoAllocMap) { - if x.ref61e219c9 != nil { - return *x.ref61e219c9, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilUnsealRangeResponse) Deref() { - if x.ref61e219c9 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref61e219c9.status_code) - x.ErrorMsg = packPCharString(x.ref61e219c9.error_msg) -} - -// allocFilVerifySealResponseMemory allocates memory for type C.fil_VerifySealResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVerifySealResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVerifySealResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVerifySealResponseValue = unsafe.Sizeof([1]C.fil_VerifySealResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVerifySealResponse) Ref() *C.fil_VerifySealResponse { - if x == nil { - return nil - } - return x.refd4397079 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVerifySealResponse) Free() { - if x != nil && x.allocsd4397079 != nil { - x.allocsd4397079.(*cgoAllocMap).Free() - x.refd4397079 = nil - } -} - -// NewFilVerifySealResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVerifySealResponseRef(ref unsafe.Pointer) *FilVerifySealResponse { - if ref == nil { - return nil - } - obj := new(FilVerifySealResponse) - obj.refd4397079 = (*C.fil_VerifySealResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVerifySealResponse) PassRef() (*C.fil_VerifySealResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refd4397079 != nil { - return x.refd4397079, nil - } - memd4397079 := allocFilVerifySealResponseMemory(1) - refd4397079 := (*C.fil_VerifySealResponse)(memd4397079) - allocsd4397079 := new(cgoAllocMap) - allocsd4397079.Add(memd4397079) - - var cstatus_code_allocs *cgoAllocMap - refd4397079.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsd4397079.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - refd4397079.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsd4397079.Borrow(cerror_msg_allocs) - - var cis_valid_allocs *cgoAllocMap - refd4397079.is_valid, cis_valid_allocs = (C._Bool)(x.IsValid), cgoAllocsUnknown - allocsd4397079.Borrow(cis_valid_allocs) - - x.refd4397079 = refd4397079 - x.allocsd4397079 = allocsd4397079 - return refd4397079, allocsd4397079 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVerifySealResponse) PassValue() (C.fil_VerifySealResponse, *cgoAllocMap) { - if x.refd4397079 != nil { - return *x.refd4397079, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVerifySealResponse) Deref() { - if x.refd4397079 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.refd4397079.status_code) - x.ErrorMsg = packPCharString(x.refd4397079.error_msg) - x.IsValid = (bool)(x.refd4397079.is_valid) -} - -// allocFilGenerateWinningPoStSectorChallengeMemory allocates memory for type C.fil_GenerateWinningPoStSectorChallenge in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateWinningPoStSectorChallengeMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateWinningPoStSectorChallengeValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateWinningPoStSectorChallengeValue = unsafe.Sizeof([1]C.fil_GenerateWinningPoStSectorChallenge{}) - -// copyPUint64TBytes copies the data from Go slice as *C.uint64_t. -func copyPUint64TBytes(slice *sliceHeader) (*C.uint64_t, *cgoAllocMap) { - allocs := new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - mem0 := unsafe.Pointer(C.CBytes(*(*[]byte)(unsafe.Pointer(&sliceHeader{ - Data: slice.Data, - Len: int(sizeOfUint64TValue) * slice.Len, - Cap: int(sizeOfUint64TValue) * slice.Len, - })))) - allocs.Add(mem0) - - return (*C.uint64_t)(mem0), allocs -} - -// allocUint64TMemory allocates memory for type C.uint64_t in C. -// The caller is responsible for freeing the this memory via C.free. -func allocUint64TMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfUint64TValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfUint64TValue = unsafe.Sizeof([1]C.uint64_t{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateWinningPoStSectorChallenge) Ref() *C.fil_GenerateWinningPoStSectorChallenge { - if x == nil { - return nil - } - return x.ref69d2a405 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateWinningPoStSectorChallenge) Free() { - if x != nil && x.allocs69d2a405 != nil { - x.allocs69d2a405.(*cgoAllocMap).Free() - x.ref69d2a405 = nil - } -} - -// NewFilGenerateWinningPoStSectorChallengeRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateWinningPoStSectorChallengeRef(ref unsafe.Pointer) *FilGenerateWinningPoStSectorChallenge { - if ref == nil { - return nil - } - obj := new(FilGenerateWinningPoStSectorChallenge) - obj.ref69d2a405 = (*C.fil_GenerateWinningPoStSectorChallenge)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateWinningPoStSectorChallenge) PassRef() (*C.fil_GenerateWinningPoStSectorChallenge, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref69d2a405 != nil { - return x.ref69d2a405, nil - } - mem69d2a405 := allocFilGenerateWinningPoStSectorChallengeMemory(1) - ref69d2a405 := (*C.fil_GenerateWinningPoStSectorChallenge)(mem69d2a405) - allocs69d2a405 := new(cgoAllocMap) - allocs69d2a405.Add(mem69d2a405) - - var cerror_msg_allocs *cgoAllocMap - ref69d2a405.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs69d2a405.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref69d2a405.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs69d2a405.Borrow(cstatus_code_allocs) - - var cids_ptr_allocs *cgoAllocMap - ref69d2a405.ids_ptr, cids_ptr_allocs = copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&x.IdsPtr))) - allocs69d2a405.Borrow(cids_ptr_allocs) - - var cids_len_allocs *cgoAllocMap - ref69d2a405.ids_len, cids_len_allocs = (C.size_t)(x.IdsLen), cgoAllocsUnknown - allocs69d2a405.Borrow(cids_len_allocs) - - x.ref69d2a405 = ref69d2a405 - x.allocs69d2a405 = allocs69d2a405 - return ref69d2a405, allocs69d2a405 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateWinningPoStSectorChallenge) PassValue() (C.fil_GenerateWinningPoStSectorChallenge, *cgoAllocMap) { - if x.ref69d2a405 != nil { - return *x.ref69d2a405, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateWinningPoStSectorChallenge) Deref() { - if x.ref69d2a405 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref69d2a405.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref69d2a405.status_code) - hxf69fe70 := (*sliceHeader)(unsafe.Pointer(&x.IdsPtr)) - hxf69fe70.Data = unsafe.Pointer(x.ref69d2a405.ids_ptr) - hxf69fe70.Cap = 0x7fffffff - // hxf69fe70.Len = ? - - x.IdsLen = (uint)(x.ref69d2a405.ids_len) -} - -// allocFilGenerateFallbackSectorChallengesResponseMemory allocates memory for type C.fil_GenerateFallbackSectorChallengesResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateFallbackSectorChallengesResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateFallbackSectorChallengesResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateFallbackSectorChallengesResponseValue = unsafe.Sizeof([1]C.fil_GenerateFallbackSectorChallengesResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateFallbackSectorChallengesResponse) Ref() *C.fil_GenerateFallbackSectorChallengesResponse { - if x == nil { - return nil - } - return x.ref7047a3fa -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateFallbackSectorChallengesResponse) Free() { - if x != nil && x.allocs7047a3fa != nil { - x.allocs7047a3fa.(*cgoAllocMap).Free() - x.ref7047a3fa = nil - } -} - -// NewFilGenerateFallbackSectorChallengesResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateFallbackSectorChallengesResponseRef(ref unsafe.Pointer) *FilGenerateFallbackSectorChallengesResponse { - if ref == nil { - return nil - } - obj := new(FilGenerateFallbackSectorChallengesResponse) - obj.ref7047a3fa = (*C.fil_GenerateFallbackSectorChallengesResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateFallbackSectorChallengesResponse) PassRef() (*C.fil_GenerateFallbackSectorChallengesResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref7047a3fa != nil { - return x.ref7047a3fa, nil - } - mem7047a3fa := allocFilGenerateFallbackSectorChallengesResponseMemory(1) - ref7047a3fa := (*C.fil_GenerateFallbackSectorChallengesResponse)(mem7047a3fa) - allocs7047a3fa := new(cgoAllocMap) - allocs7047a3fa.Add(mem7047a3fa) - - var cerror_msg_allocs *cgoAllocMap - ref7047a3fa.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs7047a3fa.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref7047a3fa.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs7047a3fa.Borrow(cstatus_code_allocs) - - var cids_ptr_allocs *cgoAllocMap - ref7047a3fa.ids_ptr, cids_ptr_allocs = copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&x.IdsPtr))) - allocs7047a3fa.Borrow(cids_ptr_allocs) - - var cids_len_allocs *cgoAllocMap - ref7047a3fa.ids_len, cids_len_allocs = (C.size_t)(x.IdsLen), cgoAllocsUnknown - allocs7047a3fa.Borrow(cids_len_allocs) - - var cchallenges_ptr_allocs *cgoAllocMap - ref7047a3fa.challenges_ptr, cchallenges_ptr_allocs = copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&x.ChallengesPtr))) - allocs7047a3fa.Borrow(cchallenges_ptr_allocs) - - var cchallenges_len_allocs *cgoAllocMap - ref7047a3fa.challenges_len, cchallenges_len_allocs = (C.size_t)(x.ChallengesLen), cgoAllocsUnknown - allocs7047a3fa.Borrow(cchallenges_len_allocs) - - var cchallenges_stride_allocs *cgoAllocMap - ref7047a3fa.challenges_stride, cchallenges_stride_allocs = (C.size_t)(x.ChallengesStride), cgoAllocsUnknown - allocs7047a3fa.Borrow(cchallenges_stride_allocs) - - x.ref7047a3fa = ref7047a3fa - x.allocs7047a3fa = allocs7047a3fa - return ref7047a3fa, allocs7047a3fa - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateFallbackSectorChallengesResponse) PassValue() (C.fil_GenerateFallbackSectorChallengesResponse, *cgoAllocMap) { - if x.ref7047a3fa != nil { - return *x.ref7047a3fa, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateFallbackSectorChallengesResponse) Deref() { - if x.ref7047a3fa == nil { - return - } - x.ErrorMsg = packPCharString(x.ref7047a3fa.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref7047a3fa.status_code) - hxf65bf54 := (*sliceHeader)(unsafe.Pointer(&x.IdsPtr)) - hxf65bf54.Data = unsafe.Pointer(x.ref7047a3fa.ids_ptr) - hxf65bf54.Cap = 0x7fffffff - // hxf65bf54.Len = ? - - x.IdsLen = (uint)(x.ref7047a3fa.ids_len) - hxf3b8dbd := (*sliceHeader)(unsafe.Pointer(&x.ChallengesPtr)) - hxf3b8dbd.Data = unsafe.Pointer(x.ref7047a3fa.challenges_ptr) - hxf3b8dbd.Cap = 0x7fffffff - // hxf3b8dbd.Len = ? - - x.ChallengesLen = (uint)(x.ref7047a3fa.challenges_len) - x.ChallengesStride = (uint)(x.ref7047a3fa.challenges_stride) -} - -// allocFilVanillaProofMemory allocates memory for type C.fil_VanillaProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVanillaProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVanillaProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVanillaProofValue = unsafe.Sizeof([1]C.fil_VanillaProof{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVanillaProof) Ref() *C.fil_VanillaProof { - if x == nil { - return nil - } - return x.refb3e7638c -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVanillaProof) Free() { - if x != nil && x.allocsb3e7638c != nil { - x.allocsb3e7638c.(*cgoAllocMap).Free() - x.refb3e7638c = nil - } -} - -// NewFilVanillaProofRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVanillaProofRef(ref unsafe.Pointer) *FilVanillaProof { - if ref == nil { - return nil - } - obj := new(FilVanillaProof) - obj.refb3e7638c = (*C.fil_VanillaProof)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVanillaProof) PassRef() (*C.fil_VanillaProof, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refb3e7638c != nil { - return x.refb3e7638c, nil - } - memb3e7638c := allocFilVanillaProofMemory(1) - refb3e7638c := (*C.fil_VanillaProof)(memb3e7638c) - allocsb3e7638c := new(cgoAllocMap) - allocsb3e7638c.Add(memb3e7638c) - - var cproof_len_allocs *cgoAllocMap - refb3e7638c.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocsb3e7638c.Borrow(cproof_len_allocs) - - var cproof_ptr_allocs *cgoAllocMap - refb3e7638c.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocsb3e7638c.Borrow(cproof_ptr_allocs) - - x.refb3e7638c = refb3e7638c - x.allocsb3e7638c = allocsb3e7638c - return refb3e7638c, allocsb3e7638c - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVanillaProof) PassValue() (C.fil_VanillaProof, *cgoAllocMap) { - if x.refb3e7638c != nil { - return *x.refb3e7638c, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVanillaProof) Deref() { - if x.refb3e7638c == nil { - return - } - x.ProofLen = (uint)(x.refb3e7638c.proof_len) - hxf7a6dff := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxf7a6dff.Data = unsafe.Pointer(x.refb3e7638c.proof_ptr) - hxf7a6dff.Cap = 0x7fffffff - // hxf7a6dff.Len = ? - -} - -// allocFilGenerateSingleVanillaProofResponseMemory allocates memory for type C.fil_GenerateSingleVanillaProofResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateSingleVanillaProofResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateSingleVanillaProofResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateSingleVanillaProofResponseValue = unsafe.Sizeof([1]C.fil_GenerateSingleVanillaProofResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateSingleVanillaProofResponse) Ref() *C.fil_GenerateSingleVanillaProofResponse { - if x == nil { - return nil - } - return x.reff9d21b04 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateSingleVanillaProofResponse) Free() { - if x != nil && x.allocsf9d21b04 != nil { - x.allocsf9d21b04.(*cgoAllocMap).Free() - x.reff9d21b04 = nil - } -} - -// NewFilGenerateSingleVanillaProofResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateSingleVanillaProofResponseRef(ref unsafe.Pointer) *FilGenerateSingleVanillaProofResponse { - if ref == nil { - return nil - } - obj := new(FilGenerateSingleVanillaProofResponse) - obj.reff9d21b04 = (*C.fil_GenerateSingleVanillaProofResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateSingleVanillaProofResponse) PassRef() (*C.fil_GenerateSingleVanillaProofResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.reff9d21b04 != nil { - return x.reff9d21b04, nil - } - memf9d21b04 := allocFilGenerateSingleVanillaProofResponseMemory(1) - reff9d21b04 := (*C.fil_GenerateSingleVanillaProofResponse)(memf9d21b04) - allocsf9d21b04 := new(cgoAllocMap) - allocsf9d21b04.Add(memf9d21b04) - - var cerror_msg_allocs *cgoAllocMap - reff9d21b04.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsf9d21b04.Borrow(cerror_msg_allocs) - - var cvanilla_proof_allocs *cgoAllocMap - reff9d21b04.vanilla_proof, cvanilla_proof_allocs = x.VanillaProof.PassValue() - allocsf9d21b04.Borrow(cvanilla_proof_allocs) - - var cstatus_code_allocs *cgoAllocMap - reff9d21b04.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsf9d21b04.Borrow(cstatus_code_allocs) - - x.reff9d21b04 = reff9d21b04 - x.allocsf9d21b04 = allocsf9d21b04 - return reff9d21b04, allocsf9d21b04 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateSingleVanillaProofResponse) PassValue() (C.fil_GenerateSingleVanillaProofResponse, *cgoAllocMap) { - if x.reff9d21b04 != nil { - return *x.reff9d21b04, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateSingleVanillaProofResponse) Deref() { - if x.reff9d21b04 == nil { - return - } - x.ErrorMsg = packPCharString(x.reff9d21b04.error_msg) - x.VanillaProof = *NewFilVanillaProofRef(unsafe.Pointer(&x.reff9d21b04.vanilla_proof)) - x.StatusCode = (FCPResponseStatus)(x.reff9d21b04.status_code) -} - -// allocFilPrivateReplicaInfoMemory allocates memory for type C.fil_PrivateReplicaInfo in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPrivateReplicaInfoMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPrivateReplicaInfoValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPrivateReplicaInfoValue = unsafe.Sizeof([1]C.fil_PrivateReplicaInfo{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPrivateReplicaInfo) Ref() *C.fil_PrivateReplicaInfo { - if x == nil { - return nil - } - return x.ref81a31e9b -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPrivateReplicaInfo) Free() { - if x != nil && x.allocs81a31e9b != nil { - x.allocs81a31e9b.(*cgoAllocMap).Free() - x.ref81a31e9b = nil - } -} - -// NewFilPrivateReplicaInfoRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPrivateReplicaInfoRef(ref unsafe.Pointer) *FilPrivateReplicaInfo { - if ref == nil { - return nil - } - obj := new(FilPrivateReplicaInfo) - obj.ref81a31e9b = (*C.fil_PrivateReplicaInfo)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPrivateReplicaInfo) PassRef() (*C.fil_PrivateReplicaInfo, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref81a31e9b != nil { - return x.ref81a31e9b, nil - } - mem81a31e9b := allocFilPrivateReplicaInfoMemory(1) - ref81a31e9b := (*C.fil_PrivateReplicaInfo)(mem81a31e9b) - allocs81a31e9b := new(cgoAllocMap) - allocs81a31e9b.Add(mem81a31e9b) - - var cregistered_proof_allocs *cgoAllocMap - ref81a31e9b.registered_proof, cregistered_proof_allocs = (C.enum_fil_RegisteredPoStProof)(x.RegisteredProof), cgoAllocsUnknown - allocs81a31e9b.Borrow(cregistered_proof_allocs) - - var ccache_dir_path_allocs *cgoAllocMap - ref81a31e9b.cache_dir_path, ccache_dir_path_allocs = unpackPCharString(x.CacheDirPath) - allocs81a31e9b.Borrow(ccache_dir_path_allocs) - - var ccomm_r_allocs *cgoAllocMap - ref81a31e9b.comm_r, ccomm_r_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommR)), cgoAllocsUnknown - allocs81a31e9b.Borrow(ccomm_r_allocs) - - var creplica_path_allocs *cgoAllocMap - ref81a31e9b.replica_path, creplica_path_allocs = unpackPCharString(x.ReplicaPath) - allocs81a31e9b.Borrow(creplica_path_allocs) - - var csector_id_allocs *cgoAllocMap - ref81a31e9b.sector_id, csector_id_allocs = (C.uint64_t)(x.SectorId), cgoAllocsUnknown - allocs81a31e9b.Borrow(csector_id_allocs) - - x.ref81a31e9b = ref81a31e9b - x.allocs81a31e9b = allocs81a31e9b - return ref81a31e9b, allocs81a31e9b - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPrivateReplicaInfo) PassValue() (C.fil_PrivateReplicaInfo, *cgoAllocMap) { - if x.ref81a31e9b != nil { - return *x.ref81a31e9b, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPrivateReplicaInfo) Deref() { - if x.ref81a31e9b == nil { - return - } - x.RegisteredProof = (FilRegisteredPoStProof)(x.ref81a31e9b.registered_proof) - x.CacheDirPath = packPCharString(x.ref81a31e9b.cache_dir_path) - x.CommR = *(*[32]byte)(unsafe.Pointer(&x.ref81a31e9b.comm_r)) - x.ReplicaPath = packPCharString(x.ref81a31e9b.replica_path) - x.SectorId = (uint64)(x.ref81a31e9b.sector_id) -} - -// allocFilPoStProofMemory allocates memory for type C.fil_PoStProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPoStProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPoStProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPoStProofValue = unsafe.Sizeof([1]C.fil_PoStProof{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPoStProof) Ref() *C.fil_PoStProof { - if x == nil { - return nil - } - return x.ref3451bfa -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPoStProof) Free() { - if x != nil && x.allocs3451bfa != nil { - x.allocs3451bfa.(*cgoAllocMap).Free() - x.ref3451bfa = nil - } -} - -// NewFilPoStProofRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPoStProofRef(ref unsafe.Pointer) *FilPoStProof { - if ref == nil { - return nil - } - obj := new(FilPoStProof) - obj.ref3451bfa = (*C.fil_PoStProof)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPoStProof) PassRef() (*C.fil_PoStProof, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref3451bfa != nil { - return x.ref3451bfa, nil - } - mem3451bfa := allocFilPoStProofMemory(1) - ref3451bfa := (*C.fil_PoStProof)(mem3451bfa) - allocs3451bfa := new(cgoAllocMap) - allocs3451bfa.Add(mem3451bfa) - - var cregistered_proof_allocs *cgoAllocMap - ref3451bfa.registered_proof, cregistered_proof_allocs = (C.enum_fil_RegisteredPoStProof)(x.RegisteredProof), cgoAllocsUnknown - allocs3451bfa.Borrow(cregistered_proof_allocs) - - var cproof_len_allocs *cgoAllocMap - ref3451bfa.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocs3451bfa.Borrow(cproof_len_allocs) - - var cproof_ptr_allocs *cgoAllocMap - ref3451bfa.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocs3451bfa.Borrow(cproof_ptr_allocs) - - x.ref3451bfa = ref3451bfa - x.allocs3451bfa = allocs3451bfa - return ref3451bfa, allocs3451bfa - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPoStProof) PassValue() (C.fil_PoStProof, *cgoAllocMap) { - if x.ref3451bfa != nil { - return *x.ref3451bfa, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPoStProof) Deref() { - if x.ref3451bfa == nil { - return - } - x.RegisteredProof = (FilRegisteredPoStProof)(x.ref3451bfa.registered_proof) - x.ProofLen = (uint)(x.ref3451bfa.proof_len) - hxfe48d67 := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxfe48d67.Data = unsafe.Pointer(x.ref3451bfa.proof_ptr) - hxfe48d67.Cap = 0x7fffffff - // hxfe48d67.Len = ? - -} - -// allocFilGenerateWinningPoStResponseMemory allocates memory for type C.fil_GenerateWinningPoStResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateWinningPoStResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateWinningPoStResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateWinningPoStResponseValue = unsafe.Sizeof([1]C.fil_GenerateWinningPoStResponse{}) - -// allocStructFilPoStProofMemory allocates memory for type C.struct_fil_PoStProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilPoStProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilPoStProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilPoStProofValue = unsafe.Sizeof([1]C.struct_fil_PoStProof{}) - -// unpackSFilPoStProof transforms a sliced Go data structure into plain C format. -func unpackSFilPoStProof(x []FilPoStProof) (unpacked *C.struct_fil_PoStProof, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPoStProofMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PoStProof)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PoStProof)(h.Data) - return -} - -// packSFilPoStProof reads sliced Go data structure out from plain C format. -func packSFilPoStProof(v []FilPoStProof, ptr0 *C.struct_fil_PoStProof) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilPoStProofValue]C.struct_fil_PoStProof)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilPoStProofRef(unsafe.Pointer(&ptr1)) - } -} - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateWinningPoStResponse) Ref() *C.fil_GenerateWinningPoStResponse { - if x == nil { - return nil - } - return x.ref1405b8ec -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateWinningPoStResponse) Free() { - if x != nil && x.allocs1405b8ec != nil { - x.allocs1405b8ec.(*cgoAllocMap).Free() - x.ref1405b8ec = nil - } -} - -// NewFilGenerateWinningPoStResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateWinningPoStResponseRef(ref unsafe.Pointer) *FilGenerateWinningPoStResponse { - if ref == nil { - return nil - } - obj := new(FilGenerateWinningPoStResponse) - obj.ref1405b8ec = (*C.fil_GenerateWinningPoStResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateWinningPoStResponse) PassRef() (*C.fil_GenerateWinningPoStResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref1405b8ec != nil { - return x.ref1405b8ec, nil - } - mem1405b8ec := allocFilGenerateWinningPoStResponseMemory(1) - ref1405b8ec := (*C.fil_GenerateWinningPoStResponse)(mem1405b8ec) - allocs1405b8ec := new(cgoAllocMap) - allocs1405b8ec.Add(mem1405b8ec) - - var cerror_msg_allocs *cgoAllocMap - ref1405b8ec.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs1405b8ec.Borrow(cerror_msg_allocs) - - var cproofs_len_allocs *cgoAllocMap - ref1405b8ec.proofs_len, cproofs_len_allocs = (C.size_t)(x.ProofsLen), cgoAllocsUnknown - allocs1405b8ec.Borrow(cproofs_len_allocs) - - var cproofs_ptr_allocs *cgoAllocMap - ref1405b8ec.proofs_ptr, cproofs_ptr_allocs = unpackSFilPoStProof(x.ProofsPtr) - allocs1405b8ec.Borrow(cproofs_ptr_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref1405b8ec.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs1405b8ec.Borrow(cstatus_code_allocs) - - x.ref1405b8ec = ref1405b8ec - x.allocs1405b8ec = allocs1405b8ec - return ref1405b8ec, allocs1405b8ec - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateWinningPoStResponse) PassValue() (C.fil_GenerateWinningPoStResponse, *cgoAllocMap) { - if x.ref1405b8ec != nil { - return *x.ref1405b8ec, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateWinningPoStResponse) Deref() { - if x.ref1405b8ec == nil { - return - } - x.ErrorMsg = packPCharString(x.ref1405b8ec.error_msg) - x.ProofsLen = (uint)(x.ref1405b8ec.proofs_len) - packSFilPoStProof(x.ProofsPtr, x.ref1405b8ec.proofs_ptr) - x.StatusCode = (FCPResponseStatus)(x.ref1405b8ec.status_code) -} - -// allocFilVerifyWinningPoStResponseMemory allocates memory for type C.fil_VerifyWinningPoStResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVerifyWinningPoStResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVerifyWinningPoStResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVerifyWinningPoStResponseValue = unsafe.Sizeof([1]C.fil_VerifyWinningPoStResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVerifyWinningPoStResponse) Ref() *C.fil_VerifyWinningPoStResponse { - if x == nil { - return nil - } - return x.refaca6860c -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVerifyWinningPoStResponse) Free() { - if x != nil && x.allocsaca6860c != nil { - x.allocsaca6860c.(*cgoAllocMap).Free() - x.refaca6860c = nil - } -} - -// NewFilVerifyWinningPoStResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVerifyWinningPoStResponseRef(ref unsafe.Pointer) *FilVerifyWinningPoStResponse { - if ref == nil { - return nil - } - obj := new(FilVerifyWinningPoStResponse) - obj.refaca6860c = (*C.fil_VerifyWinningPoStResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVerifyWinningPoStResponse) PassRef() (*C.fil_VerifyWinningPoStResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refaca6860c != nil { - return x.refaca6860c, nil - } - memaca6860c := allocFilVerifyWinningPoStResponseMemory(1) - refaca6860c := (*C.fil_VerifyWinningPoStResponse)(memaca6860c) - allocsaca6860c := new(cgoAllocMap) - allocsaca6860c.Add(memaca6860c) - - var cstatus_code_allocs *cgoAllocMap - refaca6860c.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsaca6860c.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - refaca6860c.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsaca6860c.Borrow(cerror_msg_allocs) - - var cis_valid_allocs *cgoAllocMap - refaca6860c.is_valid, cis_valid_allocs = (C._Bool)(x.IsValid), cgoAllocsUnknown - allocsaca6860c.Borrow(cis_valid_allocs) - - x.refaca6860c = refaca6860c - x.allocsaca6860c = allocsaca6860c - return refaca6860c, allocsaca6860c - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVerifyWinningPoStResponse) PassValue() (C.fil_VerifyWinningPoStResponse, *cgoAllocMap) { - if x.refaca6860c != nil { - return *x.refaca6860c, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVerifyWinningPoStResponse) Deref() { - if x.refaca6860c == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.refaca6860c.status_code) - x.ErrorMsg = packPCharString(x.refaca6860c.error_msg) - x.IsValid = (bool)(x.refaca6860c.is_valid) -} - -// allocFilPublicReplicaInfoMemory allocates memory for type C.fil_PublicReplicaInfo in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPublicReplicaInfoMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPublicReplicaInfoValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPublicReplicaInfoValue = unsafe.Sizeof([1]C.fil_PublicReplicaInfo{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPublicReplicaInfo) Ref() *C.fil_PublicReplicaInfo { - if x == nil { - return nil - } - return x.ref81b617c2 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPublicReplicaInfo) Free() { - if x != nil && x.allocs81b617c2 != nil { - x.allocs81b617c2.(*cgoAllocMap).Free() - x.ref81b617c2 = nil - } -} - -// NewFilPublicReplicaInfoRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPublicReplicaInfoRef(ref unsafe.Pointer) *FilPublicReplicaInfo { - if ref == nil { - return nil - } - obj := new(FilPublicReplicaInfo) - obj.ref81b617c2 = (*C.fil_PublicReplicaInfo)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPublicReplicaInfo) PassRef() (*C.fil_PublicReplicaInfo, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref81b617c2 != nil { - return x.ref81b617c2, nil - } - mem81b617c2 := allocFilPublicReplicaInfoMemory(1) - ref81b617c2 := (*C.fil_PublicReplicaInfo)(mem81b617c2) - allocs81b617c2 := new(cgoAllocMap) - allocs81b617c2.Add(mem81b617c2) - - var cregistered_proof_allocs *cgoAllocMap - ref81b617c2.registered_proof, cregistered_proof_allocs = (C.enum_fil_RegisteredPoStProof)(x.RegisteredProof), cgoAllocsUnknown - allocs81b617c2.Borrow(cregistered_proof_allocs) - - var ccomm_r_allocs *cgoAllocMap - ref81b617c2.comm_r, ccomm_r_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommR)), cgoAllocsUnknown - allocs81b617c2.Borrow(ccomm_r_allocs) - - var csector_id_allocs *cgoAllocMap - ref81b617c2.sector_id, csector_id_allocs = (C.uint64_t)(x.SectorId), cgoAllocsUnknown - allocs81b617c2.Borrow(csector_id_allocs) - - x.ref81b617c2 = ref81b617c2 - x.allocs81b617c2 = allocs81b617c2 - return ref81b617c2, allocs81b617c2 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPublicReplicaInfo) PassValue() (C.fil_PublicReplicaInfo, *cgoAllocMap) { - if x.ref81b617c2 != nil { - return *x.ref81b617c2, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPublicReplicaInfo) Deref() { - if x.ref81b617c2 == nil { - return - } - x.RegisteredProof = (FilRegisteredPoStProof)(x.ref81b617c2.registered_proof) - x.CommR = *(*[32]byte)(unsafe.Pointer(&x.ref81b617c2.comm_r)) - x.SectorId = (uint64)(x.ref81b617c2.sector_id) -} - -// allocFilGenerateWindowPoStResponseMemory allocates memory for type C.fil_GenerateWindowPoStResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateWindowPoStResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateWindowPoStResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateWindowPoStResponseValue = unsafe.Sizeof([1]C.fil_GenerateWindowPoStResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateWindowPoStResponse) Ref() *C.fil_GenerateWindowPoStResponse { - if x == nil { - return nil - } - return x.ref2a5f3ba8 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateWindowPoStResponse) Free() { - if x != nil && x.allocs2a5f3ba8 != nil { - x.allocs2a5f3ba8.(*cgoAllocMap).Free() - x.ref2a5f3ba8 = nil - } -} - -// NewFilGenerateWindowPoStResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateWindowPoStResponseRef(ref unsafe.Pointer) *FilGenerateWindowPoStResponse { - if ref == nil { - return nil - } - obj := new(FilGenerateWindowPoStResponse) - obj.ref2a5f3ba8 = (*C.fil_GenerateWindowPoStResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateWindowPoStResponse) PassRef() (*C.fil_GenerateWindowPoStResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref2a5f3ba8 != nil { - return x.ref2a5f3ba8, nil - } - mem2a5f3ba8 := allocFilGenerateWindowPoStResponseMemory(1) - ref2a5f3ba8 := (*C.fil_GenerateWindowPoStResponse)(mem2a5f3ba8) - allocs2a5f3ba8 := new(cgoAllocMap) - allocs2a5f3ba8.Add(mem2a5f3ba8) - - var cerror_msg_allocs *cgoAllocMap - ref2a5f3ba8.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs2a5f3ba8.Borrow(cerror_msg_allocs) - - var cproofs_len_allocs *cgoAllocMap - ref2a5f3ba8.proofs_len, cproofs_len_allocs = (C.size_t)(x.ProofsLen), cgoAllocsUnknown - allocs2a5f3ba8.Borrow(cproofs_len_allocs) - - var cproofs_ptr_allocs *cgoAllocMap - ref2a5f3ba8.proofs_ptr, cproofs_ptr_allocs = unpackSFilPoStProof(x.ProofsPtr) - allocs2a5f3ba8.Borrow(cproofs_ptr_allocs) - - var cfaulty_sectors_len_allocs *cgoAllocMap - ref2a5f3ba8.faulty_sectors_len, cfaulty_sectors_len_allocs = (C.size_t)(x.FaultySectorsLen), cgoAllocsUnknown - allocs2a5f3ba8.Borrow(cfaulty_sectors_len_allocs) - - var cfaulty_sectors_ptr_allocs *cgoAllocMap - ref2a5f3ba8.faulty_sectors_ptr, cfaulty_sectors_ptr_allocs = copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&x.FaultySectorsPtr))) - allocs2a5f3ba8.Borrow(cfaulty_sectors_ptr_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref2a5f3ba8.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs2a5f3ba8.Borrow(cstatus_code_allocs) - - x.ref2a5f3ba8 = ref2a5f3ba8 - x.allocs2a5f3ba8 = allocs2a5f3ba8 - return ref2a5f3ba8, allocs2a5f3ba8 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateWindowPoStResponse) PassValue() (C.fil_GenerateWindowPoStResponse, *cgoAllocMap) { - if x.ref2a5f3ba8 != nil { - return *x.ref2a5f3ba8, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateWindowPoStResponse) Deref() { - if x.ref2a5f3ba8 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref2a5f3ba8.error_msg) - x.ProofsLen = (uint)(x.ref2a5f3ba8.proofs_len) - packSFilPoStProof(x.ProofsPtr, x.ref2a5f3ba8.proofs_ptr) - x.FaultySectorsLen = (uint)(x.ref2a5f3ba8.faulty_sectors_len) - hxf4171bf := (*sliceHeader)(unsafe.Pointer(&x.FaultySectorsPtr)) - hxf4171bf.Data = unsafe.Pointer(x.ref2a5f3ba8.faulty_sectors_ptr) - hxf4171bf.Cap = 0x7fffffff - // hxf4171bf.Len = ? - - x.StatusCode = (FCPResponseStatus)(x.ref2a5f3ba8.status_code) -} - -// allocFilVerifyWindowPoStResponseMemory allocates memory for type C.fil_VerifyWindowPoStResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVerifyWindowPoStResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVerifyWindowPoStResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVerifyWindowPoStResponseValue = unsafe.Sizeof([1]C.fil_VerifyWindowPoStResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVerifyWindowPoStResponse) Ref() *C.fil_VerifyWindowPoStResponse { - if x == nil { - return nil - } - return x.ref34c4d49f -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVerifyWindowPoStResponse) Free() { - if x != nil && x.allocs34c4d49f != nil { - x.allocs34c4d49f.(*cgoAllocMap).Free() - x.ref34c4d49f = nil - } -} - -// NewFilVerifyWindowPoStResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVerifyWindowPoStResponseRef(ref unsafe.Pointer) *FilVerifyWindowPoStResponse { - if ref == nil { - return nil - } - obj := new(FilVerifyWindowPoStResponse) - obj.ref34c4d49f = (*C.fil_VerifyWindowPoStResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVerifyWindowPoStResponse) PassRef() (*C.fil_VerifyWindowPoStResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref34c4d49f != nil { - return x.ref34c4d49f, nil - } - mem34c4d49f := allocFilVerifyWindowPoStResponseMemory(1) - ref34c4d49f := (*C.fil_VerifyWindowPoStResponse)(mem34c4d49f) - allocs34c4d49f := new(cgoAllocMap) - allocs34c4d49f.Add(mem34c4d49f) - - var cstatus_code_allocs *cgoAllocMap - ref34c4d49f.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs34c4d49f.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref34c4d49f.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs34c4d49f.Borrow(cerror_msg_allocs) - - var cis_valid_allocs *cgoAllocMap - ref34c4d49f.is_valid, cis_valid_allocs = (C._Bool)(x.IsValid), cgoAllocsUnknown - allocs34c4d49f.Borrow(cis_valid_allocs) - - x.ref34c4d49f = ref34c4d49f - x.allocs34c4d49f = allocs34c4d49f - return ref34c4d49f, allocs34c4d49f - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVerifyWindowPoStResponse) PassValue() (C.fil_VerifyWindowPoStResponse, *cgoAllocMap) { - if x.ref34c4d49f != nil { - return *x.ref34c4d49f, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVerifyWindowPoStResponse) Deref() { - if x.ref34c4d49f == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref34c4d49f.status_code) - x.ErrorMsg = packPCharString(x.ref34c4d49f.error_msg) - x.IsValid = (bool)(x.ref34c4d49f.is_valid) -} - -// allocFilMergeWindowPoStPartitionProofsResponseMemory allocates memory for type C.fil_MergeWindowPoStPartitionProofsResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilMergeWindowPoStPartitionProofsResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilMergeWindowPoStPartitionProofsResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilMergeWindowPoStPartitionProofsResponseValue = unsafe.Sizeof([1]C.fil_MergeWindowPoStPartitionProofsResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilMergeWindowPoStPartitionProofsResponse) Ref() *C.fil_MergeWindowPoStPartitionProofsResponse { - if x == nil { - return nil - } - return x.ref3369154e -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilMergeWindowPoStPartitionProofsResponse) Free() { - if x != nil && x.allocs3369154e != nil { - x.allocs3369154e.(*cgoAllocMap).Free() - x.ref3369154e = nil - } -} - -// NewFilMergeWindowPoStPartitionProofsResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilMergeWindowPoStPartitionProofsResponseRef(ref unsafe.Pointer) *FilMergeWindowPoStPartitionProofsResponse { - if ref == nil { - return nil - } - obj := new(FilMergeWindowPoStPartitionProofsResponse) - obj.ref3369154e = (*C.fil_MergeWindowPoStPartitionProofsResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilMergeWindowPoStPartitionProofsResponse) PassRef() (*C.fil_MergeWindowPoStPartitionProofsResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref3369154e != nil { - return x.ref3369154e, nil - } - mem3369154e := allocFilMergeWindowPoStPartitionProofsResponseMemory(1) - ref3369154e := (*C.fil_MergeWindowPoStPartitionProofsResponse)(mem3369154e) - allocs3369154e := new(cgoAllocMap) - allocs3369154e.Add(mem3369154e) - - var cerror_msg_allocs *cgoAllocMap - ref3369154e.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs3369154e.Borrow(cerror_msg_allocs) - - var cproof_allocs *cgoAllocMap - ref3369154e.proof, cproof_allocs = x.Proof.PassValue() - allocs3369154e.Borrow(cproof_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref3369154e.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs3369154e.Borrow(cstatus_code_allocs) - - x.ref3369154e = ref3369154e - x.allocs3369154e = allocs3369154e - return ref3369154e, allocs3369154e - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilMergeWindowPoStPartitionProofsResponse) PassValue() (C.fil_MergeWindowPoStPartitionProofsResponse, *cgoAllocMap) { - if x.ref3369154e != nil { - return *x.ref3369154e, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilMergeWindowPoStPartitionProofsResponse) Deref() { - if x.ref3369154e == nil { - return - } - x.ErrorMsg = packPCharString(x.ref3369154e.error_msg) - x.Proof = *NewFilPoStProofRef(unsafe.Pointer(&x.ref3369154e.proof)) - x.StatusCode = (FCPResponseStatus)(x.ref3369154e.status_code) -} - -// allocFilPartitionSnarkProofMemory allocates memory for type C.fil_PartitionSnarkProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPartitionSnarkProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPartitionSnarkProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPartitionSnarkProofValue = unsafe.Sizeof([1]C.fil_PartitionSnarkProof{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPartitionSnarkProof) Ref() *C.fil_PartitionSnarkProof { - if x == nil { - return nil - } - return x.ref4de03739 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPartitionSnarkProof) Free() { - if x != nil && x.allocs4de03739 != nil { - x.allocs4de03739.(*cgoAllocMap).Free() - x.ref4de03739 = nil - } -} - -// NewFilPartitionSnarkProofRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPartitionSnarkProofRef(ref unsafe.Pointer) *FilPartitionSnarkProof { - if ref == nil { - return nil - } - obj := new(FilPartitionSnarkProof) - obj.ref4de03739 = (*C.fil_PartitionSnarkProof)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPartitionSnarkProof) PassRef() (*C.fil_PartitionSnarkProof, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref4de03739 != nil { - return x.ref4de03739, nil - } - mem4de03739 := allocFilPartitionSnarkProofMemory(1) - ref4de03739 := (*C.fil_PartitionSnarkProof)(mem4de03739) - allocs4de03739 := new(cgoAllocMap) - allocs4de03739.Add(mem4de03739) - - var cregistered_proof_allocs *cgoAllocMap - ref4de03739.registered_proof, cregistered_proof_allocs = (C.enum_fil_RegisteredPoStProof)(x.RegisteredProof), cgoAllocsUnknown - allocs4de03739.Borrow(cregistered_proof_allocs) - - var cproof_len_allocs *cgoAllocMap - ref4de03739.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocs4de03739.Borrow(cproof_len_allocs) - - var cproof_ptr_allocs *cgoAllocMap - ref4de03739.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocs4de03739.Borrow(cproof_ptr_allocs) - - x.ref4de03739 = ref4de03739 - x.allocs4de03739 = allocs4de03739 - return ref4de03739, allocs4de03739 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPartitionSnarkProof) PassValue() (C.fil_PartitionSnarkProof, *cgoAllocMap) { - if x.ref4de03739 != nil { - return *x.ref4de03739, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPartitionSnarkProof) Deref() { - if x.ref4de03739 == nil { - return - } - x.RegisteredProof = (FilRegisteredPoStProof)(x.ref4de03739.registered_proof) - x.ProofLen = (uint)(x.ref4de03739.proof_len) - hxf058b18 := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxf058b18.Data = unsafe.Pointer(x.ref4de03739.proof_ptr) - hxf058b18.Cap = 0x7fffffff - // hxf058b18.Len = ? - -} - -// allocFilGetNumPartitionForFallbackPoStResponseMemory allocates memory for type C.fil_GetNumPartitionForFallbackPoStResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGetNumPartitionForFallbackPoStResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGetNumPartitionForFallbackPoStResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGetNumPartitionForFallbackPoStResponseValue = unsafe.Sizeof([1]C.fil_GetNumPartitionForFallbackPoStResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGetNumPartitionForFallbackPoStResponse) Ref() *C.fil_GetNumPartitionForFallbackPoStResponse { - if x == nil { - return nil - } - return x.refc0084478 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGetNumPartitionForFallbackPoStResponse) Free() { - if x != nil && x.allocsc0084478 != nil { - x.allocsc0084478.(*cgoAllocMap).Free() - x.refc0084478 = nil - } -} - -// NewFilGetNumPartitionForFallbackPoStResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGetNumPartitionForFallbackPoStResponseRef(ref unsafe.Pointer) *FilGetNumPartitionForFallbackPoStResponse { - if ref == nil { - return nil - } - obj := new(FilGetNumPartitionForFallbackPoStResponse) - obj.refc0084478 = (*C.fil_GetNumPartitionForFallbackPoStResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGetNumPartitionForFallbackPoStResponse) PassRef() (*C.fil_GetNumPartitionForFallbackPoStResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refc0084478 != nil { - return x.refc0084478, nil - } - memc0084478 := allocFilGetNumPartitionForFallbackPoStResponseMemory(1) - refc0084478 := (*C.fil_GetNumPartitionForFallbackPoStResponse)(memc0084478) - allocsc0084478 := new(cgoAllocMap) - allocsc0084478.Add(memc0084478) - - var cerror_msg_allocs *cgoAllocMap - refc0084478.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsc0084478.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - refc0084478.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsc0084478.Borrow(cstatus_code_allocs) - - var cnum_partition_allocs *cgoAllocMap - refc0084478.num_partition, cnum_partition_allocs = (C.size_t)(x.NumPartition), cgoAllocsUnknown - allocsc0084478.Borrow(cnum_partition_allocs) - - x.refc0084478 = refc0084478 - x.allocsc0084478 = allocsc0084478 - return refc0084478, allocsc0084478 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGetNumPartitionForFallbackPoStResponse) PassValue() (C.fil_GetNumPartitionForFallbackPoStResponse, *cgoAllocMap) { - if x.refc0084478 != nil { - return *x.refc0084478, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGetNumPartitionForFallbackPoStResponse) Deref() { - if x.refc0084478 == nil { - return - } - x.ErrorMsg = packPCharString(x.refc0084478.error_msg) - x.StatusCode = (FCPResponseStatus)(x.refc0084478.status_code) - x.NumPartition = (uint)(x.refc0084478.num_partition) -} - -// allocFilGenerateSingleWindowPoStWithVanillaResponseMemory allocates memory for type C.fil_GenerateSingleWindowPoStWithVanillaResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateSingleWindowPoStWithVanillaResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateSingleWindowPoStWithVanillaResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateSingleWindowPoStWithVanillaResponseValue = unsafe.Sizeof([1]C.fil_GenerateSingleWindowPoStWithVanillaResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateSingleWindowPoStWithVanillaResponse) Ref() *C.fil_GenerateSingleWindowPoStWithVanillaResponse { - if x == nil { - return nil - } - return x.ref96c012c3 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateSingleWindowPoStWithVanillaResponse) Free() { - if x != nil && x.allocs96c012c3 != nil { - x.allocs96c012c3.(*cgoAllocMap).Free() - x.ref96c012c3 = nil - } -} - -// NewFilGenerateSingleWindowPoStWithVanillaResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateSingleWindowPoStWithVanillaResponseRef(ref unsafe.Pointer) *FilGenerateSingleWindowPoStWithVanillaResponse { - if ref == nil { - return nil - } - obj := new(FilGenerateSingleWindowPoStWithVanillaResponse) - obj.ref96c012c3 = (*C.fil_GenerateSingleWindowPoStWithVanillaResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateSingleWindowPoStWithVanillaResponse) PassRef() (*C.fil_GenerateSingleWindowPoStWithVanillaResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref96c012c3 != nil { - return x.ref96c012c3, nil - } - mem96c012c3 := allocFilGenerateSingleWindowPoStWithVanillaResponseMemory(1) - ref96c012c3 := (*C.fil_GenerateSingleWindowPoStWithVanillaResponse)(mem96c012c3) - allocs96c012c3 := new(cgoAllocMap) - allocs96c012c3.Add(mem96c012c3) - - var cerror_msg_allocs *cgoAllocMap - ref96c012c3.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs96c012c3.Borrow(cerror_msg_allocs) - - var cpartition_proof_allocs *cgoAllocMap - ref96c012c3.partition_proof, cpartition_proof_allocs = x.PartitionProof.PassValue() - allocs96c012c3.Borrow(cpartition_proof_allocs) - - var cfaulty_sectors_len_allocs *cgoAllocMap - ref96c012c3.faulty_sectors_len, cfaulty_sectors_len_allocs = (C.size_t)(x.FaultySectorsLen), cgoAllocsUnknown - allocs96c012c3.Borrow(cfaulty_sectors_len_allocs) - - var cfaulty_sectors_ptr_allocs *cgoAllocMap - ref96c012c3.faulty_sectors_ptr, cfaulty_sectors_ptr_allocs = copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&x.FaultySectorsPtr))) - allocs96c012c3.Borrow(cfaulty_sectors_ptr_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref96c012c3.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs96c012c3.Borrow(cstatus_code_allocs) - - x.ref96c012c3 = ref96c012c3 - x.allocs96c012c3 = allocs96c012c3 - return ref96c012c3, allocs96c012c3 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateSingleWindowPoStWithVanillaResponse) PassValue() (C.fil_GenerateSingleWindowPoStWithVanillaResponse, *cgoAllocMap) { - if x.ref96c012c3 != nil { - return *x.ref96c012c3, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateSingleWindowPoStWithVanillaResponse) Deref() { - if x.ref96c012c3 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref96c012c3.error_msg) - x.PartitionProof = *NewFilPartitionSnarkProofRef(unsafe.Pointer(&x.ref96c012c3.partition_proof)) - x.FaultySectorsLen = (uint)(x.ref96c012c3.faulty_sectors_len) - hxff6bc57 := (*sliceHeader)(unsafe.Pointer(&x.FaultySectorsPtr)) - hxff6bc57.Data = unsafe.Pointer(x.ref96c012c3.faulty_sectors_ptr) - hxff6bc57.Cap = 0x7fffffff - // hxff6bc57.Len = ? - - x.StatusCode = (FCPResponseStatus)(x.ref96c012c3.status_code) -} - -// allocFilEmptySectorUpdateEncodeIntoResponseMemory allocates memory for type C.fil_EmptySectorUpdateEncodeIntoResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilEmptySectorUpdateEncodeIntoResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilEmptySectorUpdateEncodeIntoResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilEmptySectorUpdateEncodeIntoResponseValue = unsafe.Sizeof([1]C.fil_EmptySectorUpdateEncodeIntoResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilEmptySectorUpdateEncodeIntoResponse) Ref() *C.fil_EmptySectorUpdateEncodeIntoResponse { - if x == nil { - return nil - } - return x.ref8d3238a7 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilEmptySectorUpdateEncodeIntoResponse) Free() { - if x != nil && x.allocs8d3238a7 != nil { - x.allocs8d3238a7.(*cgoAllocMap).Free() - x.ref8d3238a7 = nil - } -} - -// NewFilEmptySectorUpdateEncodeIntoResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilEmptySectorUpdateEncodeIntoResponseRef(ref unsafe.Pointer) *FilEmptySectorUpdateEncodeIntoResponse { - if ref == nil { - return nil - } - obj := new(FilEmptySectorUpdateEncodeIntoResponse) - obj.ref8d3238a7 = (*C.fil_EmptySectorUpdateEncodeIntoResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilEmptySectorUpdateEncodeIntoResponse) PassRef() (*C.fil_EmptySectorUpdateEncodeIntoResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref8d3238a7 != nil { - return x.ref8d3238a7, nil - } - mem8d3238a7 := allocFilEmptySectorUpdateEncodeIntoResponseMemory(1) - ref8d3238a7 := (*C.fil_EmptySectorUpdateEncodeIntoResponse)(mem8d3238a7) - allocs8d3238a7 := new(cgoAllocMap) - allocs8d3238a7.Add(mem8d3238a7) - - var cerror_msg_allocs *cgoAllocMap - ref8d3238a7.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs8d3238a7.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - ref8d3238a7.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs8d3238a7.Borrow(cstatus_code_allocs) - - var ccomm_r_new_allocs *cgoAllocMap - ref8d3238a7.comm_r_new, ccomm_r_new_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommRNew)), cgoAllocsUnknown - allocs8d3238a7.Borrow(ccomm_r_new_allocs) - - var ccomm_r_last_new_allocs *cgoAllocMap - ref8d3238a7.comm_r_last_new, ccomm_r_last_new_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommRLastNew)), cgoAllocsUnknown - allocs8d3238a7.Borrow(ccomm_r_last_new_allocs) - - var ccomm_d_new_allocs *cgoAllocMap - ref8d3238a7.comm_d_new, ccomm_d_new_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommDNew)), cgoAllocsUnknown - allocs8d3238a7.Borrow(ccomm_d_new_allocs) - - x.ref8d3238a7 = ref8d3238a7 - x.allocs8d3238a7 = allocs8d3238a7 - return ref8d3238a7, allocs8d3238a7 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilEmptySectorUpdateEncodeIntoResponse) PassValue() (C.fil_EmptySectorUpdateEncodeIntoResponse, *cgoAllocMap) { - if x.ref8d3238a7 != nil { - return *x.ref8d3238a7, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilEmptySectorUpdateEncodeIntoResponse) Deref() { - if x.ref8d3238a7 == nil { - return - } - x.ErrorMsg = packPCharString(x.ref8d3238a7.error_msg) - x.StatusCode = (FCPResponseStatus)(x.ref8d3238a7.status_code) - x.CommRNew = *(*[32]byte)(unsafe.Pointer(&x.ref8d3238a7.comm_r_new)) - x.CommRLastNew = *(*[32]byte)(unsafe.Pointer(&x.ref8d3238a7.comm_r_last_new)) - x.CommDNew = *(*[32]byte)(unsafe.Pointer(&x.ref8d3238a7.comm_d_new)) -} - -// allocFilEmptySectorUpdateDecodeFromResponseMemory allocates memory for type C.fil_EmptySectorUpdateDecodeFromResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilEmptySectorUpdateDecodeFromResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilEmptySectorUpdateDecodeFromResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilEmptySectorUpdateDecodeFromResponseValue = unsafe.Sizeof([1]C.fil_EmptySectorUpdateDecodeFromResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilEmptySectorUpdateDecodeFromResponse) Ref() *C.fil_EmptySectorUpdateDecodeFromResponse { - if x == nil { - return nil - } - return x.reff02a01b8 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilEmptySectorUpdateDecodeFromResponse) Free() { - if x != nil && x.allocsf02a01b8 != nil { - x.allocsf02a01b8.(*cgoAllocMap).Free() - x.reff02a01b8 = nil - } -} - -// NewFilEmptySectorUpdateDecodeFromResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilEmptySectorUpdateDecodeFromResponseRef(ref unsafe.Pointer) *FilEmptySectorUpdateDecodeFromResponse { - if ref == nil { - return nil - } - obj := new(FilEmptySectorUpdateDecodeFromResponse) - obj.reff02a01b8 = (*C.fil_EmptySectorUpdateDecodeFromResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilEmptySectorUpdateDecodeFromResponse) PassRef() (*C.fil_EmptySectorUpdateDecodeFromResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.reff02a01b8 != nil { - return x.reff02a01b8, nil - } - memf02a01b8 := allocFilEmptySectorUpdateDecodeFromResponseMemory(1) - reff02a01b8 := (*C.fil_EmptySectorUpdateDecodeFromResponse)(memf02a01b8) - allocsf02a01b8 := new(cgoAllocMap) - allocsf02a01b8.Add(memf02a01b8) - - var cstatus_code_allocs *cgoAllocMap - reff02a01b8.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsf02a01b8.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - reff02a01b8.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsf02a01b8.Borrow(cerror_msg_allocs) - - x.reff02a01b8 = reff02a01b8 - x.allocsf02a01b8 = allocsf02a01b8 - return reff02a01b8, allocsf02a01b8 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilEmptySectorUpdateDecodeFromResponse) PassValue() (C.fil_EmptySectorUpdateDecodeFromResponse, *cgoAllocMap) { - if x.reff02a01b8 != nil { - return *x.reff02a01b8, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilEmptySectorUpdateDecodeFromResponse) Deref() { - if x.reff02a01b8 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.reff02a01b8.status_code) - x.ErrorMsg = packPCharString(x.reff02a01b8.error_msg) -} - -// allocFilEmptySectorUpdateRemoveEncodedDataResponseMemory allocates memory for type C.fil_EmptySectorUpdateRemoveEncodedDataResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilEmptySectorUpdateRemoveEncodedDataResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilEmptySectorUpdateRemoveEncodedDataResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilEmptySectorUpdateRemoveEncodedDataResponseValue = unsafe.Sizeof([1]C.fil_EmptySectorUpdateRemoveEncodedDataResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilEmptySectorUpdateRemoveEncodedDataResponse) Ref() *C.fil_EmptySectorUpdateRemoveEncodedDataResponse { - if x == nil { - return nil - } - return x.ref50783b83 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilEmptySectorUpdateRemoveEncodedDataResponse) Free() { - if x != nil && x.allocs50783b83 != nil { - x.allocs50783b83.(*cgoAllocMap).Free() - x.ref50783b83 = nil - } -} - -// NewFilEmptySectorUpdateRemoveEncodedDataResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilEmptySectorUpdateRemoveEncodedDataResponseRef(ref unsafe.Pointer) *FilEmptySectorUpdateRemoveEncodedDataResponse { - if ref == nil { - return nil - } - obj := new(FilEmptySectorUpdateRemoveEncodedDataResponse) - obj.ref50783b83 = (*C.fil_EmptySectorUpdateRemoveEncodedDataResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilEmptySectorUpdateRemoveEncodedDataResponse) PassRef() (*C.fil_EmptySectorUpdateRemoveEncodedDataResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref50783b83 != nil { - return x.ref50783b83, nil - } - mem50783b83 := allocFilEmptySectorUpdateRemoveEncodedDataResponseMemory(1) - ref50783b83 := (*C.fil_EmptySectorUpdateRemoveEncodedDataResponse)(mem50783b83) - allocs50783b83 := new(cgoAllocMap) - allocs50783b83.Add(mem50783b83) - - var cstatus_code_allocs *cgoAllocMap - ref50783b83.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs50783b83.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref50783b83.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs50783b83.Borrow(cerror_msg_allocs) - - x.ref50783b83 = ref50783b83 - x.allocs50783b83 = allocs50783b83 - return ref50783b83, allocs50783b83 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilEmptySectorUpdateRemoveEncodedDataResponse) PassValue() (C.fil_EmptySectorUpdateRemoveEncodedDataResponse, *cgoAllocMap) { - if x.ref50783b83 != nil { - return *x.ref50783b83, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilEmptySectorUpdateRemoveEncodedDataResponse) Deref() { - if x.ref50783b83 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref50783b83.status_code) - x.ErrorMsg = packPCharString(x.ref50783b83.error_msg) -} - -// allocFilPartitionProofMemory allocates memory for type C.fil_PartitionProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPartitionProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPartitionProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPartitionProofValue = unsafe.Sizeof([1]C.fil_PartitionProof{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPartitionProof) Ref() *C.fil_PartitionProof { - if x == nil { - return nil - } - return x.ref566a2be6 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPartitionProof) Free() { - if x != nil && x.allocs566a2be6 != nil { - x.allocs566a2be6.(*cgoAllocMap).Free() - x.ref566a2be6 = nil - } -} - -// NewFilPartitionProofRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPartitionProofRef(ref unsafe.Pointer) *FilPartitionProof { - if ref == nil { - return nil - } - obj := new(FilPartitionProof) - obj.ref566a2be6 = (*C.fil_PartitionProof)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPartitionProof) PassRef() (*C.fil_PartitionProof, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref566a2be6 != nil { - return x.ref566a2be6, nil - } - mem566a2be6 := allocFilPartitionProofMemory(1) - ref566a2be6 := (*C.fil_PartitionProof)(mem566a2be6) - allocs566a2be6 := new(cgoAllocMap) - allocs566a2be6.Add(mem566a2be6) - - var cproof_len_allocs *cgoAllocMap - ref566a2be6.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocs566a2be6.Borrow(cproof_len_allocs) - - var cproof_ptr_allocs *cgoAllocMap - ref566a2be6.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocs566a2be6.Borrow(cproof_ptr_allocs) - - x.ref566a2be6 = ref566a2be6 - x.allocs566a2be6 = allocs566a2be6 - return ref566a2be6, allocs566a2be6 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPartitionProof) PassValue() (C.fil_PartitionProof, *cgoAllocMap) { - if x.ref566a2be6 != nil { - return *x.ref566a2be6, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPartitionProof) Deref() { - if x.ref566a2be6 == nil { - return - } - x.ProofLen = (uint)(x.ref566a2be6.proof_len) - hxf5fa529 := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxf5fa529.Data = unsafe.Pointer(x.ref566a2be6.proof_ptr) - hxf5fa529.Cap = 0x7fffffff - // hxf5fa529.Len = ? - -} - -// allocFilPartitionProofResponseMemory allocates memory for type C.fil_PartitionProofResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilPartitionProofResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilPartitionProofResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilPartitionProofResponseValue = unsafe.Sizeof([1]C.fil_PartitionProofResponse{}) - -// allocStructFilPartitionProofMemory allocates memory for type C.struct_fil_PartitionProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilPartitionProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilPartitionProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilPartitionProofValue = unsafe.Sizeof([1]C.struct_fil_PartitionProof{}) - -// unpackSFilPartitionProof transforms a sliced Go data structure into plain C format. -func unpackSFilPartitionProof(x []FilPartitionProof) (unpacked *C.struct_fil_PartitionProof, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPartitionProofMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PartitionProof)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PartitionProof)(h.Data) - return -} - -// packSFilPartitionProof reads sliced Go data structure out from plain C format. -func packSFilPartitionProof(v []FilPartitionProof, ptr0 *C.struct_fil_PartitionProof) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilPartitionProofValue]C.struct_fil_PartitionProof)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilPartitionProofRef(unsafe.Pointer(&ptr1)) - } -} - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilPartitionProofResponse) Ref() *C.fil_PartitionProofResponse { - if x == nil { - return nil - } - return x.ref51343e7a -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilPartitionProofResponse) Free() { - if x != nil && x.allocs51343e7a != nil { - x.allocs51343e7a.(*cgoAllocMap).Free() - x.ref51343e7a = nil - } -} - -// NewFilPartitionProofResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilPartitionProofResponseRef(ref unsafe.Pointer) *FilPartitionProofResponse { - if ref == nil { - return nil - } - obj := new(FilPartitionProofResponse) - obj.ref51343e7a = (*C.fil_PartitionProofResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilPartitionProofResponse) PassRef() (*C.fil_PartitionProofResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref51343e7a != nil { - return x.ref51343e7a, nil - } - mem51343e7a := allocFilPartitionProofResponseMemory(1) - ref51343e7a := (*C.fil_PartitionProofResponse)(mem51343e7a) - allocs51343e7a := new(cgoAllocMap) - allocs51343e7a.Add(mem51343e7a) - - var cstatus_code_allocs *cgoAllocMap - ref51343e7a.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs51343e7a.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref51343e7a.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs51343e7a.Borrow(cerror_msg_allocs) - - var cproofs_len_allocs *cgoAllocMap - ref51343e7a.proofs_len, cproofs_len_allocs = (C.size_t)(x.ProofsLen), cgoAllocsUnknown - allocs51343e7a.Borrow(cproofs_len_allocs) - - var cproofs_ptr_allocs *cgoAllocMap - ref51343e7a.proofs_ptr, cproofs_ptr_allocs = unpackSFilPartitionProof(x.ProofsPtr) - allocs51343e7a.Borrow(cproofs_ptr_allocs) - - x.ref51343e7a = ref51343e7a - x.allocs51343e7a = allocs51343e7a - return ref51343e7a, allocs51343e7a - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilPartitionProofResponse) PassValue() (C.fil_PartitionProofResponse, *cgoAllocMap) { - if x.ref51343e7a != nil { - return *x.ref51343e7a, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilPartitionProofResponse) Deref() { - if x.ref51343e7a == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref51343e7a.status_code) - x.ErrorMsg = packPCharString(x.ref51343e7a.error_msg) - x.ProofsLen = (uint)(x.ref51343e7a.proofs_len) - packSFilPartitionProof(x.ProofsPtr, x.ref51343e7a.proofs_ptr) -} - -// allocFilVerifyPartitionProofResponseMemory allocates memory for type C.fil_VerifyPartitionProofResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVerifyPartitionProofResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVerifyPartitionProofResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVerifyPartitionProofResponseValue = unsafe.Sizeof([1]C.fil_VerifyPartitionProofResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVerifyPartitionProofResponse) Ref() *C.fil_VerifyPartitionProofResponse { - if x == nil { - return nil - } - return x.refaed1b67 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVerifyPartitionProofResponse) Free() { - if x != nil && x.allocsaed1b67 != nil { - x.allocsaed1b67.(*cgoAllocMap).Free() - x.refaed1b67 = nil - } -} - -// NewFilVerifyPartitionProofResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVerifyPartitionProofResponseRef(ref unsafe.Pointer) *FilVerifyPartitionProofResponse { - if ref == nil { - return nil - } - obj := new(FilVerifyPartitionProofResponse) - obj.refaed1b67 = (*C.fil_VerifyPartitionProofResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVerifyPartitionProofResponse) PassRef() (*C.fil_VerifyPartitionProofResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refaed1b67 != nil { - return x.refaed1b67, nil - } - memaed1b67 := allocFilVerifyPartitionProofResponseMemory(1) - refaed1b67 := (*C.fil_VerifyPartitionProofResponse)(memaed1b67) - allocsaed1b67 := new(cgoAllocMap) - allocsaed1b67.Add(memaed1b67) - - var cstatus_code_allocs *cgoAllocMap - refaed1b67.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsaed1b67.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - refaed1b67.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsaed1b67.Borrow(cerror_msg_allocs) - - var cis_valid_allocs *cgoAllocMap - refaed1b67.is_valid, cis_valid_allocs = (C._Bool)(x.IsValid), cgoAllocsUnknown - allocsaed1b67.Borrow(cis_valid_allocs) - - x.refaed1b67 = refaed1b67 - x.allocsaed1b67 = allocsaed1b67 - return refaed1b67, allocsaed1b67 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVerifyPartitionProofResponse) PassValue() (C.fil_VerifyPartitionProofResponse, *cgoAllocMap) { - if x.refaed1b67 != nil { - return *x.refaed1b67, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVerifyPartitionProofResponse) Deref() { - if x.refaed1b67 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.refaed1b67.status_code) - x.ErrorMsg = packPCharString(x.refaed1b67.error_msg) - x.IsValid = (bool)(x.refaed1b67.is_valid) -} - -// allocFilEmptySectorUpdateProofResponseMemory allocates memory for type C.fil_EmptySectorUpdateProofResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilEmptySectorUpdateProofResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilEmptySectorUpdateProofResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilEmptySectorUpdateProofResponseValue = unsafe.Sizeof([1]C.fil_EmptySectorUpdateProofResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilEmptySectorUpdateProofResponse) Ref() *C.fil_EmptySectorUpdateProofResponse { - if x == nil { - return nil - } - return x.ref5c2faef -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilEmptySectorUpdateProofResponse) Free() { - if x != nil && x.allocs5c2faef != nil { - x.allocs5c2faef.(*cgoAllocMap).Free() - x.ref5c2faef = nil - } -} - -// NewFilEmptySectorUpdateProofResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilEmptySectorUpdateProofResponseRef(ref unsafe.Pointer) *FilEmptySectorUpdateProofResponse { - if ref == nil { - return nil - } - obj := new(FilEmptySectorUpdateProofResponse) - obj.ref5c2faef = (*C.fil_EmptySectorUpdateProofResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilEmptySectorUpdateProofResponse) PassRef() (*C.fil_EmptySectorUpdateProofResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref5c2faef != nil { - return x.ref5c2faef, nil - } - mem5c2faef := allocFilEmptySectorUpdateProofResponseMemory(1) - ref5c2faef := (*C.fil_EmptySectorUpdateProofResponse)(mem5c2faef) - allocs5c2faef := new(cgoAllocMap) - allocs5c2faef.Add(mem5c2faef) - - var cstatus_code_allocs *cgoAllocMap - ref5c2faef.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs5c2faef.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref5c2faef.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs5c2faef.Borrow(cerror_msg_allocs) - - var cproof_len_allocs *cgoAllocMap - ref5c2faef.proof_len, cproof_len_allocs = (C.size_t)(x.ProofLen), cgoAllocsUnknown - allocs5c2faef.Borrow(cproof_len_allocs) - - var cproof_ptr_allocs *cgoAllocMap - ref5c2faef.proof_ptr, cproof_ptr_allocs = copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&x.ProofPtr))) - allocs5c2faef.Borrow(cproof_ptr_allocs) - - x.ref5c2faef = ref5c2faef - x.allocs5c2faef = allocs5c2faef - return ref5c2faef, allocs5c2faef - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilEmptySectorUpdateProofResponse) PassValue() (C.fil_EmptySectorUpdateProofResponse, *cgoAllocMap) { - if x.ref5c2faef != nil { - return *x.ref5c2faef, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilEmptySectorUpdateProofResponse) Deref() { - if x.ref5c2faef == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref5c2faef.status_code) - x.ErrorMsg = packPCharString(x.ref5c2faef.error_msg) - x.ProofLen = (uint)(x.ref5c2faef.proof_len) - hxf21690b := (*sliceHeader)(unsafe.Pointer(&x.ProofPtr)) - hxf21690b.Data = unsafe.Pointer(x.ref5c2faef.proof_ptr) - hxf21690b.Cap = 0x7fffffff - // hxf21690b.Len = ? - -} - -// allocFilVerifyEmptySectorUpdateProofResponseMemory allocates memory for type C.fil_VerifyEmptySectorUpdateProofResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilVerifyEmptySectorUpdateProofResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilVerifyEmptySectorUpdateProofResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilVerifyEmptySectorUpdateProofResponseValue = unsafe.Sizeof([1]C.fil_VerifyEmptySectorUpdateProofResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilVerifyEmptySectorUpdateProofResponse) Ref() *C.fil_VerifyEmptySectorUpdateProofResponse { - if x == nil { - return nil - } - return x.ref50b7b13 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilVerifyEmptySectorUpdateProofResponse) Free() { - if x != nil && x.allocs50b7b13 != nil { - x.allocs50b7b13.(*cgoAllocMap).Free() - x.ref50b7b13 = nil - } -} - -// NewFilVerifyEmptySectorUpdateProofResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilVerifyEmptySectorUpdateProofResponseRef(ref unsafe.Pointer) *FilVerifyEmptySectorUpdateProofResponse { - if ref == nil { - return nil - } - obj := new(FilVerifyEmptySectorUpdateProofResponse) - obj.ref50b7b13 = (*C.fil_VerifyEmptySectorUpdateProofResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilVerifyEmptySectorUpdateProofResponse) PassRef() (*C.fil_VerifyEmptySectorUpdateProofResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref50b7b13 != nil { - return x.ref50b7b13, nil - } - mem50b7b13 := allocFilVerifyEmptySectorUpdateProofResponseMemory(1) - ref50b7b13 := (*C.fil_VerifyEmptySectorUpdateProofResponse)(mem50b7b13) - allocs50b7b13 := new(cgoAllocMap) - allocs50b7b13.Add(mem50b7b13) - - var cstatus_code_allocs *cgoAllocMap - ref50b7b13.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs50b7b13.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref50b7b13.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs50b7b13.Borrow(cerror_msg_allocs) - - var cis_valid_allocs *cgoAllocMap - ref50b7b13.is_valid, cis_valid_allocs = (C._Bool)(x.IsValid), cgoAllocsUnknown - allocs50b7b13.Borrow(cis_valid_allocs) - - x.ref50b7b13 = ref50b7b13 - x.allocs50b7b13 = allocs50b7b13 - return ref50b7b13, allocs50b7b13 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilVerifyEmptySectorUpdateProofResponse) PassValue() (C.fil_VerifyEmptySectorUpdateProofResponse, *cgoAllocMap) { - if x.ref50b7b13 != nil { - return *x.ref50b7b13, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilVerifyEmptySectorUpdateProofResponse) Deref() { - if x.ref50b7b13 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref50b7b13.status_code) - x.ErrorMsg = packPCharString(x.ref50b7b13.error_msg) - x.IsValid = (bool)(x.ref50b7b13.is_valid) -} - -// allocFilGeneratePieceCommitmentResponseMemory allocates memory for type C.fil_GeneratePieceCommitmentResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGeneratePieceCommitmentResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGeneratePieceCommitmentResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGeneratePieceCommitmentResponseValue = unsafe.Sizeof([1]C.fil_GeneratePieceCommitmentResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGeneratePieceCommitmentResponse) Ref() *C.fil_GeneratePieceCommitmentResponse { - if x == nil { - return nil - } - return x.ref4b00fda4 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGeneratePieceCommitmentResponse) Free() { - if x != nil && x.allocs4b00fda4 != nil { - x.allocs4b00fda4.(*cgoAllocMap).Free() - x.ref4b00fda4 = nil - } -} - -// NewFilGeneratePieceCommitmentResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGeneratePieceCommitmentResponseRef(ref unsafe.Pointer) *FilGeneratePieceCommitmentResponse { - if ref == nil { - return nil - } - obj := new(FilGeneratePieceCommitmentResponse) - obj.ref4b00fda4 = (*C.fil_GeneratePieceCommitmentResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGeneratePieceCommitmentResponse) PassRef() (*C.fil_GeneratePieceCommitmentResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref4b00fda4 != nil { - return x.ref4b00fda4, nil - } - mem4b00fda4 := allocFilGeneratePieceCommitmentResponseMemory(1) - ref4b00fda4 := (*C.fil_GeneratePieceCommitmentResponse)(mem4b00fda4) - allocs4b00fda4 := new(cgoAllocMap) - allocs4b00fda4.Add(mem4b00fda4) - - var cstatus_code_allocs *cgoAllocMap - ref4b00fda4.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs4b00fda4.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref4b00fda4.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs4b00fda4.Borrow(cerror_msg_allocs) - - var ccomm_p_allocs *cgoAllocMap - ref4b00fda4.comm_p, ccomm_p_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommP)), cgoAllocsUnknown - allocs4b00fda4.Borrow(ccomm_p_allocs) - - var cnum_bytes_aligned_allocs *cgoAllocMap - ref4b00fda4.num_bytes_aligned, cnum_bytes_aligned_allocs = (C.uint64_t)(x.NumBytesAligned), cgoAllocsUnknown - allocs4b00fda4.Borrow(cnum_bytes_aligned_allocs) - - x.ref4b00fda4 = ref4b00fda4 - x.allocs4b00fda4 = allocs4b00fda4 - return ref4b00fda4, allocs4b00fda4 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGeneratePieceCommitmentResponse) PassValue() (C.fil_GeneratePieceCommitmentResponse, *cgoAllocMap) { - if x.ref4b00fda4 != nil { - return *x.ref4b00fda4, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGeneratePieceCommitmentResponse) Deref() { - if x.ref4b00fda4 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref4b00fda4.status_code) - x.ErrorMsg = packPCharString(x.ref4b00fda4.error_msg) - x.CommP = *(*[32]byte)(unsafe.Pointer(&x.ref4b00fda4.comm_p)) - x.NumBytesAligned = (uint64)(x.ref4b00fda4.num_bytes_aligned) -} - -// allocFilGenerateDataCommitmentResponseMemory allocates memory for type C.fil_GenerateDataCommitmentResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGenerateDataCommitmentResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGenerateDataCommitmentResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGenerateDataCommitmentResponseValue = unsafe.Sizeof([1]C.fil_GenerateDataCommitmentResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGenerateDataCommitmentResponse) Ref() *C.fil_GenerateDataCommitmentResponse { - if x == nil { - return nil - } - return x.ref87da7dd9 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGenerateDataCommitmentResponse) Free() { - if x != nil && x.allocs87da7dd9 != nil { - x.allocs87da7dd9.(*cgoAllocMap).Free() - x.ref87da7dd9 = nil - } -} - -// NewFilGenerateDataCommitmentResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGenerateDataCommitmentResponseRef(ref unsafe.Pointer) *FilGenerateDataCommitmentResponse { - if ref == nil { - return nil - } - obj := new(FilGenerateDataCommitmentResponse) - obj.ref87da7dd9 = (*C.fil_GenerateDataCommitmentResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGenerateDataCommitmentResponse) PassRef() (*C.fil_GenerateDataCommitmentResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref87da7dd9 != nil { - return x.ref87da7dd9, nil - } - mem87da7dd9 := allocFilGenerateDataCommitmentResponseMemory(1) - ref87da7dd9 := (*C.fil_GenerateDataCommitmentResponse)(mem87da7dd9) - allocs87da7dd9 := new(cgoAllocMap) - allocs87da7dd9.Add(mem87da7dd9) - - var cstatus_code_allocs *cgoAllocMap - ref87da7dd9.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs87da7dd9.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref87da7dd9.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs87da7dd9.Borrow(cerror_msg_allocs) - - var ccomm_d_allocs *cgoAllocMap - ref87da7dd9.comm_d, ccomm_d_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.CommD)), cgoAllocsUnknown - allocs87da7dd9.Borrow(ccomm_d_allocs) - - x.ref87da7dd9 = ref87da7dd9 - x.allocs87da7dd9 = allocs87da7dd9 - return ref87da7dd9, allocs87da7dd9 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGenerateDataCommitmentResponse) PassValue() (C.fil_GenerateDataCommitmentResponse, *cgoAllocMap) { - if x.ref87da7dd9 != nil { - return *x.ref87da7dd9, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGenerateDataCommitmentResponse) Deref() { - if x.ref87da7dd9 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref87da7dd9.status_code) - x.ErrorMsg = packPCharString(x.ref87da7dd9.error_msg) - x.CommD = *(*[32]byte)(unsafe.Pointer(&x.ref87da7dd9.comm_d)) -} - -// allocFilClearCacheResponseMemory allocates memory for type C.fil_ClearCacheResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilClearCacheResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilClearCacheResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilClearCacheResponseValue = unsafe.Sizeof([1]C.fil_ClearCacheResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilClearCacheResponse) Ref() *C.fil_ClearCacheResponse { - if x == nil { - return nil - } - return x.refa9a80400 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilClearCacheResponse) Free() { - if x != nil && x.allocsa9a80400 != nil { - x.allocsa9a80400.(*cgoAllocMap).Free() - x.refa9a80400 = nil - } -} - -// NewFilClearCacheResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilClearCacheResponseRef(ref unsafe.Pointer) *FilClearCacheResponse { - if ref == nil { - return nil - } - obj := new(FilClearCacheResponse) - obj.refa9a80400 = (*C.fil_ClearCacheResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilClearCacheResponse) PassRef() (*C.fil_ClearCacheResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refa9a80400 != nil { - return x.refa9a80400, nil - } - mema9a80400 := allocFilClearCacheResponseMemory(1) - refa9a80400 := (*C.fil_ClearCacheResponse)(mema9a80400) - allocsa9a80400 := new(cgoAllocMap) - allocsa9a80400.Add(mema9a80400) - - var cerror_msg_allocs *cgoAllocMap - refa9a80400.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsa9a80400.Borrow(cerror_msg_allocs) - - var cstatus_code_allocs *cgoAllocMap - refa9a80400.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsa9a80400.Borrow(cstatus_code_allocs) - - x.refa9a80400 = refa9a80400 - x.allocsa9a80400 = allocsa9a80400 - return refa9a80400, allocsa9a80400 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilClearCacheResponse) PassValue() (C.fil_ClearCacheResponse, *cgoAllocMap) { - if x.refa9a80400 != nil { - return *x.refa9a80400, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilClearCacheResponse) Deref() { - if x.refa9a80400 == nil { - return - } - x.ErrorMsg = packPCharString(x.refa9a80400.error_msg) - x.StatusCode = (FCPResponseStatus)(x.refa9a80400.status_code) -} - -// allocFilStringResponseMemory allocates memory for type C.fil_StringResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilStringResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilStringResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilStringResponseValue = unsafe.Sizeof([1]C.fil_StringResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilStringResponse) Ref() *C.fil_StringResponse { - if x == nil { - return nil - } - return x.ref4f413043 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilStringResponse) Free() { - if x != nil && x.allocs4f413043 != nil { - x.allocs4f413043.(*cgoAllocMap).Free() - x.ref4f413043 = nil - } -} - -// NewFilStringResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilStringResponseRef(ref unsafe.Pointer) *FilStringResponse { - if ref == nil { - return nil - } - obj := new(FilStringResponse) - obj.ref4f413043 = (*C.fil_StringResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilStringResponse) PassRef() (*C.fil_StringResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref4f413043 != nil { - return x.ref4f413043, nil - } - mem4f413043 := allocFilStringResponseMemory(1) - ref4f413043 := (*C.fil_StringResponse)(mem4f413043) - allocs4f413043 := new(cgoAllocMap) - allocs4f413043.Add(mem4f413043) - - var cstatus_code_allocs *cgoAllocMap - ref4f413043.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs4f413043.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref4f413043.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs4f413043.Borrow(cerror_msg_allocs) - - var cstring_val_allocs *cgoAllocMap - ref4f413043.string_val, cstring_val_allocs = unpackPCharString(x.StringVal) - allocs4f413043.Borrow(cstring_val_allocs) - - x.ref4f413043 = ref4f413043 - x.allocs4f413043 = allocs4f413043 - return ref4f413043, allocs4f413043 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilStringResponse) PassValue() (C.fil_StringResponse, *cgoAllocMap) { - if x.ref4f413043 != nil { - return *x.ref4f413043, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilStringResponse) Deref() { - if x.ref4f413043 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref4f413043.status_code) - x.ErrorMsg = packPCharString(x.ref4f413043.error_msg) - x.StringVal = packPCharString(x.ref4f413043.string_val) -} - -// allocFilFinalizeTicketResponseMemory allocates memory for type C.fil_FinalizeTicketResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilFinalizeTicketResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilFinalizeTicketResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilFinalizeTicketResponseValue = unsafe.Sizeof([1]C.fil_FinalizeTicketResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilFinalizeTicketResponse) Ref() *C.fil_FinalizeTicketResponse { - if x == nil { - return nil - } - return x.refb370fa86 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilFinalizeTicketResponse) Free() { - if x != nil && x.allocsb370fa86 != nil { - x.allocsb370fa86.(*cgoAllocMap).Free() - x.refb370fa86 = nil - } -} - -// NewFilFinalizeTicketResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilFinalizeTicketResponseRef(ref unsafe.Pointer) *FilFinalizeTicketResponse { - if ref == nil { - return nil - } - obj := new(FilFinalizeTicketResponse) - obj.refb370fa86 = (*C.fil_FinalizeTicketResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilFinalizeTicketResponse) PassRef() (*C.fil_FinalizeTicketResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.refb370fa86 != nil { - return x.refb370fa86, nil - } - memb370fa86 := allocFilFinalizeTicketResponseMemory(1) - refb370fa86 := (*C.fil_FinalizeTicketResponse)(memb370fa86) - allocsb370fa86 := new(cgoAllocMap) - allocsb370fa86.Add(memb370fa86) - - var cstatus_code_allocs *cgoAllocMap - refb370fa86.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocsb370fa86.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - refb370fa86.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocsb370fa86.Borrow(cerror_msg_allocs) - - var cticket_allocs *cgoAllocMap - refb370fa86.ticket, cticket_allocs = *(*[32]C.uint8_t)(unsafe.Pointer(&x.Ticket)), cgoAllocsUnknown - allocsb370fa86.Borrow(cticket_allocs) - - x.refb370fa86 = refb370fa86 - x.allocsb370fa86 = allocsb370fa86 - return refb370fa86, allocsb370fa86 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilFinalizeTicketResponse) PassValue() (C.fil_FinalizeTicketResponse, *cgoAllocMap) { - if x.refb370fa86 != nil { - return *x.refb370fa86, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilFinalizeTicketResponse) Deref() { - if x.refb370fa86 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.refb370fa86.status_code) - x.ErrorMsg = packPCharString(x.refb370fa86.error_msg) - x.Ticket = *(*[32]byte)(unsafe.Pointer(&x.refb370fa86.ticket)) -} - -// allocFilGpuDeviceResponseMemory allocates memory for type C.fil_GpuDeviceResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilGpuDeviceResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilGpuDeviceResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilGpuDeviceResponseValue = unsafe.Sizeof([1]C.fil_GpuDeviceResponse{}) - -// allocPCharMemory allocates memory for type *C.char in C. -// The caller is responsible for freeing the this memory via C.free. -func allocPCharMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfPCharValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfPCharValue = unsafe.Sizeof([1]*C.char{}) - -// unpackSString transforms a sliced Go data structure into plain C format. -func unpackSString(x []string) (unpacked **C.char, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocPCharMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]*C.char)(unsafe.Pointer(h0)) - for i0 := range x { - v0[i0], _ = unpackPCharString(x[i0]) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (**C.char)(h.Data) - return -} - -// packSString reads sliced Go data structure out from plain C format. -func packSString(v []string, ptr0 **C.char) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfPtr]*C.char)(unsafe.Pointer(ptr0)))[i0] - v[i0] = packPCharString(ptr1) - } -} - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilGpuDeviceResponse) Ref() *C.fil_GpuDeviceResponse { - if x == nil { - return nil - } - return x.ref58f92915 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilGpuDeviceResponse) Free() { - if x != nil && x.allocs58f92915 != nil { - x.allocs58f92915.(*cgoAllocMap).Free() - x.ref58f92915 = nil - } -} - -// NewFilGpuDeviceResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilGpuDeviceResponseRef(ref unsafe.Pointer) *FilGpuDeviceResponse { - if ref == nil { - return nil - } - obj := new(FilGpuDeviceResponse) - obj.ref58f92915 = (*C.fil_GpuDeviceResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilGpuDeviceResponse) PassRef() (*C.fil_GpuDeviceResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref58f92915 != nil { - return x.ref58f92915, nil - } - mem58f92915 := allocFilGpuDeviceResponseMemory(1) - ref58f92915 := (*C.fil_GpuDeviceResponse)(mem58f92915) - allocs58f92915 := new(cgoAllocMap) - allocs58f92915.Add(mem58f92915) - - var cstatus_code_allocs *cgoAllocMap - ref58f92915.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs58f92915.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref58f92915.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs58f92915.Borrow(cerror_msg_allocs) - - var cdevices_len_allocs *cgoAllocMap - ref58f92915.devices_len, cdevices_len_allocs = (C.size_t)(x.DevicesLen), cgoAllocsUnknown - allocs58f92915.Borrow(cdevices_len_allocs) - - var cdevices_ptr_allocs *cgoAllocMap - ref58f92915.devices_ptr, cdevices_ptr_allocs = unpackSString(x.DevicesPtr) - allocs58f92915.Borrow(cdevices_ptr_allocs) - - x.ref58f92915 = ref58f92915 - x.allocs58f92915 = allocs58f92915 - return ref58f92915, allocs58f92915 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilGpuDeviceResponse) PassValue() (C.fil_GpuDeviceResponse, *cgoAllocMap) { - if x.ref58f92915 != nil { - return *x.ref58f92915, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilGpuDeviceResponse) Deref() { - if x.ref58f92915 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref58f92915.status_code) - x.ErrorMsg = packPCharString(x.ref58f92915.error_msg) - x.DevicesLen = (uint)(x.ref58f92915.devices_len) - packSString(x.DevicesPtr, x.ref58f92915.devices_ptr) -} - -// allocFilInitLogFdResponseMemory allocates memory for type C.fil_InitLogFdResponse in C. -// The caller is responsible for freeing the this memory via C.free. -func allocFilInitLogFdResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfFilInitLogFdResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfFilInitLogFdResponseValue = unsafe.Sizeof([1]C.fil_InitLogFdResponse{}) - -// Ref returns the underlying reference to C object or nil if struct is nil. -func (x *FilInitLogFdResponse) Ref() *C.fil_InitLogFdResponse { - if x == nil { - return nil - } - return x.ref3c1a0a08 -} - -// Free invokes alloc map's free mechanism that cleanups any allocated memory using C free. -// Does nothing if struct is nil or has no allocation map. -func (x *FilInitLogFdResponse) Free() { - if x != nil && x.allocs3c1a0a08 != nil { - x.allocs3c1a0a08.(*cgoAllocMap).Free() - x.ref3c1a0a08 = nil - } -} - -// NewFilInitLogFdResponseRef creates a new wrapper struct with underlying reference set to the original C object. -// Returns nil if the provided pointer to C object is nil too. -func NewFilInitLogFdResponseRef(ref unsafe.Pointer) *FilInitLogFdResponse { - if ref == nil { - return nil - } - obj := new(FilInitLogFdResponse) - obj.ref3c1a0a08 = (*C.fil_InitLogFdResponse)(unsafe.Pointer(ref)) - return obj -} - -// PassRef returns the underlying C object, otherwise it will allocate one and set its values -// from this wrapping struct, counting allocations into an allocation map. -func (x *FilInitLogFdResponse) PassRef() (*C.fil_InitLogFdResponse, *cgoAllocMap) { - if x == nil { - return nil, nil - } else if x.ref3c1a0a08 != nil { - return x.ref3c1a0a08, nil - } - mem3c1a0a08 := allocFilInitLogFdResponseMemory(1) - ref3c1a0a08 := (*C.fil_InitLogFdResponse)(mem3c1a0a08) - allocs3c1a0a08 := new(cgoAllocMap) - allocs3c1a0a08.Add(mem3c1a0a08) - - var cstatus_code_allocs *cgoAllocMap - ref3c1a0a08.status_code, cstatus_code_allocs = (C.enum_FCPResponseStatus)(x.StatusCode), cgoAllocsUnknown - allocs3c1a0a08.Borrow(cstatus_code_allocs) - - var cerror_msg_allocs *cgoAllocMap - ref3c1a0a08.error_msg, cerror_msg_allocs = unpackPCharString(x.ErrorMsg) - allocs3c1a0a08.Borrow(cerror_msg_allocs) - - x.ref3c1a0a08 = ref3c1a0a08 - x.allocs3c1a0a08 = allocs3c1a0a08 - return ref3c1a0a08, allocs3c1a0a08 - -} - -// PassValue does the same as PassRef except that it will try to dereference the returned pointer. -func (x FilInitLogFdResponse) PassValue() (C.fil_InitLogFdResponse, *cgoAllocMap) { - if x.ref3c1a0a08 != nil { - return *x.ref3c1a0a08, nil - } - ref, allocs := x.PassRef() - return *ref, allocs -} - -// Deref uses the underlying reference to C object and fills the wrapping struct with values. -// Do not forget to call this method whether you get a struct for C object and want to read its values. -func (x *FilInitLogFdResponse) Deref() { - if x.ref3c1a0a08 == nil { - return - } - x.StatusCode = (FCPResponseStatus)(x.ref3c1a0a08.status_code) - x.ErrorMsg = packPCharString(x.ref3c1a0a08.error_msg) -} - -// copyPSizeTBytes copies the data from Go slice as *C.size_t. -func copyPSizeTBytes(slice *sliceHeader) (*C.size_t, *cgoAllocMap) { - allocs := new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - mem0 := unsafe.Pointer(C.CBytes(*(*[]byte)(unsafe.Pointer(&sliceHeader{ - Data: slice.Data, - Len: int(sizeOfSizeTValue) * slice.Len, - Cap: int(sizeOfSizeTValue) * slice.Len, - })))) - allocs.Add(mem0) - - return (*C.size_t)(mem0), allocs -} - -// allocSizeTMemory allocates memory for type C.size_t in C. -// The caller is responsible for freeing the this memory via C.free. -func allocSizeTMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfSizeTValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfSizeTValue = unsafe.Sizeof([1]C.size_t{}) - -// allocStructFilPublicPieceInfoMemory allocates memory for type C.struct_fil_PublicPieceInfo in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilPublicPieceInfoMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilPublicPieceInfoValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilPublicPieceInfoValue = unsafe.Sizeof([1]C.struct_fil_PublicPieceInfo{}) - -// unpackArgSFilPublicPieceInfo transforms a sliced Go data structure into plain C format. -func unpackArgSFilPublicPieceInfo(x []FilPublicPieceInfo) (unpacked *C.struct_fil_PublicPieceInfo, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPublicPieceInfoMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PublicPieceInfo)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PublicPieceInfo)(h.Data) - return -} - -// packSFilPublicPieceInfo reads sliced Go data structure out from plain C format. -func packSFilPublicPieceInfo(v []FilPublicPieceInfo, ptr0 *C.struct_fil_PublicPieceInfo) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilPublicPieceInfoValue]C.struct_fil_PublicPieceInfo)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilPublicPieceInfoRef(unsafe.Pointer(&ptr1)) - } -} - -// allocStructFil32ByteArrayMemory allocates memory for type C.struct_fil_32ByteArray in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFil32ByteArrayMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFil32ByteArrayValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFil32ByteArrayValue = unsafe.Sizeof([1]C.struct_fil_32ByteArray{}) - -// unpackArgSFil32ByteArray transforms a sliced Go data structure into plain C format. -func unpackArgSFil32ByteArray(x []Fil32ByteArray) (unpacked *C.struct_fil_32ByteArray, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFil32ByteArrayMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_32ByteArray)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_32ByteArray)(h.Data) - return -} - -// packSFil32ByteArray reads sliced Go data structure out from plain C format. -func packSFil32ByteArray(v []Fil32ByteArray, ptr0 *C.struct_fil_32ByteArray) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFil32ByteArrayValue]C.struct_fil_32ByteArray)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFil32ByteArrayRef(unsafe.Pointer(&ptr1)) - } -} - -// allocStructFilSealCommitPhase2ResponseMemory allocates memory for type C.struct_fil_SealCommitPhase2Response in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilSealCommitPhase2ResponseMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilSealCommitPhase2ResponseValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilSealCommitPhase2ResponseValue = unsafe.Sizeof([1]C.struct_fil_SealCommitPhase2Response{}) - -// unpackArgSFilSealCommitPhase2Response transforms a sliced Go data structure into plain C format. -func unpackArgSFilSealCommitPhase2Response(x []FilSealCommitPhase2Response) (unpacked *C.struct_fil_SealCommitPhase2Response, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilSealCommitPhase2ResponseMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_SealCommitPhase2Response)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_SealCommitPhase2Response)(h.Data) - return -} - -// packSFilSealCommitPhase2Response reads sliced Go data structure out from plain C format. -func packSFilSealCommitPhase2Response(v []FilSealCommitPhase2Response, ptr0 *C.struct_fil_SealCommitPhase2Response) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilSealCommitPhase2ResponseValue]C.struct_fil_SealCommitPhase2Response)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilSealCommitPhase2ResponseRef(unsafe.Pointer(&ptr1)) - } -} - -// unpackArgSFilAggregationInputs transforms a sliced Go data structure into plain C format. -func unpackArgSFilAggregationInputs(x []FilAggregationInputs) (unpacked *C.struct_fil_AggregationInputs, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilAggregationInputsMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_AggregationInputs)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_AggregationInputs)(h.Data) - return -} - -// allocStructFilVanillaProofMemory allocates memory for type C.struct_fil_VanillaProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilVanillaProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilVanillaProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilVanillaProofValue = unsafe.Sizeof([1]C.struct_fil_VanillaProof{}) - -// unpackArgSFilVanillaProof transforms a sliced Go data structure into plain C format. -func unpackArgSFilVanillaProof(x []FilVanillaProof) (unpacked *C.struct_fil_VanillaProof, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilVanillaProofMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_VanillaProof)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_VanillaProof)(h.Data) - return -} - -// packSFilVanillaProof reads sliced Go data structure out from plain C format. -func packSFilVanillaProof(v []FilVanillaProof, ptr0 *C.struct_fil_VanillaProof) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilVanillaProofValue]C.struct_fil_VanillaProof)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilVanillaProofRef(unsafe.Pointer(&ptr1)) - } -} - -// allocStructFilPrivateReplicaInfoMemory allocates memory for type C.struct_fil_PrivateReplicaInfo in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilPrivateReplicaInfoMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilPrivateReplicaInfoValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilPrivateReplicaInfoValue = unsafe.Sizeof([1]C.struct_fil_PrivateReplicaInfo{}) - -// unpackArgSFilPrivateReplicaInfo transforms a sliced Go data structure into plain C format. -func unpackArgSFilPrivateReplicaInfo(x []FilPrivateReplicaInfo) (unpacked *C.struct_fil_PrivateReplicaInfo, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPrivateReplicaInfoMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PrivateReplicaInfo)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PrivateReplicaInfo)(h.Data) - return -} - -// packSFilPrivateReplicaInfo reads sliced Go data structure out from plain C format. -func packSFilPrivateReplicaInfo(v []FilPrivateReplicaInfo, ptr0 *C.struct_fil_PrivateReplicaInfo) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilPrivateReplicaInfoValue]C.struct_fil_PrivateReplicaInfo)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilPrivateReplicaInfoRef(unsafe.Pointer(&ptr1)) - } -} - -// allocStructFilPublicReplicaInfoMemory allocates memory for type C.struct_fil_PublicReplicaInfo in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilPublicReplicaInfoMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilPublicReplicaInfoValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilPublicReplicaInfoValue = unsafe.Sizeof([1]C.struct_fil_PublicReplicaInfo{}) - -// unpackArgSFilPublicReplicaInfo transforms a sliced Go data structure into plain C format. -func unpackArgSFilPublicReplicaInfo(x []FilPublicReplicaInfo) (unpacked *C.struct_fil_PublicReplicaInfo, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPublicReplicaInfoMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PublicReplicaInfo)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PublicReplicaInfo)(h.Data) - return -} - -// packSFilPublicReplicaInfo reads sliced Go data structure out from plain C format. -func packSFilPublicReplicaInfo(v []FilPublicReplicaInfo, ptr0 *C.struct_fil_PublicReplicaInfo) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilPublicReplicaInfoValue]C.struct_fil_PublicReplicaInfo)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilPublicReplicaInfoRef(unsafe.Pointer(&ptr1)) - } -} - -// unpackArgSFilPoStProof transforms a sliced Go data structure into plain C format. -func unpackArgSFilPoStProof(x []FilPoStProof) (unpacked *C.struct_fil_PoStProof, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPoStProofMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PoStProof)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PoStProof)(h.Data) - return -} - -// allocStructFilPartitionSnarkProofMemory allocates memory for type C.struct_fil_PartitionSnarkProof in C. -// The caller is responsible for freeing the this memory via C.free. -func allocStructFilPartitionSnarkProofMemory(n int) unsafe.Pointer { - mem, err := C.calloc(C.size_t(n), (C.size_t)(sizeOfStructFilPartitionSnarkProofValue)) - if mem == nil { - panic(fmt.Sprintln("memory alloc error: ", err)) - } - return mem -} - -const sizeOfStructFilPartitionSnarkProofValue = unsafe.Sizeof([1]C.struct_fil_PartitionSnarkProof{}) - -// unpackArgSFilPartitionSnarkProof transforms a sliced Go data structure into plain C format. -func unpackArgSFilPartitionSnarkProof(x []FilPartitionSnarkProof) (unpacked *C.struct_fil_PartitionSnarkProof, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPartitionSnarkProofMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PartitionSnarkProof)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PartitionSnarkProof)(h.Data) - return -} - -// packSFilPartitionSnarkProof reads sliced Go data structure out from plain C format. -func packSFilPartitionSnarkProof(v []FilPartitionSnarkProof, ptr0 *C.struct_fil_PartitionSnarkProof) { - const m = 0x7fffffff - for i0 := range v { - ptr1 := (*(*[m / sizeOfStructFilPartitionSnarkProofValue]C.struct_fil_PartitionSnarkProof)(unsafe.Pointer(ptr0)))[i0] - v[i0] = *NewFilPartitionSnarkProofRef(unsafe.Pointer(&ptr1)) - } -} - -// unpackArgSFilPartitionProof transforms a sliced Go data structure into plain C format. -func unpackArgSFilPartitionProof(x []FilPartitionProof) (unpacked *C.struct_fil_PartitionProof, allocs *cgoAllocMap) { - if x == nil { - return nil, nil - } - allocs = new(cgoAllocMap) - defer runtime.SetFinalizer(allocs, func(a *cgoAllocMap) { - go a.Free() - }) - - len0 := len(x) - mem0 := allocStructFilPartitionProofMemory(len0) - allocs.Add(mem0) - h0 := &sliceHeader{ - Data: mem0, - Cap: len0, - Len: len0, - } - v0 := *(*[]C.struct_fil_PartitionProof)(unsafe.Pointer(h0)) - for i0 := range x { - allocs0 := new(cgoAllocMap) - v0[i0], allocs0 = x[i0].PassValue() - allocs.Borrow(allocs0) - } - h := (*sliceHeader)(unsafe.Pointer(&v0)) - unpacked = (*C.struct_fil_PartitionProof)(h.Data) - return -} diff --git a/generated/cgo_helpers.h b/generated/cgo_helpers.h deleted file mode 100644 index 952ed279..00000000 --- a/generated/cgo_helpers.h +++ /dev/null @@ -1,9 +0,0 @@ -// WARNING: This file has automatically been generated -// Code generated by https://git.io/c-for-go. DO NOT EDIT. - -#include "../filcrypto.h" -#include -#pragma once - -#define __CGOGEN 1 - diff --git a/generated/const.go b/generated/const.go deleted file mode 100644 index c68d6884..00000000 --- a/generated/const.go +++ /dev/null @@ -1,87 +0,0 @@ -// WARNING: This file has automatically been generated -// Code generated by https://git.io/c-for-go. DO NOT EDIT. - -package generated - -/* -#cgo linux LDFLAGS: -L${SRCDIR}/.. -Wl,-unresolved-symbols=ignore-all -#cgo darwin LDFLAGS: -L${SRCDIR}/.. -Wl,-undefined,dynamic_lookup -#cgo pkg-config: ${SRCDIR}/../filcrypto.pc -#include "../filcrypto.h" -#include -#include "cgo_helpers.h" -*/ -import "C" - -// FCPResponseStatus as declared in filecoin-ffi/filcrypto.h:56 -type FCPResponseStatus int32 - -// FCPResponseStatus enumeration from filecoin-ffi/filcrypto.h:56 -const ( - FCPResponseStatusFCPNoError FCPResponseStatus = C.FCPResponseStatus_FCPNoError - FCPResponseStatusFCPUnclassifiedError FCPResponseStatus = C.FCPResponseStatus_FCPUnclassifiedError - FCPResponseStatusFCPCallerError FCPResponseStatus = C.FCPResponseStatus_FCPCallerError - FCPResponseStatusFCPReceiverError FCPResponseStatus = C.FCPResponseStatus_FCPReceiverError -) - -// FilFvmRegisteredVersion as declared in filecoin-ffi/filcrypto.h:60 -type FilFvmRegisteredVersion int32 - -// FilFvmRegisteredVersion enumeration from filecoin-ffi/filcrypto.h:60 -const ( - FilFvmRegisteredVersionV1 FilFvmRegisteredVersion = C.fil_FvmRegisteredVersion_V1 -) - -// FilRegisteredAggregationProof as declared in filecoin-ffi/filcrypto.h:64 -type FilRegisteredAggregationProof int32 - -// FilRegisteredAggregationProof enumeration from filecoin-ffi/filcrypto.h:64 -const ( - FilRegisteredAggregationProofSnarkPackV1 FilRegisteredAggregationProof = C.fil_RegisteredAggregationProof_SnarkPackV1 -) - -// FilRegisteredPoStProof as declared in filecoin-ffi/filcrypto.h:77 -type FilRegisteredPoStProof int32 - -// FilRegisteredPoStProof enumeration from filecoin-ffi/filcrypto.h:77 -const ( - FilRegisteredPoStProofStackedDrgWinning2KiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWinning2KiBV1 - FilRegisteredPoStProofStackedDrgWinning8MiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWinning8MiBV1 - FilRegisteredPoStProofStackedDrgWinning512MiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWinning512MiBV1 - FilRegisteredPoStProofStackedDrgWinning32GiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWinning32GiBV1 - FilRegisteredPoStProofStackedDrgWinning64GiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWinning64GiBV1 - FilRegisteredPoStProofStackedDrgWindow2KiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWindow2KiBV1 - FilRegisteredPoStProofStackedDrgWindow8MiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWindow8MiBV1 - FilRegisteredPoStProofStackedDrgWindow512MiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWindow512MiBV1 - FilRegisteredPoStProofStackedDrgWindow32GiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWindow32GiBV1 - FilRegisteredPoStProofStackedDrgWindow64GiBV1 FilRegisteredPoStProof = C.fil_RegisteredPoStProof_StackedDrgWindow64GiBV1 -) - -// FilRegisteredSealProof as declared in filecoin-ffi/filcrypto.h:90 -type FilRegisteredSealProof int32 - -// FilRegisteredSealProof enumeration from filecoin-ffi/filcrypto.h:90 -const ( - FilRegisteredSealProofStackedDrg2KiBV1 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg2KiBV1 - FilRegisteredSealProofStackedDrg8MiBV1 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg8MiBV1 - FilRegisteredSealProofStackedDrg512MiBV1 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg512MiBV1 - FilRegisteredSealProofStackedDrg32GiBV1 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg32GiBV1 - FilRegisteredSealProofStackedDrg64GiBV1 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg64GiBV1 - FilRegisteredSealProofStackedDrg2KiBV11 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg2KiBV1_1 - FilRegisteredSealProofStackedDrg8MiBV11 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg8MiBV1_1 - FilRegisteredSealProofStackedDrg512MiBV11 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg512MiBV1_1 - FilRegisteredSealProofStackedDrg32GiBV11 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg32GiBV1_1 - FilRegisteredSealProofStackedDrg64GiBV11 FilRegisteredSealProof = C.fil_RegisteredSealProof_StackedDrg64GiBV1_1 -) - -// FilRegisteredUpdateProof as declared in filecoin-ffi/filcrypto.h:98 -type FilRegisteredUpdateProof int32 - -// FilRegisteredUpdateProof enumeration from filecoin-ffi/filcrypto.h:98 -const ( - FilRegisteredUpdateProofStackedDrg2KiBV1 FilRegisteredUpdateProof = C.fil_RegisteredUpdateProof_StackedDrg2KiBV1 - FilRegisteredUpdateProofStackedDrg8MiBV1 FilRegisteredUpdateProof = C.fil_RegisteredUpdateProof_StackedDrg8MiBV1 - FilRegisteredUpdateProofStackedDrg512MiBV1 FilRegisteredUpdateProof = C.fil_RegisteredUpdateProof_StackedDrg512MiBV1 - FilRegisteredUpdateProofStackedDrg32GiBV1 FilRegisteredUpdateProof = C.fil_RegisteredUpdateProof_StackedDrg32GiBV1 - FilRegisteredUpdateProofStackedDrg64GiBV1 FilRegisteredUpdateProof = C.fil_RegisteredUpdateProof_StackedDrg64GiBV1 -) diff --git a/generated/generated.go b/generated/generated.go deleted file mode 100644 index 2d674ea5..00000000 --- a/generated/generated.go +++ /dev/null @@ -1,1362 +0,0 @@ -// WARNING: This file has automatically been generated -// Code generated by https://git.io/c-for-go. DO NOT EDIT. - -package generated - -/* -#cgo linux LDFLAGS: -L${SRCDIR}/.. -Wl,-unresolved-symbols=ignore-all -#cgo darwin LDFLAGS: -L${SRCDIR}/.. -Wl,-undefined,dynamic_lookup -#cgo pkg-config: ${SRCDIR}/../filcrypto.pc -#include "../filcrypto.h" -#include -#include "cgo_helpers.h" -*/ -import "C" -import ( - "runtime" - "unsafe" -) - -// FilHash function as declared in filecoin-ffi/filcrypto.h:489 -func FilHash(messagePtr []byte, messageLen uint) *FilHashResponse { - cmessagePtr, cmessagePtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&messagePtr))) - cmessageLen, cmessageLenAllocMap := (C.size_t)(messageLen), cgoAllocsUnknown - __ret := C.fil_hash(cmessagePtr, cmessageLen) - runtime.KeepAlive(cmessageLenAllocMap) - runtime.KeepAlive(cmessagePtrAllocMap) - __v := NewFilHashResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilAggregate function as declared in filecoin-ffi/filcrypto.h:501 -func FilAggregate(flattenedSignaturesPtr []byte, flattenedSignaturesLen uint) *FilAggregateResponse { - cflattenedSignaturesPtr, cflattenedSignaturesPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&flattenedSignaturesPtr))) - cflattenedSignaturesLen, cflattenedSignaturesLenAllocMap := (C.size_t)(flattenedSignaturesLen), cgoAllocsUnknown - __ret := C.fil_aggregate(cflattenedSignaturesPtr, cflattenedSignaturesLen) - runtime.KeepAlive(cflattenedSignaturesLenAllocMap) - runtime.KeepAlive(cflattenedSignaturesPtrAllocMap) - __v := NewFilAggregateResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerify function as declared in filecoin-ffi/filcrypto.h:515 -func FilVerify(signaturePtr []byte, flattenedDigestsPtr []byte, flattenedDigestsLen uint, flattenedPublicKeysPtr []byte, flattenedPublicKeysLen uint) int32 { - csignaturePtr, csignaturePtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&signaturePtr))) - cflattenedDigestsPtr, cflattenedDigestsPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&flattenedDigestsPtr))) - cflattenedDigestsLen, cflattenedDigestsLenAllocMap := (C.size_t)(flattenedDigestsLen), cgoAllocsUnknown - cflattenedPublicKeysPtr, cflattenedPublicKeysPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&flattenedPublicKeysPtr))) - cflattenedPublicKeysLen, cflattenedPublicKeysLenAllocMap := (C.size_t)(flattenedPublicKeysLen), cgoAllocsUnknown - __ret := C.fil_verify(csignaturePtr, cflattenedDigestsPtr, cflattenedDigestsLen, cflattenedPublicKeysPtr, cflattenedPublicKeysLen) - runtime.KeepAlive(cflattenedPublicKeysLenAllocMap) - runtime.KeepAlive(cflattenedPublicKeysPtrAllocMap) - runtime.KeepAlive(cflattenedDigestsLenAllocMap) - runtime.KeepAlive(cflattenedDigestsPtrAllocMap) - runtime.KeepAlive(csignaturePtrAllocMap) - __v := (int32)(__ret) - return __v -} - -// FilHashVerify function as declared in filecoin-ffi/filcrypto.h:533 -func FilHashVerify(signaturePtr []byte, flattenedMessagesPtr []byte, flattenedMessagesLen uint, messageSizesPtr []uint, messageSizesLen uint, flattenedPublicKeysPtr []byte, flattenedPublicKeysLen uint) int32 { - csignaturePtr, csignaturePtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&signaturePtr))) - cflattenedMessagesPtr, cflattenedMessagesPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&flattenedMessagesPtr))) - cflattenedMessagesLen, cflattenedMessagesLenAllocMap := (C.size_t)(flattenedMessagesLen), cgoAllocsUnknown - cmessageSizesPtr, cmessageSizesPtrAllocMap := copyPSizeTBytes((*sliceHeader)(unsafe.Pointer(&messageSizesPtr))) - cmessageSizesLen, cmessageSizesLenAllocMap := (C.size_t)(messageSizesLen), cgoAllocsUnknown - cflattenedPublicKeysPtr, cflattenedPublicKeysPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&flattenedPublicKeysPtr))) - cflattenedPublicKeysLen, cflattenedPublicKeysLenAllocMap := (C.size_t)(flattenedPublicKeysLen), cgoAllocsUnknown - __ret := C.fil_hash_verify(csignaturePtr, cflattenedMessagesPtr, cflattenedMessagesLen, cmessageSizesPtr, cmessageSizesLen, cflattenedPublicKeysPtr, cflattenedPublicKeysLen) - runtime.KeepAlive(cflattenedPublicKeysLenAllocMap) - runtime.KeepAlive(cflattenedPublicKeysPtrAllocMap) - runtime.KeepAlive(cmessageSizesLenAllocMap) - runtime.KeepAlive(cmessageSizesPtrAllocMap) - runtime.KeepAlive(cflattenedMessagesLenAllocMap) - runtime.KeepAlive(cflattenedMessagesPtrAllocMap) - runtime.KeepAlive(csignaturePtrAllocMap) - __v := (int32)(__ret) - return __v -} - -// FilPrivateKeyGenerate function as declared in filecoin-ffi/filcrypto.h:544 -func FilPrivateKeyGenerate() *FilPrivateKeyGenerateResponse { - __ret := C.fil_private_key_generate() - __v := NewFilPrivateKeyGenerateResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilPrivateKeyGenerateWithSeed function as declared in filecoin-ffi/filcrypto.h:557 -func FilPrivateKeyGenerateWithSeed(rawSeed Fil32ByteArray) *FilPrivateKeyGenerateResponse { - crawSeed, crawSeedAllocMap := rawSeed.PassValue() - __ret := C.fil_private_key_generate_with_seed(crawSeed) - runtime.KeepAlive(crawSeedAllocMap) - __v := NewFilPrivateKeyGenerateResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilPrivateKeySign function as declared in filecoin-ffi/filcrypto.h:570 -func FilPrivateKeySign(rawPrivateKeyPtr []byte, messagePtr []byte, messageLen uint) *FilPrivateKeySignResponse { - crawPrivateKeyPtr, crawPrivateKeyPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&rawPrivateKeyPtr))) - cmessagePtr, cmessagePtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&messagePtr))) - cmessageLen, cmessageLenAllocMap := (C.size_t)(messageLen), cgoAllocsUnknown - __ret := C.fil_private_key_sign(crawPrivateKeyPtr, cmessagePtr, cmessageLen) - runtime.KeepAlive(cmessageLenAllocMap) - runtime.KeepAlive(cmessagePtrAllocMap) - runtime.KeepAlive(crawPrivateKeyPtrAllocMap) - __v := NewFilPrivateKeySignResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilPrivateKeyPublicKey function as declared in filecoin-ffi/filcrypto.h:583 -func FilPrivateKeyPublicKey(rawPrivateKeyPtr []byte) *FilPrivateKeyPublicKeyResponse { - crawPrivateKeyPtr, crawPrivateKeyPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&rawPrivateKeyPtr))) - __ret := C.fil_private_key_public_key(crawPrivateKeyPtr) - runtime.KeepAlive(crawPrivateKeyPtrAllocMap) - __v := NewFilPrivateKeyPublicKeyResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilCreateZeroSignature function as declared in filecoin-ffi/filcrypto.h:590 -func FilCreateZeroSignature() *FilZeroSignatureResponse { - __ret := C.fil_create_zero_signature() - __v := NewFilZeroSignatureResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilDropSignature function as declared in filecoin-ffi/filcrypto.h:595 -func FilDropSignature(sig []byte) { - csig, csigAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&sig))) - C.fil_drop_signature(csig) - runtime.KeepAlive(csigAllocMap) -} - -// FilDestroyHashResponse function as declared in filecoin-ffi/filcrypto.h:597 -func FilDestroyHashResponse(ptr *FilHashResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_hash_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyAggregateResponse function as declared in filecoin-ffi/filcrypto.h:599 -func FilDestroyAggregateResponse(ptr *FilAggregateResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_aggregate_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyPrivateKeyGenerateResponse function as declared in filecoin-ffi/filcrypto.h:601 -func FilDestroyPrivateKeyGenerateResponse(ptr *FilPrivateKeyGenerateResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_private_key_generate_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyPrivateKeySignResponse function as declared in filecoin-ffi/filcrypto.h:603 -func FilDestroyPrivateKeySignResponse(ptr *FilPrivateKeySignResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_private_key_sign_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyPrivateKeyPublicKeyResponse function as declared in filecoin-ffi/filcrypto.h:605 -func FilDestroyPrivateKeyPublicKeyResponse(ptr *FilPrivateKeyPublicKeyResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_private_key_public_key_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyZeroSignatureResponse function as declared in filecoin-ffi/filcrypto.h:607 -func FilDestroyZeroSignatureResponse(ptr *FilZeroSignatureResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_zero_signature_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilCreateFvmMachine function as declared in filecoin-ffi/filcrypto.h:615 -func FilCreateFvmMachine(fvmVersion FilFvmRegisteredVersion, chainEpoch uint64, baseFeeHi uint64, baseFeeLo uint64, baseCircSupplyHi uint64, baseCircSupplyLo uint64, networkVersion uint64, stateRootPtr []byte, stateRootLen uint, manifestCidPtr []byte, manifestCidLen uint, tracing bool, blockstoreId uint64, externsId uint64) *FilCreateFvmMachineResponse { - cfvmVersion, cfvmVersionAllocMap := (C.enum_fil_FvmRegisteredVersion)(fvmVersion), cgoAllocsUnknown - cchainEpoch, cchainEpochAllocMap := (C.uint64_t)(chainEpoch), cgoAllocsUnknown - cbaseFeeHi, cbaseFeeHiAllocMap := (C.uint64_t)(baseFeeHi), cgoAllocsUnknown - cbaseFeeLo, cbaseFeeLoAllocMap := (C.uint64_t)(baseFeeLo), cgoAllocsUnknown - cbaseCircSupplyHi, cbaseCircSupplyHiAllocMap := (C.uint64_t)(baseCircSupplyHi), cgoAllocsUnknown - cbaseCircSupplyLo, cbaseCircSupplyLoAllocMap := (C.uint64_t)(baseCircSupplyLo), cgoAllocsUnknown - cnetworkVersion, cnetworkVersionAllocMap := (C.uint64_t)(networkVersion), cgoAllocsUnknown - cstateRootPtr, cstateRootPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&stateRootPtr))) - cstateRootLen, cstateRootLenAllocMap := (C.size_t)(stateRootLen), cgoAllocsUnknown - cmanifestCidPtr, cmanifestCidPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&manifestCidPtr))) - cmanifestCidLen, cmanifestCidLenAllocMap := (C.size_t)(manifestCidLen), cgoAllocsUnknown - ctracing, ctracingAllocMap := (C._Bool)(tracing), cgoAllocsUnknown - cblockstoreId, cblockstoreIdAllocMap := (C.uint64_t)(blockstoreId), cgoAllocsUnknown - cexternsId, cexternsIdAllocMap := (C.uint64_t)(externsId), cgoAllocsUnknown - __ret := C.fil_create_fvm_machine(cfvmVersion, cchainEpoch, cbaseFeeHi, cbaseFeeLo, cbaseCircSupplyHi, cbaseCircSupplyLo, cnetworkVersion, cstateRootPtr, cstateRootLen, cmanifestCidPtr, cmanifestCidLen, ctracing, cblockstoreId, cexternsId) - runtime.KeepAlive(cexternsIdAllocMap) - runtime.KeepAlive(cblockstoreIdAllocMap) - runtime.KeepAlive(ctracingAllocMap) - runtime.KeepAlive(cmanifestCidLenAllocMap) - runtime.KeepAlive(cmanifestCidPtrAllocMap) - runtime.KeepAlive(cstateRootLenAllocMap) - runtime.KeepAlive(cstateRootPtrAllocMap) - runtime.KeepAlive(cnetworkVersionAllocMap) - runtime.KeepAlive(cbaseCircSupplyLoAllocMap) - runtime.KeepAlive(cbaseCircSupplyHiAllocMap) - runtime.KeepAlive(cbaseFeeLoAllocMap) - runtime.KeepAlive(cbaseFeeHiAllocMap) - runtime.KeepAlive(cchainEpochAllocMap) - runtime.KeepAlive(cfvmVersionAllocMap) - __v := NewFilCreateFvmMachineResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilDropFvmMachine function as declared in filecoin-ffi/filcrypto.h:630 -func FilDropFvmMachine(executor unsafe.Pointer) { - cexecutor, cexecutorAllocMap := executor, cgoAllocsUnknown - C.fil_drop_fvm_machine(cexecutor) - runtime.KeepAlive(cexecutorAllocMap) -} - -// FilFvmMachineExecuteMessage function as declared in filecoin-ffi/filcrypto.h:632 -func FilFvmMachineExecuteMessage(executor unsafe.Pointer, messagePtr []byte, messageLen uint, chainLen uint64, applyKind uint64) *FilFvmMachineExecuteResponse { - cexecutor, cexecutorAllocMap := executor, cgoAllocsUnknown - cmessagePtr, cmessagePtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&messagePtr))) - cmessageLen, cmessageLenAllocMap := (C.size_t)(messageLen), cgoAllocsUnknown - cchainLen, cchainLenAllocMap := (C.uint64_t)(chainLen), cgoAllocsUnknown - capplyKind, capplyKindAllocMap := (C.uint64_t)(applyKind), cgoAllocsUnknown - __ret := C.fil_fvm_machine_execute_message(cexecutor, cmessagePtr, cmessageLen, cchainLen, capplyKind) - runtime.KeepAlive(capplyKindAllocMap) - runtime.KeepAlive(cchainLenAllocMap) - runtime.KeepAlive(cmessageLenAllocMap) - runtime.KeepAlive(cmessagePtrAllocMap) - runtime.KeepAlive(cexecutorAllocMap) - __v := NewFilFvmMachineExecuteResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilFvmMachineFlush function as declared in filecoin-ffi/filcrypto.h:638 -func FilFvmMachineFlush(executor unsafe.Pointer) *FilFvmMachineFlushResponse { - cexecutor, cexecutorAllocMap := executor, cgoAllocsUnknown - __ret := C.fil_fvm_machine_flush(cexecutor) - runtime.KeepAlive(cexecutorAllocMap) - __v := NewFilFvmMachineFlushResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilDestroyCreateFvmMachineResponse function as declared in filecoin-ffi/filcrypto.h:640 -func FilDestroyCreateFvmMachineResponse(ptr *FilCreateFvmMachineResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_create_fvm_machine_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyFvmMachineExecuteResponse function as declared in filecoin-ffi/filcrypto.h:642 -func FilDestroyFvmMachineExecuteResponse(ptr *FilFvmMachineExecuteResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_fvm_machine_execute_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyFvmMachineFlushResponse function as declared in filecoin-ffi/filcrypto.h:644 -func FilDestroyFvmMachineFlushResponse(ptr *FilFvmMachineFlushResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_fvm_machine_flush_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilWriteWithAlignment function as declared in filecoin-ffi/filcrypto.h:650 -func FilWriteWithAlignment(registeredProof FilRegisteredSealProof, srcFd int32, srcSize uint64, dstFd int32, existingPieceSizesPtr []uint64, existingPieceSizesLen uint) *FilWriteWithAlignmentResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - csrcFd, csrcFdAllocMap := (C.int)(srcFd), cgoAllocsUnknown - csrcSize, csrcSizeAllocMap := (C.uint64_t)(srcSize), cgoAllocsUnknown - cdstFd, cdstFdAllocMap := (C.int)(dstFd), cgoAllocsUnknown - cexistingPieceSizesPtr, cexistingPieceSizesPtrAllocMap := copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&existingPieceSizesPtr))) - cexistingPieceSizesLen, cexistingPieceSizesLenAllocMap := (C.size_t)(existingPieceSizesLen), cgoAllocsUnknown - __ret := C.fil_write_with_alignment(cregisteredProof, csrcFd, csrcSize, cdstFd, cexistingPieceSizesPtr, cexistingPieceSizesLen) - runtime.KeepAlive(cexistingPieceSizesLenAllocMap) - runtime.KeepAlive(cexistingPieceSizesPtrAllocMap) - runtime.KeepAlive(cdstFdAllocMap) - runtime.KeepAlive(csrcSizeAllocMap) - runtime.KeepAlive(csrcFdAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilWriteWithAlignmentResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilWriteWithoutAlignment function as declared in filecoin-ffi/filcrypto.h:661 -func FilWriteWithoutAlignment(registeredProof FilRegisteredSealProof, srcFd int32, srcSize uint64, dstFd int32) *FilWriteWithoutAlignmentResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - csrcFd, csrcFdAllocMap := (C.int)(srcFd), cgoAllocsUnknown - csrcSize, csrcSizeAllocMap := (C.uint64_t)(srcSize), cgoAllocsUnknown - cdstFd, cdstFdAllocMap := (C.int)(dstFd), cgoAllocsUnknown - __ret := C.fil_write_without_alignment(cregisteredProof, csrcFd, csrcSize, cdstFd) - runtime.KeepAlive(cdstFdAllocMap) - runtime.KeepAlive(csrcSizeAllocMap) - runtime.KeepAlive(csrcFdAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilWriteWithoutAlignmentResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilFauxrep function as declared in filecoin-ffi/filcrypto.h:666 -func FilFauxrep(registeredProof FilRegisteredSealProof, cacheDirPath string, sealedSectorPath string) *FilFauxRepResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - sealedSectorPath = safeString(sealedSectorPath) - csealedSectorPath, csealedSectorPathAllocMap := unpackPCharString(sealedSectorPath) - __ret := C.fil_fauxrep(cregisteredProof, ccacheDirPath, csealedSectorPath) - runtime.KeepAlive(sealedSectorPath) - runtime.KeepAlive(csealedSectorPathAllocMap) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilFauxRepResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilFauxrep2 function as declared in filecoin-ffi/filcrypto.h:670 -func FilFauxrep2(registeredProof FilRegisteredSealProof, cacheDirPath string, existingPAuxPath string) *FilFauxRepResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - existingPAuxPath = safeString(existingPAuxPath) - cexistingPAuxPath, cexistingPAuxPathAllocMap := unpackPCharString(existingPAuxPath) - __ret := C.fil_fauxrep2(cregisteredProof, ccacheDirPath, cexistingPAuxPath) - runtime.KeepAlive(existingPAuxPath) - runtime.KeepAlive(cexistingPAuxPathAllocMap) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilFauxRepResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilSealPreCommitPhase1 function as declared in filecoin-ffi/filcrypto.h:678 -func FilSealPreCommitPhase1(registeredProof FilRegisteredSealProof, cacheDirPath string, stagedSectorPath string, sealedSectorPath string, sectorId uint64, proverId Fil32ByteArray, ticket Fil32ByteArray, piecesPtr []FilPublicPieceInfo, piecesLen uint) *FilSealPreCommitPhase1Response { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - stagedSectorPath = safeString(stagedSectorPath) - cstagedSectorPath, cstagedSectorPathAllocMap := unpackPCharString(stagedSectorPath) - sealedSectorPath = safeString(sealedSectorPath) - csealedSectorPath, csealedSectorPathAllocMap := unpackPCharString(sealedSectorPath) - csectorId, csectorIdAllocMap := (C.uint64_t)(sectorId), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - cticket, cticketAllocMap := ticket.PassValue() - cpiecesPtr, cpiecesPtrAllocMap := unpackArgSFilPublicPieceInfo(piecesPtr) - cpiecesLen, cpiecesLenAllocMap := (C.size_t)(piecesLen), cgoAllocsUnknown - __ret := C.fil_seal_pre_commit_phase1(cregisteredProof, ccacheDirPath, cstagedSectorPath, csealedSectorPath, csectorId, cproverId, cticket, cpiecesPtr, cpiecesLen) - runtime.KeepAlive(cpiecesLenAllocMap) - packSFilPublicPieceInfo(piecesPtr, cpiecesPtr) - runtime.KeepAlive(cpiecesPtrAllocMap) - runtime.KeepAlive(cticketAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(csectorIdAllocMap) - runtime.KeepAlive(sealedSectorPath) - runtime.KeepAlive(csealedSectorPathAllocMap) - runtime.KeepAlive(stagedSectorPath) - runtime.KeepAlive(cstagedSectorPathAllocMap) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilSealPreCommitPhase1ResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilSealPreCommitPhase2 function as declared in filecoin-ffi/filcrypto.h:692 -func FilSealPreCommitPhase2(sealPreCommitPhase1OutputPtr []byte, sealPreCommitPhase1OutputLen uint, cacheDirPath string, sealedSectorPath string) *FilSealPreCommitPhase2Response { - csealPreCommitPhase1OutputPtr, csealPreCommitPhase1OutputPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&sealPreCommitPhase1OutputPtr))) - csealPreCommitPhase1OutputLen, csealPreCommitPhase1OutputLenAllocMap := (C.size_t)(sealPreCommitPhase1OutputLen), cgoAllocsUnknown - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - sealedSectorPath = safeString(sealedSectorPath) - csealedSectorPath, csealedSectorPathAllocMap := unpackPCharString(sealedSectorPath) - __ret := C.fil_seal_pre_commit_phase2(csealPreCommitPhase1OutputPtr, csealPreCommitPhase1OutputLen, ccacheDirPath, csealedSectorPath) - runtime.KeepAlive(sealedSectorPath) - runtime.KeepAlive(csealedSectorPathAllocMap) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(csealPreCommitPhase1OutputLenAllocMap) - runtime.KeepAlive(csealPreCommitPhase1OutputPtrAllocMap) - __v := NewFilSealPreCommitPhase2ResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilSealCommitPhase1 function as declared in filecoin-ffi/filcrypto.h:701 -func FilSealCommitPhase1(registeredProof FilRegisteredSealProof, commR Fil32ByteArray, commD Fil32ByteArray, cacheDirPath string, replicaPath string, sectorId uint64, proverId Fil32ByteArray, ticket Fil32ByteArray, seed Fil32ByteArray, piecesPtr []FilPublicPieceInfo, piecesLen uint) *FilSealCommitPhase1Response { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - ccommR, ccommRAllocMap := commR.PassValue() - ccommD, ccommDAllocMap := commD.PassValue() - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - replicaPath = safeString(replicaPath) - creplicaPath, creplicaPathAllocMap := unpackPCharString(replicaPath) - csectorId, csectorIdAllocMap := (C.uint64_t)(sectorId), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - cticket, cticketAllocMap := ticket.PassValue() - cseed, cseedAllocMap := seed.PassValue() - cpiecesPtr, cpiecesPtrAllocMap := unpackArgSFilPublicPieceInfo(piecesPtr) - cpiecesLen, cpiecesLenAllocMap := (C.size_t)(piecesLen), cgoAllocsUnknown - __ret := C.fil_seal_commit_phase1(cregisteredProof, ccommR, ccommD, ccacheDirPath, creplicaPath, csectorId, cproverId, cticket, cseed, cpiecesPtr, cpiecesLen) - runtime.KeepAlive(cpiecesLenAllocMap) - packSFilPublicPieceInfo(piecesPtr, cpiecesPtr) - runtime.KeepAlive(cpiecesPtrAllocMap) - runtime.KeepAlive(cseedAllocMap) - runtime.KeepAlive(cticketAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(csectorIdAllocMap) - runtime.KeepAlive(replicaPath) - runtime.KeepAlive(creplicaPathAllocMap) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(ccommDAllocMap) - runtime.KeepAlive(ccommRAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilSealCommitPhase1ResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilSealCommitPhase2 function as declared in filecoin-ffi/filcrypto.h:713 -func FilSealCommitPhase2(sealCommitPhase1OutputPtr []byte, sealCommitPhase1OutputLen uint, sectorId uint64, proverId Fil32ByteArray) *FilSealCommitPhase2Response { - csealCommitPhase1OutputPtr, csealCommitPhase1OutputPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&sealCommitPhase1OutputPtr))) - csealCommitPhase1OutputLen, csealCommitPhase1OutputLenAllocMap := (C.size_t)(sealCommitPhase1OutputLen), cgoAllocsUnknown - csectorId, csectorIdAllocMap := (C.uint64_t)(sectorId), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_seal_commit_phase2(csealCommitPhase1OutputPtr, csealCommitPhase1OutputLen, csectorId, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(csectorIdAllocMap) - runtime.KeepAlive(csealCommitPhase1OutputLenAllocMap) - runtime.KeepAlive(csealCommitPhase1OutputPtrAllocMap) - __v := NewFilSealCommitPhase2ResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilAggregateSealProofs function as declared in filecoin-ffi/filcrypto.h:718 -func FilAggregateSealProofs(registeredProof FilRegisteredSealProof, registeredAggregation FilRegisteredAggregationProof, commRsPtr []Fil32ByteArray, commRsLen uint, seedsPtr []Fil32ByteArray, seedsLen uint, sealCommitResponsesPtr []FilSealCommitPhase2Response, sealCommitResponsesLen uint) *FilAggregateProof { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cregisteredAggregation, cregisteredAggregationAllocMap := (C.enum_fil_RegisteredAggregationProof)(registeredAggregation), cgoAllocsUnknown - ccommRsPtr, ccommRsPtrAllocMap := unpackArgSFil32ByteArray(commRsPtr) - ccommRsLen, ccommRsLenAllocMap := (C.size_t)(commRsLen), cgoAllocsUnknown - cseedsPtr, cseedsPtrAllocMap := unpackArgSFil32ByteArray(seedsPtr) - cseedsLen, cseedsLenAllocMap := (C.size_t)(seedsLen), cgoAllocsUnknown - csealCommitResponsesPtr, csealCommitResponsesPtrAllocMap := unpackArgSFilSealCommitPhase2Response(sealCommitResponsesPtr) - csealCommitResponsesLen, csealCommitResponsesLenAllocMap := (C.size_t)(sealCommitResponsesLen), cgoAllocsUnknown - __ret := C.fil_aggregate_seal_proofs(cregisteredProof, cregisteredAggregation, ccommRsPtr, ccommRsLen, cseedsPtr, cseedsLen, csealCommitResponsesPtr, csealCommitResponsesLen) - runtime.KeepAlive(csealCommitResponsesLenAllocMap) - packSFilSealCommitPhase2Response(sealCommitResponsesPtr, csealCommitResponsesPtr) - runtime.KeepAlive(csealCommitResponsesPtrAllocMap) - runtime.KeepAlive(cseedsLenAllocMap) - packSFil32ByteArray(seedsPtr, cseedsPtr) - runtime.KeepAlive(cseedsPtrAllocMap) - runtime.KeepAlive(ccommRsLenAllocMap) - packSFil32ByteArray(commRsPtr, ccommRsPtr) - runtime.KeepAlive(ccommRsPtrAllocMap) - runtime.KeepAlive(cregisteredAggregationAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilAggregateProofRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerifyAggregateSealProof function as declared in filecoin-ffi/filcrypto.h:731 -func FilVerifyAggregateSealProof(registeredProof FilRegisteredSealProof, registeredAggregation FilRegisteredAggregationProof, proverId Fil32ByteArray, proofPtr []byte, proofLen uint, commitInputsPtr []FilAggregationInputs, commitInputsLen uint) *FilVerifyAggregateSealProofResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cregisteredAggregation, cregisteredAggregationAllocMap := (C.enum_fil_RegisteredAggregationProof)(registeredAggregation), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - cproofPtr, cproofPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&proofPtr))) - cproofLen, cproofLenAllocMap := (C.size_t)(proofLen), cgoAllocsUnknown - ccommitInputsPtr, ccommitInputsPtrAllocMap := unpackArgSFilAggregationInputs(commitInputsPtr) - ccommitInputsLen, ccommitInputsLenAllocMap := (C.size_t)(commitInputsLen), cgoAllocsUnknown - __ret := C.fil_verify_aggregate_seal_proof(cregisteredProof, cregisteredAggregation, cproverId, cproofPtr, cproofLen, ccommitInputsPtr, ccommitInputsLen) - runtime.KeepAlive(ccommitInputsLenAllocMap) - packSFilAggregationInputs(commitInputsPtr, ccommitInputsPtr) - runtime.KeepAlive(ccommitInputsPtrAllocMap) - runtime.KeepAlive(cproofLenAllocMap) - runtime.KeepAlive(cproofPtrAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(cregisteredAggregationAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilVerifyAggregateSealProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilUnsealRange function as declared in filecoin-ffi/filcrypto.h:742 -func FilUnsealRange(registeredProof FilRegisteredSealProof, cacheDirPath string, sealedSectorFdRaw int32, unsealOutputFdRaw int32, sectorId uint64, proverId Fil32ByteArray, ticket Fil32ByteArray, commD Fil32ByteArray, unpaddedByteIndex uint64, unpaddedBytesAmount uint64) *FilUnsealRangeResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - csealedSectorFdRaw, csealedSectorFdRawAllocMap := (C.int)(sealedSectorFdRaw), cgoAllocsUnknown - cunsealOutputFdRaw, cunsealOutputFdRawAllocMap := (C.int)(unsealOutputFdRaw), cgoAllocsUnknown - csectorId, csectorIdAllocMap := (C.uint64_t)(sectorId), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - cticket, cticketAllocMap := ticket.PassValue() - ccommD, ccommDAllocMap := commD.PassValue() - cunpaddedByteIndex, cunpaddedByteIndexAllocMap := (C.uint64_t)(unpaddedByteIndex), cgoAllocsUnknown - cunpaddedBytesAmount, cunpaddedBytesAmountAllocMap := (C.uint64_t)(unpaddedBytesAmount), cgoAllocsUnknown - __ret := C.fil_unseal_range(cregisteredProof, ccacheDirPath, csealedSectorFdRaw, cunsealOutputFdRaw, csectorId, cproverId, cticket, ccommD, cunpaddedByteIndex, cunpaddedBytesAmount) - runtime.KeepAlive(cunpaddedBytesAmountAllocMap) - runtime.KeepAlive(cunpaddedByteIndexAllocMap) - runtime.KeepAlive(ccommDAllocMap) - runtime.KeepAlive(cticketAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(csectorIdAllocMap) - runtime.KeepAlive(cunsealOutputFdRawAllocMap) - runtime.KeepAlive(csealedSectorFdRawAllocMap) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilUnsealRangeResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerifySeal function as declared in filecoin-ffi/filcrypto.h:757 -func FilVerifySeal(registeredProof FilRegisteredSealProof, commR Fil32ByteArray, commD Fil32ByteArray, proverId Fil32ByteArray, ticket Fil32ByteArray, seed Fil32ByteArray, sectorId uint64, proofPtr []byte, proofLen uint) *FilVerifySealResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - ccommR, ccommRAllocMap := commR.PassValue() - ccommD, ccommDAllocMap := commD.PassValue() - cproverId, cproverIdAllocMap := proverId.PassValue() - cticket, cticketAllocMap := ticket.PassValue() - cseed, cseedAllocMap := seed.PassValue() - csectorId, csectorIdAllocMap := (C.uint64_t)(sectorId), cgoAllocsUnknown - cproofPtr, cproofPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&proofPtr))) - cproofLen, cproofLenAllocMap := (C.size_t)(proofLen), cgoAllocsUnknown - __ret := C.fil_verify_seal(cregisteredProof, ccommR, ccommD, cproverId, cticket, cseed, csectorId, cproofPtr, cproofLen) - runtime.KeepAlive(cproofLenAllocMap) - runtime.KeepAlive(cproofPtrAllocMap) - runtime.KeepAlive(csectorIdAllocMap) - runtime.KeepAlive(cseedAllocMap) - runtime.KeepAlive(cticketAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(ccommDAllocMap) - runtime.KeepAlive(ccommRAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilVerifySealResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateWinningPostSectorChallenge function as declared in filecoin-ffi/filcrypto.h:771 -func FilGenerateWinningPostSectorChallenge(registeredProof FilRegisteredPoStProof, randomness Fil32ByteArray, sectorSetLen uint64, proverId Fil32ByteArray) *FilGenerateWinningPoStSectorChallenge { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - crandomness, crandomnessAllocMap := randomness.PassValue() - csectorSetLen, csectorSetLenAllocMap := (C.uint64_t)(sectorSetLen), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_generate_winning_post_sector_challenge(cregisteredProof, crandomness, csectorSetLen, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(csectorSetLenAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGenerateWinningPoStSectorChallengeRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateFallbackSectorChallenges function as declared in filecoin-ffi/filcrypto.h:780 -func FilGenerateFallbackSectorChallenges(registeredProof FilRegisteredPoStProof, randomness Fil32ByteArray, sectorIdsPtr []uint64, sectorIdsLen uint, proverId Fil32ByteArray) *FilGenerateFallbackSectorChallengesResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - crandomness, crandomnessAllocMap := randomness.PassValue() - csectorIdsPtr, csectorIdsPtrAllocMap := copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(§orIdsPtr))) - csectorIdsLen, csectorIdsLenAllocMap := (C.size_t)(sectorIdsLen), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_generate_fallback_sector_challenges(cregisteredProof, crandomness, csectorIdsPtr, csectorIdsLen, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(csectorIdsLenAllocMap) - runtime.KeepAlive(csectorIdsPtrAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGenerateFallbackSectorChallengesResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateSingleVanillaProof function as declared in filecoin-ffi/filcrypto.h:790 -func FilGenerateSingleVanillaProof(replica FilPrivateReplicaInfo, challengesPtr []uint64, challengesLen uint) *FilGenerateSingleVanillaProofResponse { - creplica, creplicaAllocMap := replica.PassValue() - cchallengesPtr, cchallengesPtrAllocMap := copyPUint64TBytes((*sliceHeader)(unsafe.Pointer(&challengesPtr))) - cchallengesLen, cchallengesLenAllocMap := (C.size_t)(challengesLen), cgoAllocsUnknown - __ret := C.fil_generate_single_vanilla_proof(creplica, cchallengesPtr, cchallengesLen) - runtime.KeepAlive(cchallengesLenAllocMap) - runtime.KeepAlive(cchallengesPtrAllocMap) - runtime.KeepAlive(creplicaAllocMap) - __v := NewFilGenerateSingleVanillaProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateWinningPostWithVanilla function as declared in filecoin-ffi/filcrypto.h:798 -func FilGenerateWinningPostWithVanilla(registeredProof FilRegisteredPoStProof, randomness Fil32ByteArray, proverId Fil32ByteArray, vanillaProofsPtr []FilVanillaProof, vanillaProofsLen uint) *FilGenerateWinningPoStResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - crandomness, crandomnessAllocMap := randomness.PassValue() - cproverId, cproverIdAllocMap := proverId.PassValue() - cvanillaProofsPtr, cvanillaProofsPtrAllocMap := unpackArgSFilVanillaProof(vanillaProofsPtr) - cvanillaProofsLen, cvanillaProofsLenAllocMap := (C.size_t)(vanillaProofsLen), cgoAllocsUnknown - __ret := C.fil_generate_winning_post_with_vanilla(cregisteredProof, crandomness, cproverId, cvanillaProofsPtr, cvanillaProofsLen) - runtime.KeepAlive(cvanillaProofsLenAllocMap) - packSFilVanillaProof(vanillaProofsPtr, cvanillaProofsPtr) - runtime.KeepAlive(cvanillaProofsPtrAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGenerateWinningPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateWinningPost function as declared in filecoin-ffi/filcrypto.h:808 -func FilGenerateWinningPost(randomness Fil32ByteArray, replicasPtr []FilPrivateReplicaInfo, replicasLen uint, proverId Fil32ByteArray) *FilGenerateWinningPoStResponse { - crandomness, crandomnessAllocMap := randomness.PassValue() - creplicasPtr, creplicasPtrAllocMap := unpackArgSFilPrivateReplicaInfo(replicasPtr) - creplicasLen, creplicasLenAllocMap := (C.size_t)(replicasLen), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_generate_winning_post(crandomness, creplicasPtr, creplicasLen, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(creplicasLenAllocMap) - packSFilPrivateReplicaInfo(replicasPtr, creplicasPtr) - runtime.KeepAlive(creplicasPtrAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - __v := NewFilGenerateWinningPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerifyWinningPost function as declared in filecoin-ffi/filcrypto.h:816 -func FilVerifyWinningPost(randomness Fil32ByteArray, replicasPtr []FilPublicReplicaInfo, replicasLen uint, proofsPtr []FilPoStProof, proofsLen uint, proverId Fil32ByteArray) *FilVerifyWinningPoStResponse { - crandomness, crandomnessAllocMap := randomness.PassValue() - creplicasPtr, creplicasPtrAllocMap := unpackArgSFilPublicReplicaInfo(replicasPtr) - creplicasLen, creplicasLenAllocMap := (C.size_t)(replicasLen), cgoAllocsUnknown - cproofsPtr, cproofsPtrAllocMap := unpackArgSFilPoStProof(proofsPtr) - cproofsLen, cproofsLenAllocMap := (C.size_t)(proofsLen), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_verify_winning_post(crandomness, creplicasPtr, creplicasLen, cproofsPtr, cproofsLen, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(cproofsLenAllocMap) - packSFilPoStProof(proofsPtr, cproofsPtr) - runtime.KeepAlive(cproofsPtrAllocMap) - runtime.KeepAlive(creplicasLenAllocMap) - packSFilPublicReplicaInfo(replicasPtr, creplicasPtr) - runtime.KeepAlive(creplicasPtrAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - __v := NewFilVerifyWinningPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateWindowPostWithVanilla function as declared in filecoin-ffi/filcrypto.h:827 -func FilGenerateWindowPostWithVanilla(registeredProof FilRegisteredPoStProof, randomness Fil32ByteArray, proverId Fil32ByteArray, vanillaProofsPtr []FilVanillaProof, vanillaProofsLen uint) *FilGenerateWindowPoStResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - crandomness, crandomnessAllocMap := randomness.PassValue() - cproverId, cproverIdAllocMap := proverId.PassValue() - cvanillaProofsPtr, cvanillaProofsPtrAllocMap := unpackArgSFilVanillaProof(vanillaProofsPtr) - cvanillaProofsLen, cvanillaProofsLenAllocMap := (C.size_t)(vanillaProofsLen), cgoAllocsUnknown - __ret := C.fil_generate_window_post_with_vanilla(cregisteredProof, crandomness, cproverId, cvanillaProofsPtr, cvanillaProofsLen) - runtime.KeepAlive(cvanillaProofsLenAllocMap) - packSFilVanillaProof(vanillaProofsPtr, cvanillaProofsPtr) - runtime.KeepAlive(cvanillaProofsPtrAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGenerateWindowPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateWindowPost function as declared in filecoin-ffi/filcrypto.h:837 -func FilGenerateWindowPost(randomness Fil32ByteArray, replicasPtr []FilPrivateReplicaInfo, replicasLen uint, proverId Fil32ByteArray) *FilGenerateWindowPoStResponse { - crandomness, crandomnessAllocMap := randomness.PassValue() - creplicasPtr, creplicasPtrAllocMap := unpackArgSFilPrivateReplicaInfo(replicasPtr) - creplicasLen, creplicasLenAllocMap := (C.size_t)(replicasLen), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_generate_window_post(crandomness, creplicasPtr, creplicasLen, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(creplicasLenAllocMap) - packSFilPrivateReplicaInfo(replicasPtr, creplicasPtr) - runtime.KeepAlive(creplicasPtrAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - __v := NewFilGenerateWindowPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerifyWindowPost function as declared in filecoin-ffi/filcrypto.h:845 -func FilVerifyWindowPost(randomness Fil32ByteArray, replicasPtr []FilPublicReplicaInfo, replicasLen uint, proofsPtr []FilPoStProof, proofsLen uint, proverId Fil32ByteArray) *FilVerifyWindowPoStResponse { - crandomness, crandomnessAllocMap := randomness.PassValue() - creplicasPtr, creplicasPtrAllocMap := unpackArgSFilPublicReplicaInfo(replicasPtr) - creplicasLen, creplicasLenAllocMap := (C.size_t)(replicasLen), cgoAllocsUnknown - cproofsPtr, cproofsPtrAllocMap := unpackArgSFilPoStProof(proofsPtr) - cproofsLen, cproofsLenAllocMap := (C.size_t)(proofsLen), cgoAllocsUnknown - cproverId, cproverIdAllocMap := proverId.PassValue() - __ret := C.fil_verify_window_post(crandomness, creplicasPtr, creplicasLen, cproofsPtr, cproofsLen, cproverId) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(cproofsLenAllocMap) - packSFilPoStProof(proofsPtr, cproofsPtr) - runtime.KeepAlive(cproofsPtrAllocMap) - runtime.KeepAlive(creplicasLenAllocMap) - packSFilPublicReplicaInfo(replicasPtr, creplicasPtr) - runtime.KeepAlive(creplicasPtrAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - __v := NewFilVerifyWindowPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilMergeWindowPostPartitionProofs function as declared in filecoin-ffi/filcrypto.h:856 -func FilMergeWindowPostPartitionProofs(registeredProof FilRegisteredPoStProof, partitionProofsPtr []FilPartitionSnarkProof, partitionProofsLen uint) *FilMergeWindowPoStPartitionProofsResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - cpartitionProofsPtr, cpartitionProofsPtrAllocMap := unpackArgSFilPartitionSnarkProof(partitionProofsPtr) - cpartitionProofsLen, cpartitionProofsLenAllocMap := (C.size_t)(partitionProofsLen), cgoAllocsUnknown - __ret := C.fil_merge_window_post_partition_proofs(cregisteredProof, cpartitionProofsPtr, cpartitionProofsLen) - runtime.KeepAlive(cpartitionProofsLenAllocMap) - packSFilPartitionSnarkProof(partitionProofsPtr, cpartitionProofsPtr) - runtime.KeepAlive(cpartitionProofsPtrAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilMergeWindowPoStPartitionProofsResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetNumPartitionForFallbackPost function as declared in filecoin-ffi/filcrypto.h:864 -func FilGetNumPartitionForFallbackPost(registeredProof FilRegisteredPoStProof, numSectors uint) *FilGetNumPartitionForFallbackPoStResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - cnumSectors, cnumSectorsAllocMap := (C.size_t)(numSectors), cgoAllocsUnknown - __ret := C.fil_get_num_partition_for_fallback_post(cregisteredProof, cnumSectors) - runtime.KeepAlive(cnumSectorsAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGetNumPartitionForFallbackPoStResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateSingleWindowPostWithVanilla function as declared in filecoin-ffi/filcrypto.h:871 -func FilGenerateSingleWindowPostWithVanilla(registeredProof FilRegisteredPoStProof, randomness Fil32ByteArray, proverId Fil32ByteArray, vanillaProofsPtr []FilVanillaProof, vanillaProofsLen uint, partitionIndex uint) *FilGenerateSingleWindowPoStWithVanillaResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - crandomness, crandomnessAllocMap := randomness.PassValue() - cproverId, cproverIdAllocMap := proverId.PassValue() - cvanillaProofsPtr, cvanillaProofsPtrAllocMap := unpackArgSFilVanillaProof(vanillaProofsPtr) - cvanillaProofsLen, cvanillaProofsLenAllocMap := (C.size_t)(vanillaProofsLen), cgoAllocsUnknown - cpartitionIndex, cpartitionIndexAllocMap := (C.size_t)(partitionIndex), cgoAllocsUnknown - __ret := C.fil_generate_single_window_post_with_vanilla(cregisteredProof, crandomness, cproverId, cvanillaProofsPtr, cvanillaProofsLen, cpartitionIndex) - runtime.KeepAlive(cpartitionIndexAllocMap) - runtime.KeepAlive(cvanillaProofsLenAllocMap) - packSFilVanillaProof(vanillaProofsPtr, cvanillaProofsPtr) - runtime.KeepAlive(cvanillaProofsPtrAllocMap) - runtime.KeepAlive(cproverIdAllocMap) - runtime.KeepAlive(crandomnessAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGenerateSingleWindowPoStWithVanillaResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilEmptySectorUpdateEncodeInto function as declared in filecoin-ffi/filcrypto.h:882 -func FilEmptySectorUpdateEncodeInto(registeredProof FilRegisteredUpdateProof, newReplicaPath string, newCacheDirPath string, sectorKeyPath string, sectorKeyCacheDirPath string, stagedDataPath string, piecesPtr []FilPublicPieceInfo, piecesLen uint) *FilEmptySectorUpdateEncodeIntoResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - newReplicaPath = safeString(newReplicaPath) - cnewReplicaPath, cnewReplicaPathAllocMap := unpackPCharString(newReplicaPath) - newCacheDirPath = safeString(newCacheDirPath) - cnewCacheDirPath, cnewCacheDirPathAllocMap := unpackPCharString(newCacheDirPath) - sectorKeyPath = safeString(sectorKeyPath) - csectorKeyPath, csectorKeyPathAllocMap := unpackPCharString(sectorKeyPath) - sectorKeyCacheDirPath = safeString(sectorKeyCacheDirPath) - csectorKeyCacheDirPath, csectorKeyCacheDirPathAllocMap := unpackPCharString(sectorKeyCacheDirPath) - stagedDataPath = safeString(stagedDataPath) - cstagedDataPath, cstagedDataPathAllocMap := unpackPCharString(stagedDataPath) - cpiecesPtr, cpiecesPtrAllocMap := unpackArgSFilPublicPieceInfo(piecesPtr) - cpiecesLen, cpiecesLenAllocMap := (C.size_t)(piecesLen), cgoAllocsUnknown - __ret := C.fil_empty_sector_update_encode_into(cregisteredProof, cnewReplicaPath, cnewCacheDirPath, csectorKeyPath, csectorKeyCacheDirPath, cstagedDataPath, cpiecesPtr, cpiecesLen) - runtime.KeepAlive(cpiecesLenAllocMap) - packSFilPublicPieceInfo(piecesPtr, cpiecesPtr) - runtime.KeepAlive(cpiecesPtrAllocMap) - runtime.KeepAlive(stagedDataPath) - runtime.KeepAlive(cstagedDataPathAllocMap) - runtime.KeepAlive(sectorKeyCacheDirPath) - runtime.KeepAlive(csectorKeyCacheDirPathAllocMap) - runtime.KeepAlive(sectorKeyPath) - runtime.KeepAlive(csectorKeyPathAllocMap) - runtime.KeepAlive(newCacheDirPath) - runtime.KeepAlive(cnewCacheDirPathAllocMap) - runtime.KeepAlive(newReplicaPath) - runtime.KeepAlive(cnewReplicaPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilEmptySectorUpdateEncodeIntoResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilEmptySectorUpdateDecodeFrom function as declared in filecoin-ffi/filcrypto.h:895 -func FilEmptySectorUpdateDecodeFrom(registeredProof FilRegisteredUpdateProof, outDataPath string, replicaPath string, sectorKeyPath string, sectorKeyCacheDirPath string, commDNew Fil32ByteArray) *FilEmptySectorUpdateDecodeFromResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - outDataPath = safeString(outDataPath) - coutDataPath, coutDataPathAllocMap := unpackPCharString(outDataPath) - replicaPath = safeString(replicaPath) - creplicaPath, creplicaPathAllocMap := unpackPCharString(replicaPath) - sectorKeyPath = safeString(sectorKeyPath) - csectorKeyPath, csectorKeyPathAllocMap := unpackPCharString(sectorKeyPath) - sectorKeyCacheDirPath = safeString(sectorKeyCacheDirPath) - csectorKeyCacheDirPath, csectorKeyCacheDirPathAllocMap := unpackPCharString(sectorKeyCacheDirPath) - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - __ret := C.fil_empty_sector_update_decode_from(cregisteredProof, coutDataPath, creplicaPath, csectorKeyPath, csectorKeyCacheDirPath, ccommDNew) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(sectorKeyCacheDirPath) - runtime.KeepAlive(csectorKeyCacheDirPathAllocMap) - runtime.KeepAlive(sectorKeyPath) - runtime.KeepAlive(csectorKeyPathAllocMap) - runtime.KeepAlive(replicaPath) - runtime.KeepAlive(creplicaPathAllocMap) - runtime.KeepAlive(outDataPath) - runtime.KeepAlive(coutDataPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilEmptySectorUpdateDecodeFromResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilEmptySectorUpdateRemoveEncodedData function as declared in filecoin-ffi/filcrypto.h:906 -func FilEmptySectorUpdateRemoveEncodedData(registeredProof FilRegisteredUpdateProof, sectorKeyPath string, sectorKeyCacheDirPath string, replicaPath string, replicaCachePath string, dataPath string, commDNew Fil32ByteArray) *FilEmptySectorUpdateRemoveEncodedDataResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - sectorKeyPath = safeString(sectorKeyPath) - csectorKeyPath, csectorKeyPathAllocMap := unpackPCharString(sectorKeyPath) - sectorKeyCacheDirPath = safeString(sectorKeyCacheDirPath) - csectorKeyCacheDirPath, csectorKeyCacheDirPathAllocMap := unpackPCharString(sectorKeyCacheDirPath) - replicaPath = safeString(replicaPath) - creplicaPath, creplicaPathAllocMap := unpackPCharString(replicaPath) - replicaCachePath = safeString(replicaCachePath) - creplicaCachePath, creplicaCachePathAllocMap := unpackPCharString(replicaCachePath) - dataPath = safeString(dataPath) - cdataPath, cdataPathAllocMap := unpackPCharString(dataPath) - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - __ret := C.fil_empty_sector_update_remove_encoded_data(cregisteredProof, csectorKeyPath, csectorKeyCacheDirPath, creplicaPath, creplicaCachePath, cdataPath, ccommDNew) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(dataPath) - runtime.KeepAlive(cdataPathAllocMap) - runtime.KeepAlive(replicaCachePath) - runtime.KeepAlive(creplicaCachePathAllocMap) - runtime.KeepAlive(replicaPath) - runtime.KeepAlive(creplicaPathAllocMap) - runtime.KeepAlive(sectorKeyCacheDirPath) - runtime.KeepAlive(csectorKeyCacheDirPathAllocMap) - runtime.KeepAlive(sectorKeyPath) - runtime.KeepAlive(csectorKeyPathAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilEmptySectorUpdateRemoveEncodedDataResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateEmptySectorUpdatePartitionProofs function as declared in filecoin-ffi/filcrypto.h:918 -func FilGenerateEmptySectorUpdatePartitionProofs(registeredProof FilRegisteredUpdateProof, commROld Fil32ByteArray, commRNew Fil32ByteArray, commDNew Fil32ByteArray, sectorKeyPath string, sectorKeyCacheDirPath string, replicaPath string, replicaCachePath string) *FilPartitionProofResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - ccommROld, ccommROldAllocMap := commROld.PassValue() - ccommRNew, ccommRNewAllocMap := commRNew.PassValue() - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - sectorKeyPath = safeString(sectorKeyPath) - csectorKeyPath, csectorKeyPathAllocMap := unpackPCharString(sectorKeyPath) - sectorKeyCacheDirPath = safeString(sectorKeyCacheDirPath) - csectorKeyCacheDirPath, csectorKeyCacheDirPathAllocMap := unpackPCharString(sectorKeyCacheDirPath) - replicaPath = safeString(replicaPath) - creplicaPath, creplicaPathAllocMap := unpackPCharString(replicaPath) - replicaCachePath = safeString(replicaCachePath) - creplicaCachePath, creplicaCachePathAllocMap := unpackPCharString(replicaCachePath) - __ret := C.fil_generate_empty_sector_update_partition_proofs(cregisteredProof, ccommROld, ccommRNew, ccommDNew, csectorKeyPath, csectorKeyCacheDirPath, creplicaPath, creplicaCachePath) - runtime.KeepAlive(replicaCachePath) - runtime.KeepAlive(creplicaCachePathAllocMap) - runtime.KeepAlive(replicaPath) - runtime.KeepAlive(creplicaPathAllocMap) - runtime.KeepAlive(sectorKeyCacheDirPath) - runtime.KeepAlive(csectorKeyCacheDirPathAllocMap) - runtime.KeepAlive(sectorKeyPath) - runtime.KeepAlive(csectorKeyPathAllocMap) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(ccommRNewAllocMap) - runtime.KeepAlive(ccommROldAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilPartitionProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerifyEmptySectorUpdatePartitionProofs function as declared in filecoin-ffi/filcrypto.h:931 -func FilVerifyEmptySectorUpdatePartitionProofs(registeredProof FilRegisteredUpdateProof, proofsLen uint, proofsPtr []FilPartitionProof, commROld Fil32ByteArray, commRNew Fil32ByteArray, commDNew Fil32ByteArray) *FilVerifyPartitionProofResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - cproofsLen, cproofsLenAllocMap := (C.size_t)(proofsLen), cgoAllocsUnknown - cproofsPtr, cproofsPtrAllocMap := unpackArgSFilPartitionProof(proofsPtr) - ccommROld, ccommROldAllocMap := commROld.PassValue() - ccommRNew, ccommRNewAllocMap := commRNew.PassValue() - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - __ret := C.fil_verify_empty_sector_update_partition_proofs(cregisteredProof, cproofsLen, cproofsPtr, ccommROld, ccommRNew, ccommDNew) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(ccommRNewAllocMap) - runtime.KeepAlive(ccommROldAllocMap) - packSFilPartitionProof(proofsPtr, cproofsPtr) - runtime.KeepAlive(cproofsPtrAllocMap) - runtime.KeepAlive(cproofsLenAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilVerifyPartitionProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateEmptySectorUpdateProofWithVanilla function as declared in filecoin-ffi/filcrypto.h:942 -func FilGenerateEmptySectorUpdateProofWithVanilla(registeredProof FilRegisteredUpdateProof, vanillaProofsPtr []FilPartitionProof, vanillaProofsLen uint, commROld Fil32ByteArray, commRNew Fil32ByteArray, commDNew Fil32ByteArray) *FilEmptySectorUpdateProofResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - cvanillaProofsPtr, cvanillaProofsPtrAllocMap := unpackArgSFilPartitionProof(vanillaProofsPtr) - cvanillaProofsLen, cvanillaProofsLenAllocMap := (C.size_t)(vanillaProofsLen), cgoAllocsUnknown - ccommROld, ccommROldAllocMap := commROld.PassValue() - ccommRNew, ccommRNewAllocMap := commRNew.PassValue() - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - __ret := C.fil_generate_empty_sector_update_proof_with_vanilla(cregisteredProof, cvanillaProofsPtr, cvanillaProofsLen, ccommROld, ccommRNew, ccommDNew) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(ccommRNewAllocMap) - runtime.KeepAlive(ccommROldAllocMap) - runtime.KeepAlive(cvanillaProofsLenAllocMap) - packSFilPartitionProof(vanillaProofsPtr, cvanillaProofsPtr) - runtime.KeepAlive(cvanillaProofsPtrAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilEmptySectorUpdateProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateEmptySectorUpdateProof function as declared in filecoin-ffi/filcrypto.h:953 -func FilGenerateEmptySectorUpdateProof(registeredProof FilRegisteredUpdateProof, commROld Fil32ByteArray, commRNew Fil32ByteArray, commDNew Fil32ByteArray, sectorKeyPath string, sectorKeyCacheDirPath string, replicaPath string, replicaCachePath string) *FilEmptySectorUpdateProofResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - ccommROld, ccommROldAllocMap := commROld.PassValue() - ccommRNew, ccommRNewAllocMap := commRNew.PassValue() - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - sectorKeyPath = safeString(sectorKeyPath) - csectorKeyPath, csectorKeyPathAllocMap := unpackPCharString(sectorKeyPath) - sectorKeyCacheDirPath = safeString(sectorKeyCacheDirPath) - csectorKeyCacheDirPath, csectorKeyCacheDirPathAllocMap := unpackPCharString(sectorKeyCacheDirPath) - replicaPath = safeString(replicaPath) - creplicaPath, creplicaPathAllocMap := unpackPCharString(replicaPath) - replicaCachePath = safeString(replicaCachePath) - creplicaCachePath, creplicaCachePathAllocMap := unpackPCharString(replicaCachePath) - __ret := C.fil_generate_empty_sector_update_proof(cregisteredProof, ccommROld, ccommRNew, ccommDNew, csectorKeyPath, csectorKeyCacheDirPath, creplicaPath, creplicaCachePath) - runtime.KeepAlive(replicaCachePath) - runtime.KeepAlive(creplicaCachePathAllocMap) - runtime.KeepAlive(replicaPath) - runtime.KeepAlive(creplicaPathAllocMap) - runtime.KeepAlive(sectorKeyCacheDirPath) - runtime.KeepAlive(csectorKeyCacheDirPathAllocMap) - runtime.KeepAlive(sectorKeyPath) - runtime.KeepAlive(csectorKeyPathAllocMap) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(ccommRNewAllocMap) - runtime.KeepAlive(ccommROldAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilEmptySectorUpdateProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilVerifyEmptySectorUpdateProof function as declared in filecoin-ffi/filcrypto.h:966 -func FilVerifyEmptySectorUpdateProof(registeredProof FilRegisteredUpdateProof, proofPtr []byte, proofLen uint, commROld Fil32ByteArray, commRNew Fil32ByteArray, commDNew Fil32ByteArray) *FilVerifyEmptySectorUpdateProofResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredUpdateProof)(registeredProof), cgoAllocsUnknown - cproofPtr, cproofPtrAllocMap := copyPUint8TBytes((*sliceHeader)(unsafe.Pointer(&proofPtr))) - cproofLen, cproofLenAllocMap := (C.size_t)(proofLen), cgoAllocsUnknown - ccommROld, ccommROldAllocMap := commROld.PassValue() - ccommRNew, ccommRNewAllocMap := commRNew.PassValue() - ccommDNew, ccommDNewAllocMap := commDNew.PassValue() - __ret := C.fil_verify_empty_sector_update_proof(cregisteredProof, cproofPtr, cproofLen, ccommROld, ccommRNew, ccommDNew) - runtime.KeepAlive(ccommDNewAllocMap) - runtime.KeepAlive(ccommRNewAllocMap) - runtime.KeepAlive(ccommROldAllocMap) - runtime.KeepAlive(cproofLenAllocMap) - runtime.KeepAlive(cproofPtrAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilVerifyEmptySectorUpdateProofResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGeneratePieceCommitment function as declared in filecoin-ffi/filcrypto.h:977 -func FilGeneratePieceCommitment(registeredProof FilRegisteredSealProof, pieceFdRaw int32, unpaddedPieceSize uint64) *FilGeneratePieceCommitmentResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cpieceFdRaw, cpieceFdRawAllocMap := (C.int)(pieceFdRaw), cgoAllocsUnknown - cunpaddedPieceSize, cunpaddedPieceSizeAllocMap := (C.uint64_t)(unpaddedPieceSize), cgoAllocsUnknown - __ret := C.fil_generate_piece_commitment(cregisteredProof, cpieceFdRaw, cunpaddedPieceSize) - runtime.KeepAlive(cunpaddedPieceSizeAllocMap) - runtime.KeepAlive(cpieceFdRawAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGeneratePieceCommitmentResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGenerateDataCommitment function as declared in filecoin-ffi/filcrypto.h:984 -func FilGenerateDataCommitment(registeredProof FilRegisteredSealProof, piecesPtr []FilPublicPieceInfo, piecesLen uint) *FilGenerateDataCommitmentResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - cpiecesPtr, cpiecesPtrAllocMap := unpackArgSFilPublicPieceInfo(piecesPtr) - cpiecesLen, cpiecesLenAllocMap := (C.size_t)(piecesLen), cgoAllocsUnknown - __ret := C.fil_generate_data_commitment(cregisteredProof, cpiecesPtr, cpiecesLen) - runtime.KeepAlive(cpiecesLenAllocMap) - packSFilPublicPieceInfo(piecesPtr, cpiecesPtr) - runtime.KeepAlive(cpiecesPtrAllocMap) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilGenerateDataCommitmentResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilClearCache function as declared in filecoin-ffi/filcrypto.h:988 -func FilClearCache(sectorSize uint64, cacheDirPath string) *FilClearCacheResponse { - csectorSize, csectorSizeAllocMap := (C.uint64_t)(sectorSize), cgoAllocsUnknown - cacheDirPath = safeString(cacheDirPath) - ccacheDirPath, ccacheDirPathAllocMap := unpackPCharString(cacheDirPath) - __ret := C.fil_clear_cache(csectorSize, ccacheDirPath) - runtime.KeepAlive(cacheDirPath) - runtime.KeepAlive(ccacheDirPathAllocMap) - runtime.KeepAlive(csectorSizeAllocMap) - __v := NewFilClearCacheResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilDestroyWriteWithAlignmentResponse function as declared in filecoin-ffi/filcrypto.h:990 -func FilDestroyWriteWithAlignmentResponse(ptr *FilWriteWithAlignmentResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_write_with_alignment_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyWriteWithoutAlignmentResponse function as declared in filecoin-ffi/filcrypto.h:992 -func FilDestroyWriteWithoutAlignmentResponse(ptr *FilWriteWithoutAlignmentResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_write_without_alignment_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyFauxrepResponse function as declared in filecoin-ffi/filcrypto.h:994 -func FilDestroyFauxrepResponse(ptr *FilFauxRepResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_fauxrep_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroySealPreCommitPhase1Response function as declared in filecoin-ffi/filcrypto.h:996 -func FilDestroySealPreCommitPhase1Response(ptr *FilSealPreCommitPhase1Response) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_seal_pre_commit_phase1_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroySealPreCommitPhase2Response function as declared in filecoin-ffi/filcrypto.h:998 -func FilDestroySealPreCommitPhase2Response(ptr *FilSealPreCommitPhase2Response) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_seal_pre_commit_phase2_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroySealCommitPhase1Response function as declared in filecoin-ffi/filcrypto.h:1000 -func FilDestroySealCommitPhase1Response(ptr *FilSealCommitPhase1Response) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_seal_commit_phase1_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroySealCommitPhase2Response function as declared in filecoin-ffi/filcrypto.h:1002 -func FilDestroySealCommitPhase2Response(ptr *FilSealCommitPhase2Response) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_seal_commit_phase2_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyUnsealRangeResponse function as declared in filecoin-ffi/filcrypto.h:1004 -func FilDestroyUnsealRangeResponse(ptr *FilUnsealRangeResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_unseal_range_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGeneratePieceCommitmentResponse function as declared in filecoin-ffi/filcrypto.h:1006 -func FilDestroyGeneratePieceCommitmentResponse(ptr *FilGeneratePieceCommitmentResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_piece_commitment_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateDataCommitmentResponse function as declared in filecoin-ffi/filcrypto.h:1008 -func FilDestroyGenerateDataCommitmentResponse(ptr *FilGenerateDataCommitmentResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_data_commitment_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyStringResponse function as declared in filecoin-ffi/filcrypto.h:1010 -func FilDestroyStringResponse(ptr *FilStringResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_string_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilGetMaxUserBytesPerStagedSector function as declared in filecoin-ffi/filcrypto.h:1016 -func FilGetMaxUserBytesPerStagedSector(registeredProof FilRegisteredSealProof) uint64 { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_max_user_bytes_per_staged_sector(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := (uint64)(__ret) - return __v -} - -// FilGetSealParamsCid function as declared in filecoin-ffi/filcrypto.h:1022 -func FilGetSealParamsCid(registeredProof FilRegisteredSealProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_seal_params_cid(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetSealVerifyingKeyCid function as declared in filecoin-ffi/filcrypto.h:1028 -func FilGetSealVerifyingKeyCid(registeredProof FilRegisteredSealProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_seal_verifying_key_cid(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetSealParamsPath function as declared in filecoin-ffi/filcrypto.h:1035 -func FilGetSealParamsPath(registeredProof FilRegisteredSealProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_seal_params_path(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetSealVerifyingKeyPath function as declared in filecoin-ffi/filcrypto.h:1042 -func FilGetSealVerifyingKeyPath(registeredProof FilRegisteredSealProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_seal_verifying_key_path(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetSealCircuitIdentifier function as declared in filecoin-ffi/filcrypto.h:1048 -func FilGetSealCircuitIdentifier(registeredProof FilRegisteredSealProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_seal_circuit_identifier(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetSealVersion function as declared in filecoin-ffi/filcrypto.h:1054 -func FilGetSealVersion(registeredProof FilRegisteredSealProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredSealProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_seal_version(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetPostParamsCid function as declared in filecoin-ffi/filcrypto.h:1060 -func FilGetPostParamsCid(registeredProof FilRegisteredPoStProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_post_params_cid(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetPostVerifyingKeyCid function as declared in filecoin-ffi/filcrypto.h:1066 -func FilGetPostVerifyingKeyCid(registeredProof FilRegisteredPoStProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_post_verifying_key_cid(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetPostParamsPath function as declared in filecoin-ffi/filcrypto.h:1073 -func FilGetPostParamsPath(registeredProof FilRegisteredPoStProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_post_params_path(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetPostVerifyingKeyPath function as declared in filecoin-ffi/filcrypto.h:1080 -func FilGetPostVerifyingKeyPath(registeredProof FilRegisteredPoStProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_post_verifying_key_path(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetPostCircuitIdentifier function as declared in filecoin-ffi/filcrypto.h:1086 -func FilGetPostCircuitIdentifier(registeredProof FilRegisteredPoStProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_post_circuit_identifier(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilGetPostVersion function as declared in filecoin-ffi/filcrypto.h:1092 -func FilGetPostVersion(registeredProof FilRegisteredPoStProof) *FilStringResponse { - cregisteredProof, cregisteredProofAllocMap := (C.enum_fil_RegisteredPoStProof)(registeredProof), cgoAllocsUnknown - __ret := C.fil_get_post_version(cregisteredProof) - runtime.KeepAlive(cregisteredProofAllocMap) - __v := NewFilStringResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilDestroyVerifySealResponse function as declared in filecoin-ffi/filcrypto.h:1098 -func FilDestroyVerifySealResponse(ptr *FilVerifySealResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_verify_seal_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyVerifyAggregateSealResponse function as declared in filecoin-ffi/filcrypto.h:1104 -func FilDestroyVerifyAggregateSealResponse(ptr *FilVerifyAggregateSealProofResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_verify_aggregate_seal_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyFinalizeTicketResponse function as declared in filecoin-ffi/filcrypto.h:1106 -func FilDestroyFinalizeTicketResponse(ptr *FilFinalizeTicketResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_finalize_ticket_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyVerifyWinningPostResponse function as declared in filecoin-ffi/filcrypto.h:1112 -func FilDestroyVerifyWinningPostResponse(ptr *FilVerifyWinningPoStResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_verify_winning_post_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyVerifyWindowPostResponse function as declared in filecoin-ffi/filcrypto.h:1114 -func FilDestroyVerifyWindowPostResponse(ptr *FilVerifyWindowPoStResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_verify_window_post_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateFallbackSectorChallengesResponse function as declared in filecoin-ffi/filcrypto.h:1116 -func FilDestroyGenerateFallbackSectorChallengesResponse(ptr *FilGenerateFallbackSectorChallengesResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_fallback_sector_challenges_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateSingleVanillaProofResponse function as declared in filecoin-ffi/filcrypto.h:1118 -func FilDestroyGenerateSingleVanillaProofResponse(ptr *FilGenerateSingleVanillaProofResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_single_vanilla_proof_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateSingleWindowPostWithVanillaResponse function as declared in filecoin-ffi/filcrypto.h:1120 -func FilDestroyGenerateSingleWindowPostWithVanillaResponse(ptr *FilGenerateSingleWindowPoStWithVanillaResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_single_window_post_with_vanilla_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGetNumPartitionForFallbackPostResponse function as declared in filecoin-ffi/filcrypto.h:1122 -func FilDestroyGetNumPartitionForFallbackPostResponse(ptr *FilGetNumPartitionForFallbackPoStResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_get_num_partition_for_fallback_post_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyMergeWindowPostPartitionProofsResponse function as declared in filecoin-ffi/filcrypto.h:1124 -func FilDestroyMergeWindowPostPartitionProofsResponse(ptr *FilMergeWindowPoStPartitionProofsResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_merge_window_post_partition_proofs_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateWinningPostResponse function as declared in filecoin-ffi/filcrypto.h:1126 -func FilDestroyGenerateWinningPostResponse(ptr *FilGenerateWinningPoStResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_winning_post_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateWindowPostResponse function as declared in filecoin-ffi/filcrypto.h:1128 -func FilDestroyGenerateWindowPostResponse(ptr *FilGenerateWindowPoStResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_window_post_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateWinningPostSectorChallenge function as declared in filecoin-ffi/filcrypto.h:1130 -func FilDestroyGenerateWinningPostSectorChallenge(ptr *FilGenerateWinningPoStSectorChallenge) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_winning_post_sector_challenge(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyClearCacheResponse function as declared in filecoin-ffi/filcrypto.h:1132 -func FilDestroyClearCacheResponse(ptr *FilClearCacheResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_clear_cache_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyAggregateProof function as declared in filecoin-ffi/filcrypto.h:1138 -func FilDestroyAggregateProof(ptr *FilAggregateProof) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_aggregate_proof(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyEmptySectorUpdateGenerateProofResponse function as declared in filecoin-ffi/filcrypto.h:1144 -func FilDestroyEmptySectorUpdateGenerateProofResponse(ptr *FilEmptySectorUpdateProofResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_empty_sector_update_generate_proof_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyEmptySectorUpdateVerifyProofResponse function as declared in filecoin-ffi/filcrypto.h:1150 -func FilDestroyEmptySectorUpdateVerifyProofResponse(ptr *FilVerifyEmptySectorUpdateProofResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_empty_sector_update_verify_proof_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyGenerateEmptySectorUpdatePartitionProofResponse function as declared in filecoin-ffi/filcrypto.h:1156 -func FilDestroyGenerateEmptySectorUpdatePartitionProofResponse(ptr *FilPartitionProofResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_generate_empty_sector_update_partition_proof_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyVerifyEmptySectorUpdatePartitionProofResponse function as declared in filecoin-ffi/filcrypto.h:1162 -func FilDestroyVerifyEmptySectorUpdatePartitionProofResponse(ptr *FilVerifyPartitionProofResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_verify_empty_sector_update_partition_proof_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyEmptySectorUpdateEncodeIntoResponse function as declared in filecoin-ffi/filcrypto.h:1168 -func FilDestroyEmptySectorUpdateEncodeIntoResponse(ptr *FilEmptySectorUpdateEncodeIntoResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_empty_sector_update_encode_into_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyEmptySectorUpdateDecodeFromResponse function as declared in filecoin-ffi/filcrypto.h:1174 -func FilDestroyEmptySectorUpdateDecodeFromResponse(ptr *FilEmptySectorUpdateDecodeFromResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_empty_sector_update_decode_from_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyEmptySectorUpdateRemoveEncodedDataResponse function as declared in filecoin-ffi/filcrypto.h:1180 -func FilDestroyEmptySectorUpdateRemoveEncodedDataResponse(ptr *FilEmptySectorUpdateRemoveEncodedDataResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_empty_sector_update_remove_encoded_data_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilGetGpuDevices function as declared in filecoin-ffi/filcrypto.h:1185 -func FilGetGpuDevices() *FilGpuDeviceResponse { - __ret := C.fil_get_gpu_devices() - __v := NewFilGpuDeviceResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilInitLogFd function as declared in filecoin-ffi/filcrypto.h:1196 -func FilInitLogFd(logFd int32) *FilInitLogFdResponse { - clogFd, clogFdAllocMap := (C.int)(logFd), cgoAllocsUnknown - __ret := C.fil_init_log_fd(clogFd) - runtime.KeepAlive(clogFdAllocMap) - __v := NewFilInitLogFdResponseRef(unsafe.Pointer(__ret)) - return __v -} - -// FilDestroyGpuDeviceResponse function as declared in filecoin-ffi/filcrypto.h:1198 -func FilDestroyGpuDeviceResponse(ptr *FilGpuDeviceResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_gpu_device_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} - -// FilDestroyInitLogFdResponse function as declared in filecoin-ffi/filcrypto.h:1200 -func FilDestroyInitLogFdResponse(ptr *FilInitLogFdResponse) { - cptr, cptrAllocMap := ptr.PassRef() - C.fil_destroy_init_log_fd_response(cptr) - runtime.KeepAlive(cptrAllocMap) -} diff --git a/generated/types.go b/generated/types.go deleted file mode 100644 index 2466f61d..00000000 --- a/generated/types.go +++ /dev/null @@ -1,542 +0,0 @@ -// WARNING: This file has automatically been generated -// Code generated by https://git.io/c-for-go. DO NOT EDIT. - -package generated - -/* -#cgo linux LDFLAGS: -L${SRCDIR}/.. -Wl,-unresolved-symbols=ignore-all -#cgo darwin LDFLAGS: -L${SRCDIR}/.. -Wl,-undefined,dynamic_lookup -#cgo pkg-config: ${SRCDIR}/../filcrypto.pc -#include "../filcrypto.h" -#include -#include "cgo_helpers.h" -*/ -import "C" -import "unsafe" - -// FilBLSDigest as declared in filecoin-ffi/filcrypto.h:102 -type FilBLSDigest struct { - Inner [96]byte - ref215fc78c *C.fil_BLSDigest - allocs215fc78c interface{} -} - -// FilHashResponse as declared in filecoin-ffi/filcrypto.h:109 -type FilHashResponse struct { - Digest FilBLSDigest - refc52a22ef *C.fil_HashResponse - allocsc52a22ef interface{} -} - -// FilBLSSignature as declared in filecoin-ffi/filcrypto.h:113 -type FilBLSSignature struct { - Inner [96]byte - refa2ac09ba *C.fil_BLSSignature - allocsa2ac09ba interface{} -} - -// FilAggregateResponse as declared in filecoin-ffi/filcrypto.h:120 -type FilAggregateResponse struct { - Signature FilBLSSignature - refb3efa36d *C.fil_AggregateResponse - allocsb3efa36d interface{} -} - -// FilBLSPrivateKey as declared in filecoin-ffi/filcrypto.h:124 -type FilBLSPrivateKey struct { - Inner [32]byte - ref2f77fe3a *C.fil_BLSPrivateKey - allocs2f77fe3a interface{} -} - -// FilPrivateKeyGenerateResponse as declared in filecoin-ffi/filcrypto.h:131 -type FilPrivateKeyGenerateResponse struct { - PrivateKey FilBLSPrivateKey - ref2dba09f *C.fil_PrivateKeyGenerateResponse - allocs2dba09f interface{} -} - -// Fil32ByteArray as declared in filecoin-ffi/filcrypto.h:135 -type Fil32ByteArray struct { - Inner [32]byte - ref373ec61a *C.fil_32ByteArray - allocs373ec61a interface{} -} - -// FilPrivateKeySignResponse as declared in filecoin-ffi/filcrypto.h:142 -type FilPrivateKeySignResponse struct { - Signature FilBLSSignature - refcdf97b28 *C.fil_PrivateKeySignResponse - allocscdf97b28 interface{} -} - -// FilBLSPublicKey as declared in filecoin-ffi/filcrypto.h:146 -type FilBLSPublicKey struct { - Inner [48]byte - ref6d0cab13 *C.fil_BLSPublicKey - allocs6d0cab13 interface{} -} - -// FilPrivateKeyPublicKeyResponse as declared in filecoin-ffi/filcrypto.h:153 -type FilPrivateKeyPublicKeyResponse struct { - PublicKey FilBLSPublicKey - refee14e59d *C.fil_PrivateKeyPublicKeyResponse - allocsee14e59d interface{} -} - -// FilZeroSignatureResponse as declared in filecoin-ffi/filcrypto.h:160 -type FilZeroSignatureResponse struct { - Signature FilBLSSignature - ref835a0405 *C.fil_ZeroSignatureResponse - allocs835a0405 interface{} -} - -// FilCreateFvmMachineResponse as declared in filecoin-ffi/filcrypto.h:166 -type FilCreateFvmMachineResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - Executor unsafe.Pointer - ref40465416 *C.fil_CreateFvmMachineResponse - allocs40465416 interface{} -} - -// FilFvmMachineExecuteResponse as declared in filecoin-ffi/filcrypto.h:183 -type FilFvmMachineExecuteResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - ExitCode uint64 - ReturnPtr []byte - ReturnLen uint - GasUsed uint64 - PenaltyHi uint64 - PenaltyLo uint64 - MinerTipHi uint64 - MinerTipLo uint64 - ExecTracePtr []byte - ExecTraceLen uint - FailureInfoPtr []byte - FailureInfoLen uint - ref88f63595 *C.fil_FvmMachineExecuteResponse - allocs88f63595 interface{} -} - -// FilFvmMachineFlushResponse as declared in filecoin-ffi/filcrypto.h:190 -type FilFvmMachineFlushResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - StateRootPtr []byte - StateRootLen uint - ref9eb3b4f4 *C.fil_FvmMachineFlushResponse - allocs9eb3b4f4 interface{} -} - -// FilWriteWithAlignmentResponse as declared in filecoin-ffi/filcrypto.h:198 -type FilWriteWithAlignmentResponse struct { - CommP [32]byte - ErrorMsg string - LeftAlignmentUnpadded uint64 - StatusCode FCPResponseStatus - TotalWriteUnpadded uint64 - refa330e79 *C.fil_WriteWithAlignmentResponse - allocsa330e79 interface{} -} - -// FilWriteWithoutAlignmentResponse as declared in filecoin-ffi/filcrypto.h:205 -type FilWriteWithoutAlignmentResponse struct { - CommP [32]byte - ErrorMsg string - StatusCode FCPResponseStatus - TotalWriteUnpadded uint64 - refc8e1ed8 *C.fil_WriteWithoutAlignmentResponse - allocsc8e1ed8 interface{} -} - -// FilFauxRepResponse as declared in filecoin-ffi/filcrypto.h:211 -type FilFauxRepResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - Commitment [32]byte - refaa003f71 *C.fil_FauxRepResponse - allocsaa003f71 interface{} -} - -// FilSealPreCommitPhase1Response as declared in filecoin-ffi/filcrypto.h:218 -type FilSealPreCommitPhase1Response struct { - ErrorMsg string - StatusCode FCPResponseStatus - SealPreCommitPhase1OutputPtr []byte - SealPreCommitPhase1OutputLen uint - ref132bbfd8 *C.fil_SealPreCommitPhase1Response - allocs132bbfd8 interface{} -} - -// FilPublicPieceInfo as declared in filecoin-ffi/filcrypto.h:223 -type FilPublicPieceInfo struct { - NumBytes uint64 - CommP [32]byte - refd00025ac *C.fil_PublicPieceInfo - allocsd00025ac interface{} -} - -// FilSealPreCommitPhase2Response as declared in filecoin-ffi/filcrypto.h:231 -type FilSealPreCommitPhase2Response struct { - ErrorMsg string - StatusCode FCPResponseStatus - RegisteredProof FilRegisteredSealProof - CommD [32]byte - CommR [32]byte - ref2aa6831d *C.fil_SealPreCommitPhase2Response - allocs2aa6831d interface{} -} - -// FilSealCommitPhase1Response as declared in filecoin-ffi/filcrypto.h:238 -type FilSealCommitPhase1Response struct { - StatusCode FCPResponseStatus - ErrorMsg string - SealCommitPhase1OutputPtr []byte - SealCommitPhase1OutputLen uint - ref61ed8561 *C.fil_SealCommitPhase1Response - allocs61ed8561 interface{} -} - -// FilAggregationInputs as declared in filecoin-ffi/filcrypto.h:246 -type FilAggregationInputs struct { - CommR Fil32ByteArray - CommD Fil32ByteArray - SectorId uint64 - Ticket Fil32ByteArray - Seed Fil32ByteArray - ref90b967c9 *C.fil_AggregationInputs - allocs90b967c9 interface{} -} - -// FilSealCommitPhase2Response as declared in filecoin-ffi/filcrypto.h:255 -type FilSealCommitPhase2Response struct { - StatusCode FCPResponseStatus - ErrorMsg string - ProofPtr []byte - ProofLen uint - CommitInputsPtr []FilAggregationInputs - CommitInputsLen uint - ref5860b9a4 *C.fil_SealCommitPhase2Response - allocs5860b9a4 interface{} -} - -// FilAggregateProof as declared in filecoin-ffi/filcrypto.h:262 -type FilAggregateProof struct { - StatusCode FCPResponseStatus - ErrorMsg string - ProofLen uint - ProofPtr []byte - ref22b6c4f6 *C.fil_AggregateProof - allocs22b6c4f6 interface{} -} - -// FilVerifyAggregateSealProofResponse as declared in filecoin-ffi/filcrypto.h:268 -type FilVerifyAggregateSealProofResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - IsValid bool - ref66180e0 *C.fil_VerifyAggregateSealProofResponse - allocs66180e0 interface{} -} - -// FilUnsealRangeResponse as declared in filecoin-ffi/filcrypto.h:273 -type FilUnsealRangeResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - ref61e219c9 *C.fil_UnsealRangeResponse - allocs61e219c9 interface{} -} - -// FilVerifySealResponse as declared in filecoin-ffi/filcrypto.h:279 -type FilVerifySealResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - IsValid bool - refd4397079 *C.fil_VerifySealResponse - allocsd4397079 interface{} -} - -// FilGenerateWinningPoStSectorChallenge as declared in filecoin-ffi/filcrypto.h:286 -type FilGenerateWinningPoStSectorChallenge struct { - ErrorMsg string - StatusCode FCPResponseStatus - IdsPtr []uint64 - IdsLen uint - ref69d2a405 *C.fil_GenerateWinningPoStSectorChallenge - allocs69d2a405 interface{} -} - -// FilGenerateFallbackSectorChallengesResponse as declared in filecoin-ffi/filcrypto.h:296 -type FilGenerateFallbackSectorChallengesResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - IdsPtr []uint64 - IdsLen uint - ChallengesPtr []uint64 - ChallengesLen uint - ChallengesStride uint - ref7047a3fa *C.fil_GenerateFallbackSectorChallengesResponse - allocs7047a3fa interface{} -} - -// FilVanillaProof as declared in filecoin-ffi/filcrypto.h:301 -type FilVanillaProof struct { - ProofLen uint - ProofPtr []byte - refb3e7638c *C.fil_VanillaProof - allocsb3e7638c interface{} -} - -// FilGenerateSingleVanillaProofResponse as declared in filecoin-ffi/filcrypto.h:307 -type FilGenerateSingleVanillaProofResponse struct { - ErrorMsg string - VanillaProof FilVanillaProof - StatusCode FCPResponseStatus - reff9d21b04 *C.fil_GenerateSingleVanillaProofResponse - allocsf9d21b04 interface{} -} - -// FilPrivateReplicaInfo as declared in filecoin-ffi/filcrypto.h:315 -type FilPrivateReplicaInfo struct { - RegisteredProof FilRegisteredPoStProof - CacheDirPath string - CommR [32]byte - ReplicaPath string - SectorId uint64 - ref81a31e9b *C.fil_PrivateReplicaInfo - allocs81a31e9b interface{} -} - -// FilPoStProof as declared in filecoin-ffi/filcrypto.h:321 -type FilPoStProof struct { - RegisteredProof FilRegisteredPoStProof - ProofLen uint - ProofPtr []byte - ref3451bfa *C.fil_PoStProof - allocs3451bfa interface{} -} - -// FilGenerateWinningPoStResponse as declared in filecoin-ffi/filcrypto.h:328 -type FilGenerateWinningPoStResponse struct { - ErrorMsg string - ProofsLen uint - ProofsPtr []FilPoStProof - StatusCode FCPResponseStatus - ref1405b8ec *C.fil_GenerateWinningPoStResponse - allocs1405b8ec interface{} -} - -// FilVerifyWinningPoStResponse as declared in filecoin-ffi/filcrypto.h:334 -type FilVerifyWinningPoStResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - IsValid bool - refaca6860c *C.fil_VerifyWinningPoStResponse - allocsaca6860c interface{} -} - -// FilPublicReplicaInfo as declared in filecoin-ffi/filcrypto.h:340 -type FilPublicReplicaInfo struct { - RegisteredProof FilRegisteredPoStProof - CommR [32]byte - SectorId uint64 - ref81b617c2 *C.fil_PublicReplicaInfo - allocs81b617c2 interface{} -} - -// FilGenerateWindowPoStResponse as declared in filecoin-ffi/filcrypto.h:349 -type FilGenerateWindowPoStResponse struct { - ErrorMsg string - ProofsLen uint - ProofsPtr []FilPoStProof - FaultySectorsLen uint - FaultySectorsPtr []uint64 - StatusCode FCPResponseStatus - ref2a5f3ba8 *C.fil_GenerateWindowPoStResponse - allocs2a5f3ba8 interface{} -} - -// FilVerifyWindowPoStResponse as declared in filecoin-ffi/filcrypto.h:355 -type FilVerifyWindowPoStResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - IsValid bool - ref34c4d49f *C.fil_VerifyWindowPoStResponse - allocs34c4d49f interface{} -} - -// FilMergeWindowPoStPartitionProofsResponse as declared in filecoin-ffi/filcrypto.h:361 -type FilMergeWindowPoStPartitionProofsResponse struct { - ErrorMsg string - Proof FilPoStProof - StatusCode FCPResponseStatus - ref3369154e *C.fil_MergeWindowPoStPartitionProofsResponse - allocs3369154e interface{} -} - -// FilPartitionSnarkProof as declared in filecoin-ffi/filcrypto.h:367 -type FilPartitionSnarkProof struct { - RegisteredProof FilRegisteredPoStProof - ProofLen uint - ProofPtr []byte - ref4de03739 *C.fil_PartitionSnarkProof - allocs4de03739 interface{} -} - -// FilGetNumPartitionForFallbackPoStResponse as declared in filecoin-ffi/filcrypto.h:373 -type FilGetNumPartitionForFallbackPoStResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - NumPartition uint - refc0084478 *C.fil_GetNumPartitionForFallbackPoStResponse - allocsc0084478 interface{} -} - -// FilGenerateSingleWindowPoStWithVanillaResponse as declared in filecoin-ffi/filcrypto.h:381 -type FilGenerateSingleWindowPoStWithVanillaResponse struct { - ErrorMsg string - PartitionProof FilPartitionSnarkProof - FaultySectorsLen uint - FaultySectorsPtr []uint64 - StatusCode FCPResponseStatus - ref96c012c3 *C.fil_GenerateSingleWindowPoStWithVanillaResponse - allocs96c012c3 interface{} -} - -// FilEmptySectorUpdateEncodeIntoResponse as declared in filecoin-ffi/filcrypto.h:389 -type FilEmptySectorUpdateEncodeIntoResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - CommRNew [32]byte - CommRLastNew [32]byte - CommDNew [32]byte - ref8d3238a7 *C.fil_EmptySectorUpdateEncodeIntoResponse - allocs8d3238a7 interface{} -} - -// FilEmptySectorUpdateDecodeFromResponse as declared in filecoin-ffi/filcrypto.h:394 -type FilEmptySectorUpdateDecodeFromResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - reff02a01b8 *C.fil_EmptySectorUpdateDecodeFromResponse - allocsf02a01b8 interface{} -} - -// FilEmptySectorUpdateRemoveEncodedDataResponse as declared in filecoin-ffi/filcrypto.h:399 -type FilEmptySectorUpdateRemoveEncodedDataResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - ref50783b83 *C.fil_EmptySectorUpdateRemoveEncodedDataResponse - allocs50783b83 interface{} -} - -// FilPartitionProof as declared in filecoin-ffi/filcrypto.h:404 -type FilPartitionProof struct { - ProofLen uint - ProofPtr []byte - ref566a2be6 *C.fil_PartitionProof - allocs566a2be6 interface{} -} - -// FilPartitionProofResponse as declared in filecoin-ffi/filcrypto.h:411 -type FilPartitionProofResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - ProofsLen uint - ProofsPtr []FilPartitionProof - ref51343e7a *C.fil_PartitionProofResponse - allocs51343e7a interface{} -} - -// FilVerifyPartitionProofResponse as declared in filecoin-ffi/filcrypto.h:417 -type FilVerifyPartitionProofResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - IsValid bool - refaed1b67 *C.fil_VerifyPartitionProofResponse - allocsaed1b67 interface{} -} - -// FilEmptySectorUpdateProofResponse as declared in filecoin-ffi/filcrypto.h:424 -type FilEmptySectorUpdateProofResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - ProofLen uint - ProofPtr []byte - ref5c2faef *C.fil_EmptySectorUpdateProofResponse - allocs5c2faef interface{} -} - -// FilVerifyEmptySectorUpdateProofResponse as declared in filecoin-ffi/filcrypto.h:430 -type FilVerifyEmptySectorUpdateProofResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - IsValid bool - ref50b7b13 *C.fil_VerifyEmptySectorUpdateProofResponse - allocs50b7b13 interface{} -} - -// FilGeneratePieceCommitmentResponse as declared in filecoin-ffi/filcrypto.h:441 -type FilGeneratePieceCommitmentResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - CommP [32]byte - NumBytesAligned uint64 - ref4b00fda4 *C.fil_GeneratePieceCommitmentResponse - allocs4b00fda4 interface{} -} - -// FilGenerateDataCommitmentResponse as declared in filecoin-ffi/filcrypto.h:447 -type FilGenerateDataCommitmentResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - CommD [32]byte - ref87da7dd9 *C.fil_GenerateDataCommitmentResponse - allocs87da7dd9 interface{} -} - -// FilClearCacheResponse as declared in filecoin-ffi/filcrypto.h:452 -type FilClearCacheResponse struct { - ErrorMsg string - StatusCode FCPResponseStatus - refa9a80400 *C.fil_ClearCacheResponse - allocsa9a80400 interface{} -} - -// FilStringResponse as declared in filecoin-ffi/filcrypto.h:461 -type FilStringResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - StringVal string - ref4f413043 *C.fil_StringResponse - allocs4f413043 interface{} -} - -// FilFinalizeTicketResponse as declared in filecoin-ffi/filcrypto.h:467 -type FilFinalizeTicketResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - Ticket [32]byte - refb370fa86 *C.fil_FinalizeTicketResponse - allocsb370fa86 interface{} -} - -// FilGpuDeviceResponse as declared in filecoin-ffi/filcrypto.h:474 -type FilGpuDeviceResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - DevicesLen uint - DevicesPtr []string - ref58f92915 *C.fil_GpuDeviceResponse - allocs58f92915 interface{} -} - -// FilInitLogFdResponse as declared in filecoin-ffi/filcrypto.h:479 -type FilInitLogFdResponse struct { - StatusCode FCPResponseStatus - ErrorMsg string - ref3c1a0a08 *C.fil_InitLogFdResponse - allocs3c1a0a08 interface{} -} diff --git a/go.mod b/go.mod index 522629b0..6cccad7a 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/ipfs/go-ipfs-blockstore v1.1.2 github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.7.0 - github.com/xlab/c-for-go v0.0.0-20201112171043-ea6dce5809cb golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 ) @@ -47,27 +46,17 @@ require ( github.com/opentracing/opentracing-go v1.1.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/polydawn/refmt v0.0.0-20201211092308-30ac6d18308e // indirect - github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect github.com/smartystreets/goconvey v1.6.4 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect - github.com/tj/go-spin v1.1.0 // indirect github.com/warpfork/go-wish v0.0.0-20200122115046-b9ea61034e4a // indirect github.com/whyrusleeping/cbor-gen v0.0.0-20210713220151-be142a5ae1a8 // indirect - github.com/xlab/pkgconfig v0.0.0-20170226114623-cea12a0fd245 // indirect go.uber.org/atomic v1.6.0 // indirect go.uber.org/multierr v1.5.0 // indirect go.uber.org/zap v1.14.1 // indirect golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b // indirect - golang.org/x/mod v0.4.2 // indirect golang.org/x/sys v0.0.0-20211209171907-798191bca915 // indirect golang.org/x/tools v0.1.5 // indirect gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect lukechampine.com/blake3 v1.1.7 // indirect - modernc.org/cc v1.0.0 // indirect - modernc.org/golex v1.0.1 // indirect - modernc.org/mathutil v1.1.1 // indirect - modernc.org/strutil v1.1.0 // indirect - modernc.org/xc v1.0.0 // indirect ) diff --git a/go.sum b/go.sum index 735fc989..928eb49f 100644 --- a/go.sum +++ b/go.sum @@ -303,8 +303,6 @@ github.com/polydawn/refmt v0.0.0-20190807091052-3d65705ee9f1/go.mod h1:uIp+gprXx github.com/polydawn/refmt v0.0.0-20190809202753-05966cbd336a/go.mod h1:uIp+gprXxxrWSjjklXD+mN4wed/tMfjMMmN/9+JsA9o= github.com/polydawn/refmt v0.0.0-20201211092308-30ac6d18308e h1:ZOcivgkkFRnjfoTcGsDq3UQYiBmekwLA+qg0OjyB/ls= github.com/polydawn/refmt v0.0.0-20201211092308-30ac6d18308e/go.mod h1:uIp+gprXxxrWSjjklXD+mN4wed/tMfjMMmN/9+JsA9o= -github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= -github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= @@ -328,8 +326,6 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ= -github.com/tj/go-spin v1.1.0 h1:lhdWZsvImxvZ3q1C5OIB7d72DuOwP4O2NdBg9PyzNds= -github.com/tj/go-spin v1.1.0/go.mod h1:Mg1mzmePZm4dva8Qz60H2lHwmJ2loum4VIrLgVnKwh4= github.com/warpfork/go-wish v0.0.0-20180510122957-5ad1f5abf436/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw= github.com/warpfork/go-wish v0.0.0-20190328234359-8b3e70f8e830/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw= github.com/warpfork/go-wish v0.0.0-20200122115046-b9ea61034e4a h1:G++j5e0OC488te356JvdhaM8YS6nMsjLAYF7JxCv07w= @@ -353,12 +349,7 @@ github.com/whyrusleeping/go-notifier v0.0.0-20170827234753-097c5d47330f/go.mod h github.com/whyrusleeping/mafmt v1.2.8/go.mod h1:faQJFPbLSxzD9xpA02ttW/tS9vZykNvXwGvqIpk20FA= github.com/whyrusleeping/mdns v0.0.0-20180901202407-ef14215e6b30/go.mod h1:j4l84WPFclQPj320J9gp0XwNKBb3U0zt5CBqjPp22G4= github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7/go.mod h1:X2c0RVCI1eSUFI8eLcY3c0423ykwiUdxLJtkDvruhjI= -github.com/xlab/c-for-go v0.0.0-20201112171043-ea6dce5809cb h1:/7/dQyiKnxAOj9L69FhST7uMe17U015XPzX7cy+5ykM= -github.com/xlab/c-for-go v0.0.0-20201112171043-ea6dce5809cb/go.mod h1:pbNsDSxn1ICiNn9Ct4ZGNrwzfkkwYbx/lw8VuyutFIg= -github.com/xlab/pkgconfig v0.0.0-20170226114623-cea12a0fd245 h1:Sw125DKxZhPUI4JLlWugkzsrlB50jR9v2khiD9FxuSo= -github.com/xlab/pkgconfig v0.0.0-20170226114623-cea12a0fd245/go.mod h1:C+diUUz7pxhNY6KAoLgrTYARGWnt82zWTylZlxT92vk= github.com/xorcare/golden v0.6.0/go.mod h1:7T39/ZMvaSEZlBPoYfVFmsBLmUl3uz9IuzWj/U6FtvQ= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= @@ -378,16 +369,13 @@ golang.org/x/crypto v0.0.0-20190513172903-22d7a77e9e5f/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b h1:QAqMVf3pSa6eeTsuklijukjXBlj7Es2QQplab+/RbQ4= golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/exp v0.0.0-20181106170214-d68db9428509/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -398,13 +386,11 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190611141213-3f473d35a33a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -417,7 +403,6 @@ golang.org/x/sys v0.0.0-20190524122548-abf6ff778158/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190610200419-93c9922d18ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -441,7 +426,6 @@ golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200711155855-7342f9734a7d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.1.5 h1:ouewzE6p+/VEB31YYnTbEJdi8pFqKp4P4n85vwo3DHA= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -461,9 +445,6 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= @@ -472,17 +453,3 @@ honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt lukechampine.com/blake3 v1.1.6/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA= lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0= lukechampine.com/blake3 v1.1.7/go.mod h1:tkKEOtDkNtklkXtLNEOGNq5tcV90tJiA1vAA12R78LA= -modernc.org/cc v1.0.0 h1:nPibNuDEx6tvYrUAtvDTTw98rx5juGsa5zuDnKwEEQQ= -modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw= -modernc.org/fileutil v1.0.0/go.mod h1:JHsWpkrk/CnVV1H/eGlFf85BEpfkrp56ro8nojIq9Q8= -modernc.org/golex v1.0.0/go.mod h1:b/QX9oBD/LhixY6NDh+IdGv17hgB+51fET1i2kPSmvk= -modernc.org/golex v1.0.1 h1:EYKY1a3wStt0RzHaH8mdSRNg78Ub0OHxYfCRWw35YtM= -modernc.org/golex v1.0.1/go.mod h1:QCA53QtsT1NdGkaZZkF5ezFwk4IXh4BGNafAARTC254= -modernc.org/lex v1.0.0/go.mod h1:G6rxMTy3cH2iA0iXL/HRRv4Znu8MK4higxph/lE7ypk= -modernc.org/lexer v1.0.0/go.mod h1:F/Dld0YKYdZCLQ7bD0USbWL4YKCyTDRDHiDTOs0q0vk= -modernc.org/mathutil v1.1.1 h1:FeylZSVX8S+58VsyJlkEj2bcpdytmp9MmDKZkKx8OIE= -modernc.org/mathutil v1.1.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= -modernc.org/strutil v1.1.0 h1:+1/yCzZxY2pZwwrsbH+4T7BQMoLQ9QiBshRC9eicYsc= -modernc.org/strutil v1.1.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs= -modernc.org/xc v1.0.0 h1:7ccXrupWZIS3twbUGrtKmHS2DXY6xegFua+6O3xgAFU= -modernc.org/xc v1.0.0/go.mod h1:mRNCo0bvLjGhHO9WsyuKVU4q0ceiDDDoEeWDJHrNx8I= diff --git a/headerstubs/stdbool.h b/headerstubs/stdbool.h index e69de29b..6e4d65ca 100644 --- a/headerstubs/stdbool.h +++ b/headerstubs/stdbool.h @@ -0,0 +1,9 @@ +#ifndef _STDBOOL_H +#define _STDBOOL_H + + +#define bool _Bool +#define true 1 +#define false 0 + +#endif diff --git a/headerstubs/stddef.h b/headerstubs/stddef.h new file mode 100644 index 00000000..16ab21ec --- /dev/null +++ b/headerstubs/stddef.h @@ -0,0 +1 @@ +typedef unsigned long int size_t; diff --git a/headerstubs/stdint.h b/headerstubs/stdint.h index c48bf83c..65f45747 100644 --- a/headerstubs/stdint.h +++ b/headerstubs/stdint.h @@ -1,4 +1,7 @@ typedef unsigned char uint8_t; +typedef long long int32_t; +typedef unsigned long long uint32_t; +typedef long long int64_t; typedef unsigned long long uint64_t; -typedef unsigned long int size_t; -#define bool _Bool +typedef unsigned long long uintptr_t; /* only valid on 64bit systems */ + diff --git a/install-filcrypto b/install-filcrypto index 87614d34..41adf5fd 100755 --- a/install-filcrypto +++ b/install-filcrypto @@ -41,6 +41,7 @@ main() { # copy build assets into root of filecoin-ffi # + find -L "${__tmp_dir}" -type f -name filcrypto.h -exec cp -- "{}" . \; find -L "${__tmp_dir}" -type f -name libfilcrypto.a -exec cp -- "{}" . \; find -L "${__tmp_dir}" -type f -name filcrypto.pc -exec cp -- "{}" . \; @@ -62,6 +63,7 @@ main() { else find -L "${rust_sources_dir}/target/release" -type f -name libfilcrypto.a -exec cp -- "{}" . \; fi + find -L "${rust_sources_dir}" -type f -name filcrypto.h -exec cp -- "{}" . \; find -L "${rust_sources_dir}" -type f -name filcrypto.pc -exec cp -- "{}" . \; diff --git a/proofs.go b/proofs.go index 393e3552..e0e25671 100644 --- a/proofs.go +++ b/proofs.go @@ -11,7 +11,6 @@ import "C" import ( "os" "runtime" - "unsafe" "github.com/ipfs/go-cid" "github.com/pkg/errors" @@ -22,7 +21,7 @@ import ( "github.com/filecoin-project/go-state-types/abi" proof5 "github.com/filecoin-project/specs-actors/v5/actors/runtime/proof" - "github.com/filecoin-project/filecoin-ffi/generated" + "github.com/filecoin-project/filecoin-ffi/cgo" ) // VerifySeal returns true if the sealing operation from which its inputs were @@ -48,16 +47,10 @@ func VerifySeal(info proof5.SealVerifyInfo) (bool, error) { return false, err } - resp := generated.FilVerifySeal(sp, commR, commD, proverID, to32ByteArray(info.Randomness), to32ByteArray(info.InteractiveRandomness), uint64(info.SectorID.Number), info.Proof, uint(len(info.Proof))) - resp.Deref() + randomness := cgo.AsByteArray32(info.Randomness) + interactiveRandomness := cgo.AsByteArray32(info.InteractiveRandomness) - defer generated.FilDestroyVerifySealResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return false, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return resp.IsValid, nil + return cgo.VerifySeal(sp, &commR, &commD, &proverID, &randomness, &interactiveRandomness, uint64(info.SectorID.Number), cgo.AsSliceRefUint8(info.Proof)) } func VerifyAggregateSeals(aggregate proof5.AggregateSealVerifyProofAndInfos) (bool, error) { @@ -65,8 +58,9 @@ func VerifyAggregateSeals(aggregate proof5.AggregateSealVerifyProofAndInfos) (bo return false, xerrors.New("no seal verify infos") } - spt := aggregate.SealProof // todo assuming this needs to be the same for all sectors, potentially makes sense to put in AggregateSealVerifyProofAndInfos - inputs := make([]generated.FilAggregationInputs, len(aggregate.Infos)) + // TODO: assuming this needs to be the same for all sectors, potentially makes sense to put in AggregateSealVerifyProofAndInfos + spt := aggregate.SealProof + inputs := make([]cgo.AggregationInputs, len(aggregate.Infos)) for i, info := range aggregate.Infos { commR, err := to32ByteCommR(info.SealedCID) @@ -79,13 +73,13 @@ func VerifyAggregateSeals(aggregate proof5.AggregateSealVerifyProofAndInfos) (bo return false, err } - inputs[i] = generated.FilAggregationInputs{ - CommR: commR, - CommD: commD, - SectorId: uint64(info.Number), - Ticket: to32ByteArray(info.Randomness), - Seed: to32ByteArray(info.InteractiveRandomness), - } + inputs[i] = cgo.NewAggregationInputs( + commR, + commD, + uint64(info.Number), + cgo.AsByteArray32(info.Randomness), + cgo.AsByteArray32(info.InteractiveRandomness), + ) } sp, err := toFilRegisteredSealProof(spt) @@ -103,90 +97,62 @@ func VerifyAggregateSeals(aggregate proof5.AggregateSealVerifyProofAndInfos) (bo return false, err } - resp := generated.FilVerifyAggregateSealProof(sp, rap, proverID, aggregate.Proof, uint(len(aggregate.Proof)), inputs, uint(len(inputs))) - resp.Deref() - - defer generated.FilDestroyVerifyAggregateSealResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return false, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return resp.IsValid, nil + return cgo.VerifyAggregateSealProof(sp, rap, &proverID, cgo.AsSliceRefUint8(aggregate.Proof), cgo.AsSliceRefAggregationInputs(inputs)) } // VerifyWinningPoSt returns true if the Winning PoSt-generation operation from which its // inputs were derived was valid, and false if not. func VerifyWinningPoSt(info proof5.WinningPoStVerifyInfo) (bool, error) { - filPublicReplicaInfos, filPublicReplicaInfosLen, err := toFilPublicReplicaInfos(info.ChallengedSectors, "winning") + filPublicReplicaInfos, err := toFilPublicReplicaInfos(info.ChallengedSectors, "winning") if err != nil { return false, errors.Wrap(err, "failed to create public replica info array for FFI") } - filPoStProofs, filPoStProofsLen, free, err := toFilPoStProofs(info.Proofs) + filPoStProofs, err := toFilPoStProofs(info.Proofs) if err != nil { return false, errors.Wrap(err, "failed to create PoSt proofs array for FFI") } - defer free() proverID, err := toProverID(info.Prover) if err != nil { return false, err } + randomness := cgo.AsByteArray32(info.Randomness) - resp := generated.FilVerifyWinningPost( - to32ByteArray(info.Randomness), - filPublicReplicaInfos, - filPublicReplicaInfosLen, - filPoStProofs, - filPoStProofsLen, - proverID, + return cgo.VerifyWinningPoSt( + &randomness, + cgo.AsSliceRefPublicReplicaInfo(filPublicReplicaInfos), + cgo.AsSliceRefPoStProof(filPoStProofs), + &proverID, ) - resp.Deref() - - defer generated.FilDestroyVerifyWinningPostResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return false, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return resp.IsValid, nil } // VerifyWindowPoSt returns true if the Winning PoSt-generation operation from which its // inputs were derived was valid, and false if not. func VerifyWindowPoSt(info proof5.WindowPoStVerifyInfo) (bool, error) { - filPublicReplicaInfos, filPublicReplicaInfosLen, err := toFilPublicReplicaInfos(info.ChallengedSectors, "window") + filPublicReplicaInfos, err := toFilPublicReplicaInfos(info.ChallengedSectors, "window") if err != nil { return false, errors.Wrap(err, "failed to create public replica info array for FFI") } - filPoStProofs, filPoStProofsLen, free, err := toFilPoStProofs(info.Proofs) + filPoStProofs, err := toFilPoStProofs(info.Proofs) if err != nil { return false, errors.Wrap(err, "failed to create PoSt proofs array for FFI") } - defer free() proverID, err := toProverID(info.Prover) if err != nil { return false, err } - resp := generated.FilVerifyWindowPost( - to32ByteArray(info.Randomness), - filPublicReplicaInfos, filPublicReplicaInfosLen, - filPoStProofs, filPoStProofsLen, - proverID, - ) - resp.Deref() - - defer generated.FilDestroyVerifyWindowPostResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return false, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } + randomness := cgo.AsByteArray32(info.Randomness) - return resp.IsValid, nil + return cgo.VerifyWindowPoSt( + &randomness, + cgo.AsSliceRefPublicReplicaInfo(filPublicReplicaInfos), + cgo.AsSliceRefPoStProof(filPoStProofs), + &proverID, + ) } // GeneratePieceCommitment produces a piece commitment for the provided data @@ -213,25 +179,20 @@ func GenerateUnsealedCID(proofType abi.RegisteredSealProof, pieces []abi.PieceIn return cid.Undef, err } - filPublicPieceInfos, filPublicPieceInfosLen, err := toFilPublicPieceInfos(pieces) + filPublicPieceInfos, err := toFilPublicPieceInfos(pieces) if err != nil { return cid.Undef, err } - resp := generated.FilGenerateDataCommitment(sp, filPublicPieceInfos, filPublicPieceInfosLen) - resp.Deref() - - defer generated.FilDestroyGenerateDataCommitmentResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + resp, err := cgo.GenerateDataCommitment(sp, cgo.AsSliceRefPublicPieceInfo(filPublicPieceInfos)) + if err != nil { + return cid.Undef, err } - return commcid.DataCommitmentV1ToCID(resp.CommD[:]) + return commcid.DataCommitmentV1ToCID(resp) } -// GeneratePieceCIDFromFile produces a piece CID for the provided data stored in -//a given file. +// GeneratePieceCIDFromFile produces a piece CID for the provided data stored in a given file. func GeneratePieceCIDFromFile(proofType abi.RegisteredSealProof, pieceFile *os.File, pieceSize abi.UnpaddedPieceSize) (cid.Cid, error) { sp, err := toFilRegisteredSealProof(proofType) if err != nil { @@ -241,16 +202,12 @@ func GeneratePieceCIDFromFile(proofType abi.RegisteredSealProof, pieceFile *os.F pieceFd := pieceFile.Fd() defer runtime.KeepAlive(pieceFile) - resp := generated.FilGeneratePieceCommitment(sp, int32(pieceFd), uint64(pieceSize)) - resp.Deref() - - defer generated.FilDestroyGeneratePieceCommitmentResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + resp, err := cgo.GeneratePieceCommitment(sp, int32(pieceFd), uint64(pieceSize)) + if err != nil { + return cid.Undef, err } - return commcid.PieceCommitmentV1ToCID(resp.CommP[:]) + return commcid.PieceCommitmentV1ToCID(resp) } // WriteWithAlignment @@ -272,23 +229,19 @@ func WriteWithAlignment( stagedSectorFd := stagedSectorFile.Fd() defer runtime.KeepAlive(stagedSectorFile) - filExistingPieceSizes, filExistingPieceSizesLen := toFilExistingPieceSizes(existingPieceSizes) - - resp := generated.FilWriteWithAlignment(sp, int32(pieceFd), uint64(pieceBytes), int32(stagedSectorFd), filExistingPieceSizes, filExistingPieceSizesLen) - resp.Deref() + filExistingPieceSizes := toFilExistingPieceSizes(existingPieceSizes) - defer generated.FilDestroyWriteWithAlignmentResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return 0, 0, cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + leftAlignmentUnpadded, totalWriteUnpadded, commPRaw, err := cgo.WriteWithAlignment(sp, int32(pieceFd), uint64(pieceBytes), int32(stagedSectorFd), cgo.AsSliceRefUint64(filExistingPieceSizes)) + if err != nil { + return 0, 0, cid.Undef, err } - commP, errCommpSize := commcid.PieceCommitmentV1ToCID(resp.CommP[:]) + commP, errCommpSize := commcid.PieceCommitmentV1ToCID(commPRaw) if errCommpSize != nil { return 0, 0, cid.Undef, errCommpSize } - return abi.UnpaddedPieceSize(resp.LeftAlignmentUnpadded), abi.UnpaddedPieceSize(resp.TotalWriteUnpadded), commP, nil + return abi.UnpaddedPieceSize(leftAlignmentUnpadded), abi.UnpaddedPieceSize(totalWriteUnpadded), commP, nil } // WriteWithoutAlignment @@ -309,21 +262,17 @@ func WriteWithoutAlignment( stagedSectorFd := stagedSectorFile.Fd() defer runtime.KeepAlive(stagedSectorFile) - resp := generated.FilWriteWithoutAlignment(sp, int32(pieceFd), uint64(pieceBytes), int32(stagedSectorFd)) - resp.Deref() - - defer generated.FilDestroyWriteWithoutAlignmentResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return 0, cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + totalWriteUnpadded, commPRaw, err := cgo.WriteWithoutAlignment(sp, int32(pieceFd), uint64(pieceBytes), int32(stagedSectorFd)) + if err != nil { + return 0, cid.Undef, err } - commP, errCommpSize := commcid.PieceCommitmentV1ToCID(resp.CommP[:]) + commP, errCommpSize := commcid.PieceCommitmentV1ToCID(commPRaw) if errCommpSize != nil { return 0, cid.Undef, errCommpSize } - return abi.UnpaddedPieceSize(resp.TotalWriteUnpadded), commP, nil + return abi.UnpaddedPieceSize(totalWriteUnpadded), commP, nil } // SealPreCommitPhase1 @@ -347,21 +296,22 @@ func SealPreCommitPhase1( return nil, err } - filPublicPieceInfos, filPublicPieceInfosLen, err := toFilPublicPieceInfos(pieces) + filPublicPieceInfos, err := toFilPublicPieceInfos(pieces) if err != nil { return nil, err } - resp := generated.FilSealPreCommitPhase1(sp, cacheDirPath, stagedSectorPath, sealedSectorPath, uint64(sectorNum), proverID, to32ByteArray(ticket), filPublicPieceInfos, filPublicPieceInfosLen) - resp.Deref() - - defer generated.FilDestroySealPreCommitPhase1Response(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return copyBytes(resp.SealPreCommitPhase1OutputPtr, resp.SealPreCommitPhase1OutputLen), nil + ticketBytes := cgo.AsByteArray32(ticket) + return cgo.SealPreCommitPhase1( + sp, + cgo.AsSliceRefUint8([]byte(cacheDirPath)), + cgo.AsSliceRefUint8([]byte(stagedSectorPath)), + cgo.AsSliceRefUint8([]byte(sealedSectorPath)), + uint64(sectorNum), + &proverID, + &ticketBytes, + cgo.AsSliceRefPublicPieceInfo(filPublicPieceInfos), + ) } // SealPreCommitPhase2 @@ -370,20 +320,19 @@ func SealPreCommitPhase2( cacheDirPath string, sealedSectorPath string, ) (sealedCID cid.Cid, unsealedCID cid.Cid, err error) { - resp := generated.FilSealPreCommitPhase2(phase1Output, uint(len(phase1Output)), cacheDirPath, sealedSectorPath) - resp.Deref() - - defer generated.FilDestroySealPreCommitPhase2Response(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + commRRaw, commDRaw, err := cgo.SealPreCommitPhase2( + cgo.AsSliceRefUint8(phase1Output), + cgo.AsSliceRefUint8([]byte(cacheDirPath)), + cgo.AsSliceRefUint8([]byte(sealedSectorPath)), + ) + if err != nil { + return cid.Undef, cid.Undef, err } - - commR, errCommrSize := commcid.ReplicaCommitmentV1ToCID(resp.CommR[:]) + commR, errCommrSize := commcid.ReplicaCommitmentV1ToCID(commRRaw) if errCommrSize != nil { return cid.Undef, cid.Undef, errCommrSize } - commD, errCommdSize := commcid.DataCommitmentV1ToCID(resp.CommD[:]) + commD, errCommdSize := commcid.DataCommitmentV1ToCID(commDRaw) if errCommdSize != nil { return cid.Undef, cid.Undef, errCommdSize } @@ -424,21 +373,25 @@ func SealCommitPhase1( return nil, err } - filPublicPieceInfos, filPublicPieceInfosLen, err := toFilPublicPieceInfos(pieces) + filPublicPieceInfos, err := toFilPublicPieceInfos(pieces) if err != nil { return nil, err } - - resp := generated.FilSealCommitPhase1(sp, commR, commD, cacheDirPath, sealedSectorPath, uint64(sectorNum), proverID, to32ByteArray(ticket), to32ByteArray(seed), filPublicPieceInfos, filPublicPieceInfosLen) - resp.Deref() - - defer generated.FilDestroySealCommitPhase1Response(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return copyBytes(resp.SealCommitPhase1OutputPtr, resp.SealCommitPhase1OutputLen), nil + ticketBytes := cgo.AsByteArray32(ticket) + seedBytes := cgo.AsByteArray32(seed) + + return cgo.SealCommitPhase1( + sp, + &commR, + &commD, + cgo.AsSliceRefUint8([]byte(cacheDirPath)), + cgo.AsSliceRefUint8([]byte(sealedSectorPath)), + uint64(sectorNum), + &proverID, + &ticketBytes, + &seedBytes, + cgo.AsSliceRefPublicPieceInfo(filPublicPieceInfos), + ) } // SealCommitPhase2 @@ -452,16 +405,7 @@ func SealCommitPhase2( return nil, err } - resp := generated.FilSealCommitPhase2(phase1Output, uint(len(phase1Output)), uint64(sectorNum), proverID) - resp.Deref() - - defer generated.FilDestroySealCommitPhase2Response(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return copyBytes(resp.ProofPtr, resp.ProofLen), nil + return cgo.SealCommitPhase2(cgo.AsSliceRefUint8(phase1Output), uint64(sectorNum), &proverID) } // TODO AggregateSealProofs it only needs InteractiveRandomness out of the aggregateInfo.Infos @@ -471,39 +415,31 @@ func AggregateSealProofs(aggregateInfo proof5.AggregateSealVerifyProofAndInfos, return nil, err } - commRs := make([]generated.Fil32ByteArray, len(aggregateInfo.Infos)) - seeds := make([]generated.Fil32ByteArray, len(aggregateInfo.Infos)) + commRs := make([]cgo.ByteArray32, len(aggregateInfo.Infos)) + seeds := make([]cgo.ByteArray32, len(aggregateInfo.Infos)) for i, info := range aggregateInfo.Infos { - seeds[i] = to32ByteArray(info.InteractiveRandomness) + seeds[i] = cgo.AsByteArray32(info.InteractiveRandomness) commRs[i], err = to32ByteCommR(info.SealedCID) if err != nil { return nil, err } } - pfs := make([]generated.FilSealCommitPhase2Response, len(proofs)) - for i := range proofs { - pfs[i] = generated.FilSealCommitPhase2Response{ - ProofPtr: proofs[i], - ProofLen: uint(len(proofs[i])), - } - } + pfs, cleaner := toVanillaProofs(proofs) + defer cleaner() rap, err := toFilRegisteredAggregationProof(aggregateInfo.AggregateProof) if err != nil { return nil, err } - resp := generated.FilAggregateSealProofs(sp, rap, commRs, uint(len(commRs)), seeds, uint(len(seeds)), pfs, uint(len(pfs))) - resp.Deref() - - defer generated.FilDestroyAggregateProof(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return copyBytes(resp.ProofPtr, resp.ProofLen), nil + return cgo.AggregateSealProofs( + sp, + rap, + cgo.AsSliceRefByteArray32(commRs), + cgo.AsSliceRefByteArray32(seeds), + cgo.AsSliceRefSliceBoxedUint8(pfs), + ) } // Unseal @@ -561,16 +497,19 @@ func UnsealRange( unsealOutputFd := unsealOutput.Fd() defer runtime.KeepAlive(unsealOutput) - resp := generated.FilUnsealRange(sp, cacheDirPath, int32(sealedSectorFd), int32(unsealOutputFd), uint64(sectorNum), proverID, to32ByteArray(ticket), commD, unpaddedByteIndex, unpaddedBytesAmount) - resp.Deref() - - defer generated.FilDestroyUnsealRangeResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return nil + ticketBytes := cgo.AsByteArray32(ticket) + return cgo.UnsealRange( + sp, + cgo.AsSliceRefUint8([]byte(cacheDirPath)), + int32(sealedSectorFd), + int32(unsealOutputFd), + uint64(sectorNum), + &proverID, + &ticketBytes, + &commD, + unpaddedByteIndex, + unpaddedBytesAmount, + ) } // GenerateWinningPoStSectorChallenge @@ -590,27 +529,9 @@ func GenerateWinningPoStSectorChallenge( return nil, err } - resp := generated.FilGenerateWinningPostSectorChallenge( - pp, to32ByteArray(randomness), - eligibleSectorsLen, proverID, - ) - resp.Deref() - resp.IdsPtr = make([]uint64, resp.IdsLen) - resp.Deref() - - defer generated.FilDestroyGenerateWinningPostSectorChallenge(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - // copy from C memory space to Go - out := make([]uint64, resp.IdsLen) - for idx := range out { - out[idx] = resp.IdsPtr[idx] - } + randomnessBytes := cgo.AsByteArray32(randomness) - return out, nil + return cgo.GenerateWinningPoStSectorChallenge(pp, &randomnessBytes, eligibleSectorsLen, &proverID) } // GenerateWinningPoSt @@ -619,33 +540,23 @@ func GenerateWinningPoSt( privateSectorInfo SortedPrivateSectorInfo, randomness abi.PoStRandomness, ) ([]proof5.PoStProof, error) { - filReplicas, filReplicasLen, free, err := toFilPrivateReplicaInfos(privateSectorInfo.Values(), "winning") + filReplicas, cleanup, err := toFilPrivateReplicaInfos(privateSectorInfo.Values(), "winning") if err != nil { return nil, errors.Wrap(err, "failed to create private replica info array for FFI") } - defer free() + defer cleanup() proverID, err := toProverID(minerID) if err != nil { return nil, err } - - resp := generated.FilGenerateWinningPost( - to32ByteArray(randomness), - filReplicas, filReplicasLen, - proverID, - ) - resp.Deref() - resp.ProofsPtr = make([]generated.FilPoStProof, resp.ProofsLen) - resp.Deref() - - defer generated.FilDestroyGenerateWinningPostResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + randomnessBytes := cgo.AsByteArray32(randomness) + rawProofs, err := cgo.GenerateWinningPoSt(&randomnessBytes, cgo.AsSliceRefPrivateReplicaInfo(filReplicas), &proverID) + if err != nil { + return nil, err } - proofs, err := fromFilPoStProofs(resp.ProofsPtr) + proofs, err := fromFilPoStProofs(rawProofs) if err != nil { return nil, err } @@ -659,58 +570,36 @@ func GenerateWindowPoSt( privateSectorInfo SortedPrivateSectorInfo, randomness abi.PoStRandomness, ) ([]proof5.PoStProof, []abi.SectorNumber, error) { - filReplicas, filReplicasLen, free, err := toFilPrivateReplicaInfos(privateSectorInfo.Values(), "window") + filReplicas, cleanup, err := toFilPrivateReplicaInfos(privateSectorInfo.Values(), "window") if err != nil { return nil, nil, errors.Wrap(err, "failed to create private replica info array for FFI") } - defer free() + defer cleanup() proverID, err := toProverID(minerID) if err != nil { return nil, nil, err } - resp := generated.FilGenerateWindowPost(to32ByteArray(randomness), filReplicas, filReplicasLen, proverID) - resp.Deref() - resp.ProofsPtr = make([]generated.FilPoStProof, resp.ProofsLen) - resp.Deref() - resp.FaultySectorsPtr = resp.FaultySectorsPtr[:resp.FaultySectorsLen] - - defer generated.FilDestroyGenerateWindowPostResponse(resp) - - faultySectors, err := fromFilPoStFaultySectors(resp.FaultySectorsPtr, resp.FaultySectorsLen) + randomnessBytes := cgo.AsByteArray32(randomness) + proofsRaw, faultsRaw, err := cgo.GenerateWindowPoSt(&randomnessBytes, cgo.AsSliceRefPrivateReplicaInfo(filReplicas), &proverID) if err != nil { - return nil, nil, xerrors.Errorf("failed to parse faulty sectors list: %w", err) + faultySectors := fromFilPoStFaultySectors(faultsRaw) + return nil, faultySectors, err } - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, faultySectors, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - proofs, err := fromFilPoStProofs(resp.ProofsPtr) + proofs, err := fromFilPoStProofs(proofsRaw) if err != nil { return nil, nil, err } - return proofs, faultySectors, nil + return proofs, nil, nil } // GetGPUDevices produces a slice of strings, each representing the name of a // detected GPU device. func GetGPUDevices() ([]string, error) { - resp := generated.FilGetGpuDevices() - resp.Deref() - resp.DevicesPtr = make([]string, resp.DevicesLen) - resp.Deref() - - defer generated.FilDestroyGpuDeviceResponse(resp) - - out := make([]string, len(resp.DevicesPtr)) - for idx := range out { - out[idx] = generated.RawString(resp.DevicesPtr[idx]).Copy() - } - - return out, nil + return cgo.GetGpuDevices() } // GetSealVersion @@ -720,16 +609,7 @@ func GetSealVersion(proofType abi.RegisteredSealProof) (string, error) { return "", err } - resp := generated.FilGetSealVersion(sp) - resp.Deref() - - defer generated.FilDestroyStringResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return "", errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return generated.RawString(resp.StringVal).Copy(), nil + return cgo.GetSealVersion(sp) } // GetPoStVersion @@ -739,16 +619,7 @@ func GetPoStVersion(proofType abi.RegisteredPoStProof) (string, error) { return "", err } - resp := generated.FilGetPostVersion(pp) - resp.Deref() - - defer generated.FilDestroyStringResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return "", errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return generated.RawString(resp.StringVal).Copy(), nil + return cgo.GetPoStVersion(pp) } func GetNumPartitionForFallbackPost(proofType abi.RegisteredPoStProof, numSectors uint) (uint, error) { @@ -756,29 +627,13 @@ func GetNumPartitionForFallbackPost(proofType abi.RegisteredPoStProof, numSector if err != nil { return 0, err } - resp := generated.FilGetNumPartitionForFallbackPost(pp, numSectors) - resp.Deref() - defer generated.FilDestroyGetNumPartitionForFallbackPostResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return 0, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - return resp.NumPartition, nil + return cgo.GetNumPartitionForFallbackPost(pp, numSectors) } // ClearCache func ClearCache(sectorSize uint64, cacheDirPath string) error { - resp := generated.FilClearCache(sectorSize, cacheDirPath) - resp.Deref() - - defer generated.FilDestroyClearCacheResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return nil + return cgo.ClearCache(sectorSize, cgo.AsSliceRefUint8([]byte(cacheDirPath))) } func FauxRep(proofType abi.RegisteredSealProof, cacheDirPath string, sealedSectorPath string) (cid.Cid, error) { @@ -787,16 +642,12 @@ func FauxRep(proofType abi.RegisteredSealProof, cacheDirPath string, sealedSecto return cid.Undef, err } - resp := generated.FilFauxrep(sp, cacheDirPath, sealedSectorPath) - resp.Deref() - - defer generated.FilDestroyFauxrepResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + rawCid, err := cgo.Fauxrep(sp, cgo.AsSliceRefUint8([]byte(cacheDirPath)), cgo.AsSliceRefUint8([]byte(sealedSectorPath))) + if err != nil { + return cid.Undef, err } - return commcid.ReplicaCommitmentV1ToCID(resp.Commitment[:]) + return commcid.ReplicaCommitmentV1ToCID(rawCid) } func FauxRep2(proofType abi.RegisteredSealProof, cacheDirPath string, existingPAuxPath string) (cid.Cid, error) { @@ -805,170 +656,148 @@ func FauxRep2(proofType abi.RegisteredSealProof, cacheDirPath string, existingPA return cid.Undef, err } - resp := generated.FilFauxrep2(sp, cacheDirPath, existingPAuxPath) - resp.Deref() - - defer generated.FilDestroyFauxrepResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + rawCid, err := cgo.Fauxrep2(sp, cgo.AsSliceRefUint8([]byte(cacheDirPath)), cgo.AsSliceRefUint8([]byte(existingPAuxPath))) + if err != nil { + return cid.Undef, err } - return commcid.ReplicaCommitmentV1ToCID(resp.Commitment[:]) + return commcid.ReplicaCommitmentV1ToCID(rawCid) } -func toFilExistingPieceSizes(src []abi.UnpaddedPieceSize) ([]uint64, uint) { +func toFilExistingPieceSizes(src []abi.UnpaddedPieceSize) []uint64 { out := make([]uint64, len(src)) for idx := range out { out[idx] = uint64(src[idx]) } - return out, uint(len(out)) + return out } -func toFilPublicPieceInfos(src []abi.PieceInfo) ([]generated.FilPublicPieceInfo, uint, error) { - out := make([]generated.FilPublicPieceInfo, len(src)) +func toFilPublicPieceInfos(src []abi.PieceInfo) ([]cgo.PublicPieceInfo, error) { + out := make([]cgo.PublicPieceInfo, len(src)) for idx := range out { commP, err := to32ByteCommP(src[idx].PieceCID) if err != nil { - return nil, 0, err + return nil, err } - out[idx] = generated.FilPublicPieceInfo{ - NumBytes: uint64(src[idx].Size.Unpadded()), - CommP: commP.Inner, - } + out[idx] = cgo.NewPublicPieceInfo(uint64(src[idx].Size.Unpadded()), commP) } - return out, uint(len(out)), nil + return out, nil } -func toFilPublicReplicaInfos(src []proof5.SectorInfo, typ string) ([]generated.FilPublicReplicaInfo, uint, error) { - out := make([]generated.FilPublicReplicaInfo, len(src)) +func toFilPublicReplicaInfos(src []proof5.SectorInfo, typ string) ([]cgo.PublicReplicaInfo, error) { + out := make([]cgo.PublicReplicaInfo, len(src)) for idx := range out { commR, err := to32ByteCommR(src[idx].SealedCID) if err != nil { - return nil, 0, err + return nil, err } - out[idx] = generated.FilPublicReplicaInfo{ - CommR: commR.Inner, - SectorId: uint64(src[idx].SectorNumber), - } + var pp cgo.RegisteredPoStProof switch typ { case "window": p, err := src[idx].SealProof.RegisteredWindowPoStProof() if err != nil { - return nil, 0, err + return nil, err } - out[idx].RegisteredProof, err = toFilRegisteredPoStProof(p) + pp, err = toFilRegisteredPoStProof(p) if err != nil { - return nil, 0, err + return nil, err } case "winning": p, err := src[idx].SealProof.RegisteredWinningPoStProof() if err != nil { - return nil, 0, err + return nil, err } - out[idx].RegisteredProof, err = toFilRegisteredPoStProof(p) + pp, err = toFilRegisteredPoStProof(p) if err != nil { - return nil, 0, err + return nil, err } } + + out[idx] = cgo.NewPublicReplicaInfo(pp, commR, uint64(src[idx].SectorNumber)) } - return out, uint(len(out)), nil + return out, nil } -func toFilPrivateReplicaInfo(src PrivateSectorInfo) (generated.FilPrivateReplicaInfo, func(), error) { +func toFilPrivateReplicaInfo(src PrivateSectorInfo) (cgo.PrivateReplicaInfo, error) { commR, err := to32ByteCommR(src.SealedCID) if err != nil { - return generated.FilPrivateReplicaInfo{}, func() {}, err + return cgo.PrivateReplicaInfo{}, err } pp, err := toFilRegisteredPoStProof(src.PoStProofType) if err != nil { - return generated.FilPrivateReplicaInfo{}, func() {}, err + return cgo.PrivateReplicaInfo{}, err } - out := generated.FilPrivateReplicaInfo{ - RegisteredProof: pp, - CacheDirPath: src.CacheDirPath, - CommR: commR.Inner, - ReplicaPath: src.SealedSectorPath, - SectorId: uint64(src.SectorNumber), - } - _, allocs := out.PassRef() - return out, allocs.Free, nil + return cgo.NewPrivateReplicaInfo( + pp, + src.CacheDirPath, + commR, + src.SealedSectorPath, + uint64(src.SectorNumber), + ), nil } -func toFilPrivateReplicaInfos(src []PrivateSectorInfo, typ string) ([]generated.FilPrivateReplicaInfo, uint, func(), error) { - allocs := make([]AllocationManager, len(src)) +func makeCleanerPRI(src []cgo.PrivateReplicaInfo, limit int) func() { + return func() { + for i := 0; i < limit; i++ { + src[i].Destroy() + } + } +} - out := make([]generated.FilPrivateReplicaInfo, len(src)) +func toFilPrivateReplicaInfos(src []PrivateSectorInfo, typ string) ([]cgo.PrivateReplicaInfo, func(), error) { + out := make([]cgo.PrivateReplicaInfo, len(src)) for idx := range out { commR, err := to32ByteCommR(src[idx].SealedCID) if err != nil { - return nil, 0, func() {}, err + makeCleanerPRI(out, idx)() + return nil, nil, err } pp, err := toFilRegisteredPoStProof(src[idx].PoStProofType) if err != nil { - return nil, 0, func() {}, err + makeCleanerPRI(out, idx)() + return nil, nil, err } - out[idx] = generated.FilPrivateReplicaInfo{ - RegisteredProof: pp, - CacheDirPath: src[idx].CacheDirPath, - CommR: commR.Inner, - ReplicaPath: src[idx].SealedSectorPath, - SectorId: uint64(src[idx].SectorNumber), - } - - _, allocs[idx] = out[idx].PassRef() + out[idx] = cgo.NewPrivateReplicaInfo( + pp, + src[idx].CacheDirPath, + commR, + src[idx].SealedSectorPath, + uint64(src[idx].SectorNumber), + ) } - return out, uint(len(out)), func() { - for idx := range allocs { - allocs[idx].Free() - } - }, nil + return out, makeCleanerPRI(out, len(src)), nil } -func fromFilPoStFaultySectors(ptr []uint64, l uint) ([]abi.SectorNumber, error) { - if l == 0 { - return nil, nil - } - - type sliceHeader struct { - Data unsafe.Pointer - Len int - Cap int - } - - (*sliceHeader)(unsafe.Pointer(&ptr)).Len = int(l) // don't worry about it - - snums := make([]abi.SectorNumber, 0, l) - for i := uint(0); i < l; i++ { - snums = append(snums, abi.SectorNumber(ptr[i])) +func fromFilPoStFaultySectors(ptr []uint64) []abi.SectorNumber { + snums := make([]abi.SectorNumber, len(ptr)) + for i := range ptr { + snums[i] = abi.SectorNumber(ptr[i]) } - return snums, nil + return snums } -func fromFilPoStProofs(src []generated.FilPoStProof) ([]proof5.PoStProof, error) { +func fromFilPoStProofs(src []cgo.PoStProofGo) ([]proof5.PoStProof, error) { out := make([]proof5.PoStProof, len(src)) for idx := range out { - src[idx].Deref() - pp, err := fromFilRegisteredPoStProof(src[idx].RegisteredProof) if err != nil { return nil, err @@ -976,231 +805,170 @@ func fromFilPoStProofs(src []generated.FilPoStProof) ([]proof5.PoStProof, error) out[idx] = proof5.PoStProof{ PoStProof: pp, - ProofBytes: copyBytes(src[idx].ProofPtr, src[idx].ProofLen), + ProofBytes: src[idx].Proof, } } return out, nil } -func toFilPoStProofs(src []proof5.PoStProof) ([]generated.FilPoStProof, uint, func(), error) { - allocs := make([]AllocationManager, len(src)) - - out := make([]generated.FilPoStProof, len(src)) +func toFilPoStProofs(src []proof5.PoStProof) ([]cgo.PoStProof, error) { + out := make([]cgo.PoStProof, len(src)) for idx := range out { pp, err := toFilRegisteredPoStProof(src[idx].PoStProof) if err != nil { - return nil, 0, func() {}, err - } - - out[idx] = generated.FilPoStProof{ - RegisteredProof: pp, - ProofLen: uint(len(src[idx].ProofBytes)), - ProofPtr: src[idx].ProofBytes, + return nil, err } - _, allocs[idx] = out[idx].PassRef() + out[idx] = cgo.NewPoStProof(pp, src[idx].ProofBytes) } - return out, uint(len(out)), func() { - for idx := range allocs { - allocs[idx].Free() - } - }, nil -} - -func to32ByteArray(in []byte) generated.Fil32ByteArray { - var out generated.Fil32ByteArray - copy(out.Inner[:], in) - return out + return out, nil } -func toProverID(minerID abi.ActorID) (generated.Fil32ByteArray, error) { +func toProverID(minerID abi.ActorID) (cgo.ByteArray32, error) { maddr, err := address.NewIDAddress(uint64(minerID)) if err != nil { - return generated.Fil32ByteArray{}, errors.Wrap(err, "failed to convert ActorID to prover id ([32]byte) for FFI") + return cgo.ByteArray32{}, errors.Wrap(err, "failed to convert ActorID to prover id ([32]byte) for FFI") } - return to32ByteArray(maddr.Payload()), nil + return cgo.AsByteArray32(maddr.Payload()), nil } -func fromFilRegisteredPoStProof(p generated.FilRegisteredPoStProof) (abi.RegisteredPoStProof, error) { +func fromFilRegisteredPoStProof(p cgo.RegisteredPoStProof) (abi.RegisteredPoStProof, error) { switch p { - case generated.FilRegisteredPoStProofStackedDrgWinning2KiBV1: + case cgo.RegisteredPoStProofStackedDrgWinning2KiBV1: return abi.RegisteredPoStProof_StackedDrgWinning2KiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWinning8MiBV1: + case cgo.RegisteredPoStProofStackedDrgWinning8MiBV1: return abi.RegisteredPoStProof_StackedDrgWinning8MiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWinning512MiBV1: + case cgo.RegisteredPoStProofStackedDrgWinning512MiBV1: return abi.RegisteredPoStProof_StackedDrgWinning512MiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWinning32GiBV1: + case cgo.RegisteredPoStProofStackedDrgWinning32GiBV1: return abi.RegisteredPoStProof_StackedDrgWinning32GiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWinning64GiBV1: + case cgo.RegisteredPoStProofStackedDrgWinning64GiBV1: return abi.RegisteredPoStProof_StackedDrgWinning64GiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWindow2KiBV1: + case cgo.RegisteredPoStProofStackedDrgWindow2KiBV1: return abi.RegisteredPoStProof_StackedDrgWindow2KiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWindow8MiBV1: + case cgo.RegisteredPoStProofStackedDrgWindow8MiBV1: return abi.RegisteredPoStProof_StackedDrgWindow8MiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWindow512MiBV1: + case cgo.RegisteredPoStProofStackedDrgWindow512MiBV1: return abi.RegisteredPoStProof_StackedDrgWindow512MiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWindow32GiBV1: + case cgo.RegisteredPoStProofStackedDrgWindow32GiBV1: return abi.RegisteredPoStProof_StackedDrgWindow32GiBV1, nil - case generated.FilRegisteredPoStProofStackedDrgWindow64GiBV1: + case cgo.RegisteredPoStProofStackedDrgWindow64GiBV1: return abi.RegisteredPoStProof_StackedDrgWindow64GiBV1, nil default: return 0, errors.Errorf("no mapping to abi.RegisteredPoStProof value available for: %v", p) } } -func toFilRegisteredPoStProof(p abi.RegisteredPoStProof) (generated.FilRegisteredPoStProof, error) { +func toFilRegisteredPoStProof(p abi.RegisteredPoStProof) (cgo.RegisteredPoStProof, error) { switch p { case abi.RegisteredPoStProof_StackedDrgWinning2KiBV1: - return generated.FilRegisteredPoStProofStackedDrgWinning2KiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWinning2KiBV1, nil case abi.RegisteredPoStProof_StackedDrgWinning8MiBV1: - return generated.FilRegisteredPoStProofStackedDrgWinning8MiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWinning8MiBV1, nil case abi.RegisteredPoStProof_StackedDrgWinning512MiBV1: - return generated.FilRegisteredPoStProofStackedDrgWinning512MiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWinning512MiBV1, nil case abi.RegisteredPoStProof_StackedDrgWinning32GiBV1: - return generated.FilRegisteredPoStProofStackedDrgWinning32GiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWinning32GiBV1, nil case abi.RegisteredPoStProof_StackedDrgWinning64GiBV1: - return generated.FilRegisteredPoStProofStackedDrgWinning64GiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWinning64GiBV1, nil case abi.RegisteredPoStProof_StackedDrgWindow2KiBV1: - return generated.FilRegisteredPoStProofStackedDrgWindow2KiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWindow2KiBV1, nil case abi.RegisteredPoStProof_StackedDrgWindow8MiBV1: - return generated.FilRegisteredPoStProofStackedDrgWindow8MiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWindow8MiBV1, nil case abi.RegisteredPoStProof_StackedDrgWindow512MiBV1: - return generated.FilRegisteredPoStProofStackedDrgWindow512MiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWindow512MiBV1, nil case abi.RegisteredPoStProof_StackedDrgWindow32GiBV1: - return generated.FilRegisteredPoStProofStackedDrgWindow32GiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWindow32GiBV1, nil case abi.RegisteredPoStProof_StackedDrgWindow64GiBV1: - return generated.FilRegisteredPoStProofStackedDrgWindow64GiBV1, nil + return cgo.RegisteredPoStProofStackedDrgWindow64GiBV1, nil default: return 0, errors.Errorf("no mapping to abi.RegisteredPoStProof value available for: %v", p) } } -func toFilRegisteredSealProof(p abi.RegisteredSealProof) (generated.FilRegisteredSealProof, error) { +func toFilRegisteredSealProof(p abi.RegisteredSealProof) (cgo.RegisteredSealProof, error) { switch p { case abi.RegisteredSealProof_StackedDrg2KiBV1: - return generated.FilRegisteredSealProofStackedDrg2KiBV1, nil + return cgo.RegisteredSealProofStackedDrg2KiBV1, nil case abi.RegisteredSealProof_StackedDrg8MiBV1: - return generated.FilRegisteredSealProofStackedDrg8MiBV1, nil + return cgo.RegisteredSealProofStackedDrg8MiBV1, nil case abi.RegisteredSealProof_StackedDrg512MiBV1: - return generated.FilRegisteredSealProofStackedDrg512MiBV1, nil + return cgo.RegisteredSealProofStackedDrg512MiBV1, nil case abi.RegisteredSealProof_StackedDrg32GiBV1: - return generated.FilRegisteredSealProofStackedDrg32GiBV1, nil + return cgo.RegisteredSealProofStackedDrg32GiBV1, nil case abi.RegisteredSealProof_StackedDrg64GiBV1: - return generated.FilRegisteredSealProofStackedDrg64GiBV1, nil + return cgo.RegisteredSealProofStackedDrg64GiBV1, nil case abi.RegisteredSealProof_StackedDrg2KiBV1_1: - return generated.FilRegisteredSealProofStackedDrg2KiBV11, nil + return cgo.RegisteredSealProofStackedDrg2KiBV11, nil case abi.RegisteredSealProof_StackedDrg8MiBV1_1: - return generated.FilRegisteredSealProofStackedDrg8MiBV11, nil + return cgo.RegisteredSealProofStackedDrg8MiBV11, nil case abi.RegisteredSealProof_StackedDrg512MiBV1_1: - return generated.FilRegisteredSealProofStackedDrg512MiBV11, nil + return cgo.RegisteredSealProofStackedDrg512MiBV11, nil case abi.RegisteredSealProof_StackedDrg32GiBV1_1: - return generated.FilRegisteredSealProofStackedDrg32GiBV11, nil + return cgo.RegisteredSealProofStackedDrg32GiBV11, nil case abi.RegisteredSealProof_StackedDrg64GiBV1_1: - return generated.FilRegisteredSealProofStackedDrg64GiBV11, nil + return cgo.RegisteredSealProofStackedDrg64GiBV11, nil default: return 0, errors.Errorf("no mapping to C.FFIRegisteredSealProof value available for: %v", p) } } -func toFilRegisteredAggregationProof(p abi.RegisteredAggregationProof) (generated.FilRegisteredAggregationProof, error) { +func toFilRegisteredAggregationProof(p abi.RegisteredAggregationProof) (cgo.RegisteredAggregationProof, error) { switch p { case abi.RegisteredAggregationProof_SnarkPackV1: - return generated.FilRegisteredAggregationProofSnarkPackV1, nil + return cgo.RegisteredAggregationProofSnarkPackV1, nil default: return 0, errors.Errorf("no mapping to abi.RegisteredAggregationProof value available for: %v", p) } } -func to32ByteCommD(unsealedCID cid.Cid) (generated.Fil32ByteArray, error) { +func to32ByteCommD(unsealedCID cid.Cid) (cgo.ByteArray32, error) { commD, err := commcid.CIDToDataCommitmentV1(unsealedCID) if err != nil { - return generated.Fil32ByteArray{}, errors.Wrap(err, "failed to transform sealed CID to CommD") + return cgo.ByteArray32{}, errors.Wrap(err, "failed to transform sealed CID to CommD") } - return to32ByteArray(commD), nil + return cgo.AsByteArray32(commD), nil } -func to32ByteCommR(sealedCID cid.Cid) (generated.Fil32ByteArray, error) { - commD, err := commcid.CIDToReplicaCommitmentV1(sealedCID) +func to32ByteCommR(sealedCID cid.Cid) (cgo.ByteArray32, error) { + commR, err := commcid.CIDToReplicaCommitmentV1(sealedCID) if err != nil { - return generated.Fil32ByteArray{}, errors.Wrap(err, "failed to transform sealed CID to CommR") + return cgo.ByteArray32{}, errors.Wrap(err, "failed to transform sealed CID to CommR") } - return to32ByteArray(commD), nil + return cgo.AsByteArray32(commR), nil } -func to32ByteCommP(pieceCID cid.Cid) (generated.Fil32ByteArray, error) { +func to32ByteCommP(pieceCID cid.Cid) (cgo.ByteArray32, error) { commP, err := commcid.CIDToPieceCommitmentV1(pieceCID) if err != nil { - return generated.Fil32ByteArray{}, errors.Wrap(err, "failed to transform sealed CID to CommP") + return cgo.ByteArray32{}, errors.Wrap(err, "failed to transform sealed CID to CommP") } - return to32ByteArray(commP), nil + return cgo.AsByteArray32(commP), nil } -func copyBytes(v []byte, vLen uint) []byte { - buf := make([]byte, vLen) - if n := copy(buf, v[:vLen]); n != int(vLen) { - panic("partial read") - } - - return buf -} - -type stringHeader struct { - Data unsafe.Pointer - Len int -} - -func toVanillaProofs(src [][]byte) ([]generated.FilVanillaProof, func()) { - allocs := make([]AllocationManager, len(src)) - - out := make([]generated.FilVanillaProof, len(src)) - for idx := range out { - out[idx] = generated.FilVanillaProof{ - ProofLen: uint(len(src[idx])), - ProofPtr: src[idx], - } - - _, allocs[idx] = out[idx].PassRef() - } - - return out, func() { - for idx := range allocs { - allocs[idx].Free() +func makeCleanerSBU(src []cgo.SliceBoxedUint8, limit int) func() { + return func() { + for i := 0; i < limit; i++ { + src[i].Destroy() } } } -func toPartitionProofs(src []PartitionProof) ([]generated.FilPartitionSnarkProof, func(), error) { - allocs := make([]AllocationManager, len(src)) - cleanup := func() { - for idx := range allocs { - allocs[idx].Free() - } - } - - out := make([]generated.FilPartitionSnarkProof, len(src)) - for idx := range out { - rp, err := toFilRegisteredPoStProof(src[idx].PoStProof) - if err != nil { - return nil, cleanup, err - } - - out[idx] = generated.FilPartitionSnarkProof{ - RegisteredProof: rp, - ProofLen: uint(len(src[idx].ProofBytes)), - ProofPtr: src[idx].ProofBytes, - } +func toVanillaProofs(src [][]byte) ([]cgo.SliceBoxedUint8, func()) { + out := make([]cgo.SliceBoxedUint8, len(src)) - _, allocs[idx] = out[idx].PassRef() + for i := range out { + out[i] = cgo.AllocSliceBoxedUint8(src[i]) } - return out, cleanup, nil + return out, makeCleanerSBU(out, len(src)) } diff --git a/proofs_test.go b/proofs_test.go index 1f5ab99c..da396c5b 100644 --- a/proofs_test.go +++ b/proofs_test.go @@ -8,15 +8,12 @@ import ( "math/big" "testing" - "github.com/filecoin-project/filecoin-ffi/generated" - - "github.com/stretchr/testify/assert" - commcid "github.com/filecoin-project/go-fil-commcid" - "github.com/filecoin-project/go-state-types/abi" - + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/filecoin-project/filecoin-ffi/cgo" ) func TestRegisteredSealProofFunctions(t *testing.T) { @@ -145,20 +142,20 @@ func (tth *testingTeeHelper) AssertTrue(value bool, msgAndArgs ...interface{}) b } func TestProofTypes(t *testing.T) { - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWinning2KiBV1, abi.RegisteredPoStProof_StackedDrgWinning2KiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWinning8MiBV1, abi.RegisteredPoStProof_StackedDrgWinning8MiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWinning512MiBV1, abi.RegisteredPoStProof_StackedDrgWinning512MiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWinning32GiBV1, abi.RegisteredPoStProof_StackedDrgWinning32GiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWinning64GiBV1, abi.RegisteredPoStProof_StackedDrgWinning64GiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWindow2KiBV1, abi.RegisteredPoStProof_StackedDrgWindow2KiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWindow8MiBV1, abi.RegisteredPoStProof_StackedDrgWindow8MiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWindow512MiBV1, abi.RegisteredPoStProof_StackedDrgWindow512MiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWindow32GiBV1, abi.RegisteredPoStProof_StackedDrgWindow32GiBV1) - assert.EqualValues(t, generated.FilRegisteredPoStProofStackedDrgWindow64GiBV1, abi.RegisteredPoStProof_StackedDrgWindow64GiBV1) - - assert.EqualValues(t, generated.FilRegisteredSealProofStackedDrg2KiBV1, abi.RegisteredSealProof_StackedDrg2KiBV1) - assert.EqualValues(t, generated.FilRegisteredSealProofStackedDrg8MiBV1, abi.RegisteredSealProof_StackedDrg8MiBV1) - assert.EqualValues(t, generated.FilRegisteredSealProofStackedDrg512MiBV1, abi.RegisteredSealProof_StackedDrg512MiBV1) - assert.EqualValues(t, generated.FilRegisteredSealProofStackedDrg32GiBV1, abi.RegisteredSealProof_StackedDrg32GiBV1) - assert.EqualValues(t, generated.FilRegisteredSealProofStackedDrg64GiBV1, abi.RegisteredSealProof_StackedDrg64GiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWinning2KiBV1, abi.RegisteredPoStProof_StackedDrgWinning2KiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWinning8MiBV1, abi.RegisteredPoStProof_StackedDrgWinning8MiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWinning512MiBV1, abi.RegisteredPoStProof_StackedDrgWinning512MiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWinning32GiBV1, abi.RegisteredPoStProof_StackedDrgWinning32GiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWinning64GiBV1, abi.RegisteredPoStProof_StackedDrgWinning64GiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWindow2KiBV1, abi.RegisteredPoStProof_StackedDrgWindow2KiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWindow8MiBV1, abi.RegisteredPoStProof_StackedDrgWindow8MiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWindow512MiBV1, abi.RegisteredPoStProof_StackedDrgWindow512MiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWindow32GiBV1, abi.RegisteredPoStProof_StackedDrgWindow32GiBV1) + assert.EqualValues(t, cgo.RegisteredPoStProofStackedDrgWindow64GiBV1, abi.RegisteredPoStProof_StackedDrgWindow64GiBV1) + + assert.EqualValues(t, cgo.RegisteredSealProofStackedDrg2KiBV1, abi.RegisteredSealProof_StackedDrg2KiBV1) + assert.EqualValues(t, cgo.RegisteredSealProofStackedDrg8MiBV1, abi.RegisteredSealProof_StackedDrg8MiBV1) + assert.EqualValues(t, cgo.RegisteredSealProofStackedDrg512MiBV1, abi.RegisteredSealProof_StackedDrg512MiBV1) + assert.EqualValues(t, cgo.RegisteredSealProofStackedDrg32GiBV1, abi.RegisteredSealProof_StackedDrg32GiBV1) + assert.EqualValues(t, cgo.RegisteredSealProofStackedDrg64GiBV1, abi.RegisteredSealProof_StackedDrg64GiBV1) } diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 14421b36..9fcee722 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -88,9 +88,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.56" +version = "1.0.57" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4361135be9122e0870de935d7c439aef945b9f9ddd4199a553b5270b49c82a27" +checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" [[package]] name = "anymap" @@ -233,9 +233,9 @@ version = "0.1.53" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed6aa3524a2dfcf9fe180c51eae2b58738348d819517ceadf95789c51fff7600" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -278,9 +278,9 @@ dependencies = [ [[package]] name = "base-x" -version = "0.2.8" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4521f3e3d031370679b3b140beb36dfe4801b09ac77e30c61941f97df3ef28b" +checksum = "dc19a4937b4fbd3fe3379793130e42060d10627a360f2127802b10b87e7baf74" [[package]] name = "base64" @@ -584,25 +584,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1db59621ec70f09c5e9b597b220c7a2b43611f4710dc03ceb8748637775692c" -[[package]] -name = "cbindgen" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51e3973b165dc0f435831a9e426de67e894de532754ff7a3f307c03ee5dec7dc" -dependencies = [ - "clap 2.34.0", - "heck 0.3.3", - "indexmap", - "log", - "proc-macro2 1.0.37", - "quote 1.0.18", - "serde", - "serde_json", - "syn 1.0.91", - "tempfile", - "toml", -] - [[package]] name = "cc" version = "1.0.73" @@ -678,24 +659,9 @@ dependencies = [ [[package]] name = "clap" -version = "2.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" -dependencies = [ - "ansi_term 0.12.1", - "atty", - "bitflags 1.3.2", - "strsim 0.8.0", - "textwrap 0.11.0", - "unicode-width", - "vec_map", -] - -[[package]] -name = "clap" -version = "3.1.10" +version = "3.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3124f3f75ce09e22d1410043e1e24f2ecc44fad3afe4f08408f1f7663d68da2b" +checksum = "7c167e37342afc5f33fd87bbc870cedd020d2a6dffa05d45ccd9241fbdd146db" dependencies = [ "atty", "bitflags 1.3.2", @@ -703,9 +669,9 @@ dependencies = [ "clap_lex", "indexmap", "lazy_static", - "strsim 0.10.0", + "strsim", "termcolor", - "textwrap 0.15.0", + "textwrap", ] [[package]] @@ -714,11 +680,11 @@ version = "3.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3aab4734e083b809aaf5794e14e756d1c798d2c69c7f7de7a09a2f5214993c1" dependencies = [ - "heck 0.4.0", + "heck", "proc-macro-error", - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1004,8 +970,8 @@ version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f877be4f7c9f246b183111634f75baa039715e3f46ce860677d3b19a69fb229c" dependencies = [ - "quote 1.0.18", - "syn 1.0.91", + "quote", + "syn", ] [[package]] @@ -1044,10 +1010,10 @@ checksum = "8e91455b86830a1c21799d94524df0845183fa55bafd9aa137b01c7d1065fa36" dependencies = [ "fnv", "ident_case", - "proc-macro2 1.0.37", - "quote 1.0.18", - "strsim 0.10.0", - "syn 1.0.91", + "proc-macro2", + "quote", + "strsim", + "syn", ] [[package]] @@ -1057,8 +1023,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29b5acf0dea37a7f66f7b25d2c5e93fd46f8f6968b1a5d7a3e02e97768afc95a" dependencies = [ "darling_core", - "quote 1.0.18", - "syn 1.0.91", + "quote", + "syn", ] [[package]] @@ -1084,7 +1050,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5bbed42daaa95e780b60a50546aa345b8413a1e46f9a40a12907d3598f038db" dependencies = [ "data-encoding", - "syn 1.0.91", + "syn", ] [[package]] @@ -1093,9 +1059,9 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c5905670fd9c320154f3a4a01c9e609733cd7b753f3c58777ab7d5ce26686b3" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1114,9 +1080,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66e616858f6187ed828df7c64a6d71720d83767a7f19740b2d1b6fe6327b36e5" dependencies = [ "darling", - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -1126,7 +1092,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58a94ace95092c5acb1e97a7e846b310cfbd499652f72297da7493f618a98d73" dependencies = [ "derive_builder_core", - "syn 1.0.91", + "syn", ] [[package]] @@ -1136,10 +1102,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ "convert_case", - "proc-macro2 1.0.37", - "quote 1.0.18", + "proc-macro2", + "quote", "rustc_version", - "syn 1.0.91", + "syn", ] [[package]] @@ -1197,17 +1163,6 @@ dependencies = [ "winapi 0.3.9", ] -[[package]] -name = "drop_struct_macro_derive" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c66c28195b2c389d2a4d41a098f69cc5c689bf9536b435dc377d015f3c69d5de" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "syn 0.15.44", -] - [[package]] name = "ec-gpu" version = "0.1.0" @@ -1294,8 +1249,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af4a304bcd894a5d41f8b379d01e09bff28fd8df257216a33699658ea37bccb8" dependencies = [ "execute-command-tokens", - "quote 1.0.18", - "syn 1.0.91", + "quote", + "syn", ] [[package]] @@ -1358,16 +1313,6 @@ dependencies = [ "serde", ] -[[package]] -name = "ffi-toolkit" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b92ec22ace9da5ca0ad6ab61fa6cab1eb46faad7aaaaf9bcf24394c22b7e605a" -dependencies = [ - "drop_struct_macro_derive", - "libc", -] - [[package]] name = "fil-rustacuda" version = "0.1.3" @@ -1398,11 +1343,11 @@ dependencies = [ [[package]] name = "fil_actor_account" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ab1eb2a815bd10853da7bd6c8626669551a97961f5cffc825f7ba28db00080" +checksum = "b46b4ed5f5e18da44b4981361be4d87dae1753a830c05737ec2d2bd9d46f419b" dependencies = [ - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_shared 0.6.0", @@ -1421,7 +1366,7 @@ dependencies = [ "anyhow", "async-std", "cid", - "clap 3.1.10", + "clap", "futures", "fvm_ipld_blockstore", "fvm_ipld_car", @@ -1451,11 +1396,11 @@ dependencies = [ [[package]] name = "fil_actor_cron" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54c50223e8f8c30235d8f7fa3d43d724dc675b83bdc4ac898666b8199bc9b132" +checksum = "b018030ea343ed767aa06da132edb661d70a1b49d0ff589724b3409b48550c31" dependencies = [ - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_shared 0.6.0", @@ -1488,13 +1433,13 @@ dependencies = [ [[package]] name = "fil_actor_init" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784dfb55c87a977c5f54f096a64083e22b276d778ae0675064b8d42927e4039b" +checksum = "2ce0ba0af37891135e640794d70839ec2f57fae1cc70240391721839b640aa72" dependencies = [ "anyhow", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt 0.4.0", @@ -1529,14 +1474,14 @@ dependencies = [ [[package]] name = "fil_actor_market" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9749daecda9c9307e6dfc0c505ce44dce526d62024135e30ead1c4af5a4ddcca" +checksum = "0222db792ed187d37f7da6f6019eea538fd927c9ede4e2c755d743934715b466" dependencies = [ "ahash", "anyhow", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_bitfield", "fvm_ipld_blockstore", "fvm_ipld_encoding", @@ -1576,14 +1521,14 @@ dependencies = [ [[package]] name = "fil_actor_miner" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "893c7afc0308e5e190b5b2eb25e2cc95393dfcbfc9573a37506dc8c9b2c159b3" +checksum = "322a4a3f1c8448c8480ac75b7859996a0900ccacdaa2a34bacacdbdf21d796e4" dependencies = [ "anyhow", "byteorder 1.4.3", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_amt", "fvm_ipld_bitfield", "fvm_ipld_blockstore", @@ -1622,13 +1567,13 @@ dependencies = [ [[package]] name = "fil_actor_multisig" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c329ac34545634df336fea1faf518561061bb3c38dcec7374f97f3af23ce8ba" +checksum = "16ffc143f5cc20b8a6d91c2801feb51bfc7fe5f31bf278543a232aa644a697e6" dependencies = [ "anyhow", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt 0.4.0", @@ -1661,13 +1606,13 @@ dependencies = [ [[package]] name = "fil_actor_paych" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae7d68c5632b0135759016fa39844285244cd4d252e7bf4f3432d37669176f61" +checksum = "e655a05234a1fbce95f906eb01143ea38fb5ec2e68592073521b9480960f904a" dependencies = [ "anyhow", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_shared 0.6.0", @@ -1702,13 +1647,13 @@ dependencies = [ [[package]] name = "fil_actor_power" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "371226ea6dfc7cb7ca6db8210d3d2f9fc6b820d488ef035d8514e0de8b5df1ac" +checksum = "8aff153971f2e2237969a9a601280c8cba91de41d3ce3cd396bd25ba3af502d0" dependencies = [ "anyhow", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt 0.4.0", @@ -1743,11 +1688,11 @@ dependencies = [ [[package]] name = "fil_actor_reward" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "828e313a96da3aa50dc6e1bbf5f54cc657d6b303bfe90302cc53270e2e933180" +checksum = "69faa6bee076f0ad829f2b42016640f7772f739dd36f3c975d89f680bdb2ceec" dependencies = [ - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_shared 0.6.0", @@ -1776,11 +1721,11 @@ dependencies = [ [[package]] name = "fil_actor_system" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30ae84eae1d9e9bc5596565f330e7d1cc704b6020b33788b2e32feac788d41b5" +checksum = "3b81b4e98b07428bba01969632d5c996033728386b91831d496a62844acad451" dependencies = [ - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_shared 0.6.0", @@ -1810,13 +1755,13 @@ dependencies = [ [[package]] name = "fil_actor_verifreg" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "184108b428502135349eae651aff2aa4a9fecffce10aa6003b1c5179f05c9c71" +checksum = "14383b52216fdebaadc68b164c929e551f263799c3e2a08e228f9259cd19329c" dependencies = [ "anyhow", "cid", - "fil_actors_runtime 7.2.0", + "fil_actors_runtime 7.2.1", "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt 0.4.0", @@ -1859,9 +1804,9 @@ dependencies = [ [[package]] name = "fil_actors_runtime" -version = "7.2.0" +version = "7.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15b697964b0e4db5048b76036bd2d0e08668ba49d61c9e22c581e766f0690e46" +checksum = "deb7ae005ed35034fe64b95f22b9ab0c31166a7131f838b633d461f91d0431e2" dependencies = [ "anyhow", "base64", @@ -1915,26 +1860,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c6f790de3c8ef02e5f7be8d31d3e6fcf5217a2f45190d5fd9bef27171be2c99" dependencies = [ "cid", - "fil_actor_account 7.2.0", + "fil_actor_account 7.2.1", "fil_actor_bundler", - "fil_actor_cron 7.2.0", - "fil_actor_init 7.2.0", - "fil_actor_market 7.2.0", - "fil_actor_miner 7.2.0", - "fil_actor_multisig 7.2.0", - "fil_actor_paych 7.2.0", - "fil_actor_power 7.2.0", - "fil_actor_reward 7.2.0", - "fil_actor_system 7.2.0", - "fil_actor_verifreg 7.2.0", - "fil_actors_runtime 7.2.0", + "fil_actor_cron 7.2.1", + "fil_actor_init 7.2.1", + "fil_actor_market 7.2.1", + "fil_actor_miner 7.2.1", + "fil_actor_multisig 7.2.1", + "fil_actor_paych 7.2.1", + "fil_actor_power 7.2.1", + "fil_actor_reward 7.2.1", + "fil_actor_system 7.2.1", + "fil_actor_verifreg 7.2.1", + "fil_actors_runtime 7.2.1", ] [[package]] name = "fil_logger" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f22fe6c8b8d2ecaf2ef4560a7898455b815987cbe5c67b8f3a85986c609a01a" +checksum = "599d1b83dc76b9db1a1cf1982659e787dc667c358dae3381e806473ba5faf53a" dependencies = [ "atty", "flexi_logger", @@ -1951,11 +1896,8 @@ dependencies = [ "bls-signatures", "blstrs", "byteorder 1.4.3", - "cbindgen", "cid", - "drop_struct_macro_derive", "fff", - "ffi-toolkit", "fil_builtin_actors_bundle 6.2.0", "fil_builtin_actors_bundle 7.2.0", "fil_logger", @@ -1980,6 +1922,7 @@ dependencies = [ "rand_chacha 0.3.1", "rayon", "rust-gpu-tools", + "safer-ffi", "serde", "serde_bytes", "serde_json", @@ -2225,9 +2168,9 @@ version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -2533,6 +2476,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "ghost" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76c813ffb63e8fd3df6f1ac3cc1ea392c7612ac2de4d0b44dcbfe03e5c4bf94a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "gimli" version = "0.26.1" @@ -2588,15 +2542,6 @@ version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" -[[package]] -name = "heck" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] - [[package]] name = "heck" version = "0.4.0" @@ -2688,6 +2633,28 @@ dependencies = [ "futures-util", ] +[[package]] +name = "inventory" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0eb5160c60ba1e809707918ee329adb99d222888155835c6feedba19f6c3fd4" +dependencies = [ + "ctor", + "ghost", + "inventory-impl", +] + +[[package]] +name = "inventory-impl" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e41b53715c6f0c4be49510bb82dee2c1e51c8586d885abe65396e82ed518548" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "io-lifetimes" version = "0.5.3" @@ -2938,6 +2905,21 @@ dependencies = [ "typenum", ] +[[package]] +name = "mini_paste" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2499b7bd9834270bf24cfc4dd96be59020ba6fd7f3276b772aee2de66e82b63" +dependencies = [ + "mini_paste-proc_macro", +] + +[[package]] +name = "mini_paste-proc_macro" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c5f1f52e39b728e73af4b454f1b29173d4544607bd395dafe1918fd149db67" + [[package]] name = "miniz_oxide" version = "0.5.1" @@ -2991,9 +2973,9 @@ checksum = "fc076939022111618a5026d3be019fd8b366e76314538ff9a1b59ffbcbf98bcd" dependencies = [ "proc-macro-crate", "proc-macro-error", - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", "synstructure", ] @@ -3095,9 +3077,9 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -3112,9 +3094,9 @@ dependencies = [ [[package]] name = "num-iter" -version = "0.1.42" +version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2021c8337a54d21aca0d59a92577a029af9431cb59b909b03252b9c164fad59" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" dependencies = [ "autocfg", "num-integer", @@ -3256,9 +3238,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" [[package]] name = "pin-utils" @@ -3332,9 +3314,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", "version_check", ] @@ -3344,19 +3326,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", + "proc-macro2", + "quote", "version_check", ] [[package]] -name = "proc-macro2" -version = "0.4.30" +name = "proc-macro-hack" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" -dependencies = [ - "unicode-xid 0.1.0", -] +checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" [[package]] name = "proc-macro2" @@ -3364,7 +3343,7 @@ version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" dependencies = [ - "unicode-xid 0.2.2", + "unicode-xid", ] [[package]] @@ -3376,22 +3355,13 @@ dependencies = [ "cc", ] -[[package]] -name = "quote" -version = "0.6.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce23b6b870e8f94f81fb0a363d65d86675884b34a09043c81e5562f11c1f8e1" -dependencies = [ - "proc-macro2 0.4.30", -] - [[package]] name = "quote" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" dependencies = [ - "proc-macro2 1.0.37", + "proc-macro2", ] [[package]] @@ -3622,6 +3592,17 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a8614ee435691de62bcffcf4a66d91b3594bf1428a5722e79103249a095690" +[[package]] +name = "require_unsafe_in_body" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "296446f2214753e33792f632262451e8d037cd9697df15db2fd531bdce5a0138" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "rust-gpu-tools" version = "0.5.0" @@ -3650,9 +3631,9 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43ce8670a1a1d0fc2514a3b846dacdb65646f9bd494b6674cfacbb4ce430bd7e" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -3708,6 +3689,32 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" +[[package]] +name = "safer-ffi" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c52424d2271f2f5aae854241d76244d75194b3486c6714c8020cdb8384c6be22" +dependencies = [ + "inventory", + "libc", + "mini_paste", + "proc-macro-hack", + "require_unsafe_in_body", + "safer_ffi-proc_macro", +] + +[[package]] +name = "safer_ffi-proc_macro" +version = "0.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a12d277e24f04228e8c56c5e4482d9dccd44a287746dbc57464d5f7aea2d2d07" +dependencies = [ + "proc-macro-hack", + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "scopeguard" version = "1.1.0" @@ -3771,9 +3778,9 @@ version = "1.0.136" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -3804,9 +3811,9 @@ version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98d0516900518c29efa217c298fa1f4e6c6ffc85ae29fd7f4ee48f176e1a9ed5" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -3825,9 +3832,9 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4076151d1a2b688e25aaf236997933c66e18b870d0369f8b248b8ab2be630d7e" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -4101,12 +4108,6 @@ dependencies = [ "yastl", ] -[[package]] -name = "strsim" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" - [[package]] name = "strsim" version = "0.10.0" @@ -4119,26 +4120,15 @@ version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" -[[package]] -name = "syn" -version = "0.15.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ca4b3b69a77cbe1ffc9e198781b7acb0c7365a883670e8f1c1bc66fba79a5c5" -dependencies = [ - "proc-macro2 0.4.30", - "quote 0.6.13", - "unicode-xid 0.1.0", -] - [[package]] name = "syn" version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "unicode-xid 0.2.2", + "proc-macro2", + "quote", + "unicode-xid", ] [[package]] @@ -4147,10 +4137,10 @@ version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", - "unicode-xid 0.2.2", + "proc-macro2", + "quote", + "syn", + "unicode-xid", ] [[package]] @@ -4198,15 +4188,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "textwrap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -dependencies = [ - "unicode-width", -] - [[package]] name = "textwrap" version = "0.15.0" @@ -4228,9 +4209,9 @@ version = "1.0.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", ] [[package]] @@ -4291,24 +4272,6 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c" -[[package]] -name = "unicode-segmentation" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e8820f5d777f6224dc4be3632222971ac30164d4a258d595640799554ebfd99" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" - [[package]] name = "unicode-xid" version = "0.2.2" @@ -4331,12 +4294,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "vec_map" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" - [[package]] name = "version_check" version = "0.9.4" @@ -4380,9 +4337,9 @@ dependencies = [ "bumpalo", "lazy_static", "log", - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", "wasm-bindgen-shared", ] @@ -4404,7 +4361,7 @@ version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" dependencies = [ - "quote 1.0.18", + "quote", "wasm-bindgen-macro-support", ] @@ -4414,9 +4371,9 @@ version = "0.2.80" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4672,8 +4629,8 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4eb56561c1f8f5441784ea91f52ae8b44268d920f2a59121968fec9297fa7157" dependencies = [ - "proc-macro2 1.0.37", - "quote 1.0.18", - "syn 1.0.91", + "proc-macro2", + "quote", + "syn", "synstructure", ] diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 06aeffe4..e16deecf 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -21,9 +21,7 @@ crate-type = ["rlib", "staticlib"] bls-signatures = { version = "0.11.0", default-features = false, features = ["blst"] } blstrs = "0.4" byteorder = "1.2" -drop_struct_macro_derive = "0.5.0" ff = { version = "0.3.1", package = "fff" } -ffi-toolkit = "0.5.0" filepath = "0.1.1" group = "0.11" libc = "0.2.58" @@ -55,15 +53,13 @@ serde = "1.0.117" serde_bytes = "0.11.5" serde_tuple = "0.5" futures = "0.3.5" +safer-ffi = { version = "0.0.7", features = ["proc_macros"] } [dependencies.filecoin-proofs-api] package = "filecoin-proofs-api" version = "11.0" default-features = false -[build-dependencies] -cbindgen = "= 0.20.0" - [dev-dependencies] tempfile = "3.0.8" @@ -73,7 +69,4 @@ blst-portable = ["bls-signatures/blst-portable", "blstrs/portable"] opencl = ["filecoin-proofs-api/opencl", "bellperson/opencl", "storage-proofs-porep/opencl", "rust-gpu-tools/opencl", "fvm/opencl"] cuda = ["filecoin-proofs-api/cuda", "bellperson/cuda", "storage-proofs-porep/cuda", "rust-gpu-tools/cuda", "fvm/cuda"] multicore-sdr = ["storage-proofs-porep/multicore-sdr"] - -# Only enabled by cbindgen. When enabled, the cgo_* externs are disabled so as not to confuse -# cbindgen. -bindgen=[] +c-headers = ["safer-ffi/headers"] diff --git a/rust/build.rs b/rust/build.rs deleted file mode 100644 index bb3cf601..00000000 --- a/rust/build.rs +++ /dev/null @@ -1,11 +0,0 @@ -use std::env; -use std::path::Path; - -fn main() { - let out_dir = env::var("OUT_DIR").unwrap(); - let hdr_out = Path::new(&out_dir).join("include/filcrypto.h"); - - cbindgen::generate(std::env::var("CARGO_MANIFEST_DIR").unwrap()) - .expect("Could not generate header") - .write_to_file(hdr_out); -} diff --git a/rust/cbindgen.toml b/rust/cbindgen.toml deleted file mode 100644 index baf8f66b..00000000 --- a/rust/cbindgen.toml +++ /dev/null @@ -1,26 +0,0 @@ -header = """ -/* filcrypto Header */ - -#ifdef __cplusplus -extern "C" { -#endif -""" -trailer = """ -#ifdef __cplusplus -} /* extern "C" */ -#endif -""" - -include_guard = "filcrypto_H" -include_version = true -language = "C" - -[parse] -parse_deps = true -include = ["ffi-toolkit"] - -[parse.expand] -features = ["bindgen"] - -[enum] -prefix_with_name = true diff --git a/rust/scripts/build-release.sh b/rust/scripts/build-release.sh index b96e3bbd..16e39fd8 100755 --- a/rust/scripts/build-release.sh +++ b/rust/scripts/build-release.sh @@ -64,6 +64,10 @@ main() { find . -type f -name "lib$1.a" fi + # generate filcrypto.h + RUSTFLAGS="${__rust_flags}" HEADER_DIR="." \ + cargo test build_headers --features c-headers + # generate pkg-config # sed -e "s;@VERSION@;$(git rev-parse HEAD);" \ diff --git a/rust/src/bls/api.rs b/rust/src/bls/api.rs index 35978878..741d4306 100644 --- a/rust/src/bls/api.rs +++ b/rust/src/bls/api.rs @@ -1,5 +1,3 @@ -use std::slice::from_raw_parts; - use bls_signatures::{ aggregate as aggregate_sig, hash as hash_sig, verify as verify_sig, verify_messages as verify_messages_sig, Error, PrivateKey, PublicKey, Serialize, Signature, @@ -12,34 +10,17 @@ use rand::rngs::OsRng; use rand::SeedableRng; use rand_chacha::ChaChaRng; use rayon::prelude::*; - -use crate::bls::types; -use crate::proofs::types::fil_32ByteArray; +use safer_ffi::prelude::*; pub const SIGNATURE_BYTES: usize = 96; pub const PRIVATE_KEY_BYTES: usize = 32; pub const PUBLIC_KEY_BYTES: usize = 48; pub const DIGEST_BYTES: usize = 96; -#[repr(C)] -pub struct fil_BLSSignature { - pub inner: [u8; SIGNATURE_BYTES], -} - -#[repr(C)] -pub struct fil_BLSPrivateKey { - pub inner: [u8; PRIVATE_KEY_BYTES], -} - -#[repr(C)] -pub struct fil_BLSPublicKey { - pub inner: [u8; PUBLIC_KEY_BYTES], -} - -#[repr(C)] -pub struct fil_BLSDigest { - pub inner: [u8; DIGEST_BYTES], -} +pub type BLSSignature = [u8; SIGNATURE_BYTES]; +pub type BLSPrivateKey = [u8; PRIVATE_KEY_BYTES]; +pub type BLSPublicKey = [u8; PUBLIC_KEY_BYTES]; +pub type BLSDigest = [u8; DIGEST_BYTES]; /// Unwraps or returns the passed in value. macro_rules! try_ffi { @@ -51,109 +32,96 @@ macro_rules! try_ffi { }}; } +#[ffi_export] +fn destroy_box_bls_digest(ptr: repr_c::Box) { + drop(ptr); +} + +#[ffi_export] +fn destroy_box_bls_private_key(ptr: repr_c::Box) { + drop(ptr); +} + +#[ffi_export] +fn destroy_box_bls_public_key(ptr: repr_c::Box) { + drop(ptr); +} +#[ffi_export] +fn destroy_box_bls_signature(ptr: repr_c::Box) { + drop(ptr); +} + /// Compute the digest of a message /// /// # Arguments /// -/// * `message_ptr` - pointer to a message byte array -/// * `message_len` - length of the byte array -#[no_mangle] -pub unsafe extern "C" fn fil_hash( - message_ptr: *const u8, - message_len: libc::size_t, -) -> *mut types::fil_HashResponse { - // prep request - let message = from_raw_parts(message_ptr, message_len); - +/// * `message` - reference to a message byte array +#[ffi_export] +pub fn hash(message: c_slice::Ref) -> repr_c::Box { // call method - let digest = hash_sig(message); - - // prep response - let mut raw_digest: [u8; DIGEST_BYTES] = [0; DIGEST_BYTES]; - raw_digest.copy_from_slice(digest.to_bytes().as_ref()); + let raw_digest = hash_sig(&message).to_bytes(); + let digest: [u8; DIGEST_BYTES] = raw_digest.as_ref().try_into().expect("known size"); - let response = types::fil_HashResponse { - digest: fil_BLSDigest { inner: raw_digest }, - }; - - Box::into_raw(Box::new(response)) + repr_c::Box::new(digest) } /// Aggregate signatures together into a new signature /// /// # Arguments /// -/// * `flattened_signatures_ptr` - pointer to a byte array containing signatures -/// * `flattened_signatures_len` - length of the byte array (multiple of SIGNATURE_BYTES) +/// * `flattened_signatures` - byte array containing signatures /// -/// Returns `NULL` on error. Result must be freed using `destroy_aggregate_response`. -#[no_mangle] -pub unsafe extern "C" fn fil_aggregate( - flattened_signatures_ptr: *const u8, - flattened_signatures_len: libc::size_t, -) -> *mut types::fil_AggregateResponse { +/// Returns `None` on error. Result must be freed using `destroy_aggregate_response`. +#[ffi_export] +pub fn aggregate(flattened_signatures: c_slice::Ref) -> Option> { // prep request let signatures = try_ffi!( - from_raw_parts(flattened_signatures_ptr, flattened_signatures_len) + flattened_signatures .par_chunks(SIGNATURE_BYTES) .map(|item| { Signature::from_bytes(item) }) .collect::, _>>(), - std::ptr::null_mut() + None ); - let mut raw_signature: [u8; SIGNATURE_BYTES] = [0; SIGNATURE_BYTES]; + let mut signature: [u8; SIGNATURE_BYTES] = [0; SIGNATURE_BYTES]; - let aggregated = try_ffi!(aggregate_sig(&signatures), std::ptr::null_mut()); + let aggregated = try_ffi!(aggregate_sig(&signatures), None); aggregated - .write_bytes(&mut raw_signature.as_mut()) + .write_bytes(&mut signature.as_mut()) .expect("preallocated"); - let response = types::fil_AggregateResponse { - signature: fil_BLSSignature { - inner: raw_signature, - }, - }; - - Box::into_raw(Box::new(response)) + Some(repr_c::Box::new(signature)) } /// Verify that a signature is the aggregated signature of hashes - pubkeys /// /// # Arguments /// -/// * `signature_ptr` - pointer to a signature byte array (SIGNATURE_BYTES long) -/// * `flattened_digests_ptr` - pointer to a byte array containing digests -/// * `flattened_digests_len` - length of the byte array (multiple of DIGEST_BYTES) -/// * `flattened_public_keys_ptr` - pointer to a byte array containing public keys -/// * `flattened_public_keys_len` - length of the array -#[no_mangle] -pub unsafe extern "C" fn fil_verify( - signature_ptr: *const u8, - flattened_digests_ptr: *const u8, - flattened_digests_len: libc::size_t, - flattened_public_keys_ptr: *const u8, - flattened_public_keys_len: libc::size_t, -) -> libc::c_int { +/// * `signature` - signature byte array (SIGNATURE_BYTES long) +/// * `flattened_digests` - byte array containing digests +/// * `flattened_public_keys` - byte array containing public keys +#[ffi_export] +pub fn verify( + signature: c_slice::Ref, + flattened_digests: c_slice::Ref, + flattened_public_keys: c_slice::Ref, +) -> bool { // prep request - let raw_signature = from_raw_parts(signature_ptr, SIGNATURE_BYTES); - let signature = try_ffi!(Signature::from_bytes(raw_signature), 0); - - let raw_digests = from_raw_parts(flattened_digests_ptr, flattened_digests_len); - let raw_public_keys = from_raw_parts(flattened_public_keys_ptr, flattened_public_keys_len); + let signature = try_ffi!(Signature::from_bytes(&signature), false); - if raw_digests.len() % DIGEST_BYTES != 0 { - return 0; + if flattened_digests.len() % DIGEST_BYTES != 0 { + return false; } - if raw_public_keys.len() % PUBLIC_KEY_BYTES != 0 { - return 0; + if flattened_public_keys.len() % PUBLIC_KEY_BYTES != 0 { + return false; } - if raw_digests.len() / DIGEST_BYTES != raw_public_keys.len() / PUBLIC_KEY_BYTES { - return 0; + if flattened_digests.len() / DIGEST_BYTES != flattened_public_keys.len() / PUBLIC_KEY_BYTES { + return false; } let digests: Vec<_> = try_ffi!( - raw_digests + flattened_digests .par_chunks(DIGEST_BYTES) .map(|item: &[u8]| { let mut digest = [0u8; DIGEST_BYTES]; @@ -163,88 +131,71 @@ pub unsafe extern "C" fn fil_verify( affine.map(Into::into).ok_or(Error::CurveDecode) }) .collect::, Error>>(), - 0 + false ); let public_keys: Vec<_> = try_ffi!( - raw_public_keys + flattened_public_keys .par_chunks(PUBLIC_KEY_BYTES) .map(|item| { PublicKey::from_bytes(item) }) .collect::>(), - 0 + false ); - verify_sig(&signature, digests.as_slice(), public_keys.as_slice()) as libc::c_int + verify_sig(&signature, digests.as_slice(), public_keys.as_slice()) } /// Verify that a signature is the aggregated signature of the hashed messages /// /// # Arguments /// -/// * `signature_ptr` - pointer to a signature byte array (SIGNATURE_BYTES long) -/// * `messages_ptr` - pointer to an array containing the pointers to the messages -/// * `messages_sizes_ptr` - pointer to an array containing the lengths of the messages -/// * `messages_len` - length of the two messages arrays -/// * `flattened_public_keys_ptr` - pointer to a byte array containing public keys -/// * `flattened_public_keys_len` - length of the array -#[no_mangle] -pub unsafe extern "C" fn fil_hash_verify( - signature_ptr: *const u8, - flattened_messages_ptr: *const u8, - flattened_messages_len: libc::size_t, - message_sizes_ptr: *const libc::size_t, - message_sizes_len: libc::size_t, - flattened_public_keys_ptr: *const u8, - flattened_public_keys_len: libc::size_t, -) -> libc::c_int { +/// * `signature` - signature byte array (SIGNATURE_BYTES long) +/// * `messages` - array containing the pointers to the messages +/// * `messages_sizes` - array containing the lengths of the messages +/// * `messages_len` - length of the two messages arrays +/// * `flattened_public_keys` - byte array containing public keys +#[ffi_export] +pub fn hash_verify( + signature: c_slice::Ref, + flattened_messages: c_slice::Ref, + message_sizes: c_slice::Ref, + flattened_public_keys: c_slice::Ref, +) -> bool { // prep request - let raw_signature = from_raw_parts(signature_ptr, SIGNATURE_BYTES); - let signature = try_ffi!(Signature::from_bytes(raw_signature), 0); + let signature = try_ffi!(Signature::from_bytes(&signature), false); - let flattened = from_raw_parts(flattened_messages_ptr, flattened_messages_len); - let chunk_sizes = from_raw_parts(message_sizes_ptr, message_sizes_len); - - // split the flattened message array into slices of individual messages to - // be hashed - let mut messages: Vec<&[u8]> = Vec::with_capacity(message_sizes_len); + // split the flattened message array into slices of individual messages to be hashed + let mut messages: Vec<&[u8]> = Vec::with_capacity(message_sizes.len()); let mut offset = 0; - for chunk_size in chunk_sizes.iter() { - messages.push(&flattened[offset..offset + *chunk_size]); + for chunk_size in message_sizes.iter() { + messages.push(&flattened_messages[offset..offset + *chunk_size]); offset += *chunk_size } - let raw_public_keys = from_raw_parts(flattened_public_keys_ptr, flattened_public_keys_len); - - if raw_public_keys.len() % PUBLIC_KEY_BYTES != 0 { - return 0; + if flattened_public_keys.len() % PUBLIC_KEY_BYTES != 0 { + return false; } let public_keys: Vec<_> = try_ffi!( - raw_public_keys + flattened_public_keys .par_chunks(PUBLIC_KEY_BYTES) .map(|item| { PublicKey::from_bytes(item) }) .collect::>(), - 0 + false ); - verify_messages_sig(&signature, &messages, &public_keys) as libc::c_int + verify_messages_sig(&signature, &messages, &public_keys) } /// Generate a new private key -#[no_mangle] -pub unsafe extern "C" fn fil_private_key_generate() -> *mut types::fil_PrivateKeyGenerateResponse { +#[ffi_export] +pub fn private_key_generate() -> repr_c::Box { let mut raw_private_key: [u8; PRIVATE_KEY_BYTES] = [0; PRIVATE_KEY_BYTES]; PrivateKey::generate(&mut OsRng) .write_bytes(&mut raw_private_key.as_mut()) .expect("preallocated"); - let response = types::fil_PrivateKeyGenerateResponse { - private_key: fil_BLSPrivateKey { - inner: raw_private_key, - }, - }; - - Box::into_raw(Box::new(response)) + repr_c::Box::new(raw_private_key) } /// Generate a new private key with seed @@ -254,81 +205,53 @@ pub unsafe extern "C" fn fil_private_key_generate() -> *mut types::fil_PrivateKe /// # Arguments /// /// * `raw_seed` - a seed byte array with 32 bytes -/// -/// Returns `NULL` when passed a NULL pointer. -#[no_mangle] -pub unsafe extern "C" fn fil_private_key_generate_with_seed( - raw_seed: fil_32ByteArray, -) -> *mut types::fil_PrivateKeyGenerateResponse { - let rng = &mut ChaChaRng::from_seed(raw_seed.inner); +#[ffi_export] +pub fn private_key_generate_with_seed(raw_seed: &[u8; 32]) -> repr_c::Box { + let rng = &mut ChaChaRng::from_seed(*raw_seed); let mut raw_private_key: [u8; PRIVATE_KEY_BYTES] = [0; PRIVATE_KEY_BYTES]; PrivateKey::generate(rng) .write_bytes(&mut raw_private_key.as_mut()) .expect("preallocated"); - let response = types::fil_PrivateKeyGenerateResponse { - private_key: fil_BLSPrivateKey { - inner: raw_private_key, - }, - }; - - Box::into_raw(Box::new(response)) + repr_c::Box::new(raw_private_key) } /// Sign a message with a private key and return the signature /// /// # Arguments /// -/// * `raw_private_key_ptr` - pointer to a private key byte array -/// * `message_ptr` - pointer to a message byte array -/// * `message_len` - length of the byte array +/// * `raw_private_key` - private key byte array +/// * `message` - message byte array /// -/// Returns `NULL` when passed invalid arguments. -#[no_mangle] -pub unsafe extern "C" fn fil_private_key_sign( - raw_private_key_ptr: *const u8, - message_ptr: *const u8, - message_len: libc::size_t, -) -> *mut types::fil_PrivateKeySignResponse { - // prep request - let private_key_slice = from_raw_parts(raw_private_key_ptr, PRIVATE_KEY_BYTES); - let private_key = try_ffi!( - PrivateKey::from_bytes(private_key_slice), - std::ptr::null_mut() - ); - let message = from_raw_parts(message_ptr, message_len); +/// Returns `None` when passed invalid arguments. +#[ffi_export] +pub fn private_key_sign( + raw_private_key: c_slice::Ref, + message: c_slice::Ref, +) -> Option> { + let private_key = try_ffi!(PrivateKey::from_bytes(&raw_private_key), None); let mut raw_signature: [u8; SIGNATURE_BYTES] = [0; SIGNATURE_BYTES]; - PrivateKey::sign(&private_key, message) + PrivateKey::sign(&private_key, &message[..]) .write_bytes(&mut raw_signature.as_mut()) .expect("preallocated"); - let response = types::fil_PrivateKeySignResponse { - signature: fil_BLSSignature { - inner: raw_signature, - }, - }; - - Box::into_raw(Box::new(response)) + Some(repr_c::Box::new(raw_signature)) } /// Generate the public key for a private key /// /// # Arguments /// -/// * `raw_private_key_ptr` - pointer to a private key byte array +/// * `raw_private_key` - private key byte array /// -/// Returns `NULL` when passed invalid arguments. -#[no_mangle] -pub unsafe extern "C" fn fil_private_key_public_key( - raw_private_key_ptr: *const u8, -) -> *mut types::fil_PrivateKeyPublicKeyResponse { - let private_key_slice = from_raw_parts(raw_private_key_ptr, PRIVATE_KEY_BYTES); - let private_key = try_ffi!( - PrivateKey::from_bytes(private_key_slice), - std::ptr::null_mut() - ); +/// Returns `None` when passed invalid arguments. +#[ffi_export] +pub fn private_key_public_key( + raw_private_key: c_slice::Ref, +) -> Option> { + let private_key = try_ffi!(PrivateKey::from_bytes(&raw_private_key), None); let mut raw_public_key: [u8; PUBLIC_KEY_BYTES] = [0; PUBLIC_KEY_BYTES]; private_key @@ -336,20 +259,14 @@ pub unsafe extern "C" fn fil_private_key_public_key( .write_bytes(&mut raw_public_key.as_mut()) .expect("preallocated"); - let response = types::fil_PrivateKeyPublicKeyResponse { - public_key: fil_BLSPublicKey { - inner: raw_public_key, - }, - }; - - Box::into_raw(Box::new(response)) + Some(repr_c::Box::new(raw_public_key)) } /// Returns a zero signature, used as placeholder in Filecoin. /// /// The return value is a pointer to a compressed signature in bytes, of length `SIGNATURE_BYTES` -#[no_mangle] -pub unsafe extern "C" fn fil_create_zero_signature() -> *mut types::fil_ZeroSignatureResponse { +#[ffi_export] +pub fn create_zero_signature() -> repr_c::Box { let sig: Signature = G2Affine::identity().into(); let mut raw_signature: [u8; SIGNATURE_BYTES] = [0; SIGNATURE_BYTES]; @@ -357,19 +274,7 @@ pub unsafe extern "C" fn fil_create_zero_signature() -> *mut types::fil_ZeroSign sig.write_bytes(&mut raw_signature.as_mut()) .expect("preallocated"); - let response = types::fil_ZeroSignatureResponse { - signature: fil_BLSSignature { - inner: raw_signature, - }, - }; - - Box::into_raw(Box::new(response)) -} - -/// Frees the memory of the returned value of `fil_create_zero_signature`. -#[no_mangle] -pub unsafe extern "C" fn fil_drop_signature(sig: *mut u8) { - let _: &[u8] = std::slice::from_raw_parts_mut(sig, SIGNATURE_BYTES); + repr_c::Box::new(raw_signature) } #[cfg(test)] @@ -378,94 +283,70 @@ mod tests { #[test] fn key_verification() { - unsafe { - let private_key = (*fil_private_key_generate()).private_key.inner; - let public_key = (*fil_private_key_public_key(&private_key[0])) - .public_key - .inner; - let message = b"hello world"; - let digest = (*fil_hash(&message[0], message.len())).digest.inner; - let signature = (*fil_private_key_sign(&private_key[0], &message[0], message.len())) - .signature - .inner; - let verified = fil_verify( - &signature[0], - &digest[0], - digest.len(), - &public_key[0], - public_key.len(), - ); - - assert_eq!(1, verified); - - let flattened_messages = message; - let message_sizes = [message.len()]; - let verified = fil_hash_verify( - signature.as_ptr(), - flattened_messages.as_ptr(), - flattened_messages.len(), - message_sizes.as_ptr(), - message_sizes.len(), - public_key.as_ptr(), - public_key.len(), - ); - - assert_eq!(1, verified); - - let different_message = b"bye world"; - let different_digest = (*fil_hash(&different_message[0], different_message.len())) - .digest - .inner; - let not_verified = fil_verify( - &signature[0], - &different_digest[0], - different_digest.len(), - &public_key[0], - public_key.len(), - ); - - assert_eq!(0, not_verified); - - // garbage verification - let different_digest = vec![0, 1, 2, 3, 4]; - let not_verified = fil_verify( - &signature[0], - &different_digest[0], - different_digest.len(), - &public_key[0], - public_key.len(), - ); - - assert_eq!(0, not_verified); - } + let private_key = private_key_generate(); + let public_key = private_key_public_key(private_key[..].into()).unwrap(); + let message = b"hello world"; + let digest = hash(message[..].into()); + let signature = private_key_sign(private_key[..].into(), message[..].into()).unwrap(); + let verified = verify( + signature[..].into(), + digest[..].into(), + public_key[..].into(), + ); + + assert!(verified); + + let message_sizes = vec![message.len()]; + let flattened_messages = message; + + let verified = hash_verify( + signature[..].into(), + flattened_messages[..].into(), + message_sizes[..].into(), + public_key[..].into(), + ); + + assert!(verified); + + let different_message = b"bye world"; + let different_digest = hash(different_message[..].into()); + let not_verified = verify( + signature[..].into(), + different_digest[..].into(), + public_key[..].into(), + ); + + assert!(!not_verified); + + // garbage verification + let different_digest = vec![0, 1, 2, 3, 4]; + let not_verified = verify( + signature[..].into(), + different_digest[..].into(), + public_key[..].into(), + ); + + assert!(!not_verified); } #[test] fn private_key_with_seed() { - unsafe { - let seed = fil_32ByteArray { inner: [5u8; 32] }; - let private_key = (*fil_private_key_generate_with_seed(seed)) - .private_key - .inner; - assert_eq!( - [ - 56, 13, 181, 159, 37, 1, 12, 96, 45, 77, 254, 118, 103, 235, 218, 176, 220, - 241, 142, 119, 206, 233, 83, 35, 26, 15, 118, 198, 192, 120, 179, 52 - ], - private_key, - ); - } + let seed = [5u8; 32]; + let private_key = private_key_generate_with_seed(&seed); + assert_eq!( + &[ + 56, 13, 181, 159, 37, 1, 12, 96, 45, 77, 254, 118, 103, 235, 218, 176, 220, 241, + 142, 119, 206, 233, 83, 35, 26, 15, 118, 198, 192, 120, 179, 52 + ], + &private_key[..], + ); } #[test] fn test_zero_key() { - unsafe { - let resp = fil_create_zero_signature(); - let sig = Signature::from_bytes(&(*resp).signature.inner).unwrap(); + let resp = create_zero_signature(); + let sig = Signature::from_bytes(&(*resp)).unwrap(); - assert_eq!(sig, Signature::from(G2Affine::identity())); - - types::fil_destroy_zero_signature_response(resp); - } + assert_eq!(sig, Signature::from(G2Affine::identity())); } } diff --git a/rust/src/bls/mod.rs b/rust/src/bls/mod.rs index 8389f117..e5fdf85e 100644 --- a/rust/src/bls/mod.rs +++ b/rust/src/bls/mod.rs @@ -1,2 +1 @@ pub mod api; -pub mod types; diff --git a/rust/src/bls/types.rs b/rust/src/bls/types.rs deleted file mode 100644 index 4e79f99b..00000000 --- a/rust/src/bls/types.rs +++ /dev/null @@ -1,79 +0,0 @@ -use crate::bls::api::{fil_BLSDigest, fil_BLSPrivateKey, fil_BLSPublicKey, fil_BLSSignature}; - -/// HashResponse - -#[repr(C)] -pub struct fil_HashResponse { - pub digest: fil_BLSDigest, -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_hash_response(ptr: *mut fil_HashResponse) { - let _ = Box::from_raw(ptr); -} - -/// AggregateResponse - -#[repr(C)] -pub struct fil_AggregateResponse { - pub signature: fil_BLSSignature, -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_aggregate_response(ptr: *mut fil_AggregateResponse) { - let _ = Box::from_raw(ptr); -} - -/// PrivateKeyGenerateResponse - -#[repr(C)] -pub struct fil_PrivateKeyGenerateResponse { - pub private_key: fil_BLSPrivateKey, -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_private_key_generate_response( - ptr: *mut fil_PrivateKeyGenerateResponse, -) { - let _ = Box::from_raw(ptr); -} - -/// PrivateKeySignResponse - -#[repr(C)] -pub struct fil_PrivateKeySignResponse { - pub signature: fil_BLSSignature, -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_private_key_sign_response( - ptr: *mut fil_PrivateKeySignResponse, -) { - let _ = Box::from_raw(ptr); -} - -/// PrivateKeyPublicKeyResponse - -#[repr(C)] -pub struct fil_PrivateKeyPublicKeyResponse { - pub public_key: fil_BLSPublicKey, -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_private_key_public_key_response( - ptr: *mut fil_PrivateKeyPublicKeyResponse, -) { - let _ = Box::from_raw(ptr); -} - -/// AggregateResponse - -#[repr(C)] -pub struct fil_ZeroSignatureResponse { - pub signature: fil_BLSSignature, -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_zero_signature_response(ptr: *mut fil_ZeroSignatureResponse) { - let _ = Box::from_raw(ptr); -} diff --git a/rust/src/fvm/blockstore/cgo.rs b/rust/src/fvm/blockstore/cgo.rs index 71393acd..56662806 100644 --- a/rust/src/fvm/blockstore/cgo.rs +++ b/rust/src/fvm/blockstore/cgo.rs @@ -34,13 +34,16 @@ impl Blockstore for CgoBlockstore { match cgo_blockstore_has(self.handle, k_bytes.as_ptr(), k_bytes.len() as i32) { // We shouldn't get an "error not found" here, but there's no reason to be strict // about it. - 0 | ERR_NOT_FOUND => Ok(false), + 0 => Ok(false), + x if x == FvmError::NotFound as i32 => Ok(false), 1 => Ok(true), // Panic on unknown values. There's a bug in the program. r @ 2.. => panic!("invalid return value from has: {}", r), // Panic if the store isn't registered. This means something _very_ unsafe is going // on and there is a bug in the program. - ERR_INVALID_HANDLE => panic!("blockstore {} not registered", self.handle), + x if x == FvmError::InvalidHandle as i32 => { + panic!("blockstore {} not registered", self.handle) + } // Otherwise, return "other". We should add error codes in the future. e => Err(anyhow!("cgo blockstore 'has' failed with error code {}", e)), } @@ -61,8 +64,10 @@ impl Blockstore for CgoBlockstore { ) { 0 => Ok(Some(Vec::from_raw_parts(buf, size as usize, size as usize))), r @ 1.. => panic!("invalid return value from get: {}", r), - ERR_INVALID_HANDLE => panic!("blockstore {} not registered", self.handle), - ERR_NOT_FOUND => Ok(None), + x if x == FvmError::InvalidHandle as i32 => { + panic!("blockstore {} not registered", self.handle) + } + x if x == FvmError::NotFound as i32 => Ok(None), e => Err(anyhow!("cgo blockstore 'get' failed with error code {}", e)), } } @@ -92,9 +97,11 @@ impl Blockstore for CgoBlockstore { match result { 0 => Ok(()), r @ 1.. => panic!("invalid return value from put_many: {}", r), - ERR_INVALID_HANDLE => panic!("blockstore {} not registered", handle), + x if x == FvmError::InvalidHandle as i32 => { + panic!("blockstore {} not registered", handle) + } // This error makes no sense. - ERR_NOT_FOUND => panic!("not found error on put"), + x if x == FvmError::NotFound as i32 => panic!("not found error on put"), e => Err(anyhow!("cgo blockstore 'put' failed with error code {}", e)), } } @@ -135,9 +142,11 @@ impl Blockstore for CgoBlockstore { ) { 0 => Ok(()), r @ 1.. => panic!("invalid return value from put: {}", r), - ERR_INVALID_HANDLE => panic!("blockstore {} not registered", self.handle), + x if x == FvmError::InvalidHandle as i32 => { + panic!("blockstore {} not registered", self.handle) + } // This error makes no sense. - ERR_NOT_FOUND => panic!("not found error on put"), + x if x == FvmError::NotFound as i32 => panic!("not found error on put"), e => Err(anyhow!("cgo blockstore 'put' failed with error code {}", e)), } } diff --git a/rust/src/fvm/cgo/error.rs b/rust/src/fvm/cgo/error.rs index 35415bfc..9ced9155 100644 --- a/rust/src/fvm/cgo/error.rs +++ b/rust/src/fvm/cgo/error.rs @@ -1,19 +1,26 @@ //! Error codes used by the cgo bridge (blockstore/externs). These are used by both rust and go, so //! don't remove them even if they seem dead. -#![allow(dead_code)] +use safer_ffi::prelude::*; -/// The error code returned by cgo if the blockstore handle isn't valid. -pub const ERR_INVALID_HANDLE: i32 = -1; +#[derive_ReprC] +#[repr(i32)] +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum FvmError { + /// The error code returned by cgo if the blockstore handle isn't valid. + InvalidHandle = -1, + /// The error code returned by cgo when the block isn't found. + NotFound = -2, + /// The error code returned by cgo when there's some underlying system error. + Io = -3, + /// The error code returned by cgo when an argument is invalid. + InvalidArgument = -4, + /// The error code returned by cgo when the application panics. + Panic = -5, +} -/// The error code returned by cgo when the block isn't found. -pub const ERR_NOT_FOUND: i32 = -2; - -/// The error code returned by cgo when there's some underlying system error. -pub const ERR_IO: i32 = -3; - -/// The error code returned by cgo when an argument is invalid. -pub const ERR_INVALID_ARGUMENT: i32 = -4; - -/// The error code returned by cgo when the application panics. -pub const ERR_PANIC: i32 = -5; +// Dummy to make safer-ffi export the error enum +#[ffi_export] +fn dummy(_error: FvmError) { + panic!("Don't call me"); +} diff --git a/rust/src/fvm/cgo/mock.rs b/rust/src/fvm/cgo/mock.rs deleted file mode 100644 index 29250a81..00000000 --- a/rust/src/fvm/cgo/mock.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! This module contains the "mock" version of the cgo externs. We need these so that cbindgen -//! doesn't try to put them in the C header. Otherwise, c-for-go can't parse the header. - -pub fn cgo_blockstore_get( - store: u64, - k: *const u8, - k_len: i32, - block: *mut *mut u8, - size: *mut i32, -) -> i32 { - unimplemented!() -} - -pub fn cgo_blockstore_put( - store: u64, - k: *const u8, - k_len: i32, - block: *const u8, - block_len: i32, -) -> i32 { - unimplemented!() -} - -pub fn cgo_blockstore_put_many( - store: u64, - lengths: *const i32, - lengths_len: i32, - blocks: *const u8, -) -> i32 { - unimplemented!() -} - -pub fn cgo_blockstore_has(store: u64, k: *const u8, k_len: i32) -> i32 { - unimplemented!() -} - -pub fn cgo_extern_get_chain_randomness( - handle: u64, - pers: i64, - round: i64, - entropy: *const u8, - entropy_len: i32, - randomness: *mut [u8; 32], -) -> i32 { - unimplemented!() -} - -pub fn cgo_extern_get_beacon_randomness( - handle: u64, - pers: i64, - round: i64, - entropy: *const u8, - entropy_len: i32, - randomness: *mut [u8; 32], -) -> i32 { - unimplemented!() -} - -pub fn cgo_extern_verify_consensus_fault( - handle: u64, - h1: *const u8, - h1_len: i32, - h2: *const u8, - h2_len: i32, - extra: *const u8, - extra_len: i32, - miner_id: *mut u64, - epoch: *mut i64, - fault: *mut i64, - gas_used: *mut i64, -) -> i32 { - unimplemented!() -} diff --git a/rust/src/fvm/cgo/mod.rs b/rust/src/fvm/cgo/mod.rs index 12330abe..811ac70f 100644 --- a/rust/src/fvm/cgo/mod.rs +++ b/rust/src/fvm/cgo/mod.rs @@ -1,13 +1,5 @@ -/// cbindgen:ignore -#[cfg(not(feature = "bindgen"))] mod externs; -#[cfg(not(feature = "bindgen"))] pub use externs::*; -#[cfg(feature = "bindgen")] -mod mock; -#[cfg(feature = "bindgen")] -pub use mock::*; - mod error; pub use error::*; diff --git a/rust/src/fvm/externs.rs b/rust/src/fvm/externs.rs index 865b674d..ed2b561c 100644 --- a/rust/src/fvm/externs.rs +++ b/rust/src/fvm/externs.rs @@ -43,7 +43,9 @@ impl Rand for CgoExterns { ) { 0 => Ok(buf), r @ 1.. => panic!("invalid return value from has: {}", r), - ERR_INVALID_HANDLE => panic!("extern {} not registered", self.handle), + x if x == FvmError::InvalidHandle as i32 => { + panic!("extern {} not registered", self.handle) + } e => Err(anyhow!( "cgo extern 'get_chain_randomness' failed with error code {}", e @@ -70,7 +72,9 @@ impl Rand for CgoExterns { ) { 0 => Ok(buf), r @ 1.. => panic!("invalid return value from has: {}", r), - ERR_INVALID_HANDLE => panic!("extern {} not registered", self.handle), + x if x == FvmError::InvalidHandle as i32 => { + panic!("extern {} not registered", self.handle) + } e => Err(anyhow!( "cgo extern 'get_beacon_randomness' failed with error code {}", e @@ -118,7 +122,9 @@ impl Consensus for CgoExterns { gas_used, )), r @ 1.. => panic!("invalid return value from has: {}", r), - ERR_INVALID_HANDLE => panic!("extern {} not registered", self.handle), + x if x == FvmError::InvalidHandle as i32 => { + panic!("extern {} not registered", self.handle) + } e => Err(anyhow!( "cgo extern 'verify_consensus_fault' failed with error code {}", e diff --git a/rust/src/fvm/machine.rs b/rust/src/fvm/machine.rs index e187b01d..a101f3ab 100644 --- a/rust/src/fvm/machine.rs +++ b/rust/src/fvm/machine.rs @@ -1,9 +1,8 @@ -use std::convert::{TryFrom, TryInto}; +use std::convert::TryFrom; use std::sync::Mutex; -use anyhow::anyhow; +use anyhow::{anyhow, bail}; use cid::Cid; -use ffi_toolkit::{catch_panic_response, raw_ptr, rust_str_to_c_str, FCPResponseStatus}; use futures::executor::block_on; use fvm::call_manager::{DefaultCallManager, InvocationResult}; use fvm::executor::{ApplyKind, DefaultExecutor, Executor}; @@ -13,18 +12,20 @@ use fvm::DefaultKernel; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_car::load_car; use fvm_ipld_encoding::tuple::{Deserialize_tuple, Serialize_tuple}; +use fvm_ipld_encoding::{to_vec, RawBytes}; +use fvm_shared::address::Address; +use fvm_shared::error::{ErrorNumber, ExitCode}; use fvm_shared::receipt::Receipt; use fvm_shared::{clock::ChainEpoch, econ::TokenAmount, message::Message, version::NetworkVersion}; use lazy_static::lazy_static; use log::info; +use safer_ffi::prelude::*; use super::blockstore::{CgoBlockstore, FakeBlockstore, OverlayBlockstore}; use super::externs::CgoExterns; use super::types::*; -use crate::util::api::init_log; -use fvm_ipld_encoding::{to_vec, RawBytes}; -use fvm_shared::address::Address; -use fvm_shared::error::{ErrorNumber, ExitCode}; +use crate::destructor; +use crate::util::types::{catch_panic_response, catch_panic_response_no_default, Result}; pub type CgoExecutor = DefaultExecutor< DefaultKernel, CgoExterns>>>, @@ -38,293 +39,196 @@ lazy_static! { /// for some types is due to the generated bindings not liking the /// 32bit types as incoming args /// -#[no_mangle] -#[cfg(not(target_os = "windows"))] -pub unsafe extern "C" fn fil_create_fvm_machine( - fvm_version: fil_FvmRegisteredVersion, +#[ffi_export] +fn create_fvm_machine( + fvm_version: FvmRegisteredVersion, chain_epoch: u64, base_fee_hi: u64, base_fee_lo: u64, base_circ_supply_hi: u64, base_circ_supply_lo: u64, network_version: u64, - state_root_ptr: *const u8, - state_root_len: libc::size_t, - manifest_cid_ptr: *const u8, - manifest_cid_len: libc::size_t, + state_root: c_slice::Ref, + manifest_cid: c_slice::Ref, tracing: bool, blockstore_id: u64, externs_id: u64, -) -> *mut fil_CreateFvmMachineResponse { +) -> repr_c::Box> { use fvm::machine::NetworkConfig; - - catch_panic_response(|| { - init_log(); - - info!("fil_create_fvm_machine: start"); - - let mut response = fil_CreateFvmMachineResponse::default(); - match fvm_version { - fil_FvmRegisteredVersion::V1 => info!("using FVM V1"), - //_ => panic!("unsupported FVM Registered Version") - } - - let chain_epoch = chain_epoch as ChainEpoch; - - let base_circ_supply = TokenAmount::from( - ((base_circ_supply_hi as u128) << u64::BITS) | base_circ_supply_lo as u128, - ); - let base_fee = - TokenAmount::from(((base_fee_hi as u128) << u64::BITS) | base_fee_lo as u128); - - let network_version = match NetworkVersion::try_from(network_version as u32) { - Ok(x) => x, - Err(_) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = - rust_str_to_c_str(format!("unsupported network version: {}", network_version)); - return raw_ptr(response); + unsafe { + catch_panic_response_no_default("create_fvm_machine", || { + match fvm_version { + FvmRegisteredVersion::V1 => info!("using FVM V1"), + //_ => panic!("unsupported FVM Registered Version") } - }; - let state_root_bytes: Vec = - std::slice::from_raw_parts(state_root_ptr, state_root_len).to_vec(); - let state_root = match Cid::try_from(state_root_bytes) { - Ok(x) => x, - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("invalid state root: {}", err)); - return raw_ptr(response); - } - }; - let manifest_cid = if manifest_cid_len > 0 { - let manifest_cid_bytes: Vec = - std::slice::from_raw_parts(manifest_cid_ptr, manifest_cid_len).to_vec(); - match Cid::try_from(manifest_cid_bytes) { - Ok(x) => Some(x), - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("invalid manifest: {}", err)); - return raw_ptr(response); + let chain_epoch = chain_epoch as ChainEpoch; + + let base_circ_supply = TokenAmount::from( + ((base_circ_supply_hi as u128) << u64::BITS) | base_circ_supply_lo as u128, + ); + let base_fee = + TokenAmount::from(((base_fee_hi as u128) << u64::BITS) | base_fee_lo as u128); + + let network_version = NetworkVersion::try_from(network_version as u32) + .map_err(|_| anyhow!("unsupported network version: {}", network_version))?; + let state_root = Cid::try_from(&state_root[..]) + .map_err(|err| anyhow!("invalid state root: {}", err))?; + + let manifest_cid = if !manifest_cid.is_empty() { + let cid = Cid::try_from(&manifest_cid[..]) + .map_err(|err| anyhow!("invalid manifest: {}", err))?; + Some(cid) + } else { + // handle cid.Undef for no manifest + // this can mean two things: + // - for pre nv16, use the builtin bundles + // - for nv16 or higher, it means we have already migrated state for system + // actor and we can pass None to the machine constructor to fish it from state. + // The presence of the manifest cid argument allows us to test with new bundles + // with minimum friction. + None + }; + + let blockstore = FakeBlockstore::new(CgoBlockstore::new(blockstore_id)); + + let mut network_config = NetworkConfig::new(network_version); + match import_actors(&blockstore, manifest_cid, network_version) { + Ok(Some(manifest)) => { + network_config.override_actors(manifest); } + Ok(None) => {} + Err(err) => bail!("couldn't load builtin actors: {}", err), } - } else { - // handle cid.Undef for no manifest - // this can mean two things: - // - for pre nv16, use the builtin bundles - // - for nv16 or higher, it means we have already migrated state for system - // actor and we can pass None to the machine constructor to fish it from state. - // The presence of the manifest cid argument allows us to test with new bundles - // with minimum friction. - None - }; - - let blockstore = FakeBlockstore::new(CgoBlockstore::new(blockstore_id)); - - let mut network_config = NetworkConfig::new(network_version); - match import_actors(&blockstore, manifest_cid, network_version) { - Ok(Some(manifest)) => { - network_config.override_actors(manifest); - } - Ok(None) => {} - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = - rust_str_to_c_str(format!("couldn't load builtin actors: {}", err)); - return raw_ptr(response); - } - } + let mut machine_context = network_config.for_epoch(chain_epoch, state_root); - let mut machine_context = network_config.for_epoch(chain_epoch, state_root); + machine_context + .set_base_fee(base_fee) + .set_circulating_supply(base_circ_supply); - machine_context - .set_base_fee(base_fee) - .set_circulating_supply(base_circ_supply); - - if tracing { - machine_context.enable_tracing(); - } - let blockstore = blockstore.finish(); - - let externs = CgoExterns::new(externs_id); - let machine = - fvm::machine::DefaultMachine::new(&ENGINE, &machine_context, blockstore, externs); - match machine { - Ok(machine) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.executor = Box::into_raw(Box::new(Mutex::new(CgoExecutor::new(machine)))) - as *mut libc::c_void; + if tracing { + machine_context.enable_tracing(); } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = - rust_str_to_c_str(format!("failed to create machine: {}", err)); - return raw_ptr(response); - } - } + let blockstore = blockstore.finish(); - info!("fil_create_fvm_machine: finish"); + let externs = CgoExterns::new(externs_id); - raw_ptr(response) - }) -} + let machine = + fvm::machine::DefaultMachine::new(&ENGINE, &machine_context, blockstore, externs) + .map_err(|err| anyhow!("failed to create machine: {}", err))?; -#[no_mangle] -pub unsafe extern "C" fn fil_drop_fvm_machine(executor: *mut libc::c_void) { - let _ = Box::from_raw(executor as *mut Mutex); + Ok(Some(repr_c::Box::new(InnerFvmMachine { + machine: Some(Mutex::new(CgoExecutor::new(machine))), + }))) + }) + } } -#[no_mangle] -pub unsafe extern "C" fn fil_fvm_machine_execute_message( - executor: *mut libc::c_void, - message_ptr: *const u8, - message_len: libc::size_t, +#[ffi_export] +fn fvm_machine_execute_message( + executor: &'_ InnerFvmMachine, + message: c_slice::Ref, chain_len: u64, apply_kind: u64, /* 0: Explicit, _: Implicit */ -) -> *mut fil_FvmMachineExecuteResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_fvm_machine_execute_message: start"); - - let mut response = fil_FvmMachineExecuteResponse::default(); - +) -> repr_c::Box> { + catch_panic_response("fvm_machine_execute_message", || { let apply_kind = if apply_kind == 0 { ApplyKind::Explicit } else { ApplyKind::Implicit }; - let message_bytes = std::slice::from_raw_parts(message_ptr, message_len); - let message: Message = match fvm_ipld_encoding::from_slice(message_bytes) { - Ok(x) => x, - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - return raw_ptr(response); - } - }; + let message: Message = fvm_ipld_encoding::from_slice(&message)?; - let mut executor = unsafe { &*(executor as *mut Mutex) } + let mut executor = executor + .machine + .as_ref() + .expect("missing executor") .lock() .unwrap(); - let apply_ret = match executor.execute_message(message, apply_kind, chain_len as usize) { - Ok(x) => x, - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - return raw_ptr(response); - } - }; + let apply_ret = executor.execute_message(message, apply_kind, chain_len as usize)?; - if !apply_ret.exec_trace.is_empty() { + let exec_trace = if !apply_ret.exec_trace.is_empty() { let mut trace_iter = apply_ret.exec_trace.into_iter(); - if let Ok(Ok(lotus_t_bytes)) = build_lotus_trace( + build_lotus_trace( &trace_iter .next() .expect("already checked trace for emptiness"), &mut trace_iter, ) - .map(|lotus_trace| to_vec(&lotus_trace).map(|v| v.into_boxed_slice())) - { - response.exec_trace_ptr = lotus_t_bytes.as_ptr(); - response.exec_trace_len = lotus_t_bytes.len(); - Box::leak(lotus_t_bytes); - } - } + .ok() + .and_then(|t| to_vec(&t).ok()) + .map(|trace| trace.into_boxed_slice().into()) + } else { + None + }; - if let Some(info) = apply_ret.failure_info { - let info_bytes = info.to_string().into_boxed_str().into_boxed_bytes(); - response.failure_info_ptr = info_bytes.as_ptr(); - response.failure_info_len = info_bytes.len(); - Box::leak(info_bytes); - } + let failure_info = apply_ret + .failure_info + .map(|info| info.to_string().into_boxed_str().into()); // TODO: use the non-bigint token amount everywhere in the FVM let penalty: u128 = apply_ret.penalty.try_into().unwrap(); let miner_tip: u128 = apply_ret.miner_tip.try_into().unwrap(); - // Only do this if the return data is non-empty. The empty vec pointer is non-null and not - // valid in go. - if !apply_ret.msg_receipt.return_data.is_empty() { - let return_bytes = Vec::from(apply_ret.msg_receipt.return_data).into_boxed_slice(); - response.return_ptr = return_bytes.as_ptr(); - response.return_len = return_bytes.len(); - Box::leak(return_bytes); - } - - // TODO: Do something with the backtrace. - response.status_code = FCPResponseStatus::FCPNoError; - response.exit_code = apply_ret.msg_receipt.exit_code.value() as u64; - response.gas_used = apply_ret.msg_receipt.gas_used as u64; - response.penalty_hi = (penalty >> u64::BITS) as u64; - response.penalty_lo = penalty as u64; - response.miner_tip_hi = (miner_tip >> u64::BITS) as u64; - response.miner_tip_lo = miner_tip as u64; + let Receipt { + exit_code, + return_data, + gas_used, + } = apply_ret.msg_receipt; - info!("fil_fvm_machine_execute_message: end"); + let return_val = if return_data.is_empty() { + None + } else { + let bytes: Vec = return_data.into(); + Some(bytes.into_boxed_slice().into()) + }; - raw_ptr(response) + // TODO: Do something with the backtrace. + Ok(FvmMachineExecuteResponse { + exit_code: exit_code.value() as u64, + return_val, + gas_used: gas_used as u64, + penalty_hi: (penalty >> u64::BITS) as u64, + penalty_lo: penalty as u64, + miner_tip_hi: (miner_tip >> u64::BITS) as u64, + miner_tip_lo: miner_tip as u64, + exec_trace, + failure_info, + }) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_fvm_machine_flush( - executor: *mut libc::c_void, -) -> *mut fil_FvmMachineFlushResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_fvm_machine_flush: start"); - - let mut executor = unsafe { &*(executor as *mut Mutex) } +#[ffi_export] +fn fvm_machine_flush(executor: &'_ InnerFvmMachine) -> repr_c::Box>> { + catch_panic_response("fvm_machine_flush", || { + let mut executor = executor + .machine + .as_ref() + .expect("missing executor") .lock() .unwrap(); - let mut response = fil_FvmMachineFlushResponse::default(); - match executor.flush() { - Ok(cid) => { - let bytes = cid.to_bytes().into_boxed_slice(); - response.state_root_ptr = bytes.as_ptr(); - response.state_root_len = bytes.len(); - Box::leak(bytes); - } - Err(e) => { - response.status_code = FCPResponseStatus::FCPReceiverError; - response.error_msg = rust_str_to_c_str(e.to_string()); - } - } - info!("fil_fvm_machine_flush: end"); + let cid = executor.flush()?; - raw_ptr(response) + Ok(cid.to_bytes().into_boxed_slice().into()) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_create_fvm_machine_response( - ptr: *mut fil_CreateFvmMachineResponse, -) { - let _ = Box::from_raw(ptr); -} +destructor!(drop_fvm_machine, InnerFvmMachine); +destructor!(destroy_create_fvm_machine_response, Result); -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_fvm_machine_execute_response( - ptr: *mut fil_FvmMachineExecuteResponse, -) { - let _ = Box::from_raw(ptr); -} +destructor!( + destroy_fvm_machine_execute_response, + Result +); -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_fvm_machine_flush_response( - ptr: *mut fil_FvmMachineFlushResponse, -) { - let _ = Box::from_raw(ptr); -} +destructor!(destroy_fvm_machine_flush_response, Result>); fn import_actors( blockstore: &impl Blockstore, manifest_cid: Option, network_version: NetworkVersion, -) -> Result, &'static str> { +) -> std::result::Result, &'static str> { if manifest_cid.is_some() { return Ok(manifest_cid); } diff --git a/rust/src/fvm/mod.rs b/rust/src/fvm/mod.rs index d511f996..95e66a87 100644 --- a/rust/src/fvm/mod.rs +++ b/rust/src/fvm/mod.rs @@ -1,8 +1,8 @@ -/// cbindgen:ignore mod blockstore; mod cgo; -/// cbindgen:ignore mod externs; pub mod machine; pub mod types; + +pub use cgo::FvmError; diff --git a/rust/src/fvm/types.rs b/rust/src/fvm/types.rs index 91bfcb58..0e36fd77 100644 --- a/rust/src/fvm/types.rs +++ b/rust/src/fvm/types.rs @@ -1,104 +1,36 @@ -use std::ptr; +use std::sync::Mutex; -use drop_struct_macro_derive::DropStructMacro; -use ffi_toolkit::{code_and_message_impl, free_c_str, CodeAndMessage, FCPResponseStatus}; +use safer_ffi::prelude::*; -use fvm_shared::error::ExitCode; +use super::machine::CgoExecutor; -#[repr(C)] +#[derive_ReprC] +#[repr(u8)] #[derive(Debug, Clone, Copy, PartialEq)] -pub enum fil_FvmRegisteredVersion { +pub enum FvmRegisteredVersion { V1, } -#[repr(C)] -pub struct fil_CreateFvmMachineResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub executor: *mut libc::c_void, -} - -impl Drop for fil_CreateFvmMachineResponse { - fn drop(&mut self) { - // We implement this manually because we don't want to drop the executor here. - unsafe { - free_c_str(self.error_msg as *mut libc::c_char); - } - } +#[derive_ReprC] +#[ReprC::opaque] +#[derive(Default)] +pub struct InnerFvmMachine { + pub(crate) machine: Option>, } -impl Default for fil_CreateFvmMachineResponse { - fn default() -> fil_CreateFvmMachineResponse { - fil_CreateFvmMachineResponse { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - executor: ptr::null_mut(), - } - } -} - -code_and_message_impl!(fil_CreateFvmMachineResponse); +pub type FvmMachine = Option>; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_FvmMachineExecuteResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, +#[derive(Default)] +pub struct FvmMachineExecuteResponse { pub exit_code: u64, - pub return_ptr: *const u8, - pub return_len: libc::size_t, + pub return_val: Option>, pub gas_used: u64, pub penalty_hi: u64, pub penalty_lo: u64, pub miner_tip_hi: u64, pub miner_tip_lo: u64, - pub exec_trace_ptr: *const u8, - pub exec_trace_len: libc::size_t, - pub failure_info_ptr: *const u8, - pub failure_info_len: libc::size_t, -} - -impl Default for fil_FvmMachineExecuteResponse { - fn default() -> fil_FvmMachineExecuteResponse { - fil_FvmMachineExecuteResponse { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - exit_code: ExitCode::OK.value() as u64, - return_ptr: ptr::null(), - return_len: 0, - gas_used: 0, - penalty_hi: 0, - penalty_lo: 0, - miner_tip_hi: 0, - miner_tip_lo: 0, - exec_trace_ptr: ptr::null(), - exec_trace_len: 0, - failure_info_ptr: ptr::null(), - failure_info_len: 0, - } - } + pub exec_trace: Option>, + pub failure_info: Option, } - -code_and_message_impl!(fil_FvmMachineExecuteResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_FvmMachineFlushResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub state_root_ptr: *const u8, - pub state_root_len: libc::size_t, -} - -impl Default for fil_FvmMachineFlushResponse { - fn default() -> fil_FvmMachineFlushResponse { - fil_FvmMachineFlushResponse { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - state_root_ptr: ptr::null(), - state_root_len: 0, - } - } -} - -code_and_message_impl!(fil_FvmMachineFlushResponse); diff --git a/rust/src/lib.rs b/rust/src/lib.rs index b4e189ce..7b8f3f19 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -6,3 +6,22 @@ pub mod bls; pub mod fvm; pub mod proofs; pub mod util; + +// Generates the headers. +// Run `HEADER_DIR= cargo test build_headers --features c-headers` to build +#[safer_ffi::cfg_headers] +#[test] +fn build_headers() -> std::io::Result<()> { + use std::env; + use std::path::Path; + + let header_dir = env::var("HEADER_DIR").expect("Missing \"HEADER_DIR\""); + let out_dir = Path::new(&header_dir); + let hdr_out = out_dir.join("filcrypto.h"); + + safer_ffi::headers::builder() + .to_file(&hdr_out)? + .generate()?; + + Ok(()) +} diff --git a/rust/src/proofs/api.rs b/rust/src/proofs/api.rs index 7771fdaa..faa0cc4d 100644 --- a/rust/src/proofs/api.rs +++ b/rust/src/proofs/api.rs @@ -1,836 +1,456 @@ -use ffi_toolkit::{ - c_str_to_pbuf, catch_panic_response, raw_ptr, rust_str_to_c_str, FCPResponseStatus, -}; -use filecoin_proofs_api::seal::{ - add_piece, aggregate_seal_commit_proofs, clear_cache, compute_comm_d, fauxrep, fauxrep2, - generate_piece_commitment, get_seal_inputs, seal_commit_phase1, seal_commit_phase2, - seal_pre_commit_phase1, seal_pre_commit_phase2, verify_aggregate_seal_commit_proofs, - verify_seal, write_and_preprocess, SealCommitPhase2Output, SealPreCommitPhase2Output, -}; -use filecoin_proofs_api::update::{ - empty_sector_update_decode_from, empty_sector_update_encode_into, - empty_sector_update_remove_encoded_data, generate_empty_sector_update_proof, - generate_empty_sector_update_proof_with_vanilla, generate_partition_proofs, - verify_empty_sector_update_proof, verify_partition_proofs, -}; -use filecoin_proofs_api::{ - PartitionProofBytes, PartitionSnarkProof, PieceInfo, PrivateReplicaInfo, RegisteredPoStProof, - RegisteredSealProof, SectorId, StorageProofsError, UnpaddedByteIndex, UnpaddedBytesAmount, -}; +use std::fs; use blstrs::Scalar as Fr; -use log::{error, info}; +use filecoin_proofs_api::seal; +use filecoin_proofs_api::{ + self as api, update, PieceInfo, SectorId, StorageProofsError, UnpaddedByteIndex, + UnpaddedBytesAmount, +}; use rayon::prelude::*; +use safer_ffi::prelude::*; -use std::mem; -use std::path::PathBuf; -use std::slice::from_raw_parts; - -use super::helpers::{ - c_to_rust_partition_proofs, c_to_rust_post_proofs, c_to_rust_vanilla_partition_proofs, - to_private_replica_info_map, -}; +use super::helpers::{to_private_replica_info_map, to_public_replica_info_map}; use super::types::*; -use crate::util::api::init_log; +use crate::destructor; +use crate::util::types::{ + as_path_buf, catch_panic_response, catch_panic_response_raw, FCPResponseStatus, +}; + +#[ffi_export] +fn alloc_boxed_slice(size: usize) -> c_slice::Box { + vec![0u8; size].into_boxed_slice().into() +} + +#[ffi_export] +fn destroy_boxed_slice(ptr: c_slice::Box) { + drop(ptr); +} // A byte serialized representation of a vanilla proof. -pub type VanillaProof = Vec; +pub type ApiVanillaProof = Vec; /// TODO: document -/// -#[no_mangle] -#[cfg(not(target_os = "windows"))] -pub unsafe extern "C" fn fil_write_with_alignment( - registered_proof: fil_RegisteredSealProof, +#[ffi_export] +unsafe fn write_with_alignment( + registered_proof: RegisteredSealProof, src_fd: libc::c_int, src_size: u64, dst_fd: libc::c_int, - existing_piece_sizes_ptr: *const u64, - existing_piece_sizes_len: libc::size_t, -) -> *mut fil_WriteWithAlignmentResponse { - catch_panic_response(|| { - init_log(); - - info!("write_with_alignment: start"); - - let mut response = fil_WriteWithAlignmentResponse::default(); - - let slice: &[u64] = - std::slice::from_raw_parts(existing_piece_sizes_ptr, existing_piece_sizes_len); - let piece_sizes: Vec = slice - .to_vec() + existing_piece_sizes: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("write_with_alignment", || { + let piece_sizes: Vec = existing_piece_sizes .iter() - .map(|n| UnpaddedBytesAmount(*n)) + .copied() + .map(UnpaddedBytesAmount) .collect(); let n = UnpaddedBytesAmount(src_size); - match add_piece( + let (info, written) = seal::add_piece( registered_proof.into(), FileDescriptorRef::new(src_fd), FileDescriptorRef::new(dst_fd), n, &piece_sizes, - ) { - Ok((info, written)) => { - response.comm_p = info.commitment; - response.left_alignment_unpadded = (written - n).into(); - response.status_code = FCPResponseStatus::FCPNoError; - response.total_write_unpadded = written.into(); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } + )?; - info!("write_with_alignment: finish"); - - raw_ptr(response) + Ok(WriteWithAlignment { + comm_p: info.commitment, + left_alignment_unpadded: (written - n).into(), + total_write_unpadded: written.into(), + }) }) } /// TODO: document -/// -#[no_mangle] -#[cfg(not(target_os = "windows"))] -pub unsafe extern "C" fn fil_write_without_alignment( - registered_proof: fil_RegisteredSealProof, +#[ffi_export] +unsafe fn write_without_alignment( + registered_proof: RegisteredSealProof, src_fd: libc::c_int, src_size: u64, dst_fd: libc::c_int, -) -> *mut fil_WriteWithoutAlignmentResponse { - catch_panic_response(|| { - init_log(); - - info!("write_without_alignment: start"); - - let mut response = fil_WriteWithoutAlignmentResponse::default(); - - match write_and_preprocess( +) -> repr_c::Box { + catch_panic_response("write_without_alignment", || { + let (info, written) = seal::write_and_preprocess( registered_proof.into(), FileDescriptorRef::new(src_fd), FileDescriptorRef::new(dst_fd), UnpaddedBytesAmount(src_size), - ) { - Ok((info, written)) => { - response.comm_p = info.commitment; - response.status_code = FCPResponseStatus::FCPNoError; - response.total_write_unpadded = written.into(); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } + )?; - info!("write_without_alignment: finish"); - - raw_ptr(response) + Ok(WriteWithoutAlignment { + comm_p: info.commitment, + total_write_unpadded: written.into(), + }) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_fauxrep( - registered_proof: fil_RegisteredSealProof, - cache_dir_path: *const libc::c_char, - sealed_sector_path: *const libc::c_char, -) -> *mut fil_FauxRepResponse { - catch_panic_response(|| { - init_log(); - - info!("fauxrep: start"); - - let mut response: fil_FauxRepResponse = Default::default(); - - let result = fauxrep( +#[ffi_export] +fn fauxrep( + registered_proof: RegisteredSealProof, + cache_dir_path: c_slice::Ref, + sealed_sector_path: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("fauxrep", || { + let res = seal::fauxrep( registered_proof.into(), - c_str_to_pbuf(cache_dir_path), - c_str_to_pbuf(sealed_sector_path), - ); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.commitment = output; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fauxrep: finish"); - - raw_ptr(response) + as_path_buf(&cache_dir_path)?, + as_path_buf(&sealed_sector_path)?, + )?; + Ok(res) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_fauxrep2( - registered_proof: fil_RegisteredSealProof, - cache_dir_path: *const libc::c_char, - existing_p_aux_path: *const libc::c_char, -) -> *mut fil_FauxRepResponse { - catch_panic_response(|| { - init_log(); - - info!("fauxrep2: start"); - - let mut response: fil_FauxRepResponse = Default::default(); - - let result = fauxrep2( +#[ffi_export] +fn fauxrep2( + registered_proof: RegisteredSealProof, + cache_dir_path: c_slice::Ref, + existing_p_aux_path: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("fauxrep2", || { + let result = seal::fauxrep2( registered_proof.into(), - c_str_to_pbuf(cache_dir_path), - c_str_to_pbuf(existing_p_aux_path), - ); + as_path_buf(&cache_dir_path)?, + as_path_buf(&existing_p_aux_path)?, + )?; - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.commitment = output; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fauxrep2: finish"); - - raw_ptr(response) + Ok(result) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_seal_pre_commit_phase1( - registered_proof: fil_RegisteredSealProof, - cache_dir_path: *const libc::c_char, - staged_sector_path: *const libc::c_char, - sealed_sector_path: *const libc::c_char, +#[ffi_export] +fn seal_pre_commit_phase1( + registered_proof: RegisteredSealProof, + cache_dir_path: c_slice::Ref, + staged_sector_path: c_slice::Ref, + sealed_sector_path: c_slice::Ref, sector_id: u64, - prover_id: fil_32ByteArray, - ticket: fil_32ByteArray, - pieces_ptr: *const fil_PublicPieceInfo, - pieces_len: libc::size_t, -) -> *mut fil_SealPreCommitPhase1Response { - catch_panic_response(|| { - init_log(); - - info!("seal_pre_commit_phase1: start"); - - let slice: &[fil_PublicPieceInfo] = std::slice::from_raw_parts(pieces_ptr, pieces_len); - let public_pieces: Vec = - slice.to_vec().iter().cloned().map(Into::into).collect(); - - let mut response: fil_SealPreCommitPhase1Response = Default::default(); - - let result = seal_pre_commit_phase1( + prover_id: &[u8; 32], + ticket: &[u8; 32], + pieces: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("seal_pre_commit_phase1", || { + let public_pieces: Vec = pieces.iter().map(Into::into).collect(); + + let result = seal::seal_pre_commit_phase1( registered_proof.into(), - c_str_to_pbuf(cache_dir_path), - c_str_to_pbuf(staged_sector_path), - c_str_to_pbuf(sealed_sector_path), - prover_id.inner, + as_path_buf(&cache_dir_path)?, + as_path_buf(&staged_sector_path)?, + as_path_buf(&sealed_sector_path)?, + *prover_id, SectorId::from(sector_id), - ticket.inner, + *ticket, &public_pieces, - ) - .and_then(|output| serde_json::to_vec(&output).map_err(Into::into)); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.seal_pre_commit_phase1_output_ptr = output.as_ptr(); - response.seal_pre_commit_phase1_output_len = output.len(); - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } + )?; + let result = serde_json::to_vec(&result)?; - info!("seal_pre_commit_phase1: finish"); - - raw_ptr(response) + Ok(result.into_boxed_slice().into()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_seal_pre_commit_phase2( - seal_pre_commit_phase1_output_ptr: *const u8, - seal_pre_commit_phase1_output_len: libc::size_t, - cache_dir_path: *const libc::c_char, - sealed_sector_path: *const libc::c_char, -) -> *mut fil_SealPreCommitPhase2Response { - catch_panic_response(|| { - init_log(); - - info!("seal_pre_commit_phase2: start"); - - let mut response: fil_SealPreCommitPhase2Response = Default::default(); - - let phase_1_output = serde_json::from_slice(from_raw_parts( - seal_pre_commit_phase1_output_ptr, - seal_pre_commit_phase1_output_len, - )) - .map_err(Into::into); - - let result = phase_1_output.and_then(|o| { - seal_pre_commit_phase2::( - o, - c_str_to_pbuf(cache_dir_path), - c_str_to_pbuf(sealed_sector_path), - ) - }); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.comm_r = output.comm_r; - response.comm_d = output.comm_d; - response.registered_proof = output.registered_proof.into(); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("seal_pre_commit_phase2: finish"); - - raw_ptr(response) +#[ffi_export] +fn seal_pre_commit_phase2( + seal_pre_commit_phase1_output: c_slice::Ref, + cache_dir_path: c_slice::Ref, + sealed_sector_path: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("seal_pre_commit_phase2", || { + let phase_1_output = serde_json::from_slice(&seal_pre_commit_phase1_output)?; + + let output = seal::seal_pre_commit_phase2( + phase_1_output, + as_path_buf(&cache_dir_path)?, + as_path_buf(&sealed_sector_path)?, + )?; + + Ok(SealPreCommitPhase2 { + comm_r: output.comm_r, + comm_d: output.comm_d, + registered_proof: output.registered_proof.into(), + }) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_seal_commit_phase1( - registered_proof: fil_RegisteredSealProof, - comm_r: fil_32ByteArray, - comm_d: fil_32ByteArray, - cache_dir_path: *const libc::c_char, - replica_path: *const libc::c_char, +#[ffi_export] +fn seal_commit_phase1( + registered_proof: RegisteredSealProof, + comm_r: &[u8; 32], + comm_d: &[u8; 32], + cache_dir_path: c_slice::Ref, + replica_path: c_slice::Ref, sector_id: u64, - prover_id: fil_32ByteArray, - ticket: fil_32ByteArray, - seed: fil_32ByteArray, - pieces_ptr: *const fil_PublicPieceInfo, - pieces_len: libc::size_t, -) -> *mut fil_SealCommitPhase1Response { - catch_panic_response(|| { - init_log(); - - info!("seal_commit_phase1: start"); - - let mut response = fil_SealCommitPhase1Response::default(); - - let spcp2o = SealPreCommitPhase2Output { + prover_id: &[u8; 32], + ticket: &[u8; 32], + seed: &[u8; 32], + pieces: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("seal_commit_phase1", || { + let spcp2o = seal::SealPreCommitPhase2Output { registered_proof: registered_proof.into(), - comm_r: comm_r.inner, - comm_d: comm_d.inner, + comm_r: *comm_r, + comm_d: *comm_d, }; - let slice: &[fil_PublicPieceInfo] = std::slice::from_raw_parts(pieces_ptr, pieces_len); - let public_pieces: Vec = - slice.to_vec().iter().cloned().map(Into::into).collect(); + let public_pieces: Vec = pieces.iter().map(Into::into).collect(); - let result = seal_commit_phase1( - c_str_to_pbuf(cache_dir_path), - c_str_to_pbuf(replica_path), - prover_id.inner, + let output = seal::seal_commit_phase1( + as_path_buf(&cache_dir_path)?, + as_path_buf(&replica_path)?, + *prover_id, SectorId::from(sector_id), - ticket.inner, - seed.inner, + *ticket, + *seed, spcp2o, &public_pieces, - ); - - match result.and_then(|output| serde_json::to_vec(&output).map_err(Into::into)) { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.seal_commit_phase1_output_ptr = output.as_ptr(); - response.seal_commit_phase1_output_len = output.len(); - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("seal_commit_phase1: finish"); + )?; - raw_ptr(response) + let result = serde_json::to_vec(&output)?; + Ok(result.into_boxed_slice().into()) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_seal_commit_phase2( - seal_commit_phase1_output_ptr: *const u8, - seal_commit_phase1_output_len: libc::size_t, +#[ffi_export] +fn seal_commit_phase2( + seal_commit_phase1_output: c_slice::Ref, sector_id: u64, - prover_id: fil_32ByteArray, -) -> *mut fil_SealCommitPhase2Response { - catch_panic_response(|| { - init_log(); + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("seal_commit_phase2", || { + let scp1o = serde_json::from_slice(&seal_commit_phase1_output)?; + let result = seal::seal_commit_phase2(scp1o, *prover_id, SectorId::from(sector_id))?; - info!("seal_commit_phase2: start"); - - let mut response = fil_SealCommitPhase2Response::default(); - - let scp1o = serde_json::from_slice(from_raw_parts( - seal_commit_phase1_output_ptr, - seal_commit_phase1_output_len, - )) - .map_err(Into::into); - - let result = - scp1o.and_then(|o| seal_commit_phase2(o, prover_id.inner, SectorId::from(sector_id))); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.proof_ptr = output.proof.as_ptr(); - response.proof_len = output.proof.len(); - mem::forget(output.proof); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("seal_commit_phase2: finish"); - - raw_ptr(response) + Ok(result.proof.into_boxed_slice().into()) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_aggregate_seal_proofs( - registered_proof: fil_RegisteredSealProof, - registered_aggregation: fil_RegisteredAggregationProof, - comm_rs_ptr: *const fil_32ByteArray, - comm_rs_len: libc::size_t, - seeds_ptr: *const fil_32ByteArray, - seeds_len: libc::size_t, - seal_commit_responses_ptr: *const fil_SealCommitPhase2Response, - seal_commit_responses_len: libc::size_t, -) -> *mut fil_AggregateProof { - catch_panic_response(|| { - init_log(); - info!("aggregate_seal_proofs: start"); - - let responses: &[fil_SealCommitPhase2Response] = - std::slice::from_raw_parts(seal_commit_responses_ptr, seal_commit_responses_len); - let outputs: Vec = responses.iter().map(|x| x.into()).collect(); - - let raw_comm_rs: &[fil_32ByteArray] = std::slice::from_raw_parts(comm_rs_ptr, comm_rs_len); - let comm_rs: Vec<[u8; 32]> = raw_comm_rs.iter().map(|x| x.inner).collect(); - - let raw_seeds: &[fil_32ByteArray] = std::slice::from_raw_parts(seeds_ptr, seeds_len); - let seeds: Vec<[u8; 32]> = raw_seeds.iter().map(|x| x.inner).collect(); - - let mut response = fil_AggregateProof::default(); - - let result = aggregate_seal_commit_proofs( +#[ffi_export] +fn aggregate_seal_proofs( + registered_proof: RegisteredSealProof, + registered_aggregation: RegisteredAggregationProof, + comm_rs: c_slice::Ref<[u8; 32]>, + seeds: c_slice::Ref<[u8; 32]>, + seal_commit_responses: c_slice::Ref>, +) -> repr_c::Box { + catch_panic_response("aggregate_seal_proofs", || { + let outputs: Vec = seal_commit_responses + .iter() + .map(|p| seal::SealCommitPhase2Output { proof: p.to_vec() }) + .collect(); + + let result = seal::aggregate_seal_commit_proofs( registered_proof.into(), registered_aggregation.into(), &comm_rs, &seeds, &outputs, - ); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.proof_ptr = output.as_ptr(); - response.proof_len = output.len(); - - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } + )?; - info!("aggregate_seal_proofs: finish"); - - raw_ptr(response) + Ok(result.into_boxed_slice().into()) }) } /// Retrieves the seal inputs based on the provided input, used for aggregation verification. -/// -#[no_mangle] -pub fn convert_aggregation_inputs( - registered_proof: fil_RegisteredSealProof, - prover_id: fil_32ByteArray, - input: &fil_AggregationInputs, +fn convert_aggregation_inputs( + registered_proof: RegisteredSealProof, + prover_id: &[u8; 32], + input: &AggregationInputs, ) -> anyhow::Result>> { - get_seal_inputs( + seal::get_seal_inputs( registered_proof.into(), - input.comm_r.inner, - input.comm_d.inner, - prover_id.inner, + input.comm_r, + input.comm_d, + *prover_id, SectorId::from(input.sector_id), - input.ticket.inner, - input.seed.inner, + input.ticket, + input.seed, ) } /// Verifies the output of an aggregated seal. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_verify_aggregate_seal_proof( - registered_proof: fil_RegisteredSealProof, - registered_aggregation: fil_RegisteredAggregationProof, - prover_id: fil_32ByteArray, - proof_ptr: *const u8, - proof_len: libc::size_t, - commit_inputs_ptr: *mut fil_AggregationInputs, - commit_inputs_len: libc::size_t, -) -> *mut fil_VerifyAggregateSealProofResponse { - catch_panic_response(|| { - init_log(); - - info!("verify_aggregate_seal_proof: start"); - - let commit_inputs: &[fil_AggregationInputs] = - std::slice::from_raw_parts(commit_inputs_ptr, commit_inputs_len); - - let inputs: anyhow::Result>> = commit_inputs +#[ffi_export] +fn verify_aggregate_seal_proof( + registered_proof: RegisteredSealProof, + registered_aggregation: RegisteredAggregationProof, + prover_id: &[u8; 32], + proof: c_slice::Ref, + commit_inputs: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("verify_aggregate_seal_proof", || { + let inputs: Vec> = commit_inputs .par_iter() .map(|input| convert_aggregation_inputs(registered_proof, prover_id, input)) .try_reduce(Vec::new, |mut acc, current| { acc.extend(current); Ok(acc) - }); + })?; - let mut response = fil_VerifyAggregateSealProofResponse::default(); + let proof_bytes: Vec = proof.to_vec(); - match inputs { - Ok(inputs) => { - let proof_bytes: Vec = - std::slice::from_raw_parts(proof_ptr, proof_len).to_vec(); - let comm_rs: Vec<[u8; 32]> = commit_inputs - .iter() - .map(|input| input.comm_r.inner) - .collect(); - let seeds: Vec<[u8; 32]> = - commit_inputs.iter().map(|input| input.seed.inner).collect(); - - let result = verify_aggregate_seal_commit_proofs( - registered_proof.into(), - registered_aggregation.into(), - proof_bytes, - &comm_rs, - &seeds, - inputs, - ); - - match result { - Ok(true) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = true; - } - Ok(false) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = false; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - response.is_valid = false; - } - } - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - response.is_valid = false; - } - } + let comm_rs: Vec<[u8; 32]> = commit_inputs.iter().map(|input| input.comm_r).collect(); + let seeds: Vec<[u8; 32]> = commit_inputs.iter().map(|input| input.seed).collect(); - info!("verify_aggregate_seal_proof: finish"); + let result = seal::verify_aggregate_seal_commit_proofs( + registered_proof.into(), + registered_aggregation.into(), + proof_bytes, + &comm_rs, + &seeds, + inputs, + )?; - raw_ptr(response) + Ok(result) }) } /// TODO: document -#[no_mangle] -pub unsafe extern "C" fn fil_unseal_range( - registered_proof: fil_RegisteredSealProof, - cache_dir_path: *const libc::c_char, +#[ffi_export] +unsafe fn unseal_range( + registered_proof: RegisteredSealProof, + cache_dir_path: c_slice::Ref, sealed_sector_fd_raw: libc::c_int, unseal_output_fd_raw: libc::c_int, sector_id: u64, - prover_id: fil_32ByteArray, - ticket: fil_32ByteArray, - comm_d: fil_32ByteArray, + prover_id: &[u8; 32], + ticket: &[u8; 32], + comm_d: &[u8; 32], unpadded_byte_index: u64, unpadded_bytes_amount: u64, -) -> *mut fil_UnsealRangeResponse { - catch_panic_response(|| { - init_log(); - - info!("unseal_range: start"); - +) -> repr_c::Box { + catch_panic_response("unseal_range", || { use filepath::FilePath; use std::os::unix::io::{FromRawFd, IntoRawFd}; - let sealed_sector = std::fs::File::from_raw_fd(sealed_sector_fd_raw); - let mut unseal_output = std::fs::File::from_raw_fd(unseal_output_fd_raw); + let sealed_sector = fs::File::from_raw_fd(sealed_sector_fd_raw); + let mut unseal_output = fs::File::from_raw_fd(unseal_output_fd_raw); - let result = filecoin_proofs_api::seal::get_unsealed_range_mapped( + filecoin_proofs_api::seal::get_unsealed_range_mapped( registered_proof.into(), - c_str_to_pbuf(cache_dir_path), + as_path_buf(&cache_dir_path)?, sealed_sector.path().unwrap(), &mut unseal_output, - prover_id.inner, + *prover_id, SectorId::from(sector_id), - comm_d.inner, - ticket.inner, + *comm_d, + *ticket, UnpaddedByteIndex(unpadded_byte_index), UnpaddedBytesAmount(unpadded_bytes_amount), - ); + )?; // keep all file descriptors alive until unseal_range returns let _ = sealed_sector.into_raw_fd(); let _ = unseal_output.into_raw_fd(); - let mut response = fil_UnsealRangeResponse::default(); - - match result { - Ok(_) => { - response.status_code = FCPResponseStatus::FCPNoError; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; - - info!("unseal_range: finish"); - - raw_ptr(response) + Ok(()) }) } /// Verifies the output of seal. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_verify_seal( - registered_proof: fil_RegisteredSealProof, - comm_r: fil_32ByteArray, - comm_d: fil_32ByteArray, - prover_id: fil_32ByteArray, - ticket: fil_32ByteArray, - seed: fil_32ByteArray, +#[ffi_export] +fn verify_seal( + registered_proof: RegisteredSealProof, + comm_r: &[u8; 32], + comm_d: &[u8; 32], + prover_id: &[u8; 32], + ticket: &[u8; 32], + seed: &[u8; 32], sector_id: u64, - proof_ptr: *const u8, - proof_len: libc::size_t, -) -> *mut super::types::fil_VerifySealResponse { - catch_panic_response(|| { - init_log(); - - info!("verify_seal: start"); + proof: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("verify_seal", || { + let proof_bytes: Vec = proof.to_vec(); - let proof_bytes: Vec = std::slice::from_raw_parts(proof_ptr, proof_len).to_vec(); - - let result = verify_seal( + let result = seal::verify_seal( registered_proof.into(), - comm_r.inner, - comm_d.inner, - prover_id.inner, + *comm_r, + *comm_d, + *prover_id, SectorId::from(sector_id), - ticket.inner, - seed.inner, + *ticket, + *seed, &proof_bytes, - ); - - let mut response = fil_VerifySealResponse::default(); - - match result { - Ok(true) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = true; - } - Ok(false) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = false; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; - - info!("verify_seal: finish"); + )?; - raw_ptr(response) + Ok(result) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_winning_post_sector_challenge( - registered_proof: fil_RegisteredPoStProof, - randomness: fil_32ByteArray, +#[ffi_export] +fn generate_winning_post_sector_challenge( + registered_proof: RegisteredPoStProof, + randomness: &[u8; 32], sector_set_len: u64, - prover_id: fil_32ByteArray, -) -> *mut fil_GenerateWinningPoStSectorChallenge { - catch_panic_response(|| { - init_log(); - - info!("generate_winning_post_sector_challenge: start"); - - let mut response = fil_GenerateWinningPoStSectorChallenge::default(); - + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("generate_winning_post_sector_challenge", || { let result = filecoin_proofs_api::post::generate_winning_post_sector_challenge( registered_proof.into(), - &randomness.inner, + randomness, sector_set_len, - prover_id.inner, - ); - - match result { - Ok(output) => { - let mapped: Vec = output.into_iter().map(u64::from).collect(); - - response.status_code = FCPResponseStatus::FCPNoError; - response.ids_ptr = mapped.as_ptr(); - response.ids_len = mapped.len(); - - mem::forget(mapped); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("generate_winning_post_sector_challenge: finish"); - - raw_ptr(response) + *prover_id, + )?; + + Ok(result + .into_iter() + .map(u64::from) + .collect::>() + .into_boxed_slice() + .into()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_fallback_sector_challenges( - registered_proof: fil_RegisteredPoStProof, - randomness: fil_32ByteArray, - sector_ids_ptr: *const u64, - sector_ids_len: libc::size_t, - prover_id: fil_32ByteArray, -) -> *mut fil_GenerateFallbackSectorChallengesResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_fallback_sector_challenges: start"); - - let slice: &[u64] = std::slice::from_raw_parts(sector_ids_ptr, sector_ids_len); - let pub_sectors: Vec = slice.to_vec().iter().cloned().map(Into::into).collect(); - - let result = filecoin_proofs_api::post::generate_fallback_sector_challenges( +#[ffi_export] +fn generate_fallback_sector_challenges( + registered_proof: RegisteredPoStProof, + randomness: &[u8; 32], + sector_ids: c_slice::Ref, + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("generate_fallback_sector_challenges", || { + let pub_sectors: Vec = sector_ids.iter().copied().map(Into::into).collect(); + + let output = filecoin_proofs_api::post::generate_fallback_sector_challenges( registered_proof.into(), - &randomness.inner, + randomness, &pub_sectors, - prover_id.inner, - ); - - let mut response = fil_GenerateFallbackSectorChallengesResponse::default(); + *prover_id, + )?; - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - - let sector_ids: Vec = output - .clone() - .into_iter() - .map(|(id, _challenges)| u64::from(id)) - .collect(); - let mut challenges_stride = 0; - let mut challenges_stride_mismatch = false; - let challenges: Vec = output - .into_iter() - .flat_map(|(_id, challenges)| { - if challenges_stride == 0 { - challenges_stride = challenges.len(); - } - - if !challenges_stride_mismatch && challenges_stride != challenges.len() { - error!( - "All challenge strides must be equal: {} != {}", - challenges_stride, - challenges.len() - ); - challenges_stride_mismatch = true; - } - - challenges - }) - .collect(); - - if challenges_stride_mismatch { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str("Challenge stride mismatch".to_string()); - } else { - response.status_code = FCPResponseStatus::FCPNoError; - response.ids_ptr = sector_ids.as_ptr(); - response.ids_len = sector_ids.len(); - response.challenges_ptr = challenges.as_ptr(); - response.challenges_len = challenges.len(); - response.challenges_stride = challenges_stride; - - mem::forget(sector_ids); - mem::forget(challenges); - } - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; + let sector_ids: Vec = output + .clone() + .into_iter() + .map(|(id, _)| u64::from(id)) + .collect(); - info!("generate_fallback_sector_challenges: finish"); + let challenges: Vec> = output + .into_iter() + .map(|(_id, challenges)| challenges.into_boxed_slice().into()) + .collect(); - raw_ptr(response) + Ok(GenerateFallbackSectorChallenges { + ids: sector_ids.into_boxed_slice().into(), + challenges: challenges.into_boxed_slice().into(), + }) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_single_vanilla_proof( - replica: fil_PrivateReplicaInfo, - challenges_ptr: *const u64, - challenges_len: libc::size_t, -) -> *mut fil_GenerateSingleVanillaProofResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_single_vanilla_proof: start"); - - let challenges: Vec = - std::slice::from_raw_parts(challenges_ptr, challenges_len).to_vec(); - +#[ffi_export] +fn generate_single_vanilla_proof( + replica: PrivateReplicaInfo, + challenges: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("generate_single_vanilla_proof", || { let sector_id = SectorId::from(replica.sector_id); - let cache_dir_path = c_str_to_pbuf(replica.cache_dir_path); - let replica_path = c_str_to_pbuf(replica.replica_path); + let cache_dir_path = as_path_buf(&replica.cache_dir_path)?; + let replica_path = as_path_buf(&replica.replica_path)?; - let replica_v1 = PrivateReplicaInfo::new( + let replica_v1 = api::PrivateReplicaInfo::new( replica.registered_proof.into(), replica.comm_r, cache_dir_path, @@ -841,264 +461,128 @@ pub unsafe extern "C" fn fil_generate_single_vanilla_proof( replica.registered_proof.into(), sector_id, &replica_v1, - &challenges, - ); - - let mut response = fil_GenerateSingleVanillaProofResponse::default(); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.vanilla_proof.proof_len = output.len(); - response.vanilla_proof.proof_ptr = output.as_ptr(); - - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; - - info!("generate_single_vanilla_proof: finish"); - - raw_ptr(response) + &*challenges, + )?; + Ok(result.into_boxed_slice().into()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_winning_post_with_vanilla( - registered_proof: fil_RegisteredPoStProof, - randomness: fil_32ByteArray, - prover_id: fil_32ByteArray, - vanilla_proofs_ptr: *const fil_VanillaProof, - vanilla_proofs_len: libc::size_t, -) -> *mut fil_GenerateWinningPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_winning_post_with_vanilla: start"); - - let proofs: &[fil_VanillaProof] = - std::slice::from_raw_parts(vanilla_proofs_ptr, vanilla_proofs_len); - let vanilla_proofs: Vec = proofs +#[ffi_export] +fn generate_winning_post_with_vanilla( + registered_proof: RegisteredPoStProof, + randomness: &[u8; 32], + prover_id: &[u8; 32], + vanilla_proofs: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("generate_winning_post_with_vanilla", || { + let vanilla_proofs: Vec<_> = vanilla_proofs .iter() - .cloned() - .map(|vanilla_proof| { - std::slice::from_raw_parts(vanilla_proof.proof_ptr, vanilla_proof.proof_len) - .to_vec() - }) + .map(|vanilla_proof| vanilla_proof.to_vec()) .collect(); let result = filecoin_proofs_api::post::generate_winning_post_with_vanilla( registered_proof.into(), - &randomness.inner, - prover_id.inner, + randomness, + *prover_id, &vanilla_proofs, - ); - - let mut response = fil_GenerateWinningPoStResponse::default(); - - match result { - Ok(output) => { - let mapped: Vec = output - .iter() - .cloned() - .map(|(t, proof)| { - let out = fil_PoStProof { - registered_proof: (t).into(), - proof_len: proof.len(), - proof_ptr: proof.as_ptr(), - }; + )?; - mem::forget(proof); - - out - }) - .collect(); - - response.status_code = FCPResponseStatus::FCPNoError; - response.proofs_ptr = mapped.as_ptr(); - response.proofs_len = mapped.len(); - - mem::forget(mapped); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("generate_winning_post_with_vanilla: finish"); + let result = result + .into_iter() + .map(|(t, proof)| PoStProof { + registered_proof: (t).into(), + proof: proof.into_boxed_slice().into(), + }) + .collect::>(); - raw_ptr(response) + Ok(result.into_boxed_slice().into()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_winning_post( - randomness: fil_32ByteArray, - replicas_ptr: *const fil_PrivateReplicaInfo, - replicas_len: libc::size_t, - prover_id: fil_32ByteArray, -) -> *mut fil_GenerateWinningPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_winning_post: start"); - - let mut response = fil_GenerateWinningPoStResponse::default(); - - let result = to_private_replica_info_map(replicas_ptr, replicas_len).and_then(|rs| { - filecoin_proofs_api::post::generate_winning_post( - &randomness.inner, - &rs, - prover_id.inner, - ) - }); - - match result { - Ok(output) => { - let mapped: Vec = output - .iter() - .cloned() - .map(|(t, proof)| { - let out = fil_PoStProof { - registered_proof: (t).into(), - proof_len: proof.len(), - proof_ptr: proof.as_ptr(), - }; - - mem::forget(proof); - - out - }) - .collect(); - - response.status_code = FCPResponseStatus::FCPNoError; - response.proofs_ptr = mapped.as_ptr(); - response.proofs_len = mapped.len(); - mem::forget(mapped); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } +#[ffi_export] +fn generate_winning_post( + randomness: &[u8; 32], + replicas: c_slice::Ref, + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("generate_winning_post", || { + let replicas = to_private_replica_info_map(replicas)?; + let result = + filecoin_proofs_api::post::generate_winning_post(randomness, &replicas, *prover_id)?; - info!("generate_winning_post: finish"); + let result = result + .into_iter() + .map(|(t, proof)| PoStProof { + registered_proof: (t).into(), + proof: proof.into_boxed_slice().into(), + }) + .collect::>(); - raw_ptr(response) + Ok(result.into_boxed_slice().into()) }) } /// Verifies that a proof-of-spacetime is valid. -#[no_mangle] -pub unsafe extern "C" fn fil_verify_winning_post( - randomness: fil_32ByteArray, - replicas_ptr: *const fil_PublicReplicaInfo, - replicas_len: libc::size_t, - proofs_ptr: *const fil_PoStProof, - proofs_len: libc::size_t, - prover_id: fil_32ByteArray, -) -> *mut fil_VerifyWinningPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("verify_winning_post: start"); - - let mut response = fil_VerifyWinningPoStResponse::default(); - - let convert = super::helpers::to_public_replica_info_map(replicas_ptr, replicas_len); - - let result = convert.and_then(|replicas| { - let post_proofs = c_to_rust_post_proofs(proofs_ptr, proofs_len)?; - let proofs: Vec = post_proofs.iter().flat_map(|pp| pp.clone().proof).collect(); - - filecoin_proofs_api::post::verify_winning_post( - &randomness.inner, - &proofs, - &replicas, - prover_id.inner, - ) - }); +#[ffi_export] +fn verify_winning_post( + randomness: &[u8; 32], + replicas: c_slice::Ref, + proofs: c_slice::Ref, + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("verify_winning_post", || { + let replicas = to_public_replica_info_map(replicas); + let proofs: Vec = proofs + .iter() + .flat_map(|pp| &pp.proof[..]) + .copied() + .collect(); - match result { - Ok(is_valid) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = is_valid; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; + let result = filecoin_proofs_api::post::verify_winning_post( + randomness, &proofs, &replicas, *prover_id, + )?; - info!("verify_winning_post: {}", "finish"); - raw_ptr(response) + Ok(result) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_window_post_with_vanilla( - registered_proof: fil_RegisteredPoStProof, - randomness: fil_32ByteArray, - prover_id: fil_32ByteArray, - vanilla_proofs_ptr: *const fil_VanillaProof, - vanilla_proofs_len: libc::size_t, -) -> *mut fil_GenerateWindowPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_window_post_with_vanilla: start"); - - let vanilla_proofs: Vec = - std::slice::from_raw_parts(vanilla_proofs_ptr, vanilla_proofs_len) - .iter() - .cloned() - .map(|vanilla_proof| { - std::slice::from_raw_parts(vanilla_proof.proof_ptr, vanilla_proof.proof_len) - .to_vec() - }) - .collect(); +#[ffi_export] +fn generate_window_post_with_vanilla( + registered_proof: RegisteredPoStProof, + randomness: &[u8; 32], + prover_id: &[u8; 32], + vanilla_proofs: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response_raw("generate_window_post_with_vanilla", || { + let vanilla_proofs: Vec<_> = vanilla_proofs + .iter() + .map(|vanilla_proof| vanilla_proof.to_vec()) + .collect(); let result = filecoin_proofs_api::post::generate_window_post_with_vanilla( registered_proof.into(), - &randomness.inner, - prover_id.inner, + randomness, + *prover_id, &vanilla_proofs, ); - let mut response = fil_GenerateWindowPoStResponse::default(); + let mut response = GenerateWindowPoStResponse::default(); match result { Ok(output) => { - let mapped: Vec = output - .iter() - .cloned() - .map(|(t, proof)| { - let out = fil_PoStProof { - registered_proof: (t).into(), - proof_len: proof.len(), - proof_ptr: proof.as_ptr(), - }; - - mem::forget(proof); - - out + let mapped: Vec = output + .into_iter() + .map(|(t, proof)| PoStProof { + registered_proof: t.into(), + proof: proof.into_boxed_slice().into(), }) .collect(); - response.status_code = FCPResponseStatus::FCPNoError; - response.proofs_ptr = mapped.as_ptr(); - response.proofs_len = mapped.len(); - mem::forget(mapped); + response.status_code = FCPResponseStatus::NoError; + response.value.proofs = mapped.into_boxed_slice().into(); } Err(err) => { // If there were faulty sectors, add them to the response @@ -1109,64 +593,44 @@ pub unsafe extern "C" fn fil_generate_window_post_with_vanilla( .iter() .map(|sector| u64::from(*sector)) .collect::>(); - response.faulty_sectors_len = sectors_u64.len(); - response.faulty_sectors_ptr = sectors_u64.as_ptr(); - mem::forget(sectors_u64) + + response.value.faulty_sectors = sectors_u64.into_boxed_slice().into() } - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); + response.status_code = FCPResponseStatus::UnclassifiedError; + response.error_msg = err.to_string().into_bytes().into_boxed_slice().into(); } } - info!("generate_window_post_with_vanilla: finish"); - - raw_ptr(response) + response }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_window_post( - randomness: fil_32ByteArray, - replicas_ptr: *const fil_PrivateReplicaInfo, - replicas_len: libc::size_t, - prover_id: fil_32ByteArray, -) -> *mut fil_GenerateWindowPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_window_post: start"); - - let mut response = fil_GenerateWindowPoStResponse::default(); - - let result = to_private_replica_info_map(replicas_ptr, replicas_len).and_then(|rs| { - filecoin_proofs_api::post::generate_window_post(&randomness.inner, &rs, prover_id.inner) +#[ffi_export] +fn generate_window_post( + randomness: &[u8; 32], + replicas: c_slice::Ref, + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response_raw("generate_window_post", || { + let result = to_private_replica_info_map(replicas).and_then(|replicas| { + filecoin_proofs_api::post::generate_window_post(randomness, &replicas, *prover_id) }); + let mut response = GenerateWindowPoStResponse::default(); match result { Ok(output) => { - let mapped: Vec = output - .iter() - .cloned() - .map(|(t, proof)| { - let out = fil_PoStProof { - registered_proof: (t).into(), - proof_len: proof.len(), - proof_ptr: proof.as_ptr(), - }; - - mem::forget(proof); - - out + let mapped: Vec = output + .into_iter() + .map(|(t, proof)| PoStProof { + registered_proof: t.into(), + proof: proof.into_boxed_slice().into(), }) .collect(); - response.status_code = FCPResponseStatus::FCPNoError; - response.proofs_ptr = mapped.as_ptr(); - response.proofs_len = mapped.len(); - mem::forget(mapped); + response.status_code = FCPResponseStatus::NoError; + response.value.proofs = mapped.into_boxed_slice().into(); } Err(err) => { // If there were faulty sectors, add them to the response @@ -1177,215 +641,120 @@ pub unsafe extern "C" fn fil_generate_window_post( .iter() .map(|sector| u64::from(*sector)) .collect::>(); - response.faulty_sectors_len = sectors_u64.len(); - response.faulty_sectors_ptr = sectors_u64.as_ptr(); - mem::forget(sectors_u64) + + response.value.faulty_sectors = sectors_u64.into_boxed_slice().into(); } - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); + response.status_code = FCPResponseStatus::UnclassifiedError; + response.error_msg = err.to_string().into_bytes().into_boxed_slice().into(); } } - info!("generate_window_post: finish"); - - raw_ptr(response) + response }) } /// Verifies that a proof-of-spacetime is valid. -#[no_mangle] -pub unsafe extern "C" fn fil_verify_window_post( - randomness: fil_32ByteArray, - replicas_ptr: *const fil_PublicReplicaInfo, - replicas_len: libc::size_t, - proofs_ptr: *const fil_PoStProof, - proofs_len: libc::size_t, - prover_id: fil_32ByteArray, -) -> *mut fil_VerifyWindowPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("verify_window_post: start"); - - let mut response = fil_VerifyWindowPoStResponse::default(); - - let convert = super::helpers::to_public_replica_info_map(replicas_ptr, replicas_len); - - let result = convert.and_then(|replicas| { - let post_proofs = c_to_rust_post_proofs(proofs_ptr, proofs_len)?; - - let proofs: Vec<(RegisteredPoStProof, &[u8])> = post_proofs - .iter() - .map(|x| (x.registered_proof, x.proof.as_ref())) - .collect(); - - filecoin_proofs_api::post::verify_window_post( - &randomness.inner, - &proofs, - &replicas, - prover_id.inner, - ) - }); +#[ffi_export] +fn verify_window_post( + randomness: &[u8; 32], + replicas: c_slice::Ref, + proofs: c_slice::Ref, + prover_id: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("verify_window_post", || { + let replicas = to_public_replica_info_map(replicas); + let proofs: Vec<(api::RegisteredPoStProof, &[u8])> = proofs + .iter() + .map(|x| { + ( + api::RegisteredPoStProof::from(x.registered_proof), + &x.proof[..], + ) + }) + .collect(); - match result { - Ok(is_valid) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = is_valid; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; + let result = filecoin_proofs_api::post::verify_window_post( + randomness, &proofs, &replicas, *prover_id, + )?; - info!("verify_window_post: {}", "finish"); - raw_ptr(response) + Ok(result) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_merge_window_post_partition_proofs( - registered_proof: fil_RegisteredPoStProof, - partition_proofs_ptr: *const fil_PartitionSnarkProof, - partition_proofs_len: libc::size_t, -) -> *mut fil_MergeWindowPoStPartitionProofsResponse { - catch_panic_response(|| { - init_log(); - - info!("merge_window_post_partition_proofs: start"); - - let mut response = fil_MergeWindowPoStPartitionProofsResponse::default(); - - let partition_proofs: Vec = - match c_to_rust_partition_proofs(partition_proofs_ptr, partition_proofs_len) { - Ok(partition_proofs) => partition_proofs - .iter() - .map(|pp| PartitionSnarkProof(pp.proof.clone())) - .collect(), - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - Vec::new() - } - }; - - if !partition_proofs.is_empty() { - let result = filecoin_proofs_api::post::merge_window_post_partition_proofs( - registered_proof.into(), - partition_proofs, - ); - - match result { - Ok(output) => { - let proof = fil_PoStProof { - registered_proof, - proof_ptr: output.as_ptr(), - proof_len: output.len(), - }; - - response.status_code = FCPResponseStatus::FCPNoError; - response.proof = proof; - - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - } +#[ffi_export] +fn merge_window_post_partition_proofs( + registered_proof: RegisteredPoStProof, + partition_proofs: c_slice::Ref>, +) -> repr_c::Box { + catch_panic_response("merge_window_post_partition_proofs", || { + let partition_proofs = partition_proofs + .iter() + .map(|proof| api::PartitionSnarkProof(proof.to_vec())) + .collect::>(); - info!("merge_window_post_partition_proofs: finish"); + let proof = filecoin_proofs_api::post::merge_window_post_partition_proofs( + registered_proof.into(), + partition_proofs, + )?; - raw_ptr(response) + Ok(PoStProof { + registered_proof, + proof: proof.into_boxed_slice().into(), + }) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_num_partition_for_fallback_post( - registered_proof: fil_RegisteredPoStProof, +#[ffi_export] +fn get_num_partition_for_fallback_post( + registered_proof: RegisteredPoStProof, num_sectors: libc::size_t, -) -> *mut fil_GetNumPartitionForFallbackPoStResponse { - catch_panic_response(|| { - init_log(); - - info!("get_num_partition_for_fallback_post: start"); +) -> repr_c::Box { + catch_panic_response("get_num_partition_for_fallback_post", || { let result = filecoin_proofs_api::post::get_num_partition_for_fallback_post( registered_proof.into(), num_sectors, - ); - - let mut response = fil_GetNumPartitionForFallbackPoStResponse::default(); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.num_partition = output; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("get_num_partition_for_fallback_post: finish"); - - raw_ptr(response) + )?; + Ok(result) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_single_window_post_with_vanilla( - registered_proof: fil_RegisteredPoStProof, - randomness: fil_32ByteArray, - prover_id: fil_32ByteArray, - vanilla_proofs_ptr: *const fil_VanillaProof, - vanilla_proofs_len: libc::size_t, +#[ffi_export] +fn generate_single_window_post_with_vanilla( + registered_proof: RegisteredPoStProof, + randomness: &[u8; 32], + prover_id: &[u8; 32], + vanilla_proofs: c_slice::Ref, partition_index: libc::size_t, -) -> *mut fil_GenerateSingleWindowPoStWithVanillaResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_single_window_post_with_vanilla: start"); - - let vanilla_proofs: Vec = - std::slice::from_raw_parts(vanilla_proofs_ptr, vanilla_proofs_len) - .iter() - .cloned() - .map(|vanilla_proof| { - std::slice::from_raw_parts(vanilla_proof.proof_ptr, vanilla_proof.proof_len) - .to_vec() - }) - .collect(); +) -> repr_c::Box { + catch_panic_response_raw("generate_single_window_post_with_vanilla", || { + let vanilla_proofs: Vec<_> = vanilla_proofs + .iter() + .map(|vanilla_proof| vanilla_proof.to_vec()) + .collect(); let result = filecoin_proofs_api::post::generate_single_window_post_with_vanilla( registered_proof.into(), - &randomness.inner, - prover_id.inner, + randomness, + *prover_id, &vanilla_proofs, partition_index, ); - let mut response = fil_GenerateSingleWindowPoStWithVanillaResponse::default(); + let mut response = GenerateSingleWindowPoStWithVanillaResponse::default(); match result { Ok(output) => { - let partition_proof = fil_PartitionSnarkProof { + let partition_proof = PartitionSnarkProof { registered_proof, - proof_ptr: output.0.as_ptr(), - proof_len: output.0.len(), + proof: output.0.into_boxed_slice().into(), }; - mem::forget(output); - response.status_code = FCPResponseStatus::FCPNoError; - response.partition_proof = partition_proof; + response.status_code = FCPResponseStatus::NoError; + response.value.partition_proof = partition_proof; } Err(err) => { // If there were faulty sectors, add them to the response @@ -1396,466 +765,256 @@ pub unsafe extern "C" fn fil_generate_single_window_post_with_vanilla( .iter() .map(|sector| u64::from(*sector)) .collect::>(); - response.faulty_sectors_len = sectors_u64.len(); - response.faulty_sectors_ptr = sectors_u64.as_ptr(); - mem::forget(sectors_u64) + + response.value.faulty_sectors = sectors_u64.into_boxed_slice().into(); } - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); + response.status_code = FCPResponseStatus::UnclassifiedError; + response.error_msg = err.to_string().into_bytes().into_boxed_slice().into(); } } - info!("generate_single_window_post_with_vanilla: finish"); - - raw_ptr(response) + response }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_empty_sector_update_encode_into( - registered_proof: fil_RegisteredUpdateProof, - new_replica_path: *const libc::c_char, - new_cache_dir_path: *const libc::c_char, - sector_key_path: *const libc::c_char, - sector_key_cache_dir_path: *const libc::c_char, - staged_data_path: *const libc::c_char, - pieces_ptr: *const fil_PublicPieceInfo, - pieces_len: libc::size_t, -) -> *mut fil_EmptySectorUpdateEncodeIntoResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_empty_sector_update_encode_into: start"); - - let slice: &[fil_PublicPieceInfo] = std::slice::from_raw_parts(pieces_ptr, pieces_len); - let public_pieces: Vec = - slice.to_vec().iter().cloned().map(Into::into).collect(); - - let mut response: fil_EmptySectorUpdateEncodeIntoResponse = Default::default(); - - let result = empty_sector_update_encode_into( +#[ffi_export] +fn empty_sector_update_encode_into( + registered_proof: RegisteredUpdateProof, + new_replica_path: c_slice::Ref, + new_cache_dir_path: c_slice::Ref, + sector_key_path: c_slice::Ref, + sector_key_cache_dir_path: c_slice::Ref, + staged_data_path: c_slice::Ref, + pieces: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("empty_sector_update_encode_into", || { + let public_pieces = pieces.iter().map(Into::into).collect::>(); + + let output = update::empty_sector_update_encode_into( registered_proof.into(), - c_str_to_pbuf(new_replica_path), - c_str_to_pbuf(new_cache_dir_path), - c_str_to_pbuf(sector_key_path), - c_str_to_pbuf(sector_key_cache_dir_path), - c_str_to_pbuf(staged_data_path), + as_path_buf(&new_replica_path)?, + as_path_buf(&new_cache_dir_path)?, + as_path_buf(§or_key_path)?, + as_path_buf(§or_key_cache_dir_path)?, + as_path_buf(&staged_data_path)?, &public_pieces, - ); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.comm_r_new = output.comm_r_new; - response.comm_r_last_new = output.comm_r_last_new; - response.comm_d_new = output.comm_d_new; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fil_empty_sector_update_encode_into: finish"); + )?; - raw_ptr(response) + Ok(EmptySectorUpdateEncodeInto { + comm_r_new: output.comm_r_new, + comm_r_last_new: output.comm_r_last_new, + comm_d_new: output.comm_d_new, + }) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_empty_sector_update_decode_from( - registered_proof: fil_RegisteredUpdateProof, - out_data_path: *const libc::c_char, - replica_path: *const libc::c_char, - sector_key_path: *const libc::c_char, - sector_key_cache_dir_path: *const libc::c_char, - comm_d_new: fil_32ByteArray, -) -> *mut fil_EmptySectorUpdateDecodeFromResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_empty_sector_update_decode_from: start"); - - let mut response: fil_EmptySectorUpdateDecodeFromResponse = Default::default(); - - let result = empty_sector_update_decode_from( +#[ffi_export] +fn empty_sector_update_decode_from( + registered_proof: RegisteredUpdateProof, + out_data_path: c_slice::Ref, + replica_path: c_slice::Ref, + sector_key_path: c_slice::Ref, + sector_key_cache_dir_path: c_slice::Ref, + comm_d_new: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("empty_sector_update_decode_from", || { + update::empty_sector_update_decode_from( registered_proof.into(), - c_str_to_pbuf(out_data_path), - c_str_to_pbuf(replica_path), - c_str_to_pbuf(sector_key_path), - c_str_to_pbuf(sector_key_cache_dir_path), - comm_d_new.inner, - ); - - match result { - Ok(_output) => { - response.status_code = FCPResponseStatus::FCPNoError; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fil_empty_sector_update_decode_from: finish"); - - raw_ptr(response) - }) -} - -/// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_empty_sector_update_remove_encoded_data( - registered_proof: fil_RegisteredUpdateProof, - sector_key_path: *const libc::c_char, - sector_key_cache_dir_path: *const libc::c_char, - replica_path: *const libc::c_char, - replica_cache_path: *const libc::c_char, - data_path: *const libc::c_char, - comm_d_new: fil_32ByteArray, -) -> *mut fil_EmptySectorUpdateRemoveEncodedDataResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_empty_sector_update_remove_encoded_data: start"); - - let mut response: fil_EmptySectorUpdateRemoveEncodedDataResponse = Default::default(); - - let result = empty_sector_update_remove_encoded_data( - registered_proof.into(), - c_str_to_pbuf(sector_key_path), - c_str_to_pbuf(sector_key_cache_dir_path), - c_str_to_pbuf(replica_path), - c_str_to_pbuf(replica_cache_path), - c_str_to_pbuf(data_path), - comm_d_new.inner, - ); - - match result { - Ok(_output) => { - response.status_code = FCPResponseStatus::FCPNoError; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fil_empty_sector_update_remove_encoded_data: finish"); - - raw_ptr(response) - }) -} - -/// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_empty_sector_update_partition_proofs( - registered_proof: fil_RegisteredUpdateProof, - comm_r_old: fil_32ByteArray, - comm_r_new: fil_32ByteArray, - comm_d_new: fil_32ByteArray, - sector_key_path: *const libc::c_char, - sector_key_cache_dir_path: *const libc::c_char, - replica_path: *const libc::c_char, - replica_cache_path: *const libc::c_char, -) -> *mut fil_PartitionProofResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_generate_empty_sector_update_partition_proofs: start"); - - let mut response: fil_PartitionProofResponse = Default::default(); - - let result = generate_partition_proofs( - registered_proof.into(), - comm_r_old.inner, - comm_r_new.inner, - comm_d_new.inner, - c_str_to_pbuf(sector_key_path), - c_str_to_pbuf(sector_key_cache_dir_path), - c_str_to_pbuf(replica_path), - c_str_to_pbuf(replica_cache_path), - ); - - match result { - Ok(output) => { - let mapped: Vec = output - .iter() - .cloned() - .map(|proof| { - let out = fil_PartitionProof { - proof_ptr: proof.0.as_ptr(), - proof_len: proof.0.len(), - }; - - mem::forget(proof); - - out - }) - .collect(); - - response.status_code = FCPResponseStatus::FCPNoError; - response.proofs_ptr = mapped.as_ptr(); - response.proofs_len = mapped.len(); - - mem::forget(mapped); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fil_generate_empty_sector_update_partition_proofs: finish"); + as_path_buf(&out_data_path)?, + as_path_buf(&replica_path)?, + as_path_buf(§or_key_path)?, + as_path_buf(§or_key_cache_dir_path)?, + *comm_d_new, + )?; - raw_ptr(response) + Ok(()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_verify_empty_sector_update_partition_proofs( - registered_proof: fil_RegisteredUpdateProof, - proofs_len: libc::size_t, - proofs_ptr: *const fil_PartitionProof, - comm_r_old: fil_32ByteArray, - comm_r_new: fil_32ByteArray, - comm_d_new: fil_32ByteArray, -) -> *mut fil_VerifyPartitionProofResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_verify_empty_sector_update_partition_proofs: start"); - - let mut response: fil_VerifyPartitionProofResponse = Default::default(); - - match c_to_rust_vanilla_partition_proofs(proofs_ptr, proofs_len) { - Ok(partition_proofs) => { - let proofs: Vec = partition_proofs - .iter() - .map(|pp| PartitionProofBytes(pp.clone().proof)) - .collect(); - - let result = verify_partition_proofs( - registered_proof.into(), - &proofs, - comm_r_old.inner, - comm_r_new.inner, - comm_d_new.inner, - ); - - match result { - Ok(is_valid) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = is_valid; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; +#[ffi_export] +fn empty_sector_update_remove_encoded_data( + registered_proof: RegisteredUpdateProof, + sector_key_path: c_slice::Ref, + sector_key_cache_dir_path: c_slice::Ref, + replica_path: c_slice::Ref, + replica_cache_path: c_slice::Ref, + data_path: c_slice::Ref, + comm_d_new: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("empty_sector_update_remove_encoded_data", || { + update::empty_sector_update_remove_encoded_data( + registered_proof.into(), + as_path_buf(§or_key_path)?, + as_path_buf(§or_key_cache_dir_path)?, + as_path_buf(&replica_path)?, + as_path_buf(&replica_cache_path)?, + as_path_buf(&data_path)?, + *comm_d_new, + )?; - info!("fil_verify_empty_sector_update_partition_proofs: finish"); + Ok(()) + }) +} - raw_ptr(response) +/// TODO: document +#[ffi_export] +fn generate_empty_sector_update_partition_proofs( + registered_proof: RegisteredUpdateProof, + comm_r_old: &[u8; 32], + comm_r_new: &[u8; 32], + comm_d_new: &[u8; 32], + sector_key_path: c_slice::Ref, + sector_key_cache_dir_path: c_slice::Ref, + replica_path: c_slice::Ref, + replica_cache_path: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("generate_empty_sector_update_partition_proofs", || { + let output = update::generate_partition_proofs( + registered_proof.into(), + *comm_r_old, + *comm_r_new, + *comm_d_new, + as_path_buf(§or_key_path)?, + as_path_buf(§or_key_cache_dir_path)?, + as_path_buf(&replica_path)?, + as_path_buf(&replica_cache_path)?, + )?; + + let result = output + .into_iter() + .map(|proof| proof.0.into_boxed_slice().into()) + .collect::>() + .into_boxed_slice() + .into(); + Ok(result) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_empty_sector_update_proof_with_vanilla( - registered_proof: fil_RegisteredUpdateProof, - vanilla_proofs_ptr: *const fil_PartitionProof, - vanilla_proofs_len: libc::size_t, - comm_r_old: fil_32ByteArray, - comm_r_new: fil_32ByteArray, - comm_d_new: fil_32ByteArray, -) -> *mut fil_EmptySectorUpdateProofResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_generate_empty_sector_update_proof_with_vanilla: start"); - - let mut response: fil_EmptySectorUpdateProofResponse = Default::default(); - - let proofs: &[fil_PartitionProof] = - std::slice::from_raw_parts(vanilla_proofs_ptr, vanilla_proofs_len); - let partition_proofs: Vec = proofs +#[ffi_export] +fn verify_empty_sector_update_partition_proofs( + registered_proof: RegisteredUpdateProof, + proofs: c_slice::Ref, + comm_r_old: &[u8; 32], + comm_r_new: &[u8; 32], + comm_d_new: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("verify_empty_sector_update_partition_proofs", || { + let proofs: Vec = proofs .iter() - .cloned() - .map(|partition_proof| { - PartitionProofBytes( - std::slice::from_raw_parts( - partition_proof.proof_ptr, - partition_proof.proof_len, - ) - .to_vec(), - ) - }) + .map(|pp| api::PartitionProofBytes(pp.to_vec())) .collect(); - let result = generate_empty_sector_update_proof_with_vanilla( + let result = update::verify_partition_proofs( registered_proof.into(), - partition_proofs, - comm_r_old.inner, - comm_r_new.inner, - comm_d_new.inner, - ); + &proofs, + *comm_r_old, + *comm_r_new, + *comm_d_new, + )?; - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.proof_ptr = output.0.as_ptr(); - response.proof_len = output.0.len(); + Ok(result) + }) +} - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } +/// TODO: document +#[ffi_export] +fn generate_empty_sector_update_proof_with_vanilla( + registered_proof: RegisteredUpdateProof, + vanilla_proofs: c_slice::Ref, + comm_r_old: &[u8; 32], + comm_r_new: &[u8; 32], + comm_d_new: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("generate_empty_sector_update_proof_with_vanilla", || { + let partition_proofs: Vec = vanilla_proofs + .iter() + .map(|partition_proof| api::PartitionProofBytes(partition_proof.to_vec())) + .collect(); - info!("fil_generate_empty_sector_update_proof_with_vanilla: finish"); + let result = update::generate_empty_sector_update_proof_with_vanilla( + registered_proof.into(), + partition_proofs, + *comm_r_old, + *comm_r_new, + *comm_d_new, + )?; - raw_ptr(response) + Ok(result.0.into_boxed_slice().into()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_generate_empty_sector_update_proof( - registered_proof: fil_RegisteredUpdateProof, - comm_r_old: fil_32ByteArray, - comm_r_new: fil_32ByteArray, - comm_d_new: fil_32ByteArray, - sector_key_path: *const libc::c_char, - sector_key_cache_dir_path: *const libc::c_char, - replica_path: *const libc::c_char, - replica_cache_path: *const libc::c_char, -) -> *mut fil_EmptySectorUpdateProofResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_generate_empty_sector_update_proof: start"); - - let mut response: fil_EmptySectorUpdateProofResponse = Default::default(); - - let result = generate_empty_sector_update_proof( +#[ffi_export] +fn generate_empty_sector_update_proof( + registered_proof: RegisteredUpdateProof, + comm_r_old: &[u8; 32], + comm_r_new: &[u8; 32], + comm_d_new: &[u8; 32], + sector_key_path: c_slice::Ref, + sector_key_cache_dir_path: c_slice::Ref, + replica_path: c_slice::Ref, + replica_cache_path: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("generate_empty_sector_update_proof", || { + let result = update::generate_empty_sector_update_proof( registered_proof.into(), - comm_r_old.inner, - comm_r_new.inner, - comm_d_new.inner, - c_str_to_pbuf(sector_key_path), - c_str_to_pbuf(sector_key_cache_dir_path), - c_str_to_pbuf(replica_path), - c_str_to_pbuf(replica_cache_path), - ); - - match result { - Ok(output) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.proof_ptr = output.0.as_ptr(); - response.proof_len = output.0.len(); - - mem::forget(output); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("fil_generate_empty_sector_update_proof: finish"); - - raw_ptr(response) + *comm_r_old, + *comm_r_new, + *comm_d_new, + as_path_buf(§or_key_path)?, + as_path_buf(§or_key_cache_dir_path)?, + as_path_buf(&replica_path)?, + as_path_buf(&replica_cache_path)?, + )?; + + Ok(result.0.into_boxed_slice().into()) }) } /// TODO: document -/// -#[no_mangle] -pub unsafe extern "C" fn fil_verify_empty_sector_update_proof( - registered_proof: fil_RegisteredUpdateProof, - proof_ptr: *const u8, - proof_len: libc::size_t, - comm_r_old: fil_32ByteArray, - comm_r_new: fil_32ByteArray, - comm_d_new: fil_32ByteArray, -) -> *mut fil_VerifyEmptySectorUpdateProofResponse { - catch_panic_response(|| { - init_log(); - - info!("fil_verify_empty_sector_update_proof: start"); - - let proof_bytes: Vec = std::slice::from_raw_parts(proof_ptr, proof_len).to_vec(); - - let mut response: fil_VerifyEmptySectorUpdateProofResponse = Default::default(); - - let result = verify_empty_sector_update_proof( +#[ffi_export] +fn verify_empty_sector_update_proof( + registered_proof: RegisteredUpdateProof, + proof: c_slice::Ref, + comm_r_old: &[u8; 32], + comm_r_new: &[u8; 32], + comm_d_new: &[u8; 32], +) -> repr_c::Box { + catch_panic_response("verify_empty_sector_update_proof", || { + let proof_bytes: Vec = proof.to_vec(); + + let result = update::verify_empty_sector_update_proof( registered_proof.into(), &proof_bytes, - comm_r_old.inner, - comm_r_new.inner, - comm_d_new.inner, - ); + *comm_r_old, + *comm_r_new, + *comm_d_new, + )?; - match result { - Ok(true) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = true; - } - Ok(false) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.is_valid = false; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - response.is_valid = false; - } - } - - info!("fil_verify_empty_sector_update_proof: finish"); - - raw_ptr(response) + Ok(result) }) } /// Returns the merkle root for a piece after piece padding and alignment. /// The caller is responsible for closing the passed in file descriptor. -#[no_mangle] -#[cfg(not(target_os = "windows"))] -pub unsafe extern "C" fn fil_generate_piece_commitment( - registered_proof: fil_RegisteredSealProof, +#[ffi_export] +unsafe fn generate_piece_commitment( + registered_proof: RegisteredSealProof, piece_fd_raw: libc::c_int, unpadded_piece_size: u64, -) -> *mut fil_GeneratePieceCommitmentResponse { - catch_panic_response(|| { - init_log(); - +) -> repr_c::Box { + catch_panic_response("generate_piece_commitment", || { use std::os::unix::io::{FromRawFd, IntoRawFd}; - let mut piece_file = std::fs::File::from_raw_fd(piece_fd_raw); + let mut piece_file = fs::File::from_raw_fd(piece_fd_raw); let unpadded_piece_size = UnpaddedBytesAmount(unpadded_piece_size); - let result = generate_piece_commitment( + let result = seal::generate_piece_commitment( registered_proof.into(), &mut piece_file, unpadded_piece_size, @@ -1864,197 +1023,70 @@ pub unsafe extern "C" fn fil_generate_piece_commitment( // avoid dropping the File which closes it let _ = piece_file.into_raw_fd(); - let mut response = fil_GeneratePieceCommitmentResponse::default(); - - match result { - Ok(meta) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.comm_p = meta.commitment; - response.num_bytes_aligned = meta.size.into(); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } + let result = result.map(|meta| GeneratePieceCommitment { + comm_p: meta.commitment, + num_bytes_aligned: meta.size.into(), + })?; - raw_ptr(response) + Ok(result) }) } /// Returns the merkle root for a sector containing the provided pieces. -#[no_mangle] -pub unsafe extern "C" fn fil_generate_data_commitment( - registered_proof: fil_RegisteredSealProof, - pieces_ptr: *const fil_PublicPieceInfo, - pieces_len: libc::size_t, -) -> *mut fil_GenerateDataCommitmentResponse { - catch_panic_response(|| { - init_log(); - - info!("generate_data_commitment: start"); - - let public_pieces: Vec = std::slice::from_raw_parts(pieces_ptr, pieces_len) - .to_vec() - .iter() - .cloned() - .map(Into::into) - .collect(); - - let result = compute_comm_d(registered_proof.into(), &public_pieces); - - let mut response = fil_GenerateDataCommitmentResponse::default(); - - match result { - Ok(commitment) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.comm_d = commitment; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - info!("generate_data_commitment: finish"); - - raw_ptr(response) +#[ffi_export] +fn generate_data_commitment( + registered_proof: RegisteredSealProof, + pieces: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("generate_data_commitment", || { + let public_pieces: Vec = pieces.iter().map(Into::into).collect(); + let result = seal::compute_comm_d(registered_proof.into(), &public_pieces)?; + + Ok(result) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_clear_cache( +#[ffi_export] +fn clear_cache( sector_size: u64, - cache_dir_path: *const libc::c_char, -) -> *mut fil_ClearCacheResponse { - catch_panic_response(|| { - init_log(); - - let result = clear_cache(sector_size, &c_str_to_pbuf(cache_dir_path)); - - let mut response = fil_ClearCacheResponse::default(); - - match result { - Ok(_) => { - response.status_code = FCPResponseStatus::FCPNoError; - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - }; + cache_dir_path: c_slice::Ref, +) -> repr_c::Box { + catch_panic_response("clear_cache", || { + let result = seal::clear_cache(sector_size, &as_path_buf(&cache_dir_path)?)?; - raw_ptr(response) + Ok(result) }) } -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_write_with_alignment_response( - ptr: *mut fil_WriteWithAlignmentResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_write_without_alignment_response( - ptr: *mut fil_WriteWithoutAlignmentResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_fauxrep_response(ptr: *mut fil_FauxRepResponse) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_seal_pre_commit_phase1_response( - ptr: *mut fil_SealPreCommitPhase1Response, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_seal_pre_commit_phase2_response( - ptr: *mut fil_SealPreCommitPhase2Response, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_seal_commit_phase1_response( - ptr: *mut fil_SealCommitPhase1Response, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_seal_commit_phase2_response( - ptr: *mut fil_SealCommitPhase2Response, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_unseal_range_response(ptr: *mut fil_UnsealRangeResponse) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_piece_commitment_response( - ptr: *mut fil_GeneratePieceCommitmentResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_data_commitment_response( - ptr: *mut fil_GenerateDataCommitmentResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_string_response(ptr: *mut fil_StringResponse) { - let _ = Box::from_raw(ptr); -} - /// Returns the number of user bytes that will fit into a staged sector. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_max_user_bytes_per_staged_sector( - registered_proof: fil_RegisteredSealProof, -) -> u64 { +#[ffi_export] +fn get_max_user_bytes_per_staged_sector(registered_proof: RegisteredSealProof) -> u64 { u64::from(UnpaddedBytesAmount::from( - RegisteredSealProof::from(registered_proof).sector_size(), + api::RegisteredSealProof::from(registered_proof).sector_size(), )) } /// Returns the CID of the Groth parameter file for sealing. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_seal_params_cid( - registered_proof: fil_RegisteredSealProof, -) -> *mut fil_StringResponse { - registered_seal_proof_accessor(registered_proof, RegisteredSealProof::params_cid) +#[ffi_export] +fn get_seal_params_cid(registered_proof: RegisteredSealProof) -> repr_c::Box { + registered_seal_proof_accessor(registered_proof, api::RegisteredSealProof::params_cid) } /// Returns the CID of the verifying key-file for verifying a seal proof. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_seal_verifying_key_cid( - registered_proof: fil_RegisteredSealProof, -) -> *mut fil_StringResponse { - registered_seal_proof_accessor(registered_proof, RegisteredSealProof::verifying_key_cid) +#[ffi_export] +fn get_seal_verifying_key_cid( + registered_proof: RegisteredSealProof, +) -> repr_c::Box { + registered_seal_proof_accessor( + registered_proof, + api::RegisteredSealProof::verifying_key_cid, + ) } /// Returns the path from which the proofs library expects to find the Groth /// parameter file used when sealing. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_seal_params_path( - registered_proof: fil_RegisteredSealProof, -) -> *mut fil_StringResponse { +#[ffi_export] +fn get_seal_params_path(registered_proof: RegisteredSealProof) -> repr_c::Box { registered_seal_proof_accessor(registered_proof, |p| { p.cache_params_path() .map(|pb| String::from(pb.to_string_lossy())) @@ -2063,11 +1095,10 @@ pub unsafe extern "C" fn fil_get_seal_params_path( /// Returns the path from which the proofs library expects to find the verifying /// key-file used when verifying a seal proof. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_seal_verifying_key_path( - registered_proof: fil_RegisteredSealProof, -) -> *mut fil_StringResponse { +#[ffi_export] +fn get_seal_verifying_key_path( + registered_proof: RegisteredSealProof, +) -> repr_c::Box { registered_seal_proof_accessor(registered_proof, |p| { p.cache_verifying_key_path() .map(|pb| String::from(pb.to_string_lossy())) @@ -2075,48 +1106,43 @@ pub unsafe extern "C" fn fil_get_seal_verifying_key_path( } /// Returns the identity of the circuit for the provided seal proof. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_seal_circuit_identifier( - registered_proof: fil_RegisteredSealProof, -) -> *mut fil_StringResponse { - registered_seal_proof_accessor(registered_proof, RegisteredSealProof::circuit_identifier) +#[ffi_export] +fn get_seal_circuit_identifier( + registered_proof: RegisteredSealProof, +) -> repr_c::Box { + registered_seal_proof_accessor( + registered_proof, + api::RegisteredSealProof::circuit_identifier, + ) } /// Returns the version of the provided seal proof type. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_seal_version( - registered_proof: fil_RegisteredSealProof, -) -> *mut fil_StringResponse { +#[ffi_export] +fn get_seal_version(registered_proof: RegisteredSealProof) -> repr_c::Box { registered_seal_proof_accessor(registered_proof, |p| Ok(format!("{:?}", p))) } /// Returns the CID of the Groth parameter file for generating a PoSt. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_post_params_cid( - registered_proof: fil_RegisteredPoStProof, -) -> *mut fil_StringResponse { - registered_post_proof_accessor(registered_proof, RegisteredPoStProof::params_cid) +#[ffi_export] +fn get_post_params_cid(registered_proof: RegisteredPoStProof) -> repr_c::Box { + registered_post_proof_accessor(registered_proof, api::RegisteredPoStProof::params_cid) } /// Returns the CID of the verifying key-file for verifying a PoSt proof. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_post_verifying_key_cid( - registered_proof: fil_RegisteredPoStProof, -) -> *mut fil_StringResponse { - registered_post_proof_accessor(registered_proof, RegisteredPoStProof::verifying_key_cid) +#[ffi_export] +fn get_post_verifying_key_cid( + registered_proof: RegisteredPoStProof, +) -> repr_c::Box { + registered_post_proof_accessor( + registered_proof, + api::RegisteredPoStProof::verifying_key_cid, + ) } /// Returns the path from which the proofs library expects to find the Groth /// parameter file used when generating a PoSt. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_post_params_path( - registered_proof: fil_RegisteredPoStProof, -) -> *mut fil_StringResponse { +#[ffi_export] +fn get_post_params_path(registered_proof: RegisteredPoStProof) -> repr_c::Box { registered_post_proof_accessor(registered_proof, |p| { p.cache_params_path() .map(|pb| String::from(pb.to_string_lossy())) @@ -2125,11 +1151,10 @@ pub unsafe extern "C" fn fil_get_post_params_path( /// Returns the path from which the proofs library expects to find the verifying /// key-file used when verifying a PoSt proof. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_post_verifying_key_path( - registered_proof: fil_RegisteredPoStProof, -) -> *mut fil_StringResponse { +#[ffi_export] +fn get_post_verifying_key_path( + registered_proof: RegisteredPoStProof, +) -> repr_c::Box { registered_post_proof_accessor(registered_proof, |p| { p.cache_verifying_key_path() .map(|pb| String::from(pb.to_string_lossy())) @@ -2137,236 +1162,155 @@ pub unsafe extern "C" fn fil_get_post_verifying_key_path( } /// Returns the identity of the circuit for the provided PoSt proof type. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_post_circuit_identifier( - registered_proof: fil_RegisteredPoStProof, -) -> *mut fil_StringResponse { - registered_post_proof_accessor(registered_proof, RegisteredPoStProof::circuit_identifier) +#[ffi_export] +fn get_post_circuit_identifier( + registered_proof: RegisteredPoStProof, +) -> repr_c::Box { + registered_post_proof_accessor( + registered_proof, + api::RegisteredPoStProof::circuit_identifier, + ) } /// Returns the version of the provided seal proof. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_get_post_version( - registered_proof: fil_RegisteredPoStProof, -) -> *mut fil_StringResponse { +#[ffi_export] +fn get_post_version(registered_proof: RegisteredPoStProof) -> repr_c::Box { registered_post_proof_accessor(registered_proof, |p| Ok(format!("{:?}", p))) } -unsafe fn registered_seal_proof_accessor( - registered_proof: fil_RegisteredSealProof, - op: fn(RegisteredSealProof) -> anyhow::Result, -) -> *mut fil_StringResponse { - let mut response = fil_StringResponse::default(); - - let rsp: RegisteredSealProof = registered_proof.into(); - - match op(rsp) { - Ok(s) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.string_val = rust_str_to_c_str(s); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - raw_ptr(response) -} - -unsafe fn registered_post_proof_accessor( - registered_proof: fil_RegisteredPoStProof, - op: fn(RegisteredPoStProof) -> anyhow::Result, -) -> *mut fil_StringResponse { - let mut response = fil_StringResponse::default(); - - let rsp: RegisteredPoStProof = registered_proof.into(); - - match op(rsp) { - Ok(s) => { - response.status_code = FCPResponseStatus::FCPNoError; - response.string_val = rust_str_to_c_str(s); - } - Err(err) => { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str(format!("{:?}", err)); - } - } - - raw_ptr(response) -} - -/// Deallocates a VerifySealResponse. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_verify_seal_response(ptr: *mut fil_VerifySealResponse) { - let _ = Box::from_raw(ptr); -} - -/// Deallocates a VerifyAggregateSealProofResponse. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_verify_aggregate_seal_response( - ptr: *mut fil_VerifyAggregateSealProofResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_finalize_ticket_response( - ptr: *mut fil_FinalizeTicketResponse, -) { - let _ = Box::from_raw(ptr); -} - -/// Deallocates a VerifyPoStResponse. -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_verify_winning_post_response( - ptr: *mut fil_VerifyWinningPoStResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_verify_window_post_response( - ptr: *mut fil_VerifyWindowPoStResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_fallback_sector_challenges_response( - ptr: *mut fil_GenerateFallbackSectorChallengesResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_single_vanilla_proof_response( - ptr: *mut fil_GenerateSingleVanillaProofResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_single_window_post_with_vanilla_response( - ptr: *mut fil_GenerateSingleWindowPoStWithVanillaResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_get_num_partition_for_fallback_post_response( - ptr: *mut fil_GetNumPartitionForFallbackPoStResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_merge_window_post_partition_proofs_response( - ptr: *mut fil_MergeWindowPoStPartitionProofsResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_winning_post_response( - ptr: *mut fil_GenerateWinningPoStResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_window_post_response( - ptr: *mut fil_GenerateWindowPoStResponse, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_winning_post_sector_challenge( - ptr: *mut fil_GenerateWinningPoStSectorChallenge, -) { - let _ = Box::from_raw(ptr); -} - -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_clear_cache_response(ptr: *mut fil_ClearCacheResponse) { - let _ = Box::from_raw(ptr); -} - -/// Deallocates a AggregateProof -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_aggregate_proof(ptr: *mut fil_AggregateProof) { - let _ = Box::from_raw(ptr); -} - -/// Deallocates a EmptySectorUpdateProof -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_empty_sector_update_generate_proof_response( - ptr: *mut fil_EmptySectorUpdateProofResponse, -) { - let _ = Box::from_raw(ptr); -} - -/// Deallocates a VerifyEmptySectorUpdateProofResponse -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_empty_sector_update_verify_proof_response( - ptr: *mut fil_VerifyEmptySectorUpdateProofResponse, -) { - let _ = Box::from_raw(ptr); -} - -/// Deallocates a PartitionProofResponse -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_generate_empty_sector_update_partition_proof_response( - ptr: *mut fil_PartitionProofResponse, -) { - let _ = Box::from_raw(ptr); -} +fn registered_seal_proof_accessor( + registered_proof: RegisteredSealProof, + op: fn(api::RegisteredSealProof) -> anyhow::Result, +) -> repr_c::Box { + let rsp: api::RegisteredSealProof = registered_proof.into(); -/// Deallocates a VerifyEmptySectorUpdateProofResponse -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_verify_empty_sector_update_partition_proof_response( - ptr: *mut fil_VerifyPartitionProofResponse, -) { - let _ = Box::from_raw(ptr); + repr_c::Box::new(StringResponse::from( + op(rsp).map(|v| v.into_bytes().into_boxed_slice().into()), + )) } -/// Deallocates a EmptySectorUpdateEncodeIntoResponse -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_empty_sector_update_encode_into_response( - ptr: *mut fil_EmptySectorUpdateEncodeIntoResponse, -) { - let _ = Box::from_raw(ptr); -} +fn registered_post_proof_accessor( + registered_proof: RegisteredPoStProof, + op: fn(api::RegisteredPoStProof) -> anyhow::Result, +) -> repr_c::Box { + let rsp: api::RegisteredPoStProof = registered_proof.into(); -/// Deallocates a EmptySectorUpdateDecodeFromResponse -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_empty_sector_update_decode_from_response( - ptr: *mut fil_EmptySectorUpdateDecodeFromResponse, -) { - let _ = Box::from_raw(ptr); + repr_c::Box::new(StringResponse::from( + op(rsp).map(|v| v.into_bytes().into_boxed_slice().into()), + )) } -/// Deallocates a EmptySectorUpdateRemoveEncodedDataResponse -/// -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_empty_sector_update_remove_encoded_data_response( - ptr: *mut fil_EmptySectorUpdateRemoveEncodedDataResponse, -) { - let _ = Box::from_raw(ptr); -} +destructor!( + destroy_write_with_alignment_response, + WriteWithAlignmentResponse +); +destructor!( + destroy_write_without_alignment_response, + WriteWithoutAlignmentResponse +); +destructor!(destroy_fauxrep_response, FauxRepResponse); +destructor!( + destroy_seal_pre_commit_phase1_response, + SealPreCommitPhase1Response +); +destructor!( + destroy_seal_pre_commit_phase2_response, + SealPreCommitPhase2Response +); +destructor!( + destroy_seal_commit_phase1_response, + SealCommitPhase1Response +); +destructor!( + destroy_seal_commit_phase2_response, + SealCommitPhase2Response +); +destructor!(destroy_unseal_range_response, UnsealRangeResponse); +destructor!( + destroy_generate_piece_commitment_response, + GeneratePieceCommitmentResponse +); +destructor!( + destroy_generate_data_commitment_response, + GenerateDataCommitmentResponse +); +destructor!(destroy_string_response, StringResponse); +destructor!(destroy_verify_seal_response, VerifySealResponse); +destructor!( + destroy_verify_aggregate_seal_response, + VerifyAggregateSealProofResponse +); +destructor!(destroy_finalize_ticket_response, FinalizeTicketResponse); +destructor!( + destroy_verify_winning_post_response, + VerifyWinningPoStResponse +); +destructor!( + destroy_verify_window_post_response, + VerifyWindowPoStResponse +); +destructor!( + destroy_generate_fallback_sector_challenges_response, + GenerateFallbackSectorChallengesResponse +); +destructor!( + destroy_generate_single_vanilla_proof_response, + GenerateSingleVanillaProofResponse +); +destructor!( + destroy_generate_single_window_post_with_vanilla_response, + GenerateSingleWindowPoStWithVanillaResponse +); +destructor!( + destroy_get_num_partition_for_fallback_post_response, + GetNumPartitionForFallbackPoStResponse +); +destructor!( + destroy_merge_window_post_partition_proofs_response, + MergeWindowPoStPartitionProofsResponse +); +destructor!( + destroy_generate_winning_post_response, + GenerateWinningPoStResponse +); +destructor!( + destroy_generate_window_post_response, + GenerateWindowPoStResponse +); +destructor!( + destroy_generate_winning_post_sector_challenge, + GenerateWinningPoStSectorChallenge +); +destructor!(destroy_clear_cache_response, ClearCacheResponse); +destructor!(destroy_aggregate_proof, AggregateProof); +destructor!( + destroy_empty_sector_update_generate_proof_response, + EmptySectorUpdateProofResponse +); +destructor!( + destroy_empty_sector_update_verify_proof_response, + VerifyEmptySectorUpdateProofResponse +); +destructor!( + destroy_generate_empty_sector_update_partition_proof_response, + PartitionProofResponse +); +destructor!( + destroy_verify_empty_sector_update_partition_proof_response, + VerifyPartitionProofResponse +); +destructor!( + destroy_empty_sector_update_encode_into_response, + EmptySectorUpdateEncodeIntoResponse +); +destructor!( + destroy_empty_sector_update_decode_from_response, + EmptySectorUpdateDecodeFromResponse +); +destructor!( + destroy_empty_sector_update_remove_encoded_data_response, + EmptySectorUpdateRemoveEncodedDataResponse +); #[cfg(test)] pub mod tests { @@ -2374,18 +1318,19 @@ pub mod tests { use std::io::{Read, Seek, SeekFrom, Write}; use std::os::unix::io::IntoRawFd; use std::path::Path; + use std::str; use anyhow::{ensure, Error, Result}; - use ffi_toolkit::{c_str_to_rust_str, FCPResponseStatus}; + use log::info; use memmap::MmapOptions; use rand::{thread_rng, Rng}; + use crate::util::types::as_bytes; + use super::*; use fr32::bytes_into_fr; - use std::ffi::CStr; - // This is a test method for ensuring that the elements of 1 file - // matches the other. + /// This is a test method for ensuring that the elements of 1 file matches the other. pub fn compare_elements(path1: &Path, path2: &Path) -> Result<(), Error> { info!("Comparing elements between {:?} and {:?}", path1, path2); let f_data1 = OpenOptions::new().read(true).open(path1)?; @@ -2412,7 +1357,7 @@ pub mod tests { #[test] fn test_write_with_and_without_alignment() -> Result<()> { - let registered_proof = fil_RegisteredSealProof::StackedDrg2KiBV1; + let registered_proof = RegisteredSealProof::StackedDrg2KiBV1; // write some bytes to a temp file to be used as the byte source let mut rng = thread_rng(); @@ -2438,42 +1383,35 @@ pub mod tests { let dst_fd = dest.into_raw_fd(); // write the first file - unsafe { - let resp = fil_write_without_alignment(registered_proof, src_fd_a, 127, dst_fd); + { + let resp = unsafe { write_without_alignment(registered_proof, src_fd_a, 127, dst_fd) }; - if (*resp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp).error_msg); + if resp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp.error_msg).unwrap(); panic!("write_without_alignment failed: {:?}", msg); } assert_eq!( - (*resp).total_write_unpadded, - 127, + resp.total_write_unpadded, 127, "should have added 127 bytes of (unpadded) left alignment" ); } // write the second - unsafe { + { let existing = vec![127u64]; - let resp = fil_write_with_alignment( - registered_proof, - src_fd_b, - 508, - dst_fd, - existing.as_ptr(), - existing.len(), - ); + let resp = unsafe { + write_with_alignment(registered_proof, src_fd_b, 508, dst_fd, existing[..].into()) + }; - if (*resp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp).error_msg); + if resp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp.error_msg).unwrap(); panic!("write_with_alignment failed: {:?}", msg); } assert_eq!( - (*resp).left_alignment_unpadded, - 381, + resp.left_alignment_unpadded, 381, "should have added 381 bytes of (unpadded) left alignment" ); } @@ -2484,121 +1422,106 @@ pub mod tests { #[test] fn test_proof_types() { let seal_types = vec![ - fil_RegisteredSealProof::StackedDrg2KiBV1, - fil_RegisteredSealProof::StackedDrg8MiBV1, - fil_RegisteredSealProof::StackedDrg512MiBV1, - fil_RegisteredSealProof::StackedDrg32GiBV1, - fil_RegisteredSealProof::StackedDrg64GiBV1, - fil_RegisteredSealProof::StackedDrg2KiBV1_1, - fil_RegisteredSealProof::StackedDrg8MiBV1_1, - fil_RegisteredSealProof::StackedDrg512MiBV1_1, - fil_RegisteredSealProof::StackedDrg32GiBV1_1, - fil_RegisteredSealProof::StackedDrg64GiBV1_1, + RegisteredSealProof::StackedDrg2KiBV1, + RegisteredSealProof::StackedDrg8MiBV1, + RegisteredSealProof::StackedDrg512MiBV1, + RegisteredSealProof::StackedDrg32GiBV1, + RegisteredSealProof::StackedDrg64GiBV1, + RegisteredSealProof::StackedDrg2KiBV1_1, + RegisteredSealProof::StackedDrg8MiBV1_1, + RegisteredSealProof::StackedDrg512MiBV1_1, + RegisteredSealProof::StackedDrg32GiBV1_1, + RegisteredSealProof::StackedDrg64GiBV1_1, ]; let post_types = vec![ - fil_RegisteredPoStProof::StackedDrgWinning2KiBV1, - fil_RegisteredPoStProof::StackedDrgWinning8MiBV1, - fil_RegisteredPoStProof::StackedDrgWinning512MiBV1, - fil_RegisteredPoStProof::StackedDrgWinning32GiBV1, - fil_RegisteredPoStProof::StackedDrgWinning64GiBV1, - fil_RegisteredPoStProof::StackedDrgWindow2KiBV1, - fil_RegisteredPoStProof::StackedDrgWindow8MiBV1, - fil_RegisteredPoStProof::StackedDrgWindow512MiBV1, - fil_RegisteredPoStProof::StackedDrgWindow32GiBV1, - fil_RegisteredPoStProof::StackedDrgWindow64GiBV1, + RegisteredPoStProof::StackedDrgWinning2KiBV1, + RegisteredPoStProof::StackedDrgWinning8MiBV1, + RegisteredPoStProof::StackedDrgWinning512MiBV1, + RegisteredPoStProof::StackedDrgWinning32GiBV1, + RegisteredPoStProof::StackedDrgWinning64GiBV1, + RegisteredPoStProof::StackedDrgWindow2KiBV1, + RegisteredPoStProof::StackedDrgWindow8MiBV1, + RegisteredPoStProof::StackedDrgWindow512MiBV1, + RegisteredPoStProof::StackedDrgWindow32GiBV1, + RegisteredPoStProof::StackedDrgWindow64GiBV1, ]; let num_ops = (seal_types.len() + post_types.len()) * 6; - let mut pairs: Vec<(&str, *mut fil_StringResponse)> = Vec::with_capacity(num_ops); - - unsafe { - for st in seal_types { - pairs.push(("get_seal_params_cid", fil_get_seal_params_cid(st))); - pairs.push(( - "get_seal_verify_key_cid", - fil_get_seal_verifying_key_cid(st), - )); - pairs.push(("get_seal_verify_key_cid", fil_get_seal_params_path(st))); - pairs.push(( - "get_seal_verify_key_cid", - fil_get_seal_verifying_key_path(st), - )); - pairs.push(( - "get_seal_circuit_identifier", - fil_get_seal_circuit_identifier(st), - )); - pairs.push(("get_seal_version", fil_get_seal_version(st))); - } + let mut pairs = Vec::with_capacity(num_ops); + + for st in seal_types { + pairs.push(("get_seal_params_cid", get_seal_params_cid(st))); + pairs.push(("get_seal_verify_key_cid", get_seal_verifying_key_cid(st))); + pairs.push(("get_seal_verify_key_cid", get_seal_params_path(st))); + pairs.push(("get_seal_verify_key_cid", get_seal_verifying_key_path(st))); + pairs.push(( + "get_seal_circuit_identifier", + get_seal_circuit_identifier(st), + )); + pairs.push(("get_seal_version", get_seal_version(st))); + } - for pt in post_types { - pairs.push(("get_post_params_cid", fil_get_post_params_cid(pt))); - pairs.push(( - "get_post_verify_key_cid", - fil_get_post_verifying_key_cid(pt), - )); - pairs.push(("get_post_params_path", fil_get_post_params_path(pt))); - pairs.push(( - "get_post_verifying_key_path", - fil_get_post_verifying_key_path(pt), - )); - pairs.push(( - "get_post_circuit_identifier", - fil_get_post_circuit_identifier(pt), - )); - pairs.push(("get_post_version", fil_get_post_version(pt))); - } + for pt in post_types { + pairs.push(("get_post_params_cid", get_post_params_cid(pt))); + pairs.push(("get_post_verify_key_cid", get_post_verifying_key_cid(pt))); + pairs.push(("get_post_params_path", get_post_params_path(pt))); + pairs.push(( + "get_post_verifying_key_path", + get_post_verifying_key_path(pt), + )); + pairs.push(( + "get_post_circuit_identifier", + get_post_circuit_identifier(pt), + )); + pairs.push(("get_post_version", get_post_version(pt))); } for (label, r) in pairs { - unsafe { - assert_eq!( - (*r).status_code, - FCPResponseStatus::FCPNoError, - "non-success exit code from {:?}: {:?}", - label, - c_str_to_rust_str((*r).error_msg) - ); + assert_eq!( + r.status_code, + FCPResponseStatus::NoError, + "non-success exit code from {:?}: {:?}", + label, + str::from_utf8(&r.error_msg).unwrap() + ); - let x = CStr::from_ptr((*r).string_val); - let y = x.to_str().unwrap(); + let y = str::from_utf8(&r).unwrap(); - assert!(!y.is_empty()); + assert!(!y.is_empty()); - fil_destroy_string_response(r); - } + destroy_string_response(r); } } #[test] #[allow(clippy::cognitive_complexity)] fn test_sealing_v1() -> Result<()> { - test_sealing_inner(fil_RegisteredSealProof::StackedDrg2KiBV1) + test_sealing_inner(RegisteredSealProof::StackedDrg2KiBV1) } #[test] #[allow(clippy::cognitive_complexity)] fn test_sealing_v1_1() -> Result<()> { - test_sealing_inner(fil_RegisteredSealProof::StackedDrg2KiBV1_1) + test_sealing_inner(RegisteredSealProof::StackedDrg2KiBV1_1) } - fn test_sealing_inner(registered_proof_seal: fil_RegisteredSealProof) -> Result<()> { - let wrap = |x| fil_32ByteArray { inner: x }; - + fn test_sealing_inner(registered_proof_seal: RegisteredSealProof) -> Result<()> { // miscellaneous setup and shared values - let registered_proof_winning_post = fil_RegisteredPoStProof::StackedDrgWinning2KiBV1; - let registered_proof_window_post = fil_RegisteredPoStProof::StackedDrgWindow2KiBV1; + let registered_proof_winning_post = RegisteredPoStProof::StackedDrgWinning2KiBV1; + let registered_proof_window_post = RegisteredPoStProof::StackedDrgWindow2KiBV1; let cache_dir = tempfile::tempdir()?; let cache_dir_path = cache_dir.into_path(); + let cache_dir_path_ref = as_bytes(&cache_dir_path); - let prover_id = fil_32ByteArray { inner: [1u8; 32] }; - let randomness = fil_32ByteArray { inner: [7u8; 32] }; + let prover_id = [1u8; 32]; + let randomness = [7u8; 32]; let sector_id = 42; let sector_id2 = 43; - let seed = fil_32ByteArray { inner: [5u8; 32] }; - let ticket = fil_32ByteArray { inner: [6u8; 32] }; + let seed = [5u8; 32]; + let ticket = [6u8; 32]; // create a byte source (a user's piece) let mut rng = thread_rng(); @@ -2614,9 +1537,11 @@ pub mod tests { // create the staged sector (the byte destination) let (staged_file, staged_path) = tempfile::NamedTempFile::new()?.keep()?; + let staged_path_ref = as_bytes(&staged_path); // create a temp file to be used as the byte destination let (sealed_file, sealed_path) = tempfile::NamedTempFile::new()?.keep()?; + let sealed_path_ref = as_bytes(&sealed_path); // last temp file is used to output unsealed bytes let (unseal_file, unseal_path) = tempfile::NamedTempFile::new()?.keep()?; @@ -2626,177 +1551,159 @@ pub mod tests { let piece_file_b_fd = piece_file_b.into_raw_fd(); let staged_sector_fd = staged_file.into_raw_fd(); - unsafe { - let resp_a1 = fil_write_without_alignment( - registered_proof_seal, - piece_file_a_fd, - 127, - staged_sector_fd, - ); + { + let resp_a1 = unsafe { + write_without_alignment( + registered_proof_seal, + piece_file_a_fd, + 127, + staged_sector_fd, + ) + }; - if (*resp_a1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_a1).error_msg); + if resp_a1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_a1.error_msg).unwrap(); panic!("write_without_alignment failed: {:?}", msg); } let existing_piece_sizes = vec![127]; - let resp_a2 = fil_write_with_alignment( - registered_proof_seal, - piece_file_b_fd, - 1016, - staged_sector_fd, - existing_piece_sizes.as_ptr(), - existing_piece_sizes.len(), - ); + let resp_a2 = unsafe { + write_with_alignment( + registered_proof_seal, + piece_file_b_fd, + 1016, + staged_sector_fd, + existing_piece_sizes[..].into(), + ) + }; - if (*resp_a2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_a2).error_msg); + if resp_a2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_a2.error_msg).unwrap(); panic!("write_with_alignment failed: {:?}", msg); } let pieces = vec![ - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 127, - comm_p: (*resp_a1).comm_p, + comm_p: resp_a1.comm_p, }, - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 1016, - comm_p: (*resp_a2).comm_p, + comm_p: resp_a2.comm_p, }, ]; - let resp_x = - fil_generate_data_commitment(registered_proof_seal, pieces.as_ptr(), pieces.len()); + let resp_x = generate_data_commitment(registered_proof_seal, pieces[..].into()); - if (*resp_x).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_x).error_msg); + if resp_x.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_x.error_msg).unwrap(); panic!("generate_data_commitment failed: {:?}", msg); } - let cache_dir_path_c_str = rust_str_to_c_str(cache_dir_path.to_str().unwrap()); - let staged_path_c_str = rust_str_to_c_str(staged_path.to_str().unwrap()); - let replica_path_c_str = rust_str_to_c_str(sealed_path.to_str().unwrap()); - let unseal_path_c_str = rust_str_to_c_str(unseal_path.to_str().unwrap()); - - let resp_b1 = fil_seal_pre_commit_phase1( + let resp_b1 = seal_pre_commit_phase1( registered_proof_seal, - cache_dir_path_c_str, - staged_path_c_str, - replica_path_c_str, + cache_dir_path_ref.into(), + staged_path_ref.into(), + sealed_path_ref.into(), sector_id, - prover_id, - ticket, - pieces.as_ptr(), - pieces.len(), + &prover_id, + &ticket, + pieces[..].into(), ); - if (*resp_b1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_b1).error_msg); + if resp_b1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_b1.error_msg).unwrap(); panic!("seal_pre_commit_phase1 failed: {:?}", msg); } - let resp_b2 = fil_seal_pre_commit_phase2( - (*resp_b1).seal_pre_commit_phase1_output_ptr, - (*resp_b1).seal_pre_commit_phase1_output_len, - cache_dir_path_c_str, - replica_path_c_str, + let resp_b2 = seal_pre_commit_phase2( + resp_b1.as_ref(), + cache_dir_path_ref.into(), + sealed_path_ref.into(), ); - if (*resp_b2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_b2).error_msg); + if resp_b2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_b2.error_msg).unwrap(); panic!("seal_pre_commit_phase2 failed: {:?}", msg); } - let pre_computed_comm_d = &(*resp_x).comm_d; - let pre_commit_comm_d = &(*resp_b2).comm_d; + let pre_computed_comm_d: &[u8; 32] = &resp_x; + let pre_commit_comm_d: &[u8; 32] = &resp_b2.comm_d; assert_eq!( - format!("{:x?}", &pre_computed_comm_d), - format!("{:x?}", &pre_commit_comm_d), + format!("{:x?}", pre_computed_comm_d), + format!("{:x?}", pre_commit_comm_d), "pre-computed CommD and pre-commit CommD don't match" ); - let resp_c1 = fil_seal_commit_phase1( + let resp_c1 = seal_commit_phase1( registered_proof_seal, - wrap((*resp_b2).comm_r), - wrap((*resp_b2).comm_d), - cache_dir_path_c_str, - replica_path_c_str, + &resp_b2.comm_r, + &resp_b2.comm_d, + cache_dir_path_ref.into(), + sealed_path_ref.into(), sector_id, - prover_id, - ticket, - seed, - pieces.as_ptr(), - pieces.len(), + &prover_id, + &ticket, + &seed, + pieces[..].into(), ); - if (*resp_c1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_c1).error_msg); + if resp_c1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_c1.error_msg).unwrap(); panic!("seal_commit_phase1 failed: {:?}", msg); } - let resp_c2 = fil_seal_commit_phase2( - (*resp_c1).seal_commit_phase1_output_ptr, - (*resp_c1).seal_commit_phase1_output_len, - sector_id, - prover_id, - ); + let resp_c2 = seal_commit_phase2(resp_c1.as_ref(), sector_id, &prover_id); - if (*resp_c2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_c2).error_msg); + if resp_c2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_c2.error_msg).unwrap(); panic!("seal_commit_phase2 failed: {:?}", msg); } - let resp_d = fil_verify_seal( + let resp_d = verify_seal( registered_proof_seal, - wrap((*resp_b2).comm_r), - wrap((*resp_b2).comm_d), - prover_id, - ticket, - seed, + &resp_b2.comm_r, + &resp_b2.comm_d, + &prover_id, + &ticket, + &seed, sector_id, - (*resp_c2).proof_ptr, - (*resp_c2).proof_len, + resp_c2.as_ref(), ); - if (*resp_d).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_d).error_msg); + if resp_d.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_d.error_msg).unwrap(); panic!("seal_commit failed: {:?}", msg); } - assert!((*resp_d).is_valid, "proof was not valid"); + assert!(**resp_d, "proof was not valid"); - let resp_c22 = fil_seal_commit_phase2( - (*resp_c1).seal_commit_phase1_output_ptr, - (*resp_c1).seal_commit_phase1_output_len, - sector_id, - prover_id, - ); + let resp_c22 = seal_commit_phase2(resp_c1.as_ref(), sector_id, &prover_id); - if (*resp_c22).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_c22).error_msg); + if resp_c22.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_c22.error_msg).unwrap(); panic!("seal_commit_phase2 failed: {:?}", msg); } - let resp_d2 = fil_verify_seal( + let resp_d2 = verify_seal( registered_proof_seal, - wrap((*resp_b2).comm_r), - wrap((*resp_b2).comm_d), - prover_id, - ticket, - seed, + &resp_b2.comm_r, + &resp_b2.comm_d, + &prover_id, + &ticket, + &seed, sector_id, - (*resp_c22).proof_ptr, - (*resp_c22).proof_len, + resp_c22.as_ref(), ); - if (*resp_d2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_d2).error_msg); + if resp_d2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_d2.error_msg).unwrap(); panic!("seal_commit failed: {:?}", msg); } - assert!((*resp_d2).is_valid, "proof was not valid"); + assert!(**resp_d2, "proof was not valid"); ////////////////////////////////////////////////////////////////// // Begin Sector Upgrade testing @@ -2806,7 +1713,7 @@ pub mod tests { then finally remove the data and continue onward as normal. */ - let registered_proof_empty_sector_update = fil_RegisteredUpdateProof::StackedDrg2KiBV1; + let registered_proof_empty_sector_update = RegisteredUpdateProof::StackedDrg2KiBV1; let new_cache_dir = tempfile::tempdir()?; let new_cache_dir_path = new_cache_dir.into_path(); @@ -2836,63 +1743,62 @@ pub mod tests { let piece_file_d_fd = piece_file_d.into_raw_fd(); let new_staged_sector_fd = new_staged_file.into_raw_fd(); - let resp_new_a1 = fil_write_without_alignment( - registered_proof_seal, - piece_file_c_fd, - 127, - new_staged_sector_fd, - ); + let resp_new_a1 = unsafe { + write_without_alignment( + registered_proof_seal, + piece_file_c_fd, + 127, + new_staged_sector_fd, + ) + }; - if (*resp_new_a1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_new_a1).error_msg); + if resp_new_a1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_new_a1.error_msg).unwrap(); panic!("write_without_alignment failed: {:?}", msg); } let existing_piece_sizes = vec![127]; - let resp_new_a2 = fil_write_with_alignment( - registered_proof_seal, - piece_file_d_fd, - 1016, - new_staged_sector_fd, - existing_piece_sizes.as_ptr(), - existing_piece_sizes.len(), - ); + let resp_new_a2 = unsafe { + write_with_alignment( + registered_proof_seal, + piece_file_d_fd, + 1016, + new_staged_sector_fd, + existing_piece_sizes[..].into(), + ) + }; - if (*resp_new_a2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_new_a2).error_msg); + if resp_new_a2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_new_a2.error_msg).unwrap(); panic!("write_with_alignment failed: {:?}", msg); } let new_pieces = vec![ - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 127, - comm_p: (*resp_new_a1).comm_p, + comm_p: resp_new_a1.comm_p, }, - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 1016, - comm_p: (*resp_new_a2).comm_p, + comm_p: resp_new_a2.comm_p, }, - ]; + ] + .into_boxed_slice(); - let resp_new_x = fil_generate_data_commitment( - registered_proof_seal, - new_pieces.as_ptr(), - new_pieces.len(), - ); + let resp_new_x = generate_data_commitment(registered_proof_seal, new_pieces[..].into()); - if (*resp_new_x).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_new_x).error_msg); + if resp_new_x.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_new_x.error_msg).unwrap(); panic!("generate_data_commitment failed: {:?}", msg); } - let new_cache_dir_path_c_str = rust_str_to_c_str(new_cache_dir_path.to_str().unwrap()); - let new_staged_path_c_str = rust_str_to_c_str(new_staged_path.to_str().unwrap()); - let new_sealed_path_c_str = rust_str_to_c_str(new_sealed_path.to_str().unwrap()); - let decoded_path_c_str = rust_str_to_c_str(decoded_path.to_str().unwrap()); - let removed_data_path_c_str = rust_str_to_c_str(removed_data_path.to_str().unwrap()); - let removed_data_dir_path_c_str = - rust_str_to_c_str(removed_data_dir_path.to_str().unwrap()); + let new_cache_dir_path_ref = as_bytes(&new_cache_dir_path); + let new_staged_path_ref = as_bytes(&new_staged_path); + let new_sealed_path_ref = as_bytes(&new_sealed_path); + let decoded_path_ref = as_bytes(&decoded_path); + let removed_data_path_ref = as_bytes(&removed_data_path); + let removed_data_dir_path_ref = as_bytes(&removed_data_dir_path); // Set the new_sealed_file length to the same as the // original sealed file length (required for the API, but @@ -2905,66 +1811,63 @@ pub mod tests { .open(&new_sealed_path)?; f_new_sealed_sector.set_len(new_sealed_target_len)?; - let resp_encode = fil_empty_sector_update_encode_into( + let resp_encode = empty_sector_update_encode_into( registered_proof_empty_sector_update, - new_sealed_path_c_str, - new_cache_dir_path_c_str, - replica_path_c_str, - cache_dir_path_c_str, - new_staged_path_c_str, - new_pieces.as_ptr(), - new_pieces.len(), + new_sealed_path_ref.into(), + new_cache_dir_path_ref.into(), + sealed_path_ref.into(), + cache_dir_path_ref.into(), + new_staged_path_ref.into(), + new_pieces[..].into(), ); - if (*resp_encode).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_encode).error_msg); + if resp_encode.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_encode.error_msg).unwrap(); panic!("empty_sector_update_encode_into failed: {:?}", msg); } // First generate all vanilla partition proofs - let resp_partition_proofs = fil_generate_empty_sector_update_partition_proofs( + let resp_partition_proofs = generate_empty_sector_update_partition_proofs( registered_proof_empty_sector_update, - wrap((*resp_b2).comm_r), - wrap((*resp_encode).comm_r_new), - wrap((*resp_encode).comm_d_new), - replica_path_c_str, - cache_dir_path_c_str, - new_sealed_path_c_str, - new_cache_dir_path_c_str, + &resp_b2.comm_r, + &resp_encode.comm_r_new, + &resp_encode.comm_d_new, + sealed_path_ref.into(), + cache_dir_path_ref.into(), + new_sealed_path_ref.into(), + new_cache_dir_path_ref.into(), ); - if (*resp_partition_proofs).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_partition_proofs).error_msg); + if resp_partition_proofs.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_partition_proofs.error_msg).unwrap(); panic!("generate_partition_proofs failed: {:?}", msg); } // Verify vanilla partition proofs - let resp_verify_partition_proofs = fil_verify_empty_sector_update_partition_proofs( + let resp_verify_partition_proofs = verify_empty_sector_update_partition_proofs( registered_proof_empty_sector_update, - (*resp_partition_proofs).proofs_len, - (*resp_partition_proofs).proofs_ptr, - wrap((*resp_b2).comm_r), - wrap((*resp_encode).comm_r_new), - wrap((*resp_encode).comm_d_new), + resp_partition_proofs.as_ref(), + &resp_b2.comm_r, + &resp_encode.comm_r_new, + &resp_encode.comm_d_new, ); - if (*resp_verify_partition_proofs).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_verify_partition_proofs).error_msg); + if resp_verify_partition_proofs.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_verify_partition_proofs.error_msg).unwrap(); panic!("verify_partition_proofs failed: {:?}", msg); } // Then generate the sector update proof with the vanilla proofs - let resp_empty_sector_update = fil_generate_empty_sector_update_proof_with_vanilla( + let resp_empty_sector_update = generate_empty_sector_update_proof_with_vanilla( registered_proof_empty_sector_update, - (*resp_partition_proofs).proofs_ptr, - (*resp_partition_proofs).proofs_len, - wrap((*resp_b2).comm_r), - wrap((*resp_encode).comm_r_new), - wrap((*resp_encode).comm_d_new), + resp_partition_proofs.as_ref(), + &resp_b2.comm_r, + &resp_encode.comm_r_new, + &resp_encode.comm_d_new, ); - if (*resp_empty_sector_update).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_empty_sector_update).error_msg); + if resp_empty_sector_update.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_empty_sector_update.error_msg).unwrap(); panic!( "generate_empty_sector_update_proof_with_vanilla failed: {:?}", msg @@ -2972,48 +1875,46 @@ pub mod tests { } // And verify that sector update proof - let resp_verify_empty_sector_update = fil_verify_empty_sector_update_proof( + let resp_verify_empty_sector_update = verify_empty_sector_update_proof( registered_proof_empty_sector_update, - (*resp_empty_sector_update).proof_ptr, - (*resp_empty_sector_update).proof_len, - wrap((*resp_b2).comm_r), - wrap((*resp_encode).comm_r_new), - wrap((*resp_encode).comm_d_new), + resp_empty_sector_update.as_ref(), + &resp_b2.comm_r, + &resp_encode.comm_r_new, + &resp_encode.comm_d_new, ); - if (*resp_verify_empty_sector_update).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_verify_empty_sector_update).error_msg); + if resp_verify_empty_sector_update.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_verify_empty_sector_update.error_msg).unwrap(); panic!("verify_empty_sector_update_proof failed: {:?}", msg); } // Now re-generate the empty sector update monolithically (the vanilla proofs are generated internally) - let resp_empty_sector_update2 = fil_generate_empty_sector_update_proof( + let resp_empty_sector_update2 = generate_empty_sector_update_proof( registered_proof_empty_sector_update, - wrap((*resp_b2).comm_r), - wrap((*resp_encode).comm_r_new), - wrap((*resp_encode).comm_d_new), - replica_path_c_str, - cache_dir_path_c_str, - new_sealed_path_c_str, - new_cache_dir_path_c_str, + &resp_b2.comm_r, + &resp_encode.comm_r_new, + &resp_encode.comm_d_new, + sealed_path_ref.into(), + cache_dir_path_ref.into(), + new_sealed_path_ref.into(), + new_cache_dir_path_ref.into(), ); - if (*resp_empty_sector_update2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_empty_sector_update2).error_msg); + if resp_empty_sector_update2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_empty_sector_update2.error_msg).unwrap(); panic!("generate_empty_sector_update_proof failed: {:?}", msg); } - let resp_verify_empty_sector_update2 = fil_verify_empty_sector_update_proof( + let resp_verify_empty_sector_update2 = verify_empty_sector_update_proof( registered_proof_empty_sector_update, - (*resp_empty_sector_update2).proof_ptr, - (*resp_empty_sector_update2).proof_len, - wrap((*resp_b2).comm_r), - wrap((*resp_encode).comm_r_new), - wrap((*resp_encode).comm_d_new), + resp_empty_sector_update2.as_ref(), + &resp_b2.comm_r, + &resp_encode.comm_r_new, + &resp_encode.comm_d_new, ); - if (*resp_verify_empty_sector_update2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_verify_empty_sector_update2).error_msg); + if resp_verify_empty_sector_update2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_verify_empty_sector_update2.error_msg).unwrap(); panic!("verify_empty_sector_update_proof failed: {:?}", msg); } @@ -3027,17 +1928,17 @@ pub mod tests { .open(&decoded_path)?; f_decoded_sector.set_len(new_sealed_target_len)?; - let resp_decode = fil_empty_sector_update_decode_from( + let resp_decode = empty_sector_update_decode_from( registered_proof_empty_sector_update, - decoded_path_c_str, - new_sealed_path_c_str, - replica_path_c_str, - cache_dir_path_c_str, - wrap((*resp_encode).comm_d_new), + decoded_path_ref.into(), + new_sealed_path_ref.into(), + sealed_path_ref.into(), + cache_dir_path_ref.into(), + &resp_encode.comm_d_new, ); - if (*resp_decode).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_decode).error_msg); + if resp_decode.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_decode.error_msg).unwrap(); panic!("empty_sector_update_decode_from failed: {:?}", msg); } @@ -3054,43 +1955,41 @@ pub mod tests { .open(&removed_data_path)?; f_removed_data_sector.set_len(new_sealed_target_len)?; - let resp_removed = fil_empty_sector_update_remove_encoded_data( + let resp_removed = empty_sector_update_remove_encoded_data( registered_proof_empty_sector_update, - removed_data_path_c_str, - removed_data_dir_path_c_str, - new_sealed_path_c_str, // new sealed file path - cache_dir_path_c_str, // old replica dir path (for p_aux) - new_staged_path_c_str, // new staged file data path - wrap((*resp_encode).comm_d_new), + removed_data_path_ref.into(), + removed_data_dir_path_ref.into(), + new_sealed_path_ref.into(), // new sealed file path + cache_dir_path_ref.into(), // old replica dir path (for p_aux) + new_staged_path_ref.into(), // new staged file data path + &resp_encode.comm_d_new, ); - if (*resp_removed).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_removed).error_msg); + if resp_removed.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_removed.error_msg).unwrap(); panic!("empty_sector_update_remove_encoded_data failed: {:?}", msg); } // When the data is removed, it MUST match the original sealed data. compare_elements(&removed_data_path, &sealed_path)?; - fil_destroy_write_without_alignment_response(resp_new_a1); - fil_destroy_write_with_alignment_response(resp_new_a2); - fil_destroy_generate_data_commitment_response(resp_new_x); + destroy_write_without_alignment_response(resp_new_a1); + destroy_write_with_alignment_response(resp_new_a2); + destroy_generate_data_commitment_response(resp_new_x); - fil_destroy_empty_sector_update_encode_into_response(resp_encode); - fil_destroy_empty_sector_update_decode_from_response(resp_decode); - fil_destroy_empty_sector_update_remove_encoded_data_response(resp_removed); + destroy_empty_sector_update_encode_into_response(resp_encode); + destroy_empty_sector_update_decode_from_response(resp_decode); + destroy_empty_sector_update_remove_encoded_data_response(resp_removed); - fil_destroy_generate_empty_sector_update_partition_proof_response( - resp_partition_proofs, - ); - fil_destroy_verify_empty_sector_update_partition_proof_response( + destroy_generate_empty_sector_update_partition_proof_response(resp_partition_proofs); + destroy_verify_empty_sector_update_partition_proof_response( resp_verify_partition_proofs, ); - fil_destroy_empty_sector_update_generate_proof_response(resp_empty_sector_update); - fil_destroy_empty_sector_update_generate_proof_response(resp_empty_sector_update2); - fil_destroy_empty_sector_update_verify_proof_response(resp_verify_empty_sector_update); - fil_destroy_empty_sector_update_verify_proof_response(resp_verify_empty_sector_update2); + destroy_empty_sector_update_generate_proof_response(resp_empty_sector_update); + destroy_empty_sector_update_generate_proof_response(resp_empty_sector_update2); + destroy_empty_sector_update_verify_proof_response(resp_verify_empty_sector_update); + destroy_empty_sector_update_verify_proof_response(resp_verify_empty_sector_update2); ensure!( remove_file(&new_staged_path).is_ok(), @@ -3111,21 +2010,23 @@ pub mod tests { // End Sector Upgrade testing ////////////////////////////////////////////////////////////////// - let resp_e = fil_unseal_range( - registered_proof_seal, - cache_dir_path_c_str, - sealed_file.into_raw_fd(), - unseal_file.into_raw_fd(), - sector_id, - prover_id, - ticket, - wrap((*resp_b2).comm_d), - 0, - 2032, - ); + let resp_e = unsafe { + unseal_range( + registered_proof_seal, + cache_dir_path_ref.into(), + sealed_file.into_raw_fd(), + unseal_file.into_raw_fd(), + sector_id, + &prover_id, + &ticket, + &resp_b2.comm_d, + 0, + 2032, + ) + }; - if (*resp_e).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_e).error_msg); + if resp_e.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_e.error_msg).unwrap(); panic!("unseal failed: {:?}", msg); } @@ -3135,9 +2036,9 @@ pub mod tests { let _ = f.read_to_end(&mut buf_b)?; - let piece_a_len = (*resp_a1).total_write_unpadded as usize; - let piece_b_len = (*resp_a2).total_write_unpadded as usize; - let piece_b_prefix_len = (*resp_a2).left_alignment_unpadded as usize; + let piece_a_len = resp_a1.total_write_unpadded as usize; + let piece_b_len = resp_a2.total_write_unpadded as usize; + let piece_b_prefix_len = resp_a2.left_alignment_unpadded as usize; let alignment = vec![0; piece_b_prefix_len]; @@ -3157,68 +2058,64 @@ pub mod tests { // generate a PoSt let sectors = vec![sector_id]; - let resp_f = fil_generate_winning_post_sector_challenge( + let resp_f = generate_winning_post_sector_challenge( registered_proof_winning_post, - randomness, + &randomness, sectors.len() as u64, - prover_id, + &prover_id, ); - if (*resp_f).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_f).error_msg); - panic!("generate_candidates failed: {:?}", msg); + if resp_f.status_code != FCPResponseStatus::NoError { + panic!( + "generate_candidates failed: {}", + str::from_utf8(&resp_f.error_msg).unwrap() + ); } - // exercise the ticket-finalizing code path (but don't do anything - // with the results - let result: &[u64] = std::slice::from_raw_parts((*resp_f).ids_ptr, (*resp_f).ids_len); + // exercise the ticket-finalizing code path (but don't do anything with the results + let result: &[u64] = &resp_f; if result.is_empty() { panic!("generate_candidates produced no results"); } - let private_replicas = vec![fil_PrivateReplicaInfo { + let private_replicas = vec![PrivateReplicaInfo { registered_proof: registered_proof_winning_post, - cache_dir_path: cache_dir_path_c_str, - comm_r: (*resp_b2).comm_r, - replica_path: replica_path_c_str, + cache_dir_path: cache_dir_path_ref.to_vec().into_boxed_slice().into(), + comm_r: resp_b2.comm_r, + replica_path: sealed_path_ref.to_vec().into_boxed_slice().into(), sector_id, }]; // winning post - let resp_h = fil_generate_winning_post( - randomness, - private_replicas.as_ptr(), - private_replicas.len(), - prover_id, - ); + let resp_h = + generate_winning_post(&randomness, private_replicas[..].into(), &prover_id); - if (*resp_h).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_h).error_msg); + if resp_h.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_h.error_msg).unwrap(); panic!("generate_winning_post failed: {:?}", msg); } - let public_replicas = vec![fil_PublicReplicaInfo { + let public_replicas = vec![PublicReplicaInfo { registered_proof: registered_proof_winning_post, sector_id, - comm_r: (*resp_b2).comm_r, - }]; + comm_r: resp_b2.comm_r, + }] + .into_boxed_slice(); - let resp_i = fil_verify_winning_post( - randomness, - public_replicas.as_ptr(), - public_replicas.len(), - (*resp_h).proofs_ptr, - (*resp_h).proofs_len, - prover_id, + let resp_i = verify_winning_post( + &randomness, + public_replicas[..].into(), + resp_h.as_ref(), + &prover_id, ); - if (*resp_i).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_i).error_msg); + if resp_i.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_i.error_msg).unwrap(); panic!("verify_winning_post failed: {:?}", msg); } - if !(*resp_i).is_valid { + if !**resp_i { panic!("verify_winning_post rejected the provided proof as invalid"); } @@ -3232,137 +2129,113 @@ pub mod tests { ////////////////////////////////////////////// // First generate sector challenges. - let resp_sc = fil_generate_fallback_sector_challenges( + let resp_sc = generate_fallback_sector_challenges( registered_proof_winning_post, - randomness, - sectors.as_ptr(), - sectors.len(), - prover_id, + &randomness, + sectors[..].into(), + &prover_id, ); - if (*resp_sc).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_sc).error_msg); + if resp_sc.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_sc.error_msg).unwrap(); panic!("fallback_sector_challenges failed: {:?}", msg); } - let sector_ids: Vec = - std::slice::from_raw_parts((*resp_sc).ids_ptr, (*resp_sc).ids_len).to_vec(); - let sector_challenges: Vec = - std::slice::from_raw_parts((*resp_sc).challenges_ptr, (*resp_sc).challenges_len) - .to_vec(); - let challenges_stride = (*resp_sc).challenges_stride; - let challenge_iterations = sector_challenges.len() / challenges_stride; + let sector_ids: Vec = resp_sc.ids.to_vec(); + let sector_challenges: Vec<_> = resp_sc.challenges.to_vec(); assert_eq!( sector_ids.len(), - challenge_iterations, + sector_challenges.len(), "Challenge iterations must match the number of sector ids" ); - let mut vanilla_proofs: Vec = Vec::with_capacity(sector_ids.len()); + let mut vanilla_proofs: Vec = Vec::with_capacity(sector_ids.len()); // Gather up all vanilla proofs. - for i in 0..challenge_iterations { + for (i, challenges) in sector_challenges.iter().enumerate() { let sector_id = sector_ids[i]; - let challenges: Vec<_> = sector_challenges - [i * challenges_stride..i * challenges_stride + challenges_stride] - .to_vec(); let private_replica = private_replicas .iter() .find(|&replica| replica.sector_id == sector_id) .expect("failed to find private replica info") .clone(); - let resp_vp = fil_generate_single_vanilla_proof( - private_replica, - challenges.as_ptr(), - challenges.len(), - ); + let resp_vp = generate_single_vanilla_proof(private_replica, challenges.as_ref()); - if (*resp_vp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_vp).error_msg); + if resp_vp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_vp.error_msg).unwrap(); panic!("generate_single_vanilla_proof failed: {:?}", msg); } - vanilla_proofs.push((*resp_vp).vanilla_proof.clone()); - fil_destroy_generate_single_vanilla_proof_response(resp_vp); + vanilla_proofs.push(resp_vp.value.clone()); + destroy_generate_single_vanilla_proof_response(resp_vp); } - let resp_wpwv = fil_generate_winning_post_with_vanilla( + let resp_wpwv = generate_winning_post_with_vanilla( registered_proof_winning_post, - randomness, - prover_id, - vanilla_proofs.as_ptr(), - vanilla_proofs.len(), + &randomness, + &prover_id, + vanilla_proofs[..].into(), ); - if (*resp_wpwv).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_wpwv).error_msg); + if resp_wpwv.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_wpwv.error_msg).unwrap(); panic!("generate_winning_post_with_vanilla failed: {:?}", msg); } - // Verify the second winning post (generated by the - // distributed post API) - let resp_di = fil_verify_winning_post( - randomness, - public_replicas.as_ptr(), - public_replicas.len(), - (*resp_wpwv).proofs_ptr, - (*resp_wpwv).proofs_len, - prover_id, + // Verify the second winning post (generated by the distributed post API) + let resp_di = verify_winning_post( + &randomness, + public_replicas[..].into(), + resp_wpwv.as_ref(), + &prover_id, ); - if (*resp_di).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_di).error_msg); + if resp_di.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_di.error_msg).unwrap(); panic!("verify_winning_post failed: {:?}", msg); } - if !(*resp_di).is_valid { + if !**resp_di { panic!("verify_winning_post rejected the provided proof as invalid"); } // window post - let private_replicas = vec![fil_PrivateReplicaInfo { + let private_replicas = vec![PrivateReplicaInfo { registered_proof: registered_proof_window_post, - cache_dir_path: cache_dir_path_c_str, - comm_r: (*resp_b2).comm_r, - replica_path: replica_path_c_str, + cache_dir_path: cache_dir_path_ref.to_vec().into_boxed_slice().into(), + comm_r: resp_b2.comm_r, + replica_path: sealed_path_ref.to_vec().into_boxed_slice().into(), sector_id, }]; - let resp_j = fil_generate_window_post( - randomness, - private_replicas.as_ptr(), - private_replicas.len(), - prover_id, - ); + let resp_j = generate_window_post(&randomness, private_replicas[..].into(), &prover_id); - if (*resp_j).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_j).error_msg); + if resp_j.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_j.error_msg).unwrap(); panic!("generate_window_post failed: {:?}", msg); } - let public_replicas = vec![fil_PublicReplicaInfo { + let public_replicas = vec![PublicReplicaInfo { registered_proof: registered_proof_window_post, sector_id, - comm_r: (*resp_b2).comm_r, + comm_r: resp_b2.comm_r, }]; - let resp_k = fil_verify_window_post( - randomness, - public_replicas.as_ptr(), - public_replicas.len(), - (*resp_j).proofs_ptr, - (*resp_j).proofs_len, - prover_id, + let resp_k = verify_window_post( + &randomness, + public_replicas[..].into(), + resp_j.proofs.as_ref(), + &prover_id, ); - if (*resp_k).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_k).error_msg); + if resp_k.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_k.error_msg).unwrap(); panic!("verify_window_post failed: {:?}", msg); } - if !(*resp_k).is_valid { + if !**resp_k { panic!("verify_window_post rejected the provided proof as invalid"); } @@ -3377,69 +2250,61 @@ pub mod tests { let sectors = vec![sector_id, sector_id2]; let private_replicas = vec![ - fil_PrivateReplicaInfo { + PrivateReplicaInfo { registered_proof: registered_proof_window_post, - cache_dir_path: cache_dir_path_c_str, - comm_r: (*resp_b2).comm_r, - replica_path: replica_path_c_str, + cache_dir_path: cache_dir_path_ref.to_vec().into_boxed_slice().into(), + comm_r: resp_b2.comm_r, + replica_path: sealed_path_ref.to_vec().into_boxed_slice().into(), sector_id, }, - fil_PrivateReplicaInfo { + PrivateReplicaInfo { registered_proof: registered_proof_window_post, - cache_dir_path: cache_dir_path_c_str, - comm_r: (*resp_b2).comm_r, - replica_path: replica_path_c_str, + cache_dir_path: cache_dir_path_ref.to_vec().into_boxed_slice().into(), + comm_r: resp_b2.comm_r, + replica_path: sealed_path_ref.to_vec().into_boxed_slice().into(), sector_id: sector_id2, }, ]; let public_replicas = vec![ - fil_PublicReplicaInfo { + PublicReplicaInfo { registered_proof: registered_proof_window_post, sector_id, - comm_r: (*resp_b2).comm_r, + comm_r: resp_b2.comm_r, }, - fil_PublicReplicaInfo { + PublicReplicaInfo { registered_proof: registered_proof_window_post, sector_id: sector_id2, - comm_r: (*resp_b2).comm_r, + comm_r: resp_b2.comm_r, }, ]; // Generate sector challenges. - let resp_sc2 = fil_generate_fallback_sector_challenges( + let resp_sc2 = generate_fallback_sector_challenges( registered_proof_window_post, - randomness, - sectors.as_ptr(), - sectors.len(), - prover_id, + &randomness, + sectors[..].into(), + &prover_id, ); - if (*resp_sc2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_sc2).error_msg); + if resp_sc2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_sc2.error_msg).unwrap(); panic!("fallback_sector_challenges failed: {:?}", msg); } - let sector_ids: Vec = - std::slice::from_raw_parts((*resp_sc2).ids_ptr, (*resp_sc2).ids_len).to_vec(); - let sector_challenges: Vec = - std::slice::from_raw_parts((*resp_sc2).challenges_ptr, (*resp_sc2).challenges_len) - .to_vec(); - let challenges_stride = (*resp_sc2).challenges_stride; - let challenge_iterations = sector_challenges.len() / challenges_stride; + let sector_ids: Vec = resp_sc2.ids.to_vec(); + let sector_challenges: Vec<_> = resp_sc2.challenges.to_vec(); + assert_eq!( sector_ids.len(), - challenge_iterations, + sector_challenges.len(), "Challenge iterations must match the number of sector ids" ); - let mut vanilla_proofs: Vec = Vec::with_capacity(sector_ids.len()); + let mut vanilla_proofs: Vec = Vec::with_capacity(sector_ids.len()); // Gather up all vanilla proofs. - for i in 0..challenge_iterations { + for (i, challenges) in sector_challenges.iter().enumerate() { let sector_id = sector_ids[i]; - let challenges: Vec<_> = sector_challenges - [i * challenges_stride..i * challenges_stride + challenges_stride] - .to_vec(); let private_replica = private_replicas .iter() @@ -3447,49 +2312,42 @@ pub mod tests { .expect("failed to find private replica info") .clone(); - let resp_vp = fil_generate_single_vanilla_proof( - private_replica, - challenges.as_ptr(), - challenges.len(), - ); + let resp_vp = generate_single_vanilla_proof(private_replica, challenges.as_ref()); - if (*resp_vp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_vp).error_msg); + if resp_vp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_vp.error_msg).unwrap(); panic!("generate_single_vanilla_proof failed: {:?}", msg); } - vanilla_proofs.push((*resp_vp).vanilla_proof.clone()); - fil_destroy_generate_single_vanilla_proof_response(resp_vp); + vanilla_proofs.push(resp_vp.value.clone()); + destroy_generate_single_vanilla_proof_response(resp_vp); } - let resp_wpwv2 = fil_generate_window_post_with_vanilla( + let resp_wpwv2 = generate_window_post_with_vanilla( registered_proof_window_post, - randomness, - prover_id, - vanilla_proofs.as_ptr(), - vanilla_proofs.len(), + &randomness, + &prover_id, + vanilla_proofs[..].into(), ); - if (*resp_wpwv2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_wpwv2).error_msg); + if resp_wpwv2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_wpwv2.error_msg).unwrap(); panic!("generate_window_post_with_vanilla failed: {:?}", msg); } - let resp_k2 = fil_verify_window_post( - randomness, - public_replicas.as_ptr(), - public_replicas.len(), - (*resp_wpwv2).proofs_ptr, - (*resp_wpwv2).proofs_len, - prover_id, + let resp_k2 = verify_window_post( + &randomness, + public_replicas[..].into(), + resp_wpwv2.proofs.as_ref(), + &prover_id, ); - if (*resp_k2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_k2).error_msg); + if resp_k2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_k2.error_msg).unwrap(); panic!("verify_window_post failed: {:?}", msg); } - if !(*resp_k2).is_valid { + if !**resp_k2 { panic!("verify_window_post rejected the provided proof as invalid"); } @@ -3505,24 +2363,18 @@ pub mod tests { // Note: Re-using all of the sector challenges and types // required from above previous distributed PoSt API run. - let num_partitions_resp = fil_get_num_partition_for_fallback_post( - registered_proof_window_post, - sectors.len(), - ); - if (*num_partitions_resp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*num_partitions_resp).error_msg); + let num_partitions_resp = + get_num_partition_for_fallback_post(registered_proof_window_post, sectors.len()); + if num_partitions_resp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&num_partitions_resp.error_msg).unwrap(); panic!("get_num_partition_for_fallback_post failed: {:?}", msg); } - let mut partition_proofs: Vec = - Vec::with_capacity((*num_partitions_resp).num_partition); - for partition_index in 0..(*num_partitions_resp).num_partition { - let mut vanilla_proofs = Vec::with_capacity(challenge_iterations); - for i in 0..challenge_iterations { + let mut partition_proofs = Vec::with_capacity(**num_partitions_resp); + for partition_index in 0..**num_partitions_resp { + let mut vanilla_proofs = Vec::with_capacity(sector_challenges.len()); + for (i, challenges) in sector_challenges.iter().enumerate() { let sector_id = sector_ids[i]; - let challenges: Vec<_> = sector_challenges - [i * challenges_stride..i * challenges_stride + challenges_stride] - .to_vec(); let private_replica = private_replicas .iter() @@ -3530,108 +2382,96 @@ pub mod tests { .expect("failed to find private replica info") .clone(); - let resp_vp = fil_generate_single_vanilla_proof( - private_replica, - challenges.as_ptr(), - challenges.len(), - ); + let resp_vp = + generate_single_vanilla_proof(private_replica, challenges.as_ref()); - if (*resp_vp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_vp).error_msg); + if resp_vp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_vp.error_msg).unwrap(); panic!("generate_single_vanilla_proof failed: {:?}", msg); } - vanilla_proofs.push((*resp_vp).vanilla_proof.clone()); - fil_destroy_generate_single_vanilla_proof_response(resp_vp); + vanilla_proofs.push(resp_vp.value.clone()); + destroy_generate_single_vanilla_proof_response(resp_vp); } - let single_partition_proof_resp = fil_generate_single_window_post_with_vanilla( + let single_partition_proof_resp = generate_single_window_post_with_vanilla( registered_proof_window_post, - randomness, - prover_id, - vanilla_proofs.as_ptr(), - vanilla_proofs.len(), + &randomness, + &prover_id, + vanilla_proofs[..].into(), partition_index, ); - if (*single_partition_proof_resp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*single_partition_proof_resp).error_msg); + if single_partition_proof_resp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&single_partition_proof_resp.error_msg).unwrap(); panic!("generate_single_window_post_with_vanilla failed: {:?}", msg); } - partition_proofs.push((*single_partition_proof_resp).partition_proof.clone()); - fil_destroy_generate_single_window_post_with_vanilla_response( + partition_proofs.push(single_partition_proof_resp.partition_proof.proof.clone()); + destroy_generate_single_window_post_with_vanilla_response( single_partition_proof_resp, ); } - fil_destroy_get_num_partition_for_fallback_post_response(num_partitions_resp); + destroy_get_num_partition_for_fallback_post_response(num_partitions_resp); - let merged_proof_resp = fil_merge_window_post_partition_proofs( + let merged_proof_resp = merge_window_post_partition_proofs( registered_proof_window_post, - partition_proofs.as_ptr(), - partition_proofs.len(), + partition_proofs[..].into(), ); - if (*merged_proof_resp).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*merged_proof_resp).error_msg); + if merged_proof_resp.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&merged_proof_resp.error_msg).unwrap(); panic!("merge_window_post_partition_proofs failed: {:?}", msg); } - let resp_k3 = fil_verify_window_post( - randomness, - public_replicas.as_ptr(), - public_replicas.len(), - &(*merged_proof_resp).proof, - 1, /* len is 1, as it's a single window post proof once merged */ - prover_id, + let resp_k3 = verify_window_post( + &randomness, + public_replicas[..].into(), + vec![merged_proof_resp.value.clone()][..].into(), + &prover_id, ); - if (*resp_k3).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_k3).error_msg); + if resp_k3.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_k3.error_msg).unwrap(); panic!("verify_window_post failed: {:?}", msg); } - if !(*resp_k3).is_valid { + if !**resp_k3 { panic!("verify_window_post rejected the provided proof as invalid"); } - fil_destroy_merge_window_post_partition_proofs_response(merged_proof_resp); + destroy_merge_window_post_partition_proofs_response(merged_proof_resp); //////////////////// // Cleanup responses //////////////////// - fil_destroy_write_without_alignment_response(resp_a1); - fil_destroy_write_with_alignment_response(resp_a2); - fil_destroy_generate_data_commitment_response(resp_x); - - fil_destroy_seal_pre_commit_phase1_response(resp_b1); - fil_destroy_seal_pre_commit_phase2_response(resp_b2); - fil_destroy_seal_commit_phase1_response(resp_c1); - fil_destroy_seal_commit_phase2_response(resp_c2); - - fil_destroy_verify_seal_response(resp_d); - fil_destroy_unseal_range_response(resp_e); - - fil_destroy_generate_winning_post_sector_challenge(resp_f); - fil_destroy_generate_fallback_sector_challenges_response(resp_sc); - fil_destroy_generate_winning_post_response(resp_h); - fil_destroy_generate_winning_post_response(resp_wpwv); - fil_destroy_verify_winning_post_response(resp_i); - fil_destroy_verify_winning_post_response(resp_di); - - fil_destroy_generate_fallback_sector_challenges_response(resp_sc2); - fil_destroy_generate_window_post_response(resp_j); - fil_destroy_generate_window_post_response(resp_wpwv2); - fil_destroy_verify_window_post_response(resp_k); - fil_destroy_verify_window_post_response(resp_k2); - fil_destroy_verify_window_post_response(resp_k3); - - c_str_to_rust_str(cache_dir_path_c_str); - c_str_to_rust_str(staged_path_c_str); - c_str_to_rust_str(replica_path_c_str); - c_str_to_rust_str(unseal_path_c_str); + destroy_write_without_alignment_response(resp_a1); + destroy_write_with_alignment_response(resp_a2); + destroy_generate_data_commitment_response(resp_x); + + destroy_seal_pre_commit_phase1_response(resp_b1); + destroy_seal_pre_commit_phase2_response(resp_b2); + destroy_seal_commit_phase1_response(resp_c1); + destroy_seal_commit_phase2_response(resp_c2); + + destroy_verify_seal_response(resp_d); + destroy_unseal_range_response(resp_e); + + destroy_generate_winning_post_sector_challenge(resp_f); + destroy_generate_fallback_sector_challenges_response(resp_sc); + destroy_generate_winning_post_response(resp_h); + destroy_generate_winning_post_response(resp_wpwv); + destroy_verify_winning_post_response(resp_i); + destroy_verify_winning_post_response(resp_di); + + destroy_generate_fallback_sector_challenges_response(resp_sc2); + destroy_generate_window_post_response(resp_j); + destroy_generate_window_post_response(resp_wpwv2); + destroy_verify_window_post_response(resp_k); + destroy_verify_window_post_response(resp_k2); + destroy_verify_window_post_response(resp_k3); ensure!( remove_file(&staged_path).is_ok(), @@ -3652,25 +2492,26 @@ pub mod tests { #[test] fn test_faulty_sectors_v1() -> Result<()> { - test_faulty_sectors_inner(fil_RegisteredSealProof::StackedDrg2KiBV1) + test_faulty_sectors_inner(RegisteredSealProof::StackedDrg2KiBV1) } #[test] fn test_faulty_sectors_v1_1() -> Result<()> { - test_faulty_sectors_inner(fil_RegisteredSealProof::StackedDrg2KiBV1_1) + test_faulty_sectors_inner(RegisteredSealProof::StackedDrg2KiBV1_1) } - fn test_faulty_sectors_inner(registered_proof_seal: fil_RegisteredSealProof) -> Result<()> { + fn test_faulty_sectors_inner(registered_proof_seal: RegisteredSealProof) -> Result<()> { // miscellaneous setup and shared values - let registered_proof_window_post = fil_RegisteredPoStProof::StackedDrgWindow2KiBV1; + let registered_proof_window_post = RegisteredPoStProof::StackedDrgWindow2KiBV1; let cache_dir = tempfile::tempdir()?; let cache_dir_path = cache_dir.into_path(); + let cache_dir_path_ref = as_bytes(&cache_dir_path); - let prover_id = fil_32ByteArray { inner: [1u8; 32] }; - let randomness = fil_32ByteArray { inner: [7u8; 32] }; + let prover_id = [1u8; 32]; + let randomness = [7u8; 32]; let sector_id = 42; - let ticket = fil_32ByteArray { inner: [6u8; 32] }; + let ticket = [6u8; 32]; // create a byte source (a user's piece) let mut rng = thread_rng(); @@ -3686,140 +2527,125 @@ pub mod tests { // create the staged sector (the byte destination) let (staged_file, staged_path) = tempfile::NamedTempFile::new()?.keep()?; + let staged_path_ref = as_bytes(&staged_path); // create a temp file to be used as the byte destination let (_sealed_file, sealed_path) = tempfile::NamedTempFile::new()?.keep()?; + let sealed_path_ref = as_bytes(&sealed_path); // transmute temp files to file descriptors let piece_file_a_fd = piece_file_a.into_raw_fd(); let piece_file_b_fd = piece_file_b.into_raw_fd(); let staged_sector_fd = staged_file.into_raw_fd(); - unsafe { - let resp_a1 = fil_write_without_alignment( - registered_proof_seal, - piece_file_a_fd, - 127, - staged_sector_fd, - ); + { + let resp_a1 = unsafe { + write_without_alignment( + registered_proof_seal, + piece_file_a_fd, + 127, + staged_sector_fd, + ) + }; - if (*resp_a1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_a1).error_msg); + if resp_a1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_a1.error_msg).unwrap(); panic!("write_without_alignment failed: {:?}", msg); } let existing_piece_sizes = vec![127]; - let resp_a2 = fil_write_with_alignment( - registered_proof_seal, - piece_file_b_fd, - 1016, - staged_sector_fd, - existing_piece_sizes.as_ptr(), - existing_piece_sizes.len(), - ); + let resp_a2 = unsafe { + write_with_alignment( + registered_proof_seal, + piece_file_b_fd, + 1016, + staged_sector_fd, + existing_piece_sizes[..].into(), + ) + }; - if (*resp_a2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_a2).error_msg); + if resp_a2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_a2.error_msg).unwrap(); panic!("write_with_alignment failed: {:?}", msg); } let pieces = vec![ - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 127, - comm_p: (*resp_a1).comm_p, + comm_p: resp_a1.comm_p, }, - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 1016, - comm_p: (*resp_a2).comm_p, + comm_p: resp_a2.comm_p, }, ]; - let resp_x = - fil_generate_data_commitment(registered_proof_seal, pieces.as_ptr(), pieces.len()); + let resp_x = generate_data_commitment(registered_proof_seal, pieces[..].into()); - if (*resp_x).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_x).error_msg); + if resp_x.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_x.error_msg).unwrap(); panic!("generate_data_commitment failed: {:?}", msg); } - let cache_dir_path_c_str = rust_str_to_c_str(cache_dir_path.to_str().unwrap()); - let staged_path_c_str = rust_str_to_c_str(staged_path.to_str().unwrap()); - let replica_path_c_str = rust_str_to_c_str(sealed_path.to_str().unwrap()); - - let resp_b1 = fil_seal_pre_commit_phase1( + let resp_b1 = seal_pre_commit_phase1( registered_proof_seal, - cache_dir_path_c_str, - staged_path_c_str, - replica_path_c_str, + cache_dir_path_ref.into(), + staged_path_ref.into(), + sealed_path_ref.into(), sector_id, - prover_id, - ticket, - pieces.as_ptr(), - pieces.len(), + &prover_id, + &ticket, + pieces[..].into(), ); - if (*resp_b1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_b1).error_msg); + if resp_b1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_b1.error_msg).unwrap(); panic!("seal_pre_commit_phase1 failed: {:?}", msg); } - let resp_b2 = fil_seal_pre_commit_phase2( - (*resp_b1).seal_pre_commit_phase1_output_ptr, - (*resp_b1).seal_pre_commit_phase1_output_len, - cache_dir_path_c_str, - replica_path_c_str, + let resp_b2 = seal_pre_commit_phase2( + resp_b1.as_ref(), + cache_dir_path_ref.into(), + sealed_path_ref.into(), ); - if (*resp_b2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_b2).error_msg); + if resp_b2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_b2.error_msg).unwrap(); panic!("seal_pre_commit_phase2 failed: {:?}", msg); } // window post let faulty_sealed_file = tempfile::NamedTempFile::new()?; - let faulty_replica_path_c_str = - rust_str_to_c_str(faulty_sealed_file.path().to_str().unwrap()); + let faulty_sealed_path_ref = as_bytes(faulty_sealed_file.path()); - let private_replicas = vec![fil_PrivateReplicaInfo { + let private_replicas = vec![PrivateReplicaInfo { registered_proof: registered_proof_window_post, - cache_dir_path: cache_dir_path_c_str, - comm_r: (*resp_b2).comm_r, - replica_path: faulty_replica_path_c_str, + cache_dir_path: cache_dir_path_ref.to_vec().into_boxed_slice().into(), + comm_r: resp_b2.comm_r, + replica_path: faulty_sealed_path_ref.to_vec().into_boxed_slice().into(), sector_id, }]; - let resp_j = fil_generate_window_post( - randomness, - private_replicas.as_ptr(), - private_replicas.len(), - prover_id, - ); + let resp_j = generate_window_post(&randomness, private_replicas[..].into(), &prover_id); assert_eq!( - (*resp_j).status_code, - FCPResponseStatus::FCPUnclassifiedError, + resp_j.status_code, + FCPResponseStatus::UnclassifiedError, "generate_window_post should have failed" ); - let faulty_sectors: &[u64] = std::slice::from_raw_parts( - (*resp_j).faulty_sectors_ptr, - (*resp_j).faulty_sectors_len, - ); + let faulty_sectors: &[u64] = &resp_j.faulty_sectors; assert_eq!(faulty_sectors, &[42], "sector 42 should be faulty"); - fil_destroy_write_without_alignment_response(resp_a1); - fil_destroy_write_with_alignment_response(resp_a2); + destroy_write_without_alignment_response(resp_a1); + destroy_write_with_alignment_response(resp_a2); - fil_destroy_seal_pre_commit_phase1_response(resp_b1); - fil_destroy_seal_pre_commit_phase2_response(resp_b2); + destroy_seal_pre_commit_phase1_response(resp_b1); + destroy_seal_pre_commit_phase2_response(resp_b2); - fil_destroy_generate_window_post_response(resp_j); - - c_str_to_rust_str(cache_dir_path_c_str); - c_str_to_rust_str(staged_path_c_str); - c_str_to_rust_str(replica_path_c_str); + destroy_generate_window_post_response(resp_j); ensure!( remove_file(&staged_path).is_ok(), @@ -3838,8 +2664,8 @@ pub mod tests { #[ignore] fn test_sealing_aggregation_v1() -> Result<()> { test_sealing_aggregation( - fil_RegisteredSealProof::StackedDrg2KiBV1, - fil_RegisteredAggregationProof::SnarkPackV1, + RegisteredSealProof::StackedDrg2KiBV1, + RegisteredAggregationProof::SnarkPackV1, ) } @@ -3847,25 +2673,24 @@ pub mod tests { #[ignore] fn test_sealing_aggregation_v1_1() -> Result<()> { test_sealing_aggregation( - fil_RegisteredSealProof::StackedDrg2KiBV1_1, - fil_RegisteredAggregationProof::SnarkPackV1, + RegisteredSealProof::StackedDrg2KiBV1_1, + RegisteredAggregationProof::SnarkPackV1, ) } fn test_sealing_aggregation( - registered_proof_seal: fil_RegisteredSealProof, - registered_aggregation: fil_RegisteredAggregationProof, + registered_proof_seal: RegisteredSealProof, + registered_aggregation: RegisteredAggregationProof, ) -> Result<()> { - let wrap = |x| fil_32ByteArray { inner: x }; - // miscellaneous setup and shared values let cache_dir = tempfile::tempdir()?; let cache_dir_path = cache_dir.into_path(); + let cache_dir_path_ref = as_bytes(&cache_dir_path); - let prover_id = fil_32ByteArray { inner: [1u8; 32] }; + let prover_id = [1u8; 32]; let sector_id = 42; - let seed = fil_32ByteArray { inner: [5u8; 32] }; - let ticket = fil_32ByteArray { inner: [6u8; 32] }; + let seed = [5u8; 32]; + let ticket = [6u8; 32]; // create a byte source (a user's piece) let mut rng = thread_rng(); @@ -3881,98 +2706,96 @@ pub mod tests { // create the staged sector (the byte destination) let (staged_file, staged_path) = tempfile::NamedTempFile::new()?.keep()?; + let staged_path_ref = as_bytes(&staged_path); // create a temp file to be used as the byte destination let (_sealed_file, sealed_path) = tempfile::NamedTempFile::new()?.keep()?; + let sealed_path_ref = as_bytes(&sealed_path); // transmute temp files to file descriptors let piece_file_a_fd = piece_file_a.into_raw_fd(); let piece_file_b_fd = piece_file_b.into_raw_fd(); let staged_sector_fd = staged_file.into_raw_fd(); - unsafe { - let resp_a1 = fil_write_without_alignment( - registered_proof_seal, - piece_file_a_fd, - 127, - staged_sector_fd, - ); + { + let resp_a1 = unsafe { + write_without_alignment( + registered_proof_seal, + piece_file_a_fd, + 127, + staged_sector_fd, + ) + }; - if (*resp_a1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_a1).error_msg); + if resp_a1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_a1.error_msg).unwrap(); panic!("write_without_alignment failed: {:?}", msg); } let existing_piece_sizes = vec![127]; - let resp_a2 = fil_write_with_alignment( - registered_proof_seal, - piece_file_b_fd, - 1016, - staged_sector_fd, - existing_piece_sizes.as_ptr(), - existing_piece_sizes.len(), - ); + let resp_a2 = unsafe { + write_with_alignment( + registered_proof_seal, + piece_file_b_fd, + 1016, + staged_sector_fd, + existing_piece_sizes[..].into(), + ) + }; - if (*resp_a2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_a2).error_msg); + if resp_a2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_a2.error_msg).unwrap(); panic!("write_with_alignment failed: {:?}", msg); } let pieces = vec![ - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 127, - comm_p: (*resp_a1).comm_p, + comm_p: resp_a1.comm_p, }, - fil_PublicPieceInfo { + PublicPieceInfo { num_bytes: 1016, - comm_p: (*resp_a2).comm_p, + comm_p: resp_a2.comm_p, }, ]; - let resp_x = - fil_generate_data_commitment(registered_proof_seal, pieces.as_ptr(), pieces.len()); + let resp_x = generate_data_commitment(registered_proof_seal, pieces[..].into()); - if (*resp_x).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_x).error_msg); + if resp_x.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_x.error_msg).unwrap(); panic!("generate_data_commitment failed: {:?}", msg); } - let cache_dir_path_c_str = rust_str_to_c_str(cache_dir_path.to_str().unwrap()); - let staged_path_c_str = rust_str_to_c_str(staged_path.to_str().unwrap()); - let replica_path_c_str = rust_str_to_c_str(sealed_path.to_str().unwrap()); - - let resp_b1 = fil_seal_pre_commit_phase1( + let resp_b1 = seal_pre_commit_phase1( registered_proof_seal, - cache_dir_path_c_str, - staged_path_c_str, - replica_path_c_str, + cache_dir_path_ref.into(), + staged_path_ref.into(), + sealed_path_ref.into(), sector_id, - prover_id, - ticket, - pieces.as_ptr(), - pieces.len(), + &prover_id, + &ticket, + pieces[..].into(), ); - if (*resp_b1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_b1).error_msg); + if resp_b1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_b1.error_msg).unwrap(); panic!("seal_pre_commit_phase1 failed: {:?}", msg); } - let resp_b2 = fil_seal_pre_commit_phase2( - (*resp_b1).seal_pre_commit_phase1_output_ptr, - (*resp_b1).seal_pre_commit_phase1_output_len, - cache_dir_path_c_str, - replica_path_c_str, + let resp_b2 = seal_pre_commit_phase2( + resp_b1.as_ref(), + cache_dir_path_ref.into(), + sealed_path_ref.into(), ); - if (*resp_b2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_b2).error_msg); + if resp_b2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_b2.error_msg).unwrap(); panic!("seal_pre_commit_phase2 failed: {:?}", msg); } - let pre_computed_comm_d = &(*resp_x).comm_d; - let pre_commit_comm_d = &(*resp_b2).comm_d; + let pre_computed_comm_d: &[u8; 32] = &resp_x; + let pre_commit_comm_d: &[u8; 32] = &resp_b2.comm_d; assert_eq!( format!("{:x?}", &pre_computed_comm_d), @@ -3980,173 +2803,142 @@ pub mod tests { "pre-computed CommD and pre-commit CommD don't match" ); - let resp_c1 = fil_seal_commit_phase1( + let resp_c1 = seal_commit_phase1( registered_proof_seal, - wrap((*resp_b2).comm_r), - wrap((*resp_b2).comm_d), - cache_dir_path_c_str, - replica_path_c_str, + &resp_b2.comm_r, + &resp_b2.comm_d, + cache_dir_path_ref.into(), + sealed_path_ref.into(), sector_id, - prover_id, - ticket, - seed, - pieces.as_ptr(), - pieces.len(), + &prover_id, + &ticket, + &seed, + pieces[..].into(), ); - if (*resp_c1).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_c1).error_msg); + if resp_c1.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_c1.error_msg).unwrap(); panic!("seal_commit_phase1 failed: {:?}", msg); } - let resp_c2 = fil_seal_commit_phase2( - (*resp_c1).seal_commit_phase1_output_ptr, - (*resp_c1).seal_commit_phase1_output_len, - sector_id, - prover_id, - ); + let resp_c2 = seal_commit_phase2(resp_c1.as_ref(), sector_id, &prover_id); - if (*resp_c2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_c2).error_msg); + if resp_c2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_c2.error_msg).unwrap(); panic!("seal_commit_phase2 failed: {:?}", msg); } - let resp_d = fil_verify_seal( + let resp_d = verify_seal( registered_proof_seal, - wrap((*resp_b2).comm_r), - wrap((*resp_b2).comm_d), - prover_id, - ticket, - seed, + &resp_b2.comm_r, + &resp_b2.comm_d, + &prover_id, + &ticket, + &seed, sector_id, - (*resp_c2).proof_ptr, - (*resp_c2).proof_len, + resp_c2.as_ref(), ); - if (*resp_d).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_d).error_msg); + if resp_d.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_d.error_msg).unwrap(); panic!("seal_commit failed: {:?}", msg); } - assert!((*resp_d).is_valid, "proof was not valid"); + assert!(**resp_d, "proof was not valid"); - let resp_c22 = fil_seal_commit_phase2( - (*resp_c1).seal_commit_phase1_output_ptr, - (*resp_c1).seal_commit_phase1_output_len, - sector_id, - prover_id, - ); + let resp_c22 = seal_commit_phase2(resp_c1.as_ref(), sector_id, &prover_id); - if (*resp_c22).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_c22).error_msg); + if resp_c22.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_c22.error_msg).unwrap(); panic!("seal_commit_phase2 failed: {:?}", msg); } - let resp_d2 = fil_verify_seal( + let resp_d2 = verify_seal( registered_proof_seal, - wrap((*resp_b2).comm_r), - wrap((*resp_b2).comm_d), - prover_id, - ticket, - seed, + &resp_b2.comm_r, + &resp_b2.comm_d, + &prover_id, + &ticket, + &seed, sector_id, - (*resp_c22).proof_ptr, - (*resp_c22).proof_len, + resp_c22.as_ref(), ); - if (*resp_d2).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_d2).error_msg); + if resp_d2.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_d2.error_msg).unwrap(); panic!("seal_commit failed: {:?}", msg); } - assert!((*resp_d2).is_valid, "proof was not valid"); + assert!(**resp_d2, "proof was not valid"); - let seal_commit_responses: Vec = - vec![(*resp_c2).clone(), (*resp_c22).clone()]; + let seal_commit_responses = vec![resp_c2.value.clone(), resp_c22.value.clone()]; - let comm_rs = vec![ - fil_32ByteArray { - inner: (*resp_b2).comm_r, - }, - fil_32ByteArray { - inner: (*resp_b2).comm_r, - }, - ]; + let comm_rs = vec![resp_b2.comm_r, resp_b2.comm_r]; let seeds = vec![seed, seed]; - let resp_aggregate_proof = fil_aggregate_seal_proofs( + let resp_aggregate_proof = aggregate_seal_proofs( registered_proof_seal, registered_aggregation, - comm_rs.as_ptr(), - comm_rs.len(), - seeds.as_ptr(), - seeds.len(), - seal_commit_responses.as_ptr(), - seal_commit_responses.len(), + comm_rs[..].into(), + seeds[..].into(), + seal_commit_responses[..].into(), ); - if (*resp_aggregate_proof).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_aggregate_proof).error_msg); - panic!("aggregate_seal_proofs failed: {:?}", msg); + if resp_aggregate_proof.status_code != FCPResponseStatus::NoError { + panic!( + "aggregate_seal_proofs failed: {}", + str::from_utf8(&resp_aggregate_proof.error_msg).unwrap() + ); } - let mut inputs: Vec = vec![ - fil_AggregationInputs { - comm_r: wrap((*resp_b2).comm_r), - comm_d: wrap((*resp_b2).comm_d), + let inputs: Vec = vec![ + AggregationInputs { + comm_r: resp_b2.comm_r, + comm_d: resp_b2.comm_d, sector_id, ticket, seed, }, - fil_AggregationInputs { - comm_r: wrap((*resp_b2).comm_r), - comm_d: wrap((*resp_b2).comm_d), + AggregationInputs { + comm_r: resp_b2.comm_r, + comm_d: resp_b2.comm_d, sector_id, ticket, seed, }, ]; - let resp_ad = fil_verify_aggregate_seal_proof( + let resp_ad = verify_aggregate_seal_proof( registered_proof_seal, registered_aggregation, - prover_id, - (*resp_aggregate_proof).proof_ptr, - (*resp_aggregate_proof).proof_len, - inputs.as_mut_ptr(), - inputs.len(), + &prover_id, + resp_aggregate_proof.as_ref(), + inputs[..].into(), ); - if (*resp_ad).status_code != FCPResponseStatus::FCPNoError { - let msg = c_str_to_rust_str((*resp_ad).error_msg); + if resp_ad.status_code != FCPResponseStatus::NoError { + let msg = str::from_utf8(&resp_ad.error_msg).unwrap(); panic!("verify_aggregate_seal_proof failed: {:?}", msg); } - assert!((*resp_ad).is_valid, "aggregated proof was not valid"); - - fil_destroy_write_without_alignment_response(resp_a1); - fil_destroy_write_with_alignment_response(resp_a2); - fil_destroy_generate_data_commitment_response(resp_x); - - fil_destroy_seal_pre_commit_phase1_response(resp_b1); - fil_destroy_seal_pre_commit_phase2_response(resp_b2); - fil_destroy_seal_commit_phase1_response(resp_c1); + assert!(**resp_ad, "aggregated proof was not valid"); - fil_destroy_seal_commit_phase2_response(resp_c2); - fil_destroy_seal_commit_phase2_response(resp_c22); + destroy_write_without_alignment_response(resp_a1); + destroy_write_with_alignment_response(resp_a2); + destroy_generate_data_commitment_response(resp_x); - fil_destroy_verify_seal_response(resp_d); - fil_destroy_verify_seal_response(resp_d2); + destroy_seal_pre_commit_phase1_response(resp_b1); + destroy_seal_pre_commit_phase2_response(resp_b2); + destroy_seal_commit_phase1_response(resp_c1); - fil_destroy_verify_aggregate_seal_response(resp_ad); + destroy_seal_commit_phase2_response(resp_c2); + destroy_seal_commit_phase2_response(resp_c22); - //fil_destroy_aggregation_inputs_response(resp_c2_inputs); - //fil_destroy_aggregation_inputs_response(resp_c22_inputs); + destroy_verify_seal_response(resp_d); + destroy_verify_seal_response(resp_d2); - fil_destroy_aggregate_proof(resp_aggregate_proof); + destroy_verify_aggregate_seal_response(resp_ad); - c_str_to_rust_str(cache_dir_path_c_str); - c_str_to_rust_str(staged_path_c_str); - c_str_to_rust_str(replica_path_c_str); + destroy_aggregate_proof(resp_aggregate_proof); ensure!( remove_file(&staged_path).is_ok(), diff --git a/rust/src/proofs/helpers.rs b/rust/src/proofs/helpers.rs index 846c8a99..f70a003c 100644 --- a/rust/src/proofs/helpers.rs +++ b/rust/src/proofs/helpers.rs @@ -1,44 +1,34 @@ use std::collections::btree_map::BTreeMap; -use std::path::PathBuf; -use std::slice::from_raw_parts; -use anyhow::{ensure, Result}; -use ffi_toolkit::{c_str_to_pbuf, c_str_to_rust_str}; -use filecoin_proofs_api::{PrivateReplicaInfo, PublicReplicaInfo, SectorId}; +use anyhow::Result; +use filecoin_proofs_api::{self as api, SectorId}; +use safer_ffi::prelude::*; -use super::types::{fil_PrivateReplicaInfo, fil_PublicReplicaInfo, fil_RegisteredPoStProof}; -use crate::proofs::types::{ - fil_PartitionProof, fil_PartitionSnarkProof, fil_PoStProof, PartitionProof, - PartitionSnarkProof, PoStProof, -}; +use super::types::{PrivateReplicaInfo, PublicReplicaInfo, RegisteredPoStProof}; +use crate::util::types::as_path_buf; #[derive(Debug, Clone)] struct PublicReplicaInfoTmp { - pub registered_proof: fil_RegisteredPoStProof, + pub registered_proof: RegisteredPoStProof, pub comm_r: [u8; 32], pub sector_id: u64, } -#[allow(clippy::type_complexity)] -pub unsafe fn to_public_replica_info_map( - replicas_ptr: *const fil_PublicReplicaInfo, - replicas_len: libc::size_t, -) -> Result> { +pub fn to_public_replica_info_map( + replicas: c_slice::Ref, +) -> BTreeMap { use rayon::prelude::*; - ensure!(!replicas_ptr.is_null(), "replicas_ptr must not be null"); - - let mut replicas = Vec::new(); - - for ffi_info in from_raw_parts(replicas_ptr, replicas_len) { - replicas.push(PublicReplicaInfoTmp { + let replicas = replicas + .iter() + .map(|ffi_info| PublicReplicaInfoTmp { sector_id: ffi_info.sector_id, registered_proof: ffi_info.registered_proof, comm_r: ffi_info.comm_r, - }); - } + }) + .collect::>(); - let map = replicas + replicas .into_par_iter() .map(|info| { let PublicReplicaInfoTmp { @@ -49,46 +39,41 @@ pub unsafe fn to_public_replica_info_map( ( SectorId::from(sector_id), - PublicReplicaInfo::new(registered_proof.into(), comm_r), + api::PublicReplicaInfo::new(registered_proof.into(), comm_r), ) }) - .collect(); - - Ok(map) + .collect() } #[derive(Debug, Clone)] struct PrivateReplicaInfoTmp { - pub registered_proof: fil_RegisteredPoStProof, + pub registered_proof: RegisteredPoStProof, pub cache_dir_path: std::path::PathBuf, pub comm_r: [u8; 32], pub replica_path: std::path::PathBuf, pub sector_id: u64, } -pub unsafe fn to_private_replica_info_map( - replicas_ptr: *const fil_PrivateReplicaInfo, - replicas_len: libc::size_t, -) -> Result> { +pub fn to_private_replica_info_map( + replicas: c_slice::Ref, +) -> Result> { use rayon::prelude::*; - ensure!(!replicas_ptr.is_null(), "replicas_ptr must not be null"); - - let replicas: Vec<_> = from_raw_parts(replicas_ptr, replicas_len) + let replicas: Vec<_> = replicas .iter() .map(|ffi_info| { - let cache_dir_path = c_str_to_pbuf(ffi_info.cache_dir_path); - let replica_path = c_str_to_rust_str(ffi_info.replica_path).to_string(); + let cache_dir_path = as_path_buf(&ffi_info.cache_dir_path)?; + let replica_path = as_path_buf(&ffi_info.replica_path)?; - PrivateReplicaInfoTmp { + Ok(PrivateReplicaInfoTmp { registered_proof: ffi_info.registered_proof, cache_dir_path, comm_r: ffi_info.comm_r, - replica_path: PathBuf::from(replica_path), + replica_path, sector_id: ffi_info.sector_id, - } + }) }) - .collect(); + .collect::>()?; let map = replicas .into_par_iter() @@ -103,7 +88,7 @@ pub unsafe fn to_private_replica_info_map( ( SectorId::from(sector_id), - PrivateReplicaInfo::new( + api::PrivateReplicaInfo::new( registered_proof.into(), comm_r, cache_dir_path, @@ -115,62 +100,3 @@ pub unsafe fn to_private_replica_info_map( Ok(map) } - -pub unsafe fn c_to_rust_post_proofs( - post_proofs_ptr: *const fil_PoStProof, - post_proofs_len: libc::size_t, -) -> Result> { - ensure!( - !post_proofs_ptr.is_null(), - "post_proofs_ptr must not be null" - ); - - let out = from_raw_parts(post_proofs_ptr, post_proofs_len) - .iter() - .map(|fpp| PoStProof { - registered_proof: fpp.registered_proof.into(), - proof: from_raw_parts(fpp.proof_ptr, fpp.proof_len).to_vec(), - }) - .collect(); - - Ok(out) -} - -pub unsafe fn c_to_rust_vanilla_partition_proofs( - partition_proofs_ptr: *const fil_PartitionProof, - partition_proofs_len: libc::size_t, -) -> Result> { - ensure!( - !partition_proofs_ptr.is_null(), - "partition_proofs_ptr must not be null" - ); - - let out = from_raw_parts(partition_proofs_ptr, partition_proofs_len) - .iter() - .map(|fpp| PartitionProof { - proof: from_raw_parts(fpp.proof_ptr, fpp.proof_len).to_vec(), - }) - .collect(); - - Ok(out) -} - -pub unsafe fn c_to_rust_partition_proofs( - partition_proofs_ptr: *const fil_PartitionSnarkProof, - partition_proofs_len: libc::size_t, -) -> Result> { - ensure!( - !partition_proofs_ptr.is_null(), - "partition_proofs_ptr must not be null" - ); - - let out = from_raw_parts(partition_proofs_ptr, partition_proofs_len) - .iter() - .map(|fpp| PartitionSnarkProof { - registered_proof: fpp.registered_proof.into(), - proof: from_raw_parts(fpp.proof_ptr, fpp.proof_len).to_vec(), - }) - .collect(); - - Ok(out) -} diff --git a/rust/src/proofs/types.rs b/rust/src/proofs/types.rs index 6324c4e9..90504436 100644 --- a/rust/src/proofs/types.rs +++ b/rust/src/proofs/types.rs @@ -1,20 +1,9 @@ -use std::io::{Error, SeekFrom}; -use std::ptr; -use std::slice::from_raw_parts; - -use anyhow::Result; -use drop_struct_macro_derive::DropStructMacro; -use ffi_toolkit::{code_and_message_impl, free_c_str, CodeAndMessage, FCPResponseStatus}; -use filecoin_proofs_api::{ - seal::SealCommitPhase2Output, PieceInfo, RegisteredAggregationProof, RegisteredPoStProof, - RegisteredSealProof, RegisteredUpdateProof, UnpaddedBytesAmount, -}; +use std::io::SeekFrom; -#[repr(C)] -#[derive(Default, Debug, Clone, Copy)] -pub struct fil_32ByteArray { - pub inner: [u8; 32], -} +use filecoin_proofs_api as api; +use safer_ffi::prelude::*; + +use crate::util::types::Result; /// FileDescriptorRef does not drop its file descriptor when it is dropped. Its /// owner must manage the lifecycle of the file descriptor. @@ -35,24 +24,25 @@ impl std::io::Read for FileDescriptorRef { } impl std::io::Write for FileDescriptorRef { - fn write(&mut self, buf: &[u8]) -> Result { + fn write(&mut self, buf: &[u8]) -> std::io::Result { self.0.write(buf) } - fn flush(&mut self) -> Result<(), Error> { + fn flush(&mut self) -> std::io::Result<()> { self.0.flush() } } impl std::io::Seek for FileDescriptorRef { - fn seek(&mut self, pos: SeekFrom) -> Result { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { self.0.seek(pos) } } -#[repr(C)] +#[derive_ReprC] +#[repr(i32)] #[derive(Debug, Clone, Copy)] -pub enum fil_RegisteredSealProof { +pub enum RegisteredSealProof { StackedDrg2KiBV1, StackedDrg8MiBV1, StackedDrg512MiBV1, @@ -65,57 +55,47 @@ pub enum fil_RegisteredSealProof { StackedDrg64GiBV1_1, } -impl From for fil_RegisteredSealProof { - fn from(other: RegisteredSealProof) -> Self { +impl From for RegisteredSealProof { + fn from(other: api::RegisteredSealProof) -> Self { + use api::RegisteredSealProof::*; match other { - RegisteredSealProof::StackedDrg2KiBV1 => fil_RegisteredSealProof::StackedDrg2KiBV1, - RegisteredSealProof::StackedDrg8MiBV1 => fil_RegisteredSealProof::StackedDrg8MiBV1, - RegisteredSealProof::StackedDrg512MiBV1 => fil_RegisteredSealProof::StackedDrg512MiBV1, - RegisteredSealProof::StackedDrg32GiBV1 => fil_RegisteredSealProof::StackedDrg32GiBV1, - RegisteredSealProof::StackedDrg64GiBV1 => fil_RegisteredSealProof::StackedDrg64GiBV1, - - RegisteredSealProof::StackedDrg2KiBV1_1 => fil_RegisteredSealProof::StackedDrg2KiBV1_1, - RegisteredSealProof::StackedDrg8MiBV1_1 => fil_RegisteredSealProof::StackedDrg8MiBV1_1, - RegisteredSealProof::StackedDrg512MiBV1_1 => { - fil_RegisteredSealProof::StackedDrg512MiBV1_1 - } - RegisteredSealProof::StackedDrg32GiBV1_1 => { - fil_RegisteredSealProof::StackedDrg32GiBV1_1 - } - RegisteredSealProof::StackedDrg64GiBV1_1 => { - fil_RegisteredSealProof::StackedDrg64GiBV1_1 - } + StackedDrg2KiBV1 => RegisteredSealProof::StackedDrg2KiBV1, + StackedDrg8MiBV1 => RegisteredSealProof::StackedDrg8MiBV1, + StackedDrg512MiBV1 => RegisteredSealProof::StackedDrg512MiBV1, + StackedDrg32GiBV1 => RegisteredSealProof::StackedDrg32GiBV1, + StackedDrg64GiBV1 => RegisteredSealProof::StackedDrg64GiBV1, + StackedDrg2KiBV1_1 => RegisteredSealProof::StackedDrg2KiBV1_1, + StackedDrg8MiBV1_1 => RegisteredSealProof::StackedDrg8MiBV1_1, + StackedDrg512MiBV1_1 => RegisteredSealProof::StackedDrg512MiBV1_1, + StackedDrg32GiBV1_1 => RegisteredSealProof::StackedDrg32GiBV1_1, + StackedDrg64GiBV1_1 => RegisteredSealProof::StackedDrg64GiBV1_1, } } } -impl From for RegisteredSealProof { - fn from(other: fil_RegisteredSealProof) -> Self { +impl From for api::RegisteredSealProof { + fn from(other: RegisteredSealProof) -> Self { + use api::RegisteredSealProof::*; match other { - fil_RegisteredSealProof::StackedDrg2KiBV1 => RegisteredSealProof::StackedDrg2KiBV1, - fil_RegisteredSealProof::StackedDrg8MiBV1 => RegisteredSealProof::StackedDrg8MiBV1, - fil_RegisteredSealProof::StackedDrg512MiBV1 => RegisteredSealProof::StackedDrg512MiBV1, - fil_RegisteredSealProof::StackedDrg32GiBV1 => RegisteredSealProof::StackedDrg32GiBV1, - fil_RegisteredSealProof::StackedDrg64GiBV1 => RegisteredSealProof::StackedDrg64GiBV1, - - fil_RegisteredSealProof::StackedDrg2KiBV1_1 => RegisteredSealProof::StackedDrg2KiBV1_1, - fil_RegisteredSealProof::StackedDrg8MiBV1_1 => RegisteredSealProof::StackedDrg8MiBV1_1, - fil_RegisteredSealProof::StackedDrg512MiBV1_1 => { - RegisteredSealProof::StackedDrg512MiBV1_1 - } - fil_RegisteredSealProof::StackedDrg32GiBV1_1 => { - RegisteredSealProof::StackedDrg32GiBV1_1 - } - fil_RegisteredSealProof::StackedDrg64GiBV1_1 => { - RegisteredSealProof::StackedDrg64GiBV1_1 - } + RegisteredSealProof::StackedDrg2KiBV1 => StackedDrg2KiBV1, + RegisteredSealProof::StackedDrg8MiBV1 => StackedDrg8MiBV1, + RegisteredSealProof::StackedDrg512MiBV1 => StackedDrg512MiBV1, + RegisteredSealProof::StackedDrg32GiBV1 => StackedDrg32GiBV1, + RegisteredSealProof::StackedDrg64GiBV1 => StackedDrg64GiBV1, + + RegisteredSealProof::StackedDrg2KiBV1_1 => StackedDrg2KiBV1_1, + RegisteredSealProof::StackedDrg8MiBV1_1 => StackedDrg8MiBV1_1, + RegisteredSealProof::StackedDrg512MiBV1_1 => StackedDrg512MiBV1_1, + RegisteredSealProof::StackedDrg32GiBV1_1 => StackedDrg32GiBV1_1, + RegisteredSealProof::StackedDrg64GiBV1_1 => StackedDrg64GiBV1_1, } } } -#[repr(C)] +#[derive_ReprC] +#[repr(i32)] #[derive(Debug, Clone, Copy)] -pub enum fil_RegisteredPoStProof { +pub enum RegisteredPoStProof { StackedDrgWinning2KiBV1, StackedDrgWinning8MiBV1, StackedDrgWinning512MiBV1, @@ -128,69 +108,71 @@ pub enum fil_RegisteredPoStProof { StackedDrgWindow64GiBV1, } -impl From for fil_RegisteredPoStProof { - fn from(other: RegisteredPoStProof) -> Self { - use RegisteredPoStProof::*; +impl From for RegisteredPoStProof { + fn from(other: api::RegisteredPoStProof) -> Self { + use api::RegisteredPoStProof::*; match other { - StackedDrgWinning2KiBV1 => fil_RegisteredPoStProof::StackedDrgWinning2KiBV1, - StackedDrgWinning8MiBV1 => fil_RegisteredPoStProof::StackedDrgWinning8MiBV1, - StackedDrgWinning512MiBV1 => fil_RegisteredPoStProof::StackedDrgWinning512MiBV1, - StackedDrgWinning32GiBV1 => fil_RegisteredPoStProof::StackedDrgWinning32GiBV1, - StackedDrgWinning64GiBV1 => fil_RegisteredPoStProof::StackedDrgWinning64GiBV1, - StackedDrgWindow2KiBV1 => fil_RegisteredPoStProof::StackedDrgWindow2KiBV1, - StackedDrgWindow8MiBV1 => fil_RegisteredPoStProof::StackedDrgWindow8MiBV1, - StackedDrgWindow512MiBV1 => fil_RegisteredPoStProof::StackedDrgWindow512MiBV1, - StackedDrgWindow32GiBV1 => fil_RegisteredPoStProof::StackedDrgWindow32GiBV1, - StackedDrgWindow64GiBV1 => fil_RegisteredPoStProof::StackedDrgWindow64GiBV1, + StackedDrgWinning2KiBV1 => RegisteredPoStProof::StackedDrgWinning2KiBV1, + StackedDrgWinning8MiBV1 => RegisteredPoStProof::StackedDrgWinning8MiBV1, + StackedDrgWinning512MiBV1 => RegisteredPoStProof::StackedDrgWinning512MiBV1, + StackedDrgWinning32GiBV1 => RegisteredPoStProof::StackedDrgWinning32GiBV1, + StackedDrgWinning64GiBV1 => RegisteredPoStProof::StackedDrgWinning64GiBV1, + StackedDrgWindow2KiBV1 => RegisteredPoStProof::StackedDrgWindow2KiBV1, + StackedDrgWindow8MiBV1 => RegisteredPoStProof::StackedDrgWindow8MiBV1, + StackedDrgWindow512MiBV1 => RegisteredPoStProof::StackedDrgWindow512MiBV1, + StackedDrgWindow32GiBV1 => RegisteredPoStProof::StackedDrgWindow32GiBV1, + StackedDrgWindow64GiBV1 => RegisteredPoStProof::StackedDrgWindow64GiBV1, } } } -impl From for RegisteredPoStProof { - fn from(other: fil_RegisteredPoStProof) -> Self { - use RegisteredPoStProof::*; +impl From for api::RegisteredPoStProof { + fn from(other: RegisteredPoStProof) -> Self { + use api::RegisteredPoStProof::*; match other { - fil_RegisteredPoStProof::StackedDrgWinning2KiBV1 => StackedDrgWinning2KiBV1, - fil_RegisteredPoStProof::StackedDrgWinning8MiBV1 => StackedDrgWinning8MiBV1, - fil_RegisteredPoStProof::StackedDrgWinning512MiBV1 => StackedDrgWinning512MiBV1, - fil_RegisteredPoStProof::StackedDrgWinning32GiBV1 => StackedDrgWinning32GiBV1, - fil_RegisteredPoStProof::StackedDrgWinning64GiBV1 => StackedDrgWinning64GiBV1, - fil_RegisteredPoStProof::StackedDrgWindow2KiBV1 => StackedDrgWindow2KiBV1, - fil_RegisteredPoStProof::StackedDrgWindow8MiBV1 => StackedDrgWindow8MiBV1, - fil_RegisteredPoStProof::StackedDrgWindow512MiBV1 => StackedDrgWindow512MiBV1, - fil_RegisteredPoStProof::StackedDrgWindow32GiBV1 => StackedDrgWindow32GiBV1, - fil_RegisteredPoStProof::StackedDrgWindow64GiBV1 => StackedDrgWindow64GiBV1, + RegisteredPoStProof::StackedDrgWinning2KiBV1 => StackedDrgWinning2KiBV1, + RegisteredPoStProof::StackedDrgWinning8MiBV1 => StackedDrgWinning8MiBV1, + RegisteredPoStProof::StackedDrgWinning512MiBV1 => StackedDrgWinning512MiBV1, + RegisteredPoStProof::StackedDrgWinning32GiBV1 => StackedDrgWinning32GiBV1, + RegisteredPoStProof::StackedDrgWinning64GiBV1 => StackedDrgWinning64GiBV1, + RegisteredPoStProof::StackedDrgWindow2KiBV1 => StackedDrgWindow2KiBV1, + RegisteredPoStProof::StackedDrgWindow8MiBV1 => StackedDrgWindow8MiBV1, + RegisteredPoStProof::StackedDrgWindow512MiBV1 => StackedDrgWindow512MiBV1, + RegisteredPoStProof::StackedDrgWindow32GiBV1 => StackedDrgWindow32GiBV1, + RegisteredPoStProof::StackedDrgWindow64GiBV1 => StackedDrgWindow64GiBV1, } } } -#[repr(C)] +#[derive_ReprC] +#[repr(i32)] #[derive(Debug, Clone, Copy)] -pub enum fil_RegisteredAggregationProof { +pub enum RegisteredAggregationProof { SnarkPackV1, } -impl From for fil_RegisteredAggregationProof { - fn from(other: RegisteredAggregationProof) -> Self { +impl From for RegisteredAggregationProof { + fn from(other: api::RegisteredAggregationProof) -> Self { match other { - RegisteredAggregationProof::SnarkPackV1 => fil_RegisteredAggregationProof::SnarkPackV1, + api::RegisteredAggregationProof::SnarkPackV1 => RegisteredAggregationProof::SnarkPackV1, } } } -impl From for RegisteredAggregationProof { - fn from(other: fil_RegisteredAggregationProof) -> Self { +impl From for api::RegisteredAggregationProof { + fn from(other: RegisteredAggregationProof) -> Self { match other { - fil_RegisteredAggregationProof::SnarkPackV1 => RegisteredAggregationProof::SnarkPackV1, + RegisteredAggregationProof::SnarkPackV1 => api::RegisteredAggregationProof::SnarkPackV1, } } } -#[repr(C)] +#[derive_ReprC] +#[repr(i32)] #[derive(Debug, Clone, Copy)] -pub enum fil_RegisteredUpdateProof { +pub enum RegisteredUpdateProof { StackedDrg2KiBV1, StackedDrg8MiBV1, StackedDrg512MiBV1, @@ -198,1035 +180,294 @@ pub enum fil_RegisteredUpdateProof { StackedDrg64GiBV1, } -impl From for fil_RegisteredUpdateProof { - fn from(other: RegisteredUpdateProof) -> Self { +impl From for RegisteredUpdateProof { + fn from(other: api::RegisteredUpdateProof) -> Self { + use api::RegisteredUpdateProof::*; match other { - RegisteredUpdateProof::StackedDrg2KiBV1 => fil_RegisteredUpdateProof::StackedDrg2KiBV1, - RegisteredUpdateProof::StackedDrg8MiBV1 => fil_RegisteredUpdateProof::StackedDrg8MiBV1, - RegisteredUpdateProof::StackedDrg512MiBV1 => { - fil_RegisteredUpdateProof::StackedDrg512MiBV1 - } - RegisteredUpdateProof::StackedDrg32GiBV1 => { - fil_RegisteredUpdateProof::StackedDrg32GiBV1 - } - RegisteredUpdateProof::StackedDrg64GiBV1 => { - fil_RegisteredUpdateProof::StackedDrg64GiBV1 - } + StackedDrg2KiBV1 => RegisteredUpdateProof::StackedDrg2KiBV1, + StackedDrg8MiBV1 => RegisteredUpdateProof::StackedDrg8MiBV1, + StackedDrg512MiBV1 => RegisteredUpdateProof::StackedDrg512MiBV1, + StackedDrg32GiBV1 => RegisteredUpdateProof::StackedDrg32GiBV1, + StackedDrg64GiBV1 => RegisteredUpdateProof::StackedDrg64GiBV1, } } } -impl From for RegisteredUpdateProof { - fn from(other: fil_RegisteredUpdateProof) -> Self { +impl From for api::RegisteredUpdateProof { + fn from(other: RegisteredUpdateProof) -> Self { + use api::RegisteredUpdateProof::*; match other { - fil_RegisteredUpdateProof::StackedDrg2KiBV1 => RegisteredUpdateProof::StackedDrg2KiBV1, - fil_RegisteredUpdateProof::StackedDrg8MiBV1 => RegisteredUpdateProof::StackedDrg8MiBV1, - fil_RegisteredUpdateProof::StackedDrg512MiBV1 => { - RegisteredUpdateProof::StackedDrg512MiBV1 - } - fil_RegisteredUpdateProof::StackedDrg32GiBV1 => { - RegisteredUpdateProof::StackedDrg32GiBV1 - } - fil_RegisteredUpdateProof::StackedDrg64GiBV1 => { - RegisteredUpdateProof::StackedDrg64GiBV1 - } + RegisteredUpdateProof::StackedDrg2KiBV1 => StackedDrg2KiBV1, + RegisteredUpdateProof::StackedDrg8MiBV1 => StackedDrg8MiBV1, + RegisteredUpdateProof::StackedDrg512MiBV1 => StackedDrg512MiBV1, + RegisteredUpdateProof::StackedDrg32GiBV1 => StackedDrg32GiBV1, + RegisteredUpdateProof::StackedDrg64GiBV1 => StackedDrg64GiBV1, } } } +#[derive_ReprC] #[repr(C)] #[derive(Clone)] -pub struct fil_PublicPieceInfo { +pub struct PublicPieceInfo { pub num_bytes: u64, pub comm_p: [u8; 32], } -impl From for PieceInfo { - fn from(x: fil_PublicPieceInfo) -> Self { - let fil_PublicPieceInfo { num_bytes, comm_p } = x; - PieceInfo { - commitment: comm_p, - size: UnpaddedBytesAmount(num_bytes), +impl From<&PublicPieceInfo> for api::PieceInfo { + fn from(x: &PublicPieceInfo) -> Self { + let PublicPieceInfo { num_bytes, comm_p } = x; + api::PieceInfo { + commitment: *comm_p, + size: api::UnpaddedBytesAmount(*num_bytes), } } } -#[repr(C)] -pub struct fil_VanillaProof { - pub proof_len: libc::size_t, - pub proof_ptr: *const u8, -} - -impl Clone for fil_VanillaProof { - fn clone(&self) -> Self { - let slice: &[u8] = unsafe { std::slice::from_raw_parts(self.proof_ptr, self.proof_len) }; - let cloned: Vec = slice.to_vec(); - debug_assert_eq!(self.proof_len, cloned.len()); +pub type VanillaProof = c_slice::Box; - let proof_ptr = cloned.as_ptr(); - std::mem::forget(cloned); - - fil_VanillaProof { - proof_len: self.proof_len, - proof_ptr, - } - } -} - -impl Drop for fil_VanillaProof { - fn drop(&mut self) { - // Note that this operation also does the equivalent of - // libc::free(self.proof_ptr as *mut libc::c_void); - let _ = unsafe { - Vec::from_raw_parts(self.proof_ptr as *mut u8, self.proof_len, self.proof_len) - }; - } -} - -#[repr(C)] -pub struct fil_AggregateProof { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub proof_len: libc::size_t, - pub proof_ptr: *const u8, -} - -impl Default for fil_AggregateProof { - fn default() -> fil_AggregateProof { - fil_AggregateProof { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - proof_len: 0, - proof_ptr: ptr::null(), - } - } -} - -impl Drop for fil_AggregateProof { - fn drop(&mut self) { - unsafe { - // Note that this operation also does the equivalent of - // libc::free(self.proof_ptr as *mut libc::c_void); - drop(Vec::from_raw_parts( - self.proof_ptr as *mut u8, - self.proof_len, - self.proof_len, - )); - free_c_str(self.error_msg as *mut libc::c_char); - } - } -} - -code_and_message_impl!(fil_AggregateProof); +pub type AggregateProof = Result; #[derive(Clone, Debug)] -pub struct PoStProof { - pub registered_proof: RegisteredPoStProof, +pub struct ApiPoStProof { + pub registered_proof: api::RegisteredPoStProof, pub proof: Vec, } +#[derive_ReprC] #[repr(C)] #[derive(Clone)] -pub struct fil_PoStProof { - pub registered_proof: fil_RegisteredPoStProof, - pub proof_len: libc::size_t, - pub proof_ptr: *const u8, +pub struct PoStProof { + pub registered_proof: RegisteredPoStProof, + pub proof: c_slice::Box, } -impl Drop for fil_PoStProof { - fn drop(&mut self) { - let _ = unsafe { - Vec::from_raw_parts(self.proof_ptr as *mut u8, self.proof_len, self.proof_len) - }; +impl Default for PoStProof { + fn default() -> Self { + Self { + registered_proof: RegisteredPoStProof::StackedDrgWindow32GiBV1, // dummy value + proof: Default::default(), + } } } -impl From for PoStProof { - fn from(other: fil_PoStProof) -> Self { - let proof = unsafe { from_raw_parts(other.proof_ptr, other.proof_len).to_vec() }; - - PoStProof { +impl From for ApiPoStProof { + fn from(other: PoStProof) -> Self { + ApiPoStProof { registered_proof: other.registered_proof.into(), - proof, + proof: other.proof.to_vec(), } } } -#[repr(C)] #[derive(Clone)] -pub struct PartitionSnarkProof { - pub registered_proof: RegisteredPoStProof, +pub struct ApiPartitionSnarkProof { + pub registered_proof: api::RegisteredPoStProof, pub proof: Vec, } +#[derive_ReprC] #[repr(C)] -pub struct fil_PartitionSnarkProof { - pub registered_proof: fil_RegisteredPoStProof, - pub proof_len: libc::size_t, - pub proof_ptr: *const u8, +#[derive(Clone)] +pub struct PartitionSnarkProof { + pub registered_proof: RegisteredPoStProof, + pub proof: c_slice::Box, } -impl Clone for fil_PartitionSnarkProof { - fn clone(&self) -> Self { - let slice: &[u8] = unsafe { std::slice::from_raw_parts(self.proof_ptr, self.proof_len) }; - let cloned: Vec = slice.to_vec(); - debug_assert_eq!(self.proof_len, cloned.len()); - - let proof_ptr = cloned.as_ptr(); - std::mem::forget(cloned); - - fil_PartitionSnarkProof { - registered_proof: self.registered_proof, - proof_len: self.proof_len, - proof_ptr, +impl Default for PartitionSnarkProof { + fn default() -> Self { + Self { + registered_proof: RegisteredPoStProof::StackedDrgWindow32GiBV1, // dummy value + proof: Default::default(), } } } -impl Drop for fil_PartitionSnarkProof { - fn drop(&mut self) { - let _ = unsafe { - Vec::from_raw_parts(self.proof_ptr as *mut u8, self.proof_len, self.proof_len) - }; - } -} - -impl From for PartitionSnarkProof { - fn from(other: fil_PartitionSnarkProof) -> Self { - let proof = unsafe { from_raw_parts(other.proof_ptr, other.proof_len).to_vec() }; - - PartitionSnarkProof { +impl From for ApiPartitionSnarkProof { + fn from(other: PartitionSnarkProof) -> Self { + ApiPartitionSnarkProof { registered_proof: other.registered_proof.into(), - proof, + proof: other.proof.to_vec(), } } } -#[repr(C)] #[derive(Clone)] pub struct PartitionProof { pub proof: Vec, } -#[repr(C)] -pub struct fil_PartitionProof { - pub proof_len: libc::size_t, - pub proof_ptr: *const u8, -} - -impl Clone for fil_PartitionProof { - fn clone(&self) -> Self { - let slice: &[u8] = unsafe { std::slice::from_raw_parts(self.proof_ptr, self.proof_len) }; - let cloned: Vec = slice.to_vec(); - debug_assert_eq!(self.proof_len, cloned.len()); - - let proof_ptr = cloned.as_ptr(); - std::mem::forget(cloned); - - fil_PartitionProof { - proof_len: self.proof_len, - proof_ptr, - } - } -} - -impl Drop for fil_PartitionProof { - fn drop(&mut self) { - // Note that this operation also does the equivalent of - // libc::free(self.proof_ptr as *mut libc::c_void); - let _ = unsafe { - Vec::from_raw_parts(self.proof_ptr as *mut u8, self.proof_len, self.proof_len) - }; - } -} +pub type ApiPartitionProof = c_slice::Box; +#[derive_ReprC] #[repr(C)] #[derive(Clone)] -pub struct fil_PrivateReplicaInfo { - pub registered_proof: fil_RegisteredPoStProof, - pub cache_dir_path: *const libc::c_char, +pub struct PrivateReplicaInfo { + pub registered_proof: RegisteredPoStProof, + pub cache_dir_path: c_slice::Box, pub comm_r: [u8; 32], - pub replica_path: *const libc::c_char, + pub replica_path: c_slice::Box, pub sector_id: u64, } +#[derive_ReprC] #[repr(C)] #[derive(Clone)] -pub struct fil_PublicReplicaInfo { - pub registered_proof: fil_RegisteredPoStProof, +pub struct PublicReplicaInfo { + pub registered_proof: RegisteredPoStProof, pub comm_r: [u8; 32], pub sector_id: u64, } -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateWinningPoStSectorChallenge { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub ids_ptr: *const u64, - pub ids_len: libc::size_t, -} - -impl Default for fil_GenerateWinningPoStSectorChallenge { - fn default() -> fil_GenerateWinningPoStSectorChallenge { - fil_GenerateWinningPoStSectorChallenge { - ids_len: 0, - ids_ptr: ptr::null(), - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - } - } -} - -code_and_message_impl!(fil_GenerateWinningPoStSectorChallenge); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateFallbackSectorChallengesResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub ids_ptr: *const u64, - pub ids_len: libc::size_t, - pub challenges_ptr: *const u64, - pub challenges_len: libc::size_t, - pub challenges_stride: libc::size_t, -} - -impl Default for fil_GenerateFallbackSectorChallengesResponse { - fn default() -> fil_GenerateFallbackSectorChallengesResponse { - fil_GenerateFallbackSectorChallengesResponse { - challenges_len: 0, - challenges_stride: 0, - challenges_ptr: ptr::null(), - ids_len: 0, - ids_ptr: ptr::null(), - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - } - } -} - -code_and_message_impl!(fil_GenerateFallbackSectorChallengesResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateSingleVanillaProofResponse { - pub error_msg: *const libc::c_char, - pub vanilla_proof: fil_VanillaProof, - pub status_code: FCPResponseStatus, -} - -impl Default for fil_GenerateSingleVanillaProofResponse { - fn default() -> fil_GenerateSingleVanillaProofResponse { - fil_GenerateSingleVanillaProofResponse { - error_msg: ptr::null(), - vanilla_proof: fil_VanillaProof { - proof_len: 0, - proof_ptr: ptr::null(), - }, - status_code: FCPResponseStatus::FCPNoError, - } - } -} +pub type GenerateWinningPoStSectorChallenge = Result>; -code_and_message_impl!(fil_GenerateSingleVanillaProofResponse); +pub type GenerateFallbackSectorChallengesResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateWinningPoStResponse { - pub error_msg: *const libc::c_char, - pub proofs_len: libc::size_t, - pub proofs_ptr: *const fil_PoStProof, - pub status_code: FCPResponseStatus, +#[derive(Default)] +pub struct GenerateFallbackSectorChallenges { + pub ids: c_slice::Box, + pub challenges: c_slice::Box>, } -impl Default for fil_GenerateWinningPoStResponse { - fn default() -> fil_GenerateWinningPoStResponse { - fil_GenerateWinningPoStResponse { - error_msg: ptr::null(), - proofs_len: 0, - proofs_ptr: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - } - } -} - -code_and_message_impl!(fil_GenerateWinningPoStResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateWindowPoStResponse { - pub error_msg: *const libc::c_char, - pub proofs_len: libc::size_t, - pub proofs_ptr: *const fil_PoStProof, - pub faulty_sectors_len: libc::size_t, - pub faulty_sectors_ptr: *const u64, - pub status_code: FCPResponseStatus, -} +pub type GenerateSingleVanillaProofResponse = Result; -impl Default for fil_GenerateWindowPoStResponse { - fn default() -> fil_GenerateWindowPoStResponse { - fil_GenerateWindowPoStResponse { - error_msg: ptr::null(), - proofs_len: 0, - proofs_ptr: ptr::null(), - faulty_sectors_len: 0, - faulty_sectors_ptr: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - } - } -} +pub type GenerateWinningPoStResponse = Result>; -code_and_message_impl!(fil_GenerateWindowPoStResponse); +pub type GenerateWindowPoStResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateSingleWindowPoStWithVanillaResponse { - pub error_msg: *const libc::c_char, - pub partition_proof: fil_PartitionSnarkProof, - pub faulty_sectors_len: libc::size_t, - pub faulty_sectors_ptr: *const u64, - pub status_code: FCPResponseStatus, +#[derive(Default)] +pub struct GenerateWindowPoSt { + pub proofs: c_slice::Box, + pub faulty_sectors: c_slice::Box, } -impl Default for fil_GenerateSingleWindowPoStWithVanillaResponse { - fn default() -> fil_GenerateSingleWindowPoStWithVanillaResponse { - fil_GenerateSingleWindowPoStWithVanillaResponse { - error_msg: ptr::null(), - partition_proof: fil_PartitionSnarkProof { - registered_proof: fil_RegisteredPoStProof::StackedDrgWinning2KiBV1, - proof_len: 0, - proof_ptr: ptr::null(), - }, - faulty_sectors_len: 0, - faulty_sectors_ptr: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - } - } -} - -code_and_message_impl!(fil_GenerateSingleWindowPoStWithVanillaResponse); +pub type GenerateSingleWindowPoStWithVanillaResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GetNumPartitionForFallbackPoStResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub num_partition: libc::size_t, -} - -impl Default for fil_GetNumPartitionForFallbackPoStResponse { - fn default() -> fil_GetNumPartitionForFallbackPoStResponse { - fil_GetNumPartitionForFallbackPoStResponse { - error_msg: ptr::null(), - num_partition: 0, - status_code: FCPResponseStatus::FCPNoError, - } - } +#[derive(Default)] +pub struct GenerateSingleWindowPoStWithVanilla { + pub partition_proof: PartitionSnarkProof, + pub faulty_sectors: c_slice::Box, } -code_and_message_impl!(fil_GetNumPartitionForFallbackPoStResponse); +pub type GetNumPartitionForFallbackPoStResponse = Result; -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_MergeWindowPoStPartitionProofsResponse { - pub error_msg: *const libc::c_char, - pub proof: fil_PoStProof, - pub status_code: FCPResponseStatus, -} - -impl Default for fil_MergeWindowPoStPartitionProofsResponse { - fn default() -> fil_MergeWindowPoStPartitionProofsResponse { - fil_MergeWindowPoStPartitionProofsResponse { - error_msg: ptr::null(), - proof: fil_PoStProof { - registered_proof: fil_RegisteredPoStProof::StackedDrgWinning2KiBV1, - proof_len: 0, - proof_ptr: ptr::null(), - }, - status_code: FCPResponseStatus::FCPNoError, - } - } -} +pub type MergeWindowPoStPartitionProofsResponse = Result; -code_and_message_impl!(fil_MergeWindowPoStPartitionProofsResponse); +pub type WriteWithAlignmentResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_WriteWithAlignmentResponse { +#[derive(Default)] +pub struct WriteWithAlignment { pub comm_p: [u8; 32], - pub error_msg: *const libc::c_char, pub left_alignment_unpadded: u64, - pub status_code: FCPResponseStatus, pub total_write_unpadded: u64, } -impl Default for fil_WriteWithAlignmentResponse { - fn default() -> fil_WriteWithAlignmentResponse { - fil_WriteWithAlignmentResponse { - comm_p: Default::default(), - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - left_alignment_unpadded: 0, - total_write_unpadded: 0, - } - } -} - -code_and_message_impl!(fil_WriteWithAlignmentResponse); +pub type WriteWithoutAlignmentResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_WriteWithoutAlignmentResponse { +#[derive(Default)] +pub struct WriteWithoutAlignment { pub comm_p: [u8; 32], - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, pub total_write_unpadded: u64, } -impl Default for fil_WriteWithoutAlignmentResponse { - fn default() -> fil_WriteWithoutAlignmentResponse { - fil_WriteWithoutAlignmentResponse { - comm_p: Default::default(), - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - total_write_unpadded: 0, - } - } -} - -code_and_message_impl!(fil_WriteWithoutAlignmentResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_SealPreCommitPhase1Response { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub seal_pre_commit_phase1_output_ptr: *const u8, - pub seal_pre_commit_phase1_output_len: libc::size_t, -} - -impl Default for fil_SealPreCommitPhase1Response { - fn default() -> fil_SealPreCommitPhase1Response { - fil_SealPreCommitPhase1Response { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - seal_pre_commit_phase1_output_ptr: ptr::null(), - seal_pre_commit_phase1_output_len: 0, - } - } -} - -code_and_message_impl!(fil_SealPreCommitPhase1Response); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_FauxRepResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub commitment: [u8; 32], -} +pub type SealPreCommitPhase1Response = Result>; -impl Default for fil_FauxRepResponse { - fn default() -> fil_FauxRepResponse { - fil_FauxRepResponse { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - commitment: Default::default(), - } - } -} +pub type FauxRepResponse = Result<[u8; 32]>; -code_and_message_impl!(fil_FauxRepResponse); +pub type SealPreCommitPhase2Response = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_SealPreCommitPhase2Response { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, - pub registered_proof: fil_RegisteredSealProof, +pub struct SealPreCommitPhase2 { + pub registered_proof: RegisteredSealProof, pub comm_d: [u8; 32], pub comm_r: [u8; 32], } -impl Default for fil_SealPreCommitPhase2Response { - fn default() -> fil_SealPreCommitPhase2Response { - fil_SealPreCommitPhase2Response { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - registered_proof: fil_RegisteredSealProof::StackedDrg2KiBV1, +impl Default for SealPreCommitPhase2 { + fn default() -> Self { + Self { + registered_proof: RegisteredSealProof::StackedDrg2KiBV1_1, // dummy value comm_d: Default::default(), comm_r: Default::default(), } } } -code_and_message_impl!(fil_SealPreCommitPhase2Response); +pub type SealCommitPhase1Response = Result>; -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_SealCommitPhase1Response { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub seal_commit_phase1_output_ptr: *const u8, - pub seal_commit_phase1_output_len: libc::size_t, -} - -impl Default for fil_SealCommitPhase1Response { - fn default() -> fil_SealCommitPhase1Response { - fil_SealCommitPhase1Response { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - seal_commit_phase1_output_ptr: ptr::null(), - seal_commit_phase1_output_len: 0, - } - } -} - -code_and_message_impl!(fil_SealCommitPhase1Response); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_SealCommitPhase2Response { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub proof_ptr: *const u8, - pub proof_len: libc::size_t, - pub commit_inputs_ptr: *const fil_AggregationInputs, - pub commit_inputs_len: libc::size_t, -} - -impl From<&fil_SealCommitPhase2Response> for SealCommitPhase2Output { - fn from(other: &fil_SealCommitPhase2Response) -> Self { - let slice: &[u8] = unsafe { std::slice::from_raw_parts(other.proof_ptr, other.proof_len) }; - let proof: Vec = slice.to_vec(); - - SealCommitPhase2Output { proof } - } -} - -impl Default for fil_SealCommitPhase2Response { - fn default() -> fil_SealCommitPhase2Response { - fil_SealCommitPhase2Response { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - proof_ptr: ptr::null(), - proof_len: 0, - commit_inputs_ptr: ptr::null(), - commit_inputs_len: 0, - } - } -} - -// General note on Vec::from_raw_parts vs std::slice::from_raw_parts: -// -// Vec::from_raw_parts takes ownership of the allocation and will free -// it when it's dropped. -// -// std::slice::from_raw_parts borrows the allocation, and does not -// affect ownership. -// -// In general, usages should borrow via the slice and Drop methods -// should take ownership using the Vec. -impl Clone for fil_SealCommitPhase2Response { - fn clone(&self) -> Self { - let slice: &[u8] = unsafe { std::slice::from_raw_parts(self.proof_ptr, self.proof_len) }; - let proof: Vec = slice.to_vec(); - debug_assert_eq!(self.proof_len, proof.len()); - - let proof_len = proof.len(); - let proof_ptr = proof.as_ptr(); - - let slice: &[fil_AggregationInputs] = - unsafe { std::slice::from_raw_parts(self.commit_inputs_ptr, self.commit_inputs_len) }; - let commit_inputs: Vec = slice.to_vec(); - debug_assert_eq!(self.commit_inputs_len, commit_inputs.len()); - - let commit_inputs_len = commit_inputs.len(); - let commit_inputs_ptr = commit_inputs.as_ptr(); - - std::mem::forget(proof); - std::mem::forget(commit_inputs); - - fil_SealCommitPhase2Response { - status_code: self.status_code, - error_msg: self.error_msg, - proof_ptr, - proof_len, - commit_inputs_ptr, - commit_inputs_len, - } - } -} - -code_and_message_impl!(fil_SealCommitPhase2Response); +pub type SealCommitPhase2Response = Result>; +#[derive_ReprC] #[repr(C)] -#[derive(Clone, Default, DropStructMacro)] -pub struct fil_AggregationInputs { - pub comm_r: fil_32ByteArray, - pub comm_d: fil_32ByteArray, +#[derive(Clone, Default)] +pub struct AggregationInputs { + pub comm_r: [u8; 32], + pub comm_d: [u8; 32], pub sector_id: u64, - pub ticket: fil_32ByteArray, - pub seed: fil_32ByteArray, -} - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_UnsealRangeResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, -} - -impl Default for fil_UnsealRangeResponse { - fn default() -> fil_UnsealRangeResponse { - fil_UnsealRangeResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - } - } -} - -code_and_message_impl!(fil_UnsealRangeResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_VerifySealResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub is_valid: bool, -} - -impl Default for fil_VerifySealResponse { - fn default() -> fil_VerifySealResponse { - fil_VerifySealResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - is_valid: false, - } - } -} - -code_and_message_impl!(fil_VerifySealResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_VerifyAggregateSealProofResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub is_valid: bool, -} - -impl Default for fil_VerifyAggregateSealProofResponse { - fn default() -> fil_VerifyAggregateSealProofResponse { - fil_VerifyAggregateSealProofResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - is_valid: false, - } - } -} - -code_and_message_impl!(fil_VerifyAggregateSealProofResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_VerifyWinningPoStResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub is_valid: bool, -} - -impl Default for fil_VerifyWinningPoStResponse { - fn default() -> fil_VerifyWinningPoStResponse { - fil_VerifyWinningPoStResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - is_valid: false, - } - } + pub ticket: [u8; 32], + pub seed: [u8; 32], } -code_and_message_impl!(fil_VerifyWinningPoStResponse); +pub type UnsealRangeResponse = Result<()>; -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_VerifyWindowPoStResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub is_valid: bool, -} +pub type VerifySealResponse = Result; -impl Default for fil_VerifyWindowPoStResponse { - fn default() -> fil_VerifyWindowPoStResponse { - fil_VerifyWindowPoStResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - is_valid: false, - } - } -} +pub type VerifyAggregateSealProofResponse = Result; -code_and_message_impl!(fil_VerifyWindowPoStResponse); +pub type VerifyWinningPoStResponse = Result; -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_FinalizeTicketResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub ticket: [u8; 32], -} +pub type VerifyWindowPoStResponse = Result; -impl Default for fil_FinalizeTicketResponse { - fn default() -> Self { - fil_FinalizeTicketResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - ticket: [0u8; 32], - } - } -} +pub type FinalizeTicketResponse = Result<[u8; 32]>; -code_and_message_impl!(fil_FinalizeTicketResponse); +pub type GeneratePieceCommitmentResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GeneratePieceCommitmentResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, +#[derive(Default)] +pub struct GeneratePieceCommitment { pub comm_p: [u8; 32], /// The number of unpadded bytes in the original piece plus any (unpadded) /// alignment bytes added to create a whole merkle tree. pub num_bytes_aligned: u64, } -impl Default for fil_GeneratePieceCommitmentResponse { - fn default() -> fil_GeneratePieceCommitmentResponse { - fil_GeneratePieceCommitmentResponse { - status_code: FCPResponseStatus::FCPNoError, - comm_p: Default::default(), - error_msg: ptr::null(), - num_bytes_aligned: 0, - } - } -} - -code_and_message_impl!(fil_GeneratePieceCommitmentResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GenerateDataCommitmentResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub comm_d: [u8; 32], -} - -impl Default for fil_GenerateDataCommitmentResponse { - fn default() -> fil_GenerateDataCommitmentResponse { - fil_GenerateDataCommitmentResponse { - status_code: FCPResponseStatus::FCPNoError, - comm_d: Default::default(), - error_msg: ptr::null(), - } - } -} - -code_and_message_impl!(fil_GenerateDataCommitmentResponse); - -/// - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_StringResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub string_val: *const libc::c_char, -} - -impl Default for fil_StringResponse { - fn default() -> fil_StringResponse { - fil_StringResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - string_val: ptr::null(), - } - } -} - -code_and_message_impl!(fil_StringResponse); +pub type GenerateDataCommitmentResponse = Result<[u8; 32]>; -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_ClearCacheResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, -} +pub type StringResponse = Result>; -impl Default for fil_ClearCacheResponse { - fn default() -> fil_ClearCacheResponse { - fil_ClearCacheResponse { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - } - } -} +pub type ClearCacheResponse = Result<()>; -code_and_message_impl!(fil_ClearCacheResponse); +pub type EmptySectorUpdateEncodeIntoResponse = Result; +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_EmptySectorUpdateEncodeIntoResponse { - pub error_msg: *const libc::c_char, - pub status_code: FCPResponseStatus, +#[derive(Default)] +pub struct EmptySectorUpdateEncodeInto { pub comm_r_new: [u8; 32], pub comm_r_last_new: [u8; 32], pub comm_d_new: [u8; 32], } -impl Default for fil_EmptySectorUpdateEncodeIntoResponse { - fn default() -> fil_EmptySectorUpdateEncodeIntoResponse { - fil_EmptySectorUpdateEncodeIntoResponse { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - comm_r_new: Default::default(), - comm_r_last_new: Default::default(), - comm_d_new: Default::default(), - } - } -} - -code_and_message_impl!(fil_EmptySectorUpdateEncodeIntoResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_EmptySectorUpdateDecodeFromResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, -} - -impl Default for fil_EmptySectorUpdateDecodeFromResponse { - fn default() -> fil_EmptySectorUpdateDecodeFromResponse { - fil_EmptySectorUpdateDecodeFromResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - } - } -} - -code_and_message_impl!(fil_EmptySectorUpdateDecodeFromResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_EmptySectorUpdateRemoveEncodedDataResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, -} - -impl Default for fil_EmptySectorUpdateRemoveEncodedDataResponse { - fn default() -> fil_EmptySectorUpdateRemoveEncodedDataResponse { - fil_EmptySectorUpdateRemoveEncodedDataResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - } - } -} - -code_and_message_impl!(fil_EmptySectorUpdateRemoveEncodedDataResponse); - -#[repr(C)] -pub struct fil_EmptySectorUpdateProofResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub proof_len: libc::size_t, - pub proof_ptr: *const u8, -} - -impl Default for fil_EmptySectorUpdateProofResponse { - fn default() -> fil_EmptySectorUpdateProofResponse { - fil_EmptySectorUpdateProofResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - proof_len: 0, - proof_ptr: ptr::null(), - } - } -} - -impl Drop for fil_EmptySectorUpdateProofResponse { - fn drop(&mut self) { - unsafe { - // Note that this operation also does the equivalent of - // libc::free(self.proof_ptr as *mut libc::c_void); - drop(Vec::from_raw_parts( - self.proof_ptr as *mut u8, - self.proof_len, - self.proof_len, - )); - free_c_str(self.error_msg as *mut libc::c_char); - } - } -} - -code_and_message_impl!(fil_EmptySectorUpdateProofResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_PartitionProofResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub proofs_len: libc::size_t, - pub proofs_ptr: *const fil_PartitionProof, -} - -impl Default for fil_PartitionProofResponse { - fn default() -> fil_PartitionProofResponse { - fil_PartitionProofResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - proofs_len: 0, - proofs_ptr: ptr::null(), - } - } -} - -code_and_message_impl!(fil_PartitionProofResponse); - -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_VerifyPartitionProofResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub is_valid: bool, -} +pub type EmptySectorUpdateDecodeFromResponse = Result<()>; -impl Default for fil_VerifyPartitionProofResponse { - fn default() -> fil_VerifyPartitionProofResponse { - fil_VerifyPartitionProofResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - is_valid: false, - } - } -} +pub type EmptySectorUpdateRemoveEncodedDataResponse = Result<()>; -code_and_message_impl!(fil_VerifyPartitionProofResponse); +pub type EmptySectorUpdateProofResponse = Result>; -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_VerifyEmptySectorUpdateProofResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub is_valid: bool, -} +pub type PartitionProofResponse = Result>; -impl Default for fil_VerifyEmptySectorUpdateProofResponse { - fn default() -> fil_VerifyEmptySectorUpdateProofResponse { - fil_VerifyEmptySectorUpdateProofResponse { - status_code: FCPResponseStatus::FCPNoError, - error_msg: ptr::null(), - is_valid: false, - } - } -} +pub type VerifyPartitionProofResponse = Result; -code_and_message_impl!(fil_VerifyEmptySectorUpdateProofResponse); +pub type VerifyEmptySectorUpdateProofResponse = Result; diff --git a/rust/src/util/api.rs b/rust/src/util/api.rs index 9d941155..eb89aa04 100644 --- a/rust/src/util/api.rs +++ b/rust/src/util/api.rs @@ -1,11 +1,13 @@ -use std::ffi::CString; use std::fs::File; use std::os::unix::io::FromRawFd; use std::sync::Once; -use ffi_toolkit::{catch_panic_response, raw_ptr, rust_str_to_c_str, FCPResponseStatus}; +use anyhow::anyhow; +use safer_ffi::prelude::*; -use super::types::{fil_GpuDeviceResponse, fil_InitLogFdResponse}; +use super::types::{ + catch_panic_response, catch_panic_response_no_log, GpuDeviceResponse, InitLogFdResponse, +}; /// Protects the init off the logger. static LOG_INIT: Once = Once::new(); @@ -31,29 +33,16 @@ pub fn init_log_with_file(file: File) -> Option<()> { } /// Returns an array of strings containing the device names that can be used. -#[no_mangle] -pub unsafe extern "C" fn fil_get_gpu_devices() -> *mut fil_GpuDeviceResponse { - catch_panic_response(|| { - let mut response = fil_GpuDeviceResponse::default(); +#[ffi_export] +pub fn get_gpu_devices() -> repr_c::Box { + catch_panic_response("get_gpu_devices", || { let devices = rust_gpu_tools::Device::all(); - let n = devices.len(); - - let devices: Vec<*const libc::c_char> = devices - .iter() - .map(|d| d.name()) - .map(|d| { - CString::new(d) - .unwrap_or_else(|_| CString::new("Unknown").unwrap()) - .into_raw() as *const libc::c_char - }) + let devices: Vec<_> = devices + .into_iter() + .map(|d| d.name().into_bytes().into_boxed_slice().into()) .collect(); - let dyn_array = Box::into_raw(devices.into_boxed_slice()); - - response.devices_len = n; - response.devices_ptr = dyn_array as *const *const libc::c_char; - - raw_ptr(response) + Ok(devices.into_boxed_slice().into()) }) } @@ -64,50 +53,40 @@ pub unsafe extern "C" fn fil_get_gpu_devices() -> *mut fil_GpuDeviceResponse { /// /// This function must be called right at the start, before any other call. Else the logger will /// be initializes implicitely and log to stderr. -#[no_mangle] -#[cfg(not(target_os = "windows"))] -pub unsafe extern "C" fn fil_init_log_fd(log_fd: libc::c_int) -> *mut fil_InitLogFdResponse { - catch_panic_response(|| { - let file = File::from_raw_fd(log_fd); - let mut response = fil_InitLogFdResponse::default(); +#[ffi_export] +pub fn init_log_fd(log_fd: libc::c_int) -> repr_c::Box { + catch_panic_response_no_log(|| { + let file = unsafe { File::from_raw_fd(log_fd) }; + if init_log_with_file(file).is_none() { - response.status_code = FCPResponseStatus::FCPUnclassifiedError; - response.error_msg = rust_str_to_c_str("There is already an active logger. `fil_init_log_fd()` needs to be called before any other FFI function is called."); + return Err(anyhow!("There is already an active logger. `init_log_fd()` needs to be called before any other FFI function is called.")); } - raw_ptr(response) + Ok(()) }) } #[cfg(test)] mod tests { - use crate::util::api::fil_get_gpu_devices; - use crate::util::types::fil_destroy_gpu_device_response; + use crate::util::api::get_gpu_devices; + use crate::util::types::destroy_gpu_device_response; #[test] #[allow(clippy::needless_collect)] fn test_get_gpu_devices() { - unsafe { - let resp = fil_get_gpu_devices(); - - let strings = std::slice::from_raw_parts_mut( - (*resp).devices_ptr as *mut *mut libc::c_char, - (*resp).devices_len as usize, - ); - - let devices: Vec = strings - .iter_mut() - .map(|s| { - std::ffi::CStr::from_ptr(*s) - .to_str() - .unwrap_or("Unknown") - .to_owned() - }) - .collect(); - - assert_eq!(devices.len(), (*resp).devices_len); - fil_destroy_gpu_device_response(resp); - } + let resp = get_gpu_devices(); + assert!(resp.error_msg.is_empty()); + + let strings = &resp.value; + + let devices: Vec<&str> = strings + .iter() + .map(|s| std::str::from_utf8(s).unwrap()) + .collect(); + + assert_eq!(devices.len(), resp.value.len()); + + destroy_gpu_device_response(resp); } #[test] @@ -128,10 +107,8 @@ mod tests { use std::io::{BufRead, BufReader, Write}; use std::os::unix::io::FromRawFd; - use ffi_toolkit::FCPResponseStatus; - - use crate::util::api::fil_init_log_fd; - use crate::util::types::fil_destroy_init_log_fd_response; + use crate::util::api::init_log_fd; + use crate::util::types::{destroy_init_log_fd_response, FCPResponseStatus}; let mut fds: [libc::c_int; 2] = [0; 2]; let res = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }; @@ -140,30 +117,28 @@ mod tests { } let [read_fd, write_fd] = fds; - unsafe { - let mut reader = BufReader::new(File::from_raw_fd(read_fd)); - let mut writer = File::from_raw_fd(write_fd); + let mut reader = unsafe { BufReader::new(File::from_raw_fd(read_fd)) }; + let mut writer = unsafe { File::from_raw_fd(write_fd) }; - // Without setting this env variable there won't be any log output - env::set_var("RUST_LOG", "debug"); + // Without setting this env variable there won't be any log output + env::set_var("RUST_LOG", "debug"); - let resp = fil_init_log_fd(write_fd); - fil_destroy_init_log_fd_response(resp); + let resp = init_log_fd(write_fd); + destroy_init_log_fd_response(resp); - log::info!("a log message"); + log::info!("a log message"); - // Write a newline so that things don't block even if the logging doesn't work - writer.write_all(b"\n").unwrap(); + // Write a newline so that things don't block even if the logging doesn't work + writer.write_all(b"\n").unwrap(); - let mut log_message = String::new(); - reader.read_line(&mut log_message).unwrap(); + let mut log_message = String::new(); + reader.read_line(&mut log_message).unwrap(); - assert!(log_message.ends_with("a log message\n")); + assert!(log_message.ends_with("a log message\n")); - // Now test that there is an error when we try to init it again - let resp_error = fil_init_log_fd(write_fd); - assert_ne!((*resp_error).status_code, FCPResponseStatus::FCPNoError); - fil_destroy_init_log_fd_response(resp_error); - } + // Now test that there is an error when we try to init it again + let resp_error = init_log_fd(write_fd); + assert_ne!(resp_error.status_code, FCPResponseStatus::NoError); + destroy_init_log_fd_response(resp_error); } } diff --git a/rust/src/util/types.rs b/rust/src/util/types.rs index 732e22a1..2e53cbbc 100644 --- a/rust/src/util/types.rs +++ b/rust/src/util/types.rs @@ -1,55 +1,251 @@ -use std::ptr; +use std::{fmt::Display, mem::MaybeUninit, ops::Deref, panic, path::PathBuf, str::Utf8Error}; -use drop_struct_macro_derive::DropStructMacro; -// `CodeAndMessage` is the trait implemented by `code_and_message_impl -use ffi_toolkit::{code_and_message_impl, free_c_str, CodeAndMessage, FCPResponseStatus}; +use safer_ffi::prelude::*; +use super::api::init_log; + +#[derive_ReprC] +#[repr(i32)] +#[derive(PartialEq, Debug, Copy, Clone)] +pub enum FCPResponseStatus { + // Don't use FCPSuccess, since that complicates description of 'successful' verification. + NoError = 0, + UnclassifiedError = 1, + CallerError = 2, + ReceiverError = 3, +} + +#[cfg(target_os = "linux")] +pub fn as_path_buf(bytes: &[u8]) -> std::result::Result { + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + + Ok(OsStr::from_bytes(bytes).into()) +} + +#[cfg(not(target_os = "linux"))] +pub fn as_path_buf(bytes: &[u8]) -> std::result::Result { + std::str::from_utf8(bytes).map(Into::into) +} + +#[cfg(test)] +#[cfg(target_os = "linux")] +pub fn as_bytes(path: &std::path::Path) -> &[u8] { + use std::os::unix::ffi::OsStrExt; + + path.as_os_str().as_bytes() +} + +#[cfg(all(test, not(target_os = "linux")))] +pub fn as_bytes(path: &std::path::Path) -> &[u8] { + path.to_str().unwrap().as_bytes() +} + +#[derive_ReprC] #[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_GpuDeviceResponse { +#[derive(Clone)] +pub struct Result { pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, - pub devices_len: libc::size_t, - pub devices_ptr: *const *const libc::c_char, + pub error_msg: c_slice::Box, + pub value: T, +} + +impl Deref for Result { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.value + } } -impl Default for fil_GpuDeviceResponse { +impl Default for Result { fn default() -> Self { - Self { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, - devices_len: 0, - devices_ptr: ptr::null(), + Result { + status_code: FCPResponseStatus::NoError, + error_msg: Default::default(), + value: Default::default(), } } } -code_and_message_impl!(fil_GpuDeviceResponse); +impl From> for Result +where + T: Sized + Default, + E: Display, +{ + fn from(r: std::result::Result) -> Self { + match r { + Ok(value) => Self::ok(value), + Err(e) => Self::err(e.to_string().into_bytes().into_boxed_slice()), + } + } +} -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_gpu_device_response(ptr: *mut fil_GpuDeviceResponse) { - let _ = Box::from_raw(ptr); +impl From for Result +where + T: Sized, +{ + fn from(value: T) -> Self { + Self { + status_code: FCPResponseStatus::NoError, + error_msg: Default::default(), + value, + } + } } -#[repr(C)] -#[derive(DropStructMacro)] -pub struct fil_InitLogFdResponse { - pub status_code: FCPResponseStatus, - pub error_msg: *const libc::c_char, +impl Result { + pub fn ok(value: T) -> Self { + Result { + status_code: FCPResponseStatus::NoError, + error_msg: Default::default(), + value, + } + } + + pub unsafe fn into_boxed_raw(self) -> *mut Result { + Box::into_raw(Box::new(self)) + } + + pub fn err_with_default(err: impl Into>, value: T) -> Self { + Result { + status_code: FCPResponseStatus::UnclassifiedError, + error_msg: err.into(), + value, + } + } + + /// Safety: value must not be accessed. + pub unsafe fn err_no_default(err: impl Into>) -> Self { + Result { + status_code: FCPResponseStatus::UnclassifiedError, + error_msg: err.into(), + value: MaybeUninit::zeroed().assume_init(), + } + } } -impl Default for fil_InitLogFdResponse { - fn default() -> Self { - Self { - error_msg: ptr::null(), - status_code: FCPResponseStatus::FCPNoError, +impl Result { + pub fn err(err: impl Into>) -> Self { + Result { + status_code: FCPResponseStatus::UnclassifiedError, + error_msg: err.into(), + value: Default::default(), } } } -code_and_message_impl!(fil_InitLogFdResponse); +pub type GpuDeviceResponse = Result>>; + +#[ffi_export] +pub fn destroy_gpu_device_response(ptr: repr_c::Box) { + drop(ptr) +} + +pub type InitLogFdResponse = Result<()>; + +#[ffi_export] +pub fn destroy_init_log_fd_response(ptr: repr_c::Box) { + drop(ptr) +} + +/// Catch panics and return an error response +pub fn catch_panic_response(name: &str, callback: F) -> repr_c::Box> +where + T: Sized + Default, + F: FnOnce() -> anyhow::Result + std::panic::UnwindSafe, +{ + catch_panic_response_raw(name, || { + Result::from(callback().map_err(|err| err.to_string())) + }) +} + +pub fn catch_panic_response_no_log(callback: F) -> repr_c::Box> +where + T: Sized + Default, + F: FnOnce() -> anyhow::Result + std::panic::UnwindSafe, +{ + catch_panic_response_raw_no_log(|| Result::from(callback().map_err(|err| err.to_string()))) +} + +pub fn catch_panic_response_raw_no_log(callback: F) -> repr_c::Box> +where + T: Sized + Default, + F: FnOnce() -> Result + std::panic::UnwindSafe, +{ + let result = match panic::catch_unwind(callback) { + Ok(t) => t, + Err(panic) => { + let error_msg = match panic.downcast_ref::<&'static str>() { + Some(message) => message, + _ => "no unwind information", + }; + + Result::from(Err(format!("Rust panic: {}", error_msg))) + } + }; + + repr_c::Box::new(result) +} -#[no_mangle] -pub unsafe extern "C" fn fil_destroy_init_log_fd_response(ptr: *mut fil_InitLogFdResponse) { - let _ = Box::from_raw(ptr); +pub fn catch_panic_response_raw(name: &str, callback: F) -> repr_c::Box> +where + T: Sized + Default, + F: FnOnce() -> Result + std::panic::UnwindSafe, +{ + catch_panic_response_raw_no_log(|| { + init_log(); + log::info!("{}: start", name); + let res = callback(); + log::info!("{}: end", name); + res + }) +} + +pub unsafe fn catch_panic_response_no_default( + name: &str, + callback: F, +) -> repr_c::Box> +where + T: Sized, + F: FnOnce() -> anyhow::Result + std::panic::UnwindSafe, +{ + let result = match panic::catch_unwind(|| { + init_log(); + log::info!("{}: start", name); + let res = callback(); + log::info!("{}: end", name); + res + }) { + Ok(t) => match t { + Ok(t) => Result::ok(t), + Err(err) => Result::err_no_default(err.to_string().into_bytes().into_boxed_slice()), + }, + Err(panic) => { + let error_msg = match panic.downcast_ref::<&'static str>() { + Some(message) => message, + _ => "no unwind information", + }; + + Result::err_no_default( + format!("Rust panic: {}", error_msg) + .into_bytes() + .into_boxed_slice(), + ) + } + }; + + repr_c::Box::new(result) +} + +/// Generate a destructor for the given type wrapped in a `repr_c::Box`. +#[macro_export] +macro_rules! destructor { + ($name:ident, $type:ty) => { + /// Destroys the passed in `repr_c::Box<$type>`. + #[ffi_export] + fn $name(ptr: repr_c::Box<$type>) { + drop(ptr); + } + }; } diff --git a/sector_update.go b/sector_update.go index b6d9f8fb..6495428d 100644 --- a/sector_update.go +++ b/sector_update.go @@ -1,9 +1,10 @@ -//+build cgo +//go:build cgo +// +build cgo package ffi import ( - "github.com/filecoin-project/filecoin-ffi/generated" + "github.com/filecoin-project/filecoin-ffi/cgo" commcid "github.com/filecoin-project/go-fil-commcid" "github.com/filecoin-project/go-state-types/abi" "github.com/filecoin-project/specs-actors/v7/actors/runtime/proof" @@ -12,35 +13,35 @@ import ( "golang.org/x/xerrors" ) -func toFilRegisteredUpdateProof(p abi.RegisteredUpdateProof) (generated.FilRegisteredUpdateProof, error) { +func toFilRegisteredUpdateProof(p abi.RegisteredUpdateProof) (cgo.RegisteredUpdateProof, error) { switch p { case abi.RegisteredUpdateProof_StackedDrg2KiBV1: - return generated.FilRegisteredUpdateProofStackedDrg2KiBV1, nil + return cgo.RegisteredUpdateProofStackedDrg2KiBV1, nil case abi.RegisteredUpdateProof_StackedDrg8MiBV1: - return generated.FilRegisteredUpdateProofStackedDrg8MiBV1, nil + return cgo.RegisteredUpdateProofStackedDrg8MiBV1, nil case abi.RegisteredUpdateProof_StackedDrg512MiBV1: - return generated.FilRegisteredUpdateProofStackedDrg512MiBV1, nil + return cgo.RegisteredUpdateProofStackedDrg512MiBV1, nil case abi.RegisteredUpdateProof_StackedDrg32GiBV1: - return generated.FilRegisteredUpdateProofStackedDrg32GiBV1, nil + return cgo.RegisteredUpdateProofStackedDrg32GiBV1, nil case abi.RegisteredUpdateProof_StackedDrg64GiBV1: - return generated.FilRegisteredUpdateProofStackedDrg64GiBV1, nil + return cgo.RegisteredUpdateProofStackedDrg64GiBV1, nil default: return 0, errors.Errorf("no mapping to abi.RegisteredUpdateProof value available for: %v", p) } } //nolint:deadcode,unused -func fromFilRegisteredUpdateProof(p generated.FilRegisteredUpdateProof) (abi.RegisteredUpdateProof, error) { +func fromFilRegisteredUpdateProof(p cgo.RegisteredUpdateProof) (abi.RegisteredUpdateProof, error) { switch p { - case generated.FilRegisteredUpdateProofStackedDrg2KiBV1: + case cgo.RegisteredUpdateProofStackedDrg2KiBV1: return abi.RegisteredUpdateProof_StackedDrg2KiBV1, nil - case generated.FilRegisteredUpdateProofStackedDrg8MiBV1: + case cgo.RegisteredUpdateProofStackedDrg8MiBV1: return abi.RegisteredUpdateProof_StackedDrg8MiBV1, nil - case generated.FilRegisteredUpdateProofStackedDrg512MiBV1: + case cgo.RegisteredUpdateProofStackedDrg512MiBV1: return abi.RegisteredUpdateProof_StackedDrg512MiBV1, nil - case generated.FilRegisteredUpdateProofStackedDrg32GiBV1: + case cgo.RegisteredUpdateProofStackedDrg32GiBV1: return abi.RegisteredUpdateProof_StackedDrg32GiBV1, nil - case generated.FilRegisteredUpdateProofStackedDrg64GiBV1: + case cgo.RegisteredUpdateProofStackedDrg64GiBV1: return abi.RegisteredUpdateProof_StackedDrg64GiBV1, nil default: return 0, errors.Errorf("no mapping to abi.RegisteredUpdateProof value available for: %v", p) @@ -65,32 +66,29 @@ func (FunctionsSectorUpdate) EncodeInto( return cid.Undef, cid.Undef, err } - filPublicPieceInfos, filPublicPieceInfosLen, err := toFilPublicPieceInfos(pieces) + filPublicPieceInfos, err := toFilPublicPieceInfos(pieces) if err != nil { return cid.Undef, cid.Undef, err } - resp := generated.FilEmptySectorUpdateEncodeInto( + commRRaw, commDRaw, err := cgo.EmptySectorUpdateEncodeInto( up, - newReplicaPath, - newReplicaCachePath, - sectorKeyPath, - sectorKeyCachePath, - stagedDataPath, - filPublicPieceInfos, filPublicPieceInfosLen, + cgo.AsSliceRefUint8([]byte(newReplicaPath)), + cgo.AsSliceRefUint8([]byte(newReplicaCachePath)), + cgo.AsSliceRefUint8([]byte(sectorKeyPath)), + cgo.AsSliceRefUint8([]byte(sectorKeyCachePath)), + cgo.AsSliceRefUint8([]byte(stagedDataPath)), + cgo.AsSliceRefPublicPieceInfo(filPublicPieceInfos), ) - resp.Deref() - defer generated.FilDestroyEmptySectorUpdateEncodeIntoResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return cid.Undef, cid.Undef, errors.New(generated.RawString(resp.ErrorMsg).Copy()) + if err != nil { + return cid.Undef, cid.Undef, err } - commR, errCommrSize := commcid.ReplicaCommitmentV1ToCID(resp.CommRNew[:]) + commR, errCommrSize := commcid.ReplicaCommitmentV1ToCID(commRRaw) if errCommrSize != nil { return cid.Undef, cid.Undef, errCommrSize } - commD, errCommdSize := commcid.DataCommitmentV1ToCID(resp.CommDNew[:]) + commD, errCommdSize := commcid.DataCommitmentV1ToCID(commDRaw) if errCommdSize != nil { return cid.Undef, cid.Undef, errCommdSize } @@ -116,22 +114,14 @@ func (FunctionsSectorUpdate) DecodeFrom( return err } - resp := generated.FilEmptySectorUpdateDecodeFrom( + return cgo.EmptySectorUpdateDecodeFrom( up, - outDataPath, - replicaPath, - sectorKeyPath, - sectorKeyCachePath, - commD, + cgo.AsSliceRefUint8([]byte(outDataPath)), + cgo.AsSliceRefUint8([]byte(replicaPath)), + cgo.AsSliceRefUint8([]byte(sectorKeyPath)), + cgo.AsSliceRefUint8([]byte(sectorKeyCachePath)), + &commD, ) - resp.Deref() - defer generated.FilDestroyEmptySectorUpdateDecodeFromResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return nil } func (FunctionsSectorUpdate) RemoveData( @@ -153,23 +143,15 @@ func (FunctionsSectorUpdate) RemoveData( return err } - resp := generated.FilEmptySectorUpdateRemoveEncodedData( + return cgo.EmptySectorUpdateRemoveEncodedData( up, - sectorKeyPath, - sectorKeyCachePath, - replicaPath, - replicaCachePath, - dataPath, - commD, + cgo.AsSliceRefUint8([]byte(sectorKeyPath)), + cgo.AsSliceRefUint8([]byte(sectorKeyCachePath)), + cgo.AsSliceRefUint8([]byte(replicaPath)), + cgo.AsSliceRefUint8([]byte(replicaCachePath)), + cgo.AsSliceRefUint8([]byte(dataPath)), + &commD, ) - resp.Deref() - defer generated.FilDestroyEmptySectorUpdateRemoveEncodedDataResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - - return nil } func (FunctionsSectorUpdate) GenerateUpdateVanillaProofs( @@ -200,33 +182,16 @@ func (FunctionsSectorUpdate) GenerateUpdateVanillaProofs( return nil, xerrors.Errorf("transforming new CommD: %w", err) } - resp := generated.FilGenerateEmptySectorUpdatePartitionProofs( + return cgo.GenerateEmptySectorUpdatePartitionProofs( up, - commRold, - commRnew, - commD, - sectorKeyPath, - sectorKeyCachePath, - newReplicaPath, - newReplicaCachePath, + &commRold, + &commRnew, + &commD, + cgo.AsSliceRefUint8([]byte(sectorKeyPath)), + cgo.AsSliceRefUint8([]byte(sectorKeyCachePath)), + cgo.AsSliceRefUint8([]byte(newReplicaPath)), + cgo.AsSliceRefUint8([]byte(newReplicaCachePath)), ) - resp.Deref() - defer generated.FilDestroyGenerateEmptySectorUpdatePartitionProofResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - resp.ProofsPtr = make([]generated.FilPartitionProof, resp.ProofsLen) - resp.Deref() // deref again after initializing length - - proofs := make([][]byte, resp.ProofsLen) - for i, v := range resp.ProofsPtr { - v.Deref() - - proofs[i] = copyBytes(v.ProofPtr, v.ProofLen) - } - - return proofs, nil } func (FunctionsSectorUpdate) VerifyVanillaProofs( @@ -257,21 +222,13 @@ func (FunctionsSectorUpdate) VerifyVanillaProofs( proofs, cleanup := toUpdateVanillaProofs(vanillaProofs) defer cleanup() - resp := generated.FilVerifyEmptySectorUpdatePartitionProofs( + return cgo.VerifyEmptySectorUpdatePartitionProofs( up, - uint(len(proofs)), - proofs, // swapped, gotcha - commRold, - commRnew, - commD, + cgo.AsSliceRefSliceBoxedUint8(proofs), + &commRold, + &commRnew, + &commD, ) - resp.Deref() - defer generated.FilDestroyVerifyEmptySectorUpdatePartitionProofResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return false, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - return resp.IsValid, nil } func (FunctionsSectorUpdate) GenerateUpdateProofWithVanilla( @@ -302,39 +259,24 @@ func (FunctionsSectorUpdate) GenerateUpdateProofWithVanilla( proofs, cleanup := toUpdateVanillaProofs(vanillaProofs) defer cleanup() - resp := generated.FilGenerateEmptySectorUpdateProofWithVanilla( + return cgo.GenerateEmptySectorUpdateProofWithVanilla( up, - proofs, - uint(len(proofs)), - commRold, - commRnew, - commD, + cgo.AsSliceRefSliceBoxedUint8(proofs), + &commRold, + &commRnew, + &commD, ) - resp.Deref() - defer generated.FilDestroyEmptySectorUpdateGenerateProofResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - return copyBytes(resp.ProofPtr, resp.ProofLen), nil } -func toUpdateVanillaProofs(src [][]byte) ([]generated.FilPartitionProof, func()) { - allocs := make([]AllocationManager, len(src)) - - out := make([]generated.FilPartitionProof, len(src)) +func toUpdateVanillaProofs(src [][]byte) ([]cgo.SliceBoxedUint8, func()) { + out := make([]cgo.SliceBoxedUint8, len(src)) for idx := range out { - out[idx] = generated.FilPartitionProof{ - ProofLen: uint(len(src[idx])), - ProofPtr: src[idx], - } - - _, allocs[idx] = out[idx].PassRef() + out[idx] = cgo.AllocSliceBoxedUint8(src[idx]) } return out, func() { - for idx := range allocs { - allocs[idx].Free() + for idx := range out { + out[idx].Destroy() } } } @@ -367,23 +309,16 @@ func (FunctionsSectorUpdate) GenerateUpdateProof( return nil, xerrors.Errorf("transorming new CommD: %w", err) } - resp := generated.FilGenerateEmptySectorUpdateProof( + return cgo.GenerateEmptySectorUpdateProof( up, - commRold, - commRnew, - commD, - sectorKeyPath, - sectorKeyCachePath, - newReplicaPath, - newReplicaCachePath, + &commRold, + &commRnew, + &commD, + cgo.AsSliceRefUint8([]byte(sectorKeyPath)), + cgo.AsSliceRefUint8([]byte(sectorKeyCachePath)), + cgo.AsSliceRefUint8([]byte(newReplicaPath)), + cgo.AsSliceRefUint8([]byte(newReplicaCachePath)), ) - resp.Deref() - defer generated.FilDestroyEmptySectorUpdateGenerateProofResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return nil, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - return copyBytes(resp.ProofPtr, resp.ProofLen), nil } func (FunctionsSectorUpdate) VerifyUpdateProof(info proof.ReplicaUpdateInfo) (bool, error) { @@ -405,19 +340,11 @@ func (FunctionsSectorUpdate) VerifyUpdateProof(info proof.ReplicaUpdateInfo) (bo return false, xerrors.Errorf("transforming new CommD: %w", err) } - resp := generated.FilVerifyEmptySectorUpdateProof( + return cgo.VerifyEmptySectorUpdateProof( up, - info.Proof, - uint(len(info.Proof)), - commRold, - commRnew, - commD, + cgo.AsSliceRefUint8(info.Proof), + &commRold, + &commRnew, + &commD, ) - resp.Deref() - defer generated.FilDestroyEmptySectorUpdateVerifyProofResponse(resp) - - if resp.StatusCode != generated.FCPResponseStatusFCPNoError { - return false, errors.New(generated.RawString(resp.ErrorMsg).Copy()) - } - return resp.IsValid, nil } diff --git a/tools.go b/tools.go deleted file mode 100644 index 60b36fbc..00000000 --- a/tools.go +++ /dev/null @@ -1,7 +0,0 @@ -//+build tools - -package ffi - -import ( - _ "github.com/xlab/c-for-go" -) diff --git a/types.go b/types.go index a18a2ab1..adea1932 100644 --- a/types.go +++ b/types.go @@ -26,22 +26,22 @@ const PublicKeyBytes = 48 const DigestBytes = 96 // Signature is a compressed affine -type Signature [SignatureBytes]byte +type Signature = [SignatureBytes]byte // PrivateKey is a compressed affine -type PrivateKey [PrivateKeyBytes]byte +type PrivateKey = [PrivateKeyBytes]byte // PublicKey is a compressed affine -type PublicKey [PublicKeyBytes]byte +type PublicKey = [PublicKeyBytes]byte // Message is a byte slice -type Message []byte +type Message = []byte // Digest is a compressed affine -type Digest [DigestBytes]byte +type Digest = [DigestBytes]byte // Used when generating a private key deterministically -type PrivateKeyGenSeed [32]byte +type PrivateKeyGenSeed = [32]byte // Proofs diff --git a/workflows.go b/workflows.go index 702c1921..a2989075 100644 --- a/workflows.go +++ b/workflows.go @@ -1,4 +1,5 @@ -//+build cgo +//go:build cgo +// +build cgo package ffi