Commit Graph

355 Commits

Author SHA1 Message Date
merge-script 515c0f584a
Merge rust-bitcoin/rust-bitcoin#3559: Replace `String` with `InputString`
3f2e760d1f Replace String with InputString in ParseIntError (Tobin C. Harding)
aa5c78430c Replace invalidInteger with ParseIntError (Tobin C. Harding)
9b7a706bfd Remove From<ParseIntError> (Tobin C. Harding)
c90f4b6033 Fix bug in error output (Tobin C. Harding)
c986b2f620 internals: Move error.rs to error/mod.rs (Tobin C. Harding)

Pull request description:

  This PR hopefully clears the way for removing many of the `alloc` feature gates in `units` and `primitives`

  The three final patches were tested by adding the following test to `units::locktime::absolute`:
  ```rust
      #[test]
      pub fn debug_absolute_error_conversion_height() {
          let invalid_height = LOCK_TIME_THRESHOLD + 1;
          let err = Height::from_consensus(invalid_height).unwrap_err();
          std::println!("{:?}", err);
          std::println!("{}", err);

          let invalid_time =  LOCK_TIME_THRESHOLD - 1;
          let err = Time::from_consensus(invalid_time).unwrap_err();
          std::println!("{:?}", err);
          std::println!("{}", err);

          let invalid_height = std::format!("{:x}", LOCK_TIME_THRESHOLD + 1);
          let err = Height::from_hex(&invalid_height).unwrap_err();
          std::println!("{:?}", err);
          std::println!("{}", err);

          let invalid_time = std::format!("{:x}", LOCK_TIME_THRESHOLD - 1);
          let err = Time::from_hex(&invalid_time).unwrap_err();
          std::println!("{:?}", err);
          std::println!("{}", err);

          let err = Height::from_hex("somerandomshit").unwrap_err();
          std::println!("{:?}", err);
          std::println!("{}", err);

          let err = Time::from_hex("somerandomshit").unwrap_err();
          std::println!("{:?}", err);
          std::println!("{}", err);
      }
  ```

  Gives the following output (the last four lines is the bit that changes, the rest just proves we don't break other variants)

  On commit: `d47ff1c25 Remove From<ParseIntError>`

  ConversionError { unit: Blocks, input: 500000001 }
  invalid lock time value 500000001, expected lock-by-blockheight (must be < 500000000)
  ConversionError { unit: Seconds, input: 499999999 }
  invalid lock time value 499999999, expected lock-by-blocktime (must be >= 500000000)
  ParseHeightError(Conversion(500000001))
  block height 500000001 is above limit 499999999
  ParseTimeError(Conversion(499999999))
  block height 499999999 is below limit 500000000
  ParseHeightError(InvalidInteger { source: ParseIntError { kind: InvalidDigit }, input: "somerandomshit" })
  failed to parse somerandomshit as block height
  ParseTimeError(InvalidInteger { source: ParseIntError { kind: InvalidDigit }, input: "somerandomshit" })
  failed to parse somerandomshit as block time

  On commit: `0155a0d9a Replace invalidInteger with ParseIntError`

  ConversionError { unit: Blocks, input: 500000001 }
  invalid lock time value 500000001, expected lock-by-blockheight (must be < 500000000)
  ConversionError { unit: Seconds, input: 499999999 }
  invalid lock time value 499999999, expected lock-by-blocktime (must be >= 500000000)
  ParseHeightError(Conversion(500000001))
  block height 500000001 is above limit 499999999
  ParseTimeError(Conversion(499999999))
  block height 499999999 is below limit 500000000
  ParseHeightError(ParseInt(ParseIntError { input: "somerandomshit", bits: 32, is_signed: true, source: ParseIntError { kind: InvalidDigit } }))
  failed to parse somerandomshit as block height
  ParseTimeError(ParseInt(ParseIntError { input: "somerandomshit", bits: 32, is_signed: true, source: ParseIntError { kind: InvalidDigit } }))
  failed to parse somerandomshit as block time

  On Commit: `3f2e760d1 Replace String with InputString in ParseIntError`

  ConversionError { unit: Blocks, input: 500000001 }
  invalid lock time value 500000001, expected lock-by-blockheight (must be < 500000000)
  ConversionError { unit: Seconds, input: 499999999 }
  invalid lock time value 499999999, expected lock-by-blocktime (must be >= 500000000)
  ParseHeightError(Conversion(500000001))
  block height 500000001 is above limit 499999999
  ParseTimeError(Conversion(499999999))
  block time 499999999 is below limit 500000000
  ParseHeightError(ParseInt(ParseIntError { input: InputString("somerandomshit"), bits: 32, is_signed: true, source: ParseIntError { kind: InvalidDigit } }))
  failed to parse 'somerandomshit' as absolute Height/Time (block height)
  ParseTimeError(ParseInt(ParseIntError { input: InputString("somerandomshit"), bits: 32, is_signed: true, source: ParseIntError { kind: InvalidDigit } }))
  failed to parse 'somerandomshit' as absolute Height/Time (block time)

ACKs for top commit:
  apoelstra:
    ACK 3f2e760d1fef2951f93a2554cd53340b0d7a6e0b; successfully ran local tests; nice!

Tree-SHA512: f7fd55acfb83082419db22c24a6b375c20e2631263401e500410c5b5659463f06dc4bdb145621e475dc15d75e764668cdcbf8f88006a487248a05fdb237ad136
2024-11-01 16:27:07 +00:00
Tobin C. Harding 3f2e760d1f
Replace String with InputString in ParseIntError
Currently the `ParseIntError` contains an owned copy of the input
string, this is causing us to have to use `alloc` everywhere.

We already have a alloc-friendly string replacement type, the
`InputString` - use it.
2024-11-01 17:31:22 +11:00
Tobin C. Harding aa5c78430c
Replace invalidInteger with ParseIntError
We have a special type for wrapping integer parsing errors, use it.

To test this I added the following tests:

    #[test]
    pub fn debug_absolute_error_conversion_height() {
        let invalid_height = LOCK_TIME_THRESHOLD + 1;
        let _ = Height::from_consensus(invalid_height).unwrap();
    }

    #[test]
    pub fn debug_absolute_error_conversion_time() {
        let invalid_time =  LOCK_TIME_THRESHOLD - 1;
        let _ = Time::from_consensus(invalid_time).unwrap();
    }

    #[test]
    #[cfg(feature = "std")]
    pub fn debug_absolute_error_conversion_height_string() {
        let invalid_height = std::format!("{:x}", LOCK_TIME_THRESHOLD + 1);
        let _ = Height::from_hex(&invalid_height).unwrap();
    }

    #[test]
    #[cfg(feature = "std")]
    pub fn debug_absolute_error_conversion_time_string() {
        let invalid_time = std::format!("{:x}", LOCK_TIME_THRESHOLD - 1);
        let _ = Time::from_hex(&invalid_time).unwrap();
    }

    #[test]
    #[cfg(feature = "std")]
    pub fn debug_absolute_error_height_invalid_hex_string() {
        let _ = Height::from_hex("somerandomshit").unwrap();
    }

    #[test]
    #[cfg(feature = "std")]
    pub fn debug_absolute_error_time_invalid_hex_string() {
        let _ = Time::from_hex("somerandomshit").unwrap();
    }

Which resulted in the following output

Before:

---- locktime::absolute::tests::debug_absolute_error_conversion_height stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_height' panicked at units/src/locktime/absolute.rs:431:56:
called `Result::unwrap()` on an `Err` value: ConversionError { unit: Blocks, input: 500000001 }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- locktime::absolute::tests::debug_absolute_error_conversion_height_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_height_string' panicked at units/src/locktime/absolute.rs:444:51:
called `Result::unwrap()` on an `Err` value: ParseHeightError(Conversion(500000001))

---- locktime::absolute::tests::debug_absolute_error_conversion_time stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_time' panicked at units/src/locktime/absolute.rs:437:52:
called `Result::unwrap()` on an `Err` value: ConversionError { unit: Seconds, input: 499999999 }

---- locktime::absolute::tests::debug_absolute_error_height_invalid_hex_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_height_invalid_hex_string' panicked at units/src/locktime/absolute.rs:457:52:
called `Result::unwrap()` on an `Err` value: ParseHeightError(InvalidInteger { source: ParseIntError { kind: InvalidDigit }, input: "somerandomshit" })

---- locktime::absolute::tests::debug_absolute_error_conversion_time_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_time_string' panicked at units/src/locktime/absolute.rs:451:47:
called `Result::unwrap()` on an `Err` value: ParseTimeError(Conversion(499999999))

---- locktime::absolute::tests::debug_absolute_error_time_invalid_hex_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_time_invalid_hex_string' panicked at units/src/locktime/absolute.rs:464:50:
called `Result::unwrap()` on an `Err` value: ParseTimeError(InvalidInteger { source: ParseIntError { kind: InvalidDigit }, input: "somerandomshit" })

After:

---- locktime::absolute::tests::debug_absolute_error_conversion_height stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_height' panicked at units/src/locktime/absolute.rs:432:56:
called `Result::unwrap()` on an `Err` value: ConversionError { unit: Blocks, input: 500000001 }

---- locktime::absolute::tests::debug_absolute_error_conversion_height_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_height_string' panicked at units/src/locktime/absolute.rs:445:51:
called `Result::unwrap()` on an `Err` value: ParseHeightError(Conversion(500000001))

---- locktime::absolute::tests::debug_absolute_error_conversion_time stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_time' panicked at units/src/locktime/absolute.rs:438:52:
called `Result::unwrap()` on an `Err` value: ConversionError { unit: Seconds, input: 499999999 }

---- locktime::absolute::tests::debug_absolute_error_conversion_time_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_conversion_time_string' panicked at units/src/locktime/absolute.rs:452:47:
called `Result::unwrap()` on an `Err` value: ParseTimeError(Conversion(499999999))

---- locktime::absolute::tests::debug_absolute_error_height_invalid_hex_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_height_invalid_hex_string' panicked at units/src/locktime/absolute.rs:458:52:
called `Result::unwrap()` on an `Err` value: ParseHeightError(ParseInt(ParseIntError { input: "somerandomshit", bits: 32, is_signed: false, source: ParseIntError { kind: InvalidDigit } }))

---- locktime::absolute::tests::debug_absolute_error_time_invalid_hex_string stdout ----
thread 'locktime::absolute::tests::debug_absolute_error_time_invalid_hex_string' panicked at units/src/locktime/absolute.rs:465:50:
called `Result::unwrap()` on an `Err` value: ParseTimeError(ParseInt(ParseIntError { input: "somerandomshit", bits: 32, is_signed: false, source: ParseIntError { kind: InvalidDigit } }))
2024-11-01 17:31:22 +11:00
Tobin C. Harding 9b7a706bfd
Remove From<ParseIntError>
The errors in `units::locktime::absolute` are complex, I'd like to make
them more simple so they are more understandable.

I have no clue why this is implemented - remove it.
2024-11-01 17:31:22 +11:00
Tobin C. Harding c90f4b6033
Fix bug in error output
`ParseTimeError` should say "block time" not "block height". This looks
like a cut'n pasta error because the `ParseHeightError` uses the same
string.
2024-11-01 17:31:21 +11:00
Tobin C. Harding 6aa8c2b023
Remove needless_borrows_for_generic_args
This has been fixed and we use nightly to lint so we have access to the
merged fix.

Removing the attribute uncovers a bunch of real lint warnings, fix
them while we are at it.
2024-11-01 14:30:45 +11:00
Tobin C. Harding 10ff979fbd
amount: Move arbitrary impl
In an effort to make the `unsigned` and `signed` files be diff'able move
the `arbitrary` code to be in the same place.

Code move only.
2024-10-31 12:57:08 +11:00
Tobin C. Harding d4d9311603
amount: Move SignedAmount to private signed module
In an effort to make the `amount` module more readable move the
`SignedAmount` type to a private submodule.

Re-export everything so this is not a breaking change.

Code move and re-exports only.
2024-10-31 12:57:08 +11:00
Tobin C. Harding 0fc0e8760b
docs: Remove link from self
When we move `SignedAmount` to a submodule linking to `self` introduces
a clippy warning, I'm not exactly sure why but lets remove the link in
preparation for the move.
2024-10-31 12:57:03 +11:00
Tobin C. Harding 13f9fd1b77
amount: Move Amount to private unsigned module
In an effort to make the `amount` module more readable move the `Amount`
type to a private submodule.

Re-export everything so this is not a breaking change.

Code move and re-exports only.
2024-10-31 12:56:40 +11:00
Tobin C. Harding 2d4c0fa6c1
amount: Format serde file
Done as a separate patch so that the diff of the verification code move
was less noisy.
2024-10-31 12:29:21 +11:00
Tobin C. Harding df96267342
amount: Move serde code to submodule
No changes other than moving the module code.
2024-10-31 12:29:21 +11:00
Tobin C. Harding 87c9a3fd11
amount: Format tests file
Done as a separate patch so that the diff of the verification code move
was less noisy.
2024-10-31 12:29:21 +11:00
Tobin C. Harding e0bc68042d
amount: Move test code to submodule
In preparation for splitting the two amounts into separate files; move
the `amount` module code to a submodule.

Internal change only.
2024-10-31 12:29:20 +11:00
Tobin C. Harding 7e1269704d
tests: Use from_sat
Stop using private constructor in unit tests, use `from_sat` instead.
2024-10-31 12:29:20 +11:00
Tobin C. Harding cd5d1aba2f
amount: Format verification file
Done as a separate patch so that the diff of the verification code move
was less noisy.
2024-10-31 12:29:20 +11:00
Tobin C. Harding 01f907b7a6
amount: Move verification code to submodule
Code move only, no other changes.
2024-10-31 12:29:20 +11:00
Tobin C. Harding 5ce827c5e0
amount: Move error code to submodule
There is _a lot_ of error types in the `amount` module. Move them to a
separate `error` module.

Add a bunch of `pub(super)` to keep things private to the `amount`
module.

Eventually we will want to close all these errors.
2024-10-31 12:29:16 +11:00
Tobin C. Harding abc54d0343
Make amount module a directory
In preparation for splitting the error types out of `amount.rs` into
their own file move the `amount.rs` file to `amount/mod.rs`.

File move only, no other changes.
2024-10-31 09:52:32 +11:00
Casey Rodarmor 1d2cfb036c Make `Amount::to_sat` and `SignedAmount::to_sat` const 2024-10-19 11:49:14 -07:00
merge-script 17899d1b8c
Merge rust-bitcoin/rust-bitcoin#3475: Unify deprecated note field format
88b53a471e Unify deprecated note field format (Jamil Lambert, PhD)

Pull request description:

  Following the suggestion in Issue #3306 all the deprecated note fields have been changed to be lower case and in the format "use `abc` instead".

ACKs for top commit:
  tcharding:
    ACK 88b53a471e
  apoelstra:
    ACK 88b53a471e successfully ran local tests

Tree-SHA512: 5c20eda7140f37ce78eb58dfdf03ecc11a67fcb10f294d860e81eaaee696e3a4209516017a9885cef9bfff1aa69b845534d139578b674933770fa24d59e4275f
2024-10-16 02:10:58 +00:00
Jamil Lambert, PhD 88b53a471e
Unify deprecated note field format
All the deprecated note fields have been changed to be lower case and in
the format "use `a` instead".
2024-10-15 15:16:01 +01:00
Jamil Lambert, PhD fbc7aa7fd5
Remove unnecessary lifetimes
New lint warnings from recent nightly toolchain show some explicit
lifetimes that can be omitted.

The unnecessary lifetimes have been removed.
2024-10-15 14:02:56 +01:00
Tobin C. Harding e68da281ff
Warn on future deprecations
We use `TBD` in our `deprecated` string and it was discovered that there
is an exception on this string so as not to warn because it is used
internally by the Rust language. However there is a special lint to
enable warnings, lets use it.

Add `#![warn(deprecated_in_future)]` to the coding conventions section
of all crates except `fuzz`.
2024-10-15 07:56:06 +11:00
Fmt Bot f1733309e0 2024-10-13 automated rustfmt nightly 2024-10-13 01:20:28 +00:00
merge-script 27f6f17974
Merge rust-bitcoin/rust-bitcoin#3430: Add checked div by weight to amount
a0c58a4a8b Add checked weight division to Amount (yancy)
8def40a991 Add assertions to checked_weight_mul test (yancy)
16ce70d3a6 Add div_by_weight test to fee_rate (yancy)

Pull request description:

  Adds the checked variant of `amount / weight`.  I also added a test to the non-checked version for comparison so the reviewer knows they compute the same way (integer division rounded down).

  Also added assertion to `checked_weight_mul test` showing the results are rounded up.

ACKs for top commit:
  tcharding:
    ACK a0c58a4a8b
  apoelstra:
    ACK a0c58a4a8b successfully ran local tests

Tree-SHA512: cf14123ed261d100e3261a720c26f8c10368f05225e32eaa246f25ab766d20515db5feb98335d4e3e08a8146a70db65ff64670da3f75e7764e8f86ef534d2663
2024-10-10 18:19:16 +00:00
yancy a0c58a4a8b Add checked weight division to Amount 2024-10-09 09:30:09 -05:00
merge-script e8a3c1f01b
Merge rust-bitcoin/rust-bitcoin#3117: Release tracking PR: `bitcoin-units 0.2.0`
07a529a132 Bump version of bitcoin-units to 0.2.0 (Tobin C. Harding)
148711a4c6 units: Use double ## in changelog entries (Tobin C. Harding)
80e600ba0c units: Copy 0.1.2 release notes (Tobin C. Harding)

Pull request description:

  In preparation for releasing `units v0.2.0` bump the version number, add a changelog entry, update the lock files, and depend on the new version in all crates that depend on `units`.

  Close: #3095

ACKs for top commit:
  apoelstra:
    ACK 07a529a132 successfully ran local tests

Tree-SHA512: 98a75d485ded6225551a5fc4b4a14d8efecc76911a720f959044cdd62781024a8787f258f171ed297705f5ab470f9a88a81ad5d255c9e03c1e22857615ad2e6d
2024-10-01 22:51:05 +00:00
yancy 8def40a991 Add assertions to checked_weight_mul test 2024-09-30 19:05:18 -05:00
yancy 16ce70d3a6 Add div_by_weight test to fee_rate 2024-09-30 19:05:18 -05:00
merge-script 95be55177e
Merge rust-bitcoin/rust-bitcoin#3421: Const locktime constructors
de319670ae feat: Create relative lock times at compile time (Christian Lewe)
53e1fb6b0c feat: Create absolute lock time at compile time (Christian Lewe)

Pull request description:

  I noticed that I cannot create lock times as compile-time constants. This PR tries to remedy this issue by marking lock time constructors as `const`.

  Because the `internals` crate depends on the `units` crate in a way that I don't fully understand yet, this PR updates the `units` crate only.

  If `from_consensus` is being kept non-`const` by design, to keep the API flexible to future changes, then please close this PR. In this case, I overlooked existing discussions.

ACKs for top commit:
  apoelstra:
    ACK de319670ae successfully ran local tests; good start; should backport
  tcharding:
    ACK de319670ae

Tree-SHA512: 69f9147707bcf8f91f755dd6d1be5ed08945e775ee46918e33d77a9d07ce474047a80ed1226134a3914ead51d1ddbbc657552ca934dc3c079b92ad3d50b13152
2024-09-30 16:29:18 +00:00
Fmt Bot a65d2a0ee4 2024-09-29 automated rustfmt nightly 2024-09-29 01:21:14 +00:00
Christian Lewe de319670ae feat: Create relative lock times at compile time
Also mark these methods as const. Because <u32 as From<u16>>::from
is not available in const contexts, I had to cast u16 as u32. I try to
avoid casts as much as I can, but in this case a cast seems unavoidable.
Casting u16 as u32 should be safe on all architectures.
2024-09-28 18:29:15 +02:00
Christian Lewe 53e1fb6b0c feat: Create absolute lock time at compile time
Mark the from_consensus and to_consensus methods of the absolute
lock time structs as const. In theory. these methods do some sanity
checking and wrap a u32 value in a newtype. This should be possible
to do in const. Marking the methods as const should not break existing
call sites.
2024-09-28 18:14:35 +02:00
Tobin C. Harding 07a529a132
Bump version of bitcoin-units to 0.2.0
In preparation for releasing `units v0.2.0` bump the version number,
add a changelog entry, update the lock files, and depend on the new
version in all crates that depend on `units`.
2024-09-25 10:58:31 +10:00
Tobin C. Harding 148711a4c6
units: Use double ## in changelog entries
Mimic the `rust-bitcoin` and use double `##` for changelog entries.
2024-09-25 10:54:21 +10:00
Tobin C. Harding 80e600ba0c
units: Copy 0.1.2 release notes
When we do patch version releases (on a separate branch) the release
patches typically include a changelog entry that does not appear on
`master` - this seems like a process fail. Anyways, grab the release
notes for `v0.1.2` and add them to the changelog file. Intentionally do
not cherrypick the release patch because that may make the git index
hard to understand.
2024-09-25 10:54:21 +10:00
yancy cb2146d5fa Implement FeeRate checked_sub 2024-09-23 21:33:31 -05:00
yancy 212a751929 Implement FeeRate checked_add 2024-09-23 21:33:31 -05:00
yancy c967eabd43 Implement FeeRate SubAssign 2024-09-23 21:33:31 -05:00
yancy c3a8bfa98d Implement FeeRate AddAssign 2024-09-23 21:33:31 -05:00
yancy 0e70870056 Implement FeeRate subtraction 2024-09-23 21:33:31 -05:00
yancy 86359fe364 Implement FeeRate addition 2024-09-23 21:33:31 -05:00
merge-script 6338f7c973
Merge rust-bitcoin/rust-bitcoin#3375: Release tracking PR: `bitcoin-internals 0.4.0`
18110a51f2 Bump version of internals to 0.4.0 (Tobin C. Harding)

Pull request description:

  In preparation for releasing `internals v0.4.0` bump the version number, add a changelog entry, update the lock files, and depend on the new version in all crates that depend on `internals`.

ACKs for top commit:
  apoelstra:
    ACK 18110a51f2 successfully ran local tests; lots of nice stuff here

Tree-SHA512: a4d3d5279b7d7fa993cbc3b7b34fc6dc4024dd54c0bfa1ecd0f0d5f09b984871f156c3695092a1f6c44b7571f8b2051699040f5f77636d44d4cae6c972ab597f
2024-09-23 18:32:23 +00:00
merge-script 855c4bb754
Merge rust-bitcoin/rust-bitcoin#3364: Remove unused inports, and fix unused variables and methods in docs
f6abdcc001 Allow unused in `macros.rs` docs (Jamil Lambert, PhD)
fd89ddf401 Remove or fix unused variables and methods in docs (Jamil Lambert, PhD)
ff6b1d4f19 Remove unused variables and methods from docs (Jamil Lambert, PhD)
e58cda6f92 Remove `unused_imports` in docs (Jamil Lambert, PhD)

Pull request description:

  As mentioned in #3362 examples in documentation are not linted in the same way as other code, but should still contain correctly written code.

  #![doc(test(attr(warn(unused))))] has been added to all lib.rs files

  In the docs throughout all crates:

  - Unused imports have been removed.

  - Unused variables, structs and enums have been used e.g. with an `assert_eq!` or prefixed with `_`

  - Unused methods have been called in the example code.

ACKs for top commit:
  tcharding:
    ACK f6abdcc001
  apoelstra:
    ACK f6abdcc001 successfully ran local tests

Tree-SHA512: c3de1775ecde6971056e9fed2c9fa1621785787a6a6ccbf3a6dbd11e18d42d4956949f3f8adfc75d94fd25db998b04adb1c346cc2c2ba47f4dc37402e1388277
2024-09-20 02:10:51 +00:00
merge-script 4fb2fccd16
Merge rust-bitcoin/rust-bitcoin#3367: Comment from_str methods
f5cae1cddd Comment from_str methods (yancy)

Pull request description:

  Follow up from https://github.com/rust-bitcoin/rust-bitcoin/pull/3346

ACKs for top commit:
  tcharding:
    ACK f5cae1cddd
  apoelstra:
    ACK f5cae1cddd successfully ran local tests

Tree-SHA512: 2b95381e5281754e2b3a49aa8dfaac5742c244970fb54f68024dc23b61a74955ae95b9a0e7ae848095ac0686df5faf93faf7de3371b2f341b108cc10e5d4a9cd
2024-09-18 18:26:38 +00:00
merge-script 9e90f7dfd8
Merge rust-bitcoin/rust-bitcoin#3371: Add doc comment detailing fee calculation
8c29fe08f8 Revise doc comment (yancy)

Pull request description:

  Update doc comment to make clear that the ceiling is computed instead of the default behavior for integer division.

ACKs for top commit:
  tcharding:
    ACK 8c29fe08f8
  apoelstra:
    ACK 8c29fe08f8 successfully ran local tests

Tree-SHA512: 3793dccab5b5a3e59b3949ecb54475c76263e1debcc18df42f3b0251189435ba87e537c4b5d80c91f4b916449618a75e6efac32b4ba2fc29c42563e1b0fb4a89
2024-09-18 16:58:00 +00:00
Jamil Lambert, PhD fd89ddf401
Remove or fix unused variables and methods in docs
Examples in documentation are not linted in the same way as other code,
but should still contain correctly written code.

Throughout all of the crates except internals (another commit) unused
variables have been prefixed with `_`, unused imports have been removed,
and a warn attribute added to all of the `lib.rs` files.
2024-09-18 16:37:47 +01:00
Tobin C. Harding 18110a51f2
Bump version of internals to 0.4.0
In preparation for releasing `internals v0.4.0` bump the version number,
add a changelog entry, update the lock files, and depend on the new
version in all crates that depend on `internals`.
2024-09-18 12:22:59 +10:00
yancy f5cae1cddd Comment from_str methods 2024-09-17 17:19:51 -05:00
yancy 8c29fe08f8 Revise doc comment
Comment that the ceiling is computed instead of the floor.
2024-09-17 17:12:48 -05:00
Fmt Bot 7990724ff4 2024-09-15 automated rustfmt nightly 2024-09-15 01:19:55 +00:00
merge-script 7360c3ce9a
Merge rust-bitcoin/rust-bitcoin#3346: Add a condition for parsing zero from string when not denominated.
894f82e7cc Add a condition for parsing zero from string when not denominated. (yancy)

Pull request description:

  closes https://github.com/rust-bitcoin/rust-bitcoin/issues/3307

ACKs for top commit:
  Kixunil:
    ACK 894f82e7cc
  tcharding:
    ACK 894f82e7cc
  apoelstra:
    ACK 894f82e7cc9eb459a297d43e82734621e0824610; successfully ran local tests.

Tree-SHA512: 6d32847c74ccedc3355d615838e2dd1e08add29cc47ff69d9ef22683eda93049d41131dd0c992c8d7be3a018f5438856c415a3d2f3cb9de9c986534b268ee386
2024-09-13 17:41:38 +00:00
yancy 894f82e7cc Add a condition for parsing zero from string when not denominated. 2024-09-12 09:34:18 -05:00
Shing Him Ng eda87517c0 Update documentation to indicate that the Display implementation in Amount is unstable 2024-09-07 15:05:14 -05:00
Tobin C. Harding 8f5bde9f17
units: Fix typo in measured
Its "time is measured" not "time is measure".
2024-09-04 14:45:05 +10:00
merge-script 3bbe821ce5
Merge rust-bitcoin/rust-bitcoin#3268: Fix clippy rustdocs warnings
b6371b5801 Fix clippy rustdocs warnings (Tobin C. Harding)

Pull request description:

  A new nightly version (`nightly-2024-08-28`) introduces a few warnings because of our rustdocs. These are valid warnings and should be fixed, thanks `clippy` team.

  (The `bip152` change is a bit sloppy, open to suggestions.)

ACKs for top commit:
  apoelstra:
    ACK b6371b5801 successfully ran local tests
  Kixunil:
    ACK b6371b5801

Tree-SHA512: 503fb9d48772b74a5acdb26c0f77a85c52323c03360f983204fccee0f28bedeff142237b067caa1ce6ea04ea9842cc493e0d06dc141ca00a98151fa002b62392
2024-09-02 14:20:44 +00:00
Fmt Bot fa71b0e044 2024-09-01 automated rustfmt nightly 2024-09-01 01:22:04 +00:00
merge-script c2e3e86106
Merge rust-bitcoin/rust-bitcoin#3274: Add Arbitrary to SignedAmount type
3f244db19d Add Arbitrary to SignedAmount type (yancy)

Pull request description:

  While proptesting, I've found Arbitrary for SingedAmount to be useful.  Would appreciate adding this as well.

ACKs for top commit:
  tcharding:
    ACK 3f244db19d
  Kixunil:
    ACK 3f244db19d

Tree-SHA512: f293215505db85998135c75e147f4cb0031a08c7db619b706e6c7d632c6f23783af56992531396aecc6e3da55b107a7f2c7ec4d68a3e5737ebcf4225f306ed29
2024-08-30 20:08:17 +00:00
yancy 3f244db19d Add Arbitrary to SignedAmount type 2024-08-29 20:19:48 -05:00
Tobin C. Harding b6371b5801
Fix clippy rustdocs warnings
A new nightly version (`nightly-2024-08-28`) introduces a few warnings
because of our rustdocs. These are valid warnings and should be fixed,
thanks `clippy` team.

(The `bip152` change is a bit sloppy, open to suggestions.)
2024-08-30 05:47:31 +10:00
merge-script cfb53c7866
Merge rust-bitcoin/rust-bitcoin#3257: Add Arbitrary to Weight
f8edbd1f45 Add Arbitrary to Weight (yancy)

Pull request description:

  Adds Arbitrary to the Weight type.  I had meant to add this with the initial Arbitrary PR but I overlooked it.

ACKs for top commit:
  tcharding:
    ACK f8edbd1f45
  Kixunil:
    ACK f8edbd1f45

Tree-SHA512: b886f78285b5cd06b2531a1e53272cad623a8e43e76e8108abe90668b45d00674b6a867c5ff980ee7f0a34919e1d6bb534624bd0bc67a53c8c9a41ea2ed504e8
2024-08-28 23:02:13 +00:00
Jamil Lambert, PhD 9fce57b738
Change T::from_str(s) to s.parse::<T>() in tests
`s.parse` is more idiomatic and produces more helpful error messages.

This has been changed repo wide in tests.
2024-08-28 16:13:03 +01:00
Jamil Lambert, PhD c835bb9eab
Change T::from_str(s) to s.parse::<T>() in docs
`s.parse` is more idiomatic and produces more helpful error messages.

This has been changed repo wide in docs.
2024-08-28 13:50:42 +01:00
yancy f8edbd1f45 Add Arbitrary to Weight 2024-08-27 18:34:47 -05:00
Jamil Lambert, PhD a76d76eca1
Change `T::from_str(s)` to `s.parse::<T>()`
`s.parse` is more idiomatic and produces more helpful error messages.

This has been changed repo wide in the main codebase, not including
examples, rustdocs, and in the test module.

`use std::str::FromStr;` has been removed where this change makes
it unnecessary.
2024-08-27 17:31:00 +01:00
yancy bab2fc44b6 Bump units version 2024-08-26 13:04:15 -05:00
merge-script 51af258eaa
Merge rust-bitcoin/rust-bitcoin#3015: Add Arbitrary
3e034d5ede Add Arbitrary dependency (yancy)

Pull request description:

  Adds an example draft showing what is needed to use Arbitrary for coin selection.

  Shot out to how nice Arbitrary is for fuzzing a target by taking unstructured randomness and creating structured rust-bitcoin types for fuzzing.  Is there a way we could add this to rust-bitcoin for structuring the fuzz data needed?

  This is then the example to fuzz test a SRD algo (after applying this PR to rust-bitcoin) using rust-bitcoin types :)

  ```
  #![no_main]

  use arbitrary::Arbitrary;
  use bitcoin::{Amount, FeeRate};
  use bitcoin_coin_selection::{select_coins_srd, WeightedUtxo};
  use libfuzzer_sys::fuzz_target;
  use rand::thread_rng;

  #[derive(Arbitrary, Debug)]
  pub struct Params {
      target: Amount,
      fee_rate: FeeRate,
      weighted_utxos: Vec<WeightedUtxo>,
  }

  fuzz_target!(|params: Params| {
      let Params { target: t, fee_rate: f, weighted_utxos: wu } = params;
      select_coins_srd(t, f, &wu, &mut thread_rng());
  });
  ```

ACKs for top commit:
  tcharding:
    ACK 3e034d5ede
  Kixunil:
    ACK 3e034d5ede
  apoelstra:
    ACK 3e034d5ede successfully ran local tests

Tree-SHA512: accd565815de3b37730d2ff12a24fcfc84e52ad357e5c940b1500a1e0bb17f4ff5fd6e52d31e8e96bb5290ee4fa050cfd2a9bbd6bbae13fc378f43093b64177f
2024-08-25 13:16:49 +00:00
merge-script 837fc9c9c2
Merge rust-bitcoin/rust-bitcoin#2972: Use index size rather than pointer size to enforce convertibility of `u32` to `usize`
c427d8b213 bitcoin: Compile time assert on index size (Tobin C. Harding)
49a6acc1a0 internals: Remove double parenthesis in const_assert (Tobin C. Harding)
2300b285ef units: Remove compile time pointer width check (Tobin C. Harding)

Pull request description:

  3 patches in preparation for other size related work, this PR does not touch the `ToU64` issue which will be handled separately.

  - Patch 1: Don't check pointer width in `units` because its not consensus code
  - Patch 2: Modify internal macro `const_assert`
  - Patch 3: Use index size to enforce not building on a 16 bit machine

ACKs for top commit:
  Kixunil:
    ACK c427d8b213 though I think the last commit was kinda a waste of time and it should have been adding the trait instead or leave it for later.
  apoelstra:
    ACK c427d8b213 successfully ran local tests; unsure if we want to merg this or wait for #3215

Tree-SHA512: 823df5b6a5af3265bce2422c00d287f45816faeb5f965685650ac974a1bd441cf548e25ac2962591732ff221bee91a55703da936382eb166c014ca5d4129edf8
2024-08-24 14:16:31 +00:00
yancy 3e034d5ede Add Arbitrary dependency
Implement Arbitrary for a select subset of types.
2024-08-23 15:39:20 -05:00
Tobin C. Harding 60b3cabb41
Panic in const context
Now that our MSRV is past 1.57 we can panic in const contexts.

Fix: #2427
2024-08-22 17:37:17 +10:00
Tobin C. Harding 2300b285ef
units: Remove compile time pointer width check
The `units` crate does not contain consensus logic and since our
requirement to only support 32-bit and 64-bit machines is due to
consensus logic we do not need to enforce the `target_pointer_width` in
the `units` crate.

Remove the compile time check on pointer width from the `units` crate.
2024-08-02 11:33:30 -05:00
Martin Habovstiak c72069e921 Bump MSRV to 1.63
The version 1.63 satisfies our requirements for MSRV and provides
significant benefits so this commit bumps it. This commit also starts
using some advantages of the new MSRV, namely namespaced features, weak
dependencies and the ability to use trait bounds in `const` context.

This however does not yet migrade the `rand-std` feature because that
requires a release of `secp256k1` with the same kind of change - bumping
MSRV to 1.63 and removing `rand-std` in favor of weak dependency.
2024-07-27 07:24:32 +02:00
Tobin C. Harding e3d9376a9b
units: Remove serde re-export
We re-export to help users keep their dependencies in sync but `serde`
is at `v1.0` so this is not really a problem.

Remove the public re-export of `serde` (and with current MSRV we don't
need the `extern crate` at all).
2024-07-23 01:41:41 -05:00
merge-script e1478b1802
Merge rust-bitcoin/rust-bitcoin#3069: Remove re-export of `ParseIntError`
ab581a90f8 Remove re-export of ParseIntError (Tobin C. Harding)

Pull request description:

  In d242125 I claimed that `ParseIntError` was somehow special, I no longer thing this is the case. As we pin down the re-export policy (for errors and other types) it is hard if we have one non-typical re-export.

  We have https://github.com/rust-bitcoin/rust-bitcoin/issues/3068 to discuss the policy, for now just remove the unusual re-export.

ACKs for top commit:
  Kixunil:
    ACK ab581a90f8
  shinghim:
    ACK ab581a90f8
  apoelstra:
    ACK ab581a90f8

Tree-SHA512: 5ac4123aeb27c8cee78e5760f21e70be8035d526ba7e14e72759cba27f98b51cc2cba9b2bf0eeb99e0f6b7210ec4a750986bb6c5dc0725ed892730fdec8a7e06
2024-07-19 15:36:21 +00:00
merge-script a28f11c9fb
Merge rust-bitcoin/rust-bitcoin#3062: Add more unit test coverage for relative LockTime
a76c13f675 Add more unit test coverage for relative LockTime (Shing Him Ng)

Pull request description:

  Adding some test cases for `from_seconds_floor` and one more for `from_seconds_ceil`

ACKs for top commit:
  tcharding:
    ACK a76c13f675
  Kixunil:
    ACK a76c13f675

Tree-SHA512: 5d773a30fa56842af21109d232ec3eae7fde7ce38aca93dadccc7bfbf14d5207ea329ef737f847e45ba755fd22e1862c3e78e7e64a8a0babebcb0e27a2bb7a90
2024-07-18 14:21:46 +00:00
Tobin C. Harding ab581a90f8
Remove re-export of ParseIntError
In d242125 I claimed that `ParseIntError` was somehow special, I no
longer thing this is the case. As we pin down the re-export policy (for
errors and other types) it is hard if we have one non-typical re-export.

We have https://github.com/rust-bitcoin/rust-bitcoin/issues/3068 to
discuss the policy, for now just remove the unusual re-export.
2024-07-17 08:01:32 +10:00
Shing Him Ng a76c13f675 Add more unit test coverage for relative LockTime 2024-07-16 12:19:13 -05:00
merge-script 8eb5d8fad0
Merge rust-bitcoin/rust-bitcoin#3019: Fix error messages
2169b75bba Use lower case error messages (Jamil Lambert, PhD)

Pull request description:

  Error messages should be lower case, except for proper nouns and variable names.  These have all been changed.

  ~~They should also state what went wrong.  Some expect error messages were positive, giving the correct behaviour or correct input.  These have been changed so that they are now negative, i.e. saying what went wrong.~~

  EDIT: After further discussion it was decided not to change the expect messages.

ACKs for top commit:
  Kixunil:
    ACK 2169b75bba
  tcharding:
    ACK 2169b75bba

Tree-SHA512: 92442c869e0141532425f6fca5195fd319b65026f68c4230a65ad70253565d98931b2b44ee202975c307280525c505147e272297dc81207312e40c43d007021c
2024-07-16 15:30:26 +00:00
merge-script f765deb160
Merge rust-bitcoin/rust-bitcoin#3052: Throw error instead of panic when from_second_ceil input is too large
7874db8fc3 Throw error instead of panic when from_second_ceil input is too large (Shing Him Ng)

Pull request description:

  Update `from_second_ceil` per [comment](https://github.com/rust-bitcoin/rust-bitcoin/issues/3029#issuecomment-2227459248) and add unit tests

  Resolves #3029

ACKs for top commit:
  Kixunil:
    ACK 7874db8fc3
  tcharding:
    ACK 7874db8fc3

Tree-SHA512: 0d60397f867d4536ff00b81441c27ea3dc4bf9e5ecc2fb5afbe50cb3153101df54c2bb5056da1916d83c3e84367f987f5bac07a381b7433a5701a0ea8a587f95
2024-07-16 13:36:23 +00:00
merge-script 12f47c72c5
Merge rust-bitcoin/rust-bitcoin#3030: Rename variable assignment
84dd04cf60 Rename variable assignment (yancy)

Pull request description:

  The type created after assignment is a Weight type.  Using a var name vb which is short for virtual byte is incorrect.

  Pulled this out of stale PR 2215

ACKs for top commit:
  shinghim:
    ACK 84dd04cf60
  apoelstra:
    ACK 84dd04cf60
  Kixunil:
    ACK 84dd04cf60

Tree-SHA512: 1bfc875f53037b2c1e8da25fe44e9ca3303981bdce4e48661a8fb2061833e3cd90318d854f7119c805e861cd8a591697378f829f32eb74ac99a71dc4c947abde
2024-07-15 22:40:37 +00:00
yancy 84dd04cf60 Rename variable assignment
The type created after assighnment is a Weight type.  Using a var name
vb which is short for virtual byte is incorrect.
2024-07-15 10:05:47 -05:00
Shing Him Ng 7874db8fc3 Throw error instead of panic when from_second_ceil input is too large 2024-07-15 07:55:41 -05:00
Jamil Lambert, PhD 2169b75bba Use lower case error messages
Error messages should start with a lower case character unless it is a
proper noun.

This has been changed everywhere.
2024-07-15 09:25:08 +01:00
yancy 301fe9fad9 Move impl above tests
It's common in other modules for the tests to be at the end of the file.
Moving the tests to the bottom helps the code base uniformity.
2024-07-13 14:57:31 -05:00
Tobin C. Harding 40bee24de7
Run the formatter
I don't want to wait for the bot, just run the formatter now.

No manual changes.
2024-07-11 11:21:53 +10:00
merge-script 0511f44d99
Merge rust-bitcoin/rust-bitcoin#2994: Remove private prelude module from `units` crate
1cce1b5aa6 Remove private prelude module from units crate (Jamil Lambert, PhD)

Pull request description:

  The private prelude module has been removed from the units crate and instead imports are stated in full when needed.  As discussed in #2926.

ACKs for top commit:
  Kixunil:
    ACK 1cce1b5aa6
  apoelstra:
    ACK 1cce1b5aa6

Tree-SHA512: 58b93ff66f74399938bc1a7f59fe8d2a21d0437c7e90e0c190d3d6a8de30f9c9268c8e4288d1db287b4d190624968937b1ad6c6e54d29025370e47e71be925c1
2024-07-10 21:56:03 +00:00
Jamil Lambert, PhD 1cce1b5aa6 Remove private prelude module from units crate
The private prelude module has been removed from the units crate and
instead imports are stated in full when needed.
2024-07-10 09:14:33 +01:00
merge-script 13e27acb16
Merge rust-bitcoin/rust-bitcoin#2957: Fix rustdocs in `units` crate
6dd5af9678 Add missing links (Jamil Lambert, PhD)
47e367f011 Standardize error headings (Jamil Lambert, PhD)
75f317a689 Fix rustdoc grammar (Jamil Lambert, PhD)
573f8ce724 Add backticks to rustdoc links (Jamil Lambert, PhD)

Pull request description:

  The rustdocs in the `units` crate has been reviewed and improved.

  Some of the links were missing backticks, these have been added.

  Some grammatical changes have been made to improve the documentation.

  The use of links was inconsistent and has been changed to have links everywhere that seemed appropriate.

  A couple of error headings were added and a description as to why a capital M is not accepted in the denomination for MegaSatoshi or MegaBitcoin.

ACKs for top commit:
  apoelstra:
    ACK 6dd5af9678
  tcharding:
    ACK 6dd5af9678

Tree-SHA512: f5481a7c3aa99d7882cda9ccda9df9e27f092ff91ef584f07dc887f38bfe12e5ea801cfa7f42bb4022301860489ee6be55557752a8cbe70932f258ea753495dc
2024-07-09 14:13:32 +00:00
merge-script b392510ec1
Merge rust-bitcoin/rust-bitcoin#2889: Move `serde_round_trip` macro to internals
7fa53440dc Move serde_round_trip macro to internals (Tobin C. Harding)

Pull request description:

  We currently duplicate the serde_round_trip macro in `units` and `bitcoin`, this is unnecessary since it is a private test macro we can just throw it in `internals`.

  While we are at it lets improve the macro by testing a binary encoding also, elect to use the `bincode` crate because we already have it in our dependency graph.

  Add `test-serde` feature to `internals` to feature gate the macro and its usage (preventing the transient dependency on `bincode` and `serde_json`).

ACKs for top commit:
  Kixunil:
    ACK 7fa53440dc
  apoelstra:
    ACK 7fa53440dc

Tree-SHA512: f40c78bf2539940b7836ed413d5fe96ce4e9ce59bad7b3f86d831971320d1c2effcd23d0da5c785d6c372a2c6962bf720080ec4351248fbbdc0f2cfb4ffd602c
2024-07-08 20:50:23 +00:00
Jamil Lambert, PhD 6dd5af9678 Add missing links
The use of links in the rustdocs was inconsistent.

Links have been added when missing.

[`locktime::absolute::Height`] and [`locktime::relative::Height`] did
not work and `(crate::locktime)` was appended to fix it.
2024-07-08 08:53:13 +01:00
Jamil Lambert, PhD 47e367f011 Standardize error headings
Created headings for a couple of function error descriptions to be
consistent with the rest of the crate.

Added a description explaining why Mega is not allowed in a
denomination.
2024-07-08 08:52:15 +01:00
Jamil Lambert, PhD 75f317a689 Fix rustdoc grammar
In the rustdocs, made all function descriptions third person. Corrected
some grammar and improved some wording.
2024-07-08 08:52:15 +01:00
Jamil Lambert, PhD 573f8ce724 Add backticks to rustdoc links
Links in rustdocs should be formatted with a backtick.  This has been
changed throughout Units.
2024-07-08 08:52:15 +01:00
Fmt Bot 91382977fb 2024-07-07 automated rustfmt nightly 2024-07-07 01:10:59 +00:00
Tobin C. Harding 7fa53440dc
Move serde_round_trip macro to internals
We currently duplicate the serde_round_trip macro in `units` and
`bitcoin`, this is unnecessary since it is a private test macro we can
just throw it in `internals`.

While we are at it lets improve the macro by testing a binary encoding
also, elect to use the `bincode` crate because we already have it in
our dependency graph.

Add `test-serde` feature to `internals` to feature gate the macro and
its usage (preventing the transient dependency on `bincode` and
`serde_json`).
2024-07-06 14:51:30 +10:00
yancy dfce405007 Remove nonsense method
Weight type implicitly includes witness scale factor
2024-07-04 12:11:46 -05:00
merge-script 014c4931be
Merge rust-bitcoin/rust-bitcoin#2951: Fix `Amount` decimals handling
3196c271ac Deprecate `Amount::fmt_value_in` (Martin Habovstiak)
467546fc0c Round `Amount` when requested precision is too low (Martin Habovstiak)
7c95a777c1 Fix `Amount` decimals handling (Martin Habovstiak)

Pull request description:

  Displaying with minimal number of zeros is the default in Rust and we want to follow it. This was originally implemented in #716 but #2604 reversed it claiming this is common, however it broke people who rely on minimal display (e.g. BIP21) without fixing the root cause of #2136.

  This reverts commit d887423efc adds a test to prevent this change and also fixes the problem with `{:0.8}` not working.

  Closes #2136
  Closes #2948

  Can we backport this one too?

ACKs for top commit:
  tcharding:
    ACK 3196c271ac
  apoelstra:
    ACK 3196c271ac I also really like how this reduces the complexity of the module, basically passing everything through to `display_in`

Tree-SHA512: 3221f83086ac55af3d4caad03fe2b619be303533bba12096040419d119600c8597938809e171662f11b515d469156b083b2072b901d445e4fdfc7b1062cf7b6a
2024-07-04 13:19:32 +00:00
Martin Habovstiak 3196c271ac Deprecate `Amount::fmt_value_in`
`fmt_value_in` was added when `display_in` wasn't available. However
common usage patterns seem to favor `display_in`. It can be used within
format strings and supports formatting options.

Removing it will simplify the codebase, so this deprecates it.
2024-07-03 07:38:58 +02:00
Martin Habovstiak 467546fc0c Round `Amount` when requested precision is too low
Low precision was previously not considered because it was believed it
could lead to misleading data being displayed. However it's quite
possible that people using low precision know what they are doing and
it's sometimes useful to show rounded numbers.

To enable low precision we just compute what the rounded number would be
and display that one instead.

This actually fully closes #2136 since this issue was mentioned there
along with previously-fixed displaying of higher precisions.
2024-07-02 18:39:56 +02:00
Martin Habovstiak 7c95a777c1 Fix `Amount` decimals handling
Displaying with minimal number of zeros is the default in Rust and we
want to follow it. This was originally implemented in #716 but #2604
reversed it claiming this is common, however it broke people who rely on
minimal display (e.g. BIP21) without fixing the root cause of #2136.

This reverts commit d887423efc adds a test
to prevent this change and also fixes the problem with `{:0.8}` not
working.

Closes #2136
Closes #2948
2024-07-02 18:38:54 +02:00
merge-script e1b357ce10
Merge rust-bitcoin/rust-bitcoin#2940: Revert "bug fix" (actually a bug) from #2655
7f024c333e Revert "bug fix" (actually a bug) from #2655 (Martin Habovstiak)

Pull request description:

  In a2b019f82 it was claimed that losing the input string without alloc is a bug. It is not, because allowing no-alloc is desired and there's no way to have the input string otherwise so we just accept it'll be missing and modify the messages accordingly. The commit that forced alloc was also horribly misleading since it kept the `alloc` feature but it makes this one easier.

  Note that input string is still present by default in all configurations except for no-alloc.

  I think we should also backport this and release fixed `units` because of the misleading `alloc` feature in them. Although it's not urgent. The only crate I know of that is kinda broken by it is `ln_types` which is already broken by depending on old `bitcoin`.

ACKs for top commit:
  apoelstra:
    ACK 7f024c333e
  tcharding:
    ACK 7f024c333e

Tree-SHA512: 014ed823f0daf2c47ca6cedf1aad0d94b702f2ca53b096556a76566baeadb209b9d4d710872c2b8308542fd7cfe6d815a206f1a84174458d251bf30882be7719
2024-07-02 14:47:08 +00:00
merge-script 96dffb2152
Merge rust-bitcoin/rust-bitcoin#2939: Automated nightly rustfmt (2024-06-30)
19b093080b 2024-06-30 automated rustfmt nightly (Fmt Bot)

Pull request description:

  Automated nightly `rustfmt` changes by [create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub action

ACKs for top commit:
  apoelstra:
    ACK 19b093080b

Tree-SHA512: 50d905ab4823e5e746751c0aacd145fc5640c9cb250d99bcd44800c72a890562c0014a9eee21602198388dee7bd9354ff764bab5616aac82bf7660669f8c2ee1
2024-06-30 12:09:40 +00:00
Martin Habovstiak 7f024c333e Revert "bug fix" (actually a bug) from #2655
In a2b019f82 it was claimed that losing the input string without alloc
is a bug. It is not, because allowing no-alloc is desired and there's
no way to have the input string otherwise so we just accept it'll be
missing and modify the messages accordingly. The commit that forced
alloc was also horribly misleading since it kept the `alloc` feature but
it makes this one easier.

Note that input string is still present by default in all configurations
except for no-alloc.
2024-06-30 09:40:37 +02:00
Fmt Bot 19b093080b 2024-06-30 automated rustfmt nightly 2024-06-30 01:10:26 +00:00
Jamil Lambert, PhD d099b9c195 Remove wildcard from prelude import
Wildcards have been replaced with what is actually used.

In a couple of cases an additional use statement was added to the test
module to import `DisplayHex` which is only used in test, but
previously imported with the wildcard at the top.
2024-06-28 08:02:43 +01:00
merge-script 0f3a9969fd
Merge rust-bitcoin/rust-bitcoin#2915: Clean up manifests
bc25ed35d5 Order serde feature list alphabetically (Tobin C. Harding)
5bd3387c15 Move package metadata to be underneath package section (Tobin C. Harding)
a2a9f193fe Put workspace crates in alphabetical order (Tobin C. Harding)
05931cc0fa Run the formatter (Tobin C. Harding)

Pull request description:

  We are getting an increasing number of crates in the repo, clean up the manifests a bit in an endevour to help keep things manageable.

  All  patches are trivial and the PR makes no logic changes.

ACKs for top commit:
  Kixunil:
    ACK bc25ed35d5
  apoelstra:
    ACK bc25ed35d5

Tree-SHA512: a9850449a6f71ac5d53f501e36175e900bf4986f44c7636d3b1b55df80804b92bb10d8da7798f6bb866722aa2354ad2880ab5c0f5c4633f198c137d2ca42b7c9
2024-06-27 14:30:18 +00:00
Tobin C. Harding 5bd3387c15
Move package metadata to be underneath package section
The package metatadata never changes and is not necessary to look at
basically ever, put it down the bottom of the manifest out of the way.

Helps to keep features and dependencies closer together.

Refactor only, no logic changes.
2024-06-25 10:02:27 +10:00
Jamil Lambert, PhD 9ea8c58ad6 Fix case sensitivity of denomination
The comment in `FromStr` says that any combination of upper and lower case is considered valid, but the code only allowed a set list of variations. It also had a non exhaustive list of `CONFUSING_FORMS`.

The comment and code has been changed to only consider all upper case or all lower case denominations as valid or where BTC/btc is prefixed with a lower case c, m or u.  `CONFUSING_FORMS` has been changed to contain all combinations of an upper case prefix on an otherwise valid denomination.
2024-06-18 10:46:17 +01:00
Jamil Lambert, PhD 67569ca632 Remove denominations < 1 satoshi
Removed all millisatoshi, nano and pico bitcoin denominations and tests from `Amount`
2024-06-18 10:26:20 +01:00
Jamil Lambert, PhD 4a9f74b55c fix missing fullstops in bitcoin rustdoc
Added missing fullstops to the rustdoc titles for everything on the main page of the bitcoin crate
2024-06-06 16:37:12 +01:00
Tobin C. Harding 60ab3d26e5
CI: Remove shebang from non-executable scripts
Some of our CI shell scripts are meant only to be sourced and not
run directly however they include an initial shebang line, implying that
they should be run.

Remove the shebang line from `crates.sh` and the various `test_vars.sh`
scripts. Add a `shellcheck` directive to inhibit the no-shebang warning.

Fix: #2764
2024-05-31 10:10:00 +10:00
Tobin C. Harding 1173f3fbff
units: Add BlockHeight and BlockInterval types
Add two simple integer wrapper types for abstracting over block
height (from genesis block) and block interval.

This does not include hex because block height is typically written in
decimal.

These types are very thin wrappers, their usecase is to assist in code
readability instead of enforcing any logic.
2024-05-30 16:49:30 +10:00
Andrew Poelstra 6d06a32d9c
Merge rust-bitcoin/rust-bitcoin#2755: Fix units public re-exports
d2a597c90d unit: Group re-exports (Tobin C. Harding)
d242125ae4 units: Fix error re-exports (Tobin C. Harding)

Pull request description:

  First patch is the meat and potatoes, second one is just a trivial refactor to the same code, done separately so as to make the changes in the first patch more clear.

  From patch 1
  ```
      units: Fix error re-exports

      Currently we re-export two error types at the crate root, this is
      surprising because:

      - Why not none or all the rest?
      - Why these two?

      Observe that the `ParseIntError` is special in that it is used by
      other modules so its good to have at the crate root (other errors are
      expected to be used with a module prefix eg, `amount::ParseError`).

      There is no obvious reason why `ParseAmountError` is re-exported.

      Comment and doc inline the `ParesIntError`, remove the re-export of
      the `ParseAmountError`.
  ```

ACKs for top commit:
  apoelstra:
    ACK d2a597c90d

Tree-SHA512: 38d3f590357e66d07cbd7fedff134c39e0920e076ea99cb34ba276749a14695d428345d7b0f9ec8222f7899cb57e7c97068d3b6e7b2a9be25a0278e0a1abf762
2024-05-28 15:46:53 +00:00
Fmt Bot 4499c4c046 2024-05-26 automated rustfmt nightly 2024-05-26 01:07:01 +00:00
Andrew Poelstra e96961f333
Merge rust-bitcoin/rust-bitcoin#2798: Standardize rustdoc subheadings
11bb1ff6ff Standardize function doc Safety, Returns and Parameters (jamil.lambert)
df83016c98 Standardize function doc Errors (jamil.lambert)
d219ceb68e Standardize function doc Examples (jamil.lambert)
233a9133d8 Standardize function doc Panics (jamil.lambert)

Pull request description:

  The subheadings in the rustdocs have been standardized according to [./CONTRIBUTING.md](https://github.com/rust-bitcoin/rust-bitcoin/blob/master/CONTRIBUTING.md):
  ```rust
  impl FooBar {
      /// Constructs a `FooBar` from a [`Baz`].
      ///
      /// # Errors
      ///
      /// Returns an error if `Baz` is not ...
      ///
      /// # Panics
      ///
      /// If the `Baz`, converted to a `usize`, is out of bounds.
      pub fn from_baz(baz: Baz) -> Result<Self, Error> {
          ...
      }
  }
  ```

ACKs for top commit:
  apoelstra:
    ACK 11bb1ff6ff
  tcharding:
    ACK 11bb1ff6ff

Tree-SHA512: 163af3cd1cfb47cea3e55eddeaeb6843ff7ec89c57354e3247d6bae85e756b183e8045c2555cfcf87e8c23c1388ff9d7592cfb6a951a37a9ec41d27263e5a2e4
2024-05-25 14:55:16 +00:00
jamil.lambert d219ceb68e Standardize function doc Examples
Changed the function docs to have the same format of
///
/// # Examples
///
/// description
2024-05-24 09:59:42 +01:00
jamil.lambert 233a9133d8 Standardize function doc Panics
Changed the function docs to have the same format of
///
/// # Panics
///
/// description
2024-05-24 09:59:29 +01:00
Tobin C. Harding a5b93cb159
Flesh out hex unit parsing API
Add to `units::parse` the complete suit of hex unit parsing functions:

- remove prefix
- assert without prefix
- parse with or without prefix
- parse with prefix
- parse without prefix
- parse prefix unchecked

Refactor `bitcoin` to use the exact function we need, removing code
duplication.

This is a breaking change to `units`, it does however keep the current
re-exports from the public, now empty, `bitcoin::error` module.
2024-05-24 14:32:47 +10:00
Andrew Poelstra 1142d16192
Merge rust-bitcoin/rust-bitcoin#2785: Whitelist cfg attrs and bump nightly version
30a482504b bump nightly-version (Andrew Poelstra)
5ad7c245e3 cargo: whitelist all cfgs used in this repo (Andrew Poelstra)
814786b0a6 crypto: enable and fix accidentally disabled unit test (Andrew Poelstra)

Pull request description:

  https://github.com/rust-lang/rust/issues/124800 has been fixed and we can update our nightly version by whitelisting all cfgs that are used.

  There was one place where we had an old `cfg(feature = "no-std")` despite having removed the feature. By removing that cfg check we re-enabled a previously disabled test.

ACKs for top commit:
  tcharding:
    ACK 30a482504b

Tree-SHA512: d25bed819091db74b9d47cb2c23caa3ceb0d7be323b37831326e2ec1608cb1577d41aad2e1cdf59d66df69397537bc3e17a3c2872935d5a4f46f4dc55b5e613c
2024-05-23 16:52:22 +00:00
Andrew Poelstra 5ad7c245e3
cargo: whitelist all cfgs used in this repo 2024-05-22 13:32:24 +00:00
jamil.lambert 101378c4d0 Removed //! spare line at end of headers
Some of the headers had a //! at the end but most didn't. They have all been removed in units/src/ to make the files consistent
2024-05-22 12:29:41 +01:00
Jose Storopoli 021bea89bb
ci: shellcheck checks 2024-05-11 18:08:53 +00:00
Tobin C. Harding d2a597c90d
unit: Group re-exports
As is customary group the public re-exports differently to other use
statements and tell rustfmt to skip them.

Refactor only, no logic changes.
2024-05-08 11:53:53 +10:00
Tobin C. Harding d242125ae4
units: Fix error re-exports
Currently we re-export two error types at the crate root, this is
surprising because:

- Why not none or all the rest?
- Why these two?

Observe that the `ParseIntError` is special in that it is used by
other modules so its good to have at the crate root (other errors are
expected to be used with a module prefix eg, `amount::ParseError`).

There is no obvious reason why `ParseAmountError` is re-exported.

Comment and doc inline the `ParesIntError`, remove the re-export of
the `ParseAmountError`.
2024-05-08 11:51:58 +10:00
Andrew Poelstra 819eaa95bc
Merge rust-bitcoin/rust-bitcoin#2633: CI: Re-write `run_task.sh`
26b9782d8b CI: Re-write run_task.sh (Tobin C. Harding)

Pull request description:

  Recently we re-wrote CI to increase VM level parallelism, in hindsite this has proved to be not that great because:

  - It resulted in approx 180 jobs
  - We are on free tier so only get 20 jobs (VMs) at a time so its slow to run
  - The UI is annoying to dig through the long job list to find failures

  Have another go at organising the jobs with the main aim of shortening total run time and making it easier to quickly see fails.

  Re-write the `run_task.sh` script, notable moving manifest handling to the workflow. Also don't bother testing with beta toolchain.

  ### Note on review

  The diff is hard to read for `rust.yml`, I tried splitting out a bunch of separate patches but it resulted in the same thing (because there are so many identical lines in the yaml file). I suggest just looking at the yaml file and not the diff.

ACKs for top commit:
  apoelstra:
    ACK 26b9782d8b
  sanket1729:
    ACK 26b9782d8b.

Tree-SHA512: 1b0a0bab5cf729c5890f7150953499b42aebd3b1c31a1b0d3dfa5b5e78fda11e17a62a2df6b610ab4a950d5709f3af6fff1ae64d9e67379338903497ab77ae0e
2024-04-29 11:15:00 +00:00
Jose Storopoli b355740da4
chore: format and standardize all markdowns files
according to the github flavor
(https://github.github.com/gfm/)
2024-04-27 06:29:23 -03:00
Tobin C. Harding 26b9782d8b
CI: Re-write run_task.sh
Recently we re-wrote CI to increase VM level parallelism, in hindsite
this has proved to be not that great because:

- It resulted in approx 180 jobs
- We are on free tier so only get 20 jobs (VMs) at a time so its slow to run
- The UI is annoying to dig through the long job list to find failures

Have another go at organising the jobs with the main aim of shortening
total run time and making it easier to quickly see fails.

Re-write the `run_task.sh` script, notable moving manifest handling
to the workflow. Also don't bother testing with beta toolchain.

WASM Note

Removes the `cdylib` and `rlib` from the manifest patching during wasm
build - I do not know the following:

- Why this breaks on this PR but not on other PRs
- Why I can't get wasm test to run locally on master but PRs are passing
- What the `cdylib` and `rlib` were meant to be doing

This is the docs from: https://doc.rust-lang.org/reference/linkage.html

* --crate-type=cdylib, #![crate_type = "cdylib"] - A dynamic system
library will be produced. This is used when compiling a dynamic library
to be loaded from another language. This output type will create *.so
files on Linux, *.dylib files on macOS, and *.dll files on Windows.

* --crate-type=rlib, #![crate_type = "rlib"] - A "Rust library" file
will be produced. This is used as an intermediate artifact and can be
thought of as a "static Rust library". These rlib files, unlike
staticlib files, are interpreted by the compiler in future linkage. This
essentially means that rustc will look for metadata in rlib files like
it looks for metadata in dynamic libraries. This form of output is used
to produce statically linked executables as well as staticlib outputs.
2024-04-26 09:41:51 +10:00
Tobin C. Harding e47e57c265
Fix kani test
In a kani test we are checking if the result of `to_unsigned()` is an
error but setting `is_signed` to `true`, this field represents the
signed-ness of the return type of `to_unsigned` (`Amount`) so should be
`false`.

Fix kani daily job.
2024-04-19 06:15:49 +10:00
Tobin C. Harding 5981b15902
kani: Rename tests
The tests currently include the word "add" but they test addition as
well as subtraction. Elect to keep the multiple assertions per test and
just make the names more general.
2024-04-16 10:05:07 +10:00
Tobin C. Harding 17bacc6fb6
kani: Remove redundant import
`cargo` is reporting a redundant import warning:

 warning: the item `TryInto` is imported redundantly

Remove the import statement from the `verification` module.
2024-04-16 06:18:06 +10:00
Andrew Poelstra 163bf64fcc
Merge rust-bitcoin/rust-bitcoin#2668: Automated nightly rustfmt (2024-04-07)
747ca578dd 2024-04-07 automated rustfmt nightly (Fmt Bot)

Pull request description:

  Automated nightly `rustfmt` changes by [create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub action

ACKs for top commit:
  apoelstra:
    ACK 747ca578dd
  tcharding:
    ACK 747ca578dd

Tree-SHA512: c4387388f2cfcb9b9aacf7023d024379cbf073166f04fcba4b4c0d66972ee109f4c9f66e0d8ed1d57c419266680a9e6953a5e38ecb0aa937e6c368d59aaba976
2024-04-08 22:28:08 +00:00
Andrew Poelstra 5c56b69eed
Merge rust-bitcoin/rust-bitcoin#2667: Remove deprecated legacy numeric methods
051c358bcb Remove deprecated legacy numeric methods (Divyansh Gupta)

Pull request description:

  As `rustc 1.79.0-nightly (9d79cd5f7 2024-04-05)` is released which solves the issue mentioned , but the release has deperacted legacy numeric methods.
  Thus replaced `u16::max_value()` etc with `u32::MAX` & `core::u16` to directly `u16`.

  fix #2639

ACKs for top commit:
  tcharding:
    ACK 051c358bcb
  apoelstra:
    ACK 051c358bcb thanks! I will remove an equivalent commit from my #2669

Tree-SHA512: c08c856f7f3b281417c29283351eac5e0f75cc1c8d23d9aae58d969219a327b2337fe57932053e53773ebb9dbec04254f90149266b6639a66c5c09f2ad1675ef
2024-04-07 15:15:47 +00:00
Fmt Bot 747ca578dd 2024-04-07 automated rustfmt nightly 2024-04-07 01:03:23 +00:00
Divyansh Gupta 051c358bcb Remove deprecated legacy numeric methods
As `rustc 1.79.0-nightly (9d79cd5f7 2024-04-05)` is released which solves the issue mentioned , but the release has deperacted legacy numeric methods.
Thus replace `u16::max_value()` etc with `u32::MAX` & `core::u16` to directly `u16`.

fix #2639
2024-04-07 01:51:14 +05:30
Tobin C. Harding e06ebd69e7
units: Bump version number to 0.1.1
We just did a minor bug fix to error code in the `amounts` module. This
change did not effect the public API but improved the display of two
error types from that module.

In preparation for doing a point release bump the version number and add
a changelog entry.
2024-04-04 08:24:28 +11:00
Tobin C. Harding a2b019f823
Enable internals "alloc" feature
We have 2 crates that require an allocator, `bitcoin` and `base58ck` -
these crates should enable the "alloc" feature when depending on
`internals`.

For `units` we use the `internals::error::InputString` but do not enable
the "alloc" feature - this is a bug, it means that the parsed string is
being lost from the error types that use `InputString`.

Enable "alloc" for `bitcoin`, `base58ck`, and `units`.

- `bitcoin` and `base56ck` is just for good measure so we don't get
  bitten later on.
- `units` is a bug fix and requires a point release.
2024-04-04 08:18:51 +11:00
Tobin C. Harding a05da2294e
units: Add an initial changelog
In preparation for the initial release add a changelog. Note the version
number is already set to `v0.1.0` and this does not conflict with the
release currently on crates.io `v0.0.0`.
2024-04-03 14:39:57 +11:00
Tobin C. Harding 36ef4a62cf
units: Improve re-exports
Make an attempt to improve the ergonomics and docs clarity of the
`units` crate.

- Don't inline error type re-exports, this keeps them up in the
"Re-exports" section and saves cluttering the other inlined docs.

- Re-export and inline the docs for `FeeRate` and `Weight` same as we do
for `Amount`. This makes the "Structs" section of the docs nice except
for the exclusion of the locktime types (which cannot be helped).
2024-04-03 11:39:56 +11:00
Tobin C. Harding d33625f6e2
units: Introduce public hex_u128 function
Introduce a function for parsing a `u128` from hex. Support strings with
and without a `0x` prefix as we do for `hex_u32`.
2024-04-03 07:09:46 +11:00
Tobin C. Harding 9705d51782
docs: Use backticks on stdlib type 2024-04-03 07:09:46 +11:00
Tobin C. Harding cf65bf035f
Introduce local variable
To make the stripping of the prefix a little clearer introduce a local
variable.

Refactor only, no logic changes.
2024-04-03 07:09:46 +11:00
Tobin C. Harding 1269722770
Move helper function
Move the `strip_hex_prefix` helper function to below where it is called.
Note that I was the original author of this helper so there is no excuse
for it being above - bad Tobin no biscuit.
2024-04-03 07:09:46 +11:00
Tobin C. Harding dca054c680
test: Add unit tests for hex_u32
Test the current behaviour of `hex_u32` - verifies that we handle
parsing strings with and without a prefix.
2024-04-03 07:09:46 +11:00
Tobin C. Harding 3d01146374
Allow needless-borrows-for-generic-args
This lint triggers when parsing a reference to a large struct as a
generic argument, which is wrong.

Allow it crate wide because [subjectively] this lint never warns for
anything useful.
2024-04-02 11:40:41 +11:00
Andrew Poelstra 684b453b7c
Merge rust-bitcoin/rust-bitcoin#2632: internals: Release tracking PR `v0.3.0`
af6dc1db02 internals: Bump version to 0.3.0 (Tobin C. Harding)

Pull request description:

  In preparation for release add a changelog and bump the version number.

  Please note, the changelog is pretty terse.

ACKs for top commit:
  apoelstra:
    ACK af6dc1db02
  sanket1729:
    ACK af6dc1db02

Tree-SHA512: b70d4b9de7de90aba3cbff90dd7f25c5ac801d020dbdfe3e64af4c079347cba726aa783a94fc777e7bf177db8402b54948c2dfd4a766d90c1a7a7a6bdfd36136
2024-04-02 00:09:04 +00:00
Fmt Bot a565db9fdd 2024-03-31 automated rustfmt nightly 2024-03-31 01:03:18 +00:00
Tobin C. Harding af6dc1db02
internals: Bump version to 0.3.0
In preparation for release add a changelog and bump the version number.
2024-03-27 09:44:30 +11:00
Andrew Poelstra bfd5255ae8
Merge rust-bitcoin/rust-bitcoin#2481: Improve base58 crate
af49841433 Hide base58::Error internals (Tobin C. Harding)
4f68e79da0 bitcoin: Stop using base58 errors (Tobin C. Harding)
669d5e8fc6 base58: Add InvalidCharacterError for decoding (Tobin C. Harding)
ec8609393b base58: Add error module (Tobin C. Harding)
42fabbab03 base58: Run the formatter (Tobin C. Harding)

Pull request description:

  Improve the error code in the new `base58` crate.

ACKs for top commit:
  apoelstra:
    ACK af49841433
  sanket1729:
    ACK af49841433

Tree-SHA512: c05479f02a9a58c7c98fd5987e760288562372e16cceeeb655f0a5385b4a8605945a3b6f7fcf473a7132a40f8dc90d204bc5e9e64fd2cc0bdc37dbcabb4ddc5c
2024-03-24 14:20:29 +00:00
Andrew Poelstra 5c8fb5c11b
relative locktime: add consensus encode/decode functions 2024-03-21 22:10:13 +00:00
Andrew Poelstra ac968e02b6
relative locktime: constify a bunch of constructors 2024-03-21 22:07:29 +00:00
Andrew Poelstra f27e675e1e
relative locktime: add "obvious" constructors
Adds constructors to allow directly creating locktimes from time or
block counts; adds a flooring constructor to Time to match the ceiling
one; adds an explicit constructor to Height since the From<u16> was not
very discoverable.
2024-03-21 22:07:25 +00:00
Andrew Poelstra 2ff5085e70
locktimes: run cargo fmt 2024-03-21 22:07:25 +00:00
Tobin C. Harding 669d5e8fc6
base58: Add InvalidCharacterError for decoding
The `base58::decode` function can only return a single error type, add a
`InvalidCharacterError` struct (leaf error) to use as the return type.
2024-03-21 06:22:51 +11:00
Tobin C. Harding 911f8cbd6a
fix: Manually implement serde traits
Currently we are deriving the serde traits for the `absolute::{Height,
Time}` types, this is incorrect because we maintain an invariant on
the inner `u32` of both types that it is above or below the threshold.

Manually implement the serde traits and pass the deserialized `u32` to
`from_consensus` to maintain the invariant.

Close: #2559
2024-03-20 11:33:14 +11:00
Tobin C. Harding 290e4418e6
units: Fix cargo cult programming
When creating the ParseIntError in `hex_u32` I (Tobin) just cargo cult
programmed the generic stuff without thinking.

- The `is_signed` field is used to denote whether we were attempting to
parse a signed or unsigned integer, it should be `false`.
- The `bits` field should be directly set to 32.
2024-03-19 09:59:11 +11:00
Andrew Poelstra 93ca42cb4d
Merge rust-bitcoin/rust-bitcoin#2604: Enforce displaying Amount with trailing zeros
d887423efc Enforce displaying Amount with trailing zeros (448 OG)

Pull request description:

  It is common to display bitcoins using trailing zeros upto 8 decimals. This commit enforces:
  - Displaying Amount in BTC with trailing zeroes by eight decimal places if a precision on the Amount is not specified.
  - Displaying Amount in BTC upto the precision specified truncating the insignificant zeros.
  - Displaying amount in BTC without any decimals if the remainder of the amount divided by the satoshis in 1 BTC is equal to zero using formula `satoshis.rem_euclid(Amount::ONE_BTC.to_sat()) != 0`

  These are not breaking changes and all previous tests pass.

  A testcase is added to for changes introduced.

  Resolves: #2136

ACKs for top commit:
  sanket1729:
    ACK d887423efc
  apoelstra:
    ACK d887423efc

Tree-SHA512: c32e41216477f60a8d95f164bf4a1f6644ea14adc7e169743ce419b0f26ecb6603f3a516f9b18d6508c04ce658f6a0a78ff3b0b062aeb7101b28bbb1e9d522bc
2024-03-17 17:50:50 +00:00
448 OG d887423efc
Enforce displaying Amount with trailing zeros
It is common to display bitcoins using trailing zeros upto 8 decimals.
This commit enforces:
- Displaying Amount in BTC with trailing zeroes by eight decimal places
  if a precision on the Amount is not specified.
- Displaying Amount in BTC upto the precision specified truncating the insignificant zeros.
- Displaying amount in BTC without any decimals if the remainder of the amount
  divided by the satoshis in 1 BTC is equal to zero using formula `satoshis.rem_euclid(Amount::ONE_BTC.to_sat()) != 0`

These are not breaking changes and all previous tests pass.

A testcase is added to for changes introduced.

Resolves: #2136
2024-03-17 17:55:59 +03:00
Andrew Poelstra 750b4dfb8b
Merge rust-bitcoin/rust-bitcoin#2569: Move types to `units`
cbee9781e8 Move unit types to units (Tobin C. Harding)
5bd0d7194b Remove unused absolute::Error (Tobin C. Harding)

Pull request description:

  Move the following unit types to the new `units` crate:

  - `locktime::absolute::{Height, Time}`
  - `locktime::relative::{Height, Time}`
  - `FeeRate`
  - `Weight`

  Also move the `parse` module as well as constants as required.

  Do minimal changes to get things building:

  - Feature gate on "alloc" as needed.
  - Remove rustdocs that use `bitcoin` types.
  - Re-export units types so this is a non-breaking change.
  - Fix import paths.

  Patch 1 was originally #2526, putting it in via this PR to try and speed up the process.

  Close: #2282

ACKs for top commit:
  sanket1729:
    ACK cbee9781e8
  apoelstra:
    ACK cbee9781e8 lgtm. this is a good start. I think the LockTime types should follow Height and Time

Tree-SHA512: 6b0d63c7b054008598d7fa81be7d8c112f2778883b5529d79d446617b94b3c196c9ac735f840d1dfb488700894d3161c6976d44ab0e12ac3af4008068eac5f87
2024-03-15 22:43:51 +00:00
Tobin C. Harding 62f726d5a8
Remove useless convertion
No clue how this got into master; found with `just sane`.

Clippy emits:

 useless conversion to the same type: `amount::ParseAmountError`

As suggested, remove the useless conversion.
2024-03-12 12:56:07 +11:00
Tobin C. Harding cbee9781e8
Move unit types to units
Move the following unit types to the new `units` crate:

- `locktime::absolute::{Height, Time}`
- `locktime::relative::{Height, Time}`
- `FeeRate`
- `Weight`

Also move the `parse` module as well as constants as required.

Do minimal changes to get things building:

- Feature gate on "alloc" as needed.
- Remove rustdocs that use `bitcoin` types.
- Re-export units types so this is a non-breaking change.
- Fix import paths.
2024-03-12 11:59:39 +11:00
Liam Aharon b9f7462958
Implement infallible for errors
Creates a new macro `impl_from_infallible`, and applies it to custom
error types in the codebase.

Closes #1222.
2024-03-08 16:48:34 +11:00
Andrew Poelstra 6f14a1031a
Merge rust-bitcoin/rust-bitcoin#2527: Tidy description
e3db95226a Tidy description (yancy)

Pull request description:

  I noticed `uncheced_add` looked really bad with two spaces (my mistake).  Fixed some others as well.

ACKs for top commit:
  apoelstra:
    ACK e3db95226a oops, we should have caught this. Thanks for the fix!
  tcharding:
    ACK e3db95226a

Tree-SHA512: 8a2e7f85262f17063bea6ac22855ae45d99a1559a2d30f2627ffba1108f0fd8ebd0b541b50fe746b5af2ebb013cb3e9ea432987b90f37c046120388a808c5443
2024-02-29 21:14:31 +00:00
yancy e3db95226a Tidy description
Add one space between header and description body
2024-02-29 15:21:46 +01:00
Martin Habovstiak 08f83898a3 Report the position of an invalid char in amount
It can be helpful to report the exact position where the invalid
character was encountered. This change adds he feature.
2024-02-24 09:42:10 +01:00
Martin Habovstiak 73b325aec5 Report position of the first "too precise" digit
Sometimes people don't remember the exact number of decimal places
supported by denomination or don't want to count (e.g. when converting
fiat to BTC the calculator may yield too precise value). It's helpful to
say in error message at which digit the precision is too high.

This adds `TooPreciseError` struct containing the information and
improves the error message to display it.
2024-02-24 08:55:32 +01:00
Martin Habovstiak 28d83551eb Improve `ParseAmountError::InputTooLarge`
This variant lacked pretty important information: what is the limit. We
could just write it in the error message but it's even better to move it
to a separate struct which also says how many characters exceed the
limit - this helps users know how many need to be deleted.
2024-02-24 08:55:32 +01:00
Martin Habovstiak b7689a7d60 Split up `ParseAmountError::InvalidFormat`
The `InvalidFormat` variant was pretty bad: it didn't make it clear what
exactly is wrong with the input string, especially since it was used
when the denomination was missing. Not only was this unhelpful to the
users who don't know they have to write the denomination when the amount
was otherwise correct but it was also attributed to a problem with the
amount rather than a problem with denomination.

To fix this the variant is replaced by `MissingDigitsError`,
`MissingError` and `InvalidCharError` - all the cases `InvalidFormat`
was originally used in.

`InvalidCharError` is effectively the same as the existing variant but
it was made into a separate error to enable special casing `.` and make
extensions possible. Further this opportunity was used to add a special
case for `-` as well.

`MissingDigitsError` currently contains special casing for empty string
and a string only containing minus sign. It's currently unclear if it's
useful so this change makes this distinction private and only makes it
affect error messages.

As opposed to the previous two variants, `MissingDenominationError` was
added to `ParseError`. The struct is currenly empty and may be extended
in the future with e.g. span information.
2024-02-24 08:55:32 +01:00
Tobin C. Harding 9187bf3a65
Fix new nightly warnings/errors
The latest nightly toolchain introduced a whole bunch of new warnings
and errors, mostly to do with import statements - fix them all.
2024-02-21 14:13:49 +11:00
Andrew Poelstra bf29a76d89
Merge rust-bitcoin/rust-bitcoin#2436: Add unchecked variants to Amount and SignedAmount
df1d2f6eb5 Add unchecked variants to Amount and SignedAmount (yancy)

Pull request description:

  The checked variants have worse performance than the unchecked variants due to the additional branching operations.  To improve performance where overflow is either not possible or not a concern, unchecked variants of `Amount` and `SignedAmount` are introduced for addition, subtraction and multiplication.

  Note, it seems the default behavior for the test framework is to panic on overflow, so I haven't figured out a good way to add tests for this.  Marking as a draft for now.

  closes: https://github.com/rust-bitcoin/rust-bitcoin/issues/2434

ACKs for top commit:
  Kixunil:
    ACK df1d2f6eb5
  apoelstra:
    ACK df1d2f6eb5 gonna go ahead and merge this, we can revisit if necessary when we look at `units` overflow behavior in general

Tree-SHA512: 3fbb0ec81a758b350569226c44e25f6ca49e551566bee83c05c1c2b343874ef657d63a36b5f51c41582d8a8e36466275c574ebff6d363ed7c112ac8b4d5376fa
2024-02-15 15:04:28 +00:00
yancy df1d2f6eb5 Add unchecked variants to Amount and SignedAmount
The checked variants have worse performance than the unchecked variants
due to the additional branching operations.  To improve performance where
overflow is either not possible or not a concern, unchecked variants
of Amount and SignedAmount are introduced.
2024-02-13 23:46:51 +01:00
Andrew Poelstra 8f7cc4d6b3
Merge rust-bitcoin/rust-bitcoin#2462: feat: implement TryFrom trait to `SignedAmount` and `Amount`
251579f4ef feat: implement TryFrom trait to SignedAmount and Amount (Sumit Kumar)

Pull request description:

  Closes: #2245

  Adds `TryFrom<SignedAmount> for Amount` and `TryFrom<Amount> for Amount` in units module

ACKs for top commit:
  tcharding:
    ACK 251579f4ef
  Kixunil:
    ACK 251579f4ef
  apoelstra:
    ACK 251579f4ef

Tree-SHA512: 3e58d7a891019ccd272417eadc977037167439e3385a7b47c060fe93eba9c47fc37cdc0ca5551174ef2d93b256b2804ad7c01f5f2470ef9e9b7b912877aed11c
2024-02-12 23:11:41 +00:00
Sumit Kumar 251579f4ef
feat: implement TryFrom trait to SignedAmount and Amount 2024-02-13 01:22:36 +05:30
Tobin C. Harding 7d538c830d
units: Implement ops::Neg for SignedAmount
Its useful to be able to do `let x = -btc_amount;`

Implement `core::ops::Neg for SignedAmount`, returning a `SignedAmount`.

Fix: #2470
2024-02-12 13:06:34 +11:00
Andrew Poelstra 343510d3a0
kani: fix Amount overflow test 2024-02-05 18:52:13 +00:00
Andrew Poelstra a3c4194c3f
Merge rust-bitcoin/rust-bitcoin#2428: Remove the remaining TODOs
c69caafefc Remove attribute comments (Tobin C. Harding)
3e83ef9276 Remove consensus error wrapper TODO (Tobin C. Harding)
bfabea94e9 Remove unwrap comment (Tobin C. Harding)
8bdaf4a34d Remove carrying_mul TODO (Tobin C. Harding)

Pull request description:

  Add issues and remove the TODOs from the code.

  Resolves: #2368

ACKs for top commit:
  apoelstra:
    ACK c69caafefc
  Kixunil:
    ACK c69caafefc

Tree-SHA512: b10a3de8da7ace890735023f8441605dd11b0227c27a2357556b8aaa8276a7f34ed220e3bcbc93aad4b35357319318ff7de27210e8f60dd90f6c55af23e21470
2024-02-02 23:39:16 +00:00
Tobin C. Harding c69caafefc
Remove attribute comments
Add an issue and remove the TODO from the code as well as the attribute
comments, leave a single comment as an explanation of why the unusual
code block.

ref: https://github.com/rust-bitcoin/rust-bitcoin/issues/2427
2024-02-02 06:22:02 +11:00
Martin Habovstiak 5c15ed5441
CI: Epic overhaul
Re-write the whole CI pipeline.

Co-developed-by: Martin Habovstiak <martin.habovstiak@gmail.com>
2024-02-02 05:57:23 +11:00
Andrew Poelstra 7b937acf17
Merge rust-bitcoin/rust-bitcoin#2403: Make crate level attributes uniform
0997382772 io: Enable alloc from std (Tobin C. Harding)
ba1166a63b Make crate level attributes uniform (Tobin C. Harding)

Pull request description:

  Make the trait level attributes uniform across all released crates in the repo. Excludes things that are obviously not needed, eg, bench stuff if there is not bench code.

  - Remove `uninhabited_references` - this is allow by default now.
  - Remove `unconditional_recursion` and mark the single false positive we have with an `allow`.

  Note, this does not add `missing_docs` to the `io` crate. There is an open PR at the moment to add that along with the required docs.

ACKs for top commit:
  apoelstra:
    ACK 0997382772
  Kixunil:
    ACK 0997382772

Tree-SHA512: ef1f638aca171536287cce369be98998e871d26468ad2d8c39d9004db610b406471809c283540a4a19bcede78b12b8976a1bb37e5d431fbff8c8a3e53a64d4e3
2024-02-01 14:17:16 +00:00
Tobin C. Harding 96d3bbd065
Fix kani test
Recently (in #2379) we patched the `ParseAmountError` but we don't check
kani code on every pull request so we broke it.

Fix kani test to use the new `OutOfRangeError`.

Close: #2424
2024-02-01 15:13:50 +11:00
Tobin C. Harding bfabea94e9
Remove unwrap comment
Add an issue and remove the TODO from the code.

ref: https://github.com/rust-bitcoin/rust-bitcoin/issues/2426
2024-02-01 12:32:42 +11:00
Tobin C. Harding ba1166a63b
Make crate level attributes uniform
Make the trait level attributes uniform across all released crates in
the repo. Excludes things that are obviously not needed, eg, bench stuff
if there is not bench code.

- Remove `uninhabited_references` - this is allow by default now.
- Remove `unconditional_recursion` and mark the single false positive we
  have with an `allow`.

Note, this does not add `missing_docs` to the `io` crate. There is an
open PR at the moment to add that along with the required docs.
2024-01-31 11:32:46 +11:00
Martin Habovstiak ac26171c32 Clean up `no_std` usage
Previously the crate used negative reasoning to enable `std` which was
hard to understand, required the `prelude` module and wasn't really
needed because it's only needed when a crate wants to add `alloc`
feature-backwards compatibly and this crate always had the feature.

This cleans up usage to unconditionally use `#[no_std]` and then just
add `extern crate` on top as needed by activated features.
2024-01-27 13:25:40 +01:00
Martin Habovstiak fce03cec85 Provide `Amount` & co in no-alloc
Using the crate without allocation was previously disabled making the
crate empty without the feature. This chage makes it more fine-grained:
it only disables string and float conversions which use allocator. We
could later provide float conversions by using a sufficiently-long
`ArrayString`.
2024-01-27 12:46:55 +01:00
Andrew Poelstra e2b9555070
Merge rust-bitcoin/rust-bitcoin#2370: Improve units
7bf478373a Model `TooBig` and `Negative` as `OutOfRange` (Martin Habovstiak)
54cbbf804f Express `i64::MAX + 1` as `i64::MIN.unsigned_abs()` (Martin Habovstiak)
b562a18914 Move denomination error out of `ParseAmountError` (Martin Habovstiak)
5e6c65bc1a Clean up `unsigned_abs` (Martin Habovstiak)

Pull request description:

  Closes #2265
  Closes #2266

  Disclaimer: I did this in December and don't remember why I haven't pushed it. Maybe because it's somehow broken but I don't see how so please review a bit more carefully just in case.

ACKs for top commit:
  tcharding:
    ACK 7bf478373a
  apoelstra:
    ACK 7bf478373a

Tree-SHA512: 1f6e9adae9168bd045c9b09f06d9a69efd47ccc7709ac9ecaf48cb86e265b448b9b52a199ac5e6838d5029f5bc7514c5d7deb15a4d7c8a4606a353f390745570
2024-01-26 13:18:57 +00:00
Tobin C. Harding abe2241828
units: Remove "alloc" TODO
Remove the TODO and add an issue:

  https://github.com/rust-bitcoin/rust-bitcoin/issues/2389
2024-01-25 16:59:55 +11:00
Martin Habovstiak 7bf478373a Model `TooBig` and `Negative` as `OutOfRange`
The error returned when parsing amount had a `Negative` variant which
was weird/unreachable when parsing `SignedAmount`. Also weirdly, parsing
would return `TooBig` when the amount was negative - too low.

To resolve this we merge them into one `OutOfRange` variant that nuges
the consumers to make principled decisions and print error messages as
amounts being more than or less than a specific value which is easier to
understand for the users. Notably, the API still allows getting
information about which type was parsed and which bound was crossed but
in a less obvious way. This is OK since users who have a very good
reason can use this information but most won't.

Closes #2266
2024-01-24 11:37:46 +01:00
Martin Habovstiak 54cbbf804f Express `i64::MAX + 1` as `i64::MIN.unsigned_abs()`
This better conveys the intention that we're checking the lower bound.
2024-01-24 11:25:09 +01:00
Martin Habovstiak b562a18914 Move denomination error out of `ParseAmountError`
The `from_str_in` methods on amounts returned `ParseAmountError` which
contained `InvalidDenomination` among its variants. This one was never
returned because the method doesn't parse denomination.

This change separates the error out.

Closes #2265
2024-01-24 11:25:09 +01:00
Martin Habovstiak 5e6c65bc1a Clean up `unsigned_abs`
Previousle we copied `unsigned_abs` method from `core` because it was
unstable in older MSRV. Our current MSRV allows using the method
directly so this removes our old one and uses the one from standard
library instead.
2024-01-24 11:25:09 +01:00
Andrew Poelstra d08d3efdfa
Merge rust-bitcoin/rust-bitcoin#2336: units: Enable parsing Amount from `u64::MAX`
b2344e019d units: Assert roundtrip SignedAmount/str overflows (Tobin C. Harding)
baadcf4c0a units: Test that SignedAmount float conversion overflows (Tobin C. Harding)
d768f25da8 units: Remove duplicate assertion (Tobin C. Harding)
1d536ac8b2 units: Enable parsing Amount from u64::MAX (Tobin C. Harding)

Pull request description:

  Our `Amount` type uses an internal `u64` and we maintain no invariants on the inner value. Therefore we should be able to parse `u64::MAX`.

  Fix the parsing code by removing the explicit, incorrect check and fix unit tests to mirror this behaviour.

  Fix: #2297

ACKs for top commit:
  Kixunil:
    ACK b2344e019d
  apoelstra:
    ACK b2344e019d

Tree-SHA512: 944f8d0bfedc559f0444f75eca7d3fba042fbc204c4c032d09ff0edc29be280a3707f5b363dbc04f0d7bdf64701c0c4619e2e0de683d804a2663c2a20ac963f6
2024-01-22 19:13:12 +00:00
Tobin C. Harding b2344e019d
units: Assert roundtrip SignedAmount/str overflows
Add a unit test to prove that attempting to roundtrip a `SignedAmount`
greater than `MAX` through a string fails.
2024-01-22 09:14:26 +11:00
Tobin C. Harding baadcf4c0a
units: Test that SignedAmount float conversion overflows
We should not be able to roundtrip a `SignedAmount` value greater than
`MAX`, add a test to prove so.

While we are at it document the assertion above that proves we can parse
a float representing an `Amount` greater than `SignedAmount::MAX`.
2024-01-22 09:08:54 +11:00
Tobin C. Harding d768f25da8
units: Remove duplicate assertion
Unit test has a duplicate assertion, remove it.
2024-01-22 09:06:26 +11:00
Martin Habovstiak 22747149a9 Add convenience constants to `Denomination`
`Denomination::Bitcoin` and `Denomination::Satoshi` are often used,
especially in test code so this change adds `BTC` and `SAT` - short,
readable constants. Notably this doesn't add the other constants as that
would lead to either unidiomatic names or confusing casing (MSAT meaning
millisat not megasat) and they are not used that much anyway.
2024-01-20 22:12:52 +01:00
Tobin C. Harding 1d536ac8b2
units: Enable parsing Amount from u64::MAX
Our `Amount` type uses an internal `u64` and we maintain no invariants
on the inner value. Therefore we should be able to parse `u64::MAX`.

Fix the parsing code by removing the explicit, incorrect check and fix
unit tests to mirror this behaviour.

Fix: #2297
2024-01-15 08:56:57 +11:00
yancy 278229def5 Add allow for out of bounds indexing
Out of bounds indexing is a workaround for const panic until MSRV +1.57
2024-01-01 10:35:52 +01:00
Fmt Bot 5af7727250 2023-12-17 automated rustfmt nightly 2023-12-17 00:59:05 +00:00
Andrew Poelstra 2a6b4c1f43
Merge rust-bitcoin/rust-bitcoin#2262: Clean up `io` usage
f06d12455f bitcoin: Remove the custom sink (Tobin C. Harding)
b503aa1544 Run the formatter (Tobin C. Harding)
3ca55fb163 Remove qualifying path from Read and Write (Tobin C. Harding)
ebeb21fa7a Import fmt::Write using underscore (Tobin C. Harding)
e2dbcb1d28 Use W for writer generic type (Tobin C. Harding)
8704d9f0ae docs: Fix grammar (Tobin C. Harding)

Pull request description:

  A few cleanups to how we use the `io` crate, this is reasonably trivial but commit `a6c7e696 Remove qualifying path from Read and Write` is big, I have however gone to some effort to make sure it is easy to flick through the diff.

  Done in preparation for another go at the `BufRead` stuff.

ACKs for top commit:
  apoelstra:
    ACK f06d12455f
  Kixunil:
    ACK f06d12455f

Tree-SHA512: 751c489c67901c7563f1cc91f7761a4e3c276ae1981010338134e8c13200720ba69fcc74948c1dc1e6e65390197da0da27b2b69b86034029748321b404142cba
2023-12-12 20:07:06 +00:00
Jiri Jakes daa47b2061
Allow `SignedAmount` parse values equal to i64::MIN
Previously, parsing such textual value returned 'too big' error. This
change fixes it and adds relevant tests.
2023-12-12 18:33:44 +08:00