# A function so callers can RE-snapshot after in-pass ledger writers (the
# cutover conversion appends its converted entry mid-script; replay must
# fold that entry in the same pass, not next boot).
snapshot_os_intent_ledger() {
rm -f "$ledger_snapshot" "$ledger_snapshot.sha256" "$ledger_snapshot.skipped-bytes"
# Existence pre-check is NOISE control only (quiet fresh-VM boots); the
# python open owns enforcement, so a race here changes nothing. -e follows
# symlinks, so a DANGLING guest-planted symlink must also pass the gate via
# -L and reach the python open — that is what turns the plant into the loud
# tamper message instead of a silent healthy-looking skip.
if [ -e "$ledger_source" ] || [ -L "$ledger_source" ]; then
snap_rc=0
python3 - "$ledger_source" "$ledger_snapshot" <<'PYSNAP' 2>/dev/null || snap_rc=$?
import hashlib, os, stat, sys
src, dst = sys.argv[1], sys.argv[2]
try:
fd = os.open(src, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
except OSError:
sys.exit(3)
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
sys.exit(4)
hasher = hashlib.sha256()
retain = 16 * 1024 * 1024
ceiling = 64 * 1024 * 1024
hashed = 0
skipped = 0
out = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
while True:
chunk = os.read(fd, 1 << 20)
if not chunk:
break
hashed += len(chunk)
if hashed > ceiling:
sys.exit(5)
hasher.update(chunk)
take = chunk[:retain] if retain > 0 else b""
if take:
os.write(out, take)
retain -= len(take)
skipped += len(chunk) - len(take)
finally:
os.close(out)
if skipped:
with open(dst + ".skipped-bytes", "w") as sidecar:
sidecar.write("%d\n" % skipped)
with open(dst + ".sha256", "w") as sidecar:
sidecar.write(hasher.hexdigest() + "\n")
finally:
os.close(fd)
PYSNAP