-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmetadata-validate.sh
More file actions
executable file
·687 lines (620 loc) · 28.2 KB
/
Copy pathmetadata-validate.sh
File metadata and controls
executable file
·687 lines (620 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/messages.sh
source "$SCRIPT_DIR/lib/messages.sh"
WHITE=$'\033[1;37m'
[ -z "${NC}" ] && WHITE=''
##################################################
# Default schema URLs
CIP_100_SCHEMA="https://raw.githubusercontent.com/cardano-foundation/CIPs/refs/heads/master/CIP-0100/cip-0100.common.schema.json"
CIP_108_SCHEMA="https://raw.githubusercontent.com/cardano-foundation/CIPs/refs/heads/master/CIP-0108/cip-0108.common.schema.json"
CIP_119_SCHEMA="https://raw.githubusercontent.com/cardano-foundation/CIPs/refs/heads/master/CIP-0119/cip-0119.common.schema.json"
CIP_136_SCHEMA="https://raw.githubusercontent.com/cardano-foundation/CIPs/refs/heads/master/CIP-0136/cip-136.common.schema.json"
# temp, until CIP-169 is merged
CIP_169_SCHEMA="https://raw.githubusercontent.com/Ryun1/CIPs/refs/heads/cip-governance-metadata-extension/CIP-0169/cip-0169.common.schema.json"
CIP_116_CONWAY_SCHEMA="https://raw.githubusercontent.com/cardano-foundation/CIPs/refs/heads/master/CIP-0116/cardano-conway.json"
INTERSECT_TREASURY_SCHEMA="https://intersectmbo.github.io/governance-actions/v1.2.0/schemas/treasury-withdrawals/common.schema.json"
INTERSECT_INFO_SCHEMA="https://intersectmbo.github.io/governance-actions/v1.2.0/schemas/info/common.schema.json"
INTERSECT_PPU_SCHEMA="https://intersectmbo.github.io/governance-actions/v1.2.0/schemas/parameter-changes/common.schema.json"
INTERSECT_HFI_SCHEMA="https://intersectmbo.github.io/governance-actions/v1.2.0/schemas/hard-fork-initiation/common.schema.json"
INTERSECT_UC_SCHEMA="https://intersectmbo.github.io/governance-actions/v1.2.0/schemas/update-committee/common.schema.json"
# Default aspell dictionary (fetched at runtime so users don't need a local copy)
CARDANO_ASPELL_DICT_URL="https://raw.githubusercontent.com/IntersectMBO/governance-scripts/refs/heads/main/scripts/cardano-aspell-dict.txt"
# Default schema values
DEFAULT_USE_CIP_100="false"
DEFAULT_USE_CIP_108="false"
DEFAULT_USE_CIP_119="false"
DEFAULT_USE_CIP_136="false"
DEFAULT_USE_CIP_169="false"
DEFAULT_USE_INTERSECT="false"
DEFAULT_USE_JSONLD_CHECK="true"
##################################################
# Check if cardano-signer is installed
if ! command -v cardano-signer >/dev/null 2>&1; then
print_fail "cardano-signer is not installed or not in your PATH."
exit 1
fi
# Check if ajv is installed
if ! command -v ajv >/dev/null 2>&1; then
print_fail "ajv is not installed or not in your PATH."
exit 1
fi
set -euo pipefail
# Global variables for cleanup
TMP_JSON_FILE=""
TMP_SCHEMAS_DIR="/tmp/schemas"
TMP_DICT_FILE=""
# Cleanup function
cleanup() {
# Clean up temporary JSON file if it exists
if [ -n "$TMP_JSON_FILE" ] && [ -f "$TMP_JSON_FILE" ]; then
rm -f "$TMP_JSON_FILE" 2>/dev/null || true
fi
# Clean up temporary schemas directory if it exists
if [ -d "$TMP_SCHEMAS_DIR" ]; then
rm -rf "$TMP_SCHEMAS_DIR" 2>/dev/null || true
fi
# Clean up downloaded aspell dictionary
if [ -n "$TMP_DICT_FILE" ] && [ -f "$TMP_DICT_FILE" ]; then
rm -f "$TMP_DICT_FILE" 2>/dev/null || true
fi
}
# Set up trap to ensure cleanup on exit
trap cleanup EXIT INT TERM
# Usage message
usage() {
printf '%s%sValidate a JSON-LD metadata file%s\n\n' "$UNDERLINE" "$BOLD" "$NC"
printf 'Syntax:%s %s %s<jsonld-file>%s [%s--cip169%s] [%s--cip108%s] [%s--cip100%s] [%s--cip136%s] [%s--intersect-schema%s] [%s--schema%s URL] [%s--no-spell-check%s] [%s--no-link-check%s] [%s--no-jsonld-check%s] [%s--draft%s]\n' \
"$BOLD" "$0" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC" "$GREEN" "$NC"
print_usage_option "<jsonld-file>" "Path to the JSON-LD metadata file"
print_usage_option "[--cip100]" "Compare against CIP-100 schema (default: $DEFAULT_USE_CIP_100)"
print_usage_option "[--cip108]" "Compare against CIP-108 Governance actions schema (default: $DEFAULT_USE_CIP_108)"
print_usage_option "[--cip119]" "Compare against CIP-119 DRep schema (default: $DEFAULT_USE_CIP_119)"
print_usage_option "[--cip136]" "Compare against CIP-136 CC vote schema (default: $DEFAULT_USE_CIP_136)"
print_usage_option "[--cip169]" "Compare against CIP-169 Governance metadata schema (default: $DEFAULT_USE_CIP_169, includes CIP-116)"
print_usage_option "[--intersect-schema]" "Compare against Intersect governance action schemas (default: $DEFAULT_USE_INTERSECT)"
print_usage_option "[--schema URL]" "Compare against schema at URL"
print_usage_option "[--no-spell-check]" "Skip aspell-based spell check on body.title/abstract/motivation/rationale (default: enabled; dictionary fetched from IntersectMBO/governance-scripts main)"
print_usage_option "[--no-link-check]" "Skip URI reachability check on body URIs and prose markdown links (default: enabled; IPFS gateway via \$IPFS_GATEWAY_URI, falls back to https://ipfs.io)"
print_usage_option "[--no-jsonld-check]" "Skip JSON-LD safe-mode expansion check (default: enabled; needs node + 'jsonld' npm package)"
print_usage_option "[--draft]" "Treat the file as a pre-signing draft: downgrade the empty-authors check to a warning instead of an error."
print_usage_option "-h, --help" "Show this help message and exit"
exit 1
}
# Initialize variables with defaults
input_file=""
use_cip_108="$DEFAULT_USE_CIP_108"
use_cip_100="$DEFAULT_USE_CIP_100"
use_cip_119="$DEFAULT_USE_CIP_119"
use_cip_136="$DEFAULT_USE_CIP_136"
use_cip_169="$DEFAULT_USE_CIP_169"
use_intersect_schema="$DEFAULT_USE_INTERSECT"
user_schema_url=""
user_schema="false"
check_links="true"
check_spelling="true"
check_jsonld="$DEFAULT_USE_JSONLD_CHECK"
is_draft="false"
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--cip108|--cip-108)
use_cip_108="true"
shift
;;
--cip100|--cip-100)
use_cip_100="true"
shift
;;
--cip119|--cip-119)
use_cip_119="true"
shift
;;
--cip136|--cip-136)
use_cip_136="true"
shift
;;
--cip169|--cip-169)
use_cip_169="true"
shift
;;
--intersect-schema)
use_intersect_schema="true"
shift
;;
--schema)
user_schema_url="$2"
user_schema="true"
shift 2
;;
--no-link-check)
check_links="false"
shift
;;
--no-spell-check)
check_spelling="false"
shift
;;
--no-jsonld-check)
check_jsonld="false"
shift
;;
--draft)
is_draft="true"
shift
;;
-h|--help)
usage
;;
*)
if [ -z "$input_file" ]; then
input_file="$1"
fi
shift
;;
esac
done
# Require at least one schema source. Without it the downstream "no schemas downloaded"
# branch would fail anyway, but that happens after length/spell/URI checks run pointlessly.
if [ "$use_cip_100" = "false" ] && [ "$use_cip_108" = "false" ] && \
[ "$use_cip_119" = "false" ] && [ "$use_cip_136" = "false" ] && \
[ "$use_cip_169" = "false" ] && [ "$use_intersect_schema" = "false" ] && \
[ "$user_schema" = "false" ]; then
print_fail "At least one schema flag is required."
print_hint "Pass one or more of: --cip100 / --cip108 / --cip119 / --cip136 / --cip169, or --intersect-schema, or --schema <URL>"
usage
fi
# Welcome message
print_banner "Governance Metadata Validation Script"
print_info "This script validates JSON-LD governance metadata files against CIP standards and or Intersect schemas"
# If the file ends with .jsonld, create a temporary .json copy (overwrite if exists)
if [[ "$input_file" == *.jsonld ]]; then
if [ ! -f "$input_file" ]; then
print_fail "File $(fmt_path "$input_file") does not exist."
usage
exit 1
fi
TMP_JSON_FILE="/tmp/metadata.json"
cp -f "$input_file" "$TMP_JSON_FILE"
JSON_FILE="$TMP_JSON_FILE"
else
JSON_FILE="$input_file"
fi
# Check if the file exists
if [ ! -f "$JSON_FILE" ]; then
print_fail "File $(fmt_path "$JSON_FILE") does not exist."
usage
exit 1
fi
# Check if the file is valid JSON
if ! jq empty "$JSON_FILE" >/dev/null 2>&1; then
print_fail "$(fmt_path "$JSON_FILE") is not valid JSON."
exit 1
fi
# Length checks for title (max 80) and abstract (max 2500) — only for fields that are present
LENGTH_CHECK_FAILED=0
LENGTH_CHECK_HEADER_SHOWN=0
check_length() {
local field="$1"
local max="$2"
local text len
text=$(jq -r ".body.$field // empty" "$JSON_FILE")
if [ -z "$text" ]; then
return
fi
if [ "$LENGTH_CHECK_HEADER_SHOWN" -eq 0 ]; then
print_section "Checking field length limits"
LENGTH_CHECK_HEADER_SHOWN=1
fi
len=${#text}
if [ "$len" -gt "$max" ]; then
print_fail "'$field' is $len chars, exceeds max of $max."
LENGTH_CHECK_FAILED=1
else
print_pass "'$field' length: ${len} / ${max}"
fi
}
check_length title 80
check_length abstract 2500
if [ "$LENGTH_CHECK_FAILED" -ne 0 ]; then
exit 1
fi
# Content sanity checks (warnings only) on CIP-108 prose fields:
# - leading or trailing whitespace
# - very long markdown headings
# - nested CIP-108 field-name headings (e.g. "### abstract" inside the abstract body)
print_section "Checking content sanity"
CONTENT_WARN_COUNT=0
PROSE_FIELDS=(title abstract motivation rationale)
HEADING_LEN_MAX=80
for field in "${PROSE_FIELDS[@]}"; do
text=$(jq -r ".body.$field // empty" "$JSON_FILE")
[ -z "$text" ] && continue
if [[ "$text" =~ ^[[:space:]] ]]; then
print_warn "'$field' has leading whitespace."
CONTENT_WARN_COUNT=$((CONTENT_WARN_COUNT+1))
fi
if [[ "$text" =~ [[:space:]]$ ]]; then
print_warn "'$field' has trailing whitespace."
CONTENT_WARN_COUNT=$((CONTENT_WARN_COUNT+1))
fi
# Very long ATX-style headings (line-start only — that's what real markdown headings are).
while IFS= read -r heading_line; do
heading_text=$(printf '%s' "$heading_line" | tr -d '\r' \
| sed -E 's/^[[:space:]]{0,3}#+[[:space:]]*//; s/[[:space:]]+#+[[:space:]]*$//')
[ -z "$heading_text" ] && continue
len=${#heading_text}
if [ "$len" -gt "$HEADING_LEN_MAX" ]; then
print_warn "'$field' has a markdown heading of $len chars (>$HEADING_LEN_MAX): \"$heading_text\""
CONTENT_WARN_COUNT=$((CONTENT_WARN_COUNT+1))
fi
done < <(printf '%s\n' "$text" | grep -E '^[[:space:]]{0,3}#+[[:space:]]+' || true)
# Nested CIP-108 field-name reuse: '### abstract', '## motivation', etc., anywhere in
# the text — line-start OR mid-string. Mid-string matches because writers paste
# heading-style markers inline (e.g. "My amazing ### motivation") and that's still a
# field-name reuse worth flagging.
for nested in "${PROSE_FIELDS[@]}"; do
if printf '%s\n' "$text" | grep -qiE "(^|[^[:alnum:]_#])#{1,6}[[:space:]]+${nested}([^[:alnum:]_]|\$)"; then
print_warn "'$field' contains nested CIP-108 field heading marker for '$nested' (e.g. '### $nested'). Field content shouldn't redeclare a CIP-108 field name as a heading."
CONTENT_WARN_COUNT=$((CONTENT_WARN_COUNT+1))
fi
done
done
if [ "$CONTENT_WARN_COUNT" -eq 0 ]; then
print_pass "No content sanity warnings."
fi
# Basic spell check on key data fields (requires 'aspell' installed)
if [ "$check_spelling" = "true" ]; then
print_section "Applying spell check"
# Fetch the upstream Intersect dictionary so users don't need a local copy
print_info "Fetching Cardano aspell dictionary from ${YELLOW}${CARDANO_ASPELL_DICT_URL}${NC}"
TMP_DICT_FILE=$(mktemp /tmp/cardano-aspell-dict.XXXXXX)
if ! curl --silent --show-error --fail --location --max-time 10 \
-o "$TMP_DICT_FILE" "$CARDANO_ASPELL_DICT_URL"; then
print_fail "Failed to download aspell dictionary from $CARDANO_ASPELL_DICT_URL."
print_hint "Pass --no-spell-check to skip the spell check, or retry when online."
exit 1
fi
PERSONAL_DICT_ARG="--personal=$TMP_DICT_FILE"
# This hardcoded for CIP108
# todo fix for other schemas
SPELL_OUTPUT=""
for field in title abstract motivation rationale; do
text=$(jq -r ".body.$field // empty" "$JSON_FILE")
if [ -n "$text" ]; then
while IFS= read -r word; do
[ -n "$word" ] && SPELL_OUTPUT+=" ${BLUE}'$field': ${YELLOW}$word${NC}"$'\n'
done < <(echo "$text" | aspell list $PERSONAL_DICT_ARG | sort -u)
fi
done
if [ -n "$SPELL_OUTPUT" ]; then
print_warn "Possible misspellings:"
printf '%b' "$SPELL_OUTPUT"
else
print_pass "No misspellings found."
fi
fi
# URI reachability check — every URI (structured + markdown-embedded in prose fields)
# is HEAD-checked (with GET fallback). Duplicates are intentionally re-checked.
# Skip with --no-link-check. IPFS gateway from $IPFS_GATEWAY_URI or https://ipfs.io.
URI_CHECK_FAILED=0
if [ "$check_links" = "true" ]; then
print_section "Checking URI reachability"
IPFS_GATEWAY="${IPFS_GATEWAY_URI:-https://ipfs.io}"
IPFS_GATEWAY="${IPFS_GATEWAY%/}"
uris=()
# 1. Structured URIs anywhere under .body with a key named uri/url (case-insensitive)
while IFS= read -r u; do
[ -n "$u" ] && uris+=("$u")
done < <(jq -r '
.body
| [.. | objects | to_entries[]
| select((.key | ascii_downcase) == "uri" or (.key | ascii_downcase) == "url")
| .value | select(type == "string")]
| .[]
' "$JSON_FILE")
# 2. Markdown-embedded / bare URLs in prose fields
for field in title abstract motivation rationale; do
text=$(jq -r ".body.$field // empty" "$JSON_FILE")
if [ -n "$text" ]; then
while IFS= read -r u; do
[ -n "$u" ] && uris+=("$u")
done < <(printf '%s' "$text" | perl -0777 -ne '
while (/\[[^\]]*\]\((https?:\/\/[^)\s]+|ipfs:\/\/[^)\s]+)\)/g) { print "$1\n" }
while (/<(https?:\/\/[^>\s]+|ipfs:\/\/[^>\s]+)>/g) { print "$1\n" }
while (/(?<![\w\/:])(https?:\/\/[^\s)\]<>"'"'"'\\]+)/g) { print "$1\n" }
while (/(?<![\w\/:])(ipfs:\/\/[A-Za-z0-9\/._\-]+)/g) { print "$1\n" }
')
fi
done
total_count=${#uris[@]}
failed_count=0
if [ "$total_count" -eq 0 ]; then
print_warn "No URIs found to check."
else
for raw_uri in "${uris[@]}"; do
# Trim trailing punctuation that regex may have grabbed
uri="$raw_uri"
while :; do
case "$uri" in
*.|*,|*\;|*\!|*\?|*\)|*\]|*\>|*\"|*\'|*\`) uri="${uri%?}" ;;
*) break ;;
esac
done
# Skip non-HTTP(S)/IPFS and fragment-only
case "$uri" in
mailto:*|tel:*) continue ;;
\#*) continue ;;
esac
if [[ ! "$uri" =~ ^(https?|ipfs):// ]]; then
continue
fi
# Normalize ipfs:// to configured gateway
check_url="$uri"
if [[ "$uri" == ipfs://* ]]; then
check_url="$IPFS_GATEWAY/ipfs/${uri#ipfs://}"
fi
http_code=$(curl --silent --location \
--max-time 10 --retry 1 --retry-delay 1 \
--head -o /dev/null -w '%{http_code}' "$check_url" 2>/dev/null || true)
[ -z "$http_code" ] && http_code="000"
if [ "$http_code" = "405" ] || [ "$http_code" = "000" ]; then
http_code=$(curl --silent --location \
--max-time 10 --retry 1 --retry-delay 1 \
--request GET --range 0-0 \
-o /dev/null -w '%{http_code}' "$check_url" 2>/dev/null || true)
[ -z "$http_code" ] && http_code="000"
fi
if [[ "$http_code" =~ ^[23][0-9][0-9]$ ]]; then
if [ "$uri" != "$check_url" ]; then
print_pass "$uri ($http_code via $check_url)"
else
print_pass "$uri ($http_code)"
fi
else
failed_count=$((failed_count + 1))
if [ "$uri" != "$check_url" ]; then
print_fail "$uri ($http_code via $check_url)"
else
print_fail "$uri ($http_code)"
fi
fi
done
if [ "$failed_count" -gt 0 ]; then
print_fail "$failed_count of $total_count URIs unreachable."
print_hint "Re-run with --no-link-check to skip this check (e.g. if offline)."
URI_CHECK_FAILED=1
else
print_pass "All $total_count URIs reachable."
fi
fi
fi
# JSON-LD safe-mode expansion check. Surfaces "dropping property that did not
# expand into an absolute IRI or keyword" warnings caused by missing term
# mappings inside the document's @context. This is the failure mode that the
# v1.1.0 hard-fork-initiation schema hit on protocol_version.{major,minor}:
# the context only declared an outer @type, with no inner @context to map the
# inner keys, so safe-mode JSON-LD processors silently drop them. We use Node
# + the 'jsonld' npm package because pyld's behaviour matches it byte-for-byte
# in safe mode (same warning event shape).
JSONLD_CHECK_FAILED=0
if [ "$check_jsonld" = "true" ]; then
print_section "Applying JSON-LD safe-mode expansion check"
# Resolve where the 'jsonld' npm package lives. Try (in order):
# 1. The current NODE_PATH / CWD's node_modules
# 2. The global npm modules dir reported by `npm root -g`
JSONLD_NODE_PATH="${NODE_PATH:-}"
JSONLD_RESOLVED="false"
if ! command -v node >/dev/null 2>&1; then
JSONLD_NODE_AVAILABLE="false"
else
JSONLD_NODE_AVAILABLE="true"
if NODE_PATH="$JSONLD_NODE_PATH" node -e "require.resolve('jsonld')" >/dev/null 2>&1; then
JSONLD_RESOLVED="true"
elif command -v npm >/dev/null 2>&1; then
NPM_GLOBAL_ROOT=$(npm root -g 2>/dev/null || true)
if [ -n "$NPM_GLOBAL_ROOT" ]; then
CANDIDATE="${JSONLD_NODE_PATH:+$JSONLD_NODE_PATH:}$NPM_GLOBAL_ROOT"
if NODE_PATH="$CANDIDATE" node -e "require.resolve('jsonld')" >/dev/null 2>&1; then
JSONLD_NODE_PATH="$CANDIDATE"
JSONLD_RESOLVED="true"
fi
fi
fi
fi
if [ "$JSONLD_NODE_AVAILABLE" = "false" ]; then
print_warn "node is not installed; skipping JSON-LD safe-mode check."
print_hint "Install Node.js (>= 18) to enable. Or pass --no-jsonld-check to silence this notice."
elif [ "$JSONLD_RESOLVED" = "false" ]; then
print_warn "node is installed but the 'jsonld' package is not resolvable; skipping JSON-LD safe-mode check."
print_hint "Install with: 'npm install -g jsonld' (or 'npm install jsonld' in a project directory). Or pass --no-jsonld-check to silence."
else
# Run jsonld.expand with safe:true. Exit codes:
# 0 = clean expansion
# 2 = ValidationError (a property would be dropped)
# 3 = any other expansion error (network, malformed @context, ...)
# Using CommonJS (-e) rather than ESM so NODE_PATH is honoured for the
# bare 'jsonld' specifier — ESM (--input-type=module) ignores NODE_PATH.
set +e
JSONLD_OUTPUT=$(NODE_PATH="$JSONLD_NODE_PATH" node -e '
const jsonld = require("jsonld");
const fs = require("fs");
const doc = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
jsonld.expand(doc, { safe: true })
.then(() => process.exit(0))
.catch(e => {
if (e.name === "jsonld.ValidationError" && e.details && e.details.event) {
const ev = e.details.event;
const d = ev.details || {};
const where = d.property
? "property \x27" + d.property + "\x27" +
(d.expandedProperty && d.expandedProperty !== d.property ? " (expanded as \x27" + d.expandedProperty + "\x27)" : "")
: "(no property in event details)";
console.error((ev.code || "validation error") + ": " + (ev.message || "") + " " + where);
process.exit(2);
}
console.error("expansion failed: " + (e.message || e));
process.exit(3);
});
' "$JSON_FILE" 2>&1)
JSONLD_STATUS=$?
set -e
case "$JSONLD_STATUS" in
0)
print_pass "Document expands cleanly under JSON-LD safe mode"
;;
2)
print_fail "JSON-LD safe-mode expansion would drop properties from the anchored body."
print_hint "$JSONLD_OUTPUT"
print_hint "Cause: a key inside the document's @context lacks an IRI mapping (typically a parent term sets only @type without an inner @context to define its child terms)."
print_hint "If this is a published Intersect schema, fix it at source and bump the schema version, then re-anchor with the new URL."
JSONLD_CHECK_FAILED=1
;;
*)
print_fail "JSON-LD expansion failed."
print_hint "$JSONLD_OUTPUT"
print_hint "If this is a network failure (the @context URL couldn't be fetched), pass --no-jsonld-check to skip."
JSONLD_CHECK_FAILED=1
;;
esac
fi
fi
print_section "Applying schema check(s)"
# Create a temporary directory for schema(s)
mkdir -p "$TMP_SCHEMAS_DIR"
# Download the schemas as needed
if [ "$use_cip_100" = "true" ]; then
print_info "Downloading CIP-100 Governance Metadata schema..."
TEMP_CIP_100_SCHEMA="$TMP_SCHEMAS_DIR/cip-100-schema.json"
curl -sSfSL "$CIP_100_SCHEMA" -o "$TEMP_CIP_100_SCHEMA"
fi
if [ "$use_cip_108" = "true" ]; then
print_info "Downloading CIP-108 Governance Actions schema..."
TEMP_CIP_108_SCHEMA="$TMP_SCHEMAS_DIR/cip-108-schema.json"
curl -sSfSL "$CIP_108_SCHEMA" -o "$TEMP_CIP_108_SCHEMA"
fi
if [ "$use_cip_119" = "true" ]; then
print_info "Downloading CIP-119 DRep schema..."
TEMP_CIP_119_SCHEMA="$TMP_SCHEMAS_DIR/cip-119-schema.json"
curl -sSfSL "$CIP_119_SCHEMA" -o "$TEMP_CIP_119_SCHEMA"
fi
if [ "$use_cip_136" = "true" ]; then
print_info "Downloading CIP-136 Constitutional Committee Vote schema..."
TEMP_CIP_136_SCHEMA="$TMP_SCHEMAS_DIR/cip-136-schema.json"
curl -sSfSL "$CIP_136_SCHEMA" -o "$TEMP_CIP_136_SCHEMA"
fi
CARDANO_CONWAY_REF=""
if [ "$use_cip_169" = "true" ]; then
print_info "Downloading CIP-169 Governance Metadata Extension schema..."
TEMP_CIP_169_SCHEMA="$TMP_SCHEMAS_DIR/cip-169-schema.json"
curl -sSfSL "$CIP_169_SCHEMA" -o "$TEMP_CIP_169_SCHEMA"
echo -e "${WHITE}Downloading CIP-116 cardano-conway types (referenced by CIP-169)...${NC}"
# Filename intentionally avoids the "*-schema.json" suffix so the glob below
# does not pick it up as a top-level schema to validate against.
CARDANO_CONWAY_REF="$TMP_SCHEMAS_DIR/cardano-conway.json"
curl -sSfSL "$CIP_116_CONWAY_SCHEMA" -o "$CARDANO_CONWAY_REF"
fi
# Determine which Intersect schema to use based on the CIP-116 gov_action.tag discriminator.
if [ "$use_intersect_schema" = "true" ]; then
gov_action_tag=$(jq -r '.body.onChain.gov_action.tag // "null"' "$JSON_FILE")
case "$gov_action_tag" in
info_action)
print_info "Downloading Intersect ${YELLOW}info${NC} schema..."
INTERSECT_SCHEMA_URL="$INTERSECT_INFO_SCHEMA"
;;
treasury_withdrawals_action)
print_info "Downloading Intersect ${YELLOW}treasuryWithdrawals${NC} schema..."
INTERSECT_SCHEMA_URL="$INTERSECT_TREASURY_SCHEMA"
;;
parameter_change_action)
print_info "Downloading Intersect ${YELLOW}parameterChanges${NC} schema..."
INTERSECT_SCHEMA_URL="$INTERSECT_PPU_SCHEMA"
;;
hard_fork_initiation_action)
print_info "Downloading Intersect ${YELLOW}hardForkInitiation${NC} schema..."
INTERSECT_SCHEMA_URL="$INTERSECT_HFI_SCHEMA"
;;
update_committee)
print_info "Downloading Intersect ${YELLOW}updateCommittee${NC} schema..."
INTERSECT_SCHEMA_URL="$INTERSECT_UC_SCHEMA"
;;
*)
print_fail "Unknown body.onChain.gov_action.tag '$gov_action_tag' in $(fmt_path "$JSON_FILE")."
print_hint "Expected one of: info_action, treasury_withdrawals_action, parameter_change_action."
exit 1
;;
esac
TEMP_INT_SCHEMA="$TMP_SCHEMAS_DIR/intersect-schema.json"
curl -sSfSL "$INTERSECT_SCHEMA_URL" -o "$TEMP_INT_SCHEMA"
# Under --draft the authors array may legitimately be empty (not yet signed).
# The Intersect schema enforces minItems:1 on authors at the JSON Schema level,
# which AJV would fail on its own, bypassing the --draft logic entirely.
# Remove that constraint so AJV defers the empty-authors check to the structural
# integrity block below, where --draft correctly downgrades it to a warning.
if [ "$is_draft" = "true" ]; then
jq 'del(.definitions.authors.minItems)' "$TEMP_INT_SCHEMA" > "${TEMP_INT_SCHEMA}.tmp" \
&& mv "${TEMP_INT_SCHEMA}.tmp" "$TEMP_INT_SCHEMA"
fi
fi
if [ "$user_schema" = "true" ]; then
print_info "Downloading schema from ${YELLOW}${user_schema_url}${NC}"
TEMP_USER_SCHEMA="$TMP_SCHEMAS_DIR/user-schema.json"
curl -sSfSL "$user_schema_url" -o "$TEMP_USER_SCHEMA"
fi
# Validate the JSON file against the schemas
schemas=("$TMP_SCHEMAS_DIR"/*-schema.json)
# In the case where flags are used to not have any schemas download, exit with 1
if [ -z "$(ls -A $TMP_SCHEMAS_DIR)" ]; then
print_fail "No schemas were downloaded."
exit 1
fi
VALIDATION_FAILED=0
for schema in "${schemas[@]}"; do
print_section "Validating against schema: $schema"
if [ -f "$schema" ]; then
ajv_args=(validate -s "$schema" -d "$JSON_FILE" --all-errors --strict=false)
# CIP-169 references CIP-116 cardano-conway types via $ref; supply them.
if [[ "$schema" == *cip-169-schema.json ]] && [ -n "$CARDANO_CONWAY_REF" ]; then
ajv_args=(validate --spec=draft2020 -s "$schema" -r "$CARDANO_CONWAY_REF" -d "$JSON_FILE" --all-errors --strict=false)
fi
# Drop Ajv's "unknown format X ignored" noise for custom string formats
# CIP116 defines many custom types that AJV loves to warn us about
set +e
ajv "${ajv_args[@]}" 2>&1 \
| grep -v 'unknown format ".*" ignored in schema at path'
ajv_status="${PIPESTATUS[0]}"
set -e
if [ "$ajv_status" -ne 0 ]; then
VALIDATION_FAILED=1
fi
fi
done
# Structural integrity check beyond what ajv enforces.
# Skipped entirely when only --schema URL is in use
STRUCT_CHECK_FAILED=0
if [ "$use_cip_100" = "true" ] || [ "$use_cip_108" = "true" ] || \
[ "$use_cip_119" = "true" ] || [ "$use_cip_136" = "true" ] || \
[ "$use_cip_169" = "true" ] || [ "$use_intersect_schema" = "true" ]; then
print_section "Applying structural integrity checks"
# Non-empty authors array. Downgraded to a warning under --draft so the
authors_count=$(jq -r '(.authors // []) | length' "$JSON_FILE")
if [ "$authors_count" -eq 0 ]; then
if [ "$is_draft" = "true" ]; then
print_warn "authors: array is empty. Acceptable under --draft; re-run without --draft after signing."
else
print_fail "authors: array is empty. Governance metadata must declare at least one author for the document to be attestable."
print_hint "Add a witness or pass --draft for pre-signing validation."
STRUCT_CHECK_FAILED=1
fi
else
print_pass "authors: $authors_count entr$([ "$authors_count" -eq 1 ] && echo y || echo ies)"
fi
fi
# Final result
if [ "$VALIDATION_FAILED" -ne 0 ] || [ "$URI_CHECK_FAILED" -ne 0 ] || [ "$STRUCT_CHECK_FAILED" -ne 0 ] || [ "$JSONLD_CHECK_FAILED" -ne 0 ]; then
print_fail "One or more validation errors were found."
exit 1
else
print_pass "No validation errors found."
exit 0
fi