Commit Graph

266 Commits

Author SHA1 Message Date
Tobin C. Harding 603f441548 Add array constants
In multiple places we use array constants for zero and one. Add two
constants and use them throughout the codebase. Note the endian-ness of
`ONE` in the docs.
2022-11-06 05:21:16 +11:00
Tobin C. Harding 5417fad7cb Add method SecretKey::from_hashed_data
Analogous to the method on `Message`; add a constructor method on
`SecretKey` that hashes the input data.

While we are at it improve the rustdocs on `Message::from_hashed_data`
so docs on both methods are uniform.
2022-10-28 12:16:15 +11:00
elsirion 53c1354cc5
Fix broken `serde::Deserialize` and `FromStr` impl of `keyPair`
Fixes #491
2022-10-24 16:54:13 +02:00
Tobin C. Harding a431edb86a Create configuration conditional bench
As we did in rust-bitcoin [0] create a configuration conditional `bench`
that we can use to guard bench mark code. This has the benefit of
making our features additive i.e., we can now test with `--all-features`
with a stable toolchain (currently this fails because of our use of the
`test` crate).

[0] - https://github.com/rust-bitcoin/rust-bitcoin/pull/1092
2022-07-14 09:35:23 +10:00
Tobin C. Harding d2c97d43d8 Remove unnecessary instances of must_use
`Result` is already `must_use`, adding the compiler directive to
functions that return `Result` is unnecessary.
2022-07-11 07:56:47 +10:00
Tobin C. Harding 5f611f6f7f Conditionally compile the hex macro
We only use this macro when not fuzzing, add a cfg attribute to build it
in only when needed.
2022-06-29 11:11:39 +10:00
Andrew Poelstra 5f59820a8a
Merge rust-bitcoin/rust-secp256k1#465: Add must_use for mut self key manipulation methods
56f18430ff Add must_use for mut self key manipulation methods (Tobin C. Harding)
5b86e38aea Put compiler attributes below rustdocs (Tobin C. Harding)

Pull request description:

  We recently added a bunch of key tweaking methods that take `mut self`
  and return the tweaked/negated keys. These functions are pure and as
  such the returned result is expected to be used. To help downstream
  users use the API correctly add `must_use` attributes with a descriptive
  error string for each of the methods that takes `mut self`.

  Patch 1 is preparatory cleanup.

ACKs for top commit:
  apoelstra:
    ACK 56f18430ff

Tree-SHA512: 95ee63d5d0a34a9915551471d2f71de1963875eda04bf4217544076be0ed2836dcdee1875432dba5e02678556af86d7487e39daac6e928083807661430ddbcd6
2022-06-28 14:56:58 +00:00
Tobin C. Harding 0c15c01eb1 Use fuzzing not feature = "fuzzing"
Currently the following command fails

`RUSTFLAGS='--cfg=fuzzing' RUSTDOCFLAGS='--cfg=fuzzing' cargo test --all --all-features`

This is because `fuzzing` is not a feature, we should be using `fuzzing`
directly not `feature = "fuzzing"`.

I have no idea how this got past CI.
2022-06-28 13:30:33 +10:00
Tobin C. Harding 56f18430ff Add must_use for mut self key manipulation methods
We recently added a bunch of key tweaking methods that take `mut self`
and return the tweaked/negated keys. These functions are pure and as
such the returned result is expected to be used. To help downstream
users use the API correctly add `must_use` attributes with a descriptive
error string for each of the methods that takes `mut self`.
2022-06-28 13:18:57 +10:00
Martin Habovštiak e612458dc7
Remove mentions of 32-byte slice from tweak APIs
These methods accept `&Scalar`, not slice and `&Scalar` already guarantees 32-bytes, so this failure case is impossible.
2022-06-21 18:37:35 +02:00
Andrew Poelstra a1ac3fb311
Merge rust-bitcoin/rust-secp256k1#448: Add clippy to CI
65186e732a Add githooks (Tobin C. Harding)
6d76bd4a89 Add clippy to CI (Tobin C. Harding)
9f1ebb93cb Allow nonminimal_bool in unit test (Tobin C. Harding)
685444c342 Use "a".repeats() instead of manual implementation (Tobin C. Harding)
42de876e01 Allow let_and_return for feature guarded code (Tobin C. Harding)
d64132cd4b Allow missing_safety_doc (Tobin C. Harding)
2cb687fc69 Use to_le_bytes instead of mem::transmute (Tobin C. Harding)
c15b9d2699 Remove unneeded explicit reference (Tobin C. Harding)
35d59e7cc6 Remove explicit 'static lifetime (Tobin C. Harding)
1a582db160 Remove redundant import (Tobin C. Harding)

Pull request description:

  The first 8 patches clear clippy warnings. Next we add a CI job to run clippy. Finally we add a `githooks` directory that includes running clippy, also adds a section to the README on how to use the githooks. This is identical to the text in the [open PR](https://github.com/rust-bitcoin/rust-bitcoin/pull/1044) on `rust-bitcoin` that adds githooks _without_ yet adding clippy.

  **Note**: The new clippy CI job runs and is green :)

ACKs for top commit:
  Kixunil:
    ACK 65186e732a
  apoelstra:
    ACK 65186e732a

Tree-SHA512: f70a157896ce2a83af8cfc10f2fbacc8f68256ac96ef7dec4d190aa72324b568d2267418eb4fe99099aeda5486957c31070943d7c209973859b7b9290676ccd7
2022-06-17 17:12:12 +00:00
Tobin C. Harding 9f1ebb93cb Allow nonminimal_bool in unit test
We are explicitly testing various boolean statements, tell clippy to
allow less than minimal statements.
2022-06-17 10:17:21 +10:00
Tobin C. Harding 685444c342 Use "a".repeats() instead of manual implementation
Clippy emits:

  warning: manual implementation of `str::repeat` using iterators

As suggested, use `"a".repeats()`.
2022-06-17 10:17:21 +10:00
Tobin C. Harding c15b9d2699 Remove unneeded explicit reference
Clippy emits:

  warning: this expression creates a reference which is immediately
  dereferenced by the compiler

Remove the explicit reference.
2022-06-16 09:56:52 +10:00
Tobin C. Harding 35d59e7cc6 Remove explicit 'static lifetime
Clippy emits:

  warning: statics have by default a `'static` lifetime

Static strings no longer need an explicit lifetime, remove it.
2022-06-16 09:56:52 +10:00
Tim Ruffing f419fe884b Fix getting parity from keypair in fuzzing
This also enables a test that was failung due to the parity bug.
2022-06-15 22:41:36 +02:00
Andrew Poelstra aba2663bc8
Merge rust-bitcoin/rust-secp256k1#449: Re-implement public key ordering using underlying FFI functions
13af51926a Make key comparison non-fuzzable (Dr Maxim Orlovsky)
739660499b Implement PublicKey ordering using FFI (Dr Maxim Orlovsky)
0faf404f0e Benchmark for key ordering (Dr Maxim Orlovsky)
999d165c68 FFI for pubkey comparison ops (Dr Maxim Orlovsky)

Pull request description:

  Re-base #309 for @dr-orlovsky on request by @Kixunil.

  To do the rebase I just had to change instances of cfg_attr to use `v0_5_0` instead of `v0_4_1` e.g.,
  ```
      #[cfg_attr(not(rust_secp_no_symbol_renaming), link_name = "rustsecp256k1_v0_5_0_xonly_pubkey_cmp")]
  ```

  And drop the changes to `src/schnorrsig.rs`, all these changes are covered by the changes in `key.rs` I believe.

ACKs for top commit:
  Kixunil:
    ACK 13af51926a
  apoelstra:
    ACK 13af51926a

Tree-SHA512: 3054fcbc1707679f54466cdc91162c286394ad691e4f5c8ee18635a22b0854a4e60f1186ef3ca1532aacd8a637d0a153601ec203947e9e58dfcebf1bcb619955
2022-06-15 15:45:49 +00:00
Andrew Poelstra 4dacf55ed5
Merge rust-bitcoin/rust-secp256k1#435: Add functional style methods to various keys
12d4583638 Implement negate that consumes self (Tobin Harding)
5eb2d745b7 Rename tweak_add_assign -> add_tweak (Tobin Harding)
b9d08db8eb Replace _assign with _tweak (Tobin Harding)

Pull request description:

  The various `_assign` methods (`add_assign`, `add_expr_assign`, `mul_assign`, `tweak_add_assign`) are cumbersome to use because a local variable that uses these methods changes meaning but keeps the same identifier. It would be more useful if we had methods that consumed `self` and returned the newly modified type.

  We notice also that this API is for adding/multiplying tweaks not arbitraryly adding keys.

  - Patch 1: Changes add/mul_assign -> add/mul_tweak for `PublicKey` and `SecretKey` (incl. re-working unit tests)
  - Patch 2: Changes `tweak_add_assign` -> `add_tweak` for `KeyPair` and `XOnlyPublicKey`
  - Patch 3: Changes `negate_assign` -> `negate`

  All methods changed include:
  - New method consumes self and returns the tweaked key
  - Original  method remains with a `deprecated` attribute, however I've left a TODO in there for adding the `since` field.

  Close: #415

ACKs for top commit:
  apoelstra:
    ACK 12d4583638

Tree-SHA512: 026e8722892f3a0f18956281e4d2356d2789ef535a7ab71a375758201b180663d068397cde2dca5f60858ab7158069e53d7096326bfbd5a364269b0be680940c
2022-06-15 15:39:30 +00:00
Andrew Poelstra 613d7dc1cb
Merge rust-bitcoin/rust-secp256k1#406: Use fixed width serde impls for keys
3ca7f499e0 Add fixed-width-serde integration tests (Tobin Harding)
bf9f556225 Add rustdocs describing fixed width serde (Tobin Harding)
c28808c5a4 Improve rustdocs for KeyPair (Tobin Harding)
6842383161 Use fixed width serde impls for keys (Tobin Harding)

Pull request description:

  Currently we serialize keys using the `BytesVisitor`, this causes the serialized data to contain additional metadata encoding the length (an extra 8 bytes) when serialized with [bincode.](https://docs.rs/bincode/latest/bincode/index.html). This extra data is unnecessary since we know in advance the length of these two types.

  We do not control the data output by serialization of our types because it depends on which crate is used to do the serialization. This PR improves the situation for serialization using the `bincode` crate, and this PR introduces mentions of `bincode` in the rustdocs, is this acceptable? See below for a table that describes binary serialization by other crates.

  Implement a sequence based visitor that encodes the keys as fixed width data for:

  - `SecretKey`
  - `PublicKey`
  - `KeyPair`
  - `XOnlyPublicKey`

  Fixes: #295

  **Question**: PR only does keys, do we want to do signatures as well?

ACKs for top commit:
  apoelstra:
    ACK 3ca7f499e0

Tree-SHA512: 77babce74fa9f0981bb3b869c4e77a68a4d1ec28d22d2c3be4305e27ef01d4828dac210e20b968cbbe5de8a0563cd985d7969bccf75cfe627a34a116fed1a5df
2022-06-15 15:21:28 +00:00
Dr Maxim Orlovsky 13af51926a Make key comparison non-fuzzable
Feature guard the custom implementations of `Ord` and `PartialOrd` on
`cfg(not(fuzzing))`. When fuzzing, auto-derive implementations.

Co-authored-by: Tobin C. Harding <me@tobin.cc>
2022-06-15 08:35:50 +10:00
Dr Maxim Orlovsky 739660499b Implement PublicKey ordering using FFI
Instead of selializing the key we can call down to the ffi layer to do
ordering.

Co-authored-by: Tobin C. Harding <me@tobin.cc>
2022-06-15 08:34:05 +10:00
Tobin Harding 12d4583638 Implement negate that consumes self
The method `negate_assign` (on pub/sec key) is cumbersome to use because
a local variable that uses these methods changes meaning but keeps the
same identifier. It would be more useful if we had methods that consumed
`self` and returned a new key.

Add method `negate` that consumes self and returns the negated key.
Deprecated the `negate_assign` methods.
2022-06-15 08:13:45 +10:00
Tobin Harding 5eb2d745b7 Rename tweak_add_assign -> add_tweak
We now have a method `add_tweak` on the `SecretKey` and `PublicKey`. We
can add similar methods that consumes self and return the tweaked key
for the `KeyPair` and `XOnlyPublicKey` types.

The justification for doing so is that a local variable that calls
`tweak_add_assign` changes in meaning but the identifier remains the
same, this leads to cumbersome renaming of the local variable.

The tweaking done to the `KeyPair` is actually done via the xonly public
key not the public key. To reflect this call the method
`add_xonly_tweak`, this is similar to how it is named in secp
`secp256k1_keypair_xonly_tweak_add`.
2022-06-15 08:13:42 +10:00
Dr Maxim Orlovsky 0faf404f0e Benchmark for key ordering 2022-06-14 11:46:47 +10:00
Tobin Harding b9d08db8eb Replace _assign with _tweak
The key methods `add_assign`, `add_expr_assign`, and `mul_assign` are
cumbersome to use because a local variable that uses these methods
changes meaning but keeps the same identifier. It would be more useful
if we had methods that consumed `self` and returned a new key.

Observe also that these to methods are for adding/multiplying a key by a
tweak, rename the methods appropriately.

Add methods `add_tweak`, `add_expr_tweak`, and `mul_tweak` to the
`SecretKey` and `PublicKey` type. Deprecate `add_assign`,
`add_expr_assign`, and `mul_assign`.
2022-06-14 09:46:17 +10:00
Martin Habovstiak cabb8f9e6f Implemented `TryFrom<{u8, i32}>` for `Parity` 2022-06-10 13:35:42 +02:00
Martin Habovstiak 5a0332463d Add `Scalar` newtype and use it in tweaking APIs
This adds `Scalar` newtype to better represent values accepted by
tweaking functions. This type is always 32-bytes and guarantees being
within curve order.
2022-06-09 15:08:19 +02:00
Tobin Harding bf9f556225 Add rustdocs describing fixed width serde
We recently added fixed width serialization for some types however
serialization is only fixed width when data is serialized with the
`bincode` crate.

Add rustdocs describing fixed width serde to `SecretKey`, `PublicKey`,
and `XOnlyPublicKey` (`KeyPair` is already done).
2022-06-09 16:17:10 +10:00
Tobin Harding c28808c5a4 Improve rustdocs for KeyPair
Currently the rustdocs for `KeyPair` are stale in regards to serde, we
_do_ implement `Serialize` and `Deserialize` for `KeyPair`.

Improve the rustdocs for `KeyPair` by removing stale docs and adding
docs on fixed width binary serialization.
2022-06-09 16:17:05 +10:00
Tobin Harding 6842383161 Use fixed width serde impls for keys
Currently we serialize keys using the `BytesVisitor`, this causes the
serialized data to contain additional metadata encoding the length (an
extra 8 bytes) when serialized with the `bincode` crate. This extra data
is unnecessary since we know in advance the length of these types.

It would be useful for users of the lib to be able to get a fixed width
binary serialization, this can be done but it depends on the crate used
to do the serialization. We elect to optimise for `bincode` and add docs
noting that other binary serialization crates may differ (rustdocs added
in separate patches).

Implement a tuple based visitor that encodes the keys as fixed width
data.

Do fixed width serde implementations for:

- `SecretKey`
- `PublicKey`
- `KeyPair`
- `XOnlyPublicKey`
2022-06-09 16:09:31 +10:00
Elichai Turkel 39aaac6834
Use new trait TryFrom and do small refactoring 2022-06-07 23:59:43 +03:00
Elichai Turkel ebe46a4d4e
Update rand to 0.8 and replace CounterRng with mock::StepRng 2022-06-07 23:59:40 +03:00
Elichai Turkel 626835f540
Update secp256k1 to edition 2018 and fix imports 2022-06-07 23:59:25 +03:00
Andrew Poelstra a30e9bb9ff
Merge rust-bitcoin/rust-secp256k1#430: Add convenience methods for keys
f08276adfc Add convenience methods for keys (Tobin Harding)
b4c7fa0d4e Let the compiler work out int size (Tobin Harding)
c612130864 Borrow secret key (Tobin Harding)

Pull request description:

  We have a bunch of `from_<key>` methods for converting between key types. To make the API more ergonomic to use we can add methods that do the same but called on a variable e.g., once applied the following are equivalent:

  - `let pk = PublicKey::from_keypair(kp)`
  - `let pk = kp.public_key()`

  Do this for `SecretKey`, `PublicKey`, `KeyPair`, and `XOnlyKeyPair`.

  Fixes: #428

  ### Note to reviewers

  - `XOnlyPublicKey` -> `PublicKey` logic is made up by me, I could not work out how to get `libsecp256k1` to do this.
  - Please review the tests carefully, they include assumptions based on my current understanding of the cryptography :)

ACKs for top commit:
  sanket1729:
    ACK f08276adfc. Thanks for going through all the iterations.
  apoelstra:
    ACK f08276adfc

Tree-SHA512: 1503a6e570a3958110c6f24cd6d075fe5694b3b32b91a7a9d332c63aa0806198ff10bdd95e7f9de0cf73cbf4e3655c6826bd04e5044d1b019f551471b187c8ea
2022-04-30 16:21:46 +00:00
Tobin Harding f08276adfc Add convenience methods for keys
We have a bunch of `from_<key>` methods for converting between key types.
To improve the API and make it more ergonomic to use we can add methods
that do the same but can be called on the initial key instead of on the
resulting key's type. E.g. once applied the following are equivalent:

- `let pk = PublicKey::from_keypair(kp)`
- `let pk = kp.public_key()`

Do this for `SecretKey`, `PublicKey`, `KeyPair`, and `XOnlyKeyPair`.
2022-04-04 12:58:46 +10:00
Tobin Harding b4c7fa0d4e Let the compiler work out int size
We have two places in the code where we pass a mutable parity integer
to ffi code. At one callsite we tell the compiler explicitly what type
it is (`::secp256k1_sys::types::c_int`) and at the other call site we
let the compiler figure out the type.

Is one way better than the other? I don't know. But letting the compiler
figure it out seems to make the code easier to read.
2022-04-04 12:50:52 +10:00
Tobin Harding c612130864 Borrow secret key
`SecretKey` implements `Copy` and it is fine to take owneship of it; we
have multiple methods called `from_secret_key` and they all borrow the
secret key parameter. Favour consistency over perfection.

Borrow secret key parameter as is done in other `from_secret_key`
methods.
2022-04-04 12:50:52 +10:00
sanket1729 676a9800df Remove unnecessary panic message
1) All types in rust should have the guarantee that well-formed data is
stored in SecretKey type. Therefore, IMO the panic message is
unnecessary.
2022-03-21 16:37:15 -07:00
sanket1729 aa50cc6ced Remove Schnorr word from keypairs
Keypairs are pair of EC points that don't have anything to do with the
signature algorithm
2022-03-21 16:36:58 -07:00
Tobin Harding 7a417fd1c5
Deprecate SCHNORRSIG_PUBLIC_KEY_SIZE
Recently we moved from using the identifier 'schnorrsig' to 'schnorr',
we omitted to update the schnorr public key size constant.

Deprecate `SCHNORRSIG_PUBLIC_KEY_SIZE` and add
`SCHONORR_PUBLIC_KEY_SIZE`.
2022-03-04 14:27:58 +00:00
Andrew Poelstra dc90a43e68
Merge rust-bitcoin/rust-secp256k1#403: `Parity` conversion and error handling cleanup
5acf6d23d3 `Parity` conversion and error handling cleanup (Martin Habovstiak)

Pull request description:

  This removes the deprecated `From` conversion, replaces it with
  `TryFrom`, and adds more convenience conversions. A new error type is
  created for the invalid parity error with conversion to catch-all
  `Error`.

  This is intended for an API-breaking version.

ACKs for top commit:
  apoelstra:
    ACK 5acf6d23d3

Tree-SHA512: 49b73fc90455c172012b46f36eafa7d256b940f4b431b4eedb577ab07d9402eae40af931e00b3c409bbe502dbcac064a742e874a5e8bedd8d0cbe92a468ae4f6
2022-03-01 13:01:15 +00:00
Martin Habovstiak 5acf6d23d3 `Parity` conversion and error handling cleanup
This removes the deprecated `From` conversion and adds a new error
type for the invalid parity error with a conversion to the catch-all
`Error`.
2022-02-28 20:59:51 +01:00
Tobin Harding 5c7c76eb74
Rename serialize_secret -> secret_bytes
The `serialize_secret` method is a getter method, it does not do any
serialisation. However we use the method on secret keys and key types so
in order for the name to be uniform use the descriptive name
`secret_bytes`.

Rename `serialize_secret` to be `secret_bytes`.
2022-02-28 07:11:24 +00:00
Tobin Harding 91106f5685
Remove magic number
In array initialisation we use magic number 64, this is the secret bytes
length multiplied by 2.

Please note; we still use the magic number 32, left as such because it
is used in various ways and its not immediately clear that using a
single const would be any more descriptive.

Use `SECRET_KEY_SIZE * 2` instead of magic number 64.
2022-02-24 19:48:19 +00:00
Andrew Poelstra c7d6cdbaba
Merge rust-bitcoin/rust-secp256k1#401: Breaking: changed Parity serialization to u8
e6cb588a23 Breaking: changed `Parity` serialization to `u8` (Martin Habovstiak)

Pull request description:

  Serializing the value as `u8` is more compact but this is a breaking
  change.

  `Visitor` was renamed to avoid hungarian notation and maybe allow other
  integers in the future.

  For next major version, depends on #400

ACKs for top commit:
  tcharding:
    tACK e6cb588
  apoelstra:
    ACK e6cb588a23

Tree-SHA512: 1432a2f3c913c3a7eaec5228fd2dd4e8320d828128bec71812cbf56dd8950c969ed22c69867402eb9e820127868d29b291f3374c6e15de0a3ff2341420c4bbab
2022-02-24 15:16:21 +00:00
Tobin Harding 806eaca5f1
Use feature std with rand-std
Recently we fixed a bunch of feature gates to use `rand-std` instead
of `rand` but in doing so did not notice that the same feature gates
were using `alloc` which is meaningless if `std` is enabled.

Feature gate on `std` if we are using `rand-std`.
2022-02-11 07:44:16 +00:00
Andrew Poelstra df7520e951
Merge rust-bitcoin/rust-secp256k1#340: Improve documentation
c73eb2f391 Use 'extra' instead of 'cheap' (Tobin Harding)
c79eb976ca Remove unnecessary explanation (Tobin Harding)
f95e91a6da Use isn't instead of shouldn't (Tobin Harding)
c9e6ca1680 Use rust-bitcoin module doc style (Tobin Harding)
3fa6762437 Add link to referenced commit (Tobin Harding)
f5e68f3ba7 Add ticks around code snippet (Tobin Harding)
d25431c1da Use 3rd person tense for function docs (Tobin Harding)
c3be285c1d Fix size constant docs (Tobin Harding)
5e07e7596b Add period to sentences (Tobin Harding)
269bde042f Remove unnecessary capitalisation (Tobin Harding)

Pull request description:

  In a continued effort to find my feet around here, and inspired by issue #128 I've done a codebase wide audit of the docs (primarily just rustdocs but I glanced at `//` docs as well). Each change is in a separate commit so can be removed if resistance is met. (_"resistance is futile"_).

  I've based the stylistic decisions on [work done](https://github.com/rust-bitcoin/rust-bitcoin/pull/704) in rust-bitcoin.

  I believe the only controversial change is the last (commit: da161c9 Use rust-bitcoin module doc style), please review that one carefully.

ACKs for top commit:
  apoelstra:
    ACK c73eb2f391

Tree-SHA512: 5ea215de3fd23ca2a4f25d8f8d59a85a299044fe495269c43b621291ea50c58856fa8544e36cc109b7bdb1a7a59bcab8711f30113572ddce4509d3b06ff0d3b6
2022-02-10 15:42:30 +00:00
Martin Habovstiak e6cb588a23 Breaking: changed `Parity` serialization to `u8`
Serializing the value as `u8` is more compact but this is a breaking
change.

`Visitor` was renamed to avoid hungarian notation and maybe allow other
integers in the future.
2022-02-09 20:46:20 +01:00
Martin Habovstiak 662843e73b Improved error handling in `Parity` serde impl
* Fixes error message to be according to the trait documentation
* Uses `unexpected_value` to provide more information about the error
2022-02-09 20:42:12 +01:00
Andrew Poelstra 8bf29271de
Merge rust-bitcoin/rust-secp256k1#399: Clarified conversions between `Parity` and integers
705c9cfbc1 Clarified conversions between `Parity` and integers (Martin Habovstiak)

Pull request description:

  This was discussed in https://github.com/rust-bitcoin/rust-secp256k1/pull/390#issuecomment-1033018430

ACKs for top commit:
  apoelstra:
    ACK 705c9cfbc1

Tree-SHA512: 3ba2ec566099c3c6d1c6f830e4959312b818b8766d924e3d995e6b23bd196ab747cc03d46f494ef451569188b0163f53e3236cacd20bfae9118ee76bcdbc9c02
2022-02-09 18:36:19 +00:00
Martin Habovstiak 705c9cfbc1 Clarified conversions between `Parity` and integers 2022-02-09 15:33:25 +01:00
Tobin Harding eb453b8227
Add global context API
Our API often involves a `Secp256k1` parameter, when users enable the
`global-context` feature they must then pass `SECP256K1` into these
functions. This is kind of clunky since the global is by definition
available everywhere.

Make the API more ergonomic for `global-context` builds by adding
various API functions/methods that use the global context implicitly.
2022-02-09 09:09:06 +00:00
Tobin Harding 3ecb5e41b3
Refactor from_secret_key definition
The `from_secret_key` method definition currently uses non-standard
indentation.

Improve uniformity by using 'standard' indentation.
2022-02-09 09:04:13 +00:00
Tobin Harding 5e07e7596b
Add period to sentences
Add the terminating period to all docs sentences. (Also one instance of
capitialize initial character in sentence.)
2022-02-09 07:31:53 +00:00
Tobin Harding a0465ea279 Remove feature global-context-less-secure
Instead of providing a mechanism for users to opt out of randomization
we can just feature gate the call site i.e., opportunistically randomize
the global context on creation if `rand-std` feature is enabled.
2022-02-04 08:34:39 +11:00
Tobin Harding c30026d08b Fix typo 'epected' -> 'expected'
Fix minor spelling mistake in code comments.
2022-02-03 08:36:36 +11:00
Tobin Harding f3688ecf56 Use rand-std in key rustdoc examples
Seems there is a bug in cargo, the tests in `key.rs` run successfully
but AFAICT they should fail. Here is an example, running `cargo test
--features=rand` should make this test fail but it doesn't?
```
/// Secret 256-bit key used as `x` in an ECDSA signature.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #[cfg(all(feature = "rand", any(feature =  "alloc", feature = "std")))] {
/// use secp256k1::{rand, Secp256k1, SecretKey};
///
/// let secp = Secp256k1::new();
/// let secret_key = SecretKey::new(&mut rand::thread_rng());
/// # }
/// ```

Anywho, use the correct feature gate: `rand-std`.
2022-02-01 15:21:30 +11:00
Tobin Harding ae3e06f95b Fix lint warnings in test code
Various combinations of features trigger lint warnings for unused code,
all warnings are caused by incorrect feature gating.

Correct feature gating to remove Clippy warnings during testing.
2022-02-01 15:21:30 +11:00
Tobin Harding c01cd8f1f3 Enable running tests without default features
Currently various features fail to build when enabled without default
features. This is because many tests need feature gating.

Feature gating the import statements quickly turns into spaghetti when
trying to cover all combinations of two features correctly, instead just
allow unused imports on `tests` modules where needed.

Add correct feature requirements to the examples so they also can be run
without default features.

Improve the CI script by doing:

- Add `std` to the feature matrix.
- Add `--no-default-features` to test runs in the CI script.
2022-02-01 15:20:44 +11:00
Andrew Poelstra f7d637e6aa
Merge rust-bitcoin/rust-secp256k1#376: Add examples to `key` module
aa828f01a5 Improve documentation in the key module (Tobin Harding)
9e46d6f122 Add examples to types and methods in key module (Tobin Harding)
a7f3d9bcfd Improve key module docs (Tobin Harding)
6d23614467 Improve lib.rs rustdocs (Tobin Harding)
4c4268f1ad Improve docs on method generate_keypair (Tobin Harding)

Pull request description:

  This PR is an initial attempt to more thoroughly test our public API.

  Add examples to various types/methods/functions in the key module.

  I'm not entirely sure when is enough, do we want an example on every single public method, function, and type or is this overkill. In this PR I tried to find a balance by doing ever method/function that took an argument that is a custom type from this lib. I think this should be extended to include return values too though ...

  Thanks to @thomaseizinger for the idea!

  First 2 patches are docs improvements to `lib.rs`.

ACKs for top commit:
  apoelstra:
    ACK aa828f01a5

Tree-SHA512: 9383ad263469f98ce7e988d47edc1482a09a0ce82f43d3991bd80aabdf621430f4a3c86be4debf33232dcb1d60d3e81f2c6d930ea7de7aa0e34b037accd7bc98
2022-01-25 12:34:45 +00:00
Tobin Harding aa828f01a5 Improve documentation in the key module
We recently patched much of the docs in the `key` module, lets attempt
to attain perfection.

Improve docs by doing:

- Use full stops
- Use 100 character column width
- Use plural third person tense
- Use plural for section headings
- Fix any grammar mistakes
- Use code ticks and links as appropriate
2022-01-24 14:48:46 +11:00
Tobin Harding 9e46d6f122 Add examples to types and methods in key module
Done in an effort to better test our public API.

Add tests in the `Examples` section as is idiomatic in the Rust
ecosystem.

Make other minor improvements to any rusdocs we touch:
- Use full stops
- Use 100 character column width
- Use plural third person tense
- Use plural for section headings
2022-01-24 14:48:46 +11:00
Tobin Harding a7f3d9bcfd Improve key module docs
Use 'standard' stlye, standard is defined as
- No markdown heading
- Full sentence (capital first letter and full stop)
- Trailing empty comment line
2022-01-24 14:43:44 +11:00
Tobin Harding 6fad20ef0c Fix the mess around Parity
Recently we made a wee mess with the `Parity` opaque type. Let's fix it
up by doing:

- Use an enum with variants `Even` and `Odd`.
- Add explicit conversion methods to/from u8 and i32
- Implement `BitXor`

Note: This patch is an API breaking change that does _not_ follow the
deprecation guidelines. Rust does not allow deprecating `From` impl
blocks AFAICT.
2022-01-23 10:33:51 +11:00
elsirion 1877e4db33
Add serde impl for KeyPair
The impl is added as a module instead of being a direct implementation
since it uses the global context and users should be aware that.
2022-01-18 20:10:11 +01:00
Tobin Harding 97524b2da7 Deprecate generate_schnorrsig_keypair
We have deprecated all other functions that use the identifier
'schnorrsig' but we missed `generate_schnorrsig_keypair`.

This function is purely a helper function and serves no real purpose
other than to reduce two lines of code to a single line. Downstream
users can write this function themselves if they need it.

Also, we recently added a new public method to `KeyPair` to get the
public key in a slightly more ergonomic fashion. Use `kp.public_key()`
when replacing usage of now deprecated `generate_schnorrsig_keypair`
function.
2022-01-12 18:23:40 +11:00
Tobin Harding 389abddcc7 Add method KeyPair::public_key
Currently to get the `XOnlyPublicKey` from a `KeyPair` users must do
`XOnlyPublicKey::from_keypair(&kp)`. While this does the job we can make
the lib more ergonomic by providing a method directly on `KeyPair` that
calls through to `XOnlyPublicKey::from_keypair`.

Add method `KeyPair::public_key(&self)`.
2022-01-12 18:14:19 +11:00
Tobin Harding 26921a31b8 Add lints to catch missing traits
Rustc can warn us when we forget to add `Copy` and `Deubg` trait
implementations to types.

Add lint directives to enable warnings for missing `Copy` and `Debug`
implementations. Use the newly emitted warnings to find types that do
not implement our 'standard' traits. These 'standard' traits are defined
as the set of attributes that it has been found beneficial to
opportunistically add to all types, these are

- Copy
- Clone
- Debug
- PartialEq and Eq
- PartialOrd and Ord
- Hash
2022-01-07 10:28:10 +11:00
Tobin Harding 35556e22f2 Remove useless call to format
Clippy emits:

 warning: useless use of `format!`

As suggested, remove the useless call to `format!`.
2022-01-07 10:18:49 +11:00
sanket1729 837be22e09 Basic derives for Parity 2022-01-06 23:57:26 +05:30
Andrew Poelstra 88f6baee73
Merge rust-bitcoin/rust-secp256k1#353: Documented features
18f74d5242 Clarify what does "less security" mean (Martin Habovstiak)
94c55b4d09 Fixed typos/grammar mistakes (Martin Habovštiak)
1bf05523f0 Documented features (Martin Habovstiak)

Pull request description:

  This documents the Cargo features making sure docs.rs shows warning for
  feature-gated items. They are also explicitly spelled out in the crate
  documentation.

  The PR is similar in spirit to https://github.com/rust-bitcoin/rust-bitcoin/pull/633

ACKs for top commit:
  apoelstra:
    ACK 18f74d5242

Tree-SHA512: 8aac3fc5fd8ee887d6b13606d66b3d11ce44662afb92228c4f8da6169e3f70ac6a005b328f427a91d307f8d36d091dcf24bfe4d17dfc034d02b578258719a90a
2022-01-06 15:42:32 +00:00
Martin Habovstiak 1bf05523f0 Documented features
This documents the Cargo features making sure docs.rs shows warning for
feature-gated items. They are also explicitly spelled out in the crate
documentation.
2022-01-04 16:55:01 +01:00
Tobin Harding ede114fb1a Improve docs on tweak_add_check method
It is not immediately apparent what 'err == 1' means, one must determine
that the FFI function call returns 1 for success. We can help readers of
the code by adding a 'Return' section to the method documentation.

Add trailing full stop to method docs initial line also.
2022-01-04 09:19:11 +11:00
Tobin Harding fbc64c7725 Add opaque parity type
Two functions in the FFI secp code return and accept a parity int.
Currently we are manually converting this to a bool. Doing so forces
readers of the code to think what the bool means even though
understanding this bool is not needed since in is just passed back down
to the FFI code. We can abstract this away by using an opaque type to
hold the original int and not converting it to a boolean value.

Add 'Return' and 'Error' sections to `tweak_add_assign` while fixing the
docs to describe the new opaque parity type.
2022-01-04 09:19:05 +11:00
Tobin Harding 1b768b2749 Make tweak_add_assign return statements uniform
We have two `tweak_add_assign` methods (one for keypair and one for
x-only pubkey). Both check the return value from a FFI function call.
We can make both sites uniform to _slightly_ reduce cognitive load when
reading the code.

Use C style code to make it obvious to readers that this is basically C
code.
2022-01-04 09:01:34 +11:00
Tobin Harding edafb88f8c Move key unit tests to key module
There are currently two unit tests in the `schnorr` module that are
testing keys from the `key` module. This is possible because the tests
are only testing the public interface, none the less they are better
placed in the `key` module.
2022-01-04 08:23:05 +11:00
Tobin Harding e3d21a3d87 Clean up test imports with key module
The import statements can be simplified by using an import
wildcard (`super::*`). While we are at it put them in std, external
crate, this crate order.
2022-01-04 08:18:44 +11:00
Andrew Poelstra 50034ccb18
Merge rust-bitcoin/rust-secp256k1#342: Change context objects for verification methods
21aa914ad2 Change context objects for schnorr sig methods (sanket1729)

Pull request description:

  - The current schnorrsig verify methods should operate on verify context
  as is done throughout the bitcoin core
  - Finally, and importantly the XonlyPublicKey::from_keypair now operates
  without any context parameter.

ACKs for top commit:
  apoelstra:
    ACK 21aa914ad2

Tree-SHA512: 035338f19839805a080eb262ae7b93ab187dabb63086c8b7f6015f3a6006986604dc2c6f329a99a20ddfa78c1ee518f44cd5eee2f73810fbdc83ff8df7d12506
2021-12-24 14:34:07 +00:00
sanket1729 21aa914ad2 Change context objects for schnorr sig methods
- The current schnorrsig verify methods should operate on verify context
as is done throughout the bitcoin core
- Scondly, and importantly the XonlyPublicKey::from_keypair now operates
without any context objects.
2021-12-24 00:54:06 +05:30
Dr Maxim Orlovsky de77518d3a
Serde serialization for KeyPair 2021-11-12 21:18:53 +01:00
Thomas Eizinger d244b4d747
Fix typo in docs 2021-11-11 13:43:51 +11:00
Thomas Eizinger ce4427747d
Move ECDSA functionality into ECDSA module 2021-11-11 13:43:50 +11:00
Thomas Eizinger d4fb819d80
Move `XOnlyPublicKey` to `key` module 2021-11-11 13:43:49 +11:00
Thomas Eizinger 2e0e731664
Move `KeyPair` to `key` module
The `KeyPair` type is semantically unrelated to the schnorr signature
algorithm.
2021-11-11 13:43:48 +11:00
Andrew Poelstra 6a774bd47c
Merge rust-bitcoin/rust-secp256k1#334: Use explicit u8 when assigning a byte slice
24d6f62603 Use explicit u8 when assigning a byte slice (junderw)

Pull request description:

  Is there a way to tell the compiler to not allow `[0; 64]` and require that either the type is explicitly given to the variable, or that each member uses explicit `0u8` notation?

  I noticed the usage was a mix of explicit and implicit, so I changed all to explicit.

ACKs for top commit:
  apoelstra:
    ACK 24d6f62603

Tree-SHA512: f7796dcc3ae240983257bef0f25bd0df741943f75d86e9bca7c45076af179d96ce213bd9c339a01f721f7dc9b96a0a4a56ef2cf44339f4c91d208103b7659d9f
2021-11-02 18:21:14 +00:00
junderw 24d6f62603
Use explicit u8 when assigning a byte slice 2021-10-17 10:07:51 +09:00
Dr Maxim Orlovsky 6810c2b547
Dedicated display_secret fn for secret-containing types
Debug-print secrets as tagged hashes

Refactoring Display/Debug for secret values with display_secret
2021-09-27 14:03:58 +02:00
Andrew Poelstra 24a9c9c765
Merge pull request #304 from p2pderivatives/combine-keys-test-and-doc
Add error type for combine keys + test and doc
2021-09-24 22:37:19 +00:00
Tibo-lg 674cc79d87 Add error type for combine keys + test and doc 2021-09-02 21:19:21 +09:00
Dr Maxim Orlovsky 8ee4e05e63
Removing uneeded Secp context arguments 2021-06-20 17:15:10 +02:00
Dr Maxim Orlovsky aa6bdaff3c
Creating SecretKey and PublicKey from BIP-340 KeyPair 2021-06-16 10:56:59 +02:00
Matt Corallo 940a51c2c6 Reduce cryptography usage in --cfg=fuzzing
This reduces the usage of real cryptography in --cfg=fuzzing,
specifically replacing the secret->public key derivation with a
simple copy and ECDH with XOR of the public and private parts
(plus a stream of 1s to make a test pass that expected non-0
output).

It leaves secret tweak addition/multiplication as-is.

It also changes the context creation to over-allocate and store
the context flags at the end of the context buffer, allowing us
to easily test context flags in each function.

While it would be nice to have something fancier (eg XOR-based),
its not immediately obvious how to accomplish this, and better to
fix the issues I have than spend too much time on it.

Fixes #271.

This partially reverts b811ec133a
2021-06-08 19:17:08 +00:00
Matt Corallo f2e4b297e1 Do not test secret->public derivation or pk validity in fuzzing cfg
In the next commit the secret->public key derivation in fuzzing cfg
is changed to be simpler, as well as the validity rules of public
keys relaxed.

This adds a new test to ensure random keys can be added, not just
the hard-coded keys test that exists today.
2021-06-08 19:17:07 +00:00
Andrew Poelstra e89fd5d269
Merge pull request #291 from p2pderivatives/add-combine-keys
Add combine_keys function to PublicKey
2021-06-08 18:09:35 +00:00
sanket1729 6265b2558a Fix SecretKey FromStr bug
Secret::from_str did not check if the secret key
was a valid one or not.
2021-04-26 14:17:39 -07:00
Tibo-lg 7d32182537 Add combine_keys function to PublicKey 2021-04-08 06:28:03 +09:00
Thomas Eizinger e6e23e9dd6
Rename `HexVisitor` to `FromStrVisitor`
The visitor works with all types that implement `FromStr`. Whether or
not that ends up being hex encoding depends on the implementation
of `FromStr`.
2021-01-13 09:54:33 +11:00
Thomas Eizinger b4040f0a82
Update test names to reflect what they are doing
These tests are testing more than just the signature serialization.
2021-01-12 11:52:06 +11:00
Elichai Turkel 1f08a313e5
Replace serde macros with generic visitor module
Co-authored-by: Elichai Turkel <elichai.turkel@gmail.com>
Co-authored-by: Sebastian Geisler <sebastian@blockstream.io>
2021-01-12 11:51:29 +11:00
Andrew Poelstra b31bf2f611
Merge pull request #258 from thomaseizinger/better-wasm-tests
Run more tests in wasm
2020-12-22 06:12:01 +00:00