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
// RGB standard library
// Written in 2020 by
//     Dr. Maxim Orlovsky <orlovsky@pandoracore.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the MIT License
// along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use core::ops::Deref;

use lnpbp::rgb::schema::{
    constants::*,
    script::{Procedure, StandardProcedure},
    AssignmentAction, Bits, DataFormat, GenesisAction, GenesisSchema,
    Occurences, Schema, StateFormat, StateSchema, TransitionAction,
    TransitionSchema,
};

use crate::error::ServiceErrorDomain;
use crate::type_map;

#[derive(Debug, Display, Error, From)]
#[display(Debug)]
pub enum SchemaError {
    NotAllFieldsPresent,

    WrongSchemaId,
}

impl From<SchemaError> for ServiceErrorDomain {
    fn from(err: SchemaError) -> Self {
        ServiceErrorDomain::Schema(format!("{}", err))
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[display(Debug)]
#[repr(u16)]
pub enum FieldType {
    Name,
    Description,
    Data,
    DataFormat,
    Timestamp,
    LockDescriptor,
    LockUtxo,
    BurnUtxo,
    Salt,
    NftSource,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[display(Debug)]
#[repr(u16)]
pub enum OwnedRightsType {
    Inflation,
    Ownership,
    Renomination,
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display)]
#[display(Debug)]
#[repr(u16)]
pub enum TransitionType {
    Issue,
    Transfer,
    Engraving,
    Renomination,
    RightsSplit,
}

pub fn schema() -> Schema {
    use Occurences::*;

    Schema {
        rgb_features: none!(),
        root_id: none!(),
        genesis: GenesisSchema {
            metadata: type_map! {
                FieldType::Name => Once,
                FieldType::Description => NoneOrOnce,
                FieldType::Data => NoneOrMore,
                FieldType::DataFormat => NoneOrOnce,
                // Proof of reserves UTXO
                FieldType::LockUtxo => NoneOrMore,
                // Proof of reserves scriptPubkey descriptor used for
                // verification
                FieldType::LockDescriptor => NoneOrUpTo(32),
                FieldType::Timestamp => Once,
                FieldType::NftSource => NoneOrMore,
                FieldType::Salt => Once
            },
            owned_rights: type_map! {
                OwnedRightsType::Inflation => NoneOrOnce,
                OwnedRightsType::Renomination => NoneOrOnce,
                OwnedRightsType::Ownership => OnceOrMore
            },
            public_rights: none!(),
            abi: bmap! {
                // Here we validate hash uniqueness of NftSource values and that
                // there is always one ownership state per NftSource matching
                // its hash
                // and verification of proof of reserves
                GenesisAction::Validate => Procedure::Embedded(StandardProcedure::NonfungibleInflation)
            },
        },
        extensions: bmap! {},
        transitions: type_map! {
            TransitionType::Issue => TransitionSchema {
                metadata: type_map! {
                    // Proof of reserves UTXO
                    FieldType::LockUtxo => NoneOrMore,
                    // Proof of reserves scriptPubkey descriptor used for
                    // verification
                    FieldType::LockDescriptor => NoneOrUpTo(32),
                    FieldType::NftSource => NoneOrMore,
                    FieldType::Salt => Once
                },
                closes: type_map! {
                    OwnedRightsType::Inflation => Once
                },
                owned_rights: type_map! {
                    OwnedRightsType::Inflation => NoneOrOnce,
                    OwnedRightsType::Ownership => OnceOrMore
                },
                public_rights: none!(),
                abi: bmap! {
                    // Here we validate hash uniqueness of NftSource values and that
                    // there is always one ownership state per NftSource matching
                    // its hash, plus the fact that
                    // count(in(inflation)) >= count(out(inflation), out(nft_source))
                    // and verification of proof of reserves
                    TransitionAction::Validate => Procedure::Embedded(StandardProcedure::NonfungibleInflation)
                }
            },
            TransitionType::Transfer => TransitionSchema {
                metadata: type_map! {
                    // By default, use 0
                    FieldType::Salt => Once
                },
                closes: type_map! {
                    OwnedRightsType::Ownership => OnceOrMore
                },
                owned_rights: type_map! {
                    OwnedRightsType::Ownership => OnceOrMore
                },
                public_rights: none!(),
                abi: none!()
            },
            // One engraving per set of tokens
            TransitionType::Engraving => TransitionSchema {
                metadata: type_map! {
                    FieldType::Data => NoneOrMore,
                    FieldType::DataFormat => NoneOrOnce,
                    // By default, use 0
                    FieldType::Salt => Once
                },
                closes: type_map! {
                    OwnedRightsType::Ownership => OnceOrMore
                },
                owned_rights: type_map! {
                    OwnedRightsType::Ownership => OnceOrMore
                },
                public_rights: none!(),
                abi: none!()
            },
            TransitionType::Renomination => TransitionSchema {
                metadata: type_map! {
                    FieldType::Name => NoneOrOnce,
                    FieldType::Description => NoneOrOnce,
                    FieldType::Data => NoneOrMore,
                    FieldType::DataFormat => NoneOrOnce
                },
                closes: type_map! {
                    OwnedRightsType::Renomination => Once
                },
                owned_rights: type_map! {
                    OwnedRightsType::Renomination => NoneOrOnce
                },
                public_rights: none!(),
                abi: none!()
            },
            // Allows split of rights if they were occasionally allocated to the
            // same UTXO, for instance both assets and issuance right. Without
            // this type of transition either assets or inflation rights will be
            // lost.
            TransitionType::RightsSplit => TransitionSchema {
                metadata: type_map! {
                    FieldType::Salt => Once
                },
                closes: type_map! {
                    OwnedRightsType::Inflation => NoneOrMore,
                    OwnedRightsType::Ownership => NoneOrMore,
                    OwnedRightsType::Renomination => NoneOrOnce
                },
                owned_rights: type_map! {
                    OwnedRightsType::Inflation => NoneOrMore,
                    OwnedRightsType::Ownership => NoneOrMore,
                    OwnedRightsType::Renomination => NoneOrOnce
                },
                public_rights: none!(),
                abi: bmap! {
                    // We must allocate exactly one or none rights per each
                    // right used as input (i.e. closed seal); plus we need to
                    // control that sum of inputs is equal to the sum of outputs
                    // for each of state types having assigned confidential
                    // amounts
                    TransitionAction::Validate => Procedure::Embedded(StandardProcedure::RightsSplit)
                }
            }
        },
        field_types: type_map! {
            FieldType::Name => DataFormat::String(256),
            FieldType::Description => DataFormat::String(core::u16::MAX),
            FieldType::Data => DataFormat::Bytes(core::u16::MAX),
            FieldType::DataFormat => DataFormat::Unsigned(Bits::Bit16, 0, core::u16::MAX as u128),
            // While UNIX timestamps allow negative numbers; in context of RGB
            // Schema, assets can't be issued in the past before RGB or Bitcoin
            // even existed; so we prohibit all the dates before RGB release
            // This timestamp is equal to 10/10/2020 @ 2:37pm (UTC) - the same
            // as for RGB-20 standard.
            FieldType::Timestamp => DataFormat::Integer(Bits::Bit64, 1602340666, core::i64::MAX as i128),
            FieldType::LockUtxo => DataFormat::TxOutPoint,
            FieldType::LockDescriptor => DataFormat::String(core::u16::MAX),
            FieldType::BurnUtxo => DataFormat::TxOutPoint,
            // This type is used to "shift" unique tokens ids if there was a
            // collision between them
            FieldType::Salt => DataFormat::Unsigned(Bits::Bit32, 0, core::u32::MAX as u128),
            // Hash of these data serves as a unique NFT identifier;
            // if NFT contains no intrinsic data than simply put any unique
            // value here (like counter value, increased with each token);
            // it must be unique only within single issuance transition
            FieldType::NftSource => DataFormat::Bytes(core::u16::MAX)
        },
        owned_right_types: type_map! {
            OwnedRightsType::Inflation => StateSchema {
                // How much issuer can issue tokens on this path
                format: StateFormat::CustomData(DataFormat::Unsigned(Bits::Bit64, 0, core::u64::MAX as u128)),
                abi: none!()
            },
            OwnedRightsType::Ownership => StateSchema {
                // This is unique token identifier, which is
                // SHA256(SHA256(nft_source_state), issue_transition_id)
                // convoluted to 32-bits with XOR operation and then XORed with
                // salt value from state transition metadata.
                // NB: It is unique inside single state transition only, not
                // globally. For global unique id use non-convoluted hash value.
                format: StateFormat::CustomData(DataFormat::Unsigned(Bits::Bit32, 0, core::u32::MAX as u128)),
                abi: bmap! {
                    // Here we ensure that each unique state value is
                    // transferred once and only once (using "salt" value for
                    // collision resoultion)
                    AssignmentAction::Validate => Procedure::Embedded(StandardProcedure::IdentityTransfer)
                }
            },
            OwnedRightsType::Renomination => StateSchema {
                format: StateFormat::Declarative,
                abi: none!()
            }
        },
        public_right_types: none!(),
    }
}

impl Deref for FieldType {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        match self {
            // Nomination fields:
            FieldType::Name => &1,
            FieldType::Description => &2,
            FieldType::Timestamp => &4,
            FieldType::Data => &0x10,
            FieldType::DataFormat => &0x11,
            // Token fields:
            FieldType::Salt => &0x20,
            FieldType::NftSource => &0x21,
            // Proof-of-burn fields:
            FieldType::BurnUtxo => &FIELD_TYPE_BURN_UTXO,
            // Prood-of-reserves fields:
            FieldType::LockDescriptor => &FIELD_TYPE_LOCK_DESCRIPTOR,
            FieldType::LockUtxo => &FIELD_TYPE_LOCK_UTXO,
        }
    }
}

impl Deref for OwnedRightsType {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        match self {
            // Nomination rights:
            OwnedRightsType::Renomination => &1,
            // Inflation-control-related rights:
            OwnedRightsType::Inflation => &STATE_TYPE_NONFUNGIBLE_INFLATION,
            OwnedRightsType::Ownership => &STATE_TYPE_NONFUNGIBLE_OWNERSHIP,
        }
    }
}

impl Deref for TransitionType {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        match self {
            // Asset transfers:
            TransitionType::Transfer => &0x00,
            TransitionType::Engraving => &0x01,
            // Nomination transitions:
            TransitionType::Renomination => &0x10,
            // Inflation-related transitions:
            TransitionType::Issue => &TRANSITION_TYPE_FUNGIBLE_ISSUE,
            TransitionType::RightsSplit => &0xF0,
        }
    }
}