Commit Graph

151 Commits

Author SHA1 Message Date
Daniel Roberts c7bdec14fb Fix clippy lint and formatting for `Xpriv::derive_xpriv` and `Xpriv::derive_xpub` calls 2025-06-23 18:06:02 -05:00
rustaceanrob d9cf7270eb
Move `bitcoin/p2p` into `p2p`
Moves all of the content from `bitcoin/p2p` into `p2p`.

`TryFrom<Network>` must be implemented for `Network -> Magic` now that
`Network` is a foreign, non-exhaustive type. Ser/de test is updated
accordingly, as well as the `Magic::from_network` constructor, which I
have opted to return an `Option<Self>`. The `TryFrom` implementation
uses a new `UnknownNetworkError(Network)` that mirrors the `Magic ->
Network` error.

The example handshake does not generate a random nonce for the version
message, as there is no `rand` dependency in this crate and the program
only makes a single, user-defined connection.

It appears we can do better than copying and pasting the consensus
encoding macros and functions from `bitcoin` without doing weird
cross-crate macros that require some special knowledge of the crate to
know when they will compile.
2025-06-18 14:11:35 +01:00
Fmt Bot 4b5c6dd547 2025-06-08 automated rustfmt nightly 2025-06-08 01:44:53 +00:00
rustaceanrob cbe04b00c6
Remove all `p2p` dependency from `network`
Motivated by moving the `p2p` module to its own crate. `TryFrom` and
`From` are already implement for converting to and from
`Network`/`Magic`. The methods related to `Magic` are removed from
`Network`, as well as any reference to `p2p` in the documentation, as
`bitcoin` would no longer depend on `p2p`.

The deser roundtrip test are relocated to `p2p/mod.rs`
2025-05-29 15:20:10 +01:00
Tobin C. Harding 6b90e42e78
Finalize the script hex APIs
Recently we made an attempt at making the hex APIs for scripts easier to
use, better documented, and shown via an example.

After that work we decided it would be better if `LowerHex`/`UpperHex`
did not have the prefix. We also wanted to further clarify the inherent
function names to make the all explicit.

See GitHub issue #4316 for the thread of discussion.

Note that this PR does not require changes to the serde regression test
which were non changed in the original work either.
2025-05-08 15:12:05 +10:00
merge-script 7d4b40dfd4
Merge rust-bitcoin/rust-bitcoin#4410: Wrap secp256k1::XOnlyPublicKey to improve error handling
c11772a768 Accept flexible input types for Taproot-related functions (Erick Cestari)
2a518d62e6 Wrap secp256k1::XOnlyPublicKey to improve error handling (Erick Cestari)

Pull request description:

  This PR addresses issue #4361 by creating a wrapper type for XOnlyPublicKey instead of directly re-exporting it from the secp256k1 library.

  ### Key Changes

  1. Created a new `XOnlyPublicKey` struct that wraps `secp256k1::XOnlyPublicKey`
  2. Implemented custom error types:
      - `ParseXOnlyPublicKeyError` for handling parsing errors
      - `TweakXOnlyPublicKeyError` for tweaking an `XOnlyPublicKey`
  3. Updated all imports and usage throughout the codebase
  4. Implemented necessary traits and methods for compatibility

  Closes #4361

ACKs for top commit:
  apoelstra:
    ACK c11772a768eefd89dcc0e3b1a369d535c191f94a; successfully ran local tests
  tcharding:
    ACK c11772a768

Tree-SHA512: c8da3486e7ffcab6c24cc08f9b2f964dd9158449ef2bd720e54d56176bc7027052314ea23cac3f673d217fa785238ea8a9b5323ba57f02199f20e56df5893965
2025-05-07 17:01:31 +00:00
Erick Cestari c11772a768
Accept flexible input types for Taproot-related functions
Refactor Taproot functions to accept any type implementing `Into<XOnlyPublicKey>`,
instead of requiring `XOnlyPublicKey` directly. This improves ergonomics when working
with compatible types, avoiding unnecessary `.into()` conversions at call sites.
2025-05-06 09:01:27 -03:00
Erick Cestari 2a518d62e6
Wrap secp256k1::XOnlyPublicKey to improve error handling
This commit creates a wrapper type for XOnlyPublicKey instead of
directly re-exporting it from the secp256k1 library.
2025-05-06 09:01:17 -03:00
Jamil Lambert, PhD 282434d4bd
Use variable directly in format! string
There is a new lint error on nightly-2025-04-25 "variables can be used
directly in the `format!` string".

Use the variables in the `format!` string for all cases in
`bitcoin/examples/`.
2025-05-06 09:49:03 +01:00
merge-script 082075304e
Merge rust-bitcoin/rust-bitcoin#4373: Add as_inner method to TweakedKeypair
3bb6c73f2d Add methods to retrieve inner types (Shing Him Ng)

Pull request description:

  Resolves #4345

ACKs for top commit:
  tcharding:
    ACK 3bb6c73f2d
  apoelstra:
    ACK 3bb6c73f2d3edd1165b7b7f3a833fa471786e166; successfully ran local tests; should backport to 0.32.x

Tree-SHA512: c89017bbc2126ec62c756c4ee9b49dcc8b94a3063a8155aadcf7c69a6f0bc9337baedffe7f52a4ab6f0b738302bea683391d394483c4c7eefbb622b97d34d26c
2025-05-03 23:24:19 +00:00
Shing Him Ng 3bb6c73f2d Add methods to retrieve inner types
For TweakedKeypair, `to_inner` is also renamed to `to_keypair` to maintain
consistency. Similarly, `to_inner` is renamed to `to_x_only_pubkey` for
TweakedPublicKey
2025-05-01 08:24:43 -05:00
merge-script ee037042ae
Merge rust-bitcoin/rust-bitcoin#4387: bip32: overhaul error types and add a "maximum depth exceeded" error
b9a12043b0 bip32: return error when trying to derive a path too deep (Andrew Poelstra)
73781e047b bip32: rename Error to ParseError (Andrew Poelstra)
a66ad97fb6 bip32: split InvalidChildNumber and InvalidChildNumberFormat out of error (Andrew Poelstra)
a891fb9b74 bip32: remove unused error variants (Andrew Poelstra)
f0a237c001 bip32: split out DerivationError from the main error enum (Andrew Poelstra)
32d96f6c33 bip32: make Xpriv::new_master be infallible (Andrew Poelstra)
0e5e021b69 bip32: change several cryptographically unreachable paths to expects (Andrew Poelstra)

Pull request description:

  This PR makes a first pass at splitting the `bip32::Error` type into multiple distinct types -- one for derivation (which can fail if you try to derive a hardened child of an xpub, or if you try to derive too many layers), one for parsing child numbers or derivation paths, and one for parsing xkeys. Along the way it cleans up a ton of weird things and typos, e.g. the psbt `GetKeyError` having an unused `Bip32` variant whose display text references "bip 23".

  Because all the error types get renamed, every part of this PR is an API break, but only the last commit is a "real" API break which uses the new `DerivationError::MaximumDepthExceeded` error variant to return an error when trying to derive a path of length 256 or longer. This means that `Xpriv::derive_xpriv` again returns an error result.

  I will make a simpler version of this last commit suitable for backporting to 0.32.x. (In 0.32.x `Xpriv::derive_priv` returns an error, so we can change it to error out on max-depth-exceeded without breaking the API. Sadly most users are likely to be unwrapping the error because in 0.32.x currently the error path is cryptographically unreachable...but at least this way the panic will be in their control rather than ours.)

  Fixes https://github.com/rust-bitcoin/rust-bitcoin/issues/4308

ACKs for top commit:
  tcharding:
    ACK b9a12043b0

Tree-SHA512: 688826126ff24066c6de9de3caa73db68c516ba8893d64d9226a498774a2fb9db7d7fd797375c6b3f820588c178632e1e6e8561022dfa7042a560582bf1509b4
2025-04-30 13:12:01 +00:00
Andrew Poelstra b9a12043b0
bip32: return error when trying to derive a path too deep
This restores the Result return from derive_xpriv which we had removed
in a previous PR, but such is life.

Fixes #4308
2025-04-29 23:09:32 +00:00
Tobin C. Harding 5d5a19793a
Run the formatter 2025-04-28 13:44:24 +10:00
Tobin C. Harding 2b72f1f30b
Make Lower/Upper hex print scripts with len prefix
Add the length prefix when formatting hex strings by way of `LowerHex`
and `UpperHex`.

This looses formatting options because I can't remember right now how
not to - again.
2025-04-28 13:43:07 +10:00
Tobin C. Harding c27b95fb0d
Make script to/from hex use consensus encoding
I'm not sure why we do not use consensus encoding currently for encoding
and decoding scripts to/from hex strings. Many tests include hard coded
hex which do not include the length prefix.

- Add a pair of encoding functions to encode/decode to/from hex without
the length prefix.
- Make `to_hex` and `from_hex` expect the length prefix i.e., use
consensus encoding.

This makes the API easier to use because the various encoding APIs can
be use together now eg `consensus::encode_hex` and `ScriptBuf::from_hex`.
2025-04-28 13:39:44 +10:00
Tobin C. Harding f4bc58dc48
bitcoin: Add a script encoding example
Our encoding/decoding support for scripts is currently a bit convoluted.
Add an example that shows how all the APIs go together.

Note this highlights a potential problem. `to_hex_string` is in
`bitcoin` and therefore has access to consensus encoding but does not
include the length prefix. This means that the output string from
`to_hex_string` cannot be parsed with
`consensus::encode::deserialize_hex` - which is surprising and has lead
to difficulty by at least one user trying to debug.
2025-04-28 13:38:12 +10:00
Andrew Poelstra 32d96f6c33
bip32: make Xpriv::new_master be infallible
The only error path for this is cryptographically unreachable and was
removed in a previous commit.
2025-04-22 14:45:36 +00: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
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
planetBoy dd6687d992
Update sighash.rs 2025-03-16 16:13:21 +01:00
planetBoy 968406cb95
Update ecdsa-psbt.rs 2025-03-11 15:43:09 +01:00
merge-script febce17eff
Merge rust-bitcoin/rust-bitcoin#4186: Clean up Witness API
Pull request description:

  Enhance Witness struct element access methods:

  - Rename `nth()` to `get()` for clearer slice-like element retrieval
  - Introduce `get_back()` method for flexible reverse indexing
  - Remove redundant `second_to_last()` and `third_to_last()` methods
  - Add `#[track_caller]` to index implementation for better error tracking
  - Update all references to use new method names
  - Improve documentation with usage examples

  The changes provide a more intuitive and consistent approach to accessing witness elements.

  Close #4098

ACKs for top commit:
  Kixunil:
    ACK 3ca3218c23
  tcharding:
    ACK 3ca3218c23
  apoelstra:
    ACK 3ca3218c236c63a9b006047524e2b47e310f07d9; successfully ran local tests

Tree-SHA512: 163e7457f3fe5141373e27a6df5fe1da6f2f05f02e877ef96243510d030d832c0fa86ade781e015a3c392f004651170b60438a83d330f1059457e5ade6478af7
2025-03-06 18:43:27 +00:00
Erick Cestari 3ca3218c23 witness: Improve element access methods with get() and get_back()
Enhance Witness struct element access methods:

- Rename `nth()` to `get()` for clearer slice-like element retrieval
- Introduce `get_back()` method for flexible reverse indexing
- Remove redundant `second_to_last()` and `third_to_last()` methods
- Add `#[track_caller]` to index implementation for better error tracking
- Update all references to use new method names
- Improve documentation with usage examples

The changes provide a more intuitive and consistent approach to
accessing witness elements.
2025-03-04 12:16:48 -03:00
Tobin C. Harding 852bcf6017
bitcoin: Remove hash type re-exports
The `{W}PubkeyHash` and `{W}ScriptHash` types are not likely to be used
directly by consumers of the library because we have other function that
return them and are more ergonomic to use. There is therefor no good
reason to re-export them from the crate root.
2025-03-04 08:15:04 +11:00
19年梦醒 f80cf2cb2a
update secp256k1 to 0.30.0 2025-03-02 23:31:48 +08:00
leopardracer 83bd83385e
Update sighash.rs 2025-02-25 12:10:51 +02:00
Tobin C. Harding 6244cb75fa
Introduce monadic AmountOpResult
We would like to return an error when doing math ops on amount types.
We cannot however use the stdlib `Result` or `Option` because we want to
implement ops on the result type.

Add an `AmountOpResult` type. Return this type from all math operations
on `Amount` and `SignedAmount`.

Implement `core::iter::Sum` for the new type to allow summing iterators
of amounts - somewhat ugly to use, see tests for example usage.
2025-02-10 10:06:59 +11:00
Tobin C. Harding 00b71a670f
Use from_sat_unchecked for hardcoded ints
We have an `_unchecked` amount constructor that makes no assumptions
about the argument. We would like to start enforcing MAX_MONEY but the
diff to introduce this is massive. In an effort to make it smaller we
can do all the hardcoded ints first. We did this already but a bunch
more snuck in or were missed.

In any amount constructor that passes in a hardcoded const as a decimal
integer (i.e., not hex) use the `_unchecked` version.

Done in preparation for enforcing MAX_MONEY.
2025-01-24 09:05:00 +11:00
Tobin C. Harding dbec9807f9
Shorten identifiers by removing _in_sats
Using `_in_sats` is not meaningful because an `Amount` is an amount,
period.

Remove `_in_sats` and `_IN_SATS` from identifiers.

Internal change only.
2025-01-24 08:54:24 +11:00
merge-script 05c28cf31d
Merge rust-bitcoin/rust-bitcoin#3915: Add FIFTY_BTC const to the amount types
e0028239cf api: Run just check-api (Tobin C. Harding)
5eb5941215 Add FIFTY_BTC const to the amount types (Tobin C. Harding)

Pull request description:

  The mining reward for the first epoc is 50 bitcoin. For mainnet this is old news but for regtest it is still relevant.

  Add and use a new const `FIFTY_BTC` to the `Amount` type. To keep the amount types uniform also add it to the `SignedAmount`.

ACKs for top commit:
  storopoli:
    ACK e0028239cf
  jamillambert:
    ACK e0028239cf
  apoelstra:
    ACK e0028239cf207660deb2873a92bacfa1315af634; successfully ran local tests

Tree-SHA512: 623ed8b1f5fe8dd95309179308fea83d68be4349becf6305769b0378cc9032961df2c062dc2bf702fec5e2394e8abb7360d2be6f19b6cf505db8769a5ae39e16
2025-01-20 02:42:45 +00:00
Fmt Bot fec6a7669e 2025-01-19 automated rustfmt nightly 2025-01-19 01:19:33 +00:00
Tobin C. Harding 5eb5941215
Add FIFTY_BTC const to the amount types
The mining reward for the first epoc is 50 bitcoin. For mainnet this is
old news but for regtest it is still relevant.

Add and use a new const `FIFTY_BTC` to the `Amount` type. To keep the
amount types uniform also add it to the `SignedAmount`.
2025-01-17 10:08:09 +11:00
Tobin C. Harding 668056fb36
Use Amount in examples
Use the `Amount` type as parameter in examples code instead of a `u64`.

Done as part of preparation for enforcing MAX_MONEY.
2025-01-14 09:48:48 +11:00
merge-script 6a4ca4e61a
Merge rust-bitcoin/rust-bitcoin#3878: bitcoin: Add an example of doing I/O to encode/decode
706a135de6 bitcoin: Add an example of doing I/O to encode/decode (Tobin C. Harding)

Pull request description:

  In an effort to improve the documentation on `bitcoin_io` add an example in `bitcoin` crate that demonstrates a few things:

  - Encode/Decode a `rust-bitcoin` type to/from a stdlib type.
  - Encode to a custom type by implementing `bitcoin_io` traits.
  - Encode to a foreign custom type by using the `bitcoin_io::bridge::FromStd` wrapper.

  Later we can link to this example online in the `bitcoin_io` docs.

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

Tree-SHA512: cd3ff4067d5b86031255cb31fe17dea3fd22479699d32efad93c359de465ef6250f29aa4c43ce4218ae623fa6c355661960c11908a729a895655319141b82852
2025-01-11 14:46:13 +00:00
Tobin C. Harding 706a135de6
bitcoin: Add an example of doing I/O to encode/decode
In an effort to improve the documentation on `bitcoin_io` add an example
in `bitcoin` crate that demonstrates a few things:

- Encode/Decode a `rust-bitcoin` type to/from a stdlib type.
- Encode to a custom type by implementing `bitcoin_io` traits.
- Encode to a foreign custom type by using the `bitcoin_io::bridge::FromStd` wrapper.

Later we can link to this example online in the `bitcoin_io` docs.
2025-01-08 10:18:00 +11:00
Tobin C. Harding a7c44cebf9
Use _unchecked to construct amounts
We have a `_unchecked` constructor now for both `Amount` and
`SignedAmount`. In preparation for enforcing the `MAX_MONEY` invariant
use the `_unchecked` constructor throughout the codebase to construct
amounts from hard coded integer values.
2025-01-06 13:14:21 +11:00
Jamil Lambert, PhD e56f461916
Make capitalization of SegWit uniform in strings 2024-12-17 14:49:01 +00:00
Jamil Lambert, PhD 3520e832ac
Make capitalization of SegWit uniform in rustdocs 2024-12-17 14:28:28 +00:00
merge-script 031b402b26
Merge rust-bitcoin/rust-bitcoin#3678: Remove unused extern statement
667b7f1010 Remove unused extern statement (yancy)

Pull request description:

  `extern crate` keywords are no longer needed to import a crate as of Rust 2018

ACKs for top commit:
  tcharding:
    ACK 667b7f1010
  apoelstra:
    ACK 667b7f1010bc0745d3e39181e15ec795aeca68dc; successfully ran local tests
  sanket1729:
    ACK 667b7f1010

Tree-SHA512: d157aa881dfce12b65bb676425cb5f17fa5a193d0001f37c26f74cab1254ab08fdcc9b7462b9a74210f85028299af9e14c0071ba390642b59bb7e986ba85933d
2024-11-29 03:01:13 +00:00
yancy 667b7f1010 Remove unused extern statement
extern crate keywords are no longer needed to import a crate
2024-11-27 23:06:55 -06:00
yancy d9b48cc2ce Add p2wpkh address creation example 2024-11-27 15:09:14 -06:00
Jamil Lambert, PhD 1649b68589
Standardize wording to `constructs a new`
There is a range of different wordings used in the docs of constructor
type functions.

Change all to start with `Constructs a new` or `Constructs an empty`.
2024-11-05 13:02:26 +00:00
Jamil Lambert, PhD 27f94d5540
Replace `creates` with `constructs`
In functions that act like constructors there is a mixture of the usage
of `creates` and `constructs`.

Replace all occurrences of `creates` with `constructs` in the first line
of docs of constructor like functions.
2024-11-05 12:47:28 +00:00
Tobin C. Harding 42e5043b33
Add from_int_btc group of functions
Add/update the from_int group of functions to provide one that errors
and one that is const and panics (errors in const context are not useful
because one cannot call `unwrap` in const context).
2024-11-02 10:19:03 +11:00
Tobin C. Harding db40297f87
script: deprecate to_bytes
Deprecate the `Script::to_bytes` function in favour of `to_vec` as we
are doing elsewhere.

Note that `ScriptBuf` has `into_bytes` because it does not copy.
Potentially this should be deprecated in favour of `into_vec`?

Note that in regards to the `to_` prefix this naming as valid according
to convention because the `Script` type is borrowed and `to_vec` copies
the underlying bytes.
2024-11-01 07:09:53 +11:00
Tobin C. Harding 98383a0fbe
Introduce Transaction extension traits
WARNING: This is not like all the other extension traits.

Because of the use of generics on various `Transaction` methods it is
not easily possible to use the `define_extension_trait` macro.

Manually create the extension traits (public and private) for the
`Transaction` type. This is quite ugly but c'est la vie

(Includes two in the `transaction` module and one in the
`consensus_validation` module.)
2024-10-30 12:28:52 +11:00
Tobin C. Harding c1eccfde25
Move Witness to primitives
Move the `Witness` over to `primitives` leaving behind any method that
takes or returns a `Script` or a signature.

Includes addition of a feature gate to unit test.
2024-10-18 14:02:03 +11:00
ChrisCho-H 3565f70df9 feat: replace ENABLE_RBF_NO_LOCKTIME with ENABLE_LOCKTIME_AND_RBF 2024-10-12 12:42:43 +09:00
Tobin C. Harding 2e4179ed0f
Run the formatter
Run `just fmt`, no other manual changes.
2024-10-10 10:39:53 +11:00