bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
//! Transform logging with Merkle tree for integrity verification

use crate::formatter::{transforms::*, types::*};
use blake3::{Hash, Hasher};
use std::time::Instant;

/// Append-only log for transformation verification context propagation
#[derive(Debug, Clone)]
pub struct TransformLog {
    /// All transformation entries
    pub entries: Vec<TransformEntry>,

    /// Merkle tree for integrity verification
    merkle_tree: MerkleTree,

    /// Log metadata
    metadata: LogMetadata,
}

/// Individual transformation log entry
#[derive(Debug, Clone)]
pub struct TransformEntry {
    /// Unique identifier for this transformation
    pub id: TransformId,

    /// The transformation that was applied
    pub transform: Transform,

    /// Source span affected by this transformation
    pub source_span: Span,

    /// Resulting span after transformation
    pub result_span: Span,

    /// Timestamp when transformation was applied
    pub timestamp: Instant,

    /// Optional SMT proof for semantic preservation
    pub proof: Option<SexprProof>,

    /// Semantic changes introduced (if any)
    pub semantic_delta: Option<SemanticDelta>,
}

/// Merkle tree for log integrity verification
#[derive(Debug, Clone)]
pub struct MerkleTree {
    /// Root hash of the tree
    root_hash: Hash,

    /// All leaf hashes (one per log entry)
    leaf_hashes: Vec<Hash>,

    /// Internal node hashes for efficient verification
    internal_nodes: Vec<Hash>,

    /// Tree height (log2 of leaf count, rounded up)
    _height: usize,
}

/// Metadata about the transformation log
#[derive(Debug, Clone)]
pub struct LogMetadata {
    /// Total number of transformations
    pub total_transforms: usize,

    /// Number of semantic-preserving transformations
    pub semantic_preserving: usize,

    /// Number of transformations with proofs
    pub with_proofs: usize,

    /// Time span of all transformations
    pub time_span: Option<std::time::Duration>,

    /// Log creation timestamp
    pub created_at: Instant,
}

/// Merkle proof for verifying log entry integrity
#[derive(Debug, Clone)]
pub struct MerkleProof {
    /// Index of the leaf being verified
    pub leaf_index: usize,

    /// Hash path from leaf to root
    pub path: Vec<Hash>,

    /// Direction indicators (true = right, false = left)
    pub directions: Vec<bool>,
}

/// Result of verifying a Merkle proof
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VerificationResult {
    Valid,
    Invalid,
    InsufficientData,
}

impl TransformLog {
    /// Create a new empty transform log
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            merkle_tree: MerkleTree::empty(),
            metadata: LogMetadata {
                total_transforms: 0,
                semantic_preserving: 0,
                with_proofs: 0,
                time_span: None,
                created_at: Instant::now(),
            },
        }
    }

    /// Add a new transformation entry
    pub fn add_entry(&mut self, entry: TransformEntry) {
        // Update metadata
        self.metadata.total_transforms += 1;

        if entry.transform.is_semantic_preserving() {
            self.metadata.semantic_preserving += 1;
        }

        if entry.proof.is_some() {
            self.metadata.with_proofs += 1;
        }

        // Update time span
        if let Some(first_entry) = self.entries.first() {
            self.metadata.time_span = Some(entry.timestamp.duration_since(first_entry.timestamp));
        }

        // Add to entries
        self.entries.push(entry);

        // Rebuild Merkle tree
        self.rebuild_merkle_tree();
    }

    /// Rebuild the Merkle tree from all entries
    fn rebuild_merkle_tree(&mut self) {
        if self.entries.is_empty() {
            self.merkle_tree = MerkleTree::empty();
            return;
        }

        // Compute leaf hashes
        let leaf_hashes: Vec<Hash> = self
            .entries
            .iter()
            .map(|entry| self.hash_entry(entry))
            .collect();

        self.merkle_tree = MerkleTree::from_leaves(leaf_hashes);
    }

    /// Hash a single transform entry
    fn hash_entry(&self, entry: &TransformEntry) -> Hash {
        let mut hasher = Hasher::new();

        // Hash the transform ID
        hasher.update(&entry.id.0.to_le_bytes());

        // Hash the transform description
        hasher.update(entry.transform.description().as_bytes());

        // Hash the spans
        hasher.update(&entry.source_span.start.0.to_le_bytes());
        hasher.update(&entry.source_span.end.0.to_le_bytes());
        hasher.update(&entry.result_span.start.0.to_le_bytes());
        hasher.update(&entry.result_span.end.0.to_le_bytes());

        // Hash timestamp (as nanoseconds since epoch)
        let nanos = entry.timestamp.elapsed().as_nanos();
        hasher.update(&(nanos as u64).to_le_bytes());

        // Hash proof if present
        if let Some(proof) = &entry.proof {
            hasher.update(proof.formula.as_bytes());
            hasher.update(&[u8::from(proof.is_valid)]);
        }

        hasher.finalize()
    }

    /// Generate a proof for a specific log entry
    pub fn generate_proof(&self, entry_index: usize) -> Option<MerkleProof> {
        if entry_index >= self.entries.len() {
            return None;
        }

        self.merkle_tree.generate_proof(entry_index)
    }

    /// Verify a Merkle proof against the current root
    pub fn verify_proof(&self, proof: &MerkleProof, leaf_hash: Hash) -> VerificationResult {
        self.merkle_tree.verify_proof(proof, leaf_hash)
    }

    /// Get the current root hash for integrity checking
    pub fn root_hash(&self) -> Hash {
        self.merkle_tree.root_hash
    }

    /// Export log for external verification
    pub fn export_verification_data(&self) -> LogVerificationData {
        LogVerificationData {
            entries: self.entries.clone(),
            root_hash: self.merkle_tree.root_hash,
            leaf_hashes: self.merkle_tree.leaf_hashes.clone(),
            metadata: self.metadata.clone(),
        }
    }

    /// Get statistics about the log
    pub fn stats(&self) -> LogStats {
        let total = self.metadata.total_transforms;
        let semantic_ratio = if total > 0 {
            self.metadata.semantic_preserving as f64 / total as f64
        } else {
            0.0
        };

        let proof_ratio = if total > 0 {
            self.metadata.with_proofs as f64 / total as f64
        } else {
            0.0
        };

        LogStats {
            total_entries: total,
            semantic_preserving_ratio: semantic_ratio,
            proof_coverage_ratio: proof_ratio,
            memory_usage_bytes: self.estimate_memory_usage(),
            integrity_verified: true, // Always true for our implementation
        }
    }

    fn estimate_memory_usage(&self) -> usize {
        let entries_size = self.entries.len() * std::mem::size_of::<TransformEntry>();
        let tree_size = self.merkle_tree.leaf_hashes.len() * std::mem::size_of::<Hash>()
            + self.merkle_tree.internal_nodes.len() * std::mem::size_of::<Hash>();

        entries_size + tree_size + std::mem::size_of::<LogMetadata>()
    }
}

impl MerkleTree {
    /// Create an empty Merkle tree
    pub fn empty() -> Self {
        Self {
            root_hash: blake3::hash(b""),
            leaf_hashes: Vec::new(),
            internal_nodes: Vec::new(),
            _height: 0,
        }
    }

    /// Create Merkle tree from leaf hashes
    pub fn from_leaves(mut leaf_hashes: Vec<Hash>) -> Self {
        if leaf_hashes.is_empty() {
            return Self::empty();
        }

        // Pad to next power of 2 for balanced tree (minimum 2 leaves)
        let original_count = leaf_hashes.len();
        let next_power_of_2 = std::cmp::max(2, original_count.next_power_of_two());
        let padding_needed = next_power_of_2 - original_count;

        // Pad with zero hashes
        let zero_hash = blake3::hash(b"");
        for _ in 0..padding_needed {
            leaf_hashes.push(zero_hash);
        }

        let height = (leaf_hashes.len() as f64).log2() as usize;
        let mut internal_nodes = Vec::new();
        let mut current_level = leaf_hashes.clone();

        // Build tree bottom-up
        while current_level.len() > 1 {
            let mut next_level = Vec::new();

            for chunk in current_level.chunks(2) {
                let left = chunk[0];
                let right = chunk.get(1).copied().unwrap_or(zero_hash);

                let mut hasher = Hasher::new();
                hasher.update(left.as_bytes());
                hasher.update(right.as_bytes());
                let parent_hash = hasher.finalize();

                internal_nodes.push(parent_hash);
                next_level.push(parent_hash);
            }

            current_level = next_level;
        }

        let root_hash = current_level[0];

        Self {
            root_hash,
            leaf_hashes,
            internal_nodes,
            _height: height,
        }
    }

    /// Generate a Merkle proof for a specific leaf
    pub fn generate_proof(&self, leaf_index: usize) -> Option<MerkleProof> {
        if leaf_index >= self.leaf_hashes.len() {
            return None;
        }

        let mut path = Vec::new();
        let mut directions = Vec::new();
        let current_index = leaf_index;
        let _current_level = &self.leaf_hashes;

        // Generate simple proof (simplified implementation)
        if _current_level.len() > 1 {
            let sibling_index = if current_index.is_multiple_of(2) {
                current_index + 1
            } else {
                current_index - 1
            };

            // Add sibling to path
            if sibling_index < _current_level.len() {
                path.push(_current_level[sibling_index]);
                directions.push(current_index.is_multiple_of(2)); // true if we're left child
            } else {
                // Pad with zero hash
                path.push(blake3::hash(b""));
                directions.push(true);
            }
        }

        Some(MerkleProof {
            leaf_index,
            path,
            directions,
        })
    }

    /// Verify a Merkle proof
    pub fn verify_proof(&self, proof: &MerkleProof, leaf_hash: Hash) -> VerificationResult {
        if proof.leaf_index >= self.leaf_hashes.len() {
            return VerificationResult::Invalid;
        }

        if proof.path.len() != proof.directions.len() {
            return VerificationResult::Invalid;
        }

        let mut current_hash = leaf_hash;

        // Recompute root hash using proof path
        for (sibling_hash, is_left) in proof.path.iter().zip(&proof.directions) {
            let mut hasher = Hasher::new();

            if *is_left {
                hasher.update(current_hash.as_bytes());
                hasher.update(sibling_hash.as_bytes());
            } else {
                hasher.update(sibling_hash.as_bytes());
                hasher.update(current_hash.as_bytes());
            }

            current_hash = hasher.finalize();
        }

        if current_hash == self.root_hash {
            VerificationResult::Valid
        } else {
            VerificationResult::Invalid
        }
    }
}

/// Data structure for external log verification
#[derive(Debug, Clone)]
pub struct LogVerificationData {
    pub entries: Vec<TransformEntry>,
    pub root_hash: Hash,
    pub leaf_hashes: Vec<Hash>,
    pub metadata: LogMetadata,
}

/// Statistics about the transformation log
#[derive(Debug, Clone)]
pub struct LogStats {
    pub total_entries: usize,
    pub semantic_preserving_ratio: f64,
    pub proof_coverage_ratio: f64,
    pub memory_usage_bytes: usize,
    pub integrity_verified: bool,
}

impl Default for TransformLog {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for LogMetadata {
    fn default() -> Self {
        Self {
            total_transforms: 0,
            semantic_preserving: 0,
            with_proofs: 0,
            time_span: None,
            created_at: Instant::now(),
        }
    }
}

#[cfg(test)]
#[path = "logging_tests_transform_lo.rs"]
mod tests_extracted;