1
0
mirror of https://github.com/bitcoinbook/bitcoinbook synced 2024-12-04 22:08:23 +00:00
bitcoinbook/code/addr.cpp

49 lines
1.6 KiB
C++
Raw Normal View History

2014-09-28 15:52:50 +00:00
#include <bitcoin/bitcoin.hpp>
int main()
{
2017-07-18 04:07:31 +00:00
// Private secret key string as base16
bc::ec_secret decoded;
bc::decode_base16(decoded,
2014-09-28 15:52:50 +00:00
"038109007313a5807b2eccc082c8c3fbb988a973cacf1a7df9ce725c31b14776");
2017-07-18 04:07:31 +00:00
bc::wallet::ec_private secret(
decoded, bc::wallet::ec_private::mainnet_p2kh);
2014-09-28 15:52:50 +00:00
// Get public key.
2017-07-18 04:07:31 +00:00
bc::wallet::ec_public public_key(secret);
std::cout << "Public key: " << public_key.encoded() << std::endl;
2014-09-28 15:52:50 +00:00
// Create Bitcoin address.
// Normally you can use:
2017-07-18 04:07:31 +00:00
// bc::wallet::payment_address payaddr =
// public_key.to_payment_address(
// bc::wallet::ec_public::mainnet_p2kh);
// const std::string address = payaddr.encoded();
2014-09-28 15:52:50 +00:00
// Compute hash of public key for P2PKH address.
2017-07-18 04:07:31 +00:00
bc::data_chunk public_key_data;
public_key.to_data(public_key_data);
const auto hash = bc::bitcoin_short_hash(public_key_data);
2014-09-28 15:52:50 +00:00
bc::data_chunk unencoded_address;
// Reserve 25 bytes
// [ version:1 ]
// [ hash:20 ]
// [ checksum:4 ]
unencoded_address.reserve(25);
// Version byte, 0 is normal BTC address (P2PKH).
unencoded_address.push_back(0);
// Hash data
bc::extend_data(unencoded_address, hash);
// Checksum is computed by hashing data, and adding 4 bytes from hash.
bc::append_checksum(unencoded_address);
2017-05-09 20:16:06 +00:00
// Finally we must encode the result in Bitcoin's base58 encoding.
2014-09-28 15:52:50 +00:00
assert(unencoded_address.size() == 25);
const std::string address = bc::encode_base58(unencoded_address);
std::cout << "Address: " << address << std::endl;
return 0;
}