Bitcoin Core :: getbalance ( RPC)

Category: Tiendas Virtuales

bitcoin getbalance

API Support & Discussion for the GetBalance API by bips. Sign Up Today for Free on RapidAPI! We will use the full node that we installed then to setup a Bitcoin wallet, receive and send bitcoins, and learn how to explore bitcoin-cli getbalance getbalance returns the balance of an account, not an address. conwaytransport.com.au​wiki/Original_Bitcoin_client/API_calls_list. If there's no account by the name of.

Remarkable, the: Bitcoin getbalance

Bitcoin getbalance Achat bitcoin montreal
YOGI MOTO CENTER BTC 349
Bitcoin getbalance
Btc ya b.ed 886
Bitcoin getbalance Bitcoin wallet lock

Mastering Bitcoin by

Chapter 3. The Bitcoin Client

Bitcoin Core: The Reference Implementation

You can download the reference client Bitcoin Core, also known as the “Satoshi client,” from conwaytransport.com.au The reference client implements all aspects of the bitcoin system, including wallets, a transaction verification engine with a full copy of the entire transaction ledger (blockchain), and a full network node in the peer-to-peer bitcoin network.

OnBitcoin’s Choose Your Wallet page, select Bitcoin Core to download the reference client. Depending on your operating system, you will download an executable installer. For Windows, this is either a ZIP archive or an .exe executable. For Mac OS it is a .dmg disk image. Linux versions include a PPA package for Ubuntu or a conwaytransport.com.au archive. The conwaytransport.com.au page that lists recommended bitcoin clients is shown in Figure 

Figure  Choosing a bitcoin client at conwaytransport.com.au

Running Bitcoin Core for the First Time

If you download an installable package, such as an .exe, .dmg, or PPA, you can install it the same way as any application on your operating system. For Windows, run the .exe and follow the step-by-step instructions. For Mac OS, launch the .dmg and drag the Bitcoin-QT icon into your Applications folder. For Ubuntu, double-click the PPA in your File Explorer and it will open the package manager to install the package. Once you have completed installation you should have a new application called Bitcoin-Qt in your application list. Double-click the icon to start the bitcoin client.

The first time you run Bitcoin Core it will start downloading the blockchain, a process that might take several days (see Figure ). Leave it running in the background until it displays “Synchronized” and no longer shows “out of sync” next to the balance.

Figure  Bitcoin Core screen during the blockchain initialization

Tip

Bitcoin Core keeps a full copy of the transaction ledger (blockchain), with every transaction that has ever occurred on the bitcoin network since its inception in This dataset is several gigabytes in size (approximately 16 GB in late ) and is downloaded incrementally over several days. The client will not be able to process transactions or update account balances until the full blockchain dataset is downloaded. During that time, the client will display “out of sync” next to the account balances and show “Synchronizing” in the footer. Make sure you have enough disk space, bandwidth, and time to complete the initial synchronization.

Compiling Bitcoin Core from the Source Code

For developers, there is also the option to download the full source code as a ZIP archive or by cloning the authoritative source repository from GitHub. On the GitHub bitcoin page, select Download ZIP from the sidebar. Alternatively, use the git command line to create a local copy of the source code on your system. In the following example, we are cloning the source code from a Unix-like command line, in Linux or Mac OS:

$ git clone conwaytransport.com.au Cloning into 'bitcoin' remote: Counting objects: , done. remote: Compressing objects: % (/), done. remote: Total (delta ), reused (delta ) Receiving objects: % (/), MiB | KiB/s, done. Resolving deltas: % (/), done. $

Tip

The instructions and resulting output might vary from version to version. Follow the documentation that comes with the code even if it differs from the instructions you see here, and don’t be surprised if the output displayed on your screen is slightly different from the examples here.

When the git cloning operation has completed, you will have a complete local copy of the source code repository in the directory bitcoin. Change to this directory by typing at the prompt:

$ cd bitcoin

By default, the local copy will be synchronized with the most recent code, which might be an unstable or beta version of bitcoin. Before compiling the code, select a specific version by checking out a release tag. This will synchronize the local copy with a specific snapshot of the code repository identified by a keyword tag. Tags are used by the developers to mark specific releases of the code by version number. First, to find the available tags, we use the command:

$ git tag v vtest1 v v v v [ many more tags ] vrc2 v v vrc1 vrc1

The list of tags shows all the released versions of bitcoin. By convention,release candidates, which are intended for testing, have the suffix “rc”. Stable releases that can be run on production systems have no suffix. From the preceding list, select the highest version release, which at this writing was vrc1. To synchronize the local code with this version, use the command:

$ git checkout vrc1 Note: checking out 'vrc1'. HEAD is now at 15ec Merge pull request # $

The source code includes documentation, which can be found in a number of files. Review the main documentation located in conwaytransport.com.au in the bitcoin directory by typing at the prompt and using the space bar to progress to the next page. In this chapter, we will build the command-line bitcoin client, also known as on Linux. Review the instructions for compiling the bitcoind command-line client on your platform by typing . Alternative instructions for Mac OS X and Windows can be found in the doc directory, as conwaytransport.com.au or conwaytransport.com.au, respectively.

Carefully review the build prerequisites, which are in the first part of the build documentation. These are libraries that must be present on your system before you can begin to compile bitcoin. If these prerequisites are missing, the build process will fail with an error. If this happens because you missed a prerequisite, you can install it and then resume the build process from where you left off. Assuming the prerequisites are installed, you start the build process by generating a set of build scripts using the conwaytransport.com.au script.

Tip

The Bitcoin Core build process was changed to use the autogen/configure/make system starting with version Older versions use a simple Makefile and work slightly differently from the following example. Follow the instructions for the version you want to compile. The autogen/configure/make introduced in is likely to be the build system used for all future versions of the code and is the system demonstrated in the following examples.

$ ./conwaytransport.com.au conwaytransport.com.au installing `src/build-aux/conwaytransport.com.au' conwaytransport.com.au installing `src/build-aux/conwaytransport.com.au' conwaytransport.com.au installing `src/build-aux/install-sh' conwaytransport.com.au installing `src/build-aux/missing' src/conwaytransport.com.au: installing `src/build-aux/depcomp' $

The conwaytransport.com.au script creates a set of automatic configuration scripts that will interrogate your system to discover the correct settings and ensure you have all the necessary libraries to compile the code. The most important of these is the script that offers a number of different options to customize the build process. Type to see the various options:

$ ./configure --help `configure' configures Bitcoin Core to adapt to many kinds of systems. Usage: ./configure [OPTION] [VAR=VALUE] To assign environment variables (e.g., CC, CFLAGS), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit [ many more options and variables are displayed below ] Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] [ more options ] Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to <info@conwaytransport.com.au>. $

The script allows you to enable or disable certain features of bitcoind through the use of the and flags, where is replaced by the feature name, as listed in the help output. In this chapter, we will build the bitcoind client with all the default features. We won’t be using the configuration flags, but you should review them to understand what optional features are part of the client. Next, run the script to automatically discover all the necessary libraries and create a customized build script for your system:

$ ./configure checking build system type x86_unknown-linux-gnu checking host system type x86_unknown-linux-gnu checking for a BSD-compatible install /usr/bin/install -c checking whether build environment is sane yes checking for a thread-safe mkdir -p /bin/mkdir -p checking for gawk no checking for mawk mawk checking whether make sets $(MAKE) yes [ many more system features are tested ] configure: creating ./conwaytransport.com.au conwaytransport.com.au: creating Makefile conwaytransport.com.au: creating src/Makefile conwaytransport.com.au: creating src/test/Makefile conwaytransport.com.au: creating src/qt/Makefile conwaytransport.com.au: creating src/qt/test/Makefile conwaytransport.com.au: creating share/conwaytransport.com.au conwaytransport.com.au: creating share/qt/conwaytransport.com.au conwaytransport.com.au: creating qa/pull-tester/conwaytransport.com.au conwaytransport.com.au: creating qa/pull-tester/conwaytransport.com.au conwaytransport.com.au: creating src/bitcoin-config.h conwaytransport.com.au: executing depfiles commands $

If all goes well, the command will end by creating the customized build scripts that will allow us to compile bitcoind. If there are any missing libraries or errors, the command will terminate with an error instead of creating the build scripts. If an error occurs, it is most likely because of a missing or incompatible library. Review the build documentation again and make sure you install the missing prerequisites. Then run again and see if that fixes the error. Next, you will compile the source code, a process that can take up to an hour to complete. During the compilation process you should see output every few seconds or every few minutes, or an error if something goes wrong. The compilation process can be resumed at any time if interrupted. Type to start compiling:

$ make Making all in src make[1]: Entering directory `/home/ubuntu/bitcoin/src' make all-recursive make[2]: Entering directory `/home/ubuntu/bitcoin/src' Making all in . make[3]: Entering directory `/home/ubuntu/bitcoin/src' CXX addrman.o CXX alert.o CXX rpcserver.o CXX bloom.o CXX chainparams.o [ many more compilation messages follow ] CXX test_bitcoin-wallet_tests.o CXX test_bitcoin-rpc_wallet_tests.o CXXLD test_bitcoin make[4]: Leaving directory `/home/ubuntu/bitcoin/src/test' make[3]: Leaving directory `/home/ubuntu/bitcoin/src/test' make[2]: Leaving directory `/home/ubuntu/bitcoin/src' make[1]: Leaving directory `/home/ubuntu/bitcoin/src' make[1]: Entering directory `/home/ubuntu/bitcoin' make[1]: Nothing to be done for `all-am'. make[1]: Leaving directory `/home/ubuntu/bitcoin' $

If all goes well, bitcoind is now compiled. The final step is to install the bitcoind executable into the system path using the command:

$ sudo make install Making install in src Making install in . /bin/mkdir -p '/usr/local/bin' /usr/bin/install -c bitcoind bitcoin-cli '/usr/local/bin' Making install in test make install-am /bin/mkdir -p '/usr/local/bin' /usr/bin/install -c test_bitcoin '/usr/local/bin' $

You can confirm that bitcoin is correctly installed by asking the system for the path of the two executables, as follows:

which bitcoind /usr/local/bin/bitcoind which bitcoin-cli /usr/local/bin/bitcoin-cli

The default installation of bitcoind puts it in /usr/local/bin. When you first run bitcoind, it will remind you to create a configuration file with a strong password for the JSON-RPC interface. Run bitcoind by typing into the terminal:

$ bitcoind Error: To use the "-server" option, you must set a rpcpassword in the configuration file: /home/ubuntu/.bitcoin/conwaytransport.com.au It is recommended you use the following random password: rpcuser=bitcoinrpc rpcpassword=2XA4DuKNCbtZXsBQRRNDEwEY2nM6M4H9Tx5dFjoAVVbK (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %s | mail -s "Bitcoin Alert" admin@conwaytransport.com.au

Edit the configuration file in your preferred editor and set the parameters, replacing the password with a strong password as recommended by bitcoind. Do not use the password shown here. Create a file inside the .bitcoin directory so that it is named .bitcoin/conwaytransport.com.au and enter a username and password:

While you’re editing this configuration file, you might want to set a few other options, such as (see Transaction Database Index and txindex Option). For a full listing of the available options, type .

Now, run the Bitcoin Core client. The first time you run it, it will rebuild the bitcoin blockchain by downloading all the blocks. This is a multigigabyte file and will take an average of two days to download in full. You can shorten the blockchain initialization time by downloading a partial copy of the blockchain using a BitTorrent client from SourceForge.

Run bitcoind in the background with the option :

$ bitcoind -daemon Bitcoin version vrc1-beta ( +) Using OpenSSL version OpenSSL c 10 May Default data directory /home/bitcoin/.bitcoin Using data directory /bitcoin/ Using at most 4 connections ( file descriptors available) init message: Verifying wallet conwaytransport.com.au LogDir=/bitcoin/database ErrorFile=/bitcoin/conwaytransport.com.au Bound to [::] Bound to init message: Loading block index Opening LevelDB in /bitcoin/blocks/index Opened LevelDB successfully Opening LevelDB in /bitcoin/chainstate Opened LevelDB successfully [ more startup messages ]

Using Bitcoin Core’s JSON-RPC API from the Command Line

The Bitcoin Core client implements a JSON-RPC interface that can also be accessed using the command-line helper . The command line allows us to experiment interactively with the capabilities that are also available programmatically via the API. To start, invoke the command to see a list of the available bitcoin RPC commands:

$ bitcoin-cli help addmultisigaddress nrequired ["key",] ( "account" ) addnode "node" "add|remove|onetry" backupwallet "destination" createmultisig nrequired ["key",] createrawtransaction [{"txid":"id","vout":n},] {"address":amount,] ) lockunspent unlock [{"txid":"txid","vout":n},] move "fromaccount" "toaccount" amount ( minconf "comment" ) ping sendfrom "fromaccount" "tobitcoinaddress" amount ( minconf "comment" "comment-to" ) sendmany "fromaccount" {"address":amount,} ( minconf "comment" ) sendrawtransaction "hexstring" ( allowhighfees ) sendtoaddress "bitcoinaddress" amount ( "comment" "comment-to" ) setaccount "bitcoinaddress" "account" setgenerate generate ( genproclimit ) settxfee amount signmessage "bitcoinaddress" "message" signrawtransaction "hexstring" ( [{"txid":"id","vout":n,"scriptPubKey":"hex","redeemScript":"hex"},] ["privatekey1",] sighashtype ) stop submitblock "hexdata" ( "jsonparametersobject" ) validateaddress "bitcoinaddress" verifychain ( checklevel numblocks ) verifymessage "bitcoinaddress" "signature" "message" walletlock walletpassphrase "passphrase" timeout walletpassphrasechange "oldpassphrase" "newpassphrase"

Getting Information on the Bitcoin Core Client Status

Commands:

Bitcoin’s RPC command displays basic information about the status of the bitcoin network node, the wallet, and the blockchain database. Use to run it:

bitcoin-cli getinfo

The data is returned in JavaScript Object Notation (JSON), a format that can easily be “consumed” by all programming languages but is also quite human-readable. Among this data we see the version numbers for the bitcoin software client (), protocol (), and wallet (). We see the current balance contained in the wallet, which is zero. We see the current block height, showing us how many blocks are known to this client (). We also see various statistics about the bitcoin network and the settings related to this client. We will explore these settings in more detail in the rest of this chapter.

Tip

It will take some time, perhaps more than a day, for the bitcoind client to “catch up” to the current blockchain height as it downloads blocks from other bitcoin clients. You can check its progress using to see the number of known blocks.

Wallet Setup and Encryption

Commands: ,

Before you proceed with creating keys and other commands, you should first encrypt the wallet with a password. For this example, you will use the command with the password “foo”. Obviously, replace “foo” with a strong and complex password!

$ bitcoin-cli encryptwallet foo wallet encrypted; Bitcoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup. $

You can verify the wallet has been encrypted by running again. This time you will notice a new entry called . This is a counter showing how long the wallet decryption password will be stored in memory, keeping the wallet unlocked. At first this will be set to zero, meaning the wallet is locked:

bitcoin-cli getinfo

To unlock the wallet, issue the command, which takes two parameters—the password and a number of seconds until the wallet is locked again automatically (a time counter):

$ bitcoin-cli walletpassphrase foo $

You can confirm the wallet is unlocked and see the timeout by running again:

bitcoin-cli getinfo

Wallet Backup, Plain-text Dump, and Restore

Commands: , ,

Next, we will practice creating a wallet backup file and then restoring the wallet from the backup file. Use the command to back up, providing the filename as the parameter. Here we back up the wallet to the file conwaytransport.com.au:

$ bitcoin-cli backupwallet conwaytransport.com.au $

Now, to restore the backup file, use the command. If your wallet is locked, you will need to unlock it first (see in the preceding section) in order to import the backup file:

$ bitcoin-cli importwallet conwaytransport.com.au $

The command can be used to dump the wallet into a text file that is human-readable:

$ bitcoin-cli dumpwallet conwaytransport.com.au $ more conwaytransport.com.au # Wallet dump created by Bitcoin vrc1-beta ( +) # * Created on 8dTZ # * Best block at time of backup was (f74f0bc9d3cbc45c7b91c49aac24c0d3a44), # mined on 8dTZ KzTg2wn6Z8s7ai5NA9MVX4vstHRsqP26QKJCzLg4JvFrp6mMaGB9 4dTZ change=1 # addr=16pJ6XkwSQv5ma5FSXMRPaXEYrENCEg47F Kz3dVz7R6mUpXzdZy4gJEVZxXJwA15feVui4CUivXotzLBDKY 4dTZ change=1 # addr=17oJds8kaN8LP8kuAkWTco6ZM7BGXFC3gk [ many more keys ] $

Wallet Addresses and Receiving Transactions

Commands: getnewaddress, getreceivedbyaddress, listtransactions, getaddressesbyaccount, getbalance

The bitcoin reference client maintains a pool of addresses, the size of which is displayed by when you use the command . These addresses are generated automatically and can then be used as public receiving addresses or change addresses. To get one of these addresses, use the command:

$ bitcoin-cli getnewaddress 1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL

Now, we can use this address to send a small amount of bitcoin to our bitcoind wallet from an external wallet (assuming you have some bitcoin in an exchange, web wallet, or other bitcoind wallet held elsewhere). For this example, we will send 50 millibits ( bitcoin) to the preceding address.

We can now query the bitcoind client for the amount received by this address, and specify how many confirmations are required before an amount is counted in that balance. For this example, we will specify zero confirmations. A few seconds after sending the bitcoin from another wallet, we will see it reflected in the wallet. We use with the address and the number of confirmations set to zero (0):

$ bitcoin-cli getreceivedbyaddress 1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL 0

If we omit the zero from the end of this command, we will only see the amounts that have at least confirmations, where is the setting for the minimum number of confirmations before a transaction is listed in the balance. The setting is specified in the bitcoind configuration file. Because the transaction sending this bitcoin was only sent in the last few seconds, it has still not confirmed and therefore we will see it list a zero balance:

$ bitcoin-cli getreceivedbyaddress 1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL

The transactions received by the entire wallet can also be displayed using the command:

$ bitcoin-cli listtransactions

We can list all addresses in the entire wallet using the command:

$ bitcoin-cli getaddressesbyaccount ""

Finally, the command will show the total balance of the wallet, adding up all transactions confirmed with at least confirmations:

$ bitcoin-cli getbalance

Tip

If the transaction has not yet confirmed, the balance returned by will be zero. The configuration option “minconf” determines the minimum number of confirmations that are required before a transaction shows in the balance.

Exploring and Decoding Transactions

Commands: , ,

We’ll now explore the incoming transaction that was listed previously using the command. We can retrieve a transaction by its transaction hash, shown at earlier, with the command:

$ bitcoin-cli gettransaction 9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3

Tip

Transaction IDs are not authoritative until a transaction has been confirmed. Absence of a transaction hash in the blockchain does not mean the transaction was not processed. This is known as “transaction malleability,” because transaction hashes can be modified prior to confirmation in a block. After confirmation, the txid is immutable and authoritative.

The transaction form shown with the command is the simplified form. To retrieve the full transaction code and decode it, we will use two commands: and . First, takes the transaction hash (txid) as a parameter and returns the full transaction as a “raw” hex string, exactly as it exists on the bitcoin network:

$ bitcoin-cli getrawtransaction 9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14aedf88e2f56ce4e8a31e2ae3e9f00ba1d0adde80cea22e0c7dba4ebbeecdedeadbbde7da3dc8b8e12e61a2df0ddebefe9ef7cf70ffaf1f2cbd34c5b9b2ac1bddfbaac8a58eafe39aad2ecc14daa44fabe58ede65e4c4bac5b5b6dede05bae34c8fd3ee1dd7a44b6ed41cc79e05dbfe5ceaffffffffb4cabdbfa2efdcfc9c13d1fdac1fabbc8dd66d09bac

To decode this hex string, use the command. Copy and paste the hex as the first parameter of to get the full contents interpreted as a JSON data structure (for formatting reasons the hex string is shortened in the following example):

$ bitcoin-cli decoderawtransaction dac, "n" : 0, "scriptPubKey" : { "asm" : "OP_DUP OP_HASH 07bdbfa2efdcfc9c13d1fd2 OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76abdbfa2efdcfc9c13d1fdac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL" ] } }, { "value" : , "n" : 1, "scriptPubKey" : { "asm" : "OP_DUP OP_HASH bbc8dd66d09b OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76abbc8dd66d09bac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "12W9goQ3P7Waw5JH8fRVs1e2rVAKoGnvoy" ] } } ] }

The transaction decode shows all the components of this transaction, including the transaction inputs and outputs. In this case we see that the transaction that credited our new address with 50 millibits used one input and generated two outputs. The input to this transaction was the output from a previously confirmed transaction (shown as the vin txid starting with ). The two outputs correspond to the 50 millibit credit and an output with change back to the sender.

We can further explore the blockchain by examining the previous transaction referenced by its txid in this transaction using the same commands (e.g., ). Jumping from transaction to transaction we can follow a chain of transactions back as the coins are transmitted from owner address to owner address.

Once the transaction we received has been confirmed by inclusion in a block, the command will return additional information, showing the block hash (identifier) in which the transaction was included:

$ bitcoin-cli gettransaction 9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3 { "amount" : , "confirmations" : 1, "blockhash" : "d2ec63a26efecbed7abc31c2ab", "blockindex" : 18, "blocktime" : , "txid" : "9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3", "time" : , "timereceived" : , "details" : [ { "account" : "", "address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "category" : "receive", "amount" : } ] }

Here, we see the new information in the entries (the hash of the block in which the transaction was included), and with value 18 (indicating that our transaction was the 18th transaction in that block).

Commands: ,

Now that we know which block our transaction was included in, we can query that block. We use the command with the block hash as the parameter:

$ bitcoin-cli getblock d2ec63a26efecbed7abc31c2ab true many more transactions ] ], "time" : , "nonce" : , "bits" : "f53", "difficulty" : , "chainwork" : "dfce", "previousblockhash" : "e61d5f6ba6be0dade9f39cb4d48bac77e7", "nextblockhash" : "d2c3bf7f4c68a4caea57da8fe0da92eb6"

The block contains transactions and as you can see, the 18th transaction listed () is the txid of the one crediting 50 millibits to our address. The entry tells us this is the th block in the blockchain.

We can also retrieve a block by its block height using the command, which takes the block height as the parameter and returns the block hash for that block:

$ bitcoin-cli getblockhash dcaeeffae46a2a6cb3f1b60a8ce26f

Here, we retrieve the block hash of the “genesis block,” the first block mined by Satoshi Nakamoto, at height zero. Retrieving this block shows:

$ bitcoin-cli getblock dcaeeffae46a2a6cb3f1b60a8ce26f { "hash" : "dcaeeffae46a2a6cb3f1b60a8ce26f", "confirmations" : , "size" : , "height" : 0, "version" : 1, "merkleroot" : "4a5e1e4baab89f3aa88c31bc87ffe2cc77abb7afdeda33b", "tx" : [ "4a5e1e4baab89f3aa88c31bc87ffe2cc77abb7afdeda33b" ], "time" : , "nonce" : , "bits" : "1d00ffff", "difficulty" : , "chainwork" : "", "nextblockhash" : "a8eabd76fafceebbf18eb" }

The , , and commands can be used to explore the blockchain database, programmatically.

Creating, Signing, and Submitting Transactions Based on Unspent Outputs

Commands: , , , , ,

Bitcoin’s transactions are based on the concept of spending “outputs,” which are the result of previous transactions, to create a transaction chain that transfers ownership from address to address. Our wallet has now received a transaction that assigned one such output to our address. Once this is confirmed, we can spend that output.

First, we use the command to show all the unspent confirmed outputs in our wallet:

$ bitcoin-cli listunspent [ { "txid" : "9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3", "vout" : 0, "address" : "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL", "account" : "", "scriptPubKey" : "76abdbfa2efdcfc9c13d1fdac", "amount" : , "confirmations" : 7 } ]

We see that the transaction created an output (with vout index 0) assigned to the address for the amount of 50 millibits, which at this point has received seven confirmations. Transactions use previously created outputs as their inputs by referring to them by the previous txid and vout index. We will now create a transaction that will spend the 0th vout of the txid as its input and assign it to a new output that sends value to a new address.

First, let’s look at the specific output in more detail. We use to get the details of this unspent output. Transaction outputs are always referenced by txid and vout, and these are the parameters we pass to :

$ bitcoin-cli gettxout 9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3 0 { "bestblock" : "ce69bd4ceebcdfdbcebe89deb37efd9", "confirmations" : 7, "value" : , "scriptPubKey" : { "asm" : "OP_DUP OP_HASH 07bdbfa2efdcfc9c13d1fd2 OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76abdbfa2efdcfc9c13d1fdac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL" ] }, "version" : 1, "coinbase" : false }

What we see here is the output that assigned 50 millibits to our address . To spend this output we will create a new transaction. First, let’s make an address to which we will send the money:

$ bitcoin-cli getnewaddress 1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb

We will send 25 millibits to the new address we just created in our wallet. In our new transaction, we will spend the 50 millibit output and send 25 millibits to this new address. Because we have to spend the whole output from the previous transaction, we must also generate some change. We will generate change back to the address, sending the change back to the address from which the value originated. Finally, we will also have to pay a fee for this transaction. To pay the fee, we will reduce the change output by millibits, and return millibits in change. The difference between the sum of the new outputs (25 mBTC + mBTC = mBTC) and the input (50 mBTC) will be collected as a transaction fee by the miners.

We use to create this transaction. As parameters to we provide the transaction input (the 50 millibit unspent output from our confirmed transaction) and the two transaction outputs (money sent to the new address and change sent back to the previous address):

$ bitcoin-cli createrawtransaction '[{"txid" : "9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3", "vout" : 0}]' '{"1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb": , "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL": }' e34ac1e2baac09cfce1cbda8f7db0faecf53ebd69f9a89cffffffff02aad90d36e98fd2bc9bbdaa9bcf88acabdbfa2efdcfc9c13d1fdac

The command produces a raw hex string that encodes the transaction details we supplied. Let’s confirm everything is correct by decoding this raw string using the command:

$ bitcoin-cli decoderawtransaction e34ac1e2baac09cfce1cbda8f7db0faecf53ebd69f9a89cffffffff02aad90d36e98fd2bc9bbdaa9bcf88acabdbfa2efdcfc9c13d1fdac { "txid" : "cba8d24eecaa1c30fcb5bae3fc05d4f3cba", "version" : 1, "locktime" : 0, "vin" : [ { "txid" : "9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3", "vout" : 0, "scriptSig" : { "asm" : "", "hex" : "" }, "sequence" : } ], "vout" : [ { "value" : , "n" : 0, "scriptPubKey" : { "asm" : "OP_DUP OP_HASH d90d36e98fd2bc9bbdaa9bcf OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76ad90d36e98fd2bc9bbdaa9bcf88ac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb" ] } }, { "value" : , "n" : 1, "scriptPubKey" : { "asm" : "OP_DUP OP_HASH 07bdbfa2efdcfc9c13d1fd2 OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76abdbfa2efdcfc9c13d1fdac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL" ] } } ] }

That looks correct! Our new transaction “consumes” the unspent output from our confirmed transaction and then spends it in two outputs, one for 25 millibits to our new address and one for millibits as change back to the original address. The difference of millibits represents the transaction fee and will be credited to the miner who finds the block that includes our transaction.

As you might notice, the transaction contains an empty because we haven’t signed it yet. Without a signature, this transaction is meaningless; we haven’t yet proven that we own the address from which the unspent output is sourced. By signing, we remove the encumbrance on the output and prove that we own this output and can spend it. We use the command to sign the transaction. It takes the raw transaction hex string as the parameter:

Tip

An encrypted wallet must be unlocked before a transaction is signed because signing requires access to the secret keys in the wallet.

$ bitcoin-cli walletpassphrase foo $ bitcoin-cli signrawtransaction e34ac1e2baac09cfce1cbda8f7db0faecf53ebd69f9a89cffffffff02aad90d36e98fd2bc9bbdaa9bcf88acabdbfa2efdcfc9c13d1fdac { "hex" : "e34ac1e2baac09cfce1cbda8f7db0faecf53ebd69f9a89cae8ada80cef66bacfbc0cc6d52c4a26d1d86a54e0a1b76dfcff2a8fb2bc5bca52f2d7a7f87eaef54be4afacfc4afaa8bed88ad8a0cac1d3f00fd44ea6c71dcffffffff02aad90d36e98fd2bc9bbdaa9bcf88acabdbfa2efdcfc9c13d1fdac", "complete" : true }

The command returns another hex-encoded raw transaction. We decode it to see what changed, with :

$ bitcoin-cli decoderawtransactione34ac1e2baac09cfce1cbda8f7db0faecf53ebd69f9a89cae8ada80cef66bacfbc0cc6d52c4a26d1d86a54e0a1b76dfcff2a8fb2bc5bca52f2d7a7f87eaef54be4afacfc4afaa8bed88ad8a0cac1d3f00fd44ea6c71dcffffffff02aad90d36e98fd2bc9bbdaa9bcf88acabdbfa2efdcfc9c13d1fdac { "txid" : "aebaafbad5d84f36ae9fdffac17b", "version" : 1, "locktime" : 0, "vin" : [ { "txid" : "9ca8fbd3ef5ec2afdbf7a8bdc2e1fc66cacbae2c14ae3", "vout" : 0, "scriptSig" : { "asm" : "e8ada80cef66bacfbc0cc6d52c4a26d1d86a54e0a1b76dfcff2a8fb2bc5bca52f2d7a7f87eaef54be4afa 03cfc4afaa8bed88ad8a0cac1d3f00fd44ea6c71dc", "hex" : "e8ada80cef66bacfbc0cc6d52c4a26d1d86a54e0a1b76dfcff2a8fb2bc5bca52f2d7a7f87eaef54be4afacfc4afaa8bed88ad8a0cac1d3f00fd44ea6c71dc" }, "sequence" : } ], "vout" : [ { "value" : , "n" : 0, "scriptPubKey" : { "asm" : "OP_DUP OP_HASH d90d36e98fd2bc9bbdaa9bcf OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76ad90d36e98fd2bc9bbdaa9bcf88ac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "1LnfTndy3qzXGN19Jwscj1T8LR3MVe3JDb" ] } }, { "value" : , "n" : 1, "scriptPubKey" : { "asm" : "OP_DUP OP_HASH 07bdbfa2efdcfc9c13d1fd2 OP_EQUALVERIFY OP_CHECKSIG", "hex" : "76abdbfa2efdcfc9c13d1fdac", "reqSigs" : 1, "type" : "pubkeyhash", "addresses" : [ "1hvzSofGwT8cjb8JU7nBsCSfEVQX5u9CL" ] } } ] }

Now, the inputs used in the transaction contain a , which is a digital signature proving ownership of address and removing the encumbrance on the output so that it can be spent. The signature makes this transaction verifiable by any node in the bitcoin network.

Now it’s time to submit the newly created transaction to the network. We do that with the command , which takes the raw hex string produced by . This is the same string we just decoded:

$ bitcoin-cli sendrawtransactione34ac1e2baac09cfce1cbda8f7db0faecf53ebd69f9a89cae8ada80cef66bacfbc0cc6d52c4a26d1d86a54e0a1b76dfcff2a8fb2bc5bca52f2d7a7f87eaef54be4afacfc4afaa8bed88ad8a0cac1d3f00fd44ea6c71dcffffffff02aad90d36e98fd2bc9bbdaa9bcf88acabdbfa2efdcfc9c13d1fdacaebaafbad5d84f36ae9fdffac17b

The command returns a transaction hash (txid) as it submits the transaction on the network. We can now query that transaction ID with :

$ bitcoin-cli gettransaction aebaafbad5d84f36ae9fdffac17b

As before, we can also examine this in more detail using the and commands. These commands will return the exact same hex string that we produced and decoded previously just before we sent it on the network.

Alternative Clients, Libraries, and Toolkits

Beyond the reference client (bitcoind), other clients and libraries can be used to interact with the bitcoin network and data structures. These are implemented in a variety of programming languages, offering programmers native interfaces in their own language.

Alternative implementations include:

Many more libraries exist in a variety of other programming languages and more are created all the time.

The libbitcoin library is a C++ scalable multithreaded and modular implementation that supports a full-node client and a command-line toolset called sx, which offers many of the same capabilities as the bitcoind client commands we illustrated in this chapter. The sx tools also offer some key management and manipulation tools that are not offered by bitcoind, including type-2 deterministic keys and key mnemonics.

To install sx and the supporting library libbitcoin, download and run the online installer on a Linux system:

wget conwaytransport.com.au sudo bash ./conwaytransport.com.au

You should now have the sx tools installed. Type with no parameters to display the help text, which lists all the available commands (see Appendix D).

Tip

The sx toolkit offers many useful commands for encoding and decoding addresses, and converting to and from different formats and representations. Use them to explore the various formats such as Base58, Base58Check, hex, etc.

The Python library pycoin, originally written and maintained by Richard Kiss, is a Python-based library that supports manipulation of bitcoin keys and transactions, even supporting the scripting language enough to properly deal with nonstandard transactions.

The pycoin library supports both Python 2 (x) and Python 3 (after ), and comes with some handy command-line utilities, ku and tx. To install pycoin under Python 3 in a virtual environment (venv), use the following:

$ python3 -m venv /tmp/pycoin $ . /tmp/pycoin/bin/activate $ pip install pycoin== Downloading/unpacking pycoin== Downloading conwaytransport.com.au (66kB): 66kB downloaded Running conwaytransport.com.au (path:/tmp/pycoin/build/pycoin/conwaytransport.com.au) egg_info for package pycoin Installing collected packages: pycoin Running conwaytransport.com.au install for pycoin Installing tx script to /tmp/pycoin/bin Installing cache_tx script to /tmp/pycoin/bin Installing bu script to /tmp/pycoin/bin Installing fetch_unspent script to /tmp/pycoin/bin Installing block script to /tmp/pycoin/bin Installing spend script to /tmp/pycoin/bin Installing ku script to /tmp/pycoin/bin Installing genwallet script to /tmp/pycoin/bin Successfully installed pycoin Cleaning up $

Here’s a sample Python script to fetch and spend some bitcoin using the pycoin library:

For examples using the command-line utilities ku and tx, see Appendix B.

btcd is a full-node bitcoin implementation written in Go. It currently downloads, validates, and serves the blockchain using the exact rules (including bugs) for block acceptance as the reference implementation, bitcoind. It also properly relays newly mined blocks, maintains a transaction pool, and relays individual transactions that have not yet made it into a block. It ensures that all individual transactions admitted to the pool follow the rules required and also includes the vast majority of the more strict checks that filter transactions based on miner requirements (“standard” transactions).

One key difference between btcd and bitcoind is that btcd does not include wallet functionality, and this was a very intentional design decision. This means you can’t actually make or receive payments directly with btcd. That functionality is provided by the btcwallet and btcgui projects, which are both under active development. Other notable differences between btcd and bitcoind include btcd support for both HTTP POST requests (such as bitcoind) and the preferred Websockets, and the fact that btcd’s RPC connections are TLS-enabled by default.

To install btcd for Windows, download and run the msi available at GitHub, or run the following command on Linux, assuming you already have installed the Go language:

$ go get conwaytransport.com.au

To update btcd to the latest version, just run:

$ go get -u -v conwaytransport.com.au

btcd has a number of configuration options, which you can view by running:

btcd --help

btcd comes prepackaged with some goodies such as btcctl, which is a command-line utility that can be used to both control and query btcd via RPC. btcd does not enable its RPC server by default; you must configure at minimum both an RPC username and password in the following configuration files:

Or if you want to override the configuration files from the command line:

btcd -u myuser -P SomeDecentp4ssw0rd btcctl -u myuser -P SomeDecentp4ssw0rd

For a list of available options, run the following:

$ btcctl --help
Источник: conwaytransport.com.au

By -

0 thoughts on “Bitcoin getbalance”

Leave a Reply

Your email address will not be published. Required fields are marked *