比特币主网地址生成和签名

一.地址生成

var bip39 = require('bip39')
const bip32 = require('bip32')
const bitcoin = require('bitcoinjs-lib')
const baddress = require('bitcoinjs-lib/src/address')
const bcrypto = require('bitcoinjs-lib/src/crypto')
const NETWORKS = require('bitcoinjs-lib/src/networks')

function getAddress (node) {
    console.log("PrivateKey = " + node.toWIF().toString('hex'));
    console.log("PublicKey =" + node.publicKey.toString('hex'))
    return baddress.toBase58Check(bcrypto.hash160(node.publicKey), NETWORKS.bitcoin.pubKeyHash)
}
var mnemonic = bip39.generateMnemonic()
console.log("-----------助记词--------------")
console.log(mnemonic)
console.log("-----------助记词--------------")
var seed = bip39.mnemonicToSeed(mnemonic)
console.log("---------seed------------")
console.log(seed)
console.log("---------seed------------")
const rootMasterKey = bip32.fromSeed(seed)

var key1 = rootMasterKey.derivePath("m/44'/0'/0'/0/0")
var key2 = rootMasterKey.derivePath("m/44'/0'/0'/0/1")
var key3 = rootMasterKey.derivePath("m/44'/0'/0'/1/0")
var key4 =rootMasterKey.derivePath("m/44'/0'/0'/1/1")

// receive addresses
console.log(getAddress(key1))
console.log(getAddress(key2))

// change addresses
console.log(getAddress(key3))
console.log(getAddress(key4))

二.比特币签名

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("Send Transaction total amount is: " + sendAmount)
        txb.setVersion(1);
        var totalMoney = 0;
        for(var i=0; i

想要学习更多关于区块链钱包的知识请去笔者的GitHub,区块链钱包技术指南:https://github.com/guoshijiang/blockchain-wallet/

关注问我技术公众号,加小问,拉您入技术交流群:

比特币主网地址生成和签名_第1张图片

你可能感兴趣的:(BTC,区块链技术)