Skip to content

Commit

Permalink
logging: basics
Browse files Browse the repository at this point in the history
  • Loading branch information
SomberNight committed May 2, 2019
1 parent 4d64e13 commit 3385a94
Show file tree
Hide file tree
Showing 68 changed files with 683 additions and 565 deletions.
2 changes: 1 addition & 1 deletion electrum/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from .version import ELECTRUM_VERSION
from .util import format_satoshis, print_msg, print_error, set_verbosity
from .util import format_satoshis, set_verbosity
from .wallet import Wallet
from .storage import WalletStorage
from .coinchooser import COIN_CHOOSERS
Expand Down
10 changes: 6 additions & 4 deletions electrum/address_synchronizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,13 @@

from . import bitcoin
from .bitcoin import COINBASE_MATURITY, TYPE_ADDRESS, TYPE_PUBKEY
from .util import PrintError, profiler, bfh, TxMinedInfo
from .util import profiler, bfh, TxMinedInfo
from .transaction import Transaction, TxOutput
from .synchronizer import Synchronizer
from .verifier import SPV
from .blockchain import hash_header
from .i18n import _
from .logging import Logger

if TYPE_CHECKING:
from .storage import WalletStorage
Expand All @@ -54,7 +55,7 @@ def __str__(self):
return _("Transaction is unrelated to this wallet.")


class AddressSynchronizer(PrintError):
class AddressSynchronizer(Logger):
"""
inherited by wallet
"""
Expand All @@ -63,6 +64,7 @@ def __init__(self, storage: 'WalletStorage'):
self.storage = storage
self.db = self.storage.db
self.network = None # type: Network
Logger.__init__(self)
# verifier (SPV) and synchronizer are started in start_network
self.synchronizer = None # type: Synchronizer
self.verifier = None # type: SPV
Expand Down Expand Up @@ -307,7 +309,7 @@ def remove_from_spent_outpoints():
self.db.remove_spent_outpoint(prevout_hash, prevout_n)

with self.transaction_lock:
self.print_error("removing tx from history", tx_hash)
self.logger.info("removing tx from history", tx_hash)
tx = self.db.remove_transaction(tx_hash)
remove_from_spent_outpoints()
self._remove_tx_from_local_history(tx_hash)
Expand Down Expand Up @@ -455,7 +457,7 @@ def get_history(self, domain=None):
h2.reverse()
# fixme: this may happen if history is incomplete
if balance not in [None, 0]:
self.print_error("Error: history not synchronized")
self.logger.info("Error: history not synchronized")
return []

return h2
Expand Down
16 changes: 9 additions & 7 deletions electrum/base_wizard.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from .util import UserCancelled, InvalidPassword, WalletFileException
from .simple_config import SimpleConfig
from .plugin import Plugins
from .logging import Logger

if TYPE_CHECKING:
from .plugin import DeviceInfo
Expand All @@ -65,10 +66,11 @@ class WizardStackItem(NamedTuple):
storage_data: dict


class BaseWizard(object):
class BaseWizard(Logger):

def __init__(self, config: SimpleConfig, plugins: Plugins):
super(BaseWizard, self).__init__()
Logger.__init__(self)
self.config = config
self.plugins = plugins
self.data = {}
Expand Down Expand Up @@ -253,15 +255,15 @@ def choose_hw_device(self, purpose=HWD_SETUP_NEW_WALLET, *, storage=None):

def failed_getting_device_infos(name, e):
nonlocal debug_msg
devmgr.print_error(f'error getting device infos for {name}: {e}')
self.logger.info(f'error getting device infos for {name}: {e}')
indented_error_msg = ' '.join([''] + str(e).splitlines(keepends=True))
debug_msg += f' {name}: (error getting device infos)\n{indented_error_msg}\n'

# scan devices
try:
scanned_devices = devmgr.scan_devices()
except BaseException as e:
devmgr.print_error('error scanning devices: {}'.format(repr(e)))
self.logger.info('error scanning devices: {}'.format(repr(e)))
debug_msg = ' {}:\n {}'.format(_('Error scanning devices'), e)
else:
for splugin in supported_plugins:
Expand All @@ -280,7 +282,7 @@ def failed_getting_device_infos(name, e):
device_infos = devmgr.unpaired_device_infos(None, plugin, devices=scanned_devices,
include_failing_clients=True)
except BaseException as e:
traceback.print_exc()
self.logger.exception('')
failed_getting_device_infos(name, e)
continue
device_infos_failing = list(filter(lambda di: di.exception is not None, device_infos))
Expand Down Expand Up @@ -333,7 +335,7 @@ def on_device(self, name, device_info, *, purpose, storage=None):
self.choose_hw_device(purpose, storage=storage)
return
except BaseException as e:
traceback.print_exc(file=sys.stderr)
self.logger.exception('')
self.show_error(str(e))
self.choose_hw_device(purpose, storage=storage)
return
Expand Down Expand Up @@ -399,7 +401,7 @@ def on_hw_derivation(self, name, device_info, derivation, xtype):
except ScriptTypeNotSupported:
raise # this is handled in derivation_dialog
except BaseException as e:
traceback.print_exc(file=sys.stderr)
self.logger.exception('')
self.show_error(e)
return
d = {
Expand Down Expand Up @@ -517,7 +519,7 @@ def create_wallet(self):
self.choose_hw_device()
return
except BaseException as e:
traceback.print_exc(file=sys.stderr)
self.logger.exception('')
self.show_error(str(e))
return
self.request_storage_encryption(
Expand Down
6 changes: 4 additions & 2 deletions electrum/bip32.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
import hashlib
from typing import List, Tuple, NamedTuple, Union, Iterable

from .util import bfh, bh2u, BitcoinException, print_error
from .util import bfh, bh2u, BitcoinException
from . import constants
from . import ecc
from .crypto import hash_160, hmac_oneshot
from .bitcoin import rev_hex, int_to_hex, EncodeBase58Check, DecodeBase58Check
from .logging import get_logger


_logger = get_logger(__name__)
BIP32_PRIME = 0x80000000
UINT32_MAX = (1 << 32) - 1

Expand All @@ -24,7 +26,7 @@ def func_wrapper(*args):
try:
return func(*args[:-1], child_index=child_index)
except ecc.InvalidECPointException:
print_error('bip32 protect_against_invalid_ecpoint: skipping index')
_logger.warning('bip32 protect_against_invalid_ecpoint: skipping index')
child_index += 1
is_prime2 = child_index & BIP32_PRIME
if is_prime != is_prime2: raise OverflowError()
Expand Down
16 changes: 9 additions & 7 deletions electrum/blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,11 @@
from . import constants
from .util import bfh, bh2u
from .simple_config import SimpleConfig
from .logging import get_logger, Logger


_logger = get_logger(__name__)

HEADER_SIZE = 80 # bytes
MAX_TARGET = 0x00000000FFFF0000000000000000000000000000000000000000000000000000

Expand Down Expand Up @@ -96,7 +99,7 @@ def read_blockchains(config: 'SimpleConfig'):
if best_chain.height() > constants.net.max_checkpoint():
header_after_cp = best_chain.read_header(constants.net.max_checkpoint()+1)
if not header_after_cp or not best_chain.can_connect(header_after_cp, check_height=False):
util.print_error("[blockchain] deleting best chain. cannot connect header after last cp to last cp.")
_logger.info("[blockchain] deleting best chain. cannot connect header after last cp to last cp.")
os.unlink(best_chain.path())
best_chain.update_size()
# forks
Expand All @@ -107,7 +110,7 @@ def read_blockchains(config: 'SimpleConfig'):
l = sorted(l, key=lambda x: int(x.split('_')[1])) # sort by forkpoint

def delete_chain(filename, reason):
util.print_error(f"[blockchain] deleting chain {filename}: {reason}")
_logger.info(f"[blockchain] deleting chain {filename}: {reason}")
os.unlink(os.path.join(fdir, filename))

def instantiate_chain(filename):
Expand Down Expand Up @@ -156,7 +159,7 @@ def get_best_chain() -> 'Blockchain':
} # type: Dict[str, int]


class Blockchain(util.PrintError):
class Blockchain(Logger):
"""
Manages blockchain headers and their verification
"""
Expand All @@ -168,6 +171,7 @@ def __init__(self, config: SimpleConfig, forkpoint: int, parent: Optional['Block
# assert (parent is None) == (forkpoint == 0)
if 0 < forkpoint <= constants.net.max_checkpoint():
raise Exception(f"cannot fork below max checkpoint. forkpoint: {forkpoint}")
Logger.__init__(self)
self.config = config
self.forkpoint = forkpoint # height of first header
self.parent = parent
Expand Down Expand Up @@ -368,7 +372,7 @@ def _swap_with_parent(self) -> bool:
return False
if self.parent.get_chainwork() >= self.get_chainwork():
return False
self.print_error("swap", self.forkpoint, self.parent.forkpoint)
self.logger.info(f"swapping {self.forkpoint} {self.parent.forkpoint}")
parent_branch_size = self.parent.height() - self.forkpoint + 1
forkpoint = self.forkpoint # type: Optional[int]
parent = self.parent # type: Optional[Blockchain]
Expand Down Expand Up @@ -570,7 +574,6 @@ def can_connect(self, header: dict, check_height: bool=True) -> bool:
return False
height = header['block_height']
if check_height and self.height() != height - 1:
#self.print_error("cannot connect at height", height)
return False
if height == 0:
return hash_header(header) == constants.net.GENESIS
Expand All @@ -595,11 +598,10 @@ def connect_chunk(self, idx: int, hexdata: str) -> bool:
try:
data = bfh(hexdata)
self.verify_chunk(idx, data)
#self.print_error("validated chunk %d" % idx)
self.save_chunk(idx, data)
return True
except BaseException as e:
self.print_error(f'verify_chunk idx {idx} failed: {repr(e)}')
self.logger.info(f'verify_chunk idx {idx} failed: {repr(e)}')
return False

def get_checkpoints(self):
Expand Down
20 changes: 12 additions & 8 deletions electrum/coinchooser.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@

from .bitcoin import sha256, COIN, TYPE_ADDRESS, is_address
from .transaction import Transaction, TxOutput
from .util import NotEnoughFunds, PrintError
from .util import NotEnoughFunds
from .logging import Logger


# A simple deterministic PRNG. Used to deterministically shuffle a
Expand Down Expand Up @@ -92,10 +93,13 @@ def strip_unneeded(bkts, sufficient_funds):
raise Exception("keeping all buckets is still not enough")


class CoinChooserBase(PrintError):
class CoinChooserBase(Logger):

enable_output_value_rounding = False

def __init__(self):
Logger.__init__(self)

def keys(self, coins):
raise NotImplementedError

Expand Down Expand Up @@ -187,9 +191,9 @@ def change_outputs(self, tx, change_addrs, fee_estimator, dust_threshold):
amounts = [amount for amount in amounts if amount >= dust_threshold]
change = [TxOutput(TYPE_ADDRESS, addr, amount)
for addr, amount in zip(change_addrs, amounts)]
self.print_error('change:', change)
self.logger.info(f'change: {change}')
if dust:
self.print_error('not keeping dust', dust)
self.logger.info(f'not keeping dust {dust}')
return change

def make_tx(self, coins, inputs, outputs, change_addrs, fee_estimator,
Expand Down Expand Up @@ -268,8 +272,8 @@ def sufficient_funds(buckets, *, bucket_value_sum):
change = self.change_outputs(tx, change_addrs, fee, dust_threshold)
tx.add_outputs(change)

self.print_error("using %d inputs" % len(tx.inputs()))
self.print_error("using buckets:", [bucket.desc for bucket in buckets])
self.logger.info(f"using {len(tx.inputs())} inputs")
self.logger.info(f"using buckets: {[bucket.desc for bucket in buckets]}")

return tx

Expand Down Expand Up @@ -357,8 +361,8 @@ def choose_buckets(self, buckets, sufficient_funds, penalty_func):
candidates = self.bucket_candidates_prefer_confirmed(buckets, sufficient_funds)
penalties = [penalty_func(cand) for cand in candidates]
winner = candidates[penalties.index(min(penalties))]
self.print_error("Bucket sets:", len(buckets))
self.print_error("Winning penalty:", min(penalties))
self.logger.info(f"Bucket sets: {len(buckets)}")
self.logger.info(f"Winning penalty: {min(penalties)}")
return winner

class CoinChooserPrivacy(CoinChooserRandom):
Expand Down
3 changes: 2 additions & 1 deletion electrum/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
from typing import Optional, TYPE_CHECKING

from .import util, ecc
from .util import bfh, bh2u, format_satoshis, json_decode, print_error, json_encode, is_hash256_str
from .util import bfh, bh2u, format_satoshis, json_decode, json_encode, is_hash256_str
from . import bitcoin
from .bitcoin import is_address, hash_160, COIN, TYPE_ADDRESS
from . import bip32
Expand Down Expand Up @@ -936,6 +936,7 @@ def add_global_options(parser):
group.add_argument("--testnet", action="store_true", dest="testnet", default=False, help="Use Testnet")
group.add_argument("--regtest", action="store_true", dest="regtest", default=False, help="Use Regtest")
group.add_argument("--simnet", action="store_true", dest="simnet", default=False, help="Use Simnet")
group.add_argument("--disablefilelogging", action="store_true", dest="disablefilelogging", default=False, help="Do not log to file")

def get_parser():
# create main parser
Expand Down
8 changes: 5 additions & 3 deletions electrum/contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@

from . import bitcoin
from . import dnssec
from .util import export_meta, import_meta, print_error, to_string
from .util import export_meta, import_meta, to_string
from .logging import Logger


class Contacts(dict):
class Contacts(dict, Logger):

def __init__(self, storage):
Logger.__init__(self)
self.storage = storage
d = self.storage.get('contacts', {})
try:
Expand Down Expand Up @@ -99,7 +101,7 @@ def resolve_openalias(self, url):
try:
records, validated = dnssec.query(url, dns.rdatatype.TXT)
except DNSException as e:
print_error(f'Error resolving openalias: {repr(e)}')
self.logger.info(f'Error resolving openalias: {repr(e)}')
return None
prefix = 'btc'
for record in records:
Expand Down
Loading

0 comments on commit 3385a94

Please sign in to comment.