"""Proof that a saved forecast was saved when we say: OpenTimestamps (opentimestamps.org), anchored in Bitcoin. Each snapshot's file (the exact bytes kept in snap/) is hashed, and the hash is sent to OpenTimestamps' public calendar servers, which put it, with many others, into a Bitcoin transaction within a few hours. Its proof (.ots) shows the file existed no later than that Bitcoin block: nobody, we included, can change or backdate a saved forecast without the proof failing. Anyone can check one with the file and its proof at opentimestamps.org. All proofs are kept in one file, proofs.json: {"snapshots": {name: {"sha256": hex, "ots": base64, "block": height or null}}}. A proof is "pending" (the calendars' promise) until its Bitcoin block exists; upgrade() fetches that from the calendars and fills in "block". """ import base64 import hashlib import os from concurrent.futures import ThreadPoolExecutor from opentimestamps.calendar import RemoteCalendar from opentimestamps.core.notary import BitcoinBlockHeaderAttestation, PendingAttestation from opentimestamps.core.op import OpAppend, OpSHA256 from opentimestamps.core.serialize import BytesDeserializationContext, BytesSerializationContext from opentimestamps.core.timestamp import DetachedTimestampFile, Timestamp CALENDARS = ['https://a.pool.opentimestamps.org', 'https://b.pool.opentimestamps.org', 'https://a.pool.eternitywall.com', 'https://ots.btc.catallaxy.com'] AGENT = 'skavl-weather/1 skavl.app' def _write(proof): ctx = BytesSerializationContext() proof.serialize(ctx) return base64.b64encode(ctx.getbytes()).decode() def _read(text): return DetachedTimestampFile.deserialize(BytesDeserializationContext(base64.b64decode(text))) def _block(timestamp): """The earliest Bitcoin block the proof reaches, or None while it is pending.""" heights = [a.height for _, a in timestamp.all_attestations() if isinstance(a, BitcoinBlockHeaderAttestation)] return min(heights) if heights else None def stamp(body): """A new proof for the file `body`: {"sha256", "ots", "block": None}, or None if no calendar answered.""" digest = hashlib.sha256(body).digest() proof = DetachedTimestampFile(OpSHA256(), Timestamp(digest)) # (A random nonce first, as the ots client does: the calendars never see the file's own hash.) tip = proof.timestamp.ops.add(OpAppend(os.urandom(16))).ops.add(OpSHA256()) def submit(url): try: return RemoteCalendar(url, user_agent=AGENT).submit(tip.msg, timeout=15) except Exception as e: # (A calendar down: the others suffice.) print('OpenTimestamps:', url, 'did not answer:', e, flush=True) return None with ThreadPoolExecutor(len(CALENDARS)) as pool: got = [t for t in pool.map(submit, CALENDARS) if t] if not got: return None for t in got: tip.merge(t) return {'sha256': digest.hex(), 'ots': _write(proof), 'block': None} def upgrade(entry): """Fills in a pending proof's Bitcoin block from its calendars, where they have it. True if it changed.""" if entry.get('block') is not None: return False proof = _read(entry['ots']) def pending(stamp): if stamp.attestations: yield stamp for sub in stamp.ops.values(): yield from pending(sub) changed = False for sub in list(pending(proof.timestamp)): for a in list(sub.attestations): if isinstance(a, PendingAttestation): try: sub.merge(RemoteCalendar(a.uri, user_agent=AGENT).get_timestamp(sub.msg, timeout=15)) changed = True except Exception: # (Not in Bitcoin yet, or the calendar is down: next time.) pass block = _block(proof.timestamp) if changed and block is not None: entry['ots'], entry['block'] = _write(proof), block return True return False