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
use super::StateDownloadProgress;
use crate::{
chain::{Client, ImportedState},
schema::v1::{StateEntry, StateRequest, StateResponse},
};
use codec::{Decode, Encode};
use sc_client_api::StorageProof;
use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use std::sync::Arc;
pub struct StateSync<B: BlockT> {
target_block: B::Hash,
target_header: B::Header,
target_root: B::Hash,
last_key: Vec<u8>,
state: Vec<(Vec<u8>, Vec<u8>)>,
complete: bool,
client: Arc<dyn Client<B>>,
imported_bytes: u64,
skip_proof: bool,
}
pub enum ImportResult<B: BlockT> {
Import(B::Hash, B::Header, ImportedState<B>),
Continue(StateRequest),
BadResponse,
}
impl<B: BlockT> StateSync<B> {
pub fn new(client: Arc<dyn Client<B>>, target: B::Header, skip_proof: bool) -> Self {
StateSync {
client,
target_block: target.hash(),
target_root: target.state_root().clone(),
target_header: target,
last_key: Vec::default(),
state: Vec::default(),
complete: false,
imported_bytes: 0,
skip_proof,
}
}
pub fn import(&mut self, response: StateResponse) -> ImportResult<B> {
if response.entries.is_empty() && response.proof.is_empty() && !response.complete {
log::debug!(
target: "sync",
"Bad state response",
);
return ImportResult::BadResponse
}
if !self.skip_proof && response.proof.is_empty() {
log::debug!(
target: "sync",
"Missing proof",
);
return ImportResult::BadResponse
}
let complete = if !self.skip_proof {
log::debug!(
target: "sync",
"Importing state from {} trie nodes",
response.proof.len(),
);
let proof_size = response.proof.len() as u64;
let proof = match StorageProof::decode(&mut response.proof.as_ref()) {
Ok(proof) => proof,
Err(e) => {
log::debug!(target: "sync", "Error decoding proof: {:?}", e);
return ImportResult::BadResponse
},
};
let (values, complete) =
match self.client.verify_range_proof(self.target_root, proof, &self.last_key) {
Err(e) => {
log::debug!(
target: "sync",
"StateResponse failed proof verification: {:?}",
e,
);
return ImportResult::BadResponse
},
Ok(values) => values,
};
log::debug!(target: "sync", "Imported with {} keys", values.len());
if let Some(last) = values.last().map(|(k, _)| k) {
self.last_key = last.clone();
}
for (key, value) in values {
self.imported_bytes += key.len() as u64;
self.state.push((key, value))
}
self.imported_bytes += proof_size;
complete
} else {
log::debug!(
target: "sync",
"Importing state from {:?} to {:?}",
response.entries.last().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)),
response.entries.first().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)),
);
if let Some(e) = response.entries.last() {
self.last_key = e.key.clone();
}
for StateEntry { key, value } in response.entries {
self.imported_bytes += (key.len() + value.len()) as u64;
self.state.push((key, value))
}
response.complete
};
if complete {
self.complete = true;
ImportResult::Import(
self.target_block.clone(),
self.target_header.clone(),
ImportedState {
block: self.target_block.clone(),
state: std::mem::take(&mut self.state),
},
)
} else {
ImportResult::Continue(self.next_request())
}
}
pub fn next_request(&self) -> StateRequest {
StateRequest {
block: self.target_block.encode(),
start: self.last_key.clone(),
no_proof: self.skip_proof,
}
}
pub fn is_complete(&self) -> bool {
self.complete
}
pub fn target_block_num(&self) -> NumberFor<B> {
self.target_header.number().clone()
}
pub fn target(&self) -> B::Hash {
self.target_block.clone()
}
pub fn progress(&self) -> StateDownloadProgress {
let percent_done = (*self.last_key.get(0).unwrap_or(&0u8) as u32) * 100 / 256;
StateDownloadProgress { percentage: percent_done, size: self.imported_bytes }
}
}