Shader
Verify a rental's ticks

DocsGuides19 of 35 · 3 min read

Verify a rental's ticks

Check every signed second of a rental, each minute's digest and its seal yourself, with a short script that uses nothing from Shader.

A metered rental is charged for the seconds its meter signed (Signed seconds), and its ticks are public by rental id. You need Node 26 and the rental's id; no account, token or package.

#Check a rental

  1. Get the script

    verify-ticks.mjs imports only Node's standard library, node:crypto and node:url. It rebuilds each tick message, minute digest and seal from the encodings and the seal, so it doubles as their reference.

    verify-ticks.mjs
    #!/usr/bin/env node
    import { createHash, createPublicKey, verify } from 'node:crypto'
    import { pathToFileURL } from 'node:url'
    
    const TICK_VERSION = 'shader-meter-tick/v1'
    const MINUTE_VERSION = 'shader-meter-minute/v1'
    const SEAL_VERSION = 'shader-meter-seal/v1'
    const TICK_DOMAIN = Buffer.from(`${TICK_VERSION}\0`, 'utf8')
    const MINUTE_DOMAIN = Buffer.from(`${MINUTE_VERSION}\0`, 'utf8')
    const SEAL_DOMAIN = Buffer.from(`${SEAL_VERSION}\0`, 'utf8')
    const SIGNATURE_BYTES = 64
    const SECONDS_PER_MINUTE = 60
    const MAX_MINUTE = 0xffff_ffff
    const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
    const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')
    
    function u32le(value) {
      const bytes = Buffer.alloc(4)
      bytes.writeUInt32LE(value)
      return bytes
    }
    
    function u64le(value) {
      const bytes = Buffer.alloc(8)
      bytes.writeBigUInt64LE(BigInt(value))
      return bytes
    }
    
    function text(value) {
      const bytes = Buffer.from(value, 'utf8')
      return Buffer.concat([u32le(bytes.length), bytes])
    }
    
    function base58PublicKey(value) {
      if (typeof value !== 'string' || value.length < 32 || value.length > 44) throw new Error('Invalid base58 meter key.')
      let number = 0n
      for (const character of value) {
        const digit = BASE58.indexOf(character)
        if (digit === -1) throw new Error('Invalid base58 meter key.')
        number = number * 58n + BigInt(digit)
      }
      const hex = number.toString(16)
      const leadingZeros = value.match(/^1*/)[0].length
      const nonzeroBytes = number === 0n ? Buffer.alloc(0) : Buffer.from(hex.length % 2 ? `0${hex}` : hex, 'hex')
      const bytes = Buffer.concat([Buffer.alloc(leadingZeros), nonzeroBytes])
      if (bytes.length !== 32) throw new Error('The meter key must encode 32 bytes.')
      return createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, bytes]), type: 'spki', format: 'der' })
    }
    
    function signatureBytes(value) {
      if (typeof value !== 'string' || !/^[A-Za-z0-9+/]{85}[AQgw]==$/.test(value)) throw new Error('Invalid base64 Ed25519 signature.')
      const bytes = Buffer.from(value, 'base64')
      if (bytes.length !== SIGNATURE_BYTES) throw new Error('An Ed25519 signature must encode 64 bytes.')
      return bytes
    }
    
    function tickMessage(jobId, second, gpuUuid) {
      return Buffer.concat([TICK_DOMAIN, text(jobId), u64le(second), text(gpuUuid)])
    }
    
    export function minuteDigestInput(jobId, gpuUuid, minute, ticks) {
      return Buffer.concat([
        MINUTE_DOMAIN, text(jobId), text(gpuUuid), u32le(minute), u32le(ticks.length),
        ...ticks.map(({ second, signature }) => Buffer.concat([u64le(second), signatureBytes(signature)])),
      ])
    }
    
    export function meterSealInput(jobId, gpuUuid, { minute, count, digest }) {
      if (typeof jobId !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(jobId)) {
        throw new Error('A sealed rental needs a UUID job ID.')
      }
      if (typeof digest !== 'string' || !/^[0-9a-f]{64}$/.test(digest)) throw new Error('Invalid seal digest.')
      return Buffer.concat([
        SEAL_DOMAIN,
        Buffer.from(jobId.replaceAll('-', ''), 'hex'),
        createHash('sha256').update(gpuUuid, 'utf8').digest(),
        u32le(minute), u32le(count), Buffer.from(digest, 'hex'),
      ])
    }
    
    function isIndex(value, maximum = Number.MAX_SAFE_INTEGER) {
      return Number.isSafeInteger(value) && value >= 0 && value <= maximum
    }
    
    export function verifyMeterMinute({ jobId, meterKey, gpuUuid, sealVersion }, minute) {
      const { minute: index, firstSecond, ticks, count, digest, open, seal } = minute
      if (
        !isIndex(index, MAX_MINUTE) || firstSecond !== index * SECONDS_PER_MINUTE ||
        !Array.isArray(ticks) || ticks.length > SECONDS_PER_MINUTE || count !== ticks.length || typeof open !== 'boolean'
      ) throw new Error('Invalid minute metadata.')
      const key = base58PublicKey(meterKey)
      let lastSecond = firstSecond - 1
      for (const { second, signature } of ticks) {
        if (!isIndex(second) || second <= lastSecond || second >= firstSecond + SECONDS_PER_MINUTE) {
          throw new Error(`Out-of-order tick or tick outside minute ${index}.`)
        }
        if (!verify(null, tickMessage(jobId, second, gpuUuid), key, signatureBytes(signature))) {
          throw new Error(`Invalid signature for tick ${second} in minute ${index}.`)
        }
        lastSecond = second
      }
      if (open) {
        if (digest !== null) throw new Error(`Open minute ${index} must have a null digest.`)
        if (seal != null) throw new Error(`Open minute ${index} has a seal.`)
        return false
      }
      const expected = createHash('sha256').update(minuteDigestInput(jobId, gpuUuid, index, ticks)).digest('hex')
      if (digest !== expected) throw new Error(`Digest mismatch for minute ${index}.`)
      if (seal == null) return false
      if (sealVersion !== undefined && sealVersion !== SEAL_VERSION) throw new Error('Unsupported minute seal encoding.')
      if (seal.minute !== index || seal.count !== count || seal.digest !== expected) throw new Error(`Seal disagrees with evidence for minute ${index}.`)
      if (!verify(null, meterSealInput(jobId, gpuUuid, seal), key, signatureBytes(seal.signature))) {
        throw new Error(`Invalid seal signature for minute ${index}.`)
      }
      return true
    }
    
    async function main(apiBase, instanceId) {
      if (!apiBase || !instanceId) throw new Error('Usage: node verify-ticks.mjs <api-base> <instance-id>')
      const base = new URL(apiBase)
      if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password || base.search || base.hash) {
        throw new Error('Pass an HTTP(S) API base without credentials, a query or a fragment.')
      }
      const url = new URL(`instances/${encodeURIComponent(instanceId)}/ticks`, `${base.href.replace(/\/+$/, '')}/`)
      let from = 0
      let previousMinute = -1
      let registeredMeter
      let verifiedTicks = 0
      let verifiedDigests = 0
      let verifiedSeals = 0
      let openMinutes = 0
      for (;;) {
        url.searchParams.set('from', String(from))
        const response = await fetch(url, { redirect: 'error', signal: AbortSignal.timeout(15_000) })
        if (!response.ok) throw new Error(`The ticks endpoint returned HTTP ${response.status}.`)
        const page = await response.json()
        if (page.jobId !== instanceId || page.tickVersion !== TICK_VERSION || page.minuteVersion !== MINUTE_VERSION) {
          throw new Error('The response used a different job ID or an unsupported encoding version.')
        }
        if (!Array.isArray(page.minutes)) throw new Error('The response has no minutes array.')
        if (page.meterKey === null && page.gpuUuid === null) {
          if (registeredMeter || page.minutes.length || page.nextMinute !== null) throw new Error('Missing meter metadata.')
          break
        }
        if (typeof page.meterKey !== 'string' || typeof page.gpuUuid !== 'string' || !page.gpuUuid) {
          throw new Error('Missing meter metadata.')
        }
        const meter = [page.meterKey, page.gpuUuid]
        if (registeredMeter && registeredMeter.some((value, index) => value !== meter[index])) {
          throw new Error('Meter metadata changed between pages.')
        }
        registeredMeter = meter
        for (const minute of page.minutes) {
          if (!isIndex(minute.minute, MAX_MINUTE) || minute.minute < from || minute.minute <= previousMinute) {
            throw new Error('Meter minute pagination is out of order.')
          }
          const sealed = verifyMeterMinute(page, minute)
          previousMinute = minute.minute
          verifiedTicks += minute.count
          if (minute.open) openMinutes++
          else verifiedDigests++
          if (sealed) verifiedSeals++
          const state = minute.open ? 'open, digest pending' : `digest ${minute.digest} verified, ${sealed ? 'seal verified' : 'closed without a seal'}`
          console.log(`minute ${minute.minute}: ${minute.count} ticks, ${state}`)
        }
        if (page.nextMinute === null) break
        if (!isIndex(page.nextMinute, MAX_MINUTE) || page.nextMinute <= from || page.nextMinute <= previousMinute) {
          throw new Error('Invalid next meter minute.')
        }
        from = page.nextMinute
      }
      if (!verifiedTicks && !verifiedSeals) console.log('NO EVIDENCE: no signed ticks or seals were published.')
      else console.log(`PASS: ${verifiedTicks} tick signatures, ${verifiedDigests} closed digests, ${verifiedSeals} seals, ${verifiedDigests - verifiedSeals} closed minutes without seals, ${openMinutes} open minutes.`)
    }
    
    if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
      try {
        await main(process.argv[2], process.argv[3])
      } catch (error) {
        console.error(`FAIL: ${error.message}`)
        process.exitCode = 1
      }
    }
  2. Run it

    Pass the API base and the rental's id:

    Terminal
    node verify-ticks.mjs <api url> <instance id>
  3. Read the result

    Run against a local Shader rental while it ran, then after it stopped:

    While it ran
    minute 0: 60 ticks, digest f49e83ac58671633db3aaeb5882435d0e60fa9bb584cfb359313060eae6846b9 verified, seal verified
    minute 1: 10 ticks, open, digest pending
    PASS: 70 tick signatures, 1 closed digests, 1 seals, 0 closed minutes without seals, 1 open minutes.
    After the stop
    minute 0: 60 ticks, digest f49e83ac58671633db3aaeb5882435d0e60fa9bb584cfb359313060eae6846b9 verified, seal verified
    minute 1: 23 ticks, digest 342d71d6d6bcf4d44eddd8bf408299604c191965f88b286c4d19f039ba4beffc verified, seal verified
    PASS: 83 tick signatures, 2 closed digests, 2 seals, 0 closed minutes without seals, 0 open minutes.

    PASS means every published tick verified against the meter key, every closed minute's digest matched, and every seal matched its minute and verified. A minute still being written shows as open; once the rental stops, the agent seals its last minute too.

    Every accepted tick is published, so all 83 verify, but not every tick is billed (Signed seconds). Two of them signed seconds outside the running window, before the machine was running or after it stopped, so they were free, which left 81 billable. The rental ran 80 whole seconds of wall time, so the charge was capped at 80, at 170 base units a second, 13,600.

#What happened

  1. Read the minutes

    The script read GET /instances/{id}/ticks page by page, with the rental's meter key and GPU UUID.

  2. Check each tick

    For every tick it rebuilt the tick message from the rental id, the second and the GPU UUID, and checked the Ed25519 signature against the meter key. Seconds must rise within their minute.

  3. Check each digest

    For every closed minute it rebuilt the digest from the minute's ticks and compared it with the published one. An open minute has no digest yet.

  4. Check each seal

    For every sealed minute it checked that the seal names the same minute, count and digest, rebuilt the seal message, and checked its signature against the meter key. That seal is what the rental's settlement put on chain.

#Afterwards

The meter key the script used is the one cat /etc/shader/meter.pub prints inside the machine, and the one the instance shows as meterKey. The rental's receipts in Receipts show the seconds billed from those ticks.

#If it fails

What you seeWhyNext
NO EVIDENCE: no signed ticks or seals were published.The rental is unmetered, or its agent had not registered yetAn unmetered rental's receipts say unmetered: true
FAIL: Invalid signature for tick …A tick does not verify against the meter keyThe published tick was not signed by the rental's meter
FAIL: Digest mismatch for minute …A minute's ticks do not hash to its digestThe published minute was changed after it closed
FAIL: Seal disagrees with evidence for minute …The seal names another count or digest than the ticks showThe seal does not belong to these ticks
FAIL: Invalid seal signature for minute …The seal does not verify against the meter keyIt was not signed by the rental's meter
FAIL: The ticks endpoint returned HTTP 404.No rental with that idCheck the id