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

Commit

Permalink
Merge pull request stacks-network#4469 from stacks-network/chore/remo…
Browse files Browse the repository at this point in the history
…ve-self-signer

Remove self signer
  • Loading branch information
obycode authored Mar 5, 2024
2 parents 2c49a5b + f3fc5e4 commit 0b34e09
Show file tree
Hide file tree
Showing 11 changed files with 377 additions and 1,944 deletions.
34 changes: 32 additions & 2 deletions libsigner/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use libstackerdb::{
stackerdb_get_chunk_path, stackerdb_get_metadata_path, stackerdb_post_chunk_path, SlotMetadata,
StackerDBChunkAckData, StackerDBChunkData,
};
use stacks_common::codec::StacksMessageCodec;

use crate::error::RPCError;
use crate::http::run_http_request;
Expand Down Expand Up @@ -51,15 +52,44 @@ pub trait SignerSession {
/// Returns Ok(None) if the chunk with the given version does not exist
/// Returns Err(..) on transport error
fn get_chunk(&mut self, slot_id: u32, version: u32) -> Result<Option<Vec<u8>>, RPCError> {
Ok(self.get_chunks(&[(slot_id, version)])?[0].clone())
let mut chunks = self.get_chunks(&[(slot_id, version)])?;
// check if chunks is empty because [0] and remove(0) panic on out-of-bounds
if chunks.is_empty() {
return Ok(None);
}
// swap_remove breaks the ordering of latest_chunks, but we don't care because we
// only want the first element anyways.
Ok(chunks.swap_remove(0))
}

/// Get a single latest chunk.
/// Returns Ok(Some(..)) if the slot exists
/// Returns Ok(None) if not
/// Returns Err(..) on transport error
fn get_latest_chunk(&mut self, slot_id: u32) -> Result<Option<Vec<u8>>, RPCError> {
Ok(self.get_latest_chunks(&[(slot_id)])?[0].clone())
let mut latest_chunks = self.get_latest_chunks(&[slot_id])?;
// check if latest_chunks is empty because [0] and remove(0) panic on out-of-bounds
if latest_chunks.is_empty() {
return Ok(None);
}
// swap_remove breaks the ordering of latest_chunks, but we don't care because we
// only want the first element anyways.
Ok(latest_chunks.swap_remove(0))
}

/// Get a single latest chunk from the StackerDB and deserialize into `T` using the
/// StacksMessageCodec.
fn get_latest<T: StacksMessageCodec>(&mut self, slot_id: u32) -> Result<Option<T>, RPCError> {
let Some(latest_bytes) = self.get_latest_chunk(slot_id)? else {
return Ok(None);
};
Some(
T::consensus_deserialize(&mut latest_bytes.as_slice()).map_err(|e| {
let msg = format!("StacksMessageCodec::consensus_deserialize failure: {e}");
RPCError::Deserialize(msg)
}),
)
.transpose()
}
}

Expand Down
3 changes: 1 addition & 2 deletions stackslib/src/chainstate/stacks/boot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const POX_4_BODY: &'static str = std::include_str!("pox-4.clar");
pub const SIGNERS_BODY: &'static str = std::include_str!("signers.clar");
pub const SIGNERS_DB_0_BODY: &'static str = std::include_str!("signers-0-xxx.clar");
pub const SIGNERS_DB_1_BODY: &'static str = std::include_str!("signers-1-xxx.clar");
const SIGNERS_VOTING_BODY: &'static str = std::include_str!("signers-voting.clar");
pub const SIGNERS_VOTING_BODY: &'static str = std::include_str!("signers-voting.clar");

pub const COSTS_1_NAME: &'static str = "costs";
pub const COSTS_2_NAME: &'static str = "costs-2";
Expand Down Expand Up @@ -120,7 +120,6 @@ lazy_static! {
pub static ref POX_3_TESTNET_CODE: String =
format!("{}\n{}", BOOT_CODE_POX_TESTNET_CONSTS, POX_3_BODY);
pub static ref POX_4_CODE: String = format!("{}", POX_4_BODY);
pub static ref SIGNER_VOTING_CODE: String = format!("{}", SIGNERS_VOTING_BODY);
pub static ref BOOT_CODE_COST_VOTING_TESTNET: String = make_testnet_cost_voting();
pub static ref STACKS_BOOT_CODE_MAINNET: [(&'static str, &'static str); 6] = [
("pox", &BOOT_CODE_POX_MAINNET),
Expand Down
51 changes: 2 additions & 49 deletions stackslib/src/clarity_vm/clarity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ use crate::chainstate::stacks::boot::{
BOOT_TEST_POX_4_AGG_KEY_CONTRACT, BOOT_TEST_POX_4_AGG_KEY_FNAME, COSTS_2_NAME, COSTS_3_NAME,
MINERS_NAME, POX_2_MAINNET_CODE, POX_2_NAME, POX_2_TESTNET_CODE, POX_3_MAINNET_CODE,
POX_3_NAME, POX_3_TESTNET_CODE, POX_4_CODE, POX_4_NAME, SIGNERS_BODY, SIGNERS_DB_0_BODY,
SIGNERS_DB_1_BODY, SIGNERS_NAME, SIGNERS_VOTING_NAME, SIGNER_VOTING_CODE,
SIGNERS_DB_1_BODY, SIGNERS_NAME, SIGNERS_VOTING_BODY, SIGNERS_VOTING_NAME,
};
use crate::chainstate::stacks::db::{StacksAccount, StacksChainState};
use crate::chainstate::stacks::events::{StacksTransactionEvent, StacksTransactionReceipt};
Expand Down Expand Up @@ -1457,59 +1457,12 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> {
}
}

let initialized_agg_key = if !mainnet {
let agg_key_value_opt = self
.with_readonly_clarity_env(
false,
self.chain_id,
ClarityVersion::Clarity2,
StacksAddress::burn_address(false).into(),
None,
LimitedCostTracker::Free,
|vm_env| {
vm_env.execute_contract_allow_private(
&boot_code_id(BOOT_TEST_POX_4_AGG_KEY_CONTRACT, false),
BOOT_TEST_POX_4_AGG_KEY_FNAME,
&[],
true,
)
},
)
.map(|agg_key_value| {
agg_key_value
.expect_buff(33)
.expect("FATAL: test aggregate pub key must be a buffer")
})
.ok();
agg_key_value_opt
} else {
None
};

let mut signers_voting_code = SIGNER_VOTING_CODE.clone();
if !mainnet {
if let Some(ref agg_pub_key) = initialized_agg_key {
let hex_agg_pub_key = to_hex(agg_pub_key);
for set_in_reward_cycle in 0..pox_4_first_cycle {
info!(
"Setting initial aggregate-public-key in PoX-4";
"agg_pub_key" => &hex_agg_pub_key,
"reward_cycle" => set_in_reward_cycle,
"pox_4_first_cycle" => pox_4_first_cycle,
);
let set_str = format!("(map-set aggregate-public-keys u{set_in_reward_cycle} 0x{hex_agg_pub_key})");
signers_voting_code.push_str("\n");
signers_voting_code.push_str(&set_str);
}
}
}

let signers_voting_contract_id = boot_code_id(SIGNERS_VOTING_NAME, mainnet);
let payload = TransactionPayload::SmartContract(
TransactionSmartContract {
name: ContractName::try_from(SIGNERS_VOTING_NAME)
.expect("FATAL: invalid boot-code contract name"),
code_body: StacksString::from_str(&signers_voting_code)
code_body: StacksString::from_str(SIGNERS_VOTING_BODY)
.expect("FATAL: invalid boot code body"),
},
Some(ClarityVersion::Clarity2),
Expand Down
139 changes: 3 additions & 136 deletions testnet/stacks-node/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use rand::RngCore;
use stacks::burnchains::bitcoin::BitcoinNetworkType;
use stacks::burnchains::{Burnchain, MagicBytes, BLOCKSTACK_MAGIC_MAINNET};
use stacks::chainstate::nakamoto::signer_set::NakamotoSigners;
use stacks::chainstate::nakamoto::test_signers::TestSigners;
use stacks::chainstate::stacks::boot::MINERS_NAME;
use stacks::chainstate::stacks::index::marf::MARFOpenOpts;
use stacks::chainstate::stacks::index::storage::TrieHashCalculationMode;
Expand All @@ -33,7 +32,6 @@ use stacks::net::connection::ConnectionOptions;
use stacks::net::{Neighbor, NeighborKey};
use stacks::util_lib::boot::boot_code_id;
use stacks::util_lib::db::Error as DBError;
use stacks_common::address::{AddressHashMode, C32_ADDRESS_VERSION_TESTNET_SINGLESIG};
use stacks_common::consts::SIGNER_SLOTS_PER_USER;
use stacks_common::types::chainstate::StacksAddress;
use stacks_common::types::net::PeerAddress;
Expand Down Expand Up @@ -294,102 +292,6 @@ impl ConfigFile {
}
}

pub fn mockamoto() -> ConfigFile {
let epochs = vec![
StacksEpochConfigFile {
epoch_name: "1.0".into(),
start_height: 0,
},
StacksEpochConfigFile {
epoch_name: "2.0".into(),
start_height: 0,
},
StacksEpochConfigFile {
epoch_name: "2.05".into(),
start_height: 1,
},
StacksEpochConfigFile {
epoch_name: "2.1".into(),
start_height: 2,
},
StacksEpochConfigFile {
epoch_name: "2.2".into(),
start_height: 3,
},
StacksEpochConfigFile {
epoch_name: "2.3".into(),
start_height: 4,
},
StacksEpochConfigFile {
epoch_name: "2.4".into(),
start_height: 5,
},
StacksEpochConfigFile {
epoch_name: "2.5".into(),
start_height: 6,
},
StacksEpochConfigFile {
epoch_name: "3.0".into(),
start_height: 7,
},
];

let burnchain = BurnchainConfigFile {
mode: Some("mockamoto".into()),
rpc_port: Some(8332),
peer_port: Some(8333),
peer_host: Some("localhost".into()),
username: Some("blockstack".into()),
password: Some("blockstacksystem".into()),
magic_bytes: Some("M3".into()),
epochs: Some(epochs),
pox_prepare_length: Some(3),
pox_reward_length: Some(36),
..BurnchainConfigFile::default()
};

let node = NodeConfigFile {
bootstrap_node: None,
miner: Some(true),
stacker: Some(true),
..NodeConfigFile::default()
};

let mining_key = Secp256k1PrivateKey::new();
let miner = MinerConfigFile {
mining_key: Some(mining_key.to_hex()),
..MinerConfigFile::default()
};

let mock_private_key = Secp256k1PrivateKey::from_seed(&[0]);
let mock_public_key = Secp256k1PublicKey::from_private(&mock_private_key);
let mock_address = StacksAddress::from_public_keys(
C32_ADDRESS_VERSION_TESTNET_SINGLESIG,
&AddressHashMode::SerializeP2PKH,
1,
&vec![mock_public_key],
)
.unwrap();

info!(
"Mockamoto starting. Initial balance set to mock_private_key = {}",
mock_private_key.to_hex()
);

let ustx_balance = vec![InitialBalanceFile {
address: mock_address.to_string(),
amount: 1_000_000_000_000,
}];

ConfigFile {
burnchain: Some(burnchain),
node: Some(node),
miner: Some(miner),
ustx_balance: Some(ustx_balance),
..ConfigFile::default()
}
}

pub fn helium() -> ConfigFile {
// ## Settings for local testnet, relying on a local bitcoind server
// ## running with the following bitcoin.conf:
Expand Down Expand Up @@ -524,19 +426,6 @@ lazy_static! {
}

impl Config {
#[cfg(any(test, feature = "testing"))]
pub fn self_signing(&self) -> Option<TestSigners> {
if !(self.burnchain.mode == "nakamoto-neon" || self.burnchain.mode == "mockamoto") {
return None;
}
self.miner.self_signing_key.clone()
}

#[cfg(not(any(test, feature = "testing")))]
pub fn self_signing(&self) -> Option<TestSigners> {
return None;
}

/// get the up-to-date burnchain options from the config.
/// If the config file can't be loaded, then return the existing config
pub fn get_burnchain_config(&self) -> BurnchainConfig {
Expand Down Expand Up @@ -663,7 +552,7 @@ impl Config {
}

// check if the Epoch 3.0 burnchain settings as configured are going to be valid.
if self.burnchain.mode == "nakamoto-neon" || self.burnchain.mode == "mockamoto" {
if self.burnchain.mode == "nakamoto-neon" {
self.check_nakamoto_config(&burnchain);
}
}
Expand Down Expand Up @@ -895,15 +784,7 @@ impl Config {
}

pub fn from_config_file(config_file: ConfigFile) -> Result<Config, String> {
if config_file.burnchain.as_ref().map(|b| b.mode.clone()) == Some(Some("mockamoto".into()))
{
// in the case of mockamoto, use `ConfigFile::mockamoto()` as the default for
// processing a user-supplied config
let default = Self::from_config_default(ConfigFile::mockamoto(), Config::default())?;
Self::from_config_default(config_file, default)
} else {
Self::from_config_default(config_file, Config::default())
}
Self::from_config_default(config_file, Config::default())
}

fn from_config_default(config_file: ConfigFile, default: Config) -> Result<Config, String> {
Expand All @@ -929,7 +810,6 @@ impl Config {
"krypton",
"xenon",
"mainnet",
"mockamoto",
"nakamoto-neon",
];

Expand Down Expand Up @@ -1368,7 +1248,7 @@ impl BurnchainConfig {
match self.mode.as_str() {
"mainnet" => ("mainnet".to_string(), BitcoinNetworkType::Mainnet),
"xenon" => ("testnet".to_string(), BitcoinNetworkType::Testnet),
"helium" | "neon" | "argon" | "krypton" | "mocknet" | "mockamoto" | "nakamoto-neon" => {
"helium" | "neon" | "argon" | "krypton" | "mocknet" | "nakamoto-neon" => {
("regtest".to_string(), BitcoinNetworkType::Regtest)
}
other => panic!("Invalid stacks-node mode: {other}"),
Expand Down Expand Up @@ -1599,9 +1479,6 @@ pub struct NodeConfig {
pub chain_liveness_poll_time_secs: u64,
/// stacker DBs we replicate
pub stacker_dbs: Vec<QualifiedContractIdentifier>,
/// if running in mockamoto mode, how long to wait between each
/// simulated bitcoin block
pub mockamoto_time_ms: u64,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -1882,7 +1759,6 @@ impl Default for NodeConfig {
fault_injection_hide_blocks: false,
chain_liveness_poll_time_secs: 300,
stacker_dbs: vec![],
mockamoto_time_ms: 3_000,
}
}
}
Expand Down Expand Up @@ -2052,7 +1928,6 @@ pub struct MinerConfig {
pub candidate_retry_cache_size: u64,
pub unprocessed_block_deadline_secs: u64,
pub mining_key: Option<Secp256k1PrivateKey>,
pub self_signing_key: Option<TestSigners>,
/// Amount of time while mining in nakamoto to wait in between mining interim blocks
pub wait_on_interim_blocks: Duration,
/// minimum number of transactions that must be in a block if we're going to replace a pending
Expand Down Expand Up @@ -2100,7 +1975,6 @@ impl Default for MinerConfig {
candidate_retry_cache_size: 1024 * 1024,
unprocessed_block_deadline_secs: 30,
mining_key: None,
self_signing_key: None,
wait_on_interim_blocks: Duration::from_millis(2_500),
min_tx_count: 0,
only_increase_tx_count: false,
Expand Down Expand Up @@ -2322,9 +2196,6 @@ pub struct NodeConfigFile {
pub chain_liveness_poll_time_secs: Option<u64>,
/// Stacker DBs we replicate
pub stacker_dbs: Option<Vec<String>>,
/// if running in mockamoto mode, how long to wait between each
/// simulated bitcoin block
pub mockamoto_time_ms: Option<u64>,
}

impl NodeConfigFile {
Expand Down Expand Up @@ -2400,9 +2271,6 @@ impl NodeConfigFile {
.iter()
.filter_map(|contract_id| QualifiedContractIdentifier::parse(contract_id).ok())
.collect(),
mockamoto_time_ms: self
.mockamoto_time_ms
.unwrap_or(default_node_config.mockamoto_time_ms),
};
Ok(node_config)
}
Expand Down Expand Up @@ -2486,7 +2354,6 @@ impl MinerConfigFile {
.as_ref()
.map(|x| Secp256k1PrivateKey::from_hex(x))
.transpose()?,
self_signing_key: Some(TestSigners::default()),
wait_on_interim_blocks: self
.wait_on_interim_blocks_ms
.map(Duration::from_millis)
Expand Down
Loading

0 comments on commit 0b34e09

Please sign in to comment.