Skip to content

Commit

Permalink
Add p2wpkh address creation example
Browse files Browse the repository at this point in the history
  • Loading branch information
yancyribbens committed Nov 23, 2024
1 parent c47a41a commit 3e8dd8d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions bitcoin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ required-features = ["std", "bitcoinconsensus"]
name = "ecdsa-psbt-simple"
required-features = ["rand-std"]

[[example]]
name = "create-p2wpkh-address"
required-features = ["rand-std"]

[[example]]
name = "sign-tx-segwit-v0"
required-features = ["rand-std"]
Expand Down
26 changes: 26 additions & 0 deletions bitcoin/examples/create-p2wpkh-address.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
extern crate bitcoin;

use bitcoin::{KnownHrp, Address, CompressedPublicKey, PrivateKey, Network};
use bitcoin::secp256k1::{rand, Secp256k1};

// Note: creating a new address requires the rand-std feature flag.
// Build with cargo build --examples --features=rand-std

fn main() {
// Create a new Secp256k1 elliptic curve.
let s = Secp256k1::new();

// Generate a Secp256k1 secret key.
let (secret_key, _) = s.generate_keypair(&mut rand::thread_rng());

// Create a Bitcoin private key.
let private_key = PrivateKey::new(secret_key, Network::Bitcoin);

// Create a compressed public key derived from the private key.
let public_key = CompressedPublicKey::from_private_key(&s, private_key).unwrap();

// Create a Bitcoin P2wpkh (Pay-to-Witness-Public-Key-Hash) address.
let address = Address::p2wpkh(public_key, KnownHrp::Mainnet);

println!("Address: {}", address);
}

0 comments on commit 3e8dd8d

Please sign in to comment.