Commit Graph

71 Commits

Author SHA1 Message Date
Tobin C. Harding 7819e50055
Move Block to primitives
On the way re-design the API by doing:

- Introduce `Checked` and `Unchecked` tags
- Rename the `txdata` field to `transactions`
- Make the `Block` fields private
- Add getters for `header` and `transactions` fields
- Move the various `compute_` methods to be free standing functions
- Make the `check_` functions private
- Introduce extension traits
2024-11-15 07:16:21 +11: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 a6b7ab32a8
Move impl_array_newtype to internal_macros
The current feature gating is wrong, this bug is unreleased because it
was introduced #2585.

The `impl_array_newtype` macro is only used in the `bitcoin` crate, it
does not need to be in `internals`. Also, other crates have an `alloc`
feature which `bitcoin` does not have so if we ever need it in other
places we'll need a duplicate with the correct feature gating anyways.

Move the macro to `bitcoin::internal_macros` and remove the incorrect
`alloc` feature gating.
2024-10-31 14:15:41 +11:00
Tobin C. Harding 33566ac58c
Split encode::Error into two parts
The `consensus::encode::Error` contains an IO error but reading from a
buffer only ever errors for EOF. We converted all instances of EOF to
`MissingData` already so now we can split the IO error apart from the
actual encoding errors variants.
2024-10-22 11:58:43 +11:00
Tobin C. Harding efd7f9f06c
Add error constructor parse_failed_error
The `encode::Error::ParseFailed` variant holds an inner string, this is
suboptimal.

In an effort to patch the `encode::Error` while mimizing the diffs
required add a helper function that creates the variant. The benefit is
that later patches that effect this variant will only need to update the
constructor function and not every call site.

Internal change only.
2024-10-22 11:47:34 +11:00
merge-script 03715872cd
Merge rust-bitcoin/rust-bitcoin#3432: fmt: Use style_edition = 2021
323e706113 Add rustfmt config option style_edition (Tobin C. Harding)
2e4179ed0f Run the formatter (Tobin C. Harding)
2c40b4f4ec Configure formmater to skip read_compact_size (Tobin C. Harding)

Pull request description:

  `rustfmt` is emitting:

   Warning: the `version` option is deprecated. Use `style_edition` instead.

  As suggested add a config option and set it to 2021.

  - Patch 1: Manually configure rustfmt to skip some code
  - Patch 2: Run the formmater with current configuration
  - Patch 3: Add the new config option (remove old one), introduces no new formatting requirements

ACKs for top commit:
  apoelstra:
    ACK 323e706113 successfully ran local tests

Tree-SHA512: 7f80cc89f86d2d50936e51704344955fa00532424c29c0ee3fae1a6836e24030f909b770d28da13e1c5efde3d49ad7d52c6d909d120fb09c33abf1755f62cd38
2024-10-11 12:48:50 +00:00
Tobin C. Harding 2e4179ed0f
Run the formatter
Run `just fmt`, no other manual changes.
2024-10-10 10:39:53 +11:00
Tobin C. Harding 3b7ba4f977
Remove the SliceIndex implementation from hash types
If folk really want to index into a hash they can us `as_byte_array`
then index that.

Includes a bump to the version number of `hashes` to `v0.15.0` - this
is because otherwise `secp` won't build since we are breaking an API
that is used in the current release of secp.

Fix: #3115
2024-10-02 10:18:45 +10:00
merge-script 12e4671810
Merge rust-bitcoin/rust-bitcoin#3388: Move `OutPoint` to `primitives`
da0795e590 primitives: Use doc links for OutPoint (Tobin C. Harding)
b079cbafee Move OutPoint to primitives (Tobin C. Harding)
f5c46cd411 Introduce OutPoint extension traits (Tobin C. Harding)
7e5bd5048d Remove docs on deprecated is_null function (Tobin C. Harding)
97b20a2316 Add additional impl block to OutPoint (Tobin C. Harding)

Pull request description:

  Just the minimal move of `OutPoint` to `primitives`.

  The last patch closes #3347

ACKs for top commit:
  apoelstra:
    ACK da0795e590 successfully ran local tests

Tree-SHA512: dced5a6d6bc6af0ce8b4ae4e52c04b45c85eb77a24bb25762ba8ab7deeab1e6b392cc4b258bb14218e8a2af999715dfed45ba94599cb16963a843995a7475917
2024-09-30 21:32:14 +00:00
merge-script 0b5e0bac31
Merge rust-bitcoin/rust-bitcoin#3401: Move the `block` hash types over to `primitives`
2d8c613340 Move the block hash types to primitives (Tobin C. Harding)
6b9429ac7b Remove BlockHash::all_zeros (Tobin C. Harding)
20d8dbd586 Add missing line of whitespace (Tobin C. Harding)

Pull request description:

  As an initial step in moving the `block` module, just move over the hash types `BlockHash` and `WitnessCommitment`.

  Patch 2 introduces an associated const `BlockHash::GENESIS_PREV_BLOCKHASH` and removes `all_zeros`.

ACKs for top commit:
  apoelstra:
    ACK 2d8c613340 successfully ran local tests

Tree-SHA512: 64aa0ae81e1c8ab1b5d4cd8cd28e6ef04ed01bf79175dc5b1fd607a6f0967e06b0aaf4c10ad368e2b327edcad3705187b6643d5ca8647716319424f19a838ba1
2024-09-30 19:40:15 +00:00
Tobin C. Harding f5c46cd411
Introduce OutPoint extension traits
In preparation for moving the `OutPoint` over to `primitives` add an
extension trait to hold everything that will stay behind.
2024-09-27 12:42:19 +10:00
Tobin C. Harding 6b9429ac7b
Remove BlockHash::all_zeros
Recently we removed the `all_zeros` function from `OutPoint` in favour
of a more meaningfully named associated const. We can do the same for
`BlockHash`, the all zeros has is used for the previous blockhash of the
genesis block, add a const named as such.

In test code where we use the `all_zeros` function, just use the more
explicit form `from_byte_array([0; 32])`.
2024-09-25 06:58:14 +10:00
Steven Roose 18d8b0e469
Replace VarInt type with ReadExt and WriteExt functions
At some stage we named the compact encoding `VarInt` (which makes sense
because the compact size encoding is a variable length integer encoding).
However it turns out the term "varint" is used in Core for a different
encoding so this may lead to confusion.

While we fix this naming thing observe also that the `VarInt` type is
unnecessarily complicated, all we need to be able to do is encode and
decode integers in compact form as specified by Core. We can do this
simply by extending our `WriteExt` and `ReadExt` traits.

Add `emit_compact_size` and `read_compact_size` to emit and read compact
endcodings respectively.

Includes addition of `internals::compact_size::encoded_size_const`.

Patch originally written by Steven, Tobin cherry-picked and did a bunch
of impovements after the varint vs compact_size thing (#1016).

ref: https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer

Co-developed-by: Tobin C. Harding <me@tobin.cc>
2024-09-25 06:56:09 +10:00
Tobin C. Harding b6371b5801
Fix clippy rustdocs warnings
A new nightly version (`nightly-2024-08-28`) introduces a few warnings
because of our rustdocs. These are valid warnings and should be fixed,
thanks `clippy` team.

(The `bip152` change is a bit sloppy, open to suggestions.)
2024-08-30 05:47:31 +10:00
leichak 2756b7fd7a Removed unneeded usages of vec! macro 2024-08-19 10:12:09 +02:00
Tobin C. Harding 579b76b7cb
Introduce ToU64 conversion trait
We already explicitly do not support 16 bit machines.

Also, because Rust supports `u182`s one cannot infallibly convert from a
`usize` to a `u64`. This is unergonomic and results in a ton of casts.

We can instead limit our code to running only on machines where `usize`
is less that or equal to 64 bits then the infallible conversion is
possible.

Since 128 bit machines are not a thing yet this does not in reality
introduce any limitations on the library.

Add a "private" trait to the `internals` crate to do infallible
conversion to a `u64` from `usize`.

Implement it for all unsigned integers smaller than `u64` as well so
we have the option to use the trait instead of `u32::from(foo)`.
2024-08-08 15:32:40 +10:00
Jamil Lambert, PhD 2169b75bba Use lower case error messages
Error messages should start with a lower case character unless it is a
proper noun.

This has been changed everywhere.
2024-07-15 09:25:08 +01:00
Tobin C. Harding 40bee24de7
Run the formatter
I don't want to wait for the bot, just run the formatter now.

No manual changes.
2024-07-11 11:21:53 +10:00
merge-script 5ad78ccc6b
Merge rust-bitcoin/rust-bitcoin#2987: Add `TxIdentifier` trait
a738754f67 Add TxIdentifier trait (Tobin C. Harding)

Pull request description:

  Add a new trait `TxIdentifier` that abstracts over the `Txid` and `Wtxid` types. We make `AsRef` a super trait so that the new trait needs no methods.

  Seal the trait so consumers of the library cannot implement it.

  Use the new trait in:

  - the `bip152` module to tighten up the `with_siphash_keys` function
  - as a trait bound on the `Leaf` associated type in the `MerkleNode` trait

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

Tree-SHA512: a7bda26a4a5107f96b24ea3c163286a7ab21a817bdec3434b3ab27d78e99c0548a7362a2271d362b89038c80d9251767c0d62e1df702ef57d9edaf141ab55cd6
2024-07-10 18:28:31 +00:00
Tobin C. Harding a738754f67
Add TxIdentifier trait
Add a new trait `TxIdentifier` that abstracts over the `Txid` and
`Wtxid` types. We make `AsRef` a super trait so that the new trait needs
no methods.

Seal the trait so consumers of the library cannot implement it.

Use the new trait in:

- the `bip152` module to tighten up the `with_siphash_keys` function
- as a trait bound on the `Leaf` associated type in the `MerkleNode` trait
2024-07-09 12:28:03 +10:00
Bruno Garcia 837f466f72 bip152: check if indexes do not overflow 2024-07-05 17:44:54 -03:00
Jamil Lambert, PhD d099b9c195 Remove wildcard from prelude import
Wildcards have been replaced with what is actually used.

In a couple of cases an additional use statement was added to the test
module to import `DisplayHex` which is only used in test, but
previously imported with the wildcard at the top.
2024-06-28 08:02:43 +01:00
Andrew Poelstra 8c4899f2cc
bitcoin: remove all direct use of hashing/engines in unit tests
This is a continuation of the previous commit, but separated to make
review a little easier. This one replaces test vectors that were
previously computed by hashing garbage into Txids and various other hash
types with new test vectors which are directly-computed garbage
converted to hashes with from_byte_array.

In one case (src/hash_types.rs) this results in changing a bunch of
fixed test vectors. This is okay; this test is supposed to check the
direction of string serialization, which is unaffected by this commit
(or any commit in this PR). The existing test vectors, because they hash
the empty string, result in different bytes depending on the underlying
hash algo (sha256, sha256d, sha256t, etc). The new ones just use the
same fixed test vector for all of them.

This commit also updates a doctest in crypto/sighash.rs which
demonstrates how to manually feed sighash data into a hash engine and
correctly handle the sighash single bug. Because you can no longer
directly get a sighash object from an engine, this particular example
should maybe be rewritten to just encode to a Vec rather than a hash
engine, explaining that maybe you'd do this when implementing a HWW, to
verify the exact data being hashed. Or something.

Unrelatedly, you can check that there are no API changes in this commit
or the last several. The next commit will remove GeneralHash impls and
that's when you'll see changes.
2024-06-24 13:58:03 +00:00
Tobin C. Harding a42bcdc22e
Remove usage of blockdata from paths
the `blockdata` directory is code organisation thing, all the
types/modules are re-exported from other places. In preparation for, and
to make easier, the `primitives` crate smashing work - remove all
explicit usage of `blockdata`.

Note that the few instances remain as they seem required e.g.,

  `pub(in crate::blockdata::script)`

Refactor only, no logic changes.
2024-06-20 12:00:22 +10:00
Andrew Poelstra 5d8aa94069
Move merkle_tree hash types
Currently we are defining the two merkle tree hash types in the `block`
module, a better home for them is the `merkle_tree` module.

This is an API breaking change because the types were public in the
`block` module, however the change should/could be unnoticeable to users
if they use the crate level re-export - which is maintained.
2024-06-17 19:10:23 +00:00
Tobin C. Harding 6b7d02e5ae
Add inherent functions to hashes
Currently we have a trait `Hash` that is required for `Hmac`, `Hkdf`,
and other use cases. However, it is unegonomic for users who just want
to do a simple hash to have to import the trait.

Add inherent functions to all hash types including those created with
the new wrapper type macros.

This patch introduces some duplicate code but we are trying to make
progress in the hashes API re-write. We can come back and de-dublicate
later.

Includes making `to_byte_array`,`from_byte_array`, `as_byte_array`, and
`all_zeros` const where easily possible.
2024-06-14 10:17:00 +10:00
Jamil Lambert, PhD bac30d3e6e fix rustdocs in bip152
Added backticks on links and changed to third person on function rustdocs
2024-06-06 16:37:12 +01:00
Jamil Lambert, PhD 4a9f74b55c fix missing fullstops in bitcoin rustdoc
Added missing fullstops to the rustdoc titles for everything on the main page of the bitcoin crate
2024-06-06 16:37:12 +01:00
Andrew Poelstra 65a5dfcd6b
Merge rust-bitcoin/rust-bitcoin#2585: Improve array macros
6ba7758b30 Improve array macros (Tobin C. Harding)

Pull request description:

  Currently we have two macros used when creating array wrapper types, one is in `internals` and the other in `bitcoin::internal_macros`. It is not immediately obvious what is what and why there are two.

  Improve the macros by:

  - Move the inherent functions to `impl_array_newtype`
  - Use `*_byte_array` for the names instead of `*_bytes`
  - Re-name the other macro to match what it now does

ACKs for top commit:
  apoelstra:
    ACK 6ba7758b30

Tree-SHA512: 36ed0fae0d28f24d29287062eb05bbc1e9e8b565f4ff41fd893503a25404ed8e185a34d75e398a8a660923ffda3b832b6157011598d5a75a5c4aafdffc74af2a
2024-05-28 16:25:59 +00:00
Andrew Poelstra 2fe579bd3f
Merge rust-bitcoin/rust-bitcoin#2772: Removed //! spare line at end of headers
802af8e417 Removed //! spare line at end of headers (jamil.lambert)

Pull request description:

  Some of the headers had a //! at the end but most didn't.  They have all been removed in bitcoin/src/ to make the files consistent

ACKs for top commit:
  apoelstra:
    ACK 802af8e417

Tree-SHA512: a1eb0dda76af68cb96352f6b31231fa5391d49e11df924065e76871f82231ec0d5751190663f142240e5d757975937387243d1fdac3684d9bdbd7e2362dbd0a7
2024-05-16 13:48:15 +00:00
jamil.lambert 802af8e417 Removed //! spare line at end of headers 2024-05-16 09:59:55 +01:00
Tobin C. Harding f3c80ea820
Use concrete type for all_zeros call
Currently we use the `Hash` trait in a bunch of places to call
`all_zeros`. We are attempting to improve the `hashes` API and this
usage is both unnecessary and also hindering that effort.

Use the concrete type (e.g. `BlockHash`) instead of calling through the
trait method.

Refactor only, no logic changes.
2024-05-16 09:01:37 +10:00
Tobin C. Harding 6ba7758b30
Improve array macros
Currently we have two macros used when creating array wrapper types,
one is in `internals` and the other in `bitcoin::internal_macros`. It
is not immediately obvious what is what and why there are two.

Improve the macros by:

- Move the inherent functions to `impl_array_newtype`
- Use `*_byte_array` for the names instead of `*_bytes` for functions
  that return arrays
- Add `as_bytes` to return a slice
- Add `to_bytes` to return a vector
- Re-name the other macro to match what it now does
2024-05-14 10:42:40 +10:00
Andrew Poelstra 5c56b69eed
Merge rust-bitcoin/rust-bitcoin#2667: Remove deprecated legacy numeric methods
051c358bcb Remove deprecated legacy numeric methods (Divyansh Gupta)

Pull request description:

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

  fix #2639

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

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

fix #2639
2024-04-07 01:51:14 +05:30
Fmt Bot a565db9fdd 2024-03-31 automated rustfmt nightly 2024-03-31 01:03:18 +00:00
Liam Aharon b9f7462958
Implement infallible for errors
Creates a new macro `impl_from_infallible`, and applies it to custom
error types in the codebase.

Closes #1222.
2024-03-08 16:48:34 +11:00
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
yancy 1d13020129 test: Add conditional check for debug_assertions
Adding debug_assertions where the test case panics allows the test suite
to run in release mode successfully.
2024-02-10 12:37:50 +01:00
yancy 9bbf79b08c Rename wtxid to compute_wtxid
Computing the wtxid is computationally expensive, so rename the method
accordingly.
2024-01-23 15:57:50 +01: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
Thabokani 80665671cd
bitcoin: fix typos 2024-01-18 14:06:23 +08:00
Tobin C. Harding 263a8b3603
Require BufRead instead of Read
Our decoding code reads bytes in very small chunks. Which is not
efficient when dealing with the OS where the cost of a context switch is
significant. People could already buffer the data but it's easy to
forget it by accident.

This change requires the new `io::BufRead` trait instead of `io::Read`
in all bounds.

Code such as `Transaction::consensus_decode(&mut File::open(foo))` will
break after this is applied, uncovering the inefficiency.

This was originally Kix's work, done before we had the `io` crate.
Changes to `bitcoin` were originally his, any new mistakes are my own.
Changes to `io` are mine.

Co-developed-by: Martin Habovstiak <martin.habovstiak@gmail.com>
2024-01-16 14:36:00 +11:00
Tobin C. Harding 3ca55fb163
Remove qualifying path from Read and Write
There is no advantage in having `io::Read` as opposed to `Read` and
importing the trait. It is surprising that we do so.

Remove `io::` path from `io::Read` and `io::Write`. Some docs keep the
path, leave them as is. Add import `use io::{Read, Write}`.

Refactor only, no logic changes.
2023-12-12 11:48:29 +11:00
Tobin C. Harding 61c02ff202
Move block hash types
We would like all the various hash types to be defined where they
rightly live instead of in the `hash_types` module.

Move the block hash types to the `block` module. While moving, add full
stops to the rustdoc of each hash.

Re-export _all four_ types from lib.rs (previously `WitnessMerkleNode`
was not re-exported).
2023-12-05 14:57:28 +11:00
Tobin C. Harding 10374af75c
Make error types uniform
On our way to v1.0.0 we are defining a standard for our error types,
this includes:

- Uses the following derives (unless not possible, usually because of `io::Error`)

  `#[derive(Debug, Clone, PartialEq, Eq)]`

- Has `non_exhaustive` unless we really know we can commit to not adding
  anything.

Furthermore, we are trying to make the codebase easy to read. Error code
is write-once-read-many (well it should be) so if we make all the error
code super uniform the users can flick to an error and quickly see what
it includes. In an effort to achieve this I have made up a style and
over recent times have change much of the error code to that new style,
this PR audits _all_ error types in the code base and enforces the
style, specifically:

- Is layed out: definition, [impl block], Display impl, error::Error impl, From impls
- `error::Error` impl matches on enum even if it returns `None` for all variants
- Display/Error impls import enum variants locally
- match uses *self and `ref e`
- error::Error variants that return `Some` come first, `None` after

Re: non_exhaustive

To make dev and review easier I have added `non_exhaustive` to _every_
error type. We can then remove it error by error as we see fit. This is
because it takes a bit of thinking to do and review where as this patch
should not take much brain power to review.
2023-10-04 15:15:52 +11:00
Tobin C. Harding 43d3306822
Use explicit error::Error impl instead of the default
In a further effort to make the code brain-dead easy to read; use an
explicit implementation of `std::error::Error` that returns `None`
instead of relying on the default trait implementation.
2023-10-04 15:15:43 +11: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 4f43965ade
Make Encodable/Decodable usage uniform
One encodes to a writer and decodes from a reader, most of the time in
the consensus `Encodable`/`Decodable` traits we use generic `R`/`W` and
variable `r`/`w` but there are other places that use other characters.

While touching these lines note also that there are a bunch of unneeded
`mut`s, I'm not sure why since usually between the compiler and the
linter `mut` is handled correctly.

Make implementations of `Encodable` and `Decodable` uniform by:
- Use R/W and r/w for trait and variable name
- Remove unneeded mut
2023-08-31 13:14:02 +10:00