You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BitcoinJ库从WIF私钥生成P2SH-Segwit比特币地址时结果不符问题求助

How to Generate P2SH-Segwit (Nested Segwit) Address with BitcoinJ from WIF Private Key

我看到你现在的代码生成了普通的1-of-1多重签名P2SH地址,但你需要的是**P2SH-Segwit(嵌套Segwit,即P2WPKH wrapped in P2SH)**地址,这两种地址的构造逻辑完全不同,所以导致生成的地址和预期不符。

问题根源

你的代码用ScriptBuilder.createRedeemScript(1, eckeyAList)创建的是多重签名脚本(格式为OP_1 <pubkey> OP_1 OP_CHECKMULTISIG),但P2SH-Segwit的redeem script应该是P2WPKH的见证脚本——也就是OP_0 <20-byte pubkey hash>,这才是嵌套Segwit地址的核心构造逻辑。

修正后的解决方案

下面是调整后的完整代码,我保留了你原本正确的WIF私钥加载逻辑,只修改了地址生成的核心步骤:

String base58PrivateKeyString = "KyyJ5vVWjZck5nsAgDWvoN1u7Q8qp5FzE8WiCq97MbnRgdLesqJZ";
NetworkParameters params = MainNetParams.get();
ECKey key;

// 从WIF私钥加载ECKey(这部分你的代码没问题)
if (base58PrivateKeyString.length() == 51 || base58PrivateKeyString.length() == 52) {
    DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(params, base58PrivateKeyString);
    key = dumpedPrivateKey.getKey();
} else {
    BigInteger privKey = Base58.decodeToBigInteger(base58PrivateKeyString);
    key = ECKey.fromPrivate(privKey);
}

// 获取公钥(保留你的输出)
String pubKeyStr = key.getPublicKeyAsHex();
System.out.println("Public key is: " + pubKeyStr + "\n");

// 生成P2SH-Segwit地址的正确步骤
// 1. 获取公钥的HASH160(公钥哈希)
byte[] pubKeyHash = key.getPubKeyHash();
// 2. 创建P2WPKH的见证脚本:OP_0 + 20字节公钥哈希
Script p2wpkhScript = ScriptBuilder.createP2WPKHOutputScript(pubKeyHash);
// 3. 基于该见证脚本创建P2SH输出脚本(把P2WPKH脚本作为redeem script)
Script p2shScript = ScriptBuilder.createP2SHOutputScript(p2wpkhScript);
// 4. 提取脚本哈希并生成LegacyAddress(P2SH地址)
byte[] scriptHash = ScriptPattern.extractHashFromP2SH(p2shScript);
LegacyAddress p2shSegwitAddress = LegacyAddress.fromScriptHash(params, scriptHash);

System.out.println("P2SH-Segwit address from the WIF private key is: " + p2shSegwitAddress.toString());
// 输出结果:38SGXvkMvq8Tsop8rFx2K4JnaFKYZkjd5z

关键变化说明

  • 替换了原本的多重签名redeem script创建逻辑,改用ScriptBuilder.createP2WPKHOutputScript(pubKeyHash)生成符合Segwit标准的P2WPKH见证脚本
  • 将这个P2WPKH脚本作为参数传入createP2SHOutputScript,这样生成的P2SH脚本对应的就是嵌套Segwit地址

运行修正后的代码,就能得到你预期的正确地址38SGXvkMvq8Tsop8rFx2K4JnaFKYZkjd5z。

内容的提问来源于stack exchange,提问作者Lakshitha Kanchana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:52:33