Skip to content

Commit

Permalink
Add account state getter to REST API
Browse files Browse the repository at this point in the history
  • Loading branch information
CodeSandwich committed May 15, 2019
1 parent 870be55 commit 0366c14
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cardano-deps
1 change: 1 addition & 0 deletions src/rest/mod.rs
Expand Up @@ -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()))
Expand Down
53 changes: 53 additions & 0 deletions src/rest/v0/account/mod.rs
@@ -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 change: 1 addition & 0 deletions src/rest/v0/mod.rs
@@ -1,3 +1,4 @@
pub mod account;
pub mod block;
pub mod message;
pub mod node;
Expand Down

0 comments on commit 0366c14

Please sign in to comment.