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

feat: Add --subaccount flag to public-ids #201

Merged
merged 3 commits into from
Jun 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

- Added `--subaccount` to `quill public-ids`. (#201)
- Added Ledger support via `--ledger`. (#199)
- Added `--confirmation-text` to `quill sns pay`. (#195)
- Fixed `quill ckbtc update-balance` allowing the anonymous principal. (#191)
Expand Down
19 changes: 17 additions & 2 deletions docs/cli-reference/quill-public-ids.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ quill public-ids [option]

| Option | Description |
|---------------------------------|--------------------------------------------|
| `--principal-id <PRINCIPAL_ID>` | Principal for which to get the account_id. |
| `--principal-id <PRINCIPAL_ID>` | Principal for which to get the account id. |
| `--subaccount <SUBACCOUNT>` | Subaccount to include in the account ID. |

## Examples

Expand All @@ -38,5 +39,19 @@ This will produce the output:

```
Principal id: 2vxsx-fae
Account id: 1c7a48ba6a562aa9eaa2481a9049cdf0433b9738c992d698c31d8abf89cadc79
Legacy account id: 1c7a48ba6a562aa9eaa2481a9049cdf0433b9738c992d698c31d8abf89cadc79
```

It can also be used to display ICRC-1 account IDs:

```sh
quill public-ids --subaccount 010203
```

This will produce output like:

```
Principal id: fdsgv-62ihb-nbiqv-xgic5-iefsv-3cscz-tmbzv-63qd5-vh43v-dqfrt-pae
Legacy account id: 0ae94165785f2ffb9c56ebc84f3d13299f28db78c80b1db43c0d114eed6105af
ICRC-1 account id: fdsgv-62ihb-nbiqv-xgic5-iefsv-3cscz-tmbzv-63qd5-vh43v-dqfrt-pae-al4mwai.10203
```
8 changes: 4 additions & 4 deletions src/commands/account_balance.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use crate::{
commands::send::submit_unsigned_ingress,
lib::{
ledger_canister_id, AnyhowResult, AuthInfo, ParsedNnsAccount, ROLE_ICRC1_LEDGER,
ROLE_NNS_LEDGER,
get_account_id, ledger_canister_id, AnyhowResult, AuthInfo, ParsedNnsAccount,
ROLE_ICRC1_LEDGER, ROLE_NNS_LEDGER,
},
};
use candid::{CandidType, Encode};
use clap::Parser;

use super::get_ids;
use super::get_principal;

#[derive(CandidType)]
pub struct AccountBalanceArgs {
Expand Down Expand Up @@ -37,7 +37,7 @@ pub async fn exec(auth: &AuthInfo, opts: AccountBalanceOpts, fetch_root_key: boo
let account_id = if let Some(id) = opts.account_id {
id
} else {
let (_, id) = get_ids(auth)?;
let id = get_account_id(get_principal(auth)?, None)?;
ParsedNnsAccount::Original(id)
};
match account_id {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/ckbtc/retrieve_btc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use ic_ckbtc_minter::updates::retrieve_btc::RetrieveBtcArgs;
use icrc_ledger_types::icrc1::transfer::{Memo, TransferArg};

use crate::{
commands::get_ids,
commands::get_principal,
lib::{
ckbtc_canister_id, ckbtc_minter_canister_id, now_nanos,
signing::{sign_ingress_with_request_status_query, IngressWithRequestId},
Expand Down Expand Up @@ -58,7 +58,7 @@ pub struct RetrieveBtcOpts {
}

pub fn exec(auth: &AuthInfo, opts: RetrieveBtcOpts) -> AnyhowResult<Vec<IngressWithRequestId>> {
let (principal, _) = get_ids(auth)?;
let principal = get_principal(auth)?;
let mut messages = vec![];
let amount = opts.satoshis.unwrap_or_else(|| opts.amount.unwrap().0);
if !opts.already_transferred {
Expand Down
4 changes: 2 additions & 2 deletions src/commands/ckbtc/withdrawal_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use candid::Principal;
use clap::Parser;

use crate::{
commands::get_ids,
commands::get_principal,
lib::{AnyhowResult, AuthInfo, ParsedAccount},
};

Expand All @@ -29,7 +29,7 @@ pub fn exec(auth: &AuthInfo, opts: GetWithdrawalAddressOpts) -> AnyhowResult {
let principal = if let Some(principal) = opts.of {
principal
} else {
get_ids(auth)?.0
get_principal(auth)?
};
let address = ParsedAccount(ckbtc_withdrawal_address(&principal, opts.testnet));
println!("{address}");
Expand Down
7 changes: 4 additions & 3 deletions src/commands/generate.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::lib::{mnemonic_to_pem, AnyhowResult, AuthInfo};
use crate::lib::{get_account_id, mnemonic_to_pem, AnyhowResult, AuthInfo};
use anyhow::{anyhow, Context};
use bip39::{Language, Mnemonic};
use clap::Parser;
Expand Down Expand Up @@ -66,8 +66,9 @@ pub fn exec(opts: GenerateOpts) -> AnyhowResult {
if let Some(path) = opts.pem_file {
std::fs::write(path, &pem)?;
}
let (principal_id, account_id) = crate::commands::public::get_ids(&AuthInfo::PemFile(pem))?;
let principal_id = crate::lib::get_principal(&AuthInfo::PemFile(pem))?;
let account_id = get_account_id(principal_id, None)?;
println!("Principal id: {}", principal_id);
println!("Account id: {}", account_id);
println!("Legacy account id: {}", account_id);
Ok(())
}
6 changes: 2 additions & 4 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! This module implements the command-line API.

use crate::lib::{AnyhowResult, AuthInfo, ParsedAccount, ParsedSubaccount};
use crate::lib::{get_principal, AnyhowResult, AuthInfo, ParsedAccount, ParsedSubaccount};
use anyhow::Context;
use clap::Parser;
use icrc_ledger_types::icrc1::account::Account;
Expand All @@ -25,8 +25,6 @@ mod sns;
mod transfer;
mod update_node_provider;

pub use public::get_ids;

#[derive(Parser)]
pub enum Command {
PublicIds(public::PublicOpts),
Expand Down Expand Up @@ -188,7 +186,7 @@ fn get_account(
let mut account = if let Some(acct) = account {
acct.0
} else if let Some(auth) = auth {
let (principal, _) = get_ids(auth)?;
let principal = get_principal(auth)?;
Account {
owner: principal,
subaccount: None,
Expand Down
2 changes: 1 addition & 1 deletion src/commands/neuron_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub fn exec(auth: &AuthInfo, opts: StakeOpts) -> AnyhowResult<Vec<IngressWithReq
!opts.ledger,
"Cannot use `--ledger` with this command. This version of Quill does not support staking new neurons with a Ledger device"
);
let (controller, _) = crate::commands::public::get_ids(auth)?;
let controller = crate::lib::get_principal(auth)?;
let nonce = match (&opts.nonce, &opts.name) {
(Some(nonce), _) => *nonce,
(_, Some(name)) => convert_name_to_nonce(name),
Expand Down
38 changes: 27 additions & 11 deletions src/commands/public.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
#[cfg(feature = "ledger")]
use crate::lib::ledger::LedgerIdentity;
use crate::lib::{get_account_id, get_identity, AnyhowResult, AuthInfo};
use crate::lib::{
get_account_id, get_principal, AnyhowResult, AuthInfo, ParsedAccount, ParsedSubaccount,
};
use anyhow::{anyhow, bail, Context};
use candid::Principal;
use clap::Parser;
use icp_ledger::AccountIdentifier;
use icrc_ledger_types::icrc1::account::Account;
use k256::{elliptic_curve::sec1::ToEncodedPoint, SecretKey};
use sha3::{Digest, Keccak256};

#[derive(Parser)]
/// Prints the principal id and the account id.
/// Prints the principal and the account IDs.
pub struct PublicOpts {
/// Principal for which to get the account_id.
#[clap(long)]
Expand All @@ -21,13 +24,25 @@ pub struct PublicOpts {
#[cfg_attr(not(feature = "ledger"), clap(hidden = true))]
#[clap(long, requires = "ledgerhq")]
display_on_ledger: bool,
/// Print IDs for the provided subaccount.
#[clap(long)]
subaccount: Option<ParsedSubaccount>,
}

/// Prints the account and the principal ids.
pub fn exec(auth: &AuthInfo, opts: PublicOpts) -> AnyhowResult {
let (principal_id, account_id) = get_public_ids(auth, &opts)?;
println!("Principal id: {}", principal_id.to_text());
println!("Account id: {}", account_id);
println!("Legacy account id: {}", account_id);
if let Some(sub) = opts.subaccount {
println!(
"ICRC-1 account id: {}",
ParsedAccount(Account {
owner: principal_id,
subaccount: Some(sub.0 .0)
})
)
}
if opts.genesis_dfn {
let AuthInfo::PemFile(pem) = auth else {
bail!("Must supply a pem or seed file for the DFN address");
Expand Down Expand Up @@ -55,15 +70,22 @@ fn get_public_ids(
match &opts.principal_id {
Some(principal_id) => {
let principal_id = Principal::from_text(principal_id)?;
Ok((principal_id, get_account_id(principal_id)?))
Ok((
principal_id,
get_account_id(principal_id, opts.subaccount.map(|x| x.0))?,
))
}
None => {
if let AuthInfo::NoAuth = auth {
Err(anyhow!(
"public-ids cannot be used without specifying a private key"
))
} else {
get_ids(auth)
let principal_id = get_principal(auth)?;
Ok((
principal_id,
get_account_id(principal_id, opts.subaccount.map(|x| x.0))?,
))
}
}
}
Expand All @@ -76,9 +98,3 @@ fn get_dfn(pem: &str) -> AnyhowResult<String> {
let hash = Keccak256::digest(&uncompressed.as_bytes()[1..]);
Ok(hex::encode(&hash[12..]))
}

/// Returns the account id and the principal id if the private key was provided.
pub fn get_ids(auth: &AuthInfo) -> AnyhowResult<(Principal, AccountIdentifier)> {
let principal_id = get_identity(auth)?.sender().map_err(|e| anyhow!(e))?;
Ok((principal_id, get_account_id(principal_id)?))
}
4 changes: 2 additions & 2 deletions src/commands/sns/get_sale_participation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use clap::Parser;
use ic_sns_swap::pb::v1::GetBuyerStateRequest;

use crate::{
commands::{get_ids, send::submit_unsigned_ingress},
commands::{get_principal, send::submit_unsigned_ingress},
lib::{AnyhowResult, AuthInfo, ROLE_SNS_SWAP},
};

Expand Down Expand Up @@ -35,7 +35,7 @@ pub async fn exec(
let principal = if let Some(principal) = opts.principal {
principal
} else {
get_ids(auth)?.0
get_principal(auth)?
};
let message = GetBuyerStateRequest {
principal_id: Some(principal.into()),
Expand Down
4 changes: 2 additions & 2 deletions src/commands/sns/get_swap_refund.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use clap::Parser;
use ic_sns_swap::pb::v1::ErrorRefundIcpRequest;

use crate::{
commands::get_ids,
commands::get_principal,
lib::{
signing::{sign_ingress_with_request_status_query, IngressWithRequestId},
AnyhowResult, AuthInfo, ROLE_SNS_SWAP,
Expand Down Expand Up @@ -31,7 +31,7 @@ pub fn exec(
let principal = if let Some(principal) = opts.principal {
principal
} else {
get_ids(auth)?.0
get_principal(auth)?
};
let message = ErrorRefundIcpRequest {
source_principal_id: Some(principal.into()),
Expand Down
4 changes: 2 additions & 2 deletions src/commands/sns/neuron_id.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::commands::get_ids;
use crate::commands::get_principal;
use crate::lib::{AnyhowResult, AuthInfo};
use candid::Principal;
use clap::Parser;
Expand All @@ -22,7 +22,7 @@ pub fn exec(auth: &AuthInfo, opts: NeuronIdOpts) -> AnyhowResult {
let principal_id = if let Some(principal_id) = opts.principal_id {
principal_id
} else {
get_ids(auth)?.0
get_principal(auth)?
};

let neuron_id = NeuronId::from(ledger::compute_neuron_staking_subaccount_bytes(
Expand Down
2 changes: 1 addition & 1 deletion src/commands/sns/pay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn exec(
sns_canister_ids: &SnsCanisterIds,
opts: PayOpts,
) -> AnyhowResult<Vec<IngressWithRequestId>> {
let (controller, _) = crate::commands::public::get_ids(auth)?;
let controller = crate::lib::get_principal(auth)?;
let mut messages = vec![];
if !opts.notify_only {
let subaccount = Subaccount::from(&PrincipalId(controller));
Expand Down
2 changes: 1 addition & 1 deletion src/commands/sns/stake_neuron.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ pub fn exec(
sns_canister_ids: &SnsCanisterIds,
opts: StakeNeuronOpts,
) -> AnyhowResult<Vec<IngressWithRequestId>> {
let (controller, _) = crate::commands::public::get_ids(auth)?;
let controller = crate::lib::get_principal(auth)?;
let neuron_subaccount = ledger::compute_neuron_staking_subaccount(controller.into(), opts.memo);

let governance_canister_id = sns_canister_ids.governance_canister_id;
Expand Down
14 changes: 12 additions & 2 deletions src/lib/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,10 +366,19 @@ pub fn parse_query_response(
Err(anyhow!("Invalid cbor content"))
}

pub fn get_account_id(principal_id: Principal) -> AnyhowResult<AccountIdentifier> {
/// Returns the account id and the principal id if the private key was provided.
pub fn get_principal(auth: &AuthInfo) -> AnyhowResult<Principal> {
let principal_id = get_identity(auth)?.sender().map_err(|e| anyhow!(e))?;
Ok(principal_id)
}

pub fn get_account_id(
principal_id: Principal,
subaccount: Option<Subaccount>,
) -> AnyhowResult<AccountIdentifier> {
let base_types_principal =
PrincipalId::try_from(principal_id.as_slice()).map_err(|err| anyhow!(err))?;
Ok(AccountIdentifier::new(base_types_principal, None))
Ok(AccountIdentifier::new(base_types_principal, subaccount))
}

/// Converts menmonic to PEM format
Expand Down Expand Up @@ -422,6 +431,7 @@ fn derivation_path() -> DerivationPath {
DERIVATION_PATH.parse().unwrap()
}

#[derive(Copy, Clone)]
pub struct ParsedSubaccount(pub Subaccount);

impl FromStr for ParsedSubaccount {
Expand Down
2 changes: 2 additions & 0 deletions tests/output/default/public_ids/basic.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Principal id: fdsgv-62ihb-nbiqv-xgic5-iefsv-3cscz-tmbzv-63qd5-vh43v-dqfrt-pae
Legacy account id: 345f723e9e619934daac6ae0f4be13a7b0ba57d6a608e511a00fd0ded5866752
3 changes: 3 additions & 0 deletions tests/output/default/public_ids/with_subaccount.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Principal id: fdsgv-62ihb-nbiqv-xgic5-iefsv-3cscz-tmbzv-63qd5-vh43v-dqfrt-pae
Legacy account id: 0ae94165785f2ffb9c56ebc84f3d13299f28db78c80b1db43c0d114eed6105af
ICRC-1 account id: fdsgv-62ihb-nbiqv-xgic5-iefsv-3cscz-tmbzv-63qd5-vh43v-dqfrt-pae-al4mwai.10203
2 changes: 2 additions & 0 deletions tests/output/ledger/public_ids/basic.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Principal id: 5upke-tazvi-6ufqc-i3v6r-j4gpu-dpwti-obhal-yb5xj-ue32x-ktkql-rqe
Legacy account id: 4f3d4b40cdb852732601fccf8bd24dffe44957a647cb867913e982d98cf85676
3 changes: 3 additions & 0 deletions tests/output/ledger/public_ids/with_subaccount.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Principal id: 5upke-tazvi-6ufqc-i3v6r-j4gpu-dpwti-obhal-yb5xj-ue32x-ktkql-rqe
Legacy account id: 42c27da7e76dcaeb033329b79b62abf506b34b69270d15a3efa9ca50230ca3ae
ICRC-1 account id: 5upke-tazvi-6ufqc-i3v6r-j4gpu-dpwti-obhal-yb5xj-ue32x-ktkql-rqe-iyqwy2i.10203
12 changes: 0 additions & 12 deletions tests/output/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ mod root;
mod sns;

const PRINCIPAL: PrincipalPlaceholder = PrincipalPlaceholder;
const ACCOUNT_ID: AccountIdPlaceholder = AccountIdPlaceholder;
const ALICE: &str = "pnf55-r7gzn-s3oqn-ah2v7-r6b63-a2ma2-wyzhb-dzbwb-sghid-lzcxh-4ae";
#[allow(unused)]
const BOB: &str = "jndu2-vwnnt-bpu6t-2jrke-fg3kj-vbrgf-ajecf-gv6ju-onyol-wc3e5-kqe";
Expand Down Expand Up @@ -144,7 +143,6 @@ macro_rules! ledger_compatible {
struct AuthSettings {
args: Vec<String>,
principal: String,
account_id: String,
outputs_dir: String,
}

Expand All @@ -153,7 +151,6 @@ impl Default for AuthSettings {
Self {
args: vec!["--pem-file".into(), default_pem().into()],
principal: "fdsgv-62ihb-nbiqv-xgic5-iefsv-3cscz-tmbzv-63qd5-vh43v-dqfrt-pae".into(),
account_id: "345f723e9e619934daac6ae0f4be13a7b0ba57d6a608e511a00fd0ded5866752".into(),
outputs_dir: "default".into(),
}
}
Expand All @@ -165,7 +162,6 @@ impl AuthSettings {
Self {
args: vec!["--ledger".into()],
principal: "5upke-tazvi-6ufqc-i3v6r-j4gpu-dpwti-obhal-yb5xj-ue32x-ktkql-rqe".into(),
account_id: "4f3d4b40cdb852732601fccf8bd24dffe44957a647cb867913e982d98cf85676".into(),
outputs_dir: "ledger".into(),
}
}
Expand All @@ -179,14 +175,6 @@ impl Display for PrincipalPlaceholder {
}
}

struct AccountIdPlaceholder;

impl Display for AccountIdPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
AUTH_SETTINGS.with(|auth| auth.borrow().account_id.fmt(f))
}
}

thread_local! { static AUTH_SETTINGS: RefCell<AuthSettings> = RefCell::default(); }

#[cfg(feature = "ledger")]
Expand Down
Loading