Skip to main content

heika_node/
reader.rs

1//! API の読み役([`heika_api::Reader`])。先端を追うあいだの DB を、API のスレッドから読む。
2//!
3//! 状態は、今の行を catapult の葉のバイト列にしてから REST の JSON にする([`heika_rest::state`] の逆向き)。
4//! 葉と同じバイト列から作るので、受け取った側が JSON から組み直したハッシュは、木の葉と合う。
5//! ブロックの9本の根は DB にしまっていないので、その高さの木の根のノードを読んで求め直す。差分が残っていない高さの
6//! ブロックは、根を出せないので返さない。
7//!
8//! 状態は、`?height=` で指定された高さのものも、DB に残した差分から引く([`Db::at`])。
9//!
10//! ネームスペースの行はルートごとなので、子の ID で引かれたら、どのルートの子かを ID から求められないぶん、
11//! ネームスペースの行を全部見て探す。
12//!
13//! トランザクションの行方は、メモリプール、連署を待つものの置き場と、直近のブロックの索引([`crate::recent`])で答える。索引より古い
14//! トランザクションは知らないことにする。
15
16use std::sync::Arc;
17
18use heika_api::{
19    AliasTarget, KeyedStates, MetadataFilter, MetadataPosition, NamespaceFilter, PageRequest,
20    PartialFilter, StateError, TransactionFilter,
21};
22use heika_block::Block;
23use heika_block::statement::BlockStatement;
24use heika_chain::store::EXECUTOR_META;
25use heika_core::address::Address;
26use heika_core::hash::Hash256;
27use heika_core::key::PublicKey;
28use heika_core::merkle::{self, Position};
29use heika_core::network::{GenerationHashSeed, NetworkIdentifier};
30use heika_core::patricia::{SubCache, TreeNode};
31use heika_mempool::SharedMempool;
32use heika_mempool::partial::SharedPartialPool;
33use heika_rest::block::{BlockHeader, BlockInfo, BlockMeta};
34use heika_rest::merkle::{MerklePathItem, MerkleProofInfo, MerkleStateInfo};
35use heika_rest::node::TransactionFeesJson;
36use heika_rest::send::TransactionStatus;
37use heika_rest::state::{
38    AccountJson, MetadataEntryJson, MosaicStateJson, MultisigGraphLevel, MultisigJson,
39    NamespaceInfo, NamespaceNameJson, RootNamespaceState,
40};
41use heika_rest::transaction::{
42    TransactionInfo, TransactionJson, TransactionMeta, transaction_position,
43};
44use heika_state_transition::executor::persist::{
45    decode_account_row, height_of_meta, lock_or_restriction_state, row_key,
46};
47use heika_state_transition::tree::{EMPTY_ROOT, ROOT, node_key, walk};
48use heika_store_redb::search::{
49    METADATA_BY_SOURCE, METADATA_BY_TARGET, METADATA_BY_TARGET_ID, NAMESPACE_BY_ADDRESS,
50    NAMESPACE_BY_MOSAIC, NAMESPACE_BY_OWNER, NamespaceRow, namespace_ids, row_key_of, row_yields,
51};
52use heika_store_redb::{At, Db, DbError, MetadataFields, Now, Searches};
53use heika_transaction::{Body, Transaction};
54
55use crate::recent::SharedRecent;
56
57/// 手数料の倍率を見る、直近のブロックの数。catapult の REST の `numBlocksTransactionFeeStats` の既定値
58const FEE_STATS_BLOCKS: u64 = 300;
59
60/// ブロックを作ってみて弾いたトランザクションの、`/transactionStatus` のコード
61const REJECTED_CODE: &str = "Failure_Heika_Rejected_When_Harvesting";
62
63/// アグリゲートのトランザクションの種類(完了と保留)
64const AGGREGATE_TYPES: [u16; 2] = [0x4141, 0x4241];
65
66pub struct DbReader {
67    db: Arc<Db>,
68    network: NetworkIdentifier,
69    /// 通貨のモザイク。アカウントの葉では、これを先に並べる
70    currency: u64,
71    seed: GenerationHashSeed,
72    mempool: Arc<SharedMempool>,
73    recent: SharedRecent,
74    partials: Arc<SharedPartialPool>,
75}
76
77impl DbReader {
78    pub fn new(
79        db: Arc<Db>,
80        network: NetworkIdentifier,
81        currency: u64,
82        seed: GenerationHashSeed,
83        mempool: Arc<SharedMempool>,
84        recent: SharedRecent,
85        partials: Arc<SharedPartialPool>,
86    ) -> Self {
87        Self {
88            db,
89            network,
90            currency,
91            seed,
92            mempool,
93            recent,
94            partials,
95        }
96    }
97
98    /// 直近のブロック(ハッシュの表を作っていれば、しまってある全部のブロック)に入った `hash` のトランザクションと、
99    /// 入った高さと、ブロックの中の番号
100    fn recent_transaction(
101        &self,
102        hash: &Hash256,
103    ) -> Result<Option<(Transaction, u64, u32, Block)>, String> {
104        let found = self
105            .recent
106            .read()
107            .unwrap_or_else(|poisoned| poisoned.into_inner())
108            .find(hash);
109        // 直近のブロックになければ、ハッシュの表(storage.search の transactions)から
110        let found = match found {
111            Some(found) => Some(found),
112            None => self
113                .db
114                .transaction_location(hash)
115                .map_err(|error| error.to_string())?,
116        };
117        let Some((height, index)) = found else {
118            return Ok(None);
119        };
120        // 索引を引いたあとに枝を取り替えていれば、ブロックがないか、違うものが入っている
121        let Some(block) = self.read_block(height)? else {
122            return Ok(None);
123        };
124        let transaction = block
125            .transactions()
126            .nth(index as usize)
127            .and_then(|bytes| Transaction::from_bytes(bytes).ok())
128            .filter(|transaction| transaction.hash(&self.seed) == *hash);
129        Ok(transaction.map(|transaction| (transaction, height, index, block)))
130    }
131
132    /// 承認されたトランザクションを REST の形にする。`block` は入ったブロック
133    fn confirmed_info(
134        &self,
135        transaction: &Transaction,
136        block: &Block,
137        height: u64,
138        index: u32,
139        id: Option<String>,
140    ) -> TransactionInfo {
141        let hash = transaction.hash(&self.seed).to_string();
142        let mut json = TransactionJson::from(transaction);
143        // 中のトランザクションにも、catapult の REST と同じく、入った高さ、親、ブロックの時刻と倍率を付ける
144        for (inner, entry) in json.body.transactions.iter_mut().flatten().enumerate() {
145            entry.meta = embedded_meta(&hash, block, height, index, inner as u32);
146        }
147        TransactionInfo {
148            id,
149            meta: TransactionMeta {
150                height: Some(height.to_string()),
151                hash: Some(hash),
152                merkle_component_hash: Some(
153                    transaction.merkle_component_hash(&self.seed).to_string(),
154                ),
155                index: Some(index),
156                aggregate_hash: None,
157                aggregate_id: None,
158                timestamp: Some(block.timestamp.to_string()),
159                fee_multiplier: Some(block.fee_multiplier),
160            },
161            transaction: json,
162        }
163    }
164
165    /// 連署を待つものを、集まった連署を付けて REST の形にする。承認されていないので高さは "0"
166    fn partial_info(&self, hash: &Hash256) -> Option<TransactionInfo> {
167        let bytes = self.partials.lock().stitched(hash)?;
168        let transaction = Transaction::from_bytes(&bytes).ok()?;
169        Some(TransactionInfo {
170            id: None,
171            meta: TransactionMeta {
172                height: Some("0".to_owned()),
173                hash: Some(hash.to_string()),
174                merkle_component_hash: Some(
175                    transaction.merkle_component_hash(&self.seed).to_string(),
176                ),
177                index: Some(0),
178                aggregate_hash: None,
179                aggregate_id: None,
180                timestamp: None,
181                fee_multiplier: None,
182            },
183            transaction: TransactionJson::from(&transaction),
184        })
185    }
186
187    /// 未承認のもの(ハッシュ `hash`、バイト列 `bytes`)の JSON。`meta` は連署を待つものと同じく、高さを 0 にする
188    fn unconfirmed_info(&self, hash: &Hash256, transaction: &Transaction) -> TransactionInfo {
189        TransactionInfo {
190            id: None,
191            meta: TransactionMeta {
192                height: Some("0".to_owned()),
193                hash: Some(hash.to_string()),
194                merkle_component_hash: Some(
195                    transaction.merkle_component_hash(&self.seed).to_string(),
196                ),
197                index: Some(0),
198                aggregate_hash: None,
199                aggregate_id: None,
200                timestamp: None,
201                fee_multiplier: None,
202            },
203            transaction: TransactionJson::from(transaction),
204        }
205    }
206
207    /// `transaction` に `address` が関わるか。外側の署名者、中のトランザクションの署名者、連署者、送金の宛先
208    fn involves(&self, transaction: &Transaction, address: &Address) -> bool {
209        let of = |key: &heika_core::key::PublicKey| Address::from_public_key(key, self.network);
210        if of(&transaction.signer_public_key) == *address {
211            return true;
212        }
213        let (Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate)) =
214            &transaction.body
215        else {
216            return false;
217        };
218        aggregate
219            .cosignatures()
220            .iter()
221            .any(|cosignature| of(&cosignature.signer_public_key) == *address)
222            || aggregate.transactions().iter().any(|inner| {
223                of(&inner.signer_public_key) == *address
224                    || matches!(&inner.body, Body::Transfer(transfer)
225                        if transfer.recipient_address().0 == address.0)
226            })
227    }
228
229    fn read_block(&self, height: u64) -> Result<Option<Block>, String> {
230        let Some(bytes) = self.db.block(height).map_err(|error| error.to_string())? else {
231            return Ok(None);
232        };
233        Block::from_bytes(&bytes)
234            .map(Some)
235            .map_err(|error| error.to_string())
236    }
237
238    /// 実行した高さ
239    fn executed(&self) -> Result<u64, String> {
240        match self
241            .db
242            .meta(EXECUTOR_META)
243            .map_err(|error| error.to_string())?
244        {
245            Some(meta) => height_of_meta(&meta).map_err(|error| error.to_string()),
246            None => Ok(0),
247        }
248    }
249
250    /// `at` の高さの状態を引く先と、その高さ(`None` なら今と、実行した高さ)
251    fn view(&self, at: Option<u64>) -> Result<(View, u64), StateError> {
252        let tip = self.executed()?;
253        let Some(height) = at else {
254            let now = self
255                .db
256                .now()
257                .map_err(|error| StateError::Other(error.to_string()))?;
258            return Ok((View::Now(Box::new(now)), tip));
259        };
260        // 実行した高さより上を引くと、DB は今の値を返してしまう
261        if height > tip {
262            return Err(StateError::Ahead { height, tip });
263        }
264        match self.db.at(height) {
265            Ok(past) => Ok((View::At(Box::new(past)), height)),
266            Err(DbError::NoHistory { .. } | DbError::NotIndexed { .. }) => {
267                Err(StateError::NoHistory { height })
268            }
269            Err(error) => Err(StateError::Other(error.to_string())),
270        }
271    }
272
273    /// 状態の行。なければ `None`
274    fn row(&self, view: &View, key: &[u8]) -> Result<Option<Vec<u8>>, StateError> {
275        match view {
276            View::Now(now) => now.state(key),
277            View::At(past) => past.state(key),
278        }
279        .map_err(|error| StateError::Other(error.to_string()))
280    }
281
282    /// 状態の行を `keys` の順に。なければ `None`。全部を同じ高さで読む
283    fn rows(&self, view: &View, keys: &[Vec<u8>]) -> Result<Vec<Option<Vec<u8>>>, StateError> {
284        keys.iter().map(|key| self.row(view, key)).collect()
285    }
286
287    /// マルチシグの状態。`addresses` のうち、あるものだけを渡した順に
288    fn multisigs_in(
289        &self,
290        view: &View,
291        addresses: &[Address],
292    ) -> Result<Vec<MultisigJson>, StateError> {
293        let keys: Vec<_> = addresses
294            .iter()
295            .map(|address| row_key(SubCache::Multisig, &address.0))
296            .collect();
297        let mut out = Vec::new();
298        for (address, row) in addresses.iter().zip(self.rows(view, &keys)?) {
299            let Some(row) = row else { continue };
300            // 行はアドレスを除いたもの。葉と同じく、二つの数のあとに入れる
301            let (counts, rest) = row
302                .split_at_checked(8)
303                .ok_or_else(|| StateError::Other("マルチシグの行が短すぎます".to_owned()))?;
304            let mut bytes = 1u16.to_le_bytes().to_vec();
305            bytes.extend_from_slice(counts);
306            bytes.extend_from_slice(&address.0);
307            bytes.extend_from_slice(rest);
308            out.push(MultisigJson::from_state_bytes(&bytes).map_err(|error| error.to_string())?);
309        }
310        Ok(out)
311    }
312
313    /// 高さ `height` の状態の木 `cache` の根。差分が残っていなければ `None`
314    fn root_at(&self, cache: SubCache, height: u64) -> Result<Option<Hash256>, String> {
315        match self
316            .db
317            .trie_node_at(&node_key(cache.index() as u8, &ROOT), height)
318        {
319            Ok(Some(bytes)) => Ok(Some(decode_node(&bytes)?.hash())),
320            Ok(None) => Ok(Some(EMPTY_ROOT)),
321            Err(DbError::NoHistory { .. } | DbError::NotIndexed { .. }) => Ok(None),
322            Err(error) => Err(error.to_string()),
323        }
324    }
325}
326
327/// メタデータの検索で、検索表のどこをなめるか。並べ方と、決まった項目だけで作ったキーの頭。
328/// 頭に入らなかった項目は、なめたあとで絞る
329fn metadata_prefixes(filter: &MetadataFilter) -> Vec<Vec<u8>> {
330    let kind = filter.metadata_type;
331    let (source, target) = (filter.source.map(|a| a.0), filter.target.map(|a| a.0));
332    let target_id = filter.target_id.map(u64::to_be_bytes);
333    let scoped_key = filter.scoped_key.map(u64::to_be_bytes);
334    // 前から順に、決まっているところまでを頭にする
335    let prefix = |head: u8, parts: &[Option<&[u8]>]| {
336        let mut out = vec![head];
337        for part in parts {
338            let Some(part) = part else { break };
339            out.extend_from_slice(part);
340        }
341        out
342    };
343    let kind_byte = kind.map(|kind| [kind]);
344    if let Some(source) = &source {
345        return vec![prefix(
346            METADATA_BY_SOURCE,
347            &[
348                Some(source),
349                kind_byte.as_ref().map(|k| &k[..]),
350                target.as_ref().map(|t| &t[..]),
351                target_id.as_ref().map(|i| &i[..]),
352                scoped_key.as_ref().map(|k| &k[..]),
353            ],
354        )];
355    }
356    if let Some(target) = &target {
357        return vec![prefix(
358            METADATA_BY_TARGET,
359            &[
360                Some(target),
361                kind_byte.as_ref().map(|k| &k[..]),
362                target_id.as_ref().map(|i| &i[..]),
363                scoped_key.as_ref().map(|k| &k[..]),
364            ],
365        )];
366    }
367    // 対象からの並べ方は、モザイクとネームスペースのメタデータだけを持つ
368    let by_target_id = |kind: u8| {
369        prefix(
370            METADATA_BY_TARGET_ID,
371            &[
372                Some(&[kind][..]),
373                target_id.as_ref().map(|i| &i[..]),
374                scoped_key.as_ref().map(|k| &k[..]),
375            ],
376        )
377    };
378    match kind {
379        Some(kind @ (1 | 2)) => vec![by_target_id(kind)],
380        None if target_id.is_some_and(|id| id != [0; 8]) => vec![by_target_id(1), by_target_id(2)],
381        // ほかは、宛先からの並べ方を全部なめる(全部のメタデータが1回ずつ入っている)
382        _ => vec![vec![METADATA_BY_TARGET]],
383    }
384}
385
386fn matches(filter: &MetadataFilter, fields: &MetadataFields) -> bool {
387    filter.source.is_none_or(|source| source.0 == fields.source)
388        && filter.target.is_none_or(|target| target.0 == fields.target)
389        && filter.scoped_key.is_none_or(|key| key == fields.scoped_key)
390        && filter.target_id.is_none_or(|id| id == fields.target_id)
391        && filter
392            .metadata_type
393            .is_none_or(|kind| kind == fields.metadata_type)
394}
395
396/// 検索表の候補 `key` が、昔の高さの状態 `past` で、その行から出るか
397fn existed(past: &At, key: &[u8]) -> Result<bool, DbError> {
398    let Some(row) = row_key_of(key) else {
399        return Ok(false);
400    };
401    Ok(past
402        .state(&row)?
403        .is_some_and(|value| row_yields(key, &value)))
404}
405
406/// 承認されたアグリゲート(ハッシュは `aggregate_hash`)の `inner` 番目(0から)の中のトランザクションの `meta`。
407/// catapult の `EmbeddedTransactionMetaDTO` と同じ項目で、`aggregateId` は親の [`transaction_position`]
408fn embedded_meta(
409    aggregate_hash: &str,
410    block: &Block,
411    height: u64,
412    index: u32,
413    inner: u32,
414) -> TransactionMeta {
415    TransactionMeta {
416        height: Some(height.to_string()),
417        hash: None,
418        merkle_component_hash: None,
419        index: Some(inner),
420        aggregate_hash: Some(aggregate_hash.to_owned()),
421        aggregate_id: Some(transaction_position(height, index, 0)),
422        timestamp: Some(block.timestamp.to_string()),
423        fee_multiplier: Some(block.fee_multiplier),
424    }
425}
426
427/// 承認されたトランザクションが、検索の絞り込みに合うか。catapult の REST の条件と同じく、宛先は送金、シークレットロック、
428/// シークレットの証明の `recipientAddress`、モザイクと額は送金の `mosaics` のどれか(額はモザイクと別に、どれかが範囲に入る)。
429/// アグリゲートの中のものは、中の署名者と本体で確かめる
430fn transaction_matches(filter: &TransactionFilter, signer: &PublicKey, body: &Body) -> bool {
431    if let Some(key) = filter.signer
432        && *signer != key
433    {
434        return false;
435    }
436    if !filter.types.is_empty() && !filter.types.contains(&body.transaction_type()) {
437        return false;
438    }
439    if let Some(recipient) = filter.recipient {
440        let found = match body {
441            Body::Transfer(transfer) => transfer.recipient_address().0,
442            Body::SecretLock(lock) => lock.recipient_address.0,
443            Body::SecretProof(proof) => proof.recipient_address.0,
444            _ => return false,
445        };
446        if found != recipient {
447            return false;
448        }
449    }
450    if let Some(mosaic) = filter.mosaic {
451        let Body::Transfer(transfer) = body else {
452            return false;
453        };
454        let mosaics = transfer.mosaics();
455        if !mosaics.keys().any(|id| id.0 == mosaic) {
456            return false;
457        }
458        if let Some(from) = filter.from_amount
459            && !mosaics.values().any(|&amount| amount >= from)
460        {
461            return false;
462        }
463        if let Some(to) = filter.to_amount
464            && !mosaics.values().any(|&amount| amount <= to)
465        {
466            return false;
467        }
468    }
469    true
470}
471
472/// 状態を引く先
473enum View {
474    /// 今の状態。開いた時点の高さで読む
475    Now(Box<Now>),
476    /// ある高さのブロックを実行したあとの状態
477    At(Box<At>),
478}
479
480/// 行は、葉のバイト列からバージョンを除いたもの(モザイクとネームスペースは ID も除く)
481fn state_bytes(id: &[u8], row: &[u8]) -> Vec<u8> {
482    let mut bytes = 1u16.to_le_bytes().to_vec();
483    bytes.extend_from_slice(id);
484    bytes.extend_from_slice(row);
485    bytes
486}
487
488fn decode_node(bytes: &[u8]) -> Result<TreeNode, String> {
489    TreeNode::decode_all(bytes)
490        .ok()
491        .and_then(|nodes| nodes.into_iter().next())
492        .ok_or_else(|| "しまった木のノードが読めません".to_owned())
493}
494
495fn hex(bytes: &[u8]) -> String {
496    bytes.iter().map(|byte| format!("{byte:02X}")).collect()
497}
498
499impl heika_api::Reader for DbReader {
500    fn accounts(
501        &self,
502        addresses: &[Address],
503        at: Option<u64>,
504    ) -> Result<Vec<AccountJson>, StateError> {
505        let (view, _) = self.view(at)?;
506        let keys: Vec<_> = addresses
507            .iter()
508            .map(|address| row_key(SubCache::AccountState, &address.0))
509            .collect();
510        let mut out = Vec::new();
511        for row in self.rows(&view, &keys)?.into_iter().flatten() {
512            let account = decode_account_row(&row).map_err(|error| error.to_string())?;
513            out.push(
514                AccountJson::from_state_bytes(&account.to_state_bytes(self.currency))
515                    .map_err(|error| error.to_string())?,
516            );
517        }
518        Ok(out)
519    }
520
521    fn mosaics(&self, ids: &[u64], at: Option<u64>) -> Result<Vec<MosaicStateJson>, StateError> {
522        let (view, _) = self.view(at)?;
523        let keys: Vec<_> = ids
524            .iter()
525            .map(|id| row_key(SubCache::Mosaic, &id.to_le_bytes()))
526            .collect();
527        let mut out = Vec::new();
528        for (id, row) in ids.iter().zip(self.rows(&view, &keys)?) {
529            let Some(row) = row else { continue };
530            out.push(
531                MosaicStateJson::from_state_bytes(&state_bytes(&id.to_le_bytes(), &row))
532                    .map_err(|error| error.to_string())?,
533            );
534        }
535        Ok(out)
536    }
537
538    fn multisigs(
539        &self,
540        addresses: &[Address],
541        at: Option<u64>,
542    ) -> Result<Vec<MultisigJson>, StateError> {
543        let (view, _) = self.view(at)?;
544        self.multisigs_in(&view, addresses)
545    }
546
547    fn lock_or_restriction_states(
548        &self,
549        cache: SubCache,
550        keys: &[Vec<u8>],
551        at: Option<u64>,
552    ) -> Result<KeyedStates, StateError> {
553        let (view, _) = self.view(at)?;
554        let rows: Vec<_> = keys.iter().map(|key| row_key(cache, key)).collect();
555        let mut out = Vec::new();
556        for (key, row) in keys.iter().zip(self.rows(&view, &rows)?) {
557            let Some(row) = row else { continue };
558            let Some(state) = lock_or_restriction_state(cache, key, &row)
559                .map_err(|error| StateError::Other(error.to_string()))?
560            else {
561                continue;
562            };
563            let mut bytes = 1u16.to_le_bytes().to_vec();
564            bytes.extend_from_slice(&state);
565            out.push((key.clone(), bytes));
566        }
567        Ok(out)
568    }
569
570    fn multisig_graph(
571        &self,
572        address: &Address,
573        at: Option<u64>,
574    ) -> Result<Option<Vec<MultisigGraphLevel>>, StateError> {
575        let (view, _) = self.view(at)?;
576        heika_api::multisig_graph(address, |addresses| self.multisigs_in(&view, addresses))
577    }
578
579    fn namespace(&self, id: u64, at: Option<u64>) -> Result<Option<NamespaceInfo>, StateError> {
580        let (view, height) = self.view(at)?;
581        let root_bytes = |root_id: u64, row: &[u8]| state_bytes(&root_id.to_le_bytes(), row);
582        let mut found = self
583            .row(&view, &row_key(SubCache::Namespace, &id.to_le_bytes()))?
584            .map(|row| root_bytes(id, &row));
585        if found.is_none() {
586            // 子。ID のバイト列を含む行だけを読んで確かめる
587            let needle = id.to_le_bytes();
588            let mut rows = Vec::new();
589            let mut keep = |key: &[u8], row: &[u8]| {
590                if row.windows(8).any(|window| window == needle)
591                    && let Ok(root_id) = key[1..].try_into().map(u64::from_le_bytes)
592                {
593                    rows.push(root_bytes(root_id, row));
594                }
595            };
596            let prefix = [SubCache::Namespace.index() as u8];
597            match view {
598                View::Now(_) => self.db.for_each_state_row(&prefix, &mut keep),
599                View::At(_) => self
600                    .db
601                    .state_rows_with_prefix_at(&prefix, height)
602                    .map(|past| past.iter().for_each(|(key, row)| keep(key, row))),
603            }
604            .map_err(|error| error.to_string())?;
605            found = rows.into_iter().find(|bytes| {
606                RootNamespaceState::from_state_bytes(bytes)
607                    .is_ok_and(|state| state.info(id, 0).is_ok_and(|info| info.is_some()))
608            });
609        }
610        let Some(bytes) = found else {
611            return Ok(None);
612        };
613        Ok(RootNamespaceState::from_state_bytes(&bytes)
614            .and_then(|state| state.info(id, height))
615            .map_err(|error| error.to_string())?)
616    }
617
618    fn metadata(
619        &self,
620        composite_hash: &Hash256,
621        at: Option<u64>,
622    ) -> Result<Option<MetadataEntryJson>, StateError> {
623        let (view, _) = self.view(at)?;
624        let Some(row) = self.row(&view, &row_key(SubCache::Metadata, &composite_hash.0))? else {
625            return Ok(None);
626        };
627        Ok(Some(
628            MetadataEntryJson::from_state_bytes(&state_bytes(&[], &row))
629                .map_err(|error| error.to_string())?,
630        ))
631    }
632
633    fn search_metadata(
634        &self,
635        filter: &MetadataFilter,
636        page: PageRequest,
637        after: Option<&MetadataPosition>,
638        at: Option<u64>,
639    ) -> Result<Option<Vec<MetadataEntryJson>>, StateError> {
640        let searches = self.db.searches();
641        let wanted = match at {
642            None => Searches::METADATA,
643            Some(_) => Searches::METADATA.union(Searches::PAST),
644        };
645        if !searches.contains(wanted) {
646            return Ok(None);
647        }
648        let (view, _) = self.view(at)?;
649        let mut prefixes = metadata_prefixes(filter);
650        if page.descending {
651            prefixes.reverse();
652        }
653        let after = after.map(|after| MetadataFields {
654            source: after.source.0,
655            target: after.target.0,
656            scoped_key: after.scoped_key,
657            target_id: after.target_id,
658            metadata_type: after.metadata_type,
659        });
660        let mut skip = (page.number - 1) * page.size;
661        let mut found = Vec::new();
662        let mut failed = None;
663        for prefix in prefixes {
664            // 位置は、この並べ方のキーにして渡す
665            let after = after.map(|after| after.search_key(prefix[0]));
666            let mut visit = |key: &[u8]| {
667                let Some(fields) = MetadataFields::from_search_key(key) else {
668                    return true;
669                };
670                if !matches(filter, &fields) {
671                    return true;
672                }
673                // 昔の高さでは、候補がその高さにあったかを状態の行で確かめる
674                if let View::At(past) = &view {
675                    match existed(past, key) {
676                        Ok(true) => {}
677                        Ok(false) => return true,
678                        Err(error) => {
679                            failed = Some(error);
680                            return false;
681                        }
682                    }
683                }
684                if skip > 0 {
685                    skip -= 1;
686                    return true;
687                }
688                found.push(fields);
689                found.len() < page.size
690            };
691            let after = after.as_deref();
692            match view {
693                View::Now(_) => {
694                    self.db
695                        .for_each_search_key(&prefix, after, page.descending, &mut visit)
696                }
697                View::At(_) => self.db.for_each_search_key_with_past(
698                    &prefix,
699                    after,
700                    page.descending,
701                    &mut visit,
702                ),
703            }
704            .map_err(|error| error.to_string())?;
705            if let Some(error) = failed {
706                return Err(StateError::Other(error.to_string()));
707            }
708            if found.len() >= page.size {
709                break;
710            }
711        }
712        let mut entries = Vec::with_capacity(found.len());
713        for fields in found {
714            let Some(hash) = fields.composite_hash().map(Hash256) else {
715                continue;
716            };
717            // 検索表を読んだあとに消えていれば、飛ばす
718            if let Some(entry) = self.metadata(&hash, at)? {
719                entries.push(entry);
720            }
721        }
722        Ok(Some(entries))
723    }
724
725    fn search_namespaces(
726        &self,
727        filter: &NamespaceFilter,
728        page: PageRequest,
729        after: Option<&[u8]>,
730        at: Option<u64>,
731    ) -> Result<Option<Vec<(String, NamespaceInfo)>>, StateError> {
732        let wanted = match at {
733            None => Searches::NAMESPACES,
734            Some(_) => Searches::NAMESPACES.union(Searches::PAST),
735        };
736        if !self.db.searches().contains(wanted) {
737            return Ok(None);
738        }
739        let (view, height) = self.view(at)?;
740        let root_row =
741            |root: u64| self.row(&view, &row_key(SubCache::Namespace, &root.to_le_bytes()));
742        // 決まっている項目から、なめる並べ方と頭を選ぶ。ルートだけ決まっていれば、その持ち主から
743        let prefix = match (filter.owner, filter.level0, filter.alias_type) {
744            (Some(owner), level0, _) => {
745                let mut prefix = [&[NAMESPACE_BY_OWNER][..], &owner.0].concat();
746                if let Some(root) = level0 {
747                    prefix.extend_from_slice(&root.to_be_bytes());
748                }
749                prefix
750            }
751            (None, Some(root), _) => {
752                let Some(row) = root_row(root)?.and_then(|row| NamespaceRow::from_row(root, &row))
753                else {
754                    return Ok(Some(Vec::new()));
755                };
756                [&[NAMESPACE_BY_OWNER][..], &row.owner, &root.to_be_bytes()].concat()
757            }
758            (None, None, Some(1)) => vec![NAMESPACE_BY_MOSAIC],
759            (None, None, Some(2)) => vec![NAMESPACE_BY_ADDRESS],
760            (None, None, _) => vec![NAMESPACE_BY_OWNER],
761        };
762        if after.is_some_and(|after| after.first() != prefix.first()) {
763            return Err(StateError::Invalid(
764                "offset is not a position of this search".to_owned(),
765            ));
766        }
767        let mut skip = (page.number - 1) * page.size;
768        let mut found = Vec::new();
769        let mut failed = None;
770        // 同じルートの行は続けて出るので、最後に読んだものを覚えておく
771        let mut last_root: Option<(u64, Option<Vec<u8>>)> = None;
772        let mut visit = |key: &[u8]| {
773            let Some((root, id)) = namespace_ids(key) else {
774                return true;
775            };
776            if filter.level0.is_some_and(|level0| level0 != root)
777                || filter
778                    .registration_type
779                    .is_some_and(|kind| kind != u8::from(id != root))
780            {
781                return true;
782            }
783            if last_root.as_ref().is_none_or(|(last, _)| *last != root) {
784                match root_row(root) {
785                    Ok(row) => last_root = Some((root, row)),
786                    Err(error) => {
787                        failed = Some(error);
788                        return false;
789                    }
790                }
791            }
792            let Some((_, Some(row))) = &last_root else {
793                return true;
794            };
795            // 昔の高さでは、候補がその高さの行から出るかを確かめる。今の検索表は今の行と合っている
796            if matches!(view, View::At(_)) && !row_yields(key, row) {
797                return true;
798            }
799            let info = RootNamespaceState::from_state_bytes(&state_bytes(&root.to_le_bytes(), row))
800                .ok()
801                .and_then(|state| state.info(id, height).ok().flatten());
802            let Some(info) = info else {
803                return true;
804            };
805            if filter
806                .alias_type
807                .is_some_and(|kind| kind != info.namespace.alias.alias_type)
808            {
809                return true;
810            }
811            if skip > 0 {
812                skip -= 1;
813                return true;
814            }
815            found.push((hex(key), info));
816            found.len() < page.size
817        };
818        match &view {
819            View::Now(_) => {
820                self.db
821                    .for_each_search_key(&prefix, after, page.descending, &mut visit)
822            }
823            View::At(_) => {
824                self.db
825                    .for_each_search_key_with_past(&prefix, after, page.descending, &mut visit)
826            }
827        }
828        .map_err(|error| error.to_string())?;
829        if let Some(error) = failed {
830            return Err(error);
831        }
832        Ok(Some(found))
833    }
834
835    fn namespace_names(&self, ids: &[u64]) -> Result<Option<Vec<NamespaceNameJson>>, String> {
836        if !self.db.searches().contains(Searches::NAMESPACES) {
837            return Ok(None);
838        }
839        // catapult の REST と同じく、頼まれた ID の分を並べ、その親の分を次に並べる
840        let mut out: Vec<NamespaceNameJson> = Vec::new();
841        let mut next: Vec<u64> = ids.to_vec();
842        while !next.is_empty() {
843            let mut parents = Vec::new();
844            for id in next {
845                let text = format!("{id:016X}");
846                if out.iter().any(|name| name.id == text) {
847                    continue;
848                }
849                let Some((parent, name)) = self
850                    .db
851                    .namespace_name(id)
852                    .map_err(|error| error.to_string())?
853                else {
854                    continue;
855                };
856                out.push(NamespaceNameJson {
857                    id: text,
858                    name: String::from_utf8_lossy(&name).into_owned(),
859                    parent_id: (parent != 0).then(|| format!("{parent:016X}")),
860                });
861                if parent != 0 {
862                    parents.push(parent);
863                }
864            }
865            next = parents;
866        }
867        Ok(Some(out))
868    }
869
870    fn alias_names(&self, target: AliasTarget) -> Result<Option<Vec<String>>, String> {
871        if !self.db.searches().contains(Searches::NAMESPACES) {
872            return Ok(None);
873        }
874        let prefix = match target {
875            AliasTarget::Address(address) => [&[NAMESPACE_BY_ADDRESS][..], &address.0].concat(),
876            AliasTarget::Mosaic(id) => [&[NAMESPACE_BY_MOSAIC][..], &id.to_be_bytes()].concat(),
877        };
878        let mut ids = Vec::new();
879        self.db
880            .for_each_search_key(&prefix, None, false, &mut |key| {
881                ids.extend(namespace_ids(key));
882                true
883            })
884            .map_err(|error| error.to_string())?;
885        let height = self.executed()?;
886        let mut names = Vec::new();
887        for (root, id) in ids {
888            // catapult の REST と同じく、今有効な(期限の高さが今より後の)ものだけ
889            let row = self
890                .db
891                .state_row(&row_key(SubCache::Namespace, &root.to_le_bytes()))
892                .map_err(|error| error.to_string())?
893                .and_then(|row| NamespaceRow::from_row(root, &row));
894            if row.is_none_or(|row| row.end <= height) {
895                continue;
896            }
897            // ルートまでたどってつなぐ。どこかの名前を知らなければ出さない
898            let mut parts = Vec::new();
899            let mut at = id;
900            let full = loop {
901                let Some((parent, name)) = self
902                    .db
903                    .namespace_name(at)
904                    .map_err(|error| error.to_string())?
905                else {
906                    break None;
907                };
908                parts.push(String::from_utf8_lossy(&name).into_owned());
909                if parent == 0 {
910                    parts.reverse();
911                    break Some(parts.join("."));
912                }
913                at = parent;
914            };
915            if let Some(full) = full
916                && !names.contains(&full)
917            {
918                names.push(full);
919            }
920        }
921        Ok(Some(names))
922    }
923
924    fn state_path(
925        &self,
926        cache: SubCache,
927        key: &Hash256,
928        at: Option<u64>,
929    ) -> Result<MerkleStateInfo, StateError> {
930        let (view, _) = self.view(at)?;
931        let nodes = walk(key, |position| {
932            let key = node_key(cache.index() as u8, position);
933            match &view {
934                View::Now(_) => self.db.trie_node(&key),
935                View::At(past) => past.trie_node(&key),
936            }
937            .map_err(|error| error.to_string())?
938            .map(|bytes| decode_node(&bytes))
939            .transpose()
940        })?;
941        let raw: Vec<u8> = nodes.iter().flat_map(TreeNode::encode).collect();
942        Ok(MerkleStateInfo { raw: hex(&raw) })
943    }
944
945    fn block(&self, height: u64) -> Result<Option<BlockInfo>, String> {
946        let Some(block) = self.read_block(height)? else {
947            return Ok(None);
948        };
949        let mut roots = Vec::with_capacity(SubCache::ALL.len());
950        for cache in SubCache::ALL {
951            let Some(root) = self.root_at(cache, height)? else {
952                return Ok(None);
953            };
954            roots.push(root.to_string());
955        }
956        let (mut total_fee, mut transactions, mut total_transactions) = (0u64, 0u32, 0u32);
957        for transaction in block.transactions() {
958            total_fee += u64::from(block.fee_multiplier) * transaction.len() as u64;
959            transactions += 1;
960            total_transactions += 1;
961            let transaction_type = u16::from_le_bytes([transaction[110], transaction[111]]);
962            if AGGREGATE_TYPES.contains(&transaction_type) {
963                let embedded =
964                    heika_transaction::scan(transaction).map_or(0, |scanned| scanned.len());
965                total_transactions += embedded as u32;
966            }
967        }
968        let statements_count = match self
969            .db
970            .statement(height)
971            .map_err(|error| error.to_string())?
972        {
973            Some(bytes) => {
974                let statement =
975                    BlockStatement::from_bytes(&bytes).map_err(|error| error.to_string())?;
976                (statement.transaction_statements.len()
977                    + statement.address_resolution_statements.len()
978                    + statement.mosaic_resolution_statements.len()) as u32
979            }
980            None => 0,
981        };
982        Ok(Some(BlockInfo {
983            meta: BlockMeta {
984                hash: block.hash().to_string(),
985                generation_hash: block.generation_hash().to_string(),
986                total_fee: total_fee.to_string(),
987                state_hash_sub_cache_merkle_roots: roots,
988                total_transactions_count: total_transactions,
989                transactions_count: transactions,
990                statements_count,
991            },
992            block: BlockHeader::from(&block),
993        }))
994    }
995
996    fn transaction_status(&self, hash: &Hash256) -> Result<Option<TransactionStatus>, String> {
997        let status = |group: &str, deadline: u64, height: u64| TransactionStatus {
998            group: group.to_owned(),
999            code: Some("Success".to_owned()),
1000            hash: hash.to_string(),
1001            deadline: Some(deadline.to_string()),
1002            height: Some(height.to_string()),
1003        };
1004        if let Some(deadline) = self.mempool.lock().deadline(hash) {
1005            return Ok(Some(status("unconfirmed", deadline, 0)));
1006        }
1007        // ブロックを作ってみて、残高など状態に依ることで弾いたもの。catapult は理由ごとのコードを返すが、heika の
1008        // 実行の誤りは理由のコードを持たないので、1つのコードで答える(理由はノードのログに出る)
1009        if let Some(deadline) = self.mempool.lock().rejected(hash) {
1010            return Ok(Some(TransactionStatus {
1011                group: "failed".to_owned(),
1012                code: Some(REJECTED_CODE.to_owned()),
1013                hash: hash.to_string(),
1014                deadline: Some(deadline.to_string()),
1015                height: None,
1016            }));
1017        }
1018        if let Some(deadline) = self.partials.lock().deadline(hash) {
1019            return Ok(Some(status("partial", deadline, 0)));
1020        }
1021        Ok(self
1022            .recent_transaction(hash)?
1023            .map(|(transaction, height, _, _)| status("confirmed", transaction.deadline, height)))
1024    }
1025
1026    fn search_transactions(
1027        &self,
1028        filter: &TransactionFilter,
1029        page: PageRequest,
1030        after: Option<(u64, u32, u16)>,
1031    ) -> Result<Option<Vec<TransactionInfo>>, String> {
1032        // アドレス(署名者と宛先も、関わったアドレスに入る)があれば、アドレスの表から候補を取る。なければブロックを順に読む。
1033        // アグリゲートの中の署名者と宛先も、アグリゲートの関わったアドレスに入るので、中のものも表から取れる
1034        let indexed = filter
1035            .address
1036            .or(filter
1037                .signer
1038                .map(|key| Address::from_public_key(&key, self.network)))
1039            .map(|address| address.0)
1040            .or(filter.recipient);
1041        if indexed.is_some() && !self.db.searches().contains(Searches::TRANSACTIONS) {
1042            return Ok(None);
1043        }
1044        // catapult と同じく、中のものは `embedded=true` で、関わったアドレスで絞らないときだけ(catapult の中の
1045        // トランザクションの文書には `meta.addresses` がないので、`address` には合わない)
1046        let embedded = filter.embedded && filter.address.is_none();
1047        let heights = filter.from_height..=filter.to_height;
1048        let mut skip = (page.number - 1) * page.size;
1049        let mut out = Vec::new();
1050        let mut failed = None;
1051        // 候補の1件(アグリゲートなら中のものも)を確かめて、合えば足す。ページが埋まったら `false`
1052        let mut take = |block: &Block, height: u64, index: u32| -> bool {
1053            let Some(transaction) = block
1054                .transactions()
1055                .nth(index as usize)
1056                .and_then(|bytes| Transaction::from_bytes(bytes).ok())
1057            else {
1058                return true;
1059            };
1060            let inners = match &transaction.body {
1061                Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate)
1062                    if embedded =>
1063                {
1064                    aggregate.transactions()
1065                }
1066                _ => &[],
1067            };
1068            // 0 が外側で、中のものは 1 から。外側が先
1069            let mut order: Vec<u16> = (0..=inners.len() as u16).collect();
1070            if page.descending {
1071                order.reverse();
1072            }
1073            for inner in order {
1074                let position = (height, index, inner);
1075                // 続きは、`after` より後のものだけ
1076                if after.is_some_and(|after| {
1077                    if page.descending {
1078                        position >= after
1079                    } else {
1080                        position <= after
1081                    }
1082                }) {
1083                    continue;
1084                }
1085                let found = match inner.checked_sub(1) {
1086                    None => transaction_matches(
1087                        filter,
1088                        &transaction.signer_public_key,
1089                        &transaction.body,
1090                    ),
1091                    Some(at) => {
1092                        let item = &inners[at as usize];
1093                        transaction_matches(filter, &item.signer_public_key, &item.body)
1094                    }
1095                };
1096                if !found {
1097                    continue;
1098                }
1099                if skip > 0 {
1100                    skip -= 1;
1101                    continue;
1102                }
1103                let id = Some(transaction_position(height, index, inner));
1104                out.push(match inner.checked_sub(1) {
1105                    None => self.confirmed_info(&transaction, block, height, index, id),
1106                    Some(at) => TransactionInfo {
1107                        id,
1108                        meta: embedded_meta(
1109                            &transaction.hash(&self.seed).to_string(),
1110                            block,
1111                            height,
1112                            index,
1113                            u32::from(at),
1114                        ),
1115                        transaction: TransactionJson::from(&inners[at as usize]),
1116                    },
1117                });
1118                if out.len() >= page.size {
1119                    return false;
1120                }
1121            }
1122            true
1123        };
1124        match indexed {
1125            Some(address) => {
1126                let mut cached: Option<(u64, Block)> = None;
1127                self.db
1128                    .for_each_address_transaction(
1129                        &address,
1130                        heights,
1131                        after.map(|(height, index, _)| (height, index)),
1132                        page.descending,
1133                        &mut |height, index| {
1134                            if cached.as_ref().is_none_or(|(at, _)| *at != height) {
1135                                // 刈り込んだブロックの分は、索引に残っていても返せない
1136                                match self.read_block(height) {
1137                                    Ok(Some(block)) => cached = Some((height, block)),
1138                                    Ok(None) => return true,
1139                                    Err(error) => {
1140                                        failed = Some(error);
1141                                        return false;
1142                                    }
1143                                }
1144                            }
1145                            let Some((_, block)) = &cached else {
1146                                return true;
1147                            };
1148                            take(block, height, index)
1149                        },
1150                    )
1151                    .map_err(|error| error.to_string())?;
1152            }
1153            None => {
1154                self.db
1155                    .for_each_block(
1156                        heights,
1157                        after.map(|(height, _, _)| height),
1158                        page.descending,
1159                        &mut |height, bytes| {
1160                            let Ok(block) = Block::from_bytes(bytes) else {
1161                                return true;
1162                            };
1163                            let count = block.transactions().count() as u32;
1164                            let mut indexes: Vec<u32> = (0..count).collect();
1165                            if page.descending {
1166                                indexes.reverse();
1167                            }
1168                            for index in indexes {
1169                                // 続きのブロックでは、`after` より前のものを読まない
1170                                if let Some((at, after_index, _)) = after
1171                                    && at == height
1172                                    && (if page.descending {
1173                                        index > after_index
1174                                    } else {
1175                                        index < after_index
1176                                    })
1177                                {
1178                                    continue;
1179                                }
1180                                if !take(&block, height, index) {
1181                                    return false;
1182                                }
1183                            }
1184                            true
1185                        },
1186                    )
1187                    .map_err(|error| error.to_string())?;
1188            }
1189        }
1190        if let Some(error) = failed {
1191            return Err(error);
1192        }
1193        Ok(Some(out))
1194    }
1195
1196    fn confirmed_transaction(&self, hash: &Hash256) -> Result<Option<TransactionInfo>, String> {
1197        Ok(self
1198            .recent_transaction(hash)?
1199            .map(|(transaction, height, index, block)| {
1200                self.confirmed_info(&transaction, &block, height, index, None)
1201            }))
1202    }
1203
1204    fn transaction_merkle(
1205        &self,
1206        height: u64,
1207        hash: &Hash256,
1208    ) -> Result<Option<MerkleProofInfo>, String> {
1209        let Some(block) = self.read_block(height)? else {
1210            return Ok(None);
1211        };
1212        let Some(index) = block.transactions().position(|bytes| {
1213            Transaction::from_bytes(bytes)
1214                .is_ok_and(|transaction| transaction.hash(&self.seed) == *hash)
1215        }) else {
1216            return Ok(None);
1217        };
1218        let leaves = block
1219            .merkle_leaves(&self.seed)
1220            .map_err(|error| error.to_string())?;
1221        let path = merkle::path(&leaves, index).ok_or("Merkle の経路を作れません")?;
1222        Ok(Some(MerkleProofInfo {
1223            merkle_path: path
1224                .into_iter()
1225                .map(|node| MerklePathItem {
1226                    position: match node.position {
1227                        Position::Left => "left",
1228                        Position::Right => "right",
1229                    }
1230                    .to_owned(),
1231                    hash: node.hash.to_string(),
1232                })
1233                .collect(),
1234        }))
1235    }
1236
1237    fn transaction_fees(&self) -> Result<TransactionFeesJson, String> {
1238        let tip = self.db.blocks_tip().map_err(|error| error.to_string())?;
1239        let mut multipliers = Vec::new();
1240        for height in tip.saturating_sub(FEE_STATS_BLOCKS - 1).max(1)..=tip {
1241            if let Some(block) = self.read_block(height)? {
1242                multipliers.push(block.fee_multiplier);
1243            }
1244        }
1245        let min_fee_multiplier = self.mempool.lock().min_fee_multiplier();
1246        Ok(TransactionFeesJson::new(multipliers, min_fee_multiplier))
1247    }
1248
1249    fn partial_transaction(&self, hash: &Hash256) -> Result<Option<TransactionInfo>, String> {
1250        Ok(self.partial_info(hash))
1251    }
1252
1253    fn partial_transactions(&self, filter: &PartialFilter) -> Result<Vec<TransactionInfo>, String> {
1254        let hashes = self.partials.lock().hashes();
1255        Ok(hashes
1256            .iter()
1257            .filter_map(|hash| {
1258                let bytes = self.partials.lock().stitched(hash)?;
1259                let transaction = Transaction::from_bytes(&bytes).ok()?;
1260                let signer_ok = filter
1261                    .signer
1262                    .is_none_or(|signer| transaction.signer_public_key == signer);
1263                let address_ok = filter
1264                    .address
1265                    .is_none_or(|address| self.involves(&transaction, &address));
1266                (signer_ok && address_ok)
1267                    .then(|| self.partial_info(hash))
1268                    .flatten()
1269            })
1270            .collect())
1271    }
1272
1273    fn finalization_proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, String> {
1274        self.db.proof(epoch).map_err(|error| error.to_string())
1275    }
1276
1277    fn unconfirmed_transaction(&self, hash: &Hash256) -> Result<Option<TransactionInfo>, String> {
1278        let bytes = self.mempool.lock().get(hash).map(<[u8]>::to_vec);
1279        Ok(bytes
1280            .and_then(|bytes| Transaction::from_bytes(&bytes).ok())
1281            .map(|transaction| self.unconfirmed_info(hash, &transaction)))
1282    }
1283
1284    fn unconfirmed_transactions(
1285        &self,
1286        filter: &PartialFilter,
1287        embedded: bool,
1288    ) -> Result<Vec<TransactionInfo>, String> {
1289        // 読むあいだ置き場を止めないように、写してから JSON にする
1290        let listed: Vec<(Hash256, Vec<u8>)> = self
1291            .mempool
1292            .lock()
1293            .transactions()
1294            .map(|(hash, bytes)| (*hash, bytes.to_vec()))
1295            .collect();
1296        // catapult と同じく、中のものは関わったアドレスで絞らないときだけ
1297        let embedded = embedded && filter.address.is_none();
1298        let mut out = Vec::new();
1299        for (hash, bytes) in listed {
1300            let Ok(transaction) = Transaction::from_bytes(&bytes) else {
1301                continue;
1302            };
1303            let signer_ok = filter
1304                .signer
1305                .is_none_or(|signer| transaction.signer_public_key == signer);
1306            let address_ok = filter
1307                .address
1308                .is_none_or(|address| self.involves(&transaction, &address));
1309            if !(signer_ok && address_ok) {
1310                continue;
1311            }
1312            out.push(self.unconfirmed_info(&hash, &transaction));
1313            if let (true, Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate)) =
1314                (embedded, &transaction.body)
1315            {
1316                for (index, inner) in aggregate.transactions().iter().enumerate() {
1317                    out.push(TransactionInfo {
1318                        id: None,
1319                        meta: TransactionMeta {
1320                            height: Some("0".to_owned()),
1321                            hash: None,
1322                            merkle_component_hash: None,
1323                            index: Some(index as u32),
1324                            aggregate_hash: Some(hash.to_string()),
1325                            aggregate_id: None,
1326                            timestamp: None,
1327                            fee_multiplier: None,
1328                        },
1329                        transaction: TransactionJson::from(inner),
1330                    });
1331                }
1332            }
1333        }
1334        Ok(out)
1335    }
1336
1337    fn network(&self) -> NetworkIdentifier {
1338        self.network
1339    }
1340}
1341
1342#[cfg(test)]
1343mod tests {
1344    use super::*;
1345
1346    #[test]
1347    fn transaction_filters_follow_catapult_conditions() {
1348        let network = NetworkIdentifier::MAINNET;
1349        let mosaics = [(0xAAu64, 10u64), (0xBB, 3)]
1350            .into_iter()
1351            .map(|(id, amount)| (heika_transaction::UnresolvedMosaicId(id), amount))
1352            .collect();
1353        let transfer = Transaction::new(
1354            PublicKey([0x11; 32]),
1355            network,
1356            0,
1357            0,
1358            Body::Transfer(
1359                heika_transaction::Transfer::new(
1360                    heika_transaction::UnresolvedAddress([0x55; 24]),
1361                    mosaics,
1362                    Vec::new(),
1363                )
1364                .unwrap(),
1365            ),
1366        );
1367        let base = TransactionFilter {
1368            address: None,
1369            signer: None,
1370            recipient: None,
1371            types: Vec::new(),
1372            mosaic: None,
1373            from_amount: None,
1374            to_amount: None,
1375            from_height: 0,
1376            to_height: u64::MAX,
1377            embedded: false,
1378        };
1379        let matches = |filter: TransactionFilter| {
1380            transaction_matches(&filter, &transfer.signer_public_key, &transfer.body)
1381        };
1382        assert!(matches(base.clone()));
1383        assert!(matches(TransactionFilter {
1384            signer: Some(PublicKey([0x11; 32])),
1385            recipient: Some([0x55; 24]),
1386            types: vec![0x4141, 0x4154],
1387            ..base.clone()
1388        }));
1389        assert!(!matches(TransactionFilter {
1390            signer: Some(PublicKey([0x12; 32])),
1391            ..base.clone()
1392        }));
1393        assert!(!matches(TransactionFilter {
1394            recipient: Some([0x56; 24]),
1395            ..base.clone()
1396        }));
1397        assert!(!matches(TransactionFilter {
1398            types: vec![0x4141],
1399            ..base.clone()
1400        }));
1401        // 額は、モザイクと別に、どれかが範囲に入ればよい(catapult の MongoDB の条件と同じ)
1402        let by_mosaic = |mosaic, from_amount, to_amount| {
1403            matches(TransactionFilter {
1404                mosaic: Some(mosaic),
1405                from_amount,
1406                to_amount,
1407                ..base.clone()
1408            })
1409        };
1410        assert!(by_mosaic(0xAA, None, None));
1411        assert!(!by_mosaic(0xCC, None, None));
1412        assert!(by_mosaic(0xAA, Some(4), Some(9)));
1413        assert!(!by_mosaic(0xAA, Some(11), None));
1414    }
1415
1416    fn filter() -> MetadataFilter {
1417        MetadataFilter::default()
1418    }
1419
1420    #[test]
1421    fn picks_the_search_order_from_the_filter() {
1422        let (a, b) = (Address([0xAA; 24]), Address([0xBB; 24]));
1423        let head = |prefix: &[u8]| prefix.to_vec();
1424        // 送り主があれば送り主から。決まっている項目は、途中が抜けたらそこまで
1425        let source = MetadataFilter {
1426            source: Some(a),
1427            target: Some(b),
1428            ..filter()
1429        };
1430        assert_eq!(
1431            metadata_prefixes(&source),
1432            vec![[&[METADATA_BY_SOURCE][..], &a.0].concat()]
1433        );
1434        let source = MetadataFilter {
1435            metadata_type: Some(0),
1436            ..source
1437        };
1438        assert_eq!(
1439            metadata_prefixes(&source),
1440            vec![[&[METADATA_BY_SOURCE][..], &a.0, &[0], &b.0].concat()]
1441        );
1442        // 宛先から
1443        let target = MetadataFilter {
1444            target: Some(b),
1445            scoped_key: Some(7),
1446            ..filter()
1447        };
1448        assert_eq!(
1449            metadata_prefixes(&target),
1450            vec![[&[METADATA_BY_TARGET][..], &b.0].concat()]
1451        );
1452        // 対象からは、種類がなければモザイクとネームスペースの両方
1453        let target_id = MetadataFilter {
1454            target_id: Some(0x55),
1455            ..filter()
1456        };
1457        let id = 0x55u64.to_be_bytes();
1458        assert_eq!(
1459            metadata_prefixes(&target_id),
1460            vec![
1461                [&[METADATA_BY_TARGET_ID, 1][..], &id].concat(),
1462                [&[METADATA_BY_TARGET_ID, 2][..], &id].concat()
1463            ]
1464        );
1465        // アカウントのメタデータと、何も決まっていないときは、宛先からを全部
1466        for filter in [
1467            MetadataFilter {
1468                metadata_type: Some(0),
1469                ..filter()
1470            },
1471            MetadataFilter {
1472                target_id: Some(0),
1473                ..filter()
1474            },
1475            filter(),
1476        ] {
1477            assert_eq!(
1478                metadata_prefixes(&filter),
1479                vec![head(&[METADATA_BY_TARGET])]
1480            );
1481        }
1482        let fields = MetadataFields {
1483            source: a.0,
1484            target: b.0,
1485            scoped_key: 7,
1486            target_id: 0,
1487            metadata_type: 0,
1488        };
1489        assert!(matches(&target, &fields));
1490        assert!(!matches(&target_id, &fields));
1491    }
1492}