"""Usage: python reproduce.py.txt VERIFIED_LITECOIND_EXE OUTPUT_JSON One disposable data directory and two isolated daemon runs. No external peers, real wallets, or mainnet. """ from base64 import b64encode from contextlib import contextmanager from datetime import datetime, timezone from hashlib import sha256 import http.client import json from pathlib import Path import shutil import socket import subprocess import sys from tempfile import TemporaryDirectory import time PIN = '7430c6d0d4cb59d355361a0b90ffbfc4ac725609483e04c242bf95372cc9b8fe' VERSION = '/LitecoinCore:0.21.5.8/' class Node: def __init__(self, binary, path): self.path = path self.cookie = path / 'regtest' / '.cookie' with socket.socket() as reserved: reserved.bind(('127.0.0.1', 0)) self.port = reserved.getsockname()[1] conf = path / 'test.conf' conf.touch() args = [str(binary), '-regtest', f'-datadir={path}', f'-conf={conf}', '-server=1', '-rpcbind=127.0.0.1', '-rpcallowip=127.0.0.1', f'-rpcport={self.port}', '-listen=0', '-connect=0', '-dnsseed=0', '-discover=0', '-upnp=0', '-listenonion=0', '-fallbackfee=0.001', '-persistmempool=0', '-walletbroadcast=0'] with (path / 'daemon.log').open('wb') as log: self.process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)) def rpc(self, method, *params, wallet=None): token = b64encode(self.cookie.read_bytes().strip()).decode('ascii') conn = http.client.HTTPConnection('127.0.0.1', self.port, timeout=12) try: body = json.dumps({'jsonrpc': '1.0', 'id': 'wallet-check', 'method': method, 'params': params}) conn.request('POST', '/' if wallet is None else f'/wallet/{wallet}', body, {'Authorization': f'Basic {token}', 'Content-Type': 'application/json'}) result = json.loads(conn.getresponse().read()) finally: conn.close() if result['error'] is not None: raise RuntimeError(result['error']['message']) return result['result'] @contextmanager def running(binary, path): node = Node(binary, path) try: for _ in range(125): if node.process.poll() is not None: raise RuntimeError((path / 'daemon.log').read_text(errors='replace')[-1200:]) try: chain = node.rpc('getblockchaininfo')['chain'] break except (OSError, RuntimeError, http.client.HTTPException): time.sleep(.2) else: raise RuntimeError('Timed out waiting for the disposable node') assert chain == 'regtest' assert node.rpc('getnetworkinfo')['subversion'] == VERSION assert node.rpc('getconnectioncount') == 0 yield node finally: if node.process.poll() is None: try: node.rpc('stop') node.process.wait(timeout=20) finally: if node.process.poll() is None: node.process.kill() node.process.wait(timeout=10) from decimal import Decimal def litoshis(amount): scaled = Decimal(str(amount)) * 100_000_000 if scaled != scaled.to_integral_value(): raise ValueError('Amount is not an integer number of litoshis') return int(scaled) def output_number(tx, address): return next(o['n'] for o in tx['vout'] if o['scriptPubKey'].get('addresses') == [address]) def run(binary, base): lab = base / 'chain' lab.mkdir() with running(binary, lab) as node: for name in ('miner', 'payer', 'recipient'): node.rpc('createwallet', name) miner = node.rpc('getnewaddress', '', 'bech32', wallet='miner') payer = node.rpc('getnewaddress', '', 'bech32', wallet='payer') change = node.rpc('getnewaddress', '', 'bech32', wallet='payer') recipient = node.rpc('getnewaddress', '', 'bech32', wallet='recipient') node.rpc('generatetoaddress', 101, miner) funding = node.rpc('sendtoaddress', payer, 1, wallet='miner') funding_bytes = node.rpc('gettransaction', funding, wallet='miner')['hex'] assert node.rpc('sendrawtransaction', funding_bytes) == funding funding_block = node.rpc('generatetoaddress', 1, miner)[0] funding_tx = node.rpc('getrawtransaction', funding, True, funding_block) index = output_number(funding_tx, payer) assert litoshis(node.rpc('gettxout', funding, index, False)['value']) == 100_000_000 def candidate(change_amount): unsigned = node.rpc('createrawtransaction', [{'txid': funding, 'vout': index}], {recipient: 0.3, change: change_amount}) signed = node.rpc('signrawtransactionwithwallet', unsigned, wallet='payer') assert signed['complete'] tx = node.rpc('decoderawtransaction', signed['hex']) fee = 100_000_000 - sum(litoshis(row['value']) for row in tx['vout']) return signed['hex'], tx, fee low_hex, low, low_fee = candidate(0.69999999) accepted_hex, accepted, accepted_fee = candidate(0.69999) assert low_fee == 1 and accepted_fee == 1000 receive_index = output_number(accepted, recipient) accepted_id = accepted['txid'] rejected = node.rpc('testmempoolaccept', [low_hex])[0] assert rejected['allowed'] is False try: node.rpc('sendrawtransaction', low_hex) except RuntimeError as error: reject_message = str(error) assert 'fee' in reject_message.lower() else: raise AssertionError('Low-fee submission unexpectedly admitted') assert node.rpc('getrawmempool') == [] assert node.rpc('gettxout', funding, index) is not None assert node.rpc('getblockcount') == 102 checked = node.rpc('testmempoolaccept', [accepted_hex])[0] assert checked['allowed'] and node.rpc('getrawmempool') == [] assert node.rpc('gettxout', accepted_id, receive_index) is None assert node.rpc('sendrawtransaction', accepted_hex) == accepted_id mempool = node.rpc('getmempoolentry', accepted_id) pending_out = node.rpc('gettxout', accepted_id, receive_index, True) assert pending_out['confirmations'] == 0 assert litoshis(mempool['fees']['base']) == accepted_fee assert litoshis(pending_out['value']) == 30_000_000 assert node.rpc('gettxout', accepted_id, receive_index, False) is None assert node.rpc('gettxout', funding, index, True) is None assert node.rpc('gettxout', funding, index, False) is not None with running(binary, lab) as node: assert node.rpc('getrawmempool') == [] assert node.rpc('gettxout', funding, index, True) is not None assert node.rpc('gettxout', accepted_id, receive_index, True) is None assert node.rpc('getblockcount') == 102 assert node.rpc('sendrawtransaction', accepted_hex) == accepted_id block = node.rpc('generatetoaddress', 1, miner)[0] stats = node.rpc('getblockstats', block, ['totalfee', 'txs']) final_out = node.rpc('gettxout', accepted_id, receive_index, False) assert stats['totalfee'] == accepted_fee and stats['txs'] == 2 assert final_out['confirmations'] == 1 and litoshis(final_out['value']) == 30_000_000 assert node.rpc('gettxout', funding, index, False) is None return { 'network': 'regtest', 'version': VERSION, 'daemon_sha256': PIN, 'persist_mempool': False, 'wallet_broadcast': False, 'network_peers': 0, 'format': 'ordinary transparent P2WPKH inputs and outputs', 'fees_unit': 'litoshi', 'funding_outpoint': {'txid': funding, 'vout': index, 'amount': 100_000_000}, 'policy_rejected': {'txid': low['txid'], 'encoded_fee': low_fee, 'vbytes': low['vsize'], 'policy_reason': rejected['reject-reason'], 'submit_error': reject_message, 'in_mempool': False, 'funding_unspent': True, 'height': 102}, 'policy_checked_only': {'txid': accepted_id, 'encoded_fee': accepted_fee, 'vbytes': accepted['vsize'], 'allowed': True, 'in_mempool': False}, 'submitted_pending': {'txid': accepted_id, 'mempool_fee': accepted_fee, 'vout': receive_index, 'confirmations': 0, 'confirmed_output_exists': False}, 'isolated_restart': {'txid': accepted_id, 'in_mempool': False, 'funding_unspent': True, 'confirmed_output_exists': False, 'height': 102}, 'observed_in_block': {'txid': accepted_id, 'block_hash': block, 'height': 103, 'block_total_fee': stats['totalfee'], 'block_transactions_including_coinbase': stats['txs'], 'recipient_amount': litoshis(final_out['value']), 'confirmations': 1}, 'recorded_at_utc': datetime.now(timezone.utc).isoformat(), } if __name__ == '__main__': if len(sys.argv) != 3: raise SystemExit('Usage: python reproduce.py.txt VERIFIED_LITECOIND_EXE OUTPUT_JSON') source, output = (Path(path) for path in sys.argv[1:]) if output.exists() or sha256(source.read_bytes()).hexdigest() != PIN: raise SystemExit('Use a new output path and the pinned Windows x64 daemon.') with TemporaryDirectory(prefix='lw-fee-state-') as tmp: work = Path(tmp) daemon = work / 'litecoind.exe' shutil.copyfile(source, daemon) findings = run(daemon, work) with output.open('x', encoding='utf-8') as stream: json.dump(findings, stream, indent=2) stream.write('\n') print(json.dumps(findings, indent=2))