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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// Copyright 2021-2022 Farcaster Devs
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

//! Defines types used to characterize a swap and behaviours a blockchain must implement to
//! participate in a swap, either as an arbitrating or an accordant blockchain.
//!
//! A blockchain must identify itself with a 32 bits indetifier as defined in [SLIP
//! 44](https://github.com/satoshilabs/slips/blob/master/slip-0044.md#slip-0044--registered-coin-types-for-bip-0044)
//! or must not conflict with any registered entity.

use std::error;
use std::fmt::{self, Debug};
use std::io;
use std::str::FromStr;

use strict_encoding::{StrictDecode, StrictEncode};
use thiserror::Error;

use crate::consensus::{self, deserialize, serialize, CanonicalBytes, Decodable, Encodable};
use crate::transaction::{Buyable, Cancelable, Fundable, Lockable, Punishable, Refundable};

/// The list of supported blockchains (coins) by this library.
#[derive(
    Debug,
    Clone,
    Copy,
    Hash,
    PartialEq,
    Eq,
    Parser,
    Display,
    Serialize,
    Deserialize,
    StrictEncode,
    StrictDecode,
)]
#[display(Debug)]
pub enum Blockchain {
    /// The Bitcoin (BTC) blockchain.
    Bitcoin,
    /// The Monero (XMR) blockchain.
    Monero,
}

impl FromStr for Blockchain {
    type Err = consensus::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Bitcoin" | "bitcoin" | "btc" | "BTC" => Ok(Blockchain::Bitcoin),
            "Monero" | "monero" | "xmr" | "XMR" => Ok(Blockchain::Monero),
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

impl Decodable for Blockchain {
    fn consensus_decode<D: io::Read>(d: &mut D) -> Result<Self, consensus::Error> {
        match Decodable::consensus_decode(d)? {
            0x80000000u32 => Ok(Blockchain::Bitcoin),
            0x80000080u32 => Ok(Blockchain::Monero),
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

impl Encodable for Blockchain {
    fn consensus_encode<W: io::Write>(&self, writer: &mut W) -> Result<usize, io::Error> {
        match self {
            Blockchain::Bitcoin => 0x80000000u32.consensus_encode(writer),
            Blockchain::Monero => 0x80000080u32.consensus_encode(writer),
        }
    }
}

/// Fix the types for all arbitrating transactions needed for the swap: [`Fundable`], [`Lockable`],
/// [`Buyable`], [`Cancelable`], [`Refundable`], and [`Punishable`] transactions.
///
/// This injects concrete types to manage all the transactions.
pub trait Transactions {
    type Addr;
    type Amt;
    type Tx;
    type Px;
    type Out: Eq;
    type Ti;
    type Ms;
    type Pk;
    type Si;

    /// Defines the type for the `funding (a)` transaction
    type Funding: Fundable<Self::Tx, Self::Out, Self::Addr, Self::Pk>;
    /// Defines the type for the `lock (b)` transaction
    type Lock: Lockable<
        Self::Addr,
        Self::Tx,
        Self::Px,
        Self::Out,
        Self::Amt,
        Self::Ti,
        Self::Ms,
        Self::Pk,
        Self::Si,
    >;
    /// Defines the type for the `buy (c)` transaction
    type Buy: Buyable<
        Self::Addr,
        Self::Tx,
        Self::Px,
        Self::Out,
        Self::Amt,
        Self::Ti,
        Self::Ms,
        Self::Pk,
        Self::Si,
    >;
    /// Defines the type for the `cancel (d)` transaction
    type Cancel: Cancelable<
        Self::Addr,
        Self::Tx,
        Self::Px,
        Self::Out,
        Self::Amt,
        Self::Ti,
        Self::Ms,
        Self::Pk,
        Self::Si,
    >;
    /// Defines the type for the `refund (e)` transaction
    type Refund: Refundable<
        Self::Addr,
        Self::Tx,
        Self::Px,
        Self::Out,
        Self::Amt,
        Self::Ti,
        Self::Ms,
        Self::Pk,
        Self::Si,
    >;
    /// Defines the type for the `punish (f)` transaction
    type Punish: Punishable<
        Self::Addr,
        Self::Tx,
        Self::Px,
        Self::Out,
        Self::Amt,
        Self::Ti,
        Self::Ms,
        Self::Pk,
        Self::Si,
    >;
}

/// A fee strategy to be applied on an arbitrating transaction. As described in the specifications
/// a fee strategy can be: fixed or range. When the fee strategy allows multiple possibilities, a
/// [`FeePriority`] is used to determine what to apply.
///
/// A fee strategy is included in a deal, so Alice and Bob can verify that transactions are valid
/// upon reception by the other participant.
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum FeeStrategy<T> {
    /// A fixed strategy with the exact amount to set.
    Fixed(T),
    /// A range with a minimum and maximum (inclusive) possible fees.
    #[cfg(feature = "fee_range")]
    #[cfg_attr(docsrs, doc(cfg(feature = "fee_range")))]
    Range { min_inc: T, max_inc: T },
}

impl<T> FeeStrategy<T>
where
    T: PartialEq + PartialOrd,
{
    pub fn check(&self, value: &T) -> bool {
        match self {
            Self::Fixed(fee_strat) => value == fee_strat,
            // Check in range including min and max bounds
            #[cfg(feature = "fee_range")]
            Self::Range { min_inc, max_inc } => value >= min_inc && value <= max_inc,
        }
    }
}

impl<T> FromStr for FeeStrategy<T>
where
    T: FromStr,
{
    type Err = consensus::Error;

    #[allow(unused_mut)]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts: Vec<&str> = s.split('-').collect();
        match parts.len() {
            1 => match s.parse::<T>() {
                Ok(x) => Ok(Self::Fixed(x)),
                Err(_) => Err(consensus::Error::ParseFailed("Failed parsing FeeStrategy")),
            },
            #[cfg(feature = "fee_range")]
            2 => {
                let max_inc = parts
                    .pop()
                    .expect("lenght is checked")
                    .parse::<T>()
                    .map_err(|_| consensus::Error::ParseFailed("Failed parsing FeeStrategy"))?;
                let min_inc = parts
                    .pop()
                    .expect("lenght is checked")
                    .parse::<T>()
                    .map_err(|_| consensus::Error::ParseFailed("Failed parsing FeeStrategy"))?;
                Ok(Self::Range { min_inc, max_inc })
            }
            _ => Err(consensus::Error::ParseFailed("Failed parsing FeeStrategy")),
        }
    }
}

impl<T> fmt::Display for FeeStrategy<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            FeeStrategy::Fixed(t) => write!(f, "{}", t),
            #[cfg(feature = "fee_range")]
            FeeStrategy::Range { min_inc, max_inc } => {
                write!(f, "{}-{}", min_inc, max_inc)
            }
        }
    }
}

impl<T> Encodable for FeeStrategy<T>
where
    T: CanonicalBytes,
{
    fn consensus_encode<W: io::Write>(&self, writer: &mut W) -> Result<usize, io::Error> {
        match self {
            FeeStrategy::Fixed(t) => {
                0x01u8.consensus_encode(writer)?;
                Ok(t.as_canonical_bytes().consensus_encode(writer)? + 1)
            }
            #[cfg(feature = "fee_range")]
            FeeStrategy::Range { min_inc, max_inc } => {
                let mut len = 0x02u8.consensus_encode(writer)?;
                len += min_inc.as_canonical_bytes().consensus_encode(writer)?;
                Ok(len + max_inc.as_canonical_bytes().consensus_encode(writer)?)
            }
        }
    }
}

impl<T> Decodable for FeeStrategy<T>
where
    T: CanonicalBytes,
{
    fn consensus_decode<D: io::Read>(d: &mut D) -> Result<Self, consensus::Error> {
        match Decodable::consensus_decode(d)? {
            0x01u8 => Ok(FeeStrategy::Fixed(T::from_canonical_bytes(
                unwrap_vec_ref!(d).as_ref(),
            )?)),
            #[cfg(feature = "fee_range")]
            0x02u8 => {
                let min_inc = T::from_canonical_bytes(unwrap_vec_ref!(d).as_ref())?;
                let max_inc = T::from_canonical_bytes(unwrap_vec_ref!(d).as_ref())?;
                Ok(FeeStrategy::Range { min_inc, max_inc })
            }
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

impl<T> CanonicalBytes for FeeStrategy<T>
where
    T: CanonicalBytes,
{
    fn as_canonical_bytes(&self) -> Vec<u8> {
        serialize(self)
    }

    fn from_canonical_bytes(bytes: &[u8]) -> Result<Self, consensus::Error>
    where
        Self: Sized,
    {
        deserialize(bytes)
    }
}

impl_strict_encoding!(FeeStrategy<T>, T: CanonicalBytes);

/// Define the type of errors a fee strategy can encounter during calculation, application, and
/// validation of fees on a partial transaction.
#[derive(Error, Debug)]
pub enum FeeStrategyError {
    /// Missing metadata on inputs to retreive the amount of asset available.
    #[error("Missing metadata inputs to retreive available amount")]
    MissingInputsMetadata,
    /// Fee amount is too low and does not match the fee strategy requirements.
    #[error("Fee amount is too low")]
    AmountOfFeeTooLow,
    /// Fee amount is too high and does not match the fee strategy requirements.
    #[error("Fee amount is too high")]
    AmountOfFeeTooHigh,
    /// Not enough assets to cover the fees.
    #[error("Not enough assets to cover the fees")]
    NotEnoughAssets,
    /// Any fee strategy error not part of this list.
    #[error("Other: {0}")]
    Other(Box<dyn error::Error + Sync + Send>),
}

impl FeeStrategyError {
    /// Creates a new fee strategy error of type other with an arbitrary payload.
    pub fn new<E>(error: E) -> Self
    where
        E: Into<Box<dyn error::Error + Send + Sync>>,
    {
        Self::Other(error.into())
    }

    /// Consumes the `FeeStrategyError`, returning its inner error (if any).
    ///
    /// If this [`FeeStrategyError`] was constructed via [`new`] then this function will return [`Some`],
    /// otherwise it will return [`None`].
    ///
    /// [`new`]: FeeStrategyError::new
    ///
    pub fn into_inner(self) -> Option<Box<dyn error::Error + Sync + Send>> {
        match self {
            Self::Other(error) => Some(error),
            _ => None,
        }
    }
}

/// Defines how to set the fee when a [`FeeStrategy`] allows multiple possibilities.
#[derive(Debug, Clone, Copy, Display, Serialize, Deserialize)]
#[display(Debug)]
pub enum FeePriority {
    /// Set the fee at the minimum allowed by the strategy.
    Low,
    /// Set the fee at the maximum allowed by the strategy.
    High,
}

impl Decodable for FeePriority {
    fn consensus_decode<D: io::Read>(d: &mut D) -> Result<Self, consensus::Error> {
        match Decodable::consensus_decode(d)? {
            0x01u8 => Ok(FeePriority::Low),
            0x02u8 => Ok(FeePriority::High),
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

impl Encodable for FeePriority {
    fn consensus_encode<W: io::Write>(&self, writer: &mut W) -> Result<usize, io::Error> {
        match self {
            FeePriority::Low => 0x01u8.consensus_encode(writer),
            FeePriority::High => 0x02u8.consensus_encode(writer),
        }
    }
}

impl FromStr for FeePriority {
    type Err = consensus::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Low" | "low" => Ok(FeePriority::Low),
            "High" | "high" => Ok(FeePriority::High),
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

/// Enable fee management for an arbitrating blockchain. The [`Fee`] trait declares a fee unit used
/// in fee strategies and an amount used in transactions. Implementing this trait allow to set and
/// verify fees on transactions given a strategy and a priority.
///
/// The fee to apply on transactions is carried in the [`Deal`](crate::trade::Deal) through a
/// [`FeeStrategy`], in case the fee strategy allow multiple values a [`FeePriority`] is used to
/// fix the amount.
///
/// ```
/// use bitcoin::Amount;
/// use bitcoin::util::psbt::PartiallySignedTransaction;
/// use farcaster_core::crypto::SharedKeyId;
/// use farcaster_core::blockchain::{Fee, FeeStrategy, FeePriority, FeeStrategyError};
///
/// pub struct Psbt(PartiallySignedTransaction);
/// pub struct SatPerBytes(f32);
///
/// impl Fee for Psbt {
///     type FeeUnit = SatPerBytes;
///     type Amount = Amount;
///
///     fn set_fee(
///         &mut self, strategy:
///         &FeeStrategy<SatPerBytes>,
///         politic: FeePriority
///     ) -> Result<Self::Amount, FeeStrategyError> {
///         todo!()
///     }
///
///     fn validate_fee(
///         &self,
///         strategy: &FeeStrategy<SatPerBytes>
///     ) -> Result<bool, FeeStrategyError> {
///         todo!()
///     }
/// }
/// ```
pub trait Fee {
    /// Type for describing the fee rate of a blockchain.
    type FeeUnit;

    /// Type of asset quantity.
    type Amount;

    /// Calculates and sets the fee on the given transaction and return the amount of fee set in
    /// the blockchain native amount format.
    fn set_fee(
        &mut self,
        strategy: &FeeStrategy<Self::FeeUnit>,
        politic: FeePriority,
    ) -> Result<Self::Amount, FeeStrategyError>;

    /// Validates that the fee for the given transaction are set accordingly to the strategy.
    fn validate_fee(&self, strategy: &FeeStrategy<Self::FeeUnit>)
        -> Result<bool, FeeStrategyError>;
}

impl FromStr for Network {
    type Err = consensus::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Mainnet" | "mainnet" => Ok(Network::Mainnet),
            "Testnet" | "testnet" => Ok(Network::Testnet),
            "Local" | "local" => Ok(Network::Local),
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

/// Defines a blockchain network, identifies in which context the system interacts with the
/// blockchain.
///
/// When adding support for a new blockchain in the library a [`From`] implementation must be
/// provided such that it is possible to know what blockchain network to use for each of the three
/// generic contexts: `mainnet`, `testnet`, and `local`.
///
/// ```rust
/// use farcaster_core::blockchain::Network;
///
/// pub enum MyNet {
///     MyNet,
///     Test,
///     Regtest,
/// }
///
/// impl From<Network> for MyNet {
///     fn from(net: Network) -> Self {
///         match net {
///             Network::Mainnet => Self::MyNet,
///             Network::Testnet => Self::Test,
///             Network::Local => Self::Regtest,
///         }
///     }
/// }
/// ```
#[derive(
    Copy, PartialEq, Eq, PartialOrd, Ord, Clone, Hash, Debug, Display, Serialize, Deserialize,
)]
#[display(Debug)]
pub enum Network {
    /// Valuable, real, assets on its production network.
    Mainnet,
    /// Non-valuable assets on its online test networks.
    Testnet,
    /// Non-valuable assets on offline test network.
    Local,
}

impl Encodable for Network {
    fn consensus_encode<W: io::Write>(&self, writer: &mut W) -> Result<usize, io::Error> {
        match self {
            Network::Mainnet => 0x01u8.consensus_encode(writer),
            Network::Testnet => 0x02u8.consensus_encode(writer),
            Network::Local => 0x03u8.consensus_encode(writer),
        }
    }
}

impl Decodable for Network {
    fn consensus_decode<D: io::Read>(d: &mut D) -> Result<Self, consensus::Error> {
        match Decodable::consensus_decode(d)? {
            0x01u8 => Ok(Network::Mainnet),
            0x02u8 => Ok(Network::Testnet),
            0x03u8 => Ok(Network::Local),
            _ => Err(consensus::Error::UnknownType),
        }
    }
}

impl_strict_encoding!(Network);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bitcoin::fee::SatPerKvB;

    #[test]
    fn parse_fee_politic() {
        for s in ["High", "high", "Low", "low"].iter() {
            let parse = FeePriority::from_str(s);
            assert!(parse.is_ok());
        }
    }

    #[test]
    fn parse_network() {
        for s in ["Mainnet", "mainnet", "Testnet", "testnet", "Local", "local"].iter() {
            let parse = Network::from_str(s);
            assert!(parse.is_ok());
        }
    }

    #[test]
    fn bitcoin_network_conversion() {
        assert_eq!(Network::from(bitcoin::Network::Bitcoin), Network::Mainnet);
        assert_eq!(Network::from(bitcoin::Network::Testnet), Network::Testnet);
        assert_eq!(Network::from(bitcoin::Network::Signet), Network::Testnet);
        assert_eq!(Network::from(bitcoin::Network::Regtest), Network::Local);
        assert_eq!(
            bitcoin::Network::from(Network::Mainnet),
            bitcoin::Network::Bitcoin
        );
        assert_eq!(
            Into::<bitcoin::Network>::into(Network::Mainnet),
            bitcoin::Network::Bitcoin,
        );
        assert_eq!(
            bitcoin::Network::from(Network::Testnet),
            bitcoin::Network::Testnet
        );
        assert_eq!(
            Into::<bitcoin::Network>::into(Network::Testnet),
            bitcoin::Network::Testnet,
        );
        assert_eq!(
            bitcoin::Network::from(Network::Local),
            bitcoin::Network::Regtest
        );
        assert_eq!(
            Into::<bitcoin::Network>::into(Network::Local),
            bitcoin::Network::Regtest,
        );
    }

    #[test]
    fn monero_network_conversion() {
        assert_eq!(
            monero::Network::from(Network::Mainnet),
            monero::Network::Mainnet
        );
        assert_eq!(
            monero::Network::from(Network::Testnet),
            monero::Network::Stagenet
        );
        assert_eq!(
            monero::Network::from(Network::Local),
            monero::Network::Mainnet
        );
    }

    #[test]
    fn fee_strategy_display() {
        let strategy = FeeStrategy::Fixed(SatPerKvB::from_sat(100));
        assert_eq!(&format!("{}", strategy), "100 satoshi/kvB");
        #[cfg(feature = "fee_range")]
        {
            let strategy = FeeStrategy::Range {
                min_inc: SatPerKvB::from_sat(50),
                max_inc: SatPerKvB::from_sat(150),
            };
            assert_eq!(&format!("{}", strategy), "50 satoshi/kvB-150 satoshi/kvB")
        }
    }

    #[test]
    fn fee_strategy_parse() {
        let strings = [
            "100 satoshi/kvB",
            #[cfg(feature = "fee_range")]
            "50 satoshi/kvB-150 satoshi/kvB",
        ];
        let res = [
            FeeStrategy::Fixed(SatPerKvB::from_sat(100)),
            #[cfg(feature = "fee_range")]
            FeeStrategy::Range {
                min_inc: SatPerKvB::from_sat(50),
                max_inc: SatPerKvB::from_sat(150),
            },
        ];
        for (s, r) in strings.iter().zip(res) {
            let strategy = FeeStrategy::<SatPerKvB>::from_str(s);
            assert!(strategy.is_ok());
            assert_eq!(strategy.unwrap(), r);
        }
    }

    #[test]
    fn fee_strategy_to_str_from_str() {
        let strats = [
            FeeStrategy::Fixed(SatPerKvB::from_sat(1)),
            #[cfg(feature = "fee_range")]
            FeeStrategy::Range {
                min_inc: SatPerKvB::from_sat(1),
                max_inc: SatPerKvB::from_sat(7),
            },
        ];
        for strat in strats.iter() {
            assert_eq!(
                FeeStrategy::<SatPerKvB>::from_str(&strat.to_string()).unwrap(),
                *strat
            )
        }
    }

    #[test]
    #[cfg(feature = "fee_range")]
    fn fee_strategy_check_range() {
        let strategy = FeeStrategy::Range {
            min_inc: SatPerKvB::from_sat(50),
            max_inc: SatPerKvB::from_sat(150),
        };
        assert!(!strategy.check(&SatPerKvB::from_sat(49)));
        assert!(strategy.check(&SatPerKvB::from_sat(50)));
        assert!(strategy.check(&SatPerKvB::from_sat(150)));
        assert!(!strategy.check(&SatPerKvB::from_sat(151)));
    }
}