"""Usage: python reproduce.py.txt VERIFIED_LITECOIND_EXE OUTPUT_JSON Two disposable data directories. 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'] 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) def run(binary, base): old, fresh = base / 'old', base / 'fresh' old.mkdir() fresh.mkdir() backup = base / 'wallet-backup.dat' with running(binary, old) as a: a.rpc('createwallet', 'miner') a.rpc('createwallet', 'everyday') mining = a.rpc('getnewaddress', '', 'legacy', wallet='miner') receive = a.rpc('getnewaddress', '', 'legacy', wallet='everyday') a.rpc('generatetoaddress', 101, mining) a.rpc('backupwallet', str(backup), wallet='everyday') backup_height = a.rpc('getblockcount') old_balance_at_backup = a.rpc('getbalances', wallet='everyday')['mine']['trusted'] assert old_balance_at_backup == 0 txid = a.rpc('sendtoaddress', receive, 1.25, wallet='miner') block = a.rpc('generatetoaddress', 1, mining)[0] tx = a.rpc('getrawtransaction', txid, True, block) vout = next(o['n'] for o in tx['vout'] if o['scriptPubKey'].get('addresses') == [receive]) assert a.rpc('getbalances', wallet='everyday')['mine']['trusted'] == 1.25 chain = fresh / 'regtest' chain.mkdir() for name in ('blocks', 'chainstate'): shutil.copytree(old / 'regtest' / name, chain / name) with running(binary, fresh) as b: loaded_at_start = b.rpc('listwallets') assert 'everyday' not in loaded_at_start assert b.rpc('getbestblockhash') == block and b.rpc('gettxout', txid, vout)['value'] == 1.25 b.rpc('createwallet', 'everyday') b.rpc('createwallet', 'observer', True) target = b.rpc('getnewaddress', '', 'legacy', wallet='everyday') assert target != receive b.rpc('importaddress', receive, '', True, wallet='observer') payload = b.rpc('createrawtransaction', [{'txid': txid, 'vout': vout}], {target: 1.2499}) blank_balance = b.rpc('getbalances', wallet='everyday')['mine']['trusted'] blank_owns_address = b.rpc('getaddressinfo', receive, wallet='everyday')['ismine'] observation = b.rpc('getbalances', wallet='observer')['watchonly']['trusted'] watch_utxo = b.rpc('listunspent', 1, 9999999, [receive], wallet='observer')[0] watch_signed = b.rpc('signrawtransactionwithwallet', payload, wallet='observer')['complete'] assert blank_balance == 0 and not blank_owns_address assert observation == 1.25 and not watch_utxo['spendable'] and not watch_signed # Supply an actual wallet backup in the new node's separate wallet directory. # Its directory name is deliberately different from the original name. wallet_dir = chain / 'wallets' if (chain / 'wallets').exists() else chain restored_path = wallet_dir / 'restored' restored_path.mkdir() shutil.copyfile(backup, restored_path / 'wallet.dat') b.rpc('loadwallet', 'restored') restored_height = b.rpc('getblockcount') restored_balance = b.rpc('getbalances', wallet='restored')['mine']['trusted'] restored_owns_address = b.rpc('getaddressinfo', receive, wallet='restored')['ismine'] signed = b.rpc('signrawtransactionwithwallet', payload, wallet='restored') assert restored_balance == 1.25 and restored_owns_address and signed['complete'] spend = b.rpc('sendrawtransaction', signed['hex']) b.rpc('generatetoaddress', 1, mining) assert b.rpc('gettxout', txid, vout) is None assert b.rpc('gettransaction', spend, wallet='everyday')['confirmations'] == 1 return {'network': 'regtest', 'version': VERSION, 'daemon_sha256': PIN, 'backup_height': backup_height, 'backup_wallet_balance': old_balance_at_backup, 'deposit': {'txid': txid, 'vout': vout, 'height': restored_height, 'amount_ltc': 1.25}, 'fresh_same_name': {'trusted_ltc': blank_balance, 'owns_address': blank_owns_address}, 'watch_only': {'visible_ltc': observation, 'spendable': watch_utxo['spendable'], 'complete_signature': watch_signed}, 'restored_with_new_name': {'trusted_ltc': restored_balance, 'owns_address': restored_owns_address, 'complete_signature': signed['complete'], 'confirmed_spend_txid': spend}, 'recorded_at_utc': datetime.now(timezone.utc).isoformat()} if __name__ == '__main__': if len(sys.argv) != 3: raise SystemExit(__doc__) 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-wallet-reset-') as tmp: work = Path(tmp) daemon = work / 'litecoind.exe' shutil.copyfile(source, daemon) result = run(daemon, work) with output.open('x', encoding='utf-8') as stream: json.dump(result, stream, indent=2) stream.write('\n') print(json.dumps(result, indent=2))