|
| 1 | +#!/usr/bin/env python |
| 2 | +# |
| 3 | +# Electrum - lightweight Bitcoin client |
| 4 | +# Copyright (C) 2025 The Electrum Developers |
| 5 | +# |
| 6 | +# Permission is hereby granted, free of charge, to any person |
| 7 | +# obtaining a copy of this software and associated documentation files |
| 8 | +# (the "Software"), to deal in the Software without restriction, |
| 9 | +# including without limitation the rights to use, copy, modify, merge, |
| 10 | +# publish, distribute, sublicense, and/or sell copies of the Software, |
| 11 | +# and to permit persons to whom the Software is furnished to do so, |
| 12 | +# subject to the following conditions: |
| 13 | +# |
| 14 | +# The above copyright notice and this permission notice shall be |
| 15 | +# included in all copies or substantial portions of the Software. |
| 16 | +# |
| 17 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 18 | +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 19 | +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 20 | +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS |
| 21 | +# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN |
| 22 | +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 23 | +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 24 | +# SOFTWARE. |
| 25 | +import asyncio |
| 26 | +import ssl |
| 27 | +import time |
| 28 | +from contextlib import asynccontextmanager |
| 29 | + |
| 30 | +import electrum_ecc as ecc |
| 31 | +import electrum_aionostr as aionostr |
| 32 | +from electrum_aionostr.key import PrivateKey |
| 33 | +from typing import Dict, TYPE_CHECKING, Union, List, Tuple, Optional |
| 34 | + |
| 35 | +from electrum import util, Transaction |
| 36 | +from electrum.crypto import sha256 |
| 37 | +from electrum.i18n import _ |
| 38 | +from electrum.logging import Logger |
| 39 | +from electrum.plugin import BasePlugin |
| 40 | +from electrum.transaction import PartialTransaction, tx_from_any |
| 41 | +from electrum.util import log_exceptions, OldTaskGroup, ca_path, trigger_callback |
| 42 | +from electrum.wallet import Multisig_Wallet |
| 43 | + |
| 44 | +if TYPE_CHECKING: |
| 45 | + from electrum.wallet import Abstract_Wallet |
| 46 | + |
| 47 | +# event kind used for nostr messages (with expiration tag) |
| 48 | +NOSTR_EVENT_KIND = 4 |
| 49 | + |
| 50 | +now = lambda: int(time.time()) |
| 51 | + |
| 52 | + |
| 53 | +class PsbtNostrPlugin(BasePlugin): |
| 54 | + |
| 55 | + def __init__(self, parent, config, name): |
| 56 | + BasePlugin.__init__(self, parent, config, name) |
| 57 | + self.cosigner_wallets = {} # type: Dict[Abstract_Wallet, CosignerWallet] |
| 58 | + |
| 59 | + def is_available(self): |
| 60 | + return True |
| 61 | + |
| 62 | + def add_cosigner_wallet(self, wallet: 'Abstract_Wallet', cosigner_wallet: 'CosignerWallet'): |
| 63 | + assert isinstance(wallet, Multisig_Wallet) |
| 64 | + self.cosigner_wallets[wallet] = cosigner_wallet |
| 65 | + |
| 66 | + def remove_cosigner_wallet(self, wallet: 'Abstract_Wallet'): |
| 67 | + if cw := self.cosigner_wallets.get(wallet): |
| 68 | + cw.close() |
| 69 | + self.cosigner_wallets.pop(wallet) |
| 70 | + |
| 71 | + |
| 72 | +class CosignerWallet(Logger): |
| 73 | + # one for each open window (Qt) / open wallet (QML) |
| 74 | + # if user signs a tx, we have the password |
| 75 | + # if user receives a dm? needs to enter password first |
| 76 | + |
| 77 | + KEEP_DELAY = 24*60*60 |
| 78 | + |
| 79 | + def __init__(self, wallet: 'Multisig_Wallet'): |
| 80 | + assert isinstance(wallet, Multisig_Wallet) |
| 81 | + self.wallet = wallet |
| 82 | + self.network = wallet.network |
| 83 | + self.config = self.wallet.config |
| 84 | + |
| 85 | + Logger.__init__(self) |
| 86 | + self.known_events = wallet.db.get_dict('cosigner_events') |
| 87 | + for k, v in list(self.known_events.items()): |
| 88 | + if v < now() - self.KEEP_DELAY: |
| 89 | + self.logger.info(f'deleting old event {k}') |
| 90 | + self.known_events.pop(k) |
| 91 | + self.relays = self.config.NOSTR_RELAYS.split(',') |
| 92 | + self.ssl_context = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=ca_path) |
| 93 | + self.logger.info(f'relays {self.relays}') |
| 94 | + |
| 95 | + self.cosigner_list = [] # type: List[Tuple[str, str]] |
| 96 | + self.nostr_pubkey = None |
| 97 | + |
| 98 | + for key, keystore in wallet.keystores.items(): |
| 99 | + xpub = keystore.get_master_public_key() # type: str |
| 100 | + privkey = sha256('nostr_psbt:' + xpub) |
| 101 | + pubkey = ecc.ECPrivkey(privkey).get_public_key_bytes()[1:] |
| 102 | + if self.nostr_pubkey is None and not keystore.is_watching_only(): |
| 103 | + self.nostr_privkey = privkey.hex() |
| 104 | + self.nostr_pubkey = pubkey.hex() |
| 105 | + self.logger.info(f'nostr pubkey: {self.nostr_pubkey}') |
| 106 | + else: |
| 107 | + self.cosigner_list.append((xpub, pubkey.hex())) |
| 108 | + |
| 109 | + self.messages = asyncio.Queue() |
| 110 | + self.taskgroup = OldTaskGroup() |
| 111 | + if self.network and self.nostr_pubkey: |
| 112 | + asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop) |
| 113 | + |
| 114 | + @log_exceptions |
| 115 | + async def main_loop(self): |
| 116 | + self.logger.info("starting taskgroup.") |
| 117 | + try: |
| 118 | + async with self.taskgroup as group: |
| 119 | + await group.spawn(self.check_direct_messages()) |
| 120 | + except Exception as e: |
| 121 | + self.logger.exception("taskgroup died.") |
| 122 | + finally: |
| 123 | + self.logger.info("taskgroup stopped.") |
| 124 | + |
| 125 | + async def stop(self): |
| 126 | + await self.taskgroup.cancel_remaining() |
| 127 | + |
| 128 | + @asynccontextmanager |
| 129 | + async def nostr_manager(self): |
| 130 | + manager_logger = self.logger.getChild('aionostr') |
| 131 | + manager_logger.setLevel("INFO") # set to INFO because DEBUG is very spammy |
| 132 | + async with aionostr.Manager( |
| 133 | + relays=self.relays, |
| 134 | + private_key=self.nostr_privkey, |
| 135 | + ssl_context=self.ssl_context, |
| 136 | + # todo: add proxy support, first needs: |
| 137 | + # https://github.com/spesmilo/electrum-aionostr/pull/8 |
| 138 | + proxy=None, |
| 139 | + log=manager_logger |
| 140 | + ) as manager: |
| 141 | + yield manager |
| 142 | + |
| 143 | + @log_exceptions |
| 144 | + async def send_direct_messages(self, messages: List[Tuple[str, str]]): |
| 145 | + our_private_key: PrivateKey = aionostr.key.PrivateKey(bytes.fromhex(self.nostr_privkey)) |
| 146 | + async with self.nostr_manager() as manager: |
| 147 | + for pubkey, msg in messages: |
| 148 | + encrypted_msg: str = our_private_key.encrypt_message(msg, pubkey) |
| 149 | + eid = await aionostr._add_event( |
| 150 | + manager, |
| 151 | + kind=NOSTR_EVENT_KIND, |
| 152 | + content=encrypted_msg, |
| 153 | + private_key=self.nostr_privkey, |
| 154 | + tags=[['p', pubkey], ['expiration', str(int(now() + self.KEEP_DELAY))]]) |
| 155 | + self.logger.info(f'message sent to {pubkey}: {eid}') |
| 156 | + |
| 157 | + @log_exceptions |
| 158 | + async def check_direct_messages(self): |
| 159 | + privkey = PrivateKey(bytes.fromhex(self.nostr_privkey)) |
| 160 | + async with self.nostr_manager() as manager: |
| 161 | + await manager.connect() |
| 162 | + query = { |
| 163 | + "kinds": [NOSTR_EVENT_KIND], |
| 164 | + "limit": 100, |
| 165 | + "#p": [self.nostr_pubkey], |
| 166 | + "since": int(now() - self.KEEP_DELAY), |
| 167 | + } |
| 168 | + async for event in manager.get_events(query, single_event=False, only_stored=False): |
| 169 | + if event.id in self.known_events: |
| 170 | + self.logger.info(f'known event {event.id} {util.age(event.created_at)}') |
| 171 | + continue |
| 172 | + if event.created_at > now() + self.KEEP_DELAY: |
| 173 | + # might be malicious |
| 174 | + continue |
| 175 | + if event.created_at < now() - self.KEEP_DELAY: |
| 176 | + continue |
| 177 | + self.logger.info(f'new event {event.id}') |
| 178 | + try: |
| 179 | + message = privkey.decrypt_message(event.content, event.pubkey) |
| 180 | + except Exception as e: |
| 181 | + self.logger.info(f'could not decrypt message {event.pubkey}') |
| 182 | + self.known_events[event.id] = now() |
| 183 | + continue |
| 184 | + try: |
| 185 | + tx = tx_from_any(message) |
| 186 | + except Exception as e: |
| 187 | + self.logger.info(_("Unable to deserialize the transaction:") + "\n" + str(e)) |
| 188 | + self.known_events[event.id] = now() |
| 189 | + return |
| 190 | + self.logger.info(f"received PSBT from {event.pubkey}") |
| 191 | + trigger_callback('psbt_nostr_received', self.wallet, event.pubkey, event.id, tx) |
| 192 | + |
| 193 | + def diagnostic_name(self): |
| 194 | + return self.wallet.diagnostic_name() |
| 195 | + |
| 196 | + def close(self): |
| 197 | + self.logger.info("shutting down listener") |
| 198 | + asyncio.run_coroutine_threadsafe(self.stop(), self.network.asyncio_loop) |
| 199 | + |
| 200 | + def cosigner_can_sign(self, tx: Transaction, cosigner_xpub: str) -> bool: |
| 201 | + # TODO implement this properly: |
| 202 | + # should return True iff cosigner (with given xpub) can sign and has not yet signed. |
| 203 | + # note that tx could also be unrelated from wallet?... (not ismine inputs) |
| 204 | + return True |
| 205 | + |
| 206 | + def prepare_messages(self, tx: Union[Transaction, PartialTransaction]) -> List[Tuple[str, str]]: |
| 207 | + messages = [] |
| 208 | + for xpub, pubkey in self.cosigner_list: |
| 209 | + if not self.cosigner_can_sign(tx, xpub): |
| 210 | + continue |
| 211 | + raw_tx_bytes = tx.serialize_as_bytes() |
| 212 | + messages.append((pubkey, raw_tx_bytes.hex())) |
| 213 | + return messages |
| 214 | + |
| 215 | + def send_psbt(self, tx: Union[Transaction, PartialTransaction]): |
| 216 | + self.do_send(self.prepare_messages(tx), tx.txid()) |
| 217 | + |
| 218 | + def do_send(self, messages: List[Tuple[str, str]], txid: Optional[str] = None): |
| 219 | + raise NotImplementedError() |
| 220 | + |
| 221 | + def on_receive(self, pubkey, event_id, tx): |
| 222 | + raise NotImplementedError() |
0 commit comments