Merge rust-bitcoin/rust-bitcoin#3642: Add p2wpkh address creation example

d9b48cc2ce Add p2wpkh address creation example (yancy)

Pull request description:

  Add example for creating p2wpkh address.  It would be helpful to add examples the other address types (p2tr etc) either in separate files or in one.  Note this should be created in the Address crate however that crate is currently empty.

ACKs for top commit:
  tcharding:
    ACK d9b48cc2ce
  apoelstra:
    ACK d9b48cc2ce68b065640caa22da6fbcb1f3ad85f8; successfully ran local tests

Tree-SHA512: b383c1aca2d3669f66f0dcaf858526793ffc9e62671cf4985c44a11f7717c8e02d359b4d7d8b5822ebdde27595612e10bc831c84a2c4b654f69d4137ad16ba2f
This commit is contained in:
merge-script 2024-11-28 13:27:47 +00:00
commit 88da0674f2
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
2 changed files with 28 additions and 0 deletions

View File

@ -71,6 +71,10 @@ required-features = ["std", "bitcoinconsensus"]
name = "ecdsa-psbt-simple" name = "ecdsa-psbt-simple"
required-features = ["rand-std"] required-features = ["rand-std"]
[[example]]
name = "create-p2wpkh-address"
required-features = ["rand-std"]
[[example]] [[example]]
name = "sign-tx-segwit-v0" name = "sign-tx-segwit-v0"
required-features = ["rand-std"] required-features = ["rand-std"]

View File

@ -0,0 +1,24 @@
use bitcoin::secp256k1::{rand, Secp256k1};
use bitcoin::{Address, CompressedPublicKey, Network, PrivateKey};
/// Generate a P2WPKH (pay-to-witness-public-key-hash) address and print it
/// along with the associated private key needed to transact.
fn main() {
// Create new secp256k1 instance.
let secp = Secp256k1::new();
// Generate secp256k1 public and private key pair.
let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
// Create a Bitcoin private key to be used on the Bitcoin mainnet.
let private_key = PrivateKey::new(secret_key, Network::Bitcoin);
// Create a compressed Bitcoin public key from the secp256k1 public key.
let public_key = CompressedPublicKey(public_key);
// Create a Bitcoin P2WPKH address.
let address = Address::p2wpkh(public_key, Network::Bitcoin);
println!("Private Key: {}", private_key);
println!("Address: {}", address);
}