Browse Source

kill old-style namedtuples

3.3.3.1
SomberNight 6 years ago
parent
commit
9037f25da1
No known key found for this signature in database GPG Key ID: B33B5F232C6271E9
  1. 18
      electrum/coinchooser.py
  2. 11
      electrum/gui/qt/util.py
  3. 11
      electrum/network.py
  4. 23
      electrum/plugin.py
  5. 4
      electrum/plugins/coldcard/coldcard.py
  6. 13
      electrum/plugins/hw_wallet/plugin.py
  7. 22
      electrum/transaction.py
  8. 20
      electrum/util.py

18
electrum/coinchooser.py

@ -22,8 +22,9 @@
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
from collections import defaultdict, namedtuple from collections import defaultdict
from math import floor, log10 from math import floor, log10
from typing import NamedTuple, List
from .bitcoin import sha256, COIN, TYPE_ADDRESS, is_address from .bitcoin import sha256, COIN, TYPE_ADDRESS, is_address
from .transaction import Transaction, TxOutput from .transaction import Transaction, TxOutput
@ -68,13 +69,14 @@ class PRNG:
x[i], x[j] = x[j], x[i] x[i], x[j] = x[j], x[i]
Bucket = namedtuple('Bucket', class Bucket(NamedTuple):
['desc', desc: str
'weight', # as in BIP-141 weight: int # as in BIP-141
'value', # in satoshis value: int # in satoshis
'coins', # UTXOs coins: List[dict] # UTXOs
'min_height', # min block height where a coin was confirmed min_height: int # min block height where a coin was confirmed
'witness']) # whether any coin uses segwit witness: bool # whether any coin uses segwit
def strip_unneeded(bkts, sufficient_funds): def strip_unneeded(bkts, sufficient_funds):
'''Remove buckets that are unnecessary in achieving the spend amount''' '''Remove buckets that are unnecessary in achieving the spend amount'''

11
electrum/gui/qt/util.py

@ -3,8 +3,8 @@ import time
import sys import sys
import platform import platform
import queue import queue
from collections import namedtuple
from functools import partial from functools import partial
from typing import NamedTuple, Callable, Optional
from PyQt5.QtGui import * from PyQt5.QtGui import *
from PyQt5.QtCore import * from PyQt5.QtCore import *
@ -638,7 +638,12 @@ class TaskThread(QThread):
'''Thread that runs background tasks. Callbacks are guaranteed '''Thread that runs background tasks. Callbacks are guaranteed
to happen in the context of its parent.''' to happen in the context of its parent.'''
Task = namedtuple("Task", "task cb_success cb_done cb_error") class Task(NamedTuple):
task: Callable
cb_success: Optional[Callable]
cb_done: Optional[Callable]
cb_error: Optional[Callable]
doneSig = pyqtSignal(object, object, object) doneSig = pyqtSignal(object, object, object)
def __init__(self, parent, on_error=None): def __init__(self, parent, on_error=None):
@ -654,7 +659,7 @@ class TaskThread(QThread):
def run(self): def run(self):
while True: while True:
task = self.tasks.get() task = self.tasks.get() # type: TaskThread.Task
if not task: if not task:
break break
try: try:

11
electrum/network.py

@ -110,11 +110,12 @@ def pick_random_server(hostmap = None, protocol = 's', exclude_set = set()):
return random.choice(eligible) if eligible else None return random.choice(eligible) if eligible else None
NetworkParameters = NamedTuple("NetworkParameters", [("host", str), class NetworkParameters(NamedTuple):
("port", str), host: str
("protocol", str), port: str
("proxy", Optional[dict]), protocol: str
("auto_connect", bool)]) proxy: Optional[dict]
auto_connect: bool
proxy_modes = ['socks4', 'socks5'] proxy_modes = ['socks4', 'socks5']

23
electrum/plugin.py

@ -22,13 +22,13 @@
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
from collections import namedtuple
import traceback import traceback
import sys import sys
import os import os
import pkgutil import pkgutil
import time import time
import threading import threading
from typing import NamedTuple, Any, Union
from .i18n import _ from .i18n import _
from .util import (profiler, PrintError, DaemonThread, UserCancelled, from .util import (profiler, PrintError, DaemonThread, UserCancelled,
@ -259,14 +259,23 @@ class BasePlugin(PrintError):
pass pass
class DeviceNotFoundError(Exception): class DeviceNotFoundError(Exception): pass
pass class DeviceUnpairableError(Exception): pass
class DeviceUnpairableError(Exception):
pass
Device = namedtuple("Device", "path interface_number id_ product_key usage_page") class Device(NamedTuple):
DeviceInfo = namedtuple("DeviceInfo", "device label initialized") path: Union[str, bytes]
interface_number: int
id_: str
product_key: Any # when using hid, often Tuple[int, int]
usage_page: int
class DeviceInfo(NamedTuple):
device: Device
label: str
initialized: bool
class DeviceMgr(ThreadJob, PrintError): class DeviceMgr(ThreadJob, PrintError):
'''Manages hardware clients. A client communicates over a hardware '''Manages hardware clients. A client communicates over a hardware

4
electrum/plugins/coldcard/coldcard.py

@ -374,7 +374,7 @@ class Coldcard_KeyStore(Hardware_KeyStore):
# give empty bytes for error cases; it seems to clear the old signature box # give empty bytes for error cases; it seems to clear the old signature box
return b'' return b''
def build_psbt(self, tx, wallet=None, xfp=None): def build_psbt(self, tx: Transaction, wallet=None, xfp=None):
# Render a PSBT file, for upload to Coldcard. # Render a PSBT file, for upload to Coldcard.
# #
if xfp is None: if xfp is None:
@ -390,7 +390,7 @@ class Coldcard_KeyStore(Hardware_KeyStore):
wallet.add_hw_info(tx) wallet.add_hw_info(tx)
# wallet.add_hw_info installs this attr # wallet.add_hw_info installs this attr
assert hasattr(tx, 'output_info'), 'need data about outputs' assert tx.output_info, 'need data about outputs'
# Build map of pubkey needed as derivation from master, in PSBT binary format # Build map of pubkey needed as derivation from master, in PSBT binary format
# 1) binary version of the common subpath for all keys # 1) binary version of the common subpath for all keys

13
electrum/plugins/hw_wallet/plugin.py

@ -28,7 +28,7 @@ from electrum.plugin import BasePlugin, hook
from electrum.i18n import _ from electrum.i18n import _
from electrum.bitcoin import is_address, TYPE_SCRIPT from electrum.bitcoin import is_address, TYPE_SCRIPT
from electrum.util import bfh, versiontuple from electrum.util import bfh, versiontuple
from electrum.transaction import opcodes, TxOutput from electrum.transaction import opcodes, TxOutput, Transaction
class HW_PluginBase(BasePlugin): class HW_PluginBase(BasePlugin):
@ -113,14 +113,13 @@ class HW_PluginBase(BasePlugin):
return message return message
def is_any_tx_output_on_change_branch(tx): def is_any_tx_output_on_change_branch(tx: Transaction):
if not hasattr(tx, 'output_info'): if not tx.output_info:
return False return False
for _type, address, amount in tx.outputs(): for o in tx.outputs():
info = tx.output_info.get(address) info = tx.output_info.get(o.address)
if info is not None: if info is not None:
index, xpubs, m = info.address_index, info.sorted_xpubs, info.num_sig if info.address_index[0] == 1:
if index[0] == 1:
return True return True
return False return False

22
electrum/transaction.py

@ -31,7 +31,7 @@ import struct
import traceback import traceback
import sys import sys
from typing import (Sequence, Union, NamedTuple, Tuple, Optional, Iterable, from typing import (Sequence, Union, NamedTuple, Tuple, Optional, Iterable,
Callable, List) Callable, List, Dict)
from . import ecc, bitcoin, constants, segwit_addr from . import ecc, bitcoin, constants, segwit_addr
from .util import print_error, profiler, to_bytes, bh2u, bfh from .util import print_error, profiler, to_bytes, bh2u, bfh
@ -63,17 +63,22 @@ class MalformedBitcoinScript(Exception):
pass pass
TxOutput = NamedTuple("TxOutput", [('type', int), ('address', str), ('value', Union[int, str])]) class TxOutput(NamedTuple):
# ^ value is str when the output is set to max: '!' type: int
address: str
value: Union[int, str] # str when the output is set to max: '!'
TxOutputForUI = NamedTuple("TxOutputForUI", [('address', str), ('value', int)]) class TxOutputForUI(NamedTuple):
address: str
value: int
TxOutputHwInfo = NamedTuple("TxOutputHwInfo", [('address_index', Tuple), class TxOutputHwInfo(NamedTuple):
('sorted_xpubs', Iterable[str]), address_index: Tuple
('num_sig', Optional[int]), sorted_xpubs: Iterable[str]
('script_type', str)]) num_sig: Optional[int]
script_type: str
class BCDataStream(object): class BCDataStream(object):
@ -682,6 +687,7 @@ class Transaction:
# this value will get properly set when deserializing # this value will get properly set when deserializing
self.is_partial_originally = True self.is_partial_originally = True
self._segwit_ser = None # None means "don't know" self._segwit_ser = None # None means "don't know"
self.output_info = None # type: Optional[Dict[str, TxOutputHwInfo]]
def update(self, raw): def update(self, raw):
self.raw = raw self.raw = raw

20
electrum/util.py

@ -902,14 +902,18 @@ def ignore_exceptions(func):
return wrapper return wrapper
TxMinedStatus = NamedTuple("TxMinedStatus", [("height", int), class TxMinedStatus(NamedTuple):
("conf", int), height: int
("timestamp", int), conf: int
("header_hash", str)]) timestamp: int
VerifiedTxInfo = NamedTuple("VerifiedTxInfo", [("height", int), header_hash: str
("timestamp", int),
("txpos", int),
("header_hash", str)]) class VerifiedTxInfo(NamedTuple):
height: int
timestamp: int
txpos: int
header_hash: str
def make_aiohttp_session(proxy: dict, headers=None, timeout=None): def make_aiohttp_session(proxy: dict, headers=None, timeout=None):

Loading…
Cancel
Save