Commit Graph

67 Commits

Author SHA1 Message Date
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
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 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
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
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
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
Fmt Bot 19b093080b 2024-06-30 automated rustfmt nightly 2024-06-30 01:10:26 +00: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
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
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
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
Fmt Bot a565db9fdd 2024-03-31 automated rustfmt nightly 2024-03-31 01:03:18 +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
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
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
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
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
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
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