API Reference

Implemented coins

BTC

BTC class supports lightning out of the box. For lightning methods to work, it must be enabled from the daemon (enabled by default and edited by BTC_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

class bitcart.coins.btc.BTC(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coin.Coin, bitcart.event_delivery.EventDelivery

ALLOWED_EVENTS = ['new_block', 'new_transaction', 'new_payment', 'verified_tx']
BALANCE_ATTRS = ['confirmed', 'unconfirmed', 'unmatured', 'lightning']
RPC_PASS = 'electrumz'
RPC_URL = 'http://localhost:5000'
RPC_USER = 'electrum'
add_invoice(amount: Union[int, str, decimal.Decimal], description: str = '', expire: Union[int, float] = 15) dict

Create a lightning invoice

Create a lightning invoice and return invoice data with bolt invoice id All parameters are the same as in add_request

Example:

>>> a.add_invoice(0.5, "My invoice", 20)
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'invoice': 'lnbc500m',...
Parameters
  • self (BTC) – self

  • amount (AmountType) – amount to open invoice

  • description (str, optional) – Description of invoice. Defaults to “”.

  • expire (Union[int, float], optional) – The time invoice will expire in. In minutes. Defaults to 15.

Returns

dict – Invoice data

add_request(amount: Optional[Union[int, str, decimal.Decimal]] = None, description: str = '', expire: Union[int, float] = 15) dict

Add invoice

Create an invoice and request amount in BTC, it will expire by parameter provided. If expire is None, it will last forever.

Example:

>>> c.add_request(0.5, "My invoice", 20)
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': 'xxx',...
Parameters
  • self (BTC) – self

  • amount (Optional[AmountType]) – amount to open invoice. Defaults to None.

  • description (str, optional) – Description of invoice. Defaults to “”.

  • expire (Union[int, float], optional) – The time invoice will expire in. In minutes. Defaults to 15.

Returns

dict – Invoice data

balance() dict

Get balance of wallet

Example:

>>> c.balance()
{"confirmed": 0.00005, "unconfirmed": 0, "unmatured": 0}
Returns

dict – It should return dict of balance statuses

close_channel(channel_id: str, force: bool = False) str

Close lightning channel

Close channel by channel_id got from open_channel, returns transaction id

Parameters
  • self (BTC) – self

  • channel_id (str) – channel_id from open_channel

  • force (bool) – Create new address beyond gap limit, if no more addresses are available.

Returns

str – tx_id of closed channel

coin_name: str = 'BTC'
connect(connection_string: str) bool

Connect to lightning node

connection string must respect format pubkey@ipaddress

Parameters

connection_string (str) – connection string

Returns

bool – True on success, False otherwise

event_handlers: Dict[str, Callable]
friendly_name: str = 'Bitcoin'
get_address(address: str) list

Get address history

This method should return list of transaction informations for specified address

Example:

>>> c.get_address("31smpLFzLnza6k8tJbVpxXiatGjiEQDmzc")
[{'tx_hash': '7854bdf4c4e27276ecc1fb8d666d6799a248f5e81bdd58b16432d1ddd1d4c332', 'height': 581878, 'tx': ...
Parameters

address (str) – address to get transactions for

Returns

list – List of transactions

get_config(key: str, default: Any = None) Any

Get config key

If the key doesn’t exist, default value is returned. Keys are stored in electrum’s config file, check bitcart.coins.btc.BTC.set_config() doc for details.

Example:

>>> c.get_config("x")
5
Parameters
  • self (BTC) – self

  • key (str) – key to get

  • default (Any, optional) – The value to default to when key doesn’t exist. Defaults to None.

Returns

Any – value of the key or default value provided

get_invoice(rhash: str) dict

Get lightning invoice info

Get lightning invoice information by rhash got from add_invoice

Example:

>>> c.get_invoice("e34d7fb4cda66e0760fc193496c302055d0fd960cfd982432355c8bfeecd5f33")
{'is_lightning': True, 'amount_BTC': Decimal('0.5'), 'timestamp': 1619273042, 'expiration': 900, ...
Parameters

rhash (str) – invoice rhash

Returns

dict – invoice data

get_request(address: str) dict

Get invoice info

Get invoice information by address got from add_request

Example:

>>> c.get_request("1A6jnc6xQwmhsChNLcyKAQNWPcWsVYqCqJ")
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': '1A6jnc6xQwmhsChNLcyKAQNWPcWsVYqCqJ',...
Parameters
  • self (BTC) – self

  • address (str) – address of invoice

Returns

dict – Invoice data

get_tx(tx: str) dict

Get transaction information

Given tx hash of transaction, return full information as dictionary

Example:

>>> c.get_tx("54604b116b28124e31d2d20bbd4561e6f8398dca4b892080bffc8c87c27762ba")
{'partial': False, 'version': 2, 'segwit_ser': True, 'inputs': [{'prevout_hash': 'xxxx',...
Parameters

tx (str) – tx_hash

Returns

dict – transaction info

help() list

Get help

Returns a list of all available RPC methods

Returns

list – RPC methods list

history() dict

Get transaction history of wallet

Example:

>>> c.history()
{'summary': {'end_balance': '0.', 'end_date': None, 'from_height': None, 'incoming': '0.00185511',...
Parameters

self (BTC) – self

Returns

dict – dictionary with some data, where key transactions is list of transactions

list_channels() list

List all channels ever opened

Possible channel statuses: OPENING, OPEN, CLOSED, DISCONNECTED

Example:

>>> a.server.list_channels()
[{'local_htlcs': {'adds': {}, 'locked_in': {}, 'settles': {}, 'fails': {}}, 'remote_htlcs': ...
Returns

list – list of channels

list_fiat() Iterable[str]

List of all available fiat currencies to get price for

This list is list of only valid currencies that could be passed to rate() function

Example:

>>> c.list_fiat()
['AED', 'ARS', 'AUD', 'BCH', 'BDT', 'BHD', 'BMD', 'BNB', 'BRL', 'BTC', ...]
Parameters

self (BTC) – self

Returns

Iterable[str] – list of available fiat currencies

list_peers(gossip: bool = False) list

Get a list of lightning peers

Parameters

gossip (bool, optional) – Whether to return peers of a gossip (one per node) or of a wallet. Defaults to False.

Returns

list – list of lightning peers

lnpay(invoice: str) bool

Pay lightning invoice

Returns True on success, False otherwise

Parameters

invoice (str) – invoice to pay

Returns

bool – success or not

property node_id: Any

Return an attribute of instance, which is of type owner.

open_channel(node_id: str, amount: Union[int, str, decimal.Decimal]) str

Open lightning channel

Open channel with node, returns string of format txid:output_index

Parameters
  • self (BTC) – self

  • node_id (str) – id of node to open channel with

  • amount (AmountType) – amount to open channel

Returns

str – string of format txid:output_index

pay_to(address: str, amount: Union[int, str, decimal.Decimal], fee: Optional[Union[int, str, decimal.Decimal, Callable]] = None, feerate: Optional[Union[int, str, decimal.Decimal]] = None, broadcast: bool = True) Union[dict, str]

Pay to address

This function creates a transaction, your wallet must have sufficent balance and address must exist.

Examples:

>>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt", 0.001)
'608d9af34032868fd2849723a4de9ccd874a51544a7fba879a18c847e37e577b'
>>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001, feerate=1)
'23d0aec06f6ea6100ba9c6ce8a1fa5d333a6c1d39a780b5fadc4b2836d71b66f'
>>> btc.pay_to("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt", 0.001, broadcast=False)
{'hex': '02000000026.....', 'complete': True, 'final': False, 'name': None, 'csv_delay': 0, 'cltv_expiry': 0}
Parameters
  • self (BTC) – self

  • address (str) – address where to send BTC

  • amount (AmountType) – amount of bitcoins to send

  • fee (Optional[Union[AmountType, Callable]], optional) – Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.

  • feerate (Optional[AmountType], optional) – A sat/byte feerate, can’t be passed together with fee argument. Defaults to None.

  • broadcast (bool, optional) – Whether to broadcast transaction to network. Defaults to True.

Raises

TypeError – if you have provided both fee and feerate

Returns

Union[dict, str] – tx hash of ready transaction or raw transaction, depending on broadcast argument.

pay_to_many(outputs: Iterable[Union[dict, tuple]], fee: Optional[Union[int, str, decimal.Decimal, Callable]] = None, feerate: Optional[Union[int, str, decimal.Decimal]] = None, broadcast: bool = True) Union[dict, str]

Pay to multiple addresses(batch transaction)

This function creates a batch transaction, your wallet must have sufficent balance and addresses must exist. outputs parameter is either an iterable of (address, amount) tuples(or any iterables) or a dict with two keys: address and amount {"address": "someaddress", "amount": 0.5}

Examples:

>>> btc.pay_to_many([{"address":"mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt","amount":0.001}, {"address":"mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB","amount":0.0001}])
'60fa120d9f868a7bd03d6bbd1e225923cab0ba7a3a6b961861053c90365ed40a'
>>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)])
'd80f14e20af2ceaa43a8b7e15402d420246d39e235d87874f929977fb0b1cab8'
>>> btc.pay_to_many((("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001)), feerate=1)
'0a6611876e04a6f2742eac02d4fac4c242dda154d85f0d547bbac1a33dbbbe34'
>>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)], broadcast=False)
{'hex': '0200000...', 'complete': True, 'final': False}
Parameters
  • self (BTC) – self

  • outputs (Iterable[Union[dict, tuple]]) – An iterable with dictionary or iterable as the item

  • fee (Optional[Union[AmountType, Callable]], optional) – Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.

  • feerate (Optional[AmountType], optional) – A sat/byte feerate, can’t be passed together with fee argument. Defaults to None.

  • broadcast (bool, optional) – Whether to broadcast transaction to network. Defaults to True.

Raises

TypeError – if you have provided both fee and feerate

Returns

Union[dict, str] – tx hash of ready transaction or raw transaction, depending on broadcast argument.

poll_updates(timeout: Union[int, float] = 1) None

Poll updates

Poll daemon for new transactions in wallet, this will block forever in while True loop checking for new transactions

Example can be found on main page of docs

Parameters
  • self (BTC) – self

  • timeout (Union[int, float], optional) – seconds to wait before requesting transactions again. Defaults to 1.

Returns

None – This function runs forever

process_updates(updates: Iterable[dict], *args: Any, pass_instance: bool = False, **kwargs: Any) None
rate(currency: str = 'USD') decimal.Decimal

Get bitcoin price in selected fiat currency

It uses the same method as electrum wallet gets exchange rate-via different payment providers

Examples:

>>> c.rate()
9878.527
>>> c.rate("RUB")
757108.226
Parameters
  • self (BTC) – self

  • currency (str, optional) – Currency to get rate into. Defaults to “USD”.

Returns

Decimal – price of 1 bitcoin in selected fiat currency

set_config(key: str, value: Any) bool

Set config key to specified value

It sets the config value in electrum’s config store, usually $HOME/.electrum/config

You can set any keys and values using this function(as long as JSON serializable), and some are used to configure underlying electrum daemon.

Example:

>>> c.set_config("x", 5)
True
Parameters
  • self (BTC) – self

  • key (str) – key to set

  • value (Any) – value to set

Returns

bool – True on success, False otherwise

property spec: Any

Return an attribute of instance, which is of type owner.

start_websocket(reconnect_callback: Optional[Callable] = None, force_connect: bool = False, auto_reconnect: bool = True) None

Start a websocket connection to daemon

Parameters
  • reconnect_callback (Optional[Callable], optional) – Callback to be called right after each succesful connection. Defaults to None.

  • force_connect (bool, optional) – Whether to try reconnecting even on first failure (handshake) to daemon. Defaults to False.

  • auto_reconnect (bool, optional) – Whether to enable auto-reconnecting on websocket closing. Defaults to True.

validate_key(key: str) bool

Validate whether provided key is valid to restore a wallet

If the key is x/y/z pub/prv or electrum seed at the network daemon is running at, then it would be valid(True), else False

Examples:

>>> c.validate_key("test")
False
>>> c.validate_key("your awesome electrum seed")
True
>>> c.validate_key("x/y/z pub/prv here")
True
Parameters
  • self (BTC) – self

  • key (str) – key to check

Returns

bool – Whether the key is valid or not

xpub: Optional[str]

BCH

BCH supports Schnorr signatures, they are enabled out of the box

class bitcart.coins.bch.BCH(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.btc.BTC

AMOUNT_FIELD = 'amount (BCH)'
RPC_URL = 'http://localhost:5004'
coin_name: str = 'BCH'
event_handlers: Dict[str, Callable]
friendly_name: str = 'Bitcoin Cash'
history() dict

Get transaction history of wallet

Example:

>>> c.history()
{'summary': {'end_balance': '0.', 'end_date': None, 'from_height': None, 'incoming': '0.00185511',...
Parameters

self (BTC) – self

Returns

dict – dictionary with some data, where key transactions is list of transactions

property node_id: Any

Return an attribute of instance, which is of type owner.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

ETH

ETH support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

class bitcart.coins.eth.ETH(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.btc.BTC

ALLOWED_EVENTS = ['new_block', 'new_transaction', 'new_payment']
RPC_URL = 'http://localhost:5002'
coin_name: str = 'ETH'
event_handlers: Dict[str, Callable]
friendly_name: str = 'Ethereum'
get_address(*args: Any, **kwargs: Any) NoReturn

Get address history

This method should return list of transaction informations for specified address

Example:

>>> c.get_address("31smpLFzLnza6k8tJbVpxXiatGjiEQDmzc")
[{'tx_hash': '7854bdf4c4e27276ecc1fb8d666d6799a248f5e81bdd58b16432d1ddd1d4c332', 'height': 581878, 'tx': ...
Parameters

address (str) – address to get transactions for

Returns

list – List of transactions

history() dict

Get transaction history of wallet

Example:

>>> c.history()
{'summary': {'end_balance': '0.', 'end_date': None, 'from_height': None, 'incoming': '0.00185511',...
Parameters

self (BTC) – self

Returns

dict – dictionary with some data, where key transactions is list of transactions

property node_id: Any

Return an attribute of instance, which is of type owner.

pay_to_many(*args: Any, **kwargs: Any) NoReturn

Pay to multiple addresses(batch transaction)

This function creates a batch transaction, your wallet must have sufficent balance and addresses must exist. outputs parameter is either an iterable of (address, amount) tuples(or any iterables) or a dict with two keys: address and amount {"address": "someaddress", "amount": 0.5}

Examples:

>>> btc.pay_to_many([{"address":"mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt","amount":0.001}, {"address":"mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB","amount":0.0001}])
'60fa120d9f868a7bd03d6bbd1e225923cab0ba7a3a6b961861053c90365ed40a'
>>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)])
'd80f14e20af2ceaa43a8b7e15402d420246d39e235d87874f929977fb0b1cab8'
>>> btc.pay_to_many((("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001)), feerate=1)
'0a6611876e04a6f2742eac02d4fac4c242dda154d85f0d547bbac1a33dbbbe34'
>>> btc.pay_to_many([("mkHS9ne12qx9pS9VojpwU5xtRd4T7X7ZUt",0.001), ("mv4rnyY3Su5gjcDNzbMLKBQkBicCtHUtFB",0.0001)], broadcast=False)
{'hex': '0200000...', 'complete': True, 'final': False}
Parameters
  • self (BTC) – self

  • outputs (Iterable[Union[dict, tuple]]) – An iterable with dictionary or iterable as the item

  • fee (Optional[Union[AmountType, Callable]], optional) – Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.

  • feerate (Optional[AmountType], optional) – A sat/byte feerate, can’t be passed together with fee argument. Defaults to None.

  • broadcast (bool, optional) – Whether to broadcast transaction to network. Defaults to True.

Raises

TypeError – if you have provided both fee and feerate

Returns

Union[dict, str] – tx hash of ready transaction or raw transaction, depending on broadcast argument.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

BNB

BNB support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

class bitcart.coins.bnb.BNB(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.eth.ETH

RPC_URL = 'http://localhost:5006'
coin_name: str = 'BNB'
event_handlers: Dict[str, Callable]
friendly_name: str = 'Binance Smart Chain'
property node_id: Any

Return an attribute of instance, which is of type owner.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

SmartBCH —

SmartBCH support is based on our custom daemon implementation which tries to follow electrum APIs as closely as possible

class bitcart.coins.sbch.SBCH(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.eth.ETH

RPC_URL = 'http://localhost:5007'
coin_name: str = 'SBCH'
event_handlers: Dict[str, Callable]
friendly_name: str = 'Smart Bitcoin Cash'
property node_id: Any

Return an attribute of instance, which is of type owner.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

XRG

XRG supports Schnorr signatures, they are enabled out of the box

class bitcart.coins.xrg.XRG(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.bch.BCH

AMOUNT_FIELD = 'amount (XRG)'
RPC_URL = 'http://localhost:5005'
coin_name: str = 'XRG'
event_handlers: Dict[str, Callable]
friendly_name: str = 'Ergon'
property node_id: Any

Return an attribute of instance, which is of type owner.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

LTC

LTC class supports lightning out of the box. For lightning methods to work, it must be enabled from the daemon (enabled by default and edited by LTC_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

class bitcart.coins.ltc.LTC(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.btc.BTC

RPC_URL = 'http://localhost:5001'
coin_name: str = 'LTC'
event_handlers: Dict[str, Callable]
friendly_name: str = 'Litecoin'
property node_id: Any

Return an attribute of instance, which is of type owner.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

BSTY

BSTY class supports lightning out of the box. For lightning methods to work, it must be enabled from the daemon (enabled by default and edited by BSTY_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

class bitcart.coins.bsty.BSTY(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, proxy: Optional[str] = None, session: Optional[ClientSession] = None)

Bases: bitcart.coins.btc.BTC

RPC_URL = 'http://localhost:5003'
coin_name: str = 'BSTY'
event_handlers: Dict[str, Callable]
friendly_name: str = 'GlobalBoost'
property node_id: Any

Return an attribute of instance, which is of type owner.

server: RPCProxy
property spec: Any

Return an attribute of instance, which is of type owner.

xpub: Optional[str]

Utilities

bitcart.utils.bitcoins(amount: int) decimal.Decimal

Convert amount from satoshis to bitcoins

Parameters

amount (int) – amount in satoshis

Returns

Decimal – amount in bitcoins

async bitcart.utils.call_universal(func: Callable, *args: Any, **kwargs: Any) Any

Call a function: async or sync one. All passed arguments are passed to the function too

Parameters

func (Callable) – a function to call: either sync or async one

Returns

Any – function execution result

bitcart.utils.convert_amount_type(amount: str) decimal.Decimal

Convert amount from str to Decimal

Parameters

amount (str) – amount

Returns

Decimal

bitcart.utils.json_encode(obj: Any) Any

json.dumps supporting Decimals

Parameters

obj (Any) – any object

Returns

Any – return value of json.dumps

bitcart.utils.satoshis(amount: decimal.Decimal) int

Convert amount from bitcoins to satoshis

Parameters

amount (Decimal) – bitcoin amount

Returns

int – same amount in satoshis