当前位置: 首页 > 软件库 > Web3 > 开源货币/比特币 >

bitcoin-core

A modern Bitcoin Core REST and RPC client.
授权协议 Readme
开发语言 Python
所属分类 Web3、 开源货币/比特币
软件类型 开源软件
地区 不详
投 递 者 易焱
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

bitcoin-core

A modern Bitcoin Core REST and RPC client to execute administrative tasks, multiwallet operations and queries about network and the blockchain.

Status

Installation

Install the package via yarn:

yarn add bitcoin-core

or via npm:

Install the package via npm:

npm install bitcoin-core --save

Usage

Client(...args)

Arguments

  1. [agentOptions] (Object): Optional agent options to configure SSL/TLS.
  2. [headers=false] (boolean): Whether to return the response headers.
  3. [host=localhost] (string): The host to connect to.
  4. [logger=debugnyan('bitcoin-core')] (Function): Custom logger (by default, debugnyan).
  5. [network=mainnet] (string): The network
  6. [password] (string): The RPC server user password.
  7. [port=[network]] (string): The RPC server port.
  8. [ssl] (boolean|Object): Whether to use SSL/TLS with strict checking (boolean) or an expanded config (Object).
  9. [ssl.enabled] (boolean): Whether to use SSL/TLS.
  10. [ssl.strict] (boolean): Whether to do strict SSL/TLS checking (certificate must match host).
  11. [timeout=30000] (number): How long until the request times out (ms).
  12. [username] (number): The RPC server user name.
  13. [version] (string): Which version to check methods for (read more).
  14. [wallet] (string): Which wallet to manage (read more).

Examples

Using network mode

The network will automatically determine the port to connect to, just like the bitcoind and bitcoin-cli commands.

const Client = require('bitcoin-core');
const client = new Client({ network: 'regtest' });
Setting a custom port
const client = new Client({ port: 28332 });

Connecting to an SSL/TLS server with strict checking enabled

By default, when ssl is enabled, strict checking is implicitly enabled.

const fs = require('fs');
const client = new Client({
  agentOptions: {
    ca: fs.readFileSync('/etc/ssl/bitcoind/cert.pem')
  },
  ssl: true
});

Connecting to an SSL/TLS server without strict checking enabled

const client = new Client({
  ssl: {
    enabled: true,
    strict: false
  }
});

Using promises to process the response

client.getInfo().then((help) => console.log(help));

Using callbacks to process the response

Callback support was removed. Since every method returns a Promise, callbackify() (>node@v8.2.0) can be used, or for older node versions you can use the npm package callbackify.

util.callbackify(() => client.getInfo())((error, help) => console.log(help));

Returning headers in the response

For compatibility with other Bitcoin Core clients.

const client = new Client({ headers: true });

// Promise style with headers enabled:
client.getInfo().then(([body, headers]) => console.log(body, headers));

// Await style based on promises with headers enabled:
const [body, headers] = await client.getInfo();

Named parameters

Since version v0.14.0, it is possible to send commands via the JSON-RPC interface using named parameters instead of positional ones. This comes with the advantage of making the order of arguments irrelevant. It also helps improving the readability of certain function calls when leaving out arguments for their default value.

You must provide a version in the client arguments to enable named parameters.

const client = new Client({ version: '0.15.1' });

For instance, take the getBalance() call written using positional arguments:

const balance = await new Client().getBalance('*', 0);

It is functionally equivalent to using the named arguments account and minconf, leaving out include_watchonly (defaults to false):

const balance = await new Client({ version: '0.15.1' }).getBalance({
  account: '*',
  minconf: 0
});

This feature is available to all JSON-RPC methods that accept arguments.

Floating point number precision in JavaScript

Due to JavaScript's limited floating point precision, all big numbers (numbers with more than 15 significant digits) are returned as strings to prevent precision loss. This includes both the RPC and REST APIs.

Multiwallet

Since Bitcoin Core v0.15.0, it's possible to manage multiple wallets using a single daemon. This enables use-cases such as managing a personal and a business wallet simultaneously in order to simplify accounting and accidental misuse of funds.

Historically, the accounts feature was supposed to offer similar functionality, but it has now been replaced by this more powerful feature.

To enable Multi Wallet support, start by specifying the number of added wallets you would like to have available and loaded on the server using the -wallet argument multiple times. For convenience, the bitcoin-core docker image will be used, but it's not a requirement:

docker run --rm -it -p 18332:18332 ruimarinho/bitcoin-core:0.15-alpine \
  -printtoconsole \
  -server \
  -rpcauth='foo:e1fcea9fb59df8b0388f251984fe85$26431097d48c5b6047df8dee64f387f63835c01a2a463728ad75087d0133b8e6' \
  -regtest \
  -wallet=wallet1.dat \
  -wallet=wallet2.dat \
  -rpcallowip=172.17.0.0/16

Notice the rpcauth hash which has been previously generated for the password j1DuzF7QRUp-iSXjgewO9T_WT1Qgrtz_XWOHCMn_O-Y=. Do not copy and paste this hash ever beyond this exercise.

Instantiate a client for each wallet and execute commands targeted at each wallet:

const Client = require('bitcoin-core');

const wallet1 = new Client({
  network: 'regtest',
  wallet: 'wallet1.dat',
  username: 'foo',
  password: 'j1DuzF7QRUp-iSXjgewO9T_WT1Qgrtz_XWOHCMn_O-Y='
});

const wallet2 = new Client({
  network: 'regtest',
  wallet: 'wallet2.dat',
  username: 'foo',
  password: 'j1DuzF7QRUp-iSXjgewO9T_WT1Qgrtz_XWOHCMn_O-Y='
});

(async function() {
  await wallet2.generate(100);

  console.log(await wallet1.getBalance());
  // => 0
  console.log(await wallet2.getBalance());
  // => 50
}());

Version Checking

By default, all methods are exposed on the client independently of the version it is connecting to. This is the most flexible option as defining methods for unavailable RPC calls does not cause any harm and the library is capable of handling a Method not found response error correctly.

const client = new Client();

client.command('foobar');
// => RpcError: -32601 Method not found

However, if you prefer to be on the safe side, you can enable strict version checking. This will validate all method calls before executing the actual RPC request:

const client = new Client({ version: '0.12.0' });

client.getHashesPerSec();
// => Method "gethashespersec" is not supported by version "0.12.0"

If you want to enable strict version checking for the bleeding edge version, you may set a very high version number to exclude recently deprecated calls:

const client = new Client({ version: `${Number.MAX_SAFE_INTEGER}.0.0` });

client.getWork();
// => Throws 'Method "getwork" is not supported by version "9007199254740991.0.0"'.

To avoid potential issues with prototype references, all methods are still enumerable on the library client prototype.

RPC

Start the bitcoind with the RPC server enabled and optionally configure a username and password:

docker run --rm -it ruimarinho/bitcoin-core:0.12-alpine -printtoconsole -rpcuser=foo -rpcpassword=bar -server

These configuration values may also be set on the bitcoin.conf file of your platform installation.

By default, port 8332 is used to listen for requests in mainnet mode, or 18332 in testnet and regtest modes (the regtest change will be changed to 18443 in 0.16). Use the network property to initialize the client on the desired mode and automatically set the respective default port. You can optionally set a custom port of your choice too.

The RPC services binds to the localhost loopback network interface, so use rpcbind to change where to bind to and rpcallowip to whitelist source IP access.

Methods

All RPC methods are exposed on the client interface as a camelcase'd version of those available on bitcoind (see examples below).

For a more complete reference about which methods are available, check the RPC documentation on the Bitcoin Core Developer Reference website.

Examples
client.createRawTransaction([{ txid: '1eb590cd06127f78bf38ab4140c4cdce56ad9eb8886999eb898ddf4d3b28a91d', vout: 0 }], { 'mgnucj8nYqdrPFh2JfZSB1NmUThUGnmsqe': 0.13 });
client.sendMany('test1', { mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN: 0.1, mgnucj8nYqdrPFh2JfZSB1NmUThUGnmsqe: 0.2 }, 6, 'Example Transaction');
client.sendToAddress('mmXgiR6KAhZCyQ8ndr2BCfEq1wNG2UnyG6', 0.1,  'sendtoaddress example', 'Nemo From Example.com');

Batch requests

Batch requests are support by passing an array to the command method with a method and optionally, parameters. The return value will be an array with all the responses.

const batch = [
  { method: 'getnewaddress', parameters: [] },
  { method: 'getnewaddress', parameters: [] }
]

new Client().command(batch).then((responses) => console.log(responses)));

// Or, using ES2015 destructuring.
new Client().command(batch).then(([firstAddress, secondAddress]) => console.log(firstAddress, secondAddress)));

Note that batched requests will only throw an error if the batch request itself cannot be processed. However, each individual response may contain an error akin to an individual request.

const batch = [
  { method: 'foobar', parameters: [] },
  { method: 'getnewaddress', parameters: [] }
]

new Client().command(batch).then(([address, error]) => console.log(address, error)));
// => `mkteeBFmGkraJaWN5WzqHCjmbQWVrPo5X3, { [RpcError: Method not found] message: 'Method not found', name: 'RpcError', code: -32601 }`.

REST

Support for the REST interface is still experimental and the API is still subject to change. These endpoints are also unauthenticated so there are certain risks which you should be aware, specifically of leaking sensitive data of the node if not correctly protected.

Error handling is still fragile so avoid passing user input.

Start the bitcoind with the REST server enabled:

docker run --rm -it ruimarinho/bitcoin-core:0.12-alpine -printtoconsole -server -rest

These configuration values may also be set on the bitcoin.conf file of your platform installation. Use txindex=1 if you'd like to enable full transaction query support (note: this will take a considerable amount of time on the first run).

Methods

Unlike RPC methods which are automatically exposed on the client, REST ones are handled individually as each method has its own specificity. The following methods are supported:

getBlockByHash(hash, [options])

Given a block hash, returns a block, in binary, hex-encoded binary or JSON formats.

Arguments
  1. hash (string): The block hash.
  2. [options] (Object): The options object.
  3. [options.extension=json] (string): Return in binary (bin), hex-encoded binary (hex) or JSON (json) format.
Example
client.getBlockByHash('0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206', { extension: 'json' });

getBlockHeadersByHash(hash, count, [options])

Given a block hash, returns amount of block headers in upward direction.

Arguments
  1. hash (string): The block hash.
  2. count (number): The number of blocks to count in upward direction.
  3. [options] (Object): The options object.
  4. [options.extension=json] (string): Return in binary (bin), hex-encoded binary (hex) or JSON (json) format.
Example
client.getBlockHeadersByHash('0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206', 1, { extension: 'json' });

getBlockchainInformation()

Returns various state info regarding block chain processing.

Example
client.getBlockchainInformation();

getMemoryPoolContent()

Returns transactions in the transaction memory pool.

Example
client.getMemoryPoolContent();

getMemoryPoolInformation()

Returns various information about the transaction memory pool. Only supports JSON as output format.

  • size: the number of transactions in the transaction memory pool.
  • bytes: size of the transaction memory pool in bytes.
  • usage: total transaction memory pool memory usage.
Example
client.getMemoryPoolInformation();

getTransactionByHash(hash, [options])

Given a transaction hash, returns a transaction in binary, hex-encoded binary, or JSON formats.

Arguments

  1. hash (string): The transaction hash.
  2. [options] (Object): The options object.
  3. [options.summary=false] (boolean): Whether to return just the transaction hash, thus saving memory.
  4. [options.extension=json] (string): Return in binary (bin), hex-encoded binary (hex) or JSON (json) format.
Example
client.getTransactionByHash('b4dd08f32be15d96b7166fd77afd18aece7480f72af6c9c7f9c5cbeb01e686fe', { extension: 'json', summary: false });

getUnspentTransactionOutputs(outpoints, [options])

Query unspent transaction outputs (UTXO) for a given set of outpoints. See BIP64 for input and output serialisation.

Arguments

  1. outpoints (array<Object>|Object): The outpoint to query in the format { id: '<txid>', index: '<index>' }.
  2. [options] (Object): The options object.
  3. [options.extension=json] (string): Return in binary (bin), hex-encoded binary (hex) or JSON (json) format.
Example
client.getUnspentTransactionOutputs([{
  id: '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206',
  index: 0
}, {
  id: '0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206',
  index: 1
}], { extension: 'json' })

SSL

This client supports SSL out of the box. Simply pass the SSL public certificate to the client and optionally disable strict SSL checking which will bypass SSL validation (the connection is still encrypted but the server it is connecting to may not be trusted). This is, of course, discouraged unless for testing purposes when using something like self-signed certificates.

Generating a self-signed certificates for testing purposes

Please note that the following procedure should only be used for testing purposes.

Generate an self-signed certificate together with an unprotected private key:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 3650 -nodes

Connecting via SSL

On Bitcoin Core <0.12, you can start the bitcoind RPC server directly with SSL:

docker run --rm -it -v $(PWD)/ssl:/etc/ssl ruimarinho/bitcoin-core:0.11-alpine -printtoconsole -rpcuser=foo -rpcpassword=bar -rpcssl -rpcsslcertificatechainfile=/etc/ssl/bitcoind/cert.pem -rpcsslprivatekeyfile=/etc/ssl/bitcoind/key.pem -server

On Bitcoin Core >0.12, use must use stunnel (brew install stunnel or sudo apt-get install stunnel4) or an HTTPS reverse proxy to configure SSL since the built-in support for SSL has been removed. The trade off with stunnel is performance and simplicity versus features, as it lacks more powerful capacities such as Basic Authentication and caching which are standard in reverse proxies.

You can use stunnel by configuring stunnel.conf with the following service requirements:

[bitcoin]
accept = 28332
connect = 18332
cert = /etc/ssl/bitcoind/cert.pem
key = /etc/ssl/bitcoind/key.pem

The key option may be omitted if you concatenating your private and public certificates into a single stunnel.pem file.

On some versions of stunnel it is also possible to start a service using command line arguments. The equivalent would be:

stunnel -d 28332 -r 127.0.0.1:18332 -p stunnel.pem -P ''

Then pass the public certificate to the client:

const Client = require('bitcoin-core');
const fs = require('fs');
const client = new Client({
  agentOptions: {
    ca: fs.readFileSync('/etc/ssl/bitcoind/cert.pem')
  },
  port: 28332,
  ssl: true
});

Logging

By default, all requests made with bitcoin-core are logged using uphold/debugnyan with bitcoin-core as the logging namespace.

Please note that all sensitive data is obfuscated before calling the logger.

Example

Example output defining the environment variable DEBUG=bitcoin-core:

const client = new Client();

client.getTransactionByHash('b4dd08f32be15d96b7166fd77afd18aece7480f72af6c9c7f9c5cbeb01e686fe');

// {
//   "name": "bitcoin-core",
//   "hostname": "localhost",
//   "pid": 57908,
//   "level": 20,
//   "request": {
//     "headers": {
//       "host": "localhost:8332",
//       "accept": "application/json"
//     },
//     "id": "82cea4e5-2c85-4284-b9ec-e5876c84e67c",
//     "method": "GET",
//     "type": "request",
//     "uri": "http://localhost:8332/rest/tx/b4dd08f32be15d96b7166fd77afd18aece7480f72af6c9c7f9c5cbeb01e686fe.json"
//   },
//   "msg": "Making request 82cea4e5-2c85-4284-b9ec-e5876c84e67c to GET http://localhost:8332/rest/tx/b4dd08f32be15d96b7166fd77afd18aece7480f72af6c9c7f9c5cbeb01e686fe.json",
//   "time": "2017-02-07T14:40:35.020Z",
//   "v": 0
// }

Custom logger

A custom logger can be passed via the logger option and it should implement bunyan's log levels.

Tests

Currently the test suite is tailored for Docker (including docker-compose) due to the multitude of different bitcoind configurations that are required in order to get the test suite passing.

To test using a local installation of node.js but with dependencies (e.g. bitcoind) running inside Docker:

npm run dependencies
npm test

To test using Docker exclusively (similarly to what is done in Travis CI):

npm run testdocker

Release

npm version [<newversion> | major | minor | patch] -m "Release %s"

License

MIT

  • 学习区块链开发,当然是从比特币开始了 一、准备工作 1、京东、百度、阿里云任选一家买一个云主机,一年1000来块的配置就够了,主要是要挂一个500G以上的硬盘 2、linux-ubuntu1604,64位操作系统 二、搭建流程 1、客户端安装流程 # 下载 cd /home/disk500g wget https://bitcoin.org/bin/bitcoin-core-0.17.0.1/bi

  • 比特币核心部署 - bitcoin core for linux 1、准备服务器     最近在准备一个比特币钱包的项目,需要在CENTOS服务器上部署比特币钱包,由于该项目是部署的核心钱包,需要同步所有的blocks, 需要的磁盘空间大约在170G左右。 服务器的配置: CPU: 2核以上 内存: 2G以上 数据盘: 170G以上(注意需要专门增加一块存储盘,否则全节点区块链存不下) 带宽: 2

  • 作者:闪电HSL 第0章 引言 比特币(BTC)节点客户端在6月15日发布了最新的版本,Bitcoin core 0.16.1,本次更新有一部分内容是“Miner block size removed”,这一点被国内最知名的媒体平台们翻译错了,又因转载或抄袭的原因导致国内媒体几乎清一色地将此信息传播为bitcoin core0.16.1删除了区块大小限制——这意味着一次硬分叉。 本文解释“Mine

  • Finally I was able to create a raw transaction, sign it on the HSM and broadcast it. Here is my working example: The transaction from which I want to spend: { "error": null, "id": "1", "result": { "ha

  • 先读过前面几篇可能看起来更好点。。等我把所有的东西都写完后应该会重新整理,然后重新写一份更可读的吧(这是个flag) 该篇将会详细阐述 Bitcoin 的交易本质。同样,在本篇中不探讨区块,只讨论 Tx 在整个 bitcoin 系统中是如何运作的。本篇所用的术语承接于上一篇文章,并直接使用上一篇文章讨论的细节。 在整个bitcoin 的源码中,尤为重要的文件只有main.cpp/.h (还有scr

  • 这里有安装的方法 https://bitcoin.org/en/full-node#mac-os-x-yosemite-1010x 因为我们不要GUI,而且Bitcoin Core daemon (bitcoind) 不包括在dmg安装包里面的。 所以我们需要另外下载安装: 不建议源码安装,比较麻烦,还有需要安装一堆的依赖包。 1、下载: curl -O https://bitcoin.org/b

  • 1:通过SSLSocketFactory和HttpsURLConnection调用 参见azazar的bitcoin.jsonrpcclient 环境:JDK1.7  依赖:openssl 生成的server.cert和server.pem 导入server.cert到java keystore 1A:JKS keytool -import -alias aliasName -v -file C:

 相关资料
  • Bitcoin (比特币)是点对点(peer-to-peer)基于网络的匿名数字货币。点对点(peer-to-peer)的意思是指没有中央权威控制货币 的汇款通道。相反,这些货币转帐的任务是由网络节点进行的集体管理。匿名就意味着交易各方可以隐藏自己的真实身份。优势: 无需信托中间人,能够方便的进行互联网上的汇款。 第三方不能够控制或者阻止您的交易。 Bitcoin 交易几乎免费, 而信用卡的网上在

  • Bitcoin-Qt 是使用 Qt 开发的比特币客户端,目前该项目已经成为比特币官方的客户端,合并到比特币项目中,不再单独立项。

  • Bitcoin ETL Join Telegram Group Install Bitcoin ETL: pip install bitcoin-etl Export blocks and transactions (Schema, Reference): > bitcoinetl export_blocks_and_transactions --start-block 0 --end-block

  • BITCOIN WALLET Welcome to Bitcoin Wallet, a standalone Bitcoin payment app for your Android device! This project contains several sub-projects: wallet:The Android app itself. This is probably what you

  • Feature-rich toolkit for making Bitcoin and Lightning applications on the JVM. For a complete guide on how to get started with Bitcoin-S, see our website at Bitcoin-S.org. Contents What is bitcoin-s?

  • Translations ���� ελληνικά | ���� Français | ���� 한국어 | ���� 普通話 | ���� 台灣話 | ���� Español | ���� Türkçe | ���� Deutsch | ���� Italiano | ���� हिन्दी | Arabic | ���� Português | ���� Русский язык | ��

  • The Parity Bitcoin client. Gitter Installing from source Installing the snap Running tests Going online Importing bitcoind database Command line interface JSON-RPC Logging Internal Documentation Proje

  • 比特币项目的python简易实现,利用python实现一个完整的区块链项目 注意: 本项目属于业余项目,并不打算完全实现bitcoin全部协议,甚至会加一些不同的地方,比如最近正在思考利用V8+llvm实现虚拟机,说这个是为什么呢? 有些国人实在素质堪忧,上来就说不是完整实现,狂喷。 这里特别说明下,不伺候喷子,喷子请绕道吧! 从零用python实现简易比特币项目, 写一个完整的区块链。 加密算法

相关阅读

相关文章

相关问答

相关文档