Skip to content
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

Handling item-not-found case in RPC methods is difficult #243

Open
casey opened this issue Sep 9, 2022 · 0 comments
Open

Handling item-not-found case in RPC methods is difficult #243

casey opened this issue Sep 9, 2022 · 0 comments

Comments

@casey
Copy link
Contributor

casey commented Sep 9, 2022

For some RPC methods, like get_block_hash, get_block, and get_raw_transaction, it's often nice to handle the case where the requested item isn't found specially. I was able to do this, code reproduced below, but it's rather messy. It would be nice if such functions returned Option<T> instead of T, to avoid needing to write special-case code.

fn block_at_height(client: &Client, height: u64) -> Result<Option<Block>> {
  match client.get_block_hash(height) {
    Ok(hash) => Ok(Some(client.get_block(&hash)?)),
    Err(bitcoincore_rpc::Error::JsonRpc(bitcoincore_rpc::jsonrpc::error::Error::Rpc(
      bitcoincore_rpc::jsonrpc::error::RpcError { code: -8, .. },
    ))) => Ok(None),
    Err(bitcoincore_rpc::Error::JsonRpc(bitcoincore_rpc::jsonrpc::error::Error::Rpc(
      bitcoincore_rpc::jsonrpc::error::RpcError { message, .. },
    )))
      if message == "Block not found" =>
    {
      Ok(None)
    }
    Err(err) => Err(err.into()),
  }
}

pub(crate) fn block_with_hash(&self, hash: sha256d::Hash) -> Result<Option<Block>> {
  match self.client.get_block(&BlockHash::from_hash(hash)) {
    Ok(block) => Ok(Some(block)),
    Err(bitcoincore_rpc::Error::JsonRpc(bitcoincore_rpc::jsonrpc::error::Error::Rpc(
      bitcoincore_rpc::jsonrpc::error::RpcError { code: -8, .. },
    ))) => Ok(None),
    Err(bitcoincore_rpc::Error::JsonRpc(bitcoincore_rpc::jsonrpc::error::Error::Rpc(
      bitcoincore_rpc::jsonrpc::error::RpcError { message, .. },
    )))
      if message == "Block not found" =>
    {
      Ok(None)
    }
    Err(err) => Err(err.into()),
  }
}

pub(crate) fn transaction(&self, txid: Txid) -> Result<Option<Transaction>> {
  match self.client.get_raw_transaction(&txid, None) {
    Ok(transaction) => Ok(Some(transaction)),
    Err(bitcoincore_rpc::Error::JsonRpc(bitcoincore_rpc::jsonrpc::error::Error::Rpc(
      bitcoincore_rpc::jsonrpc::error::RpcError { code: -8, .. },
    ))) => Ok(None),
    Err(err) => Err(err.into()),
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant