From 8bf83bfcd08b5410fd25851eee490b1ea5dff9af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20=27birdy=27=20Danjou?= Date: Mon, 26 Jun 2023 19:38:00 +0200 Subject: [PATCH] feat() add isInitialized function --- codegen/codegen.py | 11 +++++++++++ examples/BlindAuction.sol | 4 ++-- lib/TFHE.sol | 12 ++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/codegen/codegen.py b/codegen/codegen.py index 88a1609..5ad0132 100644 --- a/codegen/codegen.py +++ b/codegen/codegen.py @@ -536,6 +536,17 @@ import "./Common.sol"; import "./Impl.sol"; library TFHE {""") + +to_print_is_initialized = """ + function isInitialized(euint{i} v) internal pure returns (bool) {{ + return euint{i}.unwrap(v) != 0; + }} +""" + +f.write(to_print_is_initialized.format(i=8)) +f.write(to_print_is_initialized.format(i=16)) +f.write(to_print_is_initialized.format(i=32)) + to_print_no_cast = """ function {f}(euint{i} a, euint{j} b) internal view returns (euint{k}) {{ diff --git a/examples/BlindAuction.sol b/examples/BlindAuction.sol index 7352c94..10665e9 100644 --- a/examples/BlindAuction.sol +++ b/examples/BlindAuction.sol @@ -63,7 +63,7 @@ contract BlindAuction is EIP712WithModifier { function bid(bytes calldata encryptedValue) public onlyBeforeEnd { euint32 value = TFHE.asEuint32(encryptedValue); euint32 existingBid = bids[msg.sender]; - if (euint32.unwrap(existingBid) != 0) { + if (TFHE.isInitialized(existingBid)) { euint32 isHigher = TFHE.lt(existingBid, value); // Update bid with value bids[msg.sender] = TFHE.cmux(isHigher, value, existingBid); @@ -78,7 +78,7 @@ contract BlindAuction is EIP712WithModifier { tokenContract.transferFrom(msg.sender, address(this), value); } euint32 currentBid = bids[msg.sender]; - if (euint32.unwrap(highestBid) == 0) { + if (!TFHE.isInitialized(highestBid)) { highestBid = currentBid; } else { highestBid = TFHE.cmux( diff --git a/lib/TFHE.sol b/lib/TFHE.sol index c550c91..9d3798d 100644 --- a/lib/TFHE.sol +++ b/lib/TFHE.sol @@ -6,6 +6,18 @@ import "./Common.sol"; import "./Impl.sol"; library TFHE { + function isInitialized(euint8 v) internal pure returns (bool) { + return euint8.unwrap(v) != 0; + } + + function isInitialized(euint16 v) internal pure returns (bool) { + return euint16.unwrap(v) != 0; + } + + function isInitialized(euint32 v) internal pure returns (bool) { + return euint32.unwrap(v) != 0; + } + function add(euint8 a, euint8 b) internal view returns (euint8) { return euint8.wrap(Impl.add(euint8.unwrap(a), euint8.unwrap(b))); }