nightpay 0.1.0 → 0.4.3
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.
- package/LICENSE +666 -21
- package/README.md +99 -158
- package/bin/cli.js +527 -24
- package/nightpay_sdk.py +398 -0
- package/openclaw.plugin.json +10 -0
- package/package.json +18 -7
- package/plugin.js +712 -0
- package/skills/nightpay/AGENTS.md +302 -0
- package/skills/nightpay/HEARTBEAT.md +55 -0
- package/skills/nightpay/SKILL.md +420 -61
- package/skills/nightpay/contracts/receipt.compact +358 -97
- package/skills/nightpay/contracts/receipt.stub.compact +55 -0
- package/skills/nightpay/ontology/context.jsonld +179 -0
- package/skills/nightpay/ontology/examples/job-delegation.example.jsonld +50 -0
- package/skills/nightpay/ontology/examples/pool-funded.example.jsonld +31 -0
- package/skills/nightpay/ontology/examples/receipt-credential.example.jsonld +33 -0
- package/skills/nightpay/ontology/ontology.jsonld +396 -0
- package/skills/nightpay/ontology/ontology.md +243 -0
- package/skills/nightpay/openclaw-fragment.json +16 -33
- package/skills/nightpay/rules/escrow-safety.md +62 -0
- package/skills/nightpay/rules/privacy-first.md +21 -0
- package/skills/nightpay/scripts/gateway.sh +962 -66
- package/skills/nightpay/scripts/mip003-server.sh +4739 -93
|
@@ -13,22 +13,44 @@
|
|
|
13
13
|
# Usage: ./gateway.sh <command> [args...]
|
|
14
14
|
#
|
|
15
15
|
# Commands:
|
|
16
|
-
#
|
|
17
|
-
#
|
|
18
|
-
#
|
|
19
|
-
#
|
|
20
|
-
#
|
|
21
|
-
# refund
|
|
22
|
-
#
|
|
23
|
-
#
|
|
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
|
|
24
36
|
|
|
25
37
|
set -euo pipefail
|
|
26
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
|
+
|
|
27
48
|
# ─── Required env vars ────────────────────────────────────────────────────────
|
|
28
49
|
MASUMI_PAYMENT_URL="${MASUMI_PAYMENT_URL:-http://localhost:3001/api/v1}"
|
|
29
50
|
MASUMI_REGISTRY_URL="${MASUMI_REGISTRY_URL:-http://localhost:3000/api/v1}"
|
|
30
51
|
MASUMI_API_KEY="${MASUMI_API_KEY:?SECURITY: Set MASUMI_API_KEY}"
|
|
31
|
-
|
|
52
|
+
# Keep preprod default until Midnight mainnet is live.
|
|
53
|
+
MIDNIGHT_NETWORK="${MIDNIGHT_NETWORK:-preprod}"
|
|
32
54
|
OPERATOR_ADDRESS="${OPERATOR_ADDRESS:?SECURITY: Set OPERATOR_ADDRESS}"
|
|
33
55
|
OPERATOR_FEE_BPS="${OPERATOR_FEE_BPS:-200}"
|
|
34
56
|
MAX_BOUNTY_SPECKS="${MAX_BOUNTY_SPECKS:-500000000}"
|
|
@@ -100,7 +122,7 @@ for url in sys.argv[1:]:
|
|
|
100
122
|
print(f'ERROR: {url} — must be http/https'); sys.exit(1)
|
|
101
123
|
print('ok')
|
|
102
124
|
" "$MASUMI_PAYMENT_URL" "$MASUMI_REGISTRY_URL" 2>&1) || {
|
|
103
|
-
echo "SECURITY ERROR: Invalid Masumi URL — $_url_check" >&2; exit 1
|
|
125
|
+
echo -e "${RED}SECURITY ERROR${RESET}: Invalid Masumi URL — $_url_check" >&2; exit 1
|
|
104
126
|
}
|
|
105
127
|
fi
|
|
106
128
|
|
|
@@ -110,36 +132,109 @@ fi
|
|
|
110
132
|
# 169.254.169.254 (AWS metadata) for subsequent calls. We re-resolve per call.
|
|
111
133
|
_ssrf_safe_curl() {
|
|
112
134
|
local url="$1"; shift
|
|
113
|
-
|
|
135
|
+
local resolve_arg
|
|
136
|
+
resolve_arg=$(python3 -c "
|
|
114
137
|
import sys, urllib.parse, ipaddress, socket, os
|
|
115
138
|
url = sys.argv[1]
|
|
116
139
|
parsed = urllib.parse.urlparse(url)
|
|
117
140
|
host = parsed.hostname or ''
|
|
141
|
+
port = parsed.port or (443 if parsed.scheme == 'https' else 80)
|
|
118
142
|
try:
|
|
119
|
-
|
|
143
|
+
if not host:
|
|
144
|
+
sys.exit(0)
|
|
145
|
+
addrs = socket.getaddrinfo(host, port)
|
|
120
146
|
for addr in addrs:
|
|
121
|
-
|
|
147
|
+
ip_str = addr[4][0]
|
|
148
|
+
ip = ipaddress.ip_address(ip_str)
|
|
122
149
|
if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
|
|
123
150
|
if os.environ.get('ALLOW_LOCAL_URLS') == '1':
|
|
151
|
+
print(f'{host}:{port}:{ip_str}')
|
|
124
152
|
sys.exit(0)
|
|
125
153
|
print(f'SSRF blocked: {ip}', file=sys.stderr); sys.exit(1)
|
|
154
|
+
print(f'{host}:{port}:{ip_str}')
|
|
155
|
+
sys.exit(0)
|
|
126
156
|
except socket.gaierror as e:
|
|
127
157
|
print(f'DNS error: {e}', file=sys.stderr); sys.exit(1)
|
|
128
|
-
" "$url" || { echo "SECURITY ERROR: SSRF guard blocked request to $url" >&2; exit 1; }
|
|
129
|
-
|
|
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_request_with_auth_fallback() {
|
|
170
|
+
local method="$1"
|
|
171
|
+
local base_url="$2"
|
|
172
|
+
local endpoint="$3"
|
|
173
|
+
local payload="${4:-}"
|
|
174
|
+
local auth_headers=(
|
|
175
|
+
"Authorization: Bearer $MASUMI_API_KEY"
|
|
176
|
+
"token: $MASUMI_API_KEY"
|
|
177
|
+
)
|
|
178
|
+
local hdr out
|
|
179
|
+
|
|
180
|
+
for hdr in "${auth_headers[@]}"; do
|
|
181
|
+
if [[ "$method" == "GET" ]]; then
|
|
182
|
+
if out="$(_ssrf_safe_curl "${base_url}${endpoint}" -H "$hdr" 2>/dev/null)"; then
|
|
183
|
+
printf '%s\n' "$out"
|
|
184
|
+
return 0
|
|
185
|
+
fi
|
|
186
|
+
else
|
|
187
|
+
if out="$(_ssrf_safe_curl "${base_url}${endpoint}" \
|
|
188
|
+
-X POST \
|
|
189
|
+
-H "$hdr" \
|
|
190
|
+
-H "Content-Type: application/json" \
|
|
191
|
+
-d "$payload" 2>/dev/null)"; then
|
|
192
|
+
printf '%s\n' "$out"
|
|
193
|
+
return 0
|
|
194
|
+
fi
|
|
195
|
+
fi
|
|
196
|
+
done
|
|
197
|
+
|
|
198
|
+
echo "ERROR: Masumi request failed after trying Authorization and token headers (${method} ${endpoint})" >&2
|
|
199
|
+
return 1
|
|
130
200
|
}
|
|
131
201
|
|
|
132
202
|
masumi_get() {
|
|
133
|
-
|
|
134
|
-
-H "Authorization: Bearer $MASUMI_API_KEY"
|
|
203
|
+
_masumi_request_with_auth_fallback "GET" "$MASUMI_REGISTRY_URL" "$1"
|
|
135
204
|
}
|
|
136
205
|
|
|
137
206
|
masumi_post() {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
207
|
+
_masumi_request_with_auth_fallback "POST" "$MASUMI_PAYMENT_URL" "$1" "$2"
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
# Best-effort compatibility layer for registry endpoint changes.
|
|
211
|
+
find_agents() {
|
|
212
|
+
local encoded="$1"
|
|
213
|
+
local base_urls=("$MASUMI_REGISTRY_URL" "$MASUMI_PAYMENT_URL")
|
|
214
|
+
local endpoints=(
|
|
215
|
+
"/agents?capability=${encoded}&limit=5"
|
|
216
|
+
"/registry/agents?capability=${encoded}&limit=5"
|
|
217
|
+
"/services/agents?capability=${encoded}&limit=5"
|
|
218
|
+
"/search/agents?capability=${encoded}&limit=5"
|
|
219
|
+
)
|
|
220
|
+
local base ep
|
|
221
|
+
local auth_headers=(
|
|
222
|
+
"Authorization: Bearer $MASUMI_API_KEY"
|
|
223
|
+
"token: $MASUMI_API_KEY"
|
|
224
|
+
)
|
|
225
|
+
for base in "${base_urls[@]}"; do
|
|
226
|
+
for ep in "${endpoints[@]}"; do
|
|
227
|
+
local hdr
|
|
228
|
+
for hdr in "${auth_headers[@]}"; do
|
|
229
|
+
if out="$(_ssrf_safe_curl "${base}${ep}" -H "$hdr" 2>/dev/null)"; then
|
|
230
|
+
printf '%s\n' "$out"
|
|
231
|
+
return 0
|
|
232
|
+
fi
|
|
233
|
+
done
|
|
234
|
+
done
|
|
235
|
+
done
|
|
236
|
+
echo "ERROR: agent discovery failed on all known endpoints and auth headers" >&2
|
|
237
|
+
return 1
|
|
143
238
|
}
|
|
144
239
|
|
|
145
240
|
generate_nonce() {
|
|
@@ -162,13 +257,18 @@ rate_limit() {
|
|
|
162
257
|
local now; now=$(date +%s)
|
|
163
258
|
local diff=$(( now - last_ts ))
|
|
164
259
|
if (( diff < RATE_LIMIT_SECONDS )); then
|
|
165
|
-
echo "ERROR: Rate limit — wait $(( RATE_LIMIT_SECONDS - diff ))s before calling $cmd again" >&2
|
|
260
|
+
echo -e "${RED}ERROR${RESET}: Rate limit — wait ${BOLD}$(( RATE_LIMIT_SECONDS - diff ))s${RESET} before calling ${CYAN}$cmd${RESET} again" >&2
|
|
166
261
|
exit 1
|
|
167
262
|
fi
|
|
168
263
|
fi
|
|
169
264
|
date +%s > "$lockfile"
|
|
170
265
|
}
|
|
171
266
|
|
|
267
|
+
die() {
|
|
268
|
+
echo "ERROR: $*" >&2
|
|
269
|
+
exit 1
|
|
270
|
+
}
|
|
271
|
+
|
|
172
272
|
# SECURITY: domain-separated hashes prevent cross-namespace collisions.
|
|
173
273
|
# A bounty commitment can never equal a receipt hash even with identical inputs.
|
|
174
274
|
domain_hash() {
|
|
@@ -187,6 +287,65 @@ compute_job_hash() { domain_hash "nightpay-job-v1" "$1"; }
|
|
|
187
287
|
compute_fee() { echo $(( $1 * OPERATOR_FEE_BPS / 10000 )); }
|
|
188
288
|
compute_net() { local fee; fee=$(compute_fee "$1"); echo $(( $1 - fee )); }
|
|
189
289
|
|
|
290
|
+
# ─── Encrypted memory (OpenShart) ────────────────────────────────────────────
|
|
291
|
+
# PRIVACY: funder credentials (nullifier, nonce, fundedAtTx) are the keys to
|
|
292
|
+
# emergency refunds. Printing them to stdout puts them in agent conversation
|
|
293
|
+
# history — plaintext, potentially logged by LLM providers, violating privacy.
|
|
294
|
+
#
|
|
295
|
+
# When OpenShart is available, credentials are encrypted and fragmented via
|
|
296
|
+
# Shamir's Secret Sharing. The agent gets back a memory_id, not raw secrets.
|
|
297
|
+
# To reclaim funds, the agent recalls the memory_id — OpenShart reconstructs
|
|
298
|
+
# the credentials through its ChainLock protocol with timing validation.
|
|
299
|
+
#
|
|
300
|
+
# Fallback: if OpenShart is not installed, credentials are printed to stdout
|
|
301
|
+
# with a warning. The agent must save them somewhere safe.
|
|
302
|
+
|
|
303
|
+
OPENSHART_BIN="${OPENSHART_BIN:-}"
|
|
304
|
+
|
|
305
|
+
_shart_available() {
|
|
306
|
+
if [[ -n "$OPENSHART_BIN" ]]; then
|
|
307
|
+
command -v "$OPENSHART_BIN" &>/dev/null && return 0
|
|
308
|
+
fi
|
|
309
|
+
command -v openshart &>/dev/null && { OPENSHART_BIN="openshart"; return 0; }
|
|
310
|
+
command -v npx &>/dev/null && npx openshart --version &>/dev/null 2>&1 && { OPENSHART_BIN="npx openshart"; return 0; }
|
|
311
|
+
return 1
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
# Store a JSON blob in encrypted memory. Returns the memory_id.
|
|
315
|
+
_shart_store() {
|
|
316
|
+
local content="$1"
|
|
317
|
+
local tags="${2:-nightpay,funding}"
|
|
318
|
+
local classification="${3:-CONFIDENTIAL}"
|
|
319
|
+
if ! _shart_available; then
|
|
320
|
+
return 1
|
|
321
|
+
fi
|
|
322
|
+
$OPENSHART_BIN store \
|
|
323
|
+
--content "$content" \
|
|
324
|
+
--classification "$classification" \
|
|
325
|
+
--tags "$tags" \
|
|
326
|
+
--compartments "NIGHTPAY_FUNDING" \
|
|
327
|
+
2>/dev/null | python3 -c "import sys,json; print(json.loads(sys.stdin.read()).get('id',''))"
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
# Recall a stored memory by ID. Returns the decrypted JSON.
|
|
331
|
+
_shart_recall() {
|
|
332
|
+
local memory_id="$1"
|
|
333
|
+
if ! _shart_available; then
|
|
334
|
+
return 1
|
|
335
|
+
fi
|
|
336
|
+
$OPENSHART_BIN recall --id "$memory_id" 2>/dev/null
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
# Search encrypted memories by tag. Returns matching IDs.
|
|
340
|
+
_shart_search() {
|
|
341
|
+
local query="$1"
|
|
342
|
+
local limit="${2:-10}"
|
|
343
|
+
if ! _shart_available; then
|
|
344
|
+
return 1
|
|
345
|
+
fi
|
|
346
|
+
$OPENSHART_BIN search --query "$query" --limit "$limit" 2>/dev/null
|
|
347
|
+
}
|
|
348
|
+
|
|
190
349
|
# Call midnight bridge service if BRIDGE_URL is set
|
|
191
350
|
bridge_post() {
|
|
192
351
|
local endpoint="$1"; local payload="$2"
|
|
@@ -244,8 +403,8 @@ validate_job_id() {
|
|
|
244
403
|
# The same HMAC can never be reused because the nonce is different every call.
|
|
245
404
|
require_operator_auth() {
|
|
246
405
|
if [[ -z "${OPERATOR_SECRET_KEY:-}" ]]; then
|
|
247
|
-
echo "SECURITY ERROR: withdraw-fees requires OPERATOR_SECRET_KEY env var." >&2
|
|
248
|
-
echo "This prevents unauthorized parties from draining accumulated fees
|
|
406
|
+
echo -e "${RED}SECURITY ERROR${RESET}: withdraw-fees requires ${BOLD}OPERATOR_SECRET_KEY${RESET} env var." >&2
|
|
407
|
+
echo -e "${DIM}This prevents unauthorized parties from draining accumulated fees.${RESET}" >&2
|
|
249
408
|
exit 1
|
|
250
409
|
fi
|
|
251
410
|
local payload="$1"
|
|
@@ -290,20 +449,20 @@ if os.path.exists(rules_file):
|
|
|
290
449
|
# ─── Layer 2: hardcoded fallback if no rules file or it failed to load
|
|
291
450
|
if not rules:
|
|
292
451
|
rules = [
|
|
293
|
-
('csam', r'\b(child|minor|underage|kid|teen)\b
|
|
294
|
-
('csam', r'\b(sex|porn|nude|naked|exploit)\b
|
|
295
|
-
('violence', r'\b(kill|assassinate|murder|execute)\b
|
|
296
|
-
('violence', r'\b(hire|find|pay)
|
|
452
|
+
('csam', r'\b(child|minor|underage|kid|teen)\b.{0,100}?\b(sex|porn|nude|naked|exploit)\b'),
|
|
453
|
+
('csam', r'\b(sex|porn|nude|naked|exploit)\b.{0,100}?\b(child|minor|underage|kid|teen)\b'),
|
|
454
|
+
('violence', r'\b(kill|assassinate|murder|execute)\b.{0,100}?\b(person|people|someone|him|her|them|target)\b'),
|
|
455
|
+
('violence', r'\b(hire|find|pay).{0,100}?\b(hitman|killer|assassin)\b'),
|
|
297
456
|
('violence', r'\bhit\s*man\b'),
|
|
298
|
-
('weapons_of_mass_destruction', r'\b(synthe|build|make|create|assemble)\b
|
|
299
|
-
('human_trafficking', r'\b(traffic|smuggle|exploit|enslave)\b
|
|
300
|
-
('terrorism', r'\b(fund|finance|recruit|plan|support)\b
|
|
301
|
-
('ncii', r'\b(deepfake|revenge porn|sextortion|non.?consensual)\b
|
|
302
|
-
('financial_fraud', r'\b(launder|counterfeit|forge)\b
|
|
303
|
-
('financial_fraud', r'\b(evade|bypass|circumvent)\b
|
|
304
|
-
('infrastructure_attack', r'\b(attack|hack|disrupt|destroy|sabotage)\b
|
|
305
|
-
('doxxing', r'\b(doxx|stalk|track|surveil|locate)\b
|
|
306
|
-
('drug_manufacturing', r'\b(synthe|cook|manufacture|produce)\b
|
|
457
|
+
('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'),
|
|
458
|
+
('human_trafficking', r'\b(traffic|smuggle|exploit|enslave)\b.{0,100}?\b(person|people|human|worker|organ|women|children)\b'),
|
|
459
|
+
('terrorism', r'\b(fund|finance|recruit|plan|support)\b.{0,100}?\b(terror|jihad|extremis|insurrection|attack on)\b'),
|
|
460
|
+
('ncii', r'\b(deepfake|revenge porn|sextortion|non.?consensual)\b.{0,100}?\b(nude|naked|intimate|image|video|photo)\b'),
|
|
461
|
+
('financial_fraud', r'\b(launder|counterfeit|forge)\b.{0,100}?\b(money|currency|documents|passport|identity)\b'),
|
|
462
|
+
('financial_fraud', r'\b(evade|bypass|circumvent)\b.{0,100}?\b(sanction|embargo|aml|kyc)\b'),
|
|
463
|
+
('infrastructure_attack', r'\b(attack|hack|disrupt|destroy|sabotage)\b.{0,100}?\b(power grid|water supply|hospital|election|pipeline|dam)\b'),
|
|
464
|
+
('doxxing', r'\b(doxx|stalk|track|surveil|locate)\b.{0,100}?\b(person|address|home|family|where .{0,100}? live)\b'),
|
|
465
|
+
('drug_manufacturing', r'\b(synthe|cook|manufacture|produce)\b.{0,100}?\b(meth|fentanyl|heroin|cocaine|mdma|lsd)\b'),
|
|
307
466
|
]
|
|
308
467
|
|
|
309
468
|
for category, pattern in rules:
|
|
@@ -358,6 +517,22 @@ print(json.dumps({
|
|
|
358
517
|
fi
|
|
359
518
|
}
|
|
360
519
|
|
|
520
|
+
# ─── Optimistic delivery & multisig env vars ──────────────────────────────────
|
|
521
|
+
OPTIMISTIC_WINDOW_HOURS="${OPTIMISTIC_WINDOW_HOURS:-48}"
|
|
522
|
+
MULTISIG_THRESHOLD_SPECKS="${MULTISIG_THRESHOLD_SPECKS:-1000000}"
|
|
523
|
+
MULTISIG_M="${MULTISIG_M:-2}"
|
|
524
|
+
MULTISIG_N="${MULTISIG_N:-3}"
|
|
525
|
+
OPTIMISTIC_SWEEP_PAGE_SIZE="${OPTIMISTIC_SWEEP_PAGE_SIZE:-200}" # capped to <= 500
|
|
526
|
+
UNCLAIMED_REFUND_HOURS="${UNCLAIMED_REFUND_HOURS:-24}"
|
|
527
|
+
UNCLAIMED_SWEEP_PAGE_SIZE="${UNCLAIMED_SWEEP_PAGE_SIZE:-200}" # capped to <= 500
|
|
528
|
+
# APPROVER_KEYS: comma-separated HMAC secrets, one per approver
|
|
529
|
+
# e.g. APPROVER_KEYS="key1secret,key2secret,key3secret"
|
|
530
|
+
APPROVER_KEYS="${APPROVER_KEYS:-}"
|
|
531
|
+
MIP003_PORT="${MIP003_PORT:-8090}"
|
|
532
|
+
MIP003_URL="${MIP003_URL:-http://localhost:${MIP003_PORT}}"
|
|
533
|
+
# Optional x402 passthrough for MIP-003 APIs that enforce PAYMENT-SIGNATURE.
|
|
534
|
+
MIP003_PAYMENT_SIGNATURE="${MIP003_PAYMENT_SIGNATURE:-}"
|
|
535
|
+
|
|
361
536
|
# ─── Commands ─────────────────────────────────────────────────────────────────
|
|
362
537
|
|
|
363
538
|
case "$COMMAND" in
|
|
@@ -377,6 +552,8 @@ case "$COMMAND" in
|
|
|
377
552
|
|
|
378
553
|
# SECURITY: domain-separated commitment — matches what the Compact circuit produces
|
|
379
554
|
COMMITMENT=$(compute_bounty_commitment "nullifier:${AMOUNT}:${JOB_HASH}:${NONCE}")
|
|
555
|
+
TX_ID=""
|
|
556
|
+
ON_CHAIN="false"
|
|
380
557
|
|
|
381
558
|
# If bridge is running, submit real on-chain transaction
|
|
382
559
|
if [[ -n "$BRIDGE_URL" ]]; then
|
|
@@ -387,8 +564,12 @@ print(json.dumps({'jobHash': sys.argv[1], 'amount': int(sys.argv[2]), 'nonce': s
|
|
|
387
564
|
BRIDGE_RESULT=$(bridge_post "/postBounty" "$BRIDGE_PAYLOAD" 2>/dev/null) && {
|
|
388
565
|
TX_ID=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('txId',''))" 2>/dev/null)
|
|
389
566
|
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)
|
|
390
|
-
echo "
|
|
391
|
-
|
|
567
|
+
BRIDGE_COMMITMENT=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('commitment',''))" 2>/dev/null)
|
|
568
|
+
if [[ "$BRIDGE_COMMITMENT" =~ ^[0-9a-f]{64}$ ]]; then
|
|
569
|
+
COMMITMENT="$BRIDGE_COMMITMENT"
|
|
570
|
+
fi
|
|
571
|
+
echo -e " ${GREEN}Midnight TX${RESET}: ${DIM}$TX_ID${RESET} ${CYAN}(on-chain: $ON_CHAIN)${RESET}" >&2
|
|
572
|
+
} || echo -e " ${YELLOW}WARNING${RESET}: Bridge unavailable — commitment computed locally only" >&2
|
|
392
573
|
fi
|
|
393
574
|
|
|
394
575
|
# SECURITY: nonce printed once for the caller to store securely.
|
|
@@ -415,30 +596,88 @@ print(json.dumps({
|
|
|
415
596
|
find-agent)
|
|
416
597
|
CAPABILITY="${1:?Usage: find-agent <capability_query>}"
|
|
417
598
|
ENCODED=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$CAPABILITY")
|
|
418
|
-
|
|
599
|
+
find_agents "$ENCODED"
|
|
600
|
+
;;
|
|
601
|
+
|
|
602
|
+
agent-showcase)
|
|
603
|
+
QUERY="${1:-}"
|
|
604
|
+
LIMIT="${AGENT_SHOWCASE_LIMIT:-8}"
|
|
605
|
+
URL="${MIP003_URL}/agents?limit=${LIMIT}&sort=credibility&showcase_only=1"
|
|
606
|
+
if [[ -n "$QUERY" ]]; then
|
|
607
|
+
ENCODED=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$QUERY")
|
|
608
|
+
URL="${URL}&q=${ENCODED}"
|
|
609
|
+
fi
|
|
610
|
+
curl -sf --max-time 15 "$URL"
|
|
419
611
|
;;
|
|
420
612
|
|
|
421
613
|
hire-and-pay)
|
|
422
|
-
AGENT_ID="${1:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash>}"
|
|
423
|
-
JOB_DESC="${2:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash>}"
|
|
424
|
-
COMMITMENT="${3:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash>}"
|
|
614
|
+
AGENT_ID="${1:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]}"
|
|
615
|
+
JOB_DESC="${2:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]}"
|
|
616
|
+
COMMITMENT="${3:?Usage: hire-and-pay <agent_id> <job_description> <commitment_hash> [refund_address]}"
|
|
617
|
+
REFUND_ADDRESS="${4:-}"
|
|
425
618
|
|
|
426
619
|
validate_commitment "$COMMITMENT"
|
|
427
620
|
safety_check "$JOB_DESC"
|
|
428
621
|
|
|
622
|
+
# Optional routing hint for no-claim timeout refunds.
|
|
623
|
+
# The on-chain release still follows contract logic and commitment proofs.
|
|
624
|
+
if [[ -n "$REFUND_ADDRESS" ]] && ! [[ "$REFUND_ADDRESS" =~ ^[0-9a-f]{64}$ ]]; then
|
|
625
|
+
echo "ERROR: refund_address must be a 64-character lowercase hex string" >&2
|
|
626
|
+
exit 1
|
|
627
|
+
fi
|
|
628
|
+
|
|
429
629
|
PAYLOAD=$(python3 -c "
|
|
430
630
|
import sys, json
|
|
631
|
+
refund = sys.argv[6]
|
|
632
|
+
input_obj = {
|
|
633
|
+
'description': sys.argv[2],
|
|
634
|
+
'commitmentHash': sys.argv[3],
|
|
635
|
+
'receiptContract': sys.argv[4],
|
|
636
|
+
'network': sys.argv[5]
|
|
637
|
+
}
|
|
638
|
+
if refund:
|
|
639
|
+
input_obj['refundAddress'] = refund
|
|
431
640
|
print(json.dumps({
|
|
432
641
|
'agentIdentifier': sys.argv[1],
|
|
433
|
-
'input':
|
|
642
|
+
'input': input_obj
|
|
643
|
+
}))
|
|
644
|
+
" "$AGENT_ID" "$JOB_DESC" "$COMMITMENT" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK" "$REFUND_ADDRESS")
|
|
645
|
+
masumi_post "/purchases" "$PAYLOAD"
|
|
646
|
+
;;
|
|
647
|
+
|
|
648
|
+
hire-direct)
|
|
649
|
+
AGENT_ID="${1:?Usage: hire-direct <agent_id> <job_description> <amount_specks>}"
|
|
650
|
+
JOB_DESC="${2:?Usage: hire-direct <agent_id> <job_description> <amount_specks>}"
|
|
651
|
+
AMOUNT="${3:?Usage: hire-direct <agent_id> <job_description> <amount_specks>}"
|
|
652
|
+
|
|
653
|
+
validate_amount "$AMOUNT"
|
|
654
|
+
safety_check "$JOB_DESC"
|
|
655
|
+
[[ "$AGENT_ID" =~ ^[A-Za-z0-9._:@-]{2,128}$ ]] || die "agent_id must match [A-Za-z0-9._:@-] and be 2-128 chars"
|
|
656
|
+
|
|
657
|
+
PAYLOAD=$(python3 -c "
|
|
658
|
+
import sys, json
|
|
659
|
+
print(json.dumps({
|
|
660
|
+
'amount_specks': int(sys.argv[3]),
|
|
661
|
+
'direct_agent_id': sys.argv[1],
|
|
662
|
+
'visibility': 'hidden',
|
|
663
|
+
'input_data': {
|
|
434
664
|
'description': sys.argv[2],
|
|
435
|
-
'
|
|
436
|
-
'
|
|
437
|
-
'
|
|
665
|
+
'amount_specks': int(sys.argv[3]),
|
|
666
|
+
'visibility': 'hidden',
|
|
667
|
+
'hiringMode': 'direct'
|
|
438
668
|
}
|
|
439
669
|
}))
|
|
440
|
-
" "$AGENT_ID" "$JOB_DESC" "$
|
|
441
|
-
|
|
670
|
+
" "$AGENT_ID" "$JOB_DESC" "$AMOUNT")
|
|
671
|
+
MIP_X402_ARGS=()
|
|
672
|
+
if [[ -n "$MIP003_PAYMENT_SIGNATURE" ]]; then
|
|
673
|
+
MIP_X402_ARGS=(-H "PAYMENT-SIGNATURE: ${MIP003_PAYMENT_SIGNATURE}")
|
|
674
|
+
fi
|
|
675
|
+
curl -sf --max-time 20 \
|
|
676
|
+
-X POST \
|
|
677
|
+
-H "Content-Type: application/json" \
|
|
678
|
+
"${MIP_X402_ARGS[@]}" \
|
|
679
|
+
-d "$PAYLOAD" \
|
|
680
|
+
"${MIP003_URL}/start_job"
|
|
442
681
|
;;
|
|
443
682
|
|
|
444
683
|
check-job)
|
|
@@ -447,12 +686,134 @@ print(json.dumps({
|
|
|
447
686
|
masumi_get "/purchases/$JOB_ID/status"
|
|
448
687
|
;;
|
|
449
688
|
|
|
689
|
+
approve-multisig)
|
|
690
|
+
# Each approver runs this with their own key.
|
|
691
|
+
# Collect M blobs and pass all sigs to: gateway.sh complete <id> <commit> --approvals sig1:ts1:nonce1,...
|
|
692
|
+
JOB_ID="${1:?Usage: approve-multisig <job_id> <output_hash> <approver_key>}"
|
|
693
|
+
OUTPUT_HASH="${2:?Usage: approve-multisig <job_id> <output_hash> <approver_key>}"
|
|
694
|
+
APPROVER_KEY="${3:?Usage: approve-multisig <job_id> <output_hash> <approver_key>}"
|
|
695
|
+
|
|
696
|
+
validate_job_id "$JOB_ID"
|
|
697
|
+
validate_commitment "$OUTPUT_HASH" # reuse 64-hex validator
|
|
698
|
+
|
|
699
|
+
TS=$(date +%s)
|
|
700
|
+
NONCE=$(generate_nonce)
|
|
701
|
+
# SECURITY: timestamp + nonce in payload — each approval is unique, stale replays rejected by complete
|
|
702
|
+
SIG_PAYLOAD="${JOB_ID}:${OUTPUT_HASH}:${TS}:${NONCE}"
|
|
703
|
+
SIG=$(echo -n "$SIG_PAYLOAD" | openssl dgst -sha256 -hmac "$APPROVER_KEY" | awk '{print $2}')
|
|
704
|
+
|
|
705
|
+
python3 -c "
|
|
706
|
+
import sys, json
|
|
707
|
+
print(json.dumps({
|
|
708
|
+
'job_id': sys.argv[1],
|
|
709
|
+
'output_hash': sys.argv[2],
|
|
710
|
+
'sig': sys.argv[3],
|
|
711
|
+
'ts': int(sys.argv[4]),
|
|
712
|
+
'nonce': sys.argv[5],
|
|
713
|
+
'approval_blob': f'{sys.argv[3]}:{sys.argv[4]}:{sys.argv[5]}',
|
|
714
|
+
'note': 'Pass all collected approval_blobs to: gateway.sh complete <job_id> <commitment> --approvals blob1,blob2'
|
|
715
|
+
}, indent=2))
|
|
716
|
+
" "$JOB_ID" "$OUTPUT_HASH" "$SIG" "$TS" "$NONCE"
|
|
717
|
+
;;
|
|
718
|
+
|
|
450
719
|
complete)
|
|
451
|
-
JOB_ID="${1:?Usage: complete <job_id> <commitment_hash>}"
|
|
720
|
+
JOB_ID="${1:?Usage: complete <job_id> <commitment_hash> [--approvals sig1:ts1:nonce1,...]}"
|
|
452
721
|
COMMITMENT="${2:?Usage: complete <job_id> <commitment_hash>}"
|
|
722
|
+
# Optional: $3 = "--approvals", $4 = comma-separated sig:ts:nonce blobs
|
|
723
|
+
APPROVALS_FLAG="${3:-}"
|
|
724
|
+
APPROVALS_RAW="${4:-}"
|
|
453
725
|
|
|
454
726
|
validate_job_id "$JOB_ID" # SECURITY: prevent path traversal
|
|
455
727
|
validate_commitment "$COMMITMENT"
|
|
728
|
+
MIP003_BASE="${MIP003_URL%/}"
|
|
729
|
+
|
|
730
|
+
MIP_STATUS_AUTH_ARGS=()
|
|
731
|
+
if [[ -n "${OPERATOR_SECRET_KEY:-}" ]]; then
|
|
732
|
+
MIP_STATUS_AUTH_ARGS=(-H "Authorization: Bearer ${OPERATOR_SECRET_KEY}")
|
|
733
|
+
fi
|
|
734
|
+
|
|
735
|
+
# ── Multisig verification (for high-value bounties) ────────────────────
|
|
736
|
+
# Query the MIP-003 server for job amount to decide if multisig required
|
|
737
|
+
JOB_AMOUNT=0
|
|
738
|
+
if command -v curl >/dev/null 2>&1; then
|
|
739
|
+
_JOB_INFO=$(curl -sf --max-time 5 "${MIP_STATUS_AUTH_ARGS[@]}" "${MIP003_BASE}/status/${JOB_ID}" 2>/dev/null || echo '{}')
|
|
740
|
+
JOB_AMOUNT=$(echo "$_JOB_INFO" | python3 -c "
|
|
741
|
+
import sys, json
|
|
742
|
+
try:
|
|
743
|
+
d = json.load(sys.stdin)
|
|
744
|
+
print(d.get('amount_specks') or 0)
|
|
745
|
+
except: print(0)
|
|
746
|
+
" 2>/dev/null || echo 0)
|
|
747
|
+
fi
|
|
748
|
+
|
|
749
|
+
if (( JOB_AMOUNT >= MULTISIG_THRESHOLD_SPECKS )); then
|
|
750
|
+
if [[ -z "$APPROVALS_RAW" || "$APPROVALS_FLAG" != "--approvals" ]]; then
|
|
751
|
+
echo -e "${RED}ERROR${RESET}: job amount ${BOLD}${JOB_AMOUNT} specks${RESET} >= threshold ${MULTISIG_THRESHOLD_SPECKS}" >&2
|
|
752
|
+
echo -e "${YELLOW}Multisig required.${RESET} Each approver runs:" >&2
|
|
753
|
+
echo -e " ${CYAN}gateway.sh approve-multisig${RESET} $JOB_ID <output_hash> <approver_key>" >&2
|
|
754
|
+
echo -e "Then collect M approval_blobs and run:" >&2
|
|
755
|
+
echo -e " ${CYAN}gateway.sh complete${RESET} $JOB_ID $COMMITMENT --approvals blob1,blob2" >&2
|
|
756
|
+
exit 1
|
|
757
|
+
fi
|
|
758
|
+
|
|
759
|
+
# Verify M-of-N approvals using Python stdlib only (no new deps)
|
|
760
|
+
VERIFY_OK=$(python3 -c "
|
|
761
|
+
import sys, json, hmac, hashlib, time
|
|
762
|
+
|
|
763
|
+
job_id = sys.argv[1]
|
|
764
|
+
output_hash = sys.argv[2]
|
|
765
|
+
approvals_raw = sys.argv[3]
|
|
766
|
+
approver_keys = [k for k in sys.argv[4].split(',') if k] if sys.argv[4] else []
|
|
767
|
+
required_m = int(sys.argv[5])
|
|
768
|
+
max_age_secs = 86400 # approvals expire after 24h — prevents replay attacks
|
|
769
|
+
|
|
770
|
+
# Parse: each entry is sig:ts:nonce
|
|
771
|
+
approvals = []
|
|
772
|
+
for entry in approvals_raw.split(','):
|
|
773
|
+
parts = entry.split(':')
|
|
774
|
+
if len(parts) != 3:
|
|
775
|
+
print(f'ERROR: malformed approval blob (expected sig:ts:nonce): {entry}', file=sys.stderr)
|
|
776
|
+
sys.exit(1)
|
|
777
|
+
try:
|
|
778
|
+
approvals.append({'sig': parts[0], 'ts': int(parts[1]), 'nonce': parts[2]})
|
|
779
|
+
except ValueError:
|
|
780
|
+
print(f'ERROR: non-integer timestamp in approval: {entry}', file=sys.stderr)
|
|
781
|
+
sys.exit(1)
|
|
782
|
+
|
|
783
|
+
now = int(time.time())
|
|
784
|
+
valid_count = 0
|
|
785
|
+
used_keys = set() # SECURITY: each key index counts once — no double-counting
|
|
786
|
+
|
|
787
|
+
for approval in approvals:
|
|
788
|
+
age = now - approval['ts']
|
|
789
|
+
if age > max_age_secs:
|
|
790
|
+
print(f'WARN: approval ts={approval[\"ts\"]} is too old (age={age}s > {max_age_secs}s)', file=sys.stderr)
|
|
791
|
+
continue
|
|
792
|
+
if age < -300: # 5-min future clock skew tolerance
|
|
793
|
+
print(f'WARN: approval ts={approval[\"ts\"]} is too far in future (age={age}s)', file=sys.stderr)
|
|
794
|
+
continue
|
|
795
|
+
|
|
796
|
+
payload = f'{job_id}:{output_hash}:{approval[\"ts\"]}:{approval[\"nonce\"]}'
|
|
797
|
+
for i, key in enumerate(approver_keys):
|
|
798
|
+
if i in used_keys:
|
|
799
|
+
continue
|
|
800
|
+
expected = hmac.new(key.encode(), payload.encode(), hashlib.sha256).hexdigest()
|
|
801
|
+
if hmac.compare_digest(expected, approval['sig']):
|
|
802
|
+
used_keys.add(i)
|
|
803
|
+
valid_count += 1
|
|
804
|
+
break
|
|
805
|
+
|
|
806
|
+
if valid_count >= required_m:
|
|
807
|
+
print(f'ok:{valid_count}')
|
|
808
|
+
else:
|
|
809
|
+
print(f'ERROR: only {valid_count} valid approvals, need {required_m}', file=sys.stderr)
|
|
810
|
+
sys.exit(1)
|
|
811
|
+
" "$JOB_ID" "$COMMITMENT" "$APPROVALS_RAW" "$APPROVER_KEYS" "$MULTISIG_M" 2>&1) || {
|
|
812
|
+
echo -e "${RED}SECURITY ERROR${RESET}: multisig verification failed — $VERIFY_OK" >&2
|
|
813
|
+
exit 1
|
|
814
|
+
}
|
|
815
|
+
echo -e " ${GREEN}Multisig${RESET}: $VERIFY_OK approvals verified" >&2
|
|
816
|
+
fi
|
|
456
817
|
|
|
457
818
|
RESULT_DATA=$(masumi_get "/purchases/$JOB_ID/result")
|
|
458
819
|
|
|
@@ -466,6 +827,7 @@ print(hashlib.sha256(canonical.encode()).hexdigest())
|
|
|
466
827
|
") || { echo "ERROR: Failed to parse job result as JSON — refusing to mint receipt"; exit 1; }
|
|
467
828
|
|
|
468
829
|
COMPLETION_NONCE=$(generate_nonce)
|
|
830
|
+
RECEIPT_SOURCE="local"
|
|
469
831
|
|
|
470
832
|
# SECURITY: domain-separated receipt hash — cannot be forged from bounty inputs
|
|
471
833
|
RECEIPT_HASH=$(compute_receipt_hash "${COMMITMENT}:${OUTPUT_HASH}:${COMPLETION_NONCE}")
|
|
@@ -481,8 +843,73 @@ print(json.dumps({'bountyCommitment': sys.argv[1], 'outputHash': sys.argv[2]}))
|
|
|
481
843
|
BRIDGE_RESULT=$(bridge_post "/completeAndReceipt" "$BRIDGE_PAYLOAD" 2>/dev/null) && {
|
|
482
844
|
BRIDGE_TX_ID=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('txId',''))" 2>/dev/null)
|
|
483
845
|
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)
|
|
484
|
-
echo "
|
|
485
|
-
|
|
846
|
+
BRIDGE_RECEIPT_HASH=$(echo "$BRIDGE_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('receiptHash',''))" 2>/dev/null)
|
|
847
|
+
if [[ "$BRIDGE_RECEIPT_HASH" =~ ^[0-9a-f]{64}$ ]]; then
|
|
848
|
+
RECEIPT_HASH="$BRIDGE_RECEIPT_HASH"
|
|
849
|
+
COMPLETION_NONCE=""
|
|
850
|
+
RECEIPT_SOURCE="bridge"
|
|
851
|
+
fi
|
|
852
|
+
echo -e " ${GREEN}Midnight TX${RESET}: ${DIM}$BRIDGE_TX_ID${RESET} ${CYAN}(on-chain: $BRIDGE_ON_CHAIN)${RESET}" >&2
|
|
853
|
+
} || echo -e " ${YELLOW}WARNING${RESET}: Bridge unavailable — receipt computed locally only" >&2
|
|
854
|
+
fi
|
|
855
|
+
|
|
856
|
+
# Fetch economics from MIP-003 for the cost footer (ClawWork pattern)
|
|
857
|
+
_ECON_AMOUNT=0
|
|
858
|
+
_ECON_FEE=0
|
|
859
|
+
_ECON_NET=0
|
|
860
|
+
if command -v curl >/dev/null 2>&1; then
|
|
861
|
+
_ECON_INFO=$(curl -sf --max-time 3 "${MIP_STATUS_AUTH_ARGS[@]}" "${MIP003_BASE}/status/${JOB_ID}" 2>/dev/null || echo '{}')
|
|
862
|
+
read -r _ECON_AMOUNT _ECON_FEE _ECON_NET <<< "$(python3 -c "
|
|
863
|
+
import sys, json
|
|
864
|
+
try:
|
|
865
|
+
d = json.load(sys.stdin)
|
|
866
|
+
amount = int(d.get('amount_specks') or 0)
|
|
867
|
+
fee_bps = int('${OPERATOR_FEE_BPS}')
|
|
868
|
+
fee = amount * fee_bps // 10000
|
|
869
|
+
net = amount - fee
|
|
870
|
+
print(amount, fee, net)
|
|
871
|
+
except: print(0, 0, 0)
|
|
872
|
+
" <<< "$_ECON_INFO" 2>/dev/null || echo "0 0 0")"
|
|
873
|
+
fi
|
|
874
|
+
|
|
875
|
+
# Sync MIP status so agents polling /status see the final completed state.
|
|
876
|
+
MIP_SYNC_OK="false"
|
|
877
|
+
MIP_SYNC_STATE="not_attempted"
|
|
878
|
+
if [[ -n "$MIP003_BASE" ]]; then
|
|
879
|
+
if [[ -z "${OPERATOR_SECRET_KEY:-}" ]]; then
|
|
880
|
+
MIP_SYNC_STATE="skipped_no_operator_secret"
|
|
881
|
+
echo -e " ${YELLOW}WARNING${RESET}: OPERATOR_SECRET_KEY missing — cannot sync ${CYAN}${MIP003_BASE}/complete_job${RESET}" >&2
|
|
882
|
+
else
|
|
883
|
+
MIP_SYNC_PAYLOAD=$(python3 -c "
|
|
884
|
+
import sys, json
|
|
885
|
+
print(json.dumps({
|
|
886
|
+
'receiptHash': sys.argv[1],
|
|
887
|
+
'outputHash': sys.argv[2],
|
|
888
|
+
'midnightTxId': sys.argv[3] or None,
|
|
889
|
+
'onChain': sys.argv[4] == 'true'
|
|
890
|
+
}))
|
|
891
|
+
" "$RECEIPT_HASH" "$OUTPUT_HASH" "$BRIDGE_TX_ID" "$BRIDGE_ON_CHAIN")
|
|
892
|
+
MIP_SYNC_RESULT=$(curl -sf --max-time 15 \
|
|
893
|
+
-X POST \
|
|
894
|
+
-H "Authorization: Bearer ${OPERATOR_SECRET_KEY}" \
|
|
895
|
+
-H "Content-Type: application/json" \
|
|
896
|
+
-d "$MIP_SYNC_PAYLOAD" \
|
|
897
|
+
"${MIP003_BASE}/complete_job/${JOB_ID}" 2>/dev/null) && {
|
|
898
|
+
MIP_SYNC_OK="true"
|
|
899
|
+
MIP_SYNC_STATE=$(echo "$MIP_SYNC_RESULT" | python3 -c "
|
|
900
|
+
import sys, json
|
|
901
|
+
try:
|
|
902
|
+
d = json.load(sys.stdin)
|
|
903
|
+
print(d.get('internal_status') or d.get('status') or 'completed')
|
|
904
|
+
except:
|
|
905
|
+
print('completed')
|
|
906
|
+
")
|
|
907
|
+
echo -e " ${GREEN}MIP Sync${RESET}: ${DIM}${MIP003_BASE}/complete_job/${JOB_ID}${RESET} ${CYAN}(state: ${MIP_SYNC_STATE})${RESET}" >&2
|
|
908
|
+
} || {
|
|
909
|
+
MIP_SYNC_STATE="sync_failed"
|
|
910
|
+
echo -e " ${YELLOW}WARNING${RESET}: could not sync MIP completion state at ${CYAN}${MIP003_BASE}/complete_job/${JOB_ID}${RESET}" >&2
|
|
911
|
+
}
|
|
912
|
+
fi
|
|
486
913
|
fi
|
|
487
914
|
|
|
488
915
|
python3 -c "
|
|
@@ -491,25 +918,43 @@ print(json.dumps({
|
|
|
491
918
|
'receiptHash': sys.argv[1],
|
|
492
919
|
'outputHash': sys.argv[2],
|
|
493
920
|
'commitment': sys.argv[3],
|
|
494
|
-
'completionNonce': sys.argv[4],
|
|
921
|
+
'completionNonce': sys.argv[4] or None,
|
|
922
|
+
'receiptSource': sys.argv[5],
|
|
495
923
|
'status': 'completed',
|
|
496
|
-
'midnightNetwork': sys.argv[
|
|
497
|
-
'receiptContract': sys.argv[
|
|
498
|
-
'midnightTxId': sys.argv[
|
|
499
|
-
'onChain': sys.argv[
|
|
924
|
+
'midnightNetwork': sys.argv[6],
|
|
925
|
+
'receiptContract': sys.argv[7],
|
|
926
|
+
'midnightTxId': sys.argv[8] or None,
|
|
927
|
+
'onChain': sys.argv[9] == 'true',
|
|
928
|
+
# Economics footer — ClawWork-compatible cost accounting shape
|
|
929
|
+
'economics': {
|
|
930
|
+
'amountSpecks': int(sys.argv[10]),
|
|
931
|
+
'fee': int(sys.argv[11]),
|
|
932
|
+
'netToAgent': int(sys.argv[12]),
|
|
933
|
+
'feeBps': int(sys.argv[13]),
|
|
934
|
+
},
|
|
935
|
+
'mipStatusSync': {
|
|
936
|
+
'ok': sys.argv[14] == 'true',
|
|
937
|
+
'state': sys.argv[15],
|
|
938
|
+
'baseUrl': sys.argv[16],
|
|
939
|
+
},
|
|
500
940
|
}, indent=2))
|
|
501
|
-
" "$RECEIPT_HASH" "$OUTPUT_HASH" "$COMMITMENT" "$COMPLETION_NONCE" "$MIDNIGHT_NETWORK" "$RECEIPT_CONTRACT" "$BRIDGE_TX_ID" "$BRIDGE_ON_CHAIN"
|
|
941
|
+
" "$RECEIPT_HASH" "$OUTPUT_HASH" "$COMMITMENT" "$COMPLETION_NONCE" "$RECEIPT_SOURCE" "$MIDNIGHT_NETWORK" "$RECEIPT_CONTRACT" "$BRIDGE_TX_ID" "$BRIDGE_ON_CHAIN" "$_ECON_AMOUNT" "$_ECON_FEE" "$_ECON_NET" "$OPERATOR_FEE_BPS" "$MIP_SYNC_OK" "$MIP_SYNC_STATE" "$MIP003_BASE"
|
|
502
942
|
;;
|
|
503
943
|
|
|
504
944
|
refund)
|
|
505
|
-
JOB_ID="${1:?Usage: refund <job_id> <commitment_hash>}"
|
|
506
|
-
COMMITMENT="${2:?Usage: refund <job_id> <commitment_hash>}"
|
|
945
|
+
JOB_ID="${1:?Usage: refund <job_id> <commitment_hash> [refund_address]}"
|
|
946
|
+
COMMITMENT="${2:?Usage: refund <job_id> <commitment_hash> [refund_address]}"
|
|
947
|
+
REFUND_ADDRESS="${3:-}"
|
|
507
948
|
|
|
508
949
|
validate_job_id "$JOB_ID" # SECURITY: prevent path traversal
|
|
509
950
|
validate_commitment "$COMMITMENT"
|
|
951
|
+
if [[ -n "$REFUND_ADDRESS" ]] && ! [[ "$REFUND_ADDRESS" =~ ^[0-9a-f]{64}$ ]]; then
|
|
952
|
+
echo "ERROR: refund_address must be a 64-character lowercase hex string" >&2
|
|
953
|
+
exit 1
|
|
954
|
+
fi
|
|
510
955
|
|
|
511
956
|
# Step 1: Cancel Masumi escrow on Cardano
|
|
512
|
-
echo "Cancelling Masumi escrow for job $JOB_ID..." >&2
|
|
957
|
+
echo -e "${CYAN}Cancelling Masumi escrow${RESET} for job ${BOLD}$JOB_ID${RESET}..." >&2
|
|
513
958
|
masumi_post "/purchases/$JOB_ID/cancel" "{}"
|
|
514
959
|
|
|
515
960
|
# Step 2: Emit on-chain NIGHT refund intent for the Midnight contract.
|
|
@@ -527,10 +972,11 @@ print(json.dumps({
|
|
|
527
972
|
'jobId': sys.argv[3],
|
|
528
973
|
'receiptContract': sys.argv[4],
|
|
529
974
|
'network': sys.argv[5],
|
|
975
|
+
'refundAddressHint': sys.argv[6] or None,
|
|
530
976
|
'status': 'refunded',
|
|
531
977
|
'note': 'Submit refundHash to the Midnight contract to release NIGHT back to funder'
|
|
532
978
|
}, indent=2))
|
|
533
|
-
" "$COMMITMENT" "$REFUND_HASH" "$JOB_ID" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK"
|
|
979
|
+
" "$COMMITMENT" "$REFUND_HASH" "$JOB_ID" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK" "$REFUND_ADDRESS"
|
|
534
980
|
;;
|
|
535
981
|
|
|
536
982
|
withdraw-fees)
|
|
@@ -555,10 +1001,10 @@ print(json.dumps({
|
|
|
555
1001
|
;;
|
|
556
1002
|
|
|
557
1003
|
stats)
|
|
558
|
-
echo "Querying nightpay stats from $RECEIPT_CONTRACT on $MIDNIGHT_NETWORK..." >&2
|
|
1004
|
+
echo -e "${CYAN}Querying nightpay stats${RESET} from ${DIM}$RECEIPT_CONTRACT${RESET} on ${BOLD}$MIDNIGHT_NETWORK${RESET}..." >&2
|
|
559
1005
|
if [[ -n "$BRIDGE_URL" ]]; then
|
|
560
1006
|
bridge_get "/stats" && exit 0
|
|
561
|
-
echo " WARNING: Bridge unavailable — showing placeholder" >&2
|
|
1007
|
+
echo -e " ${YELLOW}WARNING${RESET}: Bridge unavailable — showing placeholder" >&2
|
|
562
1008
|
fi
|
|
563
1009
|
python3 -c "
|
|
564
1010
|
import sys, json
|
|
@@ -571,8 +1017,458 @@ print(json.dumps({
|
|
|
571
1017
|
" "$RECEIPT_CONTRACT" "$MIDNIGHT_NETWORK"
|
|
572
1018
|
;;
|
|
573
1019
|
|
|
1020
|
+
optimistic-sweep)
|
|
1021
|
+
# Scan for jobs whose optimistic window has expired and auto-complete them.
|
|
1022
|
+
# Run on a cron: */30 * * * * bash gateway.sh optimistic-sweep
|
|
1023
|
+
# Dry-run: gateway.sh optimistic-sweep --dry-run
|
|
1024
|
+
DRY_RUN=0
|
|
1025
|
+
[[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1
|
|
1026
|
+
|
|
1027
|
+
MIP003_URL="http://localhost:${MIP003_PORT}"
|
|
1028
|
+
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
|
|
1029
|
+
|
|
1030
|
+
# Fetch one paginated slice of jobs ready for optimistic completion.
|
|
1031
|
+
NOW_ISO=$(python3 -c "
|
|
1032
|
+
from datetime import datetime, timezone
|
|
1033
|
+
print(datetime.now(timezone.utc).isoformat())
|
|
1034
|
+
")
|
|
1035
|
+
MIP_SWEEP_AUTH_ARGS=()
|
|
1036
|
+
if [[ -n "${OPERATOR_SECRET_KEY:-}" ]]; then
|
|
1037
|
+
MIP_SWEEP_AUTH_ARGS=(-H "Authorization: Bearer ${OPERATOR_SECRET_KEY}")
|
|
1038
|
+
fi
|
|
1039
|
+
JOBS_JSON=$(curl -sf --max-time 10 "${MIP_SWEEP_AUTH_ARGS[@]}" "${MIP003_URL}/jobs?status=awaiting_approval&visibility=all&approved_before=${NOW_ISO}&limit=${OPTIMISTIC_SWEEP_PAGE_SIZE}&offset=0" 2>/dev/null || echo '{"jobs":[]}')
|
|
1040
|
+
|
|
1041
|
+
# Filter for expired windows and auto-complete each
|
|
1042
|
+
python3 -c "
|
|
1043
|
+
import sys, json, subprocess, os
|
|
1044
|
+
from datetime import datetime, timezone
|
|
1045
|
+
|
|
1046
|
+
jobs_json = sys.argv[1]
|
|
1047
|
+
gateway = sys.argv[2]
|
|
1048
|
+
dry_run = sys.argv[3] == '1'
|
|
1049
|
+
env = os.environ.copy()
|
|
1050
|
+
|
|
1051
|
+
try:
|
|
1052
|
+
data = json.loads(jobs_json)
|
|
1053
|
+
except Exception as e:
|
|
1054
|
+
print(f'ERROR: could not parse /jobs response: {e}', file=sys.stderr)
|
|
1055
|
+
sys.exit(1)
|
|
1056
|
+
|
|
1057
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
1058
|
+
jobs = data.get('jobs', [])
|
|
1059
|
+
done = 0
|
|
1060
|
+
errors = 0
|
|
1061
|
+
|
|
1062
|
+
for job in jobs:
|
|
1063
|
+
jid = job.get('job_id', '')
|
|
1064
|
+
approved_at = job.get('approved_at')
|
|
1065
|
+
input_data = job.get('input_data') or {}
|
|
1066
|
+
|
|
1067
|
+
if not approved_at or approved_at > now:
|
|
1068
|
+
continue # window not yet expired
|
|
1069
|
+
|
|
1070
|
+
# Extract commitmentHash from input_data (set by hire-and-pay)
|
|
1071
|
+
if isinstance(input_data, str):
|
|
1072
|
+
try: input_data = json.loads(input_data)
|
|
1073
|
+
except: input_data = {}
|
|
1074
|
+
commit = input_data.get('commitmentHash', '')
|
|
1075
|
+
|
|
1076
|
+
if not commit:
|
|
1077
|
+
print(f'SKIP {jid}: no commitmentHash in input_data')
|
|
1078
|
+
errors += 1
|
|
1079
|
+
continue
|
|
1080
|
+
|
|
1081
|
+
if dry_run:
|
|
1082
|
+
print(f'DRY-RUN: would complete job_id={jid} commitment={commit[:16]}...')
|
|
1083
|
+
done += 1
|
|
1084
|
+
else:
|
|
1085
|
+
result = subprocess.run(
|
|
1086
|
+
['/usr/bin/env', 'bash', gateway, 'complete', jid, commit],
|
|
1087
|
+
env=env, capture_output=True, text=True
|
|
1088
|
+
)
|
|
1089
|
+
if result.returncode == 0:
|
|
1090
|
+
print(f'AUTO-COMPLETE OK: {jid}')
|
|
1091
|
+
done += 1
|
|
1092
|
+
else:
|
|
1093
|
+
print(f'AUTO-COMPLETE FAILED: {jid} — {result.stderr.strip()}')
|
|
1094
|
+
errors += 1
|
|
1095
|
+
|
|
1096
|
+
print(f'Sweep complete: {done} completed, {errors} errors.', file=sys.stderr)
|
|
1097
|
+
" "$JOBS_JSON" "$0" "$DRY_RUN"
|
|
1098
|
+
;;
|
|
1099
|
+
|
|
1100
|
+
# ─── Pool Lifecycle Commands ──────────────────────────────────────────────────
|
|
1101
|
+
|
|
1102
|
+
create-pool)
|
|
1103
|
+
JOB_DESCRIPTION="${1:?Usage: create-pool <job_description> <contribution_specks> <funding_goal_specks>}"
|
|
1104
|
+
CONTRIBUTION_SPECKS="${2:?Usage: create-pool <job_description> <contribution_specks> <funding_goal_specks>}"
|
|
1105
|
+
FUNDING_GOAL_SPECKS="${3:?Usage: create-pool <job_description> <contribution_specks> <funding_goal_specks>}"
|
|
1106
|
+
|
|
1107
|
+
# SECURITY: validate amounts
|
|
1108
|
+
[[ "$CONTRIBUTION_SPECKS" =~ ^[0-9]+$ ]] || die "contribution_specks must be a positive integer"
|
|
1109
|
+
[[ "$FUNDING_GOAL_SPECKS" =~ ^[0-9]+$ ]] || die "funding_goal_specks must be a positive integer"
|
|
1110
|
+
(( CONTRIBUTION_SPECKS > 0 )) || die "contribution_specks must be > 0"
|
|
1111
|
+
(( FUNDING_GOAL_SPECKS > 0 )) || die "funding_goal_specks must be > 0"
|
|
1112
|
+
(( FUNDING_GOAL_SPECKS >= CONTRIBUTION_SPECKS )) || die "funding_goal must be >= contribution_amount"
|
|
1113
|
+
|
|
1114
|
+
# SECURITY: exact division — no rounding dust
|
|
1115
|
+
(( FUNDING_GOAL_SPECKS % CONTRIBUTION_SPECKS == 0 )) || die "funding_goal must be exactly divisible by contribution_amount"
|
|
1116
|
+
MAX_FUNDERS=$(( FUNDING_GOAL_SPECKS / CONTRIBUTION_SPECKS ))
|
|
1117
|
+
(( MAX_FUNDERS <= 1000 )) || die "max funders exceeds 1000 cap"
|
|
1118
|
+
|
|
1119
|
+
# Generate deterministic pool commitment
|
|
1120
|
+
POOL_NONCE=$(generate_nonce)
|
|
1121
|
+
JOB_HASH=$(domain_hash "nightpay-pool-job-v1" "$JOB_DESCRIPTION")
|
|
1122
|
+
POOL_COMMITMENT=$(domain_hash "nightpay-pool-v1" "$JOB_HASH:$FUNDING_GOAL_SPECKS:$CONTRIBUTION_SPECKS:$MAX_FUNDERS:$POOL_NONCE")
|
|
1123
|
+
|
|
1124
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1125
|
+
|
|
1126
|
+
# Calculate deadline
|
|
1127
|
+
DEFAULT_POOL_DEADLINE_HOURS="${DEFAULT_POOL_DEADLINE_HOURS:-72}"
|
|
1128
|
+
DEADLINE_ISO=$(python3 -c "
|
|
1129
|
+
from datetime import datetime, timezone, timedelta
|
|
1130
|
+
print((datetime.now(timezone.utc) + timedelta(hours=int('$DEFAULT_POOL_DEADLINE_HOURS'))).isoformat())
|
|
1131
|
+
")
|
|
1132
|
+
|
|
1133
|
+
# Register pool on the board
|
|
1134
|
+
bash "$(dirname "$0")/bounty-board.sh" add "$POOL_COMMITMENT" "pool:funding"
|
|
1135
|
+
|
|
1136
|
+
# If bridge is available, submit createPool circuit call
|
|
1137
|
+
if [[ -n "$BRIDGE_URL" ]]; then
|
|
1138
|
+
bridge_post "/createPool" "{\"jobHash\":\"$JOB_HASH\",\"fundingGoal\":$FUNDING_GOAL_SPECKS,\"contributionAmount\":$CONTRIBUTION_SPECKS,\"maxFunders\":$MAX_FUNDERS,\"nonce\":\"$POOL_NONCE\"}" 2>/dev/null || true
|
|
1139
|
+
fi
|
|
1140
|
+
|
|
1141
|
+
python3 -c "
|
|
1142
|
+
import sys, json
|
|
1143
|
+
print(json.dumps({
|
|
1144
|
+
'poolCommitment': sys.argv[1],
|
|
1145
|
+
'fundingGoal': int(sys.argv[2]),
|
|
1146
|
+
'contributionAmount': int(sys.argv[3]),
|
|
1147
|
+
'maxFunders': int(sys.argv[4]),
|
|
1148
|
+
'deadline': sys.argv[5],
|
|
1149
|
+
'status': 'funding',
|
|
1150
|
+
'network': sys.argv[6],
|
|
1151
|
+
'contract': sys.argv[7],
|
|
1152
|
+
}, indent=2))
|
|
1153
|
+
" "$POOL_COMMITMENT" "$FUNDING_GOAL_SPECKS" "$CONTRIBUTION_SPECKS" "$MAX_FUNDERS" "$DEADLINE_ISO" "$MIDNIGHT_NETWORK" "$RECEIPT_CONTRACT"
|
|
1154
|
+
;;
|
|
1155
|
+
|
|
1156
|
+
fund-pool)
|
|
1157
|
+
POOL_COMMITMENT="${1:?Usage: fund-pool <pool_commitment>}"
|
|
1158
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1159
|
+
|
|
1160
|
+
FUNDER_NONCE=$(generate_nonce)
|
|
1161
|
+
FUNDER_NULLIFIER=$(domain_hash "nightpay-funder-v1" "$FUNDER_NONCE")
|
|
1162
|
+
FUNDING_RECORD=$(domain_hash "nightpay-funding-v1" "$FUNDER_NULLIFIER:$POOL_COMMITMENT:$FUNDER_NONCE")
|
|
1163
|
+
|
|
1164
|
+
# If bridge is available, submit fundPool circuit call
|
|
1165
|
+
if [[ -n "$BRIDGE_URL" ]]; then
|
|
1166
|
+
bridge_post "/fundPool" "{\"funderNullifier\":\"$FUNDER_NULLIFIER\",\"poolCommitment\":\"$POOL_COMMITMENT\",\"nonce\":\"$FUNDER_NONCE\"}" 2>/dev/null || true
|
|
1167
|
+
fi
|
|
1168
|
+
|
|
1169
|
+
# PRIVACY: store credentials encrypted via OpenShart if available.
|
|
1170
|
+
# These are the keys to emergency refunds — they should NEVER sit in
|
|
1171
|
+
# plaintext conversation history or agent logs.
|
|
1172
|
+
CREDENTIAL_JSON="{\"poolCommitment\":\"$POOL_COMMITMENT\",\"fundingRecord\":\"$FUNDING_RECORD\",\"funderNullifier\":\"$FUNDER_NULLIFIER\",\"nonce\":\"$FUNDER_NONCE\",\"fundedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"}"
|
|
1173
|
+
MEMORY_ID=""
|
|
1174
|
+
if MEMORY_ID=$(_shart_store "$CREDENTIAL_JSON" "nightpay,funding,$POOL_COMMITMENT" "CONFIDENTIAL"); then
|
|
1175
|
+
# Encrypted storage succeeded — return memory_id instead of raw secrets
|
|
1176
|
+
python3 -c "
|
|
1177
|
+
import sys, json
|
|
1178
|
+
print(json.dumps({
|
|
1179
|
+
'poolCommitment': sys.argv[1],
|
|
1180
|
+
'fundingRecord': sys.argv[2],
|
|
1181
|
+
'status': 'funded',
|
|
1182
|
+
'credentialStorage': 'encrypted',
|
|
1183
|
+
'memoryId': sys.argv[3],
|
|
1184
|
+
'note': 'Credentials stored encrypted via OpenShart. Use memoryId to recall them for refunds.'
|
|
1185
|
+
}, indent=2))
|
|
1186
|
+
" "$POOL_COMMITMENT" "$FUNDING_RECORD" "$MEMORY_ID"
|
|
1187
|
+
else
|
|
1188
|
+
# Fallback: no OpenShart — print raw credentials with warning
|
|
1189
|
+
python3 -c "
|
|
1190
|
+
import sys, json
|
|
1191
|
+
print(json.dumps({
|
|
1192
|
+
'poolCommitment': sys.argv[1],
|
|
1193
|
+
'fundingRecord': sys.argv[2],
|
|
1194
|
+
'funderNullifier': sys.argv[3],
|
|
1195
|
+
'nonce': sys.argv[4],
|
|
1196
|
+
'status': 'funded',
|
|
1197
|
+
'credentialStorage': 'plaintext',
|
|
1198
|
+
'WARNING': 'OpenShart not available — credentials are in PLAINTEXT. Install openshart for encrypted storage.',
|
|
1199
|
+
'note': 'SAVE these values securely — you need funderNullifier + nonce to claim a refund if the pool expires'
|
|
1200
|
+
}, indent=2))
|
|
1201
|
+
" "$POOL_COMMITMENT" "$FUNDING_RECORD" "$FUNDER_NULLIFIER" "$FUNDER_NONCE"
|
|
1202
|
+
fi
|
|
1203
|
+
;;
|
|
1204
|
+
|
|
1205
|
+
pool-status)
|
|
1206
|
+
POOL_COMMITMENT="${1:?Usage: pool-status <pool_commitment>}"
|
|
1207
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1208
|
+
|
|
1209
|
+
if [[ -n "$BRIDGE_URL" ]]; then
|
|
1210
|
+
bridge_get "/poolStatus/$POOL_COMMITMENT" && exit 0
|
|
1211
|
+
echo " WARNING: Bridge unavailable — showing placeholder" >&2
|
|
1212
|
+
fi
|
|
1213
|
+
|
|
1214
|
+
python3 -c "
|
|
1215
|
+
import sys, json
|
|
1216
|
+
print(json.dumps({
|
|
1217
|
+
'poolCommitment': sys.argv[1],
|
|
1218
|
+
'query': 'poolStatus',
|
|
1219
|
+
'note': 'Set BRIDGE_URL to get live on-chain pool status'
|
|
1220
|
+
}, indent=2))
|
|
1221
|
+
" "$POOL_COMMITMENT"
|
|
1222
|
+
;;
|
|
1223
|
+
|
|
1224
|
+
activate-pool)
|
|
1225
|
+
POOL_COMMITMENT="${1:?Usage: activate-pool <pool_commitment>}"
|
|
1226
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1227
|
+
|
|
1228
|
+
if [[ -n "$BRIDGE_URL" ]]; then
|
|
1229
|
+
bridge_post "/activatePool" "{\"poolCommitment\":\"$POOL_COMMITMENT\"}" 2>/dev/null || true
|
|
1230
|
+
fi
|
|
1231
|
+
|
|
1232
|
+
# Update board status
|
|
1233
|
+
bash "$(dirname "$0")/bounty-board.sh" remove "$POOL_COMMITMENT" "completed" 2>/dev/null || true
|
|
1234
|
+
|
|
1235
|
+
python3 -c "
|
|
1236
|
+
import sys, json
|
|
1237
|
+
print(json.dumps({
|
|
1238
|
+
'poolCommitment': sys.argv[1],
|
|
1239
|
+
'status': 'activated',
|
|
1240
|
+
'note': 'Pool goal met — funds released to gateway for Masumi escrow. Find an agent next.'
|
|
1241
|
+
}, indent=2))
|
|
1242
|
+
" "$POOL_COMMITMENT"
|
|
1243
|
+
;;
|
|
1244
|
+
|
|
1245
|
+
expire-pool)
|
|
1246
|
+
POOL_COMMITMENT="${1:?Usage: expire-pool <pool_commitment>}"
|
|
1247
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1248
|
+
|
|
1249
|
+
if [[ -n "$BRIDGE_URL" ]]; then
|
|
1250
|
+
bridge_post "/expirePool" "{\"poolCommitment\":\"$POOL_COMMITMENT\"}" 2>/dev/null || true
|
|
1251
|
+
fi
|
|
1252
|
+
|
|
1253
|
+
# Update board status
|
|
1254
|
+
bash "$(dirname "$0")/bounty-board.sh" remove "$POOL_COMMITMENT" "expired" 2>/dev/null || true
|
|
1255
|
+
|
|
1256
|
+
python3 -c "
|
|
1257
|
+
import sys, json
|
|
1258
|
+
print(json.dumps({
|
|
1259
|
+
'poolCommitment': sys.argv[1],
|
|
1260
|
+
'status': 'expired',
|
|
1261
|
+
'note': 'Pool expired — funders can now call claim-refund to reclaim their NIGHT'
|
|
1262
|
+
}, indent=2))
|
|
1263
|
+
" "$POOL_COMMITMENT"
|
|
1264
|
+
;;
|
|
1265
|
+
|
|
1266
|
+
claim-refund)
|
|
1267
|
+
# Accepts either:
|
|
1268
|
+
# claim-refund <pool_commitment> <funder_nullifier> (manual)
|
|
1269
|
+
# claim-refund --memory-id <openshart_memory_id> (auto-recall from encrypted storage)
|
|
1270
|
+
if [[ "${1:-}" == "--memory-id" ]]; then
|
|
1271
|
+
MEMORY_ID="${2:?Usage: claim-refund --memory-id <openshart_memory_id>}"
|
|
1272
|
+
RECALLED=$(_shart_recall "$MEMORY_ID") || { echo "ERROR: Could not recall credentials from OpenShart memory $MEMORY_ID" >&2; exit 1; }
|
|
1273
|
+
POOL_COMMITMENT=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['poolCommitment'])")
|
|
1274
|
+
FUNDER_NULLIFIER=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['funderNullifier'])")
|
|
1275
|
+
else
|
|
1276
|
+
POOL_COMMITMENT="${1:?Usage: claim-refund <pool_commitment> <funder_nullifier> OR claim-refund --memory-id <id>}"
|
|
1277
|
+
FUNDER_NULLIFIER="${2:?Usage: claim-refund <pool_commitment> <funder_nullifier>}"
|
|
1278
|
+
fi
|
|
1279
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1280
|
+
|
|
1281
|
+
if [[ -n "$BRIDGE_URL" ]]; then
|
|
1282
|
+
bridge_post "/claimRefund" "{\"poolCommitment\":\"$POOL_COMMITMENT\",\"funderNullifier\":\"$FUNDER_NULLIFIER\"}" 2>/dev/null || true
|
|
1283
|
+
fi
|
|
1284
|
+
|
|
1285
|
+
python3 -c "
|
|
1286
|
+
import sys, json
|
|
1287
|
+
print(json.dumps({
|
|
1288
|
+
'poolCommitment': sys.argv[1],
|
|
1289
|
+
'funderNullifier': sys.argv[2],
|
|
1290
|
+
'status': 'refunded',
|
|
1291
|
+
'note': 'Full contribution returned — no fee charged on expired pools'
|
|
1292
|
+
}, indent=2))
|
|
1293
|
+
" "$POOL_COMMITMENT" "$FUNDER_NULLIFIER"
|
|
1294
|
+
;;
|
|
1295
|
+
|
|
1296
|
+
emergency-refund)
|
|
1297
|
+
# FAILSAFE: bypass the gateway entirely. Submits emergencyRefund circuit call
|
|
1298
|
+
# directly to the Midnight contract. No bridge needed.
|
|
1299
|
+
# Accepts either:
|
|
1300
|
+
# emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>
|
|
1301
|
+
# emergency-refund --memory-id <openshart_memory_id> <contribution_specks> <funded_at_tx>
|
|
1302
|
+
if [[ "${1:-}" == "--memory-id" ]]; then
|
|
1303
|
+
MEMORY_ID="${2:?Usage: emergency-refund --memory-id <id> <contribution_specks> <funded_at_tx>}"
|
|
1304
|
+
CONTRIBUTION_SPECKS="${3:?Usage: emergency-refund --memory-id <id> <contribution_specks> <funded_at_tx>}"
|
|
1305
|
+
FUNDED_AT_TX="${4:?Usage: emergency-refund --memory-id <id> <contribution_specks> <funded_at_tx>}"
|
|
1306
|
+
RECALLED=$(_shart_recall "$MEMORY_ID") || { echo "ERROR: Could not recall credentials from OpenShart memory $MEMORY_ID" >&2; exit 1; }
|
|
1307
|
+
POOL_COMMITMENT=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['poolCommitment'])")
|
|
1308
|
+
FUNDER_NULLIFIER=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['funderNullifier'])")
|
|
1309
|
+
NONCE=$(echo "$RECALLED" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['nonce'])")
|
|
1310
|
+
else
|
|
1311
|
+
POOL_COMMITMENT="${1:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
|
|
1312
|
+
FUNDER_NULLIFIER="${2:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
|
|
1313
|
+
CONTRIBUTION_SPECKS="${3:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
|
|
1314
|
+
FUNDED_AT_TX="${4:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
|
|
1315
|
+
NONCE="${5:?Usage: emergency-refund <pool_commitment> <funder_nullifier> <contribution_specks> <funded_at_tx> <nonce>}"
|
|
1316
|
+
fi
|
|
1317
|
+
validate_commitment "$POOL_COMMITMENT"
|
|
1318
|
+
|
|
1319
|
+
[[ "$CONTRIBUTION_SPECKS" =~ ^[0-9]+$ ]] || die "contribution_specks must be a positive integer"
|
|
1320
|
+
[[ "$FUNDED_AT_TX" =~ ^[0-9]+$ ]] || die "funded_at_tx must be a non-negative integer"
|
|
1321
|
+
|
|
1322
|
+
python3 -c "
|
|
1323
|
+
import sys, json
|
|
1324
|
+
print(json.dumps({
|
|
1325
|
+
'poolCommitment': sys.argv[1],
|
|
1326
|
+
'funderNullifier': sys.argv[2],
|
|
1327
|
+
'contributionSpecks': int(sys.argv[3]),
|
|
1328
|
+
'fundedAtTx': int(sys.argv[4]),
|
|
1329
|
+
'nonce': sys.argv[5],
|
|
1330
|
+
'status': 'emergency_refund',
|
|
1331
|
+
'emergencyPath': True,
|
|
1332
|
+
'note': 'Submit this payload directly to the Midnight contract emergencyRefund() circuit — no bridge/gateway needed'
|
|
1333
|
+
}, indent=2))
|
|
1334
|
+
" "$POOL_COMMITMENT" "$FUNDER_NULLIFIER" "$CONTRIBUTION_SPECKS" "$FUNDED_AT_TX" "$NONCE"
|
|
1335
|
+
;;
|
|
1336
|
+
|
|
1337
|
+
refund-unclaimed)
|
|
1338
|
+
# Refund jobs that were never claimed and exceeded UNCLAIMED_REFUND_HOURS.
|
|
1339
|
+
# Safety conditions:
|
|
1340
|
+
# - status == running
|
|
1341
|
+
# - claims_count == 0 and assigned_agent_id empty
|
|
1342
|
+
# - started_at older than threshold
|
|
1343
|
+
# - commitmentHash present in input_data
|
|
1344
|
+
DRY_RUN=0
|
|
1345
|
+
[[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1
|
|
1346
|
+
MIP003_URL="http://localhost:${MIP003_PORT}"
|
|
1347
|
+
echo -e "${CYAN}Scanning for unclaimed refunds${RESET} ${DIM}(age=${UNCLAIMED_REFUND_HOURS}h, url=${MIP003_URL}, pageSize=${UNCLAIMED_SWEEP_PAGE_SIZE})${RESET}..." >&2
|
|
1348
|
+
|
|
1349
|
+
python3 -c "
|
|
1350
|
+
import json, subprocess, sys, urllib.request, urllib.error
|
|
1351
|
+
from datetime import datetime, timezone, timedelta
|
|
1352
|
+
|
|
1353
|
+
mip_url = sys.argv[1]
|
|
1354
|
+
gateway = sys.argv[2]
|
|
1355
|
+
dry_run = sys.argv[3] == '1'
|
|
1356
|
+
hours = float(sys.argv[4])
|
|
1357
|
+
page_size = int(sys.argv[5])
|
|
1358
|
+
operator_secret = sys.argv[6]
|
|
1359
|
+
|
|
1360
|
+
if page_size < 1:
|
|
1361
|
+
page_size = 1
|
|
1362
|
+
if page_size > 500:
|
|
1363
|
+
page_size = 500
|
|
1364
|
+
|
|
1365
|
+
threshold = datetime.now(timezone.utc) - timedelta(hours=hours)
|
|
1366
|
+
offset = 0
|
|
1367
|
+
scanned = 0
|
|
1368
|
+
candidates = 0
|
|
1369
|
+
done = 0
|
|
1370
|
+
errors = 0
|
|
1371
|
+
|
|
1372
|
+
def parse_iso(v):
|
|
1373
|
+
if not v:
|
|
1374
|
+
return None
|
|
1375
|
+
try:
|
|
1376
|
+
return datetime.fromisoformat(str(v).replace('Z', '+00:00'))
|
|
1377
|
+
except Exception:
|
|
1378
|
+
return None
|
|
1379
|
+
|
|
1380
|
+
while True:
|
|
1381
|
+
url = f'{mip_url}/jobs?status=running&visibility=all&limit={page_size}&offset={offset}'
|
|
1382
|
+
headers = {}
|
|
1383
|
+
if operator_secret:
|
|
1384
|
+
headers['Authorization'] = f'Bearer {operator_secret}'
|
|
1385
|
+
try:
|
|
1386
|
+
req = urllib.request.Request(url, headers=headers)
|
|
1387
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
1388
|
+
data = json.loads(r.read().decode())
|
|
1389
|
+
except Exception as e:
|
|
1390
|
+
print(f'ERROR: failed to query jobs page offset={offset}: {e}', file=sys.stderr)
|
|
1391
|
+
sys.exit(1)
|
|
1392
|
+
|
|
1393
|
+
jobs = data.get('jobs', [])
|
|
1394
|
+
if not isinstance(jobs, list):
|
|
1395
|
+
print('ERROR: unexpected /jobs response format', file=sys.stderr)
|
|
1396
|
+
sys.exit(1)
|
|
1397
|
+
|
|
1398
|
+
for job in jobs:
|
|
1399
|
+
scanned += 1
|
|
1400
|
+
jid = job.get('job_id', '')
|
|
1401
|
+
claims = int(job.get('claims_count') or 0)
|
|
1402
|
+
assigned = job.get('assigned_agent_id')
|
|
1403
|
+
started_at = parse_iso(job.get('started_at'))
|
|
1404
|
+
input_data = job.get('input_data') or {}
|
|
1405
|
+
|
|
1406
|
+
if claims > 0 or assigned:
|
|
1407
|
+
continue
|
|
1408
|
+
if not started_at or started_at > threshold:
|
|
1409
|
+
continue
|
|
1410
|
+
if isinstance(input_data, str):
|
|
1411
|
+
try:
|
|
1412
|
+
input_data = json.loads(input_data)
|
|
1413
|
+
except Exception:
|
|
1414
|
+
input_data = {}
|
|
1415
|
+
if not isinstance(input_data, dict):
|
|
1416
|
+
input_data = {}
|
|
1417
|
+
|
|
1418
|
+
commit = str(input_data.get('commitmentHash') or '')
|
|
1419
|
+
refund_addr = str(input_data.get('refundAddress') or input_data.get('funderAddress') or '')
|
|
1420
|
+
if len(commit) != 64 or any(c not in '0123456789abcdef' for c in commit):
|
|
1421
|
+
print(f'SKIP {jid}: missing/invalid commitmentHash for refund', file=sys.stderr)
|
|
1422
|
+
errors += 1
|
|
1423
|
+
continue
|
|
1424
|
+
|
|
1425
|
+
candidates += 1
|
|
1426
|
+
if dry_run:
|
|
1427
|
+
addr_hint = refund_addr[:12] + '...' if refund_addr else 'unknown'
|
|
1428
|
+
print(f'DRY-RUN: would refund job_id={jid} commitment={commit[:16]}... refundAddress={addr_hint}')
|
|
1429
|
+
done += 1
|
|
1430
|
+
continue
|
|
1431
|
+
|
|
1432
|
+
cmd = ['/usr/bin/env', 'bash', gateway, 'refund', jid, commit]
|
|
1433
|
+
if len(refund_addr) == 64 and all(c in '0123456789abcdef' for c in refund_addr):
|
|
1434
|
+
cmd.append(refund_addr)
|
|
1435
|
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
1436
|
+
if result.returncode == 0:
|
|
1437
|
+
print(f'AUTO-REFUND OK: {jid}')
|
|
1438
|
+
done += 1
|
|
1439
|
+
else:
|
|
1440
|
+
print(f'AUTO-REFUND FAILED: {jid} — {result.stderr.strip()}', file=sys.stderr)
|
|
1441
|
+
errors += 1
|
|
1442
|
+
|
|
1443
|
+
has_more = bool(data.get('has_more'))
|
|
1444
|
+
count = int(data.get('count') or 0)
|
|
1445
|
+
if not has_more or count == 0:
|
|
1446
|
+
break
|
|
1447
|
+
offset += page_size
|
|
1448
|
+
|
|
1449
|
+
print(f'Unclaimed refund sweep: scanned={scanned}, candidates={candidates}, refunded={done}, errors={errors}.', file=sys.stderr)
|
|
1450
|
+
" "$MIP003_URL" "$0" "$DRY_RUN" "$UNCLAIMED_REFUND_HOURS" "$UNCLAIMED_SWEEP_PAGE_SIZE" "${OPERATOR_SECRET_KEY:-}"
|
|
1451
|
+
;;
|
|
1452
|
+
|
|
574
1453
|
*)
|
|
575
|
-
echo
|
|
1454
|
+
echo -e "${BOLD}nightpay gateway${RESET} — anonymous bounty lifecycle CLI" >&2
|
|
1455
|
+
echo "" >&2
|
|
1456
|
+
echo -e "${BOLD}Commands:${RESET}" >&2
|
|
1457
|
+
echo -e " ${CYAN}post-bounty${RESET} <desc> <amount> Fund a bounty anonymously" >&2
|
|
1458
|
+
echo -e " ${CYAN}find-agent${RESET} <query> Search Masumi for agents" >&2
|
|
1459
|
+
echo -e " ${CYAN}agent-showcase${RESET} [query] List profile showcase agents by credibility" >&2
|
|
1460
|
+
echo -e " ${CYAN}hire-and-pay${RESET} <agent> <desc> <hash> Create escrow, start job" >&2
|
|
1461
|
+
echo -e " ${CYAN}hire-direct${RESET} <agent> <desc> <amount> Create hidden direct-hire job" >&2
|
|
1462
|
+
echo -e " ${CYAN}check-job${RESET} <job_id> Poll job status" >&2
|
|
1463
|
+
echo -e " ${CYAN}complete${RESET} <job_id> <hash> Mint receipt, release payment" >&2
|
|
1464
|
+
echo -e " ${CYAN}refund${RESET} <job_id> <hash> [addr] Cancel escrow, refund NIGHT" >&2
|
|
1465
|
+
echo -e " ${CYAN}refund-unclaimed${RESET} [--dry-run] Auto-refund old unclaimed jobs" >&2
|
|
1466
|
+
echo -e " ${CYAN}approve-multisig${RESET} <id> <hash> <key> Sign high-value approval" >&2
|
|
1467
|
+
echo -e " ${CYAN}optimistic-sweep${RESET} [--dry-run] Auto-complete expired windows" >&2
|
|
1468
|
+
echo -e " ${CYAN}withdraw-fees${RESET} [amount] Operator fee withdrawal" >&2
|
|
1469
|
+
echo -e " ${CYAN}stats${RESET} On-chain contract stats" >&2
|
|
1470
|
+
echo "" >&2
|
|
1471
|
+
echo -e "${DIM}Required: MASUMI_API_KEY MIDNIGHT_NETWORK OPERATOR_ADDRESS RECEIPT_CONTRACT_ADDRESS${RESET}" >&2
|
|
576
1472
|
exit 1
|
|
577
1473
|
;;
|
|
578
1474
|
esac
|