-
Notifications
You must be signed in to change notification settings - Fork 7
refactor: implement stealth api as rust crate #17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
720342f
refactor(api): expand and test api as stealth http interface
satsfy 780c312
feat(docs): add docs for api package
satsfy 9e1cadc
Merge remote-tracking branch 'origin/main' into satsfy-pr17-rebase
LORDBABUINO 3ab2fb3
refactor(api): drop dead-code cookie loop in detect_cookie_file
LORDBABUINO ca827db
feat(api): add permissive CORS layer
LORDBABUINO 446fb9e
refactor(api): use match for scan input validation
LORDBABUINO 2dcb2d2
refactor(api): use read_cookie_file in e2e regtest tests
LORDBABUINO 25a0594
refactor(api): remove preflight descriptor validation
LORDBABUINO a24dc0a
docs: point readme bitcoin.conf section to bitcoin.conf.example
LORDBABUINO 52fb5b4
docs: use scripts/setup.sh in readme quickstart
LORDBABUINO 86e0b40
refactor(api): use ini crate to parse bitcoin.conf
LORDBABUINO 9e4df8e
refactor(frontend): point frontend at rust stealth-api
LORDBABUINO 53a84a8
fix(engine): use sort_by_key with Reverse for clippy 1.95
LORDBABUINO 34501db
fix(api): also read rpc credentials from network-specific bitcoin.con…
LORDBABUINO 2e6f676
fix(api): reject empty descriptors/utxos arrays with bad_request
LORDBABUINO 830008a
chore: untrack and gitignore yarn install-state.gz
LORDBABUINO File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| node_modules/ | ||
| dist/ | ||
| **/.yarn/install-state.gz | ||
| .env | ||
| .env.local | ||
| *.local | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,7 @@ members = [ | |
| "model", | ||
| "bitcoincore", | ||
| "engine", | ||
| "api", | ||
| "cli", | ||
| ] | ||
| resolver = "2" | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| [package] | ||
| name = "stealth-api" | ||
| version.workspace = true | ||
| edition.workspace = true | ||
| authors.workspace = true | ||
| license.workspace = true | ||
| repository.workspace = true | ||
| rust-version.workspace = true | ||
| description = "HTTP transport for Stealth wallet privacy analysis" | ||
| categories = ["cryptography::cryptocurrencies", "web-programming::http-server"] | ||
| keywords = ["bitcoin", "privacy", "api", "wallet"] | ||
| readme = "README.md" | ||
|
|
||
| [dependencies] | ||
| axum = { workspace = true } | ||
| ini = { package = "rust-ini", version = "0.21.3" } | ||
| serde = { workspace = true, features = ["derive"] } | ||
| serde_json = { workspace = true } | ||
| stealth-bitcoincore = { path = "../bitcoincore" } | ||
| stealth-engine = { workspace = true } | ||
| thiserror = { workspace = true } | ||
| tokio = { workspace = true } | ||
| tower-http = { version = "0.6.6", features = ["cors"] } | ||
| tracing = { workspace = true } | ||
| tracing-subscriber = { workspace = true } | ||
|
|
||
| [dev-dependencies] | ||
| corepc-node = { workspace = true } | ||
| http-body-util = "0.1.3" | ||
| reqwest = { version = "0.12.9", default-features = false, features = ["json", "rustls-tls"] } | ||
| tower = { version = "0.5.2", features = ["util"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # Stealth API | ||
|
|
||
| `stealth-api` is the Rust HTTP transport layer for Stealth. It connects to a | ||
| running `bitcoind` via JSON-RPC, imports descriptors into temporary wallets, | ||
| builds a transaction graph, and runs privacy detectors from | ||
| `stealth-engine`. | ||
|
|
||
| ## Running | ||
|
|
||
| ```bash | ||
| # Stop any old API process, then start the current source build | ||
| pkill -f 'target/debug/stealth-api' 2>/dev/null || true | ||
|
|
||
| # Auto-detects local bitcoind RPC port (prefers 18443, then 8332/18332/38332) | ||
| # and uses credentials from bitcoin.conf or local cookie files. | ||
| cargo run --bin stealth-api | ||
| ``` | ||
|
|
||
| Set auth explicitly with username/password: | ||
|
|
||
| ```bash | ||
| STEALTH_RPC_URL=http://127.0.0.1:8332 \ | ||
| STEALTH_RPC_USER=user \ | ||
| STEALTH_RPC_PASS=pass \ | ||
| cargo run --bin stealth-api | ||
| ``` | ||
|
|
||
| Or use a cookie file: | ||
|
|
||
| ```bash | ||
| STEALTH_RPC_URL=http://127.0.0.1:8332 \ | ||
| STEALTH_RPC_COOKIE=~/.bitcoin/.cookie \ | ||
| cargo run --bin stealth-api | ||
| ``` | ||
|
|
||
| Configure the listen address with `STEALTH_API_BIND` (default `127.0.0.1:20899`). | ||
|
|
||
| If you see `Connection refused (os error 111)`, either: | ||
| 1. an old `stealth-api` process is still running, or | ||
| 2. `bitcoind` RPC is not reachable on the detected/configured URL. | ||
|
|
||
| ## API | ||
|
|
||
| ### `POST /api/wallet/scan` | ||
|
|
||
| Accepts one mutually-exclusive source: | ||
|
|
||
| | Field | Type | Description | | ||
| |-------|------|-------------| | ||
| | `descriptor` | `string` | Single output descriptor | | ||
| | `descriptors` | `string[]` | Multiple descriptors | | ||
| | `utxos` | `UtxoInput[]` | Raw UTXO set | | ||
|
|
||
| **Descriptor scan flow:** creates a blank watch-only wallet, imports the | ||
| descriptor(s) with a full blockchain rescan, builds a `TxGraph`, runs all | ||
| 17 detectors, then cleans up the temporary wallet. | ||
|
|
||
| **UTXO scan flow:** resolves each UTXO's address from the node, builds a | ||
| partial transaction graph, and runs applicable detectors. | ||
|
|
||
| #### Example (real descriptor from Bitcoin Core) | ||
|
|
||
| ```bash | ||
| RPC="bitcoin-cli -regtest -rpcport=18443 -rpcuser=localuser -rpcpassword=localpass" | ||
| WALLET="scanwallet_$(date +%s)" | ||
|
|
||
| $RPC createwallet "$WALLET" >/dev/null | ||
| ADDR="$($RPC -rpcwallet="$WALLET" getnewaddress)" | ||
| DESC="$($RPC -rpcwallet="$WALLET" getaddressinfo "$ADDR" | jq -r '.desc')" | ||
|
|
||
| curl 'http://localhost:20899/api/wallet/scan' \ | ||
| -H 'content-type: application/json' \ | ||
| -d "{\"descriptor\":\"$DESC\"}" | jq | ||
| ``` | ||
|
|
||
| #### Responses | ||
|
|
||
| | Status | Meaning | | ||
| |--------|---------| | ||
| | `200` | Scan completed — body is a `Report` | | ||
| | `400` | Invalid input (bad descriptor shape, empty UTXOs, …) | | ||
| | `502` | bitcoind RPC unavailable/auth failed/connection failed | | ||
|
|
||
| ## Environment variables | ||
|
|
||
| | Variable | Description | | ||
| |----------|-------------| | ||
| | `STEALTH_API_BIND` | Listen address (default `127.0.0.1:20899`) | | ||
| | `STEALTH_RPC_URL` | bitcoind RPC endpoint (overrides auto-detection) | | ||
| | `STEALTH_RPC_USER` | RPC username (otherwise read from `bitcoin.conf` when available) | | ||
| | `STEALTH_RPC_PASS` | RPC password (otherwise read from `bitcoin.conf` when available) | | ||
| | `STEALTH_RPC_COOKIE` | Path to `.cookie` file (otherwise API auto-detects common local cookie locations) | | ||
|
|
||
| ## E2E test (regtest) | ||
|
|
||
| The API includes an end-to-end regtest integration test that: | ||
| 1. creates wallets, | ||
| 2. gets a real descriptor from `bitcoind`, | ||
| 3. scans once with no history (`summary.clean = true`), | ||
| 4. creates/mine transactions, | ||
| 5. scans again and asserts findings (`summary.clean = false`). | ||
|
|
||
| Run it with: | ||
|
|
||
| ```bash | ||
| cargo test -p stealth-api scan_descriptor_clean_then_findings_after_regtest_activity -- --nocapture | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| use axum::{ | ||
| http::StatusCode, | ||
| response::{IntoResponse, Response}, | ||
| Json, | ||
| }; | ||
| use serde::Serialize; | ||
| use thiserror::Error; | ||
|
|
||
| use stealth_engine::error::AnalysisError; | ||
|
|
||
| #[derive(Debug, Error)] | ||
| pub enum ApiError { | ||
| #[error("{0}")] | ||
| BadRequest(String), | ||
| #[error("analysis failed: {0}")] | ||
| Analysis(#[from] AnalysisError), | ||
| #[error("scanner not configured – set STEALTH_RPC_URL")] | ||
| ScannerNotConfigured, | ||
| #[error("internal error: {0}")] | ||
| Internal(String), | ||
| } | ||
|
|
||
| impl ApiError { | ||
| pub fn bad_request(message: impl Into<String>) -> Self { | ||
| Self::BadRequest(message.into()) | ||
| } | ||
|
|
||
| fn status_code(&self) -> StatusCode { | ||
| match self { | ||
| Self::BadRequest(_) => StatusCode::BAD_REQUEST, | ||
| Self::Analysis(AnalysisError::EmptyDescriptor) | ||
| | Self::Analysis(AnalysisError::DescriptorNormalization { .. }) => { | ||
| StatusCode::BAD_REQUEST | ||
| } | ||
| Self::Analysis(AnalysisError::EnvironmentUnavailable(_)) => StatusCode::BAD_GATEWAY, | ||
| Self::Analysis(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
| Self::ScannerNotConfigured => StatusCode::SERVICE_UNAVAILABLE, | ||
| Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, | ||
| } | ||
| } | ||
|
|
||
| fn error_code(&self) -> &'static str { | ||
| match self { | ||
| Self::BadRequest(_) => "bad_request", | ||
| Self::Analysis(_) => "scan_failed", | ||
| Self::ScannerNotConfigured => "scanner_not_configured", | ||
| Self::Internal(_) => "internal_error", | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl IntoResponse for ApiError { | ||
| fn into_response(self) -> Response { | ||
| let status = self.status_code(); | ||
| let message = self.to_string(); | ||
| let code = self.error_code(); | ||
| let body = Json(ErrorResponse { | ||
| error: ErrorDetails { code, message }, | ||
| }); | ||
| (status, body).into_response() | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| struct ErrorResponse { | ||
| error: ErrorDetails, | ||
| } | ||
|
|
||
| #[derive(Debug, Serialize)] | ||
| struct ErrorDetails { | ||
| code: &'static str, | ||
| message: String, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| mod error; | ||
| mod routes; | ||
|
|
||
| use std::sync::Arc; | ||
|
|
||
| use axum::Router; | ||
| use stealth_engine::gateway::BlockchainGateway; | ||
| use tower_http::cors::CorsLayer; | ||
|
|
||
| /// Shared application state: an optional blockchain gateway. | ||
| pub type GatewayState = Option<Arc<dyn BlockchainGateway + Send + Sync>>; | ||
|
|
||
| /// Build the router without a gateway (503 on every scan request). | ||
| pub fn app() -> Router { | ||
| app_with_gateway(None) | ||
| } | ||
|
|
||
| /// Build the router with a concrete [`BlockchainGateway`]. | ||
| pub fn app_with_gateway(gateway: GatewayState) -> Router { | ||
| Router::new() | ||
| .nest("/api/wallet", routes::wallet::router()) | ||
| .layer(CorsLayer::permissive()) | ||
| .with_state(gateway) | ||
| } | ||
|
LORDBABUINO marked this conversation as resolved.
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.