lbry-sdk/lbry/wallet/usage_payment.py

60 lines
2.1 KiB
Python
Raw Normal View History

2020-01-06 05:29:48 +01:00
import asyncio
import logging
from lbry.wallet.dewies import lbc_to_dewies
from lbry.wallet.transaction import Output, Transaction
log = logging.getLogger(__name__)
class WalletServerPayer:
2020-02-12 02:05:49 +01:00
def __init__(self, payment_period=24 * 60 * 60):
self.ledger = None
self.wallet = None
2020-01-06 05:29:48 +01:00
self.running = False
self.task = None
2020-02-12 02:05:49 +01:00
self.payment_period = payment_period
self.analytics_manager = None
2020-01-06 05:29:48 +01:00
async def pay(self):
while self.running:
2020-02-12 02:05:49 +01:00
await asyncio.sleep(self.payment_period)
2020-01-06 05:29:48 +01:00
features = await self.ledger.network.get_server_features()
address = features['payment_address']
amount = str(features['daily_fee'])
if not address or not amount:
continue
2020-01-06 05:29:48 +01:00
if not self.ledger.is_valid_address(address):
2020-02-12 02:05:49 +01:00
log.warning("Invalid address from wallet server: '%s' - skipping payment round.", address)
continue
2020-01-06 05:29:48 +01:00
if self.wallet.is_locked:
2020-02-12 02:05:49 +01:00
log.warning("Cannot spend funds with locked wallet, skipping payment round.")
continue
2020-01-06 05:29:48 +01:00
amount = lbc_to_dewies(features['daily_fee']) # check that this is in lbc and not dewies
# todo: check that amount is less than our max
2020-02-12 02:05:49 +01:00
tx = await Transaction.create(
[],
[Output.pay_pubkey_hash(amount, self.ledger.address_to_hash160(address))],
self.wallet.get_accounts_or_all(None),
self.wallet.get_account_or_default(None)
)
2020-01-06 05:29:48 +01:00
await self.ledger.broadcast(tx)
2020-02-12 02:05:49 +01:00
if self.analytics_manager:
await self.analytics_manager.send_credits_sent()
2020-01-06 05:29:48 +01:00
2020-02-12 02:05:49 +01:00
async def start(self, ledger, default_wallet):
self.ledger = ledger
self.wallet = default_wallet
2020-01-06 05:29:48 +01:00
self.running = True
self.task = asyncio.ensure_future(self.pay())
self.task.add_done_callback(lambda _: log.info("Stopping wallet server payments."))
async def stop(self):
if self.running:
self.running = False
self.task.cancel()