Skip to content

Commit

Permalink
Merge branch '2.0' of https://github.com/iotaledger/iota-sdk into 500…
Browse files Browse the repository at this point in the history
…-error-patch
  • Loading branch information
marc2332 committed Feb 28, 2024
2 parents fdd19a1 + c43c804 commit 83580aa
Show file tree
Hide file tree
Showing 44 changed files with 510 additions and 564 deletions.
2 changes: 1 addition & 1 deletion bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ pub enum UtilsMethod {
output: Output,
},
/// Verifies the semantic of a transaction.
/// Expected response: [`TransactionFailureReason`](crate::Response::TransactionFailureReason)
/// Expected response: [`Ok`](crate::Response::Ok)
#[serde(rename_all = "camelCase")]
VerifyTransactionSemantic {
transaction: TransactionDto,
Expand Down
4 changes: 2 additions & 2 deletions bindings/core/src/method/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub enum WalletMethod {
/// Expected response: [`Ok`](crate::Response::Ok)
#[cfg(feature = "stronghold")]
#[cfg_attr(docsrs, doc(cfg(feature = "stronghold")))]
Backup {
BackupToStrongholdSnapshot {
/// The backup destination.
destination: PathBuf,
/// Stronghold file password.
Expand All @@ -71,7 +71,7 @@ pub enum WalletMethod {
#[cfg(feature = "stronghold")]
#[cfg_attr(docsrs, doc(cfg(feature = "stronghold")))]
#[serde(rename_all = "camelCase")]
RestoreBackup {
RestoreFromStrongholdSnapshot {
/// The path to the backed up Stronghold.
source: PathBuf,
/// Stronghold file password.
Expand Down
4 changes: 3 additions & 1 deletion bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
protocol_parameters,
);

Response::TransactionFailureReason(context.validate()?)
context.validate().map_err(Error::from)?;

Response::Ok
}
UtilsMethod::ManaWithDecay {
mana,
Expand Down
8 changes: 4 additions & 4 deletions bindings/core/src/method_handler/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ pub(crate) async fn call_wallet_method_internal(wallet: &Wallet, method: WalletM
let response = match method {
WalletMethod::Accounts => Response::OutputsData(wallet.ledger().await.accounts().cloned().collect()),
#[cfg(feature = "stronghold")]
WalletMethod::Backup { destination, password } => {
wallet.backup(destination, password).await?;
WalletMethod::BackupToStrongholdSnapshot { destination, password } => {
wallet.backup_to_stronghold_snapshot(destination, password).await?;
Response::Ok
}
#[cfg(feature = "stronghold")]
Expand All @@ -45,14 +45,14 @@ pub(crate) async fn call_wallet_method_internal(wallet: &Wallet, method: WalletM
Response::Bool(is_available)
}
#[cfg(feature = "stronghold")]
WalletMethod::RestoreBackup {
WalletMethod::RestoreFromStrongholdSnapshot {
source,
password,
ignore_if_coin_type_mismatch,
ignore_if_bech32_mismatch,
} => {
wallet
.restore_backup(
.restore_from_stronghold_snapshot(
source,
password,
ignore_if_coin_type_mismatch,
Expand Down
3 changes: 0 additions & 3 deletions bindings/core/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ use iota_sdk::{
},
payload::{dto::SignedTransactionPayloadDto, signed_transaction::TransactionId},
protocol::ProtocolParameters,
semantic::TransactionFailureReason,
signature::Ed25519Signature,
slot::{SlotCommitment, SlotCommitmentId},
unlock::Unlock,
Expand Down Expand Up @@ -233,8 +232,6 @@ pub enum Response {
CustomJson(serde_json::Value),
/// Response for [`ComputeSlotCommitmentId`](crate::method::UtilsMethod::ComputeSlotCommitmentId)
SlotCommitmentId(SlotCommitmentId),
/// Response for [`VerifyTransactionSemantic`](crate::method::UtilsMethod::VerifyTransactionSemantic).
TransactionFailureReason(Option<TransactionFailureReason>),

// Responses in client and wallet
/// Response for:
Expand Down
8 changes: 4 additions & 4 deletions bindings/nodejs/lib/types/wallet/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,15 @@ import type {
__PrepareIncreaseVotingPowerMethod__,
__PrepareDecreaseVotingPowerMethod__,
__PrepareStopParticipatingMethod__,
__BackupMethod__,
__BackupToStrongholdSnapshotMethod__,
__ChangeStrongholdPasswordMethod__,
__ClearStrongholdPasswordMethod__,
__ClearListenersMethod__,
__EmitTestEventMethod__,
__GenerateMnemonicMethod__,
__GetLedgerNanoStatusMethod__,
__IsStrongholdPasswordAvailableMethod__,
__RestoreBackupMethod__,
__RestoreFromStrongholdSnapshotMethod__,
__SetClientOptionsMethod__,
__SetStrongholdPasswordClearIntervalMethod__,
__SetStrongholdPasswordMethod__,
Expand Down Expand Up @@ -131,15 +131,15 @@ export type __WalletMethod__ =
| __GetParticipationOverviewMethod__
| __PrepareIncreaseVotingPowerMethod__
| __PrepareDecreaseVotingPowerMethod__
| __BackupMethod__
| __BackupToStrongholdSnapshotMethod__
| __ChangeStrongholdPasswordMethod__
| __ClearListenersMethod__
| __ClearStrongholdPasswordMethod__
| __EmitTestEventMethod__
| __GenerateMnemonicMethod__
| __GetLedgerNanoStatusMethod__
| __IsStrongholdPasswordAvailableMethod__
| __RestoreBackupMethod__
| __RestoreFromStrongholdSnapshotMethod__
| __SetClientOptionsMethod__
| __SetStrongholdPasswordClearIntervalMethod__
| __SetStrongholdPasswordMethod__
Expand Down
8 changes: 4 additions & 4 deletions bindings/nodejs/lib/types/wallet/bridge/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ export type __AnnounceCandidacyMethod__ = {
};
};

export type __BackupMethod__ = {
name: 'backup';
export type __BackupToStrongholdSnapshotMethod__ = {
name: 'backupToStrongholdSnapshot';
data: {
destination: string;
password: string;
Expand Down Expand Up @@ -93,8 +93,8 @@ export type __IsStrongholdPasswordAvailableMethod__ = {
name: 'isStrongholdPasswordAvailable';
};

export type __RestoreBackupMethod__ = {
name: 'restoreBackup';
export type __RestoreFromStrongholdSnapshotMethod__ = {
name: 'restoreFromStrongholdSnapshot';
data: {
source: string;
password: string;
Expand Down
5 changes: 0 additions & 5 deletions bindings/nodejs/lib/types/wallet/transaction-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ export interface TransactionOptions {
allowMicroAmount?: boolean;
/** Whether to allow the selection of additional inputs for this transaction. */
allowAdditionalInputSelection?: boolean;
/**
* Whether to allow allotting automatically calculated mana from the issuer account.
* If this flag is disabled, additional inputs will be selected to cover the amount.
*/
allowAllottingFromAccountMana?: boolean;
/** Transaction capabilities. */
capabilities?: HexEncodedString;
/** Mana allotments for the transaction. */
Expand Down
7 changes: 3 additions & 4 deletions bindings/nodejs/lib/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -559,16 +559,16 @@ export class Utils {
* @param unlocks The unlocks.
* @param manaRewards The total mana rewards claimed in the transaction.
*
* @returns The conflict reason.
* @returns void.
*/
static verifyTransactionSemantic(
transaction: SignedTransactionPayload,
inputs: InputSigningData[],
protocolParameters: ProtocolParameters,
unlocks?: Unlock[],
manaRewards?: { [outputId: HexEncodedString]: NumericString },
): string {
const conflictReason = callUtilsMethod({
): void {
return callUtilsMethod({
name: 'verifyTransactionSemantic',
data: {
transaction,
Expand All @@ -578,7 +578,6 @@ export class Utils {
manaRewards,
},
});
return conflictReason;
}

/**
Expand Down
11 changes: 7 additions & 4 deletions bindings/nodejs/lib/wallet/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,12 @@ export class Wallet {
/**
* Backup the data to a Stronghold snapshot.
*/
async backup(destination: string, password: string): Promise<void> {
async backupToStrongholdSnapshot(
destination: string,
password: string,
): Promise<void> {
await this.methodHandler.callMethod({
name: 'backup',
name: 'backupToStrongholdSnapshot',
data: {
destination,
password,
Expand Down Expand Up @@ -200,14 +203,14 @@ export class Wallet {
* if ignore_if_coin_type_mismatch == true, client options coin type and accounts will not be restored if the cointype doesn't match
* If a bech32 hrp is provided to ignore_if_bech32_hrp_mismatch, that doesn't match the one of the current address, the wallet will not be restored.
*/
async restoreBackup(
async restoreFromStrongholdSnapshot(
source: string,
password: string,
ignoreIfCoinTypeMismatch?: boolean,
ignoreIfBech32Mismatch?: string,
): Promise<void> {
await this.methodHandler.callMethod({
name: 'restoreBackup',
name: 'restoreFromStrongholdSnapshot',
data: {
source,
password,
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/examples/wallet/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@
# done once.
wallet.store_mnemonic(os.environ['MNEMONIC'])

wallet.backup("backup.stronghold", os.environ['STRONGHOLD_PASSWORD'])
wallet.backup_to_stronghold_snapshot("backup.stronghold", os.environ['STRONGHOLD_PASSWORD'])
print('Created backup')
2 changes: 1 addition & 1 deletion bindings/python/examples/wallet/restore_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@
if 'STRONGHOLD_PASSWORD' not in os.environ:
raise Exception(".env STRONGHOLD_PASSWORD is undefined, see .env.example")

wallet.restore_backup("backup.stronghold", os.environ['STRONGHOLD_PASSWORD'])
wallet.restore_from_stronghold_snapshot("backup.stronghold", os.environ['STRONGHOLD_PASSWORD'])

print(f'Restored wallet: {json.dumps(wallet, indent=4)}')
3 changes: 0 additions & 3 deletions bindings/python/iota_sdk/types/transaction_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,6 @@ class TransactionOptions:
note: A string attached to the transaction.
allow_micro_amount: Whether to allow sending a micro amount.
allow_additional_input_selection: Whether to allow the selection of additional inputs for this transaction.
allow_allotting_from_account_mana: Whether to allow allotting automatically calculated mana from the issuer account.
If this flag is disabled, additional inputs will be selected to cover the amount.
capabilities: Transaction capabilities.
mana_allotments: Mana allotments for the transaction.
issuer_id: Optional block issuer to which the transaction will have required mana allotted.
Expand All @@ -70,7 +68,6 @@ class TransactionOptions:
note: Optional[str] = None
allow_micro_amount: Optional[bool] = None
allow_additional_input_selection: Optional[bool] = None
allow_allotting_from_account_mana: Optional[bool] = None
capabilities: Optional[HexStr] = None
mana_allotments: Optional[dict[HexStr, int]] = None
issuer_id: Optional[HexStr] = None
4 changes: 2 additions & 2 deletions bindings/python/iota_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,10 @@ def verify_secp256k1_ecdsa_signature(

@staticmethod
def verify_transaction_semantic(
transaction: Transaction, inputs: List[InputSigningData], protocol_parameters: ProtocolParameters, unlocks: Optional[List[Unlock]] = None, mana_rewards: Optional[dict[OutputId, int]] = None) -> str:
transaction: Transaction, inputs: List[InputSigningData], protocol_parameters: ProtocolParameters, unlocks: Optional[List[Unlock]] = None, mana_rewards: Optional[dict[OutputId, int]] = None):
"""Verifies the semantic of a transaction.
"""
return _call_method('verifyTransactionSemantic', {
_call_method('verifyTransactionSemantic', {
'transaction': transaction,
'inputs': inputs,
'unlocks': unlocks,
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/iota_sdk/wallet/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _call_method(self, name: str, data=None):
message['data'] = data
return message

def backup(self, destination: str, password: str):
def backup_to_stronghold_snapshot(self, destination: str, password: str):
"""Backup storage.
"""
return self._call_method(
Expand Down Expand Up @@ -150,7 +150,7 @@ def clear_listeners(self, events: Optional[List[int]] = None):
}
)

def restore_backup(self, source: str, password: str):
def restore_from_stronghold_snapshot(self, source: str, password: str):
"""Restore a backup from a Stronghold file.
Replaces `client_options`, `coin_type`, `secret_manager` and wallet.
Returns an error if the wallet was already created. If Stronghold is used
Expand Down
28 changes: 19 additions & 9 deletions cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ fn parse_bip_path(arg: &str) -> Result<Bip44, String> {

#[derive(Debug, Clone, Subcommand)]
pub enum CliCommand {
/// Create a stronghold backup file.
/// Create a backup file. Currently only Stronghold backup is supported.
Backup {
/// Path of the created stronghold backup file.
backup_path: String,
Expand All @@ -140,7 +140,7 @@ pub enum CliCommand {
},
/// Get information about currently set node.
NodeInfo,
/// Restore a stronghold backup file.
/// Restore a backup file. Currently only Stronghold backup is supported.
Restore {
/// Path of the to be restored stronghold backup file.
backup_path: String,
Expand Down Expand Up @@ -202,7 +202,7 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
snapshot_exists: true, ..
} => {
let password = get_password("Stronghold password", false)?;
backup_command_stronghold(&wallet, &password, Path::new(&backup_path)).await?;
backup_to_stronghold_snapshot_command(&wallet, &password, Path::new(&backup_path)).await?;
return Ok(None);
}
LinkedSecretManager::Stronghold { snapshot_path, .. } => {
Expand Down Expand Up @@ -294,7 +294,7 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
// we need to explicitly drop the current wallet here to prevent:
// "error accessing storage: IO error: lock hold by current process"
drop(wallet);
let wallet = restore_command_stronghold(
let wallet = restore_from_stronghold_snapshot_command(
storage_path,
snapshot_path.as_path(),
Path::new(&backup_path),
Expand All @@ -312,7 +312,8 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
let init_params = InitParameters::default();
let snapshot_path = Path::new(&init_params.stronghold_snapshot_path);
let wallet =
restore_command_stronghold(storage_path, snapshot_path, Path::new(&backup_path)).await?;
restore_from_stronghold_snapshot_command(storage_path, snapshot_path, Path::new(&backup_path))
.await?;
Some(wallet)
}
}
Expand Down Expand Up @@ -382,8 +383,14 @@ pub async fn new_wallet(cli: Cli) -> Result<Option<Wallet>, Error> {
})
}

pub async fn backup_command_stronghold(wallet: &Wallet, password: &Password, backup_path: &Path) -> Result<(), Error> {
wallet.backup(backup_path.into(), password.clone()).await?;
pub async fn backup_to_stronghold_snapshot_command(
wallet: &Wallet,
password: &Password,
backup_path: &Path,
) -> Result<(), Error> {
wallet
.backup_to_stronghold_snapshot(backup_path.into(), password.clone())
.await?;

println_log_info!("Wallet has been backed up to \"{}\".", backup_path.display());

Expand Down Expand Up @@ -453,7 +460,7 @@ pub async fn node_info_command(wallet: &Wallet) -> Result<(), Error> {
Ok(())
}

pub async fn restore_command_stronghold(
pub async fn restore_from_stronghold_snapshot_command(
storage_path: &Path,
snapshot_path: &Path,
backup_path: &Path,
Expand Down Expand Up @@ -495,7 +502,10 @@ pub async fn restore_command_stronghold(
.await?;

let password = get_password("Stronghold backup password", false)?;
if let Err(e) = wallet.restore_backup(backup_path.into(), password, None, None).await {
if let Err(e) = wallet
.restore_from_stronghold_snapshot(backup_path.into(), password, None, None)
.await
{
// Clean up the file system after a failed restore (typically produces a wallet without a secret manager).
// TODO: a better way would be to not create any files/dirs in the first place when it's not clear yet whether
// the restore will be successful. https://github.com/iotaledger/iota-sdk/issues/2018
Expand Down
Loading

0 comments on commit 83580aa

Please sign in to comment.