Skip to content

Commit

Permalink
Merge branch '2.0' into feat/auto-txn-capabilities
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Coats committed Mar 1, 2024
2 parents 59828cb + 37d52aa commit 7f82ec2
Show file tree
Hide file tree
Showing 242 changed files with 2,496 additions and 2,359 deletions.
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 21 additions & 2 deletions bindings/core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
// Copyright 2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use iota_sdk::types::block::{
mana::ManaError, output::OutputError, payload::PayloadError, semantic::TransactionFailureReason,
signature::SignatureError, BlockError,
};
use packable::error::UnexpectedEOF;
use serde::{Serialize, Serializer};

Expand All @@ -14,7 +18,22 @@ pub type Result<T> = std::result::Result<T, Error>;
pub enum Error {
/// Block errors.
#[error("{0}")]
Block(#[from] iota_sdk::types::block::Error),
Block(#[from] BlockError),
/// Output errors.
#[error("{0}")]
Output(#[from] OutputError),
/// Payload errors.
#[error("{0}")]
Payload(#[from] PayloadError),
/// Signature errors.
#[error("{0}")]
Signature(#[from] SignatureError),
/// Mana errors.
#[error("{0}")]
Mana(#[from] ManaError),
/// Semantic errors.
#[error("{0}")]
TransactionSemantic(#[from] TransactionFailureReason),
/// Client errors.
#[error("{0}")]
Client(#[from] iota_sdk::client::Error),
Expand All @@ -29,7 +48,7 @@ pub enum Error {
SerdeJson(#[from] serde_json::error::Error),
/// Unpack errors.
#[error("{0}")]
Unpack(#[from] packable::error::UnpackError<iota_sdk::types::block::Error, UnexpectedEOF>),
Unpack(#[from] packable::error::UnpackError<BlockError, UnexpectedEOF>),
}

#[cfg(feature = "stronghold")]
Expand Down
6 changes: 3 additions & 3 deletions bindings/core/src/method/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use iota_sdk::{
unlock::Unlock,
BlockDto,
},
utils::serde::{mana_rewards, string},
utils::serde::{option_mana_rewards, string},
};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -179,8 +179,8 @@ pub enum UtilsMethod {
transaction: TransactionDto,
inputs: Vec<InputSigningData>,
unlocks: Option<Vec<Unlock>>,
#[serde(default, with = "mana_rewards")]
mana_rewards: BTreeMap<OutputId, u64>,
#[serde(default, with = "option_mana_rewards")]
mana_rewards: Option<BTreeMap<OutputId, u64>>,
protocol_parameters: ProtocolParameters,
},
/// Applies mana decay to the given mana.
Expand Down
14 changes: 8 additions & 6 deletions bindings/core/src/method_handler/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ use iota_sdk::{
output::{AccountId, FoundryId, MinimumOutputAmount, NftId, Output, OutputId, TokenId},
payload::{signed_transaction::Transaction, SignedTransactionPayload},
semantic::SemanticValidationContext,
Block, Error,
signature::SignatureError,
Block,
},
TryFromDto,
},
Expand Down Expand Up @@ -91,7 +92,7 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
}
UtilsMethod::VerifyEd25519Signature { signature, message } => {
let message: Vec<u8> = prefix_hex::decode(message)?;
Response::Bool(signature.try_verify(&message).map_err(Error::from)?)
Response::Bool(signature.try_verify(&message).map_err(iota_sdk::client::Error::from)?)
}
UtilsMethod::VerifySecp256k1EcdsaSignature {
public_key,
Expand All @@ -100,9 +101,11 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
} => {
use crypto::signatures::secp256k1_ecdsa;
let public_key = prefix_hex::decode(public_key)?;
let public_key = secp256k1_ecdsa::PublicKey::try_from_bytes(&public_key).map_err(Error::from)?;
let public_key = secp256k1_ecdsa::PublicKey::try_from_bytes(&public_key)
.map_err(SignatureError::InvalidPublicKeyBytes)?;
let signature = prefix_hex::decode(signature)?;
let signature = secp256k1_ecdsa::Signature::try_from_bytes(&signature).map_err(Error::from)?;
let signature = secp256k1_ecdsa::Signature::try_from_bytes(&signature)
.map_err(SignatureError::InvalidSignatureBytes)?;
let message: Vec<u8> = prefix_hex::decode(message)?;
Response::Bool(public_key.verify_keccak256(&signature, &message))
}
Expand All @@ -129,8 +132,7 @@ pub(crate) fn call_utils_method_internal(method: UtilsMethod) -> Result<Response
mana_rewards,
protocol_parameters,
);

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

Response::Ok
}
Expand Down
4 changes: 2 additions & 2 deletions bindings/core/tests/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
// SPDX-License-Identifier: Apache-2.0

use iota_sdk::types::block::address::{Bech32Address, Hrp};
use iota_sdk_bindings_core::{call_utils_method, Response, Result, UtilsMethod};
use iota_sdk_bindings_core::{call_utils_method, Response, UtilsMethod};
use pretty_assertions::assert_eq;

#[tokio::test]
async fn utils() -> Result<()> {
async fn utils() -> Result<(), Box<dyn std::error::Error>> {
let response = call_utils_method(UtilsMethod::GenerateMnemonic);
match response {
Response::GeneratedMnemonic(mnemonic) => println!("{:?}", serde_json::to_string(&mnemonic)?),
Expand Down
10 changes: 8 additions & 2 deletions bindings/nodejs/lib/types/wallet/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ export interface WalletSyncOptions {
accountOutputs?: boolean;
/** Whether to sync NFT outputs. */
nftOutputs?: boolean;
/** Whether to sync delegation outputs. */
delegationOutputs?: boolean;
}

/** Specifies what outputs should be synced for the address of an account output. */
Expand All @@ -139,10 +141,12 @@ export interface AccountSyncOptions {
basicOutputs?: boolean;
/** Whether to sync Account outputs. */
accountOutputs?: boolean;
/** Whether to sync NFT outputs. */
nftOutputs?: boolean;
/** Whether to sync foundry outputs. */
foundryOutputs?: boolean;
/** Whether to sync NFT outputs. */
nftOutputs?: boolean;
/** Whether to sync delegation outputs. */
delegationOutputs?: boolean;
}

/** Specifies what outputs should be synced for the address of an nft output. */
Expand All @@ -153,6 +157,8 @@ export interface NftSyncOptions {
accountOutputs?: boolean;
/** Whether to sync NFT outputs. */
nftOutputs?: boolean;
/** Whether to sync delegation outputs. */
delegationOutputs?: boolean;
}

/** Options to filter outputs */
Expand Down
4 changes: 3 additions & 1 deletion bindings/python/examples/wallet/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,7 @@
# done once.
wallet.store_mnemonic(os.environ['MNEMONIC'])

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

wallet.restore_from_stronghold_snapshot("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)}')
6 changes: 4 additions & 2 deletions bindings/python/iota_sdk/types/output_id_proof.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class OutputCommitmentProofType(IntEnum):
Attributes:
HashableNode (0): Denotes a HashableNode.
LeafHash (1): Denotes a LeafHash.
Valuehash (2): Denotes a Valuehash.
ValueHash (2): Denotes a ValueHash.
"""
HashableNode = 0
LeafHash = 1
Expand Down Expand Up @@ -88,7 +88,9 @@ class OutputIdProof:
slot: SlotIndex
output_index: int
transaction_commitment: HexStr
output_commitment_proof: OutputCommitmentProof
output_commitment_proof: OutputCommitmentProof = field(metadata=config(
decoder=deserialize_proof
))


OutputCommitmentProof: TypeAlias = Union[HashableNode, LeafHash, ValueHash]
18 changes: 12 additions & 6 deletions bindings/python/iota_sdk/wallet/sync_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ class WalletSyncOptions:
Attributes:
basic_outputs: Whether to sync basic outputs.
nft_outputs: Whether to sync NFT outputs.
account_outputs: whether to sync account outputs.
nft_outputs: Whether to sync NFT outputs.
delegation_outputs: Whether to sync delegation outputs.
"""

basic_outputs: Optional[bool] = None
nft_outputs: Optional[bool] = None
account_outputs: Optional[bool] = None
nft_outputs: Optional[bool] = None
delegation_outputs: Optional[bool] = None


@json
Expand All @@ -29,15 +31,17 @@ class AccountSyncOptions:
Attributes:
basic_outputs: Whether to sync basic outputs.
nft_outputs: Whether to sync NFT outputs.
account_outputs: Whether to sync account outputs.
foundry_outputs: Whether to sync foundry outputs.
nft_outputs: Whether to sync NFT outputs.
delegation_outputs: Whether to sync delegation outputs.
"""

basic_outputs: Optional[bool] = None
nft_outputs: Optional[bool] = None
account_outputs: Optional[bool] = None
foundry_outputs: Optional[bool] = None
nft_outputs: Optional[bool] = None
delegation_outputs: Optional[bool] = None


@json
Expand All @@ -47,13 +51,15 @@ class NftSyncOptions:
Attributes:
basic_outputs: Whether to sync basic outputs.
nft_outputs: Whether to sync NFT outputs.
account_outputs: Whether to sync account outputs.
nft_outputs: Whether to sync NFT outputs.
delegation_outputs: Whether to sync delegation outputs.
"""

basic_outputs: Optional[bool] = None
nft_outputs: Optional[bool] = None
account_outputs: Optional[bool] = None
nft_outputs: Optional[bool] = None
delegation_outputs: Optional[bool] = None


@json
Expand Down
8 changes: 0 additions & 8 deletions bindings/python/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,6 @@ impl From<std::io::Error> for Error {
}
}

impl From<iota_sdk_bindings_core::iota_sdk::types::block::Error> for Error {
fn from(err: iota_sdk_bindings_core::iota_sdk::types::block::Error) -> Self {
Self {
error: PyErr::new::<exceptions::PyValueError, _>(err.to_string()),
}
}
}

impl From<iota_sdk_bindings_core::Error> for Error {
fn from(err: iota_sdk_bindings_core::Error) -> Self {
Self {
Expand Down
13 changes: 5 additions & 8 deletions bindings/python/tests/test_api_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from typing import Generic, TypeVar
from json import load, loads, dumps
from iota_sdk import RoutesResponse, CongestionResponse, ManaRewardsResponse, ValidatorResponse, CommitteeResponse, IssuanceBlockHeaderResponse, Block, BlockMetadataResponse, BlockWithMetadataResponse, OutputMetadata, OutputResponse, TransactionMetadataResponse, SlotCommitment, UtxoChangesResponse, UtxoChangesFullResponse
from iota_sdk import RoutesResponse, CongestionResponse, OutputWithMetadataResponse, ManaRewardsResponse, ValidatorsResponse, ValidatorResponse, InfoResponse, CommitteeResponse, IssuanceBlockHeaderResponse, Block, BlockMetadataResponse, BlockWithMetadataResponse, OutputMetadata, OutputResponse, TransactionMetadataResponse, SlotCommitment, UtxoChangesResponse, UtxoChangesFullResponse


base_path = '../../sdk/tests/types/api/fixtures/'
Expand All @@ -27,16 +27,14 @@ def test_api_response(cls_type: Generic[T], path: str):
# GET /api/routes
test_api_response(RoutesResponse, "get-routes-response-example.json")
# GET /api/core/v3/info
# TODO: enable when the fixture is updated https://github.com/iotaledger/iota-sdk/issues/2015
# test_api_response(InfoResponse, "get-info-response-example.json")
test_api_response(InfoResponse, "get-info-response-example.json")
# GET /api/core/v3/accounts/{bech32Address}/congestion
test_api_response(CongestionResponse,
"get-congestion-estimate-response-example.json")
# GET /api/core/v3/rewards/{outputId}
test_api_response(ManaRewardsResponse, "get-mana-rewards-example.json")
# GET /api/core/v3/validators
# TODO: enable when TIP is updated
# test_api_response(ValidatorsResponse, "get-validators-example.json")
test_api_response(ValidatorsResponse, "get-validators-example.json")
# GET /api/core/v3/validators/{bech32Address}
test_api_response(ValidatorResponse, "get-validator-example.json")
# GET /api/core/v3/committee
Expand Down Expand Up @@ -73,9 +71,8 @@ def test_api_response(cls_type: Generic[T], path: str):
test_api_response(
OutputMetadata, "get-output-metadata-by-id-response-spent-example.json")
# GET /api/core/v3/outputs/{outputId}/full
# TODO: enable when OutputWithMetadata is updated with OutputIdProof https://github.com/iotaledger/iota-sdk/issues/2021
# test_api_response(OutputWithMetadata,
# "get-full-output-metadata-example.json")
test_api_response(OutputWithMetadataResponse,
"get-full-output-metadata-example.json")
# GET /api/core/v3/transactions/{transactionId}/metadata
test_api_response(TransactionMetadataResponse,
"get-transaction-metadata-by-id-response-example.json")
Expand Down
1 change: 1 addition & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ dialoguer = { version = "0.11.0", default-features = false, features = [
"password",
] }
dotenvy = { version = "0.15.7", default-features = false }
eyre = { version = "0.6.12", default-features = false }
fern-logger = { version = "0.5.0", default-features = false }
log = { version = "0.4.20", default-features = false }
prefix-hex = { version = "0.7.1", default-features = false, features = ["std"] }
Expand Down
Loading

0 comments on commit 7f82ec2

Please sign in to comment.