cuprate_fast_sync/
fast_sync.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
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
use std::{
    cmp,
    collections::HashMap,
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use monero_serai::{
    block::Block,
    transaction::{Input, Transaction},
};
use tower::{Service, ServiceExt};

use cuprate_consensus::transactions::new_tx_verification_data;
use cuprate_consensus_context::{BlockChainContextRequest, BlockChainContextResponse};
use cuprate_consensus_rules::{miner_tx::MinerTxError, ConsensusError};
use cuprate_helper::cast::u64_to_usize;
use cuprate_types::{VerifiedBlockInformation, VerifiedTransactionInformation};

use crate::{hash_of_hashes, BlockId, HashOfHashes};

#[cfg(not(test))]
static HASHES_OF_HASHES: &[HashOfHashes] = &include!("./data/hashes_of_hashes");

#[cfg(not(test))]
const BATCH_SIZE: usize = 512;

#[cfg(test)]
static HASHES_OF_HASHES: &[HashOfHashes] = &[
    hex_literal::hex!("3fdc9032c16d440f6c96be209c36d3d0e1aed61a2531490fe0ca475eb615c40a"),
    hex_literal::hex!("0102030405060708010203040506070801020304050607080102030405060708"),
    hex_literal::hex!("0102030405060708010203040506070801020304050607080102030405060708"),
];

#[cfg(test)]
const BATCH_SIZE: usize = 4;

#[inline]
fn max_height() -> u64 {
    (HASHES_OF_HASHES.len() * BATCH_SIZE) as u64
}

#[derive(Debug, PartialEq, Eq)]
pub struct ValidBlockId(BlockId);

fn valid_block_ids(block_ids: &[BlockId]) -> Vec<ValidBlockId> {
    block_ids.iter().map(|b| ValidBlockId(*b)).collect()
}

#[expect(clippy::large_enum_variant)]
pub enum FastSyncRequest {
    ValidateHashes {
        start_height: u64,
        block_ids: Vec<BlockId>,
    },
    ValidateBlock {
        block: Block,
        txs: HashMap<[u8; 32], Transaction>,
        token: ValidBlockId,
    },
}

#[expect(clippy::large_enum_variant)]
#[derive(Debug, PartialEq, Eq)]
pub enum FastSyncResponse {
    ValidateHashes {
        validated_hashes: Vec<ValidBlockId>,
        unknown_hashes: Vec<BlockId>,
    },
    ValidateBlock(VerifiedBlockInformation),
}

#[derive(thiserror::Error, Debug, PartialEq, Eq)]
pub enum FastSyncError {
    #[error("Block does not match its expected hash")]
    BlockHashMismatch,

    #[error("Start height must be a multiple of the batch size")]
    InvalidStartHeight,

    #[error("Hash of hashes mismatch")]
    Mismatch,

    #[error("Given range too small for fast sync (less than one batch)")]
    NothingToDo,

    #[error("Start height too high for fast sync")]
    OutOfRange,

    #[error("Block does not have the expected height entry")]
    BlockHeightMismatch,

    #[error("Block does not contain the expected transaction list")]
    TxsIncludedWithBlockIncorrect,

    #[error(transparent)]
    Consensus(#[from] ConsensusError),

    #[error(transparent)]
    MinerTx(#[from] MinerTxError),

    #[error("Database error: {0}")]
    DbErr(String),
}

impl From<tower::BoxError> for FastSyncError {
    fn from(error: tower::BoxError) -> Self {
        Self::DbErr(error.to_string())
    }
}

pub struct FastSyncService<C> {
    context_svc: C,
}

impl<C> FastSyncService<C>
where
    C: Service<
            BlockChainContextRequest,
            Response = BlockChainContextResponse,
            Error = tower::BoxError,
        > + Clone
        + Send
        + 'static,
{
    #[expect(dead_code)]
    pub(crate) const fn new(context_svc: C) -> Self {
        Self { context_svc }
    }
}

impl<C> Service<FastSyncRequest> for FastSyncService<C>
where
    C: Service<
            BlockChainContextRequest,
            Response = BlockChainContextResponse,
            Error = tower::BoxError,
        > + Clone
        + Send
        + 'static,
    C::Future: Send + 'static,
{
    type Response = FastSyncResponse;
    type Error = FastSyncError;
    type Future =
        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: FastSyncRequest) -> Self::Future {
        let context_svc = self.context_svc.clone();

        Box::pin(async move {
            match req {
                FastSyncRequest::ValidateHashes {
                    start_height,
                    block_ids,
                } => validate_hashes(start_height, &block_ids),
                FastSyncRequest::ValidateBlock { block, txs, token } => {
                    validate_block(context_svc, block, txs, token).await
                }
            }
        })
    }
}

fn validate_hashes(
    start_height: u64,
    block_ids: &[BlockId],
) -> Result<FastSyncResponse, FastSyncError> {
    let start_height_usize = u64_to_usize(start_height);

    if start_height_usize % BATCH_SIZE != 0 {
        return Err(FastSyncError::InvalidStartHeight);
    }

    if start_height >= max_height() {
        return Err(FastSyncError::OutOfRange);
    }

    let stop_height = start_height_usize + block_ids.len();

    let batch_from = start_height_usize / BATCH_SIZE;
    let batch_to = cmp::min(stop_height / BATCH_SIZE, HASHES_OF_HASHES.len());
    let n_batches = batch_to - batch_from;

    if n_batches == 0 {
        return Err(FastSyncError::NothingToDo);
    }

    for i in 0..n_batches {
        let batch = &block_ids[BATCH_SIZE * i..BATCH_SIZE * (i + 1)];
        let actual = hash_of_hashes(batch);
        let expected = HASHES_OF_HASHES[batch_from + i];

        if expected != actual {
            return Err(FastSyncError::Mismatch);
        }
    }

    let validated_hashes = valid_block_ids(&block_ids[..n_batches * BATCH_SIZE]);
    let unknown_hashes = block_ids[n_batches * BATCH_SIZE..].to_vec();

    Ok(FastSyncResponse::ValidateHashes {
        validated_hashes,
        unknown_hashes,
    })
}

async fn validate_block<C>(
    mut context_svc: C,
    block: Block,
    mut txs: HashMap<[u8; 32], Transaction>,
    token: ValidBlockId,
) -> Result<FastSyncResponse, FastSyncError>
where
    C: Service<
            BlockChainContextRequest,
            Response = BlockChainContextResponse,
            Error = tower::BoxError,
        > + Send
        + 'static,
    C::Future: Send + 'static,
{
    let BlockChainContextResponse::Context(checked_context) = context_svc
        .ready()
        .await?
        .call(BlockChainContextRequest::Context)
        .await?
    else {
        panic!("Context service returned wrong response!");
    };

    let block_chain_ctx = checked_context.unchecked_blockchain_context().clone();

    let block_hash = block.hash();
    if block_hash != token.0 {
        return Err(FastSyncError::BlockHashMismatch);
    }

    let block_blob = block.serialize();

    let Some(Input::Gen(height)) = block.miner_transaction.prefix().inputs.first() else {
        return Err(FastSyncError::MinerTx(MinerTxError::InputNotOfTypeGen));
    };
    if *height != block_chain_ctx.chain_height {
        return Err(FastSyncError::BlockHeightMismatch);
    }

    let mut verified_txs = Vec::with_capacity(txs.len());
    for tx in &block.transactions {
        let tx = txs
            .remove(tx)
            .ok_or(FastSyncError::TxsIncludedWithBlockIncorrect)?;

        let data = new_tx_verification_data(tx)?;
        verified_txs.push(VerifiedTransactionInformation {
            tx_blob: data.tx_blob,
            tx_weight: data.tx_weight,
            fee: data.fee,
            tx_hash: data.tx_hash,
            tx: data.tx,
        });
    }

    let total_fees = verified_txs.iter().map(|tx| tx.fee).sum::<u64>();
    let total_outputs = block
        .miner_transaction
        .prefix()
        .outputs
        .iter()
        .map(|output| output.amount.unwrap_or(0))
        .sum::<u64>();

    let generated_coins = total_outputs - total_fees;

    let weight = block.miner_transaction.weight()
        + verified_txs.iter().map(|tx| tx.tx_weight).sum::<usize>();

    Ok(FastSyncResponse::ValidateBlock(VerifiedBlockInformation {
        block_blob,
        txs: verified_txs,
        block_hash,
        pow_hash: [0_u8; 32],
        height: *height,
        generated_coins,
        weight,
        long_term_weight: block_chain_ctx.next_block_long_term_weight(weight),
        cumulative_difficulty: block_chain_ctx.cumulative_difficulty
            + block_chain_ctx.next_difficulty,
        block,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_hashes_errors() {
        let ids = [[1_u8; 32], [2_u8; 32], [3_u8; 32], [4_u8; 32], [5_u8; 32]];
        assert_eq!(
            validate_hashes(3, &[]),
            Err(FastSyncError::InvalidStartHeight)
        );
        assert_eq!(
            validate_hashes(3, &ids),
            Err(FastSyncError::InvalidStartHeight)
        );

        assert_eq!(validate_hashes(20, &[]), Err(FastSyncError::OutOfRange));
        assert_eq!(validate_hashes(20, &ids), Err(FastSyncError::OutOfRange));

        assert_eq!(validate_hashes(4, &[]), Err(FastSyncError::NothingToDo));
        assert_eq!(
            validate_hashes(4, &ids[..3]),
            Err(FastSyncError::NothingToDo)
        );
    }

    #[test]
    fn test_validate_hashes_success() {
        let ids = [[1_u8; 32], [2_u8; 32], [3_u8; 32], [4_u8; 32], [5_u8; 32]];
        let validated_hashes = valid_block_ids(&ids[0..4]);
        let unknown_hashes = ids[4..].to_vec();
        assert_eq!(
            validate_hashes(0, &ids),
            Ok(FastSyncResponse::ValidateHashes {
                validated_hashes,
                unknown_hashes
            })
        );
    }

    #[test]
    fn test_validate_hashes_mismatch() {
        let ids = [
            [1_u8; 32], [2_u8; 32], [3_u8; 32], [5_u8; 32], [1_u8; 32], [2_u8; 32], [3_u8; 32],
            [4_u8; 32],
        ];
        assert_eq!(validate_hashes(0, &ids), Err(FastSyncError::Mismatch));
        assert_eq!(validate_hashes(4, &ids), Err(FastSyncError::Mismatch));
    }
}