Repository: rust-bitcoin/rust-bitcoin
Pull request #1837 (2023-05-04 19:02:22)

feat: generate PrivateKey
added a function to generate a private key

Resolves: #1823

sanket1729: Can you squash everything into a single commit?
kshitjj: @sanket1729 how do you squash everything into one single commit?
Kixunil: You will need to squash again since we require that every commit passes test suite.

Patch:
diff --git a/README.md b/README.md
index 7bfd272c..0a911a57 100644
--- a/README.md
+++ b/README.md
@@ -31,37 +31,43 @@ Supports (or should support)
 For JSONRPC interaction with Bitcoin Core, it is recommended to use
 [rust-bitcoincore-rpc](https://github.com/rust-bitcoin/rust-bitcoincore-rpc).
 
-It is recommended to always use [cargo-crev](https://github.com/crev-dev/cargo-crev) to verify the
-trustworthiness of each of your dependencies, including this one.
+It is recommended to always use [cargo-crev](https://github.com/crev-dev/cargo-crev)
+to verify the trustworthiness of each of your dependencies, including this one.
 
 ## Known limitations
 
 ### Consensus
 
-This library **must not** be used for consensus code (i.e. fully validating blockchain data). It
-technically supports doing this, but doing so is very ill-advised because there are many deviations,
-known and unknown, between this library and the Bitcoin Core reference implementation. In a
-consensus based cryptocurrency such as Bitcoin it is critical that all parties are using the same
-rules to validate data, and this library is simply unable to implement the same rules as Core.
+This library **must not** be used for consensus code (i.e. fully validating
+blockchain data). It technically supports doing this, but doing so is very
+ill-advised because there are many deviations, known and unknown, between
+this library and the Bitcoin Core reference implementation. In a consensus
+based cryptocurrency such as Bitcoin it is critical that all parties are
+using the same rules to validate data, and this library is simply unable
+to implement the same rules as Core.
 
-Given the complexity of both C++ and Rust, it is unlikely that this will ever be fixed, and there
-are no plans to do so. Of course, patches to fix specific consensus incompatibilities are welcome.
+Given the complexity of both C++ and Rust, it is unlikely that this will
+ever be fixed, and there are no plans to do so. Of course, patches to
+fix specific consensus incompatibilities are welcome.
 
 ### Support for 16-bit pointer sizes
 
-16-bit pointer sizes are not supported and we can't promise they will be. If you care about them
-please let us know, so we can know how large the interest is and possibly decide to support them.
+16-bit pointer sizes are not supported and we can't promise they will be.
+If you care about them please let us know, so we can know how large the interest
+is and possibly decide to support them.
 
 ## Documentation
 
-Currently can be found on [docs.rs/bitcoin](https://docs.rs/bitcoin/). Patches to add usage examples
-and to expand on existing docs would be extremely appreciated.
+Currently can be found on [docs.rs/bitcoin](https://docs.rs/bitcoin/).
+Patches to add usage examples and to expand on existing docs would be extremely
+appreciated.
 
 ## Contributing
 
-Contributions are generally welcome. If you intend to make larger changes please discuss them in an
-issue before PRing them to avoid duplicate work and architectural mismatches. If you have any
-questions or ideas you want to discuss please join us in
+Contributions are generally welcome. If you intend to make larger changes please
+discuss them in an issue before PRing them to avoid duplicate work and
+architectural mismatches. If you have any questions or ideas you want to discuss
+please join us in
 [#bitcoin-rust](https://web.libera.chat/?channel=#bitcoin-rust) on
 [libera.chat](https://libera.chat).
 
@@ -94,20 +100,18 @@ review them.
 
 ## Installing Rust
 
-Rust can be installed using your package manager of choice or [rustup.rs](https://rustup.rs). The
-former way is considered more secure since it typically doesn't involve trust in the CA system. But
-you should be aware that the version of Rust shipped by your distribution might be out of date.
-Generally this isn't a problem for `rust-bitcoin` since we support much older versions than the
-current stable one (see MSRV section).
+Rust can be installed using your package manager of choice or
+[rustup.rs](https://rustup.rs). The former way is considered more secure since
+it typically doesn't involve trust in the CA system. But you should be aware
+that the version of Rust shipped by your distribution might be out of date.
+Generally this isn't a problem for `rust-bitcoin` since we support much older
+versions than the current stable one (see MSRV section).
 
 ## Building
 
-The cargo feature `std` is enabled by default. At least one of the features `std` or `no-std` or
-both must be enabled.
+The cargo feature `std` is enabled by default. At least one of the features `std` or `no-std` or both must be enabled.
 
-Enabling the `no-std` feature does not disable `std`. To disable the `std` feature you must disable
-default features. The `no-std` feature only enables additional features required for this crate to
-be usable without `std`. Both can be enabled without conflict.
+Enabling the `no-std` feature does not disable `std`. To disable the `std` feature you must disable default features. The `no-std` feature only enables additional features required for this crate to be usable without `std`. Both can be enabled without conflict.
 
 The library can be built and tested using [`cargo`](https://github.com/rust-lang/cargo/):
 
@@ -123,13 +127,12 @@ You can run tests with:
 cargo test
 ```
 
-Please refer to the [`cargo` documentation](https://doc.rust-lang.org/stable/cargo/) for more
-detailed instructions.
+Please refer to the [`cargo` documentation](https://doc.rust-lang.org/stable/cargo/) for more detailed instructions.
 
 ### Building the docs
 
-We build docs with the nightly toolchain, you may wish to use the following shell alias to check
-your documentation changes build correctly.
+We build docs with the nightly toolchain, you may wish to use the following
+shell alias to check your documentation changes build correctly.
 
 ```
 alias build-docs='RUSTDOCFLAGS="--cfg docsrs" cargo +nightly rustdoc --features="$FEATURES" -- -D rustdoc::broken-intra-doc-links'
@@ -165,24 +168,25 @@ then run with `RUSTFLAGS='--cfg=mutate' cargo +nightly mutagen`.
 
 ### Code verification
 
-We have started using [kani](https://github.com/model-checking/kani), install with `cargo install --locked kani-verifier`
- (no need to run `cargo kani setup`). Run the tests with `cargo kani`.
+We have started using [kani](https://github.com/model-checking/kani), install with `cargo install
+--locked kani-verifier` (no need to run `cargo kani setup`). Run the tests with `cargo kani`.
 
 ## Pull Requests
 
-Every PR needs at least two reviews to get merged. During the review phase maintainers and
-contributors are likely to leave comments and request changes. Please try to address them, otherwise
-your PR might get closed without merging after a longer time of inactivity. If your PR isn't ready
-for review yet please mark it by prefixing the title with `WIP: `.
+Every PR needs at least two reviews to get merged. During the review phase
+maintainers and contributors are likely to leave comments and request changes.
+Please try to address them, otherwise your PR might get closed without merging
+after a longer time of inactivity. If your PR isn't ready for review yet please
+mark it by prefixing the title with `WIP: `.
 
 ### CI Pipeline
 
 The CI pipeline requires approval before being run on each MR.
 
 In order to speed up the review process the CI pipeline can be run locally using
-[act](https://github.com/nektos/act). The `fuzz` and `Cross` jobs will be skipped when using `act`
-due to caching being unsupported at this time. We do not *actively* support `act` but will merge PRs
-fixing `act` issues.
+[act](https://github.com/nektos/act). The `fuzz` and `Cross` jobs will be
+skipped when using `act` due to caching being unsupported at this time. We do
+not *actively* support `act` but will merge PRs fixing `act` issues.
 
 ### Githooks
 
@@ -197,12 +201,16 @@ Alternatively add symlinks in your `.git/hooks` directory to any of the githooks
 
 ## Policy on Altcoins/Altchains
 
-Since the altcoin landscape includes projects which [frequently appear and disappear, and are poorly
-designed anyway](https://download.wpsoftware.net/bitcoin/alts.pdf) we do not support any altcoins.
-Supporting Bitcoin properly is already difficult enough and we do not want to increase the
-maintenance burden and decrease API stability by adding support for other coins.
+Patches which add support for non-Bitcoin cryptocurrencies by adding constants
+to existing enums (e.g. to set the network message magic-byte sequence) are
+welcome. Anything more involved will be considered on a case-by-case basis,
+as the altcoin landscape includes projects which [frequently appear and
+disappear, and are poorly designed anyway](https://download.wpsoftware.net/bitcoin/alts.pdf)
+and keeping the codebase maintainable is a large priority.
 
-Our code is public domain so by all means fork it and go wild :)
+In general, things that improve cross-chain compatibility (e.g. support for
+cross-chain atomic swaps) are more likely to be accepted than things which
+support only a single blockchain.
 
 
 ## Release Notes
@@ -216,5 +224,6 @@ Release notes are done per crate, see:
 
 ## Licensing
 
-The code in this project is licensed under the [Creative Commons CC0 1.0 Universal license](LICENSE).
-We use the [SPDX license list](https://spdx.org/licenses/) and [SPDX IDs](https://spdx.dev/ids/).
+The code in this project is licensed under the [Creative Commons CC0 1.0
+Universal license](LICENSE). We use the [SPDX license list](https://spdx.org/licenses/) and [SPDX
+IDs](https://spdx.dev/ids/).
diff --git a/bitcoin/examples/ecdsa-psbt.rs b/bitcoin/examples/ecdsa-psbt.rs
index f3609a47..cdee6755 100644
--- a/bitcoin/examples/ecdsa-psbt.rs
+++ b/bitcoin/examples/ecdsa-psbt.rs
@@ -192,8 +192,11 @@ fn create_psbt<C: Verification>(&self, secp: &Secp256k1<C>) -> Result<Psbt> {
                 witness: Witness::default(),
             }],
             output: vec![
-                TxOut { value: to_amount, script_pubkey: to_address.script_pubkey() },
-                TxOut { value: change_amount, script_pubkey: change_address.script_pubkey() },
+                TxOut { value: to_amount.to_sat(), script_pubkey: to_address.script_pubkey() },
+                TxOut {
+                    value: change_amount.to_sat(),
+                    script_pubkey: change_address.script_pubkey(),
+                },
             ],
         };
 
@@ -279,7 +282,7 @@ fn previous_output() -> TxOut {
         .expect("failed to parse input utxo scriptPubkey");
     let amount = Amount::from_str(INPUT_UTXO_VALUE).expect("failed to parse input utxo value");
 
-    TxOut { value: amount, script_pubkey }
+    TxOut { value: amount.to_sat(), script_pubkey }
 }
 
 struct Error(Box<dyn std::error::Error>);
diff --git a/bitcoin/examples/taproot-psbt.rs b/bitcoin/examples/taproot-psbt.rs
index 0ad84de0..62b95356 100644
--- a/bitcoin/examples/taproot-psbt.rs
+++ b/bitcoin/examples/taproot-psbt.rs
@@ -40,7 +40,7 @@
     "5120be27fa8b1f5278faf82cab8da23e8761f8f9bd5d5ebebbb37e0e12a70d92dd16";
 const UTXO_PUBKEY: &str = "a6ac32163539c16b6b5dbbca01b725b8e8acaa5f821ba42c80e7940062140d19";
 const UTXO_MASTER_FINGERPRINT: &str = "e61b318f";
-const ABSOLUTE_FEES_IN_SATS: Amount = Amount::from_sat(1_000);
+const ABSOLUTE_FEES_IN_SATS: u64 = 1000;
 
 // UTXO_1 will be used for spending example 1
 const UTXO_1: P2trUtxo = P2trUtxo {
@@ -49,7 +49,7 @@
     script_pubkey: UTXO_SCRIPT_PUBKEY,
     pubkey: UTXO_PUBKEY,
     master_fingerprint: UTXO_MASTER_FINGERPRINT,
-    amount_in_sats: Amount::from_sat(50 * 100_000_000), // 50 BTC
+    amount_in_sats: 50 * COIN_VALUE, // 50 BTC
     derivation_path: BIP86_DERIVATION_PATH,
 };
 
@@ -60,7 +60,7 @@
     script_pubkey: UTXO_SCRIPT_PUBKEY,
     pubkey: UTXO_PUBKEY,
     master_fingerprint: UTXO_MASTER_FINGERPRINT,
-    amount_in_sats: Amount::from_sat(50 * 100_000_000), // 50 BTC
+    amount_in_sats: 50 * COIN_VALUE,
     derivation_path: BIP86_DERIVATION_PATH,
 };
 
@@ -71,7 +71,7 @@
     script_pubkey: UTXO_SCRIPT_PUBKEY,
     pubkey: UTXO_PUBKEY,
     master_fingerprint: UTXO_MASTER_FINGERPRINT,
-    amount_in_sats: Amount::from_sat(50 * 100_000_000), // 50 BTC
+    amount_in_sats: 50 * COIN_VALUE,
     derivation_path: BIP86_DERIVATION_PATH,
 };
 
@@ -80,6 +80,7 @@
 
 use bitcoin::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey, Fingerprint};
 use bitcoin::consensus::encode;
+use bitcoin::constants::COIN_VALUE;
 use bitcoin::key::{TapTweak, XOnlyPublicKey};
 use bitcoin::opcodes::all::{OP_CHECKSIG, OP_CLTV, OP_DROP};
 use bitcoin::psbt::{self, Input, Output, Psbt, PsbtSighashType};
@@ -104,7 +105,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
     let change_address =
         Address::from_str("bcrt1pz449kexzydh2kaypatup5ultru3ej284t6eguhnkn6wkhswt0l7q3a7j76")?
             .require_network(Network::Regtest)?;
-    let amount_to_send_in_sats = Amount::ONE_BTC;
+    let amount_to_send_in_sats = COIN_VALUE;
     let change_amount = UTXO_1
         .amount_in_sats
         .checked_sub(amount_to_send_in_sats)
@@ -215,7 +216,7 @@ struct P2trUtxo<'a> {
     script_pubkey: &'a str,
     pubkey: &'a str,
     master_fingerprint: &'a str,
-    amount_in_sats: Amount,
+    amount_in_sats: u64,
     derivation_path: &'a str,
 }
 
@@ -258,7 +259,9 @@ fn generate_bip86_key_spend_tx(
         witness_utxo: {
             let script_pubkey = ScriptBuf::from_hex(input_utxo.script_pubkey)
                 .expect("failed to parse input utxo scriptPubkey");
-            Some(TxOut { value: from_amount, script_pubkey })
+            let amount = Amount::from_sat(from_amount);
+
+            Some(TxOut { value: amount.to_sat(), script_pubkey })
         },
         tap_key_origins: origins,
         ..Default::default()
@@ -445,7 +448,9 @@ fn create_inheritance_funding_tx(
         let input = Input {
             witness_utxo: {
                 let script_pubkey = script_pubkey;
-                Some(TxOut { value, script_pubkey })
+                let amount = Amount::from_sat(value);
+
+                Some(TxOut { value: amount.to_sat(), script_pubkey })
             },
             tap_key_origins: origins,
             tap_merkle_root: taproot_spend_info.merkle_root(),
@@ -589,9 +594,9 @@ fn refresh_tx(
             let input = Input {
                 witness_utxo: {
                     let script_pubkey = output_script_pubkey;
-                    let amount = output_value;
+                    let amount = Amount::from_sat(output_value);
 
-                    Some(TxOut { value: amount, script_pubkey })
+                    Some(TxOut { value: amount.to_sat(), script_pubkey })
                 },
                 tap_key_origins: origins,
                 tap_merkle_root: taproot_spend_info.merkle_root(),
diff --git a/bitcoin/src/address.rs b/bitcoin/src/address.rs
index 08038f2a..606f5ac4 100644
--- a/bitcoin/src/address.rs
+++ b/bitcoin/src/address.rs
@@ -615,7 +615,7 @@ impl NetworkValidation for super::NetworkUnchecked {}
 
 /// Marker of status of address's network validation. See section [*Parsing addresses*](Address#parsing-addresses)
 /// on [`Address`] for details.
-pub trait NetworkValidation: sealed::NetworkValidation + Sync + Send + Sized + Unpin {
+pub trait NetworkValidation: sealed::NetworkValidation {
     /// Indicates whether this `NetworkValidation` is `NetworkChecked` or not.
     const IS_CHECKED: bool;
 }
@@ -747,18 +747,21 @@ pub struct Address<V = NetworkChecked>(AddressInner, PhantomData<V>)
     V: NetworkValidation;
 
 #[cfg(feature = "serde")]
-struct DisplayUnchecked<'a, N: NetworkValidation>(&'a Address<N>);
+struct DisplayUnchecked<'a>(&'a Address<NetworkUnchecked>);
 
 #[cfg(feature = "serde")]
-impl<N: NetworkValidation> fmt::Display for DisplayUnchecked<'_, N> {
+impl fmt::Display for DisplayUnchecked<'_> {
     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_internal(fmt) }
 }
 
+#[cfg(feature = "serde")]
+crate::serde_utils::serde_string_serialize_impl!(Address, "a Bitcoin address");
+
 #[cfg(feature = "serde")]
 crate::serde_utils::serde_string_deserialize_impl!(Address<NetworkUnchecked>, "a Bitcoin address");
 
 #[cfg(feature = "serde")]
-impl<N: NetworkValidation> serde::Serialize for Address<N> {
+impl serde::Serialize for Address<NetworkUnchecked> {
     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
     where
         S: serde::Serializer,
diff --git a/bitcoin/src/amount.rs b/bitcoin/src/amount.rs
index 2b1e95c4..5f3b285b 100644
--- a/bitcoin/src/amount.rs
+++ b/bitcoin/src/amount.rs
@@ -11,8 +11,6 @@
 use core::str::FromStr;
 use core::{default, ops};
 
-use crate::consensus::encode::{self, Decodable, Encodable};
-use crate::io;
 use crate::prelude::*;
 
 /// A set of denominations in which amounts can be expressed.
@@ -485,8 +483,6 @@ fn fmt_satoshi_in(
 /// the checked arithmetic methods.
 ///
 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
-#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
-#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
 pub struct Amount(u64);
 
 impl Amount {
@@ -498,10 +494,6 @@ impl Amount {
     pub const ONE_BTC: Amount = Amount(100_000_000);
     /// The maximum value allowed as an amount. Useful for sanity checking.
     pub const MAX_MONEY: Amount = Amount(21_000_000 * 100_000_000);
-    /// The minimum value of an amount.
-    pub const MIN: Amount = Amount::ZERO;
-    /// The maximum value of an amount.
-    pub const MAX: Amount = Amount(u64::MAX);
 
     /// Create an [Amount] with satoshi precision and the given number of satoshis.
     pub const fn from_sat(satoshi: u64) -> Amount { Amount(satoshi) }
@@ -510,11 +502,9 @@ pub const fn from_sat(satoshi: u64) -> Amount { Amount(satoshi) }
     pub fn to_sat(self) -> u64 { self.0 }
 
     /// The maximum value of an [Amount].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Amount { Amount(u64::max_value()) }
 
     /// The minimum value of an [Amount].
-    #[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
     pub const fn min_value() -> Amount { Amount(u64::min_value()) }
 
     /// Convert from a value expressing bitcoins to an [Amount].
@@ -531,7 +521,7 @@ pub fn from_str_in(s: &str, denom: Denomination) -> Result<Amount, ParseAmountEr
         if negative {
             return Err(ParseAmountError::Negative);
         }
-        if satoshi > i64::MAX as u64 {
+        if satoshi > i64::max_value() as u64 {
             return Err(ParseAmountError::TooBig);
         }
         Ok(Amount::from_sat(satoshi))
@@ -656,7 +646,7 @@ pub fn checked_rem(self, rhs: u64) -> Option<Amount> { self.0.checked_rem(rhs).m
 
     /// Convert to a signed amount.
     pub fn to_signed(self) -> Result<SignedAmount, ParseAmountError> {
-        if self.to_sat() > SignedAmount::MAX.to_sat() as u64 {
+        if self.to_sat() > SignedAmount::max_value().to_sat() as u64 {
             Err(ParseAmountError::TooBig)
         } else {
             Ok(SignedAmount::from_sat(self.to_sat() as i64))
@@ -664,20 +654,6 @@ pub fn to_signed(self) -> Result<SignedAmount, ParseAmountError> {
     }
 }
 
-impl Decodable for Amount {
-    #[inline]
-    fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
-        Ok(Amount(Decodable::consensus_decode(r)?))
-    }
-}
-
-impl Encodable for Amount {
-    #[inline]
-    fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
-        self.0.consensus_encode(w)
-    }
-}
-
 impl default::Default for Amount {
     fn default() -> Self { Amount::ZERO }
 }
@@ -853,10 +829,6 @@ impl SignedAmount {
     pub const ONE_BTC: SignedAmount = SignedAmount(100_000_000);
     /// The maximum value allowed as an amount. Useful for sanity checking.
     pub const MAX_MONEY: SignedAmount = SignedAmount(21_000_000 * 100_000_000);
-    /// The minimum value of an amount.
-    pub const MIN: SignedAmount = SignedAmount(i64::MIN);
-    /// The maximum value of an amount.
-    pub const MAX: SignedAmount = SignedAmount(i64::MAX);
 
     /// Create an [SignedAmount] with satoshi precision and the given number of satoshis.
     pub const fn from_sat(satoshi: i64) -> SignedAmount { SignedAmount(satoshi) }
@@ -865,11 +837,9 @@ pub const fn from_sat(satoshi: i64) -> SignedAmount { SignedAmount(satoshi) }
     pub fn to_sat(self) -> i64 { self.0 }
 
     /// The maximum value of an [SignedAmount].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> SignedAmount { SignedAmount(i64::max_value()) }
 
     /// The minimum value of an [SignedAmount].
-    #[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
     pub const fn min_value() -> SignedAmount { SignedAmount(i64::min_value()) }
 
     /// Convert from a value expressing bitcoins to an [SignedAmount].
@@ -883,7 +853,7 @@ pub fn from_btc(btc: f64) -> Result<SignedAmount, ParseAmountError> {
     /// with denomination, use [FromStr].
     pub fn from_str_in(s: &str, denom: Denomination) -> Result<SignedAmount, ParseAmountError> {
         let (negative, satoshi) = parse_signed_to_satoshi(s, denom)?;
-        if satoshi > i64::MAX as u64 {
+        if satoshi > i64::max_value() as u64 {
             return Err(ParseAmountError::TooBig);
         }
         Ok(match negative {
@@ -1002,7 +972,7 @@ pub fn is_positive(self) -> bool { self.0.is_positive() }
     pub fn is_negative(self) -> bool { self.0.is_negative() }
 
     /// Get the absolute value of this [SignedAmount].
-    /// Returns [None] if overflow occurred. (`self == MIN`)
+    /// Returns [None] if overflow occurred. (`self == min_value()`)
     pub fn checked_abs(self) -> Option<SignedAmount> { self.0.checked_abs().map(SignedAmount) }
 
     /// Checked addition.
@@ -1605,7 +1575,7 @@ fn mul_div() {
     #[test]
     fn test_overflows() {
         // panic on overflow
-        let result = panic::catch_unwind(|| Amount::MAX + Amount::from_sat(1));
+        let result = panic::catch_unwind(|| Amount::max_value() + Amount::from_sat(1));
         assert!(result.is_err());
         let result = panic::catch_unwind(|| Amount::from_sat(8446744073709551615) * 3);
         assert!(result.is_err());
@@ -1616,10 +1586,10 @@ fn checked_arithmetic() {
         let sat = Amount::from_sat;
         let ssat = SignedAmount::from_sat;
 
-        assert_eq!(SignedAmount::MAX.checked_add(ssat(1)), None);
-        assert_eq!(SignedAmount::MIN.checked_sub(ssat(1)), None);
-        assert_eq!(Amount::MAX.checked_add(sat(1)), None);
-        assert_eq!(Amount::MIN.checked_sub(sat(1)), None);
+        assert_eq!(SignedAmount::max_value().checked_add(ssat(1)), None);
+        assert_eq!(SignedAmount::min_value().checked_sub(ssat(1)), None);
+        assert_eq!(Amount::max_value().checked_add(sat(1)), None);
+        assert_eq!(Amount::min_value().checked_sub(sat(1)), None);
 
         assert_eq!(sat(5).checked_div(2), Some(sat(2))); // integer division
         assert_eq!(ssat(-6).checked_div(2), Some(ssat(-3)));
@@ -1648,11 +1618,11 @@ fn floating_point() {
         assert_eq!(sf(-184467440738.0, D::Bitcoin), Err(ParseAmountError::TooBig));
         assert_eq!(f(18446744073709551617.0, D::Satoshi), Err(ParseAmountError::TooBig));
         assert_eq!(
-            f(SignedAmount::MAX.to_float_in(D::Satoshi) + 1.0, D::Satoshi),
+            f(SignedAmount::max_value().to_float_in(D::Satoshi) + 1.0, D::Satoshi),
             Err(ParseAmountError::TooBig)
         );
         assert_eq!(
-            f(Amount::MAX.to_float_in(D::Satoshi) + 1.0, D::Satoshi),
+            f(Amount::max_value().to_float_in(D::Satoshi) + 1.0, D::Satoshi),
             Err(ParseAmountError::TooBig)
         );
 
@@ -1681,7 +1651,7 @@ fn parsing() {
         assert_eq!(p("-1.0x", btc), Err(E::InvalidCharacter('x')));
         assert_eq!(p("0.0 ", btc), Err(ParseAmountError::InvalidCharacter(' ')));
         assert_eq!(p("0.000.000", btc), Err(E::InvalidFormat));
-        let more_than_max = format!("1{}", Amount::MAX);
+        let more_than_max = format!("1{}", Amount::max_value());
         assert_eq!(p(&more_than_max, btc), Err(E::TooBig));
         assert_eq!(p("0.000000042", btc), Err(E::TooPrecise));
 
@@ -1698,8 +1668,8 @@ fn parsing() {
             Ok(Amount::from_sat(12_345_678_901__123_456_78))
         );
 
-        // make sure satoshi > i64::MAX is checked.
-        let amount = Amount::from_sat(i64::MAX as u64);
+        // make sure satoshi > i64::max_value() is checked.
+        let amount = Amount::from_sat(i64::max_value() as u64);
         assert_eq!(Amount::from_str_in(&amount.to_string_in(sat), sat), Ok(amount));
         assert_eq!(
             Amount::from_str_in(&(amount + Amount(1)).to_string_in(sat), sat),
@@ -1930,13 +1900,16 @@ fn test_unsigned_signed_conversion() {
         let sa = SignedAmount::from_sat;
         let ua = Amount::from_sat;
 
-        assert_eq!(Amount::MAX.to_signed(), Err(E::TooBig));
-        assert_eq!(ua(i64::MAX as u64).to_signed(), Ok(sa(i64::MAX)));
-        assert_eq!(ua(i64::MAX as u64 + 1).to_signed(), Err(E::TooBig));
+        assert_eq!(Amount::max_value().to_signed(), Err(E::TooBig));
+        assert_eq!(ua(i64::max_value() as u64).to_signed(), Ok(sa(i64::max_value())));
+        assert_eq!(ua(i64::max_value() as u64 + 1).to_signed(), Err(E::TooBig));
 
-        assert_eq!(sa(i64::MAX).to_unsigned(), Ok(ua(i64::MAX as u64)));
+        assert_eq!(sa(i64::max_value()).to_unsigned(), Ok(ua(i64::max_value() as u64)));
 
-        assert_eq!(sa(i64::MAX).to_unsigned().unwrap().to_signed(), Ok(sa(i64::MAX)));
+        assert_eq!(
+            sa(i64::max_value()).to_unsigned().unwrap().to_signed(),
+            Ok(sa(i64::max_value()))
+        );
     }
 
     #[test]
@@ -2024,7 +1997,7 @@ fn to_from_string_in() {
             Ok(ua_sat(1_000_000_000_000))
         );
         assert_eq!(
-            ua_str(&ua_sat(u64::MAX).to_string_in(D::MilliBitcoin), D::MilliBitcoin),
+            ua_str(&ua_sat(u64::max_value()).to_string_in(D::MilliBitcoin), D::MilliBitcoin),
             Err(ParseAmountError::TooBig)
         );
 
@@ -2034,12 +2007,12 @@ fn to_from_string_in() {
         );
 
         assert_eq!(
-            sa_str(&sa_sat(i64::MAX).to_string_in(D::Satoshi), D::MicroBitcoin),
+            sa_str(&sa_sat(i64::max_value()).to_string_in(D::Satoshi), D::MicroBitcoin),
             Err(ParseAmountError::TooBig)
         );
         // Test an overflow bug in `abs()`
         assert_eq!(
-            sa_str(&sa_sat(i64::MIN).to_string_in(D::Satoshi), D::MicroBitcoin),
+            sa_str(&sa_sat(i64::min_value()).to_string_in(D::Satoshi), D::MicroBitcoin),
             Err(ParseAmountError::TooBig)
         );
 
@@ -2048,11 +2021,11 @@ fn to_from_string_in() {
             Ok(sa_sat(-1))
         );
         assert_eq!(
-            sa_str(&sa_sat(i64::MAX).to_string_in(D::Satoshi), D::NanoBitcoin),
+            sa_str(&sa_sat(i64::max_value()).to_string_in(D::Satoshi), D::NanoBitcoin),
             Err(ParseAmountError::TooPrecise)
         );
         assert_eq!(
-            sa_str(&sa_sat(i64::MIN).to_string_in(D::Satoshi), D::NanoBitcoin),
+            sa_str(&sa_sat(i64::min_value()).to_string_in(D::Satoshi), D::NanoBitcoin),
             Err(ParseAmountError::TooPrecise)
         );
 
@@ -2061,11 +2034,11 @@ fn to_from_string_in() {
             Ok(sa_sat(-1))
         );
         assert_eq!(
-            sa_str(&sa_sat(i64::MAX).to_string_in(D::Satoshi), D::PicoBitcoin),
+            sa_str(&sa_sat(i64::max_value()).to_string_in(D::Satoshi), D::PicoBitcoin),
             Err(ParseAmountError::TooPrecise)
         );
         assert_eq!(
-            sa_str(&sa_sat(i64::MIN).to_string_in(D::Satoshi), D::PicoBitcoin),
+            sa_str(&sa_sat(i64::min_value()).to_string_in(D::Satoshi), D::PicoBitcoin),
             Err(ParseAmountError::TooPrecise)
         );
     }
@@ -2267,12 +2240,12 @@ fn checked_sum_amounts() {
         assert_eq!(Some(Amount::from_sat(1400)), sum);
 
         let amounts =
-            vec![Amount::from_sat(u64::MAX), Amount::from_sat(1337), Amount::from_sat(21)];
+            vec![Amount::from_sat(u64::max_value()), Amount::from_sat(1337), Amount::from_sat(21)];
         let sum = amounts.into_iter().checked_sum();
         assert_eq!(None, sum);
 
         let amounts = vec![
-            SignedAmount::from_sat(i64::MIN),
+            SignedAmount::from_sat(i64::min_value()),
             SignedAmount::from_sat(-1),
             SignedAmount::from_sat(21),
         ];
@@ -2280,7 +2253,7 @@ fn checked_sum_amounts() {
         assert_eq!(None, sum);
 
         let amounts = vec![
-            SignedAmount::from_sat(i64::MAX),
+            SignedAmount::from_sat(i64::max_value()),
             SignedAmount::from_sat(1),
             SignedAmount::from_sat(21),
         ];
diff --git a/bitcoin/src/bip152.rs b/bitcoin/src/bip152.rs
index 380a8402..05e6a2bc 100644
--- a/bitcoin/src/bip152.rs
+++ b/bitcoin/src/bip152.rs
@@ -378,8 +378,7 @@ mod test {
     use crate::consensus::encode::{deserialize, serialize};
     use crate::hash_types::TxMerkleNode;
     use crate::{
-        Amount, CompactTarget, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid,
-        Witness,
+        CompactTarget, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness,
     };
 
     fn dummy_tx(nonce: &[u8]) -> Transaction {
@@ -392,7 +391,7 @@ fn dummy_tx(nonce: &[u8]) -> Transaction {
                 sequence: Sequence(1),
                 witness: Witness::new(),
             }],
-            output: vec![TxOut { value: Amount::ONE_SAT, script_pubkey: ScriptBuf::new() }],
+            output: vec![TxOut { value: 1, script_pubkey: ScriptBuf::new() }],
         }
     }
 
diff --git a/bitcoin/src/blockdata/constants.rs b/bitcoin/src/blockdata/constants.rs
index 8a368d45..f8825ef7 100644
--- a/bitcoin/src/blockdata/constants.rs
+++ b/bitcoin/src/blockdata/constants.rs
@@ -22,8 +22,9 @@
 use crate::internal_macros::impl_bytes_newtype;
 use crate::network::constants::Network;
 use crate::pow::CompactTarget;
-use crate::Amount;
 
+/// How many satoshis are in "one bitcoin".
+pub const COIN_VALUE: u64 = 100_000_000;
 /// How many seconds between blocks we expect on average.
 pub const TARGET_BLOCK_SPACING: u32 = 600;
 /// How many blocks between diffchanges.
@@ -60,6 +61,11 @@
 /// Number of blocks needed for an output from a coinbase transaction to be spendable.
 pub const COINBASE_MATURITY: u32 = 100;
 
+/// The maximum value allowed in an output (useful for sanity checking,
+/// since keeping everything below this value should prevent overflows
+/// if you are doing anything remotely sane with monetary values).
+pub const MAX_MONEY: u64 = 21_000_000 * COIN_VALUE;
+
 /// Constructs and returns the coinbase (and only) transaction of the Bitcoin genesis block.
 fn bitcoin_genesis_tx() -> Transaction {
     // Base
@@ -87,7 +93,7 @@ fn bitcoin_genesis_tx() -> Transaction {
     let script_bytes = hex!("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f");
     let out_script =
         script::Builder::new().push_slice(script_bytes).push_opcode(OP_CHECKSIG).into_script();
-    ret.output.push(TxOut { value: Amount::from_sat(50 * 100_000_000), script_pubkey: out_script });
+    ret.output.push(TxOut { value: 50 * COIN_VALUE, script_pubkey: out_script });
 
     // end
     ret
@@ -192,8 +198,6 @@ pub fn from_genesis_block_hash(block_hash: crate::BlockHash) -> Self {
 
 #[cfg(test)]
 mod test {
-    use core::str::FromStr;
-
     use super::*;
     use crate::blockdata::locktime::absolute;
     use crate::consensus::encode::serialize;
@@ -215,7 +219,7 @@ fn bitcoin_genesis_first_transaction() {
         assert_eq!(gen.output.len(), 1);
         assert_eq!(serialize(&gen.output[0].script_pubkey),
                    hex!("434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac"));
-        assert_eq!(gen.output[0].value, Amount::from_str("50 BTC").unwrap());
+        assert_eq!(gen.output[0].value, 50 * COIN_VALUE);
         assert_eq!(gen.lock_time, absolute::LockTime::ZERO);
 
         assert_eq!(
diff --git a/bitcoin/src/blockdata/fee_rate.rs b/bitcoin/src/blockdata/fee_rate.rs
index 100ab9e4..45f83322 100644
--- a/bitcoin/src/blockdata/fee_rate.rs
+++ b/bitcoin/src/blockdata/fee_rate.rs
@@ -28,10 +28,10 @@ impl FeeRate {
     /// Minimum possible value (0 sat/kwu).
     ///
     /// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts.
-    pub const MIN: FeeRate = FeeRate::ZERO;
+    pub const MIN: FeeRate = FeeRate(u64::min_value());
 
     /// Maximum possible value.
-    pub const MAX: FeeRate = FeeRate(u64::MAX);
+    pub const MAX: FeeRate = FeeRate(u64::max_value());
 
     /// Minimum fee rate required to broadcast a transaction.
     ///
@@ -128,8 +128,8 @@ mod tests {
     #[test]
     fn fee_rate_const_test() {
         assert_eq!(0, FeeRate::ZERO.to_sat_per_kwu());
-        assert_eq!(u64::MIN, FeeRate::MIN.to_sat_per_kwu());
-        assert_eq!(u64::MAX, FeeRate::MAX.to_sat_per_kwu());
+        assert_eq!(u64::min_value(), FeeRate::MIN.to_sat_per_kwu());
+        assert_eq!(u64::max_value(), FeeRate::MAX.to_sat_per_kwu());
         assert_eq!(250, FeeRate::BROADCAST_MIN.to_sat_per_kwu());
         assert_eq!(750, FeeRate::DUST.to_sat_per_kwu());
     }
diff --git a/bitcoin/src/blockdata/locktime/absolute.rs b/bitcoin/src/blockdata/locktime/absolute.rs
index 95e31242..957a50e0 100644
--- a/bitcoin/src/blockdata/locktime/absolute.rs
+++ b/bitcoin/src/blockdata/locktime/absolute.rs
@@ -397,13 +397,11 @@ impl Height {
     /// The minimum absolute block height (0), the genesis block.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MIN`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
     pub const fn min_value() -> Self { Self::MIN }
 
     /// The maximum absolute block height.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MAX`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Self { Self::MAX }
 
     /// Constructs a new block height.
@@ -479,13 +477,11 @@ impl Time {
     /// The minimum absolute block time.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MIN`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
     pub const fn min_value() -> Self { Self::MIN }
 
     /// The maximum absolute block time.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MAX`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Self { Self::MAX }
 
     /// Constructs a new block time.
diff --git a/bitcoin/src/blockdata/locktime/relative.rs b/bitcoin/src/blockdata/locktime/relative.rs
index d2bdfa97..4d596acc 100644
--- a/bitcoin/src/blockdata/locktime/relative.rs
+++ b/bitcoin/src/blockdata/locktime/relative.rs
@@ -210,13 +210,11 @@ impl Height {
     /// The minimum relative block height (0), can be included in any block.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MIN`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
     pub const fn min_value() -> Self { Self::MIN }
 
     /// The maximum relative block height.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Height::MAX`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Self { Self::MAX }
 
     /// Returns the inner `u16` value.
@@ -256,13 +254,11 @@ impl Time {
     /// The minimum relative block time.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MIN`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MIN instead")]
     pub const fn min_value() -> Self { Self::MIN }
 
     /// The maximum relative block time.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Time::MAX`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Self { Self::MAX }
 
     /// Create a [`Time`] using time intervals where each interval is equivalent to 512 seconds.
diff --git a/bitcoin/src/blockdata/script/instruction.rs b/bitcoin/src/blockdata/script/instruction.rs
index 70ef3594..8d824807 100644
--- a/bitcoin/src/blockdata/script/instruction.rs
+++ b/bitcoin/src/blockdata/script/instruction.rs
@@ -88,7 +88,7 @@ pub(super) fn next_push_data_len(
             // We do exhaustive matching to not forget to handle new variants if we extend
             // `UintError` type.
             // Overflow actually means early end of script (script is definitely shorter
-            // than `usize::MAX`)
+            // than `usize::max_value()`)
             Err(UintError::EarlyEndOfScript) | Err(UintError::NumericOverflow) => {
                 self.kill();
                 return Some(Err(Error::EarlyEndOfScript));
diff --git a/bitcoin/src/blockdata/script/mod.rs b/bitcoin/src/blockdata/script/mod.rs
index b688ff13..c3cab10f 100644
--- a/bitcoin/src/blockdata/script/mod.rs
+++ b/bitcoin/src/blockdata/script/mod.rs
@@ -187,11 +187,11 @@ pub fn read_scriptbool(v: &[u8]) -> bool {
 /// This function returns an error in these cases:
 ///
 /// * `data` is shorter than `size` => `EarlyEndOfScript`
-/// * `size` is greater than `u16::MAX / 8` (8191) => `NumericOverflow`
+/// * `size` is greater than `u16::max_value / 8` (8191) => `NumericOverflow`
 /// * The number being read overflows `usize` => `NumericOverflow`
 ///
 /// Note that this does **not** return an error for `size` between `core::size_of::<usize>()`
-/// and `u16::MAX / 8` if there's no overflow.
+/// and `u16::max_value / 8` if there's no overflow.
 #[inline]
 #[deprecated(since = "0.30.0", note = "bitcoin integers are signed 32 bits, use read_scriptint")]
 pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
@@ -203,7 +203,7 @@ pub fn read_uint(data: &[u8], size: usize) -> Result<usize, Error> {
 fn read_uint_iter(data: &mut core::slice::Iter<'_, u8>, size: usize) -> Result<usize, UintError> {
     if data.len() < size {
         Err(UintError::EarlyEndOfScript)
-    } else if size > usize::from(u16::MAX / 8) {
+    } else if size > usize::from(u16::max_value() / 8) {
         // Casting to u32 would overflow
         Err(UintError::NumericOverflow)
     } else {
@@ -596,7 +596,7 @@ macro_rules! read_push_data_len {
                     $formatter.write_str("<unexpected end>")?;
                     break;
                 }
-                // We got the data in a slice which implies it being shorter than `usize::MAX`
+                // We got the data in a slice which implies it being shorter than `usize::max_value()`
                 // So if we got overflow, we can confidently say the number is higher than length of
                 // the slice even though we don't know the exact number. This implies attempt to push
                 // past end.
diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs
index b2c2a878..62b28f61 100644
--- a/bitcoin/src/blockdata/transaction.rs
+++ b/bitcoin/src/blockdata/transaction.rs
@@ -35,7 +35,7 @@
 #[cfg(doc)]
 use crate::sighash::{EcdsaSighashType, TapSighashType};
 use crate::string::FromHexStr;
-use crate::{io, Amount, VarInt};
+use crate::{io, VarInt};
 
 /// A reference to a transaction output.
 ///
@@ -61,7 +61,7 @@ pub fn new(txid: Txid, vout: u32) -> OutPoint { OutPoint { txid, vout } }
     ///
     /// This value is used for coinbase transactions because they don't have any previous outputs.
     #[inline]
-    pub fn null() -> OutPoint { OutPoint { txid: Hash::all_zeros(), vout: u32::MAX } }
+    pub fn null() -> OutPoint { OutPoint { txid: Hash::all_zeros(), vout: u32::max_value() } }
 
     /// Checks if an `OutPoint` is "null".
     ///
@@ -305,7 +305,6 @@ impl Sequence {
     /// The maximum allowable sequence number.
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Sequence::MAX`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Self { Self::MAX }
 
     /// Returns `true` if the sequence number enables absolute lock-time ([`Transaction::lock_time`]).
@@ -478,7 +477,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&self.
 #[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
 pub struct TxOut {
     /// The value of the output, in satoshis.
-    pub value: Amount,
+    pub value: u64,
     /// The script which must be satisfied for the output to be spent.
     pub script_pubkey: ScriptBuf,
 }
@@ -512,7 +511,7 @@ pub fn minimal_non_dust(script_pubkey: ScriptBuf) -> Self {
         let dust_amount = (len as u64) * 3;
 
         TxOut {
-            value: Amount::from_sat(dust_amount + 1), // minimal non-dust amount is one higher than dust amount
+            value: dust_amount + 1, // minimal non-dust amount is one higher than dust amount
             script_pubkey,
         }
     }
@@ -520,9 +519,7 @@ pub fn minimal_non_dust(script_pubkey: ScriptBuf) -> Self {
 
 // This is used as a "null txout" in consensus signing code.
 impl Default for TxOut {
-    fn default() -> TxOut {
-        TxOut { value: Amount::from_sat(0xffffffffffffffff), script_pubkey: ScriptBuf::new() }
-    }
+    fn default() -> TxOut { TxOut { value: 0xffffffffffffffff, script_pubkey: ScriptBuf::new() } }
 }
 
 /// Result of [`Transaction::encode_signing_data_to`].
@@ -964,7 +961,12 @@ pub fn verify_with_flags<S, F>(&self, mut spent: S, flags: F) -> Result<(), scri
         let flags: u32 = flags.into();
         for (idx, input) in self.input.iter().enumerate() {
             if let Some(output) = spent(&input.previous_output) {
-                output.script_pubkey.verify_with_flags(idx, output.value, tx.as_slice(), flags)?;
+                output.script_pubkey.verify_with_flags(
+                    idx,
+                    crate::Amount::from_sat(output.value),
+                    tx.as_slice(),
+                    flags,
+                )?;
             } else {
                 return Err(script::Error::UnknownSpentOutput(input.previous_output));
             }
@@ -1218,13 +1220,6 @@ pub fn predict_weight<I, O>(inputs: I, output_script_lens: O) -> Weight
     I: IntoIterator<Item = InputWeightPrediction>,
     O: IntoIterator<Item = usize>,
 {
-    // This fold() does three things:
-    // 1) Counts the inputs and returns the sum as `input_count`.
-    // 2) Sums all of the input weights and returns the sum as `partial_input_weight`
-    //    For every input: script_size * 4 + witness_size
-    //    Since script_size is non-witness data, it gets a 4x multiplier.
-    // 3) Counts the number of inputs that have a witness data and returns the count as
-    //    `num_inputs_with_witnesses`.
     let (input_count, partial_input_weight, inputs_with_witnesses) = inputs.into_iter().fold(
         (0, 0, 0),
         |(count, partial_input_weight, inputs_with_witnesses), prediction| {
@@ -1235,11 +1230,6 @@ pub fn predict_weight<I, O>(inputs: I, output_script_lens: O) -> Weight
             )
         },
     );
-
-    // This fold() does two things:
-    // 1) Counts the outputs and returns the sum as `output_count`.
-    // 2) Sums the output script sizes and returns the sum as `output_scripts_size`.
-    //    script_len + the length of a VarInt struct that stores the value of script_len
     let (output_count, output_scripts_size) = output_script_lens.into_iter().fold(
         (0, 0),
         |(output_count, total_scripts_size), script_len| {
@@ -1263,11 +1253,7 @@ const fn predict_weight_internal(
     output_count: usize,
     output_scripts_size: usize,
 ) -> Weight {
-    // Lengths of txid, index and sequence: (32, 4, 4).
-    // Multiply the lengths by 4 since the fields are all non-witness fields.
     let input_weight = partial_input_weight + input_count * 4 * (32 + 4 + 4);
-
-    // The value field of a TxOut is 8 bytes.
     let output_size = 8 * output_count + output_scripts_size;
     let non_input_size =
     // version:
diff --git a/bitcoin/src/blockdata/weight.rs b/bitcoin/src/blockdata/weight.rs
index 0185e983..f2a296e0 100644
--- a/bitcoin/src/blockdata/weight.rs
+++ b/bitcoin/src/blockdata/weight.rs
@@ -26,10 +26,10 @@ impl Weight {
     /// Minimum possible value (0 wu).
     ///
     /// Equivalent to [`ZERO`](Self::ZERO), may better express intent in some contexts.
-    pub const MIN: Weight = Weight(u64::MIN);
+    pub const MIN: Weight = Weight(u64::min_value());
 
     /// Maximum possible value.
-    pub const MAX: Weight = Weight(u64::MAX);
+    pub const MAX: Weight = Weight(u64::max_value());
 
     /// The maximum allowed weight for a block, see BIP 141 (network rule).
     pub const MAX_BLOCK: Weight = Weight(4_000_000);
@@ -124,7 +124,7 @@ fn kilo_weight_constructor_test() {
     #[test]
     #[should_panic]
     fn kilo_weight_constructor_panic_test() {
-        Weight::from_kwu(u64::MAX).expect("expected weight unit");
+        Weight::from_kwu(u64::max_value()).expect("expected weight unit");
     }
 
     #[test]
@@ -132,7 +132,7 @@ fn from_vb_test() {
         let vb = Weight::from_vb(1).expect("expected weight unit");
         assert_eq!(Weight(4), vb);
 
-        let vb = Weight::from_vb(u64::MAX);
+        let vb = Weight::from_vb(u64::max_value());
         assert_eq!(None, vb);
     }
 
@@ -144,7 +144,7 @@ fn from_vb_unchecked_test() {
 
     #[test]
     #[should_panic]
-    fn from_vb_unchecked_panic_test() { Weight::from_vb_unchecked(u64::MAX); }
+    fn from_vb_unchecked_panic_test() { Weight::from_vb_unchecked(u64::max_value()); }
 
     #[test]
     fn from_witness_data_size_test() {
diff --git a/bitcoin/src/blockdata/witness.rs b/bitcoin/src/blockdata/witness.rs
index dbaf2bc7..21ec99d6 100644
--- a/bitcoin/src/blockdata/witness.rs
+++ b/bitcoin/src/blockdata/witness.rs
@@ -82,12 +82,12 @@ fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
                 let required_len = cursor
                     .checked_add(element_size)
                     .ok_or(self::Error::OversizedVectorAllocation {
-                        requested: usize::MAX,
+                        requested: usize::max_value(),
                         max: MAX_VEC_SIZE,
                     })?
                     .checked_add(element_size_varint_len)
                     .ok_or(self::Error::OversizedVectorAllocation {
-                        requested: usize::MAX,
+                        requested: usize::max_value(),
                         max: MAX_VEC_SIZE,
                     })?;
 
diff --git a/bitcoin/src/consensus/encode.rs b/bitcoin/src/consensus/encode.rs
index 7f6e2f0e..6fc6a588 100644
--- a/bitcoin/src/consensus/encode.rs
+++ b/bitcoin/src/consensus/encode.rs
@@ -895,7 +895,7 @@ fn serialize_varint_test() {
         test_varint_len(VarInt(0x10000), 5);
         test_varint_len(VarInt(0xFFFFFFFF), 5);
         test_varint_len(VarInt(0xFFFFFFFF + 1), 9);
-        test_varint_len(VarInt(u64::MAX), 9);
+        test_varint_len(VarInt(u64::max_value()), 9);
     }
 
     fn test_varint_len(varint: VarInt, expected: usize) {
diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs
index 5182c47a..605e8b88 100644
--- a/bitcoin/src/crypto/key.rs
+++ b/bitcoin/src/crypto/key.rs
@@ -12,6 +12,8 @@
 use hashes::hex::FromHex;
 use hashes::{hash160, hex, Hash};
 use internals::write_err;
+#[cfg(feature = "rand-std")]
+pub use secp256k1::rand;
 pub use secp256k1::{self, constants, KeyPair, Parity, Secp256k1, Verification, XOnlyPublicKey};
 
 use crate::hash_types::{PubkeyHash, WPubkeyHash};
@@ -298,6 +300,13 @@ pub struct PrivateKey {
 }
 
 impl PrivateKey {
+    /// Constructs new compressed ECDSA private key using the secp256k1 algorithm and
+    /// a secure random number generator.
+    #[cfg(feature = "rand-std")]
+    pub fn generate(network: Network) -> PrivateKey {
+        let secret_key = secp256k1::SecretKey::new(&mut rand::thread_rng());
+        PrivateKey::new(secret_key, network)
+    }
     /// Constructs compressed ECDSA private key from the provided generic Secp256k1 private key
     /// and the specified network
     pub fn new(key: secp256k1::SecretKey, network: Network) -> PrivateKey {
diff --git a/bitcoin/src/crypto/sighash.rs b/bitcoin/src/crypto/sighash.rs
index 6c8bc908..8ffdbf8d 100644
--- a/bitcoin/src/crypto/sighash.rs
+++ b/bitcoin/src/crypto/sighash.rs
@@ -22,7 +22,7 @@
 use crate::error::impl_std_error;
 use crate::prelude::*;
 use crate::taproot::{LeafVersion, TapLeafHash, TAPROOT_ANNEX_PREFIX};
-use crate::{io, Amount, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut};
+use crate::{io, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut};
 
 /// Used for signature hash for invalid use of SIGHASH_SINGLE.
 #[rustfmt::skip]
@@ -751,7 +751,7 @@ pub fn segwit_encode_signing_data_to<Write: io::Write>(
         mut writer: Write,
         input_index: usize,
         script_code: &Script,
-        value: Amount,
+        value: u64,
         sighash_type: EcdsaSighashType,
     ) -> Result<(), Error> {
         let zero_hash = sha256d::Hash::all_zeros();
@@ -810,7 +810,7 @@ pub fn segwit_signature_hash(
         &mut self,
         input_index: usize,
         script_code: &Script,
-        value: Amount,
+        value: u64,
         sighash_type: EcdsaSighashType,
     ) -> Result<SegwitV0Sighash, Error> {
         let mut enc = SegwitV0Sighash::engine();
@@ -1062,7 +1062,7 @@ impl<R: BorrowMut<Transaction>> SighashCache<R> {
     ///
     /// This allows in-line signing such as
     /// ```
-    /// use bitcoin::{absolute, Amount, Transaction, Script};
+    /// use bitcoin::{absolute, Transaction, Script};
     /// use bitcoin::sighash::{EcdsaSighashType, SighashCache};
     ///
     /// let mut tx_to_sign = Transaction { version: 2, lock_time: absolute::LockTime::ZERO, input: Vec::new(), output: Vec::new() };
@@ -1071,7 +1071,7 @@ impl<R: BorrowMut<Transaction>> SighashCache<R> {
     /// let mut sig_hasher = SighashCache::new(&mut tx_to_sign);
     /// for inp in 0..input_count {
     ///     let prevout_script = Script::empty();
-    ///     let _sighash = sig_hasher.segwit_signature_hash(inp, prevout_script, Amount::ONE_SAT, EcdsaSighashType::All);
+    ///     let _sighash = sig_hasher.segwit_signature_hash(inp, prevout_script, 42, EcdsaSighashType::All);
     ///     // ... sign the sighash
     ///     sig_hasher.witness_mut(inp).unwrap().push(&Vec::new());
     /// }
@@ -1468,7 +1468,7 @@ struct UtxoSpent {
             #[serde(rename = "scriptPubKey")]
             script_pubkey: ScriptBuf,
             #[serde(rename = "amountSats")]
-            value: Amount,
+            value: u64,
         }
 
         #[derive(serde::Deserialize)]
@@ -1685,7 +1685,7 @@ fn bip143_p2wpkh() {
 
         let witness_script =
             p2pkh_hex("025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357");
-        let value = Amount::from_sat(600_000_000);
+        let value = 600_000_000;
 
         let mut cache = SighashCache::new(&tx);
         assert_eq!(
@@ -1726,7 +1726,7 @@ fn bip143_p2wpkh_nested_in_p2sh() {
 
         let witness_script =
             p2pkh_hex("03ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a26873");
-        let value = Amount::from_sat(1_000_000_000);
+        let value = 1_000_000_000;
 
         let mut cache = SighashCache::new(&tx);
         assert_eq!(
@@ -1773,7 +1773,7 @@ fn bip143_p2wsh_nested_in_p2sh() {
              56ae",
         )
         .unwrap();
-        let value = Amount::from_sat(987_654_321);
+        let value = 987654321;
 
         let mut cache = SighashCache::new(&tx);
         assert_eq!(
diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs
index e2a58dda..9630ed50 100644
--- a/bitcoin/src/pow.rs
+++ b/bitcoin/src/pow.rs
@@ -133,7 +133,6 @@ impl Target {
     /// The maximum possible target (see [`Target::MAX`]).
     ///
     /// This is provided for consistency with Rust 1.41.1, newer code should use [`Target::MAX`].
-    #[deprecated(since = "0.31.0", note = "Use Self::MAX instead")]
     pub const fn max_value() -> Self { Target::MAX }
 
     /// Computes the [`Target`] value from a compact representation.
@@ -234,20 +233,6 @@ pub fn difficulty(&self) -> u128 {
     /// [`difficulty`]: Target::difficulty
     #[cfg_attr(all(test, mutate), mutate)]
     pub fn difficulty_float(&self) -> f64 { TARGET_MAX_F64 / self.0.to_f64() }
-
-    /// Computes the minimum valid [`Target`] threshold allowed for a block in which a difficulty
-    /// adjustment occurs.
-    ///
-    /// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
-    /// adjustment period.
-    pub fn min_difficulty_transition_threshold(&self) -> Self { Self(self.0 >> 2) }
-
-    /// Computes the maximum valid [`Target`] threshold allowed for a block in which a difficulty
-    /// adjustment occurs.
-    ///
-    /// The difficulty can only decrease or increase by a factor of 4 max on each difficulty
-    /// adjustment period.
-    pub fn max_difficulty_transition_threshold(&self) -> Self { Self(self.0 << 2) }
 }
 do_impl!(Target);
 
@@ -378,7 +363,7 @@ fn is_zero(&self) -> bool { self.0 == 0 && self.1 == 0 }
     fn is_one(&self) -> bool { self.0 == 0 && self.1 == 1 }
 
     #[cfg_attr(all(test, mutate), mutate)]
-    fn is_max(&self) -> bool { self.0 == u128::MAX && self.1 == u128::MAX }
+    fn is_max(&self) -> bool { self.0 == u128::max_value() && self.1 == u128::max_value() }
 
     /// Returns the low 32 bits.
     fn low_u32(&self) -> u32 { self.low_u128() as u32 }
@@ -392,8 +377,8 @@ fn low_u128(&self) -> u128 { self.1 }
     /// Returns `self` as a `u128` saturating to `u128::MAX` if `self` is too big.
     // Matagen gives false positive because >= and > both return u128::MAX
     fn saturating_to_u128(&self) -> u128 {
-        if *self > U256::from(u128::MAX) {
-            u128::MAX
+        if *self > U256::from(u128::max_value()) {
+            u128::max_value()
         } else {
             self.low_u128()
         }
@@ -952,7 +937,7 @@ fn u256_num_bits() {
         assert_eq!(U256::from(60000_u64).bits(), 16);
         assert_eq!(U256::from(70000_u64).bits(), 17);
 
-        let u = U256::from(u128::MAX) << 1;
+        let u = U256::from(u128::max_value()) << 1;
         assert_eq!(u.bits(), 129);
 
         // Try to read the following lines out loud quickly
@@ -1024,7 +1009,7 @@ fn u256_upper_hex() {
     fn u256_display() {
         assert_eq!(format!("{}", U256::from(100_u32)), "100",);
         assert_eq!(format!("{}", U256::ZERO), "0",);
-        assert_eq!(format!("{}", U256::from(u64::MAX)), format!("{}", u64::MAX),);
+        assert_eq!(format!("{}", U256::from(u64::max_value())), format!("{}", u64::max_value()),);
         assert_eq!(
             format!("{}", U256::MAX),
             "115792089237316195423570985008687907853269984665640564039457584007913129639935",
@@ -1339,7 +1324,7 @@ fn u256_mul_u64() {
 
     #[test]
     fn u256_addition() {
-        let x = U256::from(u128::MAX);
+        let x = U256::from(u128::max_value());
         let (add, overflow) = x.overflowing_add(U256::ONE);
         assert!(!overflow);
         assert_eq!(add, U256(1, 0));
@@ -1357,7 +1342,7 @@ fn u256_subtraction() {
         let x = U256(1, 0);
         let (sub, overflow) = x.overflowing_sub(U256::ONE);
         assert!(!overflow);
-        assert_eq!(sub, U256::from(u128::MAX));
+        assert_eq!(sub, U256::from(u128::max_value()));
     }
 
     #[test]
@@ -1490,7 +1475,7 @@ fn u256_serde() {
 
     #[test]
     fn u256_is_max_correct_negative() {
-        let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::MAX)];
+        let tc = vec![U256::ZERO, U256::ONE, U256::from(u128::max_value())];
         for t in tc {
             assert!(!t.is_max())
         }
@@ -1500,7 +1485,7 @@ fn u256_is_max_correct_negative() {
     fn u256_is_max_correct_positive() {
         assert!(U256::MAX.is_max());
 
-        let u = u128::MAX;
+        let u = u128::max_value();
         assert!(((U256::from(u) << 128) + U256::from(u)).is_max());
     }
 
diff --git a/bitcoin/src/psbt/mod.rs b/bitcoin/src/psbt/mod.rs
index c057f1fa..5af2317c 100644
--- a/bitcoin/src/psbt/mod.rs
+++ b/bitcoin/src/psbt/mod.rs
@@ -459,11 +459,11 @@ fn output_type(&self, input_index: usize) -> Result<OutputType, SignError> {
     pub fn fee(&self) -> Result<Amount, Error> {
         let mut inputs: u64 = 0;
         for utxo in self.iter_funding_utxos() {
-            inputs = inputs.checked_add(utxo?.value.to_sat()).ok_or(Error::FeeOverflow)?;
+            inputs = inputs.checked_add(utxo?.value).ok_or(Error::FeeOverflow)?;
         }
         let mut outputs: u64 = 0;
         for out in &self.unsigned_tx.output {
-            outputs = outputs.checked_add(out.value.to_sat()).ok_or(Error::FeeOverflow)?;
+            outputs = outputs.checked_add(out.value).ok_or(Error::FeeOverflow)?;
         }
         inputs.checked_sub(outputs).map(Amount::from_sat).ok_or(Error::NegativeFee)
     }
@@ -922,14 +922,14 @@ fn serialize_then_deserialize_global() {
                 }],
                 output: vec![
                     TxOut {
-                        value: Amount::from_sat(99_999_699),
+                        value: 99999699,
                         script_pubkey: ScriptBuf::from_hex(
                             "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac",
                         )
                         .unwrap(),
                     },
                     TxOut {
-                        value: Amount::from_sat(100_000_000),
+                        value: 100000000,
                         script_pubkey: ScriptBuf::from_hex(
                             "a9143545e6e33b832c47050f24d3eeb93c9c03948bc787",
                         )
@@ -995,7 +995,7 @@ fn test_serde_psbt() {
                 )]),
             }],
             output: vec![TxOut {
-                value: Amount::from_sat(190_303_501_938),
+                value: 190303501938,
                 script_pubkey: ScriptBuf::from_hex(
                     "a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587",
                 )
@@ -1046,7 +1046,7 @@ fn test_serde_psbt() {
                 Input {
                     non_witness_utxo: Some(tx),
                     witness_utxo: Some(TxOut {
-                        value: Amount::from_sat(190_303_501_938),
+                        value: 190303501938,
                         script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
                     }),
                     sighash_type: Some("SIGHASH_SINGLE|SIGHASH_ANYONECANPAY".parse::<PsbtSighashType>().unwrap()),
@@ -1190,11 +1190,11 @@ fn valid_vector_1() {
                     ],
                     output: vec![
                         TxOut {
-                            value: Amount::from_sat(99_999_699),
+                            value: 99999699,
                             script_pubkey: ScriptBuf::from_hex("76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac").unwrap(),
                         },
                         TxOut {
-                            value: Amount::from_sat(100_000_000),
+                            value: 100000000,
                             script_pubkey: ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap(),
                         },
                     ],
@@ -1237,11 +1237,11 @@ fn valid_vector_1() {
                             ],
                             output: vec![
                                 TxOut {
-                                    value: Amount::from_sat(200_000_000),
+                                    value: 200000000,
                                     script_pubkey: ScriptBuf::from_hex("76a91485cff1097fd9e008bb34af709c62197b38978a4888ac").unwrap(),
                                 },
                                 TxOut {
-                                    value: Amount::from_sat(190_303_501_938),
+                                    value: 190303501938,
                                     script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
                                 },
                             ],
@@ -1522,11 +1522,11 @@ fn serialize_and_deserialize_preimage_psbt() {
                 ],
                 output: vec![
                     TxOut {
-                        value: Amount::from_sat(99_999_699),
+                        value: 99999699,
                         script_pubkey: ScriptBuf::from_hex("76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac").unwrap(),
                     },
                     TxOut {
-                        value: Amount::from_sat(100_000_000),
+                        value: 100000000,
                         script_pubkey: ScriptBuf::from_hex("a9143545e6e33b832c47050f24d3eeb93c9c03948bc787").unwrap(),
                     },
                 ],
@@ -1569,11 +1569,11 @@ fn serialize_and_deserialize_preimage_psbt() {
                         ],
                         output: vec![
                             TxOut {
-                                value: Amount::from_sat(200_000_000),
+                                value: 200000000,
                                 script_pubkey: ScriptBuf::from_hex("76a91485cff1097fd9e008bb34af709c62197b38978a4888ac").unwrap(),
                             },
                             TxOut {
-                                value: Amount::from_sat(190_303_501_938),
+                                value: 190303501938,
                                 script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
                             },
                         ],
@@ -1670,9 +1670,9 @@ fn get_key_btree_map() {
 
     #[test]
     fn test_fee() {
-        let output_0_val = Amount::from_sat(99_999_699);
-        let output_1_val = Amount::from_sat(100_000_000);
-        let prev_output_val = Amount::from_sat(200_000_000);
+        let output_0_val = 99999699;
+        let output_1_val = 100000000;
+        let prev_output_val = 200000000;
 
         let mut t = PartiallySignedTransaction {
             unsigned_tx: Transaction {
@@ -1733,7 +1733,7 @@ fn test_fee() {
                                 ..Default::default()
                             },
                             TxOut {
-                                value: Amount::from_sat(190_303_501_938),
+                                value: 190303501938,
                                 ..Default::default()
                             },
                         ],
@@ -1752,7 +1752,7 @@ fn test_fee() {
         };
         assert_eq!(
             t.fee().expect("fee calculation"),
-            prev_output_val - (output_0_val + output_1_val)
+            Amount::from_sat(prev_output_val - (output_0_val + output_1_val))
         );
         // no previous output
         let mut t2 = t.clone();
@@ -1769,8 +1769,8 @@ fn test_fee() {
             e => panic!("unexpected error: {:?}", e),
         }
         // overflow
-        t.unsigned_tx.output[0].value = Amount::MAX;
-        t.unsigned_tx.output[1].value = Amount::MAX;
+        t.unsigned_tx.output[0].value = u64::max_value();
+        t.unsigned_tx.output[1].value = u64::max_value();
         match t.fee().unwrap_err() {
             Error::FeeOverflow => {}
             e => panic!("unexpected error: {:?}", e),
@@ -1801,7 +1801,7 @@ fn sign_psbt() {
 
         // First input we can spend. See comment above on key_map for why we use defaults here.
         let txout_wpkh = TxOut {
-            value: Amount::from_sat(10),
+            value: 10,
             script_pubkey: ScriptBuf::new_v0_p2wpkh(&WPubkeyHash::hash(&pk.to_bytes())),
         };
         psbt.inputs[0].witness_utxo = Some(txout_wpkh);
@@ -1813,10 +1813,8 @@ fn sign_psbt() {
         // Second input is unspendable by us e.g., from another wallet that supports future upgrades.
         let unknown_prog =
             WitnessProgram::new(crate::address::WitnessVersion::V4, vec![0xaa; 34]).unwrap();
-        let txout_unknown_future = TxOut {
-            value: Amount::from_sat(10),
-            script_pubkey: ScriptBuf::new_witness_program(&unknown_prog),
-        };
+        let txout_unknown_future =
+            TxOut { value: 10, script_pubkey: ScriptBuf::new_witness_program(&unknown_prog) };
         psbt.inputs[1].witness_utxo = Some(txout_unknown_future);
 
         let sigs = psbt.sign(&key_map, &secp).unwrap();
diff --git a/internals/src/hex/display.rs b/internals/src/hex/display.rs
index 85da1684..6a75864a 100644
--- a/internals/src/hex/display.rs
+++ b/internals/src/hex/display.rs
@@ -220,7 +220,7 @@ macro_rules! fmt_hex_exact {
     ($formatter:expr, $len:expr, $bytes:expr, $case:expr) => {{
         // statically check $len
         #[allow(deprecated)]
-        const _: () = [()][($len > usize::MAX / 2) as usize];
+        const _: () = [()][($len > usize::max_value() / 2) as usize];
         assert_eq!($bytes.len(), $len);
         let mut buf = [0u8; $len * 2];
         let buf = $crate::hex::buf_encoder::AsOutBytes::as_mut_out_bytes(&mut buf);


Test patch:
diff --git a/bitcoin/tests/psbt.rs b/bitcoin/tests/psbt.rs
index 692cc9b6..a36b1afb 100644
--- a/bitcoin/tests/psbt.rs
+++ b/bitcoin/tests/psbt.rs
@@ -188,13 +188,15 @@ struct TvInput {
         output: vec![
             TxOut {
                 value: Amount::from_str_in(output_0.amount, Denomination::Bitcoin)
-                    .expect("failed to parse amount"),
+                    .expect("failed to parse amount")
+                    .to_sat(),
                 script_pubkey: ScriptBuf::from_hex(output_0.script_pubkey)
                     .expect("failed to parse script"),
             },
             TxOut {
                 value: Amount::from_str_in(output_1.amount, Denomination::Bitcoin)
-                    .expect("failed to parse amount"),
+                    .expect("failed to parse amount")
+                    .to_sat(),
                 script_pubkey: ScriptBuf::from_hex(output_1.script_pubkey)
                     .expect("failed to parse script"),
             },
diff --git a/bitcoin/tests/serde.rs b/bitcoin/tests/serde.rs
index fc125975..042ac0ba 100644
--- a/bitcoin/tests/serde.rs
+++ b/bitcoin/tests/serde.rs
@@ -38,8 +38,8 @@
 use bitcoin::sighash::{EcdsaSighashType, TapSighashType};
 use bitcoin::taproot::{self, ControlBlock, LeafVersion, TapTree, TaprootBuilder};
 use bitcoin::{
-    ecdsa, Address, Amount, Block, Network, OutPoint, PrivateKey, PublicKey, ScriptBuf, Sequence,
-    Target, Transaction, TxIn, TxOut, Txid, Work,
+    ecdsa, Address, Block, Network, OutPoint, PrivateKey, PublicKey, ScriptBuf, Sequence, Target,
+    Transaction, TxIn, TxOut, Txid, Work,
 };
 
 /// Implicitly does regression test for `BlockHeader` also.
@@ -110,10 +110,8 @@ fn serde_regression_txin() {
 
 #[test]
 fn serde_regression_txout() {
-    let txout = TxOut {
-        value: Amount::from_sat(0xDEADBEEFCAFEBABE),
-        script_pubkey: ScriptBuf::from(vec![0u8, 1u8, 2u8]),
-    };
+    let txout =
+        TxOut { value: 0xDEADBEEFCAFEBABE, script_pubkey: ScriptBuf::from(vec![0u8, 1u8, 2u8]) };
     let got = serialize(&txout).unwrap();
     let want = include_bytes!("data/serde/txout_bincode") as &[_];
     assert_eq!(got, want)
@@ -239,7 +237,7 @@ fn serde_regression_psbt() {
             .unwrap()]),
         }],
         output: vec![TxOut {
-            value: Amount::from_sat(190_303_501_938),
+            value: 190303501938,
             script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587")
                 .unwrap(),
         }],
@@ -284,7 +282,7 @@ fn serde_regression_psbt() {
         inputs: vec![Input {
             non_witness_utxo: Some(tx),
             witness_utxo: Some(TxOut {
-                value: Amount::from_sat(190_303_501_938),
+                value: 190303501938,
                 script_pubkey: ScriptBuf::from_hex("a914339725ba21efd62ac753a9bcd067d6c7a6a39d0587").unwrap(),
             }),
             sighash_type: Some(PsbtSighashType::from(EcdsaSighashType::from_str("SIGHASH_SINGLE|SIGHASH_ANYONECANPAY").unwrap())),