diff --git a/Cargo.lock b/Cargo.lock index 4a54088324..3fbdda532d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3241,6 +3241,7 @@ dependencies = [ "tari_core", "tari_crypto", "tari_features", + "tari_max_size", "tari_script", "tari_utilities", "thiserror", @@ -3337,6 +3338,7 @@ dependencies = [ "tari_hashing", "tari_key_manager", "tari_libtor", + "tari_max_size", "tari_p2p", "tari_script", "tari_shutdown", @@ -3413,6 +3415,7 @@ dependencies = [ "tari_core", "tari_features", "tari_key_manager", + "tari_max_size", "tari_utilities", "thiserror", "tokio", @@ -3451,6 +3454,7 @@ dependencies = [ "tari_comms", "tari_core", "tari_crypto", + "tari_max_size", "tari_utilities", "thiserror", "tokio", @@ -3570,6 +3574,7 @@ dependencies = [ "tari_core", "tari_crypto", "tari_key_manager", + "tari_max_size", "tari_p2p", "tari_script", "tari_service_framework", @@ -5968,6 +5973,7 @@ dependencies = [ "tari_comms", "tari_comms_dht", "tari_contacts", + "tari_max_size", "tari_p2p", "tari_service_framework", "tari_shutdown", @@ -6168,6 +6174,7 @@ dependencies = [ "tari_comms", "tari_comms_dht", "tari_crypto", + "tari_max_size", "tari_p2p", "tari_service_framework", "tari_shutdown", @@ -6237,6 +6244,7 @@ dependencies = [ "tari_features", "tari_hashing", "tari_key_manager", + "tari_max_size", "tari_metrics", "tari_mmr", "tari_p2p", @@ -6389,6 +6397,16 @@ dependencies = [ "tor-hash-passwd", ] +[[package]] +name = "tari_max_size" +version = "1.3.0-pre.0" +dependencies = [ + "borsh", + "serde", + "tari_utilities", + "thiserror", +] + [[package]] name = "tari_metrics" version = "1.3.0-pre.0" @@ -6471,6 +6489,7 @@ dependencies = [ "sha2 0.10.8", "sha3", "tari_crypto", + "tari_max_size", "tari_utilities", "thiserror", ] diff --git a/applications/minotari_app_grpc/Cargo.toml b/applications/minotari_app_grpc/Cargo.toml index 50bd5b911e..0cd922adab 100644 --- a/applications/minotari_app_grpc/Cargo.toml +++ b/applications/minotari_app_grpc/Cargo.toml @@ -13,6 +13,7 @@ tari_comms = { path = "../../comms/core" } tari_core = { path = "../../base_layer/core" } tari_crypto = { version = "0.20.3" } tari_script = { path = "../../infrastructure/tari_script" } +tari_max_size = { path = "../../infrastructure/max_size" } tari_utilities = { version = "0.7" } argon2 = { version = "0.4.1", features = ["std", "password-hash"] } diff --git a/applications/minotari_app_grpc/src/conversions/sidechain_feature.rs b/applications/minotari_app_grpc/src/conversions/sidechain_feature.rs index a542b73477..13a2ec87f9 100644 --- a/applications/minotari_app_grpc/src/conversions/sidechain_feature.rs +++ b/applications/minotari_app_grpc/src/conversions/sidechain_feature.rs @@ -22,10 +22,7 @@ use std::convert::{TryFrom, TryInto}; -use tari_common_types::{ - types::{PublicKey, Signature}, - MaxSizeString, -}; +use tari_common_types::types::{PublicKey, Signature}; use tari_core::transactions::transaction_components::{ BuildInfo, CodeTemplateRegistration, @@ -35,6 +32,7 @@ use tari_core::transactions::transaction_components::{ ValidatorNodeRegistration, ValidatorNodeSignature, }; +use tari_max_size::MaxSizeString; use tari_utilities::ByteArray; use crate::tari_rpc as grpc; diff --git a/applications/minotari_console_wallet/Cargo.toml b/applications/minotari_console_wallet/Cargo.toml index 9722fb792f..d168f85a84 100644 --- a/applications/minotari_console_wallet/Cargo.toml +++ b/applications/minotari_console_wallet/Cargo.toml @@ -17,6 +17,7 @@ tari_contacts = { path = "../../base_layer/contacts" } tari_crypto = { version = "0.20.3" } tari_key_manager = { path = "../../base_layer/key_manager" } tari_libtor = { path = "../../infrastructure/libtor", optional = true } +tari_max_size = { path = "../../infrastructure/max_size" } tari_p2p = { path = "../../base_layer/p2p", features = ["auto-update"] } tari_script = { path = "../../infrastructure/tari_script" } tari_shutdown = { path = "../../infrastructure/shutdown" } diff --git a/applications/minotari_console_wallet/src/automation/commands.rs b/applications/minotari_console_wallet/src/automation/commands.rs index 94d8385299..60a552e953 100644 --- a/applications/minotari_console_wallet/src/automation/commands.rs +++ b/applications/minotari_console_wallet/src/automation/commands.rs @@ -1205,7 +1205,7 @@ pub async fn command_runner( &TransactionOutputVersion::get_current_version(), &script!(PushPubKey(Box::new( session_info.recipient_address.public_spend_key().clone() - ))), + )))?, &leader_info.output_features, &leader_info.sender_offset_pubkey, &leader_info.metadata_signature_ephemeral_commitment, diff --git a/applications/minotari_console_wallet/src/automation/error.rs b/applications/minotari_console_wallet/src/automation/error.rs index ceda7bf287..c2405a42a6 100644 --- a/applications/minotari_console_wallet/src/automation/error.rs +++ b/applications/minotari_console_wallet/src/automation/error.rs @@ -37,6 +37,7 @@ use tari_common_types::types::FixedHashSizeError; use tari_core::transactions::{tari_amount::MicroMinotariError, transaction_components::TransactionError}; use tari_crypto::signatures::SchnorrSignatureError; use tari_key_manager::key_manager_service::KeyManagerServiceError; +use tari_script::ScriptError; use tari_utilities::{hex::HexError, ByteArrayError}; use thiserror::Error; use tokio::task::JoinError; @@ -92,6 +93,8 @@ pub enum CommandError { GrpcTlsError(#[from] GrpcTlsError), #[error("Invalid signature: `{0}`")] FailedSignature(#[from] SchnorrSignatureError), + #[error("Tari script error: {0}")] + ScriptError(#[from] ScriptError), } impl From for CommandError { diff --git a/applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs b/applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs index a39ee4cbd0..7c4909b74f 100644 --- a/applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs +++ b/applications/minotari_console_wallet/src/grpc/wallet_grpc_server.rs @@ -976,7 +976,7 @@ impl wallet_server::Wallet for WalletGrpcServer { .await .map_err(|e| Status::internal(e.to_string()))?; - output = output.with_script(script![Nop]); + output = output.with_script(script![Nop].map_err(|e| Status::invalid_argument(e.to_string()))?); let (tx_id, transaction) = output_manager .create_send_to_self_with_output(vec![output], fee_per_gram.into(), UtxoSelectionCriteria::default()) diff --git a/applications/minotari_console_wallet/src/ui/state/tasks.rs b/applications/minotari_console_wallet/src/ui/state/tasks.rs index 57d056ddcc..b0fb66f47f 100644 --- a/applications/minotari_console_wallet/src/ui/state/tasks.rs +++ b/applications/minotari_console_wallet/src/ui/state/tasks.rs @@ -34,8 +34,6 @@ use rand::{random, rngs::OsRng}; use tari_common_types::{ tari_address::TariAddress, types::{PublicKey, Signature}, - MaxSizeBytes, - MaxSizeString, }; use tari_core::{ consensus::DomainSeparatedConsensusHasher, @@ -47,6 +45,7 @@ use tari_core::{ use tari_crypto::{keys::PublicKey as PublicKeyTrait, ristretto::RistrettoPublicKey}; use tari_hashing::TransactionHashDomain; use tari_key_manager::key_manager::KeyManager; +use tari_max_size::{MaxSizeBytes, MaxSizeString}; use tari_utilities::{hex::Hex, ByteArray}; use tokio::sync::{broadcast, watch}; diff --git a/applications/minotari_ledger_wallet/comms/src/lib.rs b/applications/minotari_ledger_wallet/comms/src/lib.rs index c5c7ec02fa..5968c408d3 100644 --- a/applications/minotari_ledger_wallet/comms/src/lib.rs +++ b/applications/minotari_ledger_wallet/comms/src/lib.rs @@ -59,15 +59,15 @@ mod test { fn test_push_pub_key_serialized_byte_representation() { let mut scripts = Vec::new(); - scripts.push((script!(Nop), NOP_IDENTIFIER, "".to_string())); - scripts.push((script!(PushOne), PUSH_ONE_IDENTIFIER, "".to_string())); + scripts.push((script!(Nop).unwrap(), NOP_IDENTIFIER, "".to_string())); + scripts.push((script!(PushOne).unwrap(), PUSH_ONE_IDENTIFIER, "".to_string())); for pub_key in [ RistrettoPublicKey::default(), RistrettoPublicKey::from_secret_key(&RistrettoSecretKey::random(&mut OsRng)), ] { scripts.push(( - script!(PushPubKey(Box::new(pub_key.clone()))), + script!(PushPubKey(Box::new(pub_key.clone()))).unwrap(), PUSH_PUBKEY_IDENTIFIER, pub_key.to_hex(), )); @@ -75,7 +75,11 @@ mod test { let key = RistrettoSecretKey::random(&mut OsRng); let msg = slice_to_boxed_message(key.as_bytes()); - scripts.push((script!(CheckSigVerify(msg)), CHECK_SIG_VERIFY_IDENTIFIER, key.to_hex())); + scripts.push(( + script!(CheckSigVerify(msg)).unwrap(), + CHECK_SIG_VERIFY_IDENTIFIER, + key.to_hex(), + )); for (script, hex_identifier, hex_payload) in scripts { let mut serialized = Vec::new(); diff --git a/applications/minotari_merge_mining_proxy/Cargo.toml b/applications/minotari_merge_mining_proxy/Cargo.toml index b3f9b2996d..a669847631 100644 --- a/applications/minotari_merge_mining_proxy/Cargo.toml +++ b/applications/minotari_merge_mining_proxy/Cargo.toml @@ -20,6 +20,7 @@ tari_common_types = { path = "../../base_layer/common_types" } tari_comms = { path = "../../comms/core" } tari_core = { path = "../../base_layer/core", default-features = false, features = ["transactions"] } tari_key_manager = { path = "../../base_layer/key_manager", features = ["key_manager_service"] } +tari_max_size = { path = "../../infrastructure/max_size" } tari_utilities = { version = "0.7" } anyhow = "1.0.53" diff --git a/applications/minotari_merge_mining_proxy/src/block_template_protocol.rs b/applications/minotari_merge_mining_proxy/src/block_template_protocol.rs index 07c1c7526b..291a4adbdb 100644 --- a/applications/minotari_merge_mining_proxy/src/block_template_protocol.rs +++ b/applications/minotari_merge_mining_proxy/src/block_template_protocol.rs @@ -26,7 +26,7 @@ use std::{cmp, convert::TryFrom, sync::Arc}; use log::*; use minotari_app_utilities::parse_miner_input::BaseNodeGrpcClient; use minotari_node_grpc_client::grpc; -use tari_common_types::{tari_address::TariAddress, types::FixedHash, MaxSizeBytes}; +use tari_common_types::{tari_address::TariAddress, types::FixedHash}; use tari_core::{ consensus::ConsensusManager, proof_of_work::{monero_rx, monero_rx::FixedByteArray, Difficulty}, @@ -37,6 +37,7 @@ use tari_core::{ }, AuxChainHashes, }; +use tari_max_size::MaxSizeBytes; use tari_utilities::{hex::Hex, ByteArray}; use crate::{ diff --git a/applications/minotari_merge_mining_proxy/src/error.rs b/applications/minotari_merge_mining_proxy/src/error.rs index f17df27032..4aab962b3a 100644 --- a/applications/minotari_merge_mining_proxy/src/error.rs +++ b/applications/minotari_merge_mining_proxy/src/error.rs @@ -29,13 +29,13 @@ use hyper::header::InvalidHeaderValue; use minotari_app_utilities::parse_miner_input::ParseInputError; use minotari_wallet_grpc_client::BasicAuthError; use tari_common::{ConfigError, ConfigurationError}; -use tari_common_types::{MaxSizeBytesError, MaxSizeVecError}; use tari_core::{ consensus::ConsensusBuilderError, proof_of_work::{monero_rx::MergeMineError, DifficultyError}, transactions::{key_manager::CoreKeyManagerError, CoinbaseBuildError}, }; use tari_key_manager::key_manager_service::KeyManagerServiceError; +use tari_max_size::{MaxSizeBytesError, MaxSizeVecError}; use thiserror::Error; use tonic::{codegen::http::uri::InvalidUri, transport}; diff --git a/applications/minotari_miner/Cargo.toml b/applications/minotari_miner/Cargo.toml index b0ea3cb37c..fd5fe89aff 100644 --- a/applications/minotari_miner/Cargo.toml +++ b/applications/minotari_miner/Cargo.toml @@ -12,6 +12,7 @@ tari_core = { path = "../../base_layer/core", default-features = false } tari_common = { path = "../../common" } tari_common_types = { path = "../../base_layer/common_types" } tari_comms = { path = "../../comms/core" } +tari_max_size = { path = "../../infrastructure/max_size" } minotari_app_utilities = { path = "../minotari_app_utilities", features = ["miner_input"] } minotari_app_grpc = { path = "../minotari_app_grpc" } tari_crypto = { version = "0.20.3" } diff --git a/applications/minotari_miner/src/errors.rs b/applications/minotari_miner/src/errors.rs index 3485d15d41..f2342f7a88 100644 --- a/applications/minotari_miner/src/errors.rs +++ b/applications/minotari_miner/src/errors.rs @@ -21,7 +21,7 @@ // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use minotari_app_grpc::authentication::BasicAuthError; use minotari_app_utilities::parse_miner_input::ParseInputError; -use tari_common_types::MaxSizeBytesError; +use tari_max_size::MaxSizeBytesError; use thiserror::Error; use tonic::codegen::http::uri::InvalidUri; diff --git a/applications/minotari_miner/src/stratum/error.rs b/applications/minotari_miner/src/stratum/error.rs index 846aab9833..29f1ac324f 100644 --- a/applications/minotari_miner/src/stratum/error.rs +++ b/applications/minotari_miner/src/stratum/error.rs @@ -20,7 +20,7 @@ // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -use tari_common_types::MaxSizeBytesError; +use tari_max_size::MaxSizeBytesError; use thiserror::Error; #[allow(clippy::enum_variant_names)] diff --git a/applications/minotari_miner/src/stratum/stratum_controller/controller.rs b/applications/minotari_miner/src/stratum/stratum_controller/controller.rs index 2cadf176c2..b19027ef63 100644 --- a/applications/minotari_miner/src/stratum/stratum_controller/controller.rs +++ b/applications/minotari_miner/src/stratum/stratum_controller/controller.rs @@ -25,7 +25,7 @@ use borsh::BorshDeserialize; use futures::stream::StreamExt; use log::*; use minotari_app_grpc::tari_rpc::BlockHeader; -use tari_common_types::MaxSizeBytes; +use tari_max_size::MaxSizeBytes; use tari_utilities::{hex::Hex, ByteArray}; use crate::{ diff --git a/base_layer/common_types/src/lib.rs b/base_layer/common_types/src/lib.rs index d10280e82d..b0d6c50ca1 100644 --- a/base_layer/common_types/src/lib.rs +++ b/base_layer/common_types/src/lib.rs @@ -31,18 +31,9 @@ pub mod encryption; pub mod epoch; pub mod grpc_authentication; pub mod key_branches; -mod max_size; pub mod serializers; pub mod tari_address; pub mod transaction; mod tx_id; pub mod types; pub mod wallet_types; -pub use max_size::{ - MaxSizeBytes, - MaxSizeBytesError, - MaxSizeString, - MaxSizeStringLengthError, - MaxSizeVec, - MaxSizeVecError, -}; diff --git a/base_layer/contacts/Cargo.toml b/base_layer/contacts/Cargo.toml index 16b2607367..b4275b0d57 100644 --- a/base_layer/contacts/Cargo.toml +++ b/base_layer/contacts/Cargo.toml @@ -13,6 +13,7 @@ tari_common_types = { path = "../../base_layer/common_types", version = "1.3.0-p tari_comms = { path = "../../comms/core", version = "1.3.0-pre.0" } tari_comms_dht = { path = "../../comms/dht", version = "1.3.0-pre.0" } tari_crypto = { version = "0.20.3" } +tari_max_size = { path = "../../infrastructure/max_size" } tari_p2p = { path = "../p2p", features = ["auto-update"], version = "1.3.0-pre.0" } tari_service_framework = { path = "../service_framework", version = "1.3.0-pre.0" } tari_shutdown = { path = "../../infrastructure/shutdown", version = "1.3.0-pre.0" } diff --git a/base_layer/contacts/src/chat_client/Cargo.toml b/base_layer/contacts/src/chat_client/Cargo.toml index d5c9e08e80..2ff1fbb779 100644 --- a/base_layer/contacts/src/chat_client/Cargo.toml +++ b/base_layer/contacts/src/chat_client/Cargo.toml @@ -15,6 +15,7 @@ tari_common_types = { path = "../../../common_types" } tari_comms = { path = "../../../../comms/core" } tari_comms_dht = { path = "../../../../comms/dht" } tari_contacts = { path = "../../../contacts" } +tari_max_size = { path = "../../../../infrastructure/max_size" } tari_p2p = { path = "../../../p2p" } tari_service_framework= { path = "../../../service_framework" } tari_shutdown = { path = "../../../../infrastructure/shutdown" } diff --git a/base_layer/contacts/src/chat_client/src/error.rs b/base_layer/contacts/src/chat_client/src/error.rs index c5eda9635a..80adf0f0c4 100644 --- a/base_layer/contacts/src/chat_client/src/error.rs +++ b/base_layer/contacts/src/chat_client/src/error.rs @@ -25,9 +25,9 @@ use std::io; use diesel::ConnectionError; use minotari_app_utilities::identity_management::IdentityError; use tari_common_sqlite::error::StorageError as SqliteStorageError; -use tari_common_types::MaxSizeBytesError; use tari_comms::peer_manager::PeerManagerError; use tari_contacts::contacts_service::error::ContactsServiceError; +use tari_max_size::MaxSizeBytesError; use tari_p2p::initialization::CommsInitializationError; use tari_storage::lmdb_store::LMDBError; diff --git a/base_layer/contacts/src/contacts_service/error.rs b/base_layer/contacts/src/contacts_service/error.rs index 74c5f22622..332d8a055c 100644 --- a/base_layer/contacts/src/contacts_service/error.rs +++ b/base_layer/contacts/src/contacts_service/error.rs @@ -22,9 +22,9 @@ use diesel::result::Error as DieselError; use tari_common_sqlite::error::SqliteStorageError; -use tari_common_types::MaxSizeBytesError; use tari_comms::connectivity::ConnectivityError; use tari_comms_dht::outbound::DhtOutboundError; +use tari_max_size::MaxSizeBytesError; use tari_p2p::services::liveness::error::LivenessError; use tari_service_framework::reply_channel::TransportChannelError; use thiserror::Error; diff --git a/base_layer/contacts/src/contacts_service/types/confirmation.rs b/base_layer/contacts/src/contacts_service/types/confirmation.rs index 27af40c236..faf992d1f0 100644 --- a/base_layer/contacts/src/contacts_service/types/confirmation.rs +++ b/base_layer/contacts/src/contacts_service/types/confirmation.rs @@ -22,7 +22,7 @@ use std::{convert::TryFrom, fmt::Display}; -use tari_common_types::MaxSizeBytes; +use tari_max_size::MaxSizeBytes; use tari_utilities::ByteArray; use crate::contacts_service::{error::ContactsServiceError, proto, types::MessageId}; diff --git a/base_layer/contacts/src/contacts_service/types/message.rs b/base_layer/contacts/src/contacts_service/types/message.rs index 99ba644483..2d500337e3 100644 --- a/base_layer/contacts/src/contacts_service/types/message.rs +++ b/base_layer/contacts/src/contacts_service/types/message.rs @@ -25,8 +25,9 @@ use std::{convert::TryFrom, fmt::Display}; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use serde::{Deserialize, Serialize}; -use tari_common_types::{tari_address::TariAddress, MaxSizeBytes}; +use tari_common_types::tari_address::TariAddress; use tari_comms_dht::domain_message::OutboundDomainMessage; +use tari_max_size::MaxSizeBytes; use tari_p2p::tari_message::TariMessageType; use tari_utilities::ByteArray; diff --git a/base_layer/core/Cargo.toml b/base_layer/core/Cargo.toml index e516dbcc9a..b856f9f607 100644 --- a/base_layer/core/Cargo.toml +++ b/base_layer/core/Cargo.toml @@ -36,6 +36,7 @@ tari_comms = { path = "../../comms/core", version = "1.3.0-pre.0" } tari_comms_dht = { path = "../../comms/dht", version = "1.3.0-pre.0" } tari_comms_rpc_macros = { path = "../../comms/rpc_macros", version = "1.3.0-pre.0" } tari_crypto = { version = "0.20.3", features = ["borsh"] } +tari_max_size = { path = "../../infrastructure/max_size" } tari_metrics = { path = "../../infrastructure/metrics", optional = true, version = "1.3.0-pre.0" } tari_mmr = { path = "../../base_layer/mmr", optional = true, version = "1.3.0-pre.0" } tari_p2p = { path = "../../base_layer/p2p", version = "1.3.0-pre.0" } diff --git a/base_layer/core/src/blocks/pre_mine/mod.rs b/base_layer/core/src/blocks/pre_mine/mod.rs index c3d16e2d5b..de52d00aa9 100644 --- a/base_layer/core/src/blocks/pre_mine/mod.rs +++ b/base_layer/core/src/blocks/pre_mine/mod.rs @@ -378,7 +378,7 @@ pub async fn create_pre_mine_genesis_block_info( Else PushPubKey(Box::new(backup_key.clone())) EndIf - ); + ).map_err(|e| e.to_string())?; let output = WalletOutputBuilder::new(item.value, commitment_mask.key_id) .with_features(OutputFeatures::new( OutputFeaturesVersion::get_current_version(), diff --git a/base_layer/core/src/common/mod.rs b/base_layer/core/src/common/mod.rs index 29e9054fbb..f6bcc40c94 100644 --- a/base_layer/core/src/common/mod.rs +++ b/base_layer/core/src/common/mod.rs @@ -22,9 +22,9 @@ use blake2::Blake2b; use digest::consts::U64; -#[cfg(feature = "base_node")] -use tari_common_types::MaxSizeVec; use tari_hashing::ConfidentialOutputHashDomain; +#[cfg(feature = "base_node")] +use tari_max_size::MaxSizeVec; use crate::consensus::DomainSeparatedConsensusHasher; diff --git a/base_layer/core/src/consensus/consensus_constants.rs b/base_layer/core/src/consensus/consensus_constants.rs index f6b48112f5..335a692222 100644 --- a/base_layer/core/src/consensus/consensus_constants.rs +++ b/base_layer/core/src/consensus/consensus_constants.rs @@ -242,7 +242,9 @@ impl ConsensusConstants { let max_extra_size = self.coinbase_output_features_extra_max_length() as usize; let features_and_scripts_size = self.transaction_weight.round_up_features_and_scripts_size( - output_features.get_serialized_size()? + max_extra_size + script![Nop].get_serialized_size()?, + output_features.get_serialized_size()? + + max_extra_size + + script![Nop].map_err(|e| e.to_std_io_error())?.get_serialized_size()?, ); Ok(self.transaction_weight.calculate(1, 0, 1, features_and_scripts_size)) } diff --git a/base_layer/core/src/consensus/consensus_encoding/hashing.rs b/base_layer/core/src/consensus/consensus_encoding/hashing.rs index 93abebc848..f0606e9450 100644 --- a/base_layer/core/src/consensus/consensus_encoding/hashing.rs +++ b/base_layer/core/src/consensus/consensus_encoding/hashing.rs @@ -120,7 +120,7 @@ mod tests { let network = Network::get_current_or_user_setting_or_default(); // Script is chosen because the consensus encoding impl for TariScript has 2 writes - let test_subject = script!(Nop); + let test_subject = script!(Nop).unwrap(); let mut hasher = Blake2b::::default(); TestHashDomain::add_domain_separation_tag(&mut hasher, &format!("{}.n{}", "foo", network.as_byte())); diff --git a/base_layer/core/src/covenants/arguments.rs b/base_layer/core/src/covenants/arguments.rs index 95e3dc2cfd..faa895fe15 100644 --- a/base_layer/core/src/covenants/arguments.rs +++ b/base_layer/core/src/covenants/arguments.rs @@ -27,10 +27,8 @@ use std::{ use borsh::{BorshDeserialize, BorshSerialize}; use integer_encoding::VarIntWriter; -use tari_common_types::{ - types::{Commitment, FixedHash, PublicKey}, - MaxSizeBytes, -}; +use tari_common_types::types::{Commitment, FixedHash, PublicKey}; +use tari_max_size::MaxSizeBytes; use tari_script::TariScript; use tari_utilities::{hex::Hex, ByteArray}; @@ -316,7 +314,11 @@ mod test { CovenantArg::Hash(FixedHash::zero()), &from_hex("010000000000000000000000000000000000000000000000000000000000000000").unwrap(), ); - test_case(CovenantArg::TariScript(script!(Nop)), &[ARG_TARI_SCRIPT, 0x01, 0x73]); + test_case(CovenantArg::TariScript(script!(Nop).unwrap()), &[ + ARG_TARI_SCRIPT, + 0x01, + 0x73, + ]); test_case(CovenantArg::OutputField(OutputField::Covenant), &[ ARG_OUTPUT_FIELD, FIELD_COVENANT, diff --git a/base_layer/core/src/covenants/fields.rs b/base_layer/core/src/covenants/fields.rs index 84ec22028a..a00a5fe4ef 100644 --- a/base_layer/core/src/covenants/fields.rs +++ b/base_layer/core/src/covenants/fields.rs @@ -410,7 +410,7 @@ mod test { sidechain_feature: Some(side_chain_features), ..Default::default() }, - script: script![Drop Nop], + script: script![Drop Nop].unwrap(), ..Default::default() }, &key_manager, @@ -455,7 +455,7 @@ mod test { output_type: OutputType::Burn, ..Default::default() }, - script: script![Drop Nop], + script: script![Drop Nop].unwrap(), minimum_value_promise: MicroMinotari(123456), value: MicroMinotari(123456), ..Default::default() @@ -466,7 +466,7 @@ mod test { .remove(0); assert!(!OutputField::Commitment.is_eq(&output, &Commitment::default()).unwrap()); - assert!(!OutputField::Script.is_eq(&output, &script![Nop Drop]).unwrap()); + assert!(!OutputField::Script.is_eq(&output, &script![Nop Drop].unwrap()).unwrap()); assert!(!OutputField::SenderOffsetPublicKey .is_eq(&output, &PublicKey::default()) .unwrap()); @@ -503,7 +503,7 @@ mod test { maturity: 42, ..Default::default() }, - script: script![Drop Nop], + script: script![Drop Nop].unwrap(), ..Default::default() }, &key_manager, @@ -583,7 +583,7 @@ mod test { 1, UtxoTestParams { features, - script: script![Drop Nop], + script: script![Drop Nop].unwrap(), minimum_value_promise: MicroMinotari(123456), value: MicroMinotari(123456), ..Default::default() diff --git a/base_layer/core/src/covenants/filters/and.rs b/base_layer/core/src/covenants/filters/and.rs index 846cc8f56d..f06192ab8e 100644 --- a/base_layer/core/src/covenants/filters/and.rs +++ b/base_layer/core/src/covenants/filters/and.rs @@ -54,7 +54,7 @@ mod test { #[tokio::test] async fn it_filters_outputset_using_intersection() { let key_manager = create_memory_db_key_manager().unwrap(); - let script = script!(CheckHeight(101)); + let script = script!(CheckHeight(101)).unwrap(); let covenant = covenant!(and(field_eq(@field::features_maturity, @uint(42),), field_eq(@field::script, @script(script.clone())))); let input = create_input(&key_manager).await; let (mut context, outputs) = setup_filter_test( @@ -64,7 +64,7 @@ mod test { |outputs| { // output satisfying maturity only outputs[2].features.maturity = 42; - outputs[2].script = script!(CheckHeight(102)); + outputs[2].script = script!(CheckHeight(102)).unwrap(); // output satisfying maturity and script outputs[5].features.maturity = 42; outputs[5].script = script.clone(); diff --git a/base_layer/core/src/covenants/filters/field_eq.rs b/base_layer/core/src/covenants/filters/field_eq.rs index 7824d4bc31..04eb94e3d7 100644 --- a/base_layer/core/src/covenants/filters/field_eq.rs +++ b/base_layer/core/src/covenants/filters/field_eq.rs @@ -152,7 +152,7 @@ mod test { #[tokio::test] async fn it_filters_tari_script() { let key_manager = create_memory_db_key_manager().unwrap(); - let script = script!(CheckHeight(100)); + let script = script!(CheckHeight(100)).unwrap(); let covenant = covenant!(field_eq( @field::script, @script(script.clone()) diff --git a/base_layer/core/src/covenants/filters/not.rs b/base_layer/core/src/covenants/filters/not.rs index 9f1d5017d5..b1fd99b61c 100644 --- a/base_layer/core/src/covenants/filters/not.rs +++ b/base_layer/core/src/covenants/filters/not.rs @@ -51,7 +51,7 @@ mod test { #[tokio::test] async fn it_filters_compliment_of_filter() { let key_manager = create_memory_db_key_manager().unwrap(); - let script = script!(CheckHeight(100)); + let script = script!(CheckHeight(100)).unwrap(); let covenant = covenant!(not(or(field_eq(@field::features_maturity, @uint(42),), field_eq(@field::script, @script(script.clone()))))); let input = create_input(&key_manager).await; let (mut context, outputs) = setup_filter_test( diff --git a/base_layer/core/src/covenants/filters/or.rs b/base_layer/core/src/covenants/filters/or.rs index 6849b2c0b0..000fdc9e4f 100644 --- a/base_layer/core/src/covenants/filters/or.rs +++ b/base_layer/core/src/covenants/filters/or.rs @@ -57,7 +57,7 @@ mod test { #[tokio::test] async fn it_filters_outputset_using_union() { let key_manager = create_memory_db_key_manager().unwrap(); - let script = script!(CheckHeight(100)); + let script = script!(CheckHeight(100)).unwrap(); let covenant = covenant!(or(field_eq(@field::features_maturity, @uint(42),), field_eq(@field::script, @script(script.clone())))); let input = create_input(&key_manager).await; let (mut context, outputs) = setup_filter_test( diff --git a/base_layer/core/src/covenants/filters/xor.rs b/base_layer/core/src/covenants/filters/xor.rs index 75d6ffc467..5a9e1e26ac 100644 --- a/base_layer/core/src/covenants/filters/xor.rs +++ b/base_layer/core/src/covenants/filters/xor.rs @@ -59,7 +59,7 @@ mod test { #[tokio::test] async fn it_filters_outputset_using_symmetric_difference() { let key_manager = create_memory_db_key_manager().unwrap(); - let script = script!(CheckHeight(100)); + let script = script!(CheckHeight(100)).unwrap(); let covenant = covenant!(and(field_eq(@field::features_maturity, @uint(42),), field_eq(@field::script, @script(script.clone())))); let input = create_input(&key_manager).await; let (mut context, outputs) = setup_filter_test( diff --git a/base_layer/core/src/covenants/macros.rs b/base_layer/core/src/covenants/macros.rs index 03faeb0bec..79ba9155e1 100644 --- a/base_layer/core/src/covenants/macros.rs +++ b/base_layer/core/src/covenants/macros.rs @@ -197,7 +197,7 @@ mod test { }; let dest_pk = PublicKey::from_hex("b0c1f788f137ba0cdc0b61e89ee43b80ebf5cca4136d3229561bf11eba347849").unwrap(); let sender_pk = dest_pk.clone(); - let script = script!(HashSha256 PushHash(Box::new(hash)) Equal IfThen PushPubKey(Box::new(dest_pk)) Else CheckHeightVerify(100) PushPubKey(Box::new(sender_pk)) EndIf); + let script = script!(HashSha256 PushHash(Box::new(hash)) Equal IfThen PushPubKey(Box::new(dest_pk)) Else CheckHeightVerify(100) PushPubKey(Box::new(sender_pk)) EndIf).unwrap(); let covenant = covenant!(field_eq(@field::script, @script(script.clone()))); let decoded = Covenant::from_bytes(&mut covenant.to_bytes().as_bytes()).unwrap(); diff --git a/base_layer/core/src/proof_of_work/proof_of_work.rs b/base_layer/core/src/proof_of_work/proof_of_work.rs index 7b07ea3c2a..446246dd19 100644 --- a/base_layer/core/src/proof_of_work/proof_of_work.rs +++ b/base_layer/core/src/proof_of_work/proof_of_work.rs @@ -25,7 +25,7 @@ use std::fmt::{Display, Error, Formatter}; use borsh::{BorshDeserialize, BorshSerialize}; use bytes::BufMut; use serde::{Deserialize, Serialize}; -use tari_common_types::MaxSizeBytes; +use tari_max_size::MaxSizeBytes; use tari_utilities::hex::Hex; use crate::proof_of_work::PowAlgorithm; diff --git a/base_layer/core/src/proto/sidechain_feature.rs b/base_layer/core/src/proto/sidechain_feature.rs index 997b851602..a0cc6f744f 100644 --- a/base_layer/core/src/proto/sidechain_feature.rs +++ b/base_layer/core/src/proto/sidechain_feature.rs @@ -24,10 +24,8 @@ use std::convert::{TryFrom, TryInto}; -use tari_common_types::{ - types::{PublicKey, Signature}, - MaxSizeString, -}; +use tari_common_types::types::{PublicKey, Signature}; +use tari_max_size::MaxSizeString; use tari_utilities::ByteArray; use crate::{ diff --git a/base_layer/core/src/transactions/test_helpers.rs b/base_layer/core/src/transactions/test_helpers.rs index 1ba4ccc333..e2ded3c714 100644 --- a/base_layer/core/src/transactions/test_helpers.rs +++ b/base_layer/core/src/transactions/test_helpers.rs @@ -203,7 +203,8 @@ impl TestParams { pub fn get_size_for_default_features_and_scripts(&self, num_outputs: usize) -> std::io::Result { let output_features = OutputFeatures { ..Default::default() }; Ok(self.fee().weighting().round_up_features_and_scripts_size( - script![Nop].get_serialized_size()? + output_features.get_serialized_size()?, + script![Nop].map_err(|e| e.to_std_io_error())?.get_serialized_size()? + + output_features.get_serialized_size()?, ) * num_outputs) } } @@ -232,7 +233,7 @@ impl Default for UtxoTestParams { fn default() -> Self { Self { value: 10.into(), - script: script![Nop], + script: script![Nop].unwrap(), features: OutputFeatures::default(), input_data: None, covenant: Covenant::default(), @@ -438,7 +439,7 @@ macro_rules! txn_schema { fee: $fee, lock_height: $lock, features: $features.clone(), - script: tari_script::script![Nop], + script: tari_script::script![Nop].unwrap(), covenant: Default::default(), input_data: None, input_version: $input_version.clone(), @@ -540,7 +541,7 @@ pub async fn create_tx( output_count, fee_per_gram, &output_features, - &script![Nop], + &script![Nop].unwrap(), &Default::default(), key_manager, ) @@ -717,7 +718,7 @@ pub async fn create_stx_protocol_internal( .with_lock_height(schema.lock_height) .with_fee_per_gram(schema.fee) .with_change_data( - script!(PushPubKey(Box::new(script_public_key))), + script!(PushPubKey(Box::new(script_public_key))).unwrap(), ExecutionStack::default(), change.script_key_id, change.commitment_mask_key_id, diff --git a/base_layer/core/src/transactions/transaction_components/encrypted_data.rs b/base_layer/core/src/transactions/transaction_components/encrypted_data.rs index 5ad5bef4c4..d986d8f3ee 100644 --- a/base_layer/core/src/transactions/transaction_components/encrypted_data.rs +++ b/base_layer/core/src/transactions/transaction_components/encrypted_data.rs @@ -47,10 +47,10 @@ use serde::{Deserialize, Serialize}; use tari_common_types::{ tari_address::{TariAddress, TARI_ADDRESS_INTERNAL_DUAL_SIZE, TARI_ADDRESS_INTERNAL_SINGLE_SIZE}, types::{Commitment, PrivateKey}, - MaxSizeBytes, }; use tari_crypto::{hashing::DomainSeparatedHasher, keys::SecretKey}; use tari_hashing::TransactionSecureNonceKdfDomain; +use tari_max_size::MaxSizeBytes; use tari_utilities::{ hex::{from_hex, to_hex, Hex, HexError}, safe_array::SafeArray, diff --git a/base_layer/core/src/transactions/transaction_components/output_features.rs b/base_layer/core/src/transactions/transaction_components/output_features.rs index ee774e2652..8eabe476e4 100644 --- a/base_layer/core/src/transactions/transaction_components/output_features.rs +++ b/base_layer/core/src/transactions/transaction_components/output_features.rs @@ -28,11 +28,8 @@ use std::{ use borsh::{BorshDeserialize, BorshSerialize}; use serde::{Deserialize, Serialize}; -use tari_common_types::{ - types::{PublicKey, Signature}, - MaxSizeBytes, - MaxSizeString, -}; +use tari_common_types::types::{PublicKey, Signature}; +use tari_max_size::{MaxSizeBytes, MaxSizeString}; use super::OutputFeaturesVersion; use crate::transactions::transaction_components::{ diff --git a/base_layer/core/src/transactions/transaction_components/side_chain/template_registration.rs b/base_layer/core/src/transactions/transaction_components/side_chain/template_registration.rs index 732ef46014..0fe680a55c 100644 --- a/base_layer/core/src/transactions/transaction_components/side_chain/template_registration.rs +++ b/base_layer/core/src/transactions/transaction_components/side_chain/template_registration.rs @@ -22,11 +22,8 @@ use borsh::{BorshDeserialize, BorshSerialize}; use serde::{Deserialize, Serialize}; -use tari_common_types::{ - types::{PublicKey, Signature}, - MaxSizeBytes, - MaxSizeString, -}; +use tari_common_types::types::{PublicKey, Signature}; +use tari_max_size::{MaxSizeBytes, MaxSizeString}; #[derive(Debug, Clone, Hash, PartialEq, Eq, Deserialize, Serialize, BorshSerialize, BorshDeserialize)] pub struct CodeTemplateRegistration { diff --git a/base_layer/core/src/transactions/transaction_components/test.rs b/base_layer/core/src/transactions/transaction_components/test.rs index 0bec358517..7e3d4f4cde 100644 --- a/base_layer/core/src/transactions/transaction_components/test.rs +++ b/base_layer/core/src/transactions/transaction_components/test.rs @@ -132,7 +132,7 @@ async fn range_proof_verification() { test_params_2.commitment_mask_key_id.clone(), ) .with_features(OutputFeatures::default()) - .with_script(script![Nop]) + .with_script(script![Nop].unwrap()) .encrypt_data_for_recovery(&key_manager, None, PaymentId::Empty) .await .unwrap() @@ -524,7 +524,7 @@ async fn inputs_not_malleable() { 2, 15.into(), &Default::default(), - &script![Nop], + &script![Nop].unwrap(), &Default::default(), &key_manager, ) @@ -538,7 +538,7 @@ async fn inputs_not_malleable() { .unwrap(); let mut inputs = tx.body().inputs().clone(); - inputs[0].set_script(script![Drop]).unwrap(); + inputs[0].set_script(script![Drop].unwrap()).unwrap(); inputs[0].input_data = stack; tx.body = AggregateBody::new(inputs, tx.body.outputs().clone(), tx.body().kernels().clone()); diff --git a/base_layer/core/src/transactions/transaction_components/wallet_output_builder.rs b/base_layer/core/src/transactions/transaction_components/wallet_output_builder.rs index 5a0622a2df..fff2dbcf37 100644 --- a/base_layer/core/src/transactions/transaction_components/wallet_output_builder.rs +++ b/base_layer/core/src/transactions/transaction_components/wallet_output_builder.rs @@ -361,7 +361,7 @@ mod test { let (commitment_mask_key, script_key_id) = key_manager.get_next_commitment_mask_and_script_key().await.unwrap(); let value = MicroMinotari(100); let kmob = WalletOutputBuilder::new(value, commitment_mask_key.key_id.clone()); - let kmob = kmob.with_script(TariScript::new(vec![])); + let kmob = kmob.with_script(TariScript::new(vec![]).unwrap()); assert!(kmob.clone().try_build(&key_manager).await.is_err()); let sender_offset = key_manager .get_next_key(TransactionKeyManagerBranch::SenderOffset.get_branch_key()) @@ -403,7 +403,7 @@ mod test { let (commitment_mask_key, script_key) = key_manager.get_next_commitment_mask_and_script_key().await.unwrap(); let value = MicroMinotari(100); let kmob = WalletOutputBuilder::new(value, commitment_mask_key.key_id.clone()); - let kmob = kmob.with_script(TariScript::new(vec![])); + let kmob = kmob.with_script(TariScript::new(vec![]).unwrap()); let sender_offset = key_manager .get_next_key(TransactionKeyManagerBranch::SenderOffset.get_branch_key()) .await diff --git a/base_layer/core/src/transactions/transaction_protocol/sender.rs b/base_layer/core/src/transactions/transaction_protocol/sender.rs index dc34b9b93b..808509d123 100644 --- a/base_layer/core/src/transactions/transaction_protocol/sender.rs +++ b/base_layer/core/src/transactions/transaction_protocol/sender.rs @@ -1119,7 +1119,7 @@ mod test { let bob_key = TestParams::new(&key_manager).await; let input = create_test_input(MicroMinotari(1200), 0, &key_manager, vec![]).await; let utxo = input.to_transaction_input(&key_manager).await.unwrap(); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let consensus_constants = create_consensus_constants(0); let mut builder = SenderTransactionProtocol::builder(consensus_constants.clone(), key_manager.clone()); let fee_per_gram = MicroMinotari(4); @@ -1230,7 +1230,7 @@ mod test { let input = create_test_input(MicroMinotari(25000), 0, &key_manager, vec![]).await; let consensus_constants = create_consensus_constants(0); let mut builder = SenderTransactionProtocol::builder(consensus_constants.clone(), key_manager.clone()); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let expected_fee = builder.fee().calculate( MicroMinotari(20), 1, @@ -1345,7 +1345,7 @@ mod test { let input3 = create_test_input(MicroMinotari(15000), 0, &key_manager, vec![]).await; let consensus_constants = create_consensus_constants(0); let mut builder = SenderTransactionProtocol::builder(consensus_constants.clone(), key_manager.clone()); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let change = TestParams::new(&key_manager).await; builder .with_lock_height(0) @@ -1450,7 +1450,7 @@ mod test { let key_manager = create_memory_db_key_manager().unwrap(); let (utxo_amount, fee_per_gram, amount) = (MicroMinotari(2500), MicroMinotari(10), MicroMinotari(500)); let input = create_test_input(utxo_amount, 0, &key_manager, vec![]).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); let mut builder = SenderTransactionProtocol::builder(create_consensus_constants(0), key_manager.clone()); let change = TestParams::new(&key_manager).await; builder @@ -1489,7 +1489,7 @@ mod test { let key_manager = create_memory_db_key_manager().unwrap(); let (utxo_amount, fee_per_gram, amount) = (MicroMinotari(2500), MicroMinotari(10), MicroMinotari(500)); let input = create_test_input(utxo_amount, 0, &key_manager, vec![]).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); let mut builder = SenderTransactionProtocol::builder(create_consensus_constants(0), key_manager.clone()); let change = TestParams::new(&key_manager).await; builder @@ -1532,7 +1532,7 @@ mod test { let bob_test_params = TestParams::new(&key_manager_bob).await; let alice_value = MicroMinotari(25000); let input = create_test_input(alice_value, 0, &key_manager_alice, vec![]).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); let consensus_constants = create_consensus_constants(0); let mut builder = SenderTransactionProtocol::builder(consensus_constants.clone(), key_manager_alice.clone()); @@ -1542,7 +1542,7 @@ mod test { .with_fee_per_gram(MicroMinotari(20)) .with_change_data( // "colour" this output so that we can find it later - script!(PushInt(1) Drop Nop), + script!(PushInt(1) Drop Nop).unwrap(), inputs!(change_params.script_key_pk), change_params.script_key_id.clone(), change_params.commitment_mask_key_id.clone(), diff --git a/base_layer/core/src/transactions/transaction_protocol/single_receiver.rs b/base_layer/core/src/transactions/transaction_protocol/single_receiver.rs index c5c5c4573b..4b45fa3b68 100644 --- a/base_layer/core/src/transactions/transaction_protocol/single_receiver.rs +++ b/base_layer/core/src/transactions/transaction_protocol/single_receiver.rs @@ -184,7 +184,7 @@ mod test { MicroMinotari(5000), test_params.commitment_mask_key_id, OutputFeatures::default(), - script!(Nop), + script!(Nop).unwrap(), ExecutionStack::default(), test_params.script_key_id, PublicKey::default(), @@ -225,7 +225,7 @@ mod test { MicroMinotari(5000), test_params.commitment_mask_key_id, OutputFeatures::default(), - script!(Nop), + script!(Nop).unwrap(), ExecutionStack::default(), test_params.script_key_id, PublicKey::default(), @@ -262,7 +262,7 @@ mod test { let m = TransactionMetadata::new(MicroMinotari(100), 0); let test_params = TestParams::new(&key_manager).await; let test_params2 = TestParams::new(&key_manager).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); let sender_offset_public_key = key_manager .get_public_key_at_key_id(&test_params.sender_offset_key_id) .await diff --git a/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs b/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs index dae717fb5f..9842f7d1d9 100644 --- a/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs +++ b/base_layer/core/src/transactions/transaction_protocol/transaction_initializer.rs @@ -634,7 +634,7 @@ mod test { // Start the builder let builder = SenderTransactionInitializer::new(&create_consensus_constants(0), key_manager.clone()); let err = builder.build().await.unwrap_err(); - let script = script!(Nop); + let script = script!(Nop).unwrap(); // We should have a bunch of fields missing still, but we can recover and continue assert_eq!(err.message, "Missing Lock Height,Missing Fee per gram"); @@ -681,7 +681,7 @@ mod test { let mut builder = err.builder; let change = TestParams::new(&key_manager).await; builder.with_change_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -721,7 +721,7 @@ mod test { ); let output = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &p, MicroMinotari(5000) - expected_fee, @@ -817,7 +817,7 @@ mod test { let p = TestParams::new(&key_manager).await; let output = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &p, MicroMinotari(500), @@ -856,7 +856,7 @@ mod test { .expect("Failed to borsh serialized size"), ); let input = create_test_input(500 * uT + tx_fee, 0, &key_manager, vec![]).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); // Start the builder let constants = create_consensus_constants(0); let mut builder = SenderTransactionInitializer::new(&constants, key_manager.clone()); @@ -867,7 +867,7 @@ mod test { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -894,7 +894,7 @@ mod test { let key_manager = create_memory_db_key_manager().unwrap(); let p = TestParams::new(&key_manager).await; let input = create_test_input(MicroMinotari(400), 0, &key_manager, vec![]).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); let output = create_wallet_output_with_data( script.clone(), OutputFeatures::default(), @@ -917,7 +917,7 @@ mod test { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -950,7 +950,7 @@ mod test { let input2 = create_test_input(MicroMinotari(3000), 0, &key_manager, vec![]).await; let fee_per_gram = MicroMinotari(6); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let constants = create_consensus_constants(0); let expected_fee = Fee::from(*constants.transaction_weight_params()).calculate( fee_per_gram, @@ -984,7 +984,7 @@ mod test { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), diff --git a/base_layer/core/src/validation/aggregate_body/aggregate_body_internal_validator.rs b/base_layer/core/src/validation/aggregate_body/aggregate_body_internal_validator.rs index b5e84ad8fd..0a9fd46ada 100644 --- a/base_layer/core/src/validation/aggregate_body/aggregate_body_internal_validator.rs +++ b/base_layer/core/src/validation/aggregate_body/aggregate_body_internal_validator.rs @@ -520,7 +520,7 @@ mod test { 100.into(), &key_manager, &OutputFeatures::create_burn_output(), - &script!(Nop), + &script!(Nop).unwrap(), &Covenant::default(), 0.into(), ) @@ -529,7 +529,7 @@ mod test { 101.into(), &key_manager, &OutputFeatures::create_burn_output(), - &script!(Nop), + &script!(Nop).unwrap(), &Covenant::default(), 0.into(), ) @@ -538,7 +538,7 @@ mod test { 102.into(), &key_manager, &OutputFeatures::create_burn_output(), - &script!(Nop), + &script!(Nop).unwrap(), &Covenant::default(), 0.into(), ) @@ -583,7 +583,7 @@ mod test { 100.into(), &key_manager, &OutputFeatures::create_burn_output(), - &script!(Nop), + &script!(Nop).unwrap(), &Covenant::default(), 0.into(), ) diff --git a/base_layer/core/src/validation/block_body/test.rs b/base_layer/core/src/validation/block_body/test.rs index f6d8d7b2e8..fede6a9984 100644 --- a/base_layer/core/src/validation/block_body/test.rs +++ b/base_layer/core/src/validation/block_body/test.rs @@ -407,7 +407,7 @@ async fn it_limits_the_script_byte_size() { let (_, coinbase_a) = blockchain.add_next_tip(block_spec!("A")).await.unwrap(); let mut schema1 = txn_schema!(from: vec![coinbase_a.clone()], to: vec![50 * T, 12 * T]); - schema1.script = script!(Nop Nop Nop); + schema1.script = script!(Nop Nop Nop).unwrap(); let (txs, _) = schema_to_transaction(&[schema1], &blockchain.km).await; let txs = txs.into_iter().map(|t| Arc::try_unwrap(t).unwrap()).collect::>(); let (block, _) = blockchain.create_next_tip(block_spec!("B", transactions: txs)).await; @@ -433,7 +433,7 @@ async fn it_limits_the_encrypted_data_byte_size() { let (_, coinbase_a) = blockchain.add_next_tip(block_spec!("A")).await.unwrap(); let mut schema1 = txn_schema!(from: vec![coinbase_a.clone()], to: vec![50 * T, 12 * T]); - schema1.script = script!(Nop Nop Nop); + schema1.script = script!(Nop Nop Nop).unwrap(); let (txs, _) = schema_to_transaction(&[schema1], &blockchain.km).await; let mut txs = txs.into_iter().map(|t| Arc::try_unwrap(t).unwrap()).collect::>(); let mut outputs = txs[0].body.outputs().clone(); diff --git a/base_layer/core/tests/chain_storage_tests/chain_backend.rs b/base_layer/core/tests/chain_storage_tests/chain_backend.rs index 590219de03..609d8ebc9a 100644 --- a/base_layer/core/tests/chain_storage_tests/chain_backend.rs +++ b/base_layer/core/tests/chain_storage_tests/chain_backend.rs @@ -126,7 +126,7 @@ fn test_utxo_order() { let mut utxos = Vec::with_capacity(2000); let version = TransactionOutputVersion::V0; let features = OutputFeatures::default(); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let proof = RangeProof::default(); let sig = ComAndPubSignature::default(); let covenant = Covenant::default(); diff --git a/base_layer/core/tests/helpers/block_builders.rs b/base_layer/core/tests/helpers/block_builders.rs index 655aef8f1d..3d31058a06 100644 --- a/base_layer/core/tests/helpers/block_builders.rs +++ b/base_layer/core/tests/helpers/block_builders.rs @@ -109,7 +109,7 @@ pub async fn create_coinbase( .unwrap(); let wallet_output = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::create_coinbase(maturity_height, extra, RangeProofType::BulletProofPlus), &p, value, @@ -238,7 +238,7 @@ pub async fn create_genesis_block_with_utxos( key_manager: &MemoryDbKeyManager, ) -> (ChainBlock, Vec) { let (mut template, coinbase) = genesis_template(100_000_000.into(), consensus_constants, key_manager).await; - let script = script!(Nop); + let script = script!(Nop).unwrap(); let output_features = OutputFeatures::default(); let mut outputs = Vec::new(); outputs.push(coinbase); diff --git a/base_layer/core/tests/tests/block_validation.rs b/base_layer/core/tests/tests/block_validation.rs index f36d1430c7..76ad5cd916 100644 --- a/base_layer/core/tests/tests/block_validation.rs +++ b/base_layer/core/tests/tests/block_validation.rs @@ -586,7 +586,7 @@ OutputFeatures::default()), // We dont need proper utxo's with signatures as the post_orphan validator does not check accounting balance + // signatures. let key_manager_utxo = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params1, outputs[1].value, @@ -595,7 +595,7 @@ OutputFeatures::default()), .await .unwrap(); let key_manager_utxo2 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params2, outputs[2].value, @@ -980,7 +980,7 @@ async fn test_block_sync_body_validator() { // We dont need proper utxo's with signatures as the post_orphan validator does not check accounting balance + // signatures. let unblinded_utxo = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params1, outputs[1].value, @@ -989,7 +989,7 @@ async fn test_block_sync_body_validator() { .await .unwrap(); let unblinded_utxo2 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params2, outputs[2].value, diff --git a/base_layer/core/tests/tests/mempool.rs b/base_layer/core/tests/tests/mempool.rs index 1532414fa5..023fa5faf2 100644 --- a/base_layer/core/tests/tests/mempool.rs +++ b/base_layer/core/tests/tests/mempool.rs @@ -1236,7 +1236,7 @@ async fn consensus_validation_large_tx() { amount_for_last_output }; let output = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params, output_amount, @@ -1398,7 +1398,7 @@ async fn validation_reject_min_fee() { let test_params = TestParams::new(&key_manager).await; let wallet_output = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params, input.value, @@ -1604,7 +1604,7 @@ async fn consensus_validation_versions() { fee: 25.into(), lock_height: 0, features: Default::default(), - script: script![Nop], + script: script![Nop].unwrap(), input_data: None, covenant: Default::default(), input_version: Some(TransactionInputVersion::V1), @@ -1621,7 +1621,7 @@ async fn consensus_validation_versions() { fee: 25.into(), lock_height: 0, features: Default::default(), - script: script![Nop], + script: script![Nop].unwrap(), input_data: None, covenant: Default::default(), input_version: None, @@ -1639,7 +1639,7 @@ async fn consensus_validation_versions() { fee: 25.into(), lock_height: 0, features: Default::default(), - script: script![Nop], + script: script![Nop].unwrap(), input_data: None, covenant: Default::default(), input_version: None, diff --git a/base_layer/core/tests/tests/node_comms_interface.rs b/base_layer/core/tests/tests/node_comms_interface.rs index be07a36f0e..c67ede3ce7 100644 --- a/base_layer/core/tests/tests/node_comms_interface.rs +++ b/base_layer/core/tests/tests/node_comms_interface.rs @@ -206,7 +206,7 @@ async fn inbound_fetch_utxos() { MicroMinotari(10_000), &key_manager, &Default::default(), - &script!(Nop), + &script!(Nop).unwrap(), &Covenant::default(), MicroMinotari::zero(), ) @@ -281,7 +281,7 @@ async fn initialize_sender_transaction_protocol_for_overflow_test( .with_lock_height(txn_schema.lock_height) .with_fee_per_gram(txn_schema.fee) .with_change_data( - script!(PushPubKey(Box::new(script_public_key))), + script!(PushPubKey(Box::new(script_public_key))).unwrap(), ExecutionStack::default(), change.script_key_id, change.commitment_mask_key_id, @@ -362,7 +362,7 @@ async fn initialize_sender_transaction_protocol_for_overflow_test( #[tokio::test] async fn test_sender_transaction_protocol_for_overflow() { let key_manager = create_memory_db_key_manager().unwrap(); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let amount = MicroMinotari(u64::MAX); // This is the adversary's attack! let output_features = OutputFeatures::default(); let covenant = Covenant::default(); diff --git a/base_layer/wallet/Cargo.toml b/base_layer/wallet/Cargo.toml index 90470e42e0..3116f0e528 100644 --- a/base_layer/wallet/Cargo.toml +++ b/base_layer/wallet/Cargo.toml @@ -15,6 +15,7 @@ tari_comms_dht = { path = "../../comms/dht", version = "1.3.0-pre.0" } tari_contacts = { path = "../../base_layer/contacts", version = "1.3.0-pre.0" } tari_core = { path = "../../base_layer/core", default-features = false, features = ["transactions", "mempool_proto", "base_node_proto"], version = "1.3.0-pre.0" } tari_crypto = { version = "0.20.3" } +tari_max_size = { path = "../../infrastructure/max_size" } tari_key_manager = { path = "../key_manager", features = ["key_manager_service"], version = "1.3.0-pre.0" } tari_p2p = { path = "../p2p", features = ["auto-update"], version = "1.3.0-pre.0" } tari_script = { path = "../../infrastructure/tari_script", version = "1.3.0-pre.0" } diff --git a/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs b/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs index 57f9ed914e..ded84fe641 100644 --- a/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs +++ b/base_layer/wallet/src/output_manager_service/recovery/standard_outputs_recoverer.rs @@ -81,10 +81,10 @@ where let known_scripts = self.db.get_all_known_one_sided_payment_scripts()?; let mut rewound_outputs: Vec<(WalletOutput, bool, FixedHash)> = Vec::new(); - let push_pub_key_script = script!(PushPubKey(Box::default())); + let push_pub_key_script = script!(PushPubKey(Box::default()))?; for output in outputs { let known_script_index = known_scripts.iter().position(|s| s.script == output.script); - if output.script != script!(Nop) && + if output.script != script!(Nop)? && known_script_index.is_none() && !output.script.pattern_match(&push_pub_key_script) { @@ -201,7 +201,7 @@ where known_script_index: Option, known_scripts: &[KnownOneSidedPaymentScript], ) -> Result, OutputManagerError> { - let (input_data, script_key) = if script == &script!(Nop) { + let (input_data, script_key) = if script == &script!(Nop)? { // This is a nop, so we can just create a new key for the input stack. let key = if let KeyId::Derived { key } = spending_key { TariKeyId::from_str(&key.to_string()).map_err(OutputManagerError::BuildError)? diff --git a/base_layer/wallet/src/output_manager_service/service.rs b/base_layer/wallet/src/output_manager_service/service.rs index fa857339d1..ba3c7d72f9 100644 --- a/base_layer/wallet/src/output_manager_service/service.rs +++ b/base_layer/wallet/src/output_manager_service/service.rs @@ -780,10 +780,10 @@ where // Confirm script hash is for the expected script, at the moment assuming Nop or Push_pubkey // if the script is Push_pubkey(default_key) we know we have to fill it in. - let script = if single_round_sender_data.script == script!(Nop) { + let script = if single_round_sender_data.script == script!(Nop)? { single_round_sender_data.script.clone() - } else if single_round_sender_data.script == script!(PushPubKey(Box::default())) { - script!(PushPubKey(Box::new(script_public_key.pub_key.clone()))) + } else if single_round_sender_data.script == script!(PushPubKey(Box::default()))? { + script!(PushPubKey(Box::new(script_public_key.pub_key.clone())))? } else { return Err(OutputManagerError::InvalidScriptHash); }; @@ -1031,7 +1031,7 @@ where .get_next_commitment_mask_and_script_key() .await?; builder.with_change_data( - script!(PushPubKey(Box::new(change_script_key.pub_key.clone()))), + script!(PushPubKey(Box::new(change_script_key.pub_key.clone())))?, ExecutionStack::default(), change_script_key.key_id, change_commitment_mask_key.key_id, @@ -1084,7 +1084,7 @@ where fee_per_gram: MicroMinotari, ) -> Result<(TxId, Transaction), OutputManagerError> { let total_value = outputs.iter().map(|o| o.value()).sum(); - let nop_script = script![Nop]; + let nop_script = script![Nop]?; let weighting = self.resources.consensus_constants.transaction_weight_params(); let mut features_and_scripts_byte_size = 0; for output in &outputs { @@ -1139,7 +1139,7 @@ where .get_next_commitment_mask_and_script_key() .await?; builder.with_change_data( - script!(PushPubKey(Box::new(change_script_key.pub_key))), + script!(PushPubKey(Box::new(change_script_key.pub_key)))?, ExecutionStack::default(), change_script_key.key_id, change_commitment_mask_key.key_id, @@ -1364,7 +1364,7 @@ where range_proof_type, ..Default::default() }; - let script = script!(PushPubKey(Box::new(recipient_address.public_spend_key().clone()))); + let script = script!(PushPubKey(Box::new(recipient_address.public_spend_key().clone())))?; let metadata_byte_size = self .resources .consensus_constants @@ -1400,7 +1400,7 @@ where ) .await? .with_change_data( - script!(PushPubKey(Box::default())), + script!(PushPubKey(Box::default()))?, ExecutionStack::default(), TariKeyId::default(), TariKeyId::default(), @@ -1665,7 +1665,7 @@ where range_proof_type, ..Default::default() }; - let temp_script = script!(PushPubKey(Box::default())); + let temp_script = script!(PushPubKey(Box::default()))?; let metadata_byte_size = self .resources .consensus_constants @@ -1693,7 +1693,7 @@ where .await? .with_sender_address(self.resources.one_sided_tari_address.clone()) .with_recipient_data( - script!(PushPubKey(Box::default())), + script!(PushPubKey(Box::default()))?, output_features, Covenant::default(), minimum_value_promise, @@ -1701,7 +1701,7 @@ where ) .await? .with_change_data( - script!(PushPubKey(Box::default())), + script!(PushPubKey(Box::default()))?, ExecutionStack::default(), TariKeyId::default(), TariKeyId::default(), @@ -1903,7 +1903,7 @@ where .get_next_commitment_mask_and_script_key() .await?; builder.with_change_data( - script!(PushPubKey(Box::new(change_script_public_key.pub_key.clone()))), + script!(PushPubKey(Box::new(change_script_public_key.pub_key.clone())))?, ExecutionStack::default(), change_script_public_key.key_id.clone(), change_commitment_mask_key_id.key_id, @@ -2538,7 +2538,7 @@ where .get_next_commitment_mask_and_script_key() .await?; tx_builder.with_change_data( - script!(PushPubKey(Box::new(change_script.pub_key))), + script!(PushPubKey(Box::new(change_script.pub_key)))?, ExecutionStack::default(), change_script.key_id, change_mask.key_id, @@ -2620,7 +2620,7 @@ where .key_manager .get_next_commitment_mask_and_script_key() .await?; - let script = script!(PushPubKey(Box::new(script_key.pub_key.clone()))); + let script = script!(PushPubKey(Box::new(script_key.pub_key.clone())))?; let payment_id = PaymentId::Address(self.resources.interactive_tari_address.clone()); let encrypted_data = self .resources @@ -2878,7 +2878,7 @@ where .get_next_commitment_mask_and_script_key() .await?; builder.with_change_data( - script!(PushPubKey(Box::new(change_script_key.pub_key.clone()))), + script!(PushPubKey(Box::new(change_script_key.pub_key.clone())))?, ExecutionStack::default(), change_script_key.key_id, change_commitment_mask_key.key_id, @@ -2963,7 +2963,7 @@ where .get_next_commitment_mask_and_script_key() .await?; builder.with_change_data( - script!(PushPubKey(Box::new(change_script_key.pub_key.clone()))), + script!(PushPubKey(Box::new(change_script_key.pub_key.clone())))?, ExecutionStack::default(), change_script_key.key_id, change_commitment_mask_key.key_id, diff --git a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs index 0cf8498398..6f37852775 100644 --- a/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs +++ b/base_layer/wallet/src/output_manager_service/storage/sqlite_db/mod.rs @@ -1456,10 +1456,15 @@ mod test { pub async fn make_input(val: MicroMinotari, key_manager: &MemoryDbKeyManager) -> (TransactionInput, WalletOutput) { let test_params = TestParams::new(key_manager).await; - let wallet_output = - create_wallet_output_with_data(script!(Nop), OutputFeatures::default(), &test_params, val, key_manager) - .await - .unwrap(); + let wallet_output = create_wallet_output_with_data( + script!(Nop).unwrap(), + OutputFeatures::default(), + &test_params, + val, + key_manager, + ) + .await + .unwrap(); let input = wallet_output.to_transaction_input(key_manager).await.unwrap(); (input, wallet_output) diff --git a/base_layer/wallet/src/transaction_service/error.rs b/base_layer/wallet/src/transaction_service/error.rs index 5f4479dea9..bacc587b5f 100644 --- a/base_layer/wallet/src/transaction_service/error.rs +++ b/base_layer/wallet/src/transaction_service/error.rs @@ -38,6 +38,7 @@ use tari_core::transactions::{ use tari_crypto::{errors::RangeProofError, signatures::CommitmentSignatureError}; use tari_key_manager::key_manager_service::KeyManagerServiceError; use tari_p2p::services::liveness::error::LivenessError; +use tari_script::ScriptError; use tari_service_framework::reply_channel::TransportChannelError; use tari_utilities::ByteArrayError; use thiserror::Error; @@ -195,6 +196,8 @@ pub enum TransactionServiceError { InvalidAddress(String), #[error("Transaction is not supported: `{0}`")] NotSupported(String), + #[error("Tari script error: {0}")] + ScriptError(#[from] ScriptError), } impl From for TransactionServiceError { diff --git a/base_layer/wallet/src/transaction_service/handle.rs b/base_layer/wallet/src/transaction_service/handle.rs index 439e48adaf..645f997d1c 100644 --- a/base_layer/wallet/src/transaction_service/handle.rs +++ b/base_layer/wallet/src/transaction_service/handle.rs @@ -33,8 +33,6 @@ use tari_common_types::{ tari_address::TariAddress, transaction::{ImportStatus, TxId}, types::{FixedHash, HashOutput, PrivateKey, PublicKey, Signature}, - MaxSizeBytes, - MaxSizeString, }; use tari_comms::types::CommsPublicKey; use tari_core::{ @@ -54,6 +52,7 @@ use tari_core::{ }, }; use tari_crypto::ristretto::pedersen::PedersenCommitment; +use tari_max_size::{MaxSizeBytes, MaxSizeString}; use tari_script::CheckSigSchnorrSignature; use tari_service_framework::reply_channel::SenderService; use tari_utilities::hex::Hex; diff --git a/base_layer/wallet/src/transaction_service/service.rs b/base_layer/wallet/src/transaction_service/service.rs index 3813882b0e..bdf64f2947 100644 --- a/base_layer/wallet/src/transaction_service/service.rs +++ b/base_layer/wallet/src/transaction_service/service.rs @@ -1428,7 +1428,7 @@ where Else CheckHeightVerify(height) PushPubKey(Box::new(self.resources.one_sided_tari_address.public_spend_key().clone())) EndIf - ); + )?; // Empty covenant let covenant = Covenant::default(); @@ -1937,7 +1937,7 @@ where fee_per_gram, tx_meta, message.clone(), - script!(Nop), + script!(Nop)?, Covenant::default(), MicroMinotari::zero(), ) @@ -2007,7 +2007,7 @@ where .features .clone(), ) - .with_script(script!(Nop)) + .with_script(script!(Nop)?) .encrypt_data_for_recovery( &self.resources.transaction_key_manager_service, Some(&recovery_key_id), diff --git a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs index 4ffbcbb224..14cc8ad353 100644 --- a/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs +++ b/base_layer/wallet/src/transaction_service/storage/sqlite_db.rs @@ -2286,7 +2286,7 @@ mod test { let mut builder = SenderTransactionProtocol::builder(constants, key_manager.clone()); let test_params = TestParams::new(&key_manager).await; let input = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params, MicroMinotari::from(100_000), @@ -2304,7 +2304,7 @@ mod test { .await .unwrap() .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), Default::default(), MicroMinotari::zero(), @@ -2313,7 +2313,7 @@ mod test { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id, change.commitment_mask_key_id, @@ -2391,7 +2391,7 @@ mod test { ); let output = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &test_params, MicroMinotari::from(100_000), diff --git a/base_layer/wallet/tests/other/mod.rs b/base_layer/wallet/tests/other/mod.rs index 91456421cf..1c3389d8a8 100644 --- a/base_layer/wallet/tests/other/mod.rs +++ b/base_layer/wallet/tests/other/mod.rs @@ -729,7 +729,7 @@ async fn test_import_utxo() { .unwrap(); let key = PrivateKey::random(&mut OsRng); let claim = PublicKey::from_secret_key(&key); - let script = script!(Nop); + let script = script!(Nop).unwrap(); let input = inputs!(claim); let temp_features = OutputFeatures::create_coinbase(50, None, RangeProofType::BulletProofPlus); diff --git a/base_layer/wallet/tests/output_manager_service_tests/service.rs b/base_layer/wallet/tests/output_manager_service_tests/service.rs index 42827d0369..a11bf6b820 100644 --- a/base_layer/wallet/tests/output_manager_service_tests/service.rs +++ b/base_layer/wallet/tests/output_manager_service_tests/service.rs @@ -263,7 +263,7 @@ async fn generate_sender_transaction_message( .await .unwrap() .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), Covenant::default(), MicroMinotari::zero(), @@ -274,7 +274,7 @@ async fn generate_sender_transaction_message( let change = TestParams::new(key_manager).await; builder.with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id, change.commitment_mask_key_id, @@ -400,7 +400,7 @@ async fn test_utxo_selection_no_chain_metadata() { fee_per_gram, TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -436,7 +436,7 @@ async fn test_utxo_selection_no_chain_metadata() { fee_per_gram, TransactionMetadata::default(), String::new(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -530,7 +530,7 @@ async fn test_utxo_selection_with_chain_metadata() { fee_per_gram, TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -612,7 +612,7 @@ async fn test_utxo_selection_with_chain_metadata() { fee_per_gram, TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -640,7 +640,7 @@ async fn test_utxo_selection_with_chain_metadata() { fee_per_gram, TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -735,7 +735,7 @@ async fn test_utxo_selection_with_tx_priority() { fee_per_gram, TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -781,7 +781,7 @@ async fn send_not_enough_funds() { MicroMinotari::from(4), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -810,7 +810,7 @@ async fn send_no_change() { ); let value1 = 5000; let uo_1 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&oms.key_manager_handle).await, MicroMinotari::from(value1), @@ -825,7 +825,7 @@ async fn send_no_change() { .unwrap(); let value2 = 8000; let uo_2 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&oms.key_manager_handle).await, MicroMinotari::from(value2), @@ -877,7 +877,7 @@ async fn send_not_enough_for_change() { let fee_without_change = Fee::new(*constants.transaction_weight_params()).calculate(fee_per_gram, 1, 2, 1, 0); let value1 = MicroMinotari(500); let uo_1 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&oms.key_manager_handle).await, value1, @@ -891,7 +891,7 @@ async fn send_not_enough_for_change() { .unwrap(); let value2 = MicroMinotari(800); let uo_2 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&oms.key_manager_handle).await, value2, @@ -914,7 +914,7 @@ async fn send_not_enough_for_change() { fee_per_gram, TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -955,7 +955,7 @@ async fn cancel_transaction() { MicroMinotari::from(4), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -1060,7 +1060,7 @@ async fn test_get_balance() { MicroMinotari::from(4), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -1131,7 +1131,7 @@ async fn sending_transaction_persisted_while_offline() { MicroMinotari::from(4), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -1164,7 +1164,7 @@ async fn sending_transaction_persisted_while_offline() { MicroMinotari::from(4), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -1942,7 +1942,7 @@ async fn test_txo_revalidation() { let output1_value = 1_000_000; let key_manager = create_memory_db_key_manager().unwrap(); let output1 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager).await, MicroMinotari::from(output1_value), @@ -1958,7 +1958,7 @@ async fn test_txo_revalidation() { let output2_value = 2_000_000; let output2 = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager).await, MicroMinotari::from(output2_value), @@ -2204,7 +2204,7 @@ async fn scan_for_recovery_test() { MicroMinotari::from(amount), commitment_mask_key.key_id, features, - script!(Nop), + script!(Nop).unwrap(), inputs!(public_script_key), script_key_id, PublicKey::default(), diff --git a/base_layer/wallet/tests/support/utils.rs b/base_layer/wallet/tests/support/utils.rs index 742c28acf3..e2ff34bd37 100644 --- a/base_layer/wallet/tests/support/utils.rs +++ b/base_layer/wallet/tests/support/utils.rs @@ -124,7 +124,7 @@ pub async fn make_input_with_features( key_manager: &MemoryDbKeyManager, ) -> WalletOutput { let test_params = TestParams::new(key_manager).await; - create_wallet_output_with_data(script!(Nop), features, &test_params, value, key_manager) + create_wallet_output_with_data(script!(Nop).unwrap(), features, &test_params, value, key_manager) .await .unwrap() } diff --git a/base_layer/wallet/tests/transaction_service_tests/service.rs b/base_layer/wallet/tests/transaction_service_tests/service.rs index 09fd092737..486d714c72 100644 --- a/base_layer/wallet/tests/transaction_service_tests/service.rs +++ b/base_layer/wallet/tests/transaction_service_tests/service.rs @@ -2546,7 +2546,7 @@ async fn finalize_tx_with_incorrect_pubkey() { MicroMinotari::from(25), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -2675,7 +2675,7 @@ async fn finalize_tx_with_missing_output() { MicroMinotari::from(20), TransactionMetadata::default(), "".to_string(), - script!(Nop), + script!(Nop).unwrap(), Covenant::default(), MicroMinotari::zero(), ) @@ -3309,7 +3309,7 @@ async fn test_transaction_cancellation() { let key_manager = create_memory_db_key_manager().unwrap(); let input = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager).await, MicroMinotari::from(100_000), @@ -3331,7 +3331,7 @@ async fn test_transaction_cancellation() { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -3339,7 +3339,7 @@ async fn test_transaction_cancellation() { TariAddress::default(), ) .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), Covenant::default(), MicroMinotari::zero(), @@ -3397,7 +3397,7 @@ async fn test_transaction_cancellation() { // Lets cancel the last one using a Comms stack message let input = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager.clone()).await, MicroMinotari::from(100_000), @@ -3417,7 +3417,7 @@ async fn test_transaction_cancellation() { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -3425,7 +3425,7 @@ async fn test_transaction_cancellation() { TariAddress::default(), ) .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), Covenant::default(), MicroMinotari::zero(), @@ -4189,7 +4189,7 @@ async fn test_restarting_transaction_protocols() { .await .unwrap() .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), Covenant::default(), MicroMinotari::zero(), @@ -4198,7 +4198,7 @@ async fn test_restarting_transaction_protocols() { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -4599,7 +4599,7 @@ async fn test_resend_on_startup() { // First we will check the Send Tranasction message let key_manager = create_memory_db_key_manager().unwrap(); let input = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager).await, MicroMinotari::from(100_000), @@ -4620,7 +4620,7 @@ async fn test_resend_on_startup() { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -4628,7 +4628,7 @@ async fn test_resend_on_startup() { TariAddress::default(), ) .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), Covenant::default(), MicroMinotari::zero(), @@ -5128,7 +5128,7 @@ async fn test_transaction_timeout_cancellation() { // First we will check the Send Transction message let key_manager = create_memory_db_key_manager().unwrap(); let input = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager).await, MicroMinotari::from(100_000), @@ -5149,7 +5149,7 @@ async fn test_transaction_timeout_cancellation() { .await .unwrap() .with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), @@ -5157,7 +5157,7 @@ async fn test_transaction_timeout_cancellation() { TariAddress::default(), ) .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), Covenant::default(), MicroMinotari::zero(), diff --git a/base_layer/wallet/tests/transaction_service_tests/storage.rs b/base_layer/wallet/tests/transaction_service_tests/storage.rs index 7369ceb3b6..41e3401691 100644 --- a/base_layer/wallet/tests/transaction_service_tests/storage.rs +++ b/base_layer/wallet/tests/transaction_service_tests/storage.rs @@ -77,7 +77,7 @@ pub async fn test_db_backend(backend: T) { let mut db = TransactionDatabase::new(backend); let key_manager = create_memory_db_key_manager().unwrap(); let input = create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &TestParams::new(&key_manager).await, MicroMinotari::from(100_000), @@ -97,7 +97,7 @@ pub async fn test_db_backend(backend: T) { .await .unwrap() .with_recipient_data( - script!(Nop), + script!(Nop).unwrap(), Default::default(), Covenant::default(), MicroMinotari::zero(), @@ -107,7 +107,7 @@ pub async fn test_db_backend(backend: T) { .unwrap(); let change = TestParams::new(&key_manager).await; builder.with_change_data( - script!(Nop), + script!(Nop).unwrap(), inputs!(change.script_key_pk), change.script_key_id.clone(), change.commitment_mask_key_id.clone(), diff --git a/base_layer/wallet_ffi/src/lib.rs b/base_layer/wallet_ffi/src/lib.rs index 55061c9264..86519156fb 100644 --- a/base_layer/wallet_ffi/src/lib.rs +++ b/base_layer/wallet_ffi/src/lib.rs @@ -11652,7 +11652,7 @@ mod test { let key_manager = create_memory_db_key_manager().unwrap(); let utxo_1 = runtime .block_on(create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &runtime.block_on(TestParams::new(&key_manager)), MicroMinotari(1234u64), @@ -11675,7 +11675,7 @@ mod test { let covenant_ptr = Box::into_raw(Box::new(utxo_1.covenant.clone())); let encrypted_data_ptr = Box::into_raw(Box::new(utxo_1.encrypted_data)); let minimum_value_promise = utxo_1.minimum_value_promise.as_u64(); - let script_ptr = CString::into_raw(CString::new(script!(Nop).to_hex()).unwrap()) as *const c_char; + let script_ptr = CString::into_raw(CString::new(script!(Nop).unwrap().to_hex()).unwrap()) as *const c_char; let input_data_ptr = CString::into_raw(CString::new(utxo_1.input_data.to_hex()).unwrap()) as *const c_char; let tari_utxo = create_tari_unblinded_output( @@ -11804,7 +11804,7 @@ mod test { // Test import with bulletproof range proof let utxo_1 = runtime .block_on(create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &runtime.block_on(TestParams::new(key_manager)), MicroMinotari(1234u64), @@ -11855,7 +11855,8 @@ mod test { let covenant_ptr_1 = Box::into_raw(Box::new(utxo_1.covenant.clone())); let encrypted_data_ptr_1 = Box::into_raw(Box::new(utxo_1.encrypted_data)); let minimum_value_promise = utxo_1.minimum_value_promise.as_u64(); - let script_ptr_1 = CString::into_raw(CString::new(script!(Nop).to_hex()).unwrap()) as *const c_char; + let script_ptr_1 = + CString::into_raw(CString::new(script!(Nop).unwrap().to_hex()).unwrap()) as *const c_char; let input_data_ptr_1 = CString::into_raw(CString::new(utxo_1.input_data.to_hex()).unwrap()) as *const c_char; @@ -11897,7 +11898,7 @@ mod test { }; let utxo_2 = runtime .block_on(create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), features, &runtime.block_on(TestParams::new(key_manager)), MicroMinotari(12345u64), @@ -11921,7 +11922,8 @@ mod test { let covenant_ptr_2 = Box::into_raw(Box::new(utxo_2.covenant.clone())); let encrypted_data_ptr_2 = Box::into_raw(Box::new(utxo_2.encrypted_data)); let minimum_value_promise = utxo_2.minimum_value_promise.as_u64(); - let script_ptr_2 = CString::into_raw(CString::new(script!(Nop).to_hex()).unwrap()) as *const c_char; + let script_ptr_2 = + CString::into_raw(CString::new(script!(Nop).unwrap().to_hex()).unwrap()) as *const c_char; let input_data_ptr_2 = CString::into_raw(CString::new(utxo_2.input_data.to_hex()).unwrap()) as *const c_char; @@ -12030,7 +12032,7 @@ mod test { let key_manager = create_memory_db_key_manager().unwrap(); let utxo_1 = runtime .block_on(create_wallet_output_with_data( - script!(Nop), + script!(Nop).unwrap(), OutputFeatures::default(), &runtime.block_on(TestParams::new(&key_manager)), MicroMinotari(1234u64), @@ -12055,7 +12057,7 @@ mod test { let encrypted_data_ptr = Box::into_raw(Box::new(utxo_1.encrypted_data)); let minimum_value_promise = utxo_1.minimum_value_promise.as_u64(); let message_ptr = CString::into_raw(CString::new("For my friend").unwrap()) as *const c_char; - let script_ptr = CString::into_raw(CString::new(script!(Nop).to_hex()).unwrap()) as *const c_char; + let script_ptr = CString::into_raw(CString::new(script!(Nop).unwrap().to_hex()).unwrap()) as *const c_char; let input_data_ptr = CString::into_raw(CString::new(utxo_1.input_data.to_hex()).unwrap()) as *const c_char; let tari_utxo = create_tari_unblinded_output( diff --git a/infrastructure/max_size/Cargo.toml b/infrastructure/max_size/Cargo.toml new file mode 100644 index 0000000000..1c83feca94 --- /dev/null +++ b/infrastructure/max_size/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "tari_max_size" +version = "1.3.0-pre.0" +edition = "2021" +description = "Tari max size library" +authors = ["The Tari Development Community"] +repository = "https://github.com/tari-project/tari" +categories = ["cryptography"] +homepage = "https://tari.com" +readme = "README.md" +license = "BSD-3-Clause" + +[dependencies] +tari_utilities = { version = "0.7" } + +borsh = "1.2" +serde = { version = "1.0.136", features = ["derive"] } +thiserror = "1.0.30" diff --git a/base_layer/common_types/src/max_size/bytes.rs b/infrastructure/max_size/src/bytes.rs similarity index 100% rename from base_layer/common_types/src/max_size/bytes.rs rename to infrastructure/max_size/src/bytes.rs diff --git a/base_layer/common_types/src/max_size/mod.rs b/infrastructure/max_size/src/lib.rs similarity index 100% rename from base_layer/common_types/src/max_size/mod.rs rename to infrastructure/max_size/src/lib.rs diff --git a/base_layer/common_types/src/max_size/string.rs b/infrastructure/max_size/src/string.rs similarity index 100% rename from base_layer/common_types/src/max_size/string.rs rename to infrastructure/max_size/src/string.rs diff --git a/base_layer/common_types/src/max_size/vec.rs b/infrastructure/max_size/src/vec.rs similarity index 77% rename from base_layer/common_types/src/max_size/vec.rs rename to infrastructure/max_size/src/vec.rs index fea8a7c4fb..3e5d26ec42 100644 --- a/base_layer/common_types/src/max_size/vec.rs +++ b/infrastructure/max_size/src/vec.rs @@ -22,6 +22,7 @@ use std::{ convert::TryFrom, + iter::FromIterator, marker::PhantomData, ops::{Deref, DerefMut}, }; @@ -30,14 +31,18 @@ use borsh::{BorshDeserialize, BorshSerialize}; use serde::{Deserialize, Serialize}; /// A vector that has a maximum size of `MAX_SIZE`. -#[derive( - Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Deserialize, Serialize, BorshSerialize, BorshDeserialize, -)] +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize, BorshSerialize, BorshDeserialize)] pub struct MaxSizeVec { vec: Vec, _marker: PhantomData, } +impl Default for MaxSizeVec { + fn default() -> Self { + Self::new() + } +} + impl MaxSizeVec { /// Creates a new `MaxSizeVec` with a capacity of `MAX_SIZE`. pub fn new() -> Self { @@ -94,6 +99,18 @@ impl MaxSizeVec { pub fn max_size(&self) -> usize { MAX_SIZE } + + /// Pushes an item to the `MaxSizeVec`. + pub fn push(&mut self, item: T) -> Result<(), MaxSizeVecError> { + if self.vec.len() >= MAX_SIZE { + return Err(MaxSizeVecError::MaxSizeVecLengthError { + expected: MAX_SIZE, + actual: self.vec.len(), + }); + } + self.vec.push(item); + Ok(()) + } } impl From> for Vec { @@ -146,7 +163,37 @@ impl DerefMut for MaxSizeVec { } } -#[derive(Debug, thiserror::Error)] +impl Iterator for MaxSizeVec { + type Item = T; + + /// Iterates over the `MaxSizeVec`. + fn next(&mut self) -> Option { + if self.vec.is_empty() { + None + } else { + Some(self.vec.remove(0)) + } + } +} + +impl FromIterator for MaxSizeVec { + /// Creates a `MaxSizeVec` from an iterator. + fn from_iter>(iter: I) -> Self { + let mut vec = Vec::with_capacity(MAX_SIZE); + for item in iter { + if vec.len() >= MAX_SIZE { + break; + } + vec.push(item); + } + Self { + vec, + _marker: PhantomData, + } + } +} + +#[derive(Clone, Debug, thiserror::Error, Eq, PartialEq, Serialize, Deserialize)] pub enum MaxSizeVecError { #[error("Invalid vector length: expected {expected}, got {actual}")] MaxSizeVecLengthError { expected: usize, actual: usize }, diff --git a/infrastructure/tari_script/Cargo.toml b/infrastructure/tari_script/Cargo.toml index 8d1f40d88d..492859b95b 100644 --- a/infrastructure/tari_script/Cargo.toml +++ b/infrastructure/tari_script/Cargo.toml @@ -12,6 +12,7 @@ license = "BSD-3-Clause" [dependencies] tari_crypto = { version = "0.20.3" } +tari_max_size = { path = "../../infrastructure/max_size" } tari_utilities = { version = "0.7" } blake2 = "0.10" diff --git a/infrastructure/tari_script/src/error.rs b/infrastructure/tari_script/src/error.rs index dd82be7783..16bce63c06 100644 --- a/infrastructure/tari_script/src/error.rs +++ b/infrastructure/tari_script/src/error.rs @@ -18,6 +18,7 @@ use std::num::TryFromIntError; use serde::{Deserialize, Serialize}; +use tari_max_size::MaxSizeVecError; use tari_utilities::ByteArrayError; use thiserror::Error; @@ -51,6 +52,14 @@ pub enum ScriptError { InvalidDigest, #[error("A compare opcode failed, aborting the script immediately with reason: `{0}`")] CompareFailed(String), + #[error("Max sized vector error: {0}")] + MaxSizeVecError(#[from] MaxSizeVecError), +} + +impl ScriptError { + pub fn to_std_io_error(self) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::Other, self.to_string()) + } } impl From for ScriptError { diff --git a/infrastructure/tari_script/src/lib.rs b/infrastructure/tari_script/src/lib.rs index c3371acf9f..8c71bce6bd 100644 --- a/infrastructure/tari_script/src/lib.rs +++ b/infrastructure/tari_script/src/lib.rs @@ -33,7 +33,7 @@ pub use op_codes::{ OpcodeVersion, ScalarValue, }; -pub use script::TariScript; +pub use script::{ScriptOpcodes, TariScript}; pub use script_context::ScriptContext; pub use stack::{ExecutionStack, StackItem}; use tari_crypto::{ @@ -49,5 +49,5 @@ pub type CheckSigSchnorrSignature = SchnorrSignature TariScript { - script!(PushPubKey(Box::new(destination_public_key.clone()))) + script!(PushPubKey(Box::new(destination_public_key.clone()))).expect("single opcode will not fail") } diff --git a/infrastructure/tari_script/src/script.rs b/infrastructure/tari_script/src/script.rs index ab07a14323..31743a151b 100644 --- a/infrastructure/tari_script/src/script.rs +++ b/infrastructure/tari_script/src/script.rs @@ -28,6 +28,7 @@ use tari_crypto::{ keys::PublicKey, ristretto::{RistrettoPublicKey, RistrettoSecretKey}, }; +use tari_max_size::MaxSizeVec; use tari_utilities::{ hex::{from_hex, to_hex, Hex, HexError}, ByteArray, @@ -58,9 +59,12 @@ macro_rules! script { const MAX_MULTISIG_LIMIT: u8 = 32; const MAX_SCRIPT_BYTES: usize = 4096; +/// The sized vector of opcodes that make up a script +pub type ScriptOpcodes = MaxSizeVec; + #[derive(Clone, Debug, PartialEq, Eq)] pub struct TariScript { - script: Vec, + script: ScriptOpcodes, } impl BorshSerialize for TariScript { @@ -95,8 +99,9 @@ impl BorshDeserialize for TariScript { } impl TariScript { - pub fn new(script: Vec) -> Self { - TariScript { script } + pub fn new(script: Vec) -> Result { + let script = ScriptOpcodes::try_from(script)?; + Ok(TariScript { script }) } /// This pattern matches two scripts ensure they have the same instructions in the opcodes, but not the same values @@ -144,7 +149,7 @@ impl TariScript { // Local execution state let mut state = ExecutionState::default(); - for opcode in &self.script { + for opcode in self.script.iter() { if self.should_execute(opcode, &state)? { self.execute_opcode(opcode, &mut stack, context, &mut state)? } else { @@ -190,7 +195,7 @@ impl TariScript { } pub fn as_slice(&self) -> &[Opcode] { - self.script.as_slice() + self.script.as_ref() } /// Calculate the hash of the script. @@ -206,7 +211,7 @@ impl TariScript { /// Try to deserialise a byte slice into a valid Tari script pub fn from_bytes(bytes: &[u8]) -> Result { - let script = Opcode::parse(bytes)?; + let script = ScriptOpcodes::try_from(Opcode::parse(bytes)?)?; Ok(TariScript { script }) } @@ -685,7 +690,7 @@ impl Hex for TariScript { /// The default Tari script is to push a sender pubkey onto the stack impl Default for TariScript { fn default() -> Self { - script!(PushPubKey(Box::default())) + script!(PushPubKey(Box::default())).expect("default will not fail") } } @@ -756,28 +761,28 @@ mod test { #[test] fn pattern_match() { - let script_a = script!(Or(1)); - let script_b = script!(Or(1)); + let script_a = script!(Or(1)).unwrap(); + let script_b = script!(Or(1)).unwrap(); assert_eq!(script_a, script_b); assert!(script_a.pattern_match(&script_b)); - let script_b = script!(Or(2)); + let script_b = script!(Or(2)).unwrap(); assert_ne!(script_a, script_b); assert!(script_a.pattern_match(&script_b)); - let script_b = script!(Or(2) Or(2)); + let script_b = script!(Or(2) Or(2)).unwrap(); assert_ne!(script_a, script_b); assert!(!script_a.pattern_match(&script_b)); - let script_a = script!(Or(2) Or(1)); - let script_b = script!(Or(3) Or(5)); + let script_a = script!(Or(2) Or(1)).unwrap(); + let script_b = script!(Or(3) Or(5)).unwrap(); assert_ne!(script_a, script_b); assert!(script_a.pattern_match(&script_b)); } #[test] fn op_or() { - let script = script!(Or(1)); + let script = script!(Or(1)).unwrap(); let inputs = inputs!(4, 4); let result = script.execute(&inputs).unwrap(); @@ -787,7 +792,7 @@ mod test { let result = script.execute(&inputs).unwrap(); assert_eq!(result, Number(0)); - let script = script!(Or(3)); + let script = script!(Or(3)).unwrap(); let inputs = inputs!(1, 2, 1, 3); let result = script.execute(&inputs).unwrap(); @@ -811,7 +816,7 @@ mod test { let err = script.execute(&inputs).unwrap_err(); assert!(matches!(err, ScriptError::StackUnderflow)); - let script = script!(OrVerify(1)); + let script = script!(OrVerify(1)).unwrap(); let inputs = inputs!(1, 4, 4); let result = script.execute(&inputs).unwrap(); @@ -821,7 +826,7 @@ mod test { let err = script.execute(&inputs).unwrap_err(); assert!(matches!(err, ScriptError::VerifyFailed)); - let script = script!(OrVerify(2)); + let script = script!(OrVerify(2)).unwrap(); let inputs = inputs!(1, 2, 2, 3); let result = script.execute(&inputs).unwrap(); @@ -835,7 +840,7 @@ mod test { #[test] fn op_if_then_else() { // basic - let script = script!(IfThen PushInt(420) Else PushInt(66) EndIf); + let script = script!(IfThen PushInt(420) Else PushInt(66) EndIf).unwrap(); let inputs = inputs!(1); let result = script.execute(&inputs); assert_eq!(result.unwrap(), Number(420)); @@ -845,54 +850,57 @@ mod test { assert_eq!(result.unwrap(), Number(66)); // nested - let script = script!(IfThen PushOne IfThen PushInt(420) Else PushInt(555) EndIf Else PushInt(66) EndIf); + let script = + script!(IfThen PushOne IfThen PushInt(420) Else PushInt(555) EndIf Else PushInt(66) EndIf).unwrap(); let inputs = inputs!(1); let result = script.execute(&inputs); assert_eq!(result.unwrap(), Number(420)); - let script = script!(IfThen PushInt(420) Else PushZero IfThen PushInt(111) Else PushInt(66) EndIf Nop EndIf); + let script = + script!(IfThen PushInt(420) Else PushZero IfThen PushInt(111) Else PushInt(66) EndIf Nop EndIf).unwrap(); let inputs = inputs!(0); let result = script.execute(&inputs); assert_eq!(result.unwrap(), Number(66)); // duplicate else - let script = script!(IfThen PushInt(420) Else PushInt(66) Else PushInt(777) EndIf); + let script = script!(IfThen PushInt(420) Else PushInt(66) Else PushInt(777) EndIf).unwrap(); let inputs = inputs!(0); let result = script.execute(&inputs); assert_eq!(result.unwrap_err(), ScriptError::InvalidOpcode); // unexpected else - let script = script!(Else); + let script = script!(Else).unwrap(); let inputs = inputs!(0); let result = script.execute(&inputs); assert_eq!(result.unwrap_err(), ScriptError::InvalidOpcode); // unexpected endif - let script = script!(EndIf); + let script = script!(EndIf).unwrap(); let inputs = inputs!(0); let result = script.execute(&inputs); assert_eq!(result.unwrap_err(), ScriptError::InvalidOpcode); // duplicate endif - let script = script!(IfThen PushInt(420) Else PushInt(66) EndIf EndIf); + let script = script!(IfThen PushInt(420) Else PushInt(66) EndIf EndIf).unwrap(); let inputs = inputs!(0); let result = script.execute(&inputs); assert_eq!(result.unwrap_err(), ScriptError::InvalidOpcode); // no else or endif - let script = script!(IfThen PushOne IfThen PushOne); + let script = script!(IfThen PushOne IfThen PushOne).unwrap(); let inputs = inputs!(1); let result = script.execute(&inputs); assert_eq!(result.unwrap_err(), ScriptError::MissingOpcode); // no else - let script = script!(IfThen PushOne EndIf); + let script = script!(IfThen PushOne EndIf).unwrap(); let inputs = inputs!(1); let result = script.execute(&inputs); assert_eq!(result.unwrap_err(), ScriptError::MissingOpcode); // nested bug - let script = script!(IfThen PushInt(111) Else PushZero IfThen PushInt(222) Else PushInt(333) EndIf EndIf); + let script = + script!(IfThen PushInt(111) Else PushZero IfThen PushInt(222) Else PushInt(333) EndIf EndIf).unwrap(); let inputs = inputs!(1); let result = script.execute(&inputs); assert_eq!(result.unwrap(), Number(111)); @@ -901,7 +909,7 @@ mod test { #[test] fn op_check_height() { let inputs = ExecutionStack::default(); - let script = script!(CheckHeight(5)); + let script = script!(CheckHeight(5)).unwrap(); for block_height in 1..=10 { let ctx = context_with_height(u64::try_from(block_height).unwrap()); @@ -911,12 +919,12 @@ mod test { ); } - let script = script!(CheckHeight(u64::MAX)); + let script = script!(CheckHeight(u64::MAX)).unwrap(); let ctx = context_with_height(i64::MAX as u64); let err = script.execute_with_context(&inputs, &ctx).unwrap_err(); assert!(matches!(err, ScriptError::ValueExceedsBounds)); - let script = script!(CheckHeightVerify(5)); + let script = script!(CheckHeightVerify(5)).unwrap(); let inputs = inputs!(1); for block_height in 1..5 { @@ -934,7 +942,7 @@ mod test { #[test] fn op_compare_height() { - let script = script!(CompareHeight); + let script = script!(CompareHeight).unwrap(); let inputs = inputs!(5); for block_height in 1..=10 { @@ -945,7 +953,7 @@ mod test { ); } - let script = script!(CompareHeightVerify); + let script = script!(CompareHeightVerify).unwrap(); let inputs = inputs!(1, 5); for block_height in 1..5 { @@ -964,37 +972,37 @@ mod test { #[test] fn op_drop_push() { let inputs = inputs!(420); - let script = script!(Drop PushOne); + let script = script!(Drop PushOne).unwrap(); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); - let script = script!(Drop PushZero); + let script = script!(Drop PushZero).unwrap(); assert_eq!(script.execute(&inputs).unwrap(), Number(0)); - let script = script!(Drop PushInt(5)); + let script = script!(Drop PushInt(5)).unwrap(); assert_eq!(script.execute(&inputs).unwrap(), Number(5)); } #[test] fn op_comparison_to_zero() { - let script = script!(GeZero); + let script = script!(GeZero).unwrap(); let inputs = inputs!(1); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); let inputs = inputs!(0); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); - let script = script!(GtZero); + let script = script!(GtZero).unwrap(); let inputs = inputs!(1); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); let inputs = inputs!(0); assert_eq!(script.execute(&inputs).unwrap(), Number(0)); - let script = script!(LeZero); + let script = script!(LeZero).unwrap(); let inputs = inputs!(-1); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); let inputs = inputs!(0); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); - let script = script!(LtZero); + let script = script!(LtZero).unwrap(); let inputs = inputs!(-1); assert_eq!(script.execute(&inputs).unwrap(), Number(1)); let inputs = inputs!(0); @@ -1006,7 +1014,7 @@ mod test { let mut rng = rand::thread_rng(); let (_, p) = RistrettoPublicKey::random_keypair(&mut rng); let c = PedersenCommitment::from_public_key(&p); - let script = script!(HashSha256); + let script = script!(HashSha256).unwrap(); let hash = Sha256::digest(p.as_bytes()); let inputs = inputs!(p.clone()); @@ -1016,7 +1024,7 @@ mod test { let inputs = inputs!(c.clone()); assert_eq!(script.execute(&inputs).unwrap(), Hash(hash.into())); - let script = script!(HashSha3); + let script = script!(HashSha3).unwrap(); let hash = Sha3::digest(p.as_bytes()); let inputs = inputs!(p); @@ -1029,14 +1037,14 @@ mod test { #[test] fn op_return() { - let script = script!(Return); + let script = script!(Return).unwrap(); let inputs = ExecutionStack::default(); assert_eq!(script.execute(&inputs), Err(ScriptError::Return)); } #[test] fn op_add() { - let script = script!(Add); + let script = script!(Add).unwrap(); let inputs = inputs!(3, 2); assert_eq!(script.execute(&inputs).unwrap(), Number(5)); let inputs = inputs!(3, -3); @@ -1049,7 +1057,7 @@ mod test { #[test] fn op_add_commitments() { - let script = script!(Add); + let script = script!(Add).unwrap(); let mut rng = rand::thread_rng(); let (_, c1) = RistrettoPublicKey::random_keypair(&mut rng); let (_, c2) = RistrettoPublicKey::random_keypair(&mut rng); @@ -1065,19 +1073,19 @@ mod test { #[test] fn op_sub() { use crate::StackItem::Number; - let script = script!(Add Sub); + let script = script!(Add Sub).unwrap(); let inputs = inputs!(5, 3, 2); assert_eq!(script.execute(&inputs).unwrap(), Number(0)); let inputs = inputs!(i64::MAX, 1); assert_eq!(script.execute(&inputs), Err(ScriptError::ValueExceedsBounds)); - let script = script!(Sub); + let script = script!(Sub).unwrap(); let inputs = inputs!(5, 3); assert_eq!(script.execute(&inputs).unwrap(), Number(2)); } #[test] fn serialisation() { - let script = script!(Add Sub Add); + let script = script!(Add Sub Add).unwrap(); assert_eq!(&script.to_bytes(), &[0x93, 0x94, 0x93]); assert_eq!(TariScript::from_bytes(&[0x93, 0x94, 0x93]).unwrap(), script); assert_eq!(script.to_hex(), "939493"); @@ -1092,14 +1100,14 @@ mod test { let m_key = RistrettoSecretKey::random(&mut rng); let sig = CheckSigSchnorrSignature::sign(&pvt_key, m_key.as_bytes(), &mut rng).unwrap(); let msg = slice_to_boxed_message(m_key.as_bytes()); - let script = script!(CheckSig(msg)); + let script = script!(CheckSig(msg)).unwrap(); let inputs = inputs!(sig.clone(), pub_key.clone()); let result = script.execute(&inputs).unwrap(); assert_eq!(result, Number(1)); let n_key = RistrettoSecretKey::random(&mut rng); let msg = slice_to_boxed_message(n_key.as_bytes()); - let script = script!(CheckSig(msg)); + let script = script!(CheckSig(msg)).unwrap(); let inputs = inputs!(sig, pub_key); let result = script.execute(&inputs).unwrap(); assert_eq!(result, Number(0)); @@ -1113,14 +1121,14 @@ mod test { let m_key = RistrettoSecretKey::random(&mut rng); let sig = CheckSigSchnorrSignature::sign(&pvt_key, m_key.as_bytes(), &mut rng).unwrap(); let msg = slice_to_boxed_message(m_key.as_bytes()); - let script = script!(CheckSigVerify(msg) PushOne); + let script = script!(CheckSigVerify(msg) PushOne).unwrap(); let inputs = inputs!(sig.clone(), pub_key.clone()); let result = script.execute(&inputs).unwrap(); assert_eq!(result, Number(1)); let n_key = RistrettoSecretKey::random(&mut rng); let msg = slice_to_boxed_message(n_key.as_bytes()); - let script = script!(CheckSigVerify(msg)); + let script = script!(CheckSigVerify(msg)).unwrap(); let inputs = inputs!(sig, pub_key); let err = script.execute(&inputs).unwrap_err(); assert!(matches!(err, ScriptError::VerifyFailed)); @@ -1166,7 +1174,7 @@ mod test { // 1 of 2 let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSig(1, 2, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone()); let result = script.execute(&inputs).unwrap(); @@ -1181,7 +1189,7 @@ mod test { // 2 of 2 let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSig(2, 2, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone(), s_bob.clone()); let result = script.execute(&inputs).unwrap(); @@ -1201,7 +1209,7 @@ mod test { // 1 of 3 let keys = vec![p_alice.clone(), p_bob.clone(), p_carol.clone()]; let ops = vec![CheckMultiSig(1, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone()); let result = script.execute(&inputs).unwrap(); @@ -1219,7 +1227,7 @@ mod test { // 2 of 3 let keys = vec![p_alice.clone(), p_bob.clone(), p_carol.clone()]; let ops = vec![CheckMultiSig(2, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone(), s_bob.clone()); let result = script.execute(&inputs).unwrap(); @@ -1240,7 +1248,7 @@ mod test { // check that sigs are only counted once let keys = vec![p_alice.clone(), p_bob.clone(), p_alice.clone()]; let ops = vec![CheckMultiSig(2, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone(), s_carol.clone()); let result = script.execute(&inputs).unwrap(); @@ -1259,7 +1267,7 @@ mod test { // 3 of 3 let keys = vec![p_alice.clone(), p_bob.clone(), p_carol]; let ops = vec![CheckMultiSig(3, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone(), s_bob.clone(), s_carol.clone()); let result = script.execute(&inputs).unwrap(); @@ -1277,21 +1285,21 @@ mod test { // errors let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSig(0, 2, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone()); let err = script.execute(&inputs).unwrap_err(); assert_eq!(err, ScriptError::ValueExceedsBounds); let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSig(1, 0, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone()); let err = script.execute(&inputs).unwrap_err(); assert_eq!(err, ScriptError::ValueExceedsBounds); let keys = vec![p_alice, p_bob]; let ops = vec![CheckMultiSig(2, 1, keys, msg)]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice); let err = script.execute(&inputs).unwrap_err(); assert_eq!(err, ScriptError::ValueExceedsBounds); @@ -1300,7 +1308,7 @@ mod test { let (msg, data) = multisig_data(33); let keys = data.iter().map(|(_, p, _)| p.clone()).collect(); let sigs = data.iter().take(17).map(|(_, _, s)| s.clone()); - let script = script!(CheckMultiSig(17, 33, keys, msg)); + let script = script!(CheckMultiSig(17, 33, keys, msg)).unwrap(); let items = sigs.map(StackItem::Signature).collect(); let inputs = ExecutionStack::new(items); let err = script.execute(&inputs).unwrap_err(); @@ -1315,7 +1323,7 @@ mod test { data[3].1.clone(), ]; let ops = vec![CheckMultiSig(3, 4, keys, msg)]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(data[0].2.clone(), data[1].2.clone(), data[2].2.clone()); let result = script.execute(&inputs).unwrap(); assert_eq!(result, Number(1)); @@ -1332,7 +1340,7 @@ mod test { data[6].1.clone(), ]; let ops = vec![CheckMultiSig(5, 7, keys, msg)]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!( data[0].2.clone(), data[1].2.clone(), @@ -1363,7 +1371,7 @@ mod test { // 1 of 2 let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSigVerify(1, 2, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(Number(1), s_alice.clone()); let result = script.execute(&inputs).unwrap(); @@ -1378,7 +1386,7 @@ mod test { // 2 of 2 let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSigVerify(2, 2, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(Number(1), s_alice.clone(), s_bob.clone()); let result = script.execute(&inputs).unwrap(); @@ -1393,7 +1401,7 @@ mod test { // 1 of 3 let keys = vec![p_alice.clone(), p_bob.clone(), p_carol.clone()]; let ops = vec![CheckMultiSigVerify(1, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(Number(1), s_alice.clone()); let result = script.execute(&inputs).unwrap(); @@ -1411,7 +1419,7 @@ mod test { // 2 of 3 let keys = vec![p_alice.clone(), p_bob.clone(), p_carol.clone()]; let ops = vec![CheckMultiSigVerify(2, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(Number(1), s_alice.clone(), s_bob.clone()); let result = script.execute(&inputs).unwrap(); @@ -1432,7 +1440,7 @@ mod test { // 2 of 3 (returning the aggregate public key of the signatories) let keys = vec![p_alice.clone(), p_bob.clone(), p_carol.clone()]; let ops = vec![CheckMultiSigVerifyAggregatePubKey(2, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone(), s_bob.clone()); let agg_pub_key = script.execute(&inputs).unwrap(); @@ -1461,7 +1469,7 @@ mod test { // 3 of 3 let keys = vec![p_alice.clone(), p_bob.clone(), p_carol]; let ops = vec![CheckMultiSigVerify(3, 3, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(Number(1), s_alice.clone(), s_bob.clone(), s_carol.clone()); let result = script.execute(&inputs).unwrap(); @@ -1479,21 +1487,21 @@ mod test { // errors let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSigVerify(0, 2, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone()); let err = script.execute(&inputs).unwrap_err(); assert_eq!(err, ScriptError::ValueExceedsBounds); let keys = vec![p_alice.clone(), p_bob.clone()]; let ops = vec![CheckMultiSigVerify(1, 0, keys, msg.clone())]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice.clone()); let err = script.execute(&inputs).unwrap_err(); assert_eq!(err, ScriptError::ValueExceedsBounds); let keys = vec![p_alice, p_bob]; let ops = vec![CheckMultiSigVerify(2, 1, keys, msg)]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(s_alice); let err = script.execute(&inputs).unwrap_err(); assert_eq!(err, ScriptError::ValueExceedsBounds); @@ -1507,7 +1515,7 @@ mod test { data[3].1.clone(), ]; let ops = vec![CheckMultiSigVerify(3, 4, keys, msg)]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!(Number(1), data[0].2.clone(), data[1].2.clone(), data[2].2.clone()); let result = script.execute(&inputs).unwrap(); assert_eq!(result, Number(1)); @@ -1524,7 +1532,7 @@ mod test { data[6].1.clone(), ]; let ops = vec![CheckMultiSigVerify(5, 7, keys, msg)]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); let inputs = inputs!( Number(1), data[0].2.clone(), @@ -1548,7 +1556,7 @@ mod test { // Unlike in Bitcoin where P2PKH includes a CheckSig at the end of the script, that part of the process is built // into definition of how TariScript is evaluated by a base node or wallet - let script = script!(Dup HashBlake256 PushHash(pkh) EqualVerify); + let script = script!(Dup HashBlake256 PushHash(pkh) EqualVerify).unwrap(); let hex_script = "71b07aae2337ce44f9ebb6169c863ec168046cb35ab4ef7aa9ed4f5f1f669bb74b09e581"; // Test serialisation assert_eq!(script.to_hex(), hex_script); @@ -1571,7 +1579,7 @@ mod test { let sig = CheckSigSchnorrSignature::sign(&secret_key, message, &mut rng).unwrap(); // Produce a script using the signature - let script = script!(CheckSig(slice_to_boxed_message(message.as_bytes()))); + let script = script!(CheckSig(slice_to_boxed_message(message.as_bytes()))).unwrap(); // Produce input satisfying the script let input = inputs!(sig, public_key); @@ -1626,7 +1634,7 @@ mod test { let lock_height = 4000u64; - let script = script!(Dup PushPubKey(Box::new(p_bob.clone())) CheckHeight(lock_height) GeZero IfThen PushPubKey(Box::new(p_alice.clone())) OrVerify(2) Else EqualVerify EndIf ); + let script = script!(Dup PushPubKey(Box::new(p_bob.clone())) CheckHeight(lock_height) GeZero IfThen PushPubKey(Box::new(p_alice.clone())) OrVerify(2) Else EqualVerify EndIf ).unwrap(); // Alice tries to spend the output before the height is reached let inputs_alice_spends_early = inputs!(p_alice.clone()); @@ -1695,7 +1703,7 @@ mod test { EndIf, EndIf, ]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); // alice let inputs = inputs!(s_alice); @@ -1723,7 +1731,7 @@ mod test { // Generate a test script let ops = vec![ToRistrettoPoint]; - let script = TariScript::new(ops); + let script = TariScript::new(ops).unwrap(); // Invalid stack type let inputs = inputs!(RistrettoPublicKey::default()); @@ -1771,7 +1779,7 @@ mod test { #[test] fn test_compare_height_block_height_exceeds_bounds() { - let script = script!(CompareHeight); + let script = script!(CompareHeight).unwrap(); let inputs = inputs!(0); let ctx = context_with_height(u64::MAX); @@ -1781,7 +1789,7 @@ mod test { #[test] fn test_compare_height_underflows() { - let script = script!(CompareHeight); + let script = script!(CompareHeight).unwrap(); let inputs = ExecutionStack::new(vec![Number(i64::MIN)]); let ctx = context_with_height(i64::MAX as u64); @@ -1791,7 +1799,7 @@ mod test { #[test] fn test_compare_height_underflows_on_empty_stack() { - let script = script!(CompareHeight); + let script = script!(CompareHeight).unwrap(); let inputs = ExecutionStack::new(vec![]); let ctx = context_with_height(i64::MAX as u64); @@ -1801,7 +1809,7 @@ mod test { #[test] fn test_compare_height_valid_with_uint_result() { - let script = script!(CompareHeight); + let script = script!(CompareHeight).unwrap(); let inputs = inputs!(100); let ctx = context_with_height(24_u64); @@ -1812,7 +1820,7 @@ mod test { #[test] fn test_compare_height_valid_with_int_result() { - let script = script!(CompareHeight); + let script = script!(CompareHeight).unwrap(); let inputs = inputs!(100); let ctx = context_with_height(110_u64); @@ -1823,7 +1831,7 @@ mod test { #[test] fn test_check_height_block_height_exceeds_bounds() { - let script = script!(CheckHeight(0)); + let script = script!(CheckHeight(0)).unwrap(); let inputs = ExecutionStack::new(vec![]); let ctx = context_with_height(u64::MAX); @@ -1833,7 +1841,7 @@ mod test { #[test] fn test_check_height_exceeds_bounds() { - let script = script!(CheckHeight(u64::MAX)); + let script = script!(CheckHeight(u64::MAX)).unwrap(); let inputs = ExecutionStack::new(vec![]); let ctx = context_with_height(10_u64); @@ -1843,7 +1851,7 @@ mod test { #[test] fn test_check_height_overflows_on_max_stack() { - let script = script!(CheckHeight(0)); + let script = script!(CheckHeight(0)).unwrap(); let mut inputs = ExecutionStack::new(vec![]); @@ -1858,7 +1866,7 @@ mod test { #[test] fn test_check_height_valid_with_uint_result() { - let script = script!(CheckHeight(24)); + let script = script!(CheckHeight(24)).unwrap(); let inputs = ExecutionStack::new(vec![]); let ctx = context_with_height(100_u64); @@ -1869,7 +1877,7 @@ mod test { #[test] fn test_check_height_valid_with_int_result() { - let script = script!(CheckHeight(100)); + let script = script!(CheckHeight(100)).unwrap(); let inputs = ExecutionStack::new(vec![]); let ctx = context_with_height(24_u64); diff --git a/integration_tests/src/transaction.rs b/integration_tests/src/transaction.rs index 98ca4e333e..1d91ddba09 100644 --- a/integration_tests/src/transaction.rs +++ b/integration_tests/src/transaction.rs @@ -106,7 +106,7 @@ impl TestTransactionBuilder { } async fn create_utxo(&mut self, key_manager: &MemoryDbKeyManager, num_inputs: usize) { - let script = script!(Nop); + let script = script!(Nop).unwrap(); let features = OutputFeatures::default(); let covenant = Covenant::default(); let value = self.amount -