70cf4515db Add `Weight` and `FeeRate` newtypes (Martin Habovstiak)
Pull request description:
Use of general-purpose integers is often error-prone and annoying. We're working towards improving it by introducing newtypes.
This adds newtypes for weight and fee rate to make fee computation easier and more readable. Note however that this dosn't change the type for individual parts of the transaction since computing the total weight is not as simple as summing them up and we want to avoid such confusion.
Part of #630
Replaces #1607 (I want to get this in quickly and don't want to be blocked on DanGould's availability.)
ACKs for top commit:
apoelstra:
ACK 70cf4515db
tcharding:
ACK 70cf4515db
Tree-SHA512: ab9cc9f554a52ab0109ff23565b3e2cb2d3f609b557457b4afd8763e3e1b418aecbb3d22733e33304e858ecf900904a1af6e6fdc16dc21483b9ef84f56f103b2
a9108d3939 Refactor script module (Tobin C. Harding)
Pull request description:
The `script` module is large and unwieldy.
Refactor the `script` module, splitting it up into a tree of modules. Here are a few of the changes and their stated benefits
- Split the two script types out into separate files: Readers of the methods can then tell immediately from the file name which type they are reading.
- Put all the impls for the two script types together: Makes parsing the API easier because one can more quickly see which traits are implemented on what i.e., all the `AsRef` imlps are grouped together.
- Put the impls for the two script types in order, first `Script` then `ScriptBuf`: Makes it easier for us to see if we missed something.
- Put the `Builder` and `Instruction` (and associated) types in their own modules: Some devs find long files hard to navigate, so far there hasn't been too much push back against short files.
- Put tests in a separate file: This idea was recently discussed.
This is only moving code and fixing import statements etc. No other changes to the code.
## Note to reviewers
This PR is impossible to review from the diff because it moves so much code. Perhaps better to look at the resulting `src/blockdata/script/` directory and see if you like it.
#### Motivation
While adding script tagging I was having difficulty navigating the script module.
ACKs for top commit:
apoelstra:
ACK a9108d3939
Kixunil:
ACK a9108d3939
Tree-SHA512: 19123c8cfbdce6c42b322fa75a74073a0114b0ed21bd06ca5727981b3573b74cf05075723b774b92ae2b497e20644fca6e2fac14e30cc44f2802dde5aa567f66
Use of general-purpose integers is often error-prone and annoying. We're
working towards improving it by introducing newtypes.
This adds newtypes for weight and fee rate to make fee computation
easier and more readable. Note however that this dosn't change the type
for individual parts of the transaction since computing the total weight
is not as simple as summing them up and we want to avoid such confusion.
Part of #630
In `bitcoin` when we use the `core2` dependency we always need the
"alloc" feature. Enabling "alloc" when enabling "core2" in the "no-std"
feature is confusing because it makes it seem that we don't always need
it.
Set usage of the "alloc" feature of `core2` in the `features` list.
`core2` is for Read/Write, nothing to do with allocation and we do not
use the "alloc" feature of `core2` in `hashes`.
Fix core2 dependency/features by doing:
- Explicitly enable "bitcoin_hashes/core2" in `bitcoin`.
- Do not enable "core2/alloc" in `hashes`
Improve all manifest package sections by doing:
- Order the list of options uniformly
- Remove unnecessary homepage option (currently same as repo)
- Add categories section
We can check which files are included in the packaged release with
`cargo package --list `.
Add an `exclude` section to each manifest that excludes `tests/` and
`contrib/`. Not all crates have a `tests/` directory yet but they should
so add the exclude anyway to future proof the crates.
32d2d62e0f Rename from_slice methods to decode (Tobin C. Harding)
Pull request description:
The `TaprootMerkleBranch` and `ControlBlock` both have methods on them called `from_slice` but these methods do more that just basic copy from a slice. `decode` is a more descriptive name.
Deprecate the `from_slice` methods and implement `decode`, on other changes to the logic.
cc sanket1729
ACKs for top commit:
apoelstra:
ACK 32d2d62e0f
Kixunil:
ACK 32d2d62e0f
Tree-SHA512: e8c089545411a214ef9393f65d3990be46983000bd045182cc27dd70b62273bf48ac97adaf89d1e7fc807c72964a01eef176c7685684e8f87a01c219746d6d3d
55d17f2c18 Instruct devs to use nightly for embedded (Tobin C. Harding)
Pull request description:
The embedded test crate requires usage of the nightly toolchain, fix the docs to show this.
ACKs for top commit:
apoelstra:
ACK 55d17f2c18
Kixunil:
ACK 55d17f2c18
Tree-SHA512: 5d3d611ff4331d8475f77d260ebaa3da3ae71960b709eb4603056d7034885306b8bcc39be488f3391697d47a1074a695979fb50b6cb31af414f873da8e82bdbd
86f372774b Add '_ back into the BitStreamWriter (Tobin C. Harding)
Pull request description:
Recently we merged `commit 53d4fe66b57c255086def2b5e47afaddee776b75` to fix CI even though a better approach is to use `'_` because it assists reading the code (shows that the bit stream writer is not writing from a reference since its writing a `Copy` type `n`).
Add back in the `'_` (I forget what its called).
ACKs for top commit:
apoelstra:
ACK 86f372774b
Kixunil:
ACK 86f372774b
Tree-SHA512: 2a9989164562dbe7bf133e3aeb090fbff7831bfeefb0ac8431e75b17d57184c4d60ac206578c6ebbcff903a3832502a162027ed9f37e5ed87e42a6bf61efa594
The `script` module is large and unwieldy.
Refactor the `script` module, splitting it up into a tree of modules.
Here are a few of the changes and their stated benefits
- Split the two script types out into separate files: Readers of the
methods can then tell immediately from the file name which type they are
reading.
- Put all the impls for the two script types together: Makes parsing the
API easier because one can more quickly see which traits are implemented
on what i.e., all the `AsRef` imlps are grouped together.
- Put the impls for the two script types in order, first `Script` then
`ScriptBuf`: Makes it easier for us to see if we missed something.
- Put the `Builder` and `Instruction` (and associated) types in their
own modules: Some devs find long files hard to navigate, so far there
hasn't been too much push back against short files.
- Put tests in a separate file: This idea was recently discussed.
This is only moving code and fixing import statements etc. No other
changes to the code.
The `TaprootMerkleBranch` and `ControlBlock` both have methods on them
called `from_slice` but these methods do more that just basic copy from
a slice. `decode` is a more descriptive name.
Deprecate the `from_slice` methods and implement `decode`, on other
changes to the logic.
75b266a129 Improve `sighash` module documentation (Martin Habovstiak)
Pull request description:
"Sighash" is a technical term that newbies in Bitcoin may not know and could get lost when trying to find how to sign a transaction. This change attempts to make it more obvious that this module is needed for signing.
Closes#1463
ACKs for top commit:
tcharding:
ACK 75b266a129
apoelstra:
ACK 75b266a129
Tree-SHA512: 7157566c1639c63ce0fba2832e8e5e846e689d89e24077ed7769b721c5db4613cd7fd8d91464992eb78de74b42912ca877e7182a9c3c9c8848bf94d89767b8cc
b3188bbac3 Add `Transaction` accessors to `SighashCache` (Martin Habovstiak)
7c6854fe02 Use `Borrow` instead of `Deref` in `SighashCache` (Martin Habovstiak)
Pull request description:
This changes the bound from `Deref<Target = Transaction>` to `Borrow<Transaction>` (with respective `mut` changes) and adds accessors.
Closes#1423 (PSBT stuff will be separate issue).
ACKs for top commit:
tcharding:
ACK b3188bbac3
apoelstra:
ACK b3188bbac3
Tree-SHA512: 9db2c5890b26e9eefd483d697b42e84b1d7d3b8676fc39b4f39075c149e12697aa538828a757f9187578a958d72a592bb913f8f5788c93feb273db5370979d99
118a593c89 Implement from arrays for TaprootMerkleBranch (Tobin C. Harding)
Pull request description:
The `TaprootMerkleBranch` contains a vector of `TapNodeHash`s, as such it can trivially be constructed from an array of the same type.
Implement `From` for all array sizes 1 - 128 inclusive.
Fix: #1469
ACKs for top commit:
Kixunil:
ACK 118a593c89
apoelstra:
ACK 118a593c89
Tree-SHA512: dd497abd9143ea8b43485133beaccac9049fb915a95a3422d41c1f99961b59ec95df93efe759aa02f62ba1cf3e1afc4597671f1202ff0fa78eeee8b305d21305
The `TaprootMerkleBranch` contains a vector of `TapNodeHash`s, as such
it can trivially be constructed from an array of the same type.
Implement `From` for all array sizes 1 - 128 inclusive.
"Sighash" is a technical term that newbies in Bitcoin may not know and
could get lost when trying to find how to sign a transaction. This
change attempts to make it more obvious that this module is needed for
signing.
Closes#1463
277e8e96bd Add KeyPair import to rustdoc example (Tobin C. Harding)
Pull request description:
Recently, and bizarrely, a PR merged that broke `cargo test --doc`.
Add an import for `KeyPair` to the `schnorr` rustdoc example.
ACKs for top commit:
apoelstra:
ACK 277e8e96bd
Kixunil:
ACK 277e8e96bd
Tree-SHA512: ad214b668827b35848cc7b260cbd2104a916a82a5a6d242bdc498c62edc9a0e864f4bdb4abcade42924dbaf951223ae80feacbe68d8a4ccb4562d8ead50b23a9
bb612fdafa Set rustv_1_53 in build script (Tobin C. Harding)
Pull request description:
The rust version is supposed to be set by the build script so that users automagically get features matching the toolchain in use. Currently we have a feature in the manifest for `rustv_1_53` instead setting a compiler conditional configuration option in the build script. This causes `cargo +1.41.1 --all-features check` to fail.
## Note
I don't see `rustv_1_46` used anywhere, do we need that still?
ACKs for top commit:
apoelstra:
ACK bb612fdafa
Kixunil:
ACK bb612fdafa
Tree-SHA512: f74195d4ee5a5bc5f209e99d30789df3552cef10aee5ea8b61a5a701b753999c34d04be9fe0321ccee7a8ec14fa5a05e0b454b9dc5f8deddd7b5b8d4f3d7e744
It may be useful to access the transaction stored in `SighashCache`
during signing or afterwards, especially when the transaction is stored
without indirection (to enable long-lived storage).
This change adds the appropriate accessors.
The requirement for a type dereferencing to `Transaction` prevented
storing the cache in long-lived data without resorting to silly
wrappers. Since `Borrow` is implemented both for `T` and for smart
pointers it's a more flexible bound which this change implements.
While this is technically breaking, all usual non-generic code will
continue to work beause smart pointers generally have `Borrow`
implemented.
Currently we use a wildcard to export all the hash types in
`hash_types`. We are moving to a world were we only export
normal/standard types from the crate root.
Remove the reexport of the following hash types:
- `FilterHash`
- `FilterHeader`
- `TxMerkleNode`
- `WitnessCommitment`
- `WitnessMerkleNode`
- `XpubIdentifier`
- `Sighash`
Fix: #1541
f0e4e38844 Add newline in rustdoc (Tobin C. Harding)
Pull request description:
Docs created with the `sha256t_hash_newtype` macro are missing a newline between the doc heading and doc main section.
Note that the strings used span multiple lines and therefor the subsequent lines must be aligned with the start of the line (not indented).
Fix: #1540
ACKs for top commit:
Kixunil:
ACK f0e4e38844
apoelstra:
ACK f0e4e38844
Tree-SHA512: 240c68864da63688c400498903d5cc345bee224dcd3235df0127dcf391c66ee08c487d31fe59f890009c674574810b689d9a53628d07d8cdd46b79bc0ac3eb2b
Docs created with the `sha256t_hash_newtype` macro are missing a newline
between the doc heading and doc main section.
Note that the strings used span multiple lines and therefor the
subsequent lines must be aligned with the start of the line (not
indented).
Fix: #1540
The rust version is supposed to be set by the build script so that users
automagically get features matching the toolchain in use. Currently we
have a feature in the manifest for `rustv_1_53` instead setting a
compiler conditional configuration option in the build script. This
causes `cargo +1.41.1 --all-features check` to fail.
32ca6cc320 Remove hex_from_slice and display Sighash forwards (Tobin C. Harding)
a308e1e2ea Remove FromHex for all types except Vec and array (Tobin C. Harding)
3e70c01826 Manually format a bunch of vecs (Tobin C. Harding)
83e1c40c4d Remove script:: prefix from unambiguous types (Tobin C. Harding)
5ab5c264d2 Use fully qualified path in macro (Tobin C. Harding)
7e85452cd9 hashes: Implement std::error::Error (Tobin C. Harding)
5e3abc5e11 Fix feature gating on unit tests (Tobin C. Harding)
3344cf6be2 Favour $reverse instead of $reversed (Tobin C. Harding)
Pull request description:
This work started out, as the branch name suggests, as an effort to use the `hex_lit` crate. But once I got to this stage it seems that the `hex!` macro we have provides different, useful, functionality than the `hex_lit::hex!` macro (it allows usage with non-consts). So I'm unsure if we want to remove it now.
- Patches 1 - 6 are preparatory clean ups
- Patch 7 reduces usage of `FromHex`, please see git log for full description
- Patch 8 removes `hex_from_slice` and fixes a bug in how we display `Sighash`
ACKs for top commit:
apoelstra:
ACK 32ca6cc320
Kixunil:
ACK 32ca6cc320
Tree-SHA512: 11b45b39ec2fc0f837d7395b5fb86de7cc44641fd51cf7e93394a635e6a8fb1c7ac441a6070d5516dae60e084c04cc6e8b605a5167093f964679e445ef60c271
facaefc49c Add conversions for TweakedKeyPair -> TweakedPublicKey (Tobin C. Harding)
2407f241e4 Remove sep256k1 path from Parity (Tobin C. Harding)
Pull request description:
It is trivially possible to get `TweakedPublicKey` from a `TweakedKeyPair`, add conversion methods for doing so.
Patch 1 is preparatory cleanup. Please note `From` is not implemented because the conversion returns the `Parity` also.
Fix: #1452
ACKs for top commit:
apoelstra:
ACK facaefc49c
Kixunil:
ACK facaefc49c
Tree-SHA512: 597026c481fe2622a625cbeb381cac345af6f49f4a115418b69817345fc3c2140bbdbc5208eae1149d7d171f94c776365d302ffe1f9c01d944e738807db28a89
`Sighash` should be displayed forwards according to BIP143. Currently we
are displaying it backwards (as we do for double SHA256). This is
working because parse using `Vec::from_hex`.
We have the means to parse hex strings directly for hashes, we no longer
need `hex_from_slice`.
BIP143 test vectors display double SHA256 forwards but we display
backwards, this is acceptable because there is no fixed display in the
ecosystem for double SHA256 hashes. In order to overcome this we parse
test vector hex strings with into `Vec` when needed.
Remove `FromHex` from hash and script types
- Remove the `FromHex` implementation from hash types and `ScriptBuf`
- Remove the `FromStr` implementation from `ScriptBuf` because it does not
roundtrip with `Display`.
- Implement a method `from_hex` on `ScriptBuf`.
- Implement `FromStr` on hash types using a fixed size array.
This leaves `FromHex` implementations only on `Vec` and fixed size arrays.
In preparation for modifying some unit test data structures, manually
format the code so it is uniform.
Move elements added to a vec with `vec!` onto a new line so they all
line up and one can better see what fields go where.
Refactor only, no logic changes.
ed6f6d11dd Implement fmt traits for ScriptBuf (Tobin C. Harding)
Pull request description:
We can improve ergonomics of the `script` module by implementing the `fmt` traits on `ScriptBuf`, trivial because we can call through to the `Script` implementations.
Fix: #1585
ACKs for top commit:
Kixunil:
ACK ed6f6d11dd
apoelstra:
ACK ed6f6d11dd
Tree-SHA512: 878a1522af4ed1e10d1d8d60d150e6571008c008b5e5c662c67462f9e09075b4f1fe4e399ed50e98cd7253b6815937c6732cd1ce02b74a5be017d5b8fcdbbd2f
We can improve ergonomics of the `script` module by implementing the
`fmt` traits on `ScriptBuf`, trivial because we can call through to the
`Script` implementations.
The `max_value` and `min_value` functions only exist to be
compatible/uniform with Rust 1.41.1 they will never change and they just
return a constant value. They can therefore be made const functions.
Recently we merged `commit 53d4fe66b57c255086def2b5e47afaddee776b75` to
fix CI even though a better approach is to use `'_` because it assists
reading the code (shows that the bit stream writer is not writing from a
reference since its writing a `Copy` type `n`).
Add back in the `'_` (I forget what its called).
877f9af364 Add new hex parse error variant (Tobin C. Harding)
Pull request description:
Recently we used an error type that holds only one expected hex string length when parsing but for `PublicKey`s we have two (66 and 130). Add a new error variant to express the error. Requires adding a variant to `bip32` for the same thing.
Fix: #1281
ACKs for top commit:
Kixunil:
ACK 877f9af364
apoelstra:
ACK 877f9af364
Tree-SHA512: c1ca493ee30418bd82bc326b35c18731260e4217c371f37301a73c64f9a6631163801acc217c6c2c7b14f632a2ad5043174266c1b4fdce127698e68ab8494f20
3c0598b399 Add standard constants to lock times (Tobin C. Harding)
Pull request description:
Some of the lock time structs (`Height`, `Time` ect.) are missing standard constants for min, max ect.
Add standard constants taking into consideration the various locktime corner cases.
Add `max_value` and `min_value` to be consistent with Rust 1.41.1 (incl. `Sequence`).
Fix: #1451
This PR is not complex in itself but **locktimes are notoriously complex, please wait for 3 acks before merging** - and ack'ing makes no guarantee that reviewer got all corner cases :)
There is no rush on this one, apoelstra, Kixunil, sanket1729 please just review when your brain is fresh.
ACKs for top commit:
apoelstra:
ACK 3c0598b399
Kixunil:
ACK 3c0598b399
Tree-SHA512: aa3d112db83b4785edb0a7a517cc335ded59f5967eb39b8979a6d68f9bba4644a27e5ca400fcabf368a1f8c0eecdef0b87b1011933ac7fd96b467b8501533203
Recently we used an error type that holds only one expected hex string
length when parsing but for `PublicKey`s we have two (66 and 130). Add a
new error variant to express the error. Requires adding a variant to
`bip32` for the same thing.
Fix: #1281
Implement `AsRef<[u8; X]>` for hash types including wrapped hash types.
Doing so means at times the compiler can no longer infer the type because we have
`AsRef<[u8]` implemented also but we can use `into_inner` and `as_inner`
to get the inner array if needed.
Add an implementation of `From<Address> for ScriptBuf` that calls
through to `address.script_pubkey` (which calls
`address.payload.script_pubkey()`).
Fix: #1457
Some of the lock time structs (`Height`, `Time` ect.) are missing
standard constants for min, max ect.
Add standard constants taking into consideration the various locktime
corner cases.
Add `max_value` and `min_value` to be consistent with Rust 1.41.1 (incl.
`Sequence`).
Fix: #1451
a762a89b48 Add documentation to Sequence::is_final (Tobin C. Harding)
b1490a26ea Move enables_absolute_lock_time method (Tobin C. Harding)
Pull request description:
The term "final" is an archaic Bitcoin term however it is well used, it exists in Bitcoin Core code as well as in various bips. To help folks new to Bitcoin add documentation to the `is_final` method including historical notes.
Note, this does _not_ deprecate `is_final` - while writing the notes I found the term "final" in enough official places that I think its fair game to keep the term, some things people just have to learn, we can definitely help with that learning though.
Fix: #1198
ACKs for top commit:
Kixunil:
ACK a762a89b48
apoelstra:
ACK a762a89b48
Tree-SHA512: 895fbdce90223d90c0a68fb1e3d6b7aada4a3606d1294ea4df1f4194681a79d970b0434e7bb078f6d5cbf413b3550e72560d6d5cf811a5a959adf53f7f778ab2
8c0e5213d3 Delegate debug for ScriptBuf to Script (Tobin C. Harding)
Pull request description:
Currently the derived implementation of `Debug` for `ScriptBuf` prints the inner vector of u8s as integers, this is ugly and hard to read. The `Script` implementation of `Debug` prints the script opcodes and data as hex, we can just delegate to it.
With this applied we get debug output of form:
Script(OP_DUP OP_HASH160 OP_PUSHBYTES_20 3bde42dbee7e4dbe6a21b2d50ce2f0167faa8159 OP_EQUALVERIFY OP_CHECKSIG)
Fix: #1516
ACKs for top commit:
Kixunil:
ACK 8c0e5213d3
apoelstra:
ACK 8c0e5213d3
Tree-SHA512: ca07d9fb191f4e0379cbd96b2944e6881094a8334d39b97209b6bf452a3c15d4aede53b9c88176b9b7667b7a539d47897940bc561dc9f8cd83ce1990a08047e1
1d3d5a9c5b Take Into<secp256k1::PublicKey> in PublicKey constructors (Tobin C. Harding)
b13a76407b keys: Clean up test imports (Tobin C. Harding)
Pull request description:
We can make the API more ergonomic by taking a generic argument that implements `Into<secp256k1::PublicKey>` in the `bitcoin::PublicKey` constructors.
The only thing than this is useful for is passing in `KeyPair` and the `From` implementation already exists. Add a unit test to verify.
Fix: #1453
## Note
As per the discussion in #1453 I checked secp and bitcoin for all keys that can be converted using `From` and it turns out its only `KeyPair` which already has `From` impls - good rust-bitcoin devs :)
ACKs for top commit:
Kixunil:
ACK 1d3d5a9c5b
apoelstra:
ACK 1d3d5a9c5b
Tree-SHA512: b5e5272561de15cdcfb15913aa5d42ddc96bf2fd5835068a5a9aa0274074ffa698ec9e81707f102b7d1b244f1abd0fdbd0eb4b6b505c84c3d5719dcb01d46efb
49e8b8da32 Use write_all for sighash encoding (Tobin C. Harding)
Pull request description:
From BIP143:
> If sighash type is SINGLE and the input index is smaller than the number of outputs, hashOutputs is the double SHA256 of the output amount with scriptPubKey of the same index as the input;
Currently we are using a `Sighash` which wraps double sha256 so while technically correct this means we are relying on `Sighash` to implement `Encodable`. We can remove this requirement by directly using the `sha256d::Hash` type to hash the outputs data.
Fix: #1549
ACKs for top commit:
Kixunil:
ACK 49e8b8da32
apoelstra:
ACK 49e8b8da32
Tree-SHA512: 8dd0037245a7cf180ba8a6eceeadad912d4adc14fc3f49df9008856de262624666d7d575195eea4868b2a5252dc565590e6be78471053b5e6367f3d2363310e8
e7bbfd3913 Improve Psbt error handling (DanGould)
Pull request description:
## Separate `encode::Error` and `psbt::Error` recursive dependency
This initial work attempts to fix#837's first 2 points
> - The current psbt::serialize::Deserialize has an error type of consensus::encode::Error. I think we should cleanly separate consensus encoding errors from application-level encoding errors like psbt.
> - There is a recursive dependence between encode::Error and psbt::Error which would need to be cleanly dissected and separated so that there is no dependence or only one-way dependence.
## Better `ParseError(String)` types
arturomf94 how compatible do your #1310 changes look to address #837's third point with this design?
> - There are a lot ParseError(String) messages that could use a better type to downflow the information.
I think your prior art would completely address this issue now.
## On handling `io::Error` with an associated error
`encode::Error` has an `Io` variant. now that `Psbt::deserialize` returns `psbt::Error` and produces an `io::Error`, we need an `Io` variant on `psbt::Error`. Except that doing so breaks `#[derive(Eq)]` and lots of tests for `psbt::Error`.
Kixunil, I'm trying to understand your feedback regarding a solution to this problem.
> I believe that the best error untangling would be to make decodable error associated.
> I meant having associated `Error` type at `Decodable` trait. Encoding should only fail if the writer fails so we should have `io::Error` there (at least until we have something like `genio`).
>
> > [it] is a problem to instantiate consensus::encode::Error in [the psbt] module for `io::Error`?
>
> It certainly does look strange. Maybe we should have this shared type:
>
> ```rust
> /// Error used when reading or decoding fails.
> pub enum ReadError<Io, Decode> {
> /// Reading failed
> Io(Io),
> /// Decoding failed
> Decode(Decode), // consensus and PSBT error here
> }
> ```
>
> However this one will be annoying to use with `?` :( We could have `ResultExt` to provide `decode()` and `io()` methods to make it easier.
>
> If that's not acceptable then I think deduplicated IO error is better.
Kixunil didn't we just get rid of Psbt as `Decodable`? Would this make more sense to have as an error associated with `Deserialize`? Or did we do the opposite of what we should have by making Psbt only `Serialize`/`Deserialize` because of #934, where only consensus objects are allowed to be `Decodable`? I wonder if we prioritized that strict categorization and are stuck with worth machinery because of it. My goal with #988 was to get to a point where we could address #837 and ultimately implement PSBTv2.
ACKs for top commit:
tcharding:
ACK e7bbfd3913
apoelstra:
ACK e7bbfd3913
Tree-SHA512: 32975594fde42727ea9030f46570a1403ae1a108570ab115519ebeddc28938f141e2134b04d6b29ce94817ed776c13815dea5647c463e4a13b47ba55f4e7858a
44d3ec487d Rename Payload::as_bytes to inner_prog_as_bytes (sanket1729)
a446df583c Make Payload non-exhaustive (sanket1729)
6ebc9de252 Introduce WitnessProgram struct and cleanup Address validity invariants (sanket1729)
41652caf05 Introduce is_spend_standard method (sanket1729)
Pull request description:
Fixes#1561.
Highlights:
- Segwitv0 programs with lengths apart from 20 or 32 are invalid `Address` struct. Such Addresses are useless and we should not parse/create them.
- Renamed `is_standard` to `is_spend_standard`.
ACKs for top commit:
apoelstra:
ACK 44d3ec487d
tcharding:
ACK 44d3ec487d
Tree-SHA512: 1ee36f7ea25c65619ddf7d643d025690096876843dbe6fbdf877ce23e88049d79b0bbd78cee6cf4b415bca028b3634bb70c9f52d1098bd90558e6ba7f8731332
Addresses with Segwitv0 not having len 20/32 are invalid and cannot be
constructed. Also cleans up a API bug in
ScriptBuf::new_witness_prog(ver, prog) allowing prog of invalid lenghts.
ebfbe74243 Implement `Debug` for generic `Address<V: NetworkValidation>` (Jiri Jakes)
Pull request description:
Previously `Debug` was implemented for both `Address<NetworkChecked>` and `Address<NetworkUnchecked>`, but not for cases when the `NetworkValidation` parameter was generic. This change adds this ability. Based on Kixunil's tip.
With previous implementation, the `test_address_debug()` resulted in error:
![image](https://user-images.githubusercontent.com/1381856/213907042-f1b27f41-fa46-4fa0-b816-cc4df53f5d29.png)
The added `Debug` on `NetworkChecked` and `NetworkUnchecked` are required by compiler.
---
While dealing with derives and impls, I also attempted to turn all the derives on `Address` into manual impls (see Kixunil's suggestion in https://github.com/rust-bitcoin/rust-bitcoin/pull/1489#discussion_r1052448057). The motivation behind this was the possibility to remove derives on `NetworkChecked` and `NetworkUnchecked`, too. However, even with manual impls, all the traits on `NetworkChecked` and `NetworkUnchecked` were still required by compiler in this sort of situations (see also the rest of the same discussion linked above). I do not fully understand why, perhaps limitation of this way of sealing traits?
It can be demonstrated by removing `Debug` derivation on `NetworkUnchecked` and `NetworkChecked` in this PR and running `test_address_debug()`.
Therefore, if we want to allow users of the library to define types generic in `NetworkValidation` and at the same time derive impls, it seems to me that `NetworkChecked` and `NetworkUnchecked` will have to have the same set of impls as `Address` itself.
ACKs for top commit:
Kixunil:
ACK ebfbe74243
tcharding:
ACK ebfbe74243
apoelstra:
ACK ebfbe74243
Tree-SHA512: 87f3fa4539602f31bf4513a29543b04e943c3899d8ece36d0d905c3b5a2d76e29eb86242694b5c494faa5e54bb8f69f5048849916c6438ddd35030368f710353
We can make the API more ergonomic by taking a generic argument that
implements `Into<secp256k1::PublicKey>` in the `bitcoin::PublicKey`
constructors.
The only thing than this is useful for is passing in `KeyPair` and the
`From` implementation already exists. Add a unit test to verify.
Fix: #1453
Currently we have an attempted tag ```compile_fail that seems to be
aiming at allowing code that does not build to exist in rustdoc. This is
causing an error when running tests.
No clue how this made it through CI.
Use ```ignore to prevent rustdoc code from being built.
Currently the derived implementation of `Debug` for `ScriptBuf` prints
the inner vector of u8s as integers, this is ugly and hard to read. The
`Script` implementation of `Debug` prints the script opcodes and data as
hex, we can just delegate to it.
With this applied we get debug output of form:
Script(OP_DUP OP_HASH160 OP_PUSHBYTES_20 \
3bde42dbee7e4dbe6a21b2d50ce2f0167faa8159 OP_EQUALVERIFY OP_CHECKSIG)
Fix: #1516
When we introduced the SPDX license blurb in [0] we incorrectly gave
attribution to Andrew when the original file author had the attribution
as "the rust-bitcoin developers". The original author [1] was Tamas
Blummer and he copied this code from code he wrote and explicitly
re-licenses it. In order to make the re-licensing comment a little
clearer and fix the mis-attribution use Tamas' name in the attribution.
[0] commit: `91ff2f628ce7db732d234a812e29fa8508f501a1 Introduce SPDX license identifiers`
[1] commit: `c93a70487f81a93c7d479ae046c75590d9fb7733 Add client side block filter (BIP158) (#281)`
The term "final" is an archaic Bitcoin term however it is well used, it
exists in Bitcoin Core code as well as in various bips. To help folks
new to Bitcoin add documentation to the `is_final` method including
historical notes.
The `bip158` module uses a `HashSet` and in order to do so requires the
`hashbrown` dependency for "no-std" builds.
We can replace the usage of `HashSet` with a `BTreeSet` in `bip158` and
remove the `hashbrown` dependency entirely.
This patch makes no claims about performance cost or benefit of this
change. The patch also makes no claims about the validity of the current
`HashSet` usage.
The `hashbrown` dependency and `HashSet` usage can be trivially added
back in if someone comes up with perf data to back it up.
Previously `Debug` was implemented for both `Address<NetworkChecked>`
and `Address<NetworkUnchecked>`, but not for cases when the
`NetworkValidation` parameter was generic. This change adds this
ability.
In preparation for deprecating the `is_final` method; move the
`enables_absolute_lock_time` method to be directly above the `is_final`
method.
Refactor only, no logic changes.
`Sighash` does not need to implement `Encodable` because it is
claimed (I don't know exactly myself) that `Sighash` is never consensus
encode in Bitcoin.
We are currently relying on `Sighash` to implement `Encodable` when
encoding creating the segwit v0 sighash for a single input.
For reference, from BIP143:
If sighash type is SINGLE and the input index is smaller than the
number of outputs, hashOutputs is the double SHA256 of the output
amount with scriptPubKey of the same index as the input;
We can use `write_all` directly to write the hashed bytes and remove the
implementation of `Encodable` from the `Sighash` type.
While we are at it, use `write_all` to write the zero hash also to make
the code more uniform and understandable.
Fix: #1549
70fe07f1ce Export the DisplayHex trait from within prelude (Tobin C. Harding)
Pull request description:
We use `internals::hex::display::DisplayHex` in many places, we can improve ergonomics of the `internals` crate by re-exporting it from the `prelude` module.
ACKs for top commit:
Kixunil:
ACK 70fe07f1ce
apoelstra:
ACK 70fe07f1ce
Tree-SHA512: 96a89135cb0b829b7b5926a3b344f78e178b5b48e772a69da5133fab6d2e14e7b7bbaa56b7a417a5c1a64337546a1c7bac32307d3a1f27aa199ed61f590902bf
Currently the docs build commands in `hashes` and `bitcoin` differ, they
should be the same.
Add a command `cargo doc` to improve coverage e.g., recently we botched
the feature guarding but since CI only runs `cargo rustdoc` with custom
compiler conditional set we didn't catch it.
Run docs in CI using nightly and stable toolchains as required.
a7dd4b5ab0 Add a rustdoc test to Denomination (Tobin C. Harding)
Pull request description:
Add a rustdoc test to the `Denomination` type to show basic usage.
ACKs for top commit:
Kixunil:
ACK a7dd4b5ab0
apoelstra:
ACK a7dd4b5ab0
Tree-SHA512: 08f15c4641e70f043276b873e60fcf0e195fe50b6c5c18a245d2d609f4a4a4badc291aae1be532fc4890a91b2057cd308c86d0d3b85770b600a07499303a7bc4
Recently we introduced some mutation testing to the `pow` module but
testing is never done - add more `mutate` attributes and add unit tests
to ensure all mutants are killed.
Of note, the `from_compact` and `to_compact_lossy` functions are not
done, doing so results in a bunch of surviving mutants.
Parsing addresses from strings required a subsequent validation of
network of the parsed address. However, this validation was not
enforced by compiler, one had to remember to perform it.
This change adds a marker type to `Address` that will assist the
compiler in enforcing this validation.
We use `internals::hex::display::DisplayHex` in many places, we can
improve ergonomics of the `internals` crate by re-exporting it from the
`prelude` module.
1b0988833a Remove `ToHex` (Martin Habovstiak)
Pull request description:
The `ToHex` trait was replaced by either simple `Display`/`LowerHex` where appropriate or `DisplayHex` from `bitcoin_internals` which is faster.
This change replaces the usages and removes the trait.
ACKs for top commit:
tcharding:
ACK 1b0988833a
apoelstra:
ACK 1b0988833a
Tree-SHA512: a1b508e24ac247a0692c01b7cb1e7fa8f23fbfa3d6c3d5dfe669eec01f940a96c3f88508cb0b2e3529eebd9cb51e7d41435dbd5f4cbaf3bc14b9c7e7d790308b
a400757676 Add failing tests from serde-json (sanket1729)
b3246bf73f Fix LeafVersion serde (sanket1729)
Pull request description:
The default implementation maps to visit_u64. The current implementation
does not roundtrip with many deserializers, including serde_json. See
the failing test in the second commit
ACKs for top commit:
Kixunil:
tACK a400757676
tcharding:
ACK a400757676
Tree-SHA512: a6307b799b0bb4af398addc9ddbff0d811b632d1cc6ab4bdd77aaf3f151e48dd1cd10e3f90a71ef8fc3feb1cd988f7a719f92ec745b5fdf2ae0f0ad97ab2fa10
The `ToHex` trait was replaced by either simple `Display`/`LowerHex`
where appropriate or `DisplayHex` from `bitcoin_internals` which is
faster.
This change replaces the usages and removes the trait.
94b678e73f Rename `push_scriptint` and make it private (Martin Habovstiak)
Pull request description:
`push_scriptint` is a significant footgun with an unclear name. This renames it and unpublishes to avoid mistakes by downstream crates.
Closes#1517
ACKs for top commit:
apoelstra:
ACK 94b678e73f
Tree-SHA512: 9e1772c6fb326d8b0c78d702ad9926a79a91589feb8650aed7c5e75bfbdbf0164357b4d5b190877c40b8469e0e3be3d3453fe407741b5dae0c5758176f756417
c4363e5ba1 Deserialize Psbt fields, don't consensus_encode (DanGould)
c1dd6ad8a2 Serialize Psbt fields, don't consensus_encode them (DanGould)
1b7b08aa5d De/serialize Psbt without consensus traits (DanGould)
Pull request description:
fix https://github.com/rust-bitcoin/rust-bitcoin/issues/934
Instead of using consensus {de,en}code, serialize high-level structures (PartiallySignedTransaciton, Output, Input) borrow the signature from `Serialize`, `Deserialize` traits and implement them on Psbt:
```rs
impl Psbt {
/// Serialize a value as raw data.
fn serialize(&self) -> Vec<u8>;
/// Deserialize a value from raw data.
fn deserialize(bytes: &[u8]) -> Result<Self, encode::Error>;
}
```
ACKs for top commit:
apoelstra:
ACK c4363e5ba1
tcharding:
ACK c4363e5ba1
sanket1729:
ACK c4363e5ba1. One small comment, but can be addressed in follow up if there is nothing else from other reviewers.
Kixunil:
ACK c4363e5ba1
Tree-SHA512: d8dd5ef1189b36fde08969b1ec36006a6fc55ae990f62ea744e6669e03a7f9e90e1d5907be7eac48ee1af23bc20a62aa7e60ff1ff78080d0e923bb9ccedcd432
The default implementation maps to visit_u64. The current implementation
does not roundtrip with many deserializers, including serde_json. See
failing test in the subsequent commit
089a1e452d Replace `Vec::from_hex` with `hex!` (Martin Habovstiak)
Pull request description:
This makes the code less noisy and is a preparation for changing it to `const`-based literal. Because of the preparation, places that used variables to store the hex string were changed to constants.
There are still some instances of `Vec::from_hex` left - where they won't be changeable to `const` and where `hex!` is unavailable (integration tests). These may be dealt with later.
See also #1189
Note that while the change appears big it's nearly entirely mechanical, so should be pretty easy to review. (But I don't feel it's `trivial`.)
ACKs for top commit:
apoelstra:
ACK 089a1e452d
tcharding:
ACK 089a1e452d
Tree-SHA512: c55357b8cffc86f8e107c0f8390490ede75948260018f63dc926455700cbcaf422f6ae72444f93943065e6f4ffa4335bee9160a64184ea4f8e91721f30a46ace
This makes the code less noisy and is a preparation for changing it to
`const`-based literal. Because of the preparation, places that used
variables to store the hex string were changed to constants.
There are still some instances of `Vec::from_hex` left - where they
won't be changeable to `const` and where `hex!` is unavailable
(integration tests). These may be dealt with later.
See also #1189
The additional `use` items were added to improve the style of
documentation. Because they were only used for doc they were `cfg`ed.
But because this is independent from being built by `docs.rs` the `cfg`
should've been `doc` not `docsrs`.
IOW `docsrs` means roughly `all(doc, nightly)` and the added items are
unrelated to `nightly`.
941083ec4e Remove rand-std dev-dependency from secp256k1 (Tobin C. Harding)
f71335f971 Add rand-std feature (Tobin C. Harding)
Pull request description:
This PR uncovered incorrect feature gating in `secp256k1`, fixed in https://github.com/rust-bitcoin/rust-secp256k1/pull/519
Currently we enable "secp256k1/rand-std" in the "rand" feature, this is incorrect because it means "rand" implies "std" which it does not.
Add a "rand-std" feature that turns on "seck256k1/rand-std" and make the "rand" feature turn on "seck256k1/rand".
Fix: #1384
ACKs for top commit:
sanket1729:
ACK 941083ec4e
apoelstra:
ACK 941083ec4e
Tree-SHA512: e1d12196766c2b3082b488fe7d0c03a865ebbfc70ffa6f128c57074df14da71e56c31ea92982991d376ac62fa86c6639049ce17aac93613b523ddcc99677c269
64f7d2549e Fix wrong newtype APIs (Martin Habovstiak)
Pull request description:
This fixes several API bugs:
* Use `TryFrom` instead of `From` for fallible conversions
* Move byte conversion methods from `impl_array_newtype` to `impl_bytes_newtype`
* Add missing trait impls like `AsRef`, `Borrow`, their mutable versions and infallible conversions from arrays
Closes#1336
Notably this change is much less bad than even I expected and some places actually get cleaner than before.
ACKs for top commit:
tcharding:
ACK 64f7d2549e
sanket1729:
code review ACK 64f7d2549e
apoelstra:
ACK 64f7d2549e
Tree-SHA512: 0c5ab19aa1a01ccf34ad1c2f3f66bd003a3142a840cb7cf57e1449e721f6eed1523555c62f0e3391012708767ff86315ff7edce9afd85017a67c61cfe57dddbc
ca471557a5 locktime: Add mutation testing (Tobin C. Harding)
26c0da41b4 locktime: Add inline to public functions (Tobin C. Harding)
Pull request description:
Add mutation testing to the `locktime` module and add unit tests to cover all mutants and ensure they are killed.
ACKs for top commit:
sanket1729:
ACK ca471557a5. How stable are the mutation tests?
apoelstra:
ACK ca471557a5
Tree-SHA512: 46a59c90fc25b0c803e96f7c5b98bd39055f7835e45ba137b2a01ad4221a676c54bc228b9ef7663b7300bb4260a6c2c80a0820c4f1bf0987650e1e2bd699f62d
cf9733d678 Verify and fix mul_u64 (Tobin C. Harding)
Pull request description:
Add kani verification for `U256::mul_u64`, doing so uncovered a bug in the current implementation due to overflow. Re-write the `mul_u64` method.
Fix: #1497
## Note
This PR now _only_ tests `mul_u64`, I will add testing div as a separate PR.
ACKs for top commit:
Kixunil:
ACK cf9733d678
apoelstra:
ACK cf9733d678
Tree-SHA512: c044fb385073bb068412195c079f26057ba560b2a7eca22693c360d324a7c0119cf10da2e70e544c69e05ca8269a81156418d307f4e11d8a4c1c1a7cafa32d0c
5a2a37d4be Allow dead_code/unused_imports when fuzzing (Tobin C. Harding)
Pull request description:
Littering the codebase with `#[cfg(not(fuzzing))]` is a bit messy just to quieten the linter during fuzzing. Instead just globally allow.
Done while debugging #1409
ACKs for top commit:
sanket1729:
ACK 5a2a37d4be
apoelstra:
ACK 5a2a37d4be
Tree-SHA512: fb84215a2b00ad6d3321b2781ba285af513ff8fd413c0997045a41c4f23028d2ef0fdf083839289d0c5108c990aa66bdae4430ad3ef32881eac5324b2e881b3b
e0bc50953a Make `Witness::tapscript()` return `Script` instead of raw bytes (Jiri Jakes)
Pull request description:
Since there is unsized `Script` now, this method can return it.
ACKs for top commit:
sanket1729:
utACK e0bc50953a
tcharding:
ACK e0bc50953a
Tree-SHA512: 32d4ca14f1b0fc1029f7376b1a43db90332b869a806609c82f660cb2690a4f0e1b91e1799fdac0d43c8a630aed0331f251d4159a662e86e5942c6fb698c42cd2
Add `#[inline]` to all public functions/methods excluding error types
and `Display` impls. Error paths do not need to be fast and presumably
`Display` is called on code paths that do IO so this also does not need
to be fast.
Add kani verification for `U256::mul_u64`, doing so uncovered a bug in
the current implementation due to overflow.
Re-write the `mul_u64` method.
Props to Elichai for the algorithm.
Co-authored-by: Elichai Turkel <elichai.turkel@gmail.com>
920599da94 Add test for previous commit (Martin Habovstiak)
a7f3458c27 Fix bug in `ScriptBuf::extend` for short iterators (Martin Habovstiak)
Pull request description:
`ScriptBuf::extend` contained an optimization for short scripts that was
supposed to preallocate the buffer and then fill it. By mistake it
attempted to fill it from already-exhausted iterator instead of the
temporary array it drained the items into. This obviously produced
garbage (empty) values.
This was not caught by tests because the optimization is only active for
scripts with known maximum length and the test used `Instructions` which
doesn't know the maximum length.
ACKs for top commit:
sanket1729:
ACK 920599da94 . Tested that the bug is correctly fixed and tested in the new test
tcharding:
ACK 920599da94
Tree-SHA512: a80f5f262a840d8e77efd42d63c511224380ee3efa6c31855233e81c90332ac15db228e8d552d039d729d7b642e03c3939c8b6a92d3279001377515acb83abea
8ce928b8e7 Add testing section to readme (Tobin C. Harding)
2e79a0bdc4 Introduce mutation testing (Tobin C. Harding)
Pull request description:
Introduce mutation testing by way of mutagen [0] (see #1484 for context).
- Conditionally add the dev-dependency `mutagen` (using `do_mutate` flag)
This flag is not very well named but `mutagen` and `mutate` are already taken?
- Mutate all methods of the `U256` struct that do not require additional unit tests.
Uses `cfg(all(test, do_mutate), mutate)` - I cannot workout why we need to check on `test` as well i.e., I don't understand why we cannot use `cfg(do_mutate, mutate)`?
With this applied test can be run as usual with a stable toolchain. To run mutagen we use `RUSTFLAGS='--cfg=do_mutate' cargo +nightly mutagen` (doing so runs 29 mutants).
[0] https://github.com/llogiq/mutagen
ACKs for top commit:
Kixunil:
ACK 8ce928b8e7
apoelstra:
ACK 8ce928b8e7
Tree-SHA512: 024ba5d2dc983f7cd0444e09ba13280771157204999d2a44502e07a1d6436f571b75003c7cb543c943f17949b848d4070eda4e194bda774a3e41443ff79af0af
This fixes several API bugs:
* Use `TryFrom` instead of `From` for fallible conversions
* Move byte conversion methods from `impl_array_newtype` to
`impl_bytes_newtype`
* Add missing trait impls like `AsRef`, `Borrow`, their mutable versions
and infallible conversions from arrays
Closes#1336
`ScriptBuf::extend` contained an optimization for short scripts that was
supposed to preallocate the buffer and then fill it. By mistake it
attempted to fill it from already-exhausted iterator instead of the
temporary array it drained the items into. This obviously produced
garbage (empty) values.
This was not caught by tests because the optimization is only active for
scripts with known maximum length and the test used `Instructions` which
doesn't know the maximum lenght.
In order to get better test coverage we should not enable the secp26k1
feature "rand-std" in dev-dependencies but instead feature gate tests
that depend on this feature.
Currently we enable "secp256k1/rand-std" in the "rand" feature, this is
incorrect because it means "rand" implies "std" which it does not.
Add a "rand-std" feature that turns on "seck256k1/rand-std" and make the
"rand" feature turn on "seck256k1/rand".
Introduce mutation testing by way of mutagen [0]
- Conditionally add the dev-dependency `mutagen` (using `do_mutate`
flag)
This flag is not very well named but `mutagen` and `mutate` are already
taken?
- Mutate all methods of the `U256` struct that do not require additional
unit tests.
Uses `cfg(all(test, do_mutate), mutate)` - I cannot workout why we need
to check on `test` as well i.e., I don't understand why we cannot use
`cfg(do_mutate, mutate)`?
With this applied test can be run as usual with a stable toolchain. To
run mutagen we use `RUSTFLAGS='--cfg=do_mutate' cargo +nightly mutagen`.
[0] https://github.com/llogiq/mutagen
This is useful when one already has bytes allocated in a vec that can be
reused.
The change also documents that the mirror method `into_bytes()` doesn't
allocate.
bae264d0c2 Add `tapscript_leaf_hash()` to `Script` (Jiri Jakes)
Pull request description:
Adds convenience method to `Script` for computing leaf hash of tapscript. Closes#1482.
The little test case is taken from `bip341_tests.json`.
ACKs for top commit:
Kixunil:
ACK bae264d0c2
apoelstra:
ACK bae264d0c2
Tree-SHA512: fb7a3a552017208decd56ca7d27eab1987a3a92aae5b8620896b3a02986c2fc13043c200ccfbadf9cfdd2d74af38b0bc25936338f55b7d318c1296acc88bf22a
6acf9ac8b8 Patch hashes and update the code (Martin Habovstiak)
Pull request description:
This patches `bitcoin_hashes` to use the version in the repository and fixes the code after removal of `Deref`.
ACKs for top commit:
tcharding:
ACK 6acf9ac8b8
apoelstra:
ACK 6acf9ac8b8
Tree-SHA512: b779fa79309f1d648020146b58e96346b67e9f76e29551cbd50251ea6bb7bcfc4c5d42f49cc7ad5660dcd0a5f6306efe96dfcd9530e4b32c62edf4af7076d830
This patches `bitcoin_hashes` to use the version in the repository and
fixes the code after removal of `Deref`.
This also turns off `AS_DEPENDENCY` check with the intention to refactor
it later.
02c1cd6291 add some documentation clarifying the locktime ordering shenanigans in #1330 (Andrew Poelstra)
Pull request description:
Updates the CHANGELOG and also the doccomment on `Transaction`.
ACKs for top commit:
tcharding:
ACK 02c1cd6291
Kixunil:
ACK 02c1cd6291
sanket1729:
ACK 02c1cd6291
Tree-SHA512: e2d23a90fb1e53758449fe49a3db7ae1497a260ce7efcade4b50265fa70840db273609019590d9d0a69e1272607a6bcf37924b805b4f09909487eb0c3b91a3cd
This renames `Script` to `ScriptBuf` and adds unsized `Script` modeled
after `PathBuf`/`Path`. The change cleans up the API a bit, especially
all functions that previously accepted `&Script` now accept truly
borrowed version. Some functions that perviously accepted `&[u8]` can
now accept `&Script` because constructing it is no loger costly.
1b15a13e5a run cargo clippy and fmt (Andrew Poelstra)
f2a5596899 examples: clean up taproot PSBT example locktime handling (Andrew Poelstra)
821842e1a1 drop Ord on absolute::LockTime; add Ord to Transaction (Andrew Poelstra)
5b7d801ee6 remove PackedLockTime type (Andrew Poelstra)
4dee116b8a delete PackedLockTime by aliasing it to LockTime (Andrew Poelstra)
fa81568fb6 locktime: add `FromHexStr` impl for `LockTime` (Andrew Poelstra)
74ff4946e4 locktime: unify serde impls (Andrew Poelstra)
Pull request description:
This is potentially a controversial PR, but hear me out. My argument is that right now `absolute::LockTime` and `PackedLockTime` are basically identical types; they can be converted between each other with `From` and they have exactly the same semantics except that `PackedLockTime` has `Ord` on it. This makes it very confusing to tell which one should be used, for example in PSBT2 where there are now extra locktime-related fields.
The motivation for having `PackedLockTime` independent of `LockTime` are:
* `PackedLockTime` is theoretically more efficient because you don't need to unpack the field, don't need to store a enum discriminate, etc. I don't buy this. If you are trying to save individual bytes in your transaction-parsing there are lots of places you'd look before messing around with locktimes, so we shouldn't privilege this specific thing.
* `PackedLockTIme` has an `Ord` impl, and removing that will have a cascading effect on transactions, blocks, etc., preventing them from being held in `BTreeMaps` etc. **My proposal**, implemented here, is to just manually impl `Ord` on `Transaction` and don't impl it on `LockTime`.
I recall some argument that we need to be able to sort miniscripts, and miniscripts might have locktimes in them, but I think this is wrong -- miniscripts always have explicitly either a `Height` or a `Time`, and there is no problem ordering these.
Closes#1455
ACKs for top commit:
sanket1729:
code review ACK 1b15a13e5a
tcharding:
ACK 1b15a13e5a
Tree-SHA512: d9776f14560c3822980e8fff8978bf8ca753035152f957a84af25d063c66e4e9df3d5cf98af38d6cb59cc52ba407282f722925b1ca670ae623ac91add3149d2f
b7a84d0c68 hashes: Do not implement Deref (Tobin C. Harding)
Pull request description:
Currently we implement `Deref` for hashes. From the docs [0]
> Deref should only be implemented for smart pointers to avoid confusion
Furthermore because we implement `Deref` as well as implement `internals::hex::display::DisplayHex` for slices hashes get coerced into slices and `to_lower_hex_string` can be called on them, this is incorrect because `DisplayHex` does not account for hashes that display backwards so we end up with the wrong string.
This is an API breaking change, and I have not built any other crates in our stack to check if anything breaks.
[0] https://doc.rust-lang.org/std/ops/trait.Deref.html
ACKs for top commit:
apoelstra:
ACK b7a84d0c68
sanket1729:
ACK b7a84d0c68
Tree-SHA512: 573169095dd9f9032e3f685e3b0af3b569f1cb5368e1b2f37940504fd887592f46488abcfbe84107baf9c5453c7db47bc342a6bc273ff98cb0570ffacb549c21
This still has the line
let lock_time = absolute::LockTime::from_height(psbt.unsigned_tx.lock_time.to_consensus_u32() + lock_time_delta).unwrap();
I'm unsure whether this "adding height to a locktime" concept is a
meaningful thing or just the sort of thing that shows up in example
code. Maybe we should have first-class support for it.
Note that the line, as written, depends on the fact that the original
locktime was a small blockheight. A proper function for this would
handle the exceptional case gracefully.
Currently we implement `Deref` for hashes. From the docs [0]
> Deref should only be implemented for smart pointers to avoid confusion
Furthermore because we implement `Deref` as well as implement
`internals::hex::display::DisplayHex` for slices hashes get coerced into
slices and `to_lower_hex_string` can be called on them, this is
incorrect because `DisplayHex` does not account for hashes that display
backwards so we end up with the wrong string.
[0] https://doc.rust-lang.org/std/ops/trait.Deref.html
This can be replicated by deleting the `type PackedLockTime = LockTime'
line, and then running
find . -type f | xargs sed -i 's/PackedLockTime/LockTime/g
at the root of the repo.
e00dfa9806 impl FromHexStr for structs with single u32 member (connormullett)
Pull request description:
Closes: #1112
- Adds new trait `FromStrHex` with 2 methods: `from_hex_str` and `from_hex_str_no_prefix`
- Impl new trait on each tuple struct with single u32 member. eg `Time(u32)`
As stated in the issue, grep through codebase with `\(u32\)` and `\(pub u32\)` to see all implementations and verify none were missed.
NonStandardSighashType is an error type and should never be constructed from a hex string. Therefore, it has been omitted from this change.
Tests are somewhat redundant, but cover 4 cases each. 2 happy paths, 1 for each function. 1 case for malformed/invalid hex input, and 1 for calling no_prefix without a prefix
ACKs for top commit:
Kixunil:
ACK e00dfa9806
apoelstra:
ACK e00dfa9806
Tree-SHA512: 221faef7fc1fa8fdb4cba79cfae317a0b63984937c345c6ca2287123a078f38911cdc07db7589a88b7bc6fbecf389e9bcff47952728410510ffcfc1857e0f91f
Adds new module `string` to be later converted to its own
crate. The module currently contains the FromHexStr trait and an error
type to be used for implementing hex parsing on types. This change
also adds implementations of FromHexStr for types with a single u32
member such as `Sequence(pub u32)`. All structs that match the
following regex have been given this implementation
`\(u32\)` and `\(pub u32\)`. All implementations have associated
unit tests matching all possible cases. NonStandardSighashType has
been ommitted from this change as it is an error and should not be
constructed using the methods added in this change.
Adds parse::hex_u32 for future use to be made generic to allow
different sizes of integers to be parsed from hex strings.
The error type FromHexError implements required traits such as
Display and std::error::Error
d7006ef80d Adds roundtrip tests for Network::from_core_arg (Sergi Delgado Segura)
bd1eb29f61 Adds Network::to_core_arg (Sergi Delgado Segura)
Pull request description:
Comming from https://github.com/rust-bitcoin/rust-bitcoincore-rpc/pull/247
`Network::from_str` only considers `rust-bitcoin` string as possible inputs to create a `Network` instance. This PR adds a new method to `Network`, `from_core_arg`, which is complementary to the existing `Network::to_core_arg`. This method allows the conversion between `bitcoind -network` string and `Network` variants.
This also links `Network::from_str` to `Network::from_core_arg` so the default case on the former calls the latter, and an error is only returned if none of the cases match.
ACKs for top commit:
Kixunil:
ACK d7006ef80d
apoelstra:
ACK d7006ef80d
Tree-SHA512: 97a66f858a7d4a3642bdef9016457833cfc1181e276f7ead7c6b87f6fcdcb7c5d1cfdb4b621225b806bc5949c3c5cc6a32b7df934157542d7c79aa00a9e20f41
c822fcf435 Remove helper variables (Martin Habovstiak)
70d1a0348e Use serde derive rather than manual parsing (Martin Habovstiak)
Pull request description:
Manual parsing Json is tedious and error-prone. It contained a bunch of
`unwrap`s and was hard to read.
This replaces manual Json parsing with serde_derive implementation.
Closes https://github.com/rust-bitcoin/rust-bitcoin/issues/1231
ACKs for top commit:
apoelstra:
ACK c822fcf435
tcharding:
ACK c822fcf435
Tree-SHA512: 0e1df6a62dc8438d67979a00658f8a2820135beebdd01d7275149b06feacd0d18accb86cecbf8c85f9a02ddc724575eaffff079b45cfe0e7765c8559c5eb03f7
Recently we (tcharding) do some mechanical improvements to the rustdocs
in the `blockdata` module without considering the content. On review a
bunch of improvements were suggested.
Improve the content of various rustdoc comments in the `blockdata`
module.
Suggested content came from reviewers, all mistakes are my own :)
Reduce the number of lines of code by using a longer column width, 100
as is more-or-less standard in this repo.
This patch only changes column width (line length), no other changes.
Manual parsing Json is tedious and error-prone. It contained a bunch of
`unwrap`s and was hard to read.
This replaces manual Json parsing with serde_derive implementation.
Closes#1231
1a2cf2681d Implement consensus encoding adapter for serde (Martin Habovstiak)
a6ecc58a5e Add `put_bytes_min` and `space_remaining` methods (Martin Habovstiak)
Pull request description:
In some protocols it is preferred to serialize consensus-encodable types
using consensus encoding. E.g. serialize `Transaction` as hex-encoded
string in Json in Bitcoin Core RPC protocol. This change provides
adapter to make this easier.
The adapter allows providing custom byte-to-string encoder for more
exotic cases and provides a hex implementation which should be useful in
majority of the cases.
Should help with #765
Based on #1252
Required by #1234
ACKs for top commit:
tcharding:
ACK 1a2cf2681d
apoelstra:
ACK 1a2cf2681d
Tree-SHA512: 96e10cf6ea0e7dfecfb58ee97453e0e7c8a2cfbb8af1e73a23c3afb67b985b394976361ac237528991fbb7344cc9f24644869199008245a91838309aff34bb97
df90c50242 Add log2 to Work (Jiri Jakes)
Pull request description:
Adds method `Work::log2()` providing value equivalent to Bitcoin Core's `log2_work` in its logs. Fixes#1326.
Questions:
- The original issue (#1326) also suggests to add log2 to Target but it does not seem to be meaningful, does it? Bitcoin Core, to which the issue refers, also displays only log2 of work.
- Although work should not be 0, the type allows it. In this case, log2 would return -inf. I think we could leave it like that but if there are suggestions to deal with it in a different way, please let me know.
ACKs for top commit:
Kixunil:
ACK df90c50242
tcharding:
ACK df90c50242
apoelstra:
ACK df90c50242
Tree-SHA512: 24e83c849ea3e16cad6f1636920883967cdac90b1b98ab19e86d1a5d0ac4585079740b54c1315afecabc1943d29a8b94316e3586bd2d10f1b61cc5cf7ad5b273
e9dffb1b7b Change `max_money` to a constant. (Martin Habovstiak)
Pull request description:
The value is statically known which is better expressed as a constant. Also allows usage in const context.
ACKs for top commit:
apoelstra:
ACK e9dffb1b7b
tcharding:
ACK e9dffb1b7b
ariard:
ACK e9dffb1
sanket1729:
ACK e9dffb1b7b
Tree-SHA512: b9b80d573531fe75dce22e185a1c84b2885160334418d1cfbd7279684fd4229c3c6c4041d3a3badb3652c5723e90ff52d3c761cbc3bff7b73978776694a67422
13d94cbc47 Remove no_run (Tobin C. Harding)
Pull request description:
`no_run` is not needed since we already mark this up as `bash` which rustc doesn't run when running examples.
While the keyword `bash` is not currently supported it may well be in the future and since only the `rust` keyword causes code to run any other string is effectively a wildcard, `no_run` is therefore meaningful only as a convention. Lets keep `bash` in case support is added later on.
cc sr-gi
ACKs for top commit:
sr-gi:
ACK 13d94cbc47
Kixunil:
ACK 13d94cbc47
sanket1729:
ACK 13d94cbc47
apoelstra:
ACK 13d94cbc47
Tree-SHA512: 90cbe8c5ea30577fc148d8e8b388008ea7f6c4975ea8b9e249e6058de901afca084d59e6a89eb9bda0a8e3112fb89336b622acd23046299c5e5ad7723ae26148
In some protocols it is preferred to serialize consensus-encodable types
using consensus encoding. E.g. serialize `Transaction` as hex-encoded
string in Json in Bitcoin Core RPC protocol. This change provides
adapter to make this easier.
The adapter allows providing custom byte-to-string encoder for more
exotic cases and provides a hex implementation which should be useful in
majority of the cases.
Should help with #765
My local scripts did not test serde feature on merge commit. While
merging 734, I accidently broke the serde feature on latest master. This
PR fixes it.
962abcc963 Add serde regression tests (Tobin Harding)
Pull request description:
Attempts to add regression tests for _all_ types defined in `rust-bitcoin` that implement `Serialize`/`Deserialize`.
- Add a `tests` directory and implement regression tests in there
- Use files for input hex and output bincode to reduce source file clutter
- Copy test block and `include_bytes!` usage from RCasatta's [PR](https://github.com/rust-bitcoin/rust-bitcoin/pull/750)
- Uses Kixunil's macro suggested below
- Adds a single regression test to `util/taproot.rs` for private types
## Note to reviewers
- Uses JSON for opcodes in a separate file (`tests/regression_opcodes.rs`), for all other tests uses bincode.
- Bypasses the order issue for maps by only serializing maps with a single element - is this correct?
Fixes#723
ACKs for top commit:
apoelstra:
ACK 962abcc963
sanket1729:
ACK 962abcc963. This has been open for a long time. Merging this in the interest of progress.
Tree-SHA512: e34e48e1c56fab5898bc74e7fb867435ed387d828dd3daf0c7d6df8f305e1da6883e91487115ac428618eb7d95bd16aa2cd209ca219684959bc95587ef0b4083
4c8570b512 base58: Run formatter (Tobin C. Harding)
2780e6cdaa Move base58 module to crate root (Tobin C. Harding)
Pull request description:
Move `base58` module to the carte root, direct `rustfmt` to not format the digits array. Run formatter as a separate patch.
ACKs for top commit:
apoelstra:
ACK 4c8570b512
sanket1729:
ACK 4c8570b512
Tree-SHA512: 3ab7afe089b9866a59f3f67c74c3e6657ca51d2d0ea1aaee0218a400b90826d36eaca7d491006a9448359ae3de5755d20b2d2df71e0fa3d6497fbaca270dcf42
`no_run` is not needed since we already mark this up as `bash` which
rustc doesn't run when running examples.
While the keyword `bash` is not currently supported it may well be in
the future and since only the `rust` keyword causes code to run any
other string is effectively a wildcard, `no_run` is therefore meaningful
only as a convention. Lets keep `bash` in case support is added later on.
In preparation for removing the `util` module move the `base58` module
to the crate root. This is likely not the final resting place for this
module but it is a step in the right direction.
Includes addition of rustfmt attribute to skip formatting the digits
array. No other changes to the `base58` module.
For some applications, such as block explorers, it's useful to be able
to obtain the public key used in case of P2PK. This is considered
general enough for addition into bitcoin library,
so this change adds it.
The public key is returned only when it's valid and the script is P2PK.
To avoid duplicating the logic checking whether a script is P2PK the
logic is moved to a new p2pk_pubkey_bytes() method which returns raw
bytes and is then called from both is_p2pk() and p2pk_public_key()
We are trying to flatten the `util` module. The `taproot` module can
live in the crate root. If/when we create a `crypto` module/crate we may
wish to pull some stuff out of this module but for now moving it gets us
closer to removing `util` without making the directory structure any
worse.
Includes adding rustfmt attributes to skip formatting of macros.
2df51dae15 Create crypto module (Tobin C. Harding)
Pull request description:
Done as part of [util flattening](https://github.com/rust-bitcoin/rust-bitcoin/issues/639).
Create a `crypto` module and move into it (out of `util`):
- ecdsa
- schnorr
- key
After review, this PR now includes some type re-names
- EcdsaSig -> ecdsa::Signature
- SchnorrSig -> schnorr::Signature
- EcdsaSigError -> ecdsa::Error
- SchnorrSigError -> schnorr::Error
- InvalidSchnorrSigSize -> InvalidSignatureSize (this is an error enum variant)
ACKs for top commit:
apoelstra:
ACK 2df51dae15
sanket1729:
ACK 2df51dae15
Tree-SHA512: 7cf63d51ed5fdc737cd59767d9bb96b1e3501634e3aee855493f6a51ad5c5397ce4b25c77f9929abd70d6ceb351fc6520e835da108f4c9a46df5b9c2b52ca6b3
f7a6d17143 Add rand feature flag to the example documentation (yancy)
Pull request description:
It's confusing trying to follow the documentation [here](https://docs.rs/bitcoin/latest/bitcoin/util/address/index.html) unless you know to enable the `rand` feature flag. This PR updates the docs so people know to enable the flag.
```
22:35 < control> hello, how can i generate a simple wallet address using rust bitcoin? cant find working example
22:45 < andytoshi> control: do you have a private key?
22:45 < andytoshi> what kind of address do you want to generate?
22:46 < andytoshi> my guess would be that you want to use bdk rather than rust-bitcoin directl
22:48 < control> P2PKH address and generate private key. just as simple as bit library in python does
22:52 < control> im trying to run this example
22:52 < control> https://docs.rs/bitcoin/latest/bitcoin/util/address/index.html
22:52 < control> but it says ^^^^ could not find `rand` in `secp256k1`
```
ACKs for top commit:
apoelstra:
ACK f7a6d17143
Kixunil:
ACK f7a6d17143
Tree-SHA512: 6d94f8ffa7797d1e7720a840d4f8bb0ac274507118597dff60631ad3d28dbe57e2341b87d6101e2a9f5fbcc2b1f0beb6d06f9dde48a480cb10a9a45c887f83a4
Kani can't really handle string processing, and appears to be unable
to check integer multiplication (for now), but we do several checks
for addition and subtraction, and conversion between signedness,
that Kani can easily prove.
Done as part of flattening util.
Currently in `util` module we have a bunch of modules that provide
cryptography related functionality.
Create a `crypto` module and move into it the following:
- ecdsa
- schnorr
- key
To improve uniformity and ergonomics, do the following re-names while we
are at it:
- EcdsaSig -> ecdsa::Signature
- SchnorrSig -> schnorr::Signature
- EcdsaSigError -> ecdsa::Error
- SchnorrSigError -> schnorr::Error
- InvalidSchnorrSigSize -> InvalidSignatureSize (this is an error enum variant)
519db4d951 add Network::to_core_arg() method (connormullett)
Pull request description:
closes: #1207
Adds converting `Network` to its `bitcoind` equivalent.
The arguments for -chain can be found in the documentation and is one of the following:
main, test, signet, regtest
ACKs for top commit:
apoelstra:
ACK 519db4d951
Kixunil:
ACK 519db4d951
Tree-SHA512: 5fd805d654f7c30f87ff877fe90e19490d0deb73b46ce87cc6b43d30595eb9d2de3f646f58a5d72180c3e8cc6a9b614bfe6753ecd6c21b8d193a8d862e3f887f
108a1f73ca Fail CI if docs build throws warnings (Tobin C. Harding)
b014f0fdcb Fix rustdocs build warnings (Tobin C. Harding)
Pull request description:
Currently we do not fail the CI script if the docs build throws warnings, since we are a group of super anal, easily triggered, code cleanliness obsessed devs this causes a mild rash to develop on the lower back [0]. We can easily fix this by checking for build warnings in CI.
[0] - Amusingly my rash has been playing up since Friday but I thought I'd fixed the warnings in an open PR someplace so I was ignoring it, seeing Kixunil's [issue](https://github.com/rust-bitcoin/rust-bitcoin/issues/1403) this morning prompted me to fix it :)
Fix#1403
ACKs for top commit:
Kixunil:
ACK 108a1f73ca
apoelstra:
ACK 108a1f73ca
Tree-SHA512: 0f86c318b2ec8bf7aa6a0d0f355f8fe8e3eb8ad5eb74d95f8dab882d6729c386c3e0ef4cc2378645e15460ff2b9b47d66e3603958f8b188f5e2b07272739d755
Convert all rustdocs build warnings to errors using `-D warnings` and
exit the script with 1 to signal the error.
While we are at it use `--all-features` instead of explicit feature list
when building docs. Without this the docs build fails with:
error: too many file operands
64495cc5fe Drop Network arg from max_money() (Antoine Riard)
Pull request description:
Amount of coins available stay in the same across Bitcoin network: signet, testnet, mainet. From my understanding this is a leftover from some potential multi-chain support.
For more context: https://github.com/lightningdevkit/rust-lightning/pull/1839#discussion_r1019753069
If there is already an existent PR, it can be closed, however didn't find one.
ACKs for top commit:
apoelstra:
ACK 64495cc5fe
tcharding:
ACK 64495cc5fe
Tree-SHA512: 929011ee73c5eda903fb0140438ed5e88c8f5b7378036a87a6a660a8b9138bf204bf59a0ba822c0cd98e37e97d2d0dbbf8c9893a834da9acdf817ba43a5ed5b6
e04a7a926d network: Run cargo fmt (Tobin C. Harding)
dc33c7999f Enable formatting of the network module (Tobin C. Harding)
81f69e846b Exclude from formatting stuff in the network module (Tobin C. Harding)
408d7737fb Run cargo fmt (Tobin C. Harding)
1ecf09359b Add local variable to reduce line length (Tobin C. Harding)
b2e74bc050 Exclude long function call (Tobin C. Harding)
ff5a80dbd3 Exclude formatting of function fmt_satoshi_in (Tobin C. Harding)
308a12b7cf Exclude array from formatting (Tobin C. Harding)
fb7ff46ccc Improve crate root re-exports (Tobin C. Harding)
Pull request description:
The `network` module is not currently included in formatting. Also, at this point in time not much is happening in the `network` module so formatting it should not cause too many merge conflicts with other in-progress PRs.
The first 3 patches are formatting preparation of the repo, the next 2 are formatting preparation of the `network` module. The last patch is the result of running `cargo +nightly fmt`. Can one reviewer please verify the last patch consists only of `rustfmt` changes by running the command on their branch. Thanks
cc luckysori :)
ACKs for top commit:
apoelstra:
ACK e04a7a926d
Tree-SHA512: 49b2873f0bfdd448df97073b462fa860c85b7f3c3094fdb0e16fd86aa467156ea8b2ceec61e2ee99848802cd171fd8abbc17e45c66672889a37c413fa4bea636
9674bf29fe hashes: Fix clippy warnings (Tobin C. Harding)
b9643bf3e9 Import bitcoin_hashes crate into hashes (Tobin C. Harding)
580feab3f9 internals: Add CHANGELOG file (Tobin C. Harding)
bae64e156e Move CHANGELOG to bitcoin crate (Tobin C. Harding)
9a2c856be6 Update gitignore file (Tobin C. Harding)
Pull request description:
#1337 was split out of this in an attempt to help review, I think we can merge this one though now it has some traction.
We would like to bring the `bitcoin_hashes` crate into the `rust-bitcoin` repository. https://github.com/rust-bitcoin/rust-bitcoin/issues/550#issuecomment-1248071843
Import `bitcoin_hashes` crate into `hashes`.
Commit hash that was tip of `bitcoin_hashes` at time of import:
commit 2a78c250f78d391599040223870a4d1d6f6f5482
Please note the commit history of `bitcoin_hashes` is only preserved on the soon-to-be-archived `bitcoin_hashes` repository.
ACKs for top commit:
sanket1729:
ACK 9674bf29fe. Did my best to review the CI code, it looks good, and seems like we are testing everything when we add "hashes" to the root level `./contrib/tests.sh`. I would like other reviewers to confirm the same.
apoelstra:
ACK 9674bf29fe
Tree-SHA512: db3ce6adeb38430c5a9f372da16be9fb048c2e5cff646b701139fb4b5fa76e10261432284ede7fd139b75cd69bb124d55973ceb7eccaa996226a7be4cad9b68a
Amount of coins available stay in the same across Bitcoin network:
signet, testnet, mainet. From my understanding this is a leftover
from some potential multi-chain support.
We just removed the `bitcoin/src/network/` exclude from `rustfmt` config
file. Run the command `cargo +nightly fmt`.
No other changes than those introduced by `rustfmt`.