使用libbitcoin-system 3.8.0从ec_private私钥获取Segwit比特币地址
无需HD密钥,从ec_private生成Segwit比特币地址
要生成Segwit地址,你需要从私钥导出公钥,再根据目标地址类型(原生P2WPKH或嵌套P2SH-P2WPKH)生成对应的支付脚本,最后编码为地址。下面是基于你的代码补充后的完整实现:
完整代码示例
#include <bitcoin/system.hpp> using namespace bc; using namespace std; int main() { data_chunk seed(16); pseudo_random_fill(seed); ec_secret secretKey = bitcoin_hash(seed); // 主网私钥(0x8000对应主网WIF前缀,true表示使用压缩公钥) wallet::ec_private wif(secretKey, 0x8000, true); string legacyAddress = wif.to_payment_address().encoded(); cout << "Legacy Address: " << legacyAddress << endl; // 1. 从私钥导出压缩公钥 wallet::ec_public publicKey = wif.to_public(); // -------------------------- // 生成原生Segwit(P2WPKH)地址 // -------------------------- // 计算公钥的SHA256+RIPEMD160哈希 short_hash pubkeyHash = bitcoin_short_hash(publicKey.point()); // 构造P2WPKH见证脚本:OP_0 + 20字节公钥哈希 script p2wpkhScript = script::to_witness_pubkey_hash_pattern(pubkeyHash); // 主网P2WPKH地址版本号为0x06,测试网为0x6f wallet::payment_address p2wpkhAddress(p2wpkhScript, 0x06); cout << "P2WPKH Address: " << p2wpkhAddress.encoded() << endl; // -------------------------- // 生成嵌套Segwit(P2SH-P2WPKH)地址 // -------------------------- // 获取P2WPKH的redeem脚本(即上述的p2wpkhScript) // 计算redeem脚本的SHA256+RIPEMD160哈希 short_hash redeemScriptHash = bitcoin_short_hash(p2wpkhScript.to_data(false)); // 构造P2SH脚本:OP_HASH160 + 20字节脚本哈希 + OP_EQUAL script p2shP2wpkhScript = script::to_pay_script_hash_pattern(redeemScriptHash); // 主网P2SH地址版本号为0x05,测试网为0xc4 wallet::payment_address p2shP2wpkhAddress(p2shP2wpkhScript, 0x05); cout << "P2SH-P2WPKH Address: " << p2shP2wpkhAddress.encoded() << endl; return 0; }
关键步骤说明
- 压缩公钥要求:Segwit地址必须使用压缩公钥,你的代码中创建
ec_private时已指定true参数,因此直接调用to_public()即可得到符合要求的公钥。 - 原生P2WPKH地址:通过
script::to_witness_pubkey_hash_pattern生成见证脚本,搭配主网版本号0x06创建地址,最终编码为以bc1开头的主网地址。 - 嵌套P2SH-P2WPKH地址:先生成P2WPKH的redeem脚本,对其哈希后构造P2SH脚本,搭配主网版本号
0x05创建地址,最终编码为以3开头的主网地址,兼容旧版比特币客户端。
版本号对应表
| 网络类型 | P2WPKH版本号 | P2SH-P2WPKH版本号 |
|---|---|---|
| 主网 | 0x06 | 0x05 |
| 测试网 | 0x6f | 0xc4 |
内容的提问来源于stack exchange,提问作者Lakshitha Kanchana
相关产品推荐
相关产品推荐

