Browse Source

replace deprecated utcfromtimestamp

add_frost
zebra-lucky 2 weeks ago
parent
commit
b8d8347165
  1. 11
      scripts/obwatch/ob-watcher.py
  2. 19
      src/jmclient/wallet.py
  3. 40
      src/jmclient/wallet_utils.py

11
scripts/obwatch/ob-watcher.py

@ -11,7 +11,7 @@ import os
import threading import threading
import time import time
import sys import sys
from datetime import datetime, timedelta import datetime
from decimal import Decimal from decimal import Decimal
from optparse import OptionParser from optparse import OptionParser
from typing import Tuple, Union from typing import Tuple, Union
@ -371,13 +371,18 @@ class OrderbookPageRequestHeader(http.server.SimpleHTTPRequestHandler):
bond_value_str = bond_value_to_str(sat_to_unit_power(bond_value, bond_value_str = bond_value_to_str(sat_to_unit_power(bond_value,
2 * bitcoin_unit_to_power(html.unescape(btc_unit))), 2 * bitcoin_unit_to_power(html.unescape(btc_unit))),
html.unescape(btc_unit)) html.unescape(btc_unit))
conf_time_str = str(datetime.utcfromtimestamp(0) + timedelta(seconds=conf_time)) conf_time_str = (
str(datetime.datetime.fromtimestamp(0, datetime.UTC) +
datetime.timedelta(seconds=conf_time)))
utxo_value_str = sat_to_unit(utxo_data["value"], html.unescape(btc_unit)) utxo_value_str = sat_to_unit(utxo_data["value"], html.unescape(btc_unit))
bondtable += ("<tr>" bondtable += ("<tr>"
+ elem(bond_data.maker_nick) + elem(bond_data.maker_nick)
+ elem(bintohex(bond_data.utxo[0]) + ":" + str(bond_data.utxo[1])) + elem(bintohex(bond_data.utxo[0]) + ":" + str(bond_data.utxo[1]))
+ elem(bond_value_str) + elem(bond_value_str)
+ elem((datetime.utcfromtimestamp(0) + timedelta(seconds=bond_data.locktime)).strftime("%Y-%m-%d")) + elem((
datetime.datetime.fromtimestamp(0, datetime.UTC) +
datetime.timedelta(seconds=bond_data.locktime)
).strftime("%Y-%m-%d"))
+ elem(utxo_value_str) + elem(utxo_value_str)
+ elem(conf_time_str) + elem(conf_time_str)
+ elem(str(bond_data.cert_expiry*RETARGET_INTERVAL)) + elem(str(bond_data.cert_expiry*RETARGET_INTERVAL))

19
src/jmclient/wallet.py

@ -11,7 +11,7 @@ import base64
import json import json
from math import ceil from math import ceil
from binascii import hexlify, unhexlify from binascii import hexlify, unhexlify
from datetime import datetime, timedelta import datetime
from calendar import timegm from calendar import timegm
from copy import deepcopy from copy import deepcopy
from mnemonic import Mnemonic as MnemonicParent from mnemonic import Mnemonic as MnemonicParent
@ -848,7 +848,8 @@ class BaseWallet(object):
"storage.") "storage.")
if not timestamp: if not timestamp:
timestamp = datetime.now().strftime('%Y/%m/%d %H:%M:%S') timestamp = datetime.datetime.now(
datetime.UTC).strftime('%Y/%m/%d %H:%M:%S')
storage.data[b'network'] = network.encode('ascii') storage.data[b'network'] = network.encode('ascii')
storage.data[b'created'] = timestamp.encode('ascii') storage.data[b'created'] = timestamp.encode('ascii')
@ -3040,7 +3041,9 @@ class FidelityBondMixin(object):
raise ValueError() raise ValueError()
year = cls.TIMELOCK_EPOCH_YEAR + (timenumber*cls.TIMENUMBER_UNIT) // cls.MONTHS_IN_YEAR year = cls.TIMELOCK_EPOCH_YEAR + (timenumber*cls.TIMENUMBER_UNIT) // cls.MONTHS_IN_YEAR
month = cls.TIMELOCK_EPOCH_MONTH + (timenumber*cls.TIMENUMBER_UNIT) % cls.MONTHS_IN_YEAR month = cls.TIMELOCK_EPOCH_MONTH + (timenumber*cls.TIMENUMBER_UNIT) % cls.MONTHS_IN_YEAR
return timegm(datetime(year, month, *cls.TIMELOCK_DAY_AND_SHORTER).timetuple()) return timegm(
datetime.datetime(
year, month, *cls.TIMELOCK_DAY_AND_SHORTER).timetuple())
@classmethod @classmethod
def datetime_to_time_number(cls, dt): def datetime_to_time_number(cls, dt):
@ -3065,7 +3068,8 @@ class FidelityBondMixin(object):
""" """
#workaround for the year 2038 problem on 32 bit systems #workaround for the year 2038 problem on 32 bit systems
#see https://stackoverflow.com/questions/10588027/converting-timestamps-larger-than-maxint-into-datetime-objects #see https://stackoverflow.com/questions/10588027/converting-timestamps-larger-than-maxint-into-datetime-objects
dt = datetime.utcfromtimestamp(0) + timedelta(seconds=timestamp) dt = (datetime.datetime.fromtimestamp(0, datetime.UTC) +
datetime.timedelta(seconds=timestamp))
return cls.datetime_to_time_number(dt) return cls.datetime_to_time_number(dt)
@classmethod @classmethod
@ -3107,7 +3111,9 @@ class FidelityBondMixin(object):
path = self.script_to_path(script) path = self.script_to_path(script)
if not self.is_timelocked_path(path): if not self.is_timelocked_path(path):
return return
if (datetime.utcfromtimestamp(0) + timedelta(seconds=path[-1])) > datetime.now(): if (datetime.datetime.fromtimestamp(0, datetime.UTC) +
datetime.timedelta(seconds=path[-1]) >
datetime.datetime.now(datetime.UTC)):
#freeze utxo if its timelock is in the future #freeze utxo if its timelock is in the future
self.disable_utxo(txid, index, disable=True) self.disable_utxo(txid, index, disable=True)
@ -3708,7 +3714,8 @@ class FrostWallet(BIP39WalletMixin, BIP32PurposedFrostMixin):
f'recovery storage wallet type: {cls.TYPE}.') f'recovery storage wallet type: {cls.TYPE}.')
if not timestamp: if not timestamp:
timestamp = datetime.now().strftime('%Y/%m/%d %H:%M:%S') timestamp = datetime.datetime.now(
datetime.UTC).strftime('%Y/%m/%d %H:%M:%S')
dkg_storage.data[b'network'] = bnetwork dkg_storage.data[b'network'] = bnetwork
dkg_storage.data[b'created'] = timestamp.encode('ascii') dkg_storage.data[b'created'] = timestamp.encode('ascii')

40
src/jmclient/wallet_utils.py

@ -5,7 +5,7 @@ import json
import os import os
import sqlite3 import sqlite3
import sys import sys
from datetime import datetime, timedelta import datetime
from optparse import OptionParser from optparse import OptionParser
from numbers import Integral from numbers import Integral
from collections import Counter, defaultdict from collections import Counter, defaultdict
@ -479,7 +479,9 @@ async def wallet_showutxos(wallet_service: WalletService, showprivkey: bool,
if showprivkey: if showprivkey:
unsp[us]['privkey'] = wallet_service.get_wif_path(av['path']) unsp[us]['privkey'] = wallet_service.get_wif_path(av['path'])
if locktime: if locktime:
unsp[us]["locktime"] = str(datetime.utcfromtimestamp(0) + timedelta(seconds=locktime)) unsp[us]["locktime"] = str(
datetime.datetime.fromtimestamp(0, datetime.UTC) +
datetime.timedelta(seconds=locktime))
used_commitments, external_commitments = podle.get_podle_commitments() used_commitments, external_commitments = podle.get_podle_commitments()
for u, ec in external_commitments.items(): for u, ec in external_commitments.items():
@ -625,13 +627,15 @@ async def wallet_display(wallet_service, showprivkey, displayall=False,
path = wallet_service.get_path(m, address_type, timenumber) path = wallet_service.get_path(m, address_type, timenumber)
addr = await wallet_service.get_address_from_path(path) addr = await wallet_service.get_address_from_path(path)
label = wallet_service.get_address_label(addr) label = wallet_service.get_address_label(addr)
timelock = datetime.utcfromtimestamp(0) + timedelta(seconds=path[-1]) timelock = (datetime.datetime.fromtimestamp(0, datetime.UTC) +
datetime.timedelta(seconds=path[-1]))
balance = sum([utxodata["value"] for _, utxodata in balance = sum([utxodata["value"] for _, utxodata in
utxos[m].items() if path == utxodata["path"]]) utxos[m].items() if path == utxodata["path"]])
status = timelock.strftime("%Y-%m-%d") + " [" + ( status = (timelock.strftime("%Y-%m-%d") + " [" + (
"LOCKED" if datetime.now() < timelock else "UNLOCKED") + "]" "LOCKED" if datetime.datetime.now(datetime.UTC) < timelock
else "UNLOCKED") + "]")
status += get_utxo_status_string(utxos[m], utxos_enabled[m], path) status += get_utxo_status_string(utxos[m], utxos_enabled[m], path)
privkey = "" privkey = ""
@ -947,10 +951,18 @@ async def wallet_fetch_history(wallet, options):
return btc.sat_to_str(v) if v != -1 else '#' + ' '*10 return btc.sat_to_str(v) if v != -1 else '#' + ' '*10
def print_row(index, time, tx_type, amount, delta, balance, cj_n, def print_row(index, time, tx_type, amount, delta, balance, cj_n,
total_fees, utxo_count, mixdepth_src, mixdepth_dst, txid): total_fees, utxo_count, mixdepth_src, mixdepth_dst, txid):
data = [index, datetime.fromtimestamp(time).strftime("%Y-%m-%d %H:%M"), data = [
tx_type, btc.sat_to_str(abs(amount)), btc.sat_to_str_p(delta), index,
btc.sat_to_str(balance), skip_n1(cj_n), sat_to_str_na(total_fees), datetime.datetime.fromtimestamp(time).strftime("%Y-%m-%d %H:%M"),
'% 3d' % utxo_count, skip_n1(mixdepth_src), skip_n1(mixdepth_dst)] tx_type, btc.sat_to_str(abs(amount)),
btc.sat_to_str_p(delta),
btc.sat_to_str(balance),
skip_n1(cj_n),
sat_to_str_na(total_fees),
'% 3d' % utxo_count,
skip_n1(mixdepth_src),
skip_n1(mixdepth_dst)
]
if options.verbosity % 2 == 0: data += [txid] if options.verbosity % 2 == 0: data += [txid]
jmprint(s().join(map('"{}"'.format, data)), "info") jmprint(s().join(map('"{}"'.format, data)), "info")
@ -1152,8 +1164,9 @@ async def wallet_fetch_history(wallet, options):
bestblockhash = jm_single().bc_interface.get_best_block_hash() bestblockhash = jm_single().bc_interface.get_best_block_hash()
now = jm_single().bc_interface.get_block_time(bestblockhash) now = jm_single().bc_interface.get_block_time(bestblockhash)
jmprint(' %s best block is %s' % (datetime.fromtimestamp(now) jmprint(' %s best block is %s' % (
.strftime("%Y-%m-%d %H:%M"), bestblockhash)) datetime.datetime.fromtimestamp(now).strftime("%Y-%m-%d %H:%M"),
bestblockhash))
total_profit = float(balance - sum(deposits)) / float(100000000) total_profit = float(balance - sum(deposits)) / float(100000000)
jmprint('total profit = %.8f BTC' % total_profit) jmprint('total profit = %.8f BTC' % total_profit)
@ -1440,8 +1453,9 @@ async def wallet_gettimelockaddress(wallet, locktime_string):
jmprint("Error: not a fidelity bond wallet", "error") jmprint("Error: not a fidelity bond wallet", "error")
return "" return ""
lock_datetime = datetime.strptime(locktime_string, "%Y-%m") lock_datetime = datetime.datetime.strptime(locktime_string, "%Y-%m")
if jm_single().config.get("BLOCKCHAIN", "network") == "mainnet" and lock_datetime <= datetime.now(): if (jm_single().config.get("BLOCKCHAIN", "network") == "mainnet"
and lock_datetime <= datetime.datetime.now()):
jmprint("Error: locktime must be a future date", "error") jmprint("Error: locktime must be a future date", "error")
return "" return ""

Loading…
Cancel
Save