Compare commits

...

18 Commits

Author SHA1 Message Date
Tommy 60b5870bb7 adding test id's and more pages 2022-03-04 16:26:39 +00:00
Tommy 8a84f9ff80 implement base changes for updating wallet-tests to use typescript 2022-03-04 12:10:06 +00:00
fmtabbara b9ef848523 fix clipboard and screen maximize 2022-03-03 12:18:08 +00:00
Tommy Verrall b7bc713cd4 Merge pull request #1137 from nymtech/feature/allow-mainnet
allow main-net prefix and denom to work
2022-03-02 17:08:28 +00:00
Tommy Verrall b966f962c8 allow main-net prefix and denom to work 2022-03-02 17:07:15 +00:00
Mark Sinclair 698cdc524d Merge pull request #1136 from nymtech/feature/upgrade-blake3
Upgrade blake3 to v1.3.1 and tauri to 1.0.0-rc.3
2022-03-02 15:25:20 +00:00
Jędrzej Stuczyński 448aba0917 Fixed dependencies in mixnet contract tests 2022-03-02 12:51:58 +00:00
fmtabbara b813e1fee0 refactor and bug fix 2022-03-02 11:08:19 +00:00
Jędrzej Stuczyński 23de430f93 Running tests with all features in CI 2022-03-02 10:34:45 +00:00
Jędrzej Stuczyński 9462bc726d Feature-locking parts of common/crypto 2022-03-02 10:34:27 +00:00
fmtabbara 3d2eaeeabb rebuild vesting timeline 2022-03-02 00:21:52 +00:00
fmtabbara a732a676e0 Merge branch 'develop' into feature/vesting-actions 2022-03-01 20:52:09 +00:00
fmtabbara d6a8fcda9c start svg based vesting timeline 2022-03-01 20:51:42 +00:00
fmtabbara 3628cd92c9 start token pool selector 2022-03-01 20:51:25 +00:00
Mark Sinclair 8d26acbc7e Upgrade tauri packages in nym-wallet 2022-03-01 18:50:05 +00:00
Mark Sinclair 07b971fe92 Upgrade tauri version on tauri-client 2022-03-01 18:50:05 +00:00
Jędrzej Stuczyński 2a539dc3cc Upgrade blake3 to v1.3.1 2022-03-01 18:50:05 +00:00
fmtabbara 3fb9737db4 capitalise balance 2022-02-28 19:28:17 +00:00
59 changed files with 5116 additions and 20843 deletions
+1 -1
View File
@@ -39,7 +39,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --all
args: --all --all-features
- name: Check formatting
uses: actions-rs/cargo@v1
Generated
+750 -481
View File
File diff suppressed because it is too large Load Diff
@@ -1,10 +1,10 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crypto::generic_array::typenum::Unsigned;
use log::*;
use nymsphinx::anonymous_replies::{
encryption_key::EncryptionKeyDigest, encryption_key::Unsigned, SurbEncryptionKey,
SurbEncryptionKeySize,
encryption_key::EncryptionKeyDigest, SurbEncryptionKey, SurbEncryptionKeySize,
};
use std::path::Path;
@@ -43,7 +43,7 @@ impl ReplyKeyStorage {
// if this fails it means we have some database corruption and we
// absolutely can't continue
if key_bytes_ref.len() != SurbEncryptionKeySize::to_usize() {
if key_bytes_ref.len() != SurbEncryptionKeySize::USIZE {
error!("REPLY KEY STORAGE DATA CORRUPTION - ENCRYPTION KEY HAS INVALID LENGTH");
panic!("REPLY KEY STORAGE DATA CORRUPTION - ENCRYPTION KEY HAS INVALID LENGTH");
}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -26,7 +26,7 @@
"@rollup/plugin-node-resolve": "^8.0.0",
"@rollup/plugin-replace": "^2.4.0",
"@rollup/plugin-url": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-beta.5",
"@tauri-apps/cli": "^1.0.0-rc.5",
"rollup": "^2.3.4",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
+2 -2
View File
@@ -12,12 +12,12 @@ build = "src/build.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.0.0-beta.2" }
tauri-build = { version = "1.0.0-rc.3" }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0.0-beta.4", features = [] }
tauri = { version = "1.0.0-rc.3", features = [] }
tokio = "1.4"
url = "2.2"
File diff suppressed because it is too large Load Diff
+10 -2
View File
@@ -64,15 +64,23 @@ export default class ValidatorClient implements INymClient {
readonly vestingContract: string;
readonly mainnetDenom = "unym";
readonly mainnetPrefix = "n";
private constructor(
client: SigningClient | QueryClient,
prefix: string,
mixnetContract: string,
vestingContract: string,
vestingContract: string
) {
this.client = client;
this.prefix = prefix;
this.denom = `u${prefix}`;
if (prefix == this.mainnetPrefix) {
this.denom = this.mainnetDenom;
} else {
this.denom = `u${prefix}`;
}
this.mixnetContract = mixnetContract;
this.vestingContract = vestingContract;
+12 -1
View File
@@ -1,8 +1,19 @@
import axios from 'axios';
import { GasPrice } from '@cosmjs/stargate';
const mainnetPrefix = 'n';
const mainnetDenom = 'nym';
export function nymGasPrice(prefix: string): GasPrice {
return GasPrice.fromString(`0.025u${prefix}`); // TODO: ideally this ugly conversion shouldn't be hardcoded here.
if (typeof prefix === 'string') {
if (prefix === mainnetPrefix) {
prefix = mainnetDenom;
}
return GasPrice.fromString(`0.025u${prefix}`); // TODO: ideally this ugly conversion shouldn't be hardcoded here.
}
else {
throw new Error(`${prefix} is not of type string`);
}
}
export const downloadWasm = async (url: string): Promise<Uint8Array> => {
+1 -1
View File
@@ -11,6 +11,6 @@ url = "2.2"
# I guess temporarily until we get serde support in coconut up and running
coconut-interface = { path = "../coconut-interface" }
crypto = { path = "../crypto" }
crypto = { path = "../crypto", features = ["asymmetric"] }
network-defaults = { path = "../network-defaults" }
validator-client = { path = "../client-libs/validator-client" }
+19 -11
View File
@@ -7,21 +7,29 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aes = { version = "0.7.4", features = ["ctr"] }
aes = { version = "0.8.1", optional = true }
bs58 = "0.4.0"
blake3 = { version = "~1.2.0", features = ["traits-preview"] }
digest = "0.9.0"
generic-array = "0.14"
hkdf = "0.11.0"
hmac = "0.11.0"
cipher = "0.3.0"
x25519-dalek = "1.1"
ed25519-dalek = "1.0"
log = "0.4"
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
blake3 = { version = "1.3.1", features = ["traits-preview"], optional = true }
ctr = { version = "0.9.1", optional = true }
digest = { version = "0.10.3", optional = true }
generic-array = { version = "0.14", optional = true }
hkdf = { version = "0.12.3", optional = true }
hmac = { version = "0.12.1", optional = true }
cipher = { version = "0.4.3", optional = true }
x25519-dalek = { version = "1.1", optional = true }
ed25519-dalek = { version = "1.0", optional = true }
rand = { version = "0.7.3", features = ["wasm-bindgen"], optional = true }
subtle-encoding = { version = "0.5", features = ["bech32-preview"]}
# internal
nymsphinx-types = { path = "../nymsphinx/types" }
pemstore = { path = "../../common/pemstore" }
config = { path="../../common/config" }
[dev-dependencies]
rand_chacha = "0.2"
[features]
asymmetric = ["x25519-dalek", "ed25519-dalek"]
hashing = ["blake3", "digest", "hkdf", "hmac", "generic-array"]
symmetric = ["aes", "ctr", "cipher", "generic-array"]
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use pemstore::traits::{PemStorableKey, PemStorableKeyPair};
#[cfg(feature = "rand")]
use rand::{CryptoRng, RngCore};
use std::fmt::{self, Display, Formatter};
@@ -46,6 +47,7 @@ pub struct KeyPair {
}
impl KeyPair {
#[cfg(feature = "rand")]
pub fn new<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let private_key = x25519_dalek::StaticSecret::new(rng);
let public_key = (&private_key).into();
@@ -6,6 +6,7 @@ pub use ed25519_dalek::SignatureError;
pub use ed25519_dalek::{Verifier, PUBLIC_KEY_LENGTH, SECRET_KEY_LENGTH, SIGNATURE_LENGTH};
use nymsphinx_types::{DestinationAddressBytes, DESTINATION_ADDRESS_LENGTH};
use pemstore::traits::{PemStorableKey, PemStorableKeyPair};
#[cfg(feature = "rand")]
use rand::{CryptoRng, RngCore};
use std::fmt::{self, Display, Formatter};
@@ -45,6 +46,7 @@ pub struct KeyPair {
}
impl KeyPair {
#[cfg(feature = "rand")]
pub fn new<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
let ed25519_keypair = ed25519_dalek::Keypair::generate(rng);
+3 -6
View File
@@ -1,14 +1,11 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use digest::{BlockInput, Digest, FixedOutput, Reset, Update};
use generic_array::{ArrayLength, GenericArray};
use digest::{Digest, Output};
pub fn compute_digest<D>(data: &[u8]) -> GenericArray<u8, <D as Digest>::OutputSize>
pub fn compute_digest<D>(data: &[u8]) -> Output<D>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
D: Digest,
{
D::digest(data)
}
+9 -7
View File
@@ -1,9 +1,13 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use digest::{BlockInput, FixedOutput, Reset, Update};
use generic_array::ArrayLength;
use hkdf::Hkdf;
use hkdf::{
hmac::{
digest::{crypto_common::BlockSizeUser, Digest},
SimpleHmac,
},
Hkdf,
};
/// Perform HKDF `extract` then `expand` as a single step.
pub fn extract_then_expand<D>(
@@ -13,14 +17,12 @@ pub fn extract_then_expand<D>(
okm_length: usize,
) -> Result<Vec<u8>, hkdf::InvalidLength>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
D: Digest + BlockSizeUser + Clone,
{
// TODO: this would need to change if we ever needed the generated pseudorandom key, but
// realistically I don't see any reasons why we might need it
let hkdf = Hkdf::<D>::new(salt, ikm);
let hkdf = Hkdf::<D, SimpleHmac<D>>::new(salt, ikm);
let mut okm = vec![0u8; okm_length];
hkdf.expand(info.unwrap_or(&[]), &mut okm)?;
+19 -24
View File
@@ -1,24 +1,23 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use digest::{BlockInput, FixedOutput, Reset, Update};
use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};
use hmac::{crypto_mac, Hmac, Mac, NewMac};
use hmac::{
digest::{crypto_common::BlockSizeUser, CtOutput, Digest, Output},
Mac, SimpleHmac,
};
pub use hmac;
// Type alias for ease of use so that it would not require explicit import of crypto_mac or Hmac
pub type HmacOutput<D> = crypto_mac::Output<Hmac<D>>;
// TODO: We should probably change it to use some sealed trait to allow for both `Hmac` and `SimpleHmac`
pub type HmacOutput<D> = CtOutput<SimpleHmac<D>>;
/// Compute keyed hmac
pub fn compute_keyed_hmac<D>(key: &[u8], data: &[u8]) -> HmacOutput<D>
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
D: Digest + BlockSizeUser,
{
let mut hmac =
Hmac::<D>::new_from_slice(key).expect("HMAC should be able to take key of any size!");
let mut hmac = SimpleHmac::<D>::new_from_slice(key)
.expect("HMAC was instantiated with a key of an invalid size!");
hmac.update(data);
hmac.finalize()
}
@@ -26,32 +25,28 @@ where
/// Compute keyed hmac and performs constant time equality check with the provided tag value.
pub fn recompute_keyed_hmac_and_verify_tag<D>(key: &[u8], data: &[u8], tag: &[u8]) -> bool
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
D: Digest + BlockSizeUser,
{
let mut hmac =
Hmac::<D>::new_from_slice(key).expect("HMAC should be able to take key of any size!");
let mut hmac = SimpleHmac::<D>::new_from_slice(key)
.expect("HMAC was instantiated with a key of an invalid size!");
hmac.update(data);
let tag_arr = Output::<D>::from_slice(tag);
// note, under the hood ct_eq is called
hmac.verify(tag).is_ok()
hmac.verify(tag_arr).is_ok()
}
/// Verifies tag of an hmac output.
pub fn verify_tag<D>(tag: &[u8], out: HmacOutput<D>) -> bool
where
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
D: Digest + BlockSizeUser,
{
if tag.len() != D::OutputSize::to_usize() {
if tag.len() != <D as Digest>::output_size() {
return false;
}
let tag_bytes = GenericArray::clone_from_slice(tag);
let tag_out = HmacOutput::new(tag_bytes);
// note, under the hood ct_eq is called
out == tag_out
let tag_arr = Output::<D>::from_slice(tag);
out == tag_arr.into()
}
#[cfg(test)]
+13 -1
View File
@@ -1,21 +1,33 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
#[cfg(feature = "asymmetric")]
pub mod asymmetric;
pub mod bech32_address_validation;
#[cfg(feature = "hashing")]
pub mod crypto_hash;
#[cfg(feature = "hashing")]
pub mod hkdf;
#[cfg(feature = "hashing")]
pub mod hmac;
#[cfg(all(feature = "asymmetric", feature = "hashing", feature = "symmetric"))]
pub mod shared_key;
#[cfg(feature = "symmetric")]
pub mod symmetric;
pub use digest::Digest;
#[cfg(feature = "hashing")]
pub use digest::{Digest, OutputSizeUser};
#[cfg(any(feature = "hashing", feature = "symmetric"))]
pub use generic_array;
// with the below my idea was to try to introduce having a single place of importing all hashing, encryption,
// etc. algorithms and import them elsewhere as needed via common/crypto
#[cfg(feature = "symmetric")]
pub use aes;
#[cfg(feature = "hashing")]
pub use blake3;
#[cfg(feature = "symmetric")]
pub use ctr;
// TODO: this function uses all three modules: asymmetric crypto, symmetric crypto and derives key...,
// so I don't know where to put it...
+15 -17
View File
@@ -3,22 +3,22 @@
use crate::asymmetric::encryption;
use crate::hkdf;
use cipher::{CipherKey, NewCipher, StreamCipher};
use digest::{BlockInput, FixedOutput, Reset, Update};
use generic_array::{typenum::Unsigned, ArrayLength};
use cipher::{Key, KeyIvInit, StreamCipher};
use digest::crypto_common::BlockSizeUser;
use digest::Digest;
#[cfg(feature = "rand")]
use rand::{CryptoRng, RngCore};
/// Generate an ephemeral encryption keypair and perform diffie-hellman to establish
/// shared key with the remote.
#[cfg(feature = "rand")]
pub fn new_ephemeral_shared_key<C, D, R>(
rng: &mut R,
remote_key: &encryption::PublicKey,
) -> (encryption::KeyPair, CipherKey<C>)
) -> (encryption::KeyPair, Key<C>)
where
C: StreamCipher + NewCipher,
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
C: StreamCipher + KeyIvInit,
D: Digest + BlockSizeUser + Clone,
R: RngCore + CryptoRng,
{
let ephemeral_keypair = encryption::KeyPair::new(rng);
@@ -27,11 +27,11 @@ where
let dh_result = ephemeral_keypair.private_key().diffie_hellman(remote_key);
// there is no reason for this to fail as our okm is expected to be only C::KeySize bytes
let okm = hkdf::extract_then_expand::<D>(None, &dh_result, None, C::KeySize::to_usize())
let okm = hkdf::extract_then_expand::<D>(None, &dh_result, None, C::key_size())
.expect("somehow too long okm was provided");
let derived_shared_key =
CipherKey::<C>::from_exact_iter(okm).expect("okm was expanded to incorrect length!");
Key::<C>::from_exact_iter(okm).expect("okm was expanded to incorrect length!");
(ephemeral_keypair, derived_shared_key)
}
@@ -40,18 +40,16 @@ where
pub fn recompute_shared_key<C, D>(
remote_key: &encryption::PublicKey,
local_key: &encryption::PrivateKey,
) -> CipherKey<C>
) -> Key<C>
where
C: StreamCipher + NewCipher,
D: Update + BlockInput + FixedOutput + Reset + Default + Clone,
D::BlockSize: ArrayLength<u8>,
D::OutputSize: ArrayLength<u8>,
C: StreamCipher + KeyIvInit,
D: Digest + BlockSizeUser + Clone,
{
let dh_result = local_key.diffie_hellman(remote_key);
// there is no reason for this to fail as our okm is expected to be only C::KeySize bytes
let okm = hkdf::extract_then_expand::<D>(None, &dh_result, None, C::KeySize::to_usize())
let okm = hkdf::extract_then_expand::<D>(None, &dh_result, None, C::key_size())
.expect("somehow too long okm was provided");
CipherKey::<C>::from_exact_iter(okm).expect("okm was expanded to incorrect length!")
Key::<C>::from_exact_iter(okm).expect("okm was expanded to incorrect length!")
}
+27 -22
View File
@@ -1,12 +1,13 @@
// Copyright 2020 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use cipher::{Nonce, StreamCipher};
use generic_array::{typenum::Unsigned, GenericArray};
use cipher::{Iv, StreamCipher};
pub use cipher::{IvSizeUser, KeyIvInit, KeySizeUser};
#[cfg(feature = "rand")]
use rand::{CryptoRng, RngCore};
// re-export this for ease of use
pub use cipher::{CipherKey, NewCipher};
pub use cipher::Key as CipherKey;
// SECURITY:
// TODO: note that this is not the most secure approach here
@@ -19,49 +20,51 @@ pub use cipher::{CipherKey, NewCipher};
// I think 'IV' looks better than 'Iv', feel free to change that.
#[allow(clippy::upper_case_acronyms)]
pub type IV<C> = Nonce<C>;
pub type IV<C> = Iv<C>;
#[cfg(feature = "rand")]
pub fn generate_key<C, R>(rng: &mut R) -> CipherKey<C>
where
C: NewCipher,
C: KeyIvInit,
R: RngCore + CryptoRng,
{
let mut key = GenericArray::default();
let mut key = CipherKey::<C>::default();
rng.fill_bytes(&mut key);
key
}
#[cfg(feature = "rand")]
pub fn random_iv<C, R>(rng: &mut R) -> IV<C>
where
C: NewCipher,
C: KeyIvInit,
R: RngCore + CryptoRng,
{
let mut iv = GenericArray::default();
let mut iv = IV::<C>::default();
rng.fill_bytes(&mut iv);
iv
}
pub fn zero_iv<C>() -> IV<C>
where
C: NewCipher,
C: KeyIvInit,
{
GenericArray::default()
Iv::<C>::default()
}
pub fn iv_from_slice<C>(b: &[u8]) -> &IV<C>
where
C: NewCipher,
C: KeyIvInit,
{
if b.len() != C::NonceSize::to_usize() {
if b.len() != C::iv_size() {
// `from_slice` would have caused a panic about this issue anyway.
// Now we at least have slightly more information
panic!(
"Tried to convert {} bytes to IV. Expected {}",
b.len(),
C::NonceSize::to_usize()
C::iv_size()
)
}
GenericArray::from_slice(b)
IV::<C>::from_slice(b)
}
// TODO: there's really no way to use more parts of the keystream if it was required at some point.
@@ -70,7 +73,7 @@ where
#[inline]
pub fn encrypt<C>(key: &CipherKey<C>, iv: &IV<C>, data: &[u8]) -> Vec<u8>
where
C: StreamCipher + NewCipher,
C: StreamCipher + KeyIvInit,
{
let mut ciphertext = data.to_vec();
encrypt_in_place::<C>(key, iv, &mut ciphertext);
@@ -80,7 +83,7 @@ where
#[inline]
pub fn encrypt_in_place<C>(key: &CipherKey<C>, iv: &IV<C>, data: &mut [u8])
where
C: StreamCipher + NewCipher,
C: StreamCipher + KeyIvInit,
{
let mut cipher = C::new(key, iv);
cipher.apply_keystream(data)
@@ -89,7 +92,7 @@ where
#[inline]
pub fn decrypt<C>(key: &CipherKey<C>, iv: &IV<C>, ciphertext: &[u8]) -> Vec<u8>
where
C: StreamCipher + NewCipher,
C: StreamCipher + KeyIvInit,
{
let mut data = ciphertext.to_vec();
decrypt_in_place::<C>(key, iv, &mut data);
@@ -99,7 +102,7 @@ where
#[inline]
pub fn decrypt_in_place<C>(key: &CipherKey<C>, iv: &IV<C>, data: &mut [u8])
where
C: StreamCipher + NewCipher,
C: StreamCipher + KeyIvInit,
{
let mut cipher = C::new(key, iv);
cipher.apply_keystream(data)
@@ -108,12 +111,12 @@ where
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::OsRng;
use rand_chacha::rand_core::SeedableRng;
#[cfg(test)]
mod aes_ctr128 {
use super::*;
use aes::Aes128Ctr;
type Aes128Ctr = ctr::Ctr64LE<aes::Aes128>;
#[test]
fn zero_iv_is_actually_zero() {
@@ -125,7 +128,8 @@ mod tests {
#[test]
fn decryption_is_reciprocal_to_encryption() {
let mut rng = OsRng;
let dummy_seed = [1u8; 32];
let mut rng = rand_chacha::ChaCha20Rng::from_seed(dummy_seed);
let arr_input = [42; 200];
let vec_input = vec![123, 200];
@@ -148,7 +152,8 @@ mod tests {
#[test]
fn in_place_variants_work_same_way() {
let mut rng = OsRng;
let dummy_seed = [1u8; 32];
let mut rng = rand_chacha::ChaCha20Rng::from_seed(dummy_seed);
let mut data = [42; 200];
let original_data = data;
+2 -2
View File
@@ -7,9 +7,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = {version = "0.7.3", features = ["wasm-bindgen"]}
rand = { version = "0.7.3", features = ["wasm-bindgen"] }
crypto = { path = "../../crypto" }
crypto = { path = "../../crypto", features = ["symmetric", "rand"] }
nymsphinx-addressing = { path = "../addressing" }
nymsphinx-params = { path = "../params" }
nymsphinx-types = { path = "../types" }
@@ -2,8 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::AckKey;
use crypto::generic_array::typenum::Unsigned;
use crypto::symmetric::stream_cipher::{self, encrypt, iv_from_slice, random_iv, NewCipher};
use crypto::symmetric::stream_cipher::{self, encrypt, iv_from_slice, random_iv, IvSizeUser};
use nymsphinx_params::{
packet_sizes::PacketSize, AckEncryptionAlgorithm, SerializedFragmentIdentifier, FRAG_ID_LEN,
};
@@ -33,7 +32,7 @@ pub fn recover_identifier(
return None;
}
let iv_size = <AckEncryptionAlgorithm as NewCipher>::NonceSize::to_usize();
let iv_size = AckEncryptionAlgorithm::iv_size();
let iv = iv_from_slice::<AckEncryptionAlgorithm>(&iv_id_ciphertext[..iv_size]);
let id = stream_cipher::decrypt::<AckEncryptionAlgorithm>(
+6 -4
View File
@@ -1,8 +1,7 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crypto::generic_array::{typenum::Unsigned, GenericArray};
use crypto::symmetric::stream_cipher::{generate_key, CipherKey, NewCipher};
use crypto::symmetric::stream_cipher::{generate_key, CipherKey, KeySizeUser};
use nymsphinx_params::AckEncryptionAlgorithm;
use pemstore::traits::PemStorableKey;
use rand::{CryptoRng, RngCore};
@@ -33,11 +32,14 @@ impl AckKey {
}
pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, AckKeyConversionError> {
if bytes.len() != <AckEncryptionAlgorithm as NewCipher>::KeySize::to_usize() {
if bytes.len() != AckEncryptionAlgorithm::key_size() {
return Err(AckKeyConversionError::BytesOfInvalidLengthError);
}
Ok(AckKey(GenericArray::clone_from_slice(bytes)))
// Ok(AckKey(GenericArray::clone_from_slice(bytes)))
Ok(AckKey(
CipherKey::<AckEncryptionAlgorithm>::clone_from_slice(bytes),
))
}
pub fn to_bytes(&self) -> Vec<u8> {
+1 -1
View File
@@ -7,7 +7,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
crypto = { path = "../../crypto" } # all addresses are expressed in terms on their crypto keys
crypto = { path = "../../crypto", features = ["asymmetric"] } # all addresses are expressed in terms on their crypto keys
nymsphinx-types = { path = "../types" } # we need to be able to refer to some types defined inside sphinx crate
serde = "1.0" # implementing serialization/deserialization for some types, like `Recipient`
@@ -1,21 +1,20 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub use crypto::generic_array::typenum::Unsigned;
use crypto::{
crypto_hash,
generic_array::GenericArray,
symmetric::stream_cipher::{generate_key, CipherKey, NewCipher},
Digest,
generic_array::{typenum::Unsigned, GenericArray},
symmetric::stream_cipher::{generate_key, CipherKey, KeySizeUser},
OutputSizeUser,
};
use nymsphinx_params::{ReplySurbEncryptionAlgorithm, ReplySurbKeyDigestAlgorithm};
use rand::{CryptoRng, RngCore};
use std::fmt::{self, Display, Formatter};
pub type EncryptionKeyDigest =
GenericArray<u8, <ReplySurbKeyDigestAlgorithm as Digest>::OutputSize>;
GenericArray<u8, <ReplySurbKeyDigestAlgorithm as OutputSizeUser>::OutputSize>;
pub type SurbEncryptionKeySize = <ReplySurbEncryptionAlgorithm as NewCipher>::KeySize;
pub type SurbEncryptionKeySize = <ReplySurbEncryptionAlgorithm as KeySizeUser>::KeySize;
#[derive(Clone, Debug)]
pub struct SurbEncryptionKey(CipherKey<ReplySurbEncryptionAlgorithm>);
@@ -45,7 +44,7 @@ impl SurbEncryptionKey {
}
pub fn try_from_bytes(bytes: &[u8]) -> Result<Self, SurbEncryptionKeyError> {
if bytes.len() != SurbEncryptionKeySize::to_usize() {
if bytes.len() != SurbEncryptionKeySize::USIZE {
return Err(SurbEncryptionKeyError::BytesOfInvalidLengthError);
}
@@ -1,5 +1,6 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
pub mod encryption_key;
pub mod reply_surb;
@@ -1,10 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::encryption_key::{
SurbEncryptionKey, SurbEncryptionKeyError, SurbEncryptionKeySize, Unsigned,
};
use crypto::Digest;
use crate::encryption_key::{SurbEncryptionKey, SurbEncryptionKeyError, SurbEncryptionKeySize};
use crypto::{generic_array::typenum::Unsigned, Digest};
use nymsphinx_addressing::clients::Recipient;
use nymsphinx_addressing::nodes::{NymNodeRoutingAddress, MAX_NODE_ADDRESS_UNPADDED_LEN};
use nymsphinx_params::packet_sizes::PacketSize;
@@ -65,7 +63,7 @@ pub struct ReplySurb {
// Serialize + Deserialize is not really used anymore (it was for a CBOR experiment)
// however, if we decided we needed it again, it's already here
impl Serialize for ReplySurb {
fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
@@ -139,7 +137,7 @@ impl ReplySurb {
// the SURB itself consists of SURB_header, first hop address and set of payload keys
// (note extra 1 for the gateway)
SurbEncryptionKeySize::to_usize()
SurbEncryptionKeySize::USIZE
+ HEADER_SIZE
+ NODE_ADDRESS_LENGTH
+ (1 + mix_hops as usize) * PAYLOAD_KEY_SIZE
@@ -160,9 +158,9 @@ impl ReplySurb {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, ReplySurbError> {
let encryption_key =
SurbEncryptionKey::try_from_bytes(&bytes[..SurbEncryptionKeySize::to_usize()])?;
SurbEncryptionKey::try_from_bytes(&bytes[..SurbEncryptionKeySize::USIZE])?;
let surb = match SURB::from_bytes(&bytes[SurbEncryptionKeySize::to_usize()..]) {
let surb = match SURB::from_bytes(&bytes[SurbEncryptionKeySize::USIZE..]) {
Err(err) => return Err(ReplySurbError::RecoveryError(err)),
Ok(surb) => surb,
};
+1 -1
View File
@@ -7,5 +7,5 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
crypto = { path = "../../crypto" }
crypto = { path = "../../crypto", features = ["hashing", "symmetric"] }
nymsphinx-types = { path = "../types" }
+4 -1
View File
@@ -1,8 +1,11 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crypto::aes::Aes128Ctr;
use crypto::aes::Aes128;
use crypto::blake3;
use crypto::ctr;
type Aes128Ctr = ctr::Ctr64LE<Aes128>;
// Re-export for ease of use
pub use packet_modes::PacketMode;
+4 -39
View File
@@ -27,12 +27,6 @@ version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544"
[[package]]
name = "arrayvec"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"
[[package]]
name = "autocfg"
version = "1.0.1"
@@ -90,21 +84,6 @@ dependencies = [
"opaque-debug 0.2.3",
]
[[package]]
name = "blake3"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "526c210b4520e416420759af363083471656e819a75e831b8d2c9d5a584f2413"
dependencies = [
"arrayref",
"arrayvec",
"cc",
"cfg-if",
"constant_time_eq",
"crypto-mac 0.11.1",
"digest 0.9.0",
]
[[package]]
name = "block-buffer"
version = "0.7.3"
@@ -230,12 +209,6 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d6f2aa4d0537bcc1c74df8755072bd31c1ef1a3a1b85a68e8404a8c353b7b8b"
[[package]]
name = "constant_time_eq"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
[[package]]
name = "contracts-common"
version = "0.1.0"
@@ -320,17 +293,9 @@ checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
name = "crypto"
version = "0.1.0"
dependencies = [
"aes",
"blake3",
"bs58",
"cipher",
"config",
"digest 0.9.0",
"ed25519-dalek",
"generic-array 0.14.5",
"hkdf",
"hmac",
"log",
"nymsphinx-types",
"pemstore",
"rand",
@@ -450,9 +415,9 @@ dependencies = [
[[package]]
name = "ed25519"
version = "1.3.0"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74e1069e39f1454367eb2de793ed062fac4c35c2934b76a81d90dd9abcd28816"
checksum = "eed12bbf7b5312f8da1c2722bc06d8c6b12c2d86a7fb35a194c7f3e6fc2bbe39"
dependencies = [
"signature",
]
@@ -1676,9 +1641,9 @@ dependencies = [
[[package]]
name = "zeroize_derive"
version = "1.2.2"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65f1a51723ec88c66d5d1fe80c841f17f63587d6691901d66be9bec6c3b51f73"
checksum = "3f8f187641dad4f680d25c4bfc4225b418165984179f26ca76ec4fb6441d3a17"
dependencies = [
"proc-macro2",
"quote",
+1 -1
View File
@@ -35,7 +35,7 @@ cosmwasm-schema = "1.0.0-beta3"
fixed = "1.1"
rand_chacha = "0.2"
rand = "0.7"
crypto = { path = "../../common/crypto" }
crypto = { path = "../../common/crypto", features = ["asymmetric", "rand"] }
[build-dependencies]
vergen = { version = "5", default-features = false, features = ["build", "git", "rustc"] }
+2 -2
View File
@@ -2,12 +2,12 @@
// SPDX-License-Identifier: Apache-2.0
use crypto::generic_array::{typenum::Unsigned, GenericArray};
use crypto::symmetric::stream_cipher::{random_iv, NewCipher, IV as CryptoIV};
use crypto::symmetric::stream_cipher::{random_iv, IvSizeUser, IV as CryptoIV};
use nymsphinx::params::GatewayEncryptionAlgorithm;
use rand::{CryptoRng, RngCore};
use thiserror::Error;
type NonceSize = <GatewayEncryptionAlgorithm as NewCipher>::NonceSize;
type NonceSize = <GatewayEncryptionAlgorithm as IvSizeUser>::IvSize;
// I think 'IV' looks better than 'Iv', feel free to change that.
#[allow(clippy::upper_case_acronyms)]
+3 -2
View File
@@ -2,7 +2,8 @@
// SPDX-License-Identifier: Apache-2.0
pub use crypto::generic_array;
use crypto::hmac::{hmac::Mac, HmacOutput};
use crypto::hmac::HmacOutput;
use crypto::OutputSizeUser;
use nymsphinx::params::GatewayIntegrityHmacAlgorithm;
pub use types::*;
@@ -15,4 +16,4 @@ pub type GatewayMac = HmacOutput<GatewayIntegrityHmacAlgorithm>;
// TODO: could using `Mac` trait here for OutputSize backfire?
// Should hmac itself be exposed, imported and used instead?
pub type GatewayMacSize = <GatewayIntegrityHmacAlgorithm as Mac>::OutputSize;
pub type GatewayMacSize = <GatewayIntegrityHmacAlgorithm as OutputSizeUser>::OutputSize;
@@ -7,7 +7,7 @@ use crypto::generic_array::{
GenericArray,
};
use crypto::hmac::{compute_keyed_hmac, recompute_keyed_hmac_and_verify_tag};
use crypto::symmetric::stream_cipher::{self, CipherKey, NewCipher, IV};
use crypto::symmetric::stream_cipher::{self, CipherKey, KeySizeUser, IV};
use nymsphinx::params::{GatewayEncryptionAlgorithm, GatewayIntegrityHmacAlgorithm};
use pemstore::traits::PemStorableKey;
use std::fmt::{self, Display, Formatter};
@@ -17,7 +17,7 @@ pub type SharedKeySize = Sum<EncryptionKeySize, MacKeySize>;
// we're using 16 byte long key in sphinx, so let's use the same one here
type MacKeySize = U16;
type EncryptionKeySize = <GatewayEncryptionAlgorithm as NewCipher>::KeySize;
type EncryptionKeySize = <GatewayEncryptionAlgorithm as KeySizeUser>::KeySize;
/// Shared key used when computing MAC for messages exchanged between client and its gateway.
pub type MacKey = GenericArray<u8, MacKeySize>;
+590 -440
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -22,6 +22,7 @@
"@types/react-dom": "^17.0.9",
"bs58": "^4.0.1",
"clsx": "^1.1.1",
"date-fns": "^2.28.0",
"notistack": "^2.0.3",
"qrcode.react": "^1.0.1",
"react": "^17.0.2",
@@ -38,8 +39,8 @@
"@babel/preset-env": "^7.15.0",
"@babel/preset-react": "^7.14.5",
"@svgr/webpack": "^6.1.1",
"@tauri-apps/api": "^1.0.0-beta.6",
"@tauri-apps/cli": "^1.0.0-beta.9",
"@tauri-apps/api": "^1.0.0-rc.1",
"@tauri-apps/cli": "^1.0.0-rc.5",
"@types/bs58": "^4.0.1",
"@types/qrcode.react": "^1.0.2",
"@types/react-router-dom": "^5.1.8",
+2 -2
View File
@@ -13,13 +13,13 @@ rust-version = "1.56"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
tauri-build = { version = "1.0.0-beta.4" }
tauri-build = { version = "1.0.0-rc.3", features = [] }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] }
strum = { version = "0.23", features = ["derive"] }
tauri = { version = "1.0.0-beta.8", features = ["shell-open"] }
tauri = { version = "1.0.0-rc.3", features = ["clipboard-all", "shell-open", "window-maximize"] }
tokio = { version = "1.10", features = ["sync"] }
dirs = "4.0"
bip39 = "1.0"
+6
View File
@@ -49,6 +49,12 @@
"active": false
},
"allowlist": {
"window": {
"maximize": true
},
"clipboard": {
"all": true
},
"shell": {
"open": true
}
@@ -0,0 +1,18 @@
import { ListItem, ListItemText, Select } from '@mui/material'
import React, { useState } from 'react'
type TPool = 'balance' | 'locked'
export const TokenPoolSelector: React.FC<{ onSelect: (pool: TPool) => void }> = ({ onSelect }) => {
const [value, setValue] = useState<TPool>()
return (
<>
<Select label="Token Pool" value={value}>
<ListItem>
<ListItemText primary="Balance" secondary="123 nymt" />
</ListItem>
</Select>
</>
)
}
+23 -9
View File
@@ -8,7 +8,9 @@ import {
getSpendableCoins,
getOriginalVesting,
getCurrentVestingPeriod,
getVestingAccountInfo,
} from '../requests'
import { VestingAccountInfo } from 'src/types/rust/vestingaccountinfo'
type TTokenAllocation = {
[key in 'vesting' | 'vested' | 'locked' | 'spendable']: Coin['amount']
@@ -20,6 +22,7 @@ export type TUseuserBalance = {
tokenAllocation?: TTokenAllocation
originalVesting?: OriginalVestingResponse
currentVestingPeriod?: Period
vestingAccountInfo?: VestingAccountInfo
isLoading: boolean
fetchBalance: () => void
clearBalance: () => void
@@ -33,6 +36,7 @@ export const useGetBalance = (address?: string): TUseuserBalance => {
const [tokenAllocation, setTokenAllocation] = useState<TTokenAllocation>()
const [originalVesting, setOriginalVesting] = useState<OriginalVestingResponse>()
const [currentVestingPeriod, setCurrentVestingPeriod] = useState<Period>()
const [vestingAccountInfo, setVestingAccountInfo] = useState<VestingAccountInfo>()
const [isLoading, setIsLoading] = useState(false)
const fetchBalance = useCallback(async () => {
@@ -54,15 +58,23 @@ export const useGetBalance = (address?: string): TUseuserBalance => {
setIsLoading(true)
if (address) {
try {
const [originalVestingValue, vestingCoins, vestedCoins, lockedCoins, spendableCoins, currentVestingPeriod] =
await Promise.all([
getOriginalVesting(address),
getVestingCoins(address),
getVestedCoins(address),
getLockedCoins(address),
getSpendableCoins(address),
getCurrentVestingPeriod(address),
])
const [
originalVestingValue,
vestingCoins,
vestedCoins,
lockedCoins,
spendableCoins,
currentVestingPeriod,
vestingAccountInfo,
] = await Promise.all([
getOriginalVesting(address),
getVestingCoins(address),
getVestedCoins(address),
getLockedCoins(address),
getSpendableCoins(address),
getCurrentVestingPeriod(address),
getVestingAccountInfo(address),
])
setOriginalVesting(originalVestingValue)
setCurrentVestingPeriod(currentVestingPeriod)
setTokenAllocation({
@@ -71,6 +83,7 @@ export const useGetBalance = (address?: string): TUseuserBalance => {
locked: lockedCoins.amount,
spendable: spendableCoins.amount,
})
setVestingAccountInfo(vestingAccountInfo)
} catch (e) {
clearTokenAllocation()
clearOriginalVesting()
@@ -110,6 +123,7 @@ export const useGetBalance = (address?: string): TUseuserBalance => {
tokenAllocation,
originalVesting,
currentVestingPeriod,
vestingAccountInfo,
fetchBalance,
clearBalance,
clearAll,
+1 -1
View File
@@ -23,7 +23,7 @@ export const BalanceCard = () => {
{!userBalance.error && (
<Typography
data-testid="refresh-success"
sx={{ color: 'nym.background.dark' }}
sx={{ color: 'nym.background.dark', textTransform: 'uppercase' }}
variant="h5"
fontWeight="700"
>
@@ -0,0 +1,54 @@
import React, { useContext } from 'react'
import { Box, Tooltip, Typography } from '@mui/material'
import { format } from 'date-fns'
import { ClientContext } from '../../../context/main'
const calculateMarkerPosition = (arrLength: number, index: number) => (1 / arrLength) * 100 * index
export const VestingTimeline: React.FC<{ percentageComplete: number }> = ({ percentageComplete }) => {
const {
userBalance: { currentVestingPeriod, vestingAccountInfo },
} = useContext(ClientContext)
const nextPeriod =
typeof currentVestingPeriod === 'object' && !!vestingAccountInfo?.periods
? Number(vestingAccountInfo?.periods[currentVestingPeriod.In + 1]?.start_time)
: undefined
return (
<Box display="flex" flexDirection="column" gap={1} position="relative" width="100%">
<svg width="100%" height="12">
<rect y="2" width="100%" height="6" rx="0" fill="#E6E6E6" />
<rect y="2" width={`${percentageComplete}%`} height="6" rx="0" fill="#121726" />
{vestingAccountInfo?.periods.map((period, i, arr) => (
<Marker
position={`${calculateMarkerPosition(arr.length, i)}%`}
color={+percentageComplete.toFixed(2) >= calculateMarkerPosition(arr.length, i) ? '#121726' : '#B9B9B9'}
tooltipText={format(new Date(Number(period.start_time) * 1000), 'HH:mm do MMM yyyy')}
key={i}
/>
))}
<Marker
position="calc(100% - 4px)"
color={percentageComplete === 100 ? '#121726' : '#B9B9B9'}
tooltipText="End of vesting schedule"
/>
</svg>
{nextPeriod && (
<Typography variant="caption" sx={{ color: 'grey.500', position: 'absolute', top: 15, left: 0 }}>
Next vesting period: {format(new Date(nextPeriod * 1000), 'HH:mm do MMM yyyy')}
</Typography>
)}
</Box>
)
}
const Marker: React.FC<{ tooltipText: string; color: string; position: string }> = ({
tooltipText,
color,
position,
}) => (
<Tooltip title={tooltipText}>
<rect x={position} width="4" height="12" rx="1" fill={color} style={{ cursor: 'pointer' }} />
</Tooltip>
)
+8 -11
View File
@@ -20,6 +20,7 @@ import { NymCard, InfoTooltip, Title, Fee } from '../../components'
import { ClientContext } from '../../context/main'
import { withdrawVestedCoins } from '../../requests'
import { Period } from '../../types'
import { VestingTimeline } from './components/vesting-timeline'
export const VestingCard = () => {
const { userBalance } = useContext(ClientContext)
@@ -55,7 +56,7 @@ export const VestingCard = () => {
<VestingSchedule />
<TokenTransfer />
<Box display="flex" justifyContent="space-between" alignItems="center">
<Fee feeType="Send" />
{userBalance.tokenAllocation?.spendable !== '0' ? <Fee feeType="Send" /> : <div />}
<Button
size="large"
variant="contained"
@@ -79,7 +80,7 @@ export const VestingCard = () => {
}
}}
endIcon={isLoading && <CircularProgress size={16} color="inherit" />}
disabled={isLoading}
disabled={isLoading || userBalance.tokenAllocation?.spendable === '0'}
disableElevation
>
Transfer
@@ -103,8 +104,9 @@ const VestingSchedule = () => {
const calculatePercentage = () => {
const { tokenAllocation, originalVesting } = userBalance
if (tokenAllocation?.vesting && tokenAllocation.vested && tokenAllocation.vested !== '0' && originalVesting) {
const percentage = Math.round((+tokenAllocation.vested / +originalVesting?.amount.amount) * 100)
setVestedPercentage(percentage)
const percentage = (+tokenAllocation.vested / +originalVesting?.amount.amount) * 100
const rounded = percentage.toFixed(2)
setVestedPercentage(+rounded)
} else {
setVestedPercentage(0)
}
@@ -135,13 +137,8 @@ const VestingSchedule = () => {
</TableCell>
<TableCell sx={{ borderBottom: 'none' }}>
<Box display="flex" alignItems="center" gap={1}>
<Typography variant="caption">{`${vestedPercentage}%`}</Typography>
<LinearProgress
sx={{ flexBasis: '99%' }}
variant="determinate"
value={vestedPercentage}
color="inherit"
/>
<Typography variant="body2">{`${vestedPercentage}%`}</Typography>
<VestingTimeline percentageComplete={vestedPercentage} />
</Box>
</TableCell>
<TableCell sx={{ borderBottom: 'none' }} align="right">
@@ -15,14 +15,14 @@ export const ExistingAccount: React.FC<{ page: 'existing account'; onPrev: () =>
return (
<Stack spacing={2} sx={{ width: 400 }} alignItems="center">
<Subtitle subtitle="Enter your mnemonic from existing wallet" />
<TextField value={mnemonic} onChange={(e) => setMnemonic(e.target.value)} multiline rows={5} fullWidth />
<TextField value={mnemonic} onChange={(e) => setMnemonic(e.target.value)} data-testid="enterMnemonic" multiline rows={5} fullWidth />
{error && (
<Alert severity="error" variant="outlined" data-testid="error" sx={{ color: 'error.light', width: '100%' }}>
{error}
</Alert>
)}
<Button variant="contained" size="large" fullWidth onClick={handleSignIn}>
<Button variant="contained" data-testid="signIn" size="large" fullWidth onClick={handleSignIn}>
Sign in
</Button>
<Button
@@ -32,6 +32,7 @@ export const ExistingAccount: React.FC<{ page: 'existing account'; onPrev: () =>
onClick={onPrev}
fullWidth
sx={{ color: 'common.white', border: '1px solid white', '&:hover': { border: '1px solid white' } }}
data-testid="backButton"
>
Back
</Button>
@@ -19,6 +19,7 @@ export const WelcomeContent: React.FC<{
disableElevation
size="large"
onClick={onCreateAccountComplete}
data-testid="createAccount"
>
Create Account
</Button>
@@ -33,6 +34,7 @@ export const WelcomeContent: React.FC<{
}}
onClick={onUseExisting}
disableRipple
data-testid="signIn"
>
Sign in
</Button>
+20 -4
View File
@@ -1,6 +1,7 @@
import { invoke } from '@tauri-apps/api'
import { VestingAccountInfo } from 'src/types/rust/vestingaccountinfo'
import { majorToMinor, minorToMajor } from '.'
import { Coin, OriginalVestingResponse, Period } from '../types'
import { Coin, DelegationResult, OriginalVestingResponse, Period } from '../types'
export const getLockedCoins = async (address: string): Promise<Coin> => {
const res: Coin = await invoke('locked_coins', { address })
@@ -23,8 +24,8 @@ export const getVestedCoins = async (vestingAccountAddress: string): Promise<Coi
export const getOriginalVesting = async (vestingAccountAddress: string): Promise<OriginalVestingResponse> => {
const res: OriginalVestingResponse = await invoke('original_vesting', { vestingAccountAddress })
const majorValue = await minorToMajor(res.amount.amount)
return {...res, amount: majorValue}
const majorValue = await minorToMajor(res.amount.amount)
return { ...res, amount: majorValue }
}
export const withdrawVestedCoins = async (amount: string) => {
@@ -32,4 +33,19 @@ export const withdrawVestedCoins = async (amount: string) => {
await invoke('withdraw_vested_coins', { amount: { amount: minor.amount, denom: 'Minor' } })
}
export const getCurrentVestingPeriod = async (address: string): Promise<Period> => await invoke('get_current_vesting_period', {address})
export const getCurrentVestingPeriod = async (address: string): Promise<Period> =>
await invoke('get_current_vesting_period', { address })
export const vestingDelegateToMixnode = async ({
identity,
amount,
}: {
identity: string
amount: Coin
}): Promise<DelegationResult> => await invoke('vesting_delegate_to_mixnode', { identity, amount })
export const vestingUnelegateFromMixnode = async (identity: string): Promise<DelegationResult> =>
await invoke('vesting_delegate_to_mixnode', { identity })
export const getVestingAccountInfo = async (address: string): Promise<VestingAccountInfo> =>
await invoke('get_account_info', { address })
+2
View File
@@ -18,3 +18,5 @@ export * from './mixnodestatusresponse'
export * from './inclusionprobabilityresponse'
export * from './network'
export * from './originalvestingresponse'
export * from './vestingperiod'
export * from './vestingaccountinfo'
+5
View File
@@ -0,0 +1,5 @@
reports
allure-results
node_modules
.vscode
.idea
@@ -0,0 +1,2 @@
build
coverage
@@ -0,0 +1,7 @@
{
"trailingComma": "all",
"singleQuote": true,
"printWidth": 120,
"tabWidth": 2,
"semi": false
}
+23
View File
@@ -0,0 +1,23 @@
{
"name": "wallet-ui-test",
"version": "1.0.0",
"description": "wallet ui tests for the nym wallet",
"scripts": {
"test": "wdio run wdio.conf.ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"-": "^0.0.1",
"@wdio/cli": "^7.16.16",
"save-dev": "^0.0.1-security",
"ts-node": "^10.6.0"
},
"devDependencies": {
"@wdio/local-runner": "^7.16.16",
"@wdio/mocha-framework": "^7.16.15",
"@wdio/spec-reporter": "^7.16.14",
"prettier": "2.5.1",
"typescript": "^4.6.2"
}
}
@@ -0,0 +1,45 @@
class WalletLogin {
get errorValidation(): Promise<WebdriverIO.Element> {
return $("[data-testid='error']")
}
get signInAccount(): Promise<WebdriverIO.Element> {
return $("[data-testid='signIn']")
}
get createAccount(): Promise<WebdriverIO.Element> {
return $("[data-testid='createAccount']")
}
get getMnemonicPhrase(): Promise<WebdriverIO.Element> {
return $("[data-testid='mnemonic-phrase']")
}
get signInButtonReturn(): Promise<WebdriverIO.Element> {
return $("[data-testid='sign-in-button']")
}
get backButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='backButton']")
}
get mnemonic(): Promise<WebdriverIO.Element> {
return $('#mui-1')
}
get selectTextArea(): Promise<WebdriverIO.Element> {
//bit nasty using the xpath - but it's not liking the elements
return $("//*[@id='mui-1']")
}
get accountBalance(): Promise<WebdriverIO.Element> {
//bit nasty using the xpath - but it's not liking the elements
return $("[data-testid='refresh-success']")
}
enterMnemonic = async (mnemonic: string): Promise<void> => {
await (await this.selectTextArea).click()
await (await this.mnemonic).addValue(mnemonic)
}
}
export default new WalletLogin()
@@ -0,0 +1,39 @@
class WalletReceive {
get receiveNymHeader(): Promise<WebdriverIO.Element> {
return $(
'#root > div > div:nth-child(2) > div:nth-child(2) > div > div > div > div.MuiCardHeader-root > div > span',
)
}
get receiveNymText(): Promise<WebdriverIO.Element> {
return $("[data-testid='receive-nym']")
}
get walletAddress(): Promise<WebdriverIO.Element> {
return $("[data-testid='client-address']")
}
get copyButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='copy-button']")
}
get qrCode(): Promise<WebdriverIO.Element> {
return $("[data-testid='qr-code']")
}
WaitForButtonChangeOnCopy = async (): Promise<void> => {
await (await this.copyButton).click()
await (await this.copyButton).waitForDisplayed({ timeout: 1500 })
await (
await this.copyButton
).waitUntil(
async function () {
return (await this.getText()) === 'COPIED'
},
{
timeout: 1500,
timeoutMsg: 'expected text to be different after 1.5s',
},
)
}
}
export default new WalletReceive()
@@ -0,0 +1,52 @@
class WalletSend {
get fromAddress() {
return $('#from')
}
get toAddress(): Promise<WebdriverIO.Element> {
return $('#to')
}
get amount(): Promise<WebdriverIO.Element> {
return $('#amount')
}
get nextButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='button")
}
get sendHeader(): Promise<WebdriverIO.Element> {
return $("[data-testid='Send punk']")
}
get accountBalance(): Promise<WebdriverIO.Element> {
return $("[data-testid='account-balance']")
}
get amountReviewAndSend(): Promise<WebdriverIO.Element> {
return $("[data-testid='Amount']")
}
get toAddressReviewAndSend(): Promise<WebdriverIO.Element> {
return $("[data-testid='To']")
}
get fromAddressReviewAndSend(): Promise<WebdriverIO.Element> {
return $("[data-testid='From']")
}
get transferFeeAmount(): Promise<WebdriverIO.Element> {
return $("[data-testid='Transfer fee']")
}
get reviewAndSendBackButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='back-button']")
}
get sendButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='button']")
}
get transactionComplete(): Promise<WebdriverIO.Element> {
return $("[data-testid='transaction-complete']")
}
get transactionCompleteRecipient(): Promise<WebdriverIO.Element> {
return $("[data-testid='to-address']")
}
get transactionCompleteAmount(): Promise<WebdriverIO.Element> {
return $("[data-testid='send-amount']")
}
get finishButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='button']")
}
}
export default new WalletSend()
@@ -0,0 +1,22 @@
class WallentUndelegate {
get transactionFee(): Promise<WebdriverIO.Element> {
return $("[data-testid='fee-amount']")
}
get mixNodeRadioButton(): Promise<WebdriverIO.Element> {
return $("[value='mixnode']")
}
get gatewayRadionButton(): Promise<WebdriverIO.Element> {
return $("[value='gateway']")
}
get nodeIdentity(): Promise<WebdriverIO.Element> {
return $('#mui-55011')
}
get identityHelper(): Promise<WebdriverIO.Element> {
return $('#identity-helper-text')
}
get delegateButton(): Promise<WebdriverIO.Element> {
return $("[data-testid='submit-button']")
}
}
export default new WallentUndelegate()
@@ -0,0 +1,44 @@
import walletLogin from '../pageobjects/wallet.login'
describe('Wallet login functionality', () => {
it.skip('submitting with no mnemonic throws error', async () => {
//sign into account
await (await walletLogin.signInAccount).click()
//submit sign in with no mnemominc
await (await walletLogin.signInAccount).click()
await (await walletLogin.errorValidation).waitForDisplayed({ timeout: 1500 })
let getErrorWarning = await (await walletLogin.errorValidation).getText()
await (await walletLogin.backButton).click()
//assert that the error was thrown
const errorText = 'mnemonic has a word count that is not a multiple of 6: 0'
expect(getErrorWarning).toStrictEqual(errorText)
})
it('should login with valid credentials', async () => {
//create account
await (await walletLogin.createAccount).click()
//allow time for the api to create the wallet address
await browser.pause(500)
await (await walletLogin.getMnemonicPhrase).waitForDisplayed({ timeout: 1500 })
//retrieve mnemonic - copy
let mnemonicPhrase = await (await walletLogin.getMnemonicPhrase).getText()
await (await walletLogin.signInButtonReturn).click()
//input new wallet mnemonic and be inside the app
await walletLogin.enterMnemonic(mnemonicPhrase)
await (await walletLogin.signInAccount).click()
await (await walletLogin.accountBalance).waitForDisplayed({ timeout: 1500 })
let balance = await (await walletLogin.accountBalance).getText()
//new accounts will always default to mainnet
expect(balance).toStrictEqual('0 NYM')
})
})
@@ -0,0 +1,6 @@
{
"compilerOptions": {
"types": ["node", "webdriverio/async", "@wdio/mocha-framework", "expect-webdriverio"],
"target": "ES5"
}
}
+82
View File
@@ -0,0 +1,82 @@
const os = require('os')
const path = require('path')
const { spawn, spawnSync } = require('child_process')
//insert path to binary
const nym_path = '../target/debug/nym_wallet'
let tauriDriver: any
exports.config = {
autoCompileOpts: {
autoCompile: true,
tsNodeOpts: {
transpileOnly: true,
project: 'test/tsconfig.json',
},
},
specs: ['./test/specs/**/*.ts'],
// Patterns to exclude.
exclude: [
// 'path/to/excluded/files'
],
maxInstances: 1,
capabilities: [
{
maxInstances: 1,
'tauri:options': {
application: nym_path,
},
},
],
//
// ===================
// Test Configurations
// ===================
// Define all options that are relevant for the WebdriverIO instance here
//
// Level of logging verbosity: trace | debug | info | warn | error | silent
logLevel: 'info',
bail: 0,
framework: 'mocha',
reporters: ['spec'],
mochaOpts: {
ui: 'bdd',
timeout: 60000,
},
// ===================
// Test Reporters
// ===================
// reporters: [
// [
// "allure",
// {
// outputDir: "allure-results",
// disableWebdriverStepsReporting: true,
// disableWebdriverScreenshotsReporting: true,
// },
// ],
// ],
// this is documentented in the readme - you will need to build the project first
// ensure the rust project is built since we expect this binary to exist for the webdriver sessions
//onPrepare: () => spawnSync("cargo", ["build", "--release"]),
// ensure we are running `tauri-driver` before the session starts so that we can proxy the webdriver requests
beforeSession: () =>
(tauriDriver = spawn(path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), [], {
stdio: [null, process.stdout, process.stderr],
})),
// afterTest: function (
// test,
// context,
// { error, result, duration, passed, retries }
// ) {
// if (error) {
// browser.takeScreenshot();
// }
// },
// clean up the `tauri-driver` process we spawned at the start of the session
afterSession: () => tauriDriver.kill(),
}
File diff suppressed because it is too large Load Diff
+115 -2044
View File
File diff suppressed because it is too large Load Diff