Skip to main content

vstd/resource/trusted/
protocol.rs

1use super::super::super::prelude::*;
2use super::super::Loc;
3
4verus! {
5
6broadcast use {
7    super::super::super::iset::group_iset_lemmas,
8    super::super::super::imap::group_imap_lemmas,
9};
10
11/// Interface for "storage protocol" ghost state.
12/// This is an extension-slash-variant on the more well-known concept
13/// of "PCM" ghost state, which we also have an interface for [here](super::ra::Resource).
14/// The unique feature of a storage protocol is the ability to use [`guard`](StorageResource::guard)
15/// to manipulate _shared_ references of ghost state.
16///
17/// Storage protocols are based on
18/// [_Leaf: Modularity for Temporary Sharing in Separation Logic_](https://dl.acm.org/doi/10.1145/3622798).
19///
20/// The reference for the laws and operations we're embedding here can be found at:
21/// <https://github.com/secure-foundations/leaf/blob/9d72b880feb6af0a7e752b2b2a43806a0812ad56/src/guarding/protocol_relational.v>
22///
23/// The reference version requires two monoids, the "protocol monoid" and the "base monoid".
24/// In this interface, we fix the base monoid to be of the form [`IMap<K, V>`](crate::imap::IMap).
25/// (with composition of overlapping maps being undefined), which has all the necessary properties.
26/// Note that there's no `create_unit` (it's not sound to do this for an arbitrary location unless you
27/// already know a protocol was initialized at that location).
28///
29/// For applications, I generally advise using the
30/// [`tokenized_state_machine!` system](https://verus-lang.github.io/verus/state_machines/),
31/// rather than using this interface directly.
32#[verifier::external_body]
33#[verifier::accept_recursive_types(K)]
34#[verifier::accept_recursive_types(P)]
35#[verifier::accept_recursive_types(V)]
36pub tracked struct StorageResource<K, V, P> {
37    _p: core::marker::PhantomData<(K, V, P)>,
38    _send_sync: super::super::super::state_machine_internal::SyncSendIfSyncSend<IMap<K, V>>,
39}
40
41#[cfg(verus_keep_ghost)]
42#[verifier::external]
43impl<K, V, P> !Copy for StorageResource<K, V, P> {
44
45}
46
47#[verifier::external_body]
48#[verifier::accept_recursive_types(K)]
49#[verifier::accept_recursive_types(P)]
50#[verifier::accept_recursive_types(V)]
51pub tracked struct CopyableStorageResource<K, V, P> {
52    _p: core::marker::PhantomData<(K, V, P)>,
53    _send_sync: super::super::super::state_machine_internal::SyncSendIfSyncSend<IMap<K, V>>,
54}
55
56impl<K, V, P> Copy for CopyableStorageResource<K, V, P> {
57
58}
59
60impl<K, V, P> Clone for CopyableStorageResource<K, V, P> {
61    #[verifier::external_body]
62    fn clone(&self) -> Self {
63        CopyableStorageResource {
64            _p: core::marker::PhantomData,
65            _send_sync: self._send_sync.clone(),
66        }
67    }
68}
69
70/// See [`StorageResource`] for more information.
71///
72/// Corresponds to the [`VerusSP`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/proph_protocol.v#L36) class in verus-belt.
73pub trait Protocol<K, V>: Sized {
74    spec fn op(self, other: Self) -> Self;
75
76    /// Note that `rel`, in contrast to [`RA::valid`](super::ra::RA::valid), is not
77    /// necessarily closed under inclusion.
78    #[verifier::prophetic]
79    spec fn rel(self, s: IMap<K, V>) -> bool;
80
81    spec fn unit() -> Self;
82
83    proof fn commutative(a: Self, b: Self)
84        ensures
85            Self::op(a, b) == Self::op(b, a),
86    ;
87
88    proof fn associative(a: Self, b: Self, c: Self)
89        ensures
90            Self::op(a, Self::op(b, c)) == Self::op(Self::op(a, b), c),
91    ;
92
93    proof fn op_unit(a: Self)
94        ensures
95            Self::op(a, Self::unit()) == a,
96    ;
97}
98
99pub open spec fn incl<K, V, P: Protocol<K, V>>(a: P, b: P) -> bool {
100    exists|c| P::op(a, c) == b
101}
102
103#[verifier::prophetic]
104pub open spec fn guards<K, V, P: Protocol<K, V>>(p: P, b: IMap<K, V>) -> bool {
105    forall|q: P, t: IMap<K, V>| #![all_triggers] P::rel(P::op(p, q), t) ==> b.submap_of(t)
106}
107
108#[verifier::prophetic]
109pub open spec fn exchanges<K, V, P: Protocol<K, V>>(
110    p1: P,
111    b1: IMap<K, V>,
112    p2: P,
113    b2: IMap<K, V>,
114) -> bool {
115    forall|q: P, t1: IMap<K, V>|
116        #![all_triggers]
117        P::rel(P::op(p1, q), t1) ==> {
118            &&& P::rel(P::op(p2, q), t1.union_prefer_right(b1).remove_keys(b2.dom()))
119            &&& t1.dom().disjoint(b1.dom())
120            &&& b2.submap_of(t1.union_prefer_right(b1))
121        }
122}
123
124#[verifier::prophetic]
125pub open spec fn exchanges_nondeterministic<K, V, P: Protocol<K, V>>(
126    p1: P,
127    s1: IMap<K, V>,
128    new_values: ISet<(P, IMap<K, V>)>,
129    f: spec_fn(P, IMap<K, V>) -> (P, IMap<K, V>, IMap<K, V>),
130) -> bool {
131    forall|q: P, t1: IMap<K, V>|
132        #![all_triggers]
133        P::rel(P::op(p1, q), t1) ==> {
134            let (p2, s2, t2) = f(q, t1);
135            &&& new_values.contains((p2, s2))
136            &&& P::rel(P::op(p2, q), t2)
137            &&& t1.dom().disjoint(s1.dom())
138            &&& t2.dom().disjoint(s2.dom())
139            &&& t1.union_prefer_right(s1) =~= t2.union_prefer_right(s2)
140        }
141}
142
143#[verifier::prophetic]
144pub open spec fn deposits<K, V, P: Protocol<K, V>>(p1: P, b1: IMap<K, V>, p2: P) -> bool {
145    forall|q: P, t1: IMap<K, V>|
146        #![all_triggers]
147        P::rel(P::op(p1, q), t1) ==> {
148            &&& P::rel(P::op(p2, q), t1.union_prefer_right(b1))
149            &&& t1.dom().disjoint(b1.dom())
150        }
151}
152
153#[verifier::prophetic]
154pub open spec fn withdraws<K, V, P: Protocol<K, V>>(p1: P, p2: P, b2: IMap<K, V>) -> bool {
155    forall|q: P, t1: IMap<K, V>|
156        #![all_triggers]
157        P::rel(P::op(p1, q), t1) ==> {
158            &&& P::rel(P::op(p2, q), t1.remove_keys(b2.dom()))
159            &&& b2.submap_of(t1)
160        }
161}
162
163#[verifier::prophetic]
164pub open spec fn updates<K, V, P: Protocol<K, V>>(p1: P, p2: P) -> bool {
165    forall|q: P, t1: IMap<K, V>|
166        #![all_triggers]
167        P::rel(P::op(p1, q), t1) ==> P::rel(P::op(p2, q), t1)
168}
169
170pub open spec fn set_op<K, V, P: Protocol<K, V>>(s: ISet<(P, IMap<K, V>)>, t: P) -> ISet<
171    (P, IMap<K, V>),
172> {
173    s.map(|q: (P, IMap<K, V>)| (P::op(q.0, t), q.1))
174}
175
176impl<K, V, P: Protocol<K, V>> StorageResource<K, V, P> {
177    pub uninterp spec fn value(self) -> P;
178
179    pub uninterp spec fn loc(self) -> Loc;
180
181    /// Proved in verus-belt as [`typed_sp_alloc`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L192).
182    pub axiom fn alloc(p: P, tracked s: IMap<K, V>) -> (tracked out: Self)
183        requires
184            P::rel(p, s),
185        ensures
186            out.value() == p,
187    ;
188
189    /// Proved in verus-belt as [`typed_sp_join`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L228).
190    pub axiom fn join(tracked a: Self, tracked b: Self) -> (tracked out: Self)
191        requires
192            a.loc() == b.loc(),
193        ensures
194            out.loc() == a.loc(),
195            out.value() == P::op(a.value(), b.value()),
196    ;
197
198    /// Proved in verus-belt as [`typed_sp_split`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L263).
199    pub axiom fn split(tracked self, a_value: P, b_value: P) -> (tracked out: (Self, Self))
200        requires
201            self.value() == P::op(a_value, b_value),
202        ensures
203            out.0.loc() == self.loc(),
204            out.1.loc() == self.loc(),
205            out.0.value() == a_value,
206            out.1.value() == b_value,
207    ;
208
209    /// Since `inv` isn't closed under inclusion, validity for an element
210    /// is defined as the inclusion-closure of invariant, i.e., an element
211    /// is valid if there exists another element `x` that, added to it,
212    /// meets the invariant.
213    ///
214    /// Proved in verus-belt as [`typed_sp_validate`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L806).
215    pub axiom fn validate(tracked self: &Self) -> (out: (P, IMap<K, V>))
216        ensures
217            ({
218                let (q, t) = out;
219                P::rel(P::op(self.value(), q), t)
220            }),
221    ;
222
223    // Helper lemma saying that unioning with an empty map is a no-op.
224    proof fn lemma_union_prefer_right_empty_is_noop_forall()
225        ensures
226            forall|m: IMap<K, V>| #[trigger] m.union_prefer_right(IMap::empty()) == m,
227    {
228        assert forall|m: IMap<K, V>| #[trigger] m.union_prefer_right(IMap::empty()) == m by {
229            assert(m.union_prefer_right(IMap::empty()) =~= m);
230        }
231    }
232
233    // Helper lemma saying that removing the empty set of keys from a map is a no-op.
234    proof fn lemma_removing_empty_keys_is_noop_forall()
235        ensures
236            forall|m: IMap<K, V>| #[trigger] m.remove_keys(ISet::empty()) == m,
237    {
238        assert forall|m: IMap<K, V>| m.remove_keys(ISet::empty()) == m by {
239            assert(m.remove_keys(ISet::empty()) =~= m);
240        }
241    }
242
243    // Updates and guards
244    /// Most general kind of update, potentially depositing and withdrawing
245    pub proof fn exchange(
246        tracked p: Self,
247        tracked s: IMap<K, V>,
248        new_p_value: P,
249        new_s_value: IMap<K, V>,
250    ) -> (tracked out: (Self, IMap<K, V>))
251        requires
252            exchanges(p.value(), s, new_p_value, new_s_value),
253        ensures
254            ({
255                let (new_p, new_s) = out;
256                new_p.loc() == p.loc() && new_p.value() == new_p_value && new_s == new_s_value
257            }),
258    {
259        let se = iset![(new_p_value, new_s_value)];
260        let f = |q: P, t1: IMap<K, V>|
261            (new_p_value, new_s_value, t1.union_prefer_right(s).remove_keys(new_s_value.dom()));
262        assert(se.contains((new_p_value, new_s_value)));
263        Self::exchange_nondeterministic(p, s, se, f)
264    }
265
266    pub proof fn deposit(tracked self, tracked base: IMap<K, V>, new_value: P) -> (tracked out:
267        Self)
268        requires
269            deposits(self.value(), base, new_value),
270        ensures
271            out.loc() == self.loc(),
272            out.value() == new_value,
273    {
274        Self::lemma_removing_empty_keys_is_noop_forall();
275        Self::exchange(self, base, new_value, IMap::empty()).0
276    }
277
278    pub proof fn withdraw(tracked self, new_value: P, new_base: IMap<K, V>) -> (tracked out: (
279        Self,
280        IMap<K, V>,
281    ))
282        requires
283            withdraws(self.value(), new_value, new_base),
284        ensures
285            out.0.loc() == self.loc(),
286            out.0.value() == new_value,
287            out.1 == new_base,
288    {
289        Self::lemma_union_prefer_right_empty_is_noop_forall();
290        Self::exchange(self, IMap::tracked_empty(), new_value, new_base)
291    }
292
293    /// "Normal" update, no depositing or withdrawing
294    pub proof fn update(tracked self, new_value: P) -> (tracked out: Self)
295        requires
296            updates(self.value(), new_value),
297        ensures
298            out.loc() == self.loc(),
299            out.value() == new_value,
300    {
301        Self::lemma_union_prefer_right_empty_is_noop_forall();
302        Self::lemma_removing_empty_keys_is_noop_forall();
303        Self::exchange(self, IMap::tracked_empty(), new_value, IMap::empty()).0
304    }
305
306    pub proof fn exchange_nondeterministic(
307        tracked p: Self,
308        tracked s: IMap<K, V>,
309        new_values: ISet<(P, IMap<K, V>)>,
310        f: spec_fn(P, IMap<K, V>) -> (P, IMap<K, V>, IMap<K, V>),
311    ) -> (tracked out: (Self, IMap<K, V>))
312        requires
313            exchanges_nondeterministic(p.value(), s, new_values, f),
314        ensures
315            ({
316                let (new_p, new_s) = out;
317                new_p.loc() == p.loc() && new_values.contains((new_p.value(), new_s))
318            }),
319    {
320        P::op_unit(p.value());
321        let tracked (selff, unit) = p.split(p.value(), P::unit());
322        let new_values0 = set_op(new_values, P::unit());
323        super::super::super::iset_lib::assert_isets_equal!(new_values0, new_values, v => {
324            P::op_unit(v.0);
325            if new_values.contains(v) {
326                assert(new_values0.contains(v));
327            }
328            if new_values0.contains(v) {
329                let q = choose |q| #[trigger] new_values.contains(q) && v == (P::op(q.0, P::unit()), q.1);
330                assert(P::op(q.0, P::unit()) == q.0) by { P::op_unit(q.0) }
331                assert(v =~= q);
332                assert(new_values.contains(v));
333            }
334        });
335        Self::exchange_nondeterministic_with_shared(selff, &unit, s, new_values, f)
336    }
337
338    /// Proved in verus-belt as [`typed_sp_guard`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L515).
339    pub axiom fn guard(tracked p: &Self, s_value: IMap<K, V>) -> (tracked s: &IMap<K, V>)
340        requires
341            guards(p.value(), s_value),
342        ensures
343            s == s_value,
344    ;
345
346    // Operations with shared references
347    /// Not yet proved in verus-belt.
348    pub axiom fn join_shared<'a>(tracked &'a self, tracked other: &'a Self) -> (tracked out:
349        &'a Self)
350        requires
351            self.loc() == other.loc(),
352        ensures
353            out.loc() == self.loc(),
354            incl(self.value(), out.value()),
355            incl(other.value(), out.value()),
356    ;
357
358    /// Proved in verus-belt as [`typed_sp_weaken`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L736).
359    pub axiom fn weaken<'a>(tracked &'a self, target: P) -> (tracked out: &'a Self)
360        requires
361            incl(target, self.value()),
362        ensures
363            out.loc() == self.loc(),
364            out.value() == target,
365    ;
366
367    /// Proved in verus-belt as [`typed_sp_validate_with_shr`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L946).
368    pub axiom fn validate_with_shared(tracked self: &mut Self, tracked x: &Self) -> (res: (
369        P,
370        IMap<K, V>,
371    ))
372        requires
373            old(self).loc() == x.loc(),
374        ensures
375            *final(self) == *old(self),
376            ({
377                let (q, t) = res;
378                { P::rel(P::op(P::op(final(self).value(), x.value()), q), t) }
379            }),
380    ;
381
382    // See `logic_exchange_with_extra_guard`
383    // https://github.com/secure-foundations/leaf/blob/a51725deedecc88294057ac1502a7c7ff2104a69/src/guarding/protocol.v#L720
384    pub proof fn exchange_with_shared(
385        tracked p: Self,
386        tracked x: &Self,
387        tracked s: IMap<K, V>,
388        new_p_value: P,
389        new_s_value: IMap<K, V>,
390    ) -> (tracked out: (Self, IMap<K, V>))
391        requires
392            p.loc() == x.loc(),
393            exchanges(P::op(p.value(), x.value()), s, P::op(new_p_value, x.value()), new_s_value),
394        ensures
395            out.0.loc() == p.loc(),
396            out.0.value() == new_p_value,
397            out.1 == new_s_value,
398    {
399        let se = iset![(new_p_value, new_s_value)];
400        let f = |q: P, t1: IMap<K, V>|
401            (
402                P::op(new_p_value, x.value()),
403                new_s_value,
404                t1.union_prefer_right(s).remove_keys(new_s_value.dom()),
405            );
406        assert(exchanges_nondeterministic(P::op(p.value(), x.value()), s, set_op(se, x.value()), f))
407            by {
408            let new_values = set_op(se, x.value());
409            assert(se.contains((new_p_value, new_s_value)));
410            assert(new_values.contains((P::op(new_p_value, x.value()), new_s_value)));
411        }
412        Self::exchange_nondeterministic_with_shared(p, x, s, se, f)
413    }
414
415    // See `logic_exchange_with_extra_guard_nondeterministic`
416    // https://github.com/secure-foundations/leaf/blob/a51725deedecc88294057ac1502a7c7ff2104a69/src/guarding/protocol.v#L834
417    /// Most general kind of update, potentially depositing and withdrawing
418    ///
419    /// Proved in verus-belt as [`typed_sp_exchange_with_shr_nondeterministic`](https://github.com/verus-lang/verus-belt/blob/d01bee9956410c922817ba24259f0f13bfd8849e/src/lambda_verus/typing/protocol.v#L1076).
420    pub axiom fn exchange_nondeterministic_with_shared(
421        tracked p: Self,
422        tracked x: &Self,
423        tracked s: IMap<K, V>,
424        new_values: ISet<(P, IMap<K, V>)>,
425        f: spec_fn(P, IMap<K, V>) -> (P, IMap<K, V>, IMap<K, V>),
426    ) -> (tracked out: (Self, IMap<K, V>))
427        requires
428            p.loc() == x.loc(),
429            exchanges_nondeterministic(
430                P::op(p.value(), x.value()),
431                s,
432                set_op(new_values, x.value()),
433                f,
434            ),
435        ensures
436            ({
437                let (new_p, new_s) = out;
438                new_p.loc() == p.loc() && new_values.contains((new_p.value(), new_s))
439            }),
440    ;
441
442    /// Wrap this resource in a type that implements `Copy`,
443    /// given that the resource is duplicable.
444    ///
445    /// Not yet proved in verus-belt.
446    pub axiom fn into_copyable(tracked self, p: P) -> (tracked r: CopyableStorageResource<K, V, P>)
447        requires
448            P::op(P::op(self.value(), self.value()), p) == self.value(),
449        ensures
450            r.loc() == self.loc(),
451            r.value() == self.value(),
452    ;
453}
454
455/// A variant of [`StorageResource`] that implements `Copy`.
456///
457/// Use [`Self::into_resource`] to get the underlying resource.
458impl<K, V, P: Protocol<K, V>> CopyableStorageResource<K, V, P> {
459    /// The underlying value of the resource
460    pub uninterp spec fn value(self) -> P;
461
462    /// The location of the resource
463    pub uninterp spec fn loc(self) -> Loc;
464
465    /// Not yet proved in verus-belt.
466    pub axiom fn into_resource(tracked self) -> (tracked r: StorageResource<K, V, P>)
467        ensures
468            r.loc() == self.loc(),
469            r.value() == self.value(),
470    ;
471}
472
473} // verus!