Skip to content

Commit

Permalink
jsonrpc: don't ignore invalid params to listaddresses
Browse files Browse the repository at this point in the history
  • Loading branch information
darosior committed Nov 11, 2023
1 parent d533820 commit 0812a12
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 13 deletions.
29 changes: 18 additions & 11 deletions src/jsonrpc/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,21 +136,28 @@ fn list_coins(control: &DaemonControl, params: Option<Params>) -> Result<serde_j
Ok(serde_json::json!(&res))
}

fn get_opt_u32<Q>(params: &Option<Params>, index: usize, name: &Q) -> Result<Option<u32>, Error>
where
String: std::borrow::Borrow<Q>,
Q: ?Sized + Ord + Eq + std::hash::Hash + std::fmt::Display,
{
Ok(
if let Some(i) = params.as_ref().and_then(|p| p.get(index, name)) {
Some(i.as_u64().and_then(|i| i.try_into().ok()).ok_or_else(|| {
Error::invalid_params(format!("Invalid value for '{}': {}", name, i))
})?)
} else {
None
},
)
}

fn list_addresses(
control: &DaemonControl,
params: Option<Params>,
) -> Result<serde_json::Value, Error> {
let start_index: Option<u32> = params
.as_ref()
.and_then(|p| p.get(0, "start_index"))
.and_then(|i| i.as_u64())
.and_then(|i| i.try_into().ok());

let count: Option<u32> = params
.as_ref()
.and_then(|p| p.get(1, "count"))
.and_then(|c| c.as_u64())
.and_then(|i| i.try_into().ok());
let start_index = get_opt_u32(&params, 0, "start_index")?;
let count = get_opt_u32(&params, 1, "count")?;

let res = &control.list_addresses(start_index, count)?;
Ok(serde_json::json!(&res))
Expand Down
20 changes: 18 additions & 2 deletions tests/test_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,29 @@ def test_listaddresses(lianad):
assert addr[-1]["index"] == 6

list3 = lianad.rpc.listaddresses() # start_index = 0, receive_index = 0
_ = lianad.rpc.getnewaddress() # start_index = 0, receive_index = 1
_ = lianad.rpc.getnewaddress() # start_index = 0, receive_index = 2
_ = lianad.rpc.getnewaddress() # start_index = 0, receive_index = 1
_ = lianad.rpc.getnewaddress() # start_index = 0, receive_index = 2
list4 = lianad.rpc.listaddresses()
assert len(list4["addresses"]) == len(list3["addresses"]) + 2 == 2
list5 = lianad.rpc.listaddresses(0)
assert list4 == list5

# Will explicitly error on invalid start_index.
with pytest.raises(
RpcError,
match=re.escape(
"Invalid params: Invalid value for \\'start_index\\': \"blabla\""
),
):
lianad.rpc.listaddresses("blabla", None)

# Will explicitly error on invalid count.
with pytest.raises(
RpcError,
match=re.escape("Invalid params: Invalid value for \\'count\\': \"blb\""),
):
lianad.rpc.listaddresses(0, "blb")


def test_listcoins(lianad, bitcoind):
# Initially empty
Expand Down

0 comments on commit 0812a12

Please sign in to comment.