Skip to content

Add generate block command #254

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 2 commits into
base: master
Choose a base branch
from
Open
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
26 changes: 25 additions & 1 deletion client/src/client.rs
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ use serde_json;
use crate::bitcoin::hashes::hex::{FromHex, ToHex};
use crate::bitcoin::secp256k1::ecdsa::Signature;
use crate::bitcoin::{
Address, Amount, Block, BlockHeader, OutPoint, PrivateKey, PublicKey, Script, Transaction,
Address, Amount, Block, BlockHeader, OutPoint, PrivateKey, PublicKey, Script, Transaction, Txid,
};
use log::Level::{Debug, Trace, Warn};

@@ -186,6 +186,13 @@ impl RawTx for String {
}
}

/// The different ways to add a transaction to a block in generate block
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum MineableTx {
RawTx(Transaction),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually this doesn't have to be a Transaction but a RawTx trait object.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't really work, have to make it a Box<dyn RawTx> but still run into errors with sizing

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, it would actually have to be a generic enum.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm actually maybe not...

Txid(Txid),
}

/// The different authentication methods for the client.
#[derive(Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum Auth {
@@ -866,6 +873,23 @@ pub trait RpcApi: Sized {
self.call("generate", &[block_num.into(), opt_into_json(maxtries)?])
}

/// Mine a set of ordered transactions to a specified address
/// and return the block hash.
fn generate_block(
&self,
address: &Address,
txs: &[MineableTx],
) -> Result<json::GenerateBlockResult> {
let tx_strs: Vec<_> = txs
.iter()
.map(|t| match t.to_owned() {
MineableTx::RawTx(tx) => tx.raw_hex(),
MineableTx::Txid(txid) => txid.to_hex(),
})
.collect();
self.call("generateblock", &[address.to_string().into(), tx_strs.into()])
}

/// Mark a block as invalid by `block_hash`
fn invalidate_block(&self, block_hash: &bitcoin::BlockHash) -> Result<()> {
self.call("invalidateblock", &[into_json(block_hash)?])
6 changes: 4 additions & 2 deletions client/src/lib.rs
Original file line number Diff line number Diff line change
@@ -42,8 +42,10 @@ fn deserialize_hex<T: Decodable>(hex: &str) -> Result<T> {
let mut reader = HexIterator::new(&hex)?;
let object = Decodable::consensus_decode(&mut reader)?;
if reader.read_u8().is_ok() {
Err(Error::BitcoinSerialization(bitcoin::consensus::encode::Error::ParseFailed("data not consumed entirely when explicitly deserializing")))
Err(Error::BitcoinSerialization(bitcoin::consensus::encode::Error::ParseFailed(
"data not consumed entirely when explicitly deserializing",
)))
} else {
Ok(object)
}
}
}
106 changes: 104 additions & 2 deletions integration_test/src/main.rs
Original file line number Diff line number Diff line change
@@ -25,8 +25,8 @@ use bitcoin::hashes::hex::{FromHex, ToHex};
use bitcoin::hashes::Hash;
use bitcoin::secp256k1;
use bitcoin::{
Address, Amount, PackedLockTime, Network, OutPoint, PrivateKey, Script, EcdsaSighashType, SignedAmount,
Sequence, Transaction, TxIn, TxOut, Txid, Witness,
Address, Amount, EcdsaSighashType, Network, OutPoint, PackedLockTime, PrivateKey, Script,
Sequence, SignedAmount, Transaction, TxIn, TxOut, Txid, Witness,
};
use bitcoincore_rpc::bitcoincore_rpc_json::{
GetBlockTemplateModes, GetBlockTemplateRules, ScanTxOutRequest,
@@ -140,6 +140,8 @@ fn main() {
test_generate(&cl);
test_get_balance_generate_to_address(&cl);
test_get_balances_generate_to_address(&cl);
test_generate_block_raw_tx(&cl);
test_generate_block_txid(&cl);
test_get_best_block_hash(&cl);
test_get_block_count(&cl);
test_get_block_hash(&cl);
@@ -277,6 +279,106 @@ fn test_get_balances_generate_to_address(cl: &Client) {
}
}

fn test_generate_block_raw_tx(cl: &Client) {
let sk = PrivateKey {
network: Network::Regtest,
inner: secp256k1::SecretKey::new(&mut secp256k1::rand::thread_rng()),
compressed: true,
};
let addr = Address::p2wpkh(&sk.public_key(&SECP), Network::Regtest).unwrap();

let options = json::ListUnspentQueryOptions {
minimum_amount: Some(btc(2)),
..Default::default()
};
let unspent = cl.list_unspent(Some(6), None, None, None, Some(options)).unwrap();
let unspent = unspent.into_iter().nth(0).unwrap();

let tx = Transaction {
version: 1,
lock_time: PackedLockTime::ZERO,
input: vec![TxIn {
previous_output: OutPoint {
txid: unspent.txid,
vout: unspent.vout,
},
sequence: Sequence::MAX,
script_sig: Script::new(),
witness: Witness::new(),
}],
output: vec![TxOut {
value: (unspent.amount - *FEE).to_sat(),
script_pubkey: addr.script_pubkey(),
}],
};

let input = json::SignRawTransactionInput {
txid: unspent.txid,
vout: unspent.vout,
script_pub_key: unspent.script_pub_key,
redeem_script: None,
amount: Some(unspent.amount),
};
let res = cl.sign_raw_transaction_with_wallet(&tx, Some(&[input]), None).unwrap();
assert!(res.complete);

let raw_tx = bitcoincore_rpc::MineableTx::RawTx(res.transaction().unwrap());
let result = cl.generate_block(&cl.get_new_address(None, None).unwrap(), &[raw_tx]).unwrap();
let tip = cl.get_best_block_hash().unwrap();
assert_eq!(result.hash, tip);
}

fn test_generate_block_txid(cl: &Client) {
let sk = PrivateKey {
network: Network::Regtest,
inner: secp256k1::SecretKey::new(&mut secp256k1::rand::thread_rng()),
compressed: true,
};
let addr = Address::p2wpkh(&sk.public_key(&SECP), Network::Regtest).unwrap();

let options = json::ListUnspentQueryOptions {
minimum_amount: Some(btc(2)),
..Default::default()
};
let unspent = cl.list_unspent(Some(6), None, None, None, Some(options)).unwrap();
let unspent = unspent.into_iter().nth(0).unwrap();

let tx = Transaction {
version: 1,
lock_time: PackedLockTime::ZERO,
input: vec![TxIn {
previous_output: OutPoint {
txid: unspent.txid,
vout: unspent.vout,
},
sequence: Sequence::MAX,
script_sig: Script::new(),
witness: Witness::new(),
}],
output: vec![TxOut {
value: (unspent.amount - *FEE).to_sat(),
script_pubkey: addr.script_pubkey(),
}],
};

let input = json::SignRawTransactionInput {
txid: unspent.txid,
vout: unspent.vout,
script_pub_key: unspent.script_pub_key,
redeem_script: None,
amount: Some(unspent.amount),
};
let res = cl.sign_raw_transaction_with_wallet(&tx, Some(&[input]), None).unwrap();
assert!(res.complete);

let tx = res.transaction().unwrap();
let txid = bitcoincore_rpc::MineableTx::Txid(tx.txid());
cl.send_raw_transaction(&tx).unwrap();
let result = cl.generate_block(&cl.get_new_address(None, None).unwrap(), &[txid]).unwrap();
let tip = cl.get_best_block_hash().unwrap();
assert_eq!(result.hash, tip);
}

fn test_get_best_block_hash(cl: &Client) {
let _ = cl.get_best_block_hash().unwrap();
}
7 changes: 7 additions & 0 deletions json/src/lib.rs
Original file line number Diff line number Diff line change
@@ -988,6 +988,13 @@ pub struct GetAddressInfoResult {
pub label: Option<String>,
}

/// Models the result of "generateblock"
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GenerateBlockResult {
/// Hash of the block generated
pub hash: bitcoin::BlockHash,
}

/// Models the result of "getblockchaininfo"
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct GetBlockchainInfoResult {