Skip to content

Commit

Permalink
No more globals
Browse files Browse the repository at this point in the history
  • Loading branch information
Ouziel committed Jan 16, 2025
1 parent c43fa92 commit c019679
Show file tree
Hide file tree
Showing 13 changed files with 59 additions and 47 deletions.
14 changes: 7 additions & 7 deletions counterparty-core/counterpartycore/lib/cli/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from json_log_formatter import JSONFormatter
from termcolor import colored, cprint

from counterpartycore.lib import config, util
from counterpartycore.lib import config
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.utils import helpers

Expand Down Expand Up @@ -66,7 +66,7 @@ def get_full_topic(record):
topic is None
and CurrentState().current_block_index() is not None
and "/counterpartycore/lib/messages/" in record.pathname
and util.PARSING_MEMPOOL
and CurrentState().parsing_mempool()
):
topic = "Mempool"

Expand Down Expand Up @@ -119,7 +119,7 @@ def format(self, record):
record.levelno != logging.EVENT
and CurrentState().current_block_index() is not None
and "/counterpartycore/lib/messages/" in record.pathname
and not util.PARSING_MEMPOOL
and not CurrentState().parsing_mempool()
):
log_message = f"Block {CurrentState().current_block_index()} - %(message)s"

Expand Down Expand Up @@ -159,7 +159,7 @@ def json_record(self, message: str, extra: dict, record: logging.LogRecord) -> d
and CurrentState().current_block_index() is not None
and "/counterpartycore/lib/messages/" in record.pathname
):
if util.PARSING_MEMPOOL:
if CurrentState().parsing_mempool():
extra["block_index"] = "Mempool"
else:
extra["block_index"] = CurrentState().current_block_index()
Expand Down Expand Up @@ -311,7 +311,7 @@ def truncate_fields(bindings):


def log_event(db, block_index, event_index, event_name, bindings):
block_name = "Mempool" if util.PARSING_MEMPOOL else f"Block {block_index}"
block_name = "Mempool" if CurrentState().parsing_mempool() else f"Block {block_index}"
log_bindings = truncate_fields(bindings)
log_bindings = " ".join([f"{key}={value}" for key, value in log_bindings.items()])
log_message = f"{block_name} - {event_name} [{log_bindings}]"
Expand All @@ -325,9 +325,9 @@ def log_event(db, block_index, event_index, event_name, bindings):
zmq_event = {
"event": event_name,
"params": bindings,
"mempool": util.PARSING_MEMPOOL,
"mempool": CurrentState().parsing_mempool(),
}
if not util.PARSING_MEMPOOL:
if not CurrentState().parsing_mempool():
zmq_event["block_index"] = block_index
zmq_event["event_index"] = event_index
zmq_publisher.publish_event(db, zmq_event)
Expand Down
18 changes: 18 additions & 0 deletions counterparty-core/counterpartycore/lib/ledger/currentstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ def set_current_block_index(self, block_index):
else:
self.state["CURRENT_BLOCK_TIME"] = 0

def set_current_tx_hash(self, tx_hash):
self.state["CURRENT_TX_HASH"] = tx_hash

def set_parsing_mempool(self, parsing_mempool):
self.state["PARSING_MEMPOOL"] = parsing_mempool

def set_block_parser_status(self, status):
self.state["BLOCK_PARSER_STATUS"] = status

def current_block_index(self):
return self.state.get("CURRENT_BLOCK_INDEX")

Expand All @@ -56,3 +65,12 @@ def current_backend_height(self):
self.backend_height = get_backend_height()

Check warning

Code scanning / pylint

Attribute 'backend_height' defined outside init. Warning

Attribute 'backend_height' defined outside __init__.
self.last_update = time.time()
return self.backend_height

def current_tx_hash(self):
return self.state.get("CURRENT_TX_HASH")

def parsing_mempool(self):
return self.state.get("PARSING_MEMPOOL")

def block_parser_status(self):
return self.state.get("BLOCK_PARSER_STATUS", "starting")
20 changes: 10 additions & 10 deletions counterparty-core/counterpartycore/lib/ledger/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from contextlib import contextmanager
from decimal import Decimal as D

from counterpartycore.lib import backend, config, exceptions, util
from counterpartycore.lib import backend, config, exceptions
from counterpartycore.lib.cli import log
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.parser import check, protocol, utxosinfo
Expand Down Expand Up @@ -40,7 +40,7 @@ def insert_record(db, table_name, record, event, event_info={}): # noqa: B006

with get_cursor(db) as cursor:
cursor.execute(query, list(record.values()))
if table_name in ["issuances", "destructions"] and not util.PARSING_MEMPOOL:
if table_name in ["issuances", "destructions"] and not CurrentState().parsing_mempool():
cursor.execute("SELECT last_insert_rowid() AS rowid")
inserted_rowid = cursor.fetchone()["rowid"]
new_record = cursor.execute(
Expand Down Expand Up @@ -181,7 +181,7 @@ def add_to_journal(db, block_index, command, category, event, bindings):
category,
bindings_string,
event,
util.CURRENT_TX_HASH or "",
CurrentState().current_tx_hash() or "",
previous_event_hash,
]
)
Expand All @@ -194,7 +194,7 @@ def add_to_journal(db, block_index, command, category, event, bindings):
"bindings": bindings_string,
"timestamp": current_time,
"event": event,
"tx_hash": util.CURRENT_TX_HASH,
"tx_hash": CurrentState().current_tx_hash(),
"event_hash": event_hash,
}
query = """INSERT INTO messages (
Expand Down Expand Up @@ -289,7 +289,7 @@ def remove_from_balance(db, address, asset, quantity, tx_index, utxo_address=Non
if protocol.enabled("utxo_support") and utxosinfo.is_utxo_format(address):
balance_address = None
utxo = address
if not util.PARSING_MEMPOOL and balance == 0:
if not CurrentState().parsing_mempool() and balance == 0:
UTXOBalancesCache(db).remove_balance(utxo)

if not no_balance: # don't create balance if quantity is 0 and there is no balance
Expand Down Expand Up @@ -375,7 +375,7 @@ def add_to_balance(db, address, asset, quantity, tx_index, utxo_address=None):
if protocol.enabled("utxo_support") and utxosinfo.is_utxo_format(address):
balance_address = None
utxo = address
if not util.PARSING_MEMPOOL and balance > 0:
if not CurrentState().parsing_mempool() and balance > 0:
UTXOBalancesCache(db).add_balance(utxo)

bindings = {
Expand Down Expand Up @@ -2039,14 +2039,14 @@ def get_matching_orders_no_cache(db, tx_hash, give_asset, get_asset):


def get_matching_orders(db, tx_hash, give_asset, get_asset):
if util.BLOCK_PARSER_STATUS == "catching up":
if CurrentState().block_parser_status() == "catching up":
return OrdersCache(db).get_matching_orders(tx_hash, give_asset, get_asset)
return get_matching_orders_no_cache(db, tx_hash, give_asset, get_asset)


def insert_order(db, order):
insert_record(db, "orders", order, "OPEN_ORDER")
if not util.PARSING_MEMPOOL:
if not CurrentState().parsing_mempool():
OrdersCache(db).insert_order(order)


Expand All @@ -2055,7 +2055,7 @@ def insert_order(db, order):

def update_order(db, tx_hash, update_data):
insert_update(db, "orders", "tx_hash", tx_hash, update_data, "ORDER_UPDATE")
if not util.PARSING_MEMPOOL:
if not CurrentState().parsing_mempool():
OrdersCache(db).update_order(tx_hash, update_data)


Expand Down Expand Up @@ -2092,7 +2092,7 @@ def mark_order_as_filled(db, tx0_hash, tx1_hash, source=None):
"ORDER_FILLED",
{"tx_hash": order["tx_hash"]},
)
if not util.PARSING_MEMPOOL:
if not CurrentState().parsing_mempool():
OrdersCache(db).update_order(order["tx_hash"], update_data)


Expand Down
3 changes: 1 addition & 2 deletions counterparty-core/counterpartycore/lib/messages/dispenser.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
config,
exceptions,
ledger,
util,
)
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.parser import messagetype, protocol
Expand Down Expand Up @@ -719,7 +718,7 @@ def parse(db, tx, message):

ledger.ledger.insert_record(db, "dispensers", bindings, "OPEN_DISPENSER")
# Add the address to the dispensable cache
if not util.PARSING_MEMPOOL:
if not CurrentState().parsing_mempool():
DispensableCache(db).new_dispensable(action_address)

logger.info(
Expand Down
17 changes: 8 additions & 9 deletions counterparty-core/counterpartycore/lib/parser/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
config,
exceptions,
ledger,
util,
)
from counterpartycore.lib.backend import rsfetcher
from counterpartycore.lib.cli import log
Expand Down Expand Up @@ -120,7 +119,7 @@ def update_transaction(db, tx, supported):


def parse_tx(db, tx):
util.CURRENT_TX_HASH = tx["tx_hash"]
CurrentState().set_current_tx_hash(tx["tx_hash"])
"""Parse the transaction, return True for success."""
cursor = db.cursor()

Expand Down Expand Up @@ -248,15 +247,15 @@ def parse_tx(db, tx):
cursor.close()
supported = supported or moved
update_transaction(db, tx, supported)
util.CURRENT_TX_HASH = None
CurrentState().set_current_tx_hash(None)

return supported


def replay_transactions_events(db, transactions):
cursor = db.cursor()
for tx in transactions:
util.CURRENT_TX_HASH = tx["tx_hash"]
CurrentState().set_current_tx_hash(tx["tx_hash"])
transaction_bindings = {
"tx_index": tx["tx_index"],
"tx_hash": tx["tx_hash"],
Expand Down Expand Up @@ -300,7 +299,7 @@ def replay_transactions_events(db, transactions):
"NEW_TRANSACTION_OUTPUT",
transaction_outputs_bindings,
)
util.CURRENT_TX_HASH = None
CurrentState().set_current_tx_hash(None)


def parse_block(
Expand Down Expand Up @@ -1008,7 +1007,7 @@ def create_views(db):

def list_tx(db, block_hash, block_index, block_time, tx_hash, tx_index, decoded_tx):
assert type(tx_hash) == str # noqa: E721
util.CURRENT_TX_HASH = tx_hash
CurrentState().set_current_tx_hash(tx_hash)
cursor = db.cursor()

source, destination, btc_amount, fee, data, dispensers_outs, utxos_info = get_tx_info(
Expand All @@ -1021,7 +1020,7 @@ def list_tx(db, block_hash, block_index, block_time, tx_hash, tx_index, decoded_
block_index = config.MEMPOOL_BLOCK_INDEX
existing_tx = ledger.ledger.get_transaction(db, tx_hash)
if existing_tx:
util.CURRENT_TX_HASH = None
CurrentState().set_current_tx_hash(None)
return tx_index
else:
assert block_index == CurrentState().current_block_index()
Expand Down Expand Up @@ -1080,7 +1079,7 @@ def list_tx(db, block_hash, block_index, block_time, tx_hash, tx_index, decoded_
return tx_index + 1
else:
pass
util.CURRENT_TX_HASH = None
CurrentState().set_current_tx_hash(None)
return tx_index


Expand Down Expand Up @@ -1439,7 +1438,7 @@ def catch_up(db, check_asset_conservation=True):
fetcher = None

try:
util.BLOCK_PARSER_STATUS = "catching up"
CurrentState().set_block_parser_status("catching up")
# update the current block index
current_block_index = ledger.ledger.last_db_index(db)
if current_block_index == 0:
Expand Down
2 changes: 1 addition & 1 deletion counterparty-core/counterpartycore/lib/parser/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import requests

from counterpartycore.lib import config, ledger, util # noqa: F401
from counterpartycore.lib import config, ledger
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.utils import database

Expand Down
3 changes: 1 addition & 2 deletions counterparty-core/counterpartycore/lib/parser/follow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
config,
exceptions,
ledger,
util,
)
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.monitors import sentry
Expand Down Expand Up @@ -254,7 +253,7 @@ def is_late(self):

async def handle(self):
self.check_software_version_if_needed()
util.BLOCK_PARSER_STATUS = "following"
CurrentState().set_block_parser_status("catching up")
late_since = None

while True:
Expand Down
7 changes: 5 additions & 2 deletions counterparty-core/counterpartycore/lib/parser/gettxinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from arc4 import ARC4

Check warning

Code scanning / pylint

No name 'ARC4' in module 'arc4'. Warning

No name 'ARC4' in module 'arc4'.
from bitcoinutils.keys import PublicKey

from counterpartycore.lib import backend, config, exceptions, ledger, util
from counterpartycore.lib import backend, config, exceptions, ledger
from counterpartycore.lib.exceptions import BTCOnlyError, DecodeError
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.messages import dispenser
Expand Down Expand Up @@ -527,7 +527,10 @@ def get_utxos_info(db, decoded_tx):


def update_utxo_balances_cache(db, utxos_info, data, destination, block_index):
if protocol.enabled("utxo_support", block_index=block_index) and not util.PARSING_MEMPOOL:
if (
protocol.enabled("utxo_support", block_index=block_index)
and not CurrentState().parsing_mempool()
):
transaction_type = messagetype.get_transaction_type(
data, destination, utxos_info, block_index
)
Expand Down
7 changes: 4 additions & 3 deletions counterparty-core/counterpartycore/lib/parser/mempool.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
import logging
import time

from counterpartycore.lib import backend, config, exceptions, ledger, util
from counterpartycore.lib import backend, config, exceptions, ledger
from counterpartycore.lib.api.apiwatcher import EVENTS_ADDRESS_FIELDS
from counterpartycore.lib.ledger.currentstate import CurrentState
from counterpartycore.lib.parser import blocks, deserialize

logger = logging.getLogger(config.LOGGER_NAME)


def parse_mempool_transactions(db, raw_tx_list, timestamps=None):
util.PARSING_MEMPOOL = True
CurrentState().set_parsing_mempool(True)

logger.trace(f"Parsing {len(raw_tx_list)} raw transaction(s) from the mempool...")
now = time.time()
Expand Down Expand Up @@ -110,7 +111,7 @@ def parse_mempool_transactions(db, raw_tx_list, timestamps=None):
event,
)
logger.trace("Mempool transaction parsed successfully.")
util.PARSING_MEMPOOL = False
CurrentState().set_parsing_mempool(False)
return not_supported_txs


Expand Down
3 changes: 0 additions & 3 deletions counterparty-core/counterpartycore/lib/util.py

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#! /usr/bin/python3
import pprint # noqa: F401
import tempfile

from counterpartycore.lib import config, util # noqa: F401
from counterpartycore.lib import config
from counterpartycore.lib.parser import protocol
from counterpartycore.test import (
conftest, # noqa: F401
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import math

import hypothesis
from counterpartycore.lib import config, util
from counterpartycore.lib import config
from counterpartycore.lib.utils import assetnames
from hypothesis import settings
from properytestnode import PropertyTestNode
from regtestnode import ComposeError
Expand Down Expand Up @@ -346,7 +347,7 @@ def move_with_counterparty_data(self, utxo_balance, destination):
utxo_address,
"fairminter",
{
"asset": util.gen_random_asset_name(utxo_asset),
"asset": assetnames.gen_random_asset_name(utxo_asset),
"price": 1,
"quantity_by_price": 5,
"exact_fee": 0,
Expand Down
Loading

0 comments on commit c019679

Please sign in to comment.