Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions nekoton-abi/src/abi_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use ton_types::UInt256;

use super::{BuildTokenValue, KnownParamType, UnpackerError, UnpackerResult};

#[derive(Clone, Debug)]
pub struct BigUint128(pub BigUint);

impl BuildTokenValue for BigUint128 {
Expand Down
6 changes: 3 additions & 3 deletions src/core/keystore/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use tokio::sync::RwLock;
use nekoton_utils::*;

use crate::crypto::{
EncryptedData, EncryptionAlgorithm, PasswordCache, SharedSecret, Signature, SignatureId,
EncryptedData, EncryptionAlgorithm, PasswordCache, SharedSecret, Signature, SignatureContext,
Signer, SignerContext, SignerEntry, SignerStorage,
};
use crate::external::Storage;
Expand Down Expand Up @@ -290,7 +290,7 @@ impl KeyStore {
pub async fn sign<T>(
&self,
data: &[u8],
signature_id: Option<SignatureId>,
signature_ctx: SignatureContext,
input: T::SignInput,
) -> Result<Signature>
where
Expand All @@ -303,7 +303,7 @@ impl KeyStore {
};
state
.get_signer_ref::<T>()?
.sign(ctx, data, signature_id, input)
.sign(ctx, data, signature_ctx, input)
.await
}

Expand Down
22 changes: 16 additions & 6 deletions src/core/ton_wallet/wallet_v5r1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ mod tests {
use crate::core::ton_wallet::wallet_v5r1::{
compute_contract_address, is_wallet_v5r1, InitData, WALLET_ID,
};
use crate::crypto::extend_with_signature_id;
use crate::crypto::{SignatureContext, SignatureType, ToSign};
use ed25519_dalek::{PublicKey, Signature, Verifier};
use nekoton_contracts::wallets;
use ton_block::AccountState;
Expand Down Expand Up @@ -438,15 +438,22 @@ mod tests {

let public_key = PublicKey::from_bytes(public_key_bytes.as_slice())?;

let result = check_signature(in_msg_body_slice, public_key, Some(2000))?;
let result = check_signature(
in_msg_body_slice,
public_key,
SignatureContext {
global_id: Some(2000),
signature_type: SignatureType::SignatureId,
},
)?;
assert!(result);
Ok(())
}

fn check_signature(
mut in_msg_body: SliceData,
public_key: PublicKey,
signature_id: Option<i32>,
ctx: SignatureContext,
) -> anyhow::Result<bool> {
let signature_binding = in_msg_body
.get_slice(in_msg_body.remaining_bits() - 512, 512)?
Expand All @@ -458,11 +465,14 @@ mod tests {
.into_cell();

let hash = payload.repr_hash();

let data = extend_with_signature_id(hash.as_ref(), signature_id);
let to_sign = ToSign {
ctx,
data: hash.into_vec(),
};
let data = to_sign.write_to_bytes();

Ok(public_key
.verify(&*data, &Signature::from_bytes(sig)?)
.verify(&data, &Signature::from_bytes(sig)?)
.is_ok())
}
}
16 changes: 7 additions & 9 deletions src/crypto/derived_key/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,16 @@ use std::collections::hash_map::{self, HashMap};

use anyhow::Result;
use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
use ed25519_dalek::{Keypair, PublicKey, Signer};
use ed25519_dalek::{Keypair, PublicKey};
use secstr::SecUtf8;
use serde::{Deserialize, Serialize, Serializer};

use nekoton_utils::*;

use super::mnemonic::*;
use super::{
default_key_name, extend_with_signature_id, Password, PasswordCache, PasswordCacheTransaction,
PubKey, SharedSecret, SignatureId, Signer as StoreSigner, SignerContext, SignerEntry,
SignerStorage,
default_key_name, Password, PasswordCache, PasswordCacheTransaction, PubKey, SharedSecret,
SignatureContext, Signer as StoreSigner, SignerContext, SignerEntry, SignerStorage,
};
use nekoton_utils::*;

#[derive(Default, Clone, Debug, Eq, PartialEq)]
pub struct DerivedKeySigner {
Expand Down Expand Up @@ -355,12 +353,12 @@ impl StoreSigner for DerivedKeySigner {
&self,
ctx: SignerContext<'_>,
data: &[u8],
signature_id: Option<SignatureId>,
signature_ctx: SignatureContext,
input: Self::SignInput,
) -> Result<[u8; 64]> {
let keypair = self.use_sign_input(ctx.password_cache, input)?;
let data = extend_with_signature_id(data, signature_id);
Ok(keypair.sign(&data).to_bytes())
let signature = signature_ctx.sign(&keypair, data);
Ok(signature.to_bytes())
}
}

Expand Down
32 changes: 17 additions & 15 deletions src/crypto/encrypted_key/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,17 @@ use std::io::Read;

use anyhow::Result;
use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit, Nonce};
use ed25519_dalek::{Keypair, PublicKey, SecretKey, Signer};
use ed25519_dalek::{Keypair, PublicKey, SecretKey};
use rand::Rng;
use secstr::SecUtf8;
use serde::{Deserialize, Serialize};

use nekoton_utils::*;

use super::mnemonic::*;
use super::{
default_key_name, extend_with_signature_id, Password, PasswordCache, PasswordCacheTransaction,
PubKey, SharedSecret, SignatureId, Signer as StoreSigner, SignerContext, SignerEntry,
SignerStorage,
default_key_name, Password, PasswordCache, PasswordCacheTransaction, PubKey, SharedSecret,
SignatureContext, Signer as StoreSigner, SignerContext, SignerEntry, SignerStorage,
};
use nekoton_utils::*;

#[derive(Default, Clone, Debug, Eq, PartialEq)]
pub struct EncryptedKeySigner {
Expand Down Expand Up @@ -194,7 +192,7 @@ impl StoreSigner for EncryptedKeySigner {
&self,
ctx: SignerContext<'_>,
data: &[u8],
signature_id: Option<SignatureId>,
signature_ctx: SignatureContext,
input: Self::SignInput,
) -> Result<[u8; 64]> {
let key = self.get_key(&input.public_key)?;
Expand All @@ -203,7 +201,7 @@ impl StoreSigner for EncryptedKeySigner {
.password_cache
.process_password(input.public_key.to_bytes(), input.password)?;

let signature = key.sign(data, signature_id, password.as_ref())?;
let signature = key.sign(data, password.as_ref(), signature_ctx)?;

password.proceed();
Ok(signature)
Expand Down Expand Up @@ -471,10 +469,10 @@ impl EncryptedKey {
pub fn sign(
&self,
data: &[u8],
signature_id: Option<SignatureId>,
password: &str,
signature_ctx: SignatureContext,
) -> Result<[u8; ed25519_dalek::SIGNATURE_LENGTH]> {
self.inner.sign(data, signature_id, password)
self.inner.sign(data, password, signature_ctx)
}

pub fn compute_shared_keys(
Expand Down Expand Up @@ -532,16 +530,16 @@ impl CryptoData {
pub fn sign(
&self,
data: &[u8],
signature_id: Option<SignatureId>,
password: &str,
signature_ctx: SignatureContext,
) -> Result<[u8; ed25519_dalek::SIGNATURE_LENGTH]> {
let secret = self.decrypt_secret(password)?;
let pair = Keypair {
secret,
public: self.pubkey,
};
let data = extend_with_signature_id(data, signature_id);
Ok(pair.sign(&data).to_bytes())
let signature = signature_ctx.sign(&pair, data);
Ok(signature.to_bytes())
}

pub fn compute_shared_keys(
Expand Down Expand Up @@ -664,7 +662,7 @@ mod tests {
use std::time::Duration;

use super::*;
use crate::crypto::PasswordCacheBehavior;
use crate::crypto::{PasswordCacheBehavior, SignatureType};

const TEST_PASSWORD: &str = "123";
const TEST_MNEMONIC: &str = "canyon stage apple useful bench lazy grass enact canvas like figure help pave reopen betray exotic nose fetch wagon senior acid across salon alley";
Expand Down Expand Up @@ -705,7 +703,11 @@ mod tests {
.unwrap();

assert!(!signer.as_json().is_empty());
let result = signer.sign(b"lol", None, "lol");
let sig_ctx = SignatureContext {
global_id: None,
signature_type: SignatureType::Empty,
};
let result = signer.sign(b"lol", "lol", sig_ctx);
assert!(result.is_err());
}

Expand Down
10 changes: 5 additions & 5 deletions src/crypto/ledger_key/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use serde::{Deserialize, Serialize};
use nekoton_utils::*;

use super::{
default_key_name, SharedSecret, SignatureId, Signer as StoreSigner, SignerContext, SignerEntry,
SignerStorage,
default_key_name, SharedSecret, SignatureContext, Signer as StoreSigner, SignerContext,
SignerEntry, SignerStorage,
};
use crate::core::ton_wallet::WalletType;
use crate::external::{LedgerConnection, LedgerSignatureContext};
Expand Down Expand Up @@ -150,22 +150,22 @@ impl StoreSigner for LedgerKeySigner {
&self,
_: SignerContext<'_>,
data: &[u8],
signature_id: Option<SignatureId>,
signature_ctx: SignatureContext,
input: Self::SignInput,
) -> Result<[u8; ed25519_dalek::SIGNATURE_LENGTH]> {
let key = self.get_key(&input.public_key)?;
let signature = match input.context {
None => {
self.connection
.sign(key.account_id, signature_id, data)
.sign(key.account_id, signature_ctx, data)
.await?
}
Some(context) => {
self.connection
.sign_transaction(
key.account_id,
input.wallet.try_into()?,
signature_id,
signature_ctx,
data,
&context,
)
Expand Down
18 changes: 3 additions & 15 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::borrow::Cow;

use anyhow::Result;
use downcast_rs::{impl_downcast, Downcast};
use dyn_clone::DynClone;
Expand All @@ -15,12 +13,14 @@ pub use encrypted_key::*;
pub use ledger_key::*;
pub use mnemonic::*;
pub use password_cache::*;
pub use signature_domain::*;

mod derived_key;
mod encrypted_key;
mod ledger_key;
mod mnemonic;
mod password_cache;
mod signature_domain;

pub type Signature = [u8; ed25519_dalek::SIGNATURE_LENGTH];
pub type PubKey = [u8; ed25519_dalek::PUBLIC_KEY_LENGTH];
Expand Down Expand Up @@ -166,7 +166,7 @@ pub trait Signer: SignerStorage {
&self,
ctx: SignerContext<'_>,
data: &[u8],
signature_id: Option<SignatureId>,
signature_ctx: SignatureContext,
input: Self::SignInput,
) -> Result<Signature>;
}
Expand Down Expand Up @@ -240,18 +240,6 @@ pub fn default_key_name(public_key: &PubKey) -> String {
)
}

pub fn extend_with_signature_id(data: &[u8], signature_id: Option<SignatureId>) -> Cow<'_, [u8]> {
match signature_id {
Some(signature_id) => {
let mut extended_data = Vec::with_capacity(4 + data.len());
extended_data.extend_from_slice(&signature_id.to_be_bytes());
extended_data.extend_from_slice(data);
Cow::Owned(extended_data)
}
None => Cow::Borrowed(data),
}
}

pub mod x25519 {
use curve25519_dalek_ng::scalar::Scalar;
use zeroize::Zeroizing;
Expand Down
Loading
Loading