Skip to main content

vstd/resource/
storage_protocol.rs

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