ddk_manager/
lib.rs

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
//! # Library providing data structures and functions supporting the execution
//! and management of DLC.

#![crate_name = "ddk_manager"]
// Coding conventions
#![forbid(unsafe_code)]
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![deny(dead_code)]
#![deny(unused_imports)]
#![deny(missing_docs)]

extern crate async_trait;
extern crate bitcoin;
extern crate ddk_dlc;
#[macro_use]
extern crate ddk_messages;
extern crate core;
extern crate ddk_trie;
extern crate lightning;
extern crate log;
#[cfg(feature = "fuzztarget")]
extern crate rand_chacha;
extern crate secp256k1_zkp;

pub mod chain_monitor;
pub mod channel;
pub mod channel_updater;
pub mod contract;
pub mod contract_updater;
mod conversion_utils;
pub mod error;
pub mod manager;
pub mod payout_curve;
mod utils;

use bitcoin::psbt::Psbt;
use bitcoin::{Address, Block, OutPoint, ScriptBuf, Transaction, TxOut, Txid};
use chain_monitor::ChainMonitor;
use channel::offered_channel::OfferedChannel;
use channel::signed_channel::{SignedChannel, SignedChannelStateType};
use channel::Channel;
use contract::PreClosedContract;
use contract::{offered_contract::OfferedContract, signed_contract::SignedContract, Contract};
use ddk_messages::oracle_msgs::{OracleAnnouncement, OracleAttestation};
use ddk_messages::ser_impls::{read_address, write_address};
use error::Error;
use lightning::ln::msgs::DecodeError;
use lightning::util::ser::{Readable, Writeable, Writer};
use secp256k1_zkp::{PublicKey, SecretKey, Signing};
use secp256k1_zkp::{Secp256k1, XOnlyPublicKey};
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::RwLock;

/// Type alias for a contract id.
pub type ContractId = [u8; 32];

/// Type alias for a keys id.
pub type KeysId = [u8; 32];

/// Type alias for a channel id.
pub type ChannelId = [u8; 32];

/// Time trait to provide current unix time. Mainly defined to facilitate testing.
pub trait Time {
    /// Must return the unix epoch corresponding to the current time.
    fn unix_time_now(&self) -> u64;
}

/// Provide current time through `SystemTime`.
pub struct SystemTimeProvider {}

impl Time for SystemTimeProvider {
    fn unix_time_now(&self) -> u64 {
        let now = std::time::SystemTime::now();
        now.duration_since(std::time::UNIX_EPOCH)
            .expect("Unexpected time error")
            .as_secs()
    }
}

/// Provides signing related functionalities.
pub trait ContractSigner: Clone {
    /// Get the public key associated with the [`ContractSigner`].
    fn get_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> Result<PublicKey, Error>;
    /// Returns the secret key associated with the [`ContractSigner`].
    // todo: remove this method and add create_adaptor_signature to the trait
    fn get_secret_key(&self) -> Result<SecretKey, Error>;
}

/// Simple sample implementation of [`ContractSigner`].
#[derive(Debug, Copy, Clone)]
pub struct SimpleSigner {
    secret_key: SecretKey,
}

impl SimpleSigner {
    /// Creates a new [`SimpleSigner`] from the provided secret key.
    pub fn new(secret_key: SecretKey) -> Self {
        Self { secret_key }
    }
}

impl ContractSigner for SimpleSigner {
    fn get_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> Result<PublicKey, Error> {
        Ok(self.secret_key.public_key(secp))
    }

    fn get_secret_key(&self) -> Result<SecretKey, Error> {
        Ok(self.secret_key)
    }
}

impl ContractSigner for SecretKey {
    fn get_public_key<C: Signing>(&self, secp: &Secp256k1<C>) -> Result<PublicKey, Error> {
        Ok(self.public_key(secp))
    }

    fn get_secret_key(&self) -> Result<SecretKey, Error> {
        Ok(*self)
    }
}

/// Derives a [`ContractSigner`] from a [`ContractSignerProvider`] and a `contract_keys_id`.
pub trait ContractSignerProvider {
    /// A type which implements [`ContractSigner`]
    type Signer: ContractSigner;

    /// Create a keys id for deriving a `Signer`.
    fn derive_signer_key_id(&self, is_offer_party: bool, temp_id: [u8; 32]) -> [u8; 32];

    /// Derives the private key material backing a `Signer`.
    fn derive_contract_signer(&self, key_id: [u8; 32]) -> Result<Self::Signer, Error>;

    /// Get the secret key associated with the provided public key.
    ///
    /// Only used for Channels.
    fn get_secret_key_for_pubkey(&self, pubkey: &PublicKey) -> Result<SecretKey, Error>;
    /// Generate a new secret key and store it in the wallet so that it can later be retrieved.
    ///
    /// Only used for Channels.
    fn get_new_secret_key(&self) -> Result<SecretKey, Error>;
}

/// Wallet trait to provide functionalities related to generating, storing and
/// managing bitcoin addresses and UTXOs.
pub trait Wallet {
    /// Returns a new (unused) address.
    fn get_new_address(&self) -> Result<Address, Error>;
    /// Returns a new (unused) change address.
    fn get_new_change_address(&self) -> Result<Address, Error>;
    /// Get a set of UTXOs to fund the given amount.
    fn get_utxos_for_amount(
        &self,
        amount: u64,
        fee_rate: u64,
        lock_utxos: bool,
    ) -> Result<Vec<Utxo>, Error>;
    /// Import the provided address.
    fn import_address(&self, address: &Address) -> Result<(), Error>;
    /// Signs a transaction input
    fn sign_psbt_input(&self, psbt: &mut Psbt, input_index: usize) -> Result<(), Error>;
    /// Unlock reserved utxo
    fn unreserve_utxos(&self, outpoints: &[OutPoint]) -> Result<(), Error>;
}

#[async_trait::async_trait]
/// Blockchain trait provides access to the bitcoin blockchain.
pub trait Blockchain {
    /// Broadcast the given transaction to the bitcoin network.
    async fn send_transaction(&self, transaction: &Transaction) -> Result<(), Error>;
    /// Returns the network currently used (mainnet, testnet or regtest).
    fn get_network(&self) -> Result<bitcoin::Network, Error>;
    /// Returns the height of the blockchain
    async fn get_blockchain_height(&self) -> Result<u64, Error>;
    /// Returns the block at given height
    async fn get_block_at_height(&self, height: u64) -> Result<Block, Error>;
    /// Get the transaction with given id.
    async fn get_transaction(&self, tx_id: &Txid) -> Result<Transaction, Error>;
    /// Get the number of confirmation for the transaction with given id.
    async fn get_transaction_confirmations(&self, tx_id: &Txid) -> Result<u32, Error>;
}

/// Storage trait provides functionalities to store and retrieve DLCs.
pub trait Storage {
    /// Returns the contract with given id if found.
    fn get_contract(&self, id: &ContractId) -> Result<Option<Contract>, Error>;
    /// Return all contracts
    fn get_contracts(&self) -> Result<Vec<Contract>, Error>;
    /// Create a record for the given contract.
    fn create_contract(&self, contract: &OfferedContract) -> Result<(), Error>;
    /// Delete the record for the contract with the given id.
    fn delete_contract(&self, id: &ContractId) -> Result<(), Error>;
    /// Update the given contract.
    fn update_contract(&self, contract: &Contract) -> Result<(), Error>;
    /// Returns the set of contracts in offered state.
    fn get_contract_offers(&self) -> Result<Vec<OfferedContract>, Error>;
    /// Returns the set of contracts in signed state.
    fn get_signed_contracts(&self) -> Result<Vec<SignedContract>, Error>;
    /// Returns the set of confirmed contracts.
    fn get_confirmed_contracts(&self) -> Result<Vec<SignedContract>, Error>;
    /// Returns the set of contracts whos broadcasted cet has not been verified to be confirmed on
    /// blockchain
    fn get_preclosed_contracts(&self) -> Result<Vec<PreClosedContract>, Error>;
    /// Update the state of the channel and optionally its associated contract
    /// atomically.
    fn upsert_channel(&self, channel: Channel, contract: Option<Contract>) -> Result<(), Error>;
    /// Delete the channel with given [`ChannelId`] if any.
    fn delete_channel(&self, channel_id: &ChannelId) -> Result<(), Error>;
    /// Returns the channel with given [`ChannelId`] if any.
    fn get_channel(&self, channel_id: &ChannelId) -> Result<Option<Channel>, Error>;
    /// Returns the set of [`SignedChannel`] in the store. Returns only the one
    /// with matching `channel_state` if set.
    fn get_signed_channels(
        &self,
        channel_state: Option<SignedChannelStateType>,
    ) -> Result<Vec<SignedChannel>, Error>;
    /// Returns the set of channels in offer state.
    fn get_offered_channels(&self) -> Result<Vec<OfferedChannel>, Error>;
    /// Writes the [`ChainMonitor`] data to the store.
    fn persist_chain_monitor(&self, monitor: &ChainMonitor) -> Result<(), Error>;
    /// Returns the latest [`ChainMonitor`] in the store if any.
    fn get_chain_monitor(&self) -> Result<Option<ChainMonitor>, Error>;
}

#[async_trait::async_trait]
/// Oracle trait provides access to oracle information.
pub trait Oracle {
    /// Returns the public key of the oracle.
    fn get_public_key(&self) -> XOnlyPublicKey;
    /// Returns the announcement for the event with the given id if found.
    async fn get_announcement(&self, event_id: &str) -> Result<OracleAnnouncement, Error>;
    /// Returns the attestation for the event with the given id if found.
    async fn get_attestation(&self, event_id: &str) -> Result<OracleAttestation, Error>;
}

/// Represents a UTXO.
#[derive(Clone, Debug)]
pub struct Utxo {
    /// The TxOut containing the value and script pubkey of the referenced output.
    pub tx_out: TxOut,
    /// The outpoint containing the txid and vout of the referenced output.
    pub outpoint: OutPoint,
    /// The address associated with the referenced output.
    pub address: Address,
    /// The redeem script for the referenced output.
    pub redeem_script: ScriptBuf,
    /// Whether this Utxo has been reserved (and so should not be used to fund
    /// a DLC).
    pub reserved: bool,
}

impl_dlc_writeable!(Utxo, {
    (tx_out, writeable),
    (outpoint, writeable),
    (address, {cb_writeable, write_address, read_address}),
    (redeem_script, writeable),
    (reserved, writeable)
});

/// A ContractSignerProvider that caches the signers
pub struct CachedContractSignerProvider<SP: Deref, X>
where
    SP::Target: ContractSignerProvider<Signer = X>,
{
    pub(crate) signer_provider: SP,
    pub(crate) cache: RwLock<HashMap<KeysId, X>>,
}

impl<SP: Deref, X> CachedContractSignerProvider<SP, X>
where
    SP::Target: ContractSignerProvider<Signer = X>,
{
    /// Create a new [`ContractSignerProvider`]
    pub fn new(signer_provider: SP) -> Self {
        Self {
            signer_provider,
            cache: RwLock::new(HashMap::new()),
        }
    }
}

impl<SP: Deref, X: ContractSigner> ContractSignerProvider for CachedContractSignerProvider<SP, X>
where
    SP::Target: ContractSignerProvider<Signer = X>,
{
    type Signer = X;

    fn derive_signer_key_id(&self, is_offer_party: bool, temp_id: [u8; 32]) -> KeysId {
        self.signer_provider
            .derive_signer_key_id(is_offer_party, temp_id)
    }

    fn derive_contract_signer(&self, key_id: KeysId) -> Result<Self::Signer, Error> {
        match self.cache.try_read().unwrap().get(&key_id) {
            Some(signer) => Ok(signer.clone()),
            None => self.signer_provider.derive_contract_signer(key_id),
        }
    }

    fn get_secret_key_for_pubkey(&self, pubkey: &PublicKey) -> Result<SecretKey, Error> {
        self.signer_provider.get_secret_key_for_pubkey(pubkey)
    }

    fn get_new_secret_key(&self) -> Result<SecretKey, Error> {
        self.signer_provider.get_new_secret_key()
    }
}