Skip to content

Commit

Permalink
feat: generate script challenge on the ledger (#6344)
Browse files Browse the repository at this point in the history
Description
---
This generates the entire challenge for the script signature on the
ledger.
Move signature signing functions into respective handler files.
Move hash domains into the hashing file.

Motivation and Context
---
The total payload size is smaller than before, and can now be done in a
single message. With no batching needed I've removed the script
signature context struct on the ledger side to reduce complexity, remove
persisted state, and free up a bit of memory.

How Has This Been Tested?
---
Manually with new wallets

Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify
  • Loading branch information
brianp authored May 20, 2024
1 parent 69bc94a commit 34db82d
Show file tree
Hide file tree
Showing 10 changed files with 181 additions and 202 deletions.
4 changes: 3 additions & 1 deletion applications/minotari_ledger_wallet/wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ license = "BSD-3-Clause"
edition = "2021"

[dependencies]
tari_crypto = { version = "0.20.1", default-features = false, features = ["borsh"]}
tari_hashing = { path = "../../../hashing", version = "1.0.0-pre.13" }

blake2 = { version = "0.10", default-features = false }
borsh = { version = "1.2", default-features = false }
critical-section = { version = "1.1.1" }
digest = { version = "0.10", default-features = false }
embedded-alloc = "0.5.0"
include_gif = "1.0.1"
ledger_device_sdk = "1.7.1"
tari_crypto = { version = "0.20.1", default-features = false, features = ["borsh"]}
zeroize = { version = "1" , default-features = false }

# once_cell defined here just to lock the version. Other dependencies may try to go to 1.19 which is incompatabile with
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

use alloc::format;

use blake2::Blake2b;
use digest::consts::U64;
use ledger_device_sdk::{io::Comm, ui::gadgets::SingleMessage};
use tari_crypto::{
keys::PublicKey,
Expand All @@ -13,11 +15,12 @@ use tari_crypto::{
RistrettoSecretKey,
},
};
use zeroize::Zeroizing;
use tari_hashing::TransactionHashDomain;

use crate::{
alloc::string::ToString,
utils::{derive_from_bip32_key, finalize_metadata_signature_challenge, get_key_from_canonical_bytes},
hashing::DomainSeparatedConsensusHasher,
utils::{derive_from_bip32_key, get_key_from_canonical_bytes},
AppSW,
KeyType,
RESPONSE_VERSION,
Expand Down Expand Up @@ -55,11 +58,7 @@ pub fn handler_get_metadata_signature(comm: &mut Comm) -> Result<(), AppSW> {
let ephemeral_private_key = derive_from_bip32_key(account, ephemeral_private_nonce_index, KeyType::Nonce)?;
let ephemeral_pubkey = RistrettoPublicKey::from_secret_key(&ephemeral_private_key);

let sender_offset_private_key = Zeroizing::new(derive_from_bip32_key(
account,
sender_offset_key_index,
KeyType::SenderOffset,
)?);
let sender_offset_private_key = derive_from_bip32_key(account, sender_offset_key_index, KeyType::SenderOffset)?;
let sender_offset_public_key = RistrettoPublicKey::from_secret_key(&sender_offset_private_key);

let challenge = finalize_metadata_signature_challenge(
Expand Down Expand Up @@ -97,3 +96,24 @@ pub fn handler_get_metadata_signature(comm: &mut Comm) -> Result<(), AppSW> {

Ok(())
}

fn finalize_metadata_signature_challenge(
_version: u64,
network: u64,
sender_offset_public_key: &RistrettoPublicKey,
ephemeral_commitment: &PedersenCommitment,
ephemeral_pubkey: &RistrettoPublicKey,
commitment: &PedersenCommitment,
message: &[u8; 32],
) -> [u8; 64] {
let challenge =
DomainSeparatedConsensusHasher::<TransactionHashDomain, Blake2b<U64>>::new("metadata_signature", network)
.chain(ephemeral_pubkey)
.chain(ephemeral_commitment)
.chain(sender_offset_public_key)
.chain(commitment)
.chain(&message)
.finalize();

challenge.into()
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,98 +3,82 @@

use alloc::format;

use ledger_device_sdk::{io::Comm, ui::gadgets::SingleMessage};
use tari_crypto::ristretto::{
pedersen::extended_commitment_factory::ExtendedPedersenCommitmentFactory,
RistrettoComAndPubSig,
RistrettoSecretKey,
use blake2::Blake2b;
use digest::consts::U64;
use ledger_device_sdk::{io::Comm, random::Random, ui::gadgets::SingleMessage};
use tari_crypto::{
commitment::HomomorphicCommitmentFactory,
keys::PublicKey,
ristretto::{
pedersen::{extended_commitment_factory::ExtendedPedersenCommitmentFactory, PedersenCommitment},
RistrettoComAndPubSig,
RistrettoPublicKey,
RistrettoSecretKey,
},
};
use tari_hashing::TransactionHashDomain;
use zeroize::Zeroizing;

use crate::{
alloc::string::ToString,
hashing::DomainSeparatedConsensusHasher,
utils::{alpha_hasher, derive_from_bip32_key, get_key_from_canonical_bytes},
AppSW,
KeyType,
RESPONSE_VERSION,
STATIC_ALPHA_INDEX,
};

const MAX_TRANSACTION_LEN: usize = 312;
pub struct ScriptSignatureCtx {
payload: [u8; MAX_TRANSACTION_LEN],
payload_len: usize,
account: u64,
}

// Implement constructor for TxInfo with default values
impl ScriptSignatureCtx {
pub fn new() -> Self {
Self {
payload: [0u8; MAX_TRANSACTION_LEN],
payload_len: 0,
account: 0,
}
}

// Implement reset for TxInfo
fn reset(&mut self) {
self.payload = [0u8; MAX_TRANSACTION_LEN];
self.payload_len = 0;
self.account = 0;
}
}

pub fn handler_get_script_signature(
comm: &mut Comm,
chunk: u8,
more: bool,
signer_ctx: &mut ScriptSignatureCtx,
) -> Result<(), AppSW> {
pub fn handler_get_script_signature(comm: &mut Comm) -> Result<(), AppSW> {
let data = comm.get_data().map_err(|_| AppSW::WrongApduLength)?;

if chunk == 0 {
// Reset transaction context
signer_ctx.reset();
}

if signer_ctx.payload_len + data.len() > MAX_TRANSACTION_LEN {
return Err(AppSW::ScriptSignatureFail);
}

// Append data to signer_ctx
signer_ctx.payload[signer_ctx.payload_len..signer_ctx.payload_len + data.len()].copy_from_slice(data);
signer_ctx.payload_len += data.len();
let mut account_bytes = [0u8; 8];
account_bytes.clone_from_slice(&data[0..8]);
let account = u64::from_le_bytes(account_bytes);

// If we expect more chunks, return
if more {
return Ok(());
}
let mut network_bytes = [0u8; 8];
network_bytes.clone_from_slice(&data[8..16]);
let network = u64::from_le_bytes(network_bytes);

// Set the account for the transaction
let mut account_bytes = [0u8; 8];
account_bytes.clone_from_slice(&signer_ctx.payload[0..8]);
signer_ctx.account = u64::from_le_bytes(account_bytes);
let mut txi_version_bytes = [0u8; 8];
txi_version_bytes.clone_from_slice(&data[16..24]);
let txi_version = u64::from_le_bytes(txi_version_bytes);

let alpha = derive_from_bip32_key(signer_ctx.account, STATIC_ALPHA_INDEX, KeyType::Alpha)?;
let alpha = derive_from_bip32_key(account, STATIC_ALPHA_INDEX, KeyType::Alpha)?;
let blinding_factor: Zeroizing<RistrettoSecretKey> =
get_key_from_canonical_bytes::<RistrettoSecretKey>(&signer_ctx.payload[8..40])?.into();
get_key_from_canonical_bytes::<RistrettoSecretKey>(&data[24..56])?.into();
let script_private_key = alpha_hasher(alpha, blinding_factor)?;
let script_public_key = RistrettoPublicKey::from_secret_key(&script_private_key);

let value: Zeroizing<RistrettoSecretKey> =
get_key_from_canonical_bytes::<RistrettoSecretKey>(&signer_ctx.payload[40..72])?.into();
get_key_from_canonical_bytes::<RistrettoSecretKey>(&data[56..88])?.into();
let spend_private_key: Zeroizing<RistrettoSecretKey> =
get_key_from_canonical_bytes::<RistrettoSecretKey>(&signer_ctx.payload[72..104])?.into();
let r_a: Zeroizing<RistrettoSecretKey> =
get_key_from_canonical_bytes::<RistrettoSecretKey>(&signer_ctx.payload[104..136])?.into();
let r_x: Zeroizing<RistrettoSecretKey> =
get_key_from_canonical_bytes::<RistrettoSecretKey>(&signer_ctx.payload[136..168])?.into();
let r_y: Zeroizing<RistrettoSecretKey> =
get_key_from_canonical_bytes::<RistrettoSecretKey>(&signer_ctx.payload[168..200])?.into();
let challenge = &signer_ctx.payload[200..264];
get_key_from_canonical_bytes::<RistrettoSecretKey>(&data[88..120])?.into();

let commitment: PedersenCommitment = get_key_from_canonical_bytes(&data[120..152])?;

let mut script_message = [0u8; 32];
script_message.clone_from_slice(&data[152..184]);

let r_a = derive_from_bip32_key(account, u32::random().into(), KeyType::Nonce)?;
let r_x = derive_from_bip32_key(account, u32::random().into(), KeyType::Nonce)?;
let r_y = derive_from_bip32_key(account, u32::random().into(), KeyType::Nonce)?;

let factory = ExtendedPedersenCommitmentFactory::default();

let ephemeral_commitment = factory.commit(&r_x, &r_a);
let ephemeral_pubkey = RistrettoPublicKey::from_secret_key(&r_y);

let challenge = finalize_script_signature_challenge(
txi_version,
network,
&ephemeral_commitment,
&ephemeral_pubkey,
&script_public_key,
&commitment,
&script_message,
);

let script_signature = match RistrettoComAndPubSig::sign(
&value,
&spend_private_key,
Expand All @@ -114,8 +98,26 @@ pub fn handler_get_script_signature(

comm.append(&[RESPONSE_VERSION]); // version
comm.append(&script_signature.to_vec());
signer_ctx.reset();
comm.reply_ok();

Ok(())
}

fn finalize_script_signature_challenge(
_version: u64,
network: u64,
ephemeral_commitment: &PedersenCommitment,
ephemeral_pubkey: &RistrettoPublicKey,
script_public_key: &RistrettoPublicKey,
commitment: &PedersenCommitment,
message: &[u8; 32],
) -> [u8; 64] {
DomainSeparatedConsensusHasher::<TransactionHashDomain, Blake2b<U64>>::new("script_challenge", network)
.chain(ephemeral_commitment)
.chain(ephemeral_pubkey)
.chain(script_public_key)
.chain(commitment)
.chain(message)
.finalize()
.into()
}
23 changes: 7 additions & 16 deletions applications/minotari_ledger_wallet/wallet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use handlers::{
get_public_alpha::handler_get_public_alpha,
get_public_key::handler_get_public_key,
get_script_offset::{handler_get_script_offset, ScriptOffsetCtx},
get_script_signature::{handler_get_script_signature, ScriptSignatureCtx},
get_script_signature::handler_get_script_signature,
get_version::handler_get_version,
};
#[cfg(feature = "pending_review_screen")]
Expand Down Expand Up @@ -111,7 +111,7 @@ pub enum Instruction {
GetAppName,
GetPublicKey,
GetPublicAlpha,
GetScriptSignature { chunk: u8, more: bool },
GetScriptSignature,
GetScriptOffset { chunk: u8, more: bool },
GetMetadataSignature,
}
Expand Down Expand Up @@ -162,16 +162,13 @@ impl TryFrom<ApduHeader> for Instruction {
(2, 0, 0) => Ok(Instruction::GetAppName),
(3, 0, 0) => Ok(Instruction::GetPublicAlpha),
(4, 0, 0) => Ok(Instruction::GetPublicKey),
(5, 0..=MAX_PAYLOADS, 0 | P2_MORE) => Ok(Instruction::GetScriptSignature {
chunk: value.p1,
more: value.p2 == P2_MORE,
}),
(5, 0, 0) => Ok(Instruction::GetScriptSignature),
(6, 0..=MAX_PAYLOADS, 0 | P2_MORE) => Ok(Instruction::GetScriptOffset {
chunk: value.p1,
more: value.p2 == P2_MORE,
}),
(7, 0, 0) => Ok(Instruction::GetMetadataSignature),
(5..=6, _, _) => Err(AppSW::WrongP1P2),
(6, _, _) => Err(AppSW::WrongP1P2),
(_, _, _) => Err(AppSW::InsNotSupported),
}
}
Expand All @@ -191,27 +188,21 @@ extern "C" fn sample_main() {
display_pending_review(&mut comm);

// This is long lived over the span the ledger app is open, across multiple interactions
let mut signer_ctx = ScriptSignatureCtx::new();
let mut offset_ctx = ScriptOffsetCtx::new();

loop {
// Wait for either a specific button push to exit the app
// or an APDU command
if let Event::Command(ins) = ui_menu_main(&mut comm) {
match handle_apdu(&mut comm, ins, &mut signer_ctx, &mut offset_ctx) {
match handle_apdu(&mut comm, ins, &mut offset_ctx) {
Ok(()) => comm.reply_ok(),
Err(sw) => comm.reply(sw),
}
}
}
}

fn handle_apdu(
comm: &mut Comm,
ins: Instruction,
signer_ctx: &mut ScriptSignatureCtx,
offset_ctx: &mut ScriptOffsetCtx,
) -> Result<(), AppSW> {
fn handle_apdu(comm: &mut Comm, ins: Instruction, offset_ctx: &mut ScriptOffsetCtx) -> Result<(), AppSW> {
match ins {
Instruction::GetVersion => handler_get_version(comm),
Instruction::GetAppName => {
Expand All @@ -220,7 +211,7 @@ fn handle_apdu(
},
Instruction::GetPublicKey => handler_get_public_key(comm),
Instruction::GetPublicAlpha => handler_get_public_alpha(comm),
Instruction::GetScriptSignature { chunk, more } => handler_get_script_signature(comm, chunk, more, signer_ctx),
Instruction::GetScriptSignature => handler_get_script_signature(comm),
Instruction::GetScriptOffset { chunk, more } => handler_get_script_offset(comm, chunk, more, offset_ctx),
Instruction::GetMetadataSignature => handler_get_metadata_signature(comm),
}
Expand Down
Loading

0 comments on commit 34db82d

Please sign in to comment.