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

How to use JavaScript to write your own Bitcoin transaction Code

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is about how to use JavaScript to write your own bitcoin trading code. I think it is very practical, so I share it with you. I hope you can get something after reading this article.

Today we will write the first bitcoin transaction code. To achieve this, we will use a JavaScript library called bitcore. JavaScript is the most popular modern programming language, and almost every developer knows it, so it makes this article universal and useful to a wider audience.

Let's start with a new NPM project with the following dependencies:

[...] "dependencies": {"bitcore-explorers": "^ 1.0.1", "bitcore-lib": "^ 0.13.19"} [.]

Open the index.js file and import the bitcore library:

Var bitcore = require ("bitcore-lib")

To spend bitcoin, we need an address that contains bitcoin and a private key that allows us to spend money. We will import the WIF version of the private key. WIF is the abbreviation of Wallet Import Format. It can easily import keys between bitcoin wallets. Then we will create a testnet address from that private key:

Var privateKeyWIF = 'cQN511BWtc2dSUMWySmZpr6ShY1un4WK42JegGwkSFX5a8n9GWr3';var privateKey = bitcore.PrivateKey.fromWIF (privateKeyWIF); var sourceAddress = privateKey.toAddress (bitcore.Networks.testnet)

* * warning! * * in that example, I shared my private key with you. You shouldn't do this in real life. The person who owns the private key is the owner of the bitcoin assigned to the address of the key. This is a sign of ownership.

In this case, I just shared the key used to create the testnet address with you. Testnet is a bitcoin network created for software and script testing. It does not contain the real bitcoin, only the tested bitcoin. You can get them for free. Even if someone steals them, it's no big deal. I can take this risk to provide you with an out-of-the-box example.

If someone uses / steals all the test bitcoins from this address, you can recharge it. Copy the address mibK5jk9eP7EkLH175RSPGTLR27zphvvxa and paste it into the form.

It's time to create the targetAddress where we want to send test bitcoin.

Var targetAddress = (new bitcore.PrivateKey) .toAddress (bitcore.Networks.testnet)

If you have any bitcoin, please check our source address. The Bitcoin network uses UTXO to store this information. UTXO is the abbreviation of Unspent Transaction Output.

We have a problem. We don't have a Bitcoin network client. The entire node requires at least 125 GB of hard disk space, which is too much for my poor MacBook Air. We must find a solution. We have to ask someone to read the Bitcoin network for us. And broadcast our deal.

In this case, we are losing the greatest advantage of the bitcoin blockchain. The structure of the system makes it unnecessary for us to trust either side. Network consensus, mathematics and encryption make the data stored in the blockchain credible. But now we ask the middleman to read the data for us. He may provide us with false or outdated data.

We will use Insight from the bitcore-explorers library. Because it is very popular, we are just studying here, we can assume that it can be trusted. The ultimate solution should be to have your own Bitcoin full node.

Well, let's use Insight to check how much bitcoin we're going to spend.

Var Insight = require ("bitcore-explorers"). Insight;var insight = new Insight ("testnet"); insight.getUnspentUtxos (sourceAddress, function (error, utxos) {if (error) {console.log (error);} else {console.log (utxos); / / transaction code goes here}

The output of UTXOs is an array. Each of its elements contains information about the address as the owner of the UTXO and the Satoshis (1 Satoshi = 0.00000001 bitcoin). It looks like this:

[]

It's time to create our deal:

Var tx = new bitcore.Transaction ()

Let's set the received UTXOs to the input of the transaction. One important thing to note is that we get bitcoin not from address but from UTXOs.

Tx.from (utxos)

Let's set up the recipient of the transaction and amount we want to deliver to him. The quantity is given in Satoshis, which is the smallest unit of bitcoin: 1 Satoshi = 0.00000001 bitcoin. This is the output we traded:

Tx.to (targetAddress, 10000)

It's time to discuss the value of the change. UTXOs is the output of a transaction that points to our address but has not been used up yet. UTXOs is like a banknote. If you have a $5 bill in your pocket and want to buy $2 beer, you won't cut some of the bill and give it to the cashier. You give a five-dollar bill and receive a three-dollar change. It is exactly the same as UTXOs. You must use the entire UTXO in the transaction and specify the change value and address, and then return change.

WTF? Do I have to specify a change value? In the store, when I bought $2 beer for $5, I received a return of $3. It's obvious. There is no need to calculate.

In Bitcoin, there is a difference. In fact, change is just another output of the transaction. The sum of outputs should be a little smaller than the sum of input. The difference is called mining fee. You pay it to the miner to include it in the trading block. Wallets or libraries like bitcore.io estimate our mining fee. So in our example, we should return change to the specified address.

Tx.change (sourceAddress)

You can notice that we use sourceAddress. As a result, some of the existing UTXOs for that address disappears (they will be used up), but a new one (from the change one) is also created.

In real life, your wallet uses a new address for every transaction you make. The aim is to improve anonymity. How is it possible that a wallet from one private key can create many public keys and address? Read the deterministic wallet to find the answer

Big! Everything is ready! All we have to do now is sign the transaction with our private key and send it to the Bitcoin blockchain. As I mentioned earlier, we don't have our own bitcoin client. We use external tools to communicate with the blockchain. The question is whether we can believe it. When we broadcast the transaction, there is no risk of capturing the private key or manipulating the transaction (for example, changing the targetAddress). If the tool makes any of the changes listed above, the signature will no longer be valid and the deal will be rejected. The only risk is that the tool will not send the transaction at all. But we can verify it in any blockchain explorer. So we can use Insight again without fear:

Tx.sign (privateKey); tx.serialize (); insight.broadcast (tx, function (error, transactionId) {if (error) {console.log (error);} else {console.log (transactionId);}})

This is everyone! The deal was broadcast to the network. If all goes well, we will receive the transaction ID. Then copy and paste it into the Bitcoin blockchain browser to see if it really works.

The complete code can be found on GitHub.

It is recommended that you visit our Huizhi website's blockchain tutorials and blockchain technology blogs to learn more about blockchain, Bitcoin, cryptocurrency, ethernet, and smart contracts.

Java Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into Java code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare bitcoin development course for Java engineers.

Php Bitcoin Development course, for beginners, covers the core concepts of Bitcoin, such as blockchain storage, decentralized consensus mechanisms, keys and scripts, transactions and UTXO, etc., as well as how to integrate Bitcoin support functions into Php code, such as creating addresses, managing wallets, constructing naked transactions, etc., is a rare bitcoin development course for Php engineers.

Ethernet workshop introductory course, mainly introduces intelligent contracts and dapp application development, suitable for programmers who are familiar with javascript or a development language.

Yi Tai Fang development advanced tutorial, mainly introduces the use of node.js, mongodb, block chain, ipfs to achieve decentralized e-commerce DApp practice, suitable for advanced.

The java ethernet development tutorial is mainly for java and android programmers to conduct a detailed web3j explanation of blockchain ethernet development.

Php Ethernet Square, mainly introduces the use of php for intelligent contract development interaction, account creation, transaction, transfer, token development, filter and transaction and so on.

Python ethernet, mainly for python engineers to use web3.py for block chain ethernet development of the detailed explanation.

C # Ethernet Square, mainly explains how to use C # to develop .net-based Ethernet Square applications, including account management, status and transactions, intelligent contract development and interaction, filters and transactions, etc.

EOS introduction course, this course helps you quickly get started with the development of EOS block chain decentralized applications, covering core knowledge points such as EOS tool chain, accounts and wallets, issuing tokens, smart contract development and deployment, using code and intelligent contract interaction, and finally using all knowledge points to complete the development of a note DApp.

The above is how to use JavaScript to write your own bitcoin transaction code, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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