Skip to content
This repository has been archived by the owner on Dec 23, 2024. It is now read-only.

fix: invalid input to C.u256_from_big_endian_bytes #116

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions fhevm/tfhe/tfhe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,30 @@ func TestMain(m *testing.M) {
os.Exit(m.Run())
}

func TestBigIntToCU256(t *testing.T) {
i := big.NewInt(0)
b := make([]byte, 32)
b[0] = 42
b[31] = 43
i.SetBytes(b)
_, err := bigIntToU256(i)
if err != nil {
t.Fatalf("bigIntToU256 must have succeeded")
}
}

func TestBigIntToCU256BigInput(t *testing.T) {
i := big.NewInt(0)
b := make([]byte, 33)
b[0] = 42
b[32] = 43
i.SetBytes(b)
_, err := bigIntToU256(i)
if err == nil {
t.Fatalf("bigIntToU256 must have failed on big input")
}
}

func TfheEncryptDecrypt(t *testing.T, fheUintType FheUintType) {
var val big.Int
switch fheUintType {
Expand Down
18 changes: 7 additions & 11 deletions fhevm/tfhe/tfhe_wrappers.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,23 +104,19 @@ func EncryptAndSerializeCompact(value uint64, fheUintType FheUintType) []byte {
return ser
}

// bigIntToU256 uses u256_from_big_endian_bytes to convert big.Int to U256
// Convert a big.Int `value` to C.U256.
// Note: If `value` is bigger than 32 bytes an error is returned.
func bigIntToU256(value *big.Int) (*C.U256, error) {
// Convert big.Int to 32-byte big-endian slice
bytes := value.Bytes()
if len(bytes) > 32 {
return nil, fmt.Errorf("big.Int too large for U256")
if len(value.Bytes()) > 32 {
return nil, fmt.Errorf("big.Int value is more than 32 bytes")
}
paddedBytes := make([]byte, 32-len(bytes)) // Padding
paddedBytes = append(paddedBytes, bytes...)

bytes := make([]byte, 32)
value.FillBytes(bytes)
var result C.U256

_, err := C.u256_from_big_endian_bytes((*C.uint8_t)(unsafe.Pointer(&paddedBytes[0])), C.size_t(32), &result)
_, err := C.u256_from_big_endian_bytes((*C.uint8_t)(unsafe.Pointer(&bytes[0])), C.size_t(32), &result)
if err != nil {
return nil, fmt.Errorf("failed to convert big.Int to U256: %v", err)
}

return &result, nil
}

Expand Down
Loading