Skip to content

Commit

Permalink
Add verify_k256_sha256 to kotlin bindings (#308)
Browse files Browse the repository at this point in the history
* add the verify method to the kotlin rust bindings

* fix error mapping

* add to udl and export to kotlin

* add the so files
  • Loading branch information
nplasterer authored Nov 3, 2023
1 parent 2ffa175 commit 981e352
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 0 deletions.
Binary file modified xmtp_dh/jniLibs/arm64-v8a/libuniffi_xmtp_dh.so
Binary file not shown.
Binary file modified xmtp_dh/jniLibs/armeabi-v7a/libuniffi_xmtp_dh.so
Binary file not shown.
Binary file modified xmtp_dh/jniLibs/x86/libuniffi_xmtp_dh.so
Binary file not shown.
Binary file modified xmtp_dh/jniLibs/x86_64/libuniffi_xmtp_dh.so
Binary file not shown.
36 changes: 36 additions & 0 deletions xmtp_dh/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,26 @@ impl std::fmt::Display for EciesError {
}
}

#[derive(Debug)]
pub enum VerifyError {
GenericError(String),
}

impl std::error::Error for VerifyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
VerifyError::GenericError(_) => None,
}
}
}

impl std::fmt::Display for VerifyError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
VerifyError::GenericError(ref message) => write!(f, "{}", message),
}
}
}
pub fn diffie_hellman_k256(
private_key_bytes: Vec<u8>,
public_key_bytes: Vec<u8>,
Expand All @@ -58,6 +78,22 @@ pub fn diffie_hellman_k256(
Ok(shared_secret)
}

pub fn verify_k256_sha256(
signed_by: Vec<u8>,
message: Vec<u8>,
signature: Vec<u8>,
recovery_id: u8,
) -> Result<bool, VerifyError> {
let result = k256_helper::verify_sha256(
signed_by.as_slice(),
message.as_slice(),
signature.as_slice(),
recovery_id,
).map_err(VerifyError::GenericError)?;

Ok(result)
}

pub fn ecies_encrypt_k256_sha3_256(
public_key_bytes: Vec<u8>,
private_key_bytes: Vec<u8>,
Expand Down
76 changes: 76 additions & 0 deletions xmtp_dh/src/uniffi/xmtp_dh/xmtp_dh.kt
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,8 @@ internal interface _UniFFILib : Library {
): RustBuffer.ByValue
fun uniffi_xmtp_dh_fn_func_generate_private_preferences_topic_identifier(`privateKeyBytes`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus,
): RustBuffer.ByValue
fun uniffi_xmtp_dh_fn_func_verify_k256_sha256(`signedBy`: RustBuffer.ByValue,`message`: RustBuffer.ByValue,`signature`: RustBuffer.ByValue,`recoveryId`: Byte,_uniffi_out_err: RustCallStatus,
): Byte
fun ffi_xmtp_dh_rustbuffer_alloc(`size`: Int,_uniffi_out_err: RustCallStatus,
): RustBuffer.ByValue
fun ffi_xmtp_dh_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,_uniffi_out_err: RustCallStatus,
Expand All @@ -388,6 +390,8 @@ internal interface _UniFFILib : Library {
): Short
fun uniffi_xmtp_dh_checksum_func_generate_private_preferences_topic_identifier(
): Short
fun uniffi_xmtp_dh_checksum_func_verify_k256_sha256(
): Short
fun ffi_xmtp_dh_uniffi_contract_version(
): Int

Expand Down Expand Up @@ -417,6 +421,9 @@ private fun uniffiCheckApiChecksums(lib: _UniFFILib) {
if (lib.uniffi_xmtp_dh_checksum_func_generate_private_preferences_topic_identifier() != 65141.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
if (lib.uniffi_xmtp_dh_checksum_func_verify_k256_sha256() != 45969.toShort()) {
throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
}
}

// Public interface members begin here.
Expand All @@ -442,6 +449,26 @@ public object FfiConverterUByte: FfiConverter<UByte, Byte> {
}
}

public object FfiConverterBoolean: FfiConverter<Boolean, Byte> {
override fun lift(value: Byte): Boolean {
return value.toInt() != 0
}

override fun read(buf: ByteBuffer): Boolean {
return lift(buf.get())
}

override fun lower(value: Boolean): Byte {
return if (value) 1.toByte() else 0.toByte()
}

override fun allocationSize(value: Boolean) = 1

override fun write(value: Boolean, buf: ByteBuffer) {
buf.put(lower(value))
}
}

public object FfiConverterString: FfiConverter<String, RustBuffer.ByValue> {
// Note: we don't inherit from FfiConverterRustBuffer, because we use a
// special encoding when lowering/lifting. We can use `RustBuffer.len` to
Expand Down Expand Up @@ -571,6 +598,46 @@ public object FfiConverterTypeEciesError : FfiConverterRustBuffer<EciesException




sealed class VerifyException(message: String): Exception(message) {
// Each variant is a nested class
// Flat enums carries a string error message, so no special implementation is necessary.
class GenericException(message: String) : VerifyException(message)


companion object ErrorHandler : CallStatusErrorHandler<VerifyException> {
override fun lift(error_buf: RustBuffer.ByValue): VerifyException = FfiConverterTypeVerifyError.lift(error_buf)
}
}

public object FfiConverterTypeVerifyError : FfiConverterRustBuffer<VerifyException> {
override fun read(buf: ByteBuffer): VerifyException {

return when(buf.getInt()) {
1 -> VerifyException.GenericException(FfiConverterString.read(buf))
else -> throw RuntimeException("invalid error enum value, something is very wrong!!")
}

}

override fun allocationSize(value: VerifyException): Int {
return 4
}

override fun write(value: VerifyException, buf: ByteBuffer) {
when(value) {
is VerifyException.GenericException -> {
buf.putInt(1)
Unit
}
}.let { /* this makes the `when` an expression, which ensures it is exhaustive */ }
}

}




public object FfiConverterSequenceUByte: FfiConverterRustBuffer<List<UByte>> {
override fun read(buf: ByteBuffer): List<UByte> {
val len = buf.getInt()
Expand Down Expand Up @@ -628,4 +695,13 @@ fun `generatePrivatePreferencesTopicIdentifier`(`privateKeyBytes`: List<UByte>):
})
}

@Throws(VerifyException::class)

fun `verifyK256Sha256`(`signedBy`: List<UByte>, `message`: List<UByte>, `signature`: List<UByte>, `recoveryId`: UByte): Boolean {
return FfiConverterBoolean.lift(
rustCallWithError(VerifyException) { _status ->
_UniFFILib.INSTANCE.uniffi_xmtp_dh_fn_func_verify_k256_sha256(FfiConverterSequenceUByte.lower(`signedBy`),FfiConverterSequenceUByte.lower(`message`),FfiConverterSequenceUByte.lower(`signature`),FfiConverterUByte.lower(`recoveryId`),_status)
})
}


7 changes: 7 additions & 0 deletions xmtp_dh/src/xmtp_dh.udl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ enum EciesError {
"GenericError",
};

[Error]
enum VerifyError {
"GenericError",
};

namespace xmtp_dh {
// TODO: Switch from sequence<u8> to bytes once https://github.com/mozilla/uniffi-rs/pull/1543
// is released in uniffi crate
Expand All @@ -19,4 +24,6 @@ namespace xmtp_dh {
sequence<u8> ecies_decrypt_k256_sha3_256(sequence<u8> public_key_bytes, sequence<u8> private_key_bytes, sequence<u8> message_bytes);
[Throws=EciesError]
string generate_private_preferences_topic_identifier(sequence<u8> private_key_bytes);
[Throws=VerifyError]
boolean verify_k256_sha256(sequence<u8> signed_by, sequence<u8> message, sequence<u8> signature, u8 recovery_id);
};

0 comments on commit 981e352

Please sign in to comment.