rgb-ops 0.11.1-rc.10

RGB ops library for working with smart contracts on Bitcoin & Lightning
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// RGB ops library for working with smart contracts on Bitcoin & Lightning
//
// SPDX-License-Identifier: Apache-2.0
//
// Written in 2019-2024 by
//     Dr Maxim Orlovsky <orlovsky@lnp-bp.org>
//
// Copyright (C) 2019-2024 LNP/BP Standards Association. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::borrow::Borrow;
use std::collections::{BTreeSet, HashMap, HashSet};

use invoice::{Allocation, Amount};
use rgb::bitcoin::OutPoint as Outpoint;
use rgb::{
    AssignmentType, ContractId, GlobalStateType, OpId, OutputSeal, RevealedData, RevealedValue,
    Schema, Txid, VoidState,
};
use strict_encoding::{FieldName, StrictDecode, StrictDumb, StrictEncode};
use strict_types::{StrictVal, TypeSystem};

use crate::contract::{AssignmentsFilter, KnownState, OutputAssignment, WitnessInfo};
use crate::info::ContractInfo;
use crate::persistence::ContractStateRead;
use crate::LIB_NAME_RGB_OPS;

#[derive(Clone, Eq, PartialEq, Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum ContractError {
    /// field name {0} is unknown to the contract schema
    FieldNameUnknown(FieldName),
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display, From)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_RGB_OPS, tags = custom)]
#[display(inner)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "camelCase")
)]
pub enum AllocatedState {
    #[from(())]
    #[from(VoidState)]
    #[display("~")]
    #[strict_type(tag = 0, dumb)]
    Void,

    #[from]
    #[from(Amount)]
    #[strict_type(tag = 1)]
    Amount(RevealedValue),

    #[from]
    #[from(Allocation)]
    #[strict_type(tag = 2)]
    Data(RevealedData),
}

impl KnownState for AllocatedState {
    const IS_FUNGIBLE: bool = false;
}

impl AllocatedState {
    fn unwrap_fungible(&self) -> Amount {
        match self {
            AllocatedState::Amount(revealed_value) => (*revealed_value).into(),
            _ => panic!("unwrapping non-fungible state"),
        }
    }
}

pub type OwnedAllocation = OutputAssignment<AllocatedState>;
pub type RightsAllocation = OutputAssignment<VoidState>;
pub type FungibleAllocation = OutputAssignment<Amount>;
pub type DataAllocation = OutputAssignment<RevealedData>;

#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Display)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "camelCase")
)]
#[display(lowercase)]
pub enum OpDirection {
    Issued,
    Received,
    Sent,
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename_all = "camelCase", tag = "type")
)]
pub struct ContractOp {
    pub direction: OpDirection,
    pub ty: AssignmentType,
    pub opids: BTreeSet<OpId>,
    pub state: AllocatedState,
    pub to: BTreeSet<OutputSeal>,
    pub witness: Option<WitnessInfo>,
}

fn reduce_to_ty(allocations: impl IntoIterator<Item = OwnedAllocation>) -> AssignmentType {
    allocations
        .into_iter()
        .map(|a| a.opout.ty)
        .reduce(|ty1, ty2| {
            assert_eq!(ty1, ty2);
            ty1
        })
        .expect("empty list of allocations")
}

impl ContractOp {
    fn non_fungible_genesis(
        our_allocations: HashSet<OwnedAllocation>,
    ) -> impl ExactSizeIterator<Item = Self> {
        our_allocations.into_iter().map(|a| Self {
            direction: OpDirection::Issued,
            ty: a.opout.ty,
            opids: bset![a.opout.op],
            state: a.state,
            to: bset![a.seal],
            witness: None,
        })
    }

    fn non_fungible_sent(
        witness: WitnessInfo,
        ext_allocations: HashSet<OwnedAllocation>,
    ) -> impl ExactSizeIterator<Item = Self> {
        ext_allocations.into_iter().map(move |a| Self {
            direction: OpDirection::Sent,
            ty: a.opout.ty,
            opids: bset![a.opout.op],
            state: a.state,
            to: bset![a.seal],
            witness: Some(witness),
        })
    }

    fn non_fungible_received(
        witness: WitnessInfo,
        our_allocations: HashSet<OwnedAllocation>,
    ) -> impl ExactSizeIterator<Item = Self> {
        our_allocations.into_iter().map(move |a| Self {
            direction: OpDirection::Received,
            ty: a.opout.ty,
            opids: bset![a.opout.op],
            state: a.state,
            to: bset![a.seal],
            witness: Some(witness),
        })
    }

    fn fungible_genesis(our_allocations: HashSet<OwnedAllocation>) -> Self {
        let to = our_allocations.iter().map(|a| a.seal).collect();
        let opids = our_allocations.iter().map(|a| a.opout.op).collect();
        let issued: Amount = our_allocations
            .iter()
            .map(|a| a.state.unwrap_fungible())
            .sum();
        Self {
            direction: OpDirection::Issued,
            ty: reduce_to_ty(our_allocations),
            opids,
            state: AllocatedState::Amount(issued.into()),
            to,
            witness: None,
        }
    }

    fn fungible_sent(witness: WitnessInfo, ext_allocations: HashSet<OwnedAllocation>) -> Self {
        let opids = ext_allocations.iter().map(|a| a.opout.op).collect();
        let to = ext_allocations.iter().map(|a| a.seal).collect();
        let amount: Amount = ext_allocations
            .iter()
            .map(|a| a.state.unwrap_fungible())
            .sum();
        Self {
            direction: OpDirection::Sent,
            ty: reduce_to_ty(ext_allocations),
            opids,
            state: AllocatedState::Amount(amount.into()),
            to,
            witness: Some(witness),
        }
    }

    fn fungible_received(witness: WitnessInfo, our_allocations: HashSet<OwnedAllocation>) -> Self {
        let opids = our_allocations.iter().map(|a| a.opout.op).collect();
        let to = our_allocations.iter().map(|a| a.seal).collect();
        let amount: Amount = our_allocations
            .iter()
            .map(|a| a.state.unwrap_fungible())
            .sum();
        Self {
            direction: OpDirection::Received,
            ty: reduce_to_ty(our_allocations),
            opids,
            state: AllocatedState::Amount(amount.into()),
            to,
            witness: Some(witness),
        }
    }
}

/// Data of a contract.
#[derive(Clone, Eq, PartialEq, Debug)]
pub struct ContractData<S: ContractStateRead> {
    pub state: S,
    pub schema: Schema,
    pub types: TypeSystem,
    pub info: ContractInfo,
}

impl<S: ContractStateRead> ContractData<S> {
    pub fn contract_id(&self) -> ContractId { self.state.contract_id() }

    /// # Panics
    ///
    /// If data is corrupted.
    pub fn global(&self, name: impl Into<FieldName>) -> impl Iterator<Item = StrictVal> + '_ {
        self.global_raw(self.schema.global_type(name))
    }

    /// # Panics
    ///
    /// If data is corrupted.
    pub fn global_raw(&self, type_id: GlobalStateType) -> impl Iterator<Item = StrictVal> + '_ {
        let global_details = self
            .schema
            .global_types
            .get(&type_id)
            .expect("cannot find type ID in schema global types");
        self.state
            .global(type_id)
            .expect("cannot find type ID in global state")
            .map(|entry| {
                self.types
                    .strict_deserialize_type(
                        global_details.global_state_schema.sem_id,
                        entry.borrow().data().as_slice(),
                    )
                    .expect("unvalidated contract data in stash")
                    .unbox()
            })
    }

    fn extract_state<'c, A, U>(
        &'c self,
        state: impl IntoIterator<Item = &'c OutputAssignment<A>> + 'c,
        type_id: AssignmentType,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = OutputAssignment<U>> + 'c, ContractError>
    where
        A: Clone + KnownState + 'c,
        U: From<A> + KnownState + 'c,
    {
        Ok(self
            .extract_state_unfiltered(state, type_id)?
            .filter(move |outp| filter.should_include(outp.seal, outp.witness)))
    }

    fn extract_state_unfiltered<'c, A, U>(
        &'c self,
        state: impl IntoIterator<Item = &'c OutputAssignment<A>> + 'c,
        type_id: AssignmentType,
    ) -> Result<impl Iterator<Item = OutputAssignment<U>> + 'c, ContractError>
    where
        A: Clone + KnownState + 'c,
        U: From<A> + KnownState + 'c,
    {
        Ok(state
            .into_iter()
            .filter(move |outp| outp.opout.ty == type_id)
            .cloned()
            .map(OutputAssignment::<A>::transmute))
    }

    pub fn rights<'c>(
        &'c self,
        name: impl Into<FieldName>,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = RightsAllocation> + 'c, ContractError> {
        let type_id = self.schema.assignment_type(name);
        self.rights_raw(type_id, filter)
    }

    pub fn rights_raw<'c>(
        &'c self,
        type_id: AssignmentType,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = RightsAllocation> + 'c, ContractError> {
        self.extract_state(self.state.rights_all(), type_id, filter)
    }

    pub fn fungible<'c>(
        &'c self,
        name: impl Into<FieldName>,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = FungibleAllocation> + 'c, ContractError> {
        let type_id = self.schema.assignment_type(name);
        self.fungible_raw(type_id, filter)
    }

    pub fn fungible_raw<'c>(
        &'c self,
        type_id: AssignmentType,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = FungibleAllocation> + 'c, ContractError> {
        self.extract_state(self.state.fungible_all(), type_id, filter)
    }

    pub fn data<'c>(
        &'c self,
        name: impl Into<FieldName>,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = DataAllocation> + 'c, ContractError> {
        let type_id = self.schema.assignment_type(name);
        self.data_raw(type_id, filter)
    }

    pub fn data_raw<'c>(
        &'c self,
        type_id: AssignmentType,
        filter: impl AssignmentsFilter + 'c,
    ) -> Result<impl Iterator<Item = DataAllocation> + 'c, ContractError> {
        self.extract_state(self.state.data_all(), type_id, filter)
    }

    pub fn allocations<'c>(
        &'c self,
        filter: impl AssignmentsFilter + Copy + 'c,
    ) -> impl Iterator<Item = OwnedAllocation> + 'c {
        fn f<'a, S, U>(
            filter: impl AssignmentsFilter + 'a,
            state: impl IntoIterator<Item = &'a OutputAssignment<S>> + 'a,
        ) -> impl Iterator<Item = OutputAssignment<U>> + 'a
        where
            S: Clone + KnownState + 'a,
            U: From<S> + KnownState + 'a,
        {
            state
                .into_iter()
                .filter(move |outp| filter.should_include(outp.seal, outp.witness))
                .cloned()
                .map(OutputAssignment::<S>::transmute)
        }

        f(filter, self.state.rights_all())
            .chain(f(filter, self.state.fungible_all()))
            .chain(f(filter, self.state.data_all()))
    }

    pub fn outpoint_allocations(
        &self,
        outpoint: Outpoint,
    ) -> impl Iterator<Item = OwnedAllocation> + '_ {
        self.allocations(outpoint)
    }

    pub fn history(
        &self,
        filter_outpoints: impl AssignmentsFilter + Clone,
        filter_witnesses: impl AssignmentsFilter + Clone,
    ) -> Vec<ContractOp> {
        self.history_fungible(filter_outpoints.clone(), filter_witnesses.clone())
            .into_iter()
            .chain(self.history_rights(filter_outpoints.clone(), filter_witnesses.clone()))
            .chain(self.history_data(filter_outpoints.clone(), filter_witnesses.clone()))
            .collect()
    }

    fn operations<'c, T: KnownState + 'c, I: Iterator<Item = &'c OutputAssignment<T>>>(
        &'c self,
        state: impl Fn(&'c S) -> I,
        filter_outpoints: impl AssignmentsFilter,
        filter_witnesses: impl AssignmentsFilter,
    ) -> Vec<ContractOp>
    where
        AllocatedState: From<T>,
    {
        // get all allocations which ever belonged to this wallet and store them by witness id
        let mut allocations_our_outpoint = state(&self.state)
            .filter(move |outp| filter_outpoints.should_include(outp.seal, outp.witness))
            .fold(HashMap::<_, HashSet<_>>::new(), |mut map, a| {
                map.entry(a.witness)
                    .or_default()
                    .insert(a.clone().transmute::<AllocatedState>());
                map
            });
        // get all allocations which has a witness transaction belonging to this wallet
        let mut allocations_our_witness = state(&self.state)
            .filter(move |outp| filter_witnesses.should_include(outp.seal, outp.witness))
            .fold(HashMap::<_, HashSet<_>>::new(), |mut map, a| {
                let witness = a.witness.expect(
                    "all empty witnesses must be already filtered out by wallet.filter_witness()",
                );
                map.entry(witness)
                    .or_default()
                    .insert(a.clone().transmute::<AllocatedState>());
                map
            });

        // gather all witnesses from both sets
        let mut witness_ids = allocations_our_witness
            .keys()
            .cloned()
            .collect::<BTreeSet<_>>();
        witness_ids.extend(allocations_our_outpoint.keys().filter_map(|x| *x));

        // reconstruct contract history from the wallet perspective
        let mut ops = Vec::with_capacity(witness_ids.len() + 1);
        // add allocations with no witness to the beginning of the history
        if let Some(genesis_allocations) = allocations_our_outpoint.remove(&None) {
            if T::IS_FUNGIBLE {
                ops.push(ContractOp::fungible_genesis(genesis_allocations));
            } else {
                ops.extend(ContractOp::non_fungible_genesis(genesis_allocations));
            }
        }
        for witness_id in witness_ids {
            let our_outpoint = allocations_our_outpoint.remove(&Some(witness_id));
            let our_witness = allocations_our_witness.remove(&witness_id);
            let witness_info = self.witness_info(witness_id).expect(
                "witness id was returned from the contract state above, so it must be there",
            );
            match (our_outpoint, our_witness) {
                // we own both allocation and witness transaction: these allocations are changes and
                // outgoing payments. The difference between the change and the payments are whether
                // a specific allocation is listed in the first tuple pattern field.
                (Some(our_allocations), Some(all_allocations)) => {
                    // all_allocations - our_allocations = external payments
                    let ext_allocations = all_allocations
                        .difference(&our_allocations)
                        .cloned()
                        .collect::<HashSet<_>>();
                    // This was an extra state transition with no external payment
                    if ext_allocations.is_empty() {
                        continue;
                    }
                    if T::IS_FUNGIBLE {
                        ops.push(ContractOp::fungible_sent(witness_info, ext_allocations))
                    } else {
                        ops.extend(ContractOp::non_fungible_sent(witness_info, ext_allocations))
                    }
                }
                // the same as above, but the payment has no change
                (None, Some(ext_allocations)) => {
                    if T::IS_FUNGIBLE {
                        ops.push(ContractOp::fungible_sent(witness_info, ext_allocations))
                    } else {
                        ops.extend(ContractOp::non_fungible_sent(witness_info, ext_allocations))
                    }
                }
                // we own allocation but the witness transaction was made by other wallet:
                // this is an incoming payment to us.
                (Some(our_allocations), None) => {
                    if T::IS_FUNGIBLE {
                        ops.push(ContractOp::fungible_received(witness_info, our_allocations))
                    } else {
                        ops.extend(ContractOp::non_fungible_received(witness_info, our_allocations))
                    }
                }
                // these can't get into the `witness_ids` due to the used filters
                (None, None) => unreachable!("broken allocation filters"),
            };
        }

        ops
    }

    pub fn history_fungible(
        &self,
        filter_outpoints: impl AssignmentsFilter,
        filter_witnesses: impl AssignmentsFilter,
    ) -> Vec<ContractOp> {
        self.operations(|state| state.fungible_all(), filter_outpoints, filter_witnesses)
    }

    pub fn history_rights(
        &self,
        filter_outpoints: impl AssignmentsFilter,
        filter_witnesses: impl AssignmentsFilter,
    ) -> Vec<ContractOp> {
        self.operations(|state| state.rights_all(), filter_outpoints, filter_witnesses)
    }

    pub fn history_data(
        &self,
        filter_outpoints: impl AssignmentsFilter,
        filter_witnesses: impl AssignmentsFilter,
    ) -> Vec<ContractOp> {
        self.operations(|state| state.data_all(), filter_outpoints, filter_witnesses)
    }

    pub fn witness_info(&self, witness_id: Txid) -> Option<WitnessInfo> {
        let ord = self.state.witness_ord(witness_id)?;
        Some(WitnessInfo {
            id: witness_id,
            ord,
        })
    }
}