Skip to content

Commit

Permalink
Effect hash computation (#7)
Browse files Browse the repository at this point in the history
* spend effect hash

* output effect hash

* delegation and undelegation effect hash

* format files

* update snapshots
  • Loading branch information
abenso authored Nov 25, 2024
1 parent e12fa54 commit 664b16f
Show file tree
Hide file tree
Showing 160 changed files with 2,861 additions and 1,866 deletions.
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,11 @@ file(GLOB_RECURSE LIB_SRC
${CMAKE_CURRENT_SOURCE_DIR}/app/src/nanopb_tiny/pb_common.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/nanopb_tiny/pb_decode.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/parser_interface.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/parser_pb_utils.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/spend_plan.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/output_plan.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/delegate_plan.c
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan/undelegate_plan.c
)

add_library(app_lib STATIC ${LIB_SRC})
Expand All @@ -153,6 +158,7 @@ target_include_directories(app_lib PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/app/src/nanopb_tiny
${CMAKE_CURRENT_SOURCE_DIR}/app/src/protobuf
${CMAKE_CURRENT_SOURCE_DIR}/app/rust/include
${CMAKE_CURRENT_SOURCE_DIR}/app/src/plan
)

##############################################################
Expand Down Expand Up @@ -233,6 +239,7 @@ target_include_directories(unittests PRIVATE
${CONAN_INCLUDE_DIRS_JSONCPP}
${CMAKE_CURRENT_SOURCE_DIR}/app/src
${CMAKE_CURRENT_SOURCE_DIR}/app/src/lib
${CMAKE_CURRENT_SOURCE_DIR}/app/rust/include
)

target_link_libraries(unittests PRIVATE
Expand Down
9 changes: 9 additions & 0 deletions app/rust/.cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,12 @@ rustflags = [
"-C",
"inline-threshold=0",
]


[target.'cfg(target_os = "linux")']
rustflags = [
"-C",
"link-arg=-Wl,--gc-sections",
"-C",
"link-arg=-Wl,--as-needed",
]
1 change: 1 addition & 0 deletions app/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ panic = "abort"

[features]
clippy = []
derive-debug = []

[patch.crates-io]
# decaf377 = { path = "../decaf377" }
Expand Down
20 changes: 15 additions & 5 deletions app/rust/include/rslib.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

#include "coin.h"

#ifdef __cplusplus
extern "C" {
#endif

void get_sr25519_sk(uint8_t *sk_ed25519_expanded);

void sign_sr25519_phase1(const uint8_t *sk_ed25519_expanded, const uint8_t *pk, const uint8_t *context_ptr,
Expand All @@ -19,11 +23,17 @@ parser_error_t rs_compute_address(keys_t *keys, uint32_t account, uint8_t *rando

// use to compute the full-viewing key
parser_error_t rs_compute_keys(keys_t *keys);
int32_t rs_bech32_encode(const uint8_t *hrp_ptr, size_t hrp_len, const uint8_t *data_ptr, size_t data_len,
uint8_t *output_ptr, size_t output_len);

// use to compute the full-viewing key
parser_error_t rs_compute_effect_hash();
parser_error_t rs_compute_effect_hash(transaction_plan_t *plan, uint8_t *output, size_t output_len);

parser_error_t rs_compute_transaction_plan(transaction_plan_t *plan, uint8_t *output, size_t output_len);
parser_error_t rs_parameter_hash(bytes_t *data, uint8_t *output, size_t output_len);
parser_error_t rs_spend_action_hash(spend_key_bytes_t *sk, spend_plan_t *plan, uint8_t *output, size_t output_len);
parser_error_t rs_output_action_hash(spend_key_bytes_t *sk, output_plan_t *plan, bytes_t *memo_key, 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);

int32_t rs_bech32_encode(const uint8_t *hrp_ptr, size_t hrp_len, const uint8_t *data_ptr, size_t data_len,
uint8_t *output_ptr, size_t output_len);
#ifdef __cplusplus
}
#endif
18 changes: 17 additions & 1 deletion app/rust/src/address.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
/*******************************************************************************
* (c) 2024 Zondax GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/

use decaf377::Fq;

use crate::keys::dk::Diversifier;
Expand Down Expand Up @@ -94,7 +110,7 @@ impl Address {
&self.ck_d
}

pub fn raw_bytes(&self) -> Result<[u8; Self::LEN], ParserError> {
pub fn to_bytes(&self) -> Result<[u8; Self::LEN], ParserError> {
let mut bytes = [0; Self::LEN];
bytes[0..16].copy_from_slice(self.diversifier().as_ref());
bytes[16..48].copy_from_slice(&self.transmission_key().0);
Expand Down
3 changes: 2 additions & 1 deletion app/rust/src/bolos.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*******************************************************************************
* (c) 2018 - 2023 Zondax AG
* (c) 2024 Zondax GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/

//! Rust interfaces to Ledger SDK APIs.
#[cfg(test)]
use getrandom::getrandom;
Expand Down
5 changes: 5 additions & 0 deletions app/rust/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@ pub const INCOMING_VIEWING_KEY_LEN: usize = KEY_LEN; //
/// The maximum detection precision, chosen so that the message bits fit in 3 bytes.
pub const MAX_PRECISION: u8 = 24;
pub const PAYLOAD_KEY_LEN_BYTES: usize = 32;
pub const RSEED_LEN_BYTES: usize = 32;
pub const ID_LEN_BYTES: usize = 32;
pub const AMOUNT_LEN_BYTES: usize = 16;

pub const DETECTION_DATA_QTY: usize = 16;
pub const ACTION_DATA_QTY: usize = 16;
pub const MAX_CLUE_SUBKEYS: usize = 10;

pub const EFFECT_HASH_LEN: usize = 64;

// Nonces:
pub const NONCE_LEN: usize = 12;
pub const NONCE_NOTE: &[u8; NONCE_LEN] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
Expand Down
2 changes: 1 addition & 1 deletion app/rust/src/ffi/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ fn compute_address(keys: &mut Keys, addr_idx: AddressIndex) -> Result<(), Parser
let address = ivk.payment_address(addr_idx).map(|(addr, _)| addr)?;

// return the f4jumble encoded raw address
let raw = address.raw_bytes()?;
let raw = address.to_bytes()?;

keys.address.copy_from_slice(&raw);

Expand Down
19 changes: 17 additions & 2 deletions app/rust/src/keys/ka.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ use zeroize::Zeroize;

use crate::ParserError;

#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Public(pub [u8; 32]);

#[derive(Clone, Zeroize, PartialEq, Eq)]
#[derive(Clone, Zeroize, PartialEq, Eq, Debug)]
#[zeroize(drop)]
pub struct Secret(decaf377::Fr);

#[derive(Clone, Zeroize, PartialEq, Eq, Debug)]
#[zeroize(drop)]
pub struct SharedSecret(pub [u8; 32]);

impl Secret {
/// Generate a new secret key using the provided `decaf377` field element.
/// Meant to be used with the SigningKey abstraction.
Expand All @@ -34,6 +38,17 @@ impl Secret {
pub fn to_bytes(&self) -> [u8; 32] {
self.0.to_bytes()
}

/// Perform key agreement with the provided public key.
///
/// Fails if the provided public key is invalid.
pub fn key_agreement_with(&self, other: &Public) -> Result<SharedSecret, ParserError> {
let pk = decaf377::Encoding(other.0)
.vartime_decompress()
.map_err(|_| ParserError::InvalidPubkeyEncoding)?;

Ok(SharedSecret((self.0 * pk).vartime_compress().into()))
}
}

impl TryFrom<&[u8]> for Public {
Expand Down
7 changes: 3 additions & 4 deletions app/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,19 @@ extern crate no_std_compat as std;
extern crate hex_literal;

use poseidon377 as _;
use educe as _;
use arrayref as _;

// pub(crate) mod addr;
pub(crate) mod address;
mod bolos;
pub mod constants;
pub mod effect_hash;
pub mod ffi;
pub(crate) mod keys;
pub mod network;
pub mod parser;
mod utils;
pub mod wallet_id;

pub use effect_hash::EffectHash;
pub use parser::{FromBytes, ParserError, ViewError};
pub(crate) use utils::prf::{expand_fq, expand_fr};

Expand Down Expand Up @@ -71,7 +70,7 @@ pub fn is_expert_mode() -> bool {
unsafe { app_mode_expert() > 0 }
}

#[cfg(any(test, fuzzing))]
#[cfg(any(test, feature = "fuzzing"))]
pub fn is_expert_mode() -> bool {
true
}
Expand Down
37 changes: 15 additions & 22 deletions app/rust/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,27 @@ use core::mem::MaybeUninit;
// actions:
// https://rustdoc.penumbra.zone/main/penumbra_transaction/plan/enum.ActionPlan.html
mod address;
mod amount;
mod asset_id;
mod clue_plan;
mod curve_fields;
mod error;
mod fee;
mod note;
mod object_list;
mod note_payload;
mod plans;
mod position;
mod precision;
mod tx_parameters;
mod value;
mod bytes;

pub use address::Address;
pub use amount::Amount;
pub use asset_id::AssetId;
pub use clue_plan::CluePlan;
pub use curve_fields::{Fq, Fr};
mod parameters;
pub mod action;
pub mod amount;
pub mod balance;
pub mod commitment;
pub mod detection;
pub mod id;
pub mod memo;
pub mod memo_plain_text;
pub mod nullifier;
pub mod rseed;
pub mod symmetric;
pub mod value;
pub mod effect_hash;
pub use error::ParserError;
pub use fee::Fee;
pub use note::Note;
pub use object_list::ObjectList;
pub use position::{Position, Tree};
pub use precision::Precision;
pub use tx_parameters::TransactionParameters;
pub use value::Value;

#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(test, derive(Debug))]
Expand Down
66 changes: 66 additions & 0 deletions app/rust/src/parser/action.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*******************************************************************************
* (c) 2024 Zondax GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/

use crate::constants::ACTION_DATA_QTY;

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ActionPlan {
Spend = 1,
Output = 2,
Swap = 3,
SwapClaim = 4,
ValidatorDefinition = 16,
IbcAction = 17,
ProposalSubmit = 18,
ProposalWithdraw = 19,
ValidatorVote = 20,
DelegatorVote = 21,
ProposalDepositClaim = 22,
PositionOpen = 30,
PositionClose = 31,
PositionWithdraw = 32,
Delegate = 40,
Undelegate = 41,
UndelegateClaim = 42,
CommunityPoolSpend = 50,
CommunityPoolOutput = 51,
CommunityPoolDeposit = 52,
Ics20Withdrawal = 200,
ActionDutchAuctionSchedule = 53,
ActionDutchAuctionEnd = 54,
ActionDutchAuctionWithdraw = 55,
}

impl ActionPlan {
pub fn from(action_type: u8) -> Self {
unsafe { std::mem::transmute(action_type) }
}
}

#[repr(C)]
#[derive(Copy, Clone)]
#[cfg_attr(any(feature = "derive-debug", test), derive(Debug))]
pub struct ActionHash(pub [u8; 64]);

#[repr(C)]
#[derive(Clone)]
#[cfg_attr(any(feature = "derive-debug", test), derive(Debug))]
pub struct ActionsHashC {
pub qty: u8,
pub hashes: [ActionHash; ACTION_DATA_QTY],
}

Loading

0 comments on commit 664b16f

Please sign in to comment.