"""Existing-workload adapter. No shell, Dashmate, reset, volume removal or key export. Docker's effective container configuration stays on its owning host. Enrollment adds private recovery records only. Image replacements preserve exact mounts, network attachments, command/env and published ports; there is no inferred rollback. """ import copy import base64 import datetime import fcntl import hashlib import hmac import http.client import json import os from pathlib import Path import re import socket import subprocess import sys import tempfile import time import urllib.parse import urllib.request class Failure(Exception): pass class Warmup(Exception): pass def require(value, code): if not value: raise Failure(code) def fingerprint(value): return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest() class UnixHTTP(http.client.HTTPConnection): def connect(self): self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.settimeout(self.timeout) self.sock.connect('/var/run/docker.sock') class Engine: def __init__(self): self.version = '' version = self.call('GET', '/version')['ApiVersion'] require(re.fullmatch(r'1\.[0-9]{2,3}', version), 'docker-api-version') self.version = '/v' + version def call(self, method, path, body=None, timeout=120, missing=False): conn = UnixHTTP('localhost', timeout=timeout) try: conn.request(method, self.version + path, body=None if body is None else json.dumps(body), headers={'Content-Type': 'application/json'}) response = conn.getresponse() raw = response.read(16 * 1024 * 1024 + 1) require(len(raw) <= 16 * 1024 * 1024, 'docker-response-size') if missing and response.status == 404: return None require(response.status in [200, 201, 204, 304], 'docker-api-' + str(response.status)) return json.loads(raw) if raw else None finally: conn.close() def inspect(self, name): return self.call('GET', '/containers/' + urllib.parse.quote(name, safe='') + '/json', missing=True) def image(self, name): return self.call('GET', '/images/' + urllib.parse.quote(name, safe='') + '/json', missing=True) def run(args, stdin=None, timeout=60): p = subprocess.run(args, input=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, check=False) require(p.returncode == 0, 'command-failed') require(len(p.stdout) <= 2 * 1024 * 1024, 'command-output-size') return p.stdout def protobuf(raw): fields, pos = {}, 0 def varint(): nonlocal pos value = 0 for shift in range(0, 70, 7): require(pos < len(raw), 'protobuf-truncated') b = raw[pos]; pos += 1; value |= (b & 127) << shift if b < 128: return value raise Failure('protobuf-varint') while pos < len(raw): tag = varint(); number, wire = tag >> 3, tag & 7 require(number and number not in fields, 'protobuf-field') if wire == 0: value = varint() elif wire in [1, 2, 5]: size = varint() if wire == 2 else (8 if wire == 1 else 4) require(size <= len(raw) - pos, 'protobuf-size') value = raw[pos:pos+size]; pos += size else: raise Failure('protobuf-wire') fields[number] = value return fields class Worker: def __init__(self, q, engine=None, root=None): self.q, self.f, self.t = q, q['fleet'], q['target'] self.engine = engine self.root = root or Path('/var/lib/dashnet-managed') / self.f['metadata']['name'] self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) def identity(self): request = urllib.request.Request('http://169.254.169.254/latest/api/token', method='PUT', headers={'X-aws-ec2-metadata-token-ttl-seconds': '60'}) with self.opener.open(request, timeout=5) as response: token = response.read(4096).decode() request = urllib.request.Request('http://169.254.169.254/latest/dynamic/instance-identity/document', headers={'X-aws-ec2-metadata-token': token}) with self.opener.open(request, timeout=5) as response: value = json.loads(response.read(65536)) require(value['instanceId'] == self.t['instanceId'] and value['accountId'] == self.f['accountId'] and value['region'] == self.f['region'], 'instance-identity') def atomic(self, name, value): self.root.mkdir(mode=0o700, parents=True, exist_ok=True) require(not self.root.is_symlink() and not (self.root/name).is_symlink(), 'state-symlink') fd, temp = tempfile.mkstemp(prefix='.pending-', dir=self.root) try: with os.fdopen(fd, 'w') as stream: json.dump(value, stream, sort_keys=True); stream.flush(); os.fsync(stream.fileno()) os.replace(temp, self.root/name) d = os.open(self.root, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(d) finally: os.close(d) finally: if os.path.exists(temp): os.unlink(temp) def read(self, name): p = self.root/name require(not p.is_symlink(), 'state-symlink') return json.loads(p.read_text()) if p.exists() else None def recipe(self, c): config, host = copy.deepcopy(c['Config']), copy.deepcopy(c['HostConfig']) # All realized volumes—including anonymous image volumes—become exact # existing sources. Docker must not silently allocate fresh state. require(not host.get('AutoRemove') and not host.get('VolumesFrom') and not host.get('Links'), 'unsupported-container-lifecycle') require(not host.get('NetworkMode', '').startswith(('container:', 'service:')), 'unsupported-network-mode') mounts, binds = [], [] declared = {m['Target']:m for m in (host.get('Mounts') or [])} for m in c['Mounts']: original = declared.get(m['Destination']) if m['Type'] == 'tmpfs': # Do not turn an API-configured memory mount into a disk path. if original: require(original['Type']=='tmpfs','mount-type-changed') mounts.append(copy.deepcopy(original)) else:require(m['Destination'] in (host.get('Tmpfs') or {}),'unsupported-tmpfs') continue require(m['Type'] in ['bind', 'volume'], 'unsupported-mount-type') source=m.get('Name') if m['Type']=='volume' else m['Source'] if original is None: # Keep legacy -v flags (including testnet's SELinux :Z). # Realized names make anonymous volumes explicit as well. require(source and ':' not in source and ':' not in m['Destination'],'unsupported-legacy-mount-path') options={x for x in (m.get('Mode') or '').split(',') if x} options.discard('rw');options.discard('ro') options.add('rw' if m['RW'] else 'ro') if m['Type']=='volume':options.add('nocopy') binds.append(source+':'+m['Destination']+':'+','.join(sorted(options))) continue # Keep subpaths, recursive read-only settings and driver options # from API mounts rather than reconstructing only their sources. value=copy.deepcopy(original) require(original['Type']==m['Type'],'mount-type-changed') value.update(Type=m['Type'], Source=m.get('Name') if m['Type']=='volume' else m['Source'], Target=m['Destination'], ReadOnly=not m['RW']) if m['Type']=='bind': value['BindOptions']=dict(value.get('BindOptions') or {}) value['BindOptions']['Propagation']=m.get('Propagation') or 'rprivate' else: value['VolumeOptions']=dict(value.get('VolumeOptions') or {}) value['VolumeOptions']['NoCopy']=True mounts.append(value) host['Binds'] = sorted(binds) or None host['Mounts'] = sorted(mounts, key=lambda m: m['Target']) # Endpoint runtime IDs/IPs are not configuration. Preserve configured # IPAM, stable aliases and driver options, not the old container ID alias. endpoints = {} for name, n in c['NetworkSettings'].get('Networks', {}).items(): aliases = [a for a in (n.get('Aliases') or []) if a not in [c['Id'], c['Id'][:12]]] endpoints[name] = dict(IPAMConfig=n.get('IPAMConfig'), Aliases=aliases, DriverOpts=n.get('DriverOpts')) return dict(Config=config, HostConfig=host, NetworkingConfig=dict(EndpointsConfig=endpoints)) def config_hash(self, recipe): value = copy.deepcopy(recipe); value['Config'].pop('Image', None) # Docker expands a few null default fields when creating from an API # spec. Normalize only representational defaults, never env/args/mounts. def normalize(v): if isinstance(v,dict):return {k:normalize(x) for k,x in v.items() if x is not None and x != [] and x != {}} if isinstance(v,list):return [normalize(x) for x in v] return v return fingerprint(normalize(value)) def containers(self): allc = self.engine.call('GET','/containers/json?all=1') selected, companions = {}, {} expected = self.t['containers']; reverse = {v:k for k,v in expected.items()} for item in allc: c = self.engine.inspect(item['Id']); name = c['Name'].lstrip('/') if name in reverse: selected[reverse[name]] = c else: companions[name] = c require(set(selected) == set(expected), 'missing-selected-container') return selected, companions def configuration_digest(self, path): data = path.read_bytes() # Dashmate renders fresh rpcauth salts even for read-only core-cli # commands. Normalize ONLY after verifying each HMAC against the # named profile's on-host credential. A changed user/password or any # other byte still changes the fingerprint; credentials never leave. if (path.name == 'dash.conf' and path.parent.name == 'core' and path.parents[2].name == '.dashmate'): source = path.parents[2] / 'config.json' if source.exists(): require(source.is_file() and not source.is_symlink() and source.stat().st_size <= 2*1024*1024, 'rpc-auth-source') profiles = json.loads(source.read_text()) users = profiles['configs'][path.parents[1].name]['core']['rpc']['users'] lines = [] for line in data.decode().splitlines(keepends=True): if line.startswith('rpcauth='): entry = line[len('rpcauth='):].strip() user, auth = entry.split(':', 1) salt, digest = auth.split('$', 1) password = users.get(user, {}).get('password') require(isinstance(password, str) and bool(password), 'rpc-auth-source') verified = hmac.new(salt.encode(), password.encode(), hashlib.sha256).hexdigest() require(hmac.compare_digest(verified, digest), 'rpc-auth-source-mismatch') identity = fingerprint(['dashnet-rpcauth-v1', user, password]) ending = '\r\n' if line.endswith('\r\n') else ('\n' if line.endswith('\n') else '') line = 'rpcauth=' + user + ':verified-credential-' + identity + ending lines.append(line) data = ''.join(lines).encode() return hashlib.sha256(data).hexdigest() def files_hash(self, selected, migration=None): files = {} for c in selected.values(): for m in c['Mounts']: if m['Type']!='bind':continue target=m['Destination']; source=Path(m['Source']) # Persistent databases/logs and validator signing *state* are # mutable. Hash only identity/configuration mounts. if not (target.endswith(('.conf','.toml','.yaml','.yml','.crt','.key')) or target.endswith('/config')):continue paths=sorted(source.rglob('*')) if source.is_dir() else [source] for p in paths: if p.is_dir():continue require(not p.is_symlink() and p.is_file() and p.stat().st_size<=2*1024*1024,'unsupported-config-file') if p.name.endswith('.lock') or p.name=='priv_validator_state.json':continue digest = self.configuration_digest(p) if migration and str(p) in migration: record = migration[str(p)] raw = p.read_bytes() require(raw in [base64.b64decode(record['before']), base64.b64decode(record['after'])], 'migration-file-drift') digest = record['digest'] files[str(p)]=digest require(len(files)<=200,'configuration-file-count') return fingerprint(files) def summary(self, c): image=self.engine.image(c['Image']);require(image is not None,'missing-image') require(image['Architecture']==self.t['architecture'] and image['Os']=='linux','image-architecture') return dict(id=c['Id'],imageId=c['Image'],image=c['Config']['Image'],digests=image.get('RepoDigests',[]), configHash=self.config_hash(self.recipe(c)),running=c['State']['Running'] and not c['State'].get('Restarting'), startedAt=c['State']['StartedAt'],restarts=c['RestartCount']) def rpc(self, selected, method, *args): core=selected['core'] paths=[m['Destination'] for m in core['Mounts'] if m['Destination'].endswith('/dash.conf')] require(len(paths)==1,'core-config-mount') p=subprocess.run(['docker','exec',core['Id'],'dash-cli','-conf='+paths[0],method,*[str(x) for x in args]], stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=60,check=False) # dash-cli exits 28 (RPC_IN_WARMUP) while dashd loads, migrates or # verifies its databases; its last stderr line is dashd's init message. if p.returncode==28:raise Warmup(re.sub(r'[^A-Za-z0-9 .,:()/%-]','',p.stderr.decode(errors='replace').strip().splitlines()[-1] if p.stderr.strip() else '')[:80].strip()) require(p.returncode==0,'command-failed');require(len(p.stdout)<=2*1024*1024,'command-output-size') raw=p.stdout try:return json.loads(raw) except json.JSONDecodeError:return raw.decode().strip() def http(self, port, method): with self.opener.open('http://127.0.0.1:'+str(port)+'/'+method,timeout=15) as response: raw=response.read(1024*1024+1) require(len(raw)<=1024*1024,'tenderdash-response-size') value=json.loads(raw);require(isinstance(value,dict) and value.get('error') is None,'tenderdash-rpc') return value.get('result',value) def port(self,c,container_port): bindings=c['HostConfig'].get('PortBindings') or {} values=bindings.get(str(container_port)+'/tcp') or [] require(len(values)==1 and values[0].get('HostIp','') in ['', '0.0.0.0','127.0.0.1'], 'unsupported-port-binding') return int(values[0]['HostPort']) def dapi(self, selected): gateway=selected['gateway'];port=self.port(gateway,10000) cert=[m['Source'] for m in gateway['Mounts'] if m['Destination'].endswith('/bundle.crt')] require(len(cert)==1,'gateway-trust-mount') with tempfile.TemporaryDirectory(prefix='dashnet-probe-') as d: headers=Path(d)/'headers' raw=run(['curl','--silent','--show-error','--fail','--noproxy','*','--max-time','20', '--http2','--cacert',cert[0],'--connect-to',self.t['address']+':'+str(port)+':127.0.0.1:'+str(port), '-D',str(headers),'-H','content-type: application/grpc','-H','te: trailers', '--data-binary','@-','https://'+self.t['address']+':'+str(port)+'/org.dash.platform.dapi.v0.Platform/getStatus'], stdin=b'\x00\x00\x00\x00\x02\x0a\x00',timeout=25) require('grpc-status: 0' in headers.read_text().lower().splitlines(),'dapi-grpc') require(len(raw)>=5 and raw[0]==0 and int.from_bytes(raw[1:5],'big')==len(raw)-5,'dapi-frame') value=protobuf(protobuf(raw[5:])[1]);software=protobuf(protobuf(value[1])[1]);chain=protobuf(value[3]);network=protobuf(value[4]);identity=protobuf(value[2]) require(software.get(2) and software.get(3) and not chain.get(1,0),'dapi-upstream') return dict(height=chain.get(4,0),chain=network[1].decode(),node=identity[1].hex(),protx=identity[2].hex()) def health(self, selected): chain={};problems=[] if 'core' in selected: try: info=self.rpc(selected,'getblockchaininfo');sync=self.rpc(selected,'mnsync','status') chain.update(coreNetwork=info['chain'],coreGenesis=self.rpc(selected,'getblockhash',1 if self.f['chainType']=='devnet' else 0), coreHash=info['bestblockhash'], coreHeight=info['blocks'],coreSynced=not info['initialblockdownload'] and sync['IsSynced'] and sync['IsBlockchainSynced'], chainLockHeight=self.rpc(selected,'getbestchainlock')['height']) if self.q.get('coreCheckpointHeight'): chain['coreCheckpointHash']=self.rpc(selected,'getblockhash',self.q['coreCheckpointHeight']) require(info['chain']==self.f['coreNetwork'],'wrong-core-chain') if self.t['role'] in ['validator','masternode']: mn=self.rpc(selected,'masternode','status');chain.update(masternodeState=mn.get('state',''),proTxHash=mn.get('proTxHash','')) if chain['proTxHash']: protx=self.rpc(selected,'protx','info',chain['proTxHash']) chain['posePenalty']=int(protx['state']['PoSePenalty']) except Warmup as w:problems.append('core-starting: '+(str(w) or 'RPC warm-up')) except Exception:problems.append('core-health-unavailable') if self.t['role']=='validator': try: port=self.port(selected['tenderdash'],36657);status=self.http(port,'status');members=self.http(port,'validators') require(len(members['validators'])==int(members['total']),'incomplete-validator-membership') powers={v['pro_tx_hash'].lower():int(v['voting_power']) for v in members['validators']} require(len(powers)==len(members['validators']) and all(v>0 for v in powers.values()),'validator-membership') reference=self.q.get('referenceHeight',0) block=self.http(port,'block?height='+str(reference))['block_id']['hash'].lower() if reference else '' dapi=self.dapi(selected) require(dapi['chain']==status['node_info']['network'] and dapi['protx']==chain.get('proTxHash',''),'dapi-identity') chain.update(platformChainId=dapi['chain'],platformHeight=int(status['sync_info']['latest_block_height']), platformHash=block,platformProtocol=int(status['node_info']['protocol_version']['app']),platformNodeId=dapi['node'], catchingUp=status['sync_info']['catching_up'],votingPower=powers,dapiHeight=dapi['height'],dapiHealthy=True) except Exception:problems.append('platform-health-unavailable') return chain,problems def native_processes(self): # Preserve native seed Core/Tor processes too; never export cmdlines. result={} for p in Path('/proc').iterdir(): if not p.name.isdigit():continue try: comm=(p/'comm').read_text().strip() if comm not in ['dashd','tor']:continue stat=(p/'stat').read_text().rsplit(')',1)[1].split() result[comm+':'+p.name]=fingerprint(dict(comm=comm,start=stat[19],command=hashlib.sha256((p/'cmdline').read_bytes()).hexdigest())) except (FileNotFoundError,ProcessLookupError):continue return result def observe(self): selected,companions=self.containers() components={k:self.summary(v) for k,v in selected.items()} # Unknown companions are preserved, even if they are not Dash services. extra={k:dict(id=v['Id'],imageId=v['Image'],image=v['Config']['Image'],digests=[],configHash=self.config_hash(self.recipe(v)), running=v['State']['Running'],startedAt=v['State']['StartedAt'],restarts=v['RestartCount']) for k,v in companions.items()} chain,problems=self.health(selected) for k,c in selected.items():require(self.engine.inspect(c['Id']) is not None,'concurrent-container-change') result = dict(instanceId=self.t['instanceId'],at=datetime.datetime.now(datetime.timezone.utc).isoformat(), components=components,companions=extra,nativeProcesses=self.native_processes(),filesHash=self.files_hash(selected),chain=chain,problems=problems) if self.t.get('miningService'): result['mining']=self.mining_receipt() marker = self.read('operation.json') if marker and marker.get('migration') and marker.get('migrationPhase') == 'installed': records = marker['migrationFiles'] for path, record in records.items(): require(Path(path).read_bytes() == base64.b64decode(record['after']), 'migration-file-drift') before = self.files_hash(selected, records) require(before == marker['baseline']['filesHash'], 'migration-unrelated-file-drift') result['migration'] = dict(operationId=marker['id'], before=before, after=result['filesHash']) return result def admit(self): self.owner() require(self.q.get('migration',{}).get('kind')=='legacy-testnet-v5','migration-policy') selected,_=self.containers() self.migration_window(selected) return self.observe() def mining_service(self): require(self.f['chainType']=='testnet' and self.t['role']=='core' and self.t.get('miningService')=='dashd-generate-miner.service','mining-target') unit=self.t['miningService'] properties=run(['systemctl','show',unit,'-p','LoadState','-p','FragmentPath','-p','DropInPaths','-p','User','-p','Group']) unit_text=run(['systemctl','cat',unit]) require(b'LoadState=loaded' in properties and b'/usr/local/bin/dashd-generate-miner.sh' in unit_text,'mining-unit-layout') script=Path('/usr/local/bin/dashd-generate-miner.sh') require(script.is_file() and not script.is_symlink(),'mining-script-layout') digest=hashlib.sha256(properties+b'\0'+unit_text+b'\0'+script.read_bytes()).hexdigest() state=run(['systemctl','show',unit,'--property=ActiveState','--value']).decode().strip() require(state in ['active','inactive'],'mining-service-transition') return digest,state=='active' def mining_receipt(self): digest,active=self.mining_service() marker=self.read('mining-pause.json') or {} return dict(serviceHash=digest,active=active,operationId=marker.get('operationId',''), paused=bool(marker.get('paused')) and not active,expiresAt=marker.get('expiresAt',0)) def mining_guard(self): self.owner() m=self.q.get('migration') or {} require(m.get('kind')=='legacy-testnet-v5' and m.get('readinessDriven') and self.t['name'] in m.get('miners',[]) and re.fullmatch('[0-9a-f]{64}',self.q.get('operationId','')), 'mining-policy') return self.mining_service() def arm_mining_recovery(self, marker): recovery = '''import fcntl,hashlib,json,os,subprocess,sys,tempfile from pathlib import Path root=Path(sys.argv[1]);token=sys.argv[2] with open('/run/dashnet-managed.lock','a') as lock: fcntl.flock(lock,fcntl.LOCK_EX) path=root/'mining-pause.json' if not path.exists():sys.exit(0) m=json.loads(path.read_text()) if not m.get('paused') or m.get('token')!=token:sys.exit(0) properties=subprocess.check_output(['systemctl','show','dashd-generate-miner.service','-p','LoadState','-p','FragmentPath','-p','DropInPaths','-p','User','-p','Group'],timeout=30) unit_text=subprocess.check_output(['systemctl','cat','dashd-generate-miner.service'],timeout=30) digest=hashlib.sha256(properties+b'\\0'+unit_text+b'\\0'+Path('/usr/local/bin/dashd-generate-miner.sh').read_bytes()).hexdigest() if digest!=m['serviceHash']:sys.exit(1) subprocess.run(['systemctl','start','dashd-generate-miner.service'],check=True,timeout=60) m['paused']=False;m['watchdogResumed']=True fd,tmp=tempfile.mkstemp(dir=root,prefix='.mining-') with os.fdopen(fd,'w') as f:json.dump(m,f);f.flush();os.fsync(f.fileno()) os.replace(tmp,path) ''' run(['systemd-run','--quiet','--unit=dashnet-mining-'+marker['token'], '--on-active=900s','--collect', '--timer-property=AccuracySec=1s','/usr/bin/python3','-c',recovery,str(self.root),marker['token']]) def mining_pause(self): digest,active=self.mining_guard() expected=self.q['expected'].get('mining') or {} require(digest==expected.get('serviceHash') and expected.get('active'),'mining-service-drift') self.assert_baseline(self.observe(),self.q['expected']) marker=self.read('mining-pause.json') if marker and marker.get('paused'): require(marker['operationId']==self.q['operationId'] and marker['serviceHash']==digest and not active and marker['expiresAt']>time.time(),'mining-existing-pause') if self.q['migration'].get('fleetMiningPause'): self.mining_renew() else:require(marker['expiresAt']>time.time()+660,'mining-existing-pause') else: require(active,'mining-not-originally-active') marker=dict(operationId=self.q['operationId'],paused=True,expiresAt=int(time.time())+900, serviceHash=digest,token=os.urandom(16).hex()) self.atomic('mining-pause.json',marker) # Arm independent recovery BEFORE stopping anything. Unique token # and host lock prevent an old timer from resuming a later pause. self.arm_mining_recovery(marker) run(['systemctl','stop',self.t['miningService']],timeout=90) selected,_=self.containers() # Killing a CLI does not necessarily cancel its in-flight mining RPC. # Require server-side generation work to drain, without stopping Core. deadline=time.monotonic()+90 while True: info=self.rpc(selected,'getrpcinfo') require(isinstance(info.get('active_commands'),list),'mining-rpc-observation') if not any(c.get('method') in ['generate','generatetoaddress','generateblock'] for c in info['active_commands']):break require(time.monotonic()time.time(),'mining-lease-lost') require(digest==self.q['expected']['mining']['serviceHash'],'mining-service-drift') # Arm the replacement BEFORE superseding the old receipt/token. A crash # or failed arm leaves the existing watchdog authoritative, never a gap. old_token=marker['token'] renewed=dict(marker,token=os.urandom(16).hex(),expiresAt=int(time.time())+900) self.arm_mining_recovery(renewed) self.atomic('mining-pause.json',renewed) try:run(['systemctl','stop','dashnet-mining-'+old_token+'.timer'],timeout=30) except Exception:pass # Old tokens cannot start mining after renewal. return self.observe() def mining_status(self): digest,active=self.mining_guard() marker=self.read('mining-pause.json') require(marker and marker['operationId']==self.q['operationId'] and marker['serviceHash']==digest,'mining-owner-or-drift') return self.observe() def mining_resume(self): digest,active=self.mining_guard() marker=self.read('mining-pause.json') if marker and marker.get('paused'): require(marker['operationId']==self.q['operationId'] and marker['serviceHash']==digest,'mining-owner-or-drift') run(['systemctl','start',self.t['miningService']],timeout=60) require(self.mining_service()[1],'mining-resume-failed') marker['paused']=False self.atomic('mining-pause.json',marker) else:require(active,'mining-unowned-inactive') return self.observe() def assert_baseline(self, actual, baseline, mutable=()): files = actual['filesHash'] receipt = actual.get('migration') if self.q.get('migration') and receipt and receipt['operationId'] == self.q.get('operationId') and receipt['after'] == files: files = receipt['before'] require(files==baseline['filesHash'],'configuration-files-changed') require(actual['companions']==baseline['companions'],'companion-changed') keep=lambda m:{k:v for k,v in m.items() if 'core' not in mutable or not k.startswith('dashd:')} require(keep(actual['nativeProcesses'])==keep(baseline['nativeProcesses']),'native-core-or-tor-changed') for k,b in baseline['components'].items(): a=actual['components'][k] require(a['configHash']==b['configHash'],'workload-configuration-changed') if k not in mutable:require(a==b,'preserved-service-changed') def owner(self): owner=self.read('owner.json') require(owner==dict(fleetId=self.q['fleetId'],instanceId=self.t['instanceId']),'not-enrolled') def enroll(self): actual=self.observe();self.assert_baseline(actual,self.q['expected']) selected,_=self.containers() value=self.read('owner.json') require(value is None or value==dict(fleetId=self.q['fleetId'],instanceId=self.t['instanceId']),'different-owner') if value is None: self.atomic('workloads.json',{k:self.recipe(c) for k,c in selected.items()}) self.atomic('owner.json',dict(fleetId=self.q['fleetId'],instanceId=self.t['instanceId'])) return actual def stage(self): self.owner() for pin in self.q['pins'].values(): require(re.fullmatch(r'[a-zA-Z0-9./:_-]+@sha256:[0-9a-f]{64}',pin),'image-pin') image=self.engine.image(pin) if image is None: run(['docker','pull','--platform','linux/'+self.t['architecture'],pin],timeout=600) image=self.engine.image(pin) require(image and image['Architecture']==self.t['architecture'] and image['Os']=='linux' and any(d.split('@')[-1]==pin.split('@')[-1] for d in image.get('RepoDigests',[])),'image-proof') if self.q.get('migration'): self.validate_migration() marker = self.read('operation.json') if marker and marker['id'] == self.q['operationId']: self.clean_migration_temp(marker) self.operation_guard(marker) else: selected, _ = self.containers() self.migration_files(selected) # fail before the first withdrawal return dict(instanceId=self.t['instanceId']) def validate_migration(self): require(self.q['migration']['kind'] == 'legacy-testnet-v5' and self.f['chainType'] == 'testnet' and self.t['role'] == 'validator' and self.q['operation'] == 'upgrade' and set(self.q['pins']) == {'core', 'drive', 'tenderdash', 'dapi'}, 'migration-scope') # Compare the actual image ID, not a version tag (including custom builds). core = self.engine.image(self.q['pins']['core']) require(core and core['Id'] == self.q['expected']['components']['core']['imageId'], 'migration-core-image-changed') for component in ['drive', 'dapi']: image = self.engine.image(self.q['pins'][component]) require(image and image['Id'] != self.q['expected']['components'][component]['imageId'], 'migration-old-platform-image') # Source must actually be Core 24; an image tag is not this proof. # During recovery Core may be stopped, so the check is made before # recording the first migration, not repeated on a half-applied host. marker = self.read('operation.json') if not marker or marker['id'] != self.q['operationId']: selected, companions = self.containers() namespaces = {c['Id'] for c in selected.values()} | set(self.t['containers'].values()) for c in companions.values(): require(c['HostConfig'].get('NetworkMode', '').removeprefix('container:') not in namespaces, 'migration-shared-companion-namespace') version = self.rpc(selected, 'getnetworkinfo').get('subversion', '') require(re.fullmatch(r'/Dash Core:24\.[0-9]+\.[0-9]+[^/]*/', version), 'migration-requires-core24') @staticmethod def migrate_core(data, user): """Only additive RPC permissions and the Core 24 compatibility output. Core intersects repeated whitelist entries: extend EVERY matching line, not a new permissive line. No credentials or other users are changed. Unknown include layouts fail rather than guessing effective permissions. """ text = data.decode('utf-8') output, found, deprecated = [], False, False section = '' for line in text.splitlines(keepends=True): stripped = line.strip() if stripped.startswith('['): section = stripped key, sep, value = stripped.partition('=') key, value = key.strip(), value.strip() require(key != 'includeconf', 'migration-includeconf-unsupported') if sep and key == 'deprecatedrpc' and value == 'service' and section in ['', '[test]']: deprecated = True if sep and key == 'rpcwhitelist': name, colon, methods = value.partition(':') if name == user: require(colon and section in ['', '[test]'] and '#' not in methods and ';' not in methods, 'migration-rpc-whitelist-layout') ending = '\r\n' if line.endswith('\r\n') else '\n' methods = methods.split(',') if methods else [] for method in ['getspecialtxes', 'getdeploymentinfo']: if method not in methods: methods.append(method) line = 'rpcwhitelist=' + user + ':' + ','.join(methods) + ending found = True output.append(line) require(found, 'migration-consensus-whitelist-missing') if not deprecated: output.insert(0, 'deprecatedrpc=service\n') return ''.join(output).encode() @staticmethod def migrate_tenderdash(data): output, section = [], '' for line in data.decode('utf-8').splitlines(keepends=True): stripped = line.strip() if stripped.startswith('['): section = stripped key = stripped.partition('=')[0].strip() if key in ['unsafe-commit-timeout-override', 'unsafe-bypass-commit-timeout-override']: require(section == '[consensus]', 'migration-tenderdash-layout') continue output.append(line) return ''.join(output).encode() def migration_files(self, selected): env = dict(x.split('=', 1) for x in selected['drive']['Config'].get('Env', []) if '=' in x) user = env.get('CORE_CONSENSUS_JSON_RPC_USERNAME') require(user == 'drive_consensus', 'migration-consensus-user') paths = [Path(m['Source']) for m in selected['core']['Mounts'] if m['Type'] == 'bind' and m['Destination'].endswith('/dash.conf')] require(len(paths) == 1, 'migration-core-config-mount') core = paths[0] paths = [] for m in selected['tenderdash']['Mounts']: if m['Type'] != 'bind': continue if m['Destination'].endswith('/config.toml'): paths.append(Path(m['Source'])) elif m['Destination'].endswith('/config'): paths.append(Path(m['Source']) / 'config.toml') require(len(paths) == 1 and paths[0] != core, 'migration-tenderdash-config-mount') records = {} for path, transform in [(core, lambda b: self.migrate_core(b, user)), (paths[0], self.migrate_tenderdash)]: require(path.is_file() and not path.is_symlink() and path.resolve() == path and path.stat().st_size <= 2*1024*1024, 'migration-config-file') before = path.read_bytes() after = transform(before) st = path.stat() records[str(path)] = dict(before=base64.b64encode(before).decode(), after=base64.b64encode(after).decode(), digest=self.configuration_digest(path), uid=st.st_uid, gid=st.st_gid, mode=st.st_mode & 0o777) # These backups remain in the root-only host journal, never in output. return records def migration_window(self, selected): epoch = datetime.datetime.fromisoformat(self.q['migration']['epochStart'].replace('Z', '+00:00')) require(epoch.tzinfo is not None, 'migration-epoch-timezone') now = datetime.datetime.now(datetime.timezone.utc) elapsed = (now - epoch).total_seconds() require(elapsed >= 0, 'migration-epoch-future') # Five minutes after the boundary, ten minutes before the next. This # admission budget is not a guarantee that an unhealthy node recovers. require(300 <= elapsed % 3600 < 3000, 'migration-epoch-window') # Owned miners can be paused, but public miners remain outside control. height = self.rpc(selected, 'getblockcount') require(13 <= height % 24 <= 20, 'migration-dkg-window') if self.q['migration'].get('readinessDriven'): status=self.rpc(selected,'quorum','dkgstatus') sessions=status.get('session') require(isinstance(sessions,list) and bool(sessions),'migration-dkg-unobserved') phases=[] def collect(value): if isinstance(value,dict): for key,item in value.items(): if key=='phase':phases.append(item) else:collect(item) elif isinstance(value,list): for item in value:collect(item) collect(sessions) require(bool(phases) and all(p==6 for p in phases),'migration-dkg-active') if self.q.get('coreCheckpointHeight'): require(height>=self.q['coreCheckpointHeight'] and self.rpc(selected,'getblockhash',self.q['coreCheckpointHeight'])==self.q['coreCheckpointHash'], 'migration-core-checkpoint') def install_migration(self, marker): if marker.get('migrationPhase') == 'installed': return if marker.get('migrationPhase') in [None, 'stopping']: selected, _ = self.containers() # A stop-intent checkpoint is not evidence that a stop occurred. # Recheck the admission window if a lost request left everything up. if not marker.get('migrationPhase') or all(selected[k]['State']['Running'] for k in self.q['pins']): self.migration_window(selected) marker['migrationPhase'] = 'stopping' self.atomic('operation.json', marker) # A lost stop response is replayed before any file is written. No # automatic restart of old Drive after the first withdrawal. for k in ['dapi', 'tenderdash', 'drive', 'core']: c = self.engine.inspect(self.t['containers'][k]) require(c is not None, 'migration-source-missing') self.engine.call('POST', '/containers/' + c['Id'] + '/stop?t=120', timeout=150) marker['migrationPhase'] = 'writing' self.atomic('operation.json', marker) for name, record in marker['migrationFiles'].items(): path = Path(name) before, after = base64.b64decode(record['before']), base64.b64decode(record['after']) require(path.is_file() and not path.is_symlink() and path.read_bytes() in [before, after], 'migration-file-drift') if path.read_bytes() == after: continue temp = str(path.parent / ('.dashnet-migration-' + marker['id'] + '-' + path.name)) fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) try: with os.fdopen(fd, 'wb') as stream: os.fchmod(stream.fileno(), record['mode']) os.fchown(stream.fileno(), record['uid'], record['gid']) stream.write(after); stream.flush(); os.fsync(stream.fileno()) os.replace(temp, path) directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) finally: if os.path.exists(temp): os.unlink(temp) marker['migrationPhase'] = 'installed' self.atomic('operation.json', marker) def clean_migration_temp(self, marker): # A hard kill can leave a partly written same-directory temp. Its exact # name and permitted bytes are bound to the durable operation, never a # wildcard deletion or an exemption from the configuration fingerprint. if marker.get('migrationPhase') != 'writing': return for name, record in marker.get('migrationFiles', {}).items(): path = Path(name) temp = path.parent / ('.dashnet-migration-' + marker['id'] + '-' + path.name) if not temp.exists(): continue require(not temp.is_symlink() and temp.is_file() and temp.stat().st_size <= len(base64.b64decode(record['after'])) and base64.b64decode(record['after']).startswith(temp.read_bytes()), 'migration-temporary-drift') temp.unlink() def wait_migrated_core(self): deadline = time.monotonic() + 300 while time.monotonic() < deadline: try: core = self.engine.inspect(self.t['containers']['core']) selected = {'core': core} self.rpc(selected, 'getdeploymentinfo') info = self.rpc(selected, 'getblockchaininfo') sync = self.rpc(selected, 'mnsync', 'status') if not info['initialblockdownload'] and sync.get('IsSynced') and sync.get('IsBlockchainSynced'): drive = self.engine.inspect(self.t['containers']['drive']) env = dict(x.split('=', 1) for x in drive['Config'].get('Env', []) if '=' in x) password = env.get('CORE_CONSENSUS_JSON_RPC_PASSWORD') require(password and '\n' not in password, 'migration-consensus-password') paths = [m['Destination'] for m in core['Mounts'] if m['Destination'].endswith('/dash.conf')] require(len(paths) == 1, 'migration-core-config-mount') for method in [['getdeploymentinfo'], ['getspecialtxes', info['bestblockhash']]]: result = subprocess.run(['docker', 'exec', '-i', core['Id'], 'dash-cli', '-conf=' + paths[0], '-rpcuser=drive_consensus', '-stdinrpcpass', *method], input=(password+'\n').encode(), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=False) require(result.returncode == 0, 'migration-consensus-rpc-denied') return except (Failure, Warmup, subprocess.TimeoutExpired): pass time.sleep(3) raise Failure('migration-core-readiness-timeout') def operation_guard(self, marker): # Recheck unaffected workloads and files even when the selected container # is absent between remove/create. Missing selected mounts are reconstructed # from the saved private recipe, never from user-provided paths. baseline=marker['baseline'];pins=marker['pins'];selected={};companions={} reverse={v:k for k,v in self.t['containers'].items()} for item in self.engine.call('GET','/containers/json?all=1'): c=self.engine.inspect(item['Id']);name=c['Name'].lstrip('/') if name in reverse:selected[reverse[name]]=c else: companions[name]=dict(id=c['Id'],imageId=c['Image'],image=c['Config']['Image'],digests=[], configHash=self.config_hash(self.recipe(c)),running=c['State']['Running'], startedAt=c['State']['StartedAt'],restarts=c['RestartCount']) require(companions==baseline['companions'],'companion-changed') keep=lambda m:{k:v for k,v in m.items() if 'core' not in pins or not k.startswith('dashd:')} require(keep(self.native_processes())==keep(baseline['nativeProcesses']),'native-core-or-tor-changed') file_sources={} for k,b in baseline['components'].items(): c=selected.get(k) if c is None: require(k in pins and marker['phase']=='applying','missing-preserved-container') mounts=[] for m in marker['recipes'][k]['HostConfig']['Mounts']: if m['Type']=='bind':mounts.append(dict(Type='bind',Source=m['Source'],Destination=m['Target'])) for bind in marker['recipes'][k]['HostConfig'].get('Binds') or []: source,target,_=bind.split(':',2) if source.startswith('/'):mounts.append(dict(Type='bind',Source=source,Destination=target)) file_sources[k]=dict(Mounts=mounts) continue a=self.summary(c) require(a['configHash']==b['configHash'],'workload-configuration-changed') if k not in pins:require(a==b,'preserved-service-changed') elif k in marker['completed']:require(c['Id']==marker['completed'][k],'applied-container-replaced') else: desired=self.engine.image(pins[k]);require(desired is not None,'image-not-staged') require((c['Id']==b['id'] and c['Image']==b['imageId']) or c['Image']==desired['Id'],'unexpected-selected-container') file_sources[k]=c require(self.files_hash(file_sources, marker.get('migrationFiles'))==baseline['filesHash'],'configuration-files-changed') def wait_abci(self): drive=self.engine.inspect(self.t['containers']['drive']) td=self.engine.inspect(self.t['containers']['tenderdash']) env=dict(v.split('=',1) for v in drive['Config'].get('Env',[]) if '=' in v) address=urllib.parse.urlparse(env.get('ABCI_CONSENSUS_BIND_ADDRESS','')) require(address.scheme=='tcp' and address.port and address.hostname,'unsupported-abci-listener') host=address.hostname if drive['HostConfig']['NetworkMode']=='host': require(host in ['0.0.0.0','127.0.0.1','::','::1'],'unsupported-abci-host') host='127.0.0.1' if host in ['0.0.0.0','::'] else host else: td_networks=(td['NetworkSettings']['Networks'] if td else self.read('operation.json')['recipes']['tenderdash']['NetworkingConfig']['EndpointsConfig']) common=set(drive['NetworkSettings']['Networks'])&set(td_networks) require(len(common)==1 and host in ['0.0.0.0','::'],'unsupported-abci-network') host=drive['NetworkSettings']['Networks'][next(iter(common))]['IPAddress'] require(bool(host),'missing-abci-address') deadline=time.monotonic()+150 while time.monotonic()=2,'confirmed-checkpoint-required') paths=[m['Source'] for m in core['Mounts'] if m['Destination'].endswith('/dash.conf')] require(len(paths)==1,'core-config-mount');path=Path(paths[0]);require(path.is_file() and not path.is_symlink() and path.stat().st_size<2*1024*1024,'core-config-file') allowed={'sporkaddr','llmqchainlocks','llmqinstantsend','llmqinstantsenddip0024','llmqplatform','llmqmnhf','minimumdifficultyblocks','highsubsidyblocks','highsubsidyfactor','powtargetspacing'} options=[];port=19999 if self.f['chainType']=='testnet' else 20001;section='';section_wanted='test' if self.f['chainType']=='testnet' else 'devnet' for line in path.read_text().splitlines(): line=line.strip() if not line or line.startswith(('#',';')):continue if line.startswith('['):section=line[1:-1];continue if section not in ['',section_wanted]:continue k,sep,v=line.partition('=');k=k.strip();v=v.strip() require(k not in ['includeconf','vbparams','dip3params','budgetparams'],'unsupported-chain-override') if k in allowed: require(self.f['chainType']=='devnet','unexpected-testnet-chain-override');options.append(k+'='+v) if k=='port':port=int(v) hostport=port if core['HostConfig']['NetworkMode']=='host' else self.port(core,port) j=dict(chainType=self.f['chainType'],coreNetwork=info['chain'],genesis=self.rpc(selected,'getblockhash',1 if self.f['chainType']=='devnet' else 0),checkpointHeight=height, checkpointHash=self.rpc(selected,'getblockhash',height),peers=[self.t['address']+':'+str(hostport)],options=options) return dict(instanceId=self.t['instanceId'],join=j) def execute(self): require(self.q['action'] in ['observe','join-profile','enroll','stage','apply','admit','mining_pause','mining_status','mining_renew','mining_resume'],'action-refused') self.identity() if self.engine is None:self.engine=Engine() if self.q['action']=='observe':return self.observe() if self.q['action']=='join-profile':return self.join_profile() self.root.mkdir(mode=0o700,parents=True,exist_ok=True) with open('/run/dashnet-managed.lock','a') as lock: try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) except BlockingIOError:raise Failure('host-busy') from None return getattr(self,self.q['action'])() def main(): try: raw=sys.stdin.buffer.read(2*1024*1024+1);require(len(raw)<=2*1024*1024,'input-size') print(json.dumps(Worker(json.loads(raw)).execute(),separators=(',',':'))) except Exception as e: code=str(e) if isinstance(e,Failure) else type(e).__name__.lower() code=re.sub('[^a-z0-9:_-]','',code)[:100] print(json.dumps(dict(error=code)));sys.exit(1) if __name__=='__main__':main()