前言:
HD 錢(qián)包全稱(chēng)為是分層確定性(Hierarchical Deterministic)錢(qián)包的縮寫(xiě) HD Wallets瓷翻。
image.png
首次創(chuàng)建 HD 錢(qián)包或者備份錢(qián)包時(shí)眯漩,會(huì)產(chǎn)生一個(gè)助記詞页畦,助記詞是一連串的英?單詞箫荡,這一串單詞序列就可以創(chuàng)建種子,種子又可以創(chuàng)建所有的私鑰季惩。單詞順序也是錢(qián)包的備份画髓,可以恢復(fù)錢(qián)包掘剪。而種?對(duì)應(yīng)的就是所確定性錢(qián)包的隨機(jī)數(shù)。
HD 錢(qián)包的優(yōu)點(diǎn)在于只需要主公鑰奈虾,就可以生成出任意數(shù)量的子公鑰夺谁。也就是說(shuō)廉赔,無(wú)需私鑰介入(主私鑰和子私鑰),就能基于主公鑰生成新(公鑰)地址匾鸥,而這些地址其實(shí)都能被主私鑰所控制蜡塌。
直接擼代碼:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.bitcoinj.core.Base58;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.HDUtils;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.UnreadableWalletException;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bscoin.coldwallet.cointype.common.ConfigUtil;
import com.bscoin.coldwallet.cointype.common.HDWallet;
import com.bscoin.coldwallet.cointype.common.HashUtils;
import com.bscoin.coldwallet.cointype.common.SecretOperation;
public class HDWalletPK {
private static Logger LOG = LoggerFactory.getLogger(HDWalletPK.class);
static NetworkParameters params;
static{
try {
Configuration config = ConfigUtil.getInstance();
params = config.getBoolean("bitcoin.testnet") ? TestNet3Params.get() : MainNetParams.get();
LOG.info("=== [BTC] bitcoin client networkID:{} ===",params.getId());
} catch (Exception e) {
LOG.info("=== [BTC] com.bscoin.coldwallet.cointype.btc.HDWalletPK:{} ===",e.getMessage(),e);
}
}
/**
* @throws IOException
* @throws FileNotFoundException
* @Title: createHDWalletByPATH
* @param @param word 助記詞
* @param @param passphrase 密碼
* @param @param childNum 生成的hd錢(qián)包數(shù)量
* @param @param params
* @param @return 參數(shù)
* @return List<HDWallet> 返回類(lèi)型
* @throws
*/
public static List<HDWallet> createHDWalletByPATH(String word, String passphrase, int[] childNum) throws FileNotFoundException, IOException {
List<HDWallet> wallet = new ArrayList<HDWallet>();
try {
DeterministicSeed deterministicSeed = new DeterministicSeed(word, null, passphrase, 0L);
DeterministicKeyChain deterministicKeyChain = DeterministicKeyChain.builder().seed(deterministicSeed).build();
DeterministicKey main = deterministicKeyChain.getKeyByPath(HDUtils.parsePath("44H/0H"), true);
DeterministicHierarchy tree = new DeterministicHierarchy(main);
DeterministicKey rootKey = tree.getRootKey();
LOG.info("### [BTC] childs privKey , pubKey , address start ###");
for (int i = childNum[0], len = childNum[1]; i < len; i++) {
DeterministicKey deriveChildKey = HDKeyDerivation.deriveChildKey(rootKey, new ChildNumber(i));
wallet.add(new HDWallet(deriveChildKey.getPathAsString(),
deriveChildKey.getPrivateKeyAsWiF(params),
Base58.encode(deriveChildKey.getPubKey()),
ECKey.fromPrivate(deriveChildKey.getPrivKey()).toAddress(params).toBase58()));
}
LOG.info("### [BTC] childs privKey , pubKey , address end ###");
} catch (UnreadableWalletException e) {
e.printStackTrace();
}
return wallet;
}
/**
* @Title: generateMnemonic
* @param @param passphrase
* @param @param params
* @param @return
* @param @throws IOException 參數(shù)
* @return String 返回類(lèi)型
* @throws
*/
public static String generateMnemonic(String passphrase) throws IOException {
StringBuilder words = new StringBuilder();
SecureRandom secureRandom = new SecureRandom();
long creationTimeSeconds = System.currentTimeMillis() / 1000;
DeterministicSeed ds = new DeterministicSeed(secureRandom, 128, passphrase, creationTimeSeconds);
for (String str : ds.getMnemonicCode()) {
words.append(str).append(" ");
}
return words.toString().trim();
}
/**
* @Title: generateAddress 根據(jù)公鑰生成地址
* @param @param publicKey
* @param @return 參數(shù)
* @return String 返回類(lèi)型
* @throws
*/
public static String generateAddress(String publicKey) {
//1\. 計(jì)算公鑰的 SHA-256 哈希值
byte[] sha256Bytes = HashUtils.sha256(Base58.decode(publicKey));
//2\. 取上一步結(jié)果,計(jì)算 RIPEMD-160 哈希值
RIPEMD160Digest digest = new RIPEMD160Digest();
digest.update(sha256Bytes, 0, sha256Bytes.length);
byte[] ripemd160Bytes = new byte[digest.getDigestSize()];
digest.doFinal(ripemd160Bytes, 0);
//3\. 取上一步結(jié)果扫腺,前面加入地址版本號(hào)(主網(wǎng)版本號(hào)“0x00”)
byte[] networkID = new BigInteger("00", 16).toByteArray();
byte[] extendedRipemd160Bytes = HashUtils.add(networkID, ripemd160Bytes);
//4\. 取上一步結(jié)果岗照,計(jì)算 SHA-256 哈希值
byte[] oneceSha256Bytes = HashUtils.sha256(extendedRipemd160Bytes);
//5\. 取上一步結(jié)果村象,再計(jì)算一下 SHA-256 哈希值
byte[] twiceSha256Bytes = HashUtils.sha256(oneceSha256Bytes);
//6\. 取上一步結(jié)果的前4個(gè)字節(jié)(8位十六進(jìn)制)
byte[] checksum = new byte[4];
System.arraycopy(twiceSha256Bytes, 0, checksum, 0, 4);
//7\. 把這4個(gè)字節(jié)加在第5步的結(jié)果后面笆环,作為校驗(yàn)
byte[] binaryAddressBytes = HashUtils.add(extendedRipemd160Bytes, checksum);
//8\. 把結(jié)果用 Base58 編碼算法進(jìn)行一次編碼
return Base58.encode(binaryAddressBytes);
}
/**
* 驗(yàn)證地址是否合法
* @param address
* @return
*/
public static boolean verifyAddress(String address) {
if (address.length() < 26 || address.length() > 35) {
return false;
}
byte[] decoded = HashUtils.decodeBase58To25Bytes(address);
if (null == decoded) {
return false;
}
// 驗(yàn)證校驗(yàn)碼
byte[] hash1 = HashUtils.sha256(Arrays.copyOfRange(decoded, 0, 21));
byte[] hash2 = HashUtils.sha256(hash1);
return Arrays.equals(Arrays.copyOfRange(hash2, 0, 4), Arrays.copyOfRange(decoded, 21, 25));
}
public static void main(String[] args) throws IOException {
String s = generateMnemonic("xx");//生成助記次
int[] a = {1,10};//根據(jù)助記詞生成childID={1-10}的錢(qián)包地址
List<HDWallet> walls = createHDWalletByPATH(s, "123457",a);
for (HDWallet hdWallet : walls) {
System.out.println(hdWallet.getPubKey());
System.out.println(hdWallet.getPrivKey());
System.out.println(hdWallet.getAddress());
System.out.println("----------------------");
}
}
}
image.gif
HashUtil:
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.stream.Stream;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ArrayUtils;
/**
* @ClassName: HashUtils
* @author DHing
*
*/
public class HashUtils {
/**
* 加密字符集合
*/
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
/**
* 使用 sha256 算法加密
* @param input
* @return
*/
public static String sha256Hex(String input) {
return DigestUtils.sha256Hex(input);
}
/**
* 使用 sha256 hash 算法加密,返回一個(gè) 64 位的字符串 hash
* @param input
* @return
*/
public static String sha256Hex(byte[] input) {
return DigestUtils.sha256Hex(input);
}
public static byte[] sha256(String input) {
return DigestUtils.sha256(input);
}
public static byte[] sha256(byte[] input) {
return DigestUtils.sha256(input);
}
/**
* 兩個(gè)byte[]數(shù)組相加
*
* @param data1
* @param data2
* @return
*/
public static byte[] add(byte[] data1, byte[] data2) {
byte[] result = new byte[data1.length + data2.length];
System.arraycopy(data1, 0, result, 0, data1.length);
System.arraycopy(data2, 0, result, data1.length, data2.length);
return result;
}
/**
* 將多個(gè)字節(jié)數(shù)組合并成一個(gè)字節(jié)數(shù)組
*
* @param bytes
* @return
*/
public static byte[] merge(byte[]... bytes) {
Stream<Byte> stream = Stream.of();
for (byte[] b : bytes) {
stream = Stream.concat(stream, Arrays.stream(ArrayUtils.toObject(b)));
}
return ArrayUtils.toPrimitive(stream.toArray(Byte[]::new));
}
/**
* long 類(lèi)型轉(zhuǎn) byte[]
*
* @param val
* @return
*/
public static byte[] toBytes(long val) {
return ByteBuffer.allocate(Long.BYTES).putLong(val).array();
}
/**
* 使用 Base58 把地址解碼成 25 字節(jié)
* @param input
* @return
*/
public static byte[] decodeBase58To25Bytes(String input) {
BigInteger num = BigInteger.ZERO;
for (char t : input.toCharArray()) {
int p = ALPHABET.indexOf(t);
if (p == -1) {
return null;
}
num = num.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(p));
}
byte[] result = new byte[25];
byte[] numBytes = num.toByteArray();
System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length);
return result;
}
}
image.gif
package com.bscoin.coldwallet.cointype.common;
import java.io.Serializable;
import org.bitcoinj.core.NetworkParameters;
public class HDWallet implements Serializable{
private static final long serialVersionUID = 1L;
public HDWallet(){}
public HDWallet(String path, String privKey, String pubKey, String address) {
super();
this.path = path;
this.privKey = privKey;
this.pubKey = pubKey;
this.address = address;
}
public HDWallet(String privKey, String pubKey, String address) {
super();
this.privKey = privKey;
this.pubKey = pubKey;
this.address = address;
}
private String word; //助記詞
private String path;//路徑-標(biāo)識(shí)位
private String passphrase;
private String privKey; //私鑰
private String pubKey; //公鑰
private String address;//地址
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPrivKey() {
return privKey;
}
public void setPrivKey(String privKey) {
this.privKey = privKey;
}
public String getPubKey() {
return pubKey;
}
public void setPubKey(String pubKey) {
this.pubKey = pubKey;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassphrase() {
return passphrase;
}
public void setPassphrase(String passphrase) {
this.passphrase = passphrase;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
image.gif