比特币bip44动态生成HD钱包地址

Java 实现 BIP44

适用场景:

动态地生成仅有只读权限的钱包地址,生成过程不需要使用私钥。

准备:

生成mnemonic > 生成seed > 生成 Extended Public Key

生成地址主要依赖Extended Public Key,加上addressIndex(0至232-1)就可以确定一个地址.

BTC使用m/44’/0’/0’/0的 Extended Public Key 生成 m/44’/0’/0’/0/*,
ETH使用m/44’/60’/0’/0的 Extended Public Key 生成 m/44’/60’/0’/0/*,
mainnet的Extended Public Key以xpub做前缀,例如:

xpub6EefkjfzXmdmDGyFKJvnarbP3jSkoGkGzJiqyUQ2mA2FbaDmHVZy7TwtQ3oNcjUKbRu6SE6kMbevgRevXdeWdfL1rZzoPktbZDVjiToy6Rh

扩展公钥不等同于公钥,扩展公钥主要包含了3个信息:
1. 区块链网络(mainnet 或 testnet)
2. 公钥
3. chain code

java代码

import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.params.MainNetParams;
import org.web3j.crypto.Keys;

/**
 * 
 * @author Kin神
 * 
 */
public class HdWalletUtils {
    //测试链可以用TestNet3Params
    private static final MainNetParams mainnetParams = new MainNetParams();


    /**
     * 生成 BTC 比特币地址
     * @param addressIndex
     * @param ext_key
     * @return
     */
    public static String getBtcAddress(int addressIndex, String ext_key) {
        DeterministicKey parentDK = DeterministicKey.deserializeB58(ext_key, mainnetParams);
        DeterministicKey childDK = HDKeyDerivation.deriveChildKey(parentDK, addressIndex);
        return childDK.toAddress(mainnetParams).toBase58();
    }

    /**
     * 生成 ETH 以太币地址
     * @param addressIndex
     * @param ext_key
     * @return
     */
    public static String getEthAddress(int addressIndex, String ext_key) {
        DeterministicKey parentDK = DeterministicKey.deserializeB58(ext_key, mainnetParams);
        DeterministicKey childDK = HDKeyDerivation.deriveChildKey(parentDK, addressIndex);
        ECKey uncompressedChildKey = childDK.decompress();
        //以太坊需要把前缀去掉(0x04前缀表示未压缩)
        String hexK = uncompressedChildKey.getPublicKeyAsHex().substring(2);
        String addr = Keys.getAddress(hexK);
        return Keys.toChecksumAddress(addr);
    }
}

参考资料

验证网址:
https://iancoleman.io/bip39/

BIP32:
https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

BIP44:
https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki

你可能感兴趣的:(区块链)