Struct Wallet

Source
pub struct Wallet {
    pub name: String,
    pub version: String,
    pub scrypt_params: ScryptParamsDef,
    pub accounts: HashMap<H160, Account>,
    pub extra: Option<HashMap<String, String>>,
    /* private fields */
}

Fields§

§name: String§version: String§scrypt_params: ScryptParamsDef§accounts: HashMap<H160, Account>§extra: Option<HashMap<String, String>>

Additional wallet metadata stored as key-value pairs

Implementations§

Source§

impl Wallet

Source

pub const DEFAULT_WALLET_NAME: &'static str = "NeoWallet"

The default wallet name.

Source

pub const CURRENT_VERSION: &'static str = "1.0"

The current wallet version.

Source

pub fn new() -> Self

Creates a new wallet instance with a default account.

Source

pub fn default() -> Self

Creates a new wallet instance without any accounts.

Source

pub fn to_nep6(&self) -> Result<Nep6Wallet, WalletError>

Converts the wallet to a NEP6Wallet format.

Source

pub fn from_nep6(nep6: Nep6Wallet) -> Result<Self, WalletError>

Creates a wallet from a NEP6Wallet format.

Source

pub fn from_account(account: &Account) -> Result<Wallet, WalletError>

Source

pub fn from_accounts(accounts: Vec<Account>) -> Result<Wallet, WalletError>

Adds the given accounts to this wallet, if it doesn’t contain an account with the same script hash (address).

§Parameters
  • accounts - The accounts to add
§Returns

Returns the mutable wallet reference if the accounts were successfully added, or a WalletError if an account is already contained in another wallet.

§Errors

Returns a WalletError::IllegalArgument error if an account is already contained in another wallet.

§Example

use neo3::prelude::*;
use neo3::neo_protocol::AccountTrait;
let account1 = protocol::Account::create().unwrap();
let account2 = protocol::Account::create().unwrap();

let mut wallet = wallets::Wallet::from_accounts(vec![account1, account2]).unwrap();
Source

pub fn save_to_file(&self, path: PathBuf) -> Result<(), WalletError>

Source

pub fn get_account(&self, script_hash: &H160) -> Option<&Account>

Source

pub fn remove_account(&mut self, script_hash: &H160) -> bool

Source

pub fn encrypt_accounts(&mut self, password: &str)

Source

pub fn encrypt_accounts_parallel(&mut self, password: &str)

Encrypts all accounts in the wallet using parallel processing.

This method provides significant performance improvements when dealing with wallets containing many accounts by leveraging Rayon’s parallel iteration. The encryption of each account is independent and CPU-intensive (due to scrypt key derivation), making it ideal for parallelization.

§Arguments
  • password - The password to use for encrypting all accounts
§Performance Notes
  • Uses Rayon’s work-stealing thread pool for optimal CPU utilization
  • Each account encryption is processed in parallel
  • Thread pool size automatically adjusts to available CPU cores
  • Performance gains scale with the number of accounts and CPU cores
§Example
// For wallets with many accounts, use parallel encryption
wallet.encrypt_accounts_parallel("strong_password");
Source

pub fn encrypt_accounts_parallel_with_threads( &mut self, password: &str, num_threads: usize, )

Encrypts accounts in parallel with custom thread pool configuration.

This method allows fine-tuning of the parallel encryption process by configuring the number of threads used. This can be useful in scenarios where you want to limit CPU usage or optimize for specific hardware.

§Arguments
  • password - The password to use for encrypting all accounts
  • num_threads - The number of threads to use for parallel processing
§Example
// Use 4 threads for encryption
wallet.encrypt_accounts_parallel_with_threads("strong_password", 4);
Source

pub fn encrypt_accounts_batch_parallel( &mut self, password: &str, batch_size: usize, )

Encrypts accounts in parallel using batch processing.

This method processes accounts in batches, which can be more efficient for very large wallets by reducing overhead and improving cache locality. It uses a different approach than the standard parallel method by collecting account data first to avoid mutable borrow conflicts.

§Arguments
  • password - The password to use for encrypting all accounts
  • batch_size - The number of accounts to process in each batch
§Example
// Process accounts in batches of 50
wallet.encrypt_accounts_batch_parallel("strong_password", 50);
Source

pub fn create(path: &PathBuf, password: &str) -> Result<Self, WalletError>

👎Deprecated since 0.1.0: Please use create_wallet instead

Creates a new wallet and saves it to the specified path

This method has been renamed to create_wallet for clarity. Please use create_wallet instead.

§Arguments
  • path - The file path where the wallet will be saved
  • password - The password to encrypt the wallet
§Returns

A Result containing the new wallet or a WalletError

Source

pub fn open(path: &PathBuf, password: &str) -> Result<Self, WalletError>

👎Deprecated since 0.1.0: Please use open_wallet instead

Opens a wallet from the specified path

This method has been renamed to open_wallet for clarity. Please use open_wallet instead.

§Arguments
  • path - The file path of the wallet to open
  • password - The password to decrypt the wallet
§Returns

A Result containing the opened wallet or a WalletError

Source

pub fn get_accounts(&self) -> Vec<&Account>

Returns all accounts in the wallet

Source

pub fn create_account(&mut self) -> Result<&Account, WalletError>

Creates a new account in the wallet

Source

pub fn import_private_key(&mut self, wif: &str) -> Result<&Account, WalletError>

Imports a private key in WIF format

Source

pub fn verify_password(&self, password: &str) -> bool

Verifies if the provided password is correct by attempting to decrypt any encrypted account

This function checks if the provided password can successfully decrypt at least one of the encrypted private keys in the wallet. If at least one account can be decrypted, the password is considered valid.

Returns true if the password is correct, false otherwise.

Source

pub fn change_password( &mut self, current_password: &str, new_password: &str, ) -> Result<(), WalletError>

Changes the wallet password

Source

pub fn change_password_parallel( &mut self, current_password: &str, new_password: &str, ) -> Result<(), WalletError>

Changes the wallet password using parallel processing.

This method provides better performance for wallets with many accounts by parallelizing both the decryption and re-encryption processes.

§Arguments
  • current_password - The current password of the wallet
  • new_password - The new password to set
§Returns

A Result indicating success or containing a WalletError on failure

§Example
wallet.change_password_parallel("old_password", "new_password").unwrap();
Source

pub async fn get_unclaimed_gas<P>( &self, rpc_client: &P, ) -> Result<UnclaimedGas, WalletError>
where P: JsonRpcProvider + APITrait + 'static, <P as APITrait>::Error: Into<ProviderError>,

Gets the unclaimed GAS for all accounts in the wallet

Source§

impl Wallet

Source

pub async fn sign_message<S: Send + Sync + AsRef<[u8]>>( &self, message: S, ) -> Result<Secp256r1Signature, WalletError>

Signs a given message using the default account’s private key.

This method computes the SHA-256 hash of the input message and then signs it using the ECDSA Secp256r1 algorithm. It’s primarily used for generating signatures that can prove ownership of an address or for other cryptographic verifications.

§Parameters
  • message: The message to be signed. This can be any data that implements AsRef<[u8]>, allowing for flexibility in the type of data that can be signed.
§Returns

A Result that, on success, contains the Secp256r1Signature of the message. On failure, it returns a WalletError, which could indicate issues like a missing key pair.

§Example
 async fn example() -> Result<(), Box<dyn std::error::Error>> {
let message = "Hello, world!";
let signature = wallet.sign_message(message).await?;
println!("Signed message: {:?}", signature);
Source

pub async fn get_witness<'a, P: JsonRpcProvider + 'static>( &self, tx: &Transaction<'a, P>, ) -> Result<Witness, WalletError>

Generates a witness for a transaction using the default account’s key pair.

This method is used to attach a signature to a transaction, proving that the transaction was authorized by the owner of the default account. It’s an essential step in transaction validation for blockchain systems.

§Parameters
  • tx: A reference to the transaction that needs a witness.
§Returns

A Result that, on success, contains the Witness for the given transaction. On failure, it returns a WalletError, which could be due to issues like a missing key pair.

§Example
 async fn example() -> Result<(), Box<dyn std::error::Error>> {
let witness = wallet.get_witness(&tx).await?;
println!("Witness: {:?}", witness);
Source

pub async fn sign_transaction<'a, P>( &self, tx_builder: &'a mut TransactionBuilder<'a, P>, account_address: &str, password: &str, ) -> Result<Transaction<'a, P>, WalletError>
where P: JsonRpcProvider + 'static,

Signs a transaction using the specified account.

§Arguments
  • tx_builder - The transaction builder containing the transaction to sign
  • account_address - The address of the account to use for signing
  • password - The password to decrypt the account’s private key if needed
§Returns

A Result containing the signed transaction or a WalletError

Source

pub fn create_wallet( path: &PathBuf, password: &str, ) -> Result<Self, WalletError>

Creates a new wallet with the specified path and password.

§Arguments
  • path - The file path where the wallet will be saved
  • password - The password to encrypt the wallet
§Returns

A Result containing the new wallet or a WalletError

Source

pub fn open_wallet(path: &PathBuf, password: &str) -> Result<Self, WalletError>

Opens an existing wallet from the specified path with the given password.

§Arguments
  • path - The file path of the wallet to open
  • password - The password to decrypt the wallet
§Returns

A Result containing the opened wallet or a WalletError

Source

pub fn get_all_accounts(&self) -> Vec<&Account>

Gets all accounts in the wallet.

§Returns

A vector of references to all accounts in the wallet

Source

pub fn create_new_account(&mut self) -> Result<&Account, WalletError>

Creates a new account in the wallet.

§Returns

A Result containing the new account or a WalletError

Source

pub fn import_from_wif( &mut self, private_key: &str, ) -> Result<&Account, WalletError>

Imports a private key into the wallet.

§Arguments
  • private_key - The private key to import
§Returns

A Result containing the imported account or a WalletError

Source

pub async fn get_unclaimed_gas_as_float<P>( &self, rpc_client: &RpcClient<P>, ) -> Result<f64, WalletError>
where P: JsonRpcProvider + 'static,

Gets the unclaimed GAS for the wallet as a float value.

§Arguments
  • rpc_client - The RPC client to use for the query
§Returns

A Result containing the unclaimed GAS amount as a float or a WalletError

Source

pub fn with_network(self, network: u32) -> Self

This method configures the wallet to operate within a specific blockchain network by setting the network magic (ID), which is essential for correctly signing transactions.

§Parameters
  • network: The network ID to set for the wallet.
§Returns

The modified Wallet instance with the new network ID set.

§Example
let mut wallet = wallets::Wallet::new();
wallet = wallet.with_network(0x334F454E); // MainNet magic number

Trait Implementations§

Source§

impl Clone for Wallet

Source§

fn clone(&self) -> Wallet

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Wallet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Wallet

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Wallet

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl WalletTrait for Wallet

Source§

type Account = Account

The type of account managed by the wallet.
Source§

fn name(&self) -> &String

Returns the name of the wallet.
Source§

fn version(&self) -> &String

Returns the version of the wallet.
Source§

fn scrypt_params(&self) -> &ScryptParamsDef

Returns the scrypt parameters used for key derivation.
Source§

fn accounts(&self) -> Vec<Self::Account>

Returns a list of accounts stored in the wallet.
Source§

fn default_account(&self) -> &Account

Returns a reference to the default account of the wallet.
Source§

fn set_name(&mut self, name: String)

Sets the name of the wallet.
Source§

fn set_version(&mut self, version: String)

Sets the version of the wallet.
Source§

fn set_scrypt_params(&mut self, params: ScryptParamsDef)

Sets the scrypt parameters for the wallet.
Source§

fn set_default_account(&mut self, default_account: H160)

Sets the default account of the wallet.
Source§

fn add_account(&mut self, account: Self::Account)

Adds a new account to the wallet.
Source§

fn remove_account(&mut self, hash: &H160) -> Option<Self::Account>

Removes an account from the wallet by its hash. Read more

Auto Trait Implementations§

§

impl Freeze for Wallet

§

impl RefUnwindSafe for Wallet

§

impl Send for Wallet

§

impl Sync for Wallet

§

impl Unpin for Wallet

§

impl UnwindSafe for Wallet

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> ErasedDestructor for T
where T: 'static,