Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the process of developing bitcoin application BitcoinJS-lib with JavaScript

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the process of developing bitcoin application BitcoinJS-lib with JavaScript? I believe many inexperienced people are at a loss about it. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

In this tutorial, we will learn how to use the Bitconjs-lib development library to develop a simple JavaScript version of Bitcoin application. The features we want to implement include: offline creation of bitcoin private keys and addresses, account recharge, offline construction of naked transactions for transfer and broadcast to Bitcoin networks.

1. Install BitcoinJS-lib

BitcoinJS-lib is a npm package that can be used in node.js or browser javascript environments. You can install the BitcoinJS-lib package using npm or yarn:

Npm install bitcoinjs-lib2, introduction of BitcoinJS-lib

First, introduce the bitcoinjs-lib development library:

Const Btc = require ('bitcoinjs-lib')

The main chain and the test chain of Bitcoin have different network parameters. For the sake of simplification and security, we use the test chain to develop the application in this tutorial, so we introduce the test chain network parameters:

Const TestNet = Btc.networks.testnet3, create a bitcoin address with BitcoinJS

Each bitcoin address corresponds to a pair of keys (private key and public key), so we first create a key pair with BitcoinJS and derive the address from the key pair:

Let keyPair = Btc.ECPair.makeRandom ({network: TestNet}) let address = keyPair.getAddress () let wifKey = keyPair.toWIF () console.log (`Address: ${address}\ n WifKey: ${wifKey} `)

In the above code, we first use the static method makeRandom () of BitcoinJS's ECPair class to generate a random key pair, then use the getAddress () method of the key pair to derive the corresponding bitcoin address, and use toWif () to obtain the private key in WIF format, and finally show the resulting address and the private key in WIF format.

The result of the code run is as follows (your result should be different):

Address: mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1WifKey: cTEAh3DsC7KE4mzY5YFTYommzr7czbdiBfLPsXZrF6o3zSQLLw9Q4, import WIF private key with BitcoinJS

If you have private keys in WIF format for other wallets, you can also import BitcoinJS and derive the corresponding address, for example:

Let wifKey = 'cTEAh3DsC7KE4mzY5YFTYommzr7czbdiBfLPsXZrF6o3zSQLLw9Q'let keyPair = new Btc.ECPair.fromWIF (privKey, TestNet) console.log ("Address:", keyPair.getAddress ())

The results are similar to the following:

Address: mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu15, using passwords to help memorize private keys

To remember the private key is a bit troublesome, we can use the password to assist in the derivation of the private key, so that we can further derive the public key and address. The following code is implemented using BitcoinJS and the nodejs large number computing library bigi:

Const BigInteger = require ('bigi') let passphrase =' J@vaScr1pt'let keyPair = generateAddressFromSHA256Hash (passphrase); console.log ('Address:', keyPair.getAddress ()) function generateAddressFromSHA256Hash (passphrase) {let hash = Btc.crypto.sha256 (passphrase); let d = BigInteger.fromBuffer (hash); let keyPair = new Btc.ECPair (d, null, {network: TestNet}); return keyPair;}

The results are as follows:

Address: mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1

Now using the generateAddressFromSHA256Hash () function, we can use the password J@VaSc1pt at any time to pay the address mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1 and its corresponding key pair.

6. Use the test chain Faucet to recharge the account

Before we continue, we need to add some bitcoin to the bitcoin address we created. There are some bitcoin test chains of Faucet on the Internet, which can be used to add some bitcoin to any given bitcoin address for development and testing. I use this, and of course you can search for more of this kind of Faucet.

Let Faucet recharge our test address as follows:

Cool, now we have 1.3bitcoins to continue testing!

7. Query Bitcoin address details

There are two ways to query the balance of a bitcoin address, UTXO, and other information: use your own node, or use a third-party API. For simplicity, in this tutorial we use a third-party API to query the balance and UTXO of the specified bitcoin address:

Onst request = require ('request'); let addr =' mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1'let apiUrl = 'https://testnet.blockexplorer.com/api/addr/'// log unspent transactionsrequest.get (apiUrl + addr +' / utxo', (err, req, body) = > {console.log ('utxo = >', JSON.parse (body))}); / / log balancerequest.get (apiUrl + addr +'/ balance', (err, req, body) = > {console.log ('balance = >', JSON.parse (body))})

The results are as follows:

Utxo = > [{address: 'mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1', txid:' 2d742aa8409ee4cd8afcb2f59aac6ede47b478fafbca2335c9c04c6aedf94c9btransactions, vout: 0, scriptPubKey: '76a9146d622b371423d2e450c19d98059867d71e6aa87c88actly, amount: 1.3,000,000 / / 1.3 BTC = 130000000 satoshis8, construct Bitcoin transfer naked transactions with BitcoinJS

Constructing a naked bitcoin transaction is a little more complicated, and we need to organize the input and output of the transaction ourselves.

First create a transaction object using BitcoinJS's transaction constructor TransactionBuider:

Let tx = new Btc.TransactionBuilder (TestNet)

Then we declare that we will transfer out and transfer the account:

Let keyPair1 = generateAddressFromSHA256Hash ('JacuvaScr1pt') let keyPair2 = generateAddressFromSHA256Hash (' Blocktc0in')

Then declare the parameters such as transfer amount and handling fee, and calculate the change amount:

Let amountWeHave = 130000000 / / 1.3BTClet amountToKeep = 100000000 / / 1 BTClet transactionFee = 1000 / / .00001 BTClet amountToSend = amountWeHave-amountToKeep-transactionFee

All right, now you can add input to the transaction. Remember the transaction output we queried earlier? This transaction output will be used as input to the new deal:

[{txid: '2d742aa8409ee4cd8afcb2f59aac6ede47b478fafbca2335c9c04c6aedf94c9b, vout: 0, satoshis: 130000000,}]

Use the addInput () method of the BitcoinJS transaction object to add transaction input:

Tx.addInput ('2d742aa8409, 0)

Next, to add the transaction output, we need to declare the target address and amount of the transaction output:

Tx.addOutput (keyPair2.getAddress (), amountToSend)

Since the transaction input amount is greater than the transaction output amount mentioned above, we also need to add change output:

Tx.addOutput (keyPair1.getAddress (), amountToKeep)

Now let's sign, because we are using keyPair1's bitcoin, so we need to use the private key of keyPair1 to sign:

Tx.sign (0, keyPair1)

Next, serialize the signature transaction into a hexadecimal stream for broadcast to the bitcoin network:

Let tx_hex = tx.build () .toHex ()

The complete code is as follows:

Let tx = new Btc.TransactionBuilder (TestNet) let keyPair1 = generateAddressFromSHA256Hash ('JargvaScr1pt') let keyPair2 = generateAddressFromSHA256Hash (' Blocktc0in') let amountWeHave = 130000000 / / 1.3 BTClet amountToKeep = 100000000 / / 1 BTClet transactionFee = 1000 /. 00001 BTClet amountToSend = amountWeHave-amountToKeep-transactionFeetx.addInput ('2d742aaa8409ee4cd8afcb2f59aac6ede47b478fafbca2335c9c04c6aedf94c9broom0) tx.addOutput (keyPair2.getAddress (), amountToSend) tx.addOutput (keyPair1.getAddress (), amountToKeep) tx.sign (0, keyPair1) let tx_hex = tx.build () .toHex (' our beautiful transaction:') Tx_hex)

The output is as follows:

01000000019b4cf9ed6a4cc0c93523cafbfa78b447de6eac9af5b2fc8acde49e40a82a742d000000006b483045022100b8e1bc891bbd910960cf00b52b87493ddf808c0b6816b05724b62c507c2ea552022071d775d9b89e0bbc1c2d1b907b700dbda58d880508ba7f6e11a3acc659d3ebe20121034ec9060d1935b235794e22f5335b4e5c55e764ba9bddab2cf7f199dac7309ce1ffffffff0298bfc901000000001976a91423e6e135110f5fcacbd77323382bb70e4f76105f88ac00e1f505000000001976a9146d622b371423d2e450c19d98059867d71e6aa87c88ac000000009, decode naked transaction

It is an effective debugging method to check the contents of naked transactions before broadcasting naked transactions. We can use the decoding tool provided by BlockCypher to view the content of the naked transaction, and the result is as follows

{"addresses": ["mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1", "minnXa8Qarg5WbxPQg3vjLZdpbZGHavCzC"], "block_height":-1, "block_index":-1, "confirmations": 0, "double_spend": false, "fees": 1000, "hash": "64697ab2a3c76b8c5930ca128316238bba5b172b2f8f61a0046b6630b1f80f08" "inputs": [{"addresses": ["mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1"], "age": 1180957, "output_index": 0, "output_value": 130000000, "prev_hash": "2d742aa8409ee4cd8afcb2f59aac6ede47b478fafbca2335c9c04c6aedf94c9b", "script": "483045022100b8e1bc891bbd910960cf00b52b87493ddf808c0b6816b05724b62c507c2ea552022071d775d9b89e0bbc1c2d1b907b700dbda58d880508ba7f6e11a3acc659d3ebe20121034ec9060d1935b235794e22f5335b4e5c55e764ba9bddab2cf7f199dac7309ce1" "script_type": "pay-to-pubkey-hash", "sequence": 4294967295}], "outputs": [{"addresses": ["minnXa8Qarg5WbxPQg3vjLZdpbZGHavCzC"], "script": "76a91423e6e135110f5fcacbd77323382bb70e4f76105f88ac", "script_type": "pay-to-pubkey-hash" "value": 29999000}, {"addresses": ["mqVKYrNJcMkdK2QHFNEd1P6Qfc1Sqs3hu1"], "script": "76a9146d622b371423d2e450c19d98059867d71e6aa87c88ac", "script_type": "pay-to-pubkey-hash", "value": 100000000}], "preference": "low" "received": "2017-09-04T05:24:14.417939071Z", "relayed_by": "54.158.194.253", "size": 226, "total": 129999000, "ver": 1, "vin_sz": 1, "vout_sz": 2} 10, broadcast Bitcoin naked transactions

Once bitcoin naked transactions are generated, many services that broadcast bitcoin naked transactions can be found online. If you want to broadcast in your code, you can also use this API.

After the broadcast is complete, you can view the transaction confirmation in the block browser:

After reading the above, have you mastered the process of developing bitcoin application BitcoinJS-lib with JavaScript? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report