Merge pull request 'wallet: no-spend (view-only) mode + RPC view-only detection + docs/WALLET.md' (#41) from feat/wallet-no-spend-view-only into main
Reviewed-on: #41
This commit is contained in:
commit
beb523bdde
4 changed files with 514 additions and 5 deletions
|
|
@ -73,6 +73,18 @@ A signed `prf` frame is shown to people who already have a session with you. App
|
||||||
|
|
||||||
OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy.
|
OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy.
|
||||||
|
|
||||||
|
Run it **view-only** (recommended). `/pay` and receipt verification need only
|
||||||
|
`create_address`/`get_transfers`, which a wallet without a spend key serves
|
||||||
|
fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC
|
||||||
|
dial, and a view-only wallet is detected over RPC (`query_key`
|
||||||
|
`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says
|
||||||
|
so plainly instead of failing with a raw wallet error. The trade-off is
|
||||||
|
explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local
|
||||||
|
spend authority — any process that can read the RPC credentials can move the
|
||||||
|
balance, and `/tip` gives a chat peer a supported way to ask for a transfer.
|
||||||
|
Loopback binding is not an authorization boundary. Full setup, view-only wallet
|
||||||
|
creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md).
|
||||||
|
|
||||||
## Backup file is the identity
|
## Backup file is the identity
|
||||||
|
|
||||||
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.
|
`/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table.
|
||||||
|
|
|
||||||
184
docs/WALLET.md
Normal file
184
docs/WALLET.md
Normal file
|
|
@ -0,0 +1,184 @@
|
||||||
|
# OnionWire + monero-wallet-rpc
|
||||||
|
|
||||||
|
OnionWire is not a wallet. It never holds a seed, a spend key, or a view key.
|
||||||
|
It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on
|
||||||
|
loopback, only to:
|
||||||
|
|
||||||
|
- hand out a receive subaddress for `/pay` invoices (`create_address`),
|
||||||
|
- read incoming transfers to verify a peer's receipt (`get_transfers`),
|
||||||
|
- and — only if you let it — spend for `/tip` (`transfer`).
|
||||||
|
|
||||||
|
**Run it view-only, and switch `/tip` off explicitly.** Everything else in this
|
||||||
|
document explains why, and what breaks when you do.
|
||||||
|
|
||||||
|
## Env vars
|
||||||
|
|
||||||
|
| Variable | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. |
|
||||||
|
| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. |
|
||||||
|
| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. |
|
||||||
|
|
||||||
|
`README.md` carries the operator summary; this file is the long form.
|
||||||
|
|
||||||
|
## Recommended topology
|
||||||
|
|
||||||
|
```
|
||||||
|
wallet host (this machine)
|
||||||
|
┌──────────────────────────────────────────────────────────────┐
|
||||||
|
│ monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-login u:p │
|
||||||
|
│ ▲ HTTP Digest, loopback only │
|
||||||
|
│ │ │
|
||||||
|
│ OnionWire (ONIONWIRE_WALLET_NO_SPEND=1) ── /pay, receipts │
|
||||||
|
│ └── /tip refused locally │
|
||||||
|
└──────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
Loopback is the only address OnionWire will dial. `.onion` RPC URLs are
|
||||||
|
rejected: there is no Arti dial for the wallet, and a remote wallet would move
|
||||||
|
your key material off the box.
|
||||||
|
|
||||||
|
## Create a view-only wallet
|
||||||
|
|
||||||
|
Either path produces a wallet file with the view key only. Keep the seed /
|
||||||
|
spend key on a machine that is **not** running OnionWire.
|
||||||
|
|
||||||
|
With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard*
|
||||||
|
address the view key belongs to, then the secret view key):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \
|
||||||
|
--daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT"
|
||||||
|
# Standard address: 4...
|
||||||
|
# Secret view key: <hex>
|
||||||
|
```
|
||||||
|
|
||||||
|
Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys`
|
||||||
|
without `spendkey` writes a watch-only wallet):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{
|
||||||
|
"filename":"viewonly","password":"walletpass",
|
||||||
|
"address":"4...","viewkey":"<hex>","restore_height":<height>}}'
|
||||||
|
# → "Watch-only wallet has been generated successfully."
|
||||||
|
```
|
||||||
|
|
||||||
|
Then serve it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \
|
||||||
|
--rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret \
|
||||||
|
--daemon-address "$YOUR_MONEROD:18089"
|
||||||
|
|
||||||
|
export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083
|
||||||
|
export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret
|
||||||
|
export ONIONWIRE_WALLET_NO_SPEND=1
|
||||||
|
```
|
||||||
|
|
||||||
|
Restore the wallet from a height *at or before* its first incoming transaction
|
||||||
|
— a view-only wallet cannot rescan cheaply from height 0.
|
||||||
|
|
||||||
|
## What works, what does not
|
||||||
|
|
||||||
|
| Feature | View-only | Spend-capable |
|
||||||
|
|---|---|---|
|
||||||
|
| `/pay <xmr>` invoice subaddress (`create_address`) | works | works |
|
||||||
|
| Receipt verification (`get_transfers`) | works | works |
|
||||||
|
| Profile `xmr_addr` fallback when RPC is down | works | works |
|
||||||
|
| `/tip <xmr>` (`transfer`) | **cannot work** | works |
|
||||||
|
| OnionWire learns your spend key | never | never (it stays in the wallet) |
|
||||||
|
|
||||||
|
With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is
|
||||||
|
contacted, with:
|
||||||
|
|
||||||
|
```
|
||||||
|
wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work
|
||||||
|
```
|
||||||
|
|
||||||
|
Without the flag, `/tip` against a view-only wallet fails at the wallet and
|
||||||
|
OnionWire then asks the wallet directly whether it can spend (see below), so you
|
||||||
|
get the same sentence instead of a raw RPC error.
|
||||||
|
|
||||||
|
## How OnionWire detects view-only over RPC
|
||||||
|
|
||||||
|
The signal people usually reach for is `query_key` with `key_type=mnemonic`. It
|
||||||
|
works, but it is the wrong key to ask for: on a spend-capable wallet it hands
|
||||||
|
over the whole seed (full spend ability) over loopback HTTP, and it answers
|
||||||
|
`-43` for wallets that have no mnemonic at all. The spend key is narrower and
|
||||||
|
just as unambiguous:
|
||||||
|
|
||||||
|
```
|
||||||
|
query_key {"key_type":"spend_key"}
|
||||||
|
spend-capable → result.key = <hex secret spend key>
|
||||||
|
view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key."
|
||||||
|
```
|
||||||
|
|
||||||
|
(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the
|
||||||
|
two agree — OnionWire asks for the spend key because it is the smaller secret.)
|
||||||
|
|
||||||
|
- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key)
|
||||||
|
- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in
|
||||||
|
[`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h)
|
||||||
|
- The view-only branch is `on_query_key` in
|
||||||
|
[`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp)
|
||||||
|
|
||||||
|
OnionWire only calls this **after** a `transfer` has already failed — it never
|
||||||
|
probes a healthy wallet — and it discards `result.key` immediately. There is no
|
||||||
|
RPC method that reports "view-only" as a plain field; `query_key` is the
|
||||||
|
documented signal and this is its only cost: a spend-capable wallet answers with
|
||||||
|
its spend key over loopback HTTP, which is one more reason to run view-only.
|
||||||
|
|
||||||
|
Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc`
|
||||||
|
answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error
|
||||||
|
unchanged. It never guesses "view-only" from an unrelated failure.
|
||||||
|
|
||||||
|
## Why loopback still needs authentication
|
||||||
|
|
||||||
|
`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it
|
||||||
|
away from other users or processes on the same machine. Any local process can
|
||||||
|
`connect(127.0.0.1:18083)`.
|
||||||
|
|
||||||
|
- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and
|
||||||
|
refuses URLs without credentials. Unset the credentials and the wallet is open
|
||||||
|
to every local process — with a spend-capable wallet file, that is a
|
||||||
|
one-curl drain of your balance.
|
||||||
|
- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext,
|
||||||
|
but Digest gives no confidentiality: a local attacker who can sniff loopback
|
||||||
|
can replay it. Treat loopback as trusted-ish, not safe.
|
||||||
|
- Do not log the password, and do not put it in a shell history you share.
|
||||||
|
Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL.
|
||||||
|
|
||||||
|
## The spend-authority warning
|
||||||
|
|
||||||
|
An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a
|
||||||
|
local spend authority: any process that can read the RPC credentials (env var,
|
||||||
|
`/proc/<pid>/environ`, shell history, a stored URL) can spend the wallet's
|
||||||
|
balance, and `/tip` gives a chat peer a supported path to ask for a transfer.
|
||||||
|
|
||||||
|
That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended
|
||||||
|
default:
|
||||||
|
|
||||||
|
- the wallet file holds no spend key, so a stolen wallet file cannot be used to
|
||||||
|
move funds;
|
||||||
|
- the RPC credentials grant only receive-address and history reads;
|
||||||
|
- `/tip` fails locally with a plain message, so nothing in the UI pretends the
|
||||||
|
spend path exists.
|
||||||
|
|
||||||
|
If you want tips to work, understand that you are deliberately making the
|
||||||
|
OnionWire process able to spend. Give it a **separate hot wallet with a small
|
||||||
|
balance**, not your savings wallet.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Monero Wallet RPC reference:
|
||||||
|
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html>
|
||||||
|
- `on_query_key` (view-only → `-29`):
|
||||||
|
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp>
|
||||||
|
- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`:
|
||||||
|
<https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h>
|
||||||
|
- `--generate-from-view-key` (incoming-only wallet):
|
||||||
|
<https://github.com/monero-project/monero/blob/master/src/simplewallet/simplewallet.cpp>
|
||||||
|
- `generate_from_keys` (watch-only when `spendkey` is omitted):
|
||||||
|
<https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#generate_from_keys>
|
||||||
|
|
@ -42,8 +42,18 @@ impl std::fmt::Debug for Endpoint {
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Wallet {
|
pub struct Wallet {
|
||||||
endpoint: Option<Endpoint>,
|
endpoint: Option<Endpoint>,
|
||||||
|
no_spend: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What /tip says when the wallet cannot spend. Same text for the explicit
|
||||||
|
/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over
|
||||||
|
/// RPC, so the operator never has to guess which one it was.
|
||||||
|
const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work";
|
||||||
|
|
||||||
|
/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's
|
||||||
|
/// `src/wallet/wallet_rpc_server_error_codes.h`.
|
||||||
|
const WATCH_ONLY_CODE: i64 = -29;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct TransferRow {
|
pub struct TransferRow {
|
||||||
pub txid: String,
|
pub txid: String,
|
||||||
|
|
@ -55,10 +65,17 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
impl Wallet {
|
impl Wallet {
|
||||||
pub fn disabled() -> Self {
|
pub fn disabled() -> Self {
|
||||||
Self { endpoint: None }
|
Self {
|
||||||
|
endpoint: None,
|
||||||
|
no_spend: false,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is
|
||||||
|
/// refused locally, before any RPC dial. `/pay` and receipt verification
|
||||||
|
/// keep working.
|
||||||
pub fn from_env() -> Self {
|
pub fn from_env() -> Self {
|
||||||
|
let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND");
|
||||||
match std::env::var("ONIONWIRE_WALLET_RPC") {
|
match std::env::var("ONIONWIRE_WALLET_RPC") {
|
||||||
// The URL can carry `user:pass@` in its userinfo: keep it in a
|
// The URL can carry `user:pass@` in its userinfo: keep it in a
|
||||||
// wiping buffer, not a bare `String`.
|
// wiping buffer, not a bare `String`.
|
||||||
|
|
@ -71,23 +88,41 @@ impl Wallet {
|
||||||
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
|
||||||
Ok(endpoint) => Self {
|
Ok(endpoint) => Self {
|
||||||
endpoint: Some(endpoint),
|
endpoint: Some(endpoint),
|
||||||
|
no_spend,
|
||||||
},
|
},
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
|
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
|
||||||
Self::disabled()
|
Self {
|
||||||
|
endpoint: None,
|
||||||
|
no_spend,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => Self::disabled(),
|
}
|
||||||
|
_ => Self {
|
||||||
|
endpoint: None,
|
||||||
|
no_spend,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_url(url: &str) -> Result<Self> {
|
pub fn from_url(url: &str) -> Result<Self> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
endpoint: Some(parse_http_url(url, None)?),
|
endpoint: Some(parse_http_url(url, None)?),
|
||||||
|
no_spend: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`.
|
||||||
|
pub fn with_no_spend(mut self, on: bool) -> Self {
|
||||||
|
self.no_spend = on;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn no_spend(&self) -> bool {
|
||||||
|
self.no_spend
|
||||||
|
}
|
||||||
|
|
||||||
pub fn configured(&self) -> bool {
|
pub fn configured(&self) -> bool {
|
||||||
self.endpoint.is_some()
|
self.endpoint.is_some()
|
||||||
}
|
}
|
||||||
|
|
@ -107,7 +142,10 @@ impl Wallet {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
|
pub async fn transfer(&self, address: &str, amount: u64) -> Result<String> {
|
||||||
let v = self
|
if self.no_spend {
|
||||||
|
return Err(Error(VIEW_ONLY_MSG.into()));
|
||||||
|
}
|
||||||
|
let sent = self
|
||||||
.rpc(
|
.rpc(
|
||||||
"transfer",
|
"transfer",
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
|
|
@ -115,10 +153,36 @@ impl Wallet {
|
||||||
"account_index": 0
|
"account_index": 0
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.await?;
|
.await;
|
||||||
|
let v = match sent {
|
||||||
|
Ok(v) => v,
|
||||||
|
// The wallet's own refusal is opaque, so ask the documented
|
||||||
|
// pre-transfer signal before surfacing it. Fail closed: if the
|
||||||
|
// probe cannot answer, the original error stands.
|
||||||
|
Err(e) => {
|
||||||
|
if self.view_only().await {
|
||||||
|
return Err(Error(VIEW_ONLY_MSG.into()));
|
||||||
|
}
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
json_str(&v, "tx_hash")
|
json_str(&v, "tx_hash")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// View-only detection over RPC: `query_key` with `key_type=spend_key` is
|
||||||
|
/// the signal monero actually exposes for a wallet with no spend key.
|
||||||
|
/// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29)
|
||||||
|
/// ("Cannot retrieve spend key"); a spend-capable wallet returns the key,
|
||||||
|
/// which this discards.
|
||||||
|
/// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`.
|
||||||
|
async fn view_only(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self.rpc("query_key", serde_json::json!({"key_type": "spend_key"}))
|
||||||
|
.await,
|
||||||
|
Err(e) if e.to_string() == VIEW_ONLY_MSG
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
|
pub async fn get_transfers(&self) -> Result<Vec<TransferRow>> {
|
||||||
let v = self
|
let v = self
|
||||||
.rpc(
|
.rpc(
|
||||||
|
|
@ -189,6 +253,17 @@ fn credentials_required() -> Error {
|
||||||
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
|
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or
|
||||||
|
/// unset) means off.
|
||||||
|
fn env_flag(name: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
std::env::var(name)
|
||||||
|
.map(|v| v.trim().to_ascii_lowercase())
|
||||||
|
.as_deref(),
|
||||||
|
Ok("1" | "true" | "yes" | "on")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
|
fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
|
||||||
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
|
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
|
||||||
if user.is_empty() || pass.is_empty() {
|
if user.is_empty() || pass.is_empty() {
|
||||||
|
|
@ -455,6 +530,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result<serde_json::Value> {
|
||||||
.get("message")
|
.get("message")
|
||||||
.and_then(|m| m.as_str())
|
.and_then(|m| m.as_str())
|
||||||
.unwrap_or("rpc error");
|
.unwrap_or("rpc error");
|
||||||
|
// The one RPC-level error we translate: a view-only wallet has no
|
||||||
|
// spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`).
|
||||||
|
if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) {
|
||||||
|
return Err(Error(VIEW_ONLY_MSG.into()));
|
||||||
|
}
|
||||||
return Err(Error(msg.into()));
|
return Err(Error(msg.into()));
|
||||||
}
|
}
|
||||||
json.get("result")
|
json.get("result")
|
||||||
|
|
|
||||||
233
tests/wallet.rs
233
tests/wallet.rs
|
|
@ -1,5 +1,7 @@
|
||||||
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use ed25519_dalek::SigningKey;
|
use ed25519_dalek::SigningKey;
|
||||||
use onionwire::pay;
|
use onionwire::pay;
|
||||||
use onionwire::wallet::{self, TransferRow, Wallet};
|
use onionwire::wallet::{self, TransferRow, Wallet};
|
||||||
|
|
@ -8,6 +10,10 @@ use rand::rngs::OsRng;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
|
||||||
|
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
|
||||||
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
|
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
|
||||||
TransferRow {
|
TransferRow {
|
||||||
txid: txid.into(),
|
txid: txid.into(),
|
||||||
|
|
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Records every request the client sends, answers the Digest challenge and
|
||||||
|
/// then replies per RPC method. Lets a test assert on the *request log*.
|
||||||
|
async fn serve_recording(
|
||||||
|
listener: TcpListener,
|
||||||
|
log: Arc<Mutex<Vec<String>>>,
|
||||||
|
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||||||
|
) {
|
||||||
|
loop {
|
||||||
|
let Ok((mut sock, _)) = listener.accept().await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let mut buf = vec![0u8; 8192];
|
||||||
|
let n = sock.read(&mut buf).await.unwrap_or(0);
|
||||||
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||||
|
log.lock().expect("log").push(req.clone());
|
||||||
|
if req.contains("Authorization:") {
|
||||||
|
let body = reply(&rpc_method(&req));
|
||||||
|
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
|
||||||
|
} else {
|
||||||
|
let _ = sock.write_all(digest_401().as_bytes()).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rpc_method(req: &str) -> String {
|
||||||
|
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
|
||||||
|
serde_json::from_str::<serde_json::Value>(body.trim())
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn http_200_body(body: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rpc_error(code: i64, message: &str) -> String {
|
||||||
|
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// JSON-RPC body only (the server wraps it in an HTTP 200).
|
||||||
|
fn rpc_result(result: &str) -> String {
|
||||||
|
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recording_wallet(port: u16) -> Wallet {
|
||||||
|
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
|
||||||
|
/// local `transfer` before any socket is opened.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::clone(&log),
|
||||||
|
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
|
||||||
|
));
|
||||||
|
let w = recording_wallet(port).with_no_spend(true);
|
||||||
|
assert!(w.no_spend());
|
||||||
|
let err = w
|
||||||
|
.transfer(
|
||||||
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string();
|
||||||
|
assert!(
|
||||||
|
err.to_ascii_lowercase().contains("view-only"),
|
||||||
|
"got {err}"
|
||||||
|
);
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||||
|
let seen = log.lock().expect("log").clone();
|
||||||
|
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
|
||||||
|
// Positive control: the recorder is live, so the emptiness above is real.
|
||||||
|
let _ = w.get_address().await;
|
||||||
|
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
|
||||||
|
/// with the no-spend flag on — only `transfer` is refused.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::clone(&log),
|
||||||
|
Arc::new(|method| match method {
|
||||||
|
"create_address" => rpc_result(
|
||||||
|
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
|
||||||
|
),
|
||||||
|
"get_transfers" => rpc_result(
|
||||||
|
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
|
||||||
|
),
|
||||||
|
_ => rpc_result(r#"{}"#),
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let w = recording_wallet(port).with_no_spend(true);
|
||||||
|
let created = w.create_address().await.expect("create_address");
|
||||||
|
assert!(created.starts_with('8'), "got {created}");
|
||||||
|
let rows = w.get_transfers().await.expect("get_transfers");
|
||||||
|
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
|
||||||
|
let seen = log.lock().expect("log").clone();
|
||||||
|
assert!(
|
||||||
|
seen.iter()
|
||||||
|
.any(|r| r.contains("\"method\":\"create_address\"")),
|
||||||
|
"recorder must have seen the invoice path: {seen:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
|
||||||
|
"transfer must never be dialed in no-spend mode"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A view-only wallet refuses `transfer` with its own opaque error. The
|
||||||
|
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
|
||||||
|
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let log = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::clone(&log),
|
||||||
|
Arc::new(|method| match method {
|
||||||
|
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||||||
|
_ => rpc_error(-18, "No transaction created"),
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let w = recording_wallet(port);
|
||||||
|
assert!(!w.no_spend());
|
||||||
|
let err = w
|
||||||
|
.transfer(
|
||||||
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string();
|
||||||
|
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||||
|
let seen = log.lock().expect("log").clone();
|
||||||
|
assert!(
|
||||||
|
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
|
||||||
|
"must ask the RPC-side signal: {seen:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A spend-capable wallet must keep its real error: no fabricated detection.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
tokio::spawn(serve_recording(
|
||||||
|
listener,
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
Arc::new(|method| match method {
|
||||||
|
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||||||
|
_ => rpc_error(-18, "No transaction created"),
|
||||||
|
}),
|
||||||
|
));
|
||||||
|
let err = recording_wallet(port)
|
||||||
|
.transfer(
|
||||||
|
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string();
|
||||||
|
assert!(err.contains("No transaction created"), "got {err}");
|
||||||
|
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn open_rpc_without_digest_challenge_is_still_refused() {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let canned = http_200_body(
|
||||||
|
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
|
||||||
|
);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut sock, _) = listener.accept().await.expect("accept");
|
||||||
|
let mut buf = vec![0u8; 4096];
|
||||||
|
let _ = sock.read(&mut buf).await;
|
||||||
|
let _ = sock.write_all(canned.as_bytes()).await;
|
||||||
|
});
|
||||||
|
let err = recording_wallet(port)
|
||||||
|
.get_address()
|
||||||
|
.await
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string();
|
||||||
|
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
|
||||||
|
#[test]
|
||||||
|
fn from_env_reads_no_spend_flag() {
|
||||||
|
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
unsafe {
|
||||||
|
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
|
||||||
|
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
|
||||||
|
}
|
||||||
|
let on = Wallet::from_env();
|
||||||
|
assert!(on.no_spend(), "flag 1 must mean no-spend");
|
||||||
|
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
|
||||||
|
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
|
||||||
|
for off in ["0", "no", "off"] {
|
||||||
|
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
|
||||||
|
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
|
||||||
|
}
|
||||||
|
unsafe {
|
||||||
|
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
|
||||||
|
std::env::remove_var("ONIONWIRE_WALLET_RPC");
|
||||||
|
}
|
||||||
|
assert!(!Wallet::from_env().no_spend(), "unset must be off");
|
||||||
|
}
|
||||||
|
|
||||||
fn digest_401() -> String {
|
fn digest_401() -> String {
|
||||||
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
|
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue