Skip to content

fix(datatool) hardened derivation paths #808

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions bin/datatool/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ pub(crate) struct SubcOpXpub {
short = 'E'
)]
pub(crate) key_from_env: bool,

#[argh(switch, description = "print the p2p key", short = 'p')]
pub(crate) p2p: bool,

#[argh(switch, description = "print the wallet key", short = 'w')]
pub(crate) wallet: bool,
}

/// Generate a network's param file from inputs.
Expand Down Expand Up @@ -148,14 +154,14 @@ pub(crate) struct SubcParams {

#[argh(
option,
description = "add a bridge operator key (must be at least one, appended after file keys)",
description = "add a bridge operator key (master xpriv, must be at least one, appended after file keys)",
short = 'b'
)]
pub(crate) opkey: Vec<String>,

#[argh(
option,
description = "read bridge operator keys by line from file",
description = "read bridge operator keys (master xpriv) by line from file",
short = 'B'
)]
pub(crate) opkeys: Option<PathBuf>,
Expand Down
25 changes: 12 additions & 13 deletions bin/datatool/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,19 @@

fn main() {
let args: args::Args = argh::from_env();
if let Err(e) = main_inner(args) {
eprintln!("ERROR\n{e:?}");
}
}
let inner = || -> anyhow::Result<()> {
let network = resolve_network(args.bitcoin_network.as_deref())?;

Check warning on line 19 in bin/datatool/src/main.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/main.rs#L18-L19

Added lines #L18 - L19 were not covered by tests

fn main_inner(args: args::Args) -> anyhow::Result<()> {
let network = resolve_network(args.bitcoin_network.as_deref())?;
let mut ctx = CmdContext {
datadir: args.datadir.unwrap_or_else(|| PathBuf::from(".")),
bitcoin_network: network,
rng: OsRng,
};

Check warning on line 25 in bin/datatool/src/main.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/main.rs#L21-L25

Added lines #L21 - L25 were not covered by tests

let mut ctx = CmdContext {
datadir: args.datadir.unwrap_or_else(|| PathBuf::from(".")),
bitcoin_network: network,
rng: OsRng,
exec_subc(args.subc, &mut ctx)?;
Ok(())

Check warning on line 28 in bin/datatool/src/main.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/main.rs#L27-L28

Added lines #L27 - L28 were not covered by tests
};

exec_subc(args.subc, &mut ctx)?;
Ok(())
if let Err(e) = inner() {
eprintln!("ERROR\n{e:?}");
}

Check warning on line 32 in bin/datatool/src/main.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/main.rs#L30-L32

Added lines #L30 - L32 were not covered by tests
}
88 changes: 51 additions & 37 deletions bin/datatool/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,15 @@

use alloy_genesis::Genesis;
use alloy_primitives::B256;
use bitcoin::{
base58,
bip32::{Xpriv, Xpub},
Network,
};
use bitcoin::{base58, bip32::Xpriv, Network};
use rand_core::CryptoRngCore;
use reth_chainspec::ChainSpec;
use strata_key_derivation::{
operator::{convert_base_xpub_to_message_xpub, convert_base_xpub_to_wallet_xpub, OperatorKeys},
sequencer::SequencerKeys,
};
use secp256k1::SECP256K1;
use strata_key_derivation::{error::KeyError, operator::OperatorKeys, sequencer::SequencerKeys};
use strata_primitives::{
block_credential,
buf::Buf32,
crypto::EvenSecretKey,
keys::ZeroizableXpriv,
operator::OperatorPubkeys,
params::{ProofPublishMode, RollupParams},
Expand Down Expand Up @@ -165,7 +160,7 @@

/// Executes the `genseqpubkey` subcommand.
///
/// Generates the sequencer [`Xpub`] from the provided [`Xpriv`]
/// Generates the sequencer [`Xpub`](bitcoin::bip32::Xpub) from the provided [`Xpriv`]
/// and prints it to stdout.
fn exec_genseqpubkey(cmd: SubcSeqPubkey, _ctx: &mut CmdContext) -> anyhow::Result<()> {
let Some(xpriv) = resolve_xpriv(&cmd.key_file, cmd.key_from_env, SEQKEY_ENVVAR)? else {
Expand All @@ -174,8 +169,7 @@

let seq_keys = SequencerKeys::new(&xpriv)?;
let seq_xpub = seq_keys.derived_xpub();
let raw_buf = seq_xpub.to_x_only_pub().serialize();
let s = base58::encode_check(&raw_buf);
let s = base58::encode_check(&seq_xpub.to_x_only_pub().serialize());

Check warning on line 172 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L172

Added line #L172 was not covered by tests

println!("{s}");

Expand Down Expand Up @@ -214,11 +208,19 @@
};

let op_keys = OperatorKeys::new(&xpriv)?;
let op_base_xpub = op_keys.base_xpub();
let raw_buf = op_base_xpub.encode();
let s = base58::encode_check(&raw_buf);
if cmd.p2p {
let p2p_pk = EvenSecretKey::from(op_keys.message_xpriv().private_key)
.x_only_public_key(SECP256K1)
.0;
println!("{}", base58::encode_check(&p2p_pk.serialize()));
}

Check warning on line 216 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L211-L216

Added lines #L211 - L216 were not covered by tests

println!("{s}");
if cmd.wallet {
let wallet_pk = EvenSecretKey::from(op_keys.wallet_xpriv().private_key)
.x_only_public_key(SECP256K1)
.0;
println!("{}", base58::encode_check(&wallet_pk.serialize()));
}

Check warning on line 223 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L218-L223

Added lines #L218 - L223 were not covered by tests

Ok(())
}
Expand Down Expand Up @@ -259,12 +261,12 @@
continue;
}

opkeys.push(parse_xpub(l)?);
opkeys.push(parse_xpriv(l)?);

Check warning on line 264 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L264

Added line #L264 was not covered by tests
}
}

for k in cmd.opkey {
opkeys.push(parse_xpub(&k)?);
opkeys.push(parse_xpriv(&k)?);

Check warning on line 269 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L269

Added line #L269 was not covered by tests
}

// Parse the deposit size str.
Expand Down Expand Up @@ -303,7 +305,10 @@
evm_genesis_info,
};

let params = construct_params(config);
let params = match construct_params(config) {
Ok(p) => p,
Err(e) => anyhow::bail!("failed to construct params: {e}"),

Check warning on line 310 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L308-L310

Added lines #L308 - L310 were not covered by tests
};
let params_buf = serde_json::to_string_pretty(&params)?;

if let Some(out_path) = &cmd.output {
Expand Down Expand Up @@ -448,8 +453,8 @@
genesis_trigger: u64,
/// Sequencer's key.
seqkey: Option<Buf32>,
/// Operators' keys.
opkeys: Vec<Xpub>,
/// Operators' master keys.
opkeys: Vec<Xpriv>,
/// Verifier's key.
rollup_vk: RollupVerifyingKey,
/// Amount of sats to deposit.
Expand All @@ -462,26 +467,35 @@

/// Constructs the parameters for a Strata network.
// TODO convert this to also initialize the sync params
fn construct_params(config: ParamsConfig) -> RollupParams {
fn construct_params(config: ParamsConfig) -> Result<RollupParams, KeyError> {

Check warning on line 470 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L470

Added line #L470 was not covered by tests
let cr = config
.seqkey
.map(block_credential::CredRule::SchnorrKey)
.unwrap_or(block_credential::CredRule::Unchecked);

let opkeys = config
.opkeys
.into_iter()
.map(|xpk| {
let message_xpub = convert_base_xpub_to_message_xpub(&xpk);
let wallet_xpub = convert_base_xpub_to_wallet_xpub(&xpk);
let message_key_buf = message_xpub.to_x_only_pub().serialize().into();
let wallet_key_buf = wallet_xpub.to_x_only_pub().serialize().into();
OperatorPubkeys::new(message_key_buf, wallet_key_buf)
})
.collect::<Vec<_>>();
.iter()
.map(OperatorKeys::new)
.collect::<Result<Vec<_>, _>>()?;

Check warning on line 480 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L478-L480

Added lines #L478 - L480 were not covered by tests

let pub_opkeys = opkeys.iter().map(|keys| {
OperatorPubkeys::new(
EvenSecretKey::from(keys.message_xpriv().private_key)
.x_only_public_key(SECP256K1)
.0
.serialize()
.into(),
EvenSecretKey::from(keys.wallet_xpriv().private_key)
.x_only_public_key(SECP256K1)
.0
.serialize()
.into(),
)
});

Check warning on line 495 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L482-L495

Added lines #L482 - L495 were not covered by tests

// TODO add in bitcoin network
RollupParams {
Ok(RollupParams {

Check warning on line 498 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L498

Added line #L498 was not covered by tests
rollup_name: config.name,
block_time: config.block_time_sec * 1000,
da_tag: config.da_tag,
Expand All @@ -490,7 +504,7 @@
// TODO do we want to remove this?
horizon_l1_height: config.horizon_height,
genesis_l1_height: config.genesis_trigger,
operator_config: strata_primitives::params::OperatorConfig::Static(opkeys),
operator_config: strata_primitives::params::OperatorConfig::Static(pub_opkeys.collect()),

Check warning on line 507 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L507

Added line #L507 was not covered by tests
evm_genesis_block_hash: config.evm_genesis_info.blockhash.0.into(),
evm_genesis_block_state_root: config.evm_genesis_info.stateroot.0.into(),
// TODO make configurable
Expand All @@ -508,17 +522,17 @@
// TODO make configurable
max_deposits_in_block: 16,
network: config.bitcoin_network,
}
})

Check warning on line 525 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L525

Added line #L525 was not covered by tests
}

/// Parses an [`Xpub`] from [`&str`], richly generating [`anyhow::Result`]s from
/// Parses an [`Xpriv`] from [`&str`], richly generating [`anyhow::Result`]s from
/// it.
fn parse_xpub(s: &str) -> anyhow::Result<Xpub> {
fn parse_xpriv(s: &str) -> anyhow::Result<Xpriv> {

Check warning on line 530 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L530

Added line #L530 was not covered by tests
let Ok(buf) = base58::decode_check(s) else {
anyhow::bail!("failed to parse key: {s}");
};

let Ok(xpk) = Xpub::decode(&buf) else {
let Ok(xpk) = Xpriv::decode(&buf) else {

Check warning on line 535 in bin/datatool/src/util.rs

View check run for this annotation

Codecov / codecov/patch

bin/datatool/src/util.rs#L535

Added line #L535 was not covered by tests
anyhow::bail!("failed to decode key: {s}");
};

Expand Down
28 changes: 5 additions & 23 deletions crates/key-derivation/src/operator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
use bitcoin::bip32::{ChildNumber, Xpriv, Xpub};
use secp256k1::SECP256K1;
use strata_primitives::constants::{
STRATA_OPERATOR_BASE_DERIVATION_PATH, STRATA_OPERATOR_MESSAGE_IDX, STRATA_OPERATOR_WALLET_IDX,
STRATA_OP_MESSAGE_DERIVATION_PATH, STRATA_OP_WALLET_DERIVATION_PATH,
STRATA_OPERATOR_BASE_DERIVATION_PATH, STRATA_OP_MESSAGE_DERIVATION_PATH,
STRATA_OP_WALLET_DERIVATION_PATH,
};
use zeroize::{Zeroize, ZeroizeOnDrop};

Expand Down Expand Up @@ -49,9 +49,9 @@ pub struct OperatorKeys {
impl OperatorKeys {
/// Creates a new [`OperatorKeys`] from a master [`Xpriv`].
pub fn new(master: &Xpriv) -> Result<Self, KeyError> {
let base_xpriv = master.derive_priv(SECP256K1, &*STRATA_OPERATOR_BASE_DERIVATION_PATH)?;
let message_xpriv = master.derive_priv(SECP256K1, &*STRATA_OP_MESSAGE_DERIVATION_PATH)?;
let wallet_xpriv = master.derive_priv(SECP256K1, &*STRATA_OP_WALLET_DERIVATION_PATH)?;
let base_xpriv = master.derive_priv(SECP256K1, &STRATA_OPERATOR_BASE_DERIVATION_PATH)?;
let message_xpriv = master.derive_priv(SECP256K1, &STRATA_OP_MESSAGE_DERIVATION_PATH)?;
let wallet_xpriv = master.derive_priv(SECP256K1, &STRATA_OP_WALLET_DERIVATION_PATH)?;

Ok(Self {
master: *master,
Expand Down Expand Up @@ -256,24 +256,6 @@ impl Zeroize for OperatorKeys {

impl ZeroizeOnDrop for OperatorKeys {}

/// Converts the base [`Xpub`] to the message [`Xpub`].
pub fn convert_base_xpub_to_message_xpub(base_xpub: &Xpub) -> Xpub {
let message_partial_path = ChildNumber::from_normal_idx(STRATA_OPERATOR_MESSAGE_IDX)
.expect("unfallible as long MESSAGE_IDX is not changed");
base_xpub
.derive_pub(SECP256K1, &message_partial_path)
.expect("unfallible")
}

/// Converts the base [`Xpub`] to the wallet [`Xpub`].
pub fn convert_base_xpub_to_wallet_xpub(base_xpub: &Xpub) -> Xpub {
let wallet_partial_path = ChildNumber::from_normal_idx(STRATA_OPERATOR_WALLET_IDX)
.expect("unfallible as long WALLET_IDX is not changed");
base_xpub
.derive_pub(SECP256K1, &wallet_partial_path)
.expect("unfallible")
}

#[cfg(test)]
mod tests {
use std::{collections::BTreeMap, sync::LazyLock};
Expand Down
2 changes: 1 addition & 1 deletion crates/key-derivation/src/sequencer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub struct SequencerKeys {
impl SequencerKeys {
/// Creates a new [`SequencerKeys`] from a master [`Xpriv`].
pub fn new(master: &Xpriv) -> Result<Self, KeyError> {
let derived = master.derive_priv(SECP256K1, &*STRATA_SEQUENCER_DERIVATION_PATH)?;
let derived = master.derive_priv(SECP256K1, &STRATA_SEQUENCER_DERIVATION_PATH)?;

Ok(Self {
master: *master,
Expand Down
Loading
Loading