gomcaptcha/gomcaptcha.go

60 lines
1.6 KiB
Go

// SPDX-FileCopyrightText: 2024 Aravinth Manivannan <realaravinth@batsense.net>
//
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// Go library that implements mCaptcha PoW.
// It is a wrapper over [mcaptcha_pow_sha256](https://crates.io/crates/mcaptcha_pow_sha256).
package gomcaptcha
/*
#cgo LDFLAGS: ./lib/libmcaptcha_pow_ffi.a -ldl
#include "./mcaptcha-pow-ffi/mcaptcha_pow_ffi.h"
#include <stdlib.h>
*/
import "C"
// Struct representing Proof-of-Work
type ProofOfWork struct {
Nonce uint64
Result string
}
// Compute Proof-of-Work over the challenge parameters presented by mCaptcha.
// All input data will be supplied by the mCaptcha instance.
// Outputs Proof-of-Work.
func ProveWork(salt string, phrase string, difficulty uint) ProofOfWork {
res := C.prove_work(C.CString(salt),
C.CString(phrase), C.uint(difficulty))
return ProofOfWork{
Nonce: uint64(res.nonce),
Result: C.GoString(res.result),
}
}
// / Check if Proof-of-Work is of sufficient difficulty. Use same salt and difficulty
// values used to compute PoW.
func (v ProofOfWork) IsSufficientDifficulty(salt string, difficulty uint) bool {
res := C.is_sufficient_difficulty(
C.ulong(v.Nonce),
C.CString(v.Result),
C.CString(salt),
C.uint(difficulty))
return bool(res)
}
// / Check if Proof-of-Work is valid. Use same challenge phrase and salt values
// used to compute PoW.
func (v ProofOfWork) IsValidProof(phrase string, salt string) bool {
res := C.is_valid_proof(
C.ulong(v.Nonce),
C.CString(v.Result),
C.CString(phrase),
C.CString(salt))
return bool(res)
}