API Reference

Coin class

class bitcart.coin.Coin

Bases: object

Coins should reimplement some methods, and initialize coin-specific info. Required information is: coin_name str friendly_name str providers list For more info see the docs.

balance() → dict

Get balance of wallet

Example:

>>> self.balance()
{"confirmed": "0.00005", "unconfirmed": 0, "unmatured": 0}
Raises:NotImplementedError – Implement in your subclass
Returns:dict – It should return dict of balance statuses
coin_name = 'Base'
friendly_name = 'Base'
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': {'partial': False,...
Parameters:address (str) – address to get transactions for
Raises:NotImplementedError – Override this method in subclass
Returns:list – List of transactions
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
Raises:NotImplementedError – Implement in your subclass
Returns:dict – transaction info
help() → list

Get help

Returns a list of all available RPC methods

Raises:NotImplementedError – Implement in your subclass
Returns:list – RPC methods list
providers = []

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, session: Optional[requests.Session] = None)

Bases: bitcart.coin.Coin

ALLOWED_EVENTS = ['new_block', 'new_transaction', 'new_payment']
RPC_PASS = 'electrumz'
RPC_URL = 'http://localhost:5000'
RPC_USER = 'electrum'
add_event_handler(events: Union[Iterable[str], str], func: Callable) → None

Add event handler to handle event(s) provided

Parameters:
  • self (BTC) – self
  • events (Union[Iterable[str], str]) – event or events
  • func (Callable) – function to handle those
Returns:

None – None

addinvoice(amount: Union[int, float], message: Optional[str] = '') → str

Create lightning invoice

Create lightning invoice and return bolt invoice id

Example:

>>> a.addinvoice(0.5)
'lnbc500m1pwnt87fpp5d60sykcjd2swk72t3g0njwmdytfe4fu65fz5v...'
Parameters:
  • self (BTC) – self
  • amount (Union[int,float]) – invoice amount
  • message (Optional[str], optional) – Invoice message. Defaults to “”.
Returns:

str – bolt invoice id

addrequest(amount: Union[int, float], 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.addrequest(0.5, "My invoice", 20)
{'time': 1562762334, 'amount': 50000000, 'exp': 1200, 'address': 'xxx',...
Parameters:
  • self (BTC) – self
  • amount (Union[int, float]) – amount to open invoice
  • description (str, optional) – Description of invoice. Defaults to “”.
  • expire (Union[int, float], optional) – The time invoice will expire in. Defaults to 15.
Returns:

dict – Invoice data

balance() → dict

Get balance of wallet

Example:

>>> self.balance()
{"confirmed": "0.00005", "unconfirmed": 0, "unmatured": 0}
Raises:NotImplementedError – Implement in your subclass
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 = 'BTC'
configure_webhook(autoconfigure: bool = True) → None
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
friendly_name = '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': {'partial': False,...
Parameters:address (str) – address to get transactions for
Raises:NotImplementedError – Override this method in subclass
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_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
Raises:NotImplementedError – Implement in your subclass
Returns:dict – transaction info
getrequest(address: str) → dict

Get invoice info

Get invoice information by address got from addrequest

Example:

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

dict – Invoice data

handle_webhook_async(request: web.Request) → web.Response
handle_webhook_sync() → dict
help() → list

Get help

Returns a list of all available RPC methods

Raises:NotImplementedError – Implement in your subclass
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
lnpay(invoice: str) → bool

Pay lightning invoice

Returns True on success, False otherwise

Parameters:invoice (str) – invoice to pay
Returns:bool – success or not
node_id

Get node id

Electrum’s lightning implementation itself is a lightning node, that way you can get a super light node, this method returns it’s id

Example:

>>> a.node_id
'030ff29580149a366bdddf148713fa808f0f4b934dccd5f7820f3d613e03c86e55'
Returns:str – id of your node
on(events: Union[Iterable[str], str]) → Callable

Register on event

Register callback function to be run when event is emmited

All available events are accessable as:

>>> btc.ALLOWED_EVENTS
['new_block', 'new_transaction']

Function signature must be

def handler(event, **kwargs):

kwargs sent differ from event to event, as for now new_block event sends height kwarg as new block height new_transaction event sends tx kwarg as tx_hash of new transaction

Parameters:
  • self (BTC) – self
  • events (Union[Iterable[str], str]) – event name or list of events for function to be run on
Returns:

Callable – It is a decorator

open_channel(node_id: str, amount: Union[int, float]) → 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 (Union[int, float]) – amount to open channel
Returns:

str – string of format txid:output_index

pay_to(address: str, amount: float, fee: Union[float, Callable, None] = None, feerate: Optional[float] = 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 (float) – amount of bitcoins to send
  • fee (Optional[Union[float, Callable]], optional) – Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.
  • feerate (Optional[float], 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:
  • ValueError – If address or amount is invalid or in other cases
  • 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: Union[float, Callable, None] = None, feerate: Optional[float] = 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[float, Callable]], optional) – Either a fixed fee, or a callable getting size and default fee as argument and returning fee. Defaults to None.
  • feerate (Optional[float], 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:
  • ValueError – If address or amount is invalid or in other cases
  • 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] = 2) → None
poll_updates_sync(timeout: Union[int, float] = 2) → 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 2.
Raises:

InvalidEventError – If server sent invalid event name not matching ALLOWED_EVENTS

Returns:

None – This function runs forever

process_updates(updates: Iterable[dict]) → None
providers = ['jsonrpcrequests']
rate(currency: str = 'USD', accurate: bool = False) → Union[float, 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”.
  • accurate (bool, optional) – Whether to return values harder to work with(decimals) or not very accurate floats. Defaults to False.
Returns:

Union[float, 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

start_webhook(port: int = 6000, **kwargs) → None
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

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, session: Optional[requests.Session] = None)

Bases: bitcart.coins.btc.BTC

RPC_URL = 'http://localhost:5001'
coin_name = 'LTC'
friendly_name = 'Litecoin'

GZRO

GZRO 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 GZRO_LIGHTNING environment variable). If lightning is disabled, LightningDisabledError is raised when calling lightning methods.

class bitcart.coins.gzro.GZRO(rpc_url: Optional[str] = None, rpc_user: Optional[str] = None, rpc_pass: Optional[str] = None, xpub: Optional[str] = None, session: Optional[requests.Session] = None)

Bases: bitcart.coins.btc.BTC

RPC_URL = 'http://localhost:5002'
coin_name = 'GZRO'
friendly_name = 'GravityZero'