前言:关于区块链方面东西的自行了解,这里只说开发实现过程。
关系梳理: 1、助记词(bip39 生成) 推导出 私钥、公钥、地址。
2、使用 私钥、地址、utxo 等进行签名广播交易。
比特币示例:
'use strict'
const bitcoin = require('bitcoinjs-lib')
const bip39 = require('bip39')
var bip32 = require('bip32')
const wallet = {}
const network = bitcoin.networks.bitcoin
wallet.mnemonicGenerate = function (words, callback) {
try {
let mnemonic = words || bip39.generateMnemonic()
let seed = bip39.mnemonicToSeedSync(mnemonic)
let hash = bitcoin.crypto.sha256(mnemonic).toString('hex')
let root = bip32.fromSeed(seed)
let BTCroot = root.derivePath("m/44'/0'/0'/0/0")
let hroot = bitcoin.HDNode.fromSeedHex(seed, network)
let BTChroot = hroot.derivePath("m/44'/0'/0'/0/0")
let store = {
mnemonic,
hash,
BTC: {
privateKey: BTCroot.toWIF(),
publicKey: BTCroot.publicKey.toString('hex'),
address: BTChroot.getAddress()
}
}
console.log(store)
} catch (err) {}
}
wallet.privateKeyToAddress = function (privateKey, callback) {
let hash = bitcoin.crypto.sha256(privateKey).toString('hex')
let keyPair = new bitcoin.ECPair.fromWIF(privateKey, network)
let address = keyPair.getAddress()
let store = {
address,
hash
}
callback(store)
}
module.exports = exports = wallet
签名
const bitcoin = require('bitcoinjs-lib');
function bitcoinSign(privateKey, amount, utxo, sendFee, toAddress, changeAddress) {
if(!privateKey || !amount || !utxo || !sendFee || !toAddress || !changeAddress ) {
console.log("one of privateKey, amount, utxo, sendFee, toAddress and changeAddress is null, please give a valid param");
} else {
console.log("param is valid, start sign transaction");
set = bitcoin.ECPair.fromWIF(privateKey);
txb = new bitcoin.TransactionBuilder();
var sendAmount = parseFloat(amount);
var fee = parseFloat(sendFee);
sendAmount += fee;
console.log(sendAmount)
txb.setVersion(1);
var totalMoney = 0;
for(var i=0; i<utxo.length; i++){
txb.addInput(utxo[i].tx_hash_big_endian, utxo[i].tx_output_n);
totalMoney += utxo[i].value;
}
console.log(totalMoney)
txb.addOutput(toAddress, sendAmount - fee);
for(var i=0;i<utxo.length;i++){
txb.sign(i, set);
}
}
return txb.buildIncomplete().toHex();
}
var bitUtxo = {
"unspent_outputs":[
{
"tx_hash":"8ee886ba0c66ba2df2c0e3da3beee526996d9a5e6bbbdfea43e1a78340cb0128",
"tx_hash_big_endian":"2801cb4083a7e143eadfbb6b5e9a6d9926e5ee3bdae3c0f22dba660cba86e88e",
"tx_index":382253932,
"tx_output_n": 0,
"script":"76a914ca45c6eceea7aed14b6aea7e0ed466c6134f14bc88ac",
"value": 1899000,
"value_hex": "1cf9f8",
"confirmations":2
}
]
}
var privateKey = "KwHEU8DTrY2ekGuqE6EqMMrcFj6Kdb6gWF4k8SpUeV7vDfc9c5Fn";
var amount = 1898000;
var utxo = bitUtxo.unspent_outputs;
var sendFee = 1000;
var toAddress = "12zEJohMNqSZLXH1Msxpw41ykkk3rxgx1s";
var changeAddress = "1KSX5wmrVax3LYaB4uKUxXzCRcv5SiLDq3";
var sign = bitcoinSign(privateKey, amount, bitUtxo.unspent_outputs, sendFee, toAddress, changeAddress);
console.log(sign);
let id = txb.buildIncomplete().getId()
let hash = txb.buildIncomplete().toHex()
附上一些参考文章希望对你们有帮助:
助记词结果验证
签名验证
比特币开发拓展
区块链了解
去中心化钱包详解
后续会写上以太坊开发
|