Commit Graph

73 Commits

Author SHA1 Message Date
Tobin C. Harding 830c1e9cfe
Allow m prefix in derivation paths
Recently in #2451 we disallowed bip32 derivation paths with the leading
'm' variable.

There is some confusion as to what exactly the bip specifies however
Bitcoin Core RPC call `getaddressinfo` returns a derivation path with a
leading "m/". This means we need to be able to parse it irrespective of
what the bip says.

Be more liberal in what we accept as a derivation path, including both
with and without the leading 'm/'.

Leave the full investigation of the bip to a later date.

Change back some of the test strings as makes sense and include test
strings to showcase the full current behaviour.
2024-04-11 07:23:30 +10:00
Tobin C. Harding e1869340be
Upgrade secp dependency
Upgrade `rust-secp256k1` to the latest version `v0.29.0`. This removes
the duplicate deps as well.
2024-04-03 09:24:41 +11:00
Fmt Bot a565db9fdd 2024-03-31 automated rustfmt nightly 2024-03-31 01:03:18 +00:00
yu 41e8fb0863 Support signing taproot in psbt 2024-02-22 10:42:44 +08: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
josibake ccbd09d5fb
Remove unnecessary m/ prefix requirement
In BIP0032, m is used as a variable for the root extended key. It is not
meant to be used as a constant prefix when serializing paths.

Update the DerivationPath parser to no longer require the m prefix.
Remove the m prefix from the unit tests and the bip32, ecdsa-psbt,
and taproot-psbt examples.

close #2449
2024-02-07 12:17:45 +01:00
Andrew Poelstra 6bd8375959
Merge rust-bitcoin/rust-bitcoin#2402: Remove TODOs
5eb2de1660 Remove TODO about rand trait (Tobin C. Harding)
66cc007c2b p2p: Remove TODO comments (Tobin C. Harding)
0b5fb45ea0 consensus: Remove HEX_BUF_SIZE todo (Tobin C. Harding)
579668892a consensus: Remove TODO (Tobin C. Harding)
53beb9db30 Remove ancient todos in test code (Tobin C. Harding)
abe2241828 units: Remove "alloc" TODO (Tobin C. Harding)
5386ef0fd2 psbt: Delete TODO comments (Tobin C. Harding)
14c8a2232b examples: Remove TODO (Tobin C. Harding)

Pull request description:

  Done while working on #2368.  There are 5 left. Do we want to leave the MSRV ones in there?

  ```bash
  bitcoin/src/blockdata/weight.rs:66:                 // TODO replace with panic!() when MSRV = 1.57+
  bitcoin/src/consensus/serde.rs:101:    // TODO: statically prove impossible cases
  bitcoin/src/pow.rs:445:            // TODO: Use `carrying_mul` when stabilized: https://github.com/rust-lang/rust/issues/85532
  units/src/amount.rs:595:        // TODO replace whith unwrap() when available in const context.
  units/src/amount.rs:599:                // TODO replace with panic!() when MSRV = 1.57+
  ```

ACKs for top commit:
  Kixunil:
    ACK 5eb2de1660
  apoelstra:
    ACK 5eb2de1660

Tree-SHA512: 285b1711a6e6fba126e2c4159b25454c7f894122b76fde1d3d29e57b2ec0a6e90230e46ac79d70aa133da177c75d267fc5a13489b69881862649de771027ec8e
2024-01-25 15:06:28 +00:00
Andrew Poelstra 2de220ec6a
Merge rust-bitcoin/rust-bitcoin#2097: Add `Witness::p2tr_key_spend` function
6715e93e89 Add Witness::p2tr_key_spend function (Tobin C. Harding)

Pull request description:

  Add a function for creating the witness when doing a key path spend for a P2TR output.

  This mirrors what we did for P2WPKH when adding `Witness::p2wpkh`.

  Includes update to the taproot signing example to use the new constructor.

ACKs for top commit:
  Kixunil:
    ACK 6715e93e89
  apoelstra:
    ACK 6715e93e89

Tree-SHA512: aab51329e8fda471442bb9cebd6327636548dd157bb9842fe66993fcdd211bb04b2b829aa9d5962dd619f5c0b73d19644a44529c1a5958df1a6bc892147b44f5
2024-01-25 13:34:06 +00:00
Tobin C. Harding 14c8a2232b
examples: Remove TODO
Remove the todo from `sighash` and add issue:

  https://github.com/rust-bitcoin/rust-bitcoin/issues/2386
2024-01-25 16:59:55 +11:00
Andrew Poelstra cf3a7bb758
Merge rust-bitcoin/rust-bitcoin#2366: Rename `txid` to `compute_txid`
7af3a58e91 Rename ntxid to compute_ntxid (yancy)
9bbf79b08c Rename wtxid to compute_wtxid (yancy)
57a7613973 Rename txid to compute_txid (yancy)

Pull request description:

  Rename txid to compute_txid and mark txid as deprecated.

  Closes #2363

ACKs for top commit:
  Kixunil:
    ACK 7af3a58e91
  apoelstra:
    ACK 7af3a58e91
  tcharding:
    ACK 7af3a58e91

Tree-SHA512: 0d9200588cd83c42b78f0ba5e6a6aa049e8360aec8b9881cf9bfbaaad0d256e6879b494fb3c4e2b06d371b9e5dde6addcc94c67a080d16a6eed5c9bc36bc845a
2024-01-24 14:07:03 +00:00
Tobin C. Harding 6715e93e89
Add Witness::p2tr_key_spend function
Add a function for creating the witness when doing a key path spend for
a P2TR output.

This mirrors what we did for P2WPKH when adding `Witness::p2wpkh`.

Includes update to the taproot signing example to use the new constructor.
2024-01-24 15:21:31 +11:00
yancy 57a7613973 Rename txid to compute_txid
Computing the txid is computationally expensive, so rename the method
accordingly.
2024-01-23 15:57:50 +01:00
Tobin C. Harding 20a5f1f35f
Use KnowHrp instead of Network
We have a bunch of functions that take `Network` when what they really
want is something that can be converted to a `KnownHrp`.

Make `KnownHrp` public and accept `impl Into<KnownHrp>`.
2024-01-23 16:53:05 +11:00
Thabokani 80665671cd
bitcoin: fix typos 2024-01-18 14:06:23 +08:00
Tobin C. Harding 271b45299f
Improve Signature field names
Applies to both `ecdsa::Signature` and `taproot::Signature`.

Re-name the `Signature` fields with more descriptive names. The
names used were decided upon in the issue discussion.

Impove rustdocs while we are at it.

Note, the change to `sign-tx-segwit-v0` is refactor only, the diff does
not show it but we have a local variable already called `sighash_type`
that is equal to `EcdsaSighashType::All`.

Includes a function argument rename as well, just to be uniform.

Fix: #2139
2024-01-15 10:26:40 +11:00
Fmt Bot 5af7727250 2023-12-17 automated rustfmt nightly 2023-12-17 00:59:05 +00:00
Tobin C. Harding 4354f37f51
Use NetworkKind in bip32 module
BIP-32 only differentiates between mainnet and some testnet when
encoding and decoding xpubs and xprivs. As such we can use the new
`NetworkKind` type instead of `Network` throughout the `bip32` module.
2023-12-15 11:50:50 +11:00
Martin Habovstiak a92d49fe33 Implement `CompressedPublicKey`
P2WPKH requires keys to be compressed which introduces error handling
even in cases when it's statically known that a key is compressed. To
avoid it, this change introduces `CompressedPublicKey` which is similar
to `PublicKey` except it's statically known to be compressed.

This also changes relevant code to use `CompressedPublicKey` instead of
`PublicKey`.
2023-12-12 15:16:16 +01:00
Tobin C. Harding fa104aefa5
bitcoin: Add signing examples
Add two signing examples to showcase signing a simple one input two
output transaction using both segwit v0 outputs and taproot outputs.

This patch is the result of the recent rust-bitcoin TABConf workshop,
wit bug fix by Sanket, updated to use APIs from tip of master branch.

This code, depending on v0.30.0 is what is being introduced to the
cookbook at the moment.
2023-10-31 10:11:48 +11:00
Tobin C. Harding 678eee8d73
Use Message::from_digest
We have a new API function available with recent version of `secp256k1`
to create a `Message` directly from a sighash byte array.

Use `Message::from_digest(sighash.to_byte_array())` to construct
messages ready to sign.
2023-10-11 08:16:25 +11:00
Tobin C. Harding 6f30ac9d02
Upgrade the secp dependency
Upgrade the `secp256k1` dependency to the newly released `v0.28.0`.

FTR this includes two simple changes:
- Use `Message::from_digest_slice` instead of `Message::from_slice`.
- Use `secp256k1::Keypair` instead of `secp256k1::KeyPair`.
2023-10-10 10:04:31 +11:00
Vincenzo Palazzo 98513ef151
clippy: more worning fixes
error[E0308]: mismatched types
  --> bitcoin/src/psbt/raw.rs:87:24
   |
87 |               return Err(encode::Error::OversizedVectorAllocation {
   |  ________________________^
88 | |                 requested: key_byte_size as usize,
89 | |                 max: MAX_VEC_SIZE,
90 | |             });
   | |_____________^ expected enum `psbt::error::Error`, found enum `consensus::encode::Error`
   |
help: try wrapping the expression in `psbt::error::Error::ConsensusEncoding`
   |
87 ~             return Err(psbt::error::Error::ConsensusEncoding(encode::Error::OversizedVectorAllocation {
88 |                 requested: key_byte_size as usize,
89 |                 max: MAX_VEC_SIZE,
90 ~             }));
   |

----

  Compiling bitcoin v0.30.0 (/home/vincent/github/work/rust-btc/rust-bitcoin/bitcoin)
    Checking bitcoin-fuzz v0.0.1 (/home/vincent/github/work/rust-btc/rust-bitcoin/fuzz)
error: redundant clone
   --> bitcoin/examples/taproot-psbt.rs:453:77
    |
453 |             witness_utxo: { Some(TxOut { value, script_pubkey: script_pubkey.clone() }) },
    |                                                                             ^^^^^^^^ help: remove this
    |
    = note: `-D clippy::redundant-clone` implied by `-D warnings`
note: this value is dropped without further use
   --> bitcoin/examples/taproot-psbt.rs:453:64
    |
453 |             witness_utxo: { Some(TxOut { value, script_pubkey: script_pubkey.clone() }) },
    |                                                                ^^^^^^^^^^^^^
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

error: could not compile `bitcoin` due to previous error
warning: build failed, waiting for other jobs to finish...
error: redundant clone
    --> bitcoin/src/psbt/mod.rs:1095:13
     |
1095 |             .clone()
     |             ^^^^^^^^ help: remove this
     |
     = note: `-D clippy::redundant-clone` implied by `-D warnings`
note: this value is dropped without further use
    --> bitcoin/src/psbt/mod.rs:1094:17
     |
1094 |           assert!(psbt
     |  _________________^
1095 | |             .clone()
     | |____________^
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-10-07 11:40:44 +02:00
Andrew Poelstra bd9c4125cf
Merge rust-bitcoin/rust-bitcoin#2082: example: Modify `taproot-psbt.rs` to make the use of prevouts clearer.
3b60ad5567 example: Modify `taproot-psbt.rs` to make the use of prevouts clearer. (S. Santos)

Pull request description:

  The `taroot-psbt.rs` example uses only one input, and therefore the current code may not make it clear that the number of prevout items must correspond to the number of transaction inputs, since the prevout slice is built within a loop.

  This PR aims to make this clear to any user who wants to reuse the logic from the example code.

ACKs for top commit:
  tcharding:
    ACK 3b60ad5567
  apoelstra:
    ACK 3b60ad5567

Tree-SHA512: afad63782b0e8a459de6cf69712d31fdab860c0d4cf9f3a51c3d85544a067bd50f4febc10ec4046e3a37d9ca518bbf2460c2599f1569549701c07f8a267dfd05
2023-10-01 15:12:25 +00:00
S. Santos 3b60ad5567 example: Modify `taproot-psbt.rs` to make the use of prevouts clearer. 2023-09-29 20:19:32 -03:00
junderw dac627cc09
Feature: Psbt fee checks 2023-09-28 00:11:33 -07:00
Clark Moody 72a7280d7d
Merge pull request #2006 from tcharding/08-18-tx-version
Add transaction::Version data type
2023-09-23 13:13:52 -05:00
Tobin C. Harding c950ef4bbd
Add transaction::Version data type
BIP-68 activated a fair while ago (circa 2019) and since then only
transaction versions 1 and 2 have been considered standard.

Currently in our `Transaction` struct we use an `i32`, this means users
can construct a non-standard transaction if they do not first look up
what the value should be. We can help folk out here by abstracting over
the version number.

Since the version number only governs standardness elect to make the
inner `i32` public (ie., not an invariant). The aim of the type is to
make life easy not restrict what versions are used.

Add transaction::Version data type that simply provides two consts `ONE`
and `TWO`.

Add a `Default` impl on `Version` that returns `Version::TWO`.

In tests that used version 0, instead use `Version::default` because the
test obviously does not care.
2023-09-21 15:02:02 +10:00
Tobin C. Harding bc398204bf
Remove redundant segwit version from function names
A P2TR output does not need to be clarified with version 1, it is
implicit. As with p2wpkh/p2wsh and version 0.

Remove redundant version identifiers from function names, deprecating
the originals.
2023-08-31 13:23:46 +10:00
Andrew Poelstra 082bd03120
Merge rust-bitcoin/rust-bitcoin#2019: Rename xpub and xpriv types
be05f9d852 Rename xpub and xpriv types (Tobin C. Harding)

Pull request description:

  The BIP-32 extended public key and extended private key exist in the Bitcoin vernacular as xpub and xpriv. We can use these terms with no loss of clarity.

  Rename our current BIP-32 types

  - `ExtendedPubKey` to `Xpub`
  - `ExtendedPrivKey` to `Xpriv`

  This patch is a mechanical search-and-replace, followed by running the formatter, no other manual changes.

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

Tree-SHA512: 49925688783c3f37a9b92a9767a0df095323a3fa51f3d672a0b5dd1d8bca86f7facbcc33921274bc147b369de09042c4850b08c31e63f71110903435daa6c00c
2023-08-25 13:41:50 +00:00
Tobin C. Harding d9533523ac
Remove usage of ThirtyTwoByteHash
The `ThirtyTwoByteHash` trait is defined in `secp256k1` and used in
`hashes` as well as `bitcoin`. This means that we must use the same
version of `hashes` in both `bitcoin` and `secp256k1`. This makes doing
release difficult.

Remove usage of `ThirtyTwoByteHash` and use `Message::from_slice`.
Include TODO above each usage because as soon as we release the new
version of secp we can use the new `Message::from_digest`.

This is step backwards as far as type safety goes and it makes the code
more ugly as well because it uses `expect` but thems the breaks.
2023-08-23 12:21:26 +10:00
Tobin C. Harding be05f9d852
Rename xpub and xpriv types
The BIP-32 extended public key and extended private key exist in the
Bitcoin vernacular as xpub and xpriv. We can use these terms with no
loss of clarity.

Rename our current BIP-32 types

- `ExtendedPubKey` to `Xpub`
- `ExtendedPrivKey` to `Xpriv`

This patch is a mechanical search-and-replace, followed by running the
formatter, no other manual changes.
2023-08-22 13:47:35 +10:00
Tobin C. Harding 4300cf2210
Add p2wpkh and p2wsh signature hash functions
The word "segwit" refers to segwit v0 and taproot but currently we have
`segwit_signature_hash` that is version specific (segwit v0).

- Rename `segwit_encode_signing_data_to` to
  `segwit_v0_encode_signing_data_to`
- Add `p2wpkh_signature_hash` and `p2wsh_signature_hash` functions

We keep the single encode function because the error handling is better
that way.

While we are at it test the bip-143 test vectors against all the
sighash types of wrapped p2wsh.
2023-08-15 11:54:08 +10:00
Tobin C. Harding d4e8f49fc3
Move p2p::constants::Network to crate root
The `Network` type is not a p2p construct, it is more general, used
throughout the codebase to define _which_ Bitcoin network we are
operating on.
2023-08-01 16:46:59 +10:00
Tobin C. Harding d9d5a4ed4f
Move p2p::constants::ServiceFlags to p2p module
The `ServiceFlags` type is used by the p2p layer. It can live in the
`mod.rs` file of the `p2p` module. Done in preparation for removing the
`p2p::constants` module.

This is a straight code move, the `ServiceFlags` replaces the
current re-export.
2023-08-01 16:36:12 +10:00
Tobin C. Harding 1bac1fd518
Rename the network module to p2p
The `network` module deals with data types and logic related to
internetworking bitcoind nodes, this is commonly referred to as the p2p
layer.

Rename the `network` module to `p2p` and fix all the paths.
2023-08-01 16:36:12 +10:00
Andrew Poelstra 04976eddcf
Merge rust-bitcoin/rust-bitcoin#1833: Use new `hex-conservative` crate
bb8bd16302 internals: Remove hex module (Tobin C. Harding)
2268b44911 Depend on hex-conservative (Tobin C. Harding)
db50509cd3 Add usage docs to the "core2" feature (Tobin C. Harding)

Pull request description:

  Use the newly released `hex-conservative` crate, by doing the following:

  - Depend on `hex-conservative` in `bitcoin` and `hashes`
  - Re-export `hex-conservative` as `hex` from both crate roots.
  - Remove all the old hex code from `hashes`
  - Remove all the old hex code from `internals`
  - Remove the now unused `internals::prelude`
  - Fix all the import statements (makes up the bulk of the lines changes in this patch)

ACKs for top commit:
  apoelstra:
    ACK bb8bd16302
  sanket1729:
    utACK bb8bd16302

Tree-SHA512: ec83b3941cae6f32272471779f28461bb04959a3f6a126a68bbf2c748d83ff9518ff8932d9e937a6f389c10028bf3eb58c6b6d71ea066924dd7a34faaec7a087
2023-07-27 16:27:01 +00:00
Riccardo Casatta 5c8933001c
Avoid serialize inner data in RawNetworkMessage
RawNetworkMessage keep the payload_len and its checksum in the struct, thus
is not needed to serialize the inner network message

pub in fields of both RawNetworkMessage and CheckedData are removed so that
invariant are preserved.
2023-07-26 08:34:49 +02:00
Tobin C. Harding 2268b44911
Depend on hex-conservative
We have just released the `hex-conservative` crate, we can now use it.

Do the following:

- Depend on `hex-conservative` in `bitcoin` and `hashes`
- Re-export `hex-conservative` as `hex` from both crate roots.
- Remove all the old hex code from `hashes`
- Fix all the import statements (makes up the bulk of the lines changed
  in this patch)
2023-07-21 10:59:46 +10:00
Alec Matusis fc167097aa Added examples for sighash computations
So far computed sighashes for:
 - P2WPKH
 - P2MS
 - P2SH multisig
 - P2WSH multisig.

TODOs:
  - Add P2TR script-path multisig and key-path examples
2023-06-20 02:07:21 -07:00
yancy 9f7449b572 Use from_int_btc function for const context 2023-06-13 11:32:58 +02:00
yancy d57ec019d5 Use Amount type for TxOut value field 2023-05-04 17:09:08 +02:00
Tobin C. Harding a11cf07501
Run the formatter
Various formatting issues have crept into the codebase because we do not
run the formatter in CI.

In preparation for enabling formatting checks in CI run `cargo +nightly
fmt` to fix current formatting issues. No changes other than those
create by the formatter.
2023-03-06 10:22:29 +11:00
Tobin C. Harding 42b07586ac
Improve the public API
We created the `crypto` crate as a container for cryptography modules
with the idea that it may be split out into a separate crate. There is
no reason for users of the lib to know about this module. Also, we have
two `taproot` modules, one in `crypto` and one at the crate root, this
makes for un-ergonomic usage of the lib.

Improve the public API by doing:

- Make the `crypto` module private (`pub(crate)`).
- Re-export `crypto::taproot::Signature` (and `Error`) from
  `crate::taproot`
2023-03-01 09:28:42 +11:00
Tobin C. Harding 161273b209
Re-name hash inner/byte methods
Currently we have an associated type on hash types `Inner` with
accompanying methods `into_inner`, `from_inner`, `as_inner`. Also, we
provide a way to create new wrapped hash types. The use of 'inner'
becomes ambiguous with the addition of wrapped types because the inner
could be the inner hash type or the `Inner` byte array of the inner
wrapped hash type.

In an effort to make the API more clear and uniform do the following:

- Rename `Inner` -> `Bytes`
- Rename `*_inner` -> `*_byte_array`
- Rename the inner hash to/from methods to `*_raw_hash`

Correct method prefix `into_` -> `to_` because theses methods convert
owned `Copy` types.

Add the trait Bound `Copy` to the `Bytes` type because we rely on this
trait bound for the conversion methods to be correctly named according
to convention.

Because of the dependency hole created by `secp256k1` this patch changes
the secp dependency to a git tag dependency that includes changes to the
hashes calls required so that we can get green lights on CI in this
repo.
2023-02-27 14:23:58 +11:00
Tobin C. Harding 324b6f264b
Use `into` for hash argument
Hash types can be converted into a `Message` because `Message`
implements `From` for any type that implements `ThirtyTwoByteHash`,
which hash types do.

Use `into` to convert the hash argument to a message to sign.
2023-02-27 12:00:08 +11:00
Lorenzo Maturano 673ca2d2fe changing docs and examples to use reference to slice in `derive_pub` 2023-02-21 14:34:14 -03:00
Tobin C. Harding be7b3754a9
Rename schnorr module to taproot
"schnorr" is a dirty word; the current `schnorr` module defines a
`Signature` that includes a sighash type, this sighash type is a bitcoin
specific construct related to taproot. Therefore the `Signature` is
better named `taproot::Signature`. Note also that the usage of `schnorr`
in `secp256k1` is probably justified because the
`secp256::schnorr::Signature` is just doing the crypto.

While we are at it, update docs and error messages to use "taproot"
instead of "schnorr". Also change function names and identifiers that
use "schnorr".
2023-02-20 12:58:09 +11:00
Tobin C. Harding 9f39e872bc
Rename SchnorrSighashType to TapSighashType
As we did for `SchnorrSighash`, rename the `SchnorrSighashType` to
`TapSighashType`.
2023-02-20 12:58:09 +11:00
Tobin C. Harding 98130f49f1
Rename TapSighashHash to TapSighash
The TapSighash is the taproot sighash, no need to append `Hash` to the
identifier.
2023-02-20 12:58:08 +11:00
Tobin C. Harding 7e4da3c0ab
Move taproot keys to the keys module
We have a keys module, taproot keys should live in there.
2023-02-20 12:58:05 +11:00