Back to Proof of Work is dead
SOURCE / PINNED RELEASE

Made of little things.

Proof of Work is dead

Release
89cac09188df…
Author-recorded commit
8ef34170172d…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-abb751b60a6

Archive hash verified: 2e3eb06f34235090…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/ring.ts
// Ring signatures over nostr keys, plus the NIP-13 miner the page compares them
// with. No DOM in here, so the tests can drive it from Node.
//
// Scheme: SAG / AOS ring signature (Abe, Ohkubo, Suzuki 2002) on secp256k1.
// Nostr public keys are x-only, so every ring key is lifted to its even-y point
// and a signer whose point has odd y negates their secret first.
//
// DEMO CODE. Unaudited. Do not protect anything real with it.

import { schnorr, secp256k1 } from '@noble/curves/secp256k1.js';
import { sha256 } from '@noble/hashes/sha2.js';
import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from '@noble/hashes/utils.js';

const Point = secp256k1.Point;
const G = Point.BASE;
const N = Point.Fn.ORDER;

export type RingPoint = InstanceType<typeof Point>;

export interface Key {
  sk: Uint8Array;
  /** 32-byte x-only public key, as nostr uses it. */
  pk: Uint8Array;
}

/** c0 plus one response per ring key: 32 * (n + 1) bytes. */
export interface RingSignature {
  c0: Uint8Array;
  r: Uint8Array[];
}

export interface Ring {
  keys: Uint8Array[];
  points: RingPoint[];
  /** Commits every challenge to the exact ring, in order. */
  digest: Uint8Array;
}

function toScalar(bytes: Uint8Array): bigint {
  return BigInt('0x' + bytesToHex(bytes));
}

function scalarBytes(value: bigint): Uint8Array {
  return hexToBytes(value.toString(16).padStart(64, '0'));
}

function mod(value: bigint): bigint {
  const result = value % N;
  return result >= 0n ? result : result + N;
}

function randomScalar(): bigint {
  // A valid secret key is a uniform scalar in [1, N).
  return toScalar(secp256k1.utils.randomSecretKey());
}

export function newKey(): Key {
  const { secretKey, publicKey } = schnorr.keygen();
  return { sk: secretKey, pk: publicKey };
}

/**
 * Throws on a key that is not 32 bytes or not the x of a curve point. Signer
 * and verifier must agree on the list, so a list with a junk key is no ring
 * for either of them; a client would filter such keys by one published rule.
 */
export function makeRing(keys: Uint8Array[]): Ring {
  if (keys.length < 2) throw new Error('A ring needs at least two keys.');
  if (keys.some((key) => key.length !== 32)) throw new Error('Ring keys are 32-byte x-only public keys.');
  return {
    keys,
    points: keys.map((key) => schnorr.utils.lift_x(toScalar(key))),
    digest: schnorr.utils.taggedHash('nostr-ring/ring', ...keys),
  };
}

/** What the ring signature signs: a throwaway key, bound to one list. */
export function credentialMessage(throwawayPk: Uint8Array, scope: string): Uint8Array {
  return schnorr.utils.taggedHash('nostr-ring/credential', throwawayPk, utf8ToBytes(scope));
}

function challenge(ring: Ring, message: Uint8Array, link: RingPoint): bigint {
  return mod(toScalar(schnorr.utils.taggedHash('nostr-ring/challenge', ring.digest, message, link.toBytes(true))));
}

function link(ring: Ring, index: number, response: bigint, c: bigint): RingPoint {
  // response and c are public here, so the faster variable-time multiply is fine.
  return G.multiplyUnsafe(response).add(ring.points[index].multiplyUnsafe(c));
}

/** The signer's secret, negated when their point has odd y. */
function evenSecret(sk: Uint8Array): bigint {
  const d = toScalar(sk);
  return G.multiply(d).toAffine().y % 2n === 0n ? d : N - d;
}

/**
 * Sign as ring member `index`. A generator, so a page can spread the work over
 * frames: it yields once per ring key and returns the signature.
 *
 * `unchecked` skips the "is this really your key" test. The tests use it to
 * show what an outsider's attempt produces: a signature that does not verify.
 */
export function* signSteps(
  ring: Ring,
  message: Uint8Array,
  index: number,
  sk: Uint8Array,
  unchecked = false,
): Generator<number, RingSignature> {
  const n = ring.points.length;
  if (index < 0 || index >= n) throw new Error('Signer index outside the ring.');
  const d = evenSecret(sk);
  if (!unchecked && !G.multiply(d).equals(ring.points[index])) {
    throw new Error('This key is not at that place in the ring.');
  }

  const c = new Array<bigint>(n);
  const r = new Array<bigint>(n);
  const k = randomScalar();
  c[(index + 1) % n] = challenge(ring, message, G.multiply(k));
  yield 1;
  for (let step = 1; step < n; step++) {
    const i = (index + step) % n;
    r[i] = randomScalar();
    c[(i + 1) % n] = challenge(ring, message, link(ring, i, r[i], c[i]));
    yield step + 1;
  }
  // Only the real secret closes the loop: r·G + c·P must equal k·G.
  r[index] = mod(k - c[index] * d);
  if (r[index] === 0n || c[0] === 0n) throw new Error('Unlucky nonce, sign again.');
  return { c0: scalarBytes(c[0]), r: r.map(scalarBytes) };
}

export function sign(ring: Ring, message: Uint8Array, index: number, sk: Uint8Array): RingSignature {
  const steps = signSteps(ring, message, index, sk);
  for (;;) {
    const next = steps.next();
    if (next.done) return next.value;
  }
}

/**
 * Walk the ring once. Yields the number of links checked so far and returns
 * whether the last challenge lands back on the first one.
 */
export function* verifySteps(ring: Ring, message: Uint8Array, signature: RingSignature): Generator<number, boolean> {
  const n = ring.points.length;
  if (signature.r.length !== n || signature.c0.length !== 32) return false;
  const c0 = toScalar(signature.c0);
  if (c0 === 0n || c0 >= N) return false;
  let c = c0;
  for (let i = 0; i < n; i++) {
    if (signature.r[i].length !== 32) return false;
    const response = toScalar(signature.r[i]);
    if (response === 0n || response >= N) return false;
    // A member can pick a response that sends this link to the point at
    // infinity. That is a malformed signature, not a reason to throw.
    const point = link(ring, i, response, c);
    if (point.is0()) return false;
    c = challenge(ring, message, point);
    if (c === 0n) return false;
    yield i + 1;
  }
  return c === c0;
}

export function verify(ring: Ring, message: Uint8Array, signature: RingSignature): boolean {
  const steps = verifySteps(ring, message, signature);
  for (;;) {
    const next = steps.next();
    if (next.done) return next.value;
  }
}

export function signatureBytes(signature: RingSignature): number {
  return signature.c0.length + signature.r.reduce((sum, part) => sum + part.length, 0);
}

// ---------------------------------------------------------------- nostr events

export interface EventTemplate {
  pubkey: string;
  created_at: number;
  kind: number;
  tags: string[][];
  content: string;
}

export interface SignedEvent extends EventTemplate {
  id: string;
  sig: string;
}

export function serializeEvent(event: EventTemplate): Uint8Array {
  return utf8ToBytes(JSON.stringify([0, event.pubkey, event.created_at, event.kind, event.tags, event.content]));
}

export function signEvent(event: EventTemplate, sk: Uint8Array): SignedEvent {
  const id = sha256(serializeEvent(event));
  return { ...event, id: bytesToHex(id), sig: bytesToHex(schnorr.sign(id, sk)) };
}

export function verifyEvent(event: SignedEvent): boolean {
  const id = sha256(serializeEvent(event));
  if (bytesToHex(id) !== event.id) return false;
  try {
    return schnorr.verify(hexToBytes(event.sig), id, hexToBytes(event.pubkey));
  } catch {
    return false;
  }
}

// ------------------------------------------------------------- NIP-13 mining

export function leadingZeroBits(hash: Uint8Array): number {
  let bits = 0;
  for (const byte of hash) {
    if (byte === 0) {
      bits += 8;
      continue;
    }
    return bits + Math.clz32(byte) - 24;
  }
  return bits;
}

const NONCE_DIGITS = 10;

/** Grinds the nonce tag of one real kind-1 event until its id has enough zero bits. */
export class Miner {
  readonly target: number;
  /** SHA-256 blocks per event id, for a fair comparison with raw hash rates. */
  readonly blocks: number;
  hashes = 0;
  best = 0;
  bestId = '';
  found = false;
  /** Milliseconds spent hashing, not counting the pauses between slices. */
  busyMs = 0;
  private readonly buffer: Uint8Array;
  private readonly nonceEnd: number;
  private readonly template: EventTemplate;

  constructor(pubkey: string, createdAt: number, target: number) {
    this.target = target;
    this.template = {
      pubkey,
      created_at: createdAt,
      kind: 1,
      tags: [['nonce', '0'.repeat(NONCE_DIGITS), String(target)]],
      content: 'gm',
    };
    this.buffer = serializeEvent(this.template);
    const marker = `["nonce","${'0'.repeat(NONCE_DIGITS)}"`;
    const text = new TextDecoder().decode(this.buffer);
    this.nonceEnd = text.indexOf(marker) + marker.length - 2;
    // Message bytes, the 0x80 marker and the 8-byte length, in 64-byte blocks.
    this.blocks = Math.ceil((this.buffer.length + 9) / 64);
  }

  /** The mined event template with the nonce that gave the best id so far. */
  event(): EventTemplate {
    return this.template;
  }

  private bump(): void {
    const buffer = this.buffer;
    for (let at = this.nonceEnd; at > this.nonceEnd - NONCE_DIGITS; at--) {
      if (buffer[at] === 57) {
        buffer[at] = 48;
      } else {
        buffer[at]++;
        return;
      }
    }
  }

  /** Hash until `now()` passes `deadline` or the target is met. */
  step(deadline: number, now: () => number): boolean {
    const started = now();
    while (!this.found) {
      for (let batch = 0; batch < 128; batch++) {
        this.bump();
        const id = sha256(this.buffer);
        this.hashes++;
        // Cheap reject first: most ids do not even start with a zero byte.
        if (id[0] !== 0 && this.best >= 8) continue;
        const bits = leadingZeroBits(id);
        if (bits > this.best) {
          this.best = bits;
          this.bestId = bytesToHex(id);
          const text = new TextDecoder().decode(this.buffer);
          this.template.tags = JSON.parse(text)[4];
          if (bits >= this.target) {
            this.found = true;
            break;
          }
        }
      }
      if (now() >= deadline) break;
    }
    this.busyMs += now() - started;
    return this.found;
  }
}

export { bytesToHex, concatBytes, hexToBytes };