heika_state_transition/executor/
validate.rs1use super::*;
4
5impl Executor {
6 pub(super) fn check_transaction(
9 &self,
10 height: u64,
11 timestamp: u64,
12 transaction: &Transaction,
13 hash: &Hash256,
14 size: u64,
15 fee: u64,
16 ) -> Result<(), ExecError> {
17 if fee > transaction.fee || transaction.fee > u64::from(u32::MAX) * size {
19 return Err(invalid(format!(
20 "トランザクション {hash} の手数料 {fee} が上限 {} に合いません",
21 transaction.fee
22 )));
23 }
24 let bonded = matches!(transaction.body, Body::AggregateBonded(_));
26 if height > 1 {
27 let lifetime = if bonded {
28 self.config.max_bonded_transaction_lifetime
29 } else {
30 self.config.max_transaction_lifetime
31 };
32 if transaction.deadline < timestamp || transaction.deadline > timestamp + lifetime {
33 return Err(invalid(format!(
34 "トランザクション {hash} の期限 {} がブロックの時刻 {timestamp} に合いません",
35 transaction.deadline
36 )));
37 }
38 }
39 if self.recent_hashes.contains(&hash.0) {
41 return Err(invalid(format!(
42 "トランザクション {hash} はもう入っています"
43 )));
44 }
45 let signer = self.address_of(&transaction.signer_public_key);
47 if self.is_multisig(&signer) {
48 return Err(invalid(format!(
49 "マルチシグの {} が直接署名しています",
50 Address(signer)
51 )));
52 }
53 if bonded {
55 let active = self
56 .hash_locks
57 .get(&hash.0)
58 .and_then(|history| history.last())
59 .is_some_and(|lock| lock.status == LockStatus::Unused && height < lock.end_height);
60 if !active {
61 return Err(invalid(format!(
62 "アグリゲート {hash} の生きているロックがありません"
63 )));
64 }
65 }
66 Ok(())
67 }
68
69 pub(super) fn remember_hash(&mut self, deadline: u64, hash: [u8; 32]) -> bool {
71 let inserted = self.recent_hashes.insert(hash);
72 if inserted {
73 self.hash_deadlines.entry(deadline).or_default().push(hash);
74 }
75 inserted
76 }
77
78 pub(super) fn forget_expired_hashes(&mut self, timestamp: u64) {
81 let kept = self.hash_deadlines.split_off(×tamp);
82 for (_, hashes) in std::mem::replace(&mut self.hash_deadlines, kept) {
83 for hash in hashes {
84 self.recent_hashes.remove(&hash);
85 }
86 }
87 }
88
89 pub fn remember_transactions(&mut self, block: &Block) -> Result<(), ExecError> {
92 for bytes in block.transactions() {
93 let transaction = Transaction::from_bytes(bytes)
94 .map_err(|error| invalid(format!("トランザクションが読めません: {error}")))?;
95 let hash = transaction.hash(&self.generation_hash_seed);
96 self.remember_hash(transaction.deadline, hash.0);
97 }
98 Ok(())
99 }
100
101 pub(super) fn is_multisig(&self, address: &[u8; 24]) -> bool {
103 self.multisigs
104 .get(address)
105 .is_some_and(|entry| !entry.cosignatories.is_empty())
106 }
107
108 pub(super) fn peek_address(&self, address: &UnresolvedAddress) -> [u8; 24] {
110 match address.namespace_id().map(|id| self.alias_of(id.0)) {
111 Some(Ok(Alias::Address(resolved))) => resolved,
112 _ => address.0,
113 }
114 }
115
116 pub(super) fn cosigners(
118 &self,
119 transaction: &Transaction,
120 aggregate: &Aggregate,
121 ) -> BTreeSet<[u8; 24]> {
122 std::iter::once(&transaction.signer_public_key)
123 .chain(
124 aggregate
125 .cosignatures()
126 .iter()
127 .map(|cosignature| &cosignature.signer_public_key),
128 )
129 .map(|key| self.address_of(key))
130 .collect()
131 }
132
133 pub(super) fn required_signers(&self, inner: &EmbeddedTransaction) -> BTreeSet<[u8; 24]> {
136 let mut required = BTreeSet::from([self.address_of(&inner.signer_public_key)]);
137 match &inner.body {
138 Body::AccountMetadata(metadata) => {
139 required.insert(self.peek_address(&metadata.target_address));
140 }
141 Body::MosaicMetadata(metadata) => {
142 required.insert(self.peek_address(&metadata.metadata.target_address));
143 }
144 Body::NamespaceMetadata(metadata) => {
145 required.insert(self.peek_address(&metadata.metadata.target_address));
146 }
147 Body::MultisigAccountModification(modification) => {
148 for address in modification.address_additions.iter() {
149 required.insert(self.peek_address(address));
150 }
151 }
152 _ => {}
153 }
154 required
155 }
156
157 pub(super) fn check_eligible_cosigners(
160 &self,
161 cosigners: &BTreeSet<[u8; 24]>,
162 aggregate: &Aggregate,
163 ) -> Result<(), ExecError> {
164 let mut eligible = BTreeSet::new();
165 for inner in aggregate.transactions() {
166 for address in self.required_signers(inner) {
167 self.mark_eligible(address, &mut eligible, 0);
168 }
169 }
170 match cosigners
171 .iter()
172 .find(|address| !eligible.contains(*address))
173 {
174 Some(address) => Err(invalid(format!(
175 "アグリゲートの連署者 {} は要りません",
176 Address(*address)
177 ))),
178 None => Ok(()),
179 }
180 }
181
182 pub(super) fn mark_eligible(
183 &self,
184 address: [u8; 24],
185 eligible: &mut BTreeSet<[u8; 24]>,
186 depth: usize,
187 ) {
188 match self.multisigs.get(&address) {
189 Some(entry) if !entry.cosignatories.is_empty() => {
190 if depth < MAX_MULTISIG_WALK {
192 for cosignatory in &entry.cosignatories {
193 self.mark_eligible(*cosignatory, eligible, depth + 1);
194 }
195 }
196 }
197 _ => {
198 eligible.insert(address);
199 }
200 }
201 }
202
203 pub(super) fn check_sufficient_cosigners(
206 &self,
207 cosigners: &BTreeSet<[u8; 24]>,
208 inner: &EmbeddedTransaction,
209 ) -> Result<(), ExecError> {
210 let operation = match &inner.body {
211 Body::MultisigAccountModification(modification)
212 if !modification.address_deletions.is_empty() =>
213 {
214 if modification.address_additions.is_empty() {
215 MultisigOperation::Removal
216 } else {
217 MultisigOperation::Both
218 }
219 }
220 _ => MultisigOperation::Normal,
221 };
222 for address in self.required_signers(inner) {
223 if !self.is_satisfied(&address, operation, cosigners, 0) {
224 return Err(invalid(format!("{} の連署が足りません", Address(address))));
225 }
226 }
227 Ok(())
228 }
229
230 pub(super) fn is_satisfied(
231 &self,
232 address: &[u8; 24],
233 operation: MultisigOperation,
234 cosigners: &BTreeSet<[u8; 24]>,
235 depth: usize,
236 ) -> bool {
237 let Some(entry) = self
238 .multisigs
239 .get(address)
240 .filter(|entry| !entry.cosignatories.is_empty())
241 else {
242 return cosigners.contains(address);
243 };
244 if depth >= MAX_MULTISIG_WALK {
245 return false;
246 }
247 let approvers = entry
248 .cosignatories
249 .iter()
250 .filter(|cosignatory| self.is_satisfied(cosignatory, operation, cosigners, depth + 1))
251 .count();
252 let required = match operation {
253 MultisigOperation::Normal => entry.min_approval,
254 MultisigOperation::Removal => entry.min_removal,
255 MultisigOperation::Both => entry.min_approval.max(entry.min_removal),
256 };
257 approvers as u64 >= u64::from(required)
258 }
259
260 pub(super) fn check_mosaic_owner(
262 &self,
263 height: u64,
264 id: u64,
265 owner: &[u8; 24],
266 ) -> Result<&MosaicEntry, ExecError> {
267 let entry = self
268 .mosaics
269 .get(&id)
270 .filter(|entry| entry.is_active(height))
271 .ok_or_else(|| invalid(format!("モザイク {id:016X} は生きていません")))?;
272 if entry.owner != *owner {
273 return Err(invalid(format!(
274 "モザイク {id:016X} の持ち主は {} ではありません",
275 Address(*owner)
276 )));
277 }
278 Ok(entry)
279 }
280
281 pub(super) fn check_namespace_owner(
283 &self,
284 height: u64,
285 id: u64,
286 owner: &[u8; 24],
287 ) -> Result<(), ExecError> {
288 let root = self
289 .namespace_paths
290 .get(&id)
291 .and_then(|path| self.namespaces.get(&path[0]))
292 .ok_or_else(|| invalid(format!("ネームスペース {id:016X} がありません")))?;
293 if !self.is_active_excluding_grace(root, height) {
294 return Err(invalid(format!("ネームスペース {id:016X} は切れています")));
295 }
296 if root.owner != *owner {
297 return Err(invalid(format!(
298 "ネームスペース {id:016X} の持ち主は {} ではありません",
299 Address(*owner)
300 )));
301 }
302 Ok(())
303 }
304
305 pub(super) fn is_active_excluding_grace(&self, root: &RootNamespace, height: u64) -> bool {
306 root.start <= height
307 && (root.end == u64::MAX || height < root.end - self.config.namespace_grace_period)
308 }
309
310 pub(super) fn check_child_namespace(
316 &self,
317 height: u64,
318 owner: &[u8; 24],
319 id: u64,
320 parent_id: u64,
321 ) -> Result<(), ExecError> {
322 let parent = self
323 .namespace_paths
324 .get(&parent_id)
325 .ok_or_else(|| invalid("親のネームスペースがありません"))?;
326 if parent.len() >= self.config.max_namespace_depth {
327 return Err(invalid(format!(
328 "ネームスペース {parent_id:016X} の下には作れません(深すぎる)"
329 )));
330 }
331 self.check_namespace_owner(height, parent_id, owner)?;
332 let exists = self
333 .namespace_paths
334 .get(&id)
335 .and_then(|path| self.namespaces.get(&path[0]))
336 .is_some_and(|root| root.start <= height && height < root.end);
337 if exists {
338 return Err(invalid(format!("ネームスペース {id:016X} はもうあります")));
339 }
340 Ok(())
341 }
342
343 pub(super) fn check_alias(
345 &self,
346 height: u64,
347 owner: &[u8; 24],
348 namespace_id: u64,
349 action: AliasAction,
350 alias: Alias,
351 ) -> Result<(), ExecError> {
352 self.check_namespace_owner(height, namespace_id, owner)?;
353 let current = self.alias_of(namespace_id)?;
354 let available = match action {
355 AliasAction::Link => current == Alias::None,
356 AliasAction::Unlink => current == alias,
357 };
358 if !available {
359 return Err(invalid(format!(
360 "ネームスペース {namespace_id:016X} の別名は {current:?} なので {action:?} できません"
361 )));
362 }
363 Ok(())
364 }
365}
366
367#[derive(Clone, Debug, PartialEq, Eq)]
369pub enum PartialCheck {
370 Complete,
372 Missing,
374 Ineligible(Vec<PublicKey>),
377}
378
379impl Executor {
380 pub fn hash_lock_ready(&self, hash: &Hash256) -> bool {
383 let height = self.height;
384 self.hash_locks
385 .get(&hash.0)
386 .and_then(|history| history.last())
387 .is_some_and(|lock| lock.status == LockStatus::Unused && height < lock.end_height)
388 }
389
390 pub fn check_partial(&self, transaction: &Transaction) -> PartialCheck {
394 let Body::AggregateBonded(aggregate) = &transaction.body else {
395 return PartialCheck::Ineligible(vec![transaction.signer_public_key]);
396 };
397 let mut eligible = BTreeSet::new();
398 for inner in aggregate.transactions() {
399 for address in self.required_signers(inner) {
400 self.mark_eligible(address, &mut eligible, 0);
401 }
402 }
403 let ineligible: Vec<PublicKey> = std::iter::once(&transaction.signer_public_key)
404 .chain(
405 aggregate
406 .cosignatures()
407 .iter()
408 .map(|cosignature| &cosignature.signer_public_key),
409 )
410 .filter(|key| !eligible.contains(&self.address_of(key)))
411 .copied()
412 .collect();
413 if !ineligible.is_empty() {
414 return PartialCheck::Ineligible(ineligible);
415 }
416 let cosigners = self.cosigners(transaction, aggregate);
417 if aggregate
418 .transactions()
419 .iter()
420 .all(|inner| self.check_sufficient_cosigners(&cosigners, inner).is_ok())
421 {
422 PartialCheck::Complete
423 } else {
424 PartialCheck::Missing
425 }
426 }
427}