nightpay 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of nightpay might be problematic. Click here for more details.

@@ -1,1365 +0,0 @@
1
- #!/usr/bin/env bash
2
- # nightpay gateway — orchestrates the bounty lifecycle with fee mechanism
3
- #
4
- # SECURITY MODEL:
5
- # - RECEIPT_CONTRACT is required — no silent no-ops against empty address
6
- # - withdraw-fees requires OPERATOR_SECRET_KEY for signing (operator-only)
7
- # - All hashes are domain-separated to prevent cross-namespace collisions
8
- # - refund path cancels Masumi escrow AND emits a signed on-chain NIGHT refund intent
9
- # - Amount bounds enforced (min + max) before any network call
10
- # - commitment_hash format validated before any network call
11
- # - curl has --max-time 30 to prevent hung connections
12
- #
13
- # Usage: ./gateway.sh <command> [args...]
14
- #
15
- # Commands:
16
- # create-pool <job_description> <contribution_specks> <funding_goal_specks>
17
- # fund-pool <pool_commitment>
18
- # pool-status <pool_commitment>
19
- # activate-pool <pool_commitment>
20
- # expire-pool <pool_commitment>
21
- # claim-refund <pool_commitment> <funder_nullifier>
22
- # emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>
23
- # post-bounty <job_description> <amount_night_specks>
24
- # find-agent <capability_query>
25
- # agent-showcase [search_query]
26
- # hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]
27
- # hire-direct <agent_id> <job_description> <amount_specks>
28
- # check-job <job_id>
29
- # complete <job_id> <commitment_hash> [--approvals sig1:ts1:nonce1,...]
30
- # refund <job_id> <commitment_hash> [refund_address]
31
- # withdraw-fees [amount_specks] # operator-only: requires OPERATOR_SECRET_KEY
32
- # stats # public contract stats
33
- # approve-multisig <job_id> <output_hash> <approver_key> # per-approver signature
34
- # optimistic-sweep [--dry-run] # auto-complete expired optimistic windows
35
- # refund-unclaimed [--dry-run] # auto-refund old jobs with zero claims
36
-
37
- set -euo pipefail
38
-
39
- # ─── Terminal colors ───────────────────────────────────────────────────────────
40
- # Gracefully disabled when stderr is not a TTY (CI, logs, pipes)
41
- if [[ -t 2 ]]; then
42
- RED=$'\e[31m'; GREEN=$'\e[32m'; YELLOW=$'\e[33m'
43
- CYAN=$'\e[36m'; BOLD=$'\e[1m'; DIM=$'\e[2m'; RESET=$'\e[0m'
44
- else
45
- RED=''; GREEN=''; YELLOW=''; CYAN=''; BOLD=''; DIM=''; RESET=''
46
- fi
47
-
48
- # ─── Required env vars ────────────────────────────────────────────────────────
49
- MASUMI_PAYMENT_URL="${MASUMI_PAYMENT_URL:-http://localhost:3001/api/v1}"
50
- MASUMI_REGISTRY_URL="${MASUMI_REGISTRY_URL:-http://localhost:3000/api/v1}"
51
- MASUMI_API_KEY="${MASUMI_API_KEY:?SECURITY: Set MASUMI_API_KEY}"
52
- # Keep preprod default until Midnight mainnet is live.
53
- MIDNIGHT_NETWORK="${MIDNIGHT_NETWORK:-preprod}"
54
- OPERATOR_ADDRESS="${OPERATOR_ADDRESS:?SECURITY: Set OPERATOR_ADDRESS}"
55
- OPERATOR_FEE_BPS="${OPERATOR_FEE_BPS:-200}"
56
- MAX_BOUNTY_SPECKS="${MAX_BOUNTY_SPECKS:-500000000}"
57
- MIN_BOUNTY_SPECKS="${MIN_BOUNTY_SPECKS:-1000}" # SECURITY: reject dust bounties
58
-
59
- # Midnight bridge — if set, gateway calls the bridge for real on-chain transactions.
60
- # If not set, gateway runs in local/stub mode (computes hashes locally, no chain).
61
- BRIDGE_URL="${BRIDGE_URL:-}"
62
-
63
- # SECURITY: contract address is REQUIRED — fail loudly rather than silently
64
- # routing funds to a void address
65
- RECEIPT_CONTRACT="${RECEIPT_CONTRACT_ADDRESS:?SECURITY: Set RECEIPT_CONTRACT_ADDRESS — funds cannot be routed without it}"
66
-
67
- # ─── Rate limiting ────────────────────────────────────────────────────────────
68
- # SECURITY: prevent bounty spam that inflates activeCount and floods Masumi.
69
- # Uses a per-command lockfile with a minimum interval between invocations.
70
- # Default: max 1 post-bounty per 5 seconds. Override with RATE_LIMIT_SECONDS.
71
- RATE_LIMIT_DIR="${RATE_LIMIT_DIR:-${HOME}/.nightpay/ratelimit}"
72
- RATE_LIMIT_SECONDS="${RATE_LIMIT_SECONDS:-5}"
73
-
74
- COMMAND="${1:?Usage: gateway.sh <command> [args...]}"
75
- shift
76
-
77
- # ─── Helpers ──────────────────────────────────────────────────────────────────
78
-
79
- # SECURITY: SSRF guard — only allow http/https to non-RFC-1918, non-loopback hosts.
80
- # Blocks: 127.x, 10.x, 172.16-31.x, 192.168.x, 169.254.x (cloud metadata), ::1
81
- validate_url() {
82
- local url="$1"
83
- python3 -c "
84
- import sys, urllib.parse, ipaddress, socket
85
-
86
- url = sys.argv[1]
87
- parsed = urllib.parse.urlparse(url)
88
-
89
- if parsed.scheme not in ('http', 'https'):
90
- print('ERROR: URL must use http or https scheme'); sys.exit(1)
91
-
92
- host = parsed.hostname
93
- if not host:
94
- print('ERROR: URL has no hostname'); sys.exit(1)
95
-
96
- # Resolve and check for private/loopback addresses
97
- try:
98
- addrs = socket.getaddrinfo(host, None)
99
- for addr in addrs:
100
- ip = ipaddress.ip_address(addr[4][0])
101
- if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
102
- # Allow localhost explicitly for dev — controlled by ALLOW_LOCAL_URLS
103
- import os
104
- if os.environ.get('ALLOW_LOCAL_URLS') == '1':
105
- sys.exit(0)
106
- print(f'ERROR: SSRF blocked — {ip} is a private/internal address'); sys.exit(1)
107
- except socket.gaierror:
108
- print(f'ERROR: Cannot resolve host {host}'); sys.exit(1)
109
-
110
- print('ok')
111
- " "$url" || exit 1
112
- }
113
-
114
- # Validate URLs at startup — fail before any command runs
115
- # Skip SSRF check for localhost (dev mode) if ALLOW_LOCAL_URLS=1
116
- if [[ "${ALLOW_LOCAL_URLS:-0}" != "1" ]]; then
117
- _url_check=$(python3 -c "
118
- import sys, urllib.parse, ipaddress
119
- for url in sys.argv[1:]:
120
- parsed = urllib.parse.urlparse(url)
121
- if parsed.scheme not in ('http','https'):
122
- print(f'ERROR: {url} — must be http/https'); sys.exit(1)
123
- print('ok')
124
- " "$MASUMI_PAYMENT_URL" "$MASUMI_REGISTRY_URL" 2>&1) || {
125
- echo -e "${RED}SECURITY ERROR${RESET}: Invalid Masumi URL — $_url_check" >&2; exit 1
126
- }
127
- fi
128
-
129
- # DARK ENERGY: DNS rebinding guard — re-resolve the hostname on every request
130
- # and verify it is still a non-private IP. An attacker who controls the DNS
131
- # server can pass the startup check (public IP) then flip the A-record to
132
- # 169.254.169.254 (AWS metadata) for subsequent calls. We re-resolve per call.
133
- _ssrf_safe_curl() {
134
- local url="$1"; shift
135
- local resolve_arg
136
- resolve_arg=$(python3 -c "
137
- import sys, urllib.parse, ipaddress, socket, os
138
- url = sys.argv[1]
139
- parsed = urllib.parse.urlparse(url)
140
- host = parsed.hostname or ''
141
- port = parsed.port or (443 if parsed.scheme == 'https' else 80)
142
- try:
143
- if not host:
144
- sys.exit(0)
145
- addrs = socket.getaddrinfo(host, port)
146
- for addr in addrs:
147
- ip_str = addr[4][0]
148
- ip = ipaddress.ip_address(ip_str)
149
- if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
150
- if os.environ.get('ALLOW_LOCAL_URLS') == '1':
151
- print(f'{host}:{port}:{ip_str}')
152
- sys.exit(0)
153
- print(f'SSRF blocked: {ip}', file=sys.stderr); sys.exit(1)
154
- print(f'{host}:{port}:{ip_str}')
155
- sys.exit(0)
156
- except socket.gaierror as e:
157
- print(f'DNS error: {e}', file=sys.stderr); sys.exit(1)
158
- " "$url") || { echo -e "${RED}SECURITY ERROR${RESET}: SSRF guard blocked request to $url" >&2; exit 1; }
159
-
160
- if [[ -n "$resolve_arg" ]]; then
161
- curl -sf --max-time 30 --resolve "$resolve_arg" "$@" "$url"
162
- else
163
- curl -sf --max-time 30 "$@" "$url"
164
- fi
165
- }
166
-
167
- # ─── SSRF error (colored) — used by _ssrf_safe_curl ───────────────────────────
168
-
169
- masumi_get() {
170
- _ssrf_safe_curl "${MASUMI_REGISTRY_URL}${1}" \
171
- -H "Authorization: Bearer $MASUMI_API_KEY"
172
- }
173
-
174
- masumi_post() {
175
- _ssrf_safe_curl "${MASUMI_PAYMENT_URL}${1}" \
176
- -X POST \
177
- -H "Authorization: Bearer $MASUMI_API_KEY" \
178
- -H "Content-Type: application/json" \
179
- -d "$2"
180
- }
181
-
182
- # Best-effort compatibility layer for registry endpoint changes.
183
- find_agents() {
184
- local encoded="$1"
185
- local base_urls=("$MASUMI_REGISTRY_URL" "$MASUMI_PAYMENT_URL")
186
- local endpoints=(
187
- "/agents?capability=${encoded}&limit=5"
188
- "/registry/agents?capability=${encoded}&limit=5"
189
- "/services/agents?capability=${encoded}&limit=5"
190
- "/search/agents?capability=${encoded}&limit=5"
191
- )
192
- local base ep
193
- local auth_headers=(
194
- "Authorization: Bearer $MASUMI_API_KEY"
195
- "token: $MASUMI_API_KEY"
196
- )
197
- for base in "${base_urls[@]}"; do
198
- for ep in "${endpoints[@]}"; do
199
- local hdr
200
- for hdr in "${auth_headers[@]}"; do
201
- if out="$(_ssrf_safe_curl "${base}${ep}" -H "$hdr" 2>/dev/null)"; then
202
- printf '%s\n' "$out"
203
- return 0
204
- fi
205
- done
206
- done
207
- done
208
- echo "ERROR: agent discovery failed on all known endpoints and auth headers" >&2
209
- return 1
210
- }
211
-
212
- generate_nonce() {
213
- # SECURITY: cryptographically secure 32-byte random nonce.
214
- # `openssl rand -hex 32` always outputs exactly 64 lowercase hex chars + newline.
215
- # No spaces, no special chars — safe from word splitting in all contexts.
216
- # We strip the newline explicitly so callers can safely use $() without concern.
217
- openssl rand -hex 32 | tr -d '[:space:]'
218
- }
219
-
220
- # SECURITY: rate limiter — prevents bounty spam and Masumi flooding.
221
- # Creates a per-command lockfile; rejects calls within RATE_LIMIT_SECONDS of last call.
222
- rate_limit() {
223
- local cmd="$1"
224
- mkdir -p "$RATE_LIMIT_DIR"
225
- chmod 700 "$RATE_LIMIT_DIR"
226
- local lockfile="${RATE_LIMIT_DIR}/${cmd}.last"
227
- if [[ -f "$lockfile" ]]; then
228
- local last_ts; last_ts=$(cat "$lockfile" 2>/dev/null || echo 0)
229
- local now; now=$(date +%s)
230
- local diff=$(( now - last_ts ))
231
- if (( diff < RATE_LIMIT_SECONDS )); then
232
- echo -e "${RED}ERROR${RESET}: Rate limit — wait ${BOLD}$(( RATE_LIMIT_SECONDS - diff ))s${RESET} before calling ${CYAN}$cmd${RESET} again" >&2
233
- exit 1
234
- fi
235
- fi
236
- date +%s > "$lockfile"
237
- }
238
-
239
- die() {
240
- echo "ERROR: $*" >&2
241
- exit 1
242
- }
243
-
244
- # SECURITY: domain-separated hashes prevent cross-namespace collisions.
245
- # A bounty commitment can never equal a receipt hash even with identical inputs.
246
- domain_hash() {
247
- # DARK ENERGY: word splitting guard — pipe through tr to guarantee the output
248
- # is exactly 64 hex chars with no whitespace. sha256sum outputs "hash -\n";
249
- # awk extracts field 1, tr strips any residual whitespace. Safe to use unquoted
250
- # in arithmetic but we always double-quote hash variables regardless.
251
- local domain="$1"; local data="$2"
252
- printf '%s:%s' "$domain" "$data" | sha256sum | awk '{print $1}' | tr -d '[:space:]'
253
- }
254
-
255
- compute_bounty_commitment() { domain_hash "nightpay-bounty-v1" "$1"; }
256
- compute_receipt_hash() { domain_hash "nightpay-receipt-v1" "$1"; }
257
- compute_job_hash() { domain_hash "nightpay-job-v1" "$1"; }
258
-
259
- compute_fee() { echo $(( $1 * OPERATOR_FEE_BPS / 10000 )); }
260
- compute_net() { local fee; fee=$(compute_fee "$1"); echo $(( $1 - fee )); }
261
-
262
- # ─── Encrypted memory (OpenShart) ────────────────────────────────────────────
263
- # PRIVACY: funder credentials (nullifier, nonce, fundedAtTx) are the keys to
264
- # emergency refunds. Printing them to stdout puts them in agent conversation
265
- # history — plaintext, potentially logged by LLM providers, violating privacy.
266
- #
267
- # When OpenShart is available, credentials are encrypted and fragmented via
268
- # Shamir's Secret Sharing. The agent gets back a memory_id, not raw secrets.
269
- # To reclaim funds, the agent recalls the memory_id — OpenShart reconstructs
270
- # the credentials through its ChainLock protocol with timing validation.
271
- #
272
- # Fallback: if OpenShart is not installed, credentials are printed to stdout
273
- # with a warning. The agent must save them somewhere safe.
274
-
275
- OPENSHART_BIN="${OPENSHART_BIN:-}"
276
-
277
- _shart_available() {
278
- if [[ -n "$OPENSHART_BIN" ]]; then
279
- command -v "$OPENSHART_BIN" &>/dev/null && return 0
280
- fi
281
- command -v openshart &>/dev/null && { OPENSHART_BIN="openshart"; return 0; }
282
- command -v npx &>/dev/null && npx openshart --version &>/dev/null 2>&1 && { OPENSHART_BIN="npx openshart"; return 0; }
283
- return 1
284
- }
285
-
286
- # Store a JSON blob in encrypted memory. Returns the memory_id.
287
- _shart_store() {
288
- local content="$1"
289
- local tags="${2:-nightpay,funding}"
290
- local classification="${3:-CONFIDENTIAL}"
291
- if ! _shart_available; then
292
- return 1
293
- fi
294
- $OPENSHART_BIN store \
295
- --content "$content" \
296
- --classification "$classification" \
297
- --tags "$tags" \
298
- --compartments "NIGHTPAY_FUNDING" \
299
- 2>/dev/null | python3 -c "import sys,json; print(json.loads(sys.stdin.read()).get('id',''))"
300
- }
301
-
302
- # Recall a stored memory by ID. Returns the decrypted JSON.
303
- _shart_recall() {
304
- local memory_id="$1"
305
- if ! _shart_available; then
306
- return 1
307
- fi
308
- $OPENSHART_BIN recall --id "$memory_id" 2>/dev/null
309
- }
310
-
311
- # Search encrypted memories by tag. Returns matching IDs.
312
- _shart_search() {
313
- local query="$1"
314
- local limit="${2:-10}"
315
- if ! _shart_available; then
316
- return 1
317
- fi
318
- $OPENSHART_BIN search --query "$query" --limit "$limit" 2>/dev/null
319
- }
320
-
321
- # Call midnight bridge service if BRIDGE_URL is set
322
- bridge_post() {
323
- local endpoint="$1"; local payload="$2"
324
- if [[ -z "$BRIDGE_URL" ]]; then
325
- return 1 # no bridge — caller falls back to local computation
326
- fi
327
- _ssrf_safe_curl "${BRIDGE_URL}${endpoint}" \
328
- -X POST \
329
- -H "Content-Type: application/json" \
330
- -d "$payload"
331
- }
332
-
333
- bridge_get() {
334
- local endpoint="$1"
335
- if [[ -z "$BRIDGE_URL" ]]; then
336
- return 1
337
- fi
338
- _ssrf_safe_curl "${BRIDGE_URL}${endpoint}" \
339
- -H "Content-Type: application/json"
340
- }
341
-
342
- validate_amount() {
343
- local amount="$1"
344
- # SECURITY: enforce integer type, min, and max before any network call
345
- if ! [[ "$amount" =~ ^[0-9]+$ ]]; then
346
- echo "ERROR: amount must be a positive integer (specks)"; exit 1
347
- fi
348
- if (( amount < MIN_BOUNTY_SPECKS )); then
349
- echo "ERROR: Amount $amount below minimum $MIN_BOUNTY_SPECKS specks"; exit 1
350
- fi
351
- if (( amount > MAX_BOUNTY_SPECKS )); then
352
- echo "ERROR: Amount $amount exceeds maximum $MAX_BOUNTY_SPECKS specks"; exit 1
353
- fi
354
- }
355
-
356
- validate_commitment() {
357
- # SECURITY: commitment must be a 64-char hex string — reject malformed inputs
358
- if ! [[ "$1" =~ ^[0-9a-f]{64}$ ]]; then
359
- echo "ERROR: commitment_hash must be a 64-character lowercase hex string"; exit 1
360
- fi
361
- }
362
-
363
- validate_job_id() {
364
- # SECURITY: job IDs must be alphanumeric + hyphens only.
365
- # Prevents path traversal (../../), shell injection, and API endpoint manipulation.
366
- if ! [[ "$1" =~ ^[a-zA-Z0-9_-]{1,128}$ ]]; then
367
- echo "ERROR: job_id must be alphanumeric/hyphens/underscores, max 128 chars"; exit 1
368
- fi
369
- }
370
-
371
- # SECURITY: operator must authenticate before fee withdrawal.
372
- # Requires OPERATOR_SECRET_KEY env var — prevents unauthorized parties from
373
- # draining accumulated fees even if they have shell access to the gateway.
374
- # SECURITY: payload includes a timestamp + random nonce — prevents replay attacks.
375
- # The same HMAC can never be reused because the nonce is different every call.
376
- require_operator_auth() {
377
- if [[ -z "${OPERATOR_SECRET_KEY:-}" ]]; then
378
- echo -e "${RED}SECURITY ERROR${RESET}: withdraw-fees requires ${BOLD}OPERATOR_SECRET_KEY${RESET} env var." >&2
379
- echo -e "${DIM}This prevents unauthorized parties from draining accumulated fees.${RESET}" >&2
380
- exit 1
381
- fi
382
- local payload="$1"
383
- local ts; ts=$(date +%s)
384
- local nonce; nonce=$(generate_nonce)
385
- # Include timestamp + nonce in signed payload — every signature is unique
386
- local full_payload="${payload}:ts=${ts}:nonce=${nonce}"
387
- local sig; sig=$(echo -n "$full_payload" | openssl dgst -sha256 -hmac "$OPERATOR_SECRET_KEY" | awk '{print $2}')
388
- # Return sig:ts:nonce so the Midnight contract can verify freshness
389
- echo "${sig}:${ts}:${nonce}"
390
- }
391
-
392
- # ─── Content Safety ────────────────────────────────────────────────────────────
393
- # SAFETY: classify-then-forget — checks job description in-memory, never logs it.
394
- # Three layers: live rules file > hardcoded fallback > external moderation API.
395
- # Rules auto-updated by update-blocklist.sh (cron). See rules/content-safety.md.
396
-
397
- CONTENT_SAFETY_URL="${CONTENT_SAFETY_URL:-}"
398
- SAFETY_RULES_FILE="${SAFETY_RULES_FILE:-${HOME}/.nightpay/safety/safety-rules.json}"
399
-
400
- safety_check() {
401
- local text="$1"
402
-
403
- local rejected_category
404
- rejected_category=$(python3 -c "
405
- import sys, re, json, os
406
-
407
- text = sys.argv[1].lower()
408
- rules_file = sys.argv[2]
409
-
410
- # ─── Layer 1: load live rules file if available (updated by update-blocklist.sh)
411
- rules = []
412
- if os.path.exists(rules_file):
413
- try:
414
- with open(rules_file) as f:
415
- data = json.load(f)
416
- rules = [(r['category'], r['pattern']) for r in data.get('rules', [])
417
- if 'category' in r and 'pattern' in r]
418
- except (json.JSONDecodeError, KeyError):
419
- pass # fall through to hardcoded
420
-
421
- # ─── Layer 2: hardcoded fallback if no rules file or it failed to load
422
- if not rules:
423
- rules = [
424
- ('csam', r'\b(child|minor|underage|kid|teen)\b.{0,100}?\b(sex|porn|nude|naked|exploit)\b'),
425
- ('csam', r'\b(sex|porn|nude|naked|exploit)\b.{0,100}?\b(child|minor|underage|kid|teen)\b'),
426
- ('violence', r'\b(kill|assassinate|murder|execute)\b.{0,100}?\b(person|people|someone|him|her|them|target)\b'),
427
- ('violence', r'\b(hire|find|pay).{0,100}?\b(hitman|killer|assassin)\b'),
428
- ('violence', r'\bhit\s*man\b'),
429
- ('weapons_of_mass_destruction', r'\b(synthe|build|make|create|assemble)\b.{0,100}?\b(bomb|bioweapon|chemical weapon|nerve agent|sarin|anthrax|ricin|nuclear|dirty bomb|explosive device)\b'),
430
- ('human_trafficking', r'\b(traffic|smuggle|exploit|enslave)\b.{0,100}?\b(person|people|human|worker|organ|women|children)\b'),
431
- ('terrorism', r'\b(fund|finance|recruit|plan|support)\b.{0,100}?\b(terror|jihad|extremis|insurrection|attack on)\b'),
432
- ('ncii', r'\b(deepfake|revenge porn|sextortion|non.?consensual)\b.{0,100}?\b(nude|naked|intimate|image|video|photo)\b'),
433
- ('financial_fraud', r'\b(launder|counterfeit|forge)\b.{0,100}?\b(money|currency|documents|passport|identity)\b'),
434
- ('financial_fraud', r'\b(evade|bypass|circumvent)\b.{0,100}?\b(sanction|embargo|aml|kyc)\b'),
435
- ('infrastructure_attack', r'\b(attack|hack|disrupt|destroy|sabotage)\b.{0,100}?\b(power grid|water supply|hospital|election|pipeline|dam)\b'),
436
- ('doxxing', r'\b(doxx|stalk|track|surveil|locate)\b.{0,100}?\b(person|address|home|family|where .{0,100}? live)\b'),
437
- ('drug_manufacturing', r'\b(synthe|cook|manufacture|produce)\b.{0,100}?\b(meth|fentanyl|heroin|cocaine|mdma|lsd)\b'),
438
- ]
439
-
440
- for category, pattern in rules:
441
- try:
442
- if re.search(pattern, text):
443
- print(category)
444
- sys.exit(0)
445
- except re.error:
446
- continue # skip malformed patterns from feeds
447
-
448
- print('safe')
449
- " "$text" "$SAFETY_RULES_FILE" 2>/dev/null) || rejected_category="safe"
450
-
451
- # ─── Layer 3: external moderation API (catches what regex misses)
452
- if [[ "$rejected_category" == "safe" && -n "$CONTENT_SAFETY_URL" ]]; then
453
- local api_payload
454
- api_payload=$(python3 -c "
455
- import sys, json
456
- print(json.dumps({'text': sys.argv[1]}))
457
- " "$text")
458
- local response
459
- response=$(curl -sf --max-time 5 -X POST \
460
- -H 'Content-Type: application/json' \
461
- -d "$api_payload" \
462
- "$CONTENT_SAFETY_URL" 2>/dev/null) || response=""
463
-
464
- if [[ -n "$response" ]]; then
465
- rejected_category=$(echo "$response" | python3 -c "
466
- import sys, json
467
- try:
468
- d = json.load(sys.stdin)
469
- if not d.get('safe', True):
470
- print(d.get('category', 'unsafe'))
471
- else:
472
- print('safe')
473
- except: print('safe')
474
- " 2>/dev/null) || rejected_category="safe"
475
- fi
476
- fi
477
-
478
- if [[ "$rejected_category" != "safe" ]]; then
479
- python3 -c "
480
- import sys, json
481
- print(json.dumps({
482
- 'status': 'REJECTED',
483
- 'reason': 'content_safety',
484
- 'category': sys.argv[1],
485
- 'message': 'This bounty description was rejected by the content safety gate. See rules/content-safety.md.'
486
- }, indent=2))
487
- " "$rejected_category"
488
- exit 2
489
- fi
490
- }
491
-
492
- # ─── Optimistic delivery & multisig env vars ──────────────────────────────────
493
- OPTIMISTIC_WINDOW_HOURS="${OPTIMISTIC_WINDOW_HOURS:-48}"
494
- MULTISIG_THRESHOLD_SPECKS="${MULTISIG_THRESHOLD_SPECKS:-1000000}"
495
- MULTISIG_M="${MULTISIG_M:-2}"
496
- MULTISIG_N="${MULTISIG_N:-3}"
497
- OPTIMISTIC_SWEEP_PAGE_SIZE="${OPTIMISTIC_SWEEP_PAGE_SIZE:-200}" # capped to <= 500
498
- UNCLAIMED_REFUND_HOURS="${UNCLAIMED_REFUND_HOURS:-24}"
499
- UNCLAIMED_SWEEP_PAGE_SIZE="${UNCLAIMED_SWEEP_PAGE_SIZE:-200}" # capped to <= 500
500
- # APPROVER_KEYS: comma-separated HMAC secrets, one per approver
501
- # e.g. APPROVER_KEYS="key1secret,key2secret,key3secret"
502
- APPROVER_KEYS="${APPROVER_KEYS:-}"
503
- MIP003_PORT="${MIP003_PORT:-8090}"
504
- MIP003_URL="${MIP003_URL:-http://localhost:${MIP003_PORT}}"
505
-
506
- # ─── Commands ─────────────────────────────────────────────────────────────────
507
-
508
- case "$COMMAND" in
509
-
510
- post-bounty)
511
- JOB_DESC="${1:?Usage: post-bounty <job_description> <amount_specks>}"
512
- AMOUNT="${2:?Usage: post-bounty <job_description> <amount_specks>}"
513
-
514
- rate_limit "post-bounty" # SECURITY: max 1 post per RATE_LIMIT_SECONDS
515
- validate_amount "$AMOUNT"
516
- safety_check "$JOB_DESC"
517
-
518
- FEE=$(compute_fee "$AMOUNT")
519
- NET=$(compute_net "$AMOUNT")
520
- NONCE=$(generate_nonce)
521
- JOB_HASH=$(compute_job_hash "$JOB_DESC")
522
-
523
- # SECURITY: domain-separated commitment — matches what the Compact circuit produces
524
- COMMITMENT=$(compute_bounty_commitment "nullifier:${AMOUNT}:${JOB_HASH}:${NONCE}")
525
-
526
- # If bridge is running, submit real on-chain transaction
527
- if [[ -n "$BRIDGE_URL" ]]; then
528
- BRIDGE_PAYLOAD=$(python3 -c "
529
- import sys, json
530
- print(json.dumps({'jobHash': sys.argv[1], 'amount': int(sys.argv[2]), 'nonce': sys.argv[3]}))
531
- " "$JOB_HASH" "$AMOUNT" "$NONCE")
532
- BRIDGE_RESULT=$(bridge_post "/postBounty" "$BRIDGE_PAYLOAD" 2>/dev/null) && {
533
- TX_ID=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('txId',''))" 2>/dev/null)
534
- ON_CHAIN=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print('false' if d.get('stub') else 'true')" 2>/dev/null)
535
- echo -e " ${GREEN}Midnight TX${RESET}: ${DIM}$TX_ID${RESET} ${CYAN}(on-chain: $ON_CHAIN)${RESET}" >&2
536
- } || echo -e " ${YELLOW}WARNING${RESET}: Bridge unavailable — commitment computed locally only" >&2
537
- fi
538
-
539
- # SECURITY: nonce printed once for the caller to store securely.
540
- # NOT persisted by the gateway — loss of nonce means the caller cannot
541
- # prove bounty ownership in a dispute.
542
- python3 -c "
543
- import sys, json
544
- print(json.dumps({
545
- 'commitment': sys.argv[1],
546
- 'nonce': sys.argv[2],
547
- 'jobHash': sys.argv[3],
548
- 'amount': int(sys.argv[4]),
549
- 'operatorFee': int(sys.argv[5]),
550
- 'netToAgent': int(sys.argv[6]),
551
- 'feeBps': int(sys.argv[7]),
552
- 'receiptContract': sys.argv[8],
553
- 'network': sys.argv[9],
554
- 'status': 'posted',
555
- 'warning': 'Store your nonce securely — it cannot be recovered and is required for dispute resolution'
556
- }, indent=2))
557
- " "$COMMITMENT" "$NONCE" "$JOB_HASH" "$AMOUNT" "$FEE" "$NET" "$OPERATOR_FEE_BPS" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK"
558
- ;;
559
-
560
- find-agent)
561
- CAPABILITY="${1:?Usage: find-agent <capability_query>}"
562
- ENCODED=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$CAPABILITY")
563
- find_agents "$ENCODED"
564
- ;;
565
-
566
- agent-showcase)
567
- QUERY="${1:-}"
568
- LIMIT="${AGENT_SHOWCASE_LIMIT:-8}"
569
- URL="${MIP003_URL}/agents?limit=${LIMIT}&sort=credibility&showcase_only=1"
570
- if [[ -n "$QUERY" ]]; then
571
- ENCODED=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$QUERY")
572
- URL="${URL}&q=${ENCODED}"
573
- fi
574
- curl -sf --max-time 15 "$URL"
575
- ;;
576
-
577
- hire-and-pay)
578
- AGENT_ID="${1:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]}"
579
- JOB_DESC="${2:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]}"
580
- COMMITMENT="${3:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]}"
581
- REFUND_ADDRESS="${4:-}"
582
-
583
- validate_commitment "$COMMITMENT"
584
- safety_check "$JOB_DESC"
585
-
586
- # Optional routing hint for no-claim timeout refunds.
587
- # The on-chain release still follows contract logic and commitment proofs.
588
- if [[ -n "$REFUND_ADDRESS" ]] && ! [[ "$REFUND_ADDRESS" =~ ^[0-9a-f]{64}$ ]]; then
589
- echo "ERROR: refund_address must be a 64-character lowercase hex string" >&2
590
- exit 1
591
- fi
592
-
593
- PAYLOAD=$(python3 -c "
594
- import sys, json
595
- refund = sys.argv[6]
596
- input_obj = {
597
- 'description': sys.argv[2],
598
- 'commitmentHash': sys.argv[3],
599
- 'receiptContract': sys.argv[4],
600
- 'network': sys.argv[5]
601
- }
602
- if refund:
603
- input_obj['refundAddress'] = refund
604
- print(json.dumps({
605
- 'agentIdentifier': sys.argv[1],
606
- 'input': input_obj
607
- }))
608
- " "$AGENT_ID" "$JOB_DESC" "$COMMITMENT" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK" "$REFUND_ADDRESS")
609
- masumi_post "/purchases" "$PAYLOAD"
610
- ;;
611
-
612
- hire-direct)
613
- AGENT_ID="${1:?Usage: hire-direct <agent_id> <job_description> <amount_specks>}"
614
- JOB_DESC="${2:?Usage: hire-direct <agent_id> <job_description> <amount_specks>}"
615
- AMOUNT="${3:?Usage: hire-direct <agent_id> <job_description> <amount_specks>}"
616
-
617
- validate_amount "$AMOUNT"
618
- safety_check "$JOB_DESC"
619
- [[ "$AGENT_ID" =~ ^[A-Za-z0-9._:@-]{2,128}$ ]] || die "agent_id must match [A-Za-z0-9._:@-] and be 2-128 chars"
620
-
621
- PAYLOAD=$(python3 -c "
622
- import sys, json
623
- print(json.dumps({
624
- 'amount_specks': int(sys.argv[3]),
625
- 'direct_agent_id': sys.argv[1],
626
- 'visibility': 'hidden',
627
- 'input_data': {
628
- 'description': sys.argv[2],
629
- 'amount_specks': int(sys.argv[3]),
630
- 'visibility': 'hidden',
631
- 'hiringMode': 'direct'
632
- }
633
- }))
634
- " "$AGENT_ID" "$JOB_DESC" "$AMOUNT")
635
- curl -sf --max-time 20 \
636
- -X POST \
637
- -H "Content-Type: application/json" \
638
- -d "$PAYLOAD" \
639
- "${MIP003_URL}/start_job"
640
- ;;
641
-
642
- check-job)
643
- JOB_ID="${1:?Usage: check-job <job_id>}"
644
- validate_job_id "$JOB_ID" # SECURITY: prevent path traversal / injection
645
- masumi_get "/purchases/$JOB_ID/status"
646
- ;;
647
-
648
- approve-multisig)
649
- # Each approver runs this with their own key.
650
- # Collect M blobs and pass all sigs to: gateway.sh complete <id> <commit> --approvals sig1:ts1:nonce1,...
651
- JOB_ID="${1:?Usage: approve-multisig <job_id> <output_hash> <approver_key>}"
652
- OUTPUT_HASH="${2:?Usage: approve-multisig <job_id> <output_hash> <approver_key>}"
653
- APPROVER_KEY="${3:?Usage: approve-multisig <job_id> <output_hash> <approver_key>}"
654
-
655
- validate_job_id "$JOB_ID"
656
- validate_commitment "$OUTPUT_HASH" # reuse 64-hex validator
657
-
658
- TS=$(date +%s)
659
- NONCE=$(generate_nonce)
660
- # SECURITY: timestamp + nonce in payload — each approval is unique, stale replays rejected by complete
661
- SIG_PAYLOAD="${JOB_ID}:${OUTPUT_HASH}:${TS}:${NONCE}"
662
- SIG=$(echo -n "$SIG_PAYLOAD" | openssl dgst -sha256 -hmac "$APPROVER_KEY" | awk '{print $2}')
663
-
664
- python3 -c "
665
- import sys, json
666
- print(json.dumps({
667
- 'job_id': sys.argv[1],
668
- 'output_hash': sys.argv[2],
669
- 'sig': sys.argv[3],
670
- 'ts': int(sys.argv[4]),
671
- 'nonce': sys.argv[5],
672
- 'approval_blob': f'{sys.argv[3]}:{sys.argv[4]}:{sys.argv[5]}',
673
- 'note': 'Pass all collected approval_blobs to: gateway.sh complete <job_id> <commitment> --approvals blob1,blob2'
674
- }, indent=2))
675
- " "$JOB_ID" "$OUTPUT_HASH" "$SIG" "$TS" "$NONCE"
676
- ;;
677
-
678
- complete)
679
- JOB_ID="${1:?Usage: complete <job_id> <commitment_hash> [--approvals sig1:ts1:nonce1,...]}"
680
- COMMITMENT="${2:?Usage: complete <job_id> <commitment_hash>}"
681
- # Optional: $3 = "--approvals", $4 = comma-separated sig:ts:nonce blobs
682
- APPROVALS_FLAG="${3:-}"
683
- APPROVALS_RAW="${4:-}"
684
-
685
- validate_job_id "$JOB_ID" # SECURITY: prevent path traversal
686
- validate_commitment "$COMMITMENT"
687
-
688
- # ── Multisig verification (for high-value bounties) ────────────────────
689
- # Query the MIP-003 server for job amount to decide if multisig required
690
- JOB_AMOUNT=0
691
- if command -v curl >/dev/null 2>&1; then
692
- _JOB_INFO=$(curl -sf --max-time 5 "http://localhost:${MIP003_PORT}/status/${JOB_ID}" 2>/dev/null || echo '{}')
693
- JOB_AMOUNT=$(echo "$_JOB_INFO" | python3 -c "
694
- import sys, json
695
- try:
696
- d = json.load(sys.stdin)
697
- print(d.get('amount_specks') or 0)
698
- except: print(0)
699
- " 2>/dev/null || echo 0)
700
- fi
701
-
702
- if (( JOB_AMOUNT >= MULTISIG_THRESHOLD_SPECKS )); then
703
- if [[ -z "$APPROVALS_RAW" || "$APPROVALS_FLAG" != "--approvals" ]]; then
704
- echo -e "${RED}ERROR${RESET}: job amount ${BOLD}${JOB_AMOUNT} specks${RESET} >= threshold ${MULTISIG_THRESHOLD_SPECKS}" >&2
705
- echo -e "${YELLOW}Multisig required.${RESET} Each approver runs:" >&2
706
- echo -e " ${CYAN}gateway.sh approve-multisig${RESET} $JOB_ID <output_hash> <approver_key>" >&2
707
- echo -e "Then collect M approval_blobs and run:" >&2
708
- echo -e " ${CYAN}gateway.sh complete${RESET} $JOB_ID $COMMITMENT --approvals blob1,blob2" >&2
709
- exit 1
710
- fi
711
-
712
- # Verify M-of-N approvals using Python stdlib only (no new deps)
713
- VERIFY_OK=$(python3 -c "
714
- import sys, json, hmac, hashlib, time
715
-
716
- job_id = sys.argv[1]
717
- output_hash = sys.argv[2]
718
- approvals_raw = sys.argv[3]
719
- approver_keys = [k for k in sys.argv[4].split(',') if k] if sys.argv[4] else []
720
- required_m = int(sys.argv[5])
721
- max_age_secs = 86400 # approvals expire after 24h — prevents replay attacks
722
-
723
- # Parse: each entry is sig:ts:nonce
724
- approvals = []
725
- for entry in approvals_raw.split(','):
726
- parts = entry.split(':')
727
- if len(parts) != 3:
728
- print(f'ERROR: malformed approval blob (expected sig:ts:nonce): {entry}', file=sys.stderr)
729
- sys.exit(1)
730
- try:
731
- approvals.append({'sig': parts[0], 'ts': int(parts[1]), 'nonce': parts[2]})
732
- except ValueError:
733
- print(f'ERROR: non-integer timestamp in approval: {entry}', file=sys.stderr)
734
- sys.exit(1)
735
-
736
- now = int(time.time())
737
- valid_count = 0
738
- used_keys = set() # SECURITY: each key index counts once — no double-counting
739
-
740
- for approval in approvals:
741
- age = now - approval['ts']
742
- if age > max_age_secs:
743
- print(f'WARN: approval ts={approval[\"ts\"]} is too old (age={age}s > {max_age_secs}s)', file=sys.stderr)
744
- continue
745
- if age < -300: # 5-min future clock skew tolerance
746
- print(f'WARN: approval ts={approval[\"ts\"]} is too far in future (age={age}s)', file=sys.stderr)
747
- continue
748
-
749
- payload = f'{job_id}:{output_hash}:{approval[\"ts\"]}:{approval[\"nonce\"]}'
750
- for i, key in enumerate(approver_keys):
751
- if i in used_keys:
752
- continue
753
- expected = hmac.new(key.encode(), payload.encode(), hashlib.sha256).hexdigest()
754
- if hmac.compare_digest(expected, approval['sig']):
755
- used_keys.add(i)
756
- valid_count += 1
757
- break
758
-
759
- if valid_count >= required_m:
760
- print(f'ok:{valid_count}')
761
- else:
762
- print(f'ERROR: only {valid_count} valid approvals, need {required_m}', file=sys.stderr)
763
- sys.exit(1)
764
- " "$JOB_ID" "$COMMITMENT" "$APPROVALS_RAW" "$APPROVER_KEYS" "$MULTISIG_M" 2>&1) || {
765
- echo -e "${RED}SECURITY ERROR${RESET}: multisig verification failed — $VERIFY_OK" >&2
766
- exit 1
767
- }
768
- echo -e " ${GREEN}Multisig${RESET}: $VERIFY_OK approvals verified" >&2
769
- fi
770
-
771
- RESULT_DATA=$(masumi_get "/purchases/$JOB_ID/result")
772
-
773
- # SECURITY: canonical JSON (sorted keys, no whitespace) prevents hash
774
- # manipulation via key reordering or whitespace changes in the API response
775
- OUTPUT_HASH=$(echo "$RESULT_DATA" | python3 -c "
776
- import sys, json, hashlib
777
- d = json.load(sys.stdin)
778
- canonical = json.dumps(d, sort_keys=True, separators=(',',':'))
779
- print(hashlib.sha256(canonical.encode()).hexdigest())
780
- ") || { echo "ERROR: Failed to parse job result as JSON — refusing to mint receipt"; exit 1; }
781
-
782
- COMPLETION_NONCE=$(generate_nonce)
783
-
784
- # SECURITY: domain-separated receipt hash — cannot be forged from bounty inputs
785
- RECEIPT_HASH=$(compute_receipt_hash "${COMMITMENT}:${OUTPUT_HASH}:${COMPLETION_NONCE}")
786
-
787
- # If bridge is running, submit real completeAndReceipt circuit call
788
- BRIDGE_TX_ID=""
789
- BRIDGE_ON_CHAIN="false"
790
- if [[ -n "$BRIDGE_URL" ]]; then
791
- BRIDGE_PAYLOAD=$(python3 -c "
792
- import sys, json
793
- print(json.dumps({'bountyCommitment': sys.argv[1], 'outputHash': sys.argv[2]}))
794
- " "$COMMITMENT" "$OUTPUT_HASH")
795
- BRIDGE_RESULT=$(bridge_post "/completeAndReceipt" "$BRIDGE_PAYLOAD" 2>/dev/null) && {
796
- BRIDGE_TX_ID=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('txId',''))" 2>/dev/null)
797
- BRIDGE_ON_CHAIN=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); print('false' if d.get('stub') else 'true')" 2>/dev/null)
798
- echo -e " ${GREEN}Midnight TX${RESET}: ${DIM}$BRIDGE_TX_ID${RESET} ${CYAN}(on-chain: $BRIDGE_ON_CHAIN)${RESET}" >&2
799
- } || echo -e " ${YELLOW}WARNING${RESET}: Bridge unavailable — receipt computed locally only" >&2
800
- fi
801
-
802
- # Fetch economics from MIP-003 for the cost footer (ClawWork pattern)
803
- _ECON_AMOUNT=0
804
- _ECON_FEE=0
805
- _ECON_NET=0
806
- if command -v curl >/dev/null 2>&1; then
807
- _ECON_INFO=$(curl -sf --max-time 3 "http://localhost:${MIP003_PORT}/status/${JOB_ID}" 2>/dev/null || echo '{}')
808
- read -r _ECON_AMOUNT _ECON_FEE _ECON_NET <<< "$(python3 -c "
809
- import sys, json
810
- try:
811
- d = json.load(sys.stdin)
812
- amount = int(d.get('amount_specks') or 0)
813
- fee_bps = int('${OPERATOR_FEE_BPS}')
814
- fee = amount * fee_bps // 10000
815
- net = amount - fee
816
- print(amount, fee, net)
817
- except: print(0, 0, 0)
818
- " <<< "$_ECON_INFO" 2>/dev/null || echo "0 0 0")"
819
- fi
820
-
821
- python3 -c "
822
- import sys, json
823
- print(json.dumps({
824
- 'receiptHash': sys.argv[1],
825
- 'outputHash': sys.argv[2],
826
- 'commitment': sys.argv[3],
827
- 'completionNonce': sys.argv[4],
828
- 'status': 'completed',
829
- 'midnightNetwork': sys.argv[5],
830
- 'receiptContract': sys.argv[6],
831
- 'midnightTxId': sys.argv[7] or None,
832
- 'onChain': sys.argv[8] == 'true',
833
- # Economics footer — ClawWork-compatible cost accounting shape
834
- 'economics': {
835
- 'amountSpecks': int(sys.argv[9]),
836
- 'fee': int(sys.argv[10]),
837
- 'netToAgent': int(sys.argv[11]),
838
- 'feeBps': int(sys.argv[12]),
839
- },
840
- }, indent=2))
841
- " "$RECEIPT_HASH" "$OUTPUT_HASH" "$COMMITMENT" "$COMPLETION_NONCE" "$MIDNIGHT_NETWORK" "$RECEIPT_CONTRACT" "$BRIDGE_TX_ID" "$BRIDGE_ON_CHAIN" "$_ECON_AMOUNT" "$_ECON_FEE" "$_ECON_NET" "$OPERATOR_FEE_BPS"
842
- ;;
843
-
844
- refund)
845
- JOB_ID="${1:?Usage: refund <job_id> <commitment_hash> [refund_address]}"
846
- COMMITMENT="${2:?Usage: refund <job_id> <commitment_hash> [refund_address]}"
847
- REFUND_ADDRESS="${3:-}"
848
-
849
- validate_job_id "$JOB_ID" # SECURITY: prevent path traversal
850
- validate_commitment "$COMMITMENT"
851
- if [[ -n "$REFUND_ADDRESS" ]] && ! [[ "$REFUND_ADDRESS" =~ ^[0-9a-f]{64}$ ]]; then
852
- echo "ERROR: refund_address must be a 64-character lowercase hex string" >&2
853
- exit 1
854
- fi
855
-
856
- # Step 1: Cancel Masumi escrow on Cardano
857
- echo -e "${CYAN}Cancelling Masumi escrow${RESET} for job ${BOLD}$JOB_ID${RESET}..." >&2
858
- masumi_post "/purchases/$JOB_ID/cancel" "{}"
859
-
860
- # Step 2: Emit on-chain NIGHT refund intent for the Midnight contract.
861
- # SECURITY: the contract's nullifier set ensures the bounty cannot be
862
- # re-claimed after a refund is submitted. The refundHash is the payload
863
- # the operator submits to the Midnight node to release NIGHT to the funder.
864
- REFUND_NONCE=$(generate_nonce)
865
- REFUND_HASH=$(compute_bounty_commitment "refund:${COMMITMENT}:${REFUND_NONCE}")
866
-
867
- python3 -c "
868
- import sys, json
869
- print(json.dumps({
870
- 'commitment': sys.argv[1],
871
- 'refundHash': sys.argv[2],
872
- 'jobId': sys.argv[3],
873
- 'receiptContract': sys.argv[4],
874
- 'network': sys.argv[5],
875
- 'refundAddressHint': sys.argv[6] or None,
876
- 'status': 'refunded',
877
- 'note': 'Submit refundHash to the Midnight contract to release NIGHT back to funder'
878
- }, indent=2))
879
- " "$COMMITMENT" "$REFUND_HASH" "$JOB_ID" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK" "$REFUND_ADDRESS"
880
- ;;
881
-
882
- withdraw-fees)
883
- AMOUNT="${1:-all}"
884
-
885
- # SECURITY: operator must sign the withdrawal — prevents anyone else
886
- # who has shell access from draining the accumulated fee balance
887
- SIG=$(require_operator_auth "${OPERATOR_ADDRESS}:${AMOUNT}")
888
-
889
- python3 -c "
890
- import sys, json
891
- print(json.dumps({
892
- 'operatorAddress': sys.argv[1],
893
- 'withdrawAmount': sys.argv[2],
894
- 'operatorSignature': sys.argv[3],
895
- 'receiptContract': sys.argv[4],
896
- 'network': sys.argv[5],
897
- 'status': 'submitted',
898
- 'note': 'Submit this payload to the Midnight contract withdrawFees() circuit'
899
- }, indent=2))
900
- " "$OPERATOR_ADDRESS" "$AMOUNT" "$SIG" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK"
901
- ;;
902
-
903
- stats)
904
- echo -e "${CYAN}Querying nightpay stats${RESET} from ${DIM}$RECEIPT_CONTRACT${RESET} on ${BOLD}$MIDNIGHT_NETWORK${RESET}..." >&2
905
- if [[ -n "$BRIDGE_URL" ]]; then
906
- bridge_get "/stats" && exit 0
907
- echo -e " ${YELLOW}WARNING${RESET}: Bridge unavailable — showing placeholder" >&2
908
- fi
909
- python3 -c "
910
- import sys, json
911
- print(json.dumps({
912
- 'receiptContract': sys.argv[1],
913
- 'network': sys.argv[2],
914
- 'query': 'getStats()',
915
- 'note': 'Set BRIDGE_URL to get live on-chain stats'
916
- }, indent=2))
917
- " "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK"
918
- ;;
919
-
920
- optimistic-sweep)
921
- # Scan for jobs whose optimistic window has expired and auto-complete them.
922
- # Run on a cron: */30 * * * * bash gateway.sh optimistic-sweep
923
- # Dry-run: gateway.sh optimistic-sweep --dry-run
924
- DRY_RUN=0
925
- [[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1
926
-
927
- MIP003_URL="http://localhost:${MIP003_PORT}"
928
- echo -e "${CYAN}Scanning for auto-approvable jobs${RESET} ${DIM}(window=${OPTIMISTIC_WINDOW_HOURS}h, url=${MIP003_URL}, pageSize=${OPTIMISTIC_SWEEP_PAGE_SIZE})${RESET}..." >&2
929
-
930
- # Fetch one paginated slice of jobs ready for optimistic completion.
931
- NOW_ISO=$(python3 -c "
932
- from datetime import datetime, timezone
933
- print(datetime.now(timezone.utc).isoformat())
934
- ")
935
- JOBS_JSON=$(curl -sf --max-time 10 "${MIP003_URL}/jobs?status=awaiting_approval&approved_before=${NOW_ISO}&limit=${OPTIMISTIC_SWEEP_PAGE_SIZE}&offset=0" 2>/dev/null || echo '{"jobs":[]}')
936
-
937
- # Filter for expired windows and auto-complete each
938
- python3 -c "
939
- import sys, json, subprocess, os
940
- from datetime import datetime, timezone
941
-
942
- jobs_json = sys.argv[1]
943
- gateway = sys.argv[2]
944
- dry_run = sys.argv[3] == '1'
945
- env = os.environ.copy()
946
-
947
- try:
948
- data = json.loads(jobs_json)
949
- except Exception as e:
950
- print(f'ERROR: could not parse /jobs response: {e}', file=sys.stderr)
951
- sys.exit(1)
952
-
953
- now = datetime.now(timezone.utc).isoformat()
954
- jobs = data.get('jobs', [])
955
- done = 0
956
- errors = 0
957
-
958
- for job in jobs:
959
- jid = job.get('job_id', '')
960
- approved_at = job.get('approved_at')
961
- input_data = job.get('input_data') or {}
962
-
963
- if not approved_at or approved_at > now:
964
- continue # window not yet expired
965
-
966
- # Extract commitmentHash from input_data (set by hire-and-pay)
967
- if isinstance(input_data, str):
968
- try: input_data = json.loads(input_data)
969
- except: input_data = {}
970
- commit = input_data.get('commitmentHash', '')
971
-
972
- if not commit:
973
- print(f'SKIP {jid}: no commitmentHash in input_data')
974
- errors += 1
975
- continue
976
-
977
- if dry_run:
978
- print(f'DRY-RUN: would complete job_id={jid} commitment={commit[:16]}...')
979
- done += 1
980
- else:
981
- result = subprocess.run(
982
- ['/usr/bin/env', 'bash', gateway, 'complete', jid, commit],
983
- env=env, capture_output=True, text=True
984
- )
985
- if result.returncode == 0:
986
- print(f'AUTO-COMPLETE OK: {jid}')
987
- done += 1
988
- else:
989
- print(f'AUTO-COMPLETE FAILED: {jid} — {result.stderr.strip()}')
990
- errors += 1
991
-
992
- print(f'Sweep complete: {done} completed, {errors} errors.', file=sys.stderr)
993
- " "$JOBS_JSON" "$0" "$DRY_RUN"
994
- ;;
995
-
996
- # ─── Pool Lifecycle Commands ──────────────────────────────────────────────────
997
-
998
- create-pool)
999
- JOB_DESCRIPTION="${1:?Usage: create-pool <job_description> <contribution_specks> <funding_goal_specks>}"
1000
- CONTRIBUTION_SPECKS="${2:?Usage: create-pool <job_description> <contribution_specks> <funding_goal_specks>}"
1001
- FUNDING_GOAL_SPECKS="${3:?Usage: create-pool <job_description> <contribution_specks> <funding_goal_specks>}"
1002
-
1003
- # SECURITY: validate amounts
1004
- [[ "$CONTRIBUTION_SPECKS" =~ ^[0-9]+$ ]] || die "contribution_specks must be a positive integer"
1005
- [[ "$FUNDING_GOAL_SPECKS" =~ ^[0-9]+$ ]] || die "funding_goal_specks must be a positive integer"
1006
- (( CONTRIBUTION_SPECKS > 0 )) || die "contribution_specks must be > 0"
1007
- (( FUNDING_GOAL_SPECKS > 0 )) || die "funding_goal_specks must be > 0"
1008
- (( FUNDING_GOAL_SPECKS >= CONTRIBUTION_SPECKS )) || die "funding_goal must be >= contribution_amount"
1009
-
1010
- # SECURITY: exact division — no rounding dust
1011
- (( FUNDING_GOAL_SPECKS % CONTRIBUTION_SPECKS == 0 )) || die "funding_goal must be exactly divisible by contribution_amount"
1012
- MAX_FUNDERS=$(( FUNDING_GOAL_SPECKS / CONTRIBUTION_SPECKS ))
1013
- (( MAX_FUNDERS <= 1000 )) || die "max funders exceeds 1000 cap"
1014
-
1015
- # Generate deterministic pool commitment
1016
- POOL_NONCE=$(generate_nonce)
1017
- JOB_HASH=$(domain_hash "nightpay-pool-job-v1" "$JOB_DESCRIPTION")
1018
- POOL_COMMITMENT=$(domain_hash "nightpay-pool-v1" "$JOB_HASH:$FUNDING_GOAL_SPECKS:$CONTRIBUTION_SPECKS:$MAX_FUNDERS:$POOL_NONCE")
1019
-
1020
- validate_commitment "$POOL_COMMITMENT"
1021
-
1022
- # Calculate deadline
1023
- DEFAULT_POOL_DEADLINE_HOURS="${DEFAULT_POOL_DEADLINE_HOURS:-72}"
1024
- DEADLINE_ISO=$(python3 -c "
1025
- from datetime import datetime, timezone, timedelta
1026
- print((datetime.now(timezone.utc) + timedelta(hours=int('$DEFAULT_POOL_DEADLINE_HOURS'))).isoformat())
1027
- ")
1028
-
1029
- # Register pool on the board
1030
- bash "$(dirname "$0")/bounty-board.sh" add "$POOL_COMMITMENT" "pool:funding"
1031
-
1032
- # If bridge is available, submit createPool circuit call
1033
- if [[ -n "$BRIDGE_URL" ]]; then
1034
- bridge_post "/createPool" "{\"jobHash\":\"$JOB_HASH\",\"fundingGoal\":$FUNDING_GOAL_SPECKS,\"contributionAmount\":$CONTRIBUTION_SPECKS,\"maxFunders\":$MAX_FUNDERS,\"nonce\":\"$POOL_NONCE\"}" 2>/dev/null || true
1035
- fi
1036
-
1037
- python3 -c "
1038
- import sys, json
1039
- print(json.dumps({
1040
- 'poolCommitment': sys.argv[1],
1041
- 'fundingGoal': int(sys.argv[2]),
1042
- 'contributionAmount': int(sys.argv[3]),
1043
- 'maxFunders': int(sys.argv[4]),
1044
- 'deadline': sys.argv[5],
1045
- 'status': 'funding',
1046
- 'network': sys.argv[6],
1047
- 'contract': sys.argv[7],
1048
- }, indent=2))
1049
- " "$POOL_COMMITMENT" "$FUNDING_GOAL_SPECKS" "$CONTRIBUTION_SPECKS" "$MAX_FUNDERS" "$DEADLINE_ISO" "$MIDNIGHT_NETWORK" "$RECEIPT_CONTRACT"
1050
- ;;
1051
-
1052
- fund-pool)
1053
- POOL_COMMITMENT="${1:?Usage: fund-pool <pool_commitment>}"
1054
- validate_commitment "$POOL_COMMITMENT"
1055
-
1056
- FUNDER_NONCE=$(generate_nonce)
1057
- FUNDER_NULLIFIER=$(domain_hash "nightpay-funder-v1" "$FUNDER_NONCE")
1058
- FUNDING_RECORD=$(domain_hash "nightpay-funding-v1" "$FUNDER_NULLIFIER:$POOL_COMMITMENT:$FUNDER_NONCE")
1059
-
1060
- # If bridge is available, submit fundPool circuit call
1061
- if [[ -n "$BRIDGE_URL" ]]; then
1062
- bridge_post "/fundPool" "{\"funderNullifier\":\"$FUNDER_NULLIFIER\",\"poolCommitment\":\"$POOL_COMMITMENT\",\"nonce\":\"$FUNDER_NONCE\"}" 2>/dev/null || true
1063
- fi
1064
-
1065
- # PRIVACY: store credentials encrypted via OpenShart if available.
1066
- # These are the keys to emergency refunds — they should NEVER sit in
1067
- # plaintext conversation history or agent logs.
1068
- CREDENTIAL_JSON="{\"poolCommitment\":\"$POOL_COMMITMENT\",\"fundingRecord\":\"$FUNDING_RECORD\",\"funderNullifier\":\"$FUNDER_NULLIFIER\",\"nonce\":\"$FUNDER_NONCE\",\"fundedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
1069
- MEMORY_ID=""
1070
- if MEMORY_ID=$(_shart_store "$CREDENTIAL_JSON" "nightpay,funding,$POOL_COMMITMENT" "CONFIDENTIAL"); then
1071
- # Encrypted storage succeeded — return memory_id instead of raw secrets
1072
- python3 -c "
1073
- import sys, json
1074
- print(json.dumps({
1075
- 'poolCommitment': sys.argv[1],
1076
- 'fundingRecord': sys.argv[2],
1077
- 'status': 'funded',
1078
- 'credentialStorage': 'encrypted',
1079
- 'memoryId': sys.argv[3],
1080
- 'note': 'Credentials stored encrypted via OpenShart. Use memoryId to recall them for refunds.'
1081
- }, indent=2))
1082
- " "$POOL_COMMITMENT" "$FUNDING_RECORD" "$MEMORY_ID"
1083
- else
1084
- # Fallback: no OpenShart — print raw credentials with warning
1085
- python3 -c "
1086
- import sys, json
1087
- print(json.dumps({
1088
- 'poolCommitment': sys.argv[1],
1089
- 'fundingRecord': sys.argv[2],
1090
- 'funderNullifier': sys.argv[3],
1091
- 'nonce': sys.argv[4],
1092
- 'status': 'funded',
1093
- 'credentialStorage': 'plaintext',
1094
- 'WARNING': 'OpenShart not available — credentials are in PLAINTEXT. Install openshart for encrypted storage.',
1095
- 'note': 'SAVE these values securely — you need funderNullifier + nonce to claim a refund if the pool expires'
1096
- }, indent=2))
1097
- " "$POOL_COMMITMENT" "$FUNDING_RECORD" "$FUNDER_NULLIFIER" "$FUNDER_NONCE"
1098
- fi
1099
- ;;
1100
-
1101
- pool-status)
1102
- POOL_COMMITMENT="${1:?Usage: pool-status <pool_commitment>}"
1103
- validate_commitment "$POOL_COMMITMENT"
1104
-
1105
- if [[ -n "$BRIDGE_URL" ]]; then
1106
- bridge_get "/poolStatus/$POOL_COMMITMENT" && exit 0
1107
- echo " WARNING: Bridge unavailable — showing placeholder" >&2
1108
- fi
1109
-
1110
- python3 -c "
1111
- import sys, json
1112
- print(json.dumps({
1113
- 'poolCommitment': sys.argv[1],
1114
- 'query': 'poolStatus',
1115
- 'note': 'Set BRIDGE_URL to get live on-chain pool status'
1116
- }, indent=2))
1117
- " "$POOL_COMMITMENT"
1118
- ;;
1119
-
1120
- activate-pool)
1121
- POOL_COMMITMENT="${1:?Usage: activate-pool <pool_commitment>}"
1122
- validate_commitment "$POOL_COMMITMENT"
1123
-
1124
- if [[ -n "$BRIDGE_URL" ]]; then
1125
- bridge_post "/activatePool" "{\"poolCommitment\":\"$POOL_COMMITMENT\"}" 2>/dev/null || true
1126
- fi
1127
-
1128
- # Update board status
1129
- bash "$(dirname "$0")/bounty-board.sh" remove "$POOL_COMMITMENT" "completed" 2>/dev/null || true
1130
-
1131
- python3 -c "
1132
- import sys, json
1133
- print(json.dumps({
1134
- 'poolCommitment': sys.argv[1],
1135
- 'status': 'activated',
1136
- 'note': 'Pool goal met — funds released to gateway for Masumi escrow. Find an agent next.'
1137
- }, indent=2))
1138
- " "$POOL_COMMITMENT"
1139
- ;;
1140
-
1141
- expire-pool)
1142
- POOL_COMMITMENT="${1:?Usage: expire-pool <pool_commitment>}"
1143
- validate_commitment "$POOL_COMMITMENT"
1144
-
1145
- if [[ -n "$BRIDGE_URL" ]]; then
1146
- bridge_post "/expirePool" "{\"poolCommitment\":\"$POOL_COMMITMENT\"}" 2>/dev/null || true
1147
- fi
1148
-
1149
- # Update board status
1150
- bash "$(dirname "$0")/bounty-board.sh" remove "$POOL_COMMITMENT" "expired" 2>/dev/null || true
1151
-
1152
- python3 -c "
1153
- import sys, json
1154
- print(json.dumps({
1155
- 'poolCommitment': sys.argv[1],
1156
- 'status': 'expired',
1157
- 'note': 'Pool expired — funders can now call claim-refund to reclaim their NIGHT'
1158
- }, indent=2))
1159
- " "$POOL_COMMITMENT"
1160
- ;;
1161
-
1162
- claim-refund)
1163
- # Accepts either:
1164
- # claim-refund <pool_commitment> <funder_nullifier> (manual)
1165
- # claim-refund --memory-id <openshart_memory_id> (auto-recall from encrypted storage)
1166
- if [[ "${1:-}" == "--memory-id" ]]; then
1167
- MEMORY_ID="${2:?Usage: claim-refund --memory-id <openshart_memory_id>}"
1168
- RECALLED=$(_shart_recall "$MEMORY_ID") || { echo "ERROR: Could not recall credentials from OpenShart memory $MEMORY_ID" >&2; exit 1; }
1169
- POOL_COMMITMENT=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['poolCommitment'])")
1170
- FUNDER_NULLIFIER=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['funderNullifier'])")
1171
- else
1172
- POOL_COMMITMENT="${1:?Usage: claim-refund <pool_commitment> <funder_nullifier> OR claim-refund --memory-id <id>}"
1173
- FUNDER_NULLIFIER="${2:?Usage: claim-refund <pool_commitment> <funder_nullifier>}"
1174
- fi
1175
- validate_commitment "$POOL_COMMITMENT"
1176
-
1177
- if [[ -n "$BRIDGE_URL" ]]; then
1178
- bridge_post "/claimRefund" "{\"poolCommitment\":\"$POOL_COMMITMENT\",\"funderNullifier\":\"$FUNDER_NULLIFIER\"}" 2>/dev/null || true
1179
- fi
1180
-
1181
- python3 -c "
1182
- import sys, json
1183
- print(json.dumps({
1184
- 'poolCommitment': sys.argv[1],
1185
- 'funderNullifier': sys.argv[2],
1186
- 'status': 'refunded',
1187
- 'note': 'Full contribution returned — no fee charged on expired pools'
1188
- }, indent=2))
1189
- " "$POOL_COMMITMENT" "$FUNDER_NULLIFIER"
1190
- ;;
1191
-
1192
- emergency-refund)
1193
- # FAILSAFE: bypass the gateway entirely. Submits emergencyRefund circuit call
1194
- # directly to the Midnight contract. No bridge needed.
1195
- # Accepts either:
1196
- # emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>
1197
- # emergency-refund --memory-id <openshart_memory_id> <contribution_specks> <funded_at_tx>
1198
- if [[ "${1:-}" == "--memory-id" ]]; then
1199
- MEMORY_ID="${2:?Usage: emergency-refund --memory-id <id> <contribution_specks> <funded_at_tx>}"
1200
- CONTRIBUTION_SPECKS="${3:?Usage: emergency-refund --memory-id <id> <contribution_specks> <funded_at_tx>}"
1201
- FUNDED_AT_TX="${4:?Usage: emergency-refund --memory-id <id> <contribution_specks> <funded_at_tx>}"
1202
- RECALLED=$(_shart_recall "$MEMORY_ID") || { echo "ERROR: Could not recall credentials from OpenShart memory $MEMORY_ID" >&2; exit 1; }
1203
- POOL_COMMITMENT=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['poolCommitment'])")
1204
- FUNDER_NULLIFIER=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['funderNullifier'])")
1205
- NONCE=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['nonce'])")
1206
- else
1207
- POOL_COMMITMENT="${1:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
1208
- FUNDER_NULLIFIER="${2:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
1209
- CONTRIBUTION_SPECKS="${3:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
1210
- FUNDED_AT_TX="${4:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
1211
- NONCE="${5:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
1212
- fi
1213
- validate_commitment "$POOL_COMMITMENT"
1214
-
1215
- [[ "$CONTRIBUTION_SPECKS" =~ ^[0-9]+$ ]] || die "contribution_specks must be a positive integer"
1216
- [[ "$FUNDED_AT_TX" =~ ^[0-9]+$ ]] || die "funded_at_tx must be a non-negative integer"
1217
-
1218
- python3 -c "
1219
- import sys, json
1220
- print(json.dumps({
1221
- 'poolCommitment': sys.argv[1],
1222
- 'funderNullifier': sys.argv[2],
1223
- 'contributionSpecks': int(sys.argv[3]),
1224
- 'fundedAtTx': int(sys.argv[4]),
1225
- 'nonce': sys.argv[5],
1226
- 'status': 'emergency_refund',
1227
- 'emergencyPath': True,
1228
- 'note': 'Submit this payload directly to the Midnight contract emergencyRefund() circuit — no bridge/gateway needed'
1229
- }, indent=2))
1230
- " "$POOL_COMMITMENT" "$FUNDER_NULLIFIER" "$CONTRIBUTION_SPECKS" "$FUNDED_AT_TX" "$NONCE"
1231
- ;;
1232
-
1233
- refund-unclaimed)
1234
- # Refund jobs that were never claimed and exceeded UNCLAIMED_REFUND_HOURS.
1235
- # Safety conditions:
1236
- # - status == running
1237
- # - claims_count == 0 and assigned_agent_id empty
1238
- # - started_at older than threshold
1239
- # - commitmentHash present in input_data
1240
- DRY_RUN=0
1241
- [[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1
1242
- MIP003_URL="http://localhost:${MIP003_PORT}"
1243
- echo -e "${CYAN}Scanning for unclaimed refunds${RESET} ${DIM}(age=${UNCLAIMED_REFUND_HOURS}h, url=${MIP003_URL}, pageSize=${UNCLAIMED_SWEEP_PAGE_SIZE})${RESET}..." >&2
1244
-
1245
- python3 -c "
1246
- import json, subprocess, sys, urllib.request, urllib.error
1247
- from datetime import datetime, timezone, timedelta
1248
-
1249
- mip_url = sys.argv[1]
1250
- gateway = sys.argv[2]
1251
- dry_run = sys.argv[3] == '1'
1252
- hours = float(sys.argv[4])
1253
- page_size = int(sys.argv[5])
1254
-
1255
- if page_size < 1:
1256
- page_size = 1
1257
- if page_size > 500:
1258
- page_size = 500
1259
-
1260
- threshold = datetime.now(timezone.utc) - timedelta(hours=hours)
1261
- offset = 0
1262
- scanned = 0
1263
- candidates = 0
1264
- done = 0
1265
- errors = 0
1266
-
1267
- def parse_iso(v):
1268
- if not v:
1269
- return None
1270
- try:
1271
- return datetime.fromisoformat(str(v).replace('Z', '+00:00'))
1272
- except Exception:
1273
- return None
1274
-
1275
- while True:
1276
- url = f'{mip_url}/jobs?status=running&limit={page_size}&offset={offset}'
1277
- try:
1278
- with urllib.request.urlopen(url, timeout=10) as r:
1279
- data = json.loads(r.read().decode())
1280
- except Exception as e:
1281
- print(f'ERROR: failed to query jobs page offset={offset}: {e}', file=sys.stderr)
1282
- sys.exit(1)
1283
-
1284
- jobs = data.get('jobs', [])
1285
- if not isinstance(jobs, list):
1286
- print('ERROR: unexpected /jobs response format', file=sys.stderr)
1287
- sys.exit(1)
1288
-
1289
- for job in jobs:
1290
- scanned += 1
1291
- jid = job.get('job_id', '')
1292
- claims = int(job.get('claims_count') or 0)
1293
- assigned = job.get('assigned_agent_id')
1294
- started_at = parse_iso(job.get('started_at'))
1295
- input_data = job.get('input_data') or {}
1296
-
1297
- if claims > 0 or assigned:
1298
- continue
1299
- if not started_at or started_at > threshold:
1300
- continue
1301
- if isinstance(input_data, str):
1302
- try:
1303
- input_data = json.loads(input_data)
1304
- except Exception:
1305
- input_data = {}
1306
- if not isinstance(input_data, dict):
1307
- input_data = {}
1308
-
1309
- commit = str(input_data.get('commitmentHash') or '')
1310
- refund_addr = str(input_data.get('refundAddress') or input_data.get('funderAddress') or '')
1311
- if len(commit) != 64 or any(c not in '0123456789abcdef' for c in commit):
1312
- print(f'SKIP {jid}: missing/invalid commitmentHash for refund', file=sys.stderr)
1313
- errors += 1
1314
- continue
1315
-
1316
- candidates += 1
1317
- if dry_run:
1318
- addr_hint = refund_addr[:12] + '...' if refund_addr else 'unknown'
1319
- print(f'DRY-RUN: would refund job_id={jid} commitment={commit[:16]}... refundAddress={addr_hint}')
1320
- done += 1
1321
- continue
1322
-
1323
- cmd = ['/usr/bin/env', 'bash', gateway, 'refund', jid, commit]
1324
- if len(refund_addr) == 64 and all(c in '0123456789abcdef' for c in refund_addr):
1325
- cmd.append(refund_addr)
1326
- result = subprocess.run(cmd, capture_output=True, text=True)
1327
- if result.returncode == 0:
1328
- print(f'AUTO-REFUND OK: {jid}')
1329
- done += 1
1330
- else:
1331
- print(f'AUTO-REFUND FAILED: {jid} — {result.stderr.strip()}', file=sys.stderr)
1332
- errors += 1
1333
-
1334
- has_more = bool(data.get('has_more'))
1335
- count = int(data.get('count') or 0)
1336
- if not has_more or count == 0:
1337
- break
1338
- offset += page_size
1339
-
1340
- print(f'Unclaimed refund sweep: scanned={scanned}, candidates={candidates}, refunded={done}, errors={errors}.', file=sys.stderr)
1341
- " "$MIP003_URL" "$0" "$DRY_RUN" "$UNCLAIMED_REFUND_HOURS" "$UNCLAIMED_SWEEP_PAGE_SIZE"
1342
- ;;
1343
-
1344
- *)
1345
- echo -e "${BOLD}nightpay gateway${RESET} — anonymous bounty lifecycle CLI" >&2
1346
- echo "" >&2
1347
- echo -e "${BOLD}Commands:${RESET}" >&2
1348
- echo -e " ${CYAN}post-bounty${RESET} <desc> <amount> Fund a bounty anonymously" >&2
1349
- echo -e " ${CYAN}find-agent${RESET} <query> Search Masumi for agents" >&2
1350
- echo -e " ${CYAN}agent-showcase${RESET} [query] List profile showcase agents by credibility" >&2
1351
- echo -e " ${CYAN}hire-and-pay${RESET} <agent> <desc> <hash> Create escrow, start job" >&2
1352
- echo -e " ${CYAN}hire-direct${RESET} <agent> <desc> <amount> Create hidden direct-hire job" >&2
1353
- echo -e " ${CYAN}check-job${RESET} <job_id> Poll job status" >&2
1354
- echo -e " ${CYAN}complete${RESET} <job_id> <hash> Mint receipt, release payment" >&2
1355
- echo -e " ${CYAN}refund${RESET} <job_id> <hash> [addr] Cancel escrow, refund NIGHT" >&2
1356
- echo -e " ${CYAN}refund-unclaimed${RESET} [--dry-run] Auto-refund old unclaimed jobs" >&2
1357
- echo -e " ${CYAN}approve-multisig${RESET} <id> <hash> <key> Sign high-value approval" >&2
1358
- echo -e " ${CYAN}optimistic-sweep${RESET} [--dry-run] Auto-complete expired windows" >&2
1359
- echo -e " ${CYAN}withdraw-fees${RESET} [amount] Operator fee withdrawal" >&2
1360
- echo -e " ${CYAN}stats${RESET} On-chain contract stats" >&2
1361
- echo "" >&2
1362
- echo -e "${DIM}Required: MASUMI_API_KEY MIDNIGHT_NETWORK OPERATOR_ADDRESS RECEIPT_CONTRACT_ADDRESS${RESET}" >&2
1363
- exit 1
1364
- ;;
1365
- esac