Skip to content
Permalink
Browse files

Add account state getter to REST API

  • Loading branch information...
CodeSandwich committed May 14, 2019
1 parent 870be55 commit 0366c1430f092967d3e4cab166d0fd94f27c0f6c
Showing with 56 additions and 1 deletion.
  1. +1 −1 cardano-deps
  2. +1 −0 src/rest/mod.rs
  3. +53 −0 src/rest/v0/account/mod.rs
  4. +1 −0 src/rest/v0/mod.rs
@@ -22,6 +22,7 @@ pub fn start_rest_server(config: &Rest, context: Context) -> Result<Server, Conf
.map(|prefix| prefix.as_str())
.unwrap_or("");
Server::builder(config.pkcs12.clone(), config.listen.clone(), prefix)
.add_handler(v0::account::create_handler(context.blockchain.clone()))
.add_handler(v0::block::create_handler(context.blockchain.clone()))
.add_handler(v0::node::stats::create_handler(context.stats_counter))
.add_handler(v0::tip::create_handler(context.blockchain.clone()))
@@ -0,0 +1,53 @@
use crate::blockchain::BlockchainR;
use actix_web::error::{Error, ErrorBadRequest, ErrorNotFound};
use actix_web::{App, Json, Path, Responder, State};
use chain_crypto::{bech32::Bech32, PublicKey};
use chain_impl_mockchain::account::{AccountAlg, Identifier};
use chain_impl_mockchain::accounting::account::AccountState;

pub fn create_handler(
blockchain: BlockchainR,
) -> impl Fn(&str) -> App<BlockchainR> + Send + Sync + Clone + 'static {
move |prefix: &str| {
App::with_state(blockchain.clone())
.prefix(format!("{}/v0/account", prefix))
.resource("/{account_id}", |r| r.get().with(handle_request))
}
}

fn handle_request(
blockchain: State<BlockchainR>,
account_id_bech32: Path<String>,
) -> Result<impl Responder, Error> {
let account_id = parse_account_id(&account_id_bech32)?;
let blockchain = blockchain.lock_read();
let state = blockchain
.multiverse
.get(&blockchain.get_tip().unwrap())
.unwrap()
.accounts()
.get_state(&account_id)
.map_err(|e| ErrorNotFound(e))?;
Ok(Json(AccountDto::from(state)))
}

fn parse_account_id(bech32: &str) -> Result<Identifier, Error> {
PublicKey::<AccountAlg>::try_from_bech32_str(bech32)
.map(Into::into)
.map_err(|e| ErrorBadRequest(e))
}

#[derive(Serialize)]
struct AccountDto {
value: u64,
counter: u32,
}

impl<'a> From<&'a AccountState> for AccountDto {
fn from(state: &'a AccountState) -> Self {
AccountDto {
value: state.get_value().as_ref().clone(),
counter: state.get_counter().into(),
}
}
}
@@ -1,3 +1,4 @@
pub mod account;
pub mod block;
pub mod message;
pub mod node;

0 comments on commit 0366c14

Please sign in to comment.
You can’t perform that action at this time.