Commit Graph

720 Commits

Author SHA1 Message Date
Shing Him Ng a66ff8f8b1 Introduce `map` function for `NumOpResult` 2025-05-13 07:34:17 -05:00
merge-script fb38e1bf2a
Merge rust-bitcoin/rust-bitcoin#4487: Automated nightly rustfmt (2025-05-11)
37d2f7eff1 2025-05-11 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:
  tcharding:
    ACK 37d2f7eff1
  apoelstra:
    ACK 37d2f7eff146b223f5f61a99aee6110d05e932a5; successfully ran local tests

Tree-SHA512: 6a3902cf487ec5a4639700034dcaf04214188f79abf0e9ae08191acd57e151084d74b3145471ccadfa942057235621fe2a46d3c21c7b5dcf295133cdcf0fc9d7
2025-05-12 16:31:13 +00:00
merge-script 5ecb8880f1
Merge rust-bitcoin/rust-bitcoin#4474: Mark method as constant
fd90c8782a Mark method as constant (yancy)

Pull request description:

  Allow external const calls to access this method

  Followup from https://github.com/rust-bitcoin/rust-bitcoin/pull/4428

ACKs for top commit:
  tcharding:
    ACK fd90c8782a
  apoelstra:
    ACK fd90c8782ab602861a715c72ca1481ed963e5c39; successfully ran local tests

Tree-SHA512: 2d04da9bddd58040972942e70096b2714405740236889f0909c00cb6993e38f3ae51ff05bbda13792a31243d3598f5976649590eecb0572c4f00c166f717399d
2025-05-12 15:01:01 +00:00
Tobin C. Harding 4ccecf5dec
Fix stale Height type link
`units::locktime::relative::Height` type is now deprecated, use the new
name in rustdoc.
2025-05-12 12:57:08 +10:00
Tobin C. Harding caebb1bf73
units: relative: Do minor rustdocs fixes
Slightly improve grammar and fix column width to 100.
2025-05-12 12:48:05 +10:00
Tobin C. Harding f9d6453d5b
Shorten locktime type term
Use lock-by-time and lock-by-height instead of lock-by-blocktime and
lock-by-blockheight respectively with no loss of clarity.
2025-05-12 12:30:53 +10:00
Tobin C. Harding 727047bd39
Fix off-by-one-bug in absolute locktime
When checking a locktime against block height we add 1 because when the
next block is being validated that is what the height will be and
`is_satisfied_by` is defined to return true if a transaction with this
locktime can be included in the next block.

As we have in `relative`, and for the same reasons, add an API to the
absolute `Height` and `MedianTimePast`: `is_satisfied_by`. Also add
`is_satisfied_by_{height, time}` variants to `absolute::LockTime`.
Call through to the new functions in `units`.
2025-05-12 12:30:53 +10:00
Tobin C. Harding 3ffdc54ca5
Fix off-by-one bug in relative locktime
Define 'is satisfied by' - this is a classic off-by-one problem, if a
relative lock is satisfied does that mean it can go in this block or the
next? Its most useful if it means 'it can go in the next' and this is
how relative height and MTP are used in Core.

Ramifications:

- When checking a time based lock we check against the chain tip MTP,
then when Core verifies a block with the output in it it uses the
previous block (and this is still the chain tip).
- When checking a height base lock we check against chain tip height + 1
because Core checks against height of the block being verified.

Additionally we currently have a false negative in the satisfaction
functions when the `crate` type (height or MTP) is to big to fit in a
u16 - in this case we should return true not false because a value too
big definitely is > the lock value.

One final API paper cut - currently if the caller puts the args in the
wrong order they get a false negative instead of an error.

Fix all this by making the satisfaction functions return errors, update
the docs to explicitly define 'satisfaction'.

For now remove the examples in rustdocs, we can circle back to these
once the dust settles.

API test of Errors:

Some of the errors are being 'API tested' tested in `primitives` but
they should be being done in `units/tests/api.rs` - put all the new
errors in the correct places.
2025-05-12 12:17:31 +10:00
Fmt Bot 37d2f7eff1 2025-05-11 automated rustfmt nightly 2025-05-11 01:39:24 +00:00
Tobin C. Harding f732b1d3cc
units: Use functional style
This is Rust not C, use functional style.

Close: #4464
2025-05-10 07:58:00 +10:00
merge-script e43c574146
Merge rust-bitcoin/rust-bitcoin#4473: Assert num op error
a7d059151e Assert error type (yancy)
2f7e74da45 Add MathOp helper methods (yancy)

Pull request description:

  Follow up from https://github.com/rust-bitcoin/rust-bitcoin/pull/4428 to assert the error type which I agree improves the test.

  Added some helper functions since it can be nice to see what type of overflow happened.

ACKs for top commit:
  tcharding:
    ACK a7d059151e
  apoelstra:
    ACK a7d059151eb47bf4202302604309c95c0d66371d; successfully ran local tests

Tree-SHA512: e1b3eba640de2e4f98e075270fd797582601c541e1eebef2959a4e609bf51129e8ad38baab1253b40474c39f82ee4802658ec545cc5c3590637f2ddb13f873f7
2025-05-09 15:47:38 +00:00
yancy fd90c8782a Mark method as constant
Allow external const calls to access this method
2025-05-09 07:23:01 -05:00
yancy a7d059151e Assert error type
Improve test granularity by asserting the specific type of overflow
returned.
2025-05-08 18:20:24 -05:00
yancy 2f7e74da45 Add MathOp helper methods
It's helpful to be able to assert what type of Math error occurred.
2025-05-08 18:18:25 -05:00
Tobin C. Harding dca4266205
units: Fix rustdoc column width
We've done a bit of renaming which has adversely effected rustdoc column
width, fix it up.
2025-05-08 10:16:57 +10:00
Tobin C. Harding d557caf552
Run the formatter 2025-05-08 10:16:56 +10:00
Tobin C. Harding 7c2115b68f
Rename MtpInterval to NumberOf512Seconds
Name the type exactly what it is. This used to be `Time`, then we tried
`MtpInterval`.

Note that this makes some of the original function names overly verbose
e.g., `NumberOf512seconds::from_512_second_intervals()` but given the
curlyness of locktimes too verbose is better than too terse. Also this
type, along with `NumberOfBlocks` is not going to be in very wide use so
the ergonomic hit is worth the additional clarity.
2025-05-08 10:12:23 +10:00
Tobin C. Harding 3a97ea2259
Rename HeightInterval to NumberOfBlocks
Name this type exactly what it is. Note for the error we just use
'height' even though this is a bit stale but the general concept is ok
in the error type because the name is long already.
2025-05-08 10:12:22 +10:00
Tobin C. Harding c3b7457f6c
Rename Mtp to MedianTimePast
Favour expressiveness over terseness for
`units::locktime::absolute::Mtp` (formerly `Time`) because in general
locktimes are curly AF.
2025-05-08 10:09:09 +10:00
Tobin C. Harding b38d2256fd
Run the formatter 2025-05-08 09:46:52 +10:00
merge-script 4ca6cd6065
Merge rust-bitcoin/rust-bitcoin#4458: locktimes: replace `MtpAndHeight` type with pair of `BlockMtp` and `BlockHeight`
47c77afaac units: delete MtpAndHeight type (Andrew Poelstra)
d82b8c0bcb primitives: stop using MtpAndHeight (Andrew Poelstra)
72d5fbad73 units: stop using MtpAndHeight in locktime::relative is_satisfied_by methods (Andrew Poelstra)
d933c754f5 units: change type of MtpHeight::to_mtp to BlockMtp (Andrew Poelstra)
dcbdb7ca8a units: add checked arithmetic to Block{Height,Mtp}{Interval,} (Andrew Poelstra)
4300271f0c units: add constructor for absolute::Mtp from timestamps (Andrew Poelstra)
4e4601b3d5 units: rename BlockInterval to BlockHeightInterval (Andrew Poelstra)
cb882c5ce1 units: add global `BlockMtpInterval` type (Andrew Poelstra)
4e3af5162f units: add global `BlockMtp` type (Andrew Poelstra)
a3228d4636 units: pull u32 conversions for BlockHeight/BlockInterval into macro (Andrew Poelstra)

Pull request description:

  This is a more involved PR than I'd expected but hopefully the individual commits make sense and are well-motivated. Essentially, my goal was to replace `MtpAndHeight` as used by relative locktimes with a pair of `Mtp` and `Height`.

  However, relative locktimes, when given a MTP/Height for the UTXO creation and the chain tip, are roughly modeled as "take a diff of MTPs to get a `relative::MtpInterval`, a diff of heights to get a `relative::HeightInterval`, and compare to the locktimes". *However*, we have no standalone MTP type to "take a diff of", and also there are failure modes when creating the diffs (e.g. if the diff would exceed the range of `MtpInterval` or `HeightInterval`).

  So I backed up and decided to use the existing `BlockHeight`/`BlockInterval` as the type to "take a diff of". I needed to introduce a `BlockMtp`/`BlockMtpInterval` to work with MTPs. These types have full-u32 range, unlike the similarly-named types in `units::locktimes::absolute`. I then needed to add some conversion methods. Along the way, I cleaned up the APIs and documentation, added checked arithmetic, etc., as needed.

  See the individual commit messages for more detail.

  I believe the resulting API is much more consistent and discoverable, even though it has more surface than the old API.

  I considered splitting this into 2 PRs but I think the first half of the changes aren't well-motivated with out the second half. Let me know.

ACKs for top commit:
  tcharding:
    ACK 47c77afaac

Tree-SHA512: ebe19a5b1684db8c2d913274347c994026aaa0dcdd79349c237920a82fe55560777278efdbbc7f1b1424c9391d9bbd891ae844db885deea75288000437a8a287
2025-05-07 22:32:16 +00:00
merge-script 884dc5e103
Merge rust-bitcoin/rust-bitcoin#4428: Use NumOpResult instead of Option
13cbead947 Use NumOpResult instead of Option (yancy)
002a0382aa Mark function constant (yancy)

Pull request description:

  Prefer the more descriptive NumOpResult return type over Option where return types are fallible.

  Closes https://github.com/rust-bitcoin/rust-bitcoin/issues/4419

ACKs for top commit:
  apoelstra:
    ACK 13cbead94766987f59482b1fbc1d0ebd0799737c; successfully ran local tests
  tcharding:
    ACK 13cbead947
  Kixunil:
    ACK 13cbead947

Tree-SHA512: 1a870962dcafe901a07abd93bd8075e41696341c1a4b3efef615493c73d5e5728bbc2326f8c2c95b9034ab001d0b3c668c9d64793ab03486d3a19f31df907c96
2025-05-07 20:04:16 +00:00
merge-script 10657865c3
Merge rust-bitcoin/rust-bitcoin#4457: rustdoc: Fix unused lint warnings
52940d4e12 Prefix unused variables with _ in rustdocs (Jamil Lambert, PhD)
a852aef4b8 Remove unused imports in rustdocs (Jamil Lambert, PhD)

Pull request description:

  There is a lint warning about unused variables and imports in the rustdoc examples.

  Remove the unused imports and prefix the unused variables with an underscore.

ACKs for top commit:
  apoelstra:
    ACK 52940d4e1216ad5118f7980cb2e6b8b425c61589; successfully ran local tests
  tcharding:
    ACK 52940d4e12

Tree-SHA512: 953862d546dc6e0bcd64172e8b383f0fc2a1a851971a1bcad0c1e30cbaeeaea993a0de7dd8b424c4ac1410053e179c52d0b5c90cd1b6560c27123b6b7fa49732
2025-05-07 18:56:53 +00:00
Andrew Poelstra 47c77afaac
units: delete MtpAndHeight type
This type provides little value beyond just pairing a BlockHeight and a
BlockMtp.
2025-05-06 19:23:31 +00:00
Andrew Poelstra 72d5fbad73
units: stop using MtpAndHeight in locktime::relative is_satisfied_by methods
Keep using it in primitives; will remove it there in the next commit.
2025-05-06 18:51:03 +00:00
Andrew Poelstra d933c754f5
units: change type of MtpHeight::to_mtp to BlockMtp
We are going to delete MtpHeight in a couple commits, but to let us do
the transition with smaller diffs, we will first change it to be easily
convertible to a BlockHeight/BlockMtp pair.
2025-05-06 15:50:55 +00:00
Andrew Poelstra dcbdb7ca8a
units: add checked arithmetic to Block{Height,Mtp}{Interval,} 2025-05-06 15:50:53 +00:00
Andrew Poelstra 4300271f0c
units: add constructor for absolute::Mtp from timestamps
This is a convenience method to allow direct construction of
absolute::Mtp rather than going through units::BlockMtp.
2025-05-06 15:50:46 +00:00
Andrew Poelstra 4e4601b3d5
units: rename BlockInterval to BlockHeightInterval
Now that we have BlockMtpInterval we want to distinguish BlockInterval
from it.
2025-05-06 15:50:43 +00:00
Andrew Poelstra cb882c5ce1
units: add global `BlockMtpInterval` type
See the previous commit message for justification; for sensible
arithmetic on block timestamps we need the ability to do MTP
calculations on arbitrary MTPs and arbitrary intervals between them.
However, the absolute::Mtp and relative::MtpInterval types are severely
limited in both range and precision.

Also adds a bunch of arithmetic ops to match the existing ops for
BlockHeight and BlockInterval. These panic on overflow, just like the
underlying std arithmetic, which I think is reasonable behavior for
types which are documented as being thin wrappers around u32.

We may want to add checked_add, checked_sub and maybe checked_sum
methods, but that's out of scope for this PR.
2025-05-06 15:19:36 +00:00
Andrew Poelstra 4e3af5162f
units: add global `BlockMtp` type
For our relative locktime API, we are going to want to take differences
of arbitrary MTPs in order to check whether they meet some relative
timelock threshold.

However, the `locktime::absolute::Mtp` type can only represent MTPs that
exceed 500 million. In practice this is a non-issue; by consensus MTPs
must be monotonic and every real chain (even test chains) have initial
real MTPs well above 500 million, which as a UNIX timestamp corresponds
to November 5, 1985.

But in theory this is a big problem: if we were to treat relative MTPs
as "differences of absolute-timelock MTPs" then we will be unable to
construct relative timelocks on chains with weird timestamps (and on
legitimate chains, we'd have .unwrap()s everywhere that would be hard to
justify). But we need to treat them as a "difference of MTPs" in *some*
sense, because otherwise they'd be very hard to construct.
2025-05-06 15:19:35 +00:00
Andrew Poelstra a3228d4636
units: pull u32 conversions for BlockHeight/BlockInterval into macro
There is a lot of duplicated code between BlockHeight and BlockInterval.
It obfuscates the differences between them: which timelock types they
can be converted to/from and what their arithmetic properties are.
2025-05-06 15:19:35 +00:00
Jamil Lambert, PhD 52940d4e12
Prefix unused variables with _ in rustdocs
There is a lint warning about unused variables in the rustdoc examples.

Prefix them with an underscore.
2025-05-06 10:28:51 +01:00
Jamil Lambert, PhD a852aef4b8
Remove unused imports in rustdocs
There is a lint warning about unused imports in the rustdoc examples.

Remove them.
2025-05-06 10:26:00 +01:00
Jamil Lambert, PhD 2fbbc825c9
Allow uninlined format args
There is a new lint error on nightly-2025-04-25 "variables can be used
directly in the `format!` string".

Exclude the lint to allow the existing syntax in `format!` strings.
2025-05-06 09:49:02 +01:00
merge-script ec44656933
Merge rust-bitcoin/rust-bitcoin#4438: Automated nightly rustfmt (2025-05-04)
1f19d9b4bd 2025-05-04 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 1f19d9b4bd8c55b9a7dc233c4b969d5d54d3a951; successfully ran local tests
  tcharding:
    ACK 1f19d9b4bd

Tree-SHA512: c13d24482848cc6e103304b52bd51964fbca9f3b09b5c179af7956aef0537b6cc05014a203844c93d0b21da08cd51bf4a84dc5611b61ae5684ae57b0beb2848f
2025-05-05 12:53:41 +00:00
yancy 13cbead947 Use NumOpResult instead of Option
Prefer the more descriptive NumOpResult return type over Option where
return types are fallible.

The returned type NumOpResult is already annotated as must_use per the
lint, so must_use can be removed after changing the method return types
to NumOpResult.
2025-05-05 07:18:15 -05:00
yancy 002a0382aa Mark function constant
Allow this function to be called elsewhere in the codebase in const
context.
2025-05-05 07:17:16 -05:00
Fmt Bot 1f19d9b4bd 2025-05-04 automated rustfmt nightly 2025-05-04 01:41:13 +00:00
Andrew Poelstra 826acb8273
units: rename relative::HeightInterval constructors
Rename `value` to `to_height` to be symmetric with `from_height`;
deprecate `to_consensus_u32` which had no symmetric `from_consensus_u32`
and was only used to implement the corresponding methods in primitives
and bitcoin.
2025-05-03 03:12:08 +00:00
Andrew Poelstra 39b4f7670d
units: rename relative::Height to HeightInterval
This is disruptive, but makes the type name consistent with
`MtpInterval` and also greatly improves clarity, helping to distinguish
between absolute and relative locktimes and reminding the author (and
reviewer) of locktime code that this needs to be a diff.
2025-05-03 03:12:08 +00:00
Andrew Poelstra d3619cc1bc
units: deprecate relative::MtpInterval::to_consensus_u32
This method is weird. It's basically just used internally to implement
the locktime methods in `primitives` and `bitcoin`. It has no symmetric
from_consensus_u32.

Conversely the constructors from 512-second intervals have no symmetric
to_* method -- the inverse of these functions is called `value`, which
is a meaningless and undiscoverable name.
2025-05-03 03:12:07 +00:00
Andrew Poelstra 1a6b8b4c7a
units: rename relative::Time to MtpInterval
The name `Time` is misleading. In fact this represents an interval
between MTPs.
2025-05-03 03:12:07 +00:00
Andrew Poelstra 39b057fade
units: rename absolute::Height consensus functions
As with absolute::Mtp, there is no "consensus encoding" of a block
height, except that obtained by converting it to a locktime. For
symmetry with `Mtp`, rename the methods.
2025-05-03 03:12:05 +00:00
Andrew Poelstra 5a8f33f380
units: rename absolute::Mtp consensus functions
There is no "consensus encoding" for a MTP. The intention for these
methods was that a user could interpret the MTP as a locktime and then
consensus-encode that locktime. However, it was instead interpreted as
the MTP representing a *blocktime* as it is consensus-encoded in a block
header.

Evidence of this misinterpretation is in several doccomments, which
casually refer to the Mtp (which used to be just called Time) as a
"block time", which is simply incorrect.
2025-05-02 17:44:58 +00:00
Andrew Poelstra 8ffcd2cf30
units: rename absolute::Time to absolute::Mtp
This is not a generic UNIX timestamp, but rather a MTP restricted to
have values between 500 million and u32::MAX. Most importantly, it is
*not* a blocktime, which is what is implied by its name and
constructors.
2025-05-02 17:44:58 +00:00
Jamil Lambert, PhD 7bcdd5ff66
Add regression tests for Display impl
The output of `Display` should not change in stable crates for types
that have well defined formatting and ones that implement `FromStr`.
Error types do not need to be tested.

Add missing tests for all implementations in `units`.
2025-04-30 18:21:09 +01:00
Jamil Lambert, PhD 9c90bf49c9
Add lock by time and denomination display regression tests
The existing display regression tests only tested height locktimes.
Denomination display regression and round trip were not tested.

Add tests for time locktimes and denomination.
2025-04-30 17:16:37 +01:00
Jamil Lambert, PhD eb7dee831e
Rename locktime tests
Existing display tests only test lock by block height.  New tests are
needed for lock by block time.

Change existing test names to make it clear which type of locktime is
being tested.
2025-04-30 16:30:56 +01:00
merge-script f9bc0f517d
Merge rust-bitcoin/rust-bitcoin#4344: Locktime MtpAndHeight
8b47068a2e feat(locktime): implement MtpAndHeight structure and validation logic (aagbotemi)

Pull request description:

  This PR fixes #4299

  - Computed MtpAndHeight structure
  - Checked if relative time and height is satisfied by MtpAndHeight
  - Compared the Ordering of MtpAndHeight with time and height
  - Checked MtpAndHeight satisfaction and comparison in Locktime
  - Added unit tests for all the implementation

  I've reviewed and adhered to the contribution guidelines

ACKs for top commit:
  apoelstra:
    ACK 8b47068a2efada30aec21c61ae4be0da4d8e8fc8; successfully ran local tests
  Kixunil:
    ACK 8b47068a2e
  tcharding:
    ACK 8b47068a2e

Tree-SHA512: b00d1384d5deaa038b486ca9d77ad33cfa6cd8c987e08407863f2be8d540014bdcc971cd9d46acb51a2d105341accc04ba151e5cccb276e8352a5d45b33097eb
2025-04-28 13:49:12 +00:00
Fmt Bot 6737c3a0e5 2025-04-27 automated rustfmt nightly 2025-04-27 01:36:56 +00:00
leopardracer d5f8a02b9b
Update result.rs 2025-04-26 12:47:19 +03:00
merge-script 12cef1d16b
Merge rust-bitcoin/rust-bitcoin#4389: Create impl_mul_assign and impl_div_assign macros
a92cc71f65 Create impl_mul_assign and impl_div_assign macros (Shing Him Ng)

Pull request description:

  The macros were called on type-rhs pairs that have an existing implementation of ops::Mul and ops::Div, respectively, that have an `Output` of `Self`

  Not as many types as I would have thought, but most of the operations result in a `NumOpResult`, which can't be then assigned back to the variable.

  Closes #4172

ACKs for top commit:
  apoelstra:
    ACK a92cc71f658771776557ea0a40d1d095d3b6d482; successfully ran local tests

Tree-SHA512: 30cfb077b9ba65af991eb17fa05ffc4a870c3f4ded746355d3a8577a71fe9a569588a882c2a936edcc9c88feede4d8bb1379a998e3f330894084a4e2fc434e6e
2025-04-25 14:08:00 +00:00
aagbotemi 8b47068a2e
feat(locktime): implement MtpAndHeight structure and validation logic
- Add MtpAndHeight for relative locktime checks
- Include unit tests for time/height comparisons
- Fix API design for mtp_as_time() error handling
- Update documentation and dependencies
- Fix BlockTime, CI, remove Ordering, and PR discussion fixed
- Fix UTXO height and timestamps
- Fix: chain_state and utxo_state handled seperately for is_satisfied_by
- Fix: panic on overflow fixed with check_add
- Fix: documentation updated and trailing whitespaces removed
- docs(mtpheight): documentation updated
- used accessors to_height and to_mtp over From impl
2025-04-25 12:24:23 +01:00
Shing Him Ng a92cc71f65 Create impl_mul_assign and impl_div_assign macros
The macros were called on type-rhs pairs that have an existing
implementation of ops::Mul and ops::Div, respectively, that have an
`Output` of `Self`
2025-04-22 22:50:09 -05:00
Jamil Lambert c4d9c1b9f8
Use a consistent rustdoc heading level of H1 `#`
There was and inconsistent usage of `#`, `##` and `###` in rustdoc
headings.  The difference in the rendered rustdocs is a minimal font
size change.

Change all headings to be H1 `#`.

Change all subheadings to be `###` to have a noticeable difference in
font size in the rendered docs.
2025-04-22 13:06:32 +01:00
Jamil Lambert f22e997587
Use parameters instead of arguments in rustdocs
The rustdocs use both `# Parameters` and `# Arguments` to mean the same
thing.

Change all of them to `# Parameters` to be consistent.
2025-04-22 10:43:13 +01:00
merge-script 8ca3a430c7
Merge rust-bitcoin/rust-bitcoin#4336: units: Make minor improvements to `MathOp`
0f62c9a582 units: Make minor improvements to MathOp (Tobin C. Harding)

Pull request description:

  Follow up from #4312, improve the `MathOp` type by:

  - Do not provide public constructor
  - Add cast protection

ACKs for top commit:
  apoelstra:
    ACK 0f62c9a5822a813be5c6f6b19d160458243f174a; successfully ran local tests
  Kixunil:
    ACK 0f62c9a582

Tree-SHA512: dbb06c5afd8df5364a2aec12b7c8632620a1e8f3955b83e91a9b4f5c2e0daaa1ecdb050d8e395e95bf018d718847cddbf3338bd89f70cbb0382bf5e080d5cf21
2025-04-20 16:35:47 +00:00
Tobin C. Harding 6323867c65
Run the formatter 2025-04-17 11:43:05 +10:00
Tobin C. Harding d5c08aef32
units: Update column width
Update column width inside the new `encapsulate` modules.

No content change.
2025-04-17 11:43:05 +10:00
Tobin C. Harding f7f1a0be8c
Add privacy boundary to BlockTime
As per policy in #4090 add a privacy boundary to the `BlockTime` type.
Use the module name `encapsulate` as is done in `amount` - its private
so the name can easily be changed later if needed.

Explicitly do not run the formatter or update rustdoc column width so
that review is easier.
2025-04-17 11:43:05 +10:00
Tobin C. Harding b3dfe0df3f
Add privacy boundary to Weight
As per policy in #4090 add a privacy boundary to the `Weight` type. Use
the module name `encapsulate` as is done in `amount` - its private so
the name can easily be changed later if needed.

Explicitly do not run the formatter or update rustdoc column width so
that review is easier.
2025-04-17 11:43:05 +10:00
Tobin C. Harding e1a14b3c2d
Add privacy boundary to FeeRate
As per policy in #4090 add a privacy boundary to the `FeeRate` type. Use
the module name `encapsulate` as is done in `amount` - its private so
the name can easily be changed later if needed.

Explicitly do not run the formatter or update rustdoc column width so
that review is easier.
2025-04-17 11:43:05 +10:00
Tobin C. Harding 4b733d4dad
Run the formatter 2025-04-17 11:43:02 +10:00
merge-script 94abc99fb0
Merge rust-bitcoin/rust-bitcoin#4318: Document the `NumOpResult` type
c30a504ea6 units: Document the NumOpResult type (Tobin C. Harding)

Pull request description:

  Document the `NumOpResult` type.

  Note that this includes two new getters on the `NumOpResult`, API hole found during review of the new docs.

  Fix: #4222

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

Tree-SHA512: ab8d971b74ff4bb06f5737943740c5c748f6313ce1b82798c7d709f8747779efdffe0aa8ed8620afa449fd0dd502b5a2050729a538c51428215972a4f7b6ebf7
2025-04-17 11:35:03 +10:00
merge-script 9364cd1f7c
Merge rust-bitcoin/rust-bitcoin#4343: units: Go over the rendered docs for the whole crate
913360b112 Make struct titles consistent (Jamil Lambert, PhD)
afe9ddd5e6 Remove - in fee rate (Jamil Lambert, PhD)
ebc6b4a876 Make warning text bold (Jamil Lambert, PhD)

Pull request description:

  I have read through all of the `units` docs and made a few changes.

  - Highlight `Warning!` in bold in `Amount` and `SignedAmount`

  - Change the one occurrence of fee-rate to fee rate to be consistent with the rest.

  - Make all of the error structs have the same title format of `Error returned...`

  - Make all other structs have the same format concisely stating what it is opposed to what it does.

ACKs for top commit:
  tcharding:
    ACK 913360b112

Tree-SHA512: 4cb08d1dae091f5b827cf9f1e931b057c6670002146a22da54886148f3052f6ea7050fcd7f62c0d83438ef170e2f109c1a36f47a280808f31466da6f3177dd01
2025-04-16 19:10:02 +00:00
merge-script b473a2090a
Merge rust-bitcoin/rust-bitcoin#4258: units: Improve code enforcing privacy boundry
ca6c607953 Adhere to sanity rules for amount types (Tobin C. Harding)
6c614d9320 units: Fix panic message (Tobin C. Harding)

Pull request description:

  This is a follow up to #4256 - onwards and upwards!

  - Patch 1: Fix the incorrect BTC value in panic message
  - Patch 2: Strictly adhere to the sanity rules (#4090)

   Close: #4140

ACKs for top commit:
  apoelstra:
    ACK ca6c607953c03aa2dc168f58329681d9e69eee04; successfully ran local tests

Tree-SHA512: 6d7fd60830e1a0f6d6262ab02ec6e297b095d0fe8fb7737563979652e4a3b4a9477a79982201c42b08e2555fd23dc5c430549966b534bdf45f40621ae81da83a
2025-04-16 18:33:09 +00:00
merge-script 551b52c7d1
Merge rust-bitcoin/rust-bitcoin#4348: refactor: Replace fold with try_fold
812c21e2e4 refactor: Replace fold with try_fold (yancy)

Pull request description:

  The and_then combinator performs a kind of bitwise and operation on two Option types here.  This is useful since the `checked` arithmetic returns an option thereby accumulating Option types.  Therefore, either the checked arithmetic operation performs the addition of the unwrapped accumulator, or it returns None.

  Instead of using `and_then` use the provided `try_fold` method which will short circuit on `None` when the checked arithmetic is used.  Also, simplify the staring condition using `Amount:ZERO` since this is logically equivalent to using the first value if one exists.

  Lastly, by using the built in `try_fold`, it's possible the performance will be improved by making use of the short circuit ability instead of evaluating each item even when the accumulator holds a None type.

ACKs for top commit:
  apoelstra:
    ACK 812c21e2e4a868046b44728c1a6209a866452820; successfully ran local tests
  tcharding:
    ACK 812c21e2e4

Tree-SHA512: 1cfcd4fa28e2b59daf3744bb5f654f65eb9853c5a36f747cb0859783e7e46c1d02ccb296612b75f7cca10782979ce052cd670c0f23c1030e0a347000d1f6df83
2025-04-16 13:56:34 +00:00
Tobin C. Harding c30a504ea6
units: Document the NumOpResult type
The `NumOpResult` type is a bit unusual. Add thorough documentation
and example usage to it.
2025-04-16 18:17:09 +10:00
Jamil Lambert, PhD 913360b112
Make struct titles consistent
Structs had various phrasings of titles.

Make the wording consistent by concisely stating what it is, instead of
what it does.

Make the wording of all error structs consistent.
2025-04-15 21:23:31 +01:00
Jamil Lambert, PhD afe9ddd5e6
Remove - in fee rate
The rest of the rustdocs use fee rate with no hyphen when using it in
normal language, i.e. not a function argument or the type.

Change it to match the others.
2025-04-15 21:22:18 +01:00
Jamil Lambert, PhD ebc6b4a876
Make warning text bold 2025-04-15 21:22:12 +01:00
merge-script c14044e76e
Merge rust-bitcoin/rust-bitcoin#4341: units: Improve crate level docs
53837d9a2e units: Improve crate level docs (Tobin C. Harding)

Pull request description:

  Add a bit more to the crate level docs. This is a simple crate so we don't need all that much.

  Done for: C-CRATE-DOC

ACKs for top commit:
  apoelstra:
    ACK 53837d9a2e1cc70e180de39c16e2d212e958a9f3; successfully ran local tests

Tree-SHA512: 374c27a25cdc9bd4edd0755be02cad66ccccedcd69836506c1f4eb86a1254bfafe11eeb6fcc27b7efd2ab3ca0acd1daa304d482c7e5a7f84ffbcffbb1bcd21d6
2025-04-15 15:12:26 +00:00
yancy 812c21e2e4 refactor: Replace fold with try_fold
The and_then combinator performs a kind of bitwise and operation on two
Option types here.  This is useful since the `checked` arithmetic
returns an option thereby accumulating Option types.  Therefore, either
the checked arithmetic operation performs the addition of the unwrapped
accumulator, or it returns None.

Instead of using `and_then` use the provided `try_fold` method which
will short circuit on `None` when the checked arithmetic is used.  Also,
simplify the staring condition using `Amount:ZERO` since this is
logically equivalent to using the first value if one exists.

Lastly, by using the built in `try_fold`, it's possible the performance
will be improved by making use of the short circuit ability instead of
evaluating each item even when the accumulator holds a None type.
2025-04-15 08:21:11 -05:00
merge-script e5b0f9cd92
Merge rust-bitcoin/rust-bitcoin#4337: Add impls for `NumOpResult` div and mul
0361604bab Add impls for NumOpResult div and mul (Tobin C. Harding)

Pull request description:

  We recently added div and mul for combinations of `Amount`, `FeeRate`, and `Weight`. When doing so we forgot to add variations for `NumOpResult`.

ACKs for top commit:
  apoelstra:
    ACK 0361604bab6c6ef260410d0bd6e33ce24a41e775; successfully ran local tests

Tree-SHA512: 6d262b9079b8a670f32d58d49e3c7e9a79d5d795a4c9f37f6bc2213879649d41900e95f515d8685c3870c935358bcb25567b2f6f332301e1ad88188056047b7b
2025-04-15 13:20:09 +00:00
Tobin C. Harding 53837d9a2e
units: Improve crate level docs
Add a bit more to the crate level docs. This is a simple crate so we
don't need all that much.

Done for: C-CRATE-DOC
2025-04-14 14:33:26 +10:00
Tobin C. Harding 0361604bab
Add impls for NumOpResult div and mul
We recently added div and mul for combinations of `Amount`, `FeeRate`,
and `Weight`. When doing so we forgot to add variations for
`NumOpResult`.
2025-04-14 11:32:24 +10:00
Tobin C. Harding 0f62c9a582
units: Make minor improvements to MathOp
Follow up from #4312, improve the `MathOp` type by:

- Do not provide public constructor
- Add cast protection
2025-04-14 10:37:28 +10:00
Jamil Lambert, PhD ec38860b65
Add a test to kill mutants in MathOp
Weekly mutation testing found mutants in `is_overflow` and
`is_divide_by_zero`.

Add a test to kill them.
2025-04-11 09:31:13 +01:00
merge-script c5b1b31963
Merge rust-bitcoin/rust-bitcoin#4320: units: Do trivial docs fixes
da69e636a9 units: Use 100 column width in rustdoc comments (Tobin C. Harding)
53c6ae4d40 units: Remove expect from rustdoc example (Tobin C. Harding)

Pull request description:

  A couple of quick docs fixes while trying to polish `units`.

ACKs for top commit:
  apoelstra:
    ACK da69e636a9d21e602289062279ed5ebc6b1429b6; successfully ran local tests

Tree-SHA512: acfbec90b0327850b882c5e1b1e7eaadbf0a09a30dcc46529386ea419ed74846a678a5980f5706f8d280f30ec6f6d06af2db8f0e1748523b15ad47a654caee4b
2025-04-10 20:54:11 +00:00
Tobin C. Harding da69e636a9
units: Use 100 column width in rustdoc comments
We typically use 100 column width for comments, do so but only if it
does not make the layout worse.
2025-04-08 14:25:04 +10:00
Tobin C. Harding 53c6ae4d40
units: Remove expect from rustdoc example
We can just assert against an explicit `Some` value instead of using
`expect`.
2025-04-08 14:25:04 +10:00
Tobin C. Harding d6881ff5f8
units: Enable differentiating div-by-zero
Division by zero is a different error class that overflow. Add a
`MathOp` enum that enables one to check the error class.
2025-04-08 09:04:30 +10:00
Tobin C. Harding 5fb64953c5
units: Return NumOpResult when implementing Div
Currently we use a std numeric type for the output of various `Div`
implementations while other ops use `NumOpResult`. This makes it
difficult to chain operations.

Throughout the crate use `Output = NumOpResult<Foo>` when implementing
`Div`.

Later we want to enable users differentiating between an overflow and a
div-by-zero. Explicitly do not implement that yet, done separately to
assist review.
2025-04-07 15:08:01 +10:00
Tobin C. Harding dba61c9efe
units: Fix internal docs
The `impl_op_for_references` macro implements an `ops` trait, nothing to
do with opcodes.
2025-04-07 12:14:12 +10:00
Tobin C. Harding 512326b8b9
units: Macroize implementing OptionExt
We are going to add implementations of `OptionExt` for various other
types and all impls are almost identical. To make doing so easier
macroize the implementation for `Amount` and `SignedAmount`.

Internal change only, no logic changes.
2025-04-07 12:14:12 +10:00
Tobin C. Harding f5b54e5fe0
units: Move general result stuff to a separate module
We currently use the `NumOpResult` for operations involving more than
just amount types (e.g. `FeeRate`) however when the `result` module was
written we only used amount types.

To make the intention of the custom result types more clear introduce a
top level `result` module and move the general code there. Leave the
amount implementations in the `amount` module. Note that both `result`
modules are private.

Move the `OptionExt` impls because later we will add a bunch more of them.

Internal change only, no logic changes.
2025-04-07 12:14:09 +10:00
Tobin C. Harding f49efdf3f7
units: Remove mention of amount in result module
We currently use the `NumOpResult` for operations involving more than
just amount types (e.g. `FeeRate`) however when the `result` module was
written we only used amount types.

To make the docs and code clearer use 'numeric type' instead of
'amount' in docs. And for local variables use `x` instead of `amount`.

This is docs and internal changes only.
2025-04-07 12:13:45 +10:00
Tobin C. Harding ca6c607953
Adhere to sanity rules for amount types
From my reading of the new sanity rules (#4090) we should only have a
single constructor that accesses the inner field of the amount types.

Furthermore we have one const constructor inside the privacy boundry and
a couple outside.

Move the const constructors outside of the privacy boundry.

Internal change only.

Please note

The function being inside privacy boundary allows it to not have the
"runtime" check (most likely optimized-away after inlining). But if we
wanted to get rid of that check we should have _unchecked method
instead. But we don't want that (yet), since the check here will have
zero performance impact in optimized builds and it's not worth the
cost of dealing with unchecked constructors to optimize debug builds.
2025-04-03 13:09:40 +11:00
Tobin C. Harding 6c614d9320
units: Fix panic message
Recently I wrote a panic message that included the maximum value of an
integer however I used the max of a 16 bit value for both signed and
unsigned - this is incorrect.

Use the correct values for `u16::MAX` and `i16::MAX`.
2025-04-03 12:58:30 +11:00
merge-script 59524adafd
Merge rust-bitcoin/rust-bitcoin#4295: Automated nightly rustfmt (2025-03-30)
b8910e201e 2025-03-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 b8910e201ea4374bb0508aa50c6779d080ef6484; successfully ran local tests

Tree-SHA512: 9bd89439304322d30e04aae8f9803f9e07830b616cb49339ac4b1e0ee1bfe440865d9ebc7f41eea1bcd35cb751060215eec20d258d88e9f20dd3f905b9ab690f
2025-03-30 19:37:31 +00:00
merge-script f2869ad348
Merge rust-bitcoin/rust-bitcoin#4292: chore: fix grammatical errors
6ebdf61e76 Fix grammatical typos (VolodymyrBg)

Pull request description:

  base58/src/error.rs:

  - Corrected grammar in error comment: "Found a invalid ASCII byte" → "Found an invalid ASCII byte".

  bitcoin/CHANGELOG.md:

  - Fixed typo in function name: p2wpkh_signiture_hash → p2wpkh_signature_hash.

  units/src/amount/error.rs:

  - Fixed grammar: "was large than" → "was larger than".

  units/src/fee_rate/mod.rs:

  - Corrected typo: "assoctiated" → "associated".

  units/tests/api.rs:

  - Grammar fix: "THE POINT of tests are" → "THE POINT of tests is".

ACKs for top commit:
  apoelstra:
    ACK 6ebdf61e769903da1ad21fd6ab9bf22ff3c04bab; successfully ran local tests

Tree-SHA512: bb5800b6248bedad46d511a0123c50b1d8d2deacfa752cd675d21e40cb78a6a5d917da28a9a87c3f779cd13819d5b16a7668d1e388d1d58d200ea688d8c114ac
2025-03-30 15:19:49 +00:00
Fmt Bot b8910e201e 2025-03-30 automated rustfmt nightly 2025-03-30 01:27:51 +00:00
lfgtwo 89d61304af chore: remove needless question mark 2025-03-29 01:00:06 +08:00
merge-script 171c779c01
Merge rust-bitcoin/rust-bitcoin#4287: units: Kill mutants found in weekly mutation testing
f15e461baf Add an exclusion for a mutant in a deprecated fn (Jamil Lambert, PhD)
9a2b56f381 Modify test in Amount to kill mutants (Jamil Lambert, PhD)
1d1cf00b1e Add test to BlockTime to kill mutants (Jamil Lambert, PhD)

Pull request description:

  Weekly mutation testing found mutants in `Amount` and `BlockTime`.

  Add a test to `BlockTime`.
  Add two asserts to `Amount` tests.
  Exclude deprecated function from mutation testing.

  Closes #4225, #4243, #4278

ACKs for top commit:
  apoelstra:
    ACK f15e461baf463da0bf9d89018180c1d5032106c1; successfully ran local tests

Tree-SHA512: 18a405362db1b2eabac7c7ac01a56d306a1bf5f705626b5c217ec329e6420daa2f2e62b37c72537f29b7ee76b9fd795adde2da71b226fec3a74d0f25dca6cd96
2025-03-28 12:29:14 +00:00
VolodymyrBg 6ebdf61e76 Fix grammatical typos
Fix grammar and typos in documentation and README
2025-03-27 20:49:19 +02:00
merge-script 158240c3c9
Merge rust-bitcoin/rust-bitcoin#4284: Use `path = [bala]` for `rust-bitcoin`'s workspace members dependencies. remove `[patch.crates-io.balab]`
9a572dabde refactor: use path dependencies for workspace members in bitcoin/Cargo.toml (Eval EXEC)

Pull request description:

  This PR want to:

  1. make all workspace members use `workspace = true` syntax to import dependencies.
  2. use `path = [balabala]` to define dependencies, instead of useing `[patch.crates-io.balabala]` , fix: https://github.com/rust-bitcoin/rust-bitcoin/issues/4283

ACKs for top commit:
  Kixunil:
    ACK 9a572dabde
  apoelstra:
    ACK 9a572dabdeb077f96b2ab66be1a80fcec3e805e3; successfully ran local tests

Tree-SHA512: 834ef881ed3fd324a9ecca440e8e591984a7e474eb6aeab86a0301cbd08b6dc96ecdc34b306ad146b11b50f7488024c289b8f8c7c6de1a2bdba7aec515b722ee
2025-03-27 15:01:47 +00:00
Eval EXEC 9a572dabde
refactor: use path dependencies for workspace members in bitcoin/Cargo.toml
Signed-off-by: Eval EXEC <execvy@gmail.com>
2025-03-27 12:55:16 +08:00
Jamil Lambert, PhD 9a2b56f381
Modify test in Amount to kill mutants
Mutants found in weekly mutation testing.

Add an assert for both signed and unsigned to an existing test to kill
them.
2025-03-26 09:48:21 +00:00
Jamil Lambert, PhD 1d1cf00b1e
Add test to BlockTime to kill mutants
Mutants found in weekly mutation testing.

Add a test to kill them.
2025-03-26 09:36:42 +00:00
merge-script ecffb4071b
Merge rust-bitcoin/rust-bitcoin#4169: units: Increase ops impls in `block` module
3ae21d5111 Use impl_add/sub_assign for block interval (Tobin C. Harding)
9d55922952 Use impl_op_for_references for block height/interval (Tobin C. Harding)
f5e17914b6 Move Assign impls together (Tobin C. Harding)
cc66838e80 units: Remove unnecessary code comments (Tobin C. Harding)

Pull request description:

  Improve the ops impls in the `block` module using the already present macros.

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

Tree-SHA512: 6565426a06bb47d337d21cf5c59acca43e69228dbec8319fc95373025d220d8ec6273c54f214f312c4229603c455d08e4c6a8c108663c6db5086df36266979de
2025-03-26 02:21:12 +00:00
merge-script cf79f05ad6
Merge rust-bitcoin/rust-bitcoin#4271: Make code style consistent and fix naming in macro Array implementations
e744347022 Make usage of Self and type uniform across both modules (Erick Cestari)
dfb49f014c Rename impl_try_from_array to impl_from_array (Erick Cestari)

Pull request description:

  This PR makes two main changes:

  1. Standardizes the function signatures in the `Amount` and `SignedAmount` implementations by consistently using `Self` as the return type instead of the concrete type names. This improves code consistency, maintainability, and follows Rust's idiomatic practices.
  2. Renames `impl_try_from_array` to `impl_from_array` to better reflect its functionality.

  ### Changes
  **Consistent usage of Self instead of concrete types**

  - Replace all occurrences of `-> Amount` with `-> Self `in unsigned.rs
  - Replace all occurrences of `-> SignedAmount` with `-> Self` in signed.rs
  - Make similar replacements for Option/Result return types
  - Use `Self::` instead of explicit type name for static method calls

  **Function rename**

  Renamed `impl_try_from_array` to `impl_from_array` for better clarity

  ### Related Issues

  Closes #4210

  Closes #4241

ACKs for top commit:
  Kixunil:
    ACK e744347022
  tcharding:
    ACK e744347022
  apoelstra:
    ACK e744347022d1ad1e0ca0a83ec9350501af08297b; successfully ran local tests

Tree-SHA512: 3113f3ccf595b298afe6b23514f1de790284df7fcb55a13658aabe3ef4fcea0e401b65b0a2c67ac18da87a1bcd247bd1f1484856fe03470b98dfa2614958a3bb
2025-03-25 19:39:23 +00:00
merge-script 4525fd3cad
Merge rust-bitcoin/rust-bitcoin#4263: docs: fix LICENSE link
d0bead6f94 docs: fix LICENCE link (jike)

Pull request description:

  ![image](https://github.com/user-attachments/assets/9c08a57e-e958-487f-ba9d-978bd6fde913)

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

Tree-SHA512: 148ea7c35ca8872e314e12889cab325af6965f533abea062c49d03809d57de3b476a97d39e2ae4e0c8479da263b7959c9cf2409050e3888af33b308c022391b1
2025-03-24 19:10:56 +00:00
jike d0bead6f94 docs: fix LICENCE link 2025-03-23 11:41:07 +00:00
Erick Cestari e744347022 Make usage of Self and type uniform across both modules
This commit standardizes the function signatures in the Amount and SignedAmount
implementations by consistently using Self as the return type instead of the concrete
type names. This makes the code more consistent, easier to maintain, and follows Rust's
idiomatic practices.

Changes:

Replace all occurrences of -> Amount with -> Self in unsigned.rs
Replace all occurrences of -> SignedAmount with -> Self in signed.rs
Make similar replacements for Option/Result return types
Use Self:: instead of the explicit type name for static method calls
2025-03-21 14:26:35 -03:00
Andrew Poelstra 2958521117
amount: remove from_sat_unchecked
Turns out we don't even need this. It is only used in one place now and
we can just stick an .expect there.
2025-03-18 19:33:03 +00:00
Andrew Poelstra d0d7a15604
amount: move MIN/MAX constants and constructors inside the privacy boundary
It's conceptually a bit tortured to have an `Amount` type defined in a
private module, with an _unchecked method allowing you to set values out
of range, which needs to be used outside of the module to *define* the
range and the constructors that check it.

Move the constants and constructors inside the privacy module, where they
can be written directly. This is easier to understand and eliminates a couple
_unchecked calls.
2025-03-18 19:33:03 +00:00
Andrew Poelstra 004d073184
amount: return i64 from parse_signed_to_satoshi
This private function is used for string-parsing an amount. It returns a
sign boolean and a u64, but its surrounding logic can be simplified if
it just returns a i64 (which is OK now since the range of `Amount` fits
into the range of i64).

Along the way we eliminate some instances of from_sat_unchecked.

Annoyingly we still need the bool to distinguish -0 from +0; when
parsing Amount we reject -0 (and we have tests for this).

This causes a couple error constructors to no longer be used outside of
unit tests. May be worth looking at whether we need them, or whether we
should be using them in parse_signed_to_satoshi.
2025-03-18 19:32:58 +00:00
Andrew Poelstra 3370c14d74
amount: stop using from_sat_unchecked in tests
There is no need for this. It's a 2-line diff to change it.
2025-03-18 19:27:54 +00:00
Andrew Poelstra beaa2db7e5
amount: add from_sat_i32 and from_sat_u32 methods for small constants
We have a ton of calls to `from_sat_unchecked` for small constants which
were clearly in range, e.g. in fee.rs. Add a new constfn for these
cases. Don't bother making a generic Into<u32>/Into<u16> variant because
there isn't an obvious name for it.

There are 7 instances where we're using this method with values that are
out of range, which we leave as from_sat_unchecked for now.
2025-03-18 19:27:53 +00:00
Andrew Poelstra 82d9d1aeea
amount: rename `from_int_btc_const` unctions to hungarian ones
We have `from_int_btc_const` on both `Amount` and `SignedAmount` because
the "real" `from_int_btc` is generic over the integer type it accepts,
which means that it cannot be a constfn. But we do want a constfn.

However, just because `from_int_btc_const` exists for the sake of
constfn doesn't mean that that's what it *is*. So rename these methods
to reflect what they *are*.
2025-03-18 19:27:51 +00:00
Tobin C. Harding 2ec1c2a044
units: Make from_int_btc_const take a 16 bit integer
The `from_int_btc_const` constructors are specifically designed for
easily creating amount types in const context but currently they return
an error which is annoying to handle in const context. If we make the
`whole_bitcoin` parameter a 16 bit integer this gives us a nicer const
constructor with the downside that it can only create values upto a
maximum of

- unsigned: 65_536
- signed: 32_767

That is plenty high enough for most use cases.

Then use the new `from_int_btc_const` in associated consts.

Note that because `from_sat` checks max (and min) values we must
define max and min from sats directly.
2025-03-18 14:49:34 +00:00
Fmt Bot a74e08a53d 2025-03-16 automated rustfmt nightly 2025-03-16 01:25:25 +00:00
merge-script 0ca9fcfd0e
Merge rust-bitcoin/rust-bitcoin#4157: Enforce MAX_MONEY invariant in amount types
ab4ea7c13d Enforce the MAX_MONEY invariant in amount types (Tobin C. Harding)

Pull request description:

  Enforcing the `MAX_MONEY` invariant is quite involved because it means multiple things:

  - Constructing amounts is now fallible
  - Converting from unsigned to signed is now infallible
  - Taking the absolute value is now infallible
  - Integer overflow is eliminated in various places

  Details:
  - Update `from_sat` to check the invariant
  - Fix all docs including examples
  - Use the unchecked constructor in test code
  - Comment any other use of the unchecked constructor
  - Deprecate `unchecked_abs`
  - Fail serde (using the horrible string error variant)
  - Try not to use the unchecked constructor in rustdocs, no need to encourage unsuspecting users to use it.
  - Use `?` in rustdoc examples (required by Rust API guidlines)
  - Remove `TryFrom<Amount> for SignedAmount` because the conversion is now infallible. Add a `From` impl.
  - Fix the arbitrary impls
  - Maintain correct formatting
  - Remove private `check_max` function as its no longer needed

  Close #620

ACKs for top commit:
  apoelstra:
    ACK ab4ea7c13d08411044bd5f9c17457e926c80ed4d; successfully ran local tests

Tree-SHA512: bec963d8ea69e202f399cd19bca864b06f3e86323d376c2d2126d74093598f8bbbf19792b2327dba0862ef6f0201202778014a2be7a14991f02917d8ca312afb
2025-03-13 23:35:40 +00:00
merge-script 2f711b0c07
Merge rust-bitcoin/rust-bitcoin#4235: Use impl_op_for_references macro in fee module
93c6c8cef5 Use impl_op_for_references macro in fee module (Erick Cestari)

Pull request description:

  This pr replaces the individual operator implementations in the fee module with the impl_op_for_references macro to handle reference operations. This removes the need to manually implement reference combinations for operands, simplifying the code and improving consistency.

  ### Changes:
  - Replaces direct implementations of operators with macro usage
  - Adds tests to verify that reference operations work correctly
  - Maintains the same semantics as the original implementation

  Closes #4173

ACKs for top commit:
  tcharding:
    ACK 93c6c8cef5
  apoelstra:
    ACK 93c6c8cef59ceed56932d62daeb212c2b40fc4a1; successfully ran local tests; yeah, I think the docs loss is fine -- the docs are hard to find and say exactly what users expect of the / operator

Tree-SHA512: 51d7643c2cecd16a0cb16afcd195fd87bc9eca9116e16518d888ba61a8edb5684162af987ea52611c9463f5299810f92a057dedc3fa8e89cdef21ef40528bca1
2025-03-13 19:37:59 +00:00
merge-script d1365eb376
Merge rust-bitcoin/rust-bitcoin#4219: Rename then new `Timestamp` type
c707b959b7 Rename timestamp module to time (Tobin C. Harding)
e2dee4900f Re-name Timestamp to BlockTime (Tobin C. Harding)

Pull request description:

  Done in two patches so we can bikeshed the name of the type and separately the name of the module.

  - Rename type: `Timestamp` to `BlockTime`
  - Rename module: `timestamp` to `time`

ACKs for top commit:
  apoelstra:
    ACK c707b959b72dd89ca6df581a6102f32daedb8368; successfully ran local tests

Tree-SHA512: de3855b38445a58b6767a6081919eecb81c6c12aee3f6699f3bfa10efaf5770b54fb412da23991a9ee734e14dfb642af670f0218d1886cdc8c8d3f393ef65d7e
2025-03-13 15:13:31 +00:00
Tobin C. Harding ab4ea7c13d
Enforce the MAX_MONEY invariant in amount types
Enforcing the MAX_MONEY invariant is quite involved because it means
multiple things:

- Constructing amounts is now fallible
- Converting from unsigned to signed is now infallible
- Taking the absolute value is now infallible
- Integer overflow is illuminated in various places

Details:

- Update from_sat to check the invariant
- Fix all docs including examples
- Use the unchecked constructor in test code
- Comment any other use of the unchecked constructor
- Deprecate unchecked_abs
- Fail serde (using the horrible string error variant)
- Try not to use the unchecked constructor in rustdocs, no need to encourage unsuspecting users to use it.
- Use ? in rustdoc examples (required by Rust API guidlines)
- Remove TryFrom<Amount> for SignedAmount because the conversion is now infallible. Add a From impl.
- Fix the arbitrary impls
- Maintain correct formatting
- Remove private check_max function as its no longer needed
2025-03-13 09:07:14 +11:00
Erick Cestari 93c6c8cef5 Use impl_op_for_references macro in fee module
This commit replaces the individual operator implementations in the fee
module with the impl_op_for_references macro to handle reference operations.
This removes the need to manually implement reference combinations for
operands, simplifying the code and improving consistency.

The change:
- Replaces direct implementations of operators with macro usage
- Adds tests to verify that reference operations work correctly
- Maintains the same semantics as the original implementation
2025-03-12 15:24:53 -03:00
Tobin C. Harding 5d851f1c3e
Remove deprecated amount methods
When we enforce the MAX_MONEY invariant these functions would require
the function signature changing - might as well just delete them.
2025-03-11 05:37:40 +11:00
Tobin C. Harding 76a2d70b28
Make mul weight by fee return NumOpResult
Now that we have the `NumOpResult<Amount>` type that is used to show a
math calculation returned a valid amount we can use it when multiplying
weight and fee rates thus removing panics.
2025-03-11 05:37:40 +11:00
Tobin C. Harding 13595fbe7d
Fix amount whole bitcoin constructors
I royally botched the recent effort to make const amount constructors
use a smaller type. I left in an  unnecessary panic and forgot to do
both of them.

Note these function return values will change again very shortly when we
start enforcing the MAX_MONEY invariant. However the 64 to 32 bit change
is unrelated to that and is easier to review if done separately.

Whole bitcoin can not in any sane environment be greater than 21,000,000
which fits in 32 bits so we can take a 32 bit integer in the whole
bitcoin constructors without loss of utility. Doing so removes the
potential panic.

This is a breaking API change. We elect not to deprecate because we want
to keep the same function names.
2025-03-11 05:37:40 +11:00
Tobin C. Harding ac71680202
Pick one - MAX or MAX_MONEY
Just use MAX everywhere in this codebase.

After discussion in PR consensus was to just use MAX throughout the
codebase.

ref: https://github.com/rust-bitcoin/rust-bitcoin/pull/4164#discussion_r1979441438
2025-03-11 05:37:39 +11:00
Tobin C. Harding 6d70c77cf9
Enforce newtype sanity rules for amount types
The unchecked-should-be-unsafe conversation is out of scope for this
patch. We want to bite off small chunks so the constructors are left as
they currently are - we are just doing the encapsulation here. This is
in preparation for enforcing the MAX_MONEY invariant which is not
currently enforced.

As per the sanity rules policy outline in:

 https://github.com/rust-bitcoin/rust-bitcoin/discussions/4090

For both amount types create a private `encapsulate` module that
consists of exactly the type and a single constructor and a single
getter.
2025-03-11 05:37:19 +11:00
Tobin C. Harding e6f7b26d80
Use _unchecked in amount const types
We are about to start enforcing the MAX_MONEY invariant. Doing so will
change constructors to return an error type.

In preparation use the `_unchecked` constructor for all the consts.

Internal change only, no logic changes.
2025-03-11 05:32:07 +11:00
Andrew Poelstra ef0af8d62e
Use sat/ssat constructors throughout tests
There is an as yet unresolved discussion about the unchecked amount
constructor. In an effort to focus the amount of changes required later
and also to make the `tests` module uniform use the `sat` and `ssat`
constructor functions everywhere.

Internal change only, no logic changes.
2025-03-11 05:32:06 +11:00
Tobin C. Harding 8ecdc7c275
Use den_ prefix for local Denomination variable
Throughout the `amount::tests` module we use `sat` and `ssat` as aliases
to amount constructors but in on test we use them as `Denomination`
variables. To assist clarity and so we can introduce uniform usage of
the constructor aliases change the variable names to use the `den_`
prefix.

Internal change only, no logic changes.
2025-03-11 05:32:06 +11:00
yancy a273814d23 Replace underflow with overflow in doc comments
The use of underflow is misleading.  Adding one to MAX and
subtracting one from MIN are both considered an overflow.
2025-03-08 10:41:20 -06:00
yancy 2f897e2109 Remove warning section
Since monadic handling has been introduced, panics have been replaced
with return errors.  Therefore this section is no longer applicable.
2025-03-08 10:41:20 -06:00
merge-script 86266d2dad
Merge rust-bitcoin/rust-bitcoin#4161: Improve ops for amount types
0a9f14f7b0 Implement Div by amount for amount types (Tobin C. Harding)
b57bfb9bc5 Add missing Mul impls for amount types (Tobin C. Harding)
501c9ab89e Test amount ops that involve an integer (Tobin C. Harding)
851080d3b1 Add more add/sub tests (Tobin C. Harding)
47923957b1 Improve add/sub tests for amount types (Tobin C. Harding)
8bb9ce3e47 Add tests for amount op int (Tobin C. Harding)

Pull request description:

  Improve the test coverage and add missing implementations of math operations for the amount types.

  Along the way close #4030.

ACKs for top commit:
  apoelstra:
    ACK 0a9f14f7b036c5232449d058fb6d425c8376d87a; successfully ran local tests; nice!

Tree-SHA512: f303b2a90b5bb9e77091e047f8325821a5c89f52dfe242d849968dba0d097d3868d444009c2c05b9d7c0e91fa2ce6898cdc4733977699ca4b1ae226562878cdf
2025-03-08 15:12:51 +00:00
Tobin C. Harding c707b959b7
Rename timestamp module to time
We just re-named `Timestamp` to `BlockTime`. We have a `units::block`
module but it currently holds abstractions (`BlockHeight` and
`BlockInterval`) that are not onchain abstractions and therefore
somewhat different from the `BlockTime`. Instead of making `block` a
block 'utils' module instead re-name the `timestamp` module to `time`.
2025-03-08 08:30:10 +11:00
Tobin C. Harding e2dee4900f
Re-name Timestamp to BlockTime
We just added a `Timestamp` type without knowing that there was a push
by OpenTimestamps to also create a timestamp and that our new type may
lead to confusion. Our timestamp is explicitly for the `time` field in a
block so we can call it `BlockTime`. This name change makes the module
name stale but we will change that in a following patch to ease review.
2025-03-08 08:28:46 +11:00
merge-script 1a18ff582c
Merge rust-bitcoin/rust-bitcoin#4127: units: Prevent casting pub enums as ints
97453ef9bc units: Prevent casting pub enums as ints (Tobin C. Harding)

Pull request description:

  A public enum with simple variants gets an automatic integer variant that can be cast by library consumers. This puts a unnecessary maintenance burden upon us because we cannot then add variants in the middle of others.

  Add a hidden variant to the single public non-error enum in `units`.

ACKs for top commit:
  Kixunil:
    ACK 97453ef9bc
  apoelstra:
    ACK 97453ef9bc2b99a67252419ff015f13679df7312; successfully ran local tests

Tree-SHA512: 2515152107fb21a2dbdef9b46308fef6bd45f4a9719da7a39149b3bdbce6a93dc0f98e112ac246eb32dbe4df1210d5e6328c26ea8678e3da15276e893b39cc9c
2025-03-07 17:32:54 +00:00
merge-script 9d7190e581
Merge rust-bitcoin/rust-bitcoin#4190: Kill mutants in primitives and units
90d909becc Kill mutants in primitives and units (Shing Him Ng)

Pull request description:

  This kills 15 mutants found with the mutants workflow. Ran `cargo mutants` locally to confirm

  Closes #4156
  Closes #4106

ACKs for top commit:
  jamillambert:
    ACK 90d909becc
  tcharding:
    ACK 90d909becc
  apoelstra:
    ACK 90d909becc4638c03003845154e9cc1eb5f3ad41; successfully ran local tests
  Kixunil:
    ACK 90d909becc

Tree-SHA512: e5c95a1c4054cf1c60c940ea605eec84dffcbff292f9c7c4d96813c6389e807c318f6c5f8f69ceeb9ffcab3c3e45aa0d5a8fda7335d540c6f070aab92bae7a0f
2025-03-07 02:53:55 +00:00
merge-script fa8eaf0257
Merge rust-bitcoin/rust-bitcoin#4092: Add `Timestamp` newtype
b3f122b399 Add Timestamp newtype (Tobin C. Harding)

Pull request description:

  Bitcoin block headers have a timestamp. Currently we are using a `u32`. While this functions correctly it gives the compiler no chance to enforce type safety.

  Add a `Timestamp` newtype that is a thin wrapper around a `u32`. Document it and test the API surface in `api.rs`.

ACKs for top commit:
  apoelstra:
    ACK b3f122b3996c1a73479be2f95b7f2ae642c9c56f; successfully ran local tests
  Kixunil:
    ACK b3f122b399

Tree-SHA512: 6f4a4a588bc836243ae28f3d36be6c0ae264cb2b7a0061277910b107d05e5ca0e679497d2890208f5d8ec148f37bf263bcd0b0410f9e5e6370d8e763ff30b78a
2025-03-06 19:34:11 +00:00
merge-script 181b7482ca
Merge rust-bitcoin/rust-bitcoin#4174: Improve weight
2434afc40d Make Weigth::from_kwu const (Tobin C. Harding)
1fe984552e Improve Weight rustdocs (Tobin C. Harding)

Pull request description:

  Do two minor improvements to the `weight` module. Docs and add `const`.

ACKs for top commit:
  apoelstra:
    ACK 2434afc40dadd213f8695c5ce91d397c03f337be; successfully ran local tests
  Kixunil:
    ACK 2434afc40d

Tree-SHA512: e3e9653d5fcd060c27a2313e642d7b96f51b9342953505a30a9748cb7f0c19a87bcb1faadb1b07ecc770aaec45496e5a750ac48e3e9141e379c554f0875df6a1
2025-03-06 15:58:59 +00:00
Tobin C. Harding 97453ef9bc
units: Prevent casting pub enums as ints
A public enum with simple variants gets an automatic integer variant
that can be cast by library consumers. This puts a unnecessary
maintenance burden upon us because we cannot then add variants in the
middle of others.

Add a hidden variant to the single public non-error enum in `units`.
2025-03-06 11:34:02 +11:00
Shing Him Ng 90d909becc Kill mutants in primitives and units
This kills 15 mutants found with the mutants workflow
2025-03-04 21:35:10 -06:00
merge-script 5f1700e79f
Merge rust-bitcoin/rust-bitcoin#4181: Implement `Rem` for `Weight`
8007840676 Add a test for remainder (Jamil Lambert, PhD)
4787aa1f89 Implement Rem for Weight (Jamil Lambert, PhD)

Pull request description:

  Weight implements `Div` but not `Rem`.

  Add the `Rem` implementation.

  Add a test for the remainder operation on `Weight`

  Close #4171

ACKs for top commit:
  Kixunil:
    ACK 8007840676
  tcharding:
    ACK 8007840676
  apoelstra:
    ACK 80078406768aa5f8e4d21d42cc1d1fe9abeed1ea; successfully ran local tests

Tree-SHA512: cfcbc49a944146f7ba24a2f7b7f79ed2e2758ba2a23e9e69d9662afb5379dd74c646ff787c0e8218053e70410353cb74115e4c03bfdaafc8a1f9a4b0e51a3e15
2025-03-04 17:42:14 +00:00
Jamil Lambert, PhD 8007840676
Add a test for remainder
A remainder operation has been implemented for `Weight`.

Test the functionality of remainder with both a `Weight` and `u64`
2025-03-03 20:47:01 +00:00
Jamil Lambert, PhD 4787aa1f89
Implement Rem for Weight
`Weight` implements `Div` but not `Rem`

Add `Rem` impl for `Weight`
2025-03-03 20:43:21 +00:00
merge-script 6483244280
Merge rust-bitcoin/rust-bitcoin#4170: Improve crate docs headings
83d071e54b chacha20: Add whitespace (Tobin C. Harding)
4451724d31 chacha20: Add a docs heading (Tobin C. Harding)
d4417f9666 io: Improve crate docs heading (Tobin C. Harding)
c466554948 hashes: Improve crate docs heading (Tobin C. Harding)
6f4eb60936 Improve docs crate headings (Tobin C. Harding)

Pull request description:

  Make them all uniform after taking 2 minutes online to try find a nice format.

ACKs for top commit:
  apoelstra:
    ACK 83d071e54be0bc4ebd760a490a3ca887c0bf90a8; successfully ran local tests; lgtm

Tree-SHA512: 6f08c6cda91a7a870f1080b497f89607ac3d6b3c0234cbd2ba2da8710d46816398acac0bca2a49a3bc9466b814ae446842d3d304a3735df9f983e3ff5df005db
2025-03-03 20:05:29 +00:00
merge-script 43814eb9e5
Merge rust-bitcoin/rust-bitcoin#4134: chore: fix some typos in comments
ce19d40a80 chore: fix some typos in comments (looklose)

Pull request description:

  fix some typos in comments

ACKs for top commit:
  apoelstra:
    ACK ce19d40a805e2b67f6199cce61a73c6592019b5c; successfully ran local tests
  tcharding:
    ACK ce19d40a80

Tree-SHA512: 4bf5d339e4e73a6f1378881ad62b17f78796e6000f24eea6b3a381d3e03f4fd8b9775710a7eb5a087bfe0d557d1ab1a8291dcc7b86a2c9ded3318774cf2e5b68
2025-03-03 17:33:28 +00:00
Tobin C. Harding 85612908af
Use uniform return statement in docs
We have a bunch of 'Returns [`None`] if .. ' statements. Make the whole
module uniform.
2025-03-03 14:06:01 +11:00
Tobin C. Harding 2434afc40d
Make Weigth::from_kwu const
The other two `Weight` constructors are const already.
2025-03-03 13:46:42 +11:00
Tobin C. Harding 1fe984552e
Improve Weight rustdocs
Do trivial improvement to rustdocs for the `Weight` type.
2025-03-03 13:44:14 +11:00
Tobin C. Harding 6f4eb60936
Improve docs crate headings
I took a look at the rendered HMTL of `bitcoin`, `primitives`, `units`,
`serde`, and `tokio` and picked a header style that I thought looked
good.

Use it for `primitives` and `units`.
2025-03-03 13:28:01 +11:00
Tobin C. Harding 3ae21d5111
Use impl_add/sub_assign for block interval
We have a macro for implementing `AddAssign` and `SubAssign`.

Use the macro, gets us an additional ref impl for both.
2025-03-03 13:16:10 +11:00
Tobin C. Harding 9d55922952
Use impl_op_for_references for block height/interval
We have a new macro for implementing ops with a bunch of reference
combos. Lets use it for block `Height` and `Interval`.

This patch is strictly additive.
2025-03-03 13:11:19 +11:00
Tobin C. Harding f5e17914b6
Move Assign impls together
Next patch will move all the impls of `Add` and `Sub` into a macro call.
In order to make that patch smaller move the assign impls to be together
below the add/sub impls.

Code move only, no logic change.
2025-03-03 13:09:10 +11:00
Tobin C. Harding cc66838e80
units: Remove unnecessary code comments
These comments to not add much value - remove them.
2025-03-03 13:05:35 +11:00