Skip to content

Commit

Permalink
Merge pull request #190 from nomic-io/default-disbursal-path-removal
Browse files Browse the repository at this point in the history
Default disbursal path removal
  • Loading branch information
mappum authored Aug 31, 2023
2 parents 0b12e6e + fd15983 commit 5184121
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 74 deletions.
30 changes: 25 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
[package]
name = "nomic"
version = "6.0.2"
authors = [ "The Nomic Team <[email protected]>" ]
authors = ["The Nomic Team <[email protected]>"]
edition = "2021"
default-run = "nomic"

[dependencies]
bitcoin = { version = "0.29.2", features = ["serde", "rand"] }
bitcoind = { version = "0.27.0", features = ["22_0"], optional = true }
orga = { git = "https://github.com/nomic-io/orga.git", rev = "860052c382b01fa5d5c4b4d954da4aa129adacb9", features = ["merk-verify", "compat"] }
orga = { git = "https://github.com/nomic-io/orga.git", rev = "860052c382b01fa5d5c4b4d954da4aa129adacb9", features = [
"merk-verify",
"compat",
] }
thiserror = "1.0.30"
ed = { git = "https://github.com/nomic-io/ed", rev = "9c0e206ffdb59dacb90f083e004e8080713e6ad8" }
clap = { version = "3.2.16", features = ["derive"], optional = true }
Expand All @@ -21,7 +24,9 @@ csv = { version = "1.1.6", optional = true }
bech32 = { version = "0.9.1" }
futures = "0.3.21"
toml_edit = "0.13.4"
tendermint-rpc = { version = "=0.30.0", features = ["http-client"], optional = true}
tendermint-rpc = { version = "=0.30.0", features = [
"http-client",
], optional = true }
bitcoincore-rpc-async = { package = "bitcoincore-rpc-async2", version = "4.0.1", optional = true }
bitcoin-script = "0.1.1"
warp = { version = "0.3.2", optional = true }
Expand All @@ -38,7 +43,7 @@ toml = { version = "0.7.2", features = ["parse"] }
split-iter = "0.1.0"
chrono = "0.4.19"
tempfile = "3"
home = {version = "0.5.5", optional = true }
home = { version = "0.5.5", optional = true }
semver = "1.0.18"

[dev-dependencies]
Expand All @@ -59,9 +64,24 @@ semver = "1.0.18"

[features]
default = ["full", "feat-ibc"]
full = ["bitcoind", "bitcoincore-rpc-async", "clap", "tokio", "orga/merk-full", "orga/abci", "orga/state-sync", "csv", "warp", "rand", "reqwest", "tendermint-rpc", "home"]
full = [
"bitcoind",
"bitcoincore-rpc-async",
"clap",
"tokio",
"orga/merk-full",
"orga/abci",
"orga/state-sync",
"csv",
"warp",
"rand",
"reqwest",
"tendermint-rpc",
"home",
]
feat-ibc = ["orga/feat-ibc"]
testnet = []
devnet = []
emergency-disbursal = []
legacy-bin = []

Expand Down
35 changes: 13 additions & 22 deletions src/bitcoin/checkpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,10 @@ impl<'a> BuildingCheckpointMut<'a> {

let mut disbursal_batch = self.batches.get_mut(BatchType::Disbursal as u64)?.unwrap();
disbursal_batch.retain_unordered(|mut tx| {
let mut input = tx.input.get_mut(0)?.unwrap();
let mut input = match tx.input.get_mut(0)? {
Some(input) => input,
None => return Ok(false),
};
input.amount -= intermediate_tx_fee / intermediate_tx_len;
for (i, output) in intermediate_tx_outputs.iter() {
if output == &(input.amount) {
Expand Down Expand Up @@ -730,35 +733,23 @@ impl<'a> BuildingCheckpointMut<'a> {
let lock_time =
time.seconds as u32 + bitcoin_config.emergency_disbursal_lock_time_interval;

let outputs: Vec<_> = nbtc_accounts
.iter()?
.map(|entry| {
let (address, coins) = entry?;
use bitcoin::hashes::hex::ToHex;
use std::str::FromStr;
let hash =
bitcoin::hashes::hash160::Hash::from_str(address.bytes().to_hex().as_str())
.map_err(|err| Error::BitcoinPubkeyHash(err.to_string()))?;
let pubkey_hash = bitcoin::PubkeyHash::from(hash);
let dest_script = match recovery_scripts.get(*address)? {
Some(script) => script.clone(),
None => Adapter::new(bitcoin::Script::new_p2pkh(&pubkey_hash)),
};

let mut outputs = Vec::new();
for entry in nbtc_accounts.iter()? {
let (address, coins) = entry?;
if let Some(dest_script) = recovery_scripts.get(*address)? {
let tx_out = bitcoin::TxOut {
value: u64::from(coins.amount) / 1_000_000,
script_pubkey: dest_script.into_inner(),
script_pubkey: dest_script.clone().into_inner(),
};

Ok::<_, crate::error::Error>(tx_out)
})
.chain(external_outputs)
.collect();
outputs.push(Ok(tx_out));
}
}

let mut final_txs = vec![BitcoinTx::with_lock_time(lock_time)];

let num_outputs = outputs.len();
for (i, output) in outputs.into_iter().enumerate() {
for (i, output) in outputs.into_iter().chain(external_outputs).enumerate() {
let output = output?;

if output.value < bitcoin_config.emergency_disbursal_min_tx_amt {
Expand Down
8 changes: 7 additions & 1 deletion src/bitcoin/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,13 @@ impl<W: Wallet> Signer<W> {
} else {
info!("Generating signatory key at {}", path.display());
let seed: [u8; 32] = rand::thread_rng().gen();
let xpriv = ExtendedPrivKey::new_master(bitcoin::Network::Bitcoin, seed.as_slice())?;

let network = if super::NETWORK == bitcoin::Network::Regtest {
bitcoin::Network::Testnet
} else {
super::NETWORK
};
let xpriv = ExtendedPrivKey::new_master(network, seed.as_slice())?;

fs::write(path, xpriv.to_string().as_bytes())?;

Expand Down
40 changes: 33 additions & 7 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#![cfg(not(target_arch = "wasm32"))]

#[cfg(feature = "full")]
use crate::app::App;
use crate::app::InnerApp;
Expand Down Expand Up @@ -28,13 +27,14 @@ use chrono::{TimeZone, Utc};
use ed::Encode;
#[cfg(feature = "full")]
use log::info;
use orga::client::Wallet;
use orga::coins::staking::{Commission, Declaration};
use orga::coins::{Address, Coin, Decimal};
use orga::context::Context;
#[cfg(feature = "full")]
use orga::merk::MerkStore;
use orga::plugins::sdk_compat::sdk;
use orga::plugins::{ABCIPlugin, ChainId, Time, MIN_FEE};
use orga::plugins::{ABCIPlugin, ChainId, SignerCall, Time, MIN_FEE};
use orga::state::State;
#[cfg(feature = "full")]
use orga::store::BackingStore;
Expand All @@ -43,13 +43,13 @@ use orga::store::Write;
#[cfg(feature = "full")]
use orga::store::{Shared, Store};
use orga::tendermint::client::HttpClient;
use orga::Result as OrgaResult;
use orga::{client::wallet::DerivedKey, macros::build_call};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[cfg(feature = "full")]
use std::path::Path;
use std::process::{Child, Command, Stdio};
#[cfg(feature = "full")]
use std::str::FromStr;
use std::time::Duration;
use std::time::{SystemTime, UNIX_EPOCH};
Expand Down Expand Up @@ -339,14 +339,36 @@ pub fn populate_bitcoin_block(client: &BitcoinD) -> BitcoinBlockData {
}
}

pub struct KeyData {
#[derive(Clone)]
pub struct NomicTestWallet {
pub privkey: SecretKey,
pub address: Address,
pub script: Script,
pub wallet: DerivedKey,
}

impl Wallet for NomicTestWallet {
fn address(&self) -> OrgaResult<Option<Address>> {
Ok(Some(self.wallet.address()))
}

fn sign(&self, call_bytes: &[u8]) -> OrgaResult<SignerCall> {
self.wallet.sign(call_bytes)
}
}

impl NomicTestWallet {
pub fn bitcoin_address(&self) -> bitcoin::Address {
bitcoin::Address::from_script(&self.script, bitcoin::Network::Regtest).unwrap()
}
}

#[cfg(feature = "full")]
pub fn setup_test_app(home: &Path, block_data: &BitcoinBlockData) -> Vec<KeyData> {
pub fn setup_test_app(
home: &Path,
block_data: &BitcoinBlockData,
num_accounts: u16,
) -> Vec<NomicTestWallet> {
let mut app = ABCIPlugin::<App>::default();
let mut store = Store::new(BackingStore::Merk(Shared::new(MerkStore::new(
home.join("merk"),
Expand Down Expand Up @@ -386,15 +408,19 @@ pub fn setup_test_app(home: &Path, block_data: &BitcoinBlockData) -> Vec<KeyData
.deposit(address, Coin::mint(1000000000))
.unwrap();

let keys: Vec<KeyData> = (0..10)
let keys: Vec<NomicTestWallet> = (0..num_accounts)
.map(|_| {
let privkey = SecretKey::new(&mut rand::thread_rng());
let address = address_from_privkey(&privkey);
let script = address_to_script(address).unwrap();
KeyData {
let secret_key =
orga::secp256k1::SecretKey::from_slice(&privkey.secret_bytes()).unwrap();
let wallet = DerivedKey::from_secret_key(secret_key);
NomicTestWallet {
privkey,
address,
script,
wallet,
}
})
.collect();
Expand Down
Loading

0 comments on commit 5184121

Please sign in to comment.