Skip to content
This repository has been archived by the owner on Feb 29, 2024. It is now read-only.

UP-42: Add API calls for frozen ledgers #2356

Merged
merged 12 commits into from
Feb 8, 2021
118 changes: 118 additions & 0 deletions cli/src/commands/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2042,6 +2042,91 @@ pub mod get_acceptance_mechanisms_command {
}
}

pub mod ledgers_freeze_command {
use super::*;

command!(CommandMetadata::build("ledgers-freeze", r#"Freeze all ledgers"#)
.add_required_param("ledgers_ids", "List ledgers for freeze.")
Toktar marked this conversation as resolved.
Show resolved Hide resolved
.add_example("ledger ledgers-freeze ledgers_ids=[1,2,3]")
.finalize()
);

fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?} params {:?}", ctx, params);

let submitter_did = ensure_active_did(&ctx)?;
let (wallet_handle, wallet_name) = ensure_opened_wallet(&ctx)?;
let ledgers_ids = get_str_param("ledgers_ids", params).map_err(error_err!())?;

let request = Ledger::build_ledgers_freeze_request(&submitter_did, ledgers_ids)
.map_err(|err| handle_indy_error(err, None, None, None))?;

let (_, response) = send_write_request!(&ctx, params, &request, wallet_handle, &wallet_name, &submitter_did);

let result = handle_transaction_response(response)?;

println!("result {:?}", result);

trace!("execute <<");
Ok(())
}
}

pub mod get_frozen_ledgers_command {
use super::*;
use serde_json::Value;

command!(CommandMetadata::build("get-frozen-ledgers", r#"Get a list of frozen ledgers"#)
.add_example("ledger get-frozen-ledgers")
.finalize()
);

fn execute(ctx: &CommandContext, params: &CommandParams) -> Result<(), ()> {
trace!("execute >> ctx {:?} params {:?}", ctx, params);

let submitter_did = ensure_active_did(&ctx)?;

let request = Ledger::build_get_frozen_ledgers_request(&submitter_did)
.map_err(|err| handle_indy_error(err, None, None, None))?;

let (_, response) = send_read_request!(&ctx, params, &request, Some(&submitter_did));
let result = handle_transaction_response(response)?;

// Flattering ap into vector
let result = result.as_object()
.expect("top level object is not a map")
.iter()
.map(|kv| {
let key = kv.0;
let value = kv.1;
Copy link
Contributor

@Toktar Toktar Feb 1, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please rename them to ledger_id and ledger_info?
The next variable ledger_id can be renamed to json_ledger_id.


let mut flat_value = value.as_object()
.expect("inner object is not a map").clone();

let ledger_id = serde_json::to_value(&key).unwrap();
Toktar marked this conversation as resolved.
Show resolved Hide resolved
flat_value.insert("ledger_id".to_owned(), ledger_id);

serde_json::to_value(&flat_value).unwrap()
Toktar marked this conversation as resolved.
Show resolved Hide resolved
}).collect::<Vec<Value>>();

print_frozen_ledgers(result)?;
trace!("execute <<");
Ok(())
}

fn print_frozen_ledgers(frozen_ledgers: Vec<serde_json::Value>) -> Result<(), ()> {
println_succ!("Following Receipts has been received.");
Toktar marked this conversation as resolved.
Show resolved Hide resolved
print_list_table(&frozen_ledgers,
&[("ledger_id", "Ledger id"),
("ledger", "Payment Address of recipient"),
("state", "Amount"),
("seq_no", "Extra")],
Toktar marked this conversation as resolved.
Show resolved Hide resolved
"");
Toktar marked this conversation as resolved.
Show resolved Hide resolved

Ok(())
}
}

pub fn set_author_agreement(ctx: &CommandContext, request: &mut String) -> Result<(), ()> {
if let Some((text, version, acc_mech_type, time_of_acceptance)) = get_transaction_author_info(&ctx) {
if acc_mech_type.is_empty() {
Expand Down Expand Up @@ -2251,6 +2336,8 @@ fn get_txn_title(role: &serde_json::Value) -> serde_json::Value {
Some("5") => "TXN_AUTHR_AGRMT_AML",
Some("6") => "GET_TXN_AUTHR_AGRMT",
Some("7") => "GET_TXN_AUTHR_AGRMT_AML",
Some("9") => "LEDGERS_FREEZE",
Some("10") => "GET_FROZEN_LEDGERS",
Some("100") => "ATTRIB",
Some("101") => "SCHEMA",
Some("104") => "GET_ATTR",
Expand Down Expand Up @@ -5079,6 +5166,37 @@ pub mod tests {
}
}

mod frozen_ledgers {
use super::*;

#[test]
pub fn ledgers_freeze() {
let ctx = setup();

{
let cmd = ledgers_freeze_command::new();
let mut params = CommandParams::new();
params.insert("ledgers_ids", json!(vec![0, 1, 10, 23]).to_string());
cmd.execute(&ctx, &params).unwrap_err();
}

tear_down();
}

#[test]
pub fn get_frozen_ledgers() {
let ctx = setup();

{
let cmd = get_frozen_ledgers_command::new();
let params = CommandParams::new();
cmd.execute(&ctx, &params).unwrap_err();
}

tear_down();
}
}

fn _path() -> (::std::path::PathBuf, String) {
let mut path = crate::utils::environment::EnvironmentUtils::indy_home_path();
path.push("transaction");
Expand Down
8 changes: 8 additions & 0 deletions cli/src/libindy/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,12 @@ impl Ledger {
endorser_did: &str) -> Result<String, IndyError> {
ledger::append_request_endorser(request_json, endorser_did).wait()
}

pub fn build_ledgers_freeze_request(submitter_did: &str, ledgers_ids: &str) -> Result<String, IndyError> {
ledger::build_ledgers_freeze_request(submitter_did, ledgers_ids).wait()
}

pub fn build_get_frozen_ledgers_request(submitter_did: &str) -> Result<String, IndyError> {
ledger::build_get_frozen_ledgers_request(submitter_did).wait()
}
}
2 changes: 2 additions & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ fn build_executor() -> CommandExecutor {
.add_command(ledger::get_acceptance_mechanisms_command::new())
.add_command(ledger::endorse_transaction_command::new())
.add_command(ledger::taa_disable_all_command::new())
.add_command(ledger::ledgers_freeze_command::new())
.add_command(ledger::get_frozen_ledgers_command::new())
.finalize_group()
.add_group(payment_address::group::new())
.add_command(payment_address::new_command::new())
Expand Down
85 changes: 85 additions & 0 deletions libindy/src/api/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1792,6 +1792,91 @@ pub extern fn indy_get_response_metadata(command_handle: CommandHandle,
res
}

/// Builds a LEDGERS_FREEZE request. Request to freeze list of ledgers.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// submitter_did: (Optional) DID of the read request sender (if not provided then default Libindy DID will be used).
/// ledgers_ids: list ids for freeze ledgers (json format).
Toktar marked this conversation as resolved.
Show resolved Hide resolved
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Request result as json.
///
/// #Errors
/// Common*
#[no_mangle]
pub extern fn indy_build_ledgers_freeze_request (command_handle: CommandHandle,
submitter_did: *const c_char,
ledgers_ids: *const c_char,
Toktar marked this conversation as resolved.
Show resolved Hide resolved
cb: Option<extern fn(command_handle_: CommandHandle,
err: ErrorCode,
request_json: *const c_char)>) -> ErrorCode {
trace!("indy_build_ledgers_freeze_request: entities >>> submitter_did: {:?}, ledgers_ids: {:?}", submitter_did, ledgers_ids);

check_useful_validatable_string!(submitter_did, ErrorCode::CommonInvalidParam2, DidValue);
check_useful_json!(ledgers_ids, ErrorCode::CommonInvalidParam3, Vec<u64>);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);

let result = CommandExecutor::instance()
.send(Command::Ledger(LedgerCommand::BuildLedgersFreezeRequest(
submitter_did,
ledgers_ids,
boxed_callback_string!("indy_build_ledgers_freeze_request", cb, command_handle)
)));

let res = prepare_result!(result);

trace!("indy_build_ledgers_freeze_request: <<< res: {:?}", res);

res
}

/// Builds a GET_FROZEN_LEDGERS request. Request to get list of frozen ledgers.
/// frozen ledgers are defined by LEDGERS_FREEZE request.
///
/// #Params
/// command_handle: command handle to map callback to caller context.
/// submitter_did: (Optional) DID of the read request sender (if not provided then default Libindy DID will be used).
/// cb: Callback that takes command result as parameter.
///
/// #Returns
/// Request result as json.
/// {
/// <ledger_id>: {
/// "ledger": String - Ledger root hash,
/// "state": String - State root hash,
/// "seq_no": u64 - the latest transaction seqNo for particular Node,
/// },
/// ...
/// }
///
/// #Errors
/// Common*
#[no_mangle]
pub extern fn indy_build_get_frozen_ledgers_request (command_handle: CommandHandle,
submitter_did: *const c_char,
cb: Option<extern fn(command_handle_: CommandHandle,
err: ErrorCode,
request_json: *const c_char)>) -> ErrorCode {
trace!("indy_build_get_frozen_ledgers_request: entities >>> submitter_did: {:?}", submitter_did);

check_useful_validatable_string!(submitter_did, ErrorCode::CommonInvalidParam2, DidValue);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam3);

let result = CommandExecutor::instance()
.send(Command::Ledger(LedgerCommand::BuildGetFrozenLedgersRequest(
submitter_did,
boxed_callback_string!("indy_build_get_frozen_ledgers_request", cb, command_handle)
)));

let res = prepare_result!(result);

trace!("indy_build_get_frozen_ledgers_request: <<< res: {:?}", res);

res
}

/// Builds a AUTH_RULE request. Request to change authentication rules for a ledger transaction.
///
/// #Params
Expand Down
39 changes: 39 additions & 0 deletions libindy/src/commands/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,13 @@ pub enum LedgerCommand {
String, // request json
DidValue, // endorser did
Box<dyn Fn(IndyResult<String>) + Send>),
BuildGetFrozenLedgersRequest(
DidValue, // submitter did
Box<dyn Fn(IndyResult<String>) + Send>),
BuildLedgersFreezeRequest(
DidValue, // submitter did
Vec<u64>, // ledgers ids
Box<dyn Fn(IndyResult<String>) + Send>),
}

pub struct LedgerCommandExecutor {
Expand Down Expand Up @@ -528,6 +535,14 @@ impl LedgerCommandExecutor {
cb(self.append_request_endorser(&request_json,
&endorser_did));
}
LedgerCommand::BuildLedgersFreezeRequest(submitter_did, ledgers_ids, cb) => {
debug!(target: "ledger_command_executor", "BuildLedgersFreezeRequest command received");
cb(self.build_ledgers_freeze_request(&submitter_did, ledgers_ids));
}
LedgerCommand::BuildGetFrozenLedgersRequest(submitter_did, cb) => {
debug!(target: "ledger_command_executor", "BuildGetFrozenLedgersRequest command received");
cb(self.build_get_frozen_ledgers_request(&submitter_did));
}
};
}

Expand Down Expand Up @@ -1308,6 +1323,30 @@ impl LedgerCommandExecutor {
let pool_response = try_cb!(pool_response, cb);
cb(self.ledger_service.parse_get_cred_def_response(&pool_response, id.get_method().as_ref().map(String::as_str)))
}

fn build_ledgers_freeze_request(&self, submitter_did: &DidValue, ledgers_ids: Vec<u64>) -> IndyResult<String>{
debug!("build_ledgers_freeze_request >>> submitter_did: {:?}, ledgers_ids: {:?}", submitter_did, ledgers_ids);

self.crypto_service.validate_did(&submitter_did)?;

let res = self.ledger_service.build_ledgers_freeze_request(&submitter_did, ledgers_ids)?;

debug!("build_ledgers_freeze_request <<< res: {:?}", res);

Ok(res)
}

fn build_get_frozen_ledgers_request(&self, submitter_did: &DidValue) -> IndyResult<String> {
debug!("build_get_frozen_ledgers_request >>> submitter_did: {:?}", submitter_did);

self.crypto_service.validate_did(&submitter_did)?;

let res = self.ledger_service.build_get_frozen_ledgers_request(&submitter_did)?;

debug!("build_get_frozen_ledgers_request <<< res: {:?}", res);

Ok(res)
}
}

enum SignatureType {
Expand Down
8 changes: 6 additions & 2 deletions libindy/src/domain/ledger/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pub const TXN_AUTHR_AGRMT_AML: &str = "5";
pub const GET_TXN_AUTHR_AGRMT: &str = "6";
pub const GET_TXN_AUTHR_AGRMT_AML: &str = "7";
pub const DISABLE_ALL_TXN_AUTHR_AGRMTS: &str = "8";
pub const LEDGERS_FREEZE: &str = "9";
pub const GET_FROZEN_LEDGERS: &str = "10";
pub const ATTRIB: &str = "100";
pub const SCHEMA: &str = "101";
pub const CRED_DEF: &str = "102";
Expand All @@ -27,10 +29,10 @@ pub const GET_AUTH_RULE: &str = "121";
pub const AUTH_RULES: &str = "122";
pub const GET_DDO: &str = "120";//TODO change number

pub const REQUESTS: [&str; 25] = [NODE, NYM, GET_TXN, ATTRIB, SCHEMA, CRED_DEF, GET_ATTR, GET_NYM, GET_SCHEMA,
pub const REQUESTS: [&str; 27] = [NODE, NYM, GET_TXN, ATTRIB, SCHEMA, CRED_DEF, GET_ATTR, GET_NYM, GET_SCHEMA,
GET_CRED_DEF, POOL_UPGRADE, POOL_RESTART, POOL_CONFIG, REVOC_REG_DEF, REVOC_REG_ENTRY, GET_REVOC_REG_DEF,
GET_REVOC_REG, GET_REVOC_REG_DELTA, GET_VALIDATOR_INFO, AUTH_RULE, GET_DDO, TXN_AUTHR_AGRMT, TXN_AUTHR_AGRMT_AML,
GET_TXN_AUTHR_AGRMT, GET_TXN_AUTHR_AGRMT_AML];
GET_TXN_AUTHR_AGRMT, GET_TXN_AUTHR_AGRMT_AML, LEDGERS_FREEZE, GET_FROZEN_LEDGERS];

pub const TRUSTEE: &str = "0";
pub const STEWARD: &str = "2";
Expand Down Expand Up @@ -71,6 +73,8 @@ pub fn txn_name_to_code(txn: &str) -> Option<&str> {
"TXN_AUTHR_AGRMT_AML" => Some(TXN_AUTHR_AGRMT_AML),
"GET_TXN_AUTHR_AGRMT" => Some(GET_TXN_AUTHR_AGRMT),
"GET_TXN_AUTHR_AGRMT_AML" => Some(GET_TXN_AUTHR_AGRMT_AML),
"LEDGERS_FREEZE" => Some(LEDGERS_FREEZE),
"GET_FROZEN_LEDGERS" => Some(GET_FROZEN_LEDGERS),
val => Some(val)
}
}
31 changes: 31 additions & 0 deletions libindy/src/domain/ledger/ledgers_freeze.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use super::constants::{LEDGERS_FREEZE, GET_FROZEN_LEDGERS};

#[derive(Serialize, PartialEq, Debug)]
pub struct LedgersFreezeOperation {
#[serde(rename = "type")]
pub _type: String,
pub ledgers_ids: Vec<u64>,
}

impl LedgersFreezeOperation {
pub fn new(ledgers_ids: Vec<u64>) -> LedgersFreezeOperation {
LedgersFreezeOperation {
ledgers_ids,
_type: LEDGERS_FREEZE.to_string()
Toktar marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

#[derive(Serialize, PartialEq, Debug)]
pub struct GetFrozenLedgersOperation {
#[serde(rename = "type")]
pub _type: String
}

impl GetFrozenLedgersOperation {
pub fn new() -> GetFrozenLedgersOperation {
GetFrozenLedgersOperation {
_type: GET_FROZEN_LEDGERS.to_string()
}
}
}
1 change: 1 addition & 0 deletions libindy/src/domain/ledger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ pub mod validator_info;
pub mod constants;
pub mod auth_rule;
pub mod author_agreement;
pub mod ledgers_freeze;
Loading