1

我正在尝试从 WIF 私钥创建 P2SH-Segwit 比特币地址。我在 Java 中使用 BitcoinJ 库。请参阅以下代码。

String base58PrivateKeyString = "KyyJ5vVWjZck5nsAgDWvoN1u7Q8qp5FzE8WiCq97MbnRgdLesqJZ";

NetworkParameters params = MainNetParams.get();
ECKey key;

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);
}

// Getting the public key
String pubKeyStr = key.getPublicKeyAsHex();
System.out.println("Public key is: " + pubKeyStr + "\n");

// Getting the P2SH address
List<ECKey> eckeyAList = new ArrayList<>();
eckeyAList.add(key);
Script redeemScript = ScriptBuilder.createRedeemScript(1, eckeyAList);
Script script = ScriptBuilder.createP2SHOutputScript(redeemScript);
byte[] scriptHash = ScriptPattern.extractHashFromP2SH(script);
LegacyAddress legacyAddress = LegacyAddress.fromScriptHash(params, scriptHash);
System.out.println("P2S address from the WIF pivate key is: " + legacyAddress.toString()); //3Az5wdibtPRGac41aGtyqzT1ejtobvb6qW
    

它的输出公钥是 03b5319c83adf4a2e274c37401623c7bf0ba453cee3e119f3bc2c523d27059b64f。它的输出 P2SH 地址是 3Az5wdibtPRGac41aGtyqzT1ejtobvb6qW,这与正确的 P2SH 地址 38SGXvkMvq8Tsop8rFx2K4JnaFKYZkjd5z 相差甚远

如果你们中的任何人知道要纠正这个问题,我很乐意听取您的意见。

4

2 回答 2

2

作为赎回脚本,您必须使用 P2WPKH(支付给见证人公钥哈希)然后赎回脚本的创建将如下所示:

脚本redeemScript = ScriptBuilder.createP2WPKHOutputScript(key);

于 2021-07-13T17:05:03.597 回答
-1

这是在 kotlin 中使用 Mikhail 的建议的正确代码:

val params: NetworkParameters = MainNetParams.get()
val key: ECKey = ECKey.fromPrivate(BigInteger("2"))
val redeemScript: Script = ScriptBuilder.createP2WPKHOutputScript(key)
val script = ScriptBuilder.createP2SHOutputScript(redeemScript)
val scriptHash = ScriptPattern.extractHashFromP2SH(script)
val legacyAddress = LegacyAddress.fromScriptHash(params, scriptHash)
println("P2S address from the WIF private key is: $legacyAddress")
于 2021-07-13T23:45:27.940 回答