ai-agent-bitcoin-escrow 0.1.0

A Rust library for AI agents to create, manage, and execute Bitcoin escrow contracts using multisig
Documentation
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
//! Release conditions for escrow contracts.
//!
//! This module provides condition-based triggers for fund releases,
//! including AI agent decisions, oracle triggers, timelocks, and
//! compound conditions (AND/OR).

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::error::{EscrowError, Result};
use crate::types::{AgentId, ConditionResult, EscrowRole, OracleId, ReleaseCondition};

/// Trait for evaluating release conditions.
#[async_trait]
pub trait ConditionEvaluator: Send + Sync {
    /// Evaluate a condition.
    async fn evaluate(&self, condition: &ReleaseCondition) -> Result<ConditionResult>;
}

/// Standard condition evaluator with pluggable oracle and AI decision support.
pub struct StandardEvaluator {
    /// Oracle providers.
    oracles: HashMap<String, Box<dyn OracleProvider>>,
    /// AI decision validators.
    ai_validators: HashMap<String, Box<dyn AIDecisionValidator>>,
}

impl StandardEvaluator {
    /// Create a new evaluator.
    pub fn new() -> Self {
        Self {
            oracles: HashMap::new(),
            ai_validators: HashMap::new(),
        }
    }

    /// Register an oracle provider.
    pub fn with_oracle(mut self, id: &str, provider: Box<dyn OracleProvider>) -> Self {
        self.oracles.insert(id.to_string(), provider);
        self
    }

    /// Register an AI decision validator.
    pub fn with_ai_validator(mut self, id: &str, validator: Box<dyn AIDecisionValidator>) -> Self {
        self.ai_validators.insert(id.to_string(), validator);
        self
    }

    /// Evaluate an AI decision condition.
    async fn evaluate_ai_decision(
        &self,
        agent_id: &AgentId,
        decision_hash: &str,
    ) -> Result<ConditionResult> {
        let validator = self
            .ai_validators
            .get(&agent_id.0)
            .ok_or_else(|| EscrowError::Condition(format!("Unknown AI agent: {}", agent_id)))?;

        validator.validate(decision_hash).await
    }

    /// Evaluate an oracle trigger.
    async fn evaluate_oracle(
        &self,
        oracle_id: &OracleId,
        query: &str,
        expected_value: &str,
    ) -> Result<ConditionResult> {
        let oracle = self
            .oracles
            .get(&oracle_id.0)
            .ok_or_else(|| EscrowError::Oracle(format!("Unknown oracle: {}", oracle_id)))?;

        oracle.query(query, expected_value).await
    }

    /// Evaluate a timelock.
    fn evaluate_timelock(&self, unlock_after: &DateTime<Utc>) -> ConditionResult {
        let now = Utc::now();
        let satisfied = now >= *unlock_after;
        
        ConditionResult {
            satisfied,
            reason: if satisfied {
                format!("Timelock expired at {}", unlock_after)
            } else {
                format!("Timelock not yet expired (unlocks at {})", unlock_after)
            },
            evaluated_at: now,
            data: Some(serde_json::json!({
                "unlock_after": unlock_after.to_rfc3339(),
                "current_time": now.to_rfc3339(),
            })),
        }
    }

    /// Evaluate manual approval.
    fn evaluate_manual_approval(&self, required_roles: &[EscrowRole]) -> ConditionResult {
        // This would be connected to the escrow state to check who has approved
        ConditionResult {
            satisfied: false, // Placeholder - needs to be connected to escrow state
            reason: format!(
                "Manual approval required from roles: {:?}",
                required_roles
            ),
            evaluated_at: Utc::now(),
            data: Some(serde_json::json!({
                "required_roles": required_roles,
            })),
        }
    }
}

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

#[async_trait]
impl ConditionEvaluator for StandardEvaluator {
    async fn evaluate(&self, condition: &ReleaseCondition) -> Result<ConditionResult> {
        match condition {
            ReleaseCondition::AIDecision { agent_id, decision_hash } => {
                self.evaluate_ai_decision(agent_id, decision_hash).await
            }
            ReleaseCondition::OracleTrigger { oracle_id, query, expected_value } => {
                self.evaluate_oracle(oracle_id, query, expected_value).await
            }
            ReleaseCondition::TimeLock { unlock_after } => {
                Ok(self.evaluate_timelock(unlock_after))
            }
            ReleaseCondition::ManualApproval { required_roles } => {
                Ok(self.evaluate_manual_approval(required_roles))
            }
            ReleaseCondition::AllOf { conditions } => {
                let mut all_satisfied = true;
                let mut reasons = Vec::new();
                let mut data = HashMap::new();

                for (i, cond) in conditions.iter().enumerate() {
                    let result = self.evaluate(cond).await?;
                    if !result.satisfied {
                        all_satisfied = false;
                    }
                    reasons.push(format!("Condition {}: {}", i + 1, result.reason));
                    data.insert(format!("condition_{}", i), result.data);
                }

                Ok(ConditionResult {
                    satisfied: all_satisfied,
                    reason: reasons.join("; "),
                    evaluated_at: Utc::now(),
                    data: Some(serde_json::to_value(data)?),
                })
            }
            ReleaseCondition::AnyOf { conditions } => {
                let mut any_satisfied = false;
                let mut reasons = Vec::new();
                let mut data = HashMap::new();

                for (i, cond) in conditions.iter().enumerate() {
                    let result = self.evaluate(cond).await?;
                    if result.satisfied {
                        any_satisfied = true;
                    }
                    reasons.push(format!("Condition {}: {}", i + 1, result.reason));
                    data.insert(format!("condition_{}", i), result.data);
                }

                Ok(ConditionResult {
                    satisfied: any_satisfied,
                    reason: reasons.join("; "),
                    evaluated_at: Utc::now(),
                    data: Some(serde_json::to_value(data)?),
                })
            }
        }
    }
}

/// Trait for oracle providers.
#[async_trait]
pub trait OracleProvider: Send + Sync {
    /// Query the oracle and check if the result matches expected value.
    async fn query(&self, query: &str, expected_value: &str) -> Result<ConditionResult>;
}

/// Trait for AI decision validators.
#[async_trait]
pub trait AIDecisionValidator: Send + Sync {
    /// Validate an AI decision by its hash.
    async fn validate(&self, decision_hash: &str) -> Result<ConditionResult>;
}

/// A simple mock oracle for testing.
pub struct MockOracle {
    responses: HashMap<String, String>,
}

impl MockOracle {
    /// Create a new mock oracle with predefined responses.
    pub fn new(responses: HashMap<String, String>) -> Self {
        Self { responses }
    }
}

#[async_trait]
impl OracleProvider for MockOracle {
    async fn query(&self, query: &str, expected_value: &str) -> Result<ConditionResult> {
        let value = self
            .responses
            .get(query)
            .cloned()
            .unwrap_or_else(|| "unknown".to_string());

        let satisfied = &value == expected_value;

        Ok(ConditionResult {
            satisfied,
            reason: if satisfied {
                format!("Oracle returned expected value: {}", value)
            } else {
                format!(
                    "Oracle returned '{}', expected '{}'",
                    value, expected_value
                )
            },
            evaluated_at: Utc::now(),
            data: Some(serde_json::json!({
                "query": query,
                "value": value,
                "expected": expected_value,
            })),
        })
    }
}

/// A simple mock AI decision validator for testing.
pub struct MockAIDecisionValidator {
    valid_hashes: Vec<String>,
}

impl MockAIDecisionValidator {
    /// Create a new mock validator with predefined valid hashes.
    pub fn new(valid_hashes: Vec<String>) -> Self {
        Self { valid_hashes }
    }
}

#[async_trait]
impl AIDecisionValidator for MockAIDecisionValidator {
    async fn validate(&self, decision_hash: &str) -> Result<ConditionResult> {
        let satisfied = self.valid_hashes.contains(&decision_hash.to_string());

        Ok(ConditionResult {
            satisfied,
            reason: if satisfied {
                format!("AI decision {} is valid", decision_hash)
            } else {
                format!("AI decision {} is not recognized", decision_hash)
            },
            evaluated_at: Utc::now(),
            data: Some(serde_json::json!({
                "decision_hash": decision_hash,
                "valid": satisfied,
            })),
        })
    }
}

/// Builder for creating compound conditions.
pub struct ConditionBuilder {
    conditions: Vec<ReleaseCondition>,
}

impl ConditionBuilder {
    /// Create a new condition builder.
    pub fn new() -> Self {
        Self { conditions: Vec::new() }
    }

    /// Add an AI decision condition.
    pub fn ai_decision(mut self, agent_id: impl Into<String>, decision_hash: impl Into<String>) -> Self {
        self.conditions.push(ReleaseCondition::AIDecision {
            agent_id: AgentId::new(agent_id),
            decision_hash: decision_hash.into(),
        });
        self
    }

    /// Add an oracle condition.
    pub fn oracle(
        mut self,
        oracle_id: impl Into<String>,
        query: impl Into<String>,
        expected_value: impl Into<String>,
    ) -> Self {
        self.conditions.push(ReleaseCondition::OracleTrigger {
            oracle_id: OracleId::new(oracle_id),
            query: query.into(),
            expected_value: expected_value.into(),
        });
        self
    }

    /// Add a timelock condition.
    pub fn timelock(mut self, unlock_after: DateTime<Utc>) -> Self {
        self.conditions.push(ReleaseCondition::TimeLock { unlock_after });
        self
    }

    /// Add a manual approval condition.
    pub fn manual_approval(mut self, required_roles: Vec<EscrowRole>) -> Self {
        self.conditions.push(ReleaseCondition::ManualApproval { required_roles });
        self
    }

    /// Build as AllOf (AND) condition.
    pub fn build_all(self) -> ReleaseCondition {
        ReleaseCondition::AllOf {
            conditions: self.conditions,
        }
    }

    /// Build as AnyOf (OR) condition.
    pub fn build_any(self) -> ReleaseCondition {
        ReleaseCondition::AnyOf {
            conditions: self.conditions,
        }
    }

    /// Build as single condition (if only one was added).
    pub fn build_single(self) -> Option<ReleaseCondition> {
        if self.conditions.len() == 1 {
            self.conditions.into_iter().next()
        } else {
            None
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[tokio::test]
    async fn test_timelock_evaluation() {
        let evaluator = StandardEvaluator::new();
        
        // Test expired timelock
        let past_time = Utc::now() - chrono::Duration::hours(1);
        let condition = ReleaseCondition::TimeLock { unlock_after: past_time };
        let result = evaluator.evaluate(&condition).await.unwrap();
        assert!(result.satisfied);

        // Test future timelock
        let future_time = Utc::now() + chrono::Duration::hours(1);
        let condition = ReleaseCondition::TimeLock { unlock_after: future_time };
        let result = evaluator.evaluate(&condition).await.unwrap();
        assert!(!result.satisfied);
    }

    #[tokio::test]
    async fn test_oracle_evaluation() {
        let mut responses = HashMap::new();
        responses.insert("btc_price".to_string(), "50000".to_string());

        let evaluator = StandardEvaluator::new()
            .with_oracle("price_oracle", Box::new(MockOracle::new(responses)));

        // Test matching value
        let condition = ReleaseCondition::OracleTrigger {
            oracle_id: OracleId::new("price_oracle"),
            query: "btc_price".to_string(),
            expected_value: "50000".to_string(),
        };
        let result = evaluator.evaluate(&condition).await.unwrap();
        assert!(result.satisfied);

        // Test non-matching value
        let condition = ReleaseCondition::OracleTrigger {
            oracle_id: OracleId::new("price_oracle"),
            query: "btc_price".to_string(),
            expected_value: "60000".to_string(),
        };
        let result = evaluator.evaluate(&condition).await.unwrap();
        assert!(!result.satisfied);
    }

    #[tokio::test]
    async fn test_condition_builder() {
        let condition = ConditionBuilder::new()
            .ai_decision("agent-1", "hash123")
            .timelock(Utc::now() - chrono::Duration::hours(1))
            .build_all();

        match condition {
            ReleaseCondition::AllOf { conditions } => {
                assert_eq!(conditions.len(), 2);
            }
            _ => panic!("Expected AllOf condition"),
        }
    }
}