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 7 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bin/datatool/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ bytemuck = { version = "1.21.0", optional = true }
rand_core.workspace = true
reth-chainspec.workspace = true
serde_json.workspace = true
shrex.workspace = true
zeroize.workspace = true

[features]
Expand Down
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 @@ -21,20 +21,19 @@ use util::{exec_subc, resolve_network};

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())?;

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,
};

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

exec_subc(args.subc, &mut ctx)?;
Ok(())
if let Err(e) = inner() {
eprintln!("ERROR\n{e:?}");
}
}
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 std::{

use alloy_genesis::Genesis;
use alloy_primitives::B256;
use bitcoin::{
base58,
bip32::{Xpriv, Xpub},
Network,
};
use bitcoin::{base58, bip32::Xpriv, secp256k1::SECP256K1, 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 shrex::Hex;
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 @@ -166,7 +161,7 @@ fn exec_genxpriv(cmd: SubcXpriv, ctx: &mut CmdContext) -> anyhow::Result<()> {

/// 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 @@ -175,8 +170,7 @@ fn exec_genseqpubkey(cmd: SubcSeqPubkey, _ctx: &mut CmdContext) -> anyhow::Resul

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());

println!("{s}");

Expand Down Expand Up @@ -215,11 +209,19 @@ fn exec_genopxpub(cmd: SubcOpXpub, _ctx: &mut CmdContext) -> anyhow::Result<()>
};

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!("{:?}", Hex(p2p_pk.serialize()));
}

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

Ok(())
}
Expand Down Expand Up @@ -260,12 +262,12 @@ fn exec_genparams(cmd: SubcParams, ctx: &mut CmdContext) -> anyhow::Result<()> {
continue;
}

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

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

// Parse the deposit size str.
Expand Down Expand Up @@ -304,7 +306,10 @@ fn exec_genparams(cmd: SubcParams, ctx: &mut CmdContext) -> anyhow::Result<()> {
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}"),
};
let params_buf = serde_json::to_string_pretty(&params)?;

if let Some(out_path) = &cmd.output {
Expand Down Expand Up @@ -449,8 +454,8 @@ pub(crate) struct ParamsConfig {
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 @@ -463,26 +468,35 @@ pub(crate) struct ParamsConfig {

/// 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> {
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<_>, _>>()?;

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(),
)
});

// TODO add in bitcoin network
RollupParams {
Ok(RollupParams {
rollup_name: config.name,
block_time: config.block_time_sec * 1000,
da_tag: config.da_tag,
Expand All @@ -491,7 +505,7 @@ fn construct_params(config: ParamsConfig) -> RollupParams {
// 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()),
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 @@ -509,17 +523,17 @@ fn construct_params(config: ParamsConfig) -> RollupParams {
// TODO make configurable
max_deposits_in_block: 16,
network: config.bitcoin_network,
}
})
}

/// 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> {
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 {
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