Skip to content

Commit

Permalink
Clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
elizabethengelman committed Apr 22, 2024
1 parent 0b7034e commit 6a22f34
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 50 deletions.
59 changes: 33 additions & 26 deletions cmd/crates/stellar-ledger/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,9 @@ impl<T> LedgerSigner<T>
where
T: Exchange,
{
/// Get the public key from the device
/// # Errors
/// Returns an error if there is an issue with connecting with the device or getting the public key from the device
pub async fn get_public_key(
&self,
index: u32,
Expand All @@ -87,6 +90,9 @@ where
Self::get_public_key_with_display_flag(self, hd_path, false).await
}

/// Get the device app's configuration
/// # Errors
/// Returns an error if there is an issue with connecting with the device or getting the config from the device
pub async fn get_app_configuration(&self) -> Result<Vec<u8>, LedgerError> {
let command = APDUCommand {
cla: CLA,
Expand All @@ -98,8 +104,11 @@ where
self.send_command_to_ledger(command).await
}

// based on impl from https://github.com/LedgerHQ/ledger-live/blob/develop/libs/ledgerjs/packages/hw-app-str/src/Str.ts#L166
async fn sign_transaction_hash(
/// Sign a Stellar transaction hash with the account on the Ledger device
/// based on impl from [https://github.com/LedgerHQ/ledger-live/blob/develop/libs/ledgerjs/packages/hw-app-str/src/Str.ts#L166](https://github.com/LedgerHQ/ledger-live/blob/develop/libs/ledgerjs/packages/hw-app-str/src/Str.ts#L166)
/// # Errors
/// Returns an error if there is an issue with connecting with the device or signing the given tx on the device. Or, if the device has not enabled hash signing
pub async fn sign_transaction_hash(
&self,
hd_path: slip10::BIP32Path,
transaction_hash: Vec<u8>,
Expand All @@ -125,6 +134,10 @@ where
self.send_command_to_ledger(command).await
}

/// Sign a Stellar transaction with the account on the Ledger device
/// # Errors
/// Returns an error if there is an issue with connecting with the device or signing the given tx on the device
#[allow(clippy::missing_panics_doc)] // TODO: handle panics/unwraps
pub async fn sign_transaction(
&self,
hd_path: slip10::BIP32Path,
Expand Down Expand Up @@ -159,8 +172,6 @@ where
let chunks_count = chunks.len();

let mut result = Vec::new();
println!("chunks_count: {:?}", chunks_count);

// notes:
// the first chunk has the hd_path_elements_count and the hd_path at the beginning, before the tx [3, 128...122...47]
// the second chunk has just the end of the tx [224, 100... 0, 0, 0, 0]
Expand Down Expand Up @@ -198,7 +209,7 @@ where
Ok(result)
}

/// The display_and_confirm bool determines if the Ledger will display the public key on its screen and requires user approval to share
/// The `display_and_confirm` bool determines if the Ledger will display the public key on its screen and requires user approval to share
async fn get_public_key_with_display_flag(
&self,
hd_path: slip10::BIP32Path,
Expand All @@ -210,8 +221,6 @@ where
let hd_path_elements_count = hd_path.depth();
hd_path_to_bytes.insert(0, hd_path_elements_count);

println!("data: {:?}", hd_path_to_bytes);

let p2 = if display_and_confirm {
P2_GET_PUBLIC_KEY_DISPLAY
} else {
Expand All @@ -227,15 +236,11 @@ where
data: hd_path_to_bytes,
};

tracing::info!("APDU in: {}", hex::encode(&command.serialize()));
tracing::info!("APDU in: {}", hex::encode(command.serialize()));

match self.send_command_to_ledger(command).await {
Ok(value) => {
return Ok(stellar_strkey::ed25519::PublicKey::from_payload(&value).unwrap());
}
Err(err) => {
return Err(err);
}
Ok(value) => Ok(stellar_strkey::ed25519::PublicKey::from_payload(&value).unwrap()),
Err(err) => Err(err),
}
}

Expand All @@ -251,21 +256,19 @@ where
response.retcode(),
);
// Ok means we successfully connected with the Ledger but it doesn't mean our request succeeded. We still need to check the response.retcode
println!("RETCODE: {:?}", response.retcode());
println!("response: {:?}", response.data());
if response.retcode() == RETURN_CODE_OK {
return Ok(response.data().to_vec());
}

let retcode = response.retcode();
let error_string = format!("Ledger APDU retcode: 0x{:X}", retcode);
return Err(LedgerError::APDUExchangeError(error_string));
let error_string = format!("Ledger APDU retcode: 0x{retcode:X}");
Err(LedgerError::APDUExchangeError(error_string))
}
Err(_err) => {
//FIX ME!!!!
return Err(LedgerError::LedgerConnectionError("test".to_string()));
Err(LedgerError::LedgerConnectionError("test".to_string()))
}
};
}
}
}

Expand All @@ -289,7 +292,7 @@ impl<T: Exchange> Stellar for LedgerSigner<T> {
fn sign_txn_hash(
&self,
txn: [u8; 32],
source_account: &stellar_strkey::Strkey,
_source_account: &stellar_strkey::Strkey,
) -> Result<DecoratedSignature, Error> {
let signature = block_on(self.sign_transaction_hash(self.hd_path.clone(), txn.to_vec())) //TODO: refactor sign_transaction_hash
.unwrap(); // FIXME: handle error
Expand All @@ -304,7 +307,7 @@ impl<T: Exchange> Stellar for LedgerSigner<T> {
fn sign_txn(
&self,
txn: Transaction,
source_account: &stellar_strkey::Strkey,
_source_account: &stellar_strkey::Strkey,
) -> Result<TransactionEnvelope, Error> {
let signature = block_on(self.sign_transaction(self.hd_path.clone(), txn.clone())).unwrap(); // FIXME: handle error

Expand All @@ -330,20 +333,25 @@ fn bip_path_from_index(index: u32) -> slip10::BIP32Path {

fn hd_path_to_bytes(hd_path: &slip10::BIP32Path) -> Vec<u8> {
(0..hd_path.depth())
.map(|index| {
.flat_map(|index| {
let value = *hd_path.index(index).unwrap();
value.to_be_bytes()
})
.flatten()
.collect::<Vec<u8>>()
}

/// Gets a transport connection for a ledger device
/// # Errors
/// Returns an error if there is an issue with connecting with the device
pub fn get_transport() -> Result<impl Exchange, LedgerError> {
// instantiate the connection to Ledger, this will return an error if Ledger is not connected
let hidapi = HidApi::new().map_err(LedgerError::HidApiError)?;
TransportNativeHID::new(&hidapi).map_err(LedgerError::LedgerHidError)
}

/// Gets a transport connection for a the Zemu emulator
/// # Errors
/// Returns an error if there is an issue with connecting with the device
pub fn get_zemu_transport(host: &str, port: u16) -> Result<impl Exchange, LedgerError> {
Ok(TransportZemuHttp::new(host, port))
}
Expand All @@ -365,7 +373,7 @@ mod test {
Memo, MuxedAccount, PaymentOp, Preconditions, SequenceNumber, TransactionExt,
};

use testcontainers::{clients, Container};
use testcontainers::clients;
use tokio::time::sleep;

const TEST_NETWORK_PASSPHRASE: &str = "Test SDF Network ; September 2015";
Expand All @@ -381,7 +389,6 @@ mod test {
});
let ledger = LedgerSigner::new(TEST_NETWORK_PASSPHRASE, ledger_options);
let public_key = ledger.get_public_key(0).await;
println!("{public_key:?}");
assert!(public_key.is_ok());
}

Expand Down
18 changes: 1 addition & 17 deletions cmd/crates/stellar-ledger/src/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use ed25519_dalek::Signer;
use ledger_transport::async_trait;
use sha2::{Digest, Sha256};
use soroban_env_host::xdr::{
self, DecoratedSignature, InvokeHostFunctionOp, Limits, Operation, OperationBody, Signature,
SignatureHint, SorobanAuthorizedFunction, Transaction, TransactionEnvelope,
self, DecoratedSignature, Limits, Signature, SignatureHint, Transaction, TransactionEnvelope,
TransactionSignaturePayload, TransactionSignaturePayloadTaggedTransaction,
TransactionV1Envelope, WriteXdr,
};
Expand All @@ -16,21 +15,6 @@ pub enum Error {
RpcError(#[from] RpcError),
}

fn requires_auth(txn: &Transaction) -> Option<xdr::Operation> {
let [op @ Operation {
body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp { auth, .. }),
..
}] = txn.operations.as_slice()
else {
return None;
};
matches!(
auth.first().map(|x| &x.root_invocation.function),
Some(&SorobanAuthorizedFunction::ContractFn(_))
)
.then(move || op.clone())
}

/// A trait for signing Stellar transactions and Soroban authorization entries
#[async_trait]
pub trait Stellar {
Expand Down
9 changes: 6 additions & 3 deletions cmd/crates/stellar-ledger/src/speculos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ use testcontainers::{core::WaitFor, Image, ImageArgs};
const NAME: &str = "docker.io/zondax/builder-zemu";
const TAG: &str = "speculos-3a3439f6b45eca7f56395673caaf434c202e7005";

#[allow(dead_code)]
static ENV: &Map = &Map(phf::phf_map! {
"BOLOS_SDK"=> "/project/deps/nanos-secure-sdk",
"BOLOS_ENV" => "/opt/bolos",
"DISPLAY" => "host.docker.internal:0",
});
struct Map(phf::Map<&'static str, &'static str>);

#[allow(clippy::implicit_hasher)]
impl From<&Map> for HashMap<String, String> {
fn from(Map(map): &Map) -> Self {
map.into_iter()
Expand All @@ -27,6 +29,7 @@ pub struct Speculos(
);
const DEFAULT_APP_PATH: &str = "/project/app/bin";
impl Speculos {
#[allow(dead_code)]
pub fn new() -> Self {
#[allow(unused_mut)]
let apps_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("apps");
Expand All @@ -42,9 +45,9 @@ impl Speculos {
}

#[derive(Debug, Default, Clone)]
pub struct SpeculosArgs;
pub struct Args;

impl ImageArgs for SpeculosArgs {
impl ImageArgs for Args {
fn into_iterator(self) -> Box<dyn Iterator<Item = String>> {
let container_elf_path = format!("{DEFAULT_APP_PATH}/stellarNanosApp.elf");
let command_string = format!("/home/zondax/speculos/speculos.py --log-level speculos:DEBUG --color JADE_GREEN --display headless -s \"other base behind follow wet put glad muscle unlock sell income october\" -m nanos {container_elf_path}");
Expand All @@ -53,7 +56,7 @@ impl ImageArgs for SpeculosArgs {
}

impl Image for Speculos {
type Args = SpeculosArgs;
type Args = Args;

fn name(&self) -> String {
NAME.to_owned()
Expand Down
5 changes: 1 addition & 4 deletions cmd/crates/stellar-ledger/src/transport_zemu_http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@ use thiserror::Error;

#[derive(Error, Debug)]
pub enum LedgerZemuError {
/// Device not found error
#[error("Ledger connect error")]
ConnectError,
/// zemu reponse error
#[error("Zemu response error")]
ResponseError,
Expand Down Expand Up @@ -72,7 +69,7 @@ struct ZemuResponse {
impl TransportZemuHttp {
pub fn new(host: &str, port: u16) -> Self {
Self {
url: format!("http://{}:{}", host, port),
url: format!("http://{host}:{port}"),
}
}
}
Expand Down

0 comments on commit 6a22f34

Please sign in to comment.