-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathapp.py
384 lines (332 loc) · 13.8 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
from cProfile import label
import sys
from urllib.request import HTTPDefaultErrorHandler
from PyQt6 import QtWidgets, uic, QtGui, QtCore
from PyQt6.QtCore import Qt, QThread
from PyQt6.QtWidgets import QWidget, QTableWidget
import asyncio
import os
import json
import time
from datetime import datetime
import base64
from itertools import groupby
from operator import itemgetter
from typing import List
from cashu.wallet import migrations
from cashu.wallet.crud import get_reserved_proofs, get_lightning_invoices
from cashu.core.helpers import fee_reserve, sum_proofs
from cashu.core.migrations import migrate_databases
from cashu.wallet.wallet import Wallet as Wallet
from cashu.core.settings import (
CASHU_DIR,
DEBUG,
ENV_FILE,
LIGHTNING,
MINT_URL,
VERSION,
TOR,
)
from cashu.core.base import Proof, Invoice
import worker
import os
walletname = "wallet"
wallet = Wallet(MINT_URL, os.path.join(CASHU_DIR, walletname))
def table_headers(table: QTableWidget, headers: List[str]):
table.setRowCount(table.rowCount() - 1)
table.setColumnCount(len(headers))
table.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignLeft)
table.setHorizontalHeaderLabels(headers)
table.resizeColumnsToContents()
table.resizeRowsToContents()
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class App:
def __init__(self):
self.thread = None
self.window = uic.loadUi(resource_path("ui/mainwindow.ui"))
self.window.button_send.clicked.connect(self.button_send_clicked)
self.window.button_receive.clicked.connect(self.button_receive_clicked)
self.window.button_pay.clicked.connect(self.button_pay_clicked)
self.window.button_invoice.clicked.connect(self.button_invoice_clicked)
self.window.show()
self.async_warpper(self.init_wallet)
self.set_app_icon()
self.init_mainwindow()
app.exec()
return
async def init_wallet(self):
"""Performs migrations and loads proofs from db."""
await migrate_databases(wallet.db, migrations)
await wallet.load_proofs()
# await wallet.load_mint()
self.load_mint_worker()
self.mint_label_update_worker()
self.update_main_label()
def load_mint_worker(self):
def load_mint_ready():
self.update_main_label()
self.mint_worker = worker.LoadMintWorker(wallet)
self.load_mint_thread = QThread()
self.mint_worker.finished.connect(load_mint_ready)
self.mint_worker.moveToThread(self.load_mint_thread)
self.load_mint_thread.started.connect(self.mint_worker.procLoadMint)
self.load_mint_thread.start()
def mint_label_update_worker(self):
"""Updates the mint label every n seconds"""
def update_wallet_state():
self.update_main_label()
self.wallet_state_worker = worker.UpdateWalletStateWorker(wallet)
self.wallet_state_thread = QThread()
self.wallet_state_worker.update.connect(update_wallet_state)
self.wallet_state_worker.moveToThread(self.wallet_state_thread)
self.wallet_state_thread.started.connect(
self.wallet_state_worker.procCheckWalletState
)
self.wallet_state_thread.start()
def check_invoice_worker(self, invoice: Invoice):
# https://stackoverflow.com/questions/6783194/background-thread-with-qthread-in-pyqt
def invoice_worker_ready(status):
print(f"got data from worker: {status}")
if status == "paid":
self.window.text_field.setPlainText("Payment received.")
self.init_mainwindow()
self.invoice_worker = worker.CheckInvoiceWorker(
wallet.mint, invoice
) # no parent!
if self.thread:
self.thread.terminate()
self.thread = QThread(parent=self) # no parent!
self.invoice_worker.strReady.connect(invoice_worker_ready)
self.invoice_worker.moveToThread(self.thread)
self.invoice_worker.finished.connect(self.thread.quit)
self.thread.started.connect(self.invoice_worker.procCounter)
self.thread.start()
def set_app_icon(self):
# set app icon
app_icon = QtGui.QIcon()
app_icon.addFile("ui/icons/16x16.png", QtCore.QSize(16, 16))
app_icon.addFile("ui/icons/24x24.png", QtCore.QSize(24, 24))
app_icon.addFile("ui/icons/32x32.png", QtCore.QSize(32, 32))
app_icon.addFile("ui/icons/48x48.png", QtCore.QSize(48, 48))
app_icon.addFile("ui/icons/256x256.png", QtCore.QSize(256, 256))
app_icon.addFile("ui/icons/512x512.png", QtCore.QSize(512, 512))
app.setWindowIcon(app_icon)
def update_main_label(self):
label_text = f"Cashu {VERSION}"
if TOR:
running = False
if hasattr(wallet, "tor"):
running = wallet.tor.is_running()
label_text += f" Tor: {'🟢' if running else '🔴'}"
label_text += "\n"
label_text += f"Mint: {wallet.url}"
self.window.label_mint_url.setText(label_text)
def init_mainwindow(self):
self.window.tabWidget.setTabText(0, "Tokens")
self.window.tabWidget.setTabText(1, "Pending")
self.update_main_label()
self.update_balance()
self.list_amounts()
self.list_pending()
self.list_invoices()
def update_balance(self):
self.window.label_balance.setText(f"{wallet.available_balance} sat")
def list_pending(self):
table: QTableWidget = self.window.table_pending
table.setRowCount(1)
async def run(*args, **kwargs):
reserved_proofs = await get_reserved_proofs(wallet.db)
if len(reserved_proofs):
sorted_proofs = sorted(reserved_proofs, key=itemgetter("send_id"))
for i, (key, value) in enumerate(
groupby(sorted_proofs, key=itemgetter("send_id"))
):
grouped_proofs = list(value)
coin = await wallet.serialize_proofs(grouped_proofs)
coin_hidden_secret = await wallet.serialize_proofs(
grouped_proofs, hide_secrets=True
)
reserved_date = datetime.utcfromtimestamp(
int(grouped_proofs[0].time_reserved)
).strftime("%Y-%m-%d %H:%M:%S")
rowPosition = table.rowCount() - 1
table.insertRow(rowPosition)
table.setItem(
rowPosition,
0,
QtWidgets.QTableWidgetItem(str(sum_proofs(grouped_proofs))),
)
table.setItem(rowPosition, 1, QtWidgets.QTableWidgetItem(str(coin)))
table.setItem(
rowPosition,
2,
QtWidgets.QTableWidgetItem(str(reserved_date) or "none"),
)
table.setItem(rowPosition, 3, QtWidgets.QTableWidgetItem(str(key)))
table_headers(table, ["amount", "token", "date", "id"])
self.async_warpper(run)
def list_amounts(self):
table: QTableWidget = self.window.table_tokens
table.setRowCount(1)
sorted_proofs = sorted(wallet.proofs, key=lambda p: p.amount)
for i, (key, value) in enumerate(groupby(sorted_proofs, lambda p: p.amount)):
grouped_proofs = list(value)
n_tokens = len(grouped_proofs)
if n_tokens < 1:
continue
rowPosition = table.rowCount() - 1
table.insertRow(rowPosition)
table.setItem(rowPosition, 0, QtWidgets.QTableWidgetItem(str(key)))
table.setItem(rowPosition, 1, QtWidgets.QTableWidgetItem(str(n_tokens)))
table.setItem(
rowPosition,
2,
QtWidgets.QTableWidgetItem(
str(sum([p.reserved or 0 for p in grouped_proofs]))
)
or "0",
)
table.setItem(
rowPosition,
3,
QtWidgets.QTableWidgetItem(
str(" ".join(set([p.id for p in grouped_proofs])))
),
)
table_headers(table, ["amount", "count", "reserved", "keyset"])
def list_invoices(self):
table: QTableWidget = self.window.table_invoices
table.setRowCount(1)
async def run(*args, **kwargs):
invoices: List[Invoice] = await get_lightning_invoices(db=wallet.db)
for invoice in invoices:
rowPosition = table.rowCount() - 1
table.insertRow(rowPosition)
table.setItem(
rowPosition, 0, QtWidgets.QTableWidgetItem(str(invoice.amount))
)
table.setItem(
rowPosition,
1,
QtWidgets.QTableWidgetItem(
str(f"{'paid' if invoice.paid else 'pending'}")
),
)
table.setItem(
rowPosition, 2, QtWidgets.QTableWidgetItem(str(invoice.pr))
)
table_headers(table, ["amount", "status", "invoice"])
table.cellDoubleClicked.connect(self.invoice_pending_clicked)
self.async_warpper(run)
def button_send_clicked(self, *args, **kwargs):
async def run(*args, **kwargs):
input = self.window.text_field.toPlainText()
try:
amount = int(input)
except:
print("no numeric amount in input field.")
return
if not amount > 0:
print("amount must be greater than 0.")
return
_, send_proofs = await wallet.split_to_send(
wallet.proofs, amount, set_reserved=True
)
coin = await wallet.serialize_proofs(send_proofs)
print(f"Send Clicked! {coin}")
self.window.text_field.setPlainText(coin)
self.async_warpper(run)
self.init_mainwindow()
def button_receive_clicked(self, *args, **kwargs):
async def run(*args, **kwargs):
input = self.window.text_field.toPlainText()
if len(input) < 16:
raise Exception("no proof provided.")
coin = input
proofs = [Proof(**p) for p in json.loads(base64.urlsafe_b64decode(coin))]
_, _ = await wallet.redeem(proofs)
print(f"Receive Clicked! {coin}")
self.window.text_field.setPlainText("")
self.async_warpper(run)
self.init_mainwindow()
def button_pay_clicked(self, *args, **kwargs):
print("Pay Clicked!")
async def run(*args, **kwargs):
input = self.window.text_field.toPlainText()
if len(input) < 16 or not input.startswith("lnbc"):
raise Exception("invalid Lightning invoice.")
invoice = input
proofs = await wallet.split_to_pay(invoice)
await wallet.pay_lightning(proofs, invoice)
self.window.text_field.setPlainText("Invoice paid.")
self.async_warpper(run)
self.init_mainwindow()
def button_invoice_clicked(self, *args, **kwargs):
print("Invoice Clicked!")
async def run(*args, **kwargs):
input = self.window.text_field.toPlainText()
try:
amount = int(input)
except:
print("no numeric amount in input field.")
return
if not amount > 0:
print("amount must be greater than 0.")
return
invoice = await wallet.request_mint(amount)
if invoice.pr:
self.window.text_field.setPlainText(invoice.pr)
# kick off the worker that checks this invoice
try:
self.check_invoice_worker(invoice)
except:
pass
return amount, invoice
amount, invoice = self.async_warpper(run)
self.init_mainwindow()
def invoice_pending_clicked(self, *args, **kwargs):
"""Activates when the user presses the "pending" cell in the invoice table."""
async def run(*args, **kwargs):
print(f"clicked {args}")
if args[1] == 1:
# pending column clicked
invoices: List[Invoice] = await get_lightning_invoices(db=wallet.db)
# get correct invoice
invoice = invoices[args[0]]
try:
await wallet.mint(invoice.amount, invoice.hash)
paid = True
self.window.text_field.setPlainText("Invoice paid.")
except Exception as e:
self.show_error(str(e))
pass
self.async_warpper(run, *args, **kwargs)
self.init_mainwindow()
async def printer(self):
while True:
time.sleep(1)
print("printer")
def async_warpper(self, f, *args, **kwargs):
try:
return asyncio.run(f(*args, **kwargs))
except Exception as e:
self.show_error(str(e))
return e
def show_error(self, msg):
dlg = QtWidgets.QMessageBox.critical(
self.window,
"Error",
f"Error: {msg}",
buttons=QtWidgets.QMessageBox.StandardButton.Ok,
)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setApplicationName("Cashu")
app = App()