Skip to content

Commit

Permalink
Undelegate claim effect hash and UI (#21)
Browse files Browse the repository at this point in the history
* add parser

* add effect hash

* add ui

* add flag to remove con in rust

* fix warnings

* update zxlib and ensure the code is compilable
  • Loading branch information
abenso authored Jan 8, 2025
1 parent f3830f6 commit 18f5c9b
Show file tree
Hide file tree
Showing 43 changed files with 3,114 additions and 1,372 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -78,5 +78,6 @@ fuzz-*.log
/scan-build
app/rust/.cargo/registry
app/rust/.cargo/.package-cache
app/rust/.cargo/.global-cache
app/rust/.cargo/git
app/rust/target
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ file(GLOB_RECURSE LIB_SRC
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/swap.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/c_api/rust.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/ics20_withdrawal.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/undelegate_claim.c
)

add_library(app_lib STATIC ${LIB_SRC})
Expand Down
4 changes: 4 additions & 0 deletions app/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,11 @@ APP_CUSTOM_LINK_DEPENDENCIES = rust

.PHONY: rust
rust:
ifeq ($(FULL_APP), 1)
cd rust && RUSTC_BOOTSTRAP=1 CARGO_HOME="$(CURDIR)/rust/.cargo" cargo build --target $(RUST_TARGET) --release --features full_app
else
cd rust && RUSTC_BOOTSTRAP=1 CARGO_HOME="$(CURDIR)/rust/.cargo" cargo build --target $(RUST_TARGET) --release
endif

# Before linking, we need to be sure rust lib is there
bin/app.elf: rust
Expand Down
14 changes: 14 additions & 0 deletions app/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions app/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ bech32 = { version = "0.11.0", default-features = false }
chacha20poly1305 = { version = "0.10.1", default-features = false }
# rand_core = { version = "0.6.4", default-features = false }
rand_chacha = { version = "0.3.1", default-features = false }
ethnum = { version = "1.3", default-features = false }
itoa = { version = "1.0.1", default-features = false }

[dev-dependencies]
hex = "0.4.2"
Expand Down Expand Up @@ -66,3 +68,6 @@ clippy = []
derive-debug = []
# use when compiling this crate as a lib for the cpp_tests suite
cpp_tests = []
# use when compiling this crate as a lib for the full_app suite
full_app = []
fuzzing = []
1 change: 1 addition & 0 deletions app/rust/include/rslib.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ parser_error_t rs_parameter_hash(bytes_t *data, uint8_t *output, size_t output_l
parser_error_t rs_spend_action_hash(spend_plan_t *plan, uint8_t *output, size_t output_len);
parser_error_t rs_output_action_hash(output_plan_t *plan, bytes_t *memo_key, uint8_t *output, size_t output_len);
parser_error_t rs_swap_action_hash(swap_plan_t *plan, uint8_t *output, size_t output_len);
parser_error_t rs_undelegate_claim_action_hash(undelegate_claim_plan_t *plan, uint8_t *output, size_t output_len);
parser_error_t rs_generic_action_hash(bytes_t *data, uint8_t action_type, uint8_t *output, size_t output_len);

parser_error_t rs_get_asset_id_from_metadata(const bytes_t *metadata, uint8_t *asset_id, uint16_t asset_id_len);
Expand Down
2 changes: 1 addition & 1 deletion app/rust/src/ffi.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub mod asset_id;
mod bech32;
pub mod bech32;
pub mod c_api;
mod keys;
pub mod sign;
8 changes: 8 additions & 0 deletions app/rust/src/ffi/bech32.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
use bech32::{Bech32m, ByteIterExt, Fe32IterExt, Hrp};

/// Encodes data using the Bech32m format.
///
/// # Safety
///
/// This function is unsafe because it dereferences raw pointers. The caller must ensure that:
/// - `hrp_ptr` points to a valid memory location with at least `hrp_len` bytes.
/// - `data_ptr` points to a valid memory location with at least `data_len` bytes.
/// - `output_ptr` points to a valid memory location with at least `output_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn rs_bech32_encode(
hrp_ptr: *const u8,
Expand Down
2 changes: 0 additions & 2 deletions app/rust/src/ffi/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ mod test {
use crate::keys::spend_key::SpendKeyBytes;
use decaf377::Fq;
use decaf377_rdsa::{SpendAuth, VerificationKey};
use std::println;
const SPEND_KEY: &str = "ff726c71bcec76abc6a88cba71df655b28de6580edbd33c7415fdfded2e422e7";
const SPEND_ZEMU_KEY: &str = "a1ffba0c37931f0a626137520da650632d35853bf591b36bb428630a4d87c4dc";
const ACCOUNT_IDX: u32 = 1;
Expand Down Expand Up @@ -255,7 +254,6 @@ mod test {
fvk_2.to_bytes_into(&mut keys_2.fvk).unwrap();

let s_2 = hex::encode(keys_2.fvk);
println!("HOLA {}", s_2);

assert_eq!(s, s_2);
}
Expand Down
1 change: 1 addition & 0 deletions app/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ extern crate no_std_compat as std;
use arrayref as _;
use educe as _;
use poseidon377 as _;
use ethnum as _;

pub(crate) mod address;
mod bolos;
Expand Down
3 changes: 3 additions & 0 deletions app/rust/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ pub mod swap_plaintext;
pub mod symmetric;
pub mod trading_pair;
pub mod value;
pub mod identity_key;
pub mod penalty;
pub mod fixpoint;

pub use bytes::BytesC;
pub use error::ParserError;
Expand Down
36 changes: 29 additions & 7 deletions app/rust/src/parser/amount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ use crate::constants::AMOUNT_LEN_BYTES;
use crate::utils::protobuf::encode_varint;
use crate::ParserError;
use decaf377::{Fq, Fr};
use crate::parser::fixpoint::U128x128;

#[derive(Clone)]
#[derive(Copy, Clone)]
#[cfg_attr(any(feature = "derive-debug", test), derive(Debug))]
pub struct Amount {
pub inner: u128,
Expand Down Expand Up @@ -87,15 +88,36 @@ impl TryFrom<AmountC> for Amount {
}
}

impl Into<Fq> for Amount {
fn into(self) -> Fq {
Fq::from(self.inner)
impl From<Amount> for U128x128 {
fn from(amount: Amount) -> U128x128 {
U128x128::from(amount.inner)
}
}

impl From<&Amount> for U128x128 {
fn from(value: &Amount) -> Self {
(*value).into()
}
}

impl TryFrom<U128x128> for Amount {
type Error = ParserError;
fn try_from(value: U128x128) -> Result<Self, Self::Error> {
Ok(Amount {
inner: value.try_into()?,
})
}
}

impl From<Amount> for Fq {
fn from(val: Amount) -> Self {
Fq::from(val.inner)
}
}

impl Into<Fr> for Amount {
fn into(self) -> Fr {
Fr::from(self.inner)
impl From<Amount> for Fr {
fn from(val: Amount) -> Self {
Fr::from(val.inner)
}
}

Expand Down
7 changes: 7 additions & 0 deletions app/rust/src/parser/commitment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ impl Commitment {
proto
}

pub fn to_proto_unbonding_claim(&self) -> [u8; Self::PROTO_LEN] {
let mut proto = [0u8; Self::PROTO_LEN];
proto[0..4].copy_from_slice(&[0x22, 0x22, 0x0a, 0x20]);
proto[4..].copy_from_slice(&self.0 .0);
proto
}

/// Returns the vartime_compress byte representation
/// of the internal defac377::Element
pub fn bytes_compress(&self) -> [u8; Self::LEN] {
Expand Down
3 changes: 3 additions & 0 deletions app/rust/src/parser/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ pub enum ParserError {
SwapPlanError, // Added
ParameterHashError, // Added
EffectHashError, // Added
UndelegateClaimPlanError, // Added
// Chain related
InvalidChainId,
UnexpectedChain, // Added
Expand Down Expand Up @@ -89,6 +90,8 @@ pub enum ParserError {
DetectionDataOverflow, // Added
ActionsOverflow, // Added
InvalidMetadata, // Added
Overflow,
NonIntegral,
}

impl From<ErrorKind> for ParserError {
Expand Down
12 changes: 3 additions & 9 deletions app/rust/src/parser/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ impl TryFrom<FeeC> for Fee {
// If conversion fails, create a new Value with the amount and staking token asset ID
Ok(Fee(Value {
amount: value.0.amount.try_into()?,
asset_id: Id {
0: Fq::from_le_bytes_mod_order(&STAKING_TOKEN_ASSET_ID_BYTES),
},
asset_id: Id(Fq::from_le_bytes_mod_order(&STAKING_TOKEN_ASSET_ID_BYTES))
}))
}
}
Expand All @@ -50,12 +48,8 @@ impl Fee {
pub const LEN: usize = AMOUNT_LEN_BYTES + ID_LEN_BYTES;

pub fn commit(&self, blinding: Fr) -> Result<Commitment, ParserError> {
let value = Value::try_from(self.0.clone());
if let Ok(value) = value {
Ok(value.commit(blinding, Sign::Required)?)
} else {
Err(ParserError::ClueCreationFailed)
}
let value = self.0.clone();
value.commit(blinding, Sign::Required)
}

pub fn to_bytes(&self) -> Result<[u8; Self::LEN], ParserError> {
Expand Down
129 changes: 129 additions & 0 deletions app/rust/src/parser/fixpoint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
use ethnum::U256;
use crate::parser::ParserError;
use crate::parser::amount::Amount;
use std::ops::Mul;

#[derive(Copy, Clone)]
pub struct U128x128(U256);

impl U128x128 {
/// Encode this number as a 32-byte array.
///
/// The encoding has the property that it preserves ordering, i.e., if `x <=
/// y` (with numeric ordering) then `x.to_bytes() <= y.to_bytes()` (with the
/// lex ordering on byte strings).
pub fn to_bytes(self) -> [u8; 32] {
// The U256 type has really weird endianness handling -- e.g., it reverses
// the endianness of the inner u128s (??) -- so just do it manually.
let mut bytes = [0u8; 32];
let (hi, lo) = self.0.into_words();
bytes[0..16].copy_from_slice(&hi.to_be_bytes());
bytes[16..32].copy_from_slice(&lo.to_be_bytes());
bytes
}

/// Decode this number from a 32-byte array.
pub fn from_bytes(bytes: [u8; 32]) -> Self {
// See above.
let hi = u128::from_be_bytes(bytes[0..16].try_into().expect("slice is 16 bytes"));
let lo = u128::from_be_bytes(bytes[16..32].try_into().expect("slice is 16 bytes"));
Self(U256::from_words(hi, lo))
}

/// Multiply an amount by this fraction, then round down.
pub fn apply_to_amount(self, rhs: &Amount) -> Result<Amount, ParserError> {
let mul = (Self::from(rhs) * self)?;
let out = mul
.round_down()
.try_into()
.expect("converting integral U128xU128 into Amount will succeed");
Ok(out)
}

/// Checks whether this number is integral, i.e., whether it has no fractional part.
pub fn is_integral(&self) -> bool {
let fractional_word = self.0.into_words().1;
fractional_word == 0
}

/// Rounds the number down to the nearest integer.
pub fn round_down(self) -> Self {
let integral_word = self.0.into_words().0;
Self(U256::from_words(integral_word, 0u128))
}

/// Performs checked multiplication, returning `Ok` if no overflow occurred.
pub fn checked_mul(self, rhs: &Self) -> Result<Self, ParserError> {
// It's important to use `into_words` because the `U256` type has an
// unsafe API that makes the limb ordering dependent on the host
// endianness.
let (x1, x0) = self.0.into_words();
let (y1, y0) = rhs.0.into_words();
let x0 = U256::from(x0);
let x1 = U256::from(x1);
let y0 = U256::from(y0);
let y1 = U256::from(y1);

// x = (x0*2^-128 + x1)*2^128
// y = (y0*2^-128 + y1)*2^128
// x*y = (x0*y0*2^-256 + (x0*y1 + x1*y0)*2^-128 + x1*y1)*2^256
// x*y*2^-128 = (x0*y0*2^-256 + (x0*y1 + x1*y0)*2^-128 + x1*y1)*2^128
// ^^^^^
// we drop the low 128 bits of this term as rounding error

let x0y0 = x0 * y0; // cannot overflow, widening mul
let x0y1 = x0 * y1; // cannot overflow, widening mul
let x1y0 = x1 * y0; // cannot overflow, widening mul
let x1y1 = x1 * y1; // cannot overflow, widening mul

let (x1y1_hi, _x1y1_lo) = x1y1.into_words();
if x1y1_hi != 0 {
return Err(ParserError::Overflow);
}

x1y1.checked_shl(128)
.and_then(|acc| acc.checked_add(x0y1))
.and_then(|acc| acc.checked_add(x1y0))
.and_then(|acc| acc.checked_add(x0y0 >> 128))
.map(U128x128)
.ok_or(ParserError::Overflow)
}
}

impl From<[u8; 32]> for U128x128 {
fn from(value: [u8; 32]) -> Self {
Self::from_bytes(value)
}
}

impl TryFrom<&[u8]> for U128x128 {
type Error = ParserError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Ok(<[u8; 32]>::try_from(value)
.map_err(|_| ParserError::InvalidLength)?
.into())
}
}

impl TryFrom<U128x128> for u128 {
type Error = ParserError;
fn try_from(value: U128x128) -> Result<Self, Self::Error> {
match value.is_integral() {
true => Ok(value.0.into_words().0),
false => Err(ParserError::NonIntegral),
}
}
}

impl From<u128> for U128x128 {
fn from(value: u128) -> Self {
Self(U256::from_words(value, 0))
}
}

impl Mul<U128x128> for U128x128 {
type Output = Result<U128x128, ParserError>;
fn mul(self, rhs: U128x128) -> Self::Output {
self.checked_mul(&rhs)
}
}
Loading

0 comments on commit 18f5c9b

Please sign in to comment.