Compare commits

..

83 Commits

Author SHA1 Message Date
merge-script
b2fdc5ccf8
Merge bitcoindevkit/rust-electrum-client#195: feat(ci): add justfile
Some checks failed
CI / Test (stable) (push) Has been cancelled
CI / Rust fmt (push) Has been cancelled
CI / Rust clippy (push) Has been cancelled
CI / Test (1.75.0) (push) Has been cancelled
df6675dc09 fix(docs): fix `bitcoin::block::Header` link (Luis Schwab)
4b98565ee2 feat(ci): add justfile (Luis Schwab)

Pull request description:

  This PR adds a `justfile` stolen from `rust-esplora-client`.

ACKs for top commit:
  oleonardolima:
    tACK df6675dc09

Tree-SHA512: 8d8f43c27631d7dc1c0eac28e01828510118a0600c762e9459b779a6423ceb6b1e3000f5c797d065a2ef6e511e2c47f6ad7bcf0182a515e573fc097e74f9e04b
2026-01-20 20:58:18 -03:00
Luis Schwab
df6675dc09
fix(docs): fix bitcoin::block::Header link 2026-01-19 17:13:06 -03:00
Luis Schwab
4b98565ee2
feat(ci): add justfile 2026-01-19 17:10:29 -03:00
merge-script
5d7be37136
Merge bitcoindevkit/rust-electrum-client#180: feat!: Change ConfigBuilder::timeout to accept Option<Duration>
5dc4bb6360 ci: bump clippy to 1.90.0 (valued mammal)
e31cf4773b feat!: Change ConfigBuilder::timeout to accept Option<Duration> (valued mammal)

Pull request description:

  Change `ConfigBuilder::timeout` to accept `Option<Duration>`. This makes the API more explicit and less error prone, as the caller no longer needs to assume the units of the given duration.

  Also updated the code to run clippy check in CI using rust 1.90.0.

  BREAKING:

  The `timeout` method on `ConfigBuilder` is changed to accept a `timeout: Option<Duration>`. Previously it was `Option<u8>`.

  fix #151
  fix #175
  Supersedes #179

ACKs for top commit:
  oleonardolima:
    ACK 5dc4bb6360

Tree-SHA512: cd6ca6fdd91dcf6f193327ca40f6d37ea8b1b548102f080d0b72a0df509f6455aa50ee43148e4746ca6b295a30a78cb7d786fb0e90c050448e96e122a5b8c92d
2025-11-10 21:32:04 -05:00
merge-script
761796c94a
Merge bitcoindevkit/rust-electrum-client#185: Release 0.24.1
Some checks failed
CI / Test (1.75.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
CI / Rust fmt (push) Has been cancelled
CI / Rust clippy (push) Has been cancelled
c2656995fc chore: Bump version to 0.24.1 (valued mammal)

Pull request description:

  Bump version to `0.24.1`.

  Update CHANGELOG.md.

ACKs for top commit:
  oleonardolima:
    ACK c2656995fc

Tree-SHA512: 1e73dc9268f0c09224df758cd84620d591f0b0b82e114dfda07507ede5c58b0c43d99d1935b301db46a162e71de35bde56c9f8d36b4d9451f90f56890b48cc07
2025-11-04 14:38:42 -05:00
valued mammal
5dc4bb6360
ci: bump clippy to 1.90.0
- Fixed hidden lifetime in `Batch::iter`
- Use `io::Error::other` in place of `io::Error::new`
when the error kind is `ErrorKind::Other`.
2025-11-03 10:10:26 -05:00
valued mammal
e31cf4773b
feat!: Change ConfigBuilder::timeout to accept Option<Duration> 2025-11-03 10:10:26 -05:00
valued mammal
c2656995fc
chore: Bump version to 0.24.1
Update CHANGELOG.md.
2025-11-03 10:06:12 -05:00
merge-script
b185259561
Merge bitcoindevkit/rust-electrum-client#183: Default to ring if multiple rustls features are set
80bf744a70 test: don't assert the value returned by `relay_fee` (valued mammal)
0e28021b3e Check in CI that we compile if all `rustls` features are set (Elias Rohrer)
980fa4afd6 Default to `ring` if multiple `rustls` features are set (Elias Rohrer)

Pull request description:

  Fixes #181

  We default to use `ring` if multiple features are set, ensuring the features are additive. To that end, we also add a check to CI that asserts we succeed to build with both features set.

  Would be cool to get a patch release for this, as it's currently breaking our docs.rs builds in `lightning-liquidity`.

ACKs for top commit:
  ValuedMammal:
    ACK 80bf744a70.
  oleonardolima:
    cACK 80bf744a70

Tree-SHA512: 0b1bacb0f3a57fd8c666e1ece14b9a733f9d5dfdec7efd6461b400d58ef0e302c286597531381e417b5fdf1b97659ed36266d2cf89f8a0c4cab5e4d9b3fdeed7
2025-11-03 09:55:26 -05:00
valued mammal
80bf744a70
test: don't assert the value returned by relay_fee
Changed `test_relay_fee` to no longer assert the value of min
relay fee, and instead assert that the value is non-zero.
This fixes a test failure likely due to some nodes now having a
smaller default min relay fee (100sat).
2025-11-03 08:04:32 -05:00
Elias Rohrer
0e28021b3e
Check in CI that we compile if all rustls features are set
We assert that we still succeed compilation if multiple `rustls`
features are set.
2025-11-03 10:49:30 +01:00
Elias Rohrer
980fa4afd6
Default to ring if multiple rustls features are set 2025-11-03 10:49:01 +01:00
merge-script
b20d41ace8
Merge bitcoindevkit/rust-electrum-client#174: chore(release): bump version to 0.24.0 and update CHANGELOG.md
Some checks failed
CI / Rust clippy (push) Has been cancelled
CI / Test (1.75.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
CI / Rust fmt (push) Has been cancelled
24d07e2cac chore(release): update `CHANGELOG.md` (Leonardo Lima)
fbffdfe65e chore(release): bump version to `0.24.0` (Leonardo Lima)

Pull request description:

  fixes #173

  - bump the crate version to `0.24.0`.
  - updates the `CHANGELOG.md` with relevant changes: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.24.0...HEAD

ACKs for top commit:
  ValuedMammal:
    ACK 24d07e2cac

Tree-SHA512: 23060238562788fbc8d4ecdb2273db25329c4f645700d4d515a8d21a98b04bb421d0c8532d1b38ff566257d4df9095299d5b539261b88d090507350f80141d86
2025-07-30 11:04:08 -04:00
Leonardo Lima
24d07e2cac
chore(release): update CHANGELOG.md 2025-07-30 11:43:53 -03:00
Leonardo Lima
fbffdfe65e
chore(release): bump version to 0.24.0 2025-07-30 11:43:44 -03:00
merge-script
dd13e4e422
Merge bitcoindevkit/rust-electrum-client#170: feat: add batch_transaction_get_merkle
74ac97cfe4 feat: add `batch_transaction_get_merkle` (Leonardo Lima)

Pull request description:

  partially addresses https://github.com/bitcoindevkit/bdk/issues/1987

  - adds the new batch method for `blockchain.transaction.get_merkle`.
  - adds a new test for `batch_transaction_get_merkle` with 3 different
    txids and block_heights.

ACKs for top commit:
  ValuedMammal:
    ACK 74ac97cfe4

Tree-SHA512: 430e07d4cb3f0dc812a389b9b093b55f934ac72d32de5eebe5e072780dc4bd82c15796ba70ff3ae9354e822fac45e479618ff76e0360bd8d887edd7b62dd1327
2025-07-29 18:45:20 -04:00
merge-script
1372898ff2
Merge bitcoindevkit/rust-electrum-client#171: Install rustls's CryptoProvider based on features
f24458248a Install `rustls`'s `CryptoProvider` based on features (Elias Rohrer)

Pull request description:

  Previously, we'd already assume `use-rustls` to use the default `aws-lc-rs` provider and `use-rustls-ring` to use the `ring` `CryptoProvider`, e.g., for `NoCertificateVerification`.

  However, we **wouldn't** actually install the respective provider based on the features, leading to a **reachable** panic at runtime when user tried to access `ssl://` Electrum servers.

  Here, we fix this omission and install the default provider according to the configured features.

  (cc @oleonardolima @thunderbiscuit)

ACKs for top commit:
  ValuedMammal:
    ACK f24458248a
  oleonardolima:
    ACK f24458248a

Tree-SHA512: b502b97e4162c0dd46e17ccf1c0a0a8461158dbec06833d7d8715072fa4feeb87beb3ee2dd93c594689ef0c2ecd84ed52a4f9309d826bebb95f3c9e57dd933fb
2025-07-23 17:14:44 -04:00
Elias Rohrer
f24458248a
Install rustls's CryptoProvider based on features
Previously, we'd already assume `use-rustls` to use the default
`aws-lc-rs` provider and `use-rustls-ring` to use the `ring`
`CryptoProvider`, e.g., for `NoCertificateVerification`.

However, we **wouldn't** actually install the respective provider based
on the features, leading to a **reachable** panic at runtime when user
tried to access `ssl://` Electrum servers.

Here, we fix this omission and install the default provider according to
the configured features.
2025-07-18 14:04:40 +02:00
Leonardo Lima
74ac97cfe4
feat: add batch_transaction_get_merkle
- adds the new batch method for `blockchain.transaction.get_merkle`.
- adds a new test for `batch_transaction_get_merkle` with 3 different
  txids and block_heights.
2025-07-14 11:09:00 -03:00
valued mammal
7de4cb758d
Merge bitcoindevkit/rust-electrum-client#169: chore(release): bump version to 0.23.1
Some checks failed
CI / Test (1.75.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
CI / Rust fmt (push) Has been cancelled
CI / Rust clippy (push) Has been cancelled
ed9784ee79 chore(release): bump version to `0.23.1` (Leonardo Lima)
e14f66b2f1 ci: use `ubuntu-latest` instead of `ubuntu-20.04` (Leonardo Lima)

Pull request description:

  fixes #168

  - updates the CI to run on `ubuntu-latest` GitHub runner, as the previously used `ubuntu-20.04` has been officially deprecated as of 2025-04-15, see: https://github.com/actions/runner-images/issues/11101.
  - updates the project version to `0.23.1`.
  - updates the `CHANGELOG.md` with changes to latest version.

ACKs for top commit:
  ValuedMammal:
    ACK ed9784ee79

Tree-SHA512: d448fc6fa2f9626dc4344ea3c8e7d1a948587f388803d923c755b454c73e4d6db860b70cba103a1092147c20656f7837e535e35eeefbead3dcb2f4260b25d839
2025-04-22 10:00:50 -04:00
Leonardo Lima
ed9784ee79
chore(release): bump version to 0.23.1
- updates the project version to `0.23.1`.
- updates the `CHANGELOG.md` with changes to latest version.
2025-04-17 17:30:39 -03:00
Leonardo Lima
e14f66b2f1
ci: use ubuntu-latest instead of ubuntu-20.04
- update the used ubuntu action runner, as `ubuntu-20.04` has been
  officially deprecated, see: https://github.com/actions/runner-images/issues/11101
2025-04-17 17:30:39 -03:00
valued mammal
862280a882
Merge bitcoindevkit/rust-electrum-client#160: fix: fix batch ordering issue
a3488f4ff9 ci: bump actions/cache to v4 (valued mammal)
0ee0a6ad7a test: add batch response ordering test (marshallyale)
6721929f22 fix: fix batch ordering issue (marshallyale)

Pull request description:

  Fixes issue #75
  This is my first open source pull request so I apologize for any formatting issues. Additionally, I don't know the repository as well as others so there may be a better way to implement the fix.

  I believe I found the root cause of this. I added a pull request to fix, but I'm going to copy/paste what I believe is causing the error.

  The main issue in the code is inside raw_client.rs inside the `recv` method implementation (snippet below):
  805ea0af30/src/raw_client.rs (L671-L685)

  When this is first called, the `self._reader_thread` will run. Inside the `self._reader_thread`, if the request id matches the response id, everything works fine. However, if the request id does not match the response id, we run the following code:
  805ea0af30/src/raw_client.rs (L602-L612)

  The channel that the response is sent back into is not unique, but rather all the channels share the same sender.clone() and receiver. The only validation that is done is to check that the request id is still being searched for inside `self.waiting_map`. This means that the receiver channel receives whatever the next response is into the channel without any validation that it matches the request id which happens here `match receiver.recv()?`.

  This is fixed by implementing unique channels for every request id. This fix can be verified with the code johnzweng used to show the issue

  If you run this with the initial code, it will error out after 1-10 cycles normally. However, after the fix this runs indefinitely.

ACKs for top commit:
  ValuedMammal:
    reACK a3488f4ff9

Tree-SHA512: c56d572c0d9e709352fde0c0438103fe4c0338e4b591d5290468b1658d6d73dbc818044e1b7ea6307e449a8d4380d9deba6adf2b89eb1dcbc119cec277fd721c
2025-03-28 12:44:41 -04:00
valued mammal
a3488f4ff9
ci: bump actions/cache to v4 2025-03-28 12:34:47 -04:00
marshallyale
0ee0a6ad7a
test: add batch response ordering test 2025-03-28 12:34:40 -04:00
marshallyale
6721929f22
fix: fix batch ordering issue
Fixes issue #75
Raw client waiting map was using the same channel
for every request/response. When items were put
back into the channel inside of _reader_thread
the waiting receiver in recv would just take the
next response without validating it on request id
request.
This fixes this by using unique channels for each
request response inside of the waiting map.
2025-03-28 12:34:28 -04:00
Lloyd Fournier
372eda9455
Merge pull request #163 from evanlinjin/electrum_api_deref
Allow types that reference `ElectrumApi` to also implement `ElectrumApi`
2025-02-24 11:29:45 +11:00
志宇
eb38c038b2
feat: allow references to ElectrumApi impls to also impl it 2025-02-08 03:27:23 +11:00
valued mammal
83747b131b
Merge bitcoindevkit/rust-electrum-client#161: chore: bump version to 0.23.0
Some checks failed
CI / Test (1.75.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
CI / Rust fmt (push) Has been cancelled
CI / Rust clippy (push) Has been cancelled
0e459b6bd6 chore: bump version to 0.23.0 (valued mammal)

Pull request description:

  Bump crate version to 0.23.0 and update `CHANGELOG.md`

ACKs for top commit:
  notmandatory:
    ACK 0e459b6bd6
  oleonardolima:
    ACK 0e459b6bd6

Tree-SHA512: b50296b65b7533114674b90991ead8446f35625931bf153f09c149f4fcd3430c412a338ff4a1aa8a9616d4f0af6706a632a5268261431dbd257e6c15929fc7dd
2025-02-04 14:10:11 -05:00
valued mammal
0e459b6bd6
chore: bump version to 0.23.0 2025-02-04 11:47:36 -05:00
Steve Myers
805ea0af30
Merge bitcoindevkit/rust-electrum-client#159: ci(msrv): bump MSRV to 1.75 and rustls to 0.23.21
3dc4daceaf ci(clippy): bump to `1.84` (Leonardo Lima)
5a476fdfd9 deps(rustls): bump to `0.23.21` (Leonardo Lima)
ec90685324 ci(msrv): bump rust MSRV to `1.75` (Leonardo Lima)

Pull request description:

  partially fixes https://github.com/bitcoindevkit/bdk/issues/1750

  It bumps the project MSRV to `1.75.0` in order to follow along with LDK changes, and to remove the pinned version of `rustls`, which now is under `1.71` MSRV, bumping it to latest `0.23.21`.

  It also updates the `clippy` step on CI to use rust `1.84`, fixing the found clippy issues.

ACKs for top commit:
  tnull:
    > ACK [3dc4dac](3dc4daceaf)
  ValuedMammal:
    ACK 3dc4dac
  notmandatory:
    ACK 3dc4daceaf

Tree-SHA512: 3b9c2feffc8cc32cb9751a36406e7f0d5ed4692afa1af186621bef93da924def3e23c5132e004deef955e40bd7c3242a2d07c33e3843b1b76b613be2f54afefe
2025-01-23 09:42:08 -06:00
Leonardo Lima
3dc4daceaf
ci(clippy): bump to 1.84
- updates the rust version on clippy step to `1.84`
- fixes the found clippy issues
2025-01-20 13:57:27 -03:00
Leonardo Lima
5a476fdfd9
deps(rustls): bump to 0.23.21 2025-01-20 13:57:26 -03:00
Leonardo Lima
ec90685324
ci(msrv): bump rust MSRV to 1.75
- bumps the MSRV on CI to 1.75.
- updates the `Cargo.toml` rust-version to 1.75.
- removes the guideline to pin `rustls` version, as previously required
  by old 1.63 MSRV.
- update `README.md` badges to `1.75` MSRV.
- update `clippy.toml` to `1.75` MSRV.
2025-01-20 13:57:25 -03:00
Steve Myers
15f753f05f
Merge bitcoindevkit/rust-electrum-client#158: chore: Enforce min rustls version to 0.23.19
ed0cdae329 chore: bump version to 0.22.1, update CHANGELOG (Steve Myers)
7ef3ff6873 chore: Enforce min `rustls` version to 0.23.19 (志宇)

Pull request description:

  `rustls` versions 0.23.18 and 0.23.19 contains fix for vulnerability RUSTSEC-2024-0399. However, 0.23.18 bumps MSRV to 1.71. 0.23.19 reverts MSRV back to 1.63.

  We enforce min `rustls` version to 0.23.19 to make it easier to compile on MSRV and ensure we include the RUSTSEC-2024-0399 fix.

  Note that in CI, I decided to pin `rustls` dependency to 0.23.19 explicitly. This is because in future versions of `rustls`, the MSRV will be changed to 1.71.

  Context: https://github.com/rustls/rustls/pull/2244

ACKs for top commit:
  notmandatory:
    ACK ed0cdae329

Tree-SHA512: 9b6319d520a1002b3404743f051019a5ff63f53a9fe37ed080ed8e761f3db3edd446d014d2145e9c098279d7b3e6e017e82dd633baeef202a904afb37c49c4d9
2024-12-05 21:34:34 -06:00
Steve Myers
ed0cdae329
chore: bump version to 0.22.1, update CHANGELOG 2024-12-05 21:28:31 -06:00
志宇
7ef3ff6873
chore: Enforce min rustls version to 0.23.19
`rustls` versions 0.23.18 and 0.23.19 contains fix for vulnerability
RUSTSEC-2024-0399. However, 0.23.18 bumps MSRV to 1.71. 0.23.19 reverts
MSRV back to 1.63.

We enforce min `rustls` version to 0.23.19 to make it easier to compile
on MSRV and ensure we include the RUSTSEC-2024-0399 fix.

Note that in CI, I decided to pin `rustls` dependency to 0.23.19
explicitly. This is because in future versions of `rustls`, the MSRV
will be changed to 1.71.
2024-12-05 21:14:43 -06:00
Steve Myers
f00b9998d1
Merge bitcoindevkit/rust-electrum-client#157: ci: pin msrv dep version for rustls
Some checks failed
CI / Rust fmt (push) Has been cancelled
CI / clippy_check (push) Has been cancelled
CI / Test (1.63.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
b0a1bfb0cb ci: pin msrv dep version for rustls (Steve Myers)

Pull request description:

  I'm not thrilled about having to pin `rustls` to meet our MSRV, but we need to make a new release and can't count on rustls/rustls#2239 being accepted by the `rustls` team.

ACKs for top commit:
  luisschwab:
    utACK b0a1bfb0cb
  ValuedMammal:
    utACK b0a1bfb0cb
  oleonardolima:
    ACK b0a1bfb0cb

Tree-SHA512: 1f37b423f3e10a7e3fa4e2072d5ad38b96341a91f78c1bcffc011dedc08071bd176b556646e40e635c3b558e6b771a4a7baa85b10d14da64d2cd385a69342ee4
2024-11-25 20:44:46 -08:00
Steve Myers
b0a1bfb0cb
ci: pin msrv dep version for rustls 2024-11-25 09:34:19 -08:00
Steve Myers
6e2a9b4b64
Merge bitcoindevkit/rust-electrum-client#156: chore: bump version to 0.22.0 and update CHANGELOG.md
43da8e9e6b chore: bump version to 0.22.0 and update CHANGELOG.md (Steve Myers)

Pull request description:

ACKs for top commit:
  LagginTimes:
    ACK 43da8e9e6b
  oleonardolima:
    ACK 43da8e9e6b

Tree-SHA512: 0acab16cce96cef3d5f10c1788d69d372395b22755344df0c5121c9d6df173af132f206959271548fbd1ced2edf81ce13a1b691f135fb11fb7438c7c7e3c90e1
2024-11-25 09:06:03 -08:00
Steve Myers
43da8e9e6b
chore: bump version to 0.22.0 and update CHANGELOG.md 2024-11-21 20:32:29 -06:00
valued mammal
3c20ca18b6
Merge bitcoindevkit/rust-electrum-client#145: Update URLs in Cargo.toml
d917f891e8 Update URLs in `Cargo.toml` (Elias Rohrer)

Pull request description:

  .. while it's still magical, the URLs seem to be outdated ..

ACKs for top commit:
  ValuedMammal:
    ACK d917f891e8

Tree-SHA512: cf652d6949d8be67f5884457f388e8fb5bc68a54d826e387dcc3542c00c2d71d62bad1dd9cb78a95f55b4f19d1beec2379540b7fea2e610a71817b8cb743f90d
2024-11-19 14:02:48 -05:00
Elias Rohrer
d917f891e8
Update URLs in Cargo.toml
.. while it's still magical, the URLs seem to be outdated ..
2024-11-19 13:52:11 -05:00
valued mammal
1fcddcba9b
Merge bitcoindevkit/rust-electrum-client#155: feat: add id_from_pos support
a871b084ec feat: add `id_from_pos` support (Wei Chen)

Pull request description:

  This PR introduces the `blockchain.transaction.id_from_pos` feature from Electrum. This functionality is essential for an ongoing implementation in `bdk_electrum`, which requires retrieving the coinbase transaction from a block at a specified `height`. Currently, there is no straightforward method to achieve this. By implementing the `id_from_pos` feature, we will effectively address this gap.

ACKs for top commit:
  oleonardolima:
    utACK a871b084ec
  ValuedMammal:
    ACK a871b084ec
  evanlinjin:
    ACK a871b084ec

Tree-SHA512: e8f1ab44473f67030b4f19e766fcee472b7cfc1dac6df8c9f0e08d966e0ed48289de03768771623b9fc7e7ef15dacdb7e3b26c04f9b0de7566d67cc7585a7fa6
2024-11-19 11:55:58 -05:00
Wei Chen
a871b084ec
feat: add id_from_pos support 2024-11-12 19:18:04 +08:00
valued mammal
6fe96fddae
Merge bitcoindevkit/rust-electrum-client#150: fix(insecure-tls): NoCertificateVerification implementation
05771a81d7 fix: `NoCertificateVerification` implementation (Leonardo Lima)

Pull request description:

  fixes #149 https://github.com/bitcoindevkit/bdk/issues/1598
  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  ### Description

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  It has been noticed some issues by both users and developers, as reported in #149, https://github.com/bitcoindevkit/bdk/issues/1598 and https://github.com/wizardsardine/liana/issues/1300, when using the library with `use-rustls-{ring}` feature to connect to electrum servers that use self-signed certificates, there are even some issues when trying to connect to `ssl://electrum.blockstream.info:50002` server.

  To connect in an insecure manner either with `rustls` or `openssl` features, the user can set the `validate_domain` field in the `Config` to false, this will either set the `SslVerifyMode::NONE` when using `openssl`, or use the custom `NoCertificateVerification` for the
  `rustls::client::danger::ServerCertVerifier` trait when using `rustls`, that said it should ignore the certificate verification when used.

  At the current library state, it's failing because we didn't set up the supported `rustls::SignatureScheme` properly, returning an empty vector at the moment. This PR focuses on fixing this issue by relying on the `CryptoProvider` in usage to get the correct and supported signature schemes.

  As part of the research to understand the problem, I've noticed that ideally, we should still use both the `rustls::webpki::verify_tls12_signature` and `rustls::webpki::verify_tls12_signature` and only rely on `rustls::client::danger::ServerCertVerified::assertion()` to ignore the certificate verification, however, it would still fail in scenarios such as https://github.com/bitcoindevkit/bdk/issues/1598 which uses X.509 certificates with any version other than 3 (it uses version 1), see [here](1a0d1646d0/src/cert.rs (L202-L218)).

  I kept the current behavior to also ignore the TLS signature, but I still would like to bring this to the discussion, should we validate it properly and update the documentation to mention the `webpki` limitation instead ?

  ### Notes to the reviewers

  I kept the current behavior to also ignore the TLS signature, but I still would like to bring this to the discussion, should we validate it properly and update the documentation to mention the `webpki` limitation instead ?

  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  - Updates the `NoCertificateVerification` implementation for the
  `rustls::client::danger::ServerCertVerifier` to use the `rustls::SignatureScheme` from `CryptoProvider` in use.

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

  #### New Features:

  * [ ] I've added tests for the new feature
  * [ ] I've added docs for the new feature

  #### Bugfixes:

  * [ ] This pull request breaks the existing API
  * [ ] I've added tests to reproduce the issue which are now passing
  * [ ] I'm linking the issue being fixed by this PR

ACKs for top commit:
  LLFourn:
    ACK 05771a81d7
  ValuedMammal:
    ACK 05771a81d7
  notmandatory:
    ACK 05771a81d7

Tree-SHA512: f74dedf458853fb19cd21dedb5b92158acd865ee0ab0fd6bbb2b3e267bac22edc7cf004d2dc0068f66d2665d87e6dd419231710a02317e3b2bfaa9f408b30759
2024-10-23 12:51:45 -04:00
Leonardo Lima
05771a81d7
fix: NoCertificateVerification implementation
It updates the `NoCertificateVerification` implementation of
`rustls::client::danger::ServerCertVerifier` trait, it keeps the usage
of both `ServerCertVerified::assertion()` and
`HandshakeSignatureValid::assertion()` usage, but now instead of having
an empty vector vector of supported `SignatureScheme`, it uses the ones
supported by the used `CryptoProvider`.
2024-09-27 14:36:14 -03:00
Steve Myers
0b97659b38
Merge bitcoindevkit/rust-electrum-client#141: Bump version to 0.21.0 and update CHANGELOG.md
Some checks failed
CI / Test (1.63.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
CI / Rust fmt (push) Has been cancelled
CI / clippy_check (push) Has been cancelled
4dd7e2135e Bump version to 0.21.0 and update CHANGELOG.md (Steve Myers)

Pull request description:

  Bumped crate version to 0.21.0 and added below to changelog:

  ## 0.21.0

   - Add use-rustls-ring feature #135
   - refactor: make validate_merkle_proof more efficient #134
   - chore: set rust edition to 2021, fix clippy, add ci fmt and clippy checks #139

  ## 0.20.0

  - Upgrade rustls to 0.23 #132
  - chore(deps): upgrade rust-bitcoin to 0.32.0 #133
  - ci: add test with MSRV 1.63.0 #128

ACKs for top commit:
  oleonardolima:
    ACK 4dd7e2135e
  ValuedMammal:
    ACK 4dd7e2135e

Tree-SHA512: 3fcec2fb437733eac235bccb1b9c8f6b706e7a713c71de85016adc93f7db128ca6eadb5e9d1d44df27f1b49cce139b222aa9c21343afcf25befdf80a47442e51
2024-08-06 16:04:34 -05:00
Steve Myers
4dd7e2135e
Bump version to 0.21.0 and update CHANGELOG.md 2024-08-06 15:43:01 -05:00
Steve Myers
9f09f50217
Merge bitcoindevkit/rust-electrum-client#139: chore: set rust edition to 2021, fix clippy, add ci fmt and clippy checks
0dd51408a3 chore(ci): add fmt and clippy checks (Steve Myers)
e7af332684 chore: fix clippy errors and set msrv to 1.63 (Steve Myers)
84f4f609b9 chore: set rust edition to 2021 (Steve Myers)

Pull request description:

  A little house keeping to avoid the warning about missing the edition. After setting the rust edition to 2021 I had to fix clippy warnings.  I also added CI fmt and clippy checks.

ACKs for top commit:
  ValuedMammal:
    ACK 0dd51408a3
  oleonardolima:
    ACK 0dd51408a3

Tree-SHA512: ee37c3ef06e217f76dcb622cdbb53e9b5c94163b789ca584037d5a8bb4bdef13c6cf251b555ac0e0ede309d7436295f1ede4e2ac6c0dc141c9bf2e3d6ecf9238
2024-08-06 15:31:10 -05:00
Steve Myers
0dd51408a3
chore(ci): add fmt and clippy checks 2024-08-06 15:06:16 -05:00
Steve Myers
e7af332684
chore: fix clippy errors and set msrv to 1.63 2024-07-31 21:37:10 -05:00
Steve Myers
84f4f609b9
chore: set rust edition to 2021 2024-07-31 18:50:13 -05:00
Steve Myers
746a0e6463
Merge bitcoindevkit/rust-electrum-client#134: refactor: make validate_merkle_proof more efficient
3a1f1bffb0 refactor: make `validate_merkle_proof` more efficient (志宇)

Pull request description:

ACKs for top commit:
  notmandatory:
    ACK 3a1f1bffb0

Tree-SHA512: 995d1582bc13d21c13b76dcd5e5edb633a59588e713b1e0aaf33363e17c47aafb22c7f250483e60cdc68e85fc94f041a0c39815160dc2592bedf959679f804dc
2024-07-31 18:20:24 -05:00
Steve Myers
54797a0be8
Merge bitcoindevkit/rust-electrum-client#135: Add use-rustls-ring feature
8d71f9597c feat: add use-rustls-ring feature (thunderbiscuit)

Pull request description:

  This PR adds the ability to build the client using the `ring` dependency for `rustls` instead of the new default `aws-lc-rs`.

  As of the [`0.23.0` release](https://github.com/rustls/rustls/releases/tag/v%2F0.23.0), rustls changed its default cryptography provider to [aws-lc-rs](https://crates.io/crates/aws-lc-rs). This new library is actually a set of bindings to a C library maintained by AWS, and they provide prebuilt bindings for [some platforms](https://aws.github.io/aws-lc-rs/platform_support.html) but not all. On these other platforms, the compilation step will attempt to build the bindings, requiring extra dependencies (CMake, libclang and others depending on the platform). This compilation step is what is currently breaking our Android and Swift builds for bdk-ffi. It is certainly possible to build the bindings (and the AWS docs on it are very nice), but for some reason I have not been able to make it work everywhere yet (local, CI, Windows).

  This PR enables us to use the previous default `ring` library for rustls. I basically have to turn off the default features on `rustls` and re-enable all of them _except_ for the `aws_lc_rs`. We also have a few feature-gated constructs in the library, for which I needed to add the new proposed `use-rustls-ring` feature in order to make all of this work for us. Let me know if there are maybe better ways to achieve this!

ACKs for top commit:
  oleonardolima:
    ACK 8d71f9597c
  notmandatory:
    ACK 8d71f9597c

Tree-SHA512: 5ea8bfac7a18700e32035518e9e8253252c8ff9064b011e14a060ac8ed7b478876ee408ce06a89af9e53de837ffa9a13fbe5030d12b48a76558fd4e8187e5651
2024-07-31 17:09:46 -05:00
thunderbiscuit
8d71f9597c
feat: add use-rustls-ring feature 2024-07-31 15:06:11 -05:00
志宇
3a1f1bffb0
refactor: make validate_merkle_proof more efficient 2024-06-18 12:03:02 +08:00
Steve Myers
64c77ee1bc
Merge bitcoindevkit/rust-electrum-client#128: ci: add test with MSRV 1.63.0
Some checks failed
CI / Test (1.63.0) (push) Has been cancelled
CI / Test (stable) (push) Has been cancelled
4b421084e9 ci: add test with MSRV 1.63.0 (Steve Myers)

Pull request description:

  Since the main BDK crates are changing to MSRV 1.63.0 as is LDK the CI for this project should also have an MSRV and test against it in CI.

  Also rustc 1.63 is the version shipped with the current debian stable (bookworm): https://packages.debian.org/stable/rust/rustc

ACKs for top commit:
  oleonardolima:
    utACK 4b421084e9
  storopoli:
    ACK 4b42108
  ValuedMammal:
    ACK 4b421084e9 looks good to me

Tree-SHA512: baff75887008a586af0ef0c4f50dd8c7c3de782f2dc6bc7d94c072c95205d4ef1a339860b3674dd781ad5558b98b071ed49b3a48507219b747e14c394dfe0a7b
2024-05-28 10:03:22 -05:00
Steve Myers
4b421084e9
ci: add test with MSRV 1.63.0 2024-05-27 12:56:17 -05:00
Steve Myers
1899234f2e
Merge bitcoindevkit/rust-electrum-client#133: chore(deps): upgrade rust-bitcoin to 0.32.0
6cf723504f deps: bump crate version to `0.20.0` (Leonardo Lima)
78cb066966 chore(deps)): upgrade `rust-bitcoin` to `0.32.0` (Leonardo Lima)

Pull request description:

  <!-- You can erase any parts of this template not applicable to your Pull Request. -->

  partially fixes [#1422](https://github.com/bitcoindevkit/bdk/issues/1422)

  ### Description

  It updates the rust-bitcoin to 0.32.0, the `bitcoin` crate dependency.

  _NOTE: The overall BDK update to `0.32.0` still requires and depends on some other crates, please refer to [#1422](https://github.com/bitcoindevkit/bdk/issues/1422)._

  <!-- Describe the purpose of this PR, what's being adding and/or fixed -->

  ### Notes to the reviewers

  It's open for any comments.
  <!-- In this section you can include notes directed to the reviewers, like explaining why some parts
  of the PR were done in a specific way -->

  ### Changelog notice

  - Update the `bitcoin` crate dependency to `0.32.0`

  <!-- Notice the release manager should include in the release tag message changelog -->
  <!-- See https://keepachangelog.com/en/1.0.0/ for examples -->

  ### Checklists

  #### All Submissions:

  * [x] I've signed all my commits
  * [x] I followed the [contribution guidelines](https://github.com/bitcoindevkit/bdk/blob/master/CONTRIBUTING.md)
  * [x] I ran `cargo fmt` and `cargo clippy` before committing

ACKs for top commit:
  notmandatory:
    utACK 6cf723504f

Tree-SHA512: c1e170d8da7687b40916b7c2de48f08ca393a2af79522abc85933bae1da6f79d2aa05d59c73b99dcbd01cc7add4def1b8a14e7858550d4e7a007c07279b45854
2024-05-27 12:54:09 -05:00
Steve Myers
1bbae7d5a0
Merge bitcoindevkit/rust-electrum-client#132: Upgrade rustls to 0.23
28b1aaa0c3 upgrade rustls to 0.23 (Nick Farrow)

Pull request description:

  With rustls 0.23 there is no longer a dependency on ring, allowing easier compilation for various targets.

  Not super confident with my updates to `ServerCertVerifier` and `Der` of certificates (is this being tested?), needs review.

ACKs for top commit:
  notmandatory:
    utACK 28b1aaa0c3

Tree-SHA512: 6561c4d20d446d86ca7a6c04ddb5a8acb136756606c82ca00e9b4a1f0eb2a3b00120d6db475f14474a89ebaa2ad600208d51c777cb5aeed0dcf62335a84fee5a
2024-05-27 12:53:26 -05:00
Leonardo Lima
6cf723504f
deps: bump crate version to 0.20.0 2024-05-14 22:09:00 -03:00
Leonardo Lima
78cb066966
chore(deps)): upgrade rust-bitcoin to 0.32.0 2024-05-14 22:08:49 -03:00
Nick Farrow
28b1aaa0c3
upgrade rustls to 0.23
* With rustls 0.23 there is no longer a dependency on ring, allowing for
  easier compilation for various targets.
2024-04-22 18:30:14 +10:00
Steve Myers
898f230081
Merge bitcoindevkit/rust-electrum-client#126: Bump version to 0.19.0 and add CHANGELOG.md
Some checks failed
CI / Test (push) Has been cancelled
ef9fd6bf50 Bump version to 0.19.0 and add CHANGELOG.md (Steve Myers)

Pull request description:

  Besides bumping the version I've also added a simple changelog that list the PRs in this (0.19.0) and the prior (0.18.0) release. The main reason for this release is the bump of the rust-bitcoin version to 0.31.0 which is needed to upgrade dependent projects like bdk to also use rust-bitcoin 0.31.0.

ACKs for top commit:
  evanlinjin:
    ACK ef9fd6bf50

Tree-SHA512: c18a0312915adfad40ef900ac4f1ee10454863f7a29882f1fa8f967f4c13df34b4e3929703614d0c3e6b8a189338f3a4d15b8d4598f68b87948454184fb13957
2023-12-19 08:38:16 -06:00
Steve Myers
ef9fd6bf50
Bump version to 0.19.0 and add CHANGELOG.md 2023-12-11 21:18:21 -06:00
Steve Myers
fd81717f8e
Merge bitcoindevkit/rust-electrum-client#125: enforce timeout on initial socks5 proxy connection
d8554fb550 enforce timeout on initial socks5 proxy connection (conduition)

Pull request description:

  This PR fixes a bug which excepted initial SOCKS5 proxy connection attempts from the punctual enforcement of timeouts.

  Before this change, invoking `Socks5Stream::connect` (or `Socks5Stream::connect_with_password`) could block for much longer than the configured timeout. In practice, this manifested as `Client::from_config` apparently failing to respect the timeout specified in the `Config` passed to it. AFAICT this only applied to SOCKS proxy connections.

  ## Example

  To demonstrate, here is a simple example program which attempts to connect to an unreachable electrum server with a 10 second timeout.
  ```rust
  use electrum_client::{Client, ConfigBuilder, Socks5Config};

  fn main() {
      let proxy = Socks5Config::new("127.0.0.1:9050");
      let config = ConfigBuilder::new()
          .socks5(Some(proxy))
          .timeout(Some(10))
          .build();

      let start = std::time::SystemTime::now();
      let result = Client::from_config(
          "tcp://bejqtnc64qttdempkczylydg7l3ordwugbdar7yqbndck53ukx7wnwad.onion:50001",
          config,
      );
      match result {
          Ok(_) => {
              println!("Successfully connected")
          }
          Err(e) => {
              println!(
                  "failed to connect after {:.2}s: {e}",
                  start.elapsed().unwrap().as_secs_f64()
              );
          }
      };
  }
  ```

  You'd expect the connection attempt to always fail at around 10 seconds, but in fact most attempts take considerably longer.

  ```
  $ for i in {1..10} ; do cargo run -q ; done
  failed to connect after 7.65s: host unreachable
  failed to connect after 47.78s: host unreachable
  failed to connect after 18.17s: host unreachable
  failed to connect after 29.24s: host unreachable
  failed to connect after 16.15s: host unreachable
  failed to connect after 14.40s: host unreachable
  failed to connect after 16.89s: host unreachable
  failed to connect after 9.93s: host unreachable
  failed to connect after 8.81s: host unreachable
  failed to connect after 17.80s: host unreachable
  ```

  ## Cause and Fix

  This was happening because the private method `Socks5Stream::connect_raw` [only respected the `timeout` parameter for _the initial connection to the proxy address_](5ecb26fd7d/src/socks/v5.rs (L200-L205)).

  Once that TCP socket is established, the SOCKS5 client code must exchange a couple of messages with the proxy itself: One request/response cycle to authenticate, and then another request/response cycle to configure the forward proxy to the ultimate destination address. The latter of these two request/response cycles could block for long periods of time, in the case where the proxy was responsive but the ultimate destination was unresponsive.

  Since no timeout was set on the socket at this stage, the `Socks5Stream` code would wait for an indefinite amount of time for a reply from the proxy, usually only once the proxy itself times out and finally sends a reply.

  My suggested fix in this PR is to set the read/write timeouts immediately on the socket connecting to the proxy, so that if the proxy doesn't reply in time, we return an error to the caller promptly.

ACKs for top commit:
  RCasatta:
    utACK d8554fb550

Tree-SHA512: 4bc0ca203465c0d9722680de7251ee49dbea6d5a2b2a833a1ed42e792342a7ac977ad72649603caacd3e58d233b1a516af1ad40c6935addb8165b720d823cf42
2023-12-08 16:11:00 -06:00
conduition
d8554fb550
enforce timeout on initial socks5 proxy connection 2023-12-07 19:05:00 +00:00
Steve Myers
91228df8a5
Merge bitcoindevkit/rust-electrum-client#121: Upgrade bitcoin
dd3c171a7a Upgrade bitcoin (Tobin C. Harding)

Pull request description:

  Upgrade bitcoin dependency to `rust-bitcoin v0.31.0-rc1`:

  Allows us to remove the dependency on `bitcoin-private` because the `hex` stuff is exposed by `bitcoin` now.

ACKs for top commit:
  notmandatory:
    ACK dd3c171a7a

Tree-SHA512: 9082d3c2136445230bb23669f83fed58c90d1baf28d35527fc3dea1d40c9d3bdebeddbc44b3bdbc8e79c9b701e09cb453c018af0bc4ac8bcd1c4a14d11c90e39
2023-12-07 11:27:10 -06:00
Tobin C. Harding
dd3c171a7a
Upgrade bitcoin
Upgrade bitcoin dependency to `rust-bitcoin v0.31.0`:

Allows us to remove the dependency on `bitcoin-private` because the
`hex` stuff is exposed by `bitcoin` now.
2023-12-07 17:16:46 +11:00
Steve Myers
e4d2b1d194
Merge bitcoindevkit/rust-electrum-client#122: Add utility to validate GetMerkleRes
54fd52d898 Add test coverage for `validate_merkle_proof` (Elias Rohrer)
fe33e19bda Add utility for validating a Merkle inclusion proof (Elias Rohrer)
dd872d6714 Make response types `Clone` (Elias Rohrer)

Pull request description:

  I recently needed to validate a Merkle inclusion proof as retrieved via `transaction_get_merkle`.

  As I figured it might be useful to other people, too, we add it here as a simple utility method.

ACKs for top commit:
  notmandatory:
    ACK 54fd52d898

Tree-SHA512: aac12160d5b91a011988f45013eb92924c2dfb244c1720e73dc5bcb731e69065c38e022502c756100d8ee6c9af06efa0de9bbfbb2b9e3c2e34d3223539206e1c
2023-12-06 22:55:03 -06:00
Steve Myers
dacd772d5e
Merge bitcoindevkit/rust-electrum-client#117: Remove webpki and bump webpki-roots to v0.25
a331ae8059 Remove `webpki` and bump `webpki-roots` to `v0.25` (Yuki Kishimoto)

Pull request description:

  I noticed that `webpki` dependency is no longer maintained and that has a high severity vulnerability.
  This PR remove the `webpki` dependency and bump `webpki-roots` to v0.25

ACKs for top commit:
  notmandatory:
    ACK a331ae8059

Tree-SHA512: 63e9498dc0d56a07e7dd09dd43ca9a924d7e9ebb09934f2c762e64c9ce163cd58edb4d1563db4eba18a0fdf22642cb7d801940baeb97b6ce5473970b739278d4
2023-12-06 22:53:02 -06:00
Steve Myers
8b31e5fe41
Merge bitcoindevkit/rust-electrum-client#94: Add Batch::raw and improve docs
adb0c7444e Add `Batch::raw` and improve docs (志宇)

Pull request description:

  Being able to add raw requests to `Batch` makes sense from an API standpoint because we already allow raw non-batched requests. This is also useful when the electrum server API gets an updated version and our client is unable to keep up.

  Additional to this, I have improved the documentation and made `Call` private (since `Call` is never used externally).

ACKs for top commit:
  notmandatory:
    ACK adb0c7444e

Tree-SHA512: 808dccf1152b750881e45a9709fb4127835ecff3da5ecccffcb9f03e62171192c58154860195db7d3d3467ae8e3e450bba845ff4e8d4dffb302c3d8d6eb837fd
2023-12-06 22:45:25 -06:00
Elias Rohrer
54fd52d898
Add test coverage for validate_merkle_proof 2023-11-10 09:51:04 +01:00
Elias Rohrer
fe33e19bda
Add utility for validating a Merkle inclusion proof
... as retrieved via `transaction_get_merkle`.
2023-11-10 09:51:04 +01:00
Elias Rohrer
dd872d6714
Make response types Clone
.. as it's convenient.
2023-10-27 16:32:51 +02:00
Yuki Kishimoto
a331ae8059
Remove webpki and bump webpki-roots to v0.25 2023-08-25 12:17:38 +02:00
Daniela Brozzoni
5ecb26fd7d
Merge bitcoindevkit/rust-electrum-client#116: Bump to version 0.18
3f6dd0c796 Bump to version 0.18 (Daniela Brozzoni)

Pull request description:

ACKs for top commit:
  RCasatta:
    ACK 3f6dd0c796

Tree-SHA512: f42f2008d79b9a0334c375652842fb2745d2481422a24f27dd4e350bcc17e47f0da2888545a344e1438ede288ed2ad0de8b359b87004fbe059f310aad886c60a
2023-08-05 21:28:48 +02:00
Daniela Brozzoni
3f6dd0c796
Bump to version 0.18
Some checks failed
CI / Test (push) Has been cancelled
2023-08-03 15:48:20 +02:00
Daniela Brozzoni
ed9bb09d02
Merge bitcoindevkit/rust-electrum-client#115: Revert "errors if expecing headers notification but not subscribed"
2d44350b44 Revert "errors if expecing headers notification but not subscribed" (Riccardo Casatta)

Pull request description:

  This reverts commit b86f2bb22c.

  Some errors started to happen in downstream tests after this commit

  #114

ACKs for top commit:
  danielabrozzoni:
    utACK 2d44350b44

Tree-SHA512: d31174055f4245cc9d99f336b166a44271067b8daecaf2bb55d507ecfa4eb557b9802d576742fba59fd4dfda3f45fc76f02d7896af31353f19fc3a38698ac5a2
2023-08-03 12:28:07 +02:00
Riccardo Casatta
2d44350b44
Revert "errors if expecing headers notification but not subscribed"
This reverts commit b86f2bb22c.

Some errors started to happen in downstream tests after this commit
2023-07-21 15:34:12 +02:00
Daniela Brozzoni
84b1435df5
Merge bitcoindevkit/rust-electrum-client#111: Bump to v0.17.0
7535debbd6 Bump to v0.17.0 (Daniela Brozzoni)

Pull request description:

ACKs for top commit:
  danielabrozzoni:
    self-ACK 7535debbd6

Tree-SHA512: 92292e6d93fcd79fd542b4153cd7689050525bb3834a556cd8e9604307f13ebb4e7012c7c4c9aee0a744046fbf9646e3b05eb93770c49b8252de7f7f2c5debbd
2023-07-13 18:51:19 -06:00
志宇
adb0c7444e
Add Batch::raw and improve docs
Being able to add raw requests to `Batch` makes sense from an API
standpoint because we already allow raw non-batched requests. This is
also useful when the electrum server API gets an updated version and our
client is unable to keep up.

Additional to this, I have improved the documentation and made `Call`
private (since `Call` is never used externally).
2023-02-14 14:16:07 +13:00
17 changed files with 1168 additions and 273 deletions

View File

@ -3,32 +3,31 @@ on: [push, pull_request]
name: CI
jobs:
test-fmt:
test:
name: Test
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
env:
TEST_ELECTRUM_SERVER: electrum.blockstream.info:50001
#TEST_ELECTRUM_SERVER: bitcoin.aranguren.org:50001
strategy:
matrix:
rust:
- stable # STABLE
- 1.75.0 # MSRV
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v4
- name: Cache
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ github.job }}-${{ hashFiles('**/Cargo.toml','**/Cargo.lock') }}
- name: Install rustup
run: curl https://sh.rustup.rs -sSf | sh -s -- -y
- name: Set default toolchain
run: $HOME/.cargo/bin/rustup default stable
- name: Set profile
run: $HOME/.cargo/bin/rustup set profile minimal
- name: Fmt
run: cargo fmt -- --check --verbose
- name: Install rust
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ matrix.rust }}
- name: Test
run: cargo test --verbose --all-features
- name: Setup iptables for the timeout test
@ -41,3 +40,32 @@ jobs:
- run: cargo check --verbose --no-default-features --features=minimal,debug-calls
- run: cargo check --verbose --no-default-features --features=proxy,use-openssl
- run: cargo check --verbose --no-default-features --features=proxy,use-rustls
- run: cargo check --verbose --no-default-features --features=proxy,use-rustls-ring
- run: cargo check --verbose --no-default-features --features=proxy,use-rustls,use-rustls-ring
fmt:
name: Rust fmt
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: stable
components: rustfmt
- name: Check fmt
run: cargo fmt --all -- --config format_code_in_doc_comments=true --check
clippy_check:
name: Rust clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@v1
with:
toolchain: 1.90.0
components: clippy
- name: Rust Cache
uses: Swatinem/rust-cache@v2.2.1
- run: cargo clippy --all-features --all-targets -- -D warnings

66
CHANGELOG.md Normal file
View File

@ -0,0 +1,66 @@
# Changelog
All notable changes to this project can be found here and in each release's git tag and can be viewed with `git tag -ln100 "v*"`.
Contributors do not need to change this file but do need to add changelog details in their PR descriptions. The person making the next release will collect changelog details from included PRs and edit this file prior to each release.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.24.1]
- Default to `ring` if multiple `rustls` features are set #183
## [0.24.0]
- Use default `CryptoProvider` if available, otherwise install `rustls`'s `CryptoProvider` based on features #171
- Add a new batch method for `blockchain.transaction.get_merkle` #170
## [0.23.1]
- Fix batch request to Electrum servers out of order responses #160
- Allow types that references to `ElectrumApi` to also implement it #163
## [0.23.0]
- Raise MSRV to `1.75` and bump `rustls` to `0.23.21` #159
- Enforce min `rustls` version 0.23.19 to support MSRV with fix for RUSTSEC-2024-0399 #158
## [0.22.0]
- Updates the NoCertificateVerification implementation for the rustls::client::danger::ServerCertVerifier to use the rustls::SignatureScheme from CryptoProvider in use #150
- Add `id_from_pos` support #155
## [0.21.0]
- Add use-rustls-ring feature #135
- refactor: make validate_merkle_proof more efficient #134
- chore: set rust edition to 2021, fix clippy, add ci fmt and clippy checks #139
## [0.20.0]
- Upgrade rustls to 0.23 #132
- chore(deps): upgrade rust-bitcoin to 0.32.0 #133
- ci: add test with MSRV 1.63.0 #128
## [0.19.0]
- Add Batch::raw and improve docs #94
- Remove webpki and bump webpki-roots to v0.25 #117
- Upgrade rust-bitcoin to v0.31.0 #121
- Add utility to validate GetMerkleRes #122
- Enforce timeout on initial socks5 proxy connection #125
## [0.18.0]
- Revert "errors if expecting headers notification but not subscribed" #115
[0.18.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.17.0...0.18.0
[0.19.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.18.0...0.19.0
[0.20.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.19.0...0.20.0
[0.21.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.20.0...0.21.0
[0.22.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.21.0...0.22.0
[0.23.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.22.0...0.23.0
[0.23.1]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.23.0...0.23.1
[0.24.0]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.23.1...0.24.0
[0.24.1]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.24.0...0.24.1
[Unreleased]: https://github.com/bitcoindevkit/rust-electrum-client/compare/0.24.1...HEAD

View File

@ -1,14 +1,16 @@
[package]
name = "electrum-client"
version = "0.17.0"
version = "0.24.1"
authors = ["Alekos Filini <alekos.filini@gmail.com>"]
license = "MIT"
homepage = "https://github.com/MagicalBitcoin/rust-electrum-client"
repository = "https://github.com/MagicalBitcoin/rust-electrum-client"
homepage = "https://github.com/bitcoindevkit/rust-electrum-client"
repository = "https://github.com/bitcoindevkit/rust-electrum-client"
documentation = "https://docs.rs/electrum-client/"
description = "Bitcoin Electrum client library. Supports plaintext, TLS and Onion servers."
keywords = ["bitcoin", "electrum"]
readme = "README.md"
rust-version = "1.75.0"
edition = "2021"
# loosely based on https://github.com/evgeniy-scherbina/rust-electrumx-client
@ -18,16 +20,14 @@ path = "src/lib.rs"
[dependencies]
log = "^0.4"
bitcoin = { version = "^0.30", features = ["serde"] }
bitcoin-private = "0.1.0"
bitcoin = { version = "0.32", features = ["serde"] }
serde = { version = "^1.0", features = ["derive"] }
serde_json = { version = "^1.0" }
# Optional dependencies
openssl = { version = "0.10", optional = true }
rustls = { version = "0.21", optional = true, features = ["dangerous_configuration"] }
webpki = { version = "0.22", optional = true }
webpki-roots = { version = "0.22", optional = true }
rustls = { version = "0.23.21", optional = true, default-features = false }
webpki-roots = { version = "0.25", optional = true }
byteorder = { version = "1.0", optional = true }
@ -42,5 +42,6 @@ default = ["proxy", "use-rustls"]
minimal = []
debug-calls = []
proxy = ["byteorder", "winapi", "libc"]
use-rustls = ["webpki", "webpki-roots", "rustls"]
use-rustls = ["webpki-roots", "rustls/default"]
use-rustls-ring = ["webpki-roots", "rustls/ring", "rustls/logging", "rustls/std", "rustls/tls12"]
use-openssl = ["openssl"]

View File

@ -1,8 +1,15 @@
# rust-electrum-client [![Build Status]][GitHub Workflow] [![Latest Version]][crates.io]
# rust-electrum-client
[![Build Status]][GitHub Workflow] [![Latest Version]][crates.io] [![MSRV Badge]][Rust Blog]
[Build Status]: https://github.com/bitcoindevkit/rust-electrum-client/actions/workflows/cont_integration.yml/badge.svg
[GitHub Workflow]: https://github.com/bitcoindevkit/rust-electrum-client/actions?query=workflow%3ACI
[Latest Version]: https://img.shields.io/crates/v/electrum-client.svg
[crates.io]: https://crates.io/crates/electrum-client
[MSRV Badge]: https://img.shields.io/badge/rustc-1.75.0%2B-lightgrey.svg
[Rust Blog]: https://blog.rust-lang.org/2023/12/28/Rust-1.75.0.html
Bitcoin Electrum client library. Supports plaintext, TLS and Onion servers.
## Minimum Supported Rust Version (MSRV)
This library should compile with any combination of features with Rust 1.75.0.

1
clippy.toml Normal file
View File

@ -0,0 +1 @@
msrv="1.75.0"

34
justfile Normal file
View File

@ -0,0 +1,34 @@
alias b := build
alias c := check
alias f := fmt
alias t := test
alias p := pre-push
_default:
@just --list
# Build the project
build:
cargo build
# Check code: formatting, compilation, linting, doc comments, and commit signature
check:
cargo +nightly fmt --all -- --check
cargo check --all-features --all-targets
cargo clippy --all-features --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --all-features --no-deps
@[ "$(git log --pretty='format:%G?' -1 HEAD)" = "N" ] && \
echo "\n⚠ Unsigned commit: BDK requires that commits be signed." || \
true
# Format all code
fmt:
cargo +nightly fmt
# Run all tests on the workspace with all features
test:
cargo test --all-features -- --test-threads=1
# Run pre-push suite: format, check, and test
pre-push: fmt check test

View File

@ -2,12 +2,185 @@
use std::borrow::Borrow;
use std::convert::TryInto;
use std::ops::Deref;
use bitcoin::consensus::encode::{deserialize, serialize};
use bitcoin::{block, Script, Transaction, Txid};
use batch::Batch;
use types::*;
use crate::batch::Batch;
use crate::types::*;
impl<E: Deref> ElectrumApi for E
where
E::Target: ElectrumApi,
{
fn raw_call(
&self,
method_name: &str,
params: impl IntoIterator<Item = Param>,
) -> Result<serde_json::Value, Error> {
(**self).raw_call(method_name, params)
}
fn batch_call(&self, batch: &Batch) -> Result<Vec<serde_json::Value>, Error> {
(**self).batch_call(batch)
}
fn block_headers_subscribe_raw(&self) -> Result<RawHeaderNotification, Error> {
(**self).block_headers_subscribe_raw()
}
fn block_headers_pop_raw(&self) -> Result<Option<RawHeaderNotification>, Error> {
(**self).block_headers_pop_raw()
}
fn block_header_raw(&self, height: usize) -> Result<Vec<u8>, Error> {
(**self).block_header_raw(height)
}
fn block_headers(&self, start_height: usize, count: usize) -> Result<GetHeadersRes, Error> {
(**self).block_headers(start_height, count)
}
fn estimate_fee(&self, number: usize) -> Result<f64, Error> {
(**self).estimate_fee(number)
}
fn relay_fee(&self) -> Result<f64, Error> {
(**self).relay_fee()
}
fn script_subscribe(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
(**self).script_subscribe(script)
}
fn batch_script_subscribe<'s, I>(&self, scripts: I) -> Result<Vec<Option<ScriptStatus>>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<&'s Script>,
{
(**self).batch_script_subscribe(scripts)
}
fn script_unsubscribe(&self, script: &Script) -> Result<bool, Error> {
(**self).script_unsubscribe(script)
}
fn script_pop(&self, script: &Script) -> Result<Option<ScriptStatus>, Error> {
(**self).script_pop(script)
}
fn script_get_balance(&self, script: &Script) -> Result<GetBalanceRes, Error> {
(**self).script_get_balance(script)
}
fn batch_script_get_balance<'s, I>(&self, scripts: I) -> Result<Vec<GetBalanceRes>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<&'s Script>,
{
(**self).batch_script_get_balance(scripts)
}
fn script_get_history(&self, script: &Script) -> Result<Vec<GetHistoryRes>, Error> {
(**self).script_get_history(script)
}
fn batch_script_get_history<'s, I>(&self, scripts: I) -> Result<Vec<Vec<GetHistoryRes>>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<&'s Script>,
{
(**self).batch_script_get_history(scripts)
}
fn script_list_unspent(&self, script: &Script) -> Result<Vec<ListUnspentRes>, Error> {
(**self).script_list_unspent(script)
}
fn batch_script_list_unspent<'s, I>(
&self,
scripts: I,
) -> Result<Vec<Vec<ListUnspentRes>>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<&'s Script>,
{
(**self).batch_script_list_unspent(scripts)
}
fn transaction_get_raw(&self, txid: &Txid) -> Result<Vec<u8>, Error> {
(**self).transaction_get_raw(txid)
}
fn batch_transaction_get_raw<'t, I>(&self, txids: I) -> Result<Vec<Vec<u8>>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<&'t Txid>,
{
(**self).batch_transaction_get_raw(txids)
}
fn batch_block_header_raw<I>(&self, heights: I) -> Result<Vec<Vec<u8>>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<u32>,
{
(**self).batch_block_header_raw(heights)
}
fn batch_estimate_fee<I>(&self, numbers: I) -> Result<Vec<f64>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<usize>,
{
(**self).batch_estimate_fee(numbers)
}
fn transaction_broadcast_raw(&self, raw_tx: &[u8]) -> Result<Txid, Error> {
(**self).transaction_broadcast_raw(raw_tx)
}
fn transaction_get_merkle(&self, txid: &Txid, height: usize) -> Result<GetMerkleRes, Error> {
(**self).transaction_get_merkle(txid, height)
}
fn batch_transaction_get_merkle<I>(
&self,
txids_and_heights: I,
) -> Result<Vec<GetMerkleRes>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<(Txid, usize)>,
{
(**self).batch_transaction_get_merkle(txids_and_heights)
}
fn txid_from_pos(&self, height: usize, tx_pos: usize) -> Result<Txid, Error> {
(**self).txid_from_pos(height, tx_pos)
}
fn txid_from_pos_with_merkle(
&self,
height: usize,
tx_pos: usize,
) -> Result<TxidFromPosRes, Error> {
(**self).txid_from_pos_with_merkle(height, tx_pos)
}
fn server_features(&self) -> Result<ServerFeaturesRes, Error> {
(**self).server_features()
}
fn ping(&self) -> Result<(), Error> {
(**self).ping()
}
#[cfg(feature = "debug-calls")]
fn calls_made(&self) -> Result<usize, Error> {
(**self).calls_made()
}
}
/// API calls exposed by an Electrum client
pub trait ElectrumApi {
@ -200,6 +373,28 @@ pub trait ElectrumApi {
/// Returns the merkle path for the transaction `txid` confirmed in the block at `height`.
fn transaction_get_merkle(&self, txid: &Txid, height: usize) -> Result<GetMerkleRes, Error>;
/// Batch version of [`transaction_get_merkle`](#method.transaction_get_merkle).
///
/// Take a list of `(txid, height)`, for transactions with `txid` confirmed in the block at `height`.
fn batch_transaction_get_merkle<I>(
&self,
txids_and_heights: I,
) -> Result<Vec<GetMerkleRes>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<(Txid, usize)>;
/// Returns a transaction hash, given a block `height` and a `tx_pos` in the block.
fn txid_from_pos(&self, height: usize, tx_pos: usize) -> Result<Txid, Error>;
/// Returns a transaction hash and a merkle path, given a block `height` and a `tx_pos` in the
/// block.
fn txid_from_pos_with_merkle(
&self,
height: usize,
tx_pos: usize,
) -> Result<TxidFromPosRes, Error>;
/// Returns the capabilities of the server.
fn server_features(&self) -> Result<ServerFeaturesRes, Error>;
@ -211,3 +406,225 @@ pub trait ElectrumApi {
/// Returns the number of network calls made since the creation of the client.
fn calls_made(&self) -> Result<usize, Error>;
}
#[cfg(test)]
mod test {
use std::{borrow::Cow, sync::Arc};
use super::ElectrumApi;
#[derive(Debug, Clone)]
struct FakeApi;
impl ElectrumApi for FakeApi {
fn raw_call(
&self,
_: &str,
_: impl IntoIterator<Item = super::Param>,
) -> Result<serde_json::Value, super::Error> {
unreachable!()
}
fn batch_call(&self, _: &crate::Batch) -> Result<Vec<serde_json::Value>, super::Error> {
unreachable!()
}
fn block_headers_subscribe_raw(
&self,
) -> Result<super::RawHeaderNotification, super::Error> {
unreachable!()
}
fn block_headers_pop_raw(
&self,
) -> Result<Option<super::RawHeaderNotification>, super::Error> {
unreachable!()
}
fn block_header_raw(&self, _: usize) -> Result<Vec<u8>, super::Error> {
unreachable!()
}
fn block_headers(&self, _: usize, _: usize) -> Result<super::GetHeadersRes, super::Error> {
unreachable!()
}
fn estimate_fee(&self, _: usize) -> Result<f64, super::Error> {
unreachable!()
}
fn relay_fee(&self) -> Result<f64, super::Error> {
unreachable!()
}
fn script_subscribe(
&self,
_: &bitcoin::Script,
) -> Result<Option<super::ScriptStatus>, super::Error> {
unreachable!()
}
fn batch_script_subscribe<'s, I>(
&self,
_: I,
) -> Result<Vec<Option<super::ScriptStatus>>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<&'s bitcoin::Script>,
{
unreachable!()
}
fn script_unsubscribe(&self, _: &bitcoin::Script) -> Result<bool, super::Error> {
unreachable!()
}
fn script_pop(
&self,
_: &bitcoin::Script,
) -> Result<Option<super::ScriptStatus>, super::Error> {
unreachable!()
}
fn script_get_balance(
&self,
_: &bitcoin::Script,
) -> Result<super::GetBalanceRes, super::Error> {
unreachable!()
}
fn batch_script_get_balance<'s, I>(
&self,
_: I,
) -> Result<Vec<super::GetBalanceRes>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<&'s bitcoin::Script>,
{
unreachable!()
}
fn script_get_history(
&self,
_: &bitcoin::Script,
) -> Result<Vec<super::GetHistoryRes>, super::Error> {
unreachable!()
}
fn batch_script_get_history<'s, I>(
&self,
_: I,
) -> Result<Vec<Vec<super::GetHistoryRes>>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<&'s bitcoin::Script>,
{
unreachable!()
}
fn script_list_unspent(
&self,
_: &bitcoin::Script,
) -> Result<Vec<super::ListUnspentRes>, super::Error> {
unreachable!()
}
fn batch_script_list_unspent<'s, I>(
&self,
_: I,
) -> Result<Vec<Vec<super::ListUnspentRes>>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<&'s bitcoin::Script>,
{
unreachable!()
}
fn transaction_get_raw(&self, _: &bitcoin::Txid) -> Result<Vec<u8>, super::Error> {
unreachable!()
}
fn batch_transaction_get_raw<'t, I>(&self, _: I) -> Result<Vec<Vec<u8>>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<&'t bitcoin::Txid>,
{
unreachable!()
}
fn batch_block_header_raw<I>(&self, _: I) -> Result<Vec<Vec<u8>>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<u32>,
{
unreachable!()
}
fn batch_estimate_fee<I>(&self, _: I) -> Result<Vec<f64>, super::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<usize>,
{
unreachable!()
}
fn transaction_broadcast_raw(&self, _: &[u8]) -> Result<bitcoin::Txid, super::Error> {
unreachable!()
}
fn transaction_get_merkle(
&self,
_: &bitcoin::Txid,
_: usize,
) -> Result<super::GetMerkleRes, super::Error> {
unreachable!()
}
fn batch_transaction_get_merkle<I>(
&self,
_: I,
) -> Result<Vec<crate::GetMerkleRes>, crate::Error>
where
I: IntoIterator + Clone,
I::Item: std::borrow::Borrow<(bitcoin::Txid, usize)>,
{
unreachable!()
}
fn txid_from_pos(&self, _: usize, _: usize) -> Result<bitcoin::Txid, super::Error> {
unreachable!()
}
fn txid_from_pos_with_merkle(
&self,
_: usize,
_: usize,
) -> Result<super::TxidFromPosRes, super::Error> {
unreachable!()
}
fn server_features(&self) -> Result<super::ServerFeaturesRes, super::Error> {
unreachable!()
}
fn ping(&self) -> Result<(), super::Error> {
unreachable!()
}
#[cfg(feature = "debug-calls")]
fn calls_made(&self) -> Result<usize, super::Error> {
unreachable!()
}
}
fn is_impl<A: ElectrumApi>() {}
#[test]
fn deref() {
is_impl::<FakeApi>();
is_impl::<&FakeApi>();
is_impl::<Arc<FakeApi>>();
is_impl::<Box<FakeApi>>();
is_impl::<Cow<FakeApi>>();
}
}

View File

@ -4,7 +4,7 @@
use bitcoin::{Script, Txid};
use types::{Call, Param, ToElectrumScriptHash};
use crate::types::{Call, Param, ToElectrumScriptHash};
/// Helper structure that caches all the requests before they are actually sent to the server.
///
@ -16,11 +16,17 @@ use types::{Call, Param, ToElectrumScriptHash};
/// [`Client`](../client/struct.Client.html), like
/// [`batch_script_get_balance`](../client/struct.Client.html#method.batch_script_get_balance) to ask the
/// server for the balance of multiple scripts with a single request.
#[derive(Default)]
pub struct Batch {
calls: Vec<Call>,
}
impl Batch {
/// Add a raw request to the batch queue
pub fn raw(&mut self, method: String, params: Vec<Param>) {
self.calls.push((method, params));
}
/// Add one `blockchain.scripthash.listunspent` request to the batch queue
pub fn script_list_unspent(&mut self, script: &Script) {
let params = vec![Param::String(script.to_electrum_scripthash().to_hex())];
@ -56,6 +62,17 @@ impl Batch {
.push((String::from("blockchain.transaction.get"), params));
}
/// Add one `blockchain.transaction.get_merkle` request to the batch queue
pub fn transaction_get_merkle(&mut self, tx_hash_and_height: &(Txid, usize)) {
let (tx_hash, height) = tx_hash_and_height;
let params = vec![
Param::String(format!("{:x}", tx_hash)),
Param::Usize(*height),
];
self.calls
.push((String::from("blockchain.transaction.get_merkle"), params));
}
/// Add one `blockchain.estimatefee` request to the batch queue
pub fn estimate_fee(&mut self, number: usize) {
let params = vec![Param::Usize(number)];
@ -71,7 +88,7 @@ impl Batch {
}
/// Returns an iterator on the batch
pub fn iter(&self) -> BatchIter {
pub fn iter(&self) -> BatchIter<'_> {
BatchIter {
batch: self,
index: 0,
@ -102,9 +119,3 @@ impl<'a> std::iter::Iterator for BatchIter<'a> {
val
}
}
impl std::default::Default for Batch {
fn default() -> Self {
Batch { calls: Vec::new() }
}
}

View File

@ -6,12 +6,12 @@ use log::{info, warn};
use bitcoin::{Script, Txid};
use api::ElectrumApi;
use batch::Batch;
use config::Config;
use raw_client::*;
use crate::api::ElectrumApi;
use crate::batch::Batch;
use crate::config::Config;
use crate::raw_client::*;
use crate::types::*;
use std::convert::TryFrom;
use types::*;
/// Generalized Electrum client that supports multiple backends. This wraps
/// [`RawClient`](client/struct.RawClient.html) and provides a more user-friendly
@ -49,7 +49,7 @@ macro_rules! impl_inner_call {
drop(read_client);
match res {
Ok(val) => return Ok(val),
Err(Error::Protocol(_) | Error::AlreadySubscribed(_) | Error::NotSubscribed(_) | Error::NotSubscribedToHeaders) => {
Err(Error::Protocol(_) | Error::AlreadySubscribed(_)) => {
return res;
},
Err(e) => {
@ -148,7 +148,6 @@ impl Client {
/// If no prefix is specified, then `tcp://` is assumed.
///
/// See [Client::from_config] for more configuration options
///
pub fn new(url: &str) -> Result<Self, Error> {
Self::from_config(url, Config::default())
}
@ -328,6 +327,36 @@ impl ElectrumApi for Client {
impl_inner_call!(self, transaction_get_merkle, txid, height)
}
#[inline]
fn batch_transaction_get_merkle<I>(
&self,
txids_and_heights: I,
) -> Result<Vec<GetMerkleRes>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<(Txid, usize)>,
{
impl_inner_call!(
self,
batch_transaction_get_merkle,
txids_and_heights.clone()
)
}
#[inline]
fn txid_from_pos(&self, height: usize, tx_pos: usize) -> Result<Txid, Error> {
impl_inner_call!(self, txid_from_pos, height, tx_pos)
}
#[inline]
fn txid_from_pos_with_merkle(
&self,
height: usize,
tx_pos: usize,
) -> Result<TxidFromPosRes, Error> {
impl_inner_call!(self, txid_from_pos_with_merkle, height, tx_pos)
}
#[inline]
fn server_features(&self) -> Result<ServerFeaturesRes, Error> {
impl_inner_call!(self, server_features)
@ -353,7 +382,7 @@ mod tests {
fn more_failed_attempts_than_retries_means_exhausted() {
let exhausted = retries_exhausted(10, 5);
assert_eq!(exhausted, true)
assert!(exhausted)
}
#[test]
@ -362,21 +391,21 @@ mod tests {
let exhausted = retries_exhausted(failed_attempts, u8::MAX);
assert_eq!(exhausted, true)
assert!(exhausted)
}
#[test]
fn less_failed_attempts_means_not_exhausted() {
let exhausted = retries_exhausted(2, 5);
assert_eq!(exhausted, false)
assert!(!exhausted)
}
#[test]
fn attempts_equals_retries_means_not_exhausted_yet() {
let exhausted = retries_exhausted(2, 2);
assert_eq!(exhausted, false)
assert!(!exhausted)
}
#[test]
@ -408,7 +437,7 @@ mod tests {
sender.send(()).unwrap();
for _stream in listener.incoming() {
loop {}
std::thread::sleep(Duration::from_secs(60))
}
});
@ -419,7 +448,9 @@ mod tests {
let now = Instant::now();
let client = Client::from_config(
&endpoint,
crate::config::ConfigBuilder::new().timeout(Some(5)).build(),
crate::config::ConfigBuilder::new()
.timeout(Some(Duration::from_secs(5)))
.build(),
);
let elapsed = now.elapsed();

View File

@ -1,5 +1,11 @@
use std::time::Duration;
/// Configuration for an electrum client
///
/// Refer to [`Client::from_config`] and [`ClientType::from_config`].
///
/// [`Client::from_config`]: crate::Client::from_config
/// [`ClientType::from_config`]: crate::ClientType::from_config
#[derive(Debug, Clone)]
pub struct Config {
/// Proxy socks5 configuration, default None
@ -49,8 +55,8 @@ impl ConfigBuilder {
}
/// Sets the timeout
pub fn timeout(mut self, timeout: Option<u8>) -> Self {
self.config.timeout = timeout.map(|t| Duration::from_secs(t as u64));
pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
self.config.timeout = timeout;
self
}
@ -97,19 +103,35 @@ impl Socks5Config {
}
impl Config {
/// Get the configuration for `socks5`
///
/// Set this with [`ConfigBuilder::socks5`]
pub fn socks5(&self) -> &Option<Socks5Config> {
&self.socks5
}
/// Get the configuration for `retry`
///
/// Set this with [`ConfigBuilder::retry`]
pub fn retry(&self) -> u8 {
self.retry
}
/// Get the configuration for `timeout`
///
/// Set this with [`ConfigBuilder::timeout`]
pub fn timeout(&self) -> Option<Duration> {
self.timeout
}
/// Get the configuration for `validate_domain`
///
/// Set this with [`ConfigBuilder::validate_domain`]
pub fn validate_domain(&self) -> bool {
self.validate_domain
}
/// Convenience method for calling [`ConfigBuilder::new`]
pub fn builder() -> ConfigBuilder {
ConfigBuilder::new()
}

View File

@ -20,22 +20,27 @@
//! ```
pub extern crate bitcoin;
extern crate bitcoin_private;
extern crate core;
extern crate log;
#[cfg(feature = "use-openssl")]
extern crate openssl;
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
any(
feature = "default",
feature = "use-rustls",
feature = "use-rustls-ring"
),
not(feature = "use-openssl")
))]
extern crate rustls;
extern crate serde;
extern crate serde_json;
#[cfg(any(feature = "use-rustls", feature = "default"))]
extern crate webpki;
#[cfg(any(feature = "use-rustls", feature = "default"))]
#[cfg(any(
feature = "default",
feature = "use-rustls",
feature = "use-rustls-ring"
))]
extern crate webpki_roots;
#[cfg(any(feature = "default", feature = "proxy"))]
@ -54,7 +59,8 @@ mod batch;
#[cfg(any(
all(feature = "proxy", feature = "use-openssl"),
all(feature = "proxy", feature = "use-rustls")
all(feature = "proxy", feature = "use-rustls"),
all(feature = "proxy", feature = "use-rustls-ring")
))]
pub mod client;
@ -63,12 +69,14 @@ mod config;
pub mod raw_client;
mod stream;
mod types;
pub mod utils;
pub use api::ElectrumApi;
pub use batch::Batch;
#[cfg(any(
all(feature = "proxy", feature = "use-openssl"),
all(feature = "proxy", feature = "use-rustls")
all(feature = "proxy", feature = "use-rustls"),
all(feature = "proxy", feature = "use-rustls-ring")
))]
pub use client::*;
pub use config::{Config, ConfigBuilder, Socks5Config};

View File

@ -3,7 +3,7 @@
//! This module contains the definition of the raw client that wraps the transport method
use std::borrow::Borrow;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::mem::drop;
use std::net::{TcpStream, ToSocketAddrs};
@ -16,28 +16,34 @@ use std::time::Duration;
use log::{debug, error, info, trace, warn};
use bitcoin::consensus::encode::deserialize;
use bitcoin::hashes::hex::FromHex;
use bitcoin::hex::{DisplayHex, FromHex};
use bitcoin::{Script, Txid};
use bitcoin_private::hex::exts::DisplayHex;
#[cfg(feature = "use-openssl")]
use openssl::ssl::{SslConnector, SslMethod, SslStream, SslVerifyMode};
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
any(
feature = "default",
feature = "use-rustls",
feature = "use-rustls-ring"
),
not(feature = "use-openssl")
))]
use rustls::{
ClientConfig, ClientConnection, OwnedTrustAnchor, RootCertStore, ServerName, StreamOwned,
pki_types::ServerName,
pki_types::{Der, TrustAnchor},
ClientConfig, ClientConnection, RootCertStore, StreamOwned,
};
#[cfg(any(feature = "default", feature = "proxy"))]
use crate::socks::{Socks5Stream, TargetAddr, ToTargetAddr};
use stream::ClonableStream;
use crate::stream::ClonableStream;
use api::ElectrumApi;
use batch::Batch;
use types::*;
use crate::api::ElectrumApi;
use crate::batch::Batch;
use crate::types::*;
macro_rules! impl_batch_call {
( $self:expr, $data:expr, $call:ident ) => {{
@ -77,7 +83,7 @@ pub trait ToSocketAddrsDomain: ToSocketAddrs {
impl ToSocketAddrsDomain for &str {
fn domain(&self) -> Option<&str> {
self.splitn(2, ':').next()
self.split(':').next()
}
}
@ -133,7 +139,7 @@ where
last_id: AtomicUsize,
waiting_map: Mutex<HashMap<usize, Sender<ChannelMessage>>>,
headers: Mutex<Option<VecDeque<RawHeaderNotification>>>,
headers: Mutex<VecDeque<RawHeaderNotification>>,
script_notifications: Mutex<HashMap<ScriptHash, VecDeque<ScriptStatus>>>,
#[cfg(feature = "debug-calls")]
@ -154,7 +160,7 @@ where
last_id: AtomicUsize::new(0),
waiting_map: Mutex::new(HashMap::new()),
headers: Mutex::new(None),
headers: Mutex::new(VecDeque::new()),
script_notifications: Mutex::new(HashMap::new()),
#[cfg(feature = "debug-calls")]
@ -284,40 +290,81 @@ impl RawClient<ElectrumSslStream> {
}
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
any(
feature = "default",
feature = "use-rustls",
feature = "use-rustls-ring"
),
not(feature = "use-openssl")
))]
mod danger {
use rustls;
use rustls::client::ServerCertVerified;
use rustls::{Certificate, Error, ServerName};
use std::time::SystemTime;
use crate::raw_client::ServerName;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified};
use rustls::crypto::CryptoProvider;
use rustls::pki_types::{CertificateDer, UnixTime};
use rustls::DigitallySignedStruct;
pub struct NoCertificateVerification {}
#[derive(Debug)]
pub struct NoCertificateVerification(CryptoProvider);
impl rustls::client::ServerCertVerifier for NoCertificateVerification {
impl NoCertificateVerification {
pub fn new(provider: CryptoProvider) -> Self {
Self(provider)
}
}
impl rustls::client::danger::ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_end_entity: &Certificate,
_intermediates: &[Certificate],
_server_name: &ServerName,
_scts: &mut dyn Iterator<Item = &[u8]>,
_ocsp_response: &[u8],
_now: SystemTime,
) -> Result<ServerCertVerified, Error> {
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
Ok(ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
Ok(HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.0.signature_verification_algorithms.supported_schemes()
}
}
}
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
any(
feature = "default",
feature = "use-rustls",
feature = "use-rustls-ring"
),
not(feature = "use-openssl")
))]
/// Transport type used to establish a Rustls TLS encrypted/authenticated connection with the server
pub type ElectrumSslStream = StreamOwned<ClientConnection, TcpStream>;
#[cfg(all(
any(feature = "default", feature = "use-rustls"),
any(
feature = "default",
feature = "use-rustls",
feature = "use-rustls-ring"
),
not(feature = "use-openssl")
))]
impl RawClient<ElectrumSslStream> {
@ -359,26 +406,53 @@ impl RawClient<ElectrumSslStream> {
) -> Result<Self, Error> {
use std::convert::TryFrom;
let builder = ClientConfig::builder().with_safe_defaults();
if rustls::crypto::CryptoProvider::get_default().is_none() {
// We install a crypto provider depending on the set feature.
#[cfg(all(feature = "use-rustls", not(feature = "use-rustls-ring")))]
rustls::crypto::CryptoProvider::install_default(
rustls::crypto::aws_lc_rs::default_provider(),
)
.map_err(|_| {
Error::CouldNotCreateConnection(rustls::Error::General(
"Failed to install CryptoProvider".to_string(),
))
})?;
#[cfg(feature = "use-rustls-ring")]
rustls::crypto::CryptoProvider::install_default(
rustls::crypto::ring::default_provider(),
)
.map_err(|_| {
Error::CouldNotCreateConnection(rustls::Error::General(
"Failed to install CryptoProvider".to_string(),
))
})?;
}
let builder = ClientConfig::builder();
let config = if validate_domain {
socket_addr.domain().ok_or(Error::MissingDomain)?;
let mut store = RootCertStore::empty();
store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.into_iter().map(|t| {
OwnedTrustAnchor::from_subject_spki_name_constraints(
t.subject,
t.spki,
t.name_constraints,
)
}));
let store = webpki_roots::TLS_SERVER_ROOTS
.iter()
.map(|t| TrustAnchor {
subject: Der::from_slice(t.subject),
subject_public_key_info: Der::from_slice(t.spki),
name_constraints: t.name_constraints.map(Der::from_slice),
})
.collect::<RootCertStore>();
// TODO: cert pinning
builder.with_root_certificates(store).with_no_client_auth()
} else {
builder
.dangerous()
.with_custom_certificate_verifier(std::sync::Arc::new(
danger::NoCertificateVerification {},
#[cfg(all(feature = "use-rustls", not(feature = "use-rustls-ring")))]
danger::NoCertificateVerification::new(rustls::crypto::aws_lc_rs::default_provider()),
#[cfg(feature = "use-rustls-ring")]
danger::NoCertificateVerification::new(rustls::crypto::ring::default_provider()),
))
.with_no_client_auth()
};
@ -386,7 +460,7 @@ impl RawClient<ElectrumSslStream> {
let domain = socket_addr.domain().unwrap_or("NONE").to_string();
let session = ClientConnection::new(
std::sync::Arc::new(config),
ServerName::try_from(domain.as_str())
ServerName::try_from(domain.clone())
.map_err(|_| Error::InvalidDNSNameError(domain.clone()))?,
)
.map_err(Error::CouldNotCreateConnection)?;
@ -425,7 +499,11 @@ impl RawClient<ElectrumProxyStream> {
Ok(stream.into())
}
#[cfg(any(feature = "use-openssl", feature = "use-rustls"))]
#[cfg(any(
feature = "use-openssl",
feature = "use-rustls",
feature = "use-rustls-ring"
))]
/// Creates a new TLS client that connects to `target_addr` using `proxy_addr` as a socks proxy
/// server. The DNS resolution of `target_addr`, if required, is done through the proxy. This
/// allows to specify, for instance, `.onion` addresses.
@ -484,11 +562,10 @@ impl<S: Read + Write> RawClient<S> {
if let Some(until_message) = until_message {
// If we are trying to start a reader thread but the corresponding sender is
// missing from the map, exit immediately. This can happen with batch calls,
// since the sender is shared for all the individual queries in a call. We
// might have already received a response for that id, but we don't know it
// yet. Exiting here forces the calling code to fallback to the sender-receiver
// method, and it should find a message there waiting for it.
// missing from the map, exit immediately. We might have already received a
// response for that id, but we don't know it yet. Exiting here forces the
// calling code to fallback to the sender-receiver method, and it should find
// a message there waiting for it.
if self.waiting_map.lock()?.get(&until_message).is_none() {
return Err(Error::CouldntLockReader);
}
@ -559,7 +636,7 @@ impl<S: Read + Write> RawClient<S> {
// No id, that's probably a notification.
let mut resp = resp;
if let Some(ref method) = resp["method"].take().as_str() {
if let Some(method) = resp["method"].take().as_str() {
self.handle_notification(method, resp["params"].take())?;
} else {
warn!("Unexpected response: {:?}", resp);
@ -648,17 +725,11 @@ impl<S: Read + Write> RawClient<S> {
fn handle_notification(&self, method: &str, result: serde_json::Value) -> Result<(), Error> {
match method {
"blockchain.headers.subscribe" => {
let mut queue = self.headers.lock()?;
match queue.as_mut() {
None => return Err(Error::NotSubscribedToHeaders),
Some(queue) => queue.append(
&mut serde_json::from_value::<Vec<RawHeaderNotification>>(result)?
.into_iter()
.collect(),
),
}
}
"blockchain.headers.subscribe" => self.headers.lock()?.append(
&mut serde_json::from_value::<Vec<RawHeaderNotification>>(result)?
.into_iter()
.collect(),
),
"blockchain.scripthash.subscribe" => {
let unserialized: ScriptNotification = serde_json::from_value(result)?;
let mut script_notifications = self.script_notifications.lock()?;
@ -682,7 +753,7 @@ impl<S: Read + Write> RawClient<S> {
) -> Result<serde_json::Value, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
&method_name,
method_name,
params,
);
let result = self.call(req)?;
@ -713,22 +784,23 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
fn batch_call(&self, batch: &Batch) -> Result<Vec<serde_json::Value>, Error> {
let mut raw = Vec::new();
let mut missing_responses = BTreeSet::new();
let mut missing_responses = Vec::new();
let mut answers = BTreeMap::new();
// Add our listener to the map before we send the request, Here we will clone the sender
// for every request id, so that we only have to monitor one receiver.
let (sender, receiver) = channel();
// Add our listener to the map before we send the request
for (method, params) in batch.iter() {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
&method,
method,
params.to_vec(),
);
missing_responses.insert(req.id);
// Add distinct channel to each request so when we remove our request id (and sender) from the waiting_map
// we can be sure that the response gets sent to the correct channel in self.recv
let (sender, receiver) = channel();
missing_responses.push((req.id, receiver));
self.waiting_map.lock()?.insert(req.id, sender.clone());
self.waiting_map.lock()?.insert(req.id, sender);
raw.append(&mut serde_json::to_vec(&req)?);
raw.extend_from_slice(b"\n");
@ -747,8 +819,8 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
self.increment_calls();
for req_id in missing_responses.iter() {
match self.recv(&receiver, *req_id) {
for (req_id, receiver) in missing_responses.iter() {
match self.recv(receiver, *req_id) {
Ok(mut resp) => answers.insert(req_id, resp["result"].take()),
Err(e) => {
// In case of error our sender could still be left in the map, depending on where
@ -756,7 +828,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
warn!("got error for req_id {}: {:?}", req_id, e);
warn!("removing all waiting req of this batch");
let mut guard = self.waiting_map.lock()?;
for req_id in missing_responses.iter() {
for (req_id, _) in missing_responses.iter() {
guard.remove(req_id);
}
return Err(e);
@ -764,15 +836,10 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
};
}
Ok(answers.into_iter().map(|(_, r)| r).collect())
Ok(answers.into_values().collect())
}
fn block_headers_subscribe_raw(&self) -> Result<RawHeaderNotification, Error> {
let mut headers = self.headers.lock()?;
if headers.is_none() {
*headers = Some(VecDeque::new());
}
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.headers.subscribe",
@ -784,11 +851,7 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
}
fn block_headers_pop_raw(&self) -> Result<Option<RawHeaderNotification>, Error> {
let mut queue = self.headers.lock()?;
match queue.as_mut() {
None => Err(Error::NotSubscribedToHeaders),
Some(queue) => Ok(queue.pop_front()),
}
Ok(self.headers.lock()?.pop_front())
}
fn block_header_raw(&self, height: usize) -> Result<Vec<u8>, Error> {
@ -1062,6 +1125,49 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
Ok(serde_json::from_value(result)?)
}
fn batch_transaction_get_merkle<I>(
&self,
txids_and_heights: I,
) -> Result<Vec<GetMerkleRes>, Error>
where
I: IntoIterator + Clone,
I::Item: Borrow<(Txid, usize)>,
{
impl_batch_call!(self, txids_and_heights, transaction_get_merkle)
}
fn txid_from_pos(&self, height: usize, tx_pos: usize) -> Result<Txid, Error> {
let params = vec![Param::Usize(height), Param::Usize(tx_pos)];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.transaction.id_from_pos",
params,
);
let result = self.call(req)?;
Ok(serde_json::from_value(result)?)
}
fn txid_from_pos_with_merkle(
&self,
height: usize,
tx_pos: usize,
) -> Result<TxidFromPosRes, Error> {
let params = vec![
Param::Usize(height),
Param::Usize(tx_pos),
Param::Bool(true),
];
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
"blockchain.transaction.id_from_pos",
params,
);
let result = self.call(req)?;
Ok(serde_json::from_value(result)?)
}
fn server_features(&self) -> Result<ServerFeaturesRes, Error> {
let req = Request::new_id(
self.last_id.fetch_add(1, Ordering::SeqCst),
@ -1094,8 +1200,10 @@ impl<T: Read + Write> ElectrumApi for RawClient<T> {
mod test {
use std::str::FromStr;
use crate::utils;
use super::RawClient;
use api::ElectrumApi;
use crate::api::ElectrumApi;
fn get_test_server() -> String {
std::env::var("TEST_ELECTRUM_SERVER").unwrap_or("electrum.blockstream.info:50001".into())
@ -1116,12 +1224,32 @@ mod test {
assert_eq!(resp.hash_function, Some("sha256".into()));
assert_eq!(resp.pruning, None);
}
#[test]
#[ignore = "depends on a live server"]
fn test_batch_response_ordering() {
// The electrum.blockstream.info:50001 node always sends back ordered responses which will make this always pass.
// However, many servers do not, so we use one of those servers for this test.
let client = RawClient::new("exs.dyshek.org:50001", None).unwrap();
let heights: Vec<u32> = vec![1, 4, 8, 12, 222, 6666, 12];
let result_times = [
1231469665, 1231470988, 1231472743, 1231474888, 1231770653, 1236456633, 1231474888,
];
// Check ordering 10 times. This usually fails within 5 if ordering is incorrect.
for _ in 0..10 {
let results = client.batch_block_header(&heights).unwrap();
for (index, result) in results.iter().enumerate() {
assert_eq!(result_times[index], result.time);
}
}
}
#[test]
fn test_relay_fee() {
let client = RawClient::new(get_test_server(), None).unwrap();
let resp = client.relay_fee().unwrap();
assert_eq!(resp, 0.00001);
assert!(resp > 0.0);
}
#[test]
@ -1194,10 +1322,10 @@ mod test {
let client = RawClient::new(get_test_server(), None).unwrap();
// Mt.Gox hack address
let addr = bitcoin::Address::from_str("1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF").unwrap();
let resp = client
.script_get_history(&addr.payload.script_pubkey())
.unwrap();
let addr = bitcoin::Address::from_str("1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF")
.unwrap()
.assume_checked();
let resp = client.script_get_history(&addr.script_pubkey()).unwrap();
assert!(resp.len() >= 328);
assert_eq!(
@ -1215,10 +1343,10 @@ mod test {
let client = RawClient::new(get_test_server(), None).unwrap();
// Peter todd's sha256 bounty address https://bitcointalk.org/index.php?topic=293382.0
let addr = bitcoin::Address::from_str("35Snmmy3uhaer2gTboc81ayCip4m9DT4ko").unwrap();
let resp = client
.script_list_unspent(&addr.payload.script_pubkey())
.unwrap();
let addr = bitcoin::Address::from_str("35Snmmy3uhaer2gTboc81ayCip4m9DT4ko")
.unwrap()
.assume_checked();
let resp = client.script_list_unspent(&addr.script_pubkey()).unwrap();
assert!(resp.len() >= 9);
let txid = "397f12ee15f8a3d2ab25c0f6bb7d3c64d2038ca056af10dd8251b98ae0f076b0";
@ -1239,7 +1367,7 @@ mod test {
// Peter todd's sha256 bounty address https://bitcointalk.org/index.php?topic=293382.0
let script_1 = bitcoin::Address::from_str("35Snmmy3uhaer2gTboc81ayCip4m9DT4ko")
.unwrap()
.payload
.assume_checked()
.script_pubkey();
let resp = client
@ -1261,7 +1389,7 @@ mod test {
#[test]
fn test_transaction_get() {
use bitcoin::Txid;
use bitcoin::{transaction, Txid};
let client = RawClient::new(get_test_server(), None).unwrap();
@ -1271,7 +1399,7 @@ mod test {
.unwrap(),
)
.unwrap();
assert_eq!(resp.version, 1);
assert_eq!(resp.version, transaction::Version::ONE);
assert_eq!(resp.lock_time.to_consensus_u32(), 0);
}
@ -1315,21 +1443,166 @@ mod test {
let client = RawClient::new(get_test_server(), None).unwrap();
let resp = client
.transaction_get_merkle(
&Txid::from_str("cc2ca076fd04c2aeed6d02151c447ced3d09be6fb4d4ef36cb5ed4e7a3260566")
.unwrap(),
630000,
)
.unwrap();
let txid =
Txid::from_str("1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d")
.unwrap();
let resp = client.transaction_get_merkle(&txid, 630000).unwrap();
assert_eq!(resp.block_height, 630000);
assert_eq!(resp.pos, 0);
assert_eq!(resp.pos, 68);
assert_eq!(resp.merkle.len(), 12);
assert_eq!(
resp.merkle[0],
[
30, 10, 161, 245, 132, 125, 136, 198, 186, 138, 107, 216, 92, 22, 145, 81, 130,
126, 200, 65, 121, 158, 105, 111, 38, 151, 38, 147, 144, 224, 5, 218
34, 65, 51, 64, 49, 139, 115, 189, 185, 246, 70, 225, 168, 193, 217, 195, 47, 66,
179, 240, 153, 24, 114, 215, 144, 196, 212, 41, 39, 155, 246, 25
]
);
// Check we can verify the merkle proof validity, but fail if we supply wrong data.
let block_header = client.block_header(resp.block_height).unwrap();
assert!(utils::validate_merkle_proof(
&txid,
&block_header.merkle_root,
&resp
));
let mut fail_resp = resp.clone();
fail_resp.pos = 13;
assert!(!utils::validate_merkle_proof(
&txid,
&block_header.merkle_root,
&fail_resp
));
let fail_block_header = client.block_header(resp.block_height + 1).unwrap();
assert!(!utils::validate_merkle_proof(
&txid,
&fail_block_header.merkle_root,
&resp
));
}
#[test]
fn test_batch_transaction_get_merkle() {
use bitcoin::Txid;
struct TestCase {
txid: Txid,
block_height: usize,
exp_pos: usize,
exp_bytes: [u8; 32],
}
let client = RawClient::new(get_test_server(), None).unwrap();
let test_cases: Vec<TestCase> = vec![
TestCase {
txid: Txid::from_str(
"1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d",
)
.unwrap(),
block_height: 630000,
exp_pos: 68,
exp_bytes: [
34, 65, 51, 64, 49, 139, 115, 189, 185, 246, 70, 225, 168, 193, 217, 195, 47,
66, 179, 240, 153, 24, 114, 215, 144, 196, 212, 41, 39, 155, 246, 25,
],
},
TestCase {
txid: Txid::from_str(
"70a8639bc9b743c0610d1231103a2f8e99f4a25670946b91f16c55a5373b37d1",
)
.unwrap(),
block_height: 630001,
exp_pos: 25,
exp_bytes: [
169, 100, 34, 99, 168, 101, 25, 168, 184, 90, 77, 50, 151, 245, 130, 101, 193,
229, 136, 128, 63, 110, 241, 19, 242, 59, 184, 137, 245, 249, 188, 110,
],
},
TestCase {
txid: Txid::from_str(
"a0db149ace545beabbd87a8d6b20ffd6aa3b5a50e58add49a3d435f898c272cf",
)
.unwrap(),
block_height: 840000,
exp_pos: 0,
exp_bytes: [
43, 184, 95, 75, 0, 75, 230, 218, 84, 247, 102, 193, 124, 30, 133, 81, 135, 50,
113, 18, 194, 49, 239, 47, 243, 94, 186, 208, 234, 103, 198, 158,
],
},
];
let txids_and_heights: Vec<(Txid, usize)> = test_cases
.iter()
.map(|case| (case.txid, case.block_height))
.collect();
let resp = client
.batch_transaction_get_merkle(&txids_and_heights)
.unwrap();
for (i, (res, test_case)) in resp.iter().zip(test_cases).enumerate() {
assert_eq!(res.block_height, test_case.block_height);
assert_eq!(res.pos, test_case.exp_pos);
assert_eq!(res.merkle.len(), 12);
assert_eq!(res.merkle[0], test_case.exp_bytes);
// Check we can verify the merkle proof validity, but fail if we supply wrong data.
let block_header = client.block_header(res.block_height).unwrap();
assert!(utils::validate_merkle_proof(
&txids_and_heights[i].0,
&block_header.merkle_root,
res
));
let mut fail_res = res.clone();
fail_res.pos = 13;
assert!(!utils::validate_merkle_proof(
&txids_and_heights[i].0,
&block_header.merkle_root,
&fail_res
));
let fail_block_header = client.block_header(res.block_height + 1).unwrap();
assert!(!utils::validate_merkle_proof(
&txids_and_heights[i].0,
&fail_block_header.merkle_root,
res
));
}
}
#[test]
fn test_txid_from_pos() {
use bitcoin::Txid;
let client = RawClient::new(get_test_server(), None).unwrap();
let txid =
Txid::from_str("1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d")
.unwrap();
let resp = client.txid_from_pos(630000, 68).unwrap();
assert_eq!(resp, txid);
}
#[test]
fn test_txid_from_pos_with_merkle() {
use bitcoin::Txid;
let client = RawClient::new(get_test_server(), None).unwrap();
let txid =
Txid::from_str("1f7ff3c407f33eabc8bec7d2cc230948f2249ec8e591bcf6f971ca9366c8788d")
.unwrap();
let resp = client.txid_from_pos_with_merkle(630000, 68).unwrap();
assert_eq!(resp.tx_hash, txid);
assert_eq!(
resp.merkle[0],
[
34, 65, 51, 64, 49, 139, 115, 189, 185, 246, 70, 225, 168, 193, 217, 195, 47, 66,
179, 240, 153, 24, 114, 215, 144, 196, 212, 41, 39, 155, 246, 25
]
);
}
@ -1348,16 +1621,6 @@ mod test {
assert!(resp.height >= 639000);
}
#[test]
fn test_block_headers_subscribe_pop() {
let client = RawClient::new(get_test_server(), None).unwrap();
let resp = client.block_headers_pop();
assert_eq!(format!("{:?}", resp), "Err(NotSubscribedToHeaders)");
client.block_headers_subscribe().unwrap();
let resp = client.block_headers_pop();
assert!(resp.is_ok());
}
#[test]
fn test_script_subscribe() {
use std::str::FromStr;
@ -1365,12 +1628,12 @@ mod test {
let client = RawClient::new(get_test_server(), None).unwrap();
// Mt.Gox hack address
let addr = bitcoin::Address::from_str("1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF").unwrap();
let addr = bitcoin::Address::from_str("1FeexV6bAHb8ybZjqQMjJrcCrHGW9sb6uF")
.unwrap()
.assume_checked();
// Just make sure that the call returns Ok(something)
client
.script_subscribe(&addr.payload.script_pubkey())
.unwrap();
client.script_subscribe(&addr.script_pubkey()).unwrap();
}
#[test]
@ -1383,7 +1646,7 @@ mod test {
#[test]
fn test_raw_call() {
use types::Param;
use crate::types::Param;
let client = RawClient::new(get_test_server(), None).unwrap();

View File

@ -99,7 +99,7 @@ impl ToTargetAddr for (Ipv6Addr, u16) {
}
}
impl<'a> ToTargetAddr for (&'a str, u16) {
impl ToTargetAddr for (&str, u16) {
fn to_target_addr(&self) -> io::Result<TargetAddr> {
// try to parse as an IP first
if let Ok(addr) = self.0.parse::<Ipv4Addr>() {
@ -114,7 +114,7 @@ impl<'a> ToTargetAddr for (&'a str, u16) {
}
}
impl<'a> ToTargetAddr for &'a str {
impl ToTargetAddr for &str {
fn to_target_addr(&self) -> io::Result<TargetAddr> {
// try to parse as an IP first
if let Ok(addr) = self.parse::<SocketAddrV4>() {

View File

@ -18,12 +18,7 @@ fn read_response(socket: &mut TcpStream) -> io::Result<SocketAddrV4> {
match response.read_u8()? {
90 => {}
91 => {
return Err(io::Error::new(
io::ErrorKind::Other,
"request rejected or failed",
))
}
91 => return Err(io::Error::other("request rejected or failed")),
92 => {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
@ -109,7 +104,7 @@ impl Socks4Stream {
let _ = packet.write_u32::<BigEndian>(Ipv4Addr::new(0, 0, 0, 1).into());
let _ = packet.write_all(userid.as_bytes());
let _ = packet.write_u8(0);
let _ = packet.extend(host.as_bytes());
packet.extend(host.as_bytes());
let _ = packet.write_u8(0);
}
}
@ -117,10 +112,7 @@ impl Socks4Stream {
socket.write_all(&packet)?;
let proxy_addr = read_response(&mut socket)?;
Ok(Socks4Stream {
socket: socket,
proxy_addr: proxy_addr,
})
Ok(Socks4Stream { socket, proxy_addr })
}
/// Returns the proxy-side address of the connection between the proxy and
@ -151,7 +143,7 @@ impl Read for Socks4Stream {
}
}
impl<'a> Read for &'a Socks4Stream {
impl Read for &Socks4Stream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&self.socket).read(buf)
}
@ -167,7 +159,7 @@ impl Write for Socks4Stream {
}
}
impl<'a> Write for &'a Socks4Stream {
impl Write for &Socks4Stream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&self.socket).write(buf)
}

View File

@ -37,10 +37,7 @@ fn read_addr<R: Read>(socket: &mut R) -> io::Result<TargetAddr> {
ip, port, 0, 0,
))))
}
_ => Err(io::Error::new(
io::ErrorKind::Other,
"unsupported address type",
)),
_ => Err(io::Error::other("unsupported address type")),
}
}
@ -54,35 +51,15 @@ fn read_response(socket: &mut TcpStream) -> io::Result<TargetAddr> {
match socket.read_u8()? {
0 => {}
1 => {
return Err(io::Error::new(
io::ErrorKind::Other,
"general SOCKS server failure",
))
}
2 => {
return Err(io::Error::new(
io::ErrorKind::Other,
"connection not allowed by ruleset",
))
}
3 => return Err(io::Error::new(io::ErrorKind::Other, "network unreachable")),
4 => return Err(io::Error::new(io::ErrorKind::Other, "host unreachable")),
5 => return Err(io::Error::new(io::ErrorKind::Other, "connection refused")),
6 => return Err(io::Error::new(io::ErrorKind::Other, "TTL expired")),
7 => {
return Err(io::Error::new(
io::ErrorKind::Other,
"command not supported",
))
}
8 => {
return Err(io::Error::new(
io::ErrorKind::Other,
"address kind not supported",
))
}
_ => return Err(io::Error::new(io::ErrorKind::Other, "unknown error")),
1 => return Err(io::Error::other("general SOCKS server failure")),
2 => return Err(io::Error::other("connection not allowed by ruleset")),
3 => return Err(io::Error::other("network unreachable")),
4 => return Err(io::Error::other("host unreachable")),
5 => return Err(io::Error::other("connection refused")),
6 => return Err(io::Error::other("TTL expired")),
7 => return Err(io::Error::other("command not supported")),
8 => return Err(io::Error::other("address kind not supported")),
_ => return Err(io::Error::other("unknown error")),
}
if socket.read_u8()? != 0 {
@ -110,7 +87,7 @@ fn write_addr(mut packet: &mut [u8], target: &TargetAddr) -> io::Result<usize> {
}
TargetAddr::Domain(ref domain, port) => {
packet.write_u8(3).unwrap();
if domain.len() > u8::max_value() as usize {
if domain.len() > u8::MAX as usize {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"domain name too long",
@ -135,7 +112,7 @@ enum Authentication<'a> {
None,
}
impl<'a> Authentication<'a> {
impl Authentication<'_> {
fn id(&self) -> u8 {
match *self {
Authentication::Password { .. } => 2,
@ -144,11 +121,7 @@ impl<'a> Authentication<'a> {
}
fn is_no_auth(&self) -> bool {
if let Authentication::None = *self {
true
} else {
false
}
matches!(*self, Authentication::None)
}
}
@ -204,6 +177,9 @@ impl Socks5Stream {
TcpStream::connect(proxy)?
};
socket.set_read_timeout(timeout)?;
socket.set_write_timeout(timeout)?;
let target = target.to_target_addr()?;
let packet_len = if auth.is_no_auth() { 3 } else { 4 };
@ -228,14 +204,11 @@ impl Socks5Stream {
}
if selected_method == 0xff {
return Err(io::Error::new(
io::ErrorKind::Other,
"no acceptable auth methods",
));
return Err(io::Error::other("no acceptable auth methods"));
}
if selected_method != auth.id() && selected_method != Authentication::None.id() {
return Err(io::Error::new(io::ErrorKind::Other, "unknown auth method"));
return Err(io::Error::other("unknown auth method"));
}
match *auth {
@ -254,10 +227,7 @@ impl Socks5Stream {
let proxy_addr = read_response(&mut socket)?;
Ok(Socks5Stream {
socket: socket,
proxy_addr: proxy_addr,
})
Ok(Socks5Stream { socket, proxy_addr })
}
fn password_authentication(
@ -265,13 +235,13 @@ impl Socks5Stream {
username: &str,
password: &str,
) -> io::Result<()> {
if username.len() < 1 || username.len() > 255 {
if username.is_empty() || username.len() > 255 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid username",
));
};
if password.len() < 1 || password.len() > 255 {
if password.is_empty() || password.len() > 255 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid password",
@ -333,7 +303,7 @@ impl Read for Socks5Stream {
}
}
impl<'a> Read for &'a Socks5Stream {
impl Read for &Socks5Stream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&self.socket).read(buf)
}
@ -349,7 +319,7 @@ impl Write for Socks5Stream {
}
}
impl<'a> Write for &'a Socks5Stream {
impl Write for &Socks5Stream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&self.socket).write(buf)
}
@ -471,10 +441,7 @@ impl Socks5Datagram {
let socket = UdpSocket::bind(addr)?;
socket.connect(&stream.proxy_addr)?;
Ok(Socks5Datagram {
socket: socket,
stream: stream,
})
Ok(Socks5Datagram { socket, stream })
}
/// Like `UdpSocket::send_to`.
@ -523,11 +490,7 @@ impl Socks5Datagram {
let addr = read_addr(&mut header)?;
unsafe {
ptr::copy(
buf.as_ptr(),
buf.as_mut_ptr().offset(header.len() as isize),
overflow,
);
ptr::copy(buf.as_ptr(), buf.as_mut_ptr().add(header.len()), overflow);
}
buf[..header.len()].copy_from_slice(header);

View File

@ -9,16 +9,15 @@ use std::sync::Arc;
use bitcoin::blockdata::block;
use bitcoin::consensus::encode::deserialize;
use bitcoin::hashes::hex::FromHex;
use bitcoin::hashes::{sha256, Hash};
use bitcoin::hex::{DisplayHex, FromHex};
use bitcoin::{Script, Txid};
use bitcoin_private::hex::exts::DisplayHex;
use serde::{de, Deserialize, Serialize};
static JSONRPC_2_0: &str = "2.0";
pub type Call = (String, Vec<Param>);
pub(crate) type Call = (String, Vec<Param>);
#[derive(Serialize, Clone)]
#[serde(untagged)]
@ -88,7 +87,7 @@ impl From<[u8; 32]> for Hex32Bytes {
}
impl Hex32Bytes {
pub(crate) fn to_hex(&self) -> String {
pub(crate) fn to_hex(self) -> String {
self.0.to_lower_hex_string()
}
}
@ -161,7 +160,7 @@ where
}
/// Response to a [`script_get_history`](../client/struct.Client.html#method.script_get_history) request.
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct GetHistoryRes {
/// Confirmation height of the transaction. 0 if unconfirmed, -1 if unconfirmed while some of
/// its inputs are unconfirmed too.
@ -173,7 +172,7 @@ pub struct GetHistoryRes {
}
/// Response to a [`script_list_unspent`](../client/struct.Client.html#method.script_list_unspent) request.
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct ListUnspentRes {
/// Confirmation height of the transaction that created this output.
pub height: usize,
@ -186,7 +185,7 @@ pub struct ListUnspentRes {
}
/// Response to a [`server_features`](../client/struct.Client.html#method.server_features) request.
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct ServerFeaturesRes {
/// Server version reported.
pub server_version: String,
@ -204,7 +203,7 @@ pub struct ServerFeaturesRes {
}
/// Response to a [`server_features`](../client/struct.Client.html#method.server_features) request.
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct GetHeadersRes {
/// Maximum number of headers returned in a single response.
pub max: usize,
@ -219,7 +218,7 @@ pub struct GetHeadersRes {
}
/// Response to a [`script_get_balance`](../client/struct.Client.html#method.script_get_balance) request.
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct GetBalanceRes {
/// Confirmed balance in Satoshis for the address.
pub confirmed: u64,
@ -230,7 +229,7 @@ pub struct GetBalanceRes {
}
/// Response to a [`transaction_get_merkle`](../client/struct.Client.html#method.transaction_get_merkle) request.
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct GetMerkleRes {
/// Height of the block that confirmed the transaction
pub block_height: usize,
@ -241,8 +240,19 @@ pub struct GetMerkleRes {
pub merkle: Vec<[u8; 32]>,
}
/// Response to a [`txid_from_pos_with_merkle`](../client/struct.Client.html#method.txid_from_pos_with_merkle)
/// request.
#[derive(Clone, Debug, Deserialize)]
pub struct TxidFromPosRes {
/// Txid of the transaction.
pub tx_hash: Txid,
/// The merkle path of the transaction.
#[serde(deserialize_with = "from_hex_array")]
pub merkle: Vec<[u8; 32]>,
}
/// Notification of a new block header
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct HeaderNotification {
/// New block height.
pub height: usize,
@ -252,7 +262,7 @@ pub struct HeaderNotification {
}
/// Notification of a new block header with the header encoded as raw bytes
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct RawHeaderNotification {
/// New block height.
pub height: usize,
@ -273,7 +283,7 @@ impl TryFrom<RawHeaderNotification> for HeaderNotification {
}
/// Notification of the new status of a script
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct ScriptNotification {
/// Address that generated this notification.
pub scripthash: ScriptHash,
@ -288,8 +298,8 @@ pub enum Error {
IOError(std::io::Error),
/// Wraps `serde_json::error::Error`
JSON(serde_json::error::Error),
/// Wraps `bitcoin::hashes::hex::Error`
Hex(bitcoin::hashes::hex::Error),
/// Wraps `bitcoin::hex::HexToBytesError`
Hex(bitcoin::hex::HexToBytesError),
/// Error returned by the Electrum server
Protocol(serde_json::Value),
/// Error during the deserialization of a Bitcoin data structure
@ -316,8 +326,7 @@ pub enum Error {
CouldntLockReader,
/// Broken IPC communication channel: the other thread probably has exited
Mpsc,
#[cfg(feature = "use-rustls")]
#[cfg(any(feature = "use-rustls", feature = "use-rustls-ring"))]
/// Could not create a rustls client connection
CouldNotCreateConnection(rustls::Error),
@ -327,9 +336,6 @@ pub enum Error {
#[cfg(feature = "use-openssl")]
/// SSL Handshake failed with the server
SslHandshakeError(openssl::ssl::HandshakeError<std::net::TcpStream>),
/// Expecting notification on headers but we are not subscribed
NotSubscribedToHeaders,
}
impl Display for Error {
@ -344,7 +350,10 @@ impl Display for Error {
Error::SslHandshakeError(e) => Display::fmt(e, f),
#[cfg(feature = "use-openssl")]
Error::InvalidSslMethod(e) => Display::fmt(e, f),
#[cfg(feature = "use-rustls")]
#[cfg(any(
feature = "use-rustls",
feature = "use-rustls-ring",
))]
Error::CouldNotCreateConnection(e) => Display::fmt(e, f),
Error::Message(e) => f.write_str(e),
@ -367,7 +376,6 @@ impl Display for Error {
Error::MissingDomain => f.write_str("Missing domain while it was explicitly asked to validate it"),
Error::CouldntLockReader => f.write_str("Couldn't take a lock on the reader mutex. This means that there's already another reader thread is running"),
Error::Mpsc => f.write_str("Broken IPC communication channel: the other thread probably has exited"),
Error::NotSubscribedToHeaders => write!(f, "Expecting notification on headers but we are not subscribed"),
}
}
}
@ -386,7 +394,7 @@ macro_rules! impl_error {
impl_error!(std::io::Error, IOError);
impl_error!(serde_json::Error, JSON);
impl_error!(bitcoin::hashes::hex::Error, Hex);
impl_error!(bitcoin::hex::HexToBytesError, Hex);
impl_error!(bitcoin::consensus::encode::Error, Bitcoin);
impl<T> From<std::sync::PoisonError<T>> for Error {

43
src/utils.rs Normal file
View File

@ -0,0 +1,43 @@
//! Utilities helping to handle Electrum-related data.
use crate::types::GetMerkleRes;
use bitcoin::hash_types::TxMerkleNode;
use bitcoin::hashes::sha256d::Hash as Sha256d;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::Txid;
/// Verifies a Merkle inclusion proof as retrieved via [`transaction_get_merkle`] for a transaction with the
/// given `txid` and `merkle_root` as included in the [`BlockHeader`].
///
/// Returns `true` if the transaction is included in the corresponding block, and `false`
/// otherwise.
///
/// [`transaction_get_merkle`]: crate::ElectrumApi::transaction_get_merkle
/// [`BlockHeader`]: bitcoin::block::Header
pub fn validate_merkle_proof(
txid: &Txid,
merkle_root: &TxMerkleNode,
merkle_res: &GetMerkleRes,
) -> bool {
let mut index = merkle_res.pos;
let mut cur = txid.to_raw_hash();
for mut bytes in merkle_res.merkle.iter().cloned() {
bytes.reverse();
let next_hash = Sha256d::from_byte_array(bytes);
cur = Sha256d::from_engine({
let mut engine = Sha256d::engine();
if index % 2 == 0 {
engine.input(cur.as_ref());
engine.input(next_hash.as_ref());
} else {
engine.input(next_hash.as_ref());
engine.input(cur.as_ref());
};
engine
});
index /= 2;
}
cur == merkle_root.to_raw_hash()
}