https://tests.bitcoin.it/w/api.php?action=feedcontributions&user=Danda&feedformat=atomBitcoin Wiki - User contributions [en]2024-03-29T11:28:22ZUser contributionsMediaWiki 1.30.0https://tests.bitcoin.it/w/index.php?title=PHP_developer_intro&diff=66653PHP developer intro2019-08-04T17:33:16Z<p>Danda: /* Alternative Libs For RPC */</p>
<hr />
<div>'''L'''inux '''A'''pache '''M'''ySQL '''P'''HP + Bitcoin tutorial.<br />
<br />
For this introduction we assume that you have GNU/Linux server with Apache and PHP and that you wish to interact with the Bitcoin network from a web application. We assume some knowledge of Bitcoin and experience in PHP.<br />
<br />
While this is written for PHP, the same principles apply for other languages. See the associated [[API reference (JSON-RPC)|API reference]] pages for info on other languages.<br />
<br />
The easiest way to get started is to run Bitcoin in daemon mode with which PHP communicates via local HTTP requests. A library called [http://jsonrpcphp.org/ JSON-RPC] is used to call the various functions of bitcoind, which will respond back with a [http://en.wikipedia.org/wiki/Json JSON object].<br />
<br />
It is however recommended to use one of the [[#Alternative_Libs_For_RPC|Alternative Libraries]] listed below instead, since they are more sophisticated.<br />
<br />
== Setting up Bitcoin ==<br />
<br />
You can download the Bitcoin daemon from the [[Main_Page|homepage]] and run one of the included binaries or compile your own from the included source code. See [[Running Bitcoin]] for details on configuring bitcoind.<br />
<br />
Before running bitcoind you will need to create a configuration file in the Bitcoin data directory (~/.bitcoin/bitcoin.conf on Linux):<br />
<source lang="bash"><br />
rpcuser=user<br />
rpcpassword={you MUST pick a unique password to be secure}<br />
</source><br />
If you miss this step, bitcoind will remind you.<br />
<br />
Now run bitcoind:<br />
<source lang="bash"><br />
$ ./bitcoind<br />
# wait a few seconds for it to start up<br />
$ ./bitcoin-cli getinfo<br />
# various information will be shown. If you get an error, try again until you see some useful output.<br />
$ ./bitcoin-cli help<br />
# get help on commands, note no dash before help<br />
</source><br />
<br />
Bitcoin will begin synchronizing with the network and downloading a complete copy of the block chain. As of August 2012, more than 2gb of data must be downloaded and verified during this process. It may take two or more hours to complete. You will know when it's done when the block count reaches the [http://blockexplorer.com/q/getblockcount current count].<br />
<br />
== Getinfo (Bitcoind's version of Hello World) ==<br />
<br />
Assuming Bitcoin has finished the initialisation process; download the file jsonRPCClient.php from [http://jsonrpcphp.org/ JSON-RPC PHP] and place it in a web-accessible location.<br />
<br />
Second, create a PHP file with the following and visit it with your browser to test.<br />
<br />
<source lang="php"><br />
require_once 'jsonRPCClient.php';<br />
<br />
$bitcoin = new jsonRPCClient('http://user:password@127.0.0.1:8332/');<br />
<br />
echo "<pre>\n";<br />
print_r($bitcoin->getinfo());<br />
echo "</pre>";<br />
</source><br />
<br />
'''Note:''' The jsonRPCClient library uses fopen() and will throw an exception saying "Unable to connect" if it receives a 404 or 500 error from bitcoind. This prevents you from being able to see error messages generated by bitcoind (as they are sent with status 404 or 500). The [[#Alternative_Libs_For_RPC|Alternative Libraries]] listed below are similar in function to JSON-RPC PHP but do not have this issue.<br />
<br />
== Precision ==<br />
<br />
Bitcoin amounts can range from 1 Satoshi (0.00000001 BTC) to nearly 2,100,000,000,000,000 (21,000,000 BTC). To avoid rounding errors, you must make sure your PHP implementation supports the full range of Bitcoin values without losing precision. Most PHP implementations use IEEE 64-bit double-precision floating point numbers with 53 bits of precision, which is enough to correctly represent the full range of bitcoin values.<br />
<br />
See [[Proper Money Handling (JSON-RPC)]] for more information.<br />
<br />
If your PHP implementation does not support 64-bit numbers (again, this is very rare), you must use a version of bitcoind that sends values as strings (genjix maintains a fork at http://github.com/genjix/bitcoin) and use the [http://php.net/manual/en/ref.gmp.php GMP] and [http://php.net/manual/en/ref.bc.php BC Math] libraries for all calculations involving bitcoin amounts.<br />
<br />
== Accounts ==<br />
<br />
In Bitcoin, money is sent to addresses and many addresses can be held by one wallet. The balance shown by default in bitcoind is the sum of the bitcoins in all the addresses in the wallet.<br />
<br />
Bitcoin goes another step. You can have [[Accounts explained|accounts]]. Each account holds multiple addresses and acts like a mini-bitcoind. <br />
<br />
<source lang="bash"><br />
$ ./bitcoin-cli listaccounts<br />
# show list of accounts and various info for each one<br />
$ ./bitcoin-cli getaccountaddress user889<br />
# get an address to receive money to that is unique for the account user889<br />
$ ./bitcoin-cli getbalance user889<br />
# get the sum of all the money in the addresses owned by the account user889<br />
</source><br />
<br />
In your application, each user should have a unique username. You may then query bitcoind for a unique address using $bitcoin->getaccountaddress("user889"); [gets the first address for user889] or $bitcoin->getnewaddress("user889"); [creates a new address for user889].<br />
<br />
The customer then deposits to this address.<br />
<br />
You can check the funds for that customer by doing $bitcoin->getbalance("user889", 4);. The 4 indicates the minimum number of confirmations we will accept before assuming this payment is valid.<br />
<br />
If you will be using accounts for multiple deposits and withdrawals long-term, you may want to consider tracking user balances in your own database. This simplifies transfers between your application's accounts and decouples your accounts from the Bitcoin wallet.<br />
<br />
=== getnewaddress vs getaccountaddress ===<br />
<br />
Using getnewaddress helps increase maintain anonymity of your users by making it hard for a malicious agent to track payments flowing through your application. Running getnewaddress too often, however, will cause your wallet to become filled with many empty addresses.<br />
<br />
It is therefore recommended to in some way limit the number of unfunded addresses each user can request. Here is an example using sessions:<br />
<source lang="php"><br />
<?php<br />
require_once('jsonRPCClient.php');<br />
$bitcoin = new jsonRPCClient('http://root:root@127.0.0.1:8332/'); <br />
# now check for appropriate funds in user account<br />
try {<br />
$username = ...<br />
if(isset($_SESSION['sendaddress']))<br />
$sendaddress = $_SESSION['sendaddress'];<br />
else {<br />
$sendaddress = $bitcoin->getnewaddress($username);<br />
$_SESSION['sendaddress'] = $sendaddress;<br />
}<br />
$balance = $bitcoin->getbalance($username);<br />
}<br />
catch (Exception $e) {<br />
die("<p>Server error! Please contact the admin.</p>");<br />
}<br />
?><br />
</source><br />
<br />
This creates a new address at the beginning of every new session, and stores it in the session variable.<br />
<br />
==Alternative Libs For RPC==<br />
There are alternative PHP libraries for connecting to the bitcoind RPC which are recommended over using the plain jsonRPCClient.php class.<br />
They do not rely on magic __call, use cURL instead of fopen and have better error handling (and can be installed using composer).<br />
<br />
* [https://github.com/nbobtc/bitcoind-php NboBTC Bitcoind-PHP]<br />
* [https://github.com/aceat64/EasyBitcoin-PHP EasyBitcoin-PHP]<br />
<br />
==Alternative CLI clients==<br />
<br />
* [https://github.com/dan-da/jsonrpc-cli jsonrpc-cli] provides simple jsonrpc queries from the command-line with highlighted json results (colors) and the ability to view/debug raw http requests and responses. It can also display json results in php print_r, var_dump, serialize formats as well as yaml.<br />
<br />
==See Also==<br />
<br />
* [[API reference (JSON-RPC)]]<br />
* [[Lazy_API]]<br />
* [https://github.com/cryptoapi/Payment-Gateway Bitcoin-PHP Payment library]<br />
* [[Merchant Howto]]<br />
* [[https://github.com/Bit-Wasp/bitcoin-lib-php Bitcoin-Lib-PHP - PHP Lib implementing signing of transactions, BIP32, etc]]<br />
<br />
[[es:Introducción para desarrolladores de PHP]]<br />
[[de:Einführung_für_PHP-Entwickler]]<br />
<br />
[[Category:Developer]]</div>Dandahttps://tests.bitcoin.it/w/index.php?title=API_reference_(JSON-RPC)&diff=66652API reference (JSON-RPC)2019-08-04T17:07:28Z<p>Danda: /* Command line (cURL) */</p>
<hr />
<div>== Controlling Bitcoin Core ==<br />
<br />
Run ''bitcoind'' or ''bitcoin-qt -server''. You can control it via the command-line bitcoin-cli utility or by [http://json-rpc.org/wiki/specification HTTP JSON-RPC] commands.<br />
<br />
You must create a bitcoin.conf configuration file setting an rpcuser and rpcpassword; see [[Running Bitcoin]] for details.<br />
<br />
Now run:<br />
$ ./bitcoind -daemon<br />
bitcoin server starting<br />
$ ./bitcoin-cli -rpcwait help<br />
# shows the help text<br />
<br />
A [[Original Bitcoin client/API Calls list|list of RPC calls]] will be shown.<br />
<br />
$ ./bitcoin-cli getbalance<br />
2000.00000<br />
<br />
If you are learning the API, it is a very good idea to use the test network (run bitcoind -testnet and bitcoin-cli -testnet).<br />
<br />
== JSON-RPC ==<br />
<br />
Running Bitcoin with the -server argument (or running bitcoind) tells it to function as a [http://json-rpc.org/wiki/specification HTTP JSON-RPC] server, but <br />
[http://en.wikipedia.org/wiki/Basic_access_authentication Basic access authentication] must be used when communicating with it, and, for security, by default, the server only accepts connections from other processes on the same machine. If your HTTP or JSON library requires you to specify which 'realm' is authenticated, use 'jsonrpc'.<br />
<br />
Bitcoin supports SSL (https) JSON-RPC connections beginning with version 0.3.14. See the [[Enabling SSL on original client daemon|rpcssl wiki page]] for setup instructions and a list of all bitcoin.conf configuration options.<br />
<br />
Allowing arbitrary machines to access the JSON-RPC port (using the rpcallowip [[Running_Bitcoin|configuration option]]) is dangerous and '''strongly discouraged'''-- access should be strictly limited to trusted machines.<br />
<br />
To access the server you should find a [http://json-rpc.org/wiki/implementations suitable library] for your language.<br />
<br />
== Proper money handling ==<br />
<br />
See the [[Proper Money Handling (JSON-RPC)|proper money handling page]] for notes on avoiding rounding errors when handling bitcoin values.<br />
<br />
== Languages ==<br />
<br />
=== Python ===<br />
<br />
[http://json-rpc.org/wiki/python-json-rpc python-jsonrpc] is the official JSON-RPC implementation for Python.<br />
It automatically generates Python methods for RPC calls.<br />
However, due to its design for supporting old versions of Python, it is also rather inefficient.<br />
[[User:jgarzik|jgarzik]] has forked it as [https://github.com/jgarzik/python-bitcoinrpc Python-BitcoinRPC] and optimized it for current versions.<br />
Generally, this version is recommended.<br />
<br />
While BitcoinRPC lacks a few obscure features from jsonrpc, software using only the ServiceProxy class can be written the same to work with either version the user might choose to install:<br />
<br />
<source lang="python"><br />
from jsonrpc import ServiceProxy<br />
<br />
access = ServiceProxy("http://user:password@127.0.0.1:8332")<br />
access.getinfo()<br />
access.listreceivedbyaddress(6)<br />
#access.sendtoaddress("11yEmxiMso2RsFVfBcCa616npBvGgxiBX", 10)<br />
</source><br />
<br />
The latest version of python-bitcoinrpc has a new syntax.<br />
<source lang="python"><br />
from bitcoinrpc.authproxy import AuthServiceProxy<br />
</source><br />
<br />
=== Ruby ===<br />
<br />
<source lang="ruby"><br />
require 'net/http'<br />
require 'uri'<br />
require 'json'<br />
<br />
class BitcoinRPC<br />
def initialize(service_url)<br />
@uri = URI.parse(service_url)<br />
end<br />
<br />
def method_missing(name, *args)<br />
post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json<br />
resp = JSON.parse( http_post_request(post_body) )<br />
raise JSONRPCError, resp['error'] if resp['error']<br />
resp['result']<br />
end<br />
<br />
def http_post_request(post_body)<br />
http = Net::HTTP.new(@uri.host, @uri.port)<br />
request = Net::HTTP::Post.new(@uri.request_uri)<br />
request.basic_auth @uri.user, @uri.password<br />
request.content_type = 'application/json'<br />
request.body = post_body<br />
http.request(request).body<br />
end<br />
<br />
class JSONRPCError < RuntimeError; end<br />
end<br />
<br />
if $0 == __FILE__<br />
h = BitcoinRPC.new('http://user:password@127.0.0.1:8332')<br />
p h.getbalance<br />
p h.getinfo<br />
p h.getnewaddress<br />
p h.dumpprivkey( h.getnewaddress )<br />
# also see: https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_Calls_list<br />
end<br />
</source><br />
<br />
=== Erlang ===<br />
Get the rebar dependency from https://github.com/edescourtis/ebitcoind . By default the client will use the configuration in <code>$HOME/.bitcoin/bitcoin.conf</code> or you can instead specify a URI like this:<br />
<source lang="erlang">ebitcoind:start_link(<<"http://user:password@localhost:8332/">>).</source><br />
<br />
Here is a usage example:<br />
<source lang="erlang"><br />
1> {ok,Pid} = ebitcoind:start_link().<br />
{ok,<0.177.0>}<br />
2> ebitcoind:getbalance(Pid).<br />
8437.02478294<br />
3> ebitcoind:getinfo(Pid).<br />
{ok, #{<<"balance">> => 8437.02478294,<br />
<<"blocks">> => 260404,<br />
<<"connections">> => 8,<br />
<<"difficulty">> => 148819199.80509263,<br />
<<"errors">> => <<>>,<br />
<<"keypoololdest">> => 1420307921,<br />
<<"keypoolsize">> => 102,<br />
<<"paytxfee">> => 0.0,<br />
<<"protocolversion">> => 70002,<br />
<<"proxy">> => <<>>,<br />
<<"relayfee">> => 1.0e-5,<br />
<<"testnet">> => false,<br />
<<"timeoffset">> => -3,<br />
<<"version">> => 90300,<br />
<<"walletversion">> => 60000}}<br />
4> ebitcoind:setgenerate(Pid,true).<br />
{ok, null}<br />
5> ebitcoind:getblocktemplate(Pid, #{}). <br />
{ok,#{<<"bits">> => <<"181b0dca">>,<br />
<<"coinbaseaux">> => #{<<"flags">> => <<"062f503253482f">>},<br />
<<"coinbasevalue">> => 2518690558,<br />
<<"curtime">> => 1420421249,<br />
<<"height">> => 337533,<br />
<<"mintime">> => 1420416332,<br />
<<"mutable">> => [<<"time">>,<<"transactions">>,<<"prevblock">>],<br />
<<"noncerange">> => <<"00000000ffffffff">>,<br />
<<"previousblockhash">> => <<"000000000000000017ce0a0d328bf84cc597785844393e899e9a971a81679a5f">>,<br />
<<"sigoplimit">> => 20000,<br />
<<"sizelimit">> => 1000000,<br />
<<"target">> => <<"00000000000000001b0dca00000000000000000000000000000000000000"...>>,<br />
<<"transactions">> => [#{<<"data">> => <<"01000000049b47ce225d29bff7c18b7df7d7df4693523a52"...>>,<br />
<<"depends">> => [],<br />
<<"fee">> => 0,<br />
<<"hash">> => <<"6d0d76e1f27b3a6f7325923710dcdb4107c9"...>>,<br />
<<"sigops">> => 1},<br />
...<br />
</source><br />
<br />
=== PHP ===<br />
<br />
The [http://jsonrpcphp.org/ JSON-RPC PHP] library also makes it very easy to connect to Bitcoin. For example:<br />
<br />
<source lang="php"><br />
require_once 'jsonRPCClient.php';<br />
<br />
$bitcoin = new jsonRPCClient('http://user:password@127.0.0.1:8332/');<br />
<br />
echo "<pre>\n";<br />
print_r($bitcoin->getinfo()); echo "\n";<br />
echo "Received: ".$bitcoin->getreceivedbylabel("Your Address")."\n";<br />
echo "</pre>";<br />
</source><br />
<br />
'''Note:''' The jsonRPCClient library uses fopen() and will throw an exception saying "Unable to connect" if it receives a 404 or 500 error from bitcoind. This prevents you from being able to see error messages generated by bitcoind (as they are sent with status 404 or 500). The [https://github.com/aceat64/EasyBitcoin-PHP EasyBitcoin-PHP library] is similar in function to JSON-RPC PHP but does not have this issue.<br />
<br />
=== Java ===<br />
<br />
The easiest way to tell Java to use HTTP Basic authentication is to set a default Authenticator:<br />
<br />
<source lang="java"><br />
final String rpcuser ="...";<br />
final String rpcpassword ="...";<br />
<br />
Authenticator.setDefault(new Authenticator() {<br />
protected PasswordAuthentication getPasswordAuthentication() {<br />
return new PasswordAuthentication (rpcuser, rpcpassword.toCharArray());<br />
}<br />
});<br />
</source><br />
<br />
Once that is done, [http://json-rpc.org/wiki/implementations any JSON-RPC library for Java] (or ordinary URL POSTs) may be used to communicate with the Bitcoin server.<br />
<br />
Instead of writing your own implementation, consider using one of the existing wrappers like [https://github.com/johannbarbie/BitcoindClient4J BitcoindClient4J], [https://github.com/priiduneemre/btcd-cli4j btcd-cli4j] or [[Bitcoin-JSON-RPC-Client|Bitcoin-JSON-RPC-Client]] instead.<br />
<br />
=== Perl ===<br />
<br />
The JSON::RPC package from CPAN can be used to communicate with Bitcoin. You must set the client's credentials; for example:<br />
<br />
<source lang="perl"><br />
use JSON::RPC::Client;<br />
use Data::Dumper;<br />
<br />
my $client = new JSON::RPC::Client;<br />
<br />
$client->ua->credentials(<br />
'localhost:8332', 'jsonrpc', 'user' => 'password' # REPLACE WITH YOUR bitcoin.conf rpcuser/rpcpassword<br />
);<br />
<br />
my $uri = 'http://localhost:8332/';<br />
my $obj = {<br />
method => 'getinfo',<br />
params => [],<br />
};<br />
<br />
my $res = $client->call( $uri, $obj );<br />
<br />
if ($res){<br />
if ($res->is_error) { print "Error : ", $res->error_message; }<br />
else { print Dumper($res->result); }<br />
} else {<br />
print $client->status_line;<br />
}<br />
</source><br />
<br />
=== Go ===<br />
<br />
The [https://github.com/btcsuite/btcrpcclient btcrpcclient package] can be used to communicate with Bitcoin. You must provide credentials to match the client you are communicating with.<br />
<br />
<source lang="go"><br />
package main<br />
<br />
import (<br />
"github.com/btcsuite/btcd/chaincfg"<br />
"github.com/btcsuite/btcrpcclient"<br />
"github.com/btcsuite/btcutil"<br />
"log"<br />
)<br />
<br />
func main() {<br />
// create new client instance<br />
client, err := btcrpcclient.New(&btcrpcclient.ConnConfig{<br />
HTTPPostMode: true,<br />
DisableTLS: true,<br />
Host: "127.0.0.1:8332",<br />
User: "rpcUsername",<br />
Pass: "rpcPassword",<br />
}, nil)<br />
if err != nil {<br />
log.Fatalf("error creating new btc client: %v", err)<br />
}<br />
<br />
// list accounts<br />
accounts, err := client.ListAccounts()<br />
if err != nil {<br />
log.Fatalf("error listing accounts: %v", err)<br />
}<br />
// iterate over accounts (map[string]btcutil.Amount) and write to stdout<br />
for label, amount := range accounts {<br />
log.Printf("%s: %s", label, amount)<br />
}<br />
<br />
// prepare a sendMany transaction<br />
receiver1, err := btcutil.DecodeAddress("1someAddressThatIsActuallyReal", &chaincfg.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver1 seems to be invalid: %v", err)<br />
}<br />
receiver2, err := btcutil.DecodeAddress("1anotherAddressThatsPrettyReal", &chaincfg.MainNetParams)<br />
if err != nil {<br />
log.Fatalf("address receiver2 seems to be invalid: %v", err)<br />
}<br />
receivers := map[btcutil.Address]btcutil.Amount{<br />
receiver1: 42, // 42 satoshi<br />
receiver2: 100, // 100 satoshi<br />
}<br />
<br />
// create and send the sendMany tx<br />
txSha, err := client.SendMany("some-account-label-from-which-to-send", receivers)<br />
if err != nil {<br />
log.Fatalf("error sendMany: %v", err)<br />
}<br />
log.Printf("sendMany completed! tx sha is: %s", txSha.String())<br />
}<br />
</source><br />
<br />
=== .NET (C#) ===<br />
The communication with the RPC service can be achieved using the standard http request/response objects.<br />
A library for serializing and deserializing Json will make your life a lot easier:<br />
<br />
Json.NET ( http://james.newtonking.com/json ) is a high performance JSON package for .NET. It is also available via NuGet from the package manager console ( Install-Package Newtonsoft.Json ).<br />
<br />
The following example uses Json.NET:<br />
<br />
<source lang="csharp"><br />
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost.:8332");<br />
webRequest.Credentials = new NetworkCredential("user", "pwd");<br />
/// important, otherwise the service can't desirialse your request properly<br />
webRequest.ContentType = "application/json-rpc";<br />
webRequest.Method = "POST";<br />
<br />
JObject joe = new JObject();<br />
joe.Add(new JProperty("jsonrpc", "1.0"));<br />
joe.Add(new JProperty("id", "1"));<br />
joe.Add(new JProperty("method", Method));<br />
// params is a collection values which the method requires..<br />
if (Params.Keys.Count == 0)<br />
{<br />
joe.Add(new JProperty("params", new JArray()));<br />
}<br />
else<br />
{<br />
JArray props = new JArray();<br />
// add the props in the reverse order!<br />
for (int i = Params.Keys.Count - 1; i >= 0; i--)<br />
{<br />
.... // add the params<br />
}<br />
joe.Add(new JProperty("params", props));<br />
}<br />
<br />
// serialize json for the request<br />
string s = JsonConvert.SerializeObject(joe);<br />
byte[] byteArray = Encoding.UTF8.GetBytes(s);<br />
webRequest.ContentLength = byteArray.Length;<br />
Stream dataStream = webRequest.GetRequestStream();<br />
dataStream.Write(byteArray, 0, byteArray.Length);<br />
dataStream.Close();<br />
<br />
<br />
WebResponse webResponse = webRequest.GetResponse();<br />
<br />
... // deserialze the response<br />
</source><br />
<br />
There is also a wrapper for Json.NET called Bitnet (https://sourceforge.net/projects/bitnet)<br />
implementing Bitcoin API in more convenient way:<br />
<br />
<source lang="csharp"><br />
BitnetClient bc = new BitnetClient("http://127.0.0.1:8332");<br />
bc.Credentials = new NetworkCredential("user", "pass");<br />
<br />
var p = bc.GetDifficulty();<br />
Console.WriteLine("Difficulty:" + p.ToString());<br />
<br />
var inf = bc.GetInfo();<br />
Console.WriteLine("Balance:" + inf["balance"]);<br />
</source><br />
<br />
A more complete library and wrapper for Bitcoin is [https://github.com/GeorgeKimionis/BitcoinLib BitcoinLib] (https://github.com/GeorgeKimionis/BitcoinLib) which is also available via [https://www.nuget.org/packages/BitcoinLib/ NuGet] from the package manager console (Install-Package BitcoinLib). <br />
<br />
Querying the daemon with [https://github.com/GeorgeKimionis/BitcoinLib BitcoinLib] is as simple as:<br />
<br />
<source lang="csharp"><br />
IBitcoinService bitcoinService = new BitcoinService();<br />
<br />
var networkDifficulty = bitcoinService.GetDifficulty();<br />
var myBalance = bitcoinService.GetBalance();<br />
</source><br />
<br />
=== Node.js ===<br />
<br />
* [https://github.com/ruimarinho/bitcoin-core bitcoin-core] (npm: [https://www.npmjs.com/package/bitcoin-core bitcoin-core]) <br />
<br />
Example using bitcoin-core:<br />
<br />
<source lang="javascript"><br />
const Client = require('bitcoin-core');<br />
const client = new Client({ <br />
network: 'regtest', <br />
username: 'user', <br />
password: 'pass', <br />
port: 18443 <br />
});<br />
<br />
client.getBlockchainInfo().then((help) => console.log(help));<br />
</source><br />
<br />
=== Command line (cURL) ===<br />
<br />
You can also send commands and see results using [http://curl.haxx.se/ cURL] or some other command-line HTTP-fetching utility; for example:<br />
<br />
<source lang="bash"><br />
curl --user user --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getinfo", "params": [] }' <br />
-H 'content-type: text/plain;' http://127.0.0.1:8332/<br />
</source><br />
<br />
You will be prompted for your rpcpassword, and then will see something like:<br />
<br />
<source lang="javascript"><br />
{"result":{"balance":0.000000000000000,"blocks":59952,"connections":48,"proxy":"","generate":false,<br />
"genproclimit":-1,"difficulty":16.61907875185736},"error":null,"id":"curltest"}<br />
</source><br />
<br />
=== Command line (jsonrpc-cli) ===<br />
<br />
[https://github.com/dan-da/jsonrpc-cli jsonrpc-cli] provides simple json queries from the command-line with highlighted json results (colors) and the ability to view/debug raw http requests and responses.<br />
<br />
<source lang="bash"><br />
jsonrpc-cli --user=rpcuser --pass=rpcpassword http://localhost:8332/ getinfo<br />
</source><br />
<br />
<source lang="javascript"><br />
{<br />
"version": 109900,<br />
"protocolversion": 70002,<br />
"walletversion": 60000,<br />
"balance": 0,<br />
"blocks": 588597,<br />
"timeoffset": -1,<br />
"connections": 9,<br />
"proxy": "127.0.0.1:9050",<br />
"difficulty": 9013786945891.682,<br />
"testnet": false,<br />
"keypoololdest": 1463279619,<br />
"keypoolsize": 101,<br />
"paytxfee": 0,<br />
"relayfee": 1.0e-5,<br />
"errors": null<br />
}<br />
</source><br />
<br />
=== Clojure ===<br />
<br />
[https://github.com/aviad/clj-btc clj-btc] is a Clojure wrapper for the bitcoin API.<br />
<br />
<source lang="clojure"><br />
user=> (require '[clj-btc.core :as btc])<br />
nil<br />
user=> (btc/getinfo)<br />
{"timeoffset" 0, "protocolversion" 70001, "blocks" 111908, "errors" "",<br />
"testnet" true, "proxy" "", "connections" 4, "version" 80500,<br />
"keypoololdest" 1380388750, "paytxfee" 0E-8M,<br />
"difficulty" 4642.44443532M, "keypoolsize" 101, "balance" 0E-8M,<br />
"walletversion" 60000}<br />
</source><br />
<br />
=== C ===<br />
The C API for processing JSON is [https://jansson.readthedocs.org/en/latest/ Jansson]. C applications like [https://github.com/bitcoin/libblkmaker libblkmaker] use [[API_reference_(JSON-RPC)#Command_line_.28cURL.29|cURL]] for making the calls and Jansson for interpreting the JSON that cURL fetches.<br />
<br />
For example basic usage (which can be easily modified for Bitcoin RPC), see the Jansson example [https://jansson.readthedocs.org/en/latest/_downloads/github_commits.c github_commits.c] and [https://jansson.readthedocs.org/en/latest/tutorial.html#the-github-repo-commits-api the associated tutorial].<br />
<br />
The following does with libcurl what the [[API_reference_(JSON-RPC)#Command_line_.28cURL.29|cURL example above]] does:<source lang="c">#include <stdlib.h><br />
<br />
#include <curl/curl.h><br />
<br />
int main()<br />
{<br />
CURL *curl = curl_easy_init();<br />
struct curl_slist *headers = NULL;<br />
<br />
if (curl) {<br />
const char *data =<br />
"{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", \"method\": \"getinfo\", \"params\": [] }";<br />
<br />
headers = curl_slist_append(headers, "content-type: text/plain;");<br />
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);<br />
<br />
curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8332/");<br />
<br />
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(data));<br />
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);<br />
<br />
curl_easy_setopt(curl, CURLOPT_USERPWD,<br />
"bitcoinrpcUSERNAME:bitcoinrpcPASSWORD");<br />
<br />
curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);<br />
<br />
curl_easy_perform(curl);<br />
}<br />
return 0;<br />
}<br />
</source>This output can be parsed with Jansson, ''à la'' the Jansson tutorial linked to above.<br />
<br />
(source: [https://bitcoin.stackexchange.com/a/41158/4334 Bitcoin StackExchange])<br />
<br />
=== Qt/C++ ===<br />
<br />
[https://bitbucket.org/devonit/qjsonrpc/overview QJsonRpc] is a Qt/C++ implementation of the JSON-RPC protocol. It integrates nicely with Qt, leveraging Qt's meta object system in order to provide services over the JSON-RPC protocol. QJsonRpc is licensed under the LGPLv2.1.<br />
<br />
<source lang="cpp"><br />
/*<br />
* Copyright (C) 2012-2013 Matt Broadstone<br />
* Contact: http://bitbucket.org/devonit/qjsonrpc<br />
*<br />
* This file is part of the QJsonRpc Library.<br />
*<br />
* This library is free software; you can redistribute it and/or<br />
* modify it under the terms of the GNU Lesser General Public<br />
* License as published by the Free Software Foundation; either<br />
* version 2.1 of the License, or (at your option) any later version.<br />
*<br />
* This library is distributed in the hope that it will be useful,<br />
* but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU<br />
* Lesser General Public License for more details.<br />
*/<br />
#include <QCoreApplication><br />
#include <QAuthenticator><br />
#include <QStringList><br />
#include <QDebug><br />
<br />
#include "qjsonrpchttpclient.h"<br />
<br />
class HttpClient : public QJsonRpcHttpClient<br />
{<br />
Q_OBJECT<br />
public:<br />
HttpClient(const QString &endpoint, QObject *parent = 0)<br />
: QJsonRpcHttpClient(endpoint, parent)<br />
{<br />
// defaults added for my local test server<br />
m_username = "bitcoinrpc";<br />
m_password = "232fb3276bbb7437d265298ea48bdc46";<br />
}<br />
<br />
void setUsername(const QString &username) {<br />
m_username = username;<br />
}<br />
<br />
void setPassword(const QString &password) {<br />
m_password = password;<br />
}<br />
<br />
private Q_SLOTS:<br />
virtual void handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator * authenticator)<br />
{<br />
Q_UNUSED(reply)<br />
authenticator->setUser(m_username);<br />
authenticator->setPassword(m_password);<br />
}<br />
<br />
private:<br />
QString m_username;<br />
QString m_password;<br />
<br />
};<br />
<br />
int main(int argc, char **argv)<br />
{<br />
QCoreApplication app(argc, argv);<br />
if (app.arguments().size() < 2) {<br />
qDebug() << "usage: " << argv[0] << "[-u username] [-p password] <command> <arguments>";<br />
return -1;<br />
}<br />
<br />
HttpClient client("http://127.0.0.1:8332");<br />
if (app.arguments().contains("-u")) {<br />
int idx = app.arguments().indexOf("-u");<br />
app.arguments().removeAt(idx);<br />
if(idx<app.arguments().count())<br />
client.setUsername(app.arguments().takeAt(idx));<br />
else qDebug()<<"-u value not defined";<br />
}<br />
<br />
if (app.arguments().contains("-p")) {<br />
int idx = app.arguments().indexOf("-p");<br />
app.arguments().removeAt(idx);<br />
if(idx<app.arguments().count())<br />
client.setPassword(app.arguments().takeAt(idx));<br />
else qDebug()<<"-p value not defined";<br />
}<br />
<br />
QJsonRpcMessage message = QJsonRpcMessage::createRequest(app.arguments().at(1));<br />
QJsonRpcMessage response = client.sendMessageBlocking(message);<br />
if (response.type() == QJsonRpcMessage::Error) {<br />
qDebug() << response.errorData();<br />
return -1;<br />
}<br />
<br />
qDebug() << response.toJson();<br />
}<br />
</source><br />
<br />
== Multi-wallet RPC calls ==<br />
<br />
[[Bitcoin Knots]] 0.13.1 added support for loading multiple, separate wallets.<br />
Multi-wallet can be enabled by using more than one <code>-wallet</code> argument when starting Bitcoin, either on the command line or in the Bitcoin config file.<br />
This was also included in [[Bitcoin Core]] 0.15.<br />
<br />
Wallet-level RPC calls (like <code>importaddress</code> or <code>listtransactions</code>) can specify which wallet file will be accessed. This is done by setting the HTTP endpoint in the JSON-RPC request in the format <code><RPC IP address>:<RPC port>/wallet/<wallet name></code>, for example <code>https://127.0.0.1:8332/wallet/wallet1.dat</code>.<br />
<br />
The command line utility bitcoin-cli can specify the wallet file using the <code>-rpcwallet</code> flag, for example <code>bitcoin-cli -rpcwallet=wallet1.dat getbalance</code><br />
<br />
For more details see the [https://github.com/bitcoin/bitcoin/blob/master/doc/release-notes/release-notes-0.15.0.md#multi-wallet-support Bitcoin Core 0.15 release notes]<br />
<br />
Alternatively (but not available in Bitcoin Core at this time), an additional parameter can be specified to <code>-rpcauth</code> naming a default wallet for JSON-RPC accesses to the normal endpoint.<br />
<br />
== See Also==<br />
<br />
* The Bitcoin Core documentation: https://github.com/bitcoin/bitcoin/blob/master/doc/JSON-RPC-interface.md#json-rpc-interface<br />
* The Bitcoin Core RPC help for each call: https://bitcoincore.org/en/doc/<br />
* The Bitcoin Core RPC error codes: https://github.com/bitcoin/bitcoin/blob/master/src/rpc/protocol.h<br />
* Bitcoin Core RPC API version changes https://masonicboom.github.io/btcrpcapi/<br />
<br />
* [[Original_Bitcoin_client/API_Calls_list|API calls list]]<br />
* [[Running Bitcoin]]<br />
* [[Lazy API]]<br />
* [[PHP developer intro]]<br />
* [[Raw_Transactions|Raw Transactions API]]<br />
* [https://gourl.io/bitcoin-payment-gateway-api.html GoUrl Bitcoin PHP Payment API]<br />
* [http://blockchain.info/api/json_rpc_api Web Based JSON RPC interface.]<br />
<br />
[[Category:Technical]]<br />
[[Category:Developer]]<br />
[[zh-cn:API_reference_(JSON-RPC)]]<br />
<br />
{{Bitcoin Core documentation}}</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Lightning_Network&diff=65634Lightning Network2018-08-19T04:59:37Z<p>Danda: /* See Also */</p>
<hr />
<div>'''Lightning Network''' is a proposed implementation of [[Hashed Timelock Contracts]] (HTLCs) with bi-directional [[payment channels]] which allows payments to be securely routed across multiple peer-to-peer payment channels.<ref name="ln_pdf">[https://lightning.network/lightning-network-paper.pdf Lightning Network paper, v0.5.9.1]<br>Joseph Poon & Thaddeus Dryja<br>''Retrieved 2016-04-10''</ref> This allows the formation of a network where any peer on the network can pay any other peer even if they don't directly have a channel open between each other.<br />
<br />
== Key features == <br />
Key features of the Lightning Network proposal include,<br />
<br />
* '''Rapid payments:''' payments within an established channel can be made almost as fast as data can travel over the Internet between the two peers.<br />
* '''No third-party trust:''' the two peers in a channel pay each other directly using regular Bitcoin transactions (of which only one is broadcast) so at no point does any third party control their funds.<br />
* '''Reduced blockchain load:''' only channel open transactions, channel close transactions, and (hopefully infrequent) anti-fraud respends need to be committed to the blockchain, allowing all other payments within Lightning Network channels to remain uncommitted. This allows Lightning Network users to make frequent payments secured by Bitcoin without placing excessive load on full nodes which must process every transaction on the blockchain.<br />
* '''Channels can stay open indefinitely:''' as long as the two parties in the channel continue to cooperate with each other, the channel can stay open indefinitely -- there is no mandatory timeout period. This can further reduce the load on the blockchain as well as allow the fees for opening and closing the channel to be amortized over a longer period of time.<br />
* '''Rapid cooperative closes:''' if both parties cooperate, a channel can be closed immediately (with the parties likely wanting to wait for one or more confirmations to ensure the channel closed in the correct state). Non-cooperative closes (such as when one party disappears) are also possible but they take longer.<br />
* '''Outsourcable enforcement:''' if one party closes a channel in an old state in an attempt to steal money, the other party has to act within a defined period of time to block the attempted theft. This function can be outsourced to a third-party without giving them control over any funds, allowing wallets to safely go offline for periods longer than the defined period.<br />
* '''Onion-style routing:''' payment routing information can be encrypted in a nested fashion so that intermediary nodes only know who they received a routable payment from and who to send it to next, preventing those intermediary nodes from knowing who the originator or destination is (provided the intermediaries didn't compare records).<br />
* '''Multisignature capable:''' each party can require that their payments into the channel be signed by multiple keys<ref name="poon_multisig">[https://lists.linuxfoundation.org/pipermail/lightning-dev/2016-January/000403.html 2-of-3 Instant Escrow, or How to Do "2-of-3 Multisig Contract" Equivilant on Lightning]<br>Joseph Poon<br>''Retrieved 2016-04-11''</ref>, giving them access to additional security techniques.<br />
* '''Securely cross blockchains:''' payments can be routed across more than one blockchain (including altcoins and sidechains) as long as all the chains support the same hash function to use for the hash lock, as well as the ability the ability to create time locks.<br />
* '''Sub-satoshi payments:''' payments can be made conditional upon the outcome of a random event, allowing probabilistic payments.<ref name="dryja_directed_graph"/> For example, Alice can pay Bob 0.1 satoshi by creating a 1-satoshi payment with 10-to-1 odds so that 90% of the time she does this she pays him 0 satoshis and 10% of the time she pays him 1 satoshi for an average payment of 0.1 satoshis.<br />
* '''Single-funded channels:''' when Alice needs to send a payment to Bob and doesn't currently have a way to pay him through the Lightning Network (whether because she can't reach him or because she doesn't have enough money in an existing channel), she can make a regular on-chain payment that establishes a channel without Bob needing to add any of his funds to the channel. Alice only uses 12 bytes more than she would for a non-Lightning direct payment and Bob would only need about 25 more [[segwit]] virtual bytes to close the channel than he would had he received a non-Lightning direct payment.<ref name="dryja_directed_graph"/><br />
<br />
== Glossary ==<br />
<br />
<br />
This section attempts to document the most frequently used terms found in Lightning Network literature that may not be familiar to a general technical audience, including both the new terms created by Lightning Network designers as well as pre-existing terms that may not be well known from Bitcoin, cryptography, network routing, and other fields.<br />
<br />
The list below should be in alphabetical order. Any commonly-used synonyms or analogs for a term are placed in parenthesis after the term.<br />
<br />
* '''Bi-directional payment channel:'''<ref name="ln_pdf"/> a payment channel where payments can flow both directions, from Alice to Bob and back to Alice. This is contrasted with Spillman-style and CLTV-style payment channels where payments can only go one direction and once Alice has paid Bob all of the bitcoins she deposited in the channel funding transaction, the channel is no longer useful and so will be closed.<br />
* '''Breach Remedy Transaction:'''<ref name="ln_pdf"/> the transaction Alice creates when Mallory attempts to steal her money by having an old version of the channel state committed to the blockchain. Alice's breach remedy transaction spends all the money that Mallory received but which Mallory can't spend yet because his unilateral spend is still locked by a relative locktime using <code>OP_CSV</code>. This is the third of the maximum of three on-chain transactions needed to maintain a Lightning channel; it only needs to be used in the case of attempted fraud (contract breach).<br />
* '''Channel''' (Lightning channel<ref name="ln_pdf"/>, payment channel<ref name="spillman_channel">[https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html Anti DoS for tx replacement]<br>Jeremy Spillman<br>Retrieved 2016-04-17</ref>) a communication channel that allows two parties to make many secure payments between each other in exchange for making only a few transactions on the blockchain.<br />
* '''Commitment Transaction:'''<ref name="ln_pdf"/> a transaction created collaboratively by Alice and Bob each time they update the state of the channel; it records their current balances within the channel. The '''Initial Commitment Transaction'''<ref name="ln_pdf"/> is the first of these transactions; it records the inital balances within the channel. This is the second of the maximum of three on-chain transactions needed to maintain a Lightning channel; it can be combined with a ''funding transaction'' for a new channel under the cooperative conditions necessary to create an ''exercise settlement transaction''.<br />
* '''Contract:'''<ref name="szabo_smart_contracts">[http://szabo.best.vwh.net/smart_contracts_idea.html The Idea of Smart Contracts]<br>Nick Szabo<br>Retrieved 2016-04-17</ref> an agreement between two or more entities to use Bitcoin transactions in a certain way, usually a way that allows Bitcoin's automated consensus to enforce some or all terms in the contract. Often called a ''smart contract''.<br />
* '''CSV:''' (<code>OP_CheckSequenceVerify</code>, <code>OP_CSV</code>)<ref name="bip68"/> a opcode that allows an output to conditionally specify how long it must be part of the blockchain before an input spending it may be added to the blockchain. See ''relative locktime.''<br />
* '''Delivery Transaction:'''<ref name="ln_pdf"/> not really a transaction but rather the name for the outputs in the ''commitment transaction'' which Alice and Bob receive if one of them closes the channel unilaterally in the correct (current) state. If the channel is closed in an old state (indicating possible fraud), a ''breach remedy transaction'' will be generated from the output that would have paid the party closing the channel. If the channel is closed cooperatively, they'll create an ''exercise settlement transaction'' instead.<br />
* '''Dispute period:''' (dispute resolution period<ref name="poon_time_bitcoin_ln">[https://lightning.network/lightning-network-presentation-time-2015-07-06.pdf Time, Bitcoin, and the Lightning Network]<br>Joseph Poon<br>Retrieved 2016-04-17</ref>) the period of time that Alice has to get her ''breach remedy transaction'' added to the blockchain after Mallory has an old ''commitment transaction'' added to the blockchain. If the dispute period ends without a breach remedy transaction being added to the blockchain, Mallory can spend the funds he received from the old commitment transaction.<br />
* '''Dual-funded channel:'''<ref name="dryja_directed_graph">[https://docs.google.com/presentation/d/1G4xchDGcO37DJ2lPC_XYyZIUkJc2khnLrCaZXgvDN0U/edit?pref=2&pli=1#slide=id.g85f425098_0_2 LN as a Directed Graph: Single-Funded Channel Topology]<br>Thaddeus Dryja<br>Retrieved 2016-04-17</ref> a channel opened by a ''funding transaction'' containing inputs from both Alice and Bob. Compare to a ''single-funded channel'' where only Alice's inputs contribute to the balance of the channel.<br />
* '''Encumbrance:'''<ref>[http://chimera.labs.oreilly.com/books/1234000001802/ch02.html Mastering Bitcoin, Chapter 2: How Bitcoin Works]<br>Andreas Antonopoulos<br>Retrieved 2016-04-17</ref> a generic name for any conditions that must be satisfied before a bitcoin output may be spent. Early Bitcoin transactions placed all their conditions in the scriptPubKey; later the introduction of P2SH allowed conditions to be added in a redeemScript which the scriptPubKey committed to; the introduction of soft fork [[segwit]] will add a similar mechanism for detached conditions that the scriptPubKey commits to; in addition, there are even more novel ways to add conditions to outputs that are discussed but rarely used. The term &quot;encumbrance&quot; allows specifying what the conditions do without fussing over exactly where the conditions appear in a serialized transaction.<br />
* '''Exercise Settlement Transaction:'''<ref name="ln_pdf"/> a form of the ''commitment transaction'' created cooperatively by Alice and Bob when they want to close their channel together. Unlike a regular commitment transaction, none of the outputs on an exercise settlement transaction are time locked, allowing them to be immediately respent.<br />
* '''Exhausted:'''<ref name="dryja_directed_graph"/> (exhausted channel) a payment channel where no additional payments can be made in one direction (such as from Alice to Bob). The person controlling the exhausted side of a Lightning channel loses nothing from fraudulently trying to commit an old channel state, so allowing a channel to become exhausted (or too near to being exhausted) is unpreferable. (Exception: channels can be securely started in an exhausted state, such as a ''single-funded channel.''<br />
* '''Full push:'''<ref name="dryja_directed_graph"/> when Alice pays the full amount of the channel to Bob in the ''initial commitment transaction'', which ''exhausts'' the channel without incentivizing fraud because Alice doesn't have a previous ''commitment transaction'' that she can broadcast. This term is used in the context of a ''single-funded transaction'' and stands in contrast to an ''overpayment'' where Alice deposits more than she pays Bob in that initial payment so that she can continue to use the channel without needing to ''rebalance''.<br />
* '''Funding Transaction:'''<ref name="ln_pdf"/> (deposit transaction) a transaction created collaboratively by Alice and Bob to open a Lightning channel. In a single-funded channel, Alice provides all the funding;<ref name="dryja_directed_graph"/> in a dual-funded channel, Alice and Bob both provide some funding. This is the first of the maximum of three on-chain transactions needed to maintain a Lightning channel; it can be combined with a commitment transaction from a previous channel being closed under cooperative conditions.<br />
* '''Half-signed:'''<ref name="ln_pdf"/> a transaction input which requires two signatures to be added to the blockchain but which only has one signature attached. (More generally, this could be any input that has fewer signatures attached than it needs to be added to the blockchain.)<br />
* '''Hash lock:'''<ref>[https://www.mail-archive.com/bitcoin-development@lists.sourceforge.net/msg05135.html BIP - Hash Locked Transaction]<br>Tier Nolan<br>Retrieved 2016-04-17</ref> an encumbrance to a transaction output that requires the pre-image used to generate a particular hash be provided in order to spend the output. In Lightning, this is used to allow payments to be routable without needing to trust the intermediaries.<br />
* '''HTLC:''' (Hashed Timelocked Contract<ref name="russell_deployable_lightning">[https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf Reaching the Ground with Lightning]<br>Rusty Russell<br>Retrieved 2016-04-17</ref>) a contract such as that used in a Lightning Channel where both a ''hash lock'' and a ''time lock'' are used, the hash lock being used to allow Alice to route payments to Bob even through a Mallory that neither of them trust, and the time lock being used to prevent Mallory from stealing back any payments he made to Alice within the channel (provided Alice enforces the contract).<br />
* '''Intermediary:'''<ref name="ln_pdf"/> When Bob has one channel open with Alice and another channel open with Charlie, Bob can serve as an intermediary for transferring payments between Alice and Charlie. With Lightning payments being secured with a ''hash lock,'' Bob can't steal the payment from Alice to Charlie when it travels through Bob's node. Lightning payments can securely travel through a theoretically unlimited number of intermediaries.<br />
* '''Limbo channel:'''<ref name="dryja_directed_graph"/> an optional special state for a Lightning channel where it cannot be immediately closed by one or both of the parties unilaterally (it can still be immediately closed cooperatively). This is used in particular for ''PLIPPs.''<br />
* '''Multisig:'''<ref name="bitcoin_0_1_code"/> (multisignature, m-of-n multisig) a transaction output that requires signatures from at least one of a set of two or more different private keys. Used in Lightning to give both Alice and Bob control over their individual funds within a channel by requiring both of them sign ''commitment transactions''.<br />
* '''Node:''' (Lightning node<ref name="ln_pdf"/>) a wallet with one or more open Lightning channels. This should not be confused with a Bitcoin [[full node]] that validates Bitcoin blocks, although a full node's wallet may also be simultaneously used as a Lightning node to the advantage of the Lightning network user.<br />
* '''Overfunding:'''<ref name="dryja_directed_graph"/> in a ''single-funded channel,'' Alice deposits more bitcoins into the channel than she pays Bob in the initial payment, allowing her to make additional payments through the Lightning network. This stands in contrast to a ''full push'' where Alice only deposits enough to pay Bob in the initial payment.<br />
* '''PILPP:''' (Pre-Image Length Probabilistic Payments<ref name="dryja_directed_graph"/>) a specific type of ''probabilistic payment'' within a payment channel where Alice creates string with a random length and Bob guesses the length; if he guesses correctly, Alice has to pay him; if he guesses incorrectly, Alice gets to keep her money.<br />
* '''Pre-image:'''<ref>[https://en.wikipedia.org/wiki/Image_%28mathematics%29#Inverse_image Image (mathematics)]<br>English Wikipedia contributors<br>Retrieved 2016-04-17</ref> (R<ref name="ln_pdf"/>) data input into a hash function, which produces a hash of the pre-image. Inputting the same pre-image into the same hash function will always produce the same hash; Lightning uses this feature to create ''hash locks''.<br />
* '''Probabilistic Payment:'''<ref>[[Nanopayments]]<br>Bitcoin Wiki contributors<br>Retrieved 2016-04-17</ref> a payment where Alice only pays Bob if some event outside of Alice's and Bob's control occurs in Bob's favor. Probabilistic payments are usually proposed for scenarios where payments can't conveniently be made small enough for technical reasons (such as not being able to pay less than 1 satoshi) or economic reasons (such as having to pay a transaction fee for every on-chain payment, making small payments uneconomical). See ''PLIPP'' for a specific type of probabilistic payment possible within a Lightning channel.<br />
* '''R:''' the variable commonly used<ref name="ln_pdf"/> in formulas to represent a ''pre-image''.<br />
* '''Rebalance:'''<ref>[https://blockstream.com/2015/09/01/lightning-network/ The Lightning Network: What Is It and What's Happening?]<br>Rusty Russell<br>Retrieved 2016-04-17</ref> a cooperative process between Alice and Bob when they adjust their balances within the channel. This happens with every payment in a Lightning channel and is only noteworthy because single-directional channels (such as Spillman-style and CLTV-style channels) are unable to rebalance and so must close as soon as Alices has paid Bob all the bitcoins she deposited into the channel. See ''bi-directional payment channels.''<br />
* '''Relative locktime:'''<ref name="bip68"/> the ability to specify when a transaction output may be spent relative to the block that included that transaction output. Enabled by BIP68 and made scriptable by BIP112. Lightning uses relative locktime to ensure ''breach remedy transactions'' may be broadcast within a time period starting from when an old ''commitment transaction'' is added to the blockchain; by making this a relative locktime (instead of an absolute date or block height), Lightning channels don't have a hard deadline for when they need to close and so can stay open indefinitely as long as the participants continue to cooperate.<br />
* '''Revocable Sequence Maturity Contract (RSMC):'''<ref name="ln_pdf"/> a ''contract'' used in Lightning to revoke the previous ''commitment transaction''. This is allowed through mutual consent in Lightning by both parties signing a new commitment transaction and releasing the data necessary to create ''breach remedy transactions'' for the previous commitment transaction. This property allows Lightning to support ''bi-directional payment channels'', recover from failed ''HTLC'' routing attempts without needing to commit to the blockchain, as well as provide advanced features such as ''PILPPs.''<br />
* '''Single-funded channel:'''<ref name="dryja_directed_graph"/> a channel opened by a ''funding transaction'' containing only inputs from Alice. Compare to a ''dual-funded channel'' where Alice and Bob both contribute inputs to the initial balance of the channel.<br />
* '''Timelock:'''<ref>[http://rusty.ozlabs.org/?p=450 Lightning Networks Part I: Revocable Transactions]<br>Rusty Russell<br>2016-04-17</ref> either an encumbrance to a transaction that prevents that transaction from being added to the blockchain before a particular time or block height (as is the case with [[nLockTime]], or an encumbrance that prevents a spend from a transaction output from being added to the blockchain before a particular time or block height (as is the case of OP_CLTV, consensus enforced sequence number relative locktime, and OP_CSV). In Lightning, this is used to prevent malicious intermediaries from holding other users' funds hostages as well as to allow victims of attempted theft to submit breach remedy transactions before the thief can respend the funds he stole.<br />
* '''TTL:''' (Time To Live<ref>[http://lists.linuxfoundation.org/pipermail/lightning-dev/2015-July/000019.html Re: Routing on the Lightning Network?]<br>Rusty Russell<br>Retrieved 2016-04-17</ref>) when Alice pays Bob with a ''hash locked'' in-channel payment that's ultimately intended for Charlie, she specifies how long Bob has to deliver the payment (its time to live) before the payment becomes invalid. When Bob pays Charlie with his own in-channel payment that has the same hash lock, Bob specifies a slightly shorter amount of time that Charlie has to reveal the pre-image that unlocks the hash lock before Bob's payment becomes invalid. This ensures that either Bob receives the data necessary to remove the hash lock from the payment he received from Alice or the payment he made to Charlie is invalidated; Alice gets the same guarantee that either the payment she made to Bob ultimate goes through to Charlie or her payment to Bob is invalidated.<br />
* '''Unilateral:'''<ref name="ln_pdf"/> any action performed by only one of the participants in a channel without requesting or needing permission from the other participant. Lightning allows channels to be closed unilaterally (so Alice can close the channel by herself if Bob becomes unresponsive) and attempted fraud can be penalized unilaterally (so Alice can take any bitcoins Mallory tried to steal when he broadcast an old ''commitment transaction'').<br />
* '''UTXO:'''<ref>[https://bitcoin.org/en/glossary/unspent-transaction-output Unspent Transaction Output (UTXO)]<br>Bitcoin.org Developer Glossary<br>Retrieved 2016-04-17</ref> (Unspent Transaction Output) spendable bitcoins. A transaction output lists a bitcoin amount and the conditions (called an ''encumbrance'') that need to be fulfilled in order to spend those bitcoins. Once those bitcoins have been spent on the blockchain, no other transaction in the same blockchain can spend the same bitcoins, so an Uspent Transaction Output (UTXO) is bitcoins that can be spent.<br />
<br />
== See Also ==<br />
<br />
* [[Payment channels]]<br />
* [[Hashed Timelock Contracts]]<br />
* [[Off-Chain Transactions]]<br />
* [http://dev.lightning.community/resources/index.html Lightning Lab's list of resources]<br />
* [https://github.com/dan-da/lightning-nodes/blob/master/README.md List of network nodes].<br />
<br />
== References ==<br />
<references><br />
<ref name="bitcoin_0_1_code">[http://satoshi.nakamotoinstitute.org/code/ Bitcoin 0.1 code]<br>Satoshi Nakamoto<br>Retrieved 2016-04-11</ref><br />
<ref name="bip68">[https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki BIP68: Relative lock-time using consensus-enforced sequence numbers]<br>Mark Friedenbach, BtcDrak, Nicolas Dorier, and kinoshitajona<br>Retrieved 2016-04-12</ref><br />
<references/><br />
<br />
[[Category:Technical]]</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=65598Deterministic wallet tools2018-07-19T06:20:07Z<p>Danda: /* Online Services */</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip39 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/trezor/python-mnemonic python-mnemonic]: Reference implementation of BIP-0039: Mnemonic code for generating deterministic keys<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic, and can generate new master keys as well. Supports segwit (p2sh,bech32) and hundreds of altcoins.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
* [https://github.com/trezor/python-trezor python-trezor]: Client side implementation for TREZOR-compatible Bitcoin hardware wallets.<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) DO-NOT-DO-THIS!!! ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=65597Deterministic wallet tools2018-07-19T06:17:05Z<p>Danda: /* Offline Command-line software */</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/trezor/python-mnemonic python-mnemonic]: Reference implementation of BIP-0039: Mnemonic code for generating deterministic keys<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic, and can generate new master keys as well. Supports segwit (p2sh,bech32) and hundreds of altcoins.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
* [https://github.com/trezor/python-trezor python-trezor]: Client side implementation for TREZOR-compatible Bitcoin hardware wallets.<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) DO-NOT-DO-THIS!!! ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=65542Deterministic wallet tools2018-07-06T05:54:03Z<p>Danda: /* Offline Command-line software */</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/trezor/python-mnemonic python-mnemonic]: Reference implementation of BIP-0039: Mnemonic code for generating deterministic keys<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic, and can generate new master keys as well. Many altcoins supported.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
* [https://github.com/trezor/python-trezor python-trezor]: Client side implementation for TREZOR-compatible Bitcoin hardware wallets.<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) DO-NOT-DO-THIS!!! ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=65541Deterministic wallet tools2018-07-06T05:53:19Z<p>Danda: /* Offline Command-line software */</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/trezor/python-mnemonic python-mnemonic]: Reference implementation of BIP-0039: Mnemonic code for generating deterministic keys<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic, and can generate new keys as well. Many altcoins supported.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
* [https://github.com/trezor/python-trezor python-trezor]: Client side implementation for TREZOR-compatible Bitcoin hardware wallets.<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) DO-NOT-DO-THIS!!! ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=64244Deterministic wallet tools2017-11-17T22:09:12Z<p>Danda: /* Offline Command-line software */</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/trezor/python-mnemonic python-mnemonic]: Reference implementation of BIP-0039: Mnemonic code for generating deterministic keys<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
* [https://github.com/trezor/python-trezor python-trezor]: Client side implementation for TREZOR-compatible Bitcoin hardware wallets.<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
Don't do this!<br />
<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=64243Deterministic wallet tools2017-11-17T22:02:42Z<p>Danda: /* Offline Command-line software */</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/trezor/python-mnemonic]: Reference implementation of BIP-0039: Mnemonic code for generating deterministic keys<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
Don't do this!<br />
<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet&diff=63774Deterministic wallet2017-08-07T22:02:08Z<p>Danda: </p>
<hr />
<div>A deterministic wallet is a system of deriving keys from a single starting point known as a seed. The seed allows a user to easily back up and restore a wallet without needing any other information and can in some cases allow the creation of public addresses without the knowledge of the private key. <br />
<br />
See also: [[Deterministic_wallet_tools|Deterministic Wallet Tools]]<br />
<br />
== Benefits ==<br />
<br />
Early clients such as the [[Satoshi client]] generate a buffer of fresh random private keys to be used as receiving and [[change|change addresses]] in the future. This has the effect of invalidating backups after a short period when the keypool buffer (typically 100 addresses) is exhausted. Deterministic wallets can generate an unlimited number of addresses on the fly and as such don't suffer from this issue. As the addresses are generated in a known fashion rather than randomly some clients can be used on multiple devices without the risk of losing funds. Users can conveniently create a single backup of the seed in a human readable format that will last the life of the wallet, without the worry of this backup becoming stale. <br />
<br />
Certain types of deterministic wallet (BIP0032, Armory, [[Coinkite]] and [https://coinb.in/#newHDaddress Coinb.in] ) additionally allow for the complete separation of private and public key creation for greater security and convenience. In this model a server can be set up to only know the Master Public Key of a particular deterministic wallet. This allows the server to create as many public keys as is necessary for receiving funds, but a compromise of the MPK will not allow an attacker to spend from the wallet. They can alternatively be used in [[Electrum]] and [[Armory]] to enable completely offline storage and spending, where an offline computer knows the private key and an online one knows only the MPK. Transactions spending coins are ferried between the two computers via USB storage which avoids exposing the offline computer to a network-based attack.<br />
<br />
Deterministic wallets implemented by hardware wallets ([[TREZOR]]) keep the generated private keys offline and do not expose them to the computer even when spending coins.<br />
<br />
==Types==<br />
<br />
===Type 1 deterministic wallet===<br />
A type 1 deterministic wallet is a simple method of generating addresses from a known starting string, as such it does not allow advanced features such as a Master Public Key. To generate a private key take SHA256(string + n), where n is an ASCII-coded number that starts from 1 and increments as additional keys are needed. <br />
<br />
This type of wallet can be created by Casascius Bitcoin Address Utility.<br />
<br />
===Type 2 hierarchical deterministic wallet===<br />
This wallet type is described in [[BIP 0032]] and is fully implemented in [[TREZOR]], [[Electrum]] and [[CarbonWallet]]. The seed is a random 128 bit value presented to the user as a 12 word mnemonic using common English words. The seed is used after 100,000 rounds of SHA256 to slow down attacks against weak user-chosen strings. [https://bitcointalk.org/index.php?topic=330672.msg3547258#msg3547258]. <br />
<br />
The initial description and workings of this wallet type is credited to Gregory Maxwell. [https://bitcointalk.org/index.php?topic=19137.msg239768#msg239768]<br />
<br />
===Armory deterministic wallet===<br />
[[Armory]] has its own Type-2 deterministic wallet format based on a "root key" and a "chain code." Earlier versions of Armory required backing up both the "root key" and "chaincode," while newer versions start deriving the chaincode from the private key in a non-reversible way. These newer Armory wallets (0.89+) only require the single, 256-bit root key. This older format is intended to be phased out in favor of the standard BIP0032 format. [https://bitcointalk.org/index.php?topic=351099.msg3770818#msg3770818]</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=63773Deterministic wallet tools2017-08-07T22:00:53Z<p>Danda: </p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallet]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
Don't do this!<br />
<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Deterministic_wallet_tools&diff=63772Deterministic wallet tools2017-08-07T21:58:44Z<p>Danda: Created page with "List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets. Tools listed on this page can typically perform some form of key..."</p>
<hr />
<div>List of tools/services for working with Hierarchical Deterministic Wallets, aka hd-wallets aka bip32 wallets.<br />
<br />
Tools listed on this page can typically perform some form of key derivation and list hd-wallet addresses.<br />
<br />
'''Warning: You should never give an online service your master extended private key (xprv) as they could use it to drain your entire wallet'''. Even sharing an extended public key [[#Risks of Sharing an Extended Public Key (xpub)|entails risks]]. If using an online hosted javascript tool, be careful to work with it offline only.<br />
<br />
See also [[Deterministic Wallets]].<br />
<br />
=== Online Services ===<br />
<br />
* [http://bip32.org/ bip32.org]: A tool for displaying information derived from bip32 extended key, or nmenonic phrase. Appears to list only the first address.<br />
* [https://iancoleman.github.io/bip39/ Mnemonic Code Converter]: A tool for listing keys and addresses from a bip32 mnemonic phrase. The tool can be saved as a file and used without any internet connection.<br />
* [https://webhdwallet.github.io/ WebHDWallet]: Implementing the Hierarchical Deterministic Wallet proposal BIP32, with the aim of creating easy to use, secure, and powerful tools for managing HD wallets and the funds within.<br />
* [https://mybitprices.info/hd-wallet-addrs.html mybitprices.info]: A tool that can derive all used wallet addresses from an extended public key and can further lookup historic price information for all wallet transactions and create gain/loss reports.<br />
* [https://bitcore.io/playground/#/hdkeys bitcore playground]: Derive HD keys from a private or public extended key and a path.<br />
<br />
=== Offline Command-line software ===<br />
<br />
* [https://github.com/dan-da/hd-wallet-derive hd-wallet-derive]: A command-line tool that derives bip32 addresses and private keys from bip32 extended keys or mnemonic.<br />
* [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs]: A command-line tool for finding bitcoin hd-wallet addresses that have actually received funds, including change addresses. (note: key derivation occurs offline, but funds lookup requires internet connection.)<br />
* [https://github.com/vbuterin/pybitcointools pybitcointools]: Simple, common-sense Bitcoin-themed Python ECC library. by Vitalik Buterin.<br />
<br />
<br />
=== Risks associated with sharing extended keys with a third party ===<br />
<br />
==== Risks of Sharing an Extended Private Key (xprv) ====<br />
<br />
# '''The recipient can spend (steal) all your wallet funds.'''<br />
# The recipient can obtain all your wallet keys and addresses, private and public.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
<br />
Don't do this!<br />
<br />
<br />
==== Risks of Sharing an Extended Public Key (xpub) ====<br />
<br />
In general it is safest NOT to share an extended public key.<br />
<br />
# The recipient can obtain all your wallet public keys and addresses, but not your private keys.<br />
# The recipient can identify and view all your historic transactions.<br />
# The recipient can link all your wallet transactions together, possibly linking anonymous transactions with those associated with your identity.<br />
# If, and only if, the recipient ''also'' obtains a single private key from your wallet, the recipient can obtain all your private keys and steal your funds, just as if they had your xprv key.</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Tax_compliance&diff=62792Tax compliance2017-06-01T20:46:28Z<p>Danda: /* BitPrices */</p>
<hr />
<div>There may be tax liabilities encountered when transacting with or trading in bitcoins. Some of those that are possible might be described below.<br />
<br />
This page was created by those in the Bitcoin community to help in understanding tax compliance concerns. This is not legal advice nor accounting advice. For either for those consult your attorney or accountant.<br />
<br />
==Tax Questions==<br />
The general tax questions and answers were shared by forum member bitcoinaccountant<ref>[http://bitcointalk.org/index.php?topic=14334.0 Bitcoin accounting and taxes]</ref>.<br />
<br />
===Are bitcoins taxable if I earned them by doing a service for someone else, or received them in exchange for something?===<br />
<br />
Anything that you receive as payment for goods or services is generally taxable income unless it is specifically exempted.<br />
<br />
That means, if you mow your neighbor’s lawn, it doesn’t matter if he pays you $20 in cash, or $20 worth of bitcoins. (Or $20 worth of tomatoes for that matter)<br />
<br />
In many jurisdictions, you are still legally required to report that as income. When using Bitcoin for payment the taxing authorities may be less likely to be aware of the payments but try to mow 10,000 neighbor’s lawns and not report the income and you will be much more likely to get caught.<br />
<br />
===Are my bitcoins taxed as income, or as capital gains?===<br />
<br />
Income that is earned through the exchange of services with another person, whether in the form of bitcoins, dollars, or barter; is included in gross income, and would be subject to income tax at applicable rates. Also these bitcoins could be subject to self employment tax.<br />
<br />
In some jurisdictions, income earned through the process of buying and selling bitcoins would also be included in gross income, but would be treated as capital gains. <br />
<br />
Note: The above interpretation is based on the assumption bitcoins are treated as a store of value such as gold, or other such commodity. If instead they are treated as a currency or debt, the full gain could be taxed based on market value at the end of each tax year. [http://www.indexuniverse.com/publications/journalofindexes/joi-news/3858--irs-ends-currency-etn-advantage.html 3858 IRS Ends Currency ETN Advantage] Simply put, the IRS never considers currency a long-term investment. Consequently, if bitcoins are treated as a currency, you will be taxed the same as holding an account in any non-functional (foreign) currency.<br />
<br />
===How are Bitcoins that I have mined treated for tax purposes?===<br />
<br />
This is a tricky question, in that bitcoins are really the first digital currency that was created in this manner and actually have a significant value in relation to other currencies. Essentially it is somewhat uncharted territory. Literally bitcoins, and even digital currencies are so new, that there is little to no precedent for some aspects of bitcoin mining, from a tax perspective.<br />
<br />
Since Bitcoins are currently traded in various online marketplaces, when someone receives a Bitcoin, they can reasonably calculate it’s value in the local currency. Because of this, it is possible that the taxing authority will treat the receipt of a Bitcoin through a mining pool, or from an individual mining operation, as a taxable event. At that time, the taxpayer would be required to estimate the value of the Bitcoins in dollars and record that amount. This would have to be done either daily or weekly depending on the value of the Bitcoins if their value keeps fluctuating as much as it has the past few weeks. These amounts would be recorded as revenue from bitcoin mining operations and would be taxable less allowed expenses.<br />
<br />
When selling mined Bitcoins, however, you would also be taxed on the increase between the value you recorded them at when you first received them, and the value you sold them for. <br />
<br />
Another possibility is that the government will consider mined Bitcoins ‘intangible personal property’. As a rule, however, financial instruments are excluded from this particular category. The question is, are bitcoins a financial instrument, or rather, will the taxing authority consider them a financial instrument? We will have to wait and see if bitcoins become popular enough for a position to be taken on that.<br />
<br />
===What expenses can I deduct/expense/itemize if I set up a Bitcoin mining operation?===<br />
<br />
That depends on your situation. Generally speaking, though, you can deduct business expenses that are ordinary and necessary. Buying video cards would be both of these, buying a big screen TV to watch while mining would be neither.<br />
<br />
===Do I need to register as a business/LLC/corporation to mine Bitcoins and deduct expenses?===<br />
<br />
In most instances, there is no requirement to do so. Whether you decide to form a corporation, register as an LLC, or simply operate as a private individual (sole proprietorship), the basic concept of tax treatment for Bitcoins is going to remain the same. For example, you will report gross income, deduct expenses, and have a net taxable income on which you will be required to pay income tax, as well as possibly self employment tax depending on how your mining business is set up.<br />
<br />
===Are there any other reporting requirements?===<br />
<br />
Each [[Tax compliance#Jurisdictions|jurisdiction]] will have varying requirements.<br />
<br />
==Types of Transactions==<br />
<br />
* Currency exchange trading<br />
* Investment as a commodity<br />
* Purchase of goods and services<br />
* Barter<br />
* Compensation / Payroll<br />
<br />
==Types of Taxes==<br />
<br />
* Sales Taxes<br />
* Value Added Taxes<br />
* Income Taxes<br />
* Excise Taxes<br />
* Payroll Taxes<br />
<br />
==Recordkeeping==<br />
<br />
===Trading===<br />
<br />
The records kept might include the same information that appears on a stock or forex brokerage statement: "Date of trade, Description of trade, Qty & Price, and Fees".<br />
<br />
===Mining===<br />
<br />
Depending on how the revenue is to be treated, you may need to know when the Bitcoin proceeds were attained<ref>[http://bitcointalk.org/index.php?topic=55731.0 How to treat Bitcoin mining income for tax purposes?]</ref>.<br />
<br />
===Commerce===<br />
<br />
Regardless of how revenue is recognized for goods and services whose payment is made using Bitcoins, the recordkeeping requirements are likely to be the same: Reference to sales (e.g., cust # / invoice #), amount received (in BTCs) and date. If sales taxes are payable, then for that purpose documentation might include a calculated based on a weighted average exchange rate that existed at the time of sale.<br />
<br />
===Payroll===<br />
<br />
Employers sending bitcoins as compensation would likely record all calculations in the functional currency (e.g., USDs) and then after all withholding amounts are subtracted the net amount of the check is paid out in bitcoins based on the market exchange rate at the time.<br />
<br />
==Jurisdictions==<br />
<br />
Below are specific details to individual tax jurisdictions.<br />
<br />
===U.S.===<br />
<br />
The IRS issued guidance on the treatment of Bitcoin and other digital currencies in their March 2014-21 Notice <ref>[http://www.irs.gov/pub/irs-drop/n-14-21.pdf IRS Notice 2014-21]</ref>. The notice clarified the position that the IRS treats digital currencies as capital assets and are therefore subject to capital gains taxes. Any disposition of these digital currencies, including trading and spending, is a tax event and capital gains must be calculated in USD. When spending, the fair value should be used as the proceeds value. The IRS also clarified that mining is treated as immediate income at the fair or market value of those mined coins on their date of receipt.<br />
<br />
While the IRS Notice does confirm that Bitcoin is taxed as property rather than a currency, there are still some unresolved issues. For instance, how should a mined alt-coin income value be determined is there is no direct fiat market, and do alt-coins benefit from <em>Like-Kind Exchanges</em> <ref>[http://www.irs.gov/publications/p550/ch04.html#en_US_2014_publink100010437 IRS Publication 550 - Like-Kind Exchanges]</ref>.<br />
<br />
There is a Report of Foreign Bank and Financial Accounts (FBAR) filing requirement for financial accounts in a foreign country when the aggregate value of the accounts exceeded $10,000 at any time during the calendar year. While the value of Bitcoins themselves don't count towards the FBAR threshold<ref>[http://www.coindesk.com/irs-no-bitcoin-reporting-fincen-foreign-banking-tax-form IRS: No Bitcoin Reporting Required for FinCEN Foreign Banking Tax Form]</ref>, there is the possibility that requirement applies to cash held in non-US bitcoin exchanges or wallet services<ref>[http://bitcointalk.org/index.php?topic=55260.msg657831#msg657831 The TD F 90-22.1 Form for Bitcoin]</ref>. An additional topic that may have a connection to Bitcoin is the Foreign Account Tax Compliance Act (FATCA) filing requirement in the U.S.<ref>[http://bitcointalk.org/index.php?action=post;topic=57369.0 FATCA & BITCOIN (The Financial Berlin Wall)]</ref>.<br />
<br />
The [[Cryptocurrency Legal Advocacy Group]] (CLAG) has published memorandum detailing aspects of income taxation in the U.S. regarding Bitcoin<ref>[http://theclag.org/CM%231001Final.pdf Staying Between the Lines: A Survey of U.S. Income Taxation and its Ramifications on Cryptocurrencies]</ref>.<br />
<br />
==Accounting and Tax Compliance Software==<br />
<br />
===BitcoinTaxes===<br />
<br />
[https://bitcoin.tax BitcoinTaxes], launched in January 2014, provides income and capital gains calculations for users of Bitcoin and other digital currencies in the US, UK, Canada, Australia, Germany and other similar tax jurisdictions. Trading records can be imported from all major trading exchanges, including Coinbase, Circle, Bitstamp, and BTC-e, to produce a complete annual trading history. In addition, spending and income records can be imported from wallets and payment processors, such as the core wallets, Blockchain.info and BitPay. Mining transactions are added from mining pools or directly from the appropriate BTC, LTC and DOGE blockchains. Capital gains are then calculated in the user's fiat currency using First-In-First-Out (FIFO) and a number of other cost-basis methods, such as Last-In-first-Out, Closest-Price-First-Out and average costing. Capital gains reports, income reports and balance reports can be downloaded as well as an 8949 attachment file and PDF of Form 8949 for US tax payers.<br />
<br />
===LibraTax===<br />
<br />
[http://libratax.com/ LibraTax] launched in 2014 and will automatically import your transactions from Coinbase, Blockchain and other exchanges. LibraTax also offers several different cost-basis reporting methods - FIFO, LIFO and Libra-Optimized. The latter cost-basis method is a selective cost-basis method, where-in LibraTax will automatically and compliantly match your redemptions of bitcoin to minimize your reportable gains, or if none, maximize your reportable losses. Upon choosing a reporting method, an additional feature becomes available - automatic generation and completion of IRS Form 8949 that needs to be included on all tax returns with bitcoin activity.<br />
<br />
LibraTax currently only services individual and business users that need to pay bitcoin-related taxes and/or meet bitcoin tax compliance and reporting guidelines in the U.S.<br />
<br />
===Kryptofolio+tax===<br />
<br />
[http://www.kryptofolio-tax.com/ Kryptofolio+tax] is a free mobile app ([https://itunes.apple.com/us/app/kryptofolio+tax/id921388783?ls=1&mt=8 iPhone], [https://play.google.com/store/apps/details?id=com.hydro.bitcoin_accounts Android], [http://apps.microsoft.com/windows/app/kryptofolio-tax/ee888fae-f5db-4bda-b7fb-7ce2a75b9758 Windows Store]/[http://www.windowsphone.com/s?appid=898edda1-1c94-4424-b1a7-216026fe86f7 Phone]) with a fully configurable FIFO (first in first out) portfolio manager and additionally tax calculator for bitcoin, litecoin and other custom configurable crypto-currencies. It works by setting up percentage cuts of capital gain, sales and flat values on specific transaction types. So can therefore be configured to be used in almost any jurisdiction as a supplement to current tax arrangements. It can import transactions either from blockchain.info or via a csv file import direct from a wallet export for all crypto-currencies. For maximum privacy, transactions can be converted to QR codes to be scanned directly into the device without being broadcast. PnL and tax contributions can then be exported and then used to prepare a tax return.<br />
<br />
===BitPrices===<br />
<br />
[http://https://github.com/dan-da/bitprices BitPrices] is an open-source command-line tool with a companion website [http://mybitprices.info mybitprices.info] intended for viewing fiat value of transactions on the day they occurred. It is useful for auditing wallet transactions and determining cost basis. The website is free to use and does not require any registration or login. The tool can generate highly customizable transaction reports as well as a schedule D report with realized gains. FIFO and LIFO cost-basis methods are supported. This tool requires a list of all Bitcoin addresses in your wallet including change addresses. A companion tool, [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs] is available that discovers all wallets addresses in an HD wallet, including Copay multisig wallets.<br />
<br />
==See Also==<br />
<br />
* [[:Category:Legal|Legal]] category<br />
* [[Petition against illegal use]]<br />
* [[Petition for illegal use]]<br />
* [http://www.mscs.dal.ca/~selinger/accounting/tutorial.html Tutorial on multiple currency accounting]<br />
* [http://www.taxanalysts.com/www/features.nsf/Articles/C1A7ED502DD2B84685257AAF0056A2A2 Digital Currency: A New Worry for Tax Administrators?] by David D. Stewart and Stephanie Soong Johnston<br />
* [http://github.com/weex/BTCReporter BTCReporter] ([http://bitcointalk.org/index.php?topic=56504 info]) analyzes your MtGox trading logs<br />
* [http://www.gao.gov/products/gao-13-516 GAO-13-516 - VIRTUAL ECONOMIES AND CURRENCIES] ([http://www.gao.gov/assets/660/654620.pdf PDF Only)])<br />
* [http://www.ustream.tv/recorded/34595935 Video: GAO - Virtual Currencies and Taxes]<br />
* [http://bitcoin.accountants Bitcoin.Accountants - Nowell Associates Limited for UK Tax Treatment of Bitcoins]<br />
* [https://bitcoin.tax BitcoinTaxes]<br />
* [http://www.kryptofolio-tax.com Kryptofolio+tax - Mobile Bitcoin and Altcoin tax calculation app (iPhone, Android, Windows Phone/Store)]<br />
<br />
==References==<br />
<references /><br />
<br />
[[Category:Financial]]<br />
[[Category:Legal]]</div>Dandahttps://tests.bitcoin.it/w/index.php?title=Tax_compliance&diff=60437Tax compliance2016-02-21T18:32:00Z<p>Danda: /* Accounting and Tax Compliance Software */</p>
<hr />
<div>There may be tax liabilities encountered when transacting with or trading in bitcoins. Some of those that are possible might be described below.<br />
<br />
This page was created by those in the Bitcoin community to help in understanding tax compliance concerns. This is not legal advice nor accounting advice. For either for those consult your attorney or accountant.<br />
<br />
==Tax Questions==<br />
The general tax questions and answers were shared by forum member bitcoinaccountant<ref>[http://bitcointalk.org/index.php?topic=14334.0 Bitcoin accounting and taxes]</ref>.<br />
<br />
===Are bitcoins taxable if I earned them by doing a service for someone else, or received them in exchange for something?===<br />
<br />
Anything that you receive as payment for goods or services is generally taxable income unless it is specifically exempted.<br />
<br />
That means, if you mow your neighbor’s lawn, it doesn’t matter if he pays you $20 in cash, or $20 worth of bitcoins. (Or $20 worth of tomatoes for that matter)<br />
<br />
In many jurisdictions, you are still legally required to report that as income. When using Bitcoin for payment the taxing authorities may be less likely to be aware of the payments but try to mow 10,000 neighbor’s lawns and not report the income and you will be much more likely to get caught.<br />
<br />
===Are my bitcoins taxed as income, or as capital gains?===<br />
<br />
Income that is earned through the exchange of services with another person, whether in the form of bitcoins, dollars, or barter; is included in gross income, and would be subject to income tax at applicable rates. Also these bitcoins could be subject to self employment tax.<br />
<br />
In some jurisdictions, income earned through the process of buying and selling bitcoins would also be included in gross income, but would be treated as capital gains. <br />
<br />
Note: The above interpretation is based on the assumption bitcoins are treated as a store of value such as gold, or other such commodity. If instead they are treated as a currency or debt, the full gain could be taxed based on market value at the end of each tax year. [http://www.indexuniverse.com/publications/journalofindexes/joi-news/3858--irs-ends-currency-etn-advantage.html 3858 IRS Ends Currency ETN Advantage] Simply put, the IRS never considers currency a long-term investment. Consequently, if bitcoins are treated as a currency, you will be taxed the same as holding an account in any non-functional (foreign) currency.<br />
<br />
===How are Bitcoins that I have mined treated for tax purposes?===<br />
<br />
This is a tricky question, in that bitcoins are really the first digital currency that was created in this manner and actually have a significant value in relation to other currencies. Essentially it is somewhat uncharted territory. Literally bitcoins, and even digital currencies are so new, that there is little to no precedent for some aspects of bitcoin mining, from a tax perspective.<br />
<br />
Since Bitcoins are currently traded in various online marketplaces, when someone receives a Bitcoin, they can reasonably calculate it’s value in the local currency. Because of this, it is possible that the taxing authority will treat the receipt of a Bitcoin through a mining pool, or from an individual mining operation, as a taxable event. At that time, the taxpayer would be required to estimate the value of the Bitcoins in dollars and record that amount. This would have to be done either daily or weekly depending on the value of the Bitcoins if their value keeps fluctuating as much as it has the past few weeks. These amounts would be recorded as revenue from bitcoin mining operations and would be taxable less allowed expenses.<br />
<br />
When selling mined Bitcoins, however, you would also be taxed on the increase between the value you recorded them at when you first received them, and the value you sold them for. <br />
<br />
Another possibility is that the government will consider mined Bitcoins ‘intangible personal property’. As a rule, however, financial instruments are excluded from this particular category. The question is, are bitcoins a financial instrument, or rather, will the taxing authority consider them a financial instrument? We will have to wait and see if bitcoins become popular enough for a position to be taken on that.<br />
<br />
===What expenses can I deduct/expense/itemize if I set up a Bitcoin mining operation?===<br />
<br />
That depends on your situation. Generally speaking, though, you can deduct business expenses that are ordinary and necessary. Buying video cards would be both of these, buying a big screen TV to watch while mining would be neither.<br />
<br />
===Do I need to register as a business/LLC/corporation to mine Bitcoins and deduct expenses?===<br />
<br />
In most instances, there is no requirement to do so. Whether you decide to form a corporation, register as an LLC, or simply operate as a private individual (sole proprietorship), the basic concept of tax treatment for Bitcoins is going to remain the same. For example, you will report gross income, deduct expenses, and have a net taxable income on which you will be required to pay income tax, as well as possibly self employment tax depending on how your mining business is set up.<br />
<br />
===Are there any other reporting requirements?===<br />
<br />
Each [[Tax compliance#Jurisdictions|jurisdiction]] will have varying requirements.<br />
<br />
==Types of Transactions==<br />
<br />
* Currency exchange trading<br />
* Investment as a commodity<br />
* Purchase of goods and services<br />
* Barter<br />
* Compensation / Payroll<br />
<br />
==Types of Taxes==<br />
<br />
* Sales Taxes<br />
* Value Added Taxes<br />
* Income Taxes<br />
* Excise Taxes<br />
* Payroll Taxes<br />
<br />
==Recordkeeping==<br />
<br />
===Trading===<br />
<br />
The records kept might include the same information that appears on a stock or forex brokerage statement: "Date of trade, Description of trade, Qty & Price, and Fees".<br />
<br />
===Mining===<br />
<br />
Depending on how the revenue is to be treated, you may need to know when the Bitcoin proceeds were attained<ref>[http://bitcointalk.org/index.php?topic=55731.0 How to treat Bitcoin mining income for tax purposes?]</ref>.<br />
<br />
===Commerce===<br />
<br />
Regardless of how revenue is recognized for goods and services whose payment is made using Bitcoins, the recordkeeping requirements are likely to be the same: Reference to sales (e.g., cust # / invoice #), amount received (in BTCs) and date. If sales taxes are payable, then for that purpose documentation might include a calculated based on a weighted average exchange rate that existed at the time of sale.<br />
<br />
===Payroll===<br />
<br />
Employers sending bitcoins as compensation would likely record all calculations in the functional currency (e.g., USDs) and then after all withholding amounts are subtracted the net amount of the check is paid out in bitcoins based on the market exchange rate at the time.<br />
<br />
==Jurisdictions==<br />
<br />
Below are specific details to individual tax jurisdictions.<br />
<br />
===U.S.===<br />
<br />
The IRS issued guidance on the treatment of Bitcoin and other digital currencies in their March 2014-21 Notice <ref>[http://www.irs.gov/pub/irs-drop/n-14-21.pdf IRS Notice 2014-21]</ref>. The notice clarified the position that the IRS treats digital currencies as capital assets and are therefore subject to capital gains taxes. Any disposition of these digital currencies, including trading and spending, is a tax event and capital gains must be calculated in USD. When spending, the fair value should be used as the proceeds value. The IRS also clarified that mining is treated as immediate income at the fair or market value of those mined coins on their date of receipt.<br />
<br />
While the IRS Notice does confirm that Bitcoin is taxed as property rather than a currency, there are still some unresolved issues. For instance, how should a mined alt-coin income value be determined is there is no direct fiat market, and do alt-coins benefit from <em>Like-Kind Exchanges</em> <ref>[http://www.irs.gov/publications/p550/ch04.html#en_US_2014_publink100010437 IRS Publication 550 - Like-Kind Exchanges]</ref>.<br />
<br />
There is a Report of Foreign Bank and Financial Accounts (FBAR) filing requirement for financial accounts in a foreign country when the aggregate value of the accounts exceeded $10,000 at any time during the calendar year. While the value of Bitcoins themselves don't count towards the FBAR threshold<ref>[http://www.coindesk.com/irs-no-bitcoin-reporting-fincen-foreign-banking-tax-form IRS: No Bitcoin Reporting Required for FinCEN Foreign Banking Tax Form]</ref>, there is the possibility that requirement applies to cash held in non-US bitcoin exchanges or wallet services<ref>[http://bitcointalk.org/index.php?topic=55260.msg657831#msg657831 The TD F 90-22.1 Form for Bitcoin]</ref>. An additional topic that may have a connection to Bitcoin is the Foreign Account Tax Compliance Act (FATCA) filing requirement in the U.S.<ref>[http://bitcointalk.org/index.php?action=post;topic=57369.0 FATCA & BITCOIN (The Financial Berlin Wall)]</ref>.<br />
<br />
The [[Cryptocurrency Legal Advocacy Group]] (CLAG) has published memorandum detailing aspects of income taxation in the U.S. regarding Bitcoin<ref>[http://theclag.org/CM%231001Final.pdf Staying Between the Lines: A Survey of U.S. Income Taxation and its Ramifications on Cryptocurrencies]</ref>.<br />
<br />
==Accounting and Tax Compliance Software==<br />
<br />
===BitcoinTaxes===<br />
<br />
[https://bitcoin.tax BitcoinTaxes], launched in January 2014, provides income and capital gains calculations for users of Bitcoin and other digital currencies in the US, UK, Canada, Australia, Germany and other similar tax jurisdictions. Trading records can be imported from all major trading exchanges, including Coinbase, Circle, Bitstamp, and BTC-e, to produce a complete annual trading history. In addition, spending and income records can be imported from wallets and payment processors, such as the core wallets, Blockchain.info and BitPay. Mining transactions are added from mining pools or directly from the appropriate BTC, LTC and DOGE blockchains. Capital gains are then calculated in the user's fiat currency using First-In-First-Out (FIFO) and a number of other cost-basis methods, such as Last-In-first-Out, Closest-Price-First-Out and average costing. Capital gains reports, income reports and balance reports can be downloaded as well as an 8949 attachment file and PDF of Form 8949 for US tax payers.<br />
<br />
===LibraTax===<br />
<br />
[http://libratax.com/ LibraTax] launched in 2014 and will automatically import your transactions from Coinbase, Blockchain and other exchanges. LibraTax also offers several different cost-basis reporting methods - FIFO, LIFO and Libra-Optimized. The latter cost-basis method is a selective cost-basis method, where-in LibraTax will automatically and compliantly match your redemptions of bitcoin to minimize your reportable gains, or if none, maximize your reportable losses. Upon choosing a reporting method, an additional feature becomes available - automatic generation and completion of IRS Form 8949 that needs to be included on all tax returns with bitcoin activity.<br />
<br />
LibraTax currently only services individual and business users that need to pay bitcoin-related taxes and/or meet bitcoin tax compliance and reporting guidelines in the U.S.<br />
<br />
===Kryptofolio+tax===<br />
<br />
[http://www.kryptofolio-tax.com/ Kryptofolio+tax] is a free mobile app ([https://itunes.apple.com/us/app/kryptofolio+tax/id921388783?ls=1&mt=8 iPhone], [https://play.google.com/store/apps/details?id=com.hydro.bitcoin_accounts Android], [http://apps.microsoft.com/windows/app/kryptofolio-tax/ee888fae-f5db-4bda-b7fb-7ce2a75b9758 Windows Store]/[http://www.windowsphone.com/s?appid=898edda1-1c94-4424-b1a7-216026fe86f7 Phone]) with a fully configurable FIFO (first in first out) portfolio manager and additionally tax calculator for bitcoin, litecoin and other custom configurable crypto-currencies. It works by setting up percentage cuts of capital gain, sales and flat values on specific transaction types. So can therefore be configured to be used in almost any jurisdiction as a supplement to current tax arrangements. It can import transactions either from blockchain.info or via a csv file import direct from a wallet export for all crypto-currencies. For maximum privacy, transactions can be converted to QR codes to be scanned directly into the device without being broadcast. PnL and tax contributions can then be exported and then used to prepare a tax return.<br />
<br />
===BitPrices===<br />
<br />
[http://https://github.com/dan-da/bitprices BitPrices] is an open-source command-line tool with a companion website [http://mybitprices.info mybitprices.info] intended for auditing wallet transactions and determining cost basis using historical prices using publicly available data. The website is free to use and does not require any registration or login. The tool can generate highly customizable transaction reports as well as a schedule D report with realized gains. FIFO and LIFO cost-basis methods are supported. By default it detects intra-wallet transfers and ignores those. This tool requires a list of all Bitcoin addresses in your wallet including change addresses. A companion tool, [https://github.com/dan-da/hd-wallet-addrs hd-wallet-addrs] is available that discovers all wallets addresses in an HD wallet.<br />
<br />
==See Also==<br />
<br />
* [[:Category:Legal|Legal]] category<br />
* [[Petition against illegal use]]<br />
* [[Petition for illegal use]]<br />
* [http://www.mscs.dal.ca/~selinger/accounting/tutorial.html Tutorial on multiple currency accounting]<br />
* [http://www.taxanalysts.com/www/features.nsf/Articles/C1A7ED502DD2B84685257AAF0056A2A2 Digital Currency: A New Worry for Tax Administrators?] by David D. Stewart and Stephanie Soong Johnston<br />
* [http://github.com/weex/BTCReporter BTCReporter] ([http://bitcointalk.org/index.php?topic=56504 info]) analyzes your MtGox trading logs<br />
* [http://www.gao.gov/products/gao-13-516 GAO-13-516 - VIRTUAL ECONOMIES AND CURRENCIES] ([http://www.gao.gov/assets/660/654620.pdf PDF Only)])<br />
* [http://www.ustream.tv/recorded/34595935 Video: GAO - Virtual Currencies and Taxes]<br />
* [http://bitcoin.accountants Bitcoin.Accountants - Nowell Associates Limited for UK Tax Treatment of Bitcoins]<br />
* [https://bitcoin.tax BitcoinTaxes]<br />
* [http://www.kryptofolio-tax.com Kryptofolio+tax - Mobile Bitcoin and Altcoin tax calculation app (iPhone, Android, Windows Phone/Store)]<br />
<br />
==References==<br />
<references /><br />
<br />
[[Category:Financial]]<br />
[[Category:Legal]]</div>Danda