lbry-sdk/lbry/db/database.py

220 lines
8.6 KiB
Python
Raw Normal View History

2020-05-01 15:29:44 +02:00
import os
2020-04-11 23:27:41 +02:00
import asyncio
2020-05-01 15:29:44 +02:00
from typing import List, Optional, Tuple, Iterable
from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
from functools import partial
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
from sqlalchemy import create_engine, text
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
from lbry.crypto.bip32 import PubKey
from lbry.blockchain.ledger import Ledger
from lbry.blockchain.transaction import Transaction, Output
from .constants import TXO_TYPES, CLAIM_TYPE_CODES
from . import queries as q
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
def clean_wallet_account_ids(constraints):
wallet = constraints.pop('wallet', None)
account = constraints.pop('account', None)
2020-04-11 23:27:41 +02:00
accounts = constraints.pop('accounts', [])
2020-05-01 15:29:44 +02:00
if account and not accounts:
accounts = [account]
if wallet:
constraints['wallet_account_ids'] = [account.id for account in wallet.accounts]
if not accounts:
accounts = wallet.accounts
2020-04-11 23:27:41 +02:00
if accounts:
2020-05-01 15:29:44 +02:00
constraints['account_ids'] = [account.id for account in accounts]
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
def add_channel_keys_to_txo_results(accounts: List, txos: Iterable[Output]):
sub_channels = set()
for txo in txos:
if txo.claim.is_channel:
for account in accounts:
private_key = account.get_channel_private_key(
txo.claim.channel.public_key_bytes
)
if private_key:
txo.private_key = private_key
break
if txo.channel is not None:
sub_channels.add(txo.channel)
if sub_channels:
add_channel_keys_to_txo_results(accounts, sub_channels)
2020-04-11 23:27:41 +02:00
class Database:
2020-05-01 15:29:44 +02:00
def __init__(self, ledger: Ledger, url: str, multiprocess=False):
2020-04-11 23:27:41 +02:00
self.url = url
2020-05-01 15:29:44 +02:00
self.ledger = ledger
self.multiprocess = multiprocess
self.executor: Optional[Executor] = None
2020-04-12 02:01:10 +02:00
2020-05-01 15:29:44 +02:00
def sync_create(self, name):
engine = create_engine(self.url)
db = engine.connect()
db.execute(text("COMMIT"))
db.execute(text(f"CREATE DATABASE {name}"))
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def create(self, name):
return await asyncio.get_event_loop().run_in_executor(None, self.sync_create, name)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
def sync_drop(self, name):
engine = create_engine(self.url)
db = engine.connect()
db.execute(text("COMMIT"))
db.execute(text(f"DROP DATABASE IF EXISTS {name}"))
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def drop(self, name):
return await asyncio.get_event_loop().run_in_executor(None, self.sync_drop, name)
2020-04-11 23:27:41 +02:00
async def open(self):
2020-05-01 15:29:44 +02:00
assert self.executor is None, "Database already open."
kwargs = dict(
initializer=q.initialize,
initargs=(self.url, self.ledger)
)
if self.multiprocess:
self.executor = ProcessPoolExecutor(
max_workers=max(os.cpu_count()-1, 4), **kwargs
)
else:
self.executor = ThreadPoolExecutor(
max_workers=1, **kwargs
)
return await self.run_in_executor(q.check_version_and_create_tables)
2020-04-11 23:27:41 +02:00
async def close(self):
2020-05-01 15:29:44 +02:00
if self.executor is not None:
self.executor.shutdown()
self.executor = None
async def run_in_executor(self, func, *args, **kwargs):
if kwargs:
clean_wallet_account_ids(kwargs)
return await asyncio.get_event_loop().run_in_executor(
self.executor, partial(func, *args, **kwargs)
2020-04-11 23:27:41 +02:00
)
2020-05-01 15:29:44 +02:00
async def execute_fetchall(self, sql):
return await self.run_in_executor(q.execute_fetchall, sql)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_best_height(self):
return await self.run_in_executor(q.get_best_height)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_blocks_without_filters(self):
return await self.run_in_executor(q.get_blocks_without_filters)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_transactions_without_filters(self):
return await self.run_in_executor(q.get_transactions_without_filters)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_block_tx_addresses(self, block_hash=None, tx_hash=None):
return await self.run_in_executor(q.get_block_tx_addresses, block_hash, tx_hash)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_block_address_filters(self):
return await self.run_in_executor(q.get_block_address_filters)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_transaction_address_filters(self, block_hash):
return await self.run_in_executor(q.get_transaction_address_filters, block_hash)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def insert_transaction(self, tx):
return await self.run_in_executor(q.insert_transaction, tx)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def update_address_used_times(self, addresses):
return await self.run_in_executor(q.update_address_used_times, addresses)
2020-04-11 23:27:41 +02:00
async def reserve_outputs(self, txos, is_reserved=True):
txo_hashes = [txo.hash for txo in txos]
if txo_hashes:
2020-05-01 15:29:44 +02:00
return await self.run_in_executor(
q.reserve_outputs, txo_hashes, is_reserved
2020-04-11 23:27:41 +02:00
)
async def release_outputs(self, txos):
2020-05-01 15:29:44 +02:00
return await self.reserve_outputs(txos, is_reserved=False)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def release_tx(self, tx):
return await self.release_outputs([txi.txo_ref.txo for txi in tx.inputs])
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def release_all_outputs(self, account):
return await self.run_in_executor(q.release_all_outputs, account.id)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_balance(self, **constraints):
return await self.run_in_executor(q.get_balance, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_supports_summary(self, **constraints):
return await self.run_in_executor(self.get_supports_summary, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_addresses(self, **constraints) -> Tuple[List[dict], Optional[int]]:
addresses, count = await self.run_in_executor(q.get_addresses, **constraints)
if addresses and 'pubkey' in addresses[0]:
2020-04-11 23:27:41 +02:00
for address in addresses:
address['pubkey'] = PubKey(
self.ledger, bytes(address.pop('pubkey')), bytes(address.pop('chain_code')),
address.pop('n'), address.pop('depth')
)
2020-05-01 15:29:44 +02:00
return addresses, count
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_all_addresses(self):
return await self.run_in_executor(q.get_all_addresses)
2020-04-11 23:27:41 +02:00
async def get_address(self, **constraints):
2020-05-01 15:29:44 +02:00
addresses, _ = await self.get_addresses(limit=1, **constraints)
2020-04-11 23:27:41 +02:00
if addresses:
return addresses[0]
async def add_keys(self, account, chain, pubkeys):
2020-05-01 15:29:44 +02:00
return await self.run_in_executor(q.add_keys, account, chain, pubkeys)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_raw_transactions(self, tx_hashes):
return await self.run_in_executor(q.get_raw_transactions, tx_hashes)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_transactions(self, **constraints) -> Tuple[List[Transaction], Optional[int]]:
return await self.run_in_executor(q.get_transactions, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_transaction(self, **constraints) -> Optional[Transaction]:
txs, _ = await self.get_transactions(limit=1, **constraints)
if txs:
return txs[0]
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_purchases(self, **constraints) -> Tuple[List[Output], Optional[int]]:
return await self.run_in_executor(q.get_purchases, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def search_claims(self, **constraints):
return await self.run_in_executor(q.search, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_txo_sum(self, **constraints):
return await self.run_in_executor(q.get_txo_sum, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_txo_plot(self, **constraints):
return await self.run_in_executor(q.get_txo_plot, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_txos(self, **constraints) -> Tuple[List[Output], Optional[int]]:
txos = await self.run_in_executor(q.get_txos, **constraints)
if 'wallet' in constraints:
add_channel_keys_to_txo_results(constraints['wallet'], txos)
return txos
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_utxos(self, **constraints) -> Tuple[List[Output], Optional[int]]:
return await self.get_txos(is_spent=False, **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_supports(self, **constraints) -> Tuple[List[Output], Optional[int]]:
return await self.get_utxos(txo_type=TXO_TYPES['support'], **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_claims(self, **constraints) -> Tuple[List[Output], Optional[int]]:
txos, count = await self.run_in_executor(q.get_claims, **constraints)
if 'wallet' in constraints:
add_channel_keys_to_txo_results(constraints['wallet'].accounts, txos)
return txos, count
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_streams(self, **constraints) -> Tuple[List[Output], Optional[int]]:
return await self.get_claims(txo_type=TXO_TYPES['stream'], **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_channels(self, **constraints) -> Tuple[List[Output], Optional[int]]:
return await self.get_claims(txo_type=TXO_TYPES['channel'], **constraints)
2020-04-11 23:27:41 +02:00
2020-05-01 15:29:44 +02:00
async def get_collections(self, **constraints) -> Tuple[List[Output], Optional[int]]:
return await self.get_claims(txo_type=TXO_TYPES['collection'], **constraints)