"""Usage: python reproduce.py.txt VERIFIED_LITECOIND_EXE OUTPUT_JSON One fresh data directory, three disposable wallets and one isolated daemon run. 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', 'owner', 'shop'): node.rpc('createwallet', name) miner = node.rpc('getnewaddress', '', 'bech32', wallet='miner') shared = node.rpc('getnewaddress', 'Shared invoice', 'bech32', wallet='owner') other = node.rpc('getnewaddress', 'Other receipts', 'bech32', wallet='owner') change = node.rpc('getrawchangeaddress', 'bech32', wallet='owner') shop = node.rpc('getnewaddress', 'Sale', 'bech32', wallet='shop') assert len({miner, shared, other, change, shop}) == 5 shared_script = node.rpc('getaddressinfo', shared, wallet='owner')['scriptPubKey'] node.rpc('generatetoaddress', 101, miner) blocks = [] transfers = [] snapshots = [] def mine_transfer(txid, label): block = node.rpc('generatetoaddress', 1, miner)[0] decoded = node.rpc('getrawtransaction', txid, True, block) blocks.append(block) transfers.append({'label': label, 'txid': txid, 'block': block}) assert decoded['confirmations'] == 1 return decoded def receive(address, amount, label): txid = node.rpc('sendtoaddress', address, amount, wallet='miner') signed = node.rpc('gettransaction', txid, wallet='miner')['hex'] assert node.rpc('sendrawtransaction', signed) == txid return mine_transfer(txid, label) def observe(stage, expected): # Read the mined outputs in the four activity blocks, with no wallet endpoint. received = 0 for block in blocks: for tx in node.rpc('getblock', block, 2)['tx']: for output in tx['vout']: if output['scriptPubKey'].get('hex') == shared_script: received += litoshis(output['value']) scan = node.rpc('scantxoutset', 'start', [f'addr({shared})']) assert scan['success'] and scan['bestblock'] == node.rpc('getbestblockhash') unspent = litoshis(scan['total_amount']) assert unspent == sum(litoshis(row['amount']) for row in scan['unspents']) mine = node.rpc('getbalances', wallet='owner')['mine'] wallet = litoshis(mine['trusted']) shop_total = litoshis(node.rpc('getbalances', wallet='shop')['mine']['trusted']) wallet_received = litoshis(node.rpc('getreceivedbyaddress', shared, 1, wallet='owner')) assert wallet_received == received assert (received, unspent, wallet, shop_total) == expected, (stage, received, unspent, wallet, shop_total) assert litoshis(mine['immature']) == litoshis(mine['untrusted_pending']) == 0 snapshots.append({'stage': stage, 'height': scan['height'], 'shared_total_received': received, 'shared_current_unspent': unspent, 'owner_wallet_confirmed_trusted': wallet, 'shop_wallet_confirmed_trusted': shop_total, 'shared_unspent_output_count': len(scan['unspents'])}) observe('before_receipts', (0, 0, 0, 0)) first = receive(shared, 0.60001, 'fund_shared_address') first_index = output_number(first, shared) observe('first_receipt_to_shared_address', (60_001_000, 60_001_000, 60_001_000, 0)) receive(other, 1.4, 'fund_second_address') observe('receipt_to_second_address', (60_001_000, 60_001_000, 200_001_000, 0)) raw = node.rpc('createrawtransaction', [{'txid': first['txid'], 'vout': first_index}], [{shop: 0.30}, {change: 0.30}]) signed = node.rpc('signrawtransactionwithwallet', raw, wallet='owner') assert signed['complete'] funded = mine_transfer(node.rpc('sendrawtransaction', signed['hex']), 'spend_shared_output') assert len(funded['vin']) == 1 and len(funded['vout']) == 2 assert funded['vin'][0]['txid'] == first['txid'] and funded['vin'][0]['vout'] == first_index outputs = [] for addr, role in ((shop, 'shop payment'), (change, 'owner change')): index = output_number(funded, addr) out = funded['vout'][index] assert litoshis(out['value']) == 30_000_000 owner_view = node.rpc('getaddressinfo', addr, wallet='owner')['ismine'] shop_view = node.rpc('getaddressinfo', addr, wallet='shop')['ismine'] assert owner_view == (addr == change) and shop_view == (addr == shop) outputs.append({'index': index, 'address': addr, 'litoshis': litoshis(out['value']), 'script_type': out['scriptPubKey']['type'], 'role_from_private_test_wallets': role, 'owner_wallet_ismine': owner_view, 'shop_wallet_ismine': shop_view}) assert {o['script_type'] for o in outputs} == {'witness_v0_keyhash'} fee = litoshis(first['vout'][first_index]['value']) - sum(row['litoshis'] for row in outputs) stats = node.rpc('getblockstats', blocks[-1], ['totalfee', 'txs']) assert fee == stats['totalfee'] == 1000 and stats['txs'] == 2 observe('shared_output_spent', (60_001_000, 0, 170_000_000, 30_000_000)) assert node.rpc('gettxout', first['txid'], first_index, False) is None receive(shared, 0.1, 'later_receipt_at_same_shared_address') observe('another_receipt_to_shared_address', (70_001_000, 10_000_000, 180_000_000, 30_000_000)) receipt_depth = node.rpc('getrawtransaction', first['txid'], True, blocks[0])['confirmations'] assert receipt_depth == 4 return {'network': 'regtest', 'network_peers': node.rpc('getconnectioncount'), 'core_version': VERSION, 'daemon_sha256': PIN, 'recorded_at_utc': datetime.now(timezone.utc).isoformat(), 'units': 'integer litoshis (100,000,000 per test LTC)', 'shared_address': shared, 'other_owner_receiving_address': other, 'transfers': transfers, 'snapshots': snapshots, 'split_spend': {'funding_txid': first['txid'], 'funding_vout': first_index, 'txid': funded['txid'], 'outputs': outputs, 'fee_litoshis': fee}, 'first_receipt_confirmations_at_end': receipt_depth} if __name__ == '__main__': if len(sys.argv) != 3: raise SystemExit('Usage: python reproduce.py.txt VERIFIED_LITECOIND_EXE NEW_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 Litecoin Core Windows x64 daemon.') with TemporaryDirectory(prefix='lw-address-view-') 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))