"""SegWit PQSB: the P2WSH lock with pins, at the levels of LEVELS. docs/pins.md has the idea and what was tested. A forger who saw a spend may place its openings at the positions in any order. A pin takes most of that away. A pinned position takes its commitment out of the pool as every position does. The script then uses the same index once more: the commitment that is now `j` places below it (j = 0 at the first pinned position, 1 at the second, ..) is taken out too, and has to be opened by its tag, SHA256 of its opening, tested with OP_RIPEMD160. A commitment is HASH160 of its opening, RIPEMD160 of SHA256. The opening behind a tag stays secret, so a tag is no opening for a gate. A forger that moves another opening to a pinned position needs the tag of that opening's neighbour. It has the tags of one spend only, and every opening it has is needed at a gate. The pinned positions are the first k. Everything else is p2wsh.py: the same gates, digests, search and solver jobs. p2wsh.py's own layouts, with no pins, were the first SegWit PQSB and are no longer built.""" import functools import hashlib import math import random from . import ecc, p2wsh, predicate as pr from .script import (push, num, encode_num, count_ops, separators_after, OP_ROLL, OP_PICK, OP_HASH160, OP_EQUALVERIFY, OP_2DROP, OP_DROP, OP_ADD, OP_RIPEMD160, OP_OVER, OP_SIZE, OP_CHECKSIGVERIFY, OP_CODESEPARATOR, OP_CHECKSIG, OP_1) # level: (lengths of T by position, commitments, pinned positions), a few of the layouts of a search over 7 to 10 # positions, 1 to 6 pins and up to 127 commitments (docs/pins.md). 64 to 88: 9 positions, 79 commitments, 4 pins, # position 0 a byte shorter for each 8 bits. 87 and 95: 8 positions, 88 commitments, 6 pins, a bit below 88 and 96 # for a quarter of the tries; at 95 position 1 is shorter too. LEVELS = { 64: ((58,) + (59,) * 8, 79, 4), 72: ((57,) + (59,) * 8, 79, 4), 80: ((56,) + (59,) * 8, 79, 4), 87: ((55,) + (59,) * 7, 88, 6), 88: ((55,) + (59,) * 8, 79, 4), 95: ((55, 58) + (59,) * 6, 88, 6), } # (commitments, positions, pins): the part of the signer's solutions that leave (h - k)! arrangements, sample(n, h, k) # over 20,000 solutions KEPT = {(79, 9, 4): 0.952, (88, 8, 6): 0.947} def script_of(coms, pub, limits, k, gates=True): """The script. gates=False: the picks and pins alone, on a witness of one opening (and one tag) a position, then OP_1; for tests of the picks. The witness under the pool, bottom first: the ordinary signature, then for each position, the last first: [tag] T A opening B index. A pinned position copies its index for the pick and takes it for the pin.""" n, h = len(coms), len(limits) below = [] for i in reversed(range(h)): below += [('tag', i)] if i < k else [] below += ([('T', i), ('A', i)] if gates else []) + [('H', i)] + ([('B', i)] if gates else []) + [('idx', i)] pool, top = n, 0 # commitments left; items above the pool depth = lambda label: top + pool + len(below) - 1 - below.index(label) s = bytearray() for j in range(n, 0, -1): s += push(coms[j - 1]) # C_n first, C_1 on top for i in range(h): if i < k: s += num(depth(('idx', i))) + bytes([OP_PICK]) else: s += num(depth(('idx', i))) + bytes([OP_ROLL]); below.remove(('idx', i)) s += bytes([OP_ROLL]); pool -= 1; top = 1 # the commitment of the position s += num(depth(('H', i))) + bytes([OP_PICK, OP_HASH160, OP_EQUALVERIFY]); top = 0 if i < k: s += num(depth(('idx', i))) + bytes([OP_ROLL]); below.remove(('idx', i)) if i: s += num(i) + bytes([OP_ADD]) s += bytes([OP_ROLL]); pool -= 1; top = 1 # the commitment of the pin s += num(depth(('tag', i))) + bytes([OP_ROLL, OP_RIPEMD160, OP_EQUALVERIFY]); below.remove(('tag', i)); top = 0 s += bytes([OP_2DROP]) * (pool // 2) + bytes([OP_DROP]) * (pool % 2) if not gates: return bytes(s + bytes([OP_2DROP]) * (h // 2) + bytes([OP_DROP]) * (h % 2) + bytes([OP_1])) for i in range(h): s += bytes([OP_OVER]) + num(3) + bytes([OP_PICK, OP_CHECKSIGVERIFY]) s += num(3) + bytes([OP_PICK, OP_SIZE]) + num(limits[i]) + bytes([OP_EQUALVERIFY, OP_OVER, OP_CHECKSIGVERIFY]) s += bytes([OP_CODESEPARATOR, OP_CHECKSIGVERIFY, OP_CHECKSIGVERIFY]) return bytes(s + push(pub) + bytes([OP_CHECKSIG])) def picks(n, k, entries): """(index of each position, the pins' entries) as the script takes them for `entries`, the pool places by position (place 0 is C_1, nearest the top). None where a pin finds nothing below, or would take a later position's entry.""" pool, idx, tags = list(range(n)), [], [] for i, e in enumerate(entries): if e not in pool: return None d = pool.index(e); pool.pop(d); idx.append(d) if i < k: if d + i >= len(pool) or pool[d + i] in entries[i + 1:]: return None tags.append(pool.pop(d + i)) return idx, tags def accepts(n, k, order, shown, tag_of): """The model of the picks: True if the script takes `order` (pool places by position) with the tags `shown` at the pinned positions. tag_of[place] is the tag of that entry. tests/pins.py holds this against the script.""" pool = list(range(n)) for i, e in enumerate(order): if e not in pool: return False d = pool.index(e); pool.pop(d) if i < k: if d + i >= len(pool) or tag_of[pool[d + i]] != shown[i]: return False pool.pop(d + i) return True def arrangements(n, h, k, gates, tags): """How many orders of the h openings of a spend the script accepts when only that spend's k tags can be shown. Exact. Every opening is needed at a gate, so no opening's own tag is free for a pin.""" gates, tags = frozenset(gates), frozenset(tags) @functools.lru_cache(None) def go(used, shown): i = len(used) if i == k: return math.factorial(h - k) gone = used | shown; total = 0 for g in gates - used: at, skip = g + 1, i # the entry i places below g among those left while at < n and (at in gone or skip): if at not in gone: skip -= 1 at += 1 if at < n and at in tags - shown: total += go(used | {g}, shown | {at}) return total return go(frozenset(), frozenset()) class PinLock(p2wsh.Lock): """A lock of p2wsh.py whose first k positions are pinned. cutoff: the most arrangements a spend may leave a forger; the signer drops a solution that leaves more. The default is the fewest there can be, (h - k)!.""" def __init__(self, scalars, key, limits, k, cutoff=None): self.k = k self.cutoff = cutoff or math.factorial(len(limits) - k) super().__init__(scalars, key, limits) self.tags = [hashlib.sha256(o).digest() for o in self.openings] @classmethod def level(cls, bits, test=False): """A lock of LEVELS[bits]; test=True puts every position at 59 bytes, for tests only.""" limits, n, k = LEVELS[bits] return cls.generate((59,) * len(limits) if test else limits, n, k) @classmethod def generate(cls, limits, n, k, cutoff=None): base = p2wsh.Lock.generate(limits, n) return cls(base.s, base.key, limits, k, cutoff) def build(self): self.script = script_of(self.coms, self.pub, self.D, self.k) self.codes = [0] + separators_after(self.script) assert len(self.codes) == self.h + 1 # ---- the signer def assign(self, cand): """One entry a position from cand[i] = [(entry, e)], all distinct, with every pin met and no more than `cutoff` arrangements left to a forger. None if there is none.""" out = [] def go(i): if i == self.h: got = picks(self.n, self.k, [j for j, _ in out]) return bool(got) and arrangements(self.n, self.h, self.k, [j for j, _ in out], got[1]) <= self.cutoff for j, e in cand[i]: if all(j != x for x, _ in out): out.append((j, e)) if go(i + 1): return True out.pop() return False return list(out) if go(0) else None def try_tx(self, tx, amount): dig = {} def D(i): if i not in dig: dig[i] = tx.bip143_digest(0, self.script[self.codes[i]:], amount) return dig[i] cand = [None] * self.h for i in sorted(range(self.h), key=lambda i: self.D[i]): cand[i] = self.matches(D(i + 1), D(i), self.D[i]) if not cand[i]: return None return self.assign(cand) def witness(self, tx, amount, sol): """The witness of a spend. Refuses a solution whose pins cannot be met, and one that leaves a forger more arrangements than `cutoff`: the bound of a level holds for a spend within the cutoff only.""" dig = self.digests(tx, amount) got = picks(self.n, self.k, [j for j, _ in sol]) if not got: raise ValueError('the pins of this solution cannot be met') idx, tags = got self.left = arrangements(self.n, self.h, self.k, [j for j, _ in sol], tags) # what this spend leaves a forger if self.left > self.cutoff: raise ValueError(f'this solution leaves a forger {self.left} arrangements, more than the cutoff of {self.cutoff}') groups = [] for i, (j, e) in enumerate(sol): T, A, B = pr.items(dig[i + 1], dig[i], self.s[j], e) groups.append(([self.tags[tags[i]]] if i < self.k else []) + [T, A, self.openings[j], B, encode_num(idx[i])]) last = ecc.der(*ecc.sign(self.key, dig[-1])) return [last] + [x for g in reversed(groups) for x in g] + [self.script] def spend_vsize(self, out_script): """The most virtual bytes a spend paying one output with out_script can take: every witness item at its longest. T has its position's length, and only the last signature (71 to 73 bytes) and a position's number (0 or 1 byte) can be shorter, so a spend is at most 1 vB under this. 1,060 or 1,061 with 9 positions and a P2WPKH output; 12 more for a P2WSH or Taproot output.""" items = [73] for i in range(self.h): items += ([len(self.tags[0])] if i < self.k else []) + [self.D[i], 33, len(self.openings[0]), 33, 1] items.append(len(self.script)) size = lambda n: 1 if n < 253 else 3 # a length's own bytes witness = 2 + size(len(items)) + sum(size(n) + n for n in items) # the marker and flag, the count, the items base = 4 + 1 + 41 + 1 + 8 + size(len(out_script)) + len(out_script) + 4 return -(-(4 * base + witness) // 4) # ---- figures def owner_tries(self, kept=None): """Expected transactions: each position chooses among the commitments left, less those a pin below it needs. kept: the part of the solutions that pass the cutoff (sample); by default that of this layout in KEPT.""" if kept is None: key = (self.n, self.h, self.k) if key not in KEPT: # another layout: sample it once hist = sample(*key, 4000) KEPT[key] = sum(v for a, v in hist.items() if a <= self.cutoff) / sum(hist.values()) kept = KEPT[key] ways, m = 1.0, self.n for i, D in enumerate(self.D): ways *= (m - (i + 1 if i < self.k else 0)) * pr.p_exact(D) m -= 2 if i < self.k else 1 return 1 / (ways * kept) def forgery_bound(self, arrangements_=None): """The bound on one try with the openings and tags of one spend that leaves `arrangements_` (the cutoff if not given): the first term of p2wsh.Lock.forgery_bound with the arrangements in the place of h!, and its second term unchanged (docs/pins.md).""" A = arrangements_ or self.cutoff p = [pr.p_upto(D) for D in self.D] second = sum(pr.ff(self.h, l) * math.prod(p[:l - 1]) * pr.delta(self.D[l - 1]) for l in range(1, self.h + 1)) return A * math.prod(p) + second def sample(n, h, k, runs, seed=1): """Random solutions of the signer: {arrangements: how many}, over those whose pins can be met.""" rng = random.Random(seed); hist = {} done = 0 while done < runs: got = picks(n, k, entries := rng.sample(range(n), h)) if not got: continue a = arrangements(n, h, k, entries, got[1]); hist[a] = hist.get(a, 0) + 1; done += 1 return dict(sorted(hist.items())) def to_json(lock, network): return dict(lock='p2wsh-pins', network=network, limits=list(lock.D), pins=lock.k, scalars=['%064x' % x for x in lock.s], key='%064x' % lock.key, script=lock.script.hex(), spent_by=None) def from_json(d): """The lock of a file that `to_json` wrote, checked by its script. A file of p2wsh.py's lock with no pins (the first SegWit PQSB) loads as that lock, so that a lock already funded can still be spent; none is made any more.""" if 'pins' not in d: return p2wsh.from_json(d) lock = PinLock([int(x, 16) for x in d['scalars']], int(d['key'], 16), tuple(d['limits']), d['pins']) if lock.script.hex() != d['script']: raise ValueError('the secrets do not give the script of this file') return lock